@odoo/o-spreadsheet 19.1.4 → 19.1.19

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,817 +0,0 @@
1
- !function(e){"use strict";class t{scope;code="";constructor(e=new n){this.scope=e}append(...e){this.code+=e.map(e=>e.toString()).join("\n")+"\n"}return(e){return new r(this.scope,this.code,e)}toString(){return o(this.code)}}class r{scope;returnExpression;code;constructor(e,t,r){this.scope=e,this.returnExpression=r,this.code=o(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;const e=this.scope.nextVariableName(),r=new t(this.scope);return r.append(this.code),r.append(`const ${e} = ${this.returnExpression};`),r.return(e)}}class n{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function o(e){let t="",r=0;const n=e.split("\n").map(e=>e.trim()).filter(e=>""!==e);for(const e of n)e.startsWith("}")&&r--,t+="\t".repeat(r)+e+"\n",e.endsWith("{")&&r++;return t.trim()}const s=/(.*?)\((.*?)\)(.*)/,i=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META","RANGE<META>"];function a(e,t="",r){return function(e,t,r){const n=e.match(s),o=n[1].trim();if(!o)throw new Error(`Function argument definition is missing a name: '${e}'.`);const a=[];let l,c=!1,u=!1;for(const e of n[2].split(",")){const t=e.trim().toUpperCase(),r=i.find(e=>t===e);r?a.push(r):"RANGE<ANY>"===t?a.push("RANGE"):"OPTIONAL"===t?c=!0:"REPEATING"===t?u=!0:t.startsWith("DEFAULT=")&&(l=e.trim().slice(8))}const h={name:o,description:t,type:a};(a.includes("ANY")||a.includes("RANGE"))&&(h.acceptErrors=!0);c&&(h.optional=!0);u&&(h.repeating=!0);void 0!==l&&(h.default=!0,h.defaultValue=l);a.some(e=>e.startsWith("RANGE"))&&(h.acceptMatrix=!0);a.every(e=>e.startsWith("RANGE"))&&(h.acceptMatrixOnly=!0);r&&r.length>0&&(h.proposalValues=r);return h}(e,t,r)}const l={};function c(e,t){const r=e.name,n=l[r]?.[t];return n||(l[r]||(l[r]={}),l[r][t]||(l[r][t]=function(e,t){const r={},n=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,o=e.nbrArgRepeating*n,s=t-e.minArgRequired-o;let i=0,a=0;for(let t=0;t<e.args.length;t++){const o=e.args[t];if(!o.optional&&!o.default||o.repeating){if(o.repeating){const s=o.optional?0:1;for(let o=0;o<n+s;o++)for(let n=0;n<e.nbrArgRepeating;n++)r[i]={index:t+n,repeatingGroupIndex:o},i++;t+=e.nbrArgRepeating-1;continue}r[i]={index:t},i++}else a<s&&(r[i]={index:t},i++),a++}return e=>r[e]}(e,t)),l[r][t])}const u=["META","RANGE<META>"];let h=class{content={};add(e,t){if(e in this.content)throw new Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(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)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}};const d=e=>e,f=()=>!1;let g=d,m=f;function p(e,...t){if(1!==t.length||"object"!=typeof t[0]||t[0]instanceof String)t.length>0&&(e=e.replace(/\%s/g,()=>t.shift()));else{const r=t[0];e=e.replace(/\%\(([^\)]+)\)s/g,(e,t)=>r[t])}return e}function b(){g===d&&m===f&&(m=()=>!0)}const v=function(e,...t){return m()?p(g(e),...t):new y(e,t)};class y extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return m()?p(g(e),...this.values):p(e,...this.values)}toString(){return this.valueOf()}}const E={NotAvailable:"#N/A",InvalidReference:"#REF",BadExpression:"#BAD_EXPR",CircularDependency:"#CYCLE",UnknownFunction:"#NAME?",DivisionByZero:"#DIV/0!",InvalidNumber:"#NUM!",SpilledBlocked:"#SPILL!",GenericError:"#ERROR",NullError:"#NULL!"},w=new Set(Object.values(E));class S{message;value;constructor(e=v("Error"),t=E.GenericError){this.message=e,this.value=t,this.message=e.toString()}}class C extends S{constructor(e=v("Invalid expression")){super(e,E.BadExpression)}}class T extends S{constructor(e=v("Circular reference")){super(e,E.CircularDependency)}}class I extends S{constructor(e=v("Invalid reference")){super(e,E.InvalidReference)}}class x extends S{constructor(e=v("Data not available")){super(e,E.NotAvailable)}}class R extends S{constructor(e=v("Unknown function")){super(e,E.UnknownFunction)}}class A extends S{constructor(e=v("Spill range is not empty")){super(e,E.SpilledBlocked)}}class O extends S{constructor(e=v("Division by zero")){super(e,E.DivisionByZero)}}class _ extends S{constructor(e=v("Number too large")){super(e,E.InvalidNumber)}}function D(e){return Array.isArray(e)&&Array.isArray(e[0])}var F;e.DIRECTION=void 0,(F=e.DIRECTION||(e.DIRECTION={})).UP="up",F.DOWN="down",F.LEFT="left",F.RIGHT="right";const N="#017E84",M="#3266ca",V="#FFFFFF",L=N,P="#111827",k="#E7E9ED",U="#374151C2",H=N,B=20,z=16,$=["#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"],G=23,W="bottom",q=10,Z="'Roboto', arial",Y="START_REVISION",j="??",X=/'|\*|\?|\/|\\|\[|\]/,K="|";const Q="\n",J={hasFilters:!1,totalRow:!1,firstColumn:!0,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,styleId:"TableStyleMedium5",automaticAutofill:!1},ee=new RegExp(X,"g");function te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function re(e){switch(typeof e){case"object":{if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&null!==e&&(e?.constructor===Object||void 0===e?.constructor)}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");const t=Array.isArray(e)?new Array(e.length):{};if(Array.isArray(e))for(let r=0,n=e.length;r<n;r++)r in e&&(t[r]=re(e[r]));else for(const r in e)t[r]=re(e[r]);return t}case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function ne(e){return oe(e,"'")}function oe(e,t='"'){return e.startsWith(t)&&(e=e.slice(1)),e.endsWith(t)&&(e=e.slice(0,-1)),e}function se(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function ie(e,t=" "){return e.replace(ee,t)}function ae(e,t,r){return e<t?t:e>r?r:e}function le(e,t,r=1){if(t<=e&&r>0)return[];if(0===r)throw new Error("range() step must not be zero");const n=Math.ceil(Math.abs((t-e)/r)),o=Array(n);for(let t=0;t<n;t++)o[t]=e+t*r;return o}function ce(e){return e.reduce((e,t,r,n)=>{if(1===Math.abs(t-n[r-1])){e[e.length-1].push(t)}else e.push([t]);return e},[])}function*ue(e,t){t.next();for(const r of e){const e=t.next();yield{...r,next:e.done?void 0:e.value}}}function he(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}const de=/^\[(.+)\]\((.+)\)$/,fe=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function ge(e){return de.test(e)}function me(e){return fe.test(e)}function pe(e,t){return`[${e}](${t})`}function be(e){const t=e.match(de)||[],r=t[1],n=t[2];if(!r||!n)throw new Error(`Could not parse markdown link ${e}.`);return{label:r,url:n}}const ve="o-spreadsheet://";function ye(e){return e.startsWith(ve)}function Ee(e){return`${ve}${e}`}function we(e){if(e.startsWith(ve))return e.slice(16);throw new Error(`${e} is not a valid sheet link`)}function Se(e){return void 0!==e}function Ce(e){return void 0===e||Object.values(e).every(e=>"object"==typeof e?Ce(e):!e)}function Te(e,t,r){let n,o=!1;const s=function(){const s=this,i=Array.from(arguments);if(!o&&r)return o=!0,e.apply(s,i);clearTimeout(n),n=setTimeout(function(){n=void 0,o=!1,e.apply(s,i)},t)};return s.isDebouncePending=()=>void 0!==n,s.stopDebounce=()=>{clearTimeout(n)},s}function Ie(e){let t="";for(let r=0,n=e.length;r<n;r++)t+=e[r];return t}function xe(e){let t,r=!1;const n=()=>(r||(t=e instanceof Function?e():e,r=!0),t);return n.map=e=>xe(()=>e(n())),n}function Re(e,t){return"after"===e?t+1:t}function Ae(...e){if(e.length<=1)return!0;for(let t=1;t<e.length;t++)if(!Oe(e[0],e[t]))return!1;return!0}function Oe(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return!1;for(const r in t)if(!(r in e)&&void 0!==t[r])return!1;for(const r in e){if(typeof e[r]!=typeof t[r])return!1;if("object"==typeof e[r]){if(!Oe(e[r],t[r]))return!1}else if(e[r]!==t[r])return!1}return!0}function _e(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ae(e[r],t[r]))return!1;return!0}function De(e,t){if(e.length<t.length)return!1;const r=new Set(e);return t.every(e=>r.has(e))}function Fe(e){if(!e)return e;const t={...e};return Object.keys(t).forEach(e=>!t[e]&&delete t[e]),t}const Ne=["\t","\f","\v",String.fromCharCode(parseInt("00a0",16)),String.fromCharCode(parseInt("1680",16)),String.fromCharCode(parseInt("2000",16)),String.fromCharCode(parseInt("200a",16)),String.fromCharCode(parseInt("2028",16)),String.fromCharCode(parseInt("2029",16)),String.fromCharCode(parseInt("202f",16)),String.fromCharCode(parseInt("205f",16)),String.fromCharCode(parseInt("3000",16)),String.fromCharCode(parseInt("feff",16))],Me=new RegExp(Ne.join("|"),"g"),Ve=/(\r\n|\r)/g,Le=Ne.concat([" "]);function Pe(e){return e?e.replace(Ve,Q):""}function ke(e){const t=Array.from(e).sort((e,t)=>e-t);for(let e=1;e<t.length;e++)if(t[e]-t[e-1]!==1)return!1;return!0}function Ue(e){const t=new Map,r=e.name?e.name+" (memoized)":"memoized";return{[r]:(...r)=>(t.has(r[0])||t.set(r[0],e(...r)),t.get(r[0]))}[r]}function He(e,t){const r=new Set(t),n=[];for(let t=0;t<e.length;t++)r.has(t)||n.push(e[t]);return n}function Be(e,t,r){return e.slice(0,r).concat(t).concat(e.slice(r))}function ze(e,t,r){const n=[...e];return n[r]=t,n}function $e(e){return e.split("\n").map(e=>e.replace(/\s+/g," ").trim()).join("\n")}function Ge(e,t,r){return t>r?Ge(e,r,t):e>=t&&e<=r}function We(e){let t=e.length;if(t<1e5)return Math.max(...e);let r=-1/0;for(;t--;)r=e[t]>r?e[t]:r;return r}function qe(e){let t=e.length;if(t<1e5)return Math.min(...e);let r=1/0;for(;t--;)r=e[t]<r?e[t]:r;return r}class Ze{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){const e=this.current,t=this.text[++this.currentIndex];return this.current=t,e}advanceBy(e){this.currentIndex+=e,this.current=this.text[this.currentIndex]}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){if(this.current!==e[0])return!1;for(let t=1;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}}function Ye(e,t=e=>e){const r=new Set;return e.filter(e=>{const n=t(e);return!r.has(n)&&(r.add(n),!0)})}function je(e){const t={};for(const r in e)for(const n in e[r])t[n]||(t[n]={}),t[n][r]=e[r][n];return t}function Xe(e,t,r={}){const n=r.compute??((e,t)=>`${e} (${t})`),o=r.computeFirstOne??!1;let s=r.start??1,i=o?n(e,s):e;for(;t.includes(i);)i=n(e,s++);return i}function Ke(e){return e.startsWith("=")||e.startsWith("+")}class Qe{jsDate;constructor(e,t,r,n=0,o=0,s=0){this.jsDate=new Date(Date.UTC(e,t,r,n,o,s,0))}static fromTimestamp(e){const t=new Date(e);return new Qe(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new Qe(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getQuarter(){return Math.floor(this.getMonth()/3)+1}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}getIsoWeek(){const e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);const r=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-r.getTime())/864e5+1)/7)}setFullYear(e){return this.jsDate.setUTCFullYear(e)}setMonth(e){return this.jsDate.setUTCMonth(e)}setDate(e){return this.jsDate.setUTCDate(e)}setHours(e){return this.jsDate.setUTCHours(e)}setMinutes(e){return this.jsDate.setUTCMinutes(e)}setSeconds(e){return this.jsDate.setUTCSeconds(e)}}const Je=new Qe(1899,11,30),et=864e5,tt=2e3,rt=Qe.now().getFullYear(),nt=Qe.now().getMonth(),ot=Qe.fromTimestamp(0).getTime()-Je.getTime(),st=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,it=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,at=Le.join(""),lt=new RegExp(`/|-|${Le.join("|")}`),ct=new RegExp(`^(\\d{1,4})[/${at}-](\\d{1,4})([/${at}-](\\d{1,4}))?$`),ut=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function ht(e,t){switch(typeof e){case"number":return e;case"string":return dt(e,t)?gt(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function dt(e,t){return null!==gt(e,t)}const ft=new Map;function gt(e,t){return ft.has(t)||ft.set(t,new Map),ft.get(t).has(e)||ft.get(t).set(e,function(e,t){e=e.trim();let r=null;const n=e.match(ut);if(n){if(r=function(e){if(e=e.trim(),ut.test(e)){const t=/AM/i.test(e),r=/PM/i.test(e),n=(t||r?e.substring(0,e.length-2).trim():e).split(/:/),o=n.length>=2,s=3===n.length;let i=Number(n[0]),a=o?Number(n[1]):0,l=s?Number(n[2]):0,c=s?"hh:mm:ss":"hh:mm";if(t||r)c+=" a";else if(!o)return null;i>=12&&t?i-=12:i<12&&r&&(i+=12),a+=Math.floor(l/60),l%=60,i+=Math.floor(a/60),a%=60,i>=24&&(c="hhhh:mm:ss");return{value:i/24+a/1440+l/86400,format:c,jsDate:new Qe(1899,11,30,i,a,l)}}return null}(n[0]),null===r)return null;e=e.replace(n[0],"").trim()}let o=null;const s=function(e,t){const r=e.match(ct);if(!r)return null;const[,n,o,,s]=r;if(n.length>2&&s&&s.length>2)return null;if(n.length>2)return{year:n,month:o,day:s,dateString:e,type:"ymd"};const i=function(e){switch(e.dateFormat[0]){case"d":return"dmy";case"m":return"mdy";case"y":return"ymd"}throw new Error("Invalid date format in locale")}(t);if(!s)return o.length>2?{month:n,year:o,day:void 0,dateString:e,type:i}:"dmy"===i?{day:n,month:o,year:s,dateString:e,type:"dmy"}:{month:n,day:o,year:s,dateString:e,type:"mdy"};if(s.length>2)return"mdy"===i?{month:n,day:o,year:s,dateString:e,type:"mdy"}:{day:n,month:o,year:s,dateString:e,type:"dmy"};if("mdy"===i)return{month:n,day:o,year:s,dateString:e,type:"mdy"};if("ymd"===i)return{year:n,month:o,day:s,dateString:e,type:"ymd"};if("dmy"===i)return{day:n,month:o,year:s,dateString:e,type:"dmy"};return null}(e,t);if(s){const t=s.dateString.match(lt)[0];if(o=function(e,t){const{year:r,month:n,day:o}=e,s=function(e){if(!e)return nt;const t=Number(e);if(t>=1&&t<=12)return t-1;return null}(n),i=function(e){if(!e)return 1;const t=Number(e);if(t>=0&&t<=31)return t;return null}(o),a=function(e){if(!e)return rt;const t=Number(e);switch(e.length){case 1:return tt+t;case 2:return tt+(tt+t>rt+10?-100:0)+t;case 3:case 4:return t}return null}(r);if(null===a||null===s||null===i)return null;const l=2===n?.length&&s+1<10||2===o?.length&&i<10,c=2!==r?.length,u=new Qe(a,s,i);if(u.getMonth()!==s||u.getDate()!==i)return null;const h=u.getTime()-Je.getTime(),d=function(e,t,r,n){const o=e.year?n?"yyyy":"yy":void 0,s=e.month?r?"mm":"m":void 0,i=e.day?r?"dd":"d":void 0;switch(e.type){case"mdy":return[s,i,o].filter(Se).join(t);case"ymd":return[o,s,i].filter(Se).join(t);case"dmy":return[i,s,o].filter(Se).join(t)}}(e,t,l,c);return{value:Math.round(h/et),format:d,jsDate:u}}(s,t),null===o)return null;e=e.replace(s.dateString,"").trim()}if(""!==e||!o&&!r)return null;if(o&&o.jsDate&&r&&r.jsDate)return{value:o.value+r.value,format:o.format+" "+("hhhh:mm:ss"===r.format?"hh:mm:ss":r.format),jsDate:new Qe(o.jsDate.getFullYear()+r.jsDate.getFullYear()-1899,o.jsDate.getMonth()+r.jsDate.getMonth()-11,o.jsDate.getDate()+r.jsDate.getDate()-30,o.jsDate.getHours()+r.jsDate.getHours(),o.jsDate.getMinutes()+r.jsDate.getMinutes(),o.jsDate.getSeconds()+r.jsDate.getSeconds())};return o||r}(e,t)),ft.get(t).get(e)}function mt(e){const t=Math.trunc(e),r=Qe.fromTimestamp(t*et-ot);let n=e-t;n=n<0?1+n:n;const o=Math.round(24*n),s=Math.round(24*(n-o/24)*60),i=Math.round(24*(n-o/24-s/24/60)*60*60);return r.setHours(o),r.setMinutes(s),r.setSeconds(i),r}function pt(e){return Math.round(bt(e))}function bt(e){return(e.getTime()-Je.getTime())/et}function vt(e){return new Qe(e.getFullYear(),e.getMonth()+1,0).getDate()}function yt(e){return vt(e)===e.getDate()}function Et(e,t,r){const n=e.getFullYear(),o=e.getMonth(),s=e.getDate(),i=new Qe(n,o+t,1);return r&&s===vt(e)||s>vt(i)?i.setDate(vt(i)):i.setDate(s),i}function wt(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function St(e,t,r){if(e===t)return 0;if(e>t){const r=t;t=e,e=r}const n=mt(e),o=mt(t);let s=n.getDate(),i=o.getDate();const a=n.getMonth(),l=o.getMonth(),c=n.getFullYear(),u=o.getFullYear();let h=0,d=0;switch(r){case 0:31===s&&(s=30),30===s&&31===i&&(i=30),1===a&&s===(wt(c)?29:28)&&(s=30,1===l&&i===(wt(u)?29:28)&&(i=30)),h=c+(30*a+s)/360,d=u+(30*l+i)/360;break;case 1:let r=365;const n=c===u;if(!n&&!(c+1===u)||!n&&a<l||!n&&a===l&&s<i){let e=0,t=0;for(let r=c;r<=u;r++)e++,t+=wt(r)?366:365;r=t/e}else n?wt(c)&&(r=366):(wt(c)&&a<2&&(r=366),wt(u)&&(l>1||1===l&&29===i)&&(r=366));h=e/r,d=t/r;break;case 2:h=e/360,d=t/360;break;case 3:h=e/365,d=t/365;break;case 4:31===s&&(s=30),31===i&&(i=30),h=c+(30*a+s)/360,d=u+(30*l+i)/360}return d-h}function Ct(e,t){const r=12*(t.getFullYear()-e.getFullYear())+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?r-1:r}function Tt(e,t){const r=e.getTime(),n=t.getTime();return Math.floor((n-r)/et)}function It(e,t){const r=t.getFullYear()-e.getFullYear(),n=e.getMonth(),o=t.getMonth(),s=e.getDate(),i=t.getDate();return o>n||o===n&&i>=s?r:r-1}function xt(e,t,r){return t>r?xt(e,r,t):(e=Math.trunc(e),t=Math.trunc(t),r=Math.trunc(r),e>=t&&e<=r)}const Rt=Ue(function(e){return e=te(e),new RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:(E|e)(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),At=Ue(function(e){const t=te(e.decimalSeparator),r="(?:\\s*"+`(?:\\d+(?:${te(e.thousandsSeparator||"")}\\d{3,})*(?:${t}\\d*)?)`+"|"+`(?:${t}\\d+)`+")(?:(e|E)(?:\\+|-)?(?:[0-9]|[0-9][0-9]|[12][0-9]{2}|30[0-7]))?(?:\\s*%)?",n="(?:\\s*-)?",o="(?:\\s*[\\$€])?",s="^(?:(?:"+[n+o+r,n+r+o,o+n+r].join(")|(?:")+"))$";return new RegExp(s,"i")});function Ot(e,t){return!!e&&At(t).test(e.trim())}const _t=Ue(function(e){return new RegExp(`[$€${te(e.thousandsSeparator||"")}]`,"g")});function Dt(e,t){e=e.replace(_t(t),""),"."!==t.decimalSeparator&&(e=e.replace(t.decimalSeparator,"."));let r=Number(e);return isNaN(r)&&e.includes("%")&&(r=Number(e.split("%")[0]),!isNaN(r))?r/100:r}function Ft(e,t,r){const n=[...e].sort((e,t)=>e-t);let o=(n.length+(r?-1:1))*t;if(r||o--,Number.isInteger(o))return n[o];const s=Math.ceil(o),i=Math.floor(o);return n[s]*(o-i)+n[i]*(s-o)}const Nt=["number","string","boolean","undefined"];function Mt(e){if(void 0!==e)return D(e)?e[0][0]?.format:e.format}function Vt(e){return"string"==typeof e&&w.has(e)}function Lt(e){return{value:E.NotAvailable,message:v("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",$t(e))}}const Pt=e=>v("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function kt(e,t){const r=Yt(e);switch(typeof r){case"number":return r;case"boolean":return r?1:0;case"string":if(Ot(r,t)||""===r)return Dt(r,t);const e=gt(r,t);if(e)return e.value;throw new S(Pt(r));default:return 0}}function Ut(e,t){return mr(e).map(e=>e.map(e=>{if("number"!=typeof e.value){let r="";throw"object"==typeof e?r=v("Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.",t):"string"==typeof e?r=v("Function [[FUNCTION_NAME]] expects number values for %s, but got a string.",t):"boolean"==typeof e&&(r=v("Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.",t)),new S(r)}return e.value}))}function Ht(e,t){const r=Yt(e);if(""===r)throw new S(Pt(r));return kt(r,t)}function Bt(e,t){return Math.trunc(kt(e,t))}function zt(e,t){return Math.trunc(Ht(e,t))}function $t(e){const t=Yt(e);switch(typeof t){case"string":return t;case"number":return t.toString();case"boolean":return t?"TRUE":"FALSE";default:return""}}const Gt=Ue(function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}),Wt=e=>v("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.",e);function qt(e){const t=Yt(e);switch(typeof t){case"boolean":return t;case"string":if(t){const e=t.toUpperCase();if("TRUE"===e)return!0;if("FALSE"===e)return!1;throw new S(Wt(t))}return!1;case"number":return!!t;default:return!1}}function Zt(e,t){return mt(kt(Yt(e),t))}function Yt(e){if("object"==typeof e&&null!==e&&"value"in e){if(Vt(e.value))throw e;return e.value}if(Vt(e))throw new S("",e);return e}function jt(e,t,r){for(const n of e)if(D(n)){const e=n.length,r=n[0].length;for(let o=0;o<r;o++)for(let r=0;r<e;r++)t(n[r][o])}else r(n)}function Xt(e,t){jt(e,e=>{if(Vt(e.value))throw e;t(e)},e=>{if(Vt(e?.value))throw e;t(e)})}function Kt(e,t,r){jt(e,e=>{if("number"==typeof e?.value&&t(e),Vt(e?.value))throw e},e=>{t({value:Ht(e,r),format:e?.format})})}function Qt(e,t,r,n,o="rowFirst"){let s=n;for(const n of e)if(D(n)){const e=n.length,r=n[0].length;if("rowFirst"===o)for(let o=0;o<r;o++)for(let r=0;r<e;r++)s=t(s,n[r][o]);else for(let o=0;o<e;o++)for(let e=0;e<r;e++)s=t(s,n[o][e])}else s=r(s,n);return s}function Jt(e,t,r,n="rowFirst"){return Qt(e,t,t,r,n)}function er(e,t,r,n){return Qt(e,(e,r)=>{const n=r?.value;if("number"==typeof n)return t(e,n);if(Vt(n))throw r;return e},(e,r)=>t(e,Ht(r,n)),r)}function tr(e,t,r,n){return Qt(e,(e,r)=>{const o=r?.value;if(null!=o){if("number"==typeof o)return t(e,o);if("boolean"==typeof o)return t(e,kt(o,n));if(Vt(o))throw r;return t(e,0)}return e},(e,r)=>t(e,kt(r,n)),r)}function rr(e,t,r){const n=Array(e);for(let o=0;o<e;o++){n[o]=Array(t);for(let e=0;e<t;e++)n[o][e]=r(o,e)}return n}function nr(e,t){return 0===e.length?[]:rr(e.length,e[0].length,(r,n)=>t(e[r][n]))}function or(e){return e.length?rr(e[0].length,e.length,(t,r)=>e[r][t]):[]}function sr(e,t,r=void 0){let n,o=1,s=1,i=1/0,a=1/0;for(let e=0;e<t.length;e++){const l=t[e];if(D(l)&&(void 0===r||r[e])){const r=l.length,c=l[0].length;1!==r||1!==c?(n??=new Array(t.length),1!==r&&1!==c?(n[e]="matrix",o=Math.max(o,r),s=Math.max(s,c),i=Math.min(i,r),a=Math.min(a,c)):1!==r?(n[e]="horizontal",o=Math.max(o,r),i=Math.min(i,r)):1!==c&&(n[e]="vertical",s=Math.max(s,c),a=Math.min(a,c))):t[e]=l[0][0]}}if(1===o&&1===s)return e(...t);return rr(o,s,(r,o)=>{if(r>i-1||o>a-1)return new x(v("Array arguments to [[FUNCTION_NAME]] are of different size."));const s=e(...(l=r,c=o,t.map((e,t)=>{switch(n?.[t]){case"matrix":return e[l][c];case"horizontal":return e[l][0];case"vertical":return e[0][c];case void 0:return e}})));var l,c;return D(s)?s[0][0]:s})}function ir(e,t){return function(e,t,r){for(const n of e)if(D(n)){const e=n.length,r=n[0].length;for(let o=0;o<r;o++)for(let r=0;r<e;r++)if(!t(n[r][o]??void 0))return}else if(!r(n))return}(e,e=>{const r=e?.value;if("boolean"==typeof r)return t(r);if("number"==typeof r)return t(!!r);if(Vt(r))throw e;return!0},e=>void 0===e||null===e.value||t(function(e){const t=Yt(e);if(""===t)throw new S(Wt(t));return qt(t)}(e)))}function ar(e,t){let r,n,o=e.substring(0,2);return"<="===o||">="===o||"<>"===o?(r=o,n=e.substring(2)):(o=e.substring(0,1),"<"===o||">"===o||"="===o?(r=o,n=e.substring(1)):(r="=",n=e)),Ot(n,t)||dt(n,t)?n=kt(n,t):"TRUE"!==n&&"FALSE"!==n||(n=qt(n)),{operator:r,operand:n}}const lr=Ue(function(e){if("*"===e)return/.+/;let t="",r="";for(const n of e)"?"===n&&"~"!==r?t+=".":"*"===n&&"~"!==r?t+=".*":("*"!==n&&"?"!==n||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(n)&&(t+="\\"),t+=n),r=n;return new RegExp("^"+t+"$","i")});function cr(e="",t,r){const{operator:n,operand:o}=t;if(void 0===o||null===e||null===o)return!1;if("number"==typeof o&&"="===n)return"string"==typeof e&&(Ot(e,r)||dt(e,r))?kt(e,r)===o:e===o;if("<>"===n||"="===n){let t;return t=typeof e==typeof o&&(""===e&&""===o||("string"==typeof e&&"string"==typeof o?lr(o).test(e):e===o)),"="===n?t:!t}if(typeof e==typeof o)switch(n){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function ur(e,t,r,n=!1){const o=e.length;if(o%2==1)throw new S(v("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const s=mr(e[0]),i=s.length,a=s[0].length,l=[];for(let t=0;t<o-1;t+=2){const o=mr(e[t]);if(o.length!==i||o[0].length!==a)throw new S(v("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const s=ar($t(e[t+1]),r);n&&"string"==typeof s.operand&&(s.operand+="*"),l.push(s)}for(let n=0;n<i;n++)for(let s=0;s<a;s++){let i=!0;for(let t=0;t<o-1;t+=2){if(i=cr(mr(e[t])[n][s].value??void 0,l[t/2],r),!i)break}i&&t(n,s)}}function hr(e,t,r,n,o,s){if(void 0===t||null===t.value)return-1;if(Vt(t.value))throw t;const i=fr(t.value),a=typeof i;let l,c,u,h,d,f,g=0,m=o-1;const p="desc"===n?t=>fr(s(e,o-t-1)):t=>fr(s(e,t));for(;m-g>=0;){for(u=Math.floor((g+m)/2),h=u,d=p(h),f=typeof d;g<h&&a!==f;)h--,d=p(h),f=typeof d;f===a&&null!=d?("strict"===r&&d===i?(l=d,c=h):"nextSmaller"===r&&d<=i?(null==l||l<d||l===d&&c<h)&&(l=d,c=h):"nextGreater"===r&&d>=i&&(void 0===l||l>d||l===d&&c<h)&&(l=d,c=h),d>i||"strict"===r&&d===i?m=h-1:g=u+1):g=u+1}return void 0===c?-1:"desc"===n?o-c-1:c}function dr(e,t,r,n,o,s,i=!1){if(void 0===t||null===t.value)return-1;if(Vt(t.value))throw t;const a=fr(t.value),l=i?(e,t)=>fr(o(e,n-t-1)):(e,t)=>fr(o(e,t)),c="wildcard"!==r||"string"!=typeof a||!(a.includes("*")||a.includes("?"));if(s&&c){const t=i?"reverseSearch":"forwardSearch";let o=s[t].get(e);if(void 0===o){o=new Map;for(let t=0;t<n;t++){const r=l(e,t)??null;o.has(r)||o.set(r,t)}s[t].set(e,o)}if(o.has(a)){const e=o.get(a);return i?n-e-1:e}if("strict"===r)return-1}const u=function(e,t,r,n,o){let s=r=>o(e,r)===t;if("wildcard"===r&&"string"==typeof t&&(t.includes("*")||t.includes("?"))){const r=lr(t);s=t=>{const n=o(e,t);return"string"==typeof n&&r.test(n)}}let i,a=-1;"nextSmaller"===r&&(s=r=>{const n=o(e,r);return(!i&&gr(t,n)>=0||gr(t,n)>=0&&gr(n,i)>0)&&(i=n,a=r),n===t});"nextGreater"===r&&(s=r=>{const n=o(e,r);return(!i&&gr(t,n)<=0||gr(t,n)<=0&&gr(n,i)<0)&&(i=n,a=r),n===t});for(let e=0;e<n;e++)if(s(e))return e;return a}(e,a,r,n,l);return i&&-1!==u?n-u-1:u}function fr(e){return"string"==typeof e?Gt(e):e}function gr(e,t){let r=Nt.indexOf(typeof e)-Nt.indexOf(typeof t);return 0===r&&("string"==typeof e&&"string"==typeof t?r=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?r=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(r=Number(e)-Number(t))),r}function mr(e){return void 0===e?[[]]:D(e)?e:[[e]]}function pr(e,t){return Jt(e,(e,r)=>(e.push(t(r)),e),[],"rowFirst")}function br(e){if(void 0===e)return!1;const{value:t}=e;return null!==t&&""!==t}const vr=v("[[FUNCTION_NAME]] has no valid input data.");function yr(e){return v("[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.",{argName:e})}function Er(e){function t(...t){for(let r=0;r<t.length;r++){const n=t[r],o=c(e,t.length);if(!e.args[o(r).index??r].acceptErrors&&!D(n)&&Vt(n?.value))return n}try{return r.apply(this,t)}catch(t){return wr(t,e.name)}}function r(...t){this.debug;const r=e.compute.apply(this,t);return D(r)?"object"==typeof r[0][0]&&null!==r[0][0]&&"value"in r[0][0]?r:nr(r,e=>({value:e})):"object"==typeof r&&null!==r&&"value"in r?r:(e.name,{value:r})}return function(...r){const n=[],o=c(e,r.length);for(let t=0;t<r.length;t++){const s=o(t).index??-1,i=e.args[s];if(!D(r[t])&&i.acceptMatrixOnly)throw new C(v("Function %s expects the parameter '%s' to be reference to a cell or range.",e.name,(t+1).toString()));n.push(!i.acceptMatrix)}return function(t){D(t)?function(e,t){const r=e.length,n=e[0]?.length??0;for(let o=0;o<r;o++)for(let r=0;r<n;r++)t(e[o][r])}(t,t=>Sr(t,e.name)):Sr(t,e.name);return t}(sr(t.bind(this),r,n))}}function wr(e,t){return r=e,void 0!==r?.value&&"string"==typeof r.value&&Vt(e.value)?(Tr(e)&&Sr(e,t),e):(console.error(e),new S(Cr+(Tr(e)?" "+e.message:"")));var r}function Sr(e,t){e.message?.includes("[[FUNCTION_NAME]]")&&(e.message=e.message.replace("[[FUNCTION_NAME]]",t))}const Cr=v("An unexpected error occurred. Submit a support ticket at odoo.com/help.");function Tr(e){return void 0!==e?.message&&"string"==typeof e.message}const Ir=[{name:"English (US)",code:"en_US",thousandsSeparator:",",decimalSeparator:".",weekStart:7,dateFormat:"m/d/yyyy",timeFormat:"hh:mm:ss a",formulaArgSeparator:","},{name:"French",code:"fr_FR",thousandsSeparator:" ",decimalSeparator:",",weekStart:1,dateFormat:"dd/mm/yyyy",timeFormat:"hh:mm:ss",formulaArgSeparator:";"}],xr=Ir[0];function Rr(e){let t;if('"'===e.current?(e.shift(),t='"'):e.currentStartsWith("[$")&&(e.advanceBy(2),t="]"),!t)return null;let r="";for(;e.current&&e.current!==t;)r+=e.shift();if(e.current!==t)throw new Error("Unterminated string in format");return e.shift(),{type:"STRING",value:r}}const Ar=new Set("$+-/():!^&~{}<>= ");function Or(e){if("\\"===e.current){e.shift();const t=e.shift();if(!t)throw new Error("Unexpected end of format string");return{type:"CHAR",value:t}}return Ar.has(e.current)?{type:"CHAR",value:e.shift()}:null}function _r(e){return","===e.current?(e.shift(),{type:"THOUSANDS_SEPARATOR",value:","}):null}function Dr(e){return"@"===e.current?(e.shift(),{type:"TEXT_PLACEHOLDER",value:"@"}):null}function Fr(e){return"."===e.current?(e.shift(),{type:"DECIMAL_POINT",value:"."}):null}function Nr(e){return"%"===e.current?(e.shift(),{type:"PERCENT",value:"%"}):null}function Mr(e){return"e"===e.current?(e.shift(),{type:"SCIENTIFIC",value:"e"}):null}function Vr(e){if("0"===e.current||"#"===e.current){const t=e.current;return e.shift(),{type:"DIGIT",value:t}}return null}const Lr=new Set("dmqyhsa");function Pr(e){if(!Lr.has(e.current))return null;const t=e.current;let r="";for(;e.current===t;)r+=e.shift();return{type:"DATE_PART",value:r}}function kr(e){if("*"!==e.current)return null;e.shift();const t=e.shift();if(!t)throw new Error("Unexpected end of format string");return{type:"REPEATED_CHAR",value:t}}const Ur={};function Hr(e){let t=Ur[e];return void 0===t&&(t=function(e){const t=function(e){const t=new Ze(e),r=[];let n=[];for(r.push(n);!t.isOver();){if(";"===t.current){n=[],r.push(n),t.shift();continue}const e=Vr(t)||Rr(t)||Or(t)||_r(t)||Fr(t)||Nr(t)||Mr(t)||Pr(t)||Dr(t)||kr(t);if(!e)throw new Error("Unknown token at "+t.remaining());n.push(e)}return r}(e);for(const e of t){const t=e.filter(e=>"REPEATED_CHAR"===e.type);for(const e of t.slice(1))e.type="CHAR"}const r=zr(t[0])||Br(t[0])||$r(t[0]);if(!r)throw new Error("Invalid first format part of: "+e);if(t.length>1&&"text"===r.type)throw new Error("The first format in a multi-part format must be a number format: "+e);const n=zr(t[1])||Br(t[1]);if(t[1]?.length&&!n)throw new Error("Invalid second format part of: "+e);const o=zr(t[2])||Br(t[2]);if(t[2]?.length&&!o)throw new Error("Invalid third format part of: "+e);const s=$r(t[3]);if(t[3]?.length&&!s)throw new Error("Invalid fourth format part of: "+e);return{positive:r,negative:n,zero:o,text:s}}(e),Ur[e]=t),t}function Br(e){if(!e||!function(e){return e.every(e=>"DIGIT"===e.type||"DECIMAL_POINT"===e.type||"THOUSANDS_SEPARATOR"===e.type||"PERCENT"===e.type||"SCIENTIFIC"===e.type||"STRING"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e))return;const t=[];let r,n=t,o=0,s=!1,i=0,a=e.findLastIndex(e=>"DIGIT"===e.type),l=!1,c=0;for(let u=0;u<e.length;u++){const h=e[u];switch(h.type){case"DIGIT":n===t?n.push(h):c<20&&(n.push(h),c++);break;case"DECIMAL_POINT":if(n!==t)throw new Error("Multiple decimal points in a number format");r=[],n=r;break;case"SCIENTIFIC":s=!0;break;case"REPEATED_CHAR":case"CHAR":case"STRING":n.push(h);break;case"PERCENT":o++,n.push(h);break;case"THOUSANDS_SEPARATOR":u-1===a?(i+=1,a++,n.push(h)):"DIGIT"===e[u+1]?.type&&"DIGIT"===e[u-1]?.type?(n===t&&(l=!0),n.push(h)):n.push({type:"CHAR",value:","})}}return{type:"number",integerPart:t,decimalPart:r,percentSymbols:o,scientific:s,thousandsSeparator:l,magnitude:i}}function zr(e){const t=e&&function(e){return e.every(e=>"DATE_PART"===e.type||"DECIMAL_POINT"===e.type||"THOUSANDS_SEPARATOR"===e.type||"STRING"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e)?{type:"date",tokens:e}:void 0;if(!t||!e?.some(e=>"DATE_PART"===e.type))return;if(t.tokens.length&&t.tokens.every(e=>"DATE_PART"===e.type&&"a"===e.value))throw new Error("Invalid date format");const r=function(e){const t=e.filter(e=>"DATE_PART"===e.type);for(let e=0;e<t.length;e++)!t[e].value.startsWith("m")||t[e].value.length>2||(t[e-1]?.value.startsWith("h")||t[e+1]?.value.startsWith("s"))&&(t[e].value=t[e].value.replaceAll("m","M"));return e}(t.tokens.map(e=>"THOUSANDS_SEPARATOR"===e.type||"DECIMAL_POINT"===e.type?{type:"CHAR",value:e.value}:e));return{type:"date",tokens:r}}function $r(e){return e&&function(e){return e.every(e=>"STRING"===e.type||"TEXT_PLACEHOLDER"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e)?{type:"text",tokens:e}:void 0}function Gr(e){return[Wr(e.positive),Wr(e.negative),Wr(e.zero),Wr(e.text)].filter(Se).join(";")}function Wr(e){if(!e)return;let t="";const r="number"!==e.type?e.tokens:function(e){const t=[...e.integerPart];e.decimalPart&&(t.push({type:"DECIMAL_POINT",value:"."}),t.push(...e.decimalPart));e.scientific&&t.push({type:"SCIENTIFIC",value:"e"});return t}(e);for(const e of r)switch(e.type){case"STRING":t+=`[$${e.value}]`;break;case"CHAR":t+=qr(e.value)?`\\${e.value}`:e.value;break;case"REPEATED_CHAR":t+="*"+e.value;break;case"DATE_PART":t+="MM"===e.value?"mm":e.value;break;default:t+=e.value}return t}function qr(e){return!Ar.has(e)}const Zr="REPEATED_CHAR_PLACEHOLDER_",Yr={0:v("January"),1:v("February"),2:v("March"),3:v("April"),4:v("May"),5:v("June"),6:v("July"),7:v("August"),8:v("September"),9:v("October"),10:v("November"),11:v("December")},jr={0:v("Sunday"),1:v("Monday"),2:v("Tuesday"),3:v("Wednesday"),4:v("Thursday"),5:v("Friday"),6:v("Saturday")};function Xr(e,{format:t,locale:r,formatWidth:n}){switch("boolean"==typeof e&&(e=e?"TRUE":"FALSE"),typeof e){case"string":{if(e.includes('\\"')&&(e=e.replaceAll(/\\"/g,'"')),!t)return e;const r=Kr(e,Hr(t)).format;return r&&"text"===r.type?Qr(e,r,n):e}case"number":t||(t=ln(e));const o=Hr(t),{format:s,isNegativeFormat:i}=Kr(e,o);if(!s)return e.toString();if("text"===s.type)return Qr(e.toString(),s,n);if(i&&(e=Math.abs(e)),"date"===s.type)return Jr(function(e,t){const r=mt(e),n=t.tokens.some(e=>"DATE_PART"===e.type&&"a"===e.value);let o="";for(const e of t.tokens)switch(e.type){case"DATE_PART":o+=sn(r,e.value,n);break;case"REPEATED_CHAR":o+=Zr+e.value;break;default:o+=e.value}return o}(e,s),n);const a=e<0,l=Jr(function(e,t,r){if(!t.integerPart.length&&!t.decimalPart?.length)return"";if(e===1/0)return"∞"+(t.percentSymbols?"%":"");let n=Math.floor(Math.log10(Math.abs(e)));n===-1/0&&(n=0);t.scientific&&(e/=10**n);const o=2*t.percentSymbols-3*t.magnitude;e*=10**o;let s=0;void 0!==t.decimalPart&&(s=t.decimalPart.filter(e=>"DIGIT"===e.type).length);const{integerDigits:i,decimalDigits:a}=tn(Math.abs(e),s);let l=function(e,t,r){let n=t.integerPart;n.some(e=>"DIGIT"===e.type)||(n=[...n,{type:"DIGIT",value:"#"}]);"0"===e&&(e="");let o="";const s=n.findIndex(e=>"DIGIT"===e.type);let i=e.length-1;function a(t,n){if("0"===n&&(t=t||"0"),!t)return;const s=e.length-1-i;o=r&&s>0&&s%3==0?t+r+o:t+o}for(let t=n.length-1;t>=0;t--){const r=n[t];switch(r.type){case"DIGIT":if(a(e[i],r.value),i--,s===t)for(;i>=0;)a(e[i],"0"),i--;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":o=Zr+r.value+o;break;default:o=r.value+o}}return o}(i,t,t.thousandsSeparator?r.thousandsSeparator:void 0);void 0!==t.decimalPart&&(l+=r.decimalSeparator+function(e,t){if(!t.decimalPart)return"";let r="",n=0;for(const o of t.decimalPart)switch(o.type){case"DIGIT":r+="#"===o.value?e[n]||"":e[n]||"0",n++;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":r+=Zr+o.value;break;default:r+=o.value}return r}(a||"",t));if(t.scientific){l+="e"+(n>=0?"+":"-")+Math.abs(n).toString().padStart(2,"0")}return l}(Math.abs(e),s,r),n);return a?"-"+l:l;case"object":return""}}function Kr(e,t){let r,n=!1;switch(typeof e){case"number":e<0&&t.negative?(r=t.negative,n=!0):r=0===e&&t.zero?t.zero:t.positive;break;case"string":const o=t.text||t.positive;"text"===o.type&&(r=o)}return{format:r,isNegativeFormat:n}}function Qr(e,t,r){let n="";for(const r of t.tokens)switch(r.type){case"TEXT_PLACEHOLDER":n+=e;break;case"CHAR":case"STRING":n+=r.value;break;case"REPEATED_CHAR":n+=Zr+r.value}return Jr(n,r)}function Jr(e,t){const r=e.indexOf(Zr);if(-1===r)return e;const n=e.slice(0,r),o=e.slice(r+26+1),s=e[r+26];const{timesToRepeat:i,padding:a}=function(){if(!t)return{timesToRepeat:0,padding:""};const e=t.measureText(n+o),r=t.measureText(s),i=t.availableWidth-e;if(i<=0)return{timesToRepeat:0,padding:""};const a=Math.floor(i/r),l=i-a*r,c=t.measureText(" ");return{timesToRepeat:a,padding:" ".repeat(Math.floor(l/c))}}();return n+s.repeat(i)+a+o}const en=[];function tn(e,t=20){const r=e.toString();if(r.includes("e"))return function(e,t=20){let r=en[t];r||(r=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),en[t]=r);const[n,o]=r.format(e).split(".");return{integerDigits:n,decimalDigits:o}}(e,t);if(Number.isInteger(e))return{integerDigits:r,decimalDigits:void 0};const n=r.indexOf(".");let o=r.substring(0,n),s=r.substring(n+1);if(0===t)return Number(s[0])>=5&&(o=(Number(o)+1).toString()),{integerDigits:o,decimalDigits:void 0};if(s.length>t){const{integerDigits:e,decimalDigits:r}=function(e,t){let r="0",n=e;const o=e.slice(0,t),s=t;if(Number(e[s])<5)return{integerDigits:r,decimalDigits:o};const i=o.match(nn)?.[0]||"",a=(Number(o)+1).toString(),l=o.slice(i.length),c=a.length>l.length;c&&!i?(r="1",n=void 0):n=c?i.slice(0,-1)+a:i+a;return{integerDigits:r,decimalDigits:n}}(s,t);s=r,"0"!==e&&(o=(Number(o)+Number(e)).toString())}return{integerDigits:o,decimalDigits:rn(s||"")}}function rn(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const nn=/^0+/;const on=Ue(function(e){if(!e)return!1;try{return"date"===Hr(e).positive.type}catch(e){return!1}});function sn(e,t,r){switch(t){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return jr[e.getDay()].slice(0,3);case"dddd":return jr[e.getDay()].toString();case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return Yr[e.getMonth()].slice(0,3);case"mmmm":return Yr[e.getMonth()].toString();case"mmmmm":return Yr[e.getMonth()].slice(0,1);case"qq":return v("Q%(quarter)s",{quarter:e.getQuarter()}).toString();case"qqqq":return v("Quarter %(quarter)s",{quarter:e.getQuarter()}).toString();case"yy":const n=String(e.getFullYear()).replace("-","").padStart(2,"0");return n.slice(n.length-2);case"yyyy":return e.getFullYear();case"hhhh":return Math.floor((e.getTime()-Je.getTime())/36e5).toString();case"hh":let o=e.getHours();return r&&(o=0===o?12:o>12?o-12:o),o.toString().padStart(2,"0");case"MM":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");case"a":return e.getHours()>=12?"PM":"AM";default:throw new Error(`invalid date format token: ${t}`)}}const an=Ue(function(e){return new RegExp(`[0-9]+${te(e.decimalSeparator)}[0-9]`)});function ln(e){let{integerDigits:t,decimalDigits:r}=tn(e);if(!r)return"0";const n=t.replace("-","").length;if(n+2>11)return"0";const o=11-n-1;return({decimalDigits:r}=tn(e,Math.min(o,r.length))),r?"0."+"0".repeat(r.length):"0"}function cn(e,t){if(!dt(e,t))return;return gt(e,t).format}function un(e){const t=e.includes(".")?"0.00":"0",r=e.match(/[\$€]/);if(r){const n=e.match(/[\d]/),o="[$"+r.values().next().value+"]";return n.index<r.index?"#,##"+t+o:o+"#,##"+t}if(e.includes("%"))return t+"%"}function hn(e,t,r){let n=0;try{n=Math.abs(kt(e?.value,r))}catch(e){return""}const o=e?.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return dn(o,1,"k");case"m":return dn(o,2,"m");case"b":return dn(o,3,"b");default:throw new S(v("The formatting unit should be 'k', 'm' or 'b'."))}}return n<1e5?dn(o,0,""):n<1e8?dn(o,1,"k"):n<1e11?dn(o,2,"m"):dn(o,3,"b")}function dn(e,t,r,n){const o=Hr(e||"#,##0");return Gr({positive:fn(o.positive,t,r),negative:o.negative?fn(o.negative,t,r):void 0,zero:o.zero?fn(o.zero,t,r):void 0,text:o.text})}function fn(e,t,r){if("number"!==e.type)return e;const n={type:"STRING",value:r};let o=[...e.integerPart];const s=o.findLastIndex(e=>"DIGIT"===e.type);if(-1===s)throw new Error("Cannot create a large number format from a format with no digit.");for(;"THOUSANDS_SEPARATOR"===o[s+1]?.type;)o=He(o,[s+1]);const i=o[s+1];o="STRING"===i?.type&&["m","k","b"].includes(i.value)?ze(o,n,s+1):Be(o,[n],s+1),t>0&&(o=Be(o,Array(t).fill({type:"THOUSANDS_SEPARATOR",value:","}),s+1));const a=e.percentSymbols-o.filter(e=>"PERCENT"===e.type).length;return o.push(...new Array(a).fill({type:"PERCENT",value:"%"})),{...e,integerPart:o,decimalPart:void 0,magnitude:t}}function gn(e,t){const r=Hr(e);return Gr(Hr(Gr({positive:mn(r.positive,t),negative:r.negative?mn(r.negative,t):void 0,zero:r.zero?mn(r.zero,t):void 0,text:r.text})))}function mn(e,t){return"number"!==e.type?e:t>0?function(e,t){let r=e.integerPart,n=e.decimalPart;if(!n){const e=r.findLastIndex(e=>"DIGIT"===e.type);n=r.slice(e+1),r=r.slice(0,e+1)}const o=le(0,t).map(()=>({type:"DIGIT",value:"0"})),s=n.findLastIndex(e=>"DIGIT"===e.type);n=-1===s?[...o,...n]:Be(n,o,s+1);return{...e,decimalPart:n,integerPart:r}}(e,t):function(e,t){let r=e.decimalPart;if(!r)return e;const n=[];let o=0;for(let e=r.length-1;e>=0&&!(o>=Math.abs(t));e--)"DIGIT"===r[e].type&&(o++,n.push(e));if(r=He(r,n),r.some(e=>"DIGIT"===e.type))return{...e,decimalPart:r};return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...r]}}(e,Math.abs(t))}function pn(e){const t=Hr(e);for(const e of[t.positive,t.negative,t.zero])if(e&&"date"===e.type&&e.tokens.some(e=>"DATE_PART"===e.type&&e.value.includes("q")))return!1;return!0}function bn(e){if(!e)return!1;try{return"text"===Hr(e).positive.type}catch{return!1}}function vn(e,t,r){const n=e.value;switch(typeof n){case"number":return Xr(n,{locale:r,format:e.format});case"string":return Vt(n)?n:`"${n}"`;case"boolean":return n?"TRUE":"FALSE"}return t}function yn(e,t){if(!e)throw new S(t)}function En(e,t=v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")){if(0===e)throw new O(t)}function wn(e){return 1===e.length||1===e[0].length}function Sn(...e){if(e.every(D)){const t=e[0].length,r=e[0][0].length;for(const n of e)if(n.length!==t||n[0].length!==r)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(1!==e.length||1!==e[0].length))}function Cn(e){return e.length===e[0].length}const Tn=e=>v("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e);function In(e){const t=Array(e);for(let r=0;r<e;r++)t[r]=Array(e).fill(0),t[r][r]=1;return t}function xn(e){if(e.length<1||e[0].length<1)throw new Error("invertMatrix: an empty matrix cannot be inverted.");if(e.length!==e[0].length)throw new Error("invertMatrix: only square matrices are invertible");let t=1;const r=e.length,n=In(r),o=e.map(e=>e.slice());for(let e=0;e<r;e++){let s=o[e][e];if(0===s){for(let s=e+1;s<r;s++)if(0!==o[e][s]){Rn(o,e,s),Rn(n,e,s),t*=-1;break}if(s=o[e][e],0===s)return{determinant:0}}for(let t=0;t<r;t++)o[t][e]=o[t][e]/s,n[t][e]=n[t][e]/s;t*=s;for(let t=0;t<r;t++){if(t===e)continue;const s=o[e][t];for(let i=0;i<r;i++)o[i][t]-=s*o[i][e],n[i][t]-=s*n[i][e]}}return{inverted:n,determinant:t}}function Rn(e,t,r){for(let n=0;n<e.length;n++){const o=e[n][t];e[n][t]=e[n][r],e[n][r]=o}}function An(e,t){if(e.length<1||t.length<1)throw new Error("multiplyMatrices: empty matrices cannot be multiplied.");if(e.length!==t[0].length)throw new Error("multiplyMatrices: incompatible matrices size.");const r=e[0].length,n=t.length,o=e.length,s=Array(n);for(let i=0;i<n;i++){s[i]=Array(r);for(let n=0;n<r;n++){let r=0;for(let s=0;s<o;s++)r+=e[s][n]*t[i][s];s[i][n]=r}}return s}function On(e){if(!D(e))return e;if(!_n(e))throw new Error("The value should be a scalar or a 1x1 matrix");return e[0][0]}function _n(e){return 1===e.length&&1===e[0].length}function Dn(e){return D(e)&&!_n(e)}function Fn(e,t){const r=e.map(mr),n=r.map(e=>e?.[0]?.length??0),o=Math.max(...n);if(t?.requireSameRowCount){const e=n[0];if(n.some(t=>t!==e))return new S(v("All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).",n.join(", ")))}const s=[];for(const e of r)for(let t=0;t<e.length;t++){const r=Array(o).fill({value:null});for(let n=0;n<e[t].length;n++)r[n]=e[t][n];s.push(r)}return s}function Nn(e,t){const r=e.map(mr),n=r.map(e=>e?.length??0),o=Math.max(...n);if(t?.requireSameColCount){const e=n[0];if(n.some(t=>t!==e))return new S(v("All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).",n.join(", ")))}const s=rr(o,r.reduce((e,t)=>e+(t?.[0]?.length??0),0),()=>({value:null}));let i=0;for(const e of r){for(let t=0;t<e.length;t++)for(let r=0;r<e[t].length;r++)s[t][i+r]=e[t][r];i+=e[0]?.length??0}return s}const Mn={description:v("Returns a result array constrained to a specific width and height."),args:[a("input_range (any, range<any>)",v("The range to constrain.")),a("rows (number)",v("The number of rows in the constrained array.")),a("columns (number)",v("The number of columns in the constrained array."))],compute:function(e,t,r){const n=mr(e),o=Bt(t?.value,this.locale),s=Bt(r?.value,this.locale);if(o<=0)return new S(v("The rows argument (%s) must be strictly positive.",o.toString()));if(s<=0)return new S(v("The columns argument (%s) must be strictly positive.",s.toString()));const i=Math.min(o,n[0].length);return rr(Math.min(s,n.length),i,(e,t)=>n[e][t])},isExported:!1},Vn={description:v("Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns."),args:[a("range (any, range<any>, repeating)",v("The range to be appended."))],compute:function(...e){return Nn(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},Ln={description:v("Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows."),args:[a("range (any, range<any>, repeating)",v("The range to be appended."))],compute:function(...e){return Fn(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},Pn={description:v("Creates a new array from the selected columns in the existing range."),args:[a("array (any, range<any>)",v("The array that contains the columns to be returned.")),a("col_num (number, range<number>, repeating)",v("The column index of the column to be returned."))],compute:function(e,...t){const r=mr(e),n=pr(t,e=>Bt(e?.value,this.locale)),o=n.filter(e=>0===e||r.length<Math.abs(e));if(0!==o.length)return new S(v("The columns arguments must be between -%s and %s (got %s), excluding 0.",r.length.toString(),r.length.toString(),o.join(",")));const s=Array(n.length);for(let e=0;e<n.length;e++)n[e]>0?s[e]=r[n[e]-1]:s[e]=r[r.length+n[e]];return s},isExported:!0},kn={description:v("Creates a new array from the selected rows in the existing range."),args:[a("array (any, range<any>)",v("The array that contains the rows to be returned.")),a("row_num (number, range<number>, repeating)",v("The row index of the row to be returned."))],compute:function(e,...t){const r=mr(e),n=pr(t,e=>Bt(e?.value,this.locale)),o=r.length,s=n.filter(e=>0===e||r[0].length<Math.abs(e));return 0!==s.length?new S(v("The rows arguments must be between -%s and %s (got %s), excluding 0.",r[0].length.toString(),r[0].length.toString(),s.join(","))):rr(o,n.length,(e,t)=>n[t]>0?r[e][n[t]-1]:r[e][r[e].length+n[t]])},isExported:!0},Un={description:v("Expands or pads an array to specified row and column dimensions."),args:[a("array (any, range<any>)",v("The array to expand.")),a("rows (number)",v("The number of rows in the expanded array. If missing, rows will not be expanded.")),a("columns (number, optional)",v("The number of columns in the expanded array. If missing, columns will not be expanded.")),a("pad_with (any, default=0)",v("The value with which to pad."))],compute:function(e,t,r,n={value:0}){const o=mr(e),s=Bt(t?.value,this.locale),i=void 0!==r?Bt(r.value,this.locale):o.length;return s<o[0].length?new S(v("The rows arguments (%s) must be greater or equal than the number of rows of the array.",s.toString())):i<o.length?new S(v("The columns arguments (%s) must be greater or equal than the number of columns of the array.",i.toString())):rr(i,s,(e,t)=>e>=o.length||t>=o[e].length?n:o[e][t])},isExported:!0},Hn={description:v("Flattens all the values from one or more ranges into a single column."),args:[a("range (any, range<any>, repeating)",v("The range to flatten."))],compute:function(...e){return[pr(e,e=>void 0===e?{value:""}:e)]},isExported:!1},Bn={description:v("Calculates the frequency distribution of a range."),args:[a("data (range<number>)",v("The array of ranges containing the values to be counted.")),a("classes (number, range<number>)",v("The range containing the set of classes."))],compute:function(e,t){const r=pr([e],e=>e.value).filter(e=>"number"==typeof e),n=pr([t],e=>e.value).filter(e=>"number"==typeof e),o=n.map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);o.push({initialIndex:o.length,value:1/0,count:0});const s=r.sort((e,t)=>e-t);let i=0;for(const e of s){for(;e>o[i].value&&i<o.length-1;)i++;o[i].count++}return[o.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},zn={description:v("Appends ranges horizontally and in sequence to return a larger array."),args:[a("range (any, range<any>, repeating)",v("The range to be appended."))],compute:function(...e){return Fn(e)},isExported:!0},$n={description:v("Returns the matrix determinant of a square matrix."),args:[a("square_matrix (number, range<number>)",v("An range with an equal number of rows and columns representing a matrix whose determinant will be calculated."))],compute:function(e){const t=Ut(e,"square_matrix");return Cn(t)?xn(t).determinant:new S(v("The argument square_matrix must have the same number of columns and rows."))},isExported:!0},Gn={description:v("Returns the multiplicative inverse of a square matrix."),args:[a("square_matrix (number, range<number>)",v("An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated."))],compute:function(e){const t=Ut(e,"square_matrix");if(!Cn(t))return new S(v("The argument square_matrix must have the same number of columns and rows."));const{inverted:r}=xn(t);return r||new S(v("The matrix is not invertible."))},isExported:!0},Wn={description:v("Calculates the matrix product of two matrices."),args:[a("matrix1 (number, range<number>)",v("The first matrix in the matrix multiplication operation.")),a("matrix2 (number, range<number>)",v("The second matrix in the matrix multiplication operation."))],compute:function(e,t){const r=Ut(e,"matrix1"),n=Ut(t,"matrix2");return 0===r.length||0===n.length?new S(v("The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.")):r.length!==n[0].length?new S(v("In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).",r.length.toString(),n[0].length.toString())):An(r,n)},isExported:!0},qn={description:v("Calculates the sum of the products of corresponding entries in equal-sized ranges."),args:[a("range (number, range<number>, repeating)",v("The range whose entries will be multiplied with corresponding entries in the other range."))],compute:function(...e){if(!Sn(...e))return new S(v("All the ranges must have the same dimensions."));const t=e.map(mr);let r=0;for(let e=0;e<t[0].length;e++)for(let n=0;n<t[0][e].length;n++){if(!t.every(t=>"number"==typeof t[e][n].value))continue;let o=1;for(const r of t)o*=kt(r[e][n],this.locale);r+=o}return r},isExported:!0};function Zn(e,t,r){if(!Sn(e,t))return new S(v("The arguments array_x and array_y must have the same dimensions."));const n=mr(e),o=mr(t);let s=!1,i=0;for(const e in n)for(const t in n[e]){const a=n[e][t].value,l=o[e][t].value;"number"==typeof a&&"number"==typeof l&&(s=!0,i+=r(a,l))}return s?i:new S(v("The arguments array_x and array_y must contain at least one pair of numbers."))}const Yn={description:v("Calculates the sum of the difference of the squares of the values in two array."),args:[a("array_x (number, range<number>)",v("The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.")),a("array_y (number, range<number>)",v("The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together."))],compute:function(e,t){return Zn(e,t,(e,t)=>e**2-t**2)},isExported:!0},jn={description:v("Calculates the sum of the sum of the squares of the values in two array."),args:[a("array_x (number, range<number>)",v("The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.")),a("array_y (number, range<number>)",v("The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together."))],compute:function(e,t){return Zn(e,t,(e,t)=>e**2+t**2)},isExported:!0},Xn={description:v("Calculates the sum of squares of the differences of values in two array."),args:[a("array_x (number, range<number>)",v("The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.")),a("array_y (number, range<number>)",v("The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together."))],compute:function(e,t){return Zn(e,t,(e,t)=>(e-t)**2)},isExported:!0},Kn=!1,Qn=[a("array (any, range<any>)",v("The array which will be transformed.")),a("ignore (number, default=0)",v("Whether to ignore certain types of values. By default, no values are ignored."),[{value:0,label:v("Keep all values (default)")},{value:1,label:v("Ignore blanks")},{value:2,label:v("Ignore errors")},{value:3,label:v("Ignore blanks and errors")}]),a("scan_by_column (number, default=false)",v("Scan the array by column. By default, the array is scanned by row."),[{value:!1,label:v("Scan by row (default)")},{value:!0,label:v("Scan by column")}])];function Jn(e){const t=Math.trunc(e);if(0===t)return()=>!0;if(1===t)return e=>null!==e.value;if(2===t)return e=>!Vt(e.value);if(3===t)return e=>null!==e.value&&!Vt(e.value);throw new S(v("Argument ignore must be between 0 and 3"))}const eo={description:v("Transforms a range of cells into a single column."),args:Qn,compute:function(e,t={value:0},r={value:Kn}){const n=mr(e),o=kt(t.value,this.locale),s=(qt(r.value)?n:or(n)).flat().filter(Jn(o));return 0===s.length?new x(v("No results for the given arguments of TOCOL.")):[s]},isExported:!0},to={description:v("Transforms a range of cells into a single row."),args:Qn,compute:function(e,t={value:0},r={value:Kn}){const n=mr(e),o=kt(t.value,this.locale),s=(qt(r.value)?n:or(n)).flat().filter(Jn(o)).map(e=>[e]);return 0===s.length||0===s[0].length?new x(v("No results for the given arguments of TOROW.")):s},isExported:!0},ro={description:v("Transposes the rows and columns of a range."),args:[a("range (any, range<any>)",v("The range to be transposed."))],compute:function(e){const t=mr(e);return rr(t[0].length,t.length,(e,r)=>t[r][e])},isExported:!0},no={description:v("Appends ranges vertically and in sequence to return a larger array."),args:[a("range (any, range<any>, repeating)",v("The range to be appended."))],compute:function(...e){return Nn(e)},isExported:!0},oo={description:v("Wraps the provided row or column of cells by columns after a specified number of elements to form a new array."),args:[a("range (any, range<any>)",v("The range to wrap.")),a("wrap_count (number)",v("The maximum number of cells for each column, rounded down to the nearest whole number.")),a("pad_with (any, default=0)",v("The value with which to fill the extra cells in the range."))],compute:function(e,t,r={value:0}){const n=mr(e),o=Bt(t?.value,this.locale);if(!wn(n))return new S(v("Argument range must be a single row or column."));const s=n.flat();return rr(Math.ceil(s.length/o),o,(e,t)=>{const n=e*o+t;return n<s.length?s[n]:r})},isExported:!0},so={description:v("Wraps the provided row or column of cells by rows after a specified number of elements to form a new array."),args:[a("range (any, range<any>)",v("The range to wrap.")),a("wrap_count (number)",v("The maximum number of cells for each row, rounded down to the nearest whole number.")),a("pad_with (any, default=0)",v("The value with which to fill the extra cells in the range."))],compute:function(e,t,r={value:0}){const n=mr(e),o=Bt(t?.value,this.locale);if(!wn(n))return new S(v("Argument range must be a single row or column."));const s=n.flat(),i=Math.ceil(s.length/o);return rr(o,i,(e,t)=>{const n=t*o+e;return n<s.length?s[n]:r})},isExported:!0},io=[{value:0,label:v("Concise format (default)")},{value:1,label:v("Strict format")}],ao={description:v("returns an array of text values from any specified range. It passes text values unchanged, and converts non-text values to text."),args:[a("array (range)",v("The array to convert into text")),a("format (number, default=0)",v("The format of the returned data."),io)],compute:function(e,t={value:0}){const r=kt(t,this.locale),n=mr(e);if(1===r)return function(e,t,r){if(D(e)){const n=","===r.decimalSeparator?"/":",";return`{${or(e).map(e=>e.map(e=>vn(e,t,r)).join(n)).join(";")}}`}return vn(e,t,r)}(n,"",this.locale);if(0===r){const e=","===this.locale.decimalSeparator?"/":",";return or(n).flatMap(e=>e.map(e=>Vt(e.value)?e.value:$t(e))).join(e)}return new S(v("Format must be 0 or 1"))},isExported:!0};var lo=Object.freeze({__proto__:null,ARRAYTOTEXT:ao,ARRAY_CONSTRAIN:Mn,ARRAY_LITERAL:Vn,ARRAY_ROW:Ln,CHOOSECOLS:Pn,CHOOSEROWS:kn,EXPAND:Un,FLATTEN:Hn,FREQUENCY:Bn,HSTACK:zn,MDETERM:$n,MINVERSE:Gn,MMULT:Wn,SUMPRODUCT:qn,SUMX2MY2:Yn,SUMX2PY2:jn,SUMXMY2:Xn,TOCOL:eo,TOROW:to,TRANSPOSE:ro,VSTACK:no,WRAPCOLS:oo,WRAPROWS:so});const co={description:v("Apply a large number format"),args:[a("value (number)",v("The number.")),a("unit (string, optional)",v("The formatting unit. Use 'k', 'm', or 'b' to force the unit"),[{value:"k",label:v("Thousand")},{value:"m",label:v("Million")},{value:"b",label:v("Billion")}])],compute:function(e,t){return{value:kt(e,this.locale),format:hn(e,t,this.locale)}}};var uo=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:co});const ho=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),fo=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),go=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),mo=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),po=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),bo=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),vo=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[ho.source,/(\$?[A-Z]{1,3})?\$?[0-9]{1,7}\s*:\s*(\$?[A-Z]{1,3})?\$?[0-9]{1,7}\s*/i.source,/\$?[A-Z]{1,3}(\$?[0-9]{1,7})?\s*:\s*\$?[A-Z]{1,3}(\$?[0-9]{1,7})?\s*/i.source].join("|")+")"+/$/.source,"i");function yo(e){return po.test(e)}function Eo(e){return bo.test(e)}function wo(e){return go.test(e)}function So(e){return mo.test(e)}function Co(e){return fo.test(e)}function To(e){if(!e.includes("!"))return{xc:e};const t=e.split("!"),r=t.pop();return{sheetName:ne(t.join("!"))||void 0,xc:r}}function Io(e,t){return void 0!==e?`${se(e)}!${t}`:t}function xo(e){switch(function(e){if(function(e){return e.startsWith("$")&&e.length>1&&e.slice(1).includes("$")}(e))return"colrow";if(function(e){return e.startsWith("$")}(e))return"col";if(function(e){return e.includes("$",1)}(e))return"row";return"none"}(e)){case"none":e=Ro(e,"colrow");break;case"colrow":e=Ro(e,"row");break;case"row":e=Ro(e,"col");break;case"col":e=Ro(e,"none")}return e}function Ro(e,t){let r;({sheetName:r,xc:e}=To(e)),r=r?se(r)+"!":"";const n=(e=e.replace(/\$/g,"")).indexOf(":");return n>=0?`${r}${Ao(e.slice(0,n),t)}:${Ao(e.slice(n+1),t)}`:r+Ao(e,t)}function Ao(e,t){const r=e.search(/[0-9]/),n=0!==r,o=r>=0;switch(t){case"col":return n?"$"+e:e;case"row":return o?e.slice(0,r)+"$"+e.slice(r):e;case"colrow":return o&&n?"$"+e.slice(0,r)+"$"+e.slice(r):"$"+e;case"none":return e}}function Oo(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class _o{getCrypto(){if("undefined"!=typeof globalThis&&globalThis.crypto)return globalThis.crypto;if("function"==typeof require)try{const e=require("crypto");if(e.webcrypto)return e.webcrypto}catch(e){}}smallUuid(){const e=this.getCrypto();return e?"10000000-1000".replace(/[01]/g,t=>{const r=Number(t);return(r^e.getRandomValues(new Uint8Array(1))[0]&15>>r/4).toString(16)}):"xxxxxxxx-xxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}uuidv4(){const e=this.getCrypto();return e?"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>{const r=Number(t);return(r^e.getRandomValues(new Uint8Array(1))[0]&15>>r/4).toString(16)}):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}}function Do(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Do(Math.floor(e/26)-1)+Do(e%26)}function Fo(e){const t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function No(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function Mo(e){return e>="0"&&e<="9"}const Vo=function(e){let t=0;const r=e.length;for(let n=0;n<r;n++){t=26*t+Fo(e[n])}return t-1}("ZZZ"),Lo=9999998;function Po(e){for(;" "===e.current;)e.advanceBy(1)}function ko(e){if("$"===e.current&&e.advanceBy(1),!e.current||!No(e.current))return-1;let t=0;for(;e.current&&No(e.current);)t=26*t+Fo(e.shift());return t}function Uo(e){if("$"===e.current&&e.advanceBy(1),!e.current||!Mo(e.current))return-1;let t=0;for(;e.current&&Mo(e.current);)t=10*t+Number(e.shift());return t}function Ho(e){const t=new Ze(e);Po(t);const r=ko(t);if(-1===r||!t.current)throw new Error(`Invalid cell description: ${e}`);const n=Uo(t);Po(t);const o=r-1,s=n-1;if(!t.isOver()||o>Vo||s>Lo)throw new Error(`Invalid cell description: ${e}`);return{col:o,row:s}}function Bo(e,t,r={colFixed:!1,rowFixed:!1}){return(r.colFixed?"$":"")+Do(e)+(r.rowFixed?"$":"")+String(t+1)}function zo(e,t=[]){if(e.length<=1&&0===t.length)return e;const r=[0],n=new Map([[0,[]]]);return $o(r,n,e,!1),$o(r,n,t,!0),Zo(r,n)}function $o(e,t,r,n=!1){for(const o of r){const r=o.left,s=void 0===o.right?void 0:o.right+1,i=Go(e,t,r,!0,0),a=Go(e,t,s,!1,i);for(let r=i;r<=a;r++){Wo(t.get(e[r]),o,n)}qo(e,t,i,a)}}function Go(e,t,r,n,o){if(void 0===r)return e.length-1;const s=Yo(e,r,o);return r!==e[s]?(e.splice(s+1,0,r),t.set(r,[...t.get(e[s])]),n?s+1:s):n?s:s-1}function Wo(e,t,r=!1){const n=t.top,o=void 0===t.bottom?void 0:t.bottom+1,s=[],i=Yo(e,n,0,!1);if((i%2!=0&&!r||i%2==0&&r)&&s.push(n),void 0===o)return e.splice(i+1),void e.push(...s);const a=jo(e,o,0,!1);(a%2==0&&!r||a%2!=0&&r)&&s.push(o);const l=a-i-1,c=s.length,u=i+1;u===e.length-1&&1===l&&1===c?e[u]=s[0]??s[1]:e.splice(u,l,...s)}function qo(e,t,r,n){const o=r-1==-1?0:r-1;for(let r=n===e.length-1?n:n+1;r>o;r--)_e(t.get(e[r]),t.get(e[r-1]))&&(t.delete(e[r]),e.splice(r,1))}function Zo(e,t){const r=[];let n=[];for(let o=0;o<e.length;o++){const s=e[o],i=t.get(s);if(!i||0===i.length){r.push(...n),n=[];continue}let a=e[o+1];void 0!==a&&a--;const l=[];for(let e=0;e<i.length;e+=2){const t=i[e];let r=i[e+1];void 0!==r&&r--;const o={top:t,left:s,bottom:r,right:a};(void 0===r&&0!==t||void 0===a&&0!==s)&&(o.hasHeader=!0);let c=!1;for(let e=n.length-1;e>=0;e--){const t=n[e];if(t.top===o.top&&t.bottom===o.bottom){t.right=o.right,n.splice(e,1),l.push(t),c=!0;break}}c||l.push(o)}r.push(...n),n=l}return r.push(...n),r}function Yo(e,t,r=0,n=!0){let o=e.length-1,s=-1;for(;r<=o;){const i=Math.floor((r+o)/2);if(e[i]===t&&n)return i;e[i]<t?(s=i,r=i+1):o=i-1}return s}function jo(e,t,r=0,n=!0){let o=e.length-1,s=e.length;for(;r<=o;){const i=Math.floor((r+o)/2);if(e[i]===t&&n)return i;e[i]>t?(s=i,o=i-1):r=i+1}return s}function Xo(e){const t=function(e){const t=new Ze(e);Po(t);const r=e.indexOf("!");-1!==r&&t.advanceBy(r+1);const n=ko(t),o=Uo(t);let s,i,a,l,c=!1,u=!1,h=!1;if(-1===o?(a=l=n-1,s=i=0,c=!0):-1===n?(s=i=o-1,a=l=0,u=!0):(a=l=n-1,s=i=o-1,h=!0),Po(t),":"===t.current){t.advanceBy(1),Po(t);const e=ko(t),r=Uo(t);-1===r?(l=e-1,c=!0):-1===e?(i=r-1,u=!0):(l=e-1,i=r-1,s=c?i:s,a=u?l:a,h=!0)}const d={top:s,left:a,bottom:c?void 0:i,right:u?void 0:l};return h=h&&(u||c),h&&(d.hasHeader=h),d}(e),r=gs(t),n=r.bottom,o=r.right;if(void 0!==n&&n>Lo||void 0!==o&&o>Vo)throw new Error(`Range string out of bounds: ${e}`);if(void 0===n&&void 0===o)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");return r}function Ko(e){const t=Xo(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function Qo(e){const{bottom:t,top:r,left:n,right:o}=e;return!(void 0!==t&&isNaN(t)||isNaN(r)||isNaN(n)||void 0!==o&&isNaN(o))&&(Jo(e)&&e.top>=0&&e.left>=0)}function Jo(e){return(void 0===e.bottom||e.bottom>=e.top&&e.bottom>=0)&&(void 0===e.right||e.right>=e.left&&e.right>=0)}function es(e){const{top:t,bottom:r,left:n,right:o}=e,s="hasHeader"in e&&e.hasHeader,i=t===r&&n===o;if(void 0===r&&void 0!==o)return 0!==t||s?`${Bo(n,t)}:${Do(o)}`:`${Do(n)}:${Do(o)}`;if(void 0===o&&void 0!==r)return 0!==n||s?`${Bo(n,t)}:${r+1}`:`${t+1}:${r+1}`;if(void 0!==r&&void 0!==o)return i?Bo(n,t):`${Bo(n,t)}:${Bo(o,r)}`;throw new Error("Bad zone format")}function ts(e,t,r,n,o){const s="left"===t?"columns":"rows",i="before"===n?r-1:r,a="left"===t?"right":"bottom";return e[t]<=i&&e[a]>i?ms(e,s,"RESIZE",o):i<e[t]?ms(e,s,"MOVE",o):{...e}}function rs(e,t,r){const n="left"===t?"right":"bottom";let o=e[t],s=e[n];for(const i of r.sort((e,t)=>t-e))e[t]>i&&(o--,s--),e[t]<i&&e[n]>=i&&s--;return{...e,[t]:o,[n]:s}}function ns(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:Math.max(...e.map(e=>e.bottom)),right:Math.max(...e.map(e=>e.right))}}function os(e,t){if(as(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:void 0!==e.bottom?Math.min(e.bottom,t.bottom):e.bottom??t.bottom,right:void 0!==e.right?Math.min(e.right,t.right):e.right??t.right}}function ss(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom&&e.hasHeader===t.hasHeader}function is(e,t){if(os(e,t))return;let r;return e.left===t.right+1&&(r={position:"left",start:Math.max(e.top,t.top),stop:void 0!==e.bottom?Math.min(e.bottom,t.bottom):t.bottom}),void 0!==e.right&&e.right+1===t.left&&(r={position:"right",start:Math.max(e.top,t.top),stop:void 0!==e.bottom?Math.min(e.bottom,t.bottom):t.bottom}),e.top===t.bottom+1&&(r={position:"top",start:Math.max(e.left,t.left),stop:void 0!==e.right?Math.min(e.right,t.right):t.right}),void 0!==e.bottom&&e.bottom+1===t.top&&(r={position:"bottom",start:Math.max(e.left,t.left),stop:void 0!==e.right?Math.min(e.right,t.right):t.right}),r&&r.start<=r.stop?r:void 0}function as(e,t){return!(void 0!==e.bottom&&e.bottom<t.top||void 0!==t.bottom&&t.bottom<e.top)&&!(void 0!==e.right&&e.right<t.left||void 0!==t.right&&t.right<e.left)}function ls(e,t,r){const{left:n,right:o,top:s,bottom:i}=r;return e>=n&&(void 0===o||e<=o)&&t>=s&&(void 0===i||t<=i)}function cs(e,t){return e.left>=t.left&&e.right<=t.right&&e.top>=t.top&&e.bottom<=t.bottom}function us(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function hs(e){const{numberOfCols:t,numberOfRows:r}=us(e);return 1===t||1===r}function ds(e){const t=[],{left:r,right:n,top:o,bottom:s}=gs(e);for(const e of le(r,n+1))for(const r of le(o,s+1))t.push({col:e,row:r});return t}function fs(e,t){const r=[],{left:n,right:o,top:s,bottom:i}=gs(t);for(const t of le(n,o+1))for(const n of le(s,i+1))r.push({sheetId:e,col:t,row:n});return r}function gs(e){return void 0!==e.right&&e.left>e.right&&(e={...e,left:e.right,right:e.left}),void 0!==e.bottom&&e.top>e.bottom&&(e={...e,top:e.bottom,bottom:e.top}),e}function ms(e,t,r,n){const o="both"===t?n[0]:"columns"===t?n:0,s="both"===t?n[1]:"rows"===t?n:0,i="hasHeader"in e&&e.hasHeader;let a;a=ys(e)&&!i?"rows"!==t:!(vs(e)&&!i)||"columns"!==t;const l={...e};return a&&"MOVE"===r&&(l.left+=o,l.top+=s),void 0!==l.right&&(l.right+=o),void 0!==l.bottom&&(l.bottom+=s),l}function ps(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function bs(e){return{...e,right:e.left,bottom:e.top}}function vs(e){return void 0===e.right}function ys(e){return void 0===e.bottom}function Es(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function ws(e){return e.length<2||1===zo(e).length}function Ss(e,t){const r=is(e,t);if(!r)return[e];const n=[];switch(r.position){case"bottom":case"top":return n.push({top:e.top,bottom:e.bottom,left:r.start,right:r.stop}),r.start>e.left&&n.push({top:e.top,bottom:e.bottom,left:e.left,right:r.start-1}),(void 0===e.right||r.stop<e.right)&&n.push({top:e.top,bottom:e.bottom,left:r.stop+1,right:e.right}),n;case"left":case"right":return n.push({top:r.start,bottom:r.stop,left:e.left,right:e.right}),r.start>e.top&&n.push({top:e.top,bottom:r.start-1,left:e.left,right:e.right}),(void 0===e.bottom||r.stop<e.bottom)&&n.push({top:r.stop+1,bottom:e.bottom,left:e.left,right:e.right}),n}}const Cs=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","DUPLICATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","UNDO","REDO","ADD_MERGE","REMOVE_MERGE","UPDATE_LOCALE","ADD_PIVOT","UPDATE_PIVOT","INSERT_PIVOT","RENAME_PIVOT","REMOVE_PIVOT","DUPLICATE_PIVOT"]),Ts=new Set(["EVALUATE_CELLS","EVALUATE_CHARTS","UPDATE_CELL","UNHIDE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","GROUP_HEADERS","SET_FORMATTING","CLEAR_FORMATTING","UNGROUP_HEADERS","FOLD_ALL_HEADER_GROUPS","FOLD_HEADER_GROUP","FOLD_HEADER_GROUPS_IN_ZONE","UNFOLD_ALL_HEADER_GROUPS","UNFOLD_HEADER_GROUP","UNFOLD_HEADER_GROUPS_IN_ZONE","UPDATE_TABLE","UPDATE_FILTER","UNDO","REDO"]),Is=new Set(["MOVE_RANGES"]),xs=new Set(["EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CHANGE_CONDITIONAL_FORMAT_PRIORITY"]),Rs=new Set(["AUTOFILL_CELL","SET_BORDER","SET_ZONE_BORDERS","SET_BORDERS_ON_TARGET"]),As=new Set(["UNHIDE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","GROUP_HEADERS","UNGROUP_HEADERS","FOLD_ALL_HEADER_GROUPS","FOLD_HEADER_GROUP","FOLD_HEADER_GROUPS_IN_ZONE","UNFOLD_ALL_HEADER_GROUPS","UNFOLD_HEADER_GROUP","UNFOLD_HEADER_GROUPS_IN_ZONE","UPDATE_TABLE","UPDATE_FILTER"]),Os=new Set(["START","ACTIVATE_SHEET","COPY","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","SET_ZOOM","EVALUATE_CELLS","EVALUATE_CHARTS","SET_FORMULA_VISIBILITY","UPDATE_FILTER","UPDATE_CHART","UPDATE_CAROUSEL_ACTIVE_ITEM","UPDATE_PIVOT"]),_s=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","CLEAR_CELLS","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","UNFREEZE_COLUMNS","UNFREEZE_ROWS","FREEZE_COLUMNS","FREEZE_ROWS","UNFREEZE_COLUMNS_ROWS","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","COLOR_SHEET","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CHANGE_CONDITIONAL_FORMAT_PRIORITY","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","CREATE_CAROUSEL","UPDATE_CAROUSEL","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","SET_ZONE_BORDERS","SET_BORDERS_ON_TARGET","CREATE_CHART","UPDATE_CHART","DELETE_CHART","CREATE_TABLE","REMOVE_TABLE","UPDATE_TABLE","CREATE_TABLE_STYLE","REMOVE_TABLE_STYLE","CREATE_IMAGE","GROUP_HEADERS","UNGROUP_HEADERS","UNFOLD_HEADER_GROUP","FOLD_HEADER_GROUP","FOLD_ALL_HEADER_GROUPS","UNFOLD_ALL_HEADER_GROUPS","UNFOLD_HEADER_GROUPS_IN_ZONE","FOLD_HEADER_GROUPS_IN_ZONE","ADD_DATA_VALIDATION_RULE","REMOVE_DATA_VALIDATION_RULE","UPDATE_LOCALE","ADD_PIVOT","UPDATE_PIVOT","INSERT_PIVOT","RENAME_PIVOT","REMOVE_PIVOT","DUPLICATE_PIVOT"]);function Ds(e){return _s.has(e.type)}class Fs{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>"Success"!==e)}static get Success(){return Ns}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}const Ns=new Fs;var Ms;!function(e){e.Success="Success",e.CancelledForUnknownReason="CancelledForUnknownReason",e.WillRemoveExistingMerge="WillRemoveExistingMerge",e.CannotMoveTableHeader="CannotMoveTableHeader",e.MergeIsDestructive="MergeIsDestructive",e.CellIsMerged="CellIsMerged",e.InvalidTarget="InvalidTarget",e.EmptyUndoStack="EmptyUndoStack",e.EmptyRedoStack="EmptyRedoStack",e.NotEnoughElements="NotEnoughElements",e.NotEnoughSheets="NotEnoughSheets",e.MissingSheetName="MissingSheetName",e.UnchangedSheetName="UnchangedSheetName",e.DuplicatedSheetName="DuplicatedSheetName",e.DuplicatedSheetId="DuplicatedSheetId",e.ForbiddenCharactersInSheetName="ForbiddenCharactersInSheetName",e.WrongSheetMove="WrongSheetMove",e.WrongSheetPosition="WrongSheetPosition",e.InvalidAnchorZone="InvalidAnchorZone",e.SelectionOutOfBound="SelectionOutOfBound",e.TargetOutOfSheet="TargetOutOfSheet",e.WrongCutSelection="WrongCutSelection",e.WrongPasteSelection="WrongPasteSelection",e.WrongPasteOption="WrongPasteOption",e.WrongFigurePasteOption="WrongFigurePasteOption",e.EmptyClipboard="EmptyClipboard",e.EmptyRange="EmptyRange",e.InvalidRange="InvalidRange",e.InvalidZones="InvalidZones",e.InvalidSheetId="InvalidSheetId",e.InvalidCellId="InvalidCellId",e.InvalidFigureId="InvalidFigureId",e.InputAlreadyFocused="InputAlreadyFocused",e.MaximumRangesReached="MaximumRangesReached",e.MinimumRangesReached="MinimumRangesReached",e.InvalidChartDefinition="InvalidChartDefinition",e.InvalidDataSet="InvalidDataSet",e.InvalidLabelRange="InvalidLabelRange",e.InvalidScorecardKeyValue="InvalidScorecardKeyValue",e.InvalidScorecardBaseline="InvalidScorecardBaseline",e.InvalidGaugeDataRange="InvalidGaugeDataRange",e.EmptyGaugeRangeMin="EmptyGaugeRangeMin",e.GaugeRangeMinNaN="GaugeRangeMinNaN",e.EmptyGaugeRangeMax="EmptyGaugeRangeMax",e.GaugeRangeMaxNaN="GaugeRangeMaxNaN",e.GaugeLowerInflectionPointNaN="GaugeLowerInflectionPointNaN",e.GaugeUpperInflectionPointNaN="GaugeUpperInflectionPointNaN",e.InvalidAutofillSelection="InvalidAutofillSelection",e.MinBiggerThanMax="MinBiggerThanMax",e.LowerBiggerThanUpper="LowerBiggerThanUpper",e.MidBiggerThanMax="MidBiggerThanMax",e.MinBiggerThanMid="MinBiggerThanMid",e.FirstArgMissing="FirstArgMissing",e.SecondArgMissing="SecondArgMissing",e.MinNaN="MinNaN",e.MidNaN="MidNaN",e.MaxNaN="MaxNaN",e.ValueUpperInflectionNaN="ValueUpperInflectionNaN",e.ValueLowerInflectionNaN="ValueLowerInflectionNaN",e.MinInvalidFormula="MinInvalidFormula",e.MidInvalidFormula="MidInvalidFormula",e.MaxInvalidFormula="MaxInvalidFormula",e.ValueUpperInvalidFormula="ValueUpperInvalidFormula",e.ValueLowerInvalidFormula="ValueLowerInvalidFormula",e.InvalidSortAnchor="InvalidSortAnchor",e.InvalidSortZone="InvalidSortZone",e.SortZoneWithArrayFormulas="SortZoneWithArrayFormulas",e.WaitingSessionConfirmation="WaitingSessionConfirmation",e.MergeOverlap="MergeOverlap",e.TooManyHiddenElements="TooManyHiddenElements",e.Readonly="Readonly",e.InvalidViewportSize="InvalidViewportSize",e.InvalidScrollingDirection="InvalidScrollingDirection",e.ViewportScrollLimitsReached="ViewportScrollLimitsReached",e.FigureDoesNotExist="FigureDoesNotExist",e.InvalidConditionalFormatId="InvalidConditionalFormatId",e.InvalidCellPopover="InvalidCellPopover",e.EmptyTarget="EmptyTarget",e.InvalidFreezeQuantity="InvalidFreezeQuantity",e.FrozenPaneOverlap="FrozenPaneOverlap",e.ValuesNotChanged="ValuesNotChanged",e.InvalidFilterZone="InvalidFilterZone",e.TableNotFound="TableNotFound",e.TableOverlap="TableOverlap",e.InvalidTableConfig="InvalidTableConfig",e.InvalidTableStyle="InvalidTableStyle",e.FilterNotFound="FilterNotFound",e.MergeInTable="MergeInTable",e.NonContinuousTargets="NonContinuousTargets",e.DuplicatedFigureId="DuplicatedFigureId",e.InvalidSelectionStep="InvalidSelectionStep",e.DuplicatedChartId="DuplicatedChartId",e.ChartDoesNotExist="ChartDoesNotExist",e.InvalidHeaderIndex="InvalidHeaderIndex",e.InvalidQuantity="InvalidQuantity",e.MoreThanOneColumnSelected="MoreThanOneColumnSelected",e.EmptySplitSeparator="EmptySplitSeparator",e.SplitWillOverwriteContent="SplitWillOverwriteContent",e.NoSplitSeparatorInSelection="NoSplitSeparatorInSelection",e.NoActiveSheet="NoActiveSheet",e.InvalidLocale="InvalidLocale",e.MoreThanOneRangeSelected="MoreThanOneRangeSelected",e.NoColumnsProvided="NoColumnsProvided",e.ColumnsNotIncludedInZone="ColumnsNotIncludedInZone",e.DuplicatesColumnsSelected="DuplicatesColumnsSelected",e.InvalidHeaderGroupStartEnd="InvalidHeaderGroupStartEnd",e.HeaderGroupAlreadyExists="HeaderGroupAlreadyExists",e.UnknownHeaderGroup="UnknownHeaderGroup",e.UnknownDataValidationRule="UnknownDataValidationRule",e.UnknownDataValidationCriterionType="UnknownDataValidationCriterionType",e.InvalidDataValidationCriterionValue="InvalidDataValidationCriterionValue",e.InvalidNumberOfCriterionValues="InvalidNumberOfCriterionValues",e.InvalidCopyPasteSelection="InvalidCopyPasteSelection",e.NoChanges="NoChanges",e.InvalidInputId="InvalidInputId",e.SheetIsHidden="SheetIsHidden",e.InvalidTableResize="InvalidTableResize",e.PivotIdNotFound="PivotIdNotFound",e.PivotIdTaken="PivotIdTaken",e.PivotInError="PivotInError",e.EmptyName="EmptyName",e.ValueCellIsInvalidFormula="ValueCellIsInvalidFormula",e.InvalidDefinition="InvalidDefinition",e.InvalidColor="InvalidColor",e.InvalidPivotDataSet="InvalidPivotDataSet",e.InvalidPivotCustomField="InvalidPivotCustomField",e.MissingFigureArguments="MissingFigureArguments",e.InvalidCarouselItem="InvalidCarouselItem"}(Ms||(Ms={}));class Vs{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return"Success"}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(const r of e){let e=r.call(this,t);Array.isArray(e)||(e=[e]);const n=e.filter(e=>"Success"!==e);if(n.length)return n}return"Success"}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class Ls extends Vs{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:r,canDispatch:n,uiActions:o,selection:s}){super(t),this.getters=e,this.ui=o,this.selection=s,this.dispatch=r,this.canDispatch=n}drawLayer(e,t){}}function Ps(e){return e.isFormula&&e.compiledFormula.tokens.some(e=>"SYMBOL"===e.type&&"SUBTOTAL"===e.value.toUpperCase())}function ks(e,t){return er(e,(e,t)=>e+t,0,t)}function Us(e){return Jt(e,(e,t)=>br(t)?e.add(t?.value):e,new Set).size}const Hs=/^-?[a-z0-9]+$/i,Bs={description:v("Absolute value of a number."),args:[a("value (number)",v("The number of which to return the absolute value."))],compute:function(e){return Math.abs(kt(e,this.locale))},isExported:!0},zs={description:v("Inverse cosine of a value, in radians."),args:[a("value (number)",v("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)>1?new S(v("The value (%s) must be between -1 and 1 inclusive.",t)):Math.acos(t)},isExported:!0},$s={description:v("Inverse hyperbolic cosine of a number."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],compute:function(e){const t=kt(e,this.locale);return t<1?new S(v("The value (%s) must be greater than or equal to 1.",t)):Math.acosh(t)},isExported:!0},Gs={description:v("Inverse cotangent of a value."),args:[a("value (number)",v("The value for which to calculate the inverse cotangent."))],compute:function(e){const t=kt(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Ws={description:v("Inverse hyperbolic cotangent of a value."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)<=1?new S(v("The value (%s) cannot be between -1 and 1 inclusive.",t)):Math.log((t+1)/(t-1))/2},isExported:!0},qs={description:v("Inverse sine of a value, in radians."),args:[a("value (number)",v("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)>1?new S(v("The value (%s) must be between -1 and 1 inclusive.",t)):Math.asin(t)},isExported:!0},Zs={description:v("Inverse hyperbolic sine of a number."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic sine."))],compute:function(e){return Math.asinh(kt(e,this.locale))},isExported:!0},Ys={description:v("Inverse tangent of a value, in radians."),args:[a("value (number)",v("The value for which to calculate the inverse tangent."))],compute:function(e){return Math.atan(kt(e,this.locale))},isExported:!0},js={description:v("Angle from the X axis to a point (x,y), in radians."),args:[a("x (number)",v("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),a("y (number)",v("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],compute:function(e,t){const r=kt(e,this.locale),n=kt(t,this.locale);return 0===r&&0===n?new O(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):Math.atan2(n,r)},isExported:!0},Xs={description:v("Inverse hyperbolic tangent of a number."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)>=1?new S(v("The value (%s) must be between -1 and 1 exclusive.",t)):Math.atanh(t)},isExported:!0},Ks={description:v("Rounds number up to nearest multiple of factor."),args:[a("value (number)",v("The value to round up to the nearest integer multiple of factor.")),a("factor (number, default=1)",v("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const r=kt(e,this.locale),n=kt(t,this.locale);return n<0&&r>0?new S(v("The factor (%s) must be positive when the value (%s) is positive.",n,r)):{value:n?Math.ceil(r/n)*n:0,format:e?.format}},isExported:!0};function Qs(e,t,r=0){return 0===t?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:0===r?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}const Js={description:v("Rounds number up to nearest multiple of factor."),args:[a("number (number)",v("The value to round up to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),a("mode (number, default=0)",v("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero."))],compute:function(e,t={value:1},r={value:0}){const n=kt(t,this.locale);return{value:Qs(kt(e,this.locale),n,kt(r,this.locale)),format:e?.format}},isExported:!0},ei={description:v("Rounds number up to nearest multiple of factor."),args:[a("number (number)",v("The value to round up to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const r=kt(t,this.locale);return{value:Qs(kt(e,this.locale),r),format:e?.format}},isExported:!0},ti={description:v("Cosine of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the cosine of, in radians."))],compute:function(e){return Math.cos(kt(e,this.locale))},isExported:!0},ri={description:v("Hyperbolic cosine of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic cosine of."))],compute:function(e){return Math.cosh(kt(e,this.locale))},isExported:!0},ni={description:v("Cotangent of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the cotangent of, in radians."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new O(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tan(t)},isExported:!0},oi={description:v("Hyperbolic cotangent of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic cotangent of."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new O(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tanh(t)},isExported:!0},si={description:v("Number of empty values."),args:[a("value (any, range, repeating)",v("Value or range in which to count the number of blanks."))],compute:function(...e){return Jt(e,(e,t)=>void 0===t||null===t.value||""===t.value?e+1:e,0)},isExported:!0},ii={description:v("A conditional count across a range."),args:[a("range (range)",v("The range that is tested against criterion.")),a("criterion (string)",v("The pattern or test to apply to range."))],compute:function(...e){let t=0;return ur(e,(e,r)=>{t+=1},this.locale),t},isExported:!0},ai={description:v("Count values depending on multiple criteria."),args:[a("criteria_range (any, range, repeating)",v("Range over which to evaluate criteria.")),a("criterion (string, repeating)",v("Criteria to check."))],compute:function(...e){let t=0;return ur(e,(e,r)=>{t+=1},this.locale),t},isExported:!0},li={description:v("Counts number of unique values in a range."),args:[a("value (any, range, repeating)",v("Value or range to consider for uniqueness."))],compute:function(...e){return Us(e)}},ci={description:v("Counts number of unique values in a range, filtered by a set of criteria."),args:[a("range (range)",v("The range of cells from which the number of unique values will be counted.")),a("criteria_range (any, range, repeating)",v("Range over which to evaluate criteria.")),a("criterion (string, repeating)",v("Criteria to check."))],compute:function(e,...t){const r=new Set;return ur(t,(t,n)=>{const o=e[t]?.[n];br(o)&&r.add(o.value)},this.locale),r.size}},ui={description:v("Cosecant of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the cosecant of, in radians."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new O(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sin(t)},isExported:!0},hi={description:v("Hyperbolic cosecant of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic cosecant of."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new O(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sinh(t)},isExported:!0},di={description:v("Converts from another base to decimal."),args:[a("value (string)",v("The number to convert.")),a("base (number)",v("The base to convert the value from."))],compute:function(e,t){let r=kt(t,this.locale);if(r=Math.floor(r),2>r||r>36)return new S(v("The base (%s) must be between 2 and 36 inclusive.",r));const n=$t(e);if(""===n)return 0;if(!Hs.test(n))return new S(v("The value (%s) must be a valid base %s representation.",n,r));const o=parseInt(n,r);return isNaN(o)?new S(v("The value (%s) must be a valid base %s representation.",n,r)):o},isExported:!0},fi={description:v("Converts an angle value in radians to degrees."),args:[a("angle (number)",v("The angle to convert from radians to degrees."))],compute:function(e){return 180*kt(e,this.locale)/Math.PI},isExported:!0},gi={description:v("Euler's number, e (~2.718) raised to a power."),args:[a("value (number)",v("The exponent to raise e."))],compute:function(e){return Math.exp(kt(e,this.locale))},isExported:!0},mi={description:v("Rounds number down to nearest multiple of factor."),args:[a("value (number)",v("The value to round down to the nearest integer multiple of factor.")),a("factor (number, default=1)",v("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const r=kt(e,this.locale),n=kt(t,this.locale);return n<0&&r>0?new S(v("The factor (%s) must be positive when the value (%s) is positive.",n,r)):{value:n?Math.floor(r/n)*n:0,format:e?.format}},isExported:!0};function pi(e,t,r=0){return 0===t?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:0===r?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}const bi={description:v("Rounds number down to nearest multiple of factor."),args:[a("number (number)",v("The value to round down to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),a("mode (number, default=0)",v("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero."))],compute:function(e,t={value:1},r={value:0}){const n=kt(t,this.locale);return{value:pi(kt(e,this.locale),n,kt(r,this.locale)),format:e?.format}},isExported:!0},vi={description:v("Rounds number down to nearest multiple of factor."),args:[a("number (number)",v("The value to round down to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const r=kt(t,this.locale);return{value:pi(kt(e,this.locale),r),format:e?.format}},isExported:!0},yi={description:v("Whether the provided value is even."),args:[a("value (number)",v("The value to be verified as even."))],compute:function(e){const t=Ht(e,this.locale);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Ei={description:v("Rounds number up to nearest multiple of factor."),args:[a("number (number)",v("The value to round up to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){return{value:Qs(kt(e,this.locale),kt(t,this.locale)),format:e?.format}},isExported:!0},wi={description:v("Whether the provided value is even."),args:[a("value (number)",v("The value to be verified as even."))],compute:function(e){const t=Ht(e,this.locale);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Si={description:v("The logarithm of a number, base e (euler's number)."),args:[a("value (number)",v("The value for which to calculate the logarithm, base e."))],compute:function(e){const t=kt(e,this.locale);return t<=0?new S(v("The value (%s) must be strictly positive.",t)):Math.log(t)},isExported:!0},Ci={description:v("The logarithm of a number, for a given base."),args:[a("value (number)",v("The value for which to calculate the logarithm.")),a("base (number, default=10)",v("The base of the logarithm."))],compute:function(e,t={value:10}){const r=kt(e,this.locale),n=kt(t,this.locale);return r<=0?new S(v("The value (%s) must be strictly positive.",r)):n<=0?new S(v("The base (%s) must be strictly positive.",n)):1===n?new S(v("The base must be different from 1.")):Math.log10(r)/Math.log10(n)},isExported:!0};function Ti(e,t){En(t,v("The divisor must be different from 0."));const r=e%t;return r>0&&t<0||r<0&&t>0?r+t:r}const Ii={description:v("Modulo (remainder) operator."),args:[a("dividend (number)",v("The number to be divided to find the remainder.")),a("divisor (number)",v("The number to divide by."))],compute:function(e,t){const r=kt(t,this.locale);return{value:Ti(kt(e,this.locale),r),format:e?.format}},isExported:!0},xi={description:v("Returns a n x n unit matrix, where n is the input dimension."),args:[a("dimension (number)",v("An integer specifying the dimension size of the unit matrix. It must be positive."))],compute:function(e){const t=Bt(e,this.locale);return t<1?new S(v("The argument dimension must be positive")):In(t)},isExported:!0},Ri={description:v("Rounds a number up to the nearest odd integer."),args:[a("value (number)",v("The value to round to the next greatest odd number."))],compute:function(e){const t=kt(e,this.locale);let r=Math.ceil(Math.abs(t));return r=1&r?r:r+1,{value:t<0?-r:r,format:e?.format}},isExported:!0},Ai={description:v("The number pi."),args:[],compute:function(){return Math.PI},isExported:!0},Oi={description:v("A number raised to a power."),args:[a("base (number)",v("The number to raise to the exponent power.")),a("exponent (number)",v("The exponent to raise base to."))],compute:function(e,t){const r=kt(e,this.locale),n=kt(t,this.locale);return r<0&&!Number.isInteger(n)?new S(v("The exponent (%s) must be an integer when the base is negative.",n)):{value:Math.pow(r,n),format:e?.format}},isExported:!0},_i={description:v("Result of multiplying a series of numbers together."),args:[a("factor (number, range<number>, repeating)",v("Number or range to calculate for the product."))],compute:function(...e){let t=0,r=1;for(const n of e)if(D(n))for(const e of n)for(const n of e){const e=n.value;if("number"==typeof e&&(r*=e,t+=1),Vt(e))return n}else void 0!==n&&null!==n.value&&(r*=Ht(n,this.locale),t+=1);return{value:0===t?0:r,format:Mt(e[0])}},isExported:!0},Di={description:v("A random number between 0 inclusive and 1 exclusive."),args:[],compute:function(){return Math.random()},isExported:!0},Fi={description:v("Returns a grid of random numbers between 0 inclusive and 1 exclusive."),args:[a("rows (number, default=1)",v("The number of rows to be returned.")),a("columns (number, default=1)",v("The number of columns to be returned.")),a("min (number, default=0)",v("The minimum number you would like returned.")),a("max (number, default=1)",v("The maximum number you would like returned.")),a("whole_number (boolean, default=FALSE)",v("Return a whole number or a decimal value."),[{value:!1,label:v("Decimal (default)")},{value:!0,label:v("Integer")}])],compute:function(e={value:1},t={value:1},r={value:0},n={value:1},o={value:!1}){const s=Bt(t,this.locale),i=Bt(e,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=qt(o);if(s<1)return new S(v("The number of columns (%s) must be positive.",s));if(i<1)return new S(v("The number of rows (%s) must be positive.",i));if(a>l)return new S(v("The maximum (%s) must be greater than or equal to the minimum (%s).",l,a));if(c&&(!Number.isInteger(a)||!Number.isInteger(l)))return new S(v("The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.",l.toString(),a.toString()));const u=Array(s);for(let e=0;e<s;e++){u[e]=Array(i);for(let t=0;t<i;t++)u[e][t]=c?Math.floor(Math.random()*(l-a+1)+a):a+Math.random()*(l-a)}return u},isExported:!0},Ni={description:v("Random integer between two values, inclusive."),args:[a("low (number)",v("The low end of the random range.")),a("high (number)",v("The high end of the random range."))],compute:function(e,t){let r=kt(e,this.locale);Number.isInteger(r)||(r=Math.ceil(r));let n=kt(t,this.locale);return Number.isInteger(n)||(n=Math.floor(n)),r>n?new S(v("The high (%s) must be greater than or equal to the low (%s).",n,r)):{value:r+Math.ceil((n-r+1)*Math.random())-1,format:e?.format}},isExported:!0},Mi={description:v("Rounds a number according to standard rules."),args:[a("value (number)",v("The value to round to places number of places.")),a("places (number, default=0)",v("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const r=kt(e,this.locale);let n=kt(t,this.locale);const o=Math.abs(r);let s;return 0===n?s=Math.round(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.round(o*Math.pow(10,n))/Math.pow(10,n)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},Vi={description:v("Rounds down a number."),args:[a("value (number)",v("The value to round to places number of places, always rounding down.")),a("places (number, default=0)",v("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const r=kt(e,this.locale);let n=kt(t,this.locale);const o=Math.abs(r);let s;return 0===n?s=Math.floor(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.floor(o*Math.pow(10,n))/Math.pow(10,n)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},Li={description:v("Rounds up a number."),args:[a("value (number)",v("The value to round to places number of places, always rounding up.")),a("places (number, default=0)",v("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const r=kt(e,this.locale);let n=kt(t,this.locale);const o=Math.abs(r);let s;return 0===n?s=Math.ceil(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.ceil(o*Math.pow(10,n))/Math.pow(10,n)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},Pi={description:v("Secant of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the secant of, in radians."))],compute:function(e){return 1/Math.cos(kt(e,this.locale))},isExported:!0},ki={description:v("Hyperbolic secant of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic secant of."))],compute:function(e){return 1/Math.cosh(kt(e,this.locale))},isExported:!0},Ui={description:v("Returns a sequence of numbers."),args:[a("rows (number)",v("The number of rows to return")),a("columns (number, optional, default=1)",v("The number of columns to return")),a("start (number, optional, default=1)",v("The first number in the sequence")),a("step (number, optional, default=1)",v("The amount to increment each value in the sequence"))],compute:function(e,t={value:1},r={value:1},n={value:1}){const o=kt(r,this.locale),s=kt(n,this.locale),i=Bt(e,this.locale),a=Bt(t,this.locale);return a<1?new S(v("The number of columns (%s) must be positive.",a)):i<1?new S(v("The number of rows (%s) must be positive.",i)):rr(a,i,(e,t)=>({value:o+t*a*s+e*s}))},isExported:!0},Hi={description:v("Sine of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the sine of, in radians."))],compute:function(e){return Math.sin(kt(e,this.locale))},isExported:!0},Bi={description:v("Hyperbolic sine of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic sine of."))],compute:function(e){return Math.sinh(kt(e,this.locale))},isExported:!0},zi={description:v("Positive square root of a positive number."),args:[a("value (number)",v("The number for which to calculate the positive square root."))],compute:function(e){const t=kt(e,this.locale);return t<0?new S(v("The value (%s) must be positive or null.",t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},$i={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP"},Gi=Object.entries($i).map(([e,t])=>({value:parseInt(e),label:v("%s (include manually-hidden rows)",t)})),Wi=Object.entries($i).map(([e,t])=>({value:parseInt(e)+100,label:v("%s (exclude manually-hidden rows)",t)})),qi={description:v("Returns a subtotal for a vertical range of cells using a specified aggregation function."),args:[a("function_code (number)",v("The function to use in subtotal aggregation."),[...Gi,...Wi]),a("ref (meta, range<meta>, repeating)",v("Range or reference for which you want the subtotal."))],compute:function(e,...t){let r=Bt(e,this.locale),n=!0;if(r>100&&(r-=100,n=!1),r<1||r>11)return new S(v("The function code (%s) must be between 1 to 11 or 101 to 111.",r));const o=[];for(const e of t){const t=e[0][0],r=To(t.value).sheetName,s=r?this.getters.getSheetIdByName(r):this.__originSheetId;if(!s)continue;const{top:i,left:a}=Ko(t.value),l=a+e.length-1,c=i+e[0].length-1;for(let e=i;e<=c;e++)if(!this.getters.isRowFiltered(s,e)&&(n||!this.getters.isRowHiddenByUser(s,e)))for(let t=a;t<=l;t++){const r=this.getters.getCorrespondingFormulaCell({sheetId:s,col:t,row:e});r&&Ps(r)||o.push(this.getters.getEvaluatedCell({sheetId:s,col:t,row:e}))}}return this[$i[r]].apply(this,[[o]])},isExported:!0},Zi={description:v("Sum of a series of numbers and/or cells."),args:[a("value (number, range<number>, repeating)",v("Number or range to add together."))],compute:function(...e){const t=e[0];return{value:ks(e,this.locale),format:Mt(t)}},isExported:!0},Yi={description:v("A conditional sum across a range."),args:[a("criteria_range (range)",v("The range which is tested against criterion.")),a("criterion (string)",v("The pattern or test to apply to range.")),a("sum_range (range, default=criteria_range)",v("The range to be summed, if different from range."))],compute:function(e,t,r){void 0===r&&(r=e);let n=0;return ur([e,t],(e,t)=>{const o=r[e]?.[t]?.value;"number"==typeof o&&(n+=o)},this.locale),n},isExported:!0},ji={description:v("Sums a range depending on multiple criteria."),args:[a("sum_range (range)",v("The range to sum.")),a("criteria_range (any, range, repeating)",v("Range to check.")),a("criterion (string, repeating)",v("Criteria to check."))],compute:function(e,...t){let r=0;return ur(t,(t,n)=>{const o=e[t]?.[n]?.value;"number"==typeof o&&(r+=o)},this.locale),r},isExported:!0},Xi={description:v("Tangent of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the tangent of, in radians."))],compute:function(e){return Math.tan(kt(e,this.locale))},isExported:!0},Ki={description:v("Hyperbolic tangent of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic tangent of."))],compute:function(e){return Math.tanh(kt(e,this.locale))},isExported:!0};function Qi(e,t){return 0===t?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*Math.pow(10,t))/Math.pow(10,t))}const Ji={description:v("Truncates a number."),args:[a("value (number)",v("The value to be truncated.")),a("places (number, default=0)",v("The number of significant digits to the right of the decimal point to retain."))],compute:function(e,t={value:0}){return{value:Qi(kt(e,this.locale),kt(t,this.locale)),format:e?.format}},isExported:!0},ea={description:v("Rounds a number down to the nearest integer that is less than or equal to it."),args:[a("value (number)",v("The number to round down to the nearest integer."))],compute:function(e){return Math.floor(kt(e,this.locale))},isExported:!0};var ta=Object.freeze({__proto__:null,ABS:Bs,ACOS:zs,ACOSH:$s,ACOT:Gs,ACOTH:Ws,ASIN:qs,ASINH:Zs,ATAN:Ys,ATAN2:js,ATANH:Xs,CEILING:Ks,CEILING_MATH:Js,CEILING_PRECISE:ei,COS:ti,COSH:ri,COT:ni,COTH:oi,COUNTBLANK:si,COUNTIF:ii,COUNTIFS:ai,COUNTUNIQUE:li,COUNTUNIQUEIFS:ci,CSC:ui,CSCH:hi,DECIMAL:di,DEGREES:fi,EXP:gi,FLOOR:mi,FLOOR_MATH:bi,FLOOR_PRECISE:vi,INT:ea,ISEVEN:yi,ISODD:wi,ISO_CEILING:Ei,LN:Si,LOG:Ci,MOD:Ii,MUNIT:xi,ODD:Ri,PI:Ai,POWER:Oi,PRODUCT:_i,RAND:Di,RANDARRAY:Fi,RANDBETWEEN:Ni,ROUND:Mi,ROUNDDOWN:Vi,ROUNDUP:Li,SEC:Pi,SECH:ki,SEQUENCE:Ui,SIN:Hi,SINH:Bi,SQRT:zi,SUBTOTAL:qi,SUM:Zi,SUMIF:Yi,SUMIFS:ji,TAN:Xi,TANH:Ki,TRUNC:Ji});function ra(...e){const t=e[0].length;e.forEach((e,r)=>yn(e.length===t,v("[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).",r.toString(),t.toString(),e.length.toString())))}function na(e,t){let r=0;const n=er(e,(e,t)=>(r+=1,e+t),0,t);return En(r),n/r}function oa(e){return Jt(e,(e,t)=>void 0!==t&&null!==t.value?e+1:e,0)}function sa(e,t){let r={value:-1/0};return Kt(e,e=>{e.value>=r.value&&(r=e)},t),r.value===-1/0?{value:0}:r}function ia(e,t){let r={value:1/0};return Kt(e,e=>{e.value<=r.value&&(r=e)},t),r.value===1/0?{value:0}:r}function aa(e,t,r){const n=e[0].length?e:[le(1,t.flat().length+1)],o=n.length;let s=r[0].length?r:n;return s=s.length===o?or(s):s,{_X:n,_newX:s}}function la(e,t,r=!0,n=!1){const o=t.flat(),s=o.length;let{_X:i}=aa(e,t,[[]]);i=i.length===s?or(i):i.slice(),ra(i[0],o);const a=i.length,l=s-a-(r?1:0),c=[o],u=or(i.reverse()),h=[];for(let e=0;e<a;e++)if(h.push(0),r){for(const t of i[e])h[e]+=t;h[e]/=s}let d=0;if(r){for(const e of o)d+=e;d/=s}const f=u.map(e=>e.map((e,t)=>e-h[t]));r&&u.forEach(e=>e.push(1));const g=ua(u,c);if(r||g.push([0]),!n)return g;const m=An(f,or(f)),{inverted:p}=xn(m);if(void 0===p)throw new S(v("Matrix is not invertible"));let b=0,y=0;for(let e=0;e<s;e++){const t=o[e]-d;let r=0;for(let t=0;t<a;t++){r+=f[e][t]*g[t][0]}const n=t-r;b+=n*n,y+=r*r}const E=Math.sqrt(b/l),w=y/(y+b),C=y/a/(b/l),T=[];for(let e=0;e<a;e++)T.push(E*Math.sqrt(p[e][e]));if(r){const e=An(p,[h]),t=An(or([h]),e);T.push(E*Math.sqrt(t[0][0]+1/o.length))}const I=[[g[0][0],T[0],w,C,y],[g[1][0],T[1],E,l,b]];for(let e=2;e<a;e++)I.push([g[e][0],T[e],"","",""]);return r?I.push([g[a][0],T[a],"","",""]):I.push([0,"","","",""]),I}function ca(e,t,r,n){ra(t,e),yn(r>=1,v("Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible."));const o=[e],s=t.map(e=>le(0,r).map(t=>Math.pow(e,r-t)));n&&s.forEach(e=>e.push(1));const i=ua(s,o);return n||i.push([0]),i}function ua(e,t){const r=An(e,or(e)),{inverted:n}=xn(r);if(void 0===n)throw new S(v("Matrix is not invertible"));const o=An(e,t);return or(An(n,o))}function ha(e){return e.map(e=>e.map(e=>Math.log(e)))}function da(e,t,r,n){const{_X:o,_newX:s}=aa(t,e,r),i=la(o,e,n,!1),a=i.length-1,l=s.map(e=>{let t=0;for(let r=0;r<a;r++)t+=i[r][0]*e[a-r-1];return t+=i[a][0],[t]});return l.length===r.length?l:or(l)}const fa=[{value:!0,label:v("b is calculated normally")},{value:!1,label:v("b is forced to 1")}],ga=[{value:!1,label:v("do not return additional regression statistics")},{value:!0,label:v("return additional regression statistics")}],ma=[{value:1,label:v("order 1 (Linear)")},{value:2,label:v("order 2 (Quadratic)")},{value:3,label:v("order 3 (Cubic)")},{value:4,label:v("order 4 (Quartic)")},{value:5,label:v("order 5 (Quintic)")},{value:6,label:v("order 6 (Sextic)")}],pa=[{value:!0,label:v("Compute intercept")},{value:!1,label:v("Force intercept to 0")}],ba=[{value:0,label:v("Minimum value")},{value:1,label:v("First quartile (25th percentile)")},{value:2,label:v("Median value (50th percentile)")},{value:3,label:v("Third quartile (75th percentile)")},{value:4,label:v("Maximum value")}];function va(e,t){const r=[],n=[];let o=0,s=0;Xt([e],e=>{r.push(e),o+=1}),Xt([t],e=>{n.push(e),s+=1}),yn(o===s,v("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",o,s));const i=[],a=[];for(let e=0;e<o;e++){const t=r[e]?.value,o=n[e]?.value;"number"==typeof t&&"number"==typeof o&&(a.push(t),i.push(o))}return{flatDataX:i,flatDataY:a}}function ya(e,t,r){const{flatDataX:n,flatDataY:o}=va(e,t),s=o.length;En(s),r&&En(s-1);let i=0,a=0;for(let e=0;e<s;e++)i+=o[e],a+=n[e];const l=i/s,c=a/s;let u=0;for(let e=0;e<s;e++)u+=(o[e]-l)*(n[e]-c);return u/(s-(r?1:0))}function Ea(e,t,r,n){let o=0;const s=r?tr:er,i=s(e,(e,t)=>(o+=1,e+t),0,n);En(o),t&&En(o-1);const a=i/o;return s(e,(e,t)=>e+Math.pow(t-a,2),0,n)/(o-(t?1:0))}function wa(e,t,r,n){const o=kt(t,n);yn(r?0<=o&&o<=1:0<o&&o<1,v("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));const s=[];let i,a=0;return Xt(e,e=>{const t=e?.value;"number"==typeof t&&(i=hr(s,e,"nextSmaller","asc",s.length,(e,t)=>e[t]),s.splice(i+1,0,t),a++)}),yn(0!==a,vr),r||yn(1/(a+1)<=o&&o<=a/(a+1),v("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),Ft(s,o,r)}const Sa={description:v("Average magnitude of deviations from mean."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the sample."))],compute:function(...e){let t=0;const r=er(e,(e,r)=>(t+=1,e+r),0,this.locale);if(0===t)return new O(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const n=r/t;return er(e,(e,t)=>e+Math.abs(n-t),0,this.locale)/t},isExported:!0},Ca={description:v("Numerical average value in a dataset, ignoring text."),args:[a("value (number, range<number>, repeating)",v("Value or range to consider when calculating the average value."))],compute:function(...e){return{value:na(e,this.locale),format:Mt(e[0])}},isExported:!0},Ta=v("[[FUNCTION_NAME]] has mismatched range sizes."),Ia=v("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),xa={description:v("Weighted average."),args:[a("values (number, range<number>, repeating)",v("Value to average.")),a("weights (number, range<number>, repeating)",v("Weight for each corresponding value."))],compute:function(...e){let t=0,r=0;for(let n=0;n<e.length-1;n+=2){const o=e[n],s=e[n+1];if(!Sn(o,s))return new S(Ta);if(D(o))for(let e=0;e<o.length;e++)for(let n=0;n<o[0].length;n++){const i=o[e][n].value,a=D(s)?s?.[e][n].value:kt(s,this.locale),l="number"==typeof i,c="number"==typeof a;if(l&&c){if(a<0)return new S(Ia);t+=i*a,r+=a}else if(l!==c)return new S(v("[[FUNCTION_NAME]] expects number values."))}else{const e=kt(o,this.locale),n=D(s)?s?.[0][0].value:kt(s,this.locale);if("number"==typeof n){if(n<0)return new S(Ia);t+=e*n,r+=n}}}return 0===r?new O(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:t/r,format:Mt(e[0])}}},Ra={description:v("Numerical average value in a dataset."),args:[a("value (number, range<number>, repeating)",v("Value or range to consider when calculating the average value."))],compute:function(...e){let t=0;const r=tr(e,(e,r)=>(t+=1,e+r),0,this.locale);return 0===t?new O(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:r/t,format:Mt(e[0])}},isExported:!0},Aa={description:v("Average of values depending on criteria."),args:[a("criteria_range (number, range<number>)",v("The range to check against criterion.")),a("criterion (string)",v("The pattern or test to apply to criteria_range.")),a("average_range (number, range<number>, default=criteria_range)",v("The range to average. If not included, criteria_range is used for the average instead."))],compute:function(e,t,r){const n=mr(void 0===r?e:r);let o=0,s=0;return ur([e,t],(e,t)=>{const r=n[e]?.[t]?.value;"number"==typeof r&&(o+=1,s+=r)},this.locale),0===o?new O(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):s/o},isExported:!0},Oa={description:v("Average of values depending on multiple criteria."),args:[a("average_range (range)",v("The range to average.")),a("criteria_range (any, range, repeating)",v("Range to check.")),a("criterion (string, repeating)",v("Criterion to check."))],compute:function(e,...t){const r=mr(e);let n=0,o=0;return ur(t,(e,t)=>{const s=r[e]?.[t]?.value;"number"==typeof s&&(n+=1,o+=s)},this.locale),0===n?new O(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):o/n},isExported:!0},_a={description:v("The number of numeric values in dataset."),args:[a("value (number, any, range<number>, repeating)",v("Value or range to consider when counting."))],compute:function(...e){return function(e,t){let r=0;for(const n of e)if(D(n))for(const e of n)for(const t of e)"number"==typeof t.value&&(r+=1);else{const e=n?.value;Vt(e)||"string"==typeof e&&!Ot(e,t)&&!gt(e,t)||(r+=1)}return r}(e,this.locale)},isExported:!0},Da={description:v("The number of values in a dataset."),args:[a("value (any, range, repeating)",v("Value or range to consider when counting."))],compute:function(...e){return oa(e)},isExported:!0},Fa={description:v("The covariance of a dataset."),args:[a("data_y (any, range)",v("The range representing the array or matrix of dependent data.")),a("data_x (any, range)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){return ya(e,t,!1)},isExported:!0},Na={description:v("The covariance of a dataset."),args:[a("data_y (any, range)",v("The range representing the array or matrix of dependent data.")),a("data_x (any, range)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){return ya(e,t,!1)},isExported:!0},Ma={description:v("The sample covariance of a dataset."),args:[a("data_y (any, range)",v("The range representing the array or matrix of dependent data.")),a("data_x (any, range)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){return ya(e,t,!0)},isExported:!0},Va={description:v("Calculates the expected y-value for a specified x based on a linear regression of a dataset."),args:[a("x (number, range<number>)",v("The value(s) on the x-axis to forecast.")),a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t,r){const{flatDataX:n,flatDataY:o}=va(t,r);return 0===n.length||0===o.length?new x(vr):da([o],[n],nr(mr(e),e=>kt(e,this.locale)),!0)},isExported:!0},La={description:v("Fits points to exponential growth trend."),args:[a("known_data_y (range<number>)",v("The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.")),a("known_data_x (range<number>, default={1;2;3;...})",v("The values of the independent variable(s) corresponding with known_data_y.")),a("new_data_x (any, range, default=known_data_x)",v("The data points to return the y values for on the ideal curve fit.")),a("b (boolean, default=TRUE)",v("Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE."),fa)],compute:function(e,t=[[]],r=[[]],n={value:!0}){return 0===e.length||0===e[0].length?new S(yr("known_data_y")):da(ha(Ut(e,"known_data_y")),Ut(t,"known_data_x"),Ut(r,"new_data_y"),qt(n)).map(e=>e.map(e=>Math.exp(e)))}},Pa={description:v("Compute the intercept of the linear regression."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=va(e,t);if(0===r.length||0===n.length)return new x(vr);const[[],[o]]=la([r],[n]);return o},isExported:!0},ka={description:v("Nth largest element from a data set."),args:[a("data (any, range)",v("Array or range containing the dataset to consider.")),a("n (number)",v("The rank from largest to smallest of the element to return."))],compute:function(e,t){const r=Math.trunc(kt(t?.value,this.locale)),n=[];let o,s=0;Xt([e],e=>{"number"==typeof e?.value&&(o=hr(n,e,"nextSmaller","asc",n.length,(e,t)=>e[t].value),n.splice(o+1,0,e),s++,s>r&&(n.shift(),s--))});const i=n.shift();return void 0===i?new S(vr):s<r?new S(v("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",r)):i},isExported:!0},Ua={description:v("Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>, default={1;2;3;...})",v("The range representing the array or matrix of independent data.")),a("calculate_b (boolean, default=TRUE)",v("A flag specifying whether to compute the slope or not"),fa),a("verbose (boolean, default=FALSE)",v("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),ga)],compute:function(e,t=[[]],r={value:!0},n={value:!1}){return 0===e.length||0===e[0].length?new S(yr("data_y")):la(Ut(t,"data_x"),Ut(e,"data_y"),qt(r),qt(n))},isExported:!0},Ha={description:v("Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>, optional, default={1;2;3;...})",v("The range representing the array or matrix of independent data.")),a("calculate_b (boolean, default=TRUE)",v("A flag specifying whether to compute the slope or not"),fa),a("verbose (boolean, default=FALSE)",v("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),ga)],compute:function(e,t=[[]],r={value:!0},n={value:!1}){if(0===e.length||0===e[0].length)return new S(yr("data_y"));const o=la(Ut(t,"data_x"),ha(Ut(e,"data_y")),qt(r),qt(n));for(let e=0;e<o.length;e++)o[e][0]=Math.exp(o[e][0]);return o},isExported:!0},Ba={description:v("Compute the Matthews correlation coefficient of a dataset."),args:[a("data_x (range)",v("The range representing the array or matrix of observed data.")),a("data_y (range)",v("The range representing the array or matrix of predicted data."))],compute:function(e,t){const r=e.flat(),n=t.flat();if(ra(r,n),0===r.length||0===n.length)return new x(vr);const o=r.length;let s=0,i=0,a=0,l=0;for(let e=0;e<o;++e){const t=qt(r[e]);t===qt(n[e])?t?i++:s++:t?l++:a++}return(i*s-a*l)/Math.sqrt((i+a)*(i+l)*(s+a)*(s+l))},isExported:!1},za={description:v("Maximum value in a numeric dataset."),args:[a("value (number, range<number>, repeating)",v("Value or range to consider when calculating the maximum value."))],compute:function(...e){return sa(e,this.locale)},isExported:!0},$a={description:v("Maximum numeric value in a dataset."),args:[a("value (any, range, repeating)",v("Value or range to consider when calculating the maximum value."))],compute:function(...e){const t=tr(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:Mt(e[0])}},isExported:!0},Ga={description:v("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[a("range (range)",v("The range of cells from which the maximum will be determined.")),a("criteria_range (any, range, repeating)",v("Range to evaluate criteria.")),a("criterion (string, repeating)",v("Criteria to check."))],compute:function(e,...t){let r=-1/0;return ur(t,(t,n)=>{const o=e[t]?.[n]?.value;"number"==typeof o&&(r=r<o?o:r)},this.locale),r===-1/0?0:r},isExported:!0},Wa={description:v("Median value in a numeric dataset."),args:[a("value (any, range, repeating)",v("Value or range to consider when calculating the median value."))],compute:function(...e){const t=[];return Kt(e,e=>{t.push(e)},this.locale),{value:wa(t,{value:.5},!0,this.locale),format:Mt(t[0])}},isExported:!0},qa={description:v("Minimum value in a numeric dataset."),args:[a("value (number, range<number>, repeating)",v("Value or range to consider when calculating the minimum value."))],compute:function(...e){return ia(e,this.locale)},isExported:!0},Za={description:v("Minimum numeric value in a dataset."),args:[a("value (number, range<number>, repeating)",v("Value or range to consider when calculating the minimum value."))],compute:function(...e){const t=tr(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:Mt(e[0])}},isExported:!0},Ya={description:v("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[a("range (range)",v("The range of cells from which the minimum will be determined.")),a("criteria_range (any, range, repeating)",v("Range to evaluate criteria.")),a("criterion (string, repeating)",v("Criterion to check."))],compute:function(e,...t){let r=1/0;return ur(t,(t,n)=>{const o=e[t]?.[n]?.value;"number"==typeof o&&(r=r>o?o:r)},this.locale),r===1/0?0:r},isExported:!0};function ja(e,t){const{flatDataX:r,flatDataY:n}=va(e,t);if(0===r.length||0===n.length)return new x(vr);const o=r.length;let s=0,i=0,a=0,l=0,c=0;for(let e=0;e<o;e++){const t=r[e],o=n[e];s+=t,i+=o,a+=t*o,l+=t*t,c+=o*o}return(o*a-s*i)/Math.sqrt((o*l-s*s)*(o*c-i*i))}const Xa={description:v("Compute the Pearson product-moment correlation coefficient of a dataset."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){return ja(e,t)},isExported:!0},Ka=Xa,Qa={description:v("Value at a given percentile of a dataset."),args:[a("data (any, range)",v("The array or range containing the dataset to consider.")),a("percentile (number)",v("The percentile whose value within data will be calculated and returned."))],compute:function(e,t){return el.compute.bind(this)(e,t)},isExported:!0},Ja={description:v("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[a("data (any, range)",v("The array or range containing the dataset to consider.")),a("percentile (number)",v("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],compute:function(e,t){return{value:wa([e],t,!1,this.locale),format:Mt(e)}},isExported:!0},el={description:v("Value at a given percentile of a dataset."),args:[a("data (any, range)",v("The array or range containing the dataset to consider.")),a("percentile (number)",v("The percentile whose value within data will be calculated and returned."))],compute:function(e,t){return{value:wa([e],t,!0,this.locale),format:Mt(e)}},isExported:!0},tl={description:v("Compute the coefficients of polynomial regression of the dataset."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data.")),a("order (number)",v("The order of the polynomial to fit the data, between 1 and 6."),ma),a("intercept (boolean, default=TRUE)",v("A flag specifying whether to compute the intercept or not."),pa)],compute:function(e,t,r,n={value:!0}){const{flatDataX:o,flatDataY:s}=va(e,t);return 0===o.length||0===s.length?new x(vr):ca(s,o,kt(r,this.locale),qt(n))},isExported:!1},rl={description:v("Predict value by computing a polynomial regression of the dataset."),args:[a("x (number, range<number>)",v("The value(s) on the x-axis to forecast.")),a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data.")),a("order (number)",v("The order of the polynomial to fit the data, between 1 and 6."),ma),a("intercept (boolean, default=TRUE)",v("A flag specifying whether to compute the intercept or not."),pa)],compute:function(e,t,r,n,o={value:!0}){const s=kt(n,this.locale),{flatDataX:i,flatDataY:a}=va(t,r);if(0===i.length||0===a.length)return new x(vr);const l=ca(a,i,s,qt(o)).flat();return nr(mr(e),e=>function(e,t,r){return e.reduce((e,n,o)=>e+n*Math.pow(t,r-o),0)}(l,kt(e,this.locale),s))},isExported:!1},nl={description:v("Value nearest to a specific quartile of a dataset."),args:[a("data (any, range)",v("The array or range containing the dataset to consider.")),a("quartile_number (number)",v("Which quartile value to return."),ba)],compute:function(e,t){return sl.compute.bind(this)(e,t)},isExported:!0},ol={description:v("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[a("data (any, range)",v("The array or range containing the dataset to consider.")),a("quartile_number (number)",v("Which quartile value, exclusive of 0 and 4, to return."),[{value:1,label:v("First quartile (25th percentile)")},{value:2,label:v("Median value (50th percentile)")},{value:3,label:v("Third quartile (75th percentile)")}])],compute:function(e,t){return{value:wa([e],{value:.25*Math.trunc(kt(t,this.locale))},!1,this.locale),format:Mt(e)}},isExported:!0},sl={description:v("Value nearest to a specific quartile of a dataset."),args:[a("data (any, range)",v("The array or range containing the dataset to consider.")),a("quartile_number (number)",v("Which quartile value to return."),ba)],compute:function(e,t){return{value:wa([e],{value:.25*Math.trunc(kt(t,this.locale))},!0,this.locale),format:Mt(e)}},isExported:!0},il={description:v("Returns the rank of a specified value in a dataset."),args:[a("value (number)",v("The value whose rank will be determined.")),a("data (range)",v("The range containing the dataset to consider.")),a("is_ascending (boolean, default=FALSE)",v("Whether to consider the values in data in descending or ascending order."),[{value:!1,label:v("Descending")},{value:!0,label:v("Ascending")}])],compute:function(e,t,r={value:!1}){const n=qt(r),o=kt(e,this.locale);let s=1,i=!1;for(const e of t)for(const t of e){if("number"!=typeof t.value)continue;const e=kt(t,this.locale);e===o?i=!0:e>o!==n&&s++}return i?s:new x(v("Value not found in the given data."))},isExported:!0},al={description:v("Compute the square of r, the Pearson product-moment correlation coefficient of a dataset."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const r=ja(e,t);if(r instanceof Error)throw r;return Math.pow(r,2)},isExported:!0},ll={description:v("Compute the slope of the linear regression."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=va(e,t);if(0===r.length||0===n.length)return new x(vr);const[[o]]=la([r],[n]);return o},isExported:!0},cl={description:v("Nth smallest element in a data set."),args:[a("data (any, range)",v("The array or range containing the dataset to consider.")),a("n (number)",v("The rank from smallest to largest of the element to return."))],compute:function(e,t){const r=Math.trunc(kt(t?.value,this.locale)),n=[];let o,s=0;Xt([e],e=>{"number"==typeof e?.value&&(o=hr(n,e,"nextSmaller","asc",n.length,(e,t)=>e[t].value),n.splice(o+1,0,e),s++,s>r&&(n.pop(),s--))});const i=n.pop();return void 0===i?new S(vr):s<r?new S(v("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",r)):i},isExported:!0},ul={description:v("Compute the Spearman rank correlation coefficient of a dataset."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=va(t,e);if(0===r.length||0===n.length)return new x(vr);const o=r.length,s=r.map((e,t)=>[e,n[t]]);s.sort((e,t)=>e[0]-t[0]);for(let e=0;e<o;++e)s[e][0]=e;s.sort((e,t)=>e[1]-t[1]);let i=0;for(let e=0;e<o;++e)i+=(s[e][0]-e)**2;return 1-6*i/(o**3-o)},isExported:!1},hl={description:v("Standard deviation."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the sample."))],compute:function(...e){return Math.sqrt(yl.compute.bind(this)(...e))},isExported:!0},dl={description:v("Standard deviation of entire population."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the population."))],compute:function(...e){return Math.sqrt(El.compute.bind(this)(...e))},isExported:!0},fl={description:v("Standard deviation."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the sample."))],compute:function(...e){return Math.sqrt(wl.compute.bind(this)(...e))},isExported:!0},gl={description:v("Standard deviation of sample (text as 0)."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the sample."))],compute:function(...e){return Math.sqrt(Sl.compute.bind(this)(...e))},isExported:!0},ml={description:v("Standard deviation of entire population."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the population."))],compute:function(...e){return Math.sqrt(Cl.compute.bind(this)(...e))},isExported:!0},pl={description:v("Standard deviation of entire population (text as 0)."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the population."))],compute:function(...e){return Math.sqrt(Tl.compute.bind(this)(...e))},isExported:!0},bl={description:v("Calculates the standard error of the predicted y-value for each x in the regression of a dataset."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=va(e,t);if(0===r.length||0===n.length)return new x(vr);return la([r],[n],!0,!0)[1][2]},isExported:!0},vl={description:v("Fits points to linear trend derived via least-squares."),args:[a("known_data_y (number, range<number>)",v("The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.")),a("known_data_x (number, range<number>, optional, default={1;2;3;...})",v("The values of the independent variable(s) corresponding with known_data_y.")),a("new_data_x (number, range<number>, optional, default=known_data_x)",v("The data points to return the y values for on the ideal curve fit.")),a("b (boolean, optional, default=TRUE)",v("Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin."),fa)],compute:function(e,t=[[]],r=[[]],n={value:!0}){return 0===e.length||0===e[0].length?new S(yr("known_data_y")):da(Ut(e,"known_data_y"),Ut(t,"known_data_x"),Ut(r,"new_data_y"),qt(n))}},yl={description:v("Variance."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the sample."))],compute:function(...e){return Ea(e,!0,!1,this.locale)},isExported:!0},El={description:v("Variance of entire population."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the population."))],compute:function(...e){return Ea(e,!1,!1,this.locale)},isExported:!0},wl={description:v("Variance."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the sample."))],compute:function(...e){return Ea(e,!0,!1,this.locale)},isExported:!0},Sl={description:v("Variance of sample (text as 0)."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the sample."))],compute:function(...e){return Ea(e,!0,!0,this.locale)},isExported:!0},Cl={description:v("Variance of entire population."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the population."))],compute:function(...e){return Ea(e,!1,!1,this.locale)},isExported:!0},Tl={description:v("Variance of entire population (text as 0)."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the population."))],compute:function(...e){return Ea(e,!1,!0,this.locale)},isExported:!0};var Il=Object.freeze({__proto__:null,AVEDEV:Sa,AVERAGE:Ca,AVERAGEA:Ra,AVERAGEIF:Aa,AVERAGEIFS:Oa,AVERAGE_WEIGHTED:xa,CORREL:Ka,COUNT:_a,COUNTA:Da,COVAR:Fa,COVARIANCE_P:Na,COVARIANCE_S:Ma,FORECAST:Va,GROWTH:La,INTERCEPT:Pa,LARGE:ka,LINEST:Ua,LOGEST:Ha,MATTHEWS:Ba,MAX:za,MAXA:$a,MAXIFS:Ga,MEDIAN:Wa,MIN:qa,MINA:Za,MINIFS:Ya,PEARSON:Xa,PERCENTILE:Qa,PERCENTILE_EXC:Ja,PERCENTILE_INC:el,POLYFIT_COEFFS:tl,POLYFIT_FORECAST:rl,QUARTILE:nl,QUARTILE_EXC:ol,QUARTILE_INC:sl,RANK:il,RSQ:al,SLOPE:ll,SMALL:cl,SPEARMAN:ul,STDEV:hl,STDEVA:gl,STDEVP:ml,STDEVPA:pl,STDEV_P:dl,STDEV_S:fl,STEYX:bl,TREND:vl,VAR:yl,VARA:Sl,VARP:Cl,VARPA:Tl,VAR_P:El,VAR_S:wl});function xl(e,t,r,n){const o=new Map,s=e.length;for(let t=s-1;t>=0;t--)o.set($t(e[t][0]).toUpperCase(),t);const i=t?.value;if("number"!=typeof i&&"string"!=typeof i)throw new S(v("The field must be a number or a string"));let a;if("number"==typeof i){if(a=Math.trunc(i)-1,a<0||s-1<a)throw new S(v("The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.",{fieldValue:i.toString(),dimRowDB:s.toString()}))}else{const e=$t(t).toUpperCase();if(a=o.get(e)??-1,-1===a)throw new S(v("The field (%s) must be one of %s.",$t(t),[...o.keys()].toString()))}const l=r[0].length;if(l<2)throw new S(v("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const u=e[0].length;for(let t=1;t<l;t++){const s=[];let i=!0;for(let n=0;n<r.length;n++){const a=$t(r[n][0]).toUpperCase(),l=o.get(a),c=r[n][t];if(null!==c.value){if(void 0===l){i=!1;break}s.push([e[l].slice(1,u)]),s.push(c)}}if(i){if(!(s.length>0)){c=new Set(Array(u-1).keys());break}ur(s,(e,t)=>{c.add(t)},n,!0)}}const h=e[a];return[...c].map(e=>h[e+1])}const Rl=[a("database (range)",v("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.")),a("field (number, string)",v("Indicates which column in database contains the values to be extracted and operated on.")),a("criteria (range)",v("An array or range containing zero or more criteria to filter the database values by before operating."))],Al={description:v("Average of a set of values from a table-like range."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return Ca.compute.bind(this)([n])},isExported:!0},Ol={description:v("Counts values from a table-like range."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return _a.compute.bind(this)([n])},isExported:!0},_l={description:v("Counts values and text from a table-like range."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return Da.compute.bind(this)([n])},isExported:!0},Dl={description:v("Single value from a table-like range."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return 1!==n.length?new S(v("More than one match found in DGET evaluation.")):n[0]},isExported:!0},Fl={description:v("Maximum of values from a table-like range."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return za.compute.bind(this)([n])},isExported:!0},Nl={description:v("Minimum of values from a table-like range."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return qa.compute.bind(this)([n])},isExported:!0},Ml={description:v("Product of values from a table-like range."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return _i.compute.bind(this)([n])},isExported:!0},Vl={description:v("Standard deviation of population sample from table."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return hl.compute.bind(this)([n])},isExported:!0},Ll={description:v("Standard deviation of entire population from table."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return ml.compute.bind(this)([n])},isExported:!0},Pl={description:v("Sum of values from a table-like range."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return Zi.compute.bind(this)([n])},isExported:!0},kl={description:v("Variance of population sample from table-like range."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return yl.compute.bind(this)([n])},isExported:!0},Ul={description:v("Variance of a population from a table-like range."),args:Rl,compute:function(e,t,r){const n=xl(e,t,r,this.locale);return Cl.compute.bind(this)([n])},isExported:!0};var Hl=Object.freeze({__proto__:null,DAVERAGE:Al,DCOUNT:Ol,DCOUNTA:_l,DGET:Dl,DMAX:Fl,DMIN:Nl,DPRODUCT:Ml,DSTDEV:Vl,DSTDEVP:Ll,DSUM:Pl,DVAR:kl,DVARP:Ul});const Bl=["%"],zl="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Bl);function $l(e,t=xr){e=Pe(e);const r=new Ze(e),n=[],o=Me.test(e)?oc:sc;for(;!r.isOver();){let e=ic(r)||o(r)||Xl(r,t)||jl(r,t)||Yl(r)||ql(r)||Kl(r)||ec(r)||Gl(r)||ac(r)||Jl(r,t)||nc(r);e||(e={type:"UNKNOWN",value:r.shift()}),n.push(e)}return n}function Gl(e){return"?"===e.current?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const Wl={"(":{type:"LEFT_PAREN",value:"("},")":{type:"RIGHT_PAREN",value:")"}};function ql(e){if("("===e.current||")"===e.current){const t=e.shift();return Wl[t]}return null}const Zl={"{":{type:"LEFT_BRACE",value:"{"},"}":{type:"RIGHT_BRACE",value:"}"}};function Yl(e){if("{"===e.current||"}"===e.current){const t=e.shift();return Zl[t]}return null}function jl(e,t){if(e.current===t.formulaArgSeparator){return{type:"ARG_SEPARATOR",value:e.shift()}}return null}function Xl(e,t){const r=";"===t.formulaArgSeparator?"\\":";";return r&&e.current===r?(e.shift(),{type:"ARRAY_ROW_SEPARATOR",value:r}):null}function Kl(e){for(const t of zl)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}const Ql=new Set("0123456789");function Jl(e,t){if(!Ql.has(e.current)&&e.current!==t.decimalSeparator)return null;const r=e.remaining().match(Rt(t.decimalSeparator));return r?(e.advanceBy(r[0].length),{type:"NUMBER",value:r[0]}):null}function ec(e){if('"'===e.current){const t=e.shift();let r=t;for(;e.current&&(e.current!==t||"\\"===r[r.length-1]);)r+=e.shift();return'"'===e.current&&(r+=e.shift()),{type:"STRING",value:r}}return null}const tc=/\p{L}|\p{N}|_|\.|!|\$/u,rc=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$");function nc(e){let t="";if("'"===e.current){let r=e.shift();for(t+=r;e.current;)if(r=e.shift(),t+=r,"'"===r){if(!e.current||"'"!==e.current)break;r=e.shift(),t+=r}if("'"!==r)return{type:"UNKNOWN",value:t}}for(;e.current&&(rc.has(e.current)||e.current.match(tc));)t+=e.shift();if(t.length){const e=t;return vo.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function oc(e){let t="";for(;" "===e.current||e.current&&e.current.match(Me);)t+=e.shift();return t?{type:"SPACE",value:t}:null}function sc(e){let t="";for(;" "===e.current;)t+=e.shift();return t?{type:"SPACE",value:t}:null}function ic(e){let t=0;for(;e.current===Q;)t++,e.shift();return t?{type:"SPACE",value:Q.repeat(t)}:null}function ac(e){return e.currentStartsWith(E.InvalidReference)?(e.advanceBy(E.InvalidReference.length),{type:"INVALID_REFERENCE",value:E.InvalidReference}):null}function lc(e){if(!e||"object"!=typeof e||e.thousandsSeparator&&"string"!=typeof e.thousandsSeparator)return!1;for(const t of["code","name","decimalSeparator","dateFormat","timeFormat","formulaArgSeparator"])if(!e[t]||"string"!=typeof e[t])return!1;if(e.formulaArgSeparator===e.decimalSeparator)return!1;if(e.thousandsSeparator===e.decimalSeparator)return!1;try{Xr(1,{locale:e,format:"#,##0.00"}),Xr(1,{locale:e,format:e.dateFormat}),Xr(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function cc(e,t){return Ke(e)?function(e,t){return dc(e.startsWith("+")?"="+e.slice(1):e,t,xr)}(e,t):function(e,t){if("."===t.decimalSeparator||!Ot(e,t))return e;t.thousandsSeparator&&(e=e.replaceAll(t.thousandsSeparator,""));return e.replace(t.decimalSeparator,".")}(e,t)}function uc(e,t){return e.startsWith("=")?hc(e,t):function(e,t){if(dt(e,xr)){const r=kt(e,xr);let n=t.dateFormat;return Number.isInteger(r)||(n+=" "+t.timeFormat),Xr(r,{locale:t,format:n})}return function(e,t){if("."===t.decimalSeparator||!Ot(e,xr))return e;const r=an(xr);return e.replace(r,e=>e.replace(".",t.decimalSeparator))}(e,t)}(e,t)}function hc(e,t){return dc(e,xr,t)}function dc(e,t,r){if(t.formulaArgSeparator===r.formulaArgSeparator&&t.decimalSeparator===r.decimalSeparator)return e;const n=$l(e,t);let o="";for(const e of n)"NUMBER"===e.type?o+=e.value.replace(t.decimalSeparator,r.decimalSeparator):"ARG_SEPARATOR"===e.type?o+=r.formulaArgSeparator:"ARRAY_ROW_SEPARATOR"===e.type?o+=";"===r.formulaArgSeparator?"\\":";":o+=e.value;return o}function fc(e){return e.dateFormat+" "+e.timeFormat}const gc=v("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."),mc=v("There must be both positive and negative values in cashflow_amounts."),pc=e=>v("The cost (%s) must be positive or null.",e),bc=e=>v("The frequency (%s) must be one of %s",e,[1,2,4].toString()),vc=e=>v("The day_count_convention (%s) must be between 0 and 4 inclusive.",e),yc=e=>v("The depreciation factor (%s) must be strictly positive.",e),Ec=e=>v("The discount (%s) must be strictly positive.",e),wc=e=>v("The discount (%s) must be smaller than 1.",e),Sc=e=>v("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e),Cc=(e,t)=>v("The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).",{first:e,last:t}),Tc=e=>v("The first_period (%s) must be strictly positive.",e),Ic=e=>v("The investment (%s) must be strictly positive.",e),xc=(e,t)=>v("The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).",{last:e,nPeriods:t}),Rc=e=>v("The last_period (%s) must be strictly positive.",e),Ac=e=>v("The life (%s) must be strictly positive.",e),Oc=(e,t)=>v("The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).",{maturity:t,settlement:e}),_c=e=>v("The number_of_periods (%s) must be strictly positive.",e),Dc=e=>v("The periods_by_year (%s) must be strictly positive.",e),Fc=(e,t)=>v("The period (%(period)s) must be less than or equal life (%(life)s).",{period:e,life:t}),Nc=e=>v("The period (%s) must be strictly positive.",e),Mc=e=>v("The present_value (%s) must be strictly positive.",e),Vc=e=>v("The price (%s) must be strictly positive.",e),Lc=e=>v("The rate_guess (%s) must be strictly greater than -1.",e),Pc=e=>v("The rate (%s) must be positive or null.",e),kc=e=>v("The rate (%s) must be strictly positive.",e),Uc=e=>v("The redemption (%s) must be strictly positive.",e),Hc=e=>v("The salvage (%s) must be positive or null.",e),Bc=(e,t)=>v("The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).",{settlement:e,maturity:t}),zc=e=>v("The unit (%s) must be strictly positive.",e),$c=e=>v("The yield (%s) must be positive or null.",e);function Gc(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function Wc(e){return![0,1,2,3,4].includes(e)}function qc(e){return![1,2,4].includes(e)}function Zc(e,t,r){const n=Zt(e,r),o=Zt(t,r),s=Zt(e,r);return s.setFullYear(n.getFullYear()+1),o.getTime()<=s.getTime()}const Yc=[{value:0,label:v("US (NASD) 30/360")},{value:1,label:v("Actual/Actual")},{value:2,label:v("Actual/360")},{value:3,label:v("Actual/365")},{value:4,label:v("European 30/360")}];var jc;!function(e){e.WHOLE_YEARS="Y",e.WHOLE_MONTHS="M",e.WHOLE_DAYS="D",e.DAYS_WITHOUT_WHOLE_MONTHS="MD",e.MONTH_WITHOUT_WHOLE_YEARS="YM",e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR="YD"}(jc||(jc={}));const Xc={description:v("Converts year/month/day into a date."),args:[a("year (number)",v("The year component of the date.")),a("month (number)",v("The month component of the date.")),a("day (number)",v("The day component of the date."))],compute:function(e,t,r){let n=Math.trunc(kt(e,this.locale));const o=Math.trunc(kt(t,this.locale)),s=Math.trunc(kt(r,this.locale));if(n<0||n>9999)return new S(v("The year (%s) must be between 0 and 9999 inclusive.",n.toString()));n<1900&&(n+=1900);const i=pt(new Qe(n,o-1,s));return i<0?new S(v("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")):{value:i,format:this.locale.dateFormat}},isExported:!0},Kc={description:v("Calculates the number of days, months, or years between two dates."),args:[a("start_date (date)",v("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.")),a("end_date (date)",v("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.")),a("unit (string)",v("A text abbreviation for unit of time."),[{value:"Y",label:v("The number of whole years between start_date and end_date")},{value:"M",label:v("The number of whole months between start_date and end_date")},{value:"D",label:v("The number of days between start_date and end_date")},{value:"MD",label:v("The number of days between start_date and end_date after subtracting whole months")},{value:"YM",label:v("The number of whole months between start_date and end_date after subtracting whole years")},{value:"YD",label:v("The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart")}])],compute:function(e,t,r){const n=$t(r).toUpperCase();if(!Object.values(jc).includes(n))return new S(((e,t)=>{const r=e.map(e=>`'${e}'`).join(", ");return v("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,r)})(Object.values(jc),$t(r)));const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=mt(o),a=mt(s);if(s<o)return new S(v("start_date (%s) should be on or before end_date (%s).",i.toLocaleDateString(),a.toLocaleDateString()));switch(n){case jc.WHOLE_YEARS:return It(i,a);case jc.WHOLE_MONTHS:return Ct(i,a);case jc.WHOLE_DAYS:return Tt(i,a);case jc.MONTH_WITHOUT_WHOLE_YEARS:return Ct(i,a)-12*It(i,a);case jc.DAYS_WITHOUT_WHOLE_MONTHS:let e=a.getDate()-i.getDate();if(e<0){e=vt(new Qe(a.getFullYear(),a.getMonth()-1,1))-Math.abs(e)}return e;case jc.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return St(e,t,1)<1}(o,s))return Tt(i,a);const e=new Qe(i.getFullYear(),a.getMonth(),a.getDate());let t=Tt(i,e);return t<0&&(e.setFullYear(i.getFullYear()+1),t=Tt(i,e)),t}}},isExported:!0},Qc={description:v("Converts a date string to a date value."),args:[a("date_string (string)",v("The string representing the date."))],compute:function(e){const t=$t(e),r=gt(t,this.locale);return null===r?new S(v("The date_string (%s) cannot be parsed to date/time.",t.toString())):Math.trunc(r.value)},isExported:!0},Jc={description:v("Day of the month that a specific date falls on."),args:[a("date (string)",v("The date from which to extract the day."))],compute:function(e){return Zt(e,this.locale).getDate()},isExported:!0},eu={description:v("Number of days between two dates."),args:[a("end_date (date)",v("The end of the date range.")),a("start_date (date)",v("The start of the date range."))],compute:function(e,t){const r=Zt(e,this.locale),n=Zt(t,this.locale),o=r.getTime()-n.getTime();return Math.round(o/et)},isExported:!0},tu=!1,ru={description:v("Number of days between two dates on a 360-day year (months of 30 days)."),args:[a("start_date (date)",v("The start date to consider in the calculation.")),a("end_date (date)",v("The end date to consider in the calculation.")),a("method (boolean, default=false)",v("An indicator of what day count method to use."),[{value:!1,label:v("U.S. NASD method (default)")},{value:!0,label:v("European method")}])],compute:function(e,t,r={value:tu}){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=St(n,o,qt(r)?4:0);return Math.sign(o-n)*Math.round(360*s)},isExported:!0},nu={description:v("Date a number of months before/after another date."),args:[a("start_date (date)",v("The date from which to calculate the result.")),a("months (number)",v("The number of months before (negative) or after (positive) 'start_date' to calculate."))],compute:function(e,t){return{value:pt(Et(Zt(e,this.locale),Math.trunc(kt(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},ou={description:v("Last day of a month before or after a date."),args:[a("start_date (date)",v("The date from which to calculate the result.")),a("months (number)",v("The number of months before (negative) or after (positive) 'start_date' to consider."))],compute:function(e,t){const r=Zt(e,this.locale),n=Math.trunc(kt(t,this.locale)),o=r.getFullYear(),s=r.getMonth();return{value:pt(new Qe(o,s+n+1,0)),format:this.locale.dateFormat}},isExported:!0},su={description:v("Hour component of a specific time."),args:[a("time (date)",v("The time from which to calculate the hour component."))],compute:function(e){return Zt(e,this.locale).getHours()},isExported:!0},iu={description:v("ISO week number of the year."),args:[a("date (date)",v("The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number."))],compute:function(e){const t=Zt(e,this.locale),r=t.getFullYear();let n=1;for(;4!==new Qe(r,0,n).getDay();)n+=1;const o=new Qe(r,0,n-3);let s=31;for(;4!==new Qe(r,11,s).getDay();)s-=1;const i=new Qe(r,11,s+3);let a,l;switch(a=o.getTime()<=t.getTime()?t.getTime()<=i.getTime()?0:1:-1,a){case 0:l=o;break;case 1:l=new Qe(r,11,s+3+1);break;case-1:let e=1;for(;4!==new Qe(r-1,0,e).getDay();)e+=1;l=new Qe(r-1,0,e-3)}const c=(t.getTime()-l.getTime())/et;return Math.floor(c/7)+1},isExported:!0},au={description:v("Minute component of a specific time."),args:[a("time (date)",v("The time from which to calculate the minute component."))],compute:function(e){return Zt(e,this.locale).getMinutes()},isExported:!0},lu={description:v("Month of the year a specific date falls in"),args:[a("date (date)",v("The date from which to extract the month."))],compute:function(e){return Zt(e,this.locale).getMonth()+1},isExported:!0},cu={description:v("Net working days between two provided days."),args:[a("start_date (date)",v("The start date of the period from which to calculate the number of net working days.")),a("end_date (date)",v("The end date of the period from which to calculate the number of net working days.")),a("holidays (date, range<date>, optional)",v("A range or array constant containing the date serial numbers to consider holidays."))],compute:function(e,t,r){return du.compute.bind(this)(e,t,{value:1},r)},isExported:!0};function uu(e){const t=e?.value;if("string"==typeof t){yn(7===t.length&&[...t].every(e=>"0"===e||"1"===e),v('When weekend is a string (%s) it must be composed of "0" or "1".',t));const e=[];for(let r=0;r<7;r++)"1"===t[r]&&e.push((r+1)%7);return e}if("number"==typeof t)return yn(1<=t&&t<=7||11<=t&&t<=17,v("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new S(v("The weekend must be a number or a string."))}const hu=[{value:1,label:v("Saturday/Sunday are weekends")},{value:2,label:v("Sunday/Monday are weekends")},{value:3,label:v("Monday/Tuesday are weekends")},{value:4,label:v("Tuesday/Wednesday are weekends")},{value:5,label:v("Wednesday/Thursday are weekends")},{value:6,label:v("Thursday/Friday are weekends")},{value:7,label:v("Friday/Saturday are weekends")},{value:11,label:v("Sunday is the only weekend")},{value:12,label:v("Monday is the only weekend")},{value:13,label:v("Tuesday is the only weekend")},{value:14,label:v("Wednesday is the only weekend")},{value:15,label:v("Thursday is the only weekend")},{value:16,label:v("Friday is the only weekend")},{value:17,label:v("Saturday is the only weekend")}],du={description:v("Net working days between two dates (specifying weekends)."),args:[a("start_date (date)",v("The start date of the period from which to calculate the number of net working days.")),a("end_date (date)",v("The end date of the period from which to calculate the number of net working days.")),a("weekend (any, default=1)",v("A number or string representing which days of the week are considered weekends."),hu),a("holidays (date, range<date>, optional)",v("A range or array constant containing the dates to consider as holidays."))],compute:function(e,t,r={value:1},n){const o=Zt(e,this.locale),s=Zt(t,this.locale),i=uu(r),a=new Set;void 0!==n&&Xt([n],e=>{const t=Zt(e,this.locale);a.add(t.getTime())});const l=o.getTime()>s.getTime(),c=Qe.fromTimestamp((l?o:s).getTime()),u=Qe.fromTimestamp((l?s:o).getTime()),h=c.getTime();let d=u.getTime(),f=0;for(;d<=h;)i.includes(u.getDay())||a.has(d)||(f+=1),u.setDate(u.getDate()+1),d=u.getTime();return l?-f:f},isExported:!0},fu={description:v("Current date and time as a date value."),args:[],compute:function(){const e=Qe.now(),t=e.getTime()-Je.getTime(),r=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/et)+r,format:fc(this.locale)}},isExported:!0},gu={description:v("Minute component of a specific time."),args:[a("time (date)",v("The time from which to calculate the second component."))],compute:function(e){return Zt(e,this.locale).getSeconds()},isExported:!0},mu={description:v("Converts hour/minute/second into a time."),args:[a("hour (number)",v("The hour component of the time.")),a("minute (number)",v("The minute component of the time.")),a("second (number)",v("The second component of the time."))],compute:function(e,t,r){let n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=Math.trunc(kt(r,this.locale));return o+=Math.floor(s/60),s=s%60+(s<0?60:0),n+=Math.floor(o/60),o=o%60+(o<0?60:0),n%=24,n<0?new S(v("The function [[FUNCTION_NAME]] result cannot be negative")):{value:n/24+o/1440+s/86400,format:this.locale.timeFormat}},isExported:!0},pu={description:v("Converts a time string into its serial number representation."),args:[a("time_string (string)",v("The string that holds the time representation."))],compute:function(e){const t=$t(e),r=gt(t,this.locale);if(null===r)return new S(v("The time_string (%s) cannot be parsed to date/time.",t));const n=r.value-Math.trunc(r.value);return n<0?1+n:n},isExported:!0},bu={description:v("Current date as a date value."),args:[],compute:function(){const e=Qe.now();return{value:pt(new Qe(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},vu={description:v("Day of the week of the date provided (as number)."),args:[a("date (date)",v("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.")),a("type (number, default=1)",v("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."),[{value:1,label:v("Numbers 1 (Sunday) trough 7 (Saturday)")},{value:2,label:v("Numbers 1 (Monday) trough 7 (Sunday)")},{value:3,label:v("Numbers 0 (Monday) trough 6 (Sunday)")},{value:11,label:v("Numbers 1 (Monday) trough 7 (Sunday)")},{value:12,label:v("Numbers 1 (Tuesday) trough 7 (Monday)")},{value:13,label:v("Numbers 1 (Wednesday) trough 7 (Tuesday)")},{value:14,label:v("Numbers 1 (Thursday) trough 7 (Wednesday)")},{value:15,label:v("Numbers 1 (Friday) trough 7 (Thursday)")},{value:16,label:v("Numbers 1 (Saturday) trough 7 (Friday)")},{value:17,label:v("Numbers 1 (Sunday) trough 7 (Saturday)")}])],compute:function(e,t={value:1}){const r=Zt(e,this.locale),n=Math.round(kt(t,this.locale)),o=r.getDay();if(!(1<=n&&n<=3||11<=n&&n<=17))return new S(v("The type (%s) must be between 1 and 3 or between 11 and 17.",n));switch(n){case 1:return o+1;case 2:return 0===o?7:o;case 3:return 0===o?6:o-1}const s=(o+1-(n-10)+7)%7;return 0===s?7:s},isExported:!0},yu={description:v("Week number of the year."),args:[a("date (date)",v("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.")),a("type (number, default=1)",v("A number representing the day that a week starts on. Sunday = 1."),[{value:1,label:v("Sunday")},{value:2,label:v("Monday")},{value:11,label:v("Monday")},{value:12,label:v("Tuesday")},{value:13,label:v("Wednesday")},{value:14,label:v("Thursday")},{value:15,label:v("Friday")},{value:16,label:v("Saturday")},{value:17,label:v("Sunday")},{value:21,label:v("ISO week number (Monday as first day of the week)")}])],compute:function(e,t={value:1}){const r=Zt(e,this.locale),n=Math.round(kt(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(n))return new S(v("The type (%s) is out of range.",n.toString()));if(21===n)return iu.compute.bind(this)(e);let o;o=1===n||2===n?n-1:n-10==7?0:n-10;const s=r.getFullYear();let i=1,a=new Qe(s,0,i);for(;a.getDay()!==o;)i+=1,a=new Qe(s,0,i);const l=(r.getTime()-a.getTime())/et;return l<0?1:Math.floor(l/7)+(1===i?1:2)},isExported:!0},Eu={description:v("Date after a number of workdays."),args:[a("start_date (date)",v("The date from which to begin counting.")),a("num_days (number)",v("The number of working days to advance from start_date. If negative, counts backwards.")),a("holidays (date, range<date>, optional)",v("A range or array constant containing the dates to consider holidays."))],compute:function(e,t,r={value:null}){return wu.compute.bind(this)(e,t,{value:1},r)},isExported:!0},wu={description:v("Date after a number of workdays (specifying weekends)."),args:[a("start_date (date)",v("The date from which to begin counting.")),a("num_days (number)",v("The number of working days to advance from start_date. If negative, counts backwards.")),a("weekend (any, default=1)",v("A number or string representing which days of the week are considered weekends."),hu),a("holidays (date, range<date>, optional)",v("A range or array constant containing the dates to consider holidays."))],compute:function(e,t,r={value:1},n){const o=Zt(e,this.locale),s=Math.trunc(kt(t,this.locale));if("1111111"===r.value)return new S(v("The weekend must be different from '1111111'."));const i=uu(r),a=new Set;void 0!==n&&Xt([n],e=>{const t=Zt(e,this.locale);a.add(t.getTime())});const l=Qe.fromTimestamp(o.getTime());let c=l.getTime();const u=Math.sign(s);let h=Math.abs(s);for(;h>0;)l.setDate(l.getDate()+u),c=l.getTime(),i.includes(l.getDay())||a.has(c)||(h-=1);const d=c-Je.getTime();return{value:Math.round(d/et),format:this.locale.dateFormat}},isExported:!0},Su={description:v("Year specified by a given date."),args:[a("date (date)",v("The date from which to extract the year."))],compute:function(e){return Zt(e,this.locale).getFullYear()},isExported:!0},Cu={description:v("Exact number of years between two dates."),args:[a("start_date (date)",v("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.")),a("end_date (date)",v("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.")),a("day_count_convention (number, default=0)",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r={value:0}){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=Math.trunc(kt(r,this.locale));return n<0?new S(v("The start_date (%s) must be positive or null.",n)):o<0?new S(v("The end_date (%s) must be positive or null.",o)):0>s||s>4?new S(v("The day_count_convention (%s) must be between 0 and 4 inclusive.",s)):St(n,o,s)}},Tu={description:v("First day of the month preceding a date."),args:[a("date (date)",v("The date from which to calculate the result."))],compute:function(e){const t=Zt(e,this.locale),r=t.getFullYear(),n=t.getMonth();return{value:pt(new Qe(r,n,1)),format:this.locale.dateFormat}}},Iu={description:v("Last day of the month following a date."),args:[a("date (date)",v("The date from which to calculate the result."))],compute:function(e){return ou.compute.bind(this)(e,{value:0})}},xu={description:v("Quarter of the year a specific date falls in"),args:[a("date (date)",v("The date from which to extract the quarter."))],compute:function(e){return Math.ceil((Zt(e,this.locale).getMonth()+1)/3)}},Ru={description:v("First day of the quarter of the year a specific date falls in."),args:[a("date (date)",v("The date from which to calculate the start of quarter."))],compute:function(e){const t=xu.compute.bind(this)(e),r=Su.compute.bind(this)(e);return{value:pt(new Qe(r,3*(t-1),1)),format:this.locale.dateFormat}}},Au={description:v("Last day of the quarter of the year a specific date falls in."),args:[a("date (date)",v("The date from which to calculate the end of quarter."))],compute:function(e){const t=xu.compute.bind(this)(e),r=Su.compute.bind(this)(e);return{value:pt(new Qe(r,3*t,0)),format:this.locale.dateFormat}}},Ou={description:v("First day of the year a specific date falls in."),args:[a("date (date)",v("The date from which to calculate the start of the year."))],compute:function(e){const t=Su.compute.bind(this)(e);return{value:pt(new Qe(t,0,1)),format:this.locale.dateFormat}}},_u={description:v("Last day of the year a specific date falls in."),args:[a("date (date)",v("The date from which to calculate the end of the year."))],compute:function(e){const t=Su.compute.bind(this)(e);return{value:pt(new Qe(t+1,0,0)),format:this.locale.dateFormat}}};var Du=Object.freeze({__proto__:null,DATE:Xc,DATEDIF:Kc,DATEVALUE:Qc,DAY:Jc,DAYS:eu,DAYS360:ru,EDATE:nu,EOMONTH:ou,HOUR:su,ISOWEEKNUM:iu,MINUTE:au,MONTH:lu,MONTH_END:Iu,MONTH_START:Tu,NETWORKDAYS:cu,NETWORKDAYS_INTL:du,NOW:fu,QUARTER:xu,QUARTER_END:Au,QUARTER_START:Ru,SECOND:gu,TIME:mu,TIMEVALUE:pu,TODAY:bu,WEEKDAY:vu,WEEKNUM:yu,WORKDAY:Eu,WORKDAY_INTL:wu,YEAR:Su,YEARFRAC:Cu,YEAR_END:_u,YEAR_START:Ou});const Fu={description:v("Compare two numeric values, returning 1 if they're equal."),args:[a("number1 (number)",v("The first number to compare.")),a("number2 (number, default=0)",v("The second number to compare."))],compute:function(e,t={value:0}){return kt(e,this.locale)===kt(t,this.locale)?1:0},isExported:!0};var Nu,Mu=Object.freeze({__proto__:null,DELTA:Fu});!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(Nu||(Nu={}));const Vu=[Nu.number,Nu.error,Nu.text,Nu.boolean];function Lu(e){const t="asc"===e?1:-1;return(e,r)=>{if(e.type===Nu.empty)return r.type===Nu.empty?0:1;if(r.type===Nu.empty)return-1;let n=Vu.indexOf(e.type)-Vu.indexOf(r.type);return 0===n&&(n=e.type===Nu.text||e.type===Nu.error?e.value.localeCompare(r.value):e.value-r.value),t*n}}function Pu(e,t,...r){for(let e=0;e<r.length;e++){const t=e%2==0?"sort_column":"is_ascending";yn(void 0!==r[e],v("Value for parameter %s is missing in [[FUNCTION_NAME]].",t))}const n=[],o=[],s=e.length;for(let i=0;i<r.length;i+=2){n.push(qt(On(r[i+1])?.value)?"asc":"desc");const a=r[i];if(D(a)&&(a.length>1||a[0].length>1))yn(1===a.length&&a[0].length===s,v("Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.",`sort_column${i+1}`,s,a.length,a[0].length)),o.push(a.flat().map(e=>e.value));else{const r=kt(On(a)?.value,t);if(r<1||r>e[0].length)return e;o.push(e.map(e=>e[r-1].value))}}if(0===o.length)for(let t=0;t<e[0].length;t++)o.push(e.map(e=>e[t].value)),n.push("asc");const i={desc:Lu("desc"),asc:Lu("asc")},a=le(0,e.length);return a.sort((e,t)=>{for(const[r,s]of o.entries()){const o=s[e],a=s[t],l={value:o,type:null===o?Nu.empty:"string"==typeof o?Nu.text:typeof o},c={value:a,type:null===a?Nu.empty:"string"==typeof a?Nu.text:typeof a},u=i[n[r]](l,c);if(0!==u)return u}return 0}),a.map(t=>e[t])}const ku={description:v("Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions."),args:[a("range (any, range<any>)",v("The data to be filtered.")),a("condition (boolean, range<boolean>, repeating)",v("Column or row containing true or false values corresponding to the range."))],compute:function(e,...t){let r=mr(e);const n=t.map(e=>nr(mr(e),e=>e.value));for(const e of n)if(!wn(e))return new S(v("The arguments condition must be a single column or row."));if(!Sn(...t))return new S(v("The arguments conditions must have the same dimensions."));const o=n.map(e=>e.flat()),s=1===n[0].length?"row":"col";if(r="row"===s?or(r):r,o.some(e=>e.length!==r.length))return new S(v("FILTER has mismatched sizes on the range and conditions."));const i=[];for(let e=0;e<r.length;e++){const t=r[e];o.every(t=>("boolean"==typeof t[e]||"number"==typeof t[e])&&t[e])&&i.push(t)}return i.length?"row"===s?or(i):i:new x(v("No match found in FILTER evaluation"))},isExported:!1},Uu={description:v("Sorts the rows of a given array or range by the values in one or more columns."),args:[a("range (range)",v("The data to be sorted.")),a("sort_column (any, range<number>, repeating, optional)",v("The index of the column in range or a range outside of range containing the value by which to sort.")),a("is_ascending (boolean, repeating, optional)",v("TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order."),[{value:!0,label:v("Ascending")},{value:!1,label:v("Descending")}])],compute:function(e,...t){const r=or(e);return or(Pu(r,this.locale,...t))},isExported:!0},Hu={description:v("Returns the first n items in a data set after performing a sort."),args:[a("range (range)",v("The data to be sorted.")),a("n (number)",v("The number of items to return.")),a("display_ties_mode (number, default=0)",v("A number representing the way to display ties.")),a("sort_column (number, range<number>, repeating, optional)",v("The index of the column in range or a range outside of range containing the value by which to sort.")),a("is_ascending (boolean, repeating, optional)",v("TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order."),[{value:!0,label:v("Ascending")},{value:!1,label:v("Descending")}])],compute:function(e,t,...r){const n=kt(t?.value??1,this.locale),o=r.length%2==0?0:kt(r[0]?.value,this.locale),s=r.length%2==0?r:r.slice(1);if(n<0)return new S(v("Wrong value of 'n'. Expected a positive number. Got %s.",n));if(o<0||o>3)return new S(v("Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.",o));const i=Pu(or(e),this.locale,...s),a=(e,t)=>JSON.stringify(i[e].map(e=>e.value))===JSON.stringify(i[t].map(e=>e.value));switch(o){case 0:return or(i.slice(0,n));case 1:for(let e=n;e<i.length;e++)if(!a(e,n-1))return or(i.slice(0,e));return or(i);case 2:{const e=[i[0]];for(let t=1;t<i.length;t++)for(let r=0;r<t&&!a(t,r);r++)r===t-1&&e.push(i[t]);return or(e.slice(0,n))}case 3:{const e=[i[0]];let t=1;for(let r=1;r<i.length&&(a(r,r-1)||t++,!(t>n));r++)e.push(i[r]);return or(e)}}},isExported:!1},Bu={description:v("Unique rows in the provided source range."),args:[a("range (any, range<any>)",v("The data to filter by unique entries.")),a("by_column (boolean, default=FALSE)",v("Whether to filter the data by columns or by rows."),[{value:!0,label:v("Return unique columns")},{value:!1,label:v("Return unique rows")}]),a("exactly_once (boolean, default=FALSE)",v("Whether to return only entries with no duplicates."),[{value:!0,label:v("Return items that appear exactly once")},{value:!1,label:v("Return every distinct item")}])],compute:function(e={value:""},t,r){if(!D(e))return[[e]];const n=qt(t?.value)||!1,o=qt(r?.value)||!1;n||(e=or(e));const s=new Map;for(const t of e){const e=JSON.stringify(t.map(e=>e.value)),r=s.get(e);r?r.count++:s.set(e,{data:t,count:1})}const i=[];for(const e of s.values())o&&e.count>1||i.push(e.data);return i.length?n?i:or(i):new S(v("No unique values found"))},isExported:!0};var zu=Object.freeze({__proto__:null,FILTER:ku,SORT:Uu,SORTN:Hu,UNIQUE:Bu});const $u=[{value:1,label:v("Annual")},{value:2,label:v("Semi-annual")},{value:4,label:v("Quarterly")}],Gu=[{value:0,label:v("End of period (default)")},{value:1,label:v("Beginning of period")}],Wu=[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("frequency (number)",v("The number of interest or coupon payments per year (1, 2, or 4)."),$u),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)];function qu(e,t,r,n,o=1e-10,s){let i,a,l,c,u=r,h=!1,d=0;do{l=e(u),isNaN(l)?(yn(d<n&&void 0!==s,v("Function [[FUNCTION_NAME]] didn't find any result.")),d++,u=s(c),c=u):(i=u-l/t(u),a=Math.abs(i-u),u=i,h=a<o||Math.abs(l)<o,yn(d<n,v("Function [[FUNCTION_NAME]] didn't find any result.")),d++)}while(!h);return u}const Zu={description:v("Accrued interest of security paying at maturity."),args:[a("issue (date)",v("The date the security was initially issued.")),a("maturity (date)",v("The maturity date of the security.")),a("rate (number)",v("The annualized rate of interest.")),a("redemption (number)",v("The redemption amount per 100 face value, or par.")),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o={value:0}){const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(n,this.locale),l=kt(r,this.locale),c=Math.trunc(kt(o,this.locale));if(s<0)return new S((e=>v("The issue (%s) must be positive or null.",e))(s));if(s>=i)return new S(Oc(s,i));if(Wc(c))return new S(vc(c));if(a<=0)return new S(Uc(a));if(l<=0)return new S(kc(l));return a*l*St(s,i,c)},isExported:!0},Yu={description:v("Depreciation for an accounting period."),args:[a("cost (number)",v("The initial cost of the asset.")),a("purchase_date (date)",v("The date the asset was purchased.")),a("first_period_end (date)",v("The date the first period ended.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("period (number)",v("The single period within life for which to calculate depreciation.")),a("rate (number)",v("The deprecation rate.")),a("day_count_convention (number, optional)",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o,s,i={value:0}){i=i||0;const a=kt(e,this.locale),l=Math.trunc(kt(t,this.locale)),c=Math.trunc(kt(r,this.locale)),u=kt(n,this.locale),h=kt(o,this.locale),d=kt(s,this.locale),f=Math.trunc(kt(i,this.locale));if(a<=0)return new S((e=>v("The cost (%s) must be strictly positive.",e))(a));if(l<0)return new S((e=>v("The purchase_date (%s) must be positive or null.",e))(l));if(u<0)return new S(Hc(u));if(u>a)return new S(((e,t)=>v("The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).",{salvage:e,cost:t}))(u,a));if(h<0)return new S((e=>v("The period (%s) must be positive or null.",e))(h));if(d<=0)return new S(kc(d));if(Wc(f))return new S(vc(f));if(l>c)return new S(((e,t)=>v("The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).",{purchaseDate:e,firstPeriodEnd:t}))(l,c));const g=h<1&&h>0?1:Math.trunc(h),m=a*d,p=St(l,c,f),b=l===c?m:m*p,y=a-b-m*g;return y>=u?0===g?b:m:u-y<m?m-(u-y):0},isExported:!0},ju={description:v("Days in coupon period containing settlement date."),args:Wu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(Oc(o,s));if(qc(i))return new S(bc(i));if(Wc(a))return new S(vc(a));if(1===a){const o=eh.compute.bind(this)(e,t,r,n).value;return kt(Qu.compute.bind(this)(e,t,r,n).value,this.locale)-kt(o,this.locale)}return(3===a?365:360)/i},isExported:!0},Xu={description:v("Days from settlement until next coupon."),args:Wu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(Oc(o,s));if(qc(i))return new S(bc(i));if(Wc(a))return new S(vc(a));const l=kt(eh.compute.bind(this)(e,t,r,n).value,this.locale);if([1,2,3].includes(a))return o-l;if(4===a){const e=St(l,o,a);return Math.round(360*e)}const c=Zt(o,this.locale),u=Zt(l,this.locale),h=u.getFullYear(),d=c.getFullYear(),f=u.getMonth()+1,g=c.getMonth()+1;let m=u.getDate(),p=c.getDate();return 2===f&&2===g&&yt(u)&&yt(c)&&(p=30),31!==p||30!==m&&31!==m||(p=30),2===f&&yt(u)&&(m=30),31===m&&(m=30),360*(d-h)+30*(g-f)+(p-m)},isExported:!0},Ku={description:v("Days from settlement until next coupon."),args:Wu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(Oc(o,s));if(qc(i))return new S(bc(i));if(Wc(a))return new S(vc(a));const l=kt(Qu.compute.bind(this)(e,t,r,n).value,this.locale);if([1,2,3].includes(a))return l-o;if(4===a){const e=St(o,l,a);return Math.round(360*e)}const c=Xu.compute.bind(this)(e,t,r,n);return kt(ju.compute.bind(this)(e,t,r,n),this.locale)-kt(c,this.locale)},isExported:!0},Qu={description:v("Next coupon date after the settlement date."),args:Wu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(Oc(o,s));if(qc(i))return new S(bc(i));if(Wc(a))return new S(vc(a));const l=12/i,c=Ju.compute.bind(this)(e,t,r,n);return{value:pt(Et(Zt(s,this.locale),-(kt(c,this.locale)-1)*l,!0)),format:this.locale.dateFormat}},isExported:!0},Ju={description:v("Number of coupons between settlement and maturity."),args:Wu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(Oc(o,s));if(qc(i))return new S(bc(i));if(Wc(a))return new S(vc(a));let l=1,c=s;const u=12/i;for(;c>o;)c=pt(Et(Zt(c,this.locale),-u,!1)),l++;return l-1},isExported:!0},eh={description:v("Last coupon date prior to or on the settlement date."),args:Wu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(Oc(o,s));if(qc(i))return new S(bc(i));if(Wc(a))return new S(vc(a));const l=12/i,c=Ju.compute.bind(this)(e,t,r,n);return{value:pt(Et(Zt(s,this.locale),-c*l,!0)),format:this.locale.dateFormat}},isExported:!0},th={description:v("Cumulative interest paid over a set of periods."),args:[a("rate (number)",v("The interest rate.")),a("number_of_periods (number)",v("The number of payments to be made.")),a("present_value (number)",v("The current value of the annuity.")),a("first_period (number)",v("The number of the payment period to begin the cumulative calculation.")),a("last_period (number)",v("The number of the payment period to end the cumulative calculation.")),a("end_or_beginning (number, default=0)",v("The timing of the payment payments are due for each period."),Gu)],compute:function(e,t,r,n,o,s={value:0}){const i=kt(n,this.locale),a=kt(o,this.locale),l=kt(e,this.locale),c=kt(r,this.locale),u=kt(t,this.locale),h=qt(s)?1:0;if(u<=0)return new S(_c(u));if(i<=0)return new S(Tc(i));if(a<=0)return new S(Rc(a));if(i>a)return new S(Cc(i,a));if(a>u)return new S(xc(a,u));if(l<=0)return new S(kc(l));if(c<=0)return new S(Mc(c));let d=0;for(let e=i;e<=a;e++)d+=mh(l,e,u,c,0,h);return d},isExported:!0},rh={description:v("Cumulative principal paid over a set of periods."),args:[a("rate (number)",v("The interest rate.")),a("number_of_periods (number)",v("The number of payments to be made.")),a("present_value (number)",v("The current value of the annuity.")),a("first_period (number)",v("The number of the payment period to begin the cumulative calculation.")),a("last_period (number)",v("The number of the payment period to end the cumulative calculation.")),a("end_or_beginning (number, default=0)",v("The timing of the payment payments are due for each period."),Gu)],compute:function(e,t,r,n,o,s={value:0}){const i=kt(n,this.locale),a=kt(o,this.locale),l=kt(e,this.locale),c=kt(r,this.locale),u=kt(t,this.locale),h=qt(s)?1:0;if(u<=0)return new S(_c(u));if(i<=0)return new S(Tc(i));if(a<=0)return new S(Rc(a));if(i>a)return new S(Cc(i,a));if(a>u)return new S(xc(a,u));if(l<=0)return new S(kc(l));if(c<=0)return new S(Mc(c));let d=0;for(let e=i;e<=a;e++)d+=Ah(l,e,u,c,0,h);return d},isExported:!0},nh={description:v("Depreciation via declining balance method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("period (number)",v("The single period within life for which to calculate depreciation.")),a("month (number, optional)",v("The number of months in the first year of depreciation."))],compute:function(e,t,r,n,...o){const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=Math.trunc(kt(n,this.locale)),c=o.length?Math.trunc(kt(o[0],this.locale)):12,u=a+(12===c?0:1);if(s<0)return new S(pc(s));if(i<0)return new S(Hc(i));if(l<=0)return new S(Nc(l));if(a<=0)return new S(Ac(a));if(1>c||c>12)return new S(v("The month (%s) must be between 1 and 12 inclusive.",c));if(l>u)return new S(((e,t)=>v("The period (%(period)s) must be less than or equal to %(lifeLimit)s.",{period:e,lifeLimit:t}))(l,u));const h=c/12;let d=1-Math.pow(i/s,1/a);d=Math.round(1e3*d)/1e3;let f=s,g=s*(1-d*h);for(let e=1;e<l;e++)f=g,g=f*(1-d),e===a&&(g=f*(1-d*(1-h)));return{value:f-g,format:"#,##0.00"}},isExported:!0},oh="#,##0.00",sh={description:v("Depreciation via double-declining balance method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("period (number)",v("The single period within life for which to calculate depreciation.")),a("factor (number, default=2)",v("The factor by which depreciation decreases."))],compute:function(e,t,r,n,o={value:2}){const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=kt(o,this.locale);if(s<0)return new S(pc(s));if(i<0)return new S(Hc(i));if(l<=0)return new S(Nc(l));if(a<=0)return new S(Ac(a));if(l>a)return new S(Fc(l,a));if(c<=0)return new S(yc(c));if(0===s||i>=s)return{value:0,format:oh};const u=c/a;if(u>1)return{value:1===l?s-i:0,format:oh};if(l<=1)return{value:s*u,format:oh};const h=s*Math.pow(1-u,l-1),d=s*Math.pow(1-u,l),f=d<i?h-i:h-d;return{value:Math.max(f,0),format:oh}},isExported:!0},ih={description:v("Discount rate of a security based on price."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("price (number)",v("The price at which the security is bought per 100 face value.")),a("redemption (number)",v("The redemption amount per 100 face value, or par.")),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(Oc(s,i));if(Wc(c))return new S(vc(c));if(a<=0)return new S(Vc(a));if(l<=0)return new S(Uc(l));return(l-a)/l/St(s,i,c)},isExported:!0},ah={description:v("Convert a decimal fraction to decimal value."),args:[a("fractional_price (number)",v("The price quotation given using fractional decimal conventions.")),a("unit (number)",v("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));if(n<=0)return new S(zc(n));const o=Math.trunc(r);return o+(r-o)*(10**Math.ceil(Math.log10(n))/n)},isExported:!0},lh={description:v("Convert a decimal value to decimal fraction."),args:[a("decimal_price (number)",v("The price quotation given as a decimal value.")),a("unit (number)",v("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));if(n<=0)return new S(zc(n));const o=Math.trunc(r);return o+(r-o)*(n/10**Math.ceil(Math.log10(n)))},isExported:!0},ch={description:v("Number of periods for an investment to reach a value."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("rate (number)",v("The annualized rate of interest.")),a("yield (number)",v("The expected annual yield of the security.")),a("frequency (number)",v("The number of interest or coupon payments per year (1, 2, or 4)."),$u),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o,s={value:0}){const i=Math.trunc(kt(e,this.locale)),a=Math.trunc(kt(t,this.locale)),l=kt(r,this.locale),c=kt(n,this.locale),u=Math.trunc(kt(o,this.locale)),h=Math.trunc(kt(s,this.locale));if(i>=a)return new S(Oc(i,a));if(qc(u))return new S(bc(u));if(Wc(h))return new S(vc(h));if(l<0)return new S(Pc(l));if(c<0)return new S($c(c));const d=St(i,a,h),f=d-Math.trunc(d)||1/u,g=Math.ceil(d*u),m=l/u,p=c/u;let b=0,v=0;for(let e=1;e<=g;e++){const t=(m+(e===g?1:0))/(1+p)**e;v+=(f+(e-1)/u)*t,b+=t}return 0===b?0:v/b},isExported:!0},uh={description:v("Annual effective interest rate."),args:[a("nominal_rate (number)",v("The nominal interest rate per year.")),a("periods_per_year (number)",v("The number of compounding periods per year."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));return r<=0?new S(v("The nominal_rate (%s) must be strictly positive.",r)):n<=0?new S(Dc(n)):Math.pow(1+r/n,n)-1},isExported:!0};function hh(e,t,r,n,o){return 0===e?-(n+r*t):-n*(1+e)**t-r*(1+e*o)*((1+e)**t-1)/e}const dh={description:v("Future value of an annuity investment."),args:[a("rate (number)",v("The interest rate.")),a("number_of_periods (number)",v("The number of payments to be made.")),a("payment_amount (number)",v("The amount per period to be paid.")),a("present_value (number, default=0)",v("The current value of the annuity.")),a("end_or_beginning (number, default=0)",v("The timing of the payment payments are due for each period."),Gu)],compute:function(e,t,r,n={value:0},o={value:0}){n=n||0,o=o||0;return{value:hh(kt(e,this.locale),kt(t,this.locale),kt(r,this.locale),kt(n,this.locale),qt(o)?1:0),format:"#,##0.00"}},isExported:!0},fh={description:v("Future value of principal from series of rates."),args:[a("principal (number)",v("The amount of initial capital or value to compound against.")),a("rate_schedule (number, range<number>)",v("A series of interest rates to compound against the principal."))],compute:function(e,t){return Jt([t],(e,t)=>e*(1+kt(t,this.locale)),kt(e,this.locale))},isExported:!0},gh={description:v("Calculates effective interest rate."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("investment (number)",v("The amount invested in the security.")),a("redemption (number)",v("The amount to be received at maturity.")),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o={value:0}){const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(n,this.locale),l=kt(r,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(Oc(s,i));if(l<=0)return new S(Ic(l));if(a<=0)return new S(Uc(a));if(Wc(c))return new S(vc(c));return(a-l)/l/St(s,i,c)},isExported:!0};function mh(e,t,r,n,o,s){return xh(e,r,n,o,s)-Ah(e,t,r,n,o,s)}const ph={description:v("Payment on the principal of an investment."),args:[a("rate (number)",v("The annualized rate of interest.")),a("period (number)",v("The amortization period, in terms of number of periods.")),a("number_of_periods (number)",v("The number of payments to be made.")),a("present_value (number)",v("The current value of the annuity.")),a("future_value (number, default=0)",v("The future value remaining after the final payment has been made.")),a("end_or_beginning (number, default=0)",v("The timing of the payment payments are due for each period."),Gu)],compute:function(e,t,r,n,o={value:0},s={value:0}){return{value:mh(kt(e,this.locale),kt(t,this.locale),kt(r,this.locale),kt(n,this.locale),kt(o,this.locale),qt(s)?1:0),format:"#,##0.00"}},isExported:!0},bh={description:v("Internal rate of return given periodic cashflows."),args:[a("cashflow_amounts (number, range<number>)",v("An array or range containing the income or payments associated with the investment.")),a("rate_guess (number, default=0.1)",v("An estimate for what the internal rate of return will be."))],compute:function(e,t={value:.1}){const r=kt(t,this.locale);if(r<=-1)return new S(Lc(r));let n=!1,o=!1;const s=[];if(Kt([e],({value:e})=>{e>0&&(n=!0),e<0&&(o=!0),s.push(e)},this.locale),!n||!o)return new S(mc);const i=s.shift();return{value:qu(function(e){return function(e,t,r){const n=r.length;let o=0;return r.reduce((t,r)=>(o++,t+r*e**(n-o)),t*e**n)}(e,i,s)},function(e){return function(e,t,r){const n=r.length;let o=0;return r.reduce((t,r)=>(o++,t+r*(n-o)*e**(n-o-1)),t*n*e**(n-1))}(e,i,s)},r+1,20,1e-5)-1,format:"0%"}},isExported:!0},vh={description:v("Returns the interest paid at a particular period of an investment."),args:[a("rate (number)",v("The interest rate.")),a("period (number)",v("The period for which you want to view the interest payment.")),a("number_of_periods (number)",v("The number of payments to be made.")),a("present_value (number)",v("The current value of the annuity."))],compute:function(e,t,r,n){const o=kt(e,this.locale),s=kt(t,this.locale),i=kt(r,this.locale),a=kt(n,this.locale);if(0===i)return new S(v("The number_of_periods (%s) must be different from zero.",i));return-1*(a-a*(s/i))*o},isExported:!0},yh={description:v("Modified Macaulay duration."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("rate (number)",v("The annualized rate of interest.")),a("yield (number)",v("The expected annual yield of the security.")),a("frequency (number)",v("The number of interest or coupon payments per year (1, 2, or 4)."),$u),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."))],compute:function(e,t,r,n,o,s={value:0}){const i=ch.compute.bind(this)(e,t,r,n,o,s),a=kt(n,this.locale),l=Math.trunc(kt(o,this.locale));return kt(i,this.locale)/(1+a/l)},isExported:!0},Eh={description:v("Modified internal rate of return."),args:[a("cashflow_amounts (range<number>)",v("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),a("financing_rate (number)",v("The interest rate paid on funds invested.")),a("reinvestment_return_rate (number)",v("The return (as a percentage) earned on reinvestment of income received from the investment."))],compute:function(e,t,r){const n=kt(t,this.locale),o=kt(r,this.locale),s=or(e).flat().filter(e=>null!==e.value).map(e=>kt(e,this.locale)),i=s.length;let a=0,l=0;for(const e of le(0,i)){const t=s[e];t>=0?a+=t*(o+1)**(i-e-1):l+=t/(n+1)**e}if(0===l||0===a)return new S(mc);return(-a/l)**(1/(i-1))-1},isExported:!0},wh={description:v("Annual nominal interest rate."),args:[a("effective_rate (number)",v("The effective interest rate per year.")),a("periods_per_year (number)",v("The number of compounding periods per year."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));return r<=0?new S(v("The effective_rate (%s) must be strictly positive.",r)):n<=0?new S(Dc(n)):(Math.pow(r+1,1/n)-1)*n},isExported:!0},Sh={description:v("Number of payment periods for an investment."),args:[a("rate (number)",v("The interest rate.")),a("payment_amount (number)",v("The amount of each payment made.")),a("present_value (number)",v("The current value of the annuity.")),a("future_value (number, default=0)",v("The future value remaining after the final payment has been made.")),a("end_or_beginning (number, default=0)",v("The timing of the payment payments are due for each period."),Gu)],compute:function(e,t,r,n={value:0},o={value:0}){n=n||0,o=o||0;const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=qt(o)?1:0;if(0===s)return-(l+a)/i;const u=i*(1+s*c)/s;return Math.log((u-l)/(a+u))/Math.log(1+s)},isExported:!0};function Ch(e,t,r,n){let o=0;return er(r,(t,r)=>(o++,t+r/(1+e)**o),t,n)}const Th={description:v("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[a("discount (number)",v("The discount rate of the investment over one period.")),a("cashflow (number, range<number>, repeating)",v("The future cash flows."))],compute:function(e,...t){const r=kt(e,this.locale);return-1===r?new S((e=>v("The discount (%s) must be different from -1.",e))(r)):{value:Ch(r,0,t,this.locale),format:"#,##0.00"}},isExported:!0},Ih={description:v("Computes the number of periods needed for an investment to reach a value."),args:[a("rate (number)",v("The rate at which the investment grows each period.")),a("present_value (number)",v("The investment's current value.")),a("future_value (number)",v("The investment's desired future value."))],compute:function(e,t,r){const n=kt(e,this.locale),o=kt(t,this.locale),s=kt(r,this.locale);return n<=0?new S(kc(n)):o<=0?new S(Mc(o)):s<=0?new S(v("The future_value (%s) must be strictly positive.",s)):(Math.log(s)-Math.log(o))/Math.log(1+n)},isExported:!0};function xh(e,t,r,n,o){if(t<=0)throw new S(_c(t));if(0===e)return-(n+r)/t;let s=-(r*(1+e)**t+n);return s=s*e/((1+e*o)*((1+e)**t-1)),s}const Rh={description:v("Periodic payment for an annuity investment."),args:[a("rate (number)",v("The annualized rate of interest.")),a("number_of_periods (number)",v("The number of payments to be made.")),a("present_value (number)",v("The current value of the annuity.")),a("future_value (number, default=0)",v("The future value remaining after the final payment has been made.")),a("end_or_beginning (number, default=0)",v("The timing of the payment payments are due for each period."),Gu)],compute:function(e,t,r,n={value:0},o={value:0}){const s=kt(t,this.locale),i=kt(e,this.locale),a=qt(o)?1:0,l=kt(n,this.locale);return{value:xh(i,s,kt(r,this.locale),l,a),format:"#,##0.00"}},isExported:!0};function Ah(e,t,r,n,o,s){if(r<=0)throw new S(_c(r));if(t<=0||t>r)throw new S(v("The period must be between 1 and number_of_periods (%s)",r));const i=xh(e,r,n,o,s);if(1===s&&1===t)return i;return i+-hh(e,0===s?t-1:t-2,i,n+i*s,0)*e}const Oh={description:v("Payment on the principal of an investment."),args:[a("rate (number)",v("The annualized rate of interest.")),a("period (number)",v("The amortization period, in terms of number of periods.")),a("number_of_periods (number)",v("The number of payments to be made.")),a("present_value (number)",v("The current value of the annuity.")),a("future_value (number, default=0)",v("The future value remaining after the final payment has been made.")),a("end_or_beginning (number, default=0)",v("The timing of the payment payments are due for each period."),Gu)],compute:function(e,t,r,n,o={value:0},s={value:0}){const i=kt(r,this.locale),a=kt(e,this.locale),l=kt(t,this.locale),c=qt(s)?1:0,u=kt(o,this.locale);return{value:Ah(a,l,i,kt(n,this.locale),u,c),format:"#,##0.00"}},isExported:!0},_h={description:v("Present value of an annuity investment."),args:[a("rate (number)",v("The interest rate.")),a("number_of_periods (number)",v("The number of payments to be made.")),a("payment_amount (number)",v("The amount per period to be paid.")),a("future_value (number, default=0)",v("The future value remaining after the final payment has been made.")),a("end_or_beginning (number, default=0)",v("The timing of the payment payments are due for each period."),Gu)],compute:function(e,t,r,n={value:0},o={value:0}){n=n||0,o=o||0;const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=qt(o)?1:0;return{value:s?-(a*(1+s*c)*((1+s)**i-1)/s+l)/(1+s)**i:-(l+a*i),format:"#,##0.00"}},isExported:!0},Dh={description:v("Price of a security paying periodic interest."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("rate (number)",v("The annualized rate of interest.")),a("yield (number)",v("The expected annual yield of the security.")),a("redemption (number)",v("The redemption amount per 100 face value, or par.")),a("frequency (number)",v("The number of interest or coupon payments per year (1, 2, or 4)."),$u),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o,s,i={value:0}){i=i||0;const a=Math.trunc(kt(e,this.locale)),l=Math.trunc(kt(t,this.locale)),c=kt(r,this.locale),u=kt(n,this.locale),h=kt(o,this.locale),d=Math.trunc(kt(s,this.locale)),f=Math.trunc(kt(i,this.locale));if(a>=l)return new S(Oc(a,l));if(qc(d))return new S(bc(d));if(Wc(f))return new S(vc(f));if(c<0)return new S(Pc(c));if(u<0)return new S($c(u));if(h<=0)return new S(Uc(h));const g=St(a,l,f)*d,m=Math.ceil(g),p=g-Math.floor(g)||1,b=1+u/d,v=100*c/d;if(1===m)return(v+h)/(p*u/d+1)-v*(1-p);let y=0;for(let e=1;e<=m;e++)y+=v/b**(e-1+p);return h/b**(m-1+p)+y-v*(1-p)},isExported:!0},Fh={description:v("Price of a discount security."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("discount (number)",v("The discount rate of the security at time of purchase.")),a("redemption (number)",v("The redemption amount per 100 face value, or par.")),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(Oc(s,i));if(Wc(c))return new S(vc(c));if(a<=0)return new S(Ec(a));if(l<=0)return new S(Uc(l));return l-a*l*St(s,i,c)},isExported:!0},Nh={description:v("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("issue (date)",v("The date the security was initially issued.")),a("rate (number)",v("The annualized rate of interest.")),a("yield (number)",v("The expected annual yield of the security.")),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o,s={value:0}){s=s||0;const i=Math.trunc(kt(e,this.locale)),a=Math.trunc(kt(t,this.locale)),l=Math.trunc(kt(r,this.locale)),c=kt(n,this.locale),u=kt(o,this.locale),h=Math.trunc(kt(s,this.locale));if(i<=l)return new S(((e,t)=>v("The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).",{settlement:e,issue:t}))(i,l));if(i>=a)return new S(Oc(i,a));if(Wc(h))return new S(vc(h));if(c<0)return new S(Pc(c));if(u<0)return new S($c(u));const d=St(i,a,h),f=St(i,l,h);return(100+St(l,a,h)*c*100)/(1+d*u)-f*c*100},isExported:!0},Mh=.1,Vh={description:v("Interest rate of an annuity investment."),args:[a("number_of_periods (number)",v("The number of payments to be made.")),a("payment_per_period (number)",v("The amount per period to be paid.")),a("present_value (number)",v("The current value of the annuity.")),a("future_value (number, default=0)",v("The future value remaining after the final payment has been made.")),a("end_or_beginning (number, default=0)",v("The timing of the payment payments are due for each period."),Gu),a("rate_guess (number, default=0.1)",v("An estimate for what the interest rate will be."))],compute:function(e,t,r,n={value:0},o={value:0},s={value:Mh}){const i=kt(e,this.locale),a=kt(t,this.locale),l=qt(o)?1:0,c=kt(s,this.locale)||Mh;let u=kt(n,this.locale),h=kt(r,this.locale);if(i<=0)return new S(_c(i));if(!Gc([a,h,u]))return new S(v("There must be both positive and negative values in [payment_amount, present_value, future_value]."));if(c<=-1)return new S(Lc(c));u-=a*l,h+=a*l;return{value:qu(e=>{const t=Math.pow(1+e,i);return u+h*t+a*((t-1)/e)},e=>{const t=Math.pow(1+e,i-1),r=Math.pow(1+e,i);return h*i*t+a*(i*t/e-(r-1)/e/e)},c,40,1e-5),format:"0%"}},isExported:!0},Lh={description:v("Amount received at maturity for a security."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("investment (number)",v("The amount invested (irrespective of face value of each security).")),a("discount (number)",v("The discount rate of the security invested in.")),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(Oc(s,i));if(Wc(c))return new S(vc(c));if(a<=0)return new S(Ic(a));if(l<=0)return new S(Ec(l));return a/(1-l*St(s,i,c))},isExported:!0},Ph={description:v("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[a("number_of_periods (number)",v("The number of periods.")),a("present_value (number)",v("The present value of the investment.")),a("future_value (number)",v("The future value of the investment."))],compute:function(e,t,r){const n=kt(e,this.locale),o=kt(t,this.locale),s=kt(r,this.locale);return n<=0?new S(_c(n)):(s/o)**(1/n)-1},isExported:!0},kh={description:v("Depreciation of an asset using the straight-line method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated."))],compute:function(e,t,r){return{value:(kt(e,this.locale)-kt(t,this.locale))/kt(r,this.locale),format:"#,##0.00"}},isExported:!0},Uh={description:v("Depreciation via sum of years digit method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("period (number)",v("The single period within life for which to calculate depreciation."))],compute:function(e,t,r,n){const o=kt(e,this.locale),s=kt(t,this.locale),i=kt(r,this.locale),a=kt(n,this.locale);if(a<=0)return new S(Nc(a));if(i<=0)return new S(Ac(i));if(a>i)return new S(Fc(a,i));return{value:(i-a+1)/(i*(i+1)/2)*(o-s),format:"#,##0.00"}},isExported:!0};function Hh(e,t,r){return 100*(1-r*St(e,t,2))}const Bh={description:v("Price of a US Treasury bill."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("discount (number)",v("The discount rate of the bill at time of purchase."))],compute:function(e,t,r){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=kt(r,this.locale);return n>=o?new S(Oc(n,o)):Zc(n,o,this.locale)?s<=0?new S(Ec(s)):s>=1?new S(wc(s)):Hh(n,o,s):new S(Bc(n,o))},isExported:!0},zh={description:v("Equivalent rate of return for a US Treasury bill."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("discount (number)",v("The discount rate of the bill at time of purchase."))],compute:function(e,t,r){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=kt(r,this.locale);if(n>=o)return new S(Oc(n,o));if(!Zc(n,o,this.locale))return new S(Bc(n,o));if(s<=0)return new S(Ec(s));if(s>=1)return new S(wc(s));const i=eu.compute.bind(this)({value:o},{value:n});if(i<=182)return 365*s/(360-s*i);const a=Hh(n,o,s)/100,l=i/(366===i?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},$h={description:v("The yield of a US Treasury bill based on price."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("price (number)",v("The price at which the security is bought per 100 face value."))],compute:function(e,t,r){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=kt(r,this.locale);if(n>=o)return new S(Oc(n,o));if(!Zc(n,o,this.locale))return new S(Bc(n,o));if(s<=0)return new S(Vc(s));return(100-s)/s*(1/St(n,o,2))},isExported:!0},Gh=!1,Wh={description:v("Variable declining balance. WARNING : does not handle decimal periods."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("start (number)",v("Starting period to calculate depreciation.")),a("end (number)",v("Ending period to calculate depreciation.")),a("factor (number, default=2)",v("The number of months in the first year of depreciation.")),a("no_switch (number, default=false)",v("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."),[{value:!1,label:v("Switch to straight-line depreciation")},{value:!0,label:v("Do not switch to straight-line depreciation")}])],compute:function(e,t,r,n,o,s={value:2},i={value:Gh}){s=s||0;const a=kt(e,this.locale),l=kt(t,this.locale),c=kt(r,this.locale),u=Math.trunc(kt(n,this.locale)),h=Math.trunc(kt(o,this.locale)),d=kt(s,this.locale),f=qt(i);if(a<0)return new S(pc(a));if(l<0)return new S(Hc(l));if(c<=0)return new S(Ac(c));if(u<0)return new S((e=>v("The start_period (%s) must be positive or null.",e))(u));if(h<0)return new S((e=>v("The end_period (%s) must be positive or null.",e))(h));if(u>h)return new S(v("The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).",{start:u,end:h}));if(h>c)return new S(((e,t)=>v("The end_period (%(end)s) must be smaller or equal to the life (%(life)s).",{end:e,life:t}))(h,c));if(d<=0)return new S(yc(d));if(0===a)return 0;if(l>=a)return u<1?a-l:0;const g=d/c;if(g>=1)return u<1?a-l:0;let m=a,p=0,b=0,y=!1;for(let e=0;e<h;e++){if(!y||f){const t=m*g,r=(m-l)/(c-e);!f&&r>t?(y=!0,p=r):p=t}const t=Math.max(m-p,l);e>=u&&(b+=m-t),m=t}return b},isExported:!0},qh={description:v("Internal rate of return given non-periodic cash flows."),args:[a("cashflow_amounts (range<number>)",v("An range containing the income or payments associated with the investment.")),a("cashflow_dates (range<number>)",v("An range with dates corresponding to the cash flows in cashflow_amounts.")),a("rate_guess (number, default=0.1)",v("An estimate for what the internal rate of return will be."))],compute:function(e,t,r={value:Mh}){const n=kt(r,this.locale);if(!Sn(e,t))return new S(gc);const o=e.flat().map(e=>kt(e,this.locale)),s=t.flat().map(e=>kt(e,this.locale));if(!Gc(o))return new S(mc);if(s.some(e=>e<s[0]))return new S(Sc(s[0]));if(n<=-1)return new S(Lc(n));const i=new Map;for(const e of le(0,s.length)){const t=s[e];i.has(t)?i.set(t,i.get(t)+o[e]):i.set(t,o[e])}const a=Array.from(i.keys()),l=a.map(e=>i.get(e));return qu(e=>{let t=l[0];for(const r of le(1,l.length)){const n=(a[0]-a[r])/365;t+=l[r]*(1+e)**n}return t},e=>{let t=0;for(const r of le(1,l.length)){const n=(a[0]-a[r])/365;t+=n*l[r]*(1+e)**(n-1)}return t},n,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},Zh={description:v("Net present value given to non-periodic cash flows.."),args:[a("discount (number)",v("The discount rate of the investment over one period.")),a("cashflow_amounts (number, range<number>)",v("An range containing the income or payments associated with the investment.")),a("cashflow_dates (number, range<number>)",v("An range with dates corresponding to the cash flows in cashflow_amounts."))],compute:function(e,t,r){const n=kt(e,this.locale);if(!Sn(t,r))return new S(gc);const o=mr(t).flat().map(e=>Ht(e,this.locale)),s=mr(r).flat().map(e=>Ht(e,this.locale));if(s.some(e=>e<s[0]))return new S(Sc(s[0]));if(n<=0)return new S(kc(n));if(1===o.length)return o[0];const i=new Map;for(const e of le(0,s.length)){const t=s[e];i.has(t)?i.set(t,i.get(t)+o[e]):i.set(t,o[e])}const a=Array.from(i.keys()),l=a.map(e=>i.get(e));let c=l[0];for(const e of le(1,l.length)){const t=(a[0]-a[e])/365;c+=l[e]*(1+n)**t}return c},isExported:!0},Yh={description:v("Annual yield of a security paying periodic interest."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("rate (number)",v("The annualized rate of interest.")),a("price (number)",v("The price at which the security is bought per 100 face value.")),a("redemption (number)",v("The redemption amount per 100 face value, or par.")),a("frequency (number)",v("The number of interest or coupon payments per year (1, 2, or 4)."),$u),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o,s,i={value:0}){i=i||0;const a=Math.trunc(kt(e,this.locale)),l=Math.trunc(kt(t,this.locale)),c=kt(r,this.locale),u=kt(n,this.locale),h=kt(o,this.locale),d=Math.trunc(kt(s,this.locale)),f=Math.trunc(kt(i,this.locale));if(a>=l)return new S(Oc(a,l));if(qc(d))return new S(bc(d));if(Wc(f))return new S(vc(f));if(c<0)return new S(Pc(c));if(u<=0)return new S(Vc(u));if(h<=0)return new S(Uc(h));const g=St(a,l,f)*d,m=Math.ceil(g),p=g-Math.floor(g)||1,b=100*c/d;if(1===m){const e=u+b*(1-p);return(h+b-e)*d*(1/p)/e}const v=qu(function(e){return function(e,t,r,n,o,s){let i=s-(e+o*(1-t))*n**(r-1+t);for(let e=1;e<=r;e++)i+=o*n**(e-1);return i}(u,p,m,e,b,h)},function(e){return function(e,t,r,n,o){let s=-(e+o*(1-t))*(r-1+t)*n**(r-2+t);for(let e=1;e<=r;e++)s+=o*(e-1)*n**(e-2);return s}(u,p,m,e,b)},1+(c+1)/d,100,1e-5);return(v-1)*d},isExported:!0},jh={description:v("Annual yield of a discount security."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("price (number)",v("The price at which the security is bought per 100 face value.")),a("redemption (number)",v("The redemption amount per 100 face value, or par.")),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(Oc(s,i));if(Wc(c))return new S(vc(c));if(a<=0)return new S(Vc(a));if(l<=0)return new S(Uc(l));return(l/a-1)/St(s,i,c)},isExported:!0},Xh={description:v("Annual yield of a security paying interest at maturity."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("issue (date)",v("The date the security was initially issued.")),a("rate (number)",v("The annualized rate of interest.")),a("price (number)",v("The price at which the security is bought.")),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Yc)],compute:function(e,t,r,n,o,s={value:0}){s=s||0;const i=Math.trunc(kt(e,this.locale)),a=Math.trunc(kt(t,this.locale)),l=Math.trunc(kt(r,this.locale)),c=kt(n,this.locale),u=kt(o,this.locale),h=Math.trunc(kt(s,this.locale));if(i>=a)return new S(Oc(i,a));if(Wc(h))return new S(vc(h));if(i<l)return new S(((e,t)=>v("The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).",{settlement:e,issue:t}))(i,l));if(c<0)return new S(Pc(c));if(u<=0)return new S(Vc(u));return(100*(1+c*St(l,a,h))/(u+100*c*St(l,i,h))-1)/St(i,a,h)},isExported:!0};var Kh=Object.freeze({__proto__:null,ACCRINTM:Zu,AMORLINC:Yu,COUPDAYBS:Xu,COUPDAYS:ju,COUPDAYSNC:Ku,COUPNCD:Qu,COUPNUM:Ju,COUPPCD:eh,CUMIPMT:th,CUMPRINC:rh,DB:nh,DDB:sh,DISC:ih,DOLLARDE:ah,DOLLARFR:lh,DURATION:ch,EFFECT:uh,FV:dh,FVSCHEDULE:fh,INTRATE:gh,IPMT:ph,IRR:bh,ISPMT:vh,MDURATION:yh,MIRR:Eh,NOMINAL:wh,NPER:Sh,NPV:Th,PDURATION:Ih,PMT:Rh,PPMT:Oh,PRICE:Dh,PRICEDISC:Fh,PRICEMAT:Nh,PV:_h,RATE:Vh,RECEIVED:Lh,RRI:Ph,SLN:kh,SYD:Uh,TBILLEQ:zh,TBILLPRICE:Bh,TBILLYIELD:$h,VDB:Wh,XIRR:qh,XNPV:Zh,YIELD:Yh,YIELDDISC:jh,YIELDMAT:Xh});const Qh=[{value:"address",label:v("Returns an absolute reference as plain text of the top left cell in reference.")},{value:"col",label:v("Returns the column number of the cell in reference.")},{value:"contents",label:v("Returns the value contained in the top left cell in reference.")},{value:"format",label:v("Returns the format of the top left cell in reference.")},{value:"row",label:v("Returns the row number of the top left cell in reference.")},{value:"type",label:v('Returns the type of data in the cell in reference. The following values are returned: "b" for a blank cell, "l" (for label) if the cell contains plain text, and "v" (for value) if the cell contains any other type of data.')}],Jh={description:v("Gets information about a cell."),args:[a("info_type (string)",v("The type of information requested."),Qh),a("reference (meta, range<meta>)",v("The reference to the cell."))],compute:function(e,t){const r=$t(e).toLowerCase();if(!Qh.map(e=>e.value).includes(r))return new S(v("The info_type should be one of %s.",Qh.join(", ")));const n=this.__originSheetId,o=t[0][0].value;let{sheetName:s,xc:i}=To(o);s=s===this.getters.getSheetName(n)?void 0:s;const a=Io(s,Ro(i,"colrow")),l=this.getters.getRangeFromSheetXC(n,a);switch(r){case"address":return this.getters.getRangeString(l,n);case"col":return l.zone.left+1;case"contents":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top};return this.getters.getEvaluatedCell(e).value}case"format":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top};return this.getters.getEvaluatedCell(e).format||""}case"row":return l.zone.top+1;case"type":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top},t=this.getters.getEvaluatedCell(e).type;return t===Nu.empty?"b":t===Nu.text?"l":"v"}}return""},isExported:!0},ed={description:v("Whether a value is an error other than #N/A."),args:[a("value (any)",v("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return Vt(t)&&t!==E.NotAvailable},isExported:!0},td={description:v("Whether a value is an error."),args:[a("value (any)",v("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return Vt(t)},isExported:!0},rd={description:v("Whether a value is `true` or `false`."),args:[a("value (any)",v("The value to be verified as a logical TRUE or FALSE."))],compute:function(e){return"boolean"==typeof e?.value},isExported:!0},nd={description:v("Whether a value is the error #N/A."),args:[a("value (any)",v("The value to be verified as an error type."))],compute:function(e){return e?.value===E.NotAvailable},isExported:!0},od={description:v("Whether a value is non-textual."),args:[a("value (any)",v("The value to be checked."))],compute:function(e){return!id.compute.bind(this)(e)},isExported:!0},sd={description:v("Whether a value is a number."),args:[a("value (any)",v("The value to be verified as a number."))],compute:function(e){return"number"==typeof e?.value},isExported:!0},id={description:v("Whether a value is text."),args:[a("value (any)",v("The value to be verified as text."))],compute:function(e){return"string"==typeof e?.value&&!1===Vt(e?.value)},isExported:!0},ad={description:v("Whether the referenced cell is empty"),args:[a("value (any)",v("Reference to the cell that will be checked for emptiness."))],compute:function(e){return null===e?.value},isExported:!0},ld={description:v("Returns the error value #N/A."),args:[],compute:function(){return{value:E.NotAvailable}},isExported:!0};var cd=Object.freeze({__proto__:null,CELL:Jh,ISBLANK:ad,ISERR:ed,ISERROR:td,ISLOGICAL:rd,ISNA:nd,ISNONTEXT:od,ISNUMBER:sd,ISTEXT:id,NA:ld});function ud(e){let t=!1,r=!0;return ir(e,e=>(t=!0,r=r&&e,r)),{foundBoolean:t,result:r}}function hd(e){let t=!1,r=!1;return ir(e,e=>(t=!0,r=r||e,!r)),{foundBoolean:t,result:r}}const dd={description:v("Logical `and` operator."),args:[a("logical_expression (boolean, range<boolean>, repeating)",v("Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value."))],compute:function(...e){const{result:t,foundBoolean:r}=ud(e);return r?t:new S(vr)},isExported:!0},fd={description:v("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},gd={description:v("Returns value depending on logical expression."),args:[a("logical_expression (boolean, range<boolean>)",v("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),a("value_if_true (any, range)",v("The value the function returns if logical_expression is TRUE.")),a("value_if_false (any, range, default=FALSE)",v("The value the function returns if logical_expression is FALSE."))],compute:function(e,t,r){if(Dn(e))return sr(gd.compute,[e,t,r]);return(qt(On(e))?t:r)??{value:0}},isExported:!0},md={description:v("Value if it is not an error, otherwise 2nd argument."),args:[a("value (any, range)",v("The value to return if value itself is not an error.")),a('value_if_error (any, range, default="empty")',v("The value the function returns if value is an error."))],compute:function(e,t){if(Dn(e))return sr(md.compute,[e,t]);return(Vt(On(e)?.value)?t:e)??{value:0}},isExported:!0},pd={description:v("Value if it is not an #N/A error, otherwise 2nd argument."),args:[a("value (any, range)",v("The value to return if value itself is not #N/A an error.")),a('value_if_error (any, range, default="empty")',v("The value the function returns if value is an #N/A error."))],compute:function(e,t){if(Dn(e))return sr(pd.compute,[e,t]);return(On(e)?.value===E.NotAvailable?t:e)??{value:0}},isExported:!0},bd={description:v("Returns a value depending on multiple logical expressions."),args:[a("condition (any, range, repeating)",v("The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.")),a("value (any, range, repeating)",v("The value to be returned if its corresponding condition is TRUE."))],compute:function(...e){if(e.length%2!=0)return new S(v("Wrong number of arguments. Expected an even number of arguments."));for(;e.length>0;){if(Dn(e[0]))return sr(bd.compute,e);const t=qt(On(e.shift())),r=e.shift();if(t)return r??{value:0}}return new S(v("No match."))},isExported:!0},vd={description:v("Returns opposite of provided logical value."),args:[a("logical_expression (boolean)",v("An expression or reference to a cell holding an expression that represents some logical value."))],compute:function(e){return!qt(e)},isExported:!0},yd={description:v("Logical `or` operator."),args:[a("logical_expression (boolean, range<boolean>, repeating)",v("Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value."))],compute:function(...e){const{result:t,foundBoolean:r}=hd(e);return r?t:new S(vr)},isExported:!0},Ed={description:v("Returns a value by comparing cases to an expression."),args:[a("expression (number, boolean, string)",v("The value to be checked.")),a("case (any, repeating)",v("Case to be checked against expression.")),a("value (any, repeating)",v("Value to be returned if its corresponding case matches expression.")),a('default (any, default="empty")',v("An optional default value to be returned if none of the cases match expression."))],compute:function(e,...t){const r=t.length%2==0?Lt(e):t.pop();for(let r=0;r<t.length;r+=2){const n=t[r];if(n&&Vt(n.value))return n;if(e?.value===n?.value)return t[r+1]||{value:0}}return r||{value:0}},isExported:!0},wd={description:v("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},Sd={description:v("Logical `xor` operator."),args:[a("logical_expression (boolean, range<boolean>, repeating)",v("Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value."))],compute:function(...e){let t=!1,r=!1;return ir(e,e=>(t=!0,r=r?!e:e,!0)),t?r:new S(vr)},isExported:!0};var Cd=Object.freeze({__proto__:null,AND:dd,FALSE:fd,IF:gd,IFERROR:md,IFNA:pd,IFS:bd,NOT:vd,OR:yd,SWITCH:Ed,TRUE:wd,XOR:Sd});v("The range is invalid"),v("The argument is missing. Please provide a value"),v("The second argument is missing. Please provide a value"),v("The minpoint must be a number"),v("The midpoint must be a number"),v("The maxpoint must be a number"),v("The first value must be a number"),v("The second value must be a number"),v("Minimum must be smaller then Maximum"),v("Minimum must be smaller then Midpoint"),v("Midpoint must be smaller then Maximum"),v("Lower inflection point must be smaller than upper inflection point"),v("Invalid Minpoint formula"),v("Invalid Maxpoint formula"),v("Invalid Midpoint formula"),v("Invalid upper inflection point formula"),v("Invalid lower inflection point formula"),v("A range needs to be defined"),v("At least one of the provided values is an invalid formula"),v("The rule is invalid for an unknown reason"),v("Color scale"),v("Icon set"),v("Data bar"),v("Series"),v("Background color"),v("Stacked bar chart"),v("Stacked line chart"),v("Stacked area chart"),v("Stacked column chart"),v("Cumulative data"),v("Treat labels as text"),v("Aggregate"),v("The chart definition is invalid for an unknown reason"),v("The dataset is invalid"),v("Labels are invalid"),v("The key value is invalid"),v("The baseline value is invalid"),v("The data range is invalid"),v("A minimum range limit value is needed"),v("The minimum range limit value must be a number"),v("A maximum range limit value is needed"),v("The maximum range limit value must be a number"),v("The lower inflection point value must be a number"),v("The upper inflection point value must be a number"),v("Blues"),v("Cividis"),v("Custom"),v("Greens"),v("Greys"),v("Oranges"),v("Purples"),v("Rainbow"),v("Reds"),v("Viridis"),v("Custom"),v("Merged cells are preventing this operation. Unmerge those cells and try again."),v("The header row of a table can't be moved."),v("Cannot split the selection for an unknown reason"),v("There is no match for the selected separator in the selection"),v("Only a selection from a single column can be split"),v("Splitting will overwrite existing content"),v("Cannot remove duplicates for an unknown reason"),v("Please select only one range of cells"),v("Please select a range of cells containing values."),v("Please select at latest one column to analyze."),v("This operation is not possible due to a merge. Please remove the merges first than try again.");const Td={DateIs:{today:v("today"),yesterday:v("yesterday"),tomorrow:v("tomorrow"),lastWeek:v("in the past week"),lastMonth:v("in the past month"),lastYear:v("in the past year")},DateIsBefore:{today:v("today"),yesterday:v("yesterday"),tomorrow:v("tomorrow"),lastWeek:v("one week ago"),lastMonth:v("one month ago"),lastYear:v("one year ago")},CriterionError:{notEmptyValue:v("The value must not be empty"),numberValue:v("The value must be a number"),dateValue:v("The value must be a date"),validRange:v("The value must be a valid range"),validFormula:v("The formula must be valid")},Errors:{InvalidRange:v("The range is invalid."),InvalidDataValidationCriterionValue:v("One or more of the provided criteria values are invalid. Please review and correct them."),InvalidNumberOfCriterionValues:v("One or more of the provided criteria values are missing."),Unexpected:v("The rule is invalid for an unknown reason.")}};v("The table zone is invalid for an unknown reason"),v("You cannot create overlapping tables."),v("A table can only be created on a continuous selection."),v("The range is invalid"),v("The range is out of the sheet"),v("Filter button"),v("Header row(s)"),v("Banded rows"),v("First column"),v("Last column"),v("Banded columns"),v("Automatically autofill formulas"),v("Total row"),v("Auto-adjust to formula result"),v("Cannot have filters without a header row"),v("For tables based on array formulas only"),v("No calculations"),v("% of grand total"),v("% of column total"),v("% of row total"),v("% of"),v("% of parent row total"),v("% of parent column total"),v("% of parent total"),v("Difference from"),v("% difference from"),v("Running total"),v("% Running total"),v("Rank smallest to largest"),v("Rank largest to smallest"),v("Index"),v("Displays the value that is entered in the field."),v("Displays values as a percentage of the grand total of all the values or data points in the report."),v("Displays all the values in each column or series as a percentage of the total for the column or series."),v("Displays the value in each row or category as a percentage of the total for the row or category."),v("Displays values as a percentage of the value of the Base item in the Base field."),v("Calculates values as follows:\n(value for the item) / (value for the parent item on rows)"),v("Calculates values as follows:\n(value for the item) / (value for the parent item on columns)"),v("Calculates values as follows:\n(value for the item) / (value for the parent item of the selected Base field)"),v("Displays values as the difference from the value of the Base item in the Base field."),v("Displays values as the percentage difference from the value of the Base item in the Base field."),v("Displays the value for successive items in the Base field as a running total."),v("Calculates the value as a percentage for successive items in the Base field that are displayed as a running total."),v("Displays the rank of selected values in a specific field, listing the smallest item in the field as 1, and each larger value with a higher rank value."),v("Displays the rank of selected values in a specific field, listing the largest item in the field as 1, and each smaller value with a higher rank value."),v("Calculates values as follows:\n((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row Total) x (Grand Column Total))");class Id{content={};add(e,t){if(e in this.content)throw new Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(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)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}}const xd=new Id;function Rd(e){return xd.get(e)}const Ad={normalizeFunctionValue:e=>kt(e,xr),toValueAndFormat:(e,t)=>({value:kt(e,xr),format:"dd mmm yyyy"}),toFunctionValue(e){const t=Zt(e,xr);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},Od={normalizeFunctionValue(e){const t=kt(e,xr);if(t<1||t>31)throw new S(v("%s is not a valid day of month (it should be a number between 1 and 31)",t));return t},toValueAndFormat:e=>({value:kt(e,xr),format:"0"}),toFunctionValue:e=>`${e}`},_d={normalizeFunctionValue(e){const t=kt(e,xr);if(t<1||t>7)throw new S(v("%s is not a valid day of week (it should be a number between 1 and 7)",t));return t},toValueAndFormat(e,t){const r=(e-1+(t||xr).weekStart)%7;return{value:jr[r].toString(),format:"@"}},toFunctionValue:e=>`${e}`},Dd={normalizeFunctionValue(e){const t=kt(e,xr);if(t<0||t>53)throw new S(v("%s is not a valid week (it should be a number between 0 and 53)",t));return t},toValueAndFormat:e=>({value:kt(e,xr),format:"0"}),toFunctionValue:e=>`${e}`},Fd={normalizeFunctionValue(e){const t=kt(e,xr);if(t<1||t>12)throw new S(v("%s is not a valid month (it should be a number between 1 and 12)",t));return t},toValueAndFormat:e=>({value:Yr[kt(e,xr)-1].toString(),format:"@"}),toFunctionValue:e=>`${e}`},Nd={normalizeFunctionValue:e=>Xr(kt(e,xr),{locale:xr,format:"mm/yyyy"}),toValueAndFormat:e=>({value:kt(e,xr),format:"mmmm yyyy"}),toFunctionValue(e){const t=Zt(e,xr);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`}},Md={normalizeFunctionValue(e){const t=kt(e,xr);if(t<1||t>4)throw new S(v("%s is not a valid quarter (it should be a number between 1 and 4)",t));return t},toValueAndFormat:e=>({value:v("Q%(quarter_number)s",{quarter_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},Vd={normalizeFunctionValue(e){const t=kt(e,xr);return t>3e3?Zt(t,xr).getFullYear():t},toValueAndFormat:e=>({value:kt(e,xr),format:"0"}),toFunctionValue:e=>`${e}`},Ld={normalizeFunctionValue(e){const t=kt(e,xr);if(t<0||t>23)throw new S(v("%s is not a valid hour (it should be a number between 0 and 23)",t));return t},toValueAndFormat:e=>({value:v("%(hour_number)sh",{hour_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},Pd={normalizeFunctionValue(e){const t=kt(e,xr);if(t<0||t>59)throw new S(v("%s is not a valid minute (it should be a number between 0 and 59)",t));return t},toValueAndFormat:e=>({value:v("%(minute_number)s'",{minute_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},kd={normalizeFunctionValue(e){const t=kt(e,xr);if(t<0||t>59)throw new S(v("%s is not a valid second (it should be a number between 0 and 59)",t));return t},toValueAndFormat:e=>({value:v("%(second_number)s''",{second_number:e}),format:"@"}),toFunctionValue:e=>`${e}`};function Ud(e){return{normalizeFunctionValue:t=>null===t?null:e.normalizeFunctionValue(t),toValueAndFormat:(t,r)=>null===t?{value:v("(Undefined)")}:e.toValueAndFormat(t,r),toFunctionValue:t=>null===t?"false":e.toFunctionValue(t)}}xd.add("day",Ud(Ad)).add("year",Ud(Vd)).add("day_of_month",Ud(Od)).add("iso_week_number",Ud(Dd)).add("month_number",Ud(Fd)).add("month",Ud(Nd)).add("quarter_number",Ud(Md)).add("day_of_week",Ud(_d)).add("hour_number",Ud(Ld)).add("minute_number",Ud(Pd)).add("second_number",Ud(kd));const Hd={displayTotals:!0,displayColumnHeaders:!0,displayMeasuresRow:!0,numberOfRows:Number.MAX_VALUE,numberOfColumns:Number.MAX_VALUE},Bd={count:v("Count"),count_distinct:v("Count Distinct"),bool_and:v("Boolean And"),bool_or:v("Boolean Or"),max:v("Maximum"),min:v("Minimum"),avg:v("Average"),sum:v("Sum")},zd=["max","min","avg","sum","count_distinct","count"],$d={integer:zd,char:zd,datetime:zd,boolean:["count_distinct","count","bool_and","bool_or"]},Gd={};for(const e in $d){Gd[e]={};for(const t of $d[e])Gd[e][t]=Bd[t]}const Wd={count:e=>({value:oa([e]),format:"0"}),count_distinct:e=>({value:Us([e]),format:"0"}),bool_and:e=>({value:ud([e]).result}),bool_or:e=>({value:hd([e]).result}),max:(e,t)=>sa([e],t),min:(e,t)=>ia([e],t),avg:(e,t)=>({value:na([e],t),format:Mt(e)}),sum:(e,t)=>({value:ks([e],t),format:Mt(e)})};function qd(e){const t=Object.keys(e);if(!t.length)return 0;const r=t.map(e=>parseInt(e,10));return Math.max(...r)}v("Year"),v("Quarter & Year"),v("Month & Year"),v("Week & Year"),v("Day"),v("Quarter"),v("Month"),v("Week"),v("Day of Month"),v("Day of Week"),v("Hour"),v("Minute"),v("Second");const Zd=["date","datetime"];function Yd(e){const[t,r]=e.split(":");return r?{fieldName:t,granularity:r}:{fieldName:t}}function jd(e,t,r){const n=[e];r&&n.push(`"${r}"`);for(const{field:e,value:r,type:o}of t){if("measure"===e){n.push('"measure"',`"${r}"`);continue}const{granularity:t}=Yd(e),s=Jd(r,{type:o,granularity:t});n.push(`"${e}"`,s)}return n}function Xd(e,t){switch(t.type){case"HEADER":return`=PIVOT.HEADER(${jd(e,t.domain).join(",")})`;case"VALUE":return`=PIVOT.VALUE(${jd(e,t.domain,t.measure).join(",")})`;case"MEASURE_HEADER":return`=PIVOT.HEADER(${jd(e,[...t.domain,{field:"measure",value:t.measure,type:"char"}]).join(",")})`}return""}function Kd(e,t){if(null===t||"null"===t)return null;const r="object"==typeof t?t.value:t;if(Vt(r))return r;if("custom"===e.type)return Yt(t)??null;const n="boolean"==typeof t?$t(t).toLocaleLowerCase():$t(t);if("null"===n)return null;if(!tf.contains(e.type))throw new S(v("Field %(field)s is not supported because of its type (%(type)s)",{field:e.displayName,type:e.type}));if("false"===n.toLowerCase())return!1;return tf.get(e.type)(n,e.granularity)}function Qd(e,t){return Rd(t??"month").normalizeFunctionValue(e)}function Jd(e,t){return null===e?'"null"':rf.contains(t.type)?rf.get(t.type)(e,t.granularity):`"${e}"`}function ef(e,t){return Rd(t??"month").toFunctionValue(e)}const tf=new Id;tf.add("date",Qd).add("datetime",Qd).add("integer",e=>kt(e,xr)).add("boolean",e=>qt(e)).add("char",e=>$t(e)).add("custom",e=>e);const rf=new Id;function nf(e,t){return 0===e.length?t:{...t,format:(t.format||"@")+"* "}}function of(e,t){return Xe(e,Object.values(t).map(e=>[e?.name,e?.string]).flat().filter(Se),{compute:(e,t)=>`${e}${t}`,start:2})}function sf(e,t){const r=t.model.getters.getPivotCellFromPosition(e),n=t.model.getters.getPivotIdFromPosition(e);if(!n||"HEADER"!==r.type)return;const o=t.model.getters.getPivotCoreDefinition(n),s=o.collapsedDomains?.[r.dimension]?[...o.collapsedDomains[r.dimension]]:[],i=s.findIndex(e=>Ae(e,r.domain));-1!==i?s.splice(i,1):s.push(r.domain);const a=o.collapsedDomains?{...o.collapsedDomains}:{COL:[],ROW:[]};a[r.dimension]=s,t.model.dispatch("UPDATE_PIVOT",{pivotId:n,pivot:{...o,collapsedDomains:a}})}function af(e,t,r,n,o,s,i){const a=e.style;return{numberOfRows:void 0!==t?kt(t,i):a?.numberOfRows??Hd.numberOfRows,numberOfColumns:void 0!==o?kt(o,i):a?.numberOfColumns??Hd.numberOfColumns,displayTotals:void 0!==r?qt(r):a?.displayTotals??Hd.displayTotals,displayColumnHeaders:void 0!==n?qt(n):a?.displayColumnHeaders??Hd.displayColumnHeaders,displayMeasuresRow:void 0!==s?qt(s):a?.displayMeasuresRow??Hd.displayMeasuresRow}}function lf(e,t){const r=t.getPivotId(e);if(!r)throw new S(v('There is no pivot with id "%s"',e));return r}function cf(e){if(e.length%2!=0)throw new S(v("Function PIVOT takes an even number of arguments."))}function uf(e,t,r){const n=[],o=e.getters.getPivotCoreDefinition(t);if("SPREADSHEET"===o.type&&o.dataSet){const{sheetId:t,zone:r}=o.dataSet,s=es(r),i=e.getters.getRangeFromSheetXC(t,s);if(void 0===i||i.invalidXc||i.invalidSheetName)throw new I;if(e.__originCellPosition&&i.sheetId===e.__originSheetId&&cs(ps(e.__originCellPosition),r))throw new T;n.push(i)}for(const o of r)o.computedBy&&n.push(...e.getters.getMeasureFullDependencies(t,o));const s=e.__originCellPosition;s&&n.length&&(e.updateDependencies?.(s),e.addDependencies?.(s,n))}rf.add("date",ef).add("datetime",ef).add("integer",e=>`${kt(e,xr)}`).add("boolean",e=>qt(e)?"TRUE":"FALSE").add("char",e=>`"${$t(e).replace(/"/g,'\\"')}"`).add("custom",e=>"string"==typeof e?`"${e}"`:String(e));const hf=!0,df=[{value:!0,label:v("A1 style (default)")},{value:!1,label:v("R1C1 style")}],ff=[{value:!0,label:v("Approximate match (default)")},{value:!1,label:v("Exact match")}],gf={description:v("Returns a cell reference as a string. "),args:[a("row (number)",v("The row number of the cell reference. ")),a("column (number)",v("The column number (not name) of the cell reference. A is column number 1. ")),a("absolute_relative_mode (number, default=1)",v("An indicator of whether the reference is row/column absolute."),[{value:1,label:v("Absolute row and column (e.g. $A$1)")},{value:2,label:v("Absolute row, relative column (e.g. A$1)")},{value:3,label:v("Relative row, absolute column (e.g. $A1)")},{value:4,label:v("Relative row and column (e.g. A1)")}]),a("use_a1_notation (boolean, default=TRUE)",v("A boolean indicating whether to use A1 style notation or R1C1 style notation."),df),a("sheet (string, optional)",v("A string indicating the name of the sheet into which the address points."))],compute:function(e,t,r={value:1},n={value:!0},o){const s=zt(e,this.locale),i=zt(t,this.locale);if(s<1)return new S(Tn(s));if(i<1)return new S(Tn(i));const a=zt(r,this.locale);if(![1,2,3,4].includes(a))return new S((l=4,c=a,v("The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.",1..toString(),l.toString(),c.toString())));var l,c;let u;if(qt(n)){u=Bo(i-1,s-1,{rowFixed:[1,2].includes(a),colFixed:[1,3].includes(a)})}else{u=([1,2].includes(a)?`R${s}`:`R[${s}]`)+([1,3].includes(a)?`C${i}`:`C[${i}]`)}return void 0!==o?Io($t(o),u):u},isExported:!0},mf={description:v("Column number of a specified cell."),args:[a("cell_reference (meta, range<meta>, default='this cell')",v("The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered."))],compute:function(e){if(void 0===e)return void 0===this.__originCellPosition?.col?new S(v("In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.")):this.__originCellPosition.col+1;if(void 0===e[0][0])return new S(v("The range is out of bounds."));if(e[0][0].value===E.InvalidReference)return e[0][0];const t=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),e[0][0].value).zone.left;return 1===e.length?t+1:rr(e.length,1,(e,r)=>({value:t+e+1}))},isExported:!0},pf={description:v("Number of columns in a specified array or range."),args:[a("range (any, range<any>)",v("The range whose column count will be returned."))],compute:function(e){const t=mr(e);return void 0===t[0][0]?new S(v("The range is out of bounds.")):t[0][0].value===E.InvalidReference?t[0][0]:t.length},isExported:!0},bf={description:v("Horizontal lookup"),args:[a("search_key (string, number, boolean)",v("The value to search for. For example, 42, 'Cats', or I24.")),a("range (any, range)",v("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),a("index (number)",v("The row index of the value to be returned, where the first row in range is numbered 1.")),a("is_sorted (boolean, default=true)",v("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."),ff)],compute:function(e,t,r,n={value:hf}){const o=Math.trunc(kt(r?.value,this.locale)),s=mr(t);if(1>o||o>s[0].length)return new S(v("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const i=(e,t)=>e[t][0].value,a=s[qt(n.value)?hr(s,e,"nextSmaller","asc",s.length,i):dr(s,e,"wildcard",s.length,i,this.lookupCaches)];return void 0===a?Lt(e):a[o-1]},isExported:!0},vf={description:v("Returns the content of a cell, specified by row and column offset."),args:[a("reference (any, range)",v("The range of cells from which the values are returned.")),a("row (number, default=0)",v("The index of the row to be returned from within the reference range of cells.")),a("column (number, default=0)",v("The index of the column to be returned from within the reference range of cells."))],compute:function(e,t={value:0},r={value:0}){const n=mr(e),o=kt(t.value,this.locale),s=kt(r.value,this.locale);return s<0||s-1>=n.length||o<0||o-1>=n[0].length?new S(v("Index out of range.")):0===o&&0===s?n:0===o?[n[s-1]]:0===s?n.map(e=>[e[o-1]]):n[s-1][o-1]},isExported:!0},yf={description:v("Returns the content of a cell, specified by a string."),args:[a("reference (string)",v("The range of cells from which the values are returned.")),a("use_a1_notation (boolean, default=TRUE)",v("A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE)."),df)],compute:function(e,t={value:!0}){const r=e?.value?.toString();if(!r)return new I(v("Reference should be defined."));if(!qt(t))return new S(v("R1C1 notation is not supported."));const n=this.__originSheetId,o=this.__originCellPosition;o&&this.updateDependencies?.(o);const s=this.getters.getRangeFromSheetXC(n,r);if(void 0===s||s.invalidXc||s.invalidSheetName)return new I;o&&this.addDependencies?.(o,[s]);const i=[];for(let e=s.zone.left;e<=s.zone.right;e++){const t=[];for(let r=s.zone.top;r<=s.zone.bottom;r++){const n={sheetId:s.sheetId,col:e,row:r};t.push(this.getters.getEvaluatedCell(n))}i.push(t)}return 1===i.length&&1===i[0].length?i[0][0]:i},isExported:!0},Ef={description:v("Look up a value."),args:[a("search_key (string, number, boolean)",v("The value to search for. For example, 42, 'Cats', or I24.")),a("search_array (any, range)",v("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.")),a("result_range (any, range, optional)",v("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method."))],compute:function(e,t,r){const n=mr(t),o=mr(r);let s=n.length,i=n[0].length;const a=i>=s,l=a?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=hr(n,e,"nextSmaller","asc",a?i:s,l);return-1===c||a&&void 0===n[0][c]||!a&&void 0===n[c][i-1]?Lt(e):0===o[0].length?a?n[s-1][c]:n[c][i-1]:(s=o.length,i=o[0].length,1!==s&&1!==i?new S(v("The result_range must be a single row or a single column.")):s>1?c>s-1?new S(v("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",c+1)):o[c][0]:c>i-1?new S(v("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",c+1)):o[0][c])},isExported:!0},wf={description:v("Position of item in range that matches value."),args:[a("search_key (string, number, boolean)",v("The value to search for. For example, 42, 'Cats', or I24.")),a("range (any, range)",v("The one-dimensional array to be searched.")),a("search_type (number, default=1)",v("The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order."),[{value:1,label:v("Ascending order (default)")},{value:0,label:v("Exact match")},{value:-1,label:v("Descending order")}])],compute:function(e,t,r={value:1}){let n=kt(r,this.locale);const o=mr(t),s=o.length,i=o[0].length;if(1!==s&&1!==i)return new S(v("The range must be a single row or a single column."));let a=-1;const l=1===s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=1===s?o[0].length:o.length;switch(n=Math.sign(n),n){case 1:a=hr(o,e,"nextSmaller","asc",c,l);break;case 0:a=dr(o,e,"wildcard",c,l,this.lookupCaches);break;case-1:a=hr(o,e,"nextGreater","desc",c,l)}return 1===s&&void 0===o[0][a]||1!==s&&void 0===o[a]?Lt(e):a+1},isExported:!0},Sf={description:v("Row number of a specified cell."),args:[a("cell_reference (meta, range<meta>, default='this cell')",v("The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered."))],compute:function(e){if(void 0===e)return void 0===this.__originCellPosition?.row?new S(v("In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.")):this.__originCellPosition.row+1;if(void 0===e[0][0])return new S(v("The range is out of bounds."));if(e[0][0].value===E.InvalidReference)return e[0][0];const t=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),e[0][0].value).zone.top;return 1===e[0].length?t+1:rr(1,e[0].length,(e,r)=>({value:t+r+1}))},isExported:!0},Cf={description:v("Number of rows in a specified array or range."),args:[a("range (any, range<any>)",v("The range whose row count will be returned."))],compute:function(e){const t=mr(e);return void 0===t[0][0]?new S(v("The range is out of bounds.")):t[0][0].value===E.InvalidReference?t[0][0]:t[0].length},isExported:!0},Tf={description:v("Vertical lookup."),args:[a("search_key (string, number, boolean)",v("The value to search for. For example, 42, 'Cats', or I24.")),a("range (any, range)",v("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),a("index (number)",v("The column index of the value to be returned, where the first column in range is numbered 1.")),a("is_sorted (boolean, default=true)",v("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."),ff)],compute:function(e,t,r,n={value:hf}){const o=Math.trunc(kt(r?.value,this.locale)),s=mr(t);if(1>o||o>s.length)return new S(v("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const i=(e,t)=>e[0][t].value,a=qt(n.value)?hr(s,e,"nextSmaller","asc",s[0].length,i):dr(s,e,"wildcard",s[0].length,i,this.lookupCaches),l=s[o-1][a];return void 0===l?Lt(e):l},isExported:!0},If={0:"strict",1:"nextGreater","-1":"nextSmaller",2:"wildcard"},xf={description:v("Search a range for a match and return the corresponding item from a second range."),args:[a("search_key (string,number,boolean)",v("The value to search for.")),a("lookup_range (any, range)",v("The range to consider for the search. Should be a single column or a single row.")),a("return_range (any, range)",v("The range containing the return value. Should have the same dimensions as lookup_range.")),a("if_not_found (any, optional)",v("If a valid match is not found, return this value.")),a("match_mode (any, default=0)",v("Specifies how to match search_key with the items in lookup_range. "),[{value:0,label:v("Exact match (default)")},{value:-1,label:v("Exact match or next smaller item")},{value:1,label:v("Exact match or next larger item")},{value:2,label:v("Wildcard character match")}]),a("search_mode (any, default=1)",v("Specifies the search mode to use. By default, a first to last search will be used."),[{value:1,label:v("Search first to last (default)")},{value:-1,label:v("Search last to first")},{value:2,label:v("Binary search (sorted ascending order)")},{value:-2,label:v("Binary search (sorted descending order)")}])],compute:function(e,t,r,n,o={value:0},s={value:1}){const i=Math.trunc(kt(o.value,this.locale)),a=Math.trunc(kt(s.value,this.locale)),l=mr(t),c=mr(r);if(1!==l.length&&1!==l[0].length)return new S(v("lookup_range should be either a single row or single column."));if(![1,-1,2,-2].includes(a))return new S(v("search_mode should be a value in [-1, 1, -2, 2]."));if(![-1,0,1,2].includes(i))return new S(v("match_mode should be a value in [-1, 0, 1, 2]."));const u=1===l.length?"col":"row";if(2===i&&[-2,2].includes(a))return new S(v("The search and match mode combination is not supported for XLOOKUP evaluation."));if("col"===u?c[0].length!==l[0].length:c.length!==l.length)return new S(v("return_range should have the same dimensions as lookup_range."));const h="col"===u?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,d="col"===u?l[0].length:l.length,f=If[i],g=-1===a,m=2===a||-2===a?hr(l,e,f,2===a?"asc":"desc",d,h):dr(l,e,f,d,h,this.lookupCaches,g);return-1!==m?"col"===u?c.map(e=>[e[m]]):[c[m]]:void 0===n?Lt(e):[[n]]},isExported:!0},Rf={description:v("Get the value from a pivot."),args:[a("pivot_id (number,string)",v("ID of the pivot.")),a("measure_name (string)",v("Name of the measure.")),a("domain_field_name (string,repeating,optional)",v("Field name.")),a("domain_value (number,string,boolean,repeating,optional)",v("Value."))],compute:function(e,t,...r){const n=$t(e),o=$t(t),s=lf(n,this.getters);!function(e,t,r){const{measures:n}=r.getPivotCoreDefinition(e);if(!n.find(e=>e.id===t)){const e=`(${n.map(e=>e.id).join(", ")})`;throw new S(v("The argument %s is not a valid measure. Here are the measures: %s",t,e))}}(s,o,this.getters),cf(r);const i=this.getters.getPivot(s);uf(this,s,this.getters.getPivotCoreDefinition(s).measures.filter(e=>e.id===o)),i.init({reload:i.needsReevaluation});const a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(r)){const e=v("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${n})`);return{value:E.GenericError,message:v("Dimensions don't match the pivot definition")+". "+e}}const l=i.parseArgsToPivotDomain(r);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(s)?.trackValue(o,l),i.getPivotCellValueAndFormat(o,l)}},Af={description:v("Get the header of a pivot."),args:[a("pivot_id (number,string)",v("ID of the pivot.")),a("domain_field_name (string,repeating,optional)",v("Field name.")),a("domain_value (number,string,value,repeating,optional)",v("Value."))],compute:function(e,...t){const r=$t(e),n=lf(r,this.getters);cf(t);const o=this.getters.getPivot(n);uf(this,n,[]),o.init({reload:o.needsReevaluation});const s=o.assertIsValid({throwOnError:!1});if(s)return s;if(!o.areDomainArgsFieldsValid(t)){const e=v("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${r})`);return{value:E.GenericError,message:v("Dimensions don't match the pivot definition")+". "+e}}const i=o.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(n)?.trackHeader(i);const a=i.at(-1);if("measure"===a?.field)return o.getPivotMeasureValue($t(a.value),i);const{value:l,format:c}=o.getPivotHeaderValueAndFormat(i);return{value:l,format:a&&"measure"!==a.field&&"false"!==a.value?c:void 0}}},Of={description:v("Get a pivot table."),args:[a("pivot_id (string)",v("ID of the pivot.")),a("row_count (number, optional)",v("number of rows")),a("include_total (boolean, default=TRUE)",v("Whether to include total/sub-totals or not.")),a("include_column_titles (boolean, default=TRUE)",v("Whether to include the column titles or not.")),a("column_count (number, optional)",v("number of columns")),a("include_measure_titles (boolean, default=TRUE)",v("Whether to include the measure titles row or not."))],compute:function(e,t,r,n,o,s){const i=lf($t(e),this.getters),a=this.getters.getPivot(i),l=this.getters.getPivotCoreDefinition(i),c=af(l,t,r,n,o,s,this.locale);if(c.numberOfRows<0)return new S(v("The number of rows must be positive."));if(c.numberOfColumns<0)return new S(v("The number of columns must be positive."));uf(this,i,l.measures),a.init({reload:a.needsReevaluation});const u=a.assertIsValid({throwOnError:!1});if(u)return u;const h=a.getCollapsedTableStructure();if(h.numberOfCells>5e5)return new S(function(e,t){const r=Xr(e,{format:"0,00",locale:t});return v("Oops—this pivot table is quite large (%s cells). Try simplifying it using the side panel.",r)}(h.numberOfCells,this.locale));const d=h.getPivotCells(c);let f=0;c.displayColumnHeaders&&(f=h.columns.length-1),c.displayMeasuresRow&&f++;const g=this.getters.getPivotName(i),m=Math.min(f+c.numberOfRows,d[0].length);if(0===m)return[[{value:g}]];const p=Math.min(1+c.numberOfColumns,d.length),b=[];for(const e of le(0,p)){b[e]=[];for(const t of le(0,m)){const r=d[e][t];switch(r.type){case"EMPTY":b[e].push({value:""});break;case"HEADER":const t=a.getPivotHeaderValueAndFormat(r.domain);b[e].push(nf(r.domain,t));break;case"MEASURE_HEADER":b[e].push(a.getPivotMeasureValue(r.measure,r.domain));break;case"VALUE":b[e].push(a.getPivotCellValueAndFormat(r.measure,r.domain))}}}return(c.displayColumnHeaders||c.displayMeasuresRow)&&(b[0][0]={value:g}),b}},_f={description:v("Returns a range reference shifted by a specified number of rows and columns from a starting cell reference."),args:[a("cell_reference (meta, range<meta>)",v("The starting point from which to count the offset rows and columns.")),a("offset_rows (number)",v("The number of rows to offset by.")),a("offset_columns (number)",v("The number of columns to offset by.")),a("height (number, default='height of cell_reference')",v("The number of rows of the range to return starting at the offset target.")),a("width (number, default='width of cell_reference')",v("The number of columns of the range to return starting at the offset target."))],compute:function(e,t,r,n,o){if(Vt(e[0][0].value))return e[0][0];const s=e[0][0].value;if(!s)return new S("In this context, the function OFFSET needs to have a cell or range in parameter.");const i=Ko(s);let a=e[0].length,l=e.length;if(n){const e=kt(n,this.locale);if(e<1)return new S(v("Height value is %(_height)s. It should be greater than or equal to 1.",{_height:e}));a=e}if(o){const e=kt(o,this.locale);if(e<1)return new S(v("Width value is %(_width)s. It should be greater than or equal to 1.",{_width:e}));l=e}const{sheetName:c}=To(s),u=c&&this.getters.getSheetIdByName(c)||this.getters.getActiveSheetId(),h=kt(t,this.locale),d=kt(r,this.locale),f=this.__originCellPosition;f&&this.updateDependencies?.(f);const g=i.left+d,m=i.top+h;if(g<0||m<0)return new I(v("OFFSET evaluates to an out of bounds range."));const p={left:g,top:m,right:g+l-1,bottom:m+a-1},b=this.getters.getRangeFromZone(u,p);return b.invalidXc||b.invalidSheetName?new I:(f&&this.addDependencies?.(f,[b]),rr(l,a,(e,t)=>this.getters.getEvaluatedCell({sheetId:u,col:g+e,row:m+t})))}},Df={description:v("Returns an element from a list of choices based on index."),args:[a("index (number)",v("Which choice to return.")),a("choice (any, range<any>, repeating)",v("A potential value to return. May be a reference to a cell or an individual value."))],compute:function(e,...t){const r=Math.floor(kt(e,this.locale))-1;if(r<0||r>=t.length)return new S(v("Index for CHOOSE is invalid. Valid values are between 1 and %(choices)s inclusive.",{choices:t.length}));return t[r]??new S(v("Choice is undefined."))},isExported:!0},Ff={description:v("Excludes a specified number of rows or columns from the start or end of an array."),args:[a("array (range)",v("The array from which to drop rows or columns")),a("rows (number)",v("The number of rows to drop. A negative value drops from the end of the array.")),a("columns (number, optional)",v("The number of columns to exclude. A negative value drops from the end of the array."))],compute:function(e,t,r){const n=kt(t,this.locale),o=kt(r,this.locale);let s=e;if(Math.abs(o)>=e.length||Math.abs(n)>=e[0].length)return new S(v("The number of rows or column to exclude must be smaller than the number of elements in the array."));s=o>=0?s.slice(o):s.slice(0,s.length+o);for(let e=0;e<s.length;e++)s[e]=n>=0?s[e].slice(n):s[e].slice(0,s[e].length+n);return s},isExported:!0},Nf={description:v("Returns a specified number of contiguous rows or columns from the start or end of an array."),args:[a("array (range)",v("The array from which to take rows or columns.")),a("rows (number)",v("The number of rows to take. A negative value takes from the end of the array.")),a("columns (number, optional)",v("The number of columns to take. A negative value takes from the end of the array."))],compute:function(e,t,r){let n=t?kt(t,this.locale):e[0].length,o=kt(r,this.locale),s=e;if((Math.abs(o)>=e.length||0===o)&&(o=e.length),Math.abs(n)>=e[0].length&&(n=e[0].length),s=o>=0?s.slice(0,o):s.slice(s.length+o,s.length),0===n)return new S(v("The number of rows can not be zero."));for(let e=0;e<s.length;e++)s[e]=n>0?s[e].slice(0,n):s[e].slice(s[e].length+n,s[e].length);return s},isExported:!0},Mf={description:v("Returns a formula as a string."),args:[a("cell_reference (meta)",v("A reference to a cell."))],compute:function(e){const{sheetName:t,xc:r}=To(e.value),{col:n,row:o}=Ho(r),s=(t&&this.getters.getSheetIdByName(t))??this.__originSheetId,i=this.getters.getCell({sheetId:s,col:n,row:o});return i&&Ke(i.content)?i.content:new x(v("The cell does not contain a formula."))},isExported:!0};var Vf=Object.freeze({__proto__:null,ADDRESS:gf,CHOOSE:Df,COLUMN:mf,COLUMNS:pf,DROP:Ff,FORMULATEXT:Mf,HLOOKUP:bf,INDEX:vf,INDIRECT:yf,LOOKUP:Ef,MATCH:wf,OFFSET:_f,PIVOT:Of,PIVOT_HEADER:Af,PIVOT_VALUE:Rf,ROW:Sf,ROWS:Cf,TAKE:Nf,VLOOKUP:Tf,XLOOKUP:xf});const Lf={description:v("Sum of two numbers."),args:[a("value1 (number)",v("The first addend.")),a("value2 (number)",v("The second addend."))],compute:function(e,t){return{value:kt(e,this.locale)+kt(t,this.locale),format:e?.format||t?.format}}},Pf={description:v("Concatenation of two values."),args:[a("value1 (string)",v("The value to which value2 will be appended.")),a("value2 (string)",v("The value to append to value1."))],compute:function(e,t){return $t(e)+$t(t)},isExported:!0},kf={description:v("One number divided by another."),args:[a("dividend (number)",v("The number to be divided.")),a("divisor (number)",v("The number to divide by."))],compute:function(e,t){const r=kt(t,this.locale);return 0===r?new O(v("The divisor must be different from zero.")):{value:kt(e,this.locale)/r,format:e?.format||t?.format}}};function Uf(e){return void 0===e||null===e.value}const Hf={number:0,string:"",boolean:!1};function Bf(e,t,r=2e-16){return Math.abs(e-t)<r}const zf={description:v("Equal."),args:[a("value1 (string, number, boolean)",v("The first value.")),a("value2 (string, number, boolean)",v("The value to test against value1 for equality."))],compute:function(e,t){if(Vt(e?.value))return e;if(Vt(t?.value))return t;let r=Uf(e)?Hf[typeof t?.value]:e?.value,n=Uf(t)?Hf[typeof e?.value]:t?.value;return"string"==typeof r&&(r=r.toUpperCase()),"string"==typeof n&&(n=n.toUpperCase()),"number"==typeof r&&"number"==typeof n?{value:Bf(r,n)}:{value:r===n}}};function $f(e,t,r){if(Vt(e?.value))return e;if(Vt(t?.value))return t;let n=Uf(e)?Hf[typeof t?.value]:e?.value,o=Uf(t)?Hf[typeof e?.value]:t?.value;"number"!=typeof n&&(n=$t(n).toUpperCase()),"number"!=typeof o&&(o=$t(o).toUpperCase());const s=typeof n,i=typeof o;return"string"===s&&"number"===i?{value:!0}:"string"===i&&"number"===s?{value:!1}:{value:r(n,o)}}const Gf={description:v("Strictly greater than."),args:[a("value1 (number, string, boolean)",v("The value to test as being greater than value2.")),a("value2 (number, string, boolean)",v("The second value."))],compute:function(e,t){return $f(e,t,(e,t)=>"number"==typeof e&&"number"==typeof t?!Bf(e,t)&&e>t:e>t)}},Wf={description:v("Greater than or equal to."),args:[a("value1 (number, string, boolean)",v("The value to test as being greater than or equal to value2.")),a("value2 (number, string, boolean)",v("The second value."))],compute:function(e,t){return $f(e,t,(e,t)=>"number"==typeof e&&"number"==typeof t?Bf(e,t)||e>t:e>=t)}},qf={description:v("Less than."),args:[a("value1 (number, string, boolean)",v("The value to test as being less than value2.")),a("value2 (number, string, boolean)",v("The second value."))],compute:function(e,t){const r=Wf.compute.bind(this)(e,t);return Vt(r.value)?r:{value:!r.value}}},Zf={description:v("Less than or equal to."),args:[a("value1 (number, string, boolean)",v("The value to test as being less than or equal to value2.")),a("value2 (number, string, boolean)",v("The second value."))],compute:function(e,t){const r=Gf.compute.bind(this)(e,t);return Vt(r.value)?r:{value:!r.value}}},Yf={description:v("Difference of two numbers."),args:[a("value1 (number)",v("The minuend, or number to be subtracted from.")),a("value2 (number)",v("The subtrahend, or number to subtract from value1."))],compute:function(e,t){return{value:kt(e,this.locale)-kt(t,this.locale),format:e?.format||t?.format}}},jf={description:v("Product of two numbers"),args:[a("factor1 (number)",v("The first multiplicand.")),a("factor2 (number)",v("The second multiplicand."))],compute:function(e,t){return{value:kt(e,this.locale)*kt(t,this.locale),format:e?.format||t?.format}}},Xf={description:v("Not equal."),args:[a("value1 (string, number, boolean)",v("The first value.")),a("value2 (string, number, boolean)",v("The value to test against value1 for inequality."))],compute:function(e,t){const r=zf.compute.bind(this)(e,t);return Vt(r.value)?r:{value:!r.value}}},Kf={description:v("A number raised to a power."),args:[a("base (number)",v("The number to raise to the exponent power.")),a("exponent (number)",v("The exponent to raise base to."))],compute:function(e,t){return Oi.compute.bind(this)(e,t)}},Qf={description:v("A number with the sign reversed."),args:[a("value (number)",v("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],compute:function(e){return{value:-kt(e,this.locale),format:e?.format}}},Jf={description:v("Value interpreted as a percentage."),args:[a("percentage (number)",v("The value to interpret as a percentage."))],compute:function(e){return kt(e,this.locale)/100}},eg={description:v("A specified number, unchanged."),args:[a("value (any)",v("The number to return."))],compute:function(e={value:null}){return e}};var tg=Object.freeze({__proto__:null,ADD:Lf,CONCAT:Pf,DIVIDE:kf,EQ:zf,GT:Gf,GTE:Wf,LT:qf,LTE:Zf,MINUS:Yf,MULTIPLY:jf,NE:Xf,POW:Kf,UMINUS:Qf,UNARY_PERCENT:Jf,UPLUS:eg});const rg=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),ng={transform:e=>e,inverseTransform:e=>e},og=1e-10,sg=.0254,ig=sg/72,ag=.3048,lg=.9144,cg=1609.34,ug=1852,hg=946073047258e4,dg={g:{...ng,category:"weight"},u:{...rg(166053e-29),category:"weight"},grain:{...rg(.0647989),category:"weight"},ozm:{...rg(28.3495),category:"weight"},lbm:{...rg(453.592),category:"weight"},stone:{...rg(6350.29),category:"weight"},sg:{...rg(14593.90294),category:"weight"},cwt:{...rg(45359.237),category:"weight"},uk_cwt:{...rg(50802.3),category:"weight"},ton:{...rg(907184.74),category:"weight"},uk_ton:{...rg(1016046.9),category:"weight"},m:{...ng,category:"distance"},km:{...rg(1e3),category:"distance"},ang:{...rg(og),category:"distance"},Picapt:{...rg(ig),category:"distance"},pica:{...rg(sg/6),category:"distance"},in:{...rg(sg),category:"distance"},ft:{...rg(ag),category:"distance"},yd:{...rg(lg),category:"distance"},ell:{...rg(1.143),category:"distance"},mi:{...rg(cg),category:"distance"},survey_mi:{...rg(1609.34),category:"distance"},Nmi:{...rg(ug),category:"distance"},ly:{...rg(hg),category:"distance"},parsec:{...rg(0x6da012f95c9fd0),category:"distance"},sec:{...ng,category:"time"},min:{...rg(60),category:"time"},hr:{...rg(3600),category:"time"},day:{...rg(86400),category:"time"},yr:{...rg(31556952),category:"time"},Pa:{...ng,category:"pressure"},bar:{...rg(1e5),category:"pressure"},mmHg:{...rg(133.322),category:"pressure"},Torr:{...rg(133.322),category:"pressure"},psi:{...rg(6894.76),category:"pressure"},atm:{...rg(101325),category:"pressure"},N:{...ng,category:"force"},dyn:{...rg(1e-5),category:"force"},pond:{...rg(.00980665),category:"force"},lbf:{...rg(4.44822),category:"force"},J:{...ng,category:"energy"},eV:{...rg(160218e-24),category:"energy"},e:{...rg(1e-7),category:"energy"},flb:{...rg(1.3558179483),category:"energy"},c:{...rg(4.184),category:"energy"},cal:{...rg(4.1868),category:"energy"},BTU:{...rg(1055.06),category:"energy"},Wh:{...rg(3600),category:"energy"},HPh:{...rg(2684520),category:"energy"},W:{...ng,category:"power"},PS:{...rg(735.499),category:"power"},HP:{...rg(745.7),category:"power"},T:{...ng,category:"magnetism"},ga:{...rg(1e-4),category:"magnetism"},K:{...ng,category:"temperature"},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:"temperature"},F:{transform:e=>5*(e-32)/9+273.15,inverseTransform:e=>9*(e-273.15)/5+32,category:"temperature"},Rank:{...rg(5/9),category:"temperature"},Reau:{transform:e=>1.25*e+273.15,inverseTransform:e=>(e-273.15)/1.25,category:"temperature"},"m^3":{...ng,category:"volume",order:3},"ang^3":{...rg(Math.pow(og,3)),category:"volume",order:3},"Picapt^3":{...rg(Math.pow(ig,3)),category:"volume",order:3},tsp:{...rg(492892e-11),category:"volume"},tspm:{...rg(5e-6),category:"volume"},tbs:{...rg(14786764825785619e-21),category:"volume"},"in^3":{...rg(Math.pow(sg,3)),category:"volume",order:3},oz:{...rg(295735295625e-16),category:"volume"},cup:{...rg(237e-6),category:"volume"},pt:{...rg(.0004731765),category:"volume"},uk_pt:{...rg(568261e-9),category:"volume"},qt:{...rg(.0009463529),category:"volume"},l:{...rg(.001),category:"volume"},uk_qt:{...rg(.0011365225),category:"volume"},gal:{...rg(.0037854118),category:"volume"},uk_gal:{...rg(.00454609),category:"volume"},"ft^3":{...rg(Math.pow(ag,3)),category:"volume",order:3},bushel:{...rg(.0352390704),category:"volume"},barrel:{...rg(.158987295),category:"volume"},"yd^3":{...rg(Math.pow(lg,3)),category:"volume",order:3},MTON:{...rg(1.13267386368),category:"volume"},GRT:{...rg(2.83168),category:"volume"},"mi^3":{...rg(Math.pow(cg,3)),category:"volume",order:3},"Nmi^3":{...rg(Math.pow(ug,3)),category:"volume",order:3},"ly^3":{...rg(Math.pow(hg,3)),category:"volume",order:3},"m^2":{...ng,category:"area",order:2},"ang^2":{...rg(Math.pow(og,2)),category:"area",order:2},"Picapt^2":{...rg(Math.pow(ig,2)),category:"area",order:2},"in^2":{...rg(Math.pow(sg,2)),category:"area",order:2},"ft^2":{...rg(Math.pow(ag,2)),category:"area",order:2},"yd^2":{...rg(Math.pow(lg,2)),category:"area",order:2},ar:{...rg(100),category:"area"},Morgen:{...rg(2500),category:"area"},uk_acre:{...rg(4046.8564224),category:"area"},us_acre:{...rg(4046.8726098743),category:"area"},ha:{...rg(1e4),category:"area"},"mi^2":{...rg(Math.pow(cg,2)),category:"area",order:2},"Nmi^2":{...rg(Math.pow(ug,2)),category:"area",order:2},"ly^2":{...rg(Math.pow(hg,2)),category:"area",order:2},bit:{...ng,category:"information"},byte:{...rg(8),category:"information"},"m/s":{...ng,category:"speed"},"m/hr":{...rg(1/3600),category:"speed"},"km/hr":{...rg(1/3.6),category:"speed"},mph:{...rg(.44704),category:"speed"},kn:{...rg(.5144444444),category:"speed"},admkn:{...rg(.5147733333),category:"speed"}},fg={shweight:"cwt",lcwt:"uk_cwt",hweight:"uk_cwt",LTON:"uk_ton",brton:"uk_ton",pc:"parsec",Pica:"Picapt",d:"day",mn:"min",s:"sec",p:"Pa",at:"atm",dy:"dyn",ev:"eV",hh:"HPh",wh:"Wh",btu:"BTU",h:"HP",cel:"C",fah:"F",kel:"K",us_pt:"pt",L:"l",lt:"l",ang3:"ang^3",ft3:"ft^3",in3:"in^3",ly3:"ly^3",m3:"m^3",mi3:"mi^3",yd3:"yd^3",Nmi3:"Nmi^3",Picapt3:"Picapt^3","Pica^3":"Picapt^3",Pica3:"Picapt^3",regton:"GRT",ang2:"ang^2",ft2:"ft^2",in2:"in^2",ly2:"ly^2",m2:"m^2",mi2:"mi^2",Nmi2:"Nmi^2",Picapt2:"Picapt^2","Pica^2":"Picapt^2",Pica2:"Picapt^2",yd2:"yd^2","m/h":"m/hr","m/sec":"m/s"},gg={"":1,Y:1e24,Z:1e21,E:1e18,P:1e15,T:1e12,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:Math.pow(2,80),Zi:Math.pow(2,70),Ei:Math.pow(2,60),Pi:Math.pow(2,50),Ti:Math.pow(2,40),Gi:Math.pow(2,30),Mi:Math.pow(2,20),ki:Math.pow(2,10)},mg={weight:v("Weight"),distance:v("Distance"),time:v("Time"),pressure:v("Pressure"),force:v("Force"),energy:v("Energy"),power:v("Power"),magnetism:v("Magnetism"),temperature:v("Temperature"),volume:v("Volume"),area:v("Area"),information:v("Information"),speed:v("Speed")},pg=Object.entries(dg).map(([e,t])=>({value:e,label:bg(t.category)}));function bg(e){return mg[e]??""}function vg(e){for(const[t,r]of Object.entries(gg)){if(t&&!e.startsWith(t))continue;const n=e.slice(t.length);let o=dg[n];if(!o&&fg[n]&&(o=dg[fg[n]]),o)return{...o,factor:o.order?Math.pow(r,o.order):r}}}const yg={description:v("Converts a numeric value to a different unit of measure."),args:[a("value (number)",v("the numeric value in start_unit to convert to end_unit")),a("start_unit (string)",v("The starting unit, the unit currently assigned to value"),pg),a("end_unit (string)",v("The unit of measure into which to convert value"),pg)],compute:function(e,t,r){const n=kt(e,this.locale),o=$t(t),s=$t(r),i=vg(o),a=vg(s);return i?a?i.category!==a.category?{value:E.GenericError,message:v("Incompatible units of measure ('%s' vs '%s')",bg(i.category),bg(a.category))}:{value:a.inverseTransform(i.factor*i.transform(n))/a.factor,format:e?.format}:{value:E.GenericError,message:v("Invalid units of measure ('%s')",s)}:{value:E.GenericError,message:v("Invalid units of measure ('%s')",o)}},isExported:!0};var Eg=Object.freeze({__proto__:null,CONVERT:yg});const wg=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,Sg=[{value:0,label:v("Case-sensitive (default)")},{value:1,label:v("Case-insensitive")}],Cg=[{value:0,label:v("Don't match to end (default)")},{value:1,label:v("Match to end")}],Tg={description:v("Gets character associated with number."),args:[a("table_number (number)",v("The number of the character to look up from the current Unicode table in decimal format."))],compute:function(e){const t=Math.trunc(kt(e,this.locale));return t<1?new S(v("The table_number (%s) is out of range.",t)):String.fromCharCode(t)},isExported:!0},Ig={description:v("Remove non-printable characters from a piece of text."),args:[a("text (string)",v("The text whose non-printable characters are to be removed."))],compute:function(e){const t=$t(e);let r="";for(const e of t)e&&e.charCodeAt(0)>31&&(r+=e);return r},isExported:!0},xg={description:v("Appends strings to one another."),args:[a("string (string, range<string>, repeating)",v("String to append in sequence."))],compute:function(...e){return Jt(e,(e,t)=>e+$t(t),"")},isExported:!0},Rg={description:v("Tests whether two strings are identical."),args:[a("string1 (string)",v("The first string to compare.")),a("string2 (string)",v("The second string to compare."))],compute:function(e,t){return $t(e)===$t(t)},isExported:!0},Ag={description:v("First position of string found in text, case-sensitive."),args:[a("search_for (string)",v("The string to look for within text_to_search.")),a("text_to_search (string)",v("The text to search for the first occurrence of search_for.")),a("starting_at (number, default=1)",v("The character within text_to_search at which to start the search."))],compute:function(e,t,r={value:1}){const n=$t(e),o=$t(t),s=kt(r,this.locale);if(""===o)return new S(v("The text_to_search must be non-empty."));if(s<1)return new S(v("The starting_at (%s) must be greater than or equal to 1.",s));const i=o.indexOf(n,s-1);return-1===i?new S(v("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",n,o)):i+1},isExported:!0},Og={description:v("Concatenates elements of arrays with delimiter."),args:[a("delimiter (string)",v("The character or string to place between each concatenated value.")),a("value_or_array (string, range<string>, repeating)",v("Value to be appended using delimiter."))],compute:function(e,...t){const r=$t(e);return Jt(t,(e,t)=>(e?e+r:"")+$t(t),"")}},_g={description:v("Substring from beginning of specified string."),args:[a("text (string)",v("The string from which the left portion will be returned.")),a("number_of_characters (number, optional)",v("The number of characters to return from the left side of string."))],compute:function(e,...t){const r=t.length?kt(t[0],this.locale):1;return r<0?new S(v("The number_of_characters (%s) must be positive or null.",r)):$t(e).substring(0,r)},isExported:!0},Dg={description:v("Length of a string."),args:[a("text (string)",v("The string whose length will be returned."))],compute:function(e){return $t(e).length},isExported:!0},Fg={description:v("Converts a specified string to lowercase."),args:[a("text (string)",v("The string to convert to lowercase."))],compute:function(e){return $t(e).toLowerCase()},isExported:!0},Ng={description:v("A segment of a string."),args:[a("text (string)",v("The string to extract a segment from.")),a("starting_at (number)",v("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),a("extract_length (number)",v("The length of the segment to extract."))],compute:function(e,t,r){const n=$t(e),o=kt(t,this.locale),s=kt(r,this.locale);return o<1?new S(v("The starting_at argument (%s) must be positive greater than one.",o.toString())):s<0?new S(v("The extract_length argument (%s) must be positive or null.",s)):n.slice(o-1,o+s-1)},isExported:!0},Mg={description:v("Capitalizes each word in a specified string."),args:[a("text_to_capitalize (string)",v("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase."))],compute:function(e){return $t(e).replace(wg,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},Vg={description:v("Extract text from a string based on the supplied regular expression."),args:[a("text (string)",v("The string on which you want to extract text.")),a("pattern (string)",v("The regular expression pattern to match against the text.")),a("return_mode (number, default=0)",v("0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array."),[{value:0,label:v("First match")},{value:1,label:v("All matches")},{value:2,label:v("Capture groups of first match")}]),a("case_sensitivity (number, default=0)",v("Whether the match is case-sensitive."),[{value:0,label:v("Case-sensitive")},{value:1,label:v("Case-insensitive")}])],compute:function(e,t,r={value:0},n={value:0}){const o=$t(e),s=$t(t),i=kt(r,this.locale),a=kt(n,this.locale);if(""===o||""===s)return{value:""};if(i<0||i>2)return new S(v("The return_mode (%s) must be 0, 1 or 2.",i));if(0!==a&&1!==a)return new S(v("The case_sensitivity (%s) must be 0 or 1.",a));const l=new RegExp(s,1===a?"gi":"g"),c=[...o.matchAll(l)];return 0===c.length?{value:E.NotAvailable,message:v("No matches found.")}:0===i?c[0][0]:1===i?c.map(e=>[e[0]]):c[0].length<2?new S(v("No capturing groups found.")):c[0].slice(1).map(e=>[e])},isExported:!0},Lg={description:v("Replaces part of a text string with different text."),args:[a("text (string)",v("The text, a part of which will be replaced.")),a("position (number)",v("The position where the replacement will begin (starting from 1).")),a("length (number)",v("The number of characters in the text to be replaced.")),a("new_text (string)",v("The text which will be inserted into the original text."))],compute:function(e,t,r,n){const o=kt(t,this.locale);if(o<1)return new S(v("The position (%s) must be greater than or equal to 1.",o));const s=$t(e),i=kt(r,this.locale),a=$t(n);return s.substring(0,o-1)+a+s.substring(o-1+i)},isExported:!0},Pg={description:v("A substring from the end of a specified string."),args:[a("text (string)",v("The string from which the right portion will be returned.")),a("number_of_characters (number, optional)",v("The number of characters to return from the right side of string."))],compute:function(e,...t){const r=t.length?kt(t[0],this.locale):1;if(r<0)return new S(v("The number_of_characters (%s) must be positive or null.",r));const n=$t(e),o=n.length;return n.substring(o-r,o)},isExported:!0},kg={description:v("First position of string found in text, ignoring case."),args:[a("search_for (string)",v("The string to look for within text_to_search.")),a("text_to_search (string)",v("The text to search for the first occurrence of search_for.")),a("starting_at (number, default=1)",v("The character within text_to_search at which to start the search."))],compute:function(e,t,r={value:1}){const n=$t(e).toLowerCase(),o=$t(t).toLowerCase(),s=kt(r,this.locale);if(""===o)return{value:E.GenericError,message:v("The text_to_search must be non-empty.")};if(s<1)return{value:E.GenericError,message:v("The starting_at (%s) must be greater than or equal to 1.",s)};const i=o.indexOf(n,s-1);return-1===i?{value:E.GenericError,message:v("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",n,o)}:{value:i+1}},isExported:!0},Ug=!0,Hg=!0,Bg={description:v("Split text by specific character delimiter(s)."),args:[a("text (string)",v("The text to divide.")),a("delimiter (string)",v("The character or characters to use to split text.")),a("split_by_each (boolean, default=true})",v("Whether or not to divide text around each character contained in delimiter.")),a("remove_empty_text (boolean, default=true)",v("Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters."))],compute:function(e,t,r={value:Ug},n={value:Hg}){const o=$t(e),s=te($t(t)),i=qt(r),a=qt(n);if(s.length<=0)return new S(v("The delimiter (%s) must be not be empty.",s));const l=i?new RegExp(`[${s}]`,"g"):new RegExp(s,"g");let c=o.split(l);return a&&(c=c.filter(e=>""!==e)),or([c])},isExported:!1},zg={description:v("Replaces existing text with new text in a string."),args:[a("text_to_search (string)",v("The text within which to search and replace.")),a("search_for (string)",v("The string to search for within text_to_search.")),a("replace_with (string)",v("The string that will replace search_for.")),a("occurrence_number (number, optional)",v("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced."))],compute:function(e,t,r,n){const o=kt(n,this.locale);if(o<0)return new S(v("The occurrenceNumber (%s) must be positive or null.",o));const s=$t(e),i=$t(t);if(""===i)return s;const a=$t(r),l=new RegExp(te(i),"g");if(0===o)return s.replace(l,a);let c=0;return s.replace(l,e=>++c===o?a:e)},isExported:!0},$g={description:v("Combines text from multiple strings and/or arrays."),args:[a("delimiter (string)",v("A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),a("ignore_empty (boolean)",v("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result."),[{value:!0,label:v("Ignore empty cells")},{value:!1,label:v("Include empty cells (default)")}]),a("texts (string, range<string>, repeating)",v("Text item to join."))],compute:function(e,t={value:true},...r){const n=$t(e),o=qt(t);let s=0;return Jt(r,(e,t)=>o&&""===$t(t)?e:(s++?e+n:"")+$t(t),"")},isExported:!0},Gg=!1,Wg={description:v("Splits text into rows or columns using specified column and row delimiters."),args:[a("text (string)",v("The text to split.")),a("col_delimiter (string, range<string>)",v("Character or string to split columns by.")),a("row_delimiter (string, range<string>, optional)",v("Character or string to split rows by.")),a("ignore_empty (boolean, default=false)",v("Whether to ignore empty cells."),[{value:!1,label:v("Include empty cells (default)")},{value:!0,label:v("Ignore empty cells")}]),a("match_mode (number, default=0)",v("Searches the text for a delimiter match. By default, a case-sensitive match is done."),Sg),a(`pad_with (string, default="${E.NotAvailable}")`,v("The value to use for padding empty cells."))],compute:function(e,t,r,n={value:Gg},o={value:0},s=new x){const i=$t(e);if(i.length<=0)return new S(v("No text to split."));if(void 0===t&&void 0===r)return new S(v("At least one delimiter must be provided."));const a=mr(t).flat().map(e=>te($t(e))),l=mr(r).flat().map(e=>te($t(e)));if(a.some(e=>""===e)||l.some(e=>""===e))return new S(v("The delimiters cannot be empty values."));const c=qt(n),u=kt(o,this.locale);if(![0,1].includes(u))return new S(v("match_mode should be a value of 0 or 1."));const h=[],d=1===u?"gi":"g",f=l.filter(e=>!a.includes(e));let g=f.length?i.split(new RegExp(f.join("|"),d)):[i];c&&(g=g.filter(e=>""!==e));const m=new RegExp(a.join("|"),d);for(const e of g){let t=a.length?e.split(m):[e];c&&(t=t.filter(e=>""!==e)),h.push(t.map(e=>({value:e})))}const p=Math.max(...h.map(e=>e.length));for(const e of h)for(;e.length<p;)e.push(s);return or(h)},isExported:!0},qg={description:v("Removes space characters."),args:[a("text (string)",v("The text or reference to a cell containing text to be trimmed."))],compute:function(e){return $e($t(e))},isExported:!0},Zg={description:v("Converts a specified string to uppercase."),args:[a("text (string)",v("The string to convert to uppercase."))],compute:function(e){return $t(e).toUpperCase()},isExported:!0},Yg={description:v("Converts a number to text according to a specified format."),args:[a("number (number)",v("The number, date or time to format.")),a("format (string)",v('The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.'))],compute:function(e,t){return Xr(kt(e,this.locale),{format:$t(t),locale:this.locale})},isExported:!0},jg={description:v("Converts a string to a numeric value."),args:[a("value (number)",v("the string to be converted"))],compute:function(e){return kt(e,this.locale)},isExported:!0},Xg={description:v("Returns text that occurs after a given substring or delimiter."),args:[a("text (string)",v("The source text.")),a("delimiter (string)",v("The substring after which text will be returned.")),a("instance_num (number, default=1)",v("The desired instance of the delimiter after which we extract the text. A negative number searches from the end.")),a("match_mode (number, default=0)",v("Searches the text for a delimiter match. By default, a case-sensitive match is done."),Sg),a("match_end (number, default=0))",v("Whether to treat the end of text as a delimiter."),Cg),a(`if_not_found (string, default="${E.NotAvailable}")`,v("Value to return if the delimiter is not found."))],compute:function(e,t,r={value:1},n={value:0},o={value:0},s=new x){const i=$t(e),a=kt(r,this.locale),l=kt(n,this.locale),c=kt(o,this.locale);if(0===a)return new S(v("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new S(v("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new S(v("match_end should have a value of 0 or 1."));const u=$t(t);if(""===u)return Math.sign(a)>0?{value:i}:{value:""};const h=1===l?"gi":"g",d=te(u),f=new RegExp(d,h);let g=[...i.matchAll(f)].map(e=>e.index+d.length);if(a<0&&(g=g.reverse()),c&&Math.abs(a)===g.length+1)return Math.sign(a)>0?{value:""}:{value:i};const m=g[Math.abs(a)-1];return void 0===m?s:{value:i.substring(m)}},isExported:!0},Kg={description:v("Returns text that occurs before a given substring or delimiter."),args:[a("text (string)",v("The source text.")),a("delimiter (string)",v("The substring after which text will be returned.")),a("instance_num (number, default=1)",v("The desired instance of the delimiter before which we extract the text. A negative number searches from the end.")),a("match_mode (number, default=0)",v("Searches the text for a delimiter match. By default, a case-sensitive match is done."),Sg),a("match_end (number, default=0))",v("Whether to match a delimiter against the end of the text."),Cg),a(`if_not_found (string, default="${E.NotAvailable}")`,v("Value to return if the delimiter is not found."))],compute:function(e,t,r={value:1},n={value:0},o={value:0},s=new x){const i=$t(e),a=kt(r,this.locale),l=kt(n,this.locale),c=kt(o,this.locale);if(0===a)return new S(v("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new S(v("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new S(v("match_end should have a value of 0 or 1."));const u=$t(t);if(""===u)return Math.sign(a)>0?{value:""}:{value:i};const h=1===l?"gi":"g",d=te(u),f=new RegExp(d,h);let g=[...i.matchAll(f)].map(e=>e.index+d.length);if(a<0&&(g=g.reverse()),c&&Math.abs(a)===g.length+1)return Math.sign(a)>0?{value:i}:{value:""};const m=g[Math.abs(a)-1];return void 0===m?s:{value:i.substring(0,m-u.length)}},isExported:!0};var Qg=Object.freeze({__proto__:null,CHAR:Tg,CLEAN:Ig,CONCATENATE:xg,EXACT:Rg,FIND:Ag,JOIN:Og,LEFT:_g,LEN:Dg,LOWER:Fg,MID:Ng,PROPER:Mg,REGEXEXTRACT:Vg,REPLACE:Lg,RIGHT:Pg,SEARCH:kg,SPLIT:Bg,SUBSTITUTE:zg,TEXT:Yg,TEXTAFTER:Xg,TEXTBEFORE:Kg,TEXTJOIN:$g,TEXTSPLIT:Wg,TRIM:qg,UPPER:Zg,VALUE:jg});const Jg={description:v("Creates a hyperlink in a cell."),args:[a("url (string)",v("The full URL of the link enclosed in quotation marks.")),a("link_label (string, optional)",v("The text to display in the cell, enclosed in quotation marks."))],compute:function(e,t){const r=$t(e).trim(),n=$t(t)||r;return""===r?n:pe(n,r)},isExported:!0};var em=Object.freeze({__proto__:null,HYPERLINK:Jg});const tm=/^[A-Z0-9\_\.]+$/;class rm extends h{mapping={};add(e,t){if((e=e.toUpperCase())in this.content)throw new Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){if(e=e.toUpperCase(),!tm.test(e))throw new Error(v("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const r=function(e,t){let r=0,n=0,o=0,s=0;for(const e of t.args)r++,e.optional||e.default||n++,e.repeating&&o++,!e.optional&&!e.default||e.repeating||s++;const i=t;return i.minArgRequired=n,i.maxArgPossible=o?1/0:r,i.nbrArgRepeating=o,i.nbrOptionalNonRepeatingArgs=s,i.hidden=t.hidden||!1,i.name=e,i}(e,t);return function(e){if(e.nbrArgRepeating&&e.nbrOptionalNonRepeatingArgs>=e.nbrArgRepeating)throw new Error(`Function ${e.name} has more optional arguments than repeatable ones.`);let t=!1,r=!1;for(const n of e.args){if(n.type.some(e=>u.includes(e))&&n.type.some(e=>!u.includes(e)))throw new Error(`Function ${e.name} has a mix of META and non-META types in the same argument: ${n.type}.`);if(n.repeating){if(!r&&t)throw new Error(`Function ${e.name} has non-consecutive repeating arguments. All repeating arguments must be declared consecutively.`);t=!0,r=!0}else r=!1}}(r),this.mapping[e]=Er(r),super.replace(e,r),this}}const nm=new rm,om=[{name:v("Array"),functions:lo},{name:v("Database"),functions:Hl},{name:v("Date"),functions:Du},{name:v("Filter"),functions:zu},{name:v("Financial"),functions:Kh},{name:v("Info"),functions:cd},{name:v("Lookup"),functions:Vf},{name:v("Logical"),functions:Cd},{name:v("Math"),functions:ta},{name:v("Misc"),functions:uo},{name:v("Operator"),functions:tg},{name:v("Statistical"),functions:Il},{name:v("Text"),functions:Qg},{name:v("Engineering"),functions:Mu},{name:v("Web"),functions:em},{name:v("Parser"),functions:Eg}];for(const e of om){const t=e.functions;for(let r in t){const n=t[r];n.category=n.category||e.name,r=r.replace(/_/g,"."),nm.add(r,{isExported:!1,...n})}}var sm;!function(e){e[e.LeftRef=0]="LeftRef",e[e.RightRef=1]="RightRef",e[e.Separator=2]="Separator",e[e.FullColumnSeparator=3]="FullColumnSeparator",e[e.FullRowSeparator=4]="FullRowSeparator",e[e.RightColumnRef=5]="RightColumnRef",e[e.RightRowRef=6]="RightRowRef",e[e.Found=7]="Found"}(sm||(sm={}));const im=(e,t=()=>!0)=>[{goTo:e,guard:t}],am=(e,t=()=>!0)=>({goTo:e,guard:t}),lm={[sm.LeftRef]:{REFERENCE:im(sm.Separator),NUMBER:im(sm.FullRowSeparator),SYMBOL:[am(sm.FullColumnSeparator,e=>yo(e.value)),am(sm.FullRowSeparator,e=>Eo(e.value))]},[sm.FullColumnSeparator]:{SPACE:im(sm.FullColumnSeparator),OPERATOR:im(sm.RightColumnRef,e=>":"===e.value)},[sm.FullRowSeparator]:{SPACE:im(sm.FullRowSeparator),OPERATOR:im(sm.RightRowRef,e=>":"===e.value)},[sm.Separator]:{SPACE:im(sm.Separator),OPERATOR:im(sm.RightRef,e=>":"===e.value)},[sm.RightRef]:{SPACE:im(sm.RightRef),NUMBER:im(sm.Found),REFERENCE:im(sm.Found,e=>Co(e.value)),SYMBOL:im(sm.Found,e=>wo(e.value)||So(e.value))},[sm.RightColumnRef]:{SPACE:im(sm.RightColumnRef),SYMBOL:im(sm.Found,e=>wo(e.value)),REFERENCE:im(sm.Found,e=>Co(e.value))},[sm.RightRowRef]:{SPACE:im(sm.RightRowRef),NUMBER:im(sm.Found),REFERENCE:im(sm.Found,e=>Co(e.value)),SYMBOL:im(sm.Found,e=>So(e.value))},[sm.Found]:{}};function cm(e){let t=0,r=lm[sm.LeftRef],n="";for(;void 0!==r;){const o=e[t++];if(!o)return null;const s=r[o.type]?.find(e=>e.guard(o)),i=s?s.goTo:void 0;switch(i){case void 0:return null;case sm.Found:return n+=o.value,e.splice(0,t),{type:"REFERENCE",value:n};default:r=lm[i],n+=o.value}}return null}function um(e,t=xr){const r=$l(e,t),n=[];for(;r.length;)n.push(cm(r)||r.shift());return n}const hm=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,dm=["-","+"],fm=["%"];class gm{tokens;currentIndex=0;current;length;constructor(e){this.tokens=e,this.current=e[0],this.length=e.length}shift(){const e=this.tokens[this.currentIndex];return this.current=this.tokens[++this.currentIndex],e}get next(){return this.tokens[this.currentIndex+1]}}const mm={"%":40,"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function pm(e){const t=e.shift();if(!t)throw new C;switch(t.type){case"DEBUGGER":const r=ym(e,1e3);return r.debug=!0,r;case"NUMBER":return{type:"NUMBER",value:Dt(t.value,xr),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"STRING":return{type:"STRING",value:oe(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"INVALID_REFERENCE":return{type:"REFERENCE",value:E.InvalidReference,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"REFERENCE":if(":"===e.current?.value&&"REFERENCE"===e.next?.type){e.shift();const r=e.shift();return{type:"REFERENCE",value:`${t.value}:${r?.value}`,tokenStartIndex:t.tokenIndex,tokenEndIndex:r.tokenIndex}}return{type:"REFERENCE",value:t.value,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"SYMBOL":const n=t.value,o=e.current;if("LEFT_PAREN"===o?.type&&hm.test(t.value)&&n===oe(n,"'")){const{args:r,rightParen:o}=function(e){vm(e,"LEFT_PAREN",v("Missing opening parenthesis"));const t=e.current;if("RIGHT_PAREN"===t?.type){return{args:[],rightParen:vm(e,"RIGHT_PAREN")}}const r=[];r.push(bm(e));for(;"RIGHT_PAREN"!==e.current?.type;)vm(e,"ARG_SEPARATOR",v("Wrong function call")),r.push(bm(e));const n=vm(e,"RIGHT_PAREN");return{args:r,rightParen:n}}(e);return{type:"FUNCALL",value:n,args:r,tokenStartIndex:t.tokenIndex,tokenEndIndex:o.tokenIndex}}const s=n.toUpperCase();return"TRUE"===s||"FALSE"===s?{type:"BOOLEAN",value:"TRUE"===s,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:"SYMBOL",value:oe(t.value,"'"),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"LEFT_PAREN":const i=ym(e),a=vm(e,"RIGHT_PAREN",v("Missing closing parenthesis"));return{...i,tokenStartIndex:t.tokenIndex,tokenEndIndex:a.tokenIndex};case"LEFT_BRACE":return function(e,t){const r=[];let n=[ym(e)];for(;"RIGHT_BRACE"!==e.current?.type;){const t=e.shift();if(!t)throw new C(v("Missing closing brace"));if("ARG_SEPARATOR"===t.type)n.push(ym(e));else{if("ARRAY_ROW_SEPARATOR"!==t.type)throw new C(v("Unexpected token: %s",t.value));r.push(n),n=[ym(e)]}}const o=vm(e,"RIGHT_BRACE",v("Missing closing brace"));return r.push(n),{type:"ARRAY",value:r,tokenStartIndex:t.tokenIndex,tokenEndIndex:o.tokenIndex}}(e,t);case"OPERATOR":const l=t.value;if(dm.includes(l)){const r=ym(e,mm[l]);return{type:"UNARY_OPERATION",value:l,operand:r,tokenStartIndex:t.tokenIndex,tokenEndIndex:r.tokenEndIndex}}throw new C(v("Unexpected token: %s",t.value));default:throw new C(v("Unexpected token: %s",t.value))}}function bm(e){const t=e.current;return"ARG_SEPARATOR"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:"",tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:ym(e)}function vm(e,t,r){const n=e.shift();if(!n||n.type!==t)throw new C(r);return n}function ym(e,t=0){if(0===e.length)throw new C;let r=pm(e);for(;"OPERATOR"===e.current?.type&&mm[e.current.value]>t;){const t=e.shift(),n=t.value;if(fm.includes(n))r={type:"UNARY_OPERATION",value:n,operand:r,postfix:!0,tokenStartIndex:r.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{const t=ym(e,mm[n]);r={type:"BIN_OPERATION",value:n,left:r,right:t,tokenStartIndex:r.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return r}function Em(e){return wm(um(e))}function wm(e){const t=e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>"SPACE"!==e.type),r=new gm(t);"="===r.current?.value&&r.shift();const n=ym(r);if(r.current)throw new C;return n}function Sm(e,t,r){return Im(e,e=>e.type===t?r(e):e)}function Cm(e){return Array.from(Tm(e))}function*Tm(e){switch(yield e,e.type){case"FUNCALL":for(const t of e.args)yield*Tm(t);break;case"ARRAY":for(const t of e.value)for(const e of t)yield*Tm(e);break;case"UNARY_OPERATION":yield*Tm(e.operand);break;case"BIN_OPERATION":yield*Tm(e.left),yield*Tm(e.right)}}function Im(e,t){switch((e=t(e)).type){case"FUNCALL":return{...e,args:e.args.map(e=>Im(e,t))};case"ARRAY":return{...e,value:e.value.map(e=>e.map(e=>Im(e,t)))};case"UNARY_OPERATION":return{...e,operand:Im(e.operand,t)};case"BIN_OPERATION":return{...e,right:Im(e.right,t),left:Im(e.left,t)};default:return e}}const xm=nm.content,Rm={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},Am={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},Om={};function _m(e){return Dm(um(e))}function Dm(e){try{return function(e){const{dependencies:r,literalValues:o,symbols:s}=function(e){const t={numbers:[],strings:[]},r=[],n=[];for(const o of e)switch(o.type){case"INVALID_REFERENCE":case"REFERENCE":r.push(o.value);break;case"STRING":const e=oe(o.value);t.strings.push({value:e});break;case"NUMBER":{const e=Dt(o.value,xr);t.numbers.push({value:e});break}case"SYMBOL":n.push(oe(o.value,"'"))}return{dependencies:r,literalValues:t,symbols:n}}(e),i=function(e){let t="";for(const r of e)switch(r.type){case"STRING":t+="|S|";break;case"NUMBER":t+="|N|";break;case"REFERENCE":case"INVALID_REFERENCE":r.value.includes(":")?t+="|R|":t+="|C|";break;case"SPACE":break;default:t+=r.value}return t}(e);if(!Om[i]){const l=wm([...e]),u=new n;let h=0,d=0,f=0;if("BIN_OPERATION"===l.type&&":"===l.value)throw new C(v("Invalid formula"));if("EMPTY"===l.type)throw new C(v("Invalid formula"));const g=y(l),m=new t;m.append(`// ${i}`),m.append(g),m.append(`return ${g.returnExpression};`);const p=new Function("deps","ref","range","getSymbolValue","ctx",m.toString());function b(e){const{args:t}=e,r=e.value.toUpperCase(),n=xm[r];if(!n)throw new R(v('Unknown function: "%s"',e.value));!function(e){const t=e.args.length,r=e.value.toUpperCase(),n=xm[r],{nbrArgRepeating:o,minArgRequired:s}=n;if(t<s)throw new C(v("Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.",{functionName:r,minArgRequired:s,nbrArgSupplied:t}));if(t>n.maxArgPossible)throw new C(v("Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.",{functionName:r,maxArgPossible:n.maxArgPossible,nbrArgSupplied:t}));if(o>1){const e=t-s-o*Math.floor((t-s)/o)-n.nbrOptionalNonRepeatingArgs;if(e>0)throw new C(v("Invalid number of arguments for the %(functionName)s function. Repeatable arguments should be supplied in groups of %(nbrArgRepeating)s, with up to %(nbrArgOptional)s optional. Got %(nbrValueRemaining)s too many.",{functionName:r,nbrArgRepeating:o,nbrArgOptional:n.nbrOptionalNonRepeatingArgs,nbrValueRemaining:e}))}}(e);const o=[],s=c(n,t.length);for(let e=0;e<t.length;e++){const r=n.args[s(e).index??-1],i=t[e],a=r.type||[],l=a.includes("META")||a.includes("RANGE<META>"),c=a.some(e=>Fm(e));o.push(y(i,l,c))}return o}function y(e,r=!1,n=!1){const o=new t(u);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&r)throw new C(v("Argument must be a reference to a cell or range."));switch(e.debug&&(o.append("debugger;"),o.append('ctx["debug"] = true;')),e.type){case"BOOLEAN":return o.return(`{ value: ${e.value} }`);case"NUMBER":return o.return(`this.literalValues.numbers[${d++}]`);case"STRING":return o.return(`this.literalValues.strings[${h++}]`);case"REFERENCE":return o.return(`${e.value.includes(":")||n?"range":"ref"}(deps[${f++}], ${r?"true":"false"})`);case"FUNCALL":const t=b(e).map(e=>e.assignResultToVariable());o.append(...t);const i=e.value.toUpperCase();return o.return(`ctx['${i}'](${t.map(e=>e.returnExpression)})`);case"ARRAY":return y({type:"FUNCALL",value:"ARRAY.LITERAL",args:e.value.map(e=>({type:"FUNCALL",value:"ARRAY.ROW",args:e,tokenStartIndex:0,tokenEndIndex:0})),tokenStartIndex:0,tokenEndIndex:0});case"UNARY_OPERATION":{const t=Am[e.value],r=y(e.operand,!1,!1).assignResultToVariable();return o.append(r),o.return(`ctx['${t}'](${r.returnExpression})`)}case"BIN_OPERATION":{const t=Rm[e.value],r=y(e.left,!1,!1).assignResultToVariable(),n=y(e.right,!1,!1).assignResultToVariable();return o.append(r),o.append(n),o.return(`ctx['${t}'](${r.returnExpression}, ${n.returnExpression})`)}case"SYMBOL":const a=s.indexOf(e.value);return o.return(`getSymbolValue(this.symbols[${a}])`);case"EMPTY":return o.return("undefined")}}Om[i]=p}const a={execute:Om[i],dependencies:r,literalValues:o,symbols:s,tokens:e,isBadExpression:!1,normalizedFormula:i};return a}(e)}catch(t){return{tokens:e,dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map(e=>e.value).join("")}}}function Fm(e){return e.startsWith("RANGE")}class Nm{listeners=[];async 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 Mm{transportService;constructor(e){this.transportService=e}async sendMessage(e){"CLIENT_JOINED"!==e.type&&"CLIENT_LEFT"!==e.type&&"CLIENT_MOVED"!==e.type||await this.transportService.sendMessage(e)}onNewMessage(e,t){this.transportService.onNewMessage(e,t)}leave(e){this.transportService.leave(e)}}class Vm{subscriptions={};on(e,t,r){if(!r)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:r})}trigger(e,t){const r=this.subscriptions[e]||[];for(let e=0,n=r.length;e<n;e++){const n=r[e];n.callback.call(n.owner,t)}}off(e,t){const r=this.subscriptions[e];r&&(this.subscriptions[e]=r.filter(e=>e.owner!==t))}clear(){this.subscriptions={}}}function Lm(e,t){const r=e.zone,n=function(e,t){const{left:r,top:n,bottom:o,right:s}=e;if(void 0!==s&&void 0!==o)return e;if(void 0===o&&void 0!==s)return{right:s,top:n,left:r,bottom:t.numberOfRows-1};if(void 0===s&&void 0!==o)return{bottom:o,left:r,top:n,right:t.numberOfCols-1};throw new Error("Bad zone format")}(r,t(e.sheetId));let o=e.parts;return 1===e.parts.length&&Es(n)>1?o=[e.parts[0],e.parts[0]]:2===e.parts.length&&1===Es(n)&&(o=[e.parts[0]]),{unboundedZone:r,zone:n,parts:o,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Pm(e,t){const r=e.xc,{xc:n,sheetName:o}=To(r),s=Xo(n),i=function(e,t){const r=e.split(":").map(e=>{const t=Eo(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}}),n=void 0===t.bottom,o=void 0===t.right;n&&(r[0].rowFixed=r[0].rowFixed||r[1].rowFixed,r[1].rowFixed=r[0].rowFixed||r[1].rowFixed);o&&(r[0].colFixed=r[0].colFixed||r[1].colFixed,r[1].colFixed=r[0].colFixed||r[1].colFixed);return r}(n,s);return Lm({zone:s,parts:i,sheetId:e.sheetId,prefixSheet:Boolean(o),invalidSheetName:e.invalidSheetName},t)}function km(e){const t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:"",zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function Um(e){return ys(e.unboundedZone)}function Hm(e){return vs(e.unboundedZone)}function Bm(e,t,r,n={useBoundedReference:!1,useFixedReference:!1}){if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return E.InvalidReference;if(e.zone.left<0||e.zone.top<0)return E.InvalidReference;const o=e.sheetId!==t||e.invalidSheetName||e.prefixSheet;let s="";if(o&&(s=e.invalidSheetName?se(e.invalidSheetName):se(r(e.sheetId))),o&&!s)return E.InvalidReference;let i=Jm(e,0,n);return 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+=":",i+=Jm(e,1,n)),`${o?s+"!":""}${i}`}function zm(e,t,r){const n=r.sheetId===e?t:r.sheetId;return{...r,sheetId:n}}function $m(e){const t=[];for(const r of e)for(const e of ds(r.zone))t.push({...e,sheetId:r.sheetId});return t}function Gm(e){const t={left:e.col,top:e.row,right:e.col,bottom:e.row};return{sheetId:e.sheetId,zone:t}}function Wm(e){return qm.get(e.type)?.(e)}const qm=new class extends Id{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};function Zm(e){const t="COL"===e.dimension?"left":"top",r="COL"===e.dimension?"right":"bottom",n="COL"===e.dimension?"columns":"rows",o=[...e.elements];o.sort((e,t)=>t-e);const s=ce(o);return o=>{if(o.sheetId!==e.sheetId)return{changeType:"NONE",range:o};let i=o,a="NONE";for(const e of s){const s=qe(e),l=We(e);if(o.zone[t]<=s&&s<=o.zone[r]){const e=Math.min(o.zone[r],l)-s+1;a="RESIZE",i=Qm(i,n,a,-e)}else if(o.zone[t]>=s&&o.zone[r]<=l)a="REMOVE",i=km(E.InvalidReference);else if(o.zone[t]<=l&&o.zone[r]>=l){const e=l-o.zone[t]+1;a="RESIZE",i=Qm(i,n,a,-e),i=Qm(i,n,"MOVE",-(o.zone[t]-s))}else s<o.zone[t]&&(a="MOVE",i=Qm(i,n,a,-(l-s+1)))}return{changeType:a,range:i}}}function Ym(e){const t="COL"===e.dimension?"left":"top",r="COL"===e.dimension?"right":"bottom",n="COL"===e.dimension?"columns":"rows";return o=>{if(o.sheetId!==e.sheetId)return{changeType:"NONE",range:o};if("after"===e.position){if(o.zone[t]<=e.base&&e.base<o.zone[r])return{changeType:"RESIZE",range:Qm(o,n,"RESIZE",e.quantity)};if(e.base<o.zone[t])return{changeType:"MOVE",range:Qm(o,n,"MOVE",e.quantity)}}else{if(o.zone[t]<e.base&&e.base<=o.zone[r])return{changeType:"RESIZE",range:Qm(o,n,"RESIZE",e.quantity)};if(e.base<=o.zone[t])return{changeType:"MOVE",range:Qm(o,n,"MOVE",e.quantity)}}return{changeType:"NONE",range:o}}}function jm(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:"NONE",range:t};const r=e.sheetName;return{changeType:"REMOVE",range:t={...km(E.InvalidReference),invalidSheetName:r}}}}function Xm(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.newName&&t.invalidSheetName===e.newName){const r=void 0,n=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:n,invalidSheetName:r}}}if(e.oldName&&t.invalidSheetName===e.oldName){const r=void 0,n=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:n,invalidSheetName:r}}}return{changeType:"NONE",range:t}}}function Km(e){const t=e.target[0];return r=>{if(r.sheetId!==e.sheetId||!cs(r.zone,t))return{changeType:"NONE",range:r};const n=e.targetSheetId,o=Qm(r,"both","MOVE",[e.col-t.left,e.row-t.top]),s=e.sheetId!==n||o.prefixSheet;return{changeType:"MOVE",range:{...o,sheetId:n,prefixSheet:s}}}}function Qm(e,t,r,n){return{...e,unboundedZone:ms(e.unboundedZone,t,r,n),zone:ms(e.zone,t,r,n)}}function Jm(e,t,r={useBoundedReference:!1,useFixedReference:!1}){const n=e.parts[t]?.colFixed||r.useFixedReference?"$":"",o=Do(0===t?e.zone.left:e.zone.right),s=e.parts[t]?.rowFixed||r.useFixedReference?"$":"",i=String(0===t?e.zone.top+1:e.zone.bottom+1);let a="";return a=ys(e.unboundedZone)&&!r.useBoundedReference?0===t&&e.unboundedZone.hasHeader?n+o+s+i:n+o:vs(e.unboundedZone)&&!r.useBoundedReference?0===t&&e.unboundedZone.hasHeader?n+o+s+i:s+i:n+o+s+i,a}function ep(e){const t=[];for(let r=0;r<e;r++){const e={cells:{}};t.push(e)}return t}function tp(e,t,r){return r.map(r=>r>=e?r+t:r)}function rp(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(const r of e)if(t>r)t--;else if(t===r)return;return t}).filter(Se)}function np(e,t="Sheet"){let r=1,n=`${t}${r}`;for(;e.includes(n);)n=`${t}${r}`,r++;return n}function op(e,t){let r=1;const n=v("Copy of %s",e);let o=n.toString();for(;t.includes(o);)o=`${n} (${r})`,r++;return o}qm.add("REMOVE_COLUMNS_ROWS",e=>({applyChange:Zm(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("ADD_COLUMNS_ROWS",e=>({applyChange:Ym(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("DELETE_SHEET",e=>({applyChange:jm(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("RENAME_SHEET",e=>({applyChange:Xm(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add("MOVE_RANGES",e=>({applyChange:Km(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));const sp=Ue(function(e){return ne(e.trim().toUpperCase())});function ip(e,t){return void 0!==e&&void 0!==t&&sp(e)===sp(t)}const ap=new class extends Id{addTransformation(e,t,r){this.content[e]||(this.content[e]=new Map);for(const n of t)this.content[e].set(n,r);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}};const lp=new class extends Id{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};function cp(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?function(e,t,r){const n="left"===t?"right":"bottom";let o=e[t],s=e[n];const i=e[n];for(const n of r.sort((e,t)=>t-e))e[t]>n&&(o--,void 0!==s&&s--),void 0!==i&&void 0!==s&&e[t]<=n&&i>=n&&s--;if(!(void 0!==s&&o>s))return{...e,[t]:o,[n]:s}}(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?function(e,t,r,n,o){const s="left"===t?"columns":"rows",i="before"===n?r-1:r,a=e["left"===t?"right":"bottom"];return e[t]<=i&&a&&a>i?ms(e,s,"RESIZE",o):i<e[t]?ms(e,s,"MOVE",o):{...e}}(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):e}function up(e,t){const r="DELETE_SHEET"===t.type&&t.sheetId;if("sheetId"in t&&e._sheetId!==t.sheetId)return e;{const n=cp(e._zone,t);if(n&&r!==e._sheetId)return{...e,_zone:n}}}const hp=/rgba?\(|\s+|\)/gi,dp=/^#([A-F\d]{2}){3,4}$/;function fp(e,t=1){const r=1!==t?Math.round(255*t).toString(16).padStart(2,"0"):"";return mp(e.toString(16).padStart(6,"0"))+r}function gp(e){return"number"==typeof e?e:Number.parseInt(mp(e).slice(1,7),16)}function mp(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(hp,"").split(",");let r=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");if(isNaN(e))throw new Error("invalid alpha value");r=Math.round(255*e)}const n=t.map(e=>parseInt(e,10));255!==r&&n.push(r);return"#"+Ie(n.map(e=>e.toString(16).padStart(2,"0"))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce((e,t)=>e+t+t,"")),t=`#${t}`),!dp.test(t))throw new Error(`invalid color input: ${e}`);return t}function pp(e){try{return mp(e),!0}catch(e){return!1}}const bp=e=>e>=0&&e<=255;function vp(e,t,r,n=1){if(!bp(e)||!bp(t)||!bp(r)||n<0||n>1)throw new Error(`Invalid RGBA values ${[e,t,r,n]}`);return{a:n,b:r,g:t,r:e}}function yp(e){let{r:t,g:r,b:n}=wp(e);t/=255,r/=255,n/=255;const o=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*o(t)+.7152*o(r)+.0722*o(n)}function Ep(e){let t=e.r.toString(16),r=e.g.toString(16),n=e.b.toString(16),o=Math.round(255*e.a).toString(16);return 1===t.length&&(t="0"+t),1===r.length&&(r="0"+r),1===n.length&&(n="0"+n),1===o.length&&(o="0"+o),"ff"===o&&(o=""),("#"+t+r+n+o).toUpperCase()}function wp(e){let t,r,n,o;if(7===(e=mp(e)).length)t=parseInt(e[1]+e[2],16),r=parseInt(e[3]+e[4],16),n=parseInt(e[5]+e[6],16),o=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),r=parseInt(e[3]+e[4],16),n=parseInt(e[5]+e[6],16),o=parseInt(e[7]+e[8],16)}return o=+(o/255).toFixed(3),{a:o,r:t,g:r,b:n}}function Sp(e){(e={...e}).s/=100,e.l/=100;const t=(1-Math.abs(2*e.l-1))*e.s,r=t*(1-Math.abs(e.h/60%2-1)),n=e.l-t/2;let o=0,s=0,i=0;return 0<=e.h&&e.h<60?(o=t,s=r,i=0):60<=e.h&&e.h<120?(o=r,s=t,i=0):120<=e.h&&e.h<180?(o=0,s=t,i=r):180<=e.h&&e.h<240?(o=0,s=r,i=t):240<=e.h&&e.h<300?(o=r,s=0,i=t):300<=e.h&&e.h<360&&(o=t,s=0,i=r),o=Math.round(255*(o+n)),s=Math.round(255*(s+n)),i=Math.round(255*(i+n)),{a:e.a,r:o,g:s,b:i}}function Cp(e){const t=e.r/255,r=e.g/255,n=e.b/255,o=Math.min(t,r,n),s=Math.max(t,r,n),i=s-o;let a=0,l=0,c=0;return a=0===i?0:s===t?(r-n)/i%6:s===r?(n-t)/i+2:(t-r)/i+4,a=Math.round(60*a),a<0&&(a+=360),c=(s+o)/2,l=0===i?0:i/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}function Tp(e){return Ep(Sp(e))}function Ip(e){return Cp(wp(e))}function xp(e){return wp("number"==typeof e?fp(e):e)}function Rp(e,t){const r=Ip(e);return 1===t?"#fff":(r.l=t*(100-r.l)+r.l,Tp(r))}function Ap(e,t){const r=Ip(e);return 1===t?"#000":(r.s=Math.min(100,t*r.s+r.s),r.l=r.l-t*r.l,Tp(r))}const Op=["#4EA7F2","#EA6175","#43C5B1","#F4A261","#8481DD","#FFD86D"],_p=["#4EA7F2","#3188E6","#43C5B1","#00A78D","#EA6175","#CE4257","#F4A261","#F48935","#8481DD","#5752D1","#FFD86D","#FFBC2C"],Dp=["#4EA7F2","#3188E6","#056BD9","#A76DBC","#7F4295","#6D2387","#EA6175","#CE4257","#982738","#43C5B1","#00A78D","#0E8270","#F4A261","#F48935","#BE5D10","#8481DD","#5752D1","#3A3580","#A4A8B6","#7E8290","#545B70","#FFD86D","#FFBC2C","#C08A16"],Fp=["#4EA7F2","#3188E6","#056BD9","#155193","#A76DBC","#7F4295","#6D2387","#4F1565","#EA6175","#CE4257","#982738","#791B29","#43C5B1","#00A78D","#0E8270","#105F53","#F4A261","#F48935","#BE5D10","#7D380D","#8481DD","#5752D1","#3A3580","#26235F","#A4A8B6","#7E8290","#545B70","#3F4250","#FFD86D","#FFBC2C","#C08A16","#936A12"],Np=["#4EA7F2","#43C5B1","#EA6175","#F4A261","#8481DD","#FFD86D","#3188E6","#00A78D","#CE4257","#F48935","#5752D1","#FFBC2C"],Mp=["#4EA7F2","#A76DBC","#EA6175","#43C5B1","#F4A261","#8481DD","#A4A8B6","#FFD86D","#3188E6","#7F4295","#CE4257","#00A78D","#F48935","#5752D1","#7E8290","#FFBC2C","#056BD9","#6D2387","#982738","#0E8270","#BE5D10","#3A3580","#545B70","#C08A16"],Vp=["#4EA7F2","#A76DBC","#EA6175","#43C5B1","#F4A261","#8481DD","#A4A8B6","#FFD86D","#3188E6","#7F4295","#CE4257","#00A78D","#F48935","#5752D1","#7E8290","#FFBC2C","#056BD9","#6D2387","#982738","#0E8270","#BE5D10","#3A3580","#545B70","#C08A16","#155193","#4F1565","#791B29","#105F53","#7D380D","#26235F","#3F4250","#936A12"];class Lp{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){var r;this.preferredColors=t,this.palette=(r=e,r<=6?Op:r<=12?_p:r<=24?Dp:Fp).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:(e=this.currentColorIndex++,(t=this.palette)[e%t.length]);var e,t}}class Pp extends Lp{constructor(e,t=[]){var r;super(e,t),this.palette=(r=e,r<=6?Op:r<=12?Np:r<=24?Mp:Vp).filter(e=>!t.includes(e))}}class kp{availableColors;colors={};constructor(e=12){this.availableColors=new Pp(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}}const Up={greys:["#ffffff","#808080","#000000"],blues:["#f7fbff","#6aaed6","#08306b"],reds:["#fff5f0","#fb694a","#67000d"],greens:["#f7fcf5","#73c476","#00441b"],oranges:["#fff5eb","#fd8c3b","#7f2704"],purples:["#fcfbfd","#9e9ac8","#3f007d"],viridis:["#440154","#21918c","#fde725"],cividis:["#00224e","#7d7c78","#fee838"],rainbow:["#B41DB4","#FFFF00","#00FFFF"]};function Hp(e,t,r,n){const o=t-e;return[((r>>16)%256-(n>>16)%256)/o,((r>>8)%256-(n>>8)%256)/o,(r%256-n%256)/o]}function Bp(e,t,r,n){const[o,s,i]=n;return Math.round((r>>16)%256-o*(e-t))<<16|Math.round((r>>8)%256-s*(e-t))<<8|Math.round(r%256-i*(e-t))}v("Light"),v("Medium"),v("Dark"),v("Custom");const zp={hasFilters:!1,totalRow:!1,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,automaticAutofill:!0,styleId:"TableStyleMedium2"};function $p(e,t){return{coloredText:Ap(t,.3),light:Rp(t,.8),medium:Rp(t,.6),dark:Ap(t,.3),mediumBorder:Rp(t,.45),highlight:t,name:e}}const Gp={black:{name:v("Black"),coloredText:"#000000",light:"#D9D9D9",medium:"#A6A6A6",dark:"#404040",mediumBorder:"#000000",highlight:"#000000"},lightBlue:$p(v("Light blue"),"#346B90"),red:$p(v("Red"),"#C53628"),lightGreen:$p(v("Light green"),"#748747"),purple:$p(v("Purple"),"#6C4E65"),gray:{name:v("Gray"),coloredText:"#666666",light:"#EEEEEE",medium:"#DDDDDD",dark:"#767676",mediumBorder:"#D0D0D0",highlight:"#A9A9A9"},orange:$p(v("Orange"),"#C37034")},Wp={black:Gp.black,orangeBlue:{...Gp.lightBlue,highlight:Gp.orange.highlight},purpleGreen:{...Gp.lightGreen,highlight:Gp.purple.highlight},redBlue:{...Gp.lightBlue,highlight:Gp.red.highlight}},qp=e=>({category:"light",templateName:"lightColoredText",primaryColor:e.highlight,wholeTable:{style:{textColor:e.coloredText},border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"}}},headerRow:{border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"thin"}}},firstRowStripe:{style:{fillColor:e.light}}}),Zp=e=>({category:"light",templateName:"lightWithHeader",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"},left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"},border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}},secondRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}}}),Yp=e=>({category:"light",templateName:"lightAllBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"},left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"},horizontal:{color:e.highlight,style:"thin"},vertical:{color:e.highlight,style:"thin"}}},headerRow:{border:{bottom:{color:e.highlight,style:"medium"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}}}),jp=e=>({category:"medium",templateName:"mediumBandedBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"},horizontal:{color:e.mediumBorder,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}}}),Xp=e=>({category:"medium",templateName:"mediumWhiteBorders",primaryColor:e.highlight,wholeTable:{border:{horizontal:{color:"#FFFFFF",style:"thin"},vertical:{color:"#FFFFFF",style:"thin"}},style:{fillColor:e.light}},headerRow:{border:{bottom:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{border:{top:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),Kp=e=>({category:"medium",templateName:"mediumMinimalBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:"#000000",style:"medium"},bottom:{color:"#000000",style:"medium"}}},totalRow:{border:{top:{color:"#000000",style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"},border:{bottom:{color:"#000000",style:"medium"}}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:Gp.black.light}},firstColumnStripe:{style:{fillColor:Gp.black.light}}}),Qp=e=>({category:"medium",templateName:"mediumAllBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"},horizontal:{color:e.mediumBorder,style:"thin"},vertical:{color:e.mediumBorder,style:"thin"}},style:{fillColor:e.light}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),Jp=e=>({category:"dark",templateName:"dark",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{style:{fillColor:e.dark,textColor:"#FFFFFF"},border:{top:{color:"#FFFFFF",style:"thick"}}},headerRow:{style:{fillColor:"#000000"},border:{bottom:{color:"#FFFFFF",style:"thick"}}},firstColumn:{style:{fillColor:e.dark},border:{right:{color:"#FFFFFF",style:"thick"}}},lastColumn:{style:{fillColor:e.dark},border:{left:{color:"#FFFFFF",style:"thick"}}},firstRowStripe:{style:{fillColor:e.dark}},firstColumnStripe:{style:{fillColor:e.dark}}}),eb=e=>({category:"dark",templateName:"darkNoBorders",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.light}},totalRow:{border:{top:{color:"#000000",style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),tb=Jp(Gp.black);tb.wholeTable.style.fillColor="#737373";const rb=Kp(Gp.black);function nb(e,t,r){return{...t(r),displayName:`${r.name}, ${e}`}}rb.wholeTable.border={...rb.wholeTable.border,left:{color:"#000000",style:"thin"},right:{color:"#000000",style:"thin"},horizontal:{color:"#000000",style:"thin"},vertical:{color:"#000000",style:"thin"}};const ob={None:{category:"light",templateName:"none",primaryColor:"",displayName:"none"},TableStyleLight1:nb("TableStyleLight1",qp,Gp.black),TableStyleLight2:nb("TableStyleLight2",qp,Gp.lightBlue),TableStyleLight3:nb("TableStyleLight3",qp,Gp.red),TableStyleLight4:nb("TableStyleLight4",qp,Gp.lightGreen),TableStyleLight5:nb("TableStyleLight5",qp,Gp.purple),TableStyleLight6:nb("TableStyleLight6",qp,Gp.gray),TableStyleLight7:nb("TableStyleLight7",qp,Gp.orange),TableStyleLight8:nb("TableStyleLight8",Zp,Gp.black),TableStyleLight9:nb("TableStyleLight9",Zp,Gp.lightBlue),TableStyleLight10:nb("TableStyleLight10",Zp,Gp.red),TableStyleLight11:nb("TableStyleLight11",Zp,Gp.lightGreen),TableStyleLight12:nb("TableStyleLight12",Zp,Gp.purple),TableStyleLight13:nb("TableStyleLight13",Zp,Gp.gray),TableStyleLight14:nb("TableStyleLight14",Zp,Gp.orange),TableStyleLight15:nb("TableStyleLight15",Yp,Gp.black),TableStyleLight16:nb("TableStyleLight16",Yp,Gp.lightBlue),TableStyleLight17:nb("TableStyleLight17",Yp,Gp.red),TableStyleLight18:nb("TableStyleLight18",Yp,Gp.lightGreen),TableStyleLight19:nb("TableStyleLight19",Yp,Gp.purple),TableStyleLight20:nb("TableStyleLight20",Yp,Gp.gray),TableStyleLight21:nb("TableStyleLight21",Yp,Gp.orange),TableStyleMedium1:nb("TableStyleMedium1",jp,Gp.black),TableStyleMedium2:nb("TableStyleMedium2",jp,Gp.lightBlue),TableStyleMedium3:nb("TableStyleMedium3",jp,Gp.red),TableStyleMedium4:nb("TableStyleMedium4",jp,Gp.lightGreen),TableStyleMedium5:nb("TableStyleMedium5",jp,Gp.purple),TableStyleMedium6:nb("TableStyleMedium6",jp,Gp.gray),TableStyleMedium7:nb("TableStyleMedium7",jp,Gp.orange),TableStyleMedium8:nb("TableStyleMedium8",Xp,Gp.black),TableStyleMedium9:nb("TableStyleMedium9",Xp,Gp.lightBlue),TableStyleMedium10:nb("TableStyleMedium10",Xp,Gp.red),TableStyleMedium11:nb("TableStyleMedium11",Xp,Gp.lightGreen),TableStyleMedium12:nb("TableStyleMedium12",Xp,Gp.purple),TableStyleMedium13:nb("TableStyleMedium13",Xp,Gp.gray),TableStyleMedium14:nb("TableStyleMedium14",Xp,Gp.orange),TableStyleMedium15:{...rb,displayName:"Black, TableStyleMedium15"},TableStyleMedium16:nb("TableStyleMedium16",Kp,Gp.lightBlue),TableStyleMedium17:nb("TableStyleMedium17",Kp,Gp.red),TableStyleMedium18:nb("TableStyleMedium18",Kp,Gp.lightGreen),TableStyleMedium19:nb("TableStyleMedium19",Kp,Gp.purple),TableStyleMedium20:nb("TableStyleMedium20",Kp,Gp.gray),TableStyleMedium21:nb("TableStyleMedium21",Kp,Gp.orange),TableStyleMedium22:nb("TableStyleMedium22",Qp,Gp.black),TableStyleMedium23:nb("TableStyleMedium23",Qp,Gp.lightBlue),TableStyleMedium24:nb("TableStyleMedium24",Qp,Gp.red),TableStyleMedium25:nb("TableStyleMedium25",Qp,Gp.lightGreen),TableStyleMedium26:nb("TableStyleMedium26",Qp,Gp.purple),TableStyleMedium27:nb("TableStyleMedium27",Qp,Gp.gray),TableStyleMedium28:nb("TableStyleMedium28",Qp,Gp.orange),TableStyleDark1:{...tb,displayName:"Black, TableStyleDark1"},TableStyleDark2:nb("TableStyleDark2",Jp,Gp.lightBlue),TableStyleDark3:nb("TableStyleDark3",Jp,Gp.red),TableStyleDark4:nb("TableStyleDark4",Jp,Gp.lightGreen),TableStyleDark5:nb("TableStyleDark5",Jp,Gp.purple),TableStyleDark6:nb("TableStyleDark6",Jp,Gp.gray),TableStyleDark7:nb("TableStyleDark7",Jp,Gp.orange),TableStyleDark8:nb("TableStyleDark8",eb,Wp.black),TableStyleDark9:nb("TableStyleDark9",eb,Wp.redBlue),TableStyleDark10:nb("TableStyleDark10",eb,Wp.purpleGreen),TableStyleDark11:nb("TableStyleDark11",eb,Wp.orangeBlue)},sb={none:()=>({category:"none",templateName:"none",primaryColor:"",name:"none"}),lightColoredText:qp,lightAllBorders:Yp,mediumAllBorders:Qp,lightWithHeader:Zp,mediumBandedBorders:jp,mediumMinimalBorders:Kp,darkNoBorders:eb,mediumWhiteBorders:Xp,dark:Jp};function ib(e,t,r){const n=$p("",r);return{...sb[t](n),category:"custom",displayName:e}}function ab(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId!==t.sheetId)return e;const r=cp(e.pivot.dataSet.zone,t),n=r?{...e.pivot.dataSet,zone:r}:void 0;return{...e,pivot:{...e.pivot,dataSet:n}}}function lb(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let r=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort((e,t)=>t-e);for(const t of e)r>t&&r--}if("ADD_COLUMNS_ROWS"===t.type){r=r>("before"===t.position?t.base-1:t.base)?r+t.quantity:r}return r>0?{...e,quantity:r}:void 0}function cb(e,t){if(e.sheetId!==t.sheetId)return e;const r=cp(e.zone,t);if(!r)return;const n=e.newTableRange?up(e.newTableRange,t):void 0;return{...e,newTableRange:n,zone:r}}function ub(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let r;if("REMOVE_COLUMNS_ROWS"===t.type)r=rp(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){r=tp(Re(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==r?{...e,base:r}:void 0}function hb(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;const r=le(e.start,e.end+1);let n=[];if("REMOVE_COLUMNS_ROWS"===t.type)n=rp(t.elements,r);else if("ADD_COLUMNS_ROWS"===t.type){n=tp(Re(t.position,t.base),t.quantity,r)}return 0!==n.length?{...e,start:Math.min(...n),end:Math.max(...n)}:void 0}ap.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],ub),ap.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],ub),ap.addTransformation("DELETE_SHEET",["MOVE_RANGES"],function(e,t){const r=t.sheetId;if(e.targetSheetId===r||e.sheetId===r)return;return e}),ap.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART","UPDATE_CAROUSEL"],function(e,t){if(e.figureId===t.figureId)return;return e}),ap.addTransformation("DELETE_CHART",["UPDATE_CHART"],function(e,t){if(e.chartId===t.chartId)return;return e}),ap.addTransformation("DELETE_CHART",["UPDATE_CAROUSEL"],function(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!("chart"===e.type&&e.chartId===t.chartId))}}}),ap.addTransformation("CREATE_SHEET",["CREATE_SHEET"],function(e,t){e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`});if(e.name===t.name)return{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1};return e}),ap.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],function(e,t){if(e.sheetId!==t.sheetId)return e;const r=[];for(const n of e.target)t.target.every(e=>!as(n,e))&&r.push(n);if(r.length)return{...e,target:r};return}),ap.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],lb),ap.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],lb),ap.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],cb),ap.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],cb),ap.addTransformation("REMOVE_TABLE_STYLE",["CREATE_TABLE","UPDATE_TABLE"],function(e,t){if(e.config?.styleId!==t.tableStyleId)return e;return{...e,config:{...e.config,styleId:zp.styleId}}}),ap.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],hb),ap.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],hb),ap.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],function(e,t){if(e.pivotId===t.pivotId)return;return e}),ap.addTransformation("DELETE_SHEET",["ADD_PIVOT","UPDATE_PIVOT"],function(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId===t.sheetId)return{...e,pivot:{...e.pivot,dataSet:void 0}};return e}),ap.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],ab),ap.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],ab);const db=new Id,fb="000000",gb={arrows:"3Arrows",smiley:"3Symbols",dots:"3TrafficLights1"},mb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",pb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",bb="http://schemas.openxmlformats.org/package/2006/relationships",vb="http://schemas.openxmlformats.org/package/2006/content-types",yb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",Eb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",wb="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",Sb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",Cb="http://schemas.microsoft.com/office/spreadsheetml/2014/revision",Tb="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3",Ib="http://schemas.openxmlformats.org/markup-compatibility/2006",xb="http://schemas.openxmlformats.org/drawingml/2006/main",Rb="http://schemas.openxmlformats.org/drawingml/2006/chart",Ab={workbook:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",macroEnabledWorkbook:"application/vnd.ms-excel.sheet.macroEnabled.main+xml",templateWorkbook:"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml",macroEnabledTemplateWorkbook:"application/vnd.ms-excel.template.macroEnabled.main+xml",excelAddInWorkbook:"application/vnd.ms-excel.addin.macroEnabled.main+xml",sheet:"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",metadata:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",sharedStrings:"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",styles:"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",drawing:"application/vnd.openxmlformats-officedocument.drawing+xml",chart:"application/vnd.openxmlformats-officedocument.drawingml.chart+xml",themes:"application/vnd.openxmlformats-officedocument.theme+xml",table:"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",pivot:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",externalLink:"application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml"},Ob="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",_b="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",Db="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",Fb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",Nb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",Mb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",Vb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",Lb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",Pb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",kb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",Ub="bdbb8cdc-fa1e-496e-a857-3c3f30c029c3",Hb="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Bb=.75,zb=.143,$b=8.43,Gb=12.75,Wb={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}]},qb=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","BYCOL","BYROW","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","CHOOSECOLS","CHOOSEROWS","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","DROP","ERF.PRECISE","ERFC.PRECISE","EXPAND","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","FIELDVALUE","FILTERXML","FLOOR.MATH","FLOOR.PRECISE","FORECAST.ETS","FORECAST.ETS.CONFINT","FORECAST.ETS.SEASONALITY","FORECAST.ETS.STAT","FORECAST.LINEAR","FORMULATEXT","GAMMA","GAMMA.DIST","GAMMA.INV","GAMMALN.PRECISE","GAUSS","HSTACK","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOMITTED","ISOWEEKNUM","LAMBDA","LET","LOGNORM.DIST","LOGNORM.INV","MAKEARRAY","MAP","MAXIFS","MINIFS","MODE.MULT","MODE.SNGL","MUNIT","NEGBINOM.DIST","NORM.DIST","NORM.INV","NORM.S.DIST","NORM.S.INV","NUMBERVALUE","PDURATION","PERCENTILE.EXC","PERCENTILE.INC","PERCENTRANK.EXC","PERCENTRANK.INC","PERMUTATIONA","PHI","POISSON.DIST","PQSOURCE","PYTHON_STR","PYTHON_TYPE","PYTHON_TYPENAME","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANDARRAY","RANK.AVG","RANK.EQ","REDUCE","RRI","SCAN","SEC","SECH","SEQUENCE","SHEET","SHEETS","SKEW.P","SORTBY","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TAKE","TEXTAFTER","TEXTBEFORE","TEXTJOIN","TEXTSPLIT","TOCOL","TOROW","UNICHAR","UNICODE","UNIQUE","VAR.P","VAR.S","VSTACK","WEBSERVICE","WEIBULL.DIST","WRAPCOLS","WRAPROWS","XLOOKUP","XOR","Z.TEST"],Zb="[Content_Types].xml";function Yb(e,t,r){if(!t.startsWith("="))return t;const n=um(t);for(let t=1;t<n.length;t++){if("REFERENCE"!==n[t].type)continue;const o=n[t].value,s=jb(e,o,r).range;o!==s&&(n[t]={value:s,type:"REFERENCE"})}return Ie(n.map(e=>e.value))}function jb(e,t,r){const n=To(t).sheetName;if(n?!ip(n,r.sheetName.old):e!==r.sheetId)return{changeType:"NONE",range:t};const o=function(e,t){if(!vo.test(e))return km(e);return Pm({xc:e,sheetId:t},Xb)}(t,n?r.sheetId:e);if(o.invalidXc)return{changeType:"NONE",range:t};const s=r.applyChange(o);if("NONE"===s.changeType||"REMOVE"===s.changeType)return{changeType:s.changeType,range:t};const i=Bm(s.range,e,function(e){return t=>t===e.sheetId?e.sheetName.current:""}(r));return i===E.InvalidReference?{changeType:"REMOVE",range:i}:{changeType:s.changeType,range:i}}function Xb(e){return{numberOfRows:Number.MAX_SAFE_INTEGER,numberOfCols:Number.MAX_SAFE_INTEGER}}function Kb(e){return e&&yp(e)<.3?"#FFFFFF":"#000000"}function Qb(e){return e&&yp(e)<.3?"#C8C8C8":"#666666"}function Jb(e,t,r){const n=db.getAll().find(e=>e.match(t.type));if(!n)throw new Error("Unknown chart type.");return n.transformDefinition(e,t,r)}function ev(e,t){return(e=re(e)).pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=Yb(e.computedBy.sheetId,e.computedBy.formula,t))}),e}function tv(e,t){return{...e,definition:Jb(e.sheetId,e.definition,t)}}v("Left"),v("Right"),lp.add("UPDATE_CELL",function(e,t){const r=e.content&&Yb(e.sheetId,e.content,t);return{...e,content:r}}),lp.add("ADD_CONDITIONAL_FORMAT",function(e,t){const r=e.cf.rule;if(e={...e,cf:{...e.cf}},"CellIsRule"===r.type)e.cf.rule={...r,values:r.values.map(r=>Yb(e.sheetId,r,t))};else if("ColorScaleRule"===r.type){const{minimum:n,maximum:o,midpoint:s}=r;e.cf.rule={...r,minimum:{...n,value:n.value&&Yb(e.sheetId,n.value,t)},maximum:{...o,value:o.value&&Yb(e.sheetId,o.value,t)},midpoint:s?{...s,value:Yb(e.sheetId,s.value,t)}:void 0}}else if("IconSetRule"===r.type){const{upperInflectionPoint:n,lowerInflectionPoint:o}=r;e.cf.rule={...r,upperInflectionPoint:{...n,value:Yb(e.sheetId,n.value,t)},lowerInflectionPoint:{...o,value:Yb(e.sheetId,o.value,t)}}}else"DataBarRule"===r.type&&(e.cf.rule={...r,rangeValues:r.rangeValues?jb(e.sheetId,r.rangeValues,t).range:void 0});return e}),lp.add("ADD_DATA_VALIDATION_RULE",function(e,t){return(e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}}).rule.criterion.values=e.rule.criterion.values.map(r=>Yb(e.sheetId,r,t)),e}),lp.add("ADD_PIVOT",ev),lp.add("UPDATE_PIVOT",ev),lp.add("CREATE_CHART",tv),lp.add("UPDATE_CHART",tv);const rv=[{match:function(e){return"sheetId"in e},fn:sv},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const r=sv(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;const n=[];for(const r of e.target){const e=cp(r,t);e&&n.push(e)}if(!n.length)return"IGNORE_COMMAND";return{...e,target:n}}},{match:function(e){return"sheetId"in e&&"zone"in e},fn:function(e,t){const r=sv(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;const n=cp(e.zone,t);if(n)return{...e,zone:n};return"IGNORE_COMMAND"}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const r=sv(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const r="COL"===t.dimension?"col":"row";let n=e[r];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort((e,t)=>t-e);if(e.includes(n))return"IGNORE_COMMAND";for(const t of e)n>=t&&n--}"ADD_COLUMNS_ROWS"===t.type&&(n>t.base||n===t.base&&"before"===t.position)&&(n+=t.quantity);return{...e,[r]:n}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const r of t.target){if(!(e.col===r.left&&e.row===r.top)&&ls(e.col,e.row,r))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e&&"elements"in e},fn:function(e,t){const r=sv(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"!==t.type&&"REMOVE_COLUMNS_ROWS"!==t.type)return"SKIP_TRANSFORMATION";if(t.dimension!==e.dimension)return e;let n=[];if("REMOVE_COLUMNS_ROWS"===t.type)n=rp(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){n=tp(Re(t.position,t.base),t.quantity,e.elements)}if(0===n.length)return"IGNORE_COMMAND";return{...e,elements:n}}},{match:function(e){return"ranges"in e},fn:function(e,t){if(!("sheetId"in t))return e;const r=e.ranges.map(e=>up(e,t)).filter(Se);if(!r.length)return"IGNORE_COMMAND";return{...e,ranges:r}}}];function nv(e,t){const r=ap.getTransformation(e.type,t.type),n=r?r(e,t):function(e,t){for(const{match:r,fn:n}of rv)if(r(e)){const r=n(e,t);if("SKIP_TRANSFORMATION"===r)continue;if("IGNORE_COMMAND"===r)return;e=r}return e}(e,t);return n?function(e,t){const r=lp.get(e.type);if(!r)return e;const n=Wm(t);if(n)return r(e,n);return e}(n,t):n}function ov(e,t){let r=[...e];const n=new Set(ap.getKeys());for(const e of t)(n.has(e.type)||qm.contains(e.type))&&(r=r.reduce((t,r)=>{const n=nv(r,e);return n&&t.push(n),t},[]));return r}function sv(e,t){if(!("sheetId"in t))return e;const r="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===r?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class iv{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,r,n,o,s){this.rootCommand=n,this.timestamp=s,this.id=e,this.clientId=t,this._commands=[...r],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class av extends Error{}class lv extends Vm{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new _o;lastLocalOperation;constructor(e,t,r=Y){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=r,this.debouncedMove=Te(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,r){if(!t.length||!r.length||!this.canApplyOptimisticUpdate())return;const n=new iv(this.uuidGenerator.uuidv4(),this.clientId,t,e,r,Date.now());this.revisions.append(n.id,n),"REQUEST_REDO"!==e.type&&(this.lastLocalOperation=n),this.trigger("new-local-state-update",{id:n.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:n.id,clientId:n.clientId,commands:n.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)),this.awaitingClientPosition&&(this._move(this.awaitingClientPosition),this.awaitingClientPosition=void 0)}loadInitialMessages(e){const t=performance.now(),r=e.reduce((e,t)=>e+("REMOTE_REVISION"===t.type?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug("Replayed",r,"commands in",performance.now()-t,"ms")}async leave(e){e&&1===Object.keys(this.clients).length&&this.lastRevisionMessage&&"SNAPSHOT_CREATED"!==this.lastRevisionMessage?.type&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.sendToTransport({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}async snapshot(e){if(0!==this.pendingMessages.length)return;const t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){const t=this.clients[e];if(!t)throw new av("The client left the session");return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(Se))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return void(this.awaitingClientPosition=e);const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const r=t?"CLIENT_MOVED":"CLIENT_JOINED",n=this.getCurrentClient();this.clients[this.clientId]={...n,position:e},this.sendToTransport({type:r,version:1,client:{...n,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");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:r,timestamp:n}=e,o=new iv(e.nextRevisionId,t,r,void 0,void 0,n);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:ov(r,t)})}break;case"SNAPSHOT_CREATED":{const t=new iv(e.nextRevisionId,"server",[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot"),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger("collaborative-event-received")}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.sendToTransport({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||this.sendPendingMessage()}async sendToTransport(e){return this.transportService.sendMessage(e)}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){let t=this.revisions.get(e.nextRevisionId);0===t.commands.length&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),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.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof av))throw e.cause||e;this.waitingAck=!1})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"SNAPSHOT_CREATED":this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case"REVISION_UNDONE":{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);const t=this.pendingMessages.findIndex(e=>"REMOTE_REVISION"===e.type);-1!==t&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if("CLIENT_MOVED"===e.type&&e.client.id===this.clientId)return!0;switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e)}}const cv=(new Id).add("ADD_COLUMNS_ROWS",function(e){const t=[];let r=e.base;"after"===e.position&&r++;for(let n=0;n<e.quantity;n++)t.push(n+r);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}).add("REMOVE_COLUMNS_ROWS",function(e){const t=[],r=[...e.elements].sort((e,t)=>e-t);for(const n of ce(r)){const r=0===n[0]?0:n[0]-1,o=0===n[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:n.length,base:r,sheetId:e.sheetId,sheetName:e.sheetName,position:o})}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,sheetName:e.name}]}).add("DELETE_SHEET",function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1,name:e.sheetName}]}).add("DUPLICATE_SHEET",function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo,sheetName:""}]}).add("CREATE_FIGURE",function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]}).add("CREATE_CHART",function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,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}]}).add("CREATE_TABLE_STYLE",function(e){return[{type:"REMOVE_TABLE_STYLE",tableStyleId:e.tableStyleId}]}).add("ADD_PIVOT",function(e){return[{type:"REMOVE_PIVOT",pivotId:e.pivotId}]}).add("RENAME_SHEET",function(e){return[{type:"RENAME_SHEET",sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]});for(const e of _s.values())cv.contains(e)||cv.add(e,uv);function uv(e){return[e]}function hv(e){return cv.get(e.type)(e)}class dv{buildTransformation;operations;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(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const r of this.operations){if(r.id===e)return e;if(r.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 r=this.buildTransformation.with(e.data),{before:n,operation:o,after:s}=this.locateOperation(t);this.operations=[...n,o,e,...s.map(e=>e.transformed(r))]}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 dv(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:r}=this.locateOperation(e);this.operations=t.concat([r])}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 fv{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new gv(this.id,xe(()=>e(this.data)))}}class gv{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new gv(this.id,this.lazyData.map(e))}}class mv{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new mv(function*(e,t){for(const r of e)if(yield r,r.operation.id===t)return}(this.operations,e))}stopBefore(e){return new mv(function*(e,t){for(const r of e){if(r.operation.id===t)return;yield r}}(this.operations,e))}startAfter(e){return new mv(function*(e,t){let r=!0;for(const n of e)r||(yield n),n.operation.id===t&&(r=!1)}(this.operations,e))}}class pv{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new mv(ue(this._execution(e),this._execution(e)))}revertedExecution(e){return new mv(ue(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const r=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),r&&this.insertPrevious(e,t,r)}insertOperationAfter(e,t,r){e.insert(t,r),this.updateNextWith(e,t,r),this.insertPrevious(e,t,r)}undo(e,t){const r=this.buildTransformation.without(t.data),n=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const o=e.fork(t.id);n&&this.branchingOperationIds.set(o,n),this.insertBranchAfter(e,o),this.transform(o,r)}redo(e){const t=this.nextBranch(e);if(!t)return;const r=this.nextBranch(t);this.removeBranchFromTree(t);const n=this.branchingOperationIds.get(t);n?this.branchingOperationIds.set(e,n):this.branchingOperationIds.delete(e),r&&this.rebaseUp(r)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const r of this.revertedExecution(e))if(r.operation.id===t)return r;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:r}=this.findPreviousBranchingOperation(e);if(!t||!r)return;const n=this.buildTransformation.without(r.data),o=t.fork(r.id);this.branchingOperationIds.set(o,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,o),o.transform(n);const s=this.nextBranch(o);s&&this.rebaseUp(s)}removeBranchFromTree(e){const t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){const r=this.branches.findIndex(t=>t===e);this.branches.splice(r+1,0,t)}updateNextWith(e,t,r){const n=this.branchingOperationIds.get(e),o=this.nextBranch(e);if(n&&o)if(e.getFirstOperationAmong(r,n)===n){const s=this.addToNextBranch(e,o,n,t,r);this.updateNextWith(o,s,r)}else{const e=this.buildTransformation.with(t.data);this.transform(o,e)}}addToNextBranch(e,t,r,n,o){let s=n;return o===r?(s=this.getTransformedOperation(e,r,n),t.prepend(s)):t.contains(o)?(s=this.getTransformedOperation(e,r,n),t.insert(s,o)):t.append(n),s}getTransformedOperation(e,t,r){const n=e.getOperation(t),o=this.buildTransformation.without(n.data);return r.transformed(o)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const r=this.nextBranch(e);r&&this.transform(r,t)}insertPrevious(e,t,r){const{previousBranch:n,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!n||!o)return;const s=this.buildTransformation.with(o.data),i=e.fork(r);i.transform(s),n.cutAfter(r),n.appendBranch(i);const a=t.transformed(s);this.insertPrevious(n,a,r)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const r=this.branchingOperationIds.get(t);return r?{previousBranch:t,branchingOperation:t.getOperation(r)}:{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 r=!!t;const n=e.getOperations();for(let o=n.length-1;o>=0;o--){const s=n[o];s.id===t&&(r=!1),r||(yield{operation:s,branch:e,isCancelled:!this.shouldExecute(e,s)})}const o=this.previousBranch(e);yield*o?this._revertedExecution(o):[]}*_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 bv{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new dv(this.buildTransformation),this.tree=new pv(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,r=new fv(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,r),this.HEAD_OPERATION=r}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const r=new fv(e,t),n=this.tree.getLastBranch();this.tree.insertOperationLast(n,r),this.HEAD_BRANCH=n,this.HEAD_OPERATION=r}insert(e,t,r){const n=new fv(e,t);this.revertTo(r),this.tree.insertOperationAfter(this.HEAD_BRANCH,n,r),this.fastForward()}undo(e,t,r){const{branch:n,operation:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(n,o),this.fastForward(),this.insert(t,this.buildEmpty(t),r)}redo(e,t,r){const{branch:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(n),this.fastForward(),this.insert(t,this.buildEmpty(t),r)}rebase(e){const t=this.get(e),r=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);const n=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,n);for(const{operation:e}of r)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}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:r,isCancelled:n}of e)n||this.revertOperation(r.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:r,isCancelled:n}of e)n||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=r}}function vv(e){return new bv({initialOperationId:e.initialRevisionId,applyOperation:t=>{const r=t.commands.slice(),{changes:n}=e.recordChanges(()=>{for(const t of r)e.dispatch(t)});t.setChanges(n)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){yv(t.changes[e])}}([e]),buildEmpty:e=>new iv(e,"empty",[]),buildTransformation:{with:e=>t=>new iv(t.id,t.clientId,ov(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new iv(t.id,t.clientId,ov(t.commands,e.commands.map(hv).flat()),t.rootCommand,void 0,t.timestamp)}})}function yv(e){const t=e.target,r=e.key,n=e.before;void 0===n?delete t[r]:t[r]=n}class Ev{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const wv=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart","comboChart","radarChart"],Sv="M256 9 a247 247 0 1 0.1 0 0";function Cv(e){return{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:e.textColor||U,path:"M120 195 h270 l-135 130"}]}}const Tv="M40 185 h270 l-135 128";function Iv(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||U,path:Tv}]}}function xv(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||U,path:"M0,225 A175,175 0 1,0 350,225 A175,175 0 1,0 0,225"},{fillColor:e.fillColor||U,path:Tv}]}}const Rv={name:"CHECKBOX_UNCHECKED",width:512,height:512,paths:[{fillColor:"#D8DADD",path:"M45,45 h422 v422 h-422 v-422 m30,30 v362 h362 v-362"}]},Av={name:"CHECKBOX_UNCHECKED",width:512,height:512,paths:[{fillColor:H,path:"M45,45 h422 v422 h-422 v-422 m30,30 v362 h362 v-362"}]},Ov={name:"CHECKBOX_CHECKED",width:512,height:512,paths:[{fillColor:H,path:"M45,45 h422 v422 h-422 v-422"},{fillColor:"#FFF",path:"M165,240 l45,45 l135,-135 h60 l-195,195 l-105,-105"}]};function _v(e,t){return{name:"PIVOT_ICON",width:512,height:512,paths:[{path:"M21,21 h469 v469 h-469",fillColor:t?P:"#777"},{path:"M64,64 v384 h384 v-384",fillColor:t?k:"#eee"},{path:e?"M149,235 h213 v43 h-213 M235,149 h43 v213 h-43":"M149,235 h213 v43 h-213",fillColor:t?P:"#777"}]}}const Dv={arrowGood:{template:"ARROW_UP",svg:{name:"ARROW_UP",width:448,height:512,paths:[{fillColor:"#6AA84F",path:"M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"}]}},arrowNeutral:{template:"ARROW_RIGHT",svg:{name:"ARROW_RIGHT",width:448,height:512,paths:[{fillColor:"#F0AD4E",path:"M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"}]}},arrowBad:{template:"ARROW_DOWN",svg:{name:"ARROW_DOWN",width:448,height:512,paths:[{fillColor:"#E06666",path:"M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"}]}},smileyGood:{template:"SMILE",svg:{name:"SMILE",width:496,height:512,paths:[{fillColor:"#6AA84F",path:"M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z"}]}},smileyNeutral:{template:"MEH",svg:{name:"MEH",width:496,height:512,paths:[{fillColor:"#F0AD4E",path:"M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm8 144H160c-13.2 0-24 10.8-24 24s10.8 24 24 24h176c13.2 0 24-10.8 24-24s-10.8-24-24-24z"}]}},smileyBad:{template:"FROWN",svg:{name:"FROWN",width:496,height:512,paths:[{fillColor:"#E06666",path:"M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm-80 128c-40.2 0-78 17.7-103.8 48.6-8.5 10.2-7.1 25.3 3.1 33.8 10.2 8.4 25.3 7.1 33.8-3.1 16.6-19.9 41-31.4 66.9-31.4s50.3 11.4 66.9 31.4c8.1 9.7 23.1 11.9 33.8 3.1 10.2-8.5 11.5-23.6 3.1-33.8C326 321.7 288.2 304 248 304z"}]}},dotGood:{template:"GREEN_DOT",svg:{name:"GREEN_DOT",width:512,height:512,paths:[{fillColor:"#6AA84F",path:Sv}]}},dotNeutral:{template:"YELLOW_DOT",svg:{name:"YELLOW_DOT",width:512,height:512,paths:[{fillColor:"#F0AD4E",path:Sv}]}},dotBad:{template:"RED_DOT",svg:{name:"RED_DOT",width:512,height:512,paths:[{fillColor:"#E06666",path:Sv}]}}},Fv={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}};function Nv(e,t){const r=e.split("/"),n=t.split("/");let o="",s=0;for(let e=0;e<r.length-1;e++)r[e]===n[e]?s++:o+="../";return o+=n.slice(s).join("/"),o}function Mv(e,t=0){const r={};for(let n=0;n<e.length;n++)e[n]&&(r[n+t]=e[n]);return r}function Vv(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}function Lv(e,t,r){return"COL"===t?(e.cols[r]||(e.cols[r]={}),e.cols[r]):(e.rows[r]||(e.rows[r]={}),e.rows[r])}function Pv(e){if("="===e[0])return e;const t=$l(e);return 1===t.length&&"REFERENCE"!==t[0].type?e:"="+e}var kv;!function(e){e.DiagonalBorderNotSupported="Diagonal Borders",e.BorderStyleNotSupported="Border style",e.FillStyleNotSupported="Fill Style",e.FontNotSupported="Font",e.HorizontalAlignmentNotSupported="Horizontal Alignment",e.VerticalAlignmentNotSupported="Vertical Alignments",e.MultipleRulesCfNotSupported="Multiple rules conditional formats",e.CfTypeNotSupported="Conditional format type",e.CfFormatBorderNotSupported="Borders in conditional formats",e.CfFormatAlignmentNotSupported="Alignment in conditional formats",e.CfFormatNumFmtNotSupported="Num formats in conditional formats",e.CfIconSetEmptyIconNotSupported="IconSets with empty icons",e.BadlyFormattedHyperlink="Badly formatted hyperlink",e.NumFmtIdNotSupported="Number format",e.TimeDataValidationNotSupported="Time data validation rules",e.TextLengthDataValidationNotSupported="Text length data validation rules",e.WholeNumberDataValidationNotSupported="Whole number data validation rules",e.NotEqualDateDataValidationNotSupported="Not equal date data validation rules"}(kv||(kv={}));class Uv{_parsingWarnings=new Set;_conversionWarnings=new Set;addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,r){let n=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;r&&(n+=`Only ${r.join(", ")} are currently supported.`),this._conversionWarnings.has(n)||this._conversionWarnings.add(n)}}const Hv=["thin","medium","thick","dashed","dotted"],Bv=["general","left","center","right"],zv=["top","center","bottom"],$v=["Arial"],Gv=["solid","none"],Wv=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWithText","containsBlanks","notContainsBlanks"],qv={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},Zv={dashDot:"thin",dashDotDot:"thin",dashed:"dashed",dotted:"dotted",double:"thin",hair:"thin",medium:"medium",mediumDashDot:"thin",mediumDashDotDot:"thin",mediumDashed:"thin",none:void 0,slantDashDot:"thin",thick:"thick",thin:"thin"},Yv={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},jv={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},Xv={top:"top",middle:"center",bottom:"bottom"},Kv={beginsWith:"beginsWithText",endsWith:"endsWithText",containsText:"containsText",notContains:"notContainsText",between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},Qv={aboveAverage:void 0,expression:"customFormula",cellIs:void 0,colorScale:void 0,dataBar:void 0,iconSet:void 0,top10:void 0,uniqueValues:void 0,duplicateValues:void 0,containsText:"containsText",notContainsText:"notContainsText",beginsWith:"beginsWithText",endsWith:"endsWithText",containsBlanks:"isEmpty",notContainsBlanks:"isNotEmpty",containsErrors:void 0,notContainsErrors:void 0,timePeriod:void 0},Jv={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},ey={NoIcons:void 0,"3Arrows":"arrows","3ArrowsGray":"arrows","3Symbols":"smiley","3Symbols2":"smiley","3Signs":"dots","3Flags":"dots","3TrafficLights1":"dots","3TrafficLights2":"dots","4Arrows":"arrows","4ArrowsGray":"arrows","4RedToBlack":"dots","4Rating":"smiley","4TrafficLights":"dots","5Arrows":"arrows","5ArrowsGray":"arrows","5Rating":"smiley","5Quarters":"dots","3Stars":"smiley","3Triangles":"arrows","5Boxes":"dots"},ty={none:"none",b:"bottom",t:"top",l:"left",r:"right",tr:"right"},ry={areaChart:void 0,area3DChart:void 0,lineChart:"line",line3DChart:void 0,stockChart:void 0,radarChart:"radar",scatterChart:"scatter",pieChart:"pie",pie3DChart:void 0,doughnutChart:"pie",barChart:"bar",bar3DChart:void 0,ofPieChart:void 0,surfaceChart:void 0,surface3DChart:void 0,bubbleChart:void 0,comboChart:"combo"},ny={exp:"exponential",log:"logarithmic",poly:"polynomial",movingAvg:"trailingMovingAverage"},oy={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP",101:"AVERAGE",102:"COUNT",103:"COUNTA",104:"MAX",105:"MIN",106:"PRODUCT",107:"STDEV",108:"STDEVP",109:"SUM",110:"VAR",111:"VARP"},sy={0:"General",1:"0",2:"0.00",3:"#,#00",4:"#,##0.00",9:"0%",10:"0.00%",11:void 0,12:void 0,13:void 0,14:"m/d/yyyy",15:"m/d/yyyy",16:"m/d/yyyy",17:"m/d/yyyy",18:"hh:mm:ss a",19:"hh:mm:ss a",20:"hhhh:mm:ss",21:"hhhh:mm:ss",22:"m/d/yy h:mm",37:void 0,38:void 0,39:void 0,40:void 0,45:"hhhh:mm:ss",46:"hhhh:mm:ss",47:"hhhh:mm:ss",48:void 0,49:"@"},iy={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},ay={0:"000000",1:"FFFFFF",2:"FF0000",3:"00FF00",4:"0000FF",5:"FFFF00",6:"FF00FF",7:"00FFFF",8:"000000",9:"FFFFFF",10:"FF0000",11:"00FF00",12:"0000FF",13:"FFFF00",14:"FF00FF",15:"00FFFF",16:"800000",17:"008000",18:"000080",19:"808000",20:"800080",21:"008080",22:"C0C0C0",23:"808080",24:"9999FF",25:"993366",26:"FFFFCC",27:"CCFFFF",28:"660066",29:"FF8080",30:"0066CC",31:"CCCCFF",32:"000080",33:"FF00FF",34:"FFFF00",35:"00FFFF",36:"800080",37:"800000",38:"008080",39:"0000FF",40:"00CCFF",41:"CCFFFF",42:"CCFFCC",43:"FFFF99",44:"99CCFF",45:"FF99CC",46:"CC99FF",47:"FFCC99",48:"3366FF",49:"33CCCC",50:"99CC00",51:"FFCC00",52:"FF9900",53:"FF6600",54:"666699",55:"969696",56:"003366",57:"339966",58:"003300",59:"333300",60:"993300",61:"993366",62:"333399",63:"333333",64:"000000",65:"FFFFFF"},ly={"image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/vnd.microsoft.icon":"ico","image/jpeg":"jpeg","image/png":"png","image/tiff":"tiff","image/webp":"webp"},cy={avif:"image/avif",bmp:"image/bmp",gif:"image/gif",ico:"image/vnd.microsoft.icon",jpeg:"image/jpeg",png:"image/png",tiff:"image/tiff",webp:"image/webp",jpg:"image/jpeg"},uy={between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},hy={between:"dateIsBetween",notBetween:"dateIsNotBetween",equal:"dateIs",greaterThan:"dateIsAfter",greaterThanOrEqual:"dateIsOnOrAfter",lessThan:"dateIsBefore",lessThanOrEqual:"dateIsOnOrBefore"};function dy(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=fb;else{if(!e.indexed)return;t=ay[e.indexed]}var r;return t=6===(r=t).length?"#"+r+"FF":"#"+r.slice(2)+r.slice(0,2),e.tint&&(t=function(e,t){const r=wp(e),n=Cp(r);t<0&&(n.l=n.l*(1+t));t>0&&(n.l=n.l*(1-t)+(100-100*(1-t)));return Ep(Sp(n))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function fy(e){return 9===e.length&&(e=e.slice(0,7)),parseInt(e.replace("#",""),16)}const gy=new WeakMap,my=new WeakMap;function py(e,t){gy.has(t)||(gy.set(t,new Map),my.set(t,0));const r=gy.get(t),n=yy(e);if(r.has(n)){const o=r.get(n);return t[o]=e,o}const o=my.get(t)+1;return r.set(n,o),my.set(t,o),t[o]=e,o}function by(e){const t={};for(const r in e){const n=zo(e[r].map(ps));for(const e of n)t[es(e)]=Number(r)}return t}function*vy(e,t){for(const r in t){const n=Ko(r),o=t[r];for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++){const n={sheetId:e,col:r,row:t};yield[n,o]}}}function yy(e){if(null===e)return"null";if(void 0===e)return"undefined";if("object"!=typeof e)return String(e);if(Array.isArray(e)){const t=e.length;let r="[";for(let n=0;n<t;n++)n>0&&(r+=","),r+=yy(e[n]);return r+"]"}const t=Object.keys(e).sort();let r="{";for(const n of t)void 0!==e[n]&&(r+=`"${n}":${yy(e[n])},`);return r+="}",r}function Ey(e){switch(e){case"isNotEmpty":case"notContainsText":return"notContainsBlanks";case"isEmpty":return"containsBlanks";case"containsText":return"containsText";case"beginsWithText":return"beginsWith";case"endsWithText":return"endsWith";case"isGreaterThan":case"dateIsAfter":return"greaterThan";case"isGreaterOrEqualTo":case"dateIsOnOrAfter":return"greaterThanOrEqual";case"isLessThan":case"dateIsBefore":return"lessThan";case"isLessOrEqualTo":case"dateIsOnOrBefore":return"lessThanOrEqual";case"isBetween":return"between";case"isNotBetween":return"notBetween";case"isEqual":return"equal";case"isNotEqual":return"notEqual";case"customFormula":case"dateIs":return""}}function wy(e){return Math.round(Bb*e*100)/100}function Sy(e){return Math.round(zb*e*100)/100}function Cy(e){return e?Math.round(e/Bb*100)/100:e}function Ty(e){return e?Math.round(e/zb*100)/100:e}function Iy(e,t,r,n,o){const s=r?e.styles[r]:{},i=n?e.formats[n]:void 0,a={font:{size:s?.fontSize||q,color:{rgb:s?.textColor?s.textColor:"000000"},family:2,name:"Arial"},fill:s?.fillColor?{fgColor:{rgb:s.fillColor}}:{reservedAttribute:"none"},numFmt:i?{format:i,id:0}:void 0,border:o||0,alignment:{horizontal:s.align,vertical:s.verticalAlign?Xv[s.verticalAlign]:void 0,wrapText:!("wrap"!==s.wrapping&&!t?.includes(Q))||void 0,textRotation:s.rotation?xy(s.rotation):void 0,shrinkToFit:"clip"===s.wrapping||void 0}};return a.font.strike=!!s?.strikethrough||void 0,a.font.underline=!!s?.underline||void 0,a.font.bold=!!s?.bold||void 0,a.font.italic=!!s?.italic||void 0,a}function xy(e){let t=Math.round(-e/Math.PI*180)%180;return t>90?t-=180:t<-90&&(t+=180),t>=0?t:90-t}function Ry(e,t){const r=function(e,t){if(!e)return 0;let r=iy[e.format];r||(r=_y(e,t)+164);return r}(t.numFmt,e.numFmts),n={fontId:_y(t.font,e.fonts),fillId:_y(t.fill,e.fills),borderId:t.border,numFmtId:r,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText,textRotation:t.alignment.textRotation,shrinkToFit:t.alignment.shrinkToFit}};return _y(n,e.styles)}function Ay(e,t,r){const n=e.find(e=>e.path===t);let o;return n?(o=`rId${(n.rels.length+1).toString()}`,n.rels.push({...r,id:o})):(o="rId1",e.push({path:t,rels:[{...r,id:o}]})),o}const Oy=new WeakMap;function _y(e,t){let r=Oy.get(t);if(!r){r=new Map;for(let e=0;e<t.length;e++){const n=yy(t[e]);r.set(n,e)}Oy.set(t,r)}const n=yy(e);if(r.has(n))return r.get(n);const o=t.length;return t.push(e),r.set(n,o),o}function Dy(e,t){const r=t.chartIds.findIndex(t=>t===e);return-1===r?(t.chartIds.push(e),t.chartIds.length):r+1}const Fy=[];function Ny(e){const t=Fy.findIndex(t=>t===e);return-1===t?(Fy.push(e),Fy.length):t+1}function My(e){return Math.round(914400*e/96)}function Vy(e,t,r){let n,o,s=e;if(({xc:s,sheetName:n}=To(e)),n){const e=r.sheets.findIndex(e=>ip(e.name,n));if(e<0)throw new Error("Unable to find a sheet with the name "+n);o=e}else o=Number(t);const i=Xo(s);return void 0===i.right&&(i.right=r.sheets[o].colNumber),void 0===i.bottom&&(i.bottom=r.sheets[o].rowNumber),(i.right-i.left+1)*(i.bottom-i.top+1)}function Ly(e){return Math.round(96*e/914400)}function Py(e,t){let r=0;for(let n=0;n<e;n++){const e=t.cols.find(e=>n>=e.min&&n<=e.max);e?.width?r+=e.width:t.sheetFormat?.defaultColWidth?r+=t.sheetFormat.defaultColWidth:r+=$b}return r/zb}function ky(e,t){let r=0;for(let n=0;n<e;n++){const e=t.rows.find(e=>e.index-1===n);e?.height?r+=e.height:t.sheetFormat?.defaultRowHeight?r+=t.sheetFormat.defaultRowHeight:r+=Gb}return r/Bb}const Uy=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function Hy(e,t,r){const n=sy[e]||t.find(t=>t.id===e)?.format;if("General"!==n){if(n)try{let e=n.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]");if(e=e.replace(/\[\$\]/g,""),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),function(e){return Uy.test(e)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm/g,"mmm"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return Xr(0,{format:e,locale:xr}),!0}catch(e){return!1}}(e))return e}catch(e){}r.generateNotSupportedWarning(kv.NumFmtIdNotSupported,n||`nmFmtId ${e}`)}}function By(e,t){const r=e.borders.map(e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(kv.DiagonalBorderNotSupported)}(e,t);const r={top:zy(e.top,t),bottom:zy(e.bottom,t),left:zy(e.left,t),right:zy(e.right,t)};return Object.keys(r).forEach(e=>void 0===r[e]&&delete r[e]),r});return Mv(r,1)}function zy(e,t){if(!e)return;!function(e,t){Hv.includes(e.style)||t.generateNotSupportedWarning(kv.BorderStyleNotSupported,e.style,Hv)}(e,t);const r=Zv[e.style];return r?{style:r,color:dy(e.color)}:void 0}function $y(e,t){return Mv(e.styles.map(r=>Gy({fontStyle:e.fonts[r.fontId],fillStyle:e.fills[r.fillId],alignment:r.alignment},t)),1)}function Gy(e,t){return function(e,t,r){e&&e.name&&!$v.includes(e.name)&&r.generateNotSupportedWarning(kv.FontNotSupported,e.name,$v);t&&t.patternType&&!Gv.includes(t.patternType)&&r.generateNotSupportedWarning(kv.FillStyleNotSupported,t.patternType,Gv)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!Bv.includes(e)&&t.generateNotSupportedWarning(kv.HorizontalAlignmentNotSupported,e,Bv)}(e?.alignment?.horizontal,t),function(e,t){e&&!zv.includes(e)&&t.generateNotSupportedWarning(kv.VerticalAlignmentNotSupported,e,zv)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?jv[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?Yv[e.alignment.horizontal]:void 0,rotation:e.alignment?.textRotation?(r=e.alignment.textRotation,r<=90?-r/180*Math.PI:-(90-r)/180*Math.PI):void 0,fillColor:"solid"===e.fillStyle?.patternType?dy(e.fillStyle?.fgColor):dy(e.fillStyle?.bgColor),textColor:dy(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"};var r}function Wy(e,t){const r=[];for(const n of e.styles){const o=Hy(n.numFmtId,e.numFmts,t);o&&(r[n.numFmtId]=o)}return Mv(r,1)}function qy(e,t,r){const n=[];let o=1;for(const s of e){if(0===s.cfRules.length)continue;Ky(s,t,r);const e=s.cfRules[0];let i;const a=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type||"dataBar"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"duplicateValues":case"top10":case"uniqueValues":case"timePeriod":continue;case"dataBar":const t=Zy(o++,s);t&&n.push(t);continue;case"colorScale":const l=Yy(o++,s);l&&n.push(l);continue;case"iconSet":const c=jy(o++,s,r);c&&n.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;i=Qv[e.type],a.push(e.text);break;case"expression":if(!e.formula?.length)continue;i=Qv[e.type],a.push(`=${e.formula[0]}`);break;case"containsBlanks":case"notContainsBlanks":i=Qv[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;i=Kv[e.operator],a.push(Pv(e.formula[0])),2===e.formula.length&&a.push(Pv(e.formula[1]))}i&&void 0!==e.dxfId&&n.push({id:(o++).toString(),ranges:s.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:i,values:a,style:Gy({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},r)}})}}return n}function Zy(e,t){const r=t.cfRules[0].dataBar;if(!r)return;const n=fy(dy(r.color)||"#FFFFFF");return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"DataBarRule",color:n}}}function Yy(e,t){const r=t.cfRules[0].colorScale;if(!r||r.cfvos.length!==r.colors.length||r.cfvos.length<2||r.cfvos.length>3)return;const n=[];for(let e=0;e<r.cfvos.length;e++)n.push({color:fy(dy(r.colors[e])||"#FFFFFF"),type:Jv[r.cfvos[e].type],value:r.cfvos[e].value});const o=n[0],s=2===n.length?n[1]:n[2],i=3===n.length?n[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:o,midpoint:i,maximum:s}}}function jy(e,t,r){const n=t.cfRules[0].iconSet;if(!n)return;let o=n.cfvos,s=n.cfIcons;if(o.length<3||s&&s.length<3)return;o.length>3&&(o=[o[0],o[Math.floor(o.length/2)],o[o.length-1]]),s&&s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]);const i=[];for(let e=1;e<=2;e++){const t=Jv[o[e].type];if("value"===t)return;i.push({value:o[e].value||"",operator:o[e].gte?"ge":"gt",type:t})}let a={lower:s?Xy(s[0].iconSet,s[0].iconId):Xy(n.iconSet,0),middle:s?Xy(s[1].iconSet,s[1].iconId):Xy(n.iconSet,1),upper:s?Xy(s[2].iconSet,s[2].iconId):Xy(n.iconSet,2)};n.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(const e of Object.keys(a))if(!a[e])switch(r.generateNotSupportedWarning(kv.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=Fv.dots.good;break;case"middle":a[e]=Fv.dots.neutral;break;case"lower":a[e]=Fv.dots.bad}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"IconSetRule",icons:a,upperInflectionPoint:i[1],lowerInflectionPoint:i[0]}}}function Xy(e,t){const r=ey[e];return r?0===t?Fv[r].bad:1===t?Fv[r].neutral:Fv[r].good:""}function Ky(e,t,r){if(e.cfRules.length>1&&r.generateNotSupportedWarning(kv.MultipleRulesCfNotSupported),Wv.includes(e.cfRules[0].type)||r.generateNotSupportedWarning(kv.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const n=t[e.cfRules[0].dxfId];n.border&&r.generateNotSupportedWarning(kv.CfFormatBorderNotSupported),n.alignment&&r.generateNotSupportedWarning(kv.CfFormatAlignmentNotSupported),n.numFmt&&r.generateNotSupportedWarning(kv.CfFormatNumFmtNotSupported)}}function Qy(e){let t=1;return e.figures.map(r=>function(e,t,r){let n,o,s,i,a;if(1===e.anchors.length)({col:n,row:o,offset:s}=rE(e.anchors[0])),a=Ly(e.figureSize.cx),i=Ly(e.figureSize.cy);else{({col:n,row:o,offset:s}=rE(e.anchors[0]));const{x:t,y:l}=nE(e.anchors[0],r),{x:c,y:u}=nE(e.anchors[1],r);a=c-t,i=u-l}const l={id:t,col:n,row:o,offset:s};if("dataSets"in(c=e.data)&&c.dataSets.length>0)return{...l,width:a,height:i,tag:"chart",data:Jy(e.data)};if(function(e){return"imageSrc"in e}(e.data))return{...l,width:Ly(e.data.size.cx),height:Ly(e.data.size.cy),tag:"image",data:{path:e.data.imageSrc,mimetype:e.data.mimetype}};var c;return}(r,(t++).toString(),e)).filter(Se)}function Jy(e){const t=e.dataSets.some(e=>"reference"in(e.label??{})),r=e.labelRange?eE(e.labelRange,t):void 0,n=e.dataSets.map(e=>{let r;return e.label&&"text"in e.label&&(r=e.label.text),{dataRange:eE(e.range,t),label:r,backgroundColor:e.backgroundColor,trend:tE(e.trend)}});"pie"===e.type&&n.reverse();const o={range:n,dataSetsHaveTitle:t,auxiliaryRange:r,title:e.title??{text:""},background:dy({rgb:e.backgroundColor})||"#FFFFFF",legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,cumulative:e.cumulative||!1,labelsAsText:!1,horizontal:e.horizontal,isDoughnut:e.isDoughnut,pieHolePercentage:e.pieHolePercentage};try{return db.get(e.type).getChartDefinitionFromContextCreation(o)}catch(e){return}}function eE(e,t){const{sheetName:r,xc:n}=To(e);let o=Xo(n);if(t&&void 0!==o.bottom&&void 0!==o.right){const e=o.bottom-o.top+1,t=o.right-o.left+1;1===e?o={...o,left:o.left-1}:1===t&&(o={...o,top:o.top-1})}return Io(r,es(o))}function tE(e){if(e&&e.type)return{type:"linear"===e.type?"polynomial":ny[e.type],order:"linear"===e.type?1:e.order,color:e.color,window:e.window||2,display:!0}}function rE(e){const t={x:Ly(e.colOffset)-1,y:Ly(e.rowOffset)-1};return{col:e.col,row:e.row,offset:t}}function nE(e,t){return{x:Py(e.col,t)+Ly(e.colOffset),y:ky(e.row,t)+Ly(e.rowOffset)}}function oE(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const sE=new Id;function iE(e,t){return{url:e=oE(e),label:t||e,isExternal:!0,isUrlEditable:!0}}sE.add("sheet_URL",{match:e=>ye(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const r=we(e);return t.tryGetSheetName(r)||v("Invalid sheet")},open(e,t){const r=we(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:r}).isCancelledBecause("SheetIsHidden")&&t.notifyUser({type:"warning",sticky:!1,text:v("Cannot open the link because the linked sheet is hidden.")})},sequence:0});const aE={createLink:iE,match:e=>me(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function lE(e){if("string"==typeof e){if(ge(e)){const{label:t,url:r}=be(e);return function(e){return sE.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||aE}(r).createLink(r,t)}return me(e)?iE(e):void 0}}function cE(e,t,r){return hE({value:bn(t.format)&&null!==e.parsedValue?e.content:e.parsedValue,format:t.format,origin:r},t.locale)}function uE(e,t){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e.startsWith("'"))return e.slice(1);if(""===e)return null;if(e.includes("\n"))return e;if(Ot(e,xr))return Dt(e,xr);const r=gt(e,t);return r?r.value:he(e)?"TRUE"===e.toUpperCase():e}function hE(e,t=xr,r,n){const o=lE(e.value);if(!o){return mE(dE(e,t,r),e.origin??n)}const s=uE(o.label,t);return mE({...dE({value:s,format:e.format||("number"==typeof s?cn(o.label,t)||un(o.label):void 0)},t,r),link:o},e.origin??n)}function dE(e,t,r){let{value:n,format:o,message:s}=e;o=r?.format||o;const i=Xr(n,{format:o,locale:t});return Vt(n)?function(e,t){return{value:e,formattedValue:e,message:t,type:Nu.error,isAutoSummable:!1,defaultAlign:"center"}}(n,s):null===n?gE(o):bn(o)?fE($t(n),o,i):"number"==typeof n?on(o||"")?function(e,t,r){return{value:e,format:t,formattedValue:r,type:Nu.number,isAutoSummable:!1,defaultAlign:"right"}}(n,o,i):function(e,t,r){return{value:e||0,format:t,formattedValue:r,type:Nu.number,isAutoSummable:!0,defaultAlign:"right"}}(n,o,i):"boolean"==typeof n?function(e,t,r){return{value:e,format:t,formattedValue:r,type:Nu.boolean,isAutoSummable:!1,defaultAlign:"center"}}(n,o,i):fE(n,o,i)}function fE(e,t,r){return{value:e,format:t,formattedValue:r,type:Nu.text,isAutoSummable:!0,defaultAlign:"left"}}const gE=Ue(function(e){return{value:null,format:e,formattedValue:"",type:Nu.empty,isAutoSummable:!0,defaultAlign:"left"}});function mE(e,t){return null===e.value||"origin"in e||(e.origin=t),e}function pE(e){const t=Qe.now();switch(e){case"today":return Math.floor(bt(t));case"yesterday":return t.setDate(t.getDate()-1),Math.floor(bt(t));case"tomorrow":return t.setDate(t.getDate()+1),Math.floor(bt(t));case"lastWeek":return t.setDate(t.getDate()-6),Math.floor(bt(t));case"lastMonth":{const e=0===t.getMonth()?11:t.getMonth()-1,r=new Qe(t.getFullYear(),e,1);return t.getDate()>vt(r)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(bt(t))}case"lastYear":return 1===t.getMonth()&&29===t.getDate()?(t.setDate(28),t.setFullYear(t.getFullYear()-1)):(t.setDate(t.getDate()+1),t.setFullYear(t.getFullYear()-1)),Math.floor(bt(t))}}function bE(e,t){return"dateValue"in e&&"exactDate"!==e.dateValue?[pE(e.dateValue)]:e.values.map(e=>ht(e,t))}function vE(e,t){return e.map(e=>{if(e.startsWith("="))return e;const r=uE(e,t);return"number"==typeof r?Xr(r,{format:t.dateFormat,locale:t}):""})}function yE(e,t){const r=[];let n=1;for(const o of e)if(o)switch(o.type){case"time":t.generateNotSupportedWarning(kv.TimeDataValidationNotSupported);break;case"textLength":t.generateNotSupportedWarning(kv.TextLengthDataValidationNotSupported);break;case"whole":t.generateNotSupportedWarning(kv.WholeNumberDataValidationNotSupported);break;case"decimal":const e=EE(n++,o);r.push(e);break;case"list":const s=wE(n++,o);r.push(s);break;case"date":if("notEqual"===o.operator){t.generateNotSupportedWarning(kv.NotEqualDateDataValidationNotSupported);break}const i=SE(n++,o);r.push(i);break;case"custom":const a=CE(n++,o);r.push(a)}return r}function EE(e,t){const r=[Pv(t.formula1.toString())];return t.formula2&&r.push(Pv(t.formula2.toString())),{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:uy[t.operator],values:r}}}function wE(e,t){const r=t.formula1.toString(),n=vo.test(r);return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:n?"isValueInRange":"isValueInList",values:n?[r]:r.replaceAll('"',"").split(","),displayStyle:"arrow"}}}function SE(e,t){let r;const n=[Pv(t.formula1.toString())];return t.formula2?(n.push(Pv(t.formula2.toString())),r={type:hy[t.operator],values:vE(n,xr)}):r={type:hy[t.operator],values:vE(n,xr),dateValue:"exactDate"},{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:r}}function CE(e,t){return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:"customFormula",values:[Pv(t.formula1.toString())]}}}const TE=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),IE=new RegExp(/SUBTOTAL\(([0-9]*),/g),xE=new RegExp(ho.source,"ig");function RE(e,t){const r=function(e){const t={};for(const r of e.rows)for(const e of r.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(const n of e.rows.map(e=>e.cells).flat())n?.formula&&(n.formula.content=void 0===n.formula.sharedIndex||n.formula.content?"="+n.formula.content:"="+OE(n.xc,r[n.formula.sharedIndex]),n.formula.content=AE(n.formula.content,t))}function AE(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(IE,(e,t)=>{const r=oy[t];return r?r+"(":e})).replace(TE,(e,r,n,o)=>{r=Number(r)-1,o=o.replace(/\$/g,"");const s=t.externalBooks[r].sheetNames.findIndex(e=>ip(e,n));if(-1===s)return e;const i=t.externalBooks[r].datasets.find(e=>e.sheetId===s)?.data;if(!i)return e;const a=i&&i[o];return(Number(a)?a:`"${a}"`)||e})}function OE(e,t){const r=Ho(t.refCellXc);let n,o=t.formula.slice();do{if(n=xE.exec(o),n){const t=Ho(n[0].replace("$","")),s=Ho(e),i={colFixed:n[0].startsWith("$"),rowFixed:n[0].includes("$",1)},a={col:s.col-r.col,row:s.row-r.row},l={col:i.colFixed?t.col:t.col+a.col,row:i.rowFixed?t.row:t.row+a.row};o=o.slice(0,n.index)+Bo(l.col,l.row,i)+o.slice(n.index+n[0].length)}}while(n);return o}function _E(e,t){return e.sheets.map(r=>{RE(r,e);const n=function(e){const t=[0,0];for(const r of e.rows)t[0]=Math.max(t[0],We(r.cells.map(e=>Ho(e.xc).col))),t[1]=Math.max(t[1],r.index);for(const r of e.figures)t[0]=Math.max(t[0],r.anchors[r.anchors.length-1]?.col??0),t[1]=Math.max(t[1],r.anchors[r.anchors.length-1]?.row??0);return t[0]=Math.max(t[0]+5,30),t[1]=Math.max(t[1]+5,100),t}(r),o=r.sheetViews[0],s=VE(r,"ROW",n[1]),i=VE(r,"COL",n[0]);return{id:r.sheetName,areGridLinesVisible:!o||o.showGridLines,name:r.sheetName,colNumber:n[0],rowNumber:n[1],...NE(r,e,n,t),merges:r.merges,cols:DE(r,n[0],i),rows:FE(r,n[1],s),conditionalFormats:qy(r.cfs,e.dxfs,t),dataValidationRules:yE(r.dataValidations,t),figures:Qy(r),isVisible:r.isVisible,panes:o?{xSplit:o.pane.xSplit,ySplit:o.pane.ySplit}:{xSplit:0,ySplit:0},tables:[],headerGroups:{COL:i,ROW:s},color:dy(r.sheetProperties?.tabColor)}})}function DE(e,t,r){const n={};for(let o=1;o<t+1;o++){const t=e.cols.find(e=>e.min<=o&&o<=e.max);let s;s=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:$b;const i=o-1,a=r.some(e=>e.isFolded&&e.start<=i&&i<=e.end);n[i]={size:Ty(s),isHidden:!a&&t?.hidden}}return n}function FE(e,t,r){const n={};for(let o=1;o<t+1;o++){const t=e.rows.find(e=>e.index===o);let s;s=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:Gb;const i=o-1,a=r.some(e=>e.isFolded&&e.start<=i&&i<=e.end);n[i]={size:Cy(s),isHidden:!a&&t?.hidden}}return n}function NE(e,t,r,n){const o={},s={},i={},a={},l=t.sharedStrings.map(Pe);const c=e.hyperlinks.reduce((e,t)=>(e[t.xc]=t,e),{});for(const r of e.rows)for(const e of r.cells)o[e.xc]=ME(e,c,l,n),e.styleIndex&&(s[e.xc]=e.styleIndex+1,i[e.xc]=t.styles[e.styleIndex].numFmtId+1,a[e.xc]=t.styles[e.styleIndex].borderId+1);for(const n of e.rows.filter(e=>e.styleIndex))for(let e=1;e<=r[0];e++){const r=Bo(e-1,n.index-1);s[r]??=n.styleIndex+1,a[r]??=t.styles[n.styleIndex].borderId+1,i[r]??=t.styles[n.styleIndex].numFmtId+1}for(const n of e.cols.filter(e=>e.styleIndex))for(let e=n.min;e<=Math.min(n.max,r[0]);e++)for(let o=1;o<=r[1];o++){const r=Bo(e-1,o-1);s[r]??=n.styleIndex+1,a[r]??=t.styles[n.styleIndex].borderId+1,i[r]??=t.styles[n.styleIndex].numFmtId+1}return{cells:o,styles:s,formats:i,borders:a}}function ME(e,t,r,n){let o;switch(e.type){case"sharedString":o=r[parseInt(e.value,10)];break;case"boolean":o=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":o=e.value}return o&&t[e.xc]&&(o=function(e,t,r){const n=e.display||t;e.relTarget||e.location||r.generateNotSupportedWarning(kv.BadlyFormattedHyperlink);const o=e.relTarget?e.relTarget:Ee(To(e.location).sheetName);return pe(n,o)}(t[e.xc],o,n)),e.formula&&(o=e.formula.content),o}function VE(e,t,r){const n=e?.sheetProperties?.outlinePr,o=[];let s=0;for(let i=0;i<r;i++){const r=PE(e,t,i),a=r?.outlineLevel||0;if(a>s){const r=LE(e,t,i,("ROW"===t?n?.summaryBelow:n?.summaryRight)??!0);r&&o.push(r)}s=a}return o}function LE(e,t,r,n){const o=PE(e,t,r),s=o?.outlineLevel;if(!s||!s)return;let i=s,a=r,l=o;for(;l&&i>=s;)a++,l=PE(e,t,a),i=l?.outlineLevel||0;const c=r,u=a-1,h=PE(e,t,n?u+1:c-1);return{start:c-1,end:u-1,isFolded:h?.collapsed||!1}}function PE(e,t,r){return"COL"===t?e.cols.find(e=>e.min<=r&&r<=e.max):e.rows.find(e=>e.index===r)}function kE(e,t){for(const r of t.sheets){const t=e.sheets.find(e=>e.name===r.sheetName);if(t){t.tables||(t.tables=[]);for(const e of r.tables)t.tables.push({range:e.ref,config:UE(e)});for(const e of r.pivotTables)t.tables.push({range:e.location.ref,config:HE(e)})}}!function(e,t){let r=null;for(const n of e){const o=t.find(e=>ip(e.sheetName,n.name)).tables;if(o&&0!==o.length){r||(r=BE(e));for(const t of o)for(const o in r){const s=e.find(e=>e.id===o);for(const e in r[o]){for(let i=r[o][e].length-3;i>=0;i-=2){const a=r[o][e][i];if(!a.endsWith(t.name))continue;const l=r[o][e][i+1],c=zE(n.id===s.id?"":n.name+"!",l,t,e);r[o][e][i+2]=a.slice(0,a.indexOf(t.name))+c+r[o][e][i+2],r[o][e].splice(i,2)}}}}}if(!r)return;for(const t in r){const n=e.find(e=>e.id===t);for(const e in r[t]){const o=r[t][e];if(1===o.length){n.cells[e]=o[0];continue}let s="";for(let e=0;e<o.length;e+=2)s+=o[e]+"["+o[e+1]+"]";s+=o[o.length-1],n.cells[e]=s}}}(e.sheets,t.sheets)}function UE(e){const t=e.style?.name||"";return{hasFilters:void 0!==e.autoFilter,numberOfHeaders:e.headerRowCount,totalRow:e.totalsRowCount>0,firstColumn:e.style?.showFirstColumn||!1,lastColumn:e.style?.showLastColumn||!1,bandedRows:e.style?.showRowStripes||!1,bandedColumns:e.style?.showColumnStripes||!1,styleId:ob[t]?t:zp.styleId}}function HE(e){return{hasFilters:!1,numberOfHeaders:e.location.firstDataRow,totalRow:e.rowGrandTotals,firstColumn:!0,lastColumn:e.style?.showLastColumn||!1,bandedRows:e.style?.showRowStripes||!1,bandedColumns:e.style?.showColStripes||!1,styleId:zp.styleId}}function BE(e){const t={};for(const r of e)for(const e in r.cells){const n=r.cells[e];if(!n||!n.startsWith("="))continue;const o=n.indexOf("[");if(-1===o)continue;const s=[];let i=n.slice(0,o),a="",l=1,c=0,u=o;for(let e=o+1;e<n.length;e++)"["!==n[e]?"]"===n[e]&&(l--,0===l&&(a=n.slice(u+1,e),s.push(i),s.push(a),c=e+1)):(0===l&&(i=n.slice(c,e),u=e),l++);s.length&&(t[r.id]||(t[r.id]={}),s.push(n.slice(c)),t[r.id][e]=[...s])}return t}function zE(e,t,r,n){const o=t.split(",").map(e=>e.trim()),s=Ko(r.ref),i=[],a=[],l=[];for(const e of o)if($E(e).startsWith("#")){const t=$E(e);switch(l.push(t),t){case"#All":a.push(s.top,s.bottom);break;case"#Data":const e=r.headerRowCount?s.top+r.headerRowCount:s.top,t=r.totalsRowCount?s.bottom-r.totalsRowCount:s.bottom;a.push(e,t);break;case"#This Row":a.push(Ho(n).row);break;case"#Headers":if(!r.headerRowCount)return E.InvalidReference;a.push(s.top);break;case"#Totals":if(!r.totalsRowCount)return E.InvalidReference;a.push(s.bottom)}}else{const t=e.split(":").map(e=>e.trim()).map($E);if(i.length)return E.InvalidReference;const n=r.cols.findIndex(e=>e.name===t[0]);if(-1===n)return E.InvalidReference;if(i.push(n+s.left),t[1]){const e=r.cols.findIndex(e=>e.name===t[1]);if(-1===e)return E.InvalidReference;i.push(e+s.left)}}if(!function(e){if(e.length<2)return!0;if(e.length>2)return!1;if(e.includes("#Data")&&e.includes("#Totals"))return!0;if(e.includes("#Headers")&&e.includes("#Data"))return!0;return!1}(l))return E.InvalidReference;if(0===a.length){const e=r.headerRowCount?s.top+r.headerRowCount:s.top,t=r.totalsRowCount?s.bottom-r.totalsRowCount:s.bottom;a.push(e,t)}0===i.length&&i.push(s.left,s.right);return e+es({top:Math.min(...a),left:Math.min(...i),bottom:Math.max(...a),right:Math.max(...i)})}function $E(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,e.length-1):e}function GE(e,t,r){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:r}}function WE(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function qE(e){return new Ev(e.map(([e,t])=>`${e}="${WE(t)}"`).join(" "))}function ZE(e,t="text/xml"){const r=(new DOMParser).parseFromString(e.toString(),t),n=r.querySelector("parsererror");if(n){const t=n.innerHTML,r=parseInt(t.split(":")[0],10),o=e.toString().trim().split("\n"),s=o.slice(Math.max(r-3,0),Math.min(r+2,o.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${s}`)}return r}function YE(e){if(e)return{style:e.style,color:{rgb:e.color}}}function jE(e,t){return KE`
2
- <Override ContentType="${t}" PartName="${e}" />
3
- `}function XE(e){return new Ev(e.join("\n"))}function KE(e,...t){const r=[e[0]];for(let n=0;n<t.length;n++){const o=t[n]instanceof Ev?t[n]:WE(t[n]);r.push(o+e[n+1])}return new Ev(Ie(r))}function QE(e){return e.replace(/NAMESPACE.*NAMESPACE(.*)/,"$1")}function JE(e){return e.replaceAll(/(<\/?)([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"$1NAMESPACE$2NAMESPACE$3")}function ew(e){return e.replaceAll(/([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"NAMESPACE$1NAMESPACE$2")}class tw{value;constructor(e){this.value=e}asString(){return Vv(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class rw{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;constructor(e,t,r){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=r,this.relationships={},e.rels&&this.extractRelationships(e.rels).map(e=>{this.relationships[e.id]=e})}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()}))}getListOfXMLFiles(){return Object.entries(this.xlsxFileStructure).filter(([e])=>"images"!==e).map(([e,t])=>t).flat().filter(Se)}mapOnElements(e,t){const r=[],n=this.currentFile;let o;if(e.children){const t=this.querySelector(e.parent,e.query)?.children;o=t||[]}else o=this.querySelectorAll(e.parent,e.query);if(o)for(const e of o)try{r.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=n,r}catchErrorOnElement(e,t){const r=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([r,e.message].join("\n"))}extractAttr(e,t,r){const n=e.attributes[t];n||this.handleMissingValue(e,`attribute "${t}"`,r);const o=n?.value?n.value:r?.default;return void 0===o?void 0:new tw(o)}extractTextContent(e,t){if(void 0!==t?.default&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const r="preserve"===e?.attributes["xml:space"]?.value;let n=e?.textContent;return e&&null!==n||this.handleMissingValue(e,"text content",t),n&&(n=r?n:n.trim()),n?Vv(n):t?.default}extractChildAttr(e,t,r,n){let o;o="number"==typeof t?e.children[t]:this.querySelector(e,t),o||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,n);const s=o?this.extractAttr(o,r,n)?.asString():n?.default;return void 0!==s?new tw(s):void 0}extractChildTextContent(e,t,r){if(void 0!==r?.default&&"string"!=typeof r.default)throw new Error("extractTextContent default value should be a string");const n=this.querySelector(e,t);return n||this.handleMissingValue(e,`child <${t}>`,r),n?this.extractTextContent(n,r):r?.default}handleMissingValue(e,t,r){if(r?.required){if(void 0===r?.default)throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${r.default}`)}}extractColor(e,t,r){if(!e)return r?{rgb:r}:void 0;const n=this.extractAttr(e,"theme")?.asString();let o;if(void 0!==n){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");o=this.getThemeColor(n,t.clrScheme)}else o=this.extractAttr(e,"rgb")?.asString(),o="FF000000"===o?void 0:o;return{rgb:o||r,auto:this.extractAttr(e,"auto")?.asBool(),indexed:this.extractAttr(e,"indexed")?.asNum(),tint:this.extractAttr(e,"tint")?.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");const t=this.processRelationshipTargetName(e.target),r=this.getListOfXMLFiles().find(e=>e.file.fileName.endsWith(t));if(!r||!r.file)throw new Error("Cannot find target file");return r}getTargetImageFile(e){if(!e)throw new Error("Undefined target file");const t=this.processRelationshipTargetName(e.target),r=this.xlsxFileStructure.images.find(e=>e.fileName.endsWith(t));if(!r)throw new Error("Cannot find target file");return r}querySelector(e,t){const r=ew(t);return e.querySelector(r)}querySelectorAll(e,t){const r=ew(t);return e.querySelectorAll(r)}getThemeColor(e,t){switch(e){case"0":return"FFFFFF";case"1":return"000000";case"2":return t[3].value;case"3":return t[2].value;default:return t[e].value}}processRelationshipTargetName(e){return e.replace(/\.+\//,"")}}class nw extends rw{getTheme(){return{clrScheme:this.mapOnElements({query:"a:clrScheme",parent:this.rootFile.file.xml,children:!0},e=>({name:e.tagName,value:this.extractChildAttr(e,0,"val",{required:!0,default:fb}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:fb}).asString()}))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"si"},e=>this.mapOnElements({parent:e,query:"t"},e=>this.extractTextContent(e)||"").join(""))}}class ow extends rw{theme;constructor(e,t,r,n){super(e,t,r),this.theme=n}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},e=>({sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:this.extractAttr(e,"pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},e=>({sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:this.extractAttr(e,"xm:pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,"dxfId")?.asNum(),stopIfTrue:this.extractAttr(e,"stopIfTrue")?.asBool(),aboveAverage:this.extractAttr(e,"aboveAverage")?.asBool(),percent:this.extractAttr(e,"percent")?.asBool(),bottom:this.extractAttr(e,"bottom")?.asBool(),operator:this.extractAttr(e,"operator")?.asString(),text:this.extractAttr(e,"text")?.asString(),timePeriod:this.extractAttr(e,"timePeriod")?.asString(),rank:this.extractAttr(e,"rank")?.asNum(),stdDev:this.extractAttr(e,"stdDev")?.asNum(),equalAverage:this.extractAttr(e,"equalAverage")?.asBool(),dataBar:this.extractCfDataBar(e,t)}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},e=>this.extractTextContent(e,{required:!0}))}extractCfColorScale(e,t){const r=this.querySelector(e,"colorScale");if(r)return{colors:this.mapOnElements({parent:r,query:"color"},e=>this.extractColor(e,t,"ffffff")),cfvos:this.extractCFVos(r)}}extractCfDataBar(e,t){const r=this.querySelector(e,"dataBar");if(r)return{color:this.extractColor(r.querySelector("color"),t,"EFF7FF"),cfvos:this.extractCFVos(r)}}extractCfIconSet(e){const t=this.querySelector(e,"iconSet, x14:iconSet");if(t)return{iconSet:this.extractAttr(t,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(t,"showValue",{default:!0}).asBool(),percent:this.extractAttr(t,"percent",{default:!0}).asBool(),reverse:this.extractAttr(t,"reverse")?.asBool(),custom:this.extractAttr(t,"custom")?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()}));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),gte:this.extractAttr(e,"gte",{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,"val")?.asString():this.extractChildTextContent(e,"f, xm:f")}))}}class sw extends rw{theme;constructor(e,t,r,n){super(e,t,r),this.theme=n}extractDataValidations(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > dataValidations > dataValidation"},e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),operator:this.extractAttr(e,"operator",{default:"between"})?.asString(),sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),errorStyle:this.extractAttr(e,"errorStyle")?.asString(),formula1:this.extractDataValidationFormula(e,1)[0],formula2:this.extractDataValidationFormula(e,2)[0],showErrorMessage:this.extractAttr(e,"showErrorMessage")?.asBool(),errorTitle:this.extractAttr(e,"errorTitle")?.asString(),error:this.extractAttr(e,"error")?.asString(),showInputMessage:this.extractAttr(e,"showInputMessage")?.asBool(),promptTitle:this.extractAttr(e,"promptTitle")?.asString(),prompt:this.extractAttr(e,"prompt")?.asString(),allowBlank:this.extractAttr(e,"allowBlank")?.asBool()}))}extractDataValidationFormula(e,t){return this.mapOnElements({parent:e,query:`formula${t}`},e=>this.extractTextContent(e,{required:!0}))}}class iw extends rw{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},e=>{const t=this.getChartType(e);if(!ry[t])throw new Error(`Unsupported chart type ${t}`);if("combo"===ry[t])return this.extractComboChart(e);const r=this.mapOnElements({parent:e,query:"c:chart > c:title a:t"},e=>e.textContent||"").join(""),n=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString(),o=this.extractChildAttr(e,"c:barDir","val",{default:"col"}).asString(),s=this.extractChildAttr(e,"c:holeSize","val",{default:"0"}).asNum();return{title:{text:r},type:ry[t],dataSets:this.extractChartDatasets(this.querySelectorAll(e,`c:${t}`),t),labelRange:this.extractLabelRange(t,e),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),legendPosition:ty[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===n,fontColor:"000000",horizontal:"bar"===o,isDoughnut:s>0,pieHolePercentage:s}})[0]}extractLabelRange(e,t){return"scatterChart"===e?this.extractChildTextContent(t,"c:ser c:strRef c:f")||this.extractChildTextContent(t,"c:ser c:numRef c:f"):this.extractChildTextContent(t,"c:ser c:cat c:f")}extractComboChart(e){const t=this.mapOnElements({parent:e,query:"c:title a:t"},e=>e.textContent||"").join(""),r=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:{text:t},type:"combo",dataSets:[...this.extractChartDatasets(this.querySelectorAll(e,"c:barChart"),"comboChart"),...this.extractChartDatasets(this.querySelectorAll(e,"c:lineChart"),"comboChart")],labelRange:this.extractChildTextContent(e,"c:ser c:cat c:f"),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),legendPosition:ty[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===r,fontColor:"000000"}}extractChartDatasets(e,t){return Array.from(e).map(e=>"scatterChart"===t?this.extractScatterChartDatasets(e):this.mapOnElements({parent:e,query:"c:ser"},e=>{let t={};const r=this.extractChildTextContent(e,"c:tx c:f");if(r)t={reference:r};else{const r=this.extractChildTextContent(e,"c:tx c:v");r&&(t={text:r})}const n=this.querySelectorAll(e,"c:spPr a:solidFill"),o=n.length?this.querySelector(n[0],"a:srgbClr"):void 0,s=o?o.getAttribute("val"):void 0;return{label:t,range:this.extractChildTextContent(e,"c:val c:f",{required:!0}),backgroundColor:s&&pp(s)?`${mp(s)}`:void 0,trend:this.extractChartTrendline(e)}})).flat()}extractChartTrendline(e){const t=this.querySelector(e,"c:trendline");if(!t)return;const r=this.extractChildAttr(t,"c:trendlineType","val"),n=this.extractChildAttr(t,"a:solidFill a:srgbClr","val");return{type:r?r.asString():void 0,order:this.extractChildAttr(t,"c:order","val")?.asNum(),window:this.extractChildAttr(t,"c:period","val")?.asNum(),color:n&&pp(n.asString())?`${mp(n.asString())}`:void 0}}extractScatterChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},e=>{let t={};const r=this.querySelectorAll(e,"c:spPr a:solidFill a:srgbClr"),n=r.length?r[0].getAttribute("val"):void 0,o=this.extractChildTextContent(e,"c:tx c:f");if(o)t={reference:o};else{const r=this.extractChildTextContent(e,"c:tx c:v");r&&(t={text:r})}return{label:t,range:this.extractChildTextContent(e,"c:yVal c:f",{required:!0}),trend:this.extractChartTrendline(e),backgroundColor:n&&pp(n)?`${mp(n)}`:void 0}})}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");let r;for(const e of t.children){const t=QE(e.tagName);wv.some(e=>e===t)&&(r?r!==t&&(r="comboChart"):r=t)}if(r)return r;throw new Error("Unknown chart type")}}const aw="oneCellAnchor",lw="twoCellAnchor";class cw extends rw{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},e=>{const t=QE(e.tagName),r=this.extractFigureAnchorsByType(e,t),n=this.querySelector(e,"c:chart"),o=this.querySelector(e,"a:blip");if(!n&&!o)throw new Error("Only chart and image figures are currently supported.");return{anchors:r,data:n?this.extractChart(n):this.extractImage(e),figureSize:t===aw?this.extractFigureSizeFromSizeTag(e,"xdr:ext"):void 0}})}extractFigureAnchorsByType(e,t){switch(t){case aw:return[this.extractFigureAnchor("xdr:from",e)];case lw:return[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)];default:throw new Error(`${t} is not supported for xlsx drawings. `)}}extractFigureSizeFromSizeTag(e,t){const r=this.querySelector(e,t);if(!r)throw new Error(`Missing size element '${t}'`);return{cx:this.extractAttr(r,"cx",{required:!0}).asNum(),cy:this.extractAttr(r,"cy",{required:!0}).asNum()}}extractFigureAnchor(e,t){const r=this.querySelector(t,e);if(!r)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(r,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(r,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(r,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(r,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),r=this.getTargetXmlFile(this.relationships[t]),n=new iw(r,this.xlsxFileStructure,this.warningManager).extractChart();if(!n)throw new Error("Unable to extract chart definition");return n}extractImage(e){const t=this.querySelector(e,"a:blip"),r=this.extractAttr(t,"r:embed",{required:!0}).asString(),n=this.getTargetImageFile(this.relationships[r]);if(!n)throw new Error("Unable to extract image");const o=n.fileName.split(".").at(-1),s=QE(e.tagName),i=s===lw?this.querySelector(e,"a:xfrm"):e,a=s===lw?"a:ext":"xdr:ext",l=this.extractFigureSizeFromSizeTag(i,a);return{imageSrc:n.imageSrc,mimetype:o?cy[o]:void 0,size:l}}}class uw extends rw{getPivotTable(){return this.mapOnElements({query:":root",parent:this.rootFile.file.xml},e=>({name:this.extractAttr(e,"name",{required:!0}).asString(),rowGrandTotals:this.extractAttr(e,"rowGrandTotals",{default:!0}).asBool(),location:this.extractPivotLocation(e),style:this.extractPivotStyleInfo(e)}))[0]}extractPivotLocation(e){return this.mapOnElements({query:"location",parent:e},e=>({ref:this.extractAttr(e,"ref",{required:!0}).asString(),firstHeaderRow:this.extractAttr(e,"firstHeaderRow",{required:!0}).asNum(),firstDataRow:this.extractAttr(e,"firstDataRow",{required:!0}).asNum(),firstDataCol:this.extractAttr(e,"firstDataCol",{required:!0}).asNum()}))[0]}extractPivotStyleInfo(e){return this.mapOnElements({query:"pivotTableStyleInfo",parent:e},e=>({name:this.extractAttr(e,"name",{required:!0}).asString(),showRowHeaders:this.extractAttr(e,"showRowHeaders",{required:!0}).asBool(),showColHeaders:this.extractAttr(e,"showColHeaders",{required:!0}).asBool(),showRowStripes:this.extractAttr(e,"showRowStripes",{required:!0}).asBool(),showColStripes:this.extractAttr(e,"showColStripes",{required:!0}).asBool(),showLastColumn:this.extractAttr(e,"showLastColumn")?.asBool()}))[0]}}class hw extends rw{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},e=>({displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:this.extractAttr(e,"name")?.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")}))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},e=>({name:this.extractAttr(e,"name")?.asString(),showFirstColumn:this.extractAttr(e,"showFirstColumn")?.asBool(),showLastColumn:this.extractAttr(e,"showLastColumn")?.asBool(),showRowStripes:this.extractAttr(e,"showRowStripes")?.asBool(),showColumnStripes:this.extractAttr(e,"showColumnStripes")?.asBool()}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()}))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)}))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},e=>({val:this.extractAttr(e,"val",{required:!0}).asString()}))}}class dw extends rw{theme;constructor(e,t,r,n){super(e,t,r),this.theme=n}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),sheetProperties:this.extractSheetProperties(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),dataValidations:this.extractDataValidations(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:this.extractTables(e),pivotTables:this.extractPivotTables(),isVisible:"visible"===t.state}})[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}})}extractSheetName(){const e=Nv(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id;for(const e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,"sheet"))if(e.attributes["r:id"].value===t)return e.attributes.name.value;throw new Error("Missing sheet name")}getSheetWorkbookInfo(){const e=Nv(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id,r=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()})).find(e=>e.relationshipId===t);if(!r)throw new Error("Cannot find corresponding workbook sheet");return r}extractConditionalFormats(){return new ow(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new sw(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractDataValidations()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),r=this.getTargetXmlFile(this.relationships[t]);return new cw(r,this.xlsxFileStructure,this.warningManager).extractFigures()})[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),r=this.getTargetXmlFile(this.relationships[t]);return new hw(r,this.xlsxFileStructure,this.warningManager).getTable()})}extractPivotTables(){try{return Object.values(this.relationships).filter(e=>e.type.endsWith("pivotTable")).map(e=>{const t=this.getTargetXmlFile(e);return new uw(t,this.xlsxFileStructure,this.warningManager).getPivotTable()})}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:"mergeCell"},e=>this.extractAttr(e,"ref",{required:!0}).asString())}extractSheetFormat(e){const t=this.querySelector(e,"sheetFormatPr");if(t)return{defaultColWidth:this.extractAttr(t,"defaultColWidth",{default:$b.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:Gb.toString()}).asNum()}}extractSheetProperties(e){const t=this.querySelector(e,"sheetPr");if(t)return{outlinePr:this.extractSheetOutlineProperties(t),tabColor:this.extractColor(this.querySelector(t,"tabColor"),this.theme)}}extractSheetOutlineProperties(e){const t=this.querySelector(e,"outlinePr");if(t)return{summaryBelow:this.extractAttr(t,"summaryBelow",{default:!0}).asBool(),summaryRight:this.extractAttr(t,"summaryRight",{default:!0}).asBool()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},e=>({width:this.extractAttr(e,"width")?.asNum(),customWidth:this.extractAttr(e,"customWidth")?.asBool(),bestFit:this.extractAttr(e,"bestFit")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),min:this.extractAttr(e,"min",{required:!0})?.asNum(),max:this.extractAttr(e,"max",{required:!0})?.asNum(),styleIndex:this.extractAttr(e,"style")?.asNum(),outlineLevel:this.extractAttr(e,"outlineLevel")?.asNum(),collapsed:this.extractAttr(e,"collapsed")?.asBool()}))}extractRows(e){const t=new Set;return this.mapOnElements({parent:e,query:"sheetData row"},e=>({index:this.extractAttr(e,"r",{required:!0})?.asNum(),cells:this.extractCells(e,t),height:this.extractAttr(e,"ht")?.asNum(),customHeight:this.extractAttr(e,"customHeight")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),styleIndex:this.extractAttr(e,"s")?.asNum(),outlineLevel:this.extractAttr(e,"outlineLevel")?.asNum(),collapsed:this.extractAttr(e,"collapsed")?.asBool()}))}extractCells(e,t){return this.mapOnElements({parent:e,query:"c"},e=>{const r=this.extractAttr(e,"r",{required:!0})?.asString(),n=this.extractCellFormula(e);if(n?.ref&&void 0===n.sharedIndex){const e=Ko(n.ref);for(const{col:n,row:o}of ds(e)){const e=Bo(n,o);e!==r&&t.add(e)}}const o=t.has(r);return{xc:r,styleIndex:this.extractAttr(e,"s")?.asNum(),type:qv[this.extractAttr(e,"t",{default:"n"})?.asString()],value:o?void 0:this.extractChildTextContent(e,"v")??void 0,formula:o?void 0:n}})}extractCellFormula(e){const t=this.querySelector(e,"f");if(!t)return;const r=this.extractTextContent(t),n=this.extractAttr(t,"si")?.asNum(),o=this.extractAttr(t,"ref")?.asString();return void 0!==r&&""!==r.trim()||void 0!==n?{content:r,sharedIndex:n,ref:o}:void 0}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},e=>{const t=this.extractAttr(e,"r:id")?.asString();return{xc:this.extractAttr(e,"ref",{required:!0})?.asString(),location:this.extractAttr(e,"location")?.asString(),display:this.extractAttr(e,"display")?.asString(),relTarget:t?this.relationships[t].target:void 0}})}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),r={};for(const e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),n=this.extractTextContent(e,{required:!0});r[t]=n}const n=[];for(let e=0;e<Object.keys(r).length;e++)r[e]?n.push(r[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),n.push(""));return n}}class fw extends rw{theme;constructor(e,t,r){super(e.styles,e,t),this.theme=r}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},e=>this.extractNumFormats(e))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},e=>this.extractFont(e))}extractFont(e){const t=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),r=this.extractChildAttr(e,"sz","val",{default:q.toString()}).asNum(),n=this.extractColor(this.querySelector(e,"color"),this.theme),o=this.querySelector(e,"i")||void 0,s=o&&"0"!==o.attributes.val?.value,i=this.querySelector(e,"b")||void 0,a=i&&"0"!==i.attributes.val?.value,l=this.querySelector(e,"strike")||void 0,c=l&&"0"!==l.attributes.val?.value,u=this.querySelector(e,"u")||void 0;return{name:t,size:r,color:n,italic:s,bold:a,underline:u&&"none"!==u.attributes.val?.value,strike:c}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},e=>this.extractFill(e))}extractFill(e){const t=e.children[0];return"patternFill"===t.tagName?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(t,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(t,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},e=>this.extractBorder(e))}extractBorder(e){const t={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,"diagonalUp")?.asBool(),t.diagonalDown=this.extractAttr(e,"diagonalDown")?.asBool()),t}extractSingleBorder(e,t,r){const n=this.querySelector(e,t);if(n&&n.attributes.style)return{style:this.extractAttr(n,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(n.children[0],r,"000000")}}extractAlignment(e){return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"bottom"}).asString(),textRotation:this.extractAttr(e,"textRotation")?.asNum(),wrapText:this.extractAttr(e,"wrapText")?.asBool(),indent:this.extractAttr(e,"indent")?.asNum(),relativeIndent:this.extractAttr(e,"relativeIndent")?.asNum(),justifyLastLine:this.extractAttr(e,"justifyLastLine")?.asBool(),shrinkToFit:this.extractAttr(e,"shrinkToFit")?.asBool(),readingOrder:this.extractAttr(e,"readingOrder")?.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},e=>{const t=this.querySelector(e,"font"),r=this.querySelector(e,"fill"),n=this.querySelector(e,"border"),o=this.querySelector(e,"numFmt"),s=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:r?this.extractFill(r):void 0,numFmt:o?this.extractNumFormats(o):void 0,alignment:s?this.extractAlignment(s):void 0,border:n?this.extractBorder(n):void 0}})}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}})}}class gw extends rw{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},e=>this.extractAttr(e,"val",{required:!0}).asString()),datasets:this.extractExternalSheetData(e)}))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},e=>{const t=this.mapOnElements({parent:e,query:"cell"},e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})})),r={};for(const e of t)r[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:r}})}}function mw(e,t){const r=function(e,t){const r=t[Zb],n=r.querySelectorAll(`Override[ContentType="${e}"]`),o=[];for(const e of n){const t=e?.attributes.PartName.value;o.push(t.substring(1))}return o}(e,t);return function(e,t){const r=[];for(const n of e){const e=pw(n,t);r.push({file:{fileName:n,xml:t[n]},rels:e?{fileName:e,xml:t[e]}:void 0})}return r}(r,t)}function pw(e,t){if(e===Zb)return"_rels/.rels";let r="";const n=e.split("/");for(let e=0;e<n.length-1;e++)r+=n[e]+"/";return r+="_rels/",r+=n[n.length-1]+".rels",t[r]||(r=void 0),r}class bw{warningManager;xmls;images;constructor(e){this.warningManager=new Uv,this.xmls={},this.images=[];for(const t of Object.keys(e))if(t.endsWith(".xml")||t.endsWith(".rels")){const r=JE(e[t]);this.xmls[t]=ZE(new Ev(r))}else t.includes("media/image")&&this.images.push({fileName:t,imageSrc:e[t].imageSrc})}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new nw(e.theme,e,this.warningManager).getTheme():void 0,r=e.sharedStrings?new nw(e.sharedStrings,e,this.warningManager).getSharedStrings():[],n=e.sheets.sort((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0})).map(r=>new dw(r,e,this.warningManager,t).getSheet()),o=e.externalLinks.map(t=>new gw(t,e,this.warningManager).getExternalBook()),s=new fw(e,this.warningManager,t);return{fonts:s.getFonts(),fills:s.getFills(),borders:s.getBorders(),dxfs:s.getDxfs(),numFmts:s.getNumFormats(),styles:s.getStyles(),sheets:n,sharedStrings:r,externalBooks:o,chartIds:[],imageIds:[]}}buildXlsxFileStructure(){const e={sheets:mw(Ab.sheet,this.xmls),workbook:mw(Ab.workbook,this.xmls)[0]||mw(Ab.macroEnabledWorkbook,this.xmls)[0]||mw(Ab.templateWorkbook,this.xmls)[0]||mw(Ab.macroEnabledTemplateWorkbook,this.xmls)[0]||mw(Ab.excelAddInWorkbook,this.xmls)[0],styles:mw(Ab.styles,this.xmls)[0],sharedStrings:mw(Ab.sharedStrings,this.xmls)[0],theme:mw(Ab.themes,this.xmls)[0],charts:mw(Ab.chart,this.xmls),figures:mw(Ab.drawing,this.xmls),tables:mw(Ab.table,this.xmls),pivots:mw(Ab.pivot,this.xmls),externalLinks:mw(Ab.externalLink,this.xmls),images:this.images};if(!e.workbook.rels)throw Error(v("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:"18.4.2",sheets:_E(e,this.warningManager),styles:$y(e,this.warningManager),formats:Wy(e,this.warningManager),borders:By(e,this.warningManager),revisionId:Y};return kE(t,e),Object.keys(e.styles).map(t=>{e.styles[t]=Fe(e.styles[t])}),t}}function vw(e){const t=Up[e];return void 0===t?void 0:{minColor:t[0],midColor:3===t.length?t[1]:void 0,maxColor:t[t.length-1]}}function yw(e){const t=um(e),r=[];return{text:"".concat(...t.map(e=>{if("REFERENCE"===e.type&&ho.test(e.value)){const t=e.value.trim();return r.includes(t)||r.push(t),`${K}${r.indexOf(t)}${K}`}return e.value})),dependencies:r}}const Ew={am_ET:7,ar_001:6,ar_SY:6,az_AZ:1,eu_ES:1,be_BY:1,bn_IN:1,bs_BA:1,bg_BG:1,ca_ES:1,zh_CN:7,zh_HK:7,zh_TW:7,hr_HR:1,cs_CZ:1,da_DK:1,nl_BE:1,nl_NL:1,en_AU:7,en_CA:7,en_GB:1,en_IN:7,en_NZ:7,et_EE:1,fi_FI:1,fr_BE:1,fr_CA:7,fr_CH:1,fr_FR:1,gl_ES:1,ka_GE:1,de_DE:1,de_CH:1,el_GR:1,gu_IN:7,he_IL:7,hi_IN:7,hu_HU:1,id_ID:7,it_IT:1,ja_JP:7,kab_DZ:6,km_KH:7,ko_KP:1,ko_KR:7,lo_LA:7,lv_LV:1,lt_LT:1,lb_LU:1,mk_MK:1,ml_IN:1,mn_MN:7,ms_MY:1,nb_NO:1,fa_IR:6,pl_PL:1,pt_AO:1,pt_BR:7,pt_PT:1,ro_RO:1,ru_RU:1,sr_RS:7,"sr@latin":7,sk_SK:1,sl_SI:1,es_AR:7,es_BO:1,es_CL:1,es_CO:7,es_CR:1,es_DO:1,es_EC:1,es_GT:7,es_MX:7,es_PA:7,es_PE:7,es_PY:7,es_UY:1,es_VE:7,sw:1,sv_SE:1,th_TH:7,tl_PH:1,tr_TR:1,uk_UA:1,vi_VN:1,sq_AL:1,te_IN:7,en_US:7,my_MM:7,es_ES:1,es_419:1},ww=new h;function Sw(e){for(const t of e.sheets||[]){const e=[];for(const r of t.filterTables||[]){const t=Ko(r.range),n=e.findIndex(e=>as(e,t));-1!==n?e[n]=t:e.push(t)}t.filterTables=e.map(e=>({range:es(e)}))}return e}function Cw(){return Tw().at(-1)}function Tw(){return ww.getKeys().sort(Aw)}ww.add("0.1",{migrate:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)}).add("0.2",{migrate(e){if(e.sheets&&e.sheets.length)for(const t of e.sheets)t.id=t.id||t.name;return e}}).add("0.3",{migrate(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find(t=>t.name===e.activeSheet);e.activeSheet=t.id}return e}}).add("0.4",{migrate(e){for(const t of e.sheets||[])t.figures=t.figures||[];return e}}).add("0.5",{migrate(e){for(const t of e.sheets||[])for(const e in t.cells||[]){const r=t.cells[e];r.content&&r.content.startsWith("=")&&(r.formula=yw(r.content))}return e}}).add("0.6",{migrate(e){for(const t of e.sheets||[])for(const e in t.figures||[]){const{dataSets:r,...n}=t.figures[e].data,o=[];for(const e of r)if(e.labelCell){const t=Ko(e.dataRange),r=e.labelCell+":"+Bo(t.right,t.bottom);o.push(r)}else o.push(e.dataRange);n.dataSetsHaveTitle=Boolean(r[0].labelCell),n.dataSets=o,t.figures[e].data=n}return e}}).add("0.7",{migrate(e){const t=[];for(const r of e.sheets||[]){if(!r.name)continue;const e=r.name,n=Xe(ie(e,"_"),t,{compute:(e,t)=>`${e}${t}`});r.name=n,t.push(n);const o=t=>{if(void 0===t)return t;let r=t.replace(e,n),o=t;for(;o!==r;)o=r,r=o.replace(e,n);return o};for(const e in r.cells){const t=r.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(o))}for(const e of r.figures||[])if("chart"===e.tag){const t=e.data.dataSets.map(o),r=o(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:r}}for(const e of r.conditionalFormats||[]){e.ranges=e.ranges.map(o);for(const t of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===e.rule[t]?.type&&(e.rule[t].value=o(e.rule[t].value))}}return e}}).add("0.8",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=V,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}}).add("0.9",{migrate(e){for(const t of e.sheets||[])for(const e in t.cells||[]){const r=t.cells[e];if(r.formula){let{text:e,dependencies:t}=r.formula;for(const[r,n]of Object.entries(t)){const t=`\\${K}${r}\\${K}`;e=e.replace(new RegExp(t,"g"),n)}r.content=e,delete r.formula}}return e}}).add("0.10",{migrate(e){const t={};for(const r of e.sheets||[])for(const e in r.cells||[]){const n=r.cells[e];n.format&&(n.format=py(n.format,t))}return e.formats=t,e}}).add("15.4",{migrate(e){for(const t of e.sheets||[])t.isVisible=!0;return e}}).add("15.4.1",{migrate:e=>Sw(e)}).add("16.3",{migrate(e){for(const t in e.borders){const r=e.borders[t];for(const e in r)Array.isArray(r[e])&&(r[e]={style:r[e][0],color:r[e][1]})}return e}}).add("16.4",{migrate:e=>(e.settings||(e.settings={}),e.settings.locale||(e.settings.locale=xr),e)}).add("16.4.1",{migrate:e=>Sw(e)}).add("17.2",{migrate(e){for(const t of e.sheets||[])t.tables=t.tables||t.filterTables||[],delete t.filterTables;return e}}).add("17.3",{migrate:e=>(e.pivots||(e.pivots={}),e.pivotNextId||(e.pivotNextId=qd(e.pivots)+1),e)}).add("17.4",{migrate(e){for(const t of e.sheets||[])for(const e in t.figures||[]){const r=t.figures[e];"title"in r.data&&"string"==typeof r.data.title&&(r.data.title={text:r.data.title});const n=r.data.type;if(!["line","bar","pie","scatter","waterfall","combo"].includes(n))continue;const{dataSets:o,...s}=t.figures[e].data,i=o.map(e=>({dataRange:e}));s.dataSets=i,t.figures[e].data=s}return e}}).add("18.0",{migrate:e=>e}).add("18.0.1",{migrate(e){for(const t of Object.values(e.pivots||{}))t.measures=t.measures.map(e=>({id:e.name,fieldName:e.name,aggregator:e.aggregator})),t.columns=t.columns.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity})),t.rows=t.rows.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity}));return e}}).add("18.0.2",{migrate(e){const t=e.settings?.locale;if(t){const e=t.code;t.weekStart=Ew[e]||1}return e}}).add("18.0.3",{migrate(e){for(const t of e.sheets||[]){t.styles={},t.formats={},t.borders={};for(const e in t.cells)t.styles[e]=t.cells[e].style,t.formats[e]=t.cells[e].format,t.borders[e]=t.cells[e].border,delete t.cells[e].style,delete t.cells[e].format,delete t.cells[e].border}return e}}).add("18.0.4",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[]){if("chart"!==e.tag||"gauge"!==e.data.type)continue;const t=e.data;t?.sectionRule?.lowerInflectionPoint&&(t.sectionRule.lowerInflectionPoint.operator="<="),t?.sectionRule?.upperInflectionPoint&&(t.sectionRule.upperInflectionPoint.operator="<=")}return e}}).add("18.1",{migrate(e){for(const t of e.sheets||[])for(const e of t.tables||[])e.config||(e.config={...zp,hasFilters:!0});return e}}).add("18.1.1",{migrate(e){for(const t of e.sheets||[])for(const e in t.cells){const r=t.cells[e];r&&(t.cells[e]=r.content)}return e}}).add("18.2",{migrate:e=>e}).add("18.3",{migrate(e){if(!e.pivots)return e;for(const t of Object.values(e.pivots)){if(!t.sortedColumn)continue;t.measures.map(e=>e.id).includes(t.sortedColumn.measure)||delete t.sortedColumn}return e}}).add("18.3.1",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[]){const t=e;e.offset={x:t.x||0,y:t.y||0},e.col=0,e.row=0,delete e.x,delete e.y}return e}}).add("18.4.1",{migrate(e){const t={textContains:"containsText",textNotContains:"notContainsText",textIs:"isEqualText",textIsEmail:"isEmail",textIsLink:"isLink"},r={BeginsWith:"beginsWithText",Between:"isBetween",ContainsText:"containsText",EndsWith:"endsWithText",Equal:"isEqual",GreaterThan:"isGreaterThan",GreaterThanOrEqual:"isGreaterOrEqualTo",IsEmpty:"isEmpty",IsNotEmpty:"isNotEmpty",LessThan:"isLessThan",LessThanOrEqual:"isLessOrEqualTo",NotBetween:"isNotBetween",NotContains:"notContainsText",NotEqual:"isNotEqual"};for(const t of e.sheets||[])for(const e of t.conditionalFormats||[])"CellIsRule"===e.rule.type&&(e.rule.operator=r[e.rule.operator]);for(const r of e.sheets||[])for(const e of r.dataValidationRules||[])e.criterion.type in t&&(e.criterion.type=t[e.criterion.type]);return e}}).add("18.4.2",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[]){if("chart"!==e.tag||"scorecard"!==e.data.type)continue;const t=e.data;t.baselineDescr&&(t.baselineDescr={text:t.baselineDescr})}return e}}).add("18.4.3",{migrate(e){if(!e.pivots)return e;for(const t in e.pivots){const r=e.pivots[t];if(r.sortedColumn){const e=r.measures.find(e=>e.fieldName===r.sortedColumn?.measure);e&&(r.sortedColumn.measure=e.id)}}return e}}).add("18.5.1",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[])"chart"===e.tag&&(e.data.chartId=e.id);return e}}).add("19.1.0",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[])if("chart"===e.tag&&"geo"===e.data.type&&"colorScale"in e.data&&"string"==typeof e.data.colorScale&&(e.data.colorScale=vw(e.data.colorScale)),"carousel"===e.tag)for(const t of Object.values(e.data.chartDefinitions)||[])"geo"===t.type&&"colorScale"in t&&"string"==typeof t.colorScale&&(t.colorScale=vw(t.colorScale));return e}});const Iw="Sheet1";function xw(e,t){if(!e)return Fw();console.debug("### Loading data ###");const r=performance.now();if(e["[Content_Types].xml"]){const r=new bw(e);if(e=r.convertXlsx(),t)for(const e of r.warningManager.warnings.sort())console.warn(e)}return"version"in e&&(function(e){return"number"==typeof e.version}(e)&&(e.version=Rw[e.version]),e.version!==Cw()&&(console.debug("Migrating data from version",e.version),e=function(e){const t=performance.now(),r=Tw();for(let t=r.findIndex(t=>t===e.version)+1;t<r.length;t++){const n=r[t];e=ww.get(n).migrate(e)}return console.debug("Data migrated in",performance.now()-t,"ms"),e}(e))),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,r=new Set,n=new _o;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=n.smallUuid()),t.add(e.id),"chart"===e.tag&&(r.has(e.data?.chartId)&&(e.data.chartId+=n.smallUuid()),r.add(e.data?.chartId));return e.uniqueFigureIds=!0,e}(e),e=function(e){const t=Object.assign(Fw(),e,{version:Cw()});t.sheets=t.sheets?t.sheets.map((e,t)=>Object.assign(Dw(`Sheet${t+1}`,`Sheet${t+1}`),e)):[],0===t.sheets.length&&t.sheets.push(Dw(Iw,"Sheet1"));lc(t.settings.locale)||(t.settings.locale=xr);return t}(e),e}(e),console.debug("Data loaded in",performance.now()-r,"ms"),console.debug("###"),e}const Rw={25:"18.2",24:"18.1.1",23:"18.1",22:"18.0.4",21:"18.0.3",20:"18.0.2",19:"18.0.1",18:"18.0",17:"17.4",16:"17.3",15:"17.2",14.5:"16.4.1",14:"16.4",13:"16.3",12.5:"15.4.1",12:"15.4",11:"0.10",10:"0.9",9:"0.8",8:"0.7",7:"0.6",6:"0.5",5:"0.4",4:"0.3",3:"0.2",2:"0.1",1:"0"};function Aw(e,t){const r=e.split(".").map(Number),n=t.split(".").map(Number);for(let e=0;e<Math.max(r.length,n.length);e++){const t=r[e]||0,o=n[e]||0;if(t>o)return 1;if(t<o)return-1}return 0}function Ow(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const r=[],n=[],o=e=>{if("CREATE_SHEET"===e.type)r.push(e.sheetId);else if("sheetId"in e&&!r.includes(e.sheetId))return{...e,sheetId:Iw};return e};for(const e of t)"REMOTE_REVISION"===e.type?n.push({...e,commands:e.commands.map(o)}):n.push(e);return n}(e,t),t=_w(t,"SORT_CELLS"),t=function(e,t){if(!e.version||Aw(String(e.version),"18.5.1")>=0)return t;const r=[],n={};for(const t of e.sheets||[])t.figures?.forEach(e=>{"chart"===e.tag&&(n[e.id]=e.data)});for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const r of e.commands){let e=r;switch(r.type){case"CREATE_CHART":n[r.chartId]=r.definition;break;case"UPDATE_CHART":if(!n[r.chartId]){console.log(`Fix chart definition: chart with id ${r.chartId} not found.`);continue}const t={...n[r.chartId],...r.definition};e={...r,definition:t},n[r.chartId]=t}t.push(e)}r.push({...e,commands:t})}else r.push(e);return r}(e,t=_w(t,"SET_DECIMAL")),t=function(e,t){const r={};for(const t of e.sheets||[])t.figures?.forEach(e=>{r[e.id]=e.offset});for(const e of t)if("REMOTE_REVISION"===e.type)for(const t of e.commands)switch(t.type){case"UPDATE_FIGURE":t.offset&&(void 0===t.offset.x&&(t.offset.x=r[t.figureId]||0),void 0===t.offset.y&&(t.offset.y=r[t.figureId]||0),r[t.figureId]=r);break;case"CREATE_IMAGE":case"CREATE_CHART":case"CREATE_FIGURE":r[t.figureId]=t.offset}return t}(e,t),t=function(e,t){const r={};for(const t of e.sheets||[])r[t.id]=t.name;const n=[];for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const n of e.commands){switch(n.type){case"DUPLICATE_SHEET":n.sheetNameTo=n.sheetNameTo??op(r[n.sheetId],Object.values(r));break;case"CREATE_SHEET":r[n.sheetId]=n.name||np(Object.values(r));break;case"RENAME_SHEET":r[n.sheetId]=n.newName||np(Object.values(r))}t.push(n)}n.push({...e,commands:t})}else n.push(e);return t}(e,t),t}function _w(e,t){const r=[];for(const n of e)"REMOTE_REVISION"===n.type?r.push({...n,commands:n.commands.filter(e=>e.type!==t)}):r.push(n);return r}function Dw(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},styles:{},formats:{},borders:{},cols:{},rows:{},merges:[],conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],isVisible:!0}}function Fw(e="Sheet1"){return{version:Cw(),sheets:[Dw(Iw,e)],styles:{},formats:{},borders:{},revisionId:Y,uniqueFigureIds:!0,settings:{locale:xr},pivots:{},pivotNextId:1,customTableStyles:{}}}class Nw{map={};constructor(e=[]){for(const[t,r]of e)this.set(t,r)}set({sheetId:e,col:t,row:r},n){const o=this.map;o[e]||(o[e]={}),o[e][t]||(o[e][t]={}),o[e][t][r]=n}setMany(e){for(const[t,r]of e)this.set(t,r)}get({sheetId:e,col:t,row:r}){return this.map[e]?.[t]?.[r]}getSheet(e){return this.map[e]}clearSheet(e){delete this.map[e]}has({sheetId:e,col:t,row:r}){return void 0!==this.map[e]?.[t]?.[r]}delete({sheetId:e,col:t,row:r}){delete this.map[e]?.[t]?.[r]}keys(){const e=this.map,t=[];for(const r in e)for(const n in e[r])for(const o in e[r][n])t.push({sheetId:r,col:parseInt(n),row:parseInt(o)});return t}keysForSheet(e){const t=this.map[e];if(!t)return[];const r=[];for(const n in t)for(const o in t[n])r.push({sheetId:e,col:parseInt(n),row:parseInt(o)});return r}*entries(){const e=this.map;for(const t of this.keys()){const{sheetId:r,col:n,row:o}=t;yield[t,e[r][n][o]]}}}class Mw extends Vs{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:r,dispatch:n,canDispatch:o}){super(t),r.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=n,this.canDispatch=o}import(e){}export(e){}adaptRanges(e,t,r){}}class Vw{id;format;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,r,n,o,s){this.id=e,this.format=r,this.sheetId=o,this.getRangeString=s;let i=0;const a=t.tokens.map(e=>{if("REFERENCE"===e.type){const e=i++;return new Lw(n,e,this.sheetId,this.getRangeString)}return e});this.compiledFormula={...t,dependencies:n,tokens:a}}get content(){return Ie(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return Ie(this.compiledFormula.tokens.map(t=>{if("REFERENCE"===t.type){const t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value}))}}class Lw{ranges;rangeIndex;sheetId;getRangeString;type="REFERENCE";constructor(e,t,r,n){this.ranges=e,this.rangeIndex=t,this.sheetId=r,this.getRangeString=n}get value(){const e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}}const Pw=new Id;Pw.add("containsText",{type:"containsText",isValueValid:(e,t)=>String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>v('The value must be a text that contains "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Td.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text contains"),getPreview:e=>v('Text contains "%s"',e.values[0])}),Pw.add("notContainsText",{type:"notContainsText",isValueValid:(e,t)=>!String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>v('The value must be a text that does not contain "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Td.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text does not contain"),getPreview:e=>v('Text does not contain "%s"',e.values[0])}),Pw.add("isEqualText",{type:"isEqualText",isValueValid:(e,t)=>String(e).toLowerCase()===String(t.values[0]).toLowerCase(),getErrorString:e=>v('The value must be exactly "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Td.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text is exactly"),getPreview:e=>v('Text is exactly "%s"',e.values[0])});const kw=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/;function Uw(e,t){return e.values.map(e=>void 0!==e?uc(String(e),t):E.InvalidReference)}function Hw(e,t){return bE(e,xr).map(e=>void 0!==e?Xr(e,{locale:t,format:t.dateFormat}):E.InvalidReference)}function Bw(e){return void 0!==ht(e,xr)}function zw(e){const t=function(e,t){try{return kt(e,t)}catch(e){return}}(e,xr);return void 0!==t}function $w(e){return""===e?NaN:Number(e)}Pw.add("isEmail",{type:"isEmail",isValueValid:(e,t)=>"string"==typeof e&&kw.test(e),getErrorString:()=>v("The value must be a valid email address"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:v("Text is valid email"),getPreview:()=>v("Text is valid email")}),Pw.add("isLink",{type:"isLink",isValueValid:(e,t)=>void 0!==lE(e),getErrorString:()=>v("The value must be a valid link"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:v("Text is valid link"),getPreview:()=>v("Text is valid link")}),Pw.add("dateIs",{type:"dateIs",isValueValid:(e,t)=>{const r=bE(t,xr)[0],n=ht(e,xr);if(void 0===n||void 0===r)return!1;if(["lastWeek","lastMonth","lastYear"].includes(t.dateValue)){return xt(n,Math.floor(bt(Qe.now())),r)}return o=n,s=r,Math.trunc(o)===Math.trunc(s);var o,s},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be the date %s",Hw(e,r)[0]):v("The value must be %s",Td.DateIs[e.dateValue])},isCriterionValueValid:e=>Bw(e),criterionValueErrorString:Td.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:v("Date is"),getPreview:(e,t)=>"exactDate"===e.dateValue?v("Date is %s",vE(e.values,t.getLocale())[0]):v("Date is %s",Td.DateIs[e.dateValue])}),Pw.add("dateIsBefore",{type:"dateIsBefore",isValueValid:(e,t)=>{const r=bE(t,xr)[0],n=ht(e,xr);return void 0!==n&&void 0!==r&&function(e,t){return Math.trunc(e)<Math.trunc(t)}(n,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date before %s",Hw(e,r)[0]):v("The value must be a date before %s",Td.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>Bw(e),criterionValueErrorString:Td.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:v("Date is before"),getPreview:(e,t)=>"exactDate"===e.dateValue?v("Date is before %s",vE(e.values,t.getLocale())[0]):v("Date is before %s",Td.DateIsBefore[e.dateValue])}),Pw.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",isValueValid:(e,t)=>{const r=bE(t,xr)[0],n=ht(e,xr);return void 0!==n&&void 0!==r&&function(e,t){return Math.trunc(e)<=Math.trunc(t)}(n,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date on or before %s",Hw(e,r)[0]):v("The value must be a date on or before %s",Td.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>Bw(e),criterionValueErrorString:Td.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:v("Date is on or before"),getPreview:(e,t)=>"exactDate"===e.dateValue?v("Date is on or before %s",vE(e.values,t.getLocale())[0]):v("Date is on or before %s",Td.DateIsBefore[e.dateValue])}),Pw.add("dateIsAfter",{type:"dateIsAfter",isValueValid:(e,t)=>{const r=bE(t,xr)[0],n=ht(e,xr);return void 0!==n&&void 0!==r&&function(e,t){return Math.trunc(e)>Math.trunc(t)}(n,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date after %s",Hw(e,r)[0]):v("The value must be a date after %s",Td.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>Bw(e),criterionValueErrorString:Td.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:v("Date is after"),getPreview:(e,t)=>"exactDate"===e.dateValue?v("Date is after %s",vE(e.values,t.getLocale())[0]):v("Date is after %s",Td.DateIsBefore[e.dateValue])}),Pw.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",isValueValid:(e,t)=>{const r=bE(t,xr)[0],n=ht(e,xr);return void 0!==n&&void 0!==r&&function(e,t){return Math.trunc(e)>=Math.trunc(t)}(n,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date on or after %s",Hw(e,r)[0]):v("The value must be a date on or after %s",Td.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>Bw(e),criterionValueErrorString:Td.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:v("Date is on or after"),getPreview:(e,t)=>"exactDate"===e.dateValue?v("Date is on or after %s",vE(e.values,t.getLocale())[0]):v("Date is on or after %s",Td.DateIsBefore[e.dateValue])}),Pw.add("dateIsBetween",{type:"dateIsBetween",isValueValid:(e,t)=>{const r=bE(t,xr),n=ht(e,xr);return void 0!==n&&void 0!==r[0]&&void 0!==r[1]&&xt(n,r[0],r[1])},getErrorString:(e,t)=>{const r=Hw(e,t.getLocale());return v("The value must be a date between %s and %s",r[0],r[1])},isCriterionValueValid:e=>Bw(e),criterionValueErrorString:Td.CriterionError.dateValue,numberOfValues:()=>2,name:v("Date is between"),getPreview:(e,t)=>{const r=vE(e.values,t.getLocale());return v("Date is between %s and %s",r[0],r[1])}}),Pw.add("dateIsNotBetween",{type:"dateIsNotBetween",isValueValid:(e,t)=>{const r=bE(t,xr),n=ht(e,xr);return void 0!==n&&void 0!==r[0]&&void 0!==r[1]&&!xt(n,r[0],r[1])},getErrorString:(e,t)=>{const r=Hw(e,t.getLocale());return v("The value must be a date not between %s and %s",r[0],r[1])},isCriterionValueValid:e=>Bw(e),criterionValueErrorString:Td.CriterionError.dateValue,numberOfValues:()=>2,name:v("Date is not between"),getPreview:(e,t)=>{const r=vE(e.values,t.getLocale());return v("Date is not between %s and %s",r[0],r[1])}}),Pw.add("dateIsValid",{type:"dateIsValid",isValueValid:(e,t)=>void 0!==ht(e,xr),getErrorString:()=>v("The value must be a valid date"),isCriterionValueValid:e=>Bw(e),criterionValueErrorString:"",numberOfValues:()=>0,name:v("Is valid date"),getPreview:()=>v("Date is valid")}),Pw.add("isEqual",{type:"isEqual",isValueValid:(e,t)=>e===t.values[0],getErrorString:(e,t)=>{const r=Uw(e,t.getLocale());return v("The value must be equal to %s",r[0])},isCriterionValueValid:e=>zw(e),criterionValueErrorString:Td.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is equal to"),getPreview:e=>v("Value is equal to %s",e.values[0])}),Pw.add("isNotEqual",{type:"isNotEqual",isValueValid:(e,t)=>e!==t.values[0],getErrorString:(e,t)=>{const r=Uw(e,t.getLocale());return v("The value must not be equal to %s",r[0])},isCriterionValueValid:e=>zw(e),criterionValueErrorString:Td.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is not equal to"),getPreview:e=>v("Value is not equal to %s",e.values[0])}),Pw.add("isGreaterThan",{type:"isGreaterThan",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const r=t.values[0];return"number"==typeof r&&e>r},getErrorString:(e,t)=>{const r=Uw(e,t.getLocale());return v("The value must be greater than %s",r[0])},isCriterionValueValid:e=>zw(e),criterionValueErrorString:Td.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is greater than"),getPreview:e=>v("Value is greater than %s",e.values[0])}),Pw.add("isGreaterOrEqualTo",{type:"isGreaterOrEqualTo",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const r=t.values[0];return"number"==typeof r&&e>=r},getErrorString:(e,t)=>{const r=Uw(e,t.getLocale());return v("The value must be greater or equal to %s",r[0])},isCriterionValueValid:e=>zw(e),criterionValueErrorString:Td.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is greater or equal to"),getPreview:e=>v("Value is greater or equal to %s",e.values[0])}),Pw.add("isLessThan",{type:"isLessThan",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const r=t.values[0];return"number"==typeof r&&e<r},getErrorString:(e,t)=>{const r=Uw(e,t.getLocale());return v("The value must be less than %s",r[0])},isCriterionValueValid:e=>zw(e),criterionValueErrorString:Td.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is less than"),getPreview:e=>v("Value is less than %s",e.values[0])}),Pw.add("isLessOrEqualTo",{type:"isLessOrEqualTo",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const r=t.values[0];return"number"==typeof r&&e<=r},getErrorString:(e,t)=>{const r=Uw(e,t.getLocale());return v("The value must be less or equal to %s",r[0])},isCriterionValueValid:e=>zw(e),criterionValueErrorString:Td.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is less or equal to"),getPreview:e=>v("Value is less or equal to %s",e.values[0])}),Pw.add("isBetween",{type:"isBetween",isValueValid:(e,t)=>"number"==typeof e&&("number"==typeof t.values[0]&&"number"==typeof t.values[1]&&Ge(e,t.values[0],t.values[1])),getErrorString:(e,t)=>{const r=Uw(e,t.getLocale());return v("The value must be between %s and %s",r[0],r[1])},isCriterionValueValid:e=>zw(e),criterionValueErrorString:Td.CriterionError.numberValue,numberOfValues:()=>2,name:v("Is between"),getPreview:e=>v("Value is between %s and %s",e.values[0],e.values[1])}),Pw.add("isNotBetween",{type:"isNotBetween",isValueValid:(e,t)=>"number"==typeof e&&("number"==typeof t.values[0]&&"number"==typeof t.values[1]&&!Ge(e,t.values[0],t.values[1])),getErrorString:(e,t)=>{const r=Uw(e,t.getLocale());return v("The value must not be between %s and %s",r[0],r[1])},isCriterionValueValid:e=>zw(e),criterionValueErrorString:Td.CriterionError.numberValue,numberOfValues:()=>2,name:v("Is not between"),getPreview:e=>v("Value is not between %s and %s",e.values[0],e.values[1])}),Pw.add("isBoolean",{type:"isBoolean",isValueValid:(e,t)=>""===e||"boolean"==typeof e,getErrorString:()=>v("The value must be a boolean"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:v("Checkbox"),getPreview:()=>v("Checkbox")}),Pw.add("isValueInList",{type:"isValueInList",isValueValid:(e,t)=>null!==e&&t.values.map(e=>String(e).toLowerCase()).includes(e.toString().toLowerCase()),getErrorString:e=>v("The value must be one of: %s",e.values.join(", ")),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>{},allowedValues:"onlyLiterals",name:v("Value in list"),getPreview:e=>v("Value one of: %s",e.values.join(", "))}),Pw.add("isValueInRange",{type:"isValueInList",isValueValid:(e,t,r,n)=>{if(!e)return!1;return r.getDataValidationRangeValues(n,t).map(e=>e.value.toLowerCase()).includes(e.toString().toLowerCase())},getErrorString:e=>v("The value must be a value in the range %s",String(e.values[0])),isCriterionValueValid:e=>vo.test(e),criterionValueErrorString:Td.CriterionError.validRange,numberOfValues:()=>1,allowedValues:"onlyLiterals",name:v("Value in range"),getPreview:e=>v("Value in range %s",e.values[0])}),Pw.add("customFormula",{type:"customFormula",isValueValid:(e,t)=>{const r=t.values[0];return("number"==typeof r||"boolean"==typeof r)&&!!r},getErrorString:()=>v("The value does not match the custom formula data validation rule"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>1,allowedValues:"onlyFormulas",name:v("Custom formula"),getPreview:e=>v("Custom formula %s",e.values[0])}),Pw.add("beginsWithText",{type:"beginsWithText",isValueValid:(e,t)=>String(e).toLowerCase().startsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>v('The value must be a text that begins with "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Td.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text begins with"),getPreview:e=>v('Text begins with "%s"',e.values[0])}),Pw.add("endsWithText",{type:"endsWithText",isValueValid:(e,t)=>String(e).toLowerCase().endsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>v('The value must be a text that ends with "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:Td.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text ends with"),getPreview:e=>v('Text ends with "%s"',e.values[0])}),Pw.add("isEmpty",{type:"isEmpty",isValueValid:(e,t)=>""===(e??"").toString().trim(),getErrorString:()=>v("The value must be empty"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:v("Is empty"),getPreview:()=>v("Is empty")}),Pw.add("isNotEmpty",{type:"isNotEmpty",isValueValid:(e,t)=>""!==(e??"").toString().trim(),getErrorString:()=>v("The value must not be empty"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:v("Is not empty"),getPreview:()=>v("Is not empty")});function Gw(e){return Object.entries(e).map(([e,t])=>t?Ww(parseInt(e,10),t):void 0).filter(Se).map(e=>Bo(e.left,e.top)+":"+Bo(e.right,e.bottom))}function Ww(e,t){return{...t.zone,id:e}}class qw{measures;columns;rows;sortedColumn;collapsedDomains;customFields;constructor(e,t){this.columns=e.columns.map(e=>this.createPivotDimension(t,e)),this.rows=e.rows.map(e=>this.createPivotDimension(t,e)),this.measures=e.measures.map(e=>this.createMeasure(t,e)),this.sortedColumn=e.sortedColumn,this.collapsedDomains=e.collapsedDomains,this.customFields=e.customFields}getDimension(e){const t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new S(v("Dimension %s does not exist",e));return t}getMeasure(e){const t=this.measures.find(t=>t.id===e);if(!t)throw new S(v("Field %s is not a measure",e));return t}get invalidAggregatorsForCustomField(){return[]}createMeasure(e,t){const r=t.fieldName,n="__count"===r?{name:"__count",string:v("Count"),type:"integer",aggregator:"sum"}:e[r],o=t.aggregator;let s=!(!n&&!t.computedBy);for(const t of[...this.rows,...this.columns]){const r=e[t.fieldName];if(r?.isCustomField&&this.invalidAggregatorsForCustomField.includes(o)){s=!1;break}}return{id:t.id,get displayName(){return t.userDefinedName??n?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:r,aggregator:o,type:"__count"===r?"integer":n?.type??"integer",isValid:s,isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}createPivotDimension(e,t){const r=e[t.fieldName],n=r?.type??"integer",o=r&&function(e){return Zd.includes(e.type)}(r)?t.granularity:void 0;return{displayName:r?.string??t.fieldName,nameWithGranularity:t.fieldName+(o?`:${o}`:""),fieldName:t.fieldName,granularity:o,type:r?.isCustomField?"custom":n,order:t.order,isValid:!!r,isCustomField:!!r?.isCustomField,customGroups:r?.customGroups,parentField:r?.parentField}}}class Zw extends qw{range;constructor(e,t,r){if(super(e,t),e.dataSet){const{sheetId:t,zone:n}=e.dataSet;this.range=r.getRangeFromZone(t,n)}}}const Yw="(previous)";function jw(e,t){const r=e.definition.rows.map(e=>e.nameWithGranularity),n=t.filter(e=>r.includes(e.field)),o=e.definition.columns.map(e=>e.nameWithGranularity);return{colDomain:t.filter(e=>o.includes(e.field)),rowDomain:n}}function Xw(e,t,r){return"column"===t?jw(e,r).colDomain:jw(e,r).rowDomain}function Kw(e,t){return void 0!==Qw(e,t)}function Qw(e,t,r){let n=t;for(const t of e){const e=n.find(e=>e.value===t.value);if(!e)return;if(e.field===r)return n;n=e.children}return n}function Jw(e,t,r){const n=(e=re(e)).find(e=>e.field===t);return n?(n.value=r,e):e}function eS(e,t){return t.some(t=>t.field===e)}function tS(e,t){if(e.definition.rows.map(e=>e.nameWithGranularity).includes(t))return"row";if(e.definition.columns.map(e=>e.nameWithGranularity).includes(t))return"column";throw new Error(`Field ${t} not found in pivot`)}function rS(e){return e?e.map(nS).join(", "):""}function nS(e){return e?`${e.field}=${e.value}`:""}function oS(e,t){const r=e.findIndex(e=>e.field===t);if(-1===r)return"";const n=e.slice(0,r),o=e.at(-1);return rS(o.field===t?n:[...n,o])}function sS(e,t){const r=e.findIndex(e=>e.field===t);return-1===r?"":rS([...e.slice(0,r),...e.slice(r+1)])}function iS(e,t,r){const n=[...e],o=[...t];n.sort((e,t)=>r([...o,e],[...o,t]));for(const t of e){const e=iS(t.children,[...o,t],r);t.children=e}return n}function aS(e,t){return e.length>t.length&&t.every((t,r)=>Ae(t,e[r]))}class lS{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,r,n,o={COL:[],ROW:[]}){this.measures=r,this.fieldsType=n,o.COL.length&&(e=this.removeCollapsedColumns(e,r,o.COL)),this.columns=e.map(e=>{let t=1;return e.map(e=>(e={...e,offset:t},t+=e.width,e))}),this.rows=t.filter(e=>!this.isParentCollapsed(o.ROW,e)),this.maxIndent=Math.max(...this.rows.map(e=>e.indent)),this.rowTree=xe(()=>this.buildRowsTree()),this.colTree=xe(()=>this.buildColumnsTree())}removeCollapsedColumns(e,t,r){const n=(r,n)=>{const o=this.getDomain(r),s=e[n],i=s.findIndex(e=>aS(this.getDomain(e),o)),a=s.findLastIndex(e=>aS(this.getDomain(e),o)),l=n===e.length-1,c=t.map(e=>({fields:l?[...r.fields,"measure"]:[],values:l?[...r.values,e]:[],width:1,offset:0,collapsedHeader:!l}));s.splice(i,a-i+1,...c)};return e.map((o,s)=>{for(const i of o){if(s>=e.length-2)return o;const a=this.getDomain(i);if(r.some(e=>Ae(a,e))){i.width=t.length;for(let t=s+1;t<e.length;t++)n(i,t)}}return o})}isParentCollapsed(e,t){const r=this.getDomain(t);return e.some(e=>aS(r,e))}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getSkippedRows(e){const t=new Set;if(!e.displayColumnHeaders)for(let e=0;e<this.columns.length-1;e++)t.add(e);return e.displayMeasuresRow||t.add(this.columns.length-1),t}getPivotCells(e=Hd){const t=JSON.stringify(e);if(!this.pivotCells[t]){const{displayTotals:r}=e,n=this.rows.length,o=this.getNumberOfDataColumns();let s=this.columns.length+n,i=1+o;r||1===n||(s-=1),r||o===this.measures.length||(i-=this.measures.length);const a=[],l=this.getSkippedRows(e);for(let e=0;e<i;e++){a.push([]);for(let t=0;t<s;t++)l.has(t)||a[e].push(this.getPivotCell(e,t,r))}this.pivotCells[t]=a}return this.pivotCells[t]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,r=!0){const n=this.columns.length;if(e>0&&t===n-1){const r=this.getColHeaderDomain(e,t);if(!r)return cS;const n=r.at(-1)?.value?.toString()||"";return{type:"MEASURE_HEADER",domain:r.slice(0,-1),measure:n}}if(t<=n-1){const r=this.getColHeaderDomain(e,t);return r?{type:"HEADER",domain:r,dimension:"COL"}:cS}if(0===e){const e=t-n;return{type:"HEADER",domain:this.getDomain(this.rows[e]),dimension:"ROW"}}{const o=t-n;if(!r&&this.isTotalRow(o))return cS;return{type:"VALUE",domain:[...this.getDomain(this.rows[o]),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(0===e)return;const r=this.columns[t].find(t=>t.offset===e);return r&&!r.collapsedHeader?this.getDomain(r):void 0}getDomain(e){return e.fields.map((t,r)=>{if("measure"===t)return{type:"char",field:t,value:Kd({displayName:"measure",type:"char"},e.values[r])};{const{fieldName:n,granularity:o}=Yd(t),s=this.fieldsType[n]||"char";return{type:s,field:t,value:Kd({displayName:n,type:s,granularity:o},e.values[r])}}})}getColDomain(e){const t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){const t=this.getColHeaderDomain(e,this.columns.length-1),r=t?.at(-1)?.value;if(null==r)throw new Error("Measure is missing");return r.toString()}buildRowsTree(){const e=[];let t=0;const r={};r[0]=e;for(const n of this.rows){if(0===n.fields.length||0===n.values.length)return e;const o=n.fields.length-1,s=n.fields[o],{fieldName:i,granularity:a}=Yd(s),l=Kd({displayName:i,type:this.fieldsType[i]??"char",granularity:a},n.values[o]);if(o>t){t=o,r[t]=[];const e=r[t-1].at(-1);e&&(e.children=r[t])}t=o;const c={value:l,field:n.fields[o],children:[],type:this.fieldsType[i]||"char",width:0};r[t].push(c)}return e}buildColumnsTree(){const e=[],t=this.columns.at(-2)||[],r={};r[0]=e;for(const e of t)for(let t=0;t<e.fields.length;t++){const n=e.fields[t],{fieldName:o,granularity:s}=Yd(n),i=Kd({displayName:o,type:this.fieldsType[o]??"char",granularity:s},e.values[t]),a={value:i,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[o]||"char"};r[t]?.at(-1)?.value!==i&&(r[t+1]=[],a.children=r[t+1],r[t].push(a))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}sort(e,t,r){if(this.isSorted)return;const n=(e,t)=>{const n=r(e,t).value;return"number"==typeof n?n:-1/0},o=t.domain,s=iS(this.rowTree(),[],(r,s)=>{const i=n(e,[...r,...o]),a=n(e,[...s,...o]);return"asc"===t.order?i-a:a-i});this.rowTree=xe(s),this.rows=[...this.rowTreeToRows(s),this.rows[this.rows.length-1]],this.isSorted=!0}rowTreeToRows(e,t){return e.flatMap(e=>{const r={indent:t?t.indent+1:1,fields:[...t?.fields||[],e.field],values:[...t?.values||[],e.value]};return[r,...this.rowTreeToRows(e.children,r)]})}get numberOfCells(){return this.rows.length*this.getNumberOfDataColumns()}getColumnDomainsAtDepth(e){return e<0||e>=this.columns.length-1?[]:this.columns[e].map(e=>this.getDomain(e)).filter(e=>e.length)}getRowDomainsAtDepth(e){return e<0||e>this.maxIndent?[]:this.rows.filter(t=>t.indent===e+1).map(e=>this.getDomain(e))}}const cS={type:"EMPTY"};function uS(e,t,r){const n=t.measures.filter(e=>!e.isHidden).map(e=>e.id),o=dS(e,t.columns,0);fS(o,n.length);const s=function(e,t){const r=t.columns.map(e=>e.nameWithGranularity),n=r.length,o=t.measures.filter(e=>!e.isHidden),s=o.length,i=new Array(n).fill(0).map(()=>[]);function a(e,t,o){const s=i[t];for(const i of e){const e=o.concat([i.value]),l={fields:r.slice(0,t+1),values:e,width:i.width,offset:0};s.push(l),t<=n-1&&a(i.children,t+1,e)}}a(e,0,[]);const l=r.length>0,c=[];l&&i[i.length-1].forEach(e=>{o.forEach(t=>{const r={fields:[...e.fields,"measure"],values:[...e.values,t.id],width:1,offset:0};c.push(r)})});o.forEach(e=>{const t={fields:["measure"],values:[e.id],width:1,offset:0};c.push(t)}),i.push(c),1===i.length&&i.unshift([]);return i[i.length-2].push({fields:[],values:[],width:s,offset:0}),i}(o,t),i=hS(e,0,t.rows,[],[]);i.push({fields:[],values:[],indent:0});const a={};for(const e of t.columns)a[e.fieldName]=e.type;for(const e of t.rows)a[e.fieldName]=e.type;const l="collapsed"===r?t.collapsedDomains:void 0;return new lS(s,i,n,a,l)}function hS(e,t,r,n,o){if(t>=r.length)return[];const s=r[t],i=s.nameWithGranularity,a=gS(e,s),l=mS(a,s),c=[],u=n.concat(i);for(const e of l){const n=o.concat(e);c.push({fields:u,values:n,indent:t+1});const s=a[e];s&&c.push(...hS(s,t+1,r,u,n))}return c}function dS(e,t,r){if(r>=t.length)return[];const n=t[r],o=t[r].nameWithGranularity,s=gS(e,n);return mS(s,t[r]).map(e=>({value:s[e]?.[0]?.[n.nameWithGranularity]?.value??null,field:o,children:dS(s[e]||[],t,r+1),type:n.type,width:0}))}function fS(e,t){for(const r in e){const n=e[r];0===n.children.length?n.width=t:(fS(n.children,t),n.width=n.children.reduce((e,t)=>e+t.width,0))}}function gS(e,t){return Object.groupBy(e,function(e){const t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}(t))}function mS(e,t){const r=t.order,n=t.customGroups?.find(e=>e.isOtherGroup);return r||n?Object.keys(e).sort((e,o)=>n&&e===n.name?1:n&&o===n.name?-1:r?function(e,t,r){if("null"===t)return"asc"===e.order?1:-1;if("null"===r)return"asc"===e.order?-1:1;if("integer"===e.type||"datetime"===e.type)return"asc"===e.order?kt(t,xr)-kt(r,xr):kt(r,xr)-kt(t,xr);return"asc"===e.order?t.localeCompare(r):r.localeCompare(t)}(t,e,o):0):Object.keys(e)}const pS=Symbol("NULL");function bS(e,t,r){const n=e.granularity||"month";if(!(n in vS))throw new Error(`Unknown date granularity: ${n}`);const o="number"==typeof t||"string"==typeof t?t:pS;if(!vS[n].set.has(t)){vS[n].set.add(t);let s=null;if("number"==typeof t||"string"==typeof t){const e=Zt(t,r);switch(n){case"year":s=e.getFullYear();break;case"quarter_number":s=Math.floor(e.getMonth()/3)+1;break;case"month_number":s=e.getMonth()+1;break;case"month":case"day":s=Math.floor(kt(t,r));break;case"iso_week_number":s=e.getIsoWeek();break;case"day_of_month":s=e.getDate();break;case"day_of_week":s=(e.getDay()+7-r.weekStart)%7+1;break;case"hour_number":s=e.getHours();break;case"minute_number":s=e.getMinutes();break;case"second_number":s=e.getSeconds()}}vS[n].values[o]=Kd(e,s)}return vS[n].values[o]}const vS={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};var yS;!function(e){e[e.NONE=0]="NONE",e[e.TABLE=1]="TABLE",e[e.DATA=2]="DATA",e[e.DEFINITION=3]="DEFINITION",e[e.ALL=4]="ALL"}(yS||(yS={}));const ES=new h,wS=["year","quarter_number","month_number","month","iso_week_number","day_of_month","day","day_of_week"];ES.add("SPREADSHEET",{ui:class{type="SPREADSHEET";getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];collapsedTable;expandedTable;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){this._definition&&!e.reload||(this.reload(yS.ALL),this.needsReevaluation=!1)}reload(e){e===yS.ALL&&(this.metaData=this.loadMetaData()),e>=yS.DEFINITION&&(this._definition=this.loadRuntimeDefinition()),e>=yS.DATA&&(this.dataEntries=this.loadData()),e>=yS.TABLE&&(this.collapsedTable=void 0,this.expandedTable=void 0)}onDefinitionChange(e){const t=this.coreDefinition;if(this.coreDefinition=e,this._definition){const r=Math.max(this.computeShouldReload(t,e),yS.NONE);this.reload(r)}}computeShouldReload(e,t){return Ae(e.dataSet,t.dataSet)?yS.DEFINITION:yS.ALL}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw new Error("Pivot definition should be defined at this point.");return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(const e of this.definition.measures)if(!e.isValid)return!1;for(const e of this.definition.columns)if(!e.isValid)return!1;for(const e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new S(v("At least one measure and/or dimension is not correct."));return{value:E.GenericError,message:this.invalidRangeError?.message??v("At least one measure and/or dimension is not correct.")}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map($t);return t.length&&"measure"===t.at(-1)&&(t=t.slice(0,-1)),function(e,t){let r=0,n=0;const o=t.columns.map(e=>e.nameWithGranularity),s=t.rows.map(e=>e.nameWithGranularity);for(;void 0!==e[r]&&e[r]===s[n];)r++,n++;for(n=0;void 0!==e[r]&&e[r]===o[n];)r++,n++;return e.length===r}(t,this.definition)}parseArgsToPivotDomain(e){const t=[];for(let r=0;r<e.length-1;r+=2){const n=$t(e[r]),o=this.getTypeOfDimension(n),s="measure"===n?$t(e[r+1]):Kd(this.getDimension(n),e[r+1]);t.push({field:n,value:s,type:o})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){const t=e.at(-1);if(!t)return{value:v("Total")};const r=this.getDimension(t.field),n=this.filterDataEntriesFromDomain(this.dataEntries,e),o=n[0]?.[r.nameWithGranularity];if("datetime"===r.type){return Rd(r.granularity||"month").toValueAndFormat(t.value,this.getters.getLocale())}return o?null===o.value?{value:v("(Undefined)")}:o:{value:""}}getPivotCellValueAndFormat(e,t){const r=this.filterDataEntriesFromDomain(this.dataEntries,t);if(0===r.length)return{value:""};const n=this.getMeasure(e),o=r.map(e=>e[n.fieldName]).filter(Se),s=o.filter(e=>e.type!==Nu.empty),i=n.aggregator,a=Wd[i];if(!a)throw new Error(`Aggregator ${i} does not exist`);try{const e=a([o],this.getters.getLocale());return 0===s.length?{...e,value:""}:e}catch(e){return wr(e,i.toUpperCase())}}getPossibleFieldValues(e){const t=[],r=gS(this.dataEntries,e),n=mS(r,e);for(const o of n)t.push({value:r[o]?.[0]?.[e.nameWithGranularity]?.value??"",label:r[o]?.[0]?.[e.nameWithGranularity]?.formattedValue||""});return t}getCollapsedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.collapsedTable||(this.collapsedTable=uS(this.dataEntries,this.definition,"collapsed")),this.collapsedTable}getExpandedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.expandedTable||(this.expandedTable=uS(this.dataEntries,this.definition,"expanded")),this.expandedTable}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,!this.coreDefinition.dataSet)return this.invalidRangeError=new S(v("The pivot cannot be created because the dataset is missing.")),{fields:{},fieldKeys:[]};{const{zone:e,sheetId:t}=this.coreDefinition.dataSet,r=this.getters.getRangeFromZone(t,e);try{const e=this.extractFieldsFromRange(r),t=function(e,t){const r={};for(const n of Object.values(e.customFields||{}))t[n.parentField]&&(r[n.name]={type:"custom",isCustomField:!0,name:n.name,string:n.name,customGroups:n.groups,parentField:n.parentField});return r}(this.coreDefinition,e.fields);return{...e,fields:{...e.fields,...t}}}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}}loadRuntimeDefinition(){return new Zw(this.coreDefinition,this.fields,this.getters)}loadData(){const e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if("measure"===e)return"char";const{fieldName:t}=Yd(e),r=this.fields[t]?.type;if(!r)throw new Error(`Field ${t} does not exist`);return r}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){const{field:r,value:n,type:o}=t,{nameWithGranularity:s}=this.getDimension(r);return e.filter(e=>{const t=e[s]?.value;return"char"===o?String(t)===String(n):t===n})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){const r=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===Nu.empty||""===e.value));return 0===r.length?"integer":r.every(e=>e.type===Nu.number&&e.format&&on(e.format))?"datetime":r.every(e=>e.type===Nu.boolean)?"boolean":r.some(e=>e.type===Nu.text)?"char":"integer"}assertCellIsValidField(e,t,r){if(r.type===Nu.error)throw new S(v("The pivot cannot be created because cell %s contains an error",Bo(e,t)));if(r.type===Nu.empty||""===r.value)throw new S(v("The pivot cannot be created because cell %s is empty",Bo(e,t)));if("__count"===r.value)throw new S(v("The pivot cannot be created because cell %s contains a reserved value",Bo(e,t)))}extractFieldsFromRange(e){const t={},r=[],n=e.sheetId,o=e.zone.top;for(let s=e.zone.left;s<=e.zone.right;s++){const i=this.getters.getEvaluatedCell({sheetId:n,col:s,row:o});this.assertCellIsValidField(s,o,i);const a=i.value?.toString();if(a){const o=this.getTypeFromZone(n,{top:e.zone.top+1,left:s,bottom:e.zone.bottom,right:s}),i=of(a,t);t[i]={name:i,type:o,string:i,aggregator:"integer"===o?"sum":"count"},r.push(i)}}return{fields:t,fieldKeys:r}}extractDataEntriesFromRange(e){const t=[];for(let r=e.zone.top+1;r<=e.zone.bottom;r++){const n={top:r,bottom:r,left:e.zone.left,right:e.zone.right},o=this.getters.getEvaluatedCellsInZone(e.sheetId,n),s={};for(const e in o){const t=o[e],r=this.fields[this.metaData.fieldKeys[e]];if(!r)throw new Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);""===t.value?s[r.name]={value:null,type:Nu.empty,formattedValue:""}:s[r.name]=t}for(const e in this.definition.customFields||{}){const t=this.definition.customFields?.[e];if(!t)continue;const r=s[t.parentField],n=this.fields[t.parentField];if(!r||!n){s[e]={value:null,type:Nu.empty,formattedValue:""};continue}const o=t.groups.find(e=>e.values.some(e=>e===r?.value))||t.groups.find(e=>e.isOtherGroup);s[e]={...r,value:o?o.name:r.value}}s.__count={value:1,type:Nu.number,formattedValue:"1"},t.push(s)}const r=this.definition.columns.concat(this.definition.rows).filter(e=>"datetime"===e.type);if(r.length){const e=this.getters.getLocale();for(const n of t)for(const t of r){const r=bS(t,n[t.fieldName]?.value||null,this.getters.getLocale()),o=Rd(t.granularity||"month"),{format:s,value:i}=o.toValueAndFormat(r,e);n[t.nameWithGranularity]={value:r,type:n[t.fieldName]?.type||Nu.empty,format:n[t.fieldName]?.format,formattedValue:Xr(i,{locale:e,format:s})}}}return t}},definition:Zw,dateGranularities:[...wS],datetimeGranularities:[...wS,"hour_number","minute_number","second_number"],isMeasureCandidate:e=>"boolean"!==e.type,isGroupable:()=>!0,canHaveCustomGroup:e=>"char"===e.type&&!e.isCustomField,isPivotUnused:()=>!0,adaptRanges:(e,t,r)=>{if("SPREADSHEET"!==t.type||!t.dataSet)return t;const{sheetId:n,zone:o}=t.dataSet,s=e.getRangeFromZone(n,o),i=function(e,t){if(!e)return;const r=t(e);if("REMOVE"===r.changeType)return;return r.range}(s,r);if(i===s)return t;const a=i&&{sheetId:i.sheetId,zone:i.zone};return{...t,dataSet:a}}});const SS={verticalAlign:"bottom",wrapping:"overflow",bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:"",textColor:""};const CS=["wholeTable","firstColumnStripe","secondColumnStripe","firstRowStripe","secondRowStripe","firstColumn","lastColumn","headerRow","totalRow"];function TS(e,t,r,n){const o=t.zone;if(o.left!==o.right)throw new Error("Can only define a filter on a single column");const s={...o,top:o.top+r.numberOfHeaders},i=n(t.sheetId,s);return{id:e,rangeWithHeaders:t,col:o.left,filteredRange:s.top>s.bottom?void 0:i}}function IS(e,t,r,n){const o=rr(r,n,()=>({}));for(const s of CS){const i=t[s]?.border;if(!i)continue;const a=OS(s,e,r,n);for(const t of a)for(let a=t.left;a<=t.right;a++)for(let l=t.top;l<=t.bottom;l++){const c="wholeTable"===s&&l<=e.numberOfHeaders-1;l===t.top&&i?.top?xS(o,"top",i.top,a,l,r,n):l!==t.top&&!c&&i?.horizontal&&xS(o,"top",i.horizontal,a,l,r,n),l===t.bottom&&i?.bottom&&xS(o,"bottom",i.bottom,a,l,r,n),a===t.left&&i?.left&&xS(o,"left",i.left,a,l,r,n),a===t.right&&i?.right?xS(o,"right",i.right,a,l,r,n):a!==t.right&&!c&&i?.vertical&&xS(o,"right",i.vertical,a,l,r,n)}}return o}function xS(e,t,r,n,o,s,i){switch(t){case"top":return e[n][o].top=r,void(0!==o&&(e[n][o-1].bottom=r));case"bottom":return e[n][o].bottom=r,void(o!==i-1&&(e[n][o+1].top=r));case"left":return e[n][o].left=r,void(0!==n&&(e[n-1][o].right=r));case"right":return e[n][o].right=r,void(n!==s-1&&(e[n+1][o].left=r))}}function RS(e,t,r,n){const o=rr(r,n,()=>({}));for(const s of CS){const i=t[s],a=AS(s);if(!i&&!a)continue;const l=OS(s,e,r,n);for(const e of l)for(let t=e.left;t<=e.right;t++)for(let r=e.top;r<=e.bottom;r++)o[t][r]||(o[t][r]={}),o[t][r]={...o[t][r],...i?.style},a&&(o[t][r].bold=!0)}return o}function AS(e){return"firstColumn"===e||"lastColumn"===e||"headerRow"===e||"totalRow"===e}function OS(e,t,r,n){const o=[],s=Math.min(t.numberOfHeaders,n),i=t.totalRow?1:0,a=r-1,l=n-1;switch(e){case"wholeTable":o.push({top:0,left:0,bottom:l,right:a});break;case"firstColumn":if(!t.firstColumn)break;o.push({top:0,left:0,bottom:l,right:0});break;case"lastColumn":if(!t.lastColumn)break;o.push({top:0,left:a,bottom:l,right:a});break;case"headerRow":if(!t.numberOfHeaders)break;o.push({top:0,left:0,bottom:s-1,right:a});break;case"totalRow":if(!t.totalRow)break;o.push({top:l,left:0,bottom:l,right:a});break;case"firstRowStripe":if(!t.bandedRows)break;for(let e=s;e<n-i;e+=2)o.push({top:e,left:0,bottom:e,right:a});break;case"secondRowStripe":if(!t.bandedRows)break;for(let e=s+1;e<n-i;e+=2)o.push({top:e,left:0,bottom:e,right:a});break;case"firstColumnStripe":if(!t.bandedColumns)break;for(let e=0;e<r;e+=2)o.push({top:s,left:e,bottom:l-i,right:e});break;case"secondColumnStripe":if(!t.bandedColumns)break;for(let e=1;e<r;e+=2)o.push({top:s,left:e,bottom:l-i,right:e})}return o}const _S=nm.content;function DS(e){try{return 0===Cm(wm(e)).filter(e=>"FUNCALL"===e.type&&!_S[e.value.toUpperCase()]?.isExported).length}catch(e){return!1}}function FS(e,t){if(!e.some(e=>"SYMBOL"===e.type&&t.includes(e.value.toUpperCase())))return[];let r;try{r=wm(e)}catch{return[]}return function(e,t){return Cm(e).filter(e=>"FUNCALL"===e.type&&t.includes(e.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}(r,t)}class NS extends Vs{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}}const MS=nm.mapping;function VS(e,t,r){return new LS(e,t,r).getParameters()}class LS{getters;computeCell;evalContext;rangeCache={};constructor(e,t,r){this.getters=t,this.computeCell=r,this.evalContext=Object.assign(Object.create(MS),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){const r=this.getRangeError(e);if(r)return r;const n={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};if(t){this.computeCell(n);return{value:Io(this.getters.getSheetName(e.sheetId),es(e.zone))}}return this.computeCell(n)}range(e,t){const r=this.getRangeError(e);if(r)return[[r]];const n=e.sheetId,o=e.zone,s=os(o,this.getters.getSheetZone(n));if(!s)return[[]];const{top:i,left:a,bottom:l,right:c}=o,u=`${n}-${i}-${a}-${l}-${c}-${t}`;if(u in this.rangeCache)return this.rangeCache[u];const h=s.bottom-s.top+1,d=s.right-s.left+1,f=new Array(d),g=this.getters.getSheetName(e.sheetId);for(let e=s.left;e<=s.right;e++){const r=e-s.left;f[r]=new Array(h);for(let o=s.top;o<=s.bottom;o++){const i=o-s.top,a=this.computeCell({sheetId:n,col:e,row:o});f[r][i]=t?{value:Io(g,Bo(e,o))}:a}}return this.rangeCache[u]=f,f}getRangeError(e){return Qo(e.zone)?e.invalidSheetName?new I(v("Invalid sheet name: %s",e.invalidSheetName)):void 0:new I}}function PS(e,t,r,n,o){kS(e,t,r||0,n||e.length-1,o||HS)}function kS(e,t,r,n,o){for(;n>r;){if(n-r>600){var s=n-r+1,i=t-r+1,a=Math.log(s),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(s-l)/s)*(i-s/2<0?-1:1);kS(e,t,Math.max(r,Math.floor(t-i*l/s+c)),Math.min(n,Math.floor(t+(s-i)*l/s+c)),o)}var u=e[t],h=r,d=n;for(US(e,r,t),o(e[n],u)>0&&US(e,r,n);h<d;){for(US(e,h,d),h++,d--;o(e[h],u)<0;)h++;for(;o(e[d],u)>0;)d--}0===o(e[r],u)?US(e,r,d):US(e,++d,n),d<=t&&(r=d+1),t<=d&&(n=d-1)}}function US(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function HS(e,t){return e<t?-1:e>t?1:0}class BS{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const r=[];if(!JS(e,t))return r;const n=this.toBBox,o=[];for(;t;){for(let s=0;s<t.children.length;s++){const i=t.children[s],a=t.leaf?n(i):i;JS(e,a)&&(t.leaf?r.push(i):QS(e,a)?this._all(i,r):o.push(i))}t=o.pop()}return r}collides(e){let t=this.data;if(!JS(e,t))return!1;const r=[];for(;t;){for(let n=0;n<t.children.length;n++){const o=t.children[n],s=t.leaf?this.toBBox(o):o;if(JS(e,s)){if(t.leaf||QS(e,s))return!0;r.push(o)}}t=r.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=eC([]),this}remove(e,t){if(!e)return this;let r=this.data;const n=this.toBBox(e),o=[],s=[];let i,a,l;for(;r||o.length;){if(r||(r=o.pop(),a=o[o.length-1],i=s.pop(),l=!0),r.leaf){const n=zS(e,r.children,t);if(-1!==n)return r.children.splice(n,1),o.push(r),this._condense(o),this}l||r.leaf||!QS(r,n)?a?(i++,r=a.children[i],l=!1):r=null:(o.push(r),s.push(i),i=0,a=r,r=r.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const r=[];for(;e;)e.leaf?t.push(...e.children):r.push(...e.children),e=r.pop();return t}_build(e,t,r,n){const o=r-t+1;let s,i=this._maxEntries;if(o<=i)return s=eC(e.slice(t,r+1)),$S(s,this.toBBox),s;n||(n=Math.ceil(Math.log(o)/Math.log(i)),i=Math.ceil(o/Math.pow(i,n-1))),s=eC([]),s.leaf=!1,s.height=n;const a=Math.ceil(o/i),l=a*Math.ceil(Math.sqrt(i));tC(e,t,r,l,this.compareMinX);for(let o=t;o<=r;o+=l){const t=Math.min(o+l-1,r);tC(e,o,t,a,this.compareMinY);for(let r=o;r<=t;r+=a){const o=Math.min(r+a-1,t);s.children.push(this._build(e,r,o,n-1))}}return $S(s,this.toBBox),s}_chooseSubtree(e,t,r,n){for(;n.push(t),!t.leaf&&n.length-1!==r;){let r,n=1/0,o=1/0;for(let s=0;s<t.children.length;s++){const i=t.children[s],a=YS(i),l=XS(e,i)-a;l<o?(o=l,n=a<n?a:n,r=i):l===o&&a<n&&(n=a,r=i)}t=r||t.children[0]}return t}_insert(e,t,r){const n=r?e:this.toBBox(e),o=[],s=this._chooseSubtree(n,this.data,t,o);for(s.children.push(e),WS(s,n);t>=0&&o[t].children.length>this._maxEntries;)this._split(o,t),t--;this._adjustParentBBoxes(n,o,t)}_split(e,t){const r=e[t],n=r.children.length,o=this._minEntries;this._chooseSplitAxis(r,o,n);const s=this._chooseSplitIndex(r,o,n),i=eC(r.children.splice(s,r.children.length-s));i.height=r.height,i.leaf=r.leaf,$S(r,this.toBBox),$S(i,this.toBBox),t?e[t-1].children.push(i):this._splitRoot(r,i)}_splitRoot(e,t){this.data=eC([e,t]),this.data.height=e.height+1,this.data.leaf=!1,$S(this.data,this.toBBox)}_chooseSplitIndex(e,t,r){let n,o=1/0,s=1/0;for(let i=t;i<=r-t;i++){const t=GS(e,0,i,this.toBBox),a=GS(e,i,r,this.toBBox),l=KS(t,a),c=YS(t)+YS(a);l<o?(o=l,n=i,s=c<s?c:s):l===o&&c<s&&(s=c,n=i)}return n||r-t}_chooseSplitAxis(e,t,r){const n=e.leaf?this.compareMinX:qS,o=e.leaf?this.compareMinY:ZS;this._allDistMargin(e,t,r,n)<this._allDistMargin(e,t,r,o)&&e.children.sort(n)}_allDistMargin(e,t,r,n){e.children.sort(n);const o=this.toBBox,s=GS(e,0,t,o),i=GS(e,r-t,r,o);let a=jS(s)+jS(i);for(let n=t;n<r-t;n++){const t=e.children[n];WS(s,e.leaf?o(t):t),a+=jS(s)}for(let n=r-t-1;n>=t;n--){const t=e.children[n];WS(i,e.leaf?o(t):t),a+=jS(i)}return a}_adjustParentBBoxes(e,t,r){for(let n=r;n>=0;n--)WS(t[n],e)}_condense(e){for(let t,r=e.length-1;r>=0;r--)0===e[r].children.length?r>0?(t=e[r-1].children,t.splice(t.indexOf(e[r]),1)):this.clear():$S(e[r],this.toBBox)}}function zS(e,t,r){if(!r)return t.indexOf(e);for(let n=0;n<t.length;n++)if(r(e,t[n]))return n;return-1}function $S(e,t){GS(e,0,e.children.length,t,e)}function GS(e,t,r,n,o){o||(o=eC(null)),o.minX=1/0,o.minY=1/0,o.maxX=-1/0,o.maxY=-1/0;for(let s=t;s<r;s++){const t=e.children[s];WS(o,e.leaf?n(t):t)}return o}function WS(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function qS(e,t){return e.minX-t.minX}function ZS(e,t){return e.minY-t.minY}function YS(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function jS(e){return e.maxX-e.minX+(e.maxY-e.minY)}function XS(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function KS(e,t){const r=Math.max(e.minX,t.minX),n=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),s=Math.min(e.maxY,t.maxY);return Math.max(0,o-r)*Math.max(0,s-n)}function QS(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function JS(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function eC(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function tC(e,t,r,n,o){const s=[t,r];for(;s.length;){if((r=s.pop())-(t=s.pop())<=n)continue;const i=t+Math.ceil((r-t)/n/2)*n;PS(e,i,t,r,o),s.push(t,i,i,r)}}class rC{rTrees={};constructor(e=[]){const t={};for(const r of e){const e=r.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(r)}for(const e in t)this.rTrees[e]=new nC,this.rTrees[e].load(t[e])}insert(e){const t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new nC),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){const t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&Ae(e.data,t.data)}}class nC extends BS{toBBox({boundingBox:e}){const t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}}class oC{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(const t of e)this.add(t)}isEmpty(){return 1===this.profiles.size&&0===this.profiles.get(0)?.length}add(e){$o(this.profilesStartingPosition,this.profiles,[e])}delete(e){$o(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return function(e,t,r){const n=r.left,o=r.right,s=Yo(e,n,0),i=void 0===o?e.length-1:Yo(e,o,s),a=r.top,l=void 0===r.bottom?void 0:r.bottom+1;for(let r=s;r<=i;r++){const n=t.get(e[r]),o=Yo(n,a,0);if(-1===o||o%2!=0)return!1;if(o+1!==(void 0===l?n.length:jo(n,l,0)))return!1}return!0}(this.profilesStartingPosition,this.profiles,e)}difference(e){const t=this.copy();for(const r of e)t.delete(r);return t}copy(){const e=new oC;e.profilesStartingPosition=[...this.profilesStartingPosition],e.profiles=new Map;for(const[t,r]of this.profiles)e.profiles.set(t,[...r]);return e}[Symbol.iterator](){return Zo(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}}class sC{setsBySheetId={};constructor(e=[]){for(const t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new oC),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(const t of e)this.add(t)}addPosition(e){this.add(Gm(e))}addManyPositions(e){for(const t of e)this.addPosition(t)}has(e){return!!this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].has(e.zone)}hasPosition(e){return this.has(Gm(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(const t of e)this.delete(t)}deleteManyPositions(e){for(const t of e)this.delete(Gm(t))}difference(e){const t=new sC;for(const e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e];for(const r in e.setsBySheetId)t.setsBySheetId[r]&&(t.setsBySheetId[r]=t.setsBySheetId[r].difference(e.setsBySheetId[r]));return t}copy(){const e=new sC;for(const t in this.setsBySheetId)e.setsBySheetId[t]=this.setsBySheetId[t].copy();return e}clear(){this.setsBySheetId={}}isEmpty(){for(const e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){const e=[];for(const t in this.setsBySheetId)for(const r of this.setsBySheetId[t])e.push({sheetId:t,zone:r});return e[Symbol.iterator]()}}class iC{rTree;constructor(e=[]){const t=function(e){let t=0,r=0;for(let n=0;n<e.length;n++){const o=e[n].boundingBox.zone;o.right>t&&(t=o.right),o.bottom>r&&(r=o.bottom)}t+=1,r+=1;const n=(((r+1)*t+1)*r+1)*t<=Number.MAX_SAFE_INTEGER;n||console.warn("Max col/row size exceeded, using slow zone key");const o={};for(const s of e){const e=s.boundingBox.sheetId;o[e]||(o[e]={});const i=s.boundingBox.zone;let a=0;if(a=n?i.left+i.top*t+i.right*t*r+i.bottom*t*r*t:`${i.left},${i.top},${i.right},${i.bottom}`,o[e][a]){o[e][a].data.add(s.data)}else o[e][a]={boundingBox:s.boundingBox,data:new sC([s.data])}}const s=[];for(const e in o){const t=o[e];for(const e in t)s.push(t[e])}return s}(e);this.rTree=new rC(t)}insert(e){const t=this.rTree.search(e.boundingBox),r=e.boundingBox,n=t.find(({boundingBox:e})=>e.sheetId===r.sheetId&&e.zone.left===r.zone.left&&e.zone.top===r.zone.top&&e.zone.right===r.zone.right&&e.zone.bottom===r.zone.bottom);n?n.data.add(e.data):this.rTree.insert({...e,data:new sC([e.data])})}search({zone:e,sheetId:t}){const r=new sC;for(const{data:n}of this.rTree.search({zone:e,sheetId:t}))r.addMany(n);return r}remove(e){const t=this.rTree.search(e.boundingBox),r=e.boundingBox,n=t.find(({boundingBox:e})=>e.sheetId===r.sheetId&&e.zone.left===r.zone.left&&e.zone.top===r.zone.top&&e.zone.right===r.zone.right&&e.zone.bottom===r.zone.bottom);n?n.data.delete(e.data):this.rTree.remove({...e,data:new sC([e.data])})}}class aC{dependencies=new Nw;rTree;constructor(e=[]){this.rTree=new iC(e)}removeAllDependencies(e){const t=this.dependencies.get(e);if(t){for(const e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){const r=t.map(({sheetId:t,zone:r})=>({data:{sheetId:e.sheetId,zone:ps(e)},boundingBox:{zone:r,sheetId:t}}));for(const e of r)this.rTree.insert(e);const n=this.dependencies.get(e);n?n.push(...r):this.dependencies.set(e,r)}getCellsDependingOn(e,t=new sC){t=t.copy();const r=Array.from(e).reverse();for(;r.length>0;){const e=r.pop();t.add(e);const n=this.rTree.search(e);r.push(...n.difference(t))}for(const r of e)t.delete(r);return t}}class lC extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){const r=function(e){if(0===e)return-1/0;if(e<0)return NaN;return 32-Math.clz32(--e)}(t),n=new this((e<<r>>5)+1);return n.columnOffset=r,n.cols=t,n.rows=e,n}getValue(e){const[t,r]=this.getCoordinates(e);return this[t]>>r&1}setValue(e,t){const[r,n]=this.getCoordinates(e),o=0===(this[r]>>n&1)&&1===t;return this[r]=this[r]&~(1<<n)|t<<n,o}isEmpty(){return!this.some(e=>0!==e)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){const{row:t,col:r}=e,n=(t<<this.columnOffset)+r,o=n>>5;return[o,n-(o<<5)]}}class cC{sheets={};insertions=[];maxSize=0;constructor(e){for(const t in e){const r=e[t].cols,n=e[t].rows;this.maxSize+=r*n,this.sheets[t]=lC.create(n,r)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(const t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(const t of e)this.delete(t)}has(e){return 1===this.sheets[e.sheetId].getValue(e)}clear(){const e=[...this];this.insertions=[];for(const e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(0===this.insertions.length)return!0;for(const e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=new Array(this.maxSize);let e=0;for(const t in this.sheets){const r=this.sheets[t];r.fillAllPositions();for(let n=0;n<r.rows;n++)for(let o=0;o<r.cols;o++)this.insertions[e++]={sheetId:t,row:n,col:o}}}*[Symbol.iterator](){for(const e of this.insertions)1===this.sheets[e.sheetId].getValue(e)&&(yield e)}}class uC{resultsToArrayFormulas=new rC;arrayFormulasToResults=new Nw;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||hC}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){const t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}}const hC=[],dC=new Id;dC.add("pivots",e=>{for(const t of e.getPivotIds()){const r=e.getPivot(t);r.markAsDirtyForEvaluation?.()}});const fC=Object.freeze(hE({...new T,origin:void 0})),gC=Object.freeze(hE({value:null}));class mC{context;getters;compilationParams;evaluatedCells=new Nw;formulaDependencies=xe(new aC);blockedArrayFormulas=new cC({});spreadingRelations=new uC;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=VS(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||gC}getSpreadZone(e,t={ignoreSpillError:!1}){const r=this.spreadingRelations.getArrayResultZone(e);if(!r)return;const n=this.evaluatedCells.get(e);return n?.type!==Nu.error||t.ignoreSpillError&&n?.value===E.SpilledBlocked?ns(ps(e),r):ps(e)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===Nu.empty)return;return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,ps(e)).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);const t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(const e of t)this.compilationParams.ensureRange(e,!1)}updateCompilationParameters(){this.compilationParams=VS(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){const e={};for(const t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new cC(e)}evaluateCells(e){const t=performance.now(),r=new sC;r.addManyPositions(e);const n=this.getArrayFormulasImpactedByChangesOf(e);r.addMany(this.getCellsDependingOn(r)),r.addMany(n),r.addMany(this.getCellsDependingOn(n)),this.evaluate(r),console.debug("evaluate Cells",performance.now()-t,"ms")}getArrayFormulasImpactedByChangesOf(e){const t=new sC;for(const r of e){const e=this.getters.getCell(r)?.content,n=this.getArrayFormulaSpreadingOn(r);void 0!==n&&t.addPosition(n),e||t.addPosition(r)}for(const e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new uC,this.formulaDependencies=xe(()=>{const e=[];for(const t of this.getters.getSheetIds()){const r=this.getters.getCells(t);for(const n in r){const o=r[n];if(o.isFormula){const r=o.compiledFormula.dependencies;for(const o of r)o.invalidSheetName||o.invalidXc||e.push({data:{sheetId:t,zone:ps(this.getters.getCellPosition(n))},boundingBox:{sheetId:o.sheetId,zone:o.zone}})}}}return new aC(e)})}evaluateAllCells(){const e=performance.now();this.evaluatedCells=new Nw;const t=[];for(const e of this.getters.getSheetIds()){const r=this.getters.getSheetZone(e);t.push({sheetId:e,zone:r})}this.evaluate(t),console.debug("evaluate all cells",performance.now()-e,"ms")}evaluateFormulaResult(e,t){const r=_m(t),n=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParameters(),this.evaluateCompiledFormula(e,{...r,dependencies:n})}evaluateCompiledFormula(e,t,r){try{const n=yC(t,this.compilationParams,e,this.buildSafeGetSymbolValue(r),this.compilationParams.evalContext.__originCellPosition);return D(n)?nr(n,bC):bC(n)}catch(e){return wr(e,"")}}getArrayFormulasBlockedBy(e,t){const r=new sC,n=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);r.addManyPositions(n);const o=[...n].filter(e=>!this.blockedArrayFormulas.has(e));return o.length&&r.deleteManyPositions(o),r.addMany(this.getCellsDependingOn(r)),r}nextRangesToUpdate=new sC;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new sC(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();const e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(const t of e){const{left:e,bottom:r,right:n,top:o}=t.zone;for(let s=e;s<=n;s++)for(let e=o;e<=r;e++){const r={sheetId:t.sheetId,col:s,row:e};if(this.nextRangesToUpdate.hasPosition(r))continue;const n=this.computeCell(r);n!==gC&&this.evaluatedCells.set(r,n)}}dC.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn("Maximum iteration reached while evaluating cells")}clearEvaluatedRanges(e){for(const t of e){const{left:e,bottom:r,right:n,top:o}=t.zone;for(let s=e;s<=n;s++)for(let e=o;e<=r;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:s,row:e})}}computeCell(e){const t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);const r=this.getters.getCell(e);if(void 0===r)return gC;const n=r.id,o={format:r.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(n)?fC:(this.cellsBeingComputed.add(n),r.isFormula?this.computeFormulaCell(e,r):cE(r,o,e))}catch(t){return t.value=t?.value||E.GenericError,t.message=t?.message||Cr,t.origin=e,hE(t)}finally{this.cellsBeingComputed.delete(n)}}computeAndSave(e){const t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){const r=yC(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!D(r)){const n=hE(vC(r),this.getters.getLocale(),t,e);return n.type===Nu.error&&(n.errorOriginPosition=r.errorOriginPosition??e),n}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,r);const n=r.length,o=r[0].length;if(0===o)return hE({value:0},this.getters.getLocale(),t);if(1===o&&1===n)return hE(vC(r[0][0]),this.getters.getLocale(),t);const s={top:e.row,bottom:e.row+o-1,left:e.col,right:e.col+n-1};return this.spreadingRelations.addRelation({resultZone:s,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,r),pC(n,o,this.checkCollision(e)),pC(n,o,this.spreadValues(e,r)),this.invalidatePositionsDependingOnSpread(e.sheetId,s),hE(vC(r[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){const r=this.getCellsDependingOn(function(e){const{top:t,left:r,bottom:n,right:o}=e;if(1===Es(e))return[];const s={top:t+1,bottom:n,left:r,right:r};if(o===r)return[s];const i={top:t,bottom:n,left:r+1,right:o};return t===n?[i]:[s,i]}(t).map(t=>({sheetId:e,zone:t})));r.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(r)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:r},n){const o=this.getters.getNumberCols(e),s=this.getters.getNumberRows(e),i=t+n.length<=o,a=r+n[0].length<=s;if(!i||!a){if(i)throw new A(v("Result couldn't be automatically expanded. Please insert more rows."));if(a)throw new A(v("Result couldn't be automatically expanded. Please insert more columns."));throw new A(v("Result couldn't be automatically expanded. Please insert more columns and rows."))}}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:r},n){if(0!==this.getters.getMergesInZone(e,{top:r,bottom:r+n[0].length-1,left:t,right:t+n.length-1}).length)throw new A(v("Merged cells found in the spill zone. Please unmerge cells before using array formulas."))}checkCollision(e){const{sheetId:t,col:r,row:n}=e;return(o,s)=>{const i={sheetId:t,col:o+r,row:s+n},a=this.getters.getCell(i);if(a?.content||this.getters.getEvaluatedCell(i).type!==Nu.empty)throw this.blockedArrayFormulas.add(e),new A(v("Array result was not expanded because it would overwrite data in %s.",Bo(i.col,i.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:r},n){return(o,s)=>{const i={sheetId:e,col:o+t,row:s+r},a=this.getters.getCell(i),l=hE(vC(n[o][s]),this.getters.getLocale(),a,i);l.type===Nu.error&&(l.errorOriginPosition=n[o][s].errorOriginPosition??i),this.evaluatedCells.set(i,l)}}invalidateSpreading(e){const t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let r=t.left;r<=t.right;r++)for(let n=t.top;n<=t.bottom;n++){const t={sheetId:e.sheetId,col:r,row:n},o=this.getters.getCell(t)?.content;o||this.evaluatedCells.delete(t)}const r=e.sheetId;this.invalidatePositionsDependingOnSpread(r,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(r,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return fC;this.symbolsBeingComputed.add(t);try{const r=e?.(t);return r||new C(v("Invalid formula"))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){const t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}}function pC(e,t,r){for(let n=0;n<e;++n)for(let e=0;e<t;++e)0===n&&0===e||r(n,e)}function bC(e){return null===e.value||void 0===e.value?{...e,value:0}:e}function vC(e){return"number"==typeof e.value&&Math.abs(e.value)>Number.MAX_VALUE?new _:bC(e)}function yC(e,t,r,n,o){return t.evalContext.__originCellPosition=o,t.evalContext.__originSheetId=r,e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,n,t.evalContext)}function EC(e,t=1){return t*(e+4)-4}function wC(e=100,t=100){return new OffscreenCanvas(e,t).getContext("2d")}function SC(e,t,r,n){return TC(e,FC(e,t,r,"wrap"===r?.wrapping?n-8:void 0),r).height+6}function CC(e,t=!1,r=!1){return`${r?"italic":""} ${t?"bold":""} ${e}px ${Z}`}function TC(e,t,r={},n="pt"){if(!t.length)return{width:0,height:0};const o=OC(r,n),s=t.map(t=>AC(e,t,o)),i=EC(s[0].height,t.length),a=Math.max(...s.map(e=>e.width));if(!r.rotation)return{height:i,width:a};const l=Math.abs(Math.cos(r.rotation)),c=Math.abs(Math.sin(r.rotation));return{width:a*l+i*c,height:c*a+l*i}}function IC(e,t,r={},n="pt"){return xC(e,t,OC(r,n),r.rotation)}function xC(e,t,r,n){const o=AC(e,t,r);if(!n)return o.width;const s=Math.abs(Math.cos(n)),i=Math.abs(Math.sin(n));return o.width*s+o.height*i}const RC={};function AC(e,t,r){if(RC[r]||(RC[r]={}),void 0===RC[r][t]){e.save(),e.font=r;const n=e.measureText(t);e.restore();const o=n.width,s=n.fontBoundingBoxAscent+n.fontBoundingBoxDescent;RC[r][t]={width:o,height:s}}return RC[r][t]}function OC(e,t="pt"){return`${e.italic?"italic ":""}${e.bold?"bold":"400"} ${("pt"===t?_C(e):e.fontSize)??q}px ${Z}`}function _C(e){return t=e?.fontSize||q,Math.round(96*t/72);var t}function DC(e,t,r,n){if(IC(e,t,n)<=r)return[t];const o=[];let s="";for(const i of t){IC(e,s+i,n)>r?(o.push(s),s=i):s+=i}return o.push(s),o}function FC(e,t,r,n){r||(r={}),ge(t)&&(t=be(t).label);const o=[],s=t.includes(Q)?t.split(Q):[t];for(const t of s){const s=t.includes(" ")?t.split(" "):[t];if(!n){o.push(t);continue}let i="",a=n;for(const t of s){const s=DC(e,t,n,r),l=s.pop(),c=IC(e,l,r);if(s.length)""!==i&&(o.push(i),i="",a=n),s.forEach(e=>{o.push(e)}),i=l,a=n-c;else{const t=""===i?l:" "+l,s=IC(e,t,r);s<=a?(i+=t,a-=s):(o.push(i),i=l,a=n-c)}}""!==i&&o.push(i)}return o}function NC(e){return e?e.toLowerCase():""}const MC=/([0-9\.]*)px/;function VC(e,t,r){let n=xC(e,t,e.font);if(n<=r)return t;const o=xC(e,"…",e.font);if(n<=o)return t;let s=t.length;for(;n>=r-o&&s-- >0;)n=xC(e,t=t.substring(0,s),e.font);return t+"…"}function LC(e,t,r,n=!1,o=!1,s=function(e){return Number(e.match(MC)?.[1])}(e.font)/10){if(e.fillText(t,r.x,r.y),!n&&!o)return;const i=e.measureText(t),a=i.width,l=i.actualBoundingBoxAscent+i.actualBoundingBoxDescent,c=i.fontBoundingBoxAscent+i.fontBoundingBoxDescent;let{x:u,y:h}=r,d=h,f=h;switch(e.textAlign){case"center":u-=a/2;break;case"right":u-=a}switch(e.textBaseline){case"top":f+=c-2*s,d+=c/2-s;break;case"middle":f+=c/2-s;break;case"alphabetic":f+=2*s,d-=3*s;break;case"bottom":f=h,d-=l/2-s/2}n&&(e.lineWidth=s,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+a,f),e.stroke()),o&&(e.lineWidth=s,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,d),e.lineTo(u+a,d),e.stroke())}const PC=new Id;PC.add("data_validation_checkbox",(e,t)=>{if(e.isCellValidCheckbox(t)){const r=!!e.getEvaluatedCell(t).value;return{svg:r?Ov:Rv,hoverSvg:r?Ov:Av,priority:2,horizontalAlign:"center",size:17,margin:2,position:t,type:"data_validation_checkbox",onClick:(e,t)=>{const n=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||!!n?.isFormula)return;const o=r?"FALSE":"TRUE";t.model.dispatch("UPDATE_CELL",{...e,content:o})}}}}),PC.add("data_validation_chip_icon",(e,t)=>{const r=e.getDataValidationChipStyle(t);if(r){const n=e.getCellComputedStyle(t);return{svg:Iv(r),hoverSvg:xv(r),priority:10,horizontalAlign:"right",size:_C(n),margin:4,position:t,onClick:(e,t)=>{const{col:r,row:n}=e;t.model.selection.selectCell(r,n),t.startCellEdition()},type:"data_validation_chip_icon"}}}),PC.add("data_validation_list_icon",(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){const n=e.getCellComputedStyle(t);return{svg:Cv(n),hoverSvg:(r=n,{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:r.textColor||U,path:"M15 15 h482 v482 h-482"},{fillColor:r.fillColor||"#fff",path:"M120 195 h270 l-135 130"}]}),priority:2,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const{col:r,row:n}=e;t.model.selection.selectCell(r,n),t.startCellEdition()},type:"data_validation_list_icon"}}var r}),PC.add("conditional_formatting",(e,t)=>{const r=e.getConditionalIcon(t);if(r){const n=e.getCellStyle(t);return{type:"conditional_formatting",svg:Dv[r].svg,priority:1,horizontalAlign:"left",size:_C(n),margin:4,position:t}}}),PC.add("pivot_collapse",(e,t)=>{if(!e.isSpillPivotFormula(t))return;const r=e.getPivotCellFromPosition(t),n=e.getPivotIdFromPosition(t);if("HEADER"===r.type&&n&&r.domain.length){const o=e.getPivotCoreDefinition(n),s=e.isDashboard(),i="COL"===r.dimension?o.columns:o.rows,a=!s&&r.domain.length!==i.length,l=(o.collapsedDomains?.[r.dimension]??[]).some(e=>Ae(e,r.domain)),c="ROW"===r.dimension?15*(r.domain.length-1):0;return{type:"pivot_collapse",priority:4,horizontalAlign:"left",size:a||!s&&"ROW"===r.dimension&&o.rows.length>1?12:0,margin:a?4+c:c,svg:a?_v(l,!1):void 0,hoverSvg:a?_v(l,!0):void 0,position:t,onClick:sf}}}),PC.add("pivot_dashboard_sorting",(e,t)=>{if(!e.isDashboard())return;if("MEASURE_HEADER"!==e.getPivotCellFromPosition(t).type)return;const r=e.getPivotCellSortDirection(t);if("asc"!==r&&"desc"!==r)return;const n=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${r}`,priority:5,horizontalAlign:"right",size:17,margin:2,svg:"asc"===r?(o=n,{name:"CARET_UP",width:512,height:512,paths:[{fillColor:o.textColor||U,path:"M120 325 h270 l-135 -130"}]}):Cv(n),position:t,onClick:void 0};var o});const kC=/"(#[0-9a-fA-F]{6})"/g;const UC=new h;function HC(){return!globalThis.Chart||!!globalThis.Chart.registry.plugins.get("chartShowValuesPlugin")}function BC(){if(globalThis.Chart)for(const e of UC.getAll())e.unregister(globalThis.Chart)}const zC=12,$C="#F3F2F1";function GC(e,t,r){const n=r??function(e){if(e instanceof HTMLCanvasElement){const t=e.getBoundingClientRect();return{width:t.width,height:t.height}}return{width:e.width,height:e.height}}(e),o="number"==typeof globalThis.devicePixelRatio?globalThis.devicePixelRatio:1;e.width=n.width*o,e.height=n.height*o;const s=e.getContext("2d");if(!s)throw new Error("Unable to retrieve 2D context from canvas");s.scale(o,o);const i=function(e,t,r){const n=t.maxValue,o=t.minValue,s=XC(t,"animated"),i=function(e,t){const r=t?25:0,n=e.height-20-r-10,o=e.width-60;let s,i;o>2*n?(s=2*n,i=n):(s=o,i=o/2);const a=r+10+(n-i)/2;return{x:30+(o-s)/2,y:a,width:s,height:i}}(e,t.title.text),a=i.width/6,l=s?(s-o.value)/(n.value-o.value):0,c={x:e.width/2,y:i.y+i.height-i.height/12};let u=80;i.height<300&&(u*=i.height/300);const h=i.width/2,d=t.gaugeValue?.label||"-";IC(r,d,{fontSize:u},"px")>h&&(u=function(e,t,r,n=.25){let o=1;if(r(o)>e)return o;if(r(t)<e)return t;let s=(o+t)/2,i=r(s),a=0;for(;Math.abs(i-e)>n&&a<20;)i>=e?t=(o+t)/2:o=(o+t)/2,s=(o+t)/2,i=r(s),a++;return s}(h,u,e=>IC(r,d,{fontSize:e},"px")));const f={x:i.x+a/2,y:i.y+i.height+zC},g={x:i.x+i.width-a/2,y:i.y+i.height+zC},m=Qb(t.background),p=function(e,t,r,n){const o=e.maxValue,s=e.minValue,i={x:t.x+t.width/2,y:t.y+t.height},a={fontSize:zC},l=[],c=[];for(const u of e.inflectionValues){const e=(u.value-s.value)/(o.value-s.value),h=IC(n,u.label,a,"px"),d=Math.PI-Math.PI*e,f=jC(d,t.height+6,i.x,i.y,h+2,zC),g=c.some(e=>YC(e,f))?zC:0;c.push(f),l.push({rotation:d,label:u.label,fontSize:zC,color:r,offset:g})}return l}(t,i,m,r);let b=0,v=0,y=0;t.title.text&&({width:v,height:y}=function(e,t,r,n="pt"){const o=AC(e,t,OC(r,n));if(!r.rotation)return o;const s=Math.abs(Math.cos(r.rotation)),i=Math.abs(Math.sin(r.rotation));return{width:o.width*s+o.height*i,height:o.height*s+o.width*i}}(r,t.title.text,{fontSize:z,...t.title},"px"));switch(t.title.align){case"right":b=e.width-v-B;break;case"center":b=(e.width-v)/2;break;default:b=B}return{width:e.width,height:e.height,title:{label:t.title.text??"",fontSize:t.title.fontSize??z,textPosition:{x:b,y:15+y/2},color:t.title.color??m,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:i,arcWidth:a,percentage:ae(l,0,1),color:WC(t)},inflectionValues:p,gaugeValue:{label:d,textPosition:c,fontSize:u,color:m},minLabel:{label:t.minValue.label,textPosition:f,fontSize:zC,color:m},maxLabel:{label:t.maxValue.label,textPosition:g,fontSize:zC,color:m}}}({...n,x:0,y:0},t,s);!function(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}(s,i),function(e,t){e.save();const r=t.gauge,n=r.rect.x+r.rect.width/2,o=r.rect.y+r.rect.height,s=r.rect.height-r.arcWidth/2;if(s<0)return;const i=1===r.percentage?0:Math.PI*(1+r.percentage);e.strokeStyle=$C,e.beginPath(),e.lineWidth=r.arcWidth,e.arc(n,o,s,i,0),e.stroke(),e.strokeStyle=r.color,e.beginPath(),e.arc(n,o,s,Math.PI,i),e.stroke(),e.restore()}(s,i),function(e,t){const{x:r,y:n,width:o,height:s}=t.gauge.rect;for(const i of t.inflectionValues){e.save(),e.translate(r+o/2-.5,n+s-.5),e.rotate(Math.PI/2-i.rotation),e.lineWidth=2,e.strokeStyle=Qb(t.backgroundColor)+"aa",e.beginPath(),e.moveTo(0,-(s-t.gauge.arcWidth)),e.lineTo(0,-s-3),e.stroke(),e.textAlign="center",e.font=`${i.fontSize}px ${Z}`,e.fillStyle=i.color;const a=-s-6-i.offset;e.fillText(i.label,0,a),e.restore()}}(s,i),function(e,t){for(const r of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign="center",e.fillStyle=r.color,e.font=`${r.fontSize}px ${Z}`,e.fillText(r.label,r.textPosition.x,r.textPosition.y),e.restore()}(s,i),function(e,t){e.save();const r=t.title;e.font=CC(r.fontSize,r.bold,r.italic),e.textBaseline="middle",e.fillStyle=r.color,e.fillText(r.label,r.textPosition.x,r.textPosition.y),e.restore()}(s,i)}function WC(e){const t=XC(e,"final");if(void 0===t)return $C;for(let r=0;r<e.inflectionValues.length;r++){const n=e.inflectionValues[r];if("<"===n.operator&&t<n.value)return e.colors[r];if("<="===n.operator&&t<=n.value)return e.colors[r]}return e.colors.at(-1)}function qC(e){return[{start:e.topLeft,end:e.topRight},{start:e.topRight,end:e.bottomRight},{start:e.bottomRight,end:e.bottomLeft},{start:e.bottomLeft,end:e.topLeft}]}function ZC(e,t){const r=e.start,n=e.end,o=t.start,s=t.end;function i(e,t,r){return(r.y-e.y)*(t.x-e.x)>(t.y-e.y)*(r.x-e.x)}return i(r,o,s)!==i(n,o,s)&&i(r,n,o)!==i(r,n,s)}function YC(e,t){const r=qC(e),n=qC(t);for(const e of r)for(const t of n)if(ZC(e,t))return!0;return!1}function jC(e,t,r,n,o,s){const i=Math.cos(e),a=Math.sin(e),l=i*t,c=a*t,u=a*(o/2),h=i*(o/2),d=i*(t+s),f=a*(t+s);return{bottomLeft:{x:l-u+r,y:n-(c+h)},bottomRight:{x:l+u+r,y:n-(c-h)},topRight:{x:d+u+r,y:n-(f-h)},topLeft:{x:d-u+r,y:n-(f+h)}}}function XC(e,t){return"animated"===t&&void 0!==e.animationValue?e.animationValue:e.gaugeValue?.value}const KC=globalThis.Path2D,QC=KC&&new KC("M8.6 4.8a.5.5 0 0 1 0 .75l-3.9 3.9a.5 .5 0 0 1 -.75 0l-3.8 -3.9a.5 .5 0 0 1 0 -.75l.4-.4a.5.5 0 0 1 .75 0l2.3 2.4v-5.7c0-.25.25-.5.5-.5h.6c.25 0 .5.25.5.5v5.8l2.3 -2.4a.5.5 0 0 1 .75 0z"),JC=KC&&new KC("M8.7 5.5a.5.5 0 0 0 0-.75l-3.8-4a.5.5 0 0 0-.75 0l-3.8 4a.5.5 0 0 0 0 .75l.4.4a.5.5 0 0 0 .75 0l2.3-2.4v5.8c0 .25.25.5.5.5h.6c.25 0 .5-.25.5-.5v-5.8l2.2 2.4a.5.5 0 0 0 .75 0z");const eT=.05;function tT(e,t){const r=e||"";return t&&r?" "+r:r}class rT{runtime;context;width;height;constructor({width:e,height:t},r){if(this.runtime=r,this.width=e,this.height=t,"undefined"==typeof OffscreenCanvas)throw new Error("OffscreenCanvas is not supported in this environment");const n=new globalThis.OffscreenCanvas(e,t).getContext("2d");if(!n)throw new Error("Unable to create scorecard measurement context");this.context=n}computeDesign(){const e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles();let r=0;if(this.title){let n,o;switch(({height:r,width:o}=this.getFullTextDimensions(this.title,t.title.font)),this.runtime.title.align){case"center":n=(this.width-o)/2;break;case"right":n=this.width-o-B;break;default:n=B}e.title={text:this.title,style:t.title,position:{x:n,y:10+r/2}}}const n=t.baselineArrow?.size??0;let{height:o,width:s}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(o=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);const i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width;let a;switch(this.runtime.baselineStyle?.align){case"right":a=this.width-B-i-s;break;case"left":a=B+n;break;default:a=(this.width-s-i+n)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:a,y:this.keyValue?this.height*(1-eT*(this.runtime.progressBar?1:2)):this.height-(this.height-r-o)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-n,y:e.baseline.position.y-(o+n)/2}})),e.baseline&&this.baselineDescr){const r={x:e.baseline.position.x+s,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:r}}let l=0;this.runtime.progressBar&&(l=.05*this.height,e.progressBar={position:{x:40,y:.9*this.height-o-l},dimension:{height:l,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});const{width:c,height:u}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),h=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width;let d;switch(this.runtime.keyValueStyle?.align){case"right":d=this.width-B-h-c;break;case"left":d=B;break;default:d=(this.width-c-h)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(B,d),y:.4*this.height+5+(r+u/2)/2}}),e.key&&this.keyDescr){const r={x:e.key.position.x+c,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:r}}return e}get title(){return this.runtime.title.text??""}get keyValue(){return this.runtime.keyValue}get keyDescr(){return tT(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return tT(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return Qb(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;const r=this.context.measureText(e);return{width:r.width,height:r.actualBoundingBoxAscent+r.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;const r=this.context.measureText(e);return{width:r.width,height:r.fontBoundingBoxAscent+r.fontBoundingBoxDescent}}getTextStyles(){const e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e);let r=this.runtime.baselineStyle?.fontSize??16;const n=Math.floor(.9*r);return this.runtime.progressBar&&(r/=1.5),{title:{font:CC(this.runtime.title.fontSize??14,this.runtime.title.bold,this.runtime.title.italic),color:this.runtime.title.color??this.secondaryFontColor},keyValue:{color:this.runtime.keyValueStyle?.textColor||this.runtime.fontColor,font:CC(e,this.runtime.keyValueStyle?.bold,this.runtime.keyValueStyle?.italic),strikethrough:this.runtime.keyValueStyle?.strikethrough,underline:this.runtime.keyValueStyle?.underline},keyDescr:{color:this.runtime.keyValueDescrStyle?.textColor||this.runtime.fontColor,font:CC(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:CC(r,this.runtime.baselineStyle?.bold,this.runtime.baselineStyle?.italic),strikethrough:this.runtime.baselineStyle?.strikethrough,underline:this.runtime.baselineStyle?.underline,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor},baselineDescr:{font:CC(n,this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:"neutral"===this.baselineArrow||this.runtime.progressBar?void 0:{size:this.keyValue?.8*r:0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}}async function nT(e,t,r){const n=(o=t.width,s=t.height,new OffscreenCanvas(o,s));var o,s;let i;if("chartJsConfig"in e){if(!globalThis.Chart)return console.log("Chart.js library is not loaded"),i;const t=HC();t||function(){if(globalThis.Chart&&!HC())for(const e of UC.getAll())e.register(globalThis.Chart)}();const r=re(e.chartJsConfig);if(r.plugins=[oT],!globalThis.Chart.registry.controllers.get(r.type))return console.log(`Chart of type "${r.type}" is not registered in Chart.js library.`),t||BC(),i;const o=new globalThis.Chart(n,r);try{i=await sT(n)}finally{o.destroy(),t||BC()}}else{if(!globalThis.OffscreenCanvas)throw new Error(`converting a ${r} chart to an image using OffscreenCanvas is not supported in this environment`);if("scorecard"===r){const r=function({width:e,height:t},r){return new rT({width:e,height:t},r).computeDesign()}(t,e);!function(e,t){const r=t.getContext("2d");if(!r)throw new Error("Unable to retrieve 2D context from canvas");const n="number"==typeof globalThis.devicePixelRatio?globalThis.devicePixelRatio:1;t.width=n*e.canvas.width,t.height=n*e.canvas.height,r.scale(n,n);const o=e.canvas.width-B;if(r.fillStyle=e.canvas.backgroundColor,r.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){r.font=e.title.style.font,r.fillStyle=e.title.style.color;const t=r.textBaseline;r.textBaseline="middle",r.fillText(VC(r,e.title.text,o-e.title.position.x),e.title.position.x,e.title.position.y),r.textBaseline=t}if(e.baseline&&(r.font=e.baseline.style.font,r.fillStyle=e.baseline.style.color,LC(r,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&KC){r.save(),r.fillStyle=e.baselineArrow.style.color,r.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);const t=e.baselineArrow.style.size/10;switch(r.scale(t,t),e.baselineArrow.direction){case"down":r.fill(QC);break;case"up":r.fill(JC)}r.restore()}if(e.baselineDescr){const t=e.baselineDescr;r.font=t.style.font,r.fillStyle=t.style.color,r.fillText(VC(r,t.text,o-t.position.x),t.position.x,t.position.y)}if(e.key&&(r.font=e.key.style.font,r.fillStyle=e.key.style.color,LC(r,VC(r,e.key.text,o-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){const t=e.keyDescr;r.font=e.keyDescr?.style.font??t.style.font,r.fillStyle=t.style.color,r.fillText(VC(r,t.text,o-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(r.fillStyle=e.progressBar.style.backgroundColor,r.beginPath(),r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),r.fill(),r.fillStyle=e.progressBar.style.color,r.beginPath(),e.progressBar.value>0)r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{const t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));r.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}r.fill()}}(r,n),i=await sT(n)}else"gauge"===r&&(GC(n,e,t),i=await sT(n))}return i}const oT={id:"customCanvasBackgroundColor",beforeDraw:e=>{const{ctx:t}=e;t.save(),t.globalCompositeOperation="destination-over",t.fillStyle="#ffffff",t.fillRect(0,0,e.width,e.height),t.restore()}};async function sT(e){const t=await async function(e){return"convertToBlob"in e?e.convertToBlob({type:"image/png"}):new Promise(t=>e.toBlob(t,"image/png"))}(e);if(t)return new Promise(e=>{const r=new FileReader;r.addEventListener("load",()=>{e(r.result)}),r.readAsDataURL(t)})}const iT={isValid:!0};const aT=["*","+","&"];function lT(e){switch(e.type){case"FUNCALL":const t=e.args.map(e=>lT(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":if(e.postfix){return(cT(e)?`(${lT(e.operand)})`:lT(e.operand))+e.value}const r=uT(e)?`(${lT(e.operand)})`:lT(e.operand);return e.value+r;case"ARRAY":return"{"+e.value.map(e=>e.map(e=>lT(e)).join(",")).join(";")+"}";case"BIN_OPERATION":const n=cT(e)?`(${lT(e.left)})`:lT(e.left),o=uT(e)?`(${lT(e.right)})`:lT(e.right);return n+e.value+o}}function cT(e){const t=e.value,r="left"in e?e.left:e.operand,n=r.value;return"BIN_OPERATION"===r.type&&mm[n]<mm[t]}function uT(e){const t=e.value,r="right"in e?e.right:e.operand,n=mm[r.value],o=mm[t];return"BIN_OPERATION"===r.type&&(n<o||n===o&&!aT.includes(t))}Ue(function(e){return"\n"+"\t".repeat(e)});const hT=["PIVOT.VALUE","PIVOT.HEADER","PIVOT"];const dT="0.00%";function fT(e){return class extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,r){super(t,r),this.getters=r.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){const r=`${e}-${t.map(e=>e.field+"="+e.value).join(",")}`;if(this.cache[r])return this.cache[r];const n=this.getMeasure(e),o=n.computedBy?this.computeMeasure(n,t):super.getPivotCellValueAndFormat(e,t);return n.format?this.cache[r]={...o,format:n.format}:this.cache[r]=o,this.cache[r]}computeMeasure(e,t){if(!e.computedBy)return{value:0};const{columns:r,rows:n}=super.definition;if(e.aggregator&&r.length+n.length!==t.length){const r=this.getValuesToAggregate(e,t),n=Wd[e.aggregator];if(!n)return{value:0};try{return n([r],this.getters.getLocale())}catch(t){return wr(t,e.aggregator.toUpperCase())}}const o=this.getters.getMeasureCompiledFormula(this.pivotId,e),s=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,o,e=>{const{columns:r,rows:n}=this.definition;if(r.find(t=>t.nameWithGranularity===e)){const{colDomain:r}=jw(this,t),n=r.findIndex(t=>t.field===e);return-1===n?new x:this.getPivotHeaderValueAndFormat(r.slice(0,n+1))}if(n.find(t=>t.nameWithGranularity===e)){const{rowDomain:r}=jw(this,t),n=r.findIndex(t=>t.field===e);return-1===n?new x:this.getPivotHeaderValueAndFormat(r.slice(0,n+1))}return this.getPivotCellValueAndFormat(e,t)});return D(s)?s[0][0]:s}getValuesToAggregate(e,t){const{rowDomain:r,colDomain:n}=jw(this,t),o=super.getExpandedTableStructure(),s=[];if(0===n.length&&r.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){const t=this.treeToLeafDomains(o.getColTree()),n=this.getSubTreeMatchingDomain(o.getRowTree(),r),i=this.treeToLeafDomains(n);for(const n of t)for(const t of i)s.push(this._getPivotCellValueAndFormat(e.id,r.concat(t).concat(n)));return s}if(r.length===this.definition.rows.length&&0===n.length){const t=o.getColTree(),i=this.getSubTreeMatchingDomain(t,n),a=this.treeToLeafDomains(i,n);for(const t of a)s.push(this._getPivotCellValueAndFormat(e.id,r.concat(t)));return s}if(r.length===this.definition.rows.length&&n.length&&n.length<this.definition.columns.length){const t=this.getSubTreeMatchingDomain(o.getColTree(),n),i=this.treeToLeafDomains(t,n);for(const t of i)s.push(this._getPivotCellValueAndFormat(e.id,r.concat(t)));return s}{const t=o.getRowTree(),i=this.getSubTreeMatchingDomain(t,r),a=this.treeToLeafDomains(i,r);for(const t of a)s.push(this._getPivotCellValueAndFormat(e.id,t.concat(n)));return s}}getSubTreeMatchingDomain(e,t,r=0){if(r>t.length)return[];if(t.length===r)return e;for(const n of e){const e=Kd(this.definition.getDimension(n.field),t[r]?.value);if(n.field===t[r]?.field&&n.value===e)return this.getSubTreeMatchingDomain(n.children,t,r+1)}return[]}treeToLeafDomains(e,t=[]){const r=[];for(const n of e){const e=this.definition.getDimension(n.field),o=[...t,{field:n.field,value:n.value,type:e.type}];0===n.children.length?r.push(o):r.push(...this.treeToLeafDomains(n.children,o))}return r}getMeasureDisplayValue(e,t){const r=this.getMeasure(e),n=this._getPivotCellValueAndFormat(e,t);if(!r.display||"no_calculations"===r.display.type||n.message)return n;const o=r.display.fieldNameWithGranularity;if(o&&!this.isFieldInPivot(o))return{value:E.NotAvailable,message:v('Field "%s" not found in pivot for measure display calculation',o)};try{const e=r.display;switch(e.type){case"%_of_grand_total":return this.asPercentOfGrandTotal(n,r);case"%_of_col_total":return this.asPercentOfColumnTotal(n,r,t);case"%_of_row_total":return this.asPercentOfRowTotal(n,r,t);case"%_of_parent_row_total":return this.asPercentOfParentRowTotal(n,r,t);case"%_of_parent_col_total":return this.asPercentOfParentColumnTotal(n,r,t);case"index":return this.asIndex(n,r,t);case"%_of_parent_total":return this.asPercentOfParentTotal(n,r,t,e);case"running_total":return this.asRunningTotal(n,r,t,e,"running_total");case"%_running_total":return this.asRunningTotal(n,r,t,e,"%_running_total");case"rank_asc":return this.asRank(n,r,t,e,"asc");case"rank_desc":return this.asRank(n,r,t,e,"desc");case"%_of":return this.asPercentOf(n,r,t,e);case"difference_from":return this.asDifferenceFrom(n,r,t,e);case"%_difference_from":return this.asDifferenceFromInPercent(n,r,t,e)}return n}catch(e){return wr(e,"COMPUTE_MEASURE_DISPLAY_VALUE")}}asPercentOfGrandTotal(e,t){const r=this.getGrandTotal(t.id);return 0===r?{value:E.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:dT}}asPercentOfRowTotal(e,t,r){const n=this.getRowTotal(t.id,r);return 0===n?{value:E.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:dT}}asPercentOfColumnTotal(e,t,r){const n=this.getColumnTotal(t.id,r);return 0===n?{value:E.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:dT}}asPercentOfParentRowTotal(e,t,r){const n=function(e,t){const{colDomain:r,rowDomain:n}=jw(e,t);return[...r,...n.slice(0,n.length-1)]}(this,r),o=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,n));return 0===o?{value:""}:{value:this.measureValueToNumber(e)/o,format:dT}}asPercentOfParentColumnTotal(e,t,r){const n=function(e,t){const{colDomain:r,rowDomain:n}=jw(e,t);return[...r.slice(0,r.length-1),...n]}(this,r),o=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,n));return 0===o?{value:""}:{value:this.measureValueToNumber(e)/o,format:dT}}asPercentOfParentTotal(e,t,r,n){const{fieldNameWithGranularity:o}=n;if(!o)return e;if(!eS(o,r))return{value:""};const s=function(e,t,r){let{rowDomain:n,colDomain:o}=jw(e,r);if("row"===tS(e,t)){const e=n.findIndex(e=>e.field===t);if(-1===e)return r;n=n.slice(0,e+1)}else{const e=o.findIndex(e=>e.field===t);if(-1===e)return r;o=o.slice(0,e+1)}return[...n,...o]}(this,o,r),i=this._getPivotCellValueAndFormat(t.id,s),a=this.measureValueToNumber(i);return 0===a?{value:""}:{value:this.measureValueToNumber(e)/a,format:dT}}asIndex(e,t,r){const n=this.measureValueToNumber(e),o=this.getRowTotal(t.id,r),s=this.getColumnTotal(t.id,r),i=this.getGrandTotal(t.id);return 0===o||0===s?{value:E.DivisionByZero}:{value:n*i/(s*o),format:void 0}}asRunningTotal(e,t,r,n,o){const{fieldNameWithGranularity:s}=n;if(!s)return e;const i="running_total"===o?this.runningTotal:this.runningTotalInPercent;let a=i[t.id]?.[s];a||(a=this.computeRunningTotal(t,s,o),i[t.id]||(i[t.id]={}),i[t.id][s]=a);const{rowDomain:l,colDomain:c}=jw(this,r),u=rS(c),h=rS(l),d=a[u]?.[h];return{value:d??"",format:"running_total"===o?e.format:dT}}asPercentOf(e,t,r,n){const{fieldNameWithGranularity:o,value:s}=n;if(void 0===s||!o)return e;if(!eS(o,r))return{value:""};const i=this.getComparisonValue(t,r,o,s),a=this.strictMeasureValueToNumber(e);return 0===i||"sameValue"===i&&0===a?{value:E.DivisionByZero}:!i||"sameValue"===i&&!a?{value:""}:"sameValue"===i?{value:1,format:dT}:void 0===a?{value:E.NullError}:{value:a/i,format:dT}}asDifferenceFrom(e,t,r,n){const{fieldNameWithGranularity:o,value:s}=n;if(void 0===s||!o)return e;if(!eS(o,r))return{value:""};const i=this.getComparisonValue(t,r,o,s)||0;return"sameValue"===i?{value:""}:{value:this.measureValueToNumber(e)-i,format:e.format}}asDifferenceFromInPercent(e,t,r,n){const{fieldNameWithGranularity:o,value:s}=n;if(void 0===s||!o)return e;if(!eS(o,r))return{value:""};const i=this.getComparisonValue(t,r,o,s),a=this.strictMeasureValueToNumber(e);return 0===i?{value:E.DivisionByZero}:i&&"sameValue"!==i?void 0===a?{value:E.NullError}:{value:(a-i)/i,format:dT}:{value:""}}asRank(e,t,r,n,o){const{fieldNameWithGranularity:s}=n;if(!s)return e;if(!eS(s,r))return{value:""};const i="asc"===o?this.rankAsc:this.rankDesc;let a=i[t.id]?.[s];a||(a=this.computeRank(t,s,o),i[t.id]||(i[t.id]={}),i[t.id][s]=a);const{rowDomain:l,colDomain:c}=jw(this,r),u=rS(c),h=rS(l),d=a[u]?.[h];return{value:d??""}}computeRank(e,t,r){const n={},o=tS(this,t),s="row"===o?"column":"row";let i=this.getPivotValueCells(e.id);"column"===o&&(i=or(i));for(const a of i){const i=rS(Xw(this,s,a[0].domain)),l=a.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:Xw(this,o,t.domain)})).filter(e=>eS(t,e.rowDomain)),c=Object.groupBy(l,e=>oS(e.rowDomain,t));for(const e in c)c[e]=Ye(c[e]||[],e=>e.value).filter(e=>void 0!==e.value).sort((e,t)=>"asc"===r?e.value-t.value:t.value-e.value);n[i]={};for(const e of l){const r=rS(Xw(this,o,e.domain)),s=c[oS(e.rowDomain,t)];if(!s)continue;const a=s.findIndex(t=>t.value===e.value);-1!==a&&(n[i][r]=a+1)}}return"row"===o?n:je(n)}computeRunningTotal(e,t,r){const n={},o=tS(this,t),s="row"===o?"column":"row";let i=this.getPivotValueCells(e.id);"column"===o&&(i=or(i));for(const a of i){const i=rS(Xw(this,s,a[0].domain));n[i]={};const l={},c=a.map(t=>({...t,rowDomain:Xw(this,o,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>eS(t,e.rowDomain));for(const e of c){const r=rS(e.rowDomain),o=sS(e.rowDomain,t),s=(l[o]||0)+e.value;l[o]=s,n[i][r]=s}if("%_running_total"===r)for(const e of c){const r=e.rowDomain,o=rS(r),s=sS(r,t),a=n[i][o]||0,c=l[s];n[i][o]=c?a/c:void 0}}return"row"===o?n:je(n)}getGrandTotal(e){const t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){const r=jw(this,t).rowDomain,n=this._getPivotCellValueAndFormat(e,r);return this.measureValueToNumber(n)}getColumnTotal(e,t){const r=jw(this,t).colDomain,n=this._getPivotCellValueAndFormat(e,r);return this.measureValueToNumber(n)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,r,n){const o=n===Yw||"(next)"===n?function(e,t,r,n){const o=tS(e,r),s="row"===o?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),i=Qw(Xw(e,o,t),s,r),a=i?.map(e=>e.value)??[],l=function(e,t){const r=t.find(t=>t.field===e);return r?.value}(r,t);if(void 0===l)return;const c=a.indexOf(l);if(void 0===l||-1===c)return;return Jw(t,r,a[ae(c+(n===Yw?-1:1),0,a.length-1)])}(this,t,r,n):Jw(t,r,n);if(Ae(o,t))return"sameValue";if(!o||!function(e,t){for(const r of t)if(void 0===e.definition.rows.find(e=>e.nameWithGranularity===r.field)&&void 0===e.definition.columns.find(e=>e.nameWithGranularity===r.field))return!1;const{rowDomain:r,colDomain:n}=jw(e,t);return Kw(r,e.getExpandedTableStructure().getRowTree())&&Kw(n,e.getExpandedTableStructure().getColTree())}(this,o))throw new x;const s=this._getPivotCellValueAndFormat(e.id,o);return this.strictMeasureValueToNumber(s)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>"VALUE"===t.type&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if("number"==typeof e.value)return e.value;if(!e.value)return 0;throw new Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if("number"==typeof e.value)return e.value;if(e.value)throw new Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){const e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){const e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;const t=this.definition.sortedColumn.measure;(function(e,t){try{if(!t.getMeasure(e.measure))return!1;const r=t.definition.columns;for(let n=0;n<e.domain.length;n++){if(r[n].nameWithGranularity!==e.domain[n].field)return!1;const o=t.getPossibleFieldValues(r[n]).map(e=>e.value);if(!(o.includes(e.domain[n].value)||null===e.domain[n].value&&o.includes("")))return!1}return!0}catch(e){return!1}})(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}}const gT=["ADD_PIVOT","UPDATE_PIVOT","REMOVE_PIVOT"];function mT(e){return gT.includes(e.type)}const pT=new Id;pT.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;let r=Math.abs(e.current).toString();r="0".repeat(Math.max(e.numberPostfixLength-r.length,0))+r;const n=`${e.prefix}${r}`;return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:n},tooltip:{props:{content:n}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t,r)=>{e.current+=e.increment;const n=e.current.toString(),o=r.getLocale(),s=Xr(e.current,{format:t.cell?.format,locale:o});return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:n},tooltip:n?{props:{content:s}}:void 0}}}).add("DATE_INCREMENT_MODIFIER",{apply:(e,t,r)=>{const n=Zt(e.current,r.getLocale());n.setFullYear(n.getFullYear()+e.increment.years||0),n.setMonth(n.getMonth()+e.increment.months||0),n.setDate(n.getDate()+e.increment.days||0);const o=bt(n);e.current=o;const s=r.getLocale(),i=Xr(o,{format:t.cell?.format,locale:s});return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:o.toString()},tooltip:o?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,r)=>{const n=t.cell?.content||"",o={locale:r.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:n},tooltip:n?{props:{content:t.cell?cE(t.cell,o).formattedValue:""}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,r,n)=>{e.current+=e.increment;let o=0,s=0;switch(n){case"up":o=0,s=-e.current;break;case"down":o=0,s=e.current;break;case"left":o=-e.current,s=0;break;case"right":o=e.current,s=0}const i=t.cell;if(!i||!i.isFormula)return{cellData:{}};const a=t.sheetId,l=r.getTranslatedCellFormula(a,o,s,i.compiledFormula.tokens);return{cellData:{border:t.border,style:t.style,format:i.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const bT=new Id,vT=/(\d+)$/,yT=/^(.*\D+)/,ET=/^(.*\D+)(\d+)$/,wT=/^0*/;function ST(e,t,r){let n=[],o=!1;for(const s of t){s===e&&(o=!0);const t=void 0===s||s.isFormula?void 0:cE(s,{locale:xr,format:s.format});if(t&&r(t))n.push(t);else{if(o)return n;n=[]}}return n}function CT(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let r=e[0];for(let n=1;n<e.length;n++){const o=e[n];t.push(o-r),r=o}return t.reduce((e,t)=>e+t,0)/t.length}(e)*e.length),t}function TT(e){if(e.length<2)return 1;const t=e.map(e=>Zt(e,xr)),r=function(e){if(e.length<2)return[{years:0,months:0,days:0}];const t=e.map((t,r)=>{if(0===r)return{years:0,months:0,days:0};const n=Qe.fromTimestamp(e[r-1].getTime()),o=It(n,t),s=Ct(n,t)%12;n.setFullYear(n.getFullYear()+o),n.setMonth(n.getMonth()+s);return{years:o,months:s,days:Tt(n,t)}});return t.slice(1)}(t),n=(o=r).length<2?o[0]||{years:0,months:0,days:0}:o.every(e=>e.years===o[0].years&&e.months===o[0].months&&e.days===o[0].days)?o[0]:void 0;var o;if(void 0===n)return;const s=1===Object.values(n).filter(e=>0!==e).length,i=Object.values(n).every(e=>0===e);if(!s||i){const r=t.map((e,r)=>{if(0===r)return 0;const n=t[r-1];return Math.floor(e.getTime())-Math.floor(n.getTime())}).slice(1);if(r.every(e=>e===r[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}bT.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&on(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&cE(e,{locale:xr}).type===Nu.text&&ET.test(e.content),generateRule:(e,t,r)=>{const n=parseInt(e.content.match(vT)[0]),o=e.content.match(yT)[0],s=ST(e,t,e=>e.type===Nu.text&&ET.test(e.value)).filter(e=>o===(e.value??"").toString().match(yT)[0]).map(e=>(e.value??"").toString().match(vT)[0]),i=s.reduce((e,t)=>{const r=t.match(wT)[0].length;return r>e[1]?[t,r]:e},[s[0],0]),a=i[1]?i[0].length:0;let l=CT(s.map(e=>parseInt(e)));return["up","left"].includes(r)&&1===s.length&&(l=-l),{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:o,current:n,increment:l,numberPostfixLength:a}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&cE(e,{locale:xr}).type===Nu.text,generateRule:()=>({type:"COPY_MODIFIER"}),sequence:20}).add("update_formula",{condition:e=>e.isFormula,generateRule:(e,t)=>({type:"FORMULA_MODIFIER",increment:t.length,current:0}),sequence:30}).add("increment_dates",{condition:(e,t)=>!e.isFormula&&cE(e,{locale:xr}).type===Nu.number&&!!e.format&&on(e.format),generateRule:(e,t)=>{const r=TT(ST(e,t,e=>e.type===Nu.number&&!!e.format&&on(e.format)).map(e=>Number(e.value)));if(void 0===r)return{type:"COPY_MODIFIER"};const n=cE(e,{locale:xr});return"object"==typeof r?{type:"DATE_INCREMENT_MODIFIER",increment:r,current:n.type===Nu.number?n.value:0}:{type:"INCREMENT_MODIFIER",increment:r,current:n.type===Nu.number?n.value:0}},sequence:25}).add("increment_number",{condition:e=>!e.isFormula&&cE(e,{locale:xr}).type===Nu.number,generateRule:(e,t,r)=>{const n=ST(e,t,e=>e.type===Nu.number&&!on(e.format||"")).map(e=>Number(e.value));let o=CT(n);["up","left"].includes(r)&&1===n.length&&(o=-o);const s=cE(e,{locale:xr});return{type:"INCREMENT_MODIFIER",increment:o,current:s.type===Nu.number?s.value:0}},sequence:40});class IT{cells;getters;index=0;direction;constructor(e,t,r){this.cells=e,this.getters=t,this.direction=r}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:r,tooltip:n}=pT.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:r,tooltip:n,origin:{col:e.data.col,row:e.data.row}}}}const xT=new Set(["HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","UNFOLD_HEADER_GROUP","UNGROUP_HEADERS","FOLD_HEADER_GROUP","FOLD_ALL_HEADER_GROUPS","UNFOLD_ALL_HEADER_GROUPS","FOLD_HEADER_GROUPS_IN_ZONE","UNFOLD_HEADER_GROUPS_IN_ZONE","CREATE_TABLE","UPDATE_TABLE","UPDATE_FILTER","REMOVE_TABLE","RESIZE_TABLE","CREATE_TABLE_STYLE","REMOVE_TABLE_STYLE"]);function RT(e){return xT.has(e.type)}const AT=new Id,OT=new Id;function _T(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return Ds(e.rootCommand)?function(e,t){if(!t)return;if(!AT.contains(t.type))return;return AT.get(t.type)(e,t)}(t,e.rootCommand):function(e,t,r){if(!OT.contains(t.type))return;return OT.get(t.type)(e,t,r)}(t,e.rootCommand,e.commands)}class DT{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,$t(e.value)])}isValuePresent(e,t){const r=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(r)}isHeaderPresent(e){const t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){const r=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(r)}trackHeader(e){const t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}}const FT={type:"bar",title:{},stacked:!1,dataSetsHaveTitle:!1,dataSets:[],legendPosition:"top",humanize:!0};function NT(e){const t=function(e){const t={};if(!e)return t;e.bold&&(t["font-weight"]="bold");e.italic&&(t["font-style"]="italic");e.fontSize&&(t["font-size"]=`${e.fontSize}px`);if(e.strikethrough||e.underline){let r=e.strikethrough?"line-through":"";r=e.underline?r+" underline":r,t["text-decoration"]=r}e.textColor&&(t.color=e.textColor);return t}(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function MT(e){let t="";for(const r in e)e[r]&&(t+=`${r}:${e[r]}; `);return t}var VT;function LT(e,t){const r=new Set(t.map(e=>e.left)),n=new Set(t.map(e=>e.right)),o=new Set(t.map(e=>e.top)),s=new Set(t.map(e=>e.bottom)),i=1===o.size&&1===s.size||1===r.size&&1===n.size?function(e){return e.reduce((e,t)=>{const r=e.length;for(let n=0;n<r;n++)if(as(e[n],t))return e[n]=ns(e[n],t),e;return e[r]=t,e},[])}(t):[t[t.length-1]],a=i.map(e=>ds(e)).flat();return{sheetId:e,zones:t,clippedZones:i,columnsIndexes:[...new Set(a.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(a.map(e=>e.row))].sort((e,t)=>e-t)}}!function(e){e.PlainText="text/plain",e.Html="text/html",e.Image="image"}(VT||(VT={}));const PT={figureHandlers:new Id,cellHandlers:new Id},kT=5242880;const UT={filterType:"criterion",type:"none",values:[]};function HT(e){return 20+120*Math.exp(-.035*(e-1))}class BT{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,r,n,o,s){if(this.getters=e,this.sheetId=t,this.boundaries=r,n.width<0||n.height<0)throw new Error("Viewport size cannot be negative");this.viewportWidth=n.height&&n.width,this.viewportHeight=n.width&&n.height,this.top=r.top,this.bottom=r.bottom,this.left=r.left,this.right=r.right,this.offsetX=s.x,this.offsetY=s.y,this.canScrollVertically=o.canScrollVertically,this.canScrollHorizontally=o.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:r}=this.getters.getColDimensions(this.sheetId,e),{end:n}=this.getters.getRowDimensions(this.sheetId,t);let o=r-this.offsetCorrectionX;this.canScrollHorizontally&&(o=Math.max(o,this.viewportWidth));let s=n-this.offsetCorrectionY;return this.canScrollVertically&&(s=Math.max(s,this.viewportHeight),n+46>s&&!this.getters.isReadonly()&&(s+=46)),{width:o,height:s}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX+this.snapCorrection.x,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY+this.snapCorrection.y,this.top)}adjustPosition(e){const t=this.sheetId,r=this.getters.getMainCellPosition({sheetId:t,...e}),{col:n,row:o}=this.getters.getNextVisibleCellPosition(r);ls(n,this.boundaries.top,this.boundaries)&&this.adjustPositionX(n),ls(this.boundaries.left,o,this.boundaries)&&this.adjustPositionY(o)}adjustPositionX(e){const t=this.sheetId,{start:r,end:n}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<n?this.offsetX=n-this.viewportWidth:this.offsetX+this.offsetCorrectionX>r&&(this.offsetX=r-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){const t=this.sheetId,{start:r,end:n}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<n?this.offsetY=n-this.viewportHeight:this.offsetY+this.offsetCorrectionY>r&&(this.offsetY=r-this.offsetCorrectionY),this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetX!==e||this.canScrollVertically&&this.offsetY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){const t=os(e,this),r=this.snapCorrection.x,n=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,t.left)+this.offsetCorrectionX-(this.left!==t.left?r:0),y:this.getters.getColRowOffset("ROW",this.top,t.top)+this.offsetCorrectionY-(this.top!==t.top?n:0),width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1)-(this.left===t.left?r:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1)-(this.top===t.top?n:0),this.viewportHeight)}}}getFullRect(e){const t=os(e,this.boundaries),r=this.snapCorrection.x,n=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,e.left)+this.offsetCorrectionX-r,y:this.getters.getColRowOffset("ROW",this.top,e.top)+this.offsetCorrectionY-n,width:this.getters.getColRowOffset("COL",e.left,e.right+1),height:this.getters.getColRowOffset("ROW",e.top,e.bottom+1)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,r=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;const n=this.sheetId,o=this.getters.getNumberHeaders(n,e);let s=r,i=o;for(;s<=i&&s!==o&&-1!==i;){const o=Math.floor((s+i)/2),a=this.getters.getColRowOffset(e,r,o),l=this.getters.getHeaderSize(n,e,o);if(t>=a&&t<a+l)return o;t>=a+l?s=o+1:i=o-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetY>e&&(this.offsetY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){this.left=this.searchHeaderIndex("COL",this.offsetX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",Math.max(this.viewportWidth+this.snapCorrection.x-.1),this.left)),this.viewportWidth&&(-1===this.left&&(this.left=this.boundaries.left),-1===this.right&&(this.right=this.boundaries.right))}adjustViewportZoneY(){this.top=this.searchHeaderIndex("ROW",this.offsetY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",Math.max(this.viewportHeight+this.snapCorrection.y-.1,0),this.top)),this.viewportHeight&&(-1===this.top&&(this.top=this.boundaries.top),-1===this.bottom&&(this.bottom=this.boundaries.bottom))}get snapCorrection(){return{x:Math.abs(this.offsetX-this.getters.getColRowOffset("COL",this.boundaries.left,Math.max(0,this.left))),y:Math.abs(this.offsetY-this.getters.getColRowOffset("ROW",this.boundaries.top,Math.max(0,this.top)))}}}const zT=(new h).add("settings",class extends Mw{static getters=["getLocale"];locale=xr;allowDispatch(e){return"UPDATE_LOCALE"===e.type?lc(e.locale)?"Success":"InvalidLocale":"Success"}handle(e){if("UPDATE_LOCALE"===e.type){const t=this.locale,r=e.locale;this.history.update("locale",r),this.changeCellsDateFormatWithLocale(t,r)}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(const r of this.getters.getSheetIds())for(const[n,o]of Object.entries(this.getters.getCells(r))){let r;if(o.format===e.dateFormat&&(r=t.dateFormat),o.format===e.timeFormat&&(r=t.timeFormat),o.format===fc(e)&&(r=fc(t)),r){const{col:e,row:t,sheetId:o}=this.getters.getCellPosition(n);this.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:o,format:r})}}}import(e){this.locale=e.settings?.locale??xr}export(e){e.settings={locale:this.locale}}}).add("sheet",class extends Mw{static getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","doesHeaderExist","doesHeadersExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","getSheetSize","getSheetZone","getPaneDivisions","checkZonesExistInSheet","getCommandZones","getUnboundedZone","checkElementsIncludeAllNonFrozenHeaders","getDuplicateSheetName"];sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if("Success"!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?"NotEnoughSheets":"Success";case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"DUPLICATE_SHEET":return this.sheets[e.sheetIdTo]?"DuplicatedSheetId":this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?"DuplicatedSheetName":"Success";case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),"Success"}catch(e){return"WrongSheetMove"}case"RENAME_SHEET":return this.isRenameAllowed(e);case"COLOR_SHEET":return!e.color||pp(e.color)?"Success":"InvalidColor";case"DELETE_SHEET":return this.getVisibleSheetIds().length>1?"Success":"NotEnoughSheets";case"ADD_COLUMNS_ROWS":return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?"InvalidQuantity":"Success":"InvalidHeaderIndex";case"REMOVE_COLUMNS_ROWS":{const t=qe(e.elements),r=We(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,r)?"InvalidHeaderIndex":this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?"NotEnoughElements":"Success"}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return"Success"}}beforeHandle(e){if("REMOVE_COLUMNS_ROWS"===e.type)"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements])}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);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("sheetIdsMapName",sp(t.name),t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.newName);break;case"COLOR_SHEET":this.history.update("sheets",e.sheetId,"color",e.color);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"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"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){for(const t of e.sheets)this.sheetIdsMapName[sp(t.name)]=t.id;for(const t of e.sheets){const e=t.name||"Sheet"+(Object.keys(this.sheets).length+1),{colNumber:r,rowNumber:n}=this.getImportedSheetSize(t),o={id:t.id,name:e,numberOfCols:r,rows:ep(n),areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(o.id),this.sheets[o.id]=o}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(Se).map(e=>{const t=this.sheets[e],r={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(r.panes=t.panes),r})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}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}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[sp(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,r){return"COL"===t?r>=0&&r<this.getNumberCols(e):r>=0&&r<this.getNumberRows(e)}doesHeadersExist(e,t,r){return r.every(r=>this.doesHeaderExist(e,t,r))}getCell({sheetId:e,col:t,row:r}){const n=this.tryGetSheet(e),o=n?.rows[r]?.cells[t];if(void 0!==o)return this.getters.getCellById(o)}getColsZone(e,t,r){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:r}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(Se)}getRowsZone(e,t,r){return{top:t,bottom:r,left:0,right:this.getSheet(e).numberOfCols-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}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){return np(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(void 0===t.bottom||void 0===t.right)return t;const r=0===t.left&&t.right===this.getNumberCols(e)-1,n=0===t.top&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:n?void 0:t.bottom,right:r&&!n?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,r){const n={...this.getPaneDivisions(e)};"COL"===r?n.xSplit=t:"ROW"===r&&(n.ySplit=t),this.history.update("sheets",e,"panes",n)}checkElementsIncludeAllNonFrozenHeaders(e,t,r){const n=this.getters.getPaneDivisions(e),o="ROW"===t?n.ySplit:n.xSplit,s=this.getters.getNumberHeaders(e,t);if(!o)return!1;return De(r,le(o,s))}getCommandZones(e){const t=[];return"zone"in e&&t.push(e.zone),"target"in e&&t.push(...e.target),"ranges"in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),"col"in e&&void 0!==e.col&&"row"in e&&void 0!==e.row&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Qo))return"InvalidRange";if(t.length){const r=this.getSheetZone(e);return t.every(e=>cs(e,r))?"Success":"TargetOutOfSheet"}return"Success"}updateCellPosition(e){const{sheetId:t,cellId:r,col:n,row:o}=e;r?this.setNewPosition(r,t,n,o):this.clearPosition(t,n,o)}setNewPosition(e,t,r,n){const o=this.cellPosition[e];o&&this.clearPosition(t,o.col,o.row),this.history.update("cellPosition",e,{row:n,col:r,sheetId:t}),this.history.update("sheets",t,"rows",n,"cells",r,e)}clearPosition(e,t,r){const n=this.sheets[e]?.rows[r].cells[t];n&&(this.history.update("cellPosition",n,void 0),this.history.update("sheets",e,"rows",r,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}createSheet(e,t,r,n,o){const s={id:e,name:t,numberOfCols:r,rows:ep(n),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},i=this.orderedSheetIds.slice();i.splice(o,0,s.id);const a=this.sheets;return this.history.update("orderedSheetIds",i),this.history.update("sheets",Object.assign({},a,{[s.id]:s})),s}moveSheet(e,t){const r=this.orderedSheetIds.slice(),n=r.findIndex(t=>t===e),o=r.splice(n,1),s=this.findIndexOfTargetSheet(n,t);r.splice(s,0,o[0]),this.history.update("orderedSheetIds",r)}findIndexOfTargetSheet(e,t){for(;0!==t&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(0===t)return e;throw new Error("There is not enough visible sheets")}checkSheetName(e){const t=this.getters.tryGetSheetName(e.sheetId),r="RENAME_SHEET"===e.type?e.newName:e.name;if(void 0!==t&&r===t)return"UnchangedSheetName";const{orderedSheetIds:n,sheets:o}=this,s=r&&r.trim().toLowerCase();return n.find(t=>ip(o[t]?.name,s)&&t!==e.sheetId)?"DuplicatedSheetName":X.test(s)?"ForbiddenCharactersInSheetName":"Success"}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?"WrongSheetPosition":"Success"}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?"Success":"InvalidFreezeQuantity"}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?"Success":"InvalidFreezeQuantity"}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const r of t)if(r.top<e.quantity&&e.quantity<=r.bottom)return"MergeOverlap";return"Success"}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const r of t)if(r.left<e.quantity&&e.quantity<=r.right)return"MergeOverlap";return"Success"}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):"MissingSheetName"}renameSheet(e,t){const r=e.name;this.history.update("sheets",e.id,"name",t.trim());const n=Object.assign({},this.sheetIdsMapName);delete n[sp(r)],n[sp(t)]=e.id,this.history.update("sheetIdsMapName",n)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t,r){const n=re(this.getSheet(e));n.id=t,n.name=r;for(let e=0;e<=n.numberOfCols;e++)for(let t=0;t<=n.rows.length;t++)n.rows[t]&&(n.rows[t].cells[e]=void 0);const o=this.orderedSheetIds.slice(),s=o.indexOf(e);o.splice(s+1,0,n.id),this.history.update("orderedSheetIds",o),this.history.update("sheets",Object.assign({},this.sheets,{[n.id]:n}));for(const t of Object.values(this.getters.getCells(e))){const{sheetId:e,col:r,row:o}=this.getCellPosition(t.id),s=this.getters.getCellStyle({sheetId:e,col:r,row:o});this.dispatch("UPDATE_CELL",{sheetId:n.id,col:r,row:o,content:t.content,format:t.format,style:s})}const i=Object.assign({},this.sheetIdsMapName);i[sp(n.name)]=n.id,this.history.update("sheetIdsMapName",i)}getDuplicateSheetName(e){return op(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){const t=e.name,r=Object.assign({},this.sheets);delete r[e.id],this.history.update("sheets",r);const n=this.orderedSheetIds.slice(),o=n.indexOf(e.id);n.splice(o,1),this.history.update("orderedSheetIds",n);const s=Object.assign({},this.sheetIdsMapName);delete s[sp(t)],this.history.update("sheetIdsMapName",s)}removeColumns(e,t){t.sort((e,t)=>t-e);for(const r of t)this.moveCellOnColumnsDeletion(e,r);const r=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",r-t.length);const n=t.filter(t=>t<e.panes.xSplit).length;n&&this.setPaneDivisions(e.id,e.panes.xSplit-n,"COL")}removeRows(e,t){t.sort((e,t)=>t-e);for(const r of ce(t)){const t=r[r.length-1],n=r[0];this.moveCellOnRowsDeletion(e,t,n),this.updateRowsStructureOnDeletion(e,t,n)}const r=t.filter(t=>t<e.panes.ySplit).length;r&&this.setPaneDivisions(e.id,e.panes.ySplit-r,"ROW")}addColumns(e,t,r,n){const o="before"===r?t:t+1;this.moveCellsOnAddition(e,o,n,"columns");const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s+n),o<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+n,"COL")}addRows(e,t,r,n){const o="before"===r?t:t+1;this.addEmptyRows(e,n),this.moveCellsOnAddition(e,o,n,"rows"),o<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+n,"ROW")}moveCellOnColumnsDeletion(e,t){this.dispatch("CLEAR_CELLS",{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let r=0;r<e.rows.length;r++){const n=e.rows[r];for(const o in n.cells){const s=Number(o),i=n.cells[o];i&&s>t&&this.setNewPosition(i,e.id,s-1,r)}}}moveCellsOnAddition(e,t,r,n){const o=[];for(let s=0;s<e.rows.length;s++){const i=e.rows[s];if("rows"!==n||s>=t)for(const a in i.cells){const l=Number(a),c=i.cells[a];c&&("rows"===n||l>=t)&&o.push({sheetId:e.id,cellId:c,col:l+("columns"===n?r:0),row:s+("rows"===n?r:0),type:"UPDATE_CELL_POSITION"})}}for(const e of o.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,r){this.dispatch("CLEAR_CELLS",{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:r}]});const n=r-t+1;for(let t=0;t<e.rows.length;t++){const o=e.rows[t];if(t>r)for(const r in o.cells){const s=Number(r),i=o.cells[r];i&&this.setNewPosition(i,e.id,s,t-n)}}}updateRowsStructureOnDeletion(e,t,r){const n=[],o=e.rows.map(e=>e.cells).reverse();for(const s in e.rows){const e=Number(s);e>=t&&e<=r||n.push({cells:o.pop()})}this.history.update("sheets",e.id,"rows",n)}addEmptyRows(e,t){const r=e.rows.slice();for(let e=0;e<t;e++)r.push({cells:{}});this.history.update("sheets",e.id,"rows",r)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(Ho);let r=e.rowNumber,n=e.colNumber;for(const{col:e,row:o}of t)r=Math.max(r,o+1),n=Math.max(n,e+1);return{rowNumber:r,colNumber:n}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?"InvalidSheetId":"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?"DuplicatedSheetId":"Success"}checkZonesAreInSheet(e){return"sheetId"in e?"ranges"in e&&e.ranges.some(e=>""!==e._sheetId&&!this.getters.tryGetSheet(e._sheetId))?"InvalidSheetId":this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):"Success"}}).add("header grouping",class extends Mw{static getters=["getHeaderGroups","getGroupsLayers","getVisibleGroupLayers","getHeaderGroup","getHeaderGroupsInZone","isGroupFolded","isRowFolded","isColFolded"];groups={};allowDispatch(e){switch(e.type){case"GROUP_HEADERS":{const{start:t,end:r,sheetId:n}=e;if(!this.getters.tryGetSheet(n))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,r]))return"InvalidHeaderGroupStartEnd";if(t>r)return"InvalidHeaderGroupStartEnd";if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,r))return"HeaderGroupAlreadyExists";break}case"UNGROUP_HEADERS":{const{start:t,end:r,sheetId:n}=e;if(!this.getters.tryGetSheet(n))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,r]))return"InvalidHeaderGroupStartEnd";if(t>r)return"InvalidHeaderGroupStartEnd";break}case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUP":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return"UnknownHeaderGroup";if(le(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(r=>r>=t.start&&r<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,r)))return"NotEnoughElements"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("groups",e.sheetId,{ROW:[],COL:[]});break;case"GROUP_HEADERS":this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case"UNGROUP_HEADERS":this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case"DUPLICATE_SHEET":{const t=re(this.groups[e.sheetId]);this.history.update("groups",e.sheetIdTo,t);break}case"DELETE_SHEET":{const t={...this.groups};delete t[e.sheetId],this.history.update("groups",t);break}case"ADD_COLUMNS_ROWS":const t=Re(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case"REMOVE_COLUMNS_ROWS":this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case"UNFOLD_HEADER_GROUP":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case"FOLD_HEADER_GROUP":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case"UNFOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const r of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,r);break}case"FOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const r of t)this.foldHeaderGroup(e.sheetId,e.dimension,r);break}case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":{const t="UNFOLD_HEADER_GROUPS_IN_ZONE"===e.type?"unfold":"fold",r=this.getGroupsLayers(e.sheetId,e.dimension);"fold"===t&&r.reverse();const n=r.flat(),o="ROW"===e.dimension?e.zone.top:e.zone.left,s="ROW"===e.dimension?e.zone.bottom:e.zone.right,i=new Set;for(let e=o;e<=s;e++){const r=n.filter(t=>t.start-1<=e&&e<=t.end);for(const e of r)if(!("fold"===t&&e.isFolded||"unfold"===t&&!e.isFolded)){i.add(e);break}}for(const r of i)"unfold"===t?this.unfoldHeaderGroup(e.sheetId,e.dimension,r):this.foldHeaderGroup(e.sheetId,e.dimension,r);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,r,n){return this.getHeaderGroups(e,t).find(e=>e.start===r&&e.end===n)}getHeaderGroupsInZone(e,t,r){return this.getHeaderGroups(e,t).filter(e=>{const n="ROW"===t?r.top:r.left,o="ROW"===t?r.bottom:r.right;return this.doGroupOverlap(e,n,o)})}getGroupsLayers(e,t){const r=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(r,0,0)}getVisibleGroupLayers(e,t){const r=this.getGroupsLayers(e,t);for(const n of r)for(let r=n.length-1;r>=0;r--){const o=n[r];if(0===o.start)continue;le(o.start-1,o.end+1).every(r=>this.getters.isHeaderHiddenByUser(e,t,r))&&n.splice(r,1)}return r.filter(e=>e.length>0)}isGroupFolded(e,t,r,n){return this.getHeaderGroup(e,t,r,n)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,"ROW").some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,"COL").some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,r,n=0){const o={};for(const t of e)o[this.getGroupId(t)]=t.isFolded;const s={};for(const t of e)for(let e=t.start;e<=t.end;e++)s[e]=s[e]?s[e]+1:1;for(let e=t;e<=r;e++)s[e]=s[e]?s[e]+n:n;const i=Math.max(...Object.values(s),0),a=Array.from({length:i},()=>[]),l=Math.max(r,...e.map(e=>e.end));for(let r=Math.min(t,...e.map(e=>e.start));r<=l;r++){const e=s[r]||0;for(let t=0;t<e;t++){const e=a[t].at(-1);if(e&&ke([e.end,r]))e.end++;else{const e={start:r,end:r};a[t].push(e)}}}for(const e of a)for(const t of e)t.isFolded=o[this.getGroupId(t)];return a}groupHeaders(e,t,r,n){const o=this.getHeaderGroups(e,t),s=this.bricksFallingAlgorithm(o,r,n,1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(s))}unGroupHeaders(e,t,r,n){const o=this.getHeaderGroups(e,t),s=this.bricksFallingAlgorithm(o,r,n,-1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(s))}moveGroupsOnHeaderInsertion(e,t,r,n){const o=this.groups[e][t];for(let s=0;s<o.length;s++){const i=o[s],[a,l]=tp(r,n,[i.start,i.end]);a===i.start&&l===i.end||this.history.update("groups",e,t,s,{...i,start:a,end:l})}}moveGroupsOnHeaderDeletion(e,t,r){const n=this.getHeaderGroups(e,t),o=[];for(const e of n){const t=rp(r,le(e.start,e.end+1));0!==t.length&&o.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update("groups",e,t,this.bricksFallingAlgorithm(o,0,0).flat())}doGroupOverlap(e,t,r){return e.start<=r&&e.end>=t}removeDuplicateGroups(e){const t={};for(const r of e)t[this.getGroupId(r)]=r;return Object.values(t)}findGroupWithStartEnd(e,t,r,n){return this.getHeaderGroups(e,t).find(e=>e.start===r&&e.end===n)}foldHeaderGroup(e,t,r){const n=this.getGroupIndex(e,t,r.start,r.end);if(void 0===n)return;this.history.update("groups",e,t,n,"isFolded",!0);const o=this.getters.getHeaderGroups(e,t);for(let n=0;n<o.length;n++){const s=o[n];s.start===r.start&&s.end<=r.end&&this.history.update("groups",e,t,n,"isFolded",!0)}}unfoldHeaderGroup(e,t,r){const n=this.getGroupIndex(e,t,r.start,r.end);if(void 0===n)return;this.history.update("groups",e,t,n,"isFolded",!1);const o=this.getters.getHeaderGroups(e,t);for(let n=0;n<o.length;n++){const s=o[n];s.start===r.start&&s.end>=r.end&&this.history.update("groups",e,t,n,"isFolded",!1)}}getGroupIndex(e,t,r,n){const o=this.groups[e][t].findIndex(e=>e.start===r&&e.end===n);return-1===o?void 0:o}import(e){for(const t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(const e of["ROW","COL"])for(const r of t.headerGroups[e]||[])this.groups[t.id][e].push({...r})}export(e){for(const t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(const t of e.sheets)for(const e of["ROW","COL"]){const r=this.getGroupsLayers(t.id,e);for(let n=0;n<r.length;n++){const o=r[n];for(const r of o){for(let o=r.start;o<=r.end;o++){const s=Lv(t,e,o);s.outlineLevel=n+1,r.isFolded&&(s.isHidden=!0)}if(r.isFolded){Lv(t,e,r.end+1).collapsed=!0}}}}}}).add("header visibility",class extends Mw{static getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isHeaderHiddenByUser","isRowHiddenByUser","isColHiddenByUser"];hiddenHeaders={};allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),r="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=r?"TooManyHiddenElements":qe(e.elements)<0||We(e.elements)>r?"InvalidHeaderIndex":"Success"}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?"NotEnoughElements":"Success":"InvalidSheetId"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":const t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update("hiddenHeaders",e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("hiddenHeaders",e.sheetIdTo,re(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(const r of[...e.elements].sort((e,t)=>t-e))t.splice(r,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=Re(e.position,e.base),r=Be([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update("hiddenHeaders",e.sheetId,e.dimension,r);break}case"HIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}checkElementsIncludeAllVisibleHeaders(e,t,r){return De(r,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,r){return"COL"===t?this.isColHiddenByUser(e,r):this.isRowHiddenByUser(e,r)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){const t=[[]],r=this.hiddenHeaders[e].COL;for(let e=0;e<r.length;e++){r[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],r=this.hiddenHeaders[e].ROW;for(let e=0;e<r.length;e++){r[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){const r=le(0,this.getters.getNumberHeaders(e,t)),n=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&n.push(...le(e.start,e.end+1))}),r.filter(r=>!this.hiddenHeaders[e][t][r]&&!n.includes(r))}import(e){for(const t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=Boolean(t.rows[e]?.isHidden);for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=Boolean(t.cols[e]?.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const r of e.sheets){void 0===r.rows&&(r.rows={});for(let e=0;e<this.getters.getNumberRows(r.id);e++)(t||this.hiddenHeaders[r.id].ROW[e])&&(void 0===r.rows[e]&&(r.rows[e]={}),r.rows[e].isHidden||=this.hiddenHeaders[r.id].ROW[e]);void 0===r.cols&&(r.cols={});for(let e=0;e<this.getters.getNumberCols(r.id);e++)(t||this.hiddenHeaders[r.id].COL[e])&&(void 0===r.cols[e]&&(r.cols[e]={}),r.cols[e].isHidden||=this.hiddenHeaders[r.id].COL[e])}}}).add("tables",class extends Mw{static getters=["getCoreTable","getCoreTables","getCoreTableMatchingTopLeft"];tables={};nextTableId=1;adaptRanges({applyChange:e},t){for(const r of this.getCoreTables(t))this.applyRangeChangeOnTable(t,r,e)}allowDispatch(e){switch(e.type){case"CREATE_TABLE":if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return"InvalidSheetId";const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return ws(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?"TableOverlap":"Success",e=>this.checkTableConfigUpdateIsValid(e.config)):"NonContinuousTargets";case"UPDATE_TABLE":return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):"TableNotFound";case"ADD_MERGE":for(const t of this.getCoreTables(e.sheetId)){const r=t.range.zone;for(const t of e.target)if(as(r,t))return"MergeInTable"}}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":{const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break}case"DUPLICATE_SHEET":{const t={};for(const r of this.getCoreTables(e.sheetId))t[r.id]="dynamic"===r.type?this.copyDynamicTableForSheet(e.sheetIdTo,r):this.copyStaticTableForSheet(e.sheetIdTo,r);this.history.update("tables",e.sheetIdTo,t);break}case"CREATE_TABLE":{const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),r=this.getters.getRangesUnion(t),n=this.getters.getMergesInZone(e.sheetId,r.zone);n.length&&this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:n});const o=this.consumeNextId(),s=e.config||zp,i="dynamic"===e.tableType?this.createDynamicTable(o,r,s):this.createStaticTable(o,e.tableType,r,s);this.history.update("tables",e.sheetId,i.id,i);break}case"REMOVE_TABLE":{const t={};for(const r of this.getCoreTables(e.sheetId))e.target.every(e=>!os(r.range.zone,e))&&(t[r.id]=r);this.history.update("tables",e.sheetId,t);break}case"UPDATE_TABLE":this.updateTable(e);break;case"UPDATE_CELL":{const t=e.sheetId;for(const r of this.getCoreTables(t)){if("dynamic"===r.type)continue;const n=this.canUpdateCellCmdExtendTable(e,r);"down"===n?this.extendTableDown(t,r):"right"===n&&this.extendTableRight(t,r)}break}case"DELETE_CONTENT":{const t={...this.tables[e.sheetId]};for(const r in t){const n=t[r];n&&e.target.some(e=>cs(n.range.zone,e))&&this.dispatch("REMOVE_TABLE",{sheetId:e.sheetId,target:[n.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(Se):[]}getCoreTable({sheetId:e,col:t,row:r}){return this.getCoreTables(e).find(e=>ls(t,r,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>as(e.range.zone,t)))}extendTableDown(e,t){const r=this.getters.extendRange(t.range,"ROW",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,r))}extendTableRight(e,t){const r=this.getters.extendRange(t.range,"COL",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,r))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:r,row:n},o){if(!e)return"none";const s=o.range.zone;let i="none";if(s.bottom+1===n&&r>=s.left&&r<=s.right?i="down":s.right+1===r&&n>=s.top&&n<=s.bottom&&(i="right"),"none"===i)return"none";const a="down"===i?{...s,bottom:s.bottom+1,top:s.bottom+1}:{...s,right:s.right+1,left:s.right+1};for(let e=a.top;e<=a.bottom;e++)for(let r=a.left;r<=a.right;r++){const n={sheetId:t,col:r,row:e},o=this.getters.getCell(n)?.content;if(o||this.getters.isInMerge(n)||this.getTablesOverlappingZones(t,[ps(n)]).length)return"none"}return i}getCoreTableMatchingTopLeft(e,t){for(const r of this.getCoreTables(e)){const e=r.range.zone;if(e.left===t.left&&e.top===t.top)return r}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return"Success";const t=this.getters.getRangeFromRangeData(e.newTableRange).zone,r=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if("Success"!==r)return r;const n=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!n)return"TableNotFound";return this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==n.id).length?"TableOverlap":"Success"}checkTableConfigUpdateIsValid(e){return e&&(void 0!==e.numberOfHeaders&&e.numberOfHeaders<0||e.hasFilters&&0===e.numberOfHeaders)?"InvalidTableConfig":"Success"}createStaticTable(e,t,r,n,o){const s=r.zone;if(!o){o=[];for(const e of le(s.left,s.right+1)){const t={...s,left:e,right:e},i=this.consumeNextId();o.push(this.createFilterFromZone(i,r.sheetId,t,n))}}return{id:e,range:r,filters:o,config:n,type:t}}createDynamicTable(e,t,r){const n=bs(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,n),config:r,type:"dynamic"}}updateTable(e){const t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;const r=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(r){const t=this.getters.getMergesInZone(e.sheetId,r.zone);this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:t})}const n=r||t.range,o=this.updateTableConfig(e.config,t.config),s=e.tableType??t.type;if("dynamic"===s&&"dynamic"!==t.type||"dynamic"!==s&&"dynamic"===t.type){const r="dynamic"===s?this.createDynamicTable(t.id,n,o):this.createStaticTable(t.id,s,n,o);this.history.update("tables",e.sheetId,t.id,r)}else{const r="dynamic"===t.type?this.updateDynamicTable(t,n,o):this.updateStaticTable(t,n,o,s);this.history.update("tables",e.sheetId,t.id,r)}}updateStaticTable(e,t,r,n=e.type){if("dynamic"===n)throw new Error("Cannot use updateStaticTable to update a dynamic table");const o=t||e.range,s=o.zone,i=this.updateTableConfig(r,e.config),a=i||e.config,l=[];if(t||i&&"numberOfHeaders"in i)for(const t of le(s.left,s.right+1)){const r=s.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,n={...s,left:t,right:t},i=r?.id||this.consumeNextId();l.push(this.createFilterFromZone(i,o.sheetId,n,a))}return{...e,range:o,config:a,filters:l.length?l:e.filters,type:n}}updateDynamicTable(e,t,r){const n=t?this.getters.getRangeFromZone(t.sheetId,bs(t.zone)):e.range,o=r||e.config;return{...e,range:n,config:o}}updateTableConfig(e,t){if(!e)return t;const r={...t,...e};return 0===e.numberOfHeaders?r.hasFilters=!1:!0===e.hasFilters&&(r.numberOfHeaders||=1),r}createFilterFromZone(e,t,r,n){return TS(e,this.getters.getRangeFromZone(t,r),n,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){const r=this.getters.getRangeFromZone(e,t.range.zone),n=t.filters.map(r=>{const n=this.getters.getRangeFromZone(e,r.rangeWithHeaders.zone);return TS(r.id,n,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:r,filters:n,config:re(t.config),type:t.type}}copyDynamicTableForSheet(e,t){const r=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:r,config:re(t.config),type:"dynamic"}}applyRangeChangeOnTable(e,t,r){const n=r(t.range);let o;switch(n.changeType){case"REMOVE":return void this.history.update("tables",e,t.id,void 0);case"NONE":return;default:o=n.range}if("dynamic"===t.type){const r=this.updateDynamicTable(t,o);return void this.history.update("tables",e,t.id,r)}const s=[];for(const e of t.filters){const n=r(e.rangeWithHeaders);switch(n.changeType){case"REMOVE":continue;case"NONE":s.push(e);break;default:const r=n.range,o=TS(e.id,r,t.config,this.getters.getRangeFromZone);s.push(o)}}const i=o.zone;if(s.length<us(i).numberOfCols){for(let r=i.left;r<=i.right;r++)if(!s.find(e=>e.col===r)){const n=this.consumeNextId(),o={...i,left:r,right:r};s.push(this.createFilterFromZone(n,e,o,t.config))}s.sort((e,t)=>e.col-t.col)}const a=this.createStaticTable(t.id,t.type,o,t.config,s);this.history.update("tables",e,t.id,a)}consumeNextId(){const e=`${this.nextTableId}`;return this.history.update("nextTableId",this.nextTableId+1),e}import(e){for(const t of e.sheets)for(const e of t.tables||[]){const r=this.consumeNextId(),n=e.config||zp,o=this.getters.getRangeFromSheetXC(t.id,e.range),s=e.type||"static",i="dynamic"===s?this.createDynamicTable(r,o,n):this.createStaticTable(r,s,o,n);this.history.update("tables",t.id,i.id,i)}}export(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const r={range:es(e.range.zone),type:e.type};Ae(e.config,zp)||(r.config=e.config),t.tables.push(r)}}exportForExcel(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const r=es(e.range.zone);t.tables.push({range:r,filters:[],config:e.config})}}}).add("dataValidation",class extends Mw{static getters=["cellHasListDataValidationIcon","getDataValidationRule","getDataValidationRules","getValidationRuleForCell"];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(const t in this.rules){for(let r=this.rules[t].length-1;r>=0;r--){const n=this.rules[t][r];for(let o=0;o<n.criterion.values.length;o++){const s=e(t,n.criterion.values[o]);this.history.update("rules",t,r,"criterion","values",o,s)}}}}adaptDVRanges(e,{applyChange:t}){for(let r=this.rules[e].length-1;r>=0;r--){const n=this.rules[e][r];for(let o=n.ranges.length-1;o>=0;o--){const s=t(n.ranges[o]);switch(s.changeType){case"REMOVE":if(1===n.ranges.length)this.removeDataValidationRule(e,n.id);else{const t=n.ranges.slice();t.splice(o,1),this.history.update("rules",e,r,"ranges",t)}break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("rules",e,r,"ranges",o,s.range)}}}}allowDispatch(e){switch(e.type){case"ADD_DATA_VALIDATION_RULE":return this.getters.tryGetSheet(e.sheetId)?e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?"InvalidSheetId":this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid)):"InvalidSheetId";case"REMOVE_DATA_VALIDATION_RULE":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";if(!this.rules[e.sheetId].find(t=>t.id===e.id))return"UnknownDataValidationRule"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("rules",e.sheetId,[]);break;case"DUPLICATE_SHEET":{const t=re(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>zm(e.sheetId,e.sheetIdTo,t))}));this.history.update("rules",e.sheetIdTo,t);break}case"DELETE_SHEET":{const t={...this.rules};delete t[e.sheetId],this.history.update("rules",t);break}case"REMOVE_DATA_VALIDATION_RULE":this.removeDataValidationRule(e.sheetId,e.id);break;case"ADD_DATA_VALIDATION_RULE":{const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case"DELETE_CONTENT":{const t=zo(e.target),r=e.sheetId;for(const e of t)for(let t=e.top;t<=e.bottom;t++)for(let n=e.left;n<=e.right;n++){const e=this.getValidationRuleForCell({sheetId:r,col:n,row:t});if(e&&("isBoolean"===e.criterion.type||"isValueInList"===e.criterion.type&&!this.getters.getCell({sheetId:r,col:n,row:t})?.content)){const e=this.rules[r],o=[this.getters.getRangeFromSheetXC(r,Bo(n,t))],s=this.removeRangesFromRules(r,o,e);this.history.update("rules",r,s)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:r}){if(this.rules[e])for(const n of this.rules[e])for(const e of n.ranges)if(ls(t,r,e.zone))return n}cellHasListDataValidationIcon(e){const t=this.getValidationRuleForCell(e);return!!t&&!("isValueInList"!==t.criterion.type&&"isValueInRange"!==t.criterion.type||"arrow"!==t.criterion.displayStyle&&"chip"!==t.criterion.displayStyle)}addDataValidationRule(e,t){const r=this.rules[e];"isBoolean"===t.criterion.type?this.setCenterStyleToBooleanCells(t):"isValueInList"===t.criterion.type&&(t.criterion.values=Array.from(new Set(t.criterion.values)));const n=this.removeRangesFromRules(e,t.ranges,r,t.id),o=n.findIndex(e=>e.id===t.id);-1!==o?(n[o]=t,this.history.update("rules",e,n)):this.history.update("rules",e,[...n,t])}removeRangesFromRules(e,t,r,n){r=re(r);for(const e of r)e.id!==n&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return r.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){const r=this.rules[e].filter(e=>e.id!==t);this.history.update("rules",e,r)}setCenterStyleToBooleanCells(e){for(const t of $m(e.ranges)){const e=this.getters.getCellStyle(t),r={...e,align:e?.align??"center",verticalAlign:e?.verticalAlign??"middle"};this.dispatch("UPDATE_CELL",{...t,style:r})}}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}import(e){for(const t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(const e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(const t of e.sheets){t.dataValidationRules=[];for(const e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(const t of e.sheets){t.dataValidationRules=[];for(const e of this.rules[t.id]){const r={...re(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};"isValueInRange"===e.criterion.type&&(r.criterion.values=e.criterion.values.map(e=>{const r=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(r,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(r)}}}checkCriterionTypeIsValid(e){return Pw.contains(e.rule.criterion.type)?"Success":"UnknownDataValidationCriterionType"}checkCriterionHasValidNumberOfValues(e){const t=e.rule.criterion,r=Pw.get(t.type).numberOfValues(t);return void 0!==r&&t.values.length!==r?"InvalidNumberOfCriterionValues":"Success"}checkCriterionValuesAreValid(e){const t=e.rule.criterion,r=Pw.get(t.type);return t.values.some(e=>"onlyFormulas"===r.allowedValues&&!e.startsWith("=")||(e.startsWith("=")?"onlyLiterals"===r.allowedValues||_m(e).isBadExpression:!r.isCriterionValueValid(e)))?"InvalidDataValidationCriterionValue":"Success"}checkValidRange(e){const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),r=t.map(t=>this.getters.getRangeString(t,e.sheetId));return r.some(e=>!this.getters.isRangeValid(e))?"InvalidRange":"Success"}}).add("cell",class extends Mw{static getters=["zoneToXC","getCells","getTranslatedCellFormula","getCellById","getFormulaString","getFormulaMovedInSheet"];nextId=1;cells={};adaptRanges({applyChange:e},t,r){for(const n of Object.keys(this.cells))for(const o of Object.values(this.cells[n]||{}))if(o.isFormula)for(const s of o.compiledFormula.dependencies)if(s.sheetId===t||s.invalidSheetName===r.old){const t=e(s);"NONE"!==t.changeType&&this.history.update("cells",n,o.id,"compiledFormula","dependencies",o.compiledFormula.dependencies.indexOf(s),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case"UPDATE_CELL_POSITION":return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?"Success":"InvalidCellId";default:return"Success"}}handle(e){switch(e.type){case"SET_FORMATTING":"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnFormat.bind(this)):this.handleAddColumnsRows(e,this.copyRowFormat.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",format:""});break;case"CLEAR_CELLS":this.clearCells(e.sheetId,e.target);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"DELETE_SHEET":this.history.update("cells",e.sheetId,void 0)}}clearZones(e,t){for(const r of zo(t))for(let t=r.left;t<=r.right;t++)for(let n=r.top;n<=r.bottom;n++){const r=this.getters.getCell({sheetId:e,col:t,row:n});(r?.isFormula||r?.content)&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:n})}}setFormatter(e,t,r){for(const n of zo(t))for(let t=n.top;t<=n.bottom;t++)for(let o=n.left;o<=n.right;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,format:r})}clearFormatting(e,t){for(const r of zo(t))for(let t=r.left;t<=r.right;t++)for(let n=r.top;n<=r.bottom;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,format:""})}clearCells(e,t){for(const r of t)for(let t=r.left;t<=r.right;t++)for(let n=r.top;n<=r.bottom;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,content:"",format:""})}handleAddColumnsRows(e,t){let r,n;"before"===e.position?(r=le(e.base,e.base+e.quantity),n=e.base+e.quantity):(r=le(e.base+1,e.base+e.quantity+1),n=e.base),t(e.sheetId,n,r)}import(e){for(const t of e.sheets){const r=t.id,n=new Nw;for(const e in t.cells)if(t.cells[e]){const{col:r,row:o}=Ho(e),s={sheetId:t.id,col:r,row:o};n.set(s,{content:t.cells[e]})}for(const[e,r]of vy(t.id,t.formats)){const t=n.get(e);t?t.format=r:n.set(e,{format:r})}for(const o of n.keysForSheet(r)){const r=n.get(o);if(r?.content||r?.format){const n=this.importCell(t.id,r?.content,r?.format?e.formats[r?.format]:void 0);this.history.update("cells",t.id,n.id,n),this.dispatch("UPDATE_CELL_POSITION",{cellId:n.id,...o})}}}}export(e){const t={};for(const r of e.sheets){const e=[],n={},o=Object.keys(this.cells[r.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(const r of o){const o=this.getters.getCell(r),s=Bo(r.col,r.row);if(o.format){const n=py(o.format,t);e[n]??=[],e[n].push(r)}o.content&&(n[s]=o.content)}r.formats=by(e),r.cells=n}e.formats=t}importCell(e,t,r){const n=this.getNextUid();return this.createCell(n,t||"",r,e)}exportForExcel(e){this.export(e);const t=[];for(const r in e.formats||[])pn(e.formats[r])||(t.push(Number(r)),delete e.formats[r]);if(t.length)for(const r of e.sheets)for(const e in r.formats){const n=r.formats[e];n&&t.includes(n)&&delete r.formats[e]}}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,r,n=!1){if(!r.length)return Ie(t.map(e=>e.value));let o=0;return Ie(t.map(t=>{if("REFERENCE"===t.type){const t=r[o++];return this.getters.getRangeString(t,e,{useBoundedReference:n})}return t.value}))}getTranslatedCellFormula(e,t,r,n){const o=this.getters.createAdaptedRanges(Dm(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,r,e);return this.getFormulaString(e,n,o)}getFormulaMovedInSheet(e,t,r){const n=Dm(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),o=this.getters.removeRangesSheetPrefix(t,n);return this.getFormulaString(t,r,o)}zoneToXC(e,t,r=[{colFixed:!1,rowFixed:!1}]){const n=Bo((t=this.getters.expandZone(e,t)).left,t.top,r[0]),o=Bo(t.right,t.bottom,r.length>1?r[1]:r[0]),s=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),i=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=s.col===i.col&&s.row===i.row;return n===o||a?n:n+":"+o}copyColumnFormat(e,t,r){for(let n=0;n<this.getters.getNumberRows(e);n++){const o=this.getFormat(e,t,n);if(o.format)for(const t of r)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,...o})}}copyRowFormat(e,t,r){for(let n=0;n<this.getters.getNumberCols(e);n++){const o=this.getFormat(e,n,t);if(o.format)for(const t of r)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,...o})}}getFormat(e,t,r){const n={},o=this.getters.getMainCellPosition({sheetId:e,col:t,row:r}),s=this.getters.getCell(o);return s&&s.format&&(n.format=s.format),n}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,r,n){const o=this.getters.getCell({sheetId:e,col:t,row:r}),s="content"in n||"formula"in n,i=s?Pe(n?.content):o?.content||"",a="format"in n?n.format:o&&o.format;if((s&&!i&&!n.formula||!s&&(!o||""===o.content))&&!a)return void(o&&(this.history.update("cells",e,o.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:r,sheetId:e})));const l=o?.id||this.getNextUid(),c=this.createCell(l,i,a,e);this.history.update("cells",e,c.id,c),this.dispatch("UPDATE_CELL_POSITION",{cellId:c.id,col:t,row:r,sheetId:e})}createCell(e,t,r,n){return t.startsWith("=")?this.createFormulaCell(e,t,r,n):this.createLiteralCell(e,t,r)}createLiteralCell(e,t,r){const n=this.getters.getLocale(),o=uE(t,n);return bn(r=r||("number"==typeof o?cn(t,n)||un(t):void 0))||t.startsWith("'")||Vt(t)||(t=$t(o)),{id:e,content:t,format:r,isFormula:!1,parsedValue:o}}createFormulaCell(e,t,r,n){const o=_m(t);return o.dependencies.length?this.createFormulaCellWithDependencies(e,o,r,n):{id:e,content:t,format:r,isFormula:!0,compiledFormula:{...o,dependencies:[]}}}createFormulaCellWithDependencies(e,t,r,n){const o=[];for(const e of t.dependencies)o.push(this.getters.getRangeFromSheetXC(n,e));return new Vw(e,t,r,o,n,this.getters.getRangeString)}checkCellOutOfSheet(e){const{sheetId:t,col:r,row:n}=e;if(!this.getters.tryGetSheet(t))return"InvalidSheetId";return ls(r,n,this.getters.getSheetZone(t))?"Success":"TargetOutOfSheet"}checkUselessClearCell(e){const t=this.getters.getCell(e),r=this.getters.getCellStyle(e);return t&&(t.content||r||t.format)?"Success":"NoChanges"}checkUselessUpdateCell(e){const t=this.getters.getCell(e),r="content"in e||"formula"in e,n="style"in e,o=n&&this.getters.getCellStyle(e),s="format"in e;return r&&t?.content!==e.content||n&&!Ae(o,e.style)||s&&t?.format!==e.format?"Success":"NoChanges"}}).add("merge",class extends Mw{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge","getSelectionRangeString","isMainCellPosition"];nextId=1;merges={};mergeCellMap={};allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return"Success"}}handle(e){switch(e.type){case"CREATE_SHEET":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;for(const r of Object.values(t).filter(Se))this.addMerge(e.sheetIdTo,r.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(Se)}getMerge({sheetId:e,col:t,row:r}){const n=this.mergeCellMap[e],o=n?t in n&&n[t]?.[r]:void 0;return o?this.getMergeById(e,o):void 0}getMergesInZone(e,t){const r=this.mergeCellMap[e];if(!r)return[];const n=new Set;for(let e=t.left;e<=t.right;e++)for(let o=t.top;o<=t.bottom;o++){const t=r[e]?.[o];t&&n.add(t)}return Array.from(n).map(t=>this.getMergeById(e,t)).filter(Se)}getSelectionRangeString(e,t){const r=this.getters.expandZone(e.sheetId,e.zone),n=Lm({...e,zone:{...r,bottom:Um(e)?void 0:r.bottom,right:Hm(e)?void 0:r.right}},this.getters.getSheetSize),o=this.getters.getRangeString(n,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){const{sheetName:e,xc:t}=To(o);return Io(e,t.split(":")[0])}return o}doesIntersectMerge(e,t){for(const r of this.getMerges(e))if(as(t,r))return!0;return!1}doesColumnsHaveCommonMerges(e,t,r){const n=this.getters.getSheet(e);for(let o=0;o<this.getters.getNumberRows(e);o++)if(this.isInSameMerge(n.id,t,o,r,o))return!0;return!1}doesRowsHaveCommonMerges(e,t,r){const n=this.getters.getSheet(e);for(let o=0;o<=this.getters.getNumberCols(e);o++)if(this.isInSameMerge(n.id,o,t,o,r))return!0;return!1}expandZone(e,t){const{left:r,right:n,top:o,bottom:s}=t;let i={left:r,right:n,top:o,bottom:s};for(const t in this.merges[e]){const r=this.getMergeById(e,parseInt(t));r&&as(r,i)&&(i=ns(r,i))}return ss(i,t)?i:this.expandZone(e,i)}isInSameMerge(e,t,r,n,o){const s=this.getMerge({sheetId:e,col:t,row:r}),i=this.getMerge({sheetId:e,col:n,row:o});return!(!s||!i)&&ss(s,i)}isInMerge({sheetId:e,col:t,row:r}){const n=this.mergeCellMap[e];return!!n&&(t in n&&Boolean(n[t]?.[r]))}getMainCellPosition(e){const t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){const r=this.getters.getHiddenColsGroups(e),n=this.getters.getHiddenRowsGroups(e);for(const e of r)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(const e of n)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const r=this.getMerge({sheetId:e,col:t.left,row:t.top});if(r)return ss(t,r);const{numberOfCols:n,numberOfRows:o}=us(t);return 1===n&&1===o}isMainCellPosition(e){return Ae(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:r,right:n,top:o,bottom:s}=t;n=ae(n,0,this.getters.getNumberCols(e)-1),s=ae(s,0,this.getters.getNumberRows(e)-1);for(let t=o;t<=s;t++)for(let s=r;s<=n;s++)if(s!==r||t!==o){const r=this.getters.getCell({sheetId:e,col:s,row:t});if(r&&""!==r.content)return!0}return!1}getMergeById(e,t){const r=this.merges[e]?.[t];return void 0!==r?Ww(t,r):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";return t.some(t=>this.isMergeDestructive(e,t))?"MergeIsDestructive":"Success"}checkOverlap({target:e}){for(const t of e)for(const r of e)if(t!==r&&as(t,r))return"MergeOverlap";return"Success"}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";const{xSplit:r,ySplit:n}=this.getters.getPaneDivisions(e);return function(e,t,r){return e.some(e=>function(e,t,r){return e.left<t&&t<=e.right||e.top<r&&r<=e.bottom}(e,t,r))}(t,r,n)?"FrozenPaneOverlap":"Success"}checkMergedContentUpdate(e){const{col:t,row:r,content:n}=e;if(void 0===n)return"Success";const{col:o,row:s}=this.getMainCellPosition(e);return o===t&&s===r?"Success":"CellIsMerged"}checkMergeExists(e){const{sheetId:t,target:r}=e;for(const e of r){const{left:r,top:n}=e,o=this.getMerge({sheetId:t,col:r,row:n});if(void 0===o||!ss(e,o))return"InvalidTarget"}return"Success"}addMerge(e,t){let{left:r,right:n,top:o,bottom:s}=t;n=ae(n,0,this.getters.getNumberCols(e)-1),s=ae(s,0,this.getters.getNumberRows(e)-1);if(Bo(r,o)===Bo(n,s))return;const i=this.nextId++;this.history.update("merges",e,i,this.getters.getRangeFromSheetXC(e,es({left:r,top:o,right:n,bottom:s})));const a=new Set;for(let t=o;t<=s;t++)for(let s=r;s<=n;s++){s===r&&t===o||this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,content:""});const n=this.getMerge({sheetId:e,col:s,row:t});n&&a.add(n.id),this.history.update("mergeCellMap",e,s,t,i)}for(const t of a){const{top:r,bottom:n,left:o,right:s}=this.getMergeById(e,t);for(let t=r;t<=n;t++)for(let r=o;r<=s;r++){const n={sheetId:e,col:r,row:t},o=this.getMerge(n);o&&o.id===i||(this.history.update("mergeCellMap",e,r,t,void 0),this.dispatch("CLEAR_CELL",n))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:r,top:n,bottom:o,right:s}=t,i=this.getMerge({sheetId:e,col:r,row:n});if(void 0!==i&&ss(t,i)){this.history.update("merges",e,i.id,void 0);for(let t=n;t<=o;t++)for(let n=r;n<=s;n++)this.history.update("mergeCellMap",e,n,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){const r=Object.entries(this.merges[e]||{});for(const[n,o]of r)if(o){const r=o.zone,s=t(o);switch(s.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,r);break;default:const{numberOfCols:t,numberOfRows:o}=us(s.range.zone);1===t&&1===o?this.removeMerge(e,r):this.history.update("merges",e,parseInt(n,10),s.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:r,row:n}of ds(t))this.history.update("mergeCellMap",e,r,n,t.id)}import(e){const t=e.sheets||[];for(const e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(const r of t)this.addMerge(e,Ko(r))}export(e){for(const t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Gw(e))}}exportForExcel(e){this.export(e)}}).add("style",class extends Mw{static getters=["getCellStyle","getCellStyleInZone","getZoneStyles","getStyleColors"];styles={};allowDispatch(e){return"SET_FORMATTING"===e.type?this.checkUselessSetFormatting(e):"Success"}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.onMerge(e.sheetId,t);break;case"SET_FORMATTING":void 0!==e.style&&(null!==e.style?this.setStyles(e.sheetId,e.target,e.style):this.clearStyle(e.sheetId,e.target));break;case"CLEAR_FORMATTING":case"CLEAR_CELLS":this.clearStyle(e.sheetId,e.target);break;case"UPDATE_CELL":void 0!==e.style&&(null!==e.style?this.setStyles(e.sheetId,[ps(e)],e.style,{force:!0}):this.clearStyle(e.sheetId,[ps(e)]));break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnn(e):this.handleAddRows(e);break;case"CLEAR_CELL":this.clearStyle(e.sheetId,[ps(e)]);break;case"DELETE_SHEET":this.history.update("styles",e.sheetId,void 0)}}adaptRanges({applyChange:e},t){const r=[];for(const n of this.styles[t]??[]){const o=e(this.getters.getRangeFromZone(t,n.zone));switch(o.changeType){case"RESIZE":case"CHANGE":case"MOVE":r.push({style:n.style,zone:o.range.unboundedZone});break;case"NONE":r.push(n)}}this.history.update("styles",t,r)}handleAddColumnn(e){const t=this.styles[e.sheetId]??[];for(let r=0;r<t.length;r++){const n=t[r];n.zone.left-e.quantity===e.base&&"before"===e.position?this.history.update("styles",e.sheetId,r,"zone","left",n.zone.left-e.quantity):n.zone.right===e.base&&"after"===e.position&&this.history.update("styles",e.sheetId,r,"zone","right",n.zone.right+e.quantity)}}handleAddRows(e){const t=this.styles[e.sheetId]??[];for(let r=0;r<t.length;r++){const n=t[r];n.zone.top-e.quantity===e.base&&"before"===e.position?this.history.update("styles",e.sheetId,r,"zone","top",n.zone.top-e.quantity):n.zone.bottom===e.base&&"after"===e.position&&this.history.update("styles",e.sheetId,r,"zone","bottom",n.zone.bottom+e.quantity)}}styleIsDefault(e){for(const t in e)if(SS[t]!==e[t])return!1;return!0}removeDefaultStyleValues(e){const t={...e};for(const r in e)void 0!==t[r]&&t[r]!==SS[r]||delete t[r];return Object.keys(t).length>0?t:void 0}onMerge(e,t){this.setStyle(e,t,this.getCellStyle({sheetId:e,col:t.left,row:t.top}),{force:!0})}setStyles(e,t,r,n={force:!1}){for(const o of t)this.setStyle(e,o,r,n)}setStyle(e,t,r,n={force:!1}){const o=[];let s=[this.getters.expandZone(e,t)];for(const i of this.styles[e]??[]){const e=os(i.zone,t);if(!e){o.push(i);continue}let a=n.force?r:{...i.style,...r};if(a=this.removeDefaultStyleValues(a),Ae(i.style,a))o.push(i);else{a&&!this.styleIsDefault(a)&&o.push({zone:e,style:a});for(const t of zo([i.zone],[e]))o.push({zone:t,style:i.style})}s=zo(s,[e])}(r=this.removeDefaultStyleValues(r))&&o.push(...s.map(e=>({zone:e,style:r}))),this.history.update("styles",e,o)}clearStyle(e,t){this.setStyles(e,t,void 0,{force:!0})}getCellStyle(e){const t=this.styles[e.sheetId]?.find(t=>ls(e.col,e.row,t.zone));return t?.style}getCellStyleInZone(e,t){const r=new Nw;for(const{zone:n,style:o}of this.styles[e]??[]){const s=os(n,t);if(s)for(let t=s.left;t<=s.right;t++)for(let n=s.top;n<=s.bottom;n++)r.set({sheetId:e,col:t,row:n},o)}return r}getZoneStyles(e,t){const r=[];for(const n of this.styles[e]??[]){const e=os(n.zone,t);e&&r.push({zone:e,style:n.style})}return r}getStyleColors(e){const t=new Set;for(const r of this.styles[e]??[])r.style.textColor&&t.add(r.style.textColor),r.style.fillColor&&t.add(r.style.fillColor);return[...t]}import(e){if(Object.keys(e.styles||{}).length){for(const t of e.sheets)for(const r in t.styles){const n=t.styles[r];this.setStyle(t.id,Ko(r),e.styles[n])}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.onMerge(t.id,Ko(e))}}export(e){const t={};for(const r of e.sheets){r.styles={};for(const e of this.styles[r.id]??[])r.styles[es(e.zone)]=py(e.style,t)}e.styles=t}exportForExcel(e){this.export(e)}checkUselessSetFormatting(e){const{sheetId:t,target:r}=e,n="style"in e,o="format"in e;if(!n&&!o)return"NoChanges";for(const s of zo(r))for(let r=s.left;r<=s.right;r++)for(let i=s.top;i<=s.bottom;i++){const s={sheetId:t,col:r,row:i},a=this.getters.getCell(s),l=this.getCellStyle(s);if(n&&!Ae(l,e.style)||o&&a?.format!==e.format)return"Success"}return"NoChanges"}}).add("headerSize",class extends Mw{static getters=["getUserRowSize","getColSize"];sizes={};handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("sizes",e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case"DUPLICATE_SHEET":this.history.update("sizes",e.sheetIdTo,re(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const t={...this.sizes};delete t[e.sheetId],this.history.update("sizes",t);break;case"REMOVE_COLUMNS_ROWS":{const t=He(this.sizes[e.sheetId][e.dimension],e.elements);this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=this.sizes[e.sheetId][e.dimension],r=Re(e.position,e.base),n=t[e.base],o=Be(t,Array(e.quantity).fill(n),r);this.history.update("sizes",e.sheetId,e.dimension,o);break}case"RESIZE_COLUMNS_ROWS":if("ROW"===e.dimension)for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0);else for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0)}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){const r=this.sizes[e]?.ROW[t];return r?Math.round(r):void 0}import(e){for(const t of e.sheets){const e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(const[r,n]of Object.entries(t.rows))n.size&&(e.ROW[r]=n.size);for(const[r,n]of Object.entries(t.cols))n.size&&(e.COL[r]=n.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const r of e.sheets){void 0===r.rows&&(r.rows={});for(const e of le(0,this.getters.getNumberRows(r.id)))(t||this.sizes[r.id].ROW[e])&&(r.rows[e]={...r.rows[e],size:this.getUserRowSize(r.id,e)??G});void 0===r.cols&&(r.cols={});for(const e of le(0,this.getters.getNumberCols(r.id)))(t||this.sizes[r.id].COL[e])&&(r.cols[e]={...r.cols[e],size:this.getColSize(r.id,e)})}}}).add("borders",class extends Mw{static getters=["getCellBorder","getBorders","getBordersColors","getCellBordersInZone"];borders={};allowDispatch(e){return"SET_BORDER"===e.type?this.checkValidations(e,this.checkBordersUnchanged,this.ensureHasBorder):"Success"}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("borders",e.sheetIdTo,re(this.borders[e.sheetId]));break;case"DELETE_SHEET":const t={...this.borders};delete t[e.sheetId],this.history.update("borders",t);break;case"SET_BORDER":e.border&&this.addBorders(e.sheetId,[ps(e)],e.border);break;case"SET_BORDERS_ON_TARGET":for(const t of e.target)for(let r=t.left;r<=t.right;r++)for(let n=t.top;n<=t.bottom;n++)this.addBorder(e.sheetId,{left:r,right:r,top:n,bottom:n},e.border&&Object.keys(e.border).length?e.border:void 0);break;case"SET_ZONE_BORDERS":const r=e.target.map(t=>this.getters.expandZone(e.sheetId,t));"clear"===e.border.position?this.clearBorders(e.sheetId,r):this.addBorders(e.sheetId,r,this.borderDataToNewBorderData(e.border));break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target)}}beforeHandle(e){"REMOVE_COLUMNS_ROWS"===e.type&&("ROW"===e.dimension?this.onRowRemove(e.sheetId,e.elements):this.onColRemove(e.sheetId,e.elements))}adaptRanges({applyChange:e},t){const r=[];for(const n of this.borders[t]??[]){const o=e(this.getters.getRangeFromZone(t,n.zone));switch(o.changeType){case"RESIZE":case"CHANGE":case"MOVE":r.push({...n,zone:o.range.unboundedZone});break;case"NONE":r.push(n)}}this.history.update("borders",t,r.filter(e=>!this.borderIsClear(e)))}onRowRemove(e,t){const r=new Set(t),n=[];for(const t of this.borders[e]??[]){let e=t;r.has(t.zone.top)&&(e=re(t),e.style.top=t.style.horizontal),void 0!==t.zone.bottom&&r.has(t.zone.bottom)&&(e=e===t?re(t):e,e.style.bottom=t.style.horizontal),n.push(e)}this.history.update("borders",e,n)}onColRemove(e,t){const r=new Set(t),n=[];for(const t of this.borders[e]??[]){let e=t;r.has(t.zone.left)&&(e=re(t),e.style.left=t.style.vertical),void 0!==t.zone.right&&r.has(t.zone.right)&&(e=e===t?re(t):e,e.style.right=t.style.vertical),n.push(e)}this.history.update("borders",e,n.filter(e=>!this.borderIsClear(e)))}getCellBorder(e){return this.getZoneExternalBorders(e.sheetId,ps(e))}getZoneExternalBorders(e,t){const r={};for(const n of this.borders[e]??[])as(n.zone,t)&&(r.right=(t.right===n.zone.right?n.style.right:n.style.vertical)??r.right,r.left=(t.left===n.zone.left?n.style.left:n.style.vertical)??r.left,r.bottom=(t.bottom===n.zone.bottom?n.style.bottom:n.style.horizontal)??r.bottom,r.top=(t.top===n.zone.top?n.style.top:n.style.horizontal)??r.top);return r}getCellBordersInZone(e,t){const r=new Nw;for(const n of this.borders[e]??[]){const{zone:o,style:s}=n,i=os(o,t);if(i)for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){const i=r.get({sheetId:e,col:t,row:n})??{};i.right=(t===o.right?s.right:s.vertical)??i.right,i.left=(t===o.left?s.left:s.vertical)??i.left,i.bottom=(n===o.bottom?s.bottom:s.horizontal)??i.bottom,i.top=(n===o.top?s.top:s.horizontal)??i.top,r.set({sheetId:e,col:t,row:n},i)}}return r}getBordersColors(e){const t=new Set;for(const r of this.borders[e]??[])for(const e of Object.values(r.style))e?.color&&t.add(e.color);return[...t]}getBorders(e,t){const r=[];for(const n of this.borders[e]??[]){const e=os(n.zone,t);e&&r.push(this.computeBorderFromZone(e,n))}return r}computeBorderFromZone(e,t){const r=t.style,n=t.zone,o=e.top===n.top,s=e.bottom===n.bottom,i=e.left===n.left,a=e.right===n.right;return{zone:e,style:{top:o?r.top:r.horizontal,bottom:s?r.bottom:r.horizontal,left:i?r.left:r.vertical,right:a?r.right:r.vertical,vertical:r.vertical,horizontal:r.horizontal}}}borderIsClear(e){const t=e.style;if(t.left||t.right||t.bottom||t.top)return!1;const r=e.zone;return(!(void 0===r.bottom||r.top<r.bottom)||!t.horizontal)&&(!(void 0===r.right||r.left<r.right)||!t.vertical)}clearBorders(e,t){for(const r of t)this.removeAndClearAdjacent(e,r)}removeAndClearAdjacent(e,t){const r=[];for(const n of this.borders[e]??[])for(const e of zo([n.zone],[t]))for(const o of Ss(e,t)){const e=this.computeBorderFromZone(o,n),s=is(o,t);switch(s?.position){case"left":e.style.left=void 0;break;case"right":e.style.right=void 0;break;case"top":e.style.top=void 0;break;case"bottom":e.style.bottom=void 0}r.push(e)}this.history.update("borders",e,r)}addBorders(e,t,r){for(const n of t)this.addBorder(e,n,r)}addBorder(e,t,r,n=!1){const o=[],s=r?{zone:t,style:r}:void 0,i={left:!!r?.right,right:!!r?.left,top:!!r?.bottom,bottom:!!r?.top};let a=[t];for(const r of this.borders[e]??[]){const e=os(r.zone,t);if(!e){const e=is(r.zone,t);if(e&&i[e.position])for(const e of Ss(r.zone,t)){const n=this.computeBorderFromZone(e,r),s=is(e,t);switch(s?.position){case"left":n.style.left=void 0;break;case"right":n.style.right=void 0;break;case"top":n.style.top=void 0;break;case"bottom":n.style.bottom=void 0}o.push(n)}else o.push(r);continue}if(s){let t=this.computeBorderFromZone(e,s).style;n||(t={...this.computeBorderFromZone(e,r).style,...Fe(t)}),o.push({zone:e,style:t})}a=zo(a,[e]);for(const t of zo([r.zone],[e]))o.push(this.computeBorderFromZone(t,r))}s&&o.push(...a.map(e=>this.computeBorderFromZone(e,s))),this.history.update("borders",e,o.filter(e=>!this.borderIsClear(e)))}borderDataToNewBorderData(e){const t={},r={color:e.color??"#000000",style:e.style??"thin"};return["all","external","top"].includes(e.position)&&(t.top={...r}),["all","external","bottom"].includes(e.position)&&(t.bottom={...r}),["all","external","left"].includes(e.position)&&(t.left={...r}),["all","external","right"].includes(e.position)&&(t.right={...r}),["all","hv","v"].includes(e.position)&&(t.vertical={...r}),["all","hv","h"].includes(e.position)&&(t.horizontal={...r}),t}checkBordersUnchanged(e){const t=this.getCellBorder(e),r=!(e.border?.bottom||e.border?.left||e.border?.right||e.border?.top);return!t&&r||Ae(t,e.border)?"NoChanges":"Success"}ensureHasBorder(e){return e.border?"Success":"NoChanges"}addBordersToMerge(e,t){const r={...this.getZoneExternalBorders(e,t),...Fe(this.getCellBorder({sheetId:e,col:t.left,row:t.top}))};this.addBorder(e,t,r,!0)}import(e){if(Object.keys(e.borders||{}).length)for(const t of e.sheets)for(const r in t.borders){const n=t.borders[r];this.addBorder(t.id,Ko(r),e.borders[n])}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.addBordersToMerge(t.id,Ko(e))}export(e){const t={};for(const r of e.sheets){r.borders={};for(const e of this.borders[r.id]??[])r.borders[es(e.zone)]=py(e.style,t)}e.borders=t}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends Mw{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell","getAdaptedCfRanges"];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(const r in this.cfRules)for(const n of this.cfRules[r])if("DataBarRule"===n.rule.type&&n.rule.rangeValues){const t=e(n.rule.rangeValues);switch(t.changeType){case"REMOVE":this.history.update("cfRules",r,this.cfRules[r].indexOf(n),"rule","rangeValues",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",r,this.cfRules[r].indexOf(n),"rule","rangeValues",t.range)}}else if("CellIsRule"===n.rule.type)for(let e=0;e<n.rule.values.length;e++)this.history.update("cfRules",r,this.cfRules[r].indexOf(n),"rule","values",e,t(r,n.rule.values[e]));else if("IconSetRule"===n.rule.type)for(const e of["lowerInflectionPoint","upperInflectionPoint"])"formula"===n.rule[e].type&&this.history.update("cfRules",r,this.cfRules[r].indexOf(n),"rule",e,"value",t(r,n.rule[e].value));else if("ColorScaleRule"===n.rule.type)for(const e of["minimum","maximum","midpoint"]){const o=n.rule[e];"formula"===o?.type&&o?.value&&this.history.update("cfRules",r,this.cfRules[r].indexOf(n),"rule",e,"value",t(r,o.value))}}adaptCFRanges(e,{applyChange:t}){for(const r of this.cfRules[e])for(const n of r.ranges){const o=t(n);switch(o.changeType){case"REMOVE":const t=r.ranges.slice();t.splice(r.ranges.indexOf(n),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(r),"ranges",t):this.removeConditionalFormatting(r.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(r),"ranges",r.ranges.indexOf(n),o.range)}}}adaptRanges(e,t){const r=t?[t]:Object.keys(this.cfRules);for(const t of r)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?"InvalidSheetId":this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case"CHANGE_CONDITIONAL_FORMAT_PRIORITY":return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(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 r={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(r,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"CHANGE_CONDITIONAL_FORMAT_PRIORITY":this.changeCFPriority(e.cfId,e.delta,e.sheetId)}}import(e){for(const t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(const t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(const t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){const r=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{r.add(e)})}),Array.from(r)}getRulesByZone(e,t){const r=new Set;for(let n=t.top;n<=t.bottom;n++)for(let o=t.left;o<=t.right;o++){this.getRulesByCell(e,o,n).forEach(e=>{r.add(e.id)})}return r}getRulesByCell(e,t,r){const n=[];for(const o of this.cfRules[e])for(const e of o.ranges)ls(t,r,e.zone)&&n.push(o);return new Set(n.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,r,n){if(0===r.length&&0===n.length)return;const o=this.getters.getConditionalFormats(e),s=o.findIndex(e=>e.id===t.id);let i=[];s>-1&&(i=o[s].ranges.map(Xo));const a=zo(i,n);return zo([...r,...a],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:r}={useBoundedReference:!1}){const n=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:r}));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:n}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:r})},ranges:n}}mapToConditionalFormatInternal(e,t){const r=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:r}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:r}}addConditionalFormatting(e,t){const r=this.cfRules[t].slice(),n=r.findIndex(t=>t.id===e.id),o=this.mapToConditionalFormatInternal(t,e);n>-1?r.splice(n,1,o):r.push(o),this.history.update("cfRules",t,r)}checkValidPriorityChange(e,t,r){if(!this.cfRules[r])return"InvalidSheetId";const n=this.cfRules[r].findIndex(t=>t.id===e);if(-1===n)return"InvalidConditionalFormatId";const o=n-t;return o<0||o>=this.cfRules[r].length?"InvalidConditionalFormatId":"Success"}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues);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"Success"}checkCFHasChanged(e){const t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),r=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return r&&Ae(t,r)?"NoChanges":"Success"}checkOperatorArgsNumber(e){const t=Pw.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(void 0===t||t>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");const r=[],n=e=>void 0===e||""===e;return t>=1&&n(e.values[0])&&r.push("FirstArgMissing"),t>=2&&n(e.values[1])&&r.push("SecondArgMissing"),r.length?r:"Success"}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return"MinNaN";case"max":return"MaxNaN";case"mid":return"MidNaN";case"upperInflectionPoint":return"ValueUpperInflectionNaN";case"lowerInflectionPoint":return"ValueLowerInflectionNaN"}return"Success"}checkFormulaCompilation(e,t){if("formula"!==e.type)return"Success";if(_m(e.value||"").isBadExpression)switch(t){case"min":return"MinInvalidFormula";case"max":return"MaxInvalidFormula";case"mid":return"MidInvalidFormula";case"upperInflectionPoint":return"ValueUpperInvalidFormula";case"lowerInflectionPoint":return"ValueLowerInvalidFormula"}return"Success"}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,"min"),t=>e(t.maximum,"max"),t=>t.midpoint?e(t.midpoint,"mid"):"Success")}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,"lowerInflectionPoint"),t=>e(t.upperInflectionPoint,"upperInflectionPoint"))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,r=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(r)?"LowerBiggerThanUpper":"Success"}checkMinBiggerThanMax(e){const t=e.minimum.value,r=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&$w(t)>=$w(r)?"MinBiggerThanMax":"Success"}checkMidBiggerThanMax(e){const t=e.midpoint?.value,r=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&$w(t)>=$w(r)?"MidBiggerThanMax":"Success"}checkMinBiggerThanMid(e){const t=e.minimum.value,r=e.midpoint?.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&$w(t)>=$w(r)?"MinBiggerThanMid":"Success"}checkCFValues(e){for(const t of e.values){if(!t.startsWith("="))continue;if(_m(t||"").isBadExpression)return"ValueCellIsInvalidFormula"}return"Success"}removeConditionalFormatting(e,t){const r=this.cfRules[t].findIndex(t=>t.id===e);if(-1!==r){const e=this.cfRules[t].slice();e.splice(r,1),this.history.update("cfRules",t,e)}}changeCFPriority(e,t,r){const n=this.cfRules[r].findIndex(t=>t.id===e),o=this.cfRules[r][n],s=n-t,i=[...this.cfRules[r]];i.splice(n,1),i.splice(s,0,o),this.history.update("cfRules",r,i)}}).add("figures",class extends Mw{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};insertionOrders=[];adaptRanges({applyChange:e},t){for(const r of this.getFigures(t)){const n=e(this.getters.getRangeFromZone(t,{left:r.col,right:r.col,top:r.row,bottom:r.row}));if("MOVE"===n.changeType)this.history.update("figures",t,r.id,"col",n.range.zone.right),this.history.update("figures",t,r.id,"row",n.range.zone.bottom);else if("REMOVE"===n.changeType){const n=e(this.getters.getRangeFromZone(t,{left:0,right:r.col-1,top:0,bottom:r.row-1}));let{offset:o,col:s,row:i}=r;"NONE"!==n.changeType&&(s=n.range.zone.right+1,i=n.range.zone.bottom+1),({offset:o,col:s,row:i}=this.getPositionInSheet(t,{...r,col:s,row:i})),this.history.update("figures",t,r.id,"offset",o),this.history.update("figures",t,r.id,"col",s),this.history.update("figures",t,r.id,"row",i)}}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case"UPDATE_FIGURE":return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case"DELETE_FIGURE":return this.checkFigureExists(e);default:return"Success"}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch("DELETE_FIGURE",{figureId:t.id,sheetId:e.sheetId})})}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":const t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case"UPDATE_FIGURE":this.updateFigure(e);break;case"DELETE_FIGURE":this.removeFigure(e.figureId,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case"DUPLICATE_SHEET":for(const t of this.getFigures(e.sheetId)){const r=t.id,n=this.figures[e.sheetId]?.[r];if(!n)continue;const o=r.split(j).pop(),s=`${e.sheetIdTo}${j}${o}`;this.dispatch("CREATE_FIGURE",{figureId:s,...n,size:{width:n.width,height:n.height},sheetId:e.sheetIdTo})}}}onColRemove(e){const t=this.getters.getNumberCols(e),r=new Array(t+1);r[t]=0;for(let n=t-1;n>=0;n--)r[n]=r[n+1]+this.getters.getColSize(e,n);for(const t of this.getFigures(e))if(t.offset.x+t.width>r[t.col]){let n=t.offset.x,o=t.col;for(n=Math.min(n,r[o]-t.width);n<0&&o>0;)o--,n=r[o]-t.width;n!==t.offset.x&&this.history.update("figures",e,t.id,"offset",{x:Math.max(n,0),y:t.offset.y}),o!==t.col&&this.history.update("figures",e,t.id,"col",o)}}onRowRemove(e){const t=this.getters.getNumberRows(e),r=new Array(t+1);r[t]=0;for(let n=t-1;n>=0;n--)r[n]=r[n+1]+(this.getters.getUserRowSize(e,n)??G);for(const t of this.getFigures(e))if(t.offset.y+t.height>r[t.row]){let n=t.offset.y,o=t.row;for(let t=this.getters.getUserRowSize(e,o)??G;t<n;t=this.getters.getUserRowSize(e,o)??G)o+=1,n-=t;for(n=Math.min(n,r[o]-t.height);n<0&&o>0;)o--,n=r[o]-t.height;n!==t.offset.y&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(0,n)}),o!==t.row&&this.history.update("figures",e,t.id,"row",o)}else t.offset.y+t.height>r[0]&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(r[0]-t.height,0)})}getPositionInSheet(e,t){const{numberOfRows:r,numberOfCols:n}=this.getters.getSheetSize(e);let o,s,i=0,a=0,{col:l,row:c}=t;const u={...t.offset};for(o=r;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??G;for(c>o?(c=o,u.y=Math.max(i-t.height,0)):c===o&&(u.y=ae(u.y,0,Math.max(i-t.height,0))),s=n;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return l>s?(l=s,u.x=Math.max(a-t.width,0)):s===l&&(u.x=ae(u.x,0,Math.max(a-t.width,0))),{col:l,row:c,offset:u}}updateFigure(e){if(!("figureId"in e)||!("sheetId"in e))return;const{figureId:t,sheetId:r,...n}=e,o={...this.getFigure(r,t),...n};for(const[e,t]of Object.entries(n))switch(e){case"tag":case"offset":this.history.update("figures",r,o.id,e,t);break;case"col":case"row":case"width":case"height":void 0!==t&&this.history.update("figures",r,o.id,e,t)}}addFigure(e,t){this.history.update("figures",t,e.id,e),this.history.update("insertionOrders",this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update("insertionOrders",this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("insertionOrders",this.insertionOrders.filter(t=>t!==e)),this.history.update("figures",t,e,void 0)}checkFigureExists(e){return void 0===this.figures[e.sheetId]?.[e.figureId]?"FigureDoesNotExist":"Success"}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?"DuplicatedFigureId":"Success"}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?"WrongSheetPosition":"Success"}getFigures(e){const t=[];for(const r of this.insertionOrders){const n=this.figures[e]?.[r];n&&t.push(n)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>void 0!==this.figures[t]?.[e])}import(e){for(const t of e.sheets)for(const e of t.figures)this.addFigure(e,t.id)}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const r=void 0;t.figures.push({...e,data:r})}}exportForExcel(e){return this.export(e)}}).add("chart",class extends Mw{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getFigureIdFromChartId","getContextCreationChart"];charts={};createChart=function(e){const t=db.getAll().sort((e,t)=>e.sequence-t.sequence);return function(r,n,o){const s=t.find(e=>e.match(n.type));if(!s)throw new Error(`No builder for this chart: ${n.type}`);return s.createChart(n,o,e)}}(this.getters);validateChartDefinition=e=>function(e,t){const r=db.getAll().find(e=>e.match(t.type));if(!r)throw new Error("Unknown chart type.");return r.validateChartDefinition(e,t)}(this,e.definition);adaptRanges(e){for(const[t,r]of Object.entries(this.charts)){if(!r)continue;const n=r.chart.updateRanges(e);this.history.update("charts",t,n?{figureId:r.figureId,chart:n}:void 0)}}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists,this.checkChartChanged));case"DELETE_CHART":return this.checkChartExists(e);default:return"Success"}}handle(e){switch(e.type){case"CREATE_CHART":const{col:t,row:r,offset:n,size:o,sheetId:s,figureId:i}=e;this.getters.getFigure(s,i)||void 0===n||void 0===t||void 0===r||this.addFigure(i,s,t,r,n,o),this.addChart(e.figureId,e.chartId,e.definition);break;case"UPDATE_CHART":this.addChart(e.figureId,e.chartId,e.definition);break;case"DUPLICATE_SHEET":for(const t of this.getChartIds(e.sheetId)){const{chart:r,figureId:n}=this.charts[t]||{};if(!r||!n)continue;const o=this.getters.getFigure(e.sheetId,n);if(!o)continue;const s=n.split(j).pop(),i=`${e.sheetIdTo}${j}${s}`,a=t.split(j).pop(),l=`${e.sheetIdTo}${j}${a}`,c=r.duplicateInDuplicatedSheet(e.sheetIdTo);c&&this.dispatch("CREATE_CHART",{figureId:i,chartId:l,col:o.col,row:o.row,offset:o.offset,size:{width:o.width,height:o.height},definition:c.getDefinition(),sheetId:e.sheetIdTo})}break;case"DELETE_FIGURE":for(const t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch("DELETE_CHART",{chartId:t,sheetId:e.sheetId});break;case"DELETE_CHART":this.isChartDefined(e.chartId)&&this.history.update("charts",e.chartId,void 0);break;case"DELETE_SHEET":for(const t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw new Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){const t=this.charts[e]?.chart.type;if(!t)throw new Error("Chart not defined.");return t}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){const t=this.charts[e]?.chart.getDefinition();if(!t)throw new Error(`There is no chart with the given id: ${e}`);return t}import(e){for(const t of e.sheets)if(t.figures)for(const e of t.figures)if("chart"===e.tag){const r=e.data.chartId,n=this.createChart(e.id,e.data,t.id);this.charts[r]={chart:n,figureId:e.id}}else if("carousel"===e.tag)for(const r in e.data.chartDefinitions||{}){const n=e.data.chartDefinitions[r],o=this.createChart(e.id,n,t.id);this.charts[r]={chart:o,figureId:e.id}}}export(e){if(e.sheets)for(const t of e.sheets){const e=this.getters.getFigures(t.id),r=[];for(const t of e){const e=t,n=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&"chart"===e.tag&&n){const t=this.charts[n]?.chart.getDefinition();t&&(e.data={...t,chartId:n},r.push(e))}else if(e&&"carousel"===e.tag){const n=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),o={};for(const e of n)o[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:o},r.push(e)}else r.push(e)}t.figures=r}}addFigure(e,t,r,n,o,s={width:536,height:335}){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:r,row:n,offset:o,size:s,tag:"chart"})}addChart(e,t,r){const n=this.getters.getFigureSheetId(e);if(n){const o=this.createChart(e,r,n);this.history.update("charts",t,{figureId:e,chart:o})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?"DuplicatedChartId":"Success"}checkChartExists(e){return this.isChartDefined(e.chartId)?"Success":"ChartDoesNotExist"}checkChartChanged(e){return e.figureId!==this.charts[e.chartId]?.figureId?"Success":Ae(this.getChartDefinition(e.chartId),e.definition)?"NoChanges":"Success"}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||void 0!==e.offset&&void 0!==e.col&&void 0!==e.row?"Success":"MissingFigureArguments"}}).add("carousel",class extends Mw{static getters=["getCarousel","doesCarouselExist"];carousels={};allowDispatch(e){switch(e.type){case"CREATE_CAROUSEL":return this.getters.getFigure(e.sheetId,e.figureId)?"DuplicatedFigureId":"Success";case"UPDATE_CAROUSEL":return this.carousels[e.sheetId]?.[e.figureId]?"Success":"InvalidFigureId"}return"Success"}handle(e){switch(e.type){case"CREATE_CAROUSEL":this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch("CREATE_FIGURE",{...e,tag:"carousel"}),this.history.update("carousels",e.sheetId,e.figureId,e.definition);break;case"UPDATE_CAROUSEL":this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update("carousels",e.sheetId,e.figureId,e.definition);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const r of t)if("carousel"===r.tag){const t=r.id.split(j).pop(),n=`${e.sheetIdTo}${j}${t}`,o=this.getCarousel(r.id);if(o){const t={width:r.width,height:r.height};this.dispatch("CREATE_CAROUSEL",{sheetId:e.sheetIdTo,figureId:n,offset:r.offset,col:r.col,row:r.row,size:t,definition:{items:o.items.map(t=>{if("carouselDataView"===t.type)return{...t};const r=t.chartId.split(j).pop(),n=`${e.sheetIdTo}${j}${r}`;return{...t,chartId:n}})}})}}break}case"DELETE_FIGURE":this.history.update("carousels",e.sheetId,e.figureId,void 0);break;case"DELETE_SHEET":this.history.update("carousels",e.sheetId,void 0)}}doesCarouselExist(e){for(const t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(const t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw new Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){const r=new Set(e.definition.items.filter(e=>"chart"===e.type).map(e=>e.chartId));for(const n of t)"chart"!==n.type||r.has(n.chartId)||this.dispatch("DELETE_CHART",{chartId:n.chartId,sheetId:e.sheetId})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter(e=>"carousel"===e.tag);for(const r of e)this.history.update("carousels",t.id,r.id,{items:r.data.items,title:r.data.title})}}export(e){for(const t of e.sheets){const e=t.figures.filter(e=>"carousel"===e.tag);for(const r of e)this.carousels[t.id]?.[r.id]&&(r.data={...r.data,...this.carousels[t.id]?.[r.id]})}}}).add("image",class extends Mw{static getters=["getImage","getImagePath","getImageSize"];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?"InvalidFigureId":"Success"}handle(e){switch(e.type){case"CREATE_IMAGE":this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const r of t)if("image"===r.tag){const t=r.id.split(j).pop(),n=`${e.sheetIdTo}${j}${t}`,o=this.getImage(r.id);if(o){const t={width:r.width,height:r.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:n,offset:r.offset,col:r.col,row:r.row,size:t,definition:re(o)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.figureId,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,r,n,o,s){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:r,row:n,offset:o,size:s,tag:"image"})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter(e=>"image"===e.tag);for(const r of e)this.history.update("images",t.id,r.id,r.data),this.syncedImages.add(r.data.path)}}export(e){for(const t of e.sheets){const e=t.figures.filter(e=>"image"===e.tag);for(const r of e)r.data=this.images[t.id]?.[r.id]}}exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),r=[];for(const t of e)if("image"===t?.tag){const e=this.getImage(t.id);e&&r.push({...t,data:re(e)})}t.images=[...t.images,...r]}}}).add("pivot_core",class extends Mw{static getters=["getPivotCoreDefinition","getPivotDisplayName","getPivotId","getPivotFormulaId","getPivotIds","getMeasureCompiledFormula","getPivotName","isExistingPivot","getMeasureFullDependencies"];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case"ADD_PIVOT":return e.pivotId in this.pivots?"PivotIdTaken":this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case"UPDATE_PIVOT":return e.pivotId in this.pivots?Ae(e.pivot,this.pivots[e.pivotId]?.definition)?"NoChanges":""===e.pivot.name?"EmptyName":this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):"PivotIdNotFound";case"RENAME_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound";if(""===e.name)return"EmptyName";break;case"REMOVE_PIVOT":case"DUPLICATE_PIVOT":case"INSERT_PIVOT":case"DUPLICATE_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound"}return"Success"}handle(e){switch(e.type){case"ADD_PIVOT":{const{pivotId:t,pivot:r}=e;this.addPivot(t,r);break}case"INSERT_PIVOT":{const{sheetId:t,col:r,row:n,pivotId:o,table:s}=e,i={sheetId:t,col:r,row:n},{cols:a,rows:l,measures:c,fieldsType:u}=s,h=new lS(a,l,c,u||{}),d=this.getPivotFormulaId(o);this.insertPivot(i,d,h);break}case"RENAME_PIVOT":this.history.update("pivots",e.pivotId,"definition","name",e.name);break;case"REMOVE_PIVOT":{const t={...this.pivots};delete t[e.pivotId];const r=this.getPivotFormulaId(e.pivotId);this.history.update("formulaIds",r,void 0),this.history.update("pivots",t);break}case"DUPLICATE_PIVOT":{const{pivotId:t,newPivotId:r}=e,n=re(this.getPivotCore(t).definition);n.name=e.duplicatedPivotName??n.name+" (copy)",this.addPivot(r,n);break}case"UPDATE_PIVOT":this.history.update("pivots",e.pivotId,"definition",re(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures)}}adaptRanges({applyChange:e,adaptFormulaString:t}){for(const t in this.pivots){const r=re(this.pivots[t]?.definition);if(!r)continue;const n=ES.get(r.type)?.adaptRanges?.(this.getters,r,e);n&&!Ae(r,n)&&this.history.update("pivots",t,"definition",n)}for(const r in this.compiledMeasureFormulas)for(const n in this.compiledMeasureFormulas[r]){const o=this.pivots[r]?.definition.measures.find(e=>e.id===n);if(!o||!o.computedBy)continue;const s=o.computedBy.sheetId,{formula:i,dependencies:a}=this.compiledMeasureFormulas[r][n];this.history.update("compiledMeasureFormulas",r,n,"formula","dependencies",i.dependencies.map(t=>e(t).range)),this.history.update("compiledMeasureFormulas",r,o.id,"dependencies",a.map(t=>e(t).range));const l=o.computedBy.formula,c=t(s,l);c!==l&&this.replaceMeasureFormula(r,o,c)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw new Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw new Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,r=this.nextFormulaId.toString()){this.history.update("pivots",e,{definition:re(t),formulaId:r}),this.compileCalculatedMeasures(e,t.measures),this.history.update("formulaIds",r,e),this.history.update("nextFormulaId",this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(const r of t)if(r.computedBy){const t=this.compileMeasureFormula(r.computedBy.sheetId,r.computedBy.formula);this.history.update("compiledMeasureFormulas",e,r.id,"formula",t)}for(const r of t)if(r.computedBy){const t=this.computeMeasureFullDependencies(e,r);this.history.update("compiledMeasureFormulas",e,r.id,"dependencies",t)}}computeMeasureFullDependencies(e,t,r=new Set){const n=[],o=this.getPivotCoreDefinition(e),s=this.getMeasureCompiledFormula(e,t);r.add(t.id);for(const i of s.tokens){if("SYMBOL"!==i.type)continue;const s=o.measures.find(e=>se(e.id)===i.value&&t.id!==e.id);s&&!r.has(s.id)&&s.computedBy&&n.push(...this.computeMeasureFullDependencies(e,s,r))}return n.push(...s.dependencies.filter(e=>!e.invalidXc)),n}insertPivot(e,t,r){this.resizeSheet(e.sheetId,e,r);const n=r.getPivotCells();for(let r=0;r<n.length;r++)for(let o=0;o<n[r].length;o++){const s=n[r][o];this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col+r,row:e.row+o,content:Xd(t,s)})}}resizeSheet(e,{col:t,row:r},n){const o=n.getNumberOfDataColumns()+1,s=this.getters.getNumberCols(e),i=s-t;i<o&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:s-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o-i,position:"after"});const a=n.columns.length+n.rows.length,l=this.getters.getNumberRows(e),c=l-r;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}getPivotCore(e){const t=this.pivots[e];if(!t)throw new Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){const r=_m(t),n=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...r,dependencies:n}}replaceMeasureFormula(e,t,r){const n=this.pivots[e];if(!n)return;const o=n.definition.measures.indexOf(t);this.history.update("pivots",e,"definition","measures",o,"computedBy",{formula:r,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){const t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?"InvalidDefinition":"Success"}checkDuplicatedMeasureIds(e){const t=new Set(e.measures.map(e=>e.id));return e.measures.length!==t.size?"InvalidDefinition":"Success"}checkCustomFieldsAreValid(e){for(const t in e.customFields){const r=e.customFields[t],n=new Set,o=new Set;let s=!1;for(const e of r.groups){if(!e.name||o.has(e.name))return"InvalidPivotCustomField";if(e.values.some(e=>n.has(e)))return"InvalidPivotCustomField";if(e.isOtherGroup&&s)return"InvalidPivotCustomField";e.values.forEach(e=>n.add(e)),o.add(e.name),s||=!!e.isOtherGroup}}return"Success"}import(e){if(e.pivots)for(const[t,r]of Object.entries(e.pivots))this.addPivot(t,r,r.formulaId);this.history.update("nextFormulaId",e.pivotNextId||qd(this.pivots)+1)}export(e){e.pivots={};for(const t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}}).add("spreadsheet_pivot_core",class extends Mw{allowDispatch(e){switch(e.type){case"ADD_PIVOT":case"UPDATE_PIVOT":const t=e.pivot;return this.checkDataSetValidity(t)}return"Success"}checkDataSetValidity(e){if("SPREADSHEET"===e.type&&e.dataSet){const{zone:t,sheetId:r}=e.dataSet;return r&&this.getters.tryGetSheet(r)&&t&&Qo(t)?this.getters.checkZonesExistInSheet(r,[t]):"InvalidDataSet"}return"Success"}}).add("tableStyle",class extends Mw{static getters=["getNewCustomTableStyleName","getTableStyle","getTableStyles","isTableStyleEditable"];styles={};allowDispatch(e){switch(e.type){case"CREATE_TABLE":case"UPDATE_TABLE":if(e.config?.styleId&&!this.styles[e.config.styleId])return"InvalidTableConfig";break;case"CREATE_TABLE_STYLE":if(!sb[e.templateName])return"InvalidTableStyle";try{mp(e.primaryColor)}catch(e){return"InvalidTableStyle"}}return"Success"}handle(e){switch(e.type){case"CREATE_TABLE_STYLE":const t=ib(e.tableStyleName,e.templateName,e.primaryColor);this.history.update("styles",e.tableStyleId,t);break;case"REMOVE_TABLE_STYLE":const r={...this.styles};delete r[e.tableStyleId],this.history.update("styles",r);for(const t of this.getters.getSheetIds())for(const r of this.getters.getCoreTables(t))r.config.styleId===e.tableStyleId&&this.dispatch("UPDATE_TABLE",{sheetId:t,zone:r.range.zone,config:{styleId:zp.styleId}})}}getTableStyle(e){if(!this.styles[e])throw new Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Xe(v("Custom Table Style"),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!ob[e]}import(e){for(const e in ob)this.styles[e]=ob[e];for(const t in e.customTableStyles){const r=e.customTableStyles[t];this.styles[t]=ib(r.displayName,r.templateName,r.primaryColor)}}export(e){const t={};for(const e in this.styles)ob[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}}),$T=(new h).add("ui_sheet",class extends Ls{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getMultilineTextSize","getContiguousZone","computeTextYCoordinate"];ctx=wC();allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(const t of e.cols){const r=this.getColMaxWidth(e.sheetId,t);0!==r&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:r,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":this.autoResizeRows(e.sheetId,e.rows);break;case"DELETE_UNFILTERED_CONTENT":const t=[];for(const r of e.target){const n=ce(le(r.top,r.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(const e of n)t.push({...r,top:e[0],bottom:e[e.length-1]})}this.dispatch("DELETE_CONTENT",{sheetId:e.sheetId,target:t})}}getCellWidth(e){const t=this.getters.getCellComputedStyle(e);let r=0;const n=this.getters.getEvaluatedCell(e).formattedValue;if(n){const e=FC(this.ctx,n,t,void 0);r+=TC(this.ctx,e,t).width}for(const t of this.getters.getCellIcons(e))r+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(r+=10),0===r)return 0;if(r+=8,"wrap"===t.wrapping){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,r)}return r}getTextWidth(e,t){return IC(this.ctx,e,t)}getMultilineTextSize(e,t){return TC(this.ctx,e,t)}getCellText(e,t){const r=this.getters.getCell(e),n=this.getters.getLocale();if(t?.showFormula&&r?.isFormula)return hc(r.content,n);if(t?.showFormula&&!r?.content)return"";{const r=this.getters.getCellStyle(e),o=this.getters.getEvaluatedCell(e),s=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>IC(this.ctx,e,r||{})}:void 0;return Xr(o.value,{format:o.format,locale:n,formatWidth:s})}}getCellMultiLineText(e,t){const r=this.getters.getCellStyle(e),n=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return FC(this.ctx,n,r,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,r=W,n=1){const o=e.y+1,s=EC(t,n);if(e.height>s+8){if("middle"===r)return Math.ceil(o+(e.height-s)/2);if("bottom"===r)return o+e.height-s-4}return o+4}getContiguousZone(e,t){const r=t=>{for(const r of le(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:r,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:r,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(const r of le(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:r}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:r}))return{...t,right:t.right+1}}return t};let n=!1,o=t;do{n=!1;const e=r(o);ss(o,e)||(n=!0,o=e)}while(n);return o}isCellEmpty(e){const t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===Nu.empty}getColMaxWidth(e,t){const r=ds(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,We(r))}checkSheetExists(e){return"sheetId"in e&&void 0===this.getters.tryGetSheet(e.sheetId)?"InvalidSheetId":"Success"}checkZonesAreInSheet(e){const t="sheetId"in e?e.sheetId:this.getters.tryGetActiveSheetId();if("ranges"in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return"InvalidSheetId";const r=this.getters.getCommandZones(e);return!t&&r.length>0?"NoActiveSheet":t&&r.length>0?this.getters.checkZonesExistInSheet(t,r):"Success"}autoResizeRows(e,t){const r=[];for(const n of t){let t,o=0;for(const[r,s]of this.getters.getEvaluatedCellsPositionInZone(e,this.getters.getRowsZone(e,n,n))){if(void 0===s.value)continue;const n=this.getters.getColSize(e,r.col),i=this.getters.getCellStyle(r),a=s.formattedValue,l=SC(this.ctx,a,i,n);l>o&&l>G&&(o=l,t=r)}const s=t&&this.getters.getCell(t);s&&!s.isFormula&&(o=0),r.push(o||null)}const n=new Map(r.map(e=>[e,[]]));for(let e=0;e<r.length;e++)n.get(r[e])?.push(t[e]);for(const[t,r]of n)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:r,dimension:"ROW",size:t,sheetId:e})}}).add("ui_options",class extends Ls{static getters=["shouldShowFormulas"];showFormulas=!1;handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}).add("autofill",class extends Ls{static layers=["Autofill"];static getters=["getAutofillTooltip"];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){if("AUTOFILL_SELECT"===e.type){const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:ae(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:ae(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?"Success":"InvalidAutofillSelection"}return"Success"}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto()}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),r=this.autofillZone,n=[];switch(this.direction){case"down":for(let e=t.left;e<=t.right;e++){const o=[];for(let r=t.top;r<=t.bottom;r++)o.push(Bo(e,r));const s=this.createGenerator(o);for(let t=r.top;t<=r.bottom;t++)n.push(this.computeNewCell(s,e,t))}break;case"up":for(let e=t.left;e<=t.right;e++){const o=[];for(let r=t.bottom;r>=t.top;r--)o.push(Bo(e,r));const s=this.createGenerator(o);for(let t=r.bottom;t>=r.top;t--)n.push(this.computeNewCell(s,e,t))}break;case"left":for(let e=t.top;e<=t.bottom;e++){const o=[];for(let r=t.right;r>=t.left;r--)o.push(Bo(r,e));const s=this.createGenerator(o);for(let t=r.right;t>=r.left;t--)n.push(this.computeNewCell(s,t,e))}break;case"right":for(let e=t.top;e<=t.bottom;e++){const o=[];for(let r=t.left;r<=t.right;r++)o.push(Bo(r,e));const s=this.createGenerator(o);for(let t=r.left;t<=r.right;t++)n.push(this.computeNewCell(s,t,e))}}if(e){const e={},t={},r={},o=this.getters.getActiveSheetId();for(const s of n)this.collectBordersData(s,e),this.autofillMerge(o,s),this.autofillCell(o,s),this.collectConditionalFormatsData(o,s,t),this.collectDataValidationsData(o,s,r);this.autofillBorders(o,e),this.autofillConditionalFormats(o,t),this.autofillDataValidations(o,r),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){const r=JSON.stringify(e.border);r in t||(t[r]=[]),t[r].push(ps({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,r){const{originCol:n,originRow:o,col:s,row:i}=t,a=this.getters.getRulesByCell(e,n,o),l=Bo(s,i);for(const e of a)e.id in r||(r[e.id]=[]),r[e.id].push(l)}collectDataValidationsData(e,t,r){const{originCol:n,originRow:o,col:s,row:i}=t,a={sheetId:e,col:n,row:o},l=this.getters.getValidationRuleForCell(a);l&&(l.id in r||(r[l.id]=[]),r[l.id].push(ps({col:s,row:i})))}autofillCell(e,t){this.dispatch("UPDATE_CELL",{sheetId:e,col:t.col,row:t.row,content:t.content||"",style:t.style||null,format:t.format||""}),this.dispatch("AUTOFILL_CELL",t)}autofillBorders(e,t){for(const r in t){const n="undefined"===r?void 0:JSON.parse(r);this.dispatch("SET_BORDERS_ON_TARGET",{sheetId:e,border:n,target:zo(t[r])})}}autofillConditionalFormats(e,t){for(const r in t){const n=t[r],o=this.getters.getConditionalFormats(e).find(e=>e.id===r);if(!o)continue;const s=this.getters.getAdaptedCfRanges(e,o,n.map(Ko),[]);s&&this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:o.id,rule:o.rule,stopIfTrue:o.stopIfTrue},ranges:s,sheetId:e})}}autofillDataValidations(e,t){for(const r in t){const n=t[r],o=this.getters.getDataValidationRule(e,r);if(!o)continue;const s=o.ranges.map(e=>e.zone),i=zo(s.concat(n),[]);this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:o,ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){const r=this.getters.getSelectedZone();if(ls(e,t,r))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,r.top-1,r.left,r.right),this.steps=r.top-t;break;case"down":this.saveZone(r.bottom+1,t,r.left,r.right),this.steps=t-r.bottom;break;case"left":this.saveZone(r.top,r.bottom,e,r.left-1),this.steps=r.left-e;break;case"right":this.saveZone(r.top,r.bottom,r.right+1,e),this.steps=e-r.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getActivePosition(),t=this.getters.getTable(e);let r=t?t.range.zone.bottom:this.getAutofillAutoLastRow();const n=this.getters.getSelectedZone();for(let t=n.bottom+1;t<=r;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==Nu.empty){r=t-1;break}r>n.bottom&&(this.select(e.col,r),this.autofill(!0))}getAutofillAutoLastRow(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let r=e.left,n=e.bottom;if(r>0){let e={sheetId:t,col:r-1,row:n};for(;this.getters.getEvaluatedCell(e).type!==Nu.empty;)n+=1,e={sheetId:t,col:r-1,row:n}}if(n===e.bottom&&(r=e.right,r<=this.getters.getNumberCols(t))){let e={sheetId:t,col:r+1,row:n};for(;this.getters.getEvaluatedCell(e).type!==Nu.empty;)n+=1,e={sheetId:t,col:r+1,row:n}}return n-1}computeNewCell(e,t,r){const{cellData:n,tooltip:o,origin:s}=e.next(),{content:i,style:a,border:l,format:c}=n;return this.tooltip=o,{originCol:s.col,originRow:s.row,col:t,row:r,content:i,style:a,border:l,format:c}}getRule(e,t){const r=bT.getAll().sort((e,t)=>e.sequence-t.sequence).find(r=>r.condition(e,t));return r&&this.direction&&r.generateRule(e,t,this.direction)}createGenerator(e){const t=[],r=[],n=this.getters.getActiveSheetId();for(const t of e){const{col:e,row:o}=Ho(t),s=this.getters.getCell({sheetId:n,col:e,row:o});r.push({col:e,row:o,cell:s,sheetId:n})}const o=r.map(e=>e.cell);for(const e of r){let r={type:"COPY_MODIFIER"};if(e&&e.cell){r=this.getRule(e.cell,o)||r}const n=this.getters.getCellBorder(e),s=this.getters.getCellStyle(e);t.push({data:{...e,border:n,style:s},rule:r})}return new IT(t,this.getters,this.direction)}saveZone(e,t,r,n){this.autofillZone={top:e,bottom:t,left:r,right:n}}getDirection(e,t){const r=this.getters.getSelectedZone(),n={up:{number:r.top-t,value:"up"},down:{number:t-r.bottom,value:"down"},left:{number:r.left-e,value:"left"},right:{number:e-r.right,value:"right"}};if(1===Object.values(n).map(e=>e.number>0?1:0).reduce((e,t)=>e+t))return Object.values(n).find(e=>e.number>0?1:0).value;const o=n.up.number>0?"up":"down",s=n.left.number>0?"left":"right";return Math.abs(n[o].number)>=Math.abs(n[s].number)?n[o].value:n[s].value}autofillMerge(e,t){const{originCol:r,originRow:n,col:o,row:s}=t,i={sheetId:e,col:o,row:s},a={sheetId:e,col:r,row:n};if(this.getters.isInMerge(i)&&!this.getters.isInMerge(a)){const t=this.getters.getMerge(i);t&&this.dispatch("REMOVE_MERGE",{sheetId:e,target:[t]})}const l=this.getters.getMerge(a);l?.left===r&&l?.top===n&&this.dispatch("ADD_MERGE",{sheetId:e,target:[{top:s,bottom:s+l.bottom-l.top,left:o,right:o+l.right-l.left}]})}drawLayer(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:r}=e,{x:n,y:o,width:s,height:i}=this.getters.getVisibleRect(this.autofillZone);s>0&&i>0&&(t.strokeStyle="black",t.lineWidth=r,t.setLineDash([3]),t.strokeRect(n,o,s,i),t.setLineDash([]))}}).add("sort",class extends Ls{allowDispatch(e){return"SORT_CELLS"===e.type?ls(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):"InvalidSortAnchor":"Success"}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return"Success";return ds(t).some(({col:t,row:r})=>!this.getters.isInMerge({sheetId:e,col:t,row:r}))?"InvalidSortZone":"Success"}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return"Success";const r=this.getters.getMerges(e).filter(e=>as(e,t)),n=us(r[0]),[o,s]=[n.numberOfCols,n.numberOfRows];return r.every(e=>{const[t,r]=[e.right-e.left+1,e.bottom-e.top+1];return t===o&&r===s})?"Success":"InvalidSortZone"}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return ds(t).some(({col:t,row:r})=>{const n=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:r});return n&&!Ae(n,{sheetId:e,col:t,row:r})})?"SortZoneWithArrayFormulas":"Success"}hasHeader(e,t){if(1===t[0].length)return!1;let r=t.map(t=>t.map(({col:t,row:r})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:r}).type));return r[0][0]===Nu.empty&&(r=r.slice(1)),!r.some(e=>e[0]===Nu.empty)&&!!r.some(e=>e[1]!==Nu.empty&&e[0]!==e[1])}sortZone(e,t,r,n,o){const[s,i]=this.mainCellsSteps(e,r),a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},r);let c=this.mainCells(e,r);!o.sortHeaders&&this.hasHeader(e,c)&&(l.top+=i),c=this.mainCells(e,l);const u=function(e,t,r){const n=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(r?n.map(e=>e.type===Nu.empty?{...e,type:Nu.number,value:0}:e):n).sort(Lu(t))}(c[a-l.left].map(e=>this.getters.getEvaluatedCell(e)),n,Boolean(o.emptyCellAsZero)),h=u.map(e=>e.index),[d,f]=[c.length,c[0].length],g=[];for(let t=0;t<d;t++)for(let r=0;r<f;r++){const n=c[t][h[r]],o=this.getters.getCell(n),a=this.getters.getCellStyle(n),u=l.left+t*s,d=l.top+r*i,f={sheetId:n.sheetId,col:u,row:d,content:""};if(o){let t=o.content;if(o.isFormula){const r=this.getters.getCellPosition(o.id);t=this.getters.getTranslatedCellFormula(e,0,d-r.row,o.compiledFormula.tokens)}f.style=a,f.content=t,f.format=o.format}g.push(f)}g.forEach(e=>this.dispatch("UPDATE_CELL",e))}mainCellsSteps(e,t){const r=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[r?r.right-r.left+1:1,r?r.bottom-r.top+1:1]}mainCells(e,t){const[r,n]=this.mainCellsSteps(e,t),o=[],s=le(t.left,t.right+1,r),i=le(t.top,t.bottom+1,n);for(const t of s){const r=[];o.push(r);for(const n of i)r.push({sheetId:e,col:t,row:n})}return o}}).add("automatic_sum",class extends Ls{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:r}=this.getters.getSelection();for(const n of t){const t=this.getAutomaticSums(e,n,r.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,r){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,r):this.sumData(e,t)}sumData(e,t){const r=this.dimensionsToSum(e,t),n=this.sumDimensions(e,t,r).filter(({zone:t})=>!this.getters.isEmpty(e,t));return r.has("ROW")&&r.has("COL")&&n.push(this.sumTotal(t)),n}sumAdjacentData(e,t,r){const{col:n,row:o}=ls(r.col,r.row,t)?r:{col:t.left,row:t.top},s=this.findAdjacentData(e,n,o);return s?this.getters.isSingleCellOrMerge(e,t)||hs(ns(s,t))?[{position:{col:n,row:o},zone:s}]:this.sumDimensions(e,ns(s,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,r){const n=this.getters.getSheet(e),o=this.getters.getMainCellPosition({sheetId:e,col:t,row:r}),s=this.findSuitableZoneToSum(n,o.col,o.row);if(s)return this.getters.expandZone(e,s)}findSuitableZoneToSum(e,t,r){const n=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:r-1}),o=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:r});if(this.isNumber(o)&&!this.isNumber(n))return this.findHorizontalZone(e,t,r);const s=this.findVerticalZone(e,t,r);if(this.isZoneValid(s))return s;const i=this.findHorizontalZone(e,t,r);return this.isZoneValid(i)?i:void 0}findVerticalZone(e,t,r){const n={top:0,bottom:r-1,left:t,right:t},o=this.reduceZoneStart(e,n,n.bottom);return{...n,top:o}}findHorizontalZone(e,t,r){const n={top:r,bottom:r,left:0,right:t-1},o=this.reduceZoneStart(e,n,n.right);return{...n,left:o}}reduceZoneStart(e,t,r){const n=this.getters.getEvaluatedCellsInZone(e.id,t),o=le(r,-1,-1),s=We(o.filter(e=>n[e]&&!n[e].isAutoSummable)),i=ce(o.filter(e=>this.isNumber(n[e])))[0]||[];return We(i)<s?1/0:qe(i)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===Nu.number&&!(e.format&&on(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const r=new Set;return hs(t)?(r.add(1===us(t).numberOfCols?"COL":"ROW"),r):(this.lastColIsEmpty(e,t)&&r.add("ROW"),this.lastRowIsEmpty(e,t)&&r.add("COL"),0===r.size&&r.add("COL"),r)}sumDimensions(e,t,r){return[...r.has("COL")?this.sumColumns(t,e):[],...r.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:r}=e;return{position:{col:r,row:t},zone:{...e,top:t,right:r-1}}}sumColumns(e,t){const r=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,r.bottom-1)},ds(r).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){const r=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,r.right-1)},ds(r).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(const r of t){const{col:t,row:n}=r.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,content:`=SUM(${this.getters.zoneToXC(e,r.zone)})`})}}nextEmptyRow(e,t){let r=t.bottom+1;const{left:n,right:o}=t;for(;!this.getters.isEmpty(e,{bottom:r,top:r,left:n,right:o});)r++;return{...t,top:r,bottom:r}}nextEmptyCol(e,t){let r=t.right+1;const{top:n,bottom:o}=t;for(;!this.getters.isEmpty(e,{left:r,right:r,top:n,bottom:o});)r++;return{...t,left:r,right:r}}transpose(e){return new Set([...e.values()].map(e=>"COL"===e?"ROW":"COL"))}}).add("format",class extends Ls{handle(e){switch(e.type){case"SET_DECIMAL":this.setDecimal(e.sheetId,e.target,e.step);break;case"SET_FORMATTING_WITH_PIVOT":this.setContextualFormat(e.sheetId,e.target,e.format)}}setContextualFormat(e,t,r){const n=[],o={};for(const r of zo(t))for(let t=r.left;t<=r.right;t++)for(let s=r.top;s<=r.bottom;s++){const r={sheetId:e,col:t,row:s},i=this.getters.getPivotCellFromPosition(r);if(this.isSpilledPivotValueFormula(r,i)){n.push(r);const e=this.getters.getPivotIdFromPosition(r)||"";o[e]??=new Set,o[e].add(i.measure)}}const s=zo(n.map(ps));for(const e in o){const t=o[e],n=this.getters.getPivotCoreDefinition(e);this.dispatch("UPDATE_PIVOT",{pivotId:e,pivot:{...n,measures:n.measures.map(e=>t.has(e.id)?{...e,format:r}:e)}})}this.dispatch("SET_FORMATTING",{sheetId:e,target:s,format:""}),this.dispatch("SET_FORMATTING",{sheetId:e,target:zo(t,s),format:r})}isSpilledPivotValueFormula(e,t){const r=this.getters.getCell(e);return"VALUE"===t.type&&!r?.isFormula}setDecimal(e,t,r){const n={};for(const o of zo(t))for(const t of ds(o)){const o=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==o){const e=gn(o,r);n[e]=n[e]||[],n[e].push(t)}}for(const t in n){const r=zo(n[t].map(e=>ps(e)));this.setContextualFormat(e,r,t)}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==Nu.number||e.format&&on(e.format)))return e.format||ln(e.value)}}}).add("insert_pivot",class extends Ls{static getters=[];allowDispatch(e){if("DUPLICATE_PIVOT_IN_NEW_SHEET"===e.type){if(!this.getters.isExistingPivot(e.pivotId))return"PivotIdNotFound";if(!this.getters.getPivot(e.pivotId).isValid())return"PivotInError"}return"Success"}handle(e){switch(e.type){case"INSERT_NEW_PIVOT":this.insertNewPivot(e.pivotId,e.newSheetId);break;case"DUPLICATE_PIVOT_IN_NEW_SHEET":this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case"INSERT_PIVOT_WITH_TABLE":this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case"SPLIT_PIVOT_FORMULA":this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){1===Es(this.getters.getSelectedZone())&&this.selection.selectTableAroundSelection();const r=this.getters.getActiveSheetId();this.dispatch("ADD_PIVOT",{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:r},columns:[],rows:[],measures:[],name:v("New pivot"),type:"SPREADSHEET"}});const n=this.getters.getSheetIds().findIndex(e=>e===r)+1,o=this.getters.getPivotFormulaId(e);this.dispatch("CREATE_SHEET",{sheetId:t,name:v("Pivot #%(formulaId)s",{formulaId:o}),position:n}),this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:r,sheetIdTo:t});const s=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,s.getCollapsedTableStructure().export(),"dynamic")}duplicatePivotInNewSheet(e,t,r){this.dispatch("DUPLICATE_PIVOT",{pivotId:e,newPivotId:t,duplicatedPivotName:v("%s (copy)",this.getters.getPivotCoreDefinition(e).name)});const n=this.getters.getActiveSheetId(),o=this.getters.getSheetIds().indexOf(n)+1,s=this.getters.getPivotFormulaId(t),i=this.getters.getPivotName(t);if(this.dispatch("CREATE_SHEET",{sheetId:r,name:this.getPivotDuplicateSheetName(v("%(newPivotName)s (Pivot #%(formulaId)s)",{newPivotName:i,formulaId:s})),position:o}).isSuccessful){this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:n,sheetIdTo:r});const o=this.getters.getPivot(e);this.insertPivotWithTable(r,0,0,t,o.getCollapsedTableStructure().export(),"dynamic")}}getPivotDuplicateSheetName(e){const t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return Xe(ie(e),t)}insertPivotWithTable(e,t,r,n,o,s){const{cols:i,rows:a,measures:l,fieldsType:c}=o,u=new lS(i,a,l,c||{}),h=u.columns.length-1;this.resizeSheet(e,t,r,u);const d=this.getters.getPivotFormulaId(n);let f;"dynamic"===s?(this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:r,content:`=PIVOT(${d})`}),f={left:t,right:t,top:r,bottom:r}):(this.dispatch("INSERT_PIVOT",{sheetId:e,col:t,row:r,pivotId:n,table:u.export()}),f={left:t,right:t+u.getNumberOfDataColumns(),top:r,bottom:r+h+u.rows.length}),this.dispatch("CREATE_TABLE",{tableType:s,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,f)],config:{...J,numberOfHeaders:h}})}resizeSheet(e,t,r,n){const o=n.getNumberOfDataColumns()+1,s=this.getters.getNumberCols(e),i=s-t;i<o&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:s-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o-i,position:"after"});const a=n.columns.length+n.rows.length,l=this.getters.getNumberRows(e),c=l-r;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}splitPivotFormula(e,t,r,n){const o=this.getters.getSpreadZone({sheetId:e,col:t,row:r});if(!o)return;const s=this.getters.getPivotFormulaId(n),i=new Map;for(let t=o.left;t<=o.right;t++)for(let r=o.top;r<=o.bottom;r++){const n={sheetId:e,col:t,row:r};i.set(n,this.getters.getPivotCellFromPosition(n))}for(const[e,t]of i)this.dispatch("UPDATE_CELL",{...e,content:Xd(s,t)});const a=this.getters.getCoreTable({sheetId:e,col:t,row:r});if("dynamic"===a?.type){const n=ps({col:t,row:r}),s=this.getters.getRangeDataFromZone(e,o);this.dispatch("UPDATE_TABLE",{sheetId:e,zone:n,newTableRange:s,tableType:"static"})}}}).add("pivot_presence",class extends Ls{static getters=["getPivotPresenceTracker"];trackPresencePivotId;tracker;handle(e){switch(e.type){case"PIVOT_START_PRESENCE_TRACKING":this.tracker=new DT,this.trackPresencePivotId=e.pivotId;break;case"PIVOT_STOP_PRESENCE_TRACKING":this.trackPresencePivotId=void 0}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw new Error("Tracker not initialized");return this.tracker}}}).add("split_to_columns",class extends Ls{static getters=["getAutomaticSeparator"];allowDispatch(e){return"SPLIT_TEXT_INTO_COLUMNS"===e.type?this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e):"Success"}handle(e){if("SPLIT_TEXT_INTO_COLUMNS"===e.type)this.splitIntoColumns(e)}getAutomaticSeparator(){const e=this.getters.getSelectedCells();for(const t of e)if(t.value&&t.type===Nu.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[Q,";",","," ","."];for(const r of t)if(e.includes(r))return r}splitIntoColumns({separator:e,addNewColumns:t}){const r=this.getters.getSelectedZone(),n=this.getters.getActiveSheetId(),o=this.getSplittedCols(r,e);t&&this.addColsToAvoidCollisions(r,o),this.removeMergesInSplitZone(r,o),this.addColumnsToNotOverflowSheet(r,o);for(let e=0;e<o.length;e++){const t=r.top+e,s=o[e],i=r.left,a=this.getters.getCell({sheetId:n,col:i,row:t}),l=this.getters.getCellStyle({sheetId:n,col:i,row:t});if(1!==s.length||s[0]!==a?.content)for(const[e,r]of s.entries())this.dispatch("UPDATE_CELL",{sheetId:n,col:i+e,row:t,content:cc(r,this.getters.getLocale()),format:"",style:{...SS,...l}})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const r=this.getters.getActiveSheetId(),n=[];for(const o of le(e.top,e.bottom+1)){const s=this.getters.getEvaluatedCell({sheetId:r,col:e.left,row:o}).formattedValue;n.push(this.splitAndRemoveTrailingEmpty(s,t))}return n}splitAndRemoveTrailingEmpty(e,t){const r=e.split(t);for(;r.length>1&&""===r[r.length-1];)r.pop();return r}willSplittedColsOverwriteContent(e,t){const r=this.getters.getActiveSheetId();for(const n of le(e.top,e.bottom+1)){const o=t[n-e.top];for(let t=1;t<o.length;t++){const o=this.getters.getCell({sheetId:r,col:e.left+t,row:n});if(o&&o.content)return!0}}return!1}removeMergesInSplitZone(e,t){const r=this.getters.getActiveSheetId(),n=Math.max(...t.map(e=>e.length)),o={...e,right:e.left+n-1},s=this.getters.getMergesInZone(r,o);this.dispatch("REMOVE_MERGE",{sheetId:r,target:s})}addColsToAvoidCollisions(e,t){const r=this.getters.getActiveSheetId();let n=0;for(const o of le(e.top,e.bottom+1)){const s={sheetId:r,col:e.left,row:o},i=t[o-e.top],a=this.getColsToAddToAvoidCollision(s,i);n=Math.max(n,a)}n&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:r,sheetName:this.getters.getSheetName(r),quantity:n,position:"after"})}getColsToAddToAvoidCollision(e,t){const r=t.length;for(let t=1;t<r;t++){const n=e.col+t,o=this.getters.getCell({...e,col:n});if(o&&o.content)return r-t}return 0}addColumnsToNotOverflowSheet(e,t){const r=this.getters.getActiveSheetId(),n=Math.max(...t.map(e=>e.length-1)),o=this.getters.getNumberCols(r)-1;e.left+n>o&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:o,sheetId:r,sheetName:this.getters.getSheetName(r),quantity:e.left+n-o,position:"after"})}checkSingleColSelected(){return this.getters.isSingleColSelected()?"Success":"MoreThanOneColumnSelected"}checkNonEmptySelector(e){return""===e.separator?"EmptySplitSeparator":"Success"}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return"Success";const t=this.getters.getSelectedZones()[0],r=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,r)?"SplitWillOverwriteContent":"Success"}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const r of t)if(r.formattedValue.includes(e))return"Success";return"NoSplitSeparatorInSelection"}}).add("subtotal_evaluation",class extends Ls{subtotalCells=new Set;handle(e){switch(e.type){case"START":this.subtotalCells.clear();for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t){const r=t[e];Ps(r)&&this.subtotalCells.add(r.id)}}break;case"UPDATE_CELL":{if(!("content"in e))return;const t=this.getters.getCell(e);if(!t)return;Ps(t)?this.subtotalCells.add(t.id):this.subtotalCells.delete(t.id);break}}As.has(e.type)&&this.dispatch("EVALUATE_CELLS",{cellIds:Array.from(this.subtotalCells)})}}).add("collaborative",class extends Ls{static getters=["getClientsToDisplay","getClient","getCurrentClient","getConnectedClients","isFullySynchronized"];static layers=["Selection"];colors=new kp(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map(e=>({...e,color:this.colors.get(e.id)}))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getCurrentClient()}catch(e){if(e instanceof av)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const r of this.getters.getConnectedClients())r.id!==this.getters.getCurrentClient().id&&r.position&&r.position.sheetId===e&&this.isPositionValid(r.position)&&t.push({...r,position:r.position});return t}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:r}=e,n=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:o,col:s}=e.position,i=this.getters.expandZone(n,{top:o,bottom:o,left:s,right:s}),{x:a,y:l,width:c,height:u}=this.getters.getVisibleRect(i);if(c<=0||u<=0)continue;const h=e.color;t.fillStyle=`${h}10`,t.lineWidth=4*r,t.strokeStyle=h,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,u),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,u),t.font=`bold ${q+1}px ${Z}`}}}).add("history",class extends Ls{static getters=["canUndo","canRedo"];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("snapshot",this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return"EmptyUndoStack";break;case"REQUEST_REDO":if(!this.canRedo())return"EmptyRedoStack"}return"Success"}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();if(!t){const e=this.getPossibleRevisionToRepeat();if(!e)return;const t=_T(e,this.getters);if(!t)return;if(!Array.isArray(t))return void this.dispatch(t.type,t);for(const e of t)this.dispatch(e.type,e);return}"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(){if(this.redoStack.length>0)return!0;const e=this.getPossibleRevisionToRepeat();return!(!(t=e)||!t.rootCommand||"object"!=typeof t.rootCommand)&&(Ds(t.rootCommand)?AT.contains(t.rootCommand.type):OT.contains(t.rootCommand.type));var t}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}}).add("table_autofill",class extends Ls{handle(e){if("AUTOFILL_TABLE_COLUMN"===e.type){const t=this.getters.getCoreTable(e),r=this.getters.getCell(e);if(!t?.config.automaticAutofill||"dynamic"===t.type||!r?.isFormula)return;const{col:n,row:o}=e,s=function(e,t){const r=t.numberOfHeaders,n={...e,top:e.top+r};return n.top<=n.bottom?n:void 0}(t.range.zone,t.config);if(s&&ls(n,o,s)){const t=e.autofillRowStart??s.top,r=e.autofillRowEnd??s.bottom,n={...s,top:t,bottom:r};this.autofillTableZone(e,n)}}}autofillTableZone(e,t){if(t.top===t.bottom)return;const{col:r,row:n,sheetId:o}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==n&&this.getters.getEvaluatedCell({col:r,row:e,sheetId:o}).type!==Nu.empty)return;const s={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(r,n),this.dispatch("AUTOFILL_SELECT",{col:r,row:t.bottom}),this.dispatch("AUTOFILL"),this.selection.selectCell(r,n),this.dispatch("AUTOFILL_SELECT",{col:r,row:t.top}),this.dispatch("AUTOFILL"),this.selection.selectZone(s)}}).add("table_ui_resize",class extends Ls{allowDispatch(e){if("RESIZE_TABLE"===e.type){const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return"TableNotFound";const r=t.range.zone,n=this.getters.getRangeFromRangeData(e.newTableRange).zone;return n.top!==r.top||n.left!==r.left?"InvalidTableResize":this.canDispatch("UPDATE_TABLE",{...e}).reasons}return"Success"}handle(e){switch(e.type){case"RESIZE_TABLE":{const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch("UPDATE_TABLE",{...e}),!t)return;const r=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(r.right,r.bottom),!t.config.automaticAutofill)return;const n=t.range.zone;if(r.bottom>=n.bottom){for(let t=r.left;t<=r.right;t++){const o={col:t,row:n.bottom,sheetId:e.sheetId};this.getters.getCell(o)?.content.startsWith("=")&&this.dispatch("AUTOFILL_TABLE_COLUMN",{...o,autofillRowStart:n.bottom,autofillRowEnd:r.bottom})}break}}}}}).add("datavalidation_insert",class extends Ls{handle(e){if("ADD_DATA_VALIDATION_RULE"===e.type)if("isBoolean"===e.rule.criterion.type){const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(const e of $m(t)){const t=this.getters.getCell(e),r=this.getters.getEvaluatedCell(e);if(t?.content)if(t?.content&&r.type===Nu.empty){let r;if(t.content.startsWith("=")){const n=this.getters.evaluateFormula(e.sheetId,t.content);r=(D(n)?n[0][0]:n)?.toString()}else r=t.content;r&&he(r)||this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}else r.type!==Nu.boolean&&this.dispatch("UPDATE_CELL",{...e,content:"FALSE"});else this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}}}}).add("checkbox_toggle",class extends Ls{static getters=["hasBooleanValidationInZones"];handle(e){if("TOGGLE_CHECKBOX"===e.type)this.toggleCheckbox(e.sheetId,e.target)}hasBooleanValidationInZones(e){const t=this.getters.getActiveSheetId();for(const r of e)for(let e=r.left;e<=r.right;e++)for(let n=r.top;n<=r.bottom;n++)if(this.getters.isCellValidCheckbox({col:e,row:n,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(const r of t)for(let t=r.left;t<=r.right;t++)for(let n=r.top;n<=r.bottom;n++){const r={col:t,row:n,sheetId:e};if(this.getters.isCellValidCheckbox(r)){const e=this.getters.getEvaluatedCell(r).value?"FALSE":"TRUE";this.dispatch("UPDATE_CELL",{...r,content:e})}}}}).add("dynamic_translate",class extends Ls{static getters=["dynamicTranslate"];dynamicTranslate(e){return e}}).add("geo_features",class extends Ls{static getters=["getGeoJsonFeatures","geoFeatureNameToId","getGeoChartAvailableRegions"];geoJsonService;geoJsonCache={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error("No geoJsonService provided to the model"),[])}getGeoJsonFeatures(e){if(!this.geoJsonService)return void console.error("No geoJsonService provided to the model");const t=this.geoJsonCache[e];return t instanceof Promise?void 0:void 0!==t?t??void 0:void(this.geoJsonCache[e]=new Promise(async t=>{const r=await(this.geoJsonService?.getTopoJson(e));this.geoJsonCache[e]=this.convertToGeoJson(r),this.dispatch("EVALUATE_CHARTS"),t()}))}geoFeatureNameToId(e,t){if(this.geoJsonService)return this.geoJsonService.geoFeatureNameToId(e,t);console.error("No geoJsonService provided to the model")}convertToGeoJson(e){if(!e)return null;if("Topology"===e.type){const t=globalThis.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return"FeatureCollection"===t.type?t.features:[t]}if("FeatureCollection"===e.type)return e.features;throw new Error("Invalid TopoJSON")}}),GT=(new h).add("selection",class extends Ls{static layers=["Selection"];static getters=["getActiveSheet","getActiveSheetId","getActiveSheetName","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId","isGridSelectionActive","getSelectecUnboundedZone"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;isUnbounded;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient,this.isUnbounded=!1}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return"SheetIsHidden";break}catch(e){return"InvalidSheetId"}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return"Success"}handleEvent(e){let t=e.anchor,r=[...this.gridSelection.zones];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case"overrideSelection":r=[t.zone];break;case"updateAnchor":const n=r.findIndex(t=>ss(t,e.previousAnchor.zone));n>=0&&(r[n]=t.zone);break;case"newAnchor":r.push(t.zone);break;case"commitSelection":const o=r.find(e=>cs(t.zone,e)&&!ss(t.zone,e));if(r.filter(e=>ss(t.zone,e)).length>1&&r.length>2)r=r.filter(e=>!ss(e,t.zone));else if(o){const e=function(e,t){const r=[];return e.bottom<t.bottom&&r.push({...t,top:e.bottom+1}),e.right<t.right&&r.push({...t,left:e.right+1,top:e.top,bottom:e.bottom}),e.left>t.left&&r.push({...t,right:e.left-1,top:e.top,bottom:e.bottom}),e.top>t.top&&r.push({...t,bottom:e.top-1}),r}(t.zone,o);r=r.filter(e=>!ss(e,t.zone)&&!ss(e,o)).concat(e)}r=function(e){return e.reverse().filter((e,t,r)=>t===r.findIndex(t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)).reverse()}(r);const s=r[r.length-1];t={cell:{col:s.left,row:s.top},zone:s}}this.setSelectionMixin(t,r),this.selection.resetDefaultAnchor(this,re(this.gridSelection.anchor));const{col:n,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:n,row:o}),this.selectedFigureId=null}handle(e){switch(e.type){case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.figureId&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);const{col:r,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(r,n),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:r,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:r,row:n})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:r,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:r,row:n})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.figureId;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":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 t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:re(t)}}this.fallbackToVisibleSheet();const s=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(s,e)),this.gridSelection.anchor.zone=this.getters.expandZone(s,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,re(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveSheetName(){return this.activeSheet.name}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(const t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let r=t.left;r<=t.right;r++)e.add(r);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(const r of this.gridSelection.zones)if(0===r.left&&r.right===this.getters.getNumberCols(t)-1)for(let t=r.top;t<=r.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})??{}}getSelectedZones(){return re(this.gridSelection.zones)}getSelectedZone(){return re(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return re(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return re(this.gridSelection)}getSelectedCells(){const e=this.getters.getActiveSheetId(),t=[];for(const r of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,r));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){const e=this.getters.getSelectedZones();return 1===e.length&&e[0].left===e[0].right}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 r=[];const n="COL"===e?"left":"top",o="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[o]-e[n]+1},(t,r)=>e[n]+r);r=r.concat(t)}return[...new Set(r)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:re(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,re(this.gridSelection.anchor));else{const{col:e,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,r)}const{col:r,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:r,row:n})}setSelectionMixin(e,t){const{anchor:r,zones:n}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=r,this.gridSelection.zones=n}selectCell(e,t){const r=this.getters.getActiveSheetId(),n=this.getters.expandZone(r,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:n,cell:{col:e,row:t}},[n])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){const t=this.getters.getSheetIds(),r=(t.findIndex(e=>e===this.activeSheet.id)+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[r]})}onColumnsRemoved(e){const{cell:t,zone:r}=this.gridSelection.anchor,n=rs(r,"left",[...e.elements]);let o={left:t.col,right:t.col,top:t.row,bottom:t.row};o=rs(o,"left",[...e.elements]);const s={cell:{col:o.left,row:o.top},zone:n},i=this.gridSelection.zones.map(t=>rs(t,"left",[...e.elements]));this.setSelectionMixin(s,i)}onRowsRemoved(e){const{cell:t,zone:r}=this.gridSelection.anchor,n=rs(r,"top",[...e.elements]);let o={left:t.col,right:t.col,top:t.row,bottom:t.row};o=rs(o,"top",[...e.elements]);const s={cell:{col:o.left,row:o.top},zone:n},i=this.gridSelection.zones.map(t=>rs(t,"top",[...e.elements]));this.setSelectionMixin(s,i)}onAddElements(e){const t="COL"===e.dimension?"left":"top",r=ts(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),n=this.gridSelection.zones.map(r=>ts(r,t,e.base,e.position,e.quantity)),o={cell:{col:r.left,row:r.top},zone:r};this.setSelectionMixin(o,n)}onMoveElements(e){const t=e.elements.length,r=this.getFiguresUpdates(e);this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,base:e.base,quantity:t,position:e.position});const n="COL"===e.dimension,o=e.elements[0],s=e.elements[t-1],i=e.base<o,a=i&&n?t:0,l=i&&!n?t:0,c=i?e.elements.map(e=>e+t):e.elements,u={};for(const t of c)u[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);const h=[{left:n?o+a:0,right:n?s+a:this.getters.getNumberCols(e.sheetId)-1,top:n?0:o+l,bottom:n?this.getters.getNumberRows(e.sheetId)-1:s+l}],d=this.getActiveSheetId(),f=i?e.base:e.base+1,g=[{left:n?f:0,right:n?f+t-1:this.getters.getNumberCols(e.sheetId)-1,top:n?0:f,bottom:n?this.getters.getNumberRows(e.sheetId)-1:f+t-1}],m=PT.cellHandlers.getKeys().map(e=>[e,new(PT.cellHandlers.get(e))(this.getters,this.dispatch)]),p={};for(const[e,t]of m)p[e]=t.copy(LT(d,h),!1,"shiftCells");for(const[e,t]of m)p[e]&&t.paste({zones:g,sheetId:d},p[e],{isCutOperation:!0});const b=g[0],v=b.left,y=b.top;this.setSelectionMixin({zone:b,cell:{col:v,row:y}},[b]);let E=i?e.base:e.base+1;const w={};for(const t of c){const r=u[t];r!==this.getters.getHeaderSize(e.sheetId,e.dimension,E)&&(w[r]??=[],w[r].push(E)),E+=1}for(const t in w)this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:w[t]});this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:c}),this.applyFigureUpdates(r)}getFiguresUpdates(e){const t=[],r={},n=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)r[e.elements[t]]=n+t;for(const n of this.getters.getFigures(e.sheetId))"COL"===e.dimension&&n.col in r&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:n.id,col:r[n.col],row:n.row}),"ROW"===e.dimension&&n.row in r&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:n.id,row:r[n.row],col:n.col});return t}applyFigureUpdates(e){for(const t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){const t="COL"===e.dimension,r=e.elements[0],n=e.elements[e.elements.length-1],o=e.sheetId,s=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(s(o,r-1,r)||s(o,n,n+1)||s(o,e.base-1,e.base))return"WillRemoveExistingMerge";const i=[e.base,...e.elements],a=t?this.getters.getNumberCols(o):this.getters.getNumberRows(o);return i.some(e=>e<0||e>=a)?"InvalidHeaderIndex":t||this.isTableRowMoveAllowed(o,e.elements)?"Success":"CannotMoveTableHeader"}isTableRowMoveAllowed(e,t){const r=this.getters.getCoreTables(e);if(0===r.length)return!0;const n=new Set(t);return r.every(({range:{zone:e},config:r})=>{const{top:o,bottom:s}=e;if(0===r.numberOfHeaders)return!0;const i=o+r.numberOfHeaders-1;if(!t.some(e=>e>=o&&e<=i))return!0;return le(o,s+1).every(e=>n.has(e))})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:r})}}clipSelection(e,t){const r=this.getters.getNumberCols(e)-1,n=this.getters.getNumberRows(e)-1;return{zones:t.zones.map(e=>({left:ae(e.left,0,r),right:ae(e.right,0,r),top:ae(e.top,0,n),bottom:ae(e.bottom,0,n)})),anchor:{cell:{col:ae(t.anchor.cell.col,0,r),row:ae(t.anchor.cell.row,0,n)},zone:{left:ae(t.anchor.zone.left,0,r),right:ae(t.anchor.zone.right,0,r),top:ae(t.anchor.zone.top,0,n),bottom:ae(t.anchor.zone.bottom,0,n)}}}}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:r}=e,n=this.getSelectedZones();t.fillStyle="#f3f7fe";const o=1===n.length&&n[0].left===n[0].right&&n[0].top===n[0].bottom;t.fillStyle=o?"#f3f7fe":"#e9f0ff",t.strokeStyle=M,t.lineWidth=1.5*r;for(const e of n){const{x:r,y:n,width:o,height:s}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(r,n,o,s),t.globalCompositeOperation="source-over",t.strokeRect(r,n,o,s)}t.globalCompositeOperation="source-over";const s=this.getActivePosition();let i;t.strokeStyle=M,t.lineWidth=3*r,i=this.getters.isInMerge(s)?this.getters.getMerge(s):ps(s);const{x:a,y:l,width:c,height:u}=this.getters.getVisibleRect(i);c>0&&u>0&&t.strokeRect(a,l,c,u)}}).add("evaluation_filter",class extends Ls{static getters=["getFilterValue","getFilterHiddenValues","getFilterCriterionValue","getFirstTableInSelection","isRowFiltered","isFilterActive"];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return"FilterNotFound";return"Success"}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_TABLE":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":case"UPDATE_TABLE":this.isEvaluationDirty=!0;break;case"START":for(const e of this.getters.getSheetIds())this.filterValues[e]={};break;case"CREATE_SHEET":this.filterValues[e.sheetId]={};break;case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"GROUP_HEADERS":case"UNGROUP_HEADERS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_ALL_HEADER_GROUPS":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":this.updateHiddenRows(e.sheetId);break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case"DUPLICATE_SHEET":this.filterValues[e.sheetIdTo]=re(this.filterValues[e.sheetId])}}finalize(){if(this.isEvaluationDirty){for(const e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){const t=this.getters.getFilterId(e),r=e.sheetId;return t?this.filterValues[r]?.[t]:void 0}getFilterHiddenValues(e){const t=this.getters.getFilterId(e),r=e.sheetId;if(!t||!this.filterValues[r])return[];const n=this.filterValues[r][t]||[];return"values"===n.filterType?n.hiddenValues:[]}getFilterCriterionValue(e){const t=this.getters.getFilterId(e),r=e.sheetId;if(!t||!this.filterValues[r])return UT;const n=this.filterValues[r][t];return n&&"criterion"===n.filterType?n:UT}isFilterActive(e){const t=this.getters.getFilterId(e);if(!t)return!1;const r=e.sheetId,n=this.filterValues[r]?.[t];return!!n&&("values"===n.filterType?n.hiddenValues.length>0:"none"!==n.type)}getFirstTableInSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:r,sheetId:n}){const o=this.getters.getFilterId({sheetId:n,col:e,row:t});o&&(this.filterValues[n]||(this.filterValues[n]={}),this.filterValues[n][o]=r)}updateHiddenRows(e){const t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),r=new Set;for(const n of t){const t=this.filterValues[e]?.[n.id],o=n.filteredRange?.zone;if(t&&o&&!r.has(n.rangeWithHeaders.zone.top)&&!this.getters.isRowHiddenByUser(e,n.rangeWithHeaders.zone.top))if("values"===t.filterType){const s=t.hiddenValues?.map(NC);if(!s)continue;const i=new Set(s);for(let t=o.top;t<=o.bottom;t++){const o=this.getCellValueAsString(e,n.col,t);i.has(o)&&r.add(t)}}else{if("none"===t.type)continue;const s=Pw.get(t.type),i=t.values.map(t=>t.startsWith("=")?this.getters.evaluateFormula(e,t)??"":uE(t,xr));if(i.some(Dn))continue;const a={type:t.type,values:i.map(On),dateValue:t.dateValue};for(let t=o.top;t<=o.bottom;t++){const o={sheetId:e,col:n.col,row:t},i=this.getters.getEvaluatedCell(o).value??"";s.isValueValid(i,a,this.getters,e)||r.add(t)}}}this.hiddenRows[e]=r}getCellValueAsString(e,t,r){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:r}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const r of t.tables){const n=Ko(r.range),o=[],s=[];for(const r of le(0,us(n).numberOfCols)){const i={sheetId:t.id,col:n.left+r,row:n.top},a=this.getFilterHiddenValues(i),l=this.getters.getFilter(i),c=l?.filteredRange?ds(l.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(a.length){const e=c.filter(e=>e).filter(e=>!a.includes(e));o.push({colId:r,displayedValues:[...new Set(e)],displayBlanks:!a.includes("")&&c.some(e=>!e)})}const u=this.getters.getEvaluatedCell(i).formattedValue,h=this.getUniqueColNameForExcel(r,u,s);s.push(h);const d=Bo(i.col,i.row);t.cells[d]=h,t.cellValues[d]=h}r.filters=o}}}getUniqueColNameForExcel(e,t,r){return t||(t=`Column${e}`),Xe(t,r,{compute:(e,r)=>t+String(r),start:2})}}).add("header_visibility_ui",class extends Ls{static getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,r){return"COL"===t?this.isColHidden(e,r):this.isRowHidden(e,r)}getNextVisibleCellPosition({sheetId:e,col:t,row:r}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",r,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,r,n){if(r<=n)for(let o=r;o<=n;o++)if(this.getters.doesHeaderExist(e,t,o)&&!this.isHeaderHidden(e,t,o))return o;if(r>n)for(let o=r;o>=n;o--)if(this.getters.doesHeaderExist(e,t,o)&&!this.isHeaderHidden(e,t,o))return o}findLastVisibleColRowIndex(e,t,{last:r,first:n}){return le(r,n,-1).find(r=>!this.isHeaderHidden(e,t,r))||n}findFirstVisibleColRowIndex(e,t){const r=this.getters.getNumberHeaders(e,t);for(let n=0;n<r;n++){if("COL"===t&&!this.isColHidden(e,n))return n;if("ROW"===t&&!this.isRowHidden(e,n))return n}}exportForExcel(e){for(const t of e.sheets)for(const[e,r]of Object.entries(t.rows))r.isHidden=this.isRowHidden(t.id,Number(e))}}).add("cell_computed_style",class extends Ls{static getters=["getCellComputedBorder","getCellComputedStyle"];styles=new Nw;borders=new Nw;handle(e){if(Cs.has(e.type)||"UPDATE_CELL"===e.type||"SET_FORMATTING"===e.type||"ADD_DATA_VALIDATION_RULE"===e.type||"REMOVE_DATA_VALIDATION_RULE"===e.type||"EVALUATE_CELLS"===e.type)return this.styles=new Nw,void(this.borders=new Nw);RT(e)?"sheetId"in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new Nw,this.borders=new Nw):xs.has(e.type)?this.styles=new Nw:Rs.has(e.type)&&(this.borders=new Nw)}getCellComputedBorder(e,t){let r=this.borders.get(e);return void 0===r&&(this.precomputeCellBorders(e.sheetId,t??ps(e)),r=this.borders.get(e)),r??null}precomputeCellBorders(e,t){const r=this.getters.getCellBordersInZone(e,t),n=this.getters.getCellTableBorderZone(e,t);for(let o=t.left;o<=t.right;o++)for(let s=t.top;s<=t.bottom;s++){const t={sheetId:e,col:o,row:s};if(void 0!==this.borders.get(t))continue;const i=r.get(t),a={...Fe(n.get(t)),...Fe(i)};Ce(a)?this.borders.set(t,null):this.borders.set(t,a)}}getCellComputedStyle(e,t){let r=this.styles.get(e);return void 0===r&&(this.precomputeCellStyle(e.sheetId,t??ps(e)),r=this.styles.get(e)??{}),r}precomputeCellStyle(e,t){const r=this.getters.getCellStyleInZone(e,t),n=this.getters.getCellTableStyleZone(e,t);for(let o=t.left;o<=t.right;o++)for(let s=t.top;s<=t.bottom;s++){const t={sheetId:e,col:o,row:s};if(void 0!==this.styles.get(t))continue;const i={...Fe(n.get(t)),...Fe(this.getters.getDataValidationCellStyle(t)),...Fe(r.get(t)),...Fe(this.getters.getCellConditionalFormatStyle(t))};this.getters.getEvaluatedCell(t).link&&!i.textColor&&(i.textColor=L),this.styles.set(t,i)}}}).add("table_computed_style",class extends Ls{static getters=["getCellTableStyle","getCellTableBorder","getCellTableBorderZone","getCellTableStyleZone"];tableStyles={};handle(e){Cs.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type?this.tableStyles={}:RT(e)&&("sheetId"in e?delete this.tableStyles[e.sheetId]:this.tableStyles={})}finalize(){for(const e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(const t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){const t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableStyleZone(e,t){const r=new Nw;for(const n of this.getters.getTablesOverlappingZones(e,[t])){const t=this.tableStyles[e][n.id]().styles;for(const n of Object.keys(t)){const o=t[n],s=parseInt(n);for(const t of Object.keys(o)){const n=o[t];n&&r.set({sheetId:e,col:s,row:parseInt(t)},n)}}}return r}getCellTableBorder(e){const t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}getCellTableBorderZone(e,t){const r=new Nw;for(const n of this.getters.getTablesOverlappingZones(e,[t])){const t=this.tableStyles[e][n.id]().borders;for(const n of Object.keys(t)){const o=t[n],s=parseInt(n);for(const t of Object.keys(o)){const n=o[t];n&&r.set({sheetId:e,col:s,row:parseInt(t)},n)}}}return r}computeTableStyle(e,t){return xe(()=>{const{config:r,numberOfCols:n,numberOfRows:o}=this.getTableRuntimeConfig(e,t),s=function(e,t,r,n){return{borders:IS(e,t,r,n),styles:RS(e,t,r,n)}}(r,this.getters.getTableStyle(t.config.styleId),n,o),i=this.getTableMapping(e,t),a={borders:{},styles:{}};for(let e=0;e<n;e++){const t=i.colMapping[e];a.borders[t]={},a.styles[t]={};for(let r=0;r<o;r++){const n=i.rowMapping[r];a.borders[t][n]=s.borders[e][r],a.styles[t][n]=s.styles[e][r]}}return a})}getTableRuntimeConfig(e,t){const r=t.range.zone,n={...t.config};let o=r.right-r.left+1,s=r.bottom-r.top+1;for(let o=r.top;o<=r.bottom;o++)this.getters.isRowHidden(e,o)&&(s--,o-r.top<t.config.numberOfHeaders&&(n.numberOfHeaders--,n.numberOfHeaders<0&&(n.numberOfHeaders=0)),o===r.bottom&&(n.totalRow=!1));for(let t=r.left;t<=r.right;t++)this.getters.isColHidden(e,t)&&(o--,t===r.left&&(n.firstColumn=!1),t===r.right&&(n.lastColumn=!1));return{config:n,numberOfCols:o,numberOfRows:s}}getTableMapping(e,t){const r={},n={};let o=0,s=0;const i=t.range.zone;for(let t=i.left;t<=i.right;t++)if(!this.getters.isColHidden(e,t)){r[o]=t,o++;for(let t=i.top;t<=i.bottom;t++)this.getters.isRowHidden(e,t)||(n[s]=t,s++)}return{colMapping:r,rowMapping:n}}}).add("header_positions",class extends Ls{static getters=["getColDimensions","getRowDimensions","getColRowOffset"];headerPositions={};isDirty=!0;handle(e){switch(Cs.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case"START":for(const e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case"UPDATE_CELL":case"SET_FORMATTING":case"CLEAR_FORMATTING":case"UPDATE_FILTER":case"UPDATE_TABLE":case"REMOVE_TABLE":this.headerPositions={},this.isDirty=!0;break;case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_ALL_HEADER_GROUPS":case"UNGROUP_HEADERS":case"GROUP_HEADERS":case"CREATE_SHEET":this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case"DUPLICATE_SHEET":this.headerPositions[e.sheetIdTo]=re(this.headerPositions[e.sheetId])}}finalize(){for(const e of this.getters.getSheetIds())!this.isDirty&&this.headerPositions[e]||(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){const r=this.headerPositions[e].COL[t],n=this.getters.getColSize(e,t);return{start:r,size:n,end:r+(this.getters.isColHidden(e,t)?0:n)}}getRowDimensions(e,t){const r=this.headerPositions[e].ROW[t],n=this.getters.getRowSize(e,t);return{start:r,size:n,end:r+(this.getters.isRowHidden(e,t)?0:n)}}getColRowOffset(e,t,r,n=this.getters.getActiveSheetId()){const o=this.headerPositions[n][e][t];return this.headerPositions[n][e][r]-o}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,"COL"),ROW:this.computePositions(e,"ROW")}}computePositions(e,t){const r={};let n=0;for(let o=0;o<this.getters.getNumberHeaders(e,t)+1;o++)r[o]=n,this.getters.isHeaderHidden(e,t,o)||(n+=this.getters.getHeaderSize(e,t,o));return r}}).add("viewport",class extends Ls{static getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getVisibleRectWithoutHeaders","getVisibleRectWithZoom","getVisibleCellPositions","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","isPixelPositionVisible","getColDimensionsInViewport","getRowDimensionsInViewport","getAllActiveViewportsZonesAndRect","getRect","getFigureUI","getPositionAnchorOffset","getGridOffset","getViewportZoomLevel","getScrollBarWidth","getMaximumSheetOffset"];viewports={};sheetViewWidth=0;sheetViewHeight=0;gridOffsetX=0;gridOffsetY=0;zoomLevel=1;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return"Success"}}handleEvent(e){const t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:r,row:n}=function(e,t){let r,n;const{left:o,right:s,top:i,bottom:a}=e,{left:l,right:c,top:u,bottom:h}=t;return r=l!==o?l:c!==s?c:l,n=u!==i?u:h!==a?h:u,{col:r,row:n}}(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const o=e.previousAnchor.zone,s=e.anchor.zone,{top:i,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);o.left===s.left&&o.right===s.right&&(r=l>r||r>c?l:r),o.top===s.top&&o.bottom===s.bottom&&(n=i>n||n>a?i:n)}r=Math.min(r,this.getters.getNumberCols(t)-1),n=Math.min(n,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:r,row:n})}}handle(e){if(Cs.has(e.type))for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.cleanViewports();for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);this.shouldAdjustViewports=!0;break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SET_ZOOM":this.zoomLevel=e.zoom||1;break;case"SHIFT_VIEWPORT_DOWN":const t=this.getters.getActiveSheetId(),{top:r,viewportHeight:n,offsetCorrectionY:o}=this.getMainInternalViewport(t),s=this.getters.getRowDimensions(t,r);this.shiftVertically(s.start+n-o);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:r,offsetCorrectionY:n}=this.getMainInternalViewport(e),o=this.getters.getRowDimensions(e,t);this.shiftVertically(o.end-n-r);break}case"REMOVE_TABLE":case"UPDATE_TABLE":case"UPDATE_FILTER":case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UNGROUP_HEADERS":case"GROUP_HEADERS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_ALL_HEADER_GROUPS":this.sheetsWithDirtyViewports.add(e.sheetId);break;case"UPDATE_CELL":case"SET_FORMATTING":if("content"in e||"format"in e||void 0!==e.style?.fontSize||void 0!==e.style?.wrapping)for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case"DELETE_SHEET":this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"ACTIVATE_SHEET":this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case"SCROLL_TO_CELL":this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row})}}finalize(){for(const e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){const t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){const e=this.getters.getSheetIds();for(const t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getRowIndex(e)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getGridOffset(){return{x:this.gridOffsetX,y:this.gridOffsetY}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>le(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,"COL",t))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>le(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,"ROW",t))}getVisibleCellPositions(){const e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),r=this.getters.getActiveSheetId(),n=[];for(const o of e)for(const e of t){const t={sheetId:r,col:o,row:e},s=this.getters.getMainCellPosition(t);s.row===e&&s.col===o&&n.push(t)}return n}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:r,ySplit:n}=this.getters.getPaneDivisions(e),{width:o,height:s}=t.getMaxSize();return{x:this.getters.getColDimensions(e,r).start,y:this.getters.getRowDimensions(e,n).start,width:o,height:s}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:r}=this.getMainViewportRect(),n=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-n.viewportWidth),maxOffsetY:Math.max(0,r-n.viewportHeight)}}getColRowOffsetInViewport(e,t,r){if(r<t)return-this.getColRowOffsetInViewport(e,r,t);const n=this.getters.getActiveSheetId(),o="COL"===e?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),s=o.findIndex(e=>t>=e);let i=o.findIndex(e=>r<=e);i=-1===i?o.length:i;const a=o.slice(s,i);let l=0;for(const t of a)l+=this.getters.getHeaderSize(n,e,t);return l*this.zoomLevel}isVisibleInViewport({sheetId:e,col:t,row:r}){return this.getSubViewports(e).some(e=>e.isVisible(t,r))}getScrollBarWidth(){return 15/this.zoomLevel}getEdgeScrollCol(e,t,r){let n=!1,o=0,s=0;const{xSplit:i}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(n=!0,s=HT(e-a),o=1):e<l&&r>=l&&c>0?(n=!0,s=HT(l-e),o=-1):i&&t<l&&e>l&&(n=!0,s=HT(e),o="reset"),{canEdgeScroll:n,direction:o,delay:s}}getEdgeScrollRow(e,t,r){let n=!1,o=0,s=0;const{ySplit:i}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(n=!0,s=HT(e-a),o=1):e<l&&r>=l&&c>0?(n=!0,s=HT(l-e),o=-1):i&&t<l&&e>l&&(n=!0,s=HT(e),o="reset"),{canEdgeScroll:n,direction:o,delay:s}}getVisibleRect(e){const t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithZoom(e){const t=this.getViewportZoomLevel(),r=this.getVisibleRectWithoutHeaders(e);return r.width=r.width*t,r.height=r.height*t,r.x=r.x*t+this.gridOffsetX*t,r.y=r.y*t+this.gridOffsetY*t,r}getVisibleRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){const t=this.getters.getActiveSheetId(),r=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...r,x:r.x+this.gridOffsetX,y:r.y+this.gridOffsetY}}getRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getFullRect(e))}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:r}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,r).start}}getColDimensionsInViewport(e,t){const{top:r}=this.getMainInternalViewport(e),n={left:t,right:t,top:r,bottom:r},{x:o,width:s}=this.getVisibleRect(n),i=o-this.gridOffsetX;return{start:i,size:s,end:i+s}}getRowDimensionsInViewport(e,t){const{left:r}=this.getMainInternalViewport(e),n={left:0,right:r,top:t,bottom:t},{y:o,height:s}=this.getVisibleRect(n),i=o-this.gridOffsetY;return{start:i,size:s,end:i+s}}getAllActiveViewportsZonesAndRect(){const e=this.getters.getActiveSheetId();return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}getViewportZoomLevel(){return this.zoomLevel}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(Se)}checkPositiveDimension(e){return e.width<0||e.height<0?"InvalidViewportSize":"Success"}checkValuesAreDifferent(e){const{height:t,width:r}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===r&&e.height===t?"ValuesNotChanged":"Success"}checkScrollingDirection({offsetX:e,offsetY:t}){const r=this.getMainInternalViewport(this.getters.getActiveSheetId());return!r.canScrollHorizontally&&e>0||!r.canScrollVertically&&t>0?"InvalidScrollingDirection":"Success"}checkIfViewportsWillChange({offsetX:e,offsetY:t}){const r=this.getters.getActiveSheetId(),{maxOffsetX:n,maxOffsetY:o}=this.getMaximumSheetOffset();return this.getSubViewports(r).some(r=>r.willNewOffsetScrollViewport(ae(e,0,n),ae(t,0,o)))?"Success":"ViewportScrollLimitsReached"}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e={};for(const t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,r=0,n=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=r,this.gridOffsetY=n,this.recomputeViewports()}recomputeViewports(){for(const e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){const r=this.getters.getActiveSheetId(),{maxOffsetX:n,maxOffsetY:o}=this.getMaximumSheetOffset();this.getSubViewports(r).forEach(r=>r.setViewportOffset(ae(e,0,n),ae(t,0,o)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetX||0,y:this.viewports[e]?.bottomRight.offsetY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:r}=this.getters.getPaneDivisions(e),n=this.getters.getNumberCols(e),o=this.getters.getNumberRows(e),s=Math.min(this.getters.getColRowOffset("COL",0,t,e),this.sheetViewWidth),i=Math.min(this.getters.getColRowOffset("ROW",0,r,e),this.sheetViewHeight),a=Math.max(this.sheetViewWidth-s,0),l=Math.max(this.sheetViewHeight-i,0),{xRatio:c,yRatio:u}=this.getFrozenSheetViewRatio(e),h=c<1,d=u<1,f=this.getViewportOffset(e),g={topLeft:r&&t&&new BT(this.getters,e,{left:0,right:t-1,top:0,bottom:r-1},{width:s,height:i},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:r&&new BT(this.getters,e,{left:t,right:n-1,top:0,bottom:r-1},{width:a,height:i},{canScrollHorizontally:h,canScrollVertically:!1},{x:h?f.x:0,y:0})||void 0,bottomLeft:t&&new BT(this.getters,e,{left:0,right:t-1,top:r,bottom:o-1},{width:s,height:l},{canScrollHorizontally:!1,canScrollVertically:d},{x:0,y:d?f.y:0})||void 0,bottomRight:new BT(this.getters,e,{left:t,right:n-1,top:r,bottom:o-1},{width:a,height:l},{canScrollHorizontally:h,canScrollVertically:d},{x:h?f.x:0,y:d?f.y:0})};this.viewports[e]=g}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){const t=this.getters.getActiveSheetId(),{top:r}=this.getMainInternalViewport(t),{scrollX:n}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(n,e);const{anchor:o}=this.getters.getSelection();if(o.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-r;this.selection.selectCell(o.cell.col,o.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let r=this.getActiveMainViewport().left,n=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset("COL",r,0);for(;e<n;r--)n-=this.getters.getColSize(t,r-1);return Math.max(r,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let r=this.getActiveMainViewport().top,n=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset("ROW",r,0);for(;e<n;r--)n-=this.getters.getRowSize(t,r-1);return Math.max(r,0)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],r=this.getters.getFigures(e),{scrollX:n,scrollY:o}=this.getters.getActiveSheetScrollInfo(),{x:s,y:i}=this.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const c of r){const r=this.getFigureUI(e,c),{x:u,y:h}=r;u>=s&&(u+c.width<n+s||u>a+n+s)||(h>=i&&(h+c.height<o+i||h>l+o+i)||t.push(r))}return t}getFigureUI(e,t){const r=t.offset.x+this.getters.getColDimensions(e,t.col).start,n=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:r,y:n}}getPositionAnchorOffset(e){const{scrollX:t,scrollY:r}=this.getters.getActiveSheetScrollInfo(),n=e.x-t,o=e.y-r,s=n>=0?this.getColIndex(n):this.getColIndexLeftOfMainViewport(n),i=o>=0?this.getRowIndex(o):this.getRowIndexTopOfMainViewport(o),{x:a,y:l}=this.getRect(ps({col:s,row:i}));return{col:s,row:i,offset:{x:Math.max(n-a+this.gridOffsetX,0),y:Math.max(o-l+this.gridOffsetY,0)}}}isPixelPositionVisible(e){const{scrollX:t,scrollY:r}=this.getters.getActiveSheetScrollInfo(),{x:n,y:o}=this.getters.getMainViewportCoordinates(),{width:s,height:i}=this.getters.getSheetViewDimension();return!(e.x>=n&&(e.x<n+t||e.x>s+t+n))&&!(e.y>=o&&(e.y<o+r||e.y>i+r+o))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:r}=this.getters.getPaneDivisions(e),n=this.getters.getColDimensions(e,t).start,o=this.getters.getRowDimensions(e,r).start;return{xRatio:n/(this.sheetViewWidth+this.gridOffsetX),yRatio:o/(this.sheetViewHeight+this.gridOffsetY)}}mapViewportsToRect(e,t){let r=1/0,n=1/0,o=0,s=0,i=!1;for(const a of this.getSubViewports(e)){const e=t(a);e&&(i=!0,r=Math.min(r,e.x),n=Math.min(n,e.y),o=Math.max(o,e.x+e.width),s=Math.max(s,e.y+e.height))}return i?{x:r,y:n,width:o-r,height:s-n}:{x:0,y:0,width:0,height:0}}}).add("clipboard",class extends Ls{static layers=["Clipboard"];static getters=["getClipboardTextAndImageContent","getClipboardId","getClipboardTextContent","isCutOperation"];status="invisible";originSheetId;copiedData;_isCutOperation=!1;clipboardId=(new _o).uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new _o}allowDispatch(e){switch(e.type){case"CUT":const t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case"PASTE_FROM_OS_CLIPBOARD":{const t=this.convertTextToClipboardData(e.clipboardContent.text??""),r=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:r,isCutOperation:!1})}case"PASTE":{if(!this.copiedData)return"EmptyClipboard";const t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].top&&0===e[0].bottom)return"InvalidCopyPasteSelection";break}case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].left&&0===e[0].right)return"InvalidCopyPasteSelection";break}case"INSERT_CELL":{const{cut:t,paste:r}=this.getInsertCellsTargets(e.zone,e.shiftDimension),n=this.copy(t,"shiftCells");return this.isPasteAllowed(r,n,{isCutOperation:!0})}case"DELETE_CELL":{const{cut:t,paste:r}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),n=this.copy(t,"shiftCells");return this.isPasteAllowed(r,n,{isCutOperation:!0})}}return"Success"}handle(e){switch(e.type){case"COPY":case"CUT":const t=this.getters.getSelectedZones();this.status="visible",this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation="CUT"===e.type,this.copiedData=this.copy(t);break;case"PASTE_FROM_OS_CLIPBOARD":{this._isCutOperation=!1;const t=e.clipboardContent.data;if(e.clipboardContent.imageData){const t=this.getters.getActiveSheetId(),r=this.uuidGenerator.uuidv4(),n=e.clipboardContent.imageData,o=function(e,t){const r=re(t),n=e.getSheetViewDimension(),o=n.width,s=n.height;if(r.width>o){const e=o/r.width;r.width=o,r.height=r.height*e}if(r.height>s){const e=s/r.height;r.height=s,r.width=r.width*e}return r}(this.getters,n.size);this.dispatch("CREATE_IMAGE",{definition:n,size:o,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:t,figureId:r})}this.copiedData=t||this.convertTextToClipboardData(e.clipboardContent.text??"");const r=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:r,selectTarget:!0,isCutOperation:!1}),this.status="invisible",this.copiedData=void 0;break}case"PASTE":{const t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status="invisible",this._isCutOperation&&(this.copiedData=void 0,this._isCutOperation=!1);break}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZone(),t=e.top!==e.bottom,r={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();const n=this.copy([r]);this.paste([e],n,{isCutOperation:!1,selectTarget:!0})}break;case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZone(),t=e.left!==e.right,r={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();const n=this.copy([r]);this.paste([e],n,{isCutOperation:!1,selectTarget:!0})}break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:r}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Qo(t[0])){this.dispatch("CLEAR_CELLS",{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}const n=this.copy(t,"shiftCells");this.paste(r,n,{isCutOperation:!0});break}case"INSERT_CELL":{const{cut:t,paste:r}=this.getInsertCellsTargets(e.zone,e.shiftDimension),n=this.copy(t,"shiftCells");this.paste(r,n,{isCutOperation:!0});break}case"ADD_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(const t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}}this.status="invisible";break;case"REPEAT_PASTE":this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case"DELETE_SHEET":if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status="invisible");break;default:Ds(e)&&(this.status="invisible")}}convertTextToClipboardData(e){const t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),r={};for(const{handlerName:n,handler:o}of t){const t=o.convertTextToClipboardData(e);r[n]=t;const s=["sheetId","cells","zones","figureId"];for(const e of s)t&&e in t&&(r[e]=t[e])}return r}selectClipboardHandlers(e){const t="figureId"in e?PT.figureHandlers:PT.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){const t=this.getClipboardData(e);for(const{handler:e}of this.selectClipboardHandlers(t)){const r=e.isCutAllowed(t);if("Success"!==r)return r}return"Success"}isPasteAllowed(e,t,r){for(const{handler:n}of this.selectClipboardHandlers(t)){const o=n.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...r});if("Success"!==o)return o}return"Success"}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;const{zones:r}=this.copiedData;for(const n of r){if("COL"===t&&e<=n.right)return!0;if("ROW"===t&&e<=n.bottom)return!0}return!1}copy(e,t="copyPaste"){const r={},n=this.getClipboardData(e);for(const{handlerName:e,handler:o}of this.selectClipboardHandlers(n)){const s=o.copy(n,this._isCutOperation,t);r[e]=s;const i=["sheetId","cells","zones","figureId"];for(const e of i)s&&e in s&&(r[e]=s[e])}return r}paste(e,t,r){if(!t)return;const n=this.getters.getActiveSheetId(),o=this.selectClipboardHandlers(t),{target:s,zone:i,selectedZones:a}=function(e,t,r,n,o){let s;const i=[],a={sheetId:e,zones:t};for(const{handlerName:l,handler:c}of n){const n=r[l];if(!n)continue;const u=c.getPasteTarget(e,t,n,o);u.figureId&&(a.figureId=u.figureId);for(const e of u.zones)i.push(e),s=void 0!==s?ns(s,e):e}return{target:a,zone:s,selectedZones:i}}(n,e,t,o,r);void 0!==i&&this.addMissingDimensions(n,i.right-i.left+1,i.bottom-i.top+1,i.left,i.top),((e,t,r,n)=>{e.forEach(({handlerName:e,handler:o})=>{const s=t[e];s&&o.paste(r,s,n)})})(o,t,s,r),r?.selectTarget&&((e,t,r)=>{const n={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:n,zone:ns(...r)},{scrollIntoView:!1})})(this.selection,e,a)}addMissingDimensions(e,t,r,n,o){const s=r+o-this.getters.getNumberRows(e);s>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s,position:"after"});const i=t+n-this.getters.getNumberCols(e);i>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i,position:"after"})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){const e=await this.getImageContent(),t=e?.type,r={[VT.PlainText]:this.getPlainTextContent(),[VT.Html]:await this.getHTMLContent()};return t&&e&&(r[t]=e),r}getSheetData(){const e={version:Cw(),clipboardId:this.clipboardId};return this.copiedData&&"figureId"in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map(e=>e.map(e=>this.getters.shouldShowFormulas()&&e?.tokens?.length?e?.content||"":e.evaluatedCell?.formattedValue||"").join("\t")).join("\n")||"\t"}async getHTMLContent(){let e="";const t=this.copiedData?.cells;if(t)if(1===t.length&&1===t[0].length)e=`${this.getters.getCellText(t[0][0].position)}`;else{if(!t[0][0])return"";{let r='<table border="1" style="border-collapse:collapse">';for(const e of t){r+="<tr>";for(const t of e){if(!t)continue;r+=`<td style="${MT(NT(this.getters.getCellComputedStyle(t.position)))}">`+WE(this.getters.getCellText(t.position))+"</td>"}r+="</tr>"}r+="</table>",e=r}}else if(this.copiedData?.figureId){const t=this.copiedData.figureId,r=this.getters.getFigureSheetId(t);e="image"===this.getters.getFigure(r,t).tag?await this.craftImageHTML(t):"\t"}else e="\t";return`<div data-osheet-clipboard='${WE(JSON.stringify(this.getSheetData()))}'>${e}</div>`}readFileAsDataURL(e){return new Promise(t=>{const r=new FileReader;r.onload=()=>t(r.result),r.readAsDataURL(e)})}async craftImageHTML(e){if(!this.fileStore)return"\t";const t=this.getters.getImage(e).path,r=await(this.fileStore?.getFile(t))||null;if(r){return`<img src="${WE(await this.readFileAsDataURL(r))}" />`}return"\t"}async getImageContent(){const e=this.copiedData?.figureId;if(!e)return;const t=this.getters.getFigureSheetId(e);let r;if("image"===this.getters.getFigure(t,e).tag){if(!this.fileStore)return;const t=this.getters.getImage(e).path;if(r=await(this.fileStore?.getFile(t)),"image/png"!==r.type){if(r.size>kT)return void this.ui.notifyUI({text:v("The file you are trying to copy is too large (>%sMB).\nIt will not be added to your OS clipboard.\nYou can download it directly instead.",Math.round(5)),sticky:!1,type:"warning"});r=await async function(e){return new Promise((t,r)=>{const n=new Image;n.addEventListener("load",()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const r=e.getContext("2d");r?.drawImage(n,0,0),e.toBlob(t,"image/png")}),n.addEventListener("error",r),n.src=e})}(t)}}return r?r instanceof File?r:new File([r],"image.png",{type:"image/png"}):void 0}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){const r=this.getters.getActiveSheetId();let n;return n="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(r)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(r)-1},{cut:[n],paste:[e]}}getInsertCellsTargets(e,t){const r=this.getters.getActiveSheetId();let n,o;return"COL"===t?(n={...e,right:this.getters.getNumberCols(r)-1},o={...e,left:e.right+1,right:e.right+1}):(n={...e,bottom:this.getters.getNumberRows(r)-1},o={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(r)-1}),{cut:[n],paste:[o]}}getClipboardData(e){const t=this.getters.getActiveSheetId(),r=this.getters.getSelectedFigureId();if(r)return{figureId:r,sheetId:t};const n=LT(t,e);return this._isCutOperation||(n.rowsIndexes=n.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),n}drawLayer(e){if("visible"!==this.status||!this.copiedData)return;const{sheetId:t,zones:r}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!r||!r.length)return;const{ctx:n,thinLineWidth:o}=e;n.setLineDash([8,5]),n.strokeStyle=M,n.lineWidth=3.3*o;for(const e of r){const{x:t,y:r,width:o,height:s}=this.getters.getVisibleRect(e);o>0&&s>0&&n.strokeRect(t,r,o,s)}}}).add("carousel_ui",class extends Ls{static getters=["getSelectedCarouselItem","getChartFromFigureId","getChartIdFromFigureId"];uuidGenerator=new _o;carouselStates={};allowDispatch(e){switch(e.type){case"ADD_FIGURE_CHART_TO_CAROUSEL":return this.getters.doesCarouselExist(e.carouselFigureId)&&"chart"===this.getters.getFigure(e.sheetId,e.chartFigureId)?.tag?"Success":"InvalidFigureId";case"DUPLICATE_CAROUSEL_CHART":return this.getters.doesCarouselExist(e.carouselId)&&this.getters.getCarousel(e.carouselId).items.some(t=>"chart"===t.type&&t.chartId===e.chartId)&&!this.getters.getChart(e.duplicatedChartId)?"Success":"InvalidFigureId";case"ADD_NEW_CHART_TO_CAROUSEL":return this.getters.doesCarouselExist(e.figureId)?"Success":"InvalidFigureId";case"UPDATE_CAROUSEL_ACTIVE_ITEM":return this.getters.doesCarouselExist(e.figureId)?this.getters.getCarousel(e.figureId).items.some(t=>Ae(t,e.item))?"Success":"InvalidCarouselItem":"InvalidFigureId"}return"Success"}handle(e){switch(e.type){case"ADD_NEW_CHART_TO_CAROUSEL":this.addNewChartToCarousel(e.figureId,e.sheetId);break;case"ADD_FIGURE_CHART_TO_CAROUSEL":this.addFigureChartToCarousel(e.carouselFigureId,e.chartFigureId,e.sheetId);break;case"DUPLICATE_CAROUSEL_CHART":this.duplicateCarouselChart(e);break;case"UPDATE_CAROUSEL_ACTIVE_ITEM":this.carouselStates[e.figureId]=this.getCarouselItemId(e.item);break;case"POPOUT_CHART_FROM_CAROUSEL":this.popOutChartFromCarousel(e.carouselId,e.chartId,e.sheetId);break;case"DELETE_FIGURE":delete this.carouselStates[e.figureId];break;case"UPDATE_CAROUSEL":this.fixWrongCarouselState(e.figureId);break;case"DELETE_CHART":case"UNDO":case"REDO":case"DELETE_SHEET":for(const e in this.carouselStates)this.fixWrongCarouselState(e)}}popOutChartFromCarousel(e,t,r){const n=this.getters.getCarousel(e);if(!n)return;const o=this.getters.getFigure(r,e),s=this.getters.getChartDefinition(t);if(!s||!o)return;const i=this.getters.getFigureUI(r,o),a=this.getters.getPositionAnchorOffset({x:i.x+50,y:i.y+50}),l=this.uuidGenerator.smallUuid();this.dispatch("CREATE_CHART",{...a,chartId:this.uuidGenerator.smallUuid(),figureId:l,sheetId:r,size:{width:o.width,height:o.height},definition:{...s}});const c=n.items.filter(e=>"chart"!==e.type||e.chartId!==t);this.dispatch("UPDATE_CAROUSEL",{sheetId:r,figureId:e,definition:{...n,items:c}}),this.dispatch("SELECT_FIGURE",{figureId:l})}getSelectedCarouselItem(e){const t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;const t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){const t=this.getters.getFigureSheetId(e);if(!t)return;const r=this.getters.getFigure(t,e);if(r&&("chart"===r.tag||"carousel"===r.tag)){if("carousel"===r.tag){const t=this.getSelectedCarouselItem(e);return"chart"===t?.type?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e))return void delete this.carouselStates[e];const t=this.getters.getCarousel(e);0===t.items.length?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){const r=this.getters.getCarousel(e),n=this.uuidGenerator.smallUuid();this.dispatch("CREATE_CHART",{chartId:n,figureId:e,sheetId:t,definition:FT});const o={...r,items:[...r.items,{type:"chart",chartId:n}]};this.dispatch("UPDATE_CAROUSEL",{sheetId:t,figureId:e,definition:o})}addFigureChartToCarousel(e,t,r){const n=this.getChartIdFromFigureId(t);if(!n)return;const o=this.getters.getCarousel(e),s={...o,items:[...o.items,{type:"chart",chartId:n}]};this.dispatch("UPDATE_CAROUSEL",{sheetId:r,figureId:e,definition:s}),this.dispatch("UPDATE_CHART",{sheetId:r,chartId:n,figureId:e,definition:this.getters.getChartDefinition(n)}),this.dispatch("DELETE_FIGURE",{sheetId:r,figureId:t})}duplicateCarouselChart({carouselId:e,chartId:t,sheetId:r,duplicatedChartId:n}){const o=this.getters.getChart(t);if(!o)return;const s=this.getters.getCarousel(e),i=s.items.findIndex(e=>"chart"===e.type&&e.chartId===t);if(-1===i)return;this.dispatch("CREATE_CHART",{chartId:n,figureId:e,sheetId:r,definition:o.getDefinition()});const a=Be(s.items,[{type:"chart",chartId:n}],i+1);this.dispatch("UPDATE_CAROUSEL",{sheetId:r,figureId:e,definition:{...s,items:a}})}getCarouselItemId(e){return"chart"===e.type?e.chartId:"carouselDataView"}}),WT=(new h).add("evaluation",class extends NS{static getters=["evaluateFormula","evaluateFormulaResult","evaluateCompiledFormula","getCorrespondingFormulaCell","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getEvaluatedCellsInZone","getEvaluatedCellsPositionInZone","getEvaluatedCellsPositions","getSpreadZone","getArrayFormulaSpreadingOn","isArrayFormulaSpillBlocked","isEmpty"];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new mC(e.custom,this.getters)}beforeHandle(e){(Cs.has(e.type)||Is.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case"UPDATE_CELL":if(!("content"in e)&&!("format"in e)||this.shouldRebuildDependenciesGraph)return;const t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),"content"in e&&this.evaluator.updateDependencies(t);break;case"EVALUATE_CELLS":if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells()}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t){const r=this.evaluateFormulaResult(e,t);return D(r)?nr(r,e=>e.value):r.value}evaluateFormulaResult(e,t){return this.evaluator.evaluateFormulaResult(e,t)}evaluateCompiledFormula(e,t,r){return this.evaluator.evaluateCompiledFormula(e,t,r)}getRangeFormattedValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).formattedValue)}getRangeValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).value)}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map(e=>e.format)}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return fs(e,t).map(this.getters.getEvaluatedCell)}getEvaluatedCellsPositionInZone(e,t){return fs(e,t).map(e=>[e,this.getters.getEvaluatedCell(e)])}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return ds(t).map(({col:t,row:r})=>this.getEvaluatedCell({sheetId:e,col:t,row:r})).every(e=>e.type===Nu.empty)}mapVisiblePositions(e,t){const{sheetId:r,zone:n}=e;return ds(n).reduce((e,n)=>{const{col:o,row:s}=n;return this.getters.isColHidden(r,o)||this.getters.isRowHidden(r,s)||e.push(t({sheetId:r,...n})),e},[])}exportForExcel(e){for(const t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(const t of this.evaluator.getEvaluatedPositions()){const r=this.evaluator.getEvaluatedCell(t),n=Bo(t.col,t.row),o=r.value;let s,i=!1,a=!0;const l=e.sheets.find(e=>e.id===t.sheetId),c=this.getCorrespondingFormulaCell(t);if(c){const u=this.getters.getCell(t);if(a=DS(c.compiledFormula.tokens),i=a&&u?.content===c.content,!a&&""!==o){s=(o??"").toString();const t=r.format;if(t){const r=py(t,e.formats);l.formats[n]=r}}}const u=l.cells[n];let h;h=a&&i&&c instanceof Vw?c.contentWithFixedReferences:a?u:s,l.cells[n]=h,l.cellValues[n]="error"!==r.type?o:void 0;const d=this.getSpreadZone(t);d&&(l.formulaSpillRanges[n]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,d),t.sheetId))}}getCorrespondingFormulaCell(e){const t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;const r=this.getArrayFormulaSpreadingOn(e);if(void 0===r)return;const n=this.getters.getCell(r);return n?.isFormula?n:void 0}}).add("evaluation_chart",class extends NS{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=function(e){const t=db.getAll().sort((e,t)=>e.sequence-t.sequence);return function(r){const n=t.find(e=>e.match(r.type));if(!n)throw new Error("No runtime builder for this chart.");const o=n.getChartRuntime(r,e),s=r.getDefinition();if("chartJsConfig"in o&&/line|combo|bar|scatter|waterfall/.test(s.type)){const e=o.chartJsConfig;o.masterChartConfig=function(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>{return!("x1"===(t=e.xAxisID)||"xMovingAverage"===t);var t}).map(e=>({...e,pointRadius:!1===e.showLine?2:0}))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return function(e,t=20){return e?e.length>t?e.substring(0,t)+"…":e:""}(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}(e)}return o}}(this.getters);handle(e){if(Cs.has(e.type)||xs.has(e.type)||Ts.has(e.type))for(const e in this.charts)this.charts[e]=void 0;switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":case"DELETE_CHART":this.charts[e.chartId]=void 0;break;case"DELETE_SHEET":for(const e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0)}}getChartRuntime(e){if(!this.charts[e]){const t=this.getters.getChart(e);if(!t)throw new Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:Kb(e)};if(!t)return{background:V,fontColor:Kb(V)};const r=t.zone.left,n=t.zone.top,o=t.sheetId,s=this.getters.getCellComputedStyle({sheetId:o,col:r,row:n}),i=s.fillColor||V;return{background:i,fontColor:s.textColor||Kb(i)}}async exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),r=[];for(const n of e){if(!n||"chart"!==n.tag)continue;const e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===n.id);if(!e)continue;const o=this.getters.getChart(e),s=o?.getDefinitionForExcel(this.getters);if(s)r.push({...n,data:s});else{if(!o)continue;const r=this.getters.getChartType(e),s=this.getters.getChartRuntime(e),i=await nT(s,n,r);i&&t.images.push({...n,tag:"image",data:{mimetype:"image/png",path:i,size:{width:n.width,height:n.height}}})}}t.charts=r}}}).add("evaluation_cf",class extends NS{static getters=["getConditionalIcon","getCellConditionalFormatStyle","getConditionalDataBar"];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Cs.has(e.type)||xs.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(const e of this.getters.getSheetIds())this.computedStyles[e]=xe(()=>this.getComputedStyles(e)),this.computedIcons[e]=xe(()=>this.getComputedIcons(e)),this.computedDataBars[e]=xe(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){const{sheetId:t,col:r,row:n}=e,o=this.computedStyles[t]();return o&&o[r]?.[n]}getConditionalIcon({sheetId:e,col:t,row:r}){const n=this.computedIcons[e]();return n&&n[t]?.[r]}getConditionalDataBar({sheetId:e,col:t,row:r}){const n=this.computedDataBars[e]();return n&&n[t]?.[r]}getComputedStyles(e){const t={};for(const r of this.getters.getConditionalFormats(e).reverse())switch(r.rule.type){case"ColorScaleRule":for(const n of r.ranges)this.applyColorScale(e,n,r.rule,t);break;case"CellIsRule":const n=r.rule.values.map(e=>e.startsWith("=")?_m(e):void 0);for(const o of r.ranges){const s=this.getters.getRangeFromSheetXC(e,o).zone;for(let o=s.top;o<=s.bottom;o++)for(let i=s.left;i<=s.right;i++){const a={sheetId:e,col:i,row:o},l=r.rule.values.map((t,r)=>{const a=n[r];return a?this.getters.getTranslatedCellFormula(e,i-s.left,o-s.top,a.tokens):t});this.getRuleResultForTarget(a,{...r.rule,values:l})&&(t[i]||(t[i]=[]),t[i][o]=Object.assign(t[i]?.[o]||{},r.rule.style))}}}return t}getComputedIcons(e){const t={};for(const r of this.getters.getConditionalFormats(e).reverse())if("IconSetRule"===r.rule.type)for(const n of r.ranges)this.applyIcon(e,n,r.rule,t);return t}getComputedDataBars(e){const t={};for(const r of this.getters.getConditionalFormats(e).reverse())if("DataBarRule"===r.rule.type)for(const n of r.ranges)this.applyDataBar(e,n,r.rule,t);return t}parsePoint(e,t,r,n){const o=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter(e=>e.type===Nu.number).map(e=>e.value);switch(r.type){case"value":return"max"===n?We(o):qe(o);case"number":return Number(r.value);case"percentage":const t=qe(o);return t+(We(o)-t)*Number(r.value)/100;case"percentile":return Ft(o,Number(r.value)/100,!0);case"formula":const s=r.value&&this.getters.evaluateFormula(e,r.value);return"number"==typeof s?s:null;default:return null}}applyIcon(e,t,r,n){const o=this.parsePoint(e,t,r.lowerInflectionPoint),s=this.parsePoint(e,t,r.upperInflectionPoint);if(null===o||null===s||o>s)return;const i=this.getters.getRangeFromSheetXC(e,t).zone,a=[r.icons.upper,r.icons.middle,r.icons.lower];for(let t=i.top;t<=i.bottom;t++)for(let l=i.left;l<=i.right;l++){const i=this.getters.getEvaluatedCell({sheetId:e,col:l,row:t});if(i.type!==Nu.number)continue;const c=this.computeIcon(i.value,s,r.upperInflectionPoint.operator,o,r.lowerInflectionPoint.operator,a);n[l]||(n[l]=[]),n[l][t]=c}}computeIcon(e,t,r,n,o,s){return"ge"===r&&e>=t||"gt"===r&&e>t?s[0]:"ge"===o&&e>=n||"gt"===o&&e>n?s[1]:s[2]}applyDataBar(e,t,r,n){const o=this.getters.getRangeFromSheetXC(e,r.rangeValues||t),s=We(this.getters.getEvaluatedCellsInZone(e,o.zone).filter(e=>e.type===Nu.number).map(e=>e.value));if(s<=0)return;const i=r.color,a=this.getters.getRangeFromSheetXC(e,t).zone,l=o.zone;for(let t=a.top;t<=a.bottom;t++)for(let r=a.left;r<=a.right;r++){const o=r-a.left+l.left,c=t-a.top+l.top,u=this.getters.getEvaluatedCell({sheetId:e,col:o,row:c});!ls(o,c,l)||u.type!==Nu.number||u.value<=0||(n[r]||(n[r]=[]),n[r][t]={color:fp(i),percentage:100*u.value/s})}}applyColorScale(e,t,r,n){const o=this.parsePoint(e,t,r.minimum,"min"),s=r.midpoint?this.parsePoint(e,t,r.midpoint):null,i=this.parsePoint(e,t,r.maximum,"max");if(null===o||null===i||o>=i||s&&(o>=s||s>=i))return;const a=this.getters.getRangeFromSheetXC(e,t).zone,l=[{value:o,color:r.minimum.color}];r.midpoint&&s&&l.push({value:s,color:r.midpoint.color}),l.push({value:i,color:r.maximum.color});const c=function(e){if(e.length<2)throw new Error("Color scale must have at least 2 points");const t=[...e.sort((e,t)=>e.value-t.value)],r=[];for(let e=1;e<t.length;e++){const n=xp(t[e-1].color).a,o=xp(t[e].color).a,s=gp(t[e-1].color),i=gp(t[e].color);r.push({min:t[e-1].value,max:t[e].value,minColor:s,maxColor:i,minColorAlpha:n,maxColorAlpha:o,colorDiff:Hp(t[e-1].value,t[e].value,s,i)})}return e=>{if(e<r[0].min)return fp(r[0].minColor,r[0].minColorAlpha);for(const t of r)if(e>=t.min&&e<=t.max)return fp(Bp(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return fp(r[r.length-1].maxColor,r[r.length-1].maxColorAlpha)}}(l);for(let t=a.top;t<=a.bottom;t++)for(let r=a.left;r<=a.right;r++){const s=this.getters.getEvaluatedCell({sheetId:e,col:r,row:t});if(s.type===Nu.number){const e=ae(s.value,o,i);n[r]||(n[r]=[]),n[r][t]=n[r]?.[t]||{},n[r][t].fillColor=c(e)}}}getRuleResultForTarget(e,t){const r=this.getters.getEvaluatedCell(e);if(r.type===Nu.error)return!1;const{sheetId:n}=e,o=Pw.get(t.operator),s=t.values.map(e=>e.startsWith("=")?this.getters.evaluateFormula(n,e)??"":uE(e,xr));if(s.some(Dn))return!1;const i={type:t.operator,values:s.map(On),dateValue:t.dateValue||"exactDate"};return o.isValueValid(r.value??"",i,this.getters,n)}}).add("row_size",class extends NS{static getters=["getRowSize","getHeaderSize","getMaxAnchorOffset"];tallestCellInRow={};ctx=wC();beforeHandle(e){if("ADD_COLUMNS_ROWS"===e.type){if("COL"===e.dimension)return;const t=Re(e.position,e.base),r=Array(e.quantity).fill(void 0),n=Be(this.tallestCellInRow[e.sheetId],r,t);this.history.update("tallestCellInRow",e.sheetId,n)}}handle(e){switch(e.type){case"START":case"UPDATE_LOCALE":for(const e of this.getters.getSheetIds())this.initializeSheet(e);break;case"CREATE_SHEET":this.initializeSheet(e.sheetId);break;case"DUPLICATE_SHEET":{const t=re(this.tallestCellInRow[e.sheetId]);this.history.update("tallestCellInRow",e.sheetIdTo,t);break}case"DELETE_SHEET":const t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update("tallestCellInRow",t);break;case"REMOVE_COLUMNS_ROWS":{if("COL"===e.dimension)return;const t=He(this.tallestCellInRow[e.sheetId],e.elements);this.history.update("tallestCellInRow",e.sheetId,t);break}case"RESIZE_COLUMNS_ROWS":{const t=e.sheetId;if("ROW"===e.dimension)for(const r of e.elements){const e=this.getRowTallestCell(t,r);this.history.update("tallestCellInRow",t,r,e)}else for(const r of le(0,this.getters.getNumberRows(t)))for(const n of e.elements)this.updateRowSizeForCellChange(t,r,n)}break;case"SET_FORMATTING":if(e.style&&("fontSize"in e.style||"wrapping"in e.style||"rotation"in e.style))for(const t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);break;case"UPDATE_CELL":this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case"ADD_MERGE":case"REMOVE_MERGE":for(const t of e.target)for(const r of ds(t))this.updateRowSizeForCellChange(e.sheetId,r.row,r.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??G)}getMaxAnchorOffset(e,t,r){let{numberOfRows:n,numberOfCols:o}=this.getters.getSheetSize(e),s=0;for(;s<t&&n>0;n--)s+=this.getRowSize(e,n-1);let i=0;for(;i<r&&o>0;o--)i+=this.getters.getColSize(e,o-1);return{col:o,row:n,offset:{x:i-r,y:s-t}}}getHeaderSize(e,t,r){return this.getters.isHeaderHidden(e,t,r)?0:"ROW"===t?this.getRowSize(e,r):this.getters.getColSize(e,r)}updateRowSizeForZoneChange(e,t){for(let r=t.top;r<=t.bottom;r++){const t=this.getRowTallestCell(e,r);this.history.update("tallestCellInRow",e,r,t)}}updateRowSizeForCellChange(e,t,r){const n=this.tallestCellInRow[e]?.[t];if(n?.cell.col===r){const r=this.getRowTallestCell(e,t);this.history.update("tallestCellInRow",e,t,r)}const o=this.getCellHeight({sheetId:e,col:r,row:t});if(!(o<=G)&&(!n&&o>G||n&&o>n.size)){const n={cell:{sheetId:e,col:r,row:t},size:o};this.history.update("tallestCellInRow",e,t,n)}}initializeSheet(e){const t=[];for(let r=0;r<this.getters.getNumberRows(e);r++){const n=this.getRowTallestCell(e,r);t.push(n)}this.history.update("tallestCellInRow",e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return G;const t=this.getters.getCell(e),r=this.getters.getCellStyle(e),n=this.getters.getColSize(e.sheetId,e.col);return function(e,t,r,n,o){if(!t||!t.isFormula&&!t.content)return G;let s="";try{if(!t.isFormula){const e={format:t.format,locale:n};s=Xr(uE(t.content,n),e)}}catch{s=E.GenericError}return SC(e,s,r,o)}(this.ctx,t,r,this.getters.getLocale(),n)}isInMultiRowMerge(e){const t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(void 0!==this.getters.getUserRowSize(e,t))return;const r=this.getters.getRowCells(e,t);let n,o=0;for(let e=0;e<r.length;e++){const t=this.getters.getCellById(r[e]);if(!t)continue;const s=this.getters.getCellPosition(t.id),i=this.getCellHeight(s);i>o&&i>G&&(o=i,n={cell:s,size:i})}return n&&n.size>G?n:void 0}}).add("data_validation_ui",class extends NS{static getters=["getDataValidationInvalidCriterionValueMessage","getInvalidDataValidationMessage","getValidationResultForCellValue","getDataValidationRangeValues","isCellValidCheckbox","getDataValidationCellStyle","getDataValidationChipStyle","isDataValidationInvalid"];validationResults={};handle(e){if(Cs.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))this.validationResults={};else switch(e.type){case"ADD_DATA_VALIDATION_RULE":case"REMOVE_DATA_VALIDATION_RULE":delete this.validationResults[e.sheetId]}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:k}}getInvalidDataValidationMessage(e){const t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){const r=Pw.get(e);return t.startsWith("=")?"onlyLiterals"===r.allowedValues?v("The value must not be a formula"):this.isValidFormula(t)?void 0:Td.CriterionError.validFormula:"onlyFormulas"===r.allowedValues?v("The value must be a formula"):r.isCriterionValueValid(t)?void 0:r.criterionValueErrorString}getDataValidationRangeValues(e,t){const r=this.getters.getRangeFromSheetXC(e,String(t.values[0])),n=[],o=new Set;for(const e of ds(r.zone)){const t=this.getters.getEvaluatedCell({...e,sheetId:r.sheetId});t.formattedValue&&!o.has(t.formattedValue)&&(o.add(t.formattedValue),n.push({label:t.formattedValue,value:t.value?.toString()||""}))}return n}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;const t=this.getters.getValidationRuleForCell(e);return!(!t||"isBoolean"!==t.criterion.type)&&this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){const r=this.getters.getValidationRuleForCell(t);if(!r)return iT;const n=this.getRuleErrorForCellValue(e,t,r);return n?{error:n,rule:r,isValid:!1}:iT}hasChip(e){const t=this.getters.getValidationRuleForCell(e);return("isValueInList"===t?.criterion.type||"isValueInRange"===t?.criterion.type)&&"chip"===t.criterion.displayStyle}getDataValidationStyle(e){const t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;const r=this.getters.getEvaluatedCell(e),n=this.getValueColor(t,r.value);if(!n)return;var o;return{fillColor:n,textColor:(o=n,yp(o)<.6?Rp(o,.9):Ap(o,.75))}}getValueColor(e,t){if("isValueInList"===e.criterion.type||"isValueInRange"===e.criterion.type)for(const r in e.criterion.colors)if(r.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[r]}isValidFormula(e){return!_m(e).isBadExpression}getValidationResultForCell(e){const{col:t,row:r,sheetId:n}=e;return this.validationResults[n]||(this.validationResults[n]=this.computeSheetValidationResults(n)),this.validationResults[n][t]?.[r]?.()||iT}computeSheetValidationResults(e){const t={},r=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(const e of $m(r.flat())){const{col:r,row:n}=e;t[r]||(t[r]=[]),t[r][n]=xe(()=>{const t=this.getters.getEvaluatedCell(e);return t.type===Nu.empty?iT:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,r){const{sheetId:n}=t,o=r.criterion,s=Pw.get(o.type),i=this.getCellOffsetInRule(t,r),a=this.getEvaluatedCriterionValues(n,i,o);if(a.some(Dn))return;const l={...o,values:a.map(On)};return s.isValueValid(e,l,this.getters,n)?void 0:s.getErrorString(l,this.getters,n)}getCellOffsetInRule(e,t){const r=t.ranges.find(t=>ls(e.col,e.row,t.zone));if(!r)throw new Error("The cell is not in any range of the rule");return{col:e.col-r.zone.left,row:e.row-r.zone.top}}getEvaluatedCriterionValues(e,t,r){return r.values.map(r=>{if(!r.startsWith("="))return uE(r,xr);const n=_m(r),o=this.getters.getTranslatedCellFormula(e,t.col,t.row,n.tokens);return this.getters.evaluateFormula(e,o)})}}).add("dynamic_tables",class extends NS{static getters=["canCreateDynamicTableOnZones","doesZonesContainFilter","getFilter","getFilters","getTable","getTables","getTablesOverlappingZones","getFilterId","getFilterHeaders","isFilterHeader"];tables={};handle(e){if(Cs.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type)this.tables={};else switch(e.type){case"CREATE_TABLE":case"REMOVE_TABLE":case"UPDATE_TABLE":case"DELETE_CONTENT":this.tables={}}}finalize(){for(const e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){const t=[],r=this.getters.getCoreTables(e);for(const e of r)"dynamic"!==e.type&&t.push(e);const n=[...t];for(const o of r){if("dynamic"!==o.type)continue;const r=this.coreTableToTable(e,o);let s=r.range.zone;for(const e of n)as(s,e.range.zone)&&(s={...s,right:e.range.zone.left-1});t.push({...r,range:this.getters.getRangeFromZone(e,s)})}return t}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){const t=this.getTable(e);if(t&&t.config.hasFilters)return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:r}){return this.getTables(e).find(e=>ls(t,r,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>as(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){const t=[];for(const r of this.getTables(e)){if(!r.config.hasFilters)continue;const n=r.range.zone,o=n.top;for(let r=n.left;r<=n.right;r++)t.push({sheetId:e,col:r,row:o})}return t}isFilterHeader({sheetId:e,col:t,row:r}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===r)}canCreateDynamicTableOnZones(e,t){if(!ws(t))return!1;const r=ns(...t),n={col:r.left,row:r.top,sheetId:e},o=this.getters.getArrayFormulaSpreadingOn(n);if(!o){const e=this.getters.getEvaluatedCell(n);return e.value===E.SpilledBlocked&&!e.errorOriginPosition}if(Ae(o,n)&&1===Es(r))return!0;return Ae(r,this.getters.getSpreadZone(o))}coreTableToTable(e,t){if("dynamic"!==t.type)return t;const r=t.range.zone,n={sheetId:e,col:r.left,row:r.top},o=this.getters.getSpreadZone(n)??t.range.zone,s=this.getters.getRangeFromZone(e,o),i=this.getDynamicTableFilters(e,t,o);return{id:t.id,range:s,filters:i,config:t.config}}getDynamicTableFilters(e,t,r){const n=[],{top:o,bottom:s,left:i,right:a}=r;for(let r=i;r<=a;r++){const a=r-i,l={left:r,right:r,top:o,bottom:s},c=TS(this.getDynamicTableFilterId(t.id,a),this.getters.getRangeFromZone(e,l),t.config,this.getters.getRangeFromZone);n.push(c)}return n}getDynamicTableFilterId(e,t){return e+"_"+t}exportForExcel(e){for(const t of e.sheets)for(const e of t.tables){const r=Ko(e.range),n={sheetId:t.id,col:r.left,row:r.top},o=this.getters.getCoreTable(n),s=this.getTable(n);"dynamic"===o?.type&&s&&(e.range=es(s.range.zone))}}}).add("custom_colors",class extends NS{customColors={};shouldUpdateColors=!0;static getters=["getCustomColors"];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case"START":for(const e of this.getters.getSheetIds())for(const t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case"UPDATE_CHART":case"CREATE_CHART":this.tryToAddColors(this.getChartColors(e.chartId));break;case"UPDATE_CELL":case"ADD_CONDITIONAL_FORMAT":case"SET_BORDER":case"SET_ZONE_BORDERS":case"SET_FORMATTING":case"CREATE_TABLE":case"UPDATE_TABLE":this.history.update("shouldUpdateColors",!0)}}finalize(){this.shouldUpdateColors&&(this.history.update("shouldUpdateColors",!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return function(e){const t=[{leadColor:vp(255,0,0),colors:[]},{leadColor:vp(255,128,0),colors:[]},{leadColor:vp(128,128,0),colors:[]},{leadColor:vp(128,255,0),colors:[]},{leadColor:vp(0,255,0),colors:[]},{leadColor:vp(0,255,128),colors:[]},{leadColor:vp(0,255,255),colors:[]},{leadColor:vp(0,127,255),colors:[]},{leadColor:vp(0,0,255),colors:[]},{leadColor:vp(127,0,255),colors:[]},{leadColor:vp(128,0,128),colors:[]},{leadColor:vp(255,0,128),colors:[]}];for(const r of e.map(wp)){let e=500,n=0;t.forEach((t,o)=>{const s=(i=r,a=t.leadColor,Math.sqrt(Math.pow(i.r-a.r,2)+Math.pow(i.g-a.g,2)+Math.pow(i.b-a.b,2)));var i,a;e>s&&(e=s,n=o)}),t[n].colors.push(r)}return t.map(e=>e.colors.sort((e,t)=>Cp(e).s-Cp(t).s)).flat().map(Ep)}(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(const t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){const t=new Set;for(const r of this.getters.getStyleColors(e))t.add(r);for(const r of this.getters.getBordersColors(e))t.add(r);return[...t]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),r=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(r.push(t.style.textColor),r.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(r.push(fp(t.minimum.color)),r.push(t.midpoint?fp(t.midpoint.color):void 0),r.push(fp(t.maximum.color)))}return r.filter(Se)}getChartColors(e){const t=this.getters.getChart(e);if(void 0===t)return[];return[...JSON.stringify(t.getDefinition()).matchAll(kC)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{const t=e.config,r=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(r.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(r.headerRow):[],t.totalRow?this.getTableStyleElementColors(r.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(r.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(r.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(r.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(r.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(r.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(r.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(Se):[]}tryToAddColors(e){for(const t of e){if(!pp(t))continue;const e=mp(t);t&&!$.includes(e)&&this.history.update("customColors",e,!0)}}}).add("pivot_ui",class extends NS{static getters=["getPivot","getFirstPivotFunction","getPivotCellSortDirection","getPivotIdFromPosition","getPivotCellFromPosition","generateNewCalculatedMeasureName","isPivotUnused","isSpillPivotFormula"];pivots={};unusedPivotsInFormulas;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){if("START"===e.type)for(const e of this.getters.getPivotIds())this.setupPivot(e)}handle(e){if(Cs.has(e.type))for(const e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case"REFRESH_PIVOT":this.refreshPivot(e.id);break;case"ADD_PIVOT":this.setupPivot(e.pivotId);break;case"DUPLICATE_PIVOT":this.setupPivot(e.newPivotId);break;case"UPDATE_PIVOT":this.setupPivot(e.pivotId,{recreate:!0});break;case"DELETE_SHEET":case"UPDATE_CELL":this.unusedPivotsInFormulas=void 0;break;case"UNDO":case"REDO":{this.unusedPivotsInFormulas=void 0;const t=e.commands.filter(mT);for(const e of t){const t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case"UPDATE_LOCALE":!function(){for(const e in vS)vS[e].set.clear(),vS[e].values={}}()}}getPivotIdFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){const r=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(r){const e=r.args[0]?.toString();return e&&this.getters.getPivotId(e)}}}isSpillPivotFormula(e){const t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){const r=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);return"PIVOT"===r?.functionName}return!1}getFirstPivotFunction(e,t){const r=function(e){return FS(e,hT)[0]}(t);if(!r)return;const{functionName:n,args:o}=r;return{functionName:n,args:o.map(t=>{if("EMPTY"===t.type)return;if("STRING"===t.type||"BOOLEAN"===t.type||"NUMBER"===t.type)return t.value;const r=lT(t);return this.getters.evaluateFormula(e,r)})}}getPivotCellFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||0===FS(t.compiledFormula.tokens,hT).length)return cS;const r=this.getters.getCellPosition(t.id),n=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!n)return cS;let{functionName:o,args:s}=n;const i=s[0];if(!i)return cS;const a=this.getters.getPivotId(i.toString());if(!a)return cS;const l=this.getPivot(a);if(!l.isValid())return cS;if("PIVOT"===o&&!t.content.replaceAll(" ","").toUpperCase().startsWith("=PIVOT"))return cS;if("PIVOT"===o){const t=af(this.getters.getPivotCoreDefinition(a),On(s[1]),On(s[2]),On(s[3]),On(s[4]),On(s[5]),this.getters.getLocale()),n=l.getCollapsedTableStructure().getPivotCells(t),o=e.col-r.col,i=e.row-r.row;return n[o][i]}try{const t=e.row-r.row,n=e.col-r.col;if(s=s.map(e=>D(e)?e[n][t]:e),"PIVOT.HEADER"===o&&"measure"===s.at(-2)){return{type:"MEASURE_HEADER",domain:l.parseArgsToPivotDomain(s.slice(1,-2).map(e=>({value:e}))),measure:s.at(-1)?.toString()||""}}if("PIVOT.HEADER"===o){const e=l.parseArgsToPivotDomain(s.slice(1).map(e=>({value:e})));return{type:"HEADER",domain:e,dimension:jw(l,e).colDomain.length?"COL":"ROW"}}const[i,...a]=s.slice(1);return{type:"VALUE",domain:l.parseArgsToPivotDomain(a.map(e=>({value:e}))),measure:i?.toString()||""}}catch(e){return cS}}generateNewCalculatedMeasureName(e){const t=e.map(e=>e.fieldName);return Xe(v("Calculated measure 1"),t,{compute:(e,t)=>v("Calculated measure %s",t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw new Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){const{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&ES.get(t).isPivotUnused(this.getters,e)}getPivotCellSortDirection(e){const t=this.getters.getPivotIdFromPosition(e),r=this.getters.getPivotCellFromPosition(e);if("EMPTY"===r.type||"HEADER"===r.type||!t)return;const n=this.getters.getPivot(t),o=jw(n,r.domain).colDomain,s=n.definition.sortedColumn;return s?.measure===r.measure&&Ae(s.domain,o)?s.order:"none"}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){const r=re(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(r);else{const t=fT(ES.get(r.type).ui);this.pivots[e]=new t(e,this.custom,{definition:r,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(void 0!==this.unusedPivotsInFormulas)return this.unusedPivotsInFormulas;const e=new Set(this.getters.getPivotIds());for(const t of this.getters.getSheetIds())for(const r in this.getters.getCells(t)){const t=this.getters.getCellPosition(r),n=this.getPivotIdFromPosition(t);if(n&&(e.delete(n),!e.size))return this.unusedPivotsInFormulas=[],[]}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}}).add("cell_icon",class extends NS{static getters=["doesCellHaveGridIcon","getCellIcons","getCellIconRect"];cellIconsCache={};handle(e){"SET_VIEWPORT_OFFSET"!==e.type&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){const r=e.position,n=this.getters.getCellStyle(r)?.verticalAlign;return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,n),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,r){const n=e.x,o=e.x+e.width;switch(t){case"right":return o-r.margin-r.size;case"left":return n+r.margin;default:const e=Math.floor((o-n-r.size)/2);return o-r.size-e}}computeCellIcons(e){const t={left:void 0,right:void 0,center:void 0},r=PC.getAll();for(const n of r){const r=n(this.getters,e);r&&(!t[r.horizontalAlign]||r.priority>t[r.horizontalAlign].priority)&&(t[r.horizontalAlign]=r)}if(t.center&&(t.left||t.right)){const e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(Se)}doesCellHaveGridIcon(e){return Boolean(this.getCellIcons(e).length)}});class qT{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=["copyFormulaStringForSheet","extendRange","getRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeData","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData","getRangeFromZone","getRangesUnion","recomputeRanges","isRangeValid","removeRangesSheetPrefix"];allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?"Success":"InvalidZones":"Success"}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw new Error("Plugins cannot dispatch commands during adaptRanges phase");const t=Wm(e);t&&this.executeOnAllRanges(t)}finalize(){}verifyRangeRemoved(e){return t=>{const r=e(t);return"NONE"===r.changeType||Qo(r.range.zone)?r:{range:r.range,changeType:"REMOVE"}}}executeOnAllRanges(e){this.isAdaptingRanges=!0;const t={applyChange:this.verifyRangeRemoved(e.applyChange),adaptRangeString:(t,r)=>jb(t,r,e),adaptFormulaString:(t,r)=>Yb(t,r,e)};for(const r of this.providers)r(t,e.sheetId,e.sheetName);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,r,n){return e.map(e=>{if(!Qo(e.zone))return e;const o=e.prefixSheet?e.sheetId:n,s=Hm(e),i=Um(e),a={...e.unboundedZone,left:s&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:s?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:i&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:r),bottom:i?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:r)};return function(e){if(Jo(e.zone))return e;const t={...e.unboundedZone},r={...e.zone};let n=e.parts;if(void 0!==t.right&&t.right<t.left){const e=t.right;t.right=t.left,t.left=e,r.right=r.left,r.left=e,n=[{colFixed:n[1]?.colFixed||!1,rowFixed:n[0]?.rowFixed||!1},{colFixed:n[0]?.colFixed||!1,rowFixed:n[1]?.rowFixed||!1}]}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.bottom;t.bottom=t.top,t.top=e,r.bottom=r.top,r.top=e,n=[{colFixed:n[0]?.colFixed||!1,rowFixed:n[1]?.rowFixed||!1},{colFixed:n[1]?.colFixed||!1,rowFixed:n[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:r,parts:n,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}(Lm({...e,sheetId:o,zone:a},this.getters.getSheetSize))})}removeRangesSheetPrefix(e,t){return t.map(t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t)}extendRange(e,t,r){const n="COL"===t?e.zone.right+r:e.zone.right,o="ROW"===t?e.zone.bottom+r:e.zone.bottom,s={left:e.zone.left,top:e.zone.top,right:Hm(e)?void 0:n,bottom:Um(e)?void 0:o};return Lm({...e,zone:s},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!vo.test(t)||!this.getters.tryGetSheet(e))return km(t);const{sheetName:r}=To(t);return Pm({xc:t,sheetId:this.getters.getSheetIdByName(r)||e,invalidSheetName:r&&!this.getters.getSheetIdByName(r)?r:void 0},this.getters.getSheetSize)}getRangeString(e,t,r={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?Bm(e,t,this.getters.getSheetName,r):E.InvalidReference:E.InvalidReference}getRangeDataFromXc(e,t){const r=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(r.sheetId,r.unboundedZone)}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t=this.getters.getUnboundedZone(e,t)}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return Lm({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){const r=e.map(e=>e.unboundedZone),n=t.map(e=>e.unboundedZone);return zo(r,n).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){if(!this.getters.tryGetSheet(e._sheetId))return km(E.InvalidReference);return Lm({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize)}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:r}=To(e);return null!==t.match(vo)&&(!r||void 0!==this.getters.getSheetIdByName(r))}getRangesUnion(e){const t=e.map(e=>e.unboundedZone),r=function(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:e.some(e=>void 0===e.bottom)?void 0:Math.max(...e.map(e=>e.bottom)),right:e.some(e=>void 0===e.right)?void 0:Math.max(...e.map(e=>e.right))}}(...t);return this.getRangeFromZone(e[0].sheetId,r)}copyFormulaStringForSheet(e,t,r,n){if(!r.startsWith("="))return r;const o=_m(r),s=o.dependencies.map(r=>{const o=this.getters.getRangeFromSheetXC(e,r);return"keepSameReference"===n?o:zm(e,t,o)});return this.getters.getFormulaString(t,o.tokens,s)}}class ZT{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}unobserve(e){this.observers.delete(e)}capture(e,t){if(this.observers.get(e))throw new Error("You are already subscribed forever");this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.get(e)||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),this.observers.forEach(t=>t.callbacks.handleEvent(e))}}class YT{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new ZT,this.anchor={cell:{col:0,row:0},zone:ps({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,r){this.stream.capture(e,r),this.anchor=t}registerAsDefault(e,t,r){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,r),this.defaultAnchor=t,this.capture(e,t,r)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}unobserve(e){this.stream.unobserve(e)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}modifyAnchor(e,t,r){const n=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(n,e.zone)},this.processEvent({options:r,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,"overrideSelection",t)}selectCell(e,t){const r=ps({col:e,row:t});return this.selectZone({zone:r,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new Fs("InvalidSelectionStep");const{col:r,row:n}=this.getNextAvailablePosition(e,t);return this.selectCell(r,n)}setAnchorCorner(e,t){const r=this.getters.getActiveSheetId(),{col:n,row:o}=this.anchor.cell,s={left:Math.min(n,e),top:Math.min(o,t),right:Math.max(n,e),bottom:Math.max(o,t)},i=this.getters.expandZone(r,s);if(ss(this.anchor.zone,i))return new Fs("NoChanges");const a={zone:i,cell:{col:n,row:o}};return this.processEvent({mode:"updateAnchor",anchor:a,options:{scrollIntoView:!1}})}addCellToSelection(e,t){const r=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:r,col:e,row:t}));const n=this.getters.expandZone(r,ps({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:n,cell:{col:e,row:t}},mode:"newAnchor"})}commitSelection(){return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:this.anchor,mode:"commitSelection"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new Fs("InvalidSelectionStep");const r=this.getters.getActiveSheetId(),n=this.anchor,{col:o,row:s}=n.cell,{left:i,right:a,top:l,bottom:c}=n.zone,u=this.getStartingPosition(e),[h,d]=this.deltaToTarget(u,e,t);if(0===h&&0===d)return Fs.Success;let f=n.zone;const g=e=>{e=gs(e);const{left:t,right:n,top:o,bottom:s}=this.getters.expandZone(r,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(r)-1,n),top:Math.max(0,o),bottom:Math.min(this.getters.getNumberRows(r)-1,s)}},{cell:m,zone:p}=this.getReferenceAnchor(),{col:b,row:v}=m;let y=0;for(;null!==f;){if(y++,h<0){const e=this.getNextAvailableCol(h,a-(y-1),v);f=p.right<=a-y?g({top:l,left:i,bottom:c,right:e}):null}if(h>0){const e=this.getNextAvailableCol(h,i+(y-1),v);f=i+y<=p.left?g({top:l,left:e,bottom:c,right:a}):null}if(d<0){const e=this.getNextAvailableRow(d,b,c-(y-1));f=p.bottom<=c-y?g({top:l,left:i,bottom:e,right:a}):null}if(d>0){const e=this.getNextAvailableRow(d,b,l+(y-1));f=l+y<=p.top?g({top:e,left:i,bottom:c,right:a}):null}if(f=f?gs(f):f,f&&!ss(f,n.zone))return this.processEvent({options:{scrollIntoView:!0},mode:"updateAnchor",anchor:{zone:f,cell:{col:o,row:s}}})}f=g(ns({top:s,bottom:s,left:o,right:o},gs({top:this.getNextAvailableRow(d,b,l),left:this.getNextAvailableCol(h,i,v),bottom:this.getNextAvailableRow(d,b,c),right:this.getNextAvailableCol(h,a,v)})));const E={zone:f,cell:{col:o,row:s}};return this.processEvent({anchor:E,mode:"updateAnchor",options:{scrollIntoView:!0}})}selectColumn(e,t){const r=this.getters.getActiveSheetId(),n=this.getters.getNumberRows(r)-1;let o={left:e,right:e,top:0,bottom:n};const s=this.getters.findFirstVisibleColRowIndex(r,"ROW");let i,a;switch(t){case"overrideSelection":case"newAnchor":i=e,a=s;break;case"updateAnchor":({col:i,row:a}=this.anchor.cell),o=ns(o,{left:i,right:i,top:s,bottom:n})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:o,cell:{col:i,row:a}},mode:t})}selectRow(e,t){const r=this.getters.getActiveSheetId(),n=this.getters.getNumberCols(r)-1;let o={top:e,bottom:e,left:0,right:n};const s=this.getters.findFirstVisibleColRowIndex(r,"COL");let i,a;switch(t){case"overrideSelection":case"newAnchor":i=s,a=e;break;case"updateAnchor":({col:i,row:a}=this.anchor.cell),o=ns(o,{left:s,right:n,top:a,bottom:a})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:o,cell:{col:i,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(ss(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:ps(t.cell)},"updateAnchor",{scrollIntoView:!1});const r=this.getters.getContiguousZone(e,t.zone);return Ae(r,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:r},"updateAnchor",{scrollIntoView:!1})}selectTableAroundSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},"updateAnchor",{scrollIntoView:!1})}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){const t={...e,previousAnchor:re(this.anchor)},r=this.checkEventAnchorZone(t);return"Success"!==r?new Fs(r):(this.anchor=t.anchor,this.stream.send(t),Fs.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:r}=e;if(!ls(t.col,t.row,r))return"InvalidAnchorZone";const{left:n,right:o,top:s,bottom:i}=r,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",n,o);return void 0===this.getters.findVisibleHeader(a,"ROW",s,i)||void 0===l?"SelectionOutOfBound":"Success"}checkAnchorZoneOrThrow(e){if("InvalidAnchorZone"===this.checkAnchorZone(e))throw new Error("The provided anchor is invalid. The cell must be part of the zone.")}getNextAvailablePosition(e,t=1){const{col:r,row:n}=this.anchor.cell,o=this.deltaToTarget({col:r,row:n},e,t);return{col:this.getNextAvailableCol(o[0],r,n),row:this.getNextAvailableRow(o[1],r,n)}}getNextAvailableCol(e,t,r){const n=this.getters.getActiveSheetId(),o={col:t,row:r};return this.getNextAvailableHeader(e,"COL",t,o,e=>this.getters.isInSameMerge(n,t,r,e,r))}getNextAvailableRow(e,t,r){const n=this.getters.getActiveSheetId(),o={col:t,row:r};return this.getNextAvailableHeader(e,"ROW",r,o,e=>this.getters.isInSameMerge(n,t,r,t,e))}getNextAvailableHeader(e,t,r,n,o){const s=this.getters.getActiveSheetId();if(0===e)return r;const i=Math.sign(e);let a=r+e;for(;o(a);)a+=i;for(;this.getters.isHeaderHidden(s,t,a);)a+=i;return a<0||a>this.getters.getNumberHeaders(s,t)-1?this.getters.isHeaderHidden(s,t,r)?this.getNextAvailableHeader(-i,t,r,n,o):r:a}getReferenceAnchor(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:r,right:n,top:o,bottom:s}=t.zone,{col:i,row:a}=t.cell,l=this.getters.isColHidden(e,i)&&this.getters.findVisibleHeader(e,"COL",r,n)||i,c=this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",o,s)||a;return{cell:{col:l,row:c},zone:this.getters.expandZone(e,{left:l,right:l,top:c,bottom:c})}}deltaToTarget(e,t,r){switch(t){case"up":return"end"!==r?[0,-r]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==r?[0,r]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==r?[-r,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==r?[r,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:r}=this.getPosition();const n=this.anchor.zone;switch(e){case"down":case"up":r=r===n.top?n.bottom:n.top;break;case"left":case"right":t=t===n.right?n.left:n.right}return{col:t,row:r}}getEndOfCluster(e,t,r){const n=this.getters.getActiveSheetId();let o=e;const s=this.getNextCellPosition(e,t,r),i=this.isCellSkippableInCluster({...o,sheetId:n})||this.isCellSkippableInCluster({...s,sheetId:n})?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(o,t,r);if(o.col===e.col&&o.row===e.row)break;const s=this.isCellSkippableInCluster({...e,sheetId:n});if("endOfCluster"===i&&s)break;if("nextCluster"===i&&!s){o=e;break}o=e}return"cols"===t?o.col:o.row}getNextCellPosition(e,t,r){const n={...e};return n["cols"===t?"col":"row"]="cols"===t?this.getNextAvailableCol(r,n.col,n.row):this.getNextAvailableRow(r,n.col,n.row),{col:n.col,row:n.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){const t=this.getters.getMainCellPosition(e),r=this.getters.getEvaluatedCell(t);return r.type===Nu.empty||r.type===Nu.text&&""===r.value}}class jT{changes;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();let r=e[0];const n=e.at(-1),o=e.length-2;for(let t=1;t<=o;t++){const n=e[t];if(void 0===r[n]){const o=e[t+1];r[n]=Oo(o)}r=r[n]}r[n]!==t&&(this.changes?.push({key:n,target:r,before:r[n]}),void 0===t?delete r[n]:r[n]=t)}}function XT(e){return 8===(e=mp(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}const KT=17781237,QT=17781238,JT=88853993,eI=88853994;function tI(e,t,r){const n=[["xmlns:r",Hb],["xmlns:a",xb],["xmlns:c",Rb]],o=rI({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let s=KE``;if(e.data.title?.text){const t=XT(Qb(e.data.backgroundColor)),r=e.data.title.fontSize??z;s=KE`
4
- <c:title>
5
- ${oI(e.data.title.text,t,r,e.data.title)}
6
- <c:overlay val="0" />
7
- </c:title>
8
- `}let i=KE``;switch(e.data.type){case"bar":i=function(e){const t=e.horizontal?"bar":"col",r=e.dataSets.map(e=>e.backgroundColor??""),n=new Lp(e.dataSets.length,r),o=[],s=[];for(const[t,r]of Object.entries(e.dataSets)){const i=XT(n.next()),a=rI({backgroundColor:i,line:{color:i}}),l=KE`
9
- <c:ser>
10
- <c:idx val="${t}"/>
11
- <c:order val="${t}"/>
12
- ${iI(r.trend,i)}
13
- ${lI(r.label)}
14
- ${a}
15
- ${e.labelRange?KE`<c:cat>${hI(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
16
- <c:val> <!-- x-coordinate values -->
17
- ${dI(r.range)}
18
- </c:val>
19
- </c:ser>
20
- `;r.rightYAxis?s.push(l):o.push(l)}const i=e.stacked?"stacked":"clustered",a=e.stacked?100:-20;return KE`
21
- ${o.length?KE`
22
- <c:barChart>
23
- <c:barDir val="${t}"/>
24
- <c:grouping val="${i}"/>
25
- <c:overlap val="${a}"/>
26
- <c:gapWidth val="70"/>
27
- <!-- each data marker in the series does not have a different color -->
28
- <c:varyColors val="0"/>
29
- ${XE(o)}
30
- <c:axId val="${KT}" />
31
- <c:axId val="${JT}" />
32
- </c:barChart>
33
- ${"col"===t?uI("b","c:catAx",KT,JT,e.axesDesign?.x?.title,e.fontColor):uI("b","c:catAx",KT,JT,e.axesDesign?.y?.title,e.fontColor,void 0,"maxMin")}
34
- ${"col"===t?uI("l","c:valAx",JT,KT,e.axesDesign?.y?.title,e.fontColor):uI("l","c:valAx",JT,KT,e.axesDesign?.x?.title,e.fontColor,void 0,void 0,"max")}
35
- `:""}
36
- ${s.length?KE`
37
- <c:barChart>
38
- <c:barDir val="col"/>
39
- <c:grouping val="${i}"/>
40
- <c:overlap val="${a}"/>
41
- <c:gapWidth val="70"/>
42
- <!-- each data marker in the series does not have a different color -->
43
- <c:varyColors val="0"/>
44
- ${XE(s)}
45
- <c:axId val="${17781238}" />
46
- <c:axId val="${88853994}" />
47
- </c:barChart>
48
- ${uI("b","c:catAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,o.length?1:0)}
49
- ${uI("r","c:valAx",88853994,17781238,e.axesDesign?.y1?.title,e.fontColor)}
50
- `:""}`}(e.data);break;case"combo":i=function(e){const t=e.dataSets,r=t.map(e=>e.backgroundColor??""),n=new Lp(t.length,r);let o=t[0];const s=XT(n.next()),i=o.rightYAxis??!1,a=KE`
51
- <c:ser>
52
- <c:idx val="0"/>
53
- <c:order val="0"/>
54
- ${iI(o.trend,s)}
55
- ${lI(o.label)}
56
- ${rI({backgroundColor:s,line:{color:s}})}
57
- ${e.labelRange?KE`<c:cat>${hI(e.labelRange)}</c:cat>`:""}
58
- <!-- x-coordinate values -->
59
- <c:val>
60
- ${dI(o.range)}
61
- </c:val>
62
- </c:ser>
63
- `,l=[],c=[];for(let r=1;r<t.length;r++){o=t[r];const s=XT(n.next()),i=rI({backgroundColor:s,line:{color:s}}),a=KE`
64
- <c:ser>
65
- <c:idx val="${r}"/>
66
- <c:order val="${r}"/>
67
- <c:smooth val="0"/>
68
- <c:marker>
69
- <c:symbol val="circle" />
70
- <c:size val="5"/>
71
- ${i}
72
- </c:marker>
73
- ${iI(o.trend,s)}
74
- ${lI(o.label)}
75
- ${i}
76
- ${e.labelRange?KE`<c:cat>${hI(e.labelRange)}</c:cat>`:""}
77
- <!-- x-coordinate values -->
78
- <c:val>
79
- ${dI(o.range)}
80
- </c:val>
81
- </c:ser>
82
- `;o.rightYAxis?c.push(a):l.push(a)}const u=e.stacked?100:-20;return KE`
83
- <c:barChart>
84
- <c:barDir val="col"/>
85
- <c:grouping val="clustered"/>
86
- <c:overlap val="${u}"/>
87
- <c:gapWidth val="70"/>
88
- <!-- each data marker in the series does not have a different color -->
89
- <c:varyColors val="0"/>
90
- ${a}
91
- <c:axId val="${i?QT:KT}" />
92
- <c:axId val="${i?eI:JT}" />
93
- </c:barChart>
94
- ${l.length?KE`
95
- <c:lineChart>
96
- <c:grouping val="standard"/>
97
- <!-- each data marker in the series does not have a different color -->
98
- <c:varyColors val="0"/>
99
- ${XE(l)}
100
- <c:axId val="${KT}" />
101
- <c:axId val="${JT}" />
102
- </c:lineChart>
103
- `:""}
104
- ${c.length?KE`
105
- <c:lineChart>
106
- <c:grouping val="standard"/>
107
- <!-- each data marker in the series does not have a different color -->
108
- <c:varyColors val="0"/>
109
- ${XE(c)}
110
- <c:axId val="${QT}" />
111
- <c:axId val="${eI}" />
112
- </c:lineChart>
113
- `:""}
114
- ${!i||l.length?KE`
115
- ${uI("b","c:catAx",KT,JT,e.axesDesign?.x?.title,e.fontColor,0)}
116
- ${uI("l","c:valAx",JT,KT,e.axesDesign?.y?.title,e.fontColor)}
117
- `:""}
118
- ${i||c.length?KE`
119
- ${uI("b","c:catAx",QT,eI,e.axesDesign?.x?.title,e.fontColor,l.length||!i?1:0)}
120
- ${uI("r","c:valAx",eI,QT,e.axesDesign?.y1?.title,e.fontColor)}
121
- `:""}
122
- `}(e.data);break;case"pyramid":i=function(e){const t=e.dataSets,r=t.map(e=>e.backgroundColor??""),n=new Lp(t.length,r),o=t[0],s=t[1],i=XT(n.next()),a=XT(n.next()),{maxValue:l,majorUnit:c}=function(e){const t=3,r=((e,t)=>{let r=Math.ceil(e);for(;r%t!==0;)r++;return r})(e,t),n=r/t;return{maxValue:r,majorUnit:n}}(e.maxValue),u=e.labelRange?KE`<c:cat>${hI(e.labelRange)}</c:cat>`:"",h=KE`
123
- <c:ser>
124
- <c:idx val="0"/>
125
- <c:order val="0"/>
126
- <c:invertIfNegative val="0" />
127
- ${lI(o.label)}
128
- ${rI({backgroundColor:i,line:{color:i}})}
129
- ${u}
130
- <!-- x-coordinate values -->
131
- <c:val>
132
- ${dI(o.range)}
133
- </c:val>
134
- </c:ser>
135
- `,d=KE`
136
- <c:ser>
137
- <c:idx val="1"/>
138
- <c:order val="1"/>
139
- <c:invertIfNegative val="0" />
140
- ${lI(s.label)}
141
- ${rI({backgroundColor:a,line:{color:a}})}
142
- ${e.labelRange?KE`<c:cat>${hI(e.labelRange)}</c:cat>`:""}
143
- <!-- x-coordinate values -->
144
- <c:val>
145
- ${dI(s.range)}
146
- </c:val>
147
- </c:ser>
148
- `;return KE`
149
- <c:barChart>
150
- <c:barDir val="bar"/>
151
- <c:grouping val="clustered"/>
152
- <c:varyColors val="0" />
153
- ${h}
154
- <c:gapWidth val="50" />
155
- <c:axId val="${KT}" />
156
- <c:axId val="${JT}" />
157
- </c:barChart>
158
- <c:barChart>
159
- <c:barDir val="bar"/>
160
- <c:grouping val="clustered"/>
161
- <c:varyColors val="0" />
162
- ${d}
163
- <c:gapWidth val="50" />
164
- <c:axId val="${QT}" />
165
- <c:axId val="${eI}" />
166
- </c:barChart>
167
- ${uI("r","c:catAx",KT,JT,e.axesDesign?.y?.title,e.fontColor,0,"maxMin","autoZero","high")}
168
- ${uI("b","c:valAx",JT,KT,e.axesDesign?.x?.title,e.fontColor,0,"maxMin","max","nextTo",l,c,"#0;#0")}
169
- ${uI("t","c:valAx",eI,QT,void 0,e.fontColor,1)}
170
- ${uI("l","c:catAx",QT,eI,void 0,e.fontColor,1,"maxMin")}
171
- `}(e.data);break;case"line":i=function(e){const t=e.dataSets.map(e=>e.backgroundColor??""),r=new Lp(e.dataSets.length,t),n=[],o=[];for(const[t,s]of Object.entries(e.dataSets)){const i=XT(r.next()),a=rI({line:{width:2.5,style:"solid",color:i}}),l=KE`
172
- <c:ser>
173
- <c:idx val="${t}"/>
174
- <c:order val="${t}"/>
175
- <c:smooth val="0"/>
176
- <c:marker>
177
- <c:symbol val="circle" />
178
- <c:size val="5"/>
179
- ${rI({backgroundColor:i,line:{color:i}})}
180
- </c:marker>
181
- ${iI(s.trend,i)}
182
- ${lI(s.label)}
183
- ${a}
184
- ${e.labelRange?KE`<c:cat>${hI(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
185
- <c:val> <!-- x-coordinate values -->
186
- ${dI(s.range)}
187
- </c:val>
188
- </c:ser>
189
- `;s.rightYAxis?o.push(l):n.push(l)}const s=e.stacked?"stacked":"standard";return KE`
190
- ${n.length?KE`
191
- <c:lineChart>
192
- <c:grouping val="${s}"/>
193
- <!-- each data marker in the series does not have a different color -->
194
- <c:varyColors val="0"/>
195
- ${XE(n)}
196
- <c:axId val="${KT}" />
197
- <c:axId val="${JT}" />
198
- </c:lineChart>
199
- ${uI("b","c:catAx",KT,JT,e.axesDesign?.x?.title,e.fontColor)}
200
- ${uI("l","c:valAx",JT,KT,e.axesDesign?.y?.title,e.fontColor)}
201
- `:""}
202
- ${o.length?KE`
203
- <c:lineChart>
204
- <c:grouping val="${s}"/>
205
- <!-- each data marker in the series does not have a different color -->
206
- <c:varyColors val="0"/>
207
- ${XE(o)}
208
- <c:axId val="${17781238}" />
209
- <c:axId val="${88853994}" />
210
- </c:lineChart>
211
- ${uI("b","c:catAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,n.length?1:0)}
212
- ${uI("r","c:valAx",88853994,17781238,e.axesDesign?.y1?.title,e.fontColor)}
213
- `:""}
214
- `}(e.data);break;case"scatter":i=function(e){const t=e.dataSets.map(e=>e.backgroundColor??""),r=new Lp(e.dataSets.length,t),n=[],o=[];for(const[t,s]of Object.entries(e.dataSets)){const i=XT(r.next()),a=KE`
215
- <c:ser>
216
- <c:idx val="${t}"/>
217
- <c:order val="${t}"/>
218
- <c:smooth val="0"/>
219
- <c:spPr>
220
- <a:ln w="19050" cap="rnd">
221
- <a:noFill/>
222
- <a:round/>
223
- </a:ln>
224
- <a:effectLst/>
225
- </c:spPr>
226
- <c:marker>
227
- <c:symbol val="circle" />
228
- <c:size val="5"/>
229
- ${rI({backgroundColor:i,line:{color:i}})}
230
- </c:marker>
231
- ${iI(s.trend,i)}
232
- ${lI(s.label)}
233
- ${e.labelRange?KE`<c:xVal> <!-- x-coordinate values -->
234
- ${dI(e.labelRange)}
235
- </c:xVal>`:""}
236
- <c:yVal> <!-- y-coordinate values -->
237
- ${dI(s.range)}
238
- </c:yVal>
239
- </c:ser>
240
- `;s.rightYAxis?o.push(a):n.push(a)}return KE`
241
- ${n.length?KE`
242
- <c:scatterChart>
243
- <!-- each data marker in the series does not have a different color -->
244
- <c:varyColors val="0"/>
245
- <c:scatterStyle val="lineMarker"/>
246
- ${XE(n)}
247
- <c:axId val="${KT}" />
248
- <c:axId val="${JT}" />
249
- </c:scatterChart>
250
- ${uI("b","c:valAx",KT,JT,e.axesDesign?.x?.title,e.fontColor)}
251
- ${uI("l","c:valAx",JT,KT,e.axesDesign?.y?.title,e.fontColor)}
252
- `:""}
253
- ${o.length?KE`
254
- <c:scatterChart>
255
- <!-- each data marker in the series does not have a different color -->
256
- <c:varyColors val="0"/>
257
- <c:scatterStyle val="lineMarker"/>
258
- ${XE(o)}
259
- <c:axId val="${17781238}" />
260
- <c:axId val="${88853994}" />
261
- </c:scatterChart>
262
- ${uI("b","c:valAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,n.length?1:0)}
263
- ${uI("r","c:valAx",88853994,17781238,e.axesDesign?.y1?.title,e.fontColor)}
264
- `:""}`}(e.data);break;case"pie":i=function(e,t,r){const n=We(e.dataSets.map(e=>Vy(e.range,t,r))),o=new Lp(n),s=le(0,n).map(()=>XT(o.next())),i=[];for(const[n,o]of Object.entries(e.dataSets).reverse()){const a=Vy(o.range,t,r),l=[];for(const e of le(0,a)){const t=rI({backgroundColor:s[e],line:{color:"FFFFFF",width:1.5}});l.push(KE`
265
- <c:dPt>
266
- <c:idx val="${e}"/>
267
- ${t}
268
- </c:dPt>
269
- `)}i.push(KE`
270
- <c:ser>
271
- <c:idx val="${n}"/>
272
- <c:order val="${n}"/>
273
- ${lI(o.label)}
274
- ${XE(l)}
275
- ${cI({showLeaderLines:!0})}
276
- ${e.labelRange?KE`<c:cat>${hI(e.labelRange)}</c:cat>`:""}
277
- <c:val>
278
- ${dI(o.range)}
279
- </c:val>
280
- </c:ser>
281
- `)}return KE`
282
- <c:doughnutChart>
283
- <c:varyColors val="1" />
284
- <c:holeSize val="${e.pieHolePercentage??(e.isDoughnut?50:0)}" />
285
- ${cI()}
286
- ${XE(i)}
287
- </c:doughnutChart>
288
- `}(e.data,t,r);break;case"radar":i=function(e){const t=e.dataSets.map(e=>e.backgroundColor??""),r=new Lp(e.dataSets.length,t),n=[];for(const[t,o]of Object.entries(e.dataSets)){const s=XT(r.next()),i=rI({line:{width:2.5,style:"solid",color:s}}),a=KE`
289
- <c:ser>
290
- <c:idx val="${t}"/>
291
- <c:order val="${t}"/>
292
- <c:smooth val="0"/>
293
- <c:marker>
294
- <c:symbol val="circle" />
295
- <c:size val="5"/>
296
- ${rI({backgroundColor:s,line:{color:s}})}
297
- </c:marker>
298
- ${lI(o.label)}
299
- ${i}
300
- ${e.labelRange?KE`<c:cat>${hI(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
301
- <c:val> <!-- x-coordinate values -->
302
- ${dI(o.range)}
303
- </c:val>
304
- </c:ser>
305
- `;n.push(a)}return KE`
306
- ${KE`
307
- <c:radarChart>
308
- <c:radarStyle val="marker"/>
309
- <c:varyColors val="0"/>
310
- ${XE(n)}
311
- <c:axId val="${KT}" />
312
- <c:axId val="${JT}" />
313
- </c:radarChart>
314
- ${uI("b","c:catAx",KT,JT,e.axesDesign?.x?.title,e.fontColor)}
315
- ${uI("l","c:valAx",JT,KT,e.axesDesign?.y?.title,e.fontColor)}
316
- `}
317
- `}(e.data)}let a="none";switch(e.data.legendPosition){case"bottom":a="b";break;case"left":a="l";break;case"right":a="r";break;case"top":a="t"}const l=e.data.fontColor,c=KE`
318
- <c:chartSpace ${qE(n)}>
319
- <c:roundedCorners val="0" />
320
- <!-- <manualLayout/> to manually position the chart in the figure container -->
321
- ${o}
322
- <c:chart>
323
- ${s}
324
- <c:autoTitleDeleted val="0" />
325
- <c:plotArea>
326
- <!-- how the chart element is placed on the chart -->
327
- <c:layout />
328
- ${i}
329
- ${rI({backgroundColor:e.data.backgroundColor})}
330
- </c:plotArea>
331
- ${"none"!==a?function(e,t){return KE`
332
- <c:legend>
333
- <c:legendPos val="${e}"/>
334
- <c:overlay val="0"/>
335
- ${sI(10,t)}
336
- </c:legend>
337
- `}(a,l):""}
338
- </c:chart>
339
- </c:chartSpace>
340
- `;return ZE(c)}function rI(e){return KE`
341
- <c:spPr>
342
- ${e.backgroundColor?nI(e.backgroundColor):""}
343
- ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",My(e.width)]);const r=e.style?KE`<a:prstDash val="${e.style}"/>`:"";return KE`
344
- <a:ln ${qE(t)}>
345
- ${nI(e.color)}
346
- ${r}
347
- </a:ln>
348
- `}(e.line):""}
349
- </c:spPr>
350
- `}function nI(e){return KE`
351
- <a:solidFill>
352
- <a:srgbClr val="${e}"/>
353
- </a:solidFill>
354
- `}function oI(e,t="000000",r=16,n={}){return KE`
355
- <c:tx>
356
- <c:rich>
357
- <a:bodyPr />
358
- <a:lstStyle />
359
- <a:p>
360
- <a:pPr lvl="0">
361
- <a:defRPr b="${n?.bold?1:0}" i="${n?.italic?1:0}">
362
- ${nI(t)}
363
- <a:latin typeface="+mn-lt"/>
364
- </a:defRPr>
365
- </a:pPr>
366
- <a:r> <!-- Runs -->
367
- <a:rPr b="${n?.bold?1:0}" i="${n?.italic?1:0}" sz="${100*r}"/>
368
- <a:t>${e}</a:t>
369
- </a:r>
370
- </a:p>
371
- </c:rich>
372
- </c:tx>
373
- `}function sI(e=12,t="000000",r=!1,n=!1){return KE`
374
- <c:txPr>
375
- <a:bodyPr/>
376
- <a:lstStyle/>
377
- <a:p>
378
- <a:pPr lvl="0">
379
- <a:defRPr ${qE([["b",r?"1":"0"],["i",n?"1":"0"],["sz",100*e]])}>
380
- ${nI(t)}
381
- <a:latin typeface="+mn-lt"/>
382
- </a:defRPr>
383
- </a:pPr>
384
- </a:p>
385
- </c:txPr>
386
- `}function iI(e,t){if(!e)return KE``;const{type:r,order:n,window:o}=e,s=[];switch(r){case"poly":n&&n>1?(s.push(KE`<c:trendlineType val="poly" />`),s.push(KE`<c:order val="${n}" />`)):s.push(KE`<c:trendlineType val="linear" />`);break;case"movingAvg":s.push(KE`<c:trendlineType val="movingAvg" />`),o&&s.push(KE`<c:period val="${o}" />`);break;default:s.push(KE`<c:trendlineType val="${r}" />`)}return KE`
387
- <c:trendline>
388
- ${function(e,t){if(!e)return KE``;const r=[["val",e.color?XT(e.color).slice(-6):aI(t)]];return KE`
389
- <c:spPr>
390
- <a:ln w="19050" cap="rnd">
391
- <a:solidFill>
392
- <a:srgbClr ${qE(r)}/>
393
- </a:solidFill>
394
- <a:prstDash val="sysDot" />
395
- </a:ln>
396
- <a:effectLst />
397
- </c:spPr>
398
- <c:dispRSqr val="0" />
399
- <c:dispEq val="0" />
400
- `}(e,t)}
401
- ${XE(s)}
402
- </c:trendline>
403
- `}function aI(e){return XT(Rp(e,.5))}function lI(e){return e?"text"in e&&e.text?KE`
404
- <c:tx><c:v>${e.text}</c:v></c:tx>
405
- `:"reference"in e&&e.reference?KE`
406
- <c:tx>
407
- ${hI(e.reference)}
408
- </c:tx>
409
- `:KE``:KE``}function cI({showLeaderLines:e}={showLeaderLines:!1}){return KE`
410
- <dLbls>
411
- <c:showLegendKey val="0"/>
412
- <c:showVal val="0"/>
413
- <c:showCatName val="0"/>
414
- <c:showSerName val="0"/>
415
- <c:showPercent val="0"/>
416
- <c:showBubbleSize val="0"/>
417
- <c:showLeaderLines val="${e?"1":"0"}"/>
418
- </dLbls>
419
- `}function uI(e,t,r,n,o,s,i=0,a="minMax",l,c="nextTo",u,h,d="General"){const f=o?.color?XT(o.color):s,g=o?.fontSize??12;return KE`
420
- <${t}>
421
- <c:axId val="${r}"/>
422
- <c:crossAx val="${n}"/> <!-- reference to the other axe of the chart -->
423
- <c:crosses val="${l||("b"===e||"l"===e?"min":"max")}"/>
424
- <c:auto val="1"/>
425
- ${"c:valAx"===t?KE`<c:crossBetween val="between" />`:""}
426
- <c:delete val="${i}"/> <!-- by default, axis are not displayed -->
427
- <c:scaling>
428
- <c:orientation val="${a}" />
429
- ${u?KE`<c:max val="${u}" />`:""}
430
- ${u?KE`<c:min val="${-u}" />`:""}
431
- </c:scaling>
432
- ${h?KE`<c:majorUnit val="${h}" />`:""}
433
- <c:axPos val="${e}" />
434
- <c:tickLblPos val="${c}" />
435
- ${function(e="B7B7B7"){return KE`
436
- <c:majorGridlines>
437
- ${rI({line:{color:e}})}
438
- </c:majorGridlines>
439
- `}()}
440
- <c:majorTickMark val="out" />
441
- <c:minorTickMark val="none" />
442
- <c:numFmt formatCode="${d}" sourceLinked="${"General"===d?"1":"0"}" />
443
- <c:title>
444
- ${oI(o?.text??"",f,g,o)}
445
- </c:title>
446
- ${sI(10,s)}
447
- </${t}>
448
- <!-- <tickLblPos/> omitted -->
449
- `}function hI(e){return KE`
450
- <c:strRef>
451
- <c:f>${e}</c:f>
452
- </c:strRef>
453
- `}function dI(e){return KE`
454
- <c:numRef>
455
- <c:f>${e}</c:f>
456
- <c:numCache />
457
- </c:numRef>
458
- `}function fI(e,t,r){if(!e)return{attrs:[],node:KE``};const n=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n";default:return}}(t);if(void 0===n)return{attrs:[],node:KE``};var o;return{attrs:[["cm","1"],["t",n]],node:KE`<f t="array" ref="${r}">${mI(e)}</f><v>${(o=t)===E.InvalidReference?"#REF!":o}</v>`}}function gI(e,t,r=!1){let n=e;const o=[],s=n.trim().toUpperCase();return!r&&["TRUE","FALSE"].includes(s)?(n="TRUE"===s?"1":"0",o.push(["t","b"])):!r&&Ot(n,xr)||(n=_y(e,t),o.push(["t","s"])),{attrs:o,node:KE`<v>${n}</v>`}}function mI(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Em(e)}catch(t){return e}return t=Sm(t,"STRING",pI),t=Sm(t,"FUNCALL",e=>e=function(e){const t=e.value.toUpperCase(),r=e.args,n=Wb[t];if(n){const o=nm.content[t].args.filter(e=>!e.optional),s=o.length-e.args.length;if(s)for(let t=e.args.length;t<o.length;t++){const e=n[t-s];r.push({type:e.type,value:e.value,tokenEndIndex:0,tokenStartIndex:0})}}return{...e,args:r}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:qb.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()}))),t=Sm(t,"REFERENCE",e=>e.value===E.InvalidReference?{...e,value:"#REF!"}:e),t?lT(t):e}function pI(e){const t=e.value.replace(new RegExp('"',"g"),""),r=gt(t,xr);if(r){const n=[];return(st.test(t)||it.test(t))&&n.push("yyyy-mm-dd"),ut.test(t)&&n.push("hh:mm:ss"),{...e,value:Xr(r.value,{format:n.join(" "),locale:xr})}}return{...e,value:e.value.replace(/\\"/g,'""')}}function bI(e,t){const r=[];for(const n of t)switch(n.rule.type){case"CellIsRule":r.push(vI(n,n.rule,e));break;case"ColorScaleRule":r.push(EI(n,n.rule));break;case"IconSetRule":r.push(wI(n,n.rule));break;case"DataBarRule":r.push(yI(n,n.rule));break;default:console.warn(`Conditional formatting ${n.rule.type} not implemented`)}return r}function vI(e,t,r){const n=SI(e),o=Ey(t.operator);n.push(...function(e){const t=Ey(e.operator);switch(e.operator){case"containsText":case"notContainsText":case"beginsWithText":case"endsWithText":return[["type",t],["text",e.values[0]]];case"isEmpty":case"isNotEmpty":return[["type",t]];case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"isBetween":case"isNotBetween":case"dateIsBefore":case"dateIsAfter":case"dateIsOnOrAfter":case"dateIsOnOrBefore":return[["type","cellIs"]];case"dateIs":case"customFormula":return[["type","expression"]]}}(t)),o.length&&n.push(["operator",o]);const s=function(e,t){const r=e[0].split(":")[0],n=t.values;switch(t.operator){case"containsText":return[`NOT(ISERROR(SEARCH("${n[0]}",${r})))`];case"notContainsText":return[`ISERROR(SEARCH("${n[0]}",${r}))`];case"beginsWithText":return[`LEFT(${r},LEN("${n[0]}"))="${n[0]}"`];case"endsWithText":return[`RIGHT(${r},LEN("${n[0]}"))="${n[0]}"`];case"isEmpty":return[`LEN(TRIM(${r}))=0`];case"isNotEmpty":return[`LEN(TRIM(${r}))>0`];case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":return[n[0]];case"customFormula":return n[0].startsWith("=")?[n[0].slice(1)]:[n[0]];case"isBetween":case"isNotBetween":return[n[0],n[1]];case"dateIs":switch(t.dateValue){case"exactDate":{const e=`ROUNDDOWN(${n[0].startsWith("=")?n[0].slice(1):(uE(n[0],xr)||"").toString()},0)`;return[`AND(${r}>=${e},${r}<${e}+1)`]}case"today":return[`AND(${r}>=TODAY(),${r}<TODAY()+1)`];case"yesterday":return[`AND(${r}>=TODAY()-1,${r}<TODAY())`];case"tomorrow":return[`AND(${r}>=TODAY()+1,${r}<TODAY()+2)`];case"lastWeek":return[`AND(${r}>=TODAY()-7,${r}<TODAY())`];case"lastMonth":return[`AND(${r}>=EDATE(TODAY(),-1),${r}<TODAY())`];case"lastYear":return[`AND(${r}>=EDATE(TODAY(),-12),${r}<TODAY())`];case void 0:throw new Error("dateValue should be defined")}case"dateIsBefore":case"dateIsAfter":case"dateIsOnOrAfter":case"dateIsOnOrBefore":switch(t.dateValue){case"exactDate":return n[0].startsWith("=")?[n[0].slice(1)]:[(uE(n[0],xr)||"").toString()];case"today":return["TODAY()"];case"yesterday":return["TODAY()-1"];case"tomorrow":return["TODAY()+1"];case"lastWeek":return["TODAY()-7"];case"lastMonth":return["EDATE(TODAY(),-1)"];case"lastYear":return["EDATE(TODAY(),-12)"];case void 0:throw new Error("dateValue should be defined")}}}(e.ranges,t).map(e=>KE`<formula>${e}</formula>`),i={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};return t.style.fillColor&&(i.fill={fgColor:{rgb:t.style.fillColor}}),n.push(["dxfId",_y(i,r)]),KE`
459
- <conditionalFormatting sqref="${e.ranges.join(" ")}">
460
- <cfRule ${qE(n)}>
461
- ${XE(s)}
462
- </cfRule>
463
- </conditionalFormatting>
464
- `}function yI(e,t){const r=SI(e);return r.push(["type","dataBar"]),KE`
465
- <conditionalFormatting sqref="${e.ranges.join(" ")}">
466
- <cfRule ${qE(r)}>
467
- <dataBar>
468
- <cfvo type="min" val="0"/>
469
- <cfvo type="max" val="100"/>
470
- <color rgb="${XT(fp(t.color))}"/>
471
- </dataBar>
472
- </cfRule>
473
- </conditionalFormatting>
474
- `}function EI(e,t){const r=SI(e);r.push(["type","colorScale"]);const n=[];for(const o of e.ranges){const e=[],s=[];let i=!0;for(const r of["minimum","midpoint","maximum"]){const n=t[r];n&&("formula"!==n.type?(e.push(xI(n,r)),s.push([["rgb",XT(fp(n.color))]])):i=!1)}if(!i){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map(e=>KE`<cfvo ${qE(e)}/>`),l=s.map(e=>KE`<color ${qE(e)}/>`);n.push(KE`
475
- <conditionalFormatting sqref="${o}">
476
- <cfRule ${qE(r)}>
477
- <colorScale>
478
- ${XE(a)}
479
- ${XE(l)}
480
- </colorScale>
481
- </cfRule>
482
- </conditionalFormatting>
483
- `)}return XE(n)}function wI(e,t){const r=SI(e);r.push(["type","iconSet"]);const n=[];for(const o of e.ranges){const e=[[["type","percent"],["val",0]]];let s=!0;for(const r of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[r].type){s=!1;continue}const n=t[r];e.push([...xI(n,r),["gte","ge"===n.operator?"1":"0"]])}if(!s){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const i=e.map(e=>KE`<cfvo ${qE(e)} />`),a=[["iconSet",TI(t.icons)]];CI(t.icons)&&a.push(["reverse","1"]),n.push(KE`
484
- <conditionalFormatting sqref="${o}">
485
- <cfRule ${qE(r)}>
486
- <iconSet ${qE(a)}>
487
- ${XE(i)}
488
- </iconSet>
489
- </cfRule>
490
- </conditionalFormatting>
491
- `)}return XE(n)}function SI(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function CI(e){const t=Fv[II(e)];return e.upper===t.bad&&e.lower===t.good}function TI(e){return gb[II(e)]}function II(e){return Object.keys(Fv).find(t=>Object.values(Fv[t]).includes(e.upper))||"dots"}function xI(e,t){const r=function(e,t){switch(e){case"value":return"minimum"===t?"min":"max";case"number":return"num";case"percentage":return"percent";default:return e}}(e.type,t),n=[["type",r]];if("min"!==r&&"max"!==r){let t=e.value;if("formula"===r)try{t=mI(e.value)}catch(r){t=e.value}n.push(["val",t])}return n}function RI(e){const t=e.length;if(0===t)return[];const r=[new Ev(`<dataValidations count="${t}">`)];for(const t of e)switch(t.criterion.type){case"dateIs":case"dateIsBefore":case"dateIsOnOrBefore":case"dateIsAfter":case"dateIsOnOrAfter":case"dateIsBetween":case"dateIsNotBetween":r.push(AI(t));break;case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"isBetween":case"isNotBetween":r.push(OI(t));break;case"isValueInRange":case"isValueInList":r.push(_I(t));break;case"customFormula":r.push(DI(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`)}return r.push(new Ev("</dataValidations>")),r}function AI(e){const t=e.criterion,r=mI(t.values[0]),n=t.values[1]?mI(t.values[1]):void 0,o=function(e){return Object.keys(hy).find(t=>hy[t]===e)}(e.criterion.type),s=FI(e);return s.push(["type","date"],["operator",o]),n?KE`
492
- <dataValidation ${qE(s)}>
493
- <formula1>${kt(r,xr)}</formula1>
494
- <formula2>${kt(n,xr)}</formula2>
495
- </dataValidation>
496
- `:KE`
497
- <dataValidation ${qE(s)}>
498
- <formula1>${kt(r,xr)}</formula1>
499
- </dataValidation>
500
- `}function OI(e){const t=e.criterion,r=mI(t.values[0]),n=t.values[1]?mI(t.values[1]):void 0,o=function(e){return Object.keys(uy).find(t=>uy[t]===e)}(e.criterion.type),s=FI(e);return s.push(["type","decimal"],["operator",o]),n?KE`
501
- <dataValidation ${qE(s)}>
502
- <formula1>${r}</formula1>
503
- <formula2>${n}</formula2>
504
- </dataValidation>
505
- `:KE`
506
- <dataValidation ${qE(s)}>
507
- <formula1>${r}</formula1>
508
- </dataValidation>
509
- `}function _I(e){const t=e.criterion,r="isValueInRange"===e.criterion.type?mI(t.values[0]):`"${t.values.join(",")}"`,n=FI(e);return n.push(["type","list"]),KE`
510
- <dataValidation ${qE(n)}>
511
- <formula1>${r}</formula1>
512
- </dataValidation>
513
- `}function DI(e){const t=mI(e.criterion.values[0]),r=FI(e);return r.push(["type","custom"]),KE`
514
- <dataValidation ${qE(r)}>
515
- <formula1>${t}</formula1>
516
- </dataValidation>
517
- `}function FI(e){return[["allowBlank","1"],["showInputMessage","1"],["showErrorMessage","1"],["errorStyle",e.isBlocking?"":"warning"],["sqref",e.ranges.join(" ")]]}function NI(e,t,r,n){const o=[["xmlns:xdr",wb],["xmlns:r",Hb],["xmlns:a",xb],["xmlns:c",Rb]],s=[];for(const[o,i]of Object.entries(r))switch(i?.tag){case"chart":s.push(LI(i,t,e[o],n));break;case"image":s.push(PI(i,t,e[o]))}return ZE(KE`
518
- <xdr:wsDr ${qE(o)}>
519
- ${XE(s)}
520
- </xdr:wsDr>
521
- `)}function MI(e,t){const{col:r,row:n,offset:o,width:s,height:i}=e,{x:a,y:l}=o,c=Object.values(t.rows),{index:u,offset:h}=VI(c,n,l),{index:d,offset:f}=VI(c,n,l+i),g=Object.values(t.cols),{index:m,offset:p}=VI(g,r,a),{index:b,offset:v}=VI(g,r,a+s);return{from:{col:m,colOff:p,row:u,rowOff:h},to:{col:b,colOff:v,row:d,rowOff:f}}}function VI(e,t,r){let n=0;for(const[o,s]of e.slice(t).entries()){if(n<=r&&r<n+s.size)return{index:t+o,offset:My(r-n+1)};o<e.length-1&&(n+=s.size)}return{index:e.length-1,offset:My(r-n+1)}}function LI(e,t,r,n){const{from:o,to:s}=MI(e,t),i=Dy(e.id,n),a=[["id",i],["name",`Chart ${i}`],["title","Chart"]];return KE`
522
- <xdr:twoCellAnchor>
523
- <xdr:from>
524
- <xdr:col>${o.col}</xdr:col>
525
- <xdr:colOff>${o.colOff}</xdr:colOff>
526
- <xdr:row>${o.row}</xdr:row>
527
- <xdr:rowOff>${o.rowOff}</xdr:rowOff>
528
- </xdr:from>
529
- <xdr:to>
530
- <xdr:col>${s.col}</xdr:col>
531
- <xdr:colOff>${s.colOff}</xdr:colOff>
532
- <xdr:row>${s.row}</xdr:row>
533
- <xdr:rowOff>${s.rowOff}</xdr:rowOff>
534
- </xdr:to>
535
- <xdr:graphicFrame>
536
- <xdr:nvGraphicFramePr>
537
- <xdr:cNvPr ${qE(a)} />
538
- <xdr:cNvGraphicFramePr />
539
- </xdr:nvGraphicFramePr>
540
- <xdr:xfrm>
541
- <a:off x="0" y="0"/>
542
- <a:ext cx="0" cy="0"/>
543
- </xdr:xfrm>
544
- <a:graphic>
545
- <a:graphicData uri="${Rb}">
546
- <c:chart r:id="${r}" />
547
- </a:graphicData>
548
- </a:graphic>
549
- </xdr:graphicFrame>
550
- <xdr:clientData fLocksWithSheet="0"/>
551
- </xdr:twoCellAnchor>
552
- `}function PI(e,t,r){const{from:n,to:o}=MI(e,t),s=Ny(e.id),i=[["id",s],["name",`Image ${s}`],["title","Image"]],a=My(e.width),l=My(e.height);return KE`
553
- <xdr:twoCellAnchor editAs="oneCell">
554
- <xdr:from>
555
- <xdr:col>${n.col}</xdr:col>
556
- <xdr:colOff>${n.colOff}</xdr:colOff>
557
- <xdr:row>${n.row}</xdr:row>
558
- <xdr:rowOff>${n.rowOff}</xdr:rowOff>
559
- </xdr:from>
560
- <xdr:to>
561
- <xdr:col>${o.col}</xdr:col>
562
- <xdr:colOff>${o.colOff}</xdr:colOff>
563
- <xdr:row>${o.row}</xdr:row>
564
- <xdr:rowOff>${o.rowOff}</xdr:rowOff>
565
- </xdr:to>
566
- <xdr:pic>
567
- <xdr:nvPicPr>
568
- <xdr:cNvPr ${qE(i)}/>
569
- <xdr:cNvPicPr preferRelativeResize="0"/>
570
- </xdr:nvPicPr>
571
- <xdr:blipFill>
572
- <a:blip cstate="print" r:embed="${r}"/>
573
- <a:stretch>
574
- <a:fillRect/>
575
- </a:stretch>
576
- </xdr:blipFill>
577
- <xdr:spPr>
578
- <a:xfrm>
579
- <a:ext cx="${a}" cy="${l}" />
580
- </a:xfrm>
581
- <a:prstGeom prst="rect">
582
- <a:avLst/>
583
- </a:prstGeom>
584
- <a:noFill/>
585
- </xdr:spPr>
586
- </xdr:pic>
587
- <xdr:clientData fLocksWithSheet="0"/>
588
- </xdr:twoCellAnchor>
589
- `}function kI(e){return Ce(e)?KE``:KE`
590
- <font>
591
- ${e.bold?KE`<b />`:""}
592
- ${e.italic?KE`<i />`:""}
593
- ${e.underline?KE`<u />`:""}
594
- ${e.strike?KE`<strike />`:""}
595
- ${e.size?KE`<sz val="${e.size}" />`:""}
596
- ${e.color&&e.color.rgb?KE`<color rgb="${XT(e.color.rgb)}" />`:""}
597
- ${e.name?KE`<name val="${e.name}" />`:""}
598
- </font>
599
- `}function UI(e){return e?qE([["style",e.style]]):KE``}function HI(e){return e?KE`
600
- <color ${qE([["rgb",XT(e.color.rgb)]])}/>
601
- `:KE``}function BI(e,t,r){const n=KE`
602
- <table ${qE([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["headerRowCount",e.config.numberOfHeaders],["totalsRowCount",e.config.totalRow?1:0],["xmlns",Sb],["xmlns:xr",Cb],["xmlns:xr3",Tb],["xmlns:mc",Ib]])}>
603
- ${e.config.hasFilters?function(e){const t=[["ref",e.range]];return KE`
604
- <autoFilter ${qE(t)}>
605
- ${XE(function(e){const t=[];for(const r of e.filters){const e=KE`
606
- <filterColumn ${qE([["colId",r.colId]])}>
607
- ${zI(r)}
608
- </filterColumn>
609
- `;t.push(e)}return t}(e))}
610
- </autoFilter>
611
- `}(e):""}
612
- ${function(e,t){const r=Ko(e.range),n=[];for(const o of le(0,us(r).numberOfCols)){const s=Bo(r.left+o,r.top),i=[["id",o+1],["name",t.cells[s]||`col${o}`]];if(e.config.totalRow){const e=Bo(r.left+o,r.bottom),n=t.cells[e];n?.startsWith("=")&&i.push(["totalsRowFunction","custom"])}n.push(KE`<tableColumn ${qE(i)}/>`)}return KE`
613
- <tableColumns ${qE([["count",n.length]])}>
614
- ${XE(n)}
615
- </tableColumns>
616
- `}(e,r)}
617
- ${function(e){const t=[["name",e.config.styleId],["showFirstColumn",e.config.firstColumn?1:0],["showLastColumn",e.config.lastColumn?1:0],["showRowStripes",e.config.bandedRows?1:0],["showColumnStripes",e.config.bandedColumns?1:0]];return KE`<tableStyleInfo ${qE(t)}/>`}(e)}
618
- </table>
619
- `;return ZE(n)}function zI(e){const t=e.displayedValues.map(e=>KE`<filter ${qE([["val",e]])}/>`);return KE`
620
- <filters ${qE(e.displayBlanks?[["blank",1]]:[])}>
621
- ${XE(t)}
622
- </filters>
623
- `}function $I(e){if(!Object.values(e).length)return KE``;const t=[];for(const[r,n]of Object.entries(e)){const e=[["min",parseInt(r)+1],["max",parseInt(r)+1],["width",Sy(n.size||96)],["customWidth",1],["hidden",n.isHidden?1:0]];n.outlineLevel&&e.push(["outlineLevel",n.outlineLevel]),n.collapsed&&e.push(["collapsed",1]),t.push(KE`
624
- <col ${qE(e)}/>
625
- `)}return KE`
626
- <cols>
627
- ${XE(t)}
628
- </cols>
629
- `}function GI(e,t,r){const n=[],o=new Nw(vy(r.id,r.styles)),s=new Nw(vy(r.id,r.borders)),i=new Nw(vy(r.id,r.formats));for(let a=0;a<r.rowNumber;a++){const l=[["r",a+1]],c=r.rows[a]||{};c.size&&c.size!==G&&l.push(["ht",wy(c.size)],["customHeight",1]),c.isHidden&&l.push(["hidden",1]),c.outlineLevel&&l.push(["outlineLevel",c.outlineLevel]),c.collapsed&&l.push(["collapsed",1]);const u=[];for(let n=0;n<r.colNumber;n++){const l=Bo(n,a),c=r.cells[l],h=r.cellValues[l],d={sheetId:r.id,col:n,row:a},f=o.get(d),g=i.get(d),m=s.get(d);if(c||f||g||m||void 0!==h){const o=[["r",l]],s=Ry(e,Iy(t,c,f,g,m));s&&o.push(["s",s]);let i=[],d=KE``;if(c?.startsWith("=")&&void 0!==h){const e=fI(c,h,r.formulaSpillRanges[l]??l);if(!e)continue;({attrs:i,node:d}=e)}else if(c&&ge(c)){const{label:t}=be(c);({attrs:i,node:d}=gI(t,e.sharedStrings))}else if(c&&""!==c){const o=WI(n,a,r),s=qI(n,a,r),l=!(!g||!bn(t.formats[g]));({attrs:i,node:d}=gI(c,e.sharedStrings,o||s||l))}o.push(...i),u.push(KE`<c ${qE(o)}>
630
- ${d}
631
- </c>`)}}(u.length||c.size!==G||c.isHidden||c.outlineLevel||c.collapsed)&&n.push(KE`
632
- <row ${qE(l)}>
633
- ${XE(u)}
634
- </row>
635
- `)}return KE`
636
- <sheetData>
637
- ${XE(n)}
638
- </sheetData>
639
- `}function WI(e,t,r){return r.tables.some(r=>{const n=Ko(r.range),o={...n,bottom:n.top};return ls(e,t,o)})}function qI(e,t,r){return r.tables.some(r=>{if(!r.config.totalRow)return!1;const n=Ko(r.range),o={...n,top:n.bottom};return ls(e,t,o)})}function ZI(e,t,r){const n=t.sheets[r].cells,o=[];for(const s in n){const i=n[s];if(i&&ge(i)){const{label:n,url:a}=be(i);if(ye(a)){const e=we(a),r=t.sheets.find(t=>t.id===e),i=[["display",n],["location",r?`${r.name}!A1`:E.InvalidReference],["ref",s]];o.push(KE`
640
- <hyperlink ${qE(i)}/>
641
- `)}else{const t=[["r:id",Ay(e.relsFiles,`xl/worksheets/_rels/sheet${r}.xml.rels`,{target:oE(a),type:Pb,targetMode:"External"})],["ref",s]];o.push(KE`
642
- <hyperlink ${qE(t)}/>
643
- `)}}}return o.length?KE`
644
- <hyperlinks>
645
- ${XE(o)}
646
- </hyperlinks>
647
- `:KE``}function YI(e){if(e.length){const t=e.map(e=>KE`<mergeCell ref="${e}" />`);return KE`
648
- <mergeCells count="${e.length}">
649
- ${XE(t)}
650
- </mergeCells>
651
- `}return KE``}function jI(e){const t=e.panes;let r=KE``;if(t&&(t.xSplit||t.ySplit)){const e=Bo(t.xSplit,t.ySplit),n=t.xSplit?KE`xSplit="${t.xSplit}"`:"",o=t.ySplit?KE`ySplit="${t.ySplit}"`:"",s=t.xSplit?KE`<selection pane="topRight"/>`:"",i=t.ySplit?KE`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?KE`<selection pane="bottomRight"/>`:"";r=KE`
652
- <pane
653
- ${n}
654
- ${o}
655
- topLeftCell="${e}"
656
- activePane="${t.xSplit?t.ySplit?"bottomRight":"topRight":"bottomLeft"}"
657
- state="frozen"/>
658
- ${s}
659
- ${i}
660
- ${a}
661
- `}return KE`
662
- <sheetViews>
663
- <sheetView ${qE([["showGridLines",e.areGridLinesVisible?1:0],["workbookViewId",0]])}>
664
- ${r}
665
- </sheetView>
666
- </sheetViews>
667
- `}function XI(e){return e.color?KE`
668
- <sheetPr>
669
- <tabColor ${qE([["rgb",XT(e.color)]])} />
670
- </sheetPr>
671
- `:""}function KI(e){const t=[],r=function(e){const t=[{},...Object.values(e.borders).map(e=>({left:YE(e.left),right:YE(e.right),bottom:YE(e.bottom),top:YE(e.top)}))];return{relsFiles:[],sharedStrings:[],chartIds:[],imageIds:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{}}],fonts:[{size:q,family:2,color:{rgb:"000000"},name:"Arial"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:t,numFmts:[],dxfs:[]}}(e=function(e){for(const t of e.sheets)t.tables=t.tables.filter(e=>us(Ko(e.range)).numberOfRows>1);return e}(e=function(e){const t={},r=[];for(const n of e.sheets){let e=n.name.slice(0,31);e=Xe(e,r,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),r.push(e),e!==n.name&&(t[n.name]=e,n.name=e)}if(!Object.keys(t).length)return e;const n=Object.keys(t).sort((e,t)=>t.length-e.length);let o=JSON.stringify(e);for(const e of n){const r=new RegExp(`'?${te(e)}'?!`,"g");o=o.replaceAll(r,r=>{const n=t[e];return r.replace(e,n)})}return JSON.parse(o)}(e)));return t.push(function(e,t){const r=[["xmlns",Eb],["xmlns:r",Hb]],n=[];for(const[r,o]of Object.entries(e.sheets)){const e=[["state",o.isVisible?"visible":"hidden"],["name",o.name],["sheetId",parseInt(r)+1],["r:id",`rId${parseInt(r)+1}`]];n.push(KE`
672
- <sheet ${qE(e)} />
673
- `),Ay(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:_b,target:`worksheets/sheet${r}.xml`})}return GE(ZE(KE`
674
- <workbook ${qE(r)}>
675
- <sheets>
676
- ${XE(n)}
677
- </sheets>
678
- </workbook>
679
- `),"xl/workbook.xml","workbook")}(e,r)),t.push(...function(e,t){const r=[];let n=1;for(const[o,s]of Object.entries(e.sheets)){const i=[["xmlns",yb],["xmlns:r",Hb]],a=[["defaultRowHeight",wy(G)],["defaultColWidth",Sy(96)]],l=QI(s,o,n,t,r);n+=s.tables.length;let c=KE``;const u=[];for(const n of s.charts){const s=Dy(n.id,t),i=Ay(t.relsFiles,`xl/drawings/_rels/drawing${o}.xml.rels`,{target:`../charts/chart${s}.xml`,type:Vb});u.push(i),r.push(GE(tI(n,o,e),`xl/charts/chart${s}.xml`,"chart"))}for(const e of s.images){const n=e.data.mimetype;if(void 0===n)continue;const s=ly[n];if(void 0===s)continue;const i=`image${Ny(e.id)}.${s}`,a=Ay(t.relsFiles,`xl/drawings/_rels/drawing${o}.xml.rels`,{target:`../media/${i}`,type:kb});u.push(a),r.push({path:`xl/media/${i}`,imageSrc:e.data.path})}const h=[...s.charts,...s.images];if(h.length){const e=Ay(t.relsFiles,`xl/worksheets/_rels/sheet${o}.xml.rels`,{target:`../drawings/drawing${o}.xml`,type:Mb});r.push(GE(NI(u,s,h,t),`xl/drawings/drawing${o}.xml`,"drawing")),c=KE`<drawing r:id="${e}" />`}const d=KE`
680
- <worksheet ${qE(i)}>
681
- ${XI(s)}
682
- ${jI(s)}
683
- <sheetFormatPr ${qE(a)} />
684
- ${$I(s.cols)}
685
- ${GI(t,e,s)}
686
- ${YI(s.merges)}
687
- ${XE(bI(t.dxfs,s.conditionalFormats))}
688
- ${XE(RI(s.dataValidationRules))}
689
- ${ZI(t,e,o)}
690
- ${c}
691
- ${l}
692
- </worksheet>
693
- `;r.push(GE(ZE(d),`xl/worksheets/sheet${o}.xml`,"sheet"))}const o=KE`
694
- <metadata xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:xda="http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray">
695
- <metadataTypes count="1">
696
- <metadataType name="XLDAPR" minSupportedVersion="120000" copy="1" pasteAll="1"
697
- pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1"
698
- clearComments="1" assign="1" coerce="1" cellMeta="1" />
699
- </metadataTypes>
700
- <futureMetadata name="XLDAPR" count="1">
701
- <bk>
702
- <extLst>
703
- <ext uri="{${Ub}}">
704
- <xda:dynamicArrayProperties fDynamic="1" fCollapsed="0" />
705
- </ext>
706
- </extLst>
707
- </bk>
708
- </futureMetadata>
709
- <cellMetadata count="1">
710
- <bk>
711
- <rc t="1" v="0" />
712
- </bk>
713
- </cellMetadata>
714
- </metadata>
715
- `;return r.push(GE(ZE(o),"xl/metadata.xml","metadata")),Ay(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Fb,target:"sharedStrings.xml"}),Ay(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Nb,target:"styles.xml"}),Ay(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Db,target:"metadata.xml"}),r}(e,r)),t.push(function(e){const t=KE`
716
- <styleSheet ${qE([["xmlns",mb],["xmlns:r",Hb]])}>
717
- ${function(e){const t=[];for(const[r,n]of Object.entries(e)){const e=[["numFmtId",parseInt(r)+164],["formatCode",n.format]];t.push(KE`
718
- <numFmt ${qE(e)}/>
719
- `)}return KE`
720
- <numFmts count="${e.length}">
721
- ${XE(t)}
722
- </numFmts>
723
- `}(e.numFmts)}
724
- ${r=e.fonts,KE`
725
- <fonts count="${r.length}">
726
- ${XE(Object.values(r).map(kI))}
727
- </fonts>
728
- `}
729
- ${function(e){const t=[];for(const r of Object.values(e))void 0!==r.reservedAttribute?t.push(KE`
730
- <fill>
731
- <patternFill patternType="${r.reservedAttribute}" />
732
- </fill>
733
- `):t.push(KE`
734
- <fill>
735
- <patternFill patternType="solid">
736
- <fgColor rgb="${XT(r.fgColor.rgb)}" />
737
- <bgColor indexed="64" />
738
- </patternFill>
739
- </fill>
740
- `);return KE`
741
- <fills count="${e.length}">
742
- ${XE(t)}
743
- </fills>
744
- `}(e.fills)}
745
- ${function(e){const t=[];for(const r of Object.values(e))t.push(KE`
746
- <border>
747
- <left ${UI(r.left)}>
748
- ${HI(r.left)}
749
- </left>
750
- <right ${UI(r.right)}>
751
- ${HI(r.right)}
752
- </right>
753
- <top ${UI(r.top)}>
754
- ${HI(r.top)}
755
- </top>
756
- <bottom ${UI(r.bottom)}>
757
- ${HI(r.bottom)}
758
- </bottom>
759
- <diagonal ${UI(r.diagonal)}>
760
- ${HI(r.diagonal)}
761
- </diagonal>
762
- </border>
763
- `);return KE`
764
- <borders count="${e.length}">
765
- ${XE(t)}
766
- </borders>
767
- `}(e.borders)}
768
- ${function(e){const t=[];for(const r of e){const e=[["numFmtId",r.numFmtId],["fillId",r.fillId],["fontId",r.fontId],["borderId",r.borderId]],n=[];r.alignment&&r.alignment.vertical&&n.push(["vertical",r.alignment.vertical]),r.alignment&&r.alignment.horizontal&&n.push(["horizontal",r.alignment.horizontal]),r.alignment&&r.alignment.wrapText&&n.push(["wrapText","1"]),r.alignment&&r.alignment.textRotation&&n.push(["textRotation",r.alignment.textRotation]),r.alignment&&r.alignment.shrinkToFit&&n.push(["shrinkToFit","1"]),n.length>0?(e.push(["applyAlignment","1"]),t.push(KE`<xf ${qE(e)}><alignment ${qE(n)} /></xf> `)):t.push(KE`<xf ${qE(e)} />`)}return KE`
769
- <cellXfs count="${e.length}">
770
- ${XE(t)}
771
- </cellXfs>
772
- `}(e.styles)}
773
- ${function(e){const t=[];for(const r of e){let e=KE``;r.font&&(e=kI(r.font));let n=KE``;r.fill&&(n=KE`
774
- <fill>
775
- <patternFill>
776
- <bgColor rgb="${XT(r.fill.fgColor.rgb)}" />
777
- </patternFill>
778
- </fill>
779
- `),t.push(KE`
780
- <dxf>
781
- ${e}
782
- ${n}
783
- </dxf>
784
- `)}return KE`
785
- <dxfs count="${e.length}">
786
- ${XE(t)}
787
- </dxfs>
788
- `}(e.dxfs)}
789
- </styleSheet>
790
- `;var r;return GE(ZE(t),"xl/styles.xml","styles")}(r)),t.push(function(e){const t=[["xmlns",pb],["count",e.length],["uniqueCount",e.length]],r=e.map(e=>e.trim()!==e?KE`<si><t xml:space="preserve">${e}</t></si>`:KE`<si><t>${e}</t></si>`);return GE(ZE(KE`
791
- <sst ${qE(t)}>
792
- ${XE(r)}
793
- </sst>
794
- `),"xl/sharedStrings.xml","sharedStrings")}(r.sharedStrings)),t.push(...function(e){const t=[];for(const r of e){const e=[];for(const t of r.rels){const r=[["Id",t.id],["Target",t.target],["Type",t.type]];t.targetMode&&r.push(["TargetMode",t.targetMode]),e.push(KE`
795
- <Relationship ${qE(r)} />
796
- `)}const n=KE`
797
- <Relationships xmlns="${bb}">
798
- ${XE(e)}
799
- </Relationships>
800
- `;t.push(GE(ZE(n),r.path))}return t}(r.relsFiles)),t.push(function(e){const t=[],r=Object.entries(ly).map(([e,t])=>function(e,t){return KE`
801
- <Default Extension="${e}" ContentType="${t}" />
802
- `}(t,e));for(const r of e)"contentType"in r&&r.contentType&&t.push(jE("/"+r.path,Ab[r.contentType]));const n=[["Extension","rels"],["ContentType","application/vnd.openxmlformats-package.relationships+xml"]],o=[["Extension","xml"],["ContentType","application/xml"]];return GE(ZE(KE`
803
- <Types xmlns="${vb}">
804
- ${XE(Object.values(r))}
805
- <Default ${qE(n)} />
806
- <Default ${qE(o)} />
807
- ${XE(t)}
808
- </Types>
809
- `),"[Content_Types].xml")}(t)),t.push(GE(ZE(KE`
810
- <Relationships xmlns="${bb}">
811
- <Relationship ${qE([["Id","rId1"],["Type",Ob],["Target","xl/workbook.xml"]])} />
812
- </Relationships>
813
- `),"_rels/.rels")),{name:"my_spreadsheet.xlsx",files:t}}function QI(e,t,r,n,o){let s=r;if(!e.tables.length)return new Ev("");const i=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.tables){const r=Ay(n.relsFiles,i,{target:`../tables/table${s}.xml`,type:Lb});o.push(GE(BI(t,s,e),`xl/tables/table${s}.xml`,"table")),a.push(KE`<tablePart r:id="${r}" />`),s++}return KE`
814
- <tableParts count="${e.tables.length}">
815
- ${XE(a)}
816
- </tableParts>
817
- `}var JI;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(JI||(JI={}));function ex(e,t={}){const r=re(t);return r.type=e,r}const tx={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},rx=Ue(()=>Object.keys(tx).sort((e,t)=>tx[e]-tx[t]));const nx={};e.BadExpressionError=C,e.BasePlugin=Vs,e.CellErrorType=E,e.CircularDependencyError=T,e.DEFAULT_LOCALE=xr,e.DEFAULT_LOCALES=Ir,e.DivisionByZeroError=O,e.EvaluationError=S,e.FunctionCodeBuilder=t,e.FunctionRegistry=rm,e.InvalidReferenceError=I,e.Model=class extends Vm{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},r=[],n=new _o,o=!1){const s=performance.now();console.debug("##### Model creation #####"),super(),b(),r=Ow(e,r);const i=xw(e,o);this.state=new jT,this.uuidGenerator=n,this.config=this.setupConfig(t),this.session=this.setupSession(i.revisionId),this.coreGetters={},this.range=new qT(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode},this.selection=new YT(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(const e of zT.getAll())this.setupCorePlugin(e,i);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(const e of WT.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of GT.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of $T.getAll()){const t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e["[Content_Types].xml"]&&!this.getters.isReadonly()){const e=performance.now();console.debug("Snapshot requested"),this.session.snapshot(this.exportData()),console.debug("Snapshot taken in",performance.now()-e,"ms")}console.debug("Model created in",performance.now()-s,"ms"),console.debug("######")}joinSession(){this.session.join(this.config.client)}async leaveSession(){const e=this.getters.isReadonly()?void 0:xe(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(const r of e.getters){if(!(r in t))throw new Error(`Invalid getter name: ${r} for plugin ${t.constructor}`);if(r in this.getters)throw new Error(`Getter "${r}" is already defined.`);this.getters[r]=t[r].bind(t)}for(const r of e.layers)this.renderers[r]||(this.renderers[r]=[]),this.renderers[r].push(t);return t}setupCoreViewPlugin(e){const t=new e(this.coreViewPluginConfig);for(const r of e.getters){if(!(r in t))throw new Error(`Invalid getter name: ${r} for plugin ${t.constructor}`);if(r in this.getters)throw new Error(`Getter "${r}" is already defined.`);this.getters[r]=t[r].bind(t)}return t}setupCorePlugin(e,t){const r=new e(this.corePluginConfig);for(const t of e.getters){if(!(t in r))throw new Error(`Invalid getter name: ${t} for plugin ${r.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=r[t].bind(r)}r.import(t),this.corePlugins.push(r),this.coreHandlers.push(r),this.handlers.push(r)}onRemoteRevisionReceived({commands:e}){for(const t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new lv(vv({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful?(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1):this.dispatchToHandlers(this.coreHandlers,{type:"UNDO",commands:[e]})}}),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-undone",this,({commands:e})=>{this.dispatchFromCorePlugin("UNDO",{commands:e}),this.finalize()}),this.session.on("revision-redone",this,({commands:e})=>{this.dispatchFromCorePlugin("REDO",{commands:e}),this.finalize()}),this.session.on("unexpected-revision-id",this,()=>this.trigger("unexpected-revision-id")),this.session.on("collaborative-event-received",this,()=>{this.trigger("update")})}setupConfig(e){const t=e.client||{id:this.uuidGenerator.smallUuid(),name:v("Anonymous").toString()},r=e.transportService||new Nm,n="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:n?new Mm(r):r,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),raiseBlockingErrorUI:e=>this.trigger("raise-error-ui",{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){const t=e.loadLocales||(()=>Promise.resolve(Ir));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){const t=Ds(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>"Success"!==e)?new Fs(t.flat()):Fs.Success}checkDispatchAllowedCoreCommand(e){const t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0,this.trigger("command-finalized")}canDispatch=(e,t)=>this.checkDispatchAllowed(ex(e,t));dispatch=(e,t)=>{const r=ex(e,t),n=this.status;if(this.getters.isReadonly()&&(o=r,!Os.has(o.type)))return new Fs("Readonly");var o;if(!this.session.canApplyOptimisticUpdate())return new Fs("WaitingSessionConfirmation");switch(n){case 0:const t=this.checkDispatchAllowed(r);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:n,commands:o}=this.state.recordChanges(()=>{const t=performance.now();Ds(r)&&this.state.addCommand(r),this.dispatchToHandlers(this.handlers,r),this.finalize();const n=performance.now()-t;n>5&&console.debug(e,n,"ms")});this.session.save(r,o,n),this.status=0,this.trigger("update");break;case 1:if(Ds(r)){const e=this.checkDispatchAllowed(r);if(!e.isSuccessful)return e;this.state.addCommand(r)}this.dispatchToHandlers(this.handlers,r);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(Ds(r))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,r)}return Fs.Success};dispatchFromCorePlugin=(e,t)=>{const r=ex(e,t),n=this.status;this.status=2;const o=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(o,r),this.status=n,Fs.Success};dispatchToHandlers(e,t){const r=Ds(t);for(const n of e)!r&&n instanceof Mw||n.beforeHandle(t);for(const n of e)!r&&n instanceof Mw||n.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const r=this.renderers[t];if(r)for(const n of r)e.ctx.save(),n.drawLayer(e,t),e.ctx.restore()}exportData(){let e=Fw();for(const t of this.handlers)t instanceof Mw&&t.export(e);return e.revisionId=this.session.getRevisionId()||Y,e=re(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}async exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...Fw(),sheets:[(t=Iw,r="Sheet1",{...Dw(t,r),charts:[],images:[],cellValues:{}})]};var t,r;for(const t of this.handlers)t instanceof Vs&&await t.exportForExcel(e);return e=re(e),KI(e)}},e.NotAvailableError=x,e.NumberTooLargeError=_,e.OPERATOR_MAP=Rm,e.OP_PRIORITY=mm,e.OrderedLayers=rx,e.POSTFIX_UNARY_OPERATORS=Bl,e.Registry=h,e.Scope=n,e.SplillBlockedError=A,e.StateObserver=jT,e.TokenizingChars=Ze,e.UNARY_OPERATOR_MAP=Am,e.UnknownFunctionError=R,e.UuidGenerator=_o,e.__info__=nx,e._t=v,e.addRenderingLayer=function(e,t){if(tx[e])throw new Error(`Layer ${e} already exists`);tx[e]=t},e.batched=function(e){let t=!1;return async(...r)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...r))}},e.borderStyles=["thin","medium","thick","dashed","dotted"],e.buildSheetLink=Ee,e.categories=om,e.cellReference=ho,e.chartStyleToCellStyle=function(e){return{bold:e.bold,italic:e.italic,fontSize:e.fontSize,textColor:e.color,align:e.align}},e.clip=ae,e.compile=_m,e.compileTokens=Dm,e.concat=Ie,e.convertAstNodes=Sm,e.createEmptyStructure=Oo,e.debounce=Te,e.deepCopy=re,e.deepEquals=Ae,e.deepEqualsArray=_e,e.errorTypes=w,e.escapeRegExp=te,e.findNextDefinedValue=function(e,t){let r=e.slice(t).find(e=>e);return r||(r=e.slice(0,t).reverse().find(e=>e)),r||""},e.functionCache=Om,e.getAddHeaderStartIndex=Re,e.getCanonicalSymbolName=se,e.getFormulaNumberRegex=Rt,e.getFullReference=Io,e.getSearchRegex=function(e,t){let r=te(e);const n=t.matchCase?"":"i";return t.exactMatch&&(r=`^${r}$`),RegExp(r,n)},e.getUniqueText=Xe,e.getUnquotedSheetName=ne,e.groupConsecutive=ce,e.includesAll=De,e.insertItemsAtIndex=Be,e.isBoolean=he,e.isColHeader=wo,e.isColReference=yo,e.isConsecutive=ke,e.isDefined=Se,e.isFormula=Ke,e.isMarkdownLink=ge,e.isMatrix=D,e.isNotNull=function(e){return null!==e},e.isNumber=Ot,e.isNumberBetween=Ge,e.isObjectEmptyRecursive=Ce,e.isRowHeader=So,e.isRowReference=Eo,e.isSheetUrl=ye,e.isSingleCellReference=Co,e.isWebLink=me,e.iterateAstNodes=Cm,e.largeMax=We,e.largeMin=qe,e.lazy=xe,e.linkNext=ue,e.loopThroughReferenceType=function(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:r}=To(e.value),[n,o]=t.split(":"),s=xo(n),i=o?`:${xo(o)}`:"";return{...e,value:Io(r,s+i)}},e.mapAst=Im,e.markdownLink=pe,e.memoize=Ue,e.parse=Em,e.parseMarkdownLink=be,e.parseNumber=Dt,e.parseSheetUrl=we,e.parseTokens=wm,e.percentile=Ft,e.range=le,e.rangeReference=vo,e.rangeTokenize=um,e.removeDuplicates=Ye,e.removeFalsyAttributes=Fe,e.removeIndexesFromArray=He,e.replaceItemAtIndex=ze,e.replaceNewLines=Pe,e.sanitizeSheetName=ie,e.setDefaultTranslationMethod=b,e.setTranslationMethod=function(e,t=()=>!0){g=e,m=t},e.setXcToFixedReferenceType=Ro,e.specialWhiteSpaceRegexp=Me,e.splitReference=To,e.tokenize=$l,e.transpose2dPOJO=je,e.trimContent=$e,e.unquote=oe,e.whiteSpaceCharacters=Le,nx.version="19.1.0-alpha.3",nx.date="2026-01-21T11:06:38.842Z",nx.hash="ceae12a"}(this.o_spreadsheet_engine=this.o_spreadsheet_engine||{});