@odoo/o-spreadsheet 19.1.0-alpha.8 → 19.1.0-alpha.9
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.
- package/dist/o-spreadsheet-engine.d.ts +11 -2
- package/dist/o-spreadsheet-engine.esm.js +22 -13
- package/dist/o-spreadsheet-engine.iife.js +22 -13
- package/dist/o-spreadsheet-engine.min.iife.js +2 -2
- package/dist/o-spreadsheet.d.ts +242 -148
- package/dist/o_spreadsheet.esm.js +114 -59
- package/dist/o_spreadsheet.iife.js +114 -59
- package/dist/o_spreadsheet.min.iife.js +2 -2
- package/dist/o_spreadsheet.xml +52 -31
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(e){"use strict";class t{scope;code="";constructor(e=new n){this.scope=e}append(...e){this.code+=e.map(e=>e.toString()).join("\n")+"\n"}return(e){return new r(this.scope,this.code,e)}toString(){return o(this.code)}}class r{scope;returnExpression;code;constructor(e,t,r){this.scope=e,this.returnExpression=r,this.code=o(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;const e=this.scope.nextVariableName(),r=new t(this.scope);return r.append(this.code),r.append(`const ${e} = ${this.returnExpression};`),r.return(e)}}class n{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function o(e){let t="",r=0;const n=e.split("\n").map(e=>e.trim()).filter(e=>""!==e);for(const e of n)e.startsWith("}")&&r--,t+="\t".repeat(r)+e+"\n",e.endsWith("{")&&r++;return t.trim()}const s=/(.*?)\((.*?)\)(.*)/,i=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META","RANGE<META>"];function a(e,t="",r){return function(e,t,r){const n=e.match(s),o=n[1].trim();if(!o)throw new Error(`Function argument definition is missing a name: '${e}'.`);const a=[];let l,c=!1,u=!1;for(const e of n[2].split(",")){const t=e.trim().toUpperCase(),r=i.find(e=>t===e);r?a.push(r):"RANGE<ANY>"===t?a.push("RANGE"):"OPTIONAL"===t?c=!0:"REPEATING"===t?u=!0:t.startsWith("DEFAULT=")&&(l=e.trim().slice(8))}const h={name:o,description:t,type:a};(a.includes("ANY")||a.includes("RANGE"))&&(h.acceptErrors=!0);c&&(h.optional=!0);u&&(h.repeating=!0);void 0!==l&&(h.default=!0,h.defaultValue=l);a.some(e=>e.startsWith("RANGE"))&&(h.acceptMatrix=!0);a.every(e=>e.startsWith("RANGE"))&&(h.acceptMatrixOnly=!0);r&&r.length>0&&(h.proposalValues=r);return h}(e,t,r)}const l={};function c(e,t){const r=e.name,n=l[r]?.[t];return n||(l[r]||(l[r]={}),l[r][t]||(l[r][t]=function(e,t){const r={},n=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,o=e.nbrArgRepeating*n,s=t-e.minArgRequired-o;let i=0,a=0;for(let t=0;t<e.args.length;t++){const o=e.args[t];if(o.optional||o.default)a<s&&(r[i]=t,i++),a++;else if(o.repeating){for(let o=0;o<n;o++)for(let n=0;n<e.nbrArgRepeating;n++)r[i]=t+n,i++;t+=e.nbrArgRepeating-1}else r[i]=t,i++}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!",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 _ extends S{constructor(e=v("Division by zero")){super(e,w.DivisionByZero)}}function O(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 F="#017E84",N="#3266ca",M="#FFFFFF",V=F,L="#111827",P="#E7E9ED",k="#374151C2",U=F,H=20,B=16,z=["#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"],$=23,G={align:"left",verticalAlign:"bottom",wrapping:"overflow",bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:"",textColor:""},W=G.verticalAlign,q=G.fontSize,Z="'Roboto', arial",Y="START_REVISION",j="??",X=/'|\*|\?|\/|\\|\[|\]/,K="|";const Q="\n",J={hasFilters:!1,totalRow:!1,firstColumn:!0,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,styleId:"TableStyleMedium5",automaticAutofill:!1},ee=new RegExp(X,"g");function te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function re(e){switch(typeof e){case"object":{if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&null!==e&&(e?.constructor===Object||void 0===e?.constructor)}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");const t=Array.isArray(e)?new Array(e.length):{};if(Array.isArray(e))for(let r=0,n=e.length;r<n;r++)r in e&&(t[r]=re(e[r]));else for(const r in e)t[r]=re(e[r]);return t}case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function ne(e){return oe(e,"'")}function oe(e,t='"'){return e.startsWith(t)&&(e=e.slice(1)),e.endsWith(t)&&(e=e.slice(0,-1)),e}function se(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function ie(e,t=" "){return e.replace(ee,t)}function ae(e,t,r){return e<t?t:e>r?r:e}function le(e,t,r=1){if(t<=e&&r>0)return[];if(0===r)throw new Error("range() step must not be zero");const n=Math.ceil(Math.abs((t-e)/r)),o=Array(n);for(let t=0;t<n;t++)o[t]=e+t*r;return o}function ce(e){return e.reduce((e,t,r,n)=>{if(1===Math.abs(t-n[r-1])){e[e.length-1].push(t)}else e.push([t]);return e},[])}function*ue(e,t){t.next();for(const r of e){const e=t.next();yield{...r,next:e.done?void 0:e.value}}}function he(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}const de=/^\[(.+)\]\((.+)\)$/,fe=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function ge(e){return de.test(e)}function me(e){return fe.test(e)}function pe(e,t){return`[${e}](${t})`}function be(e){const t=e.match(de)||[],r=t[1],n=t[2];if(!r||!n)throw new Error(`Could not parse markdown link ${e}.`);return{label:r,url:n}}const ve="o-spreadsheet://";function ye(e){return e.startsWith(ve)}function 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 n;const o=function(){const o=this,s=Array.from(arguments);const i=r&&!n;clearTimeout(n),n=setTimeout(function(){n=void 0,r||e.apply(o,s)},t),i&&e.apply(o,s)};return o.isDebouncePending=()=>void 0!==n,o.stopDebounce=()=>{clearTimeout(n)},o}function Ie(e){let t="";for(let r=0,n=e.length;r<n;r++)t+=e[r];return t}function xe(e){let t,r=!1;const n=()=>(r||(t=e instanceof Function?e():e,r=!0),t);return n.map=e=>xe(()=>e(n())),n}function Re(e,t){return"after"===e?t+1:t}function Ae(...e){if(e.length<=1)return!0;for(let t=1;t<e.length;t++)if(!_e(e[0],e[t]))return!1;return!0}function _e(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(!_e(e[r],t[r]))return!1}else if(e[r]!==t[r])return!1}return!0}function Oe(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ae(e[r],t[r]))return!1;return!0}function De(e,t){if(e.length<t.length)return!1;const r=new Set(e);return t.every(e=>r.has(e))}function Fe(e){if(!e)return e;const t={...e};return Object.keys(t).forEach(e=>!t[e]&&delete t[e]),t}const Ne=["\t","\f","\v",String.fromCharCode(parseInt("00a0",16)),String.fromCharCode(parseInt("1680",16)),String.fromCharCode(parseInt("2000",16)),String.fromCharCode(parseInt("200a",16)),String.fromCharCode(parseInt("2028",16)),String.fromCharCode(parseInt("2029",16)),String.fromCharCode(parseInt("202f",16)),String.fromCharCode(parseInt("205f",16)),String.fromCharCode(parseInt("3000",16)),String.fromCharCode(parseInt("feff",16))],Me=new RegExp(Ne.join("|"),"g"),Ve=/(\r\n|\r)/g,Le=Ne.concat([" "]);function Pe(e){return e?e.replace(Ve,Q):""}function ke(e){const t=Array.from(e).sort((e,t)=>e-t);for(let e=1;e<t.length;e++)if(t[e]-t[e-1]!==1)return!1;return!0}function Ue(e){const t=new Map,r=e.name?e.name+" (memoized)":"memoized";return{[r]:(...r)=>(t.has(r[0])||t.set(r[0],e(...r)),t.get(r[0]))}[r]}function He(e,t){const r=new Set(t),n=[];for(let t=0;t<e.length;t++)r.has(t)||n.push(e[t]);return n}function Be(e,t,r){return e.slice(0,r).concat(t).concat(e.slice(r))}function ze(e,t,r){const n=[...e];return n[r]=t,n}function $e(e){return e.split("\n").map(e=>e.replace(/\s+/g," ").trim()).join("\n")}function Ge(e,t,r){return t>r?Ge(e,r,t):e>=t&&e<=r}function We(e){let t=e.length;if(t<1e5)return Math.max(...e);let r=-1/0;for(;t--;)r=e[t]>r?e[t]:r;return r}function qe(e){let t=e.length;if(t<1e5)return Math.min(...e);let r=1/0;for(;t--;)r=e[t]<r?e[t]:r;return r}class Ze{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){const e=this.current,t=this.text[++this.currentIndex];return this.current=t,e}advanceBy(e){this.currentIndex+=e,this.current=this.text[this.currentIndex]}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){if(this.current!==e[0])return!1;for(let t=1;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}}function Ye(e,t=e=>e){const r=new Set;return e.filter(e=>{const n=t(e);return!r.has(n)&&(r.add(n),!0)})}function je(e){const t={};for(const r in e)for(const n in e[r])t[n]||(t[n]={}),t[n][r]=e[r][n];return t}function Xe(e,t,r={}){const n=r.compute??((e,t)=>`${e} (${t})`),o=r.computeFirstOne??!1;let s=r.start??1,i=o?n(e,s):e;for(;t.includes(i);)i=n(e,s++);return i}function Ke(e){return e.startsWith("=")||e.startsWith("+")}class Qe{jsDate;constructor(e,t,r,n=0,o=0,s=0){this.jsDate=new Date(Date.UTC(e,t,r,n,o,s,0))}static fromTimestamp(e){const t=new Date(e);return new Qe(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new Qe(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getQuarter(){return Math.floor(this.getMonth()/3)+1}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}getIsoWeek(){const e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);const r=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-r.getTime())/864e5+1)/7)}setFullYear(e){return this.jsDate.setUTCFullYear(e)}setMonth(e){return this.jsDate.setUTCMonth(e)}setDate(e){return this.jsDate.setUTCDate(e)}setHours(e){return this.jsDate.setUTCHours(e)}setMinutes(e){return this.jsDate.setUTCMinutes(e)}setSeconds(e){return this.jsDate.setUTCSeconds(e)}}const Je=new Qe(1899,11,30),et=864e5,tt=2e3,rt=Qe.now().getFullYear(),nt=Qe.now().getMonth(),ot=Qe.fromTimestamp(0).getTime()-Je.getTime(),st=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,it=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,at=Le.join(""),lt=new RegExp(`/|-|${Le.join("|")}`),ct=new RegExp(`^(\\d{1,4})[/${at}-](\\d{1,4})([/${at}-](\\d{1,4}))?$`),ut=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function ht(e,t){switch(typeof e){case"number":return e;case"string":return dt(e,t)?gt(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function dt(e,t){return null!==gt(e,t)}const ft=new Map;function gt(e,t){return ft.has(t)||ft.set(t,new Map),ft.get(t).has(e)||ft.get(t).set(e,function(e,t){e=e.trim();let r=null;const n=e.match(ut);if(n){if(r=function(e){if(e=e.trim(),ut.test(e)){const t=/AM/i.test(e),r=/PM/i.test(e),n=(t||r?e.substring(0,e.length-2).trim():e).split(/:/),o=n.length>=2,s=3===n.length;let i=Number(n[0]),a=o?Number(n[1]):0,l=s?Number(n[2]):0,c=s?"hh:mm:ss":"hh:mm";if(t||r)c+=" a";else if(!o)return null;i>=12&&t?i-=12:i<12&&r&&(i+=12),a+=Math.floor(l/60),l%=60,i+=Math.floor(a/60),a%=60,i>=24&&(c="hhhh:mm:ss");return{value:i/24+a/1440+l/86400,format:c,jsDate:new Qe(1899,11,30,i,a,l)}}return null}(n[0]),null===r)return null;e=e.replace(n[0],"").trim()}let o=null;const s=function(e,t){const r=e.match(ct);if(!r)return null;const[,n,o,,s]=r;if(n.length>2&&s&&s.length>2)return null;if(n.length>2)return{year:n,month:o,day:s,dateString:e,type:"ymd"};const i=function(e){switch(e.dateFormat[0]){case"d":return"dmy";case"m":return"mdy";case"y":return"ymd"}throw new Error("Invalid date format in locale")}(t);if(!s)return o.length>2?{month:n,year:o,day:void 0,dateString:e,type:i}:"dmy"===i?{day:n,month:o,year:s,dateString:e,type:"dmy"}:{month:n,day:o,year:s,dateString:e,type:"mdy"};if(s.length>2)return"mdy"===i?{month:n,day:o,year:s,dateString:e,type:"mdy"}:{day:n,month:o,year:s,dateString:e,type:"dmy"};if("mdy"===i)return{month:n,day:o,year:s,dateString:e,type:"mdy"};if("ymd"===i)return{year:n,month:o,day:s,dateString:e,type:"ymd"};if("dmy"===i)return{day:n,month:o,year:s,dateString:e,type:"dmy"};return null}(e,t);if(s){const t=s.dateString.match(lt)[0];if(o=function(e,t){const{year:r,month:n,day:o}=e,s=function(e){if(!e)return nt;const t=Number(e);if(t>=1&&t<=12)return t-1;return null}(n),i=function(e){if(!e)return 1;const t=Number(e);if(t>=0&&t<=31)return t;return null}(o),a=function(e){if(!e)return rt;const t=Number(e);switch(e.length){case 1:return tt+t;case 2:return tt+(tt+t>rt+10?-100:0)+t;case 3:case 4:return t}return null}(r);if(null===a||null===s||null===i)return null;const l=2===n?.length&&s+1<10||2===o?.length&&i<10,c=2!==r?.length,u=new Qe(a,s,i);if(u.getMonth()!==s||u.getDate()!==i)return null;const h=u.getTime()-Je.getTime(),d=function(e,t,r,n){const o=e.year?n?"yyyy":"yy":void 0,s=e.month?r?"mm":"m":void 0,i=e.day?r?"dd":"d":void 0;switch(e.type){case"mdy":return[s,i,o].filter(Se).join(t);case"ymd":return[o,s,i].filter(Se).join(t);case"dmy":return[i,s,o].filter(Se).join(t)}}(e,t,l,c);return{value:Math.round(h/et),format:d,jsDate:u}}(s,t),null===o)return null;e=e.replace(s.dateString,"").trim()}if(""!==e||!o&&!r)return null;if(o&&o.jsDate&&r&&r.jsDate)return{value:o.value+r.value,format:o.format+" "+("hhhh:mm:ss"===r.format?"hh:mm:ss":r.format),jsDate:new Qe(o.jsDate.getFullYear()+r.jsDate.getFullYear()-1899,o.jsDate.getMonth()+r.jsDate.getMonth()-11,o.jsDate.getDate()+r.jsDate.getDate()-30,o.jsDate.getHours()+r.jsDate.getHours(),o.jsDate.getMinutes()+r.jsDate.getMinutes(),o.jsDate.getSeconds()+r.jsDate.getSeconds())};return o||r}(e,t)),ft.get(t).get(e)}function mt(e){const t=Math.trunc(e),r=Qe.fromTimestamp(t*et-ot);let n=e-t;n=n<0?1+n:n;const o=Math.round(24*n),s=Math.round(24*(n-o/24)*60),i=Math.round(24*(n-o/24-s/24/60)*60*60);return r.setHours(o),r.setMinutes(s),r.setSeconds(i),r}function pt(e){return Math.round(bt(e))}function bt(e){return(e.getTime()-Je.getTime())/et}function vt(e){return new Qe(e.getFullYear(),e.getMonth()+1,0).getDate()}function yt(e){return vt(e)===e.getDate()}function wt(e,t,r){const n=e.getFullYear(),o=e.getMonth(),s=e.getDate(),i=new Qe(n,o+t,1);return r&&s===vt(e)||s>vt(i)?i.setDate(vt(i)):i.setDate(s),i}function Et(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function St(e,t,r){if(e===t)return 0;if(e>t){const r=t;t=e,e=r}const n=mt(e),o=mt(t);let s=n.getDate(),i=o.getDate();const a=n.getMonth(),l=o.getMonth(),c=n.getFullYear(),u=o.getFullYear();let h=0,d=0;switch(r){case 0:31===s&&(s=30),30===s&&31===i&&(i=30),1===a&&s===(Et(c)?29:28)&&(s=30,1===l&&i===(Et(u)?29:28)&&(i=30)),h=c+(30*a+s)/360,d=u+(30*l+i)/360;break;case 1:let r=365;const n=c===u;if(!n&&!(c+1===u)||!n&&a<l||!n&&a===l&&s<i){let e=0,t=0;for(let r=c;r<=u;r++)e++,t+=Et(r)?366:365;r=t/e}else n?Et(c)&&(r=366):(Et(c)&&a<2&&(r=366),Et(u)&&(l>1||1===l&&29===i)&&(r=366));h=e/r,d=t/r;break;case 2:h=e/360,d=t/360;break;case 3:h=e/365,d=t/365;break;case 4:31===s&&(s=30),31===i&&(i=30),h=c+(30*a+s)/360,d=u+(30*l+i)/360}return d-h}function Ct(e,t){const r=12*(t.getFullYear()-e.getFullYear())+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?r-1:r}function Tt(e,t){const r=e.getTime(),n=t.getTime();return Math.floor((n-r)/et)}function It(e,t){const r=t.getFullYear()-e.getFullYear(),n=e.getMonth(),o=t.getMonth(),s=e.getDate(),i=t.getDate();return o>n||o===n&&i>=s?r:r-1}function xt(e,t,r){return t>r?xt(e,r,t):(e=Math.trunc(e),t=Math.trunc(t),r=Math.trunc(r),e>=t&&e<=r)}const Rt=Ue(function(e){return e=te(e),new RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),At=Ue(function(e){const t=te(e.decimalSeparator),r="(?:\\s*"+`(?:\\d+(?:${te(e.thousandsSeparator||"")}\\d{3,})*(?:${t}\\d*)?)`+"|"+`(?:${t}\\d+)`+")(?:e(?:\\+|-)?\\d+)?(?:\\s*%)?",n="(?:\\s*-)?",o="(?:\\s*[\\$€])?",s="^(?:(?:"+[n+o+r,n+r+o,o+n+r].join(")|(?:")+"))$";return new RegExp(s,"i")});function _t(e,t){return!!e&&At(t).test(e.trim())}const Ot=Ue(function(e){return new RegExp(`[$€${te(e.thousandsSeparator||"")}]`,"g")});function Dt(e,t){e=e.replace(Ot(t),""),"."!==t.decimalSeparator&&(e=e.replace(t.decimalSeparator,"."));let r=Number(e);return isNaN(r)&&e.includes("%")&&(r=Number(e.split("%")[0]),!isNaN(r))?r/100:r}function Ft(e,t,r){const n=[...e].sort((e,t)=>e-t);let o=(n.length+(r?-1:1))*t;if(r||o--,Number.isInteger(o))return n[o];const s=Math.ceil(o),i=Math.floor(o);return n[s]*(o-i)+n[i]*(s-o)}const Nt=["number","string","boolean","undefined"];function Mt(e){if(void 0!==e)return O(e)?e[0][0]?.format:e.format}function Vt(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.",$t(e))}}const Pt=e=>v("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function kt(e,t){const r=Yt(e);switch(typeof r){case"number":return r;case"boolean":return r?1:0;case"string":if(_t(r,t)||""===r)return Dt(r,t);const e=gt(r,t);if(e)return e.value;throw new S(Pt(r));default:return 0}}function Ut(e,t){return mr(e).map(e=>e.map(e=>{if("number"!=typeof e.value){let r="";throw"object"==typeof e?r=v("Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.",t):"string"==typeof e?r=v("Function [[FUNCTION_NAME]] expects number values for %s, but got a string.",t):"boolean"==typeof e&&(r=v("Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.",t)),new S(r)}return e.value}))}function Ht(e,t){const r=Yt(e);if(""===r)throw new S(Pt(r));return kt(r,t)}function Bt(e,t){return Math.trunc(kt(e,t))}function zt(e,t){return Math.trunc(Ht(e,t))}function $t(e){const t=Yt(e);switch(typeof t){case"string":return t;case"number":return t.toString();case"boolean":return t?"TRUE":"FALSE";default:return""}}const Gt=Ue(function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}),Wt=e=>v("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.",e);function qt(e){const t=Yt(e);switch(typeof t){case"boolean":return t;case"string":if(t){const e=t.toUpperCase();if("TRUE"===e)return!0;if("FALSE"===e)return!1;throw new S(Wt(t))}return!1;case"number":return!!t;default:return!1}}function Zt(e,t){return mt(kt(Yt(e),t))}function Yt(e){if("object"==typeof e&&null!==e&&"value"in e){if(Vt(e.value))throw e;return e.value}if(Vt(e))throw new S("",e);return e}function jt(e,t,r){for(const n of e)if(O(n)){const e=n.length,r=n[0].length;for(let o=0;o<r;o++)for(let r=0;r<e;r++)t(n[r][o])}else r(n)}function Xt(e,t){jt(e,e=>{if(Vt(e.value))throw e;t(e)},e=>{if(Vt(e?.value))throw e;t(e)})}function Kt(e,t,r){jt(e,e=>{if("number"==typeof e?.value&&t(e),Vt(e?.value))throw e},e=>{t({value:Ht(e,r),format:e?.format})})}function Qt(e,t,r,n,o="rowFirst"){let s=n;for(const n of e)if(O(n)){const e=n.length,r=n[0].length;if("rowFirst"===o)for(let o=0;o<r;o++)for(let r=0;r<e;r++)s=t(s,n[r][o]);else for(let o=0;o<e;o++)for(let e=0;e<r;e++)s=t(s,n[o][e])}else s=r(s,n);return s}function Jt(e,t,r,n="rowFirst"){return Qt(e,t,t,r,n)}function er(e,t,r,n){return Qt(e,(e,r)=>{const n=r?.value;if("number"==typeof n)return t(e,n);if(Vt(n))throw r;return e},(e,r)=>t(e,Ht(r,n)),r)}function tr(e,t,r,n){return Qt(e,(e,r)=>{const o=r?.value;if(null!=o){if("number"==typeof o)return t(e,o);if("boolean"==typeof o)return t(e,kt(o,n));if(Vt(o))throw r;return t(e,0)}return e},(e,r)=>t(e,kt(r,n)),r)}function rr(e,t,r){const n=Array(e);for(let o=0;o<e;o++){n[o]=Array(t);for(let e=0;e<t;e++)n[o][e]=r(o,e)}return n}function nr(e,t){return 0===e.length?[]:rr(e.length,e[0].length,(r,n)=>t(e[r][n]))}function or(e){return e.length?rr(e[0].length,e.length,(t,r)=>e[r][t]):[]}function sr(e,t,r=void 0){let n,o=1,s=1,i=1/0,a=1/0;for(let e=0;e<t.length;e++){const l=t[e];if(O(l)&&(void 0===r||r[e])){const r=l.length,c=l[0].length;1!==r||1!==c?(n??=new Array(t.length),1!==r&&1!==c?(n[e]="matrix",o=Math.max(o,r),s=Math.max(s,c),i=Math.min(i,r),a=Math.min(a,c)):1!==r?(n[e]="horizontal",o=Math.max(o,r),i=Math.min(i,r)):1!==c&&(n[e]="vertical",s=Math.max(s,c),a=Math.min(a,c))):t[e]=l[0][0]}}if(1===o&&1===s)return e(...t);return rr(o,s,(r,o)=>{if(r>i-1||o>a-1)return new x(v("Array arguments to [[FUNCTION_NAME]] are of different size."));const s=e(...(l=r,c=o,t.map((e,t)=>{switch(n?.[t]){case"matrix":return e[l][c];case"horizontal":return e[l][0];case"vertical":return e[0][c];case void 0:return e}})));var l,c;return O(s)?s[0][0]:s})}function ir(e,t){return function(e,t,r){for(const n of e)if(O(n)){const e=n.length,r=n[0].length;for(let o=0;o<r;o++)for(let r=0;r<e;r++)if(!t(n[r][o]??void 0))return}else if(!r(n))return}(e,e=>{const r=e?.value;if("boolean"==typeof r)return t(r);if("number"==typeof r)return t(!!r);if(Vt(r))throw e;return!0},e=>void 0===e||null===e.value||t(function(e){const t=Yt(e);if(""===t)throw new S(Wt(t));return qt(t)}(e)))}function ar(e,t){let r,n,o=e.substring(0,2);return"<="===o||">="===o||"<>"===o?(r=o,n=e.substring(2)):(o=e.substring(0,1),"<"===o||">"===o||"="===o?(r=o,n=e.substring(1)):(r="=",n=e)),_t(n,t)||dt(n,t)?n=kt(n,t):"TRUE"!==n&&"FALSE"!==n||(n=qt(n)),{operator:r,operand:n}}const lr=Ue(function(e){if("*"===e)return/.+/;let t="",r="";for(const n of e)"?"===n&&"~"!==r?t+=".":"*"===n&&"~"!==r?t+=".*":("*"!==n&&"?"!==n||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(n)&&(t+="\\"),t+=n),r=n;return new RegExp("^"+t+"$","i")});function cr(e="",t,r){const{operator:n,operand:o}=t;if(void 0===o||null===e||null===o)return!1;if("number"==typeof o&&"="===n)return"string"==typeof e&&(_t(e,r)||dt(e,r))?kt(e,r)===o:e===o;if("<>"===n||"="===n){let t;return t=typeof e==typeof o&&("string"==typeof e&&"string"==typeof o?lr(o).test(e):e===o),"="===n?t:!t}if(typeof e==typeof o)switch(n){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function ur(e,t,r,n=!1){const o=e.length;if(o%2==1)throw new S(v("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const s=mr(e[0]),i=s.length,a=s[0].length,l=[];for(let t=0;t<o-1;t+=2){const o=mr(e[t]);if(o.length!==i||o[0].length!==a)throw new S(v("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const s=ar($t(e[t+1]),r);n&&"string"==typeof s.operand&&(s.operand+="*"),l.push(s)}for(let n=0;n<i;n++)for(let s=0;s<a;s++){let i=!0;for(let t=0;t<o-1;t+=2){if(i=cr(mr(e[t])[n][s].value??void 0,l[t/2],r),!i)break}i&&t(n,s)}}function hr(e,t,r,n,o,s){if(void 0===t||null===t.value)return-1;if(Vt(t.value))throw t;const i=fr(t.value),a=typeof i;let l,c,u,h,d,f,g=0,m=o-1;const p="desc"===n?t=>fr(s(e,o-t-1)):t=>fr(s(e,t));for(;m-g>=0;){for(u=Math.floor((g+m)/2),h=u,d=p(h),f=typeof d;g<h&&a!==f;)h--,d=p(h),f=typeof d;f===a&&null!=d?("strict"===r&&d===i?(l=d,c=h):"nextSmaller"===r&&d<=i?(null==l||l<d||l===d&&c<h)&&(l=d,c=h):"nextGreater"===r&&d>=i&&(void 0===l||l>d||l===d&&c<h)&&(l=d,c=h),d>i||"strict"===r&&d===i?m=h-1:g=u+1):g=u+1}return void 0===c?-1:"desc"===n?o-c-1:c}function dr(e,t,r,n,o,s,i=!1){if(void 0===t||null===t.value)return-1;if(Vt(t.value))throw t;const a=fr(t.value),l=i?(e,t)=>fr(o(e,n-t-1)):(e,t)=>fr(o(e,t)),c="wildcard"!==r||"string"!=typeof a||!(a.includes("*")||a.includes("?"));if(s&&c){const t=i?"reverseSearch":"forwardSearch";let o=s[t].get(e);if(void 0===o){o=new Map;for(let t=0;t<n;t++){const r=l(e,t)??null;o.has(r)||o.set(r,t)}s[t].set(e,o)}if(o.has(a)){const e=o.get(a);return i?n-e-1:e}if("strict"===r)return-1}const u=function(e,t,r,n,o){let s=r=>o(e,r)===t;if("wildcard"===r&&"string"==typeof t&&(t.includes("*")||t.includes("?"))){const r=lr(t);s=t=>{const n=o(e,t);return"string"==typeof n&&r.test(n)}}let i,a=-1;"nextSmaller"===r&&(s=r=>{const n=o(e,r);return(!i&&gr(t,n)>=0||gr(t,n)>=0&&gr(n,i)>0)&&(i=n,a=r),n===t});"nextGreater"===r&&(s=r=>{const n=o(e,r);return(!i&&gr(t,n)<=0||gr(t,n)<=0&&gr(n,i)<0)&&(i=n,a=r),n===t});for(let e=0;e<n;e++)if(s(e))return e;return a}(e,a,r,n,l);return i&&-1!==u?n-u-1:u}function fr(e){return"string"==typeof e?Gt(e):e}function gr(e,t){let r=Nt.indexOf(typeof e)-Nt.indexOf(typeof t);return 0===r&&("string"==typeof e&&"string"==typeof t?r=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?r=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(r=Number(e)-Number(t))),r}function mr(e){return void 0===e?[[]]:O(e)?e:[[e]]}function pr(e,t){return Jt(e,(e,r)=>(e.push(t(r)),e),[],"rowFirst")}function br(e){if(void 0===e)return!1;const{value:t}=e;return null!==t&&""!==t}const vr=v("[[FUNCTION_NAME]] has no valid input data.");function yr(e){return v("[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.",{argName:e})}function wr(e){function t(...t){for(let r=0;r<t.length;r++){const n=t[r],o=c(e,t.length);if(!e.args[o(r)||r].acceptErrors&&!O(n)&&Vt(n?.value))return n}try{return r.apply(this,t)}catch(t){return Er(t,e.name)}}function r(...t){this.debug;const r=e.compute.apply(this,t);return O(r)?"object"==typeof r[0][0]&&null!==r[0][0]&&"value"in r[0][0]?(function(e,t){const r=e.length,n=e[0]?.length??0;for(let o=0;o<r;o++)for(let r=0;r<n;r++)t(e[o][r])}(r,t=>Sr(t,e.name)),r):nr(r,e=>({value:e})):"object"==typeof r&&null!==r&&"value"in r?(Sr(r,e.name),r):{value:r}}return function(...r){const n=[],o=c(e,r.length);for(let t=0;t<r.length;t++){const s=o(t)??-1,i=e.args[s];if(!O(r[t])&&i.acceptMatrixOnly)throw new C(v("Function %s expects the parameter '%s' to be reference to a cell or range.",e.name,(t+1).toString()));n.push(!i.acceptMatrix)}return sr(t.bind(this),r,n)}}function Er(e,t){return r=e,void 0!==r?.value&&"string"==typeof r.value&&Vt(e.value)?(Tr(e)&&Sr(e,t),e):(console.error(e),new S(Cr+(Tr(e)?" "+e.message:"")));var r}function Sr(e,t){e.message?.includes("[[FUNCTION_NAME]]")&&(e.message=e.message.replace("[[FUNCTION_NAME]]",t))}const Cr=v("An unexpected error occurred. Submit a support ticket at odoo.com/help.");function Tr(e){return void 0!==e?.message&&"string"==typeof e.message}function Ir(e,t){if(!e)throw new S(t)}function xr(e,t=v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")){if(0===e)throw new _(t)}function Rr(e){return 1===e.length||1===e[0].length}function Ar(...e){if(e.every(O)){const t=e[0].length,r=e[0][0].length;for(const n of e)if(n.length!==t||n[0].length!==r)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(1!==e.length||1!==e[0].length))}function _r(e){return e.length===e[0].length}const Or=e=>v("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e);function Dr(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 Fr(e){if(e.length<1||e[0].length<1)throw new Error("invertMatrix: an empty matrix cannot be inverted.");if(e.length!==e[0].length)throw new Error("invertMatrix: only square matrices are invertible");let t=1;const r=e.length,n=Dr(r),o=e.map(e=>e.slice());for(let e=0;e<r;e++){let s=o[e][e];if(0===s){for(let s=e+1;s<r;s++)if(0!==o[e][s]){Nr(o,e,s),Nr(n,e,s),t*=-1;break}if(s=o[e][e],0===s)return{determinant:0}}for(let t=0;t<r;t++)o[t][e]=o[t][e]/s,n[t][e]=n[t][e]/s;t*=s;for(let t=0;t<r;t++){if(t===e)continue;const s=o[e][t];for(let i=0;i<r;i++)o[i][t]-=s*o[i][e],n[i][t]-=s*n[i][e]}}return{inverted:n,determinant:t}}function Nr(e,t,r){for(let n=0;n<e.length;n++){const o=e[n][t];e[n][t]=e[n][r],e[n][r]=o}}function Mr(e,t){if(e.length<1||t.length<1)throw new Error("multiplyMatrices: empty matrices cannot be multiplied.");if(e.length!==t[0].length)throw new Error("multiplyMatrices: incompatible matrices size.");const r=e[0].length,n=t.length,o=e.length,s=Array(n);for(let i=0;i<n;i++){s[i]=Array(r);for(let n=0;n<r;n++){let r=0;for(let s=0;s<o;s++)r+=e[s][n]*t[i][s];s[i][n]=r}}return s}function Vr(e){if(!O(e))return e;if(!Lr(e))throw new Error("The value should be a scalar or a 1x1 matrix");return e[0][0]}function Lr(e){return 1===e.length&&1===e[0].length}function Pr(e){return O(e)&&!Lr(e)}const kr={description:v("Returns a result array constrained to a specific width and height."),args:[a("input_range (any, range<any>)",v("The range to constrain.")),a("rows (number)",v("The number of rows in the constrained array.")),a("columns (number)",v("The number of columns in the constrained array."))],compute:function(e,t,r){const n=mr(e),o=Bt(t?.value,this.locale),s=Bt(r?.value,this.locale);if(o<=0)return new S(v("The rows argument (%s) must be strictly positive.",o.toString()));if(s<=0)return new S(v("The columns argument (%s) must be strictly positive.",s.toString()));const i=Math.min(o,n[0].length);return rr(Math.min(s,n.length),i,(e,t)=>n[e][t])},isExported:!1},Ur={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>)",v("The first column index of the columns to be returned.")),a("col_num2 (number, range<number>, repeating)",v("The columns indexes of the columns to be returned."))],compute:function(e,...t){const r=mr(e),n=pr(t,e=>Bt(e?.value,this.locale)),o=n.filter(e=>0===e||r.length<Math.abs(e));if(0!==o.length)return new S(v("The columns arguments must be between -%s and %s (got %s), excluding 0.",r.length.toString(),r.length.toString(),o.join(",")));const s=Array(n.length);for(let e=0;e<n.length;e++)n[e]>0?s[e]=r[n[e]-1]:s[e]=r[r.length+n[e]];return s},isExported:!0},Hr={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>)",v("The first row index of the rows to be returned.")),a("row_num2 (number, range<number>, repeating)",v("The rows indexes of the rows to be returned."))],compute:function(e,...t){const r=mr(e),n=pr(t,e=>Bt(e?.value,this.locale)),o=r.length,s=n.filter(e=>0===e||r[0].length<Math.abs(e));return 0!==s.length?new S(v("The rows arguments must be between -%s and %s (got %s), excluding 0.",r[0].length.toString(),r[0].length.toString(),s.join(","))):rr(o,n.length,(e,t)=>n[t]>0?r[e][n[t]-1]:r[e][r[e].length+n[t]])},isExported:!0},Br={description:v("Expands or pads an array to specified row and column dimensions."),args:[a("array (any, range<any>)",v("The array to expand.")),a("rows (number)",v("The number of rows in the expanded array. If missing, rows will not be expanded.")),a("columns (number, optional)",v("The number of columns in the expanded array. If missing, columns will not be expanded.")),a("pad_with (any, default=0)",v("The value with which to pad."))],compute:function(e,t,r,n={value:0}){const o=mr(e),s=Bt(t?.value,this.locale),i=void 0!==r?Bt(r.value,this.locale):o.length;return s<o[0].length?new S(v("The rows arguments (%s) must be greater or equal than the number of rows of the array.",s.toString())):i<o.length?new S(v("The columns arguments (%s) must be greater or equal than the number of columns of the array.",i.toString())):rr(i,s,(e,t)=>e>=o.length||t>=o[e].length?n:o[e][t])},isExported:!0},zr={description:v("Flattens all the values from one or more ranges into a single column."),args:[a("range (any, range<any>)",v("The first range to flatten.")),a("range2 (any, range<any>, repeating)",v("Additional ranges to flatten."))],compute:function(...e){return[pr(e,e=>void 0===e?{value:""}:e)]},isExported:!1},$r={description:v("Calculates the frequency distribution of a range."),args:[a("data (range<number>)",v("The array of ranges containing the values to be counted.")),a("classes (number, range<number>)",v("The range containing the set of classes."))],compute:function(e,t){const r=pr([e],e=>e.value).filter(e=>"number"==typeof e),n=pr([t],e=>e.value).filter(e=>"number"==typeof e),o=n.map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);o.push({initialIndex:o.length,value:1/0,count:0});const s=r.sort((e,t)=>e-t);let i=0;for(const e of s){for(;e>o[i].value&&i<o.length-1;)i++;o[i].count++}return[o.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},Gr={description:v("Appends ranges horizontally and in sequence to return a larger array."),args:[a("range1 (any, range<any>)",v("The first range to be appended.")),a("range2 (any, range<any>, repeating)",v("Additional ranges to add to range1."))],compute:function(...e){const t=Math.max(...e.map(e=>e?.[0]?.length??0)),r=[];for(const n of e){const e=mr(n);for(let n=0;n<e.length;n++){const o=Array(t).fill({value:null});for(let t=0;t<e[n].length;t++)o[t]=e[n][t];r.push(o)}}return r},isExported:!0},Wr={description:v("Returns the matrix determinant of a square matrix."),args:[a("square_matrix (number, range<number>)",v("An range with an equal number of rows and columns representing a matrix whose determinant will be calculated."))],compute:function(e){const t=Ut(e,"square_matrix");return _r(t)?Fr(t).determinant:new S(v("The argument square_matrix must have the same number of columns and rows."))},isExported:!0},qr={description:v("Returns the multiplicative inverse of a square matrix."),args:[a("square_matrix (number, range<number>)",v("An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated."))],compute:function(e){const t=Ut(e,"square_matrix");if(!_r(t))return new S(v("The argument square_matrix must have the same number of columns and rows."));const{inverted:r}=Fr(t);return r||new S(v("The matrix is not invertible."))},isExported:!0},Zr={description:v("Calculates the matrix product of two matrices."),args:[a("matrix1 (number, range<number>)",v("The first matrix in the matrix multiplication operation.")),a("matrix2 (number, range<number>)",v("The second matrix in the matrix multiplication operation."))],compute:function(e,t){const r=Ut(e,"matrix1"),n=Ut(t,"matrix2");return 0===r.length||0===n.length?new S(v("The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.")):r.length!==n[0].length?new S(v("In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).",r.length.toString(),n[0].length.toString())):Mr(r,n)},isExported:!0},Yr={description:v("Calculates the sum of the products of corresponding entries in equal-sized ranges."),args:[a("range1 (number, range<number>)",v("The first range whose entries will be multiplied with corresponding entries in the other ranges.")),a("range2 (number, range<number>, repeating)",v("The other range whose entries will be multiplied with corresponding entries in the other ranges."))],compute:function(...e){if(!Ar(...e))return new S(v("All the ranges must have the same dimensions."));const t=e.map(mr);let r=0;for(let e=0;e<t[0].length;e++)for(let n=0;n<t[0][e].length;n++){if(!t.every(t=>"number"==typeof t[e][n].value))continue;let o=1;for(const r of t)o*=kt(r[e][n],this.locale);r+=o}return r},isExported:!0};function jr(e,t,r){if(!Ar(e,t))return new S(v("The arguments array_x and array_y must have the same dimensions."));const n=mr(e),o=mr(t);let s=!1,i=0;for(const e in n)for(const t in n[e]){const a=n[e][t].value,l=o[e][t].value;"number"==typeof a&&"number"==typeof l&&(s=!0,i+=r(a,l))}return s?i:new S(v("The arguments array_x and array_y must contain at least one pair of numbers."))}const Xr={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 jr(e,t,(e,t)=>e**2-t**2)},isExported:!0},Kr={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 jr(e,t,(e,t)=>e**2+t**2)},isExported:!0},Qr={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 jr(e,t,(e,t)=>(e-t)**2)},isExported:!0},Jr=!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=>!Vt(e.value);if(3===t)return e=>null!==e.value&&!Vt(e.value);throw new S(v("Argument ignore must be between 0 and 3"))}const rn={description:v("Transforms a range of cells into a single column."),args:en,compute:function(e,t={value:0},r={value:Jr}){const n=mr(e),o=kt(t.value,this.locale),s=(qt(r.value)?n:or(n)).flat().filter(tn(o));return 0===s.length?new x(v("No results for the given arguments of TOCOL.")):[s]},isExported:!0},nn={description:v("Transforms a range of cells into a single row."),args:en,compute:function(e,t={value:0},r={value:Jr}){const n=mr(e),o=kt(t.value,this.locale),s=(qt(r.value)?n:or(n)).flat().filter(tn(o)).map(e=>[e]);return 0===s.length||0===s[0].length?new x(v("No results for the given arguments of TOROW.")):s},isExported:!0},on={description:v("Transposes the rows and columns of a range."),args:[a("range (any, range<any>)",v("The range to be transposed."))],compute:function(e){const t=mr(e);return rr(t[0].length,t.length,(e,r)=>t[r][e])},isExported:!0},sn={description:v("Appends ranges vertically and in sequence to return a larger array."),args:[a("range1 (any, range<any>)",v("The first range to be appended.")),a("range2 (any, range<any>, repeating)",v("Additional ranges to add to range1."))],compute:function(...e){const t=Math.max(...e.map(e=>mr(e).length)),r=e.reduce((e,t)=>e+mr(t)[0].length,0),n=Array(t).fill([]).map(()=>Array(r).fill({value:0}));let o=0;for(const t of e){const e=mr(t);for(let t=0;t<e.length;t++)for(let r=0;r<e[t].length;r++)n[t][o+r]=e[t][r];o+=e[0].length}return n},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 n=mr(e),o=Bt(t?.value,this.locale);if(!Rr(n))return new S(v("Argument range must be a single row or column."));const s=n.flat();return rr(Math.ceil(s.length/o),o,(e,t)=>{const n=e*o+t;return n<s.length?s[n]:r})},isExported:!0},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 n=mr(e),o=Bt(t?.value,this.locale);if(!Rr(n))return new S(v("Argument range must be a single row or column."));const s=n.flat(),i=Math.ceil(s.length/o);return rr(o,i,(e,t)=>{const n=t*o+e;return n<s.length?s[n]:r})},isExported:!0};var cn=Object.freeze({__proto__:null,ARRAY_CONSTRAIN:kr,CHOOSECOLS:Ur,CHOOSEROWS:Hr,EXPAND:Br,FLATTEN:zr,FREQUENCY:$r,HSTACK:Gr,MDETERM:Wr,MINVERSE:qr,MMULT:Zr,SUMPRODUCT:Yr,SUMX2MY2:Xr,SUMX2PY2:Kr,SUMXMY2:Qr,TOCOL:rn,TOROW:nn,TRANSPOSE:on,VSTACK:sn,WRAPCOLS:an,WRAPROWS:ln});function un(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 hn=new Set("$+-/():!^&~{}<>= ");function dn(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 hn.has(e.current)?{type:"CHAR",value:e.shift()}:null}function fn(e){return","===e.current?(e.shift(),{type:"THOUSANDS_SEPARATOR",value:","}):null}function gn(e){return"@"===e.current?(e.shift(),{type:"TEXT_PLACEHOLDER",value:"@"}):null}function mn(e){return"."===e.current?(e.shift(),{type:"DECIMAL_POINT",value:"."}):null}function pn(e){return"%"===e.current?(e.shift(),{type:"PERCENT",value:"%"}):null}function bn(e){if("0"===e.current||"#"===e.current){const t=e.current;return e.shift(),{type:"DIGIT",value:t}}return null}const vn=new Set("dmqyhsa");function yn(e){if(!vn.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 wn(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 En={};function Sn(e){let t=En[e];return void 0===t&&(t=function(e){const t=function(e){const t=new Ze(e),r=[];let n=[];for(r.push(n);!t.isOver();){if(";"===t.current){n=[],r.push(n),t.shift();continue}const e=bn(t)||un(t)||dn(t)||fn(t)||mn(t)||pn(t)||yn(t)||gn(t)||wn(t);if(!e)throw new Error("Unknown token at "+t.remaining());n.push(e)}return r}(e);for(const e of t){const t=e.filter(e=>"REPEATED_CHAR"===e.type);for(const e of t.slice(1))e.type="CHAR"}const r=Tn(t[0])||Cn(t[0])||In(t[0]);if(!r)throw new Error("Invalid first format part of: "+e);if(t.length>1&&"text"===r.type)throw new Error("The first format in a multi-part format must be a number format: "+e);const n=Tn(t[1])||Cn(t[1]);if(t[1]?.length&&!n)throw new Error("Invalid second format part of: "+e);const o=Tn(t[2])||Cn(t[2]);if(t[2]?.length&&!o)throw new Error("Invalid third format part of: "+e);const s=In(t[3]);if(t[3]?.length&&!s)throw new Error("Invalid fourth format part of: "+e);return{positive:r,negative:n,zero:o,text:s}}(e),En[e]=t),t}function Cn(e){if(!e||!function(e){return e.every(e=>"DIGIT"===e.type||"DECIMAL_POINT"===e.type||"THOUSANDS_SEPARATOR"===e.type||"PERCENT"===e.type||"STRING"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e))return;const t=[];let r,n=t,o=0,s=0,i=e.findLastIndex(e=>"DIGIT"===e.type),a=!1,l=0;for(let c=0;c<e.length;c++){const u=e[c];switch(u.type){case"DIGIT":n===t?n.push(u):l<20&&(n.push(u),l++);break;case"DECIMAL_POINT":if(n!==t)throw new Error("Multiple decimal points in a number format");r=[],n=r;break;case"REPEATED_CHAR":case"CHAR":case"STRING":n.push(u);break;case"PERCENT":o++,n.push(u);break;case"THOUSANDS_SEPARATOR":c-1===i?(s+=1,i++,n.push(u)):"DIGIT"===e[c+1]?.type&&"DIGIT"===e[c-1]?.type?(n===t&&(a=!0),n.push(u)):n.push({type:"CHAR",value:","})}}return{type:"number",integerPart:t,decimalPart:r,percentSymbols:o,thousandsSeparator:a,magnitude:s}}function Tn(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)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 In(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 xn(e){return[Rn(e.positive),Rn(e.negative),Rn(e.zero),Rn(e.text)].filter(Se).join(";")}function Rn(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));return t}(e);for(const e of r)switch(e.type){case"STRING":t+=`[$${e.value}]`;break;case"CHAR":t+=An(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 An(e){return!hn.has(e)}const _n="REPEATED_CHAR_PLACEHOLDER_",On={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")},Dn={0:v("Sunday"),1:v("Monday"),2:v("Tuesday"),3:v("Wednesday"),4:v("Thursday"),5:v("Friday"),6:v("Saturday")};function Fn(e,{format:t,locale:r,formatWidth:n}){switch("boolean"==typeof e&&(e=e?"TRUE":"FALSE"),typeof e){case"string":{if(e.includes('\\"')&&(e=e.replaceAll(/\\"/g,'"')),!t)return e;const r=Nn(e,Sn(t)).format;return r&&"text"===r.type?Mn(e,r,n):e}case"number":t||(t=$n(e));const o=Sn(t),{format:s,isNegativeFormat:i}=Nn(e,o);if(!s)return e.toString();if("text"===s.type)return Mn(e.toString(),s,n);if(i&&(e=Math.abs(e)),"date"===s.type)return Vn(function(e,t){const r=mt(e),n=t.tokens.some(e=>"DATE_PART"===e.type&&"a"===e.value);let o="";for(const e of t.tokens)switch(e.type){case"DATE_PART":o+=Bn(r,e.value,n);break;case"REPEATED_CHAR":o+=_n+e.value;break;default:o+=e.value}return o}(e,s),n);const a=e<0,l=Vn(function(e,t,r){if(e===1/0)return"∞"+(t.percentSymbols?"%":"");const n=2*t.percentSymbols-3*t.magnitude;e*=10**n;let o=0;void 0!==t.decimalPart&&(o=t.decimalPart.filter(e=>"DIGIT"===e.type).length);const{integerDigits:s,decimalDigits:i}=Pn(Math.abs(e),o);let a=function(e,t,r){let n=t.integerPart;n.some(e=>"DIGIT"===e.type)||(n=[...n,{type:"DIGIT",value:"#"}]);"0"===e&&(e="");let o="";const s=n.findIndex(e=>"DIGIT"===e.type);let i=e.length-1;function a(t,n){if("0"===n&&(t=t||"0"),!t)return;const s=e.length-1-i;o=r&&s>0&&s%3==0?t+r+o:t+o}for(let t=n.length-1;t>=0;t--){const r=n[t];switch(r.type){case"DIGIT":if(a(e[i],r.value),i--,s===t)for(;i>=0;)a(e[i],"0"),i--;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":o=_n+r.value+o;break;default:o=r.value+o}}return o}(s,t,t.thousandsSeparator?r.thousandsSeparator:void 0);void 0!==t.decimalPart&&(a+=r.decimalSeparator+function(e,t){if(!t.decimalPart)return"";let r="",n=0;for(const o of t.decimalPart)switch(o.type){case"DIGIT":r+="#"===o.value?e[n]||"":e[n]||"0",n++;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":r+=_n+o.value;break;default:r+=o.value}return r}(i||"",t));return a}(Math.abs(e),s,r),n);return a?"-"+l:l;case"object":return""}}function Nn(e,t){let r,n=!1;switch(typeof e){case"number":e<0&&t.negative?(r=t.negative,n=!0):r=0===e&&t.zero?t.zero:t.positive;break;case"string":const o=t.text||t.positive;"text"===o.type&&(r=o)}return{format:r,isNegativeFormat:n}}function Mn(e,t,r){let n="";for(const r of t.tokens)switch(r.type){case"TEXT_PLACEHOLDER":n+=e;break;case"CHAR":case"STRING":n+=r.value;break;case"REPEATED_CHAR":n+=_n+r.value}return Vn(n,r)}function Vn(e,t){const r=e.indexOf(_n);if(-1===r)return e;const n=e.slice(0,r),o=e.slice(r+26+1),s=e[r+26];const{timesToRepeat:i,padding:a}=function(){if(!t)return{timesToRepeat:0,padding:""};const e=t.measureText(n+o),r=t.measureText(s),i=t.availableWidth-e;if(i<=0)return{timesToRepeat:0,padding:""};const a=Math.floor(i/r),l=i-a*r,c=t.measureText(" ");return{timesToRepeat:a,padding:" ".repeat(Math.floor(l/c))}}();return n+s.repeat(i)+a+o}const Ln=[];function Pn(e,t=20){const r=e.toString();if(r.includes("e"))return function(e,t=20){let r=Ln[t];r||(r=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),Ln[t]=r);const[n,o]=r.format(e).split(".");return{integerDigits:n,decimalDigits:o}}(e,t);if(Number.isInteger(e))return{integerDigits:r,decimalDigits:void 0};const n=r.indexOf(".");let o=r.substring(0,n),s=r.substring(n+1);if(0===t)return Number(s[0])>=5&&(o=(Number(o)+1).toString()),{integerDigits:o,decimalDigits:void 0};if(s.length>t){const{integerDigits:e,decimalDigits:r}=function(e,t){let r="0",n=e;const o=e.slice(0,t),s=t;if(Number(e[s])<5)return{integerDigits:r,decimalDigits:o};const i=o.match(Un)?.[0]||"",a=(Number(o)+1).toString(),l=o.slice(i.length),c=a.length>l.length;c&&!i?(r="1",n=void 0):n=c?i.slice(0,-1)+a:i+a;return{integerDigits:r,decimalDigits:n}}(s,t);s=r,"0"!==e&&(o=(Number(o)+Number(e)).toString())}return{integerDigits:o,decimalDigits:kn(s||"")}}function kn(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const Un=/^0+/;const Hn=Ue(function(e){if(!e)return!1;try{return"date"===Sn(e).positive.type}catch(e){return!1}});function Bn(e,t,r){switch(t){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return Dn[e.getDay()].slice(0,3);case"dddd":return Dn[e.getDay()].toString();case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return On[e.getMonth()].slice(0,3);case"mmmm":return On[e.getMonth()].toString();case"mmmmm":return On[e.getMonth()].slice(0,1);case"qq":return v("Q%(quarter)s",{quarter:e.getQuarter()}).toString();case"qqqq":return v("Quarter %(quarter)s",{quarter:e.getQuarter()}).toString();case"yy":const n=String(e.getFullYear()).replace("-","").padStart(2,"0");return n.slice(n.length-2);case"yyyy":return e.getFullYear();case"hhhh":return Math.floor((e.getTime()-Je.getTime())/36e5).toString();case"hh":let o=e.getHours();return r&&(o=0===o?12:o>12?o-12:o),o.toString().padStart(2,"0");case"MM":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");case"a":return e.getHours()>=12?"PM":"AM";default:throw new Error(`invalid date format token: ${t}`)}}const zn=Ue(function(e){return new RegExp(`[0-9]+${te(e.decimalSeparator)}[0-9]`)});function $n(e){let{integerDigits:t,decimalDigits:r}=Pn(e);if(!r)return"0";const n=t.replace("-","").length;if(n+2>11)return"0";const o=11-n-1;return({decimalDigits:r}=Pn(e,Math.min(o,r.length))),r?"0."+"0".repeat(r.length):"0"}function Gn(e,t){if(!dt(e,t))return;return gt(e,t).format}function Wn(e){const t=e.includes(".")?"0.00":"0",r=e.match(/[\$€]/);if(r){const n=e.match(/[\d]/),o="[$"+r.values().next().value+"]";return n.index<r.index?"#,##"+t+o:o+"#,##"+t}if(e.includes("%"))return t+"%"}function qn(e,t,r){let n=0;try{n=Math.abs(kt(e?.value,r))}catch(e){return""}const o=e?.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return Zn(o,1,"k");case"m":return Zn(o,2,"m");case"b":return Zn(o,3,"b");default:throw new S(v("The formatting unit should be 'k', 'm' or 'b'."))}}return n<1e5?Zn(o,0,""):n<1e8?Zn(o,1,"k"):n<1e11?Zn(o,2,"m"):Zn(o,3,"b")}function Zn(e,t,r,n){const o=Sn(e||"#,##0");return xn({positive:Yn(o.positive,t,r),negative:o.negative?Yn(o.negative,t,r):void 0,zero:o.zero?Yn(o.zero,t,r):void 0,text:o.text})}function Yn(e,t,r){if("number"!==e.type)return e;const n={type:"STRING",value:r};let o=[...e.integerPart];const s=o.findLastIndex(e=>"DIGIT"===e.type);if(-1===s)throw new Error("Cannot create a large number format from a format with no digit.");for(;"THOUSANDS_SEPARATOR"===o[s+1]?.type;)o=He(o,[s+1]);const i=o[s+1];o="STRING"===i?.type&&["m","k","b"].includes(i.value)?ze(o,n,s+1):Be(o,[n],s+1),t>0&&(o=Be(o,Array(t).fill({type:"THOUSANDS_SEPARATOR",value:","}),s+1));const a=e.percentSymbols-o.filter(e=>"PERCENT"===e.type).length;return o.push(...new Array(a).fill({type:"PERCENT",value:"%"})),{...e,integerPart:o,decimalPart:void 0,magnitude:t}}function jn(e,t){const r=Sn(e);return xn(Sn(xn({positive:Xn(r.positive,t),negative:r.negative?Xn(r.negative,t):void 0,zero:r.zero?Xn(r.zero,t):void 0,text:r.text})))}function Xn(e,t){return"number"!==e.type?e:t>0?function(e,t){let r=e.integerPart,n=e.decimalPart;if(!n){const e=r.findLastIndex(e=>"DIGIT"===e.type);n=r.slice(e+1),r=r.slice(0,e+1)}const o=le(0,t).map(()=>({type:"DIGIT",value:"0"})),s=n.findLastIndex(e=>"DIGIT"===e.type);n=-1===s?[...o,...n]:Be(n,o,s+1);return{...e,decimalPart:n,integerPart:r}}(e,t):function(e,t){let r=e.decimalPart;if(!r)return e;const n=[];let o=0;for(let e=r.length-1;e>=0&&!(o>=Math.abs(t));e--)"DIGIT"===r[e].type&&(o++,n.push(e));if(r=He(r,n),r.some(e=>"DIGIT"===e.type))return{...e,decimalPart:r};return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...r]}}(e,Math.abs(t))}function Kn(e){const t=Sn(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 Qn(e){if(!e)return!1;try{return"text"===Sn(e).positive.type}catch{return!1}}const Jn={description:v("Apply a large number format"),args:[a("value (number)",v("The number.")),a("unit (string, optional)",v("The formatting unit. Use 'k', 'm', or 'b' to force the unit"),[{value:"k",label:v("Thousand")},{value:"m",label:v("Million")},{value:"b",label:v("Billion")}])],compute:function(e,t){return{value:kt(e,this.locale),format:qn(e,t,this.locale)}}};var eo=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Jn});const to=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),ro=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),no=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),oo=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),so=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),io=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),ao=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[to.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 lo(e){return so.test(e)}function co(e){return io.test(e)}function uo(e){return no.test(e)}function ho(e){return oo.test(e)}function fo(e){return ro.test(e)}function go(e){if(!e.includes("!"))return{xc:e};const t=e.split("!"),r=t.pop();return{sheetName:ne(t.join("!"))||void 0,xc:r}}function mo(e,t){return void 0!==e?`${se(e)}!${t}`:t}function po(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=bo(e,"colrow");break;case"colrow":e=bo(e,"row");break;case"row":e=bo(e,"col");break;case"col":e=bo(e,"none")}return e}function bo(e,t){let r;({sheetName:r,xc:e}=go(e)),r=r?r+"!":"";const n=(e=e.replace(/\$/g,"")).indexOf(":");return n>=0?`${r}${vo(e.slice(0,n),t)}:${vo(e.slice(n+1),t)}`:r+vo(e,t)}function vo(e,t){const r=e.search(/[0-9]/),n=0!==r,o=r>=0;switch(t){case"col":return n?"$"+e:e;case"row":return o?e.slice(0,r)+"$"+e.slice(r):e;case"colrow":return o&&n?"$"+e.slice(0,r)+"$"+e.slice(r):"$"+e;case"none":return e}}function yo(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class wo{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 Eo(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Eo(Math.floor(e/26)-1)+Eo(e%26)}function So(e){const t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function Co(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function To(e){return e>="0"&&e<="9"}const Io=function(e){let t=0;const r=e.length;for(let n=0;n<r;n++){t=26*t+So(e[n])}return t-1}("ZZZ"),xo=9999998;function Ro(e){for(;" "===e.current;)e.advanceBy(1)}function Ao(e){if("$"===e.current&&e.advanceBy(1),!e.current||!Co(e.current))return-1;let t=0;for(;e.current&&Co(e.current);)t=26*t+So(e.shift());return t}function _o(e){if("$"===e.current&&e.advanceBy(1),!e.current||!To(e.current))return-1;let t=0;for(;e.current&&To(e.current);)t=10*t+Number(e.shift());return t}function Oo(e){const t=new Ze(e);Ro(t);const r=Ao(t);if(-1===r||!t.current)throw new Error(`Invalid cell description: ${e}`);const n=_o(t);Ro(t);const o=r-1,s=n-1;if(!t.isOver()||o>Io||s>xo)throw new Error(`Invalid cell description: ${e}`);return{col:o,row:s}}function Do(e,t,r={colFixed:!1,rowFixed:!1}){return(r.colFixed?"$":"")+Eo(e)+(r.rowFixed?"$":"")+String(t+1)}function Fo(e,t=[]){if(e.length<=1&&0===t.length)return e;const r=[0],n=new Map([[0,[]]]);return No(r,n,e,!1),No(r,n,t,!0),Po(r,n)}function No(e,t,r,n=!1){for(const o of r){const r=o.left,s=void 0===o.right?void 0:o.right+1,i=Mo(e,t,r,!0,0),a=Mo(e,t,s,!1,i);for(let r=i;r<=a;r++){Vo(t.get(e[r]),o,n)}Lo(e,t,i,a)}}function Mo(e,t,r,n,o){if(void 0===r)return e.length-1;const s=ko(e,r,o);return r!==e[s]?(e.splice(s+1,0,r),t.set(r,[...t.get(e[s])]),n?s+1:s):n?s:s-1}function Vo(e,t,r=!1){const n=t.top,o=void 0===t.bottom?void 0:t.bottom+1,s=[],i=ko(e,n,0,!1);if((i%2!=0&&!r||i%2==0&&r)&&s.push(n),void 0===o)return e.splice(i+1),void e.push(...s);const a=Uo(e,o,0,!1);(a%2==0&&!r||a%2!=0&&r)&&s.push(o);const l=a-i-1,c=s.length,u=i+1;u===e.length-1&&1===l&&1===c?e[u]=s[0]??s[1]:e.splice(u,l,...s)}function Lo(e,t,r,n){const o=r-1==-1?0:r-1;for(let r=n===e.length-1?n:n+1;r>o;r--)Oe(t.get(e[r]),t.get(e[r-1]))&&(t.delete(e[r]),e.splice(r,1))}function Po(e,t){const r=[];let n=[];for(let o=0;o<e.length;o++){const s=e[o],i=t.get(s);if(!i||0===i.length){r.push(...n),n=[];continue}let a=e[o+1];void 0!==a&&a--;const l=[];for(let e=0;e<i.length;e+=2){const t=i[e];let r=i[e+1];void 0!==r&&r--;const o={top:t,left:s,bottom:r,right:a};(void 0===r&&0!==t||void 0===a&&0!==s)&&(o.hasHeader=!0);let c=!1;for(let e=n.length-1;e>=0;e--){const t=n[e];if(t.top===o.top&&t.bottom===o.bottom){t.right=o.right,n.splice(e,1),l.push(t),c=!0;break}}c||l.push(o)}r.push(...n),n=l}return r.push(...n),r}function ko(e,t,r=0,n=!0){let o=e.length-1,s=-1;for(;r<=o;){const i=Math.floor((r+o)/2);if(e[i]===t&&n)return i;e[i]<t?(s=i,r=i+1):o=i-1}return s}function Uo(e,t,r=0,n=!0){let o=e.length-1,s=e.length;for(;r<=o;){const i=Math.floor((r+o)/2);if(e[i]===t&&n)return i;e[i]>t?(s=i,o=i-1):r=i+1}return s}function Ho(e){const t=function(e){const t=new Ze(e);Ro(t);const r=e.indexOf("!");-1!==r&&t.advanceBy(r+1);const n=Ao(t),o=_o(t);let s,i,a,l,c=!1,u=!1,h=!1;if(-1===o?(a=l=n-1,s=i=0,c=!0):-1===n?(s=i=o-1,a=l=0,u=!0):(a=l=n-1,s=i=o-1,h=!0),Ro(t),":"===t.current){t.advanceBy(1),Ro(t);const e=Ao(t),r=_o(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=ns(t),n=r.bottom,o=r.right;if(void 0!==n&&n>xo||void 0!==o&&o>Io)throw new Error(`Range string out of bounds: ${e}`);if(void 0===n&&void 0===o)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");return r}function Bo(e){const t=Ho(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function zo(e){const{bottom:t,top:r,left:n,right:o}=e;return!(void 0!==t&&isNaN(t)||isNaN(r)||isNaN(n)||void 0!==o&&isNaN(o))&&($o(e)&&e.top>=0&&e.left>=0)}function $o(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 Go(e){const{top:t,bottom:r,left:n,right:o}=e,s="hasHeader"in e&&e.hasHeader,i=t===r&&n===o;if(void 0===r&&void 0!==o)return 0!==t||s?`${Do(n,t)}:${Eo(o)}`:`${Eo(n)}:${Eo(o)}`;if(void 0===o&&void 0!==r)return 0!==n||s?`${Do(n,t)}:${r+1}`:`${t+1}:${r+1}`;if(void 0!==r&&void 0!==o)return i?Do(n,t):`${Do(n,t)}:${Do(o,r)}`;throw new Error("Bad zone format")}function Wo(e,t,r,n,o){const s="left"===t?"columns":"rows",i="before"===n?r-1:r,a="left"===t?"right":"bottom";return e[t]<=i&&e[a]>i?os(e,s,"RESIZE",o):i<e[t]?os(e,s,"MOVE",o):{...e}}function qo(e,t,r){const n="left"===t?"right":"bottom";let o=e[t],s=e[n];for(const i of r.sort((e,t)=>t-e))e[t]>i&&(o--,s--),e[t]<i&&e[n]>=i&&s--;return{...e,[t]:o,[n]:s}}function Zo(...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 Yo(e,t){if(Ko(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 jo(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom&&e.hasHeader===t.hasHeader}function Xo(e,t){if(Yo(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 Ko(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 Qo(e,t,r){const{left:n,right:o,top:s,bottom:i}=r;return e>=n&&e<=o&&t>=s&&t<=i}function Jo(e,t){return jo(Zo(t,e),t)}function es(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function ts(e){const{numberOfCols:t,numberOfRows:r}=es(e);return 1===t||1===r}function rs(e){const t=[],{left:r,right:n,top:o,bottom:s}=ns(e);for(const e of le(r,n+1))for(const r of le(o,s+1))t.push({col:e,row:r});return t}function ns(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 os(e,t,r,n){const o="both"===t?n[0]:"columns"===t?n:0,s="both"===t?n[1]:"rows"===t?n:0,i="hasHeader"in e&&e.hasHeader;let a;a=ls(e)&&!i?"rows"!==t:!(as(e)&&!i)||"columns"!==t;const l={...e};return a&&"MOVE"===r&&(l.left+=o,l.top+=s),void 0!==l.right&&(l.right+=o),void 0!==l.bottom&&(l.bottom+=s),l}function ss(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function is(e){return{...e,right:e.left,bottom:e.top}}function as(e){return void 0===e.right}function ls(e){return void 0===e.bottom}function cs(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function us(e){return e.length<2||1===Fo(e).length}function hs(e,t){const r=Xo(e,t);if(!r)return[e];const n=[];switch(r.position){case"bottom":case"top":return n.push({top:e.top,bottom:e.bottom,left:r.start,right:r.stop}),r.start>e.left&&n.push({top:e.top,bottom:e.bottom,left:e.left,right:r.start-1}),(void 0===e.right||r.stop<e.right)&&n.push({top:e.top,bottom:e.bottom,left:r.stop+1,right:e.right}),n;case"left":case"right":return n.push({top:r.start,bottom:r.stop,left:e.left,right:e.right}),r.start>e.top&&n.push({top:e.top,bottom:r.start-1,left:e.left,right:e.right}),(void 0===e.bottom||r.stop<e.bottom)&&n.push({top:r.stop+1,bottom:e.bottom,left:e.left,right:e.right}),n}}const ds=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","DUPLICATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","UNDO","REDO","ADD_MERGE","REMOVE_MERGE","DUPLICATE_SHEET","UPDATE_LOCALE","ADD_PIVOT","UPDATE_PIVOT","INSERT_PIVOT","RENAME_PIVOT","REMOVE_PIVOT","DUPLICATE_PIVOT"]),fs=new Set(["EVALUATE_CELLS","EVALUATE_CHARTS","UPDATE_CELL","UNHIDE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","GROUP_HEADERS","UNGROUP_HEADERS","FOLD_ALL_HEADER_GROUPS","FOLD_HEADER_GROUP","FOLD_HEADER_GROUPS_IN_ZONE","UNFOLD_ALL_HEADER_GROUPS","UNFOLD_HEADER_GROUP","UNFOLD_HEADER_GROUPS_IN_ZONE","UPDATE_TABLE","UPDATE_FILTER","UNDO","REDO"]),gs=new Set(["MOVE_RANGES"]),ms=new Set(["EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CHANGE_CONDITIONAL_FORMAT_PRIORITY"]),ps=new Set(["AUTOFILL_CELL","SET_BORDER","SET_ZONE_BORDERS","SET_BORDERS_ON_TARGET"]),bs=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"]),vs=new Set(["START","ACTIVATE_SHEET","COPY","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","EVALUATE_CELLS","EVALUATE_CHARTS","SET_FORMULA_VISIBILITY","UPDATE_FILTER","UPDATE_CHART","UPDATE_CAROUSEL_ACTIVE_ITEM","UPDATE_PIVOT"]),ys=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 ws(e){return ys.has(e.type)}class Es{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>"Success"!==e)}static get Success(){return Ss}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}const Ss=new Es;var Cs;!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.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"}(Cs||(Cs={}));class Ts{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return"Success"}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(const r of e){let e=r.call(this,t);Array.isArray(e)||(e=[e]);const n=e.filter(e=>"Success"!==e);if(n.length)return n}return"Success"}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class Is extends Ts{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:r,canDispatch:n,uiActions:o,selection:s}){super(t),this.getters=e,this.ui=o,this.selection=s,this.dispatch=r,this.canDispatch=n}drawLayer(e,t){}}function xs(e){return e.isFormula&&e.compiledFormula.tokens.some(e=>"SYMBOL"===e.type&&"SUBTOTAL"===e.value.toUpperCase())}function Rs(e,t){return er(e,(e,t)=>e+t,0,t)}function As(e){return Jt(e,(e,t)=>br(t)?e.add(t?.value):e,new Set).size}const _s=/^-?[a-z0-9]+$/i,Os={description:v("Absolute value of a number."),args:[a("value (number)",v("The number of which to return the absolute value."))],compute:function(e){return Math.abs(kt(e,this.locale))},isExported:!0},Ds={description:v("Inverse cosine of a value, in radians."),args:[a("value (number)",v("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)>1?new S(v("The value (%s) must be between -1 and 1 inclusive.",t)):Math.acos(t)},isExported:!0},Fs={description:v("Inverse hyperbolic cosine of a number."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],compute:function(e){const t=kt(e,this.locale);return t<1?new S(v("The value (%s) must be greater than or equal to 1.",t)):Math.acosh(t)},isExported:!0},Ns={description:v("Inverse cotangent of a value."),args:[a("value (number)",v("The value for which to calculate the inverse cotangent."))],compute:function(e){const t=kt(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Ms={description:v("Inverse hyperbolic cotangent of a value."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)<=1?new S(v("The value (%s) cannot be between -1 and 1 inclusive.",t)):Math.log((t+1)/(t-1))/2},isExported:!0},Vs={description:v("Inverse sine of a value, in radians."),args:[a("value (number)",v("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)>1?new S(v("The value (%s) must be between -1 and 1 inclusive.",t)):Math.asin(t)},isExported:!0},Ls={description:v("Inverse hyperbolic sine of a number."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic sine."))],compute:function(e){return Math.asinh(kt(e,this.locale))},isExported:!0},Ps={description:v("Inverse tangent of a value, in radians."),args:[a("value (number)",v("The value for which to calculate the inverse tangent."))],compute:function(e){return Math.atan(kt(e,this.locale))},isExported:!0},ks={description:v("Angle from the X axis to a point (x,y), in radians."),args:[a("x (number)",v("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),a("y (number)",v("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],compute:function(e,t){const r=kt(e,this.locale),n=kt(t,this.locale);return 0===r&&0===n?new _(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):Math.atan2(n,r)},isExported:!0},Us={description:v("Inverse hyperbolic tangent of a number."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)>=1?new S(v("The value (%s) must be between -1 and 1 exclusive.",t)):Math.atanh(t)},isExported:!0},Hs={description:v("Rounds number up to nearest multiple of factor."),args:[a("value (number)",v("The value to round up to the nearest integer multiple of factor.")),a("factor (number, default=1)",v("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const r=kt(e,this.locale),n=kt(t,this.locale);return n<0&&r>0?new S(v("The factor (%s) must be positive when the value (%s) is positive.",n,r)):{value:n?Math.ceil(r/n)*n:0,format:e?.format}},isExported:!0};function Bs(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 zs={description:v("Rounds number up to nearest multiple of factor."),args:[a("number (number)",v("The value to round up to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),a("mode (number, default=0)",v("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero."))],compute:function(e,t={value:1},r={value:0}){const n=kt(t,this.locale);return{value:Bs(kt(e,this.locale),n,kt(r,this.locale)),format:e?.format}},isExported:!0},$s={description:v("Rounds number up to nearest multiple of factor."),args:[a("number (number)",v("The value to round up to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const r=kt(t,this.locale);return{value:Bs(kt(e,this.locale),r),format:e?.format}},isExported:!0},Gs={description:v("Cosine of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the cosine of, in radians."))],compute:function(e){return Math.cos(kt(e,this.locale))},isExported:!0},Ws={description:v("Hyperbolic cosine of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic cosine of."))],compute:function(e){return Math.cosh(kt(e,this.locale))},isExported:!0},qs={description:v("Cotangent of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the cotangent of, in radians."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new _(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tan(t)},isExported:!0},Zs={description:v("Hyperbolic cotangent of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic cotangent of."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new _(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tanh(t)},isExported:!0},Ys={description:v("Number of empty values."),args:[a("value1 (any, range)",v("The first value or range in which to count the number of blanks.")),a("value2 (any, range, repeating)",v("Additional values or ranges in which to count the number of blanks."))],compute:function(...e){return Jt(e,(e,t)=>void 0===t||null===t.value||""===t.value?e+1:e,0)},isExported:!0},js={description:v("A conditional count across a range."),args:[a("range (range)",v("The range that is tested against criterion.")),a("criterion (string)",v("The pattern or test to apply to range."))],compute:function(...e){let t=0;return ur(e,(e,r)=>{t+=1},this.locale),t},isExported:!0},Xs={description:v("Count values depending on multiple criteria."),args:[a("criteria_range1 (range)",v("The range to check against criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1.")),a("criteria_range2 (any, range, repeating)",v("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),a("criterion2 (string, repeating)",v("Additional criteria to check."))],compute:function(...e){let t=0;return ur(e,(e,r)=>{t+=1},this.locale),t},isExported:!0},Ks={description:v("Counts number of unique values in a range."),args:[a("value1 (any, range)",v("The first value or range to consider for uniqueness.")),a("value2 (any, range, repeating)",v("Additional values or ranges to consider for uniqueness."))],compute:function(...e){return As(e)}},Qs={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_range1 (range)",v("The range of cells over which to evaluate criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),a("criteria_range2 (any, range, repeating)",v("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),a("criterion2 (string, repeating)",v("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){const r=new Set;return ur(t,(t,n)=>{const o=e[t]?.[n];br(o)&&r.add(o.value)},this.locale),r.size}},Js={description:v("Cosecant of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the cosecant of, in radians."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new _(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sin(t)},isExported:!0},ei={description:v("Hyperbolic cosecant of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic cosecant of."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new _(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sinh(t)},isExported:!0},ti={description:v("Converts from another base to decimal."),args:[a("value (string)",v("The number to convert.")),a("base (number)",v("The base to convert the value from."))],compute:function(e,t){let r=kt(t,this.locale);if(r=Math.floor(r),2>r||r>36)return new S(v("The base (%s) must be between 2 and 36 inclusive.",r));const n=$t(e);if(""===n)return 0;if(!_s.test(n))return new S(v("The value (%s) must be a valid base %s representation.",n,r));const o=parseInt(n,r);return isNaN(o)?new S(v("The value (%s) must be a valid base %s representation.",n,r)):o},isExported:!0},ri={description:v("Converts an angle value in radians to degrees."),args:[a("angle (number)",v("The angle to convert from radians to degrees."))],compute:function(e){return 180*kt(e,this.locale)/Math.PI},isExported:!0},ni={description:v("Euler's number, e (~2.718) raised to a power."),args:[a("value (number)",v("The exponent to raise e."))],compute:function(e){return Math.exp(kt(e,this.locale))},isExported:!0},oi={description:v("Rounds number down to nearest multiple of factor."),args:[a("value (number)",v("The value to round down to the nearest integer multiple of factor.")),a("factor (number, default=1)",v("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const r=kt(e,this.locale),n=kt(t,this.locale);return n<0&&r>0?new S(v("The factor (%s) must be positive when the value (%s) is positive.",n,r)):{value:n?Math.floor(r/n)*n:0,format:e?.format}},isExported:!0};function si(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 ii={description:v("Rounds number down to nearest multiple of factor."),args:[a("number (number)",v("The value to round down to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),a("mode (number, default=0)",v("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero."))],compute:function(e,t={value:1},r={value:0}){const n=kt(t,this.locale);return{value:si(kt(e,this.locale),n,kt(r,this.locale)),format:e?.format}},isExported:!0},ai={description:v("Rounds number down to nearest multiple of factor."),args:[a("number (number)",v("The value to round down to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const r=kt(t,this.locale);return{value:si(kt(e,this.locale),r),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=Ht(e,this.locale);return!(1&Math.floor(Math.abs(t)))},isExported:!0},ci={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:Bs(kt(e,this.locale),kt(t,this.locale)),format:e?.format}},isExported:!0},ui={description:v("Whether the provided value is even."),args:[a("value (number)",v("The value to be verified as even."))],compute:function(e){const t=Ht(e,this.locale);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},hi={description:v("The logarithm of a number, base e (euler's number)."),args:[a("value (number)",v("The value for which to calculate the logarithm, base e."))],compute:function(e){const t=kt(e,this.locale);return t<=0?new S(v("The value (%s) must be strictly positive.",t)):Math.log(t)},isExported:!0},di={description:v("The logarithm of a number, for a given base."),args:[a("value (number)",v("The value for which to calculate the logarithm.")),a("base (number, default=10)",v("The base of the logarithm."))],compute:function(e,t={value:10}){const r=kt(e,this.locale),n=kt(t,this.locale);return r<=0?new S(v("The value (%s) must be strictly positive.",r)):n<=0?new S(v("The base (%s) must be strictly positive.",n)):1===n?new S(v("The base must be different from 1.")):Math.log10(r)/Math.log10(n)},isExported:!0};function fi(e,t){xr(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 gi={description:v("Modulo (remainder) operator."),args:[a("dividend (number)",v("The number to be divided to find the remainder.")),a("divisor (number)",v("The number to divide by."))],compute:function(e,t){const r=kt(t,this.locale);return{value:fi(kt(e,this.locale),r),format:e?.format}},isExported:!0},mi={description:v("Returns a n x n unit matrix, where n is the input dimension."),args:[a("dimension (number)",v("An integer specifying the dimension size of the unit matrix. It must be positive."))],compute:function(e){const t=Bt(e,this.locale);return t<1?new S(v("The argument dimension must be positive")):Dr(t)},isExported:!0},pi={description:v("Rounds a number up to the nearest odd integer."),args:[a("value (number)",v("The value to round to the next greatest odd number."))],compute:function(e){const t=kt(e,this.locale);let r=Math.ceil(Math.abs(t));return r=1&r?r:r+1,{value:t<0?-r:r,format:e?.format}},isExported:!0},bi={description:v("The number pi."),args:[],compute:function(){return Math.PI},isExported:!0},vi={description:v("A number raised to a power."),args:[a("base (number)",v("The number to raise to the exponent power.")),a("exponent (number)",v("The exponent to raise base to."))],compute:function(e,t){const r=kt(e,this.locale),n=kt(t,this.locale);return r<0&&!Number.isInteger(n)?new S(v("The exponent (%s) must be an integer when the base is negative.",n)):{value:Math.pow(r,n),format:e?.format}},isExported:!0},yi={description:v("Result of multiplying a series of numbers together."),args:[a("factor1 (number, range<number>)",v("The first number or range to calculate for the product.")),a("factor2 (number, range<number>, repeating)",v("More numbers or ranges to calculate for the product."))],compute:function(...e){let t=0,r=1;for(const n of e)if(O(n))for(const e of n)for(const n of e){const e=n.value;if("number"==typeof e&&(r*=e,t+=1),Vt(e))return n}else void 0!==n&&null!==n.value&&(r*=Ht(n,this.locale),t+=1);return{value:0===t?0:r,format:Mt(e[0])}},isExported:!0},wi={description:v("A random number between 0 inclusive and 1 exclusive."),args:[],compute:function(){return Math.random()},isExported:!0},Ei={description:v("Returns a grid of random numbers between 0 inclusive and 1 exclusive."),args:[a("rows (number, default=1)",v("The number of rows to be returned.")),a("columns (number, default=1)",v("The number of columns to be returned.")),a("min (number, default=0)",v("The minimum number you would like returned.")),a("max (number, default=1)",v("The maximum number you would like returned.")),a("whole_number (boolean, default=FALSE)",v("Return a whole number or a decimal value."),[{value:!1,label:v("Decimal (default)")},{value:!0,label:v("Integer")}])],compute:function(e={value:1},t={value:1},r={value:0},n={value:1},o={value:!1}){const s=Bt(t,this.locale),i=Bt(e,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=qt(o);if(s<1)return new S(v("The number of columns (%s) must be positive.",s));if(i<1)return new S(v("The number of rows (%s) must be positive.",i));if(a>l)return new S(v("The maximum (%s) must be greater than or equal to the minimum (%s).",l,a));if(c&&(!Number.isInteger(a)||!Number.isInteger(l)))return new S(v("The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.",l.toString(),a.toString()));const u=Array(s);for(let e=0;e<s;e++){u[e]=Array(i);for(let t=0;t<i;t++)u[e][t]=c?Math.floor(Math.random()*(l-a+1)+a):a+Math.random()*(l-a)}return u},isExported:!0},Si={description:v("Random integer between two values, inclusive."),args:[a("low (number)",v("The low end of the random range.")),a("high (number)",v("The high end of the random range."))],compute:function(e,t){let r=kt(e,this.locale);Number.isInteger(r)||(r=Math.ceil(r));let n=kt(t,this.locale);return Number.isInteger(n)||(n=Math.floor(n)),r>n?new S(v("The high (%s) must be greater than or equal to the low (%s).",n,r)):{value:r+Math.ceil((n-r+1)*Math.random())-1,format:e?.format}},isExported:!0},Ci={description:v("Rounds a number according to standard rules."),args:[a("value (number)",v("The value to round to places number of places.")),a("places (number, default=0)",v("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const r=kt(e,this.locale);let n=kt(t,this.locale);const o=Math.abs(r);let s;return 0===n?s=Math.round(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.round(o*Math.pow(10,n))/Math.pow(10,n)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},Ti={description:v("Rounds down a number."),args:[a("value (number)",v("The value to round to places number of places, always rounding down.")),a("places (number, default=0)",v("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const r=kt(e,this.locale);let n=kt(t,this.locale);const o=Math.abs(r);let s;return 0===n?s=Math.floor(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.floor(o*Math.pow(10,n))/Math.pow(10,n)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},Ii={description:v("Rounds up a number."),args:[a("value (number)",v("The value to round to places number of places, always rounding up.")),a("places (number, default=0)",v("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const r=kt(e,this.locale);let n=kt(t,this.locale);const o=Math.abs(r);let s;return 0===n?s=Math.ceil(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.ceil(o*Math.pow(10,n))/Math.pow(10,n)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},xi={description:v("Secant of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the secant of, in radians."))],compute:function(e){return 1/Math.cos(kt(e,this.locale))},isExported:!0},Ri={description:v("Hyperbolic secant of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic secant of."))],compute:function(e){return 1/Math.cosh(kt(e,this.locale))},isExported:!0},Ai={description:v("Returns a sequence of numbers."),args:[a("rows (number)",v("The number of rows to return")),a("columns (number, optional, default=1)",v("The number of columns to return")),a("start (number, optional, default=1)",v("The first number in the sequence")),a("step (number, optional, default=1)",v("The amount to increment each value in the sequence"))],compute:function(e,t={value:1},r={value:1},n={value:1}){const o=kt(r,this.locale),s=kt(n,this.locale),i=Bt(e,this.locale),a=Bt(t,this.locale);return a<1?new S(v("The number of columns (%s) must be positive.",a)):i<1?new S(v("The number of rows (%s) must be positive.",i)):rr(a,i,(e,t)=>({value:o+t*a*s+e*s}))},isExported:!0},_i={description:v("Sine of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the sine of, in radians."))],compute:function(e){return Math.sin(kt(e,this.locale))},isExported:!0},Oi={description:v("Hyperbolic sine of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic sine of."))],compute:function(e){return Math.sinh(kt(e,this.locale))},isExported:!0},Di={description:v("Positive square root of a positive number."),args:[a("value (number)",v("The number for which to calculate the positive square root."))],compute:function(e){const t=kt(e,this.locale);return t<0?new S(v("The value (%s) must be positive or null.",t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},Fi={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP"},Ni=Object.entries(Fi).map(([e,t])=>({value:parseInt(e),label:v("%s (include manually-hidden rows)",t)})),Mi=Object.entries(Fi).map(([e,t])=>({value:parseInt(e)+100,label:v("%s (exclude manually-hidden rows)",t)})),Vi={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."),[...Ni,...Mi]),a("ref1 (meta, range<meta>)",v("The range or reference for which you want the subtotal.")),a("ref2 (meta, range<meta>, repeating)",v("Additional ranges or references for which you want the subtotal."))],compute:function(e,...t){let r=Bt(e,this.locale),n=!0;if(r>100&&(r-=100,n=!1),r<1||r>11)return new S(v("The function code (%s) must be between 1 to 11 or 101 to 111.",r));const o=[];for(const e of t){const t=e[0][0],r=go(t.value).sheetName,s=r?this.getters.getSheetIdByName(r):this.__originSheetId;if(!s)continue;const{top:i,left:a}=Bo(t.value),l=a+e.length-1,c=i+e[0].length-1;for(let e=i;e<=c;e++)if(!this.getters.isRowFiltered(s,e)&&(n||!this.getters.isRowHiddenByUser(s,e)))for(let t=a;t<=l;t++){const r=this.getters.getCell({sheetId:s,col:t,row:e});r&&xs(r)||o.push(this.getters.getEvaluatedCell({sheetId:s,col:t,row:e}))}}return this[Fi[r]].apply(this,[[o]])},isExported:!0},Li={description:v("Sum of a series of numbers and/or cells."),args:[a("value1 (number, range<number>)",v("The first number or range to add together.")),a("value2 (number, range<number>, repeating)",v("Additional numbers or ranges to add to value1."))],compute:function(...e){const t=e[0];return{value:Rs(e,this.locale),format:Mt(t)}},isExported:!0},Pi={description:v("A conditional sum across a range."),args:[a("criteria_range (range)",v("The range which is tested against criterion.")),a("criterion (string)",v("The pattern or test to apply to range.")),a("sum_range (range, default=criteria_range)",v("The range to be summed, if different from range."))],compute:function(e,t,r){void 0===r&&(r=e);let n=0;return ur([e,t],(e,t)=>{const o=r[e]?.[t]?.value;"number"==typeof o&&(n+=o)},this.locale),n},isExported:!0},ki={description:v("Sums a range depending on multiple criteria."),args:[a("sum_range (range)",v("The range to sum.")),a("criteria_range1 (range)",v("The range to check against criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1.")),a("criteria_range2 (any, range, repeating)",v("Additional ranges to check.")),a("criterion2 (string, repeating)",v("Additional criteria to check."))],compute:function(e,...t){let r=0;return ur(t,(t,n)=>{const o=e[t]?.[n]?.value;"number"==typeof o&&(r+=o)},this.locale),r},isExported:!0},Ui={description:v("Tangent of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the tangent of, in radians."))],compute:function(e){return Math.tan(kt(e,this.locale))},isExported:!0},Hi={description:v("Hyperbolic tangent of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic tangent of."))],compute:function(e){return Math.tanh(kt(e,this.locale))},isExported:!0};function Bi(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 zi={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:Bi(kt(e,this.locale),kt(t,this.locale)),format:e?.format}},isExported:!0},$i={description:v("Rounds a number down to the nearest integer that is less than or equal to it."),args:[a("value (number)",v("The number to round down to the nearest integer."))],compute:function(e){return Math.floor(kt(e,this.locale))},isExported:!0};var Gi=Object.freeze({__proto__:null,ABS:Os,ACOS:Ds,ACOSH:Fs,ACOT:Ns,ACOTH:Ms,ASIN:Vs,ASINH:Ls,ATAN:Ps,ATAN2:ks,ATANH:Us,CEILING:Hs,CEILING_MATH:zs,CEILING_PRECISE:$s,COS:Gs,COSH:Ws,COT:qs,COTH:Zs,COUNTBLANK:Ys,COUNTIF:js,COUNTIFS:Xs,COUNTUNIQUE:Ks,COUNTUNIQUEIFS:Qs,CSC:Js,CSCH:ei,DECIMAL:ti,DEGREES:ri,EXP:ni,FLOOR:oi,FLOOR_MATH:ii,FLOOR_PRECISE:ai,INT:$i,ISEVEN:li,ISODD:ui,ISO_CEILING:ci,LN:hi,LOG:di,MOD:gi,MUNIT:mi,ODD:pi,PI:bi,POWER:vi,PRODUCT:yi,RAND:wi,RANDARRAY:Ei,RANDBETWEEN:Si,ROUND:Ci,ROUNDDOWN:Ti,ROUNDUP:Ii,SEC:xi,SECH:Ri,SEQUENCE:Ai,SIN:_i,SINH:Oi,SQRT:Di,SUBTOTAL:Vi,SUM:Li,SUMIF:Pi,SUMIFS:ki,TAN:Ui,TANH:Hi,TRUNC:zi});function Wi(...e){const t=e[0].length;e.forEach((e,r)=>Ir(e.length===t,v("[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).",r.toString(),t.toString(),e.length.toString())))}function qi(e,t){let r=0;const n=er(e,(e,t)=>(r+=1,e+t),0,t);return xr(r),n/r}function Zi(e){return Jt(e,(e,t)=>void 0!==t&&null!==t.value?e+1:e,0)}function Yi(e,t){let r={value:-1/0};return Kt(e,e=>{e.value>=r.value&&(r=e)},t),r.value===-1/0?{value:0}:r}function ji(e,t){let r={value:1/0};return Kt(e,e=>{e.value<=r.value&&(r=e)},t),r.value===1/0?{value:0}:r}function Xi(e,t,r){const n=e[0].length?e:[le(1,t.flat().length+1)],o=n.length;let s=r[0].length?r:n;return s=s.length===o?or(s):s,{_X:n,_newX:s}}function Ki(e,t,r=!0,n=!1){const o=t.flat(),s=o.length;let{_X:i}=Xi(e,t,[[]]);i=i.length===s?or(i):i.slice(),Wi(i[0],o);const a=i.length,l=s-a-(r?1:0),c=[o],u=or(i.reverse()),h=[];for(let e=0;e<a;e++)if(h.push(0),r){for(const t of i[e])h[e]+=t;h[e]/=s}let d=0;if(r){for(const e of o)d+=e;d/=s}const f=u.map(e=>e.map((e,t)=>e-h[t]));r&&u.forEach(e=>e.push(1));const g=Ji(u,c);if(r||g.push([0]),!n)return g;const m=Mr(f,or(f)),{inverted:p}=Fr(m);if(void 0===p)throw new S(v("Matrix is not invertible"));let b=0,y=0;for(let e=0;e<s;e++){const t=o[e]-d;let r=0;for(let t=0;t<a;t++){r+=f[e][t]*g[t][0]}const n=t-r;b+=n*n,y+=r*r}const 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=Mr(p,[h]),t=Mr(or([h]),e);T.push(w*Math.sqrt(t[0][0]+1/o.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 Qi(e,t,r,n){Wi(t,e),Ir(r>=1,v("Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible."));const o=[e],s=t.map(e=>le(0,r).map(t=>Math.pow(e,r-t)));n&&s.forEach(e=>e.push(1));const i=Ji(s,o);return n||i.push([0]),i}function Ji(e,t){const r=Mr(e,or(e)),{inverted:n}=Fr(r);if(void 0===n)throw new S(v("Matrix is not invertible"));const o=Mr(e,t);return or(Mr(n,o))}function ea(e){return e.map(e=>e.map(e=>Math.log(e)))}function ta(e,t,r,n){const{_X:o,_newX:s}=Xi(t,e,r),i=Ki(o,e,n,!1),a=i.length-1,l=s.map(e=>{let t=0;for(let r=0;r<a;r++)t+=i[r][0]*e[a-r-1];return t+=i[a][0],[t]});return l.length===r.length?l:or(l)}const ra=[{value:!0,label:v("b is calculated normally")},{value:!1,label:v("b is forced to 1")}],na=[{value:!1,label:v("do not return additional regression statistics")},{value:!0,label:v("return additional regression statistics")}],oa=[{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)")}],sa=[{value:!0,label:v("Compute intercept")},{value:!1,label:v("Force intercept to 0")}],ia=[{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 aa(e,t){const r=[],n=[];let o=0,s=0;Xt([e],e=>{r.push(e),o+=1}),Xt([t],e=>{n.push(e),s+=1}),Ir(o===s,v("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",o,s));const i=[],a=[];for(let e=0;e<o;e++){const t=r[e]?.value,o=n[e]?.value;"number"==typeof t&&"number"==typeof o&&(a.push(t),i.push(o))}return{flatDataX:i,flatDataY:a}}function la(e,t,r){const{flatDataX:n,flatDataY:o}=aa(e,t),s=o.length;xr(s),r&&xr(s-1);let i=0,a=0;for(let e=0;e<s;e++)i+=o[e],a+=n[e];const l=i/s,c=a/s;let u=0;for(let e=0;e<s;e++)u+=(o[e]-l)*(n[e]-c);return u/(s-(r?1:0))}function ca(e,t,r,n){let o=0;const s=r?tr:er,i=s(e,(e,t)=>(o+=1,e+t),0,n);xr(o),t&&xr(o-1);const a=i/o;return s(e,(e,t)=>e+Math.pow(t-a,2),0,n)/(o-(t?1:0))}function ua(e,t,r,n){const o=kt(t,n);Ir(r?0<=o&&o<=1:0<o&&o<1,v("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));const s=[];let i,a=0;return Xt(e,e=>{const t=e?.value;"number"==typeof t&&(i=hr(s,e,"nextSmaller","asc",s.length,(e,t)=>e[t]),s.splice(i+1,0,t),a++)}),Ir(0!==a,vr),r||Ir(1/(a+1)<=o&&o<=a/(a+1),v("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),Ft(s,o,r)}const ha={description:v("Average magnitude of deviations from mean."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){let t=0;const r=er(e,(e,r)=>(t+=1,e+r),0,this.locale);if(0===t)return new _(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const n=r/t;return er(e,(e,t)=>e+Math.abs(n-t),0,this.locale)/t},isExported:!0},da={description:v("Numerical average value in a dataset, ignoring text."),args:[a("value1 (number, range<number>)",v("The first value or range to consider when calculating the average value.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to consider when calculating the average value."))],compute:function(...e){return{value:qi(e,this.locale),format:Mt(e[0])}},isExported:!0},fa=v("[[FUNCTION_NAME]] has mismatched range sizes."),ga=v("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),ma={description:v("Weighted average."),args:[a("values (number, range<number>)",v("Values to average.")),a("weights (number, range<number>)",v("Weights for each corresponding value.")),a("additional_values (number, range<number>, repeating)",v("Additional values to average.")),a("additional_weights (number, range<number>, repeating)",v("Additional weights."))],compute:function(...e){let t=0,r=0;for(let n=0;n<e.length-1;n+=2){const o=e[n],s=e[n+1];if(!Ar(o,s))return new S(fa);if(O(o))for(let e=0;e<o.length;e++)for(let n=0;n<o[0].length;n++){const i=o[e][n].value,a=O(s)?s?.[e][n].value:kt(s,this.locale),l="number"==typeof i,c="number"==typeof a;if(l&&c){if(a<0)return new S(ga);t+=i*a,r+=a}else if(l!==c)return new S(v("[[FUNCTION_NAME]] expects number values."))}else{const e=kt(o,this.locale),n=O(s)?s?.[0][0].value:kt(s,this.locale);if("number"==typeof n){if(n<0)return new S(ga);t+=e*n,r+=n}}}return 0===r?new _(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:t/r,format:Mt(e[0])}}},pa={description:v("Numerical average value in a dataset."),args:[a("value1 (number, range<number>)",v("The first value or range to consider when calculating the average value.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to consider when calculating the average value."))],compute:function(...e){let t=0;const r=tr(e,(e,r)=>(t+=1,e+r),0,this.locale);return 0===t?new _(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:r/t,format:Mt(e[0])}},isExported:!0},ba={description:v("Average of values depending on criteria."),args:[a("criteria_range (number, range<number>)",v("The range to check against criterion.")),a("criterion (string)",v("The pattern or test to apply to criteria_range.")),a("average_range (number, range<number>, default=criteria_range)",v("The range to average. If not included, criteria_range is used for the average instead."))],compute:function(e,t,r){const n=mr(void 0===r?e:r);let o=0,s=0;return ur([e,t],(e,t)=>{const r=n[e]?.[t]?.value;"number"==typeof r&&(o+=1,s+=r)},this.locale),0===o?new _(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):s/o},isExported:!0},va={description:v("Average of values depending on multiple criteria."),args:[a("average_range (range)",v("The range to average.")),a("criteria_range1 (range)",v("The range to check against criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1.")),a("criteria_range2 (any, range, repeating)",v("Additional criteria_range and criterion to check.")),a("criterion2 (string, repeating)",v("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){const r=mr(e);let n=0,o=0;return ur(t,(e,t)=>{const s=r[e]?.[t]?.value;"number"==typeof s&&(n+=1,o+=s)},this.locale),0===n?new _(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):o/n},isExported:!0},ya={description:v("The number of numeric values in dataset."),args:[a("value1 (number, any, range<number>)",v("The first value or range to consider when counting.")),a("value2 (number, any, range<number>, repeating)",v("Additional values or ranges to consider when counting."))],compute:function(...e){return function(e,t){let r=0;for(const n of e)if(O(n))for(const e of n)for(const t of e)"number"==typeof t.value&&(r+=1);else{const e=n?.value;Vt(e)||"string"==typeof e&&!_t(e,t)&&!gt(e,t)||(r+=1)}return r}(e,this.locale)},isExported:!0},wa={description:v("The number of values in a dataset."),args:[a("value1 (any, range)",v("The first value or range to consider when counting.")),a("value2 (any, range, repeating)",v("Additional values or ranges to consider when counting."))],compute:function(...e){return Zi(e)},isExported:!0},Ea={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 la(e,t,!1)},isExported:!0},Sa={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 la(e,t,!1)},isExported:!0},Ca={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 la(e,t,!0)},isExported:!0},Ta={description:v("Calculates the expected y-value for a specified x based on a linear regression of a dataset."),args:[a("x (number, range<number>)",v("The value(s) on the x-axis to forecast.")),a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t,r){const{flatDataX:n,flatDataY:o}=aa(t,r);return 0===n.length||0===o.length?new x(vr):ta([o],[n],nr(mr(e),e=>kt(e,this.locale)),!0)},isExported:!0},Ia={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."),ra)],compute:function(e,t=[[]],r=[[]],n={value:!0}){return 0===e.length||0===e[0].length?new S(yr("known_data_y")):ta(ea(Ut(e,"known_data_y")),Ut(t,"known_data_x"),Ut(r,"new_data_y"),qt(n)).map(e=>e.map(e=>Math.exp(e)))}},xa={description:v("Compute the intercept of the linear regression."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=aa(e,t);if(0===r.length||0===n.length)return new x(vr);const[[],[o]]=Ki([r],[n]);return o},isExported:!0},Ra={description:v("Nth largest element from a data set."),args:[a("data (any, range)",v("Array or range containing the dataset to consider.")),a("n (number)",v("The rank from largest to smallest of the element to return."))],compute:function(e,t){const r=Math.trunc(kt(t?.value,this.locale)),n=[];let o,s=0;Xt([e],e=>{"number"==typeof e?.value&&(o=hr(n,e,"nextSmaller","asc",n.length,(e,t)=>e[t].value),n.splice(o+1,0,e),s++,s>r&&(n.shift(),s--))});const i=n.shift();return void 0===i?new S(vr):s<r?new S(v("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",r)):i},isExported:!0},Aa={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"),ra),a("verbose (boolean, default=FALSE)",v("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),na)],compute:function(e,t=[[]],r={value:!0},n={value:!1}){return 0===e.length||0===e[0].length?new S(yr("data_y")):Ki(Ut(t,"data_x"),Ut(e,"data_y"),qt(r),qt(n))},isExported:!0},_a={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"),ra),a("verbose (boolean, default=FALSE)",v("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),na)],compute:function(e,t=[[]],r={value:!0},n={value:!1}){if(0===e.length||0===e[0].length)return new S(yr("data_y"));const o=Ki(Ut(t,"data_x"),ea(Ut(e,"data_y")),qt(r),qt(n));for(let e=0;e<o.length;e++)o[e][0]=Math.exp(o[e][0]);return o},isExported:!0},Oa={description:v("Compute the Matthews correlation coefficient of a dataset."),args:[a("data_x (range)",v("The range representing the array or matrix of observed data.")),a("data_y (range)",v("The range representing the array or matrix of predicted data."))],compute:function(e,t){const r=e.flat(),n=t.flat();if(Wi(r,n),0===r.length||0===n.length)return new x(vr);const o=r.length;let s=0,i=0,a=0,l=0;for(let e=0;e<o;++e){const t=qt(r[e]);t===qt(n[e])?t?i++:s++:t?l++:a++}return(i*s-a*l)/Math.sqrt((i+a)*(i+l)*(s+a)*(s+l))},isExported:!1},Da={description:v("Maximum value in a numeric dataset."),args:[a("value1 (number, range<number>)",v("The first value or range to consider when calculating the maximum value.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to consider when calculating the maximum value."))],compute:function(...e){return Yi(e,this.locale)},isExported:!0},Fa={description:v("Maximum numeric value in a dataset."),args:[a("value1 (any, range)",v("The first value or range to consider when calculating the maximum value.")),a("value2 (any, range, repeating)",v("Additional values or ranges to consider when calculating the maximum value."))],compute:function(...e){const t=tr(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:Mt(e[0])}},isExported:!0},Na={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_range1 (range)",v("The range of cells over which to evaluate criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),a("criteria_range2 (any, range, repeating)",v("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),a("criterion2 (string, repeating)",v("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){let r=-1/0;return ur(t,(t,n)=>{const o=e[t]?.[n]?.value;"number"==typeof o&&(r=r<o?o:r)},this.locale),r===-1/0?0:r},isExported:!0},Ma={description:v("Median value in a numeric dataset."),args:[a("value1 (any, range)",v("The first value or range to consider when calculating the median value.")),a("value2 (any, range, repeating)",v("Additional values or ranges to consider when calculating the median value."))],compute:function(...e){const t=[];return Kt(e,e=>{t.push(e)},this.locale),{value:ua(t,{value:.5},!0,this.locale),format:Mt(t[0])}},isExported:!0},Va={description:v("Minimum value in a numeric dataset."),args:[a("value1 (number, range<number>)",v("The first value or range to consider when calculating the minimum value.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to consider when calculating the minimum value."))],compute:function(...e){return ji(e,this.locale)},isExported:!0},La={description:v("Minimum numeric value in a dataset."),args:[a("value1 (number, range<number>)",v("The first value or range to consider when calculating the minimum value.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to consider when calculating the minimum value."))],compute:function(...e){const t=tr(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:Mt(e[0])}},isExported:!0},Pa={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_range1 (range)",v("The range of cells over which to evaluate criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),a("criteria_range2 (any, range, repeating)",v("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),a("criterion2 (string, repeating)",v("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){let r=1/0;return ur(t,(t,n)=>{const o=e[t]?.[n]?.value;"number"==typeof o&&(r=r>o?o:r)},this.locale),r===1/0?0:r},isExported:!0};function ka(e,t){const{flatDataX:r,flatDataY:n}=aa(e,t);if(0===r.length||0===n.length)return new x(vr);const o=r.length;let s=0,i=0,a=0,l=0,c=0;for(let e=0;e<o;e++){const t=r[e],o=n[e];s+=t,i+=o,a+=t*o,l+=t*t,c+=o*o}return(o*a-s*i)/Math.sqrt((o*l-s*s)*(o*c-i*i))}const Ua={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 ka(e,t)},isExported:!0},Ha=Ua,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 $a.compute.bind(this)(e,t)},isExported:!0},za={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:ua([e],t,!1,this.locale),format:Mt(e)}},isExported:!0},$a={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:ua([e],t,!0,this.locale),format:Mt(e)}},isExported:!0},Ga={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."),oa),a("intercept (boolean, default=TRUE)",v("A flag specifying whether to compute the intercept or not."),sa)],compute:function(e,t,r,n={value:!0}){const{flatDataX:o,flatDataY:s}=aa(e,t);return 0===o.length||0===s.length?new x(vr):Qi(s,o,kt(r,this.locale),qt(n))},isExported:!1},Wa={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."),oa),a("intercept (boolean, default=TRUE)",v("A flag specifying whether to compute the intercept or not."),sa)],compute:function(e,t,r,n,o={value:!0}){const s=kt(n,this.locale),{flatDataX:i,flatDataY:a}=aa(t,r);if(0===i.length||0===a.length)return new x(vr);const l=Qi(a,i,s,qt(o)).flat();return nr(mr(e),e=>function(e,t,r){return e.reduce((e,n,o)=>e+n*Math.pow(t,r-o),0)}(l,kt(e,this.locale),s))},isExported:!1},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."),ia)],compute:function(e,t){return Ya.compute.bind(this)(e,t)},isExported:!0},Za={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:ua([e],{value:.25*Math.trunc(kt(t,this.locale))},!1,this.locale),format:Mt(e)}},isExported:!0},Ya={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."),ia)],compute:function(e,t){return{value:ua([e],{value:.25*Math.trunc(kt(t,this.locale))},!0,this.locale),format:Mt(e)}},isExported:!0},ja={description:v("Returns the rank of a specified value in a dataset."),args:[a("value (number)",v("The value whose rank will be determined.")),a("data (range)",v("The range containing the dataset to consider.")),a("is_ascending (boolean, default=FALSE)",v("Whether to consider the values in data in descending or ascending order."),[{value:!1,label:v("Descending")},{value:!0,label:v("Ascending")}])],compute:function(e,t,r={value:!1}){const n=qt(r),o=kt(e,this.locale);let s=1,i=!1;for(const e of t)for(const t of e){if("number"!=typeof t.value)continue;const e=kt(t,this.locale);e===o?i=!0:e>o!==n&&s++}return i?s:new x(v("Value not found in the given data."))},isExported:!0},Xa={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=ka(e,t);if(r instanceof Error)throw r;return Math.pow(r,2)},isExported:!0},Ka={description:v("Compute the slope of the linear regression."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=aa(e,t);if(0===r.length||0===n.length)return new x(vr);const[[o]]=Ki([r],[n]);return o},isExported:!0},Qa={description:v("Nth smallest element in a data set."),args:[a("data (any, range)",v("The array or range containing the dataset to consider.")),a("n (number)",v("The rank from smallest to largest of the element to return."))],compute:function(e,t){const r=Math.trunc(kt(t?.value,this.locale)),n=[];let o,s=0;Xt([e],e=>{"number"==typeof e?.value&&(o=hr(n,e,"nextSmaller","asc",n.length,(e,t)=>e[t].value),n.splice(o+1,0,e),s++,s>r&&(n.pop(),s--))});const i=n.pop();return void 0===i?new S(vr):s<r?new S(v("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",r)):i},isExported:!0},Ja={description:v("Compute the Spearman rank correlation coefficient of a dataset."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=aa(t,e);if(0===r.length||0===n.length)return new x(vr);const o=r.length,s=r.map((e,t)=>[e,n[t]]);s.sort((e,t)=>e[0]-t[0]);for(let e=0;e<o;++e)s[e][0]=e;s.sort((e,t)=>e[1]-t[1]);let i=0;for(let e=0;e<o;++e)i+=(s[e][0]-e)**2;return 1-6*i/(o**3-o)},isExported:!1},el={description:v("Standard deviation."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(ll.compute.bind(this)(...e))},isExported:!0},tl={description:v("Standard deviation of entire population."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(cl.compute.bind(this)(...e))},isExported:!0},rl={description:v("Standard deviation."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(ul.compute.bind(this)(...e))},isExported:!0},nl={description:v("Standard deviation of sample (text as 0)."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(hl.compute.bind(this)(...e))},isExported:!0},ol={description:v("Standard deviation of entire population."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(dl.compute.bind(this)(...e))},isExported:!0},sl={description:v("Standard deviation of entire population (text as 0)."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(fl.compute.bind(this)(...e))},isExported:!0},il={description:v("Calculates the standard error of the predicted y-value for each x in the regression of a dataset."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=aa(e,t);if(0===r.length||0===n.length)return new x(vr);return Ki([r],[n],!0,!0)[1][2]},isExported:!0},al={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."),ra)],compute:function(e,t=[[]],r=[[]],n={value:!0}){return 0===e.length||0===e[0].length?new S(yr("known_data_y")):ta(Ut(e,"known_data_y"),Ut(t,"known_data_x"),Ut(r,"new_data_y"),qt(n))}},ll={description:v("Variance."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return ca(e,!0,!1,this.locale)},isExported:!0},cl={description:v("Variance of entire population."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return ca(e,!1,!1,this.locale)},isExported:!0},ul={description:v("Variance."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return ca(e,!0,!1,this.locale)},isExported:!0},hl={description:v("Variance of sample (text as 0)."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return ca(e,!0,!0,this.locale)},isExported:!0},dl={description:v("Variance of entire population."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return ca(e,!1,!1,this.locale)},isExported:!0},fl={description:v("Variance of entire population (text as 0)."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return ca(e,!1,!0,this.locale)},isExported:!0};var gl=Object.freeze({__proto__:null,AVEDEV:ha,AVERAGE:da,AVERAGEA:pa,AVERAGEIF:ba,AVERAGEIFS:va,AVERAGE_WEIGHTED:ma,CORREL:Ha,COUNT:ya,COUNTA:wa,COVAR:Ea,COVARIANCE_P:Sa,COVARIANCE_S:Ca,FORECAST:Ta,GROWTH:Ia,INTERCEPT:xa,LARGE:Ra,LINEST:Aa,LOGEST:_a,MATTHEWS:Oa,MAX:Da,MAXA:Fa,MAXIFS:Na,MEDIAN:Ma,MIN:Va,MINA:La,MINIFS:Pa,PEARSON:Ua,PERCENTILE:Ba,PERCENTILE_EXC:za,PERCENTILE_INC:$a,POLYFIT_COEFFS:Ga,POLYFIT_FORECAST:Wa,QUARTILE:qa,QUARTILE_EXC:Za,QUARTILE_INC:Ya,RANK:ja,RSQ:Xa,SLOPE:Ka,SMALL:Qa,SPEARMAN:Ja,STDEV:el,STDEVA:nl,STDEVP:ol,STDEVPA:sl,STDEV_P:tl,STDEV_S:rl,STEYX:il,TREND:al,VAR:ll,VARA:hl,VARP:dl,VARPA:fl,VAR_P:cl,VAR_S:ul});function ml(e,t,r,n){const o=new Map,s=e.length;for(let t=s-1;t>=0;t--)o.set($t(e[t][0]).toUpperCase(),t);const i=t?.value;if("number"!=typeof i&&"string"!=typeof i)throw new S(v("The field must be a number or a string"));let a;if("number"==typeof i){if(a=Math.trunc(i)-1,a<0||s-1<a)throw new S(v("The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.",{fieldValue:i.toString(),dimRowDB:s.toString()}))}else{const e=$t(t).toUpperCase();if(a=o.get(e)??-1,-1===a)throw new S(v("The field (%s) must be one of %s.",$t(t),[...o.keys()].toString()))}const l=r[0].length;if(l<2)throw new S(v("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const u=e[0].length;for(let t=1;t<l;t++){const s=[];let i=!0;for(let n=0;n<r.length;n++){const a=$t(r[n][0]).toUpperCase(),l=o.get(a),c=r[n][t];if(null!==c.value){if(void 0===l){i=!1;break}s.push([e[l].slice(1,u)]),s.push(c)}}if(i){if(!(s.length>0)){c=new Set(Array(u-1).keys());break}ur(s,(e,t)=>{c.add(t)},n,!0)}}const h=e[a];return[...c].map(e=>h[e+1])}const pl=[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."))],bl={description:v("Average of a set of values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return da.compute.bind(this)([n])},isExported:!0},vl={description:v("Counts values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return ya.compute.bind(this)([n])},isExported:!0},yl={description:v("Counts values and text from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return wa.compute.bind(this)([n])},isExported:!0},wl={description:v("Single value from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return 1!==n.length?new S(v("More than one match found in DGET evaluation.")):n[0]},isExported:!0},El={description:v("Maximum of values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return Da.compute.bind(this)([n])},isExported:!0},Sl={description:v("Minimum of values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return Va.compute.bind(this)([n])},isExported:!0},Cl={description:v("Product of values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return yi.compute.bind(this)([n])},isExported:!0},Tl={description:v("Standard deviation of population sample from table."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return el.compute.bind(this)([n])},isExported:!0},Il={description:v("Standard deviation of entire population from table."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return ol.compute.bind(this)([n])},isExported:!0},xl={description:v("Sum of values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return Li.compute.bind(this)([n])},isExported:!0},Rl={description:v("Variance of population sample from table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return ll.compute.bind(this)([n])},isExported:!0},Al={description:v("Variance of a population from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return dl.compute.bind(this)([n])},isExported:!0};var _l=Object.freeze({__proto__:null,DAVERAGE:bl,DCOUNT:vl,DCOUNTA:yl,DGET:wl,DMAX:El,DMIN:Sl,DPRODUCT:Cl,DSTDEV:Tl,DSTDEVP:Il,DSUM:xl,DVAR:Rl,DVARP:Al});const Ol=[{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:";"}],Dl=Ol[0],Fl=["%"],Nl="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Fl);function Ml(e,t=Dl){e=Pe(e);const r=new Ze(e),n=[],o=Me.test(e)?ql:Zl;for(;!r.isOver();){let e=Yl(r)||o(r)||kl(r,t)||Pl(r)||Ul(r)||zl(r)||Vl(r)||jl(r)||Bl(r,t)||Wl(r);e||(e={type:"UNKNOWN",value:r.shift()}),n.push(e)}return n}function Vl(e){return"?"===e.current?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const Ll={"(":{type:"LEFT_PAREN",value:"("},")":{type:"RIGHT_PAREN",value:")"}};function Pl(e){if("("===e.current||")"===e.current){const t=e.shift();return Ll[t]}return null}function kl(e,t){if(e.current===t.formulaArgSeparator){return{type:"ARG_SEPARATOR",value:e.shift()}}return null}function Ul(e){for(const t of Nl)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}const Hl=new Set("0123456789");function Bl(e,t){if(!Hl.has(e.current)&&e.current!==t.decimalSeparator)return null;const r=e.remaining().match(Rt(t.decimalSeparator));return r?(e.advanceBy(r[0].length),{type:"NUMBER",value:r[0]}):null}function zl(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 $l=/\p{L}|\p{N}|_|\.|!|\$/u,Gl=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$");function Wl(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&&(Gl.has(e.current)||e.current.match($l));)t+=e.shift();if(t.length){const e=t;return ao.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function ql(e){let t="";for(;" "===e.current||e.current&&e.current.match(Me);)t+=e.shift();return t?{type:"SPACE",value:t}:null}function Zl(e){let t="";for(;" "===e.current;)t+=e.shift();return t?{type:"SPACE",value:t}:null}function Yl(e){let t=0;for(;e.current===Q;)t++,e.shift();return t?{type:"SPACE",value:Q.repeat(t)}:null}function jl(e){return e.currentStartsWith(w.InvalidReference)?(e.advanceBy(w.InvalidReference.length),{type:"INVALID_REFERENCE",value:w.InvalidReference}):null}function Xl(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{Fn(1,{locale:e,format:"#,##0.00"}),Fn(1,{locale:e,format:e.dateFormat}),Fn(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function Kl(e,t){return Ke(e)?function(e,t){return ec(e.startsWith("+")?"="+e.slice(1):e,t,Dl)}(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 Ql(e,t){return e.startsWith("=")?Jl(e,t):function(e,t){if(dt(e,Dl)){const r=kt(e,Dl);let n=t.dateFormat;return Number.isInteger(r)||(n+=" "+t.timeFormat),Fn(r,{locale:t,format:n})}return function(e,t){if("."===t.decimalSeparator||!_t(e,Dl))return e;const r=zn(Dl);return e.replace(r,e=>e.replace(".",t.decimalSeparator))}(e,t)}(e,t)}function Jl(e,t){return ec(e,Dl,t)}function ec(e,t,r){if(t.formulaArgSeparator===r.formulaArgSeparator&&t.decimalSeparator===r.decimalSeparator)return e;const n=Ml(e,t);let o="";for(const e of n)"NUMBER"===e.type?o+=e.value.replace(t.decimalSeparator,r.decimalSeparator):"ARG_SEPARATOR"===e.type?o+=r.formulaArgSeparator:o+=e.value;return o}function tc(e){return e.dateFormat+" "+e.timeFormat}const rc=v("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."),nc=v("There must be both positive and negative values in cashflow_amounts."),oc=e=>v("The cost (%s) must be positive or null.",e),sc=e=>v("The frequency (%s) must be one of %s",e,[1,2,4].toString()),ic=e=>v("The day_count_convention (%s) must be between 0 and 4 inclusive.",e),ac=e=>v("The depreciation factor (%s) must be strictly positive.",e),lc=e=>v("The discount (%s) must be strictly positive.",e),cc=e=>v("The discount (%s) must be smaller than 1.",e),uc=e=>v("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e),hc=(e,t)=>v("The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).",{first:e,last:t}),dc=e=>v("The first_period (%s) must be strictly positive.",e),fc=e=>v("The investment (%s) must be strictly positive.",e),gc=(e,t)=>v("The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).",{last:e,nPeriods:t}),mc=e=>v("The last_period (%s) must be strictly positive.",e),pc=e=>v("The life (%s) must be strictly positive.",e),bc=(e,t)=>v("The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).",{maturity:t,settlement:e}),vc=e=>v("The number_of_periods (%s) must be strictly positive.",e),yc=e=>v("The periods_by_year (%s) must be strictly positive.",e),wc=(e,t)=>v("The period (%(period)s) must be less than or equal life (%(life)s).",{period:e,life:t}),Ec=e=>v("The period (%s) must be strictly positive.",e),Sc=e=>v("The present_value (%s) must be strictly positive.",e),Cc=e=>v("The price (%s) must be strictly positive.",e),Tc=e=>v("The rate_guess (%s) must be strictly greater than -1.",e),Ic=e=>v("The rate (%s) must be positive or null.",e),xc=e=>v("The rate (%s) must be strictly positive.",e),Rc=e=>v("The redemption (%s) must be strictly positive.",e),Ac=e=>v("The salvage (%s) must be positive or null.",e),_c=(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),Dc=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 Nc(e){return![0,1,2,3,4].includes(e)}function Mc(e){return![1,2,4].includes(e)}function Vc(e,t,r){const n=Zt(e,r),o=Zt(t,r),s=Zt(e,r);return s.setFullYear(n.getFullYear()+1),o.getTime()<=s.getTime()}const Lc=[{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 kc={description:v("Converts year/month/day into a date."),args:[a("year (number)",v("The year component of the date.")),a("month (number)",v("The month component of the date.")),a("day (number)",v("The day component of the date."))],compute:function(e,t,r){let n=Math.trunc(kt(e,this.locale));const o=Math.trunc(kt(t,this.locale)),s=Math.trunc(kt(r,this.locale));if(n<0||n>9999)return new S(v("The year (%s) must be between 0 and 9999 inclusive.",n.toString()));n<1900&&(n+=1900);const i=pt(new Qe(n,o-1,s));return i<0?new S(v("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")):{value:i,format:this.locale.dateFormat}},isExported:!0},Uc={description:v("Calculates the number of days, months, or years between two dates."),args:[a("start_date (date)",v("The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.")),a("end_date (date)",v("The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.")),a("unit (string)",v("A text abbreviation for unit of time."),[{value:"Y",label:v("The number of whole years between start_date and end_date")},{value:"M",label:v("The number of whole months between start_date and end_date")},{value:"D",label:v("The number of days between start_date and end_date")},{value:"MD",label:v("The number of days between start_date and end_date after subtracting whole months")},{value:"YM",label:v("The number of whole months between start_date and end_date after subtracting whole years")},{value:"YD",label:v("The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart")}])],compute:function(e,t,r){const n=$t(r).toUpperCase();if(!Object.values(Pc).includes(n))return new S(((e,t)=>{const r=e.map(e=>`'${e}'`).join(", ");return v("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,r)})(Object.values(Pc),$t(r)));const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=mt(o),a=mt(s);if(s<o)return new S(v("start_date (%s) should be on or before end_date (%s).",i.toLocaleDateString(),a.toLocaleDateString()));switch(n){case Pc.WHOLE_YEARS:return It(i,a);case Pc.WHOLE_MONTHS:return Ct(i,a);case Pc.WHOLE_DAYS:return Tt(i,a);case Pc.MONTH_WITHOUT_WHOLE_YEARS:return Ct(i,a)-12*It(i,a);case Pc.DAYS_WITHOUT_WHOLE_MONTHS:let e=a.getDate()-i.getDate();if(e<0){e=vt(new Qe(a.getFullYear(),a.getMonth()-1,1))-Math.abs(e)}return e;case Pc.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return St(e,t,1)<1}(o,s))return Tt(i,a);const e=new Qe(i.getFullYear(),a.getMonth(),a.getDate());let t=Tt(i,e);return t<0&&(e.setFullYear(i.getFullYear()+1),t=Tt(i,e)),t}}},isExported:!0},Hc={description:v("Converts a date string to a date value."),args:[a("date_string (string)",v("The string representing the date."))],compute:function(e){const t=$t(e),r=gt(t,this.locale);return null===r?new S(v("The date_string (%s) cannot be parsed to date/time.",t.toString())):Math.trunc(r.value)},isExported:!0},Bc={description:v("Day of the month that a specific date falls on."),args:[a("date (string)",v("The date from which to extract the day."))],compute:function(e){return Zt(e,this.locale).getDate()},isExported:!0},zc={description:v("Number of days between two dates."),args:[a("end_date (date)",v("The end of the date range.")),a("start_date (date)",v("The start of the date range."))],compute:function(e,t){const r=Zt(e,this.locale),n=Zt(t,this.locale),o=r.getTime()-n.getTime();return Math.round(o/et)},isExported:!0},$c=!1,Gc={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:$c}){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=St(n,o,qt(r)?4:0);return Math.sign(o-n)*Math.round(360*s)},isExported:!0},Wc={description:v("Date a number of months before/after another date."),args:[a("start_date (date)",v("The date from which to calculate the result.")),a("months (number)",v("The number of months before (negative) or after (positive) 'start_date' to calculate."))],compute:function(e,t){return{value:pt(wt(Zt(e,this.locale),Math.trunc(kt(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},qc={description:v("Last day of a month before or after a date."),args:[a("start_date (date)",v("The date from which to calculate the result.")),a("months (number)",v("The number of months before (negative) or after (positive) 'start_date' to consider."))],compute:function(e,t){const r=Zt(e,this.locale),n=Math.trunc(kt(t,this.locale)),o=r.getFullYear(),s=r.getMonth();return{value:pt(new Qe(o,s+n+1,0)),format:this.locale.dateFormat}},isExported:!0},Zc={description:v("Hour component of a specific time."),args:[a("time (date)",v("The time from which to calculate the hour component."))],compute:function(e){return Zt(e,this.locale).getHours()},isExported:!0},Yc={description:v("ISO week number of the year."),args:[a("date (date)",v("The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number."))],compute:function(e){const t=Zt(e,this.locale),r=t.getFullYear();let n=1;for(;4!==new Qe(r,0,n).getDay();)n+=1;const o=new Qe(r,0,n-3);let s=31;for(;4!==new Qe(r,11,s).getDay();)s-=1;const i=new Qe(r,11,s+3);let a,l;switch(a=o.getTime()<=t.getTime()?t.getTime()<=i.getTime()?0:1:-1,a){case 0:l=o;break;case 1:l=new Qe(r,11,s+3+1);break;case-1:let e=1;for(;4!==new Qe(r-1,0,e).getDay();)e+=1;l=new Qe(r-1,0,e-3)}const c=(t.getTime()-l.getTime())/et;return Math.floor(c/7)+1},isExported:!0},jc={description:v("Minute component of a specific time."),args:[a("time (date)",v("The time from which to calculate the minute component."))],compute:function(e){return Zt(e,this.locale).getMinutes()},isExported:!0},Xc={description:v("Month of the year a specific date falls in"),args:[a("date (date)",v("The date from which to extract the month."))],compute:function(e){return Zt(e,this.locale).getMonth()+1},isExported:!0},Kc={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 eu.compute.bind(this)(e,t,{value:1},r)},isExported:!0};function Qc(e){const t=e?.value;if("string"==typeof t){Ir(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 Ir(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 Jc=[{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")}],eu={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."),Jc),a("holidays (date, range<date>, optional)",v("A range or array constant containing the dates to consider as holidays."))],compute:function(e,t,r={value:1},n){const o=Zt(e,this.locale),s=Zt(t,this.locale),i=Qc(r),a=new Set;void 0!==n&&Xt([n],e=>{const t=Zt(e,this.locale);a.add(t.getTime())});const l=o.getTime()>s.getTime(),c=Qe.fromTimestamp((l?o:s).getTime()),u=Qe.fromTimestamp((l?s:o).getTime()),h=c.getTime();let d=u.getTime(),f=0;for(;d<=h;)i.includes(u.getDay())||a.has(d)||(f+=1),u.setDate(u.getDate()+1),d=u.getTime();return l?-f:f},isExported:!0},tu={description:v("Current date and time as a date value."),args:[],compute:function(){const e=Qe.now(),t=e.getTime()-Je.getTime(),r=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/et)+r,format:tc(this.locale)}},isExported:!0},ru={description:v("Minute component of a specific time."),args:[a("time (date)",v("The time from which to calculate the second component."))],compute:function(e){return Zt(e,this.locale).getSeconds()},isExported:!0},nu={description:v("Converts hour/minute/second into a time."),args:[a("hour (number)",v("The hour component of the time.")),a("minute (number)",v("The minute component of the time.")),a("second (number)",v("The second component of the time."))],compute:function(e,t,r){let n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=Math.trunc(kt(r,this.locale));return o+=Math.floor(s/60),s=s%60+(s<0?60:0),n+=Math.floor(o/60),o=o%60+(o<0?60:0),n%=24,n<0?new S(v("The function [[FUNCTION_NAME]] result cannot be negative")):{value:n/24+o/1440+s/86400,format:this.locale.timeFormat}},isExported:!0},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=$t(e),r=gt(t,this.locale);if(null===r)return new S(v("The time_string (%s) cannot be parsed to date/time.",t));const n=r.value-Math.trunc(r.value);return n<0?1+n:n},isExported:!0},su={description:v("Current date as a date value."),args:[],compute:function(){const e=Qe.now();return{value:pt(new Qe(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},iu={description:v("Day of the week of the date provided (as number)."),args:[a("date (date)",v("The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),a("type (number, default=1)",v("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."),[{value:1,label:v("Numbers 1 (Sunday) trough 7 (Saturday)")},{value:2,label:v("Numbers 1 (Monday) trough 7 (Sunday)")},{value:3,label:v("Numbers 0 (Monday) trough 6 (Sunday)")},{value:11,label:v("Numbers 1 (Monday) trough 7 (Sunday)")},{value:12,label:v("Numbers 1 (Tuesday) trough 7 (Monday)")},{value:13,label:v("Numbers 1 (Wednesday) trough 7 (Tuesday)")},{value:14,label:v("Numbers 1 (Thursday) trough 7 (Wednesday)")},{value:15,label:v("Numbers 1 (Friday) trough 7 (Thursday)")},{value:16,label:v("Numbers 1 (Saturday) trough 7 (Friday)")},{value:17,label:v("Numbers 1 (Sunday) trough 7 (Saturday)")}])],compute:function(e,t={value:1}){const r=Zt(e,this.locale),n=Math.round(kt(t,this.locale)),o=r.getDay();if(!(1<=n&&n<=3||11<=n&&n<=17))return new S(v("The type (%s) must be between 1 and 3 or between 11 and 17.",n));switch(n){case 1:return o+1;case 2:return 0===o?7:o;case 3:return 0===o?6:o-1}const s=(o+1-(n-10)+7)%7;return 0===s?7:s},isExported:!0},au={description:v("Week number of the year."),args:[a("date (date)",v("The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),a("type (number, default=1)",v("A number representing the day that a week starts on. Sunday = 1."),[{value:1,label:v("Sunday")},{value:2,label:v("Monday")},{value:11,label:v("Monday")},{value:12,label:v("Tuesday")},{value:13,label:v("Wednesday")},{value:14,label:v("Thursday")},{value:15,label:v("Friday")},{value:16,label:v("Saturday")},{value:17,label:v("Sunday")},{value:21,label:v("ISO week number (Monday as first day of the week)")}])],compute:function(e,t={value:1}){const r=Zt(e,this.locale),n=Math.round(kt(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(n))return new S(v("The type (%s) is out of range.",n.toString()));if(21===n)return Yc.compute.bind(this)(e);let o;o=1===n||2===n?n-1:n-10==7?0:n-10;const s=r.getFullYear();let i=1,a=new Qe(s,0,i);for(;a.getDay()!==o;)i+=1,a=new Qe(s,0,i);const l=(r.getTime()-a.getTime())/et;return l<0?1:Math.floor(l/7)+(1===i?1:2)},isExported:!0},lu={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 cu.compute.bind(this)(e,t,{value:1},r)},isExported:!0},cu={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."),Jc),a("holidays (date, range<date>, optional)",v("A range or array constant containing the dates to consider holidays."))],compute:function(e,t,r={value:1},n){const o=Zt(e,this.locale),s=Math.trunc(kt(t,this.locale));if("1111111"===r.value)return new S(v("The weekend must be different from '1111111'."));const i=Qc(r),a=new Set;void 0!==n&&Xt([n],e=>{const t=Zt(e,this.locale);a.add(t.getTime())});const l=Qe.fromTimestamp(o.getTime());let c=l.getTime();const u=Math.sign(s);let h=Math.abs(s);for(;h>0;)l.setDate(l.getDate()+u),c=l.getTime(),i.includes(l.getDay())||a.has(c)||(h-=1);const d=c-Je.getTime();return{value:Math.round(d/et),format:this.locale.dateFormat}},isExported:!0},uu={description:v("Year specified by a given date."),args:[a("date (date)",v("The date from which to extract the year."))],compute:function(e){return Zt(e,this.locale).getFullYear()},isExported:!0},hu={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."),Lc)],compute:function(e,t,r={value:0}){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=Math.trunc(kt(r,this.locale));return n<0?new S(v("The start_date (%s) must be positive or null.",n)):o<0?new S(v("The end_date (%s) must be positive or null.",o)):0>s||s>4?new S(v("The day_count_convention (%s) must be between 0 and 4 inclusive.",s)):St(n,o,s)}},du={description:v("First day of the month preceding a date."),args:[a("date (date)",v("The date from which to calculate the result."))],compute:function(e){const t=Zt(e,this.locale),r=t.getFullYear(),n=t.getMonth();return{value:pt(new Qe(r,n,1)),format:this.locale.dateFormat}}},fu={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 qc.compute.bind(this)(e,{value:0})}},gu={description:v("Quarter of the year a specific date falls in"),args:[a("date (date)",v("The date from which to extract the quarter."))],compute:function(e){return Math.ceil((Zt(e,this.locale).getMonth()+1)/3)}},mu={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=gu.compute.bind(this)(e),r=uu.compute.bind(this)(e);return{value:pt(new Qe(r,3*(t-1),1)),format:this.locale.dateFormat}}},pu={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=gu.compute.bind(this)(e),r=uu.compute.bind(this)(e);return{value:pt(new Qe(r,3*t,0)),format:this.locale.dateFormat}}},bu={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=uu.compute.bind(this)(e);return{value:pt(new Qe(t,0,1)),format:this.locale.dateFormat}}},vu={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=uu.compute.bind(this)(e);return{value:pt(new Qe(t+1,0,0)),format:this.locale.dateFormat}}};var yu=Object.freeze({__proto__:null,DATE:kc,DATEDIF:Uc,DATEVALUE:Hc,DAY:Bc,DAYS:zc,DAYS360:Gc,EDATE:Wc,EOMONTH:qc,HOUR:Zc,ISOWEEKNUM:Yc,MINUTE:jc,MONTH:Xc,MONTH_END:fu,MONTH_START:du,NETWORKDAYS:Kc,NETWORKDAYS_INTL:eu,NOW:tu,QUARTER:gu,QUARTER_END:pu,QUARTER_START:mu,SECOND:ru,TIME:nu,TIMEVALUE:ou,TODAY:su,WEEKDAY:iu,WEEKNUM:au,WORKDAY:lu,WORKDAY_INTL:cu,YEAR:uu,YEARFRAC:hu,YEAR_END:vu,YEAR_START:bu});const wu={description:v("Compare two numeric values, returning 1 if they're equal."),args:[a("number1 (number)",v("The first number to compare.")),a("number2 (number, default=0)",v("The second number to compare."))],compute:function(e,t={value:0}){return kt(e,this.locale)===kt(t,this.locale)?1:0},isExported:!0};var Eu,Su=Object.freeze({__proto__:null,DELTA:wu});!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(Eu||(Eu={}));const Cu=[Eu.number,Eu.error,Eu.text,Eu.boolean];function Tu(e){const t="asc"===e?1:-1;return(e,r)=>{if(e.type===Eu.empty)return r.type===Eu.empty?0:1;if(r.type===Eu.empty)return-1;let n=Cu.indexOf(e.type)-Cu.indexOf(r.type);return 0===n&&(n=e.type===Eu.text||e.type===Eu.error?e.value.localeCompare(r.value):e.value-r.value),t*n}}function Iu(e,t,...r){for(let e=0;e<r.length;e++){const t=e%2==0?"sort_column":"is_ascending";Ir(void 0!==r[e],v("Value for parameter %s is missing in [[FUNCTION_NAME]].",t))}const n=[],o=[],s=e.length;for(let i=0;i<r.length;i+=2){n.push(qt(Vr(r[i+1])?.value)?"asc":"desc");const a=r[i];if(O(a)&&(a.length>1||a[0].length>1))Ir(1===a.length&&a[0].length===s,v("Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.",`sort_column${i+1}`,s,a.length,a[0].length)),o.push(a.flat().map(e=>e.value));else{const r=kt(Vr(a)?.value,t);if(r<1||r>e[0].length)return e;o.push(e.map(e=>e[r-1].value))}}if(0===o.length)for(let t=0;t<e[0].length;t++)o.push(e.map(e=>e[t].value)),n.push("asc");const i={desc:Tu("desc"),asc:Tu("asc")},a=le(0,e.length);return a.sort((e,t)=>{for(const[r,s]of o.entries()){const o=s[e],a=s[t],l={value:o,type:null===o?Eu.empty:"string"==typeof o?Eu.text:typeof o},c={value:a,type:null===a?Eu.empty:"string"==typeof a?Eu.text:typeof a},u=i[n[r]](l,c);if(0!==u)return u}return 0}),a.map(t=>e[t])}const xu={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("condition1 (boolean, range<boolean>)",v("A column or row containing true or false values corresponding to the first column or row of range.")),a("condition2 (boolean, range<boolean>, repeating)",v("Additional column or row containing true or false values."))],compute:function(e,...t){let r=mr(e);const n=t.map(e=>nr(mr(e),e=>e.value));for(const e of n)if(!Rr(e))return new S(v("The arguments condition must be a single column or row."));if(!Ar(...t))return new S(v("The arguments conditions must have the same dimensions."));const o=n.map(e=>e.flat()),s=1===n[0].length?"row":"col";if(r="row"===s?or(r):r,o.some(e=>e.length!==r.length))return new S(v("FILTER has mismatched sizes on the range and conditions."));const i=[];for(let e=0;e<r.length;e++){const t=r[e];o.every(t=>("boolean"==typeof t[e]||"number"==typeof t[e])&&t[e])&&i.push(t)}return i.length?"row"===s?or(i):i:new x(v("No match found in FILTER evaluation"))},isExported:!1},Ru={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)",v("The index of the column in range or a range outside of range containing the values by which to sort.")),a("is_ascending (boolean, repeating)",v("TRUE or FALSE indicating whether to sort sort_column in ascending order."),[{value:!0,label:v("Ascending")},{value:!1,label:v("Descending")}])],compute:function(e,...t){const r=or(e);return or(Iu(r,this.locale,...t))},isExported:!0},Au={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)",v("The index of the column in range or a range outside of range containing the values by which to sort.")),a("is_ascending (boolean, repeating)",v("TRUE or FALSE indicating whether to sort sort_column in ascending order."),[{value:!0,label:v("Ascending")},{value:!1,label:v("Descending")}])],compute:function(e,t,...r){const n=kt(t?.value??1,this.locale),o=r.length%2==0?0:kt(r[0]?.value,this.locale),s=r.length%2==0?r:r.slice(1);if(n<0)return new S(v("Wrong value of 'n'. Expected a positive number. Got %s.",n));if(o<0||o>3)return new S(v("Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.",o));const i=Iu(or(e),this.locale,...s),a=(e,t)=>JSON.stringify(i[e].map(e=>e.value))===JSON.stringify(i[t].map(e=>e.value));switch(o){case 0:return or(i.slice(0,n));case 1:for(let e=n;e<i.length;e++)if(!a(e,n-1))return or(i.slice(0,e));return or(i);case 2:{const e=[i[0]];for(let t=1;t<i.length;t++)for(let r=0;r<t&&!a(t,r);r++)r===t-1&&e.push(i[t]);return or(e.slice(0,n))}case 3:{const e=[i[0]];let t=1;for(let r=1;r<i.length&&(a(r,r-1)||t++,!(t>n));r++)e.push(i[r]);return or(e)}}},isExported:!1},_u={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(!O(e))return[[e]];const n=qt(t?.value)||!1,o=qt(r?.value)||!1;n||(e=or(e));const s=new Map;for(const t of e){const e=JSON.stringify(t.map(e=>e.value)),r=s.get(e);r?r.count++:s.set(e,{data:t,count:1})}const i=[];for(const e of s.values())o&&e.count>1||i.push(e.data);return i.length?n?i:or(i):new S(v("No unique values found"))},isExported:!0};var Ou=Object.freeze({__proto__:null,FILTER:xu,SORT:Ru,SORTN:Au,UNIQUE:_u});const Du=[{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")}],Nu=[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)."),Du),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Lc)];function Mu(e,t,r,n,o=1e-10,s){let i,a,l,c,u=r,h=!1,d=0;do{l=e(u),isNaN(l)?(Ir(d<n&&void 0!==s,v("Function [[FUNCTION_NAME]] didn't find any result.")),d++,u=s(c),c=u):(i=u-l/t(u),a=Math.abs(i-u),u=i,h=a<o||Math.abs(l)<o,Ir(d<n,v("Function [[FUNCTION_NAME]] didn't find any result.")),d++)}while(!h);return u}const Vu={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."),Lc)],compute:function(e,t,r,n,o={value:0}){const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(n,this.locale),l=kt(r,this.locale),c=Math.trunc(kt(o,this.locale));if(s<0)return new S((e=>v("The issue (%s) must be positive or null.",e))(s));if(s>=i)return new S(bc(s,i));if(Nc(c))return new S(ic(c));if(a<=0)return new S(Rc(a));if(l<=0)return new S(xc(l));return a*l*St(s,i,c)},isExported:!0},Lu={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."),Lc)],compute:function(e,t,r,n,o,s,i={value:0}){i=i||0;const a=kt(e,this.locale),l=Math.trunc(kt(t,this.locale)),c=Math.trunc(kt(r,this.locale)),u=kt(n,this.locale),h=kt(o,this.locale),d=kt(s,this.locale),f=Math.trunc(kt(i,this.locale));if(a<=0)return new S((e=>v("The cost (%s) must be strictly positive.",e))(a));if(l<0)return new S((e=>v("The purchase_date (%s) must be positive or null.",e))(l));if(u<0)return new S(Ac(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(xc(d));if(Nc(f))return new S(ic(f));if(l>c)return new S(((e,t)=>v("The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).",{purchaseDate:e,firstPeriodEnd:t}))(l,c));const g=h<1&&h>0?1:Math.trunc(h),m=a*d,p=St(l,c,f),b=l===c?m:m*p,y=a-b-m*g;return y>=u?0===g?b:m:u-y<m?m-(u-y):0},isExported:!0},Pu={description:v("Days in coupon period containing settlement date."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));if(1===a){const o=zu.compute.bind(this)(e,t,r,n).value;return kt(Hu.compute.bind(this)(e,t,r,n).value,this.locale)-kt(o,this.locale)}return(3===a?365:360)/i},isExported:!0},ku={description:v("Days from settlement until next coupon."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));const l=kt(zu.compute.bind(this)(e,t,r,n).value,this.locale);if([1,2,3].includes(a))return o-l;if(4===a){const e=St(l,o,a);return Math.round(360*e)}const c=Zt(o,this.locale),u=Zt(l,this.locale),h=u.getFullYear(),d=c.getFullYear(),f=u.getMonth()+1,g=c.getMonth()+1;let m=u.getDate(),p=c.getDate();return 2===f&&2===g&&yt(u)&&yt(c)&&(p=30),31!==p||30!==m&&31!==m||(p=30),2===f&&yt(u)&&(m=30),31===m&&(m=30),360*(d-h)+30*(g-f)+(p-m)},isExported:!0},Uu={description:v("Days from settlement until next coupon."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));const l=kt(Hu.compute.bind(this)(e,t,r,n).value,this.locale);if([1,2,3].includes(a))return l-o;if(4===a){const e=St(o,l,a);return Math.round(360*e)}const c=ku.compute.bind(this)(e,t,r,n);return kt(Pu.compute.bind(this)(e,t,r,n),this.locale)-kt(c,this.locale)},isExported:!0},Hu={description:v("Next coupon date after the settlement date."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));const l=12/i,c=Bu.compute.bind(this)(e,t,r,n);return{value:pt(wt(Zt(s,this.locale),-(kt(c,this.locale)-1)*l,!0)),format:this.locale.dateFormat}},isExported:!0},Bu={description:v("Number of coupons between settlement and maturity."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));let l=1,c=s;const u=12/i;for(;c>o;)c=pt(wt(Zt(c,this.locale),-u,!1)),l++;return l-1},isExported:!0},zu={description:v("Last coupon date prior to or on the settlement date."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));const l=12/i,c=Bu.compute.bind(this)(e,t,r,n);return{value:pt(wt(Zt(s,this.locale),-c*l,!0)),format:this.locale.dateFormat}},isExported:!0},$u={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,n,o,s={value:0}){const i=kt(n,this.locale),a=kt(o,this.locale),l=kt(e,this.locale),c=kt(r,this.locale),u=kt(t,this.locale),h=qt(s)?1:0;if(u<=0)return new S(vc(u));if(i<=0)return new S(dc(i));if(a<=0)return new S(mc(a));if(i>a)return new S(hc(i,a));if(a>u)return new S(gc(a,u));if(l<=0)return new S(xc(l));if(c<=0)return new S(Sc(c));let d=0;for(let e=i;e<=a;e++)d+=nh(l,e,u,c,0,h);return d},isExported:!0},Gu={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,n,o,s={value:0}){const i=kt(n,this.locale),a=kt(o,this.locale),l=kt(e,this.locale),c=kt(r,this.locale),u=kt(t,this.locale),h=qt(s)?1:0;if(u<=0)return new S(vc(u));if(i<=0)return new S(dc(i));if(a<=0)return new S(mc(a));if(i>a)return new S(hc(i,a));if(a>u)return new S(gc(a,u));if(l<=0)return new S(xc(l));if(c<=0)return new S(Sc(c));let d=0;for(let e=i;e<=a;e++)d+=ph(l,e,u,c,0,h);return d},isExported:!0},Wu={description:v("Depreciation via declining balance method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("period (number)",v("The single period within life for which to calculate depreciation.")),a("month (number, optional)",v("The number of months in the first year of depreciation."))],compute:function(e,t,r,n,...o){const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=Math.trunc(kt(n,this.locale)),c=o.length?Math.trunc(kt(o[0],this.locale)):12,u=a+(12===c?0:1);if(s<0)return new S(oc(s));if(i<0)return new S(Ac(i));if(l<=0)return new S(Ec(l));if(a<=0)return new S(pc(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},qu="#,##0.00",Zu={description:v("Depreciation via double-declining balance method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("period (number)",v("The single period within life for which to calculate depreciation.")),a("factor (number, default=2)",v("The factor by which depreciation decreases."))],compute:function(e,t,r,n,o={value:2}){const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=kt(o,this.locale);if(s<0)return new S(oc(s));if(i<0)return new S(Ac(i));if(l<=0)return new S(Ec(l));if(a<=0)return new S(pc(a));if(l>a)return new S(wc(l,a));if(c<=0)return new S(ac(c));if(0===s||i>=s)return{value:0,format:qu};const u=c/a;if(u>1)return{value:1===l?s-i:0,format:qu};if(l<=1)return{value:s*u,format:qu};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:qu}},isExported:!0},Yu={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."),Lc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(bc(s,i));if(Nc(c))return new S(ic(c));if(a<=0)return new S(Cc(a));if(l<=0)return new S(Rc(l));return(l-a)/l/St(s,i,c)},isExported:!0},ju={description:v("Convert a decimal fraction to decimal value."),args:[a("fractional_price (number)",v("The price quotation given using fractional decimal conventions.")),a("unit (number)",v("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));if(n<=0)return new S(Oc(n));const o=Math.trunc(r);return o+(r-o)*(10**Math.ceil(Math.log10(n))/n)},isExported:!0},Xu={description:v("Convert a decimal value to decimal fraction."),args:[a("decimal_price (number)",v("The price quotation given as a decimal value.")),a("unit (number)",v("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));if(n<=0)return new S(Oc(n));const o=Math.trunc(r);return o+(r-o)*(n/10**Math.ceil(Math.log10(n)))},isExported:!0},Ku={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)."),Du),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Lc)],compute:function(e,t,r,n,o,s={value:0}){const i=Math.trunc(kt(e,this.locale)),a=Math.trunc(kt(t,this.locale)),l=kt(r,this.locale),c=kt(n,this.locale),u=Math.trunc(kt(o,this.locale)),h=Math.trunc(kt(s,this.locale));if(i>=a)return new S(bc(i,a));if(Mc(u))return new S(sc(u));if(Nc(h))return new S(ic(h));if(l<0)return new S(Ic(l));if(c<0)return new S(Dc(c));const d=St(i,a,h),f=d-Math.trunc(d)||1/u,g=Math.ceil(d*u),m=l/u,p=c/u;let b=0,v=0;for(let e=1;e<=g;e++){const t=(m+(e===g?1:0))/(1+p)**e;v+=(f+(e-1)/u)*t,b+=t}return 0===b?0:v/b},isExported:!0},Qu={description:v("Annual effective interest rate."),args:[a("nominal_rate (number)",v("The nominal interest rate per year.")),a("periods_per_year (number)",v("The number of compounding periods per year."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));return r<=0?new S(v("The nominal_rate (%s) must be strictly positive.",r)):n<=0?new S(yc(n)):Math.pow(1+r/n,n)-1},isExported:!0};function Ju(e,t,r,n,o){return 0===e?-(n+r*t):-n*(1+e)**t-r*(1+e*o)*((1+e)**t-1)/e}const eh={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,n={value:0},o={value:0}){n=n||0,o=o||0;return{value:Ju(kt(e,this.locale),kt(t,this.locale),kt(r,this.locale),kt(n,this.locale),qt(o)?1:0),format:"#,##0.00"}},isExported:!0},th={description:v("Future value of principal from series of rates."),args:[a("principal (number)",v("The amount of initial capital or value to compound against.")),a("rate_schedule (number, range<number>)",v("A series of interest rates to compound against the principal."))],compute:function(e,t){return Jt([t],(e,t)=>e*(1+kt(t,this.locale)),kt(e,this.locale))},isExported:!0},rh={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."),Lc)],compute:function(e,t,r,n,o={value:0}){const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(n,this.locale),l=kt(r,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(bc(s,i));if(l<=0)return new S(fc(l));if(a<=0)return new S(Rc(a));if(Nc(c))return new S(ic(c));return(a-l)/l/St(s,i,c)},isExported:!0};function nh(e,t,r,n,o,s){return gh(e,r,n,o,s)-ph(e,t,r,n,o,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,n,o={value:0},s={value:0}){return{value:nh(kt(e,this.locale),kt(t,this.locale),kt(r,this.locale),kt(n,this.locale),kt(o,this.locale),qt(s)?1:0),format:"#,##0.00"}},isExported:!0},sh={description:v("Internal rate of return given periodic cashflows."),args:[a("cashflow_amounts (number, range<number>)",v("An array or range containing the income or payments associated with the investment.")),a("rate_guess (number, default=0.1)",v("An estimate for what the internal rate of return will be."))],compute:function(e,t={value:.1}){const r=kt(t,this.locale);if(r<=-1)return new S(Tc(r));let n=!1,o=!1;const s=[];if(Kt([e],({value:e})=>{e>0&&(n=!0),e<0&&(o=!0),s.push(e)},this.locale),!n||!o)return new S(nc);const i=s.shift();return{value:Mu(function(e){return function(e,t,r){const n=r.length;let o=0;return r.reduce((t,r)=>(o++,t+r*e**(n-o)),t*e**n)}(e,i,s)},function(e){return function(e,t,r){const n=r.length;let o=0;return r.reduce((t,r)=>(o++,t+r*(n-o)*e**(n-o-1)),t*n*e**(n-1))}(e,i,s)},r+1,20,1e-5)-1,format:"0%"}},isExported:!0},ih={description:v("Returns the interest paid at a particular period of an investment."),args:[a("rate (number)",v("The interest rate.")),a("period (number)",v("The period for which you want to view the interest payment.")),a("number_of_periods (number)",v("The number of payments to be made.")),a("present_value (number)",v("The current value of the annuity."))],compute:function(e,t,r,n){const o=kt(e,this.locale),s=kt(t,this.locale),i=kt(r,this.locale),a=kt(n,this.locale);if(0===i)return new S(v("The number_of_periods (%s) must be different from zero.",i));return-1*(a-a*(s/i))*o},isExported:!0},ah={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)."),Du),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."))],compute:function(e,t,r,n,o,s={value:0}){const i=Ku.compute.bind(this)(e,t,r,n,o,s),a=kt(n,this.locale),l=Math.trunc(kt(o,this.locale));return kt(i,this.locale)/(1+a/l)},isExported:!0},lh={description:v("Modified internal rate of return."),args:[a("cashflow_amounts (range<number>)",v("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),a("financing_rate (number)",v("The interest rate paid on funds invested.")),a("reinvestment_return_rate (number)",v("The return (as a percentage) earned on reinvestment of income received from the investment."))],compute:function(e,t,r){const n=kt(t,this.locale),o=kt(r,this.locale),s=or(e).flat().filter(e=>null!==e.value).map(e=>kt(e,this.locale)),i=s.length;let a=0,l=0;for(const e of le(0,i)){const t=s[e];t>=0?a+=t*(o+1)**(i-e-1):l+=t/(n+1)**e}if(0===l||0===a)return new S(nc);return(-a/l)**(1/(i-1))-1},isExported:!0},ch={description:v("Annual nominal interest rate."),args:[a("effective_rate (number)",v("The effective interest rate per year.")),a("periods_per_year (number)",v("The number of compounding periods per year."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));return r<=0?new S(v("The effective_rate (%s) must be strictly positive.",r)):n<=0?new S(yc(n)):(Math.pow(r+1,1/n)-1)*n},isExported:!0},uh={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,n={value:0},o={value:0}){n=n||0,o=o||0;const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=qt(o)?1:0;if(0===s)return-(l+a)/i;const u=i*(1+s*c)/s;return Math.log((u-l)/(a+u))/Math.log(1+s)},isExported:!0};function hh(e,t,r,n){let o=0;return er(r,(t,r)=>(o++,t+r/(1+e)**o),t,n)}const dh={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("cashflow1 (number, range<number>)",v("The first future cash flow.")),a("cashflow2 (number, range<number>, repeating)",v("Additional future cash flows."))],compute:function(e,...t){const r=kt(e,this.locale);return-1===r?new S((e=>v("The discount (%s) must be different from -1.",e))(r)):{value:hh(r,0,t,this.locale),format:"#,##0.00"}},isExported:!0},fh={description:v("Computes the number of periods needed for an investment to reach a value."),args:[a("rate (number)",v("The rate at which the investment grows each period.")),a("present_value (number)",v("The investment's current value.")),a("future_value (number)",v("The investment's desired future value."))],compute:function(e,t,r){const n=kt(e,this.locale),o=kt(t,this.locale),s=kt(r,this.locale);return n<=0?new S(xc(n)):o<=0?new S(Sc(o)):s<=0?new S(v("The future_value (%s) must be strictly positive.",s)):(Math.log(s)-Math.log(o))/Math.log(1+n)},isExported:!0};function gh(e,t,r,n,o){if(t<=0)throw new S(vc(t));if(0===e)return-(n+r)/t;let s=-(r*(1+e)**t+n);return s=s*e/((1+e*o)*((1+e)**t-1)),s}const mh={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,n={value:0},o={value:0}){const s=kt(t,this.locale),i=kt(e,this.locale),a=qt(o)?1:0,l=kt(n,this.locale);return{value:gh(i,s,kt(r,this.locale),l,a),format:"#,##0.00"}},isExported:!0};function ph(e,t,r,n,o,s){if(r<=0)throw new S(vc(r));if(t<=0||t>r)throw new S(v("The period must be between 1 and number_of_periods (%s)",r));const i=gh(e,r,n,o,s);if(1===s&&1===t)return i;return i+-Ju(e,0===s?t-1:t-2,i,n+i*s,0)*e}const bh={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,n,o={value:0},s={value:0}){const i=kt(r,this.locale),a=kt(e,this.locale),l=kt(t,this.locale),c=qt(s)?1:0,u=kt(o,this.locale);return{value:ph(a,l,i,kt(n,this.locale),u,c),format:"#,##0.00"}},isExported:!0},vh={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,n={value:0},o={value:0}){n=n||0,o=o||0;const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=qt(o)?1:0;return{value:s?-(a*(1+s*c)*((1+s)**i-1)/s+l)/(1+s)**i:-(l+a*i),format:"#,##0.00"}},isExported:!0},yh={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)."),Du),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Lc)],compute:function(e,t,r,n,o,s,i={value:0}){i=i||0;const a=Math.trunc(kt(e,this.locale)),l=Math.trunc(kt(t,this.locale)),c=kt(r,this.locale),u=kt(n,this.locale),h=kt(o,this.locale),d=Math.trunc(kt(s,this.locale)),f=Math.trunc(kt(i,this.locale));if(a>=l)return new S(bc(a,l));if(Mc(d))return new S(sc(d));if(Nc(f))return new S(ic(f));if(c<0)return new S(Ic(c));if(u<0)return new S(Dc(u));if(h<=0)return new S(Rc(h));const g=St(a,l,f)*d,m=Math.ceil(g),p=g-Math.floor(g)||1,b=1+u/d,v=100*c/d;if(1===m)return(v+h)/(p*u/d+1)-v*(1-p);let y=0;for(let e=1;e<=m;e++)y+=v/b**(e-1+p);return h/b**(m-1+p)+y-v*(1-p)},isExported:!0},wh={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."),Lc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(bc(s,i));if(Nc(c))return new S(ic(c));if(a<=0)return new S(lc(a));if(l<=0)return new S(Rc(l));return l-a*l*St(s,i,c)},isExported:!0},Eh={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."),Lc)],compute:function(e,t,r,n,o,s={value:0}){s=s||0;const i=Math.trunc(kt(e,this.locale)),a=Math.trunc(kt(t,this.locale)),l=Math.trunc(kt(r,this.locale)),c=kt(n,this.locale),u=kt(o,this.locale),h=Math.trunc(kt(s,this.locale));if(i<=l)return new S(((e,t)=>v("The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).",{settlement:e,issue:t}))(i,l));if(i>=a)return new S(bc(i,a));if(Nc(h))return new S(ic(h));if(c<0)return new S(Ic(c));if(u<0)return new S(Dc(u));const d=St(i,a,h),f=St(i,l,h);return(100+St(l,a,h)*c*100)/(1+d*u)-f*c*100},isExported:!0},Sh=.1,Ch={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,n={value:0},o={value:0},s={value:Sh}){const i=kt(e,this.locale),a=kt(t,this.locale),l=qt(o)?1:0,c=kt(s,this.locale)||Sh;let u=kt(n,this.locale),h=kt(r,this.locale);if(i<=0)return new S(vc(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(Tc(c));u-=a*l,h+=a*l;return{value:Mu(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},Th={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."),Lc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(bc(s,i));if(Nc(c))return new S(ic(c));if(a<=0)return new S(fc(a));if(l<=0)return new S(lc(l));return a/(1-l*St(s,i,c))},isExported:!0},Ih={description:v("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[a("number_of_periods (number)",v("The number of periods.")),a("present_value (number)",v("The present value of the investment.")),a("future_value (number)",v("The future value of the investment."))],compute:function(e,t,r){const n=kt(e,this.locale),o=kt(t,this.locale),s=kt(r,this.locale);return n<=0?new S(vc(n)):(s/o)**(1/n)-1},isExported:!0},xh={description:v("Depreciation of an asset using the straight-line method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated."))],compute:function(e,t,r){return{value:(kt(e,this.locale)-kt(t,this.locale))/kt(r,this.locale),format:"#,##0.00"}},isExported:!0},Rh={description:v("Depreciation via sum of years digit method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("period (number)",v("The single period within life for which to calculate depreciation."))],compute:function(e,t,r,n){const o=kt(e,this.locale),s=kt(t,this.locale),i=kt(r,this.locale),a=kt(n,this.locale);if(a<=0)return new S(Ec(a));if(i<=0)return new S(pc(i));if(a>i)return new S(wc(a,i));return{value:(i-a+1)/(i*(i+1)/2)*(o-s),format:"#,##0.00"}},isExported:!0};function Ah(e,t,r){return 100*(1-r*St(e,t,2))}const _h={description:v("Price of a US Treasury bill."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("discount (number)",v("The discount rate of the bill at time of purchase."))],compute:function(e,t,r){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=kt(r,this.locale);return n>=o?new S(bc(n,o)):Vc(n,o,this.locale)?s<=0?new S(lc(s)):s>=1?new S(cc(s)):Ah(n,o,s):new S(_c(n,o))},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 n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=kt(r,this.locale);if(n>=o)return new S(bc(n,o));if(!Vc(n,o,this.locale))return new S(_c(n,o));if(s<=0)return new S(lc(s));if(s>=1)return new S(cc(s));const i=zc.compute.bind(this)({value:o},{value:n});if(i<=182)return 365*s/(360-s*i);const a=Ah(n,o,s)/100,l=i/(366===i?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},Dh={description:v("The yield of a US Treasury bill based on price."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("price (number)",v("The price at which the security is bought per 100 face value."))],compute:function(e,t,r){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=kt(r,this.locale);if(n>=o)return new S(bc(n,o));if(!Vc(n,o,this.locale))return new S(_c(n,o));if(s<=0)return new S(Cc(s));return(100-s)/s*(1/St(n,o,2))},isExported:!0},Fh=!1,Nh={description:v("Variable declining balance. WARNING : does not handle decimal periods."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("start (number)",v("Starting period to calculate depreciation.")),a("end (number)",v("Ending period to calculate depreciation.")),a("factor (number, default=2)",v("The number of months in the first year of depreciation.")),a("no_switch (number, default=false)",v("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."),[{value:!1,label:v("Switch to straight-line depreciation")},{value:!0,label:v("Do not switch to straight-line depreciation")}])],compute:function(e,t,r,n,o,s={value:2},i={value:Fh}){s=s||0;const a=kt(e,this.locale),l=kt(t,this.locale),c=kt(r,this.locale),u=Math.trunc(kt(n,this.locale)),h=Math.trunc(kt(o,this.locale)),d=kt(s,this.locale),f=qt(i);if(a<0)return new S(oc(a));if(l<0)return new S(Ac(l));if(c<=0)return new S(pc(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(ac(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},Mh={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:Sh}){const n=kt(r,this.locale);if(!Ar(e,t))return new S(rc);const o=e.flat().map(e=>kt(e,this.locale)),s=t.flat().map(e=>kt(e,this.locale));if(!Fc(o))return new S(nc);if(s.some(e=>e<s[0]))return new S(uc(s[0]));if(n<=-1)return new S(Tc(n));const i=new Map;for(const e of le(0,s.length)){const t=s[e];i.has(t)?i.set(t,i.get(t)+o[e]):i.set(t,o[e])}const a=Array.from(i.keys()),l=a.map(e=>i.get(e));return Mu(e=>{let t=l[0];for(const r of le(1,l.length)){const n=(a[0]-a[r])/365;t+=l[r]*(1+e)**n}return t},e=>{let t=0;for(const r of le(1,l.length)){const n=(a[0]-a[r])/365;t+=n*l[r]*(1+e)**(n-1)}return t},n,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},Vh={description:v("Net present value given to non-periodic cash flows.."),args:[a("discount (number)",v("The discount rate of the investment over one period.")),a("cashflow_amounts (number, range<number>)",v("An range containing the income or payments associated with the investment.")),a("cashflow_dates (number, range<number>)",v("An range with dates corresponding to the cash flows in cashflow_amounts."))],compute:function(e,t,r){const n=kt(e,this.locale);if(!Ar(t,r))return new S(rc);const o=mr(t).flat().map(e=>Ht(e,this.locale)),s=mr(r).flat().map(e=>Ht(e,this.locale));if(s.some(e=>e<s[0]))return new S(uc(s[0]));if(n<=0)return new S(xc(n));if(1===o.length)return o[0];const i=new Map;for(const e of le(0,s.length)){const t=s[e];i.has(t)?i.set(t,i.get(t)+o[e]):i.set(t,o[e])}const a=Array.from(i.keys()),l=a.map(e=>i.get(e));let c=l[0];for(const e of le(1,l.length)){const t=(a[0]-a[e])/365;c+=l[e]*(1+n)**t}return c},isExported:!0},Lh={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)."),Du),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Lc)],compute:function(e,t,r,n,o,s,i={value:0}){i=i||0;const a=Math.trunc(kt(e,this.locale)),l=Math.trunc(kt(t,this.locale)),c=kt(r,this.locale),u=kt(n,this.locale),h=kt(o,this.locale),d=Math.trunc(kt(s,this.locale)),f=Math.trunc(kt(i,this.locale));if(a>=l)return new S(bc(a,l));if(Mc(d))return new S(sc(d));if(Nc(f))return new S(ic(f));if(c<0)return new S(Ic(c));if(u<=0)return new S(Cc(u));if(h<=0)return new S(Rc(h));const g=St(a,l,f)*d,m=Math.ceil(g),p=g-Math.floor(g)||1,b=100*c/d;if(1===m){const e=u+b*(1-p);return(h+b-e)*d*(1/p)/e}const v=Mu(function(e){return function(e,t,r,n,o,s){let i=s-(e+o*(1-t))*n**(r-1+t);for(let e=1;e<=r;e++)i+=o*n**(e-1);return i}(u,p,m,e,b,h)},function(e){return function(e,t,r,n,o){let s=-(e+o*(1-t))*(r-1+t)*n**(r-2+t);for(let e=1;e<=r;e++)s+=o*(e-1)*n**(e-2);return s}(u,p,m,e,b)},1+(c+1)/d,100,1e-5);return(v-1)*d},isExported:!0},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."),Lc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(bc(s,i));if(Nc(c))return new S(ic(c));if(a<=0)return new S(Cc(a));if(l<=0)return new S(Rc(l));return(l/a-1)/St(s,i,c)},isExported:!0},kh={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."),Lc)],compute:function(e,t,r,n,o,s={value:0}){s=s||0;const i=Math.trunc(kt(e,this.locale)),a=Math.trunc(kt(t,this.locale)),l=Math.trunc(kt(r,this.locale)),c=kt(n,this.locale),u=kt(o,this.locale),h=Math.trunc(kt(s,this.locale));if(i>=a)return new S(bc(i,a));if(Nc(h))return new S(ic(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(Ic(c));if(u<=0)return new S(Cc(u));return(100*(1+c*St(l,a,h))/(u+100*c*St(l,i,h))-1)/St(i,a,h)},isExported:!0};var Uh=Object.freeze({__proto__:null,ACCRINTM:Vu,AMORLINC:Lu,COUPDAYBS:ku,COUPDAYS:Pu,COUPDAYSNC:Uu,COUPNCD:Hu,COUPNUM:Bu,COUPPCD:zu,CUMIPMT:$u,CUMPRINC:Gu,DB:Wu,DDB:Zu,DISC:Yu,DOLLARDE:ju,DOLLARFR:Xu,DURATION:Ku,EFFECT:Qu,FV:eh,FVSCHEDULE:th,INTRATE:rh,IPMT:oh,IRR:sh,ISPMT:ih,MDURATION:ah,MIRR:lh,NOMINAL:ch,NPER:uh,NPV:dh,PDURATION:fh,PMT:mh,PPMT:bh,PRICE:yh,PRICEDISC:wh,PRICEMAT:Eh,PV:vh,RATE:Ch,RECEIVED:Th,RRI:Ih,SLN:xh,SYD:Rh,TBILLEQ:Oh,TBILLPRICE:_h,TBILLYIELD:Dh,VDB:Nh,XIRR:Mh,XNPV:Vh,YIELD:Lh,YIELDDISC:Ph,YIELDMAT:kh});const Hh=[{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.')}],Bh={description:v("Gets information about a cell."),args:[a("info_type (string)",v("The type of information requested."),Hh),a("reference (meta, range<meta>)",v("The reference to the cell."))],compute:function(e,t){const r=$t(e).toLowerCase();if(!Hh.map(e=>e.value).includes(r))return new S(v("The info_type should be one of %s.",Hh.join(", ")));const n=this.__originSheetId,o=t[0][0].value;let{sheetName:s,xc:i}=go(o);s=s===this.getters.getSheetName(n)?void 0:s;const a=mo(s,bo(i,"colrow")),l=this.getters.getRangeFromSheetXC(n,a);switch(r){case"address":return this.getters.getRangeString(l,n);case"col":return l.zone.left+1;case"contents":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top};return this.getters.getEvaluatedCell(e).value}case"format":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top};return this.getters.getEvaluatedCell(e).format||""}case"row":return l.zone.top+1;case"type":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top},t=this.getters.getEvaluatedCell(e).type;return t===Eu.empty?"b":t===Eu.text?"l":"v"}}return""},isExported:!0},zh={description:v("Whether a value is an error other than #N/A."),args:[a("value (any)",v("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return Vt(t)&&t!==w.NotAvailable},isExported:!0},$h={description:v("Whether a value is an error."),args:[a("value (any)",v("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return Vt(t)},isExported:!0},Gh={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},Wh={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},qh={description:v("Whether a value is non-textual."),args:[a("value (any)",v("The value to be checked."))],compute:function(e){return!Yh.compute.bind(this)(e)},isExported:!0},Zh={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},Yh={description:v("Whether a value is text."),args:[a("value (any)",v("The value to be verified as text."))],compute:function(e){return"string"==typeof e?.value&&!1===Vt(e?.value)},isExported:!0},jh={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},Xh={description:v("Returns the error value #N/A."),args:[],compute:function(){return{value:w.NotAvailable}},isExported:!0};var Kh=Object.freeze({__proto__:null,CELL:Bh,ISBLANK:jh,ISERR:zh,ISERROR:$h,ISLOGICAL:Gh,ISNA:Wh,ISNONTEXT:qh,ISNUMBER:Zh,ISTEXT:Yh,NA:Xh});function Qh(e){let t=!1,r=!0;return ir(e,e=>(t=!0,r=r&&e,r)),{foundBoolean:t,result:r}}function Jh(e){let t=!1,r=!1;return ir(e,e=>(t=!0,r=r||e,!r)),{foundBoolean:t,result:r}}const ed={description:v("Logical `and` operator."),args:[a("logical_expression1 (boolean, range<boolean>)",v("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),a("logical_expression2 (boolean, range<boolean>, repeating)",v("More expressions that represent logical values."))],compute:function(...e){const{result:t,foundBoolean:r}=Qh(e);return r?t:new S(vr)},isExported:!0},td={description:v("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},rd={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(Pr(e))return sr(rd.compute,[e,t,r]);return(qt(Vr(e))?t:r)??{value:0}},isExported:!0},nd={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(Pr(e))return sr(nd.compute,[e,t]);return(Vt(Vr(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(Pr(e))return sr(od.compute,[e,t]);return(Vr(e)?.value===w.NotAvailable?t:e)??{value:0}},isExported:!0},sd={description:v("Returns a value depending on multiple logical expressions."),args:[a("condition1 (boolean, range<boolean>)",v("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),a("value1 (any, range)",v("The returned value if condition1 is TRUE.")),a("condition2 (boolean, any, range, repeating)",v("Additional conditions to be evaluated if the previous ones are FALSE.")),a("value2 (any, range, repeating)",v("Additional values to be returned if their corresponding conditions are 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(Pr(e[0]))return sr(sd.compute,e);const t=qt(Vr(e.shift())),r=e.shift();if(t)return r??{value:0}}return new S(v("No match."))},isExported:!0},id={description:v("Returns opposite of provided logical value."),args:[a("logical_expression (boolean)",v("An expression or reference to a cell holding an expression that represents some logical value."))],compute:function(e){return!qt(e)},isExported:!0},ad={description:v("Logical `or` operator."),args:[a("logical_expression1 (boolean, range<boolean>)",v("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),a("logical_expression2 (boolean, range<boolean>, repeating)",v("More expressions that evaluate to logical values."))],compute:function(...e){const{result:t,foundBoolean:r}=Jh(e);return r?t:new S(vr)},isExported:!0},ld={description:v("Returns a value by comparing cases to an expression."),args:[a("expression (number, boolean, string)",v("The value to be checked.")),a("case1 (number, boolean, string)",v("The first case to be checked against expression.")),a("value1 (any)",v("The corresponding value to be returned if case1 matches expression.")),a("case2 (any, repeating)",v("Additional cases to try if the previous ones don't match expression.")),a("value2 (any, repeating)",v("Additional values to be returned if their corresponding cases match expression.")),a('default (any, default="empty")',v("An optional default value to be returned if none of the cases match expression."))],compute:function(e,...t){const r=t.length%2==0?Lt(e):t.pop();for(let r=0;r<t.length;r+=2){const n=t[r];if(n&&Vt(n.value))return n;if(e?.value===n?.value)return t[r+1]||{value:0}}return r||{value:0}},isExported:!0},cd={description:v("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},ud={description:v("Logical `xor` operator."),args:[a("logical_expression1 (boolean, range<boolean>)",v("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),a("logical_expression2 (boolean, range<boolean>, repeating)",v("More expressions that evaluate to logical values."))],compute:function(...e){let t=!1,r=!1;return ir(e,e=>(t=!0,r=r?!e:e,!0)),t?r:new S(vr)},isExported:!0};var hd=Object.freeze({__proto__:null,AND:ed,FALSE:td,IF:rd,IFERROR:nd,IFNA:od,IFS:sd,NOT:id,OR:ad,SWITCH:ld,TRUE:cd,XOR:ud});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("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 dd={DateIs:{today:v("today"),yesterday:v("yesterday"),tomorrow:v("tomorrow"),lastWeek:v("in the past week"),lastMonth:v("in the past month"),lastYear:v("in the past year")},DateIsBefore:{today:v("today"),yesterday:v("yesterday"),tomorrow:v("tomorrow"),lastWeek:v("one week ago"),lastMonth:v("one month ago"),lastYear:v("one year ago")},CriterionError:{notEmptyValue:v("The value must not be empty"),numberValue:v("The value must be a number"),dateValue:v("The value must be a date"),validRange:v("The value must be a valid range"),validFormula:v("The formula must be valid")},Errors:{InvalidRange:v("The range is invalid."),InvalidDataValidationCriterionValue:v("One or more of the provided criteria values are invalid. Please review and correct them."),InvalidNumberOfCriterionValues:v("One or more of the provided criteria values are missing."),Unexpected:v("The rule is invalid for an unknown reason.")}};v("The table zone is invalid for an unknown reason"),v("You cannot create overlapping tables."),v("A table can only be created on a continuous selection."),v("The range is invalid"),v("The range is out of the sheet"),v("Filter button"),v("Header row(s)"),v("Banded rows"),v("First column"),v("Last column"),v("Banded columns"),v("Automatically autofill formulas"),v("Total row"),v("Auto-adjust to formula result"),v("Cannot have filters without a header row"),v("For tables based on array formulas only"),v("No calculations"),v("% of grand total"),v("% of column total"),v("% of row total"),v("% of"),v("% of parent row total"),v("% of parent column total"),v("% of parent total"),v("Difference from"),v("% difference from"),v("Running total"),v("% Running total"),v("Rank smallest to largest"),v("Rank largest to smallest"),v("Index"),v("Displays the value that is entered in the field."),v("Displays values as a percentage of the grand total of all the values or data points in the report."),v("Displays all the values in each column or series as a percentage of the total for the column or series."),v("Displays the value in each row or category as a percentage of the total for the row or category."),v("Displays values as a percentage of the value of the Base item in the Base field."),v("Calculates values as follows:\n(value for the item) / (value for the parent item on rows)"),v("Calculates values as follows:\n(value for the item) / (value for the parent item on columns)"),v("Calculates values as follows:\n(value for the item) / (value for the parent item of the selected Base field)"),v("Displays values as the difference from the value of the Base item in the Base field."),v("Displays values as the percentage difference from the value of the Base item in the Base field."),v("Displays the value for successive items in the Base field as a running total."),v("Calculates the value as a percentage for successive items in the Base field that are displayed as a running total."),v("Displays the rank of selected values in a specific field, listing the smallest item in the field as 1, and each larger value with a higher rank value."),v("Displays the rank of selected values in a specific field, listing the largest item in the field as 1, and each smaller value with a higher rank value."),v("Calculates values as follows:\n((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row Total) x (Grand Column Total))");class fd{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 gd=new fd;function md(e){return gd.get(e)}const pd={normalizeFunctionValue:e=>kt(e,Dl),toValueAndFormat:(e,t)=>({value:kt(e,Dl),format:"dd mmm yyyy"}),toFunctionValue(e){const t=Zt(e,Dl);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},bd={normalizeFunctionValue(e){const t=kt(e,Dl);if(t<1||t>31)throw new S(v("%s is not a valid day of month (it should be a number between 1 and 31)",t));return t},toValueAndFormat:e=>({value:kt(e,Dl),format:"0"}),toFunctionValue:e=>`${e}`},vd={normalizeFunctionValue(e){const t=kt(e,Dl);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||Dl).weekStart)%7;return{value:Dn[r].toString(),format:"@"}},toFunctionValue:e=>`${e}`},yd={normalizeFunctionValue(e){const t=kt(e,Dl);if(t<0||t>53)throw new S(v("%s is not a valid week (it should be a number between 0 and 53)",t));return t},toValueAndFormat:e=>({value:kt(e,Dl),format:"0"}),toFunctionValue:e=>`${e}`},wd={normalizeFunctionValue(e){const t=kt(e,Dl);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:On[kt(e,Dl)-1].toString(),format:"@"}),toFunctionValue:e=>`${e}`},Ed={normalizeFunctionValue:e=>Fn(kt(e,Dl),{locale:Dl,format:"mm/yyyy"}),toValueAndFormat:e=>({value:kt(e,Dl),format:"mmmm yyyy"}),toFunctionValue(e){const t=Zt(e,Dl);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`}},Sd={normalizeFunctionValue(e){const t=kt(e,Dl);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}`},Cd={normalizeFunctionValue(e){const t=kt(e,Dl);return t>3e3?Zt(t,Dl).getFullYear():t},toValueAndFormat:e=>({value:kt(e,Dl),format:"0"}),toFunctionValue:e=>`${e}`},Td={normalizeFunctionValue(e){const t=kt(e,Dl);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}`},Id={normalizeFunctionValue(e){const t=kt(e,Dl);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}`},xd={normalizeFunctionValue(e){const t=kt(e,Dl);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 Rd(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)}}gd.add("day",Rd(pd)).add("year",Rd(Cd)).add("day_of_month",Rd(bd)).add("iso_week_number",Rd(yd)).add("month_number",Rd(wd)).add("month",Rd(Ed)).add("quarter_number",Rd(Sd)).add("day_of_week",Rd(vd)).add("hour_number",Rd(Td)).add("minute_number",Rd(Id)).add("second_number",Rd(xd));const Ad={displayTotals:!0,displayColumnHeaders:!0,displayMeasuresRow:!0,numberOfRows:Number.MAX_VALUE,numberOfColumns:Number.MAX_VALUE},_d={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"],Dd={integer:Od,char:Od,datetime:Od,boolean:["count_distinct","count","bool_and","bool_or"]},Fd={};for(const e in Dd){Fd[e]={};for(const t of Dd[e])Fd[e][t]=_d[t]}const Nd={count:e=>({value:Zi([e]),format:"0"}),count_distinct:e=>({value:As([e]),format:"0"}),bool_and:e=>({value:Qh([e]).result}),bool_or:e=>({value:Jh([e]).result}),max:(e,t)=>Yi([e],t),min:(e,t)=>ji([e],t),avg:(e,t)=>({value:qi([e],t),format:Mt(e)}),sum:(e,t)=>({value:Rs([e],t),format:Mt(e)})};function Md(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 Vd=["date","datetime"];function Ld(e){const[t,r]=e.split(":");return r?{fieldName:t,granularity:r}:{fieldName:t}}function Pd(e,t,r){const n=[e];r&&n.push(`"${r}"`);for(const{field:e,value:r,type:o}of t){if("measure"===e){n.push('"measure"',`"${r}"`);continue}const{granularity:t}=Ld(e),s=Bd(r,{type:o,granularity:t});n.push(`"${e}"`,s)}return n}function kd(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 Ud(e,t){if(null===t||"null"===t)return null;const r="object"==typeof t?t.value:t;if(Vt(r))return r;if("custom"===e.type)return Yt(t)??null;const n="boolean"==typeof t?$t(t).toLocaleLowerCase():$t(t);if("null"===n)return null;if(!$d.contains(e.type))throw new S(v("Field %(field)s is not supported because of its type (%(type)s)",{field:e.displayName,type:e.type}));if("false"===n.toLowerCase())return!1;return $d.get(e.type)(n,e.granularity)}function Hd(e,t){return md(t??"month").normalizeFunctionValue(e)}function Bd(e,t){return null===e?'"null"':Gd.contains(t.type)?Gd.get(t.type)(e,t.granularity):`"${e}"`}function zd(e,t){return md(t??"month").toFunctionValue(e)}const $d=new fd;$d.add("date",Hd).add("datetime",Hd).add("integer",e=>kt(e,Dl)).add("boolean",e=>qt(e)).add("char",e=>$t(e)).add("custom",e=>e);const Gd=new fd;function Wd(e,t){return 0===e.length?t:{...t,format:(t.format||"@")+"* "}}function qd(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 Zd(e,t){const r=t.model.getters.getPivotCellFromPosition(e),n=t.model.getters.getPivotIdFromPosition(e);if(!n||"HEADER"!==r.type)return;const o=t.model.getters.getPivotCoreDefinition(n),s=o.collapsedDomains?.[r.dimension]?[...o.collapsedDomains[r.dimension]]:[],i=s.findIndex(e=>Ae(e,r.domain));-1!==i?s.splice(i,1):s.push(r.domain);const a=o.collapsedDomains?{...o.collapsedDomains}:{COL:[],ROW:[]};a[r.dimension]=s,t.model.dispatch("UPDATE_PIVOT",{pivotId:n,pivot:{...o,collapsedDomains:a}})}function Yd(e,t,r,n,o,s,i){const a=e.style;return{numberOfRows:void 0!==t?kt(t,i):a?.numberOfRows??Ad.numberOfRows,numberOfColumns:void 0!==o?kt(o,i):a?.numberOfColumns??Ad.numberOfColumns,displayTotals:void 0!==r?qt(r):a?.displayTotals??Ad.displayTotals,displayColumnHeaders:void 0!==n?qt(n):a?.displayColumnHeaders??Ad.displayColumnHeaders,displayMeasuresRow:void 0!==s?qt(s):a?.displayMeasuresRow??Ad.displayMeasuresRow}}function jd(e,t){const r=t.getPivotId(e);if(!r)throw new S(v('There is no pivot with id "%s"',e));return r}function Xd(e){if(e.length%2!=0)throw new S(v("Function PIVOT takes an even number of arguments."))}function Kd(e,t,r){const n=[];if("SPREADSHEET"===t.type&&t.dataSet){const{sheetId:r,zone:o}=t.dataSet,s=Go(o),i=e.getters.getRangeFromSheetXC(r,s);if(void 0===i||i.invalidXc||i.invalidSheetName)throw new I;if(e.__originCellPosition&&i.sheetId===e.__originSheetId&&Jo(ss(e.__originCellPosition),o))throw new T;n.push(i)}for(const t of r)if(t.computedBy){const r=e.getters.getMeasureCompiledFormula(t);n.push(...r.dependencies.filter(e=>!e.invalidXc))}const o=e.__originCellPosition;o&&n.length&&(e.updateDependencies?.(o),e.addDependencies?.(o,n))}Gd.add("date",zd).add("datetime",zd).add("integer",e=>`${kt(e,Dl)}`).add("boolean",e=>qt(e)?"TRUE":"FALSE").add("char",e=>`"${$t(e).replace(/"/g,'\\"')}"`).add("custom",e=>"string"==typeof e?`"${e}"`:String(e));const Qd=!0,Jd=[{value:!0,label:v("A1 style (default)")},{value:!1,label:v("R1C1 style")}],ef=[{value:!0,label:v("Approximate match (default)")},{value:!1,label:v("Exact match")}],tf={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."),Jd),a("sheet (string, optional)",v("A string indicating the name of the sheet into which the address points."))],compute:function(e,t,r={value:1},n={value:!0},o){const s=zt(e,this.locale),i=zt(t,this.locale);if(s<1)return new S(Or(s));if(i<1)return new S(Or(i));const a=zt(r,this.locale);if(![1,2,3,4].includes(a))return new S((l=4,c=a,v("The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.",1..toString(),l.toString(),c.toString())));var l,c;let u;if(qt(n)){u=Do(i-1,s-1,{rowFixed:[1,2].includes(a),colFixed:[1,3].includes(a)})}else{u=([1,2].includes(a)?`R${s}`:`R[${s}]`)+([1,3].includes(a)?`C${i}`:`C[${i}]`)}return void 0!==o?mo($t(o),u):u},isExported:!0},rf={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:rr(e.length,1,(e,r)=>({value:t+e+1}))},isExported:!0},nf={description:v("Number of columns in a specified array or range."),args:[a("range (any, range<any>)",v("The range whose column count will be returned."))],compute:function(e){const t=mr(e);return void 0===t[0][0]?new S(v("The range is out of bounds.")):t[0][0].value===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."),ef)],compute:function(e,t,r,n={value:Qd}){const o=Math.trunc(kt(r?.value,this.locale)),s=mr(t);if(1>o||o>s[0].length)return new S(v("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const i=(e,t)=>e[t][0].value,a=s[qt(n.value)?hr(s,e,"nextSmaller","asc",s.length,i):dr(s,e,"wildcard",s.length,i,this.lookupCaches)];return void 0===a?Lt(e):a[o-1]},isExported:!0},sf={description:v("Returns the content of a cell, specified by row and column offset."),args:[a("reference (any, range)",v("The range of cells from which the values are returned.")),a("row (number, default=0)",v("The index of the row to be returned from within the reference range of cells.")),a("column (number, default=0)",v("The index of the column to be returned from within the reference range of cells."))],compute:function(e,t={value:0},r={value:0}){const n=mr(e),o=kt(t.value,this.locale),s=kt(r.value,this.locale);return s<0||s-1>=n.length||o<0||o-1>=n[0].length?new S(v("Index out of range.")):0===o&&0===s?n:0===o?[n[s-1]]:0===s?n.map(e=>[e[o-1]]):n[s-1][o-1]},isExported:!0},af={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)."),Jd)],compute:function(e,t={value:!0}){const r=e?.value?.toString();if(!r)return new I(v("Reference should be defined."));if(!qt(t))return new S(v("R1C1 notation is not supported."));const n=this.__originSheetId,o=this.__originCellPosition;o&&this.updateDependencies?.(o);const s=this.getters.getRangeFromSheetXC(n,r);if(void 0===s||s.invalidXc||s.invalidSheetName)return new I;o&&this.addDependencies?.(o,[s]);const i=[];for(let e=s.zone.left;e<=s.zone.right;e++){const t=[];for(let r=s.zone.top;r<=s.zone.bottom;r++){const n={sheetId:s.sheetId,col:e,row:r};t.push(this.getters.getEvaluatedCell(n))}i.push(t)}return 1===i.length&&1===i[0].length?i[0][0]:i},isExported:!0},lf={description:v("Look up a value."),args:[a("search_key (string, number, boolean)",v("The value to search for. For example, 42, 'Cats', or I24.")),a("search_array (any, range)",v("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")),a("result_range (any, range, optional)",v("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method."))],compute:function(e,t,r){const n=mr(t),o=mr(r);let s=n.length,i=n[0].length;const a=i>=s,l=a?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=hr(n,e,"nextSmaller","asc",a?i:s,l);return-1===c||a&&void 0===n[0][c]||!a&&void 0===n[c][i-1]?Lt(e):0===o[0].length?a?n[s-1][c]:n[c][i-1]:(s=o.length,i=o[0].length,1!==s&&1!==i?new S(v("The result_range must be a single row or a single column.")):s>1?c>s-1?new S(v("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",c+1)):o[c][0]:c>i-1?new S(v("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",c+1)):o[0][c])},isExported:!0},cf={description:v("Position of item in range that matches value."),args:[a("search_key (string, number, boolean)",v("The value to search for. For example, 42, 'Cats', or I24.")),a("range (any, range)",v("The one-dimensional array to be searched.")),a("search_type (number, default=1)",v("The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order."),[{value:1,label:v("Ascending order (default)")},{value:0,label:v("Exact match")},{value:-1,label:v("Descending order")}])],compute:function(e,t,r={value:1}){let n=kt(r,this.locale);const o=mr(t),s=o.length,i=o[0].length;if(1!==s&&1!==i)return new S(v("The range must be a single row or a single column."));let a=-1;const l=1===s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=1===s?o[0].length:o.length;switch(n=Math.sign(n),n){case 1:a=hr(o,e,"nextSmaller","asc",c,l);break;case 0:a=dr(o,e,"wildcard",c,l,this.lookupCaches);break;case-1:a=hr(o,e,"nextGreater","desc",c,l)}return 1===s&&void 0===o[0][a]||1!==s&&void 0===o[a]?Lt(e):a+1},isExported:!0},uf={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:rr(1,e[0].length,(e,r)=>({value:t+r+1}))},isExported:!0},hf={description:v("Number of rows in a specified array or range."),args:[a("range (any, range<any>)",v("The range whose row count will be returned."))],compute:function(e){const t=mr(e);return void 0===t[0][0]?new S(v("The range is out of bounds.")):t[0][0].value===w.InvalidReference?t[0][0]:t[0].length},isExported:!0},df={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."),ef)],compute:function(e,t,r,n={value:Qd}){const o=Math.trunc(kt(r?.value,this.locale)),s=mr(t);if(1>o||o>s.length)return new S(v("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const i=(e,t)=>e[0][t].value,a=qt(n.value)?hr(s,e,"nextSmaller","asc",s[0].length,i):dr(s,e,"wildcard",s[0].length,i,this.lookupCaches),l=s[o-1][a];return void 0===l?Lt(e):l},isExported:!0},ff={0:"strict",1:"nextGreater","-1":"nextSmaller",2:"wildcard"},gf={description:v("Search a range for a match and return the corresponding item from a second range."),args:[a("search_key (string,number,boolean)",v("The value to search for.")),a("lookup_range (any, range)",v("The range to consider for the search. Should be a single column or a single row.")),a("return_range (any, range)",v("The range containing the return value. Should have the same dimensions as lookup_range.")),a("if_not_found (any, optional)",v("If a valid match is not found, return this value.")),a("match_mode (any, default=0)",v("Specifies how to match search_key with the items in lookup_range. "),[{value:0,label:v("Exact match (default)")},{value:-1,label:v("Exact match or next smaller item")},{value:1,label:v("Exact match or next larger item")},{value:2,label:v("Wildcard character match")}]),a("search_mode (any, default=1)",v("Specifies the search mode to use. By default, a first to last search will be used."),[{value:1,label:v("Search first to last (default)")},{value:-1,label:v("Search last to first")},{value:2,label:v("Binary search (sorted ascending order)")},{value:-2,label:v("Binary search (sorted descending order)")}])],compute:function(e,t,r,n,o={value:0},s={value:1}){const i=Math.trunc(kt(o.value,this.locale)),a=Math.trunc(kt(s.value,this.locale)),l=mr(t),c=mr(r);if(1!==l.length&&1!==l[0].length)return new S(v("lookup_range should be either a single row or single column."));if(![1,-1,2,-2].includes(a))return new S(v("search_mode should be a value in [-1, 1, -2, 2]."));if(![-1,0,1,2].includes(i))return new S(v("match_mode should be a value in [-1, 0, 1, 2]."));const u=1===l.length?"col":"row";if(2===i&&[-2,2].includes(a))return new S(v("The search and match mode combination is not supported for XLOOKUP evaluation."));if("col"===u?c[0].length!==l[0].length:c.length!==l.length)return new S(v("return_range should have the same dimensions as lookup_range."));const h="col"===u?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,d="col"===u?l[0].length:l.length,f=ff[i],g=-1===a,m=2===a||-2===a?hr(l,e,f,2===a?"asc":"desc",d,h):dr(l,e,f,d,h,this.lookupCaches,g);return-1!==m?"col"===u?c.map(e=>[e[m]]):[c[m]]:void 0===n?Lt(e):[[n]]},isExported:!0},mf={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)",v("Field name.")),a("domain_value (number,string,boolean,repeating)",v("Value."))],compute:function(e,t,...r){const n=$t(e),o=$t(t),s=jd(n,this.getters);!function(e,t,r){const{measures:n}=r.getPivotCoreDefinition(e);if(!n.find(e=>e.id===t)){const e=`(${n.map(e=>e.id).join(", ")})`;throw new S(v("The argument %s is not a valid measure. Here are the measures: %s",t,e))}}(s,o,this.getters),Xd(r);const i=this.getters.getPivot(s),a=this.getters.getPivotCoreDefinition(s);Kd(this,a,a.measures.filter(e=>e.id===o)),i.init({reload:i.needsReevaluation});const l=i.assertIsValid({throwOnError:!1});if(l)return l;if(!i.areDomainArgsFieldsValid(r)){const e=v("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${n})`);return{value:w.GenericError,message:v("Dimensions don't match the pivot definition")+". "+e}}const c=i.parseArgsToPivotDomain(r);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(s)?.trackValue(o,c),i.getPivotCellValueAndFormat(o,c)}},pf={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)",v("Field name.")),a("domain_value (number,string,value,repeating)",v("Value."))],compute:function(e,...t){const r=$t(e),n=jd(r,this.getters);Xd(t);const o=this.getters.getPivot(n);Kd(this,this.getters.getPivotCoreDefinition(n),[]),o.init({reload:o.needsReevaluation});const s=o.assertIsValid({throwOnError:!1});if(s)return s;if(!o.areDomainArgsFieldsValid(t)){const e=v("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${r})`);return{value:w.GenericError,message:v("Dimensions don't match the pivot definition")+". "+e}}const i=o.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(n)?.trackHeader(i);const a=i.at(-1);if("measure"===a?.field)return o.getPivotMeasureValue($t(a.value),i);const{value:l,format:c}=o.getPivotHeaderValueAndFormat(i);return{value:l,format:a&&"measure"!==a.field&&"false"!==a.value?c:void 0}}},bf={description:v("Get a pivot table."),args:[a("pivot_id (string)",v("ID of the pivot.")),a("row_count (number, optional)",v("number of rows")),a("include_total (boolean, default=TRUE)",v("Whether to include total/sub-totals or not.")),a("include_column_titles (boolean, default=TRUE)",v("Whether to include the column titles or not.")),a("column_count (number, optional)",v("number of columns")),a("include_measure_titles (boolean, default=TRUE)",v("Whether to include the measure titles row or not."))],compute:function(e,t,r,n,o,s){const i=jd($t(e),this.getters),a=this.getters.getPivot(i),l=this.getters.getPivotCoreDefinition(i),c=Yd(l,t,r,n,o,s,this.locale);if(c.numberOfRows<0)return new S(v("The number of rows must be positive."));if(c.numberOfColumns<0)return new S(v("The number of columns must be positive."));Kd(this,l,l.measures),a.init({reload:a.needsReevaluation});const u=a.assertIsValid({throwOnError:!1});if(u)return u;const h=a.getCollapsedTableStructure();if(h.numberOfCells>1e5)return new S(function(e,t){const r=Fn(e,{format:"0,00",locale:t});return v("Oops—this pivot table is quite large (%s cells). Try simplifying it using the side panel.",r)}(h.numberOfCells,this.locale));const d=h.getPivotCells(c);let f=0;c.displayColumnHeaders&&(f=h.columns.length-1),c.displayMeasuresRow&&f++;const g=this.getters.getPivotName(i),m=Math.min(f+c.numberOfRows,d[0].length);if(0===m)return[[{value:g}]];const p=Math.min(1+c.numberOfColumns,d.length),b=[];for(const e of le(0,p)){b[e]=[];for(const t of le(0,m)){const r=d[e][t];switch(r.type){case"EMPTY":b[e].push({value:""});break;case"HEADER":const t=a.getPivotHeaderValueAndFormat(r.domain);b[e].push(Wd(r.domain,t));break;case"MEASURE_HEADER":b[e].push(a.getPivotMeasureValue(r.measure,r.domain));break;case"VALUE":b[e].push(a.getPivotCellValueAndFormat(r.measure,r.domain))}}}return(c.displayColumnHeaders||c.displayMeasuresRow)&&(b[0][0]={value:g}),b}},vf={description:v("Returns a range reference shifted by a specified number of rows and columns from a starting cell reference."),args:[a("cell_reference (meta, range<meta>)",v("The starting point from which to count the offset rows and columns.")),a("offset_rows (number)",v("The number of rows to offset by.")),a("offset_columns (number)",v("The number of columns to offset by.")),a("height (number, default='height of cell_reference')",v("The number of rows of the range to return starting at the offset target.")),a("width (number, default='width of cell_reference')",v("The number of columns of the range to return starting at the offset target."))],compute:function(e,t,r,n,o){if(Vt(e[0][0].value))return e[0][0];const s=e[0][0].value;if(!s)return new S("In this context, the function OFFSET needs to have a cell or range in parameter.");const i=Bo(s);let a=e[0].length,l=e.length;if(n){const e=kt(n,this.locale);if(e<1)return new S(v("Height value is %(_height)s. It should be greater than or equal to 1.",{_height:e}));a=e}if(o){const e=kt(o,this.locale);if(e<1)return new S(v("Width value is %(_width)s. It should be greater than or equal to 1.",{_width:e}));l=e}const{sheetName:c}=go(s),u=c&&this.getters.getSheetIdByName(c)||this.getters.getActiveSheetId(),h=kt(t,this.locale),d=kt(r,this.locale),f=this.__originCellPosition;f&&this.updateDependencies?.(f);const g=i.left+d,m=i.top+h;if(g<0||m<0)return new I(v("OFFSET evaluates to an out of bounds range."));const p={left:g,top:m,right:g+l-1,bottom:m+a-1},b=this.getters.getRangeFromZone(u,p);return b.invalidXc||b.invalidSheetName?new I:(f&&this.addDependencies?.(f,[b]),rr(l,a,(e,t)=>this.getters.getEvaluatedCell({sheetId:u,col:g+e,row:m+t})))}};var yf=Object.freeze({__proto__:null,ADDRESS:tf,COLUMN:rf,COLUMNS:nf,HLOOKUP:of,INDEX:sf,INDIRECT:af,LOOKUP:lf,MATCH:cf,OFFSET:vf,PIVOT:bf,PIVOT_HEADER:pf,PIVOT_VALUE:mf,ROW:uf,ROWS:hf,VLOOKUP:df,XLOOKUP:gf});const wf={description:v("Sum of two numbers."),args:[a("value1 (number)",v("The first addend.")),a("value2 (number)",v("The second addend."))],compute:function(e,t){return{value:kt(e,this.locale)+kt(t,this.locale),format:e?.format||t?.format}}},Ef={description:v("Concatenation of two values."),args:[a("value1 (string)",v("The value to which value2 will be appended.")),a("value2 (string)",v("The value to append to value1."))],compute:function(e,t){return $t(e)+$t(t)},isExported:!0},Sf={description:v("One number divided by another."),args:[a("dividend (number)",v("The number to be divided.")),a("divisor (number)",v("The number to divide by."))],compute:function(e,t){const r=kt(t,this.locale);return 0===r?new _(v("The divisor must be different from zero.")):{value:kt(e,this.locale)/r,format:e?.format||t?.format}}};function Cf(e){return void 0===e||null===e.value}const Tf={number:0,string:"",boolean:!1};function If(e,t,r=2e-16){return Math.abs(e-t)<r}const xf={description:v("Equal."),args:[a("value1 (string, number, boolean)",v("The first value.")),a("value2 (string, number, boolean)",v("The value to test against value1 for equality."))],compute:function(e,t){if(Vt(e?.value))return e;if(Vt(t?.value))return t;let r=Cf(e)?Tf[typeof t?.value]:e?.value,n=Cf(t)?Tf[typeof e?.value]:t?.value;return"string"==typeof r&&(r=r.toUpperCase()),"string"==typeof n&&(n=n.toUpperCase()),"number"==typeof r&&"number"==typeof n?{value:If(r,n)}:{value:r===n}}};function Rf(e,t,r){if(Vt(e?.value))return e;if(Vt(t?.value))return t;let n=Cf(e)?Tf[typeof t?.value]:e?.value,o=Cf(t)?Tf[typeof e?.value]:t?.value;"number"!=typeof n&&(n=$t(n).toUpperCase()),"number"!=typeof o&&(o=$t(o).toUpperCase());const s=typeof n,i=typeof o;return"string"===s&&"number"===i?{value:!0}:"string"===i&&"number"===s?{value:!1}:{value:r(n,o)}}const Af={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 Rf(e,t,(e,t)=>"number"==typeof e&&"number"==typeof t?!If(e,t)&&e>t:e>t)}},_f={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 Rf(e,t,(e,t)=>"number"==typeof e&&"number"==typeof t?If(e,t)||e>t:e>=t)}},Of={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=_f.compute.bind(this)(e,t);return Vt(r.value)?r:{value:!r.value}}},Df={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=Af.compute.bind(this)(e,t);return Vt(r.value)?r:{value:!r.value}}},Ff={description:v("Difference of two numbers."),args:[a("value1 (number)",v("The minuend, or number to be subtracted from.")),a("value2 (number)",v("The subtrahend, or number to subtract from value1."))],compute:function(e,t){return{value:kt(e,this.locale)-kt(t,this.locale),format:e?.format||t?.format}}},Nf={description:v("Product of two numbers"),args:[a("factor1 (number)",v("The first multiplicand.")),a("factor2 (number)",v("The second multiplicand."))],compute:function(e,t){return{value:kt(e,this.locale)*kt(t,this.locale),format:e?.format||t?.format}}},Mf={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=xf.compute.bind(this)(e,t);return Vt(r.value)?r:{value:!r.value}}},Vf={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 vi.compute.bind(this)(e,t)}},Lf={description:v("A number with the sign reversed."),args:[a("value (number)",v("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],compute:function(e){return{value:-kt(e,this.locale),format:e?.format}}},Pf={description:v("Value interpreted as a percentage."),args:[a("percentage (number)",v("The value to interpret as a percentage."))],compute:function(e){return kt(e,this.locale)/100}},kf={description:v("A specified number, unchanged."),args:[a("value (any)",v("The number to return."))],compute:function(e={value:null}){return e}};var Uf=Object.freeze({__proto__:null,ADD:wf,CONCAT:Ef,DIVIDE:Sf,EQ:xf,GT:Af,GTE:_f,LT:Of,LTE:Df,MINUS:Ff,MULTIPLY:Nf,NE:Mf,POW:Vf,UMINUS:Lf,UNARY_PERCENT:Pf,UPLUS:kf});const Hf=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),Bf={transform:e=>e,inverseTransform:e=>e},zf=1e-10,$f=.0254,Gf=$f/72,Wf=.3048,qf=.9144,Zf=1609.34,Yf=1852,jf=946073047258e4,Xf={g:{...Bf,category:"weight"},u:{...Hf(166053e-29),category:"weight"},grain:{...Hf(.0647989),category:"weight"},ozm:{...Hf(28.3495),category:"weight"},lbm:{...Hf(453.592),category:"weight"},stone:{...Hf(6350.29),category:"weight"},sg:{...Hf(14593.90294),category:"weight"},cwt:{...Hf(45359.237),category:"weight"},uk_cwt:{...Hf(50802.3),category:"weight"},ton:{...Hf(907184.74),category:"weight"},uk_ton:{...Hf(1016046.9),category:"weight"},m:{...Bf,category:"distance"},km:{...Hf(1e3),category:"distance"},ang:{...Hf(zf),category:"distance"},Picapt:{...Hf(Gf),category:"distance"},pica:{...Hf($f/6),category:"distance"},in:{...Hf($f),category:"distance"},ft:{...Hf(Wf),category:"distance"},yd:{...Hf(qf),category:"distance"},ell:{...Hf(1.143),category:"distance"},mi:{...Hf(Zf),category:"distance"},survey_mi:{...Hf(1609.34),category:"distance"},Nmi:{...Hf(Yf),category:"distance"},ly:{...Hf(jf),category:"distance"},parsec:{...Hf(0x6da012f95c9fd0),category:"distance"},sec:{...Bf,category:"time"},min:{...Hf(60),category:"time"},hr:{...Hf(3600),category:"time"},day:{...Hf(86400),category:"time"},yr:{...Hf(31556952),category:"time"},Pa:{...Bf,category:"pressure"},bar:{...Hf(1e5),category:"pressure"},mmHg:{...Hf(133.322),category:"pressure"},Torr:{...Hf(133.322),category:"pressure"},psi:{...Hf(6894.76),category:"pressure"},atm:{...Hf(101325),category:"pressure"},N:{...Bf,category:"force"},dyn:{...Hf(1e-5),category:"force"},pond:{...Hf(.00980665),category:"force"},lbf:{...Hf(4.44822),category:"force"},J:{...Bf,category:"energy"},eV:{...Hf(160218e-24),category:"energy"},e:{...Hf(1e-7),category:"energy"},flb:{...Hf(1.3558179483),category:"energy"},c:{...Hf(4.184),category:"energy"},cal:{...Hf(4.1868),category:"energy"},BTU:{...Hf(1055.06),category:"energy"},Wh:{...Hf(3600),category:"energy"},HPh:{...Hf(2684520),category:"energy"},W:{...Bf,category:"power"},PS:{...Hf(735.499),category:"power"},HP:{...Hf(745.7),category:"power"},T:{...Bf,category:"magnetism"},ga:{...Hf(1e-4),category:"magnetism"},K:{...Bf,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:{...Hf(5/9),category:"temperature"},Reau:{transform:e=>1.25*e+273.15,inverseTransform:e=>(e-273.15)/1.25,category:"temperature"},"m^3":{...Bf,category:"volume",order:3},"ang^3":{...Hf(Math.pow(zf,3)),category:"volume",order:3},"Picapt^3":{...Hf(Math.pow(Gf,3)),category:"volume",order:3},tsp:{...Hf(492892e-11),category:"volume"},tspm:{...Hf(5e-6),category:"volume"},tbs:{...Hf(14786764825785619e-21),category:"volume"},"in^3":{...Hf(Math.pow($f,3)),category:"volume",order:3},oz:{...Hf(295735295625e-16),category:"volume"},cup:{...Hf(237e-6),category:"volume"},pt:{...Hf(.0004731765),category:"volume"},uk_pt:{...Hf(568261e-9),category:"volume"},qt:{...Hf(.0009463529),category:"volume"},l:{...Hf(.001),category:"volume"},uk_qt:{...Hf(.0011365225),category:"volume"},gal:{...Hf(.0037854118),category:"volume"},uk_gal:{...Hf(.00454609),category:"volume"},"ft^3":{...Hf(Math.pow(Wf,3)),category:"volume",order:3},bushel:{...Hf(.0352390704),category:"volume"},barrel:{...Hf(.158987295),category:"volume"},"yd^3":{...Hf(Math.pow(qf,3)),category:"volume",order:3},MTON:{...Hf(1.13267386368),category:"volume"},GRT:{...Hf(2.83168),category:"volume"},"mi^3":{...Hf(Math.pow(Zf,3)),category:"volume",order:3},"Nmi^3":{...Hf(Math.pow(Yf,3)),category:"volume",order:3},"ly^3":{...Hf(Math.pow(jf,3)),category:"volume",order:3},"m^2":{...Bf,category:"area",order:2},"ang^2":{...Hf(Math.pow(zf,2)),category:"area",order:2},"Picapt^2":{...Hf(Math.pow(Gf,2)),category:"area",order:2},"in^2":{...Hf(Math.pow($f,2)),category:"area",order:2},"ft^2":{...Hf(Math.pow(Wf,2)),category:"area",order:2},"yd^2":{...Hf(Math.pow(qf,2)),category:"area",order:2},ar:{...Hf(100),category:"area"},Morgen:{...Hf(2500),category:"area"},uk_acre:{...Hf(4046.8564224),category:"area"},us_acre:{...Hf(4046.8726098743),category:"area"},ha:{...Hf(1e4),category:"area"},"mi^2":{...Hf(Math.pow(Zf,2)),category:"area",order:2},"Nmi^2":{...Hf(Math.pow(Yf,2)),category:"area",order:2},"ly^2":{...Hf(Math.pow(jf,2)),category:"area",order:2},bit:{...Bf,category:"information"},byte:{...Hf(8),category:"information"},"m/s":{...Bf,category:"speed"},"m/hr":{...Hf(1/3600),category:"speed"},"km/hr":{...Hf(1/3.6),category:"speed"},mph:{...Hf(.44704),category:"speed"},kn:{...Hf(.5144444444),category:"speed"},admkn:{...Hf(.5147733333),category:"speed"}},Kf={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"},Qf={"":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)},Jf={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")},eg=Object.entries(Xf).map(([e,t])=>({value:e,label:tg(t.category)}));function tg(e){return Jf[e]??""}function rg(e){for(const[t,r]of Object.entries(Qf)){if(t&&!e.startsWith(t))continue;const n=e.slice(t.length);let o=Xf[n];if(!o&&Kf[n]&&(o=Xf[Kf[n]]),o)return{...o,factor:o.order?Math.pow(r,o.order):r}}}const ng={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"),eg),a("end_unit (string)",v("The unit of measure into which to convert value"),eg)],compute:function(e,t,r){const n=kt(e,this.locale),o=$t(t),s=$t(r),i=rg(o),a=rg(s);return i?a?i.category!==a.category?{value:w.GenericError,message:v("Incompatible units of measure ('%s' vs '%s')",tg(i.category),tg(a.category))}:{value:a.inverseTransform(i.factor*i.transform(n))/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')",o)}},isExported:!0};var og=Object.freeze({__proto__:null,CONVERT:ng});const sg=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,ig=[{value:0,label:v("Case-sensitive (default)")},{value:1,label:v("Case-insensitive")}],ag=[{value:0,label:v("Don't match to end (default)")},{value:1,label:v("Match to end")}],lg={description:v("Gets character associated with number."),args:[a("table_number (number)",v("The number of the character to look up from the current Unicode table in decimal format."))],compute:function(e){const t=Math.trunc(kt(e,this.locale));return t<1?new S(v("The table_number (%s) is out of range.",t)):String.fromCharCode(t)},isExported:!0},cg={description:v("Remove non-printable characters from a piece of text."),args:[a("text (string)",v("The text whose non-printable characters are to be removed."))],compute:function(e){const t=$t(e);let r="";for(const e of t)e&&e.charCodeAt(0)>31&&(r+=e);return r},isExported:!0},ug={description:v("Appends strings to one another."),args:[a("string1 (string, range<string>)",v("The initial string.")),a("string2 (string, range<string>, repeating)",v("More strings to append in sequence."))],compute:function(...e){return Jt(e,(e,t)=>e+$t(t),"")},isExported:!0},hg={description:v("Tests whether two strings are identical."),args:[a("string1 (string)",v("The first string to compare.")),a("string2 (string)",v("The second string to compare."))],compute:function(e,t){return $t(e)===$t(t)},isExported:!0},dg={description:v("First position of string found in text, case-sensitive."),args:[a("search_for (string)",v("The string to look for within text_to_search.")),a("text_to_search (string)",v("The text to search for the first occurrence of search_for.")),a("starting_at (number, default=1)",v("The character within text_to_search at which to start the search."))],compute:function(e,t,r={value:1}){const n=$t(e),o=$t(t),s=kt(r,this.locale);if(""===o)return new S(v("The text_to_search must be non-empty."));if(s<1)return new S(v("The starting_at (%s) must be greater than or equal to 1.",s));const i=o.indexOf(n,s-1);return-1===i?new S(v("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",n,o)):i+1},isExported:!0},fg={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_array1 (string, range<string>)",v("The value or values to be appended using delimiter.")),a("value_or_array2 (string, range<string>, repeating)",v("More values to be appended using delimiter."))],compute:function(e,...t){const r=$t(e);return Jt(t,(e,t)=>(e?e+r:"")+$t(t),"")}},gg={description:v("Substring from beginning of specified string."),args:[a("text (string)",v("The string from which the left portion will be returned.")),a("number_of_characters (number, optional)",v("The number of characters to return from the left side of string."))],compute:function(e,...t){const r=t.length?kt(t[0],this.locale):1;return r<0?new S(v("The number_of_characters (%s) must be positive or null.",r)):$t(e).substring(0,r)},isExported:!0},mg={description:v("Length of a string."),args:[a("text (string)",v("The string whose length will be returned."))],compute:function(e){return $t(e).length},isExported:!0},pg={description:v("Converts a specified string to lowercase."),args:[a("text (string)",v("The string to convert to lowercase."))],compute:function(e){return $t(e).toLowerCase()},isExported:!0},bg={description:v("A segment of a string."),args:[a("text (string)",v("The string to extract a segment from.")),a("starting_at (number)",v("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),a("extract_length (number)",v("The length of the segment to extract."))],compute:function(e,t,r){const n=$t(e),o=kt(t,this.locale),s=kt(r,this.locale);return o<1?new S(v("The starting_at argument (%s) must be positive greater than one.",o.toString())):s<0?new S(v("The extract_length argument (%s) must be positive or null.",s)):n.slice(o-1,o+s-1)},isExported:!0},vg={description:v("Capitalizes each word in a specified string."),args:[a("text_to_capitalize (string)",v("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase."))],compute:function(e){return $t(e).replace(sg,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},yg={description:v("Extract text from a string based on the supplied regular expression."),args:[a("text (string)",v("The string on which you want to extract text.")),a("pattern (string)",v("The regular expression pattern to match against the text.")),a("return_mode (number, default=0)",v("0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array."),[{value:0,label:v("First match")},{value:1,label:v("All matches")},{value:2,label:v("Capture groups of first match")}]),a("case_sensitivity (number, default=0)",v("Whether the match is case-sensitive."),[{value:0,label:v("Case-sensitive")},{value:1,label:v("Case-insensitive")}])],compute:function(e,t,r={value:0},n={value:0}){const o=$t(e),s=$t(t),i=kt(r,this.locale),a=kt(n,this.locale);if(""===o||""===s)return{value:""};if(i<0||i>2)return new S(v("The return_mode (%s) must be 0, 1 or 2.",i));if(0!==a&&1!==a)return new S(v("The case_sensitivity (%s) must be 0 or 1.",a));const l=new RegExp(s,1===a?"gi":"g"),c=[...o.matchAll(l)];return 0===c.length?{value: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},wg={description:v("Replaces part of a text string with different text."),args:[a("text (string)",v("The text, a part of which will be replaced.")),a("position (number)",v("The position where the replacement will begin (starting from 1).")),a("length (number)",v("The number of characters in the text to be replaced.")),a("new_text (string)",v("The text which will be inserted into the original text."))],compute:function(e,t,r,n){const o=kt(t,this.locale);if(o<1)return new S(v("The position (%s) must be greater than or equal to 1.",o));const s=$t(e),i=kt(r,this.locale),a=$t(n);return s.substring(0,o-1)+a+s.substring(o-1+i)},isExported:!0},Eg={description:v("A substring from the end of a specified string."),args:[a("text (string)",v("The string from which the right portion will be returned.")),a("number_of_characters (number, optional)",v("The number of characters to return from the right side of string."))],compute:function(e,...t){const r=t.length?kt(t[0],this.locale):1;if(r<0)return new S(v("The number_of_characters (%s) must be positive or null.",r));const n=$t(e),o=n.length;return n.substring(o-r,o)},isExported:!0},Sg={description:v("First position of string found in text, ignoring case."),args:[a("search_for (string)",v("The string to look for within text_to_search.")),a("text_to_search (string)",v("The text to search for the first occurrence of search_for.")),a("starting_at (number, default=1)",v("The character within text_to_search at which to start the search."))],compute:function(e,t,r={value:1}){const n=$t(e).toLowerCase(),o=$t(t).toLowerCase(),s=kt(r,this.locale);if(""===o)return{value: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=o.indexOf(n,s-1);return-1===i?{value:w.GenericError,message:v("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",n,o)}:{value:i+1}},isExported:!0},Cg=!0,Tg=!0,Ig={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:Cg},n={value:Tg}){const o=$t(e),s=te($t(t)),i=qt(r),a=qt(n);if(s.length<=0)return new S(v("The delimiter (%s) must be not be empty.",s));const l=i?new RegExp(`[${s}]`,"g"):new RegExp(s,"g");let c=o.split(l);return a&&(c=c.filter(e=>""!==e)),or([c])},isExported:!1},xg={description:v("Replaces existing text with new text in a string."),args:[a("text_to_search (string)",v("The text within which to search and replace.")),a("search_for (string)",v("The string to search for within text_to_search.")),a("replace_with (string)",v("The string that will replace search_for.")),a("occurrence_number (number, optional)",v("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced."))],compute:function(e,t,r,n){const o=kt(n,this.locale);if(o<0)return new S(v("The occurrenceNumber (%s) must be positive or null.",o));const s=$t(e),i=$t(t);if(""===i)return s;const a=$t(r),l=new RegExp(te(i),"g");if(0===o)return s.replace(l,a);let c=0;return s.replace(l,e=>++c===o?a:e)},isExported:!0},Rg={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("text1 (string, range<string>)",v("Any text item. This could be a string, or an array of strings in a range.")),a("text2 (string, range<string>, repeating)",v("Additional text item(s)."))],compute:function(e,t={value:true},...r){const n=$t(e),o=qt(t);let s=0;return Jt(r,(e,t)=>o&&""===$t(t)?e:(s++?e+n:"")+$t(t),"")},isExported:!0},Ag=!1,_g={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."),ig),a(`pad_with (string, default="${w.NotAvailable}")`,v("The value to use for padding empty cells."))],compute:function(e,t,r,n={value:Ag},o={value:0},s=new x){const i=$t(e);if(i.length<=0)return new S(v("No text to split."));if(void 0===t&&void 0===r)return new S(v("At least one delimiter must be provided."));const a=mr(t).flat().map(e=>te($t(e))),l=mr(r).flat().map(e=>te($t(e)));if(a.some(e=>""===e)||l.some(e=>""===e))return new S(v("The delimiters cannot be empty values."));const c=qt(n),u=kt(o,this.locale);if(![0,1].includes(u))return new S(v("match_mode should be a value of 0 or 1."));const h=[],d=1===u?"gi":"g",f=l.filter(e=>!a.includes(e));let g=f.length?i.split(new RegExp(f.join("|"),d)):[i];c&&(g=g.filter(e=>""!==e));const m=new RegExp(a.join("|"),d);for(const e of g){let t=a.length?e.split(m):[e];c&&(t=t.filter(e=>""!==e)),h.push(t.map(e=>({value:e})))}const p=Math.max(...h.map(e=>e.length));for(const e of h)for(;e.length<p;)e.push(s);return or(h)},isExported:!0},Og={description:v("Removes space characters."),args:[a("text (string)",v("The text or reference to a cell containing text to be trimmed."))],compute:function(e){return $e($t(e))},isExported:!0},Dg={description:v("Converts a specified string to uppercase."),args:[a("text (string)",v("The string to convert to uppercase."))],compute:function(e){return $t(e).toUpperCase()},isExported:!0},Fg={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 Fn(kt(e,this.locale),{format:$t(t),locale:this.locale})},isExported:!0},Ng={description:v("Converts a string to a numeric value."),args:[a("value (number)",v("the string to be converted"))],compute:function(e){return kt(e,this.locale)},isExported:!0},Mg={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."),ig),a("match_end (number, default=0))",v("Whether to treat the end of text as a delimiter."),ag),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},n={value:0},o={value:0},s=new x){const i=$t(e),a=kt(r,this.locale),l=kt(n,this.locale),c=kt(o,this.locale);if(0===a)return new S(v("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new S(v("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new S(v("match_end should have a value of 0 or 1."));const u=$t(t);if(""===u)return Math.sign(a)>0?{value:i}:{value:""};const h=1===l?"gi":"g",d=te(u),f=new RegExp(d,h);let g=[...i.matchAll(f)].map(e=>e.index+d.length);if(a<0&&(g=g.reverse()),c&&Math.abs(a)===g.length+1)return Math.sign(a)>0?{value:""}:{value:i};const m=g[Math.abs(a)-1];return void 0===m?s:{value:i.substring(m)}},isExported:!0},Vg={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."),ig),a("match_end (number, default=0))",v("Whether to match a delimiter against the end of the text."),ag),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},n={value:0},o={value:0},s=new x){const i=$t(e),a=kt(r,this.locale),l=kt(n,this.locale),c=kt(o,this.locale);if(0===a)return new S(v("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new S(v("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new S(v("match_end should have a value of 0 or 1."));const u=$t(t);if(""===u)return Math.sign(a)>0?{value:""}:{value:i};const h=1===l?"gi":"g",d=te(u),f=new RegExp(d,h);let g=[...i.matchAll(f)].map(e=>e.index+d.length);if(a<0&&(g=g.reverse()),c&&Math.abs(a)===g.length+1)return Math.sign(a)>0?{value:i}:{value:""};const m=g[Math.abs(a)-1];return void 0===m?s:{value:i.substring(0,m-u.length)}},isExported:!0};var Lg=Object.freeze({__proto__:null,CHAR:lg,CLEAN:cg,CONCATENATE:ug,EXACT:hg,FIND:dg,JOIN:fg,LEFT:gg,LEN:mg,LOWER:pg,MID:bg,PROPER:vg,REGEXEXTRACT:yg,REPLACE:wg,RIGHT:Eg,SEARCH:Sg,SPLIT:Ig,SUBSTITUTE:xg,TEXT:Fg,TEXTAFTER:Mg,TEXTBEFORE:Vg,TEXTJOIN:Rg,TEXTSPLIT:_g,TRIM:Og,UPPER:Dg,VALUE:Ng});const Pg={description:v("Creates a hyperlink in a cell."),args:[a("url (string)",v("The full URL of the link enclosed in quotation marks.")),a("link_label (string, optional)",v("The text to display in the cell, enclosed in quotation marks."))],compute:function(e,t){const r=$t(e).trim(),n=$t(t)||r;return""===r?n:pe(n,r)},isExported:!0};var kg=Object.freeze({__proto__:null,HYPERLINK:Pg});const Ug=/^[A-Z0-9\_\.]+$/;class Hg 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(),!Ug.test(e))throw new Error(v("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const r=function(e,t){let r=0,n=0,o=0,s=0;for(const e of t.args)r++,e.optional||e.repeating||e.default||n++,e.repeating&&o++,(e.optional||e.default)&&s++;const i=t;return i.minArgRequired=n,i.maxArgPossible=o?1/0:r,i.nbrArgRepeating=o,i.nbrArgOptional=s,i.hidden=t.hidden||!1,i.name=e,i}(e,t);return function(e){if(e.nbrArgRepeating&&e.nbrArgOptional>=e.nbrArgRepeating)throw new Error(`Function ${e.name} has more optional arguments than repeatable ones.`);let t=!1,r=!1;for(const n of e.args){if(n.type.some(e=>u.includes(e))&&n.type.some(e=>!u.includes(e)))throw new Error(`Function ${e.name} has a mix of META and non-META types in the same argument: ${n.type}.`);if(n.repeating){if(!r&&t)throw new Error(`Function ${e.name} has non-consecutive repeating arguments. All repeating arguments must be declared consecutively.`);t=!0,r=!0}else r=!1}}(r),this.mapping[e]=wr(r),super.replace(e,r),this}}const Bg=new Hg,zg=[{name:v("Array"),functions:cn},{name:v("Database"),functions:_l},{name:v("Date"),functions:yu},{name:v("Filter"),functions:Ou},{name:v("Financial"),functions:Uh},{name:v("Info"),functions:Kh},{name:v("Lookup"),functions:yf},{name:v("Logical"),functions:hd},{name:v("Math"),functions:Gi},{name:v("Misc"),functions:eo},{name:v("Operator"),functions:Uf},{name:v("Statistical"),functions:gl},{name:v("Text"),functions:Lg},{name:v("Engineering"),functions:Su},{name:v("Web"),functions:kg},{name:v("Parser"),functions:og}];for(const e of zg){const t=e.functions;for(let r in t){const n=t[r];n.category=n.category||e.name,r=r.replace(/_/g,"."),Bg.add(r,{isExported:!1,...n})}}var $g;!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"}($g||($g={}));const Gg=(e,t=()=>!0)=>[{goTo:e,guard:t}],Wg=(e,t=()=>!0)=>({goTo:e,guard:t}),qg={[$g.LeftRef]:{REFERENCE:Gg($g.Separator),NUMBER:Gg($g.FullRowSeparator),SYMBOL:[Wg($g.FullColumnSeparator,e=>lo(e.value)),Wg($g.FullRowSeparator,e=>co(e.value))]},[$g.FullColumnSeparator]:{SPACE:Gg($g.FullColumnSeparator),OPERATOR:Gg($g.RightColumnRef,e=>":"===e.value)},[$g.FullRowSeparator]:{SPACE:Gg($g.FullRowSeparator),OPERATOR:Gg($g.RightRowRef,e=>":"===e.value)},[$g.Separator]:{SPACE:Gg($g.Separator),OPERATOR:Gg($g.RightRef,e=>":"===e.value)},[$g.RightRef]:{SPACE:Gg($g.RightRef),NUMBER:Gg($g.Found),REFERENCE:Gg($g.Found,e=>fo(e.value)),SYMBOL:Gg($g.Found,e=>uo(e.value)||ho(e.value))},[$g.RightColumnRef]:{SPACE:Gg($g.RightColumnRef),SYMBOL:Gg($g.Found,e=>uo(e.value)),REFERENCE:Gg($g.Found,e=>fo(e.value))},[$g.RightRowRef]:{SPACE:Gg($g.RightRowRef),NUMBER:Gg($g.Found),REFERENCE:Gg($g.Found,e=>fo(e.value)),SYMBOL:Gg($g.Found,e=>ho(e.value))},[$g.Found]:{}};function Zg(e){let t=0,r=qg[$g.LeftRef],n="";for(;void 0!==r;){const o=e[t++];if(!o)return null;const s=r[o.type]?.find(e=>e.guard(o)),i=s?s.goTo:void 0;switch(i){case void 0:return null;case $g.Found:return n+=o.value,e.splice(0,t),{type:"REFERENCE",value:n};default:r=qg[i],n+=o.value}}return null}function Yg(e,t=Dl){const r=Ml(e,t),n=[];for(;r.length;)n.push(Zg(r)||r.shift());return n}const jg=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,Xg=["-","+"],Kg=["%"];class Qg{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 Jg={"%":40,"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function em(e){const t=e.shift();if(!t)throw new C;switch(t.type){case"DEBUGGER":const r=nm(e,1e3);return r.debug=!0,r;case"NUMBER":return{type:"NUMBER",value:Dt(t.value,Dl),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"STRING":return{type:"STRING",value:oe(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"INVALID_REFERENCE":return{type:"REFERENCE",value: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 n=t.value,o=e.current;if("LEFT_PAREN"===o?.type&&jg.test(t.value)&&n===oe(n,"'")){const{args:r,rightParen:o}=function(e){rm(e,"LEFT_PAREN",v("Missing opening parenthesis"));const t=e.current;if("RIGHT_PAREN"===t?.type){return{args:[],rightParen:rm(e,"RIGHT_PAREN")}}const r=[];r.push(tm(e));for(;"RIGHT_PAREN"!==e.current?.type;)rm(e,"ARG_SEPARATOR",v("Wrong function call")),r.push(tm(e));const n=rm(e,"RIGHT_PAREN");return{args:r,rightParen:n}}(e);return{type:"FUNCALL",value:n,args:r,tokenStartIndex:t.tokenIndex,tokenEndIndex:o.tokenIndex}}const s=n.toUpperCase();return"TRUE"===s||"FALSE"===s?{type:"BOOLEAN",value:"TRUE"===s,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:"SYMBOL",value:oe(t.value,"'"),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"LEFT_PAREN":const i=nm(e),a=rm(e,"RIGHT_PAREN",v("Missing closing parenthesis"));return{...i,tokenStartIndex:t.tokenIndex,tokenEndIndex:a.tokenIndex};case"OPERATOR":const l=t.value;if(Xg.includes(l)){const r=nm(e,Jg[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 tm(e){const t=e.current;return"ARG_SEPARATOR"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:"",tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:nm(e)}function rm(e,t,r){const n=e.shift();if(!n||n.type!==t)throw new C(r);return n}function nm(e,t=0){if(0===e.length)throw new C;let r=em(e);for(;"OPERATOR"===e.current?.type&&Jg[e.current.value]>t;){const t=e.shift(),n=t.value;if(Kg.includes(n))r={type:"UNARY_OPERATION",value:n,operand:r,postfix:!0,tokenStartIndex:r.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{const t=nm(e,Jg[n]);r={type:"BIN_OPERATION",value:n,left:r,right:t,tokenStartIndex:r.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return r}function om(e){return sm(Yg(e))}function sm(e){const t=e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>"SPACE"!==e.type),r=new Qg(t);"="===r.current?.value&&r.shift();const n=nm(r);if(r.current)throw new C;return n}function im(e,t,r){return cm(e,e=>e.type===t?r(e):e)}function am(e){return Array.from(lm(e))}function*lm(e){switch(yield e,e.type){case"FUNCALL":for(const t of e.args)yield*lm(t);break;case"UNARY_OPERATION":yield*lm(e.operand);break;case"BIN_OPERATION":yield*lm(e.left),yield*lm(e.right)}}function cm(e,t){switch((e=t(e)).type){case"FUNCALL":return{...e,args:e.args.map(e=>cm(e,t))};case"UNARY_OPERATION":return{...e,operand:cm(e.operand,t)};case"BIN_OPERATION":return{...e,right:cm(e.right,t),left:cm(e.left,t)};default:return e}}const um=Bg.content,hm={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},dm={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},fm={};function gm(e){return mm(Yg(e))}function mm(e){try{return function(e){const{dependencies:r,literalValues:o,symbols:s}=function(e){const t={numbers:[],strings:[]},r=[],n=[];for(const o of e)switch(o.type){case"INVALID_REFERENCE":case"REFERENCE":r.push(o.value);break;case"STRING":const e=oe(o.value);t.strings.push({value:e});break;case"NUMBER":{const e=Dt(o.value,Dl);t.numbers.push({value:e});break}case"SYMBOL":n.push(oe(o.value,"'"))}return{dependencies:r,literalValues:t,symbols:n}}(e),i=function(e){let t="";for(const r of e)switch(r.type){case"STRING":t+="|S|";break;case"NUMBER":t+="|N|";break;case"REFERENCE":case"INVALID_REFERENCE":r.value.includes(":")?t+="|R|":t+="|C|";break;case"SPACE":break;default:t+=r.value}return t}(e);if(!fm[i]){const l=sm([...e]),u=new n;let h=0,d=0,f=0;if("BIN_OPERATION"===l.type&&":"===l.value)throw new C(v("Invalid formula"));if("EMPTY"===l.type)throw new C(v("Invalid formula"));const g=y(l),m=new t;m.append(`// ${i}`),m.append(g),m.append(`return ${g.returnExpression};`);const p=new Function("deps","ref","range","getSymbolValue","ctx",m.toString());function b(e){const{args:t}=e,r=e.value.toUpperCase(),n=um[r];if(!n)throw new R(v('Unknown function: "%s"',e.value));!function(e){const t=e.args.length,r=e.value.toUpperCase(),n=um[r],{nbrArgRepeating:o,minArgRequired:s}=n;if(t<s)throw new C(v("Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.",{functionName:r,minArgRequired:s,nbrArgSupplied:t}));if(t>n.maxArgPossible)throw new C(v("Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.",{functionName:r,maxArgPossible:n.maxArgPossible,nbrArgSupplied:t}));if(o>1){const e=t-s-o*Math.floor((t-s)/o)-n.nbrArgOptional;if(e>0)throw new C(v("Invalid number of arguments for the %(functionName)s function. Repeatable arguments should be supplied in groups of %(nbrArgRepeating)s, with up to %(nbrArgOptional)s optional. Got %(nbrValueRemaining)s too many.",{functionName:r,nbrArgRepeating:o,nbrArgOptional:n.nbrArgOptional,nbrValueRemaining:e}))}}(e);const o=[],s=c(n,t.length);for(let e=0;e<t.length;e++){const r=n.args[s(e)??-1],i=t[e],a=r.type||[],l=a.includes("META")||a.includes("RANGE<META>"),c=a.some(e=>pm(e));o.push(y(i,l,c))}return o}function y(e,r=!1,n=!1){const o=new t(u);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&r)throw new C(v("Argument must be a reference to a cell or range."));switch(e.debug&&(o.append("debugger;"),o.append('ctx["debug"] = true;')),e.type){case"BOOLEAN":return o.return(`{ value: ${e.value} }`);case"NUMBER":return o.return(`this.literalValues.numbers[${d++}]`);case"STRING":return o.return(`this.literalValues.strings[${h++}]`);case"REFERENCE":return o.return(`${e.value.includes(":")||n?"range":"ref"}(deps[${f++}], ${r?"true":"false"})`);case"FUNCALL":const t=b(e).map(e=>e.assignResultToVariable());o.append(...t);const i=e.value.toUpperCase();return o.return(`ctx['${i}'](${t.map(e=>e.returnExpression)})`);case"UNARY_OPERATION":{const t=dm[e.value],r=y(e.operand,!1,!1).assignResultToVariable();return o.append(r),o.return(`ctx['${t}'](${r.returnExpression})`)}case"BIN_OPERATION":{const t=hm[e.value],r=y(e.left,!1,!1).assignResultToVariable(),n=y(e.right,!1,!1).assignResultToVariable();return o.append(r),o.append(n),o.return(`ctx['${t}'](${r.returnExpression}, ${n.returnExpression})`)}case"SYMBOL":const a=s.indexOf(e.value);return o.return(`getSymbolValue(this.symbols[${a}])`);case"EMPTY":return o.return("undefined")}}fm[i]=p}const a={execute:fm[i],dependencies:r,literalValues:o,symbols:s,tokens:e,isBadExpression:!1,normalizedFormula:i};return a}(e)}catch(t){return{tokens:e,dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map(e=>e.value).join("")}}}function pm(e){return e.startsWith("RANGE")}class bm{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 vm{transportService;constructor(e){this.transportService=e}async sendMessage(e){"CLIENT_JOINED"!==e.type&&"CLIENT_LEFT"!==e.type&&"CLIENT_MOVED"!==e.type||this.transportService.sendMessage(e)}onNewMessage(e,t){this.transportService.onNewMessage(e,t)}leave(e){this.transportService.leave(e)}}class ym{subscriptions={};on(e,t,r){if(!r)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:r})}trigger(e,t){const r=this.subscriptions[e]||[];for(let e=0,n=r.length;e<n;e++){const n=r[e];n.callback.call(n.owner,t)}}off(e,t){const r=this.subscriptions[e];r&&(this.subscriptions[e]=r.filter(e=>e.owner!==t))}clear(){this.subscriptions={}}}function wm(e){const t=[];for(let r=0;r<e;r++){const e={cells:{}};t.push(e)}return t}function Em(e,t,r){return r.map(r=>r>=e?r+t:r)}function Sm(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 Cm(e,t="Sheet"){let r=1,n=`${t}${r}`;for(;e.includes(n);)n=`${t}${r}`,r++;return n}function Tm(e,t){let r=1;const n=v("Copy of %s",e);let o=n.toString();for(;t.includes(o);)o=`${n} (${r})`,r++;return o}function Im(e,t){return void 0!==e&&void 0!==t&&ne(e.trim().toUpperCase())===ne(t.trim().toUpperCase())}function xm(e,t){const r=e.zone,n=function(e,t){const{left:r,top:n,bottom:o,right:s}=e;if(void 0!==s&&void 0!==o)return e;if(void 0===o&&void 0!==s)return{right:s,top:n,left:r,bottom:t.numberOfRows-1};if(void 0===s&&void 0!==o)return{bottom:o,left:r,top:n,right:t.numberOfCols-1};throw new Error("Bad zone format")}(r,t(e.sheetId));let o=e.parts;return 1===e.parts.length&&cs(n)>1?o=[e.parts[0],e.parts[0]]:2===e.parts.length&&1===cs(n)&&(o=[e.parts[0]]),{unboundedZone:r,zone:n,parts:o,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Rm(e,t){const r=e.xc,{xc:n,sheetName:o}=go(r),s=Ho(n),i=function(e,t){const r=e.split(":").map(e=>{const t=co(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}}),n=void 0===t.bottom,o=void 0===t.right;n&&(r[0].rowFixed=r[0].rowFixed||r[1].rowFixed,r[1].rowFixed=r[0].rowFixed||r[1].rowFixed);o&&(r[0].colFixed=r[0].colFixed||r[1].colFixed,r[1].colFixed=r[0].colFixed||r[1].colFixed);return r}(n,s);return xm({zone:s,parts:i,sheetId:e.sheetId,prefixSheet:Boolean(o),invalidSheetName:e.invalidSheetName},t)}function Am(e){const t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:"",zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function _m(e){return ls(e.unboundedZone)}function Om(e){return as(e.unboundedZone)}function Dm(e,t,r,n={useBoundedReference:!1,useFixedReference:!1}){if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return w.InvalidReference;if(e.zone.left<0||e.zone.top<0)return w.InvalidReference;const o=e.sheetId!==t||e.invalidSheetName||e.prefixSheet;let s="";if(o&&(s=e.invalidSheetName?e.invalidSheetName:se(r(e.sheetId))),o&&!s)return w.InvalidReference;let i=$m(e,0,n);return e.parts&&2===e.parts.length&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(i+=":",i+=$m(e,1,n)),`${o?s+"!":""}${i}`}function Fm(e,t,r){const n=r.sheetId===e?t:r.sheetId;return{...r,sheetId:n}}function Nm(e){const t=[];for(const r of e)for(const e of rs(r.zone))t.push({...e,sheetId:r.sheetId});return t}function Mm(e){const t={left:e.col,top:e.row,right:e.col,bottom:e.row};return{sheetId:e.sheetId,zone:t}}function Vm(e){return Lm.get(e.type)?.(e)}const Lm=new class extends fd{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};function Pm(e){const t="COL"===e.dimension?"left":"top",r="COL"===e.dimension?"right":"bottom",n="COL"===e.dimension?"columns":"rows",o=[...e.elements];o.sort((e,t)=>t-e);const s=ce(o);return o=>{if(!Im(o.sheetId,e.sheetId))return{changeType:"NONE"};let i=o,a="NONE";for(const e of s){const s=qe(e),l=We(e);if(o.zone[t]<=s&&s<=o.zone[r]){const e=Math.min(o.zone[r],l)-s+1;a="RESIZE",i=zm(i,n,a,-e)}else if(o.zone[t]>=s&&o.zone[r]<=l)a="REMOVE",i=Am(w.InvalidReference);else if(o.zone[t]<=l&&o.zone[r]>=l){const e=l-o.zone[t]+1;a="RESIZE",i=zm(i,n,a,-e),i=zm(i,n,"MOVE",-(o.zone[t]-s))}else s<o.zone[t]&&(a="MOVE",i=zm(i,n,a,-(l-s+1)))}return"NONE"!==a?{changeType:a,range:i}:{changeType:"NONE"}}}function km(e){const t="COL"===e.dimension?"left":"top",r="COL"===e.dimension?"right":"bottom",n="COL"===e.dimension?"columns":"rows";return o=>{if(o.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(o.zone[t]<=e.base&&e.base<o.zone[r])return{changeType:"RESIZE",range:zm(o,n,"RESIZE",e.quantity)};if(e.base<o.zone[t])return{changeType:"MOVE",range:zm(o,n,"MOVE",e.quantity)}}else{if(o.zone[t]<e.base&&e.base<=o.zone[r])return{changeType:"RESIZE",range:zm(o,n,"RESIZE",e.quantity)};if(e.base<=o.zone[t])return{changeType:"MOVE",range:zm(o,n,"MOVE",e.quantity)}}return{changeType:"NONE"}}}function Um(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:"NONE"};const r=e.sheetName;return{changeType:"REMOVE",range:t={...Am(w.InvalidReference),invalidSheetName:r}}}}function Hm(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.newName&&t.invalidSheetName===e.newName){const r=void 0,n=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:n,invalidSheetName:r}}}if(e.oldName&&t.invalidSheetName===e.oldName){const r=void 0,n=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:n,invalidSheetName:r}}}return{changeType:"NONE"}}}function Bm(e){const t=e.target[0];return r=>{if(r.sheetId!==e.sheetId||!Jo(r.zone,t))return{changeType:"NONE"};const n=e.targetSheetId,o=zm(r,"both","MOVE",[e.col-t.left,e.row-t.top]),s=e.sheetId!==n||o.prefixSheet;return{changeType:"MOVE",range:{...o,sheetId:n,prefixSheet:s}}}}function zm(e,t,r,n){return{...e,unboundedZone:os(e.unboundedZone,t,r,n),zone:os(e.zone,t,r,n)}}function $m(e,t,r={useBoundedReference:!1,useFixedReference:!1}){const n=e.parts[t]?.colFixed||r.useFixedReference?"$":"",o=Eo(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=ls(e.unboundedZone)&&!r.useBoundedReference?0===t&&e.unboundedZone.hasHeader?n+o+s+i:n+o:as(e.unboundedZone)&&!r.useBoundedReference?0===t&&e.unboundedZone.hasHeader?n+o+s+i:s+i:n+o+s+i,a}Lm.add("REMOVE_COLUMNS_ROWS",e=>({applyChange:Pm(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("ADD_COLUMNS_ROWS",e=>({applyChange:km(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("DELETE_SHEET",e=>({applyChange:Um(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("RENAME_SHEET",e=>({applyChange:Hm(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add("MOVE_RANGES",e=>({applyChange:Bm(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));const Gm=new class extends fd{addTransformation(e,t,r){this.content[e]||(this.content[e]=new Map);for(const n of t)this.content[e].set(n,r);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}};const Wm=new class extends fd{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};function qm(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?function(e,t,r){const n="left"===t?"right":"bottom";let o=e[t],s=e[n];const i=e[n];for(const n of r.sort((e,t)=>t-e))e[t]>n&&(o--,void 0!==s&&s--),void 0!==i&&void 0!==s&&e[t]<=n&&i>=n&&s--;if(!(void 0!==s&&o>s))return{...e,[t]:o,[n]:s}}(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?function(e,t,r,n,o){const s="left"===t?"columns":"rows",i="before"===n?r-1:r,a=e["left"===t?"right":"bottom"];return e[t]<=i&&a&&a>i?os(e,s,"RESIZE",o):i<e[t]?os(e,s,"MOVE",o):{...e}}(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):e}function Zm(e,t){const r="DELETE_SHEET"===t.type&&t.sheetId;if("sheetId"in t&&e._sheetId!==t.sheetId)return e;{const n=qm(e._zone,t);if(n&&r!==e._sheetId)return{...e,_zone:n}}}const Ym=/rgba?\(|\s+|\)/gi,jm=/^#([A-F\d]{2}){3,4}$/;function Xm(e,t=1){const r=1!==t?Math.round(255*t).toString(16).padStart(2,"0"):"";return Qm(e.toString(16).padStart(6,"0"))+r}function Km(e){return"number"==typeof e?e:Number.parseInt(Qm(e).slice(1,7),16)}function Qm(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(Ym,"").split(",");let r=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");if(isNaN(e))throw new Error("invalid alpha value");r=Math.round(255*e)}const n=t.map(e=>parseInt(e,10));255!==r&&n.push(r);return"#"+Ie(n.map(e=>e.toString(16).padStart(2,"0"))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce((e,t)=>e+t+t,"")),t=`#${t}`),!jm.test(t))throw new Error(`invalid color input: ${e}`);return t}function Jm(e){try{return Qm(e),!0}catch(e){return!1}}const ep=e=>e>=0&&e<=255;function tp(e,t,r,n=1){if(!ep(e)||!ep(t)||!ep(r)||n<0||n>1)throw new Error(`Invalid RGBA values ${[e,t,r,n]}`);return{a:n,b:r,g:t,r:e}}function rp(e){let{r:t,g:r,b:n}=op(e);t/=255,r/=255,n/=255;const o=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*o(t)+.7152*o(r)+.0722*o(n)}function np(e){let t=e.r.toString(16),r=e.g.toString(16),n=e.b.toString(16),o=Math.round(255*e.a).toString(16);return 1===t.length&&(t="0"+t),1===r.length&&(r="0"+r),1===n.length&&(n="0"+n),1===o.length&&(o="0"+o),"ff"===o&&(o=""),("#"+t+r+n+o).toUpperCase()}function op(e){let t,r,n,o;if(7===(e=Qm(e)).length)t=parseInt(e[1]+e[2],16),r=parseInt(e[3]+e[4],16),n=parseInt(e[5]+e[6],16),o=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),r=parseInt(e[3]+e[4],16),n=parseInt(e[5]+e[6],16),o=parseInt(e[7]+e[8],16)}return o=+(o/255).toFixed(3),{a:o,r:t,g:r,b:n}}function sp(e){(e={...e}).s/=100,e.l/=100;const t=(1-Math.abs(2*e.l-1))*e.s,r=t*(1-Math.abs(e.h/60%2-1)),n=e.l-t/2;let o=0,s=0,i=0;return 0<=e.h&&e.h<60?(o=t,s=r,i=0):60<=e.h&&e.h<120?(o=r,s=t,i=0):120<=e.h&&e.h<180?(o=0,s=t,i=r):180<=e.h&&e.h<240?(o=0,s=r,i=t):240<=e.h&&e.h<300?(o=r,s=0,i=t):300<=e.h&&e.h<360&&(o=t,s=0,i=r),o=Math.round(255*(o+n)),s=Math.round(255*(s+n)),i=Math.round(255*(i+n)),{a:e.a,r:o,g:s,b:i}}function ip(e){const t=e.r/255,r=e.g/255,n=e.b/255,o=Math.min(t,r,n),s=Math.max(t,r,n),i=s-o;let a=0,l=0,c=0;return a=0===i?0:s===t?(r-n)/i%6:s===r?(n-t)/i+2:(t-r)/i+4,a=Math.round(60*a),a<0&&(a+=360),c=(s+o)/2,l=0===i?0:i/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}function ap(e){return np(sp(e))}function lp(e){return ip(op(e))}function cp(e){return op("number"==typeof e?Xm(e):e)}function up(e,t){const r=lp(e);return 1===t?"#fff":(r.l=t*(100-r.l)+r.l,ap(r))}function hp(e,t){const r=lp(e);return 1===t?"#000":(r.s=Math.min(100,t*r.s+r.s),r.l=r.l-t*r.l,ap(r))}const dp=["#4EA7F2","#EA6175","#43C5B1","#F4A261","#8481DD","#FFD86D"],fp=["#4EA7F2","#3188E6","#43C5B1","#00A78D","#EA6175","#CE4257","#F4A261","#F48935","#8481DD","#5752D1","#FFD86D","#FFBC2C"],gp=["#4EA7F2","#3188E6","#056BD9","#A76DBC","#7F4295","#6D2387","#EA6175","#CE4257","#982738","#43C5B1","#00A78D","#0E8270","#F4A261","#F48935","#BE5D10","#8481DD","#5752D1","#3A3580","#A4A8B6","#7E8290","#545B70","#FFD86D","#FFBC2C","#C08A16"],mp=["#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"],pp=["#4EA7F2","#43C5B1","#EA6175","#F4A261","#8481DD","#FFD86D","#3188E6","#00A78D","#CE4257","#F48935","#5752D1","#FFBC2C"],bp=["#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 yp{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){var r;this.preferredColors=t,this.palette=(r=e,r<=6?dp:r<=12?fp:r<=24?gp:mp).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 wp extends yp{constructor(e,t=[]){var r;super(e,t),this.palette=(r=e,r<=6?dp:r<=12?pp:r<=24?bp:vp).filter(e=>!t.includes(e))}}class Ep{availableColors;colors={};constructor(e=12){this.availableColors=new wp(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}}function Sp(e,t,r,n){const o=t-e;return[((r>>16)%256-(n>>16)%256)/o,((r>>8)%256-(n>>8)%256)/o,(r%256-n%256)/o]}function Cp(e,t,r,n){const[o,s,i]=n;return Math.round((r>>16)%256-o*(e-t))<<16|Math.round((r>>8)%256-s*(e-t))<<8|Math.round(r%256-i*(e-t))}v("Light"),v("Medium"),v("Dark"),v("Custom");const Tp={hasFilters:!1,totalRow:!1,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,automaticAutofill:!0,styleId:"TableStyleMedium2"};function Ip(e,t){return{coloredText:hp(t,.3),light:up(t,.8),medium:up(t,.6),dark:hp(t,.3),mediumBorder:up(t,.45),highlight:t,name:e}}const xp={black:{name:v("Black"),coloredText:"#000000",light:"#D9D9D9",medium:"#A6A6A6",dark:"#404040",mediumBorder:"#000000",highlight:"#000000"},lightBlue:Ip(v("Light blue"),"#346B90"),red:Ip(v("Red"),"#C53628"),lightGreen:Ip(v("Light green"),"#748747"),purple:Ip(v("Purple"),"#6C4E65"),gray:{name:v("Gray"),coloredText:"#666666",light:"#EEEEEE",medium:"#DDDDDD",dark:"#767676",mediumBorder:"#D0D0D0",highlight:"#A9A9A9"},orange:Ip(v("Orange"),"#C37034")},Rp={black:xp.black,orangeBlue:{...xp.lightBlue,highlight:xp.orange.highlight},purpleGreen:{...xp.lightGreen,highlight:xp.purple.highlight},redBlue:{...xp.lightBlue,highlight:xp.red.highlight}},Ap=e=>({category:"light",templateName:"lightColoredText",primaryColor:e.highlight,wholeTable:{style:{textColor:e.coloredText},border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"}}},headerRow:{border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"thin"}}},firstRowStripe:{style:{fillColor:e.light}}}),_p=e=>({category:"light",templateName:"lightWithHeader",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"},left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"},border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}},secondRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}}}),Op=e=>({category:"light",templateName:"lightAllBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"},left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"},horizontal:{color:e.highlight,style:"thin"},vertical:{color:e.highlight,style:"thin"}}},headerRow:{border:{bottom:{color:e.highlight,style:"medium"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}}}),Dp=e=>({category:"medium",templateName:"mediumBandedBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"},horizontal:{color:e.mediumBorder,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}}}),Fp=e=>({category:"medium",templateName:"mediumWhiteBorders",primaryColor:e.highlight,wholeTable:{border:{horizontal:{color:"#FFFFFF",style:"thin"},vertical:{color:"#FFFFFF",style:"thin"}},style:{fillColor:e.light}},headerRow:{border:{bottom:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{border:{top:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),Np=e=>({category:"medium",templateName:"mediumMinimalBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:"#000000",style:"medium"},bottom:{color:"#000000",style:"medium"}}},totalRow:{border:{top:{color:"#000000",style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"},border:{bottom:{color:"#000000",style:"medium"}}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:xp.black.light}},firstColumnStripe:{style:{fillColor:xp.black.light}}}),Mp=e=>({category:"medium",templateName:"mediumAllBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"},horizontal:{color:e.mediumBorder,style:"thin"},vertical:{color:e.mediumBorder,style:"thin"}},style:{fillColor:e.light}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),Vp=e=>({category:"dark",templateName:"dark",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{style:{fillColor:e.dark,textColor:"#FFFFFF"},border:{top:{color:"#FFFFFF",style:"thick"}}},headerRow:{style:{fillColor:"#000000"},border:{bottom:{color:"#FFFFFF",style:"thick"}}},firstColumn:{style:{fillColor:e.dark},border:{right:{color:"#FFFFFF",style:"thick"}}},lastColumn:{style:{fillColor:e.dark},border:{left:{color:"#FFFFFF",style:"thick"}}},firstRowStripe:{style:{fillColor:e.dark}},firstColumnStripe:{style:{fillColor:e.dark}}}),Lp=e=>({category:"dark",templateName:"darkNoBorders",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.light}},totalRow:{border:{top:{color:"#000000",style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),Pp=Vp(xp.black);Pp.wholeTable.style.fillColor="#737373";const kp=Np(xp.black);function Up(e,t,r){return{...t(r),displayName:`${r.name}, ${e}`}}kp.wholeTable.border={...kp.wholeTable.border,left:{color:"#000000",style:"thin"},right:{color:"#000000",style:"thin"},horizontal:{color:"#000000",style:"thin"},vertical:{color:"#000000",style:"thin"}};const Hp={None:{category:"light",templateName:"none",primaryColor:"",displayName:"none"},TableStyleLight1:Up("TableStyleLight1",Ap,xp.black),TableStyleLight2:Up("TableStyleLight2",Ap,xp.lightBlue),TableStyleLight3:Up("TableStyleLight3",Ap,xp.red),TableStyleLight4:Up("TableStyleLight4",Ap,xp.lightGreen),TableStyleLight5:Up("TableStyleLight5",Ap,xp.purple),TableStyleLight6:Up("TableStyleLight6",Ap,xp.gray),TableStyleLight7:Up("TableStyleLight7",Ap,xp.orange),TableStyleLight8:Up("TableStyleLight8",_p,xp.black),TableStyleLight9:Up("TableStyleLight9",_p,xp.lightBlue),TableStyleLight10:Up("TableStyleLight10",_p,xp.red),TableStyleLight11:Up("TableStyleLight11",_p,xp.lightGreen),TableStyleLight12:Up("TableStyleLight12",_p,xp.purple),TableStyleLight13:Up("TableStyleLight13",_p,xp.gray),TableStyleLight14:Up("TableStyleLight14",_p,xp.orange),TableStyleLight15:Up("TableStyleLight15",Op,xp.black),TableStyleLight16:Up("TableStyleLight16",Op,xp.lightBlue),TableStyleLight17:Up("TableStyleLight17",Op,xp.red),TableStyleLight18:Up("TableStyleLight18",Op,xp.lightGreen),TableStyleLight19:Up("TableStyleLight19",Op,xp.purple),TableStyleLight20:Up("TableStyleLight20",Op,xp.gray),TableStyleLight21:Up("TableStyleLight21",Op,xp.orange),TableStyleMedium1:Up("TableStyleMedium1",Dp,xp.black),TableStyleMedium2:Up("TableStyleMedium2",Dp,xp.lightBlue),TableStyleMedium3:Up("TableStyleMedium3",Dp,xp.red),TableStyleMedium4:Up("TableStyleMedium4",Dp,xp.lightGreen),TableStyleMedium5:Up("TableStyleMedium5",Dp,xp.purple),TableStyleMedium6:Up("TableStyleMedium6",Dp,xp.gray),TableStyleMedium7:Up("TableStyleMedium7",Dp,xp.orange),TableStyleMedium8:Up("TableStyleMedium8",Fp,xp.black),TableStyleMedium9:Up("TableStyleMedium9",Fp,xp.lightBlue),TableStyleMedium10:Up("TableStyleMedium10",Fp,xp.red),TableStyleMedium11:Up("TableStyleMedium11",Fp,xp.lightGreen),TableStyleMedium12:Up("TableStyleMedium12",Fp,xp.purple),TableStyleMedium13:Up("TableStyleMedium13",Fp,xp.gray),TableStyleMedium14:Up("TableStyleMedium14",Fp,xp.orange),TableStyleMedium15:{...kp,displayName:"Black, TableStyleMedium15"},TableStyleMedium16:Up("TableStyleMedium16",Np,xp.lightBlue),TableStyleMedium17:Up("TableStyleMedium17",Np,xp.red),TableStyleMedium18:Up("TableStyleMedium18",Np,xp.lightGreen),TableStyleMedium19:Up("TableStyleMedium19",Np,xp.purple),TableStyleMedium20:Up("TableStyleMedium20",Np,xp.gray),TableStyleMedium21:Up("TableStyleMedium21",Np,xp.orange),TableStyleMedium22:Up("TableStyleMedium22",Mp,xp.black),TableStyleMedium23:Up("TableStyleMedium23",Mp,xp.lightBlue),TableStyleMedium24:Up("TableStyleMedium24",Mp,xp.red),TableStyleMedium25:Up("TableStyleMedium25",Mp,xp.lightGreen),TableStyleMedium26:Up("TableStyleMedium26",Mp,xp.purple),TableStyleMedium27:Up("TableStyleMedium27",Mp,xp.gray),TableStyleMedium28:Up("TableStyleMedium28",Mp,xp.orange),TableStyleDark1:{...Pp,displayName:"Black, TableStyleDark1"},TableStyleDark2:Up("TableStyleDark2",Vp,xp.lightBlue),TableStyleDark3:Up("TableStyleDark3",Vp,xp.red),TableStyleDark4:Up("TableStyleDark4",Vp,xp.lightGreen),TableStyleDark5:Up("TableStyleDark5",Vp,xp.purple),TableStyleDark6:Up("TableStyleDark6",Vp,xp.gray),TableStyleDark7:Up("TableStyleDark7",Vp,xp.orange),TableStyleDark8:Up("TableStyleDark8",Lp,Rp.black),TableStyleDark9:Up("TableStyleDark9",Lp,Rp.redBlue),TableStyleDark10:Up("TableStyleDark10",Lp,Rp.purpleGreen),TableStyleDark11:Up("TableStyleDark11",Lp,Rp.orangeBlue)},Bp={none:()=>({category:"none",templateName:"none",primaryColor:"",name:"none"}),lightColoredText:Ap,lightAllBorders:Op,mediumAllBorders:Mp,lightWithHeader:_p,mediumBandedBorders:Dp,mediumMinimalBorders:Np,darkNoBorders:Lp,mediumWhiteBorders:Fp,dark:Vp};function zp(e,t,r){const n=Ip("",r);return{...Bp[t](n),category:"custom",displayName:e}}function $p(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId!==t.sheetId)return e;const r=qm(e.pivot.dataSet.zone,t),n=r?{...e.pivot.dataSet,zone:r}:void 0;return{...e,pivot:{...e.pivot,dataSet:n}}}function Gp(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 Wp(e,t){if(e.sheetId!==t.sheetId)return e;const r=qm(e.zone,t);if(!r)return;const n=e.newTableRange?Zm(e.newTableRange,t):void 0;return{...e,newTableRange:n,zone:r}}function qp(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let r;if("REMOVE_COLUMNS_ROWS"===t.type)r=Sm(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){r=Em(Re(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==r?{...e,base:r}:void 0}function Zp(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;const r=le(e.start,e.end+1);let n=[];if("REMOVE_COLUMNS_ROWS"===t.type)n=Sm(t.elements,r);else if("ADD_COLUMNS_ROWS"===t.type){n=Em(Re(t.position,t.base),t.quantity,r)}return 0!==n.length?{...e,start:Math.min(...n),end:Math.max(...n)}:void 0}Gm.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],qp),Gm.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],qp),Gm.addTransformation("DELETE_SHEET",["MOVE_RANGES"],function(e,t){const r=t.sheetId;if(e.targetSheetId===r||e.sheetId===r)return;return e}),Gm.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART","UPDATE_CAROUSEL"],function(e,t){if(e.figureId===t.figureId)return;return e}),Gm.addTransformation("DELETE_CHART",["UPDATE_CHART"],function(e,t){if(e.chartId===t.chartId)return;return e}),Gm.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))}}}),Gm.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}),Gm.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],function(e,t){if(e.sheetId!==t.sheetId)return e;const r=[];for(const n of e.target)t.target.every(e=>!Ko(n,e))&&r.push(n);if(r.length)return{...e,target:r};return}),Gm.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Gp),Gm.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Gp),Gm.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],Wp),Gm.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],Wp),Gm.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:Tp.styleId}}}),Gm.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],Zp),Gm.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],Zp),Gm.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],function(e,t){if(e.pivotId===t.pivotId)return;return e}),Gm.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}),Gm.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],$p),Gm.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],$p);const Yp=new fd,jp="000000",Xp={arrows:"3Arrows",smiley:"3Symbols",dots:"3TrafficLights1"},Kp="http://schemas.openxmlformats.org/spreadsheetml/2006/main",Qp="http://schemas.openxmlformats.org/spreadsheetml/2006/main",Jp="http://schemas.openxmlformats.org/package/2006/relationships",eb="http://schemas.openxmlformats.org/package/2006/content-types",tb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",rb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",nb="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",ob="http://schemas.openxmlformats.org/spreadsheetml/2006/main",sb="http://schemas.microsoft.com/office/spreadsheetml/2014/revision",ib="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3",ab="http://schemas.openxmlformats.org/markup-compatibility/2006",lb="http://schemas.openxmlformats.org/drawingml/2006/main",cb="http://schemas.openxmlformats.org/drawingml/2006/chart",ub={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"},hb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",db="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",fb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",gb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",mb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",pb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",bb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",vb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",yb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",wb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",Eb="bdbb8cdc-fa1e-496e-a857-3c3f30c029c3",Sb="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Cb=.75,Tb=.143,Ib=8.43,xb=12.75,Rb={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}]},Ab=["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"],_b="[Content_Types].xml";function Ob(e,t,r){if(!t.startsWith("="))return t;const n=Yg(t);for(let t=1;t<n.length;t++){if("REFERENCE"!==n[t].type)continue;const o=n[t].value,s=Db(e,o,r);o!==s&&(n[t]={value:s,type:"REFERENCE"})}return Ie(n.map(e=>e.value))}function Db(e,t,r){const n=go(t).sheetName;if(n?!Im(n,r.sheetName.old):e!==r.sheetId)return t;const o=function(e,t){if(!ao.test(e))return Am(e);return Rm({xc:e,sheetId:t},Fb)}(t,n?r.sheetId:e);if(o.invalidXc)return t;const s=r.applyChange(o);return"NONE"===s.changeType||"REMOVE"===s.changeType?t:Dm(s.range,e,function(e){return t=>t===e.sheetId?e.sheetName.current:""}(r))}function Fb(e){return{numberOfRows:Number.MAX_SAFE_INTEGER,numberOfCols:Number.MAX_SAFE_INTEGER}}function Nb(e){return e&&rp(e)<.3?"#FFFFFF":"#000000"}function Mb(e){return e&&rp(e)<.3?"#C8C8C8":"#666666"}function Vb(e,t,r){const n=Yp.getAll().find(e=>e.match(t.type));if(!n)throw new Error("Unknown chart type.");return n.transformDefinition(e,t,r)}function Lb(e,t){return(e=re(e)).pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=Ob(e.computedBy.sheetId,e.computedBy.formula,t))}),e}function Pb(e,t){return{...e,definition:Vb(e.sheetId,e.definition,t)}}v("Left"),v("Right"),Wm.add("UPDATE_CELL",function(e,t){const r=e.content&&Ob(e.sheetId,e.content,t);return{...e,content:r}}),Wm.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=>Ob(e.sheetId,r,t))};else if("ColorScaleRule"===r.type){const{minimum:n,maximum:o,midpoint:s}=r;e.cf.rule={...r,minimum:{...n,value:n.value&&Ob(e.sheetId,n.value,t)},maximum:{...o,value:o.value&&Ob(e.sheetId,o.value,t)},midpoint:s?{...s,value:Ob(e.sheetId,s.value,t)}:void 0}}else if("IconSetRule"===r.type){const{upperInflectionPoint:n,lowerInflectionPoint:o}=r;e.cf.rule={...r,upperInflectionPoint:{...n,value:Ob(e.sheetId,n.value,t)},lowerInflectionPoint:{...o,value:Ob(e.sheetId,o.value,t)}}}else"DataBarRule"===r.type&&(e.cf.rule={...r,rangeValues:r.rangeValues?Db(e.sheetId,r.rangeValues,t):void 0});return e}),Wm.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=>Ob(e.sheetId,r,t)),e}),Wm.add("ADD_PIVOT",Lb),Wm.add("UPDATE_PIVOT",Lb),Wm.add("CREATE_CHART",Pb),Wm.add("UPDATE_CHART",Pb);const kb=[{match:function(e){return"sheetId"in e},fn:Bb},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const r=Bb(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;const n=[];for(const r of e.target){const e=qm(r,t);e&&n.push(e)}if(!n.length)return"IGNORE_COMMAND";return{...e,target:n}}},{match:function(e){return"sheetId"in e&&"zone"in e},fn:function(e,t){const r=Bb(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;const n=qm(e.zone,t);if(n)return{...e,zone:n};return"IGNORE_COMMAND"}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const r=Bb(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const r="COL"===t.dimension?"col":"row";let n=e[r];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort((e,t)=>t-e);if(e.includes(n))return"IGNORE_COMMAND";for(const t of e)n>=t&&n--}"ADD_COLUMNS_ROWS"===t.type&&(n>t.base||n===t.base&&"before"===t.position)&&(n+=t.quantity);return{...e,[r]:n}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const r of t.target){if(!(e.col===r.left&&e.row===r.top)&&Qo(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=Bb(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"!==t.type&&"REMOVE_COLUMNS_ROWS"!==t.type)return"SKIP_TRANSFORMATION";if(t.dimension!==e.dimension)return e;let n=[];if("REMOVE_COLUMNS_ROWS"===t.type)n=Sm(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){n=Em(Re(t.position,t.base),t.quantity,e.elements)}if(0===n.length)return"IGNORE_COMMAND";return{...e,elements:n}}},{match:function(e){return"ranges"in e},fn:function(e,t){if(!("sheetId"in t))return e;const r=e.ranges.map(e=>Zm(e,t)).filter(Se);if(!r.length)return"IGNORE_COMMAND";return{...e,ranges:r}}}];function Ub(e,t){const r=Gm.getTransformation(e.type,t.type),n=r?r(e,t):function(e,t){for(const{match:r,fn:n}of kb)if(r(e)){const r=n(e,t);if("SKIP_TRANSFORMATION"===r)continue;if("IGNORE_COMMAND"===r)return;e=r}return e}(e,t);return n?function(e,t){const r=Wm.get(e.type);if(!r)return e;const n=Vm(t);if(n)return r(e,n);return e}(n,t):n}function Hb(e,t){let r=[...e];const n=new Set(Gm.getKeys());for(const e of t)(n.has(e.type)||Lm.contains(e.type))&&(r=r.reduce((t,r)=>{const n=Ub(r,e);return n&&t.push(n),t},[]));return r}function Bb(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 zb{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,r,n,o,s){this.rootCommand=n,this.timestamp=s,this.id=e,this.clientId=t,this._commands=[...r],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class $b extends Error{}class Gb extends ym{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new wo;lastLocalOperation;constructor(e,t,r=Y){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=r,this.debouncedMove=Te(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,r){if(!t.length||!r.length||!this.canApplyOptimisticUpdate())return;const n=new zb(this.uuidGenerator.uuidv4(),this.clientId,t,e,r,Date.now());this.revisions.append(n.id,n),"REQUEST_REDO"!==e.type&&(this.lastLocalOperation=n),this.trigger("new-local-state-update",{id:n.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:n.id,clientId:n.clientId,commands:n.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&(this._move(this.awaitingClientPosition),this.awaitingClientPosition=void 0)}loadInitialMessages(e){const t=performance.now(),r=e.reduce((e,t)=>e+("REMOTE_REVISION"===t.type?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug("Replayed",r,"commands in",performance.now()-t,"ms")}async leave(e){e&&1===Object.keys(this.clients).length&&this.lastRevisionMessage&&"SNAPSHOT_CREATED"!==this.lastRevisionMessage?.type&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}async snapshot(e){if(0!==this.pendingMessages.length)return;const t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({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 $b("The client left the session");return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(Se))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return void(this.awaitingClientPosition=e);const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const r=t?"CLIENT_MOVED":"CLIENT_JOINED",n=this.getCurrentClient();this.clients[this.clientId]={...n,position:e},this.transportService.sendMessage({type:r,version:1,client:{...n,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:r,timestamp:n}=e,o=new zb(e.nextRevisionId,t,r,void 0,void 0,n);if(o.clientId!==this.clientId){this.revisions.insert(o.id,o,e.serverRevisionId);const t=this.pendingMessages.filter(e=>"REMOTE_REVISION"===e.type).map(e=>e.commands).flat();this.trigger("remote-revision-received",{commands:Hb(r,t)})}break;case"SNAPSHOT_CREATED":{const t=new zb(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.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||this.sendPendingMessage()}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.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"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 Wb=(new fd).add("ADD_COLUMNS_ROWS",function(e){const t=[];let r=e.base;"after"===e.position&&r++;for(let n=0;n<e.quantity;n++)t.push(n+r);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}).add("REMOVE_COLUMNS_ROWS",function(e){const t=[],r=[...e.elements].sort((e,t)=>e-t);for(const n of ce(r)){const r=0===n[0]?0:n[0]-1,o=0===n[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:n.length,base:r,sheetId:e.sheetId,sheetName:e.sheetName,position:o})}return t}).add("ADD_MERGE",function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]}).add("REMOVE_MERGE",function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]}).add("CREATE_SHEET",function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId,sheetName:e.name}]}).add("DELETE_SHEET",function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1,name:e.sheetName}]}).add("DUPLICATE_SHEET",function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo,sheetName:""}]}).add("CREATE_FIGURE",function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]}).add("CREATE_CHART",function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]}).add("HIDE_COLUMNS_ROWS",function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}).add("UNHIDE_COLUMNS_ROWS",function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}).add("CREATE_TABLE_STYLE",function(e){return[{type:"REMOVE_TABLE_STYLE",tableStyleId:e.tableStyleId}]}).add("ADD_PIVOT",function(e){return[{type:"REMOVE_PIVOT",pivotId:e.pivotId}]}).add("RENAME_SHEET",function(e){return[{type:"RENAME_SHEET",sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]});for(const e of ys.values())Wb.contains(e)||Wb.add(e,qb);function qb(e){return[e]}function Zb(e){return Wb.get(e.type)(e)}class Yb{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find(t=>t.id===e);if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const r of this.operations){if(r.id===e)return e;if(r.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find(t=>t.id===e)}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map(e=>e.transformed(t))]}insert(e,t){const r=this.buildTransformation.with(e.data),{before:n,operation:o,after:s}=this.locateOperation(t);this.operations=[...n,o,e,...s.map(e=>e.transformed(r))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new Yb(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 jb{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new Xb(this.id,xe(()=>e(this.data)))}}class Xb{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new Xb(this.id,this.lazyData.map(e))}}class Kb{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new Kb(function*(e,t){for(const r of e)if(yield r,r.operation.id===t)return}(this.operations,e))}stopBefore(e){return new Kb(function*(e,t){for(const r of e){if(r.operation.id===t)return;yield r}}(this.operations,e))}startAfter(e){return new Kb(function*(e,t){let r=!0;for(const n of e)r||(yield n),n.operation.id===t&&(r=!1)}(this.operations,e))}}class Qb{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 Kb(ue(this._execution(e),this._execution(e)))}revertedExecution(e){return new Kb(ue(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const r=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),r&&this.insertPrevious(e,t,r)}insertOperationAfter(e,t,r){e.insert(t,r),this.updateNextWith(e,t,r),this.insertPrevious(e,t,r)}undo(e,t){const r=this.buildTransformation.without(t.data),n=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const o=e.fork(t.id);n&&this.branchingOperationIds.set(o,n),this.insertBranchAfter(e,o),this.transform(o,r)}redo(e){const t=this.nextBranch(e);if(!t)return;const r=this.nextBranch(t);this.removeBranchFromTree(t);const n=this.branchingOperationIds.get(t);n?this.branchingOperationIds.set(e,n):this.branchingOperationIds.delete(e),r&&this.rebaseUp(r)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const r of this.revertedExecution(e))if(r.operation.id===t)return r;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:r}=this.findPreviousBranchingOperation(e);if(!t||!r)return;const n=this.buildTransformation.without(r.data),o=t.fork(r.id);this.branchingOperationIds.set(o,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,o),o.transform(n);const s=this.nextBranch(o);s&&this.rebaseUp(s)}removeBranchFromTree(e){const t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){const r=this.branches.findIndex(t=>t===e);this.branches.splice(r+1,0,t)}updateNextWith(e,t,r){const n=this.branchingOperationIds.get(e),o=this.nextBranch(e);if(n&&o)if(e.getFirstOperationAmong(r,n)===n){const s=this.addToNextBranch(e,o,n,t,r);this.updateNextWith(o,s,r)}else{const e=this.buildTransformation.with(t.data);this.transform(o,e)}}addToNextBranch(e,t,r,n,o){let s=n;return o===r?(s=this.getTransformedOperation(e,r,n),t.prepend(s)):t.contains(o)?(s=this.getTransformedOperation(e,r,n),t.insert(s,o)):t.append(n),s}getTransformedOperation(e,t,r){const n=e.getOperation(t),o=this.buildTransformation.without(n.data);return r.transformed(o)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const r=this.nextBranch(e);r&&this.transform(r,t)}insertPrevious(e,t,r){const{previousBranch:n,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!n||!o)return;const s=this.buildTransformation.with(o.data),i=e.fork(r);i.transform(s),n.cutAfter(r),n.appendBranch(i);const a=t.transformed(s);this.insertPrevious(n,a,r)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const r=this.branchingOperationIds.get(t);return r?{previousBranch:t,branchingOperation:t.getOperation(r)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex(t=>t===e);if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex(t=>t===e);if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let r=!!t;const n=e.getOperations();for(let o=n.length-1;o>=0;o--){const s=n[o];s.id===t&&(r=!1),r||(yield{operation:s,branch:e,isCancelled:!this.shouldExecute(e,s)})}const o=this.previousBranch(e);yield*o?this._revertedExecution(o):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class Jb{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 Yb(this.buildTransformation),this.tree=new Qb(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,r=new jb(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 jb(e,t),n=this.tree.getLastBranch();this.tree.insertOperationLast(n,r),this.HEAD_BRANCH=n,this.HEAD_OPERATION=r}insert(e,t,r){const n=new jb(e,t);this.revertTo(r),this.tree.insertOperationAfter(this.HEAD_BRANCH,n,r),this.fastForward()}undo(e,t,r){const{branch:n,operation:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(n,o),this.fastForward(),this.insert(t,this.buildEmpty(t),r)}redo(e,t,r){const{branch:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(n),this.fastForward(),this.insert(t,this.buildEmpty(t),r)}rebase(e){const t=this.get(e),r=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);const n=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,n);for(const{operation:e}of r)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:r,isCancelled:n}of e)n||this.revertOperation(r.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:r,isCancelled:n}of e)n||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=r}}function ev(e){return new Jb({initialOperationId:e.initialRevisionId,applyOperation:t=>{const r=t.commands.slice(),{changes:n}=e.recordChanges(()=>{for(const t of r)e.dispatch(t)});t.setChanges(n)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){tv(t.changes[e])}}([e]),buildEmpty:e=>new zb(e,"empty",[]),buildTransformation:{with:e=>t=>new zb(t.id,t.clientId,Hb(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new zb(t.id,t.clientId,Hb(t.commands,e.commands.map(Zb).flat()),t.rootCommand,void 0,t.timestamp)}})}function tv(e){const t=e.target,r=e.key,n=e.before;void 0===n?delete t[r]:t[r]=n}class rv{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const nv=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart","comboChart","radarChart"],ov="M256 9 a247 247 0 1 0.1 0 0";function sv(e){return{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:e.textColor||k,path:"M120 195 h270 l-135 130"}]}}const iv="M40 185 h270 l-135 128";function av(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||k,path:iv}]}}function lv(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||k,path:"M0,225 A175,175 0 1,0 350,225 A175,175 0 1,0 0,225"},{fillColor:e.fillColor||k,path:iv}]}}const cv={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"}]},uv={name:"CHECKBOX_UNCHECKED",width:512,height:512,paths:[{fillColor:U,path:"M45,45 h422 v422 h-422 v-422 m30,30 v362 h362 v-362"}]},hv={name:"CHECKBOX_CHECKED",width:512,height:512,paths:[{fillColor:U,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 dv(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?P:"#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 fv={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:ov}]}},dotNeutral:{template:"YELLOW_DOT",svg:{name:"YELLOW_DOT",width:512,height:512,paths:[{fillColor:"#F0AD4E",path:ov}]}},dotBad:{template:"RED_DOT",svg:{name:"RED_DOT",width:512,height:512,paths:[{fillColor:"#E06666",path:ov}]}}},gv={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("/"),n=t.split("/");let o="",s=0;for(let e=0;e<r.length-1;e++)r[e]===n[e]?s++:o+="../";return o+=n.slice(s).join("/"),o}function pv(e,t=0){const r={};for(let n=0;n<e.length;n++)e[n]&&(r[n+t]=e[n]);return r}function bv(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}function vv(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 yv(e){if("="===e[0])return e;const t=Ml(e);return 1===t.length&&"REFERENCE"!==t[0].type?e:"="+e}var wv;!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"}(wv||(wv={}));class Ev{_parsingWarnings=new Set;_conversionWarnings=new Set;addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,r){let n=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;r&&(n+=`Only ${r.join(", ")} are currently supported.`),this._conversionWarnings.has(n)||this._conversionWarnings.add(n)}}const Sv=["thin","medium","thick","dashed","dotted"],Cv=["general","left","center","right"],Tv=["top","center","bottom"],Iv=["Arial"],xv=["solid","none"],Rv=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWithText","containsBlanks","notContainsBlanks"],Av={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},_v={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"},Ov={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},Dv={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},Fv={top:"top",middle:"center",bottom:"bottom"},Nv={beginsWith:"beginsWithText",endsWith:"endsWithText",containsText:"containsText",notContains:"notContainsText",between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},Mv={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},Vv={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},Lv={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"},Pv={none:"none",b:"bottom",t:"top",l:"left",r:"right",tr:"right"},kv={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"},Uv={exp:"exponential",log:"logarithmic",poly:"polynomial",movingAvg:"trailingMovingAverage"},Hv={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"},Bv={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:"@"},zv={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},$v={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"},Gv={"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"},Wv={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"},qv={between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},Zv={between:"dateIsBetween",notBetween:"dateIsNotBetween",equal:"dateIs",greaterThan:"dateIsAfter",greaterThanOrEqual:"dateIsOnOrAfter",lessThan:"dateIsBefore",lessThanOrEqual:"dateIsOnOrBefore"};function Yv(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=jp;else{if(!e.indexed)return;t=$v[e.indexed]}var r;return t=6===(r=t).length?"#"+r+"FF":"#"+r.slice(2)+r.slice(0,2),e.tint&&(t=function(e,t){const r=op(e),n=ip(r);t<0&&(n.l=n.l*(1+t));t>0&&(n.l=n.l*(1-t)+(100-100*(1-t)));return np(sp(n))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function jv(e){return 9===e.length&&(e=e.slice(0,7)),parseInt(e.replace("#",""),16)}const Xv=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function Kv(e,t,r){const n=Bv[e]||t.find(t=>t.id===e)?.format;if("General"!==n){if(n)try{let e=n.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]");if(e=e.replace(/\[\$\]/g,""),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),function(e){return Xv.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 Fn(0,{format:e,locale:Dl}),!0}catch(e){return!1}}(e))return e}catch(e){}r.generateNotSupportedWarning(wv.NumFmtIdNotSupported,n||`nmFmtId ${e}`)}}function Qv(e,t){const r=e.borders.map(e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(wv.DiagonalBorderNotSupported)}(e,t);const r={top:Jv(e.top,t),bottom:Jv(e.bottom,t),left:Jv(e.left,t),right:Jv(e.right,t)};return Object.keys(r).forEach(e=>void 0===r[e]&&delete r[e]),r});return pv(r,1)}function Jv(e,t){if(!e)return;!function(e,t){Sv.includes(e.style)||t.generateNotSupportedWarning(wv.BorderStyleNotSupported,e.style,Sv)}(e,t);const r=_v[e.style];return r?{style:r,color:Yv(e.color)}:void 0}function ey(e,t){return pv(e.styles.map(r=>ty({fontStyle:e.fonts[r.fontId],fillStyle:e.fills[r.fillId],alignment:r.alignment},t)),1)}function ty(e,t){return function(e,t,r){e&&e.name&&!Iv.includes(e.name)&&r.generateNotSupportedWarning(wv.FontNotSupported,e.name,Iv);t&&t.patternType&&!xv.includes(t.patternType)&&r.generateNotSupportedWarning(wv.FillStyleNotSupported,t.patternType,xv)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!Cv.includes(e)&&t.generateNotSupportedWarning(wv.HorizontalAlignmentNotSupported,e,Cv)}(e?.alignment?.horizontal,t),function(e,t){e&&!Tv.includes(e)&&t.generateNotSupportedWarning(wv.VerticalAlignmentNotSupported,e,Tv)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?Dv[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?Ov[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?Yv(e.fillStyle?.fgColor):Yv(e.fillStyle?.bgColor),textColor:Yv(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function ry(e,t){const r=[];for(const n of e.styles){const o=Kv(n.numFmtId,e.numFmts,t);o&&(r[n.numFmtId]=o)}return pv(r,1)}function ny(e,t,r){const n=[];let o=1;for(const s of e){if(0===s.cfRules.length)continue;ly(s,t,r);const e=s.cfRules[0];let i;const a=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type||"dataBar"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"duplicateValues":case"top10":case"uniqueValues":case"timePeriod":continue;case"dataBar":const t=oy(o++,s);t&&n.push(t);continue;case"colorScale":const l=sy(o++,s);l&&n.push(l);continue;case"iconSet":const c=iy(o++,s,r);c&&n.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;i=Mv[e.type],a.push(e.text);break;case"expression":if(!e.formula?.length)continue;i=Mv[e.type],a.push(`=${e.formula[0]}`);break;case"containsBlanks":case"notContainsBlanks":i=Mv[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;i=Nv[e.operator],a.push(yv(e.formula[0])),2===e.formula.length&&a.push(yv(e.formula[1]))}i&&void 0!==e.dxfId&&n.push({id:(o++).toString(),ranges:s.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:i,values:a,style:ty({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},r)}})}}return n}function oy(e,t){const r=t.cfRules[0].dataBar;if(!r)return;const n=jv(Yv(r.color)||"#FFFFFF");return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"DataBarRule",color:n}}}function sy(e,t){const r=t.cfRules[0].colorScale;if(!r||r.cfvos.length!==r.colors.length||r.cfvos.length<2||r.cfvos.length>3)return;const n=[];for(let e=0;e<r.cfvos.length;e++)n.push({color:jv(Yv(r.colors[e])||"#FFFFFF"),type:Vv[r.cfvos[e].type],value:r.cfvos[e].value});const o=n[0],s=2===n.length?n[1]:n[2],i=3===n.length?n[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:o,midpoint:i,maximum:s}}}function iy(e,t,r){const n=t.cfRules[0].iconSet;if(!n)return;let o=n.cfvos,s=n.cfIcons;if(o.length<3||s&&s.length<3)return;o.length>3&&(o=[o[0],o[Math.floor(o.length/2)],o[o.length-1]]),s&&s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]);const i=[];for(let e=1;e<=2;e++){const t=Vv[o[e].type];if("value"===t)return;i.push({value:o[e].value||"",operator:o[e].gte?"ge":"gt",type:t})}let a={lower:s?ay(s[0].iconSet,s[0].iconId):ay(n.iconSet,0),middle:s?ay(s[1].iconSet,s[1].iconId):ay(n.iconSet,1),upper:s?ay(s[2].iconSet,s[2].iconId):ay(n.iconSet,2)};n.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(const e of Object.keys(a))if(!a[e])switch(r.generateNotSupportedWarning(wv.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=gv.dots.good;break;case"middle":a[e]=gv.dots.neutral;break;case"lower":a[e]=gv.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 ay(e,t){const r=Lv[e];return r?0===t?gv[r].bad:1===t?gv[r].neutral:gv[r].good:""}function ly(e,t,r){if(e.cfRules.length>1&&r.generateNotSupportedWarning(wv.MultipleRulesCfNotSupported),Rv.includes(e.cfRules[0].type)||r.generateNotSupportedWarning(wv.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const n=t[e.cfRules[0].dxfId];n.border&&r.generateNotSupportedWarning(wv.CfFormatBorderNotSupported),n.alignment&&r.generateNotSupportedWarning(wv.CfFormatAlignmentNotSupported),n.numFmt&&r.generateNotSupportedWarning(wv.CfFormatNumFmtNotSupported)}}const cy=new WeakMap,uy=new WeakMap;function hy(e,t){cy.has(t)||(cy.set(t,new Map),uy.set(t,0));const r=cy.get(t),n=gy(e);if(r.has(n)){const o=r.get(n);return t[o]=e,o}const o=uy.get(t)+1;return r.set(n,o),uy.set(t,o),t[o]=e,o}function dy(e){const t={};for(const r in e){const n=Fo(e[r].map(ss));for(const e of n)t[Go(e)]=Number(r)}return t}function*fy(e,t){for(const r in t){const n=Bo(r),o=t[r];for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++){const n={sheetId:e,col:r,row:t};yield[n,o]}}}function gy(e){if(null===e)return"null";if(void 0===e)return"undefined";if("object"!=typeof e)return String(e);if(Array.isArray(e)){const t=e.length;let r="[";for(let n=0;n<t;n++)n>0&&(r+=","),r+=gy(e[n]);return r+"]"}const t=Object.keys(e).sort();let r="{";for(const n of t)void 0!==e[n]&&(r+=`"${n}":${gy(e[n])},`);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":return"greaterThan";case"isGreaterOrEqualTo":return"greaterThanOrEqual";case"isLessThan":return"lessThan";case"isLessOrEqualTo":return"lessThanOrEqual";case"isBetween":return"between";case"isNotBetween":return"notBetween";case"isEqual":return"equal";case"isNotEqual":return"notEqual";case"customFormula":return""}}function py(e){return Math.round(Cb*e*100)/100}function by(e){return Math.round(Tb*e*100)/100}function vy(e){return e?Math.round(e/Cb*100)/100:e}function yy(e){return e?Math.round(e/Tb*100)/100:e}function wy(e,t,r,n,o){const s=r?e.styles[r]:{},i=n?e.formats[n]:void 0,a={font:{size:s?.fontSize||q,color:{rgb:s?.textColor?s.textColor:"000000"},family:2,name:"Arial"},fill:s?.fillColor?{fgColor:{rgb:s.fillColor}}:{reservedAttribute:"none"},numFmt:i?{format:i,id:0}:void 0,border:o||0,alignment:{horizontal:s.align,vertical:s.verticalAlign?Fv[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 Ey(e,t){const r=function(e,t){if(!e)return 0;let r=zv[e.format];r||(r=Ty(e,t)+164);return r}(t.numFmt,e.numFmts),n={fontId:Ty(t.font,e.fonts),fillId:Ty(t.fill,e.fills),borderId:t.border,numFmtId:r,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText}};return Ty(n,e.styles)}function Sy(e,t,r){const n=e.find(e=>e.path===t);let o;return n?(o=`rId${(n.rels.length+1).toString()}`,n.rels.push({...r,id:o})):(o="rId1",e.push({path:t,rels:[{...r,id:o}]})),o}const Cy=new WeakMap;function Ty(e,t){let r=Cy.get(t);if(!r){r=new Map;for(let e=0;e<t.length;e++){const n=gy(t[e]);r.set(n,e)}Cy.set(t,r)}const n=gy(e);if(r.has(n))return r.get(n);const o=t.length;return t.push(e),r.set(n,o),o}function Iy(e,t){const r=t.chartIds.findIndex(t=>t===e);return-1===r?(t.chartIds.push(e),t.chartIds.length):r+1}const xy=[];function Ry(e){const t=xy.findIndex(t=>t===e);return-1===t?(xy.push(e),xy.length):t+1}function Ay(e){return Math.round(914400*e/96)}function _y(e,t,r){let n,o,s=e;if(({xc:s,sheetName:n}=go(e)),n){const e=r.sheets.findIndex(e=>Im(e.name,n));if(e<0)throw new Error("Unable to find a sheet with the name "+n);o=e}else o=Number(t);const i=Ho(s);return void 0===i.right&&(i.right=r.sheets[o].colNumber),void 0===i.bottom&&(i.bottom=r.sheets[o].rowNumber),(i.right-i.left+1)*(i.bottom-i.top+1)}function Oy(e){return Math.round(96*e/914400)}function Dy(e,t){let r=0;for(let n=0;n<e;n++){const e=t.cols.find(e=>n>=e.min&&n<=e.max);e?.width?r+=e.width:t.sheetFormat?.defaultColWidth?r+=t.sheetFormat.defaultColWidth:r+=Ib}return r/Tb}function Fy(e,t){let r=0;for(let n=0;n<e;n++){const e=t.rows.find(e=>e.index-1===n);e?.height?r+=e.height:t.sheetFormat?.defaultRowHeight?r+=t.sheetFormat.defaultRowHeight:r+=xb}return r/Cb}function Ny(e){let t=1;return e.figures.map(r=>function(e,t,r){let n,o,s,i,a;if(1===e.anchors.length)({col:n,row:o,offset:s}=Py(e.anchors[0])),a=Oy(e.figureSize.cx),i=Oy(e.figureSize.cy);else{({col:n,row:o,offset:s}=Py(e.anchors[0]));const{x:t,y:l}=ky(e.anchors[0],r),{x:c,y:u}=ky(e.anchors[1],r);a=c-t,i=u-l}const l={id:t,col:n,row:o,offset:s};if("dataSets"in(c=e.data)&&c.dataSets.length>0)return{...l,width:a,height:i,tag:"chart",data:My(e.data)};if(function(e){return"imageSrc"in e}(e.data))return{...l,width:Oy(e.data.size.cx),height:Oy(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 My(e){const t=e.dataSets.some(e=>"reference"in(e.label??{})),r=e.labelRange?Vy(e.labelRange,t):void 0,n=e.dataSets.map(e=>{let r;return e.label&&"text"in e.label&&(r=e.label.text),{dataRange:Vy(e.range,t),label:r,backgroundColor:e.backgroundColor,trend:Ly(e.trend)}});"pie"===e.type&&n.reverse();const o={range:n,dataSetsHaveTitle:t,auxiliaryRange:r,title:e.title??{text:""},background:Yv({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 Yp.get(e.type).getChartDefinitionFromContextCreation(o)}catch(e){return}}function Vy(e,t){const{sheetName:r,xc:n}=go(e);let o=Ho(n);if(t&&void 0!==o.bottom&&void 0!==o.right){const e=o.bottom-o.top+1,t=o.right-o.left+1;1===e?o={...o,left:o.left-1}:1===t&&(o={...o,top:o.top-1})}return mo(r,Go(o))}function Ly(e){if(e&&e.type)return{type:"linear"===e.type?"polynomial":Uv[e.type],order:"linear"===e.type?1:e.order,color:e.color,window:e.window||2,display:!0}}function Py(e){const t={x:Oy(e.colOffset)-1,y:Oy(e.rowOffset)-1};return{col:e.col,row:e.row,offset:t}}function ky(e,t){return{x:Dy(e.col,t)+Oy(e.colOffset),y:Fy(e.row,t)+Oy(e.rowOffset)}}function Uy(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const Hy=new fd;function By(e,t){return{url:e=Uy(e),label:t||e,isExternal:!0,isUrlEditable:!0}}Hy.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 zy={createLink:By,match:e=>me(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function $y(e){if("string"==typeof e){if(ge(e)){const{label:t,url:r}=be(e);return function(e){return Hy.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||zy}(r).createLink(r,t)}return me(e)?By(e):void 0}}function Gy(e,t,r){return qy({value:Qn(t.format)&&null!==e.parsedValue?e.content:e.parsedValue,format:t.format,origin:r},t.locale)}function Wy(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,Dl))return Dt(e,Dl);const r=gt(e,t);return r?r.value:he(e)?"TRUE"===e.toUpperCase():e}function qy(e,t=Dl,r,n){const o=$y(e.value);if(!o){return Xy(Zy(e,t,r),e.origin??n)}const s=Wy(o.label,t);return Xy({...Zy({value:s,format:e.format||("number"==typeof s?Gn(o.label,t)||Wn(o.label):void 0)},t,r),link:o},e.origin??n)}function Zy(e,t,r){let{value:n,format:o,message:s}=e;o=r?.format||o;const i=Fn(n,{format:o,locale:t});return Vt(n)?function(e,t){return{value:e,formattedValue:e,message:t,type:Eu.error,isAutoSummable:!1,defaultAlign:"center"}}(n,s):null===n?jy(o):Qn(o)?Yy($t(n),o,i):"number"==typeof n?Hn(o||"")?function(e,t,r){return{value:e,format:t,formattedValue:r,type:Eu.number,isAutoSummable:!1,defaultAlign:"right"}}(n,o,i):function(e,t,r){return{value:e||0,format:t,formattedValue:r,type:Eu.number,isAutoSummable:!0,defaultAlign:"right"}}(n,o,i):"boolean"==typeof n?function(e,t,r){return{value:e,format:t,formattedValue:r,type:Eu.boolean,isAutoSummable:!1,defaultAlign:"center"}}(n,o,i):Yy(n,o,i)}function Yy(e,t,r){return{value:e,format:t,formattedValue:r,type:Eu.text,isAutoSummable:!0,defaultAlign:"left"}}const jy=Ue(function(e){return{value:null,format:e,formattedValue:"",type:Eu.empty,isAutoSummable:!0,defaultAlign:"left"}});function Xy(e,t){return null===e.value||"origin"in e||(e.origin=t),e}function Ky(e){const t=Qe.now();switch(e){case"today":return bt(t);case"yesterday":return bt(Qe.fromTimestamp(t.setDate(t.getDate()-1)));case"tomorrow":return bt(Qe.fromTimestamp(t.setDate(t.getDate()+1)));case"lastWeek":return bt(Qe.fromTimestamp(t.setDate(t.getDate()-7)));case"lastMonth":return bt(Qe.fromTimestamp(t.setMonth(t.getMonth()-1)));case"lastYear":return bt(Qe.fromTimestamp(t.setFullYear(t.getFullYear()-1)))}}function Qy(e,t){return"dateValue"in e&&"exactDate"!==e.dateValue?[Ky(e.dateValue)]:e.values.map(e=>ht(e,t))}function Jy(e,t){return e.map(e=>{if(e.startsWith("="))return e;const r=Wy(e,t);return"number"==typeof r?Fn(r,{format:t.dateFormat,locale:t}):""})}function ew(e,t){const r=[];let n=1;for(const o of e)if(o)switch(o.type){case"time":t.generateNotSupportedWarning(wv.TimeDataValidationNotSupported);break;case"textLength":t.generateNotSupportedWarning(wv.TextLengthDataValidationNotSupported);break;case"whole":t.generateNotSupportedWarning(wv.WholeNumberDataValidationNotSupported);break;case"decimal":const e=tw(n++,o);r.push(e);break;case"list":const s=rw(n++,o);r.push(s);break;case"date":if("notEqual"===o.operator){t.generateNotSupportedWarning(wv.NotEqualDateDataValidationNotSupported);break}const i=nw(n++,o);r.push(i);break;case"custom":const a=ow(n++,o);r.push(a)}return r}function tw(e,t){const r=[yv(t.formula1.toString())];return t.formula2&&r.push(yv(t.formula2.toString())),{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:qv[t.operator],values:r}}}function rw(e,t){const r=t.formula1.toString(),n=ao.test(r);return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:n?"isValueInRange":"isValueInList",values:n?[r]:r.replaceAll('"',"").split(","),displayStyle:"arrow"}}}function nw(e,t){let r;const n=[yv(t.formula1.toString())];return t.formula2?(n.push(yv(t.formula2.toString())),r={type:Zv[t.operator],values:Jy(n,Dl)}):r={type:Zv[t.operator],values:Jy(n,Dl),dateValue:"exactDate"},{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:r}}function ow(e,t){return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:"customFormula",values:[yv(t.formula1.toString())]}}}const sw=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),iw=new RegExp(/SUBTOTAL\(([0-9]*),/g),aw=new RegExp(to.source,"ig");function lw(e,t){const r=function(e){const t={};for(const r of e.rows)for(const e of r.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(const n of e.rows.map(e=>e.cells).flat())n?.formula&&(n.formula.content=void 0===n.formula.sharedIndex||n.formula.content?"="+n.formula.content:"="+uw(n.xc,r[n.formula.sharedIndex]),n.formula.content=cw(n.formula.content,t))}function cw(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(iw,(e,t)=>{const r=Hv[t];return r?r+"(":e})).replace(sw,(e,r,n,o)=>{r=Number(r)-1,o=o.replace(/\$/g,"");const s=t.externalBooks[r].sheetNames.findIndex(e=>Im(e,n));if(-1===s)return e;const i=t.externalBooks[r].datasets.find(e=>e.sheetId===s)?.data;if(!i)return e;const a=i&&i[o];return(Number(a)?a:`"${a}"`)||e})}function uw(e,t){const r=Oo(t.refCellXc);let n,o=t.formula.slice();do{if(n=aw.exec(o),n){const t=Oo(n[0].replace("$","")),s=Oo(e),i={colFixed:n[0].startsWith("$"),rowFixed:n[0].includes("$",1)},a={col:s.col-r.col,row:s.row-r.row},l={col:i.colFixed?t.col:t.col+a.col,row:i.rowFixed?t.row:t.row+a.row};o=o.slice(0,n.index)+Do(l.col,l.row,i)+o.slice(n.index+n[0].length)}}while(n);return o}function hw(e,t){return e.sheets.map(r=>{lw(r,e);const n=function(e){const t=[0,0];for(const r of e.rows)t[0]=Math.max(t[0],We(r.cells.map(e=>Oo(e.xc).col))),t[1]=Math.max(t[1],r.index);for(const r of e.figures)t[0]=Math.max(t[0],r.anchors[r.anchors.length-1]?.col??0),t[1]=Math.max(t[1],r.anchors[r.anchors.length-1]?.row??0);return t[0]=Math.max(t[0]+5,30),t[1]=Math.max(t[1]+5,100),t}(r),o=r.sheetViews[0],s=pw(r,"ROW",n[1]),i=pw(r,"COL",n[0]);return{id:r.sheetName,areGridLinesVisible:!o||o.showGridLines,name:r.sheetName,colNumber:n[0],rowNumber:n[1],...gw(r,e,n,t),merges:r.merges,cols:dw(r,n[0],i),rows:fw(r,n[1],s),conditionalFormats:ny(r.cfs,e.dxfs,t),dataValidationRules:ew(r.dataValidations,t),figures:Ny(r),isVisible:r.isVisible,panes:o?{xSplit:o.pane.xSplit,ySplit:o.pane.ySplit}:{xSplit:0,ySplit:0},tables:[],headerGroups:{COL:i,ROW:s},color:Yv(r.sheetProperties?.tabColor)}})}function dw(e,t,r){const n={};for(let o=1;o<t+1;o++){const t=e.cols.find(e=>e.min<=o&&o<=e.max);let s;s=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:Ib;const i=o-1,a=r.some(e=>e.isFolded&&e.start<=i&&i<=e.end);n[i]={size:yy(s),isHidden:!a&&t?.hidden}}return n}function fw(e,t,r){const n={};for(let o=1;o<t+1;o++){const t=e.rows.find(e=>e.index===o);let s;s=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:xb;const i=o-1,a=r.some(e=>e.isFolded&&e.start<=i&&i<=e.end);n[i]={size:vy(s),isHidden:!a&&t?.hidden}}return n}function gw(e,t,r,n){const o={},s={},i={},a={},l=t.sharedStrings.map(Pe);const c=e.hyperlinks.reduce((e,t)=>(e[t.xc]=t,e),{});for(const r of e.rows)for(const e of r.cells)o[e.xc]=mw(e,c,l,n),e.styleIndex&&(s[e.xc]=e.styleIndex+1,i[e.xc]=t.styles[e.styleIndex].numFmtId+1,a[e.xc]=t.styles[e.styleIndex].borderId+1);for(const n of e.rows.filter(e=>e.styleIndex))for(let e=1;e<=r[0];e++){const r=Do(e-1,n.index-1);s[r]??=n.styleIndex+1,a[r]??=t.styles[n.styleIndex].borderId+1,i[r]??=t.styles[n.styleIndex].numFmtId+1}for(const n of e.cols.filter(e=>e.styleIndex))for(let e=n.min;e<=Math.min(n.max,r[0]);e++)for(let o=1;o<=r[1];o++){const r=Do(e-1,o-1);s[r]??=n.styleIndex+1,a[r]??=t.styles[n.styleIndex].borderId+1,i[r]??=t.styles[n.styleIndex].numFmtId+1}return{cells:o,styles:s,formats:i,borders:a}}function mw(e,t,r,n){let o;switch(e.type){case"sharedString":o=r[parseInt(e.value,10)];break;case"boolean":o=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":o=e.value}return o&&t[e.xc]&&(o=function(e,t,r){const n=e.display||t;e.relTarget||e.location||r.generateNotSupportedWarning(wv.BadlyFormattedHyperlink);const o=e.relTarget?e.relTarget:we(go(e.location).sheetName);return pe(n,o)}(t[e.xc],o,n)),e.formula&&(o=e.formula.content),o}function pw(e,t,r){const n=e?.sheetProperties?.outlinePr,o=[];let s=0;for(let i=0;i<r;i++){const r=vw(e,t,i),a=r?.outlineLevel||0;if(a>s){const r=bw(e,t,i,("ROW"===t?n?.summaryBelow:n?.summaryRight)??!0);r&&o.push(r)}s=a}return o}function bw(e,t,r,n){const o=vw(e,t,r),s=o?.outlineLevel;if(!s||!s)return;let i=s,a=r,l=o;for(;l&&i>=s;)a++,l=vw(e,t,a),i=l?.outlineLevel||0;const c=r,u=a-1,h=vw(e,t,n?u+1:c-1);return{start:c-1,end:u-1,isFolded:h?.collapsed||!1}}function vw(e,t,r){return"COL"===t?e.cols.find(e=>e.min<=r&&r<=e.max):e.rows.find(e=>e.index===r)}function yw(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:ww(e)});for(const e of r.pivotTables)t.tables.push({range:e.location.ref,config:Ew(e)})}}!function(e,t){let r=null;for(const n of e){const o=t.find(e=>Im(e.sheetName,n.name)).tables;if(o&&0!==o.length){r||(r=Sw(e));for(const t of o)for(const o in r){const s=e.find(e=>e.id===o);for(const e in r[o]){for(let i=r[o][e].length-3;i>=0;i-=2){const a=r[o][e][i];if(!a.endsWith(t.name))continue;const l=r[o][e][i+1],c=Cw(n.id===s.id?"":n.name+"!",l,t,e);r[o][e][i+2]=a.slice(0,a.indexOf(t.name))+c+r[o][e][i+2],r[o][e].splice(i,2)}}}}}if(!r)return;for(const t in r){const n=e.find(e=>e.id===t);for(const e in r[t]){const o=r[t][e];if(1===o.length){n.cells[e]=o[0];continue}let s="";for(let e=0;e<o.length;e+=2)s+=o[e]+"["+o[e+1]+"]";s+=o[o.length-1],n.cells[e]=s}}}(e.sheets,t.sheets)}function ww(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:Hp[t]?t:Tp.styleId}}function Ew(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:Tp.styleId}}function Sw(e){const t={};for(const r of e)for(const e in r.cells){const n=r.cells[e];if(!n||!n.startsWith("="))continue;const o=n.indexOf("[");if(-1===o)continue;const s=[];let i=n.slice(0,o),a="",l=1,c=0,u=o;for(let e=o+1;e<n.length;e++)"["!==n[e]?"]"===n[e]&&(l--,0===l&&(a=n.slice(u+1,e),s.push(i),s.push(a),c=e+1)):(0===l&&(i=n.slice(c,e),u=e),l++);s.length&&(t[r.id]||(t[r.id]={}),s.push(n.slice(c)),t[r.id][e]=[...s])}return t}function Cw(e,t,r,n){const o=t.split(",").map(e=>e.trim()),s=Bo(r.ref),i=[],a=[],l=[];for(const e of o)if(Tw(e).startsWith("#")){const t=Tw(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(Oo(n).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(Tw);if(i.length)return w.InvalidReference;const n=r.cols.findIndex(e=>e.name===t[0]);if(-1===n)return w.InvalidReference;if(i.push(n+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+Go({top:Math.min(...a),left:Math.min(...i),bottom:Math.max(...a),right:Math.max(...i)})}function Tw(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,e.length-1):e}function Iw(e,t,r){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:r}}function xw(e){return String(e).replace(/\&/g,"&").replace(/\</g,"<").replace(/\>/g,">").replace(/\"/g,""").replace(/\'/g,"'").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function Rw(e){return new rv(e.map(([e,t])=>`${e}="${xw(t)}"`).join(" "))}function Aw(e,t="text/xml"){const r=(new DOMParser).parseFromString(e.toString(),t),n=r.querySelector("parsererror");if(n){const t=n.innerHTML,r=parseInt(t.split(":")[0],10),o=e.toString().trim().split("\n"),s=o.slice(Math.max(r-3,0),Math.min(r+2,o.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${s}`)}return r}function _w(e){if(e)return{style:e.style,color:{rgb:e.color}}}function Ow(e,t){return Fw`
|
|
1
|
+
!function(e){"use strict";class t{scope;code="";constructor(e=new n){this.scope=e}append(...e){this.code+=e.map(e=>e.toString()).join("\n")+"\n"}return(e){return new r(this.scope,this.code,e)}toString(){return o(this.code)}}class r{scope;returnExpression;code;constructor(e,t,r){this.scope=e,this.returnExpression=r,this.code=o(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;const e=this.scope.nextVariableName(),r=new t(this.scope);return r.append(this.code),r.append(`const ${e} = ${this.returnExpression};`),r.return(e)}}class n{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function o(e){let t="",r=0;const n=e.split("\n").map(e=>e.trim()).filter(e=>""!==e);for(const e of n)e.startsWith("}")&&r--,t+="\t".repeat(r)+e+"\n",e.endsWith("{")&&r++;return t.trim()}const s=/(.*?)\((.*?)\)(.*)/,i=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META","RANGE<META>"];function a(e,t="",r){return function(e,t,r){const n=e.match(s),o=n[1].trim();if(!o)throw new Error(`Function argument definition is missing a name: '${e}'.`);const a=[];let l,c=!1,u=!1;for(const e of n[2].split(",")){const t=e.trim().toUpperCase(),r=i.find(e=>t===e);r?a.push(r):"RANGE<ANY>"===t?a.push("RANGE"):"OPTIONAL"===t?c=!0:"REPEATING"===t?u=!0:t.startsWith("DEFAULT=")&&(l=e.trim().slice(8))}const h={name:o,description:t,type:a};(a.includes("ANY")||a.includes("RANGE"))&&(h.acceptErrors=!0);c&&(h.optional=!0);u&&(h.repeating=!0);void 0!==l&&(h.default=!0,h.defaultValue=l);a.some(e=>e.startsWith("RANGE"))&&(h.acceptMatrix=!0);a.every(e=>e.startsWith("RANGE"))&&(h.acceptMatrixOnly=!0);r&&r.length>0&&(h.proposalValues=r);return h}(e,t,r)}const l={};function c(e,t){const r=e.name,n=l[r]?.[t];return n||(l[r]||(l[r]={}),l[r][t]||(l[r][t]=function(e,t){const r={},n=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,o=e.nbrArgRepeating*n,s=t-e.minArgRequired-o;let i=0,a=0;for(let t=0;t<e.args.length;t++){const o=e.args[t];if(o.optional||o.default)a<s&&(r[i]=t,i++),a++;else if(o.repeating){for(let o=0;o<n;o++)for(let n=0;n<e.nbrArgRepeating;n++)r[i]=t+n,i++;t+=e.nbrArgRepeating-1}else r[i]=t,i++}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!",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 _ extends S{constructor(e=v("Division by zero")){super(e,w.DivisionByZero)}}function O(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 F="#017E84",N="#3266ca",M="#FFFFFF",V=F,L="#111827",P="#E7E9ED",k="#374151C2",U=F,H=20,B=16,z=["#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"],$=23,G={align:"left",verticalAlign:"bottom",wrapping:"overflow",bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:"",textColor:""},W=G.verticalAlign,q=G.fontSize,Z="'Roboto', arial",Y="START_REVISION",j="??",X=/'|\*|\?|\/|\\|\[|\]/,K="|";const Q="\n",J={hasFilters:!1,totalRow:!1,firstColumn:!0,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,styleId:"TableStyleMedium5",automaticAutofill:!1},ee=new RegExp(X,"g");function te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function re(e){switch(typeof e){case"object":{if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&null!==e&&(e?.constructor===Object||void 0===e?.constructor)}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");const t=Array.isArray(e)?new Array(e.length):{};if(Array.isArray(e))for(let r=0,n=e.length;r<n;r++)r in e&&(t[r]=re(e[r]));else for(const r in e)t[r]=re(e[r]);return t}case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function ne(e){return oe(e,"'")}function oe(e,t='"'){return e.startsWith(t)&&(e=e.slice(1)),e.endsWith(t)&&(e=e.slice(0,-1)),e}function se(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function ie(e,t=" "){return e.replace(ee,t)}function ae(e,t,r){return e<t?t:e>r?r:e}function le(e,t,r=1){if(t<=e&&r>0)return[];if(0===r)throw new Error("range() step must not be zero");const n=Math.ceil(Math.abs((t-e)/r)),o=Array(n);for(let t=0;t<n;t++)o[t]=e+t*r;return o}function ce(e){return e.reduce((e,t,r,n)=>{if(1===Math.abs(t-n[r-1])){e[e.length-1].push(t)}else e.push([t]);return e},[])}function*ue(e,t){t.next();for(const r of e){const e=t.next();yield{...r,next:e.done?void 0:e.value}}}function he(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}const de=/^\[(.+)\]\((.+)\)$/,fe=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function ge(e){return de.test(e)}function me(e){return fe.test(e)}function pe(e,t){return`[${e}](${t})`}function be(e){const t=e.match(de)||[],r=t[1],n=t[2];if(!r||!n)throw new Error(`Could not parse markdown link ${e}.`);return{label:r,url:n}}const ve="o-spreadsheet://";function ye(e){return e.startsWith(ve)}function 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 n,o=!1;const s=function(){const s=this,i=Array.from(arguments);if(!o&&r)return o=!0,e.apply(s,i);clearTimeout(n),n=setTimeout(function(){n=void 0,o=!1,e.apply(s,i)},t)};return s.isDebouncePending=()=>void 0!==n,s.stopDebounce=()=>{clearTimeout(n)},s}function Ie(e){let t="";for(let r=0,n=e.length;r<n;r++)t+=e[r];return t}function xe(e){let t,r=!1;const n=()=>(r||(t=e instanceof Function?e():e,r=!0),t);return n.map=e=>xe(()=>e(n())),n}function Re(e,t){return"after"===e?t+1:t}function Ae(...e){if(e.length<=1)return!0;for(let t=1;t<e.length;t++)if(!_e(e[0],e[t]))return!1;return!0}function _e(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(!_e(e[r],t[r]))return!1}else if(e[r]!==t[r])return!1}return!0}function Oe(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ae(e[r],t[r]))return!1;return!0}function De(e,t){if(e.length<t.length)return!1;const r=new Set(e);return t.every(e=>r.has(e))}function Fe(e){if(!e)return e;const t={...e};return Object.keys(t).forEach(e=>!t[e]&&delete t[e]),t}const Ne=["\t","\f","\v",String.fromCharCode(parseInt("00a0",16)),String.fromCharCode(parseInt("1680",16)),String.fromCharCode(parseInt("2000",16)),String.fromCharCode(parseInt("200a",16)),String.fromCharCode(parseInt("2028",16)),String.fromCharCode(parseInt("2029",16)),String.fromCharCode(parseInt("202f",16)),String.fromCharCode(parseInt("205f",16)),String.fromCharCode(parseInt("3000",16)),String.fromCharCode(parseInt("feff",16))],Me=new RegExp(Ne.join("|"),"g"),Ve=/(\r\n|\r)/g,Le=Ne.concat([" "]);function Pe(e){return e?e.replace(Ve,Q):""}function ke(e){const t=Array.from(e).sort((e,t)=>e-t);for(let e=1;e<t.length;e++)if(t[e]-t[e-1]!==1)return!1;return!0}function Ue(e){const t=new Map,r=e.name?e.name+" (memoized)":"memoized";return{[r]:(...r)=>(t.has(r[0])||t.set(r[0],e(...r)),t.get(r[0]))}[r]}function He(e,t){const r=new Set(t),n=[];for(let t=0;t<e.length;t++)r.has(t)||n.push(e[t]);return n}function Be(e,t,r){return e.slice(0,r).concat(t).concat(e.slice(r))}function ze(e,t,r){const n=[...e];return n[r]=t,n}function $e(e){return e.split("\n").map(e=>e.replace(/\s+/g," ").trim()).join("\n")}function Ge(e,t,r){return t>r?Ge(e,r,t):e>=t&&e<=r}function We(e){let t=e.length;if(t<1e5)return Math.max(...e);let r=-1/0;for(;t--;)r=e[t]>r?e[t]:r;return r}function qe(e){let t=e.length;if(t<1e5)return Math.min(...e);let r=1/0;for(;t--;)r=e[t]<r?e[t]:r;return r}class Ze{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){const e=this.current,t=this.text[++this.currentIndex];return this.current=t,e}advanceBy(e){this.currentIndex+=e,this.current=this.text[this.currentIndex]}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){if(this.current!==e[0])return!1;for(let t=1;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}}function Ye(e,t=e=>e){const r=new Set;return e.filter(e=>{const n=t(e);return!r.has(n)&&(r.add(n),!0)})}function je(e){const t={};for(const r in e)for(const n in e[r])t[n]||(t[n]={}),t[n][r]=e[r][n];return t}function Xe(e,t,r={}){const n=r.compute??((e,t)=>`${e} (${t})`),o=r.computeFirstOne??!1;let s=r.start??1,i=o?n(e,s):e;for(;t.includes(i);)i=n(e,s++);return i}function Ke(e){return e.startsWith("=")||e.startsWith("+")}class Qe{jsDate;constructor(e,t,r,n=0,o=0,s=0){this.jsDate=new Date(Date.UTC(e,t,r,n,o,s,0))}static fromTimestamp(e){const t=new Date(e);return new Qe(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new Qe(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getQuarter(){return Math.floor(this.getMonth()/3)+1}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}getIsoWeek(){const e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);const r=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-r.getTime())/864e5+1)/7)}setFullYear(e){return this.jsDate.setUTCFullYear(e)}setMonth(e){return this.jsDate.setUTCMonth(e)}setDate(e){return this.jsDate.setUTCDate(e)}setHours(e){return this.jsDate.setUTCHours(e)}setMinutes(e){return this.jsDate.setUTCMinutes(e)}setSeconds(e){return this.jsDate.setUTCSeconds(e)}}const Je=new Qe(1899,11,30),et=864e5,tt=2e3,rt=Qe.now().getFullYear(),nt=Qe.now().getMonth(),ot=Qe.fromTimestamp(0).getTime()-Je.getTime(),st=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,it=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,at=Le.join(""),lt=new RegExp(`/|-|${Le.join("|")}`),ct=new RegExp(`^(\\d{1,4})[/${at}-](\\d{1,4})([/${at}-](\\d{1,4}))?$`),ut=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function ht(e,t){switch(typeof e){case"number":return e;case"string":return dt(e,t)?gt(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function dt(e,t){return null!==gt(e,t)}const ft=new Map;function gt(e,t){return ft.has(t)||ft.set(t,new Map),ft.get(t).has(e)||ft.get(t).set(e,function(e,t){e=e.trim();let r=null;const n=e.match(ut);if(n){if(r=function(e){if(e=e.trim(),ut.test(e)){const t=/AM/i.test(e),r=/PM/i.test(e),n=(t||r?e.substring(0,e.length-2).trim():e).split(/:/),o=n.length>=2,s=3===n.length;let i=Number(n[0]),a=o?Number(n[1]):0,l=s?Number(n[2]):0,c=s?"hh:mm:ss":"hh:mm";if(t||r)c+=" a";else if(!o)return null;i>=12&&t?i-=12:i<12&&r&&(i+=12),a+=Math.floor(l/60),l%=60,i+=Math.floor(a/60),a%=60,i>=24&&(c="hhhh:mm:ss");return{value:i/24+a/1440+l/86400,format:c,jsDate:new Qe(1899,11,30,i,a,l)}}return null}(n[0]),null===r)return null;e=e.replace(n[0],"").trim()}let o=null;const s=function(e,t){const r=e.match(ct);if(!r)return null;const[,n,o,,s]=r;if(n.length>2&&s&&s.length>2)return null;if(n.length>2)return{year:n,month:o,day:s,dateString:e,type:"ymd"};const i=function(e){switch(e.dateFormat[0]){case"d":return"dmy";case"m":return"mdy";case"y":return"ymd"}throw new Error("Invalid date format in locale")}(t);if(!s)return o.length>2?{month:n,year:o,day:void 0,dateString:e,type:i}:"dmy"===i?{day:n,month:o,year:s,dateString:e,type:"dmy"}:{month:n,day:o,year:s,dateString:e,type:"mdy"};if(s.length>2)return"mdy"===i?{month:n,day:o,year:s,dateString:e,type:"mdy"}:{day:n,month:o,year:s,dateString:e,type:"dmy"};if("mdy"===i)return{month:n,day:o,year:s,dateString:e,type:"mdy"};if("ymd"===i)return{year:n,month:o,day:s,dateString:e,type:"ymd"};if("dmy"===i)return{day:n,month:o,year:s,dateString:e,type:"dmy"};return null}(e,t);if(s){const t=s.dateString.match(lt)[0];if(o=function(e,t){const{year:r,month:n,day:o}=e,s=function(e){if(!e)return nt;const t=Number(e);if(t>=1&&t<=12)return t-1;return null}(n),i=function(e){if(!e)return 1;const t=Number(e);if(t>=0&&t<=31)return t;return null}(o),a=function(e){if(!e)return rt;const t=Number(e);switch(e.length){case 1:return tt+t;case 2:return tt+(tt+t>rt+10?-100:0)+t;case 3:case 4:return t}return null}(r);if(null===a||null===s||null===i)return null;const l=2===n?.length&&s+1<10||2===o?.length&&i<10,c=2!==r?.length,u=new Qe(a,s,i);if(u.getMonth()!==s||u.getDate()!==i)return null;const h=u.getTime()-Je.getTime(),d=function(e,t,r,n){const o=e.year?n?"yyyy":"yy":void 0,s=e.month?r?"mm":"m":void 0,i=e.day?r?"dd":"d":void 0;switch(e.type){case"mdy":return[s,i,o].filter(Se).join(t);case"ymd":return[o,s,i].filter(Se).join(t);case"dmy":return[i,s,o].filter(Se).join(t)}}(e,t,l,c);return{value:Math.round(h/et),format:d,jsDate:u}}(s,t),null===o)return null;e=e.replace(s.dateString,"").trim()}if(""!==e||!o&&!r)return null;if(o&&o.jsDate&&r&&r.jsDate)return{value:o.value+r.value,format:o.format+" "+("hhhh:mm:ss"===r.format?"hh:mm:ss":r.format),jsDate:new Qe(o.jsDate.getFullYear()+r.jsDate.getFullYear()-1899,o.jsDate.getMonth()+r.jsDate.getMonth()-11,o.jsDate.getDate()+r.jsDate.getDate()-30,o.jsDate.getHours()+r.jsDate.getHours(),o.jsDate.getMinutes()+r.jsDate.getMinutes(),o.jsDate.getSeconds()+r.jsDate.getSeconds())};return o||r}(e,t)),ft.get(t).get(e)}function mt(e){const t=Math.trunc(e),r=Qe.fromTimestamp(t*et-ot);let n=e-t;n=n<0?1+n:n;const o=Math.round(24*n),s=Math.round(24*(n-o/24)*60),i=Math.round(24*(n-o/24-s/24/60)*60*60);return r.setHours(o),r.setMinutes(s),r.setSeconds(i),r}function pt(e){return Math.round(bt(e))}function bt(e){return(e.getTime()-Je.getTime())/et}function vt(e){return new Qe(e.getFullYear(),e.getMonth()+1,0).getDate()}function yt(e){return vt(e)===e.getDate()}function wt(e,t,r){const n=e.getFullYear(),o=e.getMonth(),s=e.getDate(),i=new Qe(n,o+t,1);return r&&s===vt(e)||s>vt(i)?i.setDate(vt(i)):i.setDate(s),i}function Et(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function St(e,t,r){if(e===t)return 0;if(e>t){const r=t;t=e,e=r}const n=mt(e),o=mt(t);let s=n.getDate(),i=o.getDate();const a=n.getMonth(),l=o.getMonth(),c=n.getFullYear(),u=o.getFullYear();let h=0,d=0;switch(r){case 0:31===s&&(s=30),30===s&&31===i&&(i=30),1===a&&s===(Et(c)?29:28)&&(s=30,1===l&&i===(Et(u)?29:28)&&(i=30)),h=c+(30*a+s)/360,d=u+(30*l+i)/360;break;case 1:let r=365;const n=c===u;if(!n&&!(c+1===u)||!n&&a<l||!n&&a===l&&s<i){let e=0,t=0;for(let r=c;r<=u;r++)e++,t+=Et(r)?366:365;r=t/e}else n?Et(c)&&(r=366):(Et(c)&&a<2&&(r=366),Et(u)&&(l>1||1===l&&29===i)&&(r=366));h=e/r,d=t/r;break;case 2:h=e/360,d=t/360;break;case 3:h=e/365,d=t/365;break;case 4:31===s&&(s=30),31===i&&(i=30),h=c+(30*a+s)/360,d=u+(30*l+i)/360}return d-h}function Ct(e,t){const r=12*(t.getFullYear()-e.getFullYear())+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?r-1:r}function Tt(e,t){const r=e.getTime(),n=t.getTime();return Math.floor((n-r)/et)}function It(e,t){const r=t.getFullYear()-e.getFullYear(),n=e.getMonth(),o=t.getMonth(),s=e.getDate(),i=t.getDate();return o>n||o===n&&i>=s?r:r-1}function xt(e,t,r){return t>r?xt(e,r,t):(e=Math.trunc(e),t=Math.trunc(t),r=Math.trunc(r),e>=t&&e<=r)}const Rt=Ue(function(e){return e=te(e),new RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),At=Ue(function(e){const t=te(e.decimalSeparator),r="(?:\\s*"+`(?:\\d+(?:${te(e.thousandsSeparator||"")}\\d{3,})*(?:${t}\\d*)?)`+"|"+`(?:${t}\\d+)`+")(?:e(?:\\+|-)?\\d+)?(?:\\s*%)?",n="(?:\\s*-)?",o="(?:\\s*[\\$€])?",s="^(?:(?:"+[n+o+r,n+r+o,o+n+r].join(")|(?:")+"))$";return new RegExp(s,"i")});function _t(e,t){return!!e&&At(t).test(e.trim())}const Ot=Ue(function(e){return new RegExp(`[$€${te(e.thousandsSeparator||"")}]`,"g")});function Dt(e,t){e=e.replace(Ot(t),""),"."!==t.decimalSeparator&&(e=e.replace(t.decimalSeparator,"."));let r=Number(e);return isNaN(r)&&e.includes("%")&&(r=Number(e.split("%")[0]),!isNaN(r))?r/100:r}function Ft(e,t,r){const n=[...e].sort((e,t)=>e-t);let o=(n.length+(r?-1:1))*t;if(r||o--,Number.isInteger(o))return n[o];const s=Math.ceil(o),i=Math.floor(o);return n[s]*(o-i)+n[i]*(s-o)}const Nt=["number","string","boolean","undefined"];function Mt(e){if(void 0!==e)return O(e)?e[0][0]?.format:e.format}function Vt(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.",$t(e))}}const Pt=e=>v("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function kt(e,t){const r=Yt(e);switch(typeof r){case"number":return r;case"boolean":return r?1:0;case"string":if(_t(r,t)||""===r)return Dt(r,t);const e=gt(r,t);if(e)return e.value;throw new S(Pt(r));default:return 0}}function Ut(e,t){return mr(e).map(e=>e.map(e=>{if("number"!=typeof e.value){let r="";throw"object"==typeof e?r=v("Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.",t):"string"==typeof e?r=v("Function [[FUNCTION_NAME]] expects number values for %s, but got a string.",t):"boolean"==typeof e&&(r=v("Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.",t)),new S(r)}return e.value}))}function Ht(e,t){const r=Yt(e);if(""===r)throw new S(Pt(r));return kt(r,t)}function Bt(e,t){return Math.trunc(kt(e,t))}function zt(e,t){return Math.trunc(Ht(e,t))}function $t(e){const t=Yt(e);switch(typeof t){case"string":return t;case"number":return t.toString();case"boolean":return t?"TRUE":"FALSE";default:return""}}const Gt=Ue(function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}),Wt=e=>v("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.",e);function qt(e){const t=Yt(e);switch(typeof t){case"boolean":return t;case"string":if(t){const e=t.toUpperCase();if("TRUE"===e)return!0;if("FALSE"===e)return!1;throw new S(Wt(t))}return!1;case"number":return!!t;default:return!1}}function Zt(e,t){return mt(kt(Yt(e),t))}function Yt(e){if("object"==typeof e&&null!==e&&"value"in e){if(Vt(e.value))throw e;return e.value}if(Vt(e))throw new S("",e);return e}function jt(e,t,r){for(const n of e)if(O(n)){const e=n.length,r=n[0].length;for(let o=0;o<r;o++)for(let r=0;r<e;r++)t(n[r][o])}else r(n)}function Xt(e,t){jt(e,e=>{if(Vt(e.value))throw e;t(e)},e=>{if(Vt(e?.value))throw e;t(e)})}function Kt(e,t,r){jt(e,e=>{if("number"==typeof e?.value&&t(e),Vt(e?.value))throw e},e=>{t({value:Ht(e,r),format:e?.format})})}function Qt(e,t,r,n,o="rowFirst"){let s=n;for(const n of e)if(O(n)){const e=n.length,r=n[0].length;if("rowFirst"===o)for(let o=0;o<r;o++)for(let r=0;r<e;r++)s=t(s,n[r][o]);else for(let o=0;o<e;o++)for(let e=0;e<r;e++)s=t(s,n[o][e])}else s=r(s,n);return s}function Jt(e,t,r,n="rowFirst"){return Qt(e,t,t,r,n)}function er(e,t,r,n){return Qt(e,(e,r)=>{const n=r?.value;if("number"==typeof n)return t(e,n);if(Vt(n))throw r;return e},(e,r)=>t(e,Ht(r,n)),r)}function tr(e,t,r,n){return Qt(e,(e,r)=>{const o=r?.value;if(null!=o){if("number"==typeof o)return t(e,o);if("boolean"==typeof o)return t(e,kt(o,n));if(Vt(o))throw r;return t(e,0)}return e},(e,r)=>t(e,kt(r,n)),r)}function rr(e,t,r){const n=Array(e);for(let o=0;o<e;o++){n[o]=Array(t);for(let e=0;e<t;e++)n[o][e]=r(o,e)}return n}function nr(e,t){return 0===e.length?[]:rr(e.length,e[0].length,(r,n)=>t(e[r][n]))}function or(e){return e.length?rr(e[0].length,e.length,(t,r)=>e[r][t]):[]}function sr(e,t,r=void 0){let n,o=1,s=1,i=1/0,a=1/0;for(let e=0;e<t.length;e++){const l=t[e];if(O(l)&&(void 0===r||r[e])){const r=l.length,c=l[0].length;1!==r||1!==c?(n??=new Array(t.length),1!==r&&1!==c?(n[e]="matrix",o=Math.max(o,r),s=Math.max(s,c),i=Math.min(i,r),a=Math.min(a,c)):1!==r?(n[e]="horizontal",o=Math.max(o,r),i=Math.min(i,r)):1!==c&&(n[e]="vertical",s=Math.max(s,c),a=Math.min(a,c))):t[e]=l[0][0]}}if(1===o&&1===s)return e(...t);return rr(o,s,(r,o)=>{if(r>i-1||o>a-1)return new x(v("Array arguments to [[FUNCTION_NAME]] are of different size."));const s=e(...(l=r,c=o,t.map((e,t)=>{switch(n?.[t]){case"matrix":return e[l][c];case"horizontal":return e[l][0];case"vertical":return e[0][c];case void 0:return e}})));var l,c;return O(s)?s[0][0]:s})}function ir(e,t){return function(e,t,r){for(const n of e)if(O(n)){const e=n.length,r=n[0].length;for(let o=0;o<r;o++)for(let r=0;r<e;r++)if(!t(n[r][o]??void 0))return}else if(!r(n))return}(e,e=>{const r=e?.value;if("boolean"==typeof r)return t(r);if("number"==typeof r)return t(!!r);if(Vt(r))throw e;return!0},e=>void 0===e||null===e.value||t(function(e){const t=Yt(e);if(""===t)throw new S(Wt(t));return qt(t)}(e)))}function ar(e,t){let r,n,o=e.substring(0,2);return"<="===o||">="===o||"<>"===o?(r=o,n=e.substring(2)):(o=e.substring(0,1),"<"===o||">"===o||"="===o?(r=o,n=e.substring(1)):(r="=",n=e)),_t(n,t)||dt(n,t)?n=kt(n,t):"TRUE"!==n&&"FALSE"!==n||(n=qt(n)),{operator:r,operand:n}}const lr=Ue(function(e){if("*"===e)return/.+/;let t="",r="";for(const n of e)"?"===n&&"~"!==r?t+=".":"*"===n&&"~"!==r?t+=".*":("*"!==n&&"?"!==n||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(n)&&(t+="\\"),t+=n),r=n;return new RegExp("^"+t+"$","i")});function cr(e="",t,r){const{operator:n,operand:o}=t;if(void 0===o||null===e||null===o)return!1;if("number"==typeof o&&"="===n)return"string"==typeof e&&(_t(e,r)||dt(e,r))?kt(e,r)===o:e===o;if("<>"===n||"="===n){let t;return t=typeof e==typeof o&&("string"==typeof e&&"string"==typeof o?lr(o).test(e):e===o),"="===n?t:!t}if(typeof e==typeof o)switch(n){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function ur(e,t,r,n=!1){const o=e.length;if(o%2==1)throw new S(v("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const s=mr(e[0]),i=s.length,a=s[0].length,l=[];for(let t=0;t<o-1;t+=2){const o=mr(e[t]);if(o.length!==i||o[0].length!==a)throw new S(v("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const s=ar($t(e[t+1]),r);n&&"string"==typeof s.operand&&(s.operand+="*"),l.push(s)}for(let n=0;n<i;n++)for(let s=0;s<a;s++){let i=!0;for(let t=0;t<o-1;t+=2){if(i=cr(mr(e[t])[n][s].value??void 0,l[t/2],r),!i)break}i&&t(n,s)}}function hr(e,t,r,n,o,s){if(void 0===t||null===t.value)return-1;if(Vt(t.value))throw t;const i=fr(t.value),a=typeof i;let l,c,u,h,d,f,g=0,m=o-1;const p="desc"===n?t=>fr(s(e,o-t-1)):t=>fr(s(e,t));for(;m-g>=0;){for(u=Math.floor((g+m)/2),h=u,d=p(h),f=typeof d;g<h&&a!==f;)h--,d=p(h),f=typeof d;f===a&&null!=d?("strict"===r&&d===i?(l=d,c=h):"nextSmaller"===r&&d<=i?(null==l||l<d||l===d&&c<h)&&(l=d,c=h):"nextGreater"===r&&d>=i&&(void 0===l||l>d||l===d&&c<h)&&(l=d,c=h),d>i||"strict"===r&&d===i?m=h-1:g=u+1):g=u+1}return void 0===c?-1:"desc"===n?o-c-1:c}function dr(e,t,r,n,o,s,i=!1){if(void 0===t||null===t.value)return-1;if(Vt(t.value))throw t;const a=fr(t.value),l=i?(e,t)=>fr(o(e,n-t-1)):(e,t)=>fr(o(e,t)),c="wildcard"!==r||"string"!=typeof a||!(a.includes("*")||a.includes("?"));if(s&&c){const t=i?"reverseSearch":"forwardSearch";let o=s[t].get(e);if(void 0===o){o=new Map;for(let t=0;t<n;t++){const r=l(e,t)??null;o.has(r)||o.set(r,t)}s[t].set(e,o)}if(o.has(a)){const e=o.get(a);return i?n-e-1:e}if("strict"===r)return-1}const u=function(e,t,r,n,o){let s=r=>o(e,r)===t;if("wildcard"===r&&"string"==typeof t&&(t.includes("*")||t.includes("?"))){const r=lr(t);s=t=>{const n=o(e,t);return"string"==typeof n&&r.test(n)}}let i,a=-1;"nextSmaller"===r&&(s=r=>{const n=o(e,r);return(!i&&gr(t,n)>=0||gr(t,n)>=0&&gr(n,i)>0)&&(i=n,a=r),n===t});"nextGreater"===r&&(s=r=>{const n=o(e,r);return(!i&&gr(t,n)<=0||gr(t,n)<=0&&gr(n,i)<0)&&(i=n,a=r),n===t});for(let e=0;e<n;e++)if(s(e))return e;return a}(e,a,r,n,l);return i&&-1!==u?n-u-1:u}function fr(e){return"string"==typeof e?Gt(e):e}function gr(e,t){let r=Nt.indexOf(typeof e)-Nt.indexOf(typeof t);return 0===r&&("string"==typeof e&&"string"==typeof t?r=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?r=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(r=Number(e)-Number(t))),r}function mr(e){return void 0===e?[[]]:O(e)?e:[[e]]}function pr(e,t){return Jt(e,(e,r)=>(e.push(t(r)),e),[],"rowFirst")}function br(e){if(void 0===e)return!1;const{value:t}=e;return null!==t&&""!==t}const vr=v("[[FUNCTION_NAME]] has no valid input data.");function yr(e){return v("[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.",{argName:e})}function wr(e){function t(...t){for(let r=0;r<t.length;r++){const n=t[r],o=c(e,t.length);if(!e.args[o(r)||r].acceptErrors&&!O(n)&&Vt(n?.value))return n}try{return r.apply(this,t)}catch(t){return Er(t,e.name)}}function r(...t){this.debug;const r=e.compute.apply(this,t);return O(r)?"object"==typeof r[0][0]&&null!==r[0][0]&&"value"in r[0][0]?(function(e,t){const r=e.length,n=e[0]?.length??0;for(let o=0;o<r;o++)for(let r=0;r<n;r++)t(e[o][r])}(r,t=>Sr(t,e.name)),r):nr(r,e=>({value:e})):"object"==typeof r&&null!==r&&"value"in r?(Sr(r,e.name),r):{value:r}}return function(...r){const n=[],o=c(e,r.length);for(let t=0;t<r.length;t++){const s=o(t)??-1,i=e.args[s];if(!O(r[t])&&i.acceptMatrixOnly)throw new C(v("Function %s expects the parameter '%s' to be reference to a cell or range.",e.name,(t+1).toString()));n.push(!i.acceptMatrix)}return sr(t.bind(this),r,n)}}function Er(e,t){return r=e,void 0!==r?.value&&"string"==typeof r.value&&Vt(e.value)?(Tr(e)&&Sr(e,t),e):(console.error(e),new S(Cr+(Tr(e)?" "+e.message:"")));var r}function Sr(e,t){e.message?.includes("[[FUNCTION_NAME]]")&&(e.message=e.message.replace("[[FUNCTION_NAME]]",t))}const Cr=v("An unexpected error occurred. Submit a support ticket at odoo.com/help.");function Tr(e){return void 0!==e?.message&&"string"==typeof e.message}function Ir(e,t){if(!e)throw new S(t)}function xr(e,t=v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")){if(0===e)throw new _(t)}function Rr(e){return 1===e.length||1===e[0].length}function Ar(...e){if(e.every(O)){const t=e[0].length,r=e[0][0].length;for(const n of e)if(n.length!==t||n[0].length!==r)return!1;return!0}return!e.some(e=>Array.isArray(e)&&(1!==e.length||1!==e[0].length))}function _r(e){return e.length===e[0].length}const Or=e=>v("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e);function Dr(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 Fr(e){if(e.length<1||e[0].length<1)throw new Error("invertMatrix: an empty matrix cannot be inverted.");if(e.length!==e[0].length)throw new Error("invertMatrix: only square matrices are invertible");let t=1;const r=e.length,n=Dr(r),o=e.map(e=>e.slice());for(let e=0;e<r;e++){let s=o[e][e];if(0===s){for(let s=e+1;s<r;s++)if(0!==o[e][s]){Nr(o,e,s),Nr(n,e,s),t*=-1;break}if(s=o[e][e],0===s)return{determinant:0}}for(let t=0;t<r;t++)o[t][e]=o[t][e]/s,n[t][e]=n[t][e]/s;t*=s;for(let t=0;t<r;t++){if(t===e)continue;const s=o[e][t];for(let i=0;i<r;i++)o[i][t]-=s*o[i][e],n[i][t]-=s*n[i][e]}}return{inverted:n,determinant:t}}function Nr(e,t,r){for(let n=0;n<e.length;n++){const o=e[n][t];e[n][t]=e[n][r],e[n][r]=o}}function Mr(e,t){if(e.length<1||t.length<1)throw new Error("multiplyMatrices: empty matrices cannot be multiplied.");if(e.length!==t[0].length)throw new Error("multiplyMatrices: incompatible matrices size.");const r=e[0].length,n=t.length,o=e.length,s=Array(n);for(let i=0;i<n;i++){s[i]=Array(r);for(let n=0;n<r;n++){let r=0;for(let s=0;s<o;s++)r+=e[s][n]*t[i][s];s[i][n]=r}}return s}function Vr(e){if(!O(e))return e;if(!Lr(e))throw new Error("The value should be a scalar or a 1x1 matrix");return e[0][0]}function Lr(e){return 1===e.length&&1===e[0].length}function Pr(e){return O(e)&&!Lr(e)}const kr={description:v("Returns a result array constrained to a specific width and height."),args:[a("input_range (any, range<any>)",v("The range to constrain.")),a("rows (number)",v("The number of rows in the constrained array.")),a("columns (number)",v("The number of columns in the constrained array."))],compute:function(e,t,r){const n=mr(e),o=Bt(t?.value,this.locale),s=Bt(r?.value,this.locale);if(o<=0)return new S(v("The rows argument (%s) must be strictly positive.",o.toString()));if(s<=0)return new S(v("The columns argument (%s) must be strictly positive.",s.toString()));const i=Math.min(o,n[0].length);return rr(Math.min(s,n.length),i,(e,t)=>n[e][t])},isExported:!1},Ur={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>)",v("The first column index of the columns to be returned.")),a("col_num2 (number, range<number>, repeating)",v("The columns indexes of the columns to be returned."))],compute:function(e,...t){const r=mr(e),n=pr(t,e=>Bt(e?.value,this.locale)),o=n.filter(e=>0===e||r.length<Math.abs(e));if(0!==o.length)return new S(v("The columns arguments must be between -%s and %s (got %s), excluding 0.",r.length.toString(),r.length.toString(),o.join(",")));const s=Array(n.length);for(let e=0;e<n.length;e++)n[e]>0?s[e]=r[n[e]-1]:s[e]=r[r.length+n[e]];return s},isExported:!0},Hr={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>)",v("The first row index of the rows to be returned.")),a("row_num2 (number, range<number>, repeating)",v("The rows indexes of the rows to be returned."))],compute:function(e,...t){const r=mr(e),n=pr(t,e=>Bt(e?.value,this.locale)),o=r.length,s=n.filter(e=>0===e||r[0].length<Math.abs(e));return 0!==s.length?new S(v("The rows arguments must be between -%s and %s (got %s), excluding 0.",r[0].length.toString(),r[0].length.toString(),s.join(","))):rr(o,n.length,(e,t)=>n[t]>0?r[e][n[t]-1]:r[e][r[e].length+n[t]])},isExported:!0},Br={description:v("Expands or pads an array to specified row and column dimensions."),args:[a("array (any, range<any>)",v("The array to expand.")),a("rows (number)",v("The number of rows in the expanded array. If missing, rows will not be expanded.")),a("columns (number, optional)",v("The number of columns in the expanded array. If missing, columns will not be expanded.")),a("pad_with (any, default=0)",v("The value with which to pad."))],compute:function(e,t,r,n={value:0}){const o=mr(e),s=Bt(t?.value,this.locale),i=void 0!==r?Bt(r.value,this.locale):o.length;return s<o[0].length?new S(v("The rows arguments (%s) must be greater or equal than the number of rows of the array.",s.toString())):i<o.length?new S(v("The columns arguments (%s) must be greater or equal than the number of columns of the array.",i.toString())):rr(i,s,(e,t)=>e>=o.length||t>=o[e].length?n:o[e][t])},isExported:!0},zr={description:v("Flattens all the values from one or more ranges into a single column."),args:[a("range (any, range<any>)",v("The first range to flatten.")),a("range2 (any, range<any>, repeating)",v("Additional ranges to flatten."))],compute:function(...e){return[pr(e,e=>void 0===e?{value:""}:e)]},isExported:!1},$r={description:v("Calculates the frequency distribution of a range."),args:[a("data (range<number>)",v("The array of ranges containing the values to be counted.")),a("classes (number, range<number>)",v("The range containing the set of classes."))],compute:function(e,t){const r=pr([e],e=>e.value).filter(e=>"number"==typeof e),n=pr([t],e=>e.value).filter(e=>"number"==typeof e),o=n.map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);o.push({initialIndex:o.length,value:1/0,count:0});const s=r.sort((e,t)=>e-t);let i=0;for(const e of s){for(;e>o[i].value&&i<o.length-1;)i++;o[i].count++}return[o.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},Gr={description:v("Appends ranges horizontally and in sequence to return a larger array."),args:[a("range1 (any, range<any>)",v("The first range to be appended.")),a("range2 (any, range<any>, repeating)",v("Additional ranges to add to range1."))],compute:function(...e){const t=Math.max(...e.map(e=>e?.[0]?.length??0)),r=[];for(const n of e){const e=mr(n);for(let n=0;n<e.length;n++){const o=Array(t).fill({value:null});for(let t=0;t<e[n].length;t++)o[t]=e[n][t];r.push(o)}}return r},isExported:!0},Wr={description:v("Returns the matrix determinant of a square matrix."),args:[a("square_matrix (number, range<number>)",v("An range with an equal number of rows and columns representing a matrix whose determinant will be calculated."))],compute:function(e){const t=Ut(e,"square_matrix");return _r(t)?Fr(t).determinant:new S(v("The argument square_matrix must have the same number of columns and rows."))},isExported:!0},qr={description:v("Returns the multiplicative inverse of a square matrix."),args:[a("square_matrix (number, range<number>)",v("An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated."))],compute:function(e){const t=Ut(e,"square_matrix");if(!_r(t))return new S(v("The argument square_matrix must have the same number of columns and rows."));const{inverted:r}=Fr(t);return r||new S(v("The matrix is not invertible."))},isExported:!0},Zr={description:v("Calculates the matrix product of two matrices."),args:[a("matrix1 (number, range<number>)",v("The first matrix in the matrix multiplication operation.")),a("matrix2 (number, range<number>)",v("The second matrix in the matrix multiplication operation."))],compute:function(e,t){const r=Ut(e,"matrix1"),n=Ut(t,"matrix2");return 0===r.length||0===n.length?new S(v("The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.")):r.length!==n[0].length?new S(v("In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).",r.length.toString(),n[0].length.toString())):Mr(r,n)},isExported:!0},Yr={description:v("Calculates the sum of the products of corresponding entries in equal-sized ranges."),args:[a("range1 (number, range<number>)",v("The first range whose entries will be multiplied with corresponding entries in the other ranges.")),a("range2 (number, range<number>, repeating)",v("The other range whose entries will be multiplied with corresponding entries in the other ranges."))],compute:function(...e){if(!Ar(...e))return new S(v("All the ranges must have the same dimensions."));const t=e.map(mr);let r=0;for(let e=0;e<t[0].length;e++)for(let n=0;n<t[0][e].length;n++){if(!t.every(t=>"number"==typeof t[e][n].value))continue;let o=1;for(const r of t)o*=kt(r[e][n],this.locale);r+=o}return r},isExported:!0};function jr(e,t,r){if(!Ar(e,t))return new S(v("The arguments array_x and array_y must have the same dimensions."));const n=mr(e),o=mr(t);let s=!1,i=0;for(const e in n)for(const t in n[e]){const a=n[e][t].value,l=o[e][t].value;"number"==typeof a&&"number"==typeof l&&(s=!0,i+=r(a,l))}return s?i:new S(v("The arguments array_x and array_y must contain at least one pair of numbers."))}const Xr={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 jr(e,t,(e,t)=>e**2-t**2)},isExported:!0},Kr={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 jr(e,t,(e,t)=>e**2+t**2)},isExported:!0},Qr={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 jr(e,t,(e,t)=>(e-t)**2)},isExported:!0},Jr=!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=>!Vt(e.value);if(3===t)return e=>null!==e.value&&!Vt(e.value);throw new S(v("Argument ignore must be between 0 and 3"))}const rn={description:v("Transforms a range of cells into a single column."),args:en,compute:function(e,t={value:0},r={value:Jr}){const n=mr(e),o=kt(t.value,this.locale),s=(qt(r.value)?n:or(n)).flat().filter(tn(o));return 0===s.length?new x(v("No results for the given arguments of TOCOL.")):[s]},isExported:!0},nn={description:v("Transforms a range of cells into a single row."),args:en,compute:function(e,t={value:0},r={value:Jr}){const n=mr(e),o=kt(t.value,this.locale),s=(qt(r.value)?n:or(n)).flat().filter(tn(o)).map(e=>[e]);return 0===s.length||0===s[0].length?new x(v("No results for the given arguments of TOROW.")):s},isExported:!0},on={description:v("Transposes the rows and columns of a range."),args:[a("range (any, range<any>)",v("The range to be transposed."))],compute:function(e){const t=mr(e);return rr(t[0].length,t.length,(e,r)=>t[r][e])},isExported:!0},sn={description:v("Appends ranges vertically and in sequence to return a larger array."),args:[a("range1 (any, range<any>)",v("The first range to be appended.")),a("range2 (any, range<any>, repeating)",v("Additional ranges to add to range1."))],compute:function(...e){const t=Math.max(...e.map(e=>mr(e).length)),r=e.reduce((e,t)=>e+mr(t)[0].length,0),n=Array(t).fill([]).map(()=>Array(r).fill({value:0}));let o=0;for(const t of e){const e=mr(t);for(let t=0;t<e.length;t++)for(let r=0;r<e[t].length;r++)n[t][o+r]=e[t][r];o+=e[0].length}return n},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 n=mr(e),o=Bt(t?.value,this.locale);if(!Rr(n))return new S(v("Argument range must be a single row or column."));const s=n.flat();return rr(Math.ceil(s.length/o),o,(e,t)=>{const n=e*o+t;return n<s.length?s[n]:r})},isExported:!0},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 n=mr(e),o=Bt(t?.value,this.locale);if(!Rr(n))return new S(v("Argument range must be a single row or column."));const s=n.flat(),i=Math.ceil(s.length/o);return rr(o,i,(e,t)=>{const n=t*o+e;return n<s.length?s[n]:r})},isExported:!0};var cn=Object.freeze({__proto__:null,ARRAY_CONSTRAIN:kr,CHOOSECOLS:Ur,CHOOSEROWS:Hr,EXPAND:Br,FLATTEN:zr,FREQUENCY:$r,HSTACK:Gr,MDETERM:Wr,MINVERSE:qr,MMULT:Zr,SUMPRODUCT:Yr,SUMX2MY2:Xr,SUMX2PY2:Kr,SUMXMY2:Qr,TOCOL:rn,TOROW:nn,TRANSPOSE:on,VSTACK:sn,WRAPCOLS:an,WRAPROWS:ln});function un(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 hn=new Set("$+-/():!^&~{}<>= ");function dn(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 hn.has(e.current)?{type:"CHAR",value:e.shift()}:null}function fn(e){return","===e.current?(e.shift(),{type:"THOUSANDS_SEPARATOR",value:","}):null}function gn(e){return"@"===e.current?(e.shift(),{type:"TEXT_PLACEHOLDER",value:"@"}):null}function mn(e){return"."===e.current?(e.shift(),{type:"DECIMAL_POINT",value:"."}):null}function pn(e){return"%"===e.current?(e.shift(),{type:"PERCENT",value:"%"}):null}function bn(e){if("0"===e.current||"#"===e.current){const t=e.current;return e.shift(),{type:"DIGIT",value:t}}return null}const vn=new Set("dmqyhsa");function yn(e){if(!vn.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 wn(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 En={};function Sn(e){let t=En[e];return void 0===t&&(t=function(e){const t=function(e){const t=new Ze(e),r=[];let n=[];for(r.push(n);!t.isOver();){if(";"===t.current){n=[],r.push(n),t.shift();continue}const e=bn(t)||un(t)||dn(t)||fn(t)||mn(t)||pn(t)||yn(t)||gn(t)||wn(t);if(!e)throw new Error("Unknown token at "+t.remaining());n.push(e)}return r}(e);for(const e of t){const t=e.filter(e=>"REPEATED_CHAR"===e.type);for(const e of t.slice(1))e.type="CHAR"}const r=Tn(t[0])||Cn(t[0])||In(t[0]);if(!r)throw new Error("Invalid first format part of: "+e);if(t.length>1&&"text"===r.type)throw new Error("The first format in a multi-part format must be a number format: "+e);const n=Tn(t[1])||Cn(t[1]);if(t[1]?.length&&!n)throw new Error("Invalid second format part of: "+e);const o=Tn(t[2])||Cn(t[2]);if(t[2]?.length&&!o)throw new Error("Invalid third format part of: "+e);const s=In(t[3]);if(t[3]?.length&&!s)throw new Error("Invalid fourth format part of: "+e);return{positive:r,negative:n,zero:o,text:s}}(e),En[e]=t),t}function Cn(e){if(!e||!function(e){return e.every(e=>"DIGIT"===e.type||"DECIMAL_POINT"===e.type||"THOUSANDS_SEPARATOR"===e.type||"PERCENT"===e.type||"STRING"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type)}(e))return;const t=[];let r,n=t,o=0,s=0,i=e.findLastIndex(e=>"DIGIT"===e.type),a=!1,l=0;for(let c=0;c<e.length;c++){const u=e[c];switch(u.type){case"DIGIT":n===t?n.push(u):l<20&&(n.push(u),l++);break;case"DECIMAL_POINT":if(n!==t)throw new Error("Multiple decimal points in a number format");r=[],n=r;break;case"REPEATED_CHAR":case"CHAR":case"STRING":n.push(u);break;case"PERCENT":o++,n.push(u);break;case"THOUSANDS_SEPARATOR":c-1===i?(s+=1,i++,n.push(u)):"DIGIT"===e[c+1]?.type&&"DIGIT"===e[c-1]?.type?(n===t&&(a=!0),n.push(u)):n.push({type:"CHAR",value:","})}}return{type:"number",integerPart:t,decimalPart:r,percentSymbols:o,thousandsSeparator:a,magnitude:s}}function Tn(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)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 In(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 xn(e){return[Rn(e.positive),Rn(e.negative),Rn(e.zero),Rn(e.text)].filter(Se).join(";")}function Rn(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));return t}(e);for(const e of r)switch(e.type){case"STRING":t+=`[$${e.value}]`;break;case"CHAR":t+=An(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 An(e){return!hn.has(e)}const _n="REPEATED_CHAR_PLACEHOLDER_",On={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")},Dn={0:v("Sunday"),1:v("Monday"),2:v("Tuesday"),3:v("Wednesday"),4:v("Thursday"),5:v("Friday"),6:v("Saturday")};function Fn(e,{format:t,locale:r,formatWidth:n}){switch("boolean"==typeof e&&(e=e?"TRUE":"FALSE"),typeof e){case"string":{if(e.includes('\\"')&&(e=e.replaceAll(/\\"/g,'"')),!t)return e;const r=Nn(e,Sn(t)).format;return r&&"text"===r.type?Mn(e,r,n):e}case"number":t||(t=$n(e));const o=Sn(t),{format:s,isNegativeFormat:i}=Nn(e,o);if(!s)return e.toString();if("text"===s.type)return Mn(e.toString(),s,n);if(i&&(e=Math.abs(e)),"date"===s.type)return Vn(function(e,t){const r=mt(e),n=t.tokens.some(e=>"DATE_PART"===e.type&&"a"===e.value);let o="";for(const e of t.tokens)switch(e.type){case"DATE_PART":o+=Bn(r,e.value,n);break;case"REPEATED_CHAR":o+=_n+e.value;break;default:o+=e.value}return o}(e,s),n);const a=e<0,l=Vn(function(e,t,r){if(e===1/0)return"∞"+(t.percentSymbols?"%":"");const n=2*t.percentSymbols-3*t.magnitude;e*=10**n;let o=0;void 0!==t.decimalPart&&(o=t.decimalPart.filter(e=>"DIGIT"===e.type).length);const{integerDigits:s,decimalDigits:i}=Pn(Math.abs(e),o);let a=function(e,t,r){let n=t.integerPart;n.some(e=>"DIGIT"===e.type)||(n=[...n,{type:"DIGIT",value:"#"}]);"0"===e&&(e="");let o="";const s=n.findIndex(e=>"DIGIT"===e.type);let i=e.length-1;function a(t,n){if("0"===n&&(t=t||"0"),!t)return;const s=e.length-1-i;o=r&&s>0&&s%3==0?t+r+o:t+o}for(let t=n.length-1;t>=0;t--){const r=n[t];switch(r.type){case"DIGIT":if(a(e[i],r.value),i--,s===t)for(;i>=0;)a(e[i],"0"),i--;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":o=_n+r.value+o;break;default:o=r.value+o}}return o}(s,t,t.thousandsSeparator?r.thousandsSeparator:void 0);void 0!==t.decimalPart&&(a+=r.decimalSeparator+function(e,t){if(!t.decimalPart)return"";let r="",n=0;for(const o of t.decimalPart)switch(o.type){case"DIGIT":r+="#"===o.value?e[n]||"":e[n]||"0",n++;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":r+=_n+o.value;break;default:r+=o.value}return r}(i||"",t));return a}(Math.abs(e),s,r),n);return a?"-"+l:l;case"object":return""}}function Nn(e,t){let r,n=!1;switch(typeof e){case"number":e<0&&t.negative?(r=t.negative,n=!0):r=0===e&&t.zero?t.zero:t.positive;break;case"string":const o=t.text||t.positive;"text"===o.type&&(r=o)}return{format:r,isNegativeFormat:n}}function Mn(e,t,r){let n="";for(const r of t.tokens)switch(r.type){case"TEXT_PLACEHOLDER":n+=e;break;case"CHAR":case"STRING":n+=r.value;break;case"REPEATED_CHAR":n+=_n+r.value}return Vn(n,r)}function Vn(e,t){const r=e.indexOf(_n);if(-1===r)return e;const n=e.slice(0,r),o=e.slice(r+26+1),s=e[r+26];const{timesToRepeat:i,padding:a}=function(){if(!t)return{timesToRepeat:0,padding:""};const e=t.measureText(n+o),r=t.measureText(s),i=t.availableWidth-e;if(i<=0)return{timesToRepeat:0,padding:""};const a=Math.floor(i/r),l=i-a*r,c=t.measureText(" ");return{timesToRepeat:a,padding:" ".repeat(Math.floor(l/c))}}();return n+s.repeat(i)+a+o}const Ln=[];function Pn(e,t=20){const r=e.toString();if(r.includes("e"))return function(e,t=20){let r=Ln[t];r||(r=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),Ln[t]=r);const[n,o]=r.format(e).split(".");return{integerDigits:n,decimalDigits:o}}(e,t);if(Number.isInteger(e))return{integerDigits:r,decimalDigits:void 0};const n=r.indexOf(".");let o=r.substring(0,n),s=r.substring(n+1);if(0===t)return Number(s[0])>=5&&(o=(Number(o)+1).toString()),{integerDigits:o,decimalDigits:void 0};if(s.length>t){const{integerDigits:e,decimalDigits:r}=function(e,t){let r="0",n=e;const o=e.slice(0,t),s=t;if(Number(e[s])<5)return{integerDigits:r,decimalDigits:o};const i=o.match(Un)?.[0]||"",a=(Number(o)+1).toString(),l=o.slice(i.length),c=a.length>l.length;c&&!i?(r="1",n=void 0):n=c?i.slice(0,-1)+a:i+a;return{integerDigits:r,decimalDigits:n}}(s,t);s=r,"0"!==e&&(o=(Number(o)+Number(e)).toString())}return{integerDigits:o,decimalDigits:kn(s||"")}}function kn(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const Un=/^0+/;const Hn=Ue(function(e){if(!e)return!1;try{return"date"===Sn(e).positive.type}catch(e){return!1}});function Bn(e,t,r){switch(t){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return Dn[e.getDay()].slice(0,3);case"dddd":return Dn[e.getDay()].toString();case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return On[e.getMonth()].slice(0,3);case"mmmm":return On[e.getMonth()].toString();case"mmmmm":return On[e.getMonth()].slice(0,1);case"qq":return v("Q%(quarter)s",{quarter:e.getQuarter()}).toString();case"qqqq":return v("Quarter %(quarter)s",{quarter:e.getQuarter()}).toString();case"yy":const n=String(e.getFullYear()).replace("-","").padStart(2,"0");return n.slice(n.length-2);case"yyyy":return e.getFullYear();case"hhhh":return Math.floor((e.getTime()-Je.getTime())/36e5).toString();case"hh":let o=e.getHours();return r&&(o=0===o?12:o>12?o-12:o),o.toString().padStart(2,"0");case"MM":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");case"a":return e.getHours()>=12?"PM":"AM";default:throw new Error(`invalid date format token: ${t}`)}}const zn=Ue(function(e){return new RegExp(`[0-9]+${te(e.decimalSeparator)}[0-9]`)});function $n(e){let{integerDigits:t,decimalDigits:r}=Pn(e);if(!r)return"0";const n=t.replace("-","").length;if(n+2>11)return"0";const o=11-n-1;return({decimalDigits:r}=Pn(e,Math.min(o,r.length))),r?"0."+"0".repeat(r.length):"0"}function Gn(e,t){if(!dt(e,t))return;return gt(e,t).format}function Wn(e){const t=e.includes(".")?"0.00":"0",r=e.match(/[\$€]/);if(r){const n=e.match(/[\d]/),o="[$"+r.values().next().value+"]";return n.index<r.index?"#,##"+t+o:o+"#,##"+t}if(e.includes("%"))return t+"%"}function qn(e,t,r){let n=0;try{n=Math.abs(kt(e?.value,r))}catch(e){return""}const o=e?.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return Zn(o,1,"k");case"m":return Zn(o,2,"m");case"b":return Zn(o,3,"b");default:throw new S(v("The formatting unit should be 'k', 'm' or 'b'."))}}return n<1e5?Zn(o,0,""):n<1e8?Zn(o,1,"k"):n<1e11?Zn(o,2,"m"):Zn(o,3,"b")}function Zn(e,t,r,n){const o=Sn(e||"#,##0");return xn({positive:Yn(o.positive,t,r),negative:o.negative?Yn(o.negative,t,r):void 0,zero:o.zero?Yn(o.zero,t,r):void 0,text:o.text})}function Yn(e,t,r){if("number"!==e.type)return e;const n={type:"STRING",value:r};let o=[...e.integerPart];const s=o.findLastIndex(e=>"DIGIT"===e.type);if(-1===s)throw new Error("Cannot create a large number format from a format with no digit.");for(;"THOUSANDS_SEPARATOR"===o[s+1]?.type;)o=He(o,[s+1]);const i=o[s+1];o="STRING"===i?.type&&["m","k","b"].includes(i.value)?ze(o,n,s+1):Be(o,[n],s+1),t>0&&(o=Be(o,Array(t).fill({type:"THOUSANDS_SEPARATOR",value:","}),s+1));const a=e.percentSymbols-o.filter(e=>"PERCENT"===e.type).length;return o.push(...new Array(a).fill({type:"PERCENT",value:"%"})),{...e,integerPart:o,decimalPart:void 0,magnitude:t}}function jn(e,t){const r=Sn(e);return xn(Sn(xn({positive:Xn(r.positive,t),negative:r.negative?Xn(r.negative,t):void 0,zero:r.zero?Xn(r.zero,t):void 0,text:r.text})))}function Xn(e,t){return"number"!==e.type?e:t>0?function(e,t){let r=e.integerPart,n=e.decimalPart;if(!n){const e=r.findLastIndex(e=>"DIGIT"===e.type);n=r.slice(e+1),r=r.slice(0,e+1)}const o=le(0,t).map(()=>({type:"DIGIT",value:"0"})),s=n.findLastIndex(e=>"DIGIT"===e.type);n=-1===s?[...o,...n]:Be(n,o,s+1);return{...e,decimalPart:n,integerPart:r}}(e,t):function(e,t){let r=e.decimalPart;if(!r)return e;const n=[];let o=0;for(let e=r.length-1;e>=0&&!(o>=Math.abs(t));e--)"DIGIT"===r[e].type&&(o++,n.push(e));if(r=He(r,n),r.some(e=>"DIGIT"===e.type))return{...e,decimalPart:r};return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...r]}}(e,Math.abs(t))}function Kn(e){const t=Sn(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 Qn(e){if(!e)return!1;try{return"text"===Sn(e).positive.type}catch{return!1}}const Jn={description:v("Apply a large number format"),args:[a("value (number)",v("The number.")),a("unit (string, optional)",v("The formatting unit. Use 'k', 'm', or 'b' to force the unit"),[{value:"k",label:v("Thousand")},{value:"m",label:v("Million")},{value:"b",label:v("Billion")}])],compute:function(e,t){return{value:kt(e,this.locale),format:qn(e,t,this.locale)}}};var eo=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Jn});const to=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),ro=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),no=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),oo=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),so=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),io=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),ao=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[to.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 lo(e){return so.test(e)}function co(e){return io.test(e)}function uo(e){return no.test(e)}function ho(e){return oo.test(e)}function fo(e){return ro.test(e)}function go(e){if(!e.includes("!"))return{xc:e};const t=e.split("!"),r=t.pop();return{sheetName:ne(t.join("!"))||void 0,xc:r}}function mo(e,t){return void 0!==e?`${se(e)}!${t}`:t}function po(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=bo(e,"colrow");break;case"colrow":e=bo(e,"row");break;case"row":e=bo(e,"col");break;case"col":e=bo(e,"none")}return e}function bo(e,t){let r;({sheetName:r,xc:e}=go(e)),r=r?r+"!":"";const n=(e=e.replace(/\$/g,"")).indexOf(":");return n>=0?`${r}${vo(e.slice(0,n),t)}:${vo(e.slice(n+1),t)}`:r+vo(e,t)}function vo(e,t){const r=e.search(/[0-9]/),n=0!==r,o=r>=0;switch(t){case"col":return n?"$"+e:e;case"row":return o?e.slice(0,r)+"$"+e.slice(r):e;case"colrow":return o&&n?"$"+e.slice(0,r)+"$"+e.slice(r):"$"+e;case"none":return e}}function yo(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class wo{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 Eo(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Eo(Math.floor(e/26)-1)+Eo(e%26)}function So(e){const t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function Co(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function To(e){return e>="0"&&e<="9"}const Io=function(e){let t=0;const r=e.length;for(let n=0;n<r;n++){t=26*t+So(e[n])}return t-1}("ZZZ"),xo=9999998;function Ro(e){for(;" "===e.current;)e.advanceBy(1)}function Ao(e){if("$"===e.current&&e.advanceBy(1),!e.current||!Co(e.current))return-1;let t=0;for(;e.current&&Co(e.current);)t=26*t+So(e.shift());return t}function _o(e){if("$"===e.current&&e.advanceBy(1),!e.current||!To(e.current))return-1;let t=0;for(;e.current&&To(e.current);)t=10*t+Number(e.shift());return t}function Oo(e){const t=new Ze(e);Ro(t);const r=Ao(t);if(-1===r||!t.current)throw new Error(`Invalid cell description: ${e}`);const n=_o(t);Ro(t);const o=r-1,s=n-1;if(!t.isOver()||o>Io||s>xo)throw new Error(`Invalid cell description: ${e}`);return{col:o,row:s}}function Do(e,t,r={colFixed:!1,rowFixed:!1}){return(r.colFixed?"$":"")+Eo(e)+(r.rowFixed?"$":"")+String(t+1)}function Fo(e,t=[]){if(e.length<=1&&0===t.length)return e;const r=[0],n=new Map([[0,[]]]);return No(r,n,e,!1),No(r,n,t,!0),Po(r,n)}function No(e,t,r,n=!1){for(const o of r){const r=o.left,s=void 0===o.right?void 0:o.right+1,i=Mo(e,t,r,!0,0),a=Mo(e,t,s,!1,i);for(let r=i;r<=a;r++){Vo(t.get(e[r]),o,n)}Lo(e,t,i,a)}}function Mo(e,t,r,n,o){if(void 0===r)return e.length-1;const s=ko(e,r,o);return r!==e[s]?(e.splice(s+1,0,r),t.set(r,[...t.get(e[s])]),n?s+1:s):n?s:s-1}function Vo(e,t,r=!1){const n=t.top,o=void 0===t.bottom?void 0:t.bottom+1,s=[],i=ko(e,n,0,!1);if((i%2!=0&&!r||i%2==0&&r)&&s.push(n),void 0===o)return e.splice(i+1),void e.push(...s);const a=Uo(e,o,0,!1);(a%2==0&&!r||a%2!=0&&r)&&s.push(o);const l=a-i-1,c=s.length,u=i+1;u===e.length-1&&1===l&&1===c?e[u]=s[0]??s[1]:e.splice(u,l,...s)}function Lo(e,t,r,n){const o=r-1==-1?0:r-1;for(let r=n===e.length-1?n:n+1;r>o;r--)Oe(t.get(e[r]),t.get(e[r-1]))&&(t.delete(e[r]),e.splice(r,1))}function Po(e,t){const r=[];let n=[];for(let o=0;o<e.length;o++){const s=e[o],i=t.get(s);if(!i||0===i.length){r.push(...n),n=[];continue}let a=e[o+1];void 0!==a&&a--;const l=[];for(let e=0;e<i.length;e+=2){const t=i[e];let r=i[e+1];void 0!==r&&r--;const o={top:t,left:s,bottom:r,right:a};(void 0===r&&0!==t||void 0===a&&0!==s)&&(o.hasHeader=!0);let c=!1;for(let e=n.length-1;e>=0;e--){const t=n[e];if(t.top===o.top&&t.bottom===o.bottom){t.right=o.right,n.splice(e,1),l.push(t),c=!0;break}}c||l.push(o)}r.push(...n),n=l}return r.push(...n),r}function ko(e,t,r=0,n=!0){let o=e.length-1,s=-1;for(;r<=o;){const i=Math.floor((r+o)/2);if(e[i]===t&&n)return i;e[i]<t?(s=i,r=i+1):o=i-1}return s}function Uo(e,t,r=0,n=!0){let o=e.length-1,s=e.length;for(;r<=o;){const i=Math.floor((r+o)/2);if(e[i]===t&&n)return i;e[i]>t?(s=i,o=i-1):r=i+1}return s}function Ho(e){const t=function(e){const t=new Ze(e);Ro(t);const r=e.indexOf("!");-1!==r&&t.advanceBy(r+1);const n=Ao(t),o=_o(t);let s,i,a,l,c=!1,u=!1,h=!1;if(-1===o?(a=l=n-1,s=i=0,c=!0):-1===n?(s=i=o-1,a=l=0,u=!0):(a=l=n-1,s=i=o-1,h=!0),Ro(t),":"===t.current){t.advanceBy(1),Ro(t);const e=Ao(t),r=_o(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=ns(t),n=r.bottom,o=r.right;if(void 0!==n&&n>xo||void 0!==o&&o>Io)throw new Error(`Range string out of bounds: ${e}`);if(void 0===n&&void 0===o)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");return r}function Bo(e){const t=Ho(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function zo(e){const{bottom:t,top:r,left:n,right:o}=e;return!(void 0!==t&&isNaN(t)||isNaN(r)||isNaN(n)||void 0!==o&&isNaN(o))&&($o(e)&&e.top>=0&&e.left>=0)}function $o(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 Go(e){const{top:t,bottom:r,left:n,right:o}=e,s="hasHeader"in e&&e.hasHeader,i=t===r&&n===o;if(void 0===r&&void 0!==o)return 0!==t||s?`${Do(n,t)}:${Eo(o)}`:`${Eo(n)}:${Eo(o)}`;if(void 0===o&&void 0!==r)return 0!==n||s?`${Do(n,t)}:${r+1}`:`${t+1}:${r+1}`;if(void 0!==r&&void 0!==o)return i?Do(n,t):`${Do(n,t)}:${Do(o,r)}`;throw new Error("Bad zone format")}function Wo(e,t,r,n,o){const s="left"===t?"columns":"rows",i="before"===n?r-1:r,a="left"===t?"right":"bottom";return e[t]<=i&&e[a]>i?os(e,s,"RESIZE",o):i<e[t]?os(e,s,"MOVE",o):{...e}}function qo(e,t,r){const n="left"===t?"right":"bottom";let o=e[t],s=e[n];for(const i of r.sort((e,t)=>t-e))e[t]>i&&(o--,s--),e[t]<i&&e[n]>=i&&s--;return{...e,[t]:o,[n]:s}}function Zo(...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 Yo(e,t){if(Ko(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 jo(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom&&e.hasHeader===t.hasHeader}function Xo(e,t){if(Yo(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 Ko(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 Qo(e,t,r){const{left:n,right:o,top:s,bottom:i}=r;return e>=n&&e<=o&&t>=s&&t<=i}function Jo(e,t){return jo(Zo(t,e),t)}function es(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function ts(e){const{numberOfCols:t,numberOfRows:r}=es(e);return 1===t||1===r}function rs(e){const t=[],{left:r,right:n,top:o,bottom:s}=ns(e);for(const e of le(r,n+1))for(const r of le(o,s+1))t.push({col:e,row:r});return t}function ns(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 os(e,t,r,n){const o="both"===t?n[0]:"columns"===t?n:0,s="both"===t?n[1]:"rows"===t?n:0,i="hasHeader"in e&&e.hasHeader;let a;a=ls(e)&&!i?"rows"!==t:!(as(e)&&!i)||"columns"!==t;const l={...e};return a&&"MOVE"===r&&(l.left+=o,l.top+=s),void 0!==l.right&&(l.right+=o),void 0!==l.bottom&&(l.bottom+=s),l}function ss(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function is(e){return{...e,right:e.left,bottom:e.top}}function as(e){return void 0===e.right}function ls(e){return void 0===e.bottom}function cs(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function us(e){return e.length<2||1===Fo(e).length}function hs(e,t){const r=Xo(e,t);if(!r)return[e];const n=[];switch(r.position){case"bottom":case"top":return n.push({top:e.top,bottom:e.bottom,left:r.start,right:r.stop}),r.start>e.left&&n.push({top:e.top,bottom:e.bottom,left:e.left,right:r.start-1}),(void 0===e.right||r.stop<e.right)&&n.push({top:e.top,bottom:e.bottom,left:r.stop+1,right:e.right}),n;case"left":case"right":return n.push({top:r.start,bottom:r.stop,left:e.left,right:e.right}),r.start>e.top&&n.push({top:e.top,bottom:r.start-1,left:e.left,right:e.right}),(void 0===e.bottom||r.stop<e.bottom)&&n.push({top:r.stop+1,bottom:e.bottom,left:e.left,right:e.right}),n}}const ds=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","DUPLICATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","UNDO","REDO","ADD_MERGE","REMOVE_MERGE","DUPLICATE_SHEET","UPDATE_LOCALE","ADD_PIVOT","UPDATE_PIVOT","INSERT_PIVOT","RENAME_PIVOT","REMOVE_PIVOT","DUPLICATE_PIVOT"]),fs=new Set(["EVALUATE_CELLS","EVALUATE_CHARTS","UPDATE_CELL","UNHIDE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","GROUP_HEADERS","UNGROUP_HEADERS","FOLD_ALL_HEADER_GROUPS","FOLD_HEADER_GROUP","FOLD_HEADER_GROUPS_IN_ZONE","UNFOLD_ALL_HEADER_GROUPS","UNFOLD_HEADER_GROUP","UNFOLD_HEADER_GROUPS_IN_ZONE","UPDATE_TABLE","UPDATE_FILTER","UNDO","REDO"]),gs=new Set(["MOVE_RANGES"]),ms=new Set(["EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CHANGE_CONDITIONAL_FORMAT_PRIORITY"]),ps=new Set(["AUTOFILL_CELL","SET_BORDER","SET_ZONE_BORDERS","SET_BORDERS_ON_TARGET"]),bs=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"]),vs=new Set(["START","ACTIVATE_SHEET","COPY","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","EVALUATE_CELLS","EVALUATE_CHARTS","SET_FORMULA_VISIBILITY","UPDATE_FILTER","UPDATE_CHART","UPDATE_CAROUSEL_ACTIVE_ITEM","UPDATE_PIVOT"]),ys=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 ws(e){return ys.has(e.type)}class Es{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>"Success"!==e)}static get Success(){return Ss}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}const Ss=new Es;var Cs;!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.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"}(Cs||(Cs={}));class Ts{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return"Success"}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(const r of e){let e=r.call(this,t);Array.isArray(e)||(e=[e]);const n=e.filter(e=>"Success"!==e);if(n.length)return n}return"Success"}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class Is extends Ts{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:r,canDispatch:n,uiActions:o,selection:s}){super(t),this.getters=e,this.ui=o,this.selection=s,this.dispatch=r,this.canDispatch=n}drawLayer(e,t){}}function xs(e){return e.isFormula&&e.compiledFormula.tokens.some(e=>"SYMBOL"===e.type&&"SUBTOTAL"===e.value.toUpperCase())}function Rs(e,t){return er(e,(e,t)=>e+t,0,t)}function As(e){return Jt(e,(e,t)=>br(t)?e.add(t?.value):e,new Set).size}const _s=/^-?[a-z0-9]+$/i,Os={description:v("Absolute value of a number."),args:[a("value (number)",v("The number of which to return the absolute value."))],compute:function(e){return Math.abs(kt(e,this.locale))},isExported:!0},Ds={description:v("Inverse cosine of a value, in radians."),args:[a("value (number)",v("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)>1?new S(v("The value (%s) must be between -1 and 1 inclusive.",t)):Math.acos(t)},isExported:!0},Fs={description:v("Inverse hyperbolic cosine of a number."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],compute:function(e){const t=kt(e,this.locale);return t<1?new S(v("The value (%s) must be greater than or equal to 1.",t)):Math.acosh(t)},isExported:!0},Ns={description:v("Inverse cotangent of a value."),args:[a("value (number)",v("The value for which to calculate the inverse cotangent."))],compute:function(e){const t=kt(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Ms={description:v("Inverse hyperbolic cotangent of a value."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)<=1?new S(v("The value (%s) cannot be between -1 and 1 inclusive.",t)):Math.log((t+1)/(t-1))/2},isExported:!0},Vs={description:v("Inverse sine of a value, in radians."),args:[a("value (number)",v("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)>1?new S(v("The value (%s) must be between -1 and 1 inclusive.",t)):Math.asin(t)},isExported:!0},Ls={description:v("Inverse hyperbolic sine of a number."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic sine."))],compute:function(e){return Math.asinh(kt(e,this.locale))},isExported:!0},Ps={description:v("Inverse tangent of a value, in radians."),args:[a("value (number)",v("The value for which to calculate the inverse tangent."))],compute:function(e){return Math.atan(kt(e,this.locale))},isExported:!0},ks={description:v("Angle from the X axis to a point (x,y), in radians."),args:[a("x (number)",v("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),a("y (number)",v("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],compute:function(e,t){const r=kt(e,this.locale),n=kt(t,this.locale);return 0===r&&0===n?new _(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):Math.atan2(n,r)},isExported:!0},Us={description:v("Inverse hyperbolic tangent of a number."),args:[a("value (number)",v("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],compute:function(e){const t=kt(e,this.locale);return Math.abs(t)>=1?new S(v("The value (%s) must be between -1 and 1 exclusive.",t)):Math.atanh(t)},isExported:!0},Hs={description:v("Rounds number up to nearest multiple of factor."),args:[a("value (number)",v("The value to round up to the nearest integer multiple of factor.")),a("factor (number, default=1)",v("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const r=kt(e,this.locale),n=kt(t,this.locale);return n<0&&r>0?new S(v("The factor (%s) must be positive when the value (%s) is positive.",n,r)):{value:n?Math.ceil(r/n)*n:0,format:e?.format}},isExported:!0};function Bs(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 zs={description:v("Rounds number up to nearest multiple of factor."),args:[a("number (number)",v("The value to round up to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),a("mode (number, default=0)",v("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero."))],compute:function(e,t={value:1},r={value:0}){const n=kt(t,this.locale);return{value:Bs(kt(e,this.locale),n,kt(r,this.locale)),format:e?.format}},isExported:!0},$s={description:v("Rounds number up to nearest multiple of factor."),args:[a("number (number)",v("The value to round up to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const r=kt(t,this.locale);return{value:Bs(kt(e,this.locale),r),format:e?.format}},isExported:!0},Gs={description:v("Cosine of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the cosine of, in radians."))],compute:function(e){return Math.cos(kt(e,this.locale))},isExported:!0},Ws={description:v("Hyperbolic cosine of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic cosine of."))],compute:function(e){return Math.cosh(kt(e,this.locale))},isExported:!0},qs={description:v("Cotangent of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the cotangent of, in radians."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new _(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tan(t)},isExported:!0},Zs={description:v("Hyperbolic cotangent of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic cotangent of."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new _(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tanh(t)},isExported:!0},Ys={description:v("Number of empty values."),args:[a("value1 (any, range)",v("The first value or range in which to count the number of blanks.")),a("value2 (any, range, repeating)",v("Additional values or ranges in which to count the number of blanks."))],compute:function(...e){return Jt(e,(e,t)=>void 0===t||null===t.value||""===t.value?e+1:e,0)},isExported:!0},js={description:v("A conditional count across a range."),args:[a("range (range)",v("The range that is tested against criterion.")),a("criterion (string)",v("The pattern or test to apply to range."))],compute:function(...e){let t=0;return ur(e,(e,r)=>{t+=1},this.locale),t},isExported:!0},Xs={description:v("Count values depending on multiple criteria."),args:[a("criteria_range1 (range)",v("The range to check against criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1.")),a("criteria_range2 (any, range, repeating)",v("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),a("criterion2 (string, repeating)",v("Additional criteria to check."))],compute:function(...e){let t=0;return ur(e,(e,r)=>{t+=1},this.locale),t},isExported:!0},Ks={description:v("Counts number of unique values in a range."),args:[a("value1 (any, range)",v("The first value or range to consider for uniqueness.")),a("value2 (any, range, repeating)",v("Additional values or ranges to consider for uniqueness."))],compute:function(...e){return As(e)}},Qs={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_range1 (range)",v("The range of cells over which to evaluate criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),a("criteria_range2 (any, range, repeating)",v("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),a("criterion2 (string, repeating)",v("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){const r=new Set;return ur(t,(t,n)=>{const o=e[t]?.[n];br(o)&&r.add(o.value)},this.locale),r.size}},Js={description:v("Cosecant of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the cosecant of, in radians."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new _(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sin(t)},isExported:!0},ei={description:v("Hyperbolic cosecant of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic cosecant of."))],compute:function(e){const t=kt(e,this.locale);return 0===t?new _(v("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sinh(t)},isExported:!0},ti={description:v("Converts from another base to decimal."),args:[a("value (string)",v("The number to convert.")),a("base (number)",v("The base to convert the value from."))],compute:function(e,t){let r=kt(t,this.locale);if(r=Math.floor(r),2>r||r>36)return new S(v("The base (%s) must be between 2 and 36 inclusive.",r));const n=$t(e);if(""===n)return 0;if(!_s.test(n))return new S(v("The value (%s) must be a valid base %s representation.",n,r));const o=parseInt(n,r);return isNaN(o)?new S(v("The value (%s) must be a valid base %s representation.",n,r)):o},isExported:!0},ri={description:v("Converts an angle value in radians to degrees."),args:[a("angle (number)",v("The angle to convert from radians to degrees."))],compute:function(e){return 180*kt(e,this.locale)/Math.PI},isExported:!0},ni={description:v("Euler's number, e (~2.718) raised to a power."),args:[a("value (number)",v("The exponent to raise e."))],compute:function(e){return Math.exp(kt(e,this.locale))},isExported:!0},oi={description:v("Rounds number down to nearest multiple of factor."),args:[a("value (number)",v("The value to round down to the nearest integer multiple of factor.")),a("factor (number, default=1)",v("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const r=kt(e,this.locale),n=kt(t,this.locale);return n<0&&r>0?new S(v("The factor (%s) must be positive when the value (%s) is positive.",n,r)):{value:n?Math.floor(r/n)*n:0,format:e?.format}},isExported:!0};function si(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 ii={description:v("Rounds number down to nearest multiple of factor."),args:[a("number (number)",v("The value to round down to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),a("mode (number, default=0)",v("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero."))],compute:function(e,t={value:1},r={value:0}){const n=kt(t,this.locale);return{value:si(kt(e,this.locale),n,kt(r,this.locale)),format:e?.format}},isExported:!0},ai={description:v("Rounds number down to nearest multiple of factor."),args:[a("number (number)",v("The value to round down to the nearest integer multiple of significance.")),a("significance (number, default=1)",v("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const r=kt(t,this.locale);return{value:si(kt(e,this.locale),r),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=Ht(e,this.locale);return!(1&Math.floor(Math.abs(t)))},isExported:!0},ci={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:Bs(kt(e,this.locale),kt(t,this.locale)),format:e?.format}},isExported:!0},ui={description:v("Whether the provided value is even."),args:[a("value (number)",v("The value to be verified as even."))],compute:function(e){const t=Ht(e,this.locale);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},hi={description:v("The logarithm of a number, base e (euler's number)."),args:[a("value (number)",v("The value for which to calculate the logarithm, base e."))],compute:function(e){const t=kt(e,this.locale);return t<=0?new S(v("The value (%s) must be strictly positive.",t)):Math.log(t)},isExported:!0},di={description:v("The logarithm of a number, for a given base."),args:[a("value (number)",v("The value for which to calculate the logarithm.")),a("base (number, default=10)",v("The base of the logarithm."))],compute:function(e,t={value:10}){const r=kt(e,this.locale),n=kt(t,this.locale);return r<=0?new S(v("The value (%s) must be strictly positive.",r)):n<=0?new S(v("The base (%s) must be strictly positive.",n)):1===n?new S(v("The base must be different from 1.")):Math.log10(r)/Math.log10(n)},isExported:!0};function fi(e,t){xr(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 gi={description:v("Modulo (remainder) operator."),args:[a("dividend (number)",v("The number to be divided to find the remainder.")),a("divisor (number)",v("The number to divide by."))],compute:function(e,t){const r=kt(t,this.locale);return{value:fi(kt(e,this.locale),r),format:e?.format}},isExported:!0},mi={description:v("Returns a n x n unit matrix, where n is the input dimension."),args:[a("dimension (number)",v("An integer specifying the dimension size of the unit matrix. It must be positive."))],compute:function(e){const t=Bt(e,this.locale);return t<1?new S(v("The argument dimension must be positive")):Dr(t)},isExported:!0},pi={description:v("Rounds a number up to the nearest odd integer."),args:[a("value (number)",v("The value to round to the next greatest odd number."))],compute:function(e){const t=kt(e,this.locale);let r=Math.ceil(Math.abs(t));return r=1&r?r:r+1,{value:t<0?-r:r,format:e?.format}},isExported:!0},bi={description:v("The number pi."),args:[],compute:function(){return Math.PI},isExported:!0},vi={description:v("A number raised to a power."),args:[a("base (number)",v("The number to raise to the exponent power.")),a("exponent (number)",v("The exponent to raise base to."))],compute:function(e,t){const r=kt(e,this.locale),n=kt(t,this.locale);return r<0&&!Number.isInteger(n)?new S(v("The exponent (%s) must be an integer when the base is negative.",n)):{value:Math.pow(r,n),format:e?.format}},isExported:!0},yi={description:v("Result of multiplying a series of numbers together."),args:[a("factor1 (number, range<number>)",v("The first number or range to calculate for the product.")),a("factor2 (number, range<number>, repeating)",v("More numbers or ranges to calculate for the product."))],compute:function(...e){let t=0,r=1;for(const n of e)if(O(n))for(const e of n)for(const n of e){const e=n.value;if("number"==typeof e&&(r*=e,t+=1),Vt(e))return n}else void 0!==n&&null!==n.value&&(r*=Ht(n,this.locale),t+=1);return{value:0===t?0:r,format:Mt(e[0])}},isExported:!0},wi={description:v("A random number between 0 inclusive and 1 exclusive."),args:[],compute:function(){return Math.random()},isExported:!0},Ei={description:v("Returns a grid of random numbers between 0 inclusive and 1 exclusive."),args:[a("rows (number, default=1)",v("The number of rows to be returned.")),a("columns (number, default=1)",v("The number of columns to be returned.")),a("min (number, default=0)",v("The minimum number you would like returned.")),a("max (number, default=1)",v("The maximum number you would like returned.")),a("whole_number (boolean, default=FALSE)",v("Return a whole number or a decimal value."),[{value:!1,label:v("Decimal (default)")},{value:!0,label:v("Integer")}])],compute:function(e={value:1},t={value:1},r={value:0},n={value:1},o={value:!1}){const s=Bt(t,this.locale),i=Bt(e,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=qt(o);if(s<1)return new S(v("The number of columns (%s) must be positive.",s));if(i<1)return new S(v("The number of rows (%s) must be positive.",i));if(a>l)return new S(v("The maximum (%s) must be greater than or equal to the minimum (%s).",l,a));if(c&&(!Number.isInteger(a)||!Number.isInteger(l)))return new S(v("The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.",l.toString(),a.toString()));const u=Array(s);for(let e=0;e<s;e++){u[e]=Array(i);for(let t=0;t<i;t++)u[e][t]=c?Math.floor(Math.random()*(l-a+1)+a):a+Math.random()*(l-a)}return u},isExported:!0},Si={description:v("Random integer between two values, inclusive."),args:[a("low (number)",v("The low end of the random range.")),a("high (number)",v("The high end of the random range."))],compute:function(e,t){let r=kt(e,this.locale);Number.isInteger(r)||(r=Math.ceil(r));let n=kt(t,this.locale);return Number.isInteger(n)||(n=Math.floor(n)),r>n?new S(v("The high (%s) must be greater than or equal to the low (%s).",n,r)):{value:r+Math.ceil((n-r+1)*Math.random())-1,format:e?.format}},isExported:!0},Ci={description:v("Rounds a number according to standard rules."),args:[a("value (number)",v("The value to round to places number of places.")),a("places (number, default=0)",v("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const r=kt(e,this.locale);let n=kt(t,this.locale);const o=Math.abs(r);let s;return 0===n?s=Math.round(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.round(o*Math.pow(10,n))/Math.pow(10,n)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},Ti={description:v("Rounds down a number."),args:[a("value (number)",v("The value to round to places number of places, always rounding down.")),a("places (number, default=0)",v("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const r=kt(e,this.locale);let n=kt(t,this.locale);const o=Math.abs(r);let s;return 0===n?s=Math.floor(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.floor(o*Math.pow(10,n))/Math.pow(10,n)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},Ii={description:v("Rounds up a number."),args:[a("value (number)",v("The value to round to places number of places, always rounding up.")),a("places (number, default=0)",v("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const r=kt(e,this.locale);let n=kt(t,this.locale);const o=Math.abs(r);let s;return 0===n?s=Math.ceil(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.ceil(o*Math.pow(10,n))/Math.pow(10,n)),{value:r>=0?s:-s,format:e?.format}},isExported:!0},xi={description:v("Secant of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the secant of, in radians."))],compute:function(e){return 1/Math.cos(kt(e,this.locale))},isExported:!0},Ri={description:v("Hyperbolic secant of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic secant of."))],compute:function(e){return 1/Math.cosh(kt(e,this.locale))},isExported:!0},Ai={description:v("Returns a sequence of numbers."),args:[a("rows (number)",v("The number of rows to return")),a("columns (number, optional, default=1)",v("The number of columns to return")),a("start (number, optional, default=1)",v("The first number in the sequence")),a("step (number, optional, default=1)",v("The amount to increment each value in the sequence"))],compute:function(e,t={value:1},r={value:1},n={value:1}){const o=kt(r,this.locale),s=kt(n,this.locale),i=Bt(e,this.locale),a=Bt(t,this.locale);return a<1?new S(v("The number of columns (%s) must be positive.",a)):i<1?new S(v("The number of rows (%s) must be positive.",i)):rr(a,i,(e,t)=>({value:o+t*a*s+e*s}))},isExported:!0},_i={description:v("Sine of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the sine of, in radians."))],compute:function(e){return Math.sin(kt(e,this.locale))},isExported:!0},Oi={description:v("Hyperbolic sine of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic sine of."))],compute:function(e){return Math.sinh(kt(e,this.locale))},isExported:!0},Di={description:v("Positive square root of a positive number."),args:[a("value (number)",v("The number for which to calculate the positive square root."))],compute:function(e){const t=kt(e,this.locale);return t<0?new S(v("The value (%s) must be positive or null.",t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},Fi={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP"},Ni=Object.entries(Fi).map(([e,t])=>({value:parseInt(e),label:v("%s (include manually-hidden rows)",t)})),Mi=Object.entries(Fi).map(([e,t])=>({value:parseInt(e)+100,label:v("%s (exclude manually-hidden rows)",t)})),Vi={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."),[...Ni,...Mi]),a("ref1 (meta, range<meta>)",v("The range or reference for which you want the subtotal.")),a("ref2 (meta, range<meta>, repeating)",v("Additional ranges or references for which you want the subtotal."))],compute:function(e,...t){let r=Bt(e,this.locale),n=!0;if(r>100&&(r-=100,n=!1),r<1||r>11)return new S(v("The function code (%s) must be between 1 to 11 or 101 to 111.",r));const o=[];for(const e of t){const t=e[0][0],r=go(t.value).sheetName,s=r?this.getters.getSheetIdByName(r):this.__originSheetId;if(!s)continue;const{top:i,left:a}=Bo(t.value),l=a+e.length-1,c=i+e[0].length-1;for(let e=i;e<=c;e++)if(!this.getters.isRowFiltered(s,e)&&(n||!this.getters.isRowHiddenByUser(s,e)))for(let t=a;t<=l;t++){const r=this.getters.getCell({sheetId:s,col:t,row:e});r&&xs(r)||o.push(this.getters.getEvaluatedCell({sheetId:s,col:t,row:e}))}}return this[Fi[r]].apply(this,[[o]])},isExported:!0},Li={description:v("Sum of a series of numbers and/or cells."),args:[a("value1 (number, range<number>)",v("The first number or range to add together.")),a("value2 (number, range<number>, repeating)",v("Additional numbers or ranges to add to value1."))],compute:function(...e){const t=e[0];return{value:Rs(e,this.locale),format:Mt(t)}},isExported:!0},Pi={description:v("A conditional sum across a range."),args:[a("criteria_range (range)",v("The range which is tested against criterion.")),a("criterion (string)",v("The pattern or test to apply to range.")),a("sum_range (range, default=criteria_range)",v("The range to be summed, if different from range."))],compute:function(e,t,r){void 0===r&&(r=e);let n=0;return ur([e,t],(e,t)=>{const o=r[e]?.[t]?.value;"number"==typeof o&&(n+=o)},this.locale),n},isExported:!0},ki={description:v("Sums a range depending on multiple criteria."),args:[a("sum_range (range)",v("The range to sum.")),a("criteria_range1 (range)",v("The range to check against criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1.")),a("criteria_range2 (any, range, repeating)",v("Additional ranges to check.")),a("criterion2 (string, repeating)",v("Additional criteria to check."))],compute:function(e,...t){let r=0;return ur(t,(t,n)=>{const o=e[t]?.[n]?.value;"number"==typeof o&&(r+=o)},this.locale),r},isExported:!0},Ui={description:v("Tangent of an angle provided in radians."),args:[a("angle (number)",v("The angle to find the tangent of, in radians."))],compute:function(e){return Math.tan(kt(e,this.locale))},isExported:!0},Hi={description:v("Hyperbolic tangent of any real number."),args:[a("value (number)",v("Any real value to calculate the hyperbolic tangent of."))],compute:function(e){return Math.tanh(kt(e,this.locale))},isExported:!0};function Bi(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 zi={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:Bi(kt(e,this.locale),kt(t,this.locale)),format:e?.format}},isExported:!0},$i={description:v("Rounds a number down to the nearest integer that is less than or equal to it."),args:[a("value (number)",v("The number to round down to the nearest integer."))],compute:function(e){return Math.floor(kt(e,this.locale))},isExported:!0};var Gi=Object.freeze({__proto__:null,ABS:Os,ACOS:Ds,ACOSH:Fs,ACOT:Ns,ACOTH:Ms,ASIN:Vs,ASINH:Ls,ATAN:Ps,ATAN2:ks,ATANH:Us,CEILING:Hs,CEILING_MATH:zs,CEILING_PRECISE:$s,COS:Gs,COSH:Ws,COT:qs,COTH:Zs,COUNTBLANK:Ys,COUNTIF:js,COUNTIFS:Xs,COUNTUNIQUE:Ks,COUNTUNIQUEIFS:Qs,CSC:Js,CSCH:ei,DECIMAL:ti,DEGREES:ri,EXP:ni,FLOOR:oi,FLOOR_MATH:ii,FLOOR_PRECISE:ai,INT:$i,ISEVEN:li,ISODD:ui,ISO_CEILING:ci,LN:hi,LOG:di,MOD:gi,MUNIT:mi,ODD:pi,PI:bi,POWER:vi,PRODUCT:yi,RAND:wi,RANDARRAY:Ei,RANDBETWEEN:Si,ROUND:Ci,ROUNDDOWN:Ti,ROUNDUP:Ii,SEC:xi,SECH:Ri,SEQUENCE:Ai,SIN:_i,SINH:Oi,SQRT:Di,SUBTOTAL:Vi,SUM:Li,SUMIF:Pi,SUMIFS:ki,TAN:Ui,TANH:Hi,TRUNC:zi});function Wi(...e){const t=e[0].length;e.forEach((e,r)=>Ir(e.length===t,v("[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).",r.toString(),t.toString(),e.length.toString())))}function qi(e,t){let r=0;const n=er(e,(e,t)=>(r+=1,e+t),0,t);return xr(r),n/r}function Zi(e){return Jt(e,(e,t)=>void 0!==t&&null!==t.value?e+1:e,0)}function Yi(e,t){let r={value:-1/0};return Kt(e,e=>{e.value>=r.value&&(r=e)},t),r.value===-1/0?{value:0}:r}function ji(e,t){let r={value:1/0};return Kt(e,e=>{e.value<=r.value&&(r=e)},t),r.value===1/0?{value:0}:r}function Xi(e,t,r){const n=e[0].length?e:[le(1,t.flat().length+1)],o=n.length;let s=r[0].length?r:n;return s=s.length===o?or(s):s,{_X:n,_newX:s}}function Ki(e,t,r=!0,n=!1){const o=t.flat(),s=o.length;let{_X:i}=Xi(e,t,[[]]);i=i.length===s?or(i):i.slice(),Wi(i[0],o);const a=i.length,l=s-a-(r?1:0),c=[o],u=or(i.reverse()),h=[];for(let e=0;e<a;e++)if(h.push(0),r){for(const t of i[e])h[e]+=t;h[e]/=s}let d=0;if(r){for(const e of o)d+=e;d/=s}const f=u.map(e=>e.map((e,t)=>e-h[t]));r&&u.forEach(e=>e.push(1));const g=Ji(u,c);if(r||g.push([0]),!n)return g;const m=Mr(f,or(f)),{inverted:p}=Fr(m);if(void 0===p)throw new S(v("Matrix is not invertible"));let b=0,y=0;for(let e=0;e<s;e++){const t=o[e]-d;let r=0;for(let t=0;t<a;t++){r+=f[e][t]*g[t][0]}const n=t-r;b+=n*n,y+=r*r}const 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=Mr(p,[h]),t=Mr(or([h]),e);T.push(w*Math.sqrt(t[0][0]+1/o.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 Qi(e,t,r,n){Wi(t,e),Ir(r>=1,v("Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible."));const o=[e],s=t.map(e=>le(0,r).map(t=>Math.pow(e,r-t)));n&&s.forEach(e=>e.push(1));const i=Ji(s,o);return n||i.push([0]),i}function Ji(e,t){const r=Mr(e,or(e)),{inverted:n}=Fr(r);if(void 0===n)throw new S(v("Matrix is not invertible"));const o=Mr(e,t);return or(Mr(n,o))}function ea(e){return e.map(e=>e.map(e=>Math.log(e)))}function ta(e,t,r,n){const{_X:o,_newX:s}=Xi(t,e,r),i=Ki(o,e,n,!1),a=i.length-1,l=s.map(e=>{let t=0;for(let r=0;r<a;r++)t+=i[r][0]*e[a-r-1];return t+=i[a][0],[t]});return l.length===r.length?l:or(l)}const ra=[{value:!0,label:v("b is calculated normally")},{value:!1,label:v("b is forced to 1")}],na=[{value:!1,label:v("do not return additional regression statistics")},{value:!0,label:v("return additional regression statistics")}],oa=[{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)")}],sa=[{value:!0,label:v("Compute intercept")},{value:!1,label:v("Force intercept to 0")}],ia=[{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 aa(e,t){const r=[],n=[];let o=0,s=0;Xt([e],e=>{r.push(e),o+=1}),Xt([t],e=>{n.push(e),s+=1}),Ir(o===s,v("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",o,s));const i=[],a=[];for(let e=0;e<o;e++){const t=r[e]?.value,o=n[e]?.value;"number"==typeof t&&"number"==typeof o&&(a.push(t),i.push(o))}return{flatDataX:i,flatDataY:a}}function la(e,t,r){const{flatDataX:n,flatDataY:o}=aa(e,t),s=o.length;xr(s),r&&xr(s-1);let i=0,a=0;for(let e=0;e<s;e++)i+=o[e],a+=n[e];const l=i/s,c=a/s;let u=0;for(let e=0;e<s;e++)u+=(o[e]-l)*(n[e]-c);return u/(s-(r?1:0))}function ca(e,t,r,n){let o=0;const s=r?tr:er,i=s(e,(e,t)=>(o+=1,e+t),0,n);xr(o),t&&xr(o-1);const a=i/o;return s(e,(e,t)=>e+Math.pow(t-a,2),0,n)/(o-(t?1:0))}function ua(e,t,r,n){const o=kt(t,n);Ir(r?0<=o&&o<=1:0<o&&o<1,v("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));const s=[];let i,a=0;return Xt(e,e=>{const t=e?.value;"number"==typeof t&&(i=hr(s,e,"nextSmaller","asc",s.length,(e,t)=>e[t]),s.splice(i+1,0,t),a++)}),Ir(0!==a,vr),r||Ir(1/(a+1)<=o&&o<=a/(a+1),v("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),Ft(s,o,r)}const ha={description:v("Average magnitude of deviations from mean."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){let t=0;const r=er(e,(e,r)=>(t+=1,e+r),0,this.locale);if(0===t)return new _(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const n=r/t;return er(e,(e,t)=>e+Math.abs(n-t),0,this.locale)/t},isExported:!0},da={description:v("Numerical average value in a dataset, ignoring text."),args:[a("value1 (number, range<number>)",v("The first value or range to consider when calculating the average value.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to consider when calculating the average value."))],compute:function(...e){return{value:qi(e,this.locale),format:Mt(e[0])}},isExported:!0},fa=v("[[FUNCTION_NAME]] has mismatched range sizes."),ga=v("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),ma={description:v("Weighted average."),args:[a("values (number, range<number>)",v("Values to average.")),a("weights (number, range<number>)",v("Weights for each corresponding value.")),a("additional_values (number, range<number>, repeating)",v("Additional values to average.")),a("additional_weights (number, range<number>, repeating)",v("Additional weights."))],compute:function(...e){let t=0,r=0;for(let n=0;n<e.length-1;n+=2){const o=e[n],s=e[n+1];if(!Ar(o,s))return new S(fa);if(O(o))for(let e=0;e<o.length;e++)for(let n=0;n<o[0].length;n++){const i=o[e][n].value,a=O(s)?s?.[e][n].value:kt(s,this.locale),l="number"==typeof i,c="number"==typeof a;if(l&&c){if(a<0)return new S(ga);t+=i*a,r+=a}else if(l!==c)return new S(v("[[FUNCTION_NAME]] expects number values."))}else{const e=kt(o,this.locale),n=O(s)?s?.[0][0].value:kt(s,this.locale);if("number"==typeof n){if(n<0)return new S(ga);t+=e*n,r+=n}}}return 0===r?new _(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:t/r,format:Mt(e[0])}}},pa={description:v("Numerical average value in a dataset."),args:[a("value1 (number, range<number>)",v("The first value or range to consider when calculating the average value.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to consider when calculating the average value."))],compute:function(...e){let t=0;const r=tr(e,(e,r)=>(t+=1,e+r),0,this.locale);return 0===t?new _(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:r/t,format:Mt(e[0])}},isExported:!0},ba={description:v("Average of values depending on criteria."),args:[a("criteria_range (number, range<number>)",v("The range to check against criterion.")),a("criterion (string)",v("The pattern or test to apply to criteria_range.")),a("average_range (number, range<number>, default=criteria_range)",v("The range to average. If not included, criteria_range is used for the average instead."))],compute:function(e,t,r){const n=mr(void 0===r?e:r);let o=0,s=0;return ur([e,t],(e,t)=>{const r=n[e]?.[t]?.value;"number"==typeof r&&(o+=1,s+=r)},this.locale),0===o?new _(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):s/o},isExported:!0},va={description:v("Average of values depending on multiple criteria."),args:[a("average_range (range)",v("The range to average.")),a("criteria_range1 (range)",v("The range to check against criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1.")),a("criteria_range2 (any, range, repeating)",v("Additional criteria_range and criterion to check.")),a("criterion2 (string, repeating)",v("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){const r=mr(e);let n=0,o=0;return ur(t,(e,t)=>{const s=r[e]?.[t]?.value;"number"==typeof s&&(n+=1,o+=s)},this.locale),0===n?new _(v("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):o/n},isExported:!0},ya={description:v("The number of numeric values in dataset."),args:[a("value1 (number, any, range<number>)",v("The first value or range to consider when counting.")),a("value2 (number, any, range<number>, repeating)",v("Additional values or ranges to consider when counting."))],compute:function(...e){return function(e,t){let r=0;for(const n of e)if(O(n))for(const e of n)for(const t of e)"number"==typeof t.value&&(r+=1);else{const e=n?.value;Vt(e)||"string"==typeof e&&!_t(e,t)&&!gt(e,t)||(r+=1)}return r}(e,this.locale)},isExported:!0},wa={description:v("The number of values in a dataset."),args:[a("value1 (any, range)",v("The first value or range to consider when counting.")),a("value2 (any, range, repeating)",v("Additional values or ranges to consider when counting."))],compute:function(...e){return Zi(e)},isExported:!0},Ea={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 la(e,t,!1)},isExported:!0},Sa={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 la(e,t,!1)},isExported:!0},Ca={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 la(e,t,!0)},isExported:!0},Ta={description:v("Calculates the expected y-value for a specified x based on a linear regression of a dataset."),args:[a("x (number, range<number>)",v("The value(s) on the x-axis to forecast.")),a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t,r){const{flatDataX:n,flatDataY:o}=aa(t,r);return 0===n.length||0===o.length?new x(vr):ta([o],[n],nr(mr(e),e=>kt(e,this.locale)),!0)},isExported:!0},Ia={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."),ra)],compute:function(e,t=[[]],r=[[]],n={value:!0}){return 0===e.length||0===e[0].length?new S(yr("known_data_y")):ta(ea(Ut(e,"known_data_y")),Ut(t,"known_data_x"),Ut(r,"new_data_y"),qt(n)).map(e=>e.map(e=>Math.exp(e)))}},xa={description:v("Compute the intercept of the linear regression."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=aa(e,t);if(0===r.length||0===n.length)return new x(vr);const[[],[o]]=Ki([r],[n]);return o},isExported:!0},Ra={description:v("Nth largest element from a data set."),args:[a("data (any, range)",v("Array or range containing the dataset to consider.")),a("n (number)",v("The rank from largest to smallest of the element to return."))],compute:function(e,t){const r=Math.trunc(kt(t?.value,this.locale)),n=[];let o,s=0;Xt([e],e=>{"number"==typeof e?.value&&(o=hr(n,e,"nextSmaller","asc",n.length,(e,t)=>e[t].value),n.splice(o+1,0,e),s++,s>r&&(n.shift(),s--))});const i=n.shift();return void 0===i?new S(vr):s<r?new S(v("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",r)):i},isExported:!0},Aa={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"),ra),a("verbose (boolean, default=FALSE)",v("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),na)],compute:function(e,t=[[]],r={value:!0},n={value:!1}){return 0===e.length||0===e[0].length?new S(yr("data_y")):Ki(Ut(t,"data_x"),Ut(e,"data_y"),qt(r),qt(n))},isExported:!0},_a={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"),ra),a("verbose (boolean, default=FALSE)",v("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),na)],compute:function(e,t=[[]],r={value:!0},n={value:!1}){if(0===e.length||0===e[0].length)return new S(yr("data_y"));const o=Ki(Ut(t,"data_x"),ea(Ut(e,"data_y")),qt(r),qt(n));for(let e=0;e<o.length;e++)o[e][0]=Math.exp(o[e][0]);return o},isExported:!0},Oa={description:v("Compute the Matthews correlation coefficient of a dataset."),args:[a("data_x (range)",v("The range representing the array or matrix of observed data.")),a("data_y (range)",v("The range representing the array or matrix of predicted data."))],compute:function(e,t){const r=e.flat(),n=t.flat();if(Wi(r,n),0===r.length||0===n.length)return new x(vr);const o=r.length;let s=0,i=0,a=0,l=0;for(let e=0;e<o;++e){const t=qt(r[e]);t===qt(n[e])?t?i++:s++:t?l++:a++}return(i*s-a*l)/Math.sqrt((i+a)*(i+l)*(s+a)*(s+l))},isExported:!1},Da={description:v("Maximum value in a numeric dataset."),args:[a("value1 (number, range<number>)",v("The first value or range to consider when calculating the maximum value.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to consider when calculating the maximum value."))],compute:function(...e){return Yi(e,this.locale)},isExported:!0},Fa={description:v("Maximum numeric value in a dataset."),args:[a("value1 (any, range)",v("The first value or range to consider when calculating the maximum value.")),a("value2 (any, range, repeating)",v("Additional values or ranges to consider when calculating the maximum value."))],compute:function(...e){const t=tr(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:Mt(e[0])}},isExported:!0},Na={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_range1 (range)",v("The range of cells over which to evaluate criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),a("criteria_range2 (any, range, repeating)",v("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),a("criterion2 (string, repeating)",v("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){let r=-1/0;return ur(t,(t,n)=>{const o=e[t]?.[n]?.value;"number"==typeof o&&(r=r<o?o:r)},this.locale),r===-1/0?0:r},isExported:!0},Ma={description:v("Median value in a numeric dataset."),args:[a("value1 (any, range)",v("The first value or range to consider when calculating the median value.")),a("value2 (any, range, repeating)",v("Additional values or ranges to consider when calculating the median value."))],compute:function(...e){const t=[];return Kt(e,e=>{t.push(e)},this.locale),{value:ua(t,{value:.5},!0,this.locale),format:Mt(t[0])}},isExported:!0},Va={description:v("Minimum value in a numeric dataset."),args:[a("value1 (number, range<number>)",v("The first value or range to consider when calculating the minimum value.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to consider when calculating the minimum value."))],compute:function(...e){return ji(e,this.locale)},isExported:!0},La={description:v("Minimum numeric value in a dataset."),args:[a("value1 (number, range<number>)",v("The first value or range to consider when calculating the minimum value.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to consider when calculating the minimum value."))],compute:function(...e){const t=tr(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:Mt(e[0])}},isExported:!0},Pa={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_range1 (range)",v("The range of cells over which to evaluate criterion1.")),a("criterion1 (string)",v("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),a("criteria_range2 (any, range, repeating)",v("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),a("criterion2 (string, repeating)",v("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){let r=1/0;return ur(t,(t,n)=>{const o=e[t]?.[n]?.value;"number"==typeof o&&(r=r>o?o:r)},this.locale),r===1/0?0:r},isExported:!0};function ka(e,t){const{flatDataX:r,flatDataY:n}=aa(e,t);if(0===r.length||0===n.length)return new x(vr);const o=r.length;let s=0,i=0,a=0,l=0,c=0;for(let e=0;e<o;e++){const t=r[e],o=n[e];s+=t,i+=o,a+=t*o,l+=t*t,c+=o*o}return(o*a-s*i)/Math.sqrt((o*l-s*s)*(o*c-i*i))}const Ua={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 ka(e,t)},isExported:!0},Ha=Ua,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 $a.compute.bind(this)(e,t)},isExported:!0},za={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:ua([e],t,!1,this.locale),format:Mt(e)}},isExported:!0},$a={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:ua([e],t,!0,this.locale),format:Mt(e)}},isExported:!0},Ga={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."),oa),a("intercept (boolean, default=TRUE)",v("A flag specifying whether to compute the intercept or not."),sa)],compute:function(e,t,r,n={value:!0}){const{flatDataX:o,flatDataY:s}=aa(e,t);return 0===o.length||0===s.length?new x(vr):Qi(s,o,kt(r,this.locale),qt(n))},isExported:!1},Wa={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."),oa),a("intercept (boolean, default=TRUE)",v("A flag specifying whether to compute the intercept or not."),sa)],compute:function(e,t,r,n,o={value:!0}){const s=kt(n,this.locale),{flatDataX:i,flatDataY:a}=aa(t,r);if(0===i.length||0===a.length)return new x(vr);const l=Qi(a,i,s,qt(o)).flat();return nr(mr(e),e=>function(e,t,r){return e.reduce((e,n,o)=>e+n*Math.pow(t,r-o),0)}(l,kt(e,this.locale),s))},isExported:!1},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."),ia)],compute:function(e,t){return Ya.compute.bind(this)(e,t)},isExported:!0},Za={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:ua([e],{value:.25*Math.trunc(kt(t,this.locale))},!1,this.locale),format:Mt(e)}},isExported:!0},Ya={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."),ia)],compute:function(e,t){return{value:ua([e],{value:.25*Math.trunc(kt(t,this.locale))},!0,this.locale),format:Mt(e)}},isExported:!0},ja={description:v("Returns the rank of a specified value in a dataset."),args:[a("value (number)",v("The value whose rank will be determined.")),a("data (range)",v("The range containing the dataset to consider.")),a("is_ascending (boolean, default=FALSE)",v("Whether to consider the values in data in descending or ascending order."),[{value:!1,label:v("Descending")},{value:!0,label:v("Ascending")}])],compute:function(e,t,r={value:!1}){const n=qt(r),o=kt(e,this.locale);let s=1,i=!1;for(const e of t)for(const t of e){if("number"!=typeof t.value)continue;const e=kt(t,this.locale);e===o?i=!0:e>o!==n&&s++}return i?s:new x(v("Value not found in the given data."))},isExported:!0},Xa={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=ka(e,t);if(r instanceof Error)throw r;return Math.pow(r,2)},isExported:!0},Ka={description:v("Compute the slope of the linear regression."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=aa(e,t);if(0===r.length||0===n.length)return new x(vr);const[[o]]=Ki([r],[n]);return o},isExported:!0},Qa={description:v("Nth smallest element in a data set."),args:[a("data (any, range)",v("The array or range containing the dataset to consider.")),a("n (number)",v("The rank from smallest to largest of the element to return."))],compute:function(e,t){const r=Math.trunc(kt(t?.value,this.locale)),n=[];let o,s=0;Xt([e],e=>{"number"==typeof e?.value&&(o=hr(n,e,"nextSmaller","asc",n.length,(e,t)=>e[t].value),n.splice(o+1,0,e),s++,s>r&&(n.pop(),s--))});const i=n.pop();return void 0===i?new S(vr):s<r?new S(v("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",r)):i},isExported:!0},Ja={description:v("Compute the Spearman rank correlation coefficient of a dataset."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=aa(t,e);if(0===r.length||0===n.length)return new x(vr);const o=r.length,s=r.map((e,t)=>[e,n[t]]);s.sort((e,t)=>e[0]-t[0]);for(let e=0;e<o;++e)s[e][0]=e;s.sort((e,t)=>e[1]-t[1]);let i=0;for(let e=0;e<o;++e)i+=(s[e][0]-e)**2;return 1-6*i/(o**3-o)},isExported:!1},el={description:v("Standard deviation."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(ll.compute.bind(this)(...e))},isExported:!0},tl={description:v("Standard deviation of entire population."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(cl.compute.bind(this)(...e))},isExported:!0},rl={description:v("Standard deviation."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(ul.compute.bind(this)(...e))},isExported:!0},nl={description:v("Standard deviation of sample (text as 0)."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(hl.compute.bind(this)(...e))},isExported:!0},ol={description:v("Standard deviation of entire population."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(dl.compute.bind(this)(...e))},isExported:!0},sl={description:v("Standard deviation of entire population (text as 0)."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(fl.compute.bind(this)(...e))},isExported:!0},il={description:v("Calculates the standard error of the predicted y-value for each x in the regression of a dataset."),args:[a("data_y (range<number>)",v("The range representing the array or matrix of dependent data.")),a("data_x (range<number>)",v("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:r,flatDataY:n}=aa(e,t);if(0===r.length||0===n.length)return new x(vr);return Ki([r],[n],!0,!0)[1][2]},isExported:!0},al={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."),ra)],compute:function(e,t=[[]],r=[[]],n={value:!0}){return 0===e.length||0===e[0].length?new S(yr("known_data_y")):ta(Ut(e,"known_data_y"),Ut(t,"known_data_x"),Ut(r,"new_data_y"),qt(n))}},ll={description:v("Variance."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return ca(e,!0,!1,this.locale)},isExported:!0},cl={description:v("Variance of entire population."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return ca(e,!1,!1,this.locale)},isExported:!0},ul={description:v("Variance."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return ca(e,!0,!1,this.locale)},isExported:!0},hl={description:v("Variance of sample (text as 0)."),args:[a("value1 (number, range<number>)",v("The first value or range of the sample.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the sample."))],compute:function(...e){return ca(e,!0,!0,this.locale)},isExported:!0},dl={description:v("Variance of entire population."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return ca(e,!1,!1,this.locale)},isExported:!0},fl={description:v("Variance of entire population (text as 0)."),args:[a("value1 (number, range<number>)",v("The first value or range of the population.")),a("value2 (number, range<number>, repeating)",v("Additional values or ranges to include in the population."))],compute:function(...e){return ca(e,!1,!0,this.locale)},isExported:!0};var gl=Object.freeze({__proto__:null,AVEDEV:ha,AVERAGE:da,AVERAGEA:pa,AVERAGEIF:ba,AVERAGEIFS:va,AVERAGE_WEIGHTED:ma,CORREL:Ha,COUNT:ya,COUNTA:wa,COVAR:Ea,COVARIANCE_P:Sa,COVARIANCE_S:Ca,FORECAST:Ta,GROWTH:Ia,INTERCEPT:xa,LARGE:Ra,LINEST:Aa,LOGEST:_a,MATTHEWS:Oa,MAX:Da,MAXA:Fa,MAXIFS:Na,MEDIAN:Ma,MIN:Va,MINA:La,MINIFS:Pa,PEARSON:Ua,PERCENTILE:Ba,PERCENTILE_EXC:za,PERCENTILE_INC:$a,POLYFIT_COEFFS:Ga,POLYFIT_FORECAST:Wa,QUARTILE:qa,QUARTILE_EXC:Za,QUARTILE_INC:Ya,RANK:ja,RSQ:Xa,SLOPE:Ka,SMALL:Qa,SPEARMAN:Ja,STDEV:el,STDEVA:nl,STDEVP:ol,STDEVPA:sl,STDEV_P:tl,STDEV_S:rl,STEYX:il,TREND:al,VAR:ll,VARA:hl,VARP:dl,VARPA:fl,VAR_P:cl,VAR_S:ul});function ml(e,t,r,n){const o=new Map,s=e.length;for(let t=s-1;t>=0;t--)o.set($t(e[t][0]).toUpperCase(),t);const i=t?.value;if("number"!=typeof i&&"string"!=typeof i)throw new S(v("The field must be a number or a string"));let a;if("number"==typeof i){if(a=Math.trunc(i)-1,a<0||s-1<a)throw new S(v("The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.",{fieldValue:i.toString(),dimRowDB:s.toString()}))}else{const e=$t(t).toUpperCase();if(a=o.get(e)??-1,-1===a)throw new S(v("The field (%s) must be one of %s.",$t(t),[...o.keys()].toString()))}const l=r[0].length;if(l<2)throw new S(v("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const u=e[0].length;for(let t=1;t<l;t++){const s=[];let i=!0;for(let n=0;n<r.length;n++){const a=$t(r[n][0]).toUpperCase(),l=o.get(a),c=r[n][t];if(null!==c.value){if(void 0===l){i=!1;break}s.push([e[l].slice(1,u)]),s.push(c)}}if(i){if(!(s.length>0)){c=new Set(Array(u-1).keys());break}ur(s,(e,t)=>{c.add(t)},n,!0)}}const h=e[a];return[...c].map(e=>h[e+1])}const pl=[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."))],bl={description:v("Average of a set of values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return da.compute.bind(this)([n])},isExported:!0},vl={description:v("Counts values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return ya.compute.bind(this)([n])},isExported:!0},yl={description:v("Counts values and text from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return wa.compute.bind(this)([n])},isExported:!0},wl={description:v("Single value from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return 1!==n.length?new S(v("More than one match found in DGET evaluation.")):n[0]},isExported:!0},El={description:v("Maximum of values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return Da.compute.bind(this)([n])},isExported:!0},Sl={description:v("Minimum of values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return Va.compute.bind(this)([n])},isExported:!0},Cl={description:v("Product of values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return yi.compute.bind(this)([n])},isExported:!0},Tl={description:v("Standard deviation of population sample from table."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return el.compute.bind(this)([n])},isExported:!0},Il={description:v("Standard deviation of entire population from table."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return ol.compute.bind(this)([n])},isExported:!0},xl={description:v("Sum of values from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return Li.compute.bind(this)([n])},isExported:!0},Rl={description:v("Variance of population sample from table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return ll.compute.bind(this)([n])},isExported:!0},Al={description:v("Variance of a population from a table-like range."),args:pl,compute:function(e,t,r){const n=ml(e,t,r,this.locale);return dl.compute.bind(this)([n])},isExported:!0};var _l=Object.freeze({__proto__:null,DAVERAGE:bl,DCOUNT:vl,DCOUNTA:yl,DGET:wl,DMAX:El,DMIN:Sl,DPRODUCT:Cl,DSTDEV:Tl,DSTDEVP:Il,DSUM:xl,DVAR:Rl,DVARP:Al});const Ol=[{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:";"}],Dl=Ol[0],Fl=["%"],Nl="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Fl);function Ml(e,t=Dl){e=Pe(e);const r=new Ze(e),n=[],o=Me.test(e)?ql:Zl;for(;!r.isOver();){let e=Yl(r)||o(r)||kl(r,t)||Pl(r)||Ul(r)||zl(r)||Vl(r)||jl(r)||Bl(r,t)||Wl(r);e||(e={type:"UNKNOWN",value:r.shift()}),n.push(e)}return n}function Vl(e){return"?"===e.current?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const Ll={"(":{type:"LEFT_PAREN",value:"("},")":{type:"RIGHT_PAREN",value:")"}};function Pl(e){if("("===e.current||")"===e.current){const t=e.shift();return Ll[t]}return null}function kl(e,t){if(e.current===t.formulaArgSeparator){return{type:"ARG_SEPARATOR",value:e.shift()}}return null}function Ul(e){for(const t of Nl)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}const Hl=new Set("0123456789");function Bl(e,t){if(!Hl.has(e.current)&&e.current!==t.decimalSeparator)return null;const r=e.remaining().match(Rt(t.decimalSeparator));return r?(e.advanceBy(r[0].length),{type:"NUMBER",value:r[0]}):null}function zl(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 $l=/\p{L}|\p{N}|_|\.|!|\$/u,Gl=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$");function Wl(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&&(Gl.has(e.current)||e.current.match($l));)t+=e.shift();if(t.length){const e=t;return ao.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function ql(e){let t="";for(;" "===e.current||e.current&&e.current.match(Me);)t+=e.shift();return t?{type:"SPACE",value:t}:null}function Zl(e){let t="";for(;" "===e.current;)t+=e.shift();return t?{type:"SPACE",value:t}:null}function Yl(e){let t=0;for(;e.current===Q;)t++,e.shift();return t?{type:"SPACE",value:Q.repeat(t)}:null}function jl(e){return e.currentStartsWith(w.InvalidReference)?(e.advanceBy(w.InvalidReference.length),{type:"INVALID_REFERENCE",value:w.InvalidReference}):null}function Xl(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{Fn(1,{locale:e,format:"#,##0.00"}),Fn(1,{locale:e,format:e.dateFormat}),Fn(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function Kl(e,t){return Ke(e)?function(e,t){return ec(e.startsWith("+")?"="+e.slice(1):e,t,Dl)}(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 Ql(e,t){return e.startsWith("=")?Jl(e,t):function(e,t){if(dt(e,Dl)){const r=kt(e,Dl);let n=t.dateFormat;return Number.isInteger(r)||(n+=" "+t.timeFormat),Fn(r,{locale:t,format:n})}return function(e,t){if("."===t.decimalSeparator||!_t(e,Dl))return e;const r=zn(Dl);return e.replace(r,e=>e.replace(".",t.decimalSeparator))}(e,t)}(e,t)}function Jl(e,t){return ec(e,Dl,t)}function ec(e,t,r){if(t.formulaArgSeparator===r.formulaArgSeparator&&t.decimalSeparator===r.decimalSeparator)return e;const n=Ml(e,t);let o="";for(const e of n)"NUMBER"===e.type?o+=e.value.replace(t.decimalSeparator,r.decimalSeparator):"ARG_SEPARATOR"===e.type?o+=r.formulaArgSeparator:o+=e.value;return o}function tc(e){return e.dateFormat+" "+e.timeFormat}const rc=v("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."),nc=v("There must be both positive and negative values in cashflow_amounts."),oc=e=>v("The cost (%s) must be positive or null.",e),sc=e=>v("The frequency (%s) must be one of %s",e,[1,2,4].toString()),ic=e=>v("The day_count_convention (%s) must be between 0 and 4 inclusive.",e),ac=e=>v("The depreciation factor (%s) must be strictly positive.",e),lc=e=>v("The discount (%s) must be strictly positive.",e),cc=e=>v("The discount (%s) must be smaller than 1.",e),uc=e=>v("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e),hc=(e,t)=>v("The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).",{first:e,last:t}),dc=e=>v("The first_period (%s) must be strictly positive.",e),fc=e=>v("The investment (%s) must be strictly positive.",e),gc=(e,t)=>v("The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).",{last:e,nPeriods:t}),mc=e=>v("The last_period (%s) must be strictly positive.",e),pc=e=>v("The life (%s) must be strictly positive.",e),bc=(e,t)=>v("The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).",{maturity:t,settlement:e}),vc=e=>v("The number_of_periods (%s) must be strictly positive.",e),yc=e=>v("The periods_by_year (%s) must be strictly positive.",e),wc=(e,t)=>v("The period (%(period)s) must be less than or equal life (%(life)s).",{period:e,life:t}),Ec=e=>v("The period (%s) must be strictly positive.",e),Sc=e=>v("The present_value (%s) must be strictly positive.",e),Cc=e=>v("The price (%s) must be strictly positive.",e),Tc=e=>v("The rate_guess (%s) must be strictly greater than -1.",e),Ic=e=>v("The rate (%s) must be positive or null.",e),xc=e=>v("The rate (%s) must be strictly positive.",e),Rc=e=>v("The redemption (%s) must be strictly positive.",e),Ac=e=>v("The salvage (%s) must be positive or null.",e),_c=(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),Dc=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 Nc(e){return![0,1,2,3,4].includes(e)}function Mc(e){return![1,2,4].includes(e)}function Vc(e,t,r){const n=Zt(e,r),o=Zt(t,r),s=Zt(e,r);return s.setFullYear(n.getFullYear()+1),o.getTime()<=s.getTime()}const Lc=[{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 kc={description:v("Converts year/month/day into a date."),args:[a("year (number)",v("The year component of the date.")),a("month (number)",v("The month component of the date.")),a("day (number)",v("The day component of the date."))],compute:function(e,t,r){let n=Math.trunc(kt(e,this.locale));const o=Math.trunc(kt(t,this.locale)),s=Math.trunc(kt(r,this.locale));if(n<0||n>9999)return new S(v("The year (%s) must be between 0 and 9999 inclusive.",n.toString()));n<1900&&(n+=1900);const i=pt(new Qe(n,o-1,s));return i<0?new S(v("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")):{value:i,format:this.locale.dateFormat}},isExported:!0},Uc={description:v("Calculates the number of days, months, or years between two dates."),args:[a("start_date (date)",v("The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.")),a("end_date (date)",v("The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.")),a("unit (string)",v("A text abbreviation for unit of time."),[{value:"Y",label:v("The number of whole years between start_date and end_date")},{value:"M",label:v("The number of whole months between start_date and end_date")},{value:"D",label:v("The number of days between start_date and end_date")},{value:"MD",label:v("The number of days between start_date and end_date after subtracting whole months")},{value:"YM",label:v("The number of whole months between start_date and end_date after subtracting whole years")},{value:"YD",label:v("The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart")}])],compute:function(e,t,r){const n=$t(r).toUpperCase();if(!Object.values(Pc).includes(n))return new S(((e,t)=>{const r=e.map(e=>`'${e}'`).join(", ");return v("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,r)})(Object.values(Pc),$t(r)));const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=mt(o),a=mt(s);if(s<o)return new S(v("start_date (%s) should be on or before end_date (%s).",i.toLocaleDateString(),a.toLocaleDateString()));switch(n){case Pc.WHOLE_YEARS:return It(i,a);case Pc.WHOLE_MONTHS:return Ct(i,a);case Pc.WHOLE_DAYS:return Tt(i,a);case Pc.MONTH_WITHOUT_WHOLE_YEARS:return Ct(i,a)-12*It(i,a);case Pc.DAYS_WITHOUT_WHOLE_MONTHS:let e=a.getDate()-i.getDate();if(e<0){e=vt(new Qe(a.getFullYear(),a.getMonth()-1,1))-Math.abs(e)}return e;case Pc.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return St(e,t,1)<1}(o,s))return Tt(i,a);const e=new Qe(i.getFullYear(),a.getMonth(),a.getDate());let t=Tt(i,e);return t<0&&(e.setFullYear(i.getFullYear()+1),t=Tt(i,e)),t}}},isExported:!0},Hc={description:v("Converts a date string to a date value."),args:[a("date_string (string)",v("The string representing the date."))],compute:function(e){const t=$t(e),r=gt(t,this.locale);return null===r?new S(v("The date_string (%s) cannot be parsed to date/time.",t.toString())):Math.trunc(r.value)},isExported:!0},Bc={description:v("Day of the month that a specific date falls on."),args:[a("date (string)",v("The date from which to extract the day."))],compute:function(e){return Zt(e,this.locale).getDate()},isExported:!0},zc={description:v("Number of days between two dates."),args:[a("end_date (date)",v("The end of the date range.")),a("start_date (date)",v("The start of the date range."))],compute:function(e,t){const r=Zt(e,this.locale),n=Zt(t,this.locale),o=r.getTime()-n.getTime();return Math.round(o/et)},isExported:!0},$c=!1,Gc={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:$c}){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=St(n,o,qt(r)?4:0);return Math.sign(o-n)*Math.round(360*s)},isExported:!0},Wc={description:v("Date a number of months before/after another date."),args:[a("start_date (date)",v("The date from which to calculate the result.")),a("months (number)",v("The number of months before (negative) or after (positive) 'start_date' to calculate."))],compute:function(e,t){return{value:pt(wt(Zt(e,this.locale),Math.trunc(kt(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},qc={description:v("Last day of a month before or after a date."),args:[a("start_date (date)",v("The date from which to calculate the result.")),a("months (number)",v("The number of months before (negative) or after (positive) 'start_date' to consider."))],compute:function(e,t){const r=Zt(e,this.locale),n=Math.trunc(kt(t,this.locale)),o=r.getFullYear(),s=r.getMonth();return{value:pt(new Qe(o,s+n+1,0)),format:this.locale.dateFormat}},isExported:!0},Zc={description:v("Hour component of a specific time."),args:[a("time (date)",v("The time from which to calculate the hour component."))],compute:function(e){return Zt(e,this.locale).getHours()},isExported:!0},Yc={description:v("ISO week number of the year."),args:[a("date (date)",v("The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number."))],compute:function(e){const t=Zt(e,this.locale),r=t.getFullYear();let n=1;for(;4!==new Qe(r,0,n).getDay();)n+=1;const o=new Qe(r,0,n-3);let s=31;for(;4!==new Qe(r,11,s).getDay();)s-=1;const i=new Qe(r,11,s+3);let a,l;switch(a=o.getTime()<=t.getTime()?t.getTime()<=i.getTime()?0:1:-1,a){case 0:l=o;break;case 1:l=new Qe(r,11,s+3+1);break;case-1:let e=1;for(;4!==new Qe(r-1,0,e).getDay();)e+=1;l=new Qe(r-1,0,e-3)}const c=(t.getTime()-l.getTime())/et;return Math.floor(c/7)+1},isExported:!0},jc={description:v("Minute component of a specific time."),args:[a("time (date)",v("The time from which to calculate the minute component."))],compute:function(e){return Zt(e,this.locale).getMinutes()},isExported:!0},Xc={description:v("Month of the year a specific date falls in"),args:[a("date (date)",v("The date from which to extract the month."))],compute:function(e){return Zt(e,this.locale).getMonth()+1},isExported:!0},Kc={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 eu.compute.bind(this)(e,t,{value:1},r)},isExported:!0};function Qc(e){const t=e?.value;if("string"==typeof t){Ir(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 Ir(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 Jc=[{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")}],eu={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."),Jc),a("holidays (date, range<date>, optional)",v("A range or array constant containing the dates to consider as holidays."))],compute:function(e,t,r={value:1},n){const o=Zt(e,this.locale),s=Zt(t,this.locale),i=Qc(r),a=new Set;void 0!==n&&Xt([n],e=>{const t=Zt(e,this.locale);a.add(t.getTime())});const l=o.getTime()>s.getTime(),c=Qe.fromTimestamp((l?o:s).getTime()),u=Qe.fromTimestamp((l?s:o).getTime()),h=c.getTime();let d=u.getTime(),f=0;for(;d<=h;)i.includes(u.getDay())||a.has(d)||(f+=1),u.setDate(u.getDate()+1),d=u.getTime();return l?-f:f},isExported:!0},tu={description:v("Current date and time as a date value."),args:[],compute:function(){const e=Qe.now(),t=e.getTime()-Je.getTime(),r=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/et)+r,format:tc(this.locale)}},isExported:!0},ru={description:v("Minute component of a specific time."),args:[a("time (date)",v("The time from which to calculate the second component."))],compute:function(e){return Zt(e,this.locale).getSeconds()},isExported:!0},nu={description:v("Converts hour/minute/second into a time."),args:[a("hour (number)",v("The hour component of the time.")),a("minute (number)",v("The minute component of the time.")),a("second (number)",v("The second component of the time."))],compute:function(e,t,r){let n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=Math.trunc(kt(r,this.locale));return o+=Math.floor(s/60),s=s%60+(s<0?60:0),n+=Math.floor(o/60),o=o%60+(o<0?60:0),n%=24,n<0?new S(v("The function [[FUNCTION_NAME]] result cannot be negative")):{value:n/24+o/1440+s/86400,format:this.locale.timeFormat}},isExported:!0},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=$t(e),r=gt(t,this.locale);if(null===r)return new S(v("The time_string (%s) cannot be parsed to date/time.",t));const n=r.value-Math.trunc(r.value);return n<0?1+n:n},isExported:!0},su={description:v("Current date as a date value."),args:[],compute:function(){const e=Qe.now();return{value:pt(new Qe(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},iu={description:v("Day of the week of the date provided (as number)."),args:[a("date (date)",v("The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),a("type (number, default=1)",v("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."),[{value:1,label:v("Numbers 1 (Sunday) trough 7 (Saturday)")},{value:2,label:v("Numbers 1 (Monday) trough 7 (Sunday)")},{value:3,label:v("Numbers 0 (Monday) trough 6 (Sunday)")},{value:11,label:v("Numbers 1 (Monday) trough 7 (Sunday)")},{value:12,label:v("Numbers 1 (Tuesday) trough 7 (Monday)")},{value:13,label:v("Numbers 1 (Wednesday) trough 7 (Tuesday)")},{value:14,label:v("Numbers 1 (Thursday) trough 7 (Wednesday)")},{value:15,label:v("Numbers 1 (Friday) trough 7 (Thursday)")},{value:16,label:v("Numbers 1 (Saturday) trough 7 (Friday)")},{value:17,label:v("Numbers 1 (Sunday) trough 7 (Saturday)")}])],compute:function(e,t={value:1}){const r=Zt(e,this.locale),n=Math.round(kt(t,this.locale)),o=r.getDay();if(!(1<=n&&n<=3||11<=n&&n<=17))return new S(v("The type (%s) must be between 1 and 3 or between 11 and 17.",n));switch(n){case 1:return o+1;case 2:return 0===o?7:o;case 3:return 0===o?6:o-1}const s=(o+1-(n-10)+7)%7;return 0===s?7:s},isExported:!0},au={description:v("Week number of the year."),args:[a("date (date)",v("The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),a("type (number, default=1)",v("A number representing the day that a week starts on. Sunday = 1."),[{value:1,label:v("Sunday")},{value:2,label:v("Monday")},{value:11,label:v("Monday")},{value:12,label:v("Tuesday")},{value:13,label:v("Wednesday")},{value:14,label:v("Thursday")},{value:15,label:v("Friday")},{value:16,label:v("Saturday")},{value:17,label:v("Sunday")},{value:21,label:v("ISO week number (Monday as first day of the week)")}])],compute:function(e,t={value:1}){const r=Zt(e,this.locale),n=Math.round(kt(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(n))return new S(v("The type (%s) is out of range.",n.toString()));if(21===n)return Yc.compute.bind(this)(e);let o;o=1===n||2===n?n-1:n-10==7?0:n-10;const s=r.getFullYear();let i=1,a=new Qe(s,0,i);for(;a.getDay()!==o;)i+=1,a=new Qe(s,0,i);const l=(r.getTime()-a.getTime())/et;return l<0?1:Math.floor(l/7)+(1===i?1:2)},isExported:!0},lu={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 cu.compute.bind(this)(e,t,{value:1},r)},isExported:!0},cu={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."),Jc),a("holidays (date, range<date>, optional)",v("A range or array constant containing the dates to consider holidays."))],compute:function(e,t,r={value:1},n){const o=Zt(e,this.locale),s=Math.trunc(kt(t,this.locale));if("1111111"===r.value)return new S(v("The weekend must be different from '1111111'."));const i=Qc(r),a=new Set;void 0!==n&&Xt([n],e=>{const t=Zt(e,this.locale);a.add(t.getTime())});const l=Qe.fromTimestamp(o.getTime());let c=l.getTime();const u=Math.sign(s);let h=Math.abs(s);for(;h>0;)l.setDate(l.getDate()+u),c=l.getTime(),i.includes(l.getDay())||a.has(c)||(h-=1);const d=c-Je.getTime();return{value:Math.round(d/et),format:this.locale.dateFormat}},isExported:!0},uu={description:v("Year specified by a given date."),args:[a("date (date)",v("The date from which to extract the year."))],compute:function(e){return Zt(e,this.locale).getFullYear()},isExported:!0},hu={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."),Lc)],compute:function(e,t,r={value:0}){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=Math.trunc(kt(r,this.locale));return n<0?new S(v("The start_date (%s) must be positive or null.",n)):o<0?new S(v("The end_date (%s) must be positive or null.",o)):0>s||s>4?new S(v("The day_count_convention (%s) must be between 0 and 4 inclusive.",s)):St(n,o,s)}},du={description:v("First day of the month preceding a date."),args:[a("date (date)",v("The date from which to calculate the result."))],compute:function(e){const t=Zt(e,this.locale),r=t.getFullYear(),n=t.getMonth();return{value:pt(new Qe(r,n,1)),format:this.locale.dateFormat}}},fu={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 qc.compute.bind(this)(e,{value:0})}},gu={description:v("Quarter of the year a specific date falls in"),args:[a("date (date)",v("The date from which to extract the quarter."))],compute:function(e){return Math.ceil((Zt(e,this.locale).getMonth()+1)/3)}},mu={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=gu.compute.bind(this)(e),r=uu.compute.bind(this)(e);return{value:pt(new Qe(r,3*(t-1),1)),format:this.locale.dateFormat}}},pu={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=gu.compute.bind(this)(e),r=uu.compute.bind(this)(e);return{value:pt(new Qe(r,3*t,0)),format:this.locale.dateFormat}}},bu={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=uu.compute.bind(this)(e);return{value:pt(new Qe(t,0,1)),format:this.locale.dateFormat}}},vu={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=uu.compute.bind(this)(e);return{value:pt(new Qe(t+1,0,0)),format:this.locale.dateFormat}}};var yu=Object.freeze({__proto__:null,DATE:kc,DATEDIF:Uc,DATEVALUE:Hc,DAY:Bc,DAYS:zc,DAYS360:Gc,EDATE:Wc,EOMONTH:qc,HOUR:Zc,ISOWEEKNUM:Yc,MINUTE:jc,MONTH:Xc,MONTH_END:fu,MONTH_START:du,NETWORKDAYS:Kc,NETWORKDAYS_INTL:eu,NOW:tu,QUARTER:gu,QUARTER_END:pu,QUARTER_START:mu,SECOND:ru,TIME:nu,TIMEVALUE:ou,TODAY:su,WEEKDAY:iu,WEEKNUM:au,WORKDAY:lu,WORKDAY_INTL:cu,YEAR:uu,YEARFRAC:hu,YEAR_END:vu,YEAR_START:bu});const wu={description:v("Compare two numeric values, returning 1 if they're equal."),args:[a("number1 (number)",v("The first number to compare.")),a("number2 (number, default=0)",v("The second number to compare."))],compute:function(e,t={value:0}){return kt(e,this.locale)===kt(t,this.locale)?1:0},isExported:!0};var Eu,Su=Object.freeze({__proto__:null,DELTA:wu});!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(Eu||(Eu={}));const Cu=[Eu.number,Eu.error,Eu.text,Eu.boolean];function Tu(e){const t="asc"===e?1:-1;return(e,r)=>{if(e.type===Eu.empty)return r.type===Eu.empty?0:1;if(r.type===Eu.empty)return-1;let n=Cu.indexOf(e.type)-Cu.indexOf(r.type);return 0===n&&(n=e.type===Eu.text||e.type===Eu.error?e.value.localeCompare(r.value):e.value-r.value),t*n}}function Iu(e,t,...r){for(let e=0;e<r.length;e++){const t=e%2==0?"sort_column":"is_ascending";Ir(void 0!==r[e],v("Value for parameter %s is missing in [[FUNCTION_NAME]].",t))}const n=[],o=[],s=e.length;for(let i=0;i<r.length;i+=2){n.push(qt(Vr(r[i+1])?.value)?"asc":"desc");const a=r[i];if(O(a)&&(a.length>1||a[0].length>1))Ir(1===a.length&&a[0].length===s,v("Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.",`sort_column${i+1}`,s,a.length,a[0].length)),o.push(a.flat().map(e=>e.value));else{const r=kt(Vr(a)?.value,t);if(r<1||r>e[0].length)return e;o.push(e.map(e=>e[r-1].value))}}if(0===o.length)for(let t=0;t<e[0].length;t++)o.push(e.map(e=>e[t].value)),n.push("asc");const i={desc:Tu("desc"),asc:Tu("asc")},a=le(0,e.length);return a.sort((e,t)=>{for(const[r,s]of o.entries()){const o=s[e],a=s[t],l={value:o,type:null===o?Eu.empty:"string"==typeof o?Eu.text:typeof o},c={value:a,type:null===a?Eu.empty:"string"==typeof a?Eu.text:typeof a},u=i[n[r]](l,c);if(0!==u)return u}return 0}),a.map(t=>e[t])}const xu={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("condition1 (boolean, range<boolean>)",v("A column or row containing true or false values corresponding to the first column or row of range.")),a("condition2 (boolean, range<boolean>, repeating)",v("Additional column or row containing true or false values."))],compute:function(e,...t){let r=mr(e);const n=t.map(e=>nr(mr(e),e=>e.value));for(const e of n)if(!Rr(e))return new S(v("The arguments condition must be a single column or row."));if(!Ar(...t))return new S(v("The arguments conditions must have the same dimensions."));const o=n.map(e=>e.flat()),s=1===n[0].length?"row":"col";if(r="row"===s?or(r):r,o.some(e=>e.length!==r.length))return new S(v("FILTER has mismatched sizes on the range and conditions."));const i=[];for(let e=0;e<r.length;e++){const t=r[e];o.every(t=>("boolean"==typeof t[e]||"number"==typeof t[e])&&t[e])&&i.push(t)}return i.length?"row"===s?or(i):i:new x(v("No match found in FILTER evaluation"))},isExported:!1},Ru={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)",v("The index of the column in range or a range outside of range containing the values by which to sort.")),a("is_ascending (boolean, repeating)",v("TRUE or FALSE indicating whether to sort sort_column in ascending order."),[{value:!0,label:v("Ascending")},{value:!1,label:v("Descending")}])],compute:function(e,...t){const r=or(e);return or(Iu(r,this.locale,...t))},isExported:!0},Au={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)",v("The index of the column in range or a range outside of range containing the values by which to sort.")),a("is_ascending (boolean, repeating)",v("TRUE or FALSE indicating whether to sort sort_column in ascending order."),[{value:!0,label:v("Ascending")},{value:!1,label:v("Descending")}])],compute:function(e,t,...r){const n=kt(t?.value??1,this.locale),o=r.length%2==0?0:kt(r[0]?.value,this.locale),s=r.length%2==0?r:r.slice(1);if(n<0)return new S(v("Wrong value of 'n'. Expected a positive number. Got %s.",n));if(o<0||o>3)return new S(v("Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.",o));const i=Iu(or(e),this.locale,...s),a=(e,t)=>JSON.stringify(i[e].map(e=>e.value))===JSON.stringify(i[t].map(e=>e.value));switch(o){case 0:return or(i.slice(0,n));case 1:for(let e=n;e<i.length;e++)if(!a(e,n-1))return or(i.slice(0,e));return or(i);case 2:{const e=[i[0]];for(let t=1;t<i.length;t++)for(let r=0;r<t&&!a(t,r);r++)r===t-1&&e.push(i[t]);return or(e.slice(0,n))}case 3:{const e=[i[0]];let t=1;for(let r=1;r<i.length&&(a(r,r-1)||t++,!(t>n));r++)e.push(i[r]);return or(e)}}},isExported:!1},_u={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(!O(e))return[[e]];const n=qt(t?.value)||!1,o=qt(r?.value)||!1;n||(e=or(e));const s=new Map;for(const t of e){const e=JSON.stringify(t.map(e=>e.value)),r=s.get(e);r?r.count++:s.set(e,{data:t,count:1})}const i=[];for(const e of s.values())o&&e.count>1||i.push(e.data);return i.length?n?i:or(i):new S(v("No unique values found"))},isExported:!0};var Ou=Object.freeze({__proto__:null,FILTER:xu,SORT:Ru,SORTN:Au,UNIQUE:_u});const Du=[{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")}],Nu=[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)."),Du),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Lc)];function Mu(e,t,r,n,o=1e-10,s){let i,a,l,c,u=r,h=!1,d=0;do{l=e(u),isNaN(l)?(Ir(d<n&&void 0!==s,v("Function [[FUNCTION_NAME]] didn't find any result.")),d++,u=s(c),c=u):(i=u-l/t(u),a=Math.abs(i-u),u=i,h=a<o||Math.abs(l)<o,Ir(d<n,v("Function [[FUNCTION_NAME]] didn't find any result.")),d++)}while(!h);return u}const Vu={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."),Lc)],compute:function(e,t,r,n,o={value:0}){const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(n,this.locale),l=kt(r,this.locale),c=Math.trunc(kt(o,this.locale));if(s<0)return new S((e=>v("The issue (%s) must be positive or null.",e))(s));if(s>=i)return new S(bc(s,i));if(Nc(c))return new S(ic(c));if(a<=0)return new S(Rc(a));if(l<=0)return new S(xc(l));return a*l*St(s,i,c)},isExported:!0},Lu={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."),Lc)],compute:function(e,t,r,n,o,s,i={value:0}){i=i||0;const a=kt(e,this.locale),l=Math.trunc(kt(t,this.locale)),c=Math.trunc(kt(r,this.locale)),u=kt(n,this.locale),h=kt(o,this.locale),d=kt(s,this.locale),f=Math.trunc(kt(i,this.locale));if(a<=0)return new S((e=>v("The cost (%s) must be strictly positive.",e))(a));if(l<0)return new S((e=>v("The purchase_date (%s) must be positive or null.",e))(l));if(u<0)return new S(Ac(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(xc(d));if(Nc(f))return new S(ic(f));if(l>c)return new S(((e,t)=>v("The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).",{purchaseDate:e,firstPeriodEnd:t}))(l,c));const g=h<1&&h>0?1:Math.trunc(h),m=a*d,p=St(l,c,f),b=l===c?m:m*p,y=a-b-m*g;return y>=u?0===g?b:m:u-y<m?m-(u-y):0},isExported:!0},Pu={description:v("Days in coupon period containing settlement date."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));if(1===a){const o=zu.compute.bind(this)(e,t,r,n).value;return kt(Hu.compute.bind(this)(e,t,r,n).value,this.locale)-kt(o,this.locale)}return(3===a?365:360)/i},isExported:!0},ku={description:v("Days from settlement until next coupon."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));const l=kt(zu.compute.bind(this)(e,t,r,n).value,this.locale);if([1,2,3].includes(a))return o-l;if(4===a){const e=St(l,o,a);return Math.round(360*e)}const c=Zt(o,this.locale),u=Zt(l,this.locale),h=u.getFullYear(),d=c.getFullYear(),f=u.getMonth()+1,g=c.getMonth()+1;let m=u.getDate(),p=c.getDate();return 2===f&&2===g&&yt(u)&&yt(c)&&(p=30),31!==p||30!==m&&31!==m||(p=30),2===f&&yt(u)&&(m=30),31===m&&(m=30),360*(d-h)+30*(g-f)+(p-m)},isExported:!0},Uu={description:v("Days from settlement until next coupon."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));const l=kt(Hu.compute.bind(this)(e,t,r,n).value,this.locale);if([1,2,3].includes(a))return l-o;if(4===a){const e=St(o,l,a);return Math.round(360*e)}const c=ku.compute.bind(this)(e,t,r,n);return kt(Pu.compute.bind(this)(e,t,r,n),this.locale)-kt(c,this.locale)},isExported:!0},Hu={description:v("Next coupon date after the settlement date."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));const l=12/i,c=Bu.compute.bind(this)(e,t,r,n);return{value:pt(wt(Zt(s,this.locale),-(kt(c,this.locale)-1)*l,!0)),format:this.locale.dateFormat}},isExported:!0},Bu={description:v("Number of coupons between settlement and maturity."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));let l=1,c=s;const u=12/i;for(;c>o;)c=pt(wt(Zt(c,this.locale),-u,!1)),l++;return l-1},isExported:!0},zu={description:v("Last coupon date prior to or on the settlement date."),args:Nu,compute:function(e,t,r,n={value:0}){n=n||0;const o=Math.trunc(kt(e,this.locale)),s=Math.trunc(kt(t,this.locale)),i=Math.trunc(kt(r,this.locale)),a=Math.trunc(kt(n,this.locale));if(o>=s)return new S(bc(o,s));if(Mc(i))return new S(sc(i));if(Nc(a))return new S(ic(a));const l=12/i,c=Bu.compute.bind(this)(e,t,r,n);return{value:pt(wt(Zt(s,this.locale),-c*l,!0)),format:this.locale.dateFormat}},isExported:!0},$u={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,n,o,s={value:0}){const i=kt(n,this.locale),a=kt(o,this.locale),l=kt(e,this.locale),c=kt(r,this.locale),u=kt(t,this.locale),h=qt(s)?1:0;if(u<=0)return new S(vc(u));if(i<=0)return new S(dc(i));if(a<=0)return new S(mc(a));if(i>a)return new S(hc(i,a));if(a>u)return new S(gc(a,u));if(l<=0)return new S(xc(l));if(c<=0)return new S(Sc(c));let d=0;for(let e=i;e<=a;e++)d+=nh(l,e,u,c,0,h);return d},isExported:!0},Gu={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,n,o,s={value:0}){const i=kt(n,this.locale),a=kt(o,this.locale),l=kt(e,this.locale),c=kt(r,this.locale),u=kt(t,this.locale),h=qt(s)?1:0;if(u<=0)return new S(vc(u));if(i<=0)return new S(dc(i));if(a<=0)return new S(mc(a));if(i>a)return new S(hc(i,a));if(a>u)return new S(gc(a,u));if(l<=0)return new S(xc(l));if(c<=0)return new S(Sc(c));let d=0;for(let e=i;e<=a;e++)d+=ph(l,e,u,c,0,h);return d},isExported:!0},Wu={description:v("Depreciation via declining balance method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("period (number)",v("The single period within life for which to calculate depreciation.")),a("month (number, optional)",v("The number of months in the first year of depreciation."))],compute:function(e,t,r,n,...o){const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=Math.trunc(kt(n,this.locale)),c=o.length?Math.trunc(kt(o[0],this.locale)):12,u=a+(12===c?0:1);if(s<0)return new S(oc(s));if(i<0)return new S(Ac(i));if(l<=0)return new S(Ec(l));if(a<=0)return new S(pc(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},qu="#,##0.00",Zu={description:v("Depreciation via double-declining balance method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("period (number)",v("The single period within life for which to calculate depreciation.")),a("factor (number, default=2)",v("The factor by which depreciation decreases."))],compute:function(e,t,r,n,o={value:2}){const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=kt(o,this.locale);if(s<0)return new S(oc(s));if(i<0)return new S(Ac(i));if(l<=0)return new S(Ec(l));if(a<=0)return new S(pc(a));if(l>a)return new S(wc(l,a));if(c<=0)return new S(ac(c));if(0===s||i>=s)return{value:0,format:qu};const u=c/a;if(u>1)return{value:1===l?s-i:0,format:qu};if(l<=1)return{value:s*u,format:qu};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:qu}},isExported:!0},Yu={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."),Lc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(bc(s,i));if(Nc(c))return new S(ic(c));if(a<=0)return new S(Cc(a));if(l<=0)return new S(Rc(l));return(l-a)/l/St(s,i,c)},isExported:!0},ju={description:v("Convert a decimal fraction to decimal value."),args:[a("fractional_price (number)",v("The price quotation given using fractional decimal conventions.")),a("unit (number)",v("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));if(n<=0)return new S(Oc(n));const o=Math.trunc(r);return o+(r-o)*(10**Math.ceil(Math.log10(n))/n)},isExported:!0},Xu={description:v("Convert a decimal value to decimal fraction."),args:[a("decimal_price (number)",v("The price quotation given as a decimal value.")),a("unit (number)",v("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));if(n<=0)return new S(Oc(n));const o=Math.trunc(r);return o+(r-o)*(n/10**Math.ceil(Math.log10(n)))},isExported:!0},Ku={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)."),Du),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Lc)],compute:function(e,t,r,n,o,s={value:0}){const i=Math.trunc(kt(e,this.locale)),a=Math.trunc(kt(t,this.locale)),l=kt(r,this.locale),c=kt(n,this.locale),u=Math.trunc(kt(o,this.locale)),h=Math.trunc(kt(s,this.locale));if(i>=a)return new S(bc(i,a));if(Mc(u))return new S(sc(u));if(Nc(h))return new S(ic(h));if(l<0)return new S(Ic(l));if(c<0)return new S(Dc(c));const d=St(i,a,h),f=d-Math.trunc(d)||1/u,g=Math.ceil(d*u),m=l/u,p=c/u;let b=0,v=0;for(let e=1;e<=g;e++){const t=(m+(e===g?1:0))/(1+p)**e;v+=(f+(e-1)/u)*t,b+=t}return 0===b?0:v/b},isExported:!0},Qu={description:v("Annual effective interest rate."),args:[a("nominal_rate (number)",v("The nominal interest rate per year.")),a("periods_per_year (number)",v("The number of compounding periods per year."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));return r<=0?new S(v("The nominal_rate (%s) must be strictly positive.",r)):n<=0?new S(yc(n)):Math.pow(1+r/n,n)-1},isExported:!0};function Ju(e,t,r,n,o){return 0===e?-(n+r*t):-n*(1+e)**t-r*(1+e*o)*((1+e)**t-1)/e}const eh={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,n={value:0},o={value:0}){n=n||0,o=o||0;return{value:Ju(kt(e,this.locale),kt(t,this.locale),kt(r,this.locale),kt(n,this.locale),qt(o)?1:0),format:"#,##0.00"}},isExported:!0},th={description:v("Future value of principal from series of rates."),args:[a("principal (number)",v("The amount of initial capital or value to compound against.")),a("rate_schedule (number, range<number>)",v("A series of interest rates to compound against the principal."))],compute:function(e,t){return Jt([t],(e,t)=>e*(1+kt(t,this.locale)),kt(e,this.locale))},isExported:!0},rh={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."),Lc)],compute:function(e,t,r,n,o={value:0}){const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(n,this.locale),l=kt(r,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(bc(s,i));if(l<=0)return new S(fc(l));if(a<=0)return new S(Rc(a));if(Nc(c))return new S(ic(c));return(a-l)/l/St(s,i,c)},isExported:!0};function nh(e,t,r,n,o,s){return gh(e,r,n,o,s)-ph(e,t,r,n,o,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,n,o={value:0},s={value:0}){return{value:nh(kt(e,this.locale),kt(t,this.locale),kt(r,this.locale),kt(n,this.locale),kt(o,this.locale),qt(s)?1:0),format:"#,##0.00"}},isExported:!0},sh={description:v("Internal rate of return given periodic cashflows."),args:[a("cashflow_amounts (number, range<number>)",v("An array or range containing the income or payments associated with the investment.")),a("rate_guess (number, default=0.1)",v("An estimate for what the internal rate of return will be."))],compute:function(e,t={value:.1}){const r=kt(t,this.locale);if(r<=-1)return new S(Tc(r));let n=!1,o=!1;const s=[];if(Kt([e],({value:e})=>{e>0&&(n=!0),e<0&&(o=!0),s.push(e)},this.locale),!n||!o)return new S(nc);const i=s.shift();return{value:Mu(function(e){return function(e,t,r){const n=r.length;let o=0;return r.reduce((t,r)=>(o++,t+r*e**(n-o)),t*e**n)}(e,i,s)},function(e){return function(e,t,r){const n=r.length;let o=0;return r.reduce((t,r)=>(o++,t+r*(n-o)*e**(n-o-1)),t*n*e**(n-1))}(e,i,s)},r+1,20,1e-5)-1,format:"0%"}},isExported:!0},ih={description:v("Returns the interest paid at a particular period of an investment."),args:[a("rate (number)",v("The interest rate.")),a("period (number)",v("The period for which you want to view the interest payment.")),a("number_of_periods (number)",v("The number of payments to be made.")),a("present_value (number)",v("The current value of the annuity."))],compute:function(e,t,r,n){const o=kt(e,this.locale),s=kt(t,this.locale),i=kt(r,this.locale),a=kt(n,this.locale);if(0===i)return new S(v("The number_of_periods (%s) must be different from zero.",i));return-1*(a-a*(s/i))*o},isExported:!0},ah={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)."),Du),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."))],compute:function(e,t,r,n,o,s={value:0}){const i=Ku.compute.bind(this)(e,t,r,n,o,s),a=kt(n,this.locale),l=Math.trunc(kt(o,this.locale));return kt(i,this.locale)/(1+a/l)},isExported:!0},lh={description:v("Modified internal rate of return."),args:[a("cashflow_amounts (range<number>)",v("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),a("financing_rate (number)",v("The interest rate paid on funds invested.")),a("reinvestment_return_rate (number)",v("The return (as a percentage) earned on reinvestment of income received from the investment."))],compute:function(e,t,r){const n=kt(t,this.locale),o=kt(r,this.locale),s=or(e).flat().filter(e=>null!==e.value).map(e=>kt(e,this.locale)),i=s.length;let a=0,l=0;for(const e of le(0,i)){const t=s[e];t>=0?a+=t*(o+1)**(i-e-1):l+=t/(n+1)**e}if(0===l||0===a)return new S(nc);return(-a/l)**(1/(i-1))-1},isExported:!0},ch={description:v("Annual nominal interest rate."),args:[a("effective_rate (number)",v("The effective interest rate per year.")),a("periods_per_year (number)",v("The number of compounding periods per year."))],compute:function(e,t){const r=kt(e,this.locale),n=Math.trunc(kt(t,this.locale));return r<=0?new S(v("The effective_rate (%s) must be strictly positive.",r)):n<=0?new S(yc(n)):(Math.pow(r+1,1/n)-1)*n},isExported:!0},uh={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,n={value:0},o={value:0}){n=n||0,o=o||0;const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=qt(o)?1:0;if(0===s)return-(l+a)/i;const u=i*(1+s*c)/s;return Math.log((u-l)/(a+u))/Math.log(1+s)},isExported:!0};function hh(e,t,r,n){let o=0;return er(r,(t,r)=>(o++,t+r/(1+e)**o),t,n)}const dh={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("cashflow1 (number, range<number>)",v("The first future cash flow.")),a("cashflow2 (number, range<number>, repeating)",v("Additional future cash flows."))],compute:function(e,...t){const r=kt(e,this.locale);return-1===r?new S((e=>v("The discount (%s) must be different from -1.",e))(r)):{value:hh(r,0,t,this.locale),format:"#,##0.00"}},isExported:!0},fh={description:v("Computes the number of periods needed for an investment to reach a value."),args:[a("rate (number)",v("The rate at which the investment grows each period.")),a("present_value (number)",v("The investment's current value.")),a("future_value (number)",v("The investment's desired future value."))],compute:function(e,t,r){const n=kt(e,this.locale),o=kt(t,this.locale),s=kt(r,this.locale);return n<=0?new S(xc(n)):o<=0?new S(Sc(o)):s<=0?new S(v("The future_value (%s) must be strictly positive.",s)):(Math.log(s)-Math.log(o))/Math.log(1+n)},isExported:!0};function gh(e,t,r,n,o){if(t<=0)throw new S(vc(t));if(0===e)return-(n+r)/t;let s=-(r*(1+e)**t+n);return s=s*e/((1+e*o)*((1+e)**t-1)),s}const mh={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,n={value:0},o={value:0}){const s=kt(t,this.locale),i=kt(e,this.locale),a=qt(o)?1:0,l=kt(n,this.locale);return{value:gh(i,s,kt(r,this.locale),l,a),format:"#,##0.00"}},isExported:!0};function ph(e,t,r,n,o,s){if(r<=0)throw new S(vc(r));if(t<=0||t>r)throw new S(v("The period must be between 1 and number_of_periods (%s)",r));const i=gh(e,r,n,o,s);if(1===s&&1===t)return i;return i+-Ju(e,0===s?t-1:t-2,i,n+i*s,0)*e}const bh={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,n,o={value:0},s={value:0}){const i=kt(r,this.locale),a=kt(e,this.locale),l=kt(t,this.locale),c=qt(s)?1:0,u=kt(o,this.locale);return{value:ph(a,l,i,kt(n,this.locale),u,c),format:"#,##0.00"}},isExported:!0},vh={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,n={value:0},o={value:0}){n=n||0,o=o||0;const s=kt(e,this.locale),i=kt(t,this.locale),a=kt(r,this.locale),l=kt(n,this.locale),c=qt(o)?1:0;return{value:s?-(a*(1+s*c)*((1+s)**i-1)/s+l)/(1+s)**i:-(l+a*i),format:"#,##0.00"}},isExported:!0},yh={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)."),Du),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Lc)],compute:function(e,t,r,n,o,s,i={value:0}){i=i||0;const a=Math.trunc(kt(e,this.locale)),l=Math.trunc(kt(t,this.locale)),c=kt(r,this.locale),u=kt(n,this.locale),h=kt(o,this.locale),d=Math.trunc(kt(s,this.locale)),f=Math.trunc(kt(i,this.locale));if(a>=l)return new S(bc(a,l));if(Mc(d))return new S(sc(d));if(Nc(f))return new S(ic(f));if(c<0)return new S(Ic(c));if(u<0)return new S(Dc(u));if(h<=0)return new S(Rc(h));const g=St(a,l,f)*d,m=Math.ceil(g),p=g-Math.floor(g)||1,b=1+u/d,v=100*c/d;if(1===m)return(v+h)/(p*u/d+1)-v*(1-p);let y=0;for(let e=1;e<=m;e++)y+=v/b**(e-1+p);return h/b**(m-1+p)+y-v*(1-p)},isExported:!0},wh={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."),Lc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(bc(s,i));if(Nc(c))return new S(ic(c));if(a<=0)return new S(lc(a));if(l<=0)return new S(Rc(l));return l-a*l*St(s,i,c)},isExported:!0},Eh={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."),Lc)],compute:function(e,t,r,n,o,s={value:0}){s=s||0;const i=Math.trunc(kt(e,this.locale)),a=Math.trunc(kt(t,this.locale)),l=Math.trunc(kt(r,this.locale)),c=kt(n,this.locale),u=kt(o,this.locale),h=Math.trunc(kt(s,this.locale));if(i<=l)return new S(((e,t)=>v("The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).",{settlement:e,issue:t}))(i,l));if(i>=a)return new S(bc(i,a));if(Nc(h))return new S(ic(h));if(c<0)return new S(Ic(c));if(u<0)return new S(Dc(u));const d=St(i,a,h),f=St(i,l,h);return(100+St(l,a,h)*c*100)/(1+d*u)-f*c*100},isExported:!0},Sh=.1,Ch={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,n={value:0},o={value:0},s={value:Sh}){const i=kt(e,this.locale),a=kt(t,this.locale),l=qt(o)?1:0,c=kt(s,this.locale)||Sh;let u=kt(n,this.locale),h=kt(r,this.locale);if(i<=0)return new S(vc(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(Tc(c));u-=a*l,h+=a*l;return{value:Mu(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},Th={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."),Lc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(bc(s,i));if(Nc(c))return new S(ic(c));if(a<=0)return new S(fc(a));if(l<=0)return new S(lc(l));return a/(1-l*St(s,i,c))},isExported:!0},Ih={description:v("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[a("number_of_periods (number)",v("The number of periods.")),a("present_value (number)",v("The present value of the investment.")),a("future_value (number)",v("The future value of the investment."))],compute:function(e,t,r){const n=kt(e,this.locale),o=kt(t,this.locale),s=kt(r,this.locale);return n<=0?new S(vc(n)):(s/o)**(1/n)-1},isExported:!0},xh={description:v("Depreciation of an asset using the straight-line method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated."))],compute:function(e,t,r){return{value:(kt(e,this.locale)-kt(t,this.locale))/kt(r,this.locale),format:"#,##0.00"}},isExported:!0},Rh={description:v("Depreciation via sum of years digit method."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("period (number)",v("The single period within life for which to calculate depreciation."))],compute:function(e,t,r,n){const o=kt(e,this.locale),s=kt(t,this.locale),i=kt(r,this.locale),a=kt(n,this.locale);if(a<=0)return new S(Ec(a));if(i<=0)return new S(pc(i));if(a>i)return new S(wc(a,i));return{value:(i-a+1)/(i*(i+1)/2)*(o-s),format:"#,##0.00"}},isExported:!0};function Ah(e,t,r){return 100*(1-r*St(e,t,2))}const _h={description:v("Price of a US Treasury bill."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("discount (number)",v("The discount rate of the bill at time of purchase."))],compute:function(e,t,r){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=kt(r,this.locale);return n>=o?new S(bc(n,o)):Vc(n,o,this.locale)?s<=0?new S(lc(s)):s>=1?new S(cc(s)):Ah(n,o,s):new S(_c(n,o))},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 n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=kt(r,this.locale);if(n>=o)return new S(bc(n,o));if(!Vc(n,o,this.locale))return new S(_c(n,o));if(s<=0)return new S(lc(s));if(s>=1)return new S(cc(s));const i=zc.compute.bind(this)({value:o},{value:n});if(i<=182)return 365*s/(360-s*i);const a=Ah(n,o,s)/100,l=i/(366===i?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},Dh={description:v("The yield of a US Treasury bill based on price."),args:[a("settlement (date)",v("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),a("maturity (date)",v("The maturity or end date of the security, when it can be redeemed at face, or par value.")),a("price (number)",v("The price at which the security is bought per 100 face value."))],compute:function(e,t,r){const n=Math.trunc(kt(e,this.locale)),o=Math.trunc(kt(t,this.locale)),s=kt(r,this.locale);if(n>=o)return new S(bc(n,o));if(!Vc(n,o,this.locale))return new S(_c(n,o));if(s<=0)return new S(Cc(s));return(100-s)/s*(1/St(n,o,2))},isExported:!0},Fh=!1,Nh={description:v("Variable declining balance. WARNING : does not handle decimal periods."),args:[a("cost (number)",v("The initial cost of the asset.")),a("salvage (number)",v("The value of the asset at the end of depreciation.")),a("life (number)",v("The number of periods over which the asset is depreciated.")),a("start (number)",v("Starting period to calculate depreciation.")),a("end (number)",v("Ending period to calculate depreciation.")),a("factor (number, default=2)",v("The number of months in the first year of depreciation.")),a("no_switch (number, default=false)",v("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."),[{value:!1,label:v("Switch to straight-line depreciation")},{value:!0,label:v("Do not switch to straight-line depreciation")}])],compute:function(e,t,r,n,o,s={value:2},i={value:Fh}){s=s||0;const a=kt(e,this.locale),l=kt(t,this.locale),c=kt(r,this.locale),u=Math.trunc(kt(n,this.locale)),h=Math.trunc(kt(o,this.locale)),d=kt(s,this.locale),f=qt(i);if(a<0)return new S(oc(a));if(l<0)return new S(Ac(l));if(c<=0)return new S(pc(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(ac(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},Mh={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:Sh}){const n=kt(r,this.locale);if(!Ar(e,t))return new S(rc);const o=e.flat().map(e=>kt(e,this.locale)),s=t.flat().map(e=>kt(e,this.locale));if(!Fc(o))return new S(nc);if(s.some(e=>e<s[0]))return new S(uc(s[0]));if(n<=-1)return new S(Tc(n));const i=new Map;for(const e of le(0,s.length)){const t=s[e];i.has(t)?i.set(t,i.get(t)+o[e]):i.set(t,o[e])}const a=Array.from(i.keys()),l=a.map(e=>i.get(e));return Mu(e=>{let t=l[0];for(const r of le(1,l.length)){const n=(a[0]-a[r])/365;t+=l[r]*(1+e)**n}return t},e=>{let t=0;for(const r of le(1,l.length)){const n=(a[0]-a[r])/365;t+=n*l[r]*(1+e)**(n-1)}return t},n,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},Vh={description:v("Net present value given to non-periodic cash flows.."),args:[a("discount (number)",v("The discount rate of the investment over one period.")),a("cashflow_amounts (number, range<number>)",v("An range containing the income or payments associated with the investment.")),a("cashflow_dates (number, range<number>)",v("An range with dates corresponding to the cash flows in cashflow_amounts."))],compute:function(e,t,r){const n=kt(e,this.locale);if(!Ar(t,r))return new S(rc);const o=mr(t).flat().map(e=>Ht(e,this.locale)),s=mr(r).flat().map(e=>Ht(e,this.locale));if(s.some(e=>e<s[0]))return new S(uc(s[0]));if(n<=0)return new S(xc(n));if(1===o.length)return o[0];const i=new Map;for(const e of le(0,s.length)){const t=s[e];i.has(t)?i.set(t,i.get(t)+o[e]):i.set(t,o[e])}const a=Array.from(i.keys()),l=a.map(e=>i.get(e));let c=l[0];for(const e of le(1,l.length)){const t=(a[0]-a[e])/365;c+=l[e]*(1+n)**t}return c},isExported:!0},Lh={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)."),Du),a("day_count_convention (number, default=0 )",v("An indicator of what day count method to use."),Lc)],compute:function(e,t,r,n,o,s,i={value:0}){i=i||0;const a=Math.trunc(kt(e,this.locale)),l=Math.trunc(kt(t,this.locale)),c=kt(r,this.locale),u=kt(n,this.locale),h=kt(o,this.locale),d=Math.trunc(kt(s,this.locale)),f=Math.trunc(kt(i,this.locale));if(a>=l)return new S(bc(a,l));if(Mc(d))return new S(sc(d));if(Nc(f))return new S(ic(f));if(c<0)return new S(Ic(c));if(u<=0)return new S(Cc(u));if(h<=0)return new S(Rc(h));const g=St(a,l,f)*d,m=Math.ceil(g),p=g-Math.floor(g)||1,b=100*c/d;if(1===m){const e=u+b*(1-p);return(h+b-e)*d*(1/p)/e}const v=Mu(function(e){return function(e,t,r,n,o,s){let i=s-(e+o*(1-t))*n**(r-1+t);for(let e=1;e<=r;e++)i+=o*n**(e-1);return i}(u,p,m,e,b,h)},function(e){return function(e,t,r,n,o){let s=-(e+o*(1-t))*(r-1+t)*n**(r-2+t);for(let e=1;e<=r;e++)s+=o*(e-1)*n**(e-2);return s}(u,p,m,e,b)},1+(c+1)/d,100,1e-5);return(v-1)*d},isExported:!0},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."),Lc)],compute:function(e,t,r,n,o={value:0}){o=o||0;const s=Math.trunc(kt(e,this.locale)),i=Math.trunc(kt(t,this.locale)),a=kt(r,this.locale),l=kt(n,this.locale),c=Math.trunc(kt(o,this.locale));if(s>=i)return new S(bc(s,i));if(Nc(c))return new S(ic(c));if(a<=0)return new S(Cc(a));if(l<=0)return new S(Rc(l));return(l/a-1)/St(s,i,c)},isExported:!0},kh={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."),Lc)],compute:function(e,t,r,n,o,s={value:0}){s=s||0;const i=Math.trunc(kt(e,this.locale)),a=Math.trunc(kt(t,this.locale)),l=Math.trunc(kt(r,this.locale)),c=kt(n,this.locale),u=kt(o,this.locale),h=Math.trunc(kt(s,this.locale));if(i>=a)return new S(bc(i,a));if(Nc(h))return new S(ic(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(Ic(c));if(u<=0)return new S(Cc(u));return(100*(1+c*St(l,a,h))/(u+100*c*St(l,i,h))-1)/St(i,a,h)},isExported:!0};var Uh=Object.freeze({__proto__:null,ACCRINTM:Vu,AMORLINC:Lu,COUPDAYBS:ku,COUPDAYS:Pu,COUPDAYSNC:Uu,COUPNCD:Hu,COUPNUM:Bu,COUPPCD:zu,CUMIPMT:$u,CUMPRINC:Gu,DB:Wu,DDB:Zu,DISC:Yu,DOLLARDE:ju,DOLLARFR:Xu,DURATION:Ku,EFFECT:Qu,FV:eh,FVSCHEDULE:th,INTRATE:rh,IPMT:oh,IRR:sh,ISPMT:ih,MDURATION:ah,MIRR:lh,NOMINAL:ch,NPER:uh,NPV:dh,PDURATION:fh,PMT:mh,PPMT:bh,PRICE:yh,PRICEDISC:wh,PRICEMAT:Eh,PV:vh,RATE:Ch,RECEIVED:Th,RRI:Ih,SLN:xh,SYD:Rh,TBILLEQ:Oh,TBILLPRICE:_h,TBILLYIELD:Dh,VDB:Nh,XIRR:Mh,XNPV:Vh,YIELD:Lh,YIELDDISC:Ph,YIELDMAT:kh});const Hh=[{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.')}],Bh={description:v("Gets information about a cell."),args:[a("info_type (string)",v("The type of information requested."),Hh),a("reference (meta, range<meta>)",v("The reference to the cell."))],compute:function(e,t){const r=$t(e).toLowerCase();if(!Hh.map(e=>e.value).includes(r))return new S(v("The info_type should be one of %s.",Hh.join(", ")));const n=this.__originSheetId,o=t[0][0].value;let{sheetName:s,xc:i}=go(o);s=s===this.getters.getSheetName(n)?void 0:s;const a=mo(s,bo(i,"colrow")),l=this.getters.getRangeFromSheetXC(n,a);switch(r){case"address":return this.getters.getRangeString(l,n);case"col":return l.zone.left+1;case"contents":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top};return this.getters.getEvaluatedCell(e).value}case"format":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top};return this.getters.getEvaluatedCell(e).format||""}case"row":return l.zone.top+1;case"type":{const e={sheetId:l.sheetId,col:l.zone.left,row:l.zone.top},t=this.getters.getEvaluatedCell(e).type;return t===Eu.empty?"b":t===Eu.text?"l":"v"}}return""},isExported:!0},zh={description:v("Whether a value is an error other than #N/A."),args:[a("value (any)",v("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return Vt(t)&&t!==w.NotAvailable},isExported:!0},$h={description:v("Whether a value is an error."),args:[a("value (any)",v("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return Vt(t)},isExported:!0},Gh={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},Wh={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},qh={description:v("Whether a value is non-textual."),args:[a("value (any)",v("The value to be checked."))],compute:function(e){return!Yh.compute.bind(this)(e)},isExported:!0},Zh={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},Yh={description:v("Whether a value is text."),args:[a("value (any)",v("The value to be verified as text."))],compute:function(e){return"string"==typeof e?.value&&!1===Vt(e?.value)},isExported:!0},jh={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},Xh={description:v("Returns the error value #N/A."),args:[],compute:function(){return{value:w.NotAvailable}},isExported:!0};var Kh=Object.freeze({__proto__:null,CELL:Bh,ISBLANK:jh,ISERR:zh,ISERROR:$h,ISLOGICAL:Gh,ISNA:Wh,ISNONTEXT:qh,ISNUMBER:Zh,ISTEXT:Yh,NA:Xh});function Qh(e){let t=!1,r=!0;return ir(e,e=>(t=!0,r=r&&e,r)),{foundBoolean:t,result:r}}function Jh(e){let t=!1,r=!1;return ir(e,e=>(t=!0,r=r||e,!r)),{foundBoolean:t,result:r}}const ed={description:v("Logical `and` operator."),args:[a("logical_expression1 (boolean, range<boolean>)",v("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),a("logical_expression2 (boolean, range<boolean>, repeating)",v("More expressions that represent logical values."))],compute:function(...e){const{result:t,foundBoolean:r}=Qh(e);return r?t:new S(vr)},isExported:!0},td={description:v("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},rd={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(Pr(e))return sr(rd.compute,[e,t,r]);return(qt(Vr(e))?t:r)??{value:0}},isExported:!0},nd={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(Pr(e))return sr(nd.compute,[e,t]);return(Vt(Vr(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(Pr(e))return sr(od.compute,[e,t]);return(Vr(e)?.value===w.NotAvailable?t:e)??{value:0}},isExported:!0},sd={description:v("Returns a value depending on multiple logical expressions."),args:[a("condition1 (boolean, range<boolean>)",v("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),a("value1 (any, range)",v("The returned value if condition1 is TRUE.")),a("condition2 (boolean, any, range, repeating)",v("Additional conditions to be evaluated if the previous ones are FALSE.")),a("value2 (any, range, repeating)",v("Additional values to be returned if their corresponding conditions are 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(Pr(e[0]))return sr(sd.compute,e);const t=qt(Vr(e.shift())),r=e.shift();if(t)return r??{value:0}}return new S(v("No match."))},isExported:!0},id={description:v("Returns opposite of provided logical value."),args:[a("logical_expression (boolean)",v("An expression or reference to a cell holding an expression that represents some logical value."))],compute:function(e){return!qt(e)},isExported:!0},ad={description:v("Logical `or` operator."),args:[a("logical_expression1 (boolean, range<boolean>)",v("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),a("logical_expression2 (boolean, range<boolean>, repeating)",v("More expressions that evaluate to logical values."))],compute:function(...e){const{result:t,foundBoolean:r}=Jh(e);return r?t:new S(vr)},isExported:!0},ld={description:v("Returns a value by comparing cases to an expression."),args:[a("expression (number, boolean, string)",v("The value to be checked.")),a("case1 (number, boolean, string)",v("The first case to be checked against expression.")),a("value1 (any)",v("The corresponding value to be returned if case1 matches expression.")),a("case2 (any, repeating)",v("Additional cases to try if the previous ones don't match expression.")),a("value2 (any, repeating)",v("Additional values to be returned if their corresponding cases match expression.")),a('default (any, default="empty")',v("An optional default value to be returned if none of the cases match expression."))],compute:function(e,...t){const r=t.length%2==0?Lt(e):t.pop();for(let r=0;r<t.length;r+=2){const n=t[r];if(n&&Vt(n.value))return n;if(e?.value===n?.value)return t[r+1]||{value:0}}return r||{value:0}},isExported:!0},cd={description:v("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},ud={description:v("Logical `xor` operator."),args:[a("logical_expression1 (boolean, range<boolean>)",v("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),a("logical_expression2 (boolean, range<boolean>, repeating)",v("More expressions that evaluate to logical values."))],compute:function(...e){let t=!1,r=!1;return ir(e,e=>(t=!0,r=r?!e:e,!0)),t?r:new S(vr)},isExported:!0};var hd=Object.freeze({__proto__:null,AND:ed,FALSE:td,IF:rd,IFERROR:nd,IFNA:od,IFS:sd,NOT:id,OR:ad,SWITCH:ld,TRUE:cd,XOR:ud});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("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 dd={DateIs:{today:v("today"),yesterday:v("yesterday"),tomorrow:v("tomorrow"),lastWeek:v("in the past week"),lastMonth:v("in the past month"),lastYear:v("in the past year")},DateIsBefore:{today:v("today"),yesterday:v("yesterday"),tomorrow:v("tomorrow"),lastWeek:v("one week ago"),lastMonth:v("one month ago"),lastYear:v("one year ago")},CriterionError:{notEmptyValue:v("The value must not be empty"),numberValue:v("The value must be a number"),dateValue:v("The value must be a date"),validRange:v("The value must be a valid range"),validFormula:v("The formula must be valid")},Errors:{InvalidRange:v("The range is invalid."),InvalidDataValidationCriterionValue:v("One or more of the provided criteria values are invalid. Please review and correct them."),InvalidNumberOfCriterionValues:v("One or more of the provided criteria values are missing."),Unexpected:v("The rule is invalid for an unknown reason.")}};v("The table zone is invalid for an unknown reason"),v("You cannot create overlapping tables."),v("A table can only be created on a continuous selection."),v("The range is invalid"),v("The range is out of the sheet"),v("Filter button"),v("Header row(s)"),v("Banded rows"),v("First column"),v("Last column"),v("Banded columns"),v("Automatically autofill formulas"),v("Total row"),v("Auto-adjust to formula result"),v("Cannot have filters without a header row"),v("For tables based on array formulas only"),v("No calculations"),v("% of grand total"),v("% of column total"),v("% of row total"),v("% of"),v("% of parent row total"),v("% of parent column total"),v("% of parent total"),v("Difference from"),v("% difference from"),v("Running total"),v("% Running total"),v("Rank smallest to largest"),v("Rank largest to smallest"),v("Index"),v("Displays the value that is entered in the field."),v("Displays values as a percentage of the grand total of all the values or data points in the report."),v("Displays all the values in each column or series as a percentage of the total for the column or series."),v("Displays the value in each row or category as a percentage of the total for the row or category."),v("Displays values as a percentage of the value of the Base item in the Base field."),v("Calculates values as follows:\n(value for the item) / (value for the parent item on rows)"),v("Calculates values as follows:\n(value for the item) / (value for the parent item on columns)"),v("Calculates values as follows:\n(value for the item) / (value for the parent item of the selected Base field)"),v("Displays values as the difference from the value of the Base item in the Base field."),v("Displays values as the percentage difference from the value of the Base item in the Base field."),v("Displays the value for successive items in the Base field as a running total."),v("Calculates the value as a percentage for successive items in the Base field that are displayed as a running total."),v("Displays the rank of selected values in a specific field, listing the smallest item in the field as 1, and each larger value with a higher rank value."),v("Displays the rank of selected values in a specific field, listing the largest item in the field as 1, and each smaller value with a higher rank value."),v("Calculates values as follows:\n((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row Total) x (Grand Column Total))");class fd{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 gd=new fd;function md(e){return gd.get(e)}const pd={normalizeFunctionValue:e=>kt(e,Dl),toValueAndFormat:(e,t)=>({value:kt(e,Dl),format:"dd mmm yyyy"}),toFunctionValue(e){const t=Zt(e,Dl);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},bd={normalizeFunctionValue(e){const t=kt(e,Dl);if(t<1||t>31)throw new S(v("%s is not a valid day of month (it should be a number between 1 and 31)",t));return t},toValueAndFormat:e=>({value:kt(e,Dl),format:"0"}),toFunctionValue:e=>`${e}`},vd={normalizeFunctionValue(e){const t=kt(e,Dl);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||Dl).weekStart)%7;return{value:Dn[r].toString(),format:"@"}},toFunctionValue:e=>`${e}`},yd={normalizeFunctionValue(e){const t=kt(e,Dl);if(t<0||t>53)throw new S(v("%s is not a valid week (it should be a number between 0 and 53)",t));return t},toValueAndFormat:e=>({value:kt(e,Dl),format:"0"}),toFunctionValue:e=>`${e}`},wd={normalizeFunctionValue(e){const t=kt(e,Dl);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:On[kt(e,Dl)-1].toString(),format:"@"}),toFunctionValue:e=>`${e}`},Ed={normalizeFunctionValue:e=>Fn(kt(e,Dl),{locale:Dl,format:"mm/yyyy"}),toValueAndFormat:e=>({value:kt(e,Dl),format:"mmmm yyyy"}),toFunctionValue(e){const t=Zt(e,Dl);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`}},Sd={normalizeFunctionValue(e){const t=kt(e,Dl);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}`},Cd={normalizeFunctionValue(e){const t=kt(e,Dl);return t>3e3?Zt(t,Dl).getFullYear():t},toValueAndFormat:e=>({value:kt(e,Dl),format:"0"}),toFunctionValue:e=>`${e}`},Td={normalizeFunctionValue(e){const t=kt(e,Dl);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}`},Id={normalizeFunctionValue(e){const t=kt(e,Dl);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}`},xd={normalizeFunctionValue(e){const t=kt(e,Dl);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 Rd(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)}}gd.add("day",Rd(pd)).add("year",Rd(Cd)).add("day_of_month",Rd(bd)).add("iso_week_number",Rd(yd)).add("month_number",Rd(wd)).add("month",Rd(Ed)).add("quarter_number",Rd(Sd)).add("day_of_week",Rd(vd)).add("hour_number",Rd(Td)).add("minute_number",Rd(Id)).add("second_number",Rd(xd));const Ad={displayTotals:!0,displayColumnHeaders:!0,displayMeasuresRow:!0,numberOfRows:Number.MAX_VALUE,numberOfColumns:Number.MAX_VALUE},_d={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"],Dd={integer:Od,char:Od,datetime:Od,boolean:["count_distinct","count","bool_and","bool_or"]},Fd={};for(const e in Dd){Fd[e]={};for(const t of Dd[e])Fd[e][t]=_d[t]}const Nd={count:e=>({value:Zi([e]),format:"0"}),count_distinct:e=>({value:As([e]),format:"0"}),bool_and:e=>({value:Qh([e]).result}),bool_or:e=>({value:Jh([e]).result}),max:(e,t)=>Yi([e],t),min:(e,t)=>ji([e],t),avg:(e,t)=>({value:qi([e],t),format:Mt(e)}),sum:(e,t)=>({value:Rs([e],t),format:Mt(e)})};function Md(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 Vd=["date","datetime"];function Ld(e){const[t,r]=e.split(":");return r?{fieldName:t,granularity:r}:{fieldName:t}}function Pd(e,t,r){const n=[e];r&&n.push(`"${r}"`);for(const{field:e,value:r,type:o}of t){if("measure"===e){n.push('"measure"',`"${r}"`);continue}const{granularity:t}=Ld(e),s=Bd(r,{type:o,granularity:t});n.push(`"${e}"`,s)}return n}function kd(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 Ud(e,t){if(null===t||"null"===t)return null;const r="object"==typeof t?t.value:t;if(Vt(r))return r;if("custom"===e.type)return Yt(t)??null;const n="boolean"==typeof t?$t(t).toLocaleLowerCase():$t(t);if("null"===n)return null;if(!$d.contains(e.type))throw new S(v("Field %(field)s is not supported because of its type (%(type)s)",{field:e.displayName,type:e.type}));if("false"===n.toLowerCase())return!1;return $d.get(e.type)(n,e.granularity)}function Hd(e,t){return md(t??"month").normalizeFunctionValue(e)}function Bd(e,t){return null===e?'"null"':Gd.contains(t.type)?Gd.get(t.type)(e,t.granularity):`"${e}"`}function zd(e,t){return md(t??"month").toFunctionValue(e)}const $d=new fd;$d.add("date",Hd).add("datetime",Hd).add("integer",e=>kt(e,Dl)).add("boolean",e=>qt(e)).add("char",e=>$t(e)).add("custom",e=>e);const Gd=new fd;function Wd(e,t){return 0===e.length?t:{...t,format:(t.format||"@")+"* "}}function qd(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 Zd(e,t){const r=t.model.getters.getPivotCellFromPosition(e),n=t.model.getters.getPivotIdFromPosition(e);if(!n||"HEADER"!==r.type)return;const o=t.model.getters.getPivotCoreDefinition(n),s=o.collapsedDomains?.[r.dimension]?[...o.collapsedDomains[r.dimension]]:[],i=s.findIndex(e=>Ae(e,r.domain));-1!==i?s.splice(i,1):s.push(r.domain);const a=o.collapsedDomains?{...o.collapsedDomains}:{COL:[],ROW:[]};a[r.dimension]=s,t.model.dispatch("UPDATE_PIVOT",{pivotId:n,pivot:{...o,collapsedDomains:a}})}function Yd(e,t,r,n,o,s,i){const a=e.style;return{numberOfRows:void 0!==t?kt(t,i):a?.numberOfRows??Ad.numberOfRows,numberOfColumns:void 0!==o?kt(o,i):a?.numberOfColumns??Ad.numberOfColumns,displayTotals:void 0!==r?qt(r):a?.displayTotals??Ad.displayTotals,displayColumnHeaders:void 0!==n?qt(n):a?.displayColumnHeaders??Ad.displayColumnHeaders,displayMeasuresRow:void 0!==s?qt(s):a?.displayMeasuresRow??Ad.displayMeasuresRow}}function jd(e,t){const r=t.getPivotId(e);if(!r)throw new S(v('There is no pivot with id "%s"',e));return r}function Xd(e){if(e.length%2!=0)throw new S(v("Function PIVOT takes an even number of arguments."))}function Kd(e,t,r){const n=[];if("SPREADSHEET"===t.type&&t.dataSet){const{sheetId:r,zone:o}=t.dataSet,s=Go(o),i=e.getters.getRangeFromSheetXC(r,s);if(void 0===i||i.invalidXc||i.invalidSheetName)throw new I;if(e.__originCellPosition&&i.sheetId===e.__originSheetId&&Jo(ss(e.__originCellPosition),o))throw new T;n.push(i)}for(const t of r)if(t.computedBy){const r=e.getters.getMeasureCompiledFormula(t);n.push(...r.dependencies.filter(e=>!e.invalidXc))}const o=e.__originCellPosition;o&&n.length&&(e.updateDependencies?.(o),e.addDependencies?.(o,n))}Gd.add("date",zd).add("datetime",zd).add("integer",e=>`${kt(e,Dl)}`).add("boolean",e=>qt(e)?"TRUE":"FALSE").add("char",e=>`"${$t(e).replace(/"/g,'\\"')}"`).add("custom",e=>"string"==typeof e?`"${e}"`:String(e));const Qd=!0,Jd=[{value:!0,label:v("A1 style (default)")},{value:!1,label:v("R1C1 style")}],ef=[{value:!0,label:v("Approximate match (default)")},{value:!1,label:v("Exact match")}],tf={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."),Jd),a("sheet (string, optional)",v("A string indicating the name of the sheet into which the address points."))],compute:function(e,t,r={value:1},n={value:!0},o){const s=zt(e,this.locale),i=zt(t,this.locale);if(s<1)return new S(Or(s));if(i<1)return new S(Or(i));const a=zt(r,this.locale);if(![1,2,3,4].includes(a))return new S((l=4,c=a,v("The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.",1..toString(),l.toString(),c.toString())));var l,c;let u;if(qt(n)){u=Do(i-1,s-1,{rowFixed:[1,2].includes(a),colFixed:[1,3].includes(a)})}else{u=([1,2].includes(a)?`R${s}`:`R[${s}]`)+([1,3].includes(a)?`C${i}`:`C[${i}]`)}return void 0!==o?mo($t(o),u):u},isExported:!0},rf={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:rr(e.length,1,(e,r)=>({value:t+e+1}))},isExported:!0},nf={description:v("Number of columns in a specified array or range."),args:[a("range (any, range<any>)",v("The range whose column count will be returned."))],compute:function(e){const t=mr(e);return void 0===t[0][0]?new S(v("The range is out of bounds.")):t[0][0].value===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."),ef)],compute:function(e,t,r,n={value:Qd}){const o=Math.trunc(kt(r?.value,this.locale)),s=mr(t);if(1>o||o>s[0].length)return new S(v("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const i=(e,t)=>e[t][0].value,a=s[qt(n.value)?hr(s,e,"nextSmaller","asc",s.length,i):dr(s,e,"wildcard",s.length,i,this.lookupCaches)];return void 0===a?Lt(e):a[o-1]},isExported:!0},sf={description:v("Returns the content of a cell, specified by row and column offset."),args:[a("reference (any, range)",v("The range of cells from which the values are returned.")),a("row (number, default=0)",v("The index of the row to be returned from within the reference range of cells.")),a("column (number, default=0)",v("The index of the column to be returned from within the reference range of cells."))],compute:function(e,t={value:0},r={value:0}){const n=mr(e),o=kt(t.value,this.locale),s=kt(r.value,this.locale);return s<0||s-1>=n.length||o<0||o-1>=n[0].length?new S(v("Index out of range.")):0===o&&0===s?n:0===o?[n[s-1]]:0===s?n.map(e=>[e[o-1]]):n[s-1][o-1]},isExported:!0},af={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)."),Jd)],compute:function(e,t={value:!0}){const r=e?.value?.toString();if(!r)return new I(v("Reference should be defined."));if(!qt(t))return new S(v("R1C1 notation is not supported."));const n=this.__originSheetId,o=this.__originCellPosition;o&&this.updateDependencies?.(o);const s=this.getters.getRangeFromSheetXC(n,r);if(void 0===s||s.invalidXc||s.invalidSheetName)return new I;o&&this.addDependencies?.(o,[s]);const i=[];for(let e=s.zone.left;e<=s.zone.right;e++){const t=[];for(let r=s.zone.top;r<=s.zone.bottom;r++){const n={sheetId:s.sheetId,col:e,row:r};t.push(this.getters.getEvaluatedCell(n))}i.push(t)}return 1===i.length&&1===i[0].length?i[0][0]:i},isExported:!0},lf={description:v("Look up a value."),args:[a("search_key (string, number, boolean)",v("The value to search for. For example, 42, 'Cats', or I24.")),a("search_array (any, range)",v("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")),a("result_range (any, range, optional)",v("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method."))],compute:function(e,t,r){const n=mr(t),o=mr(r);let s=n.length,i=n[0].length;const a=i>=s,l=a?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=hr(n,e,"nextSmaller","asc",a?i:s,l);return-1===c||a&&void 0===n[0][c]||!a&&void 0===n[c][i-1]?Lt(e):0===o[0].length?a?n[s-1][c]:n[c][i-1]:(s=o.length,i=o[0].length,1!==s&&1!==i?new S(v("The result_range must be a single row or a single column.")):s>1?c>s-1?new S(v("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",c+1)):o[c][0]:c>i-1?new S(v("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",c+1)):o[0][c])},isExported:!0},cf={description:v("Position of item in range that matches value."),args:[a("search_key (string, number, boolean)",v("The value to search for. For example, 42, 'Cats', or I24.")),a("range (any, range)",v("The one-dimensional array to be searched.")),a("search_type (number, default=1)",v("The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order."),[{value:1,label:v("Ascending order (default)")},{value:0,label:v("Exact match")},{value:-1,label:v("Descending order")}])],compute:function(e,t,r={value:1}){let n=kt(r,this.locale);const o=mr(t),s=o.length,i=o[0].length;if(1!==s&&1!==i)return new S(v("The range must be a single row or a single column."));let a=-1;const l=1===s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=1===s?o[0].length:o.length;switch(n=Math.sign(n),n){case 1:a=hr(o,e,"nextSmaller","asc",c,l);break;case 0:a=dr(o,e,"wildcard",c,l,this.lookupCaches);break;case-1:a=hr(o,e,"nextGreater","desc",c,l)}return 1===s&&void 0===o[0][a]||1!==s&&void 0===o[a]?Lt(e):a+1},isExported:!0},uf={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:rr(1,e[0].length,(e,r)=>({value:t+r+1}))},isExported:!0},hf={description:v("Number of rows in a specified array or range."),args:[a("range (any, range<any>)",v("The range whose row count will be returned."))],compute:function(e){const t=mr(e);return void 0===t[0][0]?new S(v("The range is out of bounds.")):t[0][0].value===w.InvalidReference?t[0][0]:t[0].length},isExported:!0},df={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."),ef)],compute:function(e,t,r,n={value:Qd}){const o=Math.trunc(kt(r?.value,this.locale)),s=mr(t);if(1>o||o>s.length)return new S(v("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const i=(e,t)=>e[0][t].value,a=qt(n.value)?hr(s,e,"nextSmaller","asc",s[0].length,i):dr(s,e,"wildcard",s[0].length,i,this.lookupCaches),l=s[o-1][a];return void 0===l?Lt(e):l},isExported:!0},ff={0:"strict",1:"nextGreater","-1":"nextSmaller",2:"wildcard"},gf={description:v("Search a range for a match and return the corresponding item from a second range."),args:[a("search_key (string,number,boolean)",v("The value to search for.")),a("lookup_range (any, range)",v("The range to consider for the search. Should be a single column or a single row.")),a("return_range (any, range)",v("The range containing the return value. Should have the same dimensions as lookup_range.")),a("if_not_found (any, optional)",v("If a valid match is not found, return this value.")),a("match_mode (any, default=0)",v("Specifies how to match search_key with the items in lookup_range. "),[{value:0,label:v("Exact match (default)")},{value:-1,label:v("Exact match or next smaller item")},{value:1,label:v("Exact match or next larger item")},{value:2,label:v("Wildcard character match")}]),a("search_mode (any, default=1)",v("Specifies the search mode to use. By default, a first to last search will be used."),[{value:1,label:v("Search first to last (default)")},{value:-1,label:v("Search last to first")},{value:2,label:v("Binary search (sorted ascending order)")},{value:-2,label:v("Binary search (sorted descending order)")}])],compute:function(e,t,r,n,o={value:0},s={value:1}){const i=Math.trunc(kt(o.value,this.locale)),a=Math.trunc(kt(s.value,this.locale)),l=mr(t),c=mr(r);if(1!==l.length&&1!==l[0].length)return new S(v("lookup_range should be either a single row or single column."));if(![1,-1,2,-2].includes(a))return new S(v("search_mode should be a value in [-1, 1, -2, 2]."));if(![-1,0,1,2].includes(i))return new S(v("match_mode should be a value in [-1, 0, 1, 2]."));const u=1===l.length?"col":"row";if(2===i&&[-2,2].includes(a))return new S(v("The search and match mode combination is not supported for XLOOKUP evaluation."));if("col"===u?c[0].length!==l[0].length:c.length!==l.length)return new S(v("return_range should have the same dimensions as lookup_range."));const h="col"===u?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,d="col"===u?l[0].length:l.length,f=ff[i],g=-1===a,m=2===a||-2===a?hr(l,e,f,2===a?"asc":"desc",d,h):dr(l,e,f,d,h,this.lookupCaches,g);return-1!==m?"col"===u?c.map(e=>[e[m]]):[c[m]]:void 0===n?Lt(e):[[n]]},isExported:!0},mf={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)",v("Field name.")),a("domain_value (number,string,boolean,repeating)",v("Value."))],compute:function(e,t,...r){const n=$t(e),o=$t(t),s=jd(n,this.getters);!function(e,t,r){const{measures:n}=r.getPivotCoreDefinition(e);if(!n.find(e=>e.id===t)){const e=`(${n.map(e=>e.id).join(", ")})`;throw new S(v("The argument %s is not a valid measure. Here are the measures: %s",t,e))}}(s,o,this.getters),Xd(r);const i=this.getters.getPivot(s),a=this.getters.getPivotCoreDefinition(s);Kd(this,a,a.measures.filter(e=>e.id===o)),i.init({reload:i.needsReevaluation});const l=i.assertIsValid({throwOnError:!1});if(l)return l;if(!i.areDomainArgsFieldsValid(r)){const e=v("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${n})`);return{value:w.GenericError,message:v("Dimensions don't match the pivot definition")+". "+e}}const c=i.parseArgsToPivotDomain(r);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(s)?.trackValue(o,c),i.getPivotCellValueAndFormat(o,c)}},pf={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)",v("Field name.")),a("domain_value (number,string,value,repeating)",v("Value."))],compute:function(e,...t){const r=$t(e),n=jd(r,this.getters);Xd(t);const o=this.getters.getPivot(n);Kd(this,this.getters.getPivotCoreDefinition(n),[]),o.init({reload:o.needsReevaluation});const s=o.assertIsValid({throwOnError:!1});if(s)return s;if(!o.areDomainArgsFieldsValid(t)){const e=v("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${r})`);return{value:w.GenericError,message:v("Dimensions don't match the pivot definition")+". "+e}}const i=o.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(n)?.trackHeader(i);const a=i.at(-1);if("measure"===a?.field)return o.getPivotMeasureValue($t(a.value),i);const{value:l,format:c}=o.getPivotHeaderValueAndFormat(i);return{value:l,format:a&&"measure"!==a.field&&"false"!==a.value?c:void 0}}},bf={description:v("Get a pivot table."),args:[a("pivot_id (string)",v("ID of the pivot.")),a("row_count (number, optional)",v("number of rows")),a("include_total (boolean, default=TRUE)",v("Whether to include total/sub-totals or not.")),a("include_column_titles (boolean, default=TRUE)",v("Whether to include the column titles or not.")),a("column_count (number, optional)",v("number of columns")),a("include_measure_titles (boolean, default=TRUE)",v("Whether to include the measure titles row or not."))],compute:function(e,t,r,n,o,s){const i=jd($t(e),this.getters),a=this.getters.getPivot(i),l=this.getters.getPivotCoreDefinition(i),c=Yd(l,t,r,n,o,s,this.locale);if(c.numberOfRows<0)return new S(v("The number of rows must be positive."));if(c.numberOfColumns<0)return new S(v("The number of columns must be positive."));Kd(this,l,l.measures),a.init({reload:a.needsReevaluation});const u=a.assertIsValid({throwOnError:!1});if(u)return u;const h=a.getCollapsedTableStructure();if(h.numberOfCells>1e5)return new S(function(e,t){const r=Fn(e,{format:"0,00",locale:t});return v("Oops—this pivot table is quite large (%s cells). Try simplifying it using the side panel.",r)}(h.numberOfCells,this.locale));const d=h.getPivotCells(c);let f=0;c.displayColumnHeaders&&(f=h.columns.length-1),c.displayMeasuresRow&&f++;const g=this.getters.getPivotName(i),m=Math.min(f+c.numberOfRows,d[0].length);if(0===m)return[[{value:g}]];const p=Math.min(1+c.numberOfColumns,d.length),b=[];for(const e of le(0,p)){b[e]=[];for(const t of le(0,m)){const r=d[e][t];switch(r.type){case"EMPTY":b[e].push({value:""});break;case"HEADER":const t=a.getPivotHeaderValueAndFormat(r.domain);b[e].push(Wd(r.domain,t));break;case"MEASURE_HEADER":b[e].push(a.getPivotMeasureValue(r.measure,r.domain));break;case"VALUE":b[e].push(a.getPivotCellValueAndFormat(r.measure,r.domain))}}}return(c.displayColumnHeaders||c.displayMeasuresRow)&&(b[0][0]={value:g}),b}},vf={description:v("Returns a range reference shifted by a specified number of rows and columns from a starting cell reference."),args:[a("cell_reference (meta, range<meta>)",v("The starting point from which to count the offset rows and columns.")),a("offset_rows (number)",v("The number of rows to offset by.")),a("offset_columns (number)",v("The number of columns to offset by.")),a("height (number, default='height of cell_reference')",v("The number of rows of the range to return starting at the offset target.")),a("width (number, default='width of cell_reference')",v("The number of columns of the range to return starting at the offset target."))],compute:function(e,t,r,n,o){if(Vt(e[0][0].value))return e[0][0];const s=e[0][0].value;if(!s)return new S("In this context, the function OFFSET needs to have a cell or range in parameter.");const i=Bo(s);let a=e[0].length,l=e.length;if(n){const e=kt(n,this.locale);if(e<1)return new S(v("Height value is %(_height)s. It should be greater than or equal to 1.",{_height:e}));a=e}if(o){const e=kt(o,this.locale);if(e<1)return new S(v("Width value is %(_width)s. It should be greater than or equal to 1.",{_width:e}));l=e}const{sheetName:c}=go(s),u=c&&this.getters.getSheetIdByName(c)||this.getters.getActiveSheetId(),h=kt(t,this.locale),d=kt(r,this.locale),f=this.__originCellPosition;f&&this.updateDependencies?.(f);const g=i.left+d,m=i.top+h;if(g<0||m<0)return new I(v("OFFSET evaluates to an out of bounds range."));const p={left:g,top:m,right:g+l-1,bottom:m+a-1},b=this.getters.getRangeFromZone(u,p);return b.invalidXc||b.invalidSheetName?new I:(f&&this.addDependencies?.(f,[b]),rr(l,a,(e,t)=>this.getters.getEvaluatedCell({sheetId:u,col:g+e,row:m+t})))}};var yf=Object.freeze({__proto__:null,ADDRESS:tf,COLUMN:rf,COLUMNS:nf,HLOOKUP:of,INDEX:sf,INDIRECT:af,LOOKUP:lf,MATCH:cf,OFFSET:vf,PIVOT:bf,PIVOT_HEADER:pf,PIVOT_VALUE:mf,ROW:uf,ROWS:hf,VLOOKUP:df,XLOOKUP:gf});const wf={description:v("Sum of two numbers."),args:[a("value1 (number)",v("The first addend.")),a("value2 (number)",v("The second addend."))],compute:function(e,t){return{value:kt(e,this.locale)+kt(t,this.locale),format:e?.format||t?.format}}},Ef={description:v("Concatenation of two values."),args:[a("value1 (string)",v("The value to which value2 will be appended.")),a("value2 (string)",v("The value to append to value1."))],compute:function(e,t){return $t(e)+$t(t)},isExported:!0},Sf={description:v("One number divided by another."),args:[a("dividend (number)",v("The number to be divided.")),a("divisor (number)",v("The number to divide by."))],compute:function(e,t){const r=kt(t,this.locale);return 0===r?new _(v("The divisor must be different from zero.")):{value:kt(e,this.locale)/r,format:e?.format||t?.format}}};function Cf(e){return void 0===e||null===e.value}const Tf={number:0,string:"",boolean:!1};function If(e,t,r=2e-16){return Math.abs(e-t)<r}const xf={description:v("Equal."),args:[a("value1 (string, number, boolean)",v("The first value.")),a("value2 (string, number, boolean)",v("The value to test against value1 for equality."))],compute:function(e,t){if(Vt(e?.value))return e;if(Vt(t?.value))return t;let r=Cf(e)?Tf[typeof t?.value]:e?.value,n=Cf(t)?Tf[typeof e?.value]:t?.value;return"string"==typeof r&&(r=r.toUpperCase()),"string"==typeof n&&(n=n.toUpperCase()),"number"==typeof r&&"number"==typeof n?{value:If(r,n)}:{value:r===n}}};function Rf(e,t,r){if(Vt(e?.value))return e;if(Vt(t?.value))return t;let n=Cf(e)?Tf[typeof t?.value]:e?.value,o=Cf(t)?Tf[typeof e?.value]:t?.value;"number"!=typeof n&&(n=$t(n).toUpperCase()),"number"!=typeof o&&(o=$t(o).toUpperCase());const s=typeof n,i=typeof o;return"string"===s&&"number"===i?{value:!0}:"string"===i&&"number"===s?{value:!1}:{value:r(n,o)}}const Af={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 Rf(e,t,(e,t)=>"number"==typeof e&&"number"==typeof t?!If(e,t)&&e>t:e>t)}},_f={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 Rf(e,t,(e,t)=>"number"==typeof e&&"number"==typeof t?If(e,t)||e>t:e>=t)}},Of={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=_f.compute.bind(this)(e,t);return Vt(r.value)?r:{value:!r.value}}},Df={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=Af.compute.bind(this)(e,t);return Vt(r.value)?r:{value:!r.value}}},Ff={description:v("Difference of two numbers."),args:[a("value1 (number)",v("The minuend, or number to be subtracted from.")),a("value2 (number)",v("The subtrahend, or number to subtract from value1."))],compute:function(e,t){return{value:kt(e,this.locale)-kt(t,this.locale),format:e?.format||t?.format}}},Nf={description:v("Product of two numbers"),args:[a("factor1 (number)",v("The first multiplicand.")),a("factor2 (number)",v("The second multiplicand."))],compute:function(e,t){return{value:kt(e,this.locale)*kt(t,this.locale),format:e?.format||t?.format}}},Mf={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=xf.compute.bind(this)(e,t);return Vt(r.value)?r:{value:!r.value}}},Vf={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 vi.compute.bind(this)(e,t)}},Lf={description:v("A number with the sign reversed."),args:[a("value (number)",v("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],compute:function(e){return{value:-kt(e,this.locale),format:e?.format}}},Pf={description:v("Value interpreted as a percentage."),args:[a("percentage (number)",v("The value to interpret as a percentage."))],compute:function(e){return kt(e,this.locale)/100}},kf={description:v("A specified number, unchanged."),args:[a("value (any)",v("The number to return."))],compute:function(e={value:null}){return e}};var Uf=Object.freeze({__proto__:null,ADD:wf,CONCAT:Ef,DIVIDE:Sf,EQ:xf,GT:Af,GTE:_f,LT:Of,LTE:Df,MINUS:Ff,MULTIPLY:Nf,NE:Mf,POW:Vf,UMINUS:Lf,UNARY_PERCENT:Pf,UPLUS:kf});const Hf=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),Bf={transform:e=>e,inverseTransform:e=>e},zf=1e-10,$f=.0254,Gf=$f/72,Wf=.3048,qf=.9144,Zf=1609.34,Yf=1852,jf=946073047258e4,Xf={g:{...Bf,category:"weight"},u:{...Hf(166053e-29),category:"weight"},grain:{...Hf(.0647989),category:"weight"},ozm:{...Hf(28.3495),category:"weight"},lbm:{...Hf(453.592),category:"weight"},stone:{...Hf(6350.29),category:"weight"},sg:{...Hf(14593.90294),category:"weight"},cwt:{...Hf(45359.237),category:"weight"},uk_cwt:{...Hf(50802.3),category:"weight"},ton:{...Hf(907184.74),category:"weight"},uk_ton:{...Hf(1016046.9),category:"weight"},m:{...Bf,category:"distance"},km:{...Hf(1e3),category:"distance"},ang:{...Hf(zf),category:"distance"},Picapt:{...Hf(Gf),category:"distance"},pica:{...Hf($f/6),category:"distance"},in:{...Hf($f),category:"distance"},ft:{...Hf(Wf),category:"distance"},yd:{...Hf(qf),category:"distance"},ell:{...Hf(1.143),category:"distance"},mi:{...Hf(Zf),category:"distance"},survey_mi:{...Hf(1609.34),category:"distance"},Nmi:{...Hf(Yf),category:"distance"},ly:{...Hf(jf),category:"distance"},parsec:{...Hf(0x6da012f95c9fd0),category:"distance"},sec:{...Bf,category:"time"},min:{...Hf(60),category:"time"},hr:{...Hf(3600),category:"time"},day:{...Hf(86400),category:"time"},yr:{...Hf(31556952),category:"time"},Pa:{...Bf,category:"pressure"},bar:{...Hf(1e5),category:"pressure"},mmHg:{...Hf(133.322),category:"pressure"},Torr:{...Hf(133.322),category:"pressure"},psi:{...Hf(6894.76),category:"pressure"},atm:{...Hf(101325),category:"pressure"},N:{...Bf,category:"force"},dyn:{...Hf(1e-5),category:"force"},pond:{...Hf(.00980665),category:"force"},lbf:{...Hf(4.44822),category:"force"},J:{...Bf,category:"energy"},eV:{...Hf(160218e-24),category:"energy"},e:{...Hf(1e-7),category:"energy"},flb:{...Hf(1.3558179483),category:"energy"},c:{...Hf(4.184),category:"energy"},cal:{...Hf(4.1868),category:"energy"},BTU:{...Hf(1055.06),category:"energy"},Wh:{...Hf(3600),category:"energy"},HPh:{...Hf(2684520),category:"energy"},W:{...Bf,category:"power"},PS:{...Hf(735.499),category:"power"},HP:{...Hf(745.7),category:"power"},T:{...Bf,category:"magnetism"},ga:{...Hf(1e-4),category:"magnetism"},K:{...Bf,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:{...Hf(5/9),category:"temperature"},Reau:{transform:e=>1.25*e+273.15,inverseTransform:e=>(e-273.15)/1.25,category:"temperature"},"m^3":{...Bf,category:"volume",order:3},"ang^3":{...Hf(Math.pow(zf,3)),category:"volume",order:3},"Picapt^3":{...Hf(Math.pow(Gf,3)),category:"volume",order:3},tsp:{...Hf(492892e-11),category:"volume"},tspm:{...Hf(5e-6),category:"volume"},tbs:{...Hf(14786764825785619e-21),category:"volume"},"in^3":{...Hf(Math.pow($f,3)),category:"volume",order:3},oz:{...Hf(295735295625e-16),category:"volume"},cup:{...Hf(237e-6),category:"volume"},pt:{...Hf(.0004731765),category:"volume"},uk_pt:{...Hf(568261e-9),category:"volume"},qt:{...Hf(.0009463529),category:"volume"},l:{...Hf(.001),category:"volume"},uk_qt:{...Hf(.0011365225),category:"volume"},gal:{...Hf(.0037854118),category:"volume"},uk_gal:{...Hf(.00454609),category:"volume"},"ft^3":{...Hf(Math.pow(Wf,3)),category:"volume",order:3},bushel:{...Hf(.0352390704),category:"volume"},barrel:{...Hf(.158987295),category:"volume"},"yd^3":{...Hf(Math.pow(qf,3)),category:"volume",order:3},MTON:{...Hf(1.13267386368),category:"volume"},GRT:{...Hf(2.83168),category:"volume"},"mi^3":{...Hf(Math.pow(Zf,3)),category:"volume",order:3},"Nmi^3":{...Hf(Math.pow(Yf,3)),category:"volume",order:3},"ly^3":{...Hf(Math.pow(jf,3)),category:"volume",order:3},"m^2":{...Bf,category:"area",order:2},"ang^2":{...Hf(Math.pow(zf,2)),category:"area",order:2},"Picapt^2":{...Hf(Math.pow(Gf,2)),category:"area",order:2},"in^2":{...Hf(Math.pow($f,2)),category:"area",order:2},"ft^2":{...Hf(Math.pow(Wf,2)),category:"area",order:2},"yd^2":{...Hf(Math.pow(qf,2)),category:"area",order:2},ar:{...Hf(100),category:"area"},Morgen:{...Hf(2500),category:"area"},uk_acre:{...Hf(4046.8564224),category:"area"},us_acre:{...Hf(4046.8726098743),category:"area"},ha:{...Hf(1e4),category:"area"},"mi^2":{...Hf(Math.pow(Zf,2)),category:"area",order:2},"Nmi^2":{...Hf(Math.pow(Yf,2)),category:"area",order:2},"ly^2":{...Hf(Math.pow(jf,2)),category:"area",order:2},bit:{...Bf,category:"information"},byte:{...Hf(8),category:"information"},"m/s":{...Bf,category:"speed"},"m/hr":{...Hf(1/3600),category:"speed"},"km/hr":{...Hf(1/3.6),category:"speed"},mph:{...Hf(.44704),category:"speed"},kn:{...Hf(.5144444444),category:"speed"},admkn:{...Hf(.5147733333),category:"speed"}},Kf={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"},Qf={"":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)},Jf={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")},eg=Object.entries(Xf).map(([e,t])=>({value:e,label:tg(t.category)}));function tg(e){return Jf[e]??""}function rg(e){for(const[t,r]of Object.entries(Qf)){if(t&&!e.startsWith(t))continue;const n=e.slice(t.length);let o=Xf[n];if(!o&&Kf[n]&&(o=Xf[Kf[n]]),o)return{...o,factor:o.order?Math.pow(r,o.order):r}}}const ng={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"),eg),a("end_unit (string)",v("The unit of measure into which to convert value"),eg)],compute:function(e,t,r){const n=kt(e,this.locale),o=$t(t),s=$t(r),i=rg(o),a=rg(s);return i?a?i.category!==a.category?{value:w.GenericError,message:v("Incompatible units of measure ('%s' vs '%s')",tg(i.category),tg(a.category))}:{value:a.inverseTransform(i.factor*i.transform(n))/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')",o)}},isExported:!0};var og=Object.freeze({__proto__:null,CONVERT:ng});const sg=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,ig=[{value:0,label:v("Case-sensitive (default)")},{value:1,label:v("Case-insensitive")}],ag=[{value:0,label:v("Don't match to end (default)")},{value:1,label:v("Match to end")}],lg={description:v("Gets character associated with number."),args:[a("table_number (number)",v("The number of the character to look up from the current Unicode table in decimal format."))],compute:function(e){const t=Math.trunc(kt(e,this.locale));return t<1?new S(v("The table_number (%s) is out of range.",t)):String.fromCharCode(t)},isExported:!0},cg={description:v("Remove non-printable characters from a piece of text."),args:[a("text (string)",v("The text whose non-printable characters are to be removed."))],compute:function(e){const t=$t(e);let r="";for(const e of t)e&&e.charCodeAt(0)>31&&(r+=e);return r},isExported:!0},ug={description:v("Appends strings to one another."),args:[a("string1 (string, range<string>)",v("The initial string.")),a("string2 (string, range<string>, repeating)",v("More strings to append in sequence."))],compute:function(...e){return Jt(e,(e,t)=>e+$t(t),"")},isExported:!0},hg={description:v("Tests whether two strings are identical."),args:[a("string1 (string)",v("The first string to compare.")),a("string2 (string)",v("The second string to compare."))],compute:function(e,t){return $t(e)===$t(t)},isExported:!0},dg={description:v("First position of string found in text, case-sensitive."),args:[a("search_for (string)",v("The string to look for within text_to_search.")),a("text_to_search (string)",v("The text to search for the first occurrence of search_for.")),a("starting_at (number, default=1)",v("The character within text_to_search at which to start the search."))],compute:function(e,t,r={value:1}){const n=$t(e),o=$t(t),s=kt(r,this.locale);if(""===o)return new S(v("The text_to_search must be non-empty."));if(s<1)return new S(v("The starting_at (%s) must be greater than or equal to 1.",s));const i=o.indexOf(n,s-1);return-1===i?new S(v("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",n,o)):i+1},isExported:!0},fg={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_array1 (string, range<string>)",v("The value or values to be appended using delimiter.")),a("value_or_array2 (string, range<string>, repeating)",v("More values to be appended using delimiter."))],compute:function(e,...t){const r=$t(e);return Jt(t,(e,t)=>(e?e+r:"")+$t(t),"")}},gg={description:v("Substring from beginning of specified string."),args:[a("text (string)",v("The string from which the left portion will be returned.")),a("number_of_characters (number, optional)",v("The number of characters to return from the left side of string."))],compute:function(e,...t){const r=t.length?kt(t[0],this.locale):1;return r<0?new S(v("The number_of_characters (%s) must be positive or null.",r)):$t(e).substring(0,r)},isExported:!0},mg={description:v("Length of a string."),args:[a("text (string)",v("The string whose length will be returned."))],compute:function(e){return $t(e).length},isExported:!0},pg={description:v("Converts a specified string to lowercase."),args:[a("text (string)",v("The string to convert to lowercase."))],compute:function(e){return $t(e).toLowerCase()},isExported:!0},bg={description:v("A segment of a string."),args:[a("text (string)",v("The string to extract a segment from.")),a("starting_at (number)",v("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),a("extract_length (number)",v("The length of the segment to extract."))],compute:function(e,t,r){const n=$t(e),o=kt(t,this.locale),s=kt(r,this.locale);return o<1?new S(v("The starting_at argument (%s) must be positive greater than one.",o.toString())):s<0?new S(v("The extract_length argument (%s) must be positive or null.",s)):n.slice(o-1,o+s-1)},isExported:!0},vg={description:v("Capitalizes each word in a specified string."),args:[a("text_to_capitalize (string)",v("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase."))],compute:function(e){return $t(e).replace(sg,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},yg={description:v("Extract text from a string based on the supplied regular expression."),args:[a("text (string)",v("The string on which you want to extract text.")),a("pattern (string)",v("The regular expression pattern to match against the text.")),a("return_mode (number, default=0)",v("0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array."),[{value:0,label:v("First match")},{value:1,label:v("All matches")},{value:2,label:v("Capture groups of first match")}]),a("case_sensitivity (number, default=0)",v("Whether the match is case-sensitive."),[{value:0,label:v("Case-sensitive")},{value:1,label:v("Case-insensitive")}])],compute:function(e,t,r={value:0},n={value:0}){const o=$t(e),s=$t(t),i=kt(r,this.locale),a=kt(n,this.locale);if(""===o||""===s)return{value:""};if(i<0||i>2)return new S(v("The return_mode (%s) must be 0, 1 or 2.",i));if(0!==a&&1!==a)return new S(v("The case_sensitivity (%s) must be 0 or 1.",a));const l=new RegExp(s,1===a?"gi":"g"),c=[...o.matchAll(l)];return 0===c.length?{value: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},wg={description:v("Replaces part of a text string with different text."),args:[a("text (string)",v("The text, a part of which will be replaced.")),a("position (number)",v("The position where the replacement will begin (starting from 1).")),a("length (number)",v("The number of characters in the text to be replaced.")),a("new_text (string)",v("The text which will be inserted into the original text."))],compute:function(e,t,r,n){const o=kt(t,this.locale);if(o<1)return new S(v("The position (%s) must be greater than or equal to 1.",o));const s=$t(e),i=kt(r,this.locale),a=$t(n);return s.substring(0,o-1)+a+s.substring(o-1+i)},isExported:!0},Eg={description:v("A substring from the end of a specified string."),args:[a("text (string)",v("The string from which the right portion will be returned.")),a("number_of_characters (number, optional)",v("The number of characters to return from the right side of string."))],compute:function(e,...t){const r=t.length?kt(t[0],this.locale):1;if(r<0)return new S(v("The number_of_characters (%s) must be positive or null.",r));const n=$t(e),o=n.length;return n.substring(o-r,o)},isExported:!0},Sg={description:v("First position of string found in text, ignoring case."),args:[a("search_for (string)",v("The string to look for within text_to_search.")),a("text_to_search (string)",v("The text to search for the first occurrence of search_for.")),a("starting_at (number, default=1)",v("The character within text_to_search at which to start the search."))],compute:function(e,t,r={value:1}){const n=$t(e).toLowerCase(),o=$t(t).toLowerCase(),s=kt(r,this.locale);if(""===o)return{value: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=o.indexOf(n,s-1);return-1===i?{value:w.GenericError,message:v("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",n,o)}:{value:i+1}},isExported:!0},Cg=!0,Tg=!0,Ig={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:Cg},n={value:Tg}){const o=$t(e),s=te($t(t)),i=qt(r),a=qt(n);if(s.length<=0)return new S(v("The delimiter (%s) must be not be empty.",s));const l=i?new RegExp(`[${s}]`,"g"):new RegExp(s,"g");let c=o.split(l);return a&&(c=c.filter(e=>""!==e)),or([c])},isExported:!1},xg={description:v("Replaces existing text with new text in a string."),args:[a("text_to_search (string)",v("The text within which to search and replace.")),a("search_for (string)",v("The string to search for within text_to_search.")),a("replace_with (string)",v("The string that will replace search_for.")),a("occurrence_number (number, optional)",v("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced."))],compute:function(e,t,r,n){const o=kt(n,this.locale);if(o<0)return new S(v("The occurrenceNumber (%s) must be positive or null.",o));const s=$t(e),i=$t(t);if(""===i)return s;const a=$t(r),l=new RegExp(te(i),"g");if(0===o)return s.replace(l,a);let c=0;return s.replace(l,e=>++c===o?a:e)},isExported:!0},Rg={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("text1 (string, range<string>)",v("Any text item. This could be a string, or an array of strings in a range.")),a("text2 (string, range<string>, repeating)",v("Additional text item(s)."))],compute:function(e,t={value:true},...r){const n=$t(e),o=qt(t);let s=0;return Jt(r,(e,t)=>o&&""===$t(t)?e:(s++?e+n:"")+$t(t),"")},isExported:!0},Ag=!1,_g={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."),ig),a(`pad_with (string, default="${w.NotAvailable}")`,v("The value to use for padding empty cells."))],compute:function(e,t,r,n={value:Ag},o={value:0},s=new x){const i=$t(e);if(i.length<=0)return new S(v("No text to split."));if(void 0===t&&void 0===r)return new S(v("At least one delimiter must be provided."));const a=mr(t).flat().map(e=>te($t(e))),l=mr(r).flat().map(e=>te($t(e)));if(a.some(e=>""===e)||l.some(e=>""===e))return new S(v("The delimiters cannot be empty values."));const c=qt(n),u=kt(o,this.locale);if(![0,1].includes(u))return new S(v("match_mode should be a value of 0 or 1."));const h=[],d=1===u?"gi":"g",f=l.filter(e=>!a.includes(e));let g=f.length?i.split(new RegExp(f.join("|"),d)):[i];c&&(g=g.filter(e=>""!==e));const m=new RegExp(a.join("|"),d);for(const e of g){let t=a.length?e.split(m):[e];c&&(t=t.filter(e=>""!==e)),h.push(t.map(e=>({value:e})))}const p=Math.max(...h.map(e=>e.length));for(const e of h)for(;e.length<p;)e.push(s);return or(h)},isExported:!0},Og={description:v("Removes space characters."),args:[a("text (string)",v("The text or reference to a cell containing text to be trimmed."))],compute:function(e){return $e($t(e))},isExported:!0},Dg={description:v("Converts a specified string to uppercase."),args:[a("text (string)",v("The string to convert to uppercase."))],compute:function(e){return $t(e).toUpperCase()},isExported:!0},Fg={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 Fn(kt(e,this.locale),{format:$t(t),locale:this.locale})},isExported:!0},Ng={description:v("Converts a string to a numeric value."),args:[a("value (number)",v("the string to be converted"))],compute:function(e){return kt(e,this.locale)},isExported:!0},Mg={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."),ig),a("match_end (number, default=0))",v("Whether to treat the end of text as a delimiter."),ag),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},n={value:0},o={value:0},s=new x){const i=$t(e),a=kt(r,this.locale),l=kt(n,this.locale),c=kt(o,this.locale);if(0===a)return new S(v("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new S(v("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new S(v("match_end should have a value of 0 or 1."));const u=$t(t);if(""===u)return Math.sign(a)>0?{value:i}:{value:""};const h=1===l?"gi":"g",d=te(u),f=new RegExp(d,h);let g=[...i.matchAll(f)].map(e=>e.index+d.length);if(a<0&&(g=g.reverse()),c&&Math.abs(a)===g.length+1)return Math.sign(a)>0?{value:""}:{value:i};const m=g[Math.abs(a)-1];return void 0===m?s:{value:i.substring(m)}},isExported:!0},Vg={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."),ig),a("match_end (number, default=0))",v("Whether to match a delimiter against the end of the text."),ag),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},n={value:0},o={value:0},s=new x){const i=$t(e),a=kt(r,this.locale),l=kt(n,this.locale),c=kt(o,this.locale);if(0===a)return new S(v("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new S(v("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new S(v("match_end should have a value of 0 or 1."));const u=$t(t);if(""===u)return Math.sign(a)>0?{value:""}:{value:i};const h=1===l?"gi":"g",d=te(u),f=new RegExp(d,h);let g=[...i.matchAll(f)].map(e=>e.index+d.length);if(a<0&&(g=g.reverse()),c&&Math.abs(a)===g.length+1)return Math.sign(a)>0?{value:i}:{value:""};const m=g[Math.abs(a)-1];return void 0===m?s:{value:i.substring(0,m-u.length)}},isExported:!0};var Lg=Object.freeze({__proto__:null,CHAR:lg,CLEAN:cg,CONCATENATE:ug,EXACT:hg,FIND:dg,JOIN:fg,LEFT:gg,LEN:mg,LOWER:pg,MID:bg,PROPER:vg,REGEXEXTRACT:yg,REPLACE:wg,RIGHT:Eg,SEARCH:Sg,SPLIT:Ig,SUBSTITUTE:xg,TEXT:Fg,TEXTAFTER:Mg,TEXTBEFORE:Vg,TEXTJOIN:Rg,TEXTSPLIT:_g,TRIM:Og,UPPER:Dg,VALUE:Ng});const Pg={description:v("Creates a hyperlink in a cell."),args:[a("url (string)",v("The full URL of the link enclosed in quotation marks.")),a("link_label (string, optional)",v("The text to display in the cell, enclosed in quotation marks."))],compute:function(e,t){const r=$t(e).trim(),n=$t(t)||r;return""===r?n:pe(n,r)},isExported:!0};var kg=Object.freeze({__proto__:null,HYPERLINK:Pg});const Ug=/^[A-Z0-9\_\.]+$/;class Hg 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(),!Ug.test(e))throw new Error(v("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const r=function(e,t){let r=0,n=0,o=0,s=0;for(const e of t.args)r++,e.optional||e.repeating||e.default||n++,e.repeating&&o++,(e.optional||e.default)&&s++;const i=t;return i.minArgRequired=n,i.maxArgPossible=o?1/0:r,i.nbrArgRepeating=o,i.nbrArgOptional=s,i.hidden=t.hidden||!1,i.name=e,i}(e,t);return function(e){if(e.nbrArgRepeating&&e.nbrArgOptional>=e.nbrArgRepeating)throw new Error(`Function ${e.name} has more optional arguments than repeatable ones.`);let t=!1,r=!1;for(const n of e.args){if(n.type.some(e=>u.includes(e))&&n.type.some(e=>!u.includes(e)))throw new Error(`Function ${e.name} has a mix of META and non-META types in the same argument: ${n.type}.`);if(n.repeating){if(!r&&t)throw new Error(`Function ${e.name} has non-consecutive repeating arguments. All repeating arguments must be declared consecutively.`);t=!0,r=!0}else r=!1}}(r),this.mapping[e]=wr(r),super.replace(e,r),this}}const Bg=new Hg,zg=[{name:v("Array"),functions:cn},{name:v("Database"),functions:_l},{name:v("Date"),functions:yu},{name:v("Filter"),functions:Ou},{name:v("Financial"),functions:Uh},{name:v("Info"),functions:Kh},{name:v("Lookup"),functions:yf},{name:v("Logical"),functions:hd},{name:v("Math"),functions:Gi},{name:v("Misc"),functions:eo},{name:v("Operator"),functions:Uf},{name:v("Statistical"),functions:gl},{name:v("Text"),functions:Lg},{name:v("Engineering"),functions:Su},{name:v("Web"),functions:kg},{name:v("Parser"),functions:og}];for(const e of zg){const t=e.functions;for(let r in t){const n=t[r];n.category=n.category||e.name,r=r.replace(/_/g,"."),Bg.add(r,{isExported:!1,...n})}}var $g;!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"}($g||($g={}));const Gg=(e,t=()=>!0)=>[{goTo:e,guard:t}],Wg=(e,t=()=>!0)=>({goTo:e,guard:t}),qg={[$g.LeftRef]:{REFERENCE:Gg($g.Separator),NUMBER:Gg($g.FullRowSeparator),SYMBOL:[Wg($g.FullColumnSeparator,e=>lo(e.value)),Wg($g.FullRowSeparator,e=>co(e.value))]},[$g.FullColumnSeparator]:{SPACE:Gg($g.FullColumnSeparator),OPERATOR:Gg($g.RightColumnRef,e=>":"===e.value)},[$g.FullRowSeparator]:{SPACE:Gg($g.FullRowSeparator),OPERATOR:Gg($g.RightRowRef,e=>":"===e.value)},[$g.Separator]:{SPACE:Gg($g.Separator),OPERATOR:Gg($g.RightRef,e=>":"===e.value)},[$g.RightRef]:{SPACE:Gg($g.RightRef),NUMBER:Gg($g.Found),REFERENCE:Gg($g.Found,e=>fo(e.value)),SYMBOL:Gg($g.Found,e=>uo(e.value)||ho(e.value))},[$g.RightColumnRef]:{SPACE:Gg($g.RightColumnRef),SYMBOL:Gg($g.Found,e=>uo(e.value)),REFERENCE:Gg($g.Found,e=>fo(e.value))},[$g.RightRowRef]:{SPACE:Gg($g.RightRowRef),NUMBER:Gg($g.Found),REFERENCE:Gg($g.Found,e=>fo(e.value)),SYMBOL:Gg($g.Found,e=>ho(e.value))},[$g.Found]:{}};function Zg(e){let t=0,r=qg[$g.LeftRef],n="";for(;void 0!==r;){const o=e[t++];if(!o)return null;const s=r[o.type]?.find(e=>e.guard(o)),i=s?s.goTo:void 0;switch(i){case void 0:return null;case $g.Found:return n+=o.value,e.splice(0,t),{type:"REFERENCE",value:n};default:r=qg[i],n+=o.value}}return null}function Yg(e,t=Dl){const r=Ml(e,t),n=[];for(;r.length;)n.push(Zg(r)||r.shift());return n}const jg=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,Xg=["-","+"],Kg=["%"];class Qg{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 Jg={"%":40,"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function em(e){const t=e.shift();if(!t)throw new C;switch(t.type){case"DEBUGGER":const r=nm(e,1e3);return r.debug=!0,r;case"NUMBER":return{type:"NUMBER",value:Dt(t.value,Dl),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"STRING":return{type:"STRING",value:oe(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"INVALID_REFERENCE":return{type:"REFERENCE",value: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 n=t.value,o=e.current;if("LEFT_PAREN"===o?.type&&jg.test(t.value)&&n===oe(n,"'")){const{args:r,rightParen:o}=function(e){rm(e,"LEFT_PAREN",v("Missing opening parenthesis"));const t=e.current;if("RIGHT_PAREN"===t?.type){return{args:[],rightParen:rm(e,"RIGHT_PAREN")}}const r=[];r.push(tm(e));for(;"RIGHT_PAREN"!==e.current?.type;)rm(e,"ARG_SEPARATOR",v("Wrong function call")),r.push(tm(e));const n=rm(e,"RIGHT_PAREN");return{args:r,rightParen:n}}(e);return{type:"FUNCALL",value:n,args:r,tokenStartIndex:t.tokenIndex,tokenEndIndex:o.tokenIndex}}const s=n.toUpperCase();return"TRUE"===s||"FALSE"===s?{type:"BOOLEAN",value:"TRUE"===s,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:"SYMBOL",value:oe(t.value,"'"),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"LEFT_PAREN":const i=nm(e),a=rm(e,"RIGHT_PAREN",v("Missing closing parenthesis"));return{...i,tokenStartIndex:t.tokenIndex,tokenEndIndex:a.tokenIndex};case"OPERATOR":const l=t.value;if(Xg.includes(l)){const r=nm(e,Jg[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 tm(e){const t=e.current;return"ARG_SEPARATOR"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:"",tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:nm(e)}function rm(e,t,r){const n=e.shift();if(!n||n.type!==t)throw new C(r);return n}function nm(e,t=0){if(0===e.length)throw new C;let r=em(e);for(;"OPERATOR"===e.current?.type&&Jg[e.current.value]>t;){const t=e.shift(),n=t.value;if(Kg.includes(n))r={type:"UNARY_OPERATION",value:n,operand:r,postfix:!0,tokenStartIndex:r.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{const t=nm(e,Jg[n]);r={type:"BIN_OPERATION",value:n,left:r,right:t,tokenStartIndex:r.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return r}function om(e){return sm(Yg(e))}function sm(e){const t=e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>"SPACE"!==e.type),r=new Qg(t);"="===r.current?.value&&r.shift();const n=nm(r);if(r.current)throw new C;return n}function im(e,t,r){return cm(e,e=>e.type===t?r(e):e)}function am(e){return Array.from(lm(e))}function*lm(e){switch(yield e,e.type){case"FUNCALL":for(const t of e.args)yield*lm(t);break;case"UNARY_OPERATION":yield*lm(e.operand);break;case"BIN_OPERATION":yield*lm(e.left),yield*lm(e.right)}}function cm(e,t){switch((e=t(e)).type){case"FUNCALL":return{...e,args:e.args.map(e=>cm(e,t))};case"UNARY_OPERATION":return{...e,operand:cm(e.operand,t)};case"BIN_OPERATION":return{...e,right:cm(e.right,t),left:cm(e.left,t)};default:return e}}const um=Bg.content,hm={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},dm={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},fm={};function gm(e){return mm(Yg(e))}function mm(e){try{return function(e){const{dependencies:r,literalValues:o,symbols:s}=function(e){const t={numbers:[],strings:[]},r=[],n=[];for(const o of e)switch(o.type){case"INVALID_REFERENCE":case"REFERENCE":r.push(o.value);break;case"STRING":const e=oe(o.value);t.strings.push({value:e});break;case"NUMBER":{const e=Dt(o.value,Dl);t.numbers.push({value:e});break}case"SYMBOL":n.push(oe(o.value,"'"))}return{dependencies:r,literalValues:t,symbols:n}}(e),i=function(e){let t="";for(const r of e)switch(r.type){case"STRING":t+="|S|";break;case"NUMBER":t+="|N|";break;case"REFERENCE":case"INVALID_REFERENCE":r.value.includes(":")?t+="|R|":t+="|C|";break;case"SPACE":break;default:t+=r.value}return t}(e);if(!fm[i]){const l=sm([...e]),u=new n;let h=0,d=0,f=0;if("BIN_OPERATION"===l.type&&":"===l.value)throw new C(v("Invalid formula"));if("EMPTY"===l.type)throw new C(v("Invalid formula"));const g=y(l),m=new t;m.append(`// ${i}`),m.append(g),m.append(`return ${g.returnExpression};`);const p=new Function("deps","ref","range","getSymbolValue","ctx",m.toString());function b(e){const{args:t}=e,r=e.value.toUpperCase(),n=um[r];if(!n)throw new R(v('Unknown function: "%s"',e.value));!function(e){const t=e.args.length,r=e.value.toUpperCase(),n=um[r],{nbrArgRepeating:o,minArgRequired:s}=n;if(t<s)throw new C(v("Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.",{functionName:r,minArgRequired:s,nbrArgSupplied:t}));if(t>n.maxArgPossible)throw new C(v("Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.",{functionName:r,maxArgPossible:n.maxArgPossible,nbrArgSupplied:t}));if(o>1){const e=t-s-o*Math.floor((t-s)/o)-n.nbrArgOptional;if(e>0)throw new C(v("Invalid number of arguments for the %(functionName)s function. Repeatable arguments should be supplied in groups of %(nbrArgRepeating)s, with up to %(nbrArgOptional)s optional. Got %(nbrValueRemaining)s too many.",{functionName:r,nbrArgRepeating:o,nbrArgOptional:n.nbrArgOptional,nbrValueRemaining:e}))}}(e);const o=[],s=c(n,t.length);for(let e=0;e<t.length;e++){const r=n.args[s(e)??-1],i=t[e],a=r.type||[],l=a.includes("META")||a.includes("RANGE<META>"),c=a.some(e=>pm(e));o.push(y(i,l,c))}return o}function y(e,r=!1,n=!1){const o=new t(u);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&r)throw new C(v("Argument must be a reference to a cell or range."));switch(e.debug&&(o.append("debugger;"),o.append('ctx["debug"] = true;')),e.type){case"BOOLEAN":return o.return(`{ value: ${e.value} }`);case"NUMBER":return o.return(`this.literalValues.numbers[${d++}]`);case"STRING":return o.return(`this.literalValues.strings[${h++}]`);case"REFERENCE":return o.return(`${e.value.includes(":")||n?"range":"ref"}(deps[${f++}], ${r?"true":"false"})`);case"FUNCALL":const t=b(e).map(e=>e.assignResultToVariable());o.append(...t);const i=e.value.toUpperCase();return o.return(`ctx['${i}'](${t.map(e=>e.returnExpression)})`);case"UNARY_OPERATION":{const t=dm[e.value],r=y(e.operand,!1,!1).assignResultToVariable();return o.append(r),o.return(`ctx['${t}'](${r.returnExpression})`)}case"BIN_OPERATION":{const t=hm[e.value],r=y(e.left,!1,!1).assignResultToVariable(),n=y(e.right,!1,!1).assignResultToVariable();return o.append(r),o.append(n),o.return(`ctx['${t}'](${r.returnExpression}, ${n.returnExpression})`)}case"SYMBOL":const a=s.indexOf(e.value);return o.return(`getSymbolValue(this.symbols[${a}])`);case"EMPTY":return o.return("undefined")}}fm[i]=p}const a={execute:fm[i],dependencies:r,literalValues:o,symbols:s,tokens:e,isBadExpression:!1,normalizedFormula:i};return a}(e)}catch(t){return{tokens:e,dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map(e=>e.value).join("")}}}function pm(e){return e.startsWith("RANGE")}class bm{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 vm{transportService;constructor(e){this.transportService=e}async sendMessage(e){"CLIENT_JOINED"!==e.type&&"CLIENT_LEFT"!==e.type&&"CLIENT_MOVED"!==e.type||this.transportService.sendMessage(e)}onNewMessage(e,t){this.transportService.onNewMessage(e,t)}leave(e){this.transportService.leave(e)}}class ym{subscriptions={};on(e,t,r){if(!r)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:r})}trigger(e,t){const r=this.subscriptions[e]||[];for(let e=0,n=r.length;e<n;e++){const n=r[e];n.callback.call(n.owner,t)}}off(e,t){const r=this.subscriptions[e];r&&(this.subscriptions[e]=r.filter(e=>e.owner!==t))}clear(){this.subscriptions={}}}function wm(e){const t=[];for(let r=0;r<e;r++){const e={cells:{}};t.push(e)}return t}function Em(e,t,r){return r.map(r=>r>=e?r+t:r)}function Sm(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 Cm(e,t="Sheet"){let r=1,n=`${t}${r}`;for(;e.includes(n);)n=`${t}${r}`,r++;return n}function Tm(e,t){let r=1;const n=v("Copy of %s",e);let o=n.toString();for(;t.includes(o);)o=`${n} (${r})`,r++;return o}function Im(e,t){return void 0!==e&&void 0!==t&&ne(e.trim().toUpperCase())===ne(t.trim().toUpperCase())}function xm(e,t){const r=e.zone,n=function(e,t){const{left:r,top:n,bottom:o,right:s}=e;if(void 0!==s&&void 0!==o)return e;if(void 0===o&&void 0!==s)return{right:s,top:n,left:r,bottom:t.numberOfRows-1};if(void 0===s&&void 0!==o)return{bottom:o,left:r,top:n,right:t.numberOfCols-1};throw new Error("Bad zone format")}(r,t(e.sheetId));let o=e.parts;return 1===e.parts.length&&cs(n)>1?o=[e.parts[0],e.parts[0]]:2===e.parts.length&&1===cs(n)&&(o=[e.parts[0]]),{unboundedZone:r,zone:n,parts:o,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Rm(e,t){const r=e.xc,{xc:n,sheetName:o}=go(r),s=Ho(n),i=function(e,t){const r=e.split(":").map(e=>{const t=co(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}}),n=void 0===t.bottom,o=void 0===t.right;n&&(r[0].rowFixed=r[0].rowFixed||r[1].rowFixed,r[1].rowFixed=r[0].rowFixed||r[1].rowFixed);o&&(r[0].colFixed=r[0].colFixed||r[1].colFixed,r[1].colFixed=r[0].colFixed||r[1].colFixed);return r}(n,s);return xm({zone:s,parts:i,sheetId:e.sheetId,prefixSheet:Boolean(o),invalidSheetName:e.invalidSheetName},t)}function Am(e){const t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:"",zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function _m(e){return ls(e.unboundedZone)}function Om(e){return as(e.unboundedZone)}function Dm(e,t,r,n={useBoundedReference:!1,useFixedReference:!1}){if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return w.InvalidReference;if(e.zone.left<0||e.zone.top<0)return w.InvalidReference;const o=e.sheetId!==t||e.invalidSheetName||e.prefixSheet;let s="";if(o&&(s=e.invalidSheetName?e.invalidSheetName:se(r(e.sheetId))),o&&!s)return w.InvalidReference;let i=$m(e,0,n);return e.parts&&2===e.parts.length&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(i+=":",i+=$m(e,1,n)),`${o?s+"!":""}${i}`}function Fm(e,t,r){const n=r.sheetId===e?t:r.sheetId;return{...r,sheetId:n}}function Nm(e){const t=[];for(const r of e)for(const e of rs(r.zone))t.push({...e,sheetId:r.sheetId});return t}function Mm(e){const t={left:e.col,top:e.row,right:e.col,bottom:e.row};return{sheetId:e.sheetId,zone:t}}function Vm(e){return Lm.get(e.type)?.(e)}const Lm=new class extends fd{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};function Pm(e){const t="COL"===e.dimension?"left":"top",r="COL"===e.dimension?"right":"bottom",n="COL"===e.dimension?"columns":"rows",o=[...e.elements];o.sort((e,t)=>t-e);const s=ce(o);return o=>{if(!Im(o.sheetId,e.sheetId))return{changeType:"NONE"};let i=o,a="NONE";for(const e of s){const s=qe(e),l=We(e);if(o.zone[t]<=s&&s<=o.zone[r]){const e=Math.min(o.zone[r],l)-s+1;a="RESIZE",i=zm(i,n,a,-e)}else if(o.zone[t]>=s&&o.zone[r]<=l)a="REMOVE",i=Am(w.InvalidReference);else if(o.zone[t]<=l&&o.zone[r]>=l){const e=l-o.zone[t]+1;a="RESIZE",i=zm(i,n,a,-e),i=zm(i,n,"MOVE",-(o.zone[t]-s))}else s<o.zone[t]&&(a="MOVE",i=zm(i,n,a,-(l-s+1)))}return"NONE"!==a?{changeType:a,range:i}:{changeType:"NONE"}}}function km(e){const t="COL"===e.dimension?"left":"top",r="COL"===e.dimension?"right":"bottom",n="COL"===e.dimension?"columns":"rows";return o=>{if(o.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(o.zone[t]<=e.base&&e.base<o.zone[r])return{changeType:"RESIZE",range:zm(o,n,"RESIZE",e.quantity)};if(e.base<o.zone[t])return{changeType:"MOVE",range:zm(o,n,"MOVE",e.quantity)}}else{if(o.zone[t]<e.base&&e.base<=o.zone[r])return{changeType:"RESIZE",range:zm(o,n,"RESIZE",e.quantity)};if(e.base<=o.zone[t])return{changeType:"MOVE",range:zm(o,n,"MOVE",e.quantity)}}return{changeType:"NONE"}}}function Um(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:"NONE"};const r=e.sheetName;return{changeType:"REMOVE",range:t={...Am(w.InvalidReference),invalidSheetName:r}}}}function Hm(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.newName&&t.invalidSheetName===e.newName){const r=void 0,n=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:n,invalidSheetName:r}}}if(e.oldName&&t.invalidSheetName===e.oldName){const r=void 0,n=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:n,invalidSheetName:r}}}return{changeType:"NONE"}}}function Bm(e){const t=e.target[0];return r=>{if(r.sheetId!==e.sheetId||!Jo(r.zone,t))return{changeType:"NONE"};const n=e.targetSheetId,o=zm(r,"both","MOVE",[e.col-t.left,e.row-t.top]),s=e.sheetId!==n||o.prefixSheet;return{changeType:"MOVE",range:{...o,sheetId:n,prefixSheet:s}}}}function zm(e,t,r,n){return{...e,unboundedZone:os(e.unboundedZone,t,r,n),zone:os(e.zone,t,r,n)}}function $m(e,t,r={useBoundedReference:!1,useFixedReference:!1}){const n=e.parts[t]?.colFixed||r.useFixedReference?"$":"",o=Eo(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=ls(e.unboundedZone)&&!r.useBoundedReference?0===t&&e.unboundedZone.hasHeader?n+o+s+i:n+o:as(e.unboundedZone)&&!r.useBoundedReference?0===t&&e.unboundedZone.hasHeader?n+o+s+i:s+i:n+o+s+i,a}Lm.add("REMOVE_COLUMNS_ROWS",e=>({applyChange:Pm(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("ADD_COLUMNS_ROWS",e=>({applyChange:km(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("DELETE_SHEET",e=>({applyChange:Um(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add("RENAME_SHEET",e=>({applyChange:Hm(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add("MOVE_RANGES",e=>({applyChange:Bm(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));const Gm=new class extends fd{addTransformation(e,t,r){this.content[e]||(this.content[e]=new Map);for(const n of t)this.content[e].set(n,r);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}};const Wm=new class extends fd{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};function qm(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?function(e,t,r){const n="left"===t?"right":"bottom";let o=e[t],s=e[n];const i=e[n];for(const n of r.sort((e,t)=>t-e))e[t]>n&&(o--,void 0!==s&&s--),void 0!==i&&void 0!==s&&e[t]<=n&&i>=n&&s--;if(!(void 0!==s&&o>s))return{...e,[t]:o,[n]:s}}(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?function(e,t,r,n,o){const s="left"===t?"columns":"rows",i="before"===n?r-1:r,a=e["left"===t?"right":"bottom"];return e[t]<=i&&a&&a>i?os(e,s,"RESIZE",o):i<e[t]?os(e,s,"MOVE",o):{...e}}(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):e}function Zm(e,t){const r="DELETE_SHEET"===t.type&&t.sheetId;if("sheetId"in t&&e._sheetId!==t.sheetId)return e;{const n=qm(e._zone,t);if(n&&r!==e._sheetId)return{...e,_zone:n}}}const Ym=/rgba?\(|\s+|\)/gi,jm=/^#([A-F\d]{2}){3,4}$/;function Xm(e,t=1){const r=1!==t?Math.round(255*t).toString(16).padStart(2,"0"):"";return Qm(e.toString(16).padStart(6,"0"))+r}function Km(e){return"number"==typeof e?e:Number.parseInt(Qm(e).slice(1,7),16)}function Qm(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(Ym,"").split(",");let r=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");if(isNaN(e))throw new Error("invalid alpha value");r=Math.round(255*e)}const n=t.map(e=>parseInt(e,10));255!==r&&n.push(r);return"#"+Ie(n.map(e=>e.toString(16).padStart(2,"0"))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce((e,t)=>e+t+t,"")),t=`#${t}`),!jm.test(t))throw new Error(`invalid color input: ${e}`);return t}function Jm(e){try{return Qm(e),!0}catch(e){return!1}}const ep=e=>e>=0&&e<=255;function tp(e,t,r,n=1){if(!ep(e)||!ep(t)||!ep(r)||n<0||n>1)throw new Error(`Invalid RGBA values ${[e,t,r,n]}`);return{a:n,b:r,g:t,r:e}}function rp(e){let{r:t,g:r,b:n}=op(e);t/=255,r/=255,n/=255;const o=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*o(t)+.7152*o(r)+.0722*o(n)}function np(e){let t=e.r.toString(16),r=e.g.toString(16),n=e.b.toString(16),o=Math.round(255*e.a).toString(16);return 1===t.length&&(t="0"+t),1===r.length&&(r="0"+r),1===n.length&&(n="0"+n),1===o.length&&(o="0"+o),"ff"===o&&(o=""),("#"+t+r+n+o).toUpperCase()}function op(e){let t,r,n,o;if(7===(e=Qm(e)).length)t=parseInt(e[1]+e[2],16),r=parseInt(e[3]+e[4],16),n=parseInt(e[5]+e[6],16),o=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),r=parseInt(e[3]+e[4],16),n=parseInt(e[5]+e[6],16),o=parseInt(e[7]+e[8],16)}return o=+(o/255).toFixed(3),{a:o,r:t,g:r,b:n}}function sp(e){(e={...e}).s/=100,e.l/=100;const t=(1-Math.abs(2*e.l-1))*e.s,r=t*(1-Math.abs(e.h/60%2-1)),n=e.l-t/2;let o=0,s=0,i=0;return 0<=e.h&&e.h<60?(o=t,s=r,i=0):60<=e.h&&e.h<120?(o=r,s=t,i=0):120<=e.h&&e.h<180?(o=0,s=t,i=r):180<=e.h&&e.h<240?(o=0,s=r,i=t):240<=e.h&&e.h<300?(o=r,s=0,i=t):300<=e.h&&e.h<360&&(o=t,s=0,i=r),o=Math.round(255*(o+n)),s=Math.round(255*(s+n)),i=Math.round(255*(i+n)),{a:e.a,r:o,g:s,b:i}}function ip(e){const t=e.r/255,r=e.g/255,n=e.b/255,o=Math.min(t,r,n),s=Math.max(t,r,n),i=s-o;let a=0,l=0,c=0;return a=0===i?0:s===t?(r-n)/i%6:s===r?(n-t)/i+2:(t-r)/i+4,a=Math.round(60*a),a<0&&(a+=360),c=(s+o)/2,l=0===i?0:i/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}function ap(e){return np(sp(e))}function lp(e){return ip(op(e))}function cp(e){return op("number"==typeof e?Xm(e):e)}function up(e,t){const r=lp(e);return 1===t?"#fff":(r.l=t*(100-r.l)+r.l,ap(r))}function hp(e,t){const r=lp(e);return 1===t?"#000":(r.s=Math.min(100,t*r.s+r.s),r.l=r.l-t*r.l,ap(r))}const dp=["#4EA7F2","#EA6175","#43C5B1","#F4A261","#8481DD","#FFD86D"],fp=["#4EA7F2","#3188E6","#43C5B1","#00A78D","#EA6175","#CE4257","#F4A261","#F48935","#8481DD","#5752D1","#FFD86D","#FFBC2C"],gp=["#4EA7F2","#3188E6","#056BD9","#A76DBC","#7F4295","#6D2387","#EA6175","#CE4257","#982738","#43C5B1","#00A78D","#0E8270","#F4A261","#F48935","#BE5D10","#8481DD","#5752D1","#3A3580","#A4A8B6","#7E8290","#545B70","#FFD86D","#FFBC2C","#C08A16"],mp=["#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"],pp=["#4EA7F2","#43C5B1","#EA6175","#F4A261","#8481DD","#FFD86D","#3188E6","#00A78D","#CE4257","#F48935","#5752D1","#FFBC2C"],bp=["#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 yp{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){var r;this.preferredColors=t,this.palette=(r=e,r<=6?dp:r<=12?fp:r<=24?gp:mp).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 wp extends yp{constructor(e,t=[]){var r;super(e,t),this.palette=(r=e,r<=6?dp:r<=12?pp:r<=24?bp:vp).filter(e=>!t.includes(e))}}class Ep{availableColors;colors={};constructor(e=12){this.availableColors=new wp(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}}function Sp(e,t,r,n){const o=t-e;return[((r>>16)%256-(n>>16)%256)/o,((r>>8)%256-(n>>8)%256)/o,(r%256-n%256)/o]}function Cp(e,t,r,n){const[o,s,i]=n;return Math.round((r>>16)%256-o*(e-t))<<16|Math.round((r>>8)%256-s*(e-t))<<8|Math.round(r%256-i*(e-t))}v("Light"),v("Medium"),v("Dark"),v("Custom");const Tp={hasFilters:!1,totalRow:!1,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,automaticAutofill:!0,styleId:"TableStyleMedium2"};function Ip(e,t){return{coloredText:hp(t,.3),light:up(t,.8),medium:up(t,.6),dark:hp(t,.3),mediumBorder:up(t,.45),highlight:t,name:e}}const xp={black:{name:v("Black"),coloredText:"#000000",light:"#D9D9D9",medium:"#A6A6A6",dark:"#404040",mediumBorder:"#000000",highlight:"#000000"},lightBlue:Ip(v("Light blue"),"#346B90"),red:Ip(v("Red"),"#C53628"),lightGreen:Ip(v("Light green"),"#748747"),purple:Ip(v("Purple"),"#6C4E65"),gray:{name:v("Gray"),coloredText:"#666666",light:"#EEEEEE",medium:"#DDDDDD",dark:"#767676",mediumBorder:"#D0D0D0",highlight:"#A9A9A9"},orange:Ip(v("Orange"),"#C37034")},Rp={black:xp.black,orangeBlue:{...xp.lightBlue,highlight:xp.orange.highlight},purpleGreen:{...xp.lightGreen,highlight:xp.purple.highlight},redBlue:{...xp.lightBlue,highlight:xp.red.highlight}},Ap=e=>({category:"light",templateName:"lightColoredText",primaryColor:e.highlight,wholeTable:{style:{textColor:e.coloredText},border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"}}},headerRow:{border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"thin"}}},firstRowStripe:{style:{fillColor:e.light}}}),_p=e=>({category:"light",templateName:"lightWithHeader",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"},left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"},border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}},secondRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}}}),Op=e=>({category:"light",templateName:"lightAllBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"},left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"},horizontal:{color:e.highlight,style:"thin"},vertical:{color:e.highlight,style:"thin"}}},headerRow:{border:{bottom:{color:e.highlight,style:"medium"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}}}),Dp=e=>({category:"medium",templateName:"mediumBandedBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"},horizontal:{color:e.mediumBorder,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}}}),Fp=e=>({category:"medium",templateName:"mediumWhiteBorders",primaryColor:e.highlight,wholeTable:{border:{horizontal:{color:"#FFFFFF",style:"thin"},vertical:{color:"#FFFFFF",style:"thin"}},style:{fillColor:e.light}},headerRow:{border:{bottom:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{border:{top:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),Np=e=>({category:"medium",templateName:"mediumMinimalBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:"#000000",style:"medium"},bottom:{color:"#000000",style:"medium"}}},totalRow:{border:{top:{color:"#000000",style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"},border:{bottom:{color:"#000000",style:"medium"}}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:xp.black.light}},firstColumnStripe:{style:{fillColor:xp.black.light}}}),Mp=e=>({category:"medium",templateName:"mediumAllBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"},horizontal:{color:e.mediumBorder,style:"thin"},vertical:{color:e.mediumBorder,style:"thin"}},style:{fillColor:e.light}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),Vp=e=>({category:"dark",templateName:"dark",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{style:{fillColor:e.dark,textColor:"#FFFFFF"},border:{top:{color:"#FFFFFF",style:"thick"}}},headerRow:{style:{fillColor:"#000000"},border:{bottom:{color:"#FFFFFF",style:"thick"}}},firstColumn:{style:{fillColor:e.dark},border:{right:{color:"#FFFFFF",style:"thick"}}},lastColumn:{style:{fillColor:e.dark},border:{left:{color:"#FFFFFF",style:"thick"}}},firstRowStripe:{style:{fillColor:e.dark}},firstColumnStripe:{style:{fillColor:e.dark}}}),Lp=e=>({category:"dark",templateName:"darkNoBorders",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.light}},totalRow:{border:{top:{color:"#000000",style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),Pp=Vp(xp.black);Pp.wholeTable.style.fillColor="#737373";const kp=Np(xp.black);function Up(e,t,r){return{...t(r),displayName:`${r.name}, ${e}`}}kp.wholeTable.border={...kp.wholeTable.border,left:{color:"#000000",style:"thin"},right:{color:"#000000",style:"thin"},horizontal:{color:"#000000",style:"thin"},vertical:{color:"#000000",style:"thin"}};const Hp={None:{category:"light",templateName:"none",primaryColor:"",displayName:"none"},TableStyleLight1:Up("TableStyleLight1",Ap,xp.black),TableStyleLight2:Up("TableStyleLight2",Ap,xp.lightBlue),TableStyleLight3:Up("TableStyleLight3",Ap,xp.red),TableStyleLight4:Up("TableStyleLight4",Ap,xp.lightGreen),TableStyleLight5:Up("TableStyleLight5",Ap,xp.purple),TableStyleLight6:Up("TableStyleLight6",Ap,xp.gray),TableStyleLight7:Up("TableStyleLight7",Ap,xp.orange),TableStyleLight8:Up("TableStyleLight8",_p,xp.black),TableStyleLight9:Up("TableStyleLight9",_p,xp.lightBlue),TableStyleLight10:Up("TableStyleLight10",_p,xp.red),TableStyleLight11:Up("TableStyleLight11",_p,xp.lightGreen),TableStyleLight12:Up("TableStyleLight12",_p,xp.purple),TableStyleLight13:Up("TableStyleLight13",_p,xp.gray),TableStyleLight14:Up("TableStyleLight14",_p,xp.orange),TableStyleLight15:Up("TableStyleLight15",Op,xp.black),TableStyleLight16:Up("TableStyleLight16",Op,xp.lightBlue),TableStyleLight17:Up("TableStyleLight17",Op,xp.red),TableStyleLight18:Up("TableStyleLight18",Op,xp.lightGreen),TableStyleLight19:Up("TableStyleLight19",Op,xp.purple),TableStyleLight20:Up("TableStyleLight20",Op,xp.gray),TableStyleLight21:Up("TableStyleLight21",Op,xp.orange),TableStyleMedium1:Up("TableStyleMedium1",Dp,xp.black),TableStyleMedium2:Up("TableStyleMedium2",Dp,xp.lightBlue),TableStyleMedium3:Up("TableStyleMedium3",Dp,xp.red),TableStyleMedium4:Up("TableStyleMedium4",Dp,xp.lightGreen),TableStyleMedium5:Up("TableStyleMedium5",Dp,xp.purple),TableStyleMedium6:Up("TableStyleMedium6",Dp,xp.gray),TableStyleMedium7:Up("TableStyleMedium7",Dp,xp.orange),TableStyleMedium8:Up("TableStyleMedium8",Fp,xp.black),TableStyleMedium9:Up("TableStyleMedium9",Fp,xp.lightBlue),TableStyleMedium10:Up("TableStyleMedium10",Fp,xp.red),TableStyleMedium11:Up("TableStyleMedium11",Fp,xp.lightGreen),TableStyleMedium12:Up("TableStyleMedium12",Fp,xp.purple),TableStyleMedium13:Up("TableStyleMedium13",Fp,xp.gray),TableStyleMedium14:Up("TableStyleMedium14",Fp,xp.orange),TableStyleMedium15:{...kp,displayName:"Black, TableStyleMedium15"},TableStyleMedium16:Up("TableStyleMedium16",Np,xp.lightBlue),TableStyleMedium17:Up("TableStyleMedium17",Np,xp.red),TableStyleMedium18:Up("TableStyleMedium18",Np,xp.lightGreen),TableStyleMedium19:Up("TableStyleMedium19",Np,xp.purple),TableStyleMedium20:Up("TableStyleMedium20",Np,xp.gray),TableStyleMedium21:Up("TableStyleMedium21",Np,xp.orange),TableStyleMedium22:Up("TableStyleMedium22",Mp,xp.black),TableStyleMedium23:Up("TableStyleMedium23",Mp,xp.lightBlue),TableStyleMedium24:Up("TableStyleMedium24",Mp,xp.red),TableStyleMedium25:Up("TableStyleMedium25",Mp,xp.lightGreen),TableStyleMedium26:Up("TableStyleMedium26",Mp,xp.purple),TableStyleMedium27:Up("TableStyleMedium27",Mp,xp.gray),TableStyleMedium28:Up("TableStyleMedium28",Mp,xp.orange),TableStyleDark1:{...Pp,displayName:"Black, TableStyleDark1"},TableStyleDark2:Up("TableStyleDark2",Vp,xp.lightBlue),TableStyleDark3:Up("TableStyleDark3",Vp,xp.red),TableStyleDark4:Up("TableStyleDark4",Vp,xp.lightGreen),TableStyleDark5:Up("TableStyleDark5",Vp,xp.purple),TableStyleDark6:Up("TableStyleDark6",Vp,xp.gray),TableStyleDark7:Up("TableStyleDark7",Vp,xp.orange),TableStyleDark8:Up("TableStyleDark8",Lp,Rp.black),TableStyleDark9:Up("TableStyleDark9",Lp,Rp.redBlue),TableStyleDark10:Up("TableStyleDark10",Lp,Rp.purpleGreen),TableStyleDark11:Up("TableStyleDark11",Lp,Rp.orangeBlue)},Bp={none:()=>({category:"none",templateName:"none",primaryColor:"",name:"none"}),lightColoredText:Ap,lightAllBorders:Op,mediumAllBorders:Mp,lightWithHeader:_p,mediumBandedBorders:Dp,mediumMinimalBorders:Np,darkNoBorders:Lp,mediumWhiteBorders:Fp,dark:Vp};function zp(e,t,r){const n=Ip("",r);return{...Bp[t](n),category:"custom",displayName:e}}function $p(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId!==t.sheetId)return e;const r=qm(e.pivot.dataSet.zone,t),n=r?{...e.pivot.dataSet,zone:r}:void 0;return{...e,pivot:{...e.pivot,dataSet:n}}}function Gp(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 Wp(e,t){if(e.sheetId!==t.sheetId)return e;const r=qm(e.zone,t);if(!r)return;const n=e.newTableRange?Zm(e.newTableRange,t):void 0;return{...e,newTableRange:n,zone:r}}function qp(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let r;if("REMOVE_COLUMNS_ROWS"===t.type)r=Sm(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){r=Em(Re(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==r?{...e,base:r}:void 0}function Zp(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;const r=le(e.start,e.end+1);let n=[];if("REMOVE_COLUMNS_ROWS"===t.type)n=Sm(t.elements,r);else if("ADD_COLUMNS_ROWS"===t.type){n=Em(Re(t.position,t.base),t.quantity,r)}return 0!==n.length?{...e,start:Math.min(...n),end:Math.max(...n)}:void 0}Gm.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],qp),Gm.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],qp),Gm.addTransformation("DELETE_SHEET",["MOVE_RANGES"],function(e,t){const r=t.sheetId;if(e.targetSheetId===r||e.sheetId===r)return;return e}),Gm.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART","UPDATE_CAROUSEL"],function(e,t){if(e.figureId===t.figureId)return;return e}),Gm.addTransformation("DELETE_CHART",["UPDATE_CHART"],function(e,t){if(e.chartId===t.chartId)return;return e}),Gm.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))}}}),Gm.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}),Gm.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],function(e,t){if(e.sheetId!==t.sheetId)return e;const r=[];for(const n of e.target)t.target.every(e=>!Ko(n,e))&&r.push(n);if(r.length)return{...e,target:r};return}),Gm.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Gp),Gm.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Gp),Gm.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],Wp),Gm.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],Wp),Gm.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:Tp.styleId}}}),Gm.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],Zp),Gm.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],Zp),Gm.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],function(e,t){if(e.pivotId===t.pivotId)return;return e}),Gm.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}),Gm.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],$p),Gm.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],$p);const Yp=new fd,jp="000000",Xp={arrows:"3Arrows",smiley:"3Symbols",dots:"3TrafficLights1"},Kp="http://schemas.openxmlformats.org/spreadsheetml/2006/main",Qp="http://schemas.openxmlformats.org/spreadsheetml/2006/main",Jp="http://schemas.openxmlformats.org/package/2006/relationships",eb="http://schemas.openxmlformats.org/package/2006/content-types",tb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",rb="http://schemas.openxmlformats.org/spreadsheetml/2006/main",nb="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",ob="http://schemas.openxmlformats.org/spreadsheetml/2006/main",sb="http://schemas.microsoft.com/office/spreadsheetml/2014/revision",ib="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3",ab="http://schemas.openxmlformats.org/markup-compatibility/2006",lb="http://schemas.openxmlformats.org/drawingml/2006/main",cb="http://schemas.openxmlformats.org/drawingml/2006/chart",ub={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"},hb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",db="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",fb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",gb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",mb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",pb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",bb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",vb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",yb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",wb="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",Eb="bdbb8cdc-fa1e-496e-a857-3c3f30c029c3",Sb="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Cb=.75,Tb=.143,Ib=8.43,xb=12.75,Rb={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}]},Ab=["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"],_b="[Content_Types].xml";function Ob(e,t,r){if(!t.startsWith("="))return t;const n=Yg(t);for(let t=1;t<n.length;t++){if("REFERENCE"!==n[t].type)continue;const o=n[t].value,s=Db(e,o,r);o!==s&&(n[t]={value:s,type:"REFERENCE"})}return Ie(n.map(e=>e.value))}function Db(e,t,r){const n=go(t).sheetName;if(n?!Im(n,r.sheetName.old):e!==r.sheetId)return t;const o=function(e,t){if(!ao.test(e))return Am(e);return Rm({xc:e,sheetId:t},Fb)}(t,n?r.sheetId:e);if(o.invalidXc)return t;const s=r.applyChange(o);return"NONE"===s.changeType||"REMOVE"===s.changeType?t:Dm(s.range,e,function(e){return t=>t===e.sheetId?e.sheetName.current:""}(r))}function Fb(e){return{numberOfRows:Number.MAX_SAFE_INTEGER,numberOfCols:Number.MAX_SAFE_INTEGER}}function Nb(e){return e&&rp(e)<.3?"#FFFFFF":"#000000"}function Mb(e){return e&&rp(e)<.3?"#C8C8C8":"#666666"}function Vb(e,t,r){const n=Yp.getAll().find(e=>e.match(t.type));if(!n)throw new Error("Unknown chart type.");return n.transformDefinition(e,t,r)}function Lb(e,t){return(e=re(e)).pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=Ob(e.computedBy.sheetId,e.computedBy.formula,t))}),e}function Pb(e,t){return{...e,definition:Vb(e.sheetId,e.definition,t)}}v("Left"),v("Right"),Wm.add("UPDATE_CELL",function(e,t){const r=e.content&&Ob(e.sheetId,e.content,t);return{...e,content:r}}),Wm.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=>Ob(e.sheetId,r,t))};else if("ColorScaleRule"===r.type){const{minimum:n,maximum:o,midpoint:s}=r;e.cf.rule={...r,minimum:{...n,value:n.value&&Ob(e.sheetId,n.value,t)},maximum:{...o,value:o.value&&Ob(e.sheetId,o.value,t)},midpoint:s?{...s,value:Ob(e.sheetId,s.value,t)}:void 0}}else if("IconSetRule"===r.type){const{upperInflectionPoint:n,lowerInflectionPoint:o}=r;e.cf.rule={...r,upperInflectionPoint:{...n,value:Ob(e.sheetId,n.value,t)},lowerInflectionPoint:{...o,value:Ob(e.sheetId,o.value,t)}}}else"DataBarRule"===r.type&&(e.cf.rule={...r,rangeValues:r.rangeValues?Db(e.sheetId,r.rangeValues,t):void 0});return e}),Wm.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=>Ob(e.sheetId,r,t)),e}),Wm.add("ADD_PIVOT",Lb),Wm.add("UPDATE_PIVOT",Lb),Wm.add("CREATE_CHART",Pb),Wm.add("UPDATE_CHART",Pb);const kb=[{match:function(e){return"sheetId"in e},fn:Bb},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const r=Bb(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;const n=[];for(const r of e.target){const e=qm(r,t);e&&n.push(e)}if(!n.length)return"IGNORE_COMMAND";return{...e,target:n}}},{match:function(e){return"sheetId"in e&&"zone"in e},fn:function(e,t){const r=Bb(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;const n=qm(e.zone,t);if(n)return{...e,zone:n};return"IGNORE_COMMAND"}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const r=Bb(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const r="COL"===t.dimension?"col":"row";let n=e[r];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort((e,t)=>t-e);if(e.includes(n))return"IGNORE_COMMAND";for(const t of e)n>=t&&n--}"ADD_COLUMNS_ROWS"===t.type&&(n>t.base||n===t.base&&"before"===t.position)&&(n+=t.quantity);return{...e,[r]:n}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const r of t.target){if(!(e.col===r.left&&e.row===r.top)&&Qo(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=Bb(e,t);if("SKIP_TRANSFORMATION"!==r)return"IGNORE_COMMAND"===r?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"!==t.type&&"REMOVE_COLUMNS_ROWS"!==t.type)return"SKIP_TRANSFORMATION";if(t.dimension!==e.dimension)return e;let n=[];if("REMOVE_COLUMNS_ROWS"===t.type)n=Sm(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){n=Em(Re(t.position,t.base),t.quantity,e.elements)}if(0===n.length)return"IGNORE_COMMAND";return{...e,elements:n}}},{match:function(e){return"ranges"in e},fn:function(e,t){if(!("sheetId"in t))return e;const r=e.ranges.map(e=>Zm(e,t)).filter(Se);if(!r.length)return"IGNORE_COMMAND";return{...e,ranges:r}}}];function Ub(e,t){const r=Gm.getTransformation(e.type,t.type),n=r?r(e,t):function(e,t){for(const{match:r,fn:n}of kb)if(r(e)){const r=n(e,t);if("SKIP_TRANSFORMATION"===r)continue;if("IGNORE_COMMAND"===r)return;e=r}return e}(e,t);return n?function(e,t){const r=Wm.get(e.type);if(!r)return e;const n=Vm(t);if(n)return r(e,n);return e}(n,t):n}function Hb(e,t){let r=[...e];const n=new Set(Gm.getKeys());for(const e of t)(n.has(e.type)||Lm.contains(e.type))&&(r=r.reduce((t,r)=>{const n=Ub(r,e);return n&&t.push(n),t},[]));return r}function Bb(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 zb{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,r,n,o,s){this.rootCommand=n,this.timestamp=s,this.id=e,this.clientId=t,this._commands=[...r],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class $b extends Error{}class Gb extends ym{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new wo;lastLocalOperation;constructor(e,t,r=Y){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=r,this.debouncedMove=Te(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,r){if(!t.length||!r.length||!this.canApplyOptimisticUpdate())return;const n=new zb(this.uuidGenerator.uuidv4(),this.clientId,t,e,r,Date.now());this.revisions.append(n.id,n),"REQUEST_REDO"!==e.type&&(this.lastLocalOperation=n),this.trigger("new-local-state-update",{id:n.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:n.id,clientId:n.clientId,commands:n.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&(this._move(this.awaitingClientPosition),this.awaitingClientPosition=void 0)}loadInitialMessages(e){const t=performance.now(),r=e.reduce((e,t)=>e+("REMOTE_REVISION"===t.type?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug("Replayed",r,"commands in",performance.now()-t,"ms")}async leave(e){e&&1===Object.keys(this.clients).length&&this.lastRevisionMessage&&"SNAPSHOT_CREATED"!==this.lastRevisionMessage?.type&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}async snapshot(e){if(0!==this.pendingMessages.length)return;const t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({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 $b("The client left the session");return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(Se))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return void(this.awaitingClientPosition=e);const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const r=t?"CLIENT_MOVED":"CLIENT_JOINED",n=this.getCurrentClient();this.clients[this.clientId]={...n,position:e},this.transportService.sendMessage({type:r,version:1,client:{...n,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:r,timestamp:n}=e,o=new zb(e.nextRevisionId,t,r,void 0,void 0,n);if(o.clientId!==this.clientId){this.revisions.insert(o.id,o,e.serverRevisionId);const t=this.pendingMessages.filter(e=>"REMOTE_REVISION"===e.type).map(e=>e.commands).flat();this.trigger("remote-revision-received",{commands:Hb(r,t)})}break;case"SNAPSHOT_CREATED":{const t=new zb(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.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||this.sendPendingMessage()}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.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"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 Wb=(new fd).add("ADD_COLUMNS_ROWS",function(e){const t=[];let r=e.base;"after"===e.position&&r++;for(let n=0;n<e.quantity;n++)t.push(n+r);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}).add("REMOVE_COLUMNS_ROWS",function(e){const t=[],r=[...e.elements].sort((e,t)=>e-t);for(const n of ce(r)){const r=0===n[0]?0:n[0]-1,o=0===n[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:n.length,base:r,sheetId:e.sheetId,sheetName:e.sheetName,position:o})}return t}).add("ADD_MERGE",function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]}).add("REMOVE_MERGE",function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]}).add("CREATE_SHEET",function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId,sheetName:e.name}]}).add("DELETE_SHEET",function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1,name:e.sheetName}]}).add("DUPLICATE_SHEET",function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo,sheetName:""}]}).add("CREATE_FIGURE",function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]}).add("CREATE_CHART",function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]}).add("HIDE_COLUMNS_ROWS",function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}).add("UNHIDE_COLUMNS_ROWS",function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}).add("CREATE_TABLE_STYLE",function(e){return[{type:"REMOVE_TABLE_STYLE",tableStyleId:e.tableStyleId}]}).add("ADD_PIVOT",function(e){return[{type:"REMOVE_PIVOT",pivotId:e.pivotId}]}).add("RENAME_SHEET",function(e){return[{type:"RENAME_SHEET",sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]});for(const e of ys.values())Wb.contains(e)||Wb.add(e,qb);function qb(e){return[e]}function Zb(e){return Wb.get(e.type)(e)}class Yb{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find(t=>t.id===e);if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const r of this.operations){if(r.id===e)return e;if(r.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find(t=>t.id===e)}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map(e=>e.transformed(t))]}insert(e,t){const r=this.buildTransformation.with(e.data),{before:n,operation:o,after:s}=this.locateOperation(t);this.operations=[...n,o,e,...s.map(e=>e.transformed(r))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new Yb(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 jb{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new Xb(this.id,xe(()=>e(this.data)))}}class Xb{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new Xb(this.id,this.lazyData.map(e))}}class Kb{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new Kb(function*(e,t){for(const r of e)if(yield r,r.operation.id===t)return}(this.operations,e))}stopBefore(e){return new Kb(function*(e,t){for(const r of e){if(r.operation.id===t)return;yield r}}(this.operations,e))}startAfter(e){return new Kb(function*(e,t){let r=!0;for(const n of e)r||(yield n),n.operation.id===t&&(r=!1)}(this.operations,e))}}class Qb{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 Kb(ue(this._execution(e),this._execution(e)))}revertedExecution(e){return new Kb(ue(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const r=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),r&&this.insertPrevious(e,t,r)}insertOperationAfter(e,t,r){e.insert(t,r),this.updateNextWith(e,t,r),this.insertPrevious(e,t,r)}undo(e,t){const r=this.buildTransformation.without(t.data),n=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const o=e.fork(t.id);n&&this.branchingOperationIds.set(o,n),this.insertBranchAfter(e,o),this.transform(o,r)}redo(e){const t=this.nextBranch(e);if(!t)return;const r=this.nextBranch(t);this.removeBranchFromTree(t);const n=this.branchingOperationIds.get(t);n?this.branchingOperationIds.set(e,n):this.branchingOperationIds.delete(e),r&&this.rebaseUp(r)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const r of this.revertedExecution(e))if(r.operation.id===t)return r;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:r}=this.findPreviousBranchingOperation(e);if(!t||!r)return;const n=this.buildTransformation.without(r.data),o=t.fork(r.id);this.branchingOperationIds.set(o,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,o),o.transform(n);const s=this.nextBranch(o);s&&this.rebaseUp(s)}removeBranchFromTree(e){const t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){const r=this.branches.findIndex(t=>t===e);this.branches.splice(r+1,0,t)}updateNextWith(e,t,r){const n=this.branchingOperationIds.get(e),o=this.nextBranch(e);if(n&&o)if(e.getFirstOperationAmong(r,n)===n){const s=this.addToNextBranch(e,o,n,t,r);this.updateNextWith(o,s,r)}else{const e=this.buildTransformation.with(t.data);this.transform(o,e)}}addToNextBranch(e,t,r,n,o){let s=n;return o===r?(s=this.getTransformedOperation(e,r,n),t.prepend(s)):t.contains(o)?(s=this.getTransformedOperation(e,r,n),t.insert(s,o)):t.append(n),s}getTransformedOperation(e,t,r){const n=e.getOperation(t),o=this.buildTransformation.without(n.data);return r.transformed(o)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const r=this.nextBranch(e);r&&this.transform(r,t)}insertPrevious(e,t,r){const{previousBranch:n,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!n||!o)return;const s=this.buildTransformation.with(o.data),i=e.fork(r);i.transform(s),n.cutAfter(r),n.appendBranch(i);const a=t.transformed(s);this.insertPrevious(n,a,r)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const r=this.branchingOperationIds.get(t);return r?{previousBranch:t,branchingOperation:t.getOperation(r)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex(t=>t===e);if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex(t=>t===e);if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let r=!!t;const n=e.getOperations();for(let o=n.length-1;o>=0;o--){const s=n[o];s.id===t&&(r=!1),r||(yield{operation:s,branch:e,isCancelled:!this.shouldExecute(e,s)})}const o=this.previousBranch(e);yield*o?this._revertedExecution(o):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class Jb{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 Yb(this.buildTransformation),this.tree=new Qb(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,r=new jb(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 jb(e,t),n=this.tree.getLastBranch();this.tree.insertOperationLast(n,r),this.HEAD_BRANCH=n,this.HEAD_OPERATION=r}insert(e,t,r){const n=new jb(e,t);this.revertTo(r),this.tree.insertOperationAfter(this.HEAD_BRANCH,n,r),this.fastForward()}undo(e,t,r){const{branch:n,operation:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(n,o),this.fastForward(),this.insert(t,this.buildEmpty(t),r)}redo(e,t,r){const{branch:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(n),this.fastForward(),this.insert(t,this.buildEmpty(t),r)}rebase(e){const t=this.get(e),r=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);const n=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,n);for(const{operation:e}of r)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:r,isCancelled:n}of e)n||this.revertOperation(r.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:r,isCancelled:n}of e)n||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=r}}function ev(e){return new Jb({initialOperationId:e.initialRevisionId,applyOperation:t=>{const r=t.commands.slice(),{changes:n}=e.recordChanges(()=>{for(const t of r)e.dispatch(t)});t.setChanges(n)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){tv(t.changes[e])}}([e]),buildEmpty:e=>new zb(e,"empty",[]),buildTransformation:{with:e=>t=>new zb(t.id,t.clientId,Hb(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new zb(t.id,t.clientId,Hb(t.commands,e.commands.map(Zb).flat()),t.rootCommand,void 0,t.timestamp)}})}function tv(e){const t=e.target,r=e.key,n=e.before;void 0===n?delete t[r]:t[r]=n}class rv{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const nv=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart","comboChart","radarChart"],ov="M256 9 a247 247 0 1 0.1 0 0";function sv(e){return{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:e.textColor||k,path:"M120 195 h270 l-135 130"}]}}const iv="M40 185 h270 l-135 128";function av(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||k,path:iv}]}}function lv(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||k,path:"M0,225 A175,175 0 1,0 350,225 A175,175 0 1,0 0,225"},{fillColor:e.fillColor||k,path:iv}]}}const cv={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"}]},uv={name:"CHECKBOX_UNCHECKED",width:512,height:512,paths:[{fillColor:U,path:"M45,45 h422 v422 h-422 v-422 m30,30 v362 h362 v-362"}]},hv={name:"CHECKBOX_CHECKED",width:512,height:512,paths:[{fillColor:U,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 dv(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?P:"#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 fv={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:ov}]}},dotNeutral:{template:"YELLOW_DOT",svg:{name:"YELLOW_DOT",width:512,height:512,paths:[{fillColor:"#F0AD4E",path:ov}]}},dotBad:{template:"RED_DOT",svg:{name:"RED_DOT",width:512,height:512,paths:[{fillColor:"#E06666",path:ov}]}}},gv={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("/"),n=t.split("/");let o="",s=0;for(let e=0;e<r.length-1;e++)r[e]===n[e]?s++:o+="../";return o+=n.slice(s).join("/"),o}function pv(e,t=0){const r={};for(let n=0;n<e.length;n++)e[n]&&(r[n+t]=e[n]);return r}function bv(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}function vv(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 yv(e){if("="===e[0])return e;const t=Ml(e);return 1===t.length&&"REFERENCE"!==t[0].type?e:"="+e}var wv;!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"}(wv||(wv={}));class Ev{_parsingWarnings=new Set;_conversionWarnings=new Set;addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,r){let n=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;r&&(n+=`Only ${r.join(", ")} are currently supported.`),this._conversionWarnings.has(n)||this._conversionWarnings.add(n)}}const Sv=["thin","medium","thick","dashed","dotted"],Cv=["general","left","center","right"],Tv=["top","center","bottom"],Iv=["Arial"],xv=["solid","none"],Rv=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWithText","containsBlanks","notContainsBlanks"],Av={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},_v={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"},Ov={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},Dv={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},Fv={top:"top",middle:"center",bottom:"bottom"},Nv={beginsWith:"beginsWithText",endsWith:"endsWithText",containsText:"containsText",notContains:"notContainsText",between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},Mv={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},Vv={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},Lv={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"},Pv={none:"none",b:"bottom",t:"top",l:"left",r:"right",tr:"right"},kv={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"},Uv={exp:"exponential",log:"logarithmic",poly:"polynomial",movingAvg:"trailingMovingAverage"},Hv={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"},Bv={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:"@"},zv={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},$v={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"},Gv={"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"},Wv={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"},qv={between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},Zv={between:"dateIsBetween",notBetween:"dateIsNotBetween",equal:"dateIs",greaterThan:"dateIsAfter",greaterThanOrEqual:"dateIsOnOrAfter",lessThan:"dateIsBefore",lessThanOrEqual:"dateIsOnOrBefore"};function Yv(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=jp;else{if(!e.indexed)return;t=$v[e.indexed]}var r;return t=6===(r=t).length?"#"+r+"FF":"#"+r.slice(2)+r.slice(0,2),e.tint&&(t=function(e,t){const r=op(e),n=ip(r);t<0&&(n.l=n.l*(1+t));t>0&&(n.l=n.l*(1-t)+(100-100*(1-t)));return np(sp(n))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function jv(e){return 9===e.length&&(e=e.slice(0,7)),parseInt(e.replace("#",""),16)}const Xv=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function Kv(e,t,r){const n=Bv[e]||t.find(t=>t.id===e)?.format;if("General"!==n){if(n)try{let e=n.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]");if(e=e.replace(/\[\$\]/g,""),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),function(e){return Xv.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 Fn(0,{format:e,locale:Dl}),!0}catch(e){return!1}}(e))return e}catch(e){}r.generateNotSupportedWarning(wv.NumFmtIdNotSupported,n||`nmFmtId ${e}`)}}function Qv(e,t){const r=e.borders.map(e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(wv.DiagonalBorderNotSupported)}(e,t);const r={top:Jv(e.top,t),bottom:Jv(e.bottom,t),left:Jv(e.left,t),right:Jv(e.right,t)};return Object.keys(r).forEach(e=>void 0===r[e]&&delete r[e]),r});return pv(r,1)}function Jv(e,t){if(!e)return;!function(e,t){Sv.includes(e.style)||t.generateNotSupportedWarning(wv.BorderStyleNotSupported,e.style,Sv)}(e,t);const r=_v[e.style];return r?{style:r,color:Yv(e.color)}:void 0}function ey(e,t){return pv(e.styles.map(r=>ty({fontStyle:e.fonts[r.fontId],fillStyle:e.fills[r.fillId],alignment:r.alignment},t)),1)}function ty(e,t){return function(e,t,r){e&&e.name&&!Iv.includes(e.name)&&r.generateNotSupportedWarning(wv.FontNotSupported,e.name,Iv);t&&t.patternType&&!xv.includes(t.patternType)&&r.generateNotSupportedWarning(wv.FillStyleNotSupported,t.patternType,xv)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!Cv.includes(e)&&t.generateNotSupportedWarning(wv.HorizontalAlignmentNotSupported,e,Cv)}(e?.alignment?.horizontal,t),function(e,t){e&&!Tv.includes(e)&&t.generateNotSupportedWarning(wv.VerticalAlignmentNotSupported,e,Tv)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?Dv[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?Ov[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?Yv(e.fillStyle?.fgColor):Yv(e.fillStyle?.bgColor),textColor:Yv(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function ry(e,t){const r=[];for(const n of e.styles){const o=Kv(n.numFmtId,e.numFmts,t);o&&(r[n.numFmtId]=o)}return pv(r,1)}function ny(e,t,r){const n=[];let o=1;for(const s of e){if(0===s.cfRules.length)continue;ly(s,t,r);const e=s.cfRules[0];let i;const a=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type||"dataBar"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"duplicateValues":case"top10":case"uniqueValues":case"timePeriod":continue;case"dataBar":const t=oy(o++,s);t&&n.push(t);continue;case"colorScale":const l=sy(o++,s);l&&n.push(l);continue;case"iconSet":const c=iy(o++,s,r);c&&n.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;i=Mv[e.type],a.push(e.text);break;case"expression":if(!e.formula?.length)continue;i=Mv[e.type],a.push(`=${e.formula[0]}`);break;case"containsBlanks":case"notContainsBlanks":i=Mv[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;i=Nv[e.operator],a.push(yv(e.formula[0])),2===e.formula.length&&a.push(yv(e.formula[1]))}i&&void 0!==e.dxfId&&n.push({id:(o++).toString(),ranges:s.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:i,values:a,style:ty({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},r)}})}}return n}function oy(e,t){const r=t.cfRules[0].dataBar;if(!r)return;const n=jv(Yv(r.color)||"#FFFFFF");return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"DataBarRule",color:n}}}function sy(e,t){const r=t.cfRules[0].colorScale;if(!r||r.cfvos.length!==r.colors.length||r.cfvos.length<2||r.cfvos.length>3)return;const n=[];for(let e=0;e<r.cfvos.length;e++)n.push({color:jv(Yv(r.colors[e])||"#FFFFFF"),type:Vv[r.cfvos[e].type],value:r.cfvos[e].value});const o=n[0],s=2===n.length?n[1]:n[2],i=3===n.length?n[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:o,midpoint:i,maximum:s}}}function iy(e,t,r){const n=t.cfRules[0].iconSet;if(!n)return;let o=n.cfvos,s=n.cfIcons;if(o.length<3||s&&s.length<3)return;o.length>3&&(o=[o[0],o[Math.floor(o.length/2)],o[o.length-1]]),s&&s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]);const i=[];for(let e=1;e<=2;e++){const t=Vv[o[e].type];if("value"===t)return;i.push({value:o[e].value||"",operator:o[e].gte?"ge":"gt",type:t})}let a={lower:s?ay(s[0].iconSet,s[0].iconId):ay(n.iconSet,0),middle:s?ay(s[1].iconSet,s[1].iconId):ay(n.iconSet,1),upper:s?ay(s[2].iconSet,s[2].iconId):ay(n.iconSet,2)};n.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(const e of Object.keys(a))if(!a[e])switch(r.generateNotSupportedWarning(wv.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=gv.dots.good;break;case"middle":a[e]=gv.dots.neutral;break;case"lower":a[e]=gv.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 ay(e,t){const r=Lv[e];return r?0===t?gv[r].bad:1===t?gv[r].neutral:gv[r].good:""}function ly(e,t,r){if(e.cfRules.length>1&&r.generateNotSupportedWarning(wv.MultipleRulesCfNotSupported),Rv.includes(e.cfRules[0].type)||r.generateNotSupportedWarning(wv.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const n=t[e.cfRules[0].dxfId];n.border&&r.generateNotSupportedWarning(wv.CfFormatBorderNotSupported),n.alignment&&r.generateNotSupportedWarning(wv.CfFormatAlignmentNotSupported),n.numFmt&&r.generateNotSupportedWarning(wv.CfFormatNumFmtNotSupported)}}const cy=new WeakMap,uy=new WeakMap;function hy(e,t){cy.has(t)||(cy.set(t,new Map),uy.set(t,0));const r=cy.get(t),n=gy(e);if(r.has(n)){const o=r.get(n);return t[o]=e,o}const o=uy.get(t)+1;return r.set(n,o),uy.set(t,o),t[o]=e,o}function dy(e){const t={};for(const r in e){const n=Fo(e[r].map(ss));for(const e of n)t[Go(e)]=Number(r)}return t}function*fy(e,t){for(const r in t){const n=Bo(r),o=t[r];for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++){const n={sheetId:e,col:r,row:t};yield[n,o]}}}function gy(e){if(null===e)return"null";if(void 0===e)return"undefined";if("object"!=typeof e)return String(e);if(Array.isArray(e)){const t=e.length;let r="[";for(let n=0;n<t;n++)n>0&&(r+=","),r+=gy(e[n]);return r+"]"}const t=Object.keys(e).sort();let r="{";for(const n of t)void 0!==e[n]&&(r+=`"${n}":${gy(e[n])},`);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":return"greaterThan";case"isGreaterOrEqualTo":return"greaterThanOrEqual";case"isLessThan":return"lessThan";case"isLessOrEqualTo":return"lessThanOrEqual";case"isBetween":return"between";case"isNotBetween":return"notBetween";case"isEqual":return"equal";case"isNotEqual":return"notEqual";case"customFormula":return""}}function py(e){return Math.round(Cb*e*100)/100}function by(e){return Math.round(Tb*e*100)/100}function vy(e){return e?Math.round(e/Cb*100)/100:e}function yy(e){return e?Math.round(e/Tb*100)/100:e}function wy(e,t,r,n,o){const s=r?e.styles[r]:{},i=n?e.formats[n]:void 0,a={font:{size:s?.fontSize||q,color:{rgb:s?.textColor?s.textColor:"000000"},family:2,name:"Arial"},fill:s?.fillColor?{fgColor:{rgb:s.fillColor}}:{reservedAttribute:"none"},numFmt:i?{format:i,id:0}:void 0,border:o||0,alignment:{horizontal:s.align,vertical:s.verticalAlign?Fv[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 Ey(e,t){const r=function(e,t){if(!e)return 0;let r=zv[e.format];r||(r=Ty(e,t)+164);return r}(t.numFmt,e.numFmts),n={fontId:Ty(t.font,e.fonts),fillId:Ty(t.fill,e.fills),borderId:t.border,numFmtId:r,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText}};return Ty(n,e.styles)}function Sy(e,t,r){const n=e.find(e=>e.path===t);let o;return n?(o=`rId${(n.rels.length+1).toString()}`,n.rels.push({...r,id:o})):(o="rId1",e.push({path:t,rels:[{...r,id:o}]})),o}const Cy=new WeakMap;function Ty(e,t){let r=Cy.get(t);if(!r){r=new Map;for(let e=0;e<t.length;e++){const n=gy(t[e]);r.set(n,e)}Cy.set(t,r)}const n=gy(e);if(r.has(n))return r.get(n);const o=t.length;return t.push(e),r.set(n,o),o}function Iy(e,t){const r=t.chartIds.findIndex(t=>t===e);return-1===r?(t.chartIds.push(e),t.chartIds.length):r+1}const xy=[];function Ry(e){const t=xy.findIndex(t=>t===e);return-1===t?(xy.push(e),xy.length):t+1}function Ay(e){return Math.round(914400*e/96)}function _y(e,t,r){let n,o,s=e;if(({xc:s,sheetName:n}=go(e)),n){const e=r.sheets.findIndex(e=>Im(e.name,n));if(e<0)throw new Error("Unable to find a sheet with the name "+n);o=e}else o=Number(t);const i=Ho(s);return void 0===i.right&&(i.right=r.sheets[o].colNumber),void 0===i.bottom&&(i.bottom=r.sheets[o].rowNumber),(i.right-i.left+1)*(i.bottom-i.top+1)}function Oy(e){return Math.round(96*e/914400)}function Dy(e,t){let r=0;for(let n=0;n<e;n++){const e=t.cols.find(e=>n>=e.min&&n<=e.max);e?.width?r+=e.width:t.sheetFormat?.defaultColWidth?r+=t.sheetFormat.defaultColWidth:r+=Ib}return r/Tb}function Fy(e,t){let r=0;for(let n=0;n<e;n++){const e=t.rows.find(e=>e.index-1===n);e?.height?r+=e.height:t.sheetFormat?.defaultRowHeight?r+=t.sheetFormat.defaultRowHeight:r+=xb}return r/Cb}function Ny(e){let t=1;return e.figures.map(r=>function(e,t,r){let n,o,s,i,a;if(1===e.anchors.length)({col:n,row:o,offset:s}=Py(e.anchors[0])),a=Oy(e.figureSize.cx),i=Oy(e.figureSize.cy);else{({col:n,row:o,offset:s}=Py(e.anchors[0]));const{x:t,y:l}=ky(e.anchors[0],r),{x:c,y:u}=ky(e.anchors[1],r);a=c-t,i=u-l}const l={id:t,col:n,row:o,offset:s};if("dataSets"in(c=e.data)&&c.dataSets.length>0)return{...l,width:a,height:i,tag:"chart",data:My(e.data)};if(function(e){return"imageSrc"in e}(e.data))return{...l,width:Oy(e.data.size.cx),height:Oy(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 My(e){const t=e.dataSets.some(e=>"reference"in(e.label??{})),r=e.labelRange?Vy(e.labelRange,t):void 0,n=e.dataSets.map(e=>{let r;return e.label&&"text"in e.label&&(r=e.label.text),{dataRange:Vy(e.range,t),label:r,backgroundColor:e.backgroundColor,trend:Ly(e.trend)}});"pie"===e.type&&n.reverse();const o={range:n,dataSetsHaveTitle:t,auxiliaryRange:r,title:e.title??{text:""},background:Yv({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 Yp.get(e.type).getChartDefinitionFromContextCreation(o)}catch(e){return}}function Vy(e,t){const{sheetName:r,xc:n}=go(e);let o=Ho(n);if(t&&void 0!==o.bottom&&void 0!==o.right){const e=o.bottom-o.top+1,t=o.right-o.left+1;1===e?o={...o,left:o.left-1}:1===t&&(o={...o,top:o.top-1})}return mo(r,Go(o))}function Ly(e){if(e&&e.type)return{type:"linear"===e.type?"polynomial":Uv[e.type],order:"linear"===e.type?1:e.order,color:e.color,window:e.window||2,display:!0}}function Py(e){const t={x:Oy(e.colOffset)-1,y:Oy(e.rowOffset)-1};return{col:e.col,row:e.row,offset:t}}function ky(e,t){return{x:Dy(e.col,t)+Oy(e.colOffset),y:Fy(e.row,t)+Oy(e.rowOffset)}}function Uy(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const Hy=new fd;function By(e,t){return{url:e=Uy(e),label:t||e,isExternal:!0,isUrlEditable:!0}}Hy.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 zy={createLink:By,match:e=>me(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function $y(e){if("string"==typeof e){if(ge(e)){const{label:t,url:r}=be(e);return function(e){return Hy.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||zy}(r).createLink(r,t)}return me(e)?By(e):void 0}}function Gy(e,t,r){return qy({value:Qn(t.format)&&null!==e.parsedValue?e.content:e.parsedValue,format:t.format,origin:r},t.locale)}function Wy(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,Dl))return Dt(e,Dl);const r=gt(e,t);return r?r.value:he(e)?"TRUE"===e.toUpperCase():e}function qy(e,t=Dl,r,n){const o=$y(e.value);if(!o){return Xy(Zy(e,t,r),e.origin??n)}const s=Wy(o.label,t);return Xy({...Zy({value:s,format:e.format||("number"==typeof s?Gn(o.label,t)||Wn(o.label):void 0)},t,r),link:o},e.origin??n)}function Zy(e,t,r){let{value:n,format:o,message:s}=e;o=r?.format||o;const i=Fn(n,{format:o,locale:t});return Vt(n)?function(e,t){return{value:e,formattedValue:e,message:t,type:Eu.error,isAutoSummable:!1,defaultAlign:"center"}}(n,s):null===n?jy(o):Qn(o)?Yy($t(n),o,i):"number"==typeof n?Hn(o||"")?function(e,t,r){return{value:e,format:t,formattedValue:r,type:Eu.number,isAutoSummable:!1,defaultAlign:"right"}}(n,o,i):function(e,t,r){return{value:e||0,format:t,formattedValue:r,type:Eu.number,isAutoSummable:!0,defaultAlign:"right"}}(n,o,i):"boolean"==typeof n?function(e,t,r){return{value:e,format:t,formattedValue:r,type:Eu.boolean,isAutoSummable:!1,defaultAlign:"center"}}(n,o,i):Yy(n,o,i)}function Yy(e,t,r){return{value:e,format:t,formattedValue:r,type:Eu.text,isAutoSummable:!0,defaultAlign:"left"}}const jy=Ue(function(e){return{value:null,format:e,formattedValue:"",type:Eu.empty,isAutoSummable:!0,defaultAlign:"left"}});function Xy(e,t){return null===e.value||"origin"in e||(e.origin=t),e}function Ky(e){const t=Qe.now();switch(e){case"today":return bt(t);case"yesterday":return bt(Qe.fromTimestamp(t.setDate(t.getDate()-1)));case"tomorrow":return bt(Qe.fromTimestamp(t.setDate(t.getDate()+1)));case"lastWeek":return bt(Qe.fromTimestamp(t.setDate(t.getDate()-7)));case"lastMonth":return bt(Qe.fromTimestamp(t.setMonth(t.getMonth()-1)));case"lastYear":return bt(Qe.fromTimestamp(t.setFullYear(t.getFullYear()-1)))}}function Qy(e,t){return"dateValue"in e&&"exactDate"!==e.dateValue?[Ky(e.dateValue)]:e.values.map(e=>ht(e,t))}function Jy(e,t){return e.map(e=>{if(e.startsWith("="))return e;const r=Wy(e,t);return"number"==typeof r?Fn(r,{format:t.dateFormat,locale:t}):""})}function ew(e,t){const r=[];let n=1;for(const o of e)if(o)switch(o.type){case"time":t.generateNotSupportedWarning(wv.TimeDataValidationNotSupported);break;case"textLength":t.generateNotSupportedWarning(wv.TextLengthDataValidationNotSupported);break;case"whole":t.generateNotSupportedWarning(wv.WholeNumberDataValidationNotSupported);break;case"decimal":const e=tw(n++,o);r.push(e);break;case"list":const s=rw(n++,o);r.push(s);break;case"date":if("notEqual"===o.operator){t.generateNotSupportedWarning(wv.NotEqualDateDataValidationNotSupported);break}const i=nw(n++,o);r.push(i);break;case"custom":const a=ow(n++,o);r.push(a)}return r}function tw(e,t){const r=[yv(t.formula1.toString())];return t.formula2&&r.push(yv(t.formula2.toString())),{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:qv[t.operator],values:r}}}function rw(e,t){const r=t.formula1.toString(),n=ao.test(r);return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:n?"isValueInRange":"isValueInList",values:n?[r]:r.replaceAll('"',"").split(","),displayStyle:"arrow"}}}function nw(e,t){let r;const n=[yv(t.formula1.toString())];return t.formula2?(n.push(yv(t.formula2.toString())),r={type:Zv[t.operator],values:Jy(n,Dl)}):r={type:Zv[t.operator],values:Jy(n,Dl),dateValue:"exactDate"},{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:r}}function ow(e,t){return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:"customFormula",values:[yv(t.formula1.toString())]}}}const sw=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),iw=new RegExp(/SUBTOTAL\(([0-9]*),/g),aw=new RegExp(to.source,"ig");function lw(e,t){const r=function(e){const t={};for(const r of e.rows)for(const e of r.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(const n of e.rows.map(e=>e.cells).flat())n?.formula&&(n.formula.content=void 0===n.formula.sharedIndex||n.formula.content?"="+n.formula.content:"="+uw(n.xc,r[n.formula.sharedIndex]),n.formula.content=cw(n.formula.content,t))}function cw(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(iw,(e,t)=>{const r=Hv[t];return r?r+"(":e})).replace(sw,(e,r,n,o)=>{r=Number(r)-1,o=o.replace(/\$/g,"");const s=t.externalBooks[r].sheetNames.findIndex(e=>Im(e,n));if(-1===s)return e;const i=t.externalBooks[r].datasets.find(e=>e.sheetId===s)?.data;if(!i)return e;const a=i&&i[o];return(Number(a)?a:`"${a}"`)||e})}function uw(e,t){const r=Oo(t.refCellXc);let n,o=t.formula.slice();do{if(n=aw.exec(o),n){const t=Oo(n[0].replace("$","")),s=Oo(e),i={colFixed:n[0].startsWith("$"),rowFixed:n[0].includes("$",1)},a={col:s.col-r.col,row:s.row-r.row},l={col:i.colFixed?t.col:t.col+a.col,row:i.rowFixed?t.row:t.row+a.row};o=o.slice(0,n.index)+Do(l.col,l.row,i)+o.slice(n.index+n[0].length)}}while(n);return o}function hw(e,t){return e.sheets.map(r=>{lw(r,e);const n=function(e){const t=[0,0];for(const r of e.rows)t[0]=Math.max(t[0],We(r.cells.map(e=>Oo(e.xc).col))),t[1]=Math.max(t[1],r.index);for(const r of e.figures)t[0]=Math.max(t[0],r.anchors[r.anchors.length-1]?.col??0),t[1]=Math.max(t[1],r.anchors[r.anchors.length-1]?.row??0);return t[0]=Math.max(t[0]+5,30),t[1]=Math.max(t[1]+5,100),t}(r),o=r.sheetViews[0],s=pw(r,"ROW",n[1]),i=pw(r,"COL",n[0]);return{id:r.sheetName,areGridLinesVisible:!o||o.showGridLines,name:r.sheetName,colNumber:n[0],rowNumber:n[1],...gw(r,e,n,t),merges:r.merges,cols:dw(r,n[0],i),rows:fw(r,n[1],s),conditionalFormats:ny(r.cfs,e.dxfs,t),dataValidationRules:ew(r.dataValidations,t),figures:Ny(r),isVisible:r.isVisible,panes:o?{xSplit:o.pane.xSplit,ySplit:o.pane.ySplit}:{xSplit:0,ySplit:0},tables:[],headerGroups:{COL:i,ROW:s},color:Yv(r.sheetProperties?.tabColor)}})}function dw(e,t,r){const n={};for(let o=1;o<t+1;o++){const t=e.cols.find(e=>e.min<=o&&o<=e.max);let s;s=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:Ib;const i=o-1,a=r.some(e=>e.isFolded&&e.start<=i&&i<=e.end);n[i]={size:yy(s),isHidden:!a&&t?.hidden}}return n}function fw(e,t,r){const n={};for(let o=1;o<t+1;o++){const t=e.rows.find(e=>e.index===o);let s;s=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:xb;const i=o-1,a=r.some(e=>e.isFolded&&e.start<=i&&i<=e.end);n[i]={size:vy(s),isHidden:!a&&t?.hidden}}return n}function gw(e,t,r,n){const o={},s={},i={},a={},l=t.sharedStrings.map(Pe);const c=e.hyperlinks.reduce((e,t)=>(e[t.xc]=t,e),{});for(const r of e.rows)for(const e of r.cells)o[e.xc]=mw(e,c,l,n),e.styleIndex&&(s[e.xc]=e.styleIndex+1,i[e.xc]=t.styles[e.styleIndex].numFmtId+1,a[e.xc]=t.styles[e.styleIndex].borderId+1);for(const n of e.rows.filter(e=>e.styleIndex))for(let e=1;e<=r[0];e++){const r=Do(e-1,n.index-1);s[r]??=n.styleIndex+1,a[r]??=t.styles[n.styleIndex].borderId+1,i[r]??=t.styles[n.styleIndex].numFmtId+1}for(const n of e.cols.filter(e=>e.styleIndex))for(let e=n.min;e<=Math.min(n.max,r[0]);e++)for(let o=1;o<=r[1];o++){const r=Do(e-1,o-1);s[r]??=n.styleIndex+1,a[r]??=t.styles[n.styleIndex].borderId+1,i[r]??=t.styles[n.styleIndex].numFmtId+1}return{cells:o,styles:s,formats:i,borders:a}}function mw(e,t,r,n){let o;switch(e.type){case"sharedString":o=r[parseInt(e.value,10)];break;case"boolean":o=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":o=e.value}return o&&t[e.xc]&&(o=function(e,t,r){const n=e.display||t;e.relTarget||e.location||r.generateNotSupportedWarning(wv.BadlyFormattedHyperlink);const o=e.relTarget?e.relTarget:we(go(e.location).sheetName);return pe(n,o)}(t[e.xc],o,n)),e.formula&&(o=e.formula.content),o}function pw(e,t,r){const n=e?.sheetProperties?.outlinePr,o=[];let s=0;for(let i=0;i<r;i++){const r=vw(e,t,i),a=r?.outlineLevel||0;if(a>s){const r=bw(e,t,i,("ROW"===t?n?.summaryBelow:n?.summaryRight)??!0);r&&o.push(r)}s=a}return o}function bw(e,t,r,n){const o=vw(e,t,r),s=o?.outlineLevel;if(!s||!s)return;let i=s,a=r,l=o;for(;l&&i>=s;)a++,l=vw(e,t,a),i=l?.outlineLevel||0;const c=r,u=a-1,h=vw(e,t,n?u+1:c-1);return{start:c-1,end:u-1,isFolded:h?.collapsed||!1}}function vw(e,t,r){return"COL"===t?e.cols.find(e=>e.min<=r&&r<=e.max):e.rows.find(e=>e.index===r)}function yw(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:ww(e)});for(const e of r.pivotTables)t.tables.push({range:e.location.ref,config:Ew(e)})}}!function(e,t){let r=null;for(const n of e){const o=t.find(e=>Im(e.sheetName,n.name)).tables;if(o&&0!==o.length){r||(r=Sw(e));for(const t of o)for(const o in r){const s=e.find(e=>e.id===o);for(const e in r[o]){for(let i=r[o][e].length-3;i>=0;i-=2){const a=r[o][e][i];if(!a.endsWith(t.name))continue;const l=r[o][e][i+1],c=Cw(n.id===s.id?"":n.name+"!",l,t,e);r[o][e][i+2]=a.slice(0,a.indexOf(t.name))+c+r[o][e][i+2],r[o][e].splice(i,2)}}}}}if(!r)return;for(const t in r){const n=e.find(e=>e.id===t);for(const e in r[t]){const o=r[t][e];if(1===o.length){n.cells[e]=o[0];continue}let s="";for(let e=0;e<o.length;e+=2)s+=o[e]+"["+o[e+1]+"]";s+=o[o.length-1],n.cells[e]=s}}}(e.sheets,t.sheets)}function ww(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:Hp[t]?t:Tp.styleId}}function Ew(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:Tp.styleId}}function Sw(e){const t={};for(const r of e)for(const e in r.cells){const n=r.cells[e];if(!n||!n.startsWith("="))continue;const o=n.indexOf("[");if(-1===o)continue;const s=[];let i=n.slice(0,o),a="",l=1,c=0,u=o;for(let e=o+1;e<n.length;e++)"["!==n[e]?"]"===n[e]&&(l--,0===l&&(a=n.slice(u+1,e),s.push(i),s.push(a),c=e+1)):(0===l&&(i=n.slice(c,e),u=e),l++);s.length&&(t[r.id]||(t[r.id]={}),s.push(n.slice(c)),t[r.id][e]=[...s])}return t}function Cw(e,t,r,n){const o=t.split(",").map(e=>e.trim()),s=Bo(r.ref),i=[],a=[],l=[];for(const e of o)if(Tw(e).startsWith("#")){const t=Tw(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(Oo(n).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(Tw);if(i.length)return w.InvalidReference;const n=r.cols.findIndex(e=>e.name===t[0]);if(-1===n)return w.InvalidReference;if(i.push(n+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+Go({top:Math.min(...a),left:Math.min(...i),bottom:Math.max(...a),right:Math.max(...i)})}function Tw(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,e.length-1):e}function Iw(e,t,r){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:r}}function xw(e){return String(e).replace(/\&/g,"&").replace(/\</g,"<").replace(/\>/g,">").replace(/\"/g,""").replace(/\'/g,"'").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function Rw(e){return new rv(e.map(([e,t])=>`${e}="${xw(t)}"`).join(" "))}function Aw(e,t="text/xml"){const r=(new DOMParser).parseFromString(e.toString(),t),n=r.querySelector("parsererror");if(n){const t=n.innerHTML,r=parseInt(t.split(":")[0],10),o=e.toString().trim().split("\n"),s=o.slice(Math.max(r-3,0),Math.min(r+2,o.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${s}`)}return r}function _w(e){if(e)return{style:e.style,color:{rgb:e.color}}}function Ow(e,t){return Fw`
|
|
2
2
|
<Override ContentType="${t}" PartName="${e}" />
|
|
3
3
|
`}function Dw(e){return new rv(e.join("\n"))}function Fw(e,...t){const r=[e[0]];for(let n=0;n<t.length;n++){const o=t[n]instanceof rv?t[n]:xw(t[n]);r.push(o+e[n+1])}return new rv(Ie(r))}function Nw(e){return e.replace(/NAMESPACE.*NAMESPACE(.*)/,"$1")}function Mw(e){return e.replaceAll(/(<\/?)([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"$1NAMESPACE$2NAMESPACE$3")}function Vw(e){return e.replaceAll(/([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"NAMESPACE$1NAMESPACE$2")}class Lw{value;constructor(e){this.value=e}asString(){return bv(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class Pw{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;constructor(e,t,r){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=r,this.relationships={},e.rels&&this.extractRelationships(e.rels).map(e=>{this.relationships[e.id]=e})}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()}))}getListOfXMLFiles(){return Object.entries(this.xlsxFileStructure).filter(([e])=>"images"!==e).map(([e,t])=>t).flat().filter(Se)}mapOnElements(e,t){const r=[],n=this.currentFile;let o;if(e.children){const t=this.querySelector(e.parent,e.query)?.children;o=t||[]}else o=this.querySelectorAll(e.parent,e.query);if(o)for(const e of o)try{r.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=n,r}catchErrorOnElement(e,t){const r=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([r,e.message].join("\n"))}extractAttr(e,t,r){const n=e.attributes[t];n||this.handleMissingValue(e,`attribute "${t}"`,r);const o=n?.value?n.value:r?.default;return void 0===o?void 0:new Lw(o)}extractTextContent(e,t){if(void 0!==t?.default&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const r="preserve"===e?.attributes["xml:space"]?.value;let n=e?.textContent;return e&&null!==n||this.handleMissingValue(e,"text content",t),n&&(n=r?n:n.trim()),n?bv(n):t?.default}extractChildAttr(e,t,r,n){let o;o="number"==typeof t?e.children[t]:this.querySelector(e,t),o||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,n);const s=o?this.extractAttr(o,r,n)?.asString():n?.default;return void 0!==s?new Lw(s):void 0}extractChildTextContent(e,t,r){if(void 0!==r?.default&&"string"!=typeof r.default)throw new Error("extractTextContent default value should be a string");const n=this.querySelector(e,t);return n||this.handleMissingValue(e,`child <${t}>`,r),n?this.extractTextContent(n,r):r?.default}handleMissingValue(e,t,r){if(r?.required){if(void 0===r?.default)throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${r.default}`)}}extractColor(e,t,r){if(!e)return r?{rgb:r}:void 0;const n=this.extractAttr(e,"theme")?.asString();let o;if(void 0!==n){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");o=this.getThemeColor(n,t.clrScheme)}else o=this.extractAttr(e,"rgb")?.asString(),o="FF000000"===o?void 0:o;return{rgb:o||r,auto:this.extractAttr(e,"auto")?.asBool(),indexed:this.extractAttr(e,"indexed")?.asNum(),tint:this.extractAttr(e,"tint")?.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");const t=this.processRelationshipTargetName(e.target),r=this.getListOfXMLFiles().find(e=>e.file.fileName.endsWith(t));if(!r||!r.file)throw new Error("Cannot find target file");return r}getTargetImageFile(e){if(!e)throw new Error("Undefined target file");const t=this.processRelationshipTargetName(e.target),r=this.xlsxFileStructure.images.find(e=>e.fileName.endsWith(t));if(!r)throw new Error("Cannot find target file");return r}querySelector(e,t){const r=Vw(t);return e.querySelector(r)}querySelectorAll(e,t){const r=Vw(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 kw extends Pw{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:jp}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:jp}).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 Uw extends Pw{theme;constructor(e,t,r,n){super(e,t,r),this.theme=n}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},e=>({sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:this.extractAttr(e,"pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},e=>({sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:this.extractAttr(e,"xm:pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,"dxfId")?.asNum(),stopIfTrue:this.extractAttr(e,"stopIfTrue")?.asBool(),aboveAverage:this.extractAttr(e,"aboveAverage")?.asBool(),percent:this.extractAttr(e,"percent")?.asBool(),bottom:this.extractAttr(e,"bottom")?.asBool(),operator:this.extractAttr(e,"operator")?.asString(),text:this.extractAttr(e,"text")?.asString(),timePeriod:this.extractAttr(e,"timePeriod")?.asString(),rank:this.extractAttr(e,"rank")?.asNum(),stdDev:this.extractAttr(e,"stdDev")?.asNum(),equalAverage:this.extractAttr(e,"equalAverage")?.asBool(),dataBar:this.extractCfDataBar(e,t)}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},e=>this.extractTextContent(e,{required:!0}))}extractCfColorScale(e,t){const r=this.querySelector(e,"colorScale");if(r)return{colors:this.mapOnElements({parent:r,query:"color"},e=>this.extractColor(e,t,"ffffff")),cfvos:this.extractCFVos(r)}}extractCfDataBar(e,t){const r=this.querySelector(e,"dataBar");if(r)return{color:this.extractColor(r.querySelector("color"),t,"EFF7FF"),cfvos:this.extractCFVos(r)}}extractCfIconSet(e){const t=this.querySelector(e,"iconSet, x14:iconSet");if(t)return{iconSet:this.extractAttr(t,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(t,"showValue",{default:!0}).asBool(),percent:this.extractAttr(t,"percent",{default:!0}).asBool(),reverse:this.extractAttr(t,"reverse")?.asBool(),custom:this.extractAttr(t,"custom")?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()}));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),gte:this.extractAttr(e,"gte",{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,"val")?.asString():this.extractChildTextContent(e,"f, xm:f")}))}}class Hw extends Pw{theme;constructor(e,t,r,n){super(e,t,r),this.theme=n}extractDataValidations(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > dataValidations > dataValidation"},e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),operator:this.extractAttr(e,"operator",{default:"between"})?.asString(),sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),errorStyle:this.extractAttr(e,"errorStyle")?.asString(),formula1:this.extractDataValidationFormula(e,1)[0],formula2:this.extractDataValidationFormula(e,2)[0],showErrorMessage:this.extractAttr(e,"showErrorMessage")?.asBool(),errorTitle:this.extractAttr(e,"errorTitle")?.asString(),error:this.extractAttr(e,"error")?.asString(),showInputMessage:this.extractAttr(e,"showInputMessage")?.asBool(),promptTitle:this.extractAttr(e,"promptTitle")?.asString(),prompt:this.extractAttr(e,"prompt")?.asString(),allowBlank:this.extractAttr(e,"allowBlank")?.asBool()}))}extractDataValidationFormula(e,t){return this.mapOnElements({parent:e,query:`formula${t}`},e=>this.extractTextContent(e,{required:!0}))}}class Bw extends Pw{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},e=>{const t=this.getChartType(e);if(!kv[t])throw new Error(`Unsupported chart type ${t}`);if("combo"===kv[t])return this.extractComboChart(e);const r=this.mapOnElements({parent:e,query:"c:chart > c:title a:t"},e=>e.textContent||"").join(""),n=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString(),o=this.extractChildAttr(e,"c:barDir","val",{default:"col"}).asString(),s=this.extractChildAttr(e,"c:holeSize","val",{default:"0"}).asNum();return{title:{text:r},type:kv[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:Pv[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===n,fontColor:"000000",horizontal:"bar"===o,isDoughnut:s>0,pieHolePercentage:s}})[0]}extractLabelRange(e,t){return"scatterChart"===e?this.extractChildTextContent(t,"c:ser c:strRef c:f")||this.extractChildTextContent(t,"c:ser c:numRef c:f"):this.extractChildTextContent(t,"c:ser c:cat c:f")}extractComboChart(e){const t=this.mapOnElements({parent:e,query:"c:title a:t"},e=>e.textContent||"").join(""),r=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:{text:t},type:"combo",dataSets:[...this.extractChartDatasets(this.querySelectorAll(e,"c:barChart"),"comboChart"),...this.extractChartDatasets(this.querySelectorAll(e,"c:lineChart"),"comboChart")],labelRange:this.extractChildTextContent(e,"c:ser c:cat c:f"),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),legendPosition:Pv[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===r,fontColor:"000000"}}extractChartDatasets(e,t){return Array.from(e).map(e=>"scatterChart"===t?this.extractScatterChartDatasets(e):this.mapOnElements({parent:e,query:"c:ser"},e=>{let t={};const r=this.extractChildTextContent(e,"c:tx c:f");if(r)t={reference:r};else{const r=this.extractChildTextContent(e,"c:tx c:v");r&&(t={text:r})}const n=this.querySelectorAll(e,"c:spPr a:solidFill"),o=n.length?this.querySelector(n[0],"a:srgbClr"):void 0,s=o?o.getAttribute("val"):void 0;return{label:t,range:this.extractChildTextContent(e,"c:val c:f",{required:!0}),backgroundColor:s&&Jm(s)?`${Qm(s)}`:void 0,trend:this.extractChartTrendline(e)}})).flat()}extractChartTrendline(e){const t=this.querySelector(e,"c:trendline");if(!t)return;const r=this.extractChildAttr(t,"c:trendlineType","val"),n=this.extractChildAttr(t,"a:solidFill a:srgbClr","val");return{type:r?r.asString():void 0,order:this.extractChildAttr(t,"c:order","val")?.asNum(),window:this.extractChildAttr(t,"c:period","val")?.asNum(),color:n&&Jm(n.asString())?`${Qm(n.asString())}`:void 0}}extractScatterChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},e=>{let t={};const r=this.querySelectorAll(e,"c:spPr a:solidFill a:srgbClr"),n=r.length?r[0].getAttribute("val"):void 0,o=this.extractChildTextContent(e,"c:tx c:f");if(o)t={reference:o};else{const r=this.extractChildTextContent(e,"c:tx c:v");r&&(t={text:r})}return{label:t,range:this.extractChildTextContent(e,"c:yVal c:f",{required:!0}),trend:this.extractChartTrendline(e),backgroundColor:n&&Jm(n)?`${Qm(n)}`:void 0}})}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");let r;for(const e of t.children){const t=Nw(e.tagName);nv.some(e=>e===t)&&(r?r!==t&&(r="comboChart"):r=t)}if(r)return r;throw new Error("Unknown chart type")}}const zw="oneCellAnchor",$w="twoCellAnchor";class Gw extends Pw{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},e=>{const t=Nw(e.tagName),r=this.extractFigureAnchorsByType(e,t),n=this.querySelector(e,"c:chart"),o=this.querySelector(e,"a:blip");if(!n&&!o)throw new Error("Only chart and image figures are currently supported.");return{anchors:r,data:n?this.extractChart(n):this.extractImage(e),figureSize:t===zw?this.extractFigureSizeFromSizeTag(e,"xdr:ext"):void 0}})}extractFigureAnchorsByType(e,t){switch(t){case zw:return[this.extractFigureAnchor("xdr:from",e)];case $w:return[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)];default:throw new Error(`${t} is not supported for xlsx drawings. `)}}extractFigureSizeFromSizeTag(e,t){const r=this.querySelector(e,t);if(!r)throw new Error(`Missing size element '${t}'`);return{cx:this.extractAttr(r,"cx",{required:!0}).asNum(),cy:this.extractAttr(r,"cy",{required:!0}).asNum()}}extractFigureAnchor(e,t){const r=this.querySelector(t,e);if(!r)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(r,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(r,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(r,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(r,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),r=this.getTargetXmlFile(this.relationships[t]),n=new Bw(r,this.xlsxFileStructure,this.warningManager).extractChart();if(!n)throw new Error("Unable to extract chart definition");return n}extractImage(e){const t=this.querySelector(e,"a:blip"),r=this.extractAttr(t,"r:embed",{required:!0}).asString(),n=this.getTargetImageFile(this.relationships[r]);if(!n)throw new Error("Unable to extract image");const o=n.fileName.split(".").at(-1),s=Nw(e.tagName),i=s===$w?this.querySelector(e,"a:xfrm"):e,a=s===$w?"a:ext":"xdr:ext",l=this.extractFigureSizeFromSizeTag(i,a);return{imageSrc:n.imageSrc,mimetype:o?Wv[o]:void 0,size:l}}}class Ww extends Pw{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 qw extends Pw{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 Zw extends Pw{theme;constructor(e,t,r,n){super(e,t,r),this.theme=n}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),sheetProperties:this.extractSheetProperties(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),dataValidations:this.extractDataValidations(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:this.extractTables(e),pivotTables:this.extractPivotTables(),isVisible:"visible"===t.state}})[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}})}extractSheetName(){const e=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 Uw(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new Hw(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 Gw(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 qw(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 Ww(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:Ib.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:xb.toString()}).asNum()}}extractSheetProperties(e){const t=this.querySelector(e,"sheetPr");if(t)return{outlinePr:this.extractSheetOutlineProperties(t),tabColor:this.extractColor(this.querySelector(t,"tabColor"),this.theme)}}extractSheetOutlineProperties(e){const t=this.querySelector(e,"outlinePr");if(t)return{summaryBelow:this.extractAttr(t,"summaryBelow",{default:!0}).asBool(),summaryRight:this.extractAttr(t,"summaryRight",{default:!0}).asBool()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},e=>({width:this.extractAttr(e,"width")?.asNum(),customWidth:this.extractAttr(e,"customWidth")?.asBool(),bestFit:this.extractAttr(e,"bestFit")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),min:this.extractAttr(e,"min",{required:!0})?.asNum(),max:this.extractAttr(e,"max",{required:!0})?.asNum(),styleIndex:this.extractAttr(e,"style")?.asNum(),outlineLevel:this.extractAttr(e,"outlineLevel")?.asNum(),collapsed:this.extractAttr(e,"collapsed")?.asBool()}))}extractRows(e){const t=new Set;return this.mapOnElements({parent:e,query:"sheetData row"},e=>({index:this.extractAttr(e,"r",{required:!0})?.asNum(),cells:this.extractCells(e,t),height:this.extractAttr(e,"ht")?.asNum(),customHeight:this.extractAttr(e,"customHeight")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),styleIndex:this.extractAttr(e,"s")?.asNum(),outlineLevel:this.extractAttr(e,"outlineLevel")?.asNum(),collapsed:this.extractAttr(e,"collapsed")?.asBool()}))}extractCells(e,t){return this.mapOnElements({parent:e,query:"c"},e=>{const r=this.extractAttr(e,"r",{required:!0})?.asString(),n=this.extractCellFormula(e);if(n?.ref&&void 0===n.sharedIndex){const e=Bo(n.ref);for(const{col:n,row:o}of rs(e)){const e=Do(n,o);e!==r&&t.add(e)}}const o=t.has(r);return{xc:r,styleIndex:this.extractAttr(e,"s")?.asNum(),type:Av[this.extractAttr(e,"t",{default:"n"})?.asString()],value:o?void 0:this.extractChildTextContent(e,"v")??void 0,formula:o?void 0:n}})}extractCellFormula(e){const t=this.querySelector(e,"f");if(!t)return;const r=this.extractTextContent(t),n=this.extractAttr(t,"si")?.asNum(),o=this.extractAttr(t,"ref")?.asString();return void 0!==r&&""!==r.trim()||void 0!==n?{content:r,sharedIndex:n,ref:o}:void 0}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},e=>{const t=this.extractAttr(e,"r:id")?.asString();return{xc:this.extractAttr(e,"ref",{required:!0})?.asString(),location:this.extractAttr(e,"location")?.asString(),display:this.extractAttr(e,"display")?.asString(),relTarget:t?this.relationships[t].target:void 0}})}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),r={};for(const e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),n=this.extractTextContent(e,{required:!0});r[t]=n}const n=[];for(let e=0;e<Object.keys(r).length;e++)r[e]?n.push(r[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),n.push(""));return n}}class Yw extends Pw{theme;constructor(e,t,r){super(e.styles,e,t),this.theme=r}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},e=>this.extractNumFormats(e))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},e=>this.extractFont(e))}extractFont(e){const t=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),r=this.extractChildAttr(e,"sz","val",{default:q.toString()}).asNum(),n=this.extractColor(this.querySelector(e,"color"),this.theme),o=this.querySelector(e,"i")||void 0,s=o&&"0"!==o.attributes.val?.value,i=this.querySelector(e,"b")||void 0,a=i&&"0"!==i.attributes.val?.value,l=this.querySelector(e,"strike")||void 0,c=l&&"0"!==l.attributes.val?.value,u=this.querySelector(e,"u")||void 0;return{name:t,size:r,color:n,italic:s,bold:a,underline:u&&"none"!==u.attributes.val?.value,strike:c}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},e=>this.extractFill(e))}extractFill(e){const t=e.children[0];return"patternFill"===t.tagName?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(t,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(t,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},e=>this.extractBorder(e))}extractBorder(e){const t={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,"diagonalUp")?.asBool(),t.diagonalDown=this.extractAttr(e,"diagonalDown")?.asBool()),t}extractSingleBorder(e,t,r){const n=this.querySelector(e,t);if(n&&n.attributes.style)return{style:this.extractAttr(n,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(n.children[0],r,"000000")}}extractAlignment(e){return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"bottom"}).asString(),textRotation:this.extractAttr(e,"textRotation")?.asNum(),wrapText:this.extractAttr(e,"wrapText")?.asBool(),indent:this.extractAttr(e,"indent")?.asNum(),relativeIndent:this.extractAttr(e,"relativeIndent")?.asNum(),justifyLastLine:this.extractAttr(e,"justifyLastLine")?.asBool(),shrinkToFit:this.extractAttr(e,"shrinkToFit")?.asBool(),readingOrder:this.extractAttr(e,"readingOrder")?.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},e=>{const t=this.querySelector(e,"font"),r=this.querySelector(e,"fill"),n=this.querySelector(e,"border"),o=this.querySelector(e,"numFmt"),s=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:r?this.extractFill(r):void 0,numFmt:o?this.extractNumFormats(o):void 0,alignment:s?this.extractAlignment(s):void 0,border:n?this.extractBorder(n):void 0}})}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}})}}class jw extends Pw{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 Xw(e,t){const r=function(e,t){const r=t[_b],n=r.querySelectorAll(`Override[ContentType="${e}"]`),o=[];for(const e of n){const t=e?.attributes.PartName.value;o.push(t.substring(1))}return o}(e,t);return function(e,t){const r=[];for(const n of e){const e=Kw(n,t);r.push({file:{fileName:n,xml:t[n]},rels:e?{fileName:e,xml:t[e]}:void 0})}return r}(r,t)}function Kw(e,t){if(e===_b)return"_rels/.rels";let r="";const n=e.split("/");for(let e=0;e<n.length-1;e++)r+=n[e]+"/";return r+="_rels/",r+=n[n.length-1]+".rels",t[r]||(r=void 0),r}class Qw{warningManager;xmls;images;constructor(e){this.warningManager=new Ev,this.xmls={},this.images=[];for(const t of Object.keys(e))if(t.endsWith(".xml")||t.endsWith(".rels")){const r=Mw(e[t]);this.xmls[t]=Aw(new rv(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 kw(e.theme,e,this.warningManager).getTheme():void 0,r=e.sharedStrings?new kw(e.sharedStrings,e,this.warningManager).getSharedStrings():[],n=e.sheets.sort((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0})).map(r=>new Zw(r,e,this.warningManager,t).getSheet()),o=e.externalLinks.map(t=>new jw(t,e,this.warningManager).getExternalBook()),s=new Yw(e,this.warningManager,t);return{fonts:s.getFonts(),fills:s.getFills(),borders:s.getBorders(),dxfs:s.getDxfs(),numFmts:s.getNumFormats(),styles:s.getStyles(),sheets:n,sharedStrings:r,externalBooks:o,chartIds:[],imageIds:[]}}buildXlsxFileStructure(){const e={sheets:Xw(ub.sheet,this.xmls),workbook:Xw(ub.workbook,this.xmls)[0]||Xw(ub.macroEnabledWorkbook,this.xmls)[0]||Xw(ub.templateWorkbook,this.xmls)[0]||Xw(ub.macroEnabledTemplateWorkbook,this.xmls)[0]||Xw(ub.excelAddInWorkbook,this.xmls)[0],styles:Xw(ub.styles,this.xmls)[0],sharedStrings:Xw(ub.sharedStrings,this.xmls)[0],theme:Xw(ub.themes,this.xmls)[0],charts:Xw(ub.chart,this.xmls),figures:Xw(ub.drawing,this.xmls),tables:Xw(ub.table,this.xmls),pivots:Xw(ub.pivot,this.xmls),externalLinks:Xw(ub.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:hw(e,this.warningManager),styles:ey(e,this.warningManager),formats:ry(e,this.warningManager),borders:Qv(e,this.warningManager),revisionId:Y};return yw(t,e),Object.keys(e.styles).map(t=>{e.styles[t]=Fe(e.styles[t])}),t}}function Jw(e){const t=Yg(e),r=[];return{text:"".concat(...t.map(e=>{if("REFERENCE"===e.type&&to.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 eE={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},tE=new h;function rE(e){for(const t of e.sheets||[]){const e=[];for(const r of t.filterTables||[]){const t=Bo(r.range),n=e.findIndex(e=>Ko(e,t));-1!==n?e[n]=t:e.push(t)}t.filterTables=e.map(e=>({range:Go(e)}))}return e}function nE(){return oE().at(-1)}function oE(){return tE.getKeys().sort(lE)}tE.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=Jw(r.content))}return e}}).add("0.6",{migrate(e){for(const t of e.sheets||[])for(const e in t.figures||[]){const{dataSets:r,...n}=t.figures[e].data,o=[];for(const e of r)if(e.labelCell){const t=Bo(e.dataRange),r=e.labelCell+":"+Do(t.right,t.bottom);o.push(r)}else o.push(e.dataRange);n.dataSetsHaveTitle=Boolean(r[0].labelCell),n.dataSets=o,t.figures[e].data=n}return e}}).add("0.7",{migrate(e){const t=[];for(const r of e.sheets||[]){if(!r.name)continue;const e=r.name,n=Xe(ie(e,"_"),t,{compute:(e,t)=>`${e}${t}`});r.name=n,t.push(n);const o=t=>{if(void 0===t)return t;let r=t.replace(e,n),o=t;for(;o!==r;)o=r,r=o.replace(e,n);return o};for(const e in r.cells){const t=r.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(o))}for(const e of r.figures||[])if("chart"===e.tag){const t=e.data.dataSets.map(o),r=o(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:r}}for(const e of r.conditionalFormats||[]){e.ranges=e.ranges.map(o);for(const t of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===e.rule[t]?.type&&(e.rule[t].value=o(e.rule[t].value))}}return e}}).add("0.8",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=M,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}}).add("0.9",{migrate(e){for(const t of e.sheets||[])for(const e in t.cells||[]){const r=t.cells[e];if(r.formula){let{text:e,dependencies:t}=r.formula;for(const[r,n]of Object.entries(t)){const t=`\\${K}${r}\\${K}`;e=e.replace(new RegExp(t,"g"),n)}r.content=e,delete r.formula}}return e}}).add("0.10",{migrate(e){const t={};for(const r of e.sheets||[])for(const e in r.cells||[]){const n=r.cells[e];n.format&&(n.format=hy(n.format,t))}return e.formats=t,e}}).add("15.4",{migrate(e){for(const t of e.sheets||[])t.isVisible=!0;return e}}).add("15.4.1",{migrate:e=>rE(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=Dl),e)}).add("16.4.1",{migrate:e=>rE(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=Md(e.pivots)+1),e)}).add("17.4",{migrate(e){for(const t of e.sheets||[])for(const e in t.figures||[]){const r=t.figures[e];"title"in r.data&&"string"==typeof r.data.title&&(r.data.title={text:r.data.title});const n=r.data.type;if(!["line","bar","pie","scatter","waterfall","combo"].includes(n))continue;const{dataSets:o,...s}=t.figures[e].data,i=o.map(e=>({dataRange:e}));s.dataSets=i,t.figures[e].data=s}return e}}).add("18.0",{migrate:e=>e}).add("18.0.1",{migrate(e){for(const t of Object.values(e.pivots||{}))t.measures=t.measures.map(e=>({id:e.name,fieldName:e.name,aggregator:e.aggregator})),t.columns=t.columns.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity})),t.rows=t.rows.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity}));return e}}).add("18.0.2",{migrate(e){const t=e.settings?.locale;if(t){const e=t.code;t.weekStart=eE[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={...Tp,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}});const sE="Sheet1";function iE(e,t){if(!e)return dE();console.debug("### Loading data ###");const r=performance.now();if(e["[Content_Types].xml"]){const r=new Qw(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=aE[e.version]),e.version!==nE()&&(console.debug("Migrating data from version",e.version),e=function(e){const t=performance.now(),r=oE();for(let t=r.findIndex(t=>t===e.version)+1;t<r.length;t++){const n=r[t];e=tE.get(n).migrate(e)}return console.debug("Data migrated in",performance.now()-t,"ms"),e}(e))),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,r=new Set,n=new wo;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=n.smallUuid()),t.add(e.id),"chart"===e.tag&&(r.has(e.data?.chartId)&&(e.data.chartId+=n.smallUuid()),r.add(e.data?.chartId));return e.uniqueFigureIds=!0,e}(e),e=function(e){const t=Object.assign(dE(),e,{version:nE()});t.sheets=t.sheets?t.sheets.map((e,t)=>Object.assign(hE(`Sheet${t+1}`,`Sheet${t+1}`),e)):[],0===t.sheets.length&&t.sheets.push(hE(sE,"Sheet1"));Xl(t.settings.locale)||(t.settings.locale=Dl);return t}(e),e}(e),console.debug("Data loaded in",performance.now()-r,"ms"),console.debug("###"),e}const aE={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:"16.4",13:"16.3",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 lE(e,t){const r=e.split(".").map(Number),n=t.split(".").map(Number);for(let e=0;e<Math.max(r.length,n.length);e++){const t=r[e]||0,o=n[e]||0;if(t>o)return 1;if(t<o)return-1}return 0}function cE(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const r=[],n=[],o=e=>{if("CREATE_SHEET"===e.type)r.push(e.sheetId);else if("sheetId"in e&&!r.includes(e.sheetId))return{...e,sheetId:sE};return e};for(const e of t)"REMOTE_REVISION"===e.type?n.push({...e,commands:e.commands.map(o)}):n.push(e);return n}(e,t),t=uE(t,"SORT_CELLS"),t=function(e,t){const r=[],n={};for(const t of e.sheets||[])t.figures?.forEach(t=>{"chart"===t.tag&&(e.version&&lE(String(e.version),"18.5.1")<=0?n[t.data.chartId]=t.data:n[t.id]=t.data)});for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const r of e.commands){let e=r;switch(r.type){case"CREATE_CHART":n[r.chartId]=r.definition;break;case"UPDATE_CHART":if(!n[r.chartId]){console.log(`Fix chart definition: chart with id ${r.chartId} not found.`);continue}const t={...n[r.chartId],...r.definition};e={...r,definition:t},n[r.chartId]=t}t.push(e)}r.push({...e,commands:t})}else r.push(e);return r}(e,t=uE(t,"SET_DECIMAL")),t=function(e,t){const r={};for(const t of e.sheets||[])t.figures?.forEach(e=>{r[e.id]=e.offset});for(const e of t)if("REMOTE_REVISION"===e.type)for(const t of e.commands)switch(t.type){case"UPDATE_FIGURE":t.offset&&(void 0===t.offset.x&&(t.offset.x=r[t.figureId]||0),void 0===t.offset.y&&(t.offset.y=r[t.figureId]||0),r[t.figureId]=r);break;case"CREATE_IMAGE":case"CREATE_CHART":case"CREATE_FIGURE":r[t.figureId]=t.offset}return t}(e,t),t=function(e,t){const r={};for(const t of e.sheets||[])r[t.id]=t.name;const n=[];for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const n of e.commands){switch(n.type){case"DUPLICATE_SHEET":n.sheetNameTo=n.sheetNameTo??Tm(r[n.sheetId],Object.values(r));break;case"CREATE_SHEET":r[n.sheetId]=n.name||Cm(Object.values(r));break;case"RENAME_SHEET":r[n.sheetId]=n.newName||Cm(Object.values(r))}t.push(n)}n.push({...e,commands:t})}else n.push(e);return t}(e,t),t}function uE(e,t){const r=[];for(const n of e)"REMOTE_REVISION"===n.type?r.push({...n,commands:n.commands.filter(e=>e.type!==t)}):r.push(n);return r}function hE(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:nE(),sheets:[hE(sE,e)],styles:{},formats:{},borders:{},revisionId:Y,uniqueFigureIds:!0,settings:{locale:Dl},pivots:{},pivotNextId:1,customTableStyles:{}}}class fE{map={};constructor(e=[]){for(const[t,r]of e)this.set(t,r)}set({sheetId:e,col:t,row:r},n){const o=this.map;o[e]||(o[e]={}),o[e][t]||(o[e][t]={}),o[e][t][r]=n}setMany(e){for(const[t,r]of e)this.set(t,r)}get({sheetId:e,col:t,row:r}){return this.map[e]?.[t]?.[r]}getSheet(e){return this.map[e]}clearSheet(e){delete this.map[e]}has({sheetId:e,col:t,row:r}){return void 0!==this.map[e]?.[t]?.[r]}delete({sheetId:e,col:t,row:r}){delete this.map[e]?.[t]?.[r]}keys(){const e=this.map,t=[];for(const r in e)for(const n in e[r])for(const o in e[r][n])t.push({sheetId:r,col:parseInt(n),row:parseInt(o)});return t}keysForSheet(e){const t=this.map[e];if(!t)return[];const r=[];for(const n in t)for(const o in t[n])r.push({sheetId:e,col:parseInt(n),row:parseInt(o)});return r}*entries(){const e=this.map;for(const t of this.keys()){const{sheetId:r,col:n,row:o}=t;yield[t,e[r][n][o]]}}}class gE extends Ts{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:r,dispatch:n,canDispatch:o}){super(t),r.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=n,this.canDispatch=o}import(e){}export(e){}adaptRanges(e,t,r){}}class mE{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,r,n,o,s,i){this.id=e,this.format=r,this.style=n,this.sheetId=s,this.getRangeString=i;let a=0;const l=t.tokens.map(e=>{if("REFERENCE"===e.type){const e=a++;return new pE(o,e,this.sheetId,this.getRangeString)}return e});this.compiledFormula={...t,dependencies:o,tokens:l}}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 pE{ranges;rangeIndex;sheetId;getRangeString;type="REFERENCE";constructor(e,t,r,n){this.ranges=e,this.rangeIndex=t,this.sheetId=r,this.getRangeString=n}get value(){const e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}}const bE=new fd;bE.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:dd.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text contains"),getPreview:e=>v('Text contains "%s"',e.values[0])}),bE.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:dd.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text does not contain"),getPreview:e=>v('Text does not contain "%s"',e.values[0])}),bE.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:dd.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text is exactly"),getPreview:e=>v('Text is exactly "%s"',e.values[0])});const vE=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/;function yE(e,t){return e.values.map(e=>void 0!==e?Ql(String(e),t):w.InvalidReference)}function wE(e,t){return Qy(e,Dl).map(e=>void 0!==e?Fn(e,{locale:t,format:t.dateFormat}):w.InvalidReference)}function EE(e){return void 0!==ht(e,Dl)}function SE(e){const t=function(e,t){try{return kt(e,t)}catch(e){return}}(e,Dl);return void 0!==t}function CE(e){return""===e?NaN:Number(e)}bE.add("isEmail",{type:"isEmail",isValueValid:(e,t)=>"string"==typeof e&&vE.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")}),bE.add("isLink",{type:"isLink",isValueValid:(e,t)=>void 0!==$y(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")}),bE.add("dateIs",{type:"dateIs",isValueValid:(e,t)=>{const r=Qy(t,Dl)[0],n=ht(e,Dl);if(void 0===n||void 0===r)return!1;if(["lastWeek","lastMonth","lastYear"].includes(t.dateValue)){return xt(n,pt(Qe.now()),r)}return o=n,s=r,Math.trunc(o)===Math.trunc(s);var o,s},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be the date %s",wE(e,r)[0]):v("The value must be %s",dd.DateIs[e.dateValue])},isCriterionValueValid:e=>EE(e),criterionValueErrorString:dd.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:v("Date is"),getPreview:(e,t)=>"exactDate"===e.dateValue?v("Date is %s",Jy(e.values,t.getLocale())[0]):v("Date is %s",dd.DateIs[e.dateValue])}),bE.add("dateIsBefore",{type:"dateIsBefore",isValueValid:(e,t)=>{const r=Qy(t,Dl)[0],n=ht(e,Dl);return void 0!==n&&void 0!==r&&function(e,t){return Math.trunc(e)<Math.trunc(t)}(n,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date before %s",wE(e,r)[0]):v("The value must be a date before %s",dd.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>EE(e),criterionValueErrorString:dd.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",Jy(e.values,t.getLocale())[0]):v("Date is before %s",dd.DateIsBefore[e.dateValue])}),bE.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",isValueValid:(e,t)=>{const r=Qy(t,Dl)[0],n=ht(e,Dl);return void 0!==n&&void 0!==r&&function(e,t){return Math.trunc(e)<=Math.trunc(t)}(n,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date on or before %s",wE(e,r)[0]):v("The value must be a date on or before %s",dd.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>EE(e),criterionValueErrorString:dd.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",Jy(e.values,t.getLocale())[0]):v("Date is on or before %s",dd.DateIsBefore[e.dateValue])}),bE.add("dateIsAfter",{type:"dateIsAfter",isValueValid:(e,t)=>{const r=Qy(t,Dl)[0],n=ht(e,Dl);return void 0!==n&&void 0!==r&&function(e,t){return Math.trunc(e)>Math.trunc(t)}(n,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date after %s",wE(e,r)[0]):v("The value must be a date after %s",dd.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>EE(e),criterionValueErrorString:dd.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",Jy(e.values,t.getLocale())[0]):v("Date is after %s",dd.DateIsBefore[e.dateValue])}),bE.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",isValueValid:(e,t)=>{const r=Qy(t,Dl)[0],n=ht(e,Dl);return void 0!==n&&void 0!==r&&function(e,t){return Math.trunc(e)>=Math.trunc(t)}(n,r)},getErrorString:(e,t)=>{const r=t.getLocale();return"exactDate"===e.dateValue?v("The value must be a date on or after %s",wE(e,r)[0]):v("The value must be a date on or after %s",dd.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>EE(e),criterionValueErrorString:dd.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",Jy(e.values,t.getLocale())[0]):v("Date is on or after %s",dd.DateIsBefore[e.dateValue])}),bE.add("dateIsBetween",{type:"dateIsBetween",isValueValid:(e,t)=>{const r=Qy(t,Dl),n=ht(e,Dl);return void 0!==n&&void 0!==r[0]&&void 0!==r[1]&&xt(n,r[0],r[1])},getErrorString:(e,t)=>{const r=wE(e,t.getLocale());return v("The value must be a date between %s and %s",r[0],r[1])},isCriterionValueValid:e=>EE(e),criterionValueErrorString:dd.CriterionError.dateValue,numberOfValues:()=>2,name:v("Date is between"),getPreview:(e,t)=>{const r=Jy(e.values,t.getLocale());return v("Date is between %s and %s",r[0],r[1])}}),bE.add("dateIsNotBetween",{type:"dateIsNotBetween",isValueValid:(e,t)=>{const r=Qy(t,Dl),n=ht(e,Dl);return void 0!==n&&void 0!==r[0]&&void 0!==r[1]&&!xt(n,r[0],r[1])},getErrorString:(e,t)=>{const r=wE(e,t.getLocale());return v("The value must be a date not between %s and %s",r[0],r[1])},isCriterionValueValid:e=>EE(e),criterionValueErrorString:dd.CriterionError.dateValue,numberOfValues:()=>2,name:v("Date is not between"),getPreview:(e,t)=>{const r=Jy(e.values,t.getLocale());return v("Date is not between %s and %s",r[0],r[1])}}),bE.add("dateIsValid",{type:"dateIsValid",isValueValid:(e,t)=>void 0!==ht(e,Dl),getErrorString:()=>v("The value must be a valid date"),isCriterionValueValid:e=>EE(e),criterionValueErrorString:"",numberOfValues:()=>0,name:v("Is valid date"),getPreview:()=>v("Date is valid")}),bE.add("isEqual",{type:"isEqual",isValueValid:(e,t)=>e===t.values[0],getErrorString:(e,t)=>{const r=yE(e,t.getLocale());return v("The value must be equal to %s",r[0])},isCriterionValueValid:e=>SE(e),criterionValueErrorString:dd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is equal to"),getPreview:e=>v("Value is equal to %s",e.values[0])}),bE.add("isNotEqual",{type:"isNotEqual",isValueValid:(e,t)=>e!==t.values[0],getErrorString:(e,t)=>{const r=yE(e,t.getLocale());return v("The value must not be equal to %s",r[0])},isCriterionValueValid:e=>SE(e),criterionValueErrorString:dd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is not equal to"),getPreview:e=>v("Value is not equal to %s",e.values[0])}),bE.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=yE(e,t.getLocale());return v("The value must be greater than %s",r[0])},isCriterionValueValid:e=>SE(e),criterionValueErrorString:dd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is greater than"),getPreview:e=>v("Value is greater than %s",e.values[0])}),bE.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=yE(e,t.getLocale());return v("The value must be greater or equal to %s",r[0])},isCriterionValueValid:e=>SE(e),criterionValueErrorString:dd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is greater or equal to"),getPreview:e=>v("Value is greater or equal to %s",e.values[0])}),bE.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=yE(e,t.getLocale());return v("The value must be less than %s",r[0])},isCriterionValueValid:e=>SE(e),criterionValueErrorString:dd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is less than"),getPreview:e=>v("Value is less than %s",e.values[0])}),bE.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=yE(e,t.getLocale());return v("The value must be less or equal to %s",r[0])},isCriterionValueValid:e=>SE(e),criterionValueErrorString:dd.CriterionError.numberValue,numberOfValues:()=>1,name:v("Is less or equal to"),getPreview:e=>v("Value is less or equal to %s",e.values[0])}),bE.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=yE(e,t.getLocale());return v("The value must be between %s and %s",r[0],r[1])},isCriterionValueValid:e=>SE(e),criterionValueErrorString:dd.CriterionError.numberValue,numberOfValues:()=>2,name:v("Is between"),getPreview:e=>v("Value is between %s and %s",e.values[0],e.values[1])}),bE.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=yE(e,t.getLocale());return v("The value must not be between %s and %s",r[0],r[1])},isCriterionValueValid:e=>SE(e),criterionValueErrorString:dd.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])}),bE.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")}),bE.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(", "))}),bE.add("isValueInRange",{type:"isValueInList",isValueValid:(e,t,r,n)=>{if(!e)return!1;return r.getDataValidationRangeValues(n,t).map(e=>e.value.toLowerCase()).includes(e.toString().toLowerCase())},getErrorString:e=>v("The value must be a value in the range %s",String(e.values[0])),isCriterionValueValid:e=>ao.test(e),criterionValueErrorString:dd.CriterionError.validRange,numberOfValues:()=>1,allowedValues:"onlyLiterals",name:v("Value in range"),getPreview:e=>v("Value in range %s",e.values[0])}),bE.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])}),bE.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:dd.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text begins with"),getPreview:e=>v('Text begins with "%s"',e.values[0])}),bE.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:dd.CriterionError.notEmptyValue,numberOfValues:()=>1,name:v("Text ends with"),getPreview:e=>v('Text ends with "%s"',e.values[0])}),bE.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")}),bE.add("isNotEmpty",{type:"isNotEmpty",isValueValid:(e,t)=>""!==(e??"").toString().trim(),getErrorString:()=>v("The value must not be empty"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:v("Is not empty"),getPreview:()=>v("Is not empty")});function TE(e){return Object.entries(e).map(([e,t])=>t?IE(parseInt(e,10),t):void 0).filter(Se).map(e=>Do(e.left,e.top)+":"+Do(e.right,e.bottom))}function IE(e,t){return{...t.zone,id:e}}const xE="(previous)";function RE(e,t){const r=e.definition.rows.map(e=>e.nameWithGranularity),n=t.filter(e=>r.includes(e.field)),o=e.definition.columns.map(e=>e.nameWithGranularity);return{colDomain:t.filter(e=>o.includes(e.field)),rowDomain:n}}function AE(e,t,r){return"column"===t?RE(e,r).colDomain:RE(e,r).rowDomain}function _E(e,t){return void 0!==OE(e,t)}function OE(e,t,r){let n=t;for(const t of e){const e=n.find(e=>e.value===t.value);if(!e)return;if(e.field===r)return n;n=e.children}return n}function DE(e,t,r){const n=(e=re(e)).find(e=>e.field===t);return n?(n.value=r,e):e}function FE(e,t){return t.some(t=>t.field===e)}function NE(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 ME(e){return e?e.map(VE).join(", "):""}function VE(e){return e?`${e.field}=${e.value}`:""}function LE(e,t){const r=e.findIndex(e=>e.field===t);if(-1===r)return"";const n=e.slice(0,r),o=e.at(-1);return ME(o.field===t?n:[...n,o])}function PE(e,t){const r=e.findIndex(e=>e.field===t);return-1===r?"":ME([...e.slice(0,r),...e.slice(r+1)])}function kE(e,t,r){const n=[...e],o=[...t];n.sort((e,t)=>r([...o,e],[...o,t]));for(const t of e){const e=kE(t.children,[...o,t],r);t.children=e}return n}function UE(e,t){return e.length>t.length&&t.every((t,r)=>Ae(t,e[r]))}class HE{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,r,n,o={COL:[],ROW:[]}){this.measures=r,this.fieldsType=n,o.COL.length&&(e=this.removeCollapsedColumns(e,r,o.COL)),this.columns=e.map(e=>{let t=1;return e.map(e=>(e={...e,offset:t},t+=e.width,e))}),this.rows=t.filter(e=>!this.isParentCollapsed(o.ROW,e)),this.maxIndent=Math.max(...this.rows.map(e=>e.indent)),this.rowTree=xe(()=>this.buildRowsTree()),this.colTree=xe(()=>this.buildColumnsTree())}removeCollapsedColumns(e,t,r){const n=(r,n)=>{const o=this.getDomain(r),s=e[n],i=s.findIndex(e=>UE(this.getDomain(e),o)),a=s.findLastIndex(e=>UE(this.getDomain(e),o)),l=n===e.length-1,c=t.map(e=>({fields:l?[...r.fields,"measure"]:[],values:l?[...r.values,e]:[],width:1,offset:0,collapsedHeader:!l}));s.splice(i,a-i+1,...c)};return e.map((o,s)=>{for(const i of o){if(s>=e.length-2)return o;const a=this.getDomain(i);if(r.some(e=>Ae(a,e))){i.width=t.length;for(let t=s+1;t<e.length;t++)n(i,t)}}return o})}isParentCollapsed(e,t){const r=this.getDomain(t);return e.some(e=>UE(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=Ad){const t=JSON.stringify(e);if(!this.pivotCells[t]){const{displayTotals:r}=e,n=this.rows.length,o=this.getNumberOfDataColumns();let s=this.columns.length+n,i=1+o;r||1===n||(s-=1),r||o===this.measures.length||(i-=this.measures.length);const a=[],l=this.getSkippedRows(e);for(let e=0;e<i;e++){a.push([]);for(let t=0;t<s;t++)l.has(t)||a[e].push(this.getPivotCell(e,t,r))}this.pivotCells[t]=a}return this.pivotCells[t]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,r=!0){const n=this.columns.length;if(e>0&&t===n-1){const r=this.getColHeaderDomain(e,t);if(!r)return BE;const n=r.at(-1)?.value?.toString()||"";return{type:"MEASURE_HEADER",domain:r.slice(0,-1),measure:n}}if(t<=n-1){const r=this.getColHeaderDomain(e,t);return r?{type:"HEADER",domain:r,dimension:"COL"}:BE}if(0===e){const e=t-n;return{type:"HEADER",domain:this.getDomain(this.rows[e]),dimension:"ROW"}}{const o=t-n;if(!r&&this.isTotalRow(o))return BE;return{type:"VALUE",domain:[...this.getDomain(this.rows[o]),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(0===e)return;const r=this.columns[t].find(t=>t.offset===e);return r&&!r.collapsedHeader?this.getDomain(r):void 0}getDomain(e){return e.fields.map((t,r)=>{if("measure"===t)return{type:"char",field:t,value:Ud({displayName:"measure",type:"char"},e.values[r])};{const{fieldName:n,granularity:o}=Ld(t),s=this.fieldsType[n]||"char";return{type:s,field:t,value:Ud({displayName:n,type:s,granularity:o},e.values[r])}}})}getColDomain(e){const t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){const t=this.getColHeaderDomain(e,this.columns.length-1),r=t?.at(-1)?.value;if(null==r)throw new Error("Measure is missing");return r.toString()}buildRowsTree(){const e=[];let t=0;const r={};r[0]=e;for(const n of this.rows){if(0===n.fields.length||0===n.values.length)return e;const o=n.fields.length-1,s=n.fields[o],{fieldName:i,granularity:a}=Ld(s),l=Ud({displayName:i,type:this.fieldsType[i]??"char",granularity:a},n.values[o]);if(o>t){t=o,r[t]=[];const e=r[t-1].at(-1);e&&(e.children=r[t])}t=o;const c={value:l,field:n.fields[o],children:[],type:this.fieldsType[i]||"char",width:0};r[t].push(c)}return e}buildColumnsTree(){const e=[],t=this.columns.at(-2)||[],r={};r[0]=e;for(const e of t)for(let t=0;t<e.fields.length;t++){const n=e.fields[t],{fieldName:o,granularity:s}=Ld(n),i=Ud({displayName:o,type:this.fieldsType[o]??"char",granularity:s},e.values[t]),a={value:i,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[o]||"char"};r[t]?.at(-1)?.value!==i&&(r[t+1]=[],a.children=r[t+1],r[t].push(a))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}sort(e,t,r){if(this.isSorted)return;const n=(e,t)=>{const n=r(e,t).value;return"number"==typeof n?n:-1/0},o=t.domain,s=kE(this.rowTree(),[],(r,s)=>{const i=n(e,[...r,...o]),a=n(e,[...s,...o]);return"asc"===t.order?i-a:a-i});this.rowTree=xe(s),this.rows=[...this.rowTreeToRows(s),this.rows[this.rows.length-1]],this.isSorted=!0}rowTreeToRows(e,t){return e.flatMap(e=>{const r={indent:t?t.indent+1:1,fields:[...t?.fields||[],e.field],values:[...t?.values||[],e.value]};return[r,...this.rowTreeToRows(e.children,r)]})}get numberOfCells(){return this.rows.length*this.getNumberOfDataColumns()}getColumnDomainsAtDepth(e){return e<0||e>=this.columns.length-1?[]:this.columns[e].map(e=>this.getDomain(e)).filter(e=>e.length)}getRowDomainsAtDepth(e){return e<0||e>this.maxIndent?[]:this.rows.filter(t=>t.indent===e+1).map(e=>this.getDomain(e))}}const BE={type:"EMPTY"};function zE(e,t){if(!e)return;const r=t(e);switch(r.changeType){case"NONE":return e;case"REMOVE":return;default:return r.range}}const $E=["wholeTable","firstColumnStripe","secondColumnStripe","firstRowStripe","secondRowStripe","firstColumn","lastColumn","headerRow","totalRow"];function GE(e,t,r,n){const o=t.zone;if(o.left!==o.right)throw new Error("Can only define a filter on a single column");const s={...o,top:o.top+r.numberOfHeaders},i=n(t.sheetId,s);return{id:e,rangeWithHeaders:t,col:o.left,filteredRange:s.top>s.bottom?void 0:i}}function WE(e,t,r,n){const o=rr(r,n,()=>({}));for(const s of $E){const i=t[s]?.border;if(!i)continue;const a=jE(s,e,r,n);for(const t of a)for(let a=t.left;a<=t.right;a++)for(let l=t.top;l<=t.bottom;l++){const c="wholeTable"===s&&l<=e.numberOfHeaders-1;l===t.top&&i?.top?qE(o,"top",i.top,a,l,r,n):l!==t.top&&!c&&i?.horizontal&&qE(o,"top",i.horizontal,a,l,r,n),l===t.bottom&&i?.bottom&&qE(o,"bottom",i.bottom,a,l,r,n),a===t.left&&i?.left&&qE(o,"left",i.left,a,l,r,n),a===t.right&&i?.right?qE(o,"right",i.right,a,l,r,n):a!==t.right&&!c&&i?.vertical&&qE(o,"right",i.vertical,a,l,r,n)}}return o}function qE(e,t,r,n,o,s,i){switch(t){case"top":return e[n][o].top=r,void(0!==o&&(e[n][o-1].bottom=r));case"bottom":return e[n][o].bottom=r,void(o!==i-1&&(e[n][o+1].top=r));case"left":return e[n][o].left=r,void(0!==n&&(e[n-1][o].right=r));case"right":return e[n][o].right=r,void(n!==s-1&&(e[n+1][o].left=r))}}function ZE(e,t,r,n){const o=rr(r,n,()=>({}));for(const s of $E){const i=t[s],a=YE(s);if(!i&&!a)continue;const l=jE(s,e,r,n);for(const e of l)for(let t=e.left;t<=e.right;t++)for(let r=e.top;r<=e.bottom;r++)o[t][r]||(o[t][r]={}),o[t][r]={...o[t][r],...i?.style},a&&(o[t][r].bold=!0)}return o}function YE(e){return"firstColumn"===e||"lastColumn"===e||"headerRow"===e||"totalRow"===e}function jE(e,t,r,n){const o=[],s=Math.min(t.numberOfHeaders,n),i=t.totalRow?1:0,a=r-1,l=n-1;switch(e){case"wholeTable":o.push({top:0,left:0,bottom:l,right:a});break;case"firstColumn":if(!t.firstColumn)break;o.push({top:0,left:0,bottom:l,right:0});break;case"lastColumn":if(!t.lastColumn)break;o.push({top:0,left:a,bottom:l,right:a});break;case"headerRow":if(!t.numberOfHeaders)break;o.push({top:0,left:0,bottom:s-1,right:a});break;case"totalRow":if(!t.totalRow)break;o.push({top:l,left:0,bottom:l,right:a});break;case"firstRowStripe":if(!t.bandedRows)break;for(let e=s;e<n-i;e+=2)o.push({top:e,left:0,bottom:e,right:a});break;case"secondRowStripe":if(!t.bandedRows)break;for(let e=s+1;e<n-i;e+=2)o.push({top:e,left:0,bottom:e,right:a});break;case"firstColumnStripe":if(!t.bandedColumns)break;for(let e=0;e<r;e+=2)o.push({top:s,left:e,bottom:l-i,right:e});break;case"secondColumnStripe":if(!t.bandedColumns)break;for(let e=1;e<r;e+=2)o.push({top:s,left:e,bottom:l-i,right:e})}return o}const XE=Bg.content;function KE(e){try{return 0===am(sm(e)).filter(e=>"FUNCALL"===e.type&&!XE[e.value.toUpperCase()]?.isExported).length}catch(e){return!1}}function QE(e,t){if(!e.some(e=>"SYMBOL"===e.type&&t.includes(e.value.toUpperCase())))return[];let r;try{r=sm(e)}catch{return[]}return function(e,t){return am(e).filter(e=>"FUNCALL"===e.type&&t.includes(e.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}(r,t)}class JE extends Ts{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}}const eS=Bg.mapping;function tS(e,t,r){return new rS(e,t,r).getParameters()}class rS{getters;computeCell;evalContext;rangeCache={};constructor(e,t,r){this.getters=t,this.computeCell=r,this.evalContext=Object.assign(Object.create(eS),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){const r=this.getRangeError(e);if(r)return r;const n={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};if(t){this.computeCell(n);return{value:mo(this.getters.getSheetName(e.sheetId),Go(e.zone))}}return this.computeCell(n)}range(e,t){const r=this.getRangeError(e);if(r)return[[r]];const n=e.sheetId,o=e.zone,s=Yo(o,this.getters.getSheetZone(n));if(!s)return[[]];const{top:i,left:a,bottom:l,right:c}=o,u=`${n}-${i}-${a}-${l}-${c}-${t}`;if(u in this.rangeCache)return this.rangeCache[u];const h=s.bottom-s.top+1,d=s.right-s.left+1,f=new Array(d),g=this.getters.getSheetName(e.sheetId);for(let e=s.left;e<=s.right;e++){const r=e-s.left;f[r]=new Array(h);for(let o=s.top;o<=s.bottom;o++){const i=o-s.top,a=this.computeCell({sheetId:n,col:e,row:o});f[r][i]=t?{value:mo(g,Do(e,o))}:a}}return this.rangeCache[u]=f,f}getRangeError(e){return zo(e.zone)?e.invalidSheetName?new I(v("Invalid sheet name: %s",e.invalidSheetName)):void 0:new I}}function nS(e,t,r,n,o){oS(e,t,r||0,n||e.length-1,o||iS)}function oS(e,t,r,n,o){for(;n>r;){if(n-r>600){var s=n-r+1,i=t-r+1,a=Math.log(s),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(s-l)/s)*(i-s/2<0?-1:1);oS(e,t,Math.max(r,Math.floor(t-i*l/s+c)),Math.min(n,Math.floor(t+(s-i)*l/s+c)),o)}var u=e[t],h=r,d=n;for(sS(e,r,t),o(e[n],u)>0&&sS(e,r,n);h<d;){for(sS(e,h,d),h++,d--;o(e[h],u)<0;)h++;for(;o(e[d],u)>0;)d--}0===o(e[r],u)?sS(e,r,d):sS(e,++d,n),d<=t&&(r=d+1),t<=d&&(n=d-1)}}function sS(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function iS(e,t){return e<t?-1:e>t?1:0}class aS{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(!yS(e,t))return r;const n=this.toBBox,o=[];for(;t;){for(let s=0;s<t.children.length;s++){const i=t.children[s],a=t.leaf?n(i):i;yS(e,a)&&(t.leaf?r.push(i):vS(e,a)?this._all(i,r):o.push(i))}t=o.pop()}return r}collides(e){let t=this.data;if(!yS(e,t))return!1;const r=[];for(;t;){for(let n=0;n<t.children.length;n++){const o=t.children[n],s=t.leaf?this.toBBox(o):o;if(yS(e,s)){if(t.leaf||vS(e,s))return!0;r.push(o)}}t=r.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=wS([]),this}remove(e,t){if(!e)return this;let r=this.data;const n=this.toBBox(e),o=[],s=[];let i,a,l;for(;r||o.length;){if(r||(r=o.pop(),a=o[o.length-1],i=s.pop(),l=!0),r.leaf){const n=lS(e,r.children,t);if(-1!==n)return r.children.splice(n,1),o.push(r),this._condense(o),this}l||r.leaf||!vS(r,n)?a?(i++,r=a.children[i],l=!1):r=null:(o.push(r),s.push(i),i=0,a=r,r=r.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const r=[];for(;e;)e.leaf?t.push(...e.children):r.push(...e.children),e=r.pop();return t}_build(e,t,r,n){const o=r-t+1;let s,i=this._maxEntries;if(o<=i)return s=wS(e.slice(t,r+1)),cS(s,this.toBBox),s;n||(n=Math.ceil(Math.log(o)/Math.log(i)),i=Math.ceil(o/Math.pow(i,n-1))),s=wS([]),s.leaf=!1,s.height=n;const a=Math.ceil(o/i),l=a*Math.ceil(Math.sqrt(i));ES(e,t,r,l,this.compareMinX);for(let o=t;o<=r;o+=l){const t=Math.min(o+l-1,r);ES(e,o,t,a,this.compareMinY);for(let r=o;r<=t;r+=a){const o=Math.min(r+a-1,t);s.children.push(this._build(e,r,o,n-1))}}return cS(s,this.toBBox),s}_chooseSubtree(e,t,r,n){for(;n.push(t),!t.leaf&&n.length-1!==r;){let r,n=1/0,o=1/0;for(let s=0;s<t.children.length;s++){const i=t.children[s],a=gS(i),l=pS(e,i)-a;l<o?(o=l,n=a<n?a:n,r=i):l===o&&a<n&&(n=a,r=i)}t=r||t.children[0]}return t}_insert(e,t,r){const n=r?e:this.toBBox(e),o=[],s=this._chooseSubtree(n,this.data,t,o);for(s.children.push(e),hS(s,n);t>=0&&o[t].children.length>this._maxEntries;)this._split(o,t),t--;this._adjustParentBBoxes(n,o,t)}_split(e,t){const r=e[t],n=r.children.length,o=this._minEntries;this._chooseSplitAxis(r,o,n);const s=this._chooseSplitIndex(r,o,n),i=wS(r.children.splice(s,r.children.length-s));i.height=r.height,i.leaf=r.leaf,cS(r,this.toBBox),cS(i,this.toBBox),t?e[t-1].children.push(i):this._splitRoot(r,i)}_splitRoot(e,t){this.data=wS([e,t]),this.data.height=e.height+1,this.data.leaf=!1,cS(this.data,this.toBBox)}_chooseSplitIndex(e,t,r){let n,o=1/0,s=1/0;for(let i=t;i<=r-t;i++){const t=uS(e,0,i,this.toBBox),a=uS(e,i,r,this.toBBox),l=bS(t,a),c=gS(t)+gS(a);l<o?(o=l,n=i,s=c<s?c:s):l===o&&c<s&&(s=c,n=i)}return n||r-t}_chooseSplitAxis(e,t,r){const n=e.leaf?this.compareMinX:dS,o=e.leaf?this.compareMinY:fS;this._allDistMargin(e,t,r,n)<this._allDistMargin(e,t,r,o)&&e.children.sort(n)}_allDistMargin(e,t,r,n){e.children.sort(n);const o=this.toBBox,s=uS(e,0,t,o),i=uS(e,r-t,r,o);let a=mS(s)+mS(i);for(let n=t;n<r-t;n++){const t=e.children[n];hS(s,e.leaf?o(t):t),a+=mS(s)}for(let n=r-t-1;n>=t;n--){const t=e.children[n];hS(i,e.leaf?o(t):t),a+=mS(i)}return a}_adjustParentBBoxes(e,t,r){for(let n=r;n>=0;n--)hS(t[n],e)}_condense(e){for(let t,r=e.length-1;r>=0;r--)0===e[r].children.length?r>0?(t=e[r-1].children,t.splice(t.indexOf(e[r]),1)):this.clear():cS(e[r],this.toBBox)}}function lS(e,t,r){if(!r)return t.indexOf(e);for(let n=0;n<t.length;n++)if(r(e,t[n]))return n;return-1}function cS(e,t){uS(e,0,e.children.length,t,e)}function uS(e,t,r,n,o){o||(o=wS(null)),o.minX=1/0,o.minY=1/0,o.maxX=-1/0,o.maxY=-1/0;for(let s=t;s<r;s++){const t=e.children[s];hS(o,e.leaf?n(t):t)}return o}function hS(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 dS(e,t){return e.minX-t.minX}function fS(e,t){return e.minY-t.minY}function gS(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function mS(e){return e.maxX-e.minX+(e.maxY-e.minY)}function pS(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 bS(e,t){const r=Math.max(e.minX,t.minX),n=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),s=Math.min(e.maxY,t.maxY);return Math.max(0,o-r)*Math.max(0,s-n)}function vS(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function yS(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function wS(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function ES(e,t,r,n,o){const s=[t,r];for(;s.length;){if((r=s.pop())-(t=s.pop())<=n)continue;const i=t+Math.ceil((r-t)/n/2)*n;nS(e,i,t,r,o),s.push(t,i,i,r)}}class SS{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 CS,this.rTrees[e].load(t[e])}insert(e){const t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new CS),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 CS extends aS{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 TS{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){No(this.profilesStartingPosition,this.profiles,[e])}delete(e){No(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return function(e,t,r){const n=r.left,o=r.right,s=r.top,i=r.bottom+1,a=ko(e,n,0),l=ko(e,o,a);if(-1===a||-1===l)return!1;for(let r=a;r<=l;r++){const n=t.get(e[r]),o=ko(n,s,0,!0),a=Uo(n,i,0,!0);if(-1===o||o%2!=0)return!1;if(s<n[o]||i>n[a])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 TS;e.profilesStartingPosition=[...this.profilesStartingPosition],e.profiles=new Map;for(const[t,r]of this.profiles)e.profiles.set(t,[...r]);return e}size(){let e=0;for(const t of this.profiles.values())e+=t.length;return e/2}[Symbol.iterator](){return Po(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}}class IS{setsBySheetId={};constructor(e=[]){for(const t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new TS),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(const t of e)this.add(t)}addPosition(e){this.add(Mm(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(Mm(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(Mm(t))}difference(e){const t=new IS;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 IS;for(const t in this.setsBySheetId)e.setsBySheetId[t]=this.setsBySheetId[t].copy();return e}clear(){this.setsBySheetId={}}size(){let e=0;for(const t in this.setsBySheetId)e+=this.setsBySheetId[t].size();return e}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 xS{rTree;constructor(e=[]){const t=function(e){let t=0,r=0;for(let n=0;n<e.length;n++){const o=e[n].boundingBox.zone;o.right>t&&(t=o.right),o.bottom>r&&(r=o.bottom)}t+=1,r+=1;const n=(((r+1)*t+1)*r+1)*t<=Number.MAX_SAFE_INTEGER;n||console.warn("Max col/row size exceeded, using slow zone key");const o={};for(const s of e){const e=s.boundingBox.sheetId;o[e]||(o[e]={});const i=s.boundingBox.zone;let a=0;if(a=n?i.left+i.top*t+i.right*t*r+i.bottom*t*r*t:`${i.left},${i.top},${i.right},${i.bottom}`,o[e][a]){o[e][a].data.add(s.data)}else o[e][a]={boundingBox:s.boundingBox,data:new IS([s.data])}}const s=[];for(const e in o){const t=o[e];for(const e in t)s.push(t[e])}return s}(e);this.rTree=new SS(t)}insert(e){const t=this.rTree.search(e.boundingBox),r=e.boundingBox,n=t.find(({boundingBox:e})=>e.sheetId===r.sheetId&&e.zone.left===r.zone.left&&e.zone.top===r.zone.top&&e.zone.right===r.zone.right&&e.zone.bottom===r.zone.bottom);n?n.data.add(e.data):this.rTree.insert({...e,data:new IS([e.data])})}search({zone:e,sheetId:t}){const r=new IS;for(const{data:n}of this.rTree.search({zone:e,sheetId:t}))r.addMany(n);return r}remove(e){const t=this.rTree.search(e.boundingBox),r=e.boundingBox,n=t.find(({boundingBox:e})=>e.sheetId===r.sheetId&&e.zone.left===r.zone.left&&e.zone.top===r.zone.top&&e.zone.right===r.zone.right&&e.zone.bottom===r.zone.bottom);n?n.data.delete(e.data):this.rTree.remove({...e,data:new IS([e.data])})}}class RS{dependencies=new fE;rTree;constructor(e=[]){this.rTree=new xS(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:ss(e)},boundingBox:{zone:r,sheetId:t}}));for(const e of r)this.rTree.insert(e);const n=this.dependencies.get(e);n?n.push(...r):this.dependencies.set(e,r)}getCellsDependingOn(e,t=new IS){t=t.copy();const r=Array.from(e).reverse();for(;r.length>0;){const e=r.pop();t.add(e);const n=this.rTree.search(e);r.push(...n.difference(t))}for(const r of e)t.delete(r);return t}}class AS extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){const r=function(e){if(0===e)return-1/0;if(e<0)return NaN;return 32-Math.clz32(--e)}(t),n=new this((e<<r>>5)+1);return n.columnOffset=r,n.cols=t,n.rows=e,n}getValue(e){const[t,r]=this.getCoordinates(e);return this[t]>>r&1}setValue(e,t){const[r,n]=this.getCoordinates(e),o=0===(this[r]>>n&1)&&1===t;return this[r]=this[r]&~(1<<n)|t<<n,o}isEmpty(){return!this.some(e=>0!==e)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){const{row:t,col:r}=e,n=(t<<this.columnOffset)+r,o=n>>5;return[o,n-(o<<5)]}}class _S{sheets={};insertions=[];maxSize=0;constructor(e){for(const t in e){const r=e[t].cols,n=e[t].rows;this.maxSize+=r*n,this.sheets[t]=AS.create(n,r)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(const t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(const t of e)this.delete(t)}has(e){return 1===this.sheets[e.sheetId].getValue(e)}clear(){const e=[...this];this.insertions=[];for(const e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(0===this.insertions.length)return!0;for(const e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=new Array(this.maxSize);let e=0;for(const t in this.sheets){const r=this.sheets[t];r.fillAllPositions();for(let n=0;n<r.rows;n++)for(let o=0;o<r.cols;o++)this.insertions[e++]={sheetId:t,row:n,col:o}}}*[Symbol.iterator](){for(const e of this.insertions)1===this.sheets[e.sheetId].getValue(e)&&(yield e)}}class OS{resultsToArrayFormulas=new SS;arrayFormulasToResults=new fE;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||DS}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:ss(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 DS=[],FS=new fd;FS.add("pivots",e=>{for(const t of e.getPivotIds()){const r=e.getPivot(t);r.markAsDirtyForEvaluation?.()}});const NS=Object.freeze(qy({...new T,origin:void 0})),MS=Object.freeze(qy({value:null}));class VS{context;getters;compilationParams;evaluatedCells=new fE;formulaDependencies=xe(new RS);blockedArrayFormulas=new _S({});spreadingRelations=new OS;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=tS(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||MS}getSpreadZone(e,t={ignoreSpillError:!1}){const r=this.spreadingRelations.getArrayResultZone(e);if(!r)return;const n=this.evaluatedCells.get(e);return n?.type!==Eu.error||t.ignoreSpillError&&n?.value===w.SpilledBlocked?Zo(ss(e),r):ss(e)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===Eu.empty)return;return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,ss(e)).find(e=>!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){const t=e.sheetId,{left:r,bottom:n,right:o,top:s}=e.zone;for(let e=r;e<=o;e++)for(let r=s;r<=n;r++)this.computeAndSave({sheetId:t,col:e,row:r})}}updateCompilationParameters(){this.compilationParams=tS(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 _S(e)}evaluateCells(e){const t=performance.now(),r=new IS;r.addManyPositions(e);const n=this.getArrayFormulasImpactedByChangesOf(e);r.addMany(this.getCellsDependingOn(r)),r.addMany(n),r.addMany(this.getCellsDependingOn(n)),this.evaluate(r),console.debug("evaluate Cells",performance.now()-t,"ms")}getArrayFormulasImpactedByChangesOf(e){const t=new IS;for(const r of e){const e=this.getters.getCell(r)?.content,n=this.getArrayFormulaSpreadingOn(r);void 0!==n&&t.addPosition(n),e||t.addPosition(r)}for(const e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new OS,this.formulaDependencies=xe(()=>{const e=[];for(const t of this.getters.getSheetIds()){const r=this.getters.getCells(t);for(const n in r){const o=r[n];if(o.isFormula){const r=o.compiledFormula.dependencies;for(const o of r)o.invalidSheetName||o.invalidXc||e.push({data:{sheetId:t,zone:ss(this.getters.getCellPosition(n))},boundingBox:{sheetId:o.sheetId,zone:o.zone}})}}}return new RS(e)})}evaluateAllCells(){const e=performance.now();this.evaluatedCells=new fE;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=gm(t),n=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParameters(),this.evaluateCompiledFormula(e,{...r,dependencies:n})}evaluateCompiledFormula(e,t,r){try{const n=kS(t,this.compilationParams,e,this.buildSafeGetSymbolValue(r),this.compilationParams.evalContext.__originCellPosition);return O(n)?nr(n,PS):PS(n)}catch(e){return Er(e,"")}}getArrayFormulasBlockedBy(e,t){const r=new IS,n=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);r.addManyPositions(n);const o=[...n].filter(e=>!this.blockedArrayFormulas.has(e));return o.length&&r.deleteManyPositions(o),r.addMany(this.getCellsDependingOn(r)),r}nextRangesToUpdate=new IS;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new IS(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();const e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(const t of e){const{left:e,bottom:r,right:n,top:o}=t.zone;for(let s=e;s<=n;s++)for(let e=o;e<=r;e++){const r={sheetId:t.sheetId,col:s,row:e};if(this.nextRangesToUpdate.hasPosition(r))continue;const n=this.computeCell(r);n!==MS&&this.evaluatedCells.set(r,n)}}FS.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn("Maximum iteration reached while evaluating cells")}clearEvaluatedRanges(e){for(const t of e){const{left:e,bottom:r,right:n,top:o}=t.zone;for(let s=e;s<=n;s++)for(let e=o;e<=r;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:s,row:e})}}computeCell(e){const t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);const r=this.getters.getCell(e);if(void 0===r)return MS;const n=r.id,o={format:r.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(n)?NS:(this.cellsBeingComputed.add(n),r.isFormula?this.computeFormulaCell(e,r):Gy(r,o,e))}catch(t){return t.value=t?.value||w.GenericError,t.message=t?.message||Cr,t.origin=e,qy(t)}finally{this.cellsBeingComputed.delete(n)}}computeAndSave(e){const t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){const r=kS(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!O(r)){const n=qy(PS(r),this.getters.getLocale(),t,e);return n.type===Eu.error&&(n.errorOriginPosition=r.errorOriginPosition??e),n}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,r);const n=r.length,o=r[0].length,s={top:e.row,bottom:e.row+o-1,left:e.col,right:e.col+n-1};return this.spreadingRelations.addRelation({resultZone:s,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,r),LS(n,o,this.checkCollision(e)),LS(n,o,this.spreadValues(e,r)),this.invalidatePositionsDependingOnSpread(e.sheetId,s),qy(PS(r[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){const r=this.getCellsDependingOn(function(e){const{top:t,left:r,bottom:n,right:o}=e;if(1===cs(e))return[];const s={top:t+1,bottom:n,left:r,right:r};if(o===r)return[s];const i={top:t,bottom:n,left:r+1,right:o};return t===n?[i]:[s,i]}(t).map(t=>({sheetId:e,zone:t})));r.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(r)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:r},n){const o=this.getters.getNumberCols(e),s=this.getters.getNumberRows(e),i=t+n.length<=o,a=r+n[0].length<=s;if(!i||!a){if(i)throw new A(v("Result couldn't be automatically expanded. Please insert more rows."));if(a)throw new A(v("Result couldn't be automatically expanded. Please insert more columns."));throw new A(v("Result couldn't be automatically expanded. Please insert more columns and rows."))}}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:r},n){if(0!==this.getters.getMergesInZone(e,{top:r,bottom:r+n[0].length-1,left:t,right:t+n.length-1}).length)throw new A(v("Merged cells found in the spill zone. Please unmerge cells before using array formulas."))}checkCollision(e){const{sheetId:t,col:r,row:n}=e;return(o,s)=>{const i={sheetId:t,col:o+r,row:s+n},a=this.getters.getCell(i);if(a?.content||this.getters.getEvaluatedCell(i).type!==Eu.empty)throw this.blockedArrayFormulas.add(e),new A(v("Array result was not expanded because it would overwrite data in %s.",Do(i.col,i.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:r},n){return(o,s)=>{const i={sheetId:e,col:o+t,row:s+r},a=this.getters.getCell(i),l=qy(PS(n[o][s]),this.getters.getLocale(),a,i);l.type===Eu.error&&(l.errorOriginPosition=n[o][s].errorOriginPosition??i),this.evaluatedCells.set(i,l)}}invalidateSpreading(e){const t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let r=t.left;r<=t.right;r++)for(let n=t.top;n<=t.bottom;n++){const t={sheetId:e.sheetId,col:r,row:n},o=this.getters.getCell(t)?.content;o||this.evaluatedCells.delete(t)}const r=e.sheetId;this.invalidatePositionsDependingOnSpread(r,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(r,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return NS;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 LS(e,t,r){for(let n=0;n<e;++n)for(let e=0;e<t;++e)0===n&&0===e||r(n,e)}function PS(e){return null===e.value||void 0===e.value?{...e,value:0}:e}function kS(e,t,r,n,o){return t.evalContext.__originCellPosition=o,t.evalContext.__originSheetId=r,e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,n,t.evalContext)}function US(e,t=1){return t*(e+4)-4}function HS(e=100,t=100){return new OffscreenCanvas(e,t).getContext("2d")}function BS(e,t,r,n){const o=KS(e,t,r,"wrap"===r?.wrapping?n-8:void 0).length;return US(jS(r),o)+6}function zS(e,t=!1,r=!1){return`${r?"italic":""} ${t?"bold":""} ${e}px ${Z}`}const $S={};function GS(e,t,r,n="pt"){return WS(e,t,YS(r,n))}function WS(e,t,r){if($S[r]||($S[r]={}),void 0===$S[r][t]){const n=e.font;e.font=r,$S[r][t]=e.measureText(t).width,e.font=n}return $S[r][t]}const qS={};function ZS(e,t,r,n="pt"){const o=YS(r,n);e.save(),e.font=o;const s=function(e,t){const r=e.font;qS[r]||(qS[r]={});if(void 0===qS[r][t]){const n=e.measureText(t),o=n.width,s=n.fontBoundingBoxAscent+n.fontBoundingBoxDescent;qS[r][t]={width:o,height:s}}return qS[r][t]}(e,t);return e.restore(),s}function YS(e,t="pt"){return`${e.italic?"italic ":""}${e.bold?"bold":"400"} ${("pt"===t?jS(e):e.fontSize)??q}px ${Z}`}function jS(e){return t=e?.fontSize||q,Math.round(96*t/72);var t}function XS(e,t,r,n){if(GS(e,t,n)<=r)return[t];const o=[];let s="";for(const i of t){GS(e,s+i,n)>r?(o.push(s),s=i):s+=i}return o.push(s),o}function KS(e,t,r,n){r||(r={}),ge(t)&&(t=be(t).label);const o=[],s=t.includes(Q)?t.split(Q):[t];for(const t of s){const s=t.includes(" ")?t.split(" "):[t];if(!n){o.push(t);continue}let i="",a=n;for(const t of s){const s=XS(e,t,n,r),l=s.pop(),c=GS(e,l,r);if(s.length)""!==i&&(o.push(i),i="",a=n),s.forEach(e=>{o.push(e)}),i=l,a=n-c;else{const t=""===i?l:" "+l,s=GS(e,t,r);s<=a?(i+=t,a-=s):(o.push(i),i=l,a=n-c)}}""!==i&&o.push(i)}return o}function QS(e){return e?e.toLowerCase():""}const JS=/([0-9\.]*)px/;function eC(e,t,r){let n=WS(e,t,e.font);if(n<=r)return t;const o=WS(e,"…",e.font);if(n<=o)return t;let s=t.length;for(;n>=r-o&&s-- >0;)n=WS(e,t=t.substring(0,s),e.font);return t+"…"}function tC(e,t,r,n=!1,o=!1,s=function(e){return Number(e.match(JS)?.[1])}(e.font)/10){if(e.fillText(t,r.x,r.y),!n&&!o)return;const i=e.measureText(t),a=i.width,l=i.actualBoundingBoxAscent+i.actualBoundingBoxDescent,c=i.fontBoundingBoxAscent+i.fontBoundingBoxDescent;let{x:u,y:h}=r,d=h,f=h;switch(e.textAlign){case"center":u-=a/2;break;case"right":u-=a}switch(e.textBaseline){case"top":f+=c-2*s,d+=c/2-s;break;case"middle":f+=c/2-s;break;case"alphabetic":f+=2*s,d-=3*s;break;case"bottom":f=h,d-=l/2-s/2}n&&(e.lineWidth=s,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+a,f),e.stroke()),o&&(e.lineWidth=s,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,d),e.lineTo(u+a,d),e.stroke())}const rC=new fd;rC.add("data_validation_checkbox",(e,t)=>{if(e.isCellValidCheckbox(t)){const r=!!e.getEvaluatedCell(t).value;return{svg:r?hv:cv,hoverSvg:r?hv:uv,priority:2,horizontalAlign:"center",size:17,margin:2,position:t,type:"data_validation_checkbox",onClick:(e,t)=>{const n=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||!!n?.isFormula)return;const o=r?"FALSE":"TRUE";t.model.dispatch("UPDATE_CELL",{...e,content:o})}}}}),rC.add("data_validation_chip_icon",(e,t)=>{const r=e.getDataValidationChipStyle(t);if(r){const n=e.getCellComputedStyle(t);return{svg:av(r),hoverSvg:lv(r),priority:10,horizontalAlign:"right",size:jS(n),margin:4,position:t,onClick:(e,t)=>{const{col:r,row:n}=e;t.model.selection.selectCell(r,n),t.startCellEdition()},type:"data_validation_chip_icon"}}}),rC.add("data_validation_list_icon",(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){const n=e.getCellComputedStyle(t);return{svg:sv(n),hoverSvg:(r=n,{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:r.textColor||k,path:"M15 15 h482 v482 h-482"},{fillColor:r.fillColor||"#fff",path:"M120 195 h270 l-135 130"}]}),priority:2,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const{col:r,row:n}=e;t.model.selection.selectCell(r,n),t.startCellEdition()},type:"data_validation_list_icon"}}var r}),rC.add("conditional_formatting",(e,t)=>{const r=e.getConditionalIcon(t);if(r){const n=e.getCellStyle(t);return{type:"conditional_formatting",svg:fv[r].svg,priority:1,horizontalAlign:"left",size:jS(n),margin:4,position:t}}}),rC.add("pivot_collapse",(e,t)=>{if(!e.isSpillPivotFormula(t))return;const r=e.getPivotCellFromPosition(t),n=e.getPivotIdFromPosition(t);if("HEADER"===r.type&&n&&r.domain.length){const o=e.getPivotCoreDefinition(n),s=e.isDashboard(),i="COL"===r.dimension?o.columns:o.rows,a=!s&&r.domain.length!==i.length,l=(o.collapsedDomains?.[r.dimension]??[]).some(e=>Ae(e,r.domain)),c="ROW"===r.dimension?15*(r.domain.length-1):0;return{type:"pivot_collapse",priority:4,horizontalAlign:"left",size:a||!s&&"ROW"===r.dimension&&o.rows.length>1?12:0,margin:a?4+c:c,svg:a?dv(l,!1):void 0,hoverSvg:a?dv(l,!0):void 0,position:t,onClick:Zd}}}),rC.add("pivot_dashboard_sorting",(e,t)=>{if(!e.isDashboard())return;if("MEASURE_HEADER"!==e.getPivotCellFromPosition(t).type)return;const r=e.getPivotCellSortDirection(t);if("asc"!==r&&"desc"!==r)return;const n=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${r}`,priority:5,horizontalAlign:"right",size:17,margin:2,svg:"asc"===r?(o=n,{name:"CARET_UP",width:512,height:512,paths:[{fillColor:o.textColor||k,path:"M120 325 h270 l-135 -130"}]}):sv(n),position:t,onClick:void 0};var o});const nC=/"(#[0-9a-fA-F]{6})"/g;const oC=12,sC="#F3F2F1";function iC(e,t,r){const n=r??function(e){if(e instanceof HTMLCanvasElement){const t=e.getBoundingClientRect();return{width:t.width,height:t.height}}return{width:e.width,height:e.height}}(e),o="number"==typeof globalThis.devicePixelRatio?globalThis.devicePixelRatio:1;e.width=n.width*o,e.height=n.height*o;const s=e.getContext("2d");if(!s)throw new Error("Unable to retrieve 2D context from canvas");s.scale(o,o);const i=function(e,t,r){const n=t.maxValue,o=t.minValue,s=dC(t,"animated"),i=function(e,t){const r=t?25:0,n=e.height-20-r-10,o=e.width-60;let s,i;o>2*n?(s=2*n,i=n):(s=o,i=o/2);const a=r+10+(n-i)/2;return{x:30+(o-s)/2,y:a,width:s,height:i}}(e,t.title.text),a=i.width/6,l=s?(s-o.value)/(n.value-o.value):0,c={x:e.width/2,y:i.y+i.height-i.height/12};let u=80;i.height<300&&(u*=i.height/300);const h=i.width/2,d=t.gaugeValue?.label||"-";GS(r,d,{fontSize:u},"px")>h&&(u=function(e,t,r,n=.25){let o=1;if(r(o)>e)return o;if(r(t)<e)return t;let s=(o+t)/2,i=r(s),a=0;for(;Math.abs(i-e)>n&&a<20;)i>=e?t=(o+t)/2:o=(o+t)/2,s=(o+t)/2,i=r(s),a++;return s}(h,u,e=>GS(r,d,{fontSize:e},"px")));const f={x:i.x+a/2,y:i.y+i.height+oC},g={x:i.x+i.width-a/2,y:i.y+i.height+oC},m=Mb(t.background),p=function(e,t,r,n){const o=e.maxValue,s=e.minValue,i={x:t.x+t.width/2,y:t.y+t.height},a={fontSize:oC},l=[],c=[];for(const u of e.inflectionValues){const e=(u.value-s.value)/(o.value-s.value),h=GS(n,u.label,a,"px"),d=Math.PI-Math.PI*e,f=hC(d,t.height+6,i.x,i.y,h+2,oC),g=c.some(e=>uC(e,f))?oC:0;c.push(f),l.push({rotation:d,label:u.label,fontSize:oC,color:r,offset:g})}return l}(t,i,m,r);let b=0,v=0,y=0;t.title.text&&({width:v,height:y}=ZS(r,t.title.text,{fontSize:B,...t.title},"px"));switch(t.title.align){case"right":b=e.width-v-H;break;case"center":b=(e.width-v)/2;break;default:b=H}return{width:e.width,height:e.height,title:{label:t.title.text??"",fontSize:t.title.fontSize??B,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:aC(t)},inflectionValues:p,gaugeValue:{label:d,textPosition:c,fontSize:u,color:m},minLabel:{label:t.minValue.label,textPosition:f,fontSize:oC,color:m},maxLabel:{label:t.maxValue.label,textPosition:g,fontSize:oC,color:m}}}({...n,x:0,y:0},t,s);!function(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}(s,i),function(e,t){e.save();const r=t.gauge,n=r.rect.x+r.rect.width/2,o=r.rect.y+r.rect.height,s=r.rect.height-r.arcWidth/2;if(s<0)return;const i=1===r.percentage?0:Math.PI*(1+r.percentage);e.strokeStyle=sC,e.beginPath(),e.lineWidth=r.arcWidth,e.arc(n,o,s,i,0),e.stroke(),e.strokeStyle=r.color,e.beginPath(),e.arc(n,o,s,Math.PI,i),e.stroke(),e.restore()}(s,i),function(e,t){const{x:r,y:n,width:o,height:s}=t.gauge.rect;for(const i of t.inflectionValues){e.save(),e.translate(r+o/2-.5,n+s-.5),e.rotate(Math.PI/2-i.rotation),e.lineWidth=2,e.strokeStyle=Mb(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=zS(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 aC(e){const t=dC(e,"final");if(void 0===t)return sC;for(let r=0;r<e.inflectionValues.length;r++){const n=e.inflectionValues[r];if("<"===n.operator&&t<n.value)return e.colors[r];if("<="===n.operator&&t<=n.value)return e.colors[r]}return e.colors.at(-1)}function lC(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 cC(e,t){const r=e.start,n=e.end,o=t.start,s=t.end;function i(e,t,r){return(r.y-e.y)*(t.x-e.x)>(t.y-e.y)*(r.x-e.x)}return i(r,o,s)!==i(n,o,s)&&i(r,n,o)!==i(r,n,s)}function uC(e,t){const r=lC(e),n=lC(t);for(const e of r)for(const t of n)if(cC(e,t))return!0;return!1}function hC(e,t,r,n,o,s){const i=Math.cos(e),a=Math.sin(e),l=i*t,c=a*t,u=a*(o/2),h=i*(o/2),d=i*(t+s),f=a*(t+s);return{bottomLeft:{x:l-u+r,y:n-(c+h)},bottomRight:{x:l+u+r,y:n-(c-h)},topRight:{x:d+u+r,y:n-(f-h)},topLeft:{x:d-u+r,y:n-(f+h)}}}function dC(e,t){return"animated"===t&&void 0!==e.animationValue?e.animationValue:e.gaugeValue?.value}const fC=globalThis.Path2D,gC=fC&&new fC("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"),mC=fC&&new fC("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 pC=.05;function bC(e,t){const r=e||"";return t&&r?" "+r:r}class vC{runtime;context;width;height;constructor({width:e,height:t},r){if(this.runtime=r,this.width=e,this.height=t,"undefined"==typeof OffscreenCanvas)throw new Error("OffscreenCanvas is not supported in this environment");const n=new globalThis.OffscreenCanvas(e,t).getContext("2d");if(!n)throw new Error("Unable to create scorecard measurement context");this.context=n}computeDesign(){const e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles();let r=0;if(this.title){let n,o;switch(({height:r,width:o}=this.getFullTextDimensions(this.title,t.title.font)),this.runtime.title.align){case"center":n=(this.width-o)/2;break;case"right":n=this.width-o-H;break;default:n=H}e.title={text:this.title,style:t.title,position:{x:n,y:10+r/2}}}const n=t.baselineArrow?.size??0;let{height:o,width:s}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(o=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);const i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width;let a;switch(this.runtime.baselineStyle?.align){case"right":a=this.width-H-i-s;break;case"left":a=H+n;break;default:a=(this.width-s-i+n)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:a,y:this.keyValue?this.height*(1-pC*(this.runtime.progressBar?1:2)):this.height-(this.height-r-o)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-n,y:e.baseline.position.y-(o+n)/2}})),e.baseline&&this.baselineDescr){const r={x:e.baseline.position.x+s,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:r}}let l=0;this.runtime.progressBar&&(l=.05*this.height,e.progressBar={position:{x:40,y:.9*this.height-o-l},dimension:{height:l,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});const{width:c,height:u}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),h=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width;let d;switch(this.runtime.keyValueStyle?.align){case"right":d=this.width-H-h-c;break;case"left":d=H;break;default:d=(this.width-c-h)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(H,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 bC(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return bC(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return Mb(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;const r=this.context.measureText(e);return{width:r.width,height:r.actualBoundingBoxAscent+r.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;const r=this.context.measureText(e);return{width:r.width,height:r.fontBoundingBoxAscent+r.fontBoundingBoxDescent}}getTextStyles(){const e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e);let r=this.runtime.baselineStyle?.fontSize??16;const n=Math.floor(.9*r);return this.runtime.progressBar&&(r/=1.5),{title:{font:zS(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:zS(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:zS(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:zS(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:zS(n,this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:"neutral"===this.baselineArrow||this.runtime.progressBar?void 0:{size:this.keyValue?.8*r:0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}}async function yC(e,t,r){const n=(o=t.width,s=t.height,new OffscreenCanvas(o,s));var o,s;let i;if("chartJsConfig"in e){const t=re(e.chartJsConfig);t.plugins=[wC];const r=new globalThis.Chart(n,t);try{i=await EC(n)}finally{r.destroy()}}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 vC({width:e,height:t},r).computeDesign()}(t,e);!function(e,t){const r=t.getContext("2d");if(!r)throw new Error("Unable to retrieve 2D context from canvas");const n="number"==typeof globalThis.devicePixelRatio?globalThis.devicePixelRatio:1;t.width=n*e.canvas.width,t.height=n*e.canvas.height,r.scale(n,n);const o=e.canvas.width-H;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(eC(r,e.title.text,o-e.title.position.x),e.title.position.x,e.title.position.y),r.textBaseline=t}if(e.baseline&&(r.font=e.baseline.style.font,r.fillStyle=e.baseline.style.color,tC(r,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&fC){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(gC);break;case"up":r.fill(mC)}r.restore()}if(e.baselineDescr){const t=e.baselineDescr;r.font=t.style.font,r.fillStyle=t.style.color,r.fillText(eC(r,t.text,o-t.position.x),t.position.x,t.position.y)}if(e.key&&(r.font=e.key.style.font,r.fillStyle=e.key.style.color,tC(r,eC(r,e.key.text,o-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){const t=e.keyDescr;r.font=e.keyDescr?.style.font??t.style.font,r.fillStyle=t.style.color,r.fillText(eC(r,t.text,o-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(r.fillStyle=e.progressBar.style.backgroundColor,r.beginPath(),r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),r.fill(),r.fillStyle=e.progressBar.style.color,r.beginPath(),e.progressBar.value>0)r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{const t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));r.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}r.fill()}}(r,n),i=await EC(n)}else"gauge"===r&&(iC(n,e,t),i=await EC(n))}return i}const wC={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 EC(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){if(!URL.createObjectURL)throw new Error("URL.createObjectURL is not supported in this environment");return URL.createObjectURL(t)}}const SC={isValid:!0};const CC=["*","+","&"];function TC(e){switch(e.type){case"FUNCALL":const t=e.args.map(e=>TC(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(IC(e)?`(${TC(e.operand)})`:TC(e.operand))+e.value}const r=xC(e)?`(${TC(e.operand)})`:TC(e.operand);return e.value+r;case"BIN_OPERATION":const n=IC(e)?`(${TC(e.left)})`:TC(e.left),o=xC(e)?`(${TC(e.right)})`:TC(e.right);return n+e.value+o}}function IC(e){const t=e.value,r="left"in e?e.left:e.operand,n=r.value;return"BIN_OPERATION"===r.type&&Jg[n]<Jg[t]}function xC(e){const t=e.value,r="right"in e?e.right:e.operand,n=Jg[r.value],o=Jg[t];return"BIN_OPERATION"===r.type&&(n<o||n===o&&!CC.includes(t))}Ue(function(e){return"\n"+"\t".repeat(e)});const RC=["PIVOT.VALUE","PIVOT.HEADER","PIVOT"];const AC="0.00%";function _C(e){return class extends e{getters;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t){super(e,t),this.getters=t.getters}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){const r=`${e}-${t.map(e=>e.field+"="+e.value).join(",")}`;if(this.cache[r])return this.cache[r];const n=this.getMeasure(e),o=n.computedBy?this.computeMeasure(n,t):super.getPivotCellValueAndFormat(e,t);return n.format?this.cache[r]={...o,format:n.format}:this.cache[r]=o,this.cache[r]}computeMeasure(e,t){if(!e.computedBy)return{value:0};const{columns:r,rows:n}=super.definition;if(e.aggregator&&r.length+n.length!==t.length){const r=this.getValuesToAggregate(e,t),n=Nd[e.aggregator];if(!n)return{value:0};try{return n([r],this.getters.getLocale())}catch(t){return Er(t,e.aggregator.toUpperCase())}}const o=this.getters.getMeasureCompiledFormula(e),s=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,o,e=>{const{columns:r,rows:n}=this.definition;if(r.find(t=>t.nameWithGranularity===e)){const{colDomain:r}=RE(this,t),n=r.findIndex(t=>t.field===e);return-1===n?new x:this.getPivotHeaderValueAndFormat(r.slice(0,n+1))}if(n.find(t=>t.nameWithGranularity===e)){const{rowDomain:r}=RE(this,t),n=r.findIndex(t=>t.field===e);return-1===n?new x:this.getPivotHeaderValueAndFormat(r.slice(0,n+1))}return this.getPivotCellValueAndFormat(e,t)});return O(s)?s[0][0]:s}getValuesToAggregate(e,t){const{rowDomain:r,colDomain:n}=RE(this,t),o=super.getExpandedTableStructure(),s=[];if(0===n.length&&r.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){const t=this.treeToLeafDomains(o.getColTree()),n=this.getSubTreeMatchingDomain(o.getRowTree(),r),i=this.treeToLeafDomains(n);for(const n of t)for(const t of i)s.push(this._getPivotCellValueAndFormat(e.id,r.concat(t).concat(n)));return s}if(r.length===this.definition.rows.length&&0===n.length){const t=o.getColTree(),i=this.getSubTreeMatchingDomain(t,n),a=this.treeToLeafDomains(i,n);for(const t of a)s.push(this._getPivotCellValueAndFormat(e.id,r.concat(t)));return s}if(r.length===this.definition.rows.length&&n.length&&n.length<this.definition.columns.length){const t=this.getSubTreeMatchingDomain(o.getColTree(),n),i=this.treeToLeafDomains(t,n);for(const t of i)s.push(this._getPivotCellValueAndFormat(e.id,r.concat(t)));return s}{const t=o.getRowTree(),i=this.getSubTreeMatchingDomain(t,r),a=this.treeToLeafDomains(i,r);for(const t of a)s.push(this._getPivotCellValueAndFormat(e.id,t.concat(n)));return s}}getSubTreeMatchingDomain(e,t,r=0){if(r>t.length)return[];if(t.length===r)return e;for(const n of e){const e=Ud(this.definition.getDimension(n.field),t[r]?.value);if(n.field===t[r]?.field&&n.value===e)return this.getSubTreeMatchingDomain(n.children,t,r+1)}return[]}treeToLeafDomains(e,t=[]){const r=[];for(const n of e){const e=this.definition.getDimension(n.field),o=[...t,{field:n.field,value:n.value,type:e.type}];0===n.children.length?r.push(o):r.push(...this.treeToLeafDomains(n.children,o))}return r}getMeasureDisplayValue(e,t){const r=this.getMeasure(e),n=this._getPivotCellValueAndFormat(e,t);if(!r.display||"no_calculations"===r.display.type||n.message)return n;const o=r.display.fieldNameWithGranularity;if(o&&!this.isFieldInPivot(o))return{value:w.NotAvailable,message:v('Field "%s" not found in pivot for measure display calculation',o)};try{const e=r.display;switch(e.type){case"%_of_grand_total":return this.asPercentOfGrandTotal(n,r);case"%_of_col_total":return this.asPercentOfColumnTotal(n,r,t);case"%_of_row_total":return this.asPercentOfRowTotal(n,r,t);case"%_of_parent_row_total":return this.asPercentOfParentRowTotal(n,r,t);case"%_of_parent_col_total":return this.asPercentOfParentColumnTotal(n,r,t);case"index":return this.asIndex(n,r,t);case"%_of_parent_total":return this.asPercentOfParentTotal(n,r,t,e);case"running_total":return this.asRunningTotal(n,r,t,e,"running_total");case"%_running_total":return this.asRunningTotal(n,r,t,e,"%_running_total");case"rank_asc":return this.asRank(n,r,t,e,"asc");case"rank_desc":return this.asRank(n,r,t,e,"desc");case"%_of":return this.asPercentOf(n,r,t,e);case"difference_from":return this.asDifferenceFrom(n,r,t,e);case"%_difference_from":return this.asDifferenceFromInPercent(n,r,t,e)}return n}catch(e){return Er(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:AC}}asPercentOfRowTotal(e,t,r){const n=this.getRowTotal(t.id,r);return 0===n?{value:w.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:AC}}asPercentOfColumnTotal(e,t,r){const n=this.getColumnTotal(t.id,r);return 0===n?{value:w.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:AC}}asPercentOfParentRowTotal(e,t,r){const n=function(e,t){const{colDomain:r,rowDomain:n}=RE(e,t);return[...r,...n.slice(0,n.length-1)]}(this,r),o=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,n));return 0===o?{value:""}:{value:this.measureValueToNumber(e)/o,format:AC}}asPercentOfParentColumnTotal(e,t,r){const n=function(e,t){const{colDomain:r,rowDomain:n}=RE(e,t);return[...r.slice(0,r.length-1),...n]}(this,r),o=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,n));return 0===o?{value:""}:{value:this.measureValueToNumber(e)/o,format:AC}}asPercentOfParentTotal(e,t,r,n){const{fieldNameWithGranularity:o}=n;if(!o)return e;if(!FE(o,r))return{value:""};const s=function(e,t,r){let{rowDomain:n,colDomain:o}=RE(e,r);if("row"===NE(e,t)){const e=n.findIndex(e=>e.field===t);if(-1===e)return r;n=n.slice(0,e+1)}else{const e=o.findIndex(e=>e.field===t);if(-1===e)return r;o=o.slice(0,e+1)}return[...n,...o]}(this,o,r),i=this._getPivotCellValueAndFormat(t.id,s),a=this.measureValueToNumber(i);return 0===a?{value:""}:{value:this.measureValueToNumber(e)/a,format:AC}}asIndex(e,t,r){const n=this.measureValueToNumber(e),o=this.getRowTotal(t.id,r),s=this.getColumnTotal(t.id,r),i=this.getGrandTotal(t.id);return 0===o||0===s?{value:w.DivisionByZero}:{value:n*i/(s*o),format:void 0}}asRunningTotal(e,t,r,n,o){const{fieldNameWithGranularity:s}=n;if(!s)return e;const i="running_total"===o?this.runningTotal:this.runningTotalInPercent;let a=i[t.id]?.[s];a||(a=this.computeRunningTotal(t,s,o),i[t.id]||(i[t.id]={}),i[t.id][s]=a);const{rowDomain:l,colDomain:c}=RE(this,r),u=ME(c),h=ME(l),d=a[u]?.[h];return{value:d??"",format:"running_total"===o?e.format:AC}}asPercentOf(e,t,r,n){const{fieldNameWithGranularity:o,value:s}=n;if(void 0===s||!o)return e;if(!FE(o,r))return{value:""};const i=this.getComparisonValue(t,r,o,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:AC}:void 0===a?{value:w.NullError}:{value:a/i,format:AC}}asDifferenceFrom(e,t,r,n){const{fieldNameWithGranularity:o,value:s}=n;if(void 0===s||!o)return e;if(!FE(o,r))return{value:""};const i=this.getComparisonValue(t,r,o,s)||0;return"sameValue"===i?{value:""}:{value:this.measureValueToNumber(e)-i,format:e.format}}asDifferenceFromInPercent(e,t,r,n){const{fieldNameWithGranularity:o,value:s}=n;if(void 0===s||!o)return e;if(!FE(o,r))return{value:""};const i=this.getComparisonValue(t,r,o,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:AC}:{value:""}}asRank(e,t,r,n,o){const{fieldNameWithGranularity:s}=n;if(!s)return e;if(!FE(s,r))return{value:""};const i="asc"===o?this.rankAsc:this.rankDesc;let a=i[t.id]?.[s];a||(a=this.computeRank(t,s,o),i[t.id]||(i[t.id]={}),i[t.id][s]=a);const{rowDomain:l,colDomain:c}=RE(this,r),u=ME(c),h=ME(l),d=a[u]?.[h];return{value:d??""}}computeRank(e,t,r){const n={},o=NE(this,t),s="row"===o?"column":"row";let i=this.getPivotValueCells(e.id);"column"===o&&(i=or(i));for(const a of i){const i=ME(AE(this,s,a[0].domain)),l=a.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:AE(this,o,t.domain)})).filter(e=>FE(t,e.rowDomain)),c=Object.groupBy(l,e=>LE(e.rowDomain,t));for(const e in c)c[e]=Ye(c[e]||[],e=>e.value).filter(e=>void 0!==e.value).sort((e,t)=>"asc"===r?e.value-t.value:t.value-e.value);n[i]={};for(const e of l){const r=ME(AE(this,o,e.domain)),s=c[LE(e.rowDomain,t)];if(!s)continue;const a=s.findIndex(t=>t.value===e.value);-1!==a&&(n[i][r]=a+1)}}return"row"===o?n:je(n)}computeRunningTotal(e,t,r){const n={},o=NE(this,t),s="row"===o?"column":"row";let i=this.getPivotValueCells(e.id);"column"===o&&(i=or(i));for(const a of i){const i=ME(AE(this,s,a[0].domain));n[i]={};const l={},c=a.map(t=>({...t,rowDomain:AE(this,o,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>FE(t,e.rowDomain));for(const e of c){const r=ME(e.rowDomain),o=PE(e.rowDomain,t),s=(l[o]||0)+e.value;l[o]=s,n[i][r]=s}if("%_running_total"===r)for(const e of c){const r=e.rowDomain,o=ME(r),s=PE(r,t),a=n[i][o]||0,c=l[s];n[i][o]=c?a/c:void 0}}return"row"===o?n:je(n)}getGrandTotal(e){const t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){const r=RE(this,t).rowDomain,n=this._getPivotCellValueAndFormat(e,r);return this.measureValueToNumber(n)}getColumnTotal(e,t){const r=RE(this,t).colDomain,n=this._getPivotCellValueAndFormat(e,r);return this.measureValueToNumber(n)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,r,n){const o=n===xE||"(next)"===n?function(e,t,r,n){const o=NE(e,r),s="row"===o?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),i=OE(AE(e,o,t),s,r),a=i?.map(e=>e.value)??[],l=function(e,t){const r=t.find(t=>t.field===e);return r?.value}(r,t);if(void 0===l)return;const c=a.indexOf(l);if(void 0===l||-1===c)return;return DE(t,r,a[ae(c+(n===xE?-1:1),0,a.length-1)])}(this,t,r,n):DE(t,r,n);if(Ae(o,t))return"sameValue";if(!o||!function(e,t){for(const r of t)if(void 0===e.definition.rows.find(e=>e.nameWithGranularity===r.field)&&void 0===e.definition.columns.find(e=>e.nameWithGranularity===r.field))return!1;const{rowDomain:r,colDomain:n}=RE(e,t);return _E(r,e.getExpandedTableStructure().getRowTree())&&_E(n,e.getExpandedTableStructure().getColTree())}(this,o))throw new x;const s=this._getPivotCellValueAndFormat(e.id,o);return this.strictMeasureValueToNumber(s)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>"VALUE"===t.type&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if("number"==typeof e.value)return e.value;if(!e.value)return 0;throw new Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if("number"==typeof e.value)return e.value;if(e.value)throw new Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){const e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){const e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;const t=this.definition.sortedColumn.measure;(function(e,t){try{if(!t.getMeasure(e.measure))return!1;const r=t.definition.columns;for(let n=0;n<e.domain.length;n++){if(r[n].nameWithGranularity!==e.domain[n].field)return!1;const o=t.getPossibleFieldValues(r[n]).map(e=>e.value);if(!(o.includes(e.domain[n].value)||null===e.domain[n].value&&o.includes("")))return!1}return!0}catch(e){return!1}})(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}}class OC{measures;columns;rows;sortedColumn;collapsedDomains;customFields;constructor(e,t){this.columns=e.columns.map(e=>this.createPivotDimension(t,e)),this.rows=e.rows.map(e=>this.createPivotDimension(t,e)),this.measures=e.measures.map(e=>this.createMeasure(t,e)),this.sortedColumn=e.sortedColumn,this.collapsedDomains=e.collapsedDomains,this.customFields=e.customFields}getDimension(e){const t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new S(v("Dimension %s does not exist",e));return t}getMeasure(e){const t=this.measures.find(t=>t.id===e);if(!t)throw new S(v("Field %s is not a measure",e));return t}get invalidAggregatorsForCustomField(){return[]}createMeasure(e,t){const r=t.fieldName,n="__count"===r?{name:"__count",string:v("Count"),type:"integer",aggregator:"sum"}:e[r],o=t.aggregator;let s=!(!n&&!t.computedBy);for(const t of[...this.rows,...this.columns]){const r=e[t.fieldName];if(r?.isCustomField&&this.invalidAggregatorsForCustomField.includes(o)){s=!1;break}}return{id:t.id,get displayName(){return t.userDefinedName??n?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:r,aggregator:o,type:"__count"===r?"integer":n?.type??"integer",isValid:s,isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}createPivotDimension(e,t){const r=e[t.fieldName],n=r?.type??"integer",o=r&&function(e){return Vd.includes(e.type)}(r)?t.granularity:void 0;return{displayName:r?.string??t.fieldName,nameWithGranularity:t.fieldName+(o?`:${o}`:""),fieldName:t.fieldName,granularity:o,type:r?.isCustomField?"custom":n,order:t.order,isValid:!!r,isCustomField:!!r?.isCustomField,customGroups:r?.customGroups,parentField:r?.parentField}}}class DC extends OC{range;constructor(e,t,r){if(super(e,t),e.dataSet){const{sheetId:t,zone:n}=e.dataSet;this.range=r.getRangeFromZone(t,n)}}}function FC(e,t,r){const n=t.measures.filter(e=>!e.isHidden).map(e=>e.id),o=MC(e,t.columns,0);VC(o,n.length);const s=function(e,t){const r=t.columns.map(e=>e.nameWithGranularity),n=r.length,o=t.measures.filter(e=>!e.isHidden),s=o.length,i=new Array(n).fill(0).map(()=>[]);function a(e,t,o){const s=i[t];for(const i of e){const e=o.concat([i.value]),l={fields:r.slice(0,t+1),values:e,width:i.width,offset:0};s.push(l),t<=n-1&&a(i.children,t+1,e)}}a(e,0,[]);const l=r.length>0,c=[];l&&i[i.length-1].forEach(e=>{o.forEach(t=>{const r={fields:[...e.fields,"measure"],values:[...e.values,t.id],width:1,offset:0};c.push(r)})});o.forEach(e=>{const t={fields:["measure"],values:[e.id],width:1,offset:0};c.push(t)}),i.push(c),1===i.length&&i.unshift([]);return i[i.length-2].push({fields:[],values:[],width:s,offset:0}),i}(o,t),i=NC(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 HE(s,i,n,a,l)}function NC(e,t,r,n,o){if(t>=r.length)return[];const s=r[t],i=s.nameWithGranularity,a=LC(e,s),l=PC(a,s),c=[],u=n.concat(i);for(const e of l){const n=o.concat(e);c.push({fields:u,values:n,indent:t+1});const s=a[e];s&&c.push(...NC(s,t+1,r,u,n))}return c}function MC(e,t,r){if(r>=t.length)return[];const n=t[r],o=t[r].nameWithGranularity,s=LC(e,n);return PC(s,t[r]).map(e=>({value:s[e]?.[0]?.[n.nameWithGranularity]?.value??null,field:o,children:MC(s[e]||[],t,r+1),type:n.type,width:0}))}function VC(e,t){for(const r in e){const n=e[r];0===n.children.length?n.width=t:(VC(n.children,t),n.width=n.children.reduce((e,t)=>e+t.width,0))}}function LC(e,t){return Object.groupBy(e,function(e){const t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}(t))}function PC(e,t){const r=t.order,n=t.customGroups?.find(e=>e.isOtherGroup);return r||n?Object.keys(e).sort((e,o)=>n&&e===n.name?1:n&&o===n.name?-1:r?function(e,t,r){if("null"===t)return"asc"===e.order?1:-1;if("null"===r)return"asc"===e.order?-1:1;if("integer"===e.type||"datetime"===e.type)return"asc"===e.order?kt(t,Dl)-kt(r,Dl):kt(r,Dl)-kt(t,Dl);return"asc"===e.order?t.localeCompare(r):r.localeCompare(t)}(t,e,o):0):Object.keys(e)}const kC=Symbol("NULL");function UC(e,t,r){const n=e.granularity||"month";if(!(n in HC))throw new Error(`Unknown date granularity: ${n}`);const o="number"==typeof t||"string"==typeof t?t:kC;if(!HC[n].set.has(t)){HC[n].set.add(t);let s=null;if("number"==typeof t||"string"==typeof t){const e=Zt(t,r);switch(n){case"year":s=e.getFullYear();break;case"quarter_number":s=Math.floor(e.getMonth()/3)+1;break;case"month_number":s=e.getMonth()+1;break;case"month":case"day":s=Math.floor(kt(t,r));break;case"iso_week_number":s=e.getIsoWeek();break;case"day_of_month":s=e.getDate();break;case"day_of_week":s=(e.getDay()+7-r.weekStart)%7+1;break;case"hour_number":s=e.getHours();break;case"minute_number":s=e.getMinutes();break;case"second_number":s=e.getSeconds()}}HC[n].values[o]=Ud(e,s)}return HC[n].values[o]}const HC={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 BC;!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"}(BC||(BC={}));const zC=new h,$C=["year","quarter_number","month_number","month","iso_week_number","day_of_month","day","day_of_week"];zC.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(BC.ALL),this.needsReevaluation=!1)}reload(e){e===BC.ALL&&(this.metaData=this.loadMetaData()),e>=BC.DEFINITION&&(this._definition=this.loadRuntimeDefinition()),e>=BC.DATA&&(this.dataEntries=this.loadData()),e>=BC.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),BC.NONE);this.reload(r)}}computeShouldReload(e,t){return Ae(e.dataSet,t.dataSet)?BC.DEFINITION:BC.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($t);return t.length&&"measure"===t.at(-1)&&(t=t.slice(0,-1)),function(e,t){let r=0,n=0;const o=t.columns.map(e=>e.nameWithGranularity),s=t.rows.map(e=>e.nameWithGranularity);for(;void 0!==e[r]&&e[r]===s[n];)r++,n++;for(n=0;void 0!==e[r]&&e[r]===o[n];)r++,n++;return e.length===r}(t,this.definition)}parseArgsToPivotDomain(e){const t=[];for(let r=0;r<e.length-1;r+=2){const n=$t(e[r]),o=this.getTypeOfDimension(n),s="measure"===n?$t(e[r+1]):Ud(this.getDimension(n),e[r+1]);t.push({field:n,value:s,type:o})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){const t=e.at(-1);if(!t)return{value:v("Total")};const r=this.getDimension(t.field),n=this.filterDataEntriesFromDomain(this.dataEntries,e),o=n[0]?.[r.nameWithGranularity];if("datetime"===r.type){return md(r.granularity||"month").toValueAndFormat(t.value,this.getters.getLocale())}return o?null===o.value?{value:v("(Undefined)")}:o:{value:""}}getPivotCellValueAndFormat(e,t){const r=this.filterDataEntriesFromDomain(this.dataEntries,t);if(0===r.length)return{value:""};const n=this.getMeasure(e),o=r.map(e=>e[n.fieldName]).filter(Se),s=o.filter(e=>e.type!==Eu.empty),i=n.aggregator,a=Nd[i];if(!a)throw new Error(`Aggregator ${i} does not exist`);try{const e=a([o],this.getters.getLocale());return 0===s.length?{...e,value:""}:e}catch(e){return Er(e,i.toUpperCase())}}getPossibleFieldValues(e){const t=[],r=LC(this.dataEntries,e),n=PC(r,e);for(const o of n)t.push({value:r[o]?.[0]?.[e.nameWithGranularity]?.value??"",label:r[o]?.[0]?.[e.nameWithGranularity]?.formattedValue||""});return t}getCollapsedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.collapsedTable||(this.collapsedTable=FC(this.dataEntries,this.definition,"collapsed")),this.collapsedTable}getExpandedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.expandedTable||(this.expandedTable=FC(this.dataEntries,this.definition,"expanded")),this.expandedTable}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,!this.coreDefinition.dataSet)return this.invalidRangeError=new S(v("The pivot cannot be created because the dataset is missing.")),{fields:{},fieldKeys:[]};{const{zone:e,sheetId:t}=this.coreDefinition.dataSet,r=this.getters.getRangeFromZone(t,e);try{const e=this.extractFieldsFromRange(r),t=function(e,t){const r={};for(const n of Object.values(e.customFields||{}))t[n.parentField]&&(r[n.name]={type:"custom",isCustomField:!0,name:n.name,string:n.name,customGroups:n.groups,parentField:n.parentField});return r}(this.coreDefinition,e.fields);return{...e,fields:{...e.fields,...t}}}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}}loadRuntimeDefinition(){return new DC(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}=Ld(e),r=this.fields[t]?.type;if(!r)throw new Error(`Field ${t} does not exist`);return r}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){const{field:r,value:n,type:o}=t,{nameWithGranularity:s}=this.getDimension(r);return e.filter(e=>{const t=e[s]?.value;return"char"===o?String(t)===String(n):t===n})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){const r=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===Eu.empty||""===e.value));return 0===r.length?"integer":r.every(e=>e.type===Eu.number&&e.format&&Hn(e.format))?"datetime":r.every(e=>e.type===Eu.boolean)?"boolean":r.some(e=>e.type===Eu.text)?"char":"integer"}assertCellIsValidField(e,t,r){if(r.type===Eu.error)throw new S(v("The pivot cannot be created because cell %s contains an error",Do(e,t)));if(r.type===Eu.empty||""===r.value)throw new S(v("The pivot cannot be created because cell %s is empty",Do(e,t)));if("__count"===r.value)throw new S(v("The pivot cannot be created because cell %s contains a reserved value",Do(e,t)))}extractFieldsFromRange(e){const t={},r=[],n=e.sheetId,o=e.zone.top;for(let s=e.zone.left;s<=e.zone.right;s++){const i=this.getters.getEvaluatedCell({sheetId:n,col:s,row:o});this.assertCellIsValidField(s,o,i);const a=i.value?.toString();if(a){const o=this.getTypeFromZone(n,{top:e.zone.top+1,left:s,bottom:e.zone.bottom,right:s}),i=qd(a,t);t[i]={name:i,type:o,string:i,aggregator:"integer"===o?"sum":"count"},r.push(i)}}return{fields:t,fieldKeys:r}}extractDataEntriesFromRange(e){const t=[];for(let r=e.zone.top+1;r<=e.zone.bottom;r++){const n={top:r,bottom:r,left:e.zone.left,right:e.zone.right},o=this.getters.getEvaluatedCellsInZone(e.sheetId,n),s={};for(const e in o){const t=o[e],r=this.fields[this.metaData.fieldKeys[e]];if(!r)throw new Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);""===t.value?s[r.name]={value:null,type:Eu.empty,formattedValue:""}:s[r.name]=t}for(const e in this.definition.customFields||{}){const t=this.definition.customFields?.[e];if(!t)continue;const r=s[t.parentField],n=this.fields[t.parentField];if(!r||!n){s[e]={value:null,type:Eu.empty,formattedValue:""};continue}const o=t.groups.find(e=>e.values.some(e=>e===r?.value))||t.groups.find(e=>e.isOtherGroup);s[e]={...r,value:o?o.name:r.value}}s.__count={value:1,type:Eu.number,formattedValue:"1"},t.push(s)}const r=this.definition.columns.concat(this.definition.rows).filter(e=>"datetime"===e.type);if(r.length){const e=this.getters.getLocale();for(const n of t)for(const t of r){const r=UC(t,n[t.fieldName]?.value||null,this.getters.getLocale()),o=md(t.granularity||"month"),{format:s,value:i}=o.toValueAndFormat(r,e);n[t.nameWithGranularity]={value:r,type:n[t.fieldName]?.type||Eu.empty,format:n[t.fieldName]?.format,formattedValue:Fn(i,{locale:e,format:s})}}}return t}},definition:DC,externalData:!1,dateGranularities:[...$C],datetimeGranularities:[...$C,"hour_number","minute_number","second_number"],isMeasureCandidate:e=>"boolean"!==e.type,isGroupable:()=>!0,canHaveCustomGroup:e=>"char"===e.type&&!e.isCustomField});const GC=["ADD_PIVOT","UPDATE_PIVOT","REMOVE_PIVOT"];function WC(e){return GC.includes(e.type)}const qC=new fd;qC.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;let r=Math.abs(e.current).toString();r="0".repeat(Math.max(e.numberPostfixLength-r.length,0))+r;const n=`${e.prefix}${r}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:{props:{content:n}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t,r)=>{e.current+=e.increment;const n=e.current.toString(),o=r.getLocale(),s=Fn(e.current,{format:t.cell?.format,locale:o});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:n?{props:{content:s}}:void 0}}}).add("DATE_INCREMENT_MODIFIER",{apply:(e,t,r)=>{const n=Zt(e.current,r.getLocale());n.setFullYear(n.getFullYear()+e.increment.years||0),n.setMonth(n.getMonth()+e.increment.months||0),n.setDate(n.getDate()+e.increment.days||0);const o=bt(n);e.current=o;const s=r.getLocale(),i=Fn(o,{format:t.cell?.format,locale:s});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o.toString()},tooltip:o?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,r)=>{const n=t.cell?.content||"",o={locale:r.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:n?{props:{content:t.cell?Gy(t.cell,o).formattedValue:""}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,r,n)=>{e.current+=e.increment;let o=0,s=0;switch(n){case"up":o=0,s=-e.current;break;case"down":o=0,s=e.current;break;case"left":o=-e.current,s=0;break;case"right":o=e.current,s=0}const i=t.cell;if(!i||!i.isFormula)return{cellData:{}};const a=t.sheetId,l=r.getTranslatedCellFormula(a,o,s,i.compiledFormula.tokens);return{cellData:{border:t.border,style:i.style,format:i.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const ZC=new fd,YC=/(\d+)$/,jC=/^(.*\D+)/,XC=/^(.*\D+)(\d+)$/,KC=/^0*/;function QC(e,t,r){let n=[],o=!1;for(const s of t){s===e&&(o=!0);const t=void 0===s||s.isFormula?void 0:Gy(s,{locale:Dl,format:s.format});if(t&&r(t))n.push(t);else{if(o)return n;n=[]}}return n}function JC(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let r=e[0];for(let n=1;n<e.length;n++){const o=e[n];t.push(o-r),r=o}return t.reduce((e,t)=>e+t,0)/t.length}(e)*e.length),t}function eT(e){if(e.length<2)return 1;const t=e.map(e=>Zt(e,Dl)),r=function(e){if(e.length<2)return[{years:0,months:0,days:0}];const t=e.map((t,r)=>{if(0===r)return{years:0,months:0,days:0};const n=Qe.fromTimestamp(e[r-1].getTime()),o=It(n,t),s=Ct(n,t)%12;n.setFullYear(n.getFullYear()+o),n.setMonth(n.getMonth()+s);return{years:o,months:s,days:Tt(n,t)}});return t.slice(1)}(t),n=(o=r).length<2?o[0]||{years:0,months:0,days:0}:o.every(e=>e.years===o[0].years&&e.months===o[0].months&&e.days===o[0].days)?o[0]:void 0;var o;if(void 0===n)return;const s=1===Object.values(n).filter(e=>0!==e).length,i=Object.values(n).every(e=>0===e);if(!s||i){const r=t.map((e,r)=>{if(0===r)return 0;const n=t[r-1];return Math.floor(e.getTime())-Math.floor(n.getTime())}).slice(1);if(r.every(e=>e===r[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}ZC.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&Hn(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Gy(e,{locale:Dl}).type===Eu.text&&XC.test(e.content),generateRule:(e,t,r)=>{const n=parseInt(e.content.match(YC)[0]),o=e.content.match(jC)[0],s=QC(e,t,e=>e.type===Eu.text&&XC.test(e.value)).filter(e=>o===(e.value??"").toString().match(jC)[0]).map(e=>(e.value??"").toString().match(YC)[0]),i=s.reduce((e,t)=>{const r=t.match(KC)[0].length;return r>e[1]?[t,r]:e},[s[0],0]),a=i[1]?i[0].length:0;let l=JC(s.map(e=>parseInt(e)));return["up","left"].includes(r)&&1===s.length&&(l=-l),{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:o,current:n,increment:l,numberPostfixLength:a}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Gy(e,{locale:Dl}).type===Eu.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&&Gy(e,{locale:Dl}).type===Eu.number&&!!e.format&&Hn(e.format),generateRule:(e,t)=>{const r=eT(QC(e,t,e=>e.type===Eu.number&&!!e.format&&Hn(e.format)).map(e=>Number(e.value)));if(void 0===r)return{type:"COPY_MODIFIER"};const n=Gy(e,{locale:Dl});return"object"==typeof r?{type:"DATE_INCREMENT_MODIFIER",increment:r,current:n.type===Eu.number?n.value:0}:{type:"INCREMENT_MODIFIER",increment:r,current:n.type===Eu.number?n.value:0}},sequence:25}).add("increment_number",{condition:e=>!e.isFormula&&Gy(e,{locale:Dl}).type===Eu.number,generateRule:(e,t,r)=>{const n=QC(e,t,e=>e.type===Eu.number&&!Hn(e.format||"")).map(e=>Number(e.value));let o=JC(n);["up","left"].includes(r)&&1===n.length&&(o=-o);const s=Gy(e,{locale:Dl});return{type:"INCREMENT_MODIFIER",increment:o,current:s.type===Eu.number?s.value:0}},sequence:40});class tT{cells;getters;index=0;direction;constructor(e,t,r){this.cells=e,this.getters=t,this.direction=r}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:r,tooltip:n}=qC.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:r,tooltip:n,origin:{col:e.data.col,row:e.data.row}}}}const rT=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 nT(e){return rT.has(e.type)}const oT=new fd,sT=new fd;function iT(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return ws(e.rootCommand)?function(e,t){if(!t)return;if(!oT.contains(t.type))return;return oT.get(t.type)(e,t)}(t,e.rootCommand):function(e,t,r){if(!sT.contains(t.type))return;return sT.get(t.type)(e,t,r)}(t,e.rootCommand,e.commands)}class aT{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,$t(e.value)])}isValuePresent(e,t){const r=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(r)}isHeaderPresent(e){const t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){const r=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(r)}trackHeader(e){const t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}}const lT={type:"bar",title:{},stacked:!1,dataSetsHaveTitle:!1,dataSets:[],legendPosition:"top",humanize:!0};function cT(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 uT(e){let t="";for(const r in e)e[r]&&(t+=`${r}:${e[r]}; `);return t}var hT;function dT(e,t){const r=new Set(t.map(e=>e.left)),n=new Set(t.map(e=>e.right)),o=new Set(t.map(e=>e.top)),s=new Set(t.map(e=>e.bottom)),i=1===o.size&&1===s.size||1===r.size&&1===n.size?function(e){return e.reduce((e,t)=>{const r=e.length;for(let n=0;n<r;n++)if(Ko(e[n],t))return e[n]=Zo(e[n],t),e;return e[r]=t,e},[])}(t):[t[t.length-1]],a=i.map(e=>rs(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"}(hT||(hT={}));const fT={figureHandlers:new fd,cellHandlers:new fd},gT=5242880;const mT={filterType:"criterion",type:"none",values:[]};function pT(e){return 20+120*Math.exp(-.035*(e-1))}class bT{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,r,n,o,s){if(this.getters=e,this.sheetId=t,this.boundaries=r,n.width<0||n.height<0)throw new Error("Viewport size cannot be negative");this.viewportWidth=n.height&&n.width,this.viewportHeight=n.width&&n.height,this.top=r.top,this.bottom=r.bottom,this.left=r.left,this.right=r.right,this.offsetX=s.x,this.offsetY=s.y,this.canScrollVertically=o.canScrollVertically,this.canScrollHorizontally=o.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:r}=this.getters.getColDimensions(this.sheetId,e),{end:n}=this.getters.getRowDimensions(this.sheetId,t);let o=r-this.offsetCorrectionX;this.canScrollHorizontally&&(o=Math.max(o,this.viewportWidth));let s=n-this.offsetCorrectionY;return this.canScrollVertically&&(s=Math.max(s,this.viewportHeight),n+46>s&&!this.getters.isReadonly()&&(s+=46)),{width:o,height:s}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX+this.snapCorrection.x,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY+this.snapCorrection.y,this.top)}adjustPosition(e){const t=this.sheetId,r=this.getters.getMainCellPosition({sheetId:t,...e}),{col:n,row:o}=this.getters.getNextVisibleCellPosition(r);Qo(n,this.boundaries.top,this.boundaries)&&this.adjustPositionX(n),Qo(this.boundaries.left,o,this.boundaries)&&this.adjustPositionY(o)}adjustPositionX(e){const t=this.sheetId,{start:r,end:n}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<n?this.offsetX=n-this.viewportWidth:this.offsetX+this.offsetCorrectionX>r&&(this.offsetX=r-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){const t=this.sheetId,{start:r,end:n}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<n?this.offsetY=n-this.viewportHeight:this.offsetY+this.offsetCorrectionY>r&&(this.offsetY=r-this.offsetCorrectionY),this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetX!==e||this.canScrollVertically&&this.offsetY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){const t=Yo(e,this),r=this.snapCorrection.x,n=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,t.left)+this.offsetCorrectionX-(this.left!==t.left?r:0),y:this.getters.getColRowOffset("ROW",this.top,t.top)+this.offsetCorrectionY-(this.top!==t.top?n:0),width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1)-(this.left===t.left?r:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1)-(this.top===t.top?n:0),this.viewportHeight)}}}getFullRect(e){const t=Yo(e,this.boundaries),r=this.snapCorrection.x,n=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,e.left)+this.offsetCorrectionX-r,y:this.getters.getColRowOffset("ROW",this.top,e.top)+this.offsetCorrectionY-n,width:this.getters.getColRowOffset("COL",e.left,e.right+1),height:this.getters.getColRowOffset("ROW",e.top,e.bottom+1)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,r=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;const n=this.sheetId,o=this.getters.getNumberHeaders(n,e);let s=r,i=o;for(;s<=i&&s!==o&&-1!==i;){const o=Math.floor((s+i)/2),a=this.getters.getColRowOffset(e,r,o),l=this.getters.getHeaderSize(n,e,o);if(t>=a&&t<a+l)return o;t>=a+l?s=o+1:i=o-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetY>e&&(this.offsetY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){this.left=this.searchHeaderIndex("COL",this.offsetX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",Math.max(this.viewportWidth+this.snapCorrection.x-.1),this.left)),this.viewportWidth&&(-1===this.left&&(this.left=this.boundaries.left),-1===this.right&&(this.right=this.boundaries.right))}adjustViewportZoneY(){this.top=this.searchHeaderIndex("ROW",this.offsetY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",Math.max(this.viewportHeight+this.snapCorrection.y-.1,0),this.top)),this.viewportHeight&&(-1===this.top&&(this.top=this.boundaries.top),-1===this.bottom&&(this.bottom=this.boundaries.bottom))}get snapCorrection(){return{x:Math.abs(this.offsetX-this.getters.getColRowOffset("COL",this.boundaries.left,Math.max(0,this.left))),y:Math.abs(this.offsetY-this.getters.getColRowOffset("ROW",this.boundaries.top,Math.max(0,this.top)))}}}const vT=(new h).add("settings",class extends gE{static getters=["getLocale"];locale=Dl;allowDispatch(e){return"UPDATE_LOCALE"===e.type?Xl(e.locale)?"Success":"InvalidLocale":"Success"}handle(e){if("UPDATE_LOCALE"===e.type){const t=this.locale,r=e.locale;this.history.update("locale",r),this.changeCellsDateFormatWithLocale(t,r)}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(const r of this.getters.getSheetIds())for(const[n,o]of Object.entries(this.getters.getCells(r))){let r;if(o.format===e.dateFormat&&(r=t.dateFormat),o.format===e.timeFormat&&(r=t.timeFormat),o.format===tc(e)&&(r=tc(t)),r){const{col:e,row:t,sheetId:o}=this.getters.getCellPosition(n);this.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:o,format:r})}}}import(e){this.locale=e.settings?.locale??Dl}export(e){e.settings={locale:this.locale}}}).add("sheet",class extends gE{static getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","doesHeaderExist","doesHeadersExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","getSheetSize","getSheetZone","getPaneDivisions","checkZonesExistInSheet","getCommandZones","getUnboundedZone","checkElementsIncludeAllNonFrozenHeaders","getDuplicateSheetName"];sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if("Success"!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?"NotEnoughSheets":"Success";case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"DUPLICATE_SHEET":return this.sheets[e.sheetIdTo]?"DuplicatedSheetId":this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?"DuplicatedSheetName":"Success";case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),"Success"}catch(e){return"WrongSheetMove"}case"RENAME_SHEET":return this.isRenameAllowed(e);case"COLOR_SHEET":return!e.color||Jm(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"}}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",t.name,t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.newName);break;case"COLOR_SHEET":this.history.update("sheets",e.sheetId,"color",e.color);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"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[t.name]=t.id;for(const t of e.sheets){const e=t.name||"Sheet"+(Object.keys(this.sheets).length+1),{colNumber:r,rowNumber:n}=this.getImportedSheetSize(t),o={id:t.id,name:e,numberOfCols:r,rows:wm(n),areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(o.id),this.sheets[o.id]=o}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(Se).map(e=>{const t=this.sheets[e],r={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(r.panes=t.panes),r})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){const t=ne(e);for(const e in this.sheetIdsMapName)if(Im(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,r){return"COL"===t?r>=0&&r<this.getNumberCols(e):r>=0&&r<this.getNumberRows(e)}doesHeadersExist(e,t,r){return r.every(r=>this.doesHeaderExist(e,t,r))}getCell({sheetId:e,col:t,row:r}){const n=this.tryGetSheet(e),o=n?.rows[r]?.cells[t];if(void 0!==o)return this.getters.getCellById(o)}getColsZone(e,t,r){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:r}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(Se)}getRowsZone(e,t,r){return{top:t,bottom:r,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){return Cm(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(void 0===t.bottom||void 0===t.right)return t;const r=0===t.left&&t.right===this.getNumberCols(e)-1,n=0===t.top&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:n?void 0:t.bottom,right:r&&!n?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,r){const n={...this.getPaneDivisions(e)};"COL"===r?n.xSplit=t:"ROW"===r&&(n.ySplit=t),this.history.update("sheets",e,"panes",n)}checkElementsIncludeAllNonFrozenHeaders(e,t,r){const n=this.getters.getPaneDivisions(e),o="ROW"===t?n.ySplit:n.xSplit,s=this.getters.getNumberHeaders(e,t);if(!o)return!1;return De(r,le(o,s))}getCommandZones(e){const t=[];return"zone"in e&&t.push(e.zone),"target"in e&&t.push(...e.target),"ranges"in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),"col"in e&&void 0!==e.col&&"row"in e&&void 0!==e.row&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(zo))return"InvalidRange";if(t.length){const r=this.getSheetZone(e);return t.every(e=>Jo(e,r))?"Success":"TargetOutOfSheet"}return"Success"}updateCellPosition(e){const{sheetId:t,cellId:r,col:n,row:o}=e;r?this.setNewPosition(r,t,n,o):this.clearPosition(t,n,o)}setNewPosition(e,t,r,n){const o=this.cellPosition[e];o&&this.clearPosition(t,o.col,o.row),this.history.update("cellPosition",e,{row:n,col:r,sheetId:t}),this.history.update("sheets",t,"rows",n,"cells",r,e)}clearPosition(e,t,r){const n=this.sheets[e]?.rows[r].cells[t];n&&(this.history.update("cellPosition",n,void 0),this.history.update("sheets",e,"rows",r,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}createSheet(e,t,r,n,o){const s={id:e,name:t,numberOfCols:r,rows:wm(n),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},i=this.orderedSheetIds.slice();i.splice(o,0,s.id);const a=this.sheets;return this.history.update("orderedSheetIds",i),this.history.update("sheets",Object.assign({},a,{[s.id]:s})),s}moveSheet(e,t){const r=this.orderedSheetIds.slice(),n=r.findIndex(t=>t===e),o=r.splice(n,1),s=this.findIndexOfTargetSheet(n,t);r.splice(s,0,o[0]),this.history.update("orderedSheetIds",r)}findIndexOfTargetSheet(e,t){for(;0!==t&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(0===t)return e;throw new Error("There is not enough visible sheets")}checkSheetName(e){const t=this.getters.tryGetSheetName(e.sheetId),r="RENAME_SHEET"===e.type?e.newName:e.name;if(void 0!==t&&r===t)return"UnchangedSheetName";const{orderedSheetIds:n,sheets:o}=this,s=r&&r.trim().toLowerCase();return n.find(t=>Im(o[t]?.name,s)&&t!==e.sheetId)?"DuplicatedSheetName":X.test(s)?"ForbiddenCharactersInSheetName":"Success"}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?"WrongSheetPosition":"Success"}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?"Success":"InvalidFreezeQuantity"}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?"Success":"InvalidFreezeQuantity"}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const r of t)if(r.top<e.quantity&&e.quantity<=r.bottom)return"MergeOverlap";return"Success"}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const r of t)if(r.left<e.quantity&&e.quantity<=r.right)return"MergeOverlap";return"Success"}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):"MissingSheetName"}renameSheet(e,t){const r=e.name;this.history.update("sheets",e.id,"name",t.trim());const n=Object.assign({},this.sheetIdsMapName);delete n[r],n[t]=e.id,this.history.update("sheetIdsMapName",n)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t,r){const n=re(this.getSheet(e));n.id=t,n.name=r;for(let e=0;e<=n.numberOfCols;e++)for(let t=0;t<=n.rows.length;t++)n.rows[t]&&(n.rows[t].cells[e]=void 0);const o=this.orderedSheetIds.slice(),s=o.indexOf(e);o.splice(s+1,0,n.id),this.history.update("orderedSheetIds",o),this.history.update("sheets",Object.assign({},this.sheets,{[n.id]:n}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:r}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:n.id,col:e,row:r,content:t.content,format:t.format,style:t.style})}const i=Object.assign({},this.sheetIdsMapName);i[n.name]=n.id,this.history.update("sheetIdsMapName",i)}getDuplicateSheetName(e){return Tm(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){const t=e.name,r=Object.assign({},this.sheets);delete r[e.id],this.history.update("sheets",r);const n=this.orderedSheetIds.slice(),o=n.indexOf(e.id);n.splice(o,1),this.history.update("orderedSheetIds",n);const s=Object.assign({},this.sheetIdsMapName);delete s[t],this.history.update("sheetIdsMapName",s)}removeColumns(e,t){t.sort((e,t)=>t-e);for(const r of t)this.moveCellOnColumnsDeletion(e,r);const r=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",r-t.length);const n=t.filter(t=>t<e.panes.xSplit).length;n&&this.setPaneDivisions(e.id,e.panes.xSplit-n,"COL")}removeRows(e,t){t.sort((e,t)=>t-e);for(const r of ce(t)){const t=r[r.length-1],n=r[0];this.moveCellOnRowsDeletion(e,t,n),this.updateRowsStructureOnDeletion(e,t,n)}const r=t.filter(t=>t<e.panes.ySplit).length;r&&this.setPaneDivisions(e.id,e.panes.ySplit-r,"ROW")}addColumns(e,t,r,n){const o="before"===r?t:t+1;this.moveCellsOnAddition(e,o,n,"columns");const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s+n),o<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+n,"COL")}addRows(e,t,r,n){const o="before"===r?t:t+1;this.addEmptyRows(e,n),this.moveCellsOnAddition(e,o,n,"rows"),o<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+n,"ROW")}moveCellOnColumnsDeletion(e,t){this.dispatch("CLEAR_CELLS",{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let r=0;r<e.rows.length;r++){const n=e.rows[r];for(const o in n.cells){const s=Number(o),i=n.cells[o];i&&s>t&&this.setNewPosition(i,e.id,s-1,r)}}}moveCellsOnAddition(e,t,r,n){const o=[];for(let s=0;s<e.rows.length;s++){const i=e.rows[s];if("rows"!==n||s>=t)for(const a in i.cells){const l=Number(a),c=i.cells[a];c&&("rows"===n||l>=t)&&o.push({sheetId:e.id,cellId:c,col:l+("columns"===n?r:0),row:s+("rows"===n?r:0),type:"UPDATE_CELL_POSITION"})}}for(const e of o.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,r){this.dispatch("CLEAR_CELLS",{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:r}]});const n=r-t+1;for(let t=0;t<e.rows.length;t++){const o=e.rows[t];if(t>r)for(const r in o.cells){const s=Number(r),i=o.cells[r];i&&this.setNewPosition(i,e.id,s,t-n)}}}updateRowsStructureOnDeletion(e,t,r){const n=[],o=e.rows.map(e=>e.cells).reverse();for(const s in e.rows){const e=Number(s);e>=t&&e<=r||n.push({cells:o.pop()})}this.history.update("sheets",e.id,"rows",n)}addEmptyRows(e,t){const r=e.rows.slice();for(let e=0;e<t;e++)r.push({cells:{}});this.history.update("sheets",e.id,"rows",r)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(Oo);let r=e.rowNumber,n=e.colNumber;for(const{col:e,row:o}of t)r=Math.max(r,o+1),n=Math.max(n,e+1);return{rowNumber:r,colNumber:n}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?"InvalidSheetId":"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?"DuplicatedSheetId":"Success"}checkZonesAreInSheet(e){return"sheetId"in e?"ranges"in e&&e.ranges.some(e=>""!==e._sheetId&&!this.getters.tryGetSheet(e._sheetId))?"InvalidSheetId":this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):"Success"}}).add("header grouping",class extends gE{static getters=["getHeaderGroups","getGroupsLayers","getVisibleGroupLayers","getHeaderGroup","getHeaderGroupsInZone","isGroupFolded","isRowFolded","isColFolded"];groups={};allowDispatch(e){switch(e.type){case"GROUP_HEADERS":{const{start:t,end:r,sheetId:n}=e;if(!this.getters.tryGetSheet(n))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,r]))return"InvalidHeaderGroupStartEnd";if(t>r)return"InvalidHeaderGroupStartEnd";if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,r))return"HeaderGroupAlreadyExists";break}case"UNGROUP_HEADERS":{const{start:t,end:r,sheetId:n}=e;if(!this.getters.tryGetSheet(n))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,r]))return"InvalidHeaderGroupStartEnd";if(t>r)return"InvalidHeaderGroupStartEnd";break}case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUP":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return"UnknownHeaderGroup";if(le(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(r=>r>=t.start&&r<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,r)))return"NotEnoughElements"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("groups",e.sheetId,{ROW:[],COL:[]});break;case"GROUP_HEADERS":this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case"UNGROUP_HEADERS":this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case"DUPLICATE_SHEET":{const t=re(this.groups[e.sheetId]);this.history.update("groups",e.sheetIdTo,t);break}case"DELETE_SHEET":{const t={...this.groups};delete t[e.sheetId],this.history.update("groups",t);break}case"ADD_COLUMNS_ROWS":const t=Re(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case"REMOVE_COLUMNS_ROWS":this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case"UNFOLD_HEADER_GROUP":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case"FOLD_HEADER_GROUP":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case"UNFOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const r of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,r);break}case"FOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const r of t)this.foldHeaderGroup(e.sheetId,e.dimension,r);break}case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":{const t="UNFOLD_HEADER_GROUPS_IN_ZONE"===e.type?"unfold":"fold",r=this.getGroupsLayers(e.sheetId,e.dimension);"fold"===t&&r.reverse();const n=r.flat(),o="ROW"===e.dimension?e.zone.top:e.zone.left,s="ROW"===e.dimension?e.zone.bottom:e.zone.right,i=new Set;for(let e=o;e<=s;e++){const r=n.filter(t=>t.start-1<=e&&e<=t.end);for(const e of r)if(!("fold"===t&&e.isFolded||"unfold"===t&&!e.isFolded)){i.add(e);break}}for(const r of i)"unfold"===t?this.unfoldHeaderGroup(e.sheetId,e.dimension,r):this.foldHeaderGroup(e.sheetId,e.dimension,r);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,r,n){return this.getHeaderGroups(e,t).find(e=>e.start===r&&e.end===n)}getHeaderGroupsInZone(e,t,r){return this.getHeaderGroups(e,t).filter(e=>{const n="ROW"===t?r.top:r.left,o="ROW"===t?r.bottom:r.right;return this.doGroupOverlap(e,n,o)})}getGroupsLayers(e,t){const r=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(r,0,0)}getVisibleGroupLayers(e,t){const r=this.getGroupsLayers(e,t);for(const n of r)for(let r=n.length-1;r>=0;r--){const o=n[r];if(0===o.start)continue;le(o.start-1,o.end+1).every(r=>this.getters.isHeaderHiddenByUser(e,t,r))&&n.splice(r,1)}return r.filter(e=>e.length>0)}isGroupFolded(e,t,r,n){return this.getHeaderGroup(e,t,r,n)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,"ROW").some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,"COL").some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,r,n=0){const o={};for(const t of e)o[this.getGroupId(t)]=t.isFolded;const s={};for(const t of e)for(let e=t.start;e<=t.end;e++)s[e]=s[e]?s[e]+1:1;for(let e=t;e<=r;e++)s[e]=s[e]?s[e]+n:n;const i=Math.max(...Object.values(s),0),a=Array.from({length:i},()=>[]),l=Math.max(r,...e.map(e=>e.end));for(let r=Math.min(t,...e.map(e=>e.start));r<=l;r++){const e=s[r]||0;for(let t=0;t<e;t++){const e=a[t].at(-1);if(e&&ke([e.end,r]))e.end++;else{const e={start:r,end:r};a[t].push(e)}}}for(const e of a)for(const t of e)t.isFolded=o[this.getGroupId(t)];return a}groupHeaders(e,t,r,n){const o=this.getHeaderGroups(e,t),s=this.bricksFallingAlgorithm(o,r,n,1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(s))}unGroupHeaders(e,t,r,n){const o=this.getHeaderGroups(e,t),s=this.bricksFallingAlgorithm(o,r,n,-1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(s))}moveGroupsOnHeaderInsertion(e,t,r,n){const o=this.groups[e][t];for(let s=0;s<o.length;s++){const i=o[s],[a,l]=Em(r,n,[i.start,i.end]);a===i.start&&l===i.end||this.history.update("groups",e,t,s,{...i,start:a,end:l})}}moveGroupsOnHeaderDeletion(e,t,r){const n=this.getHeaderGroups(e,t),o=[];for(const e of n){const t=Sm(r,le(e.start,e.end+1));0!==t.length&&o.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update("groups",e,t,this.bricksFallingAlgorithm(o,0,0).flat())}doGroupOverlap(e,t,r){return e.start<=r&&e.end>=t}removeDuplicateGroups(e){const t={};for(const r of e)t[this.getGroupId(r)]=r;return Object.values(t)}findGroupWithStartEnd(e,t,r,n){return this.getHeaderGroups(e,t).find(e=>e.start===r&&e.end===n)}foldHeaderGroup(e,t,r){const n=this.getGroupIndex(e,t,r.start,r.end);if(void 0===n)return;this.history.update("groups",e,t,n,"isFolded",!0);const o=this.getters.getHeaderGroups(e,t);for(let n=0;n<o.length;n++){const s=o[n];s.start===r.start&&s.end<=r.end&&this.history.update("groups",e,t,n,"isFolded",!0)}}unfoldHeaderGroup(e,t,r){const n=this.getGroupIndex(e,t,r.start,r.end);if(void 0===n)return;this.history.update("groups",e,t,n,"isFolded",!1);const o=this.getters.getHeaderGroups(e,t);for(let n=0;n<o.length;n++){const s=o[n];s.start===r.start&&s.end>=r.end&&this.history.update("groups",e,t,n,"isFolded",!1)}}getGroupIndex(e,t,r,n){const o=this.groups[e][t].findIndex(e=>e.start===r&&e.end===n);return-1===o?void 0:o}import(e){for(const t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(const e of["ROW","COL"])for(const r of t.headerGroups[e]||[])this.groups[t.id][e].push({...r})}export(e){for(const t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(const t of e.sheets)for(const e of["ROW","COL"]){const r=this.getGroupsLayers(t.id,e);for(let n=0;n<r.length;n++){const o=r[n];for(const r of o){for(let o=r.start;o<=r.end;o++){const s=vv(t,e,o);s.outlineLevel=n+1,r.isFolded&&(s.isHidden=!0)}if(r.isFolded){vv(t,e,r.end+1).collapsed=!0}}}}}}).add("header visibility",class extends gE{static getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isHeaderHiddenByUser","isRowHiddenByUser","isColHiddenByUser"];hiddenHeaders={};allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),r="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=r?"TooManyHiddenElements":qe(e.elements)<0||We(e.elements)>r?"InvalidHeaderIndex":"Success"}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?"NotEnoughElements":"Success":"InvalidSheetId"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":const t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update("hiddenHeaders",e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("hiddenHeaders",e.sheetIdTo,re(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(const r of[...e.elements].sort((e,t)=>t-e))t.splice(r,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=Re(e.position,e.base),r=Be([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update("hiddenHeaders",e.sheetId,e.dimension,r);break}case"HIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}checkElementsIncludeAllVisibleHeaders(e,t,r){return De(r,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,r){return"COL"===t?this.isColHiddenByUser(e,r):this.isRowHiddenByUser(e,r)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){const t=[[]],r=this.hiddenHeaders[e].COL;for(let e=0;e<r.length;e++){r[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],r=this.hiddenHeaders[e].ROW;for(let e=0;e<r.length;e++){r[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){const r=le(0,this.getters.getNumberHeaders(e,t)),n=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&n.push(...le(e.start,e.end+1))}),r.filter(r=>!this.hiddenHeaders[e][t][r]&&!n.includes(r))}import(e){for(const t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=Boolean(t.rows[e]?.isHidden);for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=Boolean(t.cols[e]?.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const r of e.sheets){void 0===r.rows&&(r.rows={});for(let e=0;e<this.getters.getNumberRows(r.id);e++)(t||this.hiddenHeaders[r.id].ROW[e])&&(void 0===r.rows[e]&&(r.rows[e]={}),r.rows[e].isHidden||=this.hiddenHeaders[r.id].ROW[e]);void 0===r.cols&&(r.cols={});for(let e=0;e<this.getters.getNumberCols(r.id);e++)(t||this.hiddenHeaders[r.id].COL[e])&&(void 0===r.cols[e]&&(r.cols[e]={}),r.cols[e].isHidden||=this.hiddenHeaders[r.id].COL[e])}}}).add("tables",class extends gE{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 us(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(Ko(r,t))return"MergeInTable"}}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":{const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break}case"DUPLICATE_SHEET":{const t={};for(const r of this.getCoreTables(e.sheetId))t[r.id]="dynamic"===r.type?this.copyDynamicTableForSheet(e.sheetIdTo,r):this.copyStaticTableForSheet(e.sheetIdTo,r);this.history.update("tables",e.sheetIdTo,t);break}case"CREATE_TABLE":{const t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),r=this.getters.getRangesUnion(t),n=this.getters.getMergesInZone(e.sheetId,r.zone);n.length&&this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:n});const o=this.consumeNextId(),s=e.config||Tp,i="dynamic"===e.tableType?this.createDynamicTable(o,r,s):this.createStaticTable(o,e.tableType,r,s);this.history.update("tables",e.sheetId,i.id,i);break}case"REMOVE_TABLE":{const t={};for(const r of this.getCoreTables(e.sheetId))e.target.every(e=>!Yo(r.range.zone,e))&&(t[r.id]=r);this.history.update("tables",e.sheetId,t);break}case"UPDATE_TABLE":this.updateTable(e);break;case"UPDATE_CELL":{const t=e.sheetId;for(const r of this.getCoreTables(t)){if("dynamic"===r.type)continue;const n=this.canUpdateCellCmdExtendTable(e,r);"down"===n?this.extendTableDown(t,r):"right"===n&&this.extendTableRight(t,r)}break}case"DELETE_CONTENT":{const t={...this.tables[e.sheetId]};for(const r in t){const n=t[r];n&&e.target.some(e=>Jo(n.range.zone,e))&&this.dispatch("REMOVE_TABLE",{sheetId:e.sheetId,target:[n.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(Se):[]}getCoreTable({sheetId:e,col:t,row:r}){return this.getCoreTables(e).find(e=>Qo(t,r,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Ko(e.range.zone,t)))}extendTableDown(e,t){const r=this.getters.extendRange(t.range,"ROW",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,r))}extendTableRight(e,t){const r=this.getters.extendRange(t.range,"COL",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,r))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:r,row:n},o){if(!e)return"none";const s=o.range.zone;let i="none";if(s.bottom+1===n&&r>=s.left&&r<=s.right?i="down":s.right+1===r&&n>=s.top&&n<=s.bottom&&(i="right"),"none"===i)return"none";const a="down"===i?{...s,bottom:s.bottom+1,top:s.bottom+1}:{...s,right:s.right+1,left:s.right+1};for(let e=a.top;e<=a.bottom;e++)for(let r=a.left;r<=a.right;r++){const n={sheetId:t,col:r,row:e},o=this.getters.getCell(n)?.content;if(o||this.getters.isInMerge(n)||this.getTablesOverlappingZones(t,[ss(n)]).length)return"none"}return i}getCoreTableMatchingTopLeft(e,t){for(const r of this.getCoreTables(e)){const e=r.range.zone;if(e.left===t.left&&e.top===t.top)return r}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return"Success";const t=this.getters.getRangeFromRangeData(e.newTableRange).zone,r=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if("Success"!==r)return r;const n=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!n)return"TableNotFound";return this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==n.id).length?"TableOverlap":"Success"}checkTableConfigUpdateIsValid(e){return e&&(void 0!==e.numberOfHeaders&&e.numberOfHeaders<0||e.hasFilters&&0===e.numberOfHeaders)?"InvalidTableConfig":"Success"}createStaticTable(e,t,r,n,o){const s=r.zone;if(!o){o=[];for(const e of le(s.left,s.right+1)){const t={...s,left:e,right:e},i=this.consumeNextId();o.push(this.createFilterFromZone(i,r.sheetId,t,n))}}return{id:e,range:r,filters:o,config:n,type:t}}createDynamicTable(e,t,r){const n=is(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,n),config:r,type:"dynamic"}}updateTable(e){const t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;const r=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(r){const t=this.getters.getMergesInZone(e.sheetId,r.zone);this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:t})}const n=r||t.range,o=this.updateTableConfig(e.config,t.config),s=e.tableType??t.type;if("dynamic"===s&&"dynamic"!==t.type||"dynamic"!==s&&"dynamic"===t.type){const r="dynamic"===s?this.createDynamicTable(t.id,n,o):this.createStaticTable(t.id,s,n,o);this.history.update("tables",e.sheetId,t.id,r)}else{const r="dynamic"===t.type?this.updateDynamicTable(t,n,o):this.updateStaticTable(t,n,o,s);this.history.update("tables",e.sheetId,t.id,r)}}updateStaticTable(e,t,r,n=e.type){if("dynamic"===n)throw new Error("Cannot use updateStaticTable to update a dynamic table");const o=t||e.range,s=o.zone,i=this.updateTableConfig(r,e.config),a=i||e.config,l=[];if(t||i&&"numberOfHeaders"in i)for(const t of le(s.left,s.right+1)){const r=s.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,n={...s,left:t,right:t},i=r?.id||this.consumeNextId();l.push(this.createFilterFromZone(i,o.sheetId,n,a))}return{...e,range:o,config:a,filters:l.length?l:e.filters,type:n}}updateDynamicTable(e,t,r){const n=t?this.getters.getRangeFromZone(t.sheetId,is(t.zone)):e.range,o=r||e.config;return{...e,range:n,config:o}}updateTableConfig(e,t){if(!e)return t;const r={...t,...e};return 0===e.numberOfHeaders?r.hasFilters=!1:!0===e.hasFilters&&(r.numberOfHeaders||=1),r}createFilterFromZone(e,t,r,n){return GE(e,this.getters.getRangeFromZone(t,r),n,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){const r=this.getters.getRangeFromZone(e,t.range.zone),n=t.filters.map(r=>{const n=this.getters.getRangeFromZone(e,r.rangeWithHeaders.zone);return GE(r.id,n,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:r,filters:n,config:re(t.config),type:t.type}}copyDynamicTableForSheet(e,t){const r=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:r,config:re(t.config),type:"dynamic"}}applyRangeChangeOnTable(e,t,r){const n=r(t.range);let o;switch(n.changeType){case"REMOVE":return void this.history.update("tables",e,t.id,void 0);case"NONE":return;default:o=n.range}if("dynamic"===t.type){const r=this.updateDynamicTable(t,o);return void this.history.update("tables",e,t.id,r)}const s=[];for(const e of t.filters){const n=r(e.rangeWithHeaders);switch(n.changeType){case"REMOVE":continue;case"NONE":s.push(e);break;default:const r=n.range,o=GE(e.id,r,t.config,this.getters.getRangeFromZone);s.push(o)}}const i=o.zone;if(s.length<es(i).numberOfCols){for(let r=i.left;r<=i.right;r++)if(!s.find(e=>e.col===r)){const n=this.consumeNextId(),o={...i,left:r,right:r};s.push(this.createFilterFromZone(n,e,o,t.config))}s.sort((e,t)=>e.col-t.col)}const a=this.createStaticTable(t.id,t.type,o,t.config,s);this.history.update("tables",e,t.id,a)}consumeNextId(){const e=`${this.nextTableId}`;return this.history.update("nextTableId",this.nextTableId+1),e}import(e){for(const t of e.sheets)for(const e of t.tables||[]){const r=this.consumeNextId(),n=e.config||Tp,o=this.getters.getRangeFromSheetXC(t.id,e.range),s=e.type||"static",i="dynamic"===s?this.createDynamicTable(r,o,n):this.createStaticTable(r,s,o,n);this.history.update("tables",t.id,i.id,i)}}export(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const r={range:Go(e.range.zone),type:e.type};Ae(e.config,Tp)||(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=Go(e.range.zone);t.tables.push({range:r,filters:[],config:e.config})}}}).add("dataValidation",class extends gE{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 n=this.rules[t][r];for(let o=0;o<n.criterion.values.length;o++){const s=this.getters.adaptFormulaStringDependencies(t,n.criterion.values[o],e);this.history.update("rules",t,r,"criterion","values",o,s)}}}}adaptDVRanges(e,t){for(let r=this.rules[e].length-1;r>=0;r--){const n=this.rules[e][r];for(let o=n.ranges.length-1;o>=0;o--){const s=t(n.ranges[o]);switch(s.changeType){case"REMOVE":if(1===n.ranges.length)this.removeDataValidationRule(e,n.id);else{const t=n.ranges.slice();t.splice(o,1),this.history.update("rules",e,r,"ranges",t)}break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("rules",e,r,"ranges",o,s.range)}}}}allowDispatch(e){switch(e.type){case"ADD_DATA_VALIDATION_RULE":return this.getters.tryGetSheet(e.sheetId)?e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?"InvalidSheetId":this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid)):"InvalidSheetId";case"REMOVE_DATA_VALIDATION_RULE":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";if(!this.rules[e.sheetId].find(t=>t.id===e.id))return"UnknownDataValidationRule"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("rules",e.sheetId,[]);break;case"DUPLICATE_SHEET":{const t=re(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>Fm(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=Fo(e.target),r=e.sheetId;for(const e of t)for(let t=e.top;t<=e.bottom;t++)for(let n=e.left;n<=e.right;n++){const e=this.getValidationRuleForCell({sheetId:r,col:n,row:t});if(e&&("isBoolean"===e.criterion.type||"isValueInList"===e.criterion.type&&!this.getters.getCell({sheetId:r,col:n,row:t})?.content)){const e=this.rules[r],o=[this.getters.getRangeFromSheetXC(r,Do(n,t))],s=this.removeRangesFromRules(r,o,e);this.history.update("rules",r,s)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:r}){if(this.rules[e])for(const n of this.rules[e])for(const e of n.ranges)if(Qo(t,r,e.zone))return n}cellHasListDataValidationIcon(e){const t=this.getValidationRuleForCell(e);return!!t&&!("isValueInList"!==t.criterion.type&&"isValueInRange"!==t.criterion.type||"arrow"!==t.criterion.displayStyle&&"chip"!==t.criterion.displayStyle)}addDataValidationRule(e,t){const r=this.rules[e];"isBoolean"===t.criterion.type?this.setCenterStyleToBooleanCells(t):"isValueInList"===t.criterion.type&&(t.criterion.values=Array.from(new Set(t.criterion.values)));const n=this.removeRangesFromRules(e,t.ranges,r,t.id),o=n.findIndex(e=>e.id===t.id);-1!==o?(n[o]=t,this.history.update("rules",e,n)):this.history.update("rules",e,[...n,t])}removeRangesFromRules(e,t,r,n){r=re(r);for(const e of r)e.id!==n&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return r.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){const r=this.rules[e].filter(e=>e.id!==t);this.history.update("rules",e,r)}setCenterStyleToBooleanCells(e){for(const t of Nm(e.ranges)){const e=this.getters.getCell(t),r={...e?.style,align:e?.style?.align??"center",verticalAlign:e?.style?.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 bE.contains(e.rule.criterion.type)?"Success":"UnknownDataValidationCriterionType"}checkCriterionHasValidNumberOfValues(e){const t=e.rule.criterion,r=bE.get(t.type).numberOfValues(t);return void 0!==r&&t.values.length!==r?"InvalidNumberOfCriterionValues":"Success"}checkCriterionValuesAreValid(e){const t=e.rule.criterion,r=bE.get(t.type);return t.values.some(e=>"onlyFormulas"===r.allowedValues&&!e.startsWith("=")||(e.startsWith("=")?"onlyLiterals"===r.allowedValues||gm(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 gE{static getters=["zoneToXC","getCells","getTranslatedCellFormula","getCellStyle","getCellById","getFormulaString","getFormulaMovedInSheet"];nextId=1;cells={};adaptRanges(e,t,r){for(const n of Object.keys(this.cells))for(const o of Object.values(this.cells[n]||{}))if(o.isFormula)for(const s of o.compiledFormula.dependencies)if(s.sheetId===t||s.invalidSheetName===r.old){const t=e(s);"NONE"!==t.changeType&&this.history.update("cells",n,o.id,"compiledFormula","dependencies",o.compiledFormula.dependencies.indexOf(s),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case"UPDATE_CELL_POSITION":return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?"Success":"InvalidCellId";default:return"Success"}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",style:null,format:""});break;case"CLEAR_CELLS":this.clearCells(e.sheetId,e.target);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"DELETE_SHEET":this.history.update("cells",e.sheetId,void 0)}}clearZones(e,t){for(const r of Fo(t))for(let t=r.left;t<=r.right;t++)for(let n=r.top;n<=r.bottom;n++){const r=this.getters.getCell({sheetId:e,col:t,row:n});(r?.isFormula||r?.content)&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:n})}}setFormatter(e,t,r){for(const n of Fo(t))for(let t=n.top;t<=n.bottom;t++)for(let o=n.left;o<=n.right;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,format:r})}clearFormatting(e,t){for(const r of Fo(t))for(let t=r.left;t<=r.right;t++)for(let n=r.top;n<=r.bottom;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,style:null,format:""})}clearCells(e,t){for(const r of t)for(let t=r.left;t<=r.right;t++)for(let n=r.top;n<=r.bottom;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,content:"",style:null,format:""})}handleAddColumnsRows(e,t){let r,n;"before"===e.position?(r=le(e.base,e.base+e.quantity),n=e.base+e.quantity):(r=le(e.base+1,e.base+e.quantity+1),n=e.base),t(e.sheetId,n,r)}import(e){for(const t of e.sheets){const r=t.id,n=new fE;for(const e in t.cells)if(t.cells[e]){const{col:r,row:o}=Oo(e),s={sheetId:t.id,col:r,row:o};n.set(s,{content:t.cells[e]})}for(const[e,r]of[["style",t.styles],["format",t.formats]])for(const[o,s]of fy(t.id,r)){const t=n.get(o);t?t[e]=s:n.set(o,{[e]:s})}for(const o of n.keysForSheet(r)){const r=n.get(o);if(r?.content||r?.format||r?.style){const n=this.importCell(t.id,r?.content,r?.style?e.styles[r?.style]:void 0,r?.format?e.formats[r?.format]:void 0);this.history.update("cells",t.id,n.id,n),this.dispatch("UPDATE_CELL_POSITION",{cellId:n.id,...o})}}}}export(e){const t={},r={};for(const n of e.sheets){const e=[],o=[],s={},i=Object.keys(this.cells[n.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(const n of i){const i=this.getters.getCell(n),a=Do(n.col,n.row),l=this.removeDefaultStyleValues(i.style);if(Object.keys(l).length){const r=hy(l,t);e[r]??=[],e[r].push(n)}if(i.format){const e=hy(i.format,r);o[e]??=[],o[e].push(n)}i.content&&(s[a]=i.content)}n.styles=dy(e),n.formats=dy(o),n.cells=s}e.styles=t,e.formats=r}importCell(e,t,r,n){const o=this.getNextUid();return this.createCell(o,t||"",n,r,e)}exportForExcel(e){this.export(e);const t=[];for(const r in e.formats||[])Kn(e.formats[r])||(t.push(Number(r)),delete e.formats[r]);if(t.length)for(const r of e.sheets)for(const e in r.formats){const n=r.formats[e];n&&t.includes(n)&&delete r.formats[e]}}removeDefaultStyleValues(e){const t={...e};for(const e in G)t[e]===G[e]&&delete t[e];return t}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,r,n=!1){if(!r.length)return Ie(t.map(e=>e.value));let o=0;return Ie(t.map(t=>{if("REFERENCE"===t.type){const t=r[o++];return this.getters.getRangeString(t,e,{useBoundedReference:n})}return t.value}))}getTranslatedCellFormula(e,t,r,n){const o=this.getters.createAdaptedRanges(mm(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,r,e);return this.getFormulaString(e,n,o)}getFormulaMovedInSheet(e,t,r){const n=mm(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),o=this.getters.removeRangesSheetPrefix(t,n);return this.getFormulaString(t,r,o)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,r=[{colFixed:!1,rowFixed:!1}]){const n=Do((t=this.getters.expandZone(e,t)).left,t.top,r[0]),o=Do(t.right,t.bottom,r.length>1?r[1]:r[0]),s=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),i=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=s.col===i.col&&s.row===i.row;return n===o||a?n:n+":"+o}setStyle(e,t,r){for(const n of Fo(t))for(let t=n.left;t<=n.right;t++)for(let o=n.top;o<=n.bottom;o++){const n=this.getters.getCell({sheetId:e,col:t,row:o});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:r?{...n?.style,...r}:void 0})}}copyColumnStyle(e,t,r){for(let n=0;n<this.getters.getNumberRows(e);n++){const o=this.getFormat(e,t,n);if(o.style||o.format)for(const t of r)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,...o})}}copyRowStyle(e,t,r){for(let n=0;n<this.getters.getNumberCols(e);n++){const o=this.getFormat(e,n,t);if(o.style||o.format)for(const t of r)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,...o})}}getFormat(e,t,r){const n={},o=this.getters.getMainCellPosition({sheetId:e,col:t,row:r}),s=this.getters.getCell(o);return s&&(s.style&&(n.style=s.style),s.format&&(n.format=s.format)),n}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,r,n){const o=this.getters.getCell({sheetId:e,col:t,row:r}),s="content"in n||"formula"in n,i=s?Pe(n?.content):o?.content||"";let a;a=void 0!==n.style?n.style||void 0:o?o.style:void 0;const l="format"in n?n.format:o&&o.format;if((s&&!i&&!n.formula||!s&&(!o||""===o.content))&&!a&&!l)return void(o&&(this.history.update("cells",e,o.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:r,sheetId:e})));const c=o?.id||this.getNextUid(),u=this.createCell(c,i,l,a,e);this.history.update("cells",e,u.id,u),this.dispatch("UPDATE_CELL_POSITION",{cellId:u.id,col:t,row:r,sheetId:e})}createCell(e,t,r,n,o){return t.startsWith("=")?this.createFormulaCell(e,t,r,n,o):this.createLiteralCell(e,t,r,n)}createLiteralCell(e,t,r,n){const o=this.getters.getLocale(),s=Wy(t,o);return Qn(r=r||("number"==typeof s?Gn(t,o)||Wn(t):void 0))||t.startsWith("'")||Vt(t)||(t=$t(s)),{id:e,content:t,style:n,format:r,isFormula:!1,parsedValue:s}}createFormulaCell(e,t,r,n,o){const s=gm(t);return s.dependencies.length?this.createFormulaCellWithDependencies(e,s,r,n,o):{id:e,content:t,style:n,format:r,isFormula:!0,compiledFormula:{...s,dependencies:[]}}}createFormulaCellWithDependencies(e,t,r,n,o){const s=[];for(const e of t.dependencies)s.push(this.getters.getRangeFromSheetXC(o,e));return new mE(e,t,r,n,s,o,this.getters.getRangeString)}checkCellOutOfSheet(e){const{sheetId:t,col:r,row:n}=e;if(!this.getters.tryGetSheet(t))return"InvalidSheetId";return Qo(r,n,this.getters.getSheetZone(t))?"Success":"TargetOutOfSheet"}checkUselessClearCell(e){const t=this.getters.getCell(e);return t&&(t.content||t.style||t.format)?"Success":"NoChanges"}checkUselessUpdateCell(e){const t=this.getters.getCell(e),r="style"in e,n="format"in e;return("content"in e||"formula"in e)&&t?.content!==e.content||r&&!Ae(t?.style,e.style)||n&&t?.format!==e.format?"Success":"NoChanges"}}).add("merge",class extends gE{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge","getSelectionRangeString","isMainCellPosition"];nextId=1;merges={};mergeCellMap={};allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return"Success"}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const r of Object.values(t).filter(Se))this.addMerge(e.sheetIdTo,r.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(Se)}getMerge({sheetId:e,col:t,row:r}){const n=this.mergeCellMap[e],o=n?t in n&&n[t]?.[r]:void 0;return o?this.getMergeById(e,o):void 0}getMergesInZone(e,t){const r=this.mergeCellMap[e];if(!r)return[];const n=new Set;for(let e=t.left;e<=t.right;e++)for(let o=t.top;o<=t.bottom;o++){const t=r[e]?.[o];t&&n.add(t)}return Array.from(n).map(t=>this.getMergeById(e,t)).filter(Se)}getSelectionRangeString(e,t){const r=this.getters.expandZone(e.sheetId,e.zone),n=xm({...e,zone:{...r,bottom:_m(e)?void 0:r.bottom,right:Om(e)?void 0:r.right}},this.getters.getSheetSize),o=this.getters.getRangeString(n,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){const{sheetName:e,xc:t}=go(o);return mo(e,t.split(":")[0])}return o}doesIntersectMerge(e,t){for(const r of this.getMerges(e))if(Ko(t,r))return!0;return!1}doesColumnsHaveCommonMerges(e,t,r){const n=this.getters.getSheet(e);for(let o=0;o<this.getters.getNumberRows(e);o++)if(this.isInSameMerge(n.id,t,o,r,o))return!0;return!1}doesRowsHaveCommonMerges(e,t,r){const n=this.getters.getSheet(e);for(let o=0;o<=this.getters.getNumberCols(e);o++)if(this.isInSameMerge(n.id,o,t,o,r))return!0;return!1}expandZone(e,t){const{left:r,right:n,top:o,bottom:s}=t;let i={left:r,right:n,top:o,bottom:s};for(const t in this.merges[e]){const r=this.getMergeById(e,parseInt(t));r&&Ko(r,i)&&(i=Zo(r,i))}return jo(i,t)?i:this.expandZone(e,i)}isInSameMerge(e,t,r,n,o){const s=this.getMerge({sheetId:e,col:t,row:r}),i=this.getMerge({sheetId:e,col:n,row:o});return!(!s||!i)&&jo(s,i)}isInMerge({sheetId:e,col:t,row:r}){const n=this.mergeCellMap[e];return!!n&&(t in n&&Boolean(n[t]?.[r]))}getMainCellPosition(e){const t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){const r=this.getters.getHiddenColsGroups(e),n=this.getters.getHiddenRowsGroups(e);for(const e of r)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(const e of n)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const r=this.getMerge({sheetId:e,col:t.left,row:t.top});if(r)return jo(t,r);const{numberOfCols:n,numberOfRows:o}=es(t);return 1===n&&1===o}isMainCellPosition(e){return Ae(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:r,right:n,top:o,bottom:s}=t;n=ae(n,0,this.getters.getNumberCols(e)-1),s=ae(s,0,this.getters.getNumberRows(e)-1);for(let t=o;t<=s;t++)for(let s=r;s<=n;s++)if(s!==r||t!==o){const r=this.getters.getCell({sheetId:e,col:s,row:t});if(r&&""!==r.content)return!0}return!1}getMergeById(e,t){const r=this.merges[e]?.[t];return void 0!==r?IE(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&&Ko(t,r))return"MergeOverlap";return"Success"}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";const{xSplit:r,ySplit:n}=this.getters.getPaneDivisions(e);return function(e,t,r){return e.some(e=>function(e,t,r){return e.left<t&&t<=e.right||e.top<r&&r<=e.bottom}(e,t,r))}(t,r,n)?"FrozenPaneOverlap":"Success"}checkMergedContentUpdate(e){const{col:t,row:r,content:n}=e;if(void 0===n)return"Success";const{col:o,row:s}=this.getMainCellPosition(e);return o===t&&s===r?"Success":"CellIsMerged"}checkMergeExists(e){const{sheetId:t,target:r}=e;for(const e of r){const{left:r,top:n}=e,o=this.getMerge({sheetId:t,col:r,row:n});if(void 0===o||!jo(e,o))return"InvalidTarget"}return"Success"}addMerge(e,t){let{left:r,right:n,top:o,bottom:s}=t;n=ae(n,0,this.getters.getNumberCols(e)-1),s=ae(s,0,this.getters.getNumberRows(e)-1);if(Do(r,o)===Do(n,s))return;const i=this.getters.getCell({sheetId:e,col:r,row:o}),a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Go({left:r,top:o,right:n,bottom:s})));const l=new Set;for(let t=o;t<=s;t++)for(let s=r;s<=n;s++){s===r&&t===o||this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,style:i?i.style:null,content:""});const n=this.getMerge({sheetId:e,col:s,row:t});n&&l.add(n.id),this.history.update("mergeCellMap",e,s,t,a)}for(const t of l){const{top:r,bottom:n,left:o,right:s}=this.getMergeById(e,t);for(let t=r;t<=n;t++)for(let r=o;r<=s;r++){const n={sheetId:e,col:r,row:t},o=this.getMerge(n);o&&o.id===a||(this.history.update("mergeCellMap",e,r,t,void 0),this.dispatch("CLEAR_CELL",n))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:r,top:n,bottom:o,right:s}=t,i=this.getMerge({sheetId:e,col:r,row:n});if(void 0!==i&&jo(t,i)){this.history.update("merges",e,i.id,void 0);for(let t=n;t<=o;t++)for(let n=r;n<=s;n++)this.history.update("mergeCellMap",e,n,t,void 0)}}applyRangeChangeOnSheet(e,t){const r=Object.entries(this.merges[e]||{});for(const[n,o]of r)if(o){const r=o.zone,s=t(o);switch(s.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,r);break;default:const{numberOfCols:t,numberOfRows:o}=es(s.range.zone);1===t&&1===o?this.removeMerge(e,r):this.history.update("merges",e,parseInt(n,10),s.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:r,row:n}of rs(t))this.history.update("mergeCellMap",e,r,n,t.id)}import(e){const t=e.sheets||[];for(const e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(const r of t)this.addMerge(e,Bo(r))}export(e){for(const t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...TE(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends gE{static getters=["getUserRowSize","getColSize"];sizes={};handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("sizes",e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case"DUPLICATE_SHEET":this.history.update("sizes",e.sheetIdTo,re(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const t={...this.sizes};delete t[e.sheetId],this.history.update("sizes",t);break;case"REMOVE_COLUMNS_ROWS":{const t=He(this.sizes[e.sheetId][e.dimension],e.elements);this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=this.sizes[e.sheetId][e.dimension],r=Re(e.position,e.base),n=t[e.base],o=Be(t,Array(e.quantity).fill(n),r);this.history.update("sizes",e.sheetId,e.dimension,o);break}case"RESIZE_COLUMNS_ROWS":if("ROW"===e.dimension)for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0);else for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0)}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){const r=this.sizes[e]?.ROW[t];return r?Math.round(r):void 0}import(e){for(const t of e.sheets){const e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(const[r,n]of Object.entries(t.rows))n.size&&(e.ROW[r]=n.size);for(const[r,n]of Object.entries(t.cols))n.size&&(e.COL[r]=n.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const r of e.sheets){void 0===r.rows&&(r.rows={});for(const e of le(0,this.getters.getNumberRows(r.id)))(t||this.sizes[r.id].ROW[e])&&(r.rows[e]={...r.rows[e],size:this.getUserRowSize(r.id,e)??$});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 gE{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,[ss(e)],e.border);break;case"SET_BORDERS_ON_TARGET":for(const t of e.target)for(let r=t.left;r<=t.right;r++)for(let n=t.top;n<=t.bottom;n++)this.addBorder(e.sheetId,{left:r,right:r,top:n,bottom:n},e.border&&Object.keys(e.border).length?e.border:void 0);break;case"SET_ZONE_BORDERS":const r=e.target.map(t=>this.getters.expandZone(e.sheetId,t));"clear"===e.border.position?this.clearBorders(e.sheetId,r):this.addBorders(e.sheetId,r,this.borderDataToNewBorderData(e.border));break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target)}}beforeHandle(e){"REMOVE_COLUMNS_ROWS"===e.type&&("ROW"===e.dimension?this.onRowRemove(e.sheetId,e.elements):this.onColRemove(e.sheetId,e.elements))}adaptRanges(e,t){const r=[];for(const n of this.borders[t]??[]){const o=e(this.getters.getRangeFromZone(t,n.zone));switch(o.changeType){case"RESIZE":case"CHANGE":case"MOVE":r.push({...n,zone:o.range.unboundedZone});break;case"NONE":r.push(n)}}this.history.update("borders",t,r.filter(e=>!this.borderIsClear(e)))}onRowRemove(e,t){const r=new Set(t),n=[];for(const t of this.borders[e]??[]){let e=t;r.has(t.zone.top)&&(e=re(t),e.style.top=t.style.horizontal),void 0!==t.zone.bottom&&r.has(t.zone.bottom)&&(e=e===t?re(t):e,e.style.bottom=t.style.horizontal),n.push(e)}this.history.update("borders",e,n)}onColRemove(e,t){const r=new Set(t),n=[];for(const t of this.borders[e]??[]){let e=t;r.has(t.zone.left)&&(e=re(t),e.style.left=t.style.vertical),void 0!==t.zone.right&&r.has(t.zone.right)&&(e=e===t?re(t):e,e.style.right=t.style.vertical),n.push(e)}this.history.update("borders",e,n.filter(e=>!this.borderIsClear(e)))}getCellBorder(e){return this.getZoneExternalBorders(e.sheetId,ss(e))}getZoneExternalBorders(e,t){const r={};for(const n of this.borders[e]??[])Ko(n.zone,t)&&(r.right=(t.right===n.zone.right?n.style.right:n.style.vertical)??r.right,r.left=(t.left===n.zone.left?n.style.left:n.style.vertical)??r.left,r.bottom=(t.bottom===n.zone.bottom?n.style.bottom:n.style.horizontal)??r.bottom,r.top=(t.top===n.zone.top?n.style.top:n.style.horizontal)??r.top);return r}getCellBordersInZone(e,t){const r=new fE;for(const n of this.borders[e]??[]){const{zone:o,style:s}=n,i=Yo(o,t);if(i)for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){const i=r.get({sheetId:e,col:t,row:n})??{};i.right=(t===o.right?s.right:s.vertical)??i.right,i.left=(t===o.left?s.left:s.vertical)??i.left,i.bottom=(n===o.bottom?s.bottom:s.horizontal)??i.bottom,i.top=(n===o.top?s.top:s.horizontal)??i.top,r.set({sheetId:e,col:t,row:n},i)}}return r}getBordersColors(e){const t=new Set;for(const r of this.borders[e]??[])for(const e of Object.values(r.style))e?.color&&t.add(e.color);return[...t]}getBorders(e,t){const r=[];for(const n of this.borders[e]??[]){const e=Yo(n.zone,t);e&&r.push(this.computeBorderFromZone(e,n))}return r}computeBorderFromZone(e,t){const r=t.style,n=t.zone,o=e.top===n.top,s=e.bottom===n.bottom,i=e.left===n.left,a=e.right===n.right;return{zone:e,style:{top:o?r.top:r.horizontal,bottom:s?r.bottom:r.horizontal,left:i?r.left:r.vertical,right:a?r.right:r.vertical,vertical:r.vertical,horizontal:r.horizontal}}}borderIsClear(e){const t=e.style;if(t.left||t.right||t.bottom||t.top)return!1;const r=e.zone;return(!(void 0===r.bottom||r.top<r.bottom)||!t.horizontal)&&(!(void 0===r.right||r.left<r.right)||!t.vertical)}clearBorders(e,t){for(const r of t)this.removeAndClearAdjacent(e,r)}removeAndClearAdjacent(e,t){const r=[];for(const n of this.borders[e]??[])for(const e of Fo([n.zone],[t]))for(const o of hs(e,t)){const e=this.computeBorderFromZone(o,n),s=Xo(o,t);switch(s?.position){case"left":e.style.left=void 0;break;case"right":e.style.right=void 0;break;case"top":e.style.top=void 0;break;case"bottom":e.style.bottom=void 0}r.push(e)}this.history.update("borders",e,r)}addBorders(e,t,r){for(const n of t)this.addBorder(e,n,r)}addBorder(e,t,r,n=!1){const o=[],s=r?{zone:t,style:r}:void 0,i={left:n||!!r?.left,right:n||!!r?.right,top:n||!!r?.top,bottom:n||!!r?.bottom};let a=[t];for(const r of this.borders[e]??[]){const e=Yo(r.zone,t);if(!e){const e=Xo(r.zone,t);if(e&&i[e.position])for(const e of hs(r.zone,t)){const n=this.computeBorderFromZone(e,r),s=Xo(e,t);switch(s?.position){case"left":n.style.left=void 0;break;case"right":n.style.right=void 0;break;case"top":n.style.top=void 0;break;case"bottom":n.style.bottom=void 0}o.push(n)}else o.push(r);continue}if(s){let t=this.computeBorderFromZone(e,s).style;n||(t={...this.computeBorderFromZone(e,r).style,...Fe(t)}),o.push({zone:e,style:t})}a=Fo(a,[e]);for(const t of Fo([r.zone],[e]))o.push(this.computeBorderFromZone(t,r))}s&&o.push(...a.map(e=>this.computeBorderFromZone(e,s))),this.history.update("borders",e,o.filter(e=>!this.borderIsClear(e)))}borderDataToNewBorderData(e){const t={},r={color:e.color??"#000000",style:e.style??"thin"};return["all","external","top"].includes(e.position)&&(t.top={...r}),["all","external","bottom"].includes(e.position)&&(t.bottom={...r}),["all","external","left"].includes(e.position)&&(t.left={...r}),["all","external","right"].includes(e.position)&&(t.right={...r}),["all","hv","v"].includes(e.position)&&(t.vertical={...r}),["all","hv","h"].includes(e.position)&&(t.horizontal={...r}),t}checkBordersUnchanged(e){const t=this.getCellBorder(e),r=!(e.border?.bottom||e.border?.left||e.border?.right||e.border?.top);return!t&&r||Ae(t,e.border)?"NoChanges":"Success"}ensureHasBorder(e){return e.border?"Success":"NoChanges"}addBordersToMerge(e,t){const r={...this.getZoneExternalBorders(e,t),...Fe(this.getCellBorder({sheetId:e,col:t.left,row:t.top}))};this.addBorder(e,t,r,!0)}import(e){if(Object.keys(e.borders||{}).length)for(const t of e.sheets)for(const r in t.borders){const n=t.borders[r];this.addBorder(t.id,Bo(r),e.borders[n])}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.addBordersToMerge(t.id,Bo(e))}export(e){const t={};for(const r of e.sheets){r.borders={};for(const e of this.borders[r.id]??[])r.borders[Go(e.zone)]=hy(e.style,t)}e.borders=t}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends gE{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 n=e(r.rule.rangeValues);switch(n.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",n.range)}}else if("CellIsRule"===r.rule.type)for(let n=0;n<r.rule.values.length;n++)this.history.update("cfRules",t,this.cfRules[t].indexOf(r),"rule","values",n,this.getters.adaptFormulaStringDependencies(t,r.rule.values[n],e));else if("IconSetRule"===r.rule.type)for(const n of["lowerInflectionPoint","upperInflectionPoint"])"formula"===r.rule[n].type&&this.history.update("cfRules",t,this.cfRules[t].indexOf(r),"rule",n,"value",this.getters.adaptFormulaStringDependencies(t,r.rule[n].value,e));else if("ColorScaleRule"===r.rule.type)for(const n of["minimum","maximum","midpoint"]){const o=r.rule[n];"formula"===o?.type&&o?.value&&this.history.update("cfRules",t,this.cfRules[t].indexOf(r),"rule",n,"value",this.getters.adaptFormulaStringDependencies(t,o.value,e))}}adaptCFRanges(e,t){for(const r of this.cfRules[e])for(const n of r.ranges){const o=t(n);switch(o.changeType){case"REMOVE":const t=r.ranges.slice();t.splice(r.ranges.indexOf(n),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(r),"ranges",t):this.removeConditionalFormatting(r.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(r),"ranges",r.ranges.indexOf(n),o.range)}}}adaptRanges(e,t){const r=t?[t]:Object.keys(this.cfRules);for(const t of r)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?"InvalidSheetId":this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case"CHANGE_CONDITIONAL_FORMAT_PRIORITY":return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const r={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(r,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"CHANGE_CONDITIONAL_FORMAT_PRIORITY":this.changeCFPriority(e.cfId,e.delta,e.sheetId)}}import(e){for(const t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(const t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(const t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){const r=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{r.add(e)})}),Array.from(r)}getRulesByZone(e,t){const r=new Set;for(let n=t.top;n<=t.bottom;n++)for(let o=t.left;o<=t.right;o++){this.getRulesByCell(e,o,n).forEach(e=>{r.add(e.id)})}return r}getRulesByCell(e,t,r){const n=[];for(const o of this.cfRules[e])for(const e of o.ranges)Qo(t,r,e.zone)&&n.push(o);return new Set(n.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,r,n){if(0===r.length&&0===n.length)return;const o=this.getters.getConditionalFormats(e),s=o.findIndex(e=>e.id===t.id);let i=[];s>-1&&(i=o[s].ranges.map(Ho));const a=Fo(i,n);return Fo([...r,...a],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:r}={useBoundedReference:!1}){const n=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:r}));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:n}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:r})},ranges:n}}mapToConditionalFormatInternal(e,t){const r=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:r}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:r}}addConditionalFormatting(e,t){const r=this.cfRules[t].slice(),n=r.findIndex(t=>t.id===e.id),o=this.mapToConditionalFormatInternal(t,e);n>-1?r.splice(n,1,o):r.push(o),this.history.update("cfRules",t,r)}checkValidPriorityChange(e,t,r){if(!this.cfRules[r])return"InvalidSheetId";const n=this.cfRules[r].findIndex(t=>t.id===e);if(-1===n)return"InvalidConditionalFormatId";const o=n-t;return o<0||o>=this.cfRules[r].length?"InvalidConditionalFormatId":"Success"}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues);case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return"Success"}checkCFHasChanged(e){const t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),r=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return r&&Ae(t,r)?"NoChanges":"Success"}checkOperatorArgsNumber(e){const t=bE.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(void 0===t||t>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");const r=[],n=e=>void 0===e||""===e;return t>=1&&n(e.values[0])&&r.push("FirstArgMissing"),t>=2&&n(e.values[1])&&r.push("SecondArgMissing"),r.length?r:"Success"}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return"MinNaN";case"max":return"MaxNaN";case"mid":return"MidNaN";case"upperInflectionPoint":return"ValueUpperInflectionNaN";case"lowerInflectionPoint":return"ValueLowerInflectionNaN"}return"Success"}checkFormulaCompilation(e,t){if("formula"!==e.type)return"Success";if(gm(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&&CE(t)>=CE(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&&CE(t)>=CE(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&&CE(t)>=CE(r)?"MinBiggerThanMid":"Success"}checkCFValues(e){for(const t of e.values){if(!t.startsWith("="))continue;if(gm(t||"").isBadExpression)return"ValueCellIsInvalidFormula"}return"Success"}removeConditionalFormatting(e,t){const r=this.cfRules[t].findIndex(t=>t.id===e);if(-1!==r){const e=this.cfRules[t].slice();e.splice(r,1),this.history.update("cfRules",t,e)}}changeCFPriority(e,t,r){const n=this.cfRules[r].findIndex(t=>t.id===e),o=this.cfRules[r][n],s=n-t,i=[...this.cfRules[r]];i.splice(n,1),i.splice(s,0,o),this.history.update("cfRules",r,i)}}).add("figures",class extends gE{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};insertionOrders=[];adaptRanges(e,t){for(const r of this.getFigures(t)){const n=e(this.getters.getRangeFromZone(t,{left:r.col,right:r.col,top:r.row,bottom:r.row}));if("MOVE"===n.changeType)this.history.update("figures",t,r.id,"col",n.range.zone.right),this.history.update("figures",t,r.id,"row",n.range.zone.bottom);else if("REMOVE"===n.changeType){const n=e(this.getters.getRangeFromZone(t,{left:0,right:r.col-1,top:0,bottom:r.row-1}));let{offset:o,col:s,row:i}=r;"NONE"!==n.changeType&&(s=n.range.zone.right+1,i=n.range.zone.bottom+1),({offset:o,col:s,row:i}=this.getPositionInSheet(t,{...r,col:s,row:i})),this.history.update("figures",t,r.id,"offset",o),this.history.update("figures",t,r.id,"col",s),this.history.update("figures",t,r.id,"row",i)}}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case"UPDATE_FIGURE":return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case"DELETE_FIGURE":return this.checkFigureExists(e);default:return"Success"}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch("DELETE_FIGURE",{figureId:t.id,sheetId:e.sheetId})})}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":const t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case"UPDATE_FIGURE":this.updateFigure(e);break;case"DELETE_FIGURE":this.removeFigure(e.figureId,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case"DUPLICATE_SHEET":for(const t in this.figures[e.sheetId]){const r=this.figures[e.sheetId]?.[t];if(!r)continue;const n=t.split(j).pop(),o=`${e.sheetIdTo}${j}${n}`;this.dispatch("CREATE_FIGURE",{figureId:o,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}}}onColRemove(e){const t=this.getters.getNumberCols(e),r=new Array(t+1);r[t]=0;for(let n=t-1;n>=0;n--)r[n]=r[n+1]+this.getters.getColSize(e,n);for(const t of this.getFigures(e))if(t.offset.x+t.width>r[t.col]){let n=t.offset.x,o=t.col;for(n=Math.min(n,r[o]-t.width);n<0&&o>0;)o--,n=r[o]-t.width;n!==t.offset.x&&this.history.update("figures",e,t.id,"offset",{x:Math.max(n,0),y:t.offset.y}),o!==t.col&&this.history.update("figures",e,t.id,"col",o)}}onRowRemove(e){const t=this.getters.getNumberRows(e),r=new Array(t+1);r[t]=0;for(let n=t-1;n>=0;n--)r[n]=r[n+1]+(this.getters.getUserRowSize(e,n)??$);for(const t of this.getFigures(e))if(t.offset.y+t.height>r[t.row]){let n=t.offset.y,o=t.row;for(let t=this.getters.getUserRowSize(e,o)??$;t<n;t=this.getters.getUserRowSize(e,o)??$)o+=1,n-=t;for(n=Math.min(n,r[o]-t.height);n<0&&o>0;)o--,n=r[o]-t.height;n!==t.offset.y&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(0,n)}),o!==t.row&&this.history.update("figures",e,t.id,"row",o)}else t.offset.y+t.height>r[0]&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(r[0]-t.height,0)})}getPositionInSheet(e,t){const{numberOfRows:r,numberOfCols:n}=this.getters.getSheetSize(e);let o,s,i=0,a=0,{col:l,row:c}=t;const u={...t.offset};for(o=r;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??$;for(c>o?(c=o,u.y=Math.max(i-t.height,0)):c===o&&(u.y=ae(u.y,0,Math.max(i-t.height,0))),s=n;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return l>s?(l=s,u.x=Math.max(a-t.width,0)):s===l&&(u.x=ae(u.x,0,Math.max(a-t.width,0))),{col:l,row:c,offset:u}}updateFigure(e){if(!("figureId"in e)||!("sheetId"in e))return;const{figureId:t,sheetId:r,...n}=e,o={...this.getFigure(r,t),...n};for(const[e,t]of Object.entries(n))switch(e){case"tag":case"offset":this.history.update("figures",r,o.id,e,t);break;case"col":case"row":case"width":case"height":void 0!==t&&this.history.update("figures",r,o.id,e,t)}}addFigure(e,t){this.history.update("figures",t,e.id,e),this.history.update("insertionOrders",this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update("insertionOrders",this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("insertionOrders",this.insertionOrders.filter(t=>t!==e)),this.history.update("figures",t,e,void 0)}checkFigureExists(e){return void 0===this.figures[e.sheetId]?.[e.figureId]?"FigureDoesNotExist":"Success"}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?"DuplicatedFigureId":"Success"}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?"WrongSheetPosition":"Success"}getFigures(e){const t=[];for(const r of this.insertionOrders){const n=this.figures[e]?.[r];n&&t.push(n)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>void 0!==this.figures[t]?.[e])}import(e){for(const t of e.sheets)for(const e of t.figures)this.addFigure(e,t.id)}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const r=void 0;t.figures.push({...e,data:r})}}exportForExcel(e){return this.export(e)}}).add("chart",class extends gE{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getFigureIdFromChartId","getContextCreationChart"];charts={};createChart=function(e){const t=Yp.getAll().sort((e,t)=>e.sequence-t.sequence);return function(r,n,o){const s=t.find(e=>e.match(n.type));if(!s)throw new Error(`No builder for this chart: ${n.type}`);return s.createChart(n,o,e)}}(this.getters);validateChartDefinition=e=>function(e,t){const r=Yp.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[n,o]of Object.entries(this.charts)){if(!o)continue;const s=o.chart.updateRanges(e,t,r);this.history.update("charts",n,s?{figureId:o.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:n,size:o,sheetId:s,figureId:i}=e;this.getters.getFigure(s,i)||void 0===n||void 0===t||void 0===r||this.addFigure(i,s,t,r,n,o),this.addChart(e.figureId,e.chartId,e.definition);break;case"UPDATE_CHART":this.addChart(e.figureId,e.chartId,e.definition);break;case"DUPLICATE_SHEET":for(const t of this.getChartIds(e.sheetId)){const{chart:r,figureId:n}=this.charts[t]||{};if(!r||!n)continue;const o=this.getters.getFigure(e.sheetId,n);if(!o)continue;const s=n.split(j).pop(),i=`${e.sheetIdTo}${j}${s}`,a=t.split(j).pop(),l=`${e.sheetIdTo}${j}${a}`,c=r.duplicateInDuplicatedSheet(e.sheetIdTo);c&&this.dispatch("CREATE_CHART",{figureId:i,chartId:l,col:o.col,row:o.row,offset:o.offset,size:{width:o.width,height:o.height},definition:c.getDefinition(),sheetId:e.sheetIdTo})}break;case"DELETE_FIGURE":for(const t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch("DELETE_CHART",{chartId:t,sheetId:e.sheetId});break;case"DELETE_CHART":this.isChartDefined(e.chartId)&&this.history.update("charts",e.chartId,void 0);break;case"DELETE_SHEET":for(const t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw new Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){const t=this.charts[e]?.chart.type;if(!t)throw new Error("Chart not defined.");return t}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){const t=this.charts[e]?.chart.getDefinition();if(!t)throw new Error(`There is no chart with the given id: ${e}`);return t}import(e){for(const t of e.sheets)if(t.figures)for(const e of t.figures)if("chart"===e.tag){const r=e.data.chartId,n=this.createChart(e.id,e.data,t.id);this.charts[r]={chart:n,figureId:e.id}}else if("carousel"===e.tag)for(const r in e.data.chartDefinitions||{}){const n=e.data.chartDefinitions[r],o=this.createChart(e.id,n,t.id);this.charts[r]={chart:o,figureId:e.id}}}export(e){if(e.sheets)for(const t of e.sheets){const e=this.getters.getFigures(t.id),r=[];for(const t of e){const e=t,n=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&"chart"===e.tag&&n){const t=this.charts[n]?.chart.getDefinition();t&&(e.data={...t,chartId:n},r.push(e))}else if(e&&"carousel"===e.tag){const n=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),o={};for(const e of n)o[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:o},r.push(e)}else r.push(e)}t.figures=r}}addFigure(e,t,r,n,o,s={width:536,height:335}){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:r,row:n,offset:o,size:s,tag:"chart"})}addChart(e,t,r){const n=this.getters.getFigureSheetId(e);if(n){const o=this.createChart(e,r,n);this.history.update("charts",t,{figureId:e,chart:o})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?"DuplicatedChartId":"Success"}checkChartExists(e){return this.isChartDefined(e.chartId)?"Success":"ChartDoesNotExist"}checkChartChanged(e){return e.figureId!==this.charts[e.chartId]?.figureId?"Success":Ae(this.getChartDefinition(e.chartId),e.definition)?"NoChanges":"Success"}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||void 0!==e.offset&&void 0!==e.col&&void 0!==e.row?"Success":"MissingFigureArguments"}}).add("carousel",class extends gE{static getters=["getCarousel","doesCarouselExist"];carousels={};allowDispatch(e){switch(e.type){case"CREATE_CAROUSEL":return this.getters.getFigure(e.sheetId,e.figureId)?"DuplicatedFigureId":"Success";case"UPDATE_CAROUSEL":return this.carousels[e.sheetId]?.[e.figureId]?"Success":"InvalidFigureId"}return"Success"}handle(e){switch(e.type){case"CREATE_CAROUSEL":this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch("CREATE_FIGURE",{...e,tag:"carousel"}),this.history.update("carousels",e.sheetId,e.figureId,e.definition);break;case"UPDATE_CAROUSEL":this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update("carousels",e.sheetId,e.figureId,e.definition);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const r of t)if("carousel"===r.tag){const t=r.id.split(j).pop(),n=`${e.sheetIdTo}${j}${t}`,o=this.getCarousel(r.id);if(o){const t={width:r.width,height:r.height};this.dispatch("CREATE_CAROUSEL",{sheetId:e.sheetIdTo,figureId:n,offset:r.offset,col:r.col,row:r.row,size:t,definition:{items:o.items.map(t=>{if("carouselDataView"===t.type)return{...t};const r=t.chartId.split(j).pop(),n=`${e.sheetIdTo}${j}${r}`;return{...t,chartId:n}})}})}}break}case"DELETE_FIGURE":this.history.update("carousels",e.sheetId,e.figureId,void 0);break;case"DELETE_SHEET":this.history.update("carousels",e.sheetId,void 0)}}doesCarouselExist(e){for(const t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(const t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw new Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){const r=new Set(e.definition.items.filter(e=>"chart"===e.type).map(e=>e.chartId));for(const n of t)"chart"!==n.type||r.has(n.chartId)||this.dispatch("DELETE_CHART",{chartId:n.chartId,sheetId:e.sheetId})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter(e=>"carousel"===e.tag);for(const r of e)this.history.update("carousels",t.id,r.id,{items:r.data.items,title:r.data.title})}}export(e){for(const t of e.sheets){const e=t.figures.filter(e=>"carousel"===e.tag);for(const r of e)this.carousels[t.id]?.[r.id]&&(r.data={...r.data,...this.carousels[t.id]?.[r.id]})}}}).add("image",class extends gE{static getters=["getImage","getImagePath","getImageSize"];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?"InvalidFigureId":"Success"}handle(e){switch(e.type){case"CREATE_IMAGE":this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const r of t)if("image"===r.tag){const t=r.id.split(j).pop(),n=`${e.sheetIdTo}${j}${t}`,o=this.getImage(r.id);if(o){const t={width:r.width,height:r.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:n,offset:r.offset,col:r.col,row:r.row,size:t,definition:re(o)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.figureId,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,r,n,o,s){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:r,row:n,offset:o,size:s,tag:"image"})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter(e=>"image"===e.tag);for(const r of e)this.history.update("images",t.id,r.id,r.data),this.syncedImages.add(r.data.path)}}export(e){for(const t of e.sheets){const e=t.figures.filter(e=>"image"===e.tag);for(const r of e)r.data=this.images[t.id]?.[r.id]}}exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),r=[];for(const t of e)if("image"===t?.tag){const e=this.getImage(t.id);e&&r.push({...t,data:re(e)})}t.images=[...t.images,...r]}}}).add("pivot_core",class extends gE{static getters=["getPivotCoreDefinition","getPivotDisplayName","getPivotId","getPivotFormulaId","getPivotIds","getMeasureCompiledFormula","getPivotName","isExistingPivot"];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case"ADD_PIVOT":return this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case"UPDATE_PIVOT":return e.pivotId in this.pivots?Ae(e.pivot,this.pivots[e.pivotId]?.definition)?"NoChanges":""===e.pivot.name?"EmptyName":this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):"PivotIdNotFound";case"RENAME_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound";if(""===e.name)return"EmptyName";break;case"REMOVE_PIVOT":case"DUPLICATE_PIVOT":case"INSERT_PIVOT":case"DUPLICATE_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound"}return"Success"}handle(e){switch(e.type){case"ADD_PIVOT":{const{pivotId:t,pivot:r}=e;this.addPivot(t,r);break}case"INSERT_PIVOT":{const{sheetId:t,col:r,row:n,pivotId:o,table:s}=e,i={sheetId:t,col:r,row:n},{cols:a,rows:l,measures:c,fieldsType:u}=s,h=new HE(a,l,c,u||{}),d=this.getPivotFormulaId(o);this.insertPivot(i,d,h);break}case"RENAME_PIVOT":this.history.update("pivots",e.pivotId,"definition","name",e.name);break;case"REMOVE_PIVOT":{const t={...this.pivots};delete t[e.pivotId];const r=this.getPivotFormulaId(e.pivotId);this.history.update("formulaIds",r,void 0),this.history.update("pivots",t);break}case"DUPLICATE_PIVOT":{const{pivotId:t,newPivotId:r}=e,n=re(this.getPivotCore(t).definition);n.name=e.duplicatedPivotName??n.name+" (copy)",this.addPivot(r,n);break}case"UPDATE_PIVOT":this.history.update("pivots",e.pivotId,"definition",re(e.pivot)),this.compileCalculatedMeasures(e.pivot.measures)}}adaptRanges(e){for(const t in this.compiledMeasureFormulas)for(const r in this.compiledMeasureFormulas[t]){const n=this.compiledMeasureFormulas[t][r],o=[];for(const t of n.dependencies){const r=e(t);"NONE"===r.changeType?o.push(t):o.push(r.range)}const s=this.getters.getFormulaString(t,n.tokens,o);s!==r&&this.replaceMeasureFormula(t,r,s)}}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){if(!e.computedBy)throw new Error(`Measure ${e.fieldName} is not computed by formula`);const t=e.computedBy.sheetId;return this.compiledMeasureFormulas[t][e.computedBy.formula]}addPivot(e,t,r=this.nextFormulaId.toString()){this.history.update("pivots",e,{definition:re(t),formulaId:r}),this.compileCalculatedMeasures(t.measures),this.history.update("formulaIds",r,e),this.history.update("nextFormulaId",this.nextFormulaId+1)}compileCalculatedMeasures(e){for(const t of e)if(t.computedBy){const e=t.computedBy.sheetId,r=this.compileMeasureFormula(t.computedBy.sheetId,t.computedBy.formula);this.history.update("compiledMeasureFormulas",e,t.computedBy.formula,r)}}insertPivot(e,t,r){this.resizeSheet(e.sheetId,e,r);const n=r.getPivotCells();for(let r=0;r<n.length;r++)for(let o=0;o<n[r].length;o++){const s=n[r][o];this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col+r,row:e.row+o,content:kd(t,s)})}}resizeSheet(e,{col:t,row:r},n){const o=n.getNumberOfDataColumns()+1,s=this.getters.getNumberCols(e),i=s-t;i<o&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:s-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o-i,position:"after"});const a=n.columns.length+n.rows.length,l=this.getters.getNumberRows(e),c=l-r;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}getPivotCore(e){const t=this.pivots[e];if(!t)throw new Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){const r=gm(t),n=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...r,dependencies:n}}replaceMeasureFormula(e,t,r){this.history.update("compiledMeasureFormulas",e,t,void 0),this.history.update("compiledMeasureFormulas",e,r,this.compileMeasureFormula(e,r));for(const n in this.pivots){const o=this.pivots[n];if(o)for(const s of o.definition.measures)if(s.computedBy?.formula===t){const t=o.definition.measures.indexOf(s);this.history.update("pivots",n,"definition","measures",t,"computedBy",{formula:r,sheetId:e})}}}checkSortedColumnInMeasures(e){const t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?"InvalidDefinition":"Success"}checkDuplicatedMeasureIds(e){const t=new Set(e.measures.map(e=>e.id));return e.measures.length!==t.size?"InvalidDefinition":"Success"}checkCustomFieldsAreValid(e){for(const t in e.customFields){const r=e.customFields[t],n=new Set,o=new Set;let s=!1;for(const e of r.groups){if(!e.name||o.has(e.name))return"InvalidPivotCustomField";if(e.values.some(e=>n.has(e)))return"InvalidPivotCustomField";if(e.isOtherGroup&&s)return"InvalidPivotCustomField";e.values.forEach(e=>n.add(e)),o.add(e.name),s||=!!e.isOtherGroup}}return"Success"}import(e){if(e.pivots)for(const[t,r]of Object.entries(e.pivots))this.addPivot(t,r,r.formulaId);this.history.update("nextFormulaId",e.pivotNextId||Md(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 gE{allowDispatch(e){switch(e.type){case"ADD_PIVOT":case"UPDATE_PIVOT":const t=e.pivot;return this.checkDataSetValidity(t)}return"Success"}adaptRanges(e){for(const t of this.getters.getPivotIds()){const r=this.getters.getPivotCoreDefinition(t);if("SPREADSHEET"===r.type&&r.dataSet){const{sheetId:n,zone:o}=r.dataSet,s=zE(this.getters.getRangeFromZone(n,o),e),i=s&&{sheetId:s.sheetId,zone:s.zone};this.dispatch("UPDATE_PIVOT",{pivotId:t,pivot:{...r,dataSet:i}})}}}checkDataSetValidity(e){if("SPREADSHEET"===e.type&&e.dataSet){const{zone:t,sheetId:r}=e.dataSet;return r&&this.getters.tryGetSheet(r)&&t&&zo(t)?this.getters.checkZonesExistInSheet(r,[t]):"InvalidDataSet"}return"Success"}}).add("tableStyle",class extends gE{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(!Bp[e.templateName])return"InvalidTableStyle";try{Qm(e.primaryColor)}catch(e){return"InvalidTableStyle"}}return"Success"}handle(e){switch(e.type){case"CREATE_TABLE_STYLE":const t=zp(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:Tp.styleId}})}}getTableStyle(e){if(!this.styles[e])throw new Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Xe(v("Custom Table Style"),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!Hp[e]}import(e){for(const e in Hp)this.styles[e]=Hp[e];for(const t in e.customTableStyles){const r=e.customTableStyles[t];this.styles[t]=zp(r.displayName,r.templateName,r.primaryColor)}}export(e){const t={};for(const e in this.styles)Hp[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}}),yT=(new h).add("ui_sheet",class extends Is{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getContiguousZone","computeTextYCoordinate"];ctx=HS();allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(const t of e.cols){const r=this.getColMaxWidth(e.sheetId,t);0!==r&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:r,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":this.autoResizeRows(e.sheetId,e.rows);break;case"DELETE_UNFILTERED_CONTENT":const t=[];for(const r of e.target){const n=ce(le(r.top,r.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(const e of n)t.push({...r,top:e[0],bottom:e[e.length-1]})}this.dispatch("DELETE_CONTENT",{sheetId:e.sheetId,target:t})}}getCellWidth(e){const t=this.getters.getCellComputedStyle(e);let r=0;const n=this.getters.getEvaluatedCell(e).formattedValue;if(n){const e=KS(this.ctx,n,t,void 0);r+=Math.max(...e.map(e=>GS(this.ctx,e,t)))}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 GS(this.ctx,e,t)}getCellText(e,t){const r=this.getters.getCell(e),n=this.getters.getLocale();if(t?.showFormula&&r?.isFormula)return Jl(r.content,n);if(t?.showFormula&&!r?.content)return"";{const o=this.getters.getEvaluatedCell(e),s=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>GS(this.ctx,e,r?.style||{})}:void 0;return Fn(o.value,{format:o.format,locale:n,formatWidth:s})}}getCellMultiLineText(e,t){const r=this.getters.getCellStyle(e),n=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return KS(this.ctx,n,r,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,r=W,n=1){const o=e.y+1,s=US(t,n);if(e.height>s+8){if("middle"===r)return Math.ceil(o+(e.height-s)/2);if("bottom"===r)return o+e.height-s-4}return o+4}getContiguousZone(e,t){const r=t=>{for(const r of le(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:r,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:r,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(const r of le(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:r}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:r}))return{...t,right:t.right+1}}return t};let n=!1,o=t;do{n=!1;const e=r(o);jo(o,e)||(n=!0,o=e)}while(n);return o}isCellEmpty(e){const t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===Eu.empty}getColMaxWidth(e,t){const r=rs(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,We(r))}checkSheetExists(e){return"sheetId"in e&&void 0===this.getters.tryGetSheet(e.sheetId)?"InvalidSheetId":"Success"}checkZonesAreInSheet(e){const t="sheetId"in e?e.sheetId:this.getters.tryGetActiveSheetId();if("ranges"in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return"InvalidSheetId";const r=this.getters.getCommandZones(e);return!t&&r.length>0?"NoActiveSheet":t&&r.length>0?this.getters.checkZonesExistInSheet(t,r):"Success"}autoResizeRows(e,t){const r=[];for(const n of t){let t=0;for(const r of this.getters.getRowCells(e,n)){const n=this.getters.getCellById(r);if(!n)continue;const o=this.getters.getCellPosition(n.id),s=this.getters.getColSize(e,o.col);if(n.isFormula||this.getters.getArrayFormulaSpreadingOn(o)){const e=this.getters.getEvaluatedCell(o).formattedValue,r=BS(this.ctx,e,n?.style,s);r>t&&r>$&&(t=r)}else{const e=n.content,r=BS(this.ctx,e,n?.style,s);r>=t&&r>$&&(t=0)}}r.push(t||null)}const n=new Map(r.map(e=>[e,[]]));for(let e=0;e<r.length;e++)n.get(r[e])?.push(t[e]);for(const[t,r]of n)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:r,dimension:"ROW",size:t,sheetId:e})}}).add("ui_options",class extends Is{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 Is{static layers=["Autofill"];static getters=["getAutofillTooltip"];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){if("AUTOFILL_SELECT"===e.type){const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:ae(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:ae(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?"Success":"InvalidAutofillSelection"}return"Success"}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto()}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),r=this.autofillZone,n=[];switch(this.direction){case"down":for(let e=t.left;e<=t.right;e++){const o=[];for(let r=t.top;r<=t.bottom;r++)o.push(Do(e,r));const s=this.createGenerator(o);for(let t=r.top;t<=r.bottom;t++)n.push(this.computeNewCell(s,e,t))}break;case"up":for(let e=t.left;e<=t.right;e++){const o=[];for(let r=t.bottom;r>=t.top;r--)o.push(Do(e,r));const s=this.createGenerator(o);for(let t=r.bottom;t>=r.top;t--)n.push(this.computeNewCell(s,e,t))}break;case"left":for(let e=t.top;e<=t.bottom;e++){const o=[];for(let r=t.right;r>=t.left;r--)o.push(Do(r,e));const s=this.createGenerator(o);for(let t=r.right;t>=r.left;t--)n.push(this.computeNewCell(s,t,e))}break;case"right":for(let e=t.top;e<=t.bottom;e++){const o=[];for(let r=t.left;r<=t.right;r++)o.push(Do(r,e));const s=this.createGenerator(o);for(let t=r.left;t<=r.right;t++)n.push(this.computeNewCell(s,t,e))}}if(e){const e={},t={},r={},o=this.getters.getActiveSheetId();for(const s of n)this.collectBordersData(s,e),this.autofillMerge(o,s),this.autofillCell(o,s),this.collectConditionalFormatsData(o,s,t),this.collectDataValidationsData(o,s,r);this.autofillBorders(o,e),this.autofillConditionalFormats(o,t),this.autofillDataValidations(o,r),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){const r=JSON.stringify(e.border);r in t||(t[r]=[]),t[r].push(ss({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,r){const{originCol:n,originRow:o,col:s,row:i}=t,a=this.getters.getRulesByCell(e,n,o),l=Do(s,i);for(const e of a)e.id in r||(r[e.id]=[]),r[e.id].push(l)}collectDataValidationsData(e,t,r){const{originCol:n,originRow:o,col:s,row:i}=t,a={sheetId:e,col:n,row:o},l=this.getters.getValidationRuleForCell(a);l&&(l.id in r||(r[l.id]=[]),r[l.id].push(ss({col:s,row:i})))}autofillCell(e,t){this.dispatch("UPDATE_CELL",{sheetId:e,col:t.col,row:t.row,content:t.content||"",style:t.style||null,format:t.format||""}),this.dispatch("AUTOFILL_CELL",t)}autofillBorders(e,t){for(const r in t){const n="undefined"===r?void 0:JSON.parse(r);this.dispatch("SET_BORDERS_ON_TARGET",{sheetId:e,border:n,target:Fo(t[r])})}}autofillConditionalFormats(e,t){for(const r in t){const n=t[r],o=this.getters.getConditionalFormats(e).find(e=>e.id===r);if(!o)continue;const s=this.getters.getAdaptedCfRanges(e,o,n.map(Bo),[]);s&&this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:o.id,rule:o.rule,stopIfTrue:o.stopIfTrue},ranges:s,sheetId:e})}}autofillDataValidations(e,t){for(const r in t){const n=t[r],o=this.getters.getDataValidationRule(e,r);if(!o)continue;const s=o.ranges.map(e=>e.zone),i=Fo(s.concat(n),[]);this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:o,ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){const r=this.getters.getSelectedZone();if(Qo(e,t,r))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,r.top-1,r.left,r.right),this.steps=r.top-t;break;case"down":this.saveZone(r.bottom+1,t,r.left,r.right),this.steps=t-r.bottom;break;case"left":this.saveZone(r.top,r.bottom,e,r.left-1),this.steps=r.left-e;break;case"right":this.saveZone(r.top,r.bottom,r.right+1,e),this.steps=e-r.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getActivePosition(),t=this.getters.getTable(e);let r=t?t.range.zone.bottom:this.getAutofillAutoLastRow();const n=this.getters.getSelectedZone();for(let t=n.bottom+1;t<=r;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==Eu.empty){r=t-1;break}r>n.bottom&&(this.select(e.col,r),this.autofill(!0))}getAutofillAutoLastRow(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let r=e.left,n=e.bottom;if(r>0){let e={sheetId:t,col:r-1,row:n};for(;this.getters.getEvaluatedCell(e).type!==Eu.empty;)n+=1,e={sheetId:t,col:r-1,row:n}}if(n===e.bottom&&(r=e.right,r<=this.getters.getNumberCols(t))){let e={sheetId:t,col:r+1,row:n};for(;this.getters.getEvaluatedCell(e).type!==Eu.empty;)n+=1,e={sheetId:t,col:r+1,row:n}}return n-1}computeNewCell(e,t,r){const{cellData:n,tooltip:o,origin:s}=e.next(),{content:i,style:a,border:l,format:c}=n;return this.tooltip=o,{originCol:s.col,originRow:s.row,col:t,row:r,content:i,style:a,border:l,format:c}}getRule(e,t){const r=ZC.getAll().sort((e,t)=>e.sequence-t.sequence).find(r=>r.condition(e,t));return r&&this.direction&&r.generateRule(e,t,this.direction)}createGenerator(e){const t=[],r=[],n=this.getters.getActiveSheetId();for(const t of e){const{col:e,row:o}=Oo(t),s=this.getters.getCell({sheetId:n,col:e,row:o});r.push({col:e,row:o,cell:s,sheetId:n})}const o=r.map(e=>e.cell);for(const e of r){let r={type:"COPY_MODIFIER"};if(e&&e.cell){r=this.getRule(e.cell,o)||r}const n=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:n},rule:r})}return new tT(t,this.getters,this.direction)}saveZone(e,t,r,n){this.autofillZone={top:e,bottom:t,left:r,right:n}}getDirection(e,t){const r=this.getters.getSelectedZone(),n={up:{number:r.top-t,value:"up"},down:{number:t-r.bottom,value:"down"},left:{number:r.left-e,value:"left"},right:{number:e-r.right,value:"right"}};if(1===Object.values(n).map(e=>e.number>0?1:0).reduce((e,t)=>e+t))return Object.values(n).find(e=>e.number>0?1:0).value;const o=n.up.number>0?"up":"down",s=n.left.number>0?"left":"right";return Math.abs(n[o].number)>=Math.abs(n[s].number)?n[o].value:n[s].value}autofillMerge(e,t){const{originCol:r,originRow:n,col:o,row:s}=t,i={sheetId:e,col:o,row:s},a={sheetId:e,col:r,row:n};if(this.getters.isInMerge(i)&&!this.getters.isInMerge(a)){const t=this.getters.getMerge(i);t&&this.dispatch("REMOVE_MERGE",{sheetId:e,target:[t]})}const l=this.getters.getMerge(a);l?.left===r&&l?.top===n&&this.dispatch("ADD_MERGE",{sheetId:e,target:[{top:s,bottom:s+l.bottom-l.top,left:o,right:o+l.right-l.left}]})}drawLayer(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:r}=e,{x:n,y:o,width:s,height:i}=this.getters.getVisibleRect(this.autofillZone);s>0&&i>0&&(t.strokeStyle="black",t.lineWidth=r,t.setLineDash([3]),t.strokeRect(n,o,s,i),t.setLineDash([]))}}).add("sort",class extends Is{allowDispatch(e){return"SORT_CELLS"===e.type?Qo(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 rs(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=>Ko(e,t)),n=es(r[0]),[o,s]=[n.numberOfCols,n.numberOfRows];return r.every(e=>{const[t,r]=[e.right-e.left+1,e.bottom-e.top+1];return t===o&&r===s})?"Success":"InvalidSortZone"}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return rs(t).some(({col:t,row:r})=>{const n=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:r});return n&&!Ae(n,{sheetId:e,col:t,row:r})})?"SortZoneWithArrayFormulas":"Success"}hasHeader(e,t){if(1===t[0].length)return!1;let r=t.map(t=>t.map(({col:t,row:r})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:r}).type));return r[0][0]===Eu.empty&&(r=r.slice(1)),!r.some(e=>e[0]===Eu.empty)&&!!r.some(e=>e[1]!==Eu.empty&&e[0]!==e[1])}sortZone(e,t,r,n,o){const[s,i]=this.mainCellsSteps(e,r),a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},r);let c=this.mainCells(e,r);!o.sortHeaders&&this.hasHeader(e,c)&&(l.top+=i),c=this.mainCells(e,l);const u=function(e,t,r){const n=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(r?n.map(e=>e.type===Eu.empty?{...e,type:Eu.number,value:0}:e):n).sort(Tu(t))}(c[a-l.left].map(e=>this.getters.getEvaluatedCell(e)),n,Boolean(o.emptyCellAsZero)),h=u.map(e=>e.index),[d,f]=[c.length,c[0].length],g=[];for(let e=0;e<d;e++)for(let t=0;t<f;t++){const{col:r,row:n,sheetId:o}=c[e][h[t]],a=this.getters.getCell({sheetId:o,col:r,row:n}),u=l.left+e*s,d=l.top+t*i,f={sheetId:o,col:u,row:d,content:""};if(a){let e=a.content;if(a.isFormula){const t=this.getters.getCellPosition(a.id);e=this.getters.getTranslatedCellFormula(o,0,d-t.row,a.compiledFormula.tokens)}f.style=a.style,f.content=e,f.format=a.format}g.push(f)}g.forEach(e=>this.dispatch("UPDATE_CELL",e))}mainCellsSteps(e,t){const r=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[r?r.right-r.left+1:1,r?r.bottom-r.top+1:1]}mainCells(e,t){const[r,n]=this.mainCellsSteps(e,t),o=[],s=le(t.left,t.right+1,r),i=le(t.top,t.bottom+1,n);for(const t of s){const r=[];o.push(r);for(const n of i)r.push({sheetId:e,col:t,row:n})}return o}}).add("automatic_sum",class extends Is{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:r}=this.getters.getSelection();for(const n of t){const t=this.getAutomaticSums(e,n,r.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,r){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,r):this.sumData(e,t)}sumData(e,t){const r=this.dimensionsToSum(e,t),n=this.sumDimensions(e,t,r).filter(({zone:t})=>!this.getters.isEmpty(e,t));return r.has("ROW")&&r.has("COL")&&n.push(this.sumTotal(t)),n}sumAdjacentData(e,t,r){const{col:n,row:o}=Qo(r.col,r.row,t)?r:{col:t.left,row:t.top},s=this.findAdjacentData(e,n,o);return s?this.getters.isSingleCellOrMerge(e,t)||ts(Zo(s,t))?[{position:{col:n,row:o},zone:s}]:this.sumDimensions(e,Zo(s,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,r){const n=this.getters.getSheet(e),o=this.getters.getMainCellPosition({sheetId:e,col:t,row:r}),s=this.findSuitableZoneToSum(n,o.col,o.row);if(s)return this.getters.expandZone(e,s)}findSuitableZoneToSum(e,t,r){const n=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:r-1}),o=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:r});if(this.isNumber(o)&&!this.isNumber(n))return this.findHorizontalZone(e,t,r);const s=this.findVerticalZone(e,t,r);if(this.isZoneValid(s))return s;const i=this.findHorizontalZone(e,t,r);return this.isZoneValid(i)?i:void 0}findVerticalZone(e,t,r){const n={top:0,bottom:r-1,left:t,right:t},o=this.reduceZoneStart(e,n,n.bottom);return{...n,top:o}}findHorizontalZone(e,t,r){const n={top:r,bottom:r,left:0,right:t-1},o=this.reduceZoneStart(e,n,n.right);return{...n,left:o}}reduceZoneStart(e,t,r){const n=this.getters.getEvaluatedCellsInZone(e.id,t),o=le(r,-1,-1),s=We(o.filter(e=>n[e]&&!n[e].isAutoSummable)),i=ce(o.filter(e=>this.isNumber(n[e])))[0]||[];return We(i)<s?1/0:qe(i)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===Eu.number&&!(e.format&&Hn(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 ts(t)?(r.add(1===es(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)},rs(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)},rs(r).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(const r of t){const{col:t,row:n}=r.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,content:`=SUM(${this.getters.zoneToXC(e,r.zone)})`})}}nextEmptyRow(e,t){let r=t.bottom+1;const{left:n,right:o}=t;for(;!this.getters.isEmpty(e,{bottom:r,top:r,left:n,right:o});)r++;return{...t,top:r,bottom:r}}nextEmptyCol(e,t){let r=t.right+1;const{top:n,bottom:o}=t;for(;!this.getters.isEmpty(e,{left:r,right:r,top:n,bottom:o});)r++;return{...t,left:r,right:r}}transpose(e){return new Set([...e.values()].map(e=>"COL"===e?"ROW":"COL"))}}).add("format",class extends Is{handle(e){switch(e.type){case"SET_DECIMAL":this.setDecimal(e.sheetId,e.target,e.step);break;case"SET_FORMATTING_WITH_PIVOT":this.setContextualFormat(e.sheetId,e.target,e.format)}}setContextualFormat(e,t,r){const n=[],o={};for(const r of Fo(t))for(let t=r.left;t<=r.right;t++)for(let s=r.top;s<=r.bottom;s++){const r={sheetId:e,col:t,row:s},i=this.getters.getPivotCellFromPosition(r);if(this.isSpilledPivotValueFormula(r,i)){n.push(r);const e=this.getters.getPivotIdFromPosition(r)||"";o[e]??=new Set,o[e].add(i.measure)}}const s=Fo(n.map(ss));for(const e in o){const t=o[e],n=this.getters.getPivotCoreDefinition(e);this.dispatch("UPDATE_PIVOT",{pivotId:e,pivot:{...n,measures:n.measures.map(e=>t.has(e.id)?{...e,format:r}:e)}})}this.dispatch("SET_FORMATTING",{sheetId:e,target:s,format:""}),this.dispatch("SET_FORMATTING",{sheetId:e,target:Fo(t,s),format:r})}isSpilledPivotValueFormula(e,t){const r=this.getters.getCell(e);return"VALUE"===t.type&&!r?.isFormula}setDecimal(e,t,r){const n={};for(const o of Fo(t))for(const t of rs(o)){const o=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==o){const e=jn(o,r);n[e]=n[e]||[],n[e].push(t)}}for(const t in n){const r=Fo(n[t].map(e=>ss(e)));this.setContextualFormat(e,r,t)}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==Eu.number||e.format&&Hn(e.format)))return e.format||$n(e.value)}}}).add("insert_pivot",class extends Is{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===cs(this.getters.getSelectedZone())&&this.selection.selectTableAroundSelection();const r=this.getters.getActiveSheetId();this.dispatch("ADD_PIVOT",{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:r},columns:[],rows:[],measures:[],name:v("New pivot"),type:"SPREADSHEET"}});const n=this.getters.getSheetIds().findIndex(e=>e===r)+1,o=this.getters.getPivotFormulaId(e);this.dispatch("CREATE_SHEET",{sheetId:t,name:v("Pivot #%(formulaId)s",{formulaId:o}),position:n}),this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:r,sheetIdTo:t});const s=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,s.getCollapsedTableStructure().export(),"dynamic")}duplicatePivotInNewSheet(e,t,r){this.dispatch("DUPLICATE_PIVOT",{pivotId:e,newPivotId:t,duplicatedPivotName:v("%s (copy)",this.getters.getPivotCoreDefinition(e).name)});const n=this.getters.getActiveSheetId(),o=this.getters.getSheetIds().indexOf(n)+1,s=this.getters.getPivotFormulaId(t),i=this.getters.getPivotName(t);if(this.dispatch("CREATE_SHEET",{sheetId:r,name:this.getPivotDuplicateSheetName(v("%(newPivotName)s (Pivot #%(formulaId)s)",{newPivotName:i,formulaId:s})),position:o}).isSuccessful){this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:n,sheetIdTo:r});const o=this.getters.getPivot(e);this.insertPivotWithTable(r,0,0,t,o.getCollapsedTableStructure().export(),"dynamic")}}getPivotDuplicateSheetName(e){const t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return Xe(ie(e),t)}insertPivotWithTable(e,t,r,n,o,s){const{cols:i,rows:a,measures:l,fieldsType:c}=o,u=new HE(i,a,l,c||{}),h=u.columns.length-1;this.resizeSheet(e,t,r,u);const d=this.getters.getPivotFormulaId(n);let f;"dynamic"===s?(this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:r,content:`=PIVOT(${d})`}),f={left:t,right:t,top:r,bottom:r}):(this.dispatch("INSERT_PIVOT",{sheetId:e,col:t,row:r,pivotId:n,table:u.export()}),f={left:t,right:t+u.getNumberOfDataColumns(),top:r,bottom:r+h+u.rows.length}),this.dispatch("CREATE_TABLE",{tableType:s,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,f)],config:{...J,numberOfHeaders:h}})}resizeSheet(e,t,r,n){const o=n.getNumberOfDataColumns()+1,s=this.getters.getNumberCols(e),i=s-t;i<o&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:s-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o-i,position:"after"});const a=n.columns.length+n.rows.length,l=this.getters.getNumberRows(e),c=l-r;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}splitPivotFormula(e,t,r,n){const o=this.getters.getSpreadZone({sheetId:e,col:t,row:r});if(!o)return;const s=this.getters.getPivotFormulaId(n),i=new Map;for(let t=o.left;t<=o.right;t++)for(let r=o.top;r<=o.bottom;r++){const n={sheetId:e,col:t,row:r};i.set(n,this.getters.getPivotCellFromPosition(n))}for(const[e,t]of i)this.dispatch("UPDATE_CELL",{...e,content:kd(s,t)});const a=this.getters.getCoreTable({sheetId:e,col:t,row:r});if("dynamic"===a?.type){const n=ss({col:t,row:r}),s=this.getters.getRangeDataFromZone(e,o);this.dispatch("UPDATE_TABLE",{sheetId:e,zone:n,newTableRange:s,tableType:"static"})}}}).add("pivot_presence",class extends Is{static getters=["getPivotPresenceTracker"];trackPresencePivotId;tracker;handle(e){switch(e.type){case"PIVOT_START_PRESENCE_TRACKING":this.tracker=new aT,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 Is{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===Eu.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[Q,";",","," ","."];for(const r of t)if(e.includes(r))return r}splitIntoColumns({separator:e,addNewColumns:t}){const r=this.getters.getSelectedZone(),n=this.getters.getActiveSheetId(),o=this.getSplittedCols(r,e);t&&this.addColsToAvoidCollisions(r,o),this.removeMergesInSplitZone(r,o),this.addColumnsToNotOverflowSheet(r,o);for(let e=0;e<o.length;e++){const t=r.top+e,s=o[e],i=r.left,a=this.getters.getCell({sheetId:n,col:i,row:t});if(1!==s.length||s[0]!==a?.content)for(const[e,r]of s.entries())this.dispatch("UPDATE_CELL",{sheetId:n,col:i+e,row:t,content:Kl(r,this.getters.getLocale()),format:"",style:a?.style||null})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const r=this.getters.getActiveSheetId(),n=[];for(const o of le(e.top,e.bottom+1)){const s=this.getters.getEvaluatedCell({sheetId:r,col:e.left,row:o}).formattedValue;n.push(this.splitAndRemoveTrailingEmpty(s,t))}return n}splitAndRemoveTrailingEmpty(e,t){const r=e.split(t);for(;r.length>1&&""===r[r.length-1];)r.pop();return r}willSplittedColsOverwriteContent(e,t){const r=this.getters.getActiveSheetId();for(const n of le(e.top,e.bottom+1)){const o=t[n-e.top];for(let t=1;t<o.length;t++){const o=this.getters.getCell({sheetId:r,col:e.left+t,row:n});if(o&&o.content)return!0}}return!1}removeMergesInSplitZone(e,t){const r=this.getters.getActiveSheetId(),n=Math.max(...t.map(e=>e.length)),o={...e,right:e.left+n-1},s=this.getters.getMergesInZone(r,o);this.dispatch("REMOVE_MERGE",{sheetId:r,target:s})}addColsToAvoidCollisions(e,t){const r=this.getters.getActiveSheetId();let n=0;for(const o of le(e.top,e.bottom+1)){const s={sheetId:r,col:e.left,row:o},i=t[o-e.top],a=this.getColsToAddToAvoidCollision(s,i);n=Math.max(n,a)}n&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:r,sheetName:this.getters.getSheetName(r),quantity:n,position:"after"})}getColsToAddToAvoidCollision(e,t){const r=t.length;for(let t=1;t<r;t++){const n=e.col+t,o=this.getters.getCell({...e,col:n});if(o&&o.content)return r-t}return 0}addColumnsToNotOverflowSheet(e,t){const r=this.getters.getActiveSheetId(),n=Math.max(...t.map(e=>e.length-1)),o=this.getters.getNumberCols(r)-1;e.left+n>o&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:o,sheetId:r,sheetName:this.getters.getSheetName(r),quantity:e.left+n-o,position:"after"})}checkSingleColSelected(){return this.getters.isSingleColSelected()?"Success":"MoreThanOneColumnSelected"}checkNonEmptySelector(e){return""===e.separator?"EmptySplitSeparator":"Success"}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return"Success";const t=this.getters.getSelectedZones()[0],r=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,r)?"SplitWillOverwriteContent":"Success"}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const r of t)if(r.formattedValue.includes(e))return"Success";return"NoSplitSeparatorInSelection"}}).add("subtotal_evaluation",class extends Is{subtotalCells=new Set;handle(e){switch(e.type){case"START":this.subtotalCells.clear();for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t){const r=t[e];xs(r)&&this.subtotalCells.add(r.id)}}break;case"UPDATE_CELL":{if(!("content"in e))return;const t=this.getters.getCell(e);if(!t)return;xs(t)?this.subtotalCells.add(t.id):this.subtotalCells.delete(t.id);break}}bs.has(e.type)&&this.dispatch("EVALUATE_CELLS",{cellIds:Array.from(this.subtotalCells)})}}).add("collaborative",class extends Is{static getters=["getClientsToDisplay","getClient","getCurrentClient","getConnectedClients","isFullySynchronized"];static layers=["Selection"];colors=new Ep(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 $b)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const r of this.getters.getConnectedClients())r.id!==this.getters.getCurrentClient().id&&r.position&&r.position.sheetId===e&&this.isPositionValid(r.position)&&t.push({...r,position:r.position});return t}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:r}=e,n=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:o,col:s}=e.position,i=this.getters.expandZone(n,{top:o,bottom:o,left:s,right:s}),{x:a,y:l,width:c,height:u}=this.getters.getVisibleRect(i);if(c<=0||u<=0)continue;const h=e.color;t.fillStyle=`${h}10`,t.lineWidth=4*r,t.strokeStyle=h,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,u),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,u),t.font=`bold ${q+1}px ${Z}`}}}).add("history",class extends Is{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=iT(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)&&(ws(t.rootCommand)?oT.contains(t.rootCommand.type):sT.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 Is{handle(e){if("AUTOFILL_TABLE_COLUMN"===e.type){const t=this.getters.getCoreTable(e),r=this.getters.getCell(e);if(!t?.config.automaticAutofill||"dynamic"===t.type||!r?.isFormula)return;const{col:n,row:o}=e,s=function(e,t){const r=t.numberOfHeaders,n={...e,top:e.top+r};return n.top<=n.bottom?n:void 0}(t.range.zone,t.config);if(s&&Qo(n,o,s)){const t=e.autofillRowStart??s.top,r=e.autofillRowEnd??s.bottom,n={...s,top:t,bottom:r};this.autofillTableZone(e,n)}}}autofillTableZone(e,t){if(t.top===t.bottom)return;const{col:r,row:n,sheetId:o}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==n&&this.getters.getEvaluatedCell({col:r,row:e,sheetId:o}).type!==Eu.empty)return;const s={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(r,n),this.dispatch("AUTOFILL_SELECT",{col:r,row:t.bottom}),this.dispatch("AUTOFILL"),this.selection.selectCell(r,n),this.dispatch("AUTOFILL_SELECT",{col:r,row:t.top}),this.dispatch("AUTOFILL"),this.selection.selectZone(s)}}).add("table_ui_resize",class extends Is{allowDispatch(e){if("RESIZE_TABLE"===e.type){const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return"TableNotFound";const r=t.range.zone,n=this.getters.getRangeFromRangeData(e.newTableRange).zone;return n.top!==r.top||n.left!==r.left?"InvalidTableResize":this.canDispatch("UPDATE_TABLE",{...e}).reasons}return"Success"}handle(e){switch(e.type){case"RESIZE_TABLE":{const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch("UPDATE_TABLE",{...e}),!t)return;const r=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(r.right,r.bottom),!t.config.automaticAutofill)return;const n=t.range.zone;if(r.bottom>=n.bottom){for(let t=r.left;t<=r.right;t++){const o={col:t,row:n.bottom,sheetId:e.sheetId};this.getters.getCell(o)?.content.startsWith("=")&&this.dispatch("AUTOFILL_TABLE_COLUMN",{...o,autofillRowStart:n.bottom,autofillRowEnd:r.bottom})}break}}}}}).add("datavalidation_insert",class extends Is{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 Nm(t)){const t=this.getters.getCell(e),r=this.getters.getEvaluatedCell(e);if(t?.content)if(t?.content&&r.type===Eu.empty){let r;if(t.content.startsWith("=")){const n=this.getters.evaluateFormula(e.sheetId,t.content);r=(O(n)?n[0][0]:n)?.toString()}else r=t.content;r&&he(r)||this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}else r.type!==Eu.boolean&&this.dispatch("UPDATE_CELL",{...e,content:"FALSE"});else this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}}}}).add("checkbox_toggle",class extends Is{static getters=["hasBooleanValidationInZones"];handle(e){if("TOGGLE_CHECKBOX"===e.type)this.toggleCheckbox(e.sheetId,e.target)}hasBooleanValidationInZones(e){const t=this.getters.getActiveSheetId();for(const r of e)for(let e=r.left;e<=r.right;e++)for(let n=r.top;n<=r.bottom;n++)if(this.getters.isCellValidCheckbox({col:e,row:n,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(const r of t)for(let t=r.left;t<=r.right;t++)for(let n=r.top;n<=r.bottom;n++){const r={col:t,row:n,sheetId:e};if(this.getters.isCellValidCheckbox(r)){const e=this.getters.getEvaluatedCell(r).value?"FALSE":"TRUE";this.dispatch("UPDATE_CELL",{...r,content:e})}}}}).add("dynamic_translate",class extends Is{static getters=["dynamicTranslate"];dynamicTranslate(e){return e}}).add("geo_features",class extends Is{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")}}),wT=(new h).add("selection",class extends Is{static layers=["Selection"];static getters=["getActiveSheet","getActiveSheetId","getActiveSheetName","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId","isGridSelectionActive","getSelectecUnboundedZone"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;isUnbounded;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient,this.isUnbounded=!1}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return"SheetIsHidden";break}catch(e){return"InvalidSheetId"}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return"Success"}handleEvent(e){const t=e.anchor;let r=[];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case"overrideSelection":r=[t.zone];break;case"updateAnchor":r=[...this.gridSelection.zones];const n=r.findIndex(t=>jo(t,e.previousAnchor.zone));n>=0&&(r[n]=t.zone);break;case"newAnchor":r=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,r),this.selection.resetDefaultAnchor(this,re(this.gridSelection.anchor));const{col:n,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:n,row:o}),this.selectedFigureId=null}handle(e){switch(e.type){case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.figureId&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);const{col:r,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(r,n),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:r,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:r,row:n})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:r,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:r,row:n})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.figureId;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const o=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(const e of o)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:re(t)}}this.fallbackToVisibleSheet();const s=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(s,e)),this.gridSelection.anchor.zone=this.getters.expandZone(s,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,re(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveSheetName(){return this.activeSheet.name}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(const t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let r=t.left;r<=t.right;r++)e.add(r);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(const r of this.gridSelection.zones)if(0===r.left&&r.right===this.getters.getNumberCols(t)-1)for(let t=r.top;t<=r.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return re(this.gridSelection.zones)}getSelectedZone(){return re(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return re(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return re(this.gridSelection)}getSelectedCells(){const e=this.getters.getActiveSheetId(),t=[];for(const r of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,r));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){const e=this.getters.getSelectedZones();return 1===e.length&&e[0].left===e[0].right}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let r=[];const n="COL"===e?"left":"top",o="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[o]-e[n]+1},(t,r)=>e[n]+r);r=r.concat(t)}return[...new Set(r)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:re(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,re(this.gridSelection.anchor));else{const{col:e,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,r)}const{col:r,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:r,row:n})}setSelectionMixin(e,t){const{anchor:r,zones:n}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=r,this.gridSelection.zones=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()}(n)}selectCell(e,t){const r=this.getters.getActiveSheetId(),n=this.getters.expandZone(r,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:n,cell:{col:e,row:t}},[n])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){const t=this.getters.getSheetIds(),r=(t.findIndex(e=>e===this.activeSheet.id)+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[r]})}onColumnsRemoved(e){const{cell:t,zone:r}=this.gridSelection.anchor,n=qo(r,"left",[...e.elements]);let o={left:t.col,right:t.col,top:t.row,bottom:t.row};o=qo(o,"left",[...e.elements]);const s={cell:{col:o.left,row:o.top},zone:n},i=this.gridSelection.zones.map(t=>qo(t,"left",[...e.elements]));this.setSelectionMixin(s,i)}onRowsRemoved(e){const{cell:t,zone:r}=this.gridSelection.anchor,n=qo(r,"top",[...e.elements]);let o={left:t.col,right:t.col,top:t.row,bottom:t.row};o=qo(o,"top",[...e.elements]);const s={cell:{col:o.left,row:o.top},zone:n},i=this.gridSelection.zones.map(t=>qo(t,"top",[...e.elements]));this.setSelectionMixin(s,i)}onAddElements(e){const t="COL"===e.dimension?"left":"top",r=Wo(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),n=this.gridSelection.zones.map(r=>Wo(r,t,e.base,e.position,e.quantity)),o={cell:{col:r.left,row:r.top},zone:r};this.setSelectionMixin(o,n)}onMoveElements(e){const t=e.elements.length,r=this.getFiguresUpdates(e);this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,base:e.base,quantity:t,position:e.position});const n="COL"===e.dimension,o=e.elements[0],s=e.elements[t-1],i=e.base<o,a=i&&n?t:0,l=i&&!n?t:0,c=i?e.elements.map(e=>e+t):e.elements,u={};for(const t of c)u[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);const h=[{left:n?o+a:0,right:n?s+a:this.getters.getNumberCols(e.sheetId)-1,top:n?0:o+l,bottom:n?this.getters.getNumberRows(e.sheetId)-1:s+l}],d=this.getActiveSheetId(),f=i?e.base:e.base+1,g=[{left:n?f:0,right:n?f+t-1:this.getters.getNumberCols(e.sheetId)-1,top:n?0:f,bottom:n?this.getters.getNumberRows(e.sheetId)-1:f+t-1}],m=fT.cellHandlers.getKeys().map(e=>[e,new(fT.cellHandlers.get(e))(this.getters,this.dispatch)]),p={};for(const[e,t]of m)p[e]=t.copy(dT(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={},n=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)r[e.elements[t]]=n+t;for(const n of this.getters.getFigures(e.sheetId))"COL"===e.dimension&&n.col in r&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:n.id,col:r[n.col],row:n.row}),"ROW"===e.dimension&&n.row in r&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:n.id,row:r[n.row],col:n.col});return t}applyFigureUpdates(e){for(const t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){const t="COL"===e.dimension,r=e.elements[0],n=e.elements[e.elements.length-1],o=e.sheetId,s=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(s(o,r-1,r)||s(o,n,n+1)||s(o,e.base-1,e.base))return"WillRemoveExistingMerge";const i=[e.base,...e.elements],a=t?this.getters.getNumberCols(o):this.getters.getNumberRows(o);return i.some(e=>e<0||e>=a)?"InvalidHeaderIndex":t||this.isTableRowMoveAllowed(o,e.elements)?"Success":"CannotMoveTableHeader"}isTableRowMoveAllowed(e,t){const r=this.getters.getCoreTables(e);if(0===r.length)return!0;const n=new Set(t);return r.every(({range:{zone:e},config:r})=>{const{top:o,bottom:s}=e;if(0===r.numberOfHeaders)return!0;const i=o+r.numberOfHeaders-1;if(!t.some(e=>e>=o&&e<=i))return!0;return le(o,s+1).every(e=>n.has(e))})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:r})}}clipSelection(e,t){const r=this.getters.getNumberCols(e)-1,n=this.getters.getNumberRows(e)-1;return{zones:t.zones.map(e=>({left:ae(e.left,0,r),right:ae(e.right,0,r),top:ae(e.top,0,n),bottom:ae(e.bottom,0,n)})),anchor:{cell:{col:ae(t.anchor.cell.col,0,r),row:ae(t.anchor.cell.row,0,n)},zone:{left:ae(t.anchor.zone.left,0,r),right:ae(t.anchor.zone.right,0,r),top:ae(t.anchor.zone.top,0,n),bottom:ae(t.anchor.zone.bottom,0,n)}}}}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:r}=e,n=this.getSelectedZones();t.fillStyle="#f3f7fe";const o=1===n.length&&n[0].left===n[0].right&&n[0].top===n[0].bottom;t.fillStyle=o?"#f3f7fe":"#e9f0ff",t.strokeStyle=N,t.lineWidth=1.5*r;for(const e of n){const{x:r,y:n,width:o,height:s}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(r,n,o,s),t.globalCompositeOperation="source-over",t.strokeRect(r,n,o,s)}t.globalCompositeOperation="source-over";const s=this.getActivePosition();let i;t.strokeStyle=N,t.lineWidth=3*r,i=this.getters.isInMerge(s)?this.getters.getMerge(s):ss(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 Is{static getters=["getFilterValue","getFilterHiddenValues","getFilterCriterionValue","getFirstTableInSelection","isRowFiltered","isFilterActive"];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return"FilterNotFound";return"Success"}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_TABLE":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":case"UPDATE_TABLE":this.isEvaluationDirty=!0;break;case"START":for(const e of this.getters.getSheetIds())this.filterValues[e]={};break;case"CREATE_SHEET":this.filterValues[e.sheetId]={};break;case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"GROUP_HEADERS":case"UNGROUP_HEADERS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_ALL_HEADER_GROUPS":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":this.updateHiddenRows(e.sheetId);break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case"DUPLICATE_SHEET":this.filterValues[e.sheetIdTo]=re(this.filterValues[e.sheetId])}}finalize(){if(this.isEvaluationDirty){for(const e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){const t=this.getters.getFilterId(e),r=e.sheetId;return t?this.filterValues[r]?.[t]:void 0}getFilterHiddenValues(e){const t=this.getters.getFilterId(e),r=e.sheetId;if(!t||!this.filterValues[r])return[];const n=this.filterValues[r][t]||[];return"values"===n.filterType?n.hiddenValues:[]}getFilterCriterionValue(e){const t=this.getters.getFilterId(e),r=e.sheetId;if(!t||!this.filterValues[r])return mT;const n=this.filterValues[r][t];return n&&"criterion"===n.filterType?n:mT}isFilterActive(e){const t=this.getters.getFilterId(e);if(!t)return!1;const r=e.sheetId,n=this.filterValues[r]?.[t];return!!n&&("values"===n.filterType?n.hiddenValues.length>0:"none"!==n.type)}getFirstTableInSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:r,sheetId:n}){const o=this.getters.getFilterId({sheetId:n,col:e,row:t});o&&(this.filterValues[n]||(this.filterValues[n]={}),this.filterValues[n][o]=r)}updateHiddenRows(e){const t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),r=new Set;for(const n of t){const t=this.filterValues[e]?.[n.id],o=n.filteredRange?.zone;if(t&&o&&!r.has(n.rangeWithHeaders.zone.top)&&!this.getters.isRowHiddenByUser(e,n.rangeWithHeaders.zone.top))if("values"===t.filterType){const s=t.hiddenValues?.map(QS);if(!s)continue;const i=new Set(s);for(let t=o.top;t<=o.bottom;t++){const o=this.getCellValueAsString(e,n.col,t);i.has(o)&&r.add(t)}}else{if("none"===t.type)continue;const s=bE.get(t.type),i=t.values.map(t=>t.startsWith("=")?this.getters.evaluateFormula(e,t)??"":Wy(t,Dl));if(i.some(Pr))continue;const a={type:t.type,values:i.map(Vr),dateValue:t.dateValue};for(let t=o.top;t<=o.bottom;t++){const o={sheetId:e,col:n.col,row:t},i=this.getters.getEvaluatedCell(o).value??"";s.isValueValid(i,a,this.getters,e)||r.add(t)}}}this.hiddenRows[e]=r}getCellValueAsString(e,t,r){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:r}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const r of t.tables){const n=Bo(r.range),o=[],s=[];for(const r of le(0,es(n).numberOfCols)){const i={sheetId:t.id,col:n.left+r,row:n.top},a=this.getFilterHiddenValues(i),l=this.getters.getFilter(i),c=l?.filteredRange?rs(l.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(a.length){const e=c.filter(e=>e).filter(e=>!a.includes(e));o.push({colId:r,displayedValues:[...new Set(e)],displayBlanks:!a.includes("")&&c.some(e=>!e)})}const u=this.getters.getEvaluatedCell(i).formattedValue,h=this.getUniqueColNameForExcel(r,u,s);s.push(h);const d=Do(i.col,i.row);t.cells[d]=h,t.cellValues[d]=h}r.filters=o}}}getUniqueColNameForExcel(e,t,r){return t||(t=`Column${e}`),Xe(t,r,{compute:(e,r)=>t+String(r),start:2})}}).add("header_visibility_ui",class extends Is{static getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,r){return"COL"===t?this.isColHidden(e,r):this.isRowHidden(e,r)}getNextVisibleCellPosition({sheetId:e,col:t,row:r}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",r,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,r,n){if(r<=n)for(let o=r;o<=n;o++)if(this.getters.doesHeaderExist(e,t,o)&&!this.isHeaderHidden(e,t,o))return o;if(r>n)for(let o=r;o>=n;o--)if(this.getters.doesHeaderExist(e,t,o)&&!this.isHeaderHidden(e,t,o))return o}findLastVisibleColRowIndex(e,t,{last:r,first:n}){return le(r,n,-1).find(r=>!this.isHeaderHidden(e,t,r))||n}findFirstVisibleColRowIndex(e,t){const r=this.getters.getNumberHeaders(e,t);for(let n=0;n<r;n++){if("COL"===t&&!this.isColHidden(e,n))return n;if("ROW"===t&&!this.isRowHidden(e,n))return n}}exportForExcel(e){for(const t of e.sheets)for(const[e,r]of Object.entries(t.rows))r.isHidden=this.isRowHidden(t.id,Number(e))}}).add("cell_computed_style",class extends Is{static getters=["getCellComputedBorder","getCellComputedStyle"];styles=new fE;borders=new fE;handle(e){if(ds.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 fE,void(this.borders=new fE);nT(e)?"sheetId"in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new fE,this.borders=new fE):ms.has(e.type)?this.styles=new fE:ps.has(e.type)&&(this.borders=new fE)}getCellComputedBorder(e,t){let r=this.borders.get(e);return void 0===r&&(this.precomputeCellBorders(e.sheetId,t??ss(e)),r=this.borders.get(e)),r??null}precomputeCellBorders(e,t){const r=this.getters.getCellBordersInZone(e,t),n=this.getters.getCellTableBorderZone(e,t);for(let o=t.left;o<=t.right;o++)for(let s=t.top;s<=t.bottom;s++){const t={sheetId:e,col:o,row:s};if(void 0!==this.borders.get(t))continue;const i=r.get(t),a={...Fe(n.get(t)),...Fe(i)};Ce(a)?this.borders.set(t,null):this.borders.set(t,a)}}getCellComputedStyle(e){let t=this.styles.get(e);return void 0===t&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellStyle(e){const t=this.getters.getCell(e),r=this.getters.getCellConditionalFormatStyle(e),n=this.getters.getCellTableStyle(e),o=this.getters.getDataValidationCellStyle(e),s={...Fe(n),...Fe(o),...Fe(t?.style),...Fe(r)};return this.getters.getEvaluatedCell(e).link&&!s.textColor&&(s.textColor=V),s}}).add("table_computed_style",class extends Is{static getters=["getCellTableStyle","getCellTableBorder","getCellTableBorderZone"];tableStyles={};handle(e){ds.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type?this.tableStyles={}:nT(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]}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 fE;for(const n of this.getters.getTablesOverlappingZones(e,[t])){const t=this.tableStyles[e][n.id]().borders;for(const[n,o]of Object.entries(t)){const t=parseInt(n);for(const[n,s]of Object.entries(o))s&&r.set({sheetId:e,col:t,row:parseInt(n)},s)}}return r}computeTableStyle(e,t){return xe(()=>{const{config:r,numberOfCols:n,numberOfRows:o}=this.getTableRuntimeConfig(e,t),s=function(e,t,r,n){return{borders:WE(e,t,r,n),styles:ZE(e,t,r,n)}}(r,this.getters.getTableStyle(t.config.styleId),n,o),i=this.getTableMapping(e,t),a={borders:{},styles:{}};for(let e=0;e<n;e++){const t=i.colMapping[e];a.borders[t]={},a.styles[t]={};for(let r=0;r<o;r++){const n=i.rowMapping[r];a.borders[t][n]=s.borders[e][r],a.styles[t][n]=s.styles[e][r]}}return a})}getTableRuntimeConfig(e,t){const r=t.range.zone,n={...t.config};let o=r.right-r.left+1,s=r.bottom-r.top+1;for(let o=r.top;o<=r.bottom;o++)this.getters.isRowHidden(e,o)&&(s--,o-r.top<t.config.numberOfHeaders&&(n.numberOfHeaders--,n.numberOfHeaders<0&&(n.numberOfHeaders=0)),o===r.bottom&&(n.totalRow=!1));for(let t=r.left;t<=r.right;t++)this.getters.isColHidden(e,t)&&(o--,t===r.left&&(n.firstColumn=!1),t===r.right&&(n.lastColumn=!1));return{config:n,numberOfCols:o,numberOfRows:s}}getTableMapping(e,t){const r={},n={};let o=0,s=0;const i=t.range.zone;for(let t=i.left;t<=i.right;t++)if(!this.getters.isColHidden(e,t)){r[o]=t,o++;for(let t=i.top;t<=i.bottom;t++)this.getters.isRowHidden(e,t)||(n[s]=t,s++)}return{colMapping:r,rowMapping:n}}}).add("header_positions",class extends Is{static getters=["getColDimensions","getRowDimensions","getColRowOffset"];headerPositions={};isDirty=!0;handle(e){switch(ds.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"UPDATE_FILTER":case"UPDATE_TABLE":case"REMOVE_TABLE":this.headerPositions={},this.isDirty=!0;break;case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_ALL_HEADER_GROUPS":case"UNGROUP_HEADERS":case"GROUP_HEADERS":case"CREATE_SHEET":this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case"DUPLICATE_SHEET":this.headerPositions[e.sheetIdTo]=re(this.headerPositions[e.sheetId])}}finalize(){for(const e of this.getters.getSheetIds())!this.isDirty&&this.headerPositions[e]||(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){const r=this.headerPositions[e].COL[t],n=this.getters.getColSize(e,t);return{start:r,size:n,end:r+(this.getters.isColHidden(e,t)?0:n)}}getRowDimensions(e,t){const r=this.headerPositions[e].ROW[t],n=this.getters.getRowSize(e,t);return{start:r,size:n,end:r+(this.getters.isRowHidden(e,t)?0:n)}}getColRowOffset(e,t,r,n=this.getters.getActiveSheetId()){const o=this.headerPositions[n][e][t];return this.headerPositions[n][e][r]-o}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,"COL"),ROW:this.computePositions(e,"ROW")}}computePositions(e,t){const r={};let n=0;for(let o=0;o<this.getters.getNumberHeaders(e,t)+1;o++)r[o]=n,this.getters.isHeaderHidden(e,t,o)||(n+=this.getters.getHeaderSize(e,t,o));return r}}).add("viewport",class extends Is{static getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getVisibleRectWithoutHeaders","getVisibleCellPositions","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","isPixelPositionVisible","getColDimensionsInViewport","getRowDimensionsInViewport","getAllActiveViewportsZonesAndRect","getRect","getFigureUI","getPositionAnchorOffset","getGridOffset"];viewports={};sheetViewWidth=0;sheetViewHeight=0;gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return"Success"}}handleEvent(e){const t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:r,row:n}=function(e,t){let r,n;const{left:o,right:s,top:i,bottom:a}=e,{left:l,right:c,top:u,bottom:h}=t;return r=l!==o?l:c!==s?c:l,n=u!==i?u:h!==a?h:u,{col:r,row:n}}(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const o=e.previousAnchor.zone,s=e.anchor.zone,{top:i,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);o.left===s.left&&o.right===s.right&&(r=l>r||r>c?l:r),o.top===s.top&&o.bottom===s.bottom&&(n=i>n||n>a?i:n)}r=Math.min(r,this.getters.getNumberCols(t)-1),n=Math.min(n,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:r,row:n})}}handle(e){if(ds.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"SHIFT_VIEWPORT_DOWN":const t=this.getters.getActiveSheetId(),{top:r,viewportHeight:n,offsetCorrectionY:o}=this.getMainInternalViewport(t),s=this.getters.getRowDimensions(t,r);this.shiftVertically(s.start+n-o);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:r,offsetCorrectionY:n}=this.getMainInternalViewport(e),o=this.getters.getRowDimensions(e,t);this.shiftVertically(o.end-n-r);break}case"REMOVE_TABLE":case"UPDATE_TABLE":case"UPDATE_FILTER":case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UNGROUP_HEADERS":case"GROUP_HEADERS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_ALL_HEADER_GROUPS":this.sheetsWithDirtyViewports.add(e.sheetId);break;case"UPDATE_CELL":if("content"in e||"format"in e||void 0!==e.style?.fontSize)for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case"DELETE_SHEET":this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"ACTIVATE_SHEET":this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case"SCROLL_TO_CELL":this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row})}}finalize(){for(const e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){const t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){const e=this.getters.getSheetIds();for(const t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getRowIndex(e)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getGridOffset(){return{x:this.gridOffsetX,y:this.gridOffsetY}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>le(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,"COL",t))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>le(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,"ROW",t))}getVisibleCellPositions(){const e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),r=this.getters.getActiveSheetId(),n=[];for(const o of e)for(const e of t){const t={sheetId:r,col:o,row:e},s=this.getters.getMainCellPosition(t);s.row===e&&s.col===o&&n.push(t)}return n}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:r,ySplit:n}=this.getters.getPaneDivisions(e),{width:o,height:s}=t.getMaxSize();return{x:this.getters.getColDimensions(e,r).start,y:this.getters.getRowDimensions(e,n).start,width:o,height:s}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:r}=this.getMainViewportRect(),n=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-n.viewportWidth),maxOffsetY:Math.max(0,r-n.viewportHeight)}}getColRowOffsetInViewport(e,t,r){if(r<t)return-this.getColRowOffsetInViewport(e,r,t);const n=this.getters.getActiveSheetId(),o="COL"===e?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),s=o.findIndex(e=>t>=e);let i=o.findIndex(e=>r<=e);i=-1===i?o.length:i;const a=o.slice(s,i);let l=0;for(const t of a)l+=this.getters.getHeaderSize(n,e,t);return l}isVisibleInViewport({sheetId:e,col:t,row:r}){return this.getSubViewports(e).some(e=>e.isVisible(t,r))}getEdgeScrollCol(e,t,r){let n=!1,o=0,s=0;const{xSplit:i}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(n=!0,s=pT(e-a),o=1):e<l&&r>=l&&c>0?(n=!0,s=pT(l-e),o=-1):i&&t<l&&e>l&&(n=!0,s=pT(e),o="reset"),{canEdgeScroll:n,direction:o,delay:s}}getEdgeScrollRow(e,t,r){let n=!1,o=0,s=0;const{ySplit:i}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(n=!0,s=pT(e-a),o=1):e<l&&r>=l&&c>0?(n=!0,s=pT(l-e),o=-1):i&&t<l&&e>l&&(n=!0,s=pT(e),o="reset"),{canEdgeScroll:n,direction:o,delay:s}}getVisibleRect(e){const t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){const t=this.getters.getActiveSheetId(),r=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...r,x:r.x+this.gridOffsetX,y:r.y+this.gridOffsetY}}getRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getFullRect(e))}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:r}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,r).start}}getColDimensionsInViewport(e,t){const{top:r}=this.getMainInternalViewport(e),n={left:t,right:t,top:r,bottom:r},{x:o,width:s}=this.getVisibleRect(n),i=o-this.gridOffsetX;return{start:i,size:s,end:i+s}}getRowDimensionsInViewport(e,t){const{left:r}=this.getMainInternalViewport(e),n={left:0,right:r,top:t,bottom:t},{y:o,height:s}=this.getVisibleRect(n),i=o-this.gridOffsetY;return{start:i,size:s,end:i+s}}getAllActiveViewportsZonesAndRect(){const e=this.getters.getActiveSheetId();return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(Se)}checkPositiveDimension(e){return e.width<0||e.height<0?"InvalidViewportSize":"Success"}checkValuesAreDifferent(e){const{height:t,width:r}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===r&&e.height===t?"ValuesNotChanged":"Success"}checkScrollingDirection({offsetX:e,offsetY:t}){const r=this.getMainInternalViewport(this.getters.getActiveSheetId());return!r.canScrollHorizontally&&e>0||!r.canScrollVertically&&t>0?"InvalidScrollingDirection":"Success"}checkIfViewportsWillChange({offsetX:e,offsetY:t}){const r=this.getters.getActiveSheetId(),{maxOffsetX:n,maxOffsetY:o}=this.getMaximumSheetOffset();return this.getSubViewports(r).some(r=>r.willNewOffsetScrollViewport(ae(e,0,n),ae(t,0,o)))?"Success":"ViewportScrollLimitsReached"}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e={};for(const t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,r=0,n=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=r,this.gridOffsetY=n,this.recomputeViewports()}recomputeViewports(){for(const e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){const r=this.getters.getActiveSheetId(),{maxOffsetX:n,maxOffsetY:o}=this.getMaximumSheetOffset();this.getSubViewports(r).forEach(r=>r.setViewportOffset(ae(e,0,n),ae(t,0,o)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetX||0,y:this.viewports[e]?.bottomRight.offsetY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:r}=this.getters.getPaneDivisions(e),n=this.getters.getNumberCols(e),o=this.getters.getNumberRows(e),s=Math.min(this.getters.getColRowOffset("COL",0,t,e),this.sheetViewWidth),i=Math.min(this.getters.getColRowOffset("ROW",0,r,e),this.sheetViewHeight),a=Math.max(this.sheetViewWidth-s,0),l=Math.max(this.sheetViewHeight-i,0),{xRatio:c,yRatio:u}=this.getFrozenSheetViewRatio(e),h=c<1,d=u<1,f=this.getViewportOffset(e),g={topLeft:r&&t&&new bT(this.getters,e,{left:0,right:t-1,top:0,bottom:r-1},{width:s,height:i},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:r&&new bT(this.getters,e,{left:t,right:n-1,top:0,bottom:r-1},{width:a,height:i},{canScrollHorizontally:h,canScrollVertically:!1},{x:h?f.x:0,y:0})||void 0,bottomLeft:t&&new bT(this.getters,e,{left:0,right:t-1,top:r,bottom:o-1},{width:s,height:l},{canScrollHorizontally:!1,canScrollVertically:d},{x:0,y:d?f.y:0})||void 0,bottomRight:new bT(this.getters,e,{left:t,right:n-1,top:r,bottom:o-1},{width:a,height:l},{canScrollHorizontally:h,canScrollVertically:d},{x:h?f.x:0,y:d?f.y:0})};this.viewports[e]=g}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){const t=this.getters.getActiveSheetId(),{top:r}=this.getMainInternalViewport(t),{scrollX:n}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(n,e);const{anchor:o}=this.getters.getSelection();if(o.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-r;this.selection.selectCell(o.cell.col,o.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let r=this.getActiveMainViewport().left,n=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset("COL",r,0);for(;e<n;r--)n-=this.getters.getColSize(t,r-1);return Math.max(r,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let r=this.getActiveMainViewport().top,n=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset("ROW",r,0);for(;e<n;r--)n-=this.getters.getRowSize(t,r-1);return Math.max(r,0)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],r=this.getters.getFigures(e),{scrollX:n,scrollY:o}=this.getters.getActiveSheetScrollInfo(),{x:s,y:i}=this.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const c of r){const r=this.getFigureUI(e,c),{x:u,y:h}=r;u>=s&&(u+c.width<n+s||u>a+n+s)||(h>=i&&(h+c.height<o+i||h>l+o+i)||t.push(r))}return t}getFigureUI(e,t){const r=t.offset.x+this.getters.getColDimensions(e,t.col).start,n=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:r,y:n}}getPositionAnchorOffset(e){const{scrollX:t,scrollY:r}=this.getters.getActiveSheetScrollInfo(),n=e.x-t,o=e.y-r,s=n>=0?this.getColIndex(n):this.getColIndexLeftOfMainViewport(n),i=o>=0?this.getRowIndex(o):this.getRowIndexTopOfMainViewport(o),{x:a,y:l}=this.getRect(ss({col:s,row:i}));return{col:s,row:i,offset:{x:Math.max(n-a+this.gridOffsetX,0),y:Math.max(o-l+this.gridOffsetY,0)}}}isPixelPositionVisible(e){const{scrollX:t,scrollY:r}=this.getters.getActiveSheetScrollInfo(),{x:n,y:o}=this.getters.getMainViewportCoordinates(),{width:s,height:i}=this.getters.getSheetViewDimension();return!(e.x>=n&&(e.x<n+t||e.x>s+t+n))&&!(e.y>=o&&(e.y<o+r||e.y>i+r+o))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:r}=this.getters.getPaneDivisions(e),n=this.getters.getColDimensions(e,t).start,o=this.getters.getRowDimensions(e,r).start;return{xRatio:n/(this.sheetViewWidth+this.gridOffsetX),yRatio:o/(this.sheetViewHeight+this.gridOffsetY)}}mapViewportsToRect(e,t){let r=1/0,n=1/0,o=0,s=0,i=!1;for(const a of this.getSubViewports(e)){const e=t(a);e&&(i=!0,r=Math.min(r,e.x),n=Math.min(n,e.y),o=Math.max(o,e.x+e.width),s=Math.max(s,e.y+e.height))}return i?{x:r,y:n,width:o-r,height:s-n}:{x:0,y:0,width:0,height:0}}}).add("clipboard",class extends Is{static layers=["Clipboard"];static getters=["getClipboardTextAndImageContent","getClipboardId","getClipboardTextContent","isCutOperation"];status="invisible";originSheetId;copiedData;_isCutOperation=!1;clipboardId=(new wo).uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new wo}allowDispatch(e){switch(e.type){case"CUT":const t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case"PASTE_FROM_OS_CLIPBOARD":{const t=this.convertTextToClipboardData(e.clipboardContent.text??""),r=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:r,isCutOperation:!1})}case"PASTE":{if(!this.copiedData)return"EmptyClipboard";const t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].top&&0===e[0].bottom)return"InvalidCopyPasteSelection";break}case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].left&&0===e[0].right)return"InvalidCopyPasteSelection";break}case"INSERT_CELL":{const{cut:t,paste:r}=this.getInsertCellsTargets(e.zone,e.shiftDimension),n=this.copy(t,"shiftCells");return this.isPasteAllowed(r,n,{isCutOperation:!0})}case"DELETE_CELL":{const{cut:t,paste:r}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),n=this.copy(t,"shiftCells");return this.isPasteAllowed(r,n,{isCutOperation:!0})}}return"Success"}handle(e){switch(e.type){case"COPY":case"CUT":const t=this.getters.getSelectedZones();this.status="visible",this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation="CUT"===e.type,this.copiedData=this.copy(t);break;case"PASTE_FROM_OS_CLIPBOARD":{this._isCutOperation=!1;const t=e.clipboardContent.data;if(e.clipboardContent.imageData){const t=this.getters.getActiveSheetId(),r=this.uuidGenerator.uuidv4(),n=e.clipboardContent.imageData,o=function(e,t){const r=re(t),n=e.getSheetViewDimension(),o=n.width,s=n.height;if(r.width>o){const e=o/r.width;r.width=o,r.height=r.height*e}if(r.height>s){const e=s/r.height;r.height=s,r.width=r.width*e}return r}(this.getters,n.size);this.dispatch("CREATE_IMAGE",{definition:n,size:o,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:t,figureId:r})}this.copiedData=t||this.convertTextToClipboardData(e.clipboardContent.text??"");const r=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:r,selectTarget:!0,isCutOperation:!1}),this.status="invisible",this.copiedData=void 0;break}case"PASTE":{const t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status="invisible",this._isCutOperation&&(this.copiedData=void 0,this._isCutOperation=!1);break}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZone(),t=e.top!==e.bottom,r={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();const n=this.copy([r]);this.paste([e],n,{isCutOperation:!1,selectTarget:!0})}break;case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZone(),t=e.left!==e.right,r={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();const n=this.copy([r]);this.paste([e],n,{isCutOperation:!1,selectTarget:!0})}break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:r}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!zo(t[0])){this.dispatch("CLEAR_CELLS",{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}const n=this.copy(t,"shiftCells");this.paste(r,n,{isCutOperation:!0});break}case"INSERT_CELL":{const{cut:t,paste:r}=this.getInsertCellsTargets(e.zone,e.shiftDimension),n=this.copy(t,"shiftCells");this.paste(r,n,{isCutOperation:!0});break}case"ADD_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(const t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}}this.status="invisible";break;case"REPEAT_PASTE":this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case"DELETE_SHEET":if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status="invisible");break;default:ws(e)&&(this.status="invisible")}}convertTextToClipboardData(e){const t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),r={};for(const{handlerName:n,handler:o}of t){const t=o.convertTextToClipboardData(e);r[n]=t;const s=["sheetId","cells","zones","figureId"];for(const e of s)t&&e in t&&(r[e]=t[e])}return r}selectClipboardHandlers(e){const t="figureId"in e?fT.figureHandlers:fT.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){const t=this.getClipboardData(e);for(const{handler:e}of this.selectClipboardHandlers(t)){const r=e.isCutAllowed(t);if("Success"!==r)return r}return"Success"}isPasteAllowed(e,t,r){for(const{handler:n}of this.selectClipboardHandlers(t)){const o=n.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...r});if("Success"!==o)return o}return"Success"}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;const{zones:r}=this.copiedData;for(const n of r){if("COL"===t&&e<=n.right)return!0;if("ROW"===t&&e<=n.bottom)return!0}return!1}copy(e,t="copyPaste"){const r={},n=this.getClipboardData(e);for(const{handlerName:e,handler:o}of this.selectClipboardHandlers(n)){const s=o.copy(n,this._isCutOperation,t);r[e]=s;const i=["sheetId","cells","zones","figureId"];for(const e of i)s&&e in s&&(r[e]=s[e])}return r}paste(e,t,r){if(!t)return;const n=this.getters.getActiveSheetId(),o=this.selectClipboardHandlers(t),{target:s,zone:i,selectedZones:a}=function(e,t,r,n,o){let s;const i=[],a={sheetId:e,zones:t};for(const{handlerName:l,handler:c}of n){const n=r[l];if(!n)continue;const u=c.getPasteTarget(e,t,n,o);u.figureId&&(a.figureId=u.figureId);for(const e of u.zones)i.push(e),s=void 0!==s?Zo(s,e):e}return{target:a,zone:s,selectedZones:i}}(n,e,t,o,r);void 0!==i&&this.addMissingDimensions(n,i.right-i.left+1,i.bottom-i.top+1,i.left,i.top),((e,t,r,n)=>{e.forEach(({handlerName:e,handler:o})=>{const s=t[e];s&&o.paste(r,s,n)})})(o,t,s,r),r?.selectTarget&&((e,t,r)=>{const n={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:n,zone:Zo(...r)},{scrollIntoView:!1})})(this.selection,e,a)}addMissingDimensions(e,t,r,n,o){const s=r+o-this.getters.getNumberRows(e);s>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s,position:"after"});const i=t+n-this.getters.getNumberCols(e);i>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i,position:"after"})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){const e=await this.getImageContent(),t=e?.type,r={[hT.PlainText]:this.getPlainTextContent(),[hT.Html]:await this.getHTMLContent()};return t&&e&&(r[t]=e),r}getSheetData(){const e={version:nE(),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="${uT(cT(this.getters.getCellComputedStyle(t.position)))}">`+xw(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='${xw(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="${xw(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>gT)return void this.ui.notifyUI({text:v("The file you are trying to copy is too large (>%sMB).\nIt will not be added to your OS clipboard.\nYou can download it directly instead.",Math.round(5)),sticky:!1,type:"warning"});r=await async function(e){return new Promise((t,r)=>{const n=new Image;n.addEventListener("load",()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const r=e.getContext("2d");r?.drawImage(n,0,0),e.toBlob(t,"image/png")}),n.addEventListener("error",r),n.src=e})}(t)}}return r?r instanceof File?r:new File([r],"image.png",{type:"image/png"}):void 0}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){const r=this.getters.getActiveSheetId();let n;return n="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(r)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(r)-1},{cut:[n],paste:[e]}}getInsertCellsTargets(e,t){const r=this.getters.getActiveSheetId();let n,o;return"COL"===t?(n={...e,right:this.getters.getNumberCols(r)-1},o={...e,left:e.right+1,right:e.right+1}):(n={...e,bottom:this.getters.getNumberRows(r)-1},o={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(r)-1}),{cut:[n],paste:[o]}}getClipboardData(e){const t=this.getters.getActiveSheetId(),r=this.getters.getSelectedFigureId();if(r)return{figureId:r,sheetId:t};const n=dT(t,e);return this._isCutOperation||(n.rowsIndexes=n.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),n}drawLayer(e){if("visible"!==this.status||!this.copiedData)return;const{sheetId:t,zones:r}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!r||!r.length)return;const{ctx:n,thinLineWidth:o}=e;n.setLineDash([8,5]),n.strokeStyle=N,n.lineWidth=3.3*o;for(const e of r){const{x:t,y:r,width:o,height:s}=this.getters.getVisibleRect(e);o>0&&s>0&&n.strokeRect(t,r,o,s)}}}).add("carousel_ui",class extends Is{static getters=["getSelectedCarouselItem","getChartFromFigureId","getChartIdFromFigureId"];uuidGenerator=new wo;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"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"UPDATE_CAROUSEL_ACTIVE_ITEM":this.carouselStates[e.figureId]=this.getCarouselItemId(e.item);break;case"POPOUT_CHART_FROM_CAROUSEL":this.popOutChartFromCarousel(e.carouselId,e.chartId,e.sheetId);break;case"DELETE_FIGURE":delete this.carouselStates[e.figureId];break;case"UPDATE_CAROUSEL":this.fixWrongCarouselState(e.figureId);break;case"DELETE_CHART":case"UNDO":case"REDO":case"DELETE_SHEET":for(const e in this.carouselStates)this.fixWrongCarouselState(e)}}popOutChartFromCarousel(e,t,r){const n=this.getters.getCarousel(e);if(!n)return;const o=this.getters.getFigure(r,e),s=this.getters.getChartDefinition(t);if(!s||!o)return;const i=this.getters.getFigureUI(r,o),a=this.getters.getPositionAnchorOffset({x:i.x+50,y:i.y+50}),l=this.uuidGenerator.smallUuid();this.dispatch("CREATE_CHART",{...a,chartId:this.uuidGenerator.smallUuid(),figureId:l,sheetId:r,size:{width:o.width,height:o.height},definition:{...s}});const c=n.items.filter(e=>"chart"!==e.type||e.chartId!==t);this.dispatch("UPDATE_CAROUSEL",{sheetId:r,figureId:e,definition:{...n,items:c}}),this.dispatch("SELECT_FIGURE",{figureId:l})}getSelectedCarouselItem(e){const t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;const t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){const t=this.getters.getFigureSheetId(e);if(!t)return;const r=this.getters.getFigure(t,e);if(r&&("chart"===r.tag||"carousel"===r.tag)){if("carousel"===r.tag){const t=this.getSelectedCarouselItem(e);return"chart"===t?.type?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e))return void delete this.carouselStates[e];const t=this.getters.getCarousel(e);0===t.items.length?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){const r=this.getters.getCarousel(e),n=this.uuidGenerator.smallUuid();this.dispatch("CREATE_CHART",{chartId:n,figureId:e,sheetId:t,definition:lT});const o={...r,items:[...r.items,{type:"chart",chartId:n}]};this.dispatch("UPDATE_CAROUSEL",{sheetId:t,figureId:e,definition:o})}addFigureChartToCarousel(e,t,r){const n=this.getChartIdFromFigureId(t);if(!n)return;const o=this.getters.getCarousel(e),s={...o,items:[...o.items,{type:"chart",chartId:n}]};this.dispatch("UPDATE_CAROUSEL",{sheetId:r,figureId:e,definition:s}),this.dispatch("UPDATE_CHART",{sheetId:r,chartId:n,figureId:e,definition:this.getters.getChartDefinition(n)}),this.dispatch("DELETE_FIGURE",{sheetId:r,figureId:t})}getCarouselItemId(e){return"chart"===e.type?e.chartId:"carouselDataView"}}),ET=(new h).add("evaluation",class extends JE{static getters=["evaluateFormula","evaluateFormulaResult","evaluateCompiledFormula","getCorrespondingFormulaCell","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getEvaluatedCellsInZone","getEvaluatedCellsPositions","getSpreadZone","getArrayFormulaSpreadingOn","isEmpty"];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new VS(e.custom,this.getters)}beforeHandle(e){(ds.has(e.type)||gs.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 O(r)?nr(r,e=>e.value):r.value}evaluateFormulaResult(e,t){return this.evaluator.evaluateFormulaResult(e,t)}evaluateCompiledFormula(e,t,r){return this.evaluator.evaluateCompiledFormula(e,t,r)}getRangeFormattedValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).formattedValue)}getRangeValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).value)}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map(e=>e.format)}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map(e=>this.getEvaluatedCell(e))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return rs(t).map(({col:t,row:r})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:r}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isEmpty(e,t){return rs(t).map(({col:t,row:r})=>this.getEvaluatedCell({sheetId:e,col:t,row:r})).every(e=>e.type===Eu.empty)}mapVisiblePositions(e,t){const{sheetId:r,zone:n}=e;return rs(n).reduce((e,n)=>{const{col:o,row:s}=n;return this.getters.isColHidden(r,o)||this.getters.isRowHidden(r,s)||e.push(t({sheetId:r,...n})),e},[])}exportForExcel(e){for(const t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(const t of this.evaluator.getEvaluatedPositions()){const r=this.evaluator.getEvaluatedCell(t),n=Do(t.col,t.row),o=r.value;let s,i=!1,a=!0;const l=e.sheets.find(e=>e.id===t.sheetId),c=this.getCorrespondingFormulaCell(t);if(c){const u=this.getters.getCell(t);if(a=KE(c.compiledFormula.tokens),i=a&&u?.content===c.content,!a&&""!==o){s=(o??"").toString();const t=r.format;if(t){const r=hy(t,e.formats);l.formats[n]=r}}}const u=l.cells[n];let h;h=a&&i&&c instanceof mE?c.contentWithFixedReferences:a?u:s,l.cells[n]=h,l.cellValues[n]="error"!==r.type?o:void 0;const d=this.getSpreadZone(t);d&&(l.formulaSpillRanges[n]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,d),t.sheetId))}}getCorrespondingFormulaCell(e){const t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;const r=this.getArrayFormulaSpreadingOn(e);if(void 0===r)return;const n=this.getters.getCell(r);return n?.isFormula?n:void 0}}).add("evaluation_chart",class extends JE{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=function(e){const t=Yp.getAll().sort((e,t)=>e.sequence-t.sequence);return function(r){const n=t.find(e=>e.match(r.type));if(!n)throw new Error("No runtime builder for this chart.");const o=n.getChartRuntime(r,e),s=r.getDefinition();if("chartJsConfig"in o&&/line|combo|bar|scatter|waterfall/.test(s.type)){const e=o.chartJsConfig;o.masterChartConfig=function(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>{return!("x1"===(t=e.xAxisID)||"xMovingAverage"===t);var t}).map(e=>({...e,pointRadius:0,showLine:!0}))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return function(e,t=20){return e?e.length>t?e.substring(0,t)+"…":e:""}(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}(e)}return o}}(this.getters);handle(e){if(ds.has(e.type)||ms.has(e.type)||fs.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:Nb(e)};if(!t)return{background:M,fontColor:Nb(M)};const r=t.zone.left,n=t.zone.top,o=t.sheetId,s=this.getters.getCellComputedStyle({sheetId:o,col:r,row:n}),i=s.fillColor||M;return{background:i,fontColor:s.textColor||Nb(i)}}async exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),r=[];for(const n of e){if(!n||"chart"!==n.tag)continue;const e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===n.id);if(!e)continue;const o=this.getters.getChart(e),s=o?.getDefinitionForExcel(this.getters);if(s)r.push({...n,data:s});else{if(!o)continue;const r=this.getters.getChartType(e),s=this.getters.getChartRuntime(e),i=await yC(s,n,r);i&&t.images.push({...n,tag:"image",data:{mimetype:"image/png",path:i,size:{width:n.width,height:n.height}}})}}t.charts=r}}}).add("evaluation_cf",class extends JE{static getters=["getConditionalIcon","getCellConditionalFormatStyle","getConditionalDataBar"];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(ds.has(e.type)||ms.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(const e of this.getters.getSheetIds())this.computedStyles[e]=xe(()=>this.getComputedStyles(e)),this.computedIcons[e]=xe(()=>this.getComputedIcons(e)),this.computedDataBars[e]=xe(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){const{sheetId:t,col:r,row:n}=e,o=this.computedStyles[t]();return o&&o[r]?.[n]}getConditionalIcon({sheetId:e,col:t,row:r}){const n=this.computedIcons[e]();return n&&n[t]?.[r]}getConditionalDataBar({sheetId:e,col:t,row:r}){const n=this.computedDataBars[e]();return n&&n[t]?.[r]}getComputedStyles(e){const t={};for(const r of this.getters.getConditionalFormats(e).reverse())switch(r.rule.type){case"ColorScaleRule":for(const n of r.ranges)this.applyColorScale(e,n,r.rule,t);break;case"CellIsRule":const n=r.rule.values.map(e=>e.startsWith("=")?gm(e):void 0);for(const o of r.ranges){const s=this.getters.getRangeFromSheetXC(e,o).zone;for(let o=s.top;o<=s.bottom;o++)for(let i=s.left;i<=s.right;i++){const a={sheetId:e,col:i,row:o},l=r.rule.values.map((t,r)=>{const a=n[r];return a?this.getters.getTranslatedCellFormula(e,i-s.left,o-s.top,a.tokens):t});this.getRuleResultForTarget(a,{...r.rule,values:l})&&(t[i]||(t[i]=[]),t[i][o]=Object.assign(t[i]?.[o]||{},r.rule.style))}}}return t}getComputedIcons(e){const t={};for(const r of this.getters.getConditionalFormats(e).reverse())if("IconSetRule"===r.rule.type)for(const n of r.ranges)this.applyIcon(e,n,r.rule,t);return t}getComputedDataBars(e){const t={};for(const r of this.getters.getConditionalFormats(e).reverse())if("DataBarRule"===r.rule.type)for(const n of r.ranges)this.applyDataBar(e,n,r.rule,t);return t}parsePoint(e,t,r,n){const o=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter(e=>e.type===Eu.number).map(e=>e.value);switch(r.type){case"value":return"max"===n?We(o):qe(o);case"number":return Number(r.value);case"percentage":const t=qe(o);return t+(We(o)-t)*Number(r.value)/100;case"percentile":return Ft(o,Number(r.value)/100,!0);case"formula":const s=r.value&&this.getters.evaluateFormula(e,r.value);return"number"==typeof s?s:null;default:return null}}applyIcon(e,t,r,n){const o=this.parsePoint(e,t,r.lowerInflectionPoint),s=this.parsePoint(e,t,r.upperInflectionPoint);if(null===o||null===s||o>s)return;const i=this.getters.getRangeFromSheetXC(e,t).zone,a=[r.icons.upper,r.icons.middle,r.icons.lower];for(let t=i.top;t<=i.bottom;t++)for(let l=i.left;l<=i.right;l++){const i=this.getters.getEvaluatedCell({sheetId:e,col:l,row:t});if(i.type!==Eu.number)continue;const c=this.computeIcon(i.value,s,r.upperInflectionPoint.operator,o,r.lowerInflectionPoint.operator,a);n[l]||(n[l]=[]),n[l][t]=c}}computeIcon(e,t,r,n,o,s){return"ge"===r&&e>=t||"gt"===r&&e>t?s[0]:"ge"===o&&e>=n||"gt"===o&&e>n?s[1]:s[2]}applyDataBar(e,t,r,n){const o=this.getters.getRangeFromSheetXC(e,r.rangeValues||t),s=We(this.getters.getEvaluatedCellsInZone(e,o.zone).filter(e=>e.type===Eu.number).map(e=>e.value));if(s<=0)return;const i=r.color,a=this.getters.getRangeFromSheetXC(e,t).zone,l=o.zone;for(let t=a.top;t<=a.bottom;t++)for(let r=a.left;r<=a.right;r++){const o=r-a.left+l.left,c=t-a.top+l.top,u=this.getters.getEvaluatedCell({sheetId:e,col:o,row:c});!Qo(o,c,l)||u.type!==Eu.number||u.value<=0||(n[r]||(n[r]=[]),n[r][t]={color:Xm(i),percentage:100*u.value/s})}}applyColorScale(e,t,r,n){const o=this.parsePoint(e,t,r.minimum,"min"),s=r.midpoint?this.parsePoint(e,t,r.midpoint):null,i=this.parsePoint(e,t,r.maximum,"max");if(null===o||null===i||o>=i||s&&(o>=s||s>=i))return;const a=this.getters.getRangeFromSheetXC(e,t).zone,l=[{value:o,color:r.minimum.color}];r.midpoint&&s&&l.push({value:s,color:r.midpoint.color}),l.push({value:i,color:r.maximum.color});const c=function(e){if(e.length<2)throw new Error("Color scale must have at least 2 points");const t=[...e.sort((e,t)=>e.value-t.value)],r=[];for(let e=1;e<t.length;e++){const n=cp(t[e-1].color).a,o=cp(t[e].color).a,s=Km(t[e-1].color),i=Km(t[e].color);r.push({min:t[e-1].value,max:t[e].value,minColor:s,maxColor:i,minColorAlpha:n,maxColorAlpha:o,colorDiff:Sp(t[e-1].value,t[e].value,s,i)})}return e=>{if(e<r[0].min)return Xm(r[0].minColor,r[0].minColorAlpha);for(const t of r)if(e>=t.min&&e<=t.max)return Xm(Cp(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return Xm(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===Eu.number){const e=ae(s.value,o,i);n[r]||(n[r]=[]),n[r][t]=n[r]?.[t]||{},n[r][t].fillColor=c(e)}}}getRuleResultForTarget(e,t){const r=this.getters.getEvaluatedCell(e);if(r.type===Eu.error)return!1;const{sheetId:n}=e,o=bE.get(t.operator),s=t.values.map(e=>e.startsWith("=")?this.getters.evaluateFormula(n,e)??"":Wy(e,Dl));if(s.some(Pr))return!1;const i={type:t.operator,values:s.map(Vr)};return o.isValueValid(r.value??"",i,this.getters,n)}}).add("row_size",class extends JE{static getters=["getRowSize","getHeaderSize","getMaxAnchorOffset"];tallestCellInRow={};ctx=HS();beforeHandle(e){if("ADD_COLUMNS_ROWS"===e.type){if("COL"===e.dimension)return;const t=Re(e.position,e.base),r=Array(e.quantity).fill(void 0),n=Be(this.tallestCellInRow[e.sheetId],r,t);this.history.update("tallestCellInRow",e.sheetId,n)}}handle(e){switch(e.type){case"START":for(const e of this.getters.getSheetIds())this.initializeSheet(e);break;case"CREATE_SHEET":this.initializeSheet(e.sheetId);break;case"DUPLICATE_SHEET":{const t=re(this.tallestCellInRow[e.sheetId]);this.history.update("tallestCellInRow",e.sheetIdTo,t);break}case"DELETE_SHEET":const t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update("tallestCellInRow",t);break;case"REMOVE_COLUMNS_ROWS":{if("COL"===e.dimension)return;const t=He(this.tallestCellInRow[e.sheetId],e.elements);this.history.update("tallestCellInRow",e.sheetId,t);break}case"RESIZE_COLUMNS_ROWS":{const t=e.sheetId;if("ROW"===e.dimension)for(const r of e.elements){const e=this.getRowTallestCell(t,r);this.history.update("tallestCellInRow",t,r,e)}else for(const r of le(0,this.getters.getNumberRows(t)))for(const n of e.elements)this.updateRowSizeForCellChange(t,r,n)}break;case"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 rs(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??$)}getMaxAnchorOffset(e,t,r){let{numberOfRows:n,numberOfCols:o}=this.getters.getSheetSize(e),s=0;for(;s<t&&n>0;n--)s+=this.getRowSize(e,n-1);let i=0;for(;i<r&&o>0;o--)i+=this.getters.getColSize(e,o-1);return{col:o,row:n,offset:{x:i-r,y:s-t}}}getHeaderSize(e,t,r){return this.getters.isHeaderHidden(e,t,r)?0:"ROW"===t?this.getRowSize(e,r):this.getters.getColSize(e,r)}updateRowSizeForCellChange(e,t,r){const n=this.tallestCellInRow[e]?.[t];if(n?.cell.col===r){const r=this.getRowTallestCell(e,t);this.history.update("tallestCellInRow",e,t,r)}const o=this.getCellHeight({sheetId:e,col:r,row:t});if(!(o<=$)&&(!n&&o>$||n&&o>n.size)){const n={cell:{sheetId:e,col:r,row:t},size:o};this.history.update("tallestCellInRow",e,t,n)}}initializeSheet(e){const t=[];for(let r=0;r<this.getters.getNumberRows(e);r++){const n=this.getRowTallestCell(e,r);t.push(n)}this.history.update("tallestCellInRow",e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return $;const t=this.getters.getCell(e),r=this.getters.getColSize(e.sheetId,e.col);return function(e,t,r){return t&&(t.isFormula||t.content)?BS(e,t.isFormula?"":t.content,t.style,r):$}(this.ctx,t,r)}isInMultiRowMerge(e){const t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(void 0!==this.getters.getUserRowSize(e,t))return;const r=this.getters.getRowCells(e,t);let n,o=0;for(let e=0;e<r.length;e++){const t=this.getters.getCellById(r[e]);if(!t)continue;const s=this.getters.getCellPosition(t.id),i=this.getCellHeight(s);i>o&&i>$&&(o=i,n={cell:s,size:i})}return n&&n.size>$?n:void 0}}).add("data_validation_ui",class extends JE{static getters=["getDataValidationInvalidCriterionValueMessage","getInvalidDataValidationMessage","getValidationResultForCellValue","getDataValidationRangeValues","isCellValidCheckbox","getDataValidationCellStyle","getDataValidationChipStyle","isDataValidationInvalid"];validationResults={};handle(e){if(ds.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))this.validationResults={};else switch(e.type){case"ADD_DATA_VALIDATION_RULE":case"REMOVE_DATA_VALIDATION_RULE":delete this.validationResults[e.sheetId]}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:P}}getInvalidDataValidationMessage(e){const t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){const r=bE.get(e);return t.startsWith("=")?"onlyLiterals"===r.allowedValues?v("The value must not be a formula"):this.isValidFormula(t)?void 0:dd.CriterionError.validFormula:"onlyFormulas"===r.allowedValues?v("The value must be a formula"):r.isCriterionValueValid(t)?void 0:r.criterionValueErrorString}getDataValidationRangeValues(e,t){const r=this.getters.getRangeFromSheetXC(e,String(t.values[0])),n=[],o=new Set;for(const e of rs(r.zone)){const t=this.getters.getEvaluatedCell({...e,sheetId:r.sheetId});t.formattedValue&&!o.has(t.formattedValue)&&(o.add(t.formattedValue),n.push({label:t.formattedValue,value:t.value?.toString()||""}))}return n}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;const t=this.getters.getValidationRuleForCell(e);return!(!t||"isBoolean"!==t.criterion.type)&&this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){const r=this.getters.getValidationRuleForCell(t);if(!r)return SC;const n=this.getRuleErrorForCellValue(e,t,r);return n?{error:n,rule:r,isValid:!1}:SC}hasChip(e){const t=this.getters.getValidationRuleForCell(e);return("isValueInList"===t?.criterion.type||"isValueInRange"===t?.criterion.type)&&"chip"===t.criterion.displayStyle}getDataValidationStyle(e){const t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;const r=this.getters.getEvaluatedCell(e),n=this.getValueColor(t,r.value);if(!n)return;var o;return{fillColor:n,textColor:(o=n,rp(o)<.6?up(o,.9):hp(o,.75))}}getValueColor(e,t){if("isValueInList"===e.criterion.type||"isValueInRange"===e.criterion.type)for(const r in e.criterion.colors)if(r.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[r]}isValidFormula(e){return!gm(e).isBadExpression}getValidationResultForCell(e){const{col:t,row:r,sheetId:n}=e;return this.validationResults[n]||(this.validationResults[n]=this.computeSheetValidationResults(n)),this.validationResults[n][t]?.[r]?.()||SC}computeSheetValidationResults(e){const t={},r=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(const e of Nm(r.flat())){const{col:r,row:n}=e;t[r]||(t[r]=[]),t[r][n]=xe(()=>{const t=this.getters.getEvaluatedCell(e);return t.type===Eu.empty?SC:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,r){const{sheetId:n}=t,o=r.criterion,s=bE.get(o.type),i=this.getCellOffsetInRule(t,r),a=this.getEvaluatedCriterionValues(n,i,o);if(a.some(Pr))return;const l={...o,values:a.map(Vr)};return s.isValueValid(e,l,this.getters,n)?void 0:s.getErrorString(l,this.getters,n)}getCellOffsetInRule(e,t){const r=t.ranges.find(t=>Qo(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 Wy(r,Dl);const n=gm(r),o=this.getters.getTranslatedCellFormula(e,t.col,t.row,n.tokens);return this.getters.evaluateFormula(e,o)})}}).add("dynamic_tables",class extends JE{static getters=["canCreateDynamicTableOnZones","doesZonesContainFilter","getFilter","getFilters","getTable","getTables","getTablesOverlappingZones","getFilterId","getFilterHeaders","isFilterHeader"];tables={};handle(e){if(ds.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type)this.tables={};else switch(e.type){case"CREATE_TABLE":case"REMOVE_TABLE":case"UPDATE_TABLE":case"DELETE_CONTENT":this.tables={}}}finalize(){for(const e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){const t=[],r=this.getters.getCoreTables(e);for(const e of r)"dynamic"!==e.type&&t.push(e);const n=[...t];for(const o of r){if("dynamic"!==o.type)continue;const r=this.coreTableToTable(e,o);let s=r.range.zone;for(const e of n)Ko(s,e.range.zone)&&(s={...s,right:e.range.zone.left-1});t.push({...r,range:this.getters.getRangeFromZone(e,s)})}return t}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){const t=this.getTable(e);if(t&&t.config.hasFilters)return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:r}){return this.getTables(e).find(e=>Qo(t,r,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Ko(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){const t=[];for(const r of this.getTables(e)){if(!r.config.hasFilters)continue;const n=r.range.zone,o=n.top;for(let r=n.left;r<=n.right;r++)t.push({sheetId:e,col:r,row:o})}return t}isFilterHeader({sheetId:e,col:t,row:r}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===r)}canCreateDynamicTableOnZones(e,t){if(!us(t))return!1;const r=Zo(...t),n={col:r.left,row:r.top,sheetId:e},o=this.getters.getArrayFormulaSpreadingOn(n);if(!o){const e=this.getters.getEvaluatedCell(n);return e.value===w.SpilledBlocked&&!e.errorOriginPosition}if(Ae(o,n)&&1===cs(r))return!0;return Ae(r,this.getters.getSpreadZone(o))}coreTableToTable(e,t){if("dynamic"!==t.type)return t;const r=t.range.zone,n={sheetId:e,col:r.left,row:r.top},o=this.getters.getSpreadZone(n)??t.range.zone,s=this.getters.getRangeFromZone(e,o),i=this.getDynamicTableFilters(e,t,o);return{id:t.id,range:s,filters:i,config:t.config}}getDynamicTableFilters(e,t,r){const n=[],{top:o,bottom:s,left:i,right:a}=r;for(let r=i;r<=a;r++){const a=r-i,l={left:r,right:r,top:o,bottom:s},c=GE(this.getDynamicTableFilterId(t.id,a),this.getters.getRangeFromZone(e,l),t.config,this.getters.getRangeFromZone);n.push(c)}return n}getDynamicTableFilterId(e,t){return e+"_"+t}exportForExcel(e){for(const t of e.sheets)for(const e of t.tables){const r=Bo(e.range),n={sheetId:t.id,col:r.left,row:r.top},o=this.getters.getCoreTable(n),s=this.getTable(n);"dynamic"===o?.type&&s&&(e.range=Go(s.range.zone))}}}).add("custom_colors",class extends JE{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:tp(255,0,0),colors:[]},{leadColor:tp(255,128,0),colors:[]},{leadColor:tp(128,128,0),colors:[]},{leadColor:tp(128,255,0),colors:[]},{leadColor:tp(0,255,0),colors:[]},{leadColor:tp(0,255,128),colors:[]},{leadColor:tp(0,255,255),colors:[]},{leadColor:tp(0,127,255),colors:[]},{leadColor:tp(0,0,255),colors:[]},{leadColor:tp(127,0,255),colors:[]},{leadColor:tp(128,0,128),colors:[]},{leadColor:tp(255,0,128),colors:[]}];for(const r of e.map(op)){let e=500,n=0;t.forEach((t,o)=>{const s=(i=r,a=t.leadColor,Math.sqrt(Math.pow(i.r-a.r,2)+Math.pow(i.g-a.g,2)+Math.pow(i.b-a.b,2)));var i,a;e>s&&(e=s,n=o)}),t[n].colors.push(r)}return t.map(e=>e.colors.sort((e,t)=>ip(e).s-ip(t).s)).flat().map(np)}(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=Object.values(this.getters.getCells(e)),r=new Set;for(const e of t)e.style?.textColor&&r.add(e.style.textColor),e.style?.fillColor&&r.add(e.style.fillColor);for(const t of this.getters.getBordersColors(e))r.add(t);return[...r]}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(Xm(t.minimum.color)),r.push(t.midpoint?Xm(t.midpoint.color):void 0),r.push(Xm(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(nC)].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(!Jm(t))continue;const e=Qm(t);t&&!z.includes(e)&&this.history.update("customColors",e,!0)}}}).add("pivot_ui",class extends JE{static getters=["getPivot","getFirstPivotFunction","getPivotCellSortDirection","getPivotIdFromPosition","getPivotCellFromPosition","generateNewCalculatedMeasureName","isPivotUnused","isSpillPivotFormula"];pivots={};unusedPivots;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(ds.has(e.type))for(const e of this.getters.getPivotIds())zC.get(this.getters.getPivotCoreDefinition(e).type).externalData||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.unusedPivots=void 0;break;case"UNDO":case"REDO":{this.unusedPivots=void 0;const t=e.commands.filter(WC);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 HC)HC[e].set.clear(),HC[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 QE(e,RC)[0]}(t);if(!r)return;const{functionName:n,args:o}=r;return{functionName:n,args:o.map(t=>{if("EMPTY"===t.type)return;if("STRING"===t.type||"BOOLEAN"===t.type||"NUMBER"===t.type)return t.value;const r=TC(t);return this.getters.evaluateFormula(e,r)})}}getPivotCellFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||0===QE(t.compiledFormula.tokens,RC).length)return BE;const r=this.getters.getCellPosition(t.id),n=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!n)return BE;let{functionName:o,args:s}=n;const i=s[0];if(!i)return BE;const a=this.getters.getPivotId(i.toString());if(!a)return BE;const l=this.getPivot(a);if(!l.isValid())return BE;if("PIVOT"===o&&!t.content.replaceAll(" ","").toUpperCase().startsWith("=PIVOT"))return BE;if("PIVOT"===o){const t=Yd(this.getters.getPivotCoreDefinition(a),Vr(s[1]),Vr(s[2]),Vr(s[3]),Vr(s[4]),Vr(s[5]),this.getters.getLocale()),n=l.getCollapsedTableStructure().getPivotCells(t),o=e.col-r.col,i=e.row-r.row;return n[o][i]}try{const t=e.row-r.row,n=e.col-r.col;if(s=s.map(e=>O(e)?e[n][t]:e),"PIVOT.HEADER"===o&&"measure"===s.at(-2)){return{type:"MEASURE_HEADER",domain:l.parseArgsToPivotDomain(s.slice(1,-2).map(e=>({value:e}))),measure:s.at(-1)?.toString()||""}}if("PIVOT.HEADER"===o){const e=l.parseArgsToPivotDomain(s.slice(1).map(e=>({value:e})));return{type:"HEADER",domain:e,dimension:RE(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 BE}}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){return this._getUnusedPivots().includes(e)}getPivotCellSortDirection(e){const t=this.getters.getPivotIdFromPosition(e),r=this.getters.getPivotCellFromPosition(e);if("EMPTY"===r.type||"HEADER"===r.type||!t)return;const n=this.getters.getPivot(t),o=RE(n,r.domain).colDomain,s=n.definition.sortedColumn;return s?.measure===r.measure&&Ae(s.domain,o)?s.order:"none"}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){const r=this.getters.getPivotCoreDefinition(e);if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(r);else{const t=_C(zC.get(r.type).ui);this.pivots[e]=new t(this.custom,{definition:r,getters:this.getters})}}_getUnusedPivots(){if(void 0!==this.unusedPivots)return this.unusedPivots;const e=new Set(this.getters.getPivotIds());for(const t of this.getters.getSheetIds())for(const r in this.getters.getCells(t)){const t=this.getters.getCellPosition(r),n=this.getPivotIdFromPosition(t);if(n&&(e.delete(n),!e.size))return this.unusedPivots=[],[]}return this.unusedPivots=[...e],this.unusedPivots}}).add("cell_icon",class extends JE{static getters=["doesCellHaveGridIcon","getCellIcons","getCellIconRect"];cellIconsCache={};handle(e){"SET_VIEWPORT_OFFSET"!==e.type&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){const r=e.position,n=this.getters.getCell(r);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,n?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,r){const n=e.x,o=e.x+e.width;switch(t){case"right":return o-r.margin-r.size;case"left":return n+r.margin;default:const e=Math.floor((o-n-r.size)/2);return o-r.size-e}}computeCellIcons(e){const t={left:void 0,right:void 0,center:void 0},r=rC.getAll();for(const n of r){const r=n(this.getters,e);r&&(!t[r.horizontalAlign]||r.priority>t[r.horizontalAlign].priority)&&(t[r.horizontalAlign]=r)}if(t.center&&(t.left||t.right)){const e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(Se)}doesCellHaveGridIcon(e){return Boolean(this.getCellIcons(e).length)}});class ST{getters;providers=[];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){const t=Vm(e);t?.applyChange&&this.executeOnAllRanges(t.applyChange,t.sheetId,t.sheetName)}finalize(){}verifyRangeRemoved(e){return t=>{const r=e(t);return"NONE"===r.changeType||zo(r.range.zone)?r:{range:r.range,changeType:"REMOVE"}}}executeOnAllRanges(e,t,r){const n=this.verifyRangeRemoved(e);for(const e of this.providers)e(n,t,r)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,r,n){return e.map(e=>{if(!zo(e.zone))return e;const o=e.prefixSheet?e.sheetId:n,s=Om(e),i=_m(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($o(e.zone))return e;const t={...e.unboundedZone},r={...e.zone};let n=e.parts;if(void 0!==t.right&&t.right<t.left){const e=t.right;t.right=t.left,t.left=e,r.right=r.left,r.left=e,n=[{colFixed:n[1]?.colFixed||!1,rowFixed:n[0]?.rowFixed||!1},{colFixed:n[0]?.colFixed||!1,rowFixed:n[1]?.rowFixed||!1}]}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.bottom;t.bottom=t.top,t.top=e,r.bottom=r.top,r.top=e,n=[{colFixed:n[0]?.colFixed||!1,rowFixed:n[1]?.rowFixed||!1},{colFixed:n[1]?.colFixed||!1,rowFixed:n[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:r,parts:n,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}(xm({...e,sheetId:o,zone:a},this.getters.getSheetSize))})}removeRangesSheetPrefix(e,t){return t.map(t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t)}extendRange(e,t,r){const n="COL"===t?e.zone.right+r:e.zone.right,o="ROW"===t?e.zone.bottom+r:e.zone.bottom,s={left:e.zone.left,top:e.zone.top,right:Om(e)?void 0:n,bottom:_m(e)?void 0:o};return xm({...e,zone:s},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!ao.test(t)||!this.getters.tryGetSheet(e))return Am(t);const{sheetName:r}=go(t);return Rm({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)?Dm(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 xm({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){const r=e.map(e=>e.unboundedZone),n=t.map(e=>e.unboundedZone);return Fo(r,n).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){if(!this.getters.tryGetSheet(e._sheetId))return Am(w.InvalidReference);return xm({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}=go(e);return null!==t.match(ao)&&(!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 n=gm(t),o=n.dependencies.map(t=>{const n=this.getters.getRangeFromSheetXC(e,t),o=r(n);return"NONE"===o.changeType?n:o.range});return this.getters.getFormulaString(e,n.tokens,o)}copyFormulaStringForSheet(e,t,r,n){if(!r.startsWith("="))return r;const o=gm(r),s=o.dependencies.map(r=>{const o=this.getters.getRangeFromSheetXC(e,r);return"keepSameReference"===n?o:Fm(e,t,o)});return this.getters.getFormulaString(t,o.tokens,s)}}class CT{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})}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 TT{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new CT,this.anchor={cell:{col:0,row:0},zone:ss({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)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}modifyAnchor(e,t,r){const n=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(n,e.zone)},this.processEvent({options:r,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,"overrideSelection",t)}selectCell(e,t){const r=ss({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 Es("InvalidSelectionStep");const{col:r,row:n}=this.getNextAvailablePosition(e,t);return this.selectCell(r,n)}setAnchorCorner(e,t){const r=this.getters.getActiveSheetId(),{col:n,row:o}=this.anchor.cell,s={left:Math.min(n,e),top:Math.min(o,t),right:Math.max(n,e),bottom:Math.max(o,t)},i={zone:this.getters.expandZone(r,s),cell:{col:n,row:o}};return this.processEvent({mode:"updateAnchor",anchor:i,options:{scrollIntoView:!1}})}addCellToSelection(e,t){const r=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:r,col:e,row:t}));const n=this.getters.expandZone(r,ss({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:n,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new Es("InvalidSelectionStep");const r=this.getters.getActiveSheetId(),n=this.anchor,{col:o,row:s}=n.cell,{left:i,right:a,top:l,bottom:c}=n.zone,u=this.getStartingPosition(e),[h,d]=this.deltaToTarget(u,e,t);if(0===h&&0===d)return Es.Success;let f=n.zone;const g=e=>{e=ns(e);const{left:t,right:n,top:o,bottom:s}=this.getters.expandZone(r,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(r)-1,n),top:Math.max(0,o),bottom:Math.min(this.getters.getNumberRows(r)-1,s)}},{cell:m,zone:p}=this.getReferenceAnchor(),{col:b,row:v}=m;let y=0;for(;null!==f;){if(y++,h<0){const e=this.getNextAvailableCol(h,a-(y-1),v);f=p.right<=a-y?g({top:l,left:i,bottom:c,right:e}):null}if(h>0){const e=this.getNextAvailableCol(h,i+(y-1),v);f=i+y<=p.left?g({top:l,left:e,bottom:c,right:a}):null}if(d<0){const e=this.getNextAvailableRow(d,b,c-(y-1));f=p.bottom<=c-y?g({top:l,left:i,bottom:e,right:a}):null}if(d>0){const e=this.getNextAvailableRow(d,b,l+(y-1));f=l+y<=p.top?g({top:e,left:i,bottom:c,right:a}):null}if(f=f?ns(f):f,f&&!jo(f,n.zone))return this.processEvent({options:{scrollIntoView:!0},mode:"updateAnchor",anchor:{zone:f,cell:{col:o,row:s}}})}f=g(Zo({top:s,bottom:s,left:o,right:o},ns({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:o,row:s}};return this.processEvent({anchor:w,mode:"updateAnchor",options:{scrollIntoView:!0}})}selectColumn(e,t){const r=this.getters.getActiveSheetId(),n=this.getters.getNumberRows(r)-1;let o={left:e,right:e,top:0,bottom:n};const s=this.getters.findFirstVisibleColRowIndex(r,"ROW");let i,a;switch(t){case"overrideSelection":case"newAnchor":i=e,a=s;break;case"updateAnchor":({col:i,row:a}=this.anchor.cell),o=Zo(o,{left:i,right:i,top:s,bottom:n})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:o,cell:{col:i,row:a}},mode:t})}selectRow(e,t){const r=this.getters.getActiveSheetId(),n=this.getters.getNumberCols(r)-1;let o={top:e,bottom:e,left:0,right:n};const s=this.getters.findFirstVisibleColRowIndex(r,"COL");let i,a;switch(t){case"overrideSelection":case"newAnchor":i=s,a=e;break;case"updateAnchor":({col:i,row:a}=this.anchor.cell),o=Zo(o,{left:s,right:n,top:a,bottom:a})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:o,cell:{col:i,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(jo(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:ss(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 Es(r):(this.anchor=t.anchor,this.stream.send(t),Es.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:r}=e;if(!Qo(t.col,t.row,r))return"InvalidAnchorZone";const{left:n,right:o,top:s,bottom:i}=r,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",n,o);return void 0===this.getters.findVisibleHeader(a,"ROW",s,i)||void 0===l?"SelectionOutOfBound":"Success"}checkAnchorZoneOrThrow(e){if("InvalidAnchorZone"===this.checkAnchorZone(e))throw new Error("The provided anchor is invalid. The cell must be part of the zone.")}getNextAvailablePosition(e,t=1){const{col:r,row:n}=this.anchor.cell,o=this.deltaToTarget({col:r,row:n},e,t);return{col:this.getNextAvailableCol(o[0],r,n),row:this.getNextAvailableRow(o[1],r,n)}}getNextAvailableCol(e,t,r){const n=this.getters.getActiveSheetId(),o={col:t,row:r};return this.getNextAvailableHeader(e,"COL",t,o,e=>this.getters.isInSameMerge(n,t,r,e,r))}getNextAvailableRow(e,t,r){const n=this.getters.getActiveSheetId(),o={col:t,row:r};return this.getNextAvailableHeader(e,"ROW",r,o,e=>this.getters.isInSameMerge(n,t,r,t,e))}getNextAvailableHeader(e,t,r,n,o){const s=this.getters.getActiveSheetId();if(0===e)return r;const i=Math.sign(e);let a=r+e;for(;o(a);)a+=i;for(;this.getters.isHeaderHidden(s,t,a);)a+=i;return a<0||a>this.getters.getNumberHeaders(s,t)-1?this.getters.isHeaderHidden(s,t,r)?this.getNextAvailableHeader(-i,t,r,n,o):r:a}getReferenceAnchor(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:r,right:n,top:o,bottom:s}=t.zone,{col:i,row:a}=t.cell,l=this.getters.isColHidden(e,i)&&this.getters.findVisibleHeader(e,"COL",r,n)||i,c=this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",o,s)||a;return{cell:{col:l,row:c},zone:this.getters.expandZone(e,{left:l,right:l,top:c,bottom:c})}}deltaToTarget(e,t,r){switch(t){case"up":return"end"!==r?[0,-r]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==r?[0,r]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==r?[-r,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==r?[r,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:r}=this.getPosition();const n=this.anchor.zone;switch(e){case"down":case"up":r=r===n.top?n.bottom:n.top;break;case"left":case"right":t=t===n.right?n.left:n.right}return{col:t,row:r}}getEndOfCluster(e,t,r){const n=this.getters.getActiveSheetId();let o=e;const s=this.getNextCellPosition(e,t,r),i=this.isCellSkippableInCluster({...o,sheetId:n})||this.isCellSkippableInCluster({...s,sheetId:n})?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(o,t,r);if(o.col===e.col&&o.row===e.row)break;const s=this.isCellSkippableInCluster({...e,sheetId:n});if("endOfCluster"===i&&s)break;if("nextCluster"===i&&!s){o=e;break}o=e}return"cols"===t?o.col:o.row}getNextCellPosition(e,t,r){const n={...e};return n["cols"===t?"col":"row"]="cols"===t?this.getNextAvailableCol(r,n.col,n.row):this.getNextAvailableRow(r,n.col,n.row),{col:n.col,row:n.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){const t=this.getters.getMainCellPosition(e),r=this.getters.getEvaluatedCell(t);return r.type===Eu.empty||r.type===Eu.text&&""===r.value}}class IT{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let r=e[0];const n=e.at(-1),o=e.length-2;for(let t=1;t<=o;t++){const n=e[t];if(void 0===r[n]){const o=e[t+1];r[n]=yo(o)}r=r[n]}r[n]!==t&&(this.changes?.push({key:n,target:r,before:r[n]}),void 0===t?delete r[n]:r[n]=t)}}function xT(e){return 8===(e=Qm(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}const RT=17781237,AT=17781238,_T=88853993,OT=88853994;function DT(e,t,r){const n=[["xmlns:r",Sb],["xmlns:a",lb],["xmlns:c",cb]],o=FT({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let s=Fw``;if(e.data.title?.text){const t=xT(Mb(e.data.backgroundColor)),r=e.data.title.fontSize??B;s=Fw`
|
|
4
4
|
<c:title>
|
|
@@ -814,4 +814,4 @@
|
|
|
814
814
|
<tableParts count="${e.tables.length}">
|
|
815
815
|
${Dw(a)}
|
|
816
816
|
</tableParts>
|
|
817
|
-
`}var _I;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(_I||(_I={}));function OI(e,t={}){const r=re(t);return r.type=e,r}const DI={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},FI=Ue(()=>Object.keys(DI).sort((e,t)=>DI[e]-DI[t]));const NI={};e.BadExpressionError=C,e.BasePlugin=Ts,e.CellErrorType=w,e.CircularDependencyError=T,e.DEFAULT_LOCALE=Dl,e.DEFAULT_LOCALES=Ol,e.DivisionByZeroError=_,e.EvaluationError=S,e.FunctionCodeBuilder=t,e.FunctionRegistry=Hg,e.InvalidReferenceError=I,e.Model=class extends ym{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},r=[],n=new wo,o=!1){const s=performance.now();console.debug("##### Model creation #####"),super(),b(),r=cE(e,r);const i=iE(e,o);this.state=new IT,this.uuidGenerator=n,this.config=this.setupConfig(t),this.session=this.setupSession(i.revisionId),this.coreGetters={},this.range=new ST(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 TT(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 vT.getAll())this.setupCorePlugin(e,i);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(const e of ET.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of wT.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of yT.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 Gb(ev({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 bm,n="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:n?new vm(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(Ol));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=ws(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>"Success"!==e)?new Es(t.flat()):Es.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(OI(e,t));dispatch=(e,t)=>{const r=OI(e,t),n=this.status;if(this.getters.isReadonly()&&(o=r,!vs.has(o.type)))return new Es("Readonly");var o;if(!this.session.canApplyOptimisticUpdate())return new Es("WaitingSessionConfirmation");switch(n){case 0:const t=this.checkDispatchAllowed(r);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:n,commands:o}=this.state.recordChanges(()=>{const t=performance.now();ws(r)&&this.state.addCommand(r),this.dispatchToHandlers(this.handlers,r),this.finalize();const n=performance.now()-t;n>5&&console.debug(e,n,"ms")});this.session.save(r,o,n),this.status=0,this.trigger("update");break;case 1:if(ws(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(ws(r))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,r)}return Es.Success};dispatchFromCorePlugin=(e,t)=>{const r=OI(e,t),n=this.status;this.status=2;const o=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(o,r),this.status=n,Es.Success};dispatchToHandlers(e,t){const r=ws(t);for(const n of e)!r&&n instanceof gE||n.beforeHandle(t);for(const n of e)!r&&n instanceof gE||n.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const r=this.renderers[t];if(r)for(const n of r)e.ctx.save(),n.drawLayer(e,t),e.ctx.restore()}exportData(){let e=dE();for(const t of this.handlers)t instanceof gE&&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=sE,r="Sheet1",{...hE(t,r),charts:[],images:[],cellValues:{}})]};var t,r;for(const t of this.handlers)t instanceof Ts&&await t.exportForExcel(e);return e=re(e),RI(e)}},e.NotAvailableError=x,e.OPERATOR_MAP=hm,e.OP_PRIORITY=Jg,e.OrderedLayers=FI,e.POSTFIX_UNARY_OPERATORS=Fl,e.Registry=h,e.Scope=n,e.SplillBlockedError=A,e.StateObserver=IT,e.TokenizingChars=Ze,e.UNARY_OPERATOR_MAP=dm,e.UnknownFunctionError=R,e.UuidGenerator=wo,e.__info__=NI,e._t=v,e.addRenderingLayer=function(e,t){if(DI[e])throw new Error(`Layer ${e} already exists`);DI[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=zg,e.cellReference=to,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=gm,e.compileTokens=mm,e.concat=Ie,e.convertAstNodes=im,e.createEmptyStructure=yo,e.debounce=Te,e.deepCopy=re,e.deepEquals=Ae,e.deepEqualsArray=Oe,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=fm,e.getAddHeaderStartIndex=Re,e.getCanonicalSymbolName=se,e.getFormulaNumberRegex=Rt,e.getFullReference=mo,e.getSearchRegex=function(e,t){let r=te(e);const n=t.matchCase?"":"i";return t.exactMatch&&(r=`^${r}$`),RegExp(r,n)},e.getUniqueText=Xe,e.getUnquotedSheetName=ne,e.groupConsecutive=ce,e.includesAll=De,e.insertItemsAtIndex=Be,e.isBoolean=he,e.isColHeader=uo,e.isColReference=lo,e.isConsecutive=ke,e.isDefined=Se,e.isFormula=Ke,e.isMarkdownLink=ge,e.isMatrix=O,e.isNotNull=function(e){return null!==e},e.isNumber=_t,e.isNumberBetween=Ge,e.isObjectEmptyRecursive=Ce,e.isRowHeader=ho,e.isRowReference=co,e.isSheetUrl=ye,e.isSingleCellReference=fo,e.isWebLink=me,e.iterateAstNodes=am,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}=go(e.value),[n,o]=t.split(":"),s=po(n),i=o?`:${po(o)}`:"";return{...e,value:mo(r,s+i)}},e.mapAst=cm,e.markdownLink=pe,e.memoize=Ue,e.parse=om,e.parseMarkdownLink=be,e.parseNumber=Dt,e.parseSheetUrl=Ee,e.parseTokens=sm,e.percentile=Ft,e.range=le,e.rangeReference=ao,e.rangeTokenize=Yg,e.removeDuplicates=Ye,e.removeFalsyAttributes=Fe,e.removeIndexesFromArray=He,e.replaceItemAtIndex=ze,e.replaceNewLines=Pe,e.sanitizeSheetName=ie,e.setDefaultTranslationMethod=b,e.setTranslationMethod=function(e,t=()=>!0){g=e,m=t},e.setXcToFixedReferenceType=bo,e.specialWhiteSpaceRegexp=Me,e.splitReference=go,e.tokenize=Ml,e.transpose2dPOJO=je,e.trimContent=$e,e.unquote=oe,e.whiteSpaceCharacters=Le,NI.version="19.1.0-alpha.3",NI.date="2025-10-23T08:19:27.355Z",NI.hash="78717d4"}(this.o_spreadsheet_engine=this.o_spreadsheet_engine||{});
|
|
817
|
+
`}var _I;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(_I||(_I={}));function OI(e,t={}){const r=re(t);return r.type=e,r}const DI={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},FI=Ue(()=>Object.keys(DI).sort((e,t)=>DI[e]-DI[t]));const NI={};e.BadExpressionError=C,e.BasePlugin=Ts,e.CellErrorType=w,e.CircularDependencyError=T,e.DEFAULT_LOCALE=Dl,e.DEFAULT_LOCALES=Ol,e.DivisionByZeroError=_,e.EvaluationError=S,e.FunctionCodeBuilder=t,e.FunctionRegistry=Hg,e.InvalidReferenceError=I,e.Model=class extends ym{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},r=[],n=new wo,o=!1){const s=performance.now();console.debug("##### Model creation #####"),super(),b(),r=cE(e,r);const i=iE(e,o);this.state=new IT,this.uuidGenerator=n,this.config=this.setupConfig(t),this.session=this.setupSession(i.revisionId),this.coreGetters={},this.range=new ST(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 TT(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 vT.getAll())this.setupCorePlugin(e,i);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(const e of ET.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of wT.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of yT.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 Gb(ev({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 bm,n="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:n?new vm(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(Ol));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=ws(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>"Success"!==e)?new Es(t.flat()):Es.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(OI(e,t));dispatch=(e,t)=>{const r=OI(e,t),n=this.status;if(this.getters.isReadonly()&&(o=r,!vs.has(o.type)))return new Es("Readonly");var o;if(!this.session.canApplyOptimisticUpdate())return new Es("WaitingSessionConfirmation");switch(n){case 0:const t=this.checkDispatchAllowed(r);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:n,commands:o}=this.state.recordChanges(()=>{const t=performance.now();ws(r)&&this.state.addCommand(r),this.dispatchToHandlers(this.handlers,r),this.finalize();const n=performance.now()-t;n>5&&console.debug(e,n,"ms")});this.session.save(r,o,n),this.status=0,this.trigger("update");break;case 1:if(ws(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(ws(r))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,r)}return Es.Success};dispatchFromCorePlugin=(e,t)=>{const r=OI(e,t),n=this.status;this.status=2;const o=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(o,r),this.status=n,Es.Success};dispatchToHandlers(e,t){const r=ws(t);for(const n of e)!r&&n instanceof gE||n.beforeHandle(t);for(const n of e)!r&&n instanceof gE||n.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const r=this.renderers[t];if(r)for(const n of r)e.ctx.save(),n.drawLayer(e,t),e.ctx.restore()}exportData(){let e=dE();for(const t of this.handlers)t instanceof gE&&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=sE,r="Sheet1",{...hE(t,r),charts:[],images:[],cellValues:{}})]};var t,r;for(const t of this.handlers)t instanceof Ts&&await t.exportForExcel(e);return e=re(e),RI(e)}},e.NotAvailableError=x,e.OPERATOR_MAP=hm,e.OP_PRIORITY=Jg,e.OrderedLayers=FI,e.POSTFIX_UNARY_OPERATORS=Fl,e.Registry=h,e.Scope=n,e.SplillBlockedError=A,e.StateObserver=IT,e.TokenizingChars=Ze,e.UNARY_OPERATOR_MAP=dm,e.UnknownFunctionError=R,e.UuidGenerator=wo,e.__info__=NI,e._t=v,e.addRenderingLayer=function(e,t){if(DI[e])throw new Error(`Layer ${e} already exists`);DI[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=zg,e.cellReference=to,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=gm,e.compileTokens=mm,e.concat=Ie,e.convertAstNodes=im,e.createEmptyStructure=yo,e.debounce=Te,e.deepCopy=re,e.deepEquals=Ae,e.deepEqualsArray=Oe,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=fm,e.getAddHeaderStartIndex=Re,e.getCanonicalSymbolName=se,e.getFormulaNumberRegex=Rt,e.getFullReference=mo,e.getSearchRegex=function(e,t){let r=te(e);const n=t.matchCase?"":"i";return t.exactMatch&&(r=`^${r}$`),RegExp(r,n)},e.getUniqueText=Xe,e.getUnquotedSheetName=ne,e.groupConsecutive=ce,e.includesAll=De,e.insertItemsAtIndex=Be,e.isBoolean=he,e.isColHeader=uo,e.isColReference=lo,e.isConsecutive=ke,e.isDefined=Se,e.isFormula=Ke,e.isMarkdownLink=ge,e.isMatrix=O,e.isNotNull=function(e){return null!==e},e.isNumber=_t,e.isNumberBetween=Ge,e.isObjectEmptyRecursive=Ce,e.isRowHeader=ho,e.isRowReference=co,e.isSheetUrl=ye,e.isSingleCellReference=fo,e.isWebLink=me,e.iterateAstNodes=am,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}=go(e.value),[n,o]=t.split(":"),s=po(n),i=o?`:${po(o)}`:"";return{...e,value:mo(r,s+i)}},e.mapAst=cm,e.markdownLink=pe,e.memoize=Ue,e.parse=om,e.parseMarkdownLink=be,e.parseNumber=Dt,e.parseSheetUrl=Ee,e.parseTokens=sm,e.percentile=Ft,e.range=le,e.rangeReference=ao,e.rangeTokenize=Yg,e.removeDuplicates=Ye,e.removeFalsyAttributes=Fe,e.removeIndexesFromArray=He,e.replaceItemAtIndex=ze,e.replaceNewLines=Pe,e.sanitizeSheetName=ie,e.setDefaultTranslationMethod=b,e.setTranslationMethod=function(e,t=()=>!0){g=e,m=t},e.setXcToFixedReferenceType=bo,e.specialWhiteSpaceRegexp=Me,e.splitReference=go,e.tokenize=Ml,e.transpose2dPOJO=je,e.trimContent=$e,e.unquote=oe,e.whiteSpaceCharacters=Le,NI.version="19.1.0-alpha.3",NI.date="2025-10-23T11:12:13.207Z",NI.hash="bd756dd"}(this.o_spreadsheet_engine=this.o_spreadsheet_engine||{});
|