@odoo/o-spreadsheet 19.2.0-alpha.3 → 19.2.11

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 o){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 n(this.code)}}class r{scope;returnExpression;code;constructor(e,t,r){this.scope=e,this.returnExpression=r,this.code=n(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 o{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function n(e){let t="",r=0;const o=e.split("\n").map(e=>e.trim()).filter(e=>""!==e);for(const e of o)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 o=e.match(s),n=o[1].trim();if(!n)throw new Error(`Function argument definition is missing a name: '${e}'.`);const a=[];let l,c=!1,u=!1;for(const e of o[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:n,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,o=l[r]?.[t];return o||(l[r]||(l[r]={}),l[r][t]||(l[r][t]=function(e,t){const r={},o=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,n=e.nbrArgRepeating*o,s=t-e.minArgRequired-n;let i=0,a=0;for(let t=0;t<e.args.length;t++){const n=e.args[t];if(!n.optional&&!n.default||n.repeating){if(n.repeating){const s=n.optional?0:1;for(let n=0;n<o+s;n++)for(let o=0;o<e.nbrArgRepeating;o++)r[i]={index:t+o,repeatingGroupIndex:n},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 w={NotAvailable:"#N/A",InvalidReference:"#REF",BadExpression:"#BAD_EXPR",CircularDependency:"#CYCLE",UnknownFunction:"#NAME?",DivisionByZero:"#DIV/0!",InvalidNumber:"#NUM!",SpilledBlocked:"#SPILL!",GenericError:"#ERROR",NullError:"#NULL!"},E=new Set(Object.values(w));class S{message;value;constructor(e=v("Error"),t=w.GenericError){this.message=e,this.value=t,this.message=e.toString()}}class C extends S{constructor(e=v("Invalid expression")){super(e,w.BadExpression)}}class T extends S{constructor(e=v("Circular reference")){super(e,w.CircularDependency)}}class I extends S{constructor(e=v("Invalid reference")){super(e,w.InvalidReference)}}class x extends S{constructor(e=v("Data not available")){super(e,w.NotAvailable)}}class R extends S{constructor(e=v("Unknown function")){super(e,w.UnknownFunction)}}class A extends S{constructor(e=v("Spill range is not empty")){super(e,w.SpilledBlocked)}}class O extends S{constructor(e=v("Division by zero")){super(e,w.DivisionByZero)}}class _ extends S{constructor(e=v("Number too large")){super(e,w.InvalidNumber)}}function F(e){return Array.isArray(e)&&Array.isArray(e[0])}var D;e.DIRECTION=void 0,(D=e.DIRECTION||(e.DIRECTION={})).UP="up",D.DOWN="down",D.LEFT="left",D.RIGHT="right";const N="#017E84",M="#3266ca",V="#FFFFFF",P=N,L="#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,o=e.length;r<o;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 oe(e){return ne(e,"'")}function ne(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 o=Math.ceil(Math.abs((t-e)/r)),n=Array(o);for(let t=0;t<o;t++)n[t]=e+t*r;return n}function ce(e){return e.reduce((e,t,r,o)=>{if(1===Math.abs(t-o[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],o=t[2];if(!r||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:r,url:o}}const ve="o-spreadsheet://";function ye(e){return e.startsWith(ve)}function we(e){return`${ve}${e}`}function Ee(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 o,n=!1;const s=function(){const s=this,i=Array.from(arguments);if(!n&&r)return n=!0,e.apply(s,i);clearTimeout(o),o=setTimeout(function(){o=void 0,n=!1,e.apply(s,i)},t)};return s.isDebouncePending=()=>void 0!==o,s.stopDebounce=()=>{clearTimeout(o)},s}function Ie(e){let t="";for(let r=0,o=e.length;r<o;r++)t+=e[r];return t}function xe(e){let t,r=!1;const o=()=>(r||(t=e instanceof Function?e():e,r=!0),t);return o.map=e=>xe(()=>e(o())),o}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 Fe(e,t){if(e.length<t.length)return!1;const r=new Set(e);return t.every(e=>r.has(e))}function De(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,Pe=Ne.concat([" "]);function Le(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),o=[];for(let t=0;t<e.length;t++)r.has(t)||o.push(e[t]);return o}function Be(e,t,r){return e.slice(0,r).concat(t).concat(e.slice(r))}function ze(e,t,r){const o=[...e];return o[r]=t,o}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 o=t(e);return!r.has(o)&&(r.add(o),!0)})}function je(e){const t={};for(const r in e)for(const o in e[r])t[o]||(t[o]={}),t[o][r]=e[r][o];return t}function Xe(e,t,r={}){const o=r.compute??((e,t)=>`${e} (${t})`),n=r.computeFirstOne??!1;let s=r.start??1,i=n?o(e,s):e;for(;t.includes(i);)i=o(e,s++);return i}function Ke(e){return e.startsWith("=")||e.startsWith("+")}function Qe(e,t){return e.isFormula&&e.compiledFormula.tokens.some(e=>"SYMBOL"===e.type&&e.value.toUpperCase()===t)}class Je{jsDate;constructor(e,t,r,o=0,n=0,s=0){this.jsDate=new Date(Date.UTC(e,t,r,o,n,s,0))}static fromTimestamp(e){const t=new Date(e);return new Je(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new Je(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 et=new Je(1899,11,30),tt=864e5,rt=2e3,ot=Je.now().getFullYear(),nt=Je.now().getMonth(),st=Je.fromTimestamp(0).getTime()-et.getTime(),it=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,at=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,lt=Pe.join(""),ct=new RegExp(`/|-|${Pe.join("|")}`),ut=new RegExp(`^(\\d{1,4})[/${lt}-](\\d{1,4})([/${lt}-](\\d{1,4}))?$`),ht=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function dt(e,t){switch(typeof e){case"number":return e;case"string":return ft(e,t)?mt(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function ft(e,t){return null!==mt(e,t)}const gt=new Map;function mt(e,t){return gt.has(t)||gt.set(t,new Map),gt.get(t).has(e)||gt.get(t).set(e,function(e,t){e=e.trim();let r=null;const o=e.match(ht);if(o){if(r=function(e){if(e=e.trim(),ht.test(e)){const t=/AM/i.test(e),r=/PM/i.test(e),o=(t||r?e.substring(0,e.length-2).trim():e).split(/:/),n=o.length>=2,s=3===o.length;let i=Number(o[0]),a=n?Number(o[1]):0,l=s?Number(o[2]):0,c=s?"hh:mm:ss":"hh:mm";if(t||r)c+=" a";else if(!n)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 Je(1899,11,30,i,a,l)}}return null}(o[0]),null===r)return null;e=e.replace(o[0],"").trim()}let n=null;const s=function(e,t){const r=e.match(ut);if(!r)return null;const[,o,n,,s]=r;if(o.length>2&&s&&s.length>2)return null;if(o.length>2)return{year:o,month:n,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 n.length>2?{month:o,year:n,day:void 0,dateString:e,type:i}:"dmy"===i?{day:o,month:n,year:s,dateString:e,type:"dmy"}:{month:o,day:n,year:s,dateString:e,type:"mdy"};if(s.length>2)return"mdy"===i?{month:o,day:n,year:s,dateString:e,type:"mdy"}:{day:o,month:n,year:s,dateString:e,type:"dmy"};if("mdy"===i)return{month:o,day:n,year:s,dateString:e,type:"mdy"};if("ymd"===i)return{year:o,month:n,day:s,dateString:e,type:"ymd"};if("dmy"===i)return{day:o,month:n,year:s,dateString:e,type:"dmy"};return null}(e,t);if(s){const t=s.dateString.match(ct)[0];if(n=function(e,t){const{year:r,month:o,day:n}=e,s=function(e){if(!e)return nt;const t=Number(e);if(t>=1&&t<=12)return t-1;return null}(o),i=function(e){if(!e)return 1;const t=Number(e);if(t>=0&&t<=31)return t;return null}(n),a=function(e){if(!e)return ot;const t=Number(e);switch(e.length){case 1:return rt+t;case 2:return rt+(rt+t>ot+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===o?.length&&s+1<10||2===n?.length&&i<10,c=2!==r?.length,u=new Je(a,s,i);if(u.getMonth()!==s||u.getDate()!==i)return null;const h=u.getTime()-et.getTime(),d=function(e,t,r,o){const n=e.year?o?"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,n].filter(Se).join(t);case"ymd":return[n,s,i].filter(Se).join(t);case"dmy":return[i,s,n].filter(Se).join(t)}}(e,t,l,c);return{value:Math.round(h/tt),format:d,jsDate:u}}(s,t),null===n)return null;e=e.replace(s.dateString,"").trim()}if(""!==e||!n&&!r)return null;if(n&&n.jsDate&&r&&r.jsDate)return{value:n.value+r.value,format:n.format+" "+("hhhh:mm:ss"===r.format?"hh:mm:ss":r.format),jsDate:new Je(n.jsDate.getFullYear()+r.jsDate.getFullYear()-1899,n.jsDate.getMonth()+r.jsDate.getMonth()-11,n.jsDate.getDate()+r.jsDate.getDate()-30,n.jsDate.getHours()+r.jsDate.getHours(),n.jsDate.getMinutes()+r.jsDate.getMinutes(),n.jsDate.getSeconds()+r.jsDate.getSeconds())};return n||r}(e,t)),gt.get(t).get(e)}function pt(e){const t=Math.trunc(e),r=Je.fromTimestamp(t*tt-st);let o=e-t;o=o<0?1+o:o;const n=Math.round(24*o),s=Math.round(24*(o-n/24)*60),i=Math.round(24*(o-n/24-s/24/60)*60*60);return r.setHours(n),r.setMinutes(s),r.setSeconds(i),r}function bt(e){return Math.round(vt(e))}function vt(e){return(e.getTime()-et.getTime())/tt}function yt(e){return new Je(e.getFullYear(),e.getMonth()+1,0).getDate()}function wt(e){return yt(e)===e.getDate()}function Et(e,t,r){const o=e.getFullYear(),n=e.getMonth(),s=e.getDate(),i=new Je(o,n+t,1);return r&&s===yt(e)||s>yt(i)?i.setDate(yt(i)):i.setDate(s),i}function St(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Ct(e,t,r){if(e===t)return 0;if(e>t){const r=t;t=e,e=r}const o=pt(e),n=pt(t);let s=o.getDate(),i=n.getDate();const a=o.getMonth(),l=n.getMonth(),c=o.getFullYear(),u=n.getFullYear();let h=0,d=0;switch(r){case 0:31===s&&(s=30),30===s&&31===i&&(i=30),1===a&&s===(St(c)?29:28)&&(s=30,1===l&&i===(St(u)?29:28)&&(i=30)),h=c+(30*a+s)/360,d=u+(30*l+i)/360;break;case 1:let r=365;const o=c===u;if(!o&&!(c+1===u)||!o&&a<l||!o&&a===l&&s<i){let e=0,t=0;for(let r=c;r<=u;r++)e++,t+=St(r)?366:365;r=t/e}else o?St(c)&&(r=366):(St(c)&&a<2&&(r=366),St(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 Tt(e,t){const r=12*(t.getFullYear()-e.getFullYear())+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?r-1:r}function It(e,t){const r=e.getTime(),o=t.getTime();return Math.floor((o-r)/tt)}function xt(e,t){const r=t.getFullYear()-e.getFullYear(),o=e.getMonth(),n=t.getMonth(),s=e.getDate(),i=t.getDate();return n>o||n===o&&i>=s?r:r-1}function Rt(e,t,r){return t>r?Rt(e,r,t):(e=Math.trunc(e),t=Math.trunc(t),r=Math.trunc(r),e>=t&&e<=r)}const At=Ue(function(e){return e=te(e),new RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:(E|e)(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),Ot=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*%)?",o="(?:\\s*-)?",n="(?:\\s*[\\$€])?",s="^(?:(?:"+[o+n+r,o+r+n,n+o+r].join(")|(?:")+"))$";return new RegExp(s,"i")});function _t(e,t){return!!e&&Ot(t).test(e.trim())}const Ft=Ue(function(e){return new RegExp(`[$€${te(e.thousandsSeparator||"")}]`,"g")});function Dt(e,t){e=e.replace(Ft(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 Nt(e,t,r){const o=[...e].sort((e,t)=>e-t);let n=(o.length+(r?-1:1))*t;if(r||n--,Number.isInteger(n))return o[n];const s=Math.ceil(n),i=Math.floor(n);return o[s]*(n-i)+o[i]*(s-n)}const Mt=["number","string","boolean","undefined"];function Vt(e){if(void 0!==e)return F(e)?e[0][0]?.format:e.format}function Pt(e){return"string"==typeof e&&E.has(e)}function Lt(e){return{value:w.NotAvailable,message:v("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Wt(e))}}const kt=e=>v("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Ut(e,t){const r=Xt(e);switch(typeof r){case"number":return r;case"boolean":return r?1:0;case"string":if(_t(r,t)||""===r)return Dt(r,t);const e=mt(r,t);if(e)return e.value;throw new S(kt(r));default:return 0}}function Ht(e,t){try{return Ut(e,t)}catch(e){return}}function Bt(e,t){return br(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 zt(e,t){const r=Xt(e);if(""===r)throw new S(kt(r));return Ut(r,t)}function $t(e,t){return Math.trunc(Ut(e,t))}function Gt(e,t){return Math.trunc(zt(e,t))}function Wt(e){const t=Xt(e);switch(typeof t){case"string":return t;case"number":return t.toString();case"boolean":return t?"TRUE":"FALSE";default:return""}}const qt=Ue(function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}),Zt=e=>v("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.",e);function Yt(e){const t=Xt(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(Zt(t))}return!1;case"number":return!!t;default:return!1}}function jt(e,t){return pt(Ut(Xt(e),t))}function Xt(e){if("object"==typeof e&&null!==e&&"value"in e){if(Pt(e.value))throw e;return e.value}if(Pt(e))throw new S("",e);return e}function Kt(e,t,r){for(const o of e)if(F(o)){const e=o.length,r=o[0].length;for(let n=0;n<r;n++)for(let r=0;r<e;r++)t(o[r][n])}else r(o)}function Qt(e,t){Kt(e,e=>{if(Pt(e.value))throw e;t(e)},e=>{if(Pt(e?.value))throw e;t(e)})}function Jt(e,t,r){Kt(e,e=>{if("number"==typeof e?.value&&t(e),Pt(e?.value))throw e},e=>{t({value:zt(e,r),format:e?.format})})}function er(e,t,r,o,n="rowFirst"){let s=o;for(const o of e)if(F(o)){const e=o.length,r=o[0].length;if("rowFirst"===n)for(let n=0;n<r;n++)for(let r=0;r<e;r++)s=t(s,o[r][n]);else for(let n=0;n<e;n++)for(let e=0;e<r;e++)s=t(s,o[n][e])}else s=r(s,o);return s}function tr(e,t,r,o="rowFirst"){return er(e,t,t,r,o)}function rr(e,t,r,o){return er(e,(e,r)=>{const o=r?.value;if("number"==typeof o)return t(e,o);if(Pt(o))throw r;return e},(e,r)=>t(e,zt(r,o)),r)}function or(e,t,r,o){return er(e,(e,r)=>{const n=r?.value;if(null!=n){if("number"==typeof n)return t(e,n);if("boolean"==typeof n)return t(e,Ut(n,o));if(Pt(n))throw r;return t(e,0)}return e},(e,r)=>t(e,Ut(r,o)),r)}function nr(e,t,r){const o=Array(e);for(let n=0;n<e;n++){o[n]=Array(t);for(let e=0;e<t;e++)o[n][e]=r(n,e)}return o}function sr(e,t){return 0===e.length?[]:nr(e.length,e[0].length,(r,o)=>t(e[r][o]))}function ir(e){return e.length?nr(e[0].length,e.length,(t,r)=>e[r][t]):[]}function ar(e,t,r=void 0){let o,n=1,s=1,i=1/0,a=1/0;for(let e=0;e<t.length;e++){const l=t[e];if(F(l)&&(void 0===r||r[e])){const r=l.length,c=l[0].length;1!==r||1!==c?(o??=new Array(t.length),1!==r&&1!==c?(o[e]="matrix",n=Math.max(n,r),s=Math.max(s,c),i=Math.min(i,r),a=Math.min(a,c)):1!==r?(o[e]="horizontal",n=Math.max(n,r),i=Math.min(i,r)):1!==c&&(o[e]="vertical",s=Math.max(s,c),a=Math.min(a,c))):t[e]=l[0][0]}}if(1===n&&1===s)return e(...t);return nr(n,s,(r,n)=>{if(r>i-1||n>a-1)return new x(v("Array arguments to [[FUNCTION_NAME]] are of different size."));const s=e(...(l=r,c=n,t.map((e,t)=>{switch(o?.[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 F(s)?s[0][0]:s})}function lr(e,t){return function(e,t,r){for(const o of e)if(F(o)){const e=o.length,r=o[0].length;for(let n=0;n<r;n++)for(let r=0;r<e;r++)if(!t(o[r][n]??void 0))return}else if(!r(o))return}(e,e=>{const r=e?.value;if("boolean"==typeof r)return t(r);if("number"==typeof r)return t(!!r);if(Pt(r))throw e;return!0},e=>void 0===e||null===e.value||t(function(e){const t=Xt(e);if(""===t)throw new S(Zt(t));return Yt(t)}(e)))}function cr(e,t){let r,o,n=e.substring(0,2);return"<="===n||">="===n||"<>"===n?(r=n,o=e.substring(2)):(n=e.substring(0,1),"<"===n||">"===n||"="===n?(r=n,o=e.substring(1)):(r="=",o=e)),_t(o,t)||ft(o,t)?o=Ut(o,t):"TRUE"!==o&&"FALSE"!==o||(o=Yt(o)),{operator:r,operand:o}}const ur=Ue(function(e){if("*"===e)return/.+/;let t="",r="";for(const o of e)"?"===o&&"~"!==r?t+=".":"*"===o&&"~"!==r?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),r=o;return new RegExp("^"+t+"$","i")});function hr(e="",t,r){const{operator:o,operand:n}=t;if(void 0===n||null===e||null===n)return!1;if("number"==typeof n&&"="===o)return"string"==typeof e&&(_t(e,r)||ft(e,r))?Ut(e,r)===n:e===n;if("<>"===o||"="===o){let t;return t=typeof e==typeof n&&("string"==typeof e&&"string"==typeof n?ur(n).test(e):e===n),"="===o?t:!t}if(typeof e==typeof n)switch(o){case"<":return e<n;case">":return e>n;case"<=":return e<=n;case">=":return e>=n}return!1}function dr(e,t,r,o=!1){const n=e.length;if(n%2==1)throw new S(v("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const s=br(e[0]),i=s.length,a=s[0].length,l=[];for(let t=0;t<n-1;t+=2){const n=br(e[t]);if(n.length!==i||n[0].length!==a)throw new S(v("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const s=cr(Wt(e[t+1]),r);o&&"string"==typeof s.operand&&(s.operand+="*"),l.push(s)}for(let o=0;o<i;o++)for(let s=0;s<a;s++){let i=!0;for(let t=0;t<n-1;t+=2){if(i=hr(br(e[t])[o][s].value??void 0,l[t/2],r),!i)break}i&&t(o,s)}}function fr(e,t,r,o,n,s){if(void 0===t||null===t.value)return-1;if(Pt(t.value))throw t;const i=mr(t.value),a=typeof i;let l,c,u,h,d,f,g=0,m=n-1;const p="desc"===o?t=>mr(s(e,n-t-1)):t=>mr(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"===o?n-c-1:c}function gr(e,t,r,o,n,s,i=!1){if(void 0===t||null===t.value)return-1;if(Pt(t.value))throw t;const a=mr(t.value),l=i?(e,t)=>mr(n(e,o-t-1)):(e,t)=>mr(n(e,t)),c="wildcard"!==r||"string"!=typeof a||!(a.includes("*")||a.includes("?"));if(s&&c){const t=i?"reverseSearch":"forwardSearch";let n=s[t].get(e);if(void 0===n){n=new Map;for(let t=0;t<o;t++){const r=l(e,t)??null;n.has(r)||n.set(r,t)}s[t].set(e,n)}if(n.has(a)){const e=n.get(a);return i?o-e-1:e}if("strict"===r)return-1}const u=function(e,t,r,o,n){let s=r=>n(e,r)===t;if("wildcard"===r&&"string"==typeof t&&(t.includes("*")||t.includes("?"))){const r=ur(t);s=t=>{const o=n(e,t);return"string"==typeof o&&r.test(o)}}let i,a=-1;"nextSmaller"===r&&(s=r=>{const o=n(e,r);return(!i&&pr(t,o)>=0||pr(t,o)>=0&&pr(o,i)>0)&&(i=o,a=r),o===t});"nextGreater"===r&&(s=r=>{const o=n(e,r);return(!i&&pr(t,o)<=0||pr(t,o)<=0&&pr(o,i)<0)&&(i=o,a=r),o===t});for(let e=0;e<o;e++)if(s(e))return e;return a}(e,a,r,o,l);return i&&-1!==u?o-u-1:u}function mr(e){return"string"==typeof e?qt(e):e}function pr(e,t){let r=Mt.indexOf(typeof e)-Mt.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 br(e){return void 0===e?[[]]:F(e)?e:[[e]]}function vr(e,t){return tr(e,(e,r)=>(e.push(t(r)),e),[],"rowFirst")}function yr(e){if(void 0===e)return!1;const{value:t}=e;return null!==t&&""!==t}const wr=v("[[FUNCTION_NAME]] has no valid input data.");function Er(e){return v("[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.",{argName:e})}function Sr(e){function t(...t){for(let r=0;r<t.length;r++){const o=t[r],n=c(e,t.length);if(!e.args[n(r).index??r].acceptErrors&&!F(o)&&Pt(o?.value))return o}try{return r.apply(this,t)}catch(t){return Cr(t,e.name)}}function r(...t){this.debug;const r=e.compute.apply(this,t);return F(r)?"object"==typeof r[0][0]&&null!==r[0][0]&&"value"in r[0][0]?(function(e,t){const r=e.length,o=e[0]?.length??0;for(let n=0;n<r;n++)for(let r=0;r<o;r++)t(e[n][r])}(r,t=>Tr(t,e.name)),r):sr(r,e=>({value:e})):"object"==typeof r&&null!==r&&"value"in r?(Tr(r,e.name),r):{value:r}}return function(...r){const o=[],n=c(e,r.length);for(let t=0;t<r.length;t++){const s=n(t).index??-1,i=e.args[s];if(!F(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()));o.push(!i.acceptMatrix)}return ar(t.bind(this),r,o)}}function Cr(e,t){return r=e,void 0!==r?.value&&"string"==typeof r.value&&Pt(e.value)?(xr(e)&&Tr(e,t),e):(console.error(e),new S(Ir+(xr(e)?" "+e.message:"")));var r}function Tr(e,t){e.message?.includes("[[FUNCTION_NAME]]")&&(e.message=e.message.replace("[[FUNCTION_NAME]]",t))}const Ir=v("An unexpected error occurred. Submit a support ticket at odoo.com/help.");function xr(e){return void 0!==e?.message&&"string"==typeof e.message}const Rr=[{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:";"}],Ar=Rr[0];function Or(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 _r=new Set("$+-/():!^&~{}<>= ");function Fr(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 _r.has(e.current)?{type:"CHAR",value:e.shift()}:null}function Dr(e){return","===e.current?(e.shift(),{type:"THOUSANDS_SEPARATOR",value:","}):null}function Nr(e){return"@"===e.current?(e.shift(),{type:"TEXT_PLACEHOLDER",value:"@"}):null}function Mr(e){return"."===e.current?(e.shift(),{type:"DECIMAL_POINT",value:"."}):null}function Vr(e){return"%"===e.current?(e.shift(),{type:"PERCENT",value:"%"}):null}function Pr(e){return"e"===e.current?(e.shift(),{type:"SCIENTIFIC",value:"e"}):null}function Lr(e){if("0"===e.current||"#"===e.current){const t=e.current;return e.shift(),{type:"DIGIT",value:t}}return null}const kr=new Set("dmqyhsa");function Ur(e){if(!kr.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 Hr(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 Br={};function zr(e){let t=Br[e];return void 0===t&&(t=function(e){const t=function(e){const t=new Ze(e),r=[];let o=[];for(r.push(o);!t.isOver();){if(";"===t.current){o=[],r.push(o),t.shift();continue}const e=Lr(t)||Or(t)||Fr(t)||Dr(t)||Mr(t)||Vr(t)||Pr(t)||Ur(t)||Nr(t)||Hr(t);if(!e)throw new Error("Unknown token at "+t.remaining());o.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=Gr(t[0])||$r(t[0])||Wr(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 o=Gr(t[1])||$r(t[1]);if(t[1]?.length&&!o)throw new Error("Invalid second format part of: "+e);const n=Gr(t[2])||$r(t[2]);if(t[2]?.length&&!n)throw new Error("Invalid third format part of: "+e);const s=Wr(t[3]);if(t[3]?.length&&!s)throw new Error("Invalid fourth format part of: "+e);return{positive:r,negative:o,zero:n,text:s}}(e),Br[e]=t),t}function $r(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,o=t,n=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":o===t?o.push(h):c<20&&(o.push(h),c++);break;case"DECIMAL_POINT":if(o!==t)throw new Error("Multiple decimal points in a number format");r=[],o=r;break;case"SCIENTIFIC":s=!0;break;case"REPEATED_CHAR":case"CHAR":case"STRING":o.push(h);break;case"PERCENT":n++,o.push(h);break;case"THOUSANDS_SEPARATOR":u-1===a?(i+=1,a++,o.push(h)):"DIGIT"===e[u+1]?.type&&"DIGIT"===e[u-1]?.type?(o===t&&(l=!0),o.push(h)):o.push({type:"CHAR",value:","})}}return{type:"number",integerPart:t,decimalPart:r,percentSymbols:n,scientific:s,thousandsSeparator:l,magnitude:i}}function Gr(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 Wr(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 qr(e){return[Zr(e.positive),Zr(e.negative),Zr(e.zero),Zr(e.text)].filter(Se).join(";")}function Zr(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+=Yr(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 Yr(e){return!_r.has(e)}const jr="REPEATED_CHAR_PLACEHOLDER_",Xr={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")},Kr={0:v("Sunday"),1:v("Monday"),2:v("Tuesday"),3:v("Wednesday"),4:v("Thursday"),5:v("Friday"),6:v("Saturday")};function Qr(e,{format:t,locale:r,formatWidth:o}){switch("boolean"==typeof e&&(e=e?"TRUE":"FALSE"),typeof e){case"string":{if(e.includes('\\"')&&(e=e.replaceAll(/\\"/g,'"')),!t)return e;const r=Jr(e,zr(t)).format;return r&&"text"===r.type?eo(e,r,o):e}case"number":t||(t=co(e));const n=zr(t),{format:s,isNegativeFormat:i}=Jr(e,n);if(!s)return e.toString();if("text"===s.type)return eo(e.toString(),s,o);if(i&&(e=Math.abs(e)),"date"===s.type)return to(function(e,t){const r=pt(e),o=t.tokens.some(e=>"DATE_PART"===e.type&&"a"===e.value);let n="";for(const e of t.tokens)switch(e.type){case"DATE_PART":n+=ao(r,e.value,o);break;case"REPEATED_CHAR":n+=jr+e.value;break;default:n+=e.value}return n}(e,s),o);const a=e<0,l=to(function(e,t,r){if(!t.integerPart.length&&!t.decimalPart?.length)return"";if(e===1/0)return"∞"+(t.percentSymbols?"%":"");let o=Math.floor(Math.log10(Math.abs(e)));o===-1/0&&(o=0);t.scientific&&(e/=10**o);const n=2*t.percentSymbols-3*t.magnitude;e*=10**n;let s=0;void 0!==t.decimalPart&&(s=t.decimalPart.filter(e=>"DIGIT"===e.type).length);const{integerDigits:i,decimalDigits:a}=oo(Math.abs(e),s);let l=function(e,t,r){let o=t.integerPart;o.some(e=>"DIGIT"===e.type)||(o=[...o,{type:"DIGIT",value:"#"}]);"0"===e&&(e="");let n="";const s=o.findIndex(e=>"DIGIT"===e.type);let i=e.length-1;function a(t,o){if("0"===o&&(t=t||"0"),!t)return;const s=e.length-1-i;n=r&&s>0&&s%3==0?t+r+n:t+n}for(let t=o.length-1;t>=0;t--){const r=o[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":n=jr+r.value+n;break;default:n=r.value+n}}return n}(i,t,t.thousandsSeparator?r.thousandsSeparator:void 0);void 0!==t.decimalPart&&(l+=r.decimalSeparator+function(e,t){if(!t.decimalPart)return"";let r="",o=0;for(const n of t.decimalPart)switch(n.type){case"DIGIT":r+="#"===n.value?e[o]||"":e[o]||"0",o++;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":r+=jr+n.value;break;default:r+=n.value}return r}(a||"",t));if(t.scientific){l+="e"+(o>=0?"+":"-")+Math.abs(o).toString().padStart(2,"0")}return l}(Math.abs(e),s,r),o);return a?"-"+l:l;case"object":return""}}function Jr(e,t){let r,o=!1;switch(typeof e){case"number":e<0&&t.negative?(r=t.negative,o=!0):r=0===e&&t.zero?t.zero:t.positive;break;case"string":const n=t.text||t.positive;"text"===n.type&&(r=n)}return{format:r,isNegativeFormat:o}}function eo(e,t,r){let o="";for(const r of t.tokens)switch(r.type){case"TEXT_PLACEHOLDER":o+=e;break;case"CHAR":case"STRING":o+=r.value;break;case"REPEATED_CHAR":o+=jr+r.value}return to(o,r)}function to(e,t){const r=e.indexOf(jr);if(-1===r)return e;const o=e.slice(0,r),n=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(o+n),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 o+s.repeat(i)+a+n}const ro=[];function oo(e,t=20){const r=e.toString();if(r.includes("e"))return function(e,t=20){let r=ro[t];r||(r=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),ro[t]=r);const[o,n]=r.format(e).split(".");return{integerDigits:o,decimalDigits:n}}(e,t);if(Number.isInteger(e))return{integerDigits:r,decimalDigits:void 0};const o=r.indexOf(".");let n=r.substring(0,o),s=r.substring(o+1);if(0===t)return Number(s[0])>=5&&(n=(Number(n)+1).toString()),{integerDigits:n,decimalDigits:void 0};if(s.length>t){const{integerDigits:e,decimalDigits:r}=function(e,t){let r="0",o=e;const n=e.slice(0,t),s=t;if(Number(e[s])<5)return{integerDigits:r,decimalDigits:n};const i=n.match(so)?.[0]||"",a=(Number(n)+1).toString(),l=n.slice(i.length),c=a.length>l.length;c&&!i?(r="1",o=void 0):o=c?i.slice(0,-1)+a:i+a;return{integerDigits:r,decimalDigits:o}}(s,t);s=r,"0"!==e&&(n=(Number(n)+Number(e)).toString())}return{integerDigits:n,decimalDigits:no(s||"")}}function no(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const so=/^0+/;const io=Ue(function(e){if(!e)return!1;try{return"date"===zr(e).positive.type}catch(e){return!1}});function ao(e,t,r){switch(t){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return Kr[e.getDay()].slice(0,3);case"dddd":return Kr[e.getDay()].toString();case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return Xr[e.getMonth()].slice(0,3);case"mmmm":return Xr[e.getMonth()].toString();case"mmmmm":return Xr[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 o=String(e.getFullYear()).replace("-","").padStart(2,"0");return o.slice(o.length-2);case"yyyy":return e.getFullYear();case"hhhh":return Math.floor((e.getTime()-et.getTime())/36e5).toString();case"hh":let n=e.getHours();return r&&(n=0===n?12:n>12?n-12:n),n.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 lo=Ue(function(e){return new RegExp(`[0-9]+${te(e.decimalSeparator)}[0-9]`)});function co(e){let{integerDigits:t,decimalDigits:r}=oo(e);if(!r)return"0";const o=t.replace("-","").length;if(o+2>11)return"0";const n=11-o-1;return({decimalDigits:r}=oo(e,Math.min(n,r.length))),r?"0."+"0".repeat(r.length):"0"}function uo(e,t){if(!ft(e,t))return;return mt(e,t).format}function ho(e){const t=e.includes(".")?"0.00":"0",r=e.match(/[\$€]/);if(r){const o=e.match(/[\d]/),n="[$"+r.values().next().value+"]";return o.index<r.index?"#,##"+t+n:n+"#,##"+t}if(e.includes("%"))return t+"%"}function fo(e,t,r){let o=0;try{o=Math.abs(Ut(e?.value,r))}catch(e){return""}const n=e?.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return go(n,1,"k");case"m":return go(n,2,"m");case"b":return go(n,3,"b");default:throw new S(v("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?go(n,0,""):o<1e8?go(n,1,"k"):o<1e11?go(n,2,"m"):go(n,3,"b")}function go(e,t,r,o){const n=zr(e||"#,##0");return qr({positive:mo(n.positive,t,r),negative:n.negative?mo(n.negative,t,r):void 0,zero:n.zero?mo(n.zero,t,r):void 0,text:n.text})}function mo(e,t,r){if("number"!==e.type)return e;const o={type:"STRING",value:r};let n=[...e.integerPart];const s=n.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"===n[s+1]?.type;)n=He(n,[s+1]);const i=n[s+1];n="STRING"===i?.type&&["m","k","b"].includes(i.value)?ze(n,o,s+1):Be(n,[o],s+1),t>0&&(n=Be(n,Array(t).fill({type:"THOUSANDS_SEPARATOR",value:","}),s+1));const a=e.percentSymbols-n.filter(e=>"PERCENT"===e.type).length;return n.push(...new Array(a).fill({type:"PERCENT",value:"%"})),{...e,integerPart:n,decimalPart:void 0,magnitude:t}}function po(e,t){const r=zr(e);return qr(zr(qr({positive:bo(r.positive,t),negative:r.negative?bo(r.negative,t):void 0,zero:r.zero?bo(r.zero,t):void 0,text:r.text})))}function bo(e,t){return"number"!==e.type?e:t>0?function(e,t){let r=e.integerPart,o=e.decimalPart;if(!o){const e=r.findLastIndex(e=>"DIGIT"===e.type);o=r.slice(e+1),r=r.slice(0,e+1)}const n=le(0,t).map(()=>({type:"DIGIT",value:"0"})),s=o.findLastIndex(e=>"DIGIT"===e.type);o=-1===s?[...n,...o]:Be(o,n,s+1);return{...e,decimalPart:o,integerPart:r}}(e,t):function(e,t){let r=e.decimalPart;if(!r)return e;const o=[];let n=0;for(let e=r.length-1;e>=0&&!(n>=Math.abs(t));e--)"DIGIT"===r[e].type&&(n++,o.push(e));if(r=He(r,o),r.some(e=>"DIGIT"===e.type))return{...e,decimalPart:r};return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...r]}}(e,Math.abs(t))}function vo(e){const t=zr(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 yo(e){if(!e)return!1;try{return"text"===zr(e).positive.type}catch{return!1}}function wo(e,t,r){const o=e.value;switch(typeof o){case"number":return Qr(o,{locale:r,format:e.format});case"string":return Pt(o)?o:`"${o}"`;case"boolean":return o?"TRUE":"FALSE"}return t}function Eo(e,t){if(!e)throw new S(t)}function So(e,t=v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")){if(0===e)throw new O(t)}function Co(e){return 1===e.length||1===e[0].length}function To(...e){if(e.every(F)){const t=e[0].length,r=e[0][0].length;for(const o of e)if(o.length!==t||o[0].length!==r)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(1!==e.length||1!==e[0].length))}function Io(e){return e.length===e[0].length}const xo=e=>v("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e);function Ro(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 Ao(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,o=Ro(r),n=e.map(e=>e.slice());for(let e=0;e<r;e++){let s=n[e][e];if(0===s){for(let s=e+1;s<r;s++)if(0!==n[e][s]){Oo(n,e,s),Oo(o,e,s),t*=-1;break}if(s=n[e][e],0===s)return{determinant:0}}for(let t=0;t<r;t++)n[t][e]=n[t][e]/s,o[t][e]=o[t][e]/s;t*=s;for(let t=0;t<r;t++){if(t===e)continue;const s=n[e][t];for(let i=0;i<r;i++)n[i][t]-=s*n[i][e],o[i][t]-=s*o[i][e]}}return{inverted:o,determinant:t}}function Oo(e,t,r){for(let o=0;o<e.length;o++){const n=e[o][t];e[o][t]=e[o][r],e[o][r]=n}}function _o(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,o=t.length,n=e.length,s=Array(o);for(let i=0;i<o;i++){s[i]=Array(r);for(let o=0;o<r;o++){let r=0;for(let s=0;s<n;s++)r+=e[s][o]*t[i][s];s[i][o]=r}}return s}function Fo(e){if(!F(e))return e;if(!Do(e))throw new Error("The value should be a scalar or a 1x1 matrix");return e[0][0]}function Do(e){return 1===e.length&&1===e[0].length}function No(e){return F(e)&&!Do(e)}function Mo(e,t){const r=e.map(br),o=r.map(e=>e?.[0]?.length??0),n=Math.max(...o);if(t?.requireSameRowCount){const e=o[0];if(o.some(t=>t!==e))return new S(v("All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).",o.join(", ")))}const s=[];for(const e of r)for(let t=0;t<e.length;t++){const r=Array(n).fill({value:null});for(let o=0;o<e[t].length;o++)r[o]=e[t][o];s.push(r)}return s}function Vo(e,t){const r=e.map(br),o=r.map(e=>e?.length??0),n=Math.max(...o);if(t?.requireSameColCount){const e=o[0];if(o.some(t=>t!==e))return new S(v("All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).",o.join(", ")))}const s=nr(n,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 Po={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 o=br(e),n=$t(t?.value,this.locale),s=$t(r?.value,this.locale);if(n<=0)return new S(v("The rows argument (%s) must be strictly positive.",n.toString()));if(s<=0)return new S(v("The columns argument (%s) must be strictly positive.",s.toString()));const i=Math.min(n,o[0].length);return nr(Math.min(s,o.length),i,(e,t)=>o[e][t])},isExported:!1},Lo={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 Vo(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},ko={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 Mo(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},Uo={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=br(e),o=vr(t,e=>$t(e?.value,this.locale)),n=o.filter(e=>0===e||r.length<Math.abs(e));if(0!==n.length)return new S(v("The columns arguments must be between -%s and %s (got %s), excluding 0.",r.length.toString(),r.length.toString(),n.join(",")));const s=Array(o.length);for(let e=0;e<o.length;e++)o[e]>0?s[e]=r[o[e]-1]:s[e]=r[r.length+o[e]];return s},isExported:!0},Ho={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=br(e),o=vr(t,e=>$t(e?.value,this.locale)),n=r.length,s=o.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(","))):nr(n,o.length,(e,t)=>o[t]>0?r[e][o[t]-1]:r[e][r[e].length+o[t]])},isExported:!0},Bo={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,o={value:0}){const n=br(e),s=$t(t?.value,this.locale),i=void 0!==r?$t(r.value,this.locale):n.length;return s<n[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<n.length?new S(v("The columns arguments (%s) must be greater or equal than the number of columns of the array.",i.toString())):nr(i,s,(e,t)=>e>=n.length||t>=n[e].length?o:n[e][t])},isExported:!0},zo={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[vr(e,e=>void 0===e?{value:""}:e)]},isExported:!1},$o={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=vr([e],e=>e.value).filter(e=>"number"==typeof e),o=vr([t],e=>e.value).filter(e=>"number"==typeof e),n=o.map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);n.push({initialIndex:n.length,value:1/0,count:0});const s=r.sort((e,t)=>e-t);let i=0;for(const e of s){for(;e>n[i].value&&i<n.length-1;)i++;n[i].count++}return[n.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},Go={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 Mo(e)},isExported:!0},Wo={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=Bt(e,"square_matrix");return Io(t)?Ao(t).determinant:new S(v("The argument square_matrix must have the same number of columns and rows."))},isExported:!0},qo={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=Bt(e,"square_matrix");if(!Io(t))return new S(v("The argument square_matrix must have the same number of columns and rows."));const{inverted:r}=Ao(t);return r||new S(v("The matrix is not invertible."))},isExported:!0},Zo={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=Bt(e,"matrix1"),o=Bt(t,"matrix2");return 0===r.length||0===o.length?new S(v("The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.")):r.length!==o[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(),o[0].length.toString())):_o(r,o)},isExported:!0},Yo={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(!To(...e))return new S(v("All the ranges must have the same dimensions."));const t=e.map(br);let r=0;for(let e=0;e<t[0].length;e++)for(let o=0;o<t[0][e].length;o++){if(!t.every(t=>"number"==typeof t[e][o].value))continue;let n=1;for(const r of t)n*=Ut(r[e][o],this.locale);r+=n}return r},isExported:!0};function jo(e,t,r){if(!To(e,t))return new S(v("The arguments array_x and array_y must have the same dimensions."));const o=br(e),n=br(t);let s=!1,i=0;for(const e in o)for(const t in o[e]){const a=o[e][t].value,l=n[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 Xo={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 jo(e,t,(e,t)=>e**2-t**2)},isExported:!0},Ko={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 jo(e,t,(e,t)=>e**2+t**2)},isExported:!0},Qo={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 jo(e,t,(e,t)=>(e-t)**2)},isExported:!0},Jo=!1,en=[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 tn(e){const t=Math.trunc(e);if(0===t)return()=>!0;if(1===t)return e=>null!==e.value;if(2===t)return e=>!Pt(e.value);if(3===t)return e=>null!==e.value&&!Pt(e.value);throw new S(v("Argument ignore must be between 0 and 3"))}const rn={description:v("Transforms a range of cells into a single column."),args:en,compute:function(e,t={value:0},r={value:Jo}){const o=br(e),n=Ut(t.value,this.locale),s=(Yt(r.value)?o:ir(o)).flat().filter(tn(n));return 0===s.length?new x(v("No results for the given arguments of TOCOL.")):[s]},isExported:!0},on={description:v("Transforms a range of cells into a single row."),args:en,compute:function(e,t={value:0},r={value:Jo}){const o=br(e),n=Ut(t.value,this.locale),s=(Yt(r.value)?o:ir(o)).flat().filter(tn(n)).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},nn={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=br(e);return nr(t[0].length,t.length,(e,r)=>t[r][e])},isExported:!0},sn={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 Vo(e)},isExported:!0},an={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 o=br(e),n=$t(t?.value,this.locale);if(!Co(o))return new S(v("Argument range must be a single row or column."));const s=o.flat();return nr(Math.ceil(s.length/n),n,(e,t)=>{const o=e*n+t;return o<s.length?s[o]:r})},isExported:!0},ln={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 o=br(e),n=$t(t?.value,this.locale);if(!Co(o))return new S(v("Argument range must be a single row or column."));const s=o.flat(),i=Math.ceil(s.length/n);return nr(n,i,(e,t)=>{const o=t*n+e;return o<s.length?s[o]:r})},isExported:!0},cn=[{value:0,label:v("Concise format (default)")},{value:1,label:v("Strict format")}],un={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."),cn)],compute:function(e,t={value:0}){const r=Ut(t,this.locale),o=br(e);if(1===r)return function(e,t,r){if(F(e)){const o=","===r.decimalSeparator?"/":",";return`{${ir(e).map(e=>e.map(e=>wo(e,t,r)).join(o)).join(";")}}`}return wo(e,t,r)}(o,"",this.locale);if(0===r){const e=","===this.locale.decimalSeparator?"/":",";return ir(o).flatMap(e=>e.map(e=>Pt(e.value)?e.value:Wt(e))).join(e)}return new S(v("Format must be 0 or 1"))},isExported:!0};var hn=Object.freeze({__proto__:null,ARRAYTOTEXT:un,ARRAY_CONSTRAIN:Po,ARRAY_LITERAL:Lo,ARRAY_ROW:ko,CHOOSECOLS:Uo,CHOOSEROWS:Ho,EXPAND:Bo,FLATTEN:zo,FREQUENCY:$o,HSTACK:Go,MDETERM:Wo,MINVERSE:qo,MMULT:Zo,SUMPRODUCT:Yo,SUMX2MY2:Xo,SUMX2PY2:Ko,SUMXMY2:Qo,TOCOL:rn,TOROW:on,TRANSPOSE:nn,VSTACK:sn,WRAPCOLS:an,WRAPROWS:ln});const dn={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:Ut(e,this.locale),format:fo(e,t,this.locale)}}};var fn=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:dn});const gn=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),mn=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),pn=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),bn=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),vn=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),yn=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),wn=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[gn.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 En(e){return vn.test(e)}function Sn(e){return yn.test(e)}function Cn(e){return pn.test(e)}function Tn(e){return bn.test(e)}function In(e){return mn.test(e)}function xn(e){if(!e.includes("!"))return{xc:e};const t=e.split("!"),r=t.pop();return{sheetName:oe(t.join("!"))||void 0,xc:r}}function Rn(e,t){return void 0!==e?`${se(e)}!${t}`:t}function An(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=On(e,"colrow");break;case"colrow":e=On(e,"row");break;case"row":e=On(e,"col");break;case"col":e=On(e,"none")}return e}function On(e,t){let r;({sheetName:r,xc:e}=xn(e)),r=r?se(r)+"!":"";const o=(e=e.replace(/\$/g,"")).indexOf(":");return o>=0?`${r}${_n(e.slice(0,o),t)}:${_n(e.slice(o+1),t)}`:r+_n(e,t)}function _n(e,t){const r=e.search(/[0-9]/),o=0!==r,n=r>=0;switch(t){case"col":return o?"$"+e:e;case"row":return n?e.slice(0,r)+"$"+e.slice(r):e;case"colrow":return n&&o?"$"+e.slice(0,r)+"$"+e.slice(r):"$"+e;case"none":return e}}function Fn(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class Dn{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 Nn(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Nn(Math.floor(e/26)-1)+Nn(e%26)}function Mn(e){const t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function Vn(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function Pn(e){return e>="0"&&e<="9"}const Ln=function(e){let t=0;const r=e.length;for(let o=0;o<r;o++){t=26*t+Mn(e[o])}return t-1}("ZZZ"),kn=9999998;function Un(e){for(;" "===e.current;)e.advanceBy(1)}function Hn(e){if("$"===e.current&&e.advanceBy(1),!e.current||!Vn(e.current))return-1;let t=0;for(;e.current&&Vn(e.current);)t=26*t+Mn(e.shift());return t}function Bn(e){if("$"===e.current&&e.advanceBy(1),!e.current||!Pn(e.current))return-1;let t=0;for(;e.current&&Pn(e.current);)t=10*t+Number(e.shift());return t}function zn(e){const t=new Ze(e);Un(t);const r=Hn(t);if(-1===r||!t.current)throw new Error(`Invalid cell description: ${e}`);const o=Bn(t);Un(t);const n=r-1,s=o-1;if(!t.isOver()||n>Ln||s>kn)throw new Error(`Invalid cell description: ${e}`);return{col:n,row:s}}function $n(e,t,r={colFixed:!1,rowFixed:!1}){return(r.colFixed?"$":"")+Nn(e)+(r.rowFixed?"$":"")+String(t+1)}function Gn(e,t=[]){if(e.length<=1&&0===t.length)return e;const r=[0],o=new Map([[0,[]]]);return Wn(r,o,e,!1),Wn(r,o,t,!0),jn(r,o)}function Wn(e,t,r,o=!1){for(const n of r){const r=n.left,s=void 0===n.right?void 0:n.right+1,i=qn(e,t,r,!0,0),a=qn(e,t,s,!1,i);for(let r=i;r<=a;r++){Zn(t.get(e[r]),n,o)}Yn(e,t,i,a)}}function qn(e,t,r,o,n){if(void 0===r)return e.length-1;const s=Xn(e,r,n);return r!==e[s]?(e.splice(s+1,0,r),t.set(r,[...t.get(e[s])]),o?s+1:s):o?s:s-1}function Zn(e,t,r=!1){const o=t.top,n=void 0===t.bottom?void 0:t.bottom+1,s=[],i=Xn(e,o,0,!1);if((i%2!=0&&!r||i%2==0&&r)&&s.push(o),void 0===n)return e.splice(i+1),void e.push(...s);const a=Kn(e,n,0,!1);(a%2==0&&!r||a%2!=0&&r)&&s.push(n);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 Yn(e,t,r,o){const n=r-1==-1?0:r-1;for(let r=o===e.length-1?o:o+1;r>n;r--)_e(t.get(e[r]),t.get(e[r-1]))&&(t.delete(e[r]),e.splice(r,1))}function jn(e,t){const r=[];let o=[];for(let n=0;n<e.length;n++){const s=e[n],i=t.get(s);if(!i||0===i.length){r.push(...o),o=[];continue}let a=e[n+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 n={top:t,left:s,bottom:r,right:a};(void 0===r&&0!==t||void 0===a&&0!==s)&&(n.hasHeader=!0);let c=!1;for(let e=o.length-1;e>=0;e--){const t=o[e];if(t.top===n.top&&t.bottom===n.bottom){t.right=n.right,o.splice(e,1),l.push(t),c=!0;break}}c||l.push(n)}r.push(...o),o=l}return r.push(...o),r}function Xn(e,t,r=0,o=!0){let n=e.length-1,s=-1;for(;r<=n;){const i=Math.floor((r+n)/2);if(e[i]===t&&o)return i;e[i]<t?(s=i,r=i+1):n=i-1}return s}function Kn(e,t,r=0,o=!0){let n=e.length-1,s=e.length;for(;r<=n;){const i=Math.floor((r+n)/2);if(e[i]===t&&o)return i;e[i]>t?(s=i,n=i-1):r=i+1}return s}function Qn(e){const t=function(e){const t=new Ze(e);Un(t);const r=e.indexOf("!");-1!==r&&t.advanceBy(r+1);const o=Hn(t),n=Bn(t);let s,i,a,l,c=!1,u=!1,h=!1;if(-1===n?(a=l=o-1,s=i=0,c=!0):-1===o?(s=i=n-1,a=l=0,u=!0):(a=l=o-1,s=i=n-1,h=!0),Un(t),":"===t.current){t.advanceBy(1),Un(t);const e=Hn(t),r=Bn(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=ps(t),o=r.bottom,n=r.right;if(void 0!==o&&o>kn||void 0!==n&&n>Ln)throw new Error(`Range string out of bounds: ${e}`);if(void 0===o&&void 0===n)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");return r}function Jn(e){const t=Qn(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function es(e){const{bottom:t,top:r,left:o,right:n}=e;return!(void 0!==t&&isNaN(t)||isNaN(r)||isNaN(o)||void 0!==n&&isNaN(n))&&(ts(e)&&e.top>=0&&e.left>=0)}function ts(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 rs(e){const{top:t,bottom:r,left:o,right:n}=e,s="hasHeader"in e&&e.hasHeader,i=t===r&&o===n;if(void 0===r&&void 0!==n)return 0!==t||s?`${$n(o,t)}:${Nn(n)}`:`${Nn(o)}:${Nn(n)}`;if(void 0===n&&void 0!==r)return 0!==o||s?`${$n(o,t)}:${r+1}`:`${t+1}:${r+1}`;if(void 0!==r&&void 0!==n)return i?$n(o,t):`${$n(o,t)}:${$n(n,r)}`;throw new Error("Bad zone format")}function os(e,t,r,o,n){const s="left"===t?"columns":"rows",i="before"===o?r-1:r,a="left"===t?"right":"bottom";return e[t]<=i&&e[a]>i?bs(e,s,"RESIZE",n):i<e[t]?bs(e,s,"MOVE",n):{...e}}function ns(e,t,r){const o="left"===t?"right":"bottom";let n=e[t],s=e[o];for(const i of r.sort((e,t)=>t-e))e[t]>i&&(n--,s--),e[t]<i&&e[o]>=i&&s--;return{...e,[t]:n,[o]:s}}function ss(...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 is(e,t){if(cs(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 as(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom&&e.hasHeader===t.hasHeader}function ls(e,t){if(is(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 cs(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 us(e,t,r){const{left:o,right:n,top:s,bottom:i}=r;return e>=o&&(void 0===n||e<=n)&&t>=s&&(void 0===i||t<=i)}function hs(e,t){return e.left>=t.left&&e.right<=t.right&&e.top>=t.top&&e.bottom<=t.bottom}function ds(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function fs(e){const{numberOfCols:t,numberOfRows:r}=ds(e);return 1===t||1===r}function gs(e){const t=[],{left:r,right:o,top:n,bottom:s}=ps(e);for(const e of le(r,o+1))for(const r of le(n,s+1))t.push({col:e,row:r});return t}function ms(e,t){const r=[],{left:o,right:n,top:s,bottom:i}=ps(t);for(const t of le(o,n+1))for(const o of le(s,i+1))r.push({sheetId:e,col:t,row:o});return r}function ps(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 bs(e,t,r,o){const n="both"===t?o[0]:"columns"===t?o:0,s="both"===t?o[1]:"rows"===t?o:0,i="hasHeader"in e&&e.hasHeader;let a;a=Es(e)&&!i?"rows"!==t:!(ws(e)&&!i)||"columns"!==t;const l={...e};return a&&"MOVE"===r&&(l.left+=n,l.top+=s),void 0!==l.right&&(l.right+=n),void 0!==l.bottom&&(l.bottom+=s),l}function vs(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function ys(e){return{...e,right:e.left,bottom:e.top}}function ws(e){return void 0===e.right}function Es(e){return void 0===e.bottom}function Ss(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Cs(e){return e.length<2||1===Gn(e).length}function Ts(e,t){const r=ls(e,t);if(!r)return[e];const o=[];switch(r.position){case"bottom":case"top":return o.push({top:e.top,bottom:e.bottom,left:r.start,right:r.stop}),r.start>e.left&&o.push({top:e.top,bottom:e.bottom,left:e.left,right:r.start-1}),(void 0===e.right||r.stop<e.right)&&o.push({top:e.top,bottom:e.bottom,left:r.stop+1,right:e.right}),o;case"left":case"right":return o.push({top:r.start,bottom:r.stop,left:e.left,right:e.right}),r.start>e.top&&o.push({top:e.top,bottom:r.start-1,left:e.left,right:e.right}),(void 0===e.bottom||r.stop<e.bottom)&&o.push({top:r.stop+1,bottom:e.bottom,left:e.left,right:e.right}),o}}function Is(e,t){return rr(e,(e,t)=>e+t,0,t)}function xs(e){return tr(e,(e,t)=>yr(t)?e.add(t?.value):e,new Set).size}const Rs=/^-?[a-z0-9]+$/i,As={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(Ut(e,this.locale))},isExported:!0},Os={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=Ut(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=Ut(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},Fs={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=Ut(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Ds={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=Ut(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},Ns={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=Ut(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},Ms={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(Ut(e,this.locale))},isExported:!0},Vs={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(Ut(e,this.locale))},isExported:!0},Ps={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=Ut(e,this.locale),o=Ut(t,this.locale);return 0===r&&0===o?new O(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):Math.atan2(o,r)},isExported:!0},Ls={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=Ut(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=Ut(e,this.locale),o=Ut(t,this.locale);return o<0&&r>0?new S(v("The factor (%s) must be positive when the value (%s) is positive.",o,r)):{value:o?Math.ceil(r/o)*o:0,format:e?.format}},isExported:!0};function Us(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 Hs={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 o=Ut(t,this.locale);return{value:Us(Ut(e,this.locale),o,Ut(r,this.locale)),format:e?.format}},isExported:!0},Bs={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=Ut(t,this.locale);return{value:Us(Ut(e,this.locale),r),format:e?.format}},isExported:!0},zs={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(Ut(e,this.locale))},isExported:!0},$s={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(Ut(e,this.locale))},isExported:!0},Gs={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=Ut(e,this.locale);return 0===t?new O(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tan(t)},isExported:!0},Ws={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=Ut(e,this.locale);return 0===t?new O(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tanh(t)},isExported:!0},qs={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 tr(e,(e,t)=>void 0===t||null===t.value||""===t.value?e+1:e,0)},isExported:!0},Zs={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 dr(e,(e,r)=>{t+=1},this.locale),t},isExported:!0},Ys={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 dr(e,(e,r)=>{t+=1},this.locale),t},isExported:!0},js={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 xs(e)}},Xs={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 dr(t,(t,o)=>{const n=e[t]?.[o];yr(n)&&r.add(n.value)},this.locale),r.size}},Ks={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=Ut(e,this.locale);return 0===t?new O(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sin(t)},isExported:!0},Qs={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=Ut(e,this.locale);return 0===t?new O(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sinh(t)},isExported:!0},Js={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=Ut(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 o=Wt(e);if(""===o)return 0;if(!Rs.test(o))return new S(v("The value (%s) must be a valid base %s representation.",o,r));const n=parseInt(o,r);return isNaN(n)?new S(v("The value (%s) must be a valid base %s representation.",o,r)):n},isExported:!0},ei={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*Ut(e,this.locale)/Math.PI},isExported:!0},ti={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(Ut(e,this.locale))},isExported:!0},ri={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=Ut(e,this.locale),o=Ut(t,this.locale);return o<0&&r>0?new S(v("The factor (%s) must be positive when the value (%s) is positive.",o,r)):{value:o?Math.floor(r/o)*o:0,format:e?.format}},isExported:!0};function oi(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 ni={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 o=Ut(t,this.locale);return{value:oi(Ut(e,this.locale),o,Ut(r,this.locale)),format:e?.format}},isExported:!0},si={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=Ut(t,this.locale);return{value:oi(Ut(e,this.locale),r),format:e?.format}},isExported:!0},ii={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=zt(e,this.locale);return!(1&Math.floor(Math.abs(t)))},isExported:!0},ai={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:Us(Ut(e,this.locale),Ut(t,this.locale)),format:e?.format}},isExported:!0},li={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=zt(e,this.locale);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},ci={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=Ut(e,this.locale);return t<=0?new S(v("The value (%s) must be strictly positive.",t)):Math.log(t)},isExported:!0},ui={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=Ut(e,this.locale),o=Ut(t,this.locale);return r<=0?new S(v("The value (%s) must be strictly positive.",r)):o<=0?new S(v("The base (%s) must be strictly positive.",o)):1===o?new S(v("The base must be different from 1.")):Math.log10(r)/Math.log10(o)},isExported:!0};function hi(e,t){So(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 di={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=Ut(t,this.locale);return{value:hi(Ut(e,this.locale),r),format:e?.format}},isExported:!0},fi={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=$t(e,this.locale);return t<1?new S(v("The argument dimension must be positive")):Ro(t)},isExported:!0},gi={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=Ut(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},mi={description:v("The number pi."),args:[],compute:function(){return Math.PI},isExported:!0},pi={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=Ut(e,this.locale),o=Ut(t,this.locale);return r<0&&!Number.isInteger(o)?new S(v("The exponent (%s) must be an integer when the base is negative.",o)):{value:Math.pow(r,o),format:e?.format}},isExported:!0},bi={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 o of e)if(F(o))for(const e of o)for(const o of e){const e=o.value;if("number"==typeof e&&(r*=e,t+=1),Pt(e))return o}else void 0!==o&&null!==o.value&&(r*=zt(o,this.locale),t+=1);return{value:0===t?0:r,format:Vt(e[0])}},isExported:!0},vi={description:v("A random number between 0 inclusive and 1 exclusive."),args:[],compute:function(){return Math.random()},isExported:!0},yi={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},o={value:1},n={value:!1}){const s=$t(t,this.locale),i=$t(e,this.locale),a=Ut(r,this.locale),l=Ut(o,this.locale),c=Yt(n);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},wi={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=Ut(e,this.locale);Number.isInteger(r)||(r=Math.ceil(r));let o=Ut(t,this.locale);return Number.isInteger(o)||(o=Math.floor(o)),r>o?new S(v("The high (%s) must be greater than or equal to the low (%s).",o,r)):{value:r+Math.ceil((o-r+1)*Math.random())-1,format:e?.format}},isExported:!0},Ei={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=Ut(e,this.locale);let o=Ut(t,this.locale);const n=Math.abs(r);let s;return 0===o?s=Math.round(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.round(n*Math.pow(10,o))/Math.pow(10,o)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},Si={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=Ut(e,this.locale);let o=Ut(t,this.locale);const n=Math.abs(r);let s;return 0===o?s=Math.floor(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.floor(n*Math.pow(10,o))/Math.pow(10,o)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},Ci={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=Ut(e,this.locale);let o=Ut(t,this.locale);const n=Math.abs(r);let s;return 0===o?s=Math.ceil(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.ceil(n*Math.pow(10,o))/Math.pow(10,o)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},Ti={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(Ut(e,this.locale))},isExported:!0},Ii={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(Ut(e,this.locale))},isExported:!0},xi={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},o={value:1}){const n=Ut(r,this.locale),s=Ut(o,this.locale),i=$t(e,this.locale),a=$t(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)):nr(a,i,(e,t)=>({value:n+t*a*s+e*s}))},isExported:!0},Ri={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(Ut(e,this.locale))},isExported:!0},Ai={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(Ut(e,this.locale))},isExported:!0},Oi={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=Ut(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"},Fi=Object.entries(_i).map(([e,t])=>({value:parseInt(e),label:v("%s (include manually-hidden rows)",t)})),Di=Object.entries(_i).map(([e,t])=>({value:parseInt(e)+100,label:v("%s (exclude manually-hidden rows)",t)})),Ni={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."),[...Fi,...Di]),a("ref (meta, range<meta>, repeating)",v("Range or reference for which you want the subtotal."))],compute:function(e,...t){let r=$t(e,this.locale),o=!0;if(r>100&&(r-=100,o=!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 n=[];for(const e of t){const t=e[0][0],r=xn(t.value).sheetName,s=r?this.getters.getSheetIdByName(r):this.__originSheetId;if(!s)continue;const{top:i,left:a}=Jn(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)&&(o||!this.getters.isRowHiddenByUser(s,e)))for(let t=a;t<=l;t++){const r=this.getters.getCorrespondingFormulaCell({sheetId:s,col:t,row:e});r&&Qe(r,"SUBTOTAL")||n.push(this.getters.getEvaluatedCell({sheetId:s,col:t,row:e}))}}return this[_i[r]].apply(this,[[n]])},isExported:!0},Mi={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:Is(e,this.locale),format:Vt(t)}},isExported:!0},Vi={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 o=0;return dr([e,t],(e,t)=>{const n=r[e]?.[t]?.value;"number"==typeof n&&(o+=n)},this.locale),o},isExported:!0},Pi={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 dr(t,(t,o)=>{const n=e[t]?.[o]?.value;"number"==typeof n&&(r+=n)},this.locale),r},isExported:!0},Li={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(Ut(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(Ut(e,this.locale))},isExported:!0};function Ui(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 Hi={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:Ui(Ut(e,this.locale),Ut(t,this.locale)),format:e?.format}},isExported:!0},Bi={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(Ut(e,this.locale))},isExported:!0};var zi=Object.freeze({__proto__:null,ABS:As,ACOS:Os,ACOSH:_s,ACOT:Fs,ACOTH:Ds,ASIN:Ns,ASINH:Ms,ATAN:Vs,ATAN2:Ps,ATANH:Ls,CEILING:ks,CEILING_MATH:Hs,CEILING_PRECISE:Bs,COS:zs,COSH:$s,COT:Gs,COTH:Ws,COUNTBLANK:qs,COUNTIF:Zs,COUNTIFS:Ys,COUNTUNIQUE:js,COUNTUNIQUEIFS:Xs,CSC:Ks,CSCH:Qs,DECIMAL:Js,DEGREES:ei,EXP:ti,FLOOR:ri,FLOOR_MATH:ni,FLOOR_PRECISE:si,INT:Bi,ISEVEN:ii,ISODD:li,ISO_CEILING:ai,LN:ci,LOG:ui,MOD:di,MUNIT:fi,ODD:gi,PI:mi,POWER:pi,PRODUCT:bi,RAND:vi,RANDARRAY:yi,RANDBETWEEN:wi,ROUND:Ei,ROUNDDOWN:Si,ROUNDUP:Ci,SEC:Ti,SECH:Ii,SEQUENCE:xi,SIN:Ri,SINH:Ai,SQRT:Oi,SUBTOTAL:Ni,SUM:Mi,SUMIF:Vi,SUMIFS:Pi,TAN:Li,TANH:ki,TRUNC:Hi});function $i(...e){const t=e[0].length;e.forEach((e,r)=>Eo(e.length===t,v("[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).",r.toString(),t.toString(),e.length.toString())))}function Gi(e,t){let r=0;const o=rr(e,(e,t)=>(r+=1,e+t),0,t);return So(r),o/r}function Wi(e){return tr(e,(e,t)=>void 0!==t&&null!==t.value?e+1:e,0)}function qi(e,t){let r={value:-1/0};return Jt(e,e=>{e.value>=r.value&&(r=e)},t),r.value===-1/0?{value:0}:r}function Zi(e,t){let r={value:1/0};return Jt(e,e=>{e.value<=r.value&&(r=e)},t),r.value===1/0?{value:0}:r}function Yi(e,t,r){const o=e[0].length?e:[le(1,t.flat().length+1)],n=o.length;let s=r[0].length?r:o;return s=s.length===n?ir(s):s,{_X:o,_newX:s}}function ji(e,t,r=!0,o=!1){const n=t.flat(),s=n.length;let{_X:i}=Yi(e,t,[[]]);i=i.length===s?ir(i):i.slice(),$i(i[0],n);const a=i.length,l=s-a-(r?1:0),c=[n],u=ir(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 n)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=Ki(u,c);if(r||g.push([0]),!o)return g;const m=_o(f,ir(f)),{inverted:p}=Ao(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=n[e]-d;let r=0;for(let t=0;t<a;t++){r+=f[e][t]*g[t][0]}const o=t-r;b+=o*o,y+=r*r}const w=Math.sqrt(b/l),E=y/(y+b),C=y/a/(b/l),T=[];for(let e=0;e<a;e++)T.push(w*Math.sqrt(p[e][e]));if(r){const e=_o(p,[h]),t=_o(ir([h]),e);T.push(w*Math.sqrt(t[0][0]+1/n.length))}const I=[[g[0][0],T[0],E,C,y],[g[1][0],T[1],w,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 Xi(e,t,r,o){$i(t,e),Eo(r>=1,v("Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible."));const n=[e],s=t.map(e=>le(0,r).map(t=>Math.pow(e,r-t)));o&&s.forEach(e=>e.push(1));const i=Ki(s,n);return o||i.push([0]),i}function Ki(e,t){const r=_o(e,ir(e)),{inverted:o}=Ao(r);if(void 0===o)throw new S(v("Matrix is not invertible"));const n=_o(e,t);return ir(_o(o,n))}function Qi(e){return e.map(e=>e.map(e=>Math.log(e)))}function Ji(e,t,r,o){const{_X:n,_newX:s}=Yi(t,e,r),i=ji(n,e,o,!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:ir(l)}const ea=[{value:!0,label:v("b is calculated normally")},{value:!1,label:v("b is forced to 1")}],ta=[{value:!1,label:v("do not return additional regression statistics")},{value:!0,label:v("return additional regression statistics")}],ra=[{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)")}],oa=[{value:!0,label:v("Compute intercept")},{value:!1,label:v("Force intercept to 0")}],na=[{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 sa(e,t){const r=[],o=[];let n=0,s=0;Qt([e],e=>{r.push(e),n+=1}),Qt([t],e=>{o.push(e),s+=1}),Eo(n===s,v("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",n,s));const i=[],a=[];for(let e=0;e<n;e++){const t=r[e]?.value,n=o[e]?.value;"number"==typeof t&&"number"==typeof n&&(a.push(t),i.push(n))}return{flatDataX:i,flatDataY:a}}function ia(e,t,r){const{flatDataX:o,flatDataY:n}=sa(e,t),s=n.length;So(s),r&&So(s-1);let i=0,a=0;for(let e=0;e<s;e++)i+=n[e],a+=o[e];const l=i/s,c=a/s;let u=0;for(let e=0;e<s;e++)u+=(n[e]-l)*(o[e]-c);return u/(s-(r?1:0))}function aa(e,t,r,o){let n=0;const s=r?or:rr,i=s(e,(e,t)=>(n+=1,e+t),0,o);So(n),t&&So(n-1);const a=i/n;return s(e,(e,t)=>e+Math.pow(t-a,2),0,o)/(n-(t?1:0))}function la(e,t,r,o){const n=Ut(t,o);Eo(r?0<=n&&n<=1:0<n&&n<1,v("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));const s=[];let i,a=0;return Qt(e,e=>{const t=e?.value;"number"==typeof t&&(i=fr(s,e,"nextSmaller","asc",s.length,(e,t)=>e[t]),s.splice(i+1,0,t),a++)}),Eo(0!==a,wr),r||Eo(1/(a+1)<=n&&n<=a/(a+1),v("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),Nt(s,n,r)}const ca={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=rr(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 o=r/t;return rr(e,(e,t)=>e+Math.abs(o-t),0,this.locale)/t},isExported:!0},ua={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:Gi(e,this.locale),format:Vt(e[0])}},isExported:!0},ha=v("[[FUNCTION_NAME]] has mismatched range sizes."),da=v("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),fa={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 o=0;o<e.length-1;o+=2){const n=e[o],s=e[o+1];if(!To(n,s))return new S(ha);if(F(n))for(let e=0;e<n.length;e++)for(let o=0;o<n[0].length;o++){const i=n[e][o].value,a=F(s)?s?.[e][o].value:Ut(s,this.locale),l="number"==typeof i,c="number"==typeof a;if(l&&c){if(a<0)return new S(da);t+=i*a,r+=a}else if(l!==c)return new S(v("[[FUNCTION_NAME]] expects number values."))}else{const e=Ut(n,this.locale),o=F(s)?s?.[0][0].value:Ut(s,this.locale);if("number"==typeof o){if(o<0)return new S(da);t+=e*o,r+=o}}}return 0===r?new O(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:t/r,format:Vt(e[0])}}},ga={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=or(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:Vt(e[0])}},isExported:!0},ma={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 o=br(void 0===r?e:r);let n=0,s=0;return dr([e,t],(e,t)=>{const r=o[e]?.[t]?.value;"number"==typeof r&&(n+=1,s+=r)},this.locale),0===n?new O(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):s/n},isExported:!0},pa={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=br(e);let o=0,n=0;return dr(t,(e,t)=>{const s=r[e]?.[t]?.value;"number"==typeof s&&(o+=1,n+=s)},this.locale),0===o?new O(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):n/o},isExported:!0},ba={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 o of e)if(F(o))for(const e of o)for(const t of e)"number"==typeof t.value&&(r+=1);else{const e=o?.value;Pt(e)||"string"==typeof e&&!_t(e,t)&&!mt(e,t)||(r+=1)}return r}(e,this.locale)},isExported:!0},va={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 Wi(e)},isExported:!0},ya={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 ia(e,t,!1)},isExported:!0},wa={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 ia(e,t,!1)},isExported:!0},Ea={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 ia(e,t,!0)},isExported:!0},Sa={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:o,flatDataY:n}=sa(t,r);return 0===o.length||0===n.length?new x(wr):Ji([n],[o],sr(br(e),e=>Ut(e,this.locale)),!0)},isExported:!0},Ca={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."),ea)],compute:function(e,t=[[]],r=[[]],o={value:!0}){return 0===e.length||0===e[0].length?new S(Er("known_data_y")):Ji(Qi(Bt(e,"known_data_y")),Bt(t,"known_data_x"),Bt(r,"new_data_y"),Yt(o)).map(e=>e.map(e=>Math.exp(e)))}},Ta={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:o}=sa(e,t);if(0===r.length||0===o.length)return new x(wr);const[[],[n]]=ji([r],[o]);return n},isExported:!0},Ia={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(Ut(t?.value,this.locale)),o=[];let n,s=0;Qt([e],e=>{"number"==typeof e?.value&&(n=fr(o,e,"nextSmaller","asc",o.length,(e,t)=>e[t].value),o.splice(n+1,0,e),s++,s>r&&(o.shift(),s--))});const i=o.shift();return void 0===i?new S(wr):s<r?new S(v("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",r)):i},isExported:!0},xa={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"),ea),a("verbose (boolean, default=FALSE)",v("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),ta)],compute:function(e,t=[[]],r={value:!0},o={value:!1}){return 0===e.length||0===e[0].length?new S(Er("data_y")):ji(Bt(t,"data_x"),Bt(e,"data_y"),Yt(r),Yt(o))},isExported:!0},Ra={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"),ea),a("verbose (boolean, default=FALSE)",v("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),ta)],compute:function(e,t=[[]],r={value:!0},o={value:!1}){if(0===e.length||0===e[0].length)return new S(Er("data_y"));const n=ji(Bt(t,"data_x"),Qi(Bt(e,"data_y")),Yt(r),Yt(o));for(let e=0;e<n.length;e++)n[e][0]=Math.exp(n[e][0]);return n},isExported:!0},Aa={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(),o=t.flat();if($i(r,o),0===r.length||0===o.length)return new x(wr);const n=r.length;let s=0,i=0,a=0,l=0;for(let e=0;e<n;++e){const t=Yt(r[e]);t===Yt(o[e])?t?i++:s++:t?l++:a++}return(i*s-a*l)/Math.sqrt((i+a)*(i+l)*(s+a)*(s+l))},isExported:!1},Oa={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 qi(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=or(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:Vt(e[0])}},isExported:!0},Fa={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 dr(t,(t,o)=>{const n=e[t]?.[o]?.value;"number"==typeof n&&(r=r<n?n:r)},this.locale),r===-1/0?0:r},isExported:!0},Da={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 Jt(e,e=>{t.push(e)},this.locale),{value:la(t,{value:.5},!0,this.locale),format:Vt(t[0])}},isExported:!0},Na={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 Zi(e,this.locale)},isExported:!0},Ma={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=or(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:Vt(e[0])}},isExported:!0},Va={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 dr(t,(t,o)=>{const n=e[t]?.[o]?.value;"number"==typeof n&&(r=r>n?n:r)},this.locale),r===1/0?0:r},isExported:!0};function Pa(e,t){const{flatDataX:r,flatDataY:o}=sa(e,t);if(0===r.length||0===o.length)return new x(wr);const n=r.length;let s=0,i=0,a=0,l=0,c=0;for(let e=0;e<n;e++){const t=r[e],n=o[e];s+=t,i+=n,a+=t*n,l+=t*t,c+=n*n}return(n*a-s*i)/Math.sqrt((n*l-s*s)*(n*c-i*i))}const La={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 Pa(e,t)},isExported:!0},ka=La,Ua={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 Ba.compute.bind(this)(e,t)},isExported:!0},Ha={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:la([e],t,!1,this.locale),format:Vt(e)}},isExported:!0},Ba={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:la([e],t,!0,this.locale),format:Vt(e)}},isExported:!0},za={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."),ra),a("intercept (boolean, default=TRUE)",v("A flag specifying whether to compute the intercept or not."),oa)],compute:function(e,t,r,o={value:!0}){const{flatDataX:n,flatDataY:s}=sa(e,t);return 0===n.length||0===s.length?new x(wr):Xi(s,n,Ut(r,this.locale),Yt(o))},isExported:!1},$a={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."),ra),a("intercept (boolean, default=TRUE)",v("A flag specifying whether to compute the intercept or not."),oa)],compute:function(e,t,r,o,n={value:!0}){const s=Ut(o,this.locale),{flatDataX:i,flatDataY:a}=sa(t,r);if(0===i.length||0===a.length)return new x(wr);const l=Xi(a,i,s,Yt(n)).flat();return sr(br(e),e=>function(e,t,r){return e.reduce((e,o,n)=>e+o*Math.pow(t,r-n),0)}(l,Ut(e,this.locale),s))},isExported:!1},Ga={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."),na)],compute:function(e,t){return qa.compute.bind(this)(e,t)},isExported:!0},Wa={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:la([e],{value:.25*Math.trunc(Ut(t,this.locale))},!1,this.locale),format:Vt(e)}},isExported:!0},qa={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."),na)],compute:function(e,t){return{value:la([e],{value:.25*Math.trunc(Ut(t,this.locale))},!0,this.locale),format:Vt(e)}},isExported:!0},Za={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 o=Yt(r),n=Ut(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=Ut(t,this.locale);e===n?i=!0:e>n!==o&&s++}return i?s:new x(v("Value not found in the given data."))},isExported:!0},Ya={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=Pa(e,t);if(r instanceof Error)throw r;return Math.pow(r,2)},isExported:!0},ja={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:o}=sa(e,t);if(0===r.length||0===o.length)return new x(wr);const[[n]]=ji([r],[o]);return n},isExported:!0},Xa={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(Ut(t?.value,this.locale)),o=[];let n,s=0;Qt([e],e=>{"number"==typeof e?.value&&(n=fr(o,e,"nextSmaller","asc",o.length,(e,t)=>e[t].value),o.splice(n+1,0,e),s++,s>r&&(o.pop(),s--))});const i=o.pop();return void 0===i?new S(wr):s<r?new S(v("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",r)):i},isExported:!0},Ka={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:o}=sa(t,e);if(0===r.length||0===o.length)return new x(wr);const n=r.length,s=r.map((e,t)=>[e,o[t]]);s.sort((e,t)=>e[0]-t[0]);for(let e=0;e<n;++e)s[e][0]=e;s.sort((e,t)=>e[1]-t[1]);let i=0;for(let e=0;e<n;++e)i+=(s[e][0]-e)**2;return 1-6*i/(n**3-n)},isExported:!1},Qa={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(il.compute.bind(this)(...e))},isExported:!0},Ja={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(al.compute.bind(this)(...e))},isExported:!0},el={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(ll.compute.bind(this)(...e))},isExported:!0},tl={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(cl.compute.bind(this)(...e))},isExported:!0},rl={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(ul.compute.bind(this)(...e))},isExported:!0},ol={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(hl.compute.bind(this)(...e))},isExported:!0},nl={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:o}=sa(e,t);if(0===r.length||0===o.length)return new x(wr);return ji([r],[o],!0,!0)[1][2]},isExported:!0},sl={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."),ea)],compute:function(e,t=[[]],r=[[]],o={value:!0}){return 0===e.length||0===e[0].length?new S(Er("known_data_y")):Ji(Bt(e,"known_data_y"),Bt(t,"known_data_x"),Bt(r,"new_data_y"),Yt(o))}},il={description:v("Variance."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the sample."))],compute:function(...e){return aa(e,!0,!1,this.locale)},isExported:!0},al={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 aa(e,!1,!1,this.locale)},isExported:!0},ll={description:v("Variance."),args:[a("value (number, range<number>, repeating)",v("Value or range to include in the sample."))],compute:function(...e){return aa(e,!0,!1,this.locale)},isExported:!0},cl={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 aa(e,!0,!0,this.locale)},isExported:!0},ul={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 aa(e,!1,!1,this.locale)},isExported:!0},hl={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 aa(e,!1,!0,this.locale)},isExported:!0};var dl=Object.freeze({__proto__:null,AVEDEV:ca,AVERAGE:ua,AVERAGEA:ga,AVERAGEIF:ma,AVERAGEIFS:pa,AVERAGE_WEIGHTED:fa,CORREL:ka,COUNT:ba,COUNTA:va,COVAR:ya,COVARIANCE_P:wa,COVARIANCE_S:Ea,FORECAST:Sa,GROWTH:Ca,INTERCEPT:Ta,LARGE:Ia,LINEST:xa,LOGEST:Ra,MATTHEWS:Aa,MAX:Oa,MAXA:_a,MAXIFS:Fa,MEDIAN:Da,MIN:Na,MINA:Ma,MINIFS:Va,PEARSON:La,PERCENTILE:Ua,PERCENTILE_EXC:Ha,PERCENTILE_INC:Ba,POLYFIT_COEFFS:za,POLYFIT_FORECAST:$a,QUARTILE:Ga,QUARTILE_EXC:Wa,QUARTILE_INC:qa,RANK:Za,RSQ:Ya,SLOPE:ja,SMALL:Xa,SPEARMAN:Ka,STDEV:Qa,STDEVA:tl,STDEVP:rl,STDEVPA:ol,STDEV_P:Ja,STDEV_S:el,STEYX:nl,TREND:sl,VAR:il,VARA:cl,VARP:ul,VARPA:hl,VAR_P:al,VAR_S:ll});function fl(e,t,r,o){const n=new Map,s=e.length;for(let t=s-1;t>=0;t--)n.set(Wt(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=Wt(t).toUpperCase();if(a=n.get(e)??-1,-1===a)throw new S(v("The field (%s) must be one of %s.",Wt(t),[...n.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 o=0;o<r.length;o++){const a=Wt(r[o][0]).toUpperCase(),l=n.get(a),c=r[o][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}dr(s,(e,t)=>{c.add(t)},o,!0)}}const h=e[a];return[...c].map(e=>h[e+1])}const gl=[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."))],ml={description:v("Average of a set of values from a table-like range."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return ua.compute.bind(this)([o])},isExported:!0},pl={description:v("Counts values from a table-like range."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return ba.compute.bind(this)([o])},isExported:!0},bl={description:v("Counts values and text from a table-like range."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return va.compute.bind(this)([o])},isExported:!0},vl={description:v("Single value from a table-like range."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return 1!==o.length?new S(v("More than one match found in DGET evaluation.")):o[0]},isExported:!0},yl={description:v("Maximum of values from a table-like range."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return Oa.compute.bind(this)([o])},isExported:!0},wl={description:v("Minimum of values from a table-like range."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return Na.compute.bind(this)([o])},isExported:!0},El={description:v("Product of values from a table-like range."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return bi.compute.bind(this)([o])},isExported:!0},Sl={description:v("Standard deviation of population sample from table."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return Qa.compute.bind(this)([o])},isExported:!0},Cl={description:v("Standard deviation of entire population from table."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return rl.compute.bind(this)([o])},isExported:!0},Tl={description:v("Sum of values from a table-like range."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return Mi.compute.bind(this)([o])},isExported:!0},Il={description:v("Variance of population sample from table-like range."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return il.compute.bind(this)([o])},isExported:!0},xl={description:v("Variance of a population from a table-like range."),args:gl,compute:function(e,t,r){const o=fl(e,t,r,this.locale);return ul.compute.bind(this)([o])},isExported:!0};var Rl=Object.freeze({__proto__:null,DAVERAGE:ml,DCOUNT:pl,DCOUNTA:bl,DGET:vl,DMAX:yl,DMIN:wl,DPRODUCT:El,DSTDEV:Sl,DSTDEVP:Cl,DSUM:Tl,DVAR:Il,DVARP:xl});const Al=["%"],Ol="+,-,*,/,:,=,<>,>=,>,<=,<,^,&,#".split(",").concat(Al);function _l(e,t=Ar){e=Le(e);const r=new Ze(e),o=[],n=Me.test(e)?Wl:ql;for(;!r.isOver();){let e=Zl(r)||n(r)||Ll(r,t)||Pl(r,t)||Vl(r)||Nl(r)||Yl(r)||kl(r)||Bl(r)||Fl(r)||Hl(r,t)||Gl(r);e||(e={type:"UNKNOWN",value:r.shift()}),o.push(e)}return o}function Fl(e){return"?"===e.current?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const Dl={"(":{type:"LEFT_PAREN",value:"("},")":{type:"RIGHT_PAREN",value:")"}};function Nl(e){if("("===e.current||")"===e.current){const t=e.shift();return Dl[t]}return null}const Ml={"{":{type:"LEFT_BRACE",value:"{"},"}":{type:"RIGHT_BRACE",value:"}"}};function Vl(e){if("{"===e.current||"}"===e.current){const t=e.shift();return Ml[t]}return null}function Pl(e,t){if(e.current===t.formulaArgSeparator){return{type:"ARG_SEPARATOR",value:e.shift()}}return null}function Ll(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 Ol)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}const Ul=new Set("0123456789");function Hl(e,t){if(!Ul.has(e.current)&&e.current!==t.decimalSeparator)return null;const r=e.remaining().match(At(t.decimalSeparator));return r?(e.advanceBy(r[0].length),{type:"NUMBER",value:r[0]}):null}function Bl(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 zl=/\p{L}|\p{N}|_|\.|!|\$/u,$l=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$");function Gl(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&&($l.has(e.current)||e.current.match(zl));)t+=e.shift();if(t.length){const e=t;return wn.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function Wl(e){let t="";for(;" "===e.current||e.current&&e.current.match(Me);)t+=e.shift();return t?{type:"SPACE",value:t}:null}function ql(e){let t="";for(;" "===e.current;)t+=e.shift();return t?{type:"SPACE",value:t}:null}function Zl(e){let t=0;for(;e.current===Q;)t++,e.shift();return t?{type:"SPACE",value:Q.repeat(t)}:null}function Yl(e){return e.currentStartsWith(w.InvalidReference)?(e.advanceBy(w.InvalidReference.length),{type:"INVALID_REFERENCE",value:w.InvalidReference}):null}function jl(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{Qr(1,{locale:e,format:"#,##0.00"}),Qr(1,{locale:e,format:e.dateFormat}),Qr(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function Xl(e,t){return Ke(e)?function(e,t){return Jl(e.startsWith("+")?"="+e.slice(1):e,t,Ar)}(e,t):function(e,t){if("."===t.decimalSeparator||!_t(e,t))return e;t.thousandsSeparator&&(e=e.replaceAll(t.thousandsSeparator,""));return e.replace(t.decimalSeparator,".")}(e,t)}function Kl(e,t){return e.startsWith("=")?Ql(e,t):function(e,t){if(ft(e,Ar)){const r=Ut(e,Ar);let o=t.dateFormat;return Number.isInteger(r)||(o+=" "+t.timeFormat),Qr(r,{locale:t,format:o})}return function(e,t){if("."===t.decimalSeparator||!_t(e,Ar))return e;const r=lo(Ar);return e.replace(r,e=>e.replace(".",t.decimalSeparator))}(e,t)}(e,t)}function Ql(e,t){return Jl(e,Ar,t)}function Jl(e,t,r){if(t.formulaArgSeparator===r.formulaArgSeparator&&t.decimalSeparator===r.decimalSeparator)return e;const o=_l(e,t);let n="";for(const e of o)"NUMBER"===e.type?n+=e.value.replace(t.decimalSeparator,r.decimalSeparator):"ARG_SEPARATOR"===e.type?n+=r.formulaArgSeparator:"ARRAY_ROW_SEPARATOR"===e.type?n+=";"===r.formulaArgSeparator?"\\":";":n+=e.value;return n}function ec(e){return e.dateFormat+" "+e.timeFormat}const tc=v("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."),rc=v("There must be both positive and negative values in cashflow_amounts."),oc=e=>v("The cost (%s) must be positive or null.",e),nc=e=>v("The frequency (%s) must be one of %s",e,[1,2,4].toString()),sc=e=>v("The day_count_convention (%s) must be between 0 and 4 inclusive.",e),ic=e=>v("The depreciation factor (%s) must be strictly positive.",e),ac=e=>v("The discount (%s) must be strictly positive.",e),lc=e=>v("The discount (%s) must be smaller than 1.",e),cc=e=>v("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e),uc=(e,t)=>v("The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).",{first:e,last:t}),hc=e=>v("The first_period (%s) must be strictly positive.",e),dc=e=>v("The investment (%s) must be strictly positive.",e),fc=(e,t)=>v("The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).",{last:e,nPeriods:t}),gc=e=>v("The last_period (%s) must be strictly positive.",e),mc=e=>v("The life (%s) must be strictly positive.",e),pc=(e,t)=>v("The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).",{maturity:t,settlement:e}),bc=e=>v("The number_of_periods (%s) must be strictly positive.",e),vc=e=>v("The periods_by_year (%s) must be strictly positive.",e),yc=(e,t)=>v("The period (%(period)s) must be less than or equal life (%(life)s).",{period:e,life:t}),wc=e=>v("The period (%s) must be strictly positive.",e),Ec=e=>v("The present_value (%s) must be strictly positive.",e),Sc=e=>v("The price (%s) must be strictly positive.",e),Cc=e=>v("The rate_guess (%s) must be strictly greater than -1.",e),Tc=e=>v("The rate (%s) must be positive or null.",e),Ic=e=>v("The rate (%s) must be strictly positive.",e),xc=e=>v("The redemption (%s) must be strictly positive.",e),Rc=e=>v("The salvage (%s) must be positive or null.",e),Ac=(e,t)=>v("The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).",{settlement:e,maturity:t}),Oc=e=>v("The unit (%s) must be strictly positive.",e),_c=e=>v("The yield (%s) must be positive or null.",e);function Fc(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function Dc(e){return![0,1,2,3,4].includes(e)}function Nc(e){return![1,2,4].includes(e)}function Mc(e,t,r){const o=jt(e,r),n=jt(t,r),s=jt(e,r);return s.setFullYear(o.getFullYear()+1),n.getTime()<=s.getTime()}const Vc=[{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 Pc;!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"}(Pc||(Pc={}));const Lc={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 o=Math.trunc(Ut(e,this.locale));const n=Math.trunc(Ut(t,this.locale)),s=Math.trunc(Ut(r,this.locale));if(o<0||o>9999)return new S(v("The year (%s) must be between 0 and 9999 inclusive.",o.toString()));o<1900&&(o+=1900);const i=bt(new Je(o,n-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 o=Wt(r).toUpperCase();if(!Object.values(Pc).includes(o))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(Pc),Wt(r)));const n=Math.trunc(Ut(e,this.locale)),s=Math.trunc(Ut(t,this.locale)),i=pt(n),a=pt(s);if(s<n)return new S(v("start_date (%s) should be on or before end_date (%s).",i.toLocaleDateString(),a.toLocaleDateString()));switch(o){case Pc.WHOLE_YEARS:return xt(i,a);case Pc.WHOLE_MONTHS:return Tt(i,a);case Pc.WHOLE_DAYS:return It(i,a);case Pc.MONTH_WITHOUT_WHOLE_YEARS:return Tt(i,a)-12*xt(i,a);case Pc.DAYS_WITHOUT_WHOLE_MONTHS:let e=a.getDate()-i.getDate();if(e<0){e=yt(new Je(a.getFullYear(),a.getMonth()-1,1))-Math.abs(e)}return e;case Pc.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return Ct(e,t,1)<1}(n,s))return It(i,a);const e=new Je(i.getFullYear(),a.getMonth(),a.getDate());let t=It(i,e);return t<0&&(e.setFullYear(i.getFullYear()+1),t=It(i,e)),t}}},isExported:!0},Uc={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=Wt(e),r=mt(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},Hc={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 jt(e,this.locale).getDate()},isExported:!0},Bc={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=jt(e,this.locale),o=jt(t,this.locale),n=r.getTime()-o.getTime();return Math.round(n/tt)},isExported:!0},zc=!1,$c={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:zc}){const o=Math.trunc(Ut(e,this.locale)),n=Math.trunc(Ut(t,this.locale)),s=Ct(o,n,Yt(r)?4:0);return Math.sign(n-o)*Math.round(360*s)},isExported:!0},Gc={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:bt(Et(jt(e,this.locale),Math.trunc(Ut(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},Wc={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=jt(e,this.locale),o=Math.trunc(Ut(t,this.locale)),n=r.getFullYear(),s=r.getMonth();return{value:bt(new Je(n,s+o+1,0)),format:this.locale.dateFormat}},isExported:!0},qc={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 jt(e,this.locale).getHours()},isExported:!0},Zc={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=jt(e,this.locale),r=t.getFullYear();let o=1;for(;4!==new Je(r,0,o).getDay();)o+=1;const n=new Je(r,0,o-3);let s=31;for(;4!==new Je(r,11,s).getDay();)s-=1;const i=new Je(r,11,s+3);let a,l;switch(a=n.getTime()<=t.getTime()?t.getTime()<=i.getTime()?0:1:-1,a){case 0:l=n;break;case 1:l=new Je(r,11,s+3+1);break;case-1:let e=1;for(;4!==new Je(r-1,0,e).getDay();)e+=1;l=new Je(r-1,0,e-3)}const c=(t.getTime()-l.getTime())/tt;return Math.floor(c/7)+1},isExported:!0},Yc={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 jt(e,this.locale).getMinutes()},isExported:!0},jc={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 jt(e,this.locale).getMonth()+1},isExported:!0},Xc={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 Jc.compute.bind(this)(e,t,{value:1},r)},isExported:!0};function Kc(e){const t=e?.value;if("string"==typeof t){Eo(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 Eo(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 Qc=[{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")}],Jc={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."),Qc),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},o){const n=jt(e,this.locale),s=jt(t,this.locale),i=Kc(r),a=new Set;void 0!==o&&Qt([o],e=>{const t=jt(e,this.locale);a.add(t.getTime())});const l=n.getTime()>s.getTime(),c=Je.fromTimestamp((l?n:s).getTime()),u=Je.fromTimestamp((l?s:n).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},eu={description:v("Current date and time as a date value."),args:[],compute:function(){const e=Je.now(),t=e.getTime()-et.getTime(),r=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/tt)+r,format:ec(this.locale)}},isExported:!0},tu={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 jt(e,this.locale).getSeconds()},isExported:!0},ru={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 o=Math.trunc(Ut(e,this.locale)),n=Math.trunc(Ut(t,this.locale)),s=Math.trunc(Ut(r,this.locale));return n+=Math.floor(s/60),s=s%60+(s<0?60:0),o+=Math.floor(n/60),n=n%60+(n<0?60:0),o%=24,o<0?new S(v("The function [[FUNCTION_NAME]] result cannot be negative")):{value:o/24+n/1440+s/86400,format:this.locale.timeFormat}},isExported:!0},ou={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=Wt(e),r=mt(t,this.locale);if(null===r)return new S(v("The time_string (%s) cannot be parsed to date/time.",t));const o=r.value-Math.trunc(r.value);return o<0?1+o:o},isExported:!0},nu={description:v("Current date as a date value."),args:[],compute:function(){const e=Je.now();return{value:bt(new Je(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},su={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=jt(e,this.locale),o=Math.round(Ut(t,this.locale)),n=r.getDay();if(!(1<=o&&o<=3||11<=o&&o<=17))return new S(v("The type (%s) must be between 1 and 3 or between 11 and 17.",o));switch(o){case 1:return n+1;case 2:return 0===n?7:n;case 3:return 0===n?6:n-1}const s=(n+1-(o-10)+7)%7;return 0===s?7:s},isExported:!0},iu={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=jt(e,this.locale),o=Math.round(Ut(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(o))return new S(v("The type (%s) is out of range.",o.toString()));if(21===o)return Zc.compute.bind(this)(e);let n;n=1===o||2===o?o-1:o-10==7?0:o-10;const s=r.getFullYear();let i=1,a=new Je(s,0,i);for(;a.getDay()!==n;)i+=1,a=new Je(s,0,i);const l=(r.getTime()-a.getTime())/tt;return l<0?1:Math.floor(l/7)+(1===i?1:2)},isExported:!0},au={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 lu.compute.bind(this)(e,t,{value:1},r)},isExported:!0},lu={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."),Qc),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},o){const n=jt(e,this.locale),s=Math.trunc(Ut(t,this.locale));if("1111111"===r.value)return new S(v("The weekend must be different from '1111111'."));const i=Kc(r),a=new Set;void 0!==o&&Qt([o],e=>{const t=jt(e,this.locale);a.add(t.getTime())});const l=Je.fromTimestamp(n.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-et.getTime();return{value:Math.round(d/tt),format:this.locale.dateFormat}},isExported:!0},cu={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 jt(e,this.locale).getFullYear()},isExported:!0},uu={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."),Vc)],compute:function(e,t,r={value:0}){const o=Math.trunc(Ut(e,this.locale)),n=Math.trunc(Ut(t,this.locale)),s=Math.trunc(Ut(r,this.locale));return o<0?new S(v("The start_date (%s) must be positive or null.",o)):n<0?new S(v("The end_date (%s) must be positive or null.",n)):0>s||s>4?new S(v("The day_count_convention (%s) must be between 0 and 4 inclusive.",s)):Ct(o,n,s)}},hu={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=jt(e,this.locale),r=t.getFullYear(),o=t.getMonth();return{value:bt(new Je(r,o,1)),format:this.locale.dateFormat}}},du={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 Wc.compute.bind(this)(e,{value:0})}},fu={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((jt(e,this.locale).getMonth()+1)/3)}},gu={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=fu.compute.bind(this)(e),r=cu.compute.bind(this)(e);return{value:bt(new Je(r,3*(t-1),1)),format:this.locale.dateFormat}}},mu={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=fu.compute.bind(this)(e),r=cu.compute.bind(this)(e);return{value:bt(new Je(r,3*t,0)),format:this.locale.dateFormat}}},pu={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=cu.compute.bind(this)(e);return{value:bt(new Je(t,0,1)),format:this.locale.dateFormat}}},bu={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=cu.compute.bind(this)(e);return{value:bt(new Je(t+1,0,0)),format:this.locale.dateFormat}}};var vu=Object.freeze({__proto__:null,DATE:Lc,DATEDIF:kc,DATEVALUE:Uc,DAY:Hc,DAYS:Bc,DAYS360:$c,EDATE:Gc,EOMONTH:Wc,HOUR:qc,ISOWEEKNUM:Zc,MINUTE:Yc,MONTH:jc,MONTH_END:du,MONTH_START:hu,NETWORKDAYS:Xc,NETWORKDAYS_INTL:Jc,NOW:eu,QUARTER:fu,QUARTER_END:mu,QUARTER_START:gu,SECOND:tu,TIME:ru,TIMEVALUE:ou,TODAY:nu,WEEKDAY:su,WEEKNUM:iu,WORKDAY:au,WORKDAY_INTL:lu,YEAR:cu,YEARFRAC:uu,YEAR_END:bu,YEAR_START:pu});const yu={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 Ut(e,this.locale)===Ut(t,this.locale)?1:0},isExported:!0};var wu,Eu=Object.freeze({__proto__:null,DELTA:yu});!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(wu||(wu={}));const Su=[wu.number,wu.error,wu.text,wu.boolean];function Cu(e){const t="asc"===e?1:-1;return(e,r)=>{if(e.type===wu.empty)return r.type===wu.empty?0:1;if(r.type===wu.empty)return-1;let o=Su.indexOf(e.type)-Su.indexOf(r.type);return 0===o&&(o=e.type===wu.text||e.type===wu.error?e.value.localeCompare(r.value):e.value-r.value),t*o}}function Tu(e,t,...r){for(let e=0;e<r.length;e++){const t=e%2==0?"sort_column":"is_ascending";Eo(void 0!==r[e],v("Value for parameter %s is missing in [[FUNCTION_NAME]].",t))}const o=[],n=[],s=e.length;for(let i=0;i<r.length;i+=2){o.push(Yt(Fo(r[i+1])?.value)?"asc":"desc");const a=r[i];if(F(a)&&(a.length>1||a[0].length>1))Eo(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)),n.push(a.flat().map(e=>e.value));else{const r=Ut(Fo(a)?.value,t);if(r<1||r>e[0].length)return e;n.push(e.map(e=>e[r-1].value))}}if(0===n.length)for(let t=0;t<e[0].length;t++)n.push(e.map(e=>e[t].value)),o.push("asc");const i={desc:Cu("desc"),asc:Cu("asc")},a=le(0,e.length);return a.sort((e,t)=>{for(const[r,s]of n.entries()){const n=s[e],a=s[t],l={value:n,type:null===n?wu.empty:"string"==typeof n?wu.text:typeof n},c={value:a,type:null===a?wu.empty:"string"==typeof a?wu.text:typeof a},u=i[o[r]](l,c);if(0!==u)return u}return 0}),a.map(t=>e[t])}const Iu={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=br(e);const o=t.map(e=>sr(br(e),e=>e.value));for(const e of o)if(!Co(e))return new S(v("The arguments condition must be a single column or row."));if(!To(...t))return new S(v("The arguments conditions must have the same dimensions."));const n=o.map(e=>e.flat()),s=1===o[0].length?"row":"col";if(r="row"===s?ir(r):r,n.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];n.every(t=>("boolean"==typeof t[e]||"number"==typeof t[e])&&t[e])&&i.push(t)}return i.length?"row"===s?ir(i):i:new x(v("No match found in FILTER evaluation"))},isExported:!1},xu={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=ir(e);return ir(Tu(r,this.locale,...t))},isExported:!0},Ru={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 o=Ut(t?.value??1,this.locale),n=r.length%2==0?0:Ut(r[0]?.value,this.locale),s=r.length%2==0?r:r.slice(1);if(o<0)return new S(v("Wrong value of 'n'. Expected a positive number. Got %s.",o));if(n<0||n>3)return new S(v("Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.",n));const i=Tu(ir(e),this.locale,...s),a=(e,t)=>JSON.stringify(i[e].map(e=>e.value))===JSON.stringify(i[t].map(e=>e.value));switch(n){case 0:return ir(i.slice(0,o));case 1:for(let e=o;e<i.length;e++)if(!a(e,o-1))return ir(i.slice(0,e));return ir(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 ir(e.slice(0,o))}case 3:{const e=[i[0]];let t=1;for(let r=1;r<i.length&&(a(r,r-1)||t++,!(t>o));r++)e.push(i[r]);return ir(e)}}},isExported:!1},Au={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(!F(e))return[[e]];const o=Yt(t?.value)||!1,n=Yt(r?.value)||!1;o||(e=ir(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())n&&e.count>1||i.push(e.data);return i.length?o?i:ir(i):new S(v("No unique values found"))},isExported:!0};var Ou=Object.freeze({__proto__:null,FILTER:Iu,SORT:xu,SORTN:Ru,UNIQUE:Au});const _u=[{value:1,label:v("Annual")},{value:2,label:v("Semi-annual")},{value:4,label:v("Quarterly")}],Fu=[{value:0,label:v("End of period (default)")},{value:1,label:v("Beginning of period")}],Du=[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."),Vc)];function Nu(e,t,r,o,n=1e-10,s){let i,a,l,c,u=r,h=!1,d=0;do{l=e(u),isNaN(l)?(Eo(d<o&&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<n||Math.abs(l)<n,Eo(d<o,v("Function [[FUNCTION_NAME]] didn't find any result.")),d++)}while(!h);return u}const Mu={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."),Vc)],compute:function(e,t,r,o,n={value:0}){const s=Math.trunc(Ut(e,this.locale)),i=Math.trunc(Ut(t,this.locale)),a=Ut(o,this.locale),l=Ut(r,this.locale),c=Math.trunc(Ut(n,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(pc(s,i));if(Dc(c))return new S(sc(c));if(a<=0)return new S(xc(a));if(l<=0)return new S(Ic(l));return a*l*Ct(s,i,c)},isExported:!0},Vu={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."),Vc)],compute:function(e,t,r,o,n,s,i={value:0}){i=i||0;const a=Ut(e,this.locale),l=Math.trunc(Ut(t,this.locale)),c=Math.trunc(Ut(r,this.locale)),u=Ut(o,this.locale),h=Ut(n,this.locale),d=Ut(s,this.locale),f=Math.trunc(Ut(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(Rc(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(Ic(d));if(Dc(f))return new S(sc(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=Ct(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},Pu={description:v("Days in coupon period containing settlement date."),args:Du,compute:function(e,t,r,o={value:0}){o=o||0;const n=Math.trunc(Ut(e,this.locale)),s=Math.trunc(Ut(t,this.locale)),i=Math.trunc(Ut(r,this.locale)),a=Math.trunc(Ut(o,this.locale));if(n>=s)return new S(pc(n,s));if(Nc(i))return new S(nc(i));if(Dc(a))return new S(sc(a));if(1===a){const n=Bu.compute.bind(this)(e,t,r,o).value;return Ut(Uu.compute.bind(this)(e,t,r,o).value,this.locale)-Ut(n,this.locale)}return(3===a?365:360)/i},isExported:!0},Lu={description:v("Days from settlement until next coupon."),args:Du,compute:function(e,t,r,o={value:0}){o=o||0;const n=Math.trunc(Ut(e,this.locale)),s=Math.trunc(Ut(t,this.locale)),i=Math.trunc(Ut(r,this.locale)),a=Math.trunc(Ut(o,this.locale));if(n>=s)return new S(pc(n,s));if(Nc(i))return new S(nc(i));if(Dc(a))return new S(sc(a));const l=Ut(Bu.compute.bind(this)(e,t,r,o).value,this.locale);if([1,2,3].includes(a))return n-l;if(4===a){const e=Ct(l,n,a);return Math.round(360*e)}const c=jt(n,this.locale),u=jt(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&&wt(u)&&wt(c)&&(p=30),31!==p||30!==m&&31!==m||(p=30),2===f&&wt(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:Du,compute:function(e,t,r,o={value:0}){o=o||0;const n=Math.trunc(Ut(e,this.locale)),s=Math.trunc(Ut(t,this.locale)),i=Math.trunc(Ut(r,this.locale)),a=Math.trunc(Ut(o,this.locale));if(n>=s)return new S(pc(n,s));if(Nc(i))return new S(nc(i));if(Dc(a))return new S(sc(a));const l=Ut(Uu.compute.bind(this)(e,t,r,o).value,this.locale);if([1,2,3].includes(a))return l-n;if(4===a){const e=Ct(n,l,a);return Math.round(360*e)}const c=Lu.compute.bind(this)(e,t,r,o);return Ut(Pu.compute.bind(this)(e,t,r,o),this.locale)-Ut(c,this.locale)},isExported:!0},Uu={description:v("Next coupon date after the settlement date."),args:Du,compute:function(e,t,r,o={value:0}){o=o||0;const n=Math.trunc(Ut(e,this.locale)),s=Math.trunc(Ut(t,this.locale)),i=Math.trunc(Ut(r,this.locale)),a=Math.trunc(Ut(o,this.locale));if(n>=s)return new S(pc(n,s));if(Nc(i))return new S(nc(i));if(Dc(a))return new S(sc(a));const l=12/i,c=Hu.compute.bind(this)(e,t,r,o);return{value:bt(Et(jt(s,this.locale),-(Ut(c,this.locale)-1)*l,!0)),format:this.locale.dateFormat}},isExported:!0},Hu={description:v("Number of coupons between settlement and maturity."),args:Du,compute:function(e,t,r,o={value:0}){o=o||0;const n=Math.trunc(Ut(e,this.locale)),s=Math.trunc(Ut(t,this.locale)),i=Math.trunc(Ut(r,this.locale)),a=Math.trunc(Ut(o,this.locale));if(n>=s)return new S(pc(n,s));if(Nc(i))return new S(nc(i));if(Dc(a))return new S(sc(a));let l=1,c=s;const u=12/i;for(;c>n;)c=bt(Et(jt(c,this.locale),-u,!1)),l++;return l-1},isExported:!0},Bu={description:v("Last coupon date prior to or on the settlement date."),args:Du,compute:function(e,t,r,o={value:0}){o=o||0;const n=Math.trunc(Ut(e,this.locale)),s=Math.trunc(Ut(t,this.locale)),i=Math.trunc(Ut(r,this.locale)),a=Math.trunc(Ut(o,this.locale));if(n>=s)return new S(pc(n,s));if(Nc(i))return new S(nc(i));if(Dc(a))return new S(sc(a));const l=12/i,c=Hu.compute.bind(this)(e,t,r,o);return{value:bt(Et(jt(s,this.locale),-c*l,!0)),format:this.locale.dateFormat}},isExported:!0},zu={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."),Fu)],compute:function(e,t,r,o,n,s={value:0}){const i=Ut(o,this.locale),a=Ut(n,this.locale),l=Ut(e,this.locale),c=Ut(r,this.locale),u=Ut(t,this.locale),h=Yt(s)?1:0;if(u<=0)return new S(bc(u));if(i<=0)return new S(hc(i));if(a<=0)return new S(gc(a));if(i>a)return new S(uc(i,a));if(a>u)return new S(fc(a,u));if(l<=0)return new S(Ic(l));if(c<=0)return new S(Ec(c));let d=0;for(let e=i;e<=a;e++)d+=rh(l,e,u,c,0,h);return d},isExported:!0},$u={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."),Fu)],compute:function(e,t,r,o,n,s={value:0}){const i=Ut(o,this.locale),a=Ut(n,this.locale),l=Ut(e,this.locale),c=Ut(r,this.locale),u=Ut(t,this.locale),h=Yt(s)?1:0;if(u<=0)return new S(bc(u));if(i<=0)return new S(hc(i));if(a<=0)return new S(gc(a));if(i>a)return new S(uc(i,a));if(a>u)return new S(fc(a,u));if(l<=0)return new S(Ic(l));if(c<=0)return new S(Ec(c));let d=0;for(let e=i;e<=a;e++)d+=mh(l,e,u,c,0,h);return d},isExported:!0},Gu={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,o,...n){const s=Ut(e,this.locale),i=Ut(t,this.locale),a=Ut(r,this.locale),l=Math.trunc(Ut(o,this.locale)),c=n.length?Math.trunc(Ut(n[0],this.locale)):12,u=a+(12===c?0:1);if(s<0)return new S(oc(s));if(i<0)return new S(Rc(i));if(l<=0)return new S(wc(l));if(a<=0)return new S(mc(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},Wu="#,##0.00",qu={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,o,n={value:2}){const s=Ut(e,this.locale),i=Ut(t,this.locale),a=Ut(r,this.locale),l=Ut(o,this.locale),c=Ut(n,this.locale);if(s<0)return new S(oc(s));if(i<0)return new S(Rc(i));if(l<=0)return new S(wc(l));if(a<=0)return new S(mc(a));if(l>a)return new S(yc(l,a));if(c<=0)return new S(ic(c));if(0===s||i>=s)return{value:0,format:Wu};const u=c/a;if(u>1)return{value:1===l?s-i:0,format:Wu};if(l<=1)return{value:s*u,format:Wu};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:Wu}},isExported:!0},Zu={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."),Vc)],compute:function(e,t,r,o,n={value:0}){n=n||0;const s=Math.trunc(Ut(e,this.locale)),i=Math.trunc(Ut(t,this.locale)),a=Ut(r,this.locale),l=Ut(o,this.locale),c=Math.trunc(Ut(n,this.locale));if(s>=i)return new S(pc(s,i));if(Dc(c))return new S(sc(c));if(a<=0)return new S(Sc(a));if(l<=0)return new S(xc(l));return(l-a)/l/Ct(s,i,c)},isExported:!0},Yu={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=Ut(e,this.locale),o=Math.trunc(Ut(t,this.locale));if(o<=0)return new S(Oc(o));const n=Math.trunc(r);return n+(r-n)*(10**Math.ceil(Math.log10(o))/o)},isExported:!0},ju={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=Ut(e,this.locale),o=Math.trunc(Ut(t,this.locale));if(o<=0)return new S(Oc(o));const n=Math.trunc(r);return n+(r-n)*(o/10**Math.ceil(Math.log10(o)))},isExported:!0},Xu={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."),Vc)],compute:function(e,t,r,o,n,s={value:0}){const i=Math.trunc(Ut(e,this.locale)),a=Math.trunc(Ut(t,this.locale)),l=Ut(r,this.locale),c=Ut(o,this.locale),u=Math.trunc(Ut(n,this.locale)),h=Math.trunc(Ut(s,this.locale));if(i>=a)return new S(pc(i,a));if(Nc(u))return new S(nc(u));if(Dc(h))return new S(sc(h));if(l<0)return new S(Tc(l));if(c<0)return new S(_c(c));const d=Ct(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},Ku={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=Ut(e,this.locale),o=Math.trunc(Ut(t,this.locale));return r<=0?new S(v("The nominal_rate (%s) must be strictly positive.",r)):o<=0?new S(vc(o)):Math.pow(1+r/o,o)-1},isExported:!0};function Qu(e,t,r,o,n){return 0===e?-(o+r*t):-o*(1+e)**t-r*(1+e*n)*((1+e)**t-1)/e}const Ju={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."),Fu)],compute:function(e,t,r,o={value:0},n={value:0}){o=o||0,n=n||0;return{value:Qu(Ut(e,this.locale),Ut(t,this.locale),Ut(r,this.locale),Ut(o,this.locale),Yt(n)?1:0),format:"#,##0.00"}},isExported:!0},eh={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 tr([t],(e,t)=>e*(1+Ut(t,this.locale)),Ut(e,this.locale))},isExported:!0},th={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."),Vc)],compute:function(e,t,r,o,n={value:0}){const s=Math.trunc(Ut(e,this.locale)),i=Math.trunc(Ut(t,this.locale)),a=Ut(o,this.locale),l=Ut(r,this.locale),c=Math.trunc(Ut(n,this.locale));if(s>=i)return new S(pc(s,i));if(l<=0)return new S(dc(l));if(a<=0)return new S(xc(a));if(Dc(c))return new S(sc(c));return(a-l)/l/Ct(s,i,c)},isExported:!0};function rh(e,t,r,o,n,s){return fh(e,r,o,n,s)-mh(e,t,r,o,n,s)}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."),Fu)],compute:function(e,t,r,o,n={value:0},s={value:0}){return{value:rh(Ut(e,this.locale),Ut(t,this.locale),Ut(r,this.locale),Ut(o,this.locale),Ut(n,this.locale),Yt(s)?1:0),format:"#,##0.00"}},isExported:!0},nh={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=Ut(t,this.locale);if(r<=-1)return new S(Cc(r));let o=!1,n=!1;const s=[];if(Jt([e],({value:e})=>{e>0&&(o=!0),e<0&&(n=!0),s.push(e)},this.locale),!o||!n)return new S(rc);const i=s.shift();return{value:Nu(function(e){return function(e,t,r){const o=r.length;let n=0;return r.reduce((t,r)=>(n++,t+r*e**(o-n)),t*e**o)}(e,i,s)},function(e){return function(e,t,r){const o=r.length;let n=0;return r.reduce((t,r)=>(n++,t+r*(o-n)*e**(o-n-1)),t*o*e**(o-1))}(e,i,s)},r+1,20,1e-5)-1,format:"0%"}},isExported:!0},sh={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,o){const n=Ut(e,this.locale),s=Ut(t,this.locale),i=Ut(r,this.locale),a=Ut(o,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))*n},isExported:!0},ih={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,o,n,s={value:0}){const i=Xu.compute.bind(this)(e,t,r,o,n,s),a=Ut(o,this.locale),l=Math.trunc(Ut(n,this.locale));return Ut(i,this.locale)/(1+a/l)},isExported:!0},ah={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 o=Ut(t,this.locale),n=Ut(r,this.locale),s=ir(e).flat().filter(e=>null!==e.value).map(e=>Ut(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*(n+1)**(i-e-1):l+=t/(o+1)**e}if(0===l||0===a)return new S(rc);return(-a/l)**(1/(i-1))-1},isExported:!0},lh={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=Ut(e,this.locale),o=Math.trunc(Ut(t,this.locale));return r<=0?new S(v("The effective_rate (%s) must be strictly positive.",r)):o<=0?new S(vc(o)):(Math.pow(r+1,1/o)-1)*o},isExported:!0},ch={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."),Fu)],compute:function(e,t,r,o={value:0},n={value:0}){o=o||0,n=n||0;const s=Ut(e,this.locale),i=Ut(t,this.locale),a=Ut(r,this.locale),l=Ut(o,this.locale),c=Yt(n)?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 uh(e,t,r,o){let n=0;return rr(r,(t,r)=>(n++,t+r/(1+e)**n),t,o)}const hh={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=Ut(e,this.locale);return-1===r?new S((e=>v("The discount (%s) must be different from -1.",e))(r)):{value:uh(r,0,t,this.locale),format:"#,##0.00"}},isExported:!0},dh={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 o=Ut(e,this.locale),n=Ut(t,this.locale),s=Ut(r,this.locale);return o<=0?new S(Ic(o)):n<=0?new S(Ec(n)):s<=0?new S(v("The future_value (%s) must be strictly positive.",s)):(Math.log(s)-Math.log(n))/Math.log(1+o)},isExported:!0};function fh(e,t,r,o,n){if(t<=0)throw new S(bc(t));if(0===e)return-(o+r)/t;let s=-(r*(1+e)**t+o);return s=s*e/((1+e*n)*((1+e)**t-1)),s}const gh={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."),Fu)],compute:function(e,t,r,o={value:0},n={value:0}){const s=Ut(t,this.locale),i=Ut(e,this.locale),a=Yt(n)?1:0,l=Ut(o,this.locale);return{value:fh(i,s,Ut(r,this.locale),l,a),format:"#,##0.00"}},isExported:!0};function mh(e,t,r,o,n,s){if(r<=0)throw new S(bc(r));if(t<=0||t>r)throw new S(v("The period must be between 1 and number_of_periods (%s)",r));const i=fh(e,r,o,n,s);if(1===s&&1===t)return i;return i+-Qu(e,0===s?t-1:t-2,i,o+i*s,0)*e}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."),Fu)],compute:function(e,t,r,o,n={value:0},s={value:0}){const i=Ut(r,this.locale),a=Ut(e,this.locale),l=Ut(t,this.locale),c=Yt(s)?1:0,u=Ut(n,this.locale);return{value:mh(a,l,i,Ut(o,this.locale),u,c),format:"#,##0.00"}},isExported:!0},bh={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."),Fu)],compute:function(e,t,r,o={value:0},n={value:0}){o=o||0,n=n||0;const s=Ut(e,this.locale),i=Ut(t,this.locale),a=Ut(r,this.locale),l=Ut(o,this.locale),c=Yt(n)?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},vh={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."),Vc)],compute:function(e,t,r,o,n,s,i={value:0}){i=i||0;const a=Math.trunc(Ut(e,this.locale)),l=Math.trunc(Ut(t,this.locale)),c=Ut(r,this.locale),u=Ut(o,this.locale),h=Ut(n,this.locale),d=Math.trunc(Ut(s,this.locale)),f=Math.trunc(Ut(i,this.locale));if(a>=l)return new S(pc(a,l));if(Nc(d))return new S(nc(d));if(Dc(f))return new S(sc(f));if(c<0)return new S(Tc(c));if(u<0)return new S(_c(u));if(h<=0)return new S(xc(h));const g=Ct(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},yh={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."),Vc)],compute:function(e,t,r,o,n={value:0}){n=n||0;const s=Math.trunc(Ut(e,this.locale)),i=Math.trunc(Ut(t,this.locale)),a=Ut(r,this.locale),l=Ut(o,this.locale),c=Math.trunc(Ut(n,this.locale));if(s>=i)return new S(pc(s,i));if(Dc(c))return new S(sc(c));if(a<=0)return new S(ac(a));if(l<=0)return new S(xc(l));return l-a*l*Ct(s,i,c)},isExported:!0},wh={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."),Vc)],compute:function(e,t,r,o,n,s={value:0}){s=s||0;const i=Math.trunc(Ut(e,this.locale)),a=Math.trunc(Ut(t,this.locale)),l=Math.trunc(Ut(r,this.locale)),c=Ut(o,this.locale),u=Ut(n,this.locale),h=Math.trunc(Ut(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(pc(i,a));if(Dc(h))return new S(sc(h));if(c<0)return new S(Tc(c));if(u<0)return new S(_c(u));const d=Ct(i,a,h),f=Ct(i,l,h);return(100+Ct(l,a,h)*c*100)/(1+d*u)-f*c*100},isExported:!0},Eh=.1,Sh={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."),Fu),a("rate_guess (number, default=0.1)",v("An estimate for what the interest rate will be."))],compute:function(e,t,r,o={value:0},n={value:0},s={value:Eh}){const i=Ut(e,this.locale),a=Ut(t,this.locale),l=Yt(n)?1:0,c=Ut(s,this.locale)||Eh;let u=Ut(o,this.locale),h=Ut(r,this.locale);if(i<=0)return new S(bc(i));if(!Fc([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(Cc(c));u-=a*l,h+=a*l;return{value:Nu(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},Ch={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."),Vc)],compute:function(e,t,r,o,n={value:0}){n=n||0;const s=Math.trunc(Ut(e,this.locale)),i=Math.trunc(Ut(t,this.locale)),a=Ut(r,this.locale),l=Ut(o,this.locale),c=Math.trunc(Ut(n,this.locale));if(s>=i)return new S(pc(s,i));if(Dc(c))return new S(sc(c));if(a<=0)return new S(dc(a));if(l<=0)return new S(ac(l));return a/(1-l*Ct(s,i,c))},isExported:!0},Th={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 o=Ut(e,this.locale),n=Ut(t,this.locale),s=Ut(r,this.locale);return o<=0?new S(bc(o)):(s/n)**(1/o)-1},isExported:!0},Ih={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:(Ut(e,this.locale)-Ut(t,this.locale))/Ut(r,this.locale),format:"#,##0.00"}},isExported:!0},xh={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,o){const n=Ut(e,this.locale),s=Ut(t,this.locale),i=Ut(r,this.locale),a=Ut(o,this.locale);if(a<=0)return new S(wc(a));if(i<=0)return new S(mc(i));if(a>i)return new S(yc(a,i));return{value:(i-a+1)/(i*(i+1)/2)*(n-s),format:"#,##0.00"}},isExported:!0};function Rh(e,t,r){return 100*(1-r*Ct(e,t,2))}const Ah={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 o=Math.trunc(Ut(e,this.locale)),n=Math.trunc(Ut(t,this.locale)),s=Ut(r,this.locale);return o>=n?new S(pc(o,n)):Mc(o,n,this.locale)?s<=0?new S(ac(s)):s>=1?new S(lc(s)):Rh(o,n,s):new S(Ac(o,n))},isExported:!0},Oh={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 o=Math.trunc(Ut(e,this.locale)),n=Math.trunc(Ut(t,this.locale)),s=Ut(r,this.locale);if(o>=n)return new S(pc(o,n));if(!Mc(o,n,this.locale))return new S(Ac(o,n));if(s<=0)return new S(ac(s));if(s>=1)return new S(lc(s));const i=Bc.compute.bind(this)({value:n},{value:o});if(i<=182)return 365*s/(360-s*i);const a=Rh(o,n,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 o=Math.trunc(Ut(e,this.locale)),n=Math.trunc(Ut(t,this.locale)),s=Ut(r,this.locale);if(o>=n)return new S(pc(o,n));if(!Mc(o,n,this.locale))return new S(Ac(o,n));if(s<=0)return new S(Sc(s));return(100-s)/s*(1/Ct(o,n,2))},isExported:!0},Fh=!1,Dh={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,o,n,s={value:2},i={value:Fh}){s=s||0;const a=Ut(e,this.locale),l=Ut(t,this.locale),c=Ut(r,this.locale),u=Math.trunc(Ut(o,this.locale)),h=Math.trunc(Ut(n,this.locale)),d=Ut(s,this.locale),f=Yt(i);if(a<0)return new S(oc(a));if(l<0)return new S(Rc(l));if(c<=0)return new S(mc(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(ic(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},Nh={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:Eh}){const o=Ut(r,this.locale);if(!To(e,t))return new S(tc);const n=e.flat().map(e=>Ut(e,this.locale)),s=t.flat().map(e=>Ut(e,this.locale));if(!Fc(n))return new S(rc);if(s.some(e=>e<s[0]))return new S(cc(s[0]));if(o<=-1)return new S(Cc(o));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)+n[e]):i.set(t,n[e])}const a=Array.from(i.keys()),l=a.map(e=>i.get(e));return Nu(e=>{let t=l[0];for(const r of le(1,l.length)){const o=(a[0]-a[r])/365;t+=l[r]*(1+e)**o}return t},e=>{let t=0;for(const r of le(1,l.length)){const o=(a[0]-a[r])/365;t+=o*l[r]*(1+e)**(o-1)}return t},o,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},Mh={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 o=Ut(e,this.locale);if(!To(t,r))return new S(tc);const n=br(t).flat().map(e=>zt(e,this.locale)),s=br(r).flat().map(e=>zt(e,this.locale));if(s.some(e=>e<s[0]))return new S(cc(s[0]));if(o<=0)return new S(Ic(o));if(1===n.length)return n[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)+n[e]):i.set(t,n[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+o)**t}return c},isExported:!0},Vh={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."),Vc)],compute:function(e,t,r,o,n,s,i={value:0}){i=i||0;const a=Math.trunc(Ut(e,this.locale)),l=Math.trunc(Ut(t,this.locale)),c=Ut(r,this.locale),u=Ut(o,this.locale),h=Ut(n,this.locale),d=Math.trunc(Ut(s,this.locale)),f=Math.trunc(Ut(i,this.locale));if(a>=l)return new S(pc(a,l));if(Nc(d))return new S(nc(d));if(Dc(f))return new S(sc(f));if(c<0)return new S(Tc(c));if(u<=0)return new S(Sc(u));if(h<=0)return new S(xc(h));const g=Ct(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=Nu(function(e){return function(e,t,r,o,n,s){let i=s-(e+n*(1-t))*o**(r-1+t);for(let e=1;e<=r;e++)i+=n*o**(e-1);return i}(u,p,m,e,b,h)},function(e){return function(e,t,r,o,n){let s=-(e+n*(1-t))*(r-1+t)*o**(r-2+t);for(let e=1;e<=r;e++)s+=n*(e-1)*o**(e-2);return s}(u,p,m,e,b)},1+(c+1)/d,100,1e-5);return(v-1)*d},isExported:!0},Ph={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."),Vc)],compute:function(e,t,r,o,n={value:0}){n=n||0;const s=Math.trunc(Ut(e,this.locale)),i=Math.trunc(Ut(t,this.locale)),a=Ut(r,this.locale),l=Ut(o,this.locale),c=Math.trunc(Ut(n,this.locale));if(s>=i)return new S(pc(s,i));if(Dc(c))return new S(sc(c));if(a<=0)return new S(Sc(a));if(l<=0)return new S(xc(l));return(l/a-1)/Ct(s,i,c)},isExported:!0},Lh={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."),Vc)],compute:function(e,t,r,o,n,s={value:0}){s=s||0;const i=Math.trunc(Ut(e,this.locale)),a=Math.trunc(Ut(t,this.locale)),l=Math.trunc(Ut(r,this.locale)),c=Ut(o,this.locale),u=Ut(n,this.locale),h=Math.trunc(Ut(s,this.locale));if(i>=a)return new S(pc(i,a));if(Dc(h))return new S(sc(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(Tc(c));if(u<=0)return new S(Sc(u));return(100*(1+c*Ct(l,a,h))/(u+100*c*Ct(l,i,h))-1)/Ct(i,a,h)},isExported:!0};var kh=Object.freeze({__proto__:null,ACCRINTM:Mu,AMORLINC:Vu,COUPDAYBS:Lu,COUPDAYS:Pu,COUPDAYSNC:ku,COUPNCD:Uu,COUPNUM:Hu,COUPPCD:Bu,CUMIPMT:zu,CUMPRINC:$u,DB:Gu,DDB:qu,DISC:Zu,DOLLARDE:Yu,DOLLARFR:ju,DURATION:Xu,EFFECT:Ku,FV:Ju,FVSCHEDULE:eh,INTRATE:th,IPMT:oh,IRR:nh,ISPMT:sh,MDURATION:ih,MIRR:ah,NOMINAL:lh,NPER:ch,NPV:hh,PDURATION:dh,PMT:gh,PPMT:ph,PRICE:vh,PRICEDISC:yh,PRICEMAT:wh,PV:bh,RATE:Sh,RECEIVED:Ch,RRI:Th,SLN:Ih,SYD:xh,TBILLEQ:Oh,TBILLPRICE:Ah,TBILLYIELD:_h,VDB:Dh,XIRR:Nh,XNPV:Mh,YIELD:Vh,YIELDDISC:Ph,YIELDMAT:Lh});const Uh=[{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.')}],Hh={description:v("Gets information about a cell."),args:[a("info_type (string)",v("The type of information requested."),Uh),a("reference (meta, range<meta>)",v("The reference to the cell."))],compute:function(e,t){const r=Wt(e).toLowerCase();if(!Uh.map(e=>e.value).includes(r))return new S(v("The info_type should be one of %s.",Uh.join(", ")));const o=this.__originSheetId,n=t[0][0].value;let{sheetName:s,xc:i}=xn(n);s=s===this.getters.getSheetName(o)?void 0:s;const a=Rn(s,On(i,"colrow")),l=this.getters.getRangeFromSheetXC(o,a);switch(r){case"address":return this.getters.getRangeString(l,o);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===wu.empty?"b":t===wu.text?"l":"v"}}return""},isExported:!0},Bh={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 Pt(t)&&t!==w.NotAvailable},isExported:!0},zh={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 Pt(t)},isExported:!0},$h={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},Gh={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===w.NotAvailable},isExported:!0},Wh={description:v("Whether a value is non-textual."),args:[a("value (any)",v("The value to be checked."))],compute:function(e){return!Zh.compute.bind(this)(e)},isExported:!0},qh={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},Zh={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===Pt(e?.value)},isExported:!0},Yh={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},jh={description:v("Returns the error value #N/A."),args:[],compute:function(){return{value:w.NotAvailable}},isExported:!0};var Xh=Object.freeze({__proto__:null,CELL:Hh,ISBLANK:Yh,ISERR:Bh,ISERROR:zh,ISLOGICAL:$h,ISNA:Gh,ISNONTEXT:Wh,ISNUMBER:qh,ISTEXT:Zh,NA:jh});function Kh(e){let t=!1,r=!0;return lr(e,e=>(t=!0,r=r&&e,r)),{foundBoolean:t,result:r}}function Qh(e){let t=!1,r=!1;return lr(e,e=>(t=!0,r=r||e,!r)),{foundBoolean:t,result:r}}const Jh={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}=Kh(e);return r?t:new S(wr)},isExported:!0},ed={description:v("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},td={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(No(e))return ar(td.compute,[e,t,r]);return(Yt(Fo(e))?t:r)??{value:0}},isExported:!0},rd={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(No(e))return ar(rd.compute,[e,t]);return(Pt(Fo(e)?.value)?t:e)??{value:0}},isExported:!0},od={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(No(e))return ar(od.compute,[e,t]);return(Fo(e)?.value===w.NotAvailable?t:e)??{value:0}},isExported:!0},nd={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(No(e[0]))return ar(nd.compute,e);const t=Yt(Fo(e.shift())),r=e.shift();if(t)return r??{value:0}}return new S(v("No match."))},isExported:!0},sd={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!Yt(e)},isExported:!0},id={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}=Qh(e);return r?t:new S(wr)},isExported:!0},ad={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 o=t[r];if(o&&Pt(o.value))return o;if(e?.value===o?.value)return t[r+1]||{value:0}}return r||{value:0}},isExported:!0},ld={description:v("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},cd={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 lr(e,e=>(t=!0,r=r?!e:e,!0)),t?r:new S(wr)},isExported:!0};var ud=Object.freeze({__proto__:null,AND:Jh,FALSE:ed,IF:td,IFERROR:rd,IFNA:od,IFS:nd,NOT:sd,OR:id,SWITCH:ad,TRUE:ld,XOR:cd});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 hd={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"),positiveNumber:v("The value must be a positive number")},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 dd{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 fd=new dd;function gd(e){return fd.get(e)}const md={normalizeFunctionValue:e=>Ut(e,Ar),toValueAndFormat:(e,t)=>({value:Ut(e,Ar),format:"dd mmm yyyy"}),toFunctionValue(e){const t=jt(e,Ar);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},pd={normalizeFunctionValue(e){const t=Ut(e,Ar);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:Ut(e,Ar),format:"0"}),toFunctionValue:e=>`${e}`},bd={normalizeFunctionValue(e){const t=Ut(e,Ar);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||Ar).weekStart)%7;return{value:Kr[r].toString(),format:"@"}},toFunctionValue:e=>`${e}`},vd={normalizeFunctionValue(e){const t=Ut(e,Ar);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:Ut(e,Ar),format:"0"}),toFunctionValue:e=>`${e}`},yd={normalizeFunctionValue(e){const t=Ut(e,Ar);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:Xr[Ut(e,Ar)-1].toString(),format:"@"}),toFunctionValue:e=>`${e}`},wd={normalizeFunctionValue:e=>Qr(Ut(e,Ar),{locale:Ar,format:"mm/yyyy"}),toValueAndFormat:e=>({value:Ut(e,Ar),format:"mmmm yyyy"}),toFunctionValue(e){const t=jt(e,Ar);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`}},Ed={normalizeFunctionValue(e){const t=Ut(e,Ar);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}`},Sd={normalizeFunctionValue(e){const t=Ut(e,Ar);return t>3e3?jt(t,Ar).getFullYear():t},toValueAndFormat:e=>({value:Ut(e,Ar),format:"0"}),toFunctionValue:e=>`${e}`},Cd={normalizeFunctionValue(e){const t=Ut(e,Ar);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}`},Td={normalizeFunctionValue(e){const t=Ut(e,Ar);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}`},Id={normalizeFunctionValue(e){const t=Ut(e,Ar);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 xd(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)}}fd.add("day",xd(md)).add("year",xd(Sd)).add("day_of_month",xd(pd)).add("iso_week_number",xd(vd)).add("month_number",xd(yd)).add("month",xd(wd)).add("quarter_number",xd(Ed)).add("day_of_week",xd(bd)).add("hour_number",xd(Cd)).add("minute_number",xd(Td)).add("second_number",xd(Id));const Rd={displayTotals:!0,displayColumnHeaders:!0,displayMeasuresRow:!0,numberOfRows:Number.MAX_VALUE,numberOfColumns:Number.MAX_VALUE,tableStyleId:"None",bandedRows:!1,bandedColumns:!1,hasFilters:!1},Ad={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")},Od=["max","min","avg","sum","count_distinct","count"],_d={integer:Od,char:Od,datetime:Od,boolean:["count_distinct","count","bool_and","bool_or"]},Fd={};for(const e in _d){Fd[e]={};for(const t of _d[e])Fd[e][t]=Ad[t]}const Dd={count:e=>({value:Wi([e]),format:"0"}),count_distinct:e=>({value:xs([e]),format:"0"}),bool_and:e=>({value:Kh([e]).result}),bool_or:e=>({value:Qh([e]).result}),max:(e,t)=>qi([e],t),min:(e,t)=>Zi([e],t),avg:(e,t)=>({value:Gi([e],t),format:Vt(e)}),sum:(e,t)=>({value:Is([e],t),format:Vt(e)})};function Nd(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 Md=["date","datetime"];function Vd(e){const[t,r]=e.split(":");return r?{fieldName:t,granularity:r}:{fieldName:t}}function Pd(e,t,r){const o=[e];r&&o.push(`"${r}"`);for(const{field:e,value:r,type:n}of t){if("measure"===e){o.push('"measure"',`"${r}"`);continue}const{granularity:t}=Vd(e),s=Hd(r,{type:n,granularity:t});o.push(`"${e}"`,s)}return o}function Ld(e,t){switch(t.type){case"HEADER":return`=PIVOT.HEADER(${Pd(e,t.domain).join(",")})`;case"VALUE":return`=PIVOT.VALUE(${Pd(e,t.domain,t.measure).join(",")})`;case"MEASURE_HEADER":return`=PIVOT.HEADER(${Pd(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(Pt(r))return r;if("custom"===e.type)return Xt(t)??null;const o="boolean"==typeof t?Wt(t).toLocaleLowerCase():Wt(t);if("null"===o)return null;if(!zd.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"===o.toLowerCase())return!1;return zd.get(e.type)(o,e.granularity)}function Ud(e,t){return gd(t??"month").normalizeFunctionValue(e)}function Hd(e,t){return null===e?'"null"':$d.contains(t.type)?$d.get(t.type)(e,t.granularity):`"${e}"`}function Bd(e,t){return gd(t??"month").toFunctionValue(e)}const zd=new dd;zd.add("date",Ud).add("datetime",Ud).add("integer",e=>Ut(e,Ar)).add("boolean",e=>Yt(e)).add("char",e=>Wt(e)).add("custom",e=>e);const $d=new dd;function Gd(e,t){return 0===e.length?t:{...t,format:(t.format||"@")+"* "}}function Wd(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 qd(e,t){const r=t.model.getters.getPivotCellFromPosition(e),o=t.model.getters.getPivotIdFromPosition(e);if(!o||"HEADER"!==r.type)return;const n=t.model.getters.getPivotCoreDefinition(o),s=n.collapsedDomains?.[r.dimension]?[...n.collapsedDomains[r.dimension]]:[],i=s.findIndex(e=>Ae(e,r.domain));-1!==i?s.splice(i,1):s.push(r.domain);const a=n.collapsedDomains?{...n.collapsedDomains}:{COL:[],ROW:[]};a[r.dimension]=s,t.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...n,collapsedDomains:a}})}function Zd(e,t,r,o,n,s,i){const a=e.style;return{numberOfRows:void 0!==t?Ut(t,i):a?.numberOfRows??Rd.numberOfRows,numberOfColumns:void 0!==n?Ut(n,i):a?.numberOfColumns??Rd.numberOfColumns,displayTotals:void 0!==r?Yt(r):a?.displayTotals??Rd.displayTotals,displayColumnHeaders:void 0!==o?Yt(o):a?.displayColumnHeaders??Rd.displayColumnHeaders,displayMeasuresRow:void 0!==s?Yt(s):a?.displayMeasuresRow??Rd.displayMeasuresRow,tableStyleId:a?.tableStyleId||Rd.tableStyleId,bandedRows:a?.bandedRows??Rd.bandedRows,bandedColumns:a?.bandedColumns??Rd.bandedColumns,hasFilters:a?.hasFilters??Rd.hasFilters}}function Yd(e,t){const r=t.getPivotId(e);if(!r)throw new S(v('There is no pivot with id "%s"',e));return r}function jd(e){if(e.length%2!=0)throw new S(v("Function PIVOT takes an even number of arguments."))}function Xd(e,t,r){const o=[],n=e.getters.getPivotCoreDefinition(t);if("SPREADSHEET"===n.type&&n.dataSet){const{sheetId:t,zone:r}=n.dataSet,s=rs(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&&hs(vs(e.__originCellPosition),r))throw new T;o.push(i)}for(const n of r)n.computedBy&&o.push(...e.getters.getMeasureFullDependencies(t,n));const s=e.__originCellPosition;s&&o.length&&(e.updateDependencies?.(s),e.addDependencies?.(s,o))}$d.add("date",Bd).add("datetime",Bd).add("integer",e=>`${Ut(e,Ar)}`).add("boolean",e=>Yt(e)?"TRUE":"FALSE").add("char",e=>`"${Wt(e).replace(/"/g,'\\"')}"`).add("custom",e=>"string"==typeof e?`"${e}"`:String(e));const Kd=!0,Qd=[{value:!0,label:v("A1 style (default)")},{value:!1,label:v("R1C1 style")}],Jd=[{value:!0,label:v("Approximate match (default)")},{value:!1,label:v("Exact match")}],ef={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."),Qd),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},o={value:!0},n){const s=Gt(e,this.locale),i=Gt(t,this.locale);if(s<1)return new S(xo(s));if(i<1)return new S(xo(i));const a=Gt(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(Yt(o)){u=$n(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!==n?Rn(Wt(n),u):u},isExported:!0},tf={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===w.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:nr(e.length,1,(e,r)=>({value:t+e+1}))},isExported:!0},rf={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=br(e);return void 0===t[0][0]?new S(v("The range is out of bounds.")):t[0][0].value===w.InvalidReference?t[0][0]:t.length},isExported:!0},of={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."),Jd)],compute:function(e,t,r,o={value:Kd}){const n=Math.trunc(Ut(r?.value,this.locale)),s=br(t);if(1>n||n>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[Yt(o.value)?fr(s,e,"nextSmaller","asc",s.length,i):gr(s,e,"wildcard",s.length,i,this.lookupCaches)];return void 0===a?Lt(e):a[n-1]},isExported:!0},nf={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 o=br(e),n=Ut(t.value,this.locale),s=Ut(r.value,this.locale);return s<0||s-1>=o.length||n<0||n-1>=o[0].length?new S(v("Index out of range.")):0===n&&0===s?o:0===n?[o[s-1]]:0===s?o.map(e=>[e[n-1]]):o[s-1][n-1]},isExported:!0},sf={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)."),Qd)],compute:function(e,t={value:!0}){const r=e?.value?.toString();if(!r)return new I(v("Reference should be defined."));if(!Yt(t))return new S(v("R1C1 notation is not supported."));const o=this.__originSheetId,n=this.__originCellPosition;n&&this.updateDependencies?.(n);const s=this.getters.getRangeFromSheetXC(o,r);if(void 0===s||s.invalidXc||s.invalidSheetName)return new I;n&&this.addDependencies?.(n,[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 o={sheetId:s.sheetId,col:e,row:r};t.push(this.getters.getEvaluatedCell(o))}i.push(t)}return 1===i.length&&1===i[0].length?i[0][0]:i},isExported:!0},af={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 o=br(t),n=br(r);let s=o.length,i=o[0].length;const a=i>=s,l=a?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=fr(o,e,"nextSmaller","asc",a?i:s,l);return-1===c||a&&void 0===o[0][c]||!a&&void 0===o[c][i-1]?Lt(e):0===n[0].length?a?o[s-1][c]:o[c][i-1]:(s=n.length,i=n[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)):n[c][0]:c>i-1?new S(v("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",c+1)):n[0][c])},isExported:!0},lf={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 o=Ut(r,this.locale);const n=br(t),s=n.length,i=n[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?n[0].length:n.length;switch(o=Math.sign(o),o){case 1:a=fr(n,e,"nextSmaller","asc",c,l);break;case 0:a=gr(n,e,"wildcard",c,l,this.lookupCaches);break;case-1:a=fr(n,e,"nextGreater","desc",c,l)}return 1===s&&void 0===n[0][a]||1!==s&&void 0===n[a]?Lt(e):a+1},isExported:!0},cf={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===w.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:nr(1,e[0].length,(e,r)=>({value:t+r+1}))},isExported:!0},uf={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=br(e);return void 0===t[0][0]?new S(v("The range is out of bounds.")):t[0][0].value===w.InvalidReference?t[0][0]:t[0].length},isExported:!0},hf={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."),Jd)],compute:function(e,t,r,o={value:Kd}){const n=Math.trunc(Ut(r?.value,this.locale)),s=br(t);if(1>n||n>s.length)return new S(v("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const i=(e,t)=>e[0][t].value,a=Yt(o.value)?fr(s,e,"nextSmaller","asc",s[0].length,i):gr(s,e,"wildcard",s[0].length,i,this.lookupCaches),l=s[n-1][a];return void 0===l?Lt(e):l},isExported:!0},df={0:"strict",1:"nextGreater","-1":"nextSmaller",2:"wildcard"},ff={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,o,n={value:0},s={value:1}){const i=Math.trunc(Ut(n.value,this.locale)),a=Math.trunc(Ut(s.value,this.locale)),l=br(t),c=br(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=df[i],g=-1===a,m=2===a||-2===a?fr(l,e,f,2===a?"asc":"desc",d,h):gr(l,e,f,d,h,this.lookupCaches,g);return-1!==m?"col"===u?c.map(e=>[e[m]]):[c[m]]:void 0===o?Lt(e):[[o]]},isExported:!0},gf={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 o=Wt(e),n=Wt(t),s=Yd(o,this.getters);!function(e,t,r){const{measures:o}=r.getPivotCoreDefinition(e);if(!o.find(e=>e.id===t)){const e=`(${o.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,n,this.getters),jd(r);const i=this.getters.getPivot(s);Xd(this,s,this.getters.getPivotCoreDefinition(s).measures.filter(e=>e.id===n)),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(${o})`);return{value:w.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(n,l),i.getPivotCellValueAndFormat(n,l)}},mf={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=Wt(e),o=Yd(r,this.getters);jd(t);const n=this.getters.getPivot(o);Xd(this,o,[]),n.init({reload:n.needsReevaluation});const s=n.assertIsValid({throwOnError:!1});if(s)return s;if(!n.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:w.GenericError,message:v("Dimensions don't match the pivot definition")+". "+e}}const i=n.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(o)?.trackHeader(i);const a=i.at(-1);if("measure"===a?.field)return n.getPivotMeasureValue(Wt(a.value),i);const{value:l,format:c}=n.getPivotHeaderValueAndFormat(i);return{value:l,format:a&&"measure"!==a.field&&"false"!==a.value?c:void 0}}},pf={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,o,n,s){const i=Yd(Wt(e),this.getters),a=this.getters.getPivot(i),l=this.getters.getPivotCoreDefinition(i),c=Zd(l,t,r,o,n,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."));Xd(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=Qr(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);c.displayColumnHeaders&&h.columns.length,c.displayMeasuresRow;const f=this.getters.getPivotName(i),{numberOfCols:g,numberOfRows:m}=h.getPivotTableDimensions(c);if(0===m)return[[{value:f}]];const p=[];for(const e of le(0,g)){p[e]=[];for(const t of le(0,m)){const r=d[e][t];switch(r.type){case"EMPTY":p[e].push({value:""});break;case"HEADER":const t=a.getPivotHeaderValueAndFormat(r.domain);p[e].push(Gd(r.domain,t));break;case"MEASURE_HEADER":p[e].push(a.getPivotMeasureValue(r.measure,r.domain));break;case"VALUE":p[e].push(a.getPivotCellValueAndFormat(r.measure,r.domain))}}}return(c.displayColumnHeaders||c.displayMeasuresRow)&&(p[0][0]={value:f}),p}},bf={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,o,n){if(Pt(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=Jn(s);let a=e[0].length,l=e.length;if(o){const e=Ut(o,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(n){const e=Ut(n,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}=xn(s),u=c&&this.getters.getSheetIdByName(c)||this.getters.getActiveSheetId(),h=Ut(t,this.locale),d=Ut(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]),nr(l,a,(e,t)=>this.getters.getEvaluatedCell({sheetId:u,col:g+e,row:m+t})))}},vf={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(Ut(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},yf={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 o=Ut(t,this.locale),n=Ut(r,this.locale);let s=e;if(Math.abs(n)>=e.length||Math.abs(o)>=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=n>=0?s.slice(n):s.slice(0,s.length+n);for(let e=0;e<s.length;e++)s[e]=o>=0?s[e].slice(o):s[e].slice(0,s[e].length+o);return s},isExported:!0},wf={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 o=t?Ut(t,this.locale):e[0].length,n=Ut(r,this.locale),s=e;if((Math.abs(n)>=e.length||0===n)&&(n=e.length),Math.abs(o)>=e[0].length&&(o=e[0].length),s=n>=0?s.slice(0,n):s.slice(s.length+n,s.length),0===o)return new S(v("The number of rows can not be zero."));for(let e=0;e<s.length;e++)s[e]=o>0?s[e].slice(0,o):s[e].slice(s[e].length+o,s[e].length);return s},isExported:!0},Ef={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}=xn(e.value),{col:o,row:n}=zn(r),s=(t&&this.getters.getSheetIdByName(t))??this.__originSheetId,i=this.getters.getCell({sheetId:s,col:o,row:n});return i&&Ke(i.content)?i.content:new x(v("The cell does not contain a formula."))},isExported:!0};var Sf=Object.freeze({__proto__:null,ADDRESS:ef,CHOOSE:vf,COLUMN:tf,COLUMNS:rf,DROP:yf,FORMULATEXT:Ef,HLOOKUP:of,INDEX:nf,INDIRECT:sf,LOOKUP:af,MATCH:lf,OFFSET:bf,PIVOT:pf,PIVOT_HEADER:mf,PIVOT_VALUE:gf,ROW:cf,ROWS:uf,TAKE:wf,VLOOKUP:hf,XLOOKUP:ff});const Cf={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:Ut(e,this.locale)+Ut(t,this.locale),format:e?.format||t?.format}}},Tf={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 Wt(e)+Wt(t)},isExported:!0},If={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=Ut(t,this.locale);return 0===r?new O(v("The divisor must be different from zero.")):{value:Ut(e,this.locale)/r,format:e?.format||t?.format}}};function xf(e){return void 0===e||null===e.value}const Rf={number:0,string:"",boolean:!1};function Af(e,t,r=2e-16){return Math.abs(e-t)<r}const Of={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(Pt(e?.value))return e;if(Pt(t?.value))return t;let r=xf(e)?Rf[typeof t?.value]:e?.value,o=xf(t)?Rf[typeof e?.value]:t?.value;return"string"==typeof r&&(r=r.toUpperCase()),"string"==typeof o&&(o=o.toUpperCase()),"number"==typeof r&&"number"==typeof o?{value:Af(r,o)}:{value:r===o}}};function _f(e,t,r){if(Pt(e?.value))return e;if(Pt(t?.value))return t;let o=xf(e)?Rf[typeof t?.value]:e?.value,n=xf(t)?Rf[typeof e?.value]:t?.value;"number"!=typeof o&&(o=Wt(o).toUpperCase()),"number"!=typeof n&&(n=Wt(n).toUpperCase());const s=typeof o,i=typeof n;return"string"===s&&"number"===i?{value:!0}:"string"===i&&"number"===s?{value:!1}:{value:r(o,n)}}const Ff={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?!Af(e,t)&&e>t:e>t)}},Df={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?Af(e,t)||e>t:e>=t)}},Nf={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=Df.compute.bind(this)(e,t);return Pt(r.value)?r:{value:!r.value}}},Mf={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=Ff.compute.bind(this)(e,t);return Pt(r.value)?r:{value:!r.value}}},Vf={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:Ut(e,this.locale)-Ut(t,this.locale),format:e?.format||t?.format}}},Pf={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:Ut(e,this.locale)*Ut(t,this.locale),format:e?.format||t?.format}}},Lf={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=Of.compute.bind(this)(e,t);return Pt(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 pi.compute.bind(this)(e,t)}},Uf={description:v("Gets the spilled range of an array formula."),args:[a("ref (meta , range<meta>)",v("The reference to get the spilled range from."))],compute:function(e){if(void 0===e)return new S(v("The range is out of bounds."));if(1!==e.length||1!==e[0].length)return new S(v("Only single-cell references are allowed to get the spilled range."));const t=e[0][0];if(Pt(t.value))return t;const r=this.getters.getRangeFromSheetXC(this.__originSheetId,t.value),o={col:r.zone.left,row:r.zone.top,sheetId:r.sheetId},n=this.__originCellPosition;n&&this.updateDependencies?.(n);const s=this.getters.getSpreadZone(o);if(void 0===s)return new I;const i=this.getters.getRangeFromZone(r.sheetId,s);return n&&this.addDependencies?.(n,[i]),nr(s.right-s.left+1,s.bottom-s.top+1,(e,t)=>this.getters.getEvaluatedCell({sheetId:i.sheetId,col:s.left+e,row:s.top+t}))},hidden:!0},Hf={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:-Ut(e,this.locale),format:e?.format}}},Bf={description:v("Value interpreted as a percentage."),args:[a("percentage (number)",v("The value to interpret as a percentage."))],compute:function(e){return Ut(e,this.locale)/100}},zf={description:v("A specified number, unchanged."),args:[a("value (any)",v("The number to return."))],compute:function(e={value:null}){return e}};var $f=Object.freeze({__proto__:null,ADD:Cf,CONCAT:Tf,DIVIDE:If,EQ:Of,GT:Ff,GTE:Df,LT:Nf,LTE:Mf,MINUS:Vf,MULTIPLY:Pf,NE:Lf,POW:kf,SPILLED_RANGE:Uf,UMINUS:Hf,UNARY_PERCENT:Bf,UPLUS:zf});const Gf=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),Wf={transform:e=>e,inverseTransform:e=>e},qf=1e-10,Zf=.0254,Yf=Zf/72,jf=.3048,Xf=.9144,Kf=1609.34,Qf=1852,Jf=946073047258e4,eg={g:{...Wf,category:"weight"},u:{...Gf(166053e-29),category:"weight"},grain:{...Gf(.0647989),category:"weight"},ozm:{...Gf(28.3495),category:"weight"},lbm:{...Gf(453.592),category:"weight"},stone:{...Gf(6350.29),category:"weight"},sg:{...Gf(14593.90294),category:"weight"},cwt:{...Gf(45359.237),category:"weight"},uk_cwt:{...Gf(50802.3),category:"weight"},ton:{...Gf(907184.74),category:"weight"},uk_ton:{...Gf(1016046.9),category:"weight"},m:{...Wf,category:"distance"},km:{...Gf(1e3),category:"distance"},ang:{...Gf(qf),category:"distance"},Picapt:{...Gf(Yf),category:"distance"},pica:{...Gf(Zf/6),category:"distance"},in:{...Gf(Zf),category:"distance"},ft:{...Gf(jf),category:"distance"},yd:{...Gf(Xf),category:"distance"},ell:{...Gf(1.143),category:"distance"},mi:{...Gf(Kf),category:"distance"},survey_mi:{...Gf(1609.34),category:"distance"},Nmi:{...Gf(Qf),category:"distance"},ly:{...Gf(Jf),category:"distance"},parsec:{...Gf(0x6da012f95c9fd0),category:"distance"},sec:{...Wf,category:"time"},min:{...Gf(60),category:"time"},hr:{...Gf(3600),category:"time"},day:{...Gf(86400),category:"time"},yr:{...Gf(31556952),category:"time"},Pa:{...Wf,category:"pressure"},bar:{...Gf(1e5),category:"pressure"},mmHg:{...Gf(133.322),category:"pressure"},Torr:{...Gf(133.322),category:"pressure"},psi:{...Gf(6894.76),category:"pressure"},atm:{...Gf(101325),category:"pressure"},N:{...Wf,category:"force"},dyn:{...Gf(1e-5),category:"force"},pond:{...Gf(.00980665),category:"force"},lbf:{...Gf(4.44822),category:"force"},J:{...Wf,category:"energy"},eV:{...Gf(160218e-24),category:"energy"},e:{...Gf(1e-7),category:"energy"},flb:{...Gf(1.3558179483),category:"energy"},c:{...Gf(4.184),category:"energy"},cal:{...Gf(4.1868),category:"energy"},BTU:{...Gf(1055.06),category:"energy"},Wh:{...Gf(3600),category:"energy"},HPh:{...Gf(2684520),category:"energy"},W:{...Wf,category:"power"},PS:{...Gf(735.499),category:"power"},HP:{...Gf(745.7),category:"power"},T:{...Wf,category:"magnetism"},ga:{...Gf(1e-4),category:"magnetism"},K:{...Wf,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:{...Gf(5/9),category:"temperature"},Reau:{transform:e=>1.25*e+273.15,inverseTransform:e=>(e-273.15)/1.25,category:"temperature"},"m^3":{...Wf,category:"volume",order:3},"ang^3":{...Gf(Math.pow(qf,3)),category:"volume",order:3},"Picapt^3":{...Gf(Math.pow(Yf,3)),category:"volume",order:3},tsp:{...Gf(492892e-11),category:"volume"},tspm:{...Gf(5e-6),category:"volume"},tbs:{...Gf(14786764825785619e-21),category:"volume"},"in^3":{...Gf(Math.pow(Zf,3)),category:"volume",order:3},oz:{...Gf(295735295625e-16),category:"volume"},cup:{...Gf(237e-6),category:"volume"},pt:{...Gf(.0004731765),category:"volume"},uk_pt:{...Gf(568261e-9),category:"volume"},qt:{...Gf(.0009463529),category:"volume"},l:{...Gf(.001),category:"volume"},uk_qt:{...Gf(.0011365225),category:"volume"},gal:{...Gf(.0037854118),category:"volume"},uk_gal:{...Gf(.00454609),category:"volume"},"ft^3":{...Gf(Math.pow(jf,3)),category:"volume",order:3},bushel:{...Gf(.0352390704),category:"volume"},barrel:{...Gf(.158987295),category:"volume"},"yd^3":{...Gf(Math.pow(Xf,3)),category:"volume",order:3},MTON:{...Gf(1.13267386368),category:"volume"},GRT:{...Gf(2.83168),category:"volume"},"mi^3":{...Gf(Math.pow(Kf,3)),category:"volume",order:3},"Nmi^3":{...Gf(Math.pow(Qf,3)),category:"volume",order:3},"ly^3":{...Gf(Math.pow(Jf,3)),category:"volume",order:3},"m^2":{...Wf,category:"area",order:2},"ang^2":{...Gf(Math.pow(qf,2)),category:"area",order:2},"Picapt^2":{...Gf(Math.pow(Yf,2)),category:"area",order:2},"in^2":{...Gf(Math.pow(Zf,2)),category:"area",order:2},"ft^2":{...Gf(Math.pow(jf,2)),category:"area",order:2},"yd^2":{...Gf(Math.pow(Xf,2)),category:"area",order:2},ar:{...Gf(100),category:"area"},Morgen:{...Gf(2500),category:"area"},uk_acre:{...Gf(4046.8564224),category:"area"},us_acre:{...Gf(4046.8726098743),category:"area"},ha:{...Gf(1e4),category:"area"},"mi^2":{...Gf(Math.pow(Kf,2)),category:"area",order:2},"Nmi^2":{...Gf(Math.pow(Qf,2)),category:"area",order:2},"ly^2":{...Gf(Math.pow(Jf,2)),category:"area",order:2},bit:{...Wf,category:"information"},byte:{...Gf(8),category:"information"},"m/s":{...Wf,category:"speed"},"m/hr":{...Gf(1/3600),category:"speed"},"km/hr":{...Gf(1/3.6),category:"speed"},mph:{...Gf(.44704),category:"speed"},kn:{...Gf(.5144444444),category:"speed"},admkn:{...Gf(.5147733333),category:"speed"}},tg={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"},rg={"":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)},og={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")},ng=Object.entries(eg).map(([e,t])=>({value:e,label:sg(t.category)}));function sg(e){return og[e]??""}function ig(e){for(const[t,r]of Object.entries(rg)){if(t&&!e.startsWith(t))continue;const o=e.slice(t.length);let n=eg[o];if(!n&&tg[o]&&(n=eg[tg[o]]),n)return{...n,factor:n.order?Math.pow(r,n.order):r}}}const ag={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"),ng),a("end_unit (string)",v("The unit of measure into which to convert value"),ng)],compute:function(e,t,r){const o=Ut(e,this.locale),n=Wt(t),s=Wt(r),i=ig(n),a=ig(s);return i?a?i.category!==a.category?{value:w.GenericError,message:v("Incompatible units of measure ('%s' vs '%s')",sg(i.category),sg(a.category))}:{value:a.inverseTransform(i.factor*i.transform(o))/a.factor,format:e?.format}:{value:w.GenericError,message:v("Invalid units of measure ('%s')",s)}:{value:w.GenericError,message:v("Invalid units of measure ('%s')",n)}},isExported:!0};var lg=Object.freeze({__proto__:null,CONVERT:ag});const cg=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,ug=[{value:0,label:v("Case-sensitive (default)")},{value:1,label:v("Case-insensitive")}],hg=[{value:0,label:v("Don't match to end (default)")},{value:1,label:v("Match to end")}],dg={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(Ut(e,this.locale));return t<1?new S(v("The table_number (%s) is out of range.",t)):String.fromCharCode(t)},isExported:!0},fg={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=Wt(e);let r="";for(const e of t)e&&e.charCodeAt(0)>31&&(r+=e);return r},isExported:!0},gg={description:v("Appends strings to one another."),args:[a("string (string, range<string>, repeating)",v("String to append in sequence."))],compute:function(...e){return tr(e,(e,t)=>e+Wt(t),"")},isExported:!0},mg={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 Wt(e)===Wt(t)},isExported:!0},pg={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 o=Wt(e),n=Wt(t),s=Ut(r,this.locale);if(""===n)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=n.indexOf(o,s-1);return-1===i?new S(v("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,n)):i+1},isExported:!0},bg={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=Wt(e);return tr(t,(e,t)=>(e?e+r:"")+Wt(t),"")}},vg={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?Ut(t[0],this.locale):1;return r<0?new S(v("The number_of_characters (%s) must be positive or null.",r)):Wt(e).substring(0,r)},isExported:!0},yg={description:v("Length of a string."),args:[a("text (string)",v("The string whose length will be returned."))],compute:function(e){return Wt(e).length},isExported:!0},wg={description:v("Converts a specified string to lowercase."),args:[a("text (string)",v("The string to convert to lowercase."))],compute:function(e){return Wt(e).toLowerCase()},isExported:!0},Eg={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 o=Wt(e),n=Ut(t,this.locale),s=Ut(r,this.locale);return n<1?new S(v("The starting_at argument (%s) must be positive greater than one.",n.toString())):s<0?new S(v("The extract_length argument (%s) must be positive or null.",s)):o.slice(n-1,n+s-1)},isExported:!0},Sg={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 Wt(e).replace(cg,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},Cg={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},o={value:0}){const n=Wt(e),s=Wt(t),i=Ut(r,this.locale),a=Ut(o,this.locale);if(""===n||""===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=[...n.matchAll(l)];return 0===c.length?{value:w.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},Tg={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,o){const n=Ut(t,this.locale);if(n<1)return new S(v("The position (%s) must be greater than or equal to 1.",n));const s=Wt(e),i=Ut(r,this.locale),a=Wt(o);return s.substring(0,n-1)+a+s.substring(n-1+i)},isExported:!0},Ig={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?Ut(t[0],this.locale):1;if(r<0)return new S(v("The number_of_characters (%s) must be positive or null.",r));const o=Wt(e),n=o.length;return o.substring(n-r,n)},isExported:!0},xg={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 o=Wt(e).toLowerCase(),n=Wt(t).toLowerCase(),s=Ut(r,this.locale);if(""===n)return{value:w.GenericError,message:v("The text_to_search must be non-empty.")};if(s<1)return{value:w.GenericError,message:v("The starting_at (%s) must be greater than or equal to 1.",s)};const i=n.indexOf(o,s-1);return-1===i?{value:w.GenericError,message:v("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,n)}:{value:i+1}},isExported:!0},Rg=!0,Ag=!0,Og={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:Rg},o={value:Ag}){const n=Wt(e),s=te(Wt(t)),i=Yt(r),a=Yt(o);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=n.split(l);return a&&(c=c.filter(e=>""!==e)),ir([c])},isExported:!1},_g={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,o){const n=Ut(o,this.locale);if(n<0)return new S(v("The occurrenceNumber (%s) must be positive or null.",n));const s=Wt(e),i=Wt(t);if(""===i)return s;const a=Wt(r),l=new RegExp(te(i),"g");if(0===n)return s.replace(l,a);let c=0;return s.replace(l,e=>++c===n?a:e)},isExported:!0},Fg={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 o=Wt(e),n=Yt(t);let s=0;return tr(r,(e,t)=>n&&""===Wt(t)?e:(s++?e+o:"")+Wt(t),"")},isExported:!0},Dg=!1,Ng={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."),ug),a(`pad_with (string, default="${w.NotAvailable}")`,v("The value to use for padding empty cells."))],compute:function(e,t,r,o={value:Dg},n={value:0},s=new x){const i=Wt(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=br(t).flat().map(e=>te(Wt(e))),l=br(r).flat().map(e=>te(Wt(e)));if(a.some(e=>""===e)||l.some(e=>""===e))return new S(v("The delimiters cannot be empty values."));const c=Yt(o),u=Ut(n,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 ir(h)},isExported:!0},Mg={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(Wt(e))},isExported:!0},Vg={description:v("Converts a specified string to uppercase."),args:[a("text (string)",v("The string to convert to uppercase."))],compute:function(e){return Wt(e).toUpperCase()},isExported:!0},Pg={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 Qr(Ut(e,this.locale),{format:Wt(t),locale:this.locale})},isExported:!0},Lg={description:v("Converts a string to a numeric value."),args:[a("value (number)",v("the string to be converted"))],compute:function(e){return Ut(e,this.locale)},isExported:!0},kg={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."),ug),a("match_end (number, default=0))",v("Whether to treat the end of text as a delimiter."),hg),a(`if_not_found (string, default="${w.NotAvailable}")`,v("Value to return if the delimiter is not found."))],compute:function(e,t,r={value:1},o={value:0},n={value:0},s=new x){const i=Wt(e),a=Ut(r,this.locale),l=Ut(o,this.locale),c=Ut(n,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=Wt(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},Ug={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."),ug),a("match_end (number, default=0))",v("Whether to match a delimiter against the end of the text."),hg),a(`if_not_found (string, default="${w.NotAvailable}")`,v("Value to return if the delimiter is not found."))],compute:function(e,t,r={value:1},o={value:0},n={value:0},s=new x){const i=Wt(e),a=Ut(r,this.locale),l=Ut(o,this.locale),c=Ut(n,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=Wt(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 Hg=Object.freeze({__proto__:null,CHAR:dg,CLEAN:fg,CONCATENATE:gg,EXACT:mg,FIND:pg,JOIN:bg,LEFT:vg,LEN:yg,LOWER:wg,MID:Eg,PROPER:Sg,REGEXEXTRACT:Cg,REPLACE:Tg,RIGHT:Ig,SEARCH:xg,SPLIT:Og,SUBSTITUTE:_g,TEXT:Pg,TEXTAFTER:kg,TEXTBEFORE:Ug,TEXTJOIN:Fg,TEXTSPLIT:Ng,TRIM:Mg,UPPER:Vg,VALUE:Lg});const Bg={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=Wt(e).trim(),o=Wt(t)||r;return""===r?o:pe(o,r)},isExported:!0};var zg=Object.freeze({__proto__:null,HYPERLINK:Bg});const $g=/^[A-Z0-9\_\.]+$/;class Gg 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(),!$g.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,o=0,n=0,s=0;for(const e of t.args)r++,e.optional||e.default||o++,e.repeating&&n++,!e.optional&&!e.default||e.repeating||s++;const i=t;return i.minArgRequired=o,i.maxArgPossible=n?1/0:r,i.nbrArgRepeating=n,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 o of e.args){if(o.type.some(e=>u.includes(e))&&o.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: ${o.type}.`);if(o.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]=Sr(r),super.replace(e,r),this}}const Wg=new Gg,qg=[{name:v("Array"),functions:hn},{name:v("Database"),functions:Rl},{name:v("Date"),functions:vu},{name:v("Filter"),functions:Ou},{name:v("Financial"),functions:kh},{name:v("Info"),functions:Xh},{name:v("Lookup"),functions:Sf},{name:v("Logical"),functions:ud},{name:v("Math"),functions:zi},{name:v("Misc"),functions:fn},{name:v("Operator"),functions:$f},{name:v("Statistical"),functions:dl},{name:v("Text"),functions:Hg},{name:v("Engineering"),functions:Eu},{name:v("Web"),functions:zg},{name:v("Parser"),functions:lg}];for(const e of qg){const t=e.functions;for(let r in t){const o=t[r];o.category=o.category||e.name,r=r.replace(/_/g,"."),Wg.add(r,{isExported:!1,...o})}}var Zg;!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"}(Zg||(Zg={}));const Yg=(e,t=()=>!0)=>[{goTo:e,guard:t}],jg=(e,t=()=>!0)=>({goTo:e,guard:t}),Xg={[Zg.LeftRef]:{REFERENCE:Yg(Zg.Separator),NUMBER:Yg(Zg.FullRowSeparator),SYMBOL:[jg(Zg.FullColumnSeparator,e=>En(e.value)),jg(Zg.FullRowSeparator,e=>Sn(e.value))]},[Zg.FullColumnSeparator]:{SPACE:Yg(Zg.FullColumnSeparator),OPERATOR:Yg(Zg.RightColumnRef,e=>":"===e.value)},[Zg.FullRowSeparator]:{SPACE:Yg(Zg.FullRowSeparator),OPERATOR:Yg(Zg.RightRowRef,e=>":"===e.value)},[Zg.Separator]:{SPACE:Yg(Zg.Separator),OPERATOR:Yg(Zg.RightRef,e=>":"===e.value)},[Zg.RightRef]:{SPACE:Yg(Zg.RightRef),NUMBER:Yg(Zg.Found),REFERENCE:Yg(Zg.Found,e=>In(e.value)),SYMBOL:Yg(Zg.Found,e=>Cn(e.value)||Tn(e.value))},[Zg.RightColumnRef]:{SPACE:Yg(Zg.RightColumnRef),SYMBOL:Yg(Zg.Found,e=>Cn(e.value)),REFERENCE:Yg(Zg.Found,e=>In(e.value))},[Zg.RightRowRef]:{SPACE:Yg(Zg.RightRowRef),NUMBER:Yg(Zg.Found),REFERENCE:Yg(Zg.Found,e=>In(e.value)),SYMBOL:Yg(Zg.Found,e=>Tn(e.value))},[Zg.Found]:{}};function Kg(e){let t=0,r=Xg[Zg.LeftRef],o="";for(;void 0!==r;){const n=e[t++];if(!n)return null;const s=r[n.type]?.find(e=>e.guard(n)),i=s?s.goTo:void 0;switch(i){case void 0:return null;case Zg.Found:return o+=n.value,e.splice(0,t),{type:"REFERENCE",value:o};default:r=Xg[i],o+=n.value}}return null}function Qg(e,t=Ar){const r=_l(e,t),o=[];for(;r.length;)o.push(Kg(r)||r.shift());return o}const Jg=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,em=["-","+"],tm=["%","#"];class rm{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 om={"#":40,"%":40,"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function nm(e){const t=e.shift();if(!t)throw new C;switch(t.type){case"DEBUGGER":const r=am(e,1e3);return r.debug=!0,r;case"NUMBER":return{type:"NUMBER",value:Dt(t.value,Ar),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"STRING":return{type:"STRING",value:ne(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"INVALID_REFERENCE":return{type:"REFERENCE",value:w.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 o=t.value,n=e.current;if("LEFT_PAREN"===n?.type&&Jg.test(t.value)&&o===ne(o,"'")){const{args:r,rightParen:n}=function(e){im(e,"LEFT_PAREN",v("Missing opening parenthesis"));const t=e.current;if("RIGHT_PAREN"===t?.type){return{args:[],rightParen:im(e,"RIGHT_PAREN")}}const r=[];r.push(sm(e));for(;"RIGHT_PAREN"!==e.current?.type;)im(e,"ARG_SEPARATOR",v("Wrong function call")),r.push(sm(e));const o=im(e,"RIGHT_PAREN");return{args:r,rightParen:o}}(e);return{type:"FUNCALL",value:o,args:r,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenIndex}}const s=o.toUpperCase();return"TRUE"===s||"FALSE"===s?{type:"BOOLEAN",value:"TRUE"===s,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:"SYMBOL",value:ne(t.value,"'"),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"LEFT_PAREN":const i=am(e),a=im(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 o=[am(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)o.push(am(e));else{if("ARRAY_ROW_SEPARATOR"!==t.type)throw new C(v("Unexpected token: %s",t.value));r.push(o),o=[am(e)]}}const n=im(e,"RIGHT_BRACE",v("Missing closing brace"));return r.push(o),{type:"ARRAY",value:r,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenIndex}}(e,t);case"OPERATOR":const l=t.value;if(em.includes(l)){const r=am(e,om[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 sm(e){const t=e.current;return"ARG_SEPARATOR"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:"",tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:am(e)}function im(e,t,r){const o=e.shift();if(!o||o.type!==t)throw new C(r);return o}function am(e,t=0){if(0===e.length)throw new C;let r=nm(e);for(;"OPERATOR"===e.current?.type&&om[e.current.value]>t;){const t=e.shift(),o=t.value;if(tm.includes(o))r={type:"UNARY_OPERATION",value:o,operand:r,postfix:!0,tokenStartIndex:r.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{const t=am(e,om[o]);r={type:"BIN_OPERATION",value:o,left:r,right:t,tokenStartIndex:r.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return r}function lm(e){return cm(Qg(e))}function cm(e){const t=e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>"SPACE"!==e.type),r=new rm(t);"="===r.current?.value&&r.shift();const o=am(r);if(r.current)throw new C;return o}function um(e,t,r){return fm(e,e=>e.type===t?r(e):e)}function hm(e){return Array.from(dm(e))}function*dm(e){switch(yield e,e.type){case"FUNCALL":for(const t of e.args)yield*dm(t);break;case"ARRAY":for(const t of e.value)for(const e of t)yield*dm(e);break;case"UNARY_OPERATION":yield*dm(e.operand);break;case"BIN_OPERATION":yield*dm(e.left),yield*dm(e.right)}}function fm(e,t){switch((e=t(e)).type){case"FUNCALL":return{...e,args:e.args.map(e=>fm(e,t))};case"ARRAY":return{...e,value:e.value.map(e=>e.map(e=>fm(e,t)))};case"UNARY_OPERATION":return{...e,operand:fm(e.operand,t)};case"BIN_OPERATION":return{...e,right:fm(e.right,t),left:fm(e.left,t)};default:return e}}const gm=Wg.content,mm={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},pm={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT","#":"SPILLED.RANGE"},bm={};function vm(e){return ym(Qg(e))}function ym(e){try{return function(e){const{dependencies:r,literalValues:n,symbols:s}=function(e){const t={numbers:[],strings:[]},r=[],o=[];for(const n of e)switch(n.type){case"INVALID_REFERENCE":case"REFERENCE":r.push(n.value);break;case"STRING":const e=ne(n.value);t.strings.push({value:e});break;case"NUMBER":{const e=Dt(n.value,Ar);t.numbers.push({value:e});break}case"SYMBOL":o.push(ne(n.value,"'"))}return{dependencies:r,literalValues:t,symbols:o}}(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(!bm[i]){const l=cm([...e]),u=new o;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(),o=gm[r];if(!o)throw new R(v('Unknown function: "%s"',e.value));!function(e){const t=e.args.length,r=e.value.toUpperCase(),o=gm[r],{nbrArgRepeating:n,minArgRequired:s}=o;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>o.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:o.maxArgPossible,nbrArgSupplied:t}));if(n>1){const e=t-s-n*Math.floor((t-s)/n)-o.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:n,nbrArgOptional:o.nbrOptionalNonRepeatingArgs,nbrValueRemaining:e}))}}(e);const n=[],s=c(o,t.length);for(let e=0;e<t.length;e++){const r=o.args[s(e).index??-1],i=t[e],a=r.type||[],l=a.includes("META")||a.includes("RANGE<META>"),c=a.some(e=>wm(e));n.push(y(i,l,c))}return n}function y(e,r=!1,o=!1){const n=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&&(n.append("debugger;"),n.append('ctx["debug"] = true;')),e.type){case"BOOLEAN":return n.return(`{ value: ${e.value} }`);case"NUMBER":return n.return(`this.literalValues.numbers[${d++}]`);case"STRING":return n.return(`this.literalValues.strings[${h++}]`);case"REFERENCE":return n.return(`${e.value.includes(":")||o?"range":"ref"}(deps[${f++}], ${r?"true":"false"})`);case"FUNCALL":const t=b(e).map(e=>e.assignResultToVariable());n.append(...t);const i=e.value.toUpperCase();return n.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=pm[e.value],{isMeta:r,hasRange:o}="#"===e.value?{isMeta:!0,hasRange:!0}:{isMeta:!1,hasRange:!1},s=y(e.operand,r,o).assignResultToVariable();return n.append(s),n.return(`ctx['${t}'](${s.returnExpression})`)}case"BIN_OPERATION":{const t=mm[e.value],r=y(e.left,!1,!1).assignResultToVariable(),o=y(e.right,!1,!1).assignResultToVariable();return n.append(r),n.append(o),n.return(`ctx['${t}'](${r.returnExpression}, ${o.returnExpression})`)}case"SYMBOL":const a=s.indexOf(e.value);return n.return(`getSymbolValue(this.symbols[${a}])`);case"EMPTY":return n.return("undefined")}}bm[i]=p}const a={execute:bm[i],dependencies:r,literalValues:n,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 wm(e){return e.startsWith("RANGE")}class Em{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 Sm{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 Cm{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,o=r.length;e<o;e++){const o=r[e];o.callback.call(o.owner,t)}}off(e,t){const r=this.subscriptions[e];r&&(this.subscriptions[e]=r.filter(e=>e.owner!==t))}clear(){this.subscriptions={}}}function Tm(e,t){const r=e.zone,o=function(e,t){const{left:r,top:o,bottom:n,right:s}=e;if(void 0!==s&&void 0!==n)return e;if(void 0===n&&void 0!==s)return{right:s,top:o,left:r,bottom:t.numberOfRows-1};if(void 0===s&&void 0!==n)return{bottom:n,left:r,top:o,right:t.numberOfCols-1};throw new Error("Bad zone format")}(r,t(e.sheetId));let n=e.parts;return 1===e.parts.length&&Ss(o)>1?n=[e.parts[0],e.parts[0]]:2===e.parts.length&&1===Ss(o)&&(n=[e.parts[0]]),{unboundedZone:r,zone:o,parts:n,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Im(e,t){const r=e.xc,{xc:o,sheetName:n}=xn(r),s=Qn(o),i=function(e,t){const r=e.split(":").map(e=>{const t=Sn(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}}),o=void 0===t.bottom,n=void 0===t.right;o&&(r[0].rowFixed=r[0].rowFixed||r[1].rowFixed,r[1].rowFixed=r[0].rowFixed||r[1].rowFixed);n&&(r[0].colFixed=r[0].colFixed||r[1].colFixed,r[1].colFixed=r[0].colFixed||r[1].colFixed);return r}(o,s);return Tm({zone:s,parts:i,sheetId:e.sheetId,prefixSheet:Boolean(n),invalidSheetName:e.invalidSheetName},t)}function xm(e){const t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:"",zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function Rm(e){return Es(e.unboundedZone)}function Am(e){return ws(e.unboundedZone)}function Om(e,t,r,o={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 w.InvalidReference;if(e.zone.left<0||e.zone.top<0)return w.InvalidReference;const n=e.sheetId!==t||e.invalidSheetName||e.prefixSheet;let s="";if(n&&(s=e.invalidSheetName?se(e.invalidSheetName):se(r(e.sheetId))),n&&!s)return w.InvalidReference;let i=Bm(e,0,o);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+=Bm(e,1,o)),`${n?s+"!":""}${i}`}function _m(e,t,r){const o=r.sheetId===e?t:r.sheetId;return{...r,sheetId:o}}function Fm(e){const t=[];for(const r of e)for(const e of gs(r.zone))t.push({...e,sheetId:r.sheetId});return t}function Dm(e){const t={left:e.col,top:e.row,right:e.col,bottom:e.row};return{sheetId:e.sheetId,zone:t}}function Nm(e){return Mm.get(e.type)?.(e)}const Mm=new class extends dd{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};function Vm(e){const t="COL"===e.dimension?"left":"top",r="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows",n=[...e.elements];n.sort((e,t)=>t-e);const s=ce(n);return n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let i=n,a="NONE";for(const e of s){const s=qe(e),l=We(e);if(n.zone[t]<=s&&s<=n.zone[r]){const e=Math.min(n.zone[r],l)-s+1;a="RESIZE",i=Hm(i,o,a,-e)}else if(n.zone[t]>=s&&n.zone[r]<=l)a="REMOVE",i=xm(w.InvalidReference);else if(n.zone[t]<=l&&n.zone[r]>=l){const e=l-n.zone[t]+1;a="RESIZE",i=Hm(i,o,a,-e),i=Hm(i,o,"MOVE",-(n.zone[t]-s))}else s<n.zone[t]&&(a="MOVE",i=Hm(i,o,a,-(l-s+1)))}return"NONE"!==a?{changeType:a,range:i}:{changeType:"NONE"}}}function Pm(e){const t="COL"===e.dimension?"left":"top",r="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";return n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(n.zone[t]<=e.base&&e.base<n.zone[r])return{changeType:"RESIZE",range:Hm(n,o,"RESIZE",e.quantity)};if(e.base<n.zone[t])return{changeType:"MOVE",range:Hm(n,o,"MOVE",e.quantity)}}else{if(n.zone[t]<e.base&&e.base<=n.zone[r])return{changeType:"RESIZE",range:Hm(n,o,"RESIZE",e.quantity)};if(e.base<=n.zone[t])return{changeType:"MOVE",range:Hm(n,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}}function Lm(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:"NONE"};const r=e.sheetName;return{changeType:"REMOVE",range:t={...xm(w.InvalidReference),invalidSheetName:r}}}}function km(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.newName&&t.invalidSheetName===e.newName){const r=void 0,o=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:o,invalidSheetName:r}}}if(e.oldName&&t.invalidSheetName===e.oldName){const r=void 0,o=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:o,invalidSheetName:r}}}return{changeType:"NONE"}}}function Um(e){const t=e.target[0];return r=>{if(r.sheetId!==e.sheetId||!hs(r.zone,t))return{changeType:"NONE"};const o=e.targetSheetId,n=Hm(r,"both","MOVE",[e.col-t.left,e.row-t.top]),s=e.sheetId!==o||n.prefixSheet;return{changeType:"MOVE",range:{...n,sheetId:o,prefixSheet:s}}}}function Hm(e,t,r,o){return{...e,unboundedZone:bs(e.unboundedZone,t,r,o),zone:bs(e.zone,t,r,o)}}function Bm(e,t,r={useBoundedReference:!1,useFixedReference:!1}){const o=e.parts[t]?.colFixed||r.useFixedReference?"$":"",n=Nn(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=Es(e.unboundedZone)&&!r.useBoundedReference?0===t&&e.unboundedZone.hasHeader?o+n+s+i:o+n:ws(e.unboundedZone)&&!r.useBoundedReference?0===t&&e.unboundedZone.hasHeader?o+n+s+i:s+i:o+n+s+i,a}function zm(e){const t=[];for(let r=0;r<e;r++){const e={cells:{}};t.push(e)}return t}function $m(e,t,r){return r.map(r=>r>=e?r+t:r)}function Gm(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 Wm(e,t="Sheet"){let r=1,o=`${t}${r}`;for(;e.includes(o);)o=`${t}${r}`,r++;return o}function qm(e,t){let r=1;const o=v("Copy of %s",e);let n=o.toString();for(;t.includes(n);)n=`${o} (${r})`,r++;return n}Mm.add("REMOVE_COLUMNS_ROWS",e=>({applyChange:Vm(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("ADD_COLUMNS_ROWS",e=>({applyChange:Pm(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("DELETE_SHEET",e=>({applyChange:Lm(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("RENAME_SHEET",e=>({applyChange:km(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add("MOVE_RANGES",e=>({applyChange:Um(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));const Zm=Ue(function(e){return oe(e.trim().toUpperCase())});function Ym(e,t){return void 0!==e&&void 0!==t&&Zm(e)===Zm(t)}const jm=new class extends dd{addTransformation(e,t,r){this.content[e]||(this.content[e]=new Map);for(const o of t)this.content[e].set(o,r);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}};const Xm=new class extends dd{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};const Km=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"]),Qm=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"]),Jm=new Set(["MOVE_RANGES"]),ep=new Set(["EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CHANGE_CONDITIONAL_FORMAT_PRIORITY"]),tp=new Set(["AUTOFILL_CELL","SET_BORDER","SET_ZONE_BORDERS","SET_BORDERS_ON_TARGET"]),rp=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"]),op=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"]),np=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 sp(e){return np.has(e.type)}class ip{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>"Success"!==e)}static get Success(){return ap}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}const ap=new ip;var lp;function cp(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?function(e,t,r){const o="left"===t?"right":"bottom";let n=e[t],s=e[o];const i=e[o];for(const o of r.sort((e,t)=>t-e))e[t]>o&&(n--,void 0!==s&&s--),void 0!==i&&void 0!==s&&e[t]<=o&&i>=o&&s--;if(!(void 0!==s&&n>s))return{...e,[t]:n,[o]:s}}(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?function(e,t,r,o,n){const s="left"===t?"columns":"rows",i="before"===o?r-1:r,a=e["left"===t?"right":"bottom"];return e[t]<=i&&a&&a>i?bs(e,s,"RESIZE",n):i<e[t]?bs(e,s,"MOVE",n):{...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 o=cp(e._zone,t);if(o&&r!==e._sheetId)return{...e,_zone:o}}}!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"}(lp||(lp={}));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 o=t.map(e=>parseInt(e,10));255!==r&&o.push(r);return"#"+Ie(o.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,o=1){if(!bp(e)||!bp(t)||!bp(r)||o<0||o>1)throw new Error(`Invalid RGBA values ${[e,t,r,o]}`);return{a:o,b:r,g:t,r:e}}function yp(e){let{r:t,g:r,b:o}=Ep(e);t/=255,r/=255,o/=255;const n=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*n(t)+.7152*n(r)+.0722*n(o)}function wp(e){let t=e.r.toString(16),r=e.g.toString(16),o=e.b.toString(16),n=Math.round(255*e.a).toString(16);return 1===t.length&&(t="0"+t),1===r.length&&(r="0"+r),1===o.length&&(o="0"+o),1===n.length&&(n="0"+n),"ff"===n&&(n=""),("#"+t+r+o+n).toUpperCase()}function Ep(e){let t,r,o,n;if(7===(e=mp(e)).length)t=parseInt(e[1]+e[2],16),r=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),n=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),o=parseInt(e[5]+e[6],16),n=parseInt(e[7]+e[8],16)}return n=+(n/255).toFixed(3),{a:n,r:t,g:r,b:o}}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)),o=e.l-t/2;let n=0,s=0,i=0;return 0<=e.h&&e.h<60?(n=t,s=r,i=0):60<=e.h&&e.h<120?(n=r,s=t,i=0):120<=e.h&&e.h<180?(n=0,s=t,i=r):180<=e.h&&e.h<240?(n=0,s=r,i=t):240<=e.h&&e.h<300?(n=r,s=0,i=t):300<=e.h&&e.h<360&&(n=t,s=0,i=r),n=Math.round(255*(n+o)),s=Math.round(255*(s+o)),i=Math.round(255*(i+o)),{a:e.a,r:n,g:s,b:i}}function Cp(e){const t=e.r/255,r=e.g/255,o=e.b/255,n=Math.min(t,r,o),s=Math.max(t,r,o),i=s-n;let a=0,l=0,c=0;return a=0===i?0:s===t?(r-o)/i%6:s===r?(o-t)/i+2:(t-r)/i+4,a=Math.round(60*a),a<0&&(a+=360),c=(s+n)/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 wp(Sp(e))}function Ip(e){return Cp(Ep(e))}function xp(e){return Ep("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"],Fp=["#4EA7F2","#3188E6","#056BD9","#A76DBC","#7F4295","#6D2387","#EA6175","#CE4257","#982738","#43C5B1","#00A78D","#0E8270","#F4A261","#F48935","#BE5D10","#8481DD","#5752D1","#3A3580","#A4A8B6","#7E8290","#545B70","#FFD86D","#FFBC2C","#C08A16"],Dp=["#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 Pp{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){var r;this.preferredColors=t,this.palette=(r=e,r<=6?Op:r<=12?_p:r<=24?Fp:Dp).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 Lp extends Pp{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 Lp(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,o){const n=t-e;return[((r>>16)%256-(o>>16)%256)/n,((r>>8)%256-(o>>8)%256)/n,(r%256-o%256)/n]}function Bp(e,t,r,o){const[n,s,i]=o;return Math.round((r>>16)%256-n*(e-t))<<16|Math.round((r>>8)%256-s*(e-t))<<8|Math.round(r%256-i*(e-t))}const zp={hasFilters:!1,totalRow:!1,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,automaticAutofill:!0,styleId:"TableStyleMedium2"},$p={light:v("Light"),medium:v("Medium"),dark:v("Dark")};function Gp(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 Wp={black:{name:v("Black"),coloredText:"#000000",light:"#D9D9D9",medium:"#A6A6A6",dark:"#404040",mediumBorder:"#000000",highlight:"#000000"},lightBlue:Gp(v("Blue"),"#346B90"),red:Gp(v("Red"),"#C53628"),lightGreen:Gp(v("Green"),"#748747"),purple:Gp(v("Purple"),"#6C4E65"),gray:{name:v("Gray"),coloredText:"#666666",light:"#EEEEEE",medium:"#DDDDDD",dark:"#767676",mediumBorder:"#D0D0D0",highlight:"#A9A9A9"},orange:Gp(v("Orange"),"#C37034")},qp={black:Wp.black,orangeBlue:{...Wp.lightBlue,highlight:Wp.orange.highlight},purpleGreen:{...Wp.lightGreen,highlight:Wp.purple.highlight},redBlue:{...Wp.lightBlue,highlight:Wp.red.highlight}},Zp=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"}},style:{bold:!0}},totalRow:{border:{top:{color:e.highlight,style:"thin"}},style:{bold:!0}},firstRowStripe:{style:{fillColor:e.light}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}}}),Yp=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",bold:!0},border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}},style:{bold:!0}},firstRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}},secondRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}}}),jp=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"}},style:{bold:!0}},totalRow:{border:{top:{color:e.highlight,style:"medium"}},style:{bold:!0}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}}}),Xp=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",bold:!0}},totalRow:{border:{top:{color:e.highlight,style:"medium"}},style:{bold:!0}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}}}),Kp=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",bold:!0}},totalRow:{border:{top:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF",bold:!0}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF",bold:!0}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF",bold:!0}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),Qp=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"}},style:{bold:!0}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF",bold:!0},border:{bottom:{color:"#000000",style:"medium"}}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF",bold:!0}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF",bold:!0}},firstRowStripe:{style:{fillColor:Wp.black.light}},firstColumnStripe:{style:{fillColor:Wp.black.light}}}),Jp=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"}},style:{bold:!0}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}},headerRow:{style:{bold:!0}}}),eb=e=>({category:"dark",templateName:"dark",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{style:{fillColor:e.dark,textColor:"#FFFFFF",bold:!0},border:{top:{color:"#FFFFFF",style:"thick"}}},headerRow:{style:{fillColor:"#000000",bold:!0},border:{bottom:{color:"#FFFFFF",style:"thick"}}},firstColumn:{style:{fillColor:e.dark,bold:!0},border:{right:{color:"#FFFFFF",style:"thick"}}},lastColumn:{style:{fillColor:e.dark,bold:!0},border:{left:{color:"#FFFFFF",style:"thick"}}},firstRowStripe:{style:{fillColor:e.dark}},firstColumnStripe:{style:{fillColor:e.dark}}}),tb=e=>({category:"dark",templateName:"darkNoBorders",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.light}},totalRow:{border:{top:{color:"#000000",style:"medium"}},style:{bold:!0}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF",bold:!0}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}},firstColumn:{style:{bold:!0}},lastColumn:{style:{bold:!0}}}),rb=eb(Wp.black);rb.wholeTable.style.fillColor="#737373";const ob=Qp(Wp.black);function nb(e,t,r){return{...t(r),displayName:`${r.name}, ${e}`}}ob.wholeTable.border={...ob.wholeTable.border,left:{color:"#000000",style:"thin"},right:{color:"#000000",style:"thin"},horizontal:{color:"#000000",style:"thin"},vertical:{color:"#000000",style:"thin"}};const sb={None:{category:"light",templateName:"none",primaryColor:"",displayName:v("None")},TableStyleLight1:nb("TableStyleLight1",Zp,Wp.black),TableStyleLight2:nb("TableStyleLight2",Zp,Wp.lightBlue),TableStyleLight3:nb("TableStyleLight3",Zp,Wp.red),TableStyleLight4:nb("TableStyleLight4",Zp,Wp.lightGreen),TableStyleLight5:nb("TableStyleLight5",Zp,Wp.purple),TableStyleLight6:nb("TableStyleLight6",Zp,Wp.gray),TableStyleLight7:nb("TableStyleLight7",Zp,Wp.orange),TableStyleLight8:nb("TableStyleLight8",Yp,Wp.black),TableStyleLight9:nb("TableStyleLight9",Yp,Wp.lightBlue),TableStyleLight10:nb("TableStyleLight10",Yp,Wp.red),TableStyleLight11:nb("TableStyleLight11",Yp,Wp.lightGreen),TableStyleLight12:nb("TableStyleLight12",Yp,Wp.purple),TableStyleLight13:nb("TableStyleLight13",Yp,Wp.gray),TableStyleLight14:nb("TableStyleLight14",Yp,Wp.orange),TableStyleLight15:nb("TableStyleLight15",jp,Wp.black),TableStyleLight16:nb("TableStyleLight16",jp,Wp.lightBlue),TableStyleLight17:nb("TableStyleLight17",jp,Wp.red),TableStyleLight18:nb("TableStyleLight18",jp,Wp.lightGreen),TableStyleLight19:nb("TableStyleLight19",jp,Wp.purple),TableStyleLight20:nb("TableStyleLight20",jp,Wp.gray),TableStyleLight21:nb("TableStyleLight21",jp,Wp.orange),TableStyleMedium1:nb("TableStyleMedium1",Xp,Wp.black),TableStyleMedium2:nb("TableStyleMedium2",Xp,Wp.lightBlue),TableStyleMedium3:nb("TableStyleMedium3",Xp,Wp.red),TableStyleMedium4:nb("TableStyleMedium4",Xp,Wp.lightGreen),TableStyleMedium5:nb("TableStyleMedium5",Xp,Wp.purple),TableStyleMedium6:nb("TableStyleMedium6",Xp,Wp.gray),TableStyleMedium7:nb("TableStyleMedium7",Xp,Wp.orange),TableStyleMedium8:nb("TableStyleMedium8",Kp,Wp.black),TableStyleMedium9:nb("TableStyleMedium9",Kp,Wp.lightBlue),TableStyleMedium10:nb("TableStyleMedium10",Kp,Wp.red),TableStyleMedium11:nb("TableStyleMedium11",Kp,Wp.lightGreen),TableStyleMedium12:nb("TableStyleMedium12",Kp,Wp.purple),TableStyleMedium13:nb("TableStyleMedium13",Kp,Wp.gray),TableStyleMedium14:nb("TableStyleMedium14",Kp,Wp.orange),TableStyleMedium15:{...ob,displayName:"Black, TableStyleMedium15"},TableStyleMedium16:nb("TableStyleMedium16",Qp,Wp.lightBlue),TableStyleMedium17:nb("TableStyleMedium17",Qp,Wp.red),TableStyleMedium18:nb("TableStyleMedium18",Qp,Wp.lightGreen),TableStyleMedium19:nb("TableStyleMedium19",Qp,Wp.purple),TableStyleMedium20:nb("TableStyleMedium20",Qp,Wp.gray),TableStyleMedium21:nb("TableStyleMedium21",Qp,Wp.orange),TableStyleMedium22:nb("TableStyleMedium22",Jp,Wp.black),TableStyleMedium23:nb("TableStyleMedium23",Jp,Wp.lightBlue),TableStyleMedium24:nb("TableStyleMedium24",Jp,Wp.red),TableStyleMedium25:nb("TableStyleMedium25",Jp,Wp.lightGreen),TableStyleMedium26:nb("TableStyleMedium26",Jp,Wp.purple),TableStyleMedium27:nb("TableStyleMedium27",Jp,Wp.gray),TableStyleMedium28:nb("TableStyleMedium28",Jp,Wp.orange),TableStyleDark1:{...rb,displayName:"Black, TableStyleDark1"},TableStyleDark2:nb("TableStyleDark2",eb,Wp.lightBlue),TableStyleDark3:nb("TableStyleDark3",eb,Wp.red),TableStyleDark4:nb("TableStyleDark4",eb,Wp.lightGreen),TableStyleDark5:nb("TableStyleDark5",eb,Wp.purple),TableStyleDark6:nb("TableStyleDark6",eb,Wp.gray),TableStyleDark7:nb("TableStyleDark7",eb,Wp.orange),TableStyleDark8:nb("TableStyleDark8",tb,qp.black),TableStyleDark9:nb("TableStyleDark9",tb,qp.redBlue),TableStyleDark10:nb("TableStyleDark10",tb,qp.purpleGreen),TableStyleDark11:nb("TableStyleDark11",tb,qp.orangeBlue)},ib={none:()=>({category:"none",templateName:"none",primaryColor:"",name:"none"}),lightColoredText:Zp,lightAllBorders:jp,mediumAllBorders:Jp,lightWithHeader:Yp,mediumBandedBorders:Xp,mediumMinimalBorders:Qp,darkNoBorders:tb,mediumWhiteBorders:Kp,dark:eb};function ab(e,t,r){const o=Gp("",r);return{...ib[t](o),category:"custom",displayName:e}}function lb(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),o=r?{...e.pivot.dataSet,zone:r}:void 0;return{...e,pivot:{...e.pivot,dataSet:o}}}function cb(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 ub(e,t){if(e.sheetId!==t.sheetId)return e;const r=cp(e.zone,t);if(!r)return;const o=e.newTableRange?up(e.newTableRange,t):void 0;return{...e,newTableRange:o,zone:r}}function hb(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let r;if("REMOVE_COLUMNS_ROWS"===t.type)r=Gm(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){r=$m(Re(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==r?{...e,base:r}:void 0}function db(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;const r=le(e.start,e.end+1);let o=[];if("REMOVE_COLUMNS_ROWS"===t.type)o=Gm(t.elements,r);else if("ADD_COLUMNS_ROWS"===t.type){o=$m(Re(t.position,t.base),t.quantity,r)}return 0!==o.length?{...e,start:Math.min(...o),end:Math.max(...o)}:void 0}jm.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],hb),jm.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],hb),jm.addTransformation("DELETE_SHEET",["MOVE_RANGES"],function(e,t){const r=t.sheetId;if(e.targetSheetId===r||e.sheetId===r)return;return e}),jm.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART","UPDATE_CAROUSEL"],function(e,t){if(e.figureId===t.figureId)return;return e}),jm.addTransformation("DELETE_CHART",["UPDATE_CHART"],function(e,t){if(e.chartId===t.chartId)return;return e}),jm.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))}}}),jm.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}),jm.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],function(e,t){if(e.sheetId!==t.sheetId)return e;const r=[];for(const o of e.target)t.target.every(e=>!cs(o,e))&&r.push(o);if(r.length)return{...e,target:r};return}),jm.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],cb),jm.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],cb),jm.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],ub),jm.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],ub),jm.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}}}),jm.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],db),jm.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],db),jm.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],function(e,t){if(e.pivotId===t.pivotId)return;return e}),jm.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}),jm.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],lb),jm.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],lb);const fb=new dd,gb="000000",mb={arrows:"3Arrows",smiley:"3Symbols",dots:"3TrafficLights1"},pb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",bb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",vb="http://schemas.openxmlformats.org/package/2006/relationships",yb="http://schemas.openxmlformats.org/package/2006/content-types",wb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",Eb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",Sb="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",Cb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",Tb="http://schemas.microsoft.com/office/spreadsheetml/2014/revision",Ib="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3",xb="http://schemas.openxmlformats.org/markup-compatibility/2006",Rb="http://schemas.openxmlformats.org/drawingml/2006/main",Ab="http://schemas.openxmlformats.org/drawingml/2006/chart",Ob={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"},_b="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",Fb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",Db="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",Nb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",Mb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",Vb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",Pb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",Lb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",kb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",Ub="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",Hb="bdbb8cdc-fa1e-496e-a857-3c3f30c029c3",Bb="http://schemas.openxmlformats.org/officeDocument/2006/relationships",zb=.75,$b=.143,Gb=8.43,Wb=12.75,qb={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}]},Zb=["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"],Yb="[Content_Types].xml";function jb(e,t,r){if(!t.startsWith("="))return t;const o=Qg(t);for(let t=1;t<o.length;t++){if("REFERENCE"!==o[t].type)continue;const n=o[t].value,s=Xb(e,n,r);n!==s&&(o[t]={value:s,type:"REFERENCE"})}return Ie(o.map(e=>e.value))}function Xb(e,t,r){const o=xn(t).sheetName;if(o?!Ym(o,r.sheetName.old):e!==r.sheetId)return t;const n=function(e,t){if(!wn.test(e))return xm(e);return Im({xc:e,sheetId:t},Kb)}(t,o?r.sheetId:e);if(n.invalidXc)return t;const s=r.applyChange(n);return"NONE"===s.changeType||"REMOVE"===s.changeType?t:Om(s.range,e,function(e){return t=>t===e.sheetId?e.sheetName.current:""}(r))}function Kb(e){return{numberOfRows:Number.MAX_SAFE_INTEGER,numberOfCols:Number.MAX_SAFE_INTEGER}}function Qb(e){return e&&yp(e)<.3?"#FFFFFF":"#000000"}function Jb(e){return e&&yp(e)<.3?"#C8C8C8":"#666666"}function ev(e,t,r){const o=fb.getAll().find(e=>e.match(t.type));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t,r)}function tv(e,t){return(e=re(e)).pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=jb(e.computedBy.sheetId,e.computedBy.formula,t))}),e}function rv(e,t){return{...e,definition:ev(e.sheetId,e.definition,t)}}v("Left"),v("Right"),Xm.add("UPDATE_CELL",function(e,t){const r=e.content&&jb(e.sheetId,e.content,t);return{...e,content:r}}),Xm.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=>jb(e.sheetId,r,t))};else if("ColorScaleRule"===r.type){const{minimum:o,maximum:n,midpoint:s}=r;e.cf.rule={...r,minimum:{...o,value:o.value&&jb(e.sheetId,o.value,t)},maximum:{...n,value:n.value&&jb(e.sheetId,n.value,t)},midpoint:s?{...s,value:jb(e.sheetId,s.value,t)}:void 0}}else if("IconSetRule"===r.type){const{upperInflectionPoint:o,lowerInflectionPoint:n}=r;e.cf.rule={...r,upperInflectionPoint:{...o,value:jb(e.sheetId,o.value,t)},lowerInflectionPoint:{...n,value:jb(e.sheetId,n.value,t)}}}else"DataBarRule"===r.type&&(e.cf.rule={...r,rangeValues:r.rangeValues?Xb(e.sheetId,r.rangeValues,t):void 0});return e}),Xm.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=>jb(e.sheetId,r,t)),e}),Xm.add("ADD_PIVOT",tv),Xm.add("UPDATE_PIVOT",tv),Xm.add("CREATE_CHART",rv),Xm.add("UPDATE_CHART",rv);const ov=[{match:function(e){return"sheetId"in e},fn:iv},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const r=iv(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;const o=[];for(const r of e.target){const e=cp(r,t);e&&o.push(e)}if(!o.length)return"IGNORE_COMMAND";return{...e,target:o}}},{match:function(e){return"sheetId"in e&&"zone"in e},fn:function(e,t){const r=iv(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;const o=cp(e.zone,t);if(o)return{...e,zone:o};return"IGNORE_COMMAND"}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const r=iv(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 o=e[r];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort((e,t)=>t-e);if(e.includes(o))return"IGNORE_COMMAND";for(const t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[r]:o}}(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)&&us(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=iv(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 o=[];if("REMOVE_COLUMNS_ROWS"===t.type)o=Gm(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){o=$m(Re(t.position,t.base),t.quantity,e.elements)}if(0===o.length)return"IGNORE_COMMAND";return{...e,elements:o}}},{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=jm.getTransformation(e.type,t.type),o=r?r(e,t):function(e,t){for(const{match:r,fn:o}of ov)if(r(e)){const r=o(e,t);if("SKIP_TRANSFORMATION"===r)continue;if("IGNORE_COMMAND"===r)return;e=r}return e}(e,t);return o?function(e,t){const r=Xm.get(e.type);if(!r)return e;const o=Nm(t);if(o)return r(e,o);return e}(o,t):o}function sv(e,t){let r=[...e];const o=new Set(jm.getKeys());for(const e of t)(o.has(e.type)||Mm.contains(e.type))&&(r=r.reduce((t,r)=>{const o=nv(r,e);return o&&t.push(o),t},[]));return r}function iv(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 av{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,r,o,n,s){this.rootCommand=o,this.timestamp=s,this.id=e,this.clientId=t,this._commands=[...r],this._changes=n?[...n]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class lv extends Error{}class cv extends Cm{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Dn;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 o=new av(this.uuidGenerator.uuidv4(),this.clientId,t,e,r,Date.now());this.revisions.append(o.id,o),"REQUEST_REDO"!==e.type&&(this.lastLocalOperation=o),this.trigger("new-local-state-update",{id:o.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:o.id,clientId:o.clientId,commands:o.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 lv("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",o=this.getCurrentClient();this.clients[this.clientId]={...o,position:e},this.sendToTransport({type:r,version:1,client:{...o,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:o}=e,n=new av(e.nextRevisionId,t,r,void 0,void 0,o);if(n.clientId!==this.clientId){this.revisions.insert(n.id,n,e.serverRevisionId);const t=this.pendingMessages.filter(e=>"REMOTE_REVISION"===e.type).map(e=>e.commands).flat();this.trigger("remote-revision-received",{commands:sv(r,t)})}break;case"SNAPSHOT_CREATED":{const t=new av(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 lv))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 uv=(new dd).add("ADD_COLUMNS_ROWS",function(e){const t=[];let r=e.base;"after"===e.position&&r++;for(let o=0;o<e.quantity;o++)t.push(o+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 o of ce(r)){const r=0===o[0]?0:o[0]-1,n=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:r,sheetId:e.sheetId,sheetName:e.sheetName,position:n})}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 np.values())uv.contains(e)||uv.add(e,hv);function hv(e){return[e]}function dv(e){return uv.get(e.type)(e)}class fv{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:o,operation:n,after:s}=this.locateOperation(t);this.operations=[...o,n,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 fv(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 gv{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new mv(this.id,xe(()=>e(this.data)))}}class mv{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new mv(this.id,this.lazyData.map(e))}}class pv{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new pv(function*(e,t){for(const r of e)if(yield r,r.operation.id===t)return}(this.operations,e))}stopBefore(e){return new pv(function*(e,t){for(const r of e){if(r.operation.id===t)return;yield r}}(this.operations,e))}startAfter(e){return new pv(function*(e,t){let r=!0;for(const o of e)r||(yield o),o.operation.id===t&&(r=!1)}(this.operations,e))}}class bv{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 pv(ue(this._execution(e),this._execution(e)))}revertedExecution(e){return new pv(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),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const n=e.fork(t.id);o&&this.branchingOperationIds.set(n,o),this.insertBranchAfter(e,n),this.transform(n,r)}redo(e){const t=this.nextBranch(e);if(!t)return;const r=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):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 o=this.buildTransformation.without(r.data),n=t.fork(r.id);this.branchingOperationIds.set(n,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,n),n.transform(o);const s=this.nextBranch(n);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 o=this.branchingOperationIds.get(e),n=this.nextBranch(e);if(o&&n)if(e.getFirstOperationAmong(r,o)===o){const s=this.addToNextBranch(e,n,o,t,r);this.updateNextWith(n,s,r)}else{const e=this.buildTransformation.with(t.data);this.transform(n,e)}}addToNextBranch(e,t,r,o,n){let s=o;return n===r?(s=this.getTransformedOperation(e,r,o),t.prepend(s)):t.contains(n)?(s=this.getTransformedOperation(e,r,o),t.insert(s,n)):t.append(o),s}getTransformedOperation(e,t,r){const o=e.getOperation(t),n=this.buildTransformation.without(o.data);return r.transformed(n)}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:o,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!o||!n)return;const s=this.buildTransformation.with(n.data),i=e.fork(r);i.transform(s),o.cutAfter(r),o.appendBranch(i);const a=t.transformed(s);this.insertPrevious(o,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 o=e.getOperations();for(let n=o.length-1;n>=0;n--){const s=o[n];s.id===t&&(r=!1),r||(yield{operation:s,branch:e,isCancelled:!this.shouldExecute(e,s)})}const n=this.previousBranch(e);yield*n?this._revertedExecution(n):[]}*_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 vv{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 fv(this.buildTransformation),this.tree=new bv(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,r=new gv(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 gv(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,r),this.HEAD_BRANCH=o,this.HEAD_OPERATION=r}insert(e,t,r){const o=new gv(e,t);this.revertTo(r),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,r),this.fastForward()}undo(e,t,r){const{branch:o,operation:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,n),this.fastForward(),this.insert(t,this.buildEmpty(t),r)}redo(e,t,r){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),r)}rebase(e){const t=this.get(e),r=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);const o=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,o);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:o}of e)o||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:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=r}}function yv(e){return new vv({initialOperationId:e.initialRevisionId,applyOperation:t=>{const r=t.commands.slice(),{changes:o}=e.recordChanges(()=>{for(const t of r)e.dispatch(t)});t.setChanges(o)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){wv(t.changes[e])}}([e]),buildEmpty:e=>new av(e,"empty",[]),buildTransformation:{with:e=>t=>new av(t.id,t.clientId,sv(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new av(t.id,t.clientId,sv(t.commands,e.commands.map(dv).flat()),t.rootCommand,void 0,t.timestamp)}})}function wv(e){const t=e.target,r=e.key,o=e.before;void 0===o?delete t[r]:t[r]=o}class Ev{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const Sv=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart","comboChart","radarChart"],Cv="M256 9 a247 247 0 1 0.1 0 0";function Tv(e){return{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:e.textColor||U,path:"M120 195 h270 l-135 130"}]}}const Iv="M40 185 h270 l-135 128";function xv(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||U,path:Iv}]}}function Rv(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:Iv}]}}const Av={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"}]},Ov={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"}]},_v={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 Fv(e,t){return{name:"PIVOT_ICON",width:512,height:512,paths:[{path:"M21,21 h469 v469 h-469",fillColor:t?L:"#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?L:"#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:Cv}]}},dotNeutral:{template:"YELLOW_DOT",svg:{name:"YELLOW_DOT",width:512,height:512,paths:[{fillColor:"#F0AD4E",path:Cv}]}},dotBad:{template:"RED_DOT",svg:{name:"RED_DOT",width:512,height:512,paths:[{fillColor:"#E06666",path:Cv}]}}},Nv={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}};function Mv(e,t){const r=e.split("/"),o=t.split("/");let n="",s=0;for(let e=0;e<r.length-1;e++)r[e]===o[e]?s++:n+="../";return n+=o.slice(s).join("/"),n}function Vv(e,t=0){const r={};for(let o=0;o<e.length;o++)e[o]&&(r[o+t]=e[o]);return r}function Pv(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 kv(e){if("="===e[0])return e;const t=_l(e);return 1===t.length&&"REFERENCE"!==t[0].type?e:"="+e}var Uv;!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"}(Uv||(Uv={}));class Hv{_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 o=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;r&&(o+=`Only ${r.join(", ")} are currently supported.`),this._conversionWarnings.has(o)||this._conversionWarnings.add(o)}}const Bv=["thin","medium","thick","dashed","dotted"],zv=["general","left","center","right"],$v=["top","center","bottom"],Gv=["Arial"],Wv=["solid","none"],qv=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWithText","containsBlanks","notContainsBlanks"],Zv={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},Yv={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"},jv={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},Xv={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},Kv={top:"top",middle:"center",bottom:"bottom"},Qv={beginsWith:"beginsWithText",endsWith:"endsWithText",containsText:"containsText",notContains:"notContainsText",between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo",top10:"top10"},Jv={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},ey={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},ty={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"},ry={none:"none",b:"bottom",t:"top",l:"left",r:"right",tr:"right"},oy={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"},sy={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"},iy={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:"@"},ay={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},ly={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"},cy={"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"},uy={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"},hy={between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},dy={between:"dateIsBetween",notBetween:"dateIsNotBetween",equal:"dateIs",greaterThan:"dateIsAfter",greaterThanOrEqual:"dateIsOnOrAfter",lessThan:"dateIsBefore",lessThanOrEqual:"dateIsOnOrBefore"};function fy(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=gb;else{if(!e.indexed)return;t=ly[e.indexed]}return t=function(e){if(6===e.length)return"#"+e+"FF";return"#"+e.slice(2)+e.slice(0,2)}(t),e.tint&&(t=function(e,t){const r=Ep(e),o=Cp(r);t<0&&(o.l=o.l*(1+t));t>0&&(o.l=o.l*(1-t)+(100-100*(1-t)));return wp(Sp(o))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function gy(e){return 9===e.length&&(e=e.slice(0,7)),parseInt(e.replace("#",""),16)}const my=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function py(e,t,r){const o=iy[e]||t.find(t=>t.id===e)?.format;if("General"!==o){if(o)try{let e=o.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 my.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 Qr(0,{format:e,locale:Ar}),!0}catch(e){return!1}}(e))return e}catch(e){}r.generateNotSupportedWarning(Uv.NumFmtIdNotSupported,o||`nmFmtId ${e}`)}}function by(e,t){const r=e.borders.map(e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(Uv.DiagonalBorderNotSupported)}(e,t);const r={top:vy(e.top,t),bottom:vy(e.bottom,t),left:vy(e.left,t),right:vy(e.right,t)};return Object.keys(r).forEach(e=>void 0===r[e]&&delete r[e]),r});return Vv(r,1)}function vy(e,t){if(!e)return;!function(e,t){Bv.includes(e.style)||t.generateNotSupportedWarning(Uv.BorderStyleNotSupported,e.style,Bv)}(e,t);const r=Yv[e.style];return r?{style:r,color:fy(e.color)}:void 0}function yy(e,t){return Vv(e.styles.map(r=>wy({fontStyle:e.fonts[r.fontId],fillStyle:e.fills[r.fillId],alignment:r.alignment},t)),1)}function wy(e,t){return function(e,t,r){e&&e.name&&!Gv.includes(e.name)&&r.generateNotSupportedWarning(Uv.FontNotSupported,e.name,Gv);t&&t.patternType&&!Wv.includes(t.patternType)&&r.generateNotSupportedWarning(Uv.FillStyleNotSupported,t.patternType,Wv)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!zv.includes(e)&&t.generateNotSupportedWarning(Uv.HorizontalAlignmentNotSupported,e,zv)}(e?.alignment?.horizontal,t),function(e,t){e&&!$v.includes(e)&&t.generateNotSupportedWarning(Uv.VerticalAlignmentNotSupported,e,$v)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?Xv[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?jv[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?fy(e.fillStyle?.fgColor):fy(e.fillStyle?.bgColor),textColor:fy(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function Ey(e,t){const r=[];for(const o of e.styles){const n=py(o.numFmtId,e.numFmts,t);n&&(r[o.numFmtId]=n)}return Vv(r,1)}function Sy(e,t,r){const o=[];let n=1;for(const s of e){if(0===s.cfRules.length)continue;Ry(s,t,r);const e=s.cfRules[0];let i;const a=[],l={};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"uniqueValues":case"timePeriod":continue;case"dataBar":const t=Cy(n++,s);t&&o.push(t);continue;case"colorScale":const c=Ty(n++,s);c&&o.push(c);continue;case"iconSet":const u=Iy(n++,s,r);u&&o.push(u);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;i=Jv[e.type],a.push(e.text);break;case"expression":if(!e.formula?.length)continue;i=Jv[e.type],a.push(`=${e.formula[0]}`);break;case"containsBlanks":case"notContainsBlanks":i=Jv[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;i=Qv[e.operator],a.push(kv(e.formula[0])),2===e.formula.length&&a.push(kv(e.formula[1]));break;case"top10":if(void 0===e.rank)continue;i=Qv[e.type],a.push(e.rank.toString()),e.percent&&(l.isPercent=!0),e.bottom&&(l.isBottom=!0)}i&&void 0!==e.dxfId&&o.push({id:(n++).toString(),ranges:s.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:i,values:a,...l,style:wy({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},r)}})}}return o}function Cy(e,t){const r=t.cfRules[0].dataBar;if(!r)return;const o=gy(fy(r.color)||"#FFFFFF");return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"DataBarRule",color:o}}}function Ty(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 o=[];for(let e=0;e<r.cfvos.length;e++)o.push({color:gy(fy(r.colors[e])||"#FFFFFF"),type:ey[r.cfvos[e].type],value:r.cfvos[e].value});const n=o[0],s=2===o.length?o[1]:o[2],i=3===o.length?o[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:n,midpoint:i,maximum:s}}}function Iy(e,t,r){const o=t.cfRules[0].iconSet;if(!o)return;let n=o.cfvos,s=o.cfIcons;if(n.length<3||s&&s.length<3)return;n.length>3&&(n=[n[0],n[Math.floor(n.length/2)],n[n.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=ey[n[e].type];if("value"===t)return;i.push({value:n[e].value||"",operator:n[e].gte?"ge":"gt",type:t})}let a={lower:s?xy(s[0].iconSet,s[0].iconId):xy(o.iconSet,0),middle:s?xy(s[1].iconSet,s[1].iconId):xy(o.iconSet,1),upper:s?xy(s[2].iconSet,s[2].iconId):xy(o.iconSet,2)};o.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(const e of Object.keys(a))if(!a[e])switch(r.generateNotSupportedWarning(Uv.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=Nv.dots.good;break;case"middle":a[e]=Nv.dots.neutral;break;case"lower":a[e]=Nv.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=ty[e];return r?0===t?Nv[r].bad:1===t?Nv[r].neutral:Nv[r].good:""}function Ry(e,t,r){if(e.cfRules.length>1&&r.generateNotSupportedWarning(Uv.MultipleRulesCfNotSupported),qv.includes(e.cfRules[0].type)||r.generateNotSupportedWarning(Uv.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const o=t[e.cfRules[0].dxfId];o.border&&r.generateNotSupportedWarning(Uv.CfFormatBorderNotSupported),o.alignment&&r.generateNotSupportedWarning(Uv.CfFormatAlignmentNotSupported),o.numFmt&&r.generateNotSupportedWarning(Uv.CfFormatNumFmtNotSupported)}}const Ay=new WeakMap,Oy=new WeakMap;function _y(e,t){Ay.has(t)||(Ay.set(t,new Map),Oy.set(t,0));const r=Ay.get(t),o=Ny(e);if(r.has(o)){const n=r.get(o);return t[n]=e,n}const n=Oy.get(t)+1;return r.set(o,n),Oy.set(t,n),t[n]=e,n}function Fy(e){const t={};for(const r in e){const o=Gn(e[r].map(vs));for(const e of o)t[rs(e)]=Number(r)}return t}function*Dy(e,t){for(const r in t){const o=Jn(r),n=t[r];for(let t=o.top;t<=o.bottom;t++)for(let r=o.left;r<=o.right;r++){const o={sheetId:e,col:r,row:t};yield[o,n]}}}function Ny(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 o=0;o<t;o++)o>0&&(r+=","),r+=Ny(e[o]);return r+"]"}const t=Object.keys(e).sort();let r="{";for(const o of t)void 0!==e[o]&&(r+=`"${o}":${Ny(e[o])},`);return r+="}",r}function My(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"";case"top10":return"top10"}}function Vy(e){return Math.round(zb*e*100)/100}function Py(e){return Math.round($b*e*100)/100}function Ly(e){return e?Math.round(e/zb*100)/100:e}function ky(e){return e?Math.round(e/$b*100)/100:e}function Uy(e,t,r,o,n){const s=r?e.styles[r]:{},i=o?e.formats[o]: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:n||0,alignment:{horizontal:s.align,vertical:s.verticalAlign?Kv[s.verticalAlign]:void 0,wrapText:!("wrap"!==s.wrapping&&!t?.includes(Q))||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 Hy(e,t){const r=function(e,t){if(!e)return 0;let r=ay[e.format];r||(r=$y(e,t)+164);return r}(t.numFmt,e.numFmts),o={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}};return $y(o,e.styles)}function By(e,t,r){const o=e.find(e=>e.path===t);let n;return o?(n=`rId${(o.rels.length+1).toString()}`,o.rels.push({...r,id:n})):(n="rId1",e.push({path:t,rels:[{...r,id:n}]})),n}const zy=new WeakMap;function $y(e,t){let r=zy.get(t);if(!r){r=new Map;for(let e=0;e<t.length;e++){const o=Ny(t[e]);r.set(o,e)}zy.set(t,r)}const o=Ny(e);if(r.has(o))return r.get(o);const n=t.length;return t.push(e),r.set(o,n),n}function Gy(e,t){const r=t.chartIds.findIndex(t=>t===e);return-1===r?(t.chartIds.push(e),t.chartIds.length):r+1}const Wy=[];function qy(e){const t=Wy.findIndex(t=>t===e);return-1===t?(Wy.push(e),Wy.length):t+1}function Zy(e){return Math.round(914400*e/96)}function Yy(e,t,r){let o,n,s=e;if(({xc:s,sheetName:o}=xn(e)),o){const e=r.sheets.findIndex(e=>Ym(e.name,o));if(e<0)throw new Error("Unable to find a sheet with the name "+o);n=e}else n=Number(t);const i=Qn(s);return void 0===i.right&&(i.right=r.sheets[n].colNumber),void 0===i.bottom&&(i.bottom=r.sheets[n].rowNumber),(i.right-i.left+1)*(i.bottom-i.top+1)}function jy(e){return Math.round(96*e/914400)}function Xy(e,t){let r=0;for(let o=0;o<e;o++){const e=t.cols.find(e=>o>=e.min&&o<=e.max);e?.width?r+=e.width:t.sheetFormat?.defaultColWidth?r+=t.sheetFormat.defaultColWidth:r+=Gb}return r/$b}function Ky(e,t){let r=0;for(let o=0;o<e;o++){const e=t.rows.find(e=>e.index-1===o);e?.height?r+=e.height:t.sheetFormat?.defaultRowHeight?r+=t.sheetFormat.defaultRowHeight:r+=Wb}return r/zb}function Qy(e){let t=1;return e.figures.map(r=>function(e,t,r){let o,n,s,i,a;if(1===e.anchors.length)({col:o,row:n,offset:s}=rw(e.anchors[0])),a=jy(e.figureSize.cx),i=jy(e.figureSize.cy);else{({col:o,row:n,offset:s}=rw(e.anchors[0]));const{x:t,y:l}=ow(e.anchors[0],r),{x:c,y:u}=ow(e.anchors[1],r);a=c-t,i=u-l}const l={id:t,col:o,row:n,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:jy(e.data.size.cx),height:jy(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?ew(e.labelRange,t):void 0,o=e.dataSets.map(e=>{let r;return e.label&&"text"in e.label&&(r=e.label.text),{dataRange:ew(e.range,t),label:r,backgroundColor:e.backgroundColor,trend:tw(e.trend)}});"pie"===e.type&&o.reverse();const n={range:o,dataSetsHaveTitle:t,auxiliaryRange:r,title:e.title??{text:""},background:fy({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 fb.get(e.type).getChartDefinitionFromContextCreation(n)}catch(e){return}}function ew(e,t){const{sheetName:r,xc:o}=xn(e);let n=Qn(o);if(t&&void 0!==n.bottom&&void 0!==n.right){const e=n.bottom-n.top+1,t=n.right-n.left+1;1===e?n={...n,left:n.left-1}:1===t&&(n={...n,top:n.top-1})}return Rn(r,rs(n))}function tw(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 rw(e){const t={x:jy(e.colOffset)-1,y:jy(e.rowOffset)-1};return{col:e.col,row:e.row,offset:t}}function ow(e,t){return{x:Xy(e.col,t)+jy(e.colOffset),y:Ky(e.row,t)+jy(e.rowOffset)}}function nw(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const sw=new dd;function iw(e,t){return{url:e=nw(e),label:t||e,isExternal:!0,isUrlEditable:!0}}sw.add("sheet_URL",{match:e=>ye(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const r=Ee(e);return t.tryGetSheetName(r)||v("Invalid sheet")},open(e,t){const r=Ee(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 aw={createLink:iw,match:e=>me(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function lw(e){if("string"==typeof e){if(ge(e)){const{label:t,url:r}=be(e);return function(e){return sw.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||aw}(r).createLink(r,t)}return me(e)?iw(e):void 0}}function cw(e,t,r){return hw({value:yo(t.format)&&null!==e.parsedValue?e.content:e.parsedValue,format:t.format,origin:r},t.locale)}function uw(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(_t(e,Ar))return Dt(e,Ar);const r=mt(e,t);return r?r.value:he(e)?"TRUE"===e.toUpperCase():e}function hw(e,t=Ar,r,o){const n=lw(e.value);if(!n){return mw(dw(e,t,r),e.origin??o)}const s=uw(n.label,t);return mw({...dw({value:s,format:e.format||("number"==typeof s?uo(n.label,t)||ho(n.label):void 0)},t,r),link:n},e.origin??o)}function dw(e,t,r){let{value:o,format:n,message:s}=e;n=r?.format||n;const i=Qr(o,{format:n,locale:t});return Pt(o)?function(e,t){return{value:e,formattedValue:e,message:t,type:wu.error,isAutoSummable:!1,defaultAlign:"center"}}(o,s):null===o?gw(n):yo(n)?fw(Wt(o),n,i):"number"==typeof o?io(n||"")?function(e,t,r){return{value:e,format:t,formattedValue:r,type:wu.number,isAutoSummable:!1,defaultAlign:"right"}}(o,n,i):function(e,t,r){return{value:e||0,format:t,formattedValue:r,type:wu.number,isAutoSummable:!0,defaultAlign:"right"}}(o,n,i):"boolean"==typeof o?function(e,t,r){return{value:e,format:t,formattedValue:r,type:wu.boolean,isAutoSummable:!1,defaultAlign:"center"}}(o,n,i):fw(o,n,i)}function fw(e,t,r){return{value:e,format:t,formattedValue:r,type:wu.text,isAutoSummable:!0,defaultAlign:"left"}}const gw=Ue(function(e){return{value:null,format:e,formattedValue:"",type:wu.empty,isAutoSummable:!0,defaultAlign:"left"}});function mw(e,t){return null===e.value||"origin"in e||(e.origin=t),e}function pw(e){const t=Je.now();switch(e){case"today":return Math.floor(vt(t));case"yesterday":return t.setDate(t.getDate()-1),Math.floor(vt(t));case"tomorrow":return t.setDate(t.getDate()+1),Math.floor(vt(t));case"lastWeek":return t.setDate(t.getDate()-6),Math.floor(vt(t));case"lastMonth":{const e=0===t.getMonth()?11:t.getMonth()-1,r=new Je(t.getFullYear(),e,1);return t.getDate()>yt(r)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(vt(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(vt(t))}}function bw(e,t){return"dateValue"in e&&"exactDate"!==e.dateValue?[pw(e.dateValue)]:e.values.map(e=>dt(e,t))}function vw(e,t){return e.map(e=>{if(e.startsWith("="))return e;const r=uw(e,t);return"number"==typeof r?Qr(r,{format:t.dateFormat,locale:t}):""})}function yw(e,t){const r=[];let o=1;for(const n of e)if(n)switch(n.type){case"time":t.generateNotSupportedWarning(Uv.TimeDataValidationNotSupported);break;case"textLength":t.generateNotSupportedWarning(Uv.TextLengthDataValidationNotSupported);break;case"whole":t.generateNotSupportedWarning(Uv.WholeNumberDataValidationNotSupported);break;case"decimal":const e=ww(o++,n);r.push(e);break;case"list":const s=Ew(o++,n);r.push(s);break;case"date":if("notEqual"===n.operator){t.generateNotSupportedWarning(Uv.NotEqualDateDataValidationNotSupported);break}const i=Sw(o++,n);r.push(i);break;case"custom":const a=Cw(o++,n);r.push(a)}return r}function ww(e,t){const r=[kv(t.formula1.toString())];return t.formula2&&r.push(kv(t.formula2.toString())),{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:hy[t.operator],values:r}}}function Ew(e,t){const r=t.formula1.toString(),o=wn.test(r);return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:o?"isValueInRange":"isValueInList",values:o?[r]:r.replaceAll('"',"").split(","),displayStyle:"arrow"}}}function Sw(e,t){let r;const o=[kv(t.formula1.toString())];return t.formula2?(o.push(kv(t.formula2.toString())),r={type:dy[t.operator],values:vw(o,Ar)}):r={type:dy[t.operator],values:vw(o,Ar),dateValue:"exactDate"},{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:r}}function Cw(e,t){return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:"customFormula",values:[kv(t.formula1.toString())]}}}const Tw=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),Iw=new RegExp(/SUBTOTAL\(([0-9]*),/g),xw=new RegExp(gn.source,"ig");function Rw(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 o of e.rows.map(e=>e.cells).flat())o?.formula&&(o.formula.content=void 0===o.formula.sharedIndex||o.formula.content?"="+o.formula.content:"="+Ow(o.xc,r[o.formula.sharedIndex]),o.formula.content=Aw(o.formula.content,t))}function Aw(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(Iw,(e,t)=>{const r=sy[t];return r?r+"(":e})).replace(Tw,(e,r,o,n)=>{r=Number(r)-1,n=n.replace(/\$/g,"");const s=t.externalBooks[r].sheetNames.findIndex(e=>Ym(e,o));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[n];return(Number(a)?a:`"${a}"`)||e})}function Ow(e,t){const r=zn(t.refCellXc);let o,n=t.formula.slice();do{if(o=xw.exec(n),o){const t=zn(o[0].replace("$","")),s=zn(e),i={colFixed:o[0].startsWith("$"),rowFixed:o[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};n=n.slice(0,o.index)+$n(l.col,l.row,i)+n.slice(o.index+o[0].length)}}while(o);return n}function _w(e,t){return e.sheets.map(r=>{Rw(r,e);const o=function(e){const t=[0,0];for(const r of e.rows)t[0]=Math.max(t[0],We(r.cells.map(e=>zn(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),n=r.sheetViews[0],s=Vw(r,"ROW",o[1]),i=Vw(r,"COL",o[0]);return{id:r.sheetName,areGridLinesVisible:!n||n.showGridLines,name:r.sheetName,colNumber:o[0],rowNumber:o[1],...Nw(r,e,o,t),merges:r.merges,cols:Fw(r,o[0],i),rows:Dw(r,o[1],s),conditionalFormats:Sy(r.cfs,e.dxfs,t),dataValidationRules:yw(r.dataValidations,t),figures:Qy(r),isVisible:r.isVisible,panes:n?{xSplit:n.pane.xSplit,ySplit:n.pane.ySplit}:{xSplit:0,ySplit:0},tables:[],headerGroups:{COL:i,ROW:s},color:fy(r.sheetProperties?.tabColor)}})}function Fw(e,t,r){const o={};for(let n=1;n<t+1;n++){const t=e.cols.find(e=>e.min<=n&&n<=e.max);let s;s=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:Gb;const i=n-1,a=r.some(e=>e.isFolded&&e.start<=i&&i<=e.end);o[i]={size:ky(s),isHidden:!a&&t?.hidden}}return o}function Dw(e,t,r){const o={};for(let n=1;n<t+1;n++){const t=e.rows.find(e=>e.index===n);let s;s=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:Wb;const i=n-1,a=r.some(e=>e.isFolded&&e.start<=i&&i<=e.end);o[i]={size:Ly(s),isHidden:!a&&t?.hidden}}return o}function Nw(e,t,r,o){const n={},s={},i={},a={},l=t.sharedStrings.map(Le);const c=e.hyperlinks.reduce((e,t)=>(e[t.xc]=t,e),{});for(const r of e.rows)for(const e of r.cells)n[e.xc]=Mw(e,c,l,o),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 o of e.rows.filter(e=>e.styleIndex))for(let e=1;e<=r[0];e++){const r=$n(e-1,o.index-1);s[r]??=o.styleIndex+1,a[r]??=t.styles[o.styleIndex].borderId+1,i[r]??=t.styles[o.styleIndex].numFmtId+1}for(const o of e.cols.filter(e=>e.styleIndex))for(let e=o.min;e<=Math.min(o.max,r[0]);e++)for(let n=1;n<=r[1];n++){const r=$n(e-1,n-1);s[r]??=o.styleIndex+1,a[r]??=t.styles[o.styleIndex].borderId+1,i[r]??=t.styles[o.styleIndex].numFmtId+1}return{cells:n,styles:s,formats:i,borders:a}}function Mw(e,t,r,o){let n;switch(e.type){case"sharedString":n=r[parseInt(e.value,10)];break;case"boolean":n=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":n=e.value}return n&&t[e.xc]&&(n=function(e,t,r){const o=e.display||t;e.relTarget||e.location||r.generateNotSupportedWarning(Uv.BadlyFormattedHyperlink);const n=e.relTarget?e.relTarget:we(xn(e.location).sheetName);return pe(o,n)}(t[e.xc],n,o)),e.formula&&(n=e.formula.content),n}function Vw(e,t,r){const o=e?.sheetProperties?.outlinePr,n=[];let s=0;for(let i=0;i<r;i++){const r=Lw(e,t,i),a=r?.outlineLevel||0;if(a>s){const r=Pw(e,t,i,("ROW"===t?o?.summaryBelow:o?.summaryRight)??!0);r&&n.push(r)}s=a}return n}function Pw(e,t,r,o){const n=Lw(e,t,r),s=n?.outlineLevel;if(!s||!s)return;let i=s,a=r,l=n;for(;l&&i>=s;)a++,l=Lw(e,t,a),i=l?.outlineLevel||0;const c=r,u=a-1,h=Lw(e,t,o?u+1:c-1);return{start:c-1,end:u-1,isFolded:h?.collapsed||!1}}function Lw(e,t,r){return"COL"===t?e.cols.find(e=>e.min<=r&&r<=e.max):e.rows.find(e=>e.index===r)}function kw(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:Uw(e)});for(const e of r.pivotTables)t.tables.push({range:e.location.ref,config:Hw(e)})}}!function(e,t){let r=null;for(const o of e){const n=t.find(e=>Ym(e.sheetName,o.name)).tables;if(n&&0!==n.length){r||(r=Bw(e));for(const t of n)for(const n in r){const s=e.find(e=>e.id===n);for(const e in r[n]){for(let i=r[n][e].length-3;i>=0;i-=2){const a=r[n][e][i];if(!a.endsWith(t.name))continue;const l=r[n][e][i+1],c=zw(o.id===s.id?"":o.name+"!",l,t,e);r[n][e][i+2]=a.slice(0,a.indexOf(t.name))+c+r[n][e][i+2],r[n][e].splice(i,2)}}}}}if(!r)return;for(const t in r){const o=e.find(e=>e.id===t);for(const e in r[t]){const n=r[t][e];if(1===n.length){o.cells[e]=n[0];continue}let s="";for(let e=0;e<n.length;e+=2)s+=n[e]+"["+n[e+1]+"]";s+=n[n.length-1],o.cells[e]=s}}}(e.sheets,t.sheets)}function Uw(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:sb[t]?t:zp.styleId}}function Hw(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 Bw(e){const t={};for(const r of e)for(const e in r.cells){const o=r.cells[e];if(!o||!o.startsWith("="))continue;const n=o.indexOf("[");if(-1===n)continue;const s=[];let i=o.slice(0,n),a="",l=1,c=0,u=n;for(let e=n+1;e<o.length;e++)"["!==o[e]?"]"===o[e]&&(l--,0===l&&(a=o.slice(u+1,e),s.push(i),s.push(a),c=e+1)):(0===l&&(i=o.slice(c,e),u=e),l++);s.length&&(t[r.id]||(t[r.id]={}),s.push(o.slice(c)),t[r.id][e]=[...s])}return t}function zw(e,t,r,o){const n=t.split(",").map(e=>e.trim()),s=Jn(r.ref),i=[],a=[],l=[];for(const e of n)if($w(e).startsWith("#")){const t=$w(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(zn(o).row);break;case"#Headers":if(!r.headerRowCount)return w.InvalidReference;a.push(s.top);break;case"#Totals":if(!r.totalsRowCount)return w.InvalidReference;a.push(s.bottom)}}else{const t=e.split(":").map(e=>e.trim()).map($w);if(i.length)return w.InvalidReference;const o=r.cols.findIndex(e=>e.name===t[0]);if(-1===o)return w.InvalidReference;if(i.push(o+s.left),t[1]){const e=r.cols.findIndex(e=>e.name===t[1]);if(-1===e)return w.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 w.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+rs({top:Math.min(...a),left:Math.min(...i),bottom:Math.max(...a),right:Math.max(...i)})}function $w(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,e.length-1):e}function Gw(e,t,r){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:r}}function Ww(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 qw(e){return new Ev(e.map(([e,t])=>`${e}="${Ww(t)}"`).join(" "))}function Zw(e,t="text/xml"){const r=(new DOMParser).parseFromString(e.toString(),t),o=r.querySelector("parsererror");if(o){const t=o.innerHTML,r=parseInt(t.split(":")[0],10),n=e.toString().trim().split("\n"),s=n.slice(Math.max(r-3,0),Math.min(r+2,n.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${s}`)}return r}function Yw(e){if(e)return{style:e.style,color:{rgb:e.color}}}function jw(e,t){return Kw`
2
- <Override ContentType="${t}" PartName="${e}" />
3
- `}function Xw(e){return new Ev(e.join("\n"))}function Kw(e,...t){const r=[e[0]];for(let o=0;o<t.length;o++){const n=t[o]instanceof Ev?t[o]:Ww(t[o]);r.push(n+e[o+1])}return new Ev(Ie(r))}function Qw(e){return e.replace(/NAMESPACE.*NAMESPACE(.*)/,"$1")}function Jw(e){return e.replaceAll(/(<\/?)([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"$1NAMESPACE$2NAMESPACE$3")}function eE(e){return e.replaceAll(/([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"NAMESPACE$1NAMESPACE$2")}class tE{value;constructor(e){this.value=e}asString(){return Pv(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class rE{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=[],o=this.currentFile;let n;if(e.children){const t=this.querySelector(e.parent,e.query)?.children;n=t||[]}else n=this.querySelectorAll(e.parent,e.query);if(n)for(const e of n)try{r.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=o,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 o=e.attributes[t];o||this.handleMissingValue(e,`attribute "${t}"`,r);const n=o?.value?o.value:r?.default;return void 0===n?void 0:new tE(n)}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 o=e?.textContent;return e&&null!==o||this.handleMissingValue(e,"text content",t),o&&(o=r?o:o.trim()),o?Pv(o):t?.default}extractChildAttr(e,t,r,o){let n;n="number"==typeof t?e.children[t]:this.querySelector(e,t),n||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,o);const s=n?this.extractAttr(n,r,o)?.asString():o?.default;return void 0!==s?new tE(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 o=this.querySelector(e,t);return o||this.handleMissingValue(e,`child <${t}>`,r),o?this.extractTextContent(o,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 o=this.extractAttr(e,"theme")?.asString();let n;if(void 0!==o){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");n=this.getThemeColor(o,t.clrScheme)}else n=this.extractAttr(e,"rgb")?.asString(),n="FF000000"===n?void 0:n;return{rgb:n||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=eE(t);return e.querySelector(r)}querySelectorAll(e,t){const r=eE(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 oE extends rE{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:gb}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:gb}).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 nE extends rE{theme;constructor(e,t,r,o){super(e,t,r),this.theme=o}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 sE extends rE{theme;constructor(e,t,r,o){super(e,t,r),this.theme=o}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 iE extends rE{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},e=>{const t=this.getChartType(e);if(!oy[t])throw new Error(`Unsupported chart type ${t}`);if("combo"===oy[t])return this.extractComboChart(e);const r=this.mapOnElements({parent:e,query:"c:chart > c:title a:t"},e=>e.textContent||"").join(""),o=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString(),n=this.extractChildAttr(e,"c:barDir","val",{default:"col"}).asString(),s=this.extractChildAttr(e,"c:holeSize","val",{default:"0"}).asNum();return{title:{text:r},type:oy[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:ry[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===o,fontColor:"000000",horizontal:"bar"===n,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:ry[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 o=this.querySelectorAll(e,"c:spPr a:solidFill"),n=o.length?this.querySelector(o[0],"a:srgbClr"):void 0,s=n?n.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"),o=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:o&&pp(o.asString())?`${mp(o.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"),o=r.length?r[0].getAttribute("val"):void 0,n=this.extractChildTextContent(e,"c:tx c:f");if(n)t={reference:n};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:o&&pp(o)?`${mp(o)}`: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=Qw(e.tagName);Sv.some(e=>e===t)&&(r?r!==t&&(r="comboChart"):r=t)}if(r)return r;throw new Error("Unknown chart type")}}const aE="oneCellAnchor",lE="twoCellAnchor";class cE extends rE{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},e=>{const t=Qw(e.tagName),r=this.extractFigureAnchorsByType(e,t),o=this.querySelector(e,"c:chart"),n=this.querySelector(e,"a:blip");if(!o&&!n)throw new Error("Only chart and image figures are currently supported.");return{anchors:r,data:o?this.extractChart(o):this.extractImage(e),figureSize:t===aE?this.extractFigureSizeFromSizeTag(e,"xdr:ext"):void 0}})}extractFigureAnchorsByType(e,t){switch(t){case aE:return[this.extractFigureAnchor("xdr:from",e)];case lE: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]),o=new iE(r,this.xlsxFileStructure,this.warningManager).extractChart();if(!o)throw new Error("Unable to extract chart definition");return o}extractImage(e){const t=this.querySelector(e,"a:blip"),r=this.extractAttr(t,"r:embed",{required:!0}).asString(),o=this.getTargetImageFile(this.relationships[r]);if(!o)throw new Error("Unable to extract image");const n=o.fileName.split(".").at(-1),s=Qw(e.tagName),i=s===lE?this.querySelector(e,"a:xfrm"):e,a=s===lE?"a:ext":"xdr:ext",l=this.extractFigureSizeFromSizeTag(i,a);return{imageSrc:o.imageSrc,mimetype:n?uy[n]:void 0,size:l}}}class uE extends rE{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 hE extends rE{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 dE extends rE{theme;constructor(e,t,r,o){super(e,t,r),this.theme=o}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=Mv(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=Mv(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 nE(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new sE(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 cE(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 hE(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 uE(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:Gb.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:Wb.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(),o=this.extractCellFormula(e);if(o?.ref&&void 0===o.sharedIndex){const e=Jn(o.ref);for(const{col:o,row:n}of gs(e)){const e=$n(o,n);e!==r&&t.add(e)}}const n=t.has(r);return{xc:r,styleIndex:this.extractAttr(e,"s")?.asNum(),type:Zv[this.extractAttr(e,"t",{default:"n"})?.asString()],value:n?void 0:this.extractChildTextContent(e,"v")??void 0,formula:n?void 0:o}})}extractCellFormula(e){const t=this.querySelector(e,"f");if(!t)return;const r=this.extractTextContent(t),o=this.extractAttr(t,"si")?.asNum(),n=this.extractAttr(t,"ref")?.asString();return void 0!==r&&""!==r.trim()||void 0!==o?{content:r,sharedIndex:o,ref:n}: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(),o=this.extractTextContent(e,{required:!0});r[t]=o}const o=[];for(let e=0;e<Object.keys(r).length;e++)r[e]?o.push(r[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),o.push(""));return o}}class fE extends rE{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(),o=this.extractColor(this.querySelector(e,"color"),this.theme),n=this.querySelector(e,"i")||void 0,s=n&&"0"!==n.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:o,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 o=this.querySelector(e,t);if(o&&o.attributes.style)return{style:this.extractAttr(o,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(o.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"),o=this.querySelector(e,"border"),n=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:n?this.extractNumFormats(n):void 0,alignment:s?this.extractAlignment(s):void 0,border:o?this.extractBorder(o):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 gE extends rE{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 mE(e,t){const r=function(e,t){const r=t[Yb],o=r.querySelectorAll(`Override[ContentType="${e}"]`),n=[];for(const e of o){const t=e?.attributes.PartName.value;n.push(t.substring(1))}return n}(e,t);return function(e,t){const r=[];for(const o of e){const e=pE(o,t);r.push({file:{fileName:o,xml:t[o]},rels:e?{fileName:e,xml:t[e]}:void 0})}return r}(r,t)}function pE(e,t){if(e===Yb)return"_rels/.rels";let r="";const o=e.split("/");for(let e=0;e<o.length-1;e++)r+=o[e]+"/";return r+="_rels/",r+=o[o.length-1]+".rels",t[r]||(r=void 0),r}class bE{warningManager;xmls;images;constructor(e){this.warningManager=new Hv,this.xmls={},this.images=[];for(const t of Object.keys(e))if(t.endsWith(".xml")||t.endsWith(".rels")){const r=Jw(e[t]);this.xmls[t]=Zw(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 oE(e.theme,e,this.warningManager).getTheme():void 0,r=e.sharedStrings?new oE(e.sharedStrings,e,this.warningManager).getSharedStrings():[],o=e.sheets.sort((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0})).map(r=>new dE(r,e,this.warningManager,t).getSheet()),n=e.externalLinks.map(t=>new gE(t,e,this.warningManager).getExternalBook()),s=new fE(e,this.warningManager,t);return{fonts:s.getFonts(),fills:s.getFills(),borders:s.getBorders(),dxfs:s.getDxfs(),numFmts:s.getNumFormats(),styles:s.getStyles(),sheets:o,sharedStrings:r,externalBooks:n,chartIds:[],imageIds:[]}}buildXlsxFileStructure(){const e={sheets:mE(Ob.sheet,this.xmls),workbook:mE(Ob.workbook,this.xmls)[0]||mE(Ob.macroEnabledWorkbook,this.xmls)[0]||mE(Ob.templateWorkbook,this.xmls)[0]||mE(Ob.macroEnabledTemplateWorkbook,this.xmls)[0]||mE(Ob.excelAddInWorkbook,this.xmls)[0],styles:mE(Ob.styles,this.xmls)[0],sharedStrings:mE(Ob.sharedStrings,this.xmls)[0],theme:mE(Ob.themes,this.xmls)[0],charts:mE(Ob.chart,this.xmls),figures:mE(Ob.drawing,this.xmls),tables:mE(Ob.table,this.xmls),pivots:mE(Ob.pivot,this.xmls),externalLinks:mE(Ob.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:_w(e,this.warningManager),styles:yy(e,this.warningManager),formats:Ey(e,this.warningManager),borders:by(e,this.warningManager),revisionId:Y};return kw(t,e),Object.keys(e.styles).map(t=>{e.styles[t]=De(e.styles[t])}),t}}function vE(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 yE(e){const t=Qg(e),r=[];return{text:"".concat(...t.map(e=>{if("REFERENCE"===e.type&&gn.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 wE={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},EE=new h;function SE(e){for(const t of e.sheets||[]){const e=[];for(const r of t.filterTables||[]){const t=Jn(r.range),o=e.findIndex(e=>cs(e,t));-1!==o?e[o]=t:e.push(t)}t.filterTables=e.map(e=>({range:rs(e)}))}return e}function CE(){return TE().at(-1)}function TE(){return EE.getKeys().sort(AE)}EE.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=yE(r.content))}return e}}).add("0.6",{migrate(e){for(const t of e.sheets||[])for(const e in t.figures||[]){const{dataSets:r,...o}=t.figures[e].data,n=[];for(const e of r)if(e.labelCell){const t=Jn(e.dataRange),r=e.labelCell+":"+$n(t.right,t.bottom);n.push(r)}else n.push(e.dataRange);o.dataSetsHaveTitle=Boolean(r[0].labelCell),o.dataSets=n,t.figures[e].data=o}return e}}).add("0.7",{migrate(e){const t=[];for(const r of e.sheets||[]){if(!r.name)continue;const e=r.name,o=Xe(ie(e,"_"),t,{compute:(e,t)=>`${e}${t}`});r.name=o,t.push(o);const n=t=>{if(void 0===t)return t;let r=t.replace(e,o),n=t;for(;n!==r;)n=r,r=n.replace(e,o);return n};for(const e in r.cells){const t=r.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(n))}for(const e of r.figures||[])if("chart"===e.tag){const t=e.data.dataSets.map(n),r=n(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:r}}for(const e of r.conditionalFormats||[]){e.ranges=e.ranges.map(n);for(const t of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===e.rule[t]?.type&&(e.rule[t].value=n(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,o]of Object.entries(t)){const t=`\\${K}${r}\\${K}`;e=e.replace(new RegExp(t,"g"),o)}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 o=r.cells[e];o.format&&(o.format=_y(o.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=>SE(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=Ar),e)}).add("16.4.1",{migrate:e=>SE(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=Nd(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 o=r.data.type;if(!["line","bar","pie","scatter","waterfall","combo"].includes(o))continue;const{dataSets:n,...s}=t.figures[e].data,i=n.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=wE[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=vE(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=vE(t.colorScale));return e}});const IE="Sheet1";function xE(e,t){if(!e)return DE();console.debug("### Loading data ###");const r=performance.now();if(e["[Content_Types].xml"]){const r=new bE(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=RE[e.version]),e.version!==CE()&&(console.debug("Migrating data from version",e.version),e=function(e){const t=performance.now(),r=TE();for(let t=r.findIndex(t=>t===e.version)+1;t<r.length;t++){const o=r[t];e=EE.get(o).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,o=new Dn;for(const n of e.sheets||[])for(const e of n.figures||[])t.has(e.id)&&(e.id+=o.smallUuid()),t.add(e.id),"chart"===e.tag&&(r.has(e.data?.chartId)&&(e.data.chartId+=o.smallUuid()),r.add(e.data?.chartId));return e.uniqueFigureIds=!0,e}(e),e=function(e){const t=Object.assign(DE(),e,{version:CE()});t.sheets=t.sheets?t.sheets.map((e,t)=>Object.assign(FE(`Sheet${t+1}`,`Sheet${t+1}`),e)):[],0===t.sheets.length&&t.sheets.push(FE(IE,"Sheet1"));jl(t.settings.locale)||(t.settings.locale=Ar);return t}(e),e}(e),console.debug("Data loaded in",performance.now()-r,"ms"),console.debug("###"),e}const RE={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 AE(e,t){const r=e.split(".").map(Number),o=t.split(".").map(Number);for(let e=0;e<Math.max(r.length,o.length);e++){const t=r[e]||0,n=o[e]||0;if(t>n)return 1;if(t<n)return-1}return 0}function OE(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const r=[],o=[],n=e=>{if("CREATE_SHEET"===e.type)r.push(e.sheetId);else if("sheetId"in e&&!r.includes(e.sheetId))return{...e,sheetId:IE};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(n)}):o.push(e);return o}(e,t),t=_E(t,"SORT_CELLS"),t=function(e,t){if(!e.version||AE(String(e.version),"18.5.1")>=0)return t;const r=[],o={};for(const t of e.sheets||[])t.figures?.forEach(e=>{"chart"===e.tag&&(o[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":o[r.chartId]=r.definition;break;case"UPDATE_CHART":if(!o[r.chartId]){console.log(`Fix chart definition: chart with id ${r.chartId} not found.`);continue}const t={...o[r.chartId],...r.definition};e={...r,definition:t},o[r.chartId]=t}t.push(e)}r.push({...e,commands:t})}else r.push(e);return r}(e,t=_E(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 o=[];for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const o of e.commands){switch(o.type){case"DUPLICATE_SHEET":o.sheetNameTo=o.sheetNameTo??qm(r[o.sheetId],Object.values(r));break;case"CREATE_SHEET":r[o.sheetId]=o.name||Wm(Object.values(r));break;case"RENAME_SHEET":r[o.sheetId]=o.newName||Wm(Object.values(r))}t.push(o)}o.push({...e,commands:t})}else o.push(e);return t}(e,t),t}function _E(e,t){const r=[];for(const o of e)"REMOTE_REVISION"===o.type?r.push({...o,commands:o.commands.filter(e=>e.type!==t)}):r.push(o);return r}function FE(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 DE(e="Sheet1"){return{version:CE(),sheets:[FE(IE,e)],styles:{},formats:{},borders:{},revisionId:Y,uniqueFigureIds:!0,settings:{locale:Ar},pivots:{},pivotNextId:1,customTableStyles:{}}}class NE{map={};constructor(e=[]){for(const[t,r]of e)this.set(t,r)}set({sheetId:e,col:t,row:r},o){const n=this.map;n[e]||(n[e]={}),n[e][t]||(n[e][t]={}),n[e][t][r]=o}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 o in e[r])for(const n in e[r][o])t.push({sheetId:r,col:parseInt(o),row:parseInt(n)});return t}keysForSheet(e){const t=this.map[e];if(!t)return[];const r=[];for(const o in t)for(const n in t[o])r.push({sheetId:e,col:parseInt(o),row:parseInt(n)});return r}*entries(){const e=this.map;for(const t of this.keys()){const{sheetId:r,col:o,row:n}=t;yield[t,e[r][o][n]]}}}class ME{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 o=e.filter(e=>"Success"!==e);if(o.length)return o}return"Success"}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class VE extends ME{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:r,dispatch:o,canDispatch:n}){super(t),r.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=o,this.canDispatch=n}import(e){}export(e){}adaptRanges(e,t,r){}}class PE{id;format;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,r,o,n,s){this.id=e,this.format=r,this.sheetId=n,this.getRangeString=s;let i=0;const a=t.tokens.map(e=>{if("REFERENCE"===e.type){const e=i++;return new LE(o,e,this.sheetId,this.getRangeString)}return e});this.compiledFormula={...t,dependencies:o,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 LE{ranges;rangeIndex;sheetId;getRangeString;type="REFERENCE";constructor(e,t,r,o){this.ranges=e,this.rangeIndex=t,this.sheetId=r,this.getRangeString=o}get value(){const e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}}const kE=new dd;kE.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:hd.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text contains"),getPreview:e=>v('Text contains "%s"',e.values[0])}),kE.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:hd.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text does not contain"),getPreview:e=>v('Text does not contain "%s"',e.values[0])}),kE.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:hd.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text is exactly"),getPreview:e=>v('Text is exactly "%s"',e.values[0])});const UE=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/;function HE(e,t){return e.values.map(e=>void 0!==e?Kl(String(e),t):w.InvalidReference)}function BE(e,t){return bw(e,Ar).map(e=>void 0!==e?Qr(e,{locale:t,format:t.dateFormat}):w.InvalidReference)}function zE(e){return void 0!==dt(e,Ar)}function $E(e){return void 0!==Ht(e,Ar)}function GE(e){return""===e?NaN:Number(e)}kE.add("isEmail",{type:"isEmail",isValueValid:(e,t)=>"string"==typeof e&&UE.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")}),kE.add("isLink",{type:"isLink",isValueValid:(e,t)=>void 0!==lw(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")}),kE.add("dateIs",{type:"dateIs",isValueValid:(e,t)=>{const r=bw(t,Ar)[0],o=dt(e,Ar);if(void 0===o||void 0===r)return!1;if(["lastWeek","lastMonth","lastYear"].includes(t.dateValue)){return Rt(o,Math.floor(vt(Je.now())),r)}return n=o,s=r,Math.trunc(n)===Math.trunc(s);var n,s},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be the date %s",BE(e,r)[0]):v("The value must be %s",hd.DateIs[e.dateValue])},isCriterionValueValid:e=>zE(e),criterionValueErrorString:hd.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:v("Date is"),getPreview:(e,t)=>"exactDate"===e.dateValue?v("Date is %s",vw(e.values,t.getLocale())[0]):v("Date is %s",hd.DateIs[e.dateValue])}),kE.add("dateIsBefore",{type:"dateIsBefore",isValueValid:(e,t)=>{const r=bw(t,Ar)[0],o=dt(e,Ar);return void 0!==o&&void 0!==r&&function(e,t){return Math.trunc(e)<Math.trunc(t)}(o,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date before %s",BE(e,r)[0]):v("The value must be a date before %s",hd.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>zE(e),criterionValueErrorString:hd.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",vw(e.values,t.getLocale())[0]):v("Date is before %s",hd.DateIsBefore[e.dateValue])}),kE.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",isValueValid:(e,t)=>{const r=bw(t,Ar)[0],o=dt(e,Ar);return void 0!==o&&void 0!==r&&function(e,t){return Math.trunc(e)<=Math.trunc(t)}(o,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date on or before %s",BE(e,r)[0]):v("The value must be a date on or before %s",hd.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>zE(e),criterionValueErrorString:hd.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",vw(e.values,t.getLocale())[0]):v("Date is on or before %s",hd.DateIsBefore[e.dateValue])}),kE.add("dateIsAfter",{type:"dateIsAfter",isValueValid:(e,t)=>{const r=bw(t,Ar)[0],o=dt(e,Ar);return void 0!==o&&void 0!==r&&function(e,t){return Math.trunc(e)>Math.trunc(t)}(o,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date after %s",BE(e,r)[0]):v("The value must be a date after %s",hd.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>zE(e),criterionValueErrorString:hd.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",vw(e.values,t.getLocale())[0]):v("Date is after %s",hd.DateIsBefore[e.dateValue])}),kE.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",isValueValid:(e,t)=>{const r=bw(t,Ar)[0],o=dt(e,Ar);return void 0!==o&&void 0!==r&&function(e,t){return Math.trunc(e)>=Math.trunc(t)}(o,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date on or after %s",BE(e,r)[0]):v("The value must be a date on or after %s",hd.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>zE(e),criterionValueErrorString:hd.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",vw(e.values,t.getLocale())[0]):v("Date is on or after %s",hd.DateIsBefore[e.dateValue])}),kE.add("dateIsBetween",{type:"dateIsBetween",isValueValid:(e,t)=>{const r=bw(t,Ar),o=dt(e,Ar);return void 0!==o&&void 0!==r[0]&&void 0!==r[1]&&Rt(o,r[0],r[1])},getErrorString:(e,t)=>{const r=BE(e,t.getLocale());return v("The value must be a date between %s and %s",r[0],r[1])},isCriterionValueValid:e=>zE(e),criterionValueErrorString:hd.CriterionError.dateValue,numberOfValues:()=>2,name:v("Date is between"),getPreview:(e,t)=>{const r=vw(e.values,t.getLocale());return v("Date is between %s and %s",r[0],r[1])}}),kE.add("dateIsNotBetween",{type:"dateIsNotBetween",isValueValid:(e,t)=>{const r=bw(t,Ar),o=dt(e,Ar);return void 0!==o&&void 0!==r[0]&&void 0!==r[1]&&!Rt(o,r[0],r[1])},getErrorString:(e,t)=>{const r=BE(e,t.getLocale());return v("The value must be a date not between %s and %s",r[0],r[1])},isCriterionValueValid:e=>zE(e),criterionValueErrorString:hd.CriterionError.dateValue,numberOfValues:()=>2,name:v("Date is not between"),getPreview:(e,t)=>{const r=vw(e.values,t.getLocale());return v("Date is not between %s and %s",r[0],r[1])}}),kE.add("dateIsValid",{type:"dateIsValid",isValueValid:(e,t)=>void 0!==dt(e,Ar),getErrorString:()=>v("The value must be a valid date"),isCriterionValueValid:e=>zE(e),criterionValueErrorString:"",numberOfValues:()=>0,name:v("Is valid date"),getPreview:()=>v("Date is valid")}),kE.add("isEqual",{type:"isEqual",isValueValid:(e,t)=>e===t.values[0],getErrorString:(e,t)=>{const r=HE(e,t.getLocale());return v("The value must be equal to %s",r[0])},isCriterionValueValid:e=>$E(e),criterionValueErrorString:hd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is equal to"),getPreview:e=>v("Value is equal to %s",e.values[0])}),kE.add("isNotEqual",{type:"isNotEqual",isValueValid:(e,t)=>e!==t.values[0],getErrorString:(e,t)=>{const r=HE(e,t.getLocale());return v("The value must not be equal to %s",r[0])},isCriterionValueValid:e=>$E(e),criterionValueErrorString:hd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is not equal to"),getPreview:e=>v("Value is not equal to %s",e.values[0])}),kE.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=HE(e,t.getLocale());return v("The value must be greater than %s",r[0])},isCriterionValueValid:e=>$E(e),criterionValueErrorString:hd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is greater than"),getPreview:e=>v("Value is greater than %s",e.values[0])}),kE.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=HE(e,t.getLocale());return v("The value must be greater or equal to %s",r[0])},isCriterionValueValid:e=>$E(e),criterionValueErrorString:hd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is greater or equal to"),getPreview:e=>v("Value is greater or equal to %s",e.values[0])}),kE.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=HE(e,t.getLocale());return v("The value must be less than %s",r[0])},isCriterionValueValid:e=>$E(e),criterionValueErrorString:hd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is less than"),getPreview:e=>v("Value is less than %s",e.values[0])}),kE.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=HE(e,t.getLocale());return v("The value must be less or equal to %s",r[0])},isCriterionValueValid:e=>$E(e),criterionValueErrorString:hd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is less or equal to"),getPreview:e=>v("Value is less or equal to %s",e.values[0])}),kE.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=HE(e,t.getLocale());return v("The value must be between %s and %s",r[0],r[1])},isCriterionValueValid:e=>$E(e),criterionValueErrorString:hd.CriterionError.numberValue,numberOfValues:()=>2,name:v("Is between"),getPreview:e=>v("Value is between %s and %s",e.values[0],e.values[1])}),kE.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=HE(e,t.getLocale());return v("The value must not be between %s and %s",r[0],r[1])},isCriterionValueValid:e=>$E(e),criterionValueErrorString:hd.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])}),kE.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")}),kE.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(", "))}),kE.add("isValueInRange",{type:"isValueInRange",preComputeCriterion:(e,t,r)=>{if(0===t.length)return new Set;const o=t[0].sheetId,n=r.getDataValidationRangeValues(o,e);return new Set(n.map(e=>e.value.toString().toLowerCase()))},isValueValid:(e,t,r)=>!!e&&r.has(e.toString().toLowerCase()),getErrorString:e=>v("The value must be a value in the range %s",String(e.values[0])),isCriterionValueValid:e=>wn.test(e),criterionValueErrorString:hd.CriterionError.validRange,numberOfValues:()=>1,allowedValues:"onlyLiterals",name:v("Value in range"),getPreview:e=>v("Value in range %s",e.values[0])}),kE.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])}),kE.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:hd.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text begins with"),getPreview:e=>v('Text begins with "%s"',e.values[0])}),kE.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:hd.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text ends with"),getPreview:e=>v('Text ends with "%s"',e.values[0])}),kE.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")}),kE.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")}),kE.add("top10",{type:"top10",preComputeCriterion:(e,t,r)=>{let o=Ht(e.values[0],Ar);if(void 0===o||o<=0)return;const n=[];for(const e of t)for(const t of r.getRangeValues(e))"number"==typeof t&&n.push(t);const s=n.sort((e,t)=>e-t);e.isPercent&&(o=ae(o,1,100));let i=0;return i=e.isBottom&&!e.isPercent?o-1:e.isBottom&&e.isPercent?Math.floor(s.length*o/100)-1:!e.isBottom&&e.isPercent?s.length-Math.floor(s.length*o/100):s.length-o,i=ae(i,0,s.length-1),s[i]},isValueValid:(e,t,r)=>"number"==typeof e&&void 0!==r&&(t.isBottom?e<=r:e>=r),getErrorString:e=>{const t={value:String(e.values[0]),percentSymbol:e.isPercent?"%":""};return e.isBottom?v("The value must be in bottom %(value)s%(percentSymbol)s",t):v("The value must be in top %(value)s%(percentSymbol)s",t)},isCriterionValueValid:e=>function(e){const t=Ht(e,Ar);return void 0!==t&&t>0}(e),criterionValueErrorString:hd.CriterionError.positiveNumber,numberOfValues:()=>1,name:v("Is in Top/Bottom ranking"),getPreview:e=>{const t={value:e.values[0],percentSymbol:e.isPercent?"%":""};return e.isBottom?v("Value is in bottom %(value)s%(percentSymbol)s",t):v("Value is in top %(value)s%(percentSymbol)s",t)}});function WE(e){return Object.entries(e).map(([e,t])=>t?qE(parseInt(e,10),t):void 0).filter(Se).map(e=>$n(e.left,e.top)+":"+$n(e.right,e.bottom))}function qE(e,t){return{...t.zone,id:e}}class ZE{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,o="__count"===r?{name:"__count",string:v("Count"),type:"integer",aggregator:"sum"}:e[r],n=t.aggregator;let s=!(!o&&!t.computedBy);for(const t of[...this.rows,...this.columns]){const r=e[t.fieldName];if(r?.isCustomField&&this.invalidAggregatorsForCustomField.includes(n)){s=!1;break}}return{id:t.id,get displayName(){return t.userDefinedName??o?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:r,aggregator:n,type:"__count"===r?"integer":o?.type??"integer",isValid:s,isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}createPivotDimension(e,t){const r=e[t.fieldName],o=r?.type??"integer",n=r&&function(e){return Md.includes(e.type)}(r)?t.granularity:void 0;return{displayName:r?.string??t.fieldName,nameWithGranularity:t.fieldName+(n?`:${n}`:""),fieldName:t.fieldName,granularity:n,type:r?.isCustomField?"custom":o,order:t.order,isValid:!!r,isCustomField:!!r?.isCustomField,customGroups:r?.customGroups,parentField:r?.parentField}}}class YE extends ZE{range;constructor(e,t,r){if(super(e,t),e.dataSet){const{sheetId:t,zone:o}=e.dataSet;this.range=r.getRangeFromZone(t,o)}}}const jE="(previous)";function XE(e,t){const r=e.definition.rows.map(e=>e.nameWithGranularity),o=t.filter(e=>r.includes(e.field)),n=e.definition.columns.map(e=>e.nameWithGranularity);return{colDomain:t.filter(e=>n.includes(e.field)),rowDomain:o}}function KE(e,t,r){return"column"===t?XE(e,r).colDomain:XE(e,r).rowDomain}function QE(e,t){return void 0!==JE(e,t)}function JE(e,t,r){let o=t;for(const t of e){const e=o.find(e=>e.value===t.value);if(!e)return;if(e.field===r)return o;o=e.children}return o}function eS(e,t,r){const o=(e=re(e)).find(e=>e.field===t);return o?(o.value=r,e):e}function tS(e,t){return t.some(t=>t.field===e)}function rS(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 oS(e){return e?e.map(nS).join(", "):""}function nS(e){return e?`${e.field}=${e.value}`:""}function sS(e,t){const r=e.findIndex(e=>e.field===t);if(-1===r)return"";const o=e.slice(0,r),n=e.at(-1);return oS(n.field===t?o:[...o,n])}function iS(e,t){const r=e.findIndex(e=>e.field===t);return-1===r?"":oS([...e.slice(0,r),...e.slice(r+1)])}function aS(e,t,r){const o=[...e],n=[...t];o.sort((e,t)=>r([...n,e],[...n,t]));for(const t of e){const e=aS(t.children,[...n,t],r);t.children=e}return o}function lS(e,t){return e.length>t.length&&t.every((t,r)=>Ae(t,e[r]))}class cS{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,r,o,n={COL:[],ROW:[]}){this.measures=r,this.fieldsType=o,n.COL.length&&(e=this.removeCollapsedColumns(e,r,n.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(n.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 o=(r,o)=>{const n=this.getDomain(r),s=e[o],i=s.findIndex(e=>lS(this.getDomain(e),n)),a=s.findLastIndex(e=>lS(this.getDomain(e),n)),l=o===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((n,s)=>{for(const i of n){if(s>=e.length-2)return n;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++)o(i,t)}}return n})}isParentCollapsed(e,t){const r=this.getDomain(t);return e.some(e=>lS(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=Rd){const t=JSON.stringify(e);if(!this.pivotCells[t]){const{displayTotals:r}=e,o=this.rows.length,n=this.getNumberOfDataColumns();let s=this.columns.length+o,i=1+n;r||1===o||(s-=1),r||n===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 o=this.columns.length;if(e>0&&t===o-1){const r=this.getColHeaderDomain(e,t);if(!r)return uS;const o=r.at(-1)?.value?.toString()||"";return{type:"MEASURE_HEADER",domain:r.slice(0,-1),measure:o}}if(t<=o-1){const r=this.getColHeaderDomain(e,t);return r?{type:"HEADER",domain:r,dimension:"COL"}:uS}if(0===e){const e=t-o;return{type:"HEADER",domain:this.getDomain(this.rows[e]),dimension:"ROW"}}{const n=t-o;if(!r&&this.isTotalRow(n))return uS;return{type:"VALUE",domain:[...this.getDomain(this.rows[n]),...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:o,granularity:n}=Vd(t),s=this.fieldsType[o]||"char";return{type:s,field:t,value:kd({displayName:o,type:s,granularity:n},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 o of this.rows){if(0===o.fields.length||0===o.values.length)return e;const n=o.fields.length-1,s=o.fields[n],{fieldName:i,granularity:a}=Vd(s),l=kd({displayName:i,type:this.fieldsType[i]??"char",granularity:a},o.values[n]);if(n>t){t=n,r[t]=[];const e=r[t-1].at(-1);e&&(e.children=r[t])}t=n;const c={value:l,field:o.fields[n],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 o=e.fields[t],{fieldName:n,granularity:s}=Vd(o),i=kd({displayName:n,type:this.fieldsType[n]??"char",granularity:s},e.values[t]),a={value:i,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[n]||"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 o=(e,t)=>{const o=r(e,t).value;return"number"==typeof o?o:-1/0},n=t.domain,s=aS(this.rowTree(),[],(r,s)=>{const i=o(e,[...r,...n]),a=o(e,[...s,...n]);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))}getPivotTableDimensions(e){const t=this.getPivotCells(e);let r=0;return e.displayColumnHeaders&&(r=this.columns.length-1),e.displayMeasuresRow&&r++,{numberOfCols:Math.min(1+e.numberOfColumns,t.length),numberOfRows:Math.min(r+e.numberOfRows,t[0].length),numberOfHeaderRows:r}}getNumberOfRowGroupBys(){return Math.max(...this.rows.map(e=>e.fields.length))}}const uS={type:"EMPTY"};function hS(e,t,r){const o=t.measures.filter(e=>!e.isHidden).map(e=>e.id),n=fS(e,t.columns,0);gS(n,o.length);const s=function(e,t){const r=t.columns.map(e=>e.nameWithGranularity),o=r.length,n=t.measures.filter(e=>!e.isHidden),s=n.length,i=new Array(o).fill(0).map(()=>[]);function a(e,t,n){const s=i[t];for(const i of e){const e=n.concat([i.value]),l={fields:r.slice(0,t+1),values:e,width:i.width,offset:0};s.push(l),t<=o-1&&a(i.children,t+1,e)}}a(e,0,[]);const l=r.length>0,c=[];l&&i[i.length-1].forEach(e=>{n.forEach(t=>{const r={fields:[...e.fields,"measure"],values:[...e.values,t.id],width:1,offset:0};c.push(r)})});n.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}(n,t),i=dS(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 cS(s,i,o,a,l)}function dS(e,t,r,o,n){if(t>=r.length)return[];const s=r[t],i=s.nameWithGranularity,a=mS(e,s),l=pS(a,s),c=[],u=o.concat(i);for(const e of l){const o=n.concat(e);c.push({fields:u,values:o,indent:t+1});const s=a[e];s&&c.push(...dS(s,t+1,r,u,o))}return c}function fS(e,t,r){if(r>=t.length)return[];const o=t[r],n=t[r].nameWithGranularity,s=mS(e,o);return pS(s,t[r]).map(e=>({value:s[e]?.[0]?.[o.nameWithGranularity]?.value??null,field:n,children:fS(s[e]||[],t,r+1),type:o.type,width:0}))}function gS(e,t){for(const r in e){const o=e[r];0===o.children.length?o.width=t:(gS(o.children,t),o.width=o.children.reduce((e,t)=>e+t.width,0))}}function mS(e,t){return Object.groupBy(e,function(e){const t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}(t))}function pS(e,t){const r=t.order,o=t.customGroups?.find(e=>e.isOtherGroup);return r||o?Object.keys(e).sort((e,n)=>o&&e===o.name?1:o&&n===o.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?Ut(t,Ar)-Ut(r,Ar):Ut(r,Ar)-Ut(t,Ar);return"asc"===e.order?t.localeCompare(r):r.localeCompare(t)}(t,e,n):0):Object.keys(e)}const bS=Symbol("NULL");function vS(e,t,r){const o=e.granularity||"month";if(!(o in yS))throw new Error(`Unknown date granularity: ${o}`);const n="number"==typeof t||"string"==typeof t?t:bS;if(!yS[o].set.has(t)){yS[o].set.add(t);let s=null;if("number"==typeof t||"string"==typeof t){const e=jt(t,r);switch(o){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(Ut(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()}}yS[o].values[n]=kd(e,s)}return yS[o].values[n]}const yS={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 wS;!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"}(wS||(wS={}));const ES=new h,SS=["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(wS.ALL),this.needsReevaluation=!1)}reload(e){e===wS.ALL&&(this.metaData=this.loadMetaData()),e>=wS.DEFINITION&&(this._definition=this.loadRuntimeDefinition()),e>=wS.DATA&&(this.dataEntries=this.loadData()),e>=wS.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),wS.NONE);this.reload(r)}}computeShouldReload(e,t){return Ae(e.dataSet,t.dataSet)?wS.DEFINITION:wS.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:w.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(Wt);return t.length&&"measure"===t.at(-1)&&(t=t.slice(0,-1)),function(e,t){let r=0,o=0;const n=t.columns.map(e=>e.nameWithGranularity),s=t.rows.map(e=>e.nameWithGranularity);for(;void 0!==e[r]&&e[r]===s[o];)r++,o++;for(o=0;void 0!==e[r]&&e[r]===n[o];)r++,o++;return e.length===r}(t,this.definition)}parseArgsToPivotDomain(e){const t=[];for(let r=0;r<e.length-1;r+=2){const o=Wt(e[r]),n=this.getTypeOfDimension(o),s="measure"===o?Wt(e[r+1]):kd(this.getDimension(o),e[r+1]);t.push({field:o,value:s,type:n})}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),o=this.filterDataEntriesFromDomain(this.dataEntries,e),n=o[0]?.[r.nameWithGranularity];if("datetime"===r.type){return gd(r.granularity||"month").toValueAndFormat(t.value,this.getters.getLocale())}return n?null===n.value?{value:v("(Undefined)")}:n:{value:""}}getPivotCellValueAndFormat(e,t){const r=this.filterDataEntriesFromDomain(this.dataEntries,t);if(0===r.length)return{value:""};const o=this.getMeasure(e),n=r.map(e=>e[o.fieldName]).filter(Se),s=n.filter(e=>e.type!==wu.empty),i=o.aggregator,a=Dd[i];if(!a)throw new Error(`Aggregator ${i} does not exist`);try{const e=a([n],this.getters.getLocale());return 0===s.length?{...e,value:""}:e}catch(e){return Cr(e,i.toUpperCase())}}getPossibleFieldValues(e){const t=[],r=mS(this.dataEntries,e),o=pS(r,e);for(const n of o)t.push({value:r[n]?.[0]?.[e.nameWithGranularity]?.value??"",label:r[n]?.[0]?.[e.nameWithGranularity]?.formattedValue||""});return t}getCollapsedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.collapsedTable||(this.collapsedTable=hS(this.dataEntries,this.definition,"collapsed")),this.collapsedTable}getExpandedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.expandedTable||(this.expandedTable=hS(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 o of Object.values(e.customFields||{}))t[o.parentField]&&(r[o.name]={type:"custom",isCustomField:!0,name:o.name,string:o.name,customGroups:o.groups,parentField:o.parentField});return r}(this.coreDefinition,e.fields);return{...e,fields:{...e.fields,...t}}}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}}loadRuntimeDefinition(){return new YE(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}=Vd(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:o,type:n}=t,{nameWithGranularity:s}=this.getDimension(r);return e.filter(e=>{const t=e[s]?.value;return"char"===n?String(t)===String(o):t===o})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){const r=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===wu.empty||""===e.value));return 0===r.length?"integer":r.every(e=>e.type===wu.number&&e.format&&io(e.format))?"datetime":r.every(e=>e.type===wu.boolean)?"boolean":r.some(e=>e.type===wu.text)?"char":"integer"}assertCellIsValidField(e,t,r){if(r.type===wu.error)throw new S(v("The pivot cannot be created because cell %s contains an error",$n(e,t)));if(r.type===wu.empty||""===r.value)throw new S(v("The pivot cannot be created because cell %s is empty",$n(e,t)));if("__count"===r.value)throw new S(v("The pivot cannot be created because cell %s contains a reserved value",$n(e,t)))}extractFieldsFromRange(e){const t={},r=[],o=e.sheetId,n=e.zone.top;for(let s=e.zone.left;s<=e.zone.right;s++){const i=this.getters.getEvaluatedCell({sheetId:o,col:s,row:n});this.assertCellIsValidField(s,n,i);const a=i.value?.toString();if(a){const n=this.getTypeFromZone(o,{top:e.zone.top+1,left:s,bottom:e.zone.bottom,right:s}),i=Wd(a,t);t[i]={name:i,type:n,string:i,aggregator:"integer"===n?"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 o={top:r,bottom:r,left:e.zone.left,right:e.zone.right},n=this.getters.getEvaluatedCellsInZone(e.sheetId,o),s={};for(const e in n){const t=n[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:wu.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],o=this.fields[t.parentField];if(!r||!o){s[e]={value:null,type:wu.empty,formattedValue:""};continue}const n=t.groups.find(e=>e.values.some(e=>e===r?.value))||t.groups.find(e=>e.isOtherGroup);s[e]={...r,value:n?n.name:r.value}}s.__count={value:1,type:wu.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 o of t)for(const t of r){const r=vS(t,o[t.fieldName]?.value||null,this.getters.getLocale()),n=gd(t.granularity||"month"),{format:s,value:i}=n.toValueAndFormat(r,e);o[t.nameWithGranularity]={value:r,type:o[t.fieldName]?.type||wu.empty,format:o[t.fieldName]?.format,formattedValue:Qr(i,{locale:e,format:s})}}}return t}},definition:YE,dateGranularities:[...SS],datetimeGranularities:[...SS,"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:o,zone:n}=t.dataSet,s=e.getRangeFromZone(o,n),i=function(e,t){if(!e)return;const r=t(e);switch(r.changeType){case"NONE":return e;case"REMOVE":return;default:return r.range}}(s,r);if(i===s)return t;const a=i&&{sheetId:i.sheetId,zone:i.zone};return{...t,dataSet:a}}});const CS={verticalAlign:"bottom",wrapping:"overflow",bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:"",textColor:""};const TS=e=>({category:"dark",templateName:"pivotDarkWithDarkHeader",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.medium},border:{horizontal:{color:e.light,style:"thin"}}},headerRow:{style:{bold:!0,fillColor:e.dark,textColor:"#FFFFFF"}},measureHeader:{border:{top:{color:e.light,style:"thin"}}},mainSubHeaderRow:{style:{bold:!0,fillColor:e.light}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:e.dark,textColor:"#FFFFFF"}},secondRowStripe:{style:{fillColor:e.mediumBorder}},firstColumnStripe:{border:{left:{color:e.light,style:"thin"},right:{color:e.light,style:"thin"}}}}),IS=e=>({category:"dark",templateName:"pivotDarkWithBlackHeader",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.highlight,textColor:"#FFFFFF"}},headerRow:{style:{bold:!0,fillColor:"#000000"}},measureHeader:{border:{top:{color:e.light,style:"thin"}}},mainSubHeaderRow:{style:{bold:!0,fillColor:e.dark}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:"#000000"}},firstRowStripe:{border:{bottom:{color:e.mediumBorder,style:"thin"},top:{color:e.mediumBorder,style:"thin"}}},firstColumnStripe:{border:{left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"}}}}),xS=e=>({category:"dark",templateName:"pivotDarkWithFirstColumn",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.highlight,textColor:"#FFFFFF"},border:{vertical:{color:"#FFFFFF",style:"thin"}}},headerRow:{style:{fillColor:e.dark},border:{bottom:{color:"#FFFFFF",style:"medium"}}},firstColumn:{style:{fillColor:e.dark}},measureHeader:{border:{top:{color:e.light,style:"thin"}}},mainSubHeaderRow:{style:{bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:e.dark},border:{top:{color:"#FFFFFF",style:"medium"}}},secondRowStripe:{style:{fillColor:e.mediumBorder}},firstColumnStripe:{style:{fillColor:e.mediumBorder}}}),RS={None:{category:"light",templateName:"none",primaryColor:"",displayName:v("None")}},AS=[Wp.black,Wp.lightBlue,Wp.red,Wp.lightGreen,Wp.purple,Wp.gray,Wp.orange];function OS(e,t){let r=1;for(const o of t)for(const t of AS){const n=e+r++,s={...o(t),displayName:_S(t.name,e,r-1)};RS[n]=s}}function _S(e,t,r){let o="";return t.includes("Light")?o=$p.light:t.includes("Medium")?o=$p.medium:t.includes("Dark")&&(o=$p.dark),`${o} ${e} ${r}`}function FS(e){const t=RS[e];return t&&Object.keys(sb).find(e=>{const r=sb[e];return r.category===t.category&&r.primaryColor===t.primaryColor})||"None"}OS("PivotTableStyleLight",[e=>({category:"light",templateName:"pivotLightWithLightBorders",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0},border:{horizontal:{color:e.light,style:"thin"}}},headerRow:{style:{bold:!0},border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"}}},mainSubHeaderRow:{style:{bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0,textColor:e.highlight}},totalRow:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"}},style:{bold:!0,fillColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.light},border:{bottom:{color:e.medium,style:"thin"},top:{color:e.medium,style:"thin"},vertical:{color:e.medium,style:"thin"}}},secondColumnStripe:{style:{fillColor:e.light},border:{left:{color:e.medium,style:"thin"},right:{color:e.medium,style:"thin"},horizontal:{color:e.medium,style:"thin"}}}}),e=>({category:"light",templateName:"pivotLightWithMediumBorders",primaryColor:e.highlight,wholeTable:{style:{textColor:e.coloredText,hideGridLines:!0},border:{horizontal:{color:e.light,style:"thin"}}},firstColumn:{border:{right:{color:e.highlight,style:"thin"}}},headerRow:{style:{bold:!0,textColor:"#000000"},border:{top:{color:e.highlight,style:"medium"},bottom:{color:e.highlight,style:"medium"},left:{color:e.highlight,style:"medium"},right:{color:e.highlight,style:"medium"}}},measureHeader:{border:{top:{color:e.light,style:"thin"}}},mainSubHeaderRow:{style:{bold:!0,textColor:"#000000",fillColor:e.light}},firstAlternatingSubHeaderRow:{style:{bold:!0,textColor:"#000000"}},totalRow:{border:{top:{color:e.highlight,style:"medium"},bottom:{color:e.highlight,style:"medium"},left:{color:e.highlight,style:"medium"},right:{color:e.highlight,style:"medium"}},style:{bold:!0,textColor:"#000000"}},firstRowStripe:{border:{bottom:{color:e.highlight,style:"thin"},top:{color:e.highlight,style:"thin"}}},secondRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}},firstColumnStripe:{border:{left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"}}},secondColumnStripe:{border:{left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"}}}}),e=>({category:"light",templateName:"PivotLightWithGrayBands",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0}},headerRow:{style:{bold:!0,fillColor:e.light},border:{horizontal:{color:e.light,style:"thin"},vertical:{color:e.light,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"}}},measureHeader:{border:{top:{color:"#FFFFFF",style:"thin"}}},mainSubHeaderRow:{style:{bold:!0},border:{bottom:{color:e.mediumBorder,style:"thin"}}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{border:{top:{color:e.mediumBorder,style:"medium"}},style:{bold:!0,fillColor:e.light}},firstRowStripe:{style:{fillColor:Wp.black.light}},secondColumnStripe:{style:{fillColor:Wp.black.light},border:{left:{color:Wp.black.medium,style:"thin"},right:{color:Wp.black.medium,style:"thin"}}}}),e=>({category:"light",templateName:"pivotLightWithColoredText",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,textColor:e.coloredText},border:{vertical:{color:e.mediumBorder,style:"thin"},top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"}}},headerRow:{border:{bottom:{color:e.mediumBorder,style:"thin"},vertical:{color:e.mediumBorder,style:"thin"}}},totalRow:{border:{top:{color:e.mediumBorder,style:"thin"}}},firstRowStripe:{style:{fillColor:e.light},border:{top:{color:Wp.black.medium,style:"thin"},bottom:{color:Wp.black.medium,style:"thin"}}},secondColumnStripe:{style:{fillColor:e.light}}})]),OS("PivotTableStyleMedium",[e=>({category:"medium",templateName:"pivotMediumHeavyColors",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0},border:{horizontal:{color:e.light,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},measureHeader:{border:{top:{color:e.light,style:"thin"}}},mainSubHeaderRow:{style:{fillColor:e.mediumBorder,textColor:"#FFFFFF"}},firstAlternatingSubHeaderRow:{style:{fillColor:e.light},border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}},style:{bold:!0}},firstRowStripe:{border:{bottom:{color:e.highlight,style:"thin"},top:{color:e.highlight,style:"thin"}}},firstColumnStripe:{border:{left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"}}}}),e=>({category:"medium",templateName:"pivotMediumLightColors",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0},border:{top:{color:e.dark,style:"medium"},bottom:{color:e.dark,style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF",bold:!0}},measureHeader:{border:{top:{color:e.mediumBorder,style:"thin"}}},mainSubHeaderRow:{style:{fillColor:e.light,bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{border:{top:{color:e.dark,style:"thin"}},style:{bold:!0}},firstRowStripe:{border:{bottom:{color:e.mediumBorder,style:"thin"},top:{color:e.mediumBorder,style:"thin"}}},firstColumnStripe:{border:{left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"}}}}),e=>({category:"medium",templateName:"pivotMediumBlackHeaders",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.light},border:{vertical:{color:e.mediumBorder,style:"thin"}}},headerRow:{style:{fillColor:"#000000",textColor:"#FFFFFF"}},measureHeader:{border:{top:{color:"#FFFFFF",style:"thin"}}},mainSubHeaderRow:{style:{bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0,textColor:"#808080"}},secondAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{fillColor:"#000000",textColor:"#FFFFFF"},border:{vertical:null}},firstRowStripe:{border:{bottom:{color:e.mediumBorder,style:"thin"},top:{color:e.mediumBorder,style:"thin"}}}}),e=>({category:"medium",templateName:"pivotMediumBlackHeaders",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.light,textColor:e.coloredText},border:{vertical:{color:"#FFFFFF",style:"thin"}}},headerRow:{style:{bold:!0},border:{vertical:{color:"#FFFFFF",style:"thin"},bottom:{color:"#FFFFFF",style:"thin"}}},firstColumn:{style:{fillColor:e.medium}},measureHeader:{border:{top:{color:"#FFFFFF",style:"thin"}}},mainSubHeaderRow:{style:{bold:!0,textColor:"#000000"}},firstAlternatingSubHeaderRow:{style:{bold:!0}},secondAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}})]),OS("PivotTableStyleDark",[TS,e=>({category:"dark",templateName:"pivotDarkWithGrayHeader",primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.light}},headerRow:{style:{bold:!0,fillColor:Wp.black.dark,textColor:"#FFFFFF"}},measureHeader:{border:{top:{color:e.light,style:"medium"}}},mainSubHeaderRow:{style:{bold:!0,fillColor:e.medium}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:Wp.black.dark,textColor:"#FFFFFF"}},firstRowStripe:{border:{bottom:{color:e.medium,style:"thin"},top:{color:e.medium,style:"thin"}}},firstColumnStripe:{border:{left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"}}}}),IS,xS]),RS.PivotTableStyleDark1={...RS.PivotTableStyleDark1,...TS({...Wp.black,mediumBorder:Ap(Wp.black.medium,.1)})},RS.PivotTableStyleDark15={...RS.PivotTableStyleDark15,...IS({...Wp.black,highlight:Wp.gray.dark,mediumBorder:Wp.black.medium})},RS.PivotTableStyleDark22={...RS.PivotTableStyleDark22,...xS({...Wp.black,highlight:Wp.gray.dark,mediumBorder:Wp.black.medium})};const DS=["wholeTable","firstColumnStripe","secondColumnStripe","firstRowStripe","secondRowStripe","firstColumn","lastColumn","headerRow","measureHeader","firstAlternatingSubHeaderRow","secondAlternatingSubHeaderRow","mainSubHeaderRow","totalRow"];function NS(e,t,r,o){const n=t.zone;if(n.left!==n.right)throw new Error("Can only define a filter on a single column");const s={...n,top:n.top+r.numberOfHeaders},i=o(t.sheetId,s);return{id:e,rangeWithHeaders:t,col:n.left,filteredRange:s.top>s.bottom?void 0:i}}function MS(e,t,r){const{numberOfCols:o,numberOfRows:n}=r,s=nr(o,n,()=>({}));for(const i of DS){const a=t[i]?.border;if(!a)continue;const l=LS(i,e,r);for(const t of l)for(let r=t.left;r<=t.right;r++)for(let l=t.top;l<=t.bottom;l++){const c="wholeTable"===i&&l<=e.numberOfHeaders-1;l===t.top&&void 0!==a?.top?VS(s,"top",a.top,r,l,o,n):l===t.top||c||void 0===a?.horizontal||VS(s,"top",a.horizontal,r,l,o,n),l===t.bottom&&void 0!==a?.bottom&&VS(s,"bottom",a.bottom,r,l,o,n),r===t.left&&void 0!==a?.left&&VS(s,"left",a.left,r,l,o,n),r===t.right&&void 0!==a?.right?VS(s,"right",a.right,r,l,o,n):r===t.right||c||void 0===a?.vertical||VS(s,"right",a.vertical,r,l,o,n)}}return s}function VS(e,t,r,o,n,s,i){switch(t){case"top":return e[o][n].top=r??void 0,void(0!==n&&(e[o][n-1].bottom=r??void 0));case"bottom":return e[o][n].bottom=r??void 0,void(n!==i-1&&(e[o][n+1].top=r??void 0));case"left":return e[o][n].left=r??void 0,void(0!==o&&(e[o-1][n].right=r??void 0));case"right":return e[o][n].right=r??void 0,void(o!==s-1&&(e[o+1][n].left=r??void 0))}}function PS(e,t,r){const{numberOfCols:o,numberOfRows:n}=r,s=nr(o,n,()=>({}));for(const o of DS){const n=t[o];if(!n)continue;const i=LS(o,e,r);for(const e of i)for(let t=e.left;t<=e.right;t++)for(let r=e.top;r<=e.bottom;r++)s[t][r]||(s[t][r]={}),s[t][r]={...s[t][r],...n?.style}}return s}function LS(e,t,r){const{numberOfCols:o,numberOfRows:n}=r,s=[],i=Math.min(t.numberOfHeaders,n),a=t.totalRow?1:0,l=o-1,c=n-1;switch(e){case"wholeTable":s.push({top:0,left:0,bottom:c,right:l});break;case"firstColumn":if(!t.firstColumn)break;s.push({top:0,left:0,bottom:c,right:0});break;case"lastColumn":if(!t.lastColumn)break;s.push({top:0,left:l,bottom:c,right:l});break;case"headerRow":if(!t.numberOfHeaders)break;s.push({top:0,left:0,bottom:i-1,right:l});break;case"totalRow":if(!t.totalRow)break;s.push({top:c,left:0,bottom:c,right:l});break;case"firstRowStripe":if(!t.bandedRows)break;for(let e=i;e<n-a;e+=2)s.push({top:e,left:0,bottom:e,right:l});break;case"secondRowStripe":if(!t.bandedRows)break;for(let e=i+1;e<n-a;e+=2)s.push({top:e,left:0,bottom:e,right:l});break;case"firstColumnStripe":{if(!t.bandedColumns)break;const e="pivot"===r.mode?c:c-a;for(let t=0;t<o;t+=2)s.push({top:i,left:t,bottom:e,right:t});break}case"secondColumnStripe":{if(!t.bandedColumns)break;const e="pivot"===r.mode?c:c-a;for(let t=1;t<o;t+=2)s.push({top:i,left:t,bottom:e,right:t});break}case"mainSubHeaderRow":for(const e of r.mainSubHeaderRows||[])s.push({top:e,bottom:e,left:0,right:r.numberOfCols-1});break;case"firstAlternatingSubHeaderRow":for(const e of r.firstAlternatingSubHeaderRows||[])s.push({top:e,bottom:e,left:0,right:r.numberOfCols-1});break;case"secondAlternatingSubHeaderRow":for(const e of r.secondAlternatingSubHeaderRows||[])s.push({top:e,bottom:e,left:0,right:r.numberOfCols-1});break;case"measureHeader":if(void 0!==r.measureRow&&r.numberOfCols>1){const e=r.measureRow;s.push({top:e,bottom:e,left:1,right:r.numberOfCols-1})}}return s}const kS=Wg.content;function US(e){try{return 0===hm(cm(e)).filter(e=>"FUNCALL"===e.type&&!kS[e.value.toUpperCase()]?.isExported).length}catch(e){return!1}}function HS(e,t){if(!e.some(e=>"SYMBOL"===e.type&&t.includes(e.value.toUpperCase())))return[];let r;try{r=cm(e)}catch{return[]}return function(e,t){return hm(e).filter(e=>"FUNCALL"===e.type&&t.includes(e.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}(r,t)}class BS extends ME{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}}const zS=Wg.mapping;function $S(e,t,r){return new GS(e,t,r).getParameters()}class GS{getters;computeCell;evalContext;rangeCache={};constructor(e,t,r){this.getters=t,this.computeCell=r,this.evalContext=Object.assign(Object.create(zS),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 o={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};if(t){this.computeCell(o);return{value:Rn(this.getters.getSheetName(e.sheetId),rs(e.zone))}}return this.computeCell(o)}range(e,t){const r=this.getRangeError(e);if(r)return[[r]];const o=e.sheetId,n=e.zone,s=is(n,this.getters.getSheetZone(o));if(!s)return[[]];const{top:i,left:a,bottom:l,right:c}=n,u=`${o}-${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 n=s.top;n<=s.bottom;n++){const i=n-s.top,a=this.computeCell({sheetId:o,col:e,row:n});f[r][i]=t?{value:Rn(g,$n(e,n))}:a}}return this.rangeCache[u]=f,f}getRangeError(e){return es(e.zone)?e.invalidSheetName?new I(v("Invalid sheet name: %s",e.invalidSheetName)):void 0:new I}}function WS(e,t,r,o,n){qS(e,t,r||0,o||e.length-1,n||YS)}function qS(e,t,r,o,n){for(;o>r;){if(o-r>600){var s=o-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);qS(e,t,Math.max(r,Math.floor(t-i*l/s+c)),Math.min(o,Math.floor(t+(s-i)*l/s+c)),n)}var u=e[t],h=r,d=o;for(ZS(e,r,t),n(e[o],u)>0&&ZS(e,r,o);h<d;){for(ZS(e,h,d),h++,d--;n(e[h],u)<0;)h++;for(;n(e[d],u)>0;)d--}0===n(e[r],u)?ZS(e,r,d):ZS(e,++d,o),d<=t&&(r=d+1),t<=d&&(o=d-1)}}function ZS(e,t,r){var o=e[t];e[t]=e[r],e[r]=o}function YS(e,t){return e<t?-1:e>t?1:0}class jS{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(!aC(e,t))return r;const o=this.toBBox,n=[];for(;t;){for(let s=0;s<t.children.length;s++){const i=t.children[s],a=t.leaf?o(i):i;aC(e,a)&&(t.leaf?r.push(i):iC(e,a)?this._all(i,r):n.push(i))}t=n.pop()}return r}collides(e){let t=this.data;if(!aC(e,t))return!1;const r=[];for(;t;){for(let o=0;o<t.children.length;o++){const n=t.children[o],s=t.leaf?this.toBBox(n):n;if(aC(e,s)){if(t.leaf||iC(e,s))return!0;r.push(n)}}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=lC([]),this}remove(e,t){if(!e)return this;let r=this.data;const o=this.toBBox(e),n=[],s=[];let i,a,l;for(;r||n.length;){if(r||(r=n.pop(),a=n[n.length-1],i=s.pop(),l=!0),r.leaf){const o=XS(e,r.children,t);if(-1!==o)return r.children.splice(o,1),n.push(r),this._condense(n),this}l||r.leaf||!iC(r,o)?a?(i++,r=a.children[i],l=!1):r=null:(n.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,o){const n=r-t+1;let s,i=this._maxEntries;if(n<=i)return s=lC(e.slice(t,r+1)),KS(s,this.toBBox),s;o||(o=Math.ceil(Math.log(n)/Math.log(i)),i=Math.ceil(n/Math.pow(i,o-1))),s=lC([]),s.leaf=!1,s.height=o;const a=Math.ceil(n/i),l=a*Math.ceil(Math.sqrt(i));cC(e,t,r,l,this.compareMinX);for(let n=t;n<=r;n+=l){const t=Math.min(n+l-1,r);cC(e,n,t,a,this.compareMinY);for(let r=n;r<=t;r+=a){const n=Math.min(r+a-1,t);s.children.push(this._build(e,r,n,o-1))}}return KS(s,this.toBBox),s}_chooseSubtree(e,t,r,o){for(;o.push(t),!t.leaf&&o.length-1!==r;){let r,o=1/0,n=1/0;for(let s=0;s<t.children.length;s++){const i=t.children[s],a=rC(i),l=nC(e,i)-a;l<n?(n=l,o=a<o?a:o,r=i):l===n&&a<o&&(o=a,r=i)}t=r||t.children[0]}return t}_insert(e,t,r){const o=r?e:this.toBBox(e),n=[],s=this._chooseSubtree(o,this.data,t,n);for(s.children.push(e),JS(s,o);t>=0&&n[t].children.length>this._maxEntries;)this._split(n,t),t--;this._adjustParentBBoxes(o,n,t)}_split(e,t){const r=e[t],o=r.children.length,n=this._minEntries;this._chooseSplitAxis(r,n,o);const s=this._chooseSplitIndex(r,n,o),i=lC(r.children.splice(s,r.children.length-s));i.height=r.height,i.leaf=r.leaf,KS(r,this.toBBox),KS(i,this.toBBox),t?e[t-1].children.push(i):this._splitRoot(r,i)}_splitRoot(e,t){this.data=lC([e,t]),this.data.height=e.height+1,this.data.leaf=!1,KS(this.data,this.toBBox)}_chooseSplitIndex(e,t,r){let o,n=1/0,s=1/0;for(let i=t;i<=r-t;i++){const t=QS(e,0,i,this.toBBox),a=QS(e,i,r,this.toBBox),l=sC(t,a),c=rC(t)+rC(a);l<n?(n=l,o=i,s=c<s?c:s):l===n&&c<s&&(s=c,o=i)}return o||r-t}_chooseSplitAxis(e,t,r){const o=e.leaf?this.compareMinX:eC,n=e.leaf?this.compareMinY:tC;this._allDistMargin(e,t,r,o)<this._allDistMargin(e,t,r,n)&&e.children.sort(o)}_allDistMargin(e,t,r,o){e.children.sort(o);const n=this.toBBox,s=QS(e,0,t,n),i=QS(e,r-t,r,n);let a=oC(s)+oC(i);for(let o=t;o<r-t;o++){const t=e.children[o];JS(s,e.leaf?n(t):t),a+=oC(s)}for(let o=r-t-1;o>=t;o--){const t=e.children[o];JS(i,e.leaf?n(t):t),a+=oC(i)}return a}_adjustParentBBoxes(e,t,r){for(let o=r;o>=0;o--)JS(t[o],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():KS(e[r],this.toBBox)}}function XS(e,t,r){if(!r)return t.indexOf(e);for(let o=0;o<t.length;o++)if(r(e,t[o]))return o;return-1}function KS(e,t){QS(e,0,e.children.length,t,e)}function QS(e,t,r,o,n){n||(n=lC(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(let s=t;s<r;s++){const t=e.children[s];JS(n,e.leaf?o(t):t)}return n}function JS(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 eC(e,t){return e.minX-t.minX}function tC(e,t){return e.minY-t.minY}function rC(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function oC(e){return e.maxX-e.minX+(e.maxY-e.minY)}function nC(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 sC(e,t){const r=Math.max(e.minX,t.minX),o=Math.max(e.minY,t.minY),n=Math.min(e.maxX,t.maxX),s=Math.min(e.maxY,t.maxY);return Math.max(0,n-r)*Math.max(0,s-o)}function iC(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function aC(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function lC(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function cC(e,t,r,o,n){const s=[t,r];for(;s.length;){if((r=s.pop())-(t=s.pop())<=o)continue;const i=t+Math.ceil((r-t)/o/2)*o;WS(e,i,t,r,n),s.push(t,i,i,r)}}class uC{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 hC,this.rTrees[e].load(t[e])}insert(e){const t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new hC),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 hC extends jS{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 dC{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){Wn(this.profilesStartingPosition,this.profiles,[e])}delete(e){Wn(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return function(e,t,r){const o=r.left,n=r.right,s=Xn(e,o,0),i=void 0===n?e.length-1:Xn(e,n,s),a=r.top,l=void 0===r.bottom?void 0:r.bottom+1;for(let r=s;r<=i;r++){const o=t.get(e[r]),n=Xn(o,a,0);if(-1===n||n%2!=0)return!1;if(n+1!==(void 0===l?o.length:Kn(o,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 dC;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 jn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}}class fC{setsBySheetId={};constructor(e=[]){for(const t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new dC),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(const t of e)this.add(t)}addPosition(e){this.add(Dm(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(Dm(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(Dm(t))}difference(e){const t=new fC;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 fC;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 gC{rTree;constructor(e=[]){const t=function(e){let t=0,r=0;for(let o=0;o<e.length;o++){const n=e[o].boundingBox.zone;n.right>t&&(t=n.right),n.bottom>r&&(r=n.bottom)}t+=1,r+=1;const o=(((r+1)*t+1)*r+1)*t<=Number.MAX_SAFE_INTEGER;o||console.warn("Max col/row size exceeded, using slow zone key");const n={};for(const s of e){const e=s.boundingBox.sheetId;n[e]||(n[e]={});const i=s.boundingBox.zone;let a=0;if(a=o?i.left+i.top*t+i.right*t*r+i.bottom*t*r*t:`${i.left},${i.top},${i.right},${i.bottom}`,n[e][a]){n[e][a].data.add(s.data)}else n[e][a]={boundingBox:s.boundingBox,data:new fC([s.data])}}const s=[];for(const e in n){const t=n[e];for(const e in t)s.push(t[e])}return s}(e);this.rTree=new uC(t)}insert(e){const t=this.rTree.search(e.boundingBox),r=e.boundingBox,o=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);o?o.data.add(e.data):this.rTree.insert({...e,data:new fC([e.data])})}search({zone:e,sheetId:t}){const r=new fC;for(const{data:o}of this.rTree.search({zone:e,sheetId:t}))r.addMany(o);return r}remove(e){const t=this.rTree.search(e.boundingBox),r=e.boundingBox,o=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);o?o.data.delete(e.data):this.rTree.remove({...e,data:new fC([e.data])})}}class mC{dependencies=new NE;rTree;constructor(e=[]){this.rTree=new gC(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:vs(e)},boundingBox:{zone:r,sheetId:t}}));for(const e of r)this.rTree.insert(e);const o=this.dependencies.get(e);o?o.push(...r):this.dependencies.set(e,r)}getCellsDependingOn(e,t=new fC){t=t.copy();const r=Array.from(e).reverse();for(;r.length>0;){const e=r.pop();t.add(e);const o=this.rTree.search(e);r.push(...o.difference(t))}for(const r of e)t.delete(r);return t}}class pC 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),o=new this((e<<r>>5)+1);return o.columnOffset=r,o.cols=t,o.rows=e,o}getValue(e){const[t,r]=this.getCoordinates(e);return this[t]>>r&1}setValue(e,t){const[r,o]=this.getCoordinates(e),n=0===(this[r]>>o&1)&&1===t;return this[r]=this[r]&~(1<<o)|t<<o,n}isEmpty(){return!this.some(e=>0!==e)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){const{row:t,col:r}=e,o=(t<<this.columnOffset)+r,n=o>>5;return[n,o-(n<<5)]}}class bC{sheets={};insertions=[];maxSize=0;constructor(e){for(const t in e){const r=e[t].cols,o=e[t].rows;this.maxSize+=r*o,this.sheets[t]=pC.create(o,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 o=0;o<r.rows;o++)for(let n=0;n<r.cols;n++)this.insertions[e++]={sheetId:t,row:o,col:n}}}*[Symbol.iterator](){for(const e of this.insertions)1===this.sheets[e.sheetId].getValue(e)&&(yield e)}}class vC{resultsToArrayFormulas=new uC;arrayFormulasToResults=new NE;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||yC}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:vs(e)},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 yC=[],wC=new dd;wC.add("pivots",e=>{for(const t of e.getPivotIds()){const r=e.getPivot(t);r.markAsDirtyForEvaluation?.()}});const EC=Object.freeze(hw({...new T,origin:void 0})),SC=Object.freeze(hw({value:null}));class CC{context;getters;compilationParams;evaluatedCells=new NE;formulaDependencies=xe(new mC);blockedArrayFormulas=new bC({});spreadingRelations=new vC;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=$S(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||SC}getSpreadZone(e,t={ignoreSpillError:!1}){const r=this.spreadingRelations.getArrayResultZone(e);if(!r)return;const o=this.evaluatedCells.get(e);return o?.type!==wu.error||t.ignoreSpillError&&o?.value===w.SpilledBlocked?ss(vs(e),r):vs(e)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===wu.empty)return;return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,vs(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=$S(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 bC(e)}evaluateCells(e){const t=performance.now(),r=new fC;r.addManyPositions(e);const o=this.getArrayFormulasImpactedByChangesOf(e);r.addMany(this.getCellsDependingOn(r)),r.addMany(o),r.addMany(this.getCellsDependingOn(o)),this.evaluate(r),console.debug("evaluate Cells",performance.now()-t,"ms")}getArrayFormulasImpactedByChangesOf(e){const t=new fC;for(const r of e){const e=this.getters.getCell(r)?.content,o=this.getArrayFormulaSpreadingOn(r);void 0!==o&&t.addPosition(o),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 vC,this.formulaDependencies=xe(()=>{const e=[];for(const t of this.getters.getSheetIds()){const r=this.getters.getCells(t);for(const o in r){const n=r[o];if(n.isFormula){const r=n.compiledFormula.dependencies;for(const n of r)n.invalidSheetName||n.invalidXc||e.push({data:{sheetId:t,zone:vs(this.getters.getCellPosition(o))},boundingBox:{sheetId:n.sheetId,zone:n.zone}})}}}return new mC(e)})}evaluateAllCells(){const e=performance.now();this.evaluatedCells=new NE;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=vm(t),o=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParameters(),this.evaluateCompiledFormula(e,{...r,dependencies:o})}evaluateCompiledFormula(e,t,r){try{const o=RC(t,this.compilationParams,e,this.buildSafeGetSymbolValue(r),this.compilationParams.evalContext.__originCellPosition);return F(o)?sr(o,IC):IC(o)}catch(e){return Cr(e,"")}}getArrayFormulasBlockedBy(e,t){const r=new fC,o=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);r.addManyPositions(o);const n=[...o].filter(e=>!this.blockedArrayFormulas.has(e));return n.length&&r.deleteManyPositions(n),r.addMany(this.getCellsDependingOn(r)),r}nextRangesToUpdate=new fC;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new fC(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:o,top:n}=t.zone;for(let s=e;s<=o;s++)for(let e=n;e<=r;e++){const r={sheetId:t.sheetId,col:s,row:e};if(this.nextRangesToUpdate.hasPosition(r))continue;const o=this.computeCell(r);o!==SC&&this.evaluatedCells.set(r,o)}}wC.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:o,top:n}=t.zone;for(let s=e;s<=o;s++)for(let e=n;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 SC;const o=r.id,n={format:r.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(o)?EC:(this.cellsBeingComputed.add(o),r.isFormula?this.computeFormulaCell(e,r):cw(r,n,e))}catch(t){return t.value=t?.value||w.GenericError,t.message=t?.message||Ir,t.origin=e,hw(t)}finally{this.cellsBeingComputed.delete(o)}}computeAndSave(e){const t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){const r=RC(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!F(r)){const o=hw(xC(r),this.getters.getLocale(),t,e);return o.type===wu.error&&(o.errorOriginPosition=r.errorOriginPosition??e),o}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,r);const o=r.length,n=r[0].length;if(0===n)return hw({value:0},this.getters.getLocale(),t);const s={top:e.row,bottom:e.row+n-1,left:e.col,right:e.col+o-1};return this.spreadingRelations.addRelation({resultZone:s,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,r),TC(o,n,this.checkCollision(e)),TC(o,n,this.spreadValues(e,r)),this.invalidatePositionsDependingOnSpread(e.sheetId,s),hw(xC(r[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){const r=this.getCellsDependingOn(function(e){const{top:t,left:r,bottom:o,right:n}=e;if(1===Ss(e))return[];const s={top:t+1,bottom:o,left:r,right:r};if(n===r)return[s];const i={top:t,bottom:o,left:r+1,right:n};return t===o?[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},o){const n=this.getters.getNumberCols(e),s=this.getters.getNumberRows(e),i=t+o.length<=n,a=r+o[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},o){if(0!==this.getters.getMergesInZone(e,{top:r,bottom:r+o[0].length-1,left:t,right:t+o.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:o}=e;return(n,s)=>{const i={sheetId:t,col:n+r,row:s+o},a=this.getters.getCell(i);if(a?.content||this.getters.getEvaluatedCell(i).type!==wu.empty)throw this.blockedArrayFormulas.add(e),new A(v("Array result was not expanded because it would overwrite data in %s.",$n(i.col,i.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:r},o){return(n,s)=>{const i={sheetId:e,col:n+t,row:s+r},a=this.getters.getCell(i),l=hw(xC(o[n][s]),this.getters.getLocale(),a,i);l.type===wu.error&&(l.errorOriginPosition=o[n][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 o=t.top;o<=t.bottom;o++){const t={sheetId:e.sheetId,col:r,row:o},n=this.getters.getCell(t)?.content;n||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 EC;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 TC(e,t,r){for(let o=0;o<e;++o)for(let e=0;e<t;++e)0===o&&0===e||r(o,e)}function IC(e){return null===e.value||void 0===e.value?{...e,value:0}:e}function xC(e){return"number"==typeof e.value&&Math.abs(e.value)>Number.MAX_VALUE?new _:IC(e)}function RC(e,t,r,o,n){return t.evalContext.__originCellPosition=n,t.evalContext.__originSheetId=r,e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,o,t.evalContext)}function AC(e,t=1){return t*(e+4)-4}function OC(e=100,t=100){return new OffscreenCanvas(e,t).getContext("2d")}function _C(e,t,r,o){return DC(e,HC(e,t,r,"wrap"===r?.wrapping?o-8:void 0),r).height+6}function FC(e,t=!1,r=!1){return`${r?"italic":""} ${t?"bold":""} ${e}px ${Z}`}function DC(e,t,r={},o="pt"){if(!t.length)return{width:0,height:0};const n=LC(r,o),s=t.map(t=>PC(e,t,n)),i=AC(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 NC(e,t,r={},o="pt"){return MC(e,t,LC(r,o),r.rotation)}function MC(e,t,r,o){const n=PC(e,t,r);if(!o)return n.width;const s=Math.abs(Math.cos(o)),i=Math.abs(Math.sin(o));return n.width*s+n.height*i}const VC={};function PC(e,t,r){if(VC[r]||(VC[r]={}),void 0===VC[r][t]){e.save(),e.font=r;const o=e.measureText(t);e.restore();const n=o.width,s=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;VC[r][t]={width:n,height:s}}return VC[r][t]}function LC(e,t="pt"){return`${e.italic?"italic ":""}${e.bold?"bold":"400"} ${("pt"===t?kC(e):e.fontSize)??q}px ${Z}`}function kC(e){return t=e?.fontSize||q,Math.round(96*t/72);var t}function UC(e,t,r,o){if(NC(e,t,o)<=r)return[t];const n=[];let s="";for(const i of t){NC(e,s+i,o)>r?(n.push(s),s=i):s+=i}return n.push(s),n}function HC(e,t,r,o){r||(r={}),ge(t)&&(t=be(t).label);const n=[],s=t.includes(Q)?t.split(Q):[t];for(const t of s){const s=t.includes(" ")?t.split(" "):[t];if(!o){n.push(t);continue}let i="",a=o;for(const t of s){const s=UC(e,t,o,r),l=s.pop(),c=NC(e,l,r);if(s.length)""!==i&&(n.push(i),i="",a=o),s.forEach(e=>{n.push(e)}),i=l,a=o-c;else{const t=""===i?l:" "+l,s=NC(e,t,r);s<=a?(i+=t,a-=s):(n.push(i),i=l,a=o-c)}}""!==i&&n.push(i)}return n}function BC(e){return e?e.toLowerCase():""}const zC=/([0-9\.]*)px/;function $C(e,t,r){let o=MC(e,t,e.font);if(o<=r)return t;const n=MC(e,"…",e.font);if(o<=n)return t;let s=t.length;for(;o>=r-n&&s-- >0;)o=MC(e,t=t.substring(0,s),e.font);return t+"…"}function GC(e,t,r,o=!1,n=!1,s=function(e){return Number(e.match(zC)?.[1])}(e.font)/10){if(e.fillText(t,r.x,r.y),!o&&!n)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}o&&(e.lineWidth=s,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+a,f),e.stroke()),n&&(e.lineWidth=s,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,d),e.lineTo(u+a,d),e.stroke())}const WC=new dd;WC.add("data_validation_checkbox",(e,t)=>{if(e.isCellValidCheckbox(t)){const r=!!e.getEvaluatedCell(t).value;return{svg:r?_v:Av,hoverSvg:r?_v:Ov,priority:2,horizontalAlign:"center",size:17,margin:2,position:t,type:"data_validation_checkbox",onClick:(e,t)=>{const o=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||!!o?.isFormula)return;const n=r?"FALSE":"TRUE";t.model.dispatch("UPDATE_CELL",{...e,content:n})}}}}),WC.add("data_validation_chip_icon",(e,t)=>{const r=e.getDataValidationChipStyle(t);if(r){const o=e.getCellComputedStyle(t);return{svg:xv(r),hoverSvg:Rv(r),priority:10,horizontalAlign:"right",size:kC(o),margin:4,position:t,onClick:(e,t)=>{const{col:r,row:o}=e;t.model.selection.selectCell(r,o),t.startCellEdition()},type:"data_validation_chip_icon"}}}),WC.add("data_validation_list_icon",(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){const o=e.getCellComputedStyle(t);return{svg:Tv(o),hoverSvg:(r=o,{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:o}=e;t.model.selection.selectCell(r,o),t.startCellEdition()},type:"data_validation_list_icon"}}var r}),WC.add("conditional_formatting",(e,t)=>{const r=e.getConditionalIcon(t);if(r){const o=e.getCellStyle(t);return{type:"conditional_formatting",svg:Dv[r].svg,priority:1,horizontalAlign:"left",size:kC(o),margin:4,position:t}}}),WC.add("pivot_collapse",(e,t)=>{if(!e.isSpillPivotFormula(t))return;const r=e.getPivotCellFromPosition(t),o=e.getPivotIdFromPosition(t);if("HEADER"===r.type&&o&&r.domain.length){const n=e.getPivotCoreDefinition(o),s=e.isDashboard(),i="COL"===r.dimension?n.columns:n.rows,a=!s&&r.domain.length!==i.length,l=(n.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&&n.rows.length>1?12:0,margin:a?4+c:c,svg:a?Fv(l,!1):void 0,hoverSvg:a?Fv(l,!0):void 0,position:t,onClick:qd}}}),WC.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 o=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${r}`,priority:5,horizontalAlign:"right",size:17,margin:2,svg:"asc"===r?(n=o,{name:"CARET_UP",width:512,height:512,paths:[{fillColor:n.textColor||U,path:"M120 325 h270 l-135 -130"}]}):Tv(o),position:t,onClick:void 0};var n});const qC=/"(#[0-9a-fA-F]{6})"/g;const ZC=new h;function YC(){return!globalThis.Chart||!!globalThis.Chart.registry.plugins.get("chartShowValuesPlugin")}function jC(){if(globalThis.Chart)for(const e of ZC.getAll())e.unregister(globalThis.Chart)}const XC=12,KC="#F3F2F1";function QC(e,t,r){const o=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),n="number"==typeof globalThis.devicePixelRatio?globalThis.devicePixelRatio:1;e.width=o.width*n,e.height=o.height*n;const s=e.getContext("2d");if(!s)throw new Error("Unable to retrieve 2D context from canvas");s.scale(n,n);const i=function(e,t,r){const o=t.maxValue,n=t.minValue,s=nT(t,"animated"),i=function(e,t){const r=t?25:0,o=e.height-20-r-10,n=e.width-60;let s,i;n>2*o?(s=2*o,i=o):(s=n,i=n/2);const a=r+10+(o-i)/2;return{x:30+(n-s)/2,y:a,width:s,height:i}}(e,t.title.text),a=i.width/6,l=s?(s-n.value)/(o.value-n.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||"-";NC(r,d,{fontSize:u},"px")>h&&(u=function(e,t,r,o=.25){let n=1;if(r(n)>e)return n;if(r(t)<e)return t;let s=(n+t)/2,i=r(s),a=0;for(;Math.abs(i-e)>o&&a<20;)i>=e?t=(n+t)/2:n=(n+t)/2,s=(n+t)/2,i=r(s),a++;return s}(h,u,e=>NC(r,d,{fontSize:e},"px")));const f={x:i.x+a/2,y:i.y+i.height+XC},g={x:i.x+i.width-a/2,y:i.y+i.height+XC},m=Jb(t.background),p=function(e,t,r,o){const n=e.maxValue,s=e.minValue,i={x:t.x+t.width/2,y:t.y+t.height},a={fontSize:XC},l=[],c=[];for(const u of e.inflectionValues){const e=(u.value-s.value)/(n.value-s.value),h=NC(o,u.label,a,"px"),d=Math.PI-Math.PI*e,f=oT(d,t.height+6,i.x,i.y,h+2,XC),g=c.some(e=>rT(e,f))?XC:0;c.push(f),l.push({rotation:d,label:u.label,fontSize:XC,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,o="pt"){const n=PC(e,t,LC(r,o));if(!r.rotation)return n;const s=Math.abs(Math.cos(r.rotation)),i=Math.abs(Math.sin(r.rotation));return{width:n.width*s+n.height*i,height:n.height*s+n.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:JC(t)},inflectionValues:p,gaugeValue:{label:d,textPosition:c,fontSize:u,color:m},minLabel:{label:t.minValue.label,textPosition:f,fontSize:XC,color:m},maxLabel:{label:t.maxValue.label,textPosition:g,fontSize:XC,color:m}}}({...o,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,o=r.rect.x+r.rect.width/2,n=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=KC,e.beginPath(),e.lineWidth=r.arcWidth,e.arc(o,n,s,i,0),e.stroke(),e.strokeStyle=r.color,e.beginPath(),e.arc(o,n,s,Math.PI,i),e.stroke(),e.restore()}(s,i),function(e,t){const{x:r,y:o,width:n,height:s}=t.gauge.rect;for(const i of t.inflectionValues){e.save(),e.translate(r+n/2-.5,o+s-.5),e.rotate(Math.PI/2-i.rotation),e.lineWidth=2,e.strokeStyle=Jb(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=FC(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 JC(e){const t=nT(e,"final");if(void 0===t)return KC;for(let r=0;r<e.inflectionValues.length;r++){const o=e.inflectionValues[r];if("<"===o.operator&&t<o.value)return e.colors[r];if("<="===o.operator&&t<=o.value)return e.colors[r]}return e.colors.at(-1)}function eT(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 tT(e,t){const r=e.start,o=e.end,n=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,n,s)!==i(o,n,s)&&i(r,o,n)!==i(r,o,s)}function rT(e,t){const r=eT(e),o=eT(t);for(const e of r)for(const t of o)if(tT(e,t))return!0;return!1}function oT(e,t,r,o,n,s){const i=Math.cos(e),a=Math.sin(e),l=i*t,c=a*t,u=a*(n/2),h=i*(n/2),d=i*(t+s),f=a*(t+s);return{bottomLeft:{x:l-u+r,y:o-(c+h)},bottomRight:{x:l+u+r,y:o-(c-h)},topRight:{x:d+u+r,y:o-(f-h)},topLeft:{x:d-u+r,y:o-(f+h)}}}function nT(e,t){return"animated"===t&&void 0!==e.animationValue?e.animationValue:e.gaugeValue?.value}const sT=globalThis.Path2D,iT=sT&&new sT("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"),aT=sT&&new sT("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 lT=.05;function cT(e,t){const r=e||"";return t&&r?" "+r:r}class uT{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 o=new globalThis.OffscreenCanvas(e,t).getContext("2d");if(!o)throw new Error("Unable to create scorecard measurement context");this.context=o}computeDesign(){const e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles();let r=0;if(this.title){let o,n;switch(({height:r,width:n}=this.getFullTextDimensions(this.title,t.title.font)),this.runtime.title.align){case"center":o=(this.width-n)/2;break;case"right":o=this.width-n-B;break;default:o=B}e.title={text:this.title,style:t.title,position:{x:o,y:10+r/2}}}const o=t.baselineArrow?.size??0;let{height:n,width:s}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(n=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+o;break;default:a=(this.width-s-i+o)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:a,y:this.keyValue?this.height*(1-lT*(this.runtime.progressBar?1:2)):this.height-(this.height-r-n)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-o,y:e.baseline.position.y-(n+o)/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-n-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 cT(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return cT(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return Jb(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 o=Math.floor(.9*r);return this.runtime.progressBar&&(r/=1.5),{title:{font:FC(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:FC(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:FC(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:FC(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:FC(o,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 hT(e,t,r){const o=(n=t.width,s=t.height,new OffscreenCanvas(n,s));var n,s;let i;if("chartJsConfig"in e){if(!globalThis.Chart)return console.log("Chart.js library is not loaded"),i;const t=YC();if(t||function(){if(globalThis.Chart&&!YC())for(const e of ZC.getAll())e.register(globalThis.Chart)}(),!globalThis.Chart.registry.controllers.get(r))return console.log(`Chart of type "${r}" is not registered in Chart.js library.`),t||jC(),i;const n=re(e.chartJsConfig);n.plugins=[dT];const s=new globalThis.Chart(o,n);try{i=await fT(o)}finally{s.destroy(),t||jC()}}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 uT({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 o="number"==typeof globalThis.devicePixelRatio?globalThis.devicePixelRatio:1;t.width=o*e.canvas.width,t.height=o*e.canvas.height,r.scale(o,o);const n=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($C(r,e.title.text,n-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,GC(r,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&sT){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(iT);break;case"up":r.fill(aT)}r.restore()}if(e.baselineDescr){const t=e.baselineDescr;r.font=t.style.font,r.fillStyle=t.style.color,r.fillText($C(r,t.text,n-t.position.x),t.position.x,t.position.y)}if(e.key&&(r.font=e.key.style.font,r.fillStyle=e.key.style.color,GC(r,$C(r,e.key.text,n-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($C(r,t.text,n-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,o),i=await fT(o)}else"gauge"===r&&(QC(o,e,t),i=await fT(o))}return i}const dT={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 fT(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 gT={isValid:!0};const mT=["SUBTOTAL","PIVOT"];const pT=["*","+","&"];function bT(e){switch(e.type){case"FUNCALL":const t=e.args.map(e=>bT(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(vT(e)?`(${bT(e.operand)})`:bT(e.operand))+e.value}const r=yT(e)?`(${bT(e.operand)})`:bT(e.operand);return e.value+r;case"ARRAY":return"{"+e.value.map(e=>e.map(e=>bT(e)).join(",")).join(";")+"}";case"BIN_OPERATION":const o=vT(e)?`(${bT(e.left)})`:bT(e.left),n=yT(e)?`(${bT(e.right)})`:bT(e.right);return o+e.value+n}}function vT(e){const t=e.value,r="left"in e?e.left:e.operand,o=r.value;return"BIN_OPERATION"===r.type&&om[o]<om[t]}function yT(e){const t=e.value,r="right"in e?e.right:e.operand,o=om[r.value],n=om[t];return"BIN_OPERATION"===r.type&&(o<n||o===n&&!pT.includes(t))}Ue(function(e){return"\n"+"\t".repeat(e)});const wT=["PIVOT.VALUE","PIVOT.HEADER","PIVOT"];const ET="0.00%";function ST(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 o=this.getMeasure(e),n=o.computedBy?this.computeMeasure(o,t):super.getPivotCellValueAndFormat(e,t);return o.format?this.cache[r]={...n,format:o.format}:this.cache[r]=n,this.cache[r]}computeMeasure(e,t){if(!e.computedBy)return{value:0};const{columns:r,rows:o}=super.definition;if(e.aggregator&&r.length+o.length!==t.length){const r=this.getValuesToAggregate(e,t),o=Dd[e.aggregator];if(!o)return{value:0};try{return o([r],this.getters.getLocale())}catch(t){return Cr(t,e.aggregator.toUpperCase())}}const n=this.getters.getMeasureCompiledFormula(this.pivotId,e),s=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,n,e=>{const{columns:r,rows:o}=this.definition;if(r.find(t=>t.nameWithGranularity===e)){const{colDomain:r}=XE(this,t),o=r.findIndex(t=>t.field===e);return-1===o?new x:this.getPivotHeaderValueAndFormat(r.slice(0,o+1))}if(o.find(t=>t.nameWithGranularity===e)){const{rowDomain:r}=XE(this,t),o=r.findIndex(t=>t.field===e);return-1===o?new x:this.getPivotHeaderValueAndFormat(r.slice(0,o+1))}return this.getPivotCellValueAndFormat(e,t)});return F(s)?s[0][0]:s}getValuesToAggregate(e,t){const{rowDomain:r,colDomain:o}=XE(this,t),n=super.getExpandedTableStructure(),s=[];if(0===o.length&&r.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){const t=this.treeToLeafDomains(n.getColTree()),o=this.getSubTreeMatchingDomain(n.getRowTree(),r),i=this.treeToLeafDomains(o);for(const o of t)for(const t of i)s.push(this._getPivotCellValueAndFormat(e.id,r.concat(t).concat(o)));return s}if(r.length===this.definition.rows.length&&0===o.length){const t=n.getColTree(),i=this.getSubTreeMatchingDomain(t,o),a=this.treeToLeafDomains(i,o);for(const t of a)s.push(this._getPivotCellValueAndFormat(e.id,r.concat(t)));return s}if(r.length===this.definition.rows.length&&o.length&&o.length<this.definition.columns.length){const t=this.getSubTreeMatchingDomain(n.getColTree(),o),i=this.treeToLeafDomains(t,o);for(const t of i)s.push(this._getPivotCellValueAndFormat(e.id,r.concat(t)));return s}{const t=n.getRowTree(),i=this.getSubTreeMatchingDomain(t,r),a=this.treeToLeafDomains(i,r);for(const t of a)s.push(this._getPivotCellValueAndFormat(e.id,t.concat(o)));return s}}getSubTreeMatchingDomain(e,t,r=0){if(r>t.length)return[];if(t.length===r)return e;for(const o of e){const e=kd(this.definition.getDimension(o.field),t[r]?.value);if(o.field===t[r]?.field&&o.value===e)return this.getSubTreeMatchingDomain(o.children,t,r+1)}return[]}treeToLeafDomains(e,t=[]){const r=[];for(const o of e){const e=this.definition.getDimension(o.field),n=[...t,{field:o.field,value:o.value,type:e.type}];0===o.children.length?r.push(n):r.push(...this.treeToLeafDomains(o.children,n))}return r}getMeasureDisplayValue(e,t){const r=this.getMeasure(e),o=this._getPivotCellValueAndFormat(e,t);if(!r.display||"no_calculations"===r.display.type||o.message)return o;const n=r.display.fieldNameWithGranularity;if(n&&!this.isFieldInPivot(n))return{value:w.NotAvailable,message:v('Field "%s" not found in pivot for measure display calculation',n)};try{const e=r.display;switch(e.type){case"%_of_grand_total":return this.asPercentOfGrandTotal(o,r);case"%_of_col_total":return this.asPercentOfColumnTotal(o,r,t);case"%_of_row_total":return this.asPercentOfRowTotal(o,r,t);case"%_of_parent_row_total":return this.asPercentOfParentRowTotal(o,r,t);case"%_of_parent_col_total":return this.asPercentOfParentColumnTotal(o,r,t);case"index":return this.asIndex(o,r,t);case"%_of_parent_total":return this.asPercentOfParentTotal(o,r,t,e);case"running_total":return this.asRunningTotal(o,r,t,e,"running_total");case"%_running_total":return this.asRunningTotal(o,r,t,e,"%_running_total");case"rank_asc":return this.asRank(o,r,t,e,"asc");case"rank_desc":return this.asRank(o,r,t,e,"desc");case"%_of":return this.asPercentOf(o,r,t,e);case"difference_from":return this.asDifferenceFrom(o,r,t,e);case"%_difference_from":return this.asDifferenceFromInPercent(o,r,t,e)}return o}catch(e){return Cr(e,"COMPUTE_MEASURE_DISPLAY_VALUE")}}asPercentOfGrandTotal(e,t){const r=this.getGrandTotal(t.id);return 0===r?{value:w.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:ET}}asPercentOfRowTotal(e,t,r){const o=this.getRowTotal(t.id,r);return 0===o?{value:w.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:ET}}asPercentOfColumnTotal(e,t,r){const o=this.getColumnTotal(t.id,r);return 0===o?{value:w.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:ET}}asPercentOfParentRowTotal(e,t,r){const o=function(e,t){const{colDomain:r,rowDomain:o}=XE(e,t);return[...r,...o.slice(0,o.length-1)]}(this,r),n=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,o));return 0===n?{value:""}:{value:this.measureValueToNumber(e)/n,format:ET}}asPercentOfParentColumnTotal(e,t,r){const o=function(e,t){const{colDomain:r,rowDomain:o}=XE(e,t);return[...r.slice(0,r.length-1),...o]}(this,r),n=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,o));return 0===n?{value:""}:{value:this.measureValueToNumber(e)/n,format:ET}}asPercentOfParentTotal(e,t,r,o){const{fieldNameWithGranularity:n}=o;if(!n)return e;if(!tS(n,r))return{value:""};const s=function(e,t,r){let{rowDomain:o,colDomain:n}=XE(e,r);if("row"===rS(e,t)){const e=o.findIndex(e=>e.field===t);if(-1===e)return r;o=o.slice(0,e+1)}else{const e=n.findIndex(e=>e.field===t);if(-1===e)return r;n=n.slice(0,e+1)}return[...o,...n]}(this,n,r),i=this._getPivotCellValueAndFormat(t.id,s),a=this.measureValueToNumber(i);return 0===a?{value:""}:{value:this.measureValueToNumber(e)/a,format:ET}}asIndex(e,t,r){const o=this.measureValueToNumber(e),n=this.getRowTotal(t.id,r),s=this.getColumnTotal(t.id,r),i=this.getGrandTotal(t.id);return 0===n||0===s?{value:w.DivisionByZero}:{value:o*i/(s*n),format:void 0}}asRunningTotal(e,t,r,o,n){const{fieldNameWithGranularity:s}=o;if(!s)return e;const i="running_total"===n?this.runningTotal:this.runningTotalInPercent;let a=i[t.id]?.[s];a||(a=this.computeRunningTotal(t,s,n),i[t.id]||(i[t.id]={}),i[t.id][s]=a);const{rowDomain:l,colDomain:c}=XE(this,r),u=oS(c),h=oS(l),d=a[u]?.[h];return{value:d??"",format:"running_total"===n?e.format:ET}}asPercentOf(e,t,r,o){const{fieldNameWithGranularity:n,value:s}=o;if(void 0===s||!n)return e;if(!tS(n,r))return{value:""};const i=this.getComparisonValue(t,r,n,s),a=this.strictMeasureValueToNumber(e);return 0===i||"sameValue"===i&&0===a?{value:w.DivisionByZero}:!i||"sameValue"===i&&!a?{value:""}:"sameValue"===i?{value:1,format:ET}:void 0===a?{value:w.NullError}:{value:a/i,format:ET}}asDifferenceFrom(e,t,r,o){const{fieldNameWithGranularity:n,value:s}=o;if(void 0===s||!n)return e;if(!tS(n,r))return{value:""};const i=this.getComparisonValue(t,r,n,s)||0;return"sameValue"===i?{value:""}:{value:this.measureValueToNumber(e)-i,format:e.format}}asDifferenceFromInPercent(e,t,r,o){const{fieldNameWithGranularity:n,value:s}=o;if(void 0===s||!n)return e;if(!tS(n,r))return{value:""};const i=this.getComparisonValue(t,r,n,s),a=this.strictMeasureValueToNumber(e);return 0===i?{value:w.DivisionByZero}:i&&"sameValue"!==i?void 0===a?{value:w.NullError}:{value:(a-i)/i,format:ET}:{value:""}}asRank(e,t,r,o,n){const{fieldNameWithGranularity:s}=o;if(!s)return e;if(!tS(s,r))return{value:""};const i="asc"===n?this.rankAsc:this.rankDesc;let a=i[t.id]?.[s];a||(a=this.computeRank(t,s,n),i[t.id]||(i[t.id]={}),i[t.id][s]=a);const{rowDomain:l,colDomain:c}=XE(this,r),u=oS(c),h=oS(l),d=a[u]?.[h];return{value:d??""}}computeRank(e,t,r){const o={},n=rS(this,t),s="row"===n?"column":"row";let i=this.getPivotValueCells(e.id);"column"===n&&(i=ir(i));for(const a of i){const i=oS(KE(this,s,a[0].domain)),l=a.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:KE(this,n,t.domain)})).filter(e=>tS(t,e.rowDomain)),c=Object.groupBy(l,e=>sS(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);o[i]={};for(const e of l){const r=oS(KE(this,n,e.domain)),s=c[sS(e.rowDomain,t)];if(!s)continue;const a=s.findIndex(t=>t.value===e.value);-1!==a&&(o[i][r]=a+1)}}return"row"===n?o:je(o)}computeRunningTotal(e,t,r){const o={},n=rS(this,t),s="row"===n?"column":"row";let i=this.getPivotValueCells(e.id);"column"===n&&(i=ir(i));for(const a of i){const i=oS(KE(this,s,a[0].domain));o[i]={};const l={},c=a.map(t=>({...t,rowDomain:KE(this,n,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>tS(t,e.rowDomain));for(const e of c){const r=oS(e.rowDomain),n=iS(e.rowDomain,t),s=(l[n]||0)+e.value;l[n]=s,o[i][r]=s}if("%_running_total"===r)for(const e of c){const r=e.rowDomain,n=oS(r),s=iS(r,t),a=o[i][n]||0,c=l[s];o[i][n]=c?a/c:void 0}}return"row"===n?o:je(o)}getGrandTotal(e){const t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){const r=XE(this,t).rowDomain,o=this._getPivotCellValueAndFormat(e,r);return this.measureValueToNumber(o)}getColumnTotal(e,t){const r=XE(this,t).colDomain,o=this._getPivotCellValueAndFormat(e,r);return this.measureValueToNumber(o)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,r,o){const n=o===jE||"(next)"===o?function(e,t,r,o){const n=rS(e,r),s="row"===n?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),i=JE(KE(e,n,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 eS(t,r,a[ae(c+(o===jE?-1:1),0,a.length-1)])}(this,t,r,o):eS(t,r,o);if(Ae(n,t))return"sameValue";if(!n||!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:o}=XE(e,t);return QE(r,e.getExpandedTableStructure().getRowTree())&&QE(o,e.getExpandedTableStructure().getColTree())}(this,n))throw new x;const s=this._getPivotCellValueAndFormat(e.id,n);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 o=0;o<e.domain.length;o++){if(r[o].nameWithGranularity!==e.domain[o].field)return!1;const n=t.getPossibleFieldValues(r[o]).map(e=>e.value);if(!(n.includes(e.domain[o].value)||null===e.domain[o].value&&n.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 CT=["ADD_PIVOT","UPDATE_PIVOT","REMOVE_PIVOT"];function TT(e){return CT.includes(e.type)}const IT=new dd;IT.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 o=`${e.prefix}${r}`;return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:o},tooltip:{props:{content:o}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t,r)=>{e.current+=e.increment;const o=e.current.toString(),n=r.getLocale(),s=Qr(e.current,{format:t.cell?.format,locale:n});return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:s}}:void 0}}}).add("DATE_INCREMENT_MODIFIER",{apply:(e,t,r)=>{const o=jt(e.current,r.getLocale());o.setFullYear(o.getFullYear()+e.increment.years||0),o.setMonth(o.getMonth()+e.increment.months||0),o.setDate(o.getDate()+e.increment.days||0);const n=vt(o);e.current=n;const s=r.getLocale(),i=Qr(n,{format:t.cell?.format,locale:s});return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:n.toString()},tooltip:n?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,r)=>{const o=t.cell?.content||"",n={locale:r.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:t.cell?cw(t.cell,n).formattedValue:""}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,r,o)=>{e.current+=e.increment;let n=0,s=0;switch(o){case"up":n=0,s=-e.current;break;case"down":n=0,s=e.current;break;case"left":n=-e.current,s=0;break;case"right":n=e.current,s=0}const i=t.cell;if(!i||!i.isFormula)return{cellData:{}};const a=t.sheetId,l=r.getTranslatedCellFormula(a,n,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 xT=new dd,RT=/(\d+)$/,AT=/^(.*\D+)/,OT=/^(.*\D+)(\d+)$/,_T=/^0*/;function FT(e,t,r){let o=[],n=!1;for(const s of t){s===e&&(n=!0);const t=void 0===s||s.isFormula?void 0:cw(s,{locale:Ar,format:s.format});if(t&&r(t))o.push(t);else{if(n)return o;o=[]}}return o}function DT(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let r=e[0];for(let o=1;o<e.length;o++){const n=e[o];t.push(n-r),r=n}return t.reduce((e,t)=>e+t,0)/t.length}(e)*e.length),t}function NT(e){if(e.length<2)return 1;const t=e.map(e=>jt(e,Ar)),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 o=Je.fromTimestamp(e[r-1].getTime()),n=xt(o,t),s=Tt(o,t)%12;o.setFullYear(o.getFullYear()+n),o.setMonth(o.getMonth()+s);return{years:n,months:s,days:It(o,t)}});return t.slice(1)}(t),o=(n=r).length<2?n[0]||{years:0,months:0,days:0}:n.every(e=>e.years===n[0].years&&e.months===n[0].months&&e.days===n[0].days)?n[0]:void 0;var n;if(void 0===o)return;const s=1===Object.values(o).filter(e=>0!==e).length,i=Object.values(o).every(e=>0===e);if(!s||i){const r=t.map((e,r)=>{if(0===r)return 0;const o=t[r-1];return Math.floor(e.getTime())-Math.floor(o.getTime())}).slice(1);if(r.every(e=>e===r[0]))return e.length*(e[1]-e[0])}return{years:o.years*e.length,months:o.months*e.length,days:o.days*e.length}}xT.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&io(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&cw(e,{locale:Ar}).type===wu.text&&OT.test(e.content),generateRule:(e,t,r)=>{const o=parseInt(e.content.match(RT)[0]),n=e.content.match(AT)[0],s=FT(e,t,e=>e.type===wu.text&&OT.test(e.value)).filter(e=>n===(e.value??"").toString().match(AT)[0]).map(e=>(e.value??"").toString().match(RT)[0]),i=s.reduce((e,t)=>{const r=t.match(_T)[0].length;return r>e[1]?[t,r]:e},[s[0],0]),a=i[1]?i[0].length:0;let l=DT(s.map(e=>parseInt(e)));return["up","left"].includes(r)&&1===s.length&&(l=-l),{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:n,current:o,increment:l,numberPostfixLength:a}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&cw(e,{locale:Ar}).type===wu.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&&cw(e,{locale:Ar}).type===wu.number&&!!e.format&&io(e.format),generateRule:(e,t)=>{const r=NT(FT(e,t,e=>e.type===wu.number&&!!e.format&&io(e.format)).map(e=>Number(e.value)));if(void 0===r)return{type:"COPY_MODIFIER"};const o=cw(e,{locale:Ar});return"object"==typeof r?{type:"DATE_INCREMENT_MODIFIER",increment:r,current:o.type===wu.number?o.value:0}:{type:"INCREMENT_MODIFIER",increment:r,current:o.type===wu.number?o.value:0}},sequence:25}).add("increment_number",{condition:e=>!e.isFormula&&cw(e,{locale:Ar}).type===wu.number,generateRule:(e,t,r)=>{const o=FT(e,t,e=>e.type===wu.number&&!io(e.format||"")).map(e=>Number(e.value));let n=DT(o);["up","left"].includes(r)&&1===o.length&&(n=-n);const s=cw(e,{locale:Ar});return{type:"INCREMENT_MODIFIER",increment:n,current:s.type===wu.number?s.value:0}},sequence:40});class MT extends ME{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:r,canDispatch:o,uiActions:n,selection:s}){super(t),this.getters=e,this.ui=n,this.selection=s,this.dispatch=r,this.canDispatch=o}drawLayer(e,t){}}class VT{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:o}=IT.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:r,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}const PT=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 LT(e){return PT.has(e.type)}const kT=new dd,UT=new dd;function HT(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return sp(e.rootCommand)?function(e,t){if(!t)return;if(!kT.contains(t.type))return;return kT.get(t.type)(e,t)}(t,e.rootCommand):function(e,t,r){if(!UT.contains(t.type))return;return UT.get(t.type)(e,t,r)}(t,e.rootCommand,e.commands)}class BT{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,Wt(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 zT={type:"bar",title:{},stacked:!1,dataSetsHaveTitle:!1,dataSets:[],legendPosition:"top",humanize:!0};function $T(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 GT(e){let t="";for(const r in e)e[r]&&(t+=`${r}:${e[r]}; `);return t}var WT;function qT(e,t){const r=new Set(t.map(e=>e.left)),o=new Set(t.map(e=>e.right)),n=new Set(t.map(e=>e.top)),s=new Set(t.map(e=>e.bottom)),i=1===n.size&&1===s.size||1===r.size&&1===o.size?function(e){return e.reduce((e,t)=>{const r=e.length;for(let o=0;o<r;o++)if(cs(e[o],t))return e[o]=ss(e[o],t),e;return e[r]=t,e},[])}(t):[t[t.length-1]],a=i.map(e=>gs(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"}(WT||(WT={}));const ZT={figureHandlers:new dd,cellHandlers:new dd},YT=5242880;const jT={filterType:"criterion",type:"none",values:[]};function XT(e){return 20+120*Math.exp(-.035*(e-1))}class KT{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,r,o,n,s){if(this.getters=e,this.sheetId=t,this.boundaries=r,o.width<0||o.height<0)throw new Error("Viewport size cannot be negative");this.viewportWidth=o.height&&o.width,this.viewportHeight=o.width&&o.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=n.canScrollVertically,this.canScrollHorizontally=n.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:o}=this.getters.getRowDimensions(this.sheetId,t);let n=r-this.offsetCorrectionX;this.canScrollHorizontally&&(n=Math.max(n,this.viewportWidth));let s=o-this.offsetCorrectionY;return this.canScrollVertically&&(s=Math.max(s,this.viewportHeight),o+46>s&&!this.getters.isReadonly()&&(s+=46)),{width:n,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:o,row:n}=this.getters.getNextVisibleCellPosition(r);us(o,this.boundaries.top,this.boundaries)&&this.adjustPositionX(o),us(this.boundaries.left,n,this.boundaries)&&this.adjustPositionY(n)}adjustPositionX(e){const t=this.sheetId,{start:r,end:o}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<o?this.offsetX=o-this.viewportWidth:this.offsetX+this.offsetCorrectionX>r&&(this.offsetX=r-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){const t=this.sheetId,{start:r,end:o}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<o?this.offsetY=o-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=is(e,this),r=this.snapCorrection.x,o=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?o: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?o:0),this.viewportHeight)}}}getFullRect(e){const t=is(e,this.boundaries),r=this.snapCorrection.x,o=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-o,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 o=this.sheetId,n=this.getters.getNumberHeaders(o,e);let s=r,i=n;for(;s<=i&&s!==n&&-1!==i;){const n=Math.floor((s+i)/2),a=this.getters.getColRowOffset(e,r,n),l=this.getters.getHeaderSize(o,e,n);if(t>=a&&t<a+l)return n;t>=a+l?s=n+1:i=n-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 QT=(new h).add("settings",class extends VE{static getters=["getLocale"];locale=Ar;allowDispatch(e){return"UPDATE_LOCALE"===e.type?jl(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[o,n]of Object.entries(this.getters.getCells(r))){let r;if(n.format===e.dateFormat&&(r=t.dateFormat),n.format===e.timeFormat&&(r=t.timeFormat),n.format===ec(e)&&(r=ec(t)),r){const{col:e,row:t,sheetId:n}=this.getters.getCellPosition(o);this.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:n,format:r})}}}import(e){this.locale=e.settings?.locale??Ar}export(e){e.settings={locale:this.locale}}}).add("sheet",class extends VE{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","tryGetCellPosition"];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",Zm(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[Zm(t.name)]=t.id;for(const t of e.sheets){const e=t.name||"Sheet"+(Object.keys(this.sheets).length+1),{colNumber:r,rowNumber:o}=this.getImportedSheetSize(t),n={id:t.id,name:e,numberOfCols:r,rows:zm(o),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(n.id),this.sheets[n.id]=n}}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[Zm(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 o=this.tryGetSheet(e),n=o?.rows[r]?.cells[t];if(void 0!==n)return this.getters.getCellById(n)}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}tryGetCellPosition(e){return this.cellPosition[e]}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){return Wm(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,o=0===t.top&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:o?void 0:t.bottom,right:r&&!o?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,r){const o={...this.getPaneDivisions(e)};"COL"===r?o.xSplit=t:"ROW"===r&&(o.ySplit=t),this.history.update("sheets",e,"panes",o)}checkElementsIncludeAllNonFrozenHeaders(e,t,r){const o=this.getters.getPaneDivisions(e),n="ROW"===t?o.ySplit:o.xSplit,s=this.getters.getNumberHeaders(e,t);if(!n)return!1;return Fe(r,le(n,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(es))return"InvalidRange";if(t.length){const r=this.getSheetZone(e);return t.every(e=>hs(e,r))?"Success":"TargetOutOfSheet"}return"Success"}updateCellPosition(e){const{sheetId:t,cellId:r,col:o,row:n}=e;r?this.setNewPosition(r,t,o,n):this.clearPosition(t,o,n)}setNewPosition(e,t,r,o){const n=this.cellPosition[e];n&&this.clearPosition(t,n.col,n.row),this.history.update("cellPosition",e,{row:o,col:r,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",r,e)}clearPosition(e,t,r){const o=this.sheets[e]?.rows[r].cells[t];o&&(this.history.update("cellPosition",o,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,o,n){const s={id:e,name:t,numberOfCols:r,rows:zm(o),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},i=this.orderedSheetIds.slice();i.splice(n,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(),o=r.findIndex(t=>t===e),n=r.splice(o,1),s=this.findIndexOfTargetSheet(o,t);r.splice(s,0,n[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:o,sheets:n}=this,s=r&&r.trim().toLowerCase();return o.find(t=>Ym(n[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 o=Object.assign({},this.sheetIdsMapName);delete o[Zm(r)],o[Zm(t)]=e.id,this.history.update("sheetIdsMapName",o)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t,r){const o=re(this.getSheet(e));o.id=t,o.name=r;for(let e=0;e<=o.numberOfCols;e++)for(let t=0;t<=o.rows.length;t++)o.rows[t]&&(o.rows[t].cells[e]=void 0);const n=this.orderedSheetIds.slice(),s=n.indexOf(e);n.splice(s+1,0,o.id),this.history.update("orderedSheetIds",n),this.history.update("sheets",Object.assign({},this.sheets,{[o.id]:o}));for(const t of Object.values(this.getters.getCells(e))){const{sheetId:e,col:r,row:n}=this.getCellPosition(t.id),s=this.getters.getCellStyle({sheetId:e,col:r,row:n});this.dispatch("UPDATE_CELL",{sheetId:o.id,col:r,row:n,content:t.content,format:t.format,style:s})}const i=Object.assign({},this.sheetIdsMapName);i[Zm(o.name)]=o.id,this.history.update("sheetIdsMapName",i)}getDuplicateSheetName(e){return qm(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 o=this.orderedSheetIds.slice(),n=o.indexOf(e.id);o.splice(n,1),this.history.update("orderedSheetIds",o);const s=Object.assign({},this.sheetIdsMapName);delete s[Zm(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 o=t.filter(t=>t<e.panes.xSplit).length;o&&this.setPaneDivisions(e.id,e.panes.xSplit-o,"COL")}removeRows(e,t){t.sort((e,t)=>t-e);for(const r of ce(t)){const t=r[r.length-1],o=r[0];this.moveCellOnRowsDeletion(e,t,o),this.updateRowsStructureOnDeletion(e,t,o)}const r=t.filter(t=>t<e.panes.ySplit).length;r&&this.setPaneDivisions(e.id,e.panes.ySplit-r,"ROW")}addColumns(e,t,r,o){const n="before"===r?t:t+1;this.moveCellsOnAddition(e,n,o,"columns");const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s+o),n<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+o,"COL")}addRows(e,t,r,o){const n="before"===r?t:t+1;this.addEmptyRows(e,o),this.moveCellsOnAddition(e,n,o,"rows"),n<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+o,"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 o=e.rows[r];for(const n in o.cells){const s=Number(n),i=o.cells[n];i&&s>t&&this.setNewPosition(i,e.id,s-1,r)}}}moveCellsOnAddition(e,t,r,o){const n=[];for(let s=0;s<e.rows.length;s++){const i=e.rows[s];if("rows"!==o||s>=t)for(const a in i.cells){const l=Number(a),c=i.cells[a];c&&("rows"===o||l>=t)&&n.push({sheetId:e.id,cellId:c,col:l+("columns"===o?r:0),row:s+("rows"===o?r:0),type:"UPDATE_CELL_POSITION"})}}for(const e of n.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 o=r-t+1;for(let t=0;t<e.rows.length;t++){const n=e.rows[t];if(t>r)for(const r in n.cells){const s=Number(r),i=n.cells[r];i&&this.setNewPosition(i,e.id,s,t-o)}}}updateRowsStructureOnDeletion(e,t,r){const o=[],n=e.rows.map(e=>e.cells).reverse();for(const s in e.rows){const e=Number(s);e>=t&&e<=r||o.push({cells:n.pop()})}this.history.update("sheets",e.id,"rows",o)}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(zn);let r=e.rowNumber,o=e.colNumber;for(const{col:e,row:n}of t)r=Math.max(r,n+1),o=Math.max(o,e+1);return{rowNumber:r,colNumber:o}}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 VE{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:o}=e;if(!this.getters.tryGetSheet(o))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:o}=e;if(!this.getters.tryGetSheet(o))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 o=r.flat(),n="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=n;e<=s;e++){const r=o.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,o){return this.getHeaderGroups(e,t).find(e=>e.start===r&&e.end===o)}getHeaderGroupsInZone(e,t,r){return this.getHeaderGroups(e,t).filter(e=>{const o="ROW"===t?r.top:r.left,n="ROW"===t?r.bottom:r.right;return this.doGroupOverlap(e,o,n)})}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 o of r)for(let r=o.length-1;r>=0;r--){const n=o[r];if(0===n.start)continue;le(n.start-1,n.end+1).every(r=>this.getters.isHeaderHiddenByUser(e,t,r))&&o.splice(r,1)}return r.filter(e=>e.length>0)}isGroupFolded(e,t,r,o){return this.getHeaderGroup(e,t,r,o)?.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,o=0){const n={};for(const t of e)n[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]+o:o;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=n[this.getGroupId(t)];return a}groupHeaders(e,t,r,o){const n=this.getHeaderGroups(e,t),s=this.bricksFallingAlgorithm(n,r,o,1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(s))}unGroupHeaders(e,t,r,o){const n=this.getHeaderGroups(e,t),s=this.bricksFallingAlgorithm(n,r,o,-1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(s))}moveGroupsOnHeaderInsertion(e,t,r,o){const n=this.groups[e][t];for(let s=0;s<n.length;s++){const i=n[s],[a,l]=$m(r,o,[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 o=this.getHeaderGroups(e,t),n=[];for(const e of o){const t=Gm(r,le(e.start,e.end+1));0!==t.length&&n.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update("groups",e,t,this.bricksFallingAlgorithm(n,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,o){return this.getHeaderGroups(e,t).find(e=>e.start===r&&e.end===o)}foldHeaderGroup(e,t,r){const o=this.getGroupIndex(e,t,r.start,r.end);if(void 0===o)return;this.history.update("groups",e,t,o,"isFolded",!0);const n=this.getters.getHeaderGroups(e,t);for(let o=0;o<n.length;o++){const s=n[o];s.start===r.start&&s.end<=r.end&&this.history.update("groups",e,t,o,"isFolded",!0)}}unfoldHeaderGroup(e,t,r){const o=this.getGroupIndex(e,t,r.start,r.end);if(void 0===o)return;this.history.update("groups",e,t,o,"isFolded",!1);const n=this.getters.getHeaderGroups(e,t);for(let o=0;o<n.length;o++){const s=n[o];s.start===r.start&&s.end>=r.end&&this.history.update("groups",e,t,o,"isFolded",!1)}}getGroupIndex(e,t,r,o){const n=this.groups[e][t].findIndex(e=>e.start===r&&e.end===o);return-1===n?void 0:n}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 o=0;o<r.length;o++){const n=r[o];for(const r of n){for(let n=r.start;n<=r.end;n++){const s=Lv(t,e,n);s.outlineLevel=o+1,r.isFolded&&(s.isHidden=!0)}if(r.isFolded){Lv(t,e,r.end+1).collapsed=!0}}}}}}).add("header visibility",class extends VE{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 Fe(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)),o=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&o.push(...le(e.start,e.end+1))}),r.filter(r=>!this.hiddenHeaders[e][t][r]&&!o.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 VE{static getters=["getCoreTable","getCoreTables","getCoreTableMatchingTopLeft"];tables={};nextTableId=1;adaptRanges(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 Cs(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(cs(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),o=this.getters.getMergesInZone(e.sheetId,r.zone);o.length&&this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:o});const n=this.consumeNextId(),s=e.config||zp,i="dynamic"===e.tableType?this.createDynamicTable(n,r,s):this.createStaticTable(n,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=>!is(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 o=this.canUpdateCellCmdExtendTable(e,r);"down"===o?this.extendTableDown(t,r):"right"===o&&this.extendTableRight(t,r)}break}case"DELETE_CONTENT":{const t={...this.tables[e.sheetId]};for(const r in t){const o=t[r];o&&e.target.some(e=>hs(o.range.zone,e))&&this.dispatch("REMOVE_TABLE",{sheetId:e.sheetId,target:[o.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=>us(t,r,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>cs(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:o},n){if(!e)return"none";const s=n.range.zone;let i="none";if(s.bottom+1===o&&r>=s.left&&r<=s.right?i="down":s.right+1===r&&o>=s.top&&o<=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 o={sheetId:t,col:r,row:e},n=this.getters.getCell(o)?.content;if(n||this.getters.isInMerge(o)||this.getTablesOverlappingZones(t,[vs(o)]).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 o=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!o)return"TableNotFound";return this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==o.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,o,n){const s=r.zone;if(!n){n=[];for(const e of le(s.left,s.right+1)){const t={...s,left:e,right:e},i=this.consumeNextId();n.push(this.createFilterFromZone(i,r.sheetId,t,o))}}return{id:e,range:r,filters:n,config:o,type:t}}createDynamicTable(e,t,r){const o=ys(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,o),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 o=r||t.range,n=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,o,n):this.createStaticTable(t.id,s,o,n);this.history.update("tables",e.sheetId,t.id,r)}else{const r="dynamic"===t.type?this.updateDynamicTable(t,o,n):this.updateStaticTable(t,o,n,s);this.history.update("tables",e.sheetId,t.id,r)}}updateStaticTable(e,t,r,o=e.type){if("dynamic"===o)throw new Error("Cannot use updateStaticTable to update a dynamic table");const n=t||e.range,s=n.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,o={...s,left:t,right:t},i=r?.id||this.consumeNextId();l.push(this.createFilterFromZone(i,n.sheetId,o,a))}return{...e,range:n,config:a,filters:l.length?l:e.filters,type:o}}updateDynamicTable(e,t,r){const o=t?this.getters.getRangeFromZone(t.sheetId,ys(t.zone)):e.range,n=r||e.config;return{...e,range:o,config:n}}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,o){return NS(e,this.getters.getRangeFromZone(t,r),o,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){const r=this.getters.getRangeFromZone(e,t.range.zone),o=t.filters.map(r=>{const o=this.getters.getRangeFromZone(e,r.rangeWithHeaders.zone);return NS(r.id,o,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:r,filters:o,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 o=r(t.range);let n;switch(o.changeType){case"REMOVE":return void this.history.update("tables",e,t.id,void 0);case"NONE":return;default:n=o.range}if("dynamic"===t.type){const r=this.updateDynamicTable(t,n);return void this.history.update("tables",e,t.id,r)}const s=[];for(const e of t.filters){const o=r(e.rangeWithHeaders);switch(o.changeType){case"REMOVE":continue;case"NONE":s.push(e);break;default:const r=o.range,n=NS(e.id,r,t.config,this.getters.getRangeFromZone);s.push(n)}}const i=n.zone;if(s.length<ds(i).numberOfCols){for(let r=i.left;r<=i.right;r++)if(!s.find(e=>e.col===r)){const o=this.consumeNextId(),n={...i,left:r,right:r};s.push(this.createFilterFromZone(o,e,n,t.config))}s.sort((e,t)=>e.col-t.col)}const a=this.createStaticTable(t.id,t.type,n,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(),o=e.config||zp,n=this.getters.getRangeFromSheetXC(t.id,e.range),s=e.type||"static",i="dynamic"===s?this.createDynamicTable(r,n,o):this.createStaticTable(r,s,n,o);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:rs(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=rs(e.range.zone);t.tables.push({range:r,filters:[],config:e.config})}}}).add("dataValidation",class extends VE{static getters=["cellHasListDataValidationIcon","getDataValidationRule","getDataValidationRules","getValidationRuleForCell"];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas(e){for(const t in this.rules){for(let r=this.rules[t].length-1;r>=0;r--){const o=this.rules[t][r];for(let n=0;n<o.criterion.values.length;n++){const s=this.getters.adaptFormulaStringDependencies(t,o.criterion.values[n],e);this.history.update("rules",t,r,"criterion","values",n,s)}}}}adaptDVRanges(e,t){for(let r=this.rules[e].length-1;r>=0;r--){const o=this.rules[e][r];for(let n=o.ranges.length-1;n>=0;n--){const s=t(o.ranges[n]);switch(s.changeType){case"REMOVE":if(1===o.ranges.length)this.removeDataValidationRule(e,o.id);else{const t=o.ranges.slice();t.splice(n,1),this.history.update("rules",e,r,"ranges",t)}break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("rules",e,r,"ranges",n,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=>_m(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=Gn(e.target),r=e.sheetId;for(const e of t)for(let t=e.top;t<=e.bottom;t++)for(let o=e.left;o<=e.right;o++){const e=this.getValidationRuleForCell({sheetId:r,col:o,row:t});if(e&&("isBoolean"===e.criterion.type||"isValueInList"===e.criterion.type&&!this.getters.getCell({sheetId:r,col:o,row:t})?.content)){const e=this.rules[r],n=[this.getters.getRangeFromSheetXC(r,$n(o,t))],s=this.removeRangesFromRules(r,n,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 o of this.rules[e])for(const e of o.ranges)if(us(t,r,e.zone))return o}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 o=this.removeRangesFromRules(e,t.ranges,r,t.id),n=o.findIndex(e=>e.id===t.id);-1!==n?(o[n]=t,this.history.update("rules",e,o)):this.history.update("rules",e,[...o,t])}removeRangesFromRules(e,t,r,o){r=re(r);for(const e of r)e.id!==o&&(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 Fm(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 kE.contains(e.rule.criterion.type)?"Success":"UnknownDataValidationCriterionType"}checkCriterionHasValidNumberOfValues(e){const t=e.rule.criterion,r=kE.get(t.type).numberOfValues(t);return void 0!==r&&t.values.length!==r?"InvalidNumberOfCriterionValues":"Success"}checkCriterionValuesAreValid(e){const t=e.rule.criterion,r=kE.get(t.type);return t.values.some(e=>"onlyFormulas"===r.allowedValues&&!e.startsWith("=")||(e.startsWith("=")?"onlyLiterals"===r.allowedValues||vm(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 VE{static getters=["zoneToXC","getCells","getTranslatedCellFormula","getCellById","getFormulaString","getFormulaMovedInSheet"];nextId=1;cells={};adaptRanges(e,t,r){for(const o of Object.keys(this.cells))for(const n of Object.values(this.cells[o]||{}))if(n.isFormula)for(const s of n.compiledFormula.dependencies)if(s.sheetId===t||s.invalidSheetName===r.old){const t=e(s);"NONE"!==t.changeType&&this.history.update("cells",o,n.id,"compiledFormula","dependencies",n.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 Gn(t))for(let t=r.left;t<=r.right;t++)for(let o=r.top;o<=r.bottom;o++){const r=this.getters.getCell({sheetId:e,col:t,row:o});(r?.isFormula||r?.content)&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}setFormatter(e,t,r){for(const o of Gn(t))for(let t=o.top;t<=o.bottom;t++)for(let n=o.left;n<=o.right;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,format:r})}clearFormatting(e,t){for(const r of Gn(t))for(let t=r.left;t<=r.right;t++)for(let o=r.top;o<=r.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,format:""})}clearCells(e,t){for(const r of t)for(let t=r.left;t<=r.right;t++)for(let o=r.top;o<=r.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:"",format:""})}handleAddColumnsRows(e,t){let r,o;"before"===e.position?(r=le(e.base,e.base+e.quantity),o=e.base+e.quantity):(r=le(e.base+1,e.base+e.quantity+1),o=e.base),t(e.sheetId,o,r)}import(e){for(const t of e.sheets){const r=t.id,o=new NE;for(const e in t.cells)if(t.cells[e]){const{col:r,row:n}=zn(e),s={sheetId:t.id,col:r,row:n};o.set(s,{content:t.cells[e]})}for(const[e,r]of Dy(t.id,t.formats)){const t=o.get(e);t?t.format=r:o.set(e,{format:r})}for(const n of o.keysForSheet(r)){const r=o.get(n);if(r?.content||r?.format){const o=this.importCell(t.id,r?.content,r?.format?e.formats[r?.format]:void 0);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,...n})}}}}export(e){const t={};for(const r of e.sheets){const e=[],o={},n=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 n){const n=this.getters.getCell(r),s=$n(r.col,r.row);if(n.format){const o=_y(n.format,t);e[o]??=[],e[o].push(r)}n.content&&(o[s]=n.content)}r.formats=Fy(e),r.cells=o}e.formats=t}importCell(e,t,r){const o=this.getNextUid();return this.createCell(o,t||"",r,e)}exportForExcel(e){this.export(e);const t=[];for(const r in e.formats||[])vo(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 o=r.formats[e];o&&t.includes(o)&&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,o=!1){if(!r.length)return Ie(t.map(e=>e.value));let n=0;return Ie(t.map(t=>{if("REFERENCE"===t.type){const t=r[n++];return this.getters.getRangeString(t,e,{useBoundedReference:o})}return t.value}))}getTranslatedCellFormula(e,t,r,o){const n=this.getters.createAdaptedRanges(ym(o).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,r,e);return this.getFormulaString(e,o,n)}getFormulaMovedInSheet(e,t,r){const o=ym(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),n=this.getters.removeRangesSheetPrefix(t,o);return this.getFormulaString(t,r,n)}zoneToXC(e,t,r=[{colFixed:!1,rowFixed:!1}]){const o=$n((t=this.getters.expandZone(e,t)).left,t.top,r[0]),n=$n(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 o===n||a?o:o+":"+n}copyColumnFormat(e,t,r){for(let o=0;o<this.getters.getNumberRows(e);o++){const n=this.getFormat(e,t,o);if(n.format)for(const t of r)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,...n})}}copyRowFormat(e,t,r){for(let o=0;o<this.getters.getNumberCols(e);o++){const n=this.getFormat(e,o,t);if(n.format)for(const t of r)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,...n})}}getFormat(e,t,r){const o={},n=this.getters.getMainCellPosition({sheetId:e,col:t,row:r}),s=this.getters.getCell(n);return s&&s.format&&(o.format=s.format),o}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,r,o){const n=this.getters.getCell({sheetId:e,col:t,row:r}),s="content"in o||"formula"in o,i=s?Le(o?.content):n?.content||"",a="format"in o?o.format:n&&n.format;if((s&&!i&&!o.formula||!s&&(!n||""===n.content))&&!a)return void(n&&(this.history.update("cells",e,n.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:r,sheetId:e})));const l=n?.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,o){return t.startsWith("=")?this.createFormulaCell(e,t,r,o):this.createLiteralCell(e,t,r)}createLiteralCell(e,t,r){const o=this.getters.getLocale(),n=uw(t,o);return yo(r=r||("number"==typeof n?uo(t,o)||ho(t):void 0))||t.startsWith("'")||Pt(t)||(t=Wt(n)),{id:e,content:t,format:r,isFormula:!1,parsedValue:n}}createFormulaCell(e,t,r,o){const n=vm(t);return n.dependencies.length?this.createFormulaCellWithDependencies(e,n,r,o):{id:e,content:t,format:r,isFormula:!0,compiledFormula:{...n,dependencies:[]}}}createFormulaCellWithDependencies(e,t,r,o){const n=[];for(const e of t.dependencies)n.push(this.getters.getRangeFromSheetXC(o,e));return new PE(e,t,r,n,o,this.getters.getRangeString)}checkCellOutOfSheet(e){const{sheetId:t,col:r,row:o}=e;if(!this.getters.tryGetSheet(t))return"InvalidSheetId";return us(r,o,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,o="style"in e,n=o&&this.getters.getCellStyle(e),s="format"in e;return r&&t?.content!==e.content||o&&!Ae(n,e.style)||s&&t?.format!==e.format?"Success":"NoChanges"}}).add("merge",class extends VE{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge","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 o=this.mergeCellMap[e],n=o?t in o&&o[t]?.[r]:void 0;return n?this.getMergeById(e,n):void 0}getMergesInZone(e,t){const r=this.mergeCellMap[e];if(!r)return[];const o=new Set;for(let e=t.left;e<=t.right;e++)for(let n=t.top;n<=t.bottom;n++){const t=r[e]?.[n];t&&o.add(t)}return Array.from(o).map(t=>this.getMergeById(e,t)).filter(Se)}doesIntersectMerge(e,t){for(const r of this.getMerges(e))if(cs(t,r))return!0;return!1}doesColumnsHaveCommonMerges(e,t,r){const o=this.getters.getSheet(e);for(let n=0;n<this.getters.getNumberRows(e);n++)if(this.isInSameMerge(o.id,t,n,r,n))return!0;return!1}doesRowsHaveCommonMerges(e,t,r){const o=this.getters.getSheet(e);for(let n=0;n<=this.getters.getNumberCols(e);n++)if(this.isInSameMerge(o.id,n,t,n,r))return!0;return!1}expandZone(e,t){const{left:r,right:o,top:n,bottom:s}=t;let i={left:r,right:o,top:n,bottom:s};for(const t in this.merges[e]){const r=this.getMergeById(e,parseInt(t));r&&cs(r,i)&&(i=ss(r,i))}return as(i,t)?i:this.expandZone(e,i)}isInSameMerge(e,t,r,o,n){const s=this.getMerge({sheetId:e,col:t,row:r}),i=this.getMerge({sheetId:e,col:o,row:n});return!(!s||!i)&&as(s,i)}isInMerge({sheetId:e,col:t,row:r}){const o=this.mergeCellMap[e];return!!o&&(t in o&&Boolean(o[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),o=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 o)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 as(t,r);const{numberOfCols:o,numberOfRows:n}=ds(t);return 1===o&&1===n}isMainCellPosition(e){return Ae(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:r,right:o,top:n,bottom:s}=t;o=ae(o,0,this.getters.getNumberCols(e)-1),s=ae(s,0,this.getters.getNumberRows(e)-1);for(let t=n;t<=s;t++)for(let s=r;s<=o;s++)if(s!==r||t!==n){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?qE(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&&cs(t,r))return"MergeOverlap";return"Success"}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";const{xSplit:r,ySplit:o}=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,o)?"FrozenPaneOverlap":"Success"}checkMergedContentUpdate(e){const{col:t,row:r,content:o}=e;if(void 0===o)return"Success";const{col:n,row:s}=this.getMainCellPosition(e);return n===t&&s===r?"Success":"CellIsMerged"}checkMergeExists(e){const{sheetId:t,target:r}=e;for(const e of r){const{left:r,top:o}=e,n=this.getMerge({sheetId:t,col:r,row:o});if(void 0===n||!as(e,n))return"InvalidTarget"}return"Success"}addMerge(e,t){let{left:r,right:o,top:n,bottom:s}=t;o=ae(o,0,this.getters.getNumberCols(e)-1),s=ae(s,0,this.getters.getNumberRows(e)-1);if($n(r,n)===$n(o,s))return;const i=this.nextId++;this.history.update("merges",e,i,this.getters.getRangeFromSheetXC(e,rs({left:r,top:n,right:o,bottom:s})));const a=new Set;for(let t=n;t<=s;t++)for(let s=r;s<=o;s++){s===r&&t===n||this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,content:""});const o=this.getMerge({sheetId:e,col:s,row:t});o&&a.add(o.id),this.history.update("mergeCellMap",e,s,t,i)}for(const t of a){const{top:r,bottom:o,left:n,right:s}=this.getMergeById(e,t);for(let t=r;t<=o;t++)for(let r=n;r<=s;r++){const o={sheetId:e,col:r,row:t},n=this.getMerge(o);n&&n.id===i||(this.history.update("mergeCellMap",e,r,t,void 0),this.dispatch("CLEAR_CELL",o))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:r,top:o,bottom:n,right:s}=t,i=this.getMerge({sheetId:e,col:r,row:o});if(void 0!==i&&as(t,i)){this.history.update("merges",e,i.id,void 0);for(let t=o;t<=n;t++)for(let o=r;o<=s;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const r=Object.entries(this.merges[e]||{});for(const[o,n]of r)if(n){const r=n.zone,s=t(n);switch(s.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,r);break;default:const{numberOfCols:t,numberOfRows:n}=ds(s.range.zone);1===t&&1===n?this.removeMerge(e,r):this.history.update("merges",e,parseInt(o,10),s.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:r,row:o}of gs(t))this.history.update("mergeCellMap",e,r,o,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,Jn(r))}export(e){for(const t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...WE(e))}}exportForExcel(e){this.export(e)}}).add("style",class extends VE{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,[vs(e)],e.style,{force:!0}):this.clearStyle(e.sheetId,[vs(e)]));break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnn(e):this.handleAddRows(e);break;case"CLEAR_CELL":this.clearStyle(e.sheetId,[vs(e)]);break;case"DELETE_SHEET":this.history.update("styles",e.sheetId,void 0)}}adaptRanges(e,t){const r=[];for(const o of this.styles[t]??[]){const n=e(this.getters.getRangeFromZone(t,o.zone));switch(n.changeType){case"RESIZE":case"CHANGE":case"MOVE":r.push({style:o.style,zone:n.range.unboundedZone});break;case"NONE":r.push(o)}}this.history.update("styles",t,r)}handleAddColumnn(e){const t=this.styles[e.sheetId]??[];for(let r=0;r<t.length;r++){const o=t[r];o.zone.left-e.quantity===e.base&&"before"===e.position?this.history.update("styles",e.sheetId,r,"zone","left",o.zone.left-e.quantity):o.zone.right===e.base&&"after"===e.position&&this.history.update("styles",e.sheetId,r,"zone","right",o.zone.right+e.quantity)}}handleAddRows(e){const t=this.styles[e.sheetId]??[];for(let r=0;r<t.length;r++){const o=t[r];o.zone.top-e.quantity===e.base&&"before"===e.position?this.history.update("styles",e.sheetId,r,"zone","top",o.zone.top-e.quantity):o.zone.bottom===e.base&&"after"===e.position&&this.history.update("styles",e.sheetId,r,"zone","bottom",o.zone.bottom+e.quantity)}}styleIsDefault(e){for(const t in e)if(CS[t]!==e[t])return!1;return!0}removeDefaultStyleValues(e){const t={...e};for(const r in e)void 0!==t[r]&&t[r]!==CS[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,o={force:!1}){for(const n of t)this.setStyle(e,n,r,o)}setStyle(e,t,r,o={force:!1}){const n=[];let s=[this.getters.expandZone(e,t)];for(const i of this.styles[e]??[]){const e=is(i.zone,t);if(!e){n.push(i);continue}let a=o.force?r:{...i.style,...r};if(a=this.removeDefaultStyleValues(a),Ae(i.style,a))n.push(i);else{a&&!this.styleIsDefault(a)&&n.push({zone:e,style:a});for(const t of Gn([i.zone],[e]))n.push({zone:t,style:i.style})}s=Gn(s,[e])}(r=this.removeDefaultStyleValues(r))&&n.push(...s.map(e=>({zone:e,style:r}))),this.history.update("styles",e,n)}clearStyle(e,t){this.setStyles(e,t,void 0,{force:!0})}getCellStyle(e){const t=this.styles[e.sheetId]?.find(t=>us(e.col,e.row,t.zone));return t?.style}getCellStyleInZone(e,t){const r=new NE;for(const{zone:o,style:n}of this.styles[e]??[]){const s=is(o,t);if(s)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++)r.set({sheetId:e,col:t,row:o},n)}return r}getZoneStyles(e,t){const r=[];for(const o of this.styles[e]??[]){const e=is(o.zone,t);e&&r.push({zone:e,style:o.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 o=t.styles[r];this.setStyle(t.id,Jn(r),e.styles[o])}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.onMerge(t.id,Jn(e))}}export(e){const t={};for(const r of e.sheets){r.styles={};for(const e of this.styles[r.id]??[])r.styles[rs(e.zone)]=_y(e.style,t)}e.styles=t}exportForExcel(e){this.export(e)}checkUselessSetFormatting(e){const{sheetId:t,target:r}=e,o="style"in e,n="format"in e;if(!o&&!n)return"NoChanges";for(const s of Gn(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(o&&!Ae(l,e.style)||n&&a?.format!==e.format)return"Success"}return"NoChanges"}}).add("headerSize",class extends VE{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),o=t[e.base],n=Be(t,Array(e.quantity).fill(o),r);this.history.update("sizes",e.sheetId,e.dimension,n);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,o]of Object.entries(t.rows))o.size&&(e.ROW[r]=o.size);for(const[r,o]of Object.entries(t.cols))o.size&&(e.COL[r]=o.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 VE{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,[vs(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 o=t.top;o<=t.bottom;o++)this.addBorder(e.sheetId,{left:r,right:r,top:o,bottom:o},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(e,t){const r=[];for(const o of this.borders[t]??[]){const n=e(this.getters.getRangeFromZone(t,o.zone));switch(n.changeType){case"RESIZE":case"CHANGE":case"MOVE":r.push({...o,zone:n.range.unboundedZone});break;case"NONE":r.push(o)}}this.history.update("borders",t,r.filter(e=>!this.borderIsClear(e)))}onRowRemove(e,t){const r=new Set(t),o=[];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),o.push(e)}this.history.update("borders",e,o)}onColRemove(e,t){const r=new Set(t),o=[];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),o.push(e)}this.history.update("borders",e,o.filter(e=>!this.borderIsClear(e)))}getCellBorder(e){return this.getZoneExternalBorders(e.sheetId,vs(e))}getZoneExternalBorders(e,t){const r={};for(const o of this.borders[e]??[])cs(o.zone,t)&&(r.right=(t.right===o.zone.right?o.style.right:o.style.vertical)??r.right,r.left=(t.left===o.zone.left?o.style.left:o.style.vertical)??r.left,r.bottom=(t.bottom===o.zone.bottom?o.style.bottom:o.style.horizontal)??r.bottom,r.top=(t.top===o.zone.top?o.style.top:o.style.horizontal)??r.top);return r}getCellBordersInZone(e,t){const r=new NE;for(const o of this.borders[e]??[]){const{zone:n,style:s}=o,i=is(n,t);if(i)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++){const i=r.get({sheetId:e,col:t,row:o})??{};i.right=(t===n.right?s.right:s.vertical)??i.right,i.left=(t===n.left?s.left:s.vertical)??i.left,i.bottom=(o===n.bottom?s.bottom:s.horizontal)??i.bottom,i.top=(o===n.top?s.top:s.horizontal)??i.top,r.set({sheetId:e,col:t,row:o},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 o of this.borders[e]??[]){const e=is(o.zone,t);e&&r.push(this.computeBorderFromZone(e,o))}return r}computeBorderFromZone(e,t){const r=t.style,o=t.zone,n=e.top===o.top,s=e.bottom===o.bottom,i=e.left===o.left,a=e.right===o.right;return{zone:e,style:{top:n?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 o of this.borders[e]??[])for(const e of Gn([o.zone],[t]))for(const n of Ts(e,t)){const e=this.computeBorderFromZone(n,o),s=ls(n,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 o of t)this.addBorder(e,o,r)}addBorder(e,t,r,o=!1){const n=[],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=is(r.zone,t);if(!e){const e=ls(r.zone,t);if(e&&i[e.position])for(const e of Ts(r.zone,t)){const o=this.computeBorderFromZone(e,r),s=ls(e,t);switch(s?.position){case"left":o.style.left=void 0;break;case"right":o.style.right=void 0;break;case"top":o.style.top=void 0;break;case"bottom":o.style.bottom=void 0}n.push(o)}else n.push(r);continue}if(s){let t=this.computeBorderFromZone(e,s).style;o||(t={...this.computeBorderFromZone(e,r).style,...De(t)}),n.push({zone:e,style:t})}a=Gn(a,[e]);for(const t of Gn([r.zone],[e]))n.push(this.computeBorderFromZone(t,r))}s&&n.push(...a.map(e=>this.computeBorderFromZone(e,s))),this.history.update("borders",e,n.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),...De(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 o=t.borders[r];this.addBorder(t.id,Jn(r),e.borders[o])}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.addBordersToMerge(t.id,Jn(e))}export(e){const t={};for(const r of e.sheets){r.borders={};for(const e of this.borders[r.id]??[])r.borders[rs(e.zone)]=_y(e.style,t)}e.borders=t}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends VE{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell","getAdaptedCfRanges"];cfRules={};adaptCFFormulas(e){for(const t in this.cfRules)for(const r of this.cfRules[t])if("DataBarRule"===r.rule.type&&r.rule.rangeValues){const o=e(r.rule.rangeValues);switch(o.changeType){case"REMOVE":this.history.update("cfRules",t,this.cfRules[t].indexOf(r),"rule","rangeValues",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",t,this.cfRules[t].indexOf(r),"rule","rangeValues",o.range)}}else if("CellIsRule"===r.rule.type)for(let o=0;o<r.rule.values.length;o++)this.history.update("cfRules",t,this.cfRules[t].indexOf(r),"rule","values",o,this.getters.adaptFormulaStringDependencies(t,r.rule.values[o],e));else if("IconSetRule"===r.rule.type)for(const o of["lowerInflectionPoint","upperInflectionPoint"])"formula"===r.rule[o].type&&this.history.update("cfRules",t,this.cfRules[t].indexOf(r),"rule",o,"value",this.getters.adaptFormulaStringDependencies(t,r.rule[o].value,e));else if("ColorScaleRule"===r.rule.type)for(const o of["minimum","maximum","midpoint"]){const n=r.rule[o];"formula"===n?.type&&n?.value&&this.history.update("cfRules",t,this.cfRules[t].indexOf(r),"rule",o,"value",this.getters.adaptFormulaStringDependencies(t,n.value,e))}}adaptCFRanges(e,t){for(const r of this.cfRules[e])for(const o of r.ranges){const n=t(o);switch(n.changeType){case"REMOVE":const t=r.ranges.slice();t.splice(r.ranges.indexOf(o),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(o),n.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 o=t.top;o<=t.bottom;o++)for(let n=t.left;n<=t.right;n++){this.getRulesByCell(e,n,o).forEach(e=>{r.add(e.id)})}return r}getRulesByCell(e,t,r){const o=[];for(const n of this.cfRules[e])for(const e of n.ranges)us(t,r,e.zone)&&o.push(n);return new Set(o.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,r,o){if(0===r.length&&0===o.length)return;const n=this.getters.getConditionalFormats(e),s=n.findIndex(e=>e.id===t.id);let i=[];s>-1&&(i=n[s].ranges.map(Qn));const a=Gn(i,o);return Gn([...r,...a],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:r}={useBoundedReference:!1}){const o=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:r}));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:o}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:r})},ranges:o}}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(),o=r.findIndex(t=>t.id===e.id),n=this.mapToConditionalFormatInternal(t,e);o>-1?r.splice(o,1,n):r.push(n),this.history.update("cfRules",t,r)}checkValidPriorityChange(e,t,r){if(!this.cfRules[r])return"InvalidSheetId";const o=this.cfRules[r].findIndex(t=>t.id===e);if(-1===o)return"InvalidConditionalFormatId";const n=o-t;return n<0||n>=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=kE.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=[],o=e=>void 0===e||""===e;return t>=1&&o(e.values[0])&&r.push("FirstArgMissing"),t>=2&&o(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(vm(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&&GE(t)>=GE(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&&GE(t)>=GE(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&&GE(t)>=GE(r)?"MinBiggerThanMid":"Success"}checkCFValues(e){for(const t of e.values){if(!t.startsWith("="))continue;if(vm(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 o=this.cfRules[r].findIndex(t=>t.id===e),n=this.cfRules[r][o],s=o-t,i=[...this.cfRules[r]];i.splice(o,1),i.splice(s,0,n),this.history.update("cfRules",r,i)}}).add("figures",class extends VE{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};insertionOrders=[];adaptRanges(e,t){for(const r of this.getFigures(t)){const o=e(this.getters.getRangeFromZone(t,{left:r.col,right:r.col,top:r.row,bottom:r.row}));if("MOVE"===o.changeType)this.history.update("figures",t,r.id,"col",o.range.zone.right),this.history.update("figures",t,r.id,"row",o.range.zone.bottom);else if("REMOVE"===o.changeType){const o=e(this.getters.getRangeFromZone(t,{left:0,right:r.col-1,top:0,bottom:r.row-1}));let{offset:n,col:s,row:i}=r;"NONE"!==o.changeType&&(s=o.range.zone.right+1,i=o.range.zone.bottom+1),({offset:n,col:s,row:i}=this.getPositionInSheet(t,{...r,col:s,row:i})),this.history.update("figures",t,r.id,"offset",n),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,o=this.figures[e.sheetId]?.[r];if(!o)continue;const n=r.split(j).pop(),s=`${e.sheetIdTo}${j}${n}`;this.dispatch("CREATE_FIGURE",{figureId:s,...o,size:{width:o.width,height:o.height},sheetId:e.sheetIdTo})}}}onColRemove(e){const t=this.getters.getNumberCols(e),r=new Array(t+1);r[t]=0;for(let o=t-1;o>=0;o--)r[o]=r[o+1]+this.getters.getColSize(e,o);for(const t of this.getFigures(e))if(t.offset.x+t.width>r[t.col]){let o=t.offset.x,n=t.col;for(o=Math.min(o,r[n]-t.width);o<0&&n>0;)n--,o=r[n]-t.width;o!==t.offset.x&&this.history.update("figures",e,t.id,"offset",{x:Math.max(o,0),y:t.offset.y}),n!==t.col&&this.history.update("figures",e,t.id,"col",n)}}onRowRemove(e){const t=this.getters.getNumberRows(e),r=new Array(t+1);r[t]=0;for(let o=t-1;o>=0;o--)r[o]=r[o+1]+(this.getters.getUserRowSize(e,o)??G);for(const t of this.getFigures(e))if(t.offset.y+t.height>r[t.row]){let o=t.offset.y,n=t.row;for(let t=this.getters.getUserRowSize(e,n)??G;t<o;t=this.getters.getUserRowSize(e,n)??G)n+=1,o-=t;for(o=Math.min(o,r[n]-t.height);o<0&&n>0;)n--,o=r[n]-t.height;o!==t.offset.y&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(0,o)}),n!==t.row&&this.history.update("figures",e,t.id,"row",n)}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:o}=this.getters.getSheetSize(e);let n,s,i=0,a=0,{col:l,row:c}=t;const u={...t.offset};for(n=r;i<t.height&&n>0;n--)i+=this.getters.getUserRowSize(e,n-1)??G;for(c>n?(c=n,u.y=Math.max(i-t.height,0)):c===n&&(u.y=ae(u.y,0,Math.max(i-t.height,0))),s=o;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,...o}=e,n={...this.getFigure(r,t),...o};for(const[e,t]of Object.entries(o))switch(e){case"tag":case"offset":this.history.update("figures",r,n.id,e,t);break;case"col":case"row":case"width":case"height":void 0!==t&&this.history.update("figures",r,n.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 o=this.figures[e]?.[r];o&&t.push(o)}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 VE{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getFigureIdFromChartId","getContextCreationChart"];charts={};createChart=function(e){const t=fb.getAll().sort((e,t)=>e.sequence-t.sequence);return function(r,o,n){const s=t.find(e=>e.match(o.type));if(!s)throw new Error(`No builder for this chart: ${o.type}`);return s.createChart(o,n,e)}}(this.getters);validateChartDefinition=e=>function(e,t){const r=fb.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,t,r){for(const[o,n]of Object.entries(this.charts)){if(!n)continue;const s=n.chart.updateRanges(e,t,r);this.history.update("charts",o,s?{figureId:n.figureId,chart:s}: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:o,size:n,sheetId:s,figureId:i}=e;this.getters.getFigure(s,i)||void 0===o||void 0===t||void 0===r||this.addFigure(i,s,t,r,o,n),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:o}=this.charts[t]||{};if(!r||!o)continue;const n=this.getters.getFigure(e.sheetId,o);if(!n)continue;const s=o.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:n.col,row:n.row,offset:n.offset,size:{width:n.width,height:n.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,o=this.createChart(e.id,e.data,t.id);this.charts[r]={chart:o,figureId:e.id}}else if("carousel"===e.tag)for(const r in e.data.chartDefinitions||{}){const o=e.data.chartDefinitions[r],n=this.createChart(e.id,o,t.id);this.charts[r]={chart:n,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,o=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&"chart"===e.tag&&o){const t=this.charts[o]?.chart.getDefinition();t&&(e.data={...t,chartId:o},r.push(e))}else if(e&&"carousel"===e.tag){const o=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),n={};for(const e of o)n[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:n},r.push(e)}else r.push(e)}t.figures=r}}addFigure(e,t,r,o,n,s={width:536,height:335}){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:r,row:o,offset:n,size:s,tag:"chart"})}addChart(e,t,r){const o=this.getters.getFigureSheetId(e);if(o){const n=this.createChart(e,r,o);this.history.update("charts",t,{figureId:e,chart:n})}}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 VE{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(),o=`${e.sheetIdTo}${j}${t}`,n=this.getCarousel(r.id);if(n){const t={width:r.width,height:r.height};this.dispatch("CREATE_CAROUSEL",{sheetId:e.sheetIdTo,figureId:o,offset:r.offset,col:r.col,row:r.row,size:t,definition:{items:n.items.map(t=>{if("carouselDataView"===t.type)return{...t};const r=t.chartId.split(j).pop(),o=`${e.sheetIdTo}${j}${r}`;return{...t,chartId:o}})}})}}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 o of t)"chart"!==o.type||r.has(o.chartId)||this.dispatch("DELETE_CHART",{chartId:o.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 VE{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(),o=`${e.sheetIdTo}${j}${t}`,n=this.getImage(r.id);if(n){const t={width:r.width,height:r.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:o,offset:r.offset,col:r.col,row:r.row,size:t,definition:re(n)})}}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,o,n,s){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:r,row:o,offset:n,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 VE{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:o,pivotId:n,table:s}=e,i={sheetId:t,col:r,row:o},{cols:a,rows:l,measures:c,fieldsType:u}=s,h=new cS(a,l,c,u||{}),d=this.getPivotFormulaId(n);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,o=re(this.getPivotCore(t).definition);o.name=e.duplicatedPivotName??o.name+" (copy)",this.addPivot(r,o);break}case"UPDATE_PIVOT":this.history.update("pivots",e.pivotId,"definition",re(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures)}}adaptRanges(e){for(const t in this.pivots){const r=re(this.pivots[t]?.definition);if(!r)continue;const o=ES.get(r.type)?.adaptRanges?.(this.getters,r,e);o&&!Ae(r,o)&&this.history.update("pivots",t,"definition",o)}for(const t in this.compiledMeasureFormulas)for(const r in this.compiledMeasureFormulas[t]){const o=this.pivots[t]?.definition.measures.find(e=>e.id===r);if(!o||!o.computedBy)continue;const n=o.computedBy.sheetId,s=this.compiledMeasureFormulas[t][r].formula,i=[];for(const t of s.dependencies){const r=e(t);"NONE"===r.changeType?i.push(t):i.push(r.range)}const a=this.getters.getFormulaString(n,s.tokens,i);a!==o.computedBy.formula&&this.replaceMeasureFormula(t,o,a)}}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 o=[],n=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=n.measures.find(e=>se(e.id)===i.value&&t.id!==e.id);s&&!r.has(s.id)&&s.computedBy&&o.push(...this.computeMeasureFullDependencies(e,s,r))}return o.push(...s.dependencies.filter(e=>!e.invalidXc)),o}insertPivot(e,t,r){this.resizeSheet(e.sheetId,e,r);const o=r.getPivotCells();for(let r=0;r<o.length;r++)for(let n=0;n<o[r].length;n++){const s=o[r][n];this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col+r,row:e.row+n,content:Ld(t,s)})}}resizeSheet(e,{col:t,row:r},o){const n=o.getNumberOfDataColumns()+1,s=this.getters.getNumberCols(e),i=s-t;i<n&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:s-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:n-i,position:"after"});const a=o.columns.length+o.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=vm(t),o=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...r,dependencies:o}}replaceMeasureFormula(e,t,r){const o=this.pivots[e];if(!o)return;const n=o.definition.measures.indexOf(t);this.history.update("pivots",e,"definition","measures",n,"computedBy",{formula:r,sheetId:t.computedBy.sheetId}),this.compileCalculatedMeasures(e,o.definition.measures)}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],o=new Set,n=new Set;let s=!1;for(const e of r.groups){if(!e.name||n.has(e.name))return"InvalidPivotCustomField";if(e.values.some(e=>o.has(e)))return"InvalidPivotCustomField";if(e.isOtherGroup&&s)return"InvalidPivotCustomField";e.values.forEach(e=>o.add(e)),n.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||Nd(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 VE{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&&es(t)?this.getters.checkZonesExistInSheet(r,[t]):"InvalidDataSet"}return"Success"}}).add("tableStyle",class extends VE{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(!ib[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=ab(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(RS[e])return RS[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!sb[e]}import(e){for(const e in sb)this.styles[e]=sb[e];for(const t in e.customTableStyles){const r=e.customTableStyles[t];this.styles[t]=ab(r.displayName,r.templateName,r.primaryColor)}}export(e){const t={};for(const e in this.styles)sb[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}}),JT=(new h).add("ui_sheet",class extends MT{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getMultilineTextSize","getContiguousZone","computeTextYCoordinate"];ctx=OC();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 o=ce(le(r.top,r.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(const e of o)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 o=this.getters.getEvaluatedCell(e).formattedValue;if(o){const e=HC(this.ctx,o,t,void 0);r+=DC(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 NC(this.ctx,e,t)}getMultilineTextSize(e,t){return DC(this.ctx,e,t)}getCellText(e,t){const r=this.getters.getCell(e),o=this.getters.getLocale();if(t?.showFormula&&r?.isFormula)return Ql(r.content,o);if(t?.showFormula&&!r?.content)return"";{const r=this.getters.getCellStyle(e),n=this.getters.getEvaluatedCell(e),s=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>NC(this.ctx,e,r||{})}:void 0;return Qr(n.value,{format:n.format,locale:o,formatWidth:s})}}getCellMultiLineText(e,t){const r=this.getters.getCellStyle(e),o=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return HC(this.ctx,o,r,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,r=W,o=1){const n=e.y+1,s=AC(t,o);if(e.height>s+8){if("middle"===r)return Math.ceil(n+(e.height-s)/2);if("bottom"===r)return n+e.height-s-4}return n+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 o=!1,n=t;do{o=!1;const e=r(n);as(n,e)||(o=!0,n=e)}while(o);return n}isCellEmpty(e){const t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===wu.empty}getColMaxWidth(e,t){const r=gs(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 o of t){let t,n=0;for(const[r,s]of this.getters.getEvaluatedCellsPositionInZone(e,this.getters.getRowsZone(e,o,o))){if(void 0===s.value)continue;const o=this.getters.getColSize(e,r.col),i=this.getters.getCellStyle(r),a=s.formattedValue,l=_C(this.ctx,a,i,o);l>n&&l>G&&(n=l,t=r)}const s=t&&this.getters.getCell(t);s&&!s.isFormula&&(n=0),r.push(n||null)}const o=new Map(r.map(e=>[e,[]]));for(let e=0;e<r.length;e++)o.get(r[e])?.push(t[e]);for(const[t,r]of o)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:r,dimension:"ROW",size:t,sheetId:e})}}).add("ui_options",class extends MT{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 MT{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,o=[];switch(this.direction){case"down":for(let e=t.left;e<=t.right;e++){const n=[];for(let r=t.top;r<=t.bottom;r++)n.push($n(e,r));const s=this.createGenerator(n);for(let t=r.top;t<=r.bottom;t++)o.push(this.computeNewCell(s,e,t))}break;case"up":for(let e=t.left;e<=t.right;e++){const n=[];for(let r=t.bottom;r>=t.top;r--)n.push($n(e,r));const s=this.createGenerator(n);for(let t=r.bottom;t>=r.top;t--)o.push(this.computeNewCell(s,e,t))}break;case"left":for(let e=t.top;e<=t.bottom;e++){const n=[];for(let r=t.right;r>=t.left;r--)n.push($n(r,e));const s=this.createGenerator(n);for(let t=r.right;t>=r.left;t--)o.push(this.computeNewCell(s,t,e))}break;case"right":for(let e=t.top;e<=t.bottom;e++){const n=[];for(let r=t.left;r<=t.right;r++)n.push($n(r,e));const s=this.createGenerator(n);for(let t=r.left;t<=r.right;t++)o.push(this.computeNewCell(s,t,e))}}if(e){const e={},t={},r={},n=this.getters.getActiveSheetId();for(const s of o)this.collectBordersData(s,e),this.autofillMerge(n,s),this.autofillCell(n,s),this.collectConditionalFormatsData(n,s,t),this.collectDataValidationsData(n,s,r);this.autofillBorders(n,e),this.autofillConditionalFormats(n,t),this.autofillDataValidations(n,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(vs({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,r){const{originCol:o,originRow:n,col:s,row:i}=t,a=this.getters.getRulesByCell(e,o,n),l=$n(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:o,originRow:n,col:s,row:i}=t,a={sheetId:e,col:o,row:n},l=this.getters.getValidationRuleForCell(a);l&&(l.id in r||(r[l.id]=[]),r[l.id].push(vs({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 o="undefined"===r?void 0:JSON.parse(r);this.dispatch("SET_BORDERS_ON_TARGET",{sheetId:e,border:o,target:Gn(t[r])})}}autofillConditionalFormats(e,t){for(const r in t){const o=t[r],n=this.getters.getConditionalFormats(e).find(e=>e.id===r);if(!n)continue;const s=this.getters.getAdaptedCfRanges(e,n,o.map(Jn),[]);s&&this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:n.id,rule:n.rule,stopIfTrue:n.stopIfTrue},ranges:s,sheetId:e})}}autofillDataValidations(e,t){for(const r in t){const o=t[r],n=this.getters.getDataValidationRule(e,r);if(!n)continue;const s=n.ranges.map(e=>e.zone),i=Gn(s.concat(o),[]);this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:n,ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){const r=this.getters.getSelectedZone();if(us(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 o=this.getters.getSelectedZone();for(let t=o.bottom+1;t<=r;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==wu.empty){r=t-1;break}r>o.bottom&&(this.select(e.col,r),this.autofill(!0))}getAutofillAutoLastRow(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let r=e.left,o=e.bottom;if(r>0){let e={sheetId:t,col:r-1,row:o};for(;this.getters.getEvaluatedCell(e).type!==wu.empty;)o+=1,e={sheetId:t,col:r-1,row:o}}if(o===e.bottom&&(r=e.right,r<=this.getters.getNumberCols(t))){let e={sheetId:t,col:r+1,row:o};for(;this.getters.getEvaluatedCell(e).type!==wu.empty;)o+=1,e={sheetId:t,col:r+1,row:o}}return o-1}computeNewCell(e,t,r){const{cellData:o,tooltip:n,origin:s}=e.next(),{content:i,style:a,border:l,format:c}=o;return this.tooltip=n,{originCol:s.col,originRow:s.row,col:t,row:r,content:i,style:a,border:l,format:c}}getRule(e,t){const r=xT.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=[],o=this.getters.getActiveSheetId();for(const t of e){const{col:e,row:n}=zn(t),s=this.getters.getCell({sheetId:o,col:e,row:n});r.push({col:e,row:n,cell:s,sheetId:o})}const n=r.map(e=>e.cell);for(const e of r){let r={type:"COPY_MODIFIER"};if(e&&e.cell){r=this.getRule(e.cell,n)||r}const o=this.getters.getCellBorder(e),s=this.getters.getCellStyle(e);t.push({data:{...e,border:o,style:s},rule:r})}return new VT(t,this.getters,this.direction)}saveZone(e,t,r,o){this.autofillZone={top:e,bottom:t,left:r,right:o}}getDirection(e,t){const r=this.getters.getSelectedZone(),o={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(o).map(e=>e.number>0?1:0).reduce((e,t)=>e+t))return Object.values(o).find(e=>e.number>0?1:0).value;const n=o.up.number>0?"up":"down",s=o.left.number>0?"left":"right";return Math.abs(o[n].number)>=Math.abs(o[s].number)?o[n].value:o[s].value}autofillMerge(e,t){const{originCol:r,originRow:o,col:n,row:s}=t,i={sheetId:e,col:n,row:s},a={sheetId:e,col:r,row:o};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===o&&this.dispatch("ADD_MERGE",{sheetId:e,target:[{top:s,bottom:s+l.bottom-l.top,left:n,right:n+l.right-l.left}]})}drawLayer(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:r}=e,{x:o,y:n,width:s,height:i}=this.getters.getVisibleRect(this.autofillZone);s>0&&i>0&&(t.strokeStyle="black",t.lineWidth=r,t.setLineDash([3]),t.strokeRect(o,n,s,i),t.setLineDash([]))}}).add("sort",class extends MT{allowDispatch(e){return"SORT_CELLS"===e.type?us(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 gs(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=>cs(e,t)),o=ds(r[0]),[n,s]=[o.numberOfCols,o.numberOfRows];return r.every(e=>{const[t,r]=[e.right-e.left+1,e.bottom-e.top+1];return t===n&&r===s})?"Success":"InvalidSortZone"}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return gs(t).some(({col:t,row:r})=>{const o=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:r});return o&&!Ae(o,{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]===wu.empty&&(r=r.slice(1)),!r.some(e=>e[0]===wu.empty)&&!!r.some(e=>e[1]!==wu.empty&&e[0]!==e[1])}sortZone(e,t,r,o,n){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);!n.sortHeaders&&this.hasHeader(e,c)&&(l.top+=i),c=this.mainCells(e,l);const u=function(e,t,r){const o=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(r?o.map(e=>e.type===wu.empty?{...e,type:wu.number,value:0}:e):o).sort(Cu(t))}(c[a-l.left].map(e=>this.getters.getEvaluatedCell(e)),o,Boolean(n.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 o=c[t][h[r]],n=this.getters.getCell(o),a=this.getters.getCellStyle(o),u=l.left+t*s,d=l.top+r*i,f={sheetId:o.sheetId,col:u,row:d,content:""};if(n){let t=n.content;if(n.isFormula){const r=this.getters.getCellPosition(n.id);t=this.getters.getTranslatedCellFormula(e,0,d-r.row,n.compiledFormula.tokens)}f.style=a,f.content=t,f.format=n.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,o]=this.mainCellsSteps(e,t),n=[],s=le(t.left,t.right+1,r),i=le(t.top,t.bottom+1,o);for(const t of s){const r=[];n.push(r);for(const o of i)r.push({sheetId:e,col:t,row:o})}return n}}).add("automatic_sum",class extends MT{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:r}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,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),o=this.sumDimensions(e,t,r).filter(({zone:t})=>!this.getters.isEmpty(e,t));return r.has("ROW")&&r.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,r){const{col:o,row:n}=us(r.col,r.row,t)?r:{col:t.left,row:t.top},s=this.findAdjacentData(e,o,n);return s?this.getters.isSingleCellOrMerge(e,t)||fs(ss(s,t))?[{position:{col:o,row:n},zone:s}]:this.sumDimensions(e,ss(s,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,r){const o=this.getters.getSheet(e),n=this.getters.getMainCellPosition({sheetId:e,col:t,row:r}),s=this.findSuitableZoneToSum(o,n.col,n.row);if(s)return this.getters.expandZone(e,s)}findSuitableZoneToSum(e,t,r){const o=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:r-1}),n=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:r});if(this.isNumber(n)&&!this.isNumber(o))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 o={top:0,bottom:r-1,left:t,right:t},n=this.reduceZoneStart(e,o,o.bottom);return{...o,top:n}}findHorizontalZone(e,t,r){const o={top:r,bottom:r,left:0,right:t-1},n=this.reduceZoneStart(e,o,o.right);return{...o,left:n}}reduceZoneStart(e,t,r){const o=this.getters.getEvaluatedCellsInZone(e.id,t),n=le(r,-1,-1),s=We(n.filter(e=>o[e]&&!o[e].isAutoSummable)),i=ce(n.filter(e=>this.isNumber(o[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===wu.number&&!(e.format&&io(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 fs(t)?(r.add(1===ds(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)},gs(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)},gs(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:o}=r.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,r.zone)})`})}}nextEmptyRow(e,t){let r=t.bottom+1;const{left:o,right:n}=t;for(;!this.getters.isEmpty(e,{bottom:r,top:r,left:o,right:n});)r++;return{...t,top:r,bottom:r}}nextEmptyCol(e,t){let r=t.right+1;const{top:o,bottom:n}=t;for(;!this.getters.isEmpty(e,{left:r,right:r,top:o,bottom:n});)r++;return{...t,left:r,right:r}}transpose(e){return new Set([...e.values()].map(e=>"COL"===e?"ROW":"COL"))}}).add("format",class extends MT{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 o=[],n={};for(const r of Gn(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)){o.push(r);const e=this.getters.getPivotIdFromPosition(r)||"";n[e]??=new Set,n[e].add(i.measure)}}const s=Gn(o.map(vs));for(const e in n){const t=n[e],o=this.getters.getPivotCoreDefinition(e);this.dispatch("UPDATE_PIVOT",{pivotId:e,pivot:{...o,measures:o.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:Gn(t,s),format:r})}isSpilledPivotValueFormula(e,t){const r=this.getters.getCell(e);return"VALUE"===t.type&&!r?.isFormula}setDecimal(e,t,r){const o={};for(const n of Gn(t))for(const t of gs(n)){const n=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==n){const e=po(n,r);o[e]=o[e]||[],o[e].push(t)}}for(const t in o){const r=Gn(o[t].map(e=>vs(e)));this.setContextualFormat(e,r,t)}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==wu.number||e.format&&io(e.format)))return e.format||co(e.value)}}}).add("insert_pivot",class extends MT{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===Ss(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",style:{tableStyleId:"PivotTableStyleMedium12"}}});const o=this.getters.getSheetIds().findIndex(e=>e===r)+1,n=this.getters.getPivotFormulaId(e);this.dispatch("CREATE_SHEET",{sheetId:t,name:v("Pivot #%(formulaId)s",{formulaId:n}),position:o}),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 o=this.getters.getActiveSheetId(),n=this.getters.getSheetIds().indexOf(o)+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:n}).isSuccessful){this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:r});const n=this.getters.getPivot(e);this.insertPivotWithTable(r,0,0,t,n.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,o,n,s){const{cols:i,rows:a,measures:l,fieldsType:c}=n,u=new cS(i,a,l,c||{}),h=u.columns.length-1;if(this.resizeSheet(e,t,r,u),"dynamic"===s)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:r,content:`=PIVOT(${this.getters.getPivotFormulaId(o)})`});else{this.dispatch("INSERT_PIVOT",{sheetId:e,col:t,row:r,pivotId:o,table:u.export()});const n={left:t,right:t+u.getNumberOfDataColumns(),top:r,bottom:r+h+u.rows.length};this.dispatch("CREATE_TABLE",{tableType:"static",sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,n)],config:{...J,numberOfHeaders:h}})}}resizeSheet(e,t,r,o){const n=o.getNumberOfDataColumns()+1,s=this.getters.getNumberCols(e),i=s-t;i<n&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:s-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:n-i,position:"after"});const a=o.columns.length+o.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,o){const n={sheetId:e,col:t,row:r},s=this.getters.getSpreadZone(n),i=this.getters.getTable(n);if(!s)return;const a=this.getters.getPivotFormulaId(o),l=new Map;for(let t=s.left;t<=s.right;t++)for(let r=s.top;r<=s.bottom;r++){const o={sheetId:e,col:t,row:r};l.set(o,this.getters.getPivotCellFromPosition(o))}for(const[e,t]of l)this.dispatch("UPDATE_CELL",{...e,content:Ld(a,t)});if(this.getters.getCoreTable(n)&&this.dispatch("REMOVE_TABLE",{sheetId:e,target:[vs(n)]}),i?.isPivotTable){const t=this.getters.getRangeDataFromZone(e,s);this.dispatch("CREATE_TABLE",{tableType:"static",sheetId:e,ranges:[t],config:{...i.config,styleId:FS(i.config.styleId)}})}}}).add("pivot_presence",class extends MT{static getters=["getPivotPresenceTracker"];trackPresencePivotId;tracker;handle(e){switch(e.type){case"PIVOT_START_PRESENCE_TRACKING":this.tracker=new BT,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 MT{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===wu.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(),o=this.getters.getActiveSheetId(),n=this.getSplittedCols(r,e);t&&this.addColsToAvoidCollisions(r,n),this.removeMergesInSplitZone(r,n),this.addColumnsToNotOverflowSheet(r,n);for(let e=0;e<n.length;e++){const t=r.top+e,s=n[e],i=r.left,a=this.getters.getCell({sheetId:o,col:i,row:t}),l=this.getters.getCellStyle({sheetId:o,col:i,row:t});if(1!==s.length||s[0]!==a?.content)for(const[e,r]of s.entries())this.dispatch("UPDATE_CELL",{sheetId:o,col:i+e,row:t,content:Xl(r,this.getters.getLocale()),format:"",style:{...CS,...l}})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const r=this.getters.getActiveSheetId(),o=[];for(const n of le(e.top,e.bottom+1)){const s=this.getters.getEvaluatedCell({sheetId:r,col:e.left,row:n}).formattedValue;o.push(this.splitAndRemoveTrailingEmpty(s,t))}return o}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 o of le(e.top,e.bottom+1)){const n=t[o-e.top];for(let t=1;t<n.length;t++){const n=this.getters.getCell({sheetId:r,col:e.left+t,row:o});if(n&&n.content)return!0}}return!1}removeMergesInSplitZone(e,t){const r=this.getters.getActiveSheetId(),o=Math.max(...t.map(e=>e.length)),n={...e,right:e.left+o-1},s=this.getters.getMergesInZone(r,n);this.dispatch("REMOVE_MERGE",{sheetId:r,target:s})}addColsToAvoidCollisions(e,t){const r=this.getters.getActiveSheetId();let o=0;for(const n of le(e.top,e.bottom+1)){const s={sheetId:r,col:e.left,row:n},i=t[n-e.top],a=this.getColsToAddToAvoidCollision(s,i);o=Math.max(o,a)}o&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:r,sheetName:this.getters.getSheetName(r),quantity:o,position:"after"})}getColsToAddToAvoidCollision(e,t){const r=t.length;for(let t=1;t<r;t++){const o=e.col+t,n=this.getters.getCell({...e,col:o});if(n&&n.content)return r-t}return 0}addColumnsToNotOverflowSheet(e,t){const r=this.getters.getActiveSheetId(),o=Math.max(...t.map(e=>e.length-1)),n=this.getters.getNumberCols(r)-1;e.left+o>n&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n,sheetId:r,sheetName:this.getters.getSheetName(r),quantity:e.left+o-n,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 MT{handle(e){rp.has(e.type)&&this.dispatch("EVALUATE_CELLS",{cellIds:this.getters.getCellsWithTrackedFormula("SUBTOTAL")})}}).add("collaborative",class extends MT{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 lv)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,o=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:s}=e.position,i=this.getters.expandZone(o,{top:n,bottom:n,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 MT{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=HT(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)&&(sp(t.rootCommand)?kT.contains(t.rootCommand.type):UT.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 MT{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:o,row:n}=e,s=function(e,t){const r=t.numberOfHeaders,o={...e,top:e.top+r};return o.top<=o.bottom?o:void 0}(t.range.zone,t.config);if(s&&us(o,n,s)){const t=e.autofillRowStart??s.top,r=e.autofillRowEnd??s.bottom,o={...s,top:t,bottom:r};this.autofillTableZone(e,o)}}}autofillTableZone(e,t){if(t.top===t.bottom)return;const{col:r,row:o,sheetId:n}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==o&&this.getters.getEvaluatedCell({col:r,row:e,sheetId:n}).type!==wu.empty)return;const s={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(r,o),this.dispatch("AUTOFILL_SELECT",{col:r,row:t.bottom}),this.dispatch("AUTOFILL"),this.selection.selectCell(r,o),this.dispatch("AUTOFILL_SELECT",{col:r,row:t.top}),this.dispatch("AUTOFILL"),this.selection.selectZone(s)}}).add("table_ui_resize",class extends MT{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,o=this.getters.getRangeFromRangeData(e.newTableRange).zone;return o.top!==r.top||o.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 o=t.range.zone;if(r.bottom>=o.bottom){for(let t=r.left;t<=r.right;t++){const n={col:t,row:o.bottom,sheetId:e.sheetId};this.getters.getCell(n)?.content.startsWith("=")&&this.dispatch("AUTOFILL_TABLE_COLUMN",{...n,autofillRowStart:o.bottom,autofillRowEnd:r.bottom})}break}}}}}).add("datavalidation_insert",class extends MT{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 Fm(t)){const t=this.getters.getCell(e),r=this.getters.getEvaluatedCell(e);if(t?.content)if(t?.content&&r.type===wu.empty){let r;if(t.content.startsWith("=")){const o=this.getters.evaluateFormula(e.sheetId,t.content);r=(F(o)?o[0][0]:o)?.toString()}else r=t.content;r&&he(r)||this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}else r.type!==wu.boolean&&this.dispatch("UPDATE_CELL",{...e,content:"FALSE"});else this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}}}}).add("checkbox_toggle",class extends MT{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 o=r.top;o<=r.bottom;o++)if(this.getters.isCellValidCheckbox({col:e,row:o,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 o=r.top;o<=r.bottom;o++){const r={col:t,row:o,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 MT{static getters=["dynamicTranslate"];dynamicTranslate(e){return e}}).add("geo_features",class extends MT{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")}}),eI=(new h).add("selection",class extends MT{static layers=["Selection"];static getters=["getActiveSheet","getActiveSheetId","getActiveSheetName","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId","isGridSelectionActive","getSelectecUnboundedZone","getSelectionRangeString"];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 o=r.findIndex(t=>as(t,e.previousAnchor.zone));o>=0&&(r[o]=t.zone);break;case"newAnchor":r.push(t.zone);break;case"commitSelection":const n=r.find(e=>hs(t.zone,e)&&!as(t.zone,e));if(r.filter(e=>as(t.zone,e)).length>1&&r.length>2)r=r.filter(e=>!as(e,t.zone));else if(n){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,n);r=r.filter(e=>!as(e,t.zone)&&!as(e,n)).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:o,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:o,row:n}),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:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(r,o),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:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:r,row:o})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:r,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:r,row:o})}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 n=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(const e of n)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 o="COL"===e?"left":"top",n="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[n]-e[o]+1},(t,r)=>e[o]+r);r=r.concat(t)}return[...new Set(r)].sort()}getSelectionRangeString(e,t){const r=this.getters.expandZone(e.sheetId,e.zone),o=Tm({...e,zone:{...r,bottom:Rm(e)?void 0:r.bottom,right:Am(e)?void 0:r.right}},this.getters.getSheetSize),n=this.getters.getRangeString(o,t);if(this.getters.isSingleCellOrMerge(e.sheetId,e.zone)){const{sheetName:e,xc:t}=xn(n);return Rn(e,t.split(":")[0])}const s=this.getters.getArrayFormulaSpreadingOn({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}),i=s&&this.getters.getSpreadZone(s,{ignoreSpillError:!0});if(i&&as(i,o.zone)){const{sheetName:e,xc:t}=xn(n);return Rn(e,t.split(":")[0])+"#"}return n}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:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:r,row:o})}setSelectionMixin(e,t){const{anchor:r,zones:o}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=r,this.gridSelection.zones=o}selectCell(e,t){const r=this.getters.getActiveSheetId(),o=this.getters.expandZone(r,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:o,cell:{col:e,row:t}},[o])}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,o=ns(r,"left",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=ns(n,"left",[...e.elements]);const s={cell:{col:n.left,row:n.top},zone:o},i=this.gridSelection.zones.map(t=>ns(t,"left",[...e.elements]));this.setSelectionMixin(s,i)}onRowsRemoved(e){const{cell:t,zone:r}=this.gridSelection.anchor,o=ns(r,"top",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=ns(n,"top",[...e.elements]);const s={cell:{col:n.left,row:n.top},zone:o},i=this.gridSelection.zones.map(t=>ns(t,"top",[...e.elements]));this.setSelectionMixin(s,i)}onAddElements(e){const t="COL"===e.dimension?"left":"top",r=os(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),o=this.gridSelection.zones.map(r=>os(r,t,e.base,e.position,e.quantity)),n={cell:{col:r.left,row:r.top},zone:r};this.setSelectionMixin(n,o)}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 o="COL"===e.dimension,n=e.elements[0],s=e.elements[t-1],i=e.base<n,a=i&&o?t:0,l=i&&!o?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:o?n+a:0,right:o?s+a:this.getters.getNumberCols(e.sheetId)-1,top:o?0:n+l,bottom:o?this.getters.getNumberRows(e.sheetId)-1:s+l}],d=this.getActiveSheetId(),f=i?e.base:e.base+1,g=[{left:o?f:0,right:o?f+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:f,bottom:o?this.getters.getNumberRows(e.sheetId)-1:f+t-1}],m=ZT.cellHandlers.getKeys().map(e=>[e,new(ZT.cellHandlers.get(e))(this.getters,this.dispatch)]),p={};for(const[e,t]of m)p[e]=t.copy(qT(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 w=i?e.base:e.base+1;const E={};for(const t of c){const r=u[t];r!==this.getters.getHeaderSize(e.sheetId,e.dimension,w)&&(E[r]??=[],E[r].push(w)),w+=1}for(const t in E)this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:E[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={},o=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]]=o+t;for(const o of this.getters.getFigures(e.sheetId))"COL"===e.dimension&&o.col in r&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:o.id,col:r[o.col],row:o.row}),"ROW"===e.dimension&&o.row in r&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:o.id,row:r[o.row],col:o.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],o=e.elements[e.elements.length-1],n=e.sheetId,s=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(s(n,r-1,r)||s(n,o,o+1)||s(n,e.base-1,e.base))return"WillRemoveExistingMerge";const i=[e.base,...e.elements],a=t?this.getters.getNumberCols(n):this.getters.getNumberRows(n);return i.some(e=>e<0||e>=a)?"InvalidHeaderIndex":t||this.isTableRowMoveAllowed(n,e.elements)?"Success":"CannotMoveTableHeader"}isTableRowMoveAllowed(e,t){const r=this.getters.getCoreTables(e);if(0===r.length)return!0;const o=new Set(t);return r.every(({range:{zone:e},config:r})=>{const{top:n,bottom:s}=e;if(0===r.numberOfHeaders)return!0;const i=n+r.numberOfHeaders-1;if(!t.some(e=>e>=n&&e<=i))return!0;return le(n,s+1).every(e=>o.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,o=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,o),bottom:ae(e.bottom,0,o)})),anchor:{cell:{col:ae(t.anchor.cell.col,0,r),row:ae(t.anchor.cell.row,0,o)},zone:{left:ae(t.anchor.zone.left,0,r),right:ae(t.anchor.zone.right,0,r),top:ae(t.anchor.zone.top,0,o),bottom:ae(t.anchor.zone.bottom,0,o)}}}}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:r}=e,o=this.getSelectedZones();t.fillStyle="#f3f7fe";const n=1===o.length&&o[0].left===o[0].right&&o[0].top===o[0].bottom;t.fillStyle=n?"#f3f7fe":"#e9f0ff",t.strokeStyle=M,t.lineWidth=1.5*r;for(const e of o){const{x:r,y:o,width:n,height:s}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(r,o,n,s),t.globalCompositeOperation="source-over",t.strokeRect(r,o,n,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):vs(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 MT{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 o=this.filterValues[r][t]||[];return"values"===o.filterType?o.hiddenValues:[]}getFilterCriterionValue(e){const t=this.getters.getFilterId(e),r=e.sheetId;if(!t||!this.filterValues[r])return jT;const o=this.filterValues[r][t];return o&&"criterion"===o.filterType?o:jT}isFilterActive(e){const t=this.getters.getFilterId(e);if(!t)return!1;const r=e.sheetId,o=this.filterValues[r]?.[t];return!!o&&("values"===o.filterType?o.hiddenValues.length>0:"none"!==o.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:o}){const n=this.getters.getFilterId({sheetId:o,col:e,row:t});n&&(this.filterValues[o]||(this.filterValues[o]={}),this.filterValues[o][n]=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 o of t){const t=this.filterValues[e]?.[o.id],n=o.filteredRange?.zone;if(t&&n&&!r.has(o.rangeWithHeaders.zone.top)&&!this.getters.isRowHiddenByUser(e,o.rangeWithHeaders.zone.top))if("values"===t.filterType){const s=t.hiddenValues?.map(BC);if(!s)continue;const i=new Set(s);for(let t=n.top;t<=n.bottom;t++){const n=this.getCellValueAsString(e,o.col,t);i.has(n)&&r.add(t)}}else{if("none"===t.type)continue;const s=kE.get(t.type),i=s.preComputeCriterion?.(t,[o.filteredRange],this.getters),a=t.values.map(t=>t.startsWith("=")?this.getters.evaluateFormula(e,t)??"":uw(t,Ar));if(a.some(No))continue;const l={type:t.type,values:a.map(Fo),dateValue:t.dateValue};for(let t=n.top;t<=n.bottom;t++){const n={sheetId:e,col:o.col,row:t},a=this.getters.getEvaluatedCell(n).value??"";s.isValueValid(a,l,i)||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 o=Jn(r.range),n=[],s=[];for(const r of le(0,ds(o).numberOfCols)){const i={sheetId:t.id,col:o.left+r,row:o.top},a=this.getFilterHiddenValues(i),l=this.getters.getFilter(i),c=l?.filteredRange?gs(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));n.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=$n(i.col,i.row);t.cells[d]=h,t.cellValues[d]=h}r.filters=n}}}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 MT{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,o){if(r<=o)for(let n=r;n<=o;n++)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n;if(r>o)for(let n=r;n>=o;n--)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n}findLastVisibleColRowIndex(e,t,{last:r,first:o}){return le(r,o,-1).find(r=>!this.isHeaderHidden(e,t,r))||o}findFirstVisibleColRowIndex(e,t){const r=this.getters.getNumberHeaders(e,t);for(let o=0;o<r;o++){if("COL"===t&&!this.isColHidden(e,o))return o;if("ROW"===t&&!this.isRowHidden(e,o))return o}}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 MT{static getters=["getCellComputedBorder","getCellComputedStyle"];styles=new NE;borders=new NE;handle(e){if(Km.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 NE,void(this.borders=new NE);LT(e)?"sheetId"in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new NE,this.borders=new NE):ep.has(e.type)?this.styles=new NE:tp.has(e.type)&&(this.borders=new NE)}getCellComputedBorder(e,t){let r=this.borders.get(e);return void 0===r&&(this.precomputeCellBorders(e.sheetId,t??vs(e)),r=this.borders.get(e)),r??null}precomputeCellBorders(e,t){const r=this.getters.getCellBordersInZone(e,t),o=this.getters.getCellTableBorderZone(e,t);for(let n=t.left;n<=t.right;n++)for(let s=t.top;s<=t.bottom;s++){const t={sheetId:e,col:n,row:s};if(void 0!==this.borders.get(t))continue;const i=r.get(t),a={...De(o.get(t)),...De(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??vs(e)),r=this.styles.get(e)??{}),r}precomputeCellStyle(e,t){const r=this.getters.getCellStyleInZone(e,t),o=this.getters.getCellTableStyleZone(e,t);for(let n=t.left;n<=t.right;n++)for(let s=t.top;s<=t.bottom;s++){const t={sheetId:e,col:n,row:s};if(void 0!==this.styles.get(t))continue;const i={...De(o.get(t)),...De(this.getters.getDataValidationCellStyle(t)),...De(r.get(t)),...De(this.getters.getCellConditionalFormatStyle(t))};this.getters.getEvaluatedCell(t).link&&!i.textColor&&(i.textColor=P),this.styles.set(t,i)}}}).add("table_computed_style",class extends MT{static getters=["getCellTableStyle","getCellTableBorder","getCellTableBorderZone","getCellTableStyleZone"];tableStyles={};handle(e){Km.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type?this.tableStyles={}:LT(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 NE;for(const o of this.getters.getTablesOverlappingZones(e,[t])){const t=this.tableStyles[e][o.id]().styles;for(const o of Object.keys(t)){const n=t[o],s=parseInt(o);for(const t of Object.keys(n)){const o=n[t];o&&r.set({sheetId:e,col:s,row:parseInt(t)},o)}}}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 NE;for(const o of this.getters.getTablesOverlappingZones(e,[t])){const t=this.tableStyles[e][o.id]().borders;for(const o of Object.keys(t)){const n=t[o],s=parseInt(o);for(const t of Object.keys(n)){const o=n[t];o&&r.set({sheetId:e,col:s,row:parseInt(t)},o)}}}return r}computeTableStyle(e,t){return xe(()=>{const r=this.getters.getTableStyle(t.config.styleId),{tableMetaData:o,config:n}=this.getTableMetaData(e,t),s=function(e,t,r){return{borders:MS(e,t,r),styles:PS(e,t,r)}}(n,r,o),i=this.getTableMapping(e,t),a={borders:{},styles:{}};for(let e=0;e<o.numberOfCols;e++){const t=i.colMapping[e];a.borders[t]={},a.styles[t]={};for(let r=0;r<o.numberOfRows;r++){const o=i.rowMapping[r];a.borders[t][o]=s.borders[e][r],a.styles[t][o]=s.styles[e][r]}}return a})}getTableMetaData(e,t){const{config:r,numberOfCols:o,numberOfRows:n}=this.getTableRuntimeConfig(e,t);if(!t.isPivotTable)return{tableMetaData:{numberOfCols:o,numberOfRows:n,mode:"table"},config:r};const s={sheetId:e,col:t.range.zone.left,row:t.range.zone.top},i=this.getters.getPivotStyleAtPosition(s);if(!i)throw new Error("No dynamic pivot info found at pivot table position");const a=this.getters.getPivot(i.pivotId),l=i.pivotStyle,c=a.getExpandedTableStructure().getNumberOfRowGroupBys(),u=a.getCollapsedTableStructure().getPivotCells(l),h=new Set,d=new Set,f=new Set;let g=0;for(let r=0;r<u[0].length;r++){if(this.getters.isRowHidden(e,r+t.range.zone.top)){g++;continue}const o=u[0][r];"HEADER"===o.type&&0!==o.domain.length&&(1===o.domain.length&&c>1?h.add(r-g):o.domain.length%2==0&&c>o.domain.length?d.add(r-g):o.domain.length%2==1&&c>o.domain.length&&f.add(r-g))}return{tableMetaData:{mode:"pivot",numberOfCols:o,numberOfRows:n,mainSubHeaderRows:h,firstAlternatingSubHeaderRows:d,secondAlternatingSubHeaderRows:f,measureRow:r.numberOfHeaders&&l.displayMeasuresRow&&!this.getters.isRowHidden(e,r.numberOfHeaders-1+t.range.zone.top)?r.numberOfHeaders-1:void 0},config:r}}getTableRuntimeConfig(e,t){const r=t.range.zone,o={...t.config};let n=r.right-r.left+1,s=r.bottom-r.top+1;for(let n=r.top;n<=r.bottom;n++)this.getters.isRowHidden(e,n)&&(s--,n-r.top<t.config.numberOfHeaders&&(o.numberOfHeaders--,o.numberOfHeaders<0&&(o.numberOfHeaders=0)),n===r.bottom&&(o.totalRow=!1));for(let t=r.left;t<=r.right;t++)this.getters.isColHidden(e,t)&&(n--,t===r.left&&(o.firstColumn=!1),t===r.right&&(o.lastColumn=!1));return{config:o,numberOfCols:n,numberOfRows:s}}getTableMapping(e,t){const r={},o={};let n=0,s=0;const i=t.range.zone;for(let t=i.left;t<=i.right;t++)if(!this.getters.isColHidden(e,t)){r[n]=t,n++;for(let t=i.top;t<=i.bottom;t++)this.getters.isRowHidden(e,t)||(o[s]=t,s++)}return{colMapping:r,rowMapping:o}}}).add("header_positions",class extends MT{static getters=["getColDimensions","getRowDimensions","getColRowOffset"];headerPositions={};isDirty=!0;handle(e){switch(Km.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],o=this.getters.getColSize(e,t);return{start:r,size:o,end:r+(this.getters.isColHidden(e,t)?0:o)}}getRowDimensions(e,t){const r=this.headerPositions[e].ROW[t],o=this.getters.getRowSize(e,t);return{start:r,size:o,end:r+(this.getters.isRowHidden(e,t)?0:o)}}getColRowOffset(e,t,r,o=this.getters.getActiveSheetId()){const n=this.headerPositions[o][e][t];return this.headerPositions[o][e][r]-n}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,"COL"),ROW:this.computePositions(e,"ROW")}}computePositions(e,t){const r={};let o=0;for(let n=0;n<this.getters.getNumberHeaders(e,t)+1;n++)r[n]=o,this.getters.isHeaderHidden(e,t,n)||(o+=this.getters.getHeaderSize(e,t,n));return r}}).add("viewport",class extends MT{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:o}=function(e,t){let r,o;const{left:n,right:s,top:i,bottom:a}=e,{left:l,right:c,top:u,bottom:h}=t;return r=l!==n?l:c!==s?c:l,o=u!==i?u:h!==a?h:u,{col:r,row:o}}(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const n=e.previousAnchor.zone,s=e.anchor.zone,{top:i,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);n.left===s.left&&n.right===s.right&&(r=l>r||r>c?l:r),n.top===s.top&&n.bottom===s.bottom&&(o=i>o||o>a?i:o)}r=Math.min(r,this.getters.getNumberCols(t)-1),o=Math.min(o,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:r,row:o})}}handle(e){if(Km.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:o,offsetCorrectionY:n}=this.getMainInternalViewport(t),s=this.getters.getRowDimensions(t,r);this.shiftVertically(s.start+o-n);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:r,offsetCorrectionY:o}=this.getMainInternalViewport(e),n=this.getters.getRowDimensions(e,t);this.shiftVertically(n.end-o-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(),o=[];for(const n of e)for(const e of t){const t={sheetId:r,col:n,row:e},s=this.getters.getMainCellPosition(t);s.row===e&&s.col===n&&o.push(t)}return o}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:r,ySplit:o}=this.getters.getPaneDivisions(e),{width:n,height:s}=t.getMaxSize();return{x:this.getters.getColDimensions(e,r).start,y:this.getters.getRowDimensions(e,o).start,width:n,height:s}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:r}=this.getMainViewportRect(),o=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-o.viewportWidth),maxOffsetY:Math.max(0,r-o.viewportHeight)}}getColRowOffsetInViewport(e,t,r){if(r<t)return-this.getColRowOffsetInViewport(e,r,t);const o=this.getters.getActiveSheetId(),n="COL"===e?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),s=n.findIndex(e=>t>=e);let i=n.findIndex(e=>r<=e);i=-1===i?n.length:i;const a=n.slice(s,i);let l=0;for(const t of a)l+=this.getters.getHeaderSize(o,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 o=!1,n=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?(o=!0,s=XT(e-a),n=1):e<l&&r>=l&&c>0?(o=!0,s=XT(l-e),n=-1):i&&t<l&&e>l&&(o=!0,s=XT(e),n="reset"),{canEdgeScroll:o,direction:n,delay:s}}getEdgeScrollRow(e,t,r){let o=!1,n=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?(o=!0,s=XT(e-a),n=1):e<l&&r>=l&&c>0?(o=!0,s=XT(l-e),n=-1):i&&t<l&&e>l&&(o=!0,s=XT(e),n="reset"),{canEdgeScroll:o,direction:n,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),o={left:t,right:t,top:r,bottom:r},{x:n,width:s}=this.getVisibleRect(o),i=n-this.gridOffsetX;return{start:i,size:s,end:i+s}}getRowDimensionsInViewport(e,t){const{left:r}=this.getMainInternalViewport(e),o={left:0,right:r,top:t,bottom:t},{y:n,height:s}=this.getVisibleRect(o),i=n-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:o,maxOffsetY:n}=this.getMaximumSheetOffset();return this.getSubViewports(r).some(r=>r.willNewOffsetScrollViewport(ae(e,0,o),ae(t,0,n)))?"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,o=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=r,this.gridOffsetY=o,this.recomputeViewports()}recomputeViewports(){for(const e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){const r=this.getters.getActiveSheetId(),{maxOffsetX:o,maxOffsetY:n}=this.getMaximumSheetOffset();this.getSubViewports(r).forEach(r=>r.setViewportOffset(ae(e,0,o),ae(t,0,n)))}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),o=this.getters.getNumberCols(e),n=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 KT(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 KT(this.getters,e,{left:t,right:o-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 KT(this.getters,e,{left:0,right:t-1,top:r,bottom:n-1},{width:s,height:l},{canScrollHorizontally:!1,canScrollVertically:d},{x:0,y:d?f.y:0})||void 0,bottomRight:new KT(this.getters,e,{left:t,right:o-1,top:r,bottom:n-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:o}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(o,e);const{anchor:n}=this.getters.getSelection();if(n.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-r;this.selection.selectCell(n.cell.col,n.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let r=this.getActiveMainViewport().left,o=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset("COL",r,0);for(;e<o;r--)o-=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,o=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset("ROW",r,0);for(;e<o;r--)o-=this.getters.getRowSize(t,r-1);return Math.max(r,0)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],r=this.getters.getFigures(e),{scrollX:o,scrollY:n}=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<o+s||u>a+o+s)||(h>=i&&(h+c.height<n+i||h>l+n+i)||t.push(r))}return t}getFigureUI(e,t){const r=t.offset.x+this.getters.getColDimensions(e,t.col).start,o=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:r,y:o}}getPositionAnchorOffset(e){const{scrollX:t,scrollY:r}=this.getters.getActiveSheetScrollInfo(),o=e.x-t,n=e.y-r,s=o>=0?this.getColIndex(o):this.getColIndexLeftOfMainViewport(o),i=n>=0?this.getRowIndex(n):this.getRowIndexTopOfMainViewport(n),{x:a,y:l}=this.getRect(vs({col:s,row:i}));return{col:s,row:i,offset:{x:Math.max(o-a+this.gridOffsetX,0),y:Math.max(n-l+this.gridOffsetY,0)}}}isPixelPositionVisible(e){const{scrollX:t,scrollY:r}=this.getters.getActiveSheetScrollInfo(),{x:o,y:n}=this.getters.getMainViewportCoordinates(),{width:s,height:i}=this.getters.getSheetViewDimension();return!(e.x>=o&&(e.x<o+t||e.x>s+t+o))&&!(e.y>=n&&(e.y<n+r||e.y>i+r+n))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:r}=this.getters.getPaneDivisions(e),o=this.getters.getColDimensions(e,t).start,n=this.getters.getRowDimensions(e,r).start;return{xRatio:o/(this.sheetViewWidth+this.gridOffsetX),yRatio:n/(this.sheetViewHeight+this.gridOffsetY)}}mapViewportsToRect(e,t){let r=1/0,o=1/0,n=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),o=Math.min(o,e.y),n=Math.max(n,e.x+e.width),s=Math.max(s,e.y+e.height))}return i?{x:r,y:o,width:n-r,height:s-o}:{x:0,y:0,width:0,height:0}}}).add("clipboard",class extends MT{static layers=["Clipboard"];static getters=["getClipboardTextAndImageContent","getClipboardId","getClipboardTextContent","isCutOperation"];status="invisible";originSheetId;copiedData;_isCutOperation=!1;clipboardId=(new Dn).uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new Dn}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";const t=this.getters.getSelectedZone(),r=this.getCopiedDataAbove(t);return this.isPasteAllowed(e,r,{isCutOperation:!1})}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";const t=this.getters.getSelectedZone(),r=this.getCopiedDataOnLeft(t);return this.isPasteAllowed(e,r,{isCutOperation:!1})}case"COPY_PASTE_CELLS_ON_ZONE":{const e=this.getters.getSelectedZones();if(e.length>1)return"InvalidCopyPasteSelection";const t=this.getters.getSelectedZone(),r=this.getCopiedDataOnLeft(t);return this.isPasteAllowed(e,r,{isCutOperation:!1})}case"INSERT_CELL":{const{cut:t,paste:r}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.copy(t,"shiftCells");return this.isPasteAllowed(r,o,{isCutOperation:!0})}case"DELETE_CELL":{const{cut:t,paste:r}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),o=this.copy(t,"shiftCells");return this.isPasteAllowed(r,o,{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(),o=e.clipboardContent.imageData,n=function(e,t){const r=re(t),o=e.getSheetViewDimension(),n=o.width,s=o.height;if(r.width>n){const e=n/r.width;r.width=n,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,o.size);this.dispatch("CREATE_IMAGE",{definition:o,size:n,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();this.originSheetId=this.getters.getActiveSheetId();const t=this.getCopiedDataAbove(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();const t=this.getCopiedDataOnLeft(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case"COPY_PASTE_CELLS_ON_ZONE":{const e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();const t=this.getCopiedDataAboveOnLeft(e);this.paste([e],t,{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(!es(t[0])){this.dispatch("CLEAR_CELLS",{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}const o=this.copy(t,"shiftCells");this.paste(r,o,{isCutOperation:!0});break}case"INSERT_CELL":{const{cut:t,paste:r}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.copy(t,"shiftCells");this.paste(r,o,{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:sp(e)&&(this.status="invisible")}}getCopiedDataAbove(e){const t=e.top!==e.bottom,r={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};return this.copy([r])}getCopiedDataOnLeft(e){const t=e.left!==e.right,r={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};return this.copy([r])}getCopiedDataAboveOnLeft(e){const t={...e,right:e.left,bottom:e.top};return this.copy([t])}convertTextToClipboardData(e){const t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),r={};for(const{handlerName:o,handler:n}of t){const t=n.convertTextToClipboardData(e);r[o]=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?ZT.figureHandlers:ZT.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:o}of this.selectClipboardHandlers(t)){const n=o.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...r});if("Success"!==n)return n}return"Success"}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;const{zones:r}=this.copiedData;for(const o of r){if("COL"===t&&e<=o.right)return!0;if("ROW"===t&&e<=o.bottom)return!0}return!1}copy(e,t="copyPaste"){const r={},o=this.getClipboardData(e);for(const{handlerName:e,handler:n}of this.selectClipboardHandlers(o)){const s=n.copy(o,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 o=this.getters.getActiveSheetId(),n=this.selectClipboardHandlers(t),{target:s,zone:i,selectedZones:a}=function(e,t,r,o,n){let s;const i=[],a={sheetId:e,zones:t};for(const{handlerName:l,handler:c}of o){const o=r[l];if(!o)continue;const u=c.getPasteTarget(e,t,o,n);u.figureId&&(a.figureId=u.figureId);for(const e of u.zones)i.push(e),s=void 0!==s?ss(s,e):e}return{target:a,zone:s,selectedZones:i}}(o,e,t,n,r);void 0!==i&&this.addMissingDimensions(o,i.right-i.left+1,i.bottom-i.top+1,i.left,i.top),((e,t,r,o)=>{e.forEach(({handlerName:e,handler:n})=>{const s=t[e];s&&n.paste(r,s,o)})})(n,t,s,r),r?.selectTarget&&((e,t,r)=>{const o={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:o,zone:ss(...r)},{scrollIntoView:!1})})(this.selection,e,a)}addMissingDimensions(e,t,r,o,n){const s=r+n-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+o-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={[WT.PlainText]:this.getPlainTextContent(),[WT.Html]:await this.getHTMLContent()};return t&&e&&(r[t]=e),r}getSheetData(){const e={version:CE(),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="${GT($T(this.getters.getCellComputedStyle(t.position)))}">`+Ww(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='${Ww(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="${Ww(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>YT)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 o=new Image;o.addEventListener("load",()=>{const e=document.createElement("canvas");e.width=o.width,e.height=o.height;const r=e.getContext("2d");r?.drawImage(o,0,0),e.toBlob(t,"image/png")}),o.addEventListener("error",r),o.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 o;return o="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:[o],paste:[e]}}getInsertCellsTargets(e,t){const r=this.getters.getActiveSheetId();let o,n;return"COL"===t?(o={...e,right:this.getters.getNumberCols(r)-1},n={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:this.getters.getNumberRows(r)-1},n={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(r)-1}),{cut:[o],paste:[n]}}getClipboardData(e){const t=this.getters.getActiveSheetId(),r=this.getters.getSelectedFigureId();if(r)return{figureId:r,sheetId:t};const o=qT(t,e);return this._isCutOperation||(o.rowsIndexes=o.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),o}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:o,thinLineWidth:n}=e;o.setLineDash([8,5]),o.strokeStyle=M,o.lineWidth=3.3*n;for(const e of r){const{x:t,y:r,width:n,height:s}=this.getters.getVisibleRect(e);n>0&&s>0&&o.strokeRect(t,r,n,s)}}}).add("carousel_ui",class extends MT{static getters=["getSelectedCarouselItem","getChartFromFigureId","getChartIdFromFigureId"];uuidGenerator=new Dn;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 o=this.getters.getCarousel(e);if(!o)return;const n=this.getters.getFigure(r,e),s=this.getters.getChartDefinition(t);if(!s||!n)return;const i=this.getters.getFigureUI(r,n),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:n.width,height:n.height},definition:{...s}});const c=o.items.filter(e=>"chart"!==e.type||e.chartId!==t);this.dispatch("UPDATE_CAROUSEL",{sheetId:r,figureId:e,definition:{...o,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),o=this.uuidGenerator.smallUuid();this.dispatch("CREATE_CHART",{chartId:o,figureId:e,sheetId:t,definition:zT});const n={...r,items:[...r.items,{type:"chart",chartId:o}]};this.dispatch("UPDATE_CAROUSEL",{sheetId:t,figureId:e,definition:n})}addFigureChartToCarousel(e,t,r){const o=this.getChartIdFromFigureId(t);if(!o)return;const n=this.getters.getCarousel(e),s={...n,items:[...n.items,{type:"chart",chartId:o}]};this.dispatch("UPDATE_CAROUSEL",{sheetId:r,figureId:e,definition:s}),this.dispatch("UPDATE_CHART",{sheetId:r,chartId:o,figureId:e,definition:this.getters.getChartDefinition(o)}),this.dispatch("DELETE_FIGURE",{sheetId:r,figureId:t})}duplicateCarouselChart({carouselId:e,chartId:t,sheetId:r,duplicatedChartId:o}){const n=this.getters.getChart(t);if(!n)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:o,figureId:e,sheetId:r,definition:n.getDefinition()});const a=Be(s.items,[{type:"chart",chartId:o}],i+1);this.dispatch("UPDATE_CAROUSEL",{sheetId:r,figureId:e,definition:{...s,items:a}})}getCarouselItemId(e){return"chart"===e.type?e.chartId:"carouselDataView"}}),tI=(new h).add("evaluation",class extends BS{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 CC(e.custom,this.getters)}beforeHandle(e){(Km.has(e.type)||Jm.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 F(r)?sr(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 ms(e,t).map(this.getters.getEvaluatedCell)}getEvaluatedCellsPositionInZone(e,t){return ms(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 gs(t).map(({col:t,row:r})=>this.getEvaluatedCell({sheetId:e,col:t,row:r})).every(e=>e.type===wu.empty)}mapVisiblePositions(e,t){const{sheetId:r,zone:o}=e;return gs(o).reduce((e,o)=>{const{col:n,row:s}=o;return this.getters.isColHidden(r,n)||this.getters.isRowHidden(r,s)||e.push(t({sheetId:r,...o})),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),o=$n(t.col,t.row),n=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=US(c.compiledFormula.tokens),i=a&&u?.content===c.content,!a&&""!==n){s=(n??"").toString();const t=r.format;if(t){const r=_y(t,e.formats);l.formats[o]=r}}}const u=l.cells[o];let h;h=a&&i&&c instanceof PE?c.contentWithFixedReferences:a?u:s,l.cells[o]=h,l.cellValues[o]="error"!==r.type?n:void 0;const d=this.getSpreadZone(t);d&&(l.formulaSpillRanges[o]=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 o=this.getters.getCell(r);return o?.isFormula?o:void 0}}).add("evaluation_chart",class extends BS{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=function(e){const t=fb.getAll().sort((e,t)=>e.sequence-t.sequence);return function(r){const o=t.find(e=>e.match(r.type));if(!o)throw new Error("No runtime builder for this chart.");const n=o.getChartRuntime(r,e),s=r.getDefinition();if("chartJsConfig"in n&&/line|combo|bar|scatter|waterfall/.test(s.type)){const e=n.chartJsConfig;n.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 n}}(this.getters);handle(e){if(Km.has(e.type)||ep.has(e.type)||Qm.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:Qb(e)};if(!t)return{background:V,fontColor:Qb(V)};const r=t.zone.left,o=t.zone.top,n=t.sheetId,s=this.getters.getCellComputedStyle({sheetId:n,col:r,row:o}),i=s.fillColor||V;return{background:i,fontColor:s.textColor||Qb(i)}}async exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),r=[];for(const o of e){if(!o||"chart"!==o.tag)continue;const e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===o.id);if(!e)continue;const n=this.getters.getChart(e),s=n?.getDefinitionForExcel(this.getters);if(s)r.push({...o,data:s});else{if(!n)continue;const r=this.getters.getChartType(e),s=this.getters.getChartRuntime(e),i=await hT(s,o,r);i&&t.images.push({...o,tag:"image",data:{mimetype:"image/png",path:i,size:{width:o.width,height:o.height}}})}}t.charts=r}}}).add("evaluation_cf",class extends BS{static getters=["getConditionalIcon","getCellConditionalFormatStyle","getConditionalDataBar"];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Km.has(e.type)||ep.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:o}=e,n=this.computedStyles[t]();return n&&n[r]?.[o]}getConditionalIcon({sheetId:e,col:t,row:r}){const o=this.computedIcons[e]();return o&&o[t]?.[r]}getConditionalDataBar({sheetId:e,col:t,row:r}){const o=this.computedDataBars[e]();return o&&o[t]?.[r]}getComputedStyles(e){const t={};for(const r of this.getters.getConditionalFormats(e).reverse())switch(r.rule.type){case"ColorScaleRule":for(const o of r.ranges)this.applyColorScale(e,o,r.rule,t);break;case"CellIsRule":const o=r.rule.values.map(e=>e.startsWith("=")?vm(e):void 0),n=kE.get(r.rule.operator),s={...r.rule,type:r.rule.operator},i=r.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t)),a=n.preComputeCriterion?.(s,i,this.getters);for(const n of r.ranges){const s=this.getters.getRangeFromSheetXC(e,n).zone;for(let n=s.top;n<=s.bottom;n++)for(let i=s.left;i<=s.right;i++){const l={sheetId:e,col:i,row:n},c=r.rule.values.map((t,r)=>{const a=o[r];return a?this.getters.getTranslatedCellFormula(e,i-s.left,n-s.top,a.tokens):t});this.getRuleResultForTarget(l,{...r.rule,values:c},a)&&(t[i]||(t[i]=[]),t[i][n]=Object.assign(t[i]?.[n]||{},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 o of r.ranges)this.applyIcon(e,o,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 o of r.ranges)this.applyDataBar(e,o,r.rule,t);return t}parsePoint(e,t,r,o){const n=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter(e=>e.type===wu.number).map(e=>e.value);switch(r.type){case"value":return"max"===o?We(n):qe(n);case"number":return Number(r.value);case"percentage":const t=qe(n);return t+(We(n)-t)*Number(r.value)/100;case"percentile":return Nt(n,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,o){const n=this.parsePoint(e,t,r.lowerInflectionPoint),s=this.parsePoint(e,t,r.upperInflectionPoint);if(null===n||null===s||n>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!==wu.number)continue;const c=this.computeIcon(i.value,s,r.upperInflectionPoint.operator,n,r.lowerInflectionPoint.operator,a);o[l]||(o[l]=[]),o[l][t]=c}}computeIcon(e,t,r,o,n,s){return"ge"===r&&e>=t||"gt"===r&&e>t?s[0]:"ge"===n&&e>=o||"gt"===n&&e>o?s[1]:s[2]}applyDataBar(e,t,r,o){const n=this.getters.getRangeFromSheetXC(e,r.rangeValues||t),s=We(this.getters.getEvaluatedCellsInZone(e,n.zone).filter(e=>e.type===wu.number).map(e=>e.value));if(s<=0)return;const i=r.color,a=this.getters.getRangeFromSheetXC(e,t).zone,l=n.zone;for(let t=a.top;t<=a.bottom;t++)for(let r=a.left;r<=a.right;r++){const n=r-a.left+l.left,c=t-a.top+l.top,u=this.getters.getEvaluatedCell({sheetId:e,col:n,row:c});!us(n,c,l)||u.type!==wu.number||u.value<=0||(o[r]||(o[r]=[]),o[r][t]={color:fp(i),percentage:100*u.value/s})}}applyColorScale(e,t,r,o){const n=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===n||null===i||n>=i||s&&(n>=s||s>=i))return;const a=this.getters.getRangeFromSheetXC(e,t).zone,l=[{value:n,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 o=xp(t[e-1].color).a,n=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:o,maxColorAlpha:n,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===wu.number){const e=ae(s.value,n,i);o[r]||(o[r]=[]),o[r][t]=o[r]?.[t]||{},o[r][t].fillColor=c(e)}}}getRuleResultForTarget(e,t,r){const o=this.getters.getEvaluatedCell(e);if(o.type===wu.error)return!1;const{sheetId:n}=e,s=kE.get(t.operator),i=t.values.map(e=>e.startsWith("=")?this.getters.evaluateFormula(n,e)??"":uw(e,Ar));if(i.some(No))return!1;const a={...t,type:t.operator,values:i.map(Fo),dateValue:t.dateValue||"exactDate"};return s.isValueValid(o.value??"",a,r)}}).add("row_size",class extends BS{static getters=["getRowSize","getHeaderSize","getMaxAnchorOffset"];tallestCellInRow={};ctx=OC();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),o=Be(this.tallestCellInRow[e.sheetId],r,t);this.history.update("tallestCellInRow",e.sheetId,o)}}handle(e){switch(e.type){case"START":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 o of e.elements)this.updateRowSizeForCellChange(t,r,o)}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 gs(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:o,numberOfCols:n}=this.getters.getSheetSize(e),s=0;for(;s<t&&o>0;o--)s+=this.getRowSize(e,o-1);let i=0;for(;i<r&&n>0;n--)i+=this.getters.getColSize(e,n-1);return{col:n,row:o,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 o=this.tallestCellInRow[e]?.[t];if(o?.cell.col===r){const r=this.getRowTallestCell(e,t);this.history.update("tallestCellInRow",e,t,r)}const n=this.getCellHeight({sheetId:e,col:r,row:t});if(!(n<=G)&&(!o&&n>G||o&&n>o.size)){const o={cell:{sheetId:e,col:r,row:t},size:n};this.history.update("tallestCellInRow",e,t,o)}}initializeSheet(e){const t=[];for(let r=0;r<this.getters.getNumberRows(e);r++){const o=this.getRowTallestCell(e,r);t.push(o)}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),o=this.getters.getColSize(e.sheetId,e.col);return function(e,t,r,o){return t&&(t.isFormula||t.content)?_C(e,t.isFormula?"":t.content,r,o):G}(this.ctx,t,r,o)}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 o,n=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>n&&i>G&&(n=i,o={cell:s,size:i})}return o&&o.size>G?o:void 0}}).add("data_validation_ui",class extends BS{static getters=["getDataValidationInvalidCriterionValueMessage","getInvalidDataValidationMessage","getValidationResultForCellValue","getDataValidationRangeValues","isCellValidCheckbox","getDataValidationCellStyle","getDataValidationChipStyle","isDataValidationInvalid"];validationResults={};criterionPreComputeResult={};handle(e){if(Km.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))return this.validationResults={},void(this.criterionPreComputeResult={});switch(e.type){case"ADD_DATA_VALIDATION_RULE":case"REMOVE_DATA_VALIDATION_RULE":delete this.validationResults[e.sheetId],delete this.criterionPreComputeResult[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=kE.get(e);return t.startsWith("=")?"onlyLiterals"===r.allowedValues?v("The value must not be a formula"):this.isValidFormula(t)?void 0:hd.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])),o=[],n=new Set;for(const e of gs(r.zone)){const t=this.getters.getEvaluatedCell({...e,sheetId:r.sheetId});t.formattedValue&&!n.has(t.formattedValue)&&(n.add(t.formattedValue),o.push({label:t.formattedValue,value:t.value?.toString()||""}))}return o}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 gT;const o=this.getRuleErrorForCellValue(e,t,r);return o?{error:o,rule:r,isValid:!1}:gT}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),o=this.getValueColor(t,r.value);if(!o)return;var n;return{fillColor:o,textColor:(n=o,yp(n)<.6?Rp(n,.9):Ap(n,.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!vm(e).isBadExpression}getValidationResultForCell(e){const{col:t,row:r,sheetId:o}=e;return this.validationResults[o]||(this.validationResults[o]=this.computeSheetValidationResults(o)),this.validationResults[o][t]?.[r]?.()||gT}computeSheetValidationResults(e){const t={},r=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(const e of Fm(r.flat())){const{col:r,row:o}=e;t[r]||(t[r]=[]),t[r][o]=xe(()=>{const t=this.getters.getEvaluatedCell(e);return t.type===wu.empty?gT:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,r){const{sheetId:o}=t,n=r.criterion,s=kE.get(n.type),i=this.getCellOffsetInRule(t,r),a=this.getEvaluatedCriterionValues(o,i,n);if(a.some(No))return;const l={...n,values:a.map(Fo)};this.criterionPreComputeResult[o]||(this.criterionPreComputeResult[o]={});let c=this.criterionPreComputeResult[o][r.id];return void 0===c&&(c=s.preComputeCriterion?.(r.criterion,r.ranges,this.getters),this.criterionPreComputeResult[o][r.id]=c),s.isValueValid(e,l,c)?void 0:s.getErrorString(l,this.getters,o)}getCellOffsetInRule(e,t){const r=t.ranges.find(t=>us(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 uw(r,Ar);const o=vm(r),n=this.getters.getTranslatedCellFormula(e,t.col,t.row,o.tokens);return this.getters.evaluateFormula(e,n)})}}).add("dynamic_tables",class extends BS{static getters=["canCreateDynamicTableOnZones","doesZonesContainFilter","getFilter","getFilters","getTable","getTables","getTablesOverlappingZones","getFilterId","getFilterHeaders","isFilterHeader"];tables={};handle(e){if(Km.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)].filter(e=>"dynamic"!==e.type);t.push(...r);for(const o of this.getDynamicTables(e)){const n=this.coreTableToTable(e,o);let s=n.range.zone;for(const e of r)cs(s,e.range.zone)&&(s={...s,right:e.range.zone.left-1});t.push({...n,range:this.getters.getRangeFromZone(e,s)})}return t}getDynamicTables(e){const t=this.getters.getCoreTables(e).filter(e=>"dynamic"===e.type),r=this.getTablesFromPivots(e),o=new Set(r.map(t=>this.getters.getRangeString(t.range,e))),n=t.filter(t=>!o.has(this.getters.getRangeString(t.range,e)));return[...r,...n]}getTablesFromPivots(e){const t=[];for(const{position:r,pivotStyle:o,pivotId:n}of this.getters.getAllPivotArrayFormulas()){const s=this.getters.getSpreadZone(r),i=this.getters.getCell(r);r.sheetId===e&&s&&i&&"None"!==o.tableStyleId&&t.push({type:"dynamic",id:"pivot_table_"+n+"_"+i.id,range:this.getters.getRangeFromZone(e,vs(r)),config:this.getTableConfigFromPivotStyle(n,o),isPivotTable:!0})}return t}getTableConfigFromPivotStyle(e,t){const r=this.getters.getPivot(e).getCollapsedTableStructure();return{hasFilters:t.hasFilters,totalRow:t.displayTotals,firstColumn:!0,lastColumn:!0,numberOfHeaders:r.getPivotTableDimensions(t).numberOfHeaderRows,bandedRows:t.bandedRows,bandedColumns:t.bandedColumns,styleId:t.tableStyleId}}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){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=>us(t,r,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>cs(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 o=r.range.zone,n=o.top;for(let r=o.left;r<=o.right;r++)t.push({sheetId:e,col:r,row:n})}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(!Cs(t))return!1;const r=ss(...t),o={col:r.left,row:r.top,sheetId:e},n=this.getters.getArrayFormulaSpreadingOn(o);if(!n){const e=this.getters.getEvaluatedCell(o);return e.value===w.SpilledBlocked&&!e.errorOriginPosition}if(Ae(n,o)&&1===Ss(r))return!0;return Ae(r,this.getters.getSpreadZone(n))}coreTableToTable(e,t){if("dynamic"!==t.type)return t;const r=t.range.zone,o={sheetId:e,col:r.left,row:r.top},n=this.getters.getSpreadZone(o)??t.range.zone,s=this.getters.getRangeFromZone(e,n),i=this.getDynamicTableFilters(e,t,n);return{id:t.id,range:s,filters:i,config:t.config,isPivotTable:t.isPivotTable}}getDynamicTableFilters(e,t,r){const o=[],{top:n,bottom:s,left:i,right:a}=r;for(let r=i;r<=a;r++){const a=r-i,l={left:r,right:r,top:n,bottom:s},c=NS(this.getDynamicTableFilterId(t.id,a),this.getters.getRangeFromZone(e,l),t.config,this.getters.getRangeFromZone);o.push(c)}return o}getDynamicTableFilterId(e,t){return e+"_"+t}exportForExcel(e){for(const t of e.sheets)for(const e of t.tables){const r=Jn(e.range),o={sheetId:t.id,col:r.left,row:r.top},n=this.getters.getCoreTable(o),s=this.getTable(o);"dynamic"===n?.type&&s&&(e.range=rs(s.range.zone))}}}).add("custom_colors",class extends BS{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(Ep)){let e=500,o=0;t.forEach((t,n)=>{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,o=n)}),t[o].colors.push(r)}return t.map(e=>e.colors.sort((e,t)=>Cp(e).s-Cp(t).s)).flat().map(wp)}(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(qC)].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 BS{static getters=["getPivot","getFirstPivotFunction","getPivotCellSortDirection","getPivotIdFromPosition","getPivotCellFromPosition","generateNewCalculatedMeasureName","isPivotUnused","isSpillPivotFormula","getAllPivotArrayFormulas","getPivotStyleAtPosition"];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(Km.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(TT);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 yS)yS[e].set.clear(),yS[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 HS(e,wT)[0]}(t);if(!r)return;const{functionName:o,args:n}=r;return{functionName:o,args:n.map(t=>{if("EMPTY"===t.type)return;if("STRING"===t.type||"BOOLEAN"===t.type||"NUMBER"===t.type)return t.value;const r=bT(t);return this.getters.evaluateFormula(e,r)})}}getPivotCellFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||0===HS(t.compiledFormula.tokens,wT).length)return uS;const r=this.getters.getCellPosition(t.id),o=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!o)return uS;let{functionName:n,args:s}=o;const i=s[0];if(!i)return uS;const a=this.getters.getPivotId(i.toString());if(!a)return uS;const l=this.getPivot(a);if(!l.isValid())return uS;if("PIVOT"===n&&!this.isMainFunctionPivotSpreadFunction(t))return uS;if("PIVOT"===n){const t=Zd(this.getters.getPivotCoreDefinition(a),Fo(s[1]),Fo(s[2]),Fo(s[3]),Fo(s[4]),Fo(s[5]),this.getters.getLocale()),o=l.getCollapsedTableStructure().getPivotCells(t),n=e.col-r.col,i=e.row-r.row;return o[n][i]}try{const t=e.row-r.row,o=e.col-r.col;if(s=s.map(e=>F(e)?e[o][t]:e),"PIVOT.HEADER"===n&&"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"===n){const e=l.parseArgsToPivotDomain(s.slice(1).map(e=>({value:e})));return{type:"HEADER",domain:e,dimension:XE(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 uS}}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 o=this.getters.getPivot(t),n=XE(o,r.domain).colDomain,s=o.definition.sortedColumn;return s?.measure===r.measure&&Ae(s.domain,n)?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=ST(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),o=this.getPivotIdFromPosition(t);if(o&&(e.delete(o),!e.size))return this.unusedPivotsInFormulas=[],[]}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}getAllPivotArrayFormulas(){const e=[];for(const t of this.getters.getCellsWithTrackedFormula("PIVOT")){const r=this.getters.getCellPosition(t),o=this.getPivotStyleAtPosition(r);o&&e.push({position:r,...o})}return e}getPivotStyleAtPosition(e){const t=this.getters.getCell(e);if(!t||!t.isFormula||!this.isMainFunctionPivotSpreadFunction(t))return;const r=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r||"PIVOT"!==r.functionName)return;const o=r.args[0];if(!o)return;const n=this.getters.getPivotId(o.toString());if(!n)return;return{pivotStyle:Zd(this.getters.getPivotCoreDefinition(n),Fo(r.args[1]),Fo(r.args[2]),Fo(r.args[3]),Fo(r.args[4]),Fo(r.args[5]),this.getters.getLocale()),pivotId:n}}isMainFunctionPivotSpreadFunction(e){const t=e.compiledFormula.tokens.find((e,t)=>t>0&&"SPACE"!==e.type);return"SYMBOL"===t?.type&&"PIVOT"===t.value.toUpperCase()}}).add("cell_icon",class extends BS{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,o=this.getters.getCellStyle(r)?.verticalAlign;return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,o),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,r){const o=e.x,n=e.x+e.width;switch(t){case"right":return n-r.margin-r.size;case"left":return o+r.margin;default:const e=Math.floor((n-o-r.size)/2);return n-r.size-e}}computeCellIcons(e){const t={left:void 0,right:void 0,center:void 0},r=WC.getAll();for(const o of r){const r=o(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)}}).add("formula_tracker",class extends BS{static getters=["getCellsWithTrackedFormula"];trackedCells={};handle(e){switch(e.type){case"START":for(const e of mT)this.trackedCells[e]={};for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t){const r=t[e];for(const e of mT)Qe(r,e)&&this.history.update("trackedCells",e,r.id,!0)}}break;case"UPDATE_CELL":{if(!("content"in e))return;const t=this.getters.getCell(e);if(!t)return;for(const e of mT)Qe(t,e)?this.history.update("trackedCells",e,t.id,!0):this.trackedCells[e][t.id]&&this.history.update("trackedCells",e,t.id,void 0);break}}}getCellsWithTrackedFormula(e){return Object.keys(this.trackedCells[e]||{}).filter(t=>this.trackedCells[e][t]&&this.getters.tryGetCellPosition(t))}});class rI{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=["adaptFormulaStringDependencies","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=Nm(e);t?.applyChange&&this.executeOnAllRanges(t.applyChange,t.sheetId,t.sheetName)}finalize(){}verifyRangeRemoved(e){return t=>{const r=e(t);return"NONE"===r.changeType||es(r.range.zone)?r:{range:r.range,changeType:"REMOVE"}}}executeOnAllRanges(e,t,r){this.isAdaptingRanges=!0;const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t,r);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,r,o){return e.map(e=>{if(!es(e.zone))return e;const n=e.prefixSheet?e.sheetId:o,s=Am(e),i=Rm(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(ts(e.zone))return e;const t={...e.unboundedZone},r={...e.zone};let o=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,o=[{colFixed:o[1]?.colFixed||!1,rowFixed:o[0]?.rowFixed||!1},{colFixed:o[0]?.colFixed||!1,rowFixed:o[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,o=[{colFixed:o[0]?.colFixed||!1,rowFixed:o[1]?.rowFixed||!1},{colFixed:o[1]?.colFixed||!1,rowFixed:o[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:r,parts:o,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}(Tm({...e,sheetId:n,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 o="COL"===t?e.zone.right+r:e.zone.right,n="ROW"===t?e.zone.bottom+r:e.zone.bottom,s={left:e.zone.left,top:e.zone.top,right:Am(e)?void 0:o,bottom:Rm(e)?void 0:n};return Tm({...e,zone:s},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!wn.test(t)||!this.getters.tryGetSheet(e))return xm(t);const{sheetName:r}=xn(t);return Im({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)?Om(e,t,this.getters.getSheetName,r):w.InvalidReference:w.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 Tm({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),o=t.map(e=>e.unboundedZone);return Gn(r,o).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){if(!this.getters.tryGetSheet(e._sheetId))return xm(w.InvalidReference);return Tm({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}=xn(e);return null!==t.match(wn)&&(!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)}adaptFormulaStringDependencies(e,t,r){if(!t.startsWith("="))return t;const o=vm(t),n=o.dependencies.map(t=>{const o=this.getters.getRangeFromSheetXC(e,t),n=r(o);return"NONE"===n.changeType?o:n.range});return this.getters.getFormulaString(e,o.tokens,n)}copyFormulaStringForSheet(e,t,r,o){if(!r.startsWith("="))return r;const n=vm(r),s=n.dependencies.map(r=>{const n=this.getters.getRangeFromSheetXC(e,r);return"keepSameReference"===o?n:_m(e,t,n)});return this.getters.getFormulaString(t,n.tokens,s)}}class oI{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 nI{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new oI,this.anchor={cell:{col:0,row:0},zone:vs({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 o=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(o,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=vs({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 ip("InvalidSelectionStep");const{col:r,row:o}=this.getNextAvailablePosition(e,t);return this.selectCell(r,o)}setAnchorCorner(e,t){const r=this.getters.getActiveSheetId(),{col:o,row:n}=this.anchor.cell,s={left:Math.min(o,e),top:Math.min(n,t),right:Math.max(o,e),bottom:Math.max(n,t)},i=this.getters.expandZone(r,s);if(as(this.anchor.zone,i))return new ip("NoChanges");const a={zone:i,cell:{col:o,row:n}};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 o=this.getters.expandZone(r,vs({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:o,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 ip("InvalidSelectionStep");const r=this.getters.getActiveSheetId(),o=this.anchor,{col:n,row:s}=o.cell,{left:i,right:a,top:l,bottom:c}=o.zone,u=this.getStartingPosition(e),[h,d]=this.deltaToTarget(u,e,t);if(0===h&&0===d)return ip.Success;let f=o.zone;const g=e=>{e=ps(e);const{left:t,right:o,top:n,bottom:s}=this.getters.expandZone(r,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(r)-1,o),top:Math.max(0,n),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?ps(f):f,f&&!as(f,o.zone))return this.processEvent({options:{scrollIntoView:!0},mode:"updateAnchor",anchor:{zone:f,cell:{col:n,row:s}}})}f=g(ss({top:s,bottom:s,left:n,right:n},ps({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 w={zone:f,cell:{col:n,row:s}};return this.processEvent({anchor:w,mode:"updateAnchor",options:{scrollIntoView:!0}})}selectColumn(e,t){const r=this.getters.getActiveSheetId(),o=this.getters.getNumberRows(r)-1;let n={left:e,right:e,top:0,bottom:o};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),n=ss(n,{left:i,right:i,top:s,bottom:o})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:n,cell:{col:i,row:a}},mode:t})}selectRow(e,t){const r=this.getters.getActiveSheetId(),o=this.getters.getNumberCols(r)-1;let n={top:e,bottom:e,left:0,right:o};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),n=ss(n,{left:s,right:o,top:a,bottom:a})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:n,cell:{col:i,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(as(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:vs(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 ip(r):(this.anchor=t.anchor,this.stream.send(t),ip.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:r}=e;if(!us(t.col,t.row,r))return"InvalidAnchorZone";const{left:o,right:n,top:s,bottom:i}=r,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",o,n);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:o}=this.anchor.cell,n=this.deltaToTarget({col:r,row:o},e,t);return{col:this.getNextAvailableCol(n[0],r,o),row:this.getNextAvailableRow(n[1],r,o)}}getNextAvailableCol(e,t,r){const o=this.getters.getActiveSheetId(),n={col:t,row:r};return this.getNextAvailableHeader(e,"COL",t,n,e=>this.getters.isInSameMerge(o,t,r,e,r))}getNextAvailableRow(e,t,r){const o=this.getters.getActiveSheetId(),n={col:t,row:r};return this.getNextAvailableHeader(e,"ROW",r,n,e=>this.getters.isInSameMerge(o,t,r,t,e))}getNextAvailableHeader(e,t,r,o,n){const s=this.getters.getActiveSheetId();if(0===e)return r;const i=Math.sign(e);let a=r+e;for(;n(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,o,n):r:a}getReferenceAnchor(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:r,right:o,top:n,bottom:s}=t.zone,{col:i,row:a}=t.cell,l=this.getters.isColHidden(e,i)&&this.getters.findVisibleHeader(e,"COL",r,o)||i,c=this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",n,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 o=this.anchor.zone;switch(e){case"down":case"up":r=r===o.top?o.bottom:o.top;break;case"left":case"right":t=t===o.right?o.left:o.right}return{col:t,row:r}}getEndOfCluster(e,t,r){const o=this.getters.getActiveSheetId();let n=e;const s=this.getNextCellPosition(e,t,r),i=this.isCellSkippableInCluster({...n,sheetId:o})||this.isCellSkippableInCluster({...s,sheetId:o})?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(n,t,r);if(n.col===e.col&&n.row===e.row)break;const s=this.isCellSkippableInCluster({...e,sheetId:o});if("endOfCluster"===i&&s)break;if("nextCluster"===i&&!s){n=e;break}n=e}return"cols"===t?n.col:n.row}getNextCellPosition(e,t,r){const o={...e};return o["cols"===t?"col":"row"]="cols"===t?this.getNextAvailableCol(r,o.col,o.row):this.getNextAvailableRow(r,o.col,o.row),{col:o.col,row:o.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){const t=this.getters.getMainCellPosition(e),r=this.getters.getEvaluatedCell(t);return r.type===wu.empty||r.type===wu.text&&""===r.value}}class sI{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 o=e.at(-1),n=e.length-2;for(let t=1;t<=n;t++){const o=e[t];if(void 0===r[o]){const n=e[t+1];r[o]=Fn(n)}r=r[o]}r[o]!==t&&(this.changes?.push({key:o,target:r,before:r[o]}),void 0===t?delete r[o]:r[o]=t)}}function iI(e){return 8===(e=mp(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}const aI=17781237,lI=17781238,cI=88853993,uI=88853994;function hI(e,t,r){const o=[["xmlns:r",Bb],["xmlns:a",Rb],["xmlns:c",Ab]],n=dI({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let s=Kw``;if(e.data.title?.text){const t=iI(Jb(e.data.backgroundColor)),r=e.data.title.fontSize??z;s=Kw`
4
- <c:title>
5
- ${gI(e.data.title.text,t,r,e.data.title)}
6
- <c:overlay val="0" />
7
- </c:title>
8
- `}let i=Kw``;switch(e.data.type){case"bar":i=function(e){const t=e.horizontal?"bar":"col",r=e.dataSets.map(e=>e.backgroundColor??""),o=new Pp(e.dataSets.length,r),n=[],s=[];for(const[t,r]of Object.entries(e.dataSets)){const i=iI(o.next()),a=dI({backgroundColor:i,line:{color:i}}),l=Kw`
9
- <c:ser>
10
- <c:idx val="${t}"/>
11
- <c:order val="${t}"/>
12
- ${pI(r.trend,i)}
13
- ${vI(r.label)}
14
- ${a}
15
- ${e.labelRange?Kw`<c:cat>${EI(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
16
- <c:val> <!-- x-coordinate values -->
17
- ${SI(r.range)}
18
- </c:val>
19
- </c:ser>
20
- `;r.rightYAxis?s.push(l):n.push(l)}const i=e.stacked?"stacked":"clustered",a=e.stacked?100:-20;return Kw`
21
- ${n.length?Kw`
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
- ${Xw(n)}
30
- <c:axId val="${aI}" />
31
- <c:axId val="${cI}" />
32
- </c:barChart>
33
- ${"col"===t?wI("b","c:catAx",aI,cI,e.axesDesign?.x?.title,e.fontColor):wI("b","c:catAx",aI,cI,e.axesDesign?.y?.title,e.fontColor,void 0,"maxMin")}
34
- ${"col"===t?wI("l","c:valAx",cI,aI,e.axesDesign?.y?.title,e.fontColor):wI("l","c:valAx",cI,aI,e.axesDesign?.x?.title,e.fontColor,void 0,void 0,"max")}
35
- `:""}
36
- ${s.length?Kw`
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
- ${Xw(s)}
45
- <c:axId val="${17781238}" />
46
- <c:axId val="${88853994}" />
47
- </c:barChart>
48
- ${wI("b","c:catAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,n.length?1:0)}
49
- ${wI("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??""),o=new Pp(t.length,r);let n=t[0];const s=iI(o.next()),i=n.rightYAxis??!1,a=Kw`
51
- <c:ser>
52
- <c:idx val="0"/>
53
- <c:order val="0"/>
54
- ${pI(n.trend,s)}
55
- ${vI(n.label)}
56
- ${dI({backgroundColor:s,line:{color:s}})}
57
- ${e.labelRange?Kw`<c:cat>${EI(e.labelRange)}</c:cat>`:""}
58
- <!-- x-coordinate values -->
59
- <c:val>
60
- ${SI(n.range)}
61
- </c:val>
62
- </c:ser>
63
- `,l=[],c=[];for(let r=1;r<t.length;r++){n=t[r];const s=iI(o.next()),i=dI({backgroundColor:s,line:{color:s}}),a=Kw`
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
- ${pI(n.trend,s)}
74
- ${vI(n.label)}
75
- ${i}
76
- ${e.labelRange?Kw`<c:cat>${EI(e.labelRange)}</c:cat>`:""}
77
- <!-- x-coordinate values -->
78
- <c:val>
79
- ${SI(n.range)}
80
- </c:val>
81
- </c:ser>
82
- `;n.rightYAxis?c.push(a):l.push(a)}const u=e.stacked?100:-20;return Kw`
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?lI:aI}" />
92
- <c:axId val="${i?uI:cI}" />
93
- </c:barChart>
94
- ${l.length?Kw`
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
- ${Xw(l)}
100
- <c:axId val="${aI}" />
101
- <c:axId val="${cI}" />
102
- </c:lineChart>
103
- `:""}
104
- ${c.length?Kw`
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
- ${Xw(c)}
110
- <c:axId val="${lI}" />
111
- <c:axId val="${uI}" />
112
- </c:lineChart>
113
- `:""}
114
- ${!i||l.length?Kw`
115
- ${wI("b","c:catAx",aI,cI,e.axesDesign?.x?.title,e.fontColor,0)}
116
- ${wI("l","c:valAx",cI,aI,e.axesDesign?.y?.title,e.fontColor)}
117
- `:""}
118
- ${i||c.length?Kw`
119
- ${wI("b","c:catAx",lI,uI,e.axesDesign?.x?.title,e.fontColor,l.length||!i?1:0)}
120
- ${wI("r","c:valAx",uI,lI,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??""),o=new Pp(t.length,r),n=t[0],s=t[1],i=iI(o.next()),a=iI(o.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),o=r/t;return{maxValue:r,majorUnit:o}}(e.maxValue),u=e.labelRange?Kw`<c:cat>${EI(e.labelRange)}</c:cat>`:"",h=Kw`
123
- <c:ser>
124
- <c:idx val="0"/>
125
- <c:order val="0"/>
126
- <c:invertIfNegative val="0" />
127
- ${vI(n.label)}
128
- ${dI({backgroundColor:i,line:{color:i}})}
129
- ${u}
130
- <!-- x-coordinate values -->
131
- <c:val>
132
- ${SI(n.range)}
133
- </c:val>
134
- </c:ser>
135
- `,d=Kw`
136
- <c:ser>
137
- <c:idx val="1"/>
138
- <c:order val="1"/>
139
- <c:invertIfNegative val="0" />
140
- ${vI(s.label)}
141
- ${dI({backgroundColor:a,line:{color:a}})}
142
- ${e.labelRange?Kw`<c:cat>${EI(e.labelRange)}</c:cat>`:""}
143
- <!-- x-coordinate values -->
144
- <c:val>
145
- ${SI(s.range)}
146
- </c:val>
147
- </c:ser>
148
- `;return Kw`
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="${aI}" />
156
- <c:axId val="${cI}" />
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="${lI}" />
165
- <c:axId val="${uI}" />
166
- </c:barChart>
167
- ${wI("r","c:catAx",aI,cI,e.axesDesign?.y?.title,e.fontColor,0,"maxMin","autoZero","high")}
168
- ${wI("b","c:valAx",cI,aI,e.axesDesign?.x?.title,e.fontColor,0,"maxMin","max","nextTo",l,c,"#0;#0")}
169
- ${wI("t","c:valAx",uI,lI,void 0,e.fontColor,1)}
170
- ${wI("l","c:catAx",lI,uI,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 Pp(e.dataSets.length,t),o=[],n=[];for(const[t,s]of Object.entries(e.dataSets)){const i=iI(r.next()),a=dI({line:{width:2.5,style:"solid",color:i}}),l=Kw`
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
- ${dI({backgroundColor:i,line:{color:i}})}
180
- </c:marker>
181
- ${pI(s.trend,i)}
182
- ${vI(s.label)}
183
- ${a}
184
- ${e.labelRange?Kw`<c:cat>${EI(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
185
- <c:val> <!-- x-coordinate values -->
186
- ${SI(s.range)}
187
- </c:val>
188
- </c:ser>
189
- `;s.rightYAxis?n.push(l):o.push(l)}const s=e.stacked?"stacked":"standard";return Kw`
190
- ${o.length?Kw`
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
- ${Xw(o)}
196
- <c:axId val="${aI}" />
197
- <c:axId val="${cI}" />
198
- </c:lineChart>
199
- ${wI("b","c:catAx",aI,cI,e.axesDesign?.x?.title,e.fontColor)}
200
- ${wI("l","c:valAx",cI,aI,e.axesDesign?.y?.title,e.fontColor)}
201
- `:""}
202
- ${n.length?Kw`
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
- ${Xw(n)}
208
- <c:axId val="${17781238}" />
209
- <c:axId val="${88853994}" />
210
- </c:lineChart>
211
- ${wI("b","c:catAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,o.length?1:0)}
212
- ${wI("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 Pp(e.dataSets.length,t),o=[],n=[];for(const[t,s]of Object.entries(e.dataSets)){const i=iI(r.next()),a=Kw`
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
- ${dI({backgroundColor:i,line:{color:i}})}
230
- </c:marker>
231
- ${pI(s.trend,i)}
232
- ${vI(s.label)}
233
- ${e.labelRange?Kw`<c:xVal> <!-- x-coordinate values -->
234
- ${SI(e.labelRange)}
235
- </c:xVal>`:""}
236
- <c:yVal> <!-- y-coordinate values -->
237
- ${SI(s.range)}
238
- </c:yVal>
239
- </c:ser>
240
- `;s.rightYAxis?n.push(a):o.push(a)}return Kw`
241
- ${o.length?Kw`
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
- ${Xw(o)}
247
- <c:axId val="${aI}" />
248
- <c:axId val="${cI}" />
249
- </c:scatterChart>
250
- ${wI("b","c:valAx",aI,cI,e.axesDesign?.x?.title,e.fontColor)}
251
- ${wI("l","c:valAx",cI,aI,e.axesDesign?.y?.title,e.fontColor)}
252
- `:""}
253
- ${n.length?Kw`
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
- ${Xw(n)}
259
- <c:axId val="${17781238}" />
260
- <c:axId val="${88853994}" />
261
- </c:scatterChart>
262
- ${wI("b","c:valAx",17781238,88853994,e.axesDesign?.x?.title,e.fontColor,o.length?1:0)}
263
- ${wI("r","c:valAx",88853994,17781238,e.axesDesign?.y1?.title,e.fontColor)}
264
- `:""}`}(e.data);break;case"pie":i=function(e,t,r){const o=We(e.dataSets.map(e=>Yy(e.range,t,r))),n=new Pp(o),s=le(0,o).map(()=>iI(n.next())),i=[];for(const[o,n]of Object.entries(e.dataSets).reverse()){const a=Yy(n.range,t,r),l=[];for(const e of le(0,a)){const t=dI({backgroundColor:s[e],line:{color:"FFFFFF",width:1.5}});l.push(Kw`
265
- <c:dPt>
266
- <c:idx val="${e}"/>
267
- ${t}
268
- </c:dPt>
269
- `)}i.push(Kw`
270
- <c:ser>
271
- <c:idx val="${o}"/>
272
- <c:order val="${o}"/>
273
- ${vI(n.label)}
274
- ${Xw(l)}
275
- ${yI({showLeaderLines:!0})}
276
- ${e.labelRange?Kw`<c:cat>${EI(e.labelRange)}</c:cat>`:""}
277
- <c:val>
278
- ${SI(n.range)}
279
- </c:val>
280
- </c:ser>
281
- `)}return Kw`
282
- <c:doughnutChart>
283
- <c:varyColors val="1" />
284
- <c:holeSize val="${e.pieHolePercentage??(e.isDoughnut?50:0)}" />
285
- ${yI()}
286
- ${Xw(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 Pp(e.dataSets.length,t),o=[];for(const[t,n]of Object.entries(e.dataSets)){const s=iI(r.next()),i=dI({line:{width:2.5,style:"solid",color:s}}),a=Kw`
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
- ${dI({backgroundColor:s,line:{color:s}})}
297
- </c:marker>
298
- ${vI(n.label)}
299
- ${i}
300
- ${e.labelRange?Kw`<c:cat>${EI(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
301
- <c:val> <!-- x-coordinate values -->
302
- ${SI(n.range)}
303
- </c:val>
304
- </c:ser>
305
- `;o.push(a)}return Kw`
306
- ${Kw`
307
- <c:radarChart>
308
- <c:radarStyle val="marker"/>
309
- <c:varyColors val="0"/>
310
- ${Xw(o)}
311
- <c:axId val="${aI}" />
312
- <c:axId val="${cI}" />
313
- </c:radarChart>
314
- ${wI("b","c:catAx",aI,cI,e.axesDesign?.x?.title,e.fontColor)}
315
- ${wI("l","c:valAx",cI,aI,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=Kw`
318
- <c:chartSpace ${qw(o)}>
319
- <c:roundedCorners val="0" />
320
- <!-- <manualLayout/> to manually position the chart in the figure container -->
321
- ${n}
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
- ${dI({backgroundColor:e.data.backgroundColor})}
330
- </c:plotArea>
331
- ${"none"!==a?function(e,t){return Kw`
332
- <c:legend>
333
- <c:legendPos val="${e}"/>
334
- <c:overlay val="0"/>
335
- ${mI(10,t)}
336
- </c:legend>
337
- `}(a,l):""}
338
- </c:chart>
339
- </c:chartSpace>
340
- `;return Zw(c)}function dI(e){return Kw`
341
- <c:spPr>
342
- ${e.backgroundColor?fI(e.backgroundColor):""}
343
- ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",Zy(e.width)]);const r=e.style?Kw`<a:prstDash val="${e.style}"/>`:"";return Kw`
344
- <a:ln ${qw(t)}>
345
- ${fI(e.color)}
346
- ${r}
347
- </a:ln>
348
- `}(e.line):""}
349
- </c:spPr>
350
- `}function fI(e){return Kw`
351
- <a:solidFill>
352
- <a:srgbClr val="${e}"/>
353
- </a:solidFill>
354
- `}function gI(e,t="000000",r=16,o={}){return Kw`
355
- <c:tx>
356
- <c:rich>
357
- <a:bodyPr />
358
- <a:lstStyle />
359
- <a:p>
360
- <a:pPr lvl="0">
361
- <a:defRPr b="${o?.bold?1:0}" i="${o?.italic?1:0}">
362
- ${fI(t)}
363
- <a:latin typeface="+mn-lt"/>
364
- </a:defRPr>
365
- </a:pPr>
366
- <a:r> <!-- Runs -->
367
- <a:rPr b="${o?.bold?1:0}" i="${o?.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 mI(e=12,t="000000",r=!1,o=!1){return Kw`
374
- <c:txPr>
375
- <a:bodyPr/>
376
- <a:lstStyle/>
377
- <a:p>
378
- <a:pPr lvl="0">
379
- <a:defRPr ${qw([["b",r?"1":"0"],["i",o?"1":"0"],["sz",100*e]])}>
380
- ${fI(t)}
381
- <a:latin typeface="+mn-lt"/>
382
- </a:defRPr>
383
- </a:pPr>
384
- </a:p>
385
- </c:txPr>
386
- `}function pI(e,t){if(!e)return Kw``;const{type:r,order:o,window:n}=e,s=[];switch(r){case"poly":o&&o>1?(s.push(Kw`<c:trendlineType val="poly" />`),s.push(Kw`<c:order val="${o}" />`)):s.push(Kw`<c:trendlineType val="linear" />`);break;case"movingAvg":s.push(Kw`<c:trendlineType val="movingAvg" />`),n&&s.push(Kw`<c:period val="${n}" />`);break;default:s.push(Kw`<c:trendlineType val="${r}" />`)}return Kw`
387
- <c:trendline>
388
- ${function(e,t){if(!e)return Kw``;const r=[["val",e.color?iI(e.color).slice(-6):bI(t)]];return Kw`
389
- <c:spPr>
390
- <a:ln w="19050" cap="rnd">
391
- <a:solidFill>
392
- <a:srgbClr ${qw(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
- ${Xw(s)}
402
- </c:trendline>
403
- `}function bI(e){return iI(Rp(e,.5))}function vI(e){return e?"text"in e&&e.text?Kw`
404
- <c:tx><c:v>${e.text}</c:v></c:tx>
405
- `:"reference"in e&&e.reference?Kw`
406
- <c:tx>
407
- ${EI(e.reference)}
408
- </c:tx>
409
- `:Kw``:Kw``}function yI({showLeaderLines:e}={showLeaderLines:!1}){return Kw`
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 wI(e,t,r,o,n,s,i=0,a="minMax",l,c="nextTo",u,h,d="General"){const f=n?.color?iI(n.color):s,g=n?.fontSize??12;return Kw`
420
- <${t}>
421
- <c:axId val="${r}"/>
422
- <c:crossAx val="${o}"/> <!-- 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?Kw`<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?Kw`<c:max val="${u}" />`:""}
430
- ${u?Kw`<c:min val="${-u}" />`:""}
431
- </c:scaling>
432
- ${h?Kw`<c:majorUnit val="${h}" />`:""}
433
- <c:axPos val="${e}" />
434
- <c:tickLblPos val="${c}" />
435
- ${function(e="B7B7B7"){return Kw`
436
- <c:majorGridlines>
437
- ${dI({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
- ${gI(n?.text??"",f,g,n)}
445
- </c:title>
446
- ${mI(10,s)}
447
- </${t}>
448
- <!-- <tickLblPos/> omitted -->
449
- `}function EI(e){return Kw`
450
- <c:strRef>
451
- <c:f>${e}</c:f>
452
- </c:strRef>
453
- `}function SI(e){return Kw`
454
- <c:numRef>
455
- <c:f>${e}</c:f>
456
- <c:numCache />
457
- </c:numRef>
458
- `}function CI(e,t,r){if(!e)return{attrs:[],node:Kw``};const o=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n";default:return}}(t);if(void 0===o)return{attrs:[],node:Kw``};var n;return{attrs:[["cm","1"],["t",o]],node:Kw`<f t="array" ref="${r}">${II(e)}</f><v>${(n=t)===w.InvalidReference?"#REF!":n}</v>`}}function TI(e,t,r=!1){let o=e;const n=[],s=o.trim().toUpperCase();return!r&&["TRUE","FALSE"].includes(s)?(o="TRUE"===s?"1":"0",n.push(["t","b"])):!r&&_t(o,Ar)||(o=$y(e,t),n.push(["t","s"])),{attrs:n,node:Kw`<v>${o}</v>`}}function II(e){let t;"="===e[0]&&(e=e.slice(1));try{t=lm(e)}catch(t){return e}return t=um(t,"STRING",xI),t=um(t,"FUNCALL",e=>e=function(e){const t=e.value.toUpperCase(),r=e.args,o=qb[t];if(o){const n=Wg.content[t].args.filter(e=>!e.optional),s=n.length-e.args.length;if(s)for(let t=e.args.length;t<n.length;t++){const e=o[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:Zb.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()}))),t=um(t,"REFERENCE",e=>e.value===w.InvalidReference?{...e,value:"#REF!"}:e),t?bT(t):e}function xI(e){const t=e.value.replace(new RegExp('"',"g"),""),r=mt(t,Ar);if(r){const o=[];return(it.test(t)||at.test(t))&&o.push("yyyy-mm-dd"),ht.test(t)&&o.push("hh:mm:ss"),{...e,value:Qr(r.value,{format:o.join(" "),locale:Ar})}}return{...e,value:e.value.replace(/\\"/g,'""')}}function RI(e,t){const r=[];for(const o of t)switch(o.rule.type){case"CellIsRule":r.push(AI(o,o.rule,e));break;case"ColorScaleRule":r.push(_I(o,o.rule));break;case"IconSetRule":r.push(FI(o,o.rule));break;case"DataBarRule":r.push(OI(o,o.rule));break;default:console.warn(`Conditional formatting ${o.rule.type} not implemented`)}return r}function AI(e,t,r){const o=DI(e),n=My(t.operator);o.push(...function(e){const t=My(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"]];case"top10":return[["type","top10"],["rank",e.values[0]],["percent",e.isPercent?"1":"0"],["bottom",e.isBottom?"1":"0"]]}}(t)),n.length&&o.push(["operator",n]);const s=function(e,t){const r=e[0].split(":")[0],o=t.values;switch(t.operator){case"containsText":return[`NOT(ISERROR(SEARCH("${o[0]}",${r})))`];case"notContainsText":return[`ISERROR(SEARCH("${o[0]}",${r}))`];case"beginsWithText":return[`LEFT(${r},LEN("${o[0]}"))="${o[0]}"`];case"endsWithText":return[`RIGHT(${r},LEN("${o[0]}"))="${o[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[o[0]];case"customFormula":return o[0].startsWith("=")?[o[0].slice(1)]:[o[0]];case"isBetween":case"isNotBetween":return[o[0],o[1]];case"dateIs":switch(t.dateValue){case"exactDate":{const e=`ROUNDDOWN(${o[0].startsWith("=")?o[0].slice(1):(uw(o[0],Ar)||"").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 o[0].startsWith("=")?[o[0].slice(1)]:[(uw(o[0],Ar)||"").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")}case"top10":return[]}}(e.ranges,t).map(e=>Kw`<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}}),o.push(["dxfId",$y(i,r)]),Kw`
459
- <conditionalFormatting sqref="${e.ranges.join(" ")}">
460
- <cfRule ${qw(o)}>
461
- ${Xw(s)}
462
- </cfRule>
463
- </conditionalFormatting>
464
- `}function OI(e,t){const r=DI(e);return r.push(["type","dataBar"]),Kw`
465
- <conditionalFormatting sqref="${e.ranges.join(" ")}">
466
- <cfRule ${qw(r)}>
467
- <dataBar>
468
- <cfvo type="min" val="0"/>
469
- <cfvo type="max" val="100"/>
470
- <color rgb="${iI(fp(t.color))}"/>
471
- </dataBar>
472
- </cfRule>
473
- </conditionalFormatting>
474
- `}function _I(e,t){const r=DI(e);r.push(["type","colorScale"]);const o=[];for(const n of e.ranges){const e=[],s=[];let i=!0;for(const r of["minimum","midpoint","maximum"]){const o=t[r];o&&("formula"!==o.type?(e.push(PI(o,r)),s.push([["rgb",iI(fp(o.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=>Kw`<cfvo ${qw(e)}/>`),l=s.map(e=>Kw`<color ${qw(e)}/>`);o.push(Kw`
475
- <conditionalFormatting sqref="${n}">
476
- <cfRule ${qw(r)}>
477
- <colorScale>
478
- ${Xw(a)}
479
- ${Xw(l)}
480
- </colorScale>
481
- </cfRule>
482
- </conditionalFormatting>
483
- `)}return Xw(o)}function FI(e,t){const r=DI(e);r.push(["type","iconSet"]);const o=[];for(const n 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 o=t[r];e.push([...PI(o,r),["gte","ge"===o.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=>Kw`<cfvo ${qw(e)} />`),a=[["iconSet",MI(t.icons)]];NI(t.icons)&&a.push(["reverse","1"]),o.push(Kw`
484
- <conditionalFormatting sqref="${n}">
485
- <cfRule ${qw(r)}>
486
- <iconSet ${qw(a)}>
487
- ${Xw(i)}
488
- </iconSet>
489
- </cfRule>
490
- </conditionalFormatting>
491
- `)}return Xw(o)}function DI(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function NI(e){const t=Nv[VI(e)];return e.upper===t.bad&&e.lower===t.good}function MI(e){return mb[VI(e)]}function VI(e){return Object.keys(Nv).find(t=>Object.values(Nv[t]).includes(e.upper))||"dots"}function PI(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),o=[["type",r]];if("min"!==r&&"max"!==r){let t=e.value;if("formula"===r)try{t=II(e.value)}catch(r){t=e.value}o.push(["val",t])}return o}function LI(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(kI(t));break;case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"isBetween":case"isNotBetween":r.push(UI(t));break;case"isValueInRange":case"isValueInList":r.push(HI(t));break;case"customFormula":r.push(BI(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`)}return r.push(new Ev("</dataValidations>")),r}function kI(e){const t=e.criterion,r=II(t.values[0]),o=t.values[1]?II(t.values[1]):void 0,n=function(e){return Object.keys(dy).find(t=>dy[t]===e)}(e.criterion.type),s=zI(e);return s.push(["type","date"],["operator",n]),o?Kw`
492
- <dataValidation ${qw(s)}>
493
- <formula1>${Ut(r,Ar)}</formula1>
494
- <formula2>${Ut(o,Ar)}</formula2>
495
- </dataValidation>
496
- `:Kw`
497
- <dataValidation ${qw(s)}>
498
- <formula1>${Ut(r,Ar)}</formula1>
499
- </dataValidation>
500
- `}function UI(e){const t=e.criterion,r=II(t.values[0]),o=t.values[1]?II(t.values[1]):void 0,n=function(e){return Object.keys(hy).find(t=>hy[t]===e)}(e.criterion.type),s=zI(e);return s.push(["type","decimal"],["operator",n]),o?Kw`
501
- <dataValidation ${qw(s)}>
502
- <formula1>${r}</formula1>
503
- <formula2>${o}</formula2>
504
- </dataValidation>
505
- `:Kw`
506
- <dataValidation ${qw(s)}>
507
- <formula1>${r}</formula1>
508
- </dataValidation>
509
- `}function HI(e){const t=e.criterion,r="isValueInRange"===e.criterion.type?II(t.values[0]):`"${t.values.join(",")}"`,o=zI(e);return o.push(["type","list"]),Kw`
510
- <dataValidation ${qw(o)}>
511
- <formula1>${r}</formula1>
512
- </dataValidation>
513
- `}function BI(e){const t=II(e.criterion.values[0]),r=zI(e);return r.push(["type","custom"]),Kw`
514
- <dataValidation ${qw(r)}>
515
- <formula1>${t}</formula1>
516
- </dataValidation>
517
- `}function zI(e){return[["allowBlank","1"],["showInputMessage","1"],["showErrorMessage","1"],["errorStyle",e.isBlocking?"":"warning"],["sqref",e.ranges.join(" ")]]}function $I(e,t,r,o){const n=[["xmlns:xdr",Sb],["xmlns:r",Bb],["xmlns:a",Rb],["xmlns:c",Ab]],s=[];for(const[n,i]of Object.entries(r))switch(i?.tag){case"chart":s.push(qI(i,t,e[n],o));break;case"image":s.push(ZI(i,t,e[n]))}return Zw(Kw`
518
- <xdr:wsDr ${qw(n)}>
519
- ${Xw(s)}
520
- </xdr:wsDr>
521
- `)}function GI(e,t){const{col:r,row:o,offset:n,width:s,height:i}=e,{x:a,y:l}=n,c=Object.values(t.rows),{index:u,offset:h}=WI(c,o,l),{index:d,offset:f}=WI(c,o,l+i),g=Object.values(t.cols),{index:m,offset:p}=WI(g,r,a),{index:b,offset:v}=WI(g,r,a+s);return{from:{col:m,colOff:p,row:u,rowOff:h},to:{col:b,colOff:v,row:d,rowOff:f}}}function WI(e,t,r){let o=0;for(const[n,s]of e.slice(t).entries()){if(o<=r&&r<o+s.size)return{index:t+n,offset:Zy(r-o+1)};n<e.length-1&&(o+=s.size)}return{index:e.length-1,offset:Zy(r-o+1)}}function qI(e,t,r,o){const{from:n,to:s}=GI(e,t),i=Gy(e.id,o),a=[["id",i],["name",`Chart ${i}`],["title","Chart"]];return Kw`
522
- <xdr:twoCellAnchor>
523
- <xdr:from>
524
- <xdr:col>${n.col}</xdr:col>
525
- <xdr:colOff>${n.colOff}</xdr:colOff>
526
- <xdr:row>${n.row}</xdr:row>
527
- <xdr:rowOff>${n.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 ${qw(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="${Ab}">
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 ZI(e,t,r){const{from:o,to:n}=GI(e,t),s=qy(e.id),i=[["id",s],["name",`Image ${s}`],["title","Image"]],a=Zy(e.width),l=Zy(e.height);return Kw`
553
- <xdr:twoCellAnchor editAs="oneCell">
554
- <xdr:from>
555
- <xdr:col>${o.col}</xdr:col>
556
- <xdr:colOff>${o.colOff}</xdr:colOff>
557
- <xdr:row>${o.row}</xdr:row>
558
- <xdr:rowOff>${o.rowOff}</xdr:rowOff>
559
- </xdr:from>
560
- <xdr:to>
561
- <xdr:col>${n.col}</xdr:col>
562
- <xdr:colOff>${n.colOff}</xdr:colOff>
563
- <xdr:row>${n.row}</xdr:row>
564
- <xdr:rowOff>${n.rowOff}</xdr:rowOff>
565
- </xdr:to>
566
- <xdr:pic>
567
- <xdr:nvPicPr>
568
- <xdr:cNvPr ${qw(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 YI(e){return Ce(e)?Kw``:Kw`
590
- <font>
591
- ${e.bold?Kw`<b />`:""}
592
- ${e.italic?Kw`<i />`:""}
593
- ${e.underline?Kw`<u />`:""}
594
- ${e.strike?Kw`<strike />`:""}
595
- ${e.size?Kw`<sz val="${e.size}" />`:""}
596
- ${e.color&&e.color.rgb?Kw`<color rgb="${iI(e.color.rgb)}" />`:""}
597
- ${e.name?Kw`<name val="${e.name}" />`:""}
598
- </font>
599
- `}function jI(e){return e?qw([["style",e.style]]):Kw``}function XI(e){return e?Kw`
600
- <color ${qw([["rgb",iI(e.color.rgb)]])}/>
601
- `:Kw``}function KI(e,t,r){const o=Kw`
602
- <table ${qw([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["headerRowCount",e.config.numberOfHeaders],["totalsRowCount",e.config.totalRow?1:0],["xmlns",Cb],["xmlns:xr",Tb],["xmlns:xr3",Ib],["xmlns:mc",xb]])}>
603
- ${e.config.hasFilters?function(e){const t=[["ref",e.range]];return Kw`
604
- <autoFilter ${qw(t)}>
605
- ${Xw(function(e){const t=[];for(const r of e.filters){const e=Kw`
606
- <filterColumn ${qw([["colId",r.colId]])}>
607
- ${QI(r)}
608
- </filterColumn>
609
- `;t.push(e)}return t}(e))}
610
- </autoFilter>
611
- `}(e):""}
612
- ${function(e,t){const r=Jn(e.range),o=[];for(const n of le(0,ds(r).numberOfCols)){const s=$n(r.left+n,r.top),i=[["id",n+1],["name",t.cells[s]||`col${n}`]];if(e.config.totalRow){const e=$n(r.left+n,r.bottom),o=t.cells[e];o?.startsWith("=")&&i.push(["totalsRowFunction","custom"])}o.push(Kw`<tableColumn ${qw(i)}/>`)}return Kw`
613
- <tableColumns ${qw([["count",o.length]])}>
614
- ${Xw(o)}
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 Kw`<tableStyleInfo ${qw(t)}/>`}(e)}
618
- </table>
619
- `;return Zw(o)}function QI(e){const t=e.displayedValues.map(e=>Kw`<filter ${qw([["val",e]])}/>`);return Kw`
620
- <filters ${qw(e.displayBlanks?[["blank",1]]:[])}>
621
- ${Xw(t)}
622
- </filters>
623
- `}function JI(e){if(!Object.values(e).length)return Kw``;const t=[];for(const[r,o]of Object.entries(e)){const e=[["min",parseInt(r)+1],["max",parseInt(r)+1],["width",Py(o.size||96)],["customWidth",1],["hidden",o.isHidden?1:0]];o.outlineLevel&&e.push(["outlineLevel",o.outlineLevel]),o.collapsed&&e.push(["collapsed",1]),t.push(Kw`
624
- <col ${qw(e)}/>
625
- `)}return Kw`
626
- <cols>
627
- ${Xw(t)}
628
- </cols>
629
- `}function ex(e,t,r){const o=[],n=new NE(Dy(r.id,r.styles)),s=new NE(Dy(r.id,r.borders)),i=new NE(Dy(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",Vy(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 o=0;o<r.colNumber;o++){const l=$n(o,a),c=r.cells[l],h=r.cellValues[l],d={sheetId:r.id,col:o,row:a},f=n.get(d),g=i.get(d),m=s.get(d);if(c||f||g||m||void 0!==h){const n=[["r",l]],s=Hy(e,Uy(t,c,f,g,m));s&&n.push(["s",s]);let i=[],d=Kw``;if(c?.startsWith("=")&&void 0!==h){const e=CI(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}=TI(t,e.sharedStrings))}else if(c&&""!==c){const n=tx(o,a,r),s=rx(o,a,r),l=!(!g||!yo(t.formats[g]));({attrs:i,node:d}=TI(c,e.sharedStrings,n||s||l))}n.push(...i),u.push(Kw`<c ${qw(n)}>
630
- ${d}
631
- </c>`)}}(u.length||c.size!==G||c.isHidden||c.outlineLevel||c.collapsed)&&o.push(Kw`
632
- <row ${qw(l)}>
633
- ${Xw(u)}
634
- </row>
635
- `)}return Kw`
636
- <sheetData>
637
- ${Xw(o)}
638
- </sheetData>
639
- `}function tx(e,t,r){return r.tables.some(r=>{const o=Jn(r.range),n={...o,bottom:o.top};return us(e,t,n)})}function rx(e,t,r){return r.tables.some(r=>{if(!r.config.totalRow)return!1;const o=Jn(r.range),n={...o,top:o.bottom};return us(e,t,n)})}function ox(e,t,r){const o=t.sheets[r].cells,n=[];for(const s in o){const i=o[s];if(i&&ge(i)){const{label:o,url:a}=be(i);if(ye(a)){const e=Ee(a),r=t.sheets.find(t=>t.id===e),i=[["display",o],["location",r?`${r.name}!A1`:w.InvalidReference],["ref",s]];n.push(Kw`
640
- <hyperlink ${qw(i)}/>
641
- `)}else{const t=[["r:id",By(e.relsFiles,`xl/worksheets/_rels/sheet${r}.xml.rels`,{target:nw(a),type:kb,targetMode:"External"})],["ref",s]];n.push(Kw`
642
- <hyperlink ${qw(t)}/>
643
- `)}}}return n.length?Kw`
644
- <hyperlinks>
645
- ${Xw(n)}
646
- </hyperlinks>
647
- `:Kw``}function nx(e){if(e.length){const t=e.map(e=>Kw`<mergeCell ref="${e}" />`);return Kw`
648
- <mergeCells count="${e.length}">
649
- ${Xw(t)}
650
- </mergeCells>
651
- `}return Kw``}function sx(e){const t=e.panes;let r=Kw``;if(t&&(t.xSplit||t.ySplit)){const e=$n(t.xSplit,t.ySplit),o=t.xSplit?Kw`xSplit="${t.xSplit}"`:"",n=t.ySplit?Kw`ySplit="${t.ySplit}"`:"",s=t.xSplit?Kw`<selection pane="topRight"/>`:"",i=t.ySplit?Kw`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?Kw`<selection pane="bottomRight"/>`:"";r=Kw`
652
- <pane
653
- ${o}
654
- ${n}
655
- topLeftCell="${e}"
656
- activePane="${t.xSplit?t.ySplit?"bottomRight":"topRight":"bottomLeft"}"
657
- state="frozen"/>
658
- ${s}
659
- ${i}
660
- ${a}
661
- `}return Kw`
662
- <sheetViews>
663
- <sheetView ${qw([["showGridLines",e.areGridLinesVisible?1:0],["workbookViewId",0]])}>
664
- ${r}
665
- </sheetView>
666
- </sheetViews>
667
- `}function ix(e){return e.color?Kw`
668
- <sheetPr>
669
- <tabColor ${qw([["rgb",iI(e.color)]])} />
670
- </sheetPr>
671
- `:""}function ax(e){const t=[],r=function(e){const t=[{},...Object.values(e.borders).map(e=>({left:Yw(e.left),right:Yw(e.right),bottom:Yw(e.bottom),top:Yw(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=>ds(Jn(e.range)).numberOfRows>1);return e}(e=function(e){const t={},r=[];for(const o of e.sheets){let e=o.name.slice(0,31);e=Xe(e,r,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),r.push(e),e!==o.name&&(t[o.name]=e,o.name=e)}if(!Object.keys(t).length)return e;const o=Object.keys(t).sort((e,t)=>t.length-e.length);let n=JSON.stringify(e);for(const e of o){const r=new RegExp(`'?${te(e)}'?!`,"g");n=n.replaceAll(r,r=>{const o=t[e];return r.replace(e,o)})}return JSON.parse(n)}(e)));return t.push(function(e,t){const r=[["xmlns",Eb],["xmlns:r",Bb]],o=[];for(const[r,n]of Object.entries(e.sheets)){const e=[["state",n.isVisible?"visible":"hidden"],["name",n.name],["sheetId",parseInt(r)+1],["r:id",`rId${parseInt(r)+1}`]];o.push(Kw`
672
- <sheet ${qw(e)} />
673
- `),By(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Fb,target:`worksheets/sheet${r}.xml`})}return Gw(Zw(Kw`
674
- <workbook ${qw(r)}>
675
- <sheets>
676
- ${Xw(o)}
677
- </sheets>
678
- </workbook>
679
- `),"xl/workbook.xml","workbook")}(e,r)),t.push(...function(e,t){const r=[];let o=1;for(const[n,s]of Object.entries(e.sheets)){const i=[["xmlns",wb],["xmlns:r",Bb]],a=[["defaultRowHeight",Vy(G)],["defaultColWidth",Py(96)]],l=lx(s,n,o,t,r);o+=s.tables.length;let c=Kw``;const u=[];for(const o of s.charts){const s=Gy(o.id,t),i=By(t.relsFiles,`xl/drawings/_rels/drawing${n}.xml.rels`,{target:`../charts/chart${s}.xml`,type:Pb});u.push(i),r.push(Gw(hI(o,n,e),`xl/charts/chart${s}.xml`,"chart"))}for(const e of s.images){const o=e.data.mimetype;if(void 0===o)continue;const s=cy[o];if(void 0===s)continue;const i=`image${qy(e.id)}.${s}`,a=By(t.relsFiles,`xl/drawings/_rels/drawing${n}.xml.rels`,{target:`../media/${i}`,type:Ub});u.push(a),r.push({path:`xl/media/${i}`,imageSrc:e.data.path})}const h=[...s.charts,...s.images];if(h.length){const e=By(t.relsFiles,`xl/worksheets/_rels/sheet${n}.xml.rels`,{target:`../drawings/drawing${n}.xml`,type:Vb});r.push(Gw($I(u,s,h,t),`xl/drawings/drawing${n}.xml`,"drawing")),c=Kw`<drawing r:id="${e}" />`}const d=Kw`
680
- <worksheet ${qw(i)}>
681
- ${ix(s)}
682
- ${sx(s)}
683
- <sheetFormatPr ${qw(a)} />
684
- ${JI(s.cols)}
685
- ${ex(t,e,s)}
686
- ${nx(s.merges)}
687
- ${Xw(RI(t.dxfs,s.conditionalFormats))}
688
- ${Xw(LI(s.dataValidationRules))}
689
- ${ox(t,e,n)}
690
- ${c}
691
- ${l}
692
- </worksheet>
693
- `;r.push(Gw(Zw(d),`xl/worksheets/sheet${n}.xml`,"sheet"))}const n=Kw`
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="{${Hb}}">
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(Gw(Zw(n),"xl/metadata.xml","metadata")),By(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Nb,target:"sharedStrings.xml"}),By(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Mb,target:"styles.xml"}),By(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Db,target:"metadata.xml"}),r}(e,r)),t.push(function(e){const t=Kw`
716
- <styleSheet ${qw([["xmlns",pb],["xmlns:r",Bb]])}>
717
- ${function(e){const t=[];for(const[r,o]of Object.entries(e)){const e=[["numFmtId",parseInt(r)+164],["formatCode",o.format]];t.push(Kw`
718
- <numFmt ${qw(e)}/>
719
- `)}return Kw`
720
- <numFmts count="${e.length}">
721
- ${Xw(t)}
722
- </numFmts>
723
- `}(e.numFmts)}
724
- ${r=e.fonts,Kw`
725
- <fonts count="${r.length}">
726
- ${Xw(Object.values(r).map(YI))}
727
- </fonts>
728
- `}
729
- ${function(e){const t=[];for(const r of Object.values(e))void 0!==r.reservedAttribute?t.push(Kw`
730
- <fill>
731
- <patternFill patternType="${r.reservedAttribute}" />
732
- </fill>
733
- `):t.push(Kw`
734
- <fill>
735
- <patternFill patternType="solid">
736
- <fgColor rgb="${iI(r.fgColor.rgb)}" />
737
- <bgColor indexed="64" />
738
- </patternFill>
739
- </fill>
740
- `);return Kw`
741
- <fills count="${e.length}">
742
- ${Xw(t)}
743
- </fills>
744
- `}(e.fills)}
745
- ${function(e){const t=[];for(const r of Object.values(e))t.push(Kw`
746
- <border>
747
- <left ${jI(r.left)}>
748
- ${XI(r.left)}
749
- </left>
750
- <right ${jI(r.right)}>
751
- ${XI(r.right)}
752
- </right>
753
- <top ${jI(r.top)}>
754
- ${XI(r.top)}
755
- </top>
756
- <bottom ${jI(r.bottom)}>
757
- ${XI(r.bottom)}
758
- </bottom>
759
- <diagonal ${jI(r.diagonal)}>
760
- ${XI(r.diagonal)}
761
- </diagonal>
762
- </border>
763
- `);return Kw`
764
- <borders count="${e.length}">
765
- ${Xw(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]],o=[];r.alignment&&r.alignment.vertical&&o.push(["vertical",r.alignment.vertical]),r.alignment&&r.alignment.horizontal&&o.push(["horizontal",r.alignment.horizontal]),r.alignment&&r.alignment.wrapText&&o.push(["wrapText","1"]),o.length>0?(e.push(["applyAlignment","1"]),t.push(Kw`<xf ${qw(e)}><alignment ${qw(o)} /></xf> `)):t.push(Kw`<xf ${qw(e)} />`)}return Kw`
769
- <cellXfs count="${e.length}">
770
- ${Xw(t)}
771
- </cellXfs>
772
- `}(e.styles)}
773
- ${function(e){const t=[];for(const r of e){let e=Kw``;r.font&&(e=YI(r.font));let o=Kw``;r.fill&&(o=Kw`
774
- <fill>
775
- <patternFill>
776
- <bgColor rgb="${iI(r.fill.fgColor.rgb)}" />
777
- </patternFill>
778
- </fill>
779
- `),t.push(Kw`
780
- <dxf>
781
- ${e}
782
- ${o}
783
- </dxf>
784
- `)}return Kw`
785
- <dxfs count="${e.length}">
786
- ${Xw(t)}
787
- </dxfs>
788
- `}(e.dxfs)}
789
- </styleSheet>
790
- `;var r;return Gw(Zw(t),"xl/styles.xml","styles")}(r)),t.push(function(e){const t=[["xmlns",bb],["count",e.length],["uniqueCount",e.length]],r=e.map(e=>e.trim()!==e?Kw`<si><t xml:space="preserve">${e}</t></si>`:Kw`<si><t>${e}</t></si>`);return Gw(Zw(Kw`
791
- <sst ${qw(t)}>
792
- ${Xw(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(Kw`
795
- <Relationship ${qw(r)} />
796
- `)}const o=Kw`
797
- <Relationships xmlns="${vb}">
798
- ${Xw(e)}
799
- </Relationships>
800
- `;t.push(Gw(Zw(o),r.path))}return t}(r.relsFiles)),t.push(function(e){const t=[],r=Object.entries(cy).map(([e,t])=>function(e,t){return Kw`
801
- <Default Extension="${e}" ContentType="${t}" />
802
- `}(t,e));for(const r of e)"contentType"in r&&r.contentType&&t.push(jw("/"+r.path,Ob[r.contentType]));const o=[["Extension","rels"],["ContentType","application/vnd.openxmlformats-package.relationships+xml"]],n=[["Extension","xml"],["ContentType","application/xml"]];return Gw(Zw(Kw`
803
- <Types xmlns="${yb}">
804
- ${Xw(Object.values(r))}
805
- <Default ${qw(o)} />
806
- <Default ${qw(n)} />
807
- ${Xw(t)}
808
- </Types>
809
- `),"[Content_Types].xml")}(t)),t.push(Gw(Zw(Kw`
810
- <Relationships xmlns="${vb}">
811
- <Relationship ${qw([["Id","rId1"],["Type",_b],["Target","xl/workbook.xml"]])} />
812
- </Relationships>
813
- `),"_rels/.rels")),{name:"my_spreadsheet.xlsx",files:t}}function lx(e,t,r,o,n){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=By(o.relsFiles,i,{target:`../tables/table${s}.xml`,type:Lb});n.push(Gw(KI(t,s,e),`xl/tables/table${s}.xml`,"table")),a.push(Kw`<tablePart r:id="${r}" />`),s++}return Kw`
814
- <tableParts count="${e.tables.length}">
815
- ${Xw(a)}
816
- </tableParts>
817
- `}var cx;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(cx||(cx={}));function ux(e,t={}){const r=re(t);return r.type=e,r}const hx={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},dx=Ue(()=>Object.keys(hx).sort((e,t)=>hx[e]-hx[t]));const fx={};e.BadExpressionError=C,e.BasePlugin=ME,e.CellErrorType=w,e.CircularDependencyError=T,e.DEFAULT_LOCALE=Ar,e.DEFAULT_LOCALES=Rr,e.DivisionByZeroError=O,e.EvaluationError=S,e.FunctionCodeBuilder=t,e.FunctionRegistry=Gg,e.InvalidReferenceError=I,e.Model=class extends Cm{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=[],o=new Dn,n=!1){const s=performance.now();console.debug("##### Model creation #####"),super(),b(),r=OE(e,r);const i=xE(e,n);this.state=new sI,this.uuidGenerator=o,this.config=this.setupConfig(t),this.session=this.setupSession(i.revisionId),this.coreGetters={},this.range=new rI(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.adaptFormulaStringDependencies=this.range.adaptFormulaStringDependencies.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 nI(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 QT.getAll())this.setupCorePlugin(e,i);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(const e of tI.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of eI.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of JT.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 cv(yv({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 Em,o="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:o?new Sm(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(Rr));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=sp(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>"Success"!==e)?new ip(t.flat()):ip.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(ux(e,t));dispatch=(e,t)=>{const r=ux(e,t),o=this.status;if(this.getters.isReadonly()&&(n=r,!op.has(n.type)))return new ip("Readonly");var n;if(!this.session.canApplyOptimisticUpdate())return new ip("WaitingSessionConfirmation");switch(o){case 0:const t=this.checkDispatchAllowed(r);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:o,commands:n}=this.state.recordChanges(()=>{const t=performance.now();sp(r)&&this.state.addCommand(r),this.dispatchToHandlers(this.handlers,r),this.finalize();const o=performance.now()-t;o>5&&console.debug(e,o,"ms")});this.session.save(r,n,o),this.status=0,this.trigger("update");break;case 1:if(sp(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(sp(r))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,r)}return ip.Success};dispatchFromCorePlugin=(e,t)=>{const r=ux(e,t),o=this.status;this.status=2;const n=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(n,r),this.status=o,ip.Success};dispatchToHandlers(e,t){const r=sp(t);for(const o of e)!r&&o instanceof VE||o.beforeHandle(t);for(const o of e)!r&&o instanceof VE||o.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const r=this.renderers[t];if(r)for(const o of r)e.ctx.save(),o.drawLayer(e,t),e.ctx.restore()}exportData(){let e=DE();for(const t of this.handlers)t instanceof VE&&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={...DE(),sheets:[(t=IE,r="Sheet1",{...FE(t,r),charts:[],images:[],cellValues:{}})]};var t,r;for(const t of this.handlers)t instanceof ME&&await t.exportForExcel(e);return e=re(e),ax(e)}},e.NotAvailableError=x,e.NumberTooLargeError=_,e.OPERATOR_MAP=mm,e.OP_PRIORITY=om,e.OrderedLayers=dx,e.POSTFIX_UNARY_OPERATORS=Al,e.Registry=h,e.Scope=o,e.SplillBlockedError=A,e.StateObserver=sI,e.TokenizingChars=Ze,e.UNARY_OPERATOR_MAP=pm,e.UnknownFunctionError=R,e.UuidGenerator=Dn,e.__info__=fx,e._t=v,e.addRenderingLayer=function(e,t){if(hx[e])throw new Error(`Layer ${e} already exists`);hx[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=we,e.categories=qg,e.cellReference=gn,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=vm,e.compileTokens=ym,e.concat=Ie,e.convertAstNodes=um,e.createEmptyStructure=Fn,e.debounce=Te,e.deepCopy=re,e.deepEquals=Ae,e.deepEqualsArray=_e,e.doesCellContainFunction=Qe,e.errorTypes=E,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=bm,e.getAddHeaderStartIndex=Re,e.getCanonicalSymbolName=se,e.getFormulaNumberRegex=At,e.getFullReference=Rn,e.getSearchRegex=function(e,t){let r=te(e);const o=t.matchCase?"":"i";return t.exactMatch&&(r=`^${r}$`),RegExp(r,o)},e.getUniqueText=Xe,e.getUnquotedSheetName=oe,e.groupConsecutive=ce,e.includesAll=Fe,e.insertItemsAtIndex=Be,e.isBoolean=he,e.isColHeader=Cn,e.isColReference=En,e.isConsecutive=ke,e.isDefined=Se,e.isFormula=Ke,e.isMarkdownLink=ge,e.isMatrix=F,e.isNotNull=function(e){return null!==e},e.isNumber=_t,e.isNumberBetween=Ge,e.isObjectEmptyRecursive=Ce,e.isRowHeader=Tn,e.isRowReference=Sn,e.isSheetUrl=ye,e.isSingleCellReference=In,e.isWebLink=me,e.iterateAstNodes=hm,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}=xn(e.value),[o,n]=t.split(":"),s=An(o),i=n?`:${An(n)}`:"";return{...e,value:Rn(r,s+i)}},e.mapAst=fm,e.markdownLink=pe,e.memoize=Ue,e.parse=lm,e.parseMarkdownLink=be,e.parseNumber=Dt,e.parseSheetUrl=Ee,e.parseTokens=cm,e.percentile=Nt,e.range=le,e.rangeReference=wn,e.rangeTokenize=Qg,e.removeDuplicates=Ye,e.removeFalsyAttributes=De,e.removeIndexesFromArray=He,e.replaceItemAtIndex=ze,e.replaceNewLines=Le,e.sanitizeSheetName=ie,e.setDefaultTranslationMethod=b,e.setTranslationMethod=function(e,t=()=>!0){g=e,m=t},e.setXcToFixedReferenceType=On,e.specialWhiteSpaceRegexp=Me,e.splitReference=xn,e.tokenize=_l,e.transpose2dPOJO=je,e.trimContent=$e,e.unquote=ne,e.whiteSpaceCharacters=Pe,fx.version="19.1.0-alpha.3",fx.date="2026-01-14T10:01:30.535Z",fx.hash="e5cbf18"}(this.o_spreadsheet_engine=this.o_spreadsheet_engine||{});