cenitu-table 0.2.0 → 0.3.0

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.
@@ -0,0 +1,184 @@
1
+ "use strict";var jn=Object.defineProperty;var Yn=(s,t,e)=>t in s?jn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var v=(s,t,e)=>Yn(s,typeof t!="symbol"?t+"":t,e);const O=(s,t,e=0)=>e*17179869184+s*16384+t,De=s=>{const t=Math.floor(s/17179869184),e=s-t*17179869184;return{row:Math.floor(e/16384),col:e%16384,sheet:t}};function Tt(s){let t="",e=s+1;for(;e>0;){const n=(e-1)%26;t=String.fromCharCode(65+n)+t,e=Math.floor((e-1)/26)}return t}function se(s){let t=0;for(const e of s.toUpperCase()){const n=e.charCodeAt(0);if(n<65||n>90)return-1;t=t*26+(n-64)}return t-1}const Kn=/^\$?([A-Za-z]{1,3})\$?(\d+)$/;function je(s){const t=Kn.exec(s.trim());if(!t)return;const e=se(t[1]),n=Number(t[2])-1;if(!(e<0||e>=16384||n<0||n>=1048576))return{row:n,col:e}}const Ne=({row:s,col:t})=>`${Tt(t)}${s+1}`;function js(s,t){return{start:{row:Math.min(s.row,t.row),col:Math.min(s.col,t.col)},end:{row:Math.max(s.row,t.row),col:Math.max(s.col,t.col)}}}const qn=(s,t,e)=>t>=s.start.row&&t<=s.end.row&&e>=s.start.col&&e<=s.end.col,Zn=/^[\p{L}_][\p{L}\p{N}_.]*$/u;function Ys(s){return Zn.test(s)&&!je(s)&&!/^(TRUE|FALSE)$/i.test(s)?s:`'${s.replace(/'/g,"''")}'`}function ue(s,t={}){var r,o;const e=s.rowAbs?s.row:s.row+(((r=t.base)==null?void 0:r.row)??0),n=s.colAbs?s.col:s.col+(((o=t.base)==null?void 0:o.col)??0);return e<0||n<0?"#REF!":`${s.colAbs?"$":""}${Tt(n)}${s.rowAbs?"$":""}${e+1}`}function as(s,t){var e;return s.sheet===void 0?"":Ys(((e=t.sheetName)==null?void 0:e.call(t,s.sheet))??`Sheet${s.sheet+1}`)+"!"}function Qt(s,t={}){const e=n=>Qt(n,t);switch(s.type){case"number":return String(s.value);case"string":return`"${s.value.replace(/"/g,'""')}"`;case"bool":return s.value?"TRUE":"FALSE";case"error":return s.code;case"ref":{const n=ue(s,t);return n==="#REF!"?n:as(s,t)+n}case"range":{const n=ue(s.start,t),r=ue(s.end,t);return n==="#REF!"||r==="#REF!"?"#REF!":`${as(s.start,t)}${n}:${r}`}case"name":return s.name;case"unary":return s.op+e(s.arg);case"percent":return e(s.arg)+"%";case"binary":return e(s.left)+s.op+e(s.right);case"paren":return`(${e(s.expr)})`;case"call":return`${s.name}(${s.args.map(e).join(",")})`}}function lt(s,t){switch(s.type){case"ref":case"range":case"name":return t(s);case"unary":case"percent":return lt(s.arg,t);case"binary":return lt(s.left,t),lt(s.right,t);case"paren":return lt(s.expr,t);case"call":for(const e of s.args)lt(e,t)}}function Nt(s,t){switch(s.type){case"unary":case"percent":return Nt(s.arg,t);case"binary":return Nt(s.left,t),Nt(s.right,t);case"paren":return Nt(s.expr,t);case"call":t(s.name);for(const e of s.args)Nt(e,t)}}function $t(s,t){switch(s.type){case"ref":case"range":case"name":return t(s);case"unary":case"percent":return s.arg=$t(s.arg,t),s;case"binary":return s.left=$t(s.left,t),s.right=$t(s.right,t),s;case"paren":return s.expr=$t(s.expr,t),s;case"call":for(let e=0;e<s.args.length;e++)s.args[e]=$t(s.args[e],t);return s;default:return s}}const Ks=["#DIV/0!","#VALUE!","#REF!","#NAME?","#N/A","#NUM!","#NULL!","#ERROR!","#CYCLE!","#SPILL!","#CALC!"];class ct{constructor(t,e){this.code=t,this.message=e}toString(){return this.code}}class L{constructor(t,e){this.values=t,this.origin=e}get height(){return this.values.length}get width(){var t;return((t=this.values[0])==null?void 0:t.length)??0}*flat(){for(const t of this.values)yield*t}}const g=s=>s instanceof ct,S=(s,t)=>new ct(s,t);function X(s){return typeof s=="string"&&s.length>1&&s[0]==="="}function at(s){if(s==null||s==="")return null;if(typeof s!="string")return s;if(s[0]==="'")return s.slice(1);const t=Ct(s);if(t!==void 0)return t;const e=s.toUpperCase();return e==="TRUE"?!0:e==="FALSE"?!1:s}const Gn=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?%?$/;function Ct(s){const t=s.trim();if(Gn.test(t))return t.endsWith("%")?Number(t.slice(0,-1))/100:Number(t)}function B(s){return!Number.isFinite(s)||Number.isInteger(s)?s:Number(s.toPrecision(15))}function q(s){if(g(s))return s;if(s===null)return 0;if(typeof s=="number")return s;if(typeof s=="boolean")return s?1:0;const t=Ct(s);return t===void 0?S("#VALUE!",`"${s}" is not a number`):t}function rt(s){return g(s)?s:s===null?"":typeof s=="boolean"?s?"TRUE":"FALSE":typeof s=="number"?Ye(s):s}function dt(s){if(g(s))return s;if(s===null)return!1;if(typeof s=="boolean")return s;if(typeof s=="number")return s!==0;const t=s.toUpperCase();return t==="TRUE"?!0:t==="FALSE"?!1:S("#VALUE!",`"${s}" is not a boolean`)}function Ye(s){return String(B(s))}function T(s){return s instanceof L?s.height===1&&s.width===1?s.values[0][0]:S("#VALUE!","Range used where a single value is expected"):s}const cs=s=>typeof s=="number"?0:typeof s=="string"?1:2;function V(s,t){s===null&&(s=t===null?0:typeof t=="string"?"":typeof t=="boolean"?!1:0),t===null&&(t=typeof s=="string"?"":typeof s=="boolean"?!1:0);const e=cs(s),n=cs(t);if(e!==n)return e-n;if(typeof s=="string"){const i=s.toLowerCase(),l=t.toLowerCase();return i<l?-1:i>l?1:0}const r=Number(s),o=Number(t);return r<o?-1:r>o?1:0}const qs=s=>s instanceof L&&(s.height!==1||s.width!==1),tt=s=>s instanceof L?s:new L([[s]]);function At(s,t){let e=0,n=0;for(const o of s)qs(o)&&(e=Math.max(e,o.height),n=Math.max(n,o.width));if(e===0)return t(...s.map(T));const r=[];for(let o=0;o<e;o++){const i=[];for(let l=0;l<n;l++)i.push(t(...s.map(a=>Qn(a,o,l))));r.push(i)}return new L(r)}function Qn(s,t,e){if(!(s instanceof L))return s;const n=s.height===1?0:t,r=s.width===1?0:e;return n<s.height&&r<s.width?s.values[n][r]:S("#N/A")}const Zs=(s,t)=>s.values.map(e=>e[t]);function $e(s){return new L(Array.from({length:s.width},(t,e)=>Zs(s,e)))}const ne=new Map;function x(s,t){const e=typeof t=="function"?{impl:t}:t;ne.set(s.toUpperCase(),er(s.toUpperCase(),e))}function Jn(s){ne.delete(s.toUpperCase())}const Le=s=>ne.get(s.toUpperCase()),tr=()=>[...ne.keys()].sort();function er(s,t){const{minArgs:e=0,maxArgs:n=1/0}=t,r=o=>o<e||o>n?S("#VALUE!",`Wrong number of arguments to ${s}`):void 0;return{...t,impl:t.impl&&((o,i)=>r(o.length)??t.impl(o,i)),lazy:t.lazy&&((o,i)=>r(o.length)??t.lazy(o,i))}}const Q=s=>q(T(s));function wt(s){const t=[];for(const e of s)if(e instanceof L)for(const n of e.flat()){if(g(n))return n;typeof n=="number"&&t.push(n)}else{if(e===null)continue;const n=q(e);if(g(n))return n;t.push(n)}return t}function G(s){return t=>At(t,(...e)=>{const n=[];for(const o of e){const i=q(o);if(g(i))return i;n.push(i)}const r=s(...n);return g(r)?r:Number.isFinite(r)?B(r):S("#NUM!")})}function Vt(s){return t=>At(t,(...e)=>{const n=[];for(const r of e){const o=rt(r);if(g(o))return o;n.push(o)}return s(...n)})}const mt=s=>s instanceof L?s:new L([[s]]);class re{constructor(){v(this,"sum",0);v(this,"comp",0)}add(t){const e=this.sum+t;this.comp+=Math.abs(this.sum)>=Math.abs(t)?this.sum-e+t:t-e+this.sum,this.sum=e}get value(){return this.sum+this.comp}}const Jt=s=>{const t=new re;return s.forEach(e=>t.add(e)),t.value};function sr(s,t){const e=Math.pow(10,Math.trunc(t));return B(Math.sign(s)*Math.round(Math.abs(s)*e+1e-9)/e)}function Ke(s,t=!0){let e="";for(let n=0;n<s.length;n++){const r=s[n];r==="~"&&n+1<s.length?e+=hs(s[++n]):r==="*"?e+="[\\s\\S]*":r==="?"?e+="[\\s\\S]":e+=hs(r)}return new RegExp(t?`^${e}$`:e,"i")}const hs=s=>s.replace(/[.*+?^${}()|[\]\\/-]/g,"\\$&"),Gs=s=>/[*?~]/.test(s);function qe(s){if(typeof s!="string")return r=>r!==null&&!g(r)&&V(r,s)===0;const t=/^(<=|>=|<>|=|<|>)?(.*)$/s.exec(s),e=t[1]??"=",n=at(t[2]);if(n===null)return e==="<>"?r=>r!==null&&r!=="":r=>r===null||r==="";if(typeof n=="string"&&(e==="="||e==="<>")&&Gs(n)){const r=Ke(n);return e==="="?o=>typeof o=="string"&&r.test(o):o=>!(typeof o=="string"&&r.test(o))}return r=>{if(g(r)||e!=="="&&e!=="<>"&&(r===null||typeof r!=typeof n)||e==="="&&r===null)return!1;const o=V(r,n);switch(e){case"=":return o===0;case"<>":return o!==0;case"<":return o<0;case"<=":return o<=0;case">":return o>0;default:return o>=0}}}function Qs(s,t){let e=0,n=s.length-1,r=-1;for(;e<=n;){const o=e+n>>1,i=s[o];i===null||V(i,t)<=0?(i!==null&&typeof i==typeof t&&(r=o),e=o+1):n=o-1}return r}function Js(s,t){const e=typeof t=="string"?qe("="+t):void 0;return s.findIndex(n=>e?e(n):n!==null&&!g(n)&&V(n,t)===0)}function tn(s,t){const e=T(s[0]);if(g(e))return e;const n=mt(s[1]),r=Q(s[2]);if(g(r))return r;const o=s.length>3?dt(T(s[3])):!0;if(g(o))return o;const i=t?n.width:n.height,l=Math.trunc(r);if(l<1)return S("#VALUE!");if(l>i)return S("#REF!");const a=t?n.values.map(h=>h[0]):n.values[0],c=o?Qs(a,e):Js(a,e);return c<0?S("#N/A"):t?n.values[c][l-1]:n.values[l-1][c]}function Ze(s,t){var a;const e=mt(s[0]),n=T(s[1]);if(g(n))return n;const r=s[2]!==void 0?mt(s[2]):e,o=qe(n),i=new re;let l=0;for(let c=0;c<e.height;c++)for(let h=0;h<e.width;h++){if(!o(e.values[c][h]))continue;if(t==="count"){l++;continue}const u=((a=r.values[c])==null?void 0:a[h])??null;if(g(u))return u;typeof u=="number"&&(i.add(u),l++)}return t==="count"?l:t==="sum"?B(i.value):l===0?S("#DIV/0!"):B(i.value/l)}x("SUM",{aggregate:!0,impl:s=>{const t=wt(s);return g(t)?t:B(Jt(t))}});x("AVERAGE",{minArgs:1,aggregate:!0,impl:s=>{const t=wt(s);return g(t)?t:t.length===0?S("#DIV/0!"):B(Jt(t)/t.length)}});x("MIN",{aggregate:!0,impl:s=>{const t=wt(s);return g(t)?t:t.length?Math.min(...t):0}});x("MAX",{aggregate:!0,impl:s=>{const t=wt(s);return g(t)?t:t.length?Math.max(...t):0}});x("COUNT",{aggregate:!0,impl:s=>{let t=0;for(const e of s)if(e instanceof L)for(const n of e.flat())typeof n=="number"&&t++;else e!==null&&!g(q(e))&&t++;return t}});x("COUNTA",{aggregate:!0,impl:s=>{let t=0;for(const e of s)if(e instanceof L)for(const n of e.flat())n!==null&&t++;else e!==null&&t++;return t}});x("COUNTBLANK",{minArgs:1,maxArgs:1,impl:([s])=>{let t=0;for(const e of mt(s).flat())(e===null||e==="")&&t++;return t}});x("IF",{minArgs:2,maxArgs:3,lazy:(s,t)=>{const e=t.evaluate(s[0]);if(qs(e)){const r=t.evaluate(s[1]),o=s.length>2?t.evaluate(s[2]):!1;return At([e,r,o],(i,l,a)=>{const c=dt(i);return g(c)?c:c?l:a})}const n=dt(T(e));return g(n)?n:n?t.evaluate(s[1]):s.length>2?t.evaluate(s[2]):!1}});x("IFERROR",{minArgs:2,maxArgs:2,lazy:(s,t)=>{const e=t.evaluate(s[0]);return g(e)?t.evaluate(s[1]):e}});x("IFNA",{minArgs:2,maxArgs:2,lazy:(s,t)=>{const e=t.evaluate(s[0]);return g(e)&&e.code==="#N/A"?t.evaluate(s[1]):e}});function Ge(s,t,e){let n=e,r=!1;for(const o of s){const i=o instanceof L?[...o.flat()].filter(l=>typeof l!="string"&&l!==null):[o];for(const l of i){const a=dt(l);if(g(a))return a;n=t(n,a),r=!0}}return r?n:S("#VALUE!")}x("AND",{minArgs:1,aggregate:!0,impl:s=>Ge(s,(t,e)=>t&&e,!0)});x("OR",{minArgs:1,aggregate:!0,impl:s=>Ge(s,(t,e)=>t||e,!1)});x("NOT",{minArgs:1,maxArgs:1,impl:([s])=>{const t=dt(T(s));return g(t)?t:!t}});x("ABS",{minArgs:1,maxArgs:1,impl:G(Math.abs)});x("INT",{minArgs:1,maxArgs:1,impl:G(Math.floor)});x("SQRT",{minArgs:1,maxArgs:1,impl:G(Math.sqrt)});x("POWER",{minArgs:2,maxArgs:2,impl:G(Math.pow)});x("PI",{maxArgs:0,impl:()=>Math.PI});x("MOD",{minArgs:2,maxArgs:2,impl:s=>{const[t,e]=s.map(Q);return g(t)?t:g(e)?e:e===0?S("#DIV/0!"):B(t-e*Math.floor(t/e))}});x("ROUND",{minArgs:1,maxArgs:2,impl:G((s,t=0)=>sr(s,t))});x("ROUNDUP",{minArgs:1,maxArgs:2,impl:G((s,t=0)=>{const e=Math.pow(10,Math.trunc(t));return Math.sign(s)*Math.ceil(Math.abs(s)*e-1e-9)/e})});x("ROUNDDOWN",{minArgs:1,maxArgs:2,impl:G((s,t=0)=>{const e=Math.pow(10,Math.trunc(t));return Math.sign(s)*Math.floor(Math.abs(s)*e+1e-9)/e})});x("CONCATENATE",{minArgs:1,impl:Vt((...s)=>s.join(""))});x("CONCAT",{minArgs:1,impl:s=>{let t="";for(const e of s)for(const n of mt(e).flat()){const r=rt(n);if(g(r))return r;t+=r}return t}});x("LEN",{minArgs:1,maxArgs:1,impl:Vt(s=>s.length)});x("UPPER",{minArgs:1,maxArgs:1,impl:Vt(s=>s.toUpperCase())});x("LOWER",{minArgs:1,maxArgs:1,impl:Vt(s=>s.toLowerCase())});x("TRIM",{minArgs:1,maxArgs:1,impl:Vt(s=>s.trim().replace(/ {2,}/g," "))});x("LEFT",{minArgs:1,maxArgs:2,impl:s=>{const t=rt(T(s[0])),e=s.length>1?Q(s[1]):1;return g(t)?t:g(e)?e:e<0?S("#VALUE!"):t.slice(0,e)}});x("RIGHT",{minArgs:1,maxArgs:2,impl:s=>{const t=rt(T(s[0])),e=s.length>1?Q(s[1]):1;return g(t)?t:g(e)?e:e<0?S("#VALUE!"):e===0?"":t.slice(-e)}});x("MID",{minArgs:3,maxArgs:3,impl:s=>{const t=rt(T(s[0])),e=Q(s[1]),n=Q(s[2]);return g(t)?t:g(e)?e:g(n)?n:e<1||n<0?S("#VALUE!"):t.substr(e-1,n)}});x("ISBLANK",{minArgs:1,maxArgs:1,impl:([s])=>T(s)===null});x("ISNUMBER",{minArgs:1,maxArgs:1,impl:([s])=>typeof T(s)=="number"});x("ISTEXT",{minArgs:1,maxArgs:1,impl:([s])=>typeof T(s)=="string"});x("ISERROR",{minArgs:1,maxArgs:1,impl:([s])=>g(T(s))});x("NA",{maxArgs:0,impl:()=>S("#N/A")});x("VLOOKUP",{minArgs:3,maxArgs:4,impl:s=>tn(s,!0)});x("HLOOKUP",{minArgs:3,maxArgs:4,impl:s=>tn(s,!1)});x("INDEX",{minArgs:2,maxArgs:3,impl:s=>{const t=mt(s[0]),e=Q(s[1]),n=s.length>2?Q(s[2]):1;if(g(e))return e;if(g(n))return n;const[r,o]=t.height===1&&s.length===2?[1,e]:[e,n];return r<1||o<1||r>t.height||o>t.width?S("#REF!"):t.values[r-1][o-1]}});x("MATCH",{minArgs:2,maxArgs:3,impl:s=>{const t=T(s[0]);if(g(t))return t;const e=mt(s[1]);if(e.height>1&&e.width>1)return S("#N/A");const n=[...e.flat()],r=s.length>2?Q(s[2]):1;if(g(r))return r;let o;if(r===0)o=Js(n,t);else if(r>0)o=Qs(n,t);else{o=-1;for(let i=0;i<n.length&&(n[i]!==null&&V(n[i],t)>=0);i++)o=i}return o<0?S("#N/A"):o+1}});x("SUMIF",{minArgs:2,maxArgs:3,impl:s=>Ze(s,"sum")});x("COUNTIF",{minArgs:2,maxArgs:2,impl:s=>Ze(s,"count")});x("AVERAGEIF",{minArgs:2,maxArgs:3,impl:s=>Ze(s,"average")});x("SUMPRODUCT",{minArgs:1,impl:s=>{const t=s.map(mt),{height:e,width:n}=t[0];if(t.some(o=>o.height!==e||o.width!==n))return S("#VALUE!");const r=new re;for(let o=0;o<e;o++)for(let i=0;i<n;i++){let l=1;for(const a of t){const c=a.values[o][i];if(g(c))return c;l*=typeof c=="number"?c:0}r.add(l)}return B(r.value)}});const Qe=864e5,en=25569,te=60;function sn(s,t,e){const n=new Date(0);return n.setUTCFullYear(s,t-1,e),n}function nn(s,t){return sn(s,t+1,0).getUTCDate()}function zt(s,t,e){if(s===1900&&t===2&&e===29)return te;const n=Math.round(sn(s,t,e).getTime()/Qe)+en;return n<=te?n-1:n}function gt(s){const t=Math.floor(s);if(t===te)return{year:1900,month:2,day:29};const e=new Date(((t<te?t+1:t)-en)*Qe);return{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}}const nr=/^(\d{4})-(\d{1,2})-(\d{1,2})$/,rr=/^(\d{1,2})([./])(\d{1,2})\2(\d{4})$/;function oe(s){const t=s.trim();let e=nr.exec(t),n;if(e?n=[Number(e[1]),Number(e[2]),Number(e[3])]:(e=rr.exec(t))&&(n=[Number(e[4]),Number(e[3]),Number(e[1])]),!n)return;const[r,o,i]=n;if(!(r<1900||o<1||o>12||i<1||i>nn(r,o)))return zt(r,o,i)}const bt=(s,t=2)=>String(s).padStart(t,"0");function Je(s,t="YYYY-MM-DD"){const{year:e,month:n,day:r}=gt(s),o=Math.round((s-Math.floor(s))*86400),i={YYYY:bt(e,4),YY:bt(e%100),MM:bt(n),M:String(n),DD:bt(r),D:String(r),HH:bt(Math.floor(o/3600)%24),mm:bt(Math.floor(o/60)%60),ss:bt(o%60)};return t.replace(/YYYY|YY|MM|M|DD|D|HH|mm|ss/g,l=>i[l])}function rn(s,t=new Date){const e=zt(t.getFullYear(),t.getMonth()+1,t.getDate());if(!s)return e;const n=((t.getHours()*60+t.getMinutes())*60+t.getSeconds())*1e3+t.getMilliseconds();return e+n/Qe}let on=()=>new Date,ln=Math.random;function or(s){on=s??(()=>new Date)}function ir(s){ln=s??Math.random}const an=()=>on(),cn=()=>ln();function St(s){const t=T(s);if(typeof t=="string"){const n=oe(t);if(n!==void 0)return n}const e=q(t);return g(e)?e:e<0?S("#NUM!","Negative date"):Math.floor(e)}function ie(s){const t=q(T(s));return g(t)?t:Math.trunc(t)}function lr(s,t){const e=[];for(const n of s){const r=t(n);if(g(r))return r;e.push(r)}return e}const ts=s=>t=>{const e=St(t[0]);return g(e)?e:s(gt(e))};function hn(s,t,e){const{year:n,month:r,day:o}=gt(s),i=n*12+(r-1)+t,l=Math.floor(i/12),a=i-l*12+1,c=nn(l,a),h=zt(l,a,e?c:Math.min(o,c));return h<1?S("#NUM!"):h}x("DATE",{minArgs:3,maxArgs:3,impl:s=>{const t=lr(s,ie);if(g(t))return t;let[e]=t;if(e<0||e>9999)return S("#NUM!");e<1900&&(e+=1900);const n=zt(e,t[1],t[2]);return n<0?S("#NUM!"):n}});x("YEAR",{minArgs:1,maxArgs:1,impl:ts(s=>s.year)});x("MONTH",{minArgs:1,maxArgs:1,impl:ts(s=>s.month)});x("DAY",{minArgs:1,maxArgs:1,impl:ts(s=>s.day)});x("TODAY",{maxArgs:0,volatile:!0,impl:()=>rn(!1,an())});x("NOW",{maxArgs:0,volatile:!0,impl:()=>rn(!0,an())});x("WEEKDAY",{minArgs:1,maxArgs:2,impl:s=>{const t=St(s[0]),e=s.length>1?ie(s[1]):1;if(g(t))return t;if(g(e))return e;const n=((t-1)%7+7)%7;switch(e){case 1:return n+1;case 2:return(n+6)%7+1;case 3:return(n+6)%7;default:return S("#NUM!")}}});x("EDATE",{minArgs:2,maxArgs:2,impl:s=>{const t=St(s[0]),e=ie(s[1]);return g(t)?t:g(e)?e:hn(t,e,!1)}});x("EOMONTH",{minArgs:2,maxArgs:2,impl:s=>{const t=St(s[0]),e=ie(s[1]);return g(t)?t:g(e)?e:hn(t,e,!0)}});x("DAYS",{minArgs:2,maxArgs:2,impl:s=>{const[t,e]=s.map(St);return g(t)?t:g(e)?e:t-e}});x("DATEDIF",{minArgs:3,maxArgs:3,impl:s=>{const t=St(s[0]),e=St(s[1]),n=rt(T(s[2]));if(g(t))return t;if(g(e))return e;if(g(n))return n;if(t>e)return S("#NUM!","Start date is after end date");const r=gt(t),o=gt(e),i=(o.year-r.year)*12+(o.month-r.month)-(o.day<r.day?1:0);switch(n.toUpperCase()){case"D":return e-t;case"M":return i;case"Y":return Math.floor(i/12);case"YM":return i%12;default:return S("#NUM!",`Unknown DATEDIF unit "${n}"`)}}});const ft=(s,t)=>B(s/t);x("CEILING",{minArgs:1,maxArgs:2,impl:G((s,t=1)=>t===0?0:s>0&&t<0?S("#NUM!"):t<0?-Math.ceil(ft(-s,-t))*-t:Math.ceil(ft(s,t))*t)});x("FLOOR",{minArgs:1,maxArgs:2,impl:G((s,t=1)=>t===0?s===0?0:S("#DIV/0!"):s>0&&t<0?S("#NUM!"):t<0?-Math.floor(ft(-s,-t))*-t:Math.floor(ft(s,t))*t)});x("CEILING.MATH",{minArgs:1,maxArgs:3,impl:G((s,t=1,e=0)=>{const n=Math.abs(t);return n===0?0:s<0&&e!==0?-Math.ceil(ft(-s,n))*n:Math.ceil(ft(s,n))*n})});x("FLOOR.MATH",{minArgs:1,maxArgs:3,impl:G((s,t=1,e=0)=>{const n=Math.abs(t);return n===0?0:s<0&&e!==0?-Math.floor(ft(-s,n))*n:Math.floor(ft(s,n))*n})});x("MROUND",{minArgs:2,maxArgs:2,impl:G((s,t)=>{if(t===0)return 0;if(s*t<0)return S("#NUM!");const e=ft(s,t);return Math.sign(e)*Math.round(Math.abs(e))*t})});x("TRUNC",{minArgs:1,maxArgs:2,impl:G((s,t=0)=>{const e=Math.pow(10,Math.trunc(t));return Math.trunc(B(s*e))/e})});x("SIGN",{minArgs:1,maxArgs:1,impl:G(s=>Math.sign(s))});x("PRODUCT",{minArgs:1,aggregate:!0,impl:s=>{const t=wt(s);if(g(t))return t;if(t.length===0)return 0;const e=t.reduce((n,r)=>n*r,1);return Number.isFinite(e)?B(e):S("#NUM!")}});x("RAND",{maxArgs:0,volatile:!0,impl:()=>cn()});x("RANDBETWEEN",{minArgs:2,maxArgs:2,volatile:!0,impl:G((s,t)=>{const e=Math.ceil(s),n=Math.floor(t);return e>n?S("#NUM!"):e+Math.floor(cn()*(n-e+1))})});function pt(s,t){return{minArgs:s,aggregate:!0,impl:e=>{const n=wt(e);if(g(n))return n;const r=t(n);return g(r)?r:Number.isFinite(r)?B(r):S("#NUM!")}}}function ar(s){if(s.length===0)return S("#NUM!");const t=[...s].sort((n,r)=>n-r),e=t.length>>1;return t.length%2?t[e]:(t[e-1]+t[e])/2}function un(s){const t=new Map;for(const r of s)t.set(r,(t.get(r)??0)+1);let e,n=1;for(const[r,o]of t)o>n&&(e=r,n=o);return e===void 0?S("#N/A"):e}function It(s,t){const e=s.length;if(e<(t?2:1))return S("#DIV/0!");const n=Jt(s)/e;return Jt(s.map(r=>(r-n)*(r-n)))/(t?e-1:e)}const es=s=>g(s)?s:Math.sqrt(s);x("MEDIAN",pt(1,ar));x("MODE.SNGL",pt(1,un));x("MODE",pt(1,un));x("VAR.S",pt(1,s=>It(s,!0)));x("VAR",pt(1,s=>It(s,!0)));x("VAR.P",pt(1,s=>It(s,!1)));x("STDEV.S",pt(1,s=>es(It(s,!0))));x("STDEV",pt(1,s=>es(It(s,!0))));x("STDEV.P",pt(1,s=>es(It(s,!1))));function dn(s,t){const e=wt([s[0]]);if(g(e))return e;const n=Q(s[1]);if(g(n))return n;const r=Math.ceil(n);return r<1||r>e.length?S("#NUM!"):[...e].sort((i,l)=>t?l-i:i-l)[r-1]}x("LARGE",{minArgs:2,maxArgs:2,aggregate:!0,impl:s=>dn(s,!0)});x("SMALL",{minArgs:2,maxArgs:2,aggregate:!0,impl:s=>dn(s,!1)});function fn(s){const t=q(T(s[0]));if(g(t))return t;const e=wt([s[1]]);if(g(e))return e;const n=s.length>2?Q(s[2]):0;return g(n)?n:e.includes(t)?1+e.filter(r=>n===0?r>t:r<t).length:S("#N/A")}x("RANK.EQ",{minArgs:2,maxArgs:3,aggregate:!0,impl:fn});x("RANK",{minArgs:2,maxArgs:3,aggregate:!0,impl:fn});function cr(s,t){const e=pn(t);let n=e[0],r=s<0;s<0&&e.length>1&&e[1]!==""?(n=e[1],r=!1):s===0&&e.length>2&&e[2]!==""&&(n=e[2]);const o=ss(n);if(o.some(a=>a.kind==="date"))return pr(s<0&&!r?-s:s,o);const i=Math.abs(s);if(o.length===0||/^general$/i.test(n.trim()))return(r?"-":"")+Ye(i);const l=fr(i,o);return r&&/[1-9]/.test(l)?"-"+l:l}function hr(s,t){const e=pn(t),n=e.length>3?e[3]:e.length===1&&ur(e[0])?e[0]:void 0;if(n!==void 0)return ss(n).map(r=>r.kind==="lit"?r.text:r.kind==="ph"&&r.ch==="@"?s:"").join("")}const ur=s=>ss(s).some(t=>t.kind==="ph"&&t.ch==="@");function pn(s){const t=[];let e="";for(let n=0;n<s.length;n++){const r=s[n];if(r==='"'){const o=s.indexOf('"',n+1),i=o<0?s.length:o;e+=s.slice(n,i+1),n=i}else r==="\\"&&n+1<s.length?e+=r+s[++n]:r===";"?(t.push(e),e=""):e+=r}return t.push(e),t}const dr=/^(am\/pm|a\/p|y+|m+|d+|h+|s+)/i;function ss(s){const t=[];for(let e=0;e<s.length;e++){const n=s[e],r=s.slice(e);if(n==='"'){const o=s.indexOf('"',e+1),i=o<0?s.length:o;t.push({kind:"lit",text:s.slice(e+1,i)}),e=i}else if(n==="\\")e+1<s.length&&t.push({kind:"lit",text:s[++e]});else if(n==="_")e++,t.push({kind:"lit",text:" "});else if(n==="*")e++;else if(n==="["){const o=s.indexOf("]",e);e=o<0?s.length:o}else if("0#?.,%@".includes(n))t.push({kind:"ph",ch:n});else if((n==="E"||n==="e")&&/^[eE][+-]0/.test(r))t.push({kind:"ph",ch:"E"+r[1]}),e++;else{const o=dr.exec(r);o?(t.push({kind:"date",text:o[0]}),e+=o[0].length-1):t.push({kind:"lit",text:n})}}return t}const us=s=>s.kind==="ph"&&(s.ch==="0"||s.ch==="#"||s.ch==="?");function fr(s,t){var A;const e=t.findIndex(us);if(e<0)return t.map(y=>y.kind==="lit"?y.text:y.kind==="ph"&&y.ch==="%"?"%":"").join("");let n=t.length-1;for(;!us(t[n]);)n--;for(;n+1<t.length&&t[n+1].kind==="ph"&&",.".includes(t[n+1].ch);)n++;let r=s;for(const y of t)y.kind==="ph"&&y.ch==="%"&&(r*=100);const o=t.slice(e,n+1).filter(y=>y.kind==="ph"),i=o.findIndex(y=>y.ch.startsWith("E")),l=i<0?o:o.slice(0,i),a=l.findIndex(y=>y.ch==="."),c=(a<0?l:l.slice(0,a)).map(y=>y.ch).join(""),h=a<0?"":l.slice(a+1).map(y=>y.ch).join("").replace(/[^0#?]/g,""),u=c.replace(/[^0#?]/g,""),d=/[0#?],+[0#?]/.test(c);r/=Math.pow(1e3,((A=/,+$/.exec(c))==null?void 0:A[0].length)??0);let m;if(i>=0){const y=o.slice(i),p=Math.max(y.slice(1).filter($=>$.ch==="0").length,1),f=y[0].ch[1];let b=r===0?0:Math.floor(Math.log10(r))-Math.max(u.length-1,0),C=r/Math.pow(10,b);const F=de(C,u,h,!1,a>=0);Number(F.replace(/,/g,""))>=Math.pow(10,Math.max(u.length,1))&&(b++,C=r/Math.pow(10,b));const R=String(Math.abs(b)).padStart(p,"0");m=de(C,u,h,!1,a>=0)+"E"+(b<0?"-":f==="+"?"+":"")+R}else m=de(r,u,h,d,a>=0);const w=y=>y.kind==="lit"?y.text:y.kind==="ph"&&",.%".includes(y.ch)?y.ch:"";return t.slice(0,e).map(w).join("")+m+t.slice(n+1).map(w).join("")}function de(s,t,e,n,r){const o=e.length,i=e.lastIndexOf("0")+1,l=(t.match(/0/g)??[]).length,a=Math.pow(10,o),c=B(Math.round(s*a+1e-9*Math.sign(s))/a);let[h,u=""]=c.toFixed(o).split(".");for(;u.length>i&&u.endsWith("0");)u=u.slice(0,-1);return h==="0"&&l===0&&(h=""),h=h.padStart(l,"0"),n&&(h=h.replace(/\B(?=(\d{3})+(?!\d))/g,",")),h+(r?"."+u:"")}const fe=["January","February","March","April","May","June","July","August","September","October","November","December"],ds=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Et=s=>String(s).padStart(2,"0");function pr(s,t){if(s<0)return;const e=Math.round(s*86400),n=Math.floor(e/86400),r=e-n*86400,{year:o,month:i,day:l}=gt(n),a=Math.floor(r/3600),c=Math.floor(r/60)%60,h=r%60,u=t.some(w=>w.kind==="date"&&/^a/i.test(w.text)),d=((n-1)%7+7)%7,m=(w,A)=>{for(let y=w+A;y>=0&&y<t.length;y+=A){const p=t[y];if(p.kind==="date")return p.text[0].toLowerCase()}};return t.map((w,A)=>{if(w.kind==="lit")return w.text;if(w.kind==="ph")return w.ch==="@"?"":w.ch;const y=w.text,p=y.toLowerCase(),f=y.length;switch(p[0]){case"y":return f<=2?Et(o%100):String(o).padStart(4,"0");case"m":return f<=2&&(m(A,-1)==="h"||m(A,1)==="s")?f===2?Et(c):String(c):f===1?String(i):f===2?Et(i):f===3?fe[i-1].slice(0,3):f===5?fe[i-1][0]:fe[i-1];case"d":return f===1?String(l):f===2?Et(l):f===3?ds[d].slice(0,3):ds[d];case"h":{const b=u?(a+11)%12+1:a;return f>=2?Et(b):String(b)}case"s":return f>=2?Et(h):String(h);default:{const b=a>=12;if(p==="a/p")return b?y[2]==="P"?"P":"p":y[0];const C=y.slice(0,2),F=y.slice(3,5);return b?F:C}}}).join("")}const mn=32767;function yt(s){return t=>At(t,(...e)=>e.find(g)??s(...e))}function J(s){return rt(s)}function Ht(s){const t=q(s);return g(t)?t:Math.trunc(t)}function gn(s){const t=s.trim(),e=Ct(t);if(e!==void 0)return e;if(/^[+-]?\d{1,3}(,\d{3})+(\.\d*)?%?$/.test(t))return Ct(t.replace(/,/g,""));const n=oe(t);if(n!==void 0)return n;const r=/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(t);if(r&&Number(r[2])<60&&Number(r[3]??0)<60)return(Number(r[1])*3600+Number(r[2])*60+Number(r[3]??0))/86400}x("TEXT",{minArgs:2,maxArgs:2,impl:yt((s,t)=>{const e=J(t);if(g(e))return e;if(typeof s=="boolean")return s?"TRUE":"FALSE";let n;if(typeof s=="string"){const r=gn(s);if(r===void 0)return hr(s,e)??s;n=r}else n=s??0;return cr(n,e)??S("#VALUE!","Value cannot be formatted as a date")})});x("VALUE",{minArgs:1,maxArgs:1,impl:yt(s=>typeof s=="number"?s:s===null?0:typeof s=="boolean"?S("#VALUE!"):gn(s)??S("#VALUE!",`"${s}" is not a number`))});function wn(s){return yt((t,e,n=1)=>{const r=J(t),o=J(e),i=Ht(n);if(g(r))return r;if(g(o))return o;if(g(i))return i;if(i<1||i>Math.max(o.length,1))return S("#VALUE!");let l;if(s)l=o.indexOf(r,i-1);else if(Gs(r)){const a=Ke(r,!1).exec(o.slice(i-1));l=a?a.index+i-1:-1}else l=o.toLowerCase().indexOf(r.toLowerCase(),i-1);return l<0?S("#VALUE!","Text not found"):l+1})}x("FIND",{minArgs:2,maxArgs:3,impl:wn(!0)});x("SEARCH",{minArgs:2,maxArgs:3,impl:wn(!1)});x("SUBSTITUTE",{minArgs:3,maxArgs:4,impl:yt((s,t,e,n)=>{const r=J(s),o=J(t),i=J(e);if(g(r))return r;if(g(o))return o;if(g(i))return i;if(o==="")return r;if(n===void 0)return r.split(o).join(i);const l=Ht(n);if(g(l))return l;if(l<1)return S("#VALUE!");let a=-1;for(let c=0;c<l;c++)if(a=r.indexOf(o,a+(c===0?0:o.length)),a<0)return r;return r.slice(0,a)+i+r.slice(a+o.length)})});x("REPLACE",{minArgs:4,maxArgs:4,impl:yt((s,t,e,n)=>{const r=J(s),o=Ht(t),i=Ht(e),l=J(n);return g(r)?r:g(o)?o:g(i)?i:g(l)?l:o<1||i<0?S("#VALUE!"):r.slice(0,o-1)+l+r.slice(o-1+i)})});x("REPT",{minArgs:2,maxArgs:2,impl:yt((s,t)=>{const e=J(s),n=Ht(t);return g(e)?e:g(n)?n:n<0||e.length*n>mn?S("#VALUE!"):e.repeat(n)})});x("PROPER",{minArgs:1,maxArgs:1,impl:yt(s=>{const t=J(s);if(g(t))return t;let e="",n=!1;for(const r of t){const o=new RegExp("\\p{L}","u").test(r);e+=o?n?r.toLowerCase():r.toUpperCase():r,n=o}return e})});x("EXACT",{minArgs:2,maxArgs:2,impl:yt((s,t)=>{const e=J(s),n=J(t);return g(e)?e:g(n)?n:e===n})});x("TEXTJOIN",{minArgs:3,impl:s=>{const t=[];for(const o of tt(s[0]).flat()){const i=rt(o);if(g(i))return i;t.push(i)}const e=dt(T(s[1]));if(g(e))return e;const n=[];for(const o of s.slice(2))for(const i of tt(o).flat()){if(g(i))return i;const l=rt(i);e&&l===""||n.push(l)}let r=n[0]??"";for(let o=1;o<n.length;o++)r+=(t.length?t[(o-1)%t.length]:"")+n[o];return r.length>mn?S("#VALUE!"):r}});function Xt(s,t){const e=t!=="count",n=s.slice(e?1:0);if(n.length===0||n.length%2)return S("#VALUE!","Criteria come in range/criterion pairs");const r=[];for(let u=0;u<n.length;u+=2){const d=T(n[u+1]);if(g(d))return d;r.push({range:tt(n[u]),test:qe(d)})}const o=e?tt(s[0]):r[0].range,{height:i,width:l}=o;if(r.some(u=>u.range.height!==i||u.range.width!==l))return S("#VALUE!","Criteria ranges must have the same size");const a=new re;let c=0,h;for(let u=0;u<i;u++)for(let d=0;d<l;d++){if(!r.every(w=>w.test(w.range.values[u][d])))continue;if(!e){c++;continue}const m=o.values[u][d];if(g(m))return m;typeof m=="number"&&(a.add(m),c++,(h===void 0||(t==="max"?m>h:m<h))&&(h=m))}switch(t){case"count":return c;case"sum":return B(a.value);case"average":return c===0?S("#DIV/0!"):B(a.value/c);default:return h??0}}x("SUMIFS",{minArgs:3,impl:s=>Xt(s,"sum")});x("COUNTIFS",{minArgs:2,impl:s=>Xt(s,"count")});x("AVERAGEIFS",{minArgs:3,impl:s=>Xt(s,"average")});x("MAXIFS",{minArgs:3,impl:s=>Xt(s,"max")});x("MINIFS",{minArgs:3,impl:s=>Xt(s,"min")});x("ISNA",{minArgs:1,maxArgs:1,impl:([s])=>{const t=T(s);return g(t)&&t.code==="#N/A"}});x("ISLOGICAL",{minArgs:1,maxArgs:1,impl:([s])=>typeof T(s)=="boolean"});x("XOR",{minArgs:1,aggregate:!0,impl:s=>Ge(s,(t,e)=>t!==e,!1)});x("IFS",{minArgs:2,lazy:(s,t)=>{if(s.length%2)return S("#VALUE!","IFS needs test/value pairs");for(let e=0;e<s.length;e+=2){const n=dt(T(t.evaluate(s[e])));if(g(n))return n;if(n)return t.evaluate(s[e+1])}return S("#N/A","No test was true")}});function mr(s,t){return s!==null&&t!==null&&typeof s!=typeof t?!1:V(s,t)===0}x("SWITCH",{minArgs:3,lazy:(s,t)=>{const e=T(t.evaluate(s[0]));if(g(e))return e;const n=Math.floor((s.length-1)/2);for(let r=0;r<n;r++){const o=1+2*r,i=T(t.evaluate(s[o]));if(g(i))return i;if(mr(e,i))return t.evaluate(s[o+1])}return s.length%2===0?t.evaluate(s[s.length-1]):S("#N/A","No case matched")}});const gr=(s,t)=>s!==null&&!g(s)&&typeof s==typeof t;function wr(s,t,e,n){const r=s.map((l,a)=>a);n<0&&r.reverse();const o=e===2&&typeof t=="string"?Ke(t):void 0;let i=-1;for(const l of r){const a=s[l];if(gr(a,t)){if(o?o.test(a):V(a,t)===0)return l;e===-1&&V(a,t)<0&&(i<0||V(a,s[i])>0)&&(i=l),e===1&&V(a,t)>0&&(i<0||V(a,s[i])<0)&&(i=l)}}return i}x("XLOOKUP",{minArgs:3,maxArgs:6,impl:s=>{const t=T(s[0]);if(g(t))return t;const e=tt(s[1]),n=tt(s[2]);if(e.width!==1&&e.height!==1)return S("#VALUE!","Lookup array must be one row or column");const r=e.width===1&&(e.height>1||n.height===1),o=r?e.height:e.width;if((r?n.height:n.width)!==o)return S("#VALUE!","Arrays must have the same length");const i=s.length>3&&s[3]!==null?s[3]:void 0,l=s.length>4&&s[4]!==null?Q(s[4]):0,a=s.length>5&&s[5]!==null?Q(s[5]):1;if(g(l))return l;if(g(a))return a;if(![0,-1,1,2].includes(l)||![1,-1,2,-2].includes(a))return S("#VALUE!");const c=r?Zs(e,0):e.values[0],h=wr(c,t,l,a);return h<0?i??S("#N/A"):r?n.width===1?n.values[h][0]:new L([n.values[h]]):n.height===1?n.values[0][h]:new L(n.values.map(u=>[u[h]]))}});x("CHOOSE",{minArgs:2,lazy:(s,t)=>{const e=q(T(t.evaluate(s[0])));if(g(e))return e;const n=Math.trunc(e);return n<1||n>=s.length?S("#VALUE!","CHOOSE index out of range"):t.evaluate(s[n])}});x("ROW",{maxArgs:1,positional:!0,lazy:(s,t)=>{if(s.length===0)return t.row+1;const e=t.reference(s[0]);return e?e.height===1?e.row+1:new L(Array.from({length:e.height},(n,r)=>[e.row+r+1])):yn(t.evaluate(s[0]))}});x("COLUMN",{maxArgs:1,positional:!0,lazy:(s,t)=>{if(s.length===0)return t.col+1;const e=t.reference(s[0]);return e?e.width===1?e.col+1:new L([Array.from({length:e.width},(n,r)=>e.col+r+1)]):yn(t.evaluate(s[0]))}});const yn=s=>g(s)?s:S("#VALUE!","Argument must be a reference");function bn(s){return{minArgs:1,maxArgs:1,lazy:(t,e)=>{const n=e.reference(t[0]);if(n)return s(n);const r=e.evaluate(t[0]);return g(r)?r:s(r instanceof L?r:{height:1,width:1})}}}x("ROWS",bn(s=>s.height));x("COLUMNS",bn(s=>s.width));const ns=()=>S("#CALC!","The result is an empty array");function _t(s,t,e){if(s.length<=t||s[t]===null)return e;const n=q(T(s[t]));return g(n)?n:Math.trunc(n)}function Te(s,t){return s.length<=t||s[t]===null?!1:dt(T(s[t]))}function le(s,t){return t?{rows:$e(s).values,rebuild:e=>$e(new L(e))}:{rows:s.values,rebuild:e=>new L(e)}}function yr(s,t){const e=s??0,n=t??0,r=g(e),o=g(n);return r||o?r&&o?0:r?1:-1:V(e,n)}x("FILTER",{minArgs:2,maxArgs:3,impl:s=>{const t=tt(s[0]),e=tt(s[1]);let n;if(e.width===1&&e.height===t.height)n=!1;else if(e.height===1&&e.width===t.width)n=!0;else return S("#VALUE!","FILTER include must match the array height or width");const r=[...e.flat()],{rows:o,rebuild:i}=le(t,n),l=[];for(let a=0;a<o.length;a++){const c=r[a];if(typeof c=="string")return S("#VALUE!");const h=dt(c);if(g(h))return h;h&&l.push(o[a])}return l.length===0?s.length>2?s[2]:ns():i(l)}});function vn(s){return g(s)||s===1||s===-1?s:S("#VALUE!","Sort order must be 1 or -1")}function xn(s,t){const e=s.map((n,r)=>r);return e.sort((n,r)=>{for(const o of t){const i=yr(o.values[n],o.values[r]);if(i!==0)return i*o.order}return n-r}),e.map(n=>s[n])}x("SORT",{minArgs:1,maxArgs:4,impl:s=>{var l;const t=tt(s[0]),e=_t(s,1,1),n=vn(_t(s,2,1)),r=Te(s,3);if(g(e))return e;if(g(n))return n;if(g(r))return r;const{rows:o,rebuild:i}=le(t,r);return e<1||e>(((l=o[0])==null?void 0:l.length)??0)?S("#VALUE!","Sort index out of range"):i(xn(o,[{values:o.map(a=>a[e-1]),order:n}]))}});x("SORTBY",{minArgs:2,impl:s=>{const t=tt(s[0]);let e;const n=[];for(let i=1;i<s.length;i+=2){const l=tt(s[i]),a=l.height===1&&l.width===t.width&&!(l.width===1&&l.height===t.height);if(!(a||l.width===1&&l.height===t.height)||e!==void 0&&e!==a)return S("#VALUE!","SORTBY arrays must match the array");e=a;const h=vn(_t(s,i+1,1));if(g(h))return h;n.push({values:[...l.flat()],order:h})}const{rows:r,rebuild:o}=le(t,e??!1);return o(xn(r,n))}});function br(s){return s===null?"n:0":g(s)?"e:"+s.code:typeof s=="string"?"s:"+s.toLowerCase():(typeof s=="number"?"n:":"b:")+String(s)}x("UNIQUE",{minArgs:1,maxArgs:3,impl:s=>{const t=Te(s,1),e=Te(s,2);if(g(t))return t;if(g(e))return e;const{rows:n,rebuild:r}=le(tt(s[0]),t),o=new Map;for(const l of n){const a=l.map(br).join("\0"),c=o.get(a);c?c.count++:o.set(a,{row:l,count:1})}const i=[...o.values()].filter(l=>!e||l.count===1).map(l=>l.row);return i.length?r(i):ns()}});x("SEQUENCE",{minArgs:1,maxArgs:4,impl:s=>{const t=_t(s,0,1),e=_t(s,1,1);if(g(t))return t;if(g(e))return e;const n=s.length>2&&s[2]!==null?q(T(s[2])):1,r=s.length>3&&s[3]!==null?q(T(s[3])):1;return g(n)?n:g(r)?r:t<0||e<0||t>1048576||e>16384?S("#VALUE!"):t===0||e===0?ns():t*e>1048576?S("#NUM!","SEQUENCE is too large"):new L(Array.from({length:t},(o,i)=>Array.from({length:e},(l,a)=>B(n+r*(i*e+a)))))}});x("TRANSPOSE",{minArgs:1,maxArgs:1,impl:([s])=>s instanceof L?$e(s):s});function ze(s,t,e,n,r,o){const i=[];for(let l=e;l<=r;l++){const a=[];for(let c=n;c<=o;c++)a.push(s.getCellValue(t,l,c));i.push(a)}return new L(i,{sheet:t,row:e,col:n})}const fs=(s,t)=>t.getCellValue(s.sheet??t.sheet,s.rowAbs?s.row:s.row+t.row,s.colAbs?s.col:s.col+t.col);function st(s,t){switch(s.type){case"number":return s.value;case"string":return s.value;case"bool":return s.value;case"error":return S(s.code);case"ref":return fs(s,t);case"range":{const{start:e,end:n}=s,r=e.sheet??t.sheet,o=e.rowAbs?e.row:e.row+t.row,i=n.rowAbs?n.row:n.row+t.row,l=e.colAbs?e.col:e.col+t.col,a=n.colAbs?n.col:n.col+t.col,[c,h,u,d]=[Math.min(o,i),Math.max(o,i),Math.min(l,a),Math.max(l,a)];return t.getRange?t.getRange(r,c,u,h,d):ze(t,r,c,u,h,d)}case"name":return s.name===""?null:t.resolveName?t.resolveName(s.name):S("#NAME?",`Unknown name "${s.name}"`);case"paren":return st(s.expr,t);case"unary":{const e=st(s.arg,t);return e instanceof L?At([e],n=>ps(s.op,n)):ps(s.op,e)}case"percent":{const e=st(s.arg,t);return e instanceof L?At([e],ms):ms(e)}case"binary":{const e=st(s.left,t),n=st(s.right,t);if(!(e instanceof L)&&!(n instanceof L))return gs(s.op,e,n);const r=s.op;return At([e,n],(o,i)=>gs(r,o,i))}case"call":{const e=Le(s.name);if(!e)return S("#NAME?",`Unknown function ${s.name}`);const n={evaluate:o=>st(o,t),sheet:t.sheet,row:t.row,col:t.col,reference:o=>An(o,t)};if(e.lazy)return e.lazy(s.args,n);const r=s.args.map(o=>e.aggregate&&o.type==="ref"?new L([[fs(o,t)]]):st(o,t));return e.impl(r,n)}}}function An(s,t){if(s.type==="paren")return An(s.expr,t);if(s.type==="ref"){const e=s.rowAbs?s.row:s.row+t.row,n=s.colAbs?s.col:s.col+t.col;return{sheet:s.sheet??t.sheet,row:e,col:n,height:1,width:1}}if(s.type==="range"||s.type==="name"){const e=st(s,t);if(e instanceof L&&e.origin)return{...e.origin,height:e.height,width:e.width}}}function ps(s,t){const e=q(t);return g(e)||s==="+"?e:-e}function ms(s){const t=q(s);return g(t)?t:t/100}function gs(s,t,e){if(g(t))return t;if(g(e))return e;switch(s){case"&":{const i=rt(t),l=rt(e);return g(i)?i:g(l)?l:i+l}case"=":return V(t,e)===0;case"<>":return V(t,e)!==0;case"<":return V(t,e)<0;case"<=":return V(t,e)<=0;case">":return V(t,e)>0;case">=":return V(t,e)>=0}const n=q(t),r=q(e);if(g(n))return n;if(g(r))return r;let o;switch(s){case"+":o=n+r;break;case"-":o=n-r;break;case"*":o=n*r;break;case"/":if(r===0)return S("#DIV/0!");o=n/r;break;case"^":if(n===0&&r===0)return S("#NUM!");o=Math.pow(n,r);break;default:return S("#ERROR!",`Unknown operator ${s}`)}return Number.isFinite(o)?B(o):S("#NUM!")}class j extends Error{constructor(t,e){super(t),this.pos=e}}const vr=/(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/y,xr=/[\p{L}_][\p{L}\p{N}_.]*/uy,Ar=/([\p{L}_][\p{L}\p{N}_.]*)!/uy,Cr=/[\p{L}_]/u,ws=/(\$?)([A-Za-z]{1,3})(\$?)(\d+)/y,Sr=["<=",">=","<>"],Er="+-*/^&=<>%(),;:";function Mr(s){const t=[];let e=0;const n=o=>(o.lastIndex=e,o.exec(s));for(;e<s.length;){const o=s[e];if(o===" "||o===" "||o===`
2
+ `||o==="\r"){e++;continue}if(o>="0"&&o<="9"||o==="."&&/\d/.test(s[e+1]??"")){const l=n(vr);t.push({type:"number",value:Number(l[0]),pos:e}),e+=l[0].length;continue}if(o==='"'){const l=e;let a="";for(e++;;){if(e>=s.length)throw new j("Unterminated string",l);if(s[e]==='"'){if(s[e+1]==='"'){a+='"',e+=2;continue}e++;break}a+=s[e++]}t.push({type:"string",value:a,pos:l});continue}if(o==="#"){const l=Ks.find(a=>s.startsWith(a,e)||s.toUpperCase().startsWith(a,e));if(!l)throw new j("Unknown error literal",e);t.push({type:"error",value:l,pos:e}),e+=l.length;continue}if(o==="'"){const l=e;let a="";for(e++;;){if(e>=s.length)throw new j("Unterminated sheet name",l);if(s[e]==="'"){if(s[e+1]==="'"){a+="'",e+=2;continue}e++;break}a+=s[e++]}if(s[e]!=="!")throw new j('Expected "!" after sheet name',e);e=r(a,l,e+1);continue}if(o==="$"||Cr.test(o)){const l=o==="$"?null:n(Ar);if(l){e=r(l[1],e,e+l[0].length);continue}const a=ys(s,e),c=o==="$"?null:n(xr);if(c&&kr(s,e+c[0].length)==="("){t.push({type:"func",value:c[0].toUpperCase(),pos:e}),e+=c[0].length;continue}if(a&&(!c||a.length>=c[0].length)){t.push({...a.token,pos:e}),e+=a.length;continue}if(!c)throw new j("Invalid reference",e);const h=c[0].toUpperCase();h==="TRUE"||h==="FALSE"?t.push({type:"bool",value:h==="TRUE",pos:e}):t.push({type:"name",value:c[0],pos:e}),e+=c[0].length;continue}const i=s.slice(e,e+2);if(Sr.includes(i)){t.push({type:"op",value:i,pos:e}),e+=2;continue}if(Er.includes(o)){t.push({type:"op",value:o===";"?",":o,pos:e}),e++;continue}throw new j(`Unexpected character "${o}"`,e)}return t.push({type:"eof",pos:s.length}),t;function r(o,i,l){const a=ys(s,l);if(!a)throw new j('Expected cell reference after "!"',l);return t.push({...a.token,sheet:o,pos:i}),l+a.length}}function kr(s,t){for(;t<s.length&&s[t]===" ";)t++;return s[t]}function ys(s,t){ws.lastIndex=t;const e=ws.exec(s);if(!e||/[\p{L}\p{N}_]/u.test(s[t+e[0].length]??""))return;const n=se(e[2]),r=Number(e[4])-1;if(!(n<0||n>=16384||r<0||r>=1048576))return{length:e[0].length,token:{type:"ref",row:r,col:n,colAbs:e[1]==="$",rowAbs:e[3]==="$"}}}const Rr={"=":1,"<>":1,"<":1,"<=":1,">":1,">=":1,"&":2,"+":3,"-":3,"*":4,"/":4,"^":5};function Ie(s,t={}){var y,p;const e=Mr(s),n=((y=t.base)==null?void 0:y.row)??0,r=((p=t.base)==null?void 0:p.col)??0;let o=0;const i=(f,b)=>({type:"ref",row:f.rowAbs?f.row:f.row-n,col:f.colAbs?f.col:f.col-r,rowAbs:f.rowAbs,colAbs:f.colAbs,...b===void 0?{}:{sheet:b}}),l=()=>e[o],a=()=>e[o++],c=(f,b)=>f.type==="op"&&f.value===b,h=f=>{const b=a();if(!c(b,f))throw new j(`Expected "${f}"`,b.pos)};function u(f){let b=d();for(;;){const C=l();if(C.type!=="op")break;const F=Rr[C.value];if(F===void 0||F<f)break;a();const R=u(F+1);b={type:"binary",op:C.value,left:b,right:R}}return b}function d(){const f=l();if(c(f,"-")||c(f,"+"))return a(),{type:"unary",op:c(f,"-")?"-":"+",arg:d()};let b=m();for(;c(l(),"%");)a(),b={type:"percent",arg:b};return b}function m(){var b,C;const f=a();switch(f.type){case"number":return{type:"number",value:f.value};case"string":return{type:"string",value:f.value};case"bool":return{type:"bool",value:f.value};case"error":return{type:"error",code:f.value};case"name":return{type:"name",name:f.value};case"ref":{const F=f.sheet===void 0||(b=t.resolveSheet)==null?void 0:b.call(t,f.sheet),R=f.sheet!==void 0&&F===void 0,$=i(f,F);if(!c(l(),":"))return R?{type:"error",code:"#REF!"}:$;a();const z=a();if(z.type!=="ref")throw new j('Expected cell reference after ":"',z.pos);if(z.sheet!==void 0&&z.sheet.toUpperCase()!==((C=f.sheet)==null?void 0:C.toUpperCase()))throw new j("A range cannot span sheets",z.pos);return R?{type:"error",code:"#REF!"}:{type:"range",start:$,end:i(z,F)}}case"func":{h("(");const F=[];if(!c(l(),")"))for(;c(l(),",")||c(l(),")")?F.push({type:"name",name:""}):F.push(u(1)),!!c(l(),",");)a();return h(")"),{type:"call",name:f.value,args:F}}case"op":if(f.value==="("){const F=u(1);return h(")"),{type:"paren",expr:F}}throw new j(`Unexpected "${f.value}"`,f.pos);case"eof":throw new j("Unexpected end of formula",f.pos)}}const w=u(1),A=l();if(A.type!=="eof")throw new j("Unexpected token",A.pos);return w}const ee=-1;class Fr{constructor(t){v(this,"sheet");v(this,"axis");this.ch=t,this.sheet=t.sheet,this.axis=t.axis}index(t){return Oe(this.ch,t)}span(t,e){return Nr(this.ch,t,e)}}class Dr{constructor(t,e,n,r,o){this.sheet=t,this.axis=e,this.start=n,this.count=r,this.target=o}index(t){const{start:e,count:n,target:r}=this,o=e+n;return r>o?t<e||t>=r?t:t<o?t+r-o:t-n:t<r||t>=o?t:t>=e?t-(e-r):t+n}span(t,e){const n=this.index(t),r=this.index(e);return n<=r?[n,r]:[r,n]}}function Cn(s,t,e){return e>s+t?{start:e-t,count:t,target:s}:e<s?{start:e,count:t,target:s+t}:{start:s,count:t,target:e}}function Sn(s,t,e,n){return n[0]-t!==n[1]-e||t!==e&&n[0]!==s.index(t)}function Oe(s,t){return t<s.index?t:s.remove?t<s.index+s.count?ee:t-s.count:t+s.count}function Nr(s,t,e){if(!s.remove)return[Oe(s,t),Oe(s,e)];const n=s.index+s.count;if(!(t>=s.index&&e<n))return[t<s.index?t:t<n?s.index:t-s.count,e<s.index?e:e<n?s.index-1:e-s.count]}const Ue=()=>({type:"error",code:"#REF!"});class $r{constructor(t){v(this,"text",!1);v(this,"meaning",!1);v(this,"homeSheet",0);v(this,"homeBefore",0);v(this,"homeAfter",0);v(this,"isRow");this.map=t,this.isRow=t.axis==="row"}adjust(t,e,n,r){return this.text=this.meaning=!1,this.homeSheet=e,this.homeBefore=n,this.homeAfter=r,this.walk(t)}walk(t){switch(t.type){case"ref":return this.ref(t);case"range":return this.range(t);case"unary":case"percent":return t.arg=this.walk(t.arg),t;case"binary":return t.left=this.walk(t.left),t.right=this.walk(t.right),t;case"paren":return t.expr=this.walk(t.expr),t;case"call":for(let e=0;e<t.args.length;e++)t.args[e]=this.walk(t.args[e]);return t;default:return t}}absolute(t){return this.isRow?t.rowAbs?t.row:t.row+this.homeBefore:t.colAbs?t.col:t.col+this.homeBefore}store(t,e){this.isRow?t.row=t.rowAbs?e:e-this.homeAfter:t.col=t.colAbs?e:e-this.homeAfter}ref(t){const e=this.absolute(t),n=(t.sheet??this.homeSheet)===this.map.sheet?this.map.index(e):e;return n===ee?(this.text=this.meaning=!0,Ue()):(n!==e&&(this.text=!0),this.store(t,n),t)}range(t){const e=this.absolute(t.start),n=this.absolute(t.end);let r=e,o=n;if((t.start.sheet??this.homeSheet)===this.map.sheet){const i=e<=n?e:n,l=e<=n?n:e,a=this.map.span(i,l);if(!a)return this.text=this.meaning=!0,Ue();Sn(this.map,i,l,a)&&(this.meaning=!0),(a[0]!==i||a[1]!==l)&&(this.text=!0),r=e<=n?a[0]:a[1],o=e<=n?a[1]:a[0]}return this.store(t.start,r),this.store(t.end,o),t}}function bs(s,t,e,n){const r=s.axis==="row",o=s.index+s.count,i=a=>r?a.rowAbs?a.row:a.row+n:a.colAbs?a.col:a.col+n;let l=!1;return lt(t,a=>{if(!(l||a.type==="name"||((a.type==="ref"?a:a.start).sheet??e)!==s.sheet))if(a.type==="ref"){const h=i(a);l=h>=s.index&&h<o}else{const h=i(a.start),u=i(a.end);l=Math.min(h,u)<o&&Math.max(h,u)>=s.index}}),l}function Lr(s,t,e){let n=!1;return{ast:$t(s,o=>{const i=o.type==="ref"?o.sheet:o.type==="range"?o.start.sheet:void 0;return o.type==="name"||(i??e)!==t?o:(n=!0,Ue())}),changed:n}}const Z=s=>Math.floor(s/17179869184),Y=s=>Math.floor(s%17179869184/16384),K=s=>s%16384,vs=(s,t,e,n)=>`${s},${t}:${e},${n}`,Tr=/^[\p{L}_][\p{L}\p{N}_.]*$/u,zr=64;class ut{constructor(){v(this,"sheetNames",[]);v(this,"sheetIds",new Map);v(this,"sheetData",[]);v(this,"rangeIndex",[]);v(this,"names",new Map);v(this,"unresolved",new Set);v(this,"evaluatingNames",new Set);v(this,"listeners",new Set);v(this,"batchDepth",0);v(this,"pendingKeys",new Set);v(this,"dirty",new Set);v(this,"volatiles",new Set);v(this,"anchors",new Set);v(this,"trace",null);v(this,"spillSeeds",new Set);v(this,"spillDirty",new Set);v(this,"ctx",{sheet:0,row:0,col:0,getCellValue:(t,e,n)=>{var r,o;return((o=(r=this.sheetData[t])==null?void 0:r.get(O(e,n,t)))==null?void 0:o.value)??null},resolveName:t=>this.nameValue(t),getRange:(t,e,n,r,o)=>{const i=this.rangeCache;if(!i)return ze(this.ctx,t,e,n,r,o);const l=`${t}!${e},${n}:${r},${o}`;let a=i.get(l);return a||i.set(l,a=ze(this.ctx,t,e,n,r,o)),a}});v(this,"rangeCache",null);this.createSheet("Sheet1")}static buildEmpty(){return new ut}static buildFromArray(t,e="Sheet1"){const n=new ut;return e!=="Sheet1"&&n.renameSheet(0,e),n.batch(()=>n.setCellContents({row:0,col:0},t)),n}static buildFromSheets(t){const e=new ut,n=Object.keys(t);return n.length===0?(e.removeSheet(0),e):(e.renameSheet(0,n[0]),n.slice(1).forEach(r=>e.addSheet(r)),e.batch(()=>n.forEach((r,o)=>e.setCellContents({row:0,col:0,sheet:o},t[r]))),e)}addSheet(t){const e=t??this.unusedSheetName();this.checkSheetName(e);const n=this.createSheet(e);return this.batch(()=>this.reresolve()),n}removeSheet(t){const e=this.requireSheet(t);return this.batch(()=>{var r,o;const n=new Set;for(const i of e.values())i.removed=!0,(r=i.dependents)==null||r.forEach(l=>n.add(l));(o=this.rangeIndex[t])==null||o.forEach(i=>i.dependents.forEach(l=>n.add(l)));for(const i of e.values())this.unlink(i),this.unresolved.delete(i),this.anchors.delete(i);this.sheetIds.delete(this.sheetNames[t].toUpperCase()),this.sheetNames[t]=void 0,this.sheetData[t]=void 0,this.rangeIndex[t]=void 0;for(const i of n){if(i.removed||!i.ast)continue;const{ast:l,changed:a}=Lr(i.ast,t,this.homeSheet(i));a&&(this.unlink(i),i.ast=l,i.textDirty=!0,this.link(i),this.dirty.add(i))}})}renameSheet(t,e){this.requireSheet(t);const n=this.sheetNames[t];if(n!==e){n.toUpperCase()!==e.toUpperCase()&&this.checkSheetName(e),this.sheetIds.delete(n.toUpperCase()),this.sheetIds.set(e.toUpperCase(),t),this.sheetNames[t]=e;for(const r of this.formulaRecords())r.crossSheet&&!r.textDirty&&Ir(r.ast,t)&&(r.textDirty=!0);this.batch(()=>this.reresolve())}}getSheetNames(){return this.sheetNames.filter(t=>t!==void 0)}getSheetId(t){return this.sheetIds.get(t.toUpperCase())}getSheetName(t){return this.sheetNames[t]}doesSheetExist(t){return this.getSheetId(t)!==void 0}countSheets(){return this.sheetIds.size}isItPossibleToAddNamedExpression(t){return Tr.test(t)&&!je(t)&&!/^(TRUE|FALSE)$/i.test(t)&&!Le(t)&&!this.isNameDefined(t)}addNamedExpression(t,e){if(!this.isItPossibleToAddNamedExpression(t))throw new Error(`Cannot add named expression "${t}"`);return this.batch(()=>{const n=this.nameRecord(t);n.name=t,this.names.delete(t.toUpperCase()),this.names.set(t.toUpperCase(),n),this.setNameExpression(n,e)})}changeNamedExpression(t,e){const n=this.definedName(t);return this.batch(()=>this.setNameExpression(n,e))}removeNamedExpression(t){const e=this.definedName(t);return this.batch(()=>{this.unlink(e),this.unresolved.delete(e),e.raw=null,e.ast=void 0,e.value=null,this.dirty.add(e),this.collectPlaceholder(e)})}getNamedExpressionValue(t){if(!this.isNameDefined(t))return;const e=this.nameValue(t);return e instanceof L?e.values:this.finalize(e)}getNamedExpressionFormula(t){const e=this.names.get(t.toUpperCase());return e&&e.raw!==null?this.textOf(e):void 0}listNamedExpressions(){return[...this.names.values()].filter(t=>t.raw!==null).map(t=>t.name)}getCellValue({row:t,col:e,sheet:n=0}){var r;return((r=this.recordAt(O(t,e,n)))==null?void 0:r.value)??null}getCellSerialized({row:t,col:e,sheet:n=0}){const r=this.recordAt(O(t,e,n));return r?this.textOf(r):null}getCellFormula(t){const e=this.getCellSerialized(t);return X(e)?e:void 0}doesCellHaveFormula(t){return this.getCellFormula(t)!==void 0}getCellType({row:t,col:e,sheet:n=0}){const r=this.recordAt(O(t,e,n));return!r||r.raw===null?"EMPTY":X(r.raw)?"FORMULA":"VALUE"}getSpillRange({row:t,col:e,sheet:n=0}){var h;const r=this.recordAt(O(t,e,n)),o=(r==null?void 0:r.spillOwner)??r;if(!(o!=null&&o.spillArea)||!((h=o.spillCells)!=null&&h.length))return;const{r0:i,c0:l,r1:a,c1:c}=o.spillArea;return{start:Rt(n,i,l),end:Rt(n,a,c)}}getSheetDimensions(t=0){var r;let e=0,n=0;for(const o of((r=this.sheetData[t])==null?void 0:r.values())??[])o.raw===null&&!o.spillOwner||(n=Math.max(n,Y(o.key)+1),e=Math.max(e,K(o.key)+1));return{width:e,height:n}}getSheetValues(t=0){return this.dump(t,e=>(e==null?void 0:e.value)??null)}getSheetSerialized(t=0){return this.dump(t,e=>e?this.textOf(e):null)}getCellPrecedents({row:t,col:e,sheet:n=0}){const r=this.recordAt(O(t,e,n));if(!(r!=null&&r.ast))return[];const o=[];return lt(r.ast,i=>{if(i.type==="ref")o.push(Rt(i.sheet??n,Mt(i,t),kt(i,e)));else if(i.type==="range"){const l=i.start.sheet??n,[a,c]=Wt(Mt(i.start,t),Mt(i.end,t)),[h,u]=Wt(kt(i.start,e),kt(i.end,e));o.push({start:Rt(l,a,h),end:Rt(l,c,u)})}}),o}getCellDependents({row:t,col:e,sheet:n=0}){const r=O(t,e,n),o=new Set,i=l=>{var a;o.has(l)||(o.add(l),l.key<0&&((a=l.dependents)==null||a.forEach(i)))};return this.forEachDependent(this.recordAt(r),r,i),[...o].filter(l=>l.key>=0).map(l=>Rt(Z(l.key),Y(l.key),K(l.key)))}calculateFormula(t,e=0){try{const n=this.parse(pe(t),0,0);return this.finalize(st(n,{...this.ctx,sheet:e,row:0,col:0}))}catch(n){if(n instanceof j)return S("#ERROR!",n.message);throw n}}validateFormula(t){try{return this.parse(pe(t),0,0),!0}catch{return!1}}setCellContents(t,e){const n=t.sheet??0;return this.requireSheet(n),this.batch(()=>{Array.isArray(e)?e.forEach((r,o)=>r.forEach((i,l)=>this.writeCell(n,t.row+o,t.col+l,i))):this.writeCell(n,t.row,t.col,e)})}setSheetContent(t,e=0){const n=this.requireSheet(e);return this.batch(()=>{for(const r of[...n.values()])r.raw!==null&&this.writeCell(e,Y(r.key),K(r.key),null);this.setCellContents({row:0,col:0,sheet:e},t)})}batch(t){this.batchDepth++;try{t()}finally{this.batchDepth--}if(this.batchDepth>0)return[];const e=this.pendingKeys,n=this.dirty;this.pendingKeys=new Set,this.dirty=new Set;const r=this.recalculate(e,n);return r.length&&this.listeners.forEach(o=>o(r)),r}addRows(t,e,n=0){return this.restructure({sheet:n,axis:"row",index:t,count:e,remove:!1})}removeRows(t,e,n=0){return this.restructure({sheet:n,axis:"row",index:t,count:e,remove:!0})}addColumns(t,e,n=0){return this.restructure({sheet:n,axis:"col",index:t,count:e,remove:!1})}removeColumns(t,e,n=0){return this.restructure({sheet:n,axis:"col",index:t,count:e,remove:!0})}moveRows(t,e,n,r=0){return this.move("row",t,e,n,r)}moveColumns(t,e,n,r=0){return this.move("col",t,e,n,r)}inverseMove(t,e,n){return Cn(t,e,n)}recalculateVolatile(){return this.batch(()=>{})}captureRemoval(t,e,n,r=0){this.requireSheet(r);const o={sheet:r,axis:t,index:e,count:n},i=t==="row",l={sheet:r,axis:t,index:e,count:n,cells:[],names:[]};this.sheetData.forEach((a,c)=>{if(a)for(const h of a.values()){if(h.raw===null)continue;const u=i?Y(h.key):K(h.key),d=c===r&&u>=e&&u<e+n,m=!!h.ast&&(c===r||!!h.crossSheet)&&bs(o,h.ast,c,u);(d||m)&&l.cells.push({address:{sheet:c,row:Y(h.key),col:K(h.key)},raw:this.textOf(h)})}});for(const a of this.names.values())a.ast&&a.raw!==null&&bs(o,a.ast,-1,0)&&l.names.push({name:a.name,raw:this.textOf(a)});return l}restoreRemoval(t){return this.batch(()=>{t.axis==="row"?this.addRows(t.index,t.count,t.sheet):this.addColumns(t.index,t.count,t.sheet);for(const e of t.cells)this.setCellContents(e.address,e.raw);for(const e of t.names)this.changeNamedExpression(e.name,e.raw)})}shiftFormula(t,e,n){if(!X(t))return t;const r=[],o=this.sheetNames.length;let i;try{i=Ie(pe(t),{resolveSheet:a=>this.getSheetId(a)??o+r.push(a)-1})}catch{return t}return"="+Qt(i,{base:{row:e,col:n},sheetName:a=>a<o?this.sheetNames[a]:r[a-o]})}on(t,e){t==="valuesUpdated"&&this.listeners.add(e)}off(t,e){t==="valuesUpdated"&&this.listeners.delete(e)}destroy(){this.sheetData.forEach(t=>t==null?void 0:t.clear()),this.rangeIndex=[],this.names.clear(),this.unresolved.clear(),this.listeners.clear(),this.volatiles.clear(),this.anchors.clear()}createSheet(t){const e=this.sheetNames.length;return this.sheetNames.push(t),this.sheetIds.set(t.toUpperCase(),e),this.sheetData.push(new Map),this.rangeIndex.push(void 0),e}checkSheetName(t){if(t.trim()==="")throw new Error("Sheet name cannot be empty");if(this.doesSheetExist(t))throw new Error(`Sheet "${t}" already exists`)}unusedSheetName(){for(let t=this.countSheets()+1;;t++)if(!this.doesSheetExist(`Sheet${t}`))return`Sheet${t}`}requireSheet(t){const e=this.sheetData[t];if(!e)throw new Error(`There is no sheet with id ${t}`);return e}recordAt(t){var e;return(e=this.sheetData[Z(t)])==null?void 0:e.get(t)}homeSheet(t){return t.key>=0?Z(t.key):-1}*formulaRecords(){for(const t of this.sheetData)if(t)for(const e of t.values())e.ast&&(yield e);for(const t of this.names.values())t.ast&&(yield t)}textOf(t){if(t.textDirty&&t.ast){const e=t.key>=0?{row:Y(t.key),col:K(t.key)}:void 0;t.raw="="+Qt(t.ast,{base:e,sheetName:n=>this.sheetNames[n]}),t.textDirty=!1}return t.raw}dump(t,e){const n=this.sheetData[t],{width:r,height:o}=this.getSheetDimensions(t);return Array.from({length:o},(i,l)=>Array.from({length:r},(a,c)=>e(n==null?void 0:n.get(O(l,c,t)))))}parse(t,e,n,r){return Ie(t,{base:{row:e,col:n},resolveSheet:o=>{const i=this.getSheetId(o);return r&&(r.crossSheet=!0,i===void 0&&(r.unresolved=!0,this.unresolved.add(r))),i}})}writeCell(t,e,n,r){var c;const o=this.requireSheet(t),i=O(e,n,t);let l=o.get(i);const a=r==null||r==="";a&&(l!=null&&l.spillOwner)||(l&&(l.spillOwner=void 0,l.spillArea&&this.dropSpill(l).forEach(h=>this.pendingKeys.add(h)),this.unlink(l),this.unresolved.delete(l),l.ast=void 0,l.textDirty=l.crossSheet=l.unresolved=!1),a?(c=l==null?void 0:l.dependents)!=null&&c.size?(l.raw=null,l.value=null):l&&(o.delete(i),l.removed=!0):(l||o.set(i,l={key:i,raw:r,value:null}),l.raw=r,X(r)?this.compile(l):l.value=at(r)),this.pendingKeys.add(i))}compile(t){t.value=null;try{t.ast=this.parse(t.raw.slice(1),Y(t.key),K(t.key),t),this.link(t)}catch(e){if(!(e instanceof j))throw e;t.value=S("#ERROR!",e.message)}}setNameExpression(t,e){if(this.unlink(t),this.unresolved.delete(t),t.raw=e??null,t.ast=void 0,t.textDirty=t.unresolved=!1,t.value=at(e),X(e))try{const n=this.parse(e.slice(1),0,0,t),r=this.sheetNames.findIndex(o=>o!==void 0);lt(n,o=>{const i=o.type==="ref"?o:o.type==="range"?o.start:void 0;!i||i.sheet!==void 0||(i.sheet=r,o.type==="range"&&(o.end.sheet=r),t.textDirty=!0)}),t.ast=n,t.crossSheet=!0,t.value=null,this.link(t)}catch(n){if(!(n instanceof j))throw n;t.value=S("#ERROR!",n.message)}this.dirty.add(t)}reresolve(){for(const t of[...this.unresolved]){if(this.unresolved.delete(t),t.removed)continue;const e=this.textOf(t);t.key<0?this.setNameExpression(t,e):(this.unlink(t),t.ast=void 0,t.crossSheet=t.unresolved=!1,this.compile(t),this.dirty.add(t))}}isNameDefined(t){const e=this.names.get(t.toUpperCase());return e!==void 0&&e.raw!==null}definedName(t){if(!this.isNameDefined(t))throw new Error(`Named expression "${t}" does not exist`);return this.names.get(t.toUpperCase())}nameRecord(t){const e=t.toUpperCase();let n=this.names.get(e);return n||this.names.set(e,n={key:-1,raw:null,value:null,name:t}),n}nameValue(t){const e=this.names.get(t.toUpperCase());if(!e||e.raw===null)return S("#NAME?",`Unknown name "${t}"`);if(!e.ast)return e.value;if(this.evaluatingNames.has(e))return S("#CYCLE!");this.evaluatingNames.add(e);try{return st(e.ast,{...this.ctx,sheet:-1,row:0,col:0})}finally{this.evaluatingNames.delete(e)}}ensureCell(t,e,n){const r=this.sheetData[t];if(!r||e<0||n<0)return;const o=O(e,n,t);let i=r.get(o);return i||r.set(o,i={key:o,raw:null,value:null}),i}rangeEntry(t,e,n,r,o){var c;const i=(c=this.rangeIndex)[t]??(c[t]=new Map),l=vs(e,n,r,o);let a=i.get(l);return a||i.set(l,a={sheet:t,r0:e,c0:n,r1:r,c1:o,id:l,dependents:new Set}),a}link(t){if(!t.ast)return;const e=this.homeSheet(t),n=t.key>=0?Y(t.key):0,r=t.key>=0?K(t.key):0,o=[],i=[],l=a=>{a&&(o.push(a),(a.dependents??(a.dependents=new Set)).add(t))};lt(t.ast,a=>{if(a.type==="name")a.name!==""&&l(this.nameRecord(a.name));else if(a.type==="ref")l(this.ensureCell(a.sheet??e,Mt(a,n),kt(a,r)));else{const c=a.start.sheet??e;if(!this.sheetData[c])return;const[h,u]=Wt(Mt(a.start,n),Mt(a.end,n)),[d,m]=Wt(kt(a.start,r),kt(a.end,r)),w=this.rangeEntry(c,h,d,u,m);w.dependents.add(t),i.push(w)}}),t.precedents=o.length?o:void 0,t.rangeDeps=i.length?i:void 0,t.volatile=t.positional=!1,Nt(t.ast,a=>{const c=Le(a);c!=null&&c.volatile&&(t.volatile=!0),c!=null&&c.positional&&(t.positional=!0)}),t.volatile&&this.volatiles.add(t)}unlink(t){var e;if(t.precedents)for(const n of t.precedents)(e=n.dependents)==null||e.delete(t),this.collectPlaceholder(n);if(t.rangeDeps)for(const n of t.rangeDeps){n.dependents.delete(t);const r=this.rangeIndex[n.sheet];n.dependents.size===0&&(r==null?void 0:r.get(n.id))===n&&r.delete(n.id)}t.precedents=t.rangeDeps=void 0,this.volatiles.delete(t)}collectPlaceholder(t){var e;if(!(t.raw!==null||t.removed||(e=t.dependents)!=null&&e.size||t.spillOwner)){if(t.key<0){const n=t.name.toUpperCase();this.names.get(n)===t&&this.names.delete(n)}else{const n=this.sheetData[Z(t.key)];(n==null?void 0:n.get(t.key))===t&&n.delete(t.key)}t.removed=!0}}forEachDependent(t,e,n,r=!1){var a,c;if((a=t==null?void 0:t.dependents)==null||a.forEach(n),r&&((c=t==null?void 0:t.spillCells)!=null&&c.length)&&this.forEachSpillDependent(t,n),e<0)return;const o=this.rangeIndex[Z(e)];if(!(o!=null&&o.size))return;const i=Y(e),l=K(e);for(const h of o.values())i>=h.r0&&i<=h.r1&&l>=h.c0&&l<=h.c1&&h.dependents.forEach(n)}recalculate(t,e){var l;const n=this.trace=new Map;let r=t,o=this.volatiles.size?[...e,...this.volatiles]:e;try{for(let a=1;this.spillSeeds=new Set,this.spillDirty=new Set,this.evaluatePass(r,o),!(!this.spillSeeds.size&&!this.spillDirty.size);a++){if(a===zr){for(const c of this.spillDirty)this.unspill(c),c.value=S("#SPILL!","Spill does not settle");break}r=this.spillSeeds,o=this.spillDirty}}finally{this.trace=null}const i=new Map;for(const a of t)this.sheetData[Z(a)]&&i.set(a,{address:De(a),value:((l=this.recordAt(a))==null?void 0:l.value)??null});for(const[a,c]of n)a.key<0||t.has(a.key)||!this.sheetData[Z(a.key)]||xs(c,a.value)||a.removed&&this.recordAt(a.key)||i.set(a.key,{address:De(a.key),value:a.value});return[...i.values()]}evaluatePass(t,e){const n=this.trace,r=new Map,o=[],i=u=>{u.removed||r.has(u)||(r.set(u,0),o.push(u),n.has(u)||n.set(u,u.value))},l=(u,d)=>{u!=null&&u.ast?i(u):this.forEachDependent(u,d,i)};for(const u of t)l(this.recordAt(u),u),this.anchors.size&&this.forEachAnchorCovering(u,i);for(const u of e)u.removed||l(u,u.key);const a=new Map;for(let u=0;u<o.length;u++){const d=o[u],m=[];this.forEachDependent(d,d.key,w=>{w.removed||(i(w),m.push(w),r.set(w,r.get(w)+1))},!0),m.length&&a.set(d,m)}const c=o.filter(u=>r.get(u)===0),h=this.ctx;this.rangeCache=new Map;try{for(;c.length;){const u=c.pop();r.set(u,-1),u.key>=0&&(h.sheet=Z(u.key),h.row=Y(u.key),h.col=K(u.key),this.assign(u,st(u.ast,h)));for(const d of a.get(u)??[]){const m=r.get(d)-1;r.set(d,m),m===0&&c.push(d)}}}finally{this.rangeCache=null}for(const u of o)r.get(u)!==-1&&(u.spillArea&&this.unspill(u,!1),u.value=S("#CYCLE!"))}finalize(t){if(t instanceof L&&(t.height===0||t.width===0))return S("#CALC!","The result is an empty array");const e=T(t);return e===null?0:e}assign(t,e){if(e instanceof L&&e.height>0&&e.width>0&&(e.height>1||e.width>1)){this.spill(t,e);return}t.spillArea&&this.unspill(t),t.value=this.finalize(e)}spill(t,e){const n=Z(t.key),r=Y(t.key),o=K(t.key),i={r0:r,c0:o,r1:r+e.height-1,c1:o+e.width-1};t.spillArea=i,this.anchors.add(t);const l=this.sheetData[n];if(i.r1>=1048576||i.c1>=16384||this.isBlocked(t,i,l)){this.touchAnchors(this.clearSpill(t),t),t.value=S("#SPILL!","The spill range is not empty");return}const a=new Set(t.spillCells),c=[],h=[];for(let u=0;u<e.height;u++)for(let d=0;d<e.width;d++){if(u===0&&d===0)continue;const m=O(r+u,o+d,n);let w=l.get(m);w||l.set(m,w={key:m,raw:null,value:null});const A=this.finalize(e.values[u][d]);if(w.spillOwner===t){if(a.delete(w),xs(w.value,A)){c.push(w);continue}}else w.spillOwner=t,h.push(m),this.spillSeeds.add(m);this.noteBefore(w),w.value=A,c.push(w)}for(const u of a)u.spillOwner!==t||u.removed||(this.vacate(u),h.push(u.key));t.spillCells=c,this.touchAnchors(h,t),this.rangeCache=new Map,t.value=this.finalize(e.values[0][0])}isBlocked(t,e,n){const r=Z(t.key);for(let o=e.r0;o<=e.r1;o++)for(let i=e.c0;i<=e.c1;i++){const l=n.get(O(o,i,r));if(l&&l!==t&&(l.raw!==null||l.spillOwner&&l.spillOwner!==t))return!0}return!1}unspill(t,e=!0){const n=this.clearSpill(t);e&&this.touchAnchors(n,t),this.anchors.delete(t),t.spillArea=void 0}dropSpill(t){const e=this.clearSpill(t);return this.anchors.delete(t),t.spillArea=void 0,e}clearSpill(t){const e=[];for(const n of t.spillCells??[])n.spillOwner!==t||n.removed||(this.vacate(n),e.push(n.key));return t.spillCells=void 0,e}vacate(t){this.noteBefore(t),t.spillOwner=void 0,t.value=null,this.collectPlaceholder(t)}noteBefore(t){this.trace&&!this.trace.has(t)&&this.trace.set(t,t.value)}touchAnchors(t,e){if(!(this.anchors.size<2||t.length===0))for(const n of t)this.forEachAnchorCovering(n,r=>{r!==e&&this.spillDirty.add(r)})}forEachAnchorCovering(t,e){const n=Z(t),r=Y(t),o=K(t);for(const i of this.anchors){const l=i.spillArea;i.key!==t&&Z(i.key)===n&&r>=l.r0&&r<=l.r1&&o>=l.c0&&o<=l.c1&&e(i)}}forEachSpillDependent(t,e){var a;let n=1/0,r=1/0,o=-1,i=-1;for(const c of t.spillCells){if(c.spillOwner!==t||c.removed)continue;(a=c.dependents)==null||a.forEach(e);const h=Y(c.key),u=K(c.key);h<n&&(n=h),h>o&&(o=h),u<r&&(r=u),u>i&&(i=u)}const l=this.rangeIndex[Z(t.key)];if(!(o<0||!(l!=null&&l.size)))for(const c of l.values())c.r0<=o&&c.r1>=n&&c.c0<=i&&c.c1>=r&&c.dependents.forEach(e)}restructure(t){return this.requireSheet(t.sheet),t.count<=0?[]:this.remap(new Fr(t))}move(t,e,n,r,o){this.requireSheet(o);const i=t==="row"?1048576:16384;if(![e,n,r].every(Number.isInteger)||e<0||n<0||r<0||e+n>i||r>i)throw new RangeError(`Invalid move of ${n} ${t==="row"?"rows":"columns"} from ${e} to ${r}`);return n===0||r>=e&&r<=e+n?[]:this.remap(new Dr(o,t,e,n,r))}remap(t){const e=this.requireSheet(t.sheet),n=t.axis==="row";return this.batch(()=>{const r=new $r(t),o=[],i=(d,m,w,A)=>{d.ast=r.adjust(d.ast,m,w,A),r.text&&(d.textDirty=!0),r.meaning?o.push(d):d.positional&&(r.text||w!==A)&&this.dirty.add(d)};this.sheetData.forEach((d,m)=>{if(!(!d||m===t.sheet))for(const w of d.values())w.ast&&w.crossSheet&&i(w,m,n?Y(w.key):K(w.key),n?Y(w.key):K(w.key))});for(const d of this.names.values())d.ast&&i(d,-1,0,0);const l=new Map,a=[],c=t.sheet*17179869184;e.forEach((d,m)=>{const w=m-c,A=Math.floor(w/16384),y=w-A*16384,p=n?A:y,f=t.index(p);if(f===ee){d.removed=!0,a.push(d);return}d.ast&&i(d,t.sheet,p,f),f!==p&&(d.key=n?m+(f-p)*16384:m+(f-p)),l.set(d.key,d)}),this.sheetData[t.sheet]=l;const h=[];for(const d of a)this.unlink(d),this.unresolved.delete(d),d.spillArea&&h.push(...this.dropSpill(d));for(const d of this.anchors)Z(d.key)===t.sheet&&this.dirty.add(d);const u=this.rangeIndex[t.sheet];if(u){const d=new Map;for(const m of u.values()){const[w,A]=n?[m.r0,m.r1]:[m.c0,m.c1],y=t.span(w,A);!y||Sn(t,w,A,y)||(n?[m.r0,m.r1]=y:[m.c0,m.c1]=y,m.id=vs(m.r0,m.c0,m.r1,m.c1),d.set(m.id,m))}this.rangeIndex[t.sheet]=d}for(const d of o)d.removed||(this.unlink(d),this.link(d),this.dirty.add(d));if(this.pendingKeys.size){const d=this.pendingKeys;this.pendingKeys=new Set;for(const m of d){if(Z(m)!==t.sheet){this.pendingKeys.add(m);continue}const w=Y(m),A=K(m),y=t.index(n?w:A);y!==ee&&this.pendingKeys.add(n?O(y,A,t.sheet):O(w,y,t.sheet))}}h.forEach(d=>this.pendingKeys.add(d))})}}const pe=s=>s.startsWith("=")?s.slice(1):s,Mt=(s,t)=>s.rowAbs?s.row:s.row+t,kt=(s,t)=>s.colAbs?s.col:s.col+t,Wt=(s,t)=>s<=t?[s,t]:[t,s];function Rt(s,t,e){return s===0?{row:t,col:e}:{row:t,col:e,sheet:s}}function Ir(s,t){let e=!1;return lt(s,n=>{(n.type==="ref"&&n.sheet===t||n.type==="range"&&n.start.sheet===t)&&(e=!0)}),e}function xs(s,t){return s instanceof Object&&t instanceof Object?s.code===t.code:s===t}function Or(s,t,e){const n=s.length,r=[],o=s.every(a=>typeof a=="number")?s:null,i=o&&n>=2?En(o):void 0,l=Ur(s);for(let a=0;a<t;a++){if(o&&i!==void 0){r.push(Pr(o[n-1]+i*(a+1)));continue}if(l){const u=a+1;r.push(`${l.prefix}${l.last+l.step*u}${l.suffix}`);continue}const c=a%n,h=s[c];r.push(X(h)?e(h,c,n+a):h)}return r}function En(s){const t=s[1]-s[0];for(let e=2;e<s.length;e++)if(Math.abs(s[e]-s[e-1]-t)>1e-9)return;return t}const As=/^(.*?)(\d+)(\D*)$/;function Ur(s){if(!s.every(i=>typeof i=="string"&&!X(i)&&As.test(i)))return;const t=s.map(i=>As.exec(i)),{1:e,3:n}=t[0];if(!t.every(i=>i[1]===e&&i[3]===n))return;const r=t.map(i=>Number(i[2])),o=r.length>=2?En(r):1;if(o!==void 0)return{prefix:e,suffix:n,last:r[r.length-1],step:o}}const Pr=s=>Number(s.toPrecision(15));class Ft{constructor(t,e,n){v(this,"sizes");v(this,"prefix",null);this.defaultSize=e,this.sizes=Array.from({length:t},(r,o)=>Array.isArray(n)?n[o]??e:n??e)}get count(){return this.sizes.length}get total(){return this.offset(this.count)}size(t){return this.sizes[t]??this.defaultSize}setSize(t,e){this.sizes[t]=e,this.prefix=null}offset(t){if(!this.prefix){const e=new Float64Array(this.sizes.length+1);for(let n=0;n<this.sizes.length;n++)e[n+1]=e[n]+this.sizes[n];this.prefix=e}return this.prefix[Math.max(0,Math.min(t,this.sizes.length))]}indexAt(t){if(this.count===0)return 0;let e=0,n=this.count-1;for(;e<n;){const r=e+n+1>>1;this.offset(r)<=t?e=r:n=r-1}return e}insert(t,e){this.sizes.splice(t,0,...Array(e).fill(this.defaultSize)),this.prefix=null}remove(t,e){this.sizes.splice(t,e),this.prefix=null}resize(t){t>this.count?this.insert(this.count,t-this.count):t<this.count&&this.remove(t,this.count-t)}}const Mn=s=>s.length>0&&s.every(t=>t!==null&&typeof t=="object"&&!Array.isArray(t));function Hr(s,t){let e=s;for(const n of t.split(".")){if(e===null||typeof e!="object")return;e=e[n]}return e}function _r(s,t,e){const n=t.split(".");let r=s;for(const o of n.slice(0,-1))(r[o]===null||typeof r[o]!="object")&&(r[o]={}),r=r[o];r[n[n.length-1]]=e}function Vr(s){return s==null?null:typeof s=="number"||typeof s=="string"||typeof s=="boolean"?s:s instanceof Date?zt(s.getFullYear(),s.getMonth()+1,s.getDate()):String(s)}class ae{constructor(t,e,n){this.objects=t,this.fields=e,this.schema=n}static create(t,e,n){const r=e.some(o=>o!==void 0)?[...e]:Object.keys(t[0]??(n==null?void 0:n())??{});return new ae(t,r,n)}toRows(){return this.objects.map(t=>this.fields.map(e=>e===void 0?null:Vr(Hr(t,e))))}write(t,e,n){const r=this.fields[e];if(r!==void 0){for(;this.objects.length<=t;)this.objects.push(this.newRow());_r(this.objects[t],r,n)}}insertRows(t,e){this.objects.splice(t,0,...Array.from({length:e},()=>this.newRow()))}removeRows(t,e){this.objects.splice(t,e)}ensureRows(t){for(;this.objects.length<t;)this.objects.push(this.newRow())}insertCols(t,e){t<=this.fields.length&&this.fields.splice(t,0,...Array(e))}removeCols(t,e){this.fields.splice(t,e)}snapshot(){return{objects:[...this.objects],fields:[...this.fields]}}restore(t){this.objects.splice(0,this.objects.length,...t.objects),this.fields=[...t.fields]}newRow(){return this.schema?this.schema():{}}}function Xr(s){let t="";return s.bold&&(t+=" ct-b"),s.italic&&(t+=" ct-i"),s.underline&&(t+=" ct-u"),s.strike&&(t+=" ct-s"),s.wrap&&(t+=" ct-wrap"),s.align&&(t+=` ct-al-${s.align[0]}`),t}const Cs=new Map;function Br(s,t){const e=`${s}|${JSON.stringify(t)}`;let n=Cs.get(e);return n||(n=new Intl.NumberFormat(s,{style:t.style??"decimal",currency:t.style==="currency"?t.currency??"TRY":void 0,minimumFractionDigits:t.minimumFractionDigits,maximumFractionDigits:t.maximumFractionDigits??(t.style==="currency"||t.style==="percent"?void 0:Math.max(t.minimumFractionDigits??0,10)),useGrouping:t.useGrouping??!0}),Cs.set(e,n)),n}const rs=s=>s!=null&&s.startsWith("tr")||s!=null&&s.startsWith("de")?"DD.MM.YYYY":"YYYY-MM-DD";function Ss(s,t,e){return t.type==="checkbox"?{text:s===!0?"☑":"☐",kind:"check"}:s==null?{text:""}:s instanceof ct?{text:s.code,kind:"err"}:typeof s=="number"?t.type==="date"?{text:Je(s,t.dateFormat??rs(e)),kind:"date"}:t.numericFormat?{text:Br(e,t.numericFormat).format(s),kind:"num"}:{text:Ye(s),kind:"num"}:typeof s=="boolean"?{text:s?"TRUE":"FALSE",kind:"bool"}:{text:s}}function jt(s,t,e){return s==null?"":t.type==="date"&&typeof s=="number"?Je(s,t.dateFormat??rs(e)):String(s)}function me(s,t={}){if(s==="")return null;if(s.length>1&&s[0]==="=")return s;if(t.type==="date")return oe(s.trim())??s;if(t.type==="checkbox"){const n=at(s);return typeof n=="boolean"?n:typeof n=="number"?n!==0:s}if(t.type==="numeric"){const n=s.trim();if(/^[+-]?\d{1,3}(\.\d{3})*(,\d+)?$/.test(n)||/^[+-]?\d+,\d+$/.test(n)){const r=Ct(n.replace(/\./g,"").replace(",","."));if(r!==void 0)return r}}if(t.type==="dropdown"||t.type==="text")return(t.type==="text"?void 0:Ct(s))??s;const e=at(s);return typeof e=="number"||typeof e=="boolean"?e:s}function Es(s,t,e,n,r){if(t==null||t==="")return;if(!X(t)){if(e.type==="numeric"&&typeof s!="number")return"Not a number";if(e.type==="date"&&typeof s!="number")return"Not a date";if(e.type==="dropdown"&&e.strict!==!1&&e.source&&!e.source.includes(String(s)))return"Not in list"}const o=e.validator;if(!o)return;if(o instanceof RegExp)return o.test(String(s??""))?void 0:"Invalid value";const i=o(s,n,r);return i===!0?void 0:typeof i=="string"?i:"Invalid value"}const ge=s=>!!s.validator||s.type==="numeric"||s.type==="date"||s.type==="dropdown",Wr=["contains","notContains","equals","notEquals","greaterThan","greaterOrEqual","lessThan","lessOrEqual","isEmpty","isNotEmpty"],Ms=1e3;function jr(s){var m,w,A,y,p,f;const t=s.anchor.ownerDocument,e=s.messages,n=t.createElement("div");n.className="ct-menu",n.setAttribute("role","dialog"),n.setAttribute("aria-label",e.columnMenu);const r=(b,C,F)=>{const R=t.createElement("button");return R.type="button",R.className=C,R.textContent=b,R.addEventListener("click",F),R};if(s.sortable){const b=t.createElement("div");b.className="ct-menu-section",b.append(r(e.sortAsc,`ct-menu-item${s.sort==="asc"?" ct-on":""}`,()=>(s.onSort("asc"),d())),r(e.sortDesc,`ct-menu-item${s.sort==="desc"?" ct-on":""}`,()=>(s.onSort("desc"),d()))),s.sortedElsewhere&&b.append(r(e.sortThenAsc,"ct-menu-item",()=>(s.onSort("asc",!0),d())),r(e.sortThenDesc,"ct-menu-item",()=>(s.onSort("desc",!0),d()))),s.sort&&b.append(r(e.sortClear,"ct-menu-item",()=>(s.onSort(null),d()))),n.append(b)}let o=()=>{};if(s.filterable){const b=t.createElement("div");b.className="ct-menu-section";const C=t.createElement("div");C.className="ct-menu-title",C.textContent=e.filterByCondition;const F=t.createElement("select");F.append(new Option(e.none,""));for(const U of Wr)F.append(new Option(e[U],U));F.value=((w=(m=s.filter)==null?void 0:m.condition)==null?void 0:w.op)??"";const R=t.createElement("input");R.type="text",R.value=((y=(A=s.filter)==null?void 0:A.condition)==null?void 0:y.value)??"";const $=()=>{R.hidden=!F.value||F.value==="isEmpty"||F.value==="isNotEmpty"};F.addEventListener("change",$),$(),b.append(C,F,R);const z=t.createElement("div");z.className="ct-menu-section";const P=t.createElement("div");P.className="ct-menu-title",P.textContent=e.filterByValue;const H=t.createElement("input");H.type="search",H.placeholder=e.search;const _=t.createElement("div");_.className="ct-menu-list";const k=new Set(((p=s.filter)==null?void 0:p.values)??s.values),M=s.values.slice(0,Ms),D=[],E=(U,et)=>{const ot=t.createElement("label"),Bt=t.createElement("input");return Bt.type="checkbox",Bt.checked=et,ot.append(Bt,t.createTextNode(U)),[ot,Bt]},[N,I]=E(e.selectAll,M.every(U=>k.has(U)));I.addEventListener("change",()=>D.forEach(([,U,et])=>!et.hidden&&(U.checked=I.checked))),_.append(N);for(const U of M){const[et,ot]=E(U===""?e.blanks:U,k.has(U));D.push([U,ot,et]),_.append(et)}H.addEventListener("input",()=>{const U=H.value.toLocaleLowerCase(s.locale);D.forEach(([et,,ot])=>ot.hidden=!et.toLocaleLowerCase(s.locale).includes(U))}),z.append(P,H,_),n.append(b,z),o=()=>{const U={};F.value&&(U.condition={op:F.value,value:R.value});const et=D.filter(([,ot])=>ot.checked).map(([ot])=>ot);et.length<D.length&&(U.values=[...et,...s.values.slice(Ms)]),s.onFilter(U.condition||U.values?U:null),d()};const W=t.createElement("div");W.className="ct-menu-footer",W.append(r(e.clearFilter,"ct-menu-link",()=>(s.onFilter(null),d())),r(e.cancel,"ct-btn",()=>d()),r(e.ok,"ct-btn ct-primary",()=>o())),n.append(W)}t.body.append(n);const i=s.anchor.getBoundingClientRect(),l=n.offsetWidth||240,a=Math.max(8,Math.min(i.right-l,(((f=t.defaultView)==null?void 0:f.innerWidth)??1024)-l-8));n.style.left=`${a}px`,n.style.top=`${i.bottom+2}px`;const c=b=>{n.contains(b.target)||d()},h=b=>{b.key==="Escape"?(b.stopPropagation(),d()):b.key==="Enter"&&s.filterable&&b.target.tagName!=="BUTTON"&&o()};t.addEventListener("mousedown",c,!0),n.addEventListener("keydown",h);let u=!1;function d(){u||(u=!0,t.removeEventListener("mousedown",c,!0),n.remove(),s.onClose())}return d}function kn(s){return s.replace(/"[^"]*"|\\.|_.|\*./g,"").replace(/\[(?![hms]+\])[^\]]*\]/gi,"")}function ce(s){if(!s)return!1;const t=s.split(";")[0];return/[dmyhs]/i.test(kn(t).replace(/General/gi,""))}const Yr=/[-/.:, $+()!^&'~{}<>=]/;function Rn(s){const t={YYYY:"yyyy",YY:"yy",MM:"mm",M:"m",DD:"dd",D:"d",HH:"hh",mm:"mm",ss:"ss"};let e="";const n=/YYYY|YY|MM|M|DD|D|HH|mm|ss/g;let r=0;for(let o=n.exec(s);o;o=n.exec(s))e+=ks(s.slice(r,o.index))+t[o[0]],r=o.index+o[0].length;return e+ks(s.slice(r))}function ks(s){let t="";for(const e of s)t+=Yr.test(e)?e:`\\${e}`;return t}const Kr=s=>s?`"${s.replace(/"/g,"")}"`:"";function we(s,t,e){return e<=0?s:`${s}.${"0".repeat(t)}${"#".repeat(Math.max(0,e-t))}`}function qr(s,t){var o;const e=s.style??"decimal",n=s.useGrouping===!1?"0":"#,##0";if(e==="percent"){const i=s.minimumFractionDigits??s.maximumFractionDigits??0;return`${we(n,i,s.maximumFractionDigits??i)}%`}if(e==="currency"){const i=new Intl.NumberFormat(t,{style:"currency",currency:s.currency??"TRY"}),l=i.resolvedOptions(),a=s.minimumFractionDigits??l.minimumFractionDigits??2,c=Math.max(a,s.maximumFractionDigits??l.maximumFractionDigits??a),h=i.formatToParts(1),u=h.findIndex(y=>y.type==="currency"),d=h.findIndex(y=>y.type==="integer"),m=Kr(((o=h[u])==null?void 0:o.value)??s.currency??""),w=h.slice(Math.min(u,d)+1,Math.max(u,d)).some(y=>y.type==="literal")?" ":"",A=we(n,a,c);return u<d?`${m}${w}${A}`:`${A}${w}${m}`}if(s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0)return;const r=s.minimumFractionDigits??0;return we(n,r,Math.max(r,s.maximumFractionDigits??r))}function Fn(s,t){if(s.formatCode)return s.formatCode;if(s.type==="date")return Rn(s.dateFormat??rs(t));if(s.numericFormat)return qr(s.numericFormat,t)}const it=(s,t=2)=>String(s).padStart(t,"0");function Dn(s,t,e){const n=t.split(";")[0],{year:r,month:o,day:i}=gt(s);let l=Math.round((s-Math.floor(s))*86400);l>=86400&&(l=86399);const a=Math.floor(l/3600),c=Math.floor(l/60)%60,h=l%60,u=/AM\/PM|A\/P/i.test(kn(n)),d=a%12===0?12:a%12,m=new Date(Date.UTC(2e3,0,1));m.setUTCFullYear(r,o-1,i);const w=f=>new Intl.DateTimeFormat(e,{...f,timeZone:"UTC"}).format(m),A=/"([^"]*)"|\\(.)|_(.)|\*(.)|\[(h+|m+|s+)\]|\[[^\]]*\]|AM\/PM|A\/P|y+|m+|d+|h+|s+|./gi,y=[];for(let f=A.exec(n);f;f=A.exec(n))y.push(f[0]);let p="";return y.forEach((f,b)=>{const C=f.toLowerCase();if(f[0]==='"')p+=f.slice(1,-1);else if(f[0]==="\\")p+=f[1];else if(f[0]==="_")p+=" ";else if(f[0]==="*")p+="";else if(/^\[h+\]$/i.test(f))p+=it(Math.floor(s)*24+a,C.length-2);else if(/^\[m+\]$/i.test(f))p+=it(Math.floor(s*1440),C.length-2);else if(/^\[s+\]$/i.test(f))p+=it(Math.floor(s*86400),C.length-2);else if(f[0]==="[")p+="";else if(C==="am/pm")p+=a<12?"AM":"PM";else if(C==="a/p")p+=a<12?"A":"P";else if(C[0]==="y")p+=C.length<=2?it(r%100):it(r,4);else if(C[0]==="d")p+=C.length===1?String(i):C.length===2?it(i):w({weekday:C.length===3?"short":"long"});else if(C[0]==="h")p+=C.length===1?String(u?d:a):it(u?d:a);else if(C[0]==="s")p+=C.length===1?String(h):it(h);else if(C[0]==="m"){const F=y.slice(0,b).reverse().find(z=>/^(\[?h+\]?|[dmys]+)$/i.test(z)),R=y.slice(b+1).find(z=>/^(\[?s+\]?|[dmyh]+)$/i.test(z));(!!F&&/h/i.test(F)||!!R&&/s/i.test(R))&&C.length<=2?p+=C.length===1?String(c):it(c):C.length===1?p+=String(o):C.length===2?p+=it(o):p+=w({month:C.length===3?"short":C.length===4?"long":"narrow"})}else p+=f}),p}const Zr=/^[=+\-@\t\r]/;function Gr(s,t){return s.includes(t)||/["\r\n]/.test(s)||/^\s|\s$/.test(s)}const Qr=(s,t)=>Gr(s,t)?`"${s.replace(/"/g,'""')}"`:s;function Jr(s,t,e,n){var o,i;const r=(i=(o=s.values)==null?void 0:o[t])==null?void 0:i[e];return r!==void 0?r:X(n)?n:at(n)}function Nn(s,t={}){var m,w,A,y;const e=t.delimiter??",",n=t.lineEnding??`\r
3
+ `,r=t.decimalSeparator??".",o=t.values==="raw",i=t.escapeFormulas!==!1,l=p=>i&&Zr.test(p)?`'${p}`:p,a=Math.max(s.data.length,((m=s.values)==null?void 0:m.length)??0);let c=0;for(let p=0;p<a;p++)c=Math.max(c,((w=s.data[p])==null?void 0:w.length)??0,((y=(A=s.values)==null?void 0:A[p])==null?void 0:y.length)??0);const h=(p,f)=>{var F,R,$;const b=(F=s.data[p])==null?void 0:F[f];if(o)return b==null?"":typeof b=="boolean"?b?"TRUE":"FALSE":typeof b=="string"?X(b)?b:l(b):u(b);const C=Jr(s,p,f,b);if(C==null)return"";if(C instanceof ct)return C.code;if(typeof C=="boolean")return C?"TRUE":"FALSE";if(typeof C=="number"){if(t.values==="formatted"&&s.text)return s.text(p,f);const z=($=(R=s.format)==null?void 0:R.call(s,p,f))==null?void 0:$.numberFormat;return ce(z)&&Number.isFinite(C)&&C>=0?Dn(C,z,t.locale):u(C)}return C===b&&X(b)?C:l(C)},u=p=>{if(typeof p=="string")return p;const f=String(B(p));return r==="."?f:f.replace(".",r)},d=[];for(let p=0;p<a;p++){const f=[];for(let b=0;b<c;b++)f.push(Qr(h(p,b),e));d.push(f.join(e))}return(t.bom===!1?"":"\uFEFF")+d.join(n)}const $n="text/csv;charset=utf-8";function Pe(s,t,e){const n=new Blob([s],{type:e}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=t,o.style.display="none",document.body.appendChild(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(r),0)}const to=new RegExp("[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F￾￿]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]","g"),eo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function nt(s){return s.replace(to,"").replace(/[&<>"']/g,t=>eo[t])}function He(s){let t="";for(const[e,n]of Object.entries(s))n===void 0||n===!1||(t+=` ${e}="${n===!0?"1":nt(String(n))}"`);return t}const ht=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
4
+ `,so="http://schemas.openxmlformats.org/spreadsheetml/2006/main",no={General:0,0:1,"0.00":2,"#,##0":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"@":49};function Rs(s){if(!s)return;let t=/^#?([0-9a-f]{6})$/i.exec(s.trim());return t?`FF${t[1].toUpperCase()}`:(t=/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(s.trim()),t?`FF${(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]).toUpperCase()}`:void 0)}class ye{constructor(t){v(this,"items",[]);v(this,"index",new Map);t.forEach(e=>this.add(e))}add(t){let e=this.index.get(t);return e===void 0&&(e=this.items.push(t)-1,this.index.set(t,e)),e}}const Fs=(s,t,e,n,r)=>`<font>${s?"<b/>":""}${t?"<i/>":""}${r?"<strike/>":""}${e?"<u/>":""}<sz val="11"/>${n?`<color rgb="${n}"/>`:""}<name val="Calibri"/><family val="2"/></font>`;class ro{constructor(){v(this,"fonts",new ye([Fs()]));v(this,"fills",new ye(['<fill><patternFill patternType="none"/></fill>','<fill><patternFill patternType="gray125"/></fill>']));v(this,"numFmts",new Map);v(this,"xfs",new ye(['<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>']))}numFmtId(t){const e=no[t];if(e!==void 0)return e;let n=this.numFmts.get(t);return n===void 0&&this.numFmts.set(t,n=164+this.numFmts.size),n}styleId(t){if(!t)return 0;const e=t.numberFormat?this.numFmtId(t.numberFormat):0,n=Rs(t.color),r=t.bold||t.italic||t.underline||t.strike||n?this.fonts.add(Fs(t.bold,t.italic,t.underline,n,t.strike)):0,o=Rs(t.background),i=o?this.fills.add(`<fill><patternFill patternType="solid"><fgColor rgb="${o}"/><bgColor indexed="64"/></patternFill></fill>`):0,l=t.align||t.wrap?`<alignment${He({horizontal:t.align,wrapText:t.wrap})}/>`:"",a=`<xf${He({numFmtId:e,fontId:r,fillId:i,borderId:0,xfId:0,applyNumberFormat:e>0,applyFont:r>0,applyFill:i>0,applyAlignment:!!l})}`+(l?`>${l}</xf>`:"/>");return this.xfs.add(a)}toXml(){const t=[...this.numFmts].map(([n,r])=>`<numFmt numFmtId="${r}" formatCode="${nt(n)}"/>`).join(""),e=(n,r)=>`<${n} count="${r.length}">${r.join("")}</${n}>`;return ht+`<styleSheet xmlns="${so}">`+(this.numFmts.size?`<numFmts count="${this.numFmts.size}">${t}</numFmts>`:"")+e("fonts",this.fonts.items)+e("fills",this.fills.items)+'<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'+e("cellXfs",this.xfs.items)+'<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles><dxfs count="0"/><tableStyles count="0"/></styleSheet>'}}let Ut;function oo(){if(Ut)return Ut;Ut=new Uint32Array(256);for(let s=0;s<256;s++){let t=s;for(let e=0;e<8;e++)t=t&1?3988292384^t>>>1:t>>>1;Ut[s]=t>>>0}return Ut}function he(s){const t=oo();let e=4294967295;for(let n=0;n<s.length;n++)e=t[(e^s[n])&255]^e>>>8;return(e^4294967295)>>>0}function io(s){const t=Math.max(1980,s.getFullYear());return{time:s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1,date:t-1980<<9|s.getMonth()+1<<5|s.getDate()}}const Ln=0,lo=8,Ds=2048;function Tn(s,t){if(s.length>65535)throw new RangeError("Too many ZIP entries");const{time:e,date:n}=io(t);let r=0,o=0;for(const m of s)r+=30+m.name.length+m.payload.length,o+=46+m.name.length;if(r+o+22>4294967295)throw new RangeError("ZIP archive too large (no ZIP64 support)");const i=new Uint8Array(r+o+22),l=new DataView(i.buffer),a=[];let c=0;const h=m=>(l.setUint16(c,m,!0),c+=2),u=m=>(l.setUint32(c,m>>>0,!0),c+=4);for(const m of s)a.push(c),u(67324752),h(20),h(Ds),h(m.method),h(e),h(n),u(m.crc),u(m.payload.length),u(m.size),h(m.name.length),h(0),i.set(m.name,c),c+=m.name.length,i.set(m.payload,c),c+=m.payload.length;const d=c;return s.forEach((m,w)=>{u(33639248),h(20),h(20),h(Ds),h(m.method),h(e),h(n),u(m.crc),u(m.payload.length),u(m.size),h(m.name.length),h(0),h(0),h(0),h(0),u(0),u(a[w]),i.set(m.name,c),c+=m.name.length}),u(101010256),h(0),h(0),h(s.length),h(s.length),u(o),u(d),h(0),i}const zn=new TextEncoder;function In(s,t=new Date){return Tn(s.map(e=>({name:zn.encode(e.path),crc:he(e.data),size:e.data.length,method:Ln,payload:e.data})),t)}async function ao(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}const co=()=>typeof CompressionStream=="function";async function On(s,t=new Date){const e=co(),n=[];for(const r of s){let o=r.data,i=Ln;if(e&&r.data.length>0)try{const l=await ao(r.data);l.length<r.data.length&&(o=l,i=lo)}catch{}n.push({name:zn.encode(r.path),crc:he(r.data),size:r.data.length,method:i,payload:o})}return Tn(n,t)}const Un="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",os="http://schemas.openxmlformats.org/spreadsheetml/2006/main",xt="http://schemas.openxmlformats.org/officeDocument/2006/relationships",be="http://schemas.openxmlformats.org/package/2006/relationships",Yt="application/vnd.openxmlformats-officedocument.spreadsheetml",is=32767,ho=new Set(["#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A"]);function Pn(s){const t=new Set;return s.map((e,n)=>{let r=e.replace(/[:\\/?*[\]]/g,"_").replace(/^'+|'+$/g,"").trim();r||(r=`Sheet${n+1}`),r=[...r].slice(0,31).join("");let o=r;for(let i=2;t.has(o.toLowerCase());i++){const l=` (${i})`;o=[...r].slice(0,31-l.length).join("")+l}return t.add(o.toLowerCase()),o})}const Hn=s=>Math.max(0,Math.round((s-5)/7*256)/256),uo=s=>Math.round(s*.75*100)/100,Lt=(s,t)=>`${Tt(t)}${s+1}`,ve=(s,t,e,n)=>`${Lt(s,t)}:${Lt(s+e-1,t+n-1)}`;class fo{constructor(){v(this,"index",new Map);v(this,"list",[]);v(this,"count",0)}add(t){this.count++;let e=this.index.get(t);return e===void 0&&(e=this.list.push(t)-1,this.index.set(t,e)),e}toXml(){const t=this.list.map(e=>`<si>${po(e)}</si>`).join("");return`${ht}<sst xmlns="${os}" count="${this.count}" uniqueCount="${this.list.length}">${t}</sst>`}}const po=s=>`<t${/^\s|\s$|\n/.test(s)?' xml:space="preserve"':""}>${nt(s.slice(0,is))}</t>`;function _n(s){return ho.has(s.code)?s.code:"#VALUE!"}function mo(s,t,e,n){return e===null?t?`<c r="${s}"${t}/>`:"":typeof e=="number"?Number.isFinite(e)?`<c r="${s}"${t}><v>${e}</v></c>`:`<c r="${s}"${t} t="e"><v>#NUM!</v></c>`:typeof e=="boolean"?`<c r="${s}"${t} t="b"><v>${e?1:0}</v></c>`:e instanceof ct?`<c r="${s}"${t} t="e"><v>${_n(e)}</v></c>`:`<c r="${s}"${t} t="s"><v>${n.add(e.slice(0,is))}</v></c>`}function go(s,t,e,n){const r=`<f>${nt(e.slice(1))}</f>`;return n==null?`<c r="${s}"${t}>${r}</c>`:typeof n=="number"?Number.isFinite(n)?`<c r="${s}"${t}>${r}<v>${n}</v></c>`:`<c r="${s}"${t} t="e">${r}<v>#NUM!</v></c>`:typeof n=="boolean"?`<c r="${s}"${t} t="b">${r}<v>${n?1:0}</v></c>`:n instanceof ct?`<c r="${s}"${t} t="e">${r}<v>${_n(n)}</v></c>`:`<c r="${s}"${t} t="str">${r}<v>${nt(n.slice(0,is))}</v></c>`}function wo(s){const t=[];for(const e of s??[]){if(e.rowspan<1||e.colspan<1||e.rowspan*e.colspan<2||e.row<0||e.col<0)continue;t.some(r=>e.row<r.row+r.rowspan&&r.row<e.row+e.rowspan&&e.col<r.col+r.colspan&&r.col<e.col+e.colspan)||t.push(e)}return t}function yo(s,t,e,n){var p,f,b,C,F;const r=s.data.length;let o=0;for(const R of s.data)o=Math.max(o,(R==null?void 0:R.length)??0);if(r>1048576||o>16384)throw new RangeError(`Sheet "${s.name}" exceeds 1048576 rows or 16384 columns`);let i=`${ht}<worksheet xmlns="${os}" xmlns:r="${xt}">`;i+=`<dimension ref="${r&&o?ve(0,0,r,o):"A1"}"/>`;const l=Math.max(0,Math.floor(((p=s.frozen)==null?void 0:p.rows)??0)),a=Math.max(0,Math.floor(((f=s.frozen)==null?void 0:f.cols)??0)),c=t===0?' tabSelected="1"':"";if(l||a){const R=l&&a?"bottomRight":l?"bottomLeft":"topRight";i+=`<sheetViews><sheetView${c} workbookViewId="0"><pane${He({xSplit:a||void 0,ySplit:l||void 0,topLeftCell:Lt(l,a),activePane:R,state:"frozen"})}/><selection pane="${R}" activeCell="${Lt(l,a)}" sqref="${Lt(l,a)}"/></sheetView></sheetViews>`}else i+=`<sheetViews><sheetView${c} workbookViewId="0"/></sheetViews>`;i+='<sheetFormatPr defaultRowHeight="15"/>';const h=s.colWidths??[],u=[];h.forEach((R,$)=>{typeof R=="number"&&R>0&&$<16384&&u.push(`<col min="${$+1}" max="${$+1}" width="${Hn(R)}" customWidth="1"/>`)}),u.length&&(i+=`<cols>${u.join("")}</cols>`);const d=s.rowHeights??[],m=Math.min(1048576,Math.max(r,d.length)),w=[];for(let R=0;R<m;R++){const $=s.data[R]??[];let z="";for(let _=0;_<$.length;_++){const k=e.styleId((b=s.format)==null?void 0:b.call(s,R,_)),M=k?` s="${k}"`:"",D=$[_],E=Lt(R,_);z+=X(D)?go(E,M,D,(F=(C=s.values)==null?void 0:C[R])==null?void 0:F[_]):mo(E,M,at(D),n)}const P=d[R],H=typeof P=="number"&&P>0?` ht="${uo(P)}" customHeight="1"`:"";(z||H)&&w.push(`<row r="${R+1}"${H}>${z}</row>`)}i+=w.length?`<sheetData>${w.join("")}</sheetData>`:"<sheetData/>";const A=s.autoFilter;A&&A.rows>0&&A.cols>0&&(i+=`<autoFilter ref="${ve(A.row,A.col,A.rows,A.cols)}"/>`);const y=wo(s.merges);if(y.length){i+=`<mergeCells count="${y.length}">`;for(const R of y)i+=`<mergeCell ref="${ve(R.row,R.col,R.rowspan,R.colspan)}"/>`;i+="</mergeCells>"}return i+='<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>',i+"</worksheet>"}const bo=s=>s.toISOString().replace(/\.\d{3}Z$/,"Z");function ls(s,t={}){if(!s.length)throw new Error("A workbook needs at least one sheet");const e=Pn(s.map(f=>f.name)),n=new ro,r=new fo,o=s.map((f,b)=>yo(f,b,n,r)),i=bo(t.modified??new Date),l=`${ht}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="${Yt}.sheet.main+xml"/>`+s.map((f,b)=>`<Override PartName="/xl/worksheets/sheet${b+1}.xml" ContentType="${Yt}.worksheet+xml"/>`).join("")+`<Override PartName="/xl/styles.xml" ContentType="${Yt}.styles+xml"/><Override PartName="/xl/sharedStrings.xml" ContentType="${Yt}.sharedStrings+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/></Types>`,a=`${ht}<Relationships xmlns="${be}"><Relationship Id="rId1" Type="${xt}/officeDocument" Target="xl/workbook.xml"/><Relationship Id="rId2" Type="${be}/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId3" Type="${xt}/extended-properties" Target="docProps/app.xml"/></Relationships>`,c=nt(t.creator??"CenituTable"),h=`${ht}<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:creator>${c}</dc:creator><cp:lastModifiedBy>${c}</cp:lastModifiedBy><dcterms:created xsi:type="dcterms:W3CDTF">${i}</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">${i}</dcterms:modified></cp:coreProperties>`,u=`${ht}<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><Application>CenituTable</Application><HeadingPairs><vt:vector size="2" baseType="variant"><vt:variant><vt:lpstr>Worksheets</vt:lpstr></vt:variant><vt:variant><vt:i4>${e.length}</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size="${e.length}" baseType="lpstr">`+e.map(f=>`<vt:lpstr>${nt(f)}</vt:lpstr>`).join("")+"</vt:vector></TitlesOfParts></Properties>",d=s.map((f,b)=>{const C=f.autoFilter;if(!C||C.rows<1||C.cols<1)return"";const F=($,z)=>`$${Tt(z)}$${$+1}`,R=`'${e[b].replace(/'/g,"''")}'!${F(C.row,C.col)}:${F(C.row+C.rows-1,C.col+C.cols-1)}`;return`<definedName name="_xlnm._FilterDatabase" localSheetId="${b}" hidden="1">${nt(R)}</definedName>`}).join(""),m=`${ht}<workbook xmlns="${os}" xmlns:r="${xt}"><bookViews><workbookView activeTab="0"/></bookViews><sheets>`+e.map((f,b)=>`<sheet name="${nt(f)}" sheetId="${b+1}" r:id="rId${b+1}"/>`).join("")+"</sheets>"+(d?`<definedNames>${d}</definedNames>`:"")+'<calcPr calcId="191029" fullCalcOnLoad="1"/></workbook>',w=s.length,A=`${ht}<Relationships xmlns="${be}">`+s.map((f,b)=>`<Relationship Id="rId${b+1}" Type="${xt}/worksheet" Target="worksheets/sheet${b+1}.xml"/>`).join("")+`<Relationship Id="rId${w+1}" Type="${xt}/styles" Target="styles.xml"/><Relationship Id="rId${w+2}" Type="${xt}/sharedStrings" Target="sharedStrings.xml"/></Relationships>`,y=new TextEncoder,p=(f,b)=>({path:f,data:y.encode(b)});return[p("[Content_Types].xml",l),p("_rels/.rels",a),p("docProps/core.xml",h),p("docProps/app.xml",u),p("xl/workbook.xml",m),p("xl/_rels/workbook.xml.rels",A),p("xl/styles.xml",n.toXml()),p("xl/sharedStrings.xml",r.toXml()),...o.map((f,b)=>p(`xl/worksheets/sheet${b+1}.xml`,f))]}function vo(s,t={}){return In(ls(s,t),t.modified)}function Vn(s,t={}){return On(ls(s,t),t.modified)}const Ns=0,xo=8,Ao=1,_e=22,Co=1024**3;function So(s){const t=Math.max(0,s.byteLength-_e-65535);for(let e=s.byteLength-_e;e>=t;e--)if(s.getUint32(e,!0)===101010256)return e;throw new Error("Not a ZIP archive")}function Eo(s){const t=new DataView(s.buffer,s.byteOffset,s.byteLength);if(s.length<_e)throw new Error("Not a ZIP archive");const e=So(t),n=t.getUint16(e+10,!0);let r=t.getUint32(e+16,!0);const o=new TextDecoder,i=[];for(let l=0;l<n;l++){if(r+46>s.length||t.getUint32(r,!0)!==33639248)throw new Error("Corrupt ZIP directory");const a=t.getUint16(r+28,!0);i.push({path:o.decode(s.subarray(r+46,r+46+a)),flags:t.getUint16(r+8,!0),method:t.getUint16(r+10,!0),crc:t.getUint32(r+16,!0),compressedSize:t.getUint32(r+20,!0),size:t.getUint32(r+24,!0),headerOffset:t.getUint32(r+42,!0)}),r+=46+a+t.getUint16(r+30,!0)+t.getUint16(r+32,!0)}return i}function Mo(s,t){const e=new DataView(s.buffer,s.byteOffset,s.byteLength),n=t.headerOffset;if(n+30>s.length||e.getUint32(n,!0)!==67324752)throw new Error(`Corrupt ZIP entry: ${t.path}`);const r=n+30+e.getUint16(n+26,!0)+e.getUint16(n+28,!0);if(r+t.compressedSize>s.length)throw new Error(`Corrupt ZIP entry: ${t.path}`);return s.subarray(r,r+t.compressedSize)}async function ko(s,t,e){if(typeof DecompressionStream!="function")throw new Error("This environment cannot decompress ZIP entries");const n=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate-raw")).getReader(),r=[];let o=0;for(;;){const{done:a,value:c}=await n.read();if(a)break;if(o+=c.length,o>t)throw await n.cancel(),new RangeError(`ZIP entry too large: ${e}`);r.push(c)}const i=new Uint8Array(o);let l=0;for(const a of r)i.set(a,l),l+=a.length;return i}class Xn{constructor(t,e={}){v(this,"entries",new Map);v(this,"remaining");this.bytes=t,this.remaining=e.maxSize??Co;for(const n of Eo(t))this.entries.set(n.path,n)}has(t){return this.entries.has(t)}get paths(){return[...this.entries.keys()]}async read(t){const e=this.entries.get(t);if(!e)return;if(e.flags&Ao)throw new Error("Encrypted packages are not supported");if(e.method!==Ns&&e.method!==xo)throw new Error(`Unsupported ZIP compression: ${e.method}`);const n=Mo(this.bytes,e),r=e.method===Ns?n:await ko(n,this.remaining,t);if(r.length>this.remaining)throw new RangeError(`ZIP entry too large: ${t}`);if(he(r)!==e.crc)throw new Error(`ZIP checksum mismatch: ${t}`);return this.remaining-=r.length,r}async readText(t){const e=await this.read(t);return e&&new TextDecoder().decode(e)}}const Ro={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function Ve(s){return s.includes("&")?s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi,(t,e)=>{if(e[0]!=="#")return Ro[e]??t;const n=e[1]==="x"||e[1]==="X"?parseInt(e.slice(2),16):parseInt(e.slice(1),10);return n<=1114111?String.fromCodePoint(n):t}):s}const Xe=s=>{const t=s.indexOf(":");return t<0?s:s.slice(t+1)},xe=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;function Fo(s){const t={};xe.lastIndex=0;for(let e=xe.exec(s);e;e=xe.exec(s))e[1].startsWith("xmlns")||(t[Xe(e[1])]=Ve(e[2]??e[3]));return t}function Do(s,t){let e="";for(let n=t;n<s.length;n++){const r=s[n];if(e)r===e&&(e="");else if(r==='"'||r==="'")e=r;else if(r===">")return n}return-1}const Ae=(s,t,e)=>{const n=s.indexOf(t,e);if(n<0)throw new Error("Malformed XML");return n+t.length};function Ot(s,t){var n,r,o,i;let e=0;for(;e<s.length;){const l=s.indexOf("<",e);if(l<0){t.text&&e<s.length&&t.text(Ve(s.slice(e)));return}if(l>e&&t.text&&t.text(Ve(s.slice(e,l))),s.startsWith("<?",l))e=Ae(s,"?>",l);else if(s.startsWith("<!--",l))e=Ae(s,"-->",l);else if(s.startsWith("<![CDATA[",l))e=Ae(s,"]]>",l),(n=t.text)==null||n.call(t,s.slice(l+9,e-3));else if(s.startsWith("<!",l))e=No(s,l);else{const a=Do(s,l);if(a<0)throw new Error("Malformed XML");if(e=a+1,s[l+1]==="/"){(r=t.close)==null||r.call(t,Xe(s.slice(l+2,a).trim()));continue}const c=s[a-1]==="/",h=s.slice(l+1,c?a-1:a),u=h.search(/\s/),d=Xe(u<0?h:h.slice(0,u));(o=t.open)==null||o.call(t,d,u>=0?Fo(h.slice(u)):{},c),c&&((i=t.close)==null||i.call(t,d))}}}function No(s,t){let e=0;for(let n=t;n<s.length;n++)if(s[n]==="[")e++;else if(s[n]==="]")e--;else if(s[n]===">"&&e===0)return n+1;throw new Error("Malformed XML")}const $o={1:"0",2:"0.00",3:"#,##0",4:"#,##0.00",9:"0%",10:"0.00%",11:"0.00E+00",12:"# ?/?",13:"# ??/??",14:"mm-dd-yy",15:"d-mmm-yy",16:"d-mmm",17:"mmm-yy",18:"h:mm AM/PM",19:"h:mm:ss AM/PM",20:"h:mm",21:"h:mm:ss",22:"m/d/yy h:mm",37:"#,##0;(#,##0)",38:"#,##0;[Red](#,##0)",39:"#,##0.00;(#,##0.00)",40:"#,##0.00;[Red](#,##0.00)",45:"mm:ss",46:"[h]:mm:ss",47:"mmss.0",48:"##0.0E+0",49:"@"},Lo=["000000","FFFFFF","FF0000","00FF00","0000FF","FFFF00","FF00FF","00FFFF","000000","FFFFFF","FF0000","00FF00","0000FF","FFFF00","FF00FF","00FFFF","800000","008000","000080","808000","800080","008080","C0C0C0","808080","9999FF","993366","FFFFCC","CCFFFF","660066","FF8080","0066CC","CCCCFF","000080","FF00FF","FFFF00","00FFFF","800080","800000","008080","0000FF","00CCFF","CCFFFF","CCFFCC","FFFF99","99CCFF","FF99CC","CC99FF","FFCC99","3366FF","33CCCC","99CC00","FFCC00","FF9900","FF6600","666699","969696","003366","339966","003300","333300","993300","993366","333399","333333"],$s=["lt1","dk1","lt2","dk2","accent1","accent2","accent3","accent4","accent5","accent6","hlink","folHlink"];function To(s){const t=new Map;if(s){let e="";Ot(s,{open(n,r){$s.includes(n)?e=n:e&&n==="srgbClr"?t.set(e,r.val):e&&n==="sysClr"&&t.set(e,r.lastClr??"")},close(n){n===e&&(e="")}})}return $s.map(e=>t.get(e)??"")}function zo(s,t){const e=n=>{const r=parseInt(s.slice(n,n+2),16),o=t<0?r*(1+t):r+(255-r)*t;return Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0")};return`${e(0)}${e(2)}${e(4)}`.toUpperCase()}function Ls(s,t){let e;if(s.rgb?e=s.rgb.length===8?s.rgb.slice(2):s.rgb:s.theme!==void 0?e=t[Number(s.theme)]:s.indexed!==void 0&&(e=Lo[Number(s.indexed)]),!(!e||!/^[0-9a-f]{6}$/i.test(e)))return`#${(s.tint?zo(e,Number(s.tint)):e).toLowerCase()}`}const Ce=s=>s.val!=="0"&&s.val!=="false",Io={left:"left",center:"center",right:"right",centerContinuous:"center"};class Oo{constructor(t,e){v(this,"codes",new Map);v(this,"fonts",[]);v(this,"fills",[]);v(this,"xfs",[]);v(this,"cache",new Map);this.theme=e,t&&this.parse(t)}parse(t){let e="",n,r,o;Ot(t,{open:(i,l)=>{i==="numFmts"||i==="fonts"||i==="fills"||i==="cellXfs"||i==="dxfs"||i==="cellStyleXfs"?e=i:e==="numFmts"&&i==="numFmt"?this.codes.set(Number(l.numFmtId),l.formatCode):e==="fonts"?i==="font"?n={}:n&&i==="b"?n.bold=Ce(l):n&&i==="i"?n.italic=Ce(l):n&&i==="strike"?n.strike=Ce(l):n&&i==="u"?n.underline=l.val!=="none":n&&i==="color"&&(n.color=Ls(l,this.theme)):e==="fills"?i==="fill"?r={solid:!1}:r&&i==="patternFill"?r.solid=l.patternType==="solid":r&&i==="fgColor"&&(r.color=Ls(l,this.theme)):e==="cellXfs"&&(i==="xf"?o={numFmtId:Number(l.numFmtId??0),fontId:Number(l.fontId??0),fillId:Number(l.fillId??0)}:o&&i==="alignment"&&(o.align=Io[l.horizontal],o.wrap=l.wrapText==="1"||l.wrapText==="true"))},close:i=>{i===e?e="":i==="font"&&n?(this.fonts.push(n),n=void 0):i==="fill"&&r?(this.fills.push(r.solid?r.color:void 0),r=void 0):i==="xf"&&o&&(this.xfs.push(o),o=void 0)}})}numberFormat(t){var n;const e=((n=this.xfs[t])==null?void 0:n.numFmtId)??0;return e?this.codes.get(e)??$o[e]:void 0}isDate(t){return ce(this.numberFormat(t))}format(t){if(this.cache.has(t))return this.cache.get(t);const e=this.xfs[t];let n;if(e){const r=this.fonts[e.fontId],o=this.fonts[0],i={},l=this.numberFormat(t);l&&(i.numberFormat=l),r!=null&&r.bold&&(i.bold=!0),r!=null&&r.italic&&(i.italic=!0),r!=null&&r.underline&&(i.underline=!0),r!=null&&r.strike&&(i.strike=!0),r!=null&&r.color&&r.color!==(o==null?void 0:o.color)&&(i.color=r.color);const a=this.fills[e.fillId];a&&(i.background=a),e.align&&(i.align=e.align),e.wrap&&(i.wrap=!0),Object.keys(i).length&&(n=i)}return this.cache.set(t,n),n}}function Uo(s){var l;const t=s.split(";")[0].replace(/\[[^\]]*\]/g,"").replace(/\\(.)/g,"$1").replace(/"([^"]*)"/g,"$1");if(/AM\/PM|A\/P|mmm|ddd|[.]0|_|\*/i.test(t))return;const e=/yyyy|yy|mm|m|dd|d|hh|h|ss|s/gi;let n="",r=0,o="";const i=[...t.matchAll(e)];for(let a=0;a<i.length;a++){const c=i[a],h=c[0].toLowerCase();if(n+=t.slice(r,c.index),r=c.index+c[0].length,h[0]==="y")n+=h.length>2?"YYYY":"YY";else if(h[0]==="d")n+=h.length>1?"DD":"D";else if(h[0]==="h")n+="HH";else if(h[0]==="s")n+="ss";else{const u=(l=i[a+1])==null?void 0:l[0][0].toLowerCase();n+=o==="h"||u==="s"?"mm":h.length>1?"MM":"M"}o=h[0]}return/[^YMDHms\s\-/.:,]/.test(n+t.slice(r))?void 0:n+t.slice(r)}const Po={"₺":"TRY",TL:"TRY","€":"EUR",$:"USD","£":"GBP"};function Ho(s){var l,a;const t=s.split(";")[0],e=((l=/\.([0#]+)/.exec(t))==null?void 0:l[1])??"",n={minimumFractionDigits:e.replace(/#/g,"").length,maximumFractionDigits:e.length,useGrouping:/#,##0|0,0/.test(t)};if(!/[0#]/.test(t)||/E[+-]|\?/i.test(t))return;if(t.includes("%"))return{style:"percent",...n};const r=/"([^"]+)"|\[\$([^\]-]*)/.exec(t),o=((r==null?void 0:r[1])??(r==null?void 0:r[2])??((a=/[₺€$£]/.exec(t))==null?void 0:a[0])??"").trim(),i=Po[o]??(/^[A-Z]{3}$/.test(o)?o:void 0);return i?{style:"currency",currency:i,...n}:{style:"decimal",...n}}function _o(s){const t={};if(s.numberFormat&&s.numberFormat!=="@")if(t.formatCode=s.numberFormat,ce(s.numberFormat)){t.type="date";const u=s.numberFormat==="mm-dd-yy"?void 0:Uo(s.numberFormat);u&&(t.dateFormat=u)}else{const u=Ho(s.numberFormat);u&&(t.numericFormat=u)}const{bold:e,italic:n,underline:r,strike:o,color:i,background:l,align:a,wrap:c}=s,h=Object.fromEntries(Object.entries({bold:e,italic:n,underline:r,strike:o,color:i,background:l,align:a,wrap:c}).filter(([,u])=>u!==void 0));return Object.keys(h).length&&(t.style=h),t}const Vo=/^([A-Z]+)(\d+)$/;function Be(s){const t=Vo.exec(s.replace(/\$/g,""));return t?{row:Number(t[2])-1,col:se(t[1])}:void 0}function Se(s){const[t,e=t]=s.split(":"),n=Be(t),r=Be(e);return n&&r?{start:n,end:r}:void 0}function Kt(s){return s===""?null:s[0]==="="||s[0]==="'"||typeof at(s)!="string"?`'${s}`:s}const Xo=s=>s.replace(/_xlfn\.(_xlws\.)?|_xlws\.|_xludf\./gi,""),Ts={fromColWidth:s=>Math.round(s*7+5),fromPt:s=>Math.round(s/.75)};function Ee(s,t){if(t[0]==="/")return t.slice(1);const e=s.split("/").slice(0,-1);for(const n of t.split("/"))n===".."?e.pop():n!=="."&&e.push(n);return e.join("/")}function zs(s){const t=new Map;return s&&Ot(s,{open(e,n){e==="Relationship"&&n.TargetMode!=="External"&&t.set(n.Id,n.Target)}}),t}function Bo(s){const t=[];if(!s)return t;let e="",n=!1,r=0;return Ot(s,{open(o){o==="si"?e="":o==="rPh"?r++:o==="t"&&(n=r===0)},close(o){o==="si"?t.push(e):o==="rPh"?r--:o==="t"&&(n=!1)},text(o){n&&(e+=o)}}),t}function Wo(s,t,e,n){const r=[],o=[],i=new Map,l=new Map,a=[],c=[],h=[],u=[],d=[],m={rows:0,cols:0};let w,A=null,y=null,p=0,f=0,b=-1,C=-1;const F=(k,M,D,E)=>{for(;r.length<=k;)r.push([]),o.push([]);r[k][M]=D,o[k][M]=E,b=Math.max(b,k),C=Math.max(C,M)},R=(k,M)=>{const D=k.value;switch(k.type){case"s":{const N=n.strings[Number(D)]??"";return{raw:Kt(N),value:N||null}}case"inlineStr":return{raw:Kt(k.inline),value:k.inline||null};case"str":return{raw:Kt(D),value:D||null};case"b":return{raw:D==="1",value:D==="1"};case"e":return{raw:`'${D}`,value:Ks.includes(D)?new ct(D):D};case"d":{const N=Date.parse(D),I=Number.isNaN(N)?null:N/864e5+25569;return{raw:I,value:I}}}if(D==="")return{raw:null,value:null};const E=Number(D)+(n.date1904&&M!==void 0?1462:0);return Number.isNaN(E)?{raw:Kt(D),value:D}:{raw:E,value:E}},$=(k,M,D)=>{const E=k.formulaAttrs;if(E){if(E.t==="shared"&&E.si!==void 0){if(k.formula)return l.set(E.si,{formula:k.formula,row:M,col:D}),k.formula;const N=l.get(E.si);return N&&n.shifter.shiftFormula(`=${N.formula}`,M-N.row,D-N.col).slice(1)}if(E.t==="array"&&E.ref){const N=Se(E.ref);N&&(N.start.row!==N.end.row||N.start.col!==N.end.col)&&a.push(N)}return k.formula||void 0}},z=k=>{const M=Be(k.ref)??{row:p,col:f};if(f=M.col+1,M.row>=1048576||M.col>=16384)return;k.style&&i.set(M.row*16384+M.col,k.style);const D=k.style&&n.styles.isDate(k.style)?1:void 0,{raw:E,value:N}=R(k,D),I=n.values?void 0:$(k,M.row,M.col);I?F(M.row,M.col,`=${Xo(I)}`,N):E!==null&&F(M.row,M.col,E,N)};Ot(s,{open(k,M,D){switch(k){case"pane":(M.state==="frozen"||M.state==="frozenSplit")&&(m.rows=Number(M.ySplit??0),m.cols=Number(M.xSplit??0));break;case"col":{const E=Number(M.min)-1,N=Math.min(Number(M.max)-1,16383);for(let I=E;I<=N&&I<E+1024;I++)M.width&&M.customWidth!=="0"&&(h[I]=Ts.fromColWidth(Number(M.width))),(M.hidden==="1"||M.hidden==="true")&&u.push(I);break}case"row":p=M.r?Number(M.r)-1:p,f=0,M.ht&&M.customHeight&&M.customHeight!=="0"&&p<1048576&&(d[p]=Ts.fromPt(Number(M.ht)));break;case"c":A={ref:M.r??"",type:M.t??"n",style:Number(M.s??0),formula:"",formulaAttrs:null,value:"",inline:""},D&&(z(A),A=null);break;case"f":A&&(A.formulaAttrs=M,y=D?null:"f");break;case"v":A&&(y=D?null:"v");break;case"t":A&&(y=D?null:"t");break;case"mergeCell":{const E=M.ref?Se(M.ref):void 0;E&&c.push({row:E.start.row,col:E.start.col,rowspan:E.end.row-E.start.row+1,colspan:E.end.col-E.start.col+1});break}case"autoFilter":{const E=M.ref?Se(M.ref):void 0;E&&(w={row:E.start.row,col:E.start.col,rows:E.end.row-E.start.row+1,cols:E.end.col-E.start.col+1});break}}},close(k){k==="c"&&A?(z(A),A=null):k==="row"?p++:(k==="f"||k==="v"||k==="t")&&(y=null)},text(k){!A||!y||(y==="f"?A.formula+=k:y==="v"?A.value+=k:A.inline+=k)}});for(const k of a)for(let M=k.start.row;M<=k.end.row;M++)for(let D=k.start.col;D<=k.end.col;D++)M===k.start.row&&D===k.start.col||r[M]&&(r[M][D]=null);const P=Math.max(b+1,c.reduce((k,M)=>Math.max(k,M.row+M.rowspan),0)),H=Math.max(C+1,c.reduce((k,M)=>Math.max(k,M.col+M.colspan),0)),_=k=>Array.from({length:P},(M,D)=>Array.from({length:H},(E,N)=>{var I;return((I=k[D])==null?void 0:I[N])??null}));return{name:t,hidden:e,data:_(r),values:_(o),colWidths:h.slice(0,H),rowHeights:d.slice(0,P),frozen:m,merges:c,hiddenColumns:u.filter(k=>k<H),autoFilter:w,format:(k,M)=>{const D=i.get(k*16384+M);return D?n.styles.format(D):void 0}}}async function jo(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(await s.arrayBuffer())}async function Bn(s,t={}){const e=new Xn(await jo(s),t),r=[...zs(await e.readText("_rels/.rels")).values()].find(p=>/workbook[^/]*\.xml$/i.test(p))??"xl/workbook.xml",o=Ee("",r),i=await e.readText(o);if(!i)throw new Error("Not an .xlsx workbook");const l=Ee(o,`_rels/${o.split("/").pop()}.rels`),a=zs(await e.readText(l)),c=[],h=[];let u=!1,d=null;Ot(i,{open(p,f){p==="sheet"?c.push({name:f.name,id:f.id,hidden:f.state==="hidden"||f.state==="veryHidden"}):p==="workbookPr"?u=f.date1904==="1"||f.date1904==="true":p==="definedName"&&(d={name:f.name,text:"",local:f.localSheetId!==void 0})},text(p){d&&(d.text+=p)},close(p){p!=="definedName"||!d||(!d.local&&!d.name.startsWith("_xlnm.")&&h.push({name:d.name,expression:`=${d.text}`}),d=null)}});const m=p=>e.paths.find(f=>f.toLowerCase()===p),w=To(await e.readText(m("xl/theme/theme1.xml")??"")),A={strings:Bo(await e.readText(m("xl/sharedstrings.xml")??"")),styles:new Oo(await e.readText(m("xl/styles.xml")??""),w),date1904:u,values:t.formulas==="values",shifter:ut.buildEmpty()},y=[];for(const p of c){const f=a.get(p.id),b=f?await e.readText(Ee(o,f)):void 0;b&&y.push(Wo(b,p.name,p.hidden,A))}return A.shifter.destroy(),{sheets:y,names:h}}function Yo(s){const t=ut.buildEmpty();s.sheets.forEach((e,n)=>{n===0?t.renameSheet(0,e.name):t.addSheet(e.name)});for(const{name:e,expression:n}of s.names)t.isItPossibleToAddNamedExpression(e)&&t.addNamedExpression(e,n);return t}function Ko(s){const t=[];s.bold&&t.push("font-weight:700"),s.italic&&t.push("font-style:italic");const e=[s.underline&&"underline",s.strike&&"line-through"].filter(Boolean).join(" ");return e&&t.push(`text-decoration:${e}`),s.color&&t.push(`color:${s.color}`),s.background&&t.push(`background-color:${s.background}`),s.align&&t.push(`text-align:${s.align}`),s.wrap&&t.push("white-space:normal"),t.join(";")}function qo(s,t){const e=(r,o)=>{const i=o?Ko(o):"";return`<td${i?` style="${nt(i)}"`:""}>${nt(r)}</td>`};return`<table>${s.map((r,o)=>`<tr>${r.map((i,l)=>{var a;return e(i,(a=t[o])==null?void 0:a[l])}).join("")}</tr>`).join("")}</table>`}const Me=s=>Number(s).toString(16).padStart(2,"0"),Zo=["auto","inherit","initial","unset","currentcolor","transparent","windowtext","window","none"];function Is(s,t){const e=s==null?void 0:s.trim().toLowerCase();if(!e)return;const n=/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)(?:[\s,/]+([\d.]+))?\s*\)$/.exec(e),r=n?n[4]==="0"?void 0:`#${Me(n[1])}${Me(n[2])}${Me(n[3])}`:/^#[0-9a-f]{3,8}$/.test(e)?e:void 0;return r?t.includes(r)?void 0:r:/^[a-z]+$/.test(e)&&!Zo.includes(e)&&!t.includes(e)?e:void 0}function Wn(s){const t=new Map;for(const e of s.split(";")){const n=e.indexOf(":");n>0&&t.set(e.slice(0,n).trim().toLowerCase(),e.slice(n+1).replace(/!important/i,"").trim())}return t}function Go(s){const t=new Map;return s.querySelectorAll("style").forEach(e=>{const n=(e.textContent??"").replace(/<!--|-->|\/\*[\s\S]*?\*\//g," ");for(const r of n.matchAll(/([^{}]+)\{([^{}]*)\}/g))for(const o of r[1].split(","))t.set(o.trim().toLowerCase(),Wn(r[2]))}),t}function Qo(s){const t={},e=s.get("font-weight");(e==="bold"||Number(e)>=600)&&(t.bold=!0),s.get("font-style")==="italic"&&(t.italic=!0);const n=s.get("text-decoration")??s.get("text-decoration-line")??"";n.includes("underline")&&(t.underline=!0),n.includes("line-through")&&(t.strike=!0);const r=Is(s.get("color"),["#000","#000000","black"]);r&&(t.color=r);const o=Is(s.get("background-color")??s.get("background"),["#fff","#ffffff","white"]);o&&(t.background=o);const i=s.get("text-align");(i==="left"||i==="center"||i==="right")&&(t.align=i);const l=s.get("white-space");return(l==="normal"||l==="pre-wrap")&&(t.wrap=!0),Object.keys(t).length?t:void 0}function Jo(s,t){const e=new t.DOMParser().parseFromString(s,"text/html"),n=e.querySelector("table");if(!n)return null;const r=Go(e),o=[],i=[];return n.querySelectorAll("tr").forEach((l,a)=>{var h,u;o[a]??(o[a]=[]),i[a]??(i[a]=[]);let c=0;for(const d of Array.from(l.children)){for(;o[a][c]!==void 0;)c++;const m=new Map([...r.get(d.tagName.toLowerCase())??[],...[...d.classList].flatMap(p=>[...r.get(`.${p.toLowerCase()}`)??[]]),...Wn(d.getAttribute("style")??"")]),w=Qo(m),A=Math.max(1,d.rowSpan||1),y=Math.max(1,d.colSpan||1);for(let p=0;p<A;p++)for(let f=0;f<y;f++)(o[h=a+p]??(o[h]=[]))[c+f]=p===0&&f===0?(d.textContent??"").trim():"",(i[u=a+p]??(i[u]=[]))[c+f]=w;c+=y}}),o.length?{texts:o,styles:i}:null}function ti(s,t,e,n,r){var y;const o=s.createElement("div");o.className="ct-menu ct-context",o.setAttribute("role","menu");const i=[];let l=!0;for(const p of t){if(p==="---"){l||o.append(Object.assign(s.createElement("div"),{className:"ct-menu-sep"})),l=!0;continue}l=!1;const f=s.createElement("button");f.type="button",f.className="ct-menu-item",f.setAttribute("role","menuitem"),f.dataset.key=p.key,f.disabled=!!p.disabled;const b=s.createElement("span");if(b.textContent=p.name,f.append(b),p.hint){const C=s.createElement("span");C.className="ct-menu-hint",C.textContent=p.hint,f.append(C)}f.addEventListener("click",()=>{A(),p.run()}),i.push(f),o.append(f)}s.body.append(o);const a=s.defaultView,c=o.offsetWidth||220,h=o.offsetHeight||300;o.style.left=`${Math.max(4,Math.min(e,((a==null?void 0:a.innerWidth)??1024)-c-4))}px`,o.style.top=`${Math.max(4,Math.min(n,((a==null?void 0:a.innerHeight)??768)-h-4))}px`;const u=()=>i.filter(p=>!p.disabled);(y=u()[0])==null||y.focus();const d=p=>{var C;const f=u(),b=f.indexOf(s.activeElement);if(p.key==="ArrowDown"||p.key==="ArrowUp"){p.preventDefault();const F=p.key==="ArrowDown"?(b+1)%f.length:(b-1+f.length)%f.length;(C=f[F])==null||C.focus()}else(p.key==="Escape"||p.key==="Tab")&&(p.preventDefault(),A());p.stopPropagation()},m=p=>{o.contains(p.target)||A()};o.addEventListener("keydown",d),s.addEventListener("mousedown",m,!0),a==null||a.addEventListener("blur",A);let w=!1;function A(){w||(w=!0,s.removeEventListener("mousedown",m,!0),a==null||a.removeEventListener("blur",A),o.remove(),r())}return A}function Os(s,t,e,n){if(e.values&&!e.values.includes(t))return!1;const r=e.condition;if(!r)return!0;const o=s===null||t==="";switch(r.op){case"isEmpty":return o;case"isNotEmpty":return!o}const i=(r.value??"").toLocaleLowerCase(n),l=t.toLocaleLowerCase(n);switch(r.op){case"contains":return l.includes(i);case"notContains":return!l.includes(i)}const a=Ct((r.value??"").replace(",",".")),c=typeof s=="number"&&a!==void 0?Math.sign(s-a):V(l,i);switch(r.op){case"equals":return c===0;case"notEquals":return c!==0;case"greaterThan":return!o&&c>0;case"greaterOrEqual":return!o&&c>=0;case"lessThan":return!o&&c<0;default:return!o&&c<=0}}const Us=new Map;function ei(s){let t=Us.get(s);return t||Us.set(s,t=new Intl.Collator(s,{sensitivity:"base",numeric:!0})),t}const Ps=s=>typeof s=="number"?0:typeof s=="string"?1:typeof s=="boolean"?2:s instanceof ct?3:4;function si(s,t,e,n){const r=s===null||s==="",o=t===null||t==="";if(r||o)return r===o?0:r?1:-1;const i=Ps(s),l=Ps(t);let a;return i!==l?a=i-l:i===3?a=0:i===1?a=ei(n).compare(s,t):a=V(s,t),e==="asc"?a:-a}const ke=s=>({start:{row:s.row,col:s.col},end:{row:s.row+s.rowspan-1,col:s.col+s.colspan-1}}),Hs=(s,t)=>s.start.row<=t.end.row&&s.end.row>=t.start.row&&s.start.col<=t.end.col&&s.end.col>=t.start.col;class ni{constructor(){v(this,"areas",[]);v(this,"index",new Map)}get list(){return this.areas}set(t){this.areas=[];for(const e of t)this.add(e);this.reindex()}add(t){if(t.rowspan<1||t.colspan<1||t.rowspan===1&&t.colspan===1)return!1;const e=ke(t);return this.areas=this.areas.filter(n=>!Hs(ke(n),e)),this.areas.push({...t}),this.reindex(),!0}removeAt(t,e){const n=this.get(t,e);return n?(this.areas=this.areas.filter(r=>r!==n),this.reindex(),!0):!1}get(t,e){return this.index.get(t*1048576+e)}expand(t){const e={start:{...t.start},end:{...t.end}};let n=this.areas.length>0;for(;n;){n=!1;for(const r of this.areas){const o=ke(r);Hs(o,e)&&(o.start.row<e.start.row&&(e.start.row=o.start.row,n=!0),o.start.col<e.start.col&&(e.start.col=o.start.col,n=!0),o.end.row>e.end.row&&(e.end.row=o.end.row,n=!0),o.end.col>e.end.col&&(e.end.col=o.end.col,n=!0))}}return e}shift(t,e,n){const r=t==="row"?"rowspan":"colspan",o=[];for(const i of this.areas){const l={...i},a=l[t],c=a+l[r]-1;if(n>0)a>=e?l[t]+=n:c>=e&&(l[r]+=n);else{const h=-n,u=Math.max(a,e),d=Math.min(c,e+h-1),m=Math.max(0,d-u+1);a>=e+h?l[t]-=h:a>=e&&(l[t]=e),l[r]-=m}l[r]>0&&(l.rowspan>1||l.colspan>1)&&o.push(l)}this.areas=o,this.reindex()}reindex(){this.index.clear();for(const t of this.areas)for(let e=t.row;e<t.row+t.rowspan;e++)for(let n=t.col;n<t.col+t.colspan;n++)this.index.set(e*1048576+n,t)}}const We={sortAsc:"Sort A → Z",sortDesc:"Sort Z → A",sortClear:"Clear sort",sortThenAsc:"Then sort A → Z",sortThenDesc:"Then sort Z → A",filterByCondition:"Filter by condition",filterByValue:"Filter by value",search:"Search",selectAll:"(Select all)",blanks:"(Blanks)",ok:"OK",cancel:"Cancel",clearFilter:"Clear filter",none:"None",contains:"Contains",notContains:"Does not contain",equals:"Is equal to",notEquals:"Is not equal to",greaterThan:"Greater than",greaterOrEqual:"Greater than or equal to",lessThan:"Less than",lessOrEqual:"Less than or equal to",isEmpty:"Is empty",isNotEmpty:"Is not empty",columnMenu:"Column menu",cut:"Cut",copy:"Copy",paste:"Paste",insertRowAbove:"Insert row above",insertRowBelow:"Insert row below",removeRow:"Delete row",removeRows:"Delete rows",insertColLeft:"Insert column left",insertColRight:"Insert column right",removeCol:"Delete column",removeCols:"Delete columns",mergeCells:"Merge cells",unmergeCells:"Unmerge cells",clearContents:"Clear contents",undo:"Undo",redo:"Redo",hideColumn:"Hide column",hideColumns:"Hide columns",showColumns:"Show hidden columns",cellAnnouncement:"{cell}: {value}",find:"Find",replace:"Replace",replaceAll:"Replace all",replaceWith:"Replace with",matchCase:"Match case",wholeCell:"Whole cell",lookInFormulas:"In formulas",noMatches:"No matches",matchCount:"{total} matches",replacedCount:"{count} replaced",next:"Next",previous:"Previous",close:"Close",formulaBar:"Cell content"},ri={sortAsc:"A → Z sırala",sortDesc:"Z → A sırala",sortClear:"Sıralamayı kaldır",sortThenAsc:"Sonra A → Z sırala",sortThenDesc:"Sonra Z → A sırala",filterByCondition:"Koşula göre filtrele",filterByValue:"Değere göre filtrele",search:"Ara",selectAll:"(Tümünü seç)",blanks:"(Boş)",ok:"Tamam",cancel:"İptal",clearFilter:"Filtreyi temizle",none:"Yok",contains:"İçerir",notContains:"İçermez",equals:"Eşittir",notEquals:"Eşit değildir",greaterThan:"Büyüktür",greaterOrEqual:"Büyük veya eşittir",lessThan:"Küçüktür",lessOrEqual:"Küçük veya eşittir",isEmpty:"Boş",isNotEmpty:"Boş değil",columnMenu:"Sütun menüsü",cut:"Kes",copy:"Kopyala",paste:"Yapıştır",insertRowAbove:"Üste satır ekle",insertRowBelow:"Alta satır ekle",removeRow:"Satırı sil",removeRows:"Satırları sil",insertColLeft:"Sola sütun ekle",insertColRight:"Sağa sütun ekle",removeCol:"Sütunu sil",removeCols:"Sütunları sil",mergeCells:"Hücreleri birleştir",unmergeCells:"Birleştirmeyi kaldır",clearContents:"İçeriği temizle",undo:"Geri al",redo:"Yinele",hideColumn:"Sütunu gizle",hideColumns:"Sütunları gizle",showColumns:"Gizli sütunları göster",cellAnnouncement:"{cell}: {value}",find:"Bul",replace:"Değiştir",replaceAll:"Tümünü değiştir",replaceWith:"Yeni değer",matchCase:"Büyük/küçük harf",wholeCell:"Hücrenin tamamı",lookInFormulas:"Formüllerde",noMatches:"Sonuç yok",matchCount:"{total} sonuç",replacedCount:"{count} değiştirildi",next:"Sonraki",previous:"Önceki",close:"Kapat",formulaBar:"Hücre içeriği"};class _s{constructor(t,e=0){v(this,"order");v(this,"hidden",new Set);v(this,"visible",[]);v(this,"inverse",new Int32Array(0));v(this,"sorted",!1);v(this,"identity",!0);this.pinned=e,this.order=Array.from({length:t},(n,r)=>r),this.rebuild()}get count(){return this.visible.length}get physicalCount(){return this.order.length}get pinnedCount(){return Math.min(this.pinned,this.order.length)}get isIdentity(){return this.identity}get isSorted(){return this.sorted}toPhysical(t){return this.visible[t]??t-this.visible.length+this.order.length}toVisual(t){return t<this.inverse.length?this.inverse[t]:-1}setPinned(t){this.pinned=t,this.rebuild()}sort(t){const e=this.order.filter(r=>r<this.pinned).sort((r,o)=>r-o),n=this.order.filter(r=>r>=this.pinned);n.sort(t??((r,o)=>r-o)),this.order=[...e,...n],this.rebuild()}setHidden(t){this.hidden=new Set([...t].filter(e=>e>=this.pinned)),this.rebuild()}insert(t,e,n=this.count){const r=a=>a>=t?a+e:a,o=this.visible[n];this.order=this.order.map(r),this.hidden=new Set([...this.hidden].map(r));const i=Array.from({length:e},(a,c)=>t+c),l=o===void 0?this.order.length:this.order.indexOf(r(o));this.order.splice(l,0,...i),this.rebuild()}remove(t,e){const n=o=>o>=t+e?o-e:o,r=o=>o>=t&&o<t+e;this.order=this.order.filter(o=>!r(o)).map(n),this.hidden=new Set([...this.hidden].filter(o=>!r(o)).map(n)),this.rebuild()}snapshot(){return{order:[...this.order],hidden:[...this.hidden]}}restore(t){this.order=[...t.order],this.hidden=new Set(t.hidden),this.rebuild()}reset(t){this.order=Array.from({length:t},(e,n)=>n),this.hidden.clear(),this.rebuild()}rebuild(){const t=this.order.filter(e=>e<this.pinned).sort((e,n)=>e-n);this.order=[...t,...this.order.filter(e=>e>=this.pinned)],this.visible=this.order.filter(e=>!this.hidden.has(e)),this.inverse=new Int32Array(this.order.length).fill(-1),this.visible.forEach((e,n)=>this.inverse[e]=n),this.sorted=!this.order.every((e,n)=>e===n),this.identity=!this.sorted&&this.hidden.size===0}}function oi(s,t){const e=s.toLocaleLowerCase(t);if(e.length===s.length)return{text:e,map:null};let n="";const r=[];for(let o=0;o<s.length;o++){const i=s[o].toLocaleLowerCase(t);n+=i;for(let l=0;l<i.length;l++)r.push(o)}return r.push(s.length),{text:n,map:r}}function Vs(s,t,e={},n){if(!t)return[];const r=e.matchCase?{text:s,map:null}:oi(s,n),o=e.matchCase?t:t.toLocaleLowerCase(n);if(e.wholeCell)return r.text===o?[[0,s.length]]:[];const i=[];for(let l=r.text.indexOf(o);l>=0;l=r.text.indexOf(o,l+o.length)){const a=l+o.length;i.push(r.map?[r.map[l],r.map[a]]:[l,a])}return i}function ii(s,t,e){let n="",r=0;for(const[o,i]of t)n+=s.slice(r,o)+e,r=i;return n+s.slice(r)}const li=150;function ai(s){const t=s.root.ownerDocument,e=s.messages,n=t.createElement("div");n.className="ct-menu ct-search",n.setAttribute("role","dialog"),n.setAttribute("aria-label",e.find);const r=(E,N)=>{const I=t.createElement("input");return I.type="text",I.value=N,I.placeholder=E,I.setAttribute("aria-label",E),I},o=(E,N,I)=>{const W=t.createElement("button");return W.type="button",W.className="ct-btn",W.textContent=E,W.title=N,W.setAttribute("aria-label",N),W.addEventListener("click",()=>{I(),k||a.focus()}),W},i=(...E)=>{const N=t.createElement("div");return N.className="ct-search-row",N.append(...E),N},l=(E,N)=>{const I=t.createElement("label"),W=t.createElement("input");return W.type="checkbox",W.checked=N,W.addEventListener("change",()=>F()),I.append(W,t.createTextNode(E)),[I,W]},a=r(e.find,s.query),c=r(e.replaceWith,""),h=t.createElement("span");h.className="ct-search-status",h.setAttribute("aria-live","polite");const[u,d]=l(e.matchCase,!!s.options.matchCase),[m,w]=l(e.wholeCell,!!s.options.wholeCell),[A,y]=l(e.lookInFormulas,s.options.lookIn==="formulas"),p=E=>h.textContent=a.value?E?e.matchCount.replace("{total}",String(E)):e.noMatches:"",f=({index:E,total:N})=>{N?h.textContent=`${E} / ${N}`:p(0)},b=()=>({matchCase:d.checked,wholeCell:w.checked,lookIn:y.checked?"formulas":"values"});let C=0;function F(){clearTimeout(C),C=0,p(s.onSearch(a.value,b()))}a.addEventListener("input",()=>{clearTimeout(C),C=setTimeout(F,li)});const R=()=>{C&&F()},$=E=>{R(),a.value&&f(s.onNext(E))},z=()=>{R(),f(s.onReplace(c.value))},P=i(c,o(e.replace,e.replace,()=>z()),o(e.replaceAll,e.replaceAll,()=>{R();const E=s.onReplaceAll(c.value);h.textContent=e.replacedCount.replace("{count}",String(E))}));P.hidden=!0,n.append(i(a,h,o("↑",e.previous,()=>$(!0)),o("↓",e.next,()=>$(!1)),o("×",e.close,()=>M())),P,i(u,m,A)),n.addEventListener("keydown",E=>{E.key==="Escape"?(E.stopPropagation(),M()):E.key==="Enter"&&E.target===a?(E.preventDefault(),$(E.shiftKey)):E.key==="Enter"&&E.target===c&&(E.preventDefault(),z())}),t.body.append(n);const H=s.root.getBoundingClientRect(),_=n.offsetWidth||340;n.style.left=`${Math.max(8,H.right-_-20)}px`,n.style.top=`${H.top+30}px`,a.value&&F();let k=!1;function M(){k||(k=!0,clearTimeout(C),n.remove(),s.onClose())}const D=E=>{E&&s.replace&&(P.hidden=!1),a.focus(),a.select()};return D(s.replace),{close:M,focus:D}}const ci=`
5
+ --ct-bg: #fff;
6
+ --ct-fg: #1f2328;
7
+ --ct-muted: #57606a;
8
+ --ct-grid: #e1e4e8;
9
+ --ct-header-bg: #f6f8fa;
10
+ --ct-header-fg: #57606a;
11
+ --ct-header-hl: #dde7f8;
12
+ --ct-accent: #1a73e8;
13
+ --ct-range: rgba(26, 115, 232, 0.1);
14
+ --ct-error: #cf222e;
15
+ --ct-invalid-bg: #ffebe9;
16
+ --ct-readonly-fg: #6e7781;
17
+ --ct-shadow: rgba(31, 35, 40, .15);
18
+ --ct-match: #fff3b0;`,Xs=`
19
+ --ct-bg: #0d1117;
20
+ --ct-fg: #e6edf3;
21
+ --ct-muted: #8b949e;
22
+ --ct-grid: #30363d;
23
+ --ct-header-bg: #161b22;
24
+ --ct-header-fg: #8b949e;
25
+ --ct-header-hl: #1f3a5f;
26
+ --ct-accent: #4c8dff;
27
+ --ct-range: rgba(76, 141, 255, 0.16);
28
+ --ct-error: #ff7b72;
29
+ --ct-invalid-bg: #3d1d1f;
30
+ --ct-readonly-fg: #7d8590;
31
+ --ct-shadow: rgba(0, 0, 0, .5);
32
+ --ct-match: #5a4a00;`,hi=`
33
+ .ct-root, .ct-menu, .ct-bar {${ci}
34
+ }
35
+ @media (prefers-color-scheme: dark) {
36
+ .ct-root:not(.ct-light), .ct-menu, .ct-bar:not(.ct-light) {${Xs}
37
+ }
38
+ }
39
+ .ct-root.ct-dark, .ct-bar.ct-dark {${Xs}
40
+ }
41
+ .ct-root {
42
+ position: relative;
43
+ overflow: auto;
44
+ outline: none;
45
+ background: var(--ct-bg);
46
+ color: var(--ct-fg);
47
+ font: 13px/1.2 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
48
+ border: 1px solid var(--ct-grid);
49
+ box-sizing: border-box;
50
+ user-select: none;
51
+ }
52
+ .ct-canvas { position: relative; }
53
+ .ct-band { display: flex; }
54
+ .ct-band-top { position: sticky; top: 0; z-index: 3; }
55
+ .ct-pane { position: relative; flex: none; }
56
+ .ct-pane-corner, .ct-pane-left { position: sticky; left: 0; background: var(--ct-bg); }
57
+ .ct-pane-corner { z-index: 4; }
58
+ .ct-pane-left { z-index: 2; }
59
+ .ct-pane-top { background: var(--ct-bg); }
60
+ .ct-edge-r { box-shadow: 2px 0 3px -1px var(--ct-shadow); }
61
+ .ct-edge-b { box-shadow: 0 2px 3px -1px var(--ct-shadow); }
62
+ .ct-pane-corner.ct-edge-r.ct-edge-b { box-shadow: 2px 2px 3px -1px var(--ct-shadow); }
63
+
64
+ .ct-cell, .ct-header {
65
+ position: absolute; box-sizing: border-box; padding: 0 6px; overflow: hidden;
66
+ white-space: nowrap; text-overflow: ellipsis; display: flex; align-items: center;
67
+ border-right: 1px solid var(--ct-grid); border-bottom: 1px solid var(--ct-grid);
68
+ }
69
+ .ct-cell { background: var(--ct-bg); }
70
+ .ct-cell.ct-num, .ct-cell.ct-date { justify-content: flex-end; font-variant-numeric: tabular-nums; }
71
+ .ct-cell.ct-bool, .ct-cell.ct-check { justify-content: center; }
72
+ .ct-cell.ct-err { color: var(--ct-error); justify-content: center; }
73
+ .ct-cell.ct-readonly { color: var(--ct-readonly-fg); }
74
+ .ct-cell.ct-invalid { background: var(--ct-invalid-bg); box-shadow: inset 0 0 0 1px var(--ct-error); }
75
+ .ct-cell.ct-dd { padding-right: 18px; }
76
+ .ct-cell.ct-dd::after { content: "▾"; position: absolute; right: 5px; color: var(--ct-muted); font-size: 11px; }
77
+ .ct-cell.ct-b { font-weight: 700; }
78
+ .ct-cell.ct-i { font-style: italic; }
79
+ .ct-cell.ct-u { text-decoration: underline; }
80
+ .ct-cell.ct-s { text-decoration: line-through; }
81
+ .ct-cell.ct-u.ct-s { text-decoration: underline line-through; }
82
+ .ct-cell.ct-wrap { white-space: normal; overflow-wrap: anywhere; line-height: 1.25; }
83
+ .ct-cell.ct-al-l { justify-content: flex-start; }
84
+ .ct-cell.ct-al-c { justify-content: center; }
85
+ .ct-cell.ct-al-r { justify-content: flex-end; }
86
+ .ct-cell.ct-match { background: var(--ct-match); }
87
+ .ct-checkbox { font-size: 15px; cursor: pointer; line-height: 1; }
88
+
89
+ .ct-header { background: var(--ct-header-bg); color: var(--ct-header-fg); justify-content: center; font-size: 12px; cursor: default; }
90
+ .ct-header.ct-hl { background: var(--ct-header-hl); color: var(--ct-fg); font-weight: 600; }
91
+ .ct-colhead { gap: 3px; padding: 0 4px; }
92
+ .ct-label { overflow: hidden; text-overflow: ellipsis; }
93
+ .ct-sort { font-size: 9px; color: var(--ct-accent); }
94
+ .ct-sort:empty { display: none; }
95
+ .ct-menu-btn {
96
+ margin-left: auto; border: 0; background: transparent; color: var(--ct-muted); cursor: pointer;
97
+ font: inherit; font-size: 11px; padding: 1px 3px; border-radius: 3px; opacity: 0; flex: none;
98
+ }
99
+ .ct-colhead:hover .ct-menu-btn, .ct-filtered .ct-menu-btn { opacity: 1; }
100
+ .ct-menu-btn:hover { background: var(--ct-grid); }
101
+ .ct-filtered .ct-menu-btn { color: var(--ct-bg); background: var(--ct-accent); }
102
+ .ct-cornerhead { cursor: pointer; }
103
+ .ct-colhead.ct-gap-r { box-shadow: inset -3px 0 0 -1px var(--ct-accent); }
104
+ .ct-colhead.ct-gap-l { box-shadow: inset 3px 0 0 -1px var(--ct-accent); }
105
+ .ct-rresize { position: absolute; left: 0; bottom: 0; width: 100%; height: 5px; cursor: row-resize; z-index: 1; }
106
+ .ct-rresize:hover { background: var(--ct-accent); opacity: .5; }
107
+ .ct-drop { position: absolute; width: 3px; background: var(--ct-accent); z-index: 6; pointer-events: none; }
108
+ .ct-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
109
+ .ct-resize { position: absolute; top: 0; right: 0; width: 6px; height: 100%; cursor: col-resize; z-index: 1; }
110
+ .ct-resize:hover { background: var(--ct-accent); opacity: .5; }
111
+
112
+ .ct-range { position: absolute; pointer-events: none; background: var(--ct-range); border: 1px solid var(--ct-accent); box-sizing: border-box; z-index: 1; }
113
+ .ct-active { position: absolute; pointer-events: none; border: 2px solid var(--ct-accent); box-sizing: border-box; z-index: 1; }
114
+ .ct-fill-area { position: absolute; pointer-events: none; border: 1px dashed var(--ct-accent); box-sizing: border-box; z-index: 1; }
115
+ .ct-fill {
116
+ position: absolute; z-index: 2; background: var(--ct-accent); border: 1px solid var(--ct-bg);
117
+ box-sizing: border-box; cursor: crosshair;
118
+ }
119
+ /* Larger hit area than the visible square. Resize handles sit inside their header because headers clip overflow. */
120
+ .ct-fill::before { content: ""; position: absolute; inset: -4px; }
121
+
122
+ .ct-editor {
123
+ position: absolute; z-index: 5; box-sizing: border-box; margin: 0; padding: 3px 5px; resize: none; overflow: hidden;
124
+ border: 2px solid var(--ct-accent); outline: none; font: inherit; color: var(--ct-fg); background: var(--ct-bg);
125
+ white-space: pre; box-shadow: 0 2px 8px var(--ct-shadow);
126
+ }
127
+ .ct-editor.ct-idle { opacity: 0; pointer-events: none; box-shadow: none; z-index: 0; caret-color: transparent; }
128
+ .ct-dd-list {
129
+ position: absolute; z-index: 6; max-height: 220px; overflow: auto; background: var(--ct-bg);
130
+ border: 1px solid var(--ct-grid); box-shadow: 0 4px 12px var(--ct-shadow); padding: 2px 0;
131
+ }
132
+ .ct-dd-item { padding: 4px 8px; cursor: pointer; white-space: nowrap; }
133
+ .ct-dd-item:hover { background: var(--ct-range); }
134
+ .ct-dd-item.ct-on { background: var(--ct-accent); color: #fff; }
135
+
136
+ .ct-menu {
137
+ position: fixed; z-index: 1000; width: 240px; box-sizing: border-box; padding: 6px 0;
138
+ background: var(--ct-bg); color: var(--ct-fg); border: 1px solid var(--ct-grid); border-radius: 6px;
139
+ box-shadow: 0 8px 24px var(--ct-shadow); font: 13px/1.3 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
140
+ }
141
+ .ct-menu-section { padding: 4px 10px; border-bottom: 1px solid var(--ct-grid); display: flex; flex-direction: column; gap: 4px; }
142
+ .ct-menu-title { font-size: 11px; font-weight: 600; color: var(--ct-muted); text-transform: uppercase; letter-spacing: .03em; padding-top: 2px; }
143
+ .ct-menu-item { text-align: left; border: 0; background: transparent; color: inherit; font: inherit; padding: 4px 6px; border-radius: 4px; cursor: pointer; }
144
+ .ct-menu-item:hover { background: var(--ct-range); }
145
+ .ct-menu-item.ct-on { color: var(--ct-accent); font-weight: 600; }
146
+ .ct-menu select, .ct-menu input[type=text], .ct-menu input[type=search] {
147
+ font: inherit; padding: 4px 6px; border: 1px solid var(--ct-grid); border-radius: 4px; background: var(--ct-bg); color: inherit;
148
+ }
149
+ .ct-menu-list { max-height: 180px; overflow: auto; display: flex; flex-direction: column; }
150
+ .ct-menu-list label { display: flex; gap: 6px; align-items: center; padding: 2px 0; white-space: nowrap; cursor: pointer; }
151
+ .ct-menu-list label[hidden] { display: none; }
152
+ .ct-menu-footer { display: flex; gap: 6px; padding: 8px 10px 2px; align-items: center; }
153
+ .ct-menu-link { margin-right: auto; border: 0; background: transparent; color: var(--ct-accent); font: inherit; cursor: pointer; padding: 0; }
154
+ .ct-context { width: auto; min-width: 200px; padding: 4px; }
155
+ .ct-context .ct-menu-item { display: flex; justify-content: space-between; gap: 24px; width: 100%; padding: 5px 8px; }
156
+ .ct-context .ct-menu-item:focus { outline: none; background: var(--ct-range); }
157
+ .ct-context .ct-menu-item:disabled { opacity: .45; cursor: default; background: transparent; }
158
+ .ct-menu-hint { color: var(--ct-muted); font-size: 12px; }
159
+ .ct-menu-sep { height: 1px; background: var(--ct-grid); margin: 4px 2px; }
160
+ .ct-search { width: 360px; padding: 8px; display: flex; flex-direction: column; gap: 6px; }
161
+ .ct-search-row { display: flex; gap: 4px; align-items: center; }
162
+ .ct-search-row[hidden] { display: none; }
163
+ .ct-search-row input[type=text] { flex: 1; min-width: 0; }
164
+ .ct-search-row label { display: flex; gap: 4px; align-items: center; margin-right: 8px; font-size: 12px; white-space: nowrap; cursor: pointer; }
165
+ .ct-search-row .ct-btn { padding: 4px 8px; white-space: nowrap; }
166
+ .ct-search-status { font-size: 12px; color: var(--ct-muted); white-space: nowrap; }
167
+ .ct-bar {
168
+ display: flex; align-items: flex-start; box-sizing: border-box; background: var(--ct-bg); color: var(--ct-fg);
169
+ border: 1px solid var(--ct-grid); border-bottom: 0; font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
170
+ }
171
+ .ct-bar-address { flex: none; width: 72px; padding: 4px 6px; box-sizing: border-box; text-align: center; color: var(--ct-muted); border-right: 1px solid var(--ct-grid); }
172
+ .ct-bar-input {
173
+ flex: 1; min-width: 0; box-sizing: border-box; margin: 0; padding: 4px 6px; border: 0; outline: none; resize: none; overflow: auto;
174
+ font: inherit; font-family: ui-monospace, Consolas, monospace; color: inherit; background: transparent; white-space: pre-wrap;
175
+ }
176
+ .ct-btn { font: inherit; padding: 4px 10px; border-radius: 4px; border: 1px solid var(--ct-grid); background: var(--ct-bg); color: inherit; cursor: pointer; }
177
+ .ct-btn.ct-primary { background: var(--ct-accent); border-color: var(--ct-accent); color: #fff; }
178
+ `;function ui(s){if(s.getElementById("ct-styles"))return;const t=s.createElement("style");t.id="ct-styles",t.textContent=hi,s.head.appendChild(t)}function di(s){return s.map(t=>t.map(e=>/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e).join(" ")).join(`
179
+ `)}function fi(s){const t=[];let e=[],n="",r=0;const o=s.replace(/\r\n?/g,`
180
+ `).replace(/\n$/,"");for(;r<o.length;){const i=o[r];if(i==='"'&&n===""){const l=pi(o,r+1);if(l!==-1&&(l+1===o.length||o[l+1]===" "||o[l+1]===`
181
+ `)){n=o.slice(r+1,l).replace(/""/g,'"'),r=l+1;continue}}i===" "?(e.push(n),n=""):i===`
182
+ `?(e.push(n),t.push(e),e=[],n=""):n+=i,r++}return e.push(n),t.push(e),t}function pi(s,t){for(let e=t;e<s.length;e++)if(s[e]==='"'){if(s[e+1]==='"'){e++;continue}return e}return-1}const mi=26,gi=50,qt=4,wi=5e4;class yi{constructor(t,e={}){v(this,"root");v(this,"data",[]);v(this,"binding");v(this,"bindingPaused",!1);v(this,"rows");v(this,"cols");v(this,"mapper");v(this,"merges",new ni);v(this,"engine");v(this,"ownsEngine",!1);v(this,"sheet",0);v(this,"opts");v(this,"messages");v(this,"headerH");v(this,"rowHeaderW");v(this,"frozenRows");v(this,"frozenCols");v(this,"columnMeta",[]);v(this,"cellMeta",new Map);v(this,"labels");v(this,"filters",new Map);v(this,"sortKeys",[]);v(this,"invalid",new Map);v(this,"rowHeights",new Map);v(this,"rowsCustomized",!1);v(this,"hiddenCols",new Map);v(this,"announcer");v(this,"announceTimer",0);v(this,"canvas");v(this,"topBand");v(this,"bodyBand");v(this,"panes");v(this,"cornerHead");v(this,"input");v(this,"editing",!1);v(this,"editorEnterMode",!1);v(this,"dropdown");v(this,"closeMenu");v(this,"anchor",null);v(this,"selEnd",null);v(this,"dragging",null);v(this,"moveDrop",null);v(this,"fillTarget",null);v(this,"hooks",new Map);v(this,"undoStack",[]);v(this,"redoStack",[]);v(this,"clipboard",null);v(this,"searchPanel");v(this,"searchQuery","");v(this,"searchOptions",{});v(this,"searchHits",new Set);v(this,"bar");v(this,"frame",0);v(this,"cleanup",[]);v(this,"onValuesUpdated",t=>{for(const{address:e}of t)(e.sheet??0)!==this.sheet||e.row>=this.data.length||(ge(this.metaAt(e.row,e.col))&&this.revalidate(e.row,e.col),this.bindingPaused||this.writeComputed(e.row,e.col,!0));this.scheduleRender()});v(this,"onInput",()=>{if(!this.editing){this.openEditor(this.input.value);return}this.autoSizeInput(),this.dropdown&&this.filterDropdown(this.input.value),this.bar&&!this.barFocused()&&(this.bar.input.value=this.input.value)});v(this,"onEditorKey",t=>{if(!this.editing)return;t.stopPropagation();const e=this.dropdown,n=(r,o)=>{t.preventDefault(),this.commitAndMove(r,o)};if(e&&e.items.length&&(t.key==="ArrowDown"||t.key==="ArrowUp")){t.preventDefault(),e.active=Math.max(0,Math.min(e.items.length-1,e.active+(t.key==="ArrowDown"?1:-1))),this.highlightDropdown();return}switch(t.key){case"Enter":if(t.altKey){t.preventDefault(),this.input.setRangeText(`
183
+ `,this.input.selectionStart,this.input.selectionEnd,"end");return}return e&&e.active>=0&&(this.input.value=e.items[e.active]),n(t.shiftKey?-1:1,0);case"Tab":return n(0,t.shiftKey?-1:1);case"Escape":t.preventDefault(),this.closeEditor(!1);return;case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":if(this.editorEnterMode){const[r,o]=Re[t.key];return n(r,o)}}});v(this,"dropLine");var c;this.opts=e,this.messages={...We,...e.language},this.headerH=e.colHeaders===!1?0:mi,this.rowHeaderW=e.rowHeaders===!1?0:gi,this.labels=Array.isArray(e.colHeaders)?[...e.colHeaders]:void 0,this.columnMeta=[...e.columns??[]];const n=t.ownerDocument;ui(n),this.root=n.createElement("div"),this.root.className="ct-root",this.root.setAttribute("role","grid"),this.root.setAttribute("aria-multiselectable","true"),e.theme==="light"&&this.root.classList.add("ct-light"),e.theme==="dark"&&this.root.classList.add("ct-dark"),this.root.style.height=typeof e.height=="number"?`${e.height}px`:e.height??"400px",this.buildDom(),t.appendChild(this.root),e.formulaBar&&this.buildFormulaBar();const r=e.formulas instanceof ut?e.formulas:void 0,o=r&&e.sheetName!==void 0?r.getSheetId(e.sheetName):r?0:void 0,i=e.data??(r&&o!==void 0?r.getSheetSerialized(o):[]);this.data=this.normalize(this.bind(i)),this.frozenRows=Math.min(e.fixedRowsTop??0,this.data.length),this.frozenCols=Math.min(e.fixedColumnsStart??0,this.countCols()),this.mapper=new _s(this.data.length,this.frozenRows),this.rows=new Ft(this.data.length,e.rowHeight??24);const l=typeof e.colWidths=="number"?e.colWidths:100,a=Array.isArray(e.colWidths)?e.colWidths:this.columnMeta.some(h=>h==null?void 0:h.width)?Array.from({length:this.countCols()},(h,u)=>{var d;return((d=this.columnMeta[u])==null?void 0:d.width)??l}):e.colWidths;this.cols=new Ft(this.countCols(),100,a),e.mergeCells&&this.merges.set(e.mergeCells.filter(h=>this.mergeAllowed(h)));for(const h of e.hiddenColumns??[])this.hiddenCols.set(h,this.cols.size(h));for(const h of this.hiddenCols.keys())this.cols.setSize(h,0);r?(this.engine=r,this.sheet=o??r.addSheet(e.sheetName),(e.data||o===void 0)&&r.setSheetContent(this.data,this.sheet)):e.formulas!==!1&&(this.engine=ut.buildFromArray(this.data,e.sheetName),this.ownsEngine=!0),(c=this.engine)==null||c.on("valuesUpdated",this.onValuesUpdated),this.syncBoundObjects(),this.validateAll(),this.bindEvents(),this.render()}countRows(){return this.mapper.count}countSourceRows(){return this.data.length}countCols(){var t;return((t=this.data[0])==null?void 0:t.length)??0}getEngine(){return this.engine}getSheetId(){return this.sheet}getSheetName(){var t;return(t=this.engine)==null?void 0:t.getSheetName(this.sheet)}toPhysicalRow(t){return this.mapper.toPhysical(t)}toVisualRow(t){return this.mapper.toVisual(t)}getDataAtCell(t,e){return this.valueAt(this.mapper.toPhysical(t),e)}getSourceDataAtCell(t,e){return this.rawAt(this.mapper.toPhysical(t),e)}getData(){return Array.from({length:this.countRows()},(t,e)=>Array.from({length:this.countCols()},(n,r)=>this.getDataAtCell(e,r)))}getSourceData(){return this.data.map((t,e)=>t.map((n,r)=>this.rawAt(e,r)))}getBoundRows(){return this.data.map((t,e)=>t.map((n,r)=>this.boundValueAt(e,r)))}getSourceObjects(){var t;return(t=this.binding)==null?void 0:t.objects}getSourceDataAtRow(t){const e=this.mapper.toPhysical(t);return this.binding?this.binding.objects[e]:this.getSourceData()[e]}propToCol(t){var e;return((e=this.binding)==null?void 0:e.fields.indexOf(t))??-1}colToProp(t){var e;return(e=this.binding)==null?void 0:e.fields[t]}setDataAtCell(t,e,n,r){const o=typeof t=="number"?[[t,e,n]]:t,i=(typeof t=="number"?r:e)??"api";this.applyChanges(o.map(([l,a,c])=>this.change(this.mapper.toPhysical(l),a,c)),i)}loadData(t){var e;this.data=this.normalize(this.bind(t)),this.frozenRows=Math.min(this.frozenRows,this.data.length),this.mapper=new _s(this.data.length,this.frozenRows),this.syncRows(),this.cols.resize(this.countCols()),this.filters.clear(),this.sortKeys=[],this.cellMeta.clear(),this.rowHeights.clear(),this.bindingPaused=!0,(e=this.engine)==null||e.setSheetContent(this.data,this.sheet),this.bindingPaused=!1,this.syncBoundObjects(),this.undoStack=[],this.redoStack=[],this.anchor=this.selEnd=null,this.validateAll(),this.render()}loadSheet(t){var r,o,i,l,a;this.merges.set([]),this.hiddenCols.clear(),this.loadData(t.data),this.frozenRows=Math.min(((r=t.frozen)==null?void 0:r.rows)??0,this.data.length),this.frozenCols=Math.min(((o=t.frozen)==null?void 0:o.cols)??0,this.countCols()),this.mapper.setPinned(this.frozenRows);const e=this.countCols();this.cols=new Ft(e,this.cols.defaultSize,Array.from({length:e},(c,h)=>{var u;return((u=t.colWidths)==null?void 0:u[h])??this.cols.defaultSize}));for(const c of t.hiddenColumns)this.hiddenCols.set(c,this.cols.size(c)),this.cols.setSize(c,0);(i=t.rowHeights)==null||i.forEach((c,h)=>{h<this.data.length&&this.rowHeights.set(h,c)}),this.rowsCustomized=this.rowHeights.size>0,this.syncRows();const n=new Map;for(let c=0;c<this.data.length;c++)for(let h=0;h<e;h++){const u=t.format(c,h);if(!u)continue;let d=n.get(u);if(d||n.set(u,d=_o(u)),d.type==="date"&&typeof((a=(l=t.values)==null?void 0:l[c])==null?void 0:a[h])=="string"){const{type:m,dateFormat:w,...A}=d;d=A}this.cellMeta.set(O(c,h),d)}this.merges.set((t.merges??[]).filter(c=>this.mergeAllowed(c))),this.validateAll(),this.render()}async importXLSX(t,e={}){var i;const n=await Bn(t,e),{sheet:r=0}=e,o=typeof r=="number"?n.sheets[r]:n.sheets.find(l=>l.name===r);if(!o)throw new Error(`Sheet not found: ${r}`);for(const{name:l,expression:a}of n.names)(i=this.engine)!=null&&i.isItPossibleToAddNamedExpression(l)&&this.engine.addNamedExpression(l,a);return this.loadSheet(o),o}getCellMeta(t,e){return this.metaAt(this.mapper.toPhysical(t),e)}setCellMeta(t,e,n){const r=this.mapper.toPhysical(t),o=O(r,e);this.cellMeta.set(o,{...this.cellMeta.get(o),...n}),this.revalidate(r,e),this.render()}updateSettings(t){this.opts={...this.opts,...t},t.language&&(this.messages={...We,...t.language}),t.columns&&(this.columnMeta=[...t.columns]),t.colHeaders!==void 0&&(this.labels=Array.isArray(t.colHeaders)?[...t.colHeaders]:void 0),(t.columnSorting!==void 0||t.filters!==void 0)&&this.resetHeaders(),(t.fixedRowsTop!==void 0||t.fixedColumnsStart!==void 0)&&(this.frozenRows=Math.min(t.fixedRowsTop??this.frozenRows,this.data.length),this.frozenCols=Math.min(t.fixedColumnsStart??this.frozenCols,this.countCols()),this.mapper.setPinned(this.frozenRows),this.syncRows(),this.merges.set(this.merges.list.filter(e=>this.mergeAllowed(e)))),t.mergeCells&&this.merges.set(t.mergeCells.filter(e=>this.mergeAllowed(e))),t.columns&&this.validateAll(),this.render()}selectCell(t,e,n=t,r=e){const o=h=>Math.max(0,Math.min(h,this.countRows()-1)),i=h=>Math.max(0,Math.min(h,this.countCols()-1));let l={row:o(t),col:i(e)},a={row:o(n),col:i(r)};const c=this.mergeAt(l.row,l.col);c&&t===n&&e===r&&(l={row:c.row,col:c.col},a={...l}),this.anchor=l,this.selEnd=a,this.scrollIntoView(this.selEnd),this.render(),this.announce(),this.run("afterSelection",l.row,l.col,a.row,a.col)}announce(){if(!this.anchor)return;const{row:t,col:e}=this.anchor,n=this.mapper.toPhysical(t),r=this.messages.cellAnnouncement.replace("{cell}",Ne({row:n,col:e})).replace("{value}",this.displayText(n,e)||"—");this.input.setAttribute("aria-label",r),clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>this.announcer.textContent=r,120)}getSelected(){if(!(!this.anchor||!this.selEnd))return[[this.anchor.row,this.anchor.col,this.selEnd.row,this.selEnd.col]]}getSelectedRange(){if(!this.anchor||!this.selEnd)return;const t=js(this.anchor,this.selEnd);return this.mergesActive()?this.merges.expand(t):t}focus(){!this.anchor&&this.countRows()&&this.countCols()&&this.selectCell(0,0),this.focusInput()}deselectCell(){this.anchor=this.selEnd=null,this.render()}setCellStyle(t,e){const n=[];for(let r=t.start.row;r<=t.end.row;r++){const o=this.mapper.toPhysical(r);for(let i=t.start.col;i<=t.end.col;i++){const l=O(o,i),a=this.cellMeta.get(l),c={...a};e?c.style={...a==null?void 0:a.style,...e}:delete c.style,n.push({key:l,before:a,after:Object.keys(c).length?c:void 0})}}this.applyMeta(n,"after"),this.undoStack.push({kind:"meta",changes:n}),this.redoStack=[],this.render(),this.run("afterStyle",t,e)}getCellStyle(t,e){const n=this.mapper.toPhysical(t);return{...this.metaAt(n,e).style,...this.conditionalStyle(n,e,this.valueAt(n,e))}}toggleCellStyle(t){const e=this.getSelectedRange();if(!e||this.opts.readOnly)return;let n=!0;for(let r=e.start.row;r<=e.end.row&&n;r++)for(let o=e.start.col;o<=e.end.col&&n;o++)n=!!this.getCellStyle(r,o)[t];this.setCellStyle(e,{[t]:!n})}setRowHeight(t,e){const n=Math.max(12,Math.round(e));this.rowHeights.set(this.mapper.toPhysical(t),n),this.rowsCustomized=!0,this.rows.setSize(t,n),this.render()}getRowHeight(t){return this.rows.size(t)}hideColumns(t){for(const e of t)e<0||e>=this.countCols()||this.hiddenCols.has(e)||(this.hiddenCols.set(e,this.cols.size(e)),this.cols.setSize(e,0));this.anchor&&this.hiddenCols.has(this.anchor.col)&&this.moveActive(0,0,!1),this.render()}showColumns(t){for(const e of t??[...this.hiddenCols.keys()]){const n=this.hiddenCols.get(e);n!==void 0&&(this.hiddenCols.delete(e),this.cols.setSize(e,n||this.cols.defaultSize))}this.render()}isColumnHidden(t){return this.hiddenCols.has(t)}getHiddenColumns(){return[...this.hiddenCols.keys()].sort((t,e)=>t-e)}toExportSheet(){const t=this.getSourceData(),e=t.map((l,a)=>l.map((c,h)=>this.valueAt(a,h))),n=this.opts.locale,r=(l,a)=>{var m,w,A;const c=this.metaAt(l,a),h={...c.style,...this.conditionalStyle(l,a,((m=e[l])==null?void 0:m[a])??null)},u={},d=Fn(c,n);return d&&(u.numberFormat=d),h.bold&&(u.bold=!0),h.italic&&(u.italic=!0),h.underline&&(u.underline=!0),h.strike&&(u.strike=!0),(w=h.color)!=null&&w.startsWith("#")&&(u.color=h.color),(A=h.background)!=null&&A.startsWith("#")&&(u.background=h.background),h.align&&(u.align=h.align),h.wrap&&(u.wrap=!0),Object.keys(u).length?u:void 0},o=this.rowHeights.size?Array.from({length:t.length},(l,a)=>this.rowHeights.get(a)??this.rows.defaultSize):void 0,i={name:this.getSheetName()??"Sheet1",data:t,values:e,colWidths:Array.from({length:this.countCols()},(l,a)=>this.cols.size(a)),rowHeights:o,frozen:{rows:this.frozenRows,cols:this.frozenCols},merges:this.mapper.isIdentity?this.getMergedCells():[],format:r,text:(l,a)=>{var c;return this.displayText(l,a,((c=e[l])==null?void 0:c[a])??null)}};return this.opts.filters&&this.frozenRows>0&&(i.autoFilter={row:this.frozenRows-1,col:0,rows:t.length-this.frozenRows+1,cols:this.countCols()}),i}exportCSV(t={}){const e=bi(this.opts.locale);return Nn(this.toExportSheet(),{delimiter:e?";":",",decimalSeparator:e?",":".",locale:this.opts.locale,...t})}downloadCSV(t="data.csv",e={}){Pe(this.exportCSV(e),t,$n)}async downloadXLSX(t="data.xlsx",e=[]){const n=await Vn([this,...e].map(r=>r.toExportSheet()));Pe(n,t,Un)}sort(t,e){this.applySort(e?[{col:t,order:e}]:[]),this.run("afterColumnSort",t,e)}sortBy(t){this.applySort(t)}applySort(t){if(t.length){const e=t.map(({col:n,order:r})=>({order:r,values:Array.from({length:this.data.length},(o,i)=>this.valueAt(i,n))}));this.mapper.sort((n,r)=>{for(const{values:o,order:i}of e){const l=si(o[n],o[r],i,this.opts.locale);if(l)return l}return 0})}else this.mapper.sort(null);this.sortKeys=t.map(e=>({...e})),this.afterRowMapping(),this.run("afterSort",this.getSortKeys())}getSortState(){return this.sortKeys[0]?{...this.sortKeys[0]}:null}getSortKeys(){return this.sortKeys.map(t=>({...t}))}setFilter(t,e){e?this.filters.set(t,e):this.filters.delete(t),this.applyFilters()}clearFilters(){this.filters.clear(),this.applyFilters()}getFilters(){return new Map(this.filters)}applyFilters(){const t=[];if(this.filters.size){const e=[...this.filters];for(let n=this.mapper.pinnedCount;n<this.data.length;n++)this.passes(n,e)||t.push(n)}this.mapper.setHidden(t),this.afterRowMapping(),this.run("afterFilter",this.getFilters())}findCells(t,e={}){const n=[];if(!t)return n;for(let r=0;r<this.countRows();r++){const o=this.mapper.toPhysical(r);for(let i=0;i<this.countCols();i++){if(this.hiddenCols.has(i)||this.metaAt(o,i).type==="checkbox")continue;const l=this.mergeAt(r,i);l&&(l.row!==r||l.col!==i)||Vs(this.searchText(o,i,e),t,e,this.opts.locale).length&&n.push({row:r,col:i})}}return n}findNext(t,e={},n=!1){const r=this.findCells(t,e),o=r[this.nextHit(r,n)];return o&&this.selectCell(o.row,o.col),o??null}replaceNext(t,e,n={}){return this.anchor&&this.replaceIn([this.anchor],t,e,n),this.findNext(t,n)}replaceAll(t,e,n={}){return this.replaceIn(this.findCells(t,n),t,e,n)}openSearch(t=!1){if(this.searchPanel)return this.searchPanel.focus(t);const e=t&&!this.opts.readOnly;this.searchPanel=ai({root:this.root,messages:this.messages,query:this.searchQuery,options:this.searchOptions,replace:e,onSearch:(n,r)=>(this.searchQuery=n,this.searchOptions=r,this.highlightHits().length),onNext:n=>this.stepSearch(n),onReplace:n=>(this.anchor&&this.replaceIn([this.anchor],this.searchQuery,n,this.searchOptions),this.stepSearch(!1)),onReplaceAll:n=>{const r=this.replaceAll(this.searchQuery,n,this.searchOptions);return this.highlightHits(),r},onClose:()=>{this.searchPanel=void 0,this.searchHits.clear(),this.render(),this.focusInput()}})}closeSearch(){var t;(t=this.searchPanel)==null||t.close()}searchText(t,e,n){return n.lookIn==="formulas"?jt(this.rawAt(t,e),this.metaAt(t,e),this.opts.locale):this.displayText(t,e)}nextHit(t,e){const n=this.anchor??{row:-1,col:-1},r=i=>i.row>n.row||i.row===n.row&&i.col>n.col,o=i=>i.row<n.row||i.row===n.row&&i.col<n.col;if(!e)return Math.max(0,t.findIndex(r));for(let i=t.length-1;i>=0;i--)if(o(t[i]))return i;return t.length-1}highlightHits(){const t=this.findCells(this.searchQuery,this.searchOptions);return this.searchHits=new Set(t.map(e=>O(this.mapper.toPhysical(e.row),e.col))),this.render(),t}stepSearch(t){const e=this.highlightHits(),n=this.nextHit(e,t);return e[n]&&this.selectCell(e[n].row,e[n].col),{index:n+1,total:e.length}}replaceIn(t,e,n,r){const o=[];for(const{row:i,col:l}of t){const a=this.mapper.toPhysical(i),c=this.rawAt(a,l);if(X(c)&&r.lookIn!=="formulas"||this.isReadOnly(a,l))continue;const h=this.metaAt(a,l),u=jt(c,h,this.opts.locale),d=Vs(u,e,r,this.opts.locale);d.length&&o.push(this.change(a,l,me(ii(u,d,n),h)))}return this.applyChanges(o,"replace"),o.length}mergeCells(t,e,n,r){const o={row:t,col:e,rowspan:n,colspan:r};return!this.mergeAllowed(o)||!this.merges.add(o)?!1:(this.render(),!0)}unmergeCells(t,e){const n=this.merges.removeAt(t,e);return n&&this.render(),n}getMergedCells(){return this.merges.list.map(t=>({...t}))}alter(t,e,n=1){const r=this.getSelectedRange(),o=t.includes("row"),i=t.startsWith("remove"),l=t==="insert_row_below"||t==="insert_col_end",a=o?this.countRows():this.countCols();let c;if(e!==void 0?c=l?e+1:e:o?c=l?((r==null?void 0:r.end.row)??a-1)+1:(r==null?void 0:r.start.row)??0:c=l?((r==null?void 0:r.end.col)??a-1)+1:(r==null?void 0:r.start.col)??0,c=Math.max(0,Math.min(c,a)),i&&(n=Math.min(n,a-c)),n<=0)return;const h=this.snapshot(),u=[];o?this.alterRows(c,n,i,u):this.alterCols(c,n,i,u),this.undoStack.push({kind:"structure",state:h,ops:u}),this.redoStack=[],this.validateAll(),this.clampSelection(),this.render(),this.run("afterAlter",t,c,n)}moveColumns(t,e,n){if(!this.canMoveColumns(t,e,n))return!1;const r=this.countCols(),o=this.snapshot(),i=[],l=h=>Bs(h,t,e,n),a=h=>{const u=new Array(h.length);return h.forEach((d,m)=>u[l(m)]=d),u};this.data=this.data.map(h=>a(h)),this.binding&&(this.binding.fields=a(this.binding.fields.length<r?[...this.binding.fields,...Array(r-this.binding.fields.length)]:this.binding.fields));const c=a(Array.from({length:r},(h,u)=>this.cols.size(u)));return this.cols=new Ft(r,this.cols.defaultSize,c),this.columnMeta.length&&(this.columnMeta=a([...this.columnMeta,...Array(Math.max(0,r-this.columnMeta.length))])),this.labels&&(this.labels=a([...this.labels,...Array(Math.max(0,r-this.labels.length)).fill("")])),this.filters=new Map([...this.filters].map(([h,u])=>[l(h),u])),this.sortKeys=this.sortKeys.map(h=>({...h,col:l(h.col)})),this.hiddenCols=Dt(this.hiddenCols,l),this.cellMeta=Dt(this.cellMeta,h=>h-h%16384+l(h%16384)),this.merges.set(this.merges.list.map(h=>({...h,col:l(h.col)}))),this.applyEngineOp(Pt(i,{axis:"col",index:t,count:e,remove:!1,target:n})),this.undoStack.push({kind:"structure",state:o,ops:i}),this.redoStack=[],this.anchor&&this.selEnd&&(this.anchor={...this.anchor,col:l(this.anchor.col)},this.selEnd={...this.selEnd,col:l(this.selEnd.col)}),this.validateAll(),this.render(),this.run("afterColumnMove",t,e,n),!0}canMoveColumns(t,e,n){const r=this.countCols();if(e<=0||t<0||t+e>r||n<0||n>r||n>=t&&n<=t+e)return!1;const o=i=>Bs(i,t,e,n);return this.merges.list.every(i=>{for(let l=1;l<i.colspan;l++)if(o(i.col+l)!==o(i.col)+l)return!1;return!0})}undo(){this.replay(this.undoStack,this.redoStack,"undo")}redo(){this.replay(this.redoStack,this.undoStack,"redo")}isUndoAvailable(){return this.undoStack.length>0}isRedoAvailable(){return this.redoStack.length>0}setColWidth(t,e){this.cols.setSize(t,Math.max(24,e)),this.render()}getColWidth(t){return this.cols.size(t)}addHook(t,e){let n=this.hooks.get(t);n||this.hooks.set(t,n=new Set),n.add(e)}removeHook(t,e){var n;(n=this.hooks.get(t))==null||n.delete(e)}getCellError(t,e){return this.invalid.get(O(this.mapper.toPhysical(t),e))}openContextMenu(t,e){var i;const n=this.getSelectedRange();if(!n||!this.opts.contextMenu)return;if((i=this.closeMenu)==null||i.call(this),t===void 0||e===void 0){const l=this.input.getBoundingClientRect();t=l.left+l.width/2,e=l.bottom}const r=this.contextMenuEntries(n),o=typeof this.opts.contextMenu=="function"?this.opts.contextMenu(r,this):r;this.closeMenu=ti(this.root.ownerDocument,o,t,e,()=>{this.closeMenu=void 0,this.focusInput()})}contextMenuEntries(t){var h;const e=this.messages,n=!!this.opts.readOnly,r=t.end.row-t.start.row+1,o=t.end.col-t.start.col+1,i=this.mergeAt(t.start.row,t.start.col),l=!!i&&r===i.rowspan&&o===i.colspan,a=(h=this.root.ownerDocument.defaultView)==null?void 0:h.navigator.clipboard,c=this.mergeAllowed({row:t.start.row,col:t.start.col,rowspan:r,colspan:o});return[{key:"cut",name:e.cut,hint:"Ctrl+X",disabled:n,run:()=>this.writeClipboard(this.copy(!0))},{key:"copy",name:e.copy,hint:"Ctrl+C",run:()=>this.writeClipboard(this.copy())},{key:"paste",name:e.paste,hint:"Ctrl+V",disabled:n||!(a!=null&&a.readText)&&!this.clipboard,run:()=>{const u=()=>this.clipboard&&this.paste(this.clipboard.text);a!=null&&a.readText?a.readText().then(d=>d?this.paste(d):u(),u):u()}},"---",{key:"row_above",name:e.insertRowAbove,disabled:n,run:()=>this.alter("insert_row_above",t.start.row,r)},{key:"row_below",name:e.insertRowBelow,disabled:n,run:()=>this.alter("insert_row_below",t.end.row,r)},{key:"remove_row",name:r>1?e.removeRows:e.removeRow,disabled:n,run:()=>this.alter("remove_row",t.start.row,r)},"---",{key:"col_left",name:e.insertColLeft,disabled:n,run:()=>this.alter("insert_col_start",t.start.col,o)},{key:"col_right",name:e.insertColRight,disabled:n,run:()=>this.alter("insert_col_end",t.end.col,o)},{key:"remove_col",name:o>1?e.removeCols:e.removeCol,disabled:n,run:()=>this.alter("remove_col",t.start.col,o)},{key:"hide_col",name:o>1?e.hideColumns:e.hideColumn,disabled:o>=this.countCols()-this.hiddenCols.size,run:()=>this.hideColumns(Array.from({length:o},(u,d)=>t.start.col+d))},...this.hiddenCols.size?[{key:"show_cols",name:e.showColumns,run:()=>this.showColumns()}]:[],"---",l?{key:"unmerge",name:e.unmergeCells,disabled:n,run:()=>this.unmergeCells(t.start.row,t.start.col)}:{key:"merge",name:e.mergeCells,disabled:n||r===1&&o===1||!c,run:()=>this.mergeCells(t.start.row,t.start.col,r,o)},{key:"clear",name:e.clearContents,hint:"Del",disabled:n,run:()=>this.clearRange(t,"clear")},"---",{key:"undo",name:e.undo,hint:"Ctrl+Z",disabled:!this.isUndoAvailable(),run:()=>this.undo()},{key:"redo",name:e.redo,hint:"Ctrl+Y",disabled:!this.isRedoAvailable(),run:()=>this.redo()}]}writeClipboard(t){var i;if(t===void 0)return;const e=this.root.ownerDocument.defaultView,n=e==null?void 0:e.navigator.clipboard,r=(i=this.clipboard)==null?void 0:i.html,o=()=>n==null?void 0:n.writeText(t).catch(()=>{});if(r&&(n!=null&&n.write)&&e&&"ClipboardItem"in e){const l=(a,c)=>new Blob([c],{type:a});n.write([new e.ClipboardItem({"text/plain":l("text/plain",t),"text/html":l("text/html",r)})]).catch(o)}else o()}copy(t=!1){var d;const e=this.getSelectedRange();if(!e)return;const n=[],r=[],o=[],i=[],l=[];let a=!1;for(let m=e.start.row;m<=e.end.row;m++){const w=this.mapper.toPhysical(m);o.push(w);const A=[],y=[],p=[],f=[];for(let b=e.start.col;b<=e.end.col;b++){A.push(this.rawAt(w,b)),y.push(this.displayText(w,b)),p.push((d=this.cellMeta.get(O(w,b)))==null?void 0:d.style);const C=this.metaAt(w,b).style;f.push(C),a||(a=!!C)}n.push(A),r.push(y),i.push(p),l.push(f)}const c=di(r),h=r.length*r[0].length,u=a&&h<=wi?qo(r,l):void 0;return this.clipboard={text:c,raws:n,rows:o,col:e.start.col,styles:i,html:u},t&&this.clearRange(e,"cut"),c}paste(t,e){var y;const n=this.getSelectedRange();if(!n||this.opts.readOnly)return;const r=this.clipboard&&this.clipboard.text===t?this.clipboard:null,o=this.root.ownerDocument.defaultView,i=!r&&e&&o?Jo(e,o):null,l=r?r.raws:t?fi(t):(i==null?void 0:i.texts)??[];if(!l.length)return;const a=i&&i.texts.length===l.length&&i.texts.every((p,f)=>p.length===l[f].length),c=(r==null?void 0:r.styles)??(a?i.styles:void 0),h=l.length===1&&l[0].length===1,u=h?n.end.row-n.start.row+1:l.length,d=h?n.end.col-n.start.col+1:Zt(l,p=>p.length);this.ensureVisualRows(n.start.row+u);const m=[],w=[];for(let p=0;p<u;p++){const f=this.mapper.toPhysical(n.start.row+p);for(let b=0;b<d;b++){const C=n.start.col+b,F=h?0:p,R=h?0:b;let $=l[F][R]??null;if(r?X($)&&this.engine&&($=this.engine.shiftFormula($,f-r.rows[F],C-(r.col+R))):$=me(String($??""),this.metaAt(f,C)),m.push(this.change(f,C,$)),c&&!this.isReadOnly(f,C)){const z=O(f,C),P=this.cellMeta.get(z),H={...P},_=(y=c[F])==null?void 0:y[R];_?H.style=_:delete H.style,(_||P!=null&&P.style)&&w.push({key:z,before:P,after:Object.keys(H).length?H:void 0})}}}const A=this.undoStack.length;if(this.applyChanges(m,"paste"),w.length&&this.undoStack.length>A){this.applyMeta(w,"after");const p=this.undoStack.splice(A);this.undoStack.push({kind:"group",entries:[...p,{kind:"meta",changes:w}]})}this.selectCell(n.start.row,n.start.col,n.start.row+u-1,n.start.col+d-1)}autofill(t,e){const n=e.start.row>t.end.row?"down":e.end.row<t.start.row?"up":e.start.col>t.end.col?"right":"left",r=n==="down"||n==="up",o=r?e.end.row-e.start.row+1:e.end.col-e.start.col+1;n==="down"&&this.ensureVisualRows(e.end.row+1),n==="right"&&this.ensureSize(this.data.length,e.end.col+1);const i=[],[l,a]=r?[t.start.col,t.end.col]:[t.start.row,t.end.row];for(let h=l;h<=a;h++){let u=[];for(let y=r?t.start.row:t.start.col;y<=(r?t.end.row:t.end.col);y++)u.push(y);(n==="up"||n==="left")&&(u=u.reverse());const d=Array.from({length:o},(y,p)=>n==="down"?t.end.row+1+p:n==="up"?t.start.row-1-p:n==="right"?t.end.col+1+p:t.start.col-1-p),m=y=>r?{p:this.mapper.toPhysical(y),c:h}:{p:this.mapper.toPhysical(h),c:y},w=[...u,...d],A=Or(u.map(y=>{const{p,c:f}=m(y);return this.rawAt(p,f)}),o,(y,p,f)=>{if(!this.engine)return y;const b=m(w[p]),C=m(w[f]);return this.engine.shiftFormula(y,C.p-b.p,C.c-b.c)});d.forEach((y,p)=>{const{p:f,c:b}=m(y);i.push(this.change(f,b,A[p]))})}this.applyChanges(i,"autofill");const c=Ws(t,e);this.selectCell(c.start.row,c.start.col,c.end.row,c.end.col),this.run("afterAutofill",t,e)}render(){xi(this.frame),this.frame=0,this.layout();const t=this.viewport(),{corner:e,top:n,left:r,main:o}=this.panes,i=[0,this.frozenRows-1],l=[0,this.frozenCols-1];this.renderPane(e,i,l),this.renderPane(n,i,[t.c0,t.c1]),this.renderPane(r,[t.r0,t.r1],l),this.renderPane(o,[t.r0,t.r1],[t.c0,t.c1]),this.editing||this.placeInput(),this.syncFormulaBar()}destroy(){var t,e,n,r,o;(t=this.closeMenu)==null||t.call(this),(e=this.searchPanel)==null||e.close(),(n=this.bar)==null||n.el.remove(),clearTimeout(this.announceTimer),this.cleanup.forEach(i=>i()),(r=this.engine)==null||r.off("valuesUpdated",this.onValuesUpdated),this.ownsEngine&&((o=this.engine)==null||o.destroy()),this.root.remove()}valueAt(t,e){var n;return this.engine?this.engine.getCellValue({row:t,col:e,sheet:this.sheet}):at((n=this.data[t])==null?void 0:n[e])}rawAt(t,e){var n;return this.engine?t<this.data.length?this.engine.getCellSerialized({row:t,col:e,sheet:this.sheet}):null:((n=this.data[t])==null?void 0:n[e])??null}metaAt(t,e){var l,a;const n=this.columnMeta[e],r=(a=(l=this.opts).cells)==null?void 0:a.call(l,t,e),o=this.cellMeta.size?this.cellMeta.get(O(t,e)):void 0;if(!r&&!o)return n??{};const i={...n,...r,...o};return(n!=null&&n.style||r!=null&&r.style||o!=null&&o.style)&&(i.style={...n==null?void 0:n.style,...r==null?void 0:r.style,...o==null?void 0:o.style}),i}displayText(t,e,n=this.valueAt(t,e)){return Ss(n,this.metaAt(t,e),this.opts.locale).text}passes(t,e){for(const[n,r]of e){const o=this.valueAt(t,n);if(!Os(o,this.displayText(t,n,o),r,this.opts.locale))return!1}return!0}change(t,e,n){var o;const r=(o=this.binding)==null?void 0:o.fields[e];return{row:this.mapper.toVisual(t),physicalRow:t,col:e,...r?{prop:r}:{},oldValue:this.rawAt(t,e),newValue:n}}isReadOnly(t,e){return!!this.opts.readOnly||!!this.metaAt(t,e).readOnly}applyChanges(t,e,n=!0){var l,a;const r=e!=="api"&&e!=="undo"&&e!=="redo";if(r&&(t=t.filter(c=>!this.isReadOnly(c.physicalRow,c.col))),!t.length||this.run("beforeChange",t,e)===!1||r&&(t=t.filter(c=>{const h=this.metaAt(c.physicalRow,c.col);return h.allowInvalid!==!1||X(c.newValue)?!0:!Es(at(c.newValue),c.newValue,h,c.physicalRow,c.col)}),!t.length))return;const o=Zt(t,c=>c.physicalRow),i=Zt(t,c=>c.col);this.ensureSize(o+1,i+1);for(const c of t)this.data[c.physicalRow][c.col]=c.newValue??null,this.computedBinding()&&X(c.newValue)||(l=this.binding)==null||l.write(c.physicalRow,c.col,c.newValue??null);(a=this.engine)==null||a.batch(()=>{for(const c of t)this.engine.setCellContents({row:c.physicalRow,col:c.col,sheet:this.sheet},c.newValue??null)});for(const c of t)this.revalidate(c.physicalRow,c.col);n&&(this.undoStack.push({kind:"cells",changes:t}),this.redoStack=[]),this.render(),this.run("afterChange",t,e)}clearRange(t,e){const n=[];for(let r=t.start.row;r<=t.end.row;r++){const o=this.mapper.toPhysical(r);for(let i=t.start.col;i<=t.end.col;i++)Fe(this.rawAt(o,i))||n.push(this.change(o,i,null))}this.applyChanges(n,e)}replay(t,e,n){const r=t.pop();r&&(this.replayEntry(r,n),e.push(r))}replayEntry(t,e){if(t.kind==="group")(e==="undo"?[...t.entries].reverse():t.entries).forEach(n=>this.replayEntry(n,e));else if(t.kind==="meta")this.applyMeta(t.changes,e==="undo"?"before":"after"),this.render();else if(t.kind==="cells"){const n=t.changes.map(r=>e==="undo"?{...r,oldValue:r.newValue,newValue:r.oldValue}:{...r});this.applyChanges(n,e,!1)}else{const n=this.snapshot();this.bindingPaused=!0,e==="undo"?[...t.ops].reverse().forEach(r=>this.undoEngineOp(r)):t.ops.forEach(r=>this.applyEngineOp(r)),this.bindingPaused=!1,this.restore(t.state),this.syncBoundObjects(),t.state=n}}applyMeta(t,e){for(const n of t){const r=n[e];r?this.cellMeta.set(n.key,r):this.cellMeta.delete(n.key)}}applyEngineOp(t){const e=this.engine;e&&(t.target!==void 0?e.moveColumns(t.index,t.count,t.target,this.sheet):t.remove?(t.record=e.captureRemoval(t.axis,t.index,t.count,this.sheet),t.axis==="row"?e.removeRows(t.index,t.count,this.sheet):e.removeColumns(t.index,t.count,this.sheet)):t.axis==="row"?e.addRows(t.index,t.count,this.sheet):e.addColumns(t.index,t.count,this.sheet))}undoEngineOp(t){const e=this.engine;if(e)if(t.target!==void 0){const n=e.inverseMove(t.index,t.count,t.target);e.moveColumns(n.start,n.count,n.target,this.sheet)}else t.remove?e.restoreRemoval(t.record):t.axis==="row"?e.removeRows(t.index,t.count,this.sheet):e.removeColumns(t.index,t.count,this.sheet)}snapshot(){var t;return{data:this.data.map(e=>[...e]),binding:(t=this.binding)==null?void 0:t.snapshot(),colSizes:Array.from({length:this.cols.count},(e,n)=>this.cols.size(n)),rows:this.mapper.snapshot(),merges:this.getMergedCells(),columns:[...this.columnMeta],labels:this.labels&&[...this.labels],filters:[...this.filters].map(([e,n])=>[e,{...n}]),sort:this.getSortKeys(),cellMeta:[...this.cellMeta],rowHeights:[...this.rowHeights],hidden:[...this.hiddenCols]}}restore(t){var e;this.data=t.data.map(n=>[...n]),t.binding&&((e=this.binding)==null||e.restore(t.binding)),this.mapper.restore(t.rows),this.syncRows(),this.cols=new Ft(t.colSizes.length,this.cols.defaultSize,t.colSizes),this.merges.set(t.merges),this.columnMeta=[...t.columns],this.labels=t.labels&&[...t.labels],this.filters=new Map(t.filters),this.sortKeys=t.sort.map(n=>({...n})),this.cellMeta=new Map(t.cellMeta),this.rowHeights=new Map(t.rowHeights),this.hiddenCols=new Map(t.hidden),this.syncRows(),this.frozenCols=Math.min(this.frozenCols,this.countCols()),this.validateAll(),this.clampSelection(),this.render()}alterRows(t,e,n,r){var o,i;if(n){const l=Array.from({length:e},(a,c)=>this.mapper.toPhysical(t+c)).sort((a,c)=>c-a);for(const a of l)this.data.splice(a,1),(o=this.binding)==null||o.removeRows(a,1),this.mapper.remove(a,1),this.shiftRowState(a,-1),this.applyEngineOp(Pt(r,{axis:"row",index:a,count:1,remove:!0}));this.merges.shift("row",t,-e)}else{const l=t<this.countRows()?this.mapper.toPhysical(t):this.data.length;this.data.splice(l,0,...Array.from({length:e},()=>Array(this.countCols()).fill(null))),(i=this.binding)==null||i.insertRows(l,e),this.mapper.insert(l,e,t),this.shiftRowState(l,e),this.applyEngineOp(Pt(r,{axis:"row",index:l,count:e,remove:!1})),this.merges.shift("row",t,e)}this.syncRows()}shiftRowState(t,e){this.cellMeta=Dt(this.cellMeta,n=>{const r=Gt(Math.floor(n/16384),t,e);return r<0?-1:r*16384+n%16384}),this.rowHeights=Dt(this.rowHeights,n=>Gt(n,t,e))}alterCols(t,e,n,r){var l,a,c,h;for(const u of this.data)n?u.splice(t,e):u.splice(t,0,...Array(e).fill(null));n?(l=this.binding)==null||l.removeCols(t,e):(a=this.binding)==null||a.insertCols(t,e),n?(this.cols.remove(t,e),this.applyEngineOp(Pt(r,{axis:"col",index:t,count:e,remove:!0})),this.columnMeta.splice(t,e),(c=this.labels)==null||c.splice(t,e)):(this.cols.insert(t,e),this.applyEngineOp(Pt(r,{axis:"col",index:t,count:e,remove:!1})),t<this.columnMeta.length&&this.columnMeta.splice(t,0,...Array(e)),(h=this.labels)==null||h.splice(t,0,...Array(e).fill("")));const o=u=>n?u>=t+e?u-e:u>=t?-1:u:u>=t?u+e:u;this.filters=new Map([...this.filters].map(([u,d])=>[o(u),d]).filter(([u])=>u>=0)),this.sortKeys=this.sortKeys.map(u=>({...u,col:o(u.col)})).filter(u=>u.col>=0),this.merges.shift("col",t,n?-e:e),this.frozenCols=Math.min(this.frozenCols,this.countCols());const i=n?-e:e;this.cellMeta=Dt(this.cellMeta,u=>{const d=Gt(u%16384,t,i);return d<0?-1:u-u%16384+d}),this.hiddenCols=Dt(this.hiddenCols,u=>Gt(u,t,i))}ensureSize(t,e){var n;if(e>this.countCols()){for(const r of this.data)for(;r.length<e;)r.push(null);this.cols.resize(e)}if(t>this.data.length){const r=t-this.data.length;for(let o=0;o<r;o++)this.data.push(Array(this.countCols()).fill(null));(n=this.binding)==null||n.ensureRows(this.data.length),this.mapper.insert(this.data.length-r,r),this.syncRows()}}ensureVisualRows(t){t>this.countRows()&&this.ensureSize(this.data.length+t-this.countRows(),this.countCols())}bind(t){return Mn(t)?(this.binding=ae.create(t,this.columnMeta.map(e=>e==null?void 0:e.data),this.opts.dataSchema),this.binding.toRows()):(this.binding=void 0,t)}normalize(t){const e=t.length===0,n=Math.max(t.length,this.opts.minRows??(e?50:0)),r=Math.max(Zt(t,o=>o.length),this.opts.minCols??(e?26:0),this.columnMeta.length,1);return Array.from({length:n},(o,i)=>Array.from({length:r},(l,a)=>{var c;return((c=t[i])==null?void 0:c[a])??null}))}syncRows(){const t=this.mapper.count;if(!this.rowsCustomized){this.rows.resize(t);return}const e=this.rows.defaultSize,n=Array.from({length:t},(r,o)=>this.rowHeights.get(this.mapper.toPhysical(o))??e);this.rows=new Ft(t,e,n),this.rowsCustomized=this.rowHeights.size>0}afterRowMapping(){this.syncRows(),this.clampSelection(),this.render()}revalidate(t,e){const n=this.metaAt(t,e),r=O(t,e),o=this.invalid.get(r),i=ge(n)?Es(this.valueAt(t,e),this.rawAt(t,e),n,t,e):void 0;i?this.invalid.set(r,i):this.invalid.delete(r),i!==o&&this.run("afterValidate",this.mapper.toVisual(t),e,i)}validateAll(){this.invalid.clear();const t=Array.from({length:this.countCols()},(n,r)=>r),e=this.opts.cells?t:t.filter(n=>this.columnMeta[n]&&ge(this.columnMeta[n]));for(let n=0;n<this.data.length;n++)for(const r of e)this.revalidate(n,r);for(const n of this.cellMeta.keys())this.revalidate(Math.floor(n/16384),n%16384)}computedBinding(){return!!this.binding&&!!this.engine&&this.opts.bindFormulas!=="text"}boundValueAt(t,e){const n=this.rawAt(t,e);if(!this.computedBinding()||!(n===null||X(n)))return n;const r=this.valueAt(t,e);return r instanceof ct?null:r}writeComputed(t,e,n){if(!this.computedBinding())return;const r=this.boundValueAt(t,e);(X(this.rawAt(t,e))||r!==null||n&&this.rawAt(t,e)===null)&&this.binding.write(t,e,r)}syncBoundObjects(){if(this.computedBinding())for(let t=0;t<this.data.length;t++)for(let e=0;e<this.data[t].length;e++)this.writeComputed(t,e,!1)}run(t,...e){let n=!0;for(const r of this.hooks.get(t)??[])r(...e)===!1&&(n=!1);return n}mergesActive(){return this.merges.list.length>0&&this.mapper.isIdentity}mergeAt(t,e){return this.mergesActive()?this.merges.get(t,e):void 0}mergeAllowed(t){const e=(n,r,o)=>o>0&&n<o&&n+r>o;return this.mapper.isIdentity&&t.row>=0&&t.col>=0&&t.row+t.rowspan<=this.data.length&&t.col+t.colspan<=this.countCols()&&!e(t.row,t.rowspan,this.frozenRows)&&!e(t.col,t.colspan,this.frozenCols)}el(t,e,n="div"){const r=this.root.ownerDocument.createElement(n);return r.className=t,e.appendChild(r),r}makePane(t,e,n,r){const o=this.el(`ct-pane ${t}`,e);return{el:o,frozenRows:n,frozenCols:r,cells:new Map,pool:[],colHeads:[],rowHeads:[],rangeBox:this.el("ct-range",o),fillBox:this.el("ct-fill-area",o),activeBox:this.el("ct-active",o),handle:this.el("ct-fill",o)}}buildDom(){this.canvas=this.el("ct-canvas",this.root),this.topBand=this.el("ct-band ct-band-top",this.canvas),this.bodyBand=this.el("ct-band ct-band-body",this.canvas),this.panes={corner:this.makePane("ct-pane-corner",this.topBand,!0,!0),top:this.makePane("ct-pane-top",this.topBand,!0,!1),left:this.makePane("ct-pane-left",this.bodyBand,!1,!0),main:this.makePane("ct-pane-main",this.bodyBand,!1,!1)},this.cornerHead=this.el("ct-header ct-cornerhead",this.panes.corner.el),this.announcer=this.el("ct-sr",this.root),this.announcer.setAttribute("aria-live","polite"),this.announcer.setAttribute("aria-atomic","true"),this.input=this.root.ownerDocument.createElement("textarea"),this.input.className="ct-editor ct-idle",this.input.setAttribute("aria-label","Cell editor"),this.input.spellcheck=!1,this.input.addEventListener("keydown",this.onEditorKey),this.input.addEventListener("input",this.onInput),this.input.addEventListener("compositionstart",()=>this.openEditor("")),this.input.addEventListener("blur",t=>{(!this.bar||t.relatedTarget!==this.bar.input)&&this.closeEditor(!0)}),this.panes.main.el.appendChild(this.input)}resetHeaders(){for(const t of Object.values(this.panes))t.colHeads.forEach(e=>e.remove()),t.colHeads=[]}frozenSize(){return{fw:this.cols.offset(this.frozenCols),fh:this.rows.offset(this.frozenRows)}}layout(){const t=this.cols.total,e=this.rows.total,{fw:n,fh:r}=this.frozenSize(),o=(i,l,a)=>{i.style.width=`${Math.max(0,l)}px`,i.style.height=`${Math.max(0,a)}px`};o(this.canvas,this.rowHeaderW+t,this.headerH+e),o(this.topBand,this.rowHeaderW+t,this.headerH+r),this.topBand.style.display=this.headerH+r>0?"":"none",o(this.bodyBand,this.rowHeaderW+t,e-r),o(this.panes.corner.el,this.rowHeaderW+n,this.headerH+r),o(this.panes.top.el,t-n,this.headerH+r),o(this.panes.left.el,this.rowHeaderW+n,e-r),o(this.panes.main.el,t-n,e-r),this.panes.corner.el.classList.toggle("ct-edge-r",n>0),this.panes.left.el.classList.toggle("ct-edge-r",n>0),this.panes.corner.el.classList.toggle("ct-edge-b",r>0),this.panes.top.el.classList.toggle("ct-edge-b",r>0),this.root.setAttribute("aria-rowcount",String(this.countRows()+(this.headerH?1:0))),this.root.setAttribute("aria-colcount",String(this.countCols()+(this.rowHeaderW?1:0))),vt(this.cornerHead,0,0,this.rowHeaderW,this.headerH),this.cornerHead.style.display=this.rowHeaderW&&this.headerH?"":"none"}cellX(t,e){return(t.frozenCols?this.rowHeaderW:0)+this.cols.offset(e)-(t.frozenCols?0:this.cols.offset(this.frozenCols))}cellY(t,e){return(t.frozenRows?this.headerH:0)+this.rows.offset(e)-(t.frozenRows?0:this.rows.offset(this.frozenRows))}viewport(){const{fw:t,fh:e}=this.frozenSize(),n=this.root.scrollTop+e,r=this.root.scrollLeft+t,o=(this.root.clientHeight||600)-this.headerH-e,i=(this.root.clientWidth||1e3)-this.rowHeaderW-t;return{r0:Math.max(this.frozenRows,this.rows.indexAt(n)-qt),r1:Math.min(this.countRows()-1,this.rows.indexAt(n+o)+qt),c0:Math.max(this.frozenCols,this.cols.indexAt(r)-qt),c1:Math.min(this.countCols()-1,this.cols.indexAt(r+i)+qt)}}paneOf(t,e){const n=t<this.frozenRows,r=e<this.frozenCols;return n?r?this.panes.corner:this.panes.top:r?this.panes.left:this.panes.main}renderPane(t,[e,n],[r,o]){const i=[];if(n>=e&&o>=r){const c=new Set;for(let h=e;h<=n;h++)for(let u=r;u<=o;u++){if(this.hiddenCols.size&&this.hiddenCols.has(u))continue;const d=this.mergeAt(h,u);if(d&&(d.row!==h||d.col!==u)){(d.row<e||d.col<r)&&c.add(d);continue}i.push([h,u,d])}for(const h of c)i.push([h.row,h.col,h])}const l=new Set(i.map(([c,h])=>O(c,h)));for(const[c,h]of t.cells)l.has(c)||t.pool.push(h);const a=new Map;for(const[c,h,u]of i){const d=O(c,h),m=t.cells.get(d)??t.pool.pop()??this.makeCell(t);a.set(d,m);const w=u?this.cols.offset(h+u.colspan)-this.cols.offset(h):this.cols.size(h),A=u?this.rows.offset(c+u.rowspan)-this.rows.offset(c):this.rows.size(c);this.paintCell(m,c,h),vt(m,this.cellX(t,h),this.cellY(t,c),w,A),m.style.display=""}for(const c of t.pool)c.style.display="none";t.cells=a,this.renderHeaders(t,[e,n],[r,o]),this.renderSelection(t)}makeCell(t){const e=this.el("ct-cell",t.el);return e.setAttribute("role","gridcell"),e}paintCell(t,e,n){var p;const r=this.mapper.toPhysical(e),o=this.metaAt(r,n),i=this.valueAt(r,n),{text:l,kind:a}=Ss(i,o,this.opts.locale);let c=a?`ct-cell ct-${a}`:"ct-cell";o.type==="dropdown"&&(c+=" ct-dd"),o.readOnly&&(c+=" ct-readonly");const h=this.invalid.size?this.invalid.get(O(r,n)):void 0;h&&(c+=" ct-invalid"),o.className&&(c+=` ${o.className}`),this.searchHits.size&&this.searchHits.has(O(r,n))&&(c+=" ct-match");const u=this.conditionalStyle(r,n,i),d=u?{...o.style,...u}:o.style;d&&(c+=Xr(d)),t.className!==c&&(t.className=c);const m=(d==null?void 0:d.color)??"";t.dataset.fg!==m&&(t.style.color=m,t.dataset.fg=m);const w=(d==null?void 0:d.background)??"";t.dataset.bg!==w&&(t.style.backgroundColor=w,t.dataset.bg=w);const A=String(e+(this.headerH?2:1)),y=String(n+(this.rowHeaderW?2:1));t.getAttribute("aria-rowindex")!==A&&t.setAttribute("aria-rowindex",A),t.getAttribute("aria-colindex")!==y&&t.setAttribute("aria-colindex",y),a==="check"?t.dataset.check!==l&&(t.textContent="",this.el("ct-checkbox",t,"span").textContent=l,t.dataset.check=l):(t.dataset.check!==void 0&&delete t.dataset.check,t.textContent!==l&&(t.textContent=l)),h?t.title=h:t.title&&(t.title=""),(p=o.renderer)==null||p.call(o,t,i,{row:e,col:n,meta:o})}conditionalStyle(t,e,n){const r=this.opts.conditionalFormats;if(!(r!=null&&r.length))return;let o;for(const i of r){if(!i.entireRow&&i.columns&&!i.columns.includes(e))continue;(i.entireRow?i.columns??[]:[e]).some(c=>{const h=c===e?n:this.valueAt(t,c);return typeof i.when=="function"?i.when(h,this.mapper.toVisual(t),c):Os(h,this.displayText(t,c,h),{condition:i.when},this.opts.locale)})&&(o={...o,...i.style})}return o}renderHeaders(t,[e,n],[r,o]){var l,a,c;const i=this.getSelectedRange();if(t.frozenRows&&this.headerH){let h=0;for(let u=r;u<=o;u++){if(this.hiddenCols.size&&this.hiddenCols.has(u))continue;const d=t.colHeads[h]??this.makeColHeader(t,h);h++,d.classList.toggle("ct-gap-r",this.hiddenCols.has(u+1)),d.classList.toggle("ct-gap-l",u>0&&this.hiddenCols.has(u-1)),d.setAttribute("aria-colindex",String(u+(this.rowHeaderW?2:1))),d.dataset.col=String(u);const m=((l=this.labels)==null?void 0:l[u])||((a=this.columnMeta[u])==null?void 0:a.title)||((c=this.binding)==null?void 0:c.fields[u])||Tt(u),w=d.children[0];w.textContent!==m&&(w.textContent=m);const A=this.sortKeys.findIndex(f=>f.col===u),y=A<0?"":`${this.sortKeys[A].order==="asc"?"▲":"▼"}${this.sortKeys.length>1?A+1:""}`,p=d.children[1];p.textContent!==y&&(p.textContent=y),d.classList.toggle("ct-hl",!!i&&u>=i.start.col&&u<=i.end.col),d.classList.toggle("ct-filtered",this.filters.has(u)),vt(d,this.cellX(t,u),0,this.cols.size(u),this.headerH),d.style.display=""}for(;h<t.colHeads.length;h++)t.colHeads[h].style.display="none"}if(t.frozenCols&&this.rowHeaderW){let h=0;for(let u=e;u<=n;u++,h++){const d=t.rowHeads[h]??this.makeRowHeader(t,h);d.dataset.row=String(u);const m=String(this.mapper.toPhysical(u)+1),w=d.children[0];w.textContent!==m&&(w.textContent=m),d.setAttribute("aria-rowindex",String(u+(this.headerH?2:1))),d.classList.toggle("ct-hl",!!i&&u>=i.start.row&&u<=i.end.row),vt(d,0,this.cellY(t,u),this.rowHeaderW,this.rows.size(u)),d.style.display=""}for(;h<t.rowHeads.length;h++)t.rowHeads[h].style.display="none"}}makeRowHeader(t,e){const n=this.el("ct-header ct-rowhead",t.el);return n.setAttribute("role","rowheader"),this.el("ct-label",n,"span"),this.el("ct-rresize",n),t.rowHeads[e]=n,n}makeColHeader(t,e){const n=this.el("ct-header ct-colhead",t.el);if(n.setAttribute("role","columnheader"),this.el("ct-label",n,"span"),this.el("ct-sort",n,"span"),this.opts.columnSorting||this.opts.filters){const r=this.el("ct-menu-btn",n,"button");r.type="button",r.tabIndex=-1,r.textContent="▾",r.setAttribute("aria-label",this.messages.columnMenu)}return this.el("ct-resize",n),t.colHeads[e]=n,n}boxFor(t,e){const n=Math.max(e.start.row,t.frozenRows?0:this.frozenRows),r=Math.min(e.end.row,t.frozenRows?this.frozenRows-1:this.countRows()-1),o=Math.max(e.start.col,t.frozenCols?0:this.frozenCols),i=Math.min(e.end.col,t.frozenCols?this.frozenCols-1:this.countCols()-1);if(n>r||o>i)return null;const l=this.cellX(t,o),a=this.cellY(t,n);return[l-1,a-1,this.cellX(t,i+1)-l+1,this.cellY(t,r+1)-a+1]}renderSelection(t){const e=this.getSelectedRange(),n=(...c)=>c.forEach(h=>h.style.display="none");if(!e||!this.anchor){n(t.rangeBox,t.activeBox,t.handle,t.fillBox);return}const r=(c,h)=>{if(!h)return n(c);vt(c,...h),c.style.display=""},o=this.mergeAt(this.anchor.row,this.anchor.col),i=o?{start:{row:o.row,col:o.col},end:{row:o.row+o.rowspan-1,col:o.col+o.colspan-1}}:{start:this.anchor,end:this.anchor},l=e.start.row!==i.start.row||e.start.col!==i.start.col||e.end.row!==i.end.row||e.end.col!==i.end.col;r(t.rangeBox,l?this.boxFor(t,e):null),r(t.activeBox,this.boxFor(t,i)),r(t.fillBox,this.fillTarget?this.boxFor(t,Ws(e,this.fillTarget.range)):null),this.opts.fillHandle!==!1&&!this.opts.readOnly&&!this.editing&&this.paneOf(e.end.row,e.end.col)===t?(vt(t.handle,this.cellX(t,e.end.col+1)-4,this.cellY(t,e.end.row+1)-4,7,7),t.handle.style.display=""):n(t.handle)}scheduleRender(){this.frame||(this.frame=vi(()=>{this.frame=0,this.render()}))}scrollIntoView({row:t,col:e}){const{fw:n,fh:r}=this.frozenSize(),o=this.root.clientHeight-this.headerH,i=this.root.clientWidth-this.rowHeaderW;if(!(o<=0||i<=0)){if(t>=this.frozenRows){const l=this.rows.offset(t),a=l+this.rows.size(t);l-r<this.root.scrollTop?this.root.scrollTop=l-r:a>this.root.scrollTop+o&&(this.root.scrollTop=a-o)}if(e>=this.frozenCols){const l=this.cols.offset(e),a=l+this.cols.size(e);l-n<this.root.scrollLeft?this.root.scrollLeft=l-n:a>this.root.scrollLeft+i&&(this.root.scrollLeft=a-i)}}}clampSelection(){if(!this.anchor||!this.selEnd)return;if(!this.countRows()||!this.countCols()){this.anchor=this.selEnd=null;return}const t=e=>({row:Math.min(e.row,this.countRows()-1),col:Math.min(e.col,this.countCols()-1)});this.anchor=t(this.anchor),this.selEnd=t(this.selEnd)}cellAtClient(t,e){const n=this.root.getBoundingClientRect(),{fw:r,fh:o}=this.frozenSize(),i=t-n.left-this.root.clientLeft-this.rowHeaderW,l=e-n.top-this.root.clientTop-this.headerH,a=i<r?Math.max(0,i):i+this.root.scrollLeft,c=l<o?Math.max(0,l):l+this.root.scrollTop;return{row:this.rows.indexAt(c),col:this.cols.indexAt(a)}}isEditing(){return this.editing}openEditor(t){if(!this.anchor||this.editing)return;const e=this.mapper.toPhysical(this.anchor.row),n=this.metaAt(e,this.anchor.col);if(this.isReadOnly(e,this.anchor.col)||n.type==="checkbox"){this.input.value="";return}const r=this.input;this.editing=!0,this.editorEnterMode=t!==void 0,r.value=t??jt(this.rawAt(e,this.anchor.col),n,this.opts.locale),r.classList.remove("ct-idle"),this.placeInput(),this.autoSizeInput(),this.focusInput(),r.setSelectionRange(r.value.length,r.value.length),n.type==="dropdown"&&n.source&&this.showDropdown(n.source,t!==void 0?r.value:""),this.render()}closeEditor(t){if(!this.editing||!this.anchor)return;this.editing=!1,this.hideDropdown();const e=this.mapper.toPhysical(this.anchor.row),n=this.anchor.col,r=this.input.value;if(this.input.value="",this.input.classList.add("ct-idle"),t){const o=me(r,this.metaAt(e,n));o!==this.rawAt(e,n)&&this.applyChanges([this.change(e,n,o)],"edit")}this.render()}focusInput(){this.barFocused()||this.root.ownerDocument.activeElement!==this.input&&this.input.focus({preventScroll:!0})}barFocused(){return!!this.bar&&this.root.ownerDocument.activeElement===this.bar.input}buildFormulaBar(){const t=this.root.ownerDocument.createElement("div");t.className=`ct-bar${this.opts.theme==="light"?" ct-light":this.opts.theme==="dark"?" ct-dark":""}`;const e=this.el("ct-bar-address",t),n=this.root.ownerDocument.createElement("textarea");n.className="ct-bar-input",n.rows=1,n.spellcheck=!1,n.setAttribute("aria-label",this.messages.formulaBar),t.appendChild(n),this.root.before(t),this.bar={el:t,address:e,input:n};const r=()=>{n.style.height="auto",n.style.height=`${Math.min(120,n.scrollHeight)}px`};n.addEventListener("focus",r),n.addEventListener("input",()=>{this.editing||this.openEditor(n.value),this.editing&&(this.input.value=n.value,this.onInput(),r())}),n.addEventListener("blur",o=>{n.style.height="",this.editing&&o.relatedTarget!==this.input&&this.closeEditor(!0)}),n.addEventListener("keydown",o=>this.onBarKey(o))}onBarKey(t){const e=this.bar.input,n=(r,o,i)=>{t.preventDefault();const l=this.editing;this.editing=!1,this.input.focus({preventScroll:!0}),this.editing=l,this.closeEditor(i),(r||o)&&this.moveActive(r,o,!1)};t.key==="Escape"?n(0,0,!1):t.key==="Tab"?n(0,t.shiftKey?-1:1,!0):t.key==="Enter"&&t.altKey?(t.preventDefault(),e.setRangeText(`
184
+ `,e.selectionStart,e.selectionEnd,"end"),e.dispatchEvent(new Event("input"))):t.key==="Enter"&&n(t.shiftKey?-1:1,0,!0)}syncFormulaBar(){const t=this.bar;if(!t)return;const e=this.anchor;if(!e){t.address.textContent="",t.input.value="",t.input.disabled=!0;return}const n=this.mapper.toPhysical(e.row),r=Ne({row:n,col:e.col});if(t.address.textContent!==r&&(t.address.textContent=r),t.input.disabled=!1,t.input.readOnly=this.isReadOnly(n,e.col)||this.metaAt(n,e.col).type==="checkbox",this.barFocused()&&this.editing)return;const o=this.editing?this.input.value:jt(this.rawAt(n,e.col),this.metaAt(n,e.col),this.opts.locale);t.input.value!==o&&(t.input.value=o)}placeInput(){if(!this.anchor)return;const{row:t,col:e}=this.anchor,n=this.paneOf(t,e);if(this.input.parentElement!==n.el){const l=this.root.ownerDocument.activeElement===this.input;n.el.appendChild(this.input),l&&this.input.focus({preventScroll:!0})}const r=this.mergeAt(t,e),o=r?this.cols.offset(e+r.colspan)-this.cols.offset(e):this.cols.size(e),i=r?this.rows.offset(t+r.rowspan)-this.rows.offset(t):this.rows.size(t);vt(this.input,this.cellX(n,e)-1,this.cellY(n,t)-1,o+2,i+2),this.input.style.minWidth=this.editing?`${o+2}px`:""}autoSizeInput(){if(!this.editing||!this.anchor)return;const t=this.input,e=this.cols.size(this.anchor.col)+2;t.style.width="0",t.style.width=`${Math.max(e,t.scrollWidth+4)}px`}showDropdown(t,e){this.hideDropdown();const n=this.el("ct-dd-list",this.input.parentElement);n.setAttribute("role","listbox"),n.addEventListener("mousedown",r=>{r.preventDefault();const o=r.target.closest("[data-i]");!o||!this.dropdown||(this.input.value=this.dropdown.items[Number(o.dataset.i)],this.commitAndMove(1,0))}),this.dropdown={el:n,items:[],active:-1},n.style.left=this.input.style.left,n.style.top=`${parseFloat(this.input.style.top)+parseFloat(this.input.style.height)}px`,n.style.minWidth=this.input.style.width,this.filterDropdown(e,t)}filterDropdown(t,e){const n=this.dropdown;if(!n||!this.anchor)return;const r=e??this.metaAt(this.mapper.toPhysical(this.anchor.row),this.anchor.col).source??[],o=this.opts.locale,i=t.toLocaleLowerCase(o);n.items=r.filter(l=>l.toLocaleLowerCase(o).includes(i)),n.active=i&&n.items.length?0:-1,n.el.textContent="",n.items.forEach((l,a)=>{const c=this.el("ct-dd-item",n.el);c.dataset.i=String(a),c.setAttribute("role","option"),c.textContent=l}),this.highlightDropdown()}highlightDropdown(){var e,n;const t=this.dropdown;t&&([...t.el.children].forEach((r,o)=>r.classList.toggle("ct-on",o===t.active)),(n=(e=t.el.children[t.active])==null?void 0:e.scrollIntoView)==null||n.call(e,{block:"nearest"}))}hideDropdown(){var t;(t=this.dropdown)==null||t.el.remove(),this.dropdown=void 0}commitAndMove(t,e){this.closeEditor(!0),this.moveActive(t,e,!1)}listen(t,e,n){t.addEventListener(e,n),this.cleanup.push(()=>t.removeEventListener(e,n))}bindEvents(){const t=this.root.ownerDocument;this.listen(this.root,"scroll",()=>{this.dropdown&&this.closeEditor(!0),this.scheduleRender()}),this.listen(this.root,"keydown",r=>this.onKeyDown(r)),this.listen(this.canvas,"mousedown",r=>this.onMouseDown(r)),this.listen(this.canvas,"dblclick",r=>this.onDoubleClick(r)),this.listen(this.canvas,"contextmenu",r=>this.onContextMenu(r)),this.listen(t,"mousemove",r=>this.onDrag(r)),this.listen(t,"mouseup",()=>this.onMouseUp());const e=()=>this.root.contains(t.activeElement)&&!this.editing,n=r=>o=>{var l,a,c;if(!e())return;const i=this.copy(r);i!==void 0&&((l=o.clipboardData)==null||l.setData("text/plain",i),(a=this.clipboard)!=null&&a.html&&((c=o.clipboardData)==null||c.setData("text/html",this.clipboard.html)),o.preventDefault())};this.listen(t,"copy",n(!1)),this.listen(t,"cut",n(!0)),this.listen(t,"paste",r=>{var l,a;if(!e())return;const o=((l=r.clipboardData)==null?void 0:l.getData("text/plain"))??"",i=(a=r.clipboardData)==null?void 0:a.getData("text/html");(o||i)&&(r.preventDefault(),this.paste(o,i))})}onMouseDown(t){const e=t.target;if(this.editing&&e===this.input||e.closest(".ct-dd-list")||t.button!==0)return;t.preventDefault(),this.editing&&this.closeEditor(!0),this.focusInput();const n=e.closest(".ct-menu-btn");if(n)return this.openMenu(Number(n.parentElement.dataset.col),n);const r=e.closest(".ct-resize");if(r)return this.startResize(Number(r.parentElement.dataset.col),t.clientX);const o=e.closest(".ct-rresize");if(o)return this.startRowResize(Number(o.parentElement.dataset.row),t.clientY);if(e.closest(".ct-fill")){this.dragging="fill";return}if(e.closest(".ct-cornerhead"))return this.selectCell(0,0,this.countRows()-1,this.countCols()-1);const i=e.closest(".ct-colhead");if(i){const c=Number(i.dataset.col),h=this.getSelectedRange(),u=!!h&&h.start.row===0&&h.end.row===this.countRows()-1;if(!t.shiftKey&&u&&c>=h.start.col&&c<=h.end.col&&!this.opts.readOnly){this.dragging="move",this.moveDrop=null;return}this.selectCell(0,t.shiftKey&&this.anchor?this.anchor.col:c,this.countRows()-1,c),this.dragging="cols";return}const l=e.closest(".ct-rowhead");if(l){const c=Number(l.dataset.row);this.selectCell(t.shiftKey&&this.anchor?this.anchor.row:c,0,c,this.countCols()-1),this.dragging="rows";return}const a=this.cellAtClient(t.clientX,t.clientY);if(e.closest(".ct-checkbox")){this.selectCell(a.row,a.col),this.toggleCheckboxes({start:a,end:a});return}t.shiftKey&&this.anchor?this.selectCell(this.anchor.row,this.anchor.col,a.row,a.col):this.selectCell(a.row,a.col),this.dragging="cells"}onContextMenu(t){if(!this.opts.contextMenu)return;t.preventDefault(),this.editing&&this.closeEditor(!0);const e=t.target,n=this.getSelectedRange(),r=(l,a)=>!!n&&l>=n.start.row&&l<=n.end.row&&a>=n.start.col&&a<=n.end.col,o=e.closest(".ct-colhead"),i=e.closest(".ct-rowhead");if(o){const l=Number(o.dataset.col),a=!!n&&n.start.row===0&&n.end.row===this.countRows()-1;(!r(0,l)||!a)&&this.selectCell(0,l,this.countRows()-1,l)}else if(i){const l=Number(i.dataset.row),a=!!n&&n.start.col===0&&n.end.col===this.countCols()-1;(!r(l,0)||!a)&&this.selectCell(l,0,l,this.countCols()-1)}else if(!e.closest(".ct-cornerhead")){const l=this.cellAtClient(t.clientX,t.clientY);r(l.row,l.col)||this.selectCell(l.row,l.col)}this.focusInput(),this.openContextMenu(t.clientX,t.clientY)}onDoubleClick(t){const e=t.target;if(e.closest(".ct-fill"))return this.fillToDataEnd();e.closest(".ct-header")||e.closest(".ct-checkbox")||e.closest(".ct-dd-list")||this.editing||this.openEditor()}onDrag(t){if(!this.dragging||!this.anchor)return;const e=this.cellAtClient(t.clientX,t.clientY);this.dragging==="cells"?this.selectCell(this.anchor.row,this.anchor.col,e.row,e.col):this.dragging==="rows"?this.selectCell(this.anchor.row,0,e.row,this.countCols()-1):this.dragging==="cols"?this.selectCell(0,this.anchor.col,this.countRows()-1,e.col):this.dragging==="move"?this.updateMoveDrop(t.clientX):this.updateFillTarget(e)}onMouseUp(){var e;if(this.dragging==="move"){const n=this.moveDrop;this.moveDrop=null,this.dragging=null,(e=this.dropLine)==null||e.remove(),this.dropLine=void 0,n&&this.moveColumns(n.start,n.count,n.target);return}const t=this.fillTarget;this.fillTarget=null,this.dragging==="fill"&&t?this.autofill(this.getSelectedRange(),t.range):t&&this.render(),this.dragging=null}updateMoveDrop(t){const e=this.getSelectedRange(),n=this.root.getBoundingClientRect(),{fw:r}=this.frozenSize(),o=t-n.left-this.root.clientLeft-this.rowHeaderW,i=o<r?Math.max(0,o):o+this.root.scrollLeft,l=this.cols.indexAt(i),a=i-this.cols.offset(l)>this.cols.size(l)/2?l+1:l,c=e.end.col-e.start.col+1,h=this.canMoveColumns(e.start.col,c,a);this.moveDrop=h?{start:e.start.col,count:c,target:a}:null,this.dropLine||(this.dropLine=this.el("ct-drop",this.root));const u=this.rowHeaderW+this.cols.offset(a)-(a>=this.frozenCols?this.root.scrollLeft:0);this.dropLine.style.display=h?"":"none",this.dropLine.style.left=`${this.root.scrollLeft+u-1}px`,this.dropLine.style.top=`${this.root.scrollTop}px`,this.dropLine.style.height=`${this.root.clientHeight}px`}updateFillTarget(t){const e=this.getSelectedRange(),n=t.row-e.end.row,r=e.start.row-t.row,o=t.col-e.end.col,i=e.start.col-t.col,l=Math.max(n,r,o,i);let a=null;l>0&&(l===n?a={direction:"down",range:{start:{row:e.end.row+1,col:e.start.col},end:{row:t.row,col:e.end.col}}}:l===r?a={direction:"up",range:{start:{row:t.row,col:e.start.col},end:{row:e.start.row-1,col:e.end.col}}}:l===o?a={direction:"right",range:{start:{row:e.start.row,col:e.end.col+1},end:{row:e.end.row,col:t.col}}}:a={direction:"left",range:{start:{row:e.start.row,col:t.col},end:{row:e.end.row,col:e.start.col-1}}}),this.fillTarget=a,this.render()}fillToDataEnd(){const t=this.getSelectedRange();if(!t)return;const e=t.start.col>0?t.start.col-1:t.end.col+1;if(e>=this.countCols())return;let n=t.end.row;for(;n+1<this.countRows()&&!Fe(this.getSourceDataAtCell(n+1,e));)n++;n>t.end.row&&this.autofill(t,{start:{row:t.end.row+1,col:t.start.col},end:{row:n,col:t.end.col}})}startResize(t,e){const n=this.root.ownerDocument,r=this.cols.size(t),o=l=>this.setColWidth(t,r+l.clientX-e),i=()=>{n.removeEventListener("mousemove",o),n.removeEventListener("mouseup",i)};n.addEventListener("mousemove",o),n.addEventListener("mouseup",i)}startRowResize(t,e){const n=this.root.ownerDocument,r=this.rows.size(t),o=l=>this.setRowHeight(t,r+l.clientY-e),i=()=>{n.removeEventListener("mousemove",o),n.removeEventListener("mouseup",i)};n.addEventListener("mousemove",o),n.addEventListener("mouseup",i)}openMenu(t,e){var i,l;(i=this.closeMenu)==null||i.call(this);const n=[...this.filters].filter(([a])=>a!==t),r=new Set;for(let a=this.mapper.pinnedCount;a<this.data.length;a++)this.passes(a,n)&&r.add(this.displayText(a,t));const o=[...r].sort((a,c)=>a===""?1:c===""?-1:a.localeCompare(c,this.opts.locale,{numeric:!0,sensitivity:"base"}));this.closeMenu=jr({anchor:e,messages:this.messages,locale:this.opts.locale,sort:((l=this.sortKeys.find(a=>a.col===t))==null?void 0:l.order)??null,sortedElsewhere:this.sortKeys.some(a=>a.col!==t),filter:this.filters.get(t),values:o,sortable:!!this.opts.columnSorting,filterable:!!this.opts.filters,onSort:(a,c)=>{const h=this.sortKeys.filter(u=>u.col!==t);if(a===null&&h.length)this.applySort(h);else if(c&&a)this.applySort([...h,{col:t,order:a}]);else return this.sort(t,a);this.run("afterColumnSort",t,a)},onFilter:a=>this.setFilter(t,a),onClose:()=>{this.closeMenu=void 0,this.focusInput()}})}toggleCheckboxes(t){const e=[];for(let n=t.start.row;n<=t.end.row;n++){const r=this.mapper.toPhysical(n);for(let o=t.start.col;o<=t.end.col;o++)this.metaAt(r,o).type==="checkbox"&&e.push(this.change(r,o,this.valueAt(r,o)!==!0))}this.applyChanges(e,"edit")}moveActive(t,e,n){if(!this.anchor||!this.selEnd)return;const r=n?this.selEnd:this.anchor;let o=r.row,i=r.col;const l=this.mergeAt(r.row,r.col);l&&!n&&(t>0&&(o=l.row+l.rowspan-1),e>0&&(i=l.col+l.colspan-1)),o+=t,i+=e;const a=e<0?-1:1;for(;this.hiddenCols.has(i)&&i+a>=0&&i+a<this.countCols();)i+=a;this.hiddenCols.has(i)&&(i=r.col),n?this.selectCell(this.anchor.row,this.anchor.col,o,i):this.selectCell(o,i)}jump(t,e,n){const r=n?this.selEnd:this.anchor,o=this.countRows()-1,i=this.countCols()-1,l=(u,d)=>!Fe(this.getSourceDataAtCell(u,d)),a=(u,d)=>u>=0&&d>=0&&u<=o&&d<=i;let c=r.row,h=r.col;if(a(c+t,h+e)&&l(c,h)&&l(c+t,h+e))for(;a(c+t,h+e)&&l(c+t,h+e);)c+=t,h+=e;else for(c+=t,h+=e;a(c,h)&&!l(c,h)&&a(c+t,h+e);)c+=t,h+=e;c=Math.max(0,Math.min(c,o)),h=Math.max(0,Math.min(h,i)),n?this.selectCell(this.anchor.row,this.anchor.col,c,h):this.selectCell(c,h)}onKeyDown(t){if(this.editing||!this.anchor||!this.selEnd)return;const e=t.ctrlKey||t.metaKey,n=t.key,r=this.metaAt(this.mapper.toPhysical(this.anchor.row),this.anchor.col);if(n==="ContextMenu"||t.shiftKey&&n==="F10"){this.opts.contextMenu&&(t.preventDefault(),this.openContextMenu());return}if(n in Re){t.preventDefault();const[o,i]=Re[n];if(t.altKey&&n==="ArrowDown"&&r.type==="dropdown")return this.openEditor();e?this.jump(o,i,t.shiftKey):this.moveActive(o,i,t.shiftKey);return}if(e){const o=n.toLowerCase();if((o==="f"||o==="h")&&this.opts.search)t.preventDefault(),this.openSearch(o==="h");else if(o==="b"||o==="i"||o==="u")t.preventDefault(),this.toggleCellStyle(o==="b"?"bold":o==="i"?"italic":"underline");else if(o==="a")t.preventDefault(),this.selectCell(0,0,this.countRows()-1,this.countCols()-1);else if(o==="z")t.preventDefault(),t.shiftKey?this.redo():this.undo();else if(o==="y")t.preventDefault(),this.redo();else if(o==="d"){t.preventDefault();const i=this.getSelectedRange();i.end.row>i.start.row&&this.autofill({start:i.start,end:{row:i.start.row,col:i.end.col}},{start:{row:i.start.row+1,col:i.start.col},end:i.end})}else n==="Home"?(t.preventDefault(),this.selectCell(0,0)):n==="End"&&(t.preventDefault(),this.selectCell(this.countRows()-1,this.countCols()-1));return}switch(n){case"Tab":t.preventDefault(),this.moveActive(0,t.shiftKey?-1:1,!1);return;case"Enter":case"F2":t.preventDefault(),r.type==="checkbox"?this.toggleCheckboxes(this.getSelectedRange()):this.openEditor();return;case" ":r.type==="checkbox"&&(t.preventDefault(),this.toggleCheckboxes(this.getSelectedRange()));return;case"Delete":case"Backspace":t.preventDefault(),this.clearRange(this.getSelectedRange(),"clear");return;case"Home":t.preventDefault(),this.moveActive(0,-this.selEnd.col,t.shiftKey);return;case"End":t.preventDefault(),this.moveActive(0,this.countCols(),t.shiftKey);return;case"PageDown":case"PageUp":{t.preventDefault();const o=Math.max(1,Math.floor((this.root.clientHeight-this.headerH)/this.rows.defaultSize)-1);this.moveActive(n==="PageDown"?o:-o,0,t.shiftKey);return}}}}const Re={ArrowUp:[-1,0],ArrowDown:[1,0],ArrowLeft:[0,-1],ArrowRight:[0,1]},Pt=(s,t)=>(s.push(t),t);function Zt(s,t){let e=-1/0;for(const n of s)e=Math.max(e,t(n));return e}function bi(s){return s?new Intl.NumberFormat(s).format(1.5).includes(","):!1}function Bs(s,t,e,n){const r=t+e;return s>=t&&s<r?n>t?s+(n-r):s-(t-n):n>r&&s>=r&&s<n?s-e:n<t&&s>=n&&s<t?s+e:s}const Gt=(s,t,e)=>s<t?s:e>0?s+e:s<t-e?-1:s+e;function Dt(s,t){const e=new Map;for(const[n,r]of s){const o=t(n);o>=0&&e.set(o,r)}return e}const Fe=s=>s==null||s==="",Ws=(s,t)=>({start:{row:Math.min(s.start.row,t.start.row),col:Math.min(s.start.col,t.start.col)},end:{row:Math.max(s.end.row,t.end.row),col:Math.max(s.end.col,t.end.col)}});function vt(s,t,e,n,r){const o=s.style;o.left=`${t}px`,o.top=`${e}px`,o.width=`${n}px`,o.height=`${r}px`}const vi=s=>typeof requestAnimationFrame=="function"?requestAnimationFrame(s):setTimeout(s,16),xi=s=>{s&&(typeof cancelAnimationFrame=="function"?cancelAnimationFrame(s):clearTimeout(s))};exports.CSV_MIME=$n;exports.CellError=ct;exports.CenituGrid=yi;exports.FormulaEngine=ut;exports.FormulaSyntaxError=j;exports.MAX_COLS=16384;exports.MAX_ROWS=1048576;exports.ObjectBinding=ae;exports.RangeValue=L;exports.SHEET_SPAN=17179869184;exports.XLSX_MIME=Un;exports.ZipReader=Xn;exports.cellKey=O;exports.columnIndex=se;exports.columnLabel=Tt;exports.crc32=he;exports.dateCodeFromPattern=Rn;exports.dateToSerial=zt;exports.downloadBlob=Pe;exports.enUS=We;exports.formatDateCode=Dn;exports.formatSerialDate=Je;exports.getRegisteredFunctionNames=tr;exports.inverseMove=Cn;exports.isDateFormat=ce;exports.isError=g;exports.isFormula=X;exports.isObjectData=Mn;exports.keyToAddress=De;exports.normalizeRange=js;exports.numberFormatFromMeta=Fn;exports.parseA1=je;exports.parseDateString=oe;exports.parseFormula=Ie;exports.pxToColWidth=Hn;exports.quoteSheetName=Ys;exports.rangeContains=qn;exports.readXLSX=Bn;exports.registerFunction=x;exports.sanitizeSheetNames=Pn;exports.serialToDate=gt;exports.setClock=or;exports.setRandom=ir;exports.toA1=Ne;exports.toCSV=Nn;exports.toXLSX=vo;exports.toXLSXCompressed=Vn;exports.trTR=ri;exports.unparse=Qt;exports.unregisterFunction=Jn;exports.workbookEngine=Yo;exports.xlsxParts=ls;exports.zipDeflate=On;exports.zipStore=In;