@univerjs/engine-formula 0.1.0-beta.1 → 0.1.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/index.js +1 -1
- package/lib/es/index.js +3564 -3064
- package/lib/types/basics/common.d.ts +28 -26
- package/lib/types/basics/error-type.d.ts +1 -1
- package/lib/types/basics/function.d.ts +5 -1
- package/lib/types/basics/inverted-index-cache.d.ts +2 -2
- package/lib/types/basics/regex.d.ts +9 -10
- package/lib/types/commands/mutations/register-function.mutation.d.ts +30 -0
- package/lib/types/commands/mutations/unregister-function.mutation.d.ts +30 -0
- package/lib/types/controller/formula.controller.d.ts +5 -1
- package/lib/types/controller/register-function.controller.d.ts +26 -0
- package/lib/types/engine/analysis/__tests__/create-command-test-bed.d.ts +4 -0
- package/lib/types/engine/analysis/__tests__/parser.spec.d.ts +16 -0
- package/lib/types/engine/analysis/lexer-tree-builder.d.ts +1 -0
- package/lib/types/engine/ast-node/function-node.d.ts +11 -2
- package/lib/types/engine/ast-node/lambda-node.d.ts +0 -2
- package/lib/types/engine/ast-node/lambda-parameter-node.d.ts +0 -1
- package/lib/types/engine/dependency/dependency-tree.d.ts +3 -1
- package/lib/types/engine/reference-object/base-reference-object.d.ts +19 -14
- package/lib/types/engine/reference-object/range-reference-object.d.ts +2 -2
- package/lib/types/engine/utils/compare.d.ts +4 -0
- package/lib/types/engine/value-object/array-value-object.d.ts +12 -7
- package/lib/types/engine/value-object/base-value-object.d.ts +14 -0
- package/lib/types/engine/value-object/primitive-object.d.ts +1 -0
- package/lib/types/functions/array/function-map.d.ts +1 -3
- package/lib/types/functions/array/function-names.d.ts +0 -1
- package/lib/types/functions/base-function.d.ts +37 -2
- package/lib/types/functions/compatibility/function-map.d.ts +1 -3
- package/lib/types/functions/compatibility/function-names.d.ts +38 -1
- package/lib/types/functions/cube/function-names.d.ts +7 -0
- package/lib/types/functions/database/function-names.d.ts +12 -0
- package/lib/types/functions/date/function-names.d.ts +25 -0
- package/lib/types/functions/engineering/function-names.d.ts +54 -0
- package/lib/types/functions/financial/function-names.d.ts +55 -0
- package/lib/types/functions/information/function-names.d.ts +21 -0
- package/lib/types/functions/logical/function-map.d.ts +3 -1
- package/lib/types/functions/logical/function-names.d.ts +19 -0
- package/lib/types/functions/logical/lambda/index.d.ts +24 -0
- package/lib/types/functions/logical/makearray/__test__/index.spec.d.ts +16 -0
- package/lib/types/functions/lookup/address/__tests__/index.spec.d.ts +16 -0
- package/lib/types/functions/lookup/address/index.d.ts +22 -0
- package/lib/types/functions/lookup/function-map.d.ts +4 -1
- package/lib/types/functions/lookup/function-names.d.ts +36 -1
- package/lib/types/functions/lookup/indirect/__test__/index.spec.d.ts +16 -0
- package/lib/types/functions/lookup/indirect/index.d.ts +4 -3
- package/lib/types/functions/lookup/vlookup/__tests__/index.spec.d.ts +16 -0
- package/lib/types/functions/lookup/vlookup/index.d.ts +21 -0
- package/lib/types/functions/math/function-names.d.ts +75 -1
- package/lib/types/functions/math/sum/index.d.ts +1 -1
- package/lib/types/functions/meta/compare/index.d.ts +1 -2
- package/lib/types/functions/meta/divided/index.d.ts +1 -2
- package/lib/types/functions/meta/minus/index.d.ts +1 -2
- package/lib/types/functions/meta/multiply/index.d.ts +1 -2
- package/lib/types/functions/meta/plus/index.d.ts +2 -3
- package/lib/types/functions/statistical/function-names.d.ts +107 -1
- package/lib/types/functions/text/function-map.d.ts +3 -1
- package/lib/types/functions/text/function-names.d.ts +47 -0
- package/lib/types/functions/web/function-names.d.ts +3 -0
- package/lib/types/index.d.ts +19 -0
- package/lib/types/models/formula-data.model.d.ts +3 -1
- package/lib/types/plugin.d.ts +4 -0
- package/lib/types/services/current-data.service.d.ts +1 -0
- package/lib/types/services/feature-calculation-manager.service.d.ts +1 -1
- package/lib/types/services/function.service.d.ts +4 -0
- package/lib/types/services/other-formula-manager.service.d.ts +2 -2
- package/lib/types/services/runtime.service.d.ts +11 -5
- package/lib/umd/index.js +1 -1
- package/package.json +7 -7
- /package/lib/types/functions/{array → logical}/makearray/index.d.ts +0 -0
- /package/lib/types/functions/{compatibility → text}/concatenate/index.d.ts +0 -0
package/lib/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Or=Object.defineProperty;var Ur=(s,r,e)=>r in s?Or(s,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[r]=e;var g=(s,r,e)=>(Ur(s,typeof r!="symbol"?r+"":r,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("@univerjs/core"),D=require("@wendellhu/redi"),_t=require("rxjs");function cr(s,r,e,t,n){for(let i=0,a=s.length;i<a;i++){const o=s[i];if(r!==o.unitId||e!==o.sheetId)continue;const{startRow:u,startColumn:c,endRow:l,endColumn:f}=o.range;if(t>=u&&t<=l&&n>=c&&n<=f)return!0}return!1}var h=(s=>(s.DIV_BY_ZERO="#DIV/0!",s.NAME="#NAME!",s.VALUE="#VALUE!",s.NUM="#NUM!",s.NA="#N/A",s.CYCLE="#CYCLE!",s.REF="#REF!",s.SPILL="#SPILL!",s.CALC="#CALC!",s.ERROR="#ERROR!",s.CONNECT="#GETTING_DATA",s.NULL="#NULL!",s))(h||{});const Ir=new Set(["#DIV/0!","#NAME!","#VALUE!","#NUM!","#N/A","#CYCLE!","#REF!","#SPILL!","#CALC!","#ERROR!","#GETTING_DATA","#NULL!"]);var lr=(s=>(s[s.Financial=0]="Financial",s[s.Date=1]="Date",s[s.Math=2]="Math",s[s.Statistical=3]="Statistical",s[s.Lookup=4]="Lookup",s[s.Database=5]="Database",s[s.Text=6]="Text",s[s.Logical=7]="Logical",s[s.Information=8]="Information",s[s.Engineering=9]="Engineering",s[s.Cube=10]="Cube",s[s.Compatibility=11]="Compatibility",s[s.Web=12]="Web",s[s.Array=13]="Array",s[s.Univer=14]="Univer",s))(lr||{}),G=(s=>(s.PLUS="+",s.MINUS="-",s.MULTIPLY="*",s.DIVIDED="/",s.CONCATENATE="&",s.POWER="^",s.EQUALS="=",s.NOT_EQUAL="<>",s.GREATER_THAN=">",s.GREATER_THAN_OR_EQUAL=">=",s.LESS_THAN="<",s.LESS_THAN_OR_EQUAL="<=",s))(G||{}),R=(s=>(s.EQUALS="=",s.NOT_EQUAL="<>",s.GREATER_THAN=">",s.GREATER_THAN_OR_EQUAL=">=",s.LESS_THAN="<",s.LESS_THAN_OR_EQUAL="<=",s))(R||{});const Be=new Map([["<>",3],["<",3],[">=",3],["=",3],[">",3],["<=",3],["&",2],["+",2],["-",2],["/",1],["*",1],["^",0]]),Ue=new Set(Be.keys()),Mr=new Set(["=","<>",">",">=","<","<="]);var w=(s=>(s.OPEN_BRACKET="(",s.CLOSE_BRACKET=")",s.COMMA=",",s.SINGLE_QUOTATION="'",s.DOUBLE_QUOTATION='"',s.OPEN_BRACES="{",s.CLOSE_BRACES="}",s.COLON=":",s.OPEN_SQUARE_BRACKET="[",s.CLOSE_SQUARE_BRACKET="]",s))(w||{}),ue=(s=>(s.PERCENTAGE="%",s.POUND="#",s))(ue||{});const xr=new Set(["%","#"]);var P=(s=>(s.AT="@",s.MINUS="-",s))(P||{});const hr=[...Object.values(R),...Object.values(G),...Object.values(w),...Object.values(ue),...Object.values(P)];function Nt(s){return hr.includes(s)}function vr(s){for(const r of hr)if(s.indexOf(r)>-1)return!0;return!1}function Pr(s){return s[0]==="'"&&s[s.length-1]==="'"?s.substring(1,s.length-1):s}function fr(s){const r={};return Object.keys(s).forEach(e=>{const t=s[e];r[e]==null&&(r[e]={}),Object.keys(t).forEach(n=>{const i=t[n];r[e][n]=new m.ObjectMatrix(i)})}),r}class nt{constructor(r){g(this,"_cache");this._cache=new m.LRUMap(r)}set(r,e){const t=this._hash(r);this._cache.set(t,e)}get(r){const e=this._hash(r);return this._cache.get(e)}clear(){this._cache.clear()}_hash(r){return m.hashAlgorithm(r)}}const De=`'?\\[((?![\\/?:"<>|*\\\\]).)*\\]`,Fe="((?![\\[\\]\\/?*\\\\]).)*!",ce="$",Ft="\\s*?:\\s*?",At=`\\${ce}?[A-Za-z]+\\${ce}?[0-9]+`,Vr=`^(${P.AT})?(${De})?(${Fe})?${At}${Ft}${At}$`,Lt=`^(${De})?(${Fe})?\\s*?${At}(${ue.POUND})?$`,Br=`^(${De})?(${Fe})?\\${ce}?[0-9]+${Ft}\\${ce}?[0-9]+$`,kr=`^(${De})?(${Fe})?\\${ce}?[A-Za-z]+${Ft}\\${ce}?[A-Za-z]+$`,jr=`^(${De})?(${Fe})?\\s*?\\${ce}?[0-9]+$`,$r=`^(${De})?(${Fe})?\\s*?\\${ce}?[A-Za-z]+$`,_r="[.*?]",Qr="{.*?}";function Gr(s){return new RegExp(Lt).test(s)||new RegExp(Vr).test(s)||new RegExp(Br).test(s)||new RegExp(kr).test(s)}const de="P_1",oe="R_1",Se="L_1",st="LR_1",dr="LO_1",Hr="LET",Me="LAMBDA";var q=(s=>(s[s.NORMAL=0]="NORMAL",s[s.NUMBER=1]="NUMBER",s[s.STRING=2]="STRING",s[s.FUNCTION=3]="FUNCTION",s[s.REFERENCE=4]="REFERENCE",s[s.ARRAY=5]="ARRAY",s))(q||{});function mr(s){let r="";for(const e of s)typeof e=="string"?r+=e:r+=e.token;return r}class F{constructor(){g(this,"_parent");g(this,"_token",oe);g(this,"_children",[]);g(this,"_lambdaId");g(this,"_functionDefinitionPrivacyVar");g(this,"_lambdaParameter","");g(this,"_startIndex",-1);g(this,"_endIndex",-1)}dispose(){var r;this._children.forEach(e=>{typeof e!="string"&&e.dispose()}),(r=this._functionDefinitionPrivacyVar)==null||r.clear(),this._parent=null}getStartIndex(){return this._startIndex}getLambdaId(){return this._lambdaId}setLambdaId(r){this._lambdaId=r}getFunctionDefinitionPrivacyVar(){return this._functionDefinitionPrivacyVar}setLambdaPrivacyVar(r){this._functionDefinitionPrivacyVar=r}getLambdaParameter(){return this._lambdaParameter}setLambdaParameter(r){this._lambdaParameter=r}getParent(){return this._parent}setParent(r){this._parent=r}getChildren(){return this._children}setChildren(r){this._children=r}addChildren(r){this._children.push(r)}addChildrenFirst(r){this._children.unshift(r)}getToken(){return this._token}setToken(r){this._token=r}setIndex(r,e){this._startIndex=r,this._endIndex=e}replaceChild(r,e){const t=this._getIndexInParent(r);t!=null&&(this.getChildren().splice(t,1,e),e.setParent(this))}changeToParent(r){const e=this.getParent();e&&e.removeChild(this),this.setParent(r),r.getChildren().push(this)}removeChild(r){const e=this._getIndexInParent(r);e!=null&&this.getChildren().splice(e,1)}serialize(){const r=this.getToken(),e=this.getChildren(),t=[],n=e.length;for(let i=0;i<n;i++){const a=e[i];a instanceof F?t.push(a.serialize()):t.push(a)}return{token:r,st:this._startIndex,ed:this._endIndex,children:t}}_getIndexInParent(r){const e=this.getChildren(),t=e.length;for(let n=0;n<t;n++)if(e[n]===r)return n}}const gr=1e5,dt=new nt(gr),mt=new nt(gr);class it extends m.Disposable{constructor(){super(...arguments);g(this,"_currentLexerNode",new F);g(this,"_upLevel",0);g(this,"_segment","");g(this,"_bracketState",[]);g(this,"_squareBracketState",0);g(this,"_bracesState",0);g(this,"_singleQuotationState",0);g(this,"_doubleQuotationState",0);g(this,"_lambdaState",!1);g(this,"_colonState",!1);g(this,"_tableBracketState",!1)}dispose(){this._resetTemp(),this._currentLexerNode.dispose(),dt.clear(),mt.clear()}getUpLevel(){return this._upLevel}isColonClose(){return this._colonState===!1}isColonOpen(){return this._colonState===!0}isDoubleQuotationClose(){return this._doubleQuotationState===0}isLambdaOpen(){return this._lambdaState===!0}isLambdaClose(){return this._lambdaState===!1}isSingleQuotationClose(){return this._singleQuotationState===0}isBracesClose(){return this._bracesState===0}isBracketClose(){return this._bracketState.length===0}isSquareBracketClose(){return this._squareBracketState===0}getCurrentLexerNode(){return this._currentLexerNode}getFunctionAndParameter(e,t){const n=this._getCurrentParamIndex(e,t);if(n==null||n===h.VALUE)return;const i=n[0];if(typeof i=="string")return;let a=i.getParent(),o=i;for(;a;){const u=a.getToken();if(u!==de&&!Nt(u)&&a.getStartIndex()!==-1){const c=a.getChildren().indexOf(o);return{functionName:u,paramIndex:c}}o=a,a=a.getParent()}}moveFormulaRefOffset(e,t,n){const i=this.sequenceNodesBuilder(e);if(i==null)return e;const a=[];for(let o=0,u=i.length;o<u;o++){const c=i[o];if(typeof c=="string"||c.nodeType!==q.REFERENCE){a.push(c);continue}const{token:l}=c,f=m.deserializeRangeWithSheet(l),{range:d,sheetName:E,unitId:A}=f,C=m.Rectangle.moveOffset(d,t,n);let N="";m.isValidRange(C)?N=m.serializeRangeToRefString({range:C,unitId:A,sheetName:E}):N=h.REF,a.push({...c,token:N})}return`=${mr(a)}`}checkIfAddBracket(e){let t=0,n=e.length-1,i=e[n];for(;(i===w.CLOSE_BRACKET||i===" ")&&n>=0;)i===w.CLOSE_BRACKET&&t++,i=e[--n];const a=this._getCurrentParamIndex(e,e.length-2);if(a==null||a===h.VALUE)return 0;const o=a[0];if(typeof o=="string")return 0;let u=o.getParent(),c=0;for(;u;){const l=u.getToken();l!==de&&l!==w.COLON&&u.getStartIndex()!==-1&&l.toUpperCase()!==Me&&(t===0?c+=1:t--),u=u.getParent()}return c}sequenceNodesBuilder(e){const t=mt.get(e);if(t)return[...t];const n=this._getSequenceArray(e);if(n.length===0)return;const i=this.getSequenceNode(n);return mt.set(e,[...i]),i}getSequenceNode(e){const t=[];let n=!1;for(let i=0,a=e.length;i<a;i++){const o=e[i],u=e[i-1],{segment:c,currentString:l,cur:f}=o;if(l===w.DOUBLE_QUOTATION&&(n=!0),(c!==""||i===0)&&i!==a-1){t.push(l);continue}let d=(u==null?void 0:u.segment)||"";const E=i-d.length;let A=i-1;const C=i-1;if(i===a-1&&this._isLastMergeString(l)&&(d+=l,A+=1),d===""||Be.has(d)){t.push(l);continue}const N=d.trim(),S=this._replacePrefixString(N);n===!0&&N[N.length-1]===w.DOUBLE_QUOTATION?(n=!1,this._pushSequenceNode(t,{nodeType:q.STRING,token:d,startIndex:E,endIndex:A},C)):new RegExp(Lt).test(S)?this._pushSequenceNode(t,{nodeType:q.REFERENCE,token:d,startIndex:E,endIndex:A},C):m.Tools.isStringNumber(N)?this._pushSequenceNode(t,{nodeType:q.NUMBER,token:d,startIndex:E,endIndex:A},C):N.length>0&&this._pushSequenceNode(t,{nodeType:q.FUNCTION,token:d,startIndex:E,endIndex:A},C),(i!==a-1||!this._isLastMergeString(l))&&t.push(l)}return this._mergeSequenceNodeReference(t)}_getCurrentParamIndex(e,t){return this._nodeMaker(e,void 0,t)}_isLastMergeString(e){return e===w.DOUBLE_QUOTATION||m.Tools.isStringNumber(e)||!Nt(e)}_mergeSequenceNodeReference(e){const t=[],n=e.length;let i=0;for(;i<n;){const a=e[i];if(typeof a=="string"){const o=e[i-1];if(a.trim()===w.CLOSE_BRACES&&o!=null&&typeof o!="string"&&o.nodeType===q.FUNCTION&&o.token.trim().substring(0,1)===w.OPEN_BRACES){o.nodeType=q.ARRAY,o.token+=a,o.endIndex+=a.length,i++;continue}t.push(a)}else{const o=e[i+1],u=e[i+2];o===w.COLON&&typeof a!="string"&&u!=null&&typeof u!="string"&&Gr((a.token+o+u.token).trim())&&(a.nodeType=q.REFERENCE,a.token+=o+u.token,a.endIndex=u.endIndex,i+=2),t.push(a)}i++}return t}_pushSequenceNode(e,t,n){const i=n-t.startIndex+1;e.splice(e.length-i,i,t)}_replacePrefixString(e){return e.replace(new RegExp(P.AT,"g"),"").replace(new RegExp(P.MINUS,"g"),"")}nodeMakerTest(e){return this._nodeMaker(e)}treeBuilder(e,t=!0,n){if(t===!0){const l=dt.get(e);if(l)return l}this._resetCurrentLexerNode(),this._currentLexerNode.setToken(oe);const i=[];let a=this._nodeMaker(e,i);if(a===h.VALUE||i.length===0)return a;let o=!1,u="";if(n){const{hasDefinedName:l,sequenceString:f}=n(i);o=l,u=f}if(o&&(this._resetCurrentLexerNode(),this._currentLexerNode.setToken(oe),a=this._nodeMaker(`=${u}`),a===h.VALUE))return a;const c=this._getTopNode(this._currentLexerNode);return c&&(this._currentLexerNode=c),t&&(this._suffixExpressionHandler(this._currentLexerNode),dt.set(e,this._currentLexerNode)),this._currentLexerNode}_suffixExpressionHandler(e){var o,u;const t=e.getChildren();if(!t)return;const n=t.length,i=[],a=[];for(let c=0;c<n;c++){const l=t[c];if(l instanceof F)this._suffixExpressionHandler(l),i.push(l);else{const f=l.trim();if(f==="")continue;if(Ue.has(f)){for(;a.length>0;){const d=(o=a[a.length-1])==null?void 0:o.trim();if(!d||d===w.OPEN_BRACKET)break;const E=Be.get(d),A=Be.get(f);if(!E||!A)break;if(A>E)i.push(a.pop());else break}a.push(l)}else if(f===w.OPEN_BRACKET)a.push(l);else if(f===w.CLOSE_BRACKET)for(;a.length>0;){const d=(u=a[a.length-1])==null?void 0:u.trim();if(!d)break;if(d===w.OPEN_BRACKET){a.pop();break}i.push(a.pop())}else i.push(l)}}for(;a.length>0;)i.push(a.pop());e.setChildren(i)}_resetCurrentLexerNode(){this._currentLexerNode=new F}_resetSegment(){this._segment=""}_openBracket(e=0){this._bracketState.push(e)}_closeBracket(){this._bracketState.pop()}_openSquareBracket(){this._squareBracketState+=1}_closeSquareBracket(){this._squareBracketState-=1}_getCurrentBracket(){const e=this._bracketState;return e[e.length-1]}_openBraces(){this._bracesState+=1}_closeBraces(){this._bracesState-=1}_openSingleQuotation(){this._singleQuotationState+=1}_closeSingleQuotation(){this._singleQuotationState-=1}_openDoubleQuotation(){this._doubleQuotationState+=1}_closeDoubleQuotation(){this._doubleQuotationState-=1}_openLambda(){this._lambdaState=!0}_closeLambda(){this._lambdaState=!1}_openColon(e){this._upLevel=e,this._colonState=!0}_closeColon(){this._upLevel=0,this._colonState=!1}_isTableBracket(){return this._tableBracketState}_openTableBracket(){this._tableBracketState=!0}_closeTableBracket(){this._tableBracketState=!1}_getLastChildCurrentLexerNode(){const e=this._currentLexerNode.getChildren();if(e&&e.length>0){const t=e[e.length-1];if(t instanceof F)return t}return!1}_getLastChildCurrent(){const e=this._currentLexerNode.getChildren();return e&&e.length>0?e[e.length-1]:!1}_setParentCurrentLexerNode(){const e=this._currentLexerNode.getParent();return e?(this._currentLexerNode=e,!0):!1}_setAncestorCurrentLexerNode(){var n,i,a,o,u,c;const e=(n=this._currentLexerNode)==null?void 0:n.getParent();let t=!1;if(e&&e.getToken()===Se){if((i=e==null?void 0:e.getParent())!=null&&i.getParent()){const l=(o=(a=this._currentLexerNode.getParent())==null?void 0:a.getParent())==null?void 0:o.getParent();l&&(this._currentLexerNode=l),t=!0}}else if(e!=null&&e.getParent()){const l=(u=this._currentLexerNode.getParent())==null?void 0:u.getParent();l&&(this._currentLexerNode=l),t=!0}for(let l=0;l<this._upLevel;l++){const f=(c=this._currentLexerNode)==null?void 0:c.getParent();f&&(this._currentLexerNode=f),this._currentLexerNode?t=!0:t=!1}return t}_segmentCount(){return this._segment.trim().length}_pushSegment(e){this._segment+=e}_pushNodeToChildren(e,t=!1){if(e!==""){const n=this._currentLexerNode.getChildren();if(!(e instanceof F)&&this.isColonOpen()){const i=new F;i.setToken(e),i.setParent(this._currentLexerNode),e=i}t?n.unshift(e):n.push(e)}this.isColonOpen()&&(this._setAncestorCurrentLexerNode(),this._closeColon())}_setCurrentLexerNode(e,t=!1){this._pushNodeToChildren(e,t),e.setParent(this._currentLexerNode),this._currentLexerNode=e}_newAndPushCurrentLexerNode(e,t,n=!1){const i=new F;i.setToken(e),i.setIndex(t-e.length,t-1),this._setCurrentLexerNode(i,n)}_getTopNode(e){let t=e;for(;t!=null&&t.getParent();)t=t.getParent();return t}_removeLastChild(){this._currentLexerNode.getChildren().splice(-1)}_findPreviousToken(e,t){for(;t>=0;){const n=e[t];if(n!==" ")return n;t--}}_negativeCondition(e){return!!(Ue.has(e)||e===w.OPEN_BRACKET||e===w.COMMA||e==="")}_getSequenceArray(e){const t=[];return this._nodeMaker(e,t),t}_resetTemp(){this._currentLexerNode=new F,this._upLevel=0,this._segment="",this._bracketState=[],this._bracesState=0,this._singleQuotationState=0,this._doubleQuotationState=0,this._lambdaState=!1,this._colonState=!1}_nodeMaker(e,t,n){e.substring(0,1)===G.EQUALS&&(e=e.substring(1));const i=e.split(""),a=i.length;let o=0;for(this._resetTemp();o<a;){const u=i[o];if(n===o)return[this._currentLexerNode,u];if(u===w.OPEN_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())if(this._segmentCount()>0||this.isLambdaOpen()){this.isLambdaClose()&&(this._newAndPushCurrentLexerNode(this._segment,o),this._resetSegment()),this._openBracket(1),this._closeLambda();const c=i[o+1];if(c&&c===w.CLOSE_BRACKET){if(!this._setParentCurrentLexerNode()&&o!==a-1)return h.VALUE;o++}else c&&this._newAndPushCurrentLexerNode(de,o)}else this._pushNodeToChildren(u),this._openBracket(0);else if(u===w.CLOSE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()){this._pushNodeToChildren(this._segment),this._resetSegment();const c=this._getCurrentBracket();if(c===0)this._pushNodeToChildren(u);else if(c===1){const l=i[o+1];if(l&&l===w.OPEN_BRACKET){if(!this._setParentCurrentLexerNode()&&o!==a-1)return h.VALUE;this._newAndPushCurrentLexerNode(Se,o,!0),this._openLambda()}else if(!this._setAncestorCurrentLexerNode()&&o!==a-1)return h.VALUE}else return h.VALUE;this._closeBracket()}else if(u===w.OPEN_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._pushSegment(u),this._openBraces();else if(u===w.CLOSE_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._pushSegment(u),this._pushNodeToChildren(this._segment),this._resetSegment(),this._closeBraces();else if(u===w.OPEN_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._segment.length>0&&this._openTableBracket(),this._pushSegment(u),this._openSquareBracket();else if(u===w.CLOSE_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._closeSquareBracket(),this.isSquareBracketClose()?(this._pushSegment(u),this._isTableBracket()&&(this._pushNodeToChildren(this._segment),this._resetSegment()),this._closeTableBracket()):this._pushSegment(u);else if(u===w.DOUBLE_QUOTATION&&this.isSingleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){if(this.isDoubleQuotationClose())this._openDoubleQuotation();else{const c=i[o+1];c&&c===w.DOUBLE_QUOTATION?o++:this._closeDoubleQuotation()}this._pushSegment(u)}else if(u===w.SINGLE_QUOTATION&&this.isDoubleQuotationClose()){if(this.isSingleQuotationClose())this._openSingleQuotation();else{const c=i[o+1];c&&c===w.SINGLE_QUOTATION?o++:this._closeSingleQuotation()}this._pushSegment(u)}else if(u===w.COMMA&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){const c=this._getCurrentBracket();if(c===1||c==null){if(this._pushNodeToChildren(this._segment),this._resetSegment(),!this._setParentCurrentLexerNode()&&o!==a-1&&c!=null)return h.VALUE;this._newAndPushCurrentLexerNode(de,o)}else return h.VALUE}else if(u===w.COLON&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){const c=new F;c.setToken(u);const l=new F;l.setToken(de),l.setParent(c);const f=new F;f.setToken(de),f.setParent(c),c.getChildren().push(l,f);let d=c,E=0;if(this._segmentCount()>0){let A,C,N=0;const S=this._segment.trim(),y=S[0],T=S[1];if(y===P.MINUS&&(A=new F,A.setToken(P.MINUS),N++),(y===P.AT||T===P.AT)&&(C=new F,C.setToken(P.AT),A&&(A.addChildren(C),C.setParent(A)),N++),N>0&&(this._segment=S.slice(N)),E=N,C)if(C.addChildren(c),c.setParent(C),C.getParent()){const Q=C.getParent();Q&&(d=Q)}else d=C;else A&&(d=A,A.addChildren(c),c.setParent(A));const b=new F;b.setToken(this._segment),b.setParent(l),l.getChildren().push(b),this._resetSegment()}else{const A=this._getLastChildCurrentLexerNode();A&&A.changeToParent(l)}this._setCurrentLexerNode(d),this._currentLexerNode=f,this._openColon(E)}else if(xr.has(u)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()){this._pushNodeToChildren(this._segment);const c=new F;c.setToken(u);const l=this._getLastChildCurrent();l instanceof F?l.changeToParent(c):l!==!1&&(c.getChildren().push(l),this._removeLastChild()),this._pushNodeToChildren(c),c.setParent(this._currentLexerNode),this._resetSegment()}else if(Ue.has(u)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()){let c=this._segment.trim();if(u===G.MINUS&&c===""){const l=this._findPreviousToken(i,o-1)||"";if(this._negativeCondition(l)){this._pushSegment(G.MINUS),t==null||t.push({segment:this._segment,currentString:u,cur:o,currentLexerNode:this._currentLexerNode}),o++;continue}}else this._segment.length>0&&c===""?c=this._segment:(this._pushNodeToChildren(this._segment),c="");if(u===G.LESS_THAN||u===G.GREATER_THAN){const l=i[o+1];l&&Ue.has(u+l)?(this._pushNodeToChildren(c+u+l),o++):this._pushNodeToChildren(c+u)}else this._pushNodeToChildren(c+u);this._resetSegment()}else this._pushSegment(u);t==null||t.push({segment:this._segment,currentString:u,cur:o,currentLexerNode:this._currentLexerNode}),o++}this._pushNodeToChildren(this._segment)}}var Yr=Object.defineProperty,qr=Object.getOwnPropertyDescriptor,zr=(s,r,e,t)=>{for(var n=t>1?void 0:t?qr(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&Yr(r,e,n),n},Qt=(s,r)=>(e,t)=>r(e,t,s);exports.FormulaDataModel=class extends m.Disposable{constructor(e,t){super();g(this,"_formulaData",{});g(this,"_arrayFormulaRange",{});g(this,"_arrayFormulaCellData",{});this._currentUniverService=e,this._lexerTreeBuilder=t}clearPreviousArrayFormulaCellData(e){Object.keys(e).forEach(t=>{const n=e[t];Object.keys(n).forEach(i=>{var c,l;const a=n[i],o=(l=(c=this._arrayFormulaRange)==null?void 0:c[t])==null?void 0:l[i];if(o==null)return!0;let u=new m.ObjectMatrix;this._arrayFormulaCellData[t][i]!=null&&(u=new m.ObjectMatrix(this._arrayFormulaCellData[t][i])),a.forValue((f,d)=>{var y;const E=(y=o==null?void 0:o[f])==null?void 0:y[d];if(E==null)return!0;const{startRow:A,startColumn:C,endRow:N,endColumn:S}=E;for(let T=A;T<=N;T++)for(let b=C;b<=S;b++)u.setValue(T,b,null)}),this._arrayFormulaCellData[t][i]=u.getData()})})}mergeArrayFormulaCellData(e){Object.keys(e).forEach(t=>{const n=e[t];this._arrayFormulaRange[t]==null&&(this._arrayFormulaRange[t]={}),this._arrayFormulaCellData[t]==null&&(this._arrayFormulaCellData[t]={}),Object.keys(n).forEach(i=>{const a=n[i];let o=new m.ObjectMatrix,u=new m.ObjectMatrix;this._arrayFormulaRange[t][i]!=null&&(o=new m.ObjectMatrix(this._arrayFormulaRange[t][i])),this._arrayFormulaCellData[t][i]!=null&&(u=new m.ObjectMatrix(this._arrayFormulaCellData[t][i])),a.forValue((c,l)=>{const f=o==null?void 0:o.getValue(c,l);if(f==null)return!0;const{startRow:d,startColumn:E,endRow:A,endColumn:C}=f;for(let N=d;N<=A;N++)for(let S=E;S<=C;S++)u.setValue(N,S,null)}),a.forValue((c,l,f)=>{u.setValue(c,l,f)}),this._arrayFormulaCellData[t][i]=u.getData()})})}getFormulaData(){return this._formulaData}setFormulaData(e){this._formulaData=e}setArrayFormulaRange(e){this._arrayFormulaRange=e}getArrayFormulaRange(){return this._arrayFormulaRange}setArrayFormulaCellData(e){this._arrayFormulaCellData=e}getArrayFormulaCellData(){return this._arrayFormulaCellData}mergeArrayFormulaRange(e){Object.keys(e).forEach(t=>{const n=e[t];this._arrayFormulaRange[t]||(this._arrayFormulaRange[t]={}),Object.keys(n).forEach(i=>{const a=new m.ObjectMatrix(n[i]);let o=new m.ObjectMatrix;this._arrayFormulaRange[t][i]&&(o=new m.ObjectMatrix(this._arrayFormulaRange[t][i])),a.forValue((u,c,l)=>{o.setValue(u,c,l)}),this._arrayFormulaRange[t][i]=o.getData()})})}deleteArrayFormulaRange(e,t,n,i){var u;const a=(u=this._arrayFormulaRange[e])==null?void 0:u[t];if(a==null)return;const o=new m.ObjectMatrix(a);o.getValue(n,i)&&(o.realDeleteValue(n,i),this._arrayFormulaRange[e][t]=o.getData())}initFormulaData(){this._currentUniverService.getAllUniverSheetsInstance();const e=this._currentUniverService.getCurrentUniverSheetInstance(),t=e.getUnitId();this._formulaData[t]={},e.getSheets().forEach(i=>{const a=i.getCellMatrix(),o=i.getSheetId();Cr(this._formulaData,t,o,a)})}getCalculateData(){const e=this._currentUniverService.getAllUniverSheetsInstance(),t={},n={};for(const i of e){const a=i.getUnitId(),o=i.getSheets(),u={},c={};for(const l of o){const f=l.getSheetId(),d=l.getConfig();u[f]={cellData:new m.ObjectMatrix(d.cellData),rowCount:d.rowCount,columnCount:d.columnCount},c[l.getName()]=l.getSheetId()}t[a]=u,n[a]=c}return{allUnitData:t,unitSheetNameMap:n}}updateFormulaData(e,t,n){const i=new m.ObjectMatrix(n),a=this.getFormulaIdMap(e,t),o=new Map,u=this._formulaData;u[e]==null&&(u[e]={});const c=u[e];c[t]==null&&(c[t]={});const l=new m.ObjectMatrix(c[t]);i.forValue((f,d,E)=>{const A=(E==null?void 0:E.f)||"",C=(E==null?void 0:E.si)||"",N=m.isFormulaString(A),S=m.isFormulaId(C);if(N&&S)l.setValue(f,d,{f:A,si:C}),a.set(C,{f:A,r:f,c:d});else if(N&&!S)l.setValue(f,d,{f:A});else if(!N&&S)l.setValue(f,d,{f:"",si:C});else if(!N&&!S&&l.getValue(f,d)){const y=l.getValue(f,d),T=(y==null?void 0:y.f)||"",b=(y==null?void 0:y.si)||"";m.isFormulaString(T)&&m.isFormulaId(b)&&o.set(b,T),l.realDeleteValue(f,d)}}),l.forValue((f,d,E)=>{const A=(E==null?void 0:E.f)||"",C=(E==null?void 0:E.si)||"";if(m.isFormulaId(C)){const N=a.get(C),S=o.get(C);if(N&&!m.isFormulaString(A)){const y=N.f,T=d-N.c,b=f-N.r;l.setValue(f,d,{f:y,si:C,x:T,y:b})}else if(typeof S=="string"){const y=E.x||0,T=E.y||0,b=this._lexerTreeBuilder.moveFormulaRefOffset(S,y,T);o.set(C,{r:f,c:d,f:b}),l.setValue(f,d,{f:b,si:C})}else if(typeof S=="object"){const y=d-S.c,T=f-S.r;l.setValue(f,d,{f:S.f,si:C,x:y,y:T})}}})}getFormulaItemBySId(e,t,n){const i=this._formulaData;if(i[n]==null)return null;const a=i[n];if(a[t]==null)return null;const o=new m.ObjectMatrix(a[t]);let u=null;return o.forValue((c,l,f)=>{const{f:d,si:E,x:A=0,y:C=0}=f;if(E===e&&d.length>0&&A===0&&C===0)return u=f,!1}),u}getFormulaDataItem(e,t,n,i){var a,o,u,c;return(c=(u=(o=(a=this._formulaData)==null?void 0:a[i])==null?void 0:o[n])==null?void 0:u[e])==null?void 0:c[t]}getFormulaIdMap(e,t){const n=new Map,i=this._formulaData;if(i[e]==null)return n;const a=i[e];return a[t]==null||new m.ObjectMatrix(a[t]).forValue((u,c,l)=>{const f=(l==null?void 0:l.f)||"",d=(l==null?void 0:l.si)||"",E=(l==null?void 0:l.x)||0,A=(l==null?void 0:l.y)||0;m.isFormulaString(f)&&m.isFormulaId(d)&&E===0&&A===0&&n.set(d,{f,r:u,c})}),n}};exports.FormulaDataModel=zr([Qt(0,m.IUniverInstanceService),Qt(1,D.Inject(it))],exports.FormulaDataModel);function Cr(s,r,e,t){const n=new Map,i=new m.ObjectMatrix;t.forValue((a,o,u)=>{const c=(u==null?void 0:u.f)||"",l=(u==null?void 0:u.si)||"",f=m.isFormulaString(c),d=m.isFormulaId(l);f&&d?(i.setValue(a,o,{f:c,si:l}),n.set(l,{f:c,r:a,c:o})):f&&!d?i.setValue(a,o,{f:c}):!f&&d&&i.setValue(a,o,{f:"",si:l})}),i.forValue((a,o,u)=>{const c=(u==null?void 0:u.f)||"",l=(u==null?void 0:u.si)||"";if(m.isFormulaId(l)&&!m.isFormulaString(c)){const f=n.get(l);if(f){const d=f.f,E=o-f.c,A=a-f.r;i.setValue(a,o,{f:d,si:l,x:E,y:A})}}}),s[r][e]=i.getData()}const Kr=s=>{const r=s.get(exports.FormulaDataModel),e=m.Tools.deepClone(r.getArrayFormulaRange()),t=m.Tools.deepClone(r.getArrayFormulaCellData());return{arrayFormulaRange:e,arrayFormulaCellData:t}},Ye={id:"formula.mutation.set-array-formula-data",type:m.CommandType.MUTATION,handler:(s,r)=>{const e=s.get(exports.FormulaDataModel);return e.setArrayFormulaRange(r.arrayFormulaRange),e.setArrayFormulaCellData(r.arrayFormulaCellData),!0}},at={id:"formula.mutation.set-defined-name",type:m.CommandType.MUTATION,handler:()=>!0},ot={id:"formula.mutation.remove-defined-name",type:m.CommandType.MUTATION,handler:()=>!0},wt={id:"formula.mutation.set-feature-calculation",type:m.CommandType.MUTATION,handler:()=>!0},Tt={id:"formula.mutation.remove-feature-calculation",type:m.CommandType.MUTATION,handler:()=>!0},Ot={id:"formula.mutation.set-formula-calculation-start",type:m.CommandType.MUTATION,handler:()=>!0},Ut={id:"formula.mutation.set-formula-calculation-stop",type:m.CommandType.MUTATION,handler:()=>!0},qe={id:"formula.mutation.set-formula-calculation-notification",type:m.CommandType.MUTATION,handler:()=>!0},It={id:"formula.mutation.set-formula-calculation-result",type:m.CommandType.MUTATION,handler:()=>!0},Mt={id:"formula.mutation.set-formula-data",type:m.CommandType.MUTATION,handler:(s,r)=>(s.get(exports.FormulaDataModel).setFormulaData(r.formulaData),!0)},xt={id:"formula.mutation.set-other-formula",type:m.CommandType.MUTATION,handler:()=>!0},vt={id:"formula.mutation.remove-other-formula",type:m.CommandType.MUTATION,handler:()=>!0},pr={id:"formula.mutation.set-super-table",type:m.CommandType.MUTATION,handler:()=>!0},Er={id:"formula.mutation.remove-super-table",type:m.CommandType.MUTATION,handler:()=>!0},Pt={id:"formula.mutation.set-super-table-option",type:m.CommandType.MUTATION,handler:()=>!0};class ut extends m.Disposable{isError(){return!1}isAsyncObject(){return!1}isAsyncArrayObject(){return!1}isReferenceObject(){return!1}isValueObject(){return!1}isEqualType(r){return!1}}var Ce=(s=>(s.FALSE="FALSE",s.TRUE="TRUE",s))(Ce||{}),ae=(s=>(s[s.SUCCESS=0]="SUCCESS",s[s.ERROR=1]="ERROR",s))(ae||{}),me=(s=>(s.ALL="#All",s.DATA="#Data",s.HEADERS="#Headers",s.TOTALS="#Totals",s))(me||{}),X=(s=>(s[s.FRONT=0]="FRONT",s[s.BACK=1]="BACK",s))(X||{});class Xr{constructor(){g(this,"_cache",new Map);g(this,"_continueBuildingCache",new Map)}set(r,e,t,n,i){if(!this.shouldContinueBuildingCache(r,e,t,i))return;let a=this._cache.get(r);a==null&&(a=new Map,this._cache.set(r,a));let o=a.get(e);o==null&&(o=new Map,a.set(e,o));let u=o.get(t);u==null&&(u=new Map,o.set(t,u));let c=u.get(n);c==null&&(c=[],u.set(n,c)),c.push(i)}getCellValuePositions(r,e,t){var n,i;return(i=(n=this._cache.get(r))==null?void 0:n.get(e))==null?void 0:i.get(t)}getCellPositions(r,e,t,n){var i,a,o;return(o=(a=(i=this._cache.get(r))==null?void 0:i.get(e))==null?void 0:a.get(t))==null?void 0:o.get(n)}getCellPosition(r,e,t,n,i,a){const o=this.getCellPositions(r,e,t,n);if(o!=null){for(const u of o)if(u>=i&&u<=a)return u}}setContinueBuildingCache(r,e,t,n,i){let a=this._continueBuildingCache.get(r);a==null&&(a=new Map,this._continueBuildingCache.set(r,a));let o=a.get(e);o==null&&(o=new Map,a.set(e,o));let u=o.get(t);if(u==null){u={startRow:n,endRow:i},o.set(t,u);return}u.startRow=Math.min(u.startRow,n),u.endRow=Math.max(u.endRow,i)}shouldContinueBuildingCache(r,e,t,n){var u,c;const i=(c=(u=this._continueBuildingCache.get(r))==null?void 0:u.get(e))==null?void 0:c.get(t);if(i==null)return!0;const{startRow:a,endRow:o}=i;return!(n>=a&&n<=o)}canUseCache(r,e,t,n,i){var c,l;const a=(l=(c=this._continueBuildingCache.get(r))==null?void 0:c.get(e))==null?void 0:l.get(t);if(a==null)return!1;const{startRow:o,endRow:u}=a;return!(n>u||i<o)}clear(){this._cache.clear(),this._continueBuildingCache.clear()}}const ge=new Xr;function Wr(){return new Intl.Collator(void 0,{numeric:!0}).compare}function Zr(s){return s.indexOf("*")>-1||s.indexOf("?")>-1}function Gt(s,r){const e=r.replace(/~?[*?]/g,n=>n.startsWith("~")?`\\${n.substring(1)}`:n==="*"?".*":n==="?"?".":n);return new RegExp(`^${e}$`).test(s)}function Ht(s){return s.replace(/~?[*?]/g,r=>r.startsWith("~")?r.substring(1):" ")}function Jr(s,r,e){let t=!1;switch(e){case R.EQUALS:t=Gt(s,r);break;case R.GREATER_THAN:case R.GREATER_THAN_OR_EQUAL:t=Gt(s,r)||s>Ht(r);break;case R.LESS_THAN:case R.LESS_THAN_OR_EQUAL:t=s<Ht(r);break}return t}class le extends ut{constructor(r){super(),this._rawValue=r}isValueObject(){return!0}getValue(){return 0}getArrayValue(){return[]}setValue(r){}setArrayValue(r){}isArray(){return!1}isString(){return!1}isNumber(){return!1}isBoolean(){return!1}isLambda(){return!1}isError(){return!1}isNull(){return!1}getNegative(){return _.create(h.NAME)}getReciprocal(){return _.create(h.NAME)}plus(r){return _.create(h.NAME)}minus(r){return _.create(h.NAME)}multiply(r){return _.create(h.NAME)}divided(r){return _.create(h.NAME)}map(r){return _.create(h.NAME)}product(r,e){return e(this,r)}compare(r,e){return _.create(h.NAME)}wildcard(r,e){return _.create(h.NAME)}isEqual(r){return this.compare(r,R.EQUALS)}isNotEqual(r){return this.compare(r,R.NOT_EQUAL)}isGreaterThanOrEqual(r){return this.compare(r,R.GREATER_THAN_OR_EQUAL)}isLessThanOrEqual(r){return this.compare(r,R.LESS_THAN_OR_EQUAL)}isLessThan(r){return this.compare(r,R.LESS_THAN)}isGreaterThan(r){return this.compare(r,R.GREATER_THAN)}concatenateFront(r){return _.create(h.NAME)}concatenateBack(r){return _.create(h.NAME)}plusBy(r){return _.create(h.NAME)}minusBy(r){return _.create(h.NAME)}multiplyBy(r){return _.create(h.NAME)}dividedBy(r){return _.create(h.NAME)}compareBy(r,e){return _.create(h.NAME)}concatenate(r,e=X.FRONT){let t=this.getValue().toString();if(typeof r=="string")e===X.FRONT?t=r+t:t+=r;else if(typeof r=="number")e===X.FRONT?t=r.toString()+t:t+=r.toString();else if(typeof r=="boolean"){const n=r?"TRUE":"FALSE";e===X.FRONT?t=n+t:t+=n}return t}pow(r){return _.create(h.VALUE)}powInverse(r){return _.create(h.VALUE)}sqrt(){return _.create(h.VALUE)}cbrt(){return _.create(h.VALUE)}cos(){return _.create(h.VALUE)}acos(){return _.create(h.VALUE)}acosh(){return _.create(h.VALUE)}sin(){return _.create(h.VALUE)}asin(){return _.create(h.VALUE)}asinh(){return _.create(h.VALUE)}tan(){return _.create(h.VALUE)}tanh(){return _.create(h.VALUE)}atan(){return _.create(h.VALUE)}atan2(r){return _.create(h.VALUE)}atan2Inverse(r){return _.create(h.VALUE)}atanh(){return _.create(h.VALUE)}mean(){return this}median(){return this}var(){return this}std(){return this}log(){return _.create(h.VALUE)}log10(){return _.create(h.VALUE)}exp(){return _.create(h.VALUE)}abs(){return _.create(h.VALUE)}round(r){return _.create(h.VALUE)}roundInverse(r){return _.create(h.VALUE)}floor(r){return _.create(h.VALUE)}floorInverse(r){return _.create(h.VALUE)}ceil(r){return _.create(h.VALUE)}ceilInverse(r){return _.create(h.VALUE)}}class _ extends le{constructor(r,e=""){super(r),this._errorType=r,this._errorContent=e}static create(r,e){return new _(r,e)}getErrorType(){return this._errorType}getErrorContent(){return this._errorContent}isEqualType(r){return r.getErrorType()===this.getErrorType()}isError(){return!0}}var en=20,tn=1,pe=1e6,Yt=1e6,rn=-7,nn=21,sn=!1,ve="[big.js] ",Ne=ve+"Invalid ",ct=Ne+"decimal places",an=Ne+"rounding mode",Nr=ve+"Division by zero",O={},Z=void 0,on=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Ar(){function s(r){var e=this;if(!(e instanceof s))return r===Z?Ar():new s(r);if(r instanceof s)e.s=r.s,e.e=r.e,e.c=r.c.slice();else{if(typeof r!="string"){if(s.strict===!0&&typeof r!="bigint")throw TypeError(Ne+"value");r=r===0&&1/r<0?"-0":String(r)}un(e,r)}e.constructor=s}return s.prototype=O,s.DP=en,s.RM=tn,s.NE=rn,s.PE=nn,s.strict=sn,s.roundDown=0,s.roundHalfUp=1,s.roundHalfEven=2,s.roundUp=3,s}function un(s,r){var e,t,n;if(!on.test(r))throw Error(Ne+"number");for(s.s=r.charAt(0)=="-"?(r=r.slice(1),-1):1,(e=r.indexOf("."))>-1&&(r=r.replace(".","")),(t=r.search(/e/i))>0?(e<0&&(e=t),e+=+r.slice(t+1),r=r.substring(0,t)):e<0&&(e=r.length),n=r.length,t=0;t<n&&r.charAt(t)=="0";)++t;if(t==n)s.c=[s.e=0];else{for(;n>0&&r.charAt(--n)=="0";);for(s.e=e-t-1,s.c=[],e=0;t<=n;)s.c[e++]=+r.charAt(t++)}return s}function Ae(s,r,e,t){var n=s.c;if(e===Z&&(e=s.constructor.RM),e!==0&&e!==1&&e!==2&&e!==3)throw Error(an);if(r<1)t=e===3&&(t||!!n[0])||r===0&&(e===1&&n[0]>=5||e===2&&(n[0]>5||n[0]===5&&(t||n[1]!==Z))),n.length=1,t?(s.e=s.e-r+1,n[0]=1):n[0]=s.e=0;else if(r<n.length){if(t=e===1&&n[r]>=5||e===2&&(n[r]>5||n[r]===5&&(t||n[r+1]!==Z||n[r-1]&1))||e===3&&(t||!!n[0]),n.length=r,t){for(;++n[--r]>9;)if(n[r]=0,r===0){++s.e,n.unshift(1);break}}for(r=n.length;!n[--r];)n.pop()}return s}function Le(s,r,e){var t=s.e,n=s.c.join(""),i=n.length;if(r)n=n.charAt(0)+(i>1?"."+n.slice(1):"")+(t<0?"e":"e+")+t;else if(t<0){for(;++t;)n="0"+n;n="0."+n}else if(t>0)if(++t>i)for(t-=i;t--;)n+="0";else t<i&&(n=n.slice(0,t)+"."+n.slice(t));else i>1&&(n=n.charAt(0)+"."+n.slice(1));return s.s<0&&e?"-"+n:n}O.abs=function(){var s=new this.constructor(this);return s.s=1,s};O.cmp=function(s){var r,e=this,t=e.c,n=(s=new e.constructor(s)).c,i=e.s,a=s.s,o=e.e,u=s.e;if(!t[0]||!n[0])return t[0]?i:n[0]?-a:0;if(i!=a)return i;if(r=i<0,o!=u)return o>u^r?1:-1;for(a=(o=t.length)<(u=n.length)?o:u,i=-1;++i<a;)if(t[i]!=n[i])return t[i]>n[i]^r?1:-1;return o==u?0:o>u^r?1:-1};O.div=function(s){var r=this,e=r.constructor,t=r.c,n=(s=new e(s)).c,i=r.s==s.s?1:-1,a=e.DP;if(a!==~~a||a<0||a>pe)throw Error(ct);if(!n[0])throw Error(Nr);if(!t[0])return s.s=i,s.c=[s.e=0],s;var o,u,c,l,f,d=n.slice(),E=o=n.length,A=t.length,C=t.slice(0,o),N=C.length,S=s,y=S.c=[],T=0,b=a+(S.e=r.e-s.e)+1;for(S.s=i,i=b<0?0:b,d.unshift(0);N++<o;)C.push(0);do{for(c=0;c<10;c++){if(o!=(N=C.length))l=o>N?1:-1;else for(f=-1,l=0;++f<o;)if(n[f]!=C[f]){l=n[f]>C[f]?1:-1;break}if(l<0){for(u=N==o?n:d;N;){if(C[--N]<u[N]){for(f=N;f&&!C[--f];)C[f]=9;--C[f],C[N]+=10}C[N]-=u[N]}for(;!C[0];)C.shift()}else break}y[T++]=l?c:++c,C[0]&&l?C[N]=t[E]||0:C=[t[E]]}while((E++<A||C[0]!==Z)&&i--);return!y[0]&&T!=1&&(y.shift(),S.e--,b--),T>b&&Ae(S,b,e.RM,C[0]!==Z),S};O.eq=function(s){return this.cmp(s)===0};O.gt=function(s){return this.cmp(s)>0};O.gte=function(s){return this.cmp(s)>-1};O.lt=function(s){return this.cmp(s)<0};O.lte=function(s){return this.cmp(s)<1};O.minus=O.sub=function(s){var r,e,t,n,i=this,a=i.constructor,o=i.s,u=(s=new a(s)).s;if(o!=u)return s.s=-u,i.plus(s);var c=i.c.slice(),l=i.e,f=s.c,d=s.e;if(!c[0]||!f[0])return f[0]?s.s=-u:c[0]?s=new a(i):s.s=1,s;if(o=l-d){for((n=o<0)?(o=-o,t=c):(d=l,t=f),t.reverse(),u=o;u--;)t.push(0);t.reverse()}else for(e=((n=c.length<f.length)?c:f).length,o=u=0;u<e;u++)if(c[u]!=f[u]){n=c[u]<f[u];break}if(n&&(t=c,c=f,f=t,s.s=-s.s),(u=(e=f.length)-(r=c.length))>0)for(;u--;)c[r++]=0;for(u=r;e>o;){if(c[--e]<f[e]){for(r=e;r&&!c[--r];)c[r]=9;--c[r],c[e]+=10}c[e]-=f[e]}for(;c[--u]===0;)c.pop();for(;c[0]===0;)c.shift(),--d;return c[0]||(s.s=1,c=[d=0]),s.c=c,s.e=d,s};O.mod=function(s){var r,e=this,t=e.constructor,n=e.s,i=(s=new t(s)).s;if(!s.c[0])throw Error(Nr);return e.s=s.s=1,r=s.cmp(e)==1,e.s=n,s.s=i,r?new t(e):(n=t.DP,i=t.RM,t.DP=t.RM=0,e=e.div(s),t.DP=n,t.RM=i,this.minus(e.times(s)))};O.neg=function(){var s=new this.constructor(this);return s.s=-s.s,s};O.plus=O.add=function(s){var r,e,t,n=this,i=n.constructor;if(s=new i(s),n.s!=s.s)return s.s=-s.s,n.minus(s);var a=n.e,o=n.c,u=s.e,c=s.c;if(!o[0]||!c[0])return c[0]||(o[0]?s=new i(n):s.s=n.s),s;if(o=o.slice(),r=a-u){for(r>0?(u=a,t=c):(r=-r,t=o),t.reverse();r--;)t.push(0);t.reverse()}for(o.length-c.length<0&&(t=c,c=o,o=t),r=c.length,e=0;r;o[r]%=10)e=(o[--r]=o[r]+c[r]+e)/10|0;for(e&&(o.unshift(e),++u),r=o.length;o[--r]===0;)o.pop();return s.c=o,s.e=u,s};O.pow=function(s){var r=this,e=new r.constructor("1"),t=e,n=s<0;if(s!==~~s||s<-Yt||s>Yt)throw Error(Ne+"exponent");for(n&&(s=-s);s&1&&(t=t.times(r)),s>>=1,!!s;)r=r.times(r);return n?e.div(t):t};O.prec=function(s,r){if(s!==~~s||s<1||s>pe)throw Error(Ne+"precision");return Ae(new this.constructor(this),s,r)};O.round=function(s,r){if(s===Z)s=0;else if(s!==~~s||s<-pe||s>pe)throw Error(ct);return Ae(new this.constructor(this),s+this.e+1,r)};O.sqrt=function(){var s,r,e,t=this,n=t.constructor,i=t.s,a=t.e,o=new n("0.5");if(!t.c[0])return new n(t);if(i<0)throw Error(ve+"No square root");i=Math.sqrt(t+""),i===0||i===1/0?(r=t.c.join(""),r.length+a&1||(r+="0"),i=Math.sqrt(r),a=((a+1)/2|0)-(a<0||a&1),s=new n((i==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+a)):s=new n(i+""),a=s.e+(n.DP+=4);do e=s,s=o.times(e.plus(t.div(e)));while(e.c.slice(0,a).join("")!==s.c.slice(0,a).join(""));return Ae(s,(n.DP-=4)+s.e+1,n.RM)};O.times=O.mul=function(s){var r,e=this,t=e.constructor,n=e.c,i=(s=new t(s)).c,a=n.length,o=i.length,u=e.e,c=s.e;if(s.s=e.s==s.s?1:-1,!n[0]||!i[0])return s.c=[s.e=0],s;for(s.e=u+c,a<o&&(r=n,n=i,i=r,c=a,a=o,o=c),r=new Array(c=a+o);c--;)r[c]=0;for(u=o;u--;){for(o=0,c=a+u;c>u;)o=r[c]+i[u]*n[c-u-1]+o,r[c--]=o%10,o=o/10|0;r[c]=o}for(o?++s.e:r.shift(),u=r.length;!r[--u];)r.pop();return s.c=r,s};O.toExponential=function(s,r){var e=this,t=e.c[0];if(s!==Z){if(s!==~~s||s<0||s>pe)throw Error(ct);for(e=Ae(new e.constructor(e),++s,r);e.c.length<s;)e.c.push(0)}return Le(e,!0,!!t)};O.toFixed=function(s,r){var e=this,t=e.c[0];if(s!==Z){if(s!==~~s||s<0||s>pe)throw Error(ct);for(e=Ae(new e.constructor(e),s+e.e+1,r),s=s+e.e+1;e.c.length<s;)e.c.push(0)}return Le(e,!1,!!t)};O[Symbol.for("nodejs.util.inspect.custom")]=O.toJSON=O.toString=function(){var s=this,r=s.constructor;return Le(s,s.e<=r.NE||s.e>=r.PE,!!s.c[0])};O.toNumber=function(){var s=Number(Le(this,!0,!0));if(this.constructor.strict===!0&&!this.eq(s.toString()))throw Error(ve+"Imprecise conversion");return s};O.toPrecision=function(s,r){var e=this,t=e.constructor,n=e.c[0];if(s!==Z){if(s!==~~s||s<1||s>pe)throw Error(Ne+"precision");for(e=Ae(new t(e),s,r);e.c.length<s;)e.c.push(0)}return Le(e,s<=e.e||e.e<=t.NE||e.e>=t.PE,!!n)};O.valueOf=function(){var s=this,r=s.constructor;if(r.strict===!0)throw Error(ve+"valueOf disallowed");return Le(s,s.e<=r.NE||s.e>=r.PE,!0)};var B=Ar();function Rt(s){let r;switch(s){case R.EQUALS:r=R.EQUALS;break;case R.GREATER_THAN:r=R.LESS_THAN;break;case R.GREATER_THAN_OR_EQUAL:r=R.LESS_THAN_OR_EQUAL;break;case R.LESS_THAN:r=R.GREATER_THAN;break;case R.LESS_THAN_OR_EQUAL:r=R.GREATER_THAN_OR_EQUAL;break;case R.NOT_EQUAL:r=R.NOT_EQUAL;break}return r}function Vt(s,r){return B(s).times(r).toNumber()}function qt(s,r){const e=10**Math.floor(r);return Math.round(Vt(s,e))/e}function zt(s,r){const e=10**Math.floor(r);return Math.floor(Vt(s,e))/e}function Kt(s,r){const e=10**Math.floor(r);return Math.ceil(Vt(s,e))/e}function Xt(s,r){return s**r}class Rr extends le{isNull(){return!0}plus(r){return new p(0,!0).plus(r)}minus(r){return new p(0,!0).minus(r)}multiply(r){return new p(0,!0).multiply(r)}divided(r){return new p(0,!0).divided(r)}compare(r,e){return r.isString()?new k("").compare(r,e):r.isBoolean()?new $(!1).compare(r,e):new p(0,!0).compare(r,e)}concatenateFront(r){return r.isArray()?r.concatenateBack(new k("")):new k(this.concatenate(r.getValue(),X.FRONT))}concatenateBack(r){return r.isArray()?r.concatenateFront(new k("")):new k(this.concatenate(r.getValue(),X.BACK))}plusBy(r){return new p(0).plusBy(r)}minusBy(r){return new p(0).minusBy(r)}multiplyBy(r){return new p(0).multiplyBy(r)}dividedBy(r){return new p(0).dividedBy(r)}compareBy(r,e){return typeof r=="string"?new k("").compareBy(r,e):typeof r=="boolean"?new $(!1).compareBy(r,e):new p(0,!0).compareBy(r,e)}pow(r){return new p(0,!0).pow(r)}sqrt(){return new p(0,!0)}cbrt(){return new p(0,!0)}cos(){return new p(0,!0)}acos(){return new p(0,!0)}acosh(){return new p(0,!0)}sin(){return new p(0,!0)}asin(){return new p(0,!0)}asinh(){return new p(0,!0)}tan(){return new p(0,!0)}tanh(){return new p(0,!0)}atan(){return new p(0,!0)}atan2(r){return new p(0,!0).atan2(r)}atanh(){return new p(0,!0)}log(){return _.create(h.NUM)}log10(){return _.create(h.NUM)}exp(){return _.create(h.NUM)}abs(){return _.create(h.NUM)}round(r){return new p(0,!0).round(r)}floor(r){return new p(0,!0).floor(r)}ceil(r){return new p(0,!0).ceil(r)}}class $ extends le{constructor(e,t=!1){super(e);g(this,"_value",!1);if(t){this._value=e;return}if(typeof e=="boolean")this._value=e;else if(typeof e=="string"){const n=e.toLocaleUpperCase();n===Ce.TRUE?this._value=!0:n===Ce.FALSE&&(this._value=!1)}else e===1?this._value=!0:this._value=!1}getValue(){return this._value}isBoolean(){return!0}getNegative(){const e=this.getValue();let t=0;return e&&(t=1),new p(-t,!0)}getReciprocal(){return this.getValue()?new p(1,!0):_.create(h.DIV_BY_ZERO)}plus(e){return this._convertTonNumber().plus(e)}minus(e){return this._convertTonNumber().minus(e)}multiply(e){return this._convertTonNumber().multiply(e)}divided(e){return this._convertTonNumber().divided(e)}compare(e,t){return this._convertTonNumber().compare(e,t)}concatenateFront(e){return this._convertTonNumber().concatenateFront(e)}concatenateBack(e){return this._convertTonNumber().concatenateBack(e)}_convertTonNumber(){const e=this.getValue();let t=0;return e&&(t=1),new p(t,!0)}pow(e){return this._convertTonNumber().pow(e)}sqrt(){return this._convertTonNumber()}cbrt(){return this._convertTonNumber()}cos(){return this._convertTonNumber().cos()}acos(){return this._convertTonNumber().acos()}acosh(){return this._convertTonNumber().acosh()}sin(){return this._convertTonNumber().sin()}asin(){return this._convertTonNumber().asin()}asinh(){return this._convertTonNumber().asinh()}tan(){return this._convertTonNumber().tan()}tanh(){return this._convertTonNumber().tanh()}atan(){return this._convertTonNumber().atan()}atan2(e){return this._convertTonNumber().atan2(e)}atanh(){return this._convertTonNumber().atanh()}log(){return this._convertTonNumber().log()}log10(){return this._convertTonNumber().log10()}exp(){return this._convertTonNumber().exp()}abs(){return this._convertTonNumber().abs()}round(e){return this._convertTonNumber().round(e)}floor(e){return this._convertTonNumber().floor(e)}ceil(e){return this._convertTonNumber().ceil(e)}}class p extends le{constructor(e,t=!1){super(e);g(this,"_value",0);if(t){this._value=e;return}this._value=Number(e)}getValue(){return this._value}setValue(e){this._value=e}isNumber(){return!0}getNegative(){return new p(0).minus(this)}getReciprocal(){return new p(1).divided(this)}plus(e){if(e.isArray())return e.plus(this);const t=this.plusBy(e.getValue());return t.isError()?this:t}equalZero(){return this._value===0}minus(e){if(e.isArray()){const n=e.getNegative();return n.isError()?n:n.plus(this)}const t=this.minusBy(e.getValue());return t.isError()?this:t}multiply(e){return e.isArray()?e.multiply(this):this.multiplyBy(e.getValue())}divided(e){if(e.isArray()){const t=e.getReciprocal();return t.isError()?t:t.multiply(this)}return this.dividedBy(e.getValue())}concatenateFront(e){return e.isArray()?e.concatenateBack(this):new k(this.concatenate(e.getValue(),X.FRONT))}concatenateBack(e){return e.isArray()?e.concatenateFront(this):new k(this.concatenate(e.getValue(),X.BACK))}compare(e,t){return e.isArray()?e.compare(this,Rt(t)):this.compareBy(e.getValue(),t)}plusBy(e){const t=this.getValue();if(typeof e=="string")return _.create(h.VALUE);if(typeof e=="number"){if(!Number.isFinite(t)||!Number.isFinite(e))return _.create(h.NUM);const n=B(t).plus(e).toNumber();return Number.isFinite(n)?new p(n):_.create(h.NUM)}return typeof e=="boolean"?new p(B(t).plus(e?1:0).toNumber()):this}minusBy(e){const t=this.getValue();if(typeof e=="string")return _.create(h.VALUE);if(typeof e=="number"){if(!Number.isFinite(t)||!Number.isFinite(e))return _.create(h.NUM);const n=B(t).minus(e).toNumber();return Number.isFinite(n)?new p(n):_.create(h.NUM)}return typeof e=="boolean"?new p(B(t).minus(e?1:0).toNumber()):this}multiplyBy(e){const t=this.getValue();if(typeof e=="string")return _.create(h.VALUE);if(typeof e=="number"){if(!Number.isFinite(t)||!Number.isFinite(e))return _.create(h.NUM);const n=B(t).times(e).toNumber();return Number.isFinite(n)?new p(n):_.create(h.NUM)}return typeof e=="boolean"?new p(B(t).times(e?1:0).toNumber()):this}dividedBy(e){const t=this.getValue();if(typeof e=="string")return _.create(h.VALUE);if(typeof e=="number"){if(e===0)return _.create(h.DIV_BY_ZERO);if(!Number.isFinite(t)||!Number.isFinite(e))return _.create(h.NUM);const n=B(t).div(e).toNumber();return Number.isFinite(n)?new p(n):_.create(h.NUM)}return typeof e=="boolean"?e===!1?_.create(h.DIV_BY_ZERO):new p(B(t).div(1).toNumber()):this}compareBy(e,t){const n=this.getValue();let i=!1;if(typeof e=="string")switch(t){case R.EQUALS:case R.GREATER_THAN:case R.GREATER_THAN_OR_EQUAL:i=!1;break;case R.LESS_THAN:case R.LESS_THAN_OR_EQUAL:case R.NOT_EQUAL:i=!0;break}else if(typeof e=="number")if(!Number.isFinite(n)||!Number.isFinite(e))i=this._compareInfinity(n,e,t);else switch(t){case R.EQUALS:i=B(n).eq(e);break;case R.GREATER_THAN:i=B(n).gt(e);break;case R.GREATER_THAN_OR_EQUAL:i=B(n).gte(e);break;case R.LESS_THAN:i=B(n).lt(e);break;case R.LESS_THAN_OR_EQUAL:i=B(n).lte(e);break;case R.NOT_EQUAL:i=!B(n).eq(e);break}else if(typeof e=="boolean")switch(t){case R.EQUALS:case R.GREATER_THAN:case R.GREATER_THAN_OR_EQUAL:i=!1;break;case R.LESS_THAN:case R.LESS_THAN_OR_EQUAL:case R.NOT_EQUAL:i=!0;break}return new $(i)}pow(e){if(e.isArray())return e.powInverse(this);const t=this.getValue(),n=e.getValue();if(typeof n=="string")return _.create(h.VALUE);if(typeof n=="number"){if(!Number.isFinite(t)||!Number.isFinite(n))return _.create(h.NUM);const i=Xt(t,n);return Number.isFinite(i)?new p(i):_.create(h.NUM)}return typeof n=="boolean"?new p(Xt(t,n?1:0)):this}sqrt(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=B(e).sqrt().toNumber();return Number.isFinite(t)?new p(t):_.create(h.NUM)}cbrt(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.cbrt(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}cos(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.cos(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}acos(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.acos(e);return Number.isNaN(t)?_.create(h.NUM):new p(t)}acosh(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.acosh(e);return Number.isNaN(t)?_.create(h.NUM):new p(t)}sin(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.sin(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}asin(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.asin(e);return Number.isNaN(t)?_.create(h.NUM):new p(t)}asinh(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.asinh(e);return Number.isNaN(t)?_.create(h.NUM):new p(t)}tan(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.tan(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}tanh(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.tanh(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}atan(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.atan(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}atan2(e){if(e.isArray())return e.atan2Inverse(this);const t=this.getValue(),n=e.getValue();if(typeof n=="string")return _.create(h.VALUE);if(typeof n=="number"){if(!Number.isFinite(t)||!Number.isFinite(n))return _.create(h.NUM);const i=Math.atan2(t,n);return Number.isFinite(i)?new p(i):_.create(h.NUM)}return typeof n=="boolean"?new p(Math.atan2(t,n?1:0)):this}atanh(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.atanh(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}log(){const e=this.getValue();if(typeof e=="number"&&e<=0||!Number.isFinite(e))return _.create(h.NUM);const t=Math.log(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}log10(){const e=this.getValue();if(typeof e=="number"&&e<=0||!Number.isFinite(e))return _.create(h.NUM);const t=Math.log10(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}exp(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.exp(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}abs(){const e=this.getValue();if(!Number.isFinite(e))return _.create(h.NUM);const t=Math.abs(e);return Number.isFinite(t)?new p(t):_.create(h.NUM)}round(e){if(e.isArray())return e.roundInverse(this);const t=this.getValue(),n=e.getValue();if(typeof n=="string")return _.create(h.VALUE);if(typeof n=="number"){if(!Number.isFinite(t)||!Number.isFinite(n))return _.create(h.NUM);const i=qt(t,n);return Number.isFinite(i)?new p(i):_.create(h.NUM)}return typeof n=="boolean"?new p(qt(t,n?1:0)):this}floor(e){if(e.isArray())return e.floorInverse(this);const t=this.getValue(),n=e.getValue();if(typeof n=="string")return _.create(h.VALUE);if(typeof n=="number"){if(!Number.isFinite(t)||!Number.isFinite(n))return _.create(h.NUM);const i=zt(t,n);return Number.isFinite(i)?new p(i):_.create(h.NUM)}return typeof n=="boolean"?new p(zt(t,n?1:0)):this}ceil(e){if(e.isArray())return e.ceilInverse(this);const t=this.getValue(),n=e.getValue();if(typeof n=="string")return _.create(h.VALUE);if(typeof n=="number"){if(!Number.isFinite(t)||!Number.isFinite(n))return _.create(h.NUM);const i=Kt(t,n);return Number.isFinite(i)?new p(i):_.create(h.NUM)}return typeof n=="boolean"?new p(Kt(t,n?1:0)):this}_compareInfinity(e,t,n){let i=!1;switch(n){case R.EQUALS:i=e===t;break;case R.GREATER_THAN:i=e>t;break;case R.GREATER_THAN_OR_EQUAL:i=e>=t;break;case R.LESS_THAN:i=e<t;break;case R.LESS_THAN_OR_EQUAL:i=e<=t;break;case R.NOT_EQUAL:i=e!==t;break}return i}}class k extends le{constructor(e,t=!1){super(e);g(this,"_value");if(t){this._value=e;return}let n=e.toString();n.charAt(0)==='"'&&n.charAt(n.length-1)==='"'&&(n=n.slice(1,-1),n=n.replace(/""/g,'"')),this._value=n}getValue(){return this._value}isString(){return!0}concatenateFront(e){return e.isArray()?e.concatenateBack(this):new k(this.concatenate(e.getValue(),X.FRONT))}concatenateBack(e){return e.isArray()?e.concatenateFront(this):new k(this.concatenate(e.getValue(),X.BACK))}compare(e,t){return e.isArray()?e.compare(this,Rt(t)):this.compareBy(e.getValue(),t)}wildcard(e,t){return e.isArray()?e.wildcard(this,Rt(t)):this._checkWildcard(e.getValue(),t)}compareBy(e,t){const n=this.getValue();let i=!1;if(typeof e=="string")switch(t){case R.EQUALS:i=n===e;break;case R.GREATER_THAN:i=n>e;break;case R.GREATER_THAN_OR_EQUAL:i=n>=e;break;case R.LESS_THAN:i=n<e;break;case R.LESS_THAN_OR_EQUAL:i=n<=e;break;case R.NOT_EQUAL:i=n!==e;break}else if(typeof e=="number")switch(t){case R.EQUALS:case R.GREATER_THAN:case R.GREATER_THAN_OR_EQUAL:i=!0;break;case R.LESS_THAN:case R.LESS_THAN_OR_EQUAL:case R.NOT_EQUAL:i=!1;break}else if(typeof e=="boolean")switch(t){case R.EQUALS:case R.GREATER_THAN:case R.GREATER_THAN_OR_EQUAL:i=!1;break;case R.LESS_THAN:case R.LESS_THAN_OR_EQUAL:case R.NOT_EQUAL:i=!0;break}return new $(i)}_checkWildcard(e,t){const n=this.getValue().toLocaleLowerCase(),i=Jr(n,e,t);return new $(i)}}function cn(s){return""}function ln(s=[]){const r=[];for(let e=0;e<s.length;e++){const t=s[e];r[e]==null&&(r[e]=[]);for(let n=0;n<t.length;n++){const i=t[n];i.isError()?r[e][n]=i.getErrorType():r[e][n]=i.getValue()}}return r}class ne extends le{constructor(e){var r=(...Gi)=>(super(...Gi),g(this,"_value",[]),g(this,"_rowCount",-1),g(this,"_columnCount",-1),g(this,"_unitId",""),g(this,"_sheetId",""),g(this,"_currentRow",-1),g(this,"_currentColumn",-1),this);if(typeof e=="string")r(e);else{const t=cn();r(t)}this._value=this._formatValue(e)}dispose(){this._value.forEach(e=>{e.forEach(t=>{t.dispose()})}),this._value=[]}getRowCount(){return this._rowCount}setRowCount(e){this._rowCount=e}getColumnCount(){return this._columnCount}setColumnCount(e){this._columnCount=e}setCurrent(e,t){this._currentRow=e,this._currentColumn=t}setUnitId(e){this._unitId=e}getUnitId(){return this._unitId}setSheetId(e){this._sheetId=e}getSheetId(){return this._sheetId}getCurrentRow(){return this._currentRow}getCurrentColumn(){return this._currentColumn}getArrayValue(){return this._value}setArrayValue(e){this._value=e}isArray(){return!0}get(e,t){return this._value[e][t]}set(e,t,n){if(e>=this._rowCount||t>=this._columnCount)throw new Error("Exceeding array bounds.");this._value[e][t]=n}getRangePosition(){const t=this.getRowCount(),n=0,i=this.getColumnCount();return{startRow:0,endRow:t-1,startColumn:n,endColumn:i-1}}iterator(e){const{startRow:t,endRow:n,startColumn:i,endColumn:a}=this.getRangePosition(),o=this.getArrayValue();for(let u=t;u<=n;u++)for(let c=i;c<=a;c++)if(e(o[u][c],u,c)===!1)return}getFirstCell(){const{startRow:e,startColumn:t}=this.getRangePosition();return this.getArrayValue()[e][t]}pick(e){const t=e.getRowCount(),n=e.getColumnCount();if(t!==this._rowCount||t!==this._rowCount)return this._createNewArray([[new p(0)]],1,1);const i=[];i[0]=[];for(let a=0;a<t;a++)for(let o=0;o<n;o++){const u=e.get(a,o),c=this.get(a,o);u.isError()||u.getValue()===!0&&i[0].push(c)}return this._createNewArray(i,1,i[0].length)}flatten(){const e=[];e[0]=[];for(let t=0;t<this._rowCount;t++)for(let n=0;n<this._rowCount;n++){const i=this.get(t,n);e[0].push(i)}return this._createNewArray(e,1,e[0].length)}slice(e,t){let n=0,i=this._rowCount-1,a=1,o=0,u=this._columnCount-1,c=1;e!=null&&(n=e[0]||0,i=e[1]||this._rowCount-1,a=e[2]||1),t!=null&&(o=t[0]||0,u=t[1]||this._columnCount-1,c=t[2]||1);const l=[],f=this._value;let d=0,E=0;for(let A=n;A<=i;A+=a){E=0,l[d]==null&&(l[d]=[]);for(let C=o;C<=u;C+=c)l[d][E]=f[A][C],E++;d++}return this._createNewArray(l,l.length,l[0].length)}sum(){let e=new p(0);return this.iterator(t=>{if(t==null)return!0;if(t.isError())return e=t,!1;e=e.plus(t)}),e}max(){let e=new p(-1/0);return this.iterator(t=>{if(t==null)return!0;if(t.isError())return e=t,!1;if(t.isString()||t.isNull())return!0;e.isLessThan(t).getValue()&&(e=t)}),e}min(){let e=new p(1/0);return this.iterator(t=>{if(t==null)return!0;if(t.isError())return e=t,!1;if(t.isString()||t.isNull())return!0;e.isGreaterThan(t).getValue()&&(e=t)}),e}count(){let e=new p(0);return this.iterator(t=>{if(t==null||t.isError()||t.isString()||t.isNull())return!0;e=e.plusBy(1)}),e}countA(){let e=new p(0);return this.iterator(t=>{if(t==null||t.isNull())return!0;e=e.plusBy(1)}),e}countBlank(){let e=new p(0);return this.iterator(t=>{if(t!=null)return!0;e=e.plusBy(1)}),e}sortByRow(e){const t=this._transposeArray(this._value);t.sort(this._sort(e)),this._value=this._transposeArray(t)}sortByColumn(e){this._value.sort(this._sort(e))}transpose(){const e=this._transposeArray(this._value),t=this._rowCount,n=this._columnCount;return this._createNewArray(e,n,t)}getNegative(){return new ne("{0}").minus(this)}getReciprocal(){return new ne("{1}").divided(this)}plus(e){return this._batchOperator(e,1)}minus(e){return this._batchOperator(e,0)}multiply(e){return this._batchOperator(e,2)}divided(e){return this._batchOperator(e,3)}compare(e,t){return this._batchOperator(e,4,t)}wildcard(e,t){return this._batchOperator(e,8,t)}concatenateFront(e){return this._batchOperator(e,5)}concatenateBack(e){return this._batchOperator(e,6)}product(e,t){return this._batchOperator(e,7,t)}map(e){var a,o;const t=this._rowCount,n=this._columnCount,i=[];for(let u=0;u<t;u++){const c=[];for(let l=0;l<n;l++){const f=(o=(a=this._value)==null?void 0:a[u])==null?void 0:o[l];f?f.isError()?c[l]=f:c[l]=e(f,u,l):c[l]=_.create(h.VALUE)}i.push(c)}return this._createNewArray(i,t,n)}pow(e){return this._batchOperator(e,9)}powInverse(e){return this.map(t=>t.isError()?t:e.pow(t))}sqrt(){return this.map(e=>e.isError()?e:e.sqrt())}cbrt(){return this.map(e=>e.isError()?e:e.cbrt())}cos(){return this.map(e=>e.isError()?e:e.cos())}acos(){return this.map(e=>e.isError()?e:e.acos())}acosh(){return this.map(e=>e.isError()?e:e.acosh())}sin(){return this.map(e=>e.isError()?e:e.sin())}asin(){return this.map(e=>e.isError()?e:e.asin())}asinh(){return this.map(e=>e.isError()?e:e.asinh())}tan(){return this.map(e=>e.isError()?e:e.tan())}tanh(){return this.map(e=>e.isError()?e:e.tanh())}atan(){return this.map(e=>e.isError()?e:e.atan())}atanh(){return this.map(e=>e.isError()?e:e.atanh())}atan2(e){return this._batchOperator(e,13)}atan2Inverse(e){return this.map(t=>t.isError()?t:e.atan2(t))}mean(){const e=this.sum(),t=this.countA();return e.divided(t)}median(){const e=this.flatten(),t=e.getColumnCount();if(t<=1)return e.get(0,0);if(e.sortByRow(0),t%2===0){const n=e.get(0,t/2),i=e.get(0,t/2-1);return n.plus(i).divided(new p(2,!0))}return e.get(0,(t-1)/2)}var(){const e=this.mean(),t=[];this.iterator((f,d,E)=>{(f==null||f.isError()||f.isString())&&(f=new p(0));let A=f.minus(e).pow(new p(2,!0));A.isError()&&(A=new p(0)),t[d]==null&&(t[d]=[]),t[d][E]=A});const{_rowCount:n,_columnCount:i,_unitId:a,_sheetId:o,_currentRow:u,_currentColumn:c}=this;return new ne({calculateValueList:t,rowCount:n,columnCount:i,unitId:a,sheetId:o,row:u,column:c}).mean()}std(){const e=this.var();return e.isError()?e:e.sqrt()}log(){return this.map(e=>e.isError()?e:e.log())}log10(){return this.map(e=>e.isError()?e:e.log10())}exp(){return this.map(e=>e.isError()?e:e.exp())}abs(){return this.map(e=>e.isError()?e:e.abs())}round(e){return this._batchOperator(e,10)}roundInverse(e){return this.map(t=>t.isError()?t:e.round(t))}floor(e){return this._batchOperator(e,11)}floorInverse(e){return this.map(t=>t.isError()?t:e.floor(t))}ceil(e){return this._batchOperator(e,12)}ceilInverse(e){return this.map(t=>t.isError()?t:e.ceil(t))}toValue(){return ln(this._value)}_sort(e){const t=Wr();return(n,i)=>{const a=n[e],o=i[e];return a.isError()&&a.isError()?0:a.isError()?1:o.isError()?-1:t(a.getValue(),o.getValue())}}_transposeArray(e){const t=e.length,n=e[0].length,i=[];for(let a=0;a<n;a++){i[a]=[];for(let o=0;o<t;o++)i[a][o]=e[o][a]}return i}_batchOperator(e,t,n){const i=[];let a=this._rowCount,o=this._columnCount;if(e.isArray()){const c=e.getRowCount(),l=e.getColumnCount();if(a=Math.max(c,a),o=Math.max(l,o),c===1&&l===1){const f=e.getFirstCell();for(let d=0;d<o;d++)i.push(f)}else if(c===1&&this._columnCount>1){const f=e.getArrayValue();for(let d=0;d<o;d++)i.push(f[0][d])}else return this._batchOperatorArray(e,t,n)}else for(let c=0;c<o;c++)i.push(e);const u=[];for(let c=0;c<o;c++){const l=i[c];this._batchOperatorValue(l,c,u,t,n)}return this._createNewArray(u,a,o)}_batchOperatorValue(e,t,n,i,a){var E,A;const o=this._rowCount;let u=!1;const c=this.getUnitId(),l=this.getSheetId(),f=this.getCurrentRow(),d=this.getCurrentColumn();if(i===4&&(u=ge.canUseCache(c,l,t+d,f,f+o-1),u===!0)){if(a===R.EQUALS){const C=ge.getCellPositions(c,l,t+d,e.getValue());if(C!=null)for(let N=0;N<o;N++)n[N]==null&&(n[N]=[]),C.includes(N+f)?n[N][t]=new $(!0):n[N][t]=new $(!1)}else{const C=ge.getCellValuePositions(c,l,t+d);C!=null&&C.forEach((N,S)=>{let y;if(typeof S=="string"?y=new k(S):typeof S=="number"?y=new p(S):typeof S=="boolean"&&(y=new $(S)),y==null)return!0;if(y.compare(e,a))for(let b=0;b<o;b++)n[b]==null&&(n[b]=[]),N.includes(b+f)?n[b][t]=new $(!0):n[b][t]=new $(!1)})}return}ge.setContinueBuildingCache(c,l,t+d,f,f+o-1);for(let C=0;C<o;C++){const N=(A=(E=this._value)==null?void 0:E[C])==null?void 0:A[t];if(n[C]==null&&(n[C]=[]),N&&e)if(N.isError())n[C][t]=N;else if(e.isError())n[C][t]=_.create(h.VALUE);else switch(i){case 1:n[C][t]=N.plus(e);break;case 0:n[C][t]=N.minus(e);break;case 2:n[C][t]=N.multiply(e);break;case 3:n[C][t]=N.divided(e);break;case 4:a?n[C][t]=N.compare(e,a):n[C][t]=_.create(h.VALUE);break;case 5:n[C][t]=N.concatenateFront(e);break;case 6:n[C][t]=N.concatenateBack(e);break;case 7:a?n[C][t]=N.product(e,a):n[C][t]=_.create(h.VALUE);break;case 8:a?n[C][t]=N.wildcard(e,a):n[C][t]=_.create(h.VALUE);break;case 9:n[C][t]=N.pow(e);break;case 10:n[C][t]=N.round(e);break;case 11:n[C][t]=N.floor(e);break;case 13:n[C][t]=N.atan2(e);break;case 12:n[C][t]=N.ceil(e);break}else n[C][t]=_.create(h.NA);N!=null&&(N.isError()?ge.set(c,l,t+d,N.getErrorType(),C+f):ge.set(c,l,t+d,N.getValue(),C+f))}}_batchOperatorArray(e,t,n){var f,d,E,A,C,N,S,y,T,b,Q,se;let i=e.getRowCount(),a=e.getColumnCount();i<this._rowCount&&(i=this._rowCount),a<this._columnCount&&(a=this._columnCount);const o=[],u=e.getArrayValue(),c=this._checkArrayCalculateType(this),l=this._checkArrayCalculateType(e);for(let Y=0;Y<i;Y++){const I=[];for(let U=0;U<a;U++){let x;c===3?x=(d=(f=this._value)==null?void 0:f[0])==null?void 0:d[0]:c===1?x=(A=(E=this._value)==null?void 0:E[0])==null?void 0:A[U]:c===2?x=(N=(C=this._value)==null?void 0:C[Y])==null?void 0:N[0]:x=(y=(S=this._value)==null?void 0:S[Y])==null?void 0:y[U];let v;if(l===3?v=(T=u==null?void 0:u[0])==null?void 0:T[0]:l===1?v=(b=u==null?void 0:u[0])==null?void 0:b[U]:l===2?v=(Q=u==null?void 0:u[Y])==null?void 0:Q[0]:v=(se=u==null?void 0:u[Y])==null?void 0:se[U],x&&v)if(x.isError())I[U]=x;else if(v.isError())I[U]=v;else switch(t){case 1:I[U]=x.plus(v);break;case 0:I[U]=x.minus(v);break;case 2:I[U]=x.multiply(v);break;case 3:I[U]=x.divided(v);break;case 4:n?I[U]=x.compare(v,n):I[U]=_.create(h.VALUE);break;case 5:I[U]=x.concatenateFront(v);break;case 6:I[U]=x.concatenateBack(v);break;case 7:n?I[U]=x.product(v,n):I[U]=_.create(h.VALUE);break;case 8:n?I[U]=x.wildcard(v,n):I[U]=_.create(h.VALUE);break;case 9:I[U]=x.pow(v);break;case 10:I[U]=x.round(v);break;case 13:I[U]=x.atan2(v);break;case 11:I[U]=x.floor(v);break;case 12:I[U]=x.ceil(v);break}else I[U]=_.create(h.NA)}o.push(I)}return this._createNewArray(o,i,a)}_checkArrayCalculateType(e){return e.getRowCount()===1&&e.getColumnCount()===1?3:e.getRowCount()===1?1:e.getColumnCount()===1?2:0}_formatValue(e){if(typeof e!="string")return e=e,this._rowCount=e.rowCount,this._columnCount=e.columnCount,this._unitId=e.unitId,this._sheetId=e.sheetId,this._currentRow=e.row,this._currentColumn=e.column,e.calculateValueList;e=e.slice(1,-1);const t=e.split(";"),n=t.length,i=[];let a=0;for(let o=0;o<n;o++){const c=t[o].split(","),l=c.length;a<l&&(a=l);const f=[];for(let d=0;d<l;d++){const E=c[d].trim();f.push(ye.create(E))}i.push(f)}return this._rowCount=n,this._columnCount=a,i}_createNewArray(e,t,n){const i={calculateValueList:e,rowCount:t,columnCount:n,unitId:this.getUnitId(),sheetId:this.getSheetId(),row:this._currentRow,column:this._currentColumn};return new ne(i)}}class ye{static create(r){if(typeof r=="boolean")return new $(r,!0);if(typeof r=="string"){const e=r.toLocaleUpperCase();return e===Ce.TRUE||e===Ce.FALSE?new $(e):m.isRealNum(r)?new p(r):new RegExp(Qr,"g").test(r)?new ne(r):new k(r)}return typeof r=="number"?Number.isFinite(r)?new p(r,!0):_.create(h.NUM):_.create(h.NA)}}const hn=1e5,St=new nt(hn);class we extends ut{constructor(e){super();g(this,"_forcedSheetId","");g(this,"_forcedSheetName","");g(this,"_defaultSheetId","");g(this,"_rangeData",{startColumn:-1,startRow:-1,endRow:-1,endColumn:-1});g(this,"_unitData",{});g(this,"_rowCount",0);g(this,"_columnCount",0);g(this,"_defaultUnitId","");g(this,"_forcedUnitId","");g(this,"_runtimeData",{});g(this,"_arrayFormulaCellData",{});g(this,"_runtimeArrayFormulaCellData",{});g(this,"_runtimeFeatureCellData",{});g(this,"_refOffsetX",0);g(this,"_refOffsetY",0);this._token=e}dispose(){this._unitData={},this._runtimeData={}}setRefOffset(e=0,t=0){this._refOffsetX=e,this._refOffsetY=t}getRefOffset(){return{x:this._refOffsetX,y:this._refOffsetY}}getRangePosition(){let e=this._rangeData.startRow,t=this._rangeData.endRow,n=this._rangeData.startColumn,i=this._rangeData.endColumn;return e===-1&&(e=0),n===-1&&(n=0),t===-1&&(t=this._rowCount-1),i===-1&&(i=this._columnCount-1),{startRow:e,endRow:t,startColumn:n,endColumn:i}}isReferenceObject(){return!0}iterator(e){const{startRow:t,endRow:n,startColumn:i,endColumn:a}=this.getRangePosition();if(this._checkIfWorksheetMiss())return e(new _(h.VALUE),t,i);for(let o=t;o<=n;o++)for(let u=i;u<=a;u++){const c=o+this._refOffsetY,l=u+this._refOffsetX;if(c<0||l<0)return e(new _(h.REF),o,u);const f=this.getCellData(c,l);let d=!1;if(f==null||m.isNullCell(f)){d=e(null,o,u);continue}const E=this.getCellValueObject(f);if(d=e(E,o,u),d===!1)return}}getFirstCell(){const{startRow:e,startColumn:t}=this.getRangePosition(),n=this.getCellData(e+this._refOffsetY,t+this._refOffsetX);return n?this.getCellValueObject(n):new p(0,!0)}getRangeData(){return this._rangeData}setRangeData(e){this._rangeData=e}getUnitId(){return this._forcedUnitId&&this._forcedUnitId.length>0?this._forcedUnitId:this._defaultUnitId}getSheetId(){return this._forcedSheetId&&this._forcedSheetId.length>0?this._forcedSheetId:this._defaultSheetId}setForcedUnitIdDirect(e){e.length>0&&(this._forcedUnitId=e)}getForcedUnitId(){return this._forcedUnitId}setForcedSheetId(e){var t;this._forcedSheetId=(t=e[this.getUnitId()])==null?void 0:t[this._forcedSheetName]}setForcedSheetIdDirect(e){this._forcedSheetId=e}getForcedSheetId(){return this._forcedSheetId}setForcedSheetName(e){e.length>0&&(this._forcedSheetName=e)}getForcedSheetName(){return this._forcedSheetName}setDefaultSheetId(e){this._defaultSheetId=e}getDefaultSheetId(){return this._defaultSheetId}setDefaultUnitId(e){this._defaultUnitId=e}getDefaultUnitId(){return this._defaultUnitId}getUnitData(){return this._unitData}setUnitData(e){this._unitData=e}getRuntimeData(){return this._runtimeData}setRuntimeData(e){this._runtimeData=e}getArrayFormulaCellData(){return this._arrayFormulaCellData}setArrayFormulaCellData(e){this._arrayFormulaCellData=e}getRuntimeArrayFormulaCellData(){return this._runtimeArrayFormulaCellData}setRuntimeArrayFormulaCellData(e){this._runtimeArrayFormulaCellData=e}getRuntimeFeatureCellData(){return this._runtimeFeatureCellData}setRuntimeFeatureCellData(e){this._runtimeFeatureCellData=e}getRowCount(){return this.getCurrentActiveSheetData().rowCount}getColumnCount(){return this.getCurrentActiveSheetData().columnCount}isCell(){return!1}isColumn(){return!1}isRow(){return!1}isRange(){return!1}isTable(){return!1}unionBy(e){return _.create(h.REF)}unionRange(e,t){return{startRow:-1,startColumn:-1,endRow:-1,endColumn:-1}}getCellValueObject(e){const t=e.v||0;return Ir.has(t)?_.create(t):e.t===m.CellValueType.NUMBER?new p(t):e.t===m.CellValueType.STRING||e.t===m.CellValueType.FORCE_STRING?new k(t):e.t===m.CellValueType.BOOLEAN?new $(t):ye.create(t)}getCellByRow(e){return this.getCellByPosition(e)}getCellByColumn(e){return this.getCellByPosition(void 0,e)}getCurrentActiveSheetData(){return this._unitData[this.getUnitId()][this.getSheetId()]}getCurrentRuntimeSheetData(){var e,t;return(t=(e=this._runtimeData)==null?void 0:e[this.getUnitId()])==null?void 0:t[this.getSheetId()]}getCurrentActiveArrayFormulaCellData(){var e,t;return(t=(e=this._arrayFormulaCellData)==null?void 0:e[this.getUnitId()])==null?void 0:t[this.getSheetId()]}getCurrentRuntimeActiveArrayFormulaCellData(){var e,t;return(t=(e=this._runtimeArrayFormulaCellData)==null?void 0:e[this.getUnitId()])==null?void 0:t[this.getSheetId()]}getCellData(e,t){const n=this.getCurrentActiveSheetData(),i=this.getCurrentRuntimeSheetData(),a=this.getCurrentActiveArrayFormulaCellData(),o=this.getCurrentRuntimeActiveArrayFormulaCellData();return(i==null?void 0:i.getValue(e,t))||(o==null?void 0:o.getValue(e,t))||this.getRuntimeFeatureCellValue(e,t)||(a==null?void 0:a.getValue(e,t))||n.cellData.getValue(e,t)}getRuntimeFeatureCellValue(e,t){var i;const n=Object.keys(this._runtimeFeatureCellData);for(const a of n){const o=this._runtimeFeatureCellData[a],u=(i=o==null?void 0:o[this.getUnitId()])==null?void 0:i[this.getSheetId()];if(u==null)continue;const c=u.getValue(e,t);if(c!=null)return c}}getCellByPosition(e,t){e||(e=this._rangeData.startRow),t||(t=this._rangeData.startColumn);const n=this.getCellData(e,t);return n?this.getCellValueObject(n):_.create(h.VALUE)}toArrayValueObject(){var E;const{startRow:e,endRow:t,startColumn:n,endColumn:i}=this.getRangePosition(),a=`${this.getUnitId()}_${this.getSheetId()}_${e+this._refOffsetY}_${t+this._refOffsetY}_${n+this._refOffsetX}_${i+this._refOffsetX}`,o=St.get(a);if(o)return o;const u=t-e+1,c=i-n+1,l=new Array(u);this.iterator((A,C,N)=>{const S=C-e,y=N-n;l[S]||(l[S]=new Array(c)),A==null&&(A=new Rr(0)),l[S][y]=A});const f={calculateValueList:l,rowCount:l.length,columnCount:((E=l[0])==null?void 0:E.length)||0,unitId:this.getUnitId(),sheetId:this.getSheetId(),row:e,column:n},d=new ne(f);return St.set(a,d),d}toUnitRange(){return{range:this._rangeData,sheetId:this.getSheetId(),unitId:this.getUnitId()}}_checkIfWorksheetMiss(){return(this._forcedSheetId==null||this._forcedSheetId.length===0)&&this._forcedSheetName.length>0}}class fn extends ut{constructor(r){super(),this._promise=r}isAsyncObject(){return!0}async getValue(){return this._promise}}class _n extends ut{constructor(r){super(),this._promiseList=r}isAsyncArrayObject(){return!0}async getValue(){var t;const r=[];for(let n=0;n<this._promiseList.length;n++){const i=this._promiseList[n];r[n]==null&&(r[n]=[]);for(let a=0;a<i.length;a++){const o=i[a];o.isAsyncObject()?r[n][a]=await o.getValue():r[n][a]=o}}const e={calculateValueList:r,rowCount:r.length,columnCount:((t=r[0])==null?void 0:t.length)||0,unitId:"",sheetId:"",row:0,column:0};return new ne(e)}}class Sr extends we{constructor(r,e,t){super(""),this.setRangeData(r),e&&this.setForcedSheetIdDirect(e),t&&this.setForcedUnitIdDirect(t)}isRange(){return!0}}var Bt=(s=>(s.MAKEARRAY="MAKEARRAY",s))(Bt||{});class M extends m.Disposable{constructor(r){super(),this._name=r}get name(){return this._name}isAsync(){return!1}isAddress(){return!1}calculate(...r){return _.create(h.VALUE)}checkArrayType(r){return r.isReferenceObject()||r.isValueObject()&&r.isArray()}}var lt=(s=>(s.CONCATENATE="CONCATENATE",s))(lt||{}),dn=(s=>{})(),mn=(s=>{})(),gn=(s=>{})(),Cn=(s=>{})(),pn=(s=>{})(),En=(s=>{})(),Nn=(s=>{})(),ze=(s=>(s.INDIRECT="INDIRECT",s.OFFSET="OFFSET",s))(ze||{}),K=(s=>(s.ABS="ABS",s.ACOS="ACOS",s.ACOSH="ACOSH",s.ACOT="ACOT",s.SUM="SUM",s.SUMIF="SUMIF",s.SUMIFS="SUMIFS",s.POWER="POWER",s))(K||{}),ie=(s=>(s.AVERAGE="AVERAGE",s.COUNT="COUNT",s.MAX="MAX",s.MIN="MIN",s.COUNTA="COUNTA",s))(ie||{}),An=(s=>{})(),Rn=(s=>{})(),Sn=(s=>{})();class yn extends m.Disposable{constructor(){super(...arguments);g(this,"_definedNameMap",new Map)}dispose(){this._definedNameMap.clear()}registerDefinedName(e,t,n){var a;this._definedNameMap.get(e)==null&&this._definedNameMap.set(e,new Map),(a=this._definedNameMap.get(e))==null||a.set(t,n)}removeDefinedName(e,t){var n;(n=this._definedNameMap.get(e))==null||n.delete(t)}getDefinedNameMap(e){return this._definedNameMap.get(e)}getValue(e,t){var n;return(n=this._definedNameMap.get(e))==null?void 0:n.get(t)}hasDefinedName(e){var n;return(((n=this._definedNameMap.get(e))==null?void 0:n.size)||0)!==0}}const ht=D.createIdentifier("univer.formula.defined-names.service");var bn=Object.defineProperty,Dn=Object.getOwnPropertyDescriptor,Fn=(s,r,e,t)=>{for(var n=t>1?void 0:t?Dn(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&bn(r,e,n),n},Ln=(s,r)=>(e,t)=>r(e,t,s);let yt=class extends m.Disposable{constructor(r){super();g(this,"_unitData",{});g(this,"_arrayFormulaCellData",{});g(this,"_formulaData",{});g(this,"_sheetNameMap",{});g(this,"_forceCalculate",!1);g(this,"_dirtyRanges",[]);g(this,"_dirtyNameMap",{});g(this,"_dirtyUnitFeatureMap",{});g(this,"_excludedCell");this._currentUniverService=r}dispose(){this._unitData={},this._formulaData={},this._arrayFormulaCellData={},this._sheetNameMap={},this._dirtyRanges=[],this._dirtyNameMap={},this._dirtyUnitFeatureMap={},this._excludedCell={}}getExcludedRange(){return this._excludedCell}getUnitData(){return this._unitData}getFormulaData(){return this._formulaData}getArrayFormulaCellData(){return this._arrayFormulaCellData}getSheetNameMap(){return this._sheetNameMap}isForceCalculate(){return this._forceCalculate}getDirtyRanges(){return this._dirtyRanges}getDirtyNameMap(){return this._dirtyNameMap}getDirtyUnitFeatureMap(){return this._dirtyUnitFeatureMap}load(r){const{allUnitData:e,unitSheetNameMap:t}=this._loadSheetData();this._unitData=e,this._formulaData=r.formulaData,this._arrayFormulaCellData=fr(r.arrayFormulaCellData),this._sheetNameMap=t,this._forceCalculate=r.forceCalculate,this._dirtyRanges=r.dirtyRanges,this._dirtyNameMap=r.dirtyNameMap,this._dirtyUnitFeatureMap=r.dirtyUnitFeatureMap,this._excludedCell=r.excludedCell}loadDirtyRangesAndExcludedCell(r,e){this._dirtyRanges=r,this._excludedCell=e}registerUnitData(r){this._unitData=r}registerFormulaData(r){this._formulaData=r}registerSheetNameMap(r){this._sheetNameMap=r}_loadSheetData(){const r=this._currentUniverService.getAllUniverSheetsInstance(),e={},t={};for(const n of r){const i=n.getUnitId(),a=n.getSheets(),o={},u={};for(const c of a){const l=c.getSheetId(),f=c.getConfig();o[l]={cellData:new m.ObjectMatrix(f.cellData),rowCount:f.rowCount,columnCount:f.columnCount},u[c.getName()]=c.getSheetId()}e[i]=o,t[i]=u}return{allUnitData:e,unitSheetNameMap:t}}};yt=Fn([Ln(0,m.IUniverInstanceService)],yt);const Te=D.createIdentifier("univer.formula.current-data.service");var wn=Object.defineProperty,Tn=Object.getOwnPropertyDescriptor,On=(s,r,e,t)=>{for(var n=t>1?void 0:t?Tn(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&wn(r,e,n),n},Un=(s,r)=>(e,t)=>r(e,t,s),W=(s=>(s[s.IDLE=0]="IDLE",s[s.START_DEPENDENCY=1]="START_DEPENDENCY",s[s.START_CALCULATION=2]="START_CALCULATION",s[s.CURRENTLY_CALCULATING=3]="CURRENTLY_CALCULATING",s[s.START_DEPENDENCY_ARRAY_FORMULA=4]="START_DEPENDENCY_ARRAY_FORMULA",s[s.START_CALCULATION_ARRAY_FORMULA=5]="START_CALCULATION_ARRAY_FORMULA",s[s.CURRENTLY_CALCULATING_ARRAY_FORMULA=6]="CURRENTLY_CALCULATING_ARRAY_FORMULA",s[s.CALCULATION_COMPLETED=7]="CALCULATION_COMPLETED",s))(W||{}),Re=(s=>(s[s.INITIAL=0]="INITIAL",s[s.STOP_EXECUTION=1]="STOP_EXECUTION",s[s.NOT_EXECUTED=2]="NOT_EXECUTED",s[s.SUCCESS=3]="SUCCESS",s))(Re||{});let bt=class extends m.Disposable{constructor(r){super();g(this,"_formulaExecuteStage",0);g(this,"_stopState",!1);g(this,"_currentRow",0);g(this,"_currentColumn",0);g(this,"_currentSubComponentId","");g(this,"_currentUnitId","");g(this,"_runtimeData",{});g(this,"_runtimeOtherData",{});g(this,"_unitArrayFormulaRange",{});g(this,"_runtimeArrayFormulaCellData",{});g(this,"_runtimeClearArrayFormulaCellData",{});g(this,"_runtimeFeatureRange",{});g(this,"_runtimeFeatureCellData",{});g(this,"_functionsExecutedState",0);g(this,"_functionDefinitionPrivacyVar",new Map);g(this,"_totalFormulasToCalculate",0);g(this,"_completedFormulasCount",0);g(this,"_totalArrayFormulasToCalculate",0);g(this,"_completedArrayFormulasCount",0);g(this,"_isCycleDependency",!1);this._currentConfigService=r}get currentRow(){return this._currentRow}get currentColumn(){return this._currentColumn}get currentSubComponentId(){return this._currentSubComponentId}get currentUnitId(){return this._currentUnitId}dispose(){this.reset(),this._runtimeFeatureCellData={},this._runtimeFeatureRange={}}enableCycleDependency(){this._isCycleDependency=!0}disableCycleDependency(){this._isCycleDependency=!1}isCycleDependency(){return this._isCycleDependency}setTotalArrayFormulasToCalculate(r){this._totalArrayFormulasToCalculate=r}getTotalArrayFormulasToCalculate(){return this._totalArrayFormulasToCalculate}setCompletedArrayFormulasCount(r){this._completedArrayFormulasCount=r}getCompletedArrayFormulasCount(){return this._completedArrayFormulasCount}setTotalFormulasToCalculate(r){this._totalFormulasToCalculate=r}getTotalFormulasToCalculate(){return this._totalFormulasToCalculate}setCompletedFormulasCount(r){this._completedFormulasCount=r}getCompletedFormulasCount(){return this._completedFormulasCount}markedAsSuccessfullyExecuted(){this._functionsExecutedState=3}markedAsNoFunctionsExecuted(){this._functionsExecutedState=2}markedAsStopFunctionsExecuted(){this._functionsExecutedState=1}markedAsInitialFunctionsExecuted(){this._functionsExecutedState=0}stopExecution(){this._stopState=!0,this.setFormulaExecuteStage(0)}isStopExecution(){return this._stopState}setFormulaExecuteStage(r){this._formulaExecuteStage=r}getFormulaExecuteStage(){return this._formulaExecuteStage}reset(){this._formulaExecuteStage=0,this._runtimeData={},this._runtimeOtherData={},this._unitArrayFormulaRange={},this._runtimeArrayFormulaCellData={},this._runtimeClearArrayFormulaCellData={},this._functionDefinitionPrivacyVar.clear(),this.markedAsInitialFunctionsExecuted(),this._isCycleDependency=!1,this._totalFormulasToCalculate=0,this._completedFormulasCount=0}setCurrent(r,e,t,n){this._currentRow=r,this._currentColumn=e,this._currentSubComponentId=t,this._currentUnitId=n}clearFunctionDefinitionPrivacyVar(){this._functionDefinitionPrivacyVar.clear()}registerFunctionDefinitionPrivacyVar(r,e){this._functionDefinitionPrivacyVar.set(r,e)}getFunctionDefinitionPrivacyVar(r){return this._functionDefinitionPrivacyVar.get(r)}setRuntimeOtherData(r,e){const t=this._currentSubComponentId,n=this._currentUnitId;this._runtimeOtherData[n]===void 0&&(this._runtimeOtherData[n]={});const i=this._runtimeOtherData[n];i[t]===void 0&&(i[t]={});const a=i[t];a[r]=this._objectValueToCellValue(e)}setRuntimeData(r){const e=this._currentRow,t=this._currentColumn,n=this._currentSubComponentId,i=this._currentUnitId;this._runtimeData[i]==null&&(this._runtimeData[i]={});const a=this._runtimeData[i];a[n]==null&&(a[n]=new m.ObjectMatrix),this._unitArrayFormulaRange[i]==null&&(this._unitArrayFormulaRange[i]={});const o=this._unitArrayFormulaRange[i];let u=new m.ObjectMatrix;o[n]||(u=new m.ObjectMatrix(o[n])),this._runtimeArrayFormulaCellData[i]===void 0&&(this._runtimeArrayFormulaCellData[i]={});const c=this._runtimeArrayFormulaCellData[i];c[n]==null&&(c[n]=new m.ObjectMatrix),this._runtimeClearArrayFormulaCellData[i]===void 0&&(this._runtimeClearArrayFormulaCellData[i]={});const l=this._runtimeClearArrayFormulaCellData[i];l[n]==null&&(l[n]=new m.ObjectMatrix);const f=a[n],d=c[n],E=l[n];if(r.isReferenceObject()||r.isValueObject()&&r.isArray()){const A=r,{startRow:C,startColumn:N,endRow:S,endColumn:y}=A.getRangePosition();if(C===S&&N===y){const b=this._objectValueToCellValue(A.getFirstCell());f.setValue(e,t,b),E.setValue(e,t,b);return}const T={startRow:e,startColumn:t,endRow:S-C+e,endColumn:y-N+t};if(this._checkIfArrayFormulaRangeHasData(i,n,e,t,T)){const b=this._objectValueToCellValue(new _(h.SPILL));f.setValue(e,t,b),E.setValue(e,t,b)}else{const b=new _(h.SPILL);A.iterator((Q,se,Y)=>{const I=this._objectValueToCellValue(Q);if(se===C&&Y===N){if(Q!=null&&Q.isError()&&Q.isEqualType(b))return E.setValue(e,t,{}),f.setValue(e,t,{...this._objectValueToCellValue(b)}),!1;f.setValue(e,t,{...I})}d.setValue(se-C+e,Y-N+t,I)}),u.setValue(e,t,T),o[n]=u.getData()}}else{const A=this._objectValueToCellValue(r);f.setValue(e,t,A),E.setValue(e,t,A)}}getUnitData(){return this._runtimeData}getUnitArrayFormula(){return this._unitArrayFormulaRange}getRuntimeOtherData(){return this._runtimeOtherData}getRuntimeArrayFormulaCellData(){return this._runtimeArrayFormulaCellData}getRuntimeClearArrayFormulaCellData(){return this._runtimeClearArrayFormulaCellData}getRuntimeFeatureRange(){return this._runtimeFeatureRange}setRuntimeFeatureRange(r,e){this._runtimeFeatureRange[r]=e}getRuntimeFeatureCellData(){return this._runtimeFeatureCellData}setRuntimeFeatureCellData(r,e){this._runtimeFeatureCellData[r]=e}getAllRuntimeData(){return{unitData:this.getUnitData(),arrayFormulaRange:this.getUnitArrayFormula(),unitOtherData:this.getRuntimeOtherData(),functionsExecutedState:this._functionsExecutedState,arrayFormulaCellData:this.getRuntimeArrayFormulaCellData(),clearArrayFormulaCellData:this.getRuntimeClearArrayFormulaCellData(),runtimeFeatureRange:this.getRuntimeFeatureRange(),runtimeFeatureCellData:this.getRuntimeFeatureCellData()}}getRuntimeState(){return{totalFormulasToCalculate:this.getTotalFormulasToCalculate(),completedFormulasCount:this.getCompletedFormulasCount(),totalArrayFormulasToCalculate:this.getTotalArrayFormulasToCalculate(),completedArrayFormulasCount:this.getCompletedArrayFormulasCount(),stage:this.getFormulaExecuteStage()}}_objectValueToCellValue(r){if(r==null)return{v:0,t:m.CellValueType.NUMBER};if(r.isError())return{v:r.getErrorType(),t:m.CellValueType.STRING};if(r.isValueObject()){const e=r,t=e.getValue();return e.isNumber()?{v:t,t:m.CellValueType.NUMBER}:e.isBoolean()?{v:t,t:m.CellValueType.BOOLEAN}:{v:t,t:m.CellValueType.STRING}}}_checkIfArrayFormulaRangeHasData(r,e,t,n,i){var f,d,E,A,C,N;const{startRow:a,startColumn:o,endRow:u,endColumn:c}=i,l=this._currentConfigService.getUnitData();for(let S=a;S<=u;S++)for(let y=o;y<=c;y++){if(S===t&&n===y)continue;const T=(E=(d=(f=this._runtimeData)==null?void 0:f[r])==null?void 0:d[e])==null?void 0:E.getValue(S,y),b=(N=(C=(A=l==null?void 0:l[r])==null?void 0:A[e])==null?void 0:C.cellData)==null?void 0:N.getValue(S,y);if((!m.isNullCell(T)||!m.isNullCell(b))&&this._isInDirtyRange(r,e,S,y))return!0}return!1}_isInDirtyRange(r,e,t,n){const i=this._currentConfigService.getDirtyRanges();return cr(i,r,e,t,n)}};bt=On([Un(0,Te)],bt);const J=D.createIdentifier("univer.formula.runtime.service");var In=Object.defineProperty,Mn=Object.getOwnPropertyDescriptor,xn=(s,r,e,t)=>{for(var n=t>1?void 0:t?Mn(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&In(r,e,n),n},gt=(s,r)=>(e,t)=>r(e,t,s);let Ee=class extends m.Disposable{constructor(s,r,e){super(),this._definedNamesService=s,this._runtimeService=r,this._lexerTreeBuilder=e}treeBuilder(s,r=!0){return this._lexerTreeBuilder.treeBuilder(s,r,this._injectDefinedName.bind(this))}_injectDefinedName(s){var i;const r=this._runtimeService.currentUnitId;if(!this._definedNamesService.hasDefinedName(r))return{sequenceString:"",hasDefinedName:!1};const e=this._lexerTreeBuilder.getSequenceNode(s);let t="",n=!1;for(let a=0,o=e.length;a<o;a++){const u=e[a];if(typeof u=="string"){t+=u;continue}const{nodeType:c,token:l}=u;if(c===q.REFERENCE||c===q.FUNCTION){const f=(i=this._definedNamesService.getDefinedNameMap(r))==null?void 0:i.get(l);f?(t+=f,n=!0):t+=l}else t+=l}return{sequenceString:t,hasDefinedName:n}}};Ee=xn([gt(0,ht),gt(1,J),gt(2,D.Inject(it))],Ee);var L=(s=>(s.REFERENCE="ReferenceNode",s.VALUE="ValueNode",s.OPERATOR="OperatorNode",s.FUNCTION="FunctionNode",s.LAMBDA="LambdaNode",s.LAMBDA_PARAMETER="LambdaNodeParameter",s.ERROR="ErrorNode",s.BASE="Base",s.ROOT="Root",s.UNION="UnionNode",s.PREFIX="PrefixNode",s.SUFFIX="SuffixNode",s.NULL="NullNode",s))(L||{});const ee=new Map([["ReferenceNode",7],["ValueNode",9],["OperatorNode",8],["FunctionNode",6],["LambdaNode",1],["LambdaNodeParameter",2],["Root",10],["UnionNode",3],["PrefixNode",4],["SuffixNode",5]]);class H extends m.Disposable{constructor(e){super();g(this,"_children",[]);g(this,"_parent");g(this,"_valueObject");g(this,"_calculateState",!1);g(this,"_async",!1);g(this,"_address",!1);g(this,"_refOffsetX",0);g(this,"_refOffsetY",0);this._token=e}dispose(){var e;this._children.forEach(t=>{t.dispose()}),(e=this._valueObject)==null||e.dispose(),this._parent=null}get nodeType(){return L.BASE}isAsync(){return this._async}isAddress(){return this._address}setAsync(){this._async=!0}setAddress(){this._address=!0}getParent(){return this._parent}setParent(e){this._parent=e,e.addChildren(this)}getChildren(){return this._children}addChildren(...e){this._children.push(...e)}getToken(){return this._token}setValue(e){this._valueObject=e}getValue(){return this._valueObject}isCalculated(){return this._calculateState}setCalculated(){this._calculateState=!0}execute(){}setNotEmpty(e=!0){}setRefOffset(e=0,t=0){this._refOffsetX=e,this._refOffsetY=t}getRefOffset(){return{x:this._refOffsetX,y:this._refOffsetY}}async executeAsync(){return Promise.resolve(ae.SUCCESS)}serialize(){const e=this.getToken(),t=this.getChildren(),n=[],i=t.length;for(let o=0;o<i;o++){const u=t[o];n.push(u.serialize())}const a={token:e,nodeType:this.nodeType};return i>0&&(a.children=n),a}}class V extends H{constructor(e){super(e);g(this,"_errorValueObject");this._errorValueObject=_.create(e)}get nodeType(){return L.ERROR}static create(e){return new V(e)}getValue(){return this._errorValueObject}}const te=100;class re extends m.Disposable{get zIndex(){return 0}create(r,e,t){let n;return r instanceof F?n=r.getToken():n=r,new H(n)}checkAndCreateNodeType(r){}}class Dt extends H{get nodeType(){return L.ROOT}execute(){const e=this.getChildren()[0];this.setValue(e.getValue())}}class yr extends re{get zIndex(){return ee.get(L.ROOT)||te}checkAndCreateNodeType(r){if(!(r instanceof F))return;if(r.getToken()===oe)return new Dt(oe)}}var j=(s=>(s.COMPARE="COMPARE",s.DIVIDED="DIVIDED",s.MINUS="MINUS",s.MULTIPLY="MULTIPLY",s.PLUS="PLUS",s.UNION="UNION",s))(j||{});class br extends m.Disposable{constructor(){super(...arguments);g(this,"_functionExecutors",new Map);g(this,"_functionDescriptions",new Map)}dispose(){this._functionExecutors.clear(),this._functionDescriptions.clear()}registerExecutors(...e){for(let t=0;t<e.length;t++){const n=e[t];this._functionExecutors.set(n.name,n)}}getExecutors(){return this._functionExecutors}getExecutor(e){return this._functionExecutors.get(e)}hasExecutor(e){return this._functionExecutors.has(e)}registerDescriptions(...e){for(let t=0;t<e.length;t++){const n=e[t];this._functionDescriptions.set(n.functionName,n)}}getDescriptions(){return this._functionDescriptions}getDescription(e){return this._functionDescriptions.get(e)}hasDescription(e){return this._functionDescriptions.has(e)}}const he=D.createIdentifier("univer.formula.function.service");var vn=Object.defineProperty,Pn=Object.getOwnPropertyDescriptor,Vn=(s,r,e,t)=>{for(var n=t>1?void 0:t?Pn(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&vn(r,e,n),n},Wt=(s,r)=>(e,t)=>r(e,t,s);class Ke extends H{constructor(r,e,t){super(e),this._accessor=r,this._operatorString=e,this._functionExecutor=t}get nodeType(){return L.PREFIX}execute(){let e=this.getChildren()[0].getValue(),t;if(e==null)throw new Error("object is null");e.isReferenceObject()&&(e=e.toArrayValueObject()),this._operatorString===P.MINUS?t=this._functionExecutor.calculate(new p(0),e):this._operatorString===P.AT?t=this._handlerAT(e):t=_.create(h.VALUE),this.setValue(t)}_handlerAT(r){if(!r.isReferenceObject())return _.create(h.VALUE);const e=r;if(e.isCell())return _.create(h.VALUE);const t=this._accessor.get(J),n=t.currentRow||0,i=t.currentColumn||0;return e.isRow()?e.getCellByColumn(i):e.isColumn()?e.getCellByRow(n):e.isRange()||e.isTable()?e.getCellByPosition():_.create(h.VALUE)}}let Xe=class extends re{constructor(s,r){super(),this._functionService=s,this._injector=r}get zIndex(){return ee.get(L.PREFIX)||te}checkAndCreateNodeType(s){if(!(s instanceof F))return;const r=s.getToken(),e=r.trim();if(e.charAt(0)==='"'&&e.charAt(e.length-1)==='"')return;let t="";if(e===P.MINUS)t=j.MINUS;else return e===P.AT?new Ke(this._injector,e):void 0;const n=this._functionService.getExecutor(t);return n?new Ke(this._injector,e,n):(console.error(`No function ${r}`),V.create(h.NAME))}};Xe=Vn([Wt(0,he),Wt(1,D.Inject(D.Injector))],Xe);var Bn=Object.defineProperty,kn=Object.getOwnPropertyDescriptor,jn=(s,r,e,t)=>{for(var n=t>1?void 0:t?kn(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&Bn(r,e,n),n},Zt=(s,r)=>(e,t)=>r(e,t,s);class $n extends H{constructor(r,e){super(r),this._functionExecutor=e,this._functionExecutor.isAsync()&&this.setAsync(),this._functionExecutor.isAddress()&&this.setAddress()}get nodeType(){return L.FUNCTION}async executeAsync(){const r=[],e=this.getChildren(),t=e.length;for(let i=0;i<t;i++){const a=e[i].getValue();a!=null&&(a.isReferenceObject()?r.push(a.toArrayValueObject()):r.push(a))}const n=this._functionExecutor.calculate(...r);return n.isAsyncObject()||n.isAsyncArrayObject()?this.setValue(await n.getValue()):this.setValue(n),Promise.resolve(ae.SUCCESS)}execute(){const r=[],e=this.getChildren(),t=e.length;for(let i=0;i<t;i++){const a=e[i].getValue();a!=null&&(a.isReferenceObject()?r.push(a.toArrayValueObject()):r.push(a))}const n=this._functionExecutor.calculate(...r);this.setValue(n)}}let We=class extends re{constructor(s,r){super(),this._functionService=s,this._injector=r}get zIndex(){return ee.get(L.FUNCTION)||te}create(s){const r=this._functionService.getExecutor(s);return r?new $n(s,r):(console.error(`No function ${s}`),V.create(h.NAME))}checkAndCreateNodeType(s){if(typeof s=="string")return;let e=s.getToken().trim().toUpperCase(),t,n;const i=e.slice(0,2);let a=0;if(new RegExp(P.MINUS,"g").test(i)){const o=this._functionService.getExecutor(j.MINUS);t=new Ke(this._injector,P.MINUS,o),a++}if(new RegExp(P.AT,"g").test(i)&&(n=new Ke(this._injector,P.AT),t&&n.setParent(t),a++),a>0&&(e=e.slice(a)),this._functionService.hasExecutor(e)){const o=this.create(e);return n?o.setParent(n):t&&o.setParent(t),o}}};We=jn([Zt(0,he),Zt(1,D.Inject(D.Injector))],We);var Qn=Object.defineProperty,Gn=Object.getOwnPropertyDescriptor,Hn=(s,r,e,t)=>{for(var n=t>1?void 0:t?Gn(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&Qn(r,e,n),n},Yn=(s,r)=>(e,t)=>r(e,t,s);let be=class extends m.Disposable{constructor(s){super(),this._runtimeService=s}dispose(){}async executeAsync(s){if(!s)return _.create(h.VALUE);await this._executeAsync(s);const r=s.getValue();if(r==null)throw new Error("node value is null");return Promise.resolve(r)}execute(s){if(!s)return _.create(h.VALUE);this._execute(s);const r=s.getValue();if(r==null)throw new Error("node value is null");return r}executePreCalculateNode(s){return s.execute(),s.getValue()}checkAsyncNode(s){const r=[];this._checkAsyncNode(s,r);for(let e=0,t=r.length;e<t;e++)if(r[e]===!0)return!0;return!1}_checkAsyncNode(s,r){const e=s.getChildren(),t=e.length;for(let n=0;n<t;n++){const i=e[n];r.push(i.isAsync()),this._checkAsyncNode(i,r)}}async _executeAsync(s){if(this._runtimeService.isStopExecution())return Promise.resolve(ae.ERROR);const r=s.getChildren(),e=r.length;for(let t=0;t<e;t++){const n=r[t];if(n.getToken().toUpperCase()===Me&&n.isEmptyParamFunction()){await n.executeAsync();continue}await this._executeAsync(n)}return s.nodeType===L.FUNCTION&&s.isAsync()?await s.executeAsync():s.execute(),Promise.resolve(ae.SUCCESS)}_execute(s){if(this._runtimeService.isStopExecution())return ae.ERROR;const r=s.getChildren(),e=r.length;for(let t=0;t<e;t++){const n=r[t];if(n.getToken().toUpperCase()===Me&&n.isEmptyParamFunction()){n.execute();continue}this._execute(n)}return s.execute(),ae.SUCCESS}};be=Hn([Yn(0,J)],be);function Dr(s){return s instanceof F?s.getToken()===Se:!1}function qn(s){return s instanceof F?s.getToken()===dr:!1}class Jt extends le{constructor(e,t,n){super(0);g(this,"_lambdaPrivacyValueMap",new Map);this._lambdaNode=e,this._interpreter=t,this._lambdaPrivacyVarKeys=n,this._lambdaPrivacyValueMap.clear()}isLambda(){return!0}execute(...e){const t=this._lambdaPrivacyVarKeys.length;if(e.length!==t)return new _(h.VALUE);this._setLambdaPrivacyValueMap(e),this._setLambdaNodeValue(this._lambdaNode),this._lambdaNode.setNotEmpty(!1);let n;if(this._interpreter.checkAsyncNode(this._lambdaNode))n=new fn(this._interpreter.executeAsync(this._lambdaNode));else{const i=this._interpreter.execute(this._lambdaNode);i.isReferenceObject()?n=i.toArrayValueObject():n=i}return this._lambdaNode.setNotEmpty(!0),n}_setLambdaNodeValue(e){const t=e.getChildren(),n=t.length;for(let i=0;i<n;i++){const a=t[i];if(a.getToken()===st){const u=a.getLambdaParameter(),c=this._lambdaPrivacyValueMap.get(u);c&&a.setValue(c);continue}this._setLambdaNodeValue(a)}}_setLambdaPrivacyValueMap(e){for(let t=0;t<e.length;t++){const n=e[t],i=this._lambdaPrivacyVarKeys[t];this._lambdaPrivacyValueMap.set(i,n)}}}var zn=Object.defineProperty,Kn=Object.getOwnPropertyDescriptor,Xn=(s,r,e,t)=>{for(var n=t>1?void 0:t?Kn(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&zn(r,e,n),n},er=(s,r)=>(e,t)=>r(e,t,s);class Wn extends H{constructor(e,t,n,i){super(e);g(this,"_isNotEmpty",!0);this._lambdaId=t,this._interpreter=n,this._lambdaPrivacyVarKeys=i}get nodeType(){return L.LAMBDA}setNotEmpty(e=!1){this._isNotEmpty=e}isEmptyParamFunction(){return this.getChildren().length<2&&this._isNotEmpty}isFunctionParameter(){return this._lambdaId===null}getLambdaId(){return this._lambdaId}execute(){if(this.isEmptyParamFunction())this.setValue(new Jt(this,this._interpreter,this._lambdaPrivacyVarKeys));else{const e=this.getChildren(),t=e.length;this.setValue(e[t-1].getValue())}}async executeAsync(){if(this.isEmptyParamFunction())await this.setValue(new Jt(this,this._interpreter,this._lambdaPrivacyVarKeys));else{const e=this.getChildren(),t=e.length;await this.setValue(e[t-1].getValue())}return Promise.resolve(ae.SUCCESS)}}let Ze=class extends re{constructor(s,r){super(),this._runtimeService=s,this._interpreter=r}get zIndex(){return ee.get(L.LAMBDA)||te}create(s){const r=s.getChildren(),e=r[0];let t=r.slice(1,-1);const n=r[r.length-1];if(!(e instanceof F&&n instanceof F))return V.create(h.NAME);if(e.getToken()===Se){const o=e.getChildren();if(t.length!==o.length)return V.create(h.VALUE)}else t=r.slice(0,-1);const i=m.Tools.generateRandomId(8),a=new Map;for(let o=0;o<t.length;o++){const u=t[o];if(u instanceof F){const c=u.getChildren()[0];u.setToken(dr),a.set(c.trim(),void 0)}else return V.create(h.VALUE)}return this._runtimeService.registerFunctionDefinitionPrivacyVar(i,a),this._updateLambdaStatement(n,i,a),new Wn(s.getToken(),i,this._interpreter,[...a.keys()])}checkAndCreateNodeType(s){if(!(!(s instanceof F)||s.getToken().trim().toUpperCase()!==Me))return this.create(s)}_updateLambdaStatement(s,r,e){this._updateTree(s,r,e)}_updateTree(s,r,e){const t=s.getChildren(),n=t.length,i=t[0];for(let a=0;a<n;a++){const o=t[a];if(!(Dr(i)&&a!==0))if(o instanceof F)this._updateTree(o,r,e);else{const u=o.trim();if(e.has(u)){const c=new F;c.setToken(st),c.setLambdaId(r),c.setLambdaPrivacyVar(e),c.setLambdaParameter(u),t[a]=c}}}}};Ze=Xn([er(0,J),er(1,D.Inject(be))],Ze);class Zn extends H{constructor(r,e,t){super(r),this._lambdaParameter=e,this._currentLambdaPrivacyVar=t}getLambdaParameter(){return this._lambdaParameter}getCurrentLambdaPrivacyVar(){return this._currentLambdaPrivacyVar}get nodeType(){return L.LAMBDA_PARAMETER}execute(){const r=this._getRootLexerNode(this._currentLambdaPrivacyVar.get(this._lambdaParameter));if(r)this.setValue(r.getValue());else{const e=this.getValue();(e==null||e.isError())&&this.setValue(_.create(h.SPILL))}}_getRootLexerNode(r){if(!r)return;if(r.getToken()!==st)return r;const e=r,t=e.getCurrentLambdaPrivacyVar(),n=e.getLambdaParameter();if(t)return this._getRootLexerNode(t.get(n))}}class Fr extends re{get zIndex(){return ee.get(L.LAMBDA_PARAMETER)||te}create(r){const e=r.getFunctionDefinitionPrivacyVar(),t=r.getLambdaParameter();return e?new Zn(r.getToken(),t,e):new V(h.SPILL)}checkAndCreateNodeType(r){if(!(!(r instanceof F)||r.getToken().trim()!==st))return this.create(r)}}class Jn extends H{constructor(r){super(r),this._operatorString=r}get nodeType(){return L.NULL}execute(){this.setValue(new Rr(0))}}var es=Object.defineProperty,ts=Object.getOwnPropertyDescriptor,rs=(s,r,e,t)=>{for(var n=t>1?void 0:t?ts(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&es(r,e,n),n},ns=(s,r)=>(e,t)=>r(e,t,s);class ss extends H{constructor(r,e){super(r),this._operatorString=r,this._functionExecutor=e}get nodeType(){return L.OPERATOR}execute(){const r=this.getChildren();this._functionExecutor.name===j.COMPARE&&this._functionExecutor.setCompareType(this.getToken());let e=r[0].getValue(),t=r[1].getValue();if(e==null||t==null)throw new Error("object1 or object2 is null");e.isReferenceObject()&&(e=e.toArrayValueObject()),t.isReferenceObject()&&(t=t.toArrayValueObject()),this.setValue(this._functionExecutor.calculate(e,t))}}let Je=class extends re{constructor(s){super(),this._functionService=s}get zIndex(){return ee.get(L.OPERATOR)||te}create(s){let r="";const e=s;e===G.PLUS?r=j.PLUS:e===G.MINUS?r=j.MINUS:e===G.MULTIPLY?r=j.MULTIPLY:e===G.DIVIDED?r=j.DIVIDED:e===G.CONCATENATE?r=lt.CONCATENATE:e===G.POWER?r=K.POWER:Mr.has(e)&&(r=j.COMPARE);const t=this._functionService.getExecutor(r);return t?new ss(e,t):(console.error(`No function ${s}`),V.create(h.NAME))}checkAndCreateNodeType(s){if(s instanceof F)return;const r=s.trim();if(!(r.charAt(0)==='"'&&r.charAt(r.length-1)==='"')&&Ue.has(r))return this.create(r)}};Je=rs([ns(0,he)],Je);class is extends m.Disposable{constructor(){super(...arguments);g(this,"_tableMap",new Map);g(this,"_tableOptionMap",new Map)}dispose(){this._tableMap.clear(),this._tableOptionMap.clear()}remove(e,t){var n;(n=this._tableMap.get(e))==null||n.delete(t)}getTableMap(e){return this._tableMap.get(e)}getTableOptionMap(){return this._tableOptionMap}registerTable(e,t,n){var i;this._tableMap.get(e)==null&&this._tableMap.set(e,new Map),(i=this._tableMap.get(e))==null||i.set(t,n)}registerTableOptionMap(e,t){this._tableOptionMap.set(e,t)}}const kt=D.createIdentifier("univer.formula.super-table.service");class jt extends we{constructor(r){super(r);const e=m.deserializeRangeWithSheet(r);this.setForcedUnitIdDirect(e.unitId),this.setForcedSheetName(e.sheetName),this.setRangeData(e.range)}isCell(){return!0}unionBy(r){if(!r.isCell())return _.create(h.REF);const e=r,t=this.unionRange(this.getRangeData(),e.getRangeData());return this._createRange(t)}unionRange(r,e){const t=r.startRow,n=r.startColumn,i=e.startRow,a=e.startColumn,o={startRow:-1,startColumn:-1,endRow:-1,endColumn:-1};return t>i?(o.startRow=i,o.endRow=t):(o.startRow=t,o.endRow=i),n>a?(o.startColumn=a,o.endColumn=n):(o.startColumn=n,o.endColumn=a),o}_createRange(r){const e=new Sr(r,this.getForcedSheetId(),this.getForcedUnitId());e.setUnitData(this.getUnitData()),e.setDefaultSheetId(this.getDefaultSheetId()),e.setDefaultUnitId(this.getDefaultUnitId()),e.setRuntimeData(this.getRuntimeData()),e.setArrayFormulaCellData(this.getArrayFormulaCellData()),e.setRuntimeArrayFormulaCellData(this.getRuntimeArrayFormulaCellData()),e.setRuntimeFeatureCellData(this.getRuntimeFeatureCellData());const{x:t,y:n}=this.getRefOffset();e.setRefOffset(t,n);const i=this.getForcedSheetId();e.setForcedSheetName(this.getForcedSheetName()),i!=null&&e.setForcedSheetIdDirect(i);const a=this.getForcedUnitId();return a&&e.setForcedUnitIdDirect(a),e}}class as extends we{constructor(r){super(r);const e=m.deserializeRangeWithSheet(r);this.setForcedUnitIdDirect(e.unitId),this.setForcedSheetName(e.sheetName);const t={startColumn:e.range.startColumn,startRow:-1,endColumn:-1,endRow:-1};this.setRangeData(t)}isColumn(){return!0}unionBy(r){if(!r.isColumn())return _.create(h.REF);const e=r;if(e.getForcedSheetName()!==void 0)return _.create(h.REF);const t=this.getRangeData();if(t.endColumn!==-1)return _.create(h.REF);const n=e.getRangeData().startColumn,i=t.startColumn;return n>i?t.endColumn=n:(t.startColumn=n,t.endColumn=i),this}}class os extends we{constructor(r){super(r);const e=m.deserializeRangeWithSheet(r);this.setForcedUnitIdDirect(e.unitId),this.setForcedSheetName(e.sheetName);const t={startColumn:-1,startRow:e.range.startRow,endColumn:-1,endRow:-1};this.setRangeData(t)}isRow(){return!0}unionBy(r){if(!r.isRow())return _.create(h.REF);const e=r;if(e.getForcedSheetName()!==void 0)return _.create(h.REF);const t=this.getRangeData();if(t.endRow!==-1)return _.create(h.REF);const n=e.getRangeData().startRow,i=t.startRow;return n>i?t.endRow=n:(t.startRow=n,t.endRow=i),this}}class us extends we{constructor(r,e,t,n){super(r),this._tableData=e,this._columnDataString=t;const i=this._tableData.sheetId,a=this._tableData.range,o=this._tableData.titleMap;this.setForcedSheetIdDirect(i);const u=this._stringToColumnData(this._columnDataString,o,n),c=u.startColumn,l=u.endColumn,f=u.type;let d=-1,E=-1;const A=a.startRow,C=a.startColumn;f===me.ALL?(d=A,E=C):f===me.DATA?(d=A+1,E=C):f===me.HEADERS?(d=A,E=A):f===me.TOTALS&&(d=C,E=C),this.setRangeData({startColumn:c,endColumn:l,startRow:d,endRow:E})}isTable(){return!0}_stringToColumnData(r,e,t){r=r.substring(1,-1);const n=r.indexOf(w.COMMA);let i=-1,a=-1,o=me.ALL;if(n===-1){const u=this._columnHandler(r,e);i=u.startColumn,a=u.endColumn}else{const u=r.substring(0,n).substring(1,-1),c=r.substring(n+1),l=this._columnHandler(c,e,!0);i=l.startColumn,a=l.endColumn,o=t.get(u),o||(o=me.ALL)}return{startColumn:i,endColumn:a,type:o}}_columnHandler(r,e,t=!1){let n=-1,i=-1;const a=r.indexOf(w.COLON);if(new RegExp(_r,"g").test(r)){const o=r.substring(0,a).substring(1,-1),u=r.substring(a+1).substring(1,-1);n=e.get(o)??-1,i=e.get(u)??-1}else t&&(r=r.substring(1,-1)),n=e.get(r)??-1,i=n;return{startColumn:n,endColumn:i}}}var cs=Object.defineProperty,ls=Object.getOwnPropertyDescriptor,hs=(s,r,e,t)=>{for(var n=t>1?void 0:t?ls(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&cs(r,e,n),n},Oe=(s,r)=>(e,t)=>r(e,t,s);class Pe extends H{constructor(r,e,t){super(e),this._accessor=r,this._operatorString=e,this._referenceObject=t}get nodeType(){return L.REFERENCE}execute(){const r=this._accessor.get(Te),e=this._accessor.get(J);this._referenceObject.setDefaultUnitId(e.currentUnitId),this._referenceObject.setDefaultSheetId(e.currentSubComponentId),this._referenceObject.setForcedSheetId(r.getSheetNameMap()),this._referenceObject.setUnitData(r.getUnitData()),this._referenceObject.setArrayFormulaCellData(r.getArrayFormulaCellData()),this._referenceObject.setRuntimeData(e.getUnitData()),this._referenceObject.setRuntimeArrayFormulaCellData(e.getRuntimeArrayFormulaCellData()),this._referenceObject.setRuntimeFeatureCellData(e.getRuntimeFeatureCellData());const{x:t,y:n}=this.getRefOffset();this._referenceObject.setRefOffset(t,n),this.setValue(this._referenceObject)}}let et=class extends re{constructor(s,r,e,t,n){super(),this._definedNamesService=s,this._superTableService=r,this._formulaRuntimeService=e,this._lexer=t,this._injector=n}get zIndex(){return ee.get(L.REFERENCE)||te}checkAndCreateNodeType(s){let r=!1,e;if(s instanceof F?(r=!0,e=s.getToken().trim()):e=s.trim(),!r&&e.charAt(0)==='"'&&e.charAt(e.length-1)==='"')return;if(new RegExp(Lt).test(e))return new Pe(this._injector,e,new jt(e));if(r&&new RegExp(jr).test(e))return new Pe(this._injector,e,new os(e));if(r&&new RegExp($r).test(e))return new Pe(this._injector,e,new as(e));const t=this._formulaRuntimeService.currentUnitId,n=this._superTableService.getTableMap(t),i=new RegExp(_r,"g"),a=e.replace(i,"");if(!r&&(n!=null&&n.has(a))){const o=i.exec(e);let u="";o&&(u=o[0]);const c=n.get(a),l=this._superTableService.getTableOptionMap();return new Pe(this._injector,e,new us(e,c,u,l))}}};et=hs([Oe(0,ht),Oe(1,kt),Oe(2,J),Oe(3,D.Inject(Ee)),Oe(4,D.Inject(D.Injector))],et);var fs=Object.defineProperty,_s=Object.getOwnPropertyDescriptor,ds=(s,r,e,t)=>{for(var n=t>1?void 0:t?_s(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&fs(r,e,n),n},tr=(s,r)=>(e,t)=>r(e,t,s);class rr extends H{constructor(r,e,t){super(e),this._accessor=r,this._operatorString=e,this._functionExecutor=t}get nodeType(){return L.SUFFIX}execute(){let e=this.getChildren()[0].getValue(),t;if(e==null)throw new Error("object is null");this._operatorString===ue.PERCENTAGE?(e.isReferenceObject()&&(e=e.toArrayValueObject()),t=this._functionExecutor.calculate(e,new p(100))):this._operatorString===ue.POUND?t=this._handlerPound(e):t=_.create(h.VALUE),this.setValue(t)}_handlerPound(r){var l,f,d,E;if(!r.isReferenceObject()||!r.isCell())return _.create(h.VALUE);const e=this._accessor.get(Te),t=this._accessor.get(Ee),n=r,i=n.getRangeData(),a=n.getUnitId(),o=n.getSheetId(),u=e.getFormulaData(),c=(E=(d=(f=(l=u==null?void 0:u[a])==null?void 0:l[o])==null?void 0:f[i.startRow])==null?void 0:d[i.startColumn])==null?void 0:E.f;return c&&t.treeBuilder(c),_.create(h.VALUE)}}let tt=class extends re{constructor(s,r){super(),this._functionService=s,this._injector=r}get zIndex(){return ee.get(L.SUFFIX)||te}checkAndCreateNodeType(s){if(!(s instanceof F))return;const r=s.getToken().trim();if(r.charAt(0)==='"'&&r.charAt(r.length-1)==='"')return;let e="";if(r===ue.PERCENTAGE)e=j.DIVIDED;else return r===ue.POUND?new rr(this._injector,r):void 0;const t=this._functionService.getExecutor(e);return t?new rr(this._injector,r,t):(console.error(`No function ${s}`),V.create(h.NAME))}};tt=ds([tr(0,he),tr(1,D.Inject(D.Injector))],tt);var ms=Object.defineProperty,gs=Object.getOwnPropertyDescriptor,Cs=(s,r,e,t)=>{for(var n=t>1?void 0:t?gs(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&ms(r,e,n),n},ps=(s,r)=>(e,t)=>r(e,t,s);class Es extends H{constructor(r){super(r),this._operatorString=r}get nodeType(){return L.UNION}execute(){const r=this.getChildren(),e=r[0].getValue(),t=r[1].getValue();if(e==null||t==null)throw new Error("leftNode and rightNode");let n;this._operatorString===w.COLON?n=this._unionFunction(e,t):n=_.create(h.NAME),this.setValue(n)}_unionFunction(r,e){return r.isError()||e.isError()||!r.isReferenceObject()||!e.isReferenceObject()?_.create(h.REF):(r=r,e=e,r.isCell()&&e.isCell()||r.isRow()&&e.isRow()||r.isColumn()&&e.isColumn()?r.unionBy(e):_.create(h.REF))}}let rt=class extends re{constructor(s){super(),this._functionService=s}get zIndex(){return ee.get(L.UNION)||te}create(s){return new Es(s)}checkAndCreateNodeType(s){if(!(s instanceof F))return;const e=s.getToken().trim();if(!(e.charAt(0)==='"'&&e.charAt(e.length-1)==='"')&&e===w.COLON)return this.create(e)}};rt=Cs([ps(0,he)],rt);class Ns extends H{constructor(r){super(r),this._operatorString=r}get nodeType(){return L.VALUE}execute(){this.setValue(ye.create(this._operatorString))}}class Lr extends re{get zIndex(){return ee.get(L.VALUE)||te}_checkValueNode(r){if(isNaN(Number(r))){const e=r.trim(),t=e.charAt(0),n=e.charAt(e.length-1);if(t==='"'&&n==='"')return this.create(e);if(t==="{"&&n==="}")return this.create(e);if(e===Ce.TRUE||e===Ce.FALSE)return this.create(e)}else return this.create(r)}create(r){return new Ns(r)}checkAndCreateNodeType(r){if(!(r instanceof F))return this._checkValueNode(r)}}var As=Object.defineProperty,Rs=Object.getOwnPropertyDescriptor,Ss=(s,r,e,t)=>{for(var n=t>1?void 0:t?Rs(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&As(r,e,n),n},z=(s,r)=>(e,t)=>r(e,t,s);let xe=class extends m.Disposable{constructor(r,e,t,n,i,a,o,u,c,l,f){super();g(this,"_astNodeFactoryList",[]);g(this,"_refOffsetX",0);g(this,"_refOffsetY",0);this._runtimeService=r,this._astRootNodeFactory=e,this._functionNodeFactory=t,this._lambdaNodeFactory=n,this._lambdaParameterNodeFactory=i,this._operatorNodeFactory=a,this._prefixNodeFactory=o,this._referenceNodeFactory=u,this._suffixNodeFactory=c,this._unionNodeFactory=l,this._valueNodeFactory=f,this._initializeAstNode()}dispose(){this._astNodeFactoryList.forEach(r=>{r.dispose()}),this._astNodeFactoryList=[]}parse(r,e=0,t=0){const n=new Dt(oe);return this._refOffsetX=e,this._refOffsetY=t,this._parse(r,n)}_lambdaParameterHandler(r,e){const t=e.getLambdaId(),n=new Dt(oe),i=this._runtimeService.getFunctionDefinitionPrivacyVar(t);if(!i)return!1;const a=[...i.keys()],o=r.getChildren(),u=o.length;for(let f=0;f<u;f++){const d=o[f];if(d instanceof F)this._parse(d,n);else return!1}const c=n.getChildren(),l=c.length;for(let f=0;f<l;f++){const d=c[f];i.set(a[f],d)}return n.setParent(e),e}_changeLetToLambda(r){const e=r.getChildren(),t=e.length;if(t%2!==1||t===0)return;const n=new F;n.setToken(Me);const i=new F;i.setToken(Se);const a=[...e];for(let u=0;u<t;u++){const c=a[u];if(!(c instanceof F))return;u%2===0?c.changeToParent(n):c.changeToParent(i)}n.addChildrenFirst(i),i.setParent(n);const o=r.getParent();return o==null||o.replaceChild(r,n),n}_getTopParent(r){let e=r;for(;e!=null&&e.getParent();)e=e.getParent();return e}_parse(r,e){const t=r.getChildren(),n=t.length,i=[];let a=null;const o=r.getToken().trim().toUpperCase();if(o===Hr){const l=this._changeLetToLambda(r);return l!=null?this._parse(l,e):V.create(h.ERROR)}if(o===de){if(a=e,n===0)return new Jn(oe).setParent(e),a}else{if(o===Se){let l=this._lambdaParameterHandler(r,e);return l===!1&&(l=V.create(h.ERROR)),l}if(a=this._checkAstNode(r),a==null)return V.create(h.ERROR)}const u=t[0];for(let l=0;l<n;l++){const f=t[l];if(Dr(u)){if(l!==0&&l!==n-1)continue}else if(qn(f)&&l!==n-1)continue;let d=null;if(f instanceof F){if(d=this._parse(f,a),d===a)continue}else d=this._checkAstNode(f);if(d==null)return V.create(h.ERROR);if(d=this._getTopParent(d),d==null)return;switch(d.nodeType){case L.ERROR:return d;case L.FUNCTION:i.push(d);break;case L.LAMBDA:i.push(d);break;case L.LAMBDA_PARAMETER:i.push(d);break;case L.OPERATOR:{const E=i.pop(),A=i.pop();if(A)A.setParent(d);else return V.create(h.ERROR);if(E)E.setParent(d);else return V.create(h.ERROR);i.push(d);break}case L.REFERENCE:d.setRefOffset(this._refOffsetX,this._refOffsetY),i.push(d);break;case L.ROOT:i.push(d);break;case L.UNION:i.push(d);break;case L.VALUE:i.push(d);break;case L.PREFIX:i.push(d);break;case L.SUFFIX:i.push(d);break}}const c=i.length;for(let l=0;l<c;l++)i[l].setParent(a);return a}_checkAstNode(r){let e=null;const t=this._astNodeFactoryList.length;for(let n=0;n<t&&(e=this._astNodeFactoryList[n].checkAndCreateNodeType(r),e==null);n++);return e}_initializeAstNode(){this._astNodeFactoryList=[this._astRootNodeFactory,this._functionNodeFactory,this._lambdaNodeFactory,this._lambdaParameterNodeFactory,this._operatorNodeFactory,this._prefixNodeFactory,this._referenceNodeFactory,this._suffixNodeFactory,this._unionNodeFactory,this._valueNodeFactory].sort(m.sortRules)}};xe=Ss([z(0,J),z(1,D.Inject(yr)),z(2,D.Inject(We)),z(3,D.Inject(Ze)),z(4,D.Inject(Fr)),z(5,D.Inject(Je)),z(6,D.Inject(Xe)),z(7,D.Inject(et)),z(8,D.Inject(tt)),z(9,D.Inject(rt)),z(10,D.Inject(Lr))],xe);class wr extends m.Disposable{constructor(){super(...arguments);g(this,"_referenceExecutorMap",new Map)}dispose(){this._referenceExecutorMap.clear()}remove(e){this._referenceExecutorMap.delete(e)}get(e){return this._referenceExecutorMap.get(e)}has(e){return this._referenceExecutorMap.has(e)}register(e,t){this._referenceExecutorMap.set(e,t)}getReferenceExecutorMap(){return this._referenceExecutorMap}}const ft=D.createIdentifier("univer.formula.feature-calculation-manager.service");class Tr extends m.Disposable{constructor(){super(...arguments);g(this,"_otherFormulaData",{})}dispose(){this._otherFormulaData={}}remove(e){var a,o,u;const{unitId:t,subComponentId:n,formulaId:i}=e;(u=(o=(a=this._otherFormulaData)==null?void 0:a[t])==null?void 0:o[n])==null||delete u[i]}get(e){var a,o;const{unitId:t,subComponentId:n,formulaId:i}=e;return(o=(a=this._otherFormulaData[t])==null?void 0:a[n])==null?void 0:o[i]}has(e){var a,o;const{unitId:t,subComponentId:n,formulaId:i}=e;return((o=(a=this._otherFormulaData[t])==null?void 0:a[n])==null?void 0:o[i])!=null}register(e){const{unitId:t,subComponentId:n,formulaId:i,item:a}=e;this._otherFormulaData[t]&&(this._otherFormulaData[t]={}),this._otherFormulaData[t][n]&&(this._otherFormulaData[t][n]={}),this._otherFormulaData[t][n][i]=a}getOtherFormulaData(){return this._otherFormulaData}}const $t=D.createIdentifier("univer.formula.other-formula-manager.service");class Ct extends m.Disposable{constructor(){super(...arguments);g(this,"node");g(this,"children",[]);g(this,"parents",[]);g(this,"formula","");g(this,"row",-1);g(this,"column",-1);g(this,"subComponentId","");g(this,"unitId","");g(this,"rangeList",[]);g(this,"formulaId");g(this,"featureId");g(this,"getDirtyData");g(this,"_state",0)}dispose(){var e;this.children.forEach(t=>{t.dispose()}),this.rangeList=[],this.parents=[],(e=this.node)==null||e.dispose()}setAdded(){this._state=1}isAdded(){return this._state===1}setSkip(){this._state=2}isSkip(){return this._state===2}inRangeData(e){const t=e.startRow,n=e.startColumn,i=e.endRow,a=e.endColumn;return!(this.row<t||this.row>i||this.column<n||this.column>a)}dependencyRange(e,t,n){var i,a;if(this.rangeList.length===0)return!1;for(let o=0,u=this.rangeList.length;o<u;o++){const c=this.rangeList[o],{unitId:l,sheetId:f,range:d}=c;if(!e.has(l))continue;const E=e.get(l);if(!E.has(f))continue;const A=E.get(f),C=(i=n==null?void 0:n[l])==null?void 0:i[f];for(const N of A){const{startRow:S,startColumn:y,endRow:T,endColumn:b}=N;if(!(d.startRow>T||d.endRow<S||d.startColumn>b||d.endColumn<y)){let Q=!0;if(C==null||C.forValue((se,Y)=>{if(se>=d.startRow&&se<=d.endRow&&Y>=d.startColumn&&Y<=d.endColumn)return Q=!1,!1}),Q)return!0}}if(((a=t[l])==null?void 0:a[f])!=null)return!0}return!1}pushChildren(e){this.children.push(e),e._pushParent(this)}pushRangeList(e){this.rangeList.push(e)}dependency(e){if(this.rangeList.length===0)return!1;for(let t=0,n=this.rangeList.length;t<n;t++){const i=this.rangeList[t],a=i.unitId,o=i.sheetId,u=i.range;if(e.unitId===a&&e.subComponentId===o&&e.inRangeData(u))return!0}return!1}_pushParent(e){this.parents.push(e)}}var ys=Object.defineProperty,bs=Object.getOwnPropertyDescriptor,Ds=(s,r,e,t)=>{for(var n=t>1?void 0:t?bs(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&ys(r,e,n),n},fe=(s,r)=>(e,t)=>r(e,t,s);const Fs=1e5,pt=new nt(Fs);let Ie=class extends m.Disposable{constructor(r,e,t,n,i,a,o){super();g(this,"_updateRangeFlattenCache",new Map);g(this,"_dirtyUnitSheetNameMap",{});this._currentConfigService=r,this._runtimeService=e,this._otherFormulaManagerService=t,this._featureCalculationManagerService=n,this._interpreter=i,this._astTreeBuilder=a,this._lexer=o}dispose(){this._updateRangeFlattenCache.clear(),pt.clear(),this._dirtyUnitSheetNameMap={}}async generate(){this._updateRangeFlatten();const r=this._currentConfigService.getFormulaData(),e=this._otherFormulaManagerService.getOtherFormulaData(),t=await this._generateTreeList(r,e),n=this._getUpdateTreeListAndMakeDependency(t);this._checkIsCycleDependency(n)&&this._runtimeService.enableCycleDependency();const a=this._calculateRunList(n);return Promise.resolve(a)}_isCyclicUtil(r,e,t){if(!e.has(r)){e.add(r),t.add(r);for(let n=0;n<r.children.length;n++)if(!e.has(r.children[n])&&this._isCyclicUtil(r.children[n],e,t)||t.has(r.children[n]))return!0}return t.delete(r),!1}_checkIsCycleDependency(r){const e=new Set,t=new Set;for(let n=0,i=r.length;n<i;n++){const a=r[n];if(this._isCyclicUtil(a,e,t)===!0)return!0}return!1}async _generateTreeList(r,e){const t=Object.keys(r),n=Object.keys(e),i=[];for(const a of t){const o=r[a],u=Object.keys(o);for(const c of u)new m.ObjectMatrix(o[c]).forValue((f,d,E)=>{if(E==null)return!0;const{f:A,x:C,y:N}=E,S=this._generateAstNode(A,C,N),y=new Ct;y.node=S,y.formula=A,y.unitId=a,y.subComponentId=c,y.row=f,y.column=d,i.push(y)})}for(const a of n){const o=e[a],u=Object.keys(o);for(const c of u){const l=o[c],f=Object.keys(l);for(const d of f){const E=l[d],{f:A}=E,C=this._generateAstNode(A),N=new Ct;N.node=C,N.formula=A,N.unitId=a,N.subComponentId=c,N.formulaId=d,i.push(N)}}}this._featureCalculationManagerService.getReferenceExecutorMap().forEach((a,o)=>{const{unitId:u,subComponentId:c,dependencyRanges:l,getDirtyData:f}=a,d=new Ct;d.unitId=u,d.subComponentId=c,d.getDirtyData=f,d.featureId=o,d.rangeList=l,i.push(d)});for(let a=0,o=i.length;a<o;a++){const u=i[a];if(this._runtimeService.setCurrent(u.row,u.column,u.subComponentId,u.unitId),u.node==null)continue;const c=await this._getRangeListByNode(u.node);for(let l=0,f=c.length;l<f;l++)u.pushRangeList(c[l])}return i}_updateRangeFlatten(){const r=this._currentConfigService.isForceCalculate(),e=this._currentConfigService.getDirtyRanges();if(!r){this._updateRangeFlattenCache.clear();for(let t=0;t<e.length;t++){const n=e[t],i=n.range,a=n.sheetId,o=n.unitId;this._addFlattenCache(o,a,i)}this._dirtyUnitSheetNameMap=this._currentConfigService.getDirtyNameMap()}}_generateAstNode(r,e=0,t=0){let n=pt.get(`${r}##${e}${t}`);if(n)return n;const i=this._lexer.treeBuilder(r);if(i in h)return V.create(i);if(n=this._astTreeBuilder.parse(i,e,t),n==null)throw new Error("astNode is null");return pt.set(`${r}##${e}${t}`,n),n}_addFlattenCache(r,e,t){let n=this._updateRangeFlattenCache.get(r);n==null&&(n=new Map,this._updateRangeFlattenCache.set(r,n));let i=n.get(e);i==null&&(i=[],n.set(e,i)),i.push(t)}_isPreCalculateNode(r){return r.nodeType===L.UNION||r.nodeType===L.PREFIX&&r.getToken()===P.AT||r.nodeType===L.SUFFIX&&r.getToken()===ue.POUND}_nodeTraversalRef(r,e){const t=r.getChildren(),n=t.length;for(let i=0;i<n;i++){const a=t[i];if(this._isPreCalculateNode(a)){e.push(a);continue}else a.nodeType===L.REFERENCE&&e.push(a);this._nodeTraversalRef(a,e)}}_nodeTraversalReferenceFunction(r,e){const t=r.getChildren(),n=t.length;for(let i=0;i<n;i++){const a=t[i];if(a.nodeType===L.FUNCTION&&a.isAddress()){e.push(a);continue}this._nodeTraversalReferenceFunction(a,e)}}async _executeNode(r){let e;return this._interpreter.checkAsyncNode(r)?e=await this._interpreter.executeAsync(r):e=this._interpreter.execute(r),e}async _getRangeListByNode(r){const e=[],t=[];this._nodeTraversalRef(r,e),this._nodeTraversalReferenceFunction(r,t);const n=[];for(let i=0,a=e.length;i<a;i++){const o=e[i],c=(await this._executeNode(o)).toUnitRange();n.push(c)}for(let i=0,a=t.length;i<a;i++){const o=t[i],c=(await this._executeNode(o)).toUnitRange();n.push(c)}return n}_getUpdateTreeListAndMakeDependency(r){const e=[],t=new Set,n=this._currentConfigService.isForceCalculate();for(let i=0,a=r.length;i<a;i++){const o=r[i];for(let u=0,c=r.length;u<c;u++){const l=r[u];o!==l&&o.dependency(l)&&o.pushChildren(l)}(n||o.dependencyRange(this._updateRangeFlattenCache,this._dirtyUnitSheetNameMap,this._currentConfigService.getExcludedRange())||this._includeTree(o))&&!t.has(o)&&(e.push(o),t.add(o))}return e}_includeTree(r){var c,l,f,d;const e=r.unitId,t=r.subComponentId,n=r.featureId;if(n!=null){const E=this._currentConfigService.getDirtyUnitFeatureMap();if(((l=(c=E==null?void 0:E[e])==null?void 0:c[t])==null?void 0:l[n])!=null)return!0}const i=(d=(f=this._currentConfigService.getExcludedRange())==null?void 0:f[e])==null?void 0:d[t];let a=!1;if(i==null||i.forValue((E,A)=>{if(r.row===E&&r.column===A)return a=!0,!1}),a||!this._updateRangeFlattenCache.has(e))return!1;const o=this._updateRangeFlattenCache.get(e);if(!o.has(t))return!1;const u=o.get(t);for(const E of u)if(r.inRangeData(E))return!0;return!1}_calculateRunList(r){let e=r;const t=[];for(;e.length>0;){const n=e.pop();if(n===void 0||n.isSkip())continue;if(n.isAdded()){t.push(n);continue}const i=[];for(let a=0,o=n.parents.length;a<o;a++){const u=n.parents[a];i.push(u)}i.length===0?(t.push(n),n.setSkip()):(n.setAdded(),e.push(n),e=e.concat(i))}return t.reverse()}};Ie=Ds([m.OnLifecycle(m.LifecycleStages.Rendered,Ie),fe(0,Te),fe(1,J),fe(2,$t),fe(3,ft),fe(4,D.Inject(be)),fe(5,D.Inject(xe)),fe(6,D.Inject(Ee))],Ie);var Ls=Object.defineProperty,ws=Object.getOwnPropertyDescriptor,Ts=(s,r,e,t)=>{for(var n=t>1?void 0:t?ws(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&Ls(r,e,n),n},_e=(s,r)=>(e,t)=>r(e,t,s);const Os=1;exports.CalculateFormulaService=class extends m.Disposable{constructor(e,t,n,i,a,o,u){super();g(this,"_executionStartListener$",new _t.Subject);g(this,"executionStartListener$",this._executionStartListener$.asObservable());g(this,"_executionCompleteListener$",new _t.Subject);g(this,"executionCompleteListener$",this._executionCompleteListener$.asObservable());g(this,"_executionInProgressListener$",new _t.Subject);g(this,"executionInProgressListener$",this._executionInProgressListener$.asObservable());this._configService=e,this._lexer=t,this._currentConfigService=n,this._runtimeService=i,this._formulaDependencyGenerator=a,this._interpreter=o,this._astTreeBuilder=u}dispose(){}stopFormulaExecution(){this._runtimeService.stopExecution()}setRuntimeFeatureCellData(e,t){this._runtimeService.setRuntimeFeatureCellData(e,t)}setRuntimeFeatureRange(e,t){this._runtimeService.setRuntimeFeatureRange(e,t)}async execute(e){this._executionStartListener$.next(!0),this._currentConfigService.load(e),this._runtimeService.reset();const t=this._configService.getConfig("CYCLE_REFERENCE_COUNT")||Os;for(let n=0;n<t&&(await this._execute(),!!this._runtimeService.isCycleDependency());n++);this._runtimeService.setFormulaExecuteStage(W.CALCULATION_COMPLETED),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()),this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData()),St.clear(),ge.clear()}async _execute(){const e=await this._apply();if(e==null)return;const{arrayFormulaRange:t,runtimeFeatureRange:n}=e,{dirtyRanges:i,excludedCell:a}=this._getArrayFormulaDirtyRangeAndExcludedRange(t,n);return i==null||i.length===0||(this._currentConfigService.loadDirtyRangesAndExcludedCell(i,a),await this._apply(!0)),!0}_getArrayFormulaDirtyRangeAndExcludedRange(e,t){const n=[],i={};return Object.keys(e).forEach(a=>{const o=e[a];Object.keys(o).forEach(u=>{const c=new m.ObjectMatrix(o[u]);if(c==null)return!0;const l=new m.ObjectMatrix;c.forValue((f,d,E)=>{l.setValue(f,d,!0),n.push({unitId:a,sheetId:u,range:E})}),i[a]==null&&(i[a]={}),i[a][u]=l})}),Object.keys(t).forEach(a=>{const o=t[a];Object.keys(o).forEach(u=>{const c=o[u];Object.keys(c).forEach(l=>{const f=c[l];if(f==null)return!0;for(const d of f)n.push({unitId:u,sheetId:l,range:d})})})}),{dirtyRanges:n,excludedCell:i}}async _apply(e=!1){e?this._runtimeService.setFormulaExecuteStage(W.START_DEPENDENCY_ARRAY_FORMULA):this._runtimeService.setFormulaExecuteStage(W.START_DEPENDENCY),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());const t=await this._formulaDependencyGenerator.generate(),n=this._interpreter;e?(this._runtimeService.setFormulaExecuteStage(W.START_CALCULATION_ARRAY_FORMULA),this._runtimeService.setTotalArrayFormulasToCalculate(t.length)):(this._runtimeService.setFormulaExecuteStage(W.START_CALCULATION),this._runtimeService.setTotalFormulasToCalculate(t.length)),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());for(let i=0,a=t.length;i<a;i++){if(await new Promise(f=>{m.requestImmediateMacroTask(f)}),this._runtimeService.isStopExecution()){this._runtimeService.setFormulaExecuteStage(W.IDLE),this._runtimeService.markedAsStopFunctionsExecuted(),this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData());return}const o=t[i],u=o.node,c=o.getDirtyData;let l;if(u==null&&c==null)throw new Error("AstNode or executor is null");if(this._runtimeService.setCurrent(o.row,o.column,o.subComponentId,o.unitId),c!=null&&o.featureId!=null){const{runtimeCellData:f,dirtyRanges:d}=c(o);this._runtimeService.setRuntimeFeatureCellData(o.featureId,f),this._runtimeService.setRuntimeFeatureRange(o.featureId,d)}else u!=null&&(n.checkAsyncNode(u)?l=await n.executeAsync(u):l=n.execute(u),o.formulaId!=null?this._runtimeService.setRuntimeOtherData(o.formulaId,l):this._runtimeService.setRuntimeData(l));e?(this._runtimeService.setFormulaExecuteStage(W.CURRENTLY_CALCULATING_ARRAY_FORMULA),this._runtimeService.setCompletedArrayFormulasCount(i+1)):(this._runtimeService.setFormulaExecuteStage(W.CURRENTLY_CALCULATING),this._runtimeService.setCompletedFormulasCount(i+1)),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState())}return t.length>0?this._runtimeService.markedAsSuccessfullyExecuted():e||this._runtimeService.markedAsNoFunctionsExecuted(),this._runtimeService.getAllRuntimeData()}calculate(e,t=!0){const n=this._lexer.treeBuilder(e,t);if(Object.values(h).includes(n))return V.create(n);const i=this._astTreeBuilder.parse(n);console.log("astNode",i==null?void 0:i.serialize())}};exports.CalculateFormulaService=Ts([m.OnLifecycle(m.LifecycleStages.Rendered,exports.CalculateFormulaService),_e(0,m.IConfigService),_e(1,D.Inject(Ee)),_e(2,Te),_e(3,J),_e(4,D.Inject(Ie)),_e(5,D.Inject(be)),_e(6,D.Inject(xe))],exports.CalculateFormulaService);var Us=Object.defineProperty,Is=Object.getOwnPropertyDescriptor,Ms=(s,r,e,t)=>{for(var n=t>1?void 0:t?Is(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&Us(r,e,n),n},Ve=(s,r)=>(e,t)=>r(e,t,s);let ke=class extends m.Disposable{constructor(s,r,e,t){super(),this._commandService=s,this._calculateFormulaService=r,this._currentUniverService=e,this._formulaDataModel=t,this._initialize()}_initialize(){this._commandExecutedListener(),this._initialExecuteFormulaListener(),this._initialExecuteFormulaProcessListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((s,r)=>{if(s.id===Ut.id)this._calculateFormulaService.stopFormulaExecution();else if(s.id===Mt.id){const e=s.params.formulaData;this._formulaDataModel.setFormulaData(e)}else if(s.id===Ot.id){const e=s.params;if(e.forceCalculation===!0)this._calculate(!0);else{const{dirtyRanges:t,dirtyNameMap:n,dirtyUnitFeatureMap:i}=e;this._calculate(!1,t,n,i)}}else if(s.id===Ye.id){const e=s.params;if(e==null)return;const{arrayFormulaRange:t,arrayFormulaCellData:n}=e;this._formulaDataModel.setArrayFormulaRange(t),this._formulaDataModel.setArrayFormulaCellData(n)}}))}async _calculate(s=!1,r=[],e={},t={}){if(r.length===0&&Object.keys(e).length===0&&Object.keys(t).length===0&&s===!1)return;const n=this._formulaDataModel.getFormulaData(),i=this._formulaDataModel.getArrayFormulaCellData();this._calculateFormulaService.execute({formulaData:n,arrayFormulaCellData:i,forceCalculate:s,dirtyRanges:r,dirtyNameMap:e,dirtyUnitFeatureMap:t})}_initialExecuteFormulaListener(){this._calculateFormulaService.executionCompleteListener$.subscribe(s=>{const r=s.functionsExecutedState;switch(r){case Re.NOT_EXECUTED:break;case Re.STOP_EXECUTION:break;case Re.SUCCESS:this._applyFormula(s);break;case Re.INITIAL:break}this._commandService.executeCommand(qe.id,{functionsExecutedState:r},{onlyLocal:!0})})}_initialExecuteFormulaProcessListener(){this._calculateFormulaService.executionInProgressListener$.subscribe(s=>{const{totalFormulasToCalculate:r,completedFormulasCount:e,totalArrayFormulasToCalculate:t,completedArrayFormulasCount:n,stage:i}=s;t>0?console.log(`Stage ${i} Array formula.There are ${t} functions to be executed, ${n} complete.`):console.log(`Stage ${i} .There are ${r} functions to be executed, ${e} complete.`),this._commandService.executeCommand(qe.id,{stageInfo:s},{onlyLocal:!0})})}async _applyFormula(s){const{unitData:r,unitOtherData:e,arrayFormulaRange:t,arrayFormulaCellData:n,clearArrayFormulaCellData:i}=s;if(!r){console.error("No sheetData from Formula Engine!");return}t&&(this._formulaDataModel.clearPreviousArrayFormulaCellData(i),this._formulaDataModel.mergeArrayFormulaCellData(n),this._formulaDataModel.mergeArrayFormulaRange(t),this._commandService.executeCommand(Ye.id,{arrayFormulaRange:this._formulaDataModel.getArrayFormulaRange(),arrayFormulaCellData:this._formulaDataModel.getArrayFormulaCellData()},{onlyLocal:!0})),this._commandService.executeCommand(It.id,{unitData:r,unitOtherData:e},{onlyLocal:!0})}};ke=Ms([m.OnLifecycle(m.LifecycleStages.Ready,ke),Ve(0,m.ICommandService),Ve(1,D.Inject(exports.CalculateFormulaService)),Ve(2,m.IUniverInstanceService),Ve(3,D.Inject(exports.FormulaDataModel))],ke);class xs extends M{calculate(...r){if(r.length!==3)return new _(h.VALUE);let e=r[0],t=r[1];if(!(r[2].isValueObject()&&r[2].isLambda()))return new _(h.VALUE);if(e.isArray()&&(e=e.getFirstCell()),t.isArray()&&(t=t.getFirstCell()),!e.isNumber())return new _(h.VALUE);if(!t.isNumber())return new _(h.VALUE);const n=r[2],i=[];for(let a=0;a<e.getValue();a++){i[a]==null&&(i[a]=[]);for(let o=0;o<t.getValue();o++){const u=n.execute(new p(a+1),new p(o+1));i[a][o]=u}}return new _n(i)}isAsync(){return!0}}const vs=[[xs,Bt.MAKEARRAY]];class Ps extends M{calculate(r,e){return _.create(h.VALUE)}}const Vs=[[Ps,lt.CONCATENATE]],Bs=[],ks=[],js=[],$s=[],Qs=[],Gs=[],Hs=[];class Ys extends M{calculate(r,e){return new jt("A5")}}class qs extends M{calculate(r,e,t,n,i){return new jt("A5")}}const zs=[[Ys,ze.INDIRECT],[qs,ze.OFFSET]];class Ks extends M{calculate(r){return r.isError()?_.create(h.VALUE):(r.isReferenceObject()&&(r=r.toArrayValueObject()),r.abs())}}class Xs extends M{calculate(r){return r.isError()?_.create(h.VALUE):(r.isReferenceObject()&&(r=r.toArrayValueObject()),r.acos())}}class Ws extends M{calculate(r){return r.isError()?_.create(h.VALUE):(r.isReferenceObject()&&(r=r.toArrayValueObject()),r.acosh())}}class Zs extends M{calculate(r){return r.isError()?_.create(h.VALUE):(r.isReferenceObject()&&(r=r.toArrayValueObject()),r.isArray()?r.map(e=>e.isError()?e:nr(e)):nr(r))}}function nr(s){let r=s.getValue();if(s.isBoolean()&&(r=r?1:0),!Number.isFinite(r))return _.create(h.VALUE);const e=Math.atan(1/Number(r));return Number.isNaN(e)?_.create(h.VALUE):new p(e)}class Js extends M{calculate(r,e){return _.create(h.VALUE)}}class ei extends M{calculate(...r){let e=new p(0);for(let t=0;t<r.length;t++){let n=r[t];if(n.isError())return n;if(e.isError())return e;n.isArray()&&(n=n.sum()),e=e.plus(n)}return e}}function ti(s){const r=[R.EQUALS,R.NOT_EQUAL,R.GREATER_THAN_OR_EQUAL,R.GREATER_THAN,R.LESS_THAN_OR_EQUAL,R.LESS_THAN];for(const e of r)if(s.startsWith(e)){const t=s.substring(e.length);return[e,ye.create(t)]}return[R.EQUALS,ye.create(s)]}function ri(s,r){const e=s.toArrayValueObject(),t=`${r.getValue()}`,[n,i]=ti(t);return Zr(t)?e.wildcard(i,n):e.compare(i,n)}class ni extends M{calculate(...r){if(r.length<2||r.length>3)return _.create(h.NA);const e=r[0],t=r[1],n=r[2];if(e.isError()||t.isError()||n&&n.isError())return _.create(h.VALUE);let i=new p(0);if(e.isReferenceObject()||e.isValueObject()&&e.isArray()){const o=ri(e,t).getArrayValue(),u=n||e,{startRow:c,startColumn:l}=u.getRangePosition();u.iterator((f,d,E)=>{if(!(f!=null&&f.isError())){const C=o[d-c][E-l].getValue()?f:new p(0);i=i.plus(C)}})}else t.isValueObject()&&(i=this._validator(e,t));return i}_validator(r,e){const t=e.getValue();if(t){const n=t.substring(0,1),i=t.substring(1);r.compare(new p(i),n).getValue()||(r=new p(0))}return r}}class si extends M{calculate(...r){return _.create(h.VALUE)}}const ii=[[Ks,K.ABS],[Xs,K.ACOS],[Ws,K.ACOSH],[Zs,K.ACOT],[ei,K.SUM],[ni,K.SUMIF],[si,K.SUMIFS],[Js,K.POWER]];class ai extends M{constructor(){super(...arguments);g(this,"_compareType",R.EQUALS)}setCompareType(e){this._compareType=e}calculate(e,t){return e.isError()||t.isError()?_.create(h.VALUE):(e.isReferenceObject()&&(e=e.toArrayValueObject()),t.isReferenceObject()&&(t=t.toArrayValueObject()),e.compare(t,this._compareType))}}class oi extends M{calculate(r,e){return r.isError()||e.isError()?_.create(h.VALUE):(r.isReferenceObject()&&(r=r.toArrayValueObject()),e.isReferenceObject()&&(e=e.toArrayValueObject()),!e.isArray()&&e.getValue()===0?_.create(h.DIV_BY_ZERO):r.divided(e))}}class ui extends M{calculate(r,e){return r.isError()||e.isError()?r:(r.isReferenceObject()&&(r=r.toArrayValueObject()),e.isReferenceObject()&&(e=e.toArrayValueObject()),r.minus(e))}}class ci extends M{calculate(r,e){return r.isError()||e.isError()?_.create(h.VALUE):(r.isReferenceObject()&&(r=r.toArrayValueObject()),e.isReferenceObject()&&(e=e.toArrayValueObject()),r.multiply(e))}}class li extends M{calculate(r,e){return r.isError()||e.isError()?_.create(h.VALUE):(r.isReferenceObject()&&(r=r.toArrayValueObject()),e.isReferenceObject()&&(e=e.toArrayValueObject()),r.plus(e))}}const hi=[[ai,j.COMPARE],[oi,j.DIVIDED],[ui,j.MINUS],[ci,j.MULTIPLY],[li,j.PLUS]];class fi extends M{calculate(...r){let e=new p(0),t=new p(0);for(let n=0;n<r.length;n++){const i=r[n];if(i.isError())return i;if(e.isError())return e;i.isArray()?(e=e.plus(i.sum()),t=t.plus(i.count())):i.isNull()||(t=t.plus(new p(1)))}return e.divided(t)}}class _i extends M{calculate(...r){let e=new p(0);for(let t=0;t<r.length;t++){let n=r[t];n.isError()||(n.isArray()?(n=n.count(),e=e.plus(n)):!n.isNull()&&!n.isString()&&(e=e.plus(new p(1))))}return e}}class di extends M{calculate(...r){let e=new p(0);for(let t=0;t<r.length;t++){let n=r[t];if(n.isError()){e=e.plus(new p(1));continue}n.isArray()?(n=n.countA(),e=e.plus(n)):n.isNull()||(e=e.plus(new p(1)))}return e}}class mi extends M{calculate(...r){let e=new p(-1/0);for(let t=0;t<r.length;t++){let n=r[t];if(n.isError())return n;n.isArray()&&(n=n.max()),!n.isNull()&&(e=this._validator(e,n))}return e}_validator(r,e){return r.isLessThan(e).getValue()&&(r=e),r}}class sr extends M{calculate(...r){let e=new p(1/0);for(let t=0;t<r.length;t++){let n=r[t];if(n.isError())return n;n.isArray()&&(n=n.min()),!n.isNull()&&(e=this._validator(e,n))}return e}_validator(r,e){return r.isGreaterThan(e).getValue()&&(r=e),r}}const gi=[[fi,ie.AVERAGE],[_i,ie.COUNT],[mi,ie.MAX],[sr,ie.MIN],[sr,ie.MIN],[di,ie.COUNTA]],Ci=[],pi=[],Ei=[];var Ni=Object.defineProperty,Ai=Object.getOwnPropertyDescriptor,Ri=(s,r,e,t)=>{for(var n=t>1?void 0:t?Ai(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&Ni(r,e,n),n},Et=(s,r)=>(e,t)=>r(e,t,s);let je=class extends m.Disposable{constructor(s,r,e){super(),this._commandService=s,this._injector=r,this._functionService=e,this._initialize()}_initialize(){this._registerCommands(),this._registerFunctions()}_registerCommands(){[Mt,Ye,Ot,Ut,qe,It,at,ot,wt,Tt,xt,vt,pr,Er,Pt].forEach(s=>this.disposeWithMe(this._commandService.registerCommand(s)))}_registerFunctions(){const s=[...vs,...Vs,...Bs,...ks,...js,...$s,...Qs,...Gs,...Hs,...zs,...ii,...hi,...gi,...Ci,...pi,...Ei].map(r=>{const e=r[0],t=r[1];return new e(t)});this._functionService.registerExecutors(...s)}};je=Ri([m.OnLifecycle(m.LifecycleStages.Ready,je),Et(0,m.ICommandService),Et(1,D.Inject(D.Injector)),Et(2,he)],je);var Si=Object.defineProperty,yi=Object.getOwnPropertyDescriptor,bi=(s,r,e,t)=>{for(var n=t>1?void 0:t?yi(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&Si(r,e,n),n},ir=(s,r)=>(e,t)=>r(e,t,s);let $e=class extends m.Disposable{constructor(s,r){super(),this._commandService=s,this._definedNamesService=r,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(s=>{if(s.id===at.id){const r=s.params;if(r==null)return;const{unitId:e,name:t,formulaOrRefString:n}=r;this._definedNamesService.registerDefinedName(e,t,n)}else if(s.id===ot.id){const r=s.params;if(r==null)return;const{unitId:e,name:t}=r;this._definedNamesService.removeDefinedName(e,t)}}))}};$e=bi([m.OnLifecycle(m.LifecycleStages.Ready,$e),ir(0,m.ICommandService),ir(1,ht)],$e);var Di=Object.defineProperty,Fi=Object.getOwnPropertyDescriptor,Li=(s,r,e,t)=>{for(var n=t>1?void 0:t?Fi(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&Di(r,e,n),n},ar=(s,r)=>(e,t)=>r(e,t,s);let Qe=class extends m.Disposable{constructor(s,r){super(),this._commandService=s,this._featureCalculationManagerService=r,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(s=>{if(s.id===wt.id){const r=s.params;if(r==null)return;const{featureId:e,calculationParam:t}=r;this._featureCalculationManagerService.register(e,t)}else if(s.id===Tt.id){const r=s.params;if(r==null)return;const{featureId:e}=r;this._featureCalculationManagerService.remove(e)}}))}};Qe=Li([m.OnLifecycle(m.LifecycleStages.Ready,Qe),ar(0,m.ICommandService),ar(1,ft)],Qe);var wi=Object.defineProperty,Ti=Object.getOwnPropertyDescriptor,Oi=(s,r,e,t)=>{for(var n=t>1?void 0:t?Ti(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&wi(r,e,n),n},or=(s,r)=>(e,t)=>r(e,t,s);let Ge=class extends m.Disposable{constructor(s,r){super(),this._commandService=s,this._otherFormulaManagerService=r,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(s=>{if(s.id===xt.id){const r=s.params;if(r==null)return;this._otherFormulaManagerService.register(r)}else if(s.id===vt.id){const r=s.params;if(r==null)return;this._otherFormulaManagerService.remove(r)}}))}};Ge=Oi([m.OnLifecycle(m.LifecycleStages.Ready,Ge),or(0,m.ICommandService),or(1,$t)],Ge);var Ui=Object.defineProperty,Ii=Object.getOwnPropertyDescriptor,Mi=(s,r,e,t)=>{for(var n=t>1?void 0:t?Ii(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&Ui(r,e,n),n},ur=(s,r)=>(e,t)=>r(e,t,s);let He=class extends m.Disposable{constructor(s,r){super(),this._commandService=s,this._superTableService=r,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(s=>{if(s.id===at.id){const r=s.params;if(r==null)return;const{unitId:e,tableName:t,reference:n}=r;this._superTableService.registerTable(e,t,n)}else if(s.id===ot.id){const r=s.params;if(r==null)return;const{unitId:e,tableName:t}=r;this._superTableService.remove(e,t)}else if(s.id===Pt.id){const r=s.params;if(r==null)return;const{tableOption:e,tableOptionType:t}=r;this._superTableService.registerTableOptionMap(e,t)}}))}};He=Mi([m.OnLifecycle(m.LifecycleStages.Ready,He),ur(0,m.ICommandService),ur(1,kt)],He);var xi=Object.defineProperty,vi=Object.getOwnPropertyDescriptor,Pi=(s,r,e,t)=>{for(var n=t>1?void 0:t?vi(r,e):r,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(t?a(r,e,n):a(n))||n);return t&&n&&xi(r,e,n),n},Vi=(s,r)=>(e,t)=>r(e,t,s);const Bi="base-formula-engine";exports.UniverFormulaEnginePlugin=class extends m.Plugin{constructor(r,e){super(Bi),this._config=r,this._injector=e}onStarting(){this._initialize()}_initialize(){var e;const r=[[he,{useClass:br}],[ft,{useClass:wr}],[ht,{useClass:yn}],[exports.FormulaDataModel],[it],[je],[Qe]];(e=this._config)!=null&&e.notExecuteFormula||r.push([exports.CalculateFormulaService],[$t,{useClass:Tr}],[kt,{useClass:is}],[Te,{useClass:yt}],[J,{useClass:bt}],[ke],[$e],[Ge],[He],[Ie],[be],[xe],[Ee],[yr],[We],[Ze],[Fr],[Je],[Xe],[et],[tt],[rt],[Lr]),r.forEach(t=>this._injector.add(t))}onReady(){this._injector.get(exports.FormulaDataModel).initFormulaData()}};exports.UniverFormulaEnginePlugin=Pi([Vi(1,D.Inject(D.Injector))],exports.UniverFormulaEnginePlugin);exports.ArrayValueObject=ne;exports.BaseFunction=M;exports.BaseReferenceObject=we;exports.BaseValueObject=le;exports.BooleanValueObject=$;exports.ErrorType=h;exports.ErrorValueObject=_;exports.FUNCTION_NAMES_ARRAY=Bt;exports.FUNCTION_NAMES_COMPATIBILITY=lt;exports.FUNCTION_NAMES_CUBE=dn;exports.FUNCTION_NAMES_DATABASE=mn;exports.FUNCTION_NAMES_DATE=gn;exports.FUNCTION_NAMES_ENGINEERING=Cn;exports.FUNCTION_NAMES_FINANCIAL=pn;exports.FUNCTION_NAMES_INFORMATION=En;exports.FUNCTION_NAMES_LOGICAL=Nn;exports.FUNCTION_NAMES_LOOKUP=ze;exports.FUNCTION_NAMES_MATH=K;exports.FUNCTION_NAMES_STATISTICAL=ie;exports.FUNCTION_NAMES_TEXT=An;exports.FUNCTION_NAMES_UNIVER=Rn;exports.FUNCTION_NAMES_WEB=Sn;exports.FeatureCalculationManagerService=wr;exports.FormulaExecuteStageType=W;exports.FormulaExecutedStateType=Re;exports.FunctionService=br;exports.FunctionType=lr;exports.IFeatureCalculationManagerService=ft;exports.IFunctionService=he;exports.LexerNode=F;exports.LexerTreeBuilder=it;exports.NumberValueObject=p;exports.OtherFormulaManagerService=Tr;exports.RangeReferenceObject=Sr;exports.RemoveDefinedNameMutation=ot;exports.RemoveFeatureCalculationMutation=Tt;exports.RemoveOtherFormulaMutation=vt;exports.RemoveSuperTableMutation=Er;exports.SetArrayFormulaDataMutation=Ye;exports.SetArrayFormulaDataUndoMutationFactory=Kr;exports.SetDefinedNameMutation=at;exports.SetFeatureCalculationMutation=wt;exports.SetFormulaCalculationNotificationMutation=qe;exports.SetFormulaCalculationResultMutation=It;exports.SetFormulaCalculationStartMutation=Ot;exports.SetFormulaCalculationStopMutation=Ut;exports.SetFormulaDataMutation=Mt;exports.SetOtherFormulaMutation=xt;exports.SetSuperTableMutation=pr;exports.SetSuperTableOptionMutation=Pt;exports.StringValueObject=k;exports.ValueObjectFactory=ye;exports.compareToken=R;exports.convertUnitDataToRuntime=fr;exports.generateStringWithSequence=mr;exports.includeFormulaLexerToken=vr;exports.initSheetFormulaData=Cr;exports.isFormulaLexerToken=Nt;exports.isInDirtyRange=cr;exports.matchToken=w;exports.normalizeSheetName=Pr;exports.sequenceNodeType=q;
|
|
1
|
+
"use strict";var mn=Object.defineProperty;var gn=(t,n,e)=>n in t?mn(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var p=(t,n,e)=>(gn(t,typeof n!="symbol"?n+"":n,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@univerjs/core"),V=require("@wendellhu/redi"),Et=require("rxjs");function Rr(t,n,e,r,s){for(let i=0,a=t.length;i<a;i++){const o=t[i];if(n!==o.unitId||e!==o.sheetId)continue;const{startRow:u,startColumn:c,endRow:l,endColumn:h}=o.range;if(r>=u&&r<=l&&s>=c&&s<=h)return!0}return!1}var f=(t=>(t.DIV_BY_ZERO="#DIV/0!",t.NAME="#NAME!",t.VALUE="#VALUE!",t.NUM="#NUM!",t.NA="#N/A",t.CYCLE="#CYCLE!",t.REF="#REF!",t.SPILL="#SPILL!",t.CALC="#CALC!",t.ERROR="#ERROR!",t.CONNECT="#GETTING_DATA",t.NULL="#NULL!",t))(f||{});const Ut=new Set(Object.values(f));var pr=(t=>(t[t.Financial=0]="Financial",t[t.Date=1]="Date",t[t.Math=2]="Math",t[t.Statistical=3]="Statistical",t[t.Lookup=4]="Lookup",t[t.Database=5]="Database",t[t.Text=6]="Text",t[t.Logical=7]="Logical",t[t.Information=8]="Information",t[t.Engineering=9]="Engineering",t[t.Cube=10]="Cube",t[t.Compatibility=11]="Compatibility",t[t.Web=12]="Web",t[t.Array=13]="Array",t[t.Univer=14]="Univer",t[t.User=15]="User",t))(pr||{}),K=(t=>(t.PLUS="+",t.MINUS="-",t.MULTIPLY="*",t.DIVIDED="/",t.CONCATENATE="&",t.POWER="^",t.EQUALS="=",t.NOT_EQUAL="<>",t.GREATER_THAN=">",t.GREATER_THAN_OR_EQUAL=">=",t.LESS_THAN="<",t.LESS_THAN_OR_EQUAL="<=",t))(K||{}),y=(t=>(t.EQUALS="=",t.NOT_EQUAL="<>",t.GREATER_THAN=">",t.GREATER_THAN_OR_EQUAL=">=",t.LESS_THAN="<",t.LESS_THAN_OR_EQUAL="<=",t))(y||{});const Xe=new Map([["<>",3],["<",3],[">=",3],["=",3],[">",3],["<=",3],["&",2],["+",2],["-",2],["/",1],["*",1],["^",0]]),Oe=new Set(Xe.keys()),Rn=new Set(["=","<>",">",">=","<","<="]);var O=(t=>(t.OPEN_BRACKET="(",t.CLOSE_BRACKET=")",t.COMMA=",",t.SINGLE_QUOTATION="'",t.DOUBLE_QUOTATION='"',t.OPEN_BRACES="{",t.CLOSE_BRACES="}",t.COLON=":",t.OPEN_SQUARE_BRACKET="[",t.CLOSE_SQUARE_BRACKET="]",t))(O||{}),ie=(t=>(t.PERCENTAGE="%",t.POUND="#",t))(ie||{});const pn=new Set(["%","#"]);var $=(t=>(t.AT="@",t.MINUS="-",t))($||{});const Dr=[...Object.values(y),...Object.values(K),...Object.values(O),...Object.values(ie),...Object.values($)];function We(t){return Dr.includes(t)}function Dn(t){for(const n of Dr)if(t.indexOf(n)>-1)return!0;return!1}function _n(t){return t[0]==="'"&&t[t.length-1]==="'"?t.substring(1,t.length-1):t}function _r(t){const n={};return Object.keys(t).forEach(e=>{const r=t[e];if(r==null)return!0;n[e]==null&&(n[e]={}),Object.keys(r).forEach(s=>{const i=r[s];n[e][s]=new g.ObjectMatrix(i)})}),n}const Ft={id:"formula.mutation.register-function",type:g.CommandType.MUTATION,handler:()=>!0};class lt{constructor(n){p(this,"_cache");this._cache=new g.LRUMap(n)}set(n,e){const r=this._hash(n);this._cache.set(r,e)}get(n){const e=this._hash(n);return this._cache.get(e)}clear(){this._cache.clear()}_hash(n){return g.hashAlgorithm(n)}}const Ve="((?![\\[\\]\\/?*\\\\]).)*!",le="$",Mt="\\s*?:\\s*?",Vt=`\\${le}?[A-Za-z]+\\${le}?[0-9]+`,En=`^(${$.AT})?(${g.UNIT_NAME_REGEX})?(${Ve})?${Vt}${Mt}${Vt}$`,ht=`^(${g.UNIT_NAME_REGEX})?(${Ve})?\\s*?${Vt}(${ie.POUND})?$`,Er=`^(${g.UNIT_NAME_REGEX})?(${Ve})?\\${le}?[0-9]+${Mt}\\${le}?[0-9]+$`,Cr=`^(${g.UNIT_NAME_REGEX})?(${Ve})?\\${le}?[A-Za-z]+${Mt}\\${le}?[A-Za-z]+$`,Cn=`^(${g.UNIT_NAME_REGEX})?(${Ve})?\\s*?\\${le}?[0-9]+$`,yn=`^(${g.UNIT_NAME_REGEX})?(${Ve})?\\s*?\\${le}?[A-Za-z]+$`,yr="[.*?]",bn="{.*?}";function wn(t){return new RegExp(ht).test(t)||new RegExp(En).test(t)||new RegExp(Er).test(t)||new RegExp(Cr).test(t)}const ge="P_1",ce="R_1",Se="L_1",je="LR_1",br="LO_1",Ln="LET",Fe="LAMBDA";var I=(t=>(t[t.NORMAL=0]="NORMAL",t[t.NUMBER=1]="NUMBER",t[t.STRING=2]="STRING",t[t.FUNCTION=3]="FUNCTION",t[t.REFERENCE=4]="REFERENCE",t[t.ARRAY=5]="ARRAY",t))(I||{});function wr(t){let n="";for(const e of t)typeof e=="string"?n+=e:n+=e.token;return n}class x{constructor(){p(this,"_parent");p(this,"_token",ce);p(this,"_children",[]);p(this,"_lambdaId");p(this,"_functionDefinitionPrivacyVar");p(this,"_lambdaParameter","");p(this,"_startIndex",-1);p(this,"_endIndex",-1)}dispose(){var n;this._children.forEach(e=>{typeof e!="string"&&e.dispose()}),(n=this._functionDefinitionPrivacyVar)==null||n.clear(),this._parent=null}getStartIndex(){return this._startIndex}getLambdaId(){return this._lambdaId}setLambdaId(n){this._lambdaId=n}getFunctionDefinitionPrivacyVar(){return this._functionDefinitionPrivacyVar}setLambdaPrivacyVar(n){this._functionDefinitionPrivacyVar=n}getLambdaParameter(){return this._lambdaParameter}setLambdaParameter(n){this._lambdaParameter=n}getParent(){return this._parent}setParent(n){this._parent=n}getChildren(){return this._children}setChildren(n){this._children=n}addChildren(n){this._children.push(n)}addChildrenFirst(n){this._children.unshift(n)}getToken(){return this._token}setToken(n){this._token=n}setIndex(n,e){this._startIndex=n,this._endIndex=e}replaceChild(n,e){const r=this._getIndexInParent(n);r!=null&&(this.getChildren().splice(r,1,e),e.setParent(this))}changeToParent(n){const e=this.getParent();e&&e.removeChild(this),this.setParent(n),n.getChildren().push(this)}removeChild(n){const e=this._getIndexInParent(n);e!=null&&this.getChildren().splice(e,1)}serialize(){const n=this.getToken(),e=this.getChildren(),r=[],s=e.length;for(let i=0;i<s;i++){const a=e[i];a instanceof x?r.push(a.serialize()):r.push(a)}return{token:n,st:this._startIndex,ed:this._endIndex,children:r}}_getIndexInParent(n){const e=this.getChildren(),r=e.length;for(let s=0;s<r;s++)if(e[s]===n)return s}}const Lr=1e5,Ct=new lt(Lr),yt=new lt(Lr);class ft extends g.Disposable{constructor(){super(...arguments);p(this,"_currentLexerNode",new x);p(this,"_upLevel",0);p(this,"_segment","");p(this,"_bracketState",[]);p(this,"_squareBracketState",0);p(this,"_bracesState",0);p(this,"_singleQuotationState",0);p(this,"_doubleQuotationState",0);p(this,"_lambdaState",!1);p(this,"_colonState",!1);p(this,"_tableBracketState",!1)}dispose(){this._resetTemp(),this._currentLexerNode.dispose(),Ct.clear(),yt.clear()}getUpLevel(){return this._upLevel}isColonClose(){return this._colonState===!1}isColonOpen(){return this._colonState===!0}isDoubleQuotationClose(){return this._doubleQuotationState===0}isLambdaOpen(){return this._lambdaState===!0}isLambdaClose(){return this._lambdaState===!1}isSingleQuotationClose(){return this._singleQuotationState===0}isBracesClose(){return this._bracesState===0}isBracketClose(){return this._bracketState.length===0}isSquareBracketClose(){return this._squareBracketState===0}getCurrentLexerNode(){return this._currentLexerNode}getFunctionAndParameter(e,r){const s=this._getCurrentParamIndex(e,r);if(s==null||s===f.VALUE)return;const i=s[0];if(typeof i=="string")return;let a=i.getParent(),o=i;for(;a;){const u=a.getToken();if(u!==ge&&!We(u)&&a.getStartIndex()!==-1){const c=a.getChildren().indexOf(o);return{functionName:u,paramIndex:c}}o=a,a=a.getParent()}}moveFormulaRefOffset(e,r,s){const i=this.sequenceNodesBuilder(e);if(i==null)return e;const a=[];for(let o=0,u=i.length;o<u;o++){const c=i[o];if(typeof c=="string"||c.nodeType!==I.REFERENCE){a.push(c);continue}const{token:l}=c,h=g.deserializeRangeWithSheet(l),{range:m,sheetName:_,unitId:E}=h,R=g.Rectangle.moveOffset(m,r,s);let D="";g.isValidRange(R)?D=g.serializeRangeToRefString({range:R,unitId:E,sheetName:_}):D=f.REF,a.push({...c,token:D})}return`=${wr(a)}`}checkIfAddBracket(e){let r=0,s=e.length-1,i=e[s];for(;(i===O.CLOSE_BRACKET||i===" ")&&s>=0;)i===O.CLOSE_BRACKET&&r++,i=e[--s];const a=this._getCurrentParamIndex(e,e.length-2);if(a==null||a===f.VALUE)return 0;const o=a[0];if(typeof o=="string")return 0;let u=o.getParent(),c=0;for(;u;){const l=u.getToken();l!==ge&&l!==O.COLON&&u.getStartIndex()!==-1&&l.toUpperCase()!==Fe&&(r===0?c+=1:r--),u=u.getParent()}return c}sequenceNodesBuilder(e){const r=yt.get(e);if(r)return[...r];const s=this._getSequenceArray(e);if(s.length===0)return;const i=this.getSequenceNode(s);return yt.set(e,[...i]),i}getSequenceNode(e){const r=[];let s=!1;for(let i=0,a=e.length;i<a;i++){const o=e[i],u=e[i-1],{segment:c,currentString:l,cur:h}=o;if(l===O.DOUBLE_QUOTATION&&(s=!0),(c!==""||i===0)&&i!==a-1){r.push(l);continue}let m=(u==null?void 0:u.segment)||"";const _=i-m.length;let E=i-1;const R=i-1;if(i===a-1&&this._isLastMergeString(l)&&(m+=l,E+=1),m===""||Xe.has(m)){r.push(l);continue}const D=m.trim(),b=this._replacePrefixString(D);s===!0&&D[D.length-1]===O.DOUBLE_QUOTATION?(s=!1,this._pushSequenceNode(r,{nodeType:I.STRING,token:m,startIndex:_,endIndex:E},R)):new RegExp(ht).test(b)?this._pushSequenceNode(r,{nodeType:I.REFERENCE,token:m,startIndex:_,endIndex:E},R):g.Tools.isStringNumber(D)?this._pushSequenceNode(r,{nodeType:I.NUMBER,token:m,startIndex:_,endIndex:E},R):D.length>0&&this._pushSequenceNode(r,{nodeType:I.FUNCTION,token:m,startIndex:_,endIndex:E},R),(i!==a-1||!this._isLastMergeString(l))&&r.push(l)}return this._mergeSequenceNodeReference(r)}_getCurrentParamIndex(e,r){return this._nodeMaker(e,void 0,r)}_isLastMergeString(e){return e===O.DOUBLE_QUOTATION||g.Tools.isStringNumber(e)||!We(e)}_mergeSequenceNodeReference(e){const r=[],s=e.length;let i=0;for(;i<s;){const a=e[i];if(typeof a=="string"){const o=e[i-1];if(a.trim()===O.CLOSE_BRACES&&o!=null&&typeof o!="string"&&o.nodeType===I.FUNCTION&&o.token.trim().substring(0,1)===O.OPEN_BRACES){o.nodeType=I.ARRAY,o.token+=a,o.endIndex+=a.length,i++;continue}r.push(a)}else{const o=e[i+1],u=e[i+2];o===O.COLON&&typeof a!="string"&&u!=null&&typeof u!="string"&&wn((a.token+o+u.token).trim())&&(a.nodeType=I.REFERENCE,a.token+=o+u.token,a.endIndex=u.endIndex,i+=2),r.push(a)}i++}return r}_pushSequenceNode(e,r,s){const i=s-r.startIndex+1;e.splice(e.length-i,i,r)}_replacePrefixString(e){return e.replace(new RegExp($.AT,"g"),"").replace(new RegExp($.MINUS,"g"),"")}nodeMakerTest(e){return this._nodeMaker(e)}treeBuilder(e,r=!0,s){if(r===!0){const l=Ct.get(e);if(l)return l}this._resetCurrentLexerNode(),this._currentLexerNode.setToken(ce);const i=[];let a=this._nodeMaker(e,i);if(a===f.VALUE||i.length===0)return a;let o=!1,u="";if(s){const{hasDefinedName:l,sequenceString:h}=s(i);o=l,u=h}if(o&&(this._resetCurrentLexerNode(),this._currentLexerNode.setToken(ce),a=this._nodeMaker(`=${u}`),a===f.VALUE))return a;const c=this._getTopNode(this._currentLexerNode);return c&&(this._currentLexerNode=c),r&&(this._suffixExpressionHandler(this._currentLexerNode),Ct.set(e,this._currentLexerNode)),this._currentLexerNode}_suffixExpressionHandler(e){var o,u;const r=e.getChildren();if(!r)return;const s=r.length,i=[],a=[];for(let c=0;c<s;c++){const l=r[c];if(l instanceof x)this._suffixExpressionHandler(l),i.push(l);else{const h=l.trim();if(h==="")continue;if(Oe.has(h)){for(;a.length>0;){const m=(o=a[a.length-1])==null?void 0:o.trim();if(!m||m===O.OPEN_BRACKET)break;const _=Xe.get(m),E=Xe.get(h);if(!_||!E)break;if(E>_)i.push(a.pop());else break}a.push(l)}else if(h===O.OPEN_BRACKET)a.push(l);else if(h===O.CLOSE_BRACKET)for(;a.length>0;){const m=(u=a[a.length-1])==null?void 0:u.trim();if(!m)break;if(m===O.OPEN_BRACKET){a.pop();break}i.push(a.pop())}else i.push(l)}}for(;a.length>0;)i.push(a.pop());e.setChildren(i)}_resetCurrentLexerNode(){this._currentLexerNode=new x}_resetSegment(){this._segment=""}_openBracket(e=0){this._bracketState.push(e)}_closeBracket(){this._bracketState.pop()}_openSquareBracket(){this._squareBracketState+=1}_closeSquareBracket(){this._squareBracketState-=1}_getCurrentBracket(){const e=this._bracketState;return e[e.length-1]}_openBraces(){this._bracesState+=1}_closeBraces(){this._bracesState-=1}_openSingleQuotation(){this._singleQuotationState+=1}_closeSingleQuotation(){this._singleQuotationState-=1}_openDoubleQuotation(){this._doubleQuotationState+=1}_closeDoubleQuotation(){this._doubleQuotationState-=1}_openLambda(){this._lambdaState=!0}_closeLambda(){this._lambdaState=!1}_openColon(e){this._upLevel=e,this._colonState=!0}_closeColon(){this._upLevel=0,this._colonState=!1}_isTableBracket(){return this._tableBracketState}_openTableBracket(){this._tableBracketState=!0}_closeTableBracket(){this._tableBracketState=!1}_getLastChildCurrentLexerNode(){const e=this._currentLexerNode.getChildren();if(e&&e.length>0){const r=e[e.length-1];if(r instanceof x)return r}return!1}_getLastChildCurrent(){const e=this._currentLexerNode.getChildren();return e&&e.length>0?e[e.length-1]:!1}_setParentCurrentLexerNode(){const e=this._currentLexerNode.getParent();return e?(this._currentLexerNode=e,!0):!1}_setAncestorCurrentLexerNode(){var s,i,a,o,u,c;const e=(s=this._currentLexerNode)==null?void 0:s.getParent();let r=!1;if(e&&e.getToken()===Se){if((i=e==null?void 0:e.getParent())!=null&&i.getParent()){const l=(o=(a=this._currentLexerNode.getParent())==null?void 0:a.getParent())==null?void 0:o.getParent();l&&(this._currentLexerNode=l),r=!0}}else if(e!=null&&e.getParent()){const l=(u=this._currentLexerNode.getParent())==null?void 0:u.getParent();l&&(this._currentLexerNode=l),r=!0}for(let l=0;l<this._upLevel;l++){const h=(c=this._currentLexerNode)==null?void 0:c.getParent();h&&(this._currentLexerNode=h),this._currentLexerNode?r=!0:r=!1}return r}_segmentCount(){return this._segment.trim().length}_pushSegment(e){this._segment+=e}_pushNodeToChildren(e,r=!1){if(e!==""){const s=this._currentLexerNode.getChildren();if(!(e instanceof x)&&this.isColonOpen()){const i=new x;i.setToken(e),i.setParent(this._currentLexerNode),e=i}r?s.unshift(e):s.push(e)}this.isColonOpen()&&(this._setAncestorCurrentLexerNode(),this._closeColon())}_setCurrentLexerNode(e,r=!1){this._pushNodeToChildren(e,r),e.setParent(this._currentLexerNode),this._currentLexerNode=e}_newAndPushCurrentLexerNode(e,r,s=!1){const i=new x;i.setToken(e),i.setIndex(r-e.length,r-1),this._setCurrentLexerNode(i,s)}_getTopNode(e){let r=e;for(;r!=null&&r.getParent();)r=r.getParent();return r}_removeLastChild(){this._currentLexerNode.getChildren().splice(-1)}_findPreviousToken(e,r){for(;r>=0;){const s=e[r];if(s!==" ")return s;r--}}_negativeCondition(e){return!!(Oe.has(e)||e===O.OPEN_BRACKET||e===O.COMMA||e==="")}_getSequenceArray(e){const r=[];return this._nodeMaker(e,r),r}_resetTemp(){this._currentLexerNode=new x,this._upLevel=0,this._segment="",this._bracketState=[],this._bracesState=0,this._singleQuotationState=0,this._doubleQuotationState=0,this._lambdaState=!1,this._colonState=!1}_checkSimilarErrorToken(e,r,s){if(e!==ie.POUND)return!0;let i=s[++r];for(;i===" ";)i=s[++r];return!!We(i)}_nodeMaker(e,r,s){e.substring(0,1)===K.EQUALS&&(e=e.substring(1));const i=e.split(""),a=i.length;let o=0;for(this._resetTemp();o<a;){const u=i[o];if(s===o)return[this._currentLexerNode,u];if(u===O.OPEN_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())if(this._segmentCount()>0||this.isLambdaOpen()){this.isLambdaClose()&&(this._newAndPushCurrentLexerNode(this._segment,o),this._resetSegment()),this._openBracket(1),this._closeLambda();const c=i[o+1];if(c&&c===O.CLOSE_BRACKET){if(!this._setParentCurrentLexerNode()&&o!==a-1)return f.VALUE;o++}else c&&this._newAndPushCurrentLexerNode(ge,o)}else this._pushNodeToChildren(u),this._openBracket(0);else if(u===O.CLOSE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()){this._pushNodeToChildren(this._segment),this._resetSegment();const c=this._getCurrentBracket();if(c===0)this._pushNodeToChildren(u);else if(c===1){const l=i[o+1];if(l&&l===O.OPEN_BRACKET){if(!this._setParentCurrentLexerNode()&&o!==a-1)return f.VALUE;this._newAndPushCurrentLexerNode(Se,o,!0),this._openLambda()}else if(!this._setAncestorCurrentLexerNode()&&o!==a-1)return f.VALUE}else return f.VALUE;this._closeBracket()}else if(u===O.OPEN_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._pushSegment(u),this._openBraces();else if(u===O.CLOSE_BRACES&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._pushSegment(u),this._pushNodeToChildren(this._segment),this._resetSegment(),this._closeBraces();else if(u===O.OPEN_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._segment.length>0&&this._openTableBracket(),this._pushSegment(u),this._openSquareBracket();else if(u===O.CLOSE_SQUARE_BRACKET&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose())this._closeSquareBracket(),this.isSquareBracketClose()?(this._pushSegment(u),this._isTableBracket()&&(this._pushNodeToChildren(this._segment),this._resetSegment()),this._closeTableBracket()):this._pushSegment(u);else if(u===O.DOUBLE_QUOTATION&&this.isSingleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){if(this.isDoubleQuotationClose())this._openDoubleQuotation();else{const c=i[o+1];c&&c===O.DOUBLE_QUOTATION?o++:this._closeDoubleQuotation()}this._pushSegment(u)}else if(u===O.SINGLE_QUOTATION&&this.isDoubleQuotationClose()){if(this.isSingleQuotationClose())this._openSingleQuotation();else{const c=i[o+1];c&&c===O.SINGLE_QUOTATION?o++:this._closeSingleQuotation()}this._pushSegment(u)}else if(u===O.COMMA&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){const c=this._getCurrentBracket();if(c===1||c==null){if(this._pushNodeToChildren(this._segment),this._resetSegment(),!this._setParentCurrentLexerNode()&&o!==a-1&&c!=null)return f.VALUE;this._newAndPushCurrentLexerNode(ge,o)}else return f.VALUE}else if(u===O.COLON&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isBracesClose()&&this.isSquareBracketClose()){const c=new x;c.setToken(u);const l=new x;l.setToken(ge),l.setParent(c);const h=new x;h.setToken(ge),h.setParent(c),c.getChildren().push(l,h);let m=c,_=0;if(this._segmentCount()>0){let E,R,D=0;const b=this._segment.trim(),w=b[0],S=b[1];if(w===$.MINUS&&(E=new x,E.setToken($.MINUS),D++),(w===$.AT||S===$.AT)&&(R=new x,R.setToken($.AT),E&&(E.addChildren(R),R.setParent(E)),D++),D>0&&(this._segment=b.slice(D)),_=D,R)if(R.addChildren(c),c.setParent(R),R.getParent()){const k=R.getParent();k&&(m=k)}else m=R;else E&&(m=E,E.addChildren(c),c.setParent(E));const L=new x;L.setToken(this._segment),L.setParent(l),l.getChildren().push(L),this._resetSegment()}else{const E=this._getLastChildCurrentLexerNode();E&&E.changeToParent(l)}this._setCurrentLexerNode(m),this._currentLexerNode=h,this._openColon(_)}else if(pn.has(u)&&this._checkSimilarErrorToken(u,o,i)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()){this._pushNodeToChildren(this._segment);const c=new x;c.setToken(u);const l=this._getLastChildCurrent();l instanceof x?l.changeToParent(c):l!==!1&&(c.getChildren().push(l),this._removeLastChild()),this._pushNodeToChildren(c),c.setParent(this._currentLexerNode),this._resetSegment()}else if(Oe.has(u)&&this.isSingleQuotationClose()&&this.isDoubleQuotationClose()&&this.isSquareBracketClose()){let c=this._segment.trim();if(u===K.MINUS&&c===""){const l=this._findPreviousToken(i,o-1)||"";if(this._negativeCondition(l)){this._pushSegment(K.MINUS),r==null||r.push({segment:this._segment,currentString:u,cur:o,currentLexerNode:this._currentLexerNode}),o++;continue}}else this._segment.length>0&&c===""?c=this._segment:(this._pushNodeToChildren(this._segment),c="");if(u===K.LESS_THAN||u===K.GREATER_THAN){const l=i[o+1];l&&Oe.has(u+l)?(this._pushNodeToChildren(c+u+l),o++):this._pushNodeToChildren(c+u)}else this._pushNodeToChildren(c+u);this._resetSegment()}else this._pushSegment(u);r==null||r.push({segment:this._segment,currentString:u,cur:o,currentLexerNode:this._currentLexerNode}),o++}this._pushNodeToChildren(this._segment)}}var Sn=Object.defineProperty,Pn=Object.getOwnPropertyDescriptor,Vn=(t,n,e,r)=>{for(var s=r>1?void 0:r?Pn(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Sn(n,e,s),s},Zt=(t,n)=>(e,r)=>n(e,r,t);exports.FormulaDataModel=class extends g.Disposable{constructor(e,r){super();p(this,"_formulaData",{});p(this,"_arrayFormulaRange",{});p(this,"_arrayFormulaCellData",{});this._currentUniverService=e,this._lexerTreeBuilder=r}clearPreviousArrayFormulaCellData(e){Object.keys(e).forEach(r=>{const s=e[r];if(s==null)return!0;Object.keys(s).forEach(i=>{var c,l,h,m;const a=s[i],o=(l=(c=this._arrayFormulaRange)==null?void 0:c[r])==null?void 0:l[i];if(o==null)return!0;let u=new g.ObjectMatrix;((h=this._arrayFormulaCellData[r])==null?void 0:h[i])!=null&&(u=new g.ObjectMatrix((m=this._arrayFormulaCellData[r])==null?void 0:m[i])),a.forValue((_,E)=>{var L;const R=(L=o==null?void 0:o[_])==null?void 0:L[E];if(R==null)return!0;const{startRow:D,startColumn:b,endRow:w,endColumn:S}=R;for(let k=D;k<=w;k++)for(let j=b;j<=S;j++)u.setValue(k,j,null)}),this._arrayFormulaCellData[r]&&(this._arrayFormulaCellData[r][i]=u.getData())})})}mergeArrayFormulaCellData(e){Object.keys(e).forEach(r=>{const s=e[r];if(s==null)return!0;this._arrayFormulaRange[r]==null&&(this._arrayFormulaRange[r]={}),this._arrayFormulaCellData[r]==null&&(this._arrayFormulaCellData[r]={}),Object.keys(s).forEach(i=>{var c,l,h,m;const a=s[i];let o=new g.ObjectMatrix,u=new g.ObjectMatrix;((c=this._arrayFormulaRange[r])==null?void 0:c[i])!=null&&(o=new g.ObjectMatrix((l=this._arrayFormulaRange[r])==null?void 0:l[i])),((h=this._arrayFormulaCellData[r])==null?void 0:h[i])!=null&&(u=new g.ObjectMatrix((m=this._arrayFormulaCellData[r])==null?void 0:m[i])),a.forValue((_,E)=>{const R=o==null?void 0:o.getValue(_,E);if(R==null)return!0;const{startRow:D,startColumn:b,endRow:w,endColumn:S}=R;for(let L=D;L<=w;L++)for(let k=b;k<=S;k++)u.setValue(L,k,null)}),a.forValue((_,E,R)=>{u.setValue(_,E,R)}),this._arrayFormulaCellData[r]&&(this._arrayFormulaCellData[r][i]=u.getData())})})}getFormulaData(){return this._formulaData}setFormulaData(e){this._formulaData=e}setArrayFormulaRange(e){this._arrayFormulaRange=e}getArrayFormulaRange(){return this._arrayFormulaRange}setArrayFormulaCellData(e){this._arrayFormulaCellData=e}getArrayFormulaCellData(){return this._arrayFormulaCellData}mergeArrayFormulaRange(e){Object.keys(e).forEach(r=>{const s=e[r];if(s==null)return!0;this._arrayFormulaRange[r]||(this._arrayFormulaRange[r]={}),Object.keys(s).forEach(i=>{var u,c;const a=new g.ObjectMatrix(s[i]);let o=new g.ObjectMatrix;(u=this._arrayFormulaRange[r])!=null&&u[i]&&(o=new g.ObjectMatrix((c=this._arrayFormulaRange[r])==null?void 0:c[i])),a.forValue((l,h,m)=>{o.setValue(l,h,m)}),this._arrayFormulaRange[r]&&(this._arrayFormulaRange[r][i]=o.getData())})})}deleteArrayFormulaRange(e,r,s,i){var u;const a=(u=this._arrayFormulaRange[e])==null?void 0:u[r];if(a==null)return;const o=new g.ObjectMatrix(a);o.getValue(s,i)&&(o.realDeleteValue(s,i),this._arrayFormulaRange[e]&&(this._arrayFormulaRange[e][r]=o.getData()))}initFormulaData(){this._currentUniverService.getAllUniverSheetsInstance();const e=this._currentUniverService.getCurrentUniverSheetInstance(),r=e.getUnitId();this._formulaData[r]={},e.getSheets().forEach(i=>{const a=i.getCellMatrix(),o=i.getSheetId();Sr(this._formulaData,r,o,a)})}getCalculateData(){const e=this._currentUniverService.getAllUniverSheetsInstance(),r={},s={};for(const i of e){const a=i.getUnitId(),o=i.getSheets(),u={},c={};for(const l of o){const h=l.getSheetId(),m=l.getConfig();u[h]={cellData:new g.ObjectMatrix(m.cellData),rowCount:m.rowCount,columnCount:m.columnCount},c[l.getName()]=l.getSheetId()}r[a]=u,s[a]=c}return{allUnitData:r,unitSheetNameMap:s}}updateFormulaData(e,r,s){const i=new g.ObjectMatrix(s),a=this.getFormulaIdMap(e,r),o=new Map,u=this._formulaData;u[e]==null&&(u[e]={});const c=u[e];c[r]==null&&(c[r]={});const l=new g.ObjectMatrix(c[r]);i.forValue((h,m,_)=>{const E=(_==null?void 0:_.f)||"",R=(_==null?void 0:_.si)||"",D=g.isFormulaString(E),b=g.isFormulaId(R);if(D&&b)l.setValue(h,m,{f:E,si:R}),a.set(R,{f:E,r:h,c:m});else if(D&&!b)l.setValue(h,m,{f:E});else if(!D&&b)l.setValue(h,m,{f:"",si:R});else if(!D&&!b&&l.getValue(h,m)){const w=l.getValue(h,m),S=(w==null?void 0:w.f)||"",L=(w==null?void 0:w.si)||"";g.isFormulaString(S)&&g.isFormulaId(L)&&o.set(L,S),l.realDeleteValue(h,m)}}),l.forValue((h,m,_)=>{const E=(_==null?void 0:_.f)||"",R=(_==null?void 0:_.si)||"";if(g.isFormulaId(R)){const D=a.get(R),b=o.get(R);if(D&&!g.isFormulaString(E)){const w=D.f,S=m-D.c,L=h-D.r;l.setValue(h,m,{f:w,si:R,x:S,y:L})}else if(typeof b=="string"){const w=_.x||0,S=_.y||0,L=this._lexerTreeBuilder.moveFormulaRefOffset(b,w,S);o.set(R,{r:h,c:m,f:L}),l.setValue(h,m,{f:L,si:R})}else if(typeof b=="object"){const w=m-b.c,S=h-b.r;l.setValue(h,m,{f:b.f,si:R,x:w,y:S})}}})}updateArrayFormulaRange(e,r,s){var u;const i=(u=this._arrayFormulaRange[e])==null?void 0:u[r];if(!i)return;const a=new g.ObjectMatrix(i);new g.ObjectMatrix(s).forValue((c,l,h)=>{if((a==null?void 0:a.getValue(c,l))==null)return!0;const _=(h==null?void 0:h.f)||"",E=(h==null?void 0:h.si)||"",R=g.isFormulaString(_),D=g.isFormulaId(E);!R&&!D&&a.realDeleteValue(c,l)})}updateArrayFormulaCellData(e,r,s){var l,h;const i=(l=this._arrayFormulaRange[e])==null?void 0:l[r];if(!i)return;const a=new g.ObjectMatrix(i),o=(h=this._arrayFormulaCellData[e])==null?void 0:h[r];if(!o)return;const u=new g.ObjectMatrix(o);new g.ObjectMatrix(s).forValue((m,_,E)=>{const R=a==null?void 0:a.getValue(m,_);if(R==null)return!0;const D=(E==null?void 0:E.f)||"",b=(E==null?void 0:E.si)||"",w=g.isFormulaString(D),S=g.isFormulaId(b);if(!w&&!S){const{startRow:L,startColumn:k,endRow:j,endColumn:Q}=R;for(let A=L;A<=j;A++)for(let P=k;P<=Q;P++)u.realDeleteValue(A,P)}})}getFormulaItemBySId(e,r,s){const i=this._formulaData;if(i[s]==null)return null;const a=i[s];if((a==null?void 0:a[r])==null)return null;const o=new g.ObjectMatrix(a[r]);let u=null;return o.forValue((c,l,h)=>{const{f:m,si:_,x:E=0,y:R=0}=h;if(_===e&&m.length>0&&E===0&&R===0)return u=h,!1}),u}getFormulaDataItem(e,r,s,i){var a,o,u,c;return(c=(u=(o=(a=this._formulaData)==null?void 0:a[i])==null?void 0:o[s])==null?void 0:u[e])==null?void 0:c[r]}getFormulaIdMap(e,r){const s=new Map,i=this._formulaData;if(i[e]==null)return s;const a=i[e];return(a==null?void 0:a[r])==null||new g.ObjectMatrix(a[r]).forValue((u,c,l)=>{const h=(l==null?void 0:l.f)||"",m=(l==null?void 0:l.si)||"",_=(l==null?void 0:l.x)||0,E=(l==null?void 0:l.y)||0;g.isFormulaString(h)&&g.isFormulaId(m)&&_===0&&E===0&&s.set(m,{f:h,r:u,c})}),s}};exports.FormulaDataModel=Vn([Zt(0,g.IUniverInstanceService),Zt(1,V.Inject(ft))],exports.FormulaDataModel);function Sr(t,n,e,r){const s=new Map,i=new g.ObjectMatrix;r.forValue((a,o,u)=>{const c=(u==null?void 0:u.f)||"",l=(u==null?void 0:u.si)||"",h=g.isFormulaString(c),m=g.isFormulaId(l);h&&m?(i.setValue(a,o,{f:c,si:l}),s.set(l,{f:c,r:a,c:o})):h&&!m?i.setValue(a,o,{f:c}):!h&&m&&i.setValue(a,o,{f:"",si:l})}),i.forValue((a,o,u)=>{const c=(u==null?void 0:u.f)||"",l=(u==null?void 0:u.si)||"";if(g.isFormulaId(l)&&!g.isFormulaString(c)){const h=s.get(l);if(h){const m=h.f,_=o-h.c,E=a-h.r;i.setValue(a,o,{f:m,si:l,x:_,y:E})}}}),t[n]&&(t[n][e]=i.getData())}const xn=t=>{const n=t.get(exports.FormulaDataModel),e=g.Tools.deepClone(n.getArrayFormulaRange()),r=g.Tools.deepClone(n.getArrayFormulaCellData());return{arrayFormulaRange:e,arrayFormulaCellData:r}},Je={id:"formula.mutation.set-array-formula-data",type:g.CommandType.MUTATION,handler:(t,n)=>{const e=t.get(exports.FormulaDataModel);return e.setArrayFormulaRange(n.arrayFormulaRange),e.setArrayFormulaCellData(n.arrayFormulaCellData),!0}},dt={id:"formula.mutation.set-defined-name",type:g.CommandType.MUTATION,handler:()=>!0},mt={id:"formula.mutation.remove-defined-name",type:g.CommandType.MUTATION,handler:()=>!0},kt={id:"formula.mutation.set-feature-calculation",type:g.CommandType.MUTATION,handler:()=>!0},jt={id:"formula.mutation.remove-feature-calculation",type:g.CommandType.MUTATION,handler:()=>!0},$t={id:"formula.mutation.set-formula-calculation-start",type:g.CommandType.MUTATION,handler:()=>!0},Qt={id:"formula.mutation.set-formula-calculation-stop",type:g.CommandType.MUTATION,handler:()=>!0},Ne={id:"formula.mutation.set-formula-calculation-notification",type:g.CommandType.MUTATION,handler:()=>!0},Ht={id:"formula.mutation.set-formula-calculation-result",type:g.CommandType.MUTATION,handler:()=>!0},Yt={id:"formula.mutation.set-formula-data",type:g.CommandType.MUTATION,handler:(t,n)=>(t.get(exports.FormulaDataModel).setFormulaData(n.formulaData),!0)},Xt={id:"formula.mutation.set-other-formula",type:g.CommandType.MUTATION,handler:()=>!0},Wt={id:"formula.mutation.remove-other-formula",type:g.CommandType.MUTATION,handler:()=>!0},Pr={id:"formula.mutation.set-super-table",type:g.CommandType.MUTATION,handler:()=>!0},Vr={id:"formula.mutation.remove-super-table",type:g.CommandType.MUTATION,handler:()=>!0},Tt={id:"formula.mutation.set-super-table-option",type:g.CommandType.MUTATION,handler:()=>!0},Kt={id:"formula.mutation.unregister-function",type:g.CommandType.MUTATION,handler:()=>!0};class gt extends g.Disposable{isError(){return!1}isAsyncObject(){return!1}isAsyncArrayObject(){return!1}isReferenceObject(){return!1}isValueObject(){return!1}isEqualType(n){return!1}}var De=(t=>(t.FALSE="FALSE",t.TRUE="TRUE",t))(De||{}),pe=(t=>(t[t.SUCCESS=0]="SUCCESS",t[t.ERROR=1]="ERROR",t))(pe||{}),Re=(t=>(t.ALL="#All",t.DATA="#Data",t.HEADERS="#Headers",t.TOTALS="#Totals",t))(Re||{}),Z=(t=>(t[t.FRONT=0]="FRONT",t[t.BACK=1]="BACK",t))(Z||{});class vn{constructor(){p(this,"_cache",new Map);p(this,"_continueBuildingCache",new Map)}set(n,e,r,s,i){if(!this.shouldContinueBuildingCache(n,e,r,i))return;let a=this._cache.get(n);a==null&&(a=new Map,this._cache.set(n,a));let o=a.get(e);o==null&&(o=new Map,a.set(e,o));let u=o.get(r);u==null&&(u=new Map,o.set(r,u));let c=u.get(s);c==null&&(c=[],u.set(s,c)),c.push(i)}getCellValuePositions(n,e,r){var s,i;return(i=(s=this._cache.get(n))==null?void 0:s.get(e))==null?void 0:i.get(r)}getCellPositions(n,e,r,s){var i,a,o;return(o=(a=(i=this._cache.get(n))==null?void 0:i.get(e))==null?void 0:a.get(r))==null?void 0:o.get(s)}getCellPosition(n,e,r,s,i,a){const o=this.getCellPositions(n,e,r,s);if(o!=null){for(const u of o)if(u>=i&&u<=a)return u}}setContinueBuildingCache(n,e,r,s,i){let a=this._continueBuildingCache.get(n);a==null&&(a=new Map,this._continueBuildingCache.set(n,a));let o=a.get(e);o==null&&(o=new Map,a.set(e,o));let u=o.get(r);if(u==null){u={startRow:s,endRow:i},o.set(r,u);return}u.startRow=Math.min(u.startRow,s),u.endRow=Math.max(u.endRow,i)}shouldContinueBuildingCache(n,e,r,s){var u,c;const i=(c=(u=this._continueBuildingCache.get(n))==null?void 0:u.get(e))==null?void 0:c.get(r);if(i==null)return!0;const{startRow:a,endRow:o}=i;return!(s>=a&&s<=o)}canUseCache(n,e,r,s,i){var c,l;if(r===-1||s===-1||i===-1)return!1;const a=(l=(c=this._continueBuildingCache.get(n))==null?void 0:c.get(e))==null?void 0:l.get(r);if(a==null)return!1;const{startRow:o,endRow:u}=a;return!(s>u||i<o)}clear(){this._cache.clear(),this._continueBuildingCache.clear()}}const oe=new vn;var Te=(t=>(t[t.MIN=0]="MIN",t[t.MAX=1]="MAX",t))(Te||{});function Jt(){return new Intl.Collator(void 0,{numeric:!0}).compare}function An(t){return t.indexOf("*")>-1||t.indexOf("?")>-1}function Nt(t,n){const e=n.replace(/~?[*?]/g,s=>s.startsWith("~")?`\\${s.substring(1)}`:s==="*"?".*":s==="?"?".":s);return new RegExp(`^${e}$`).test(t)}function er(t){return t.replace(/~?[*?]/g,n=>n.startsWith("~")?n.substring(1):" ")}function On(t,n,e){let r=!1;switch(e){case y.EQUALS:r=Nt(t,n);break;case y.GREATER_THAN:case y.GREATER_THAN_OR_EQUAL:r=Nt(t,n)||t>er(n);break;case y.LESS_THAN:case y.LESS_THAN_OR_EQUAL:r=t<er(n);break}return r}class fe extends gt{constructor(n){super(),this._rawValue=n}isValueObject(){return!0}toUnitRange(){return{range:{startColumn:-1,startRow:-1,endRow:-1,endColumn:-1},sheetId:"",unitId:""}}getValue(){return 0}getArrayValue(){return[]}setValue(n){}setArrayValue(n){}isArray(){return!1}isString(){return!1}isNumber(){return!1}isBoolean(){return!1}isLambda(){return!1}isError(){return!1}isNull(){return!1}getNegative(){return d.create(f.NAME)}getReciprocal(){return d.create(f.NAME)}plus(n){return d.create(f.NAME)}minus(n){return d.create(f.NAME)}multiply(n){return d.create(f.NAME)}divided(n){return d.create(f.NAME)}map(n){return d.create(f.NAME)}product(n,e){return e(this,n)}compare(n,e){return d.create(f.NAME)}wildcard(n,e){return d.create(f.NAME)}isEqual(n){return this.compare(n,y.EQUALS)}isNotEqual(n){return this.compare(n,y.NOT_EQUAL)}isGreaterThanOrEqual(n){return this.compare(n,y.GREATER_THAN_OR_EQUAL)}isLessThanOrEqual(n){return this.compare(n,y.LESS_THAN_OR_EQUAL)}isLessThan(n){return this.compare(n,y.LESS_THAN)}isGreaterThan(n){return this.compare(n,y.GREATER_THAN)}concatenateFront(n){return d.create(f.NAME)}concatenateBack(n){return d.create(f.NAME)}plusBy(n){return d.create(f.NAME)}minusBy(n){return d.create(f.NAME)}multiplyBy(n){return d.create(f.NAME)}dividedBy(n){return d.create(f.NAME)}compareBy(n,e){return d.create(f.NAME)}concatenate(n,e=Z.FRONT){let r=this.getValue().toString();if(typeof n=="string")e===Z.FRONT?r=n+r:r+=n;else if(typeof n=="number")e===Z.FRONT?r=n.toString()+r:r+=n.toString();else if(typeof n=="boolean"){const s=n?"TRUE":"FALSE";e===Z.FRONT?r=s+r:r+=s}return r}pow(n){return d.create(f.VALUE)}powInverse(n){return d.create(f.VALUE)}sqrt(){return d.create(f.VALUE)}cbrt(){return d.create(f.VALUE)}cos(){return d.create(f.VALUE)}acos(){return d.create(f.VALUE)}acosh(){return d.create(f.VALUE)}sin(){return d.create(f.VALUE)}asin(){return d.create(f.VALUE)}asinh(){return d.create(f.VALUE)}tan(){return d.create(f.VALUE)}tanh(){return d.create(f.VALUE)}atan(){return d.create(f.VALUE)}atan2(n){return d.create(f.VALUE)}atan2Inverse(n){return d.create(f.VALUE)}atanh(){return d.create(f.VALUE)}mean(){return this}median(){return this}var(){return this}std(){return this}log(){return d.create(f.VALUE)}log10(){return d.create(f.VALUE)}exp(){return d.create(f.VALUE)}abs(){return d.create(f.VALUE)}round(n){return d.create(f.VALUE)}roundInverse(n){return d.create(f.VALUE)}floor(n){return d.create(f.VALUE)}floorInverse(n){return d.create(f.VALUE)}ceil(n){return d.create(f.VALUE)}ceilInverse(n){return d.create(f.VALUE)}}class d extends fe{constructor(n,e=""){super(n),this._errorType=n,this._errorContent=e}static create(n,e){return new d(n,e)}getValue(){return this._errorType}getErrorType(){return this._errorType}getErrorContent(){return this._errorContent}isEqualType(n){return n.getErrorType()===this.getErrorType()}isError(){return!0}}var Bn=20,Un=1,_e=1e6,tr=1e6,Fn=-7,Mn=21,kn=!1,$e="[big.js] ",Ce=$e+"Invalid ",Rt=Ce+"decimal places",jn=Ce+"rounding mode",xr=$e+"Division by zero",U={},te=void 0,$n=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function vr(){function t(n){var e=this;if(!(e instanceof t))return n===te?vr():new t(n);if(n instanceof t)e.s=n.s,e.e=n.e,e.c=n.c.slice();else{if(typeof n!="string"){if(t.strict===!0&&typeof n!="bigint")throw TypeError(Ce+"value");n=n===0&&1/n<0?"-0":String(n)}Qn(e,n)}e.constructor=t}return t.prototype=U,t.DP=Bn,t.RM=Un,t.NE=Fn,t.PE=Mn,t.strict=kn,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function Qn(t,n){var e,r,s;if(!$n.test(n))throw Error(Ce+"number");for(t.s=n.charAt(0)=="-"?(n=n.slice(1),-1):1,(e=n.indexOf("."))>-1&&(n=n.replace(".","")),(r=n.search(/e/i))>0?(e<0&&(e=r),e+=+n.slice(r+1),n=n.substring(0,r)):e<0&&(e=n.length),s=n.length,r=0;r<s&&n.charAt(r)=="0";)++r;if(r==s)t.c=[t.e=0];else{for(;s>0&&n.charAt(--s)=="0";);for(t.e=e-r-1,t.c=[],e=0;r<=s;)t.c[e++]=+n.charAt(r++)}return t}function ye(t,n,e,r){var s=t.c;if(e===te&&(e=t.constructor.RM),e!==0&&e!==1&&e!==2&&e!==3)throw Error(jn);if(n<1)r=e===3&&(r||!!s[0])||n===0&&(e===1&&s[0]>=5||e===2&&(s[0]>5||s[0]===5&&(r||s[1]!==te))),s.length=1,r?(t.e=t.e-n+1,s[0]=1):s[0]=t.e=0;else if(n<s.length){if(r=e===1&&s[n]>=5||e===2&&(s[n]>5||s[n]===5&&(r||s[n+1]!==te||s[n-1]&1))||e===3&&(r||!!s[0]),s.length=n,r){for(;++s[--n]>9;)if(s[n]=0,n===0){++t.e,s.unshift(1);break}}for(n=s.length;!s[--n];)s.pop()}return t}function xe(t,n,e){var r=t.e,s=t.c.join(""),i=s.length;if(n)s=s.charAt(0)+(i>1?"."+s.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)s="0"+s;s="0."+s}else if(r>0)if(++r>i)for(r-=i;r--;)s+="0";else r<i&&(s=s.slice(0,r)+"."+s.slice(r));else i>1&&(s=s.charAt(0)+"."+s.slice(1));return t.s<0&&e?"-"+s:s}U.abs=function(){var t=new this.constructor(this);return t.s=1,t};U.cmp=function(t){var n,e=this,r=e.c,s=(t=new e.constructor(t)).c,i=e.s,a=t.s,o=e.e,u=t.e;if(!r[0]||!s[0])return r[0]?i:s[0]?-a:0;if(i!=a)return i;if(n=i<0,o!=u)return o>u^n?1:-1;for(a=(o=r.length)<(u=s.length)?o:u,i=-1;++i<a;)if(r[i]!=s[i])return r[i]>s[i]^n?1:-1;return o==u?0:o>u^n?1:-1};U.div=function(t){var n=this,e=n.constructor,r=n.c,s=(t=new e(t)).c,i=n.s==t.s?1:-1,a=e.DP;if(a!==~~a||a<0||a>_e)throw Error(Rt);if(!s[0])throw Error(xr);if(!r[0])return t.s=i,t.c=[t.e=0],t;var o,u,c,l,h,m=s.slice(),_=o=s.length,E=r.length,R=r.slice(0,o),D=R.length,b=t,w=b.c=[],S=0,L=a+(b.e=n.e-t.e)+1;for(b.s=i,i=L<0?0:L,m.unshift(0);D++<o;)R.push(0);do{for(c=0;c<10;c++){if(o!=(D=R.length))l=o>D?1:-1;else for(h=-1,l=0;++h<o;)if(s[h]!=R[h]){l=s[h]>R[h]?1:-1;break}if(l<0){for(u=D==o?s:m;D;){if(R[--D]<u[D]){for(h=D;h&&!R[--h];)R[h]=9;--R[h],R[D]+=10}R[D]-=u[D]}for(;!R[0];)R.shift()}else break}w[S++]=l?c:++c,R[0]&&l?R[D]=r[_]||0:R=[r[_]]}while((_++<E||R[0]!==te)&&i--);return!w[0]&&S!=1&&(w.shift(),b.e--,L--),S>L&&ye(b,L,e.RM,R[0]!==te),b};U.eq=function(t){return this.cmp(t)===0};U.gt=function(t){return this.cmp(t)>0};U.gte=function(t){return this.cmp(t)>-1};U.lt=function(t){return this.cmp(t)<0};U.lte=function(t){return this.cmp(t)<1};U.minus=U.sub=function(t){var n,e,r,s,i=this,a=i.constructor,o=i.s,u=(t=new a(t)).s;if(o!=u)return t.s=-u,i.plus(t);var c=i.c.slice(),l=i.e,h=t.c,m=t.e;if(!c[0]||!h[0])return h[0]?t.s=-u:c[0]?t=new a(i):t.s=1,t;if(o=l-m){for((s=o<0)?(o=-o,r=c):(m=l,r=h),r.reverse(),u=o;u--;)r.push(0);r.reverse()}else for(e=((s=c.length<h.length)?c:h).length,o=u=0;u<e;u++)if(c[u]!=h[u]){s=c[u]<h[u];break}if(s&&(r=c,c=h,h=r,t.s=-t.s),(u=(e=h.length)-(n=c.length))>0)for(;u--;)c[n++]=0;for(u=n;e>o;){if(c[--e]<h[e]){for(n=e;n&&!c[--n];)c[n]=9;--c[n],c[e]+=10}c[e]-=h[e]}for(;c[--u]===0;)c.pop();for(;c[0]===0;)c.shift(),--m;return c[0]||(t.s=1,c=[m=0]),t.c=c,t.e=m,t};U.mod=function(t){var n,e=this,r=e.constructor,s=e.s,i=(t=new r(t)).s;if(!t.c[0])throw Error(xr);return e.s=t.s=1,n=t.cmp(e)==1,e.s=s,t.s=i,n?new r(e):(s=r.DP,i=r.RM,r.DP=r.RM=0,e=e.div(t),r.DP=s,r.RM=i,this.minus(e.times(t)))};U.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};U.plus=U.add=function(t){var n,e,r,s=this,i=s.constructor;if(t=new i(t),s.s!=t.s)return t.s=-t.s,s.minus(t);var a=s.e,o=s.c,u=t.e,c=t.c;if(!o[0]||!c[0])return c[0]||(o[0]?t=new i(s):t.s=s.s),t;if(o=o.slice(),n=a-u){for(n>0?(u=a,r=c):(n=-n,r=o),r.reverse();n--;)r.push(0);r.reverse()}for(o.length-c.length<0&&(r=c,c=o,o=r),n=c.length,e=0;n;o[n]%=10)e=(o[--n]=o[n]+c[n]+e)/10|0;for(e&&(o.unshift(e),++u),n=o.length;o[--n]===0;)o.pop();return t.c=o,t.e=u,t};U.pow=function(t){var n=this,e=new n.constructor("1"),r=e,s=t<0;if(t!==~~t||t<-tr||t>tr)throw Error(Ce+"exponent");for(s&&(t=-t);t&1&&(r=r.times(n)),t>>=1,!!t;)n=n.times(n);return s?e.div(r):r};U.prec=function(t,n){if(t!==~~t||t<1||t>_e)throw Error(Ce+"precision");return ye(new this.constructor(this),t,n)};U.round=function(t,n){if(t===te)t=0;else if(t!==~~t||t<-_e||t>_e)throw Error(Rt);return ye(new this.constructor(this),t+this.e+1,n)};U.sqrt=function(){var t,n,e,r=this,s=r.constructor,i=r.s,a=r.e,o=new s("0.5");if(!r.c[0])return new s(r);if(i<0)throw Error($e+"No square root");i=Math.sqrt(r+""),i===0||i===1/0?(n=r.c.join(""),n.length+a&1||(n+="0"),i=Math.sqrt(n),a=((a+1)/2|0)-(a<0||a&1),t=new s((i==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+a)):t=new s(i+""),a=t.e+(s.DP+=4);do e=t,t=o.times(e.plus(r.div(e)));while(e.c.slice(0,a).join("")!==t.c.slice(0,a).join(""));return ye(t,(s.DP-=4)+t.e+1,s.RM)};U.times=U.mul=function(t){var n,e=this,r=e.constructor,s=e.c,i=(t=new r(t)).c,a=s.length,o=i.length,u=e.e,c=t.e;if(t.s=e.s==t.s?1:-1,!s[0]||!i[0])return t.c=[t.e=0],t;for(t.e=u+c,a<o&&(n=s,s=i,i=n,c=a,a=o,o=c),n=new Array(c=a+o);c--;)n[c]=0;for(u=o;u--;){for(o=0,c=a+u;c>u;)o=n[c]+i[u]*s[c-u-1]+o,n[c--]=o%10,o=o/10|0;n[c]=o}for(o?++t.e:n.shift(),u=n.length;!n[--u];)n.pop();return t.c=n,t};U.toExponential=function(t,n){var e=this,r=e.c[0];if(t!==te){if(t!==~~t||t<0||t>_e)throw Error(Rt);for(e=ye(new e.constructor(e),++t,n);e.c.length<t;)e.c.push(0)}return xe(e,!0,!!r)};U.toFixed=function(t,n){var e=this,r=e.c[0];if(t!==te){if(t!==~~t||t<0||t>_e)throw Error(Rt);for(e=ye(new e.constructor(e),t+e.e+1,n),t=t+e.e+1;e.c.length<t;)e.c.push(0)}return xe(e,!1,!!r)};U[Symbol.for("nodejs.util.inspect.custom")]=U.toJSON=U.toString=function(){var t=this,n=t.constructor;return xe(t,t.e<=n.NE||t.e>=n.PE,!!t.c[0])};U.toNumber=function(){var t=Number(xe(this,!0,!0));if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error($e+"Imprecise conversion");return t};U.toPrecision=function(t,n){var e=this,r=e.constructor,s=e.c[0];if(t!==te){if(t!==~~t||t<1||t>_e)throw Error(Ce+"precision");for(e=ye(new r(e),t,n);e.c.length<t;)e.c.push(0)}return xe(e,t<=e.e||e.e<=r.NE||e.e>=r.PE,!!s)};U.valueOf=function(){var t=this,n=t.constructor;if(n.strict===!0)throw Error($e+"valueOf disallowed");return xe(t,t.e<=n.NE||t.e>=n.PE,!0)};var Y=vr();function xt(t){let n;switch(t){case y.EQUALS:n=y.EQUALS;break;case y.GREATER_THAN:n=y.LESS_THAN;break;case y.GREATER_THAN_OR_EQUAL:n=y.LESS_THAN_OR_EQUAL;break;case y.LESS_THAN:n=y.GREATER_THAN;break;case y.LESS_THAN_OR_EQUAL:n=y.GREATER_THAN_OR_EQUAL;break;case y.NOT_EQUAL:n=y.NOT_EQUAL;break}return n}function Gt(t,n){return Y(t).times(n).toNumber()}function rr(t,n){const e=10**Math.floor(n);return Math.round(Gt(t,e))/e}function nr(t,n){const e=10**Math.floor(n);return Math.floor(Gt(t,e))/e}function sr(t,n){const e=10**Math.floor(n);return Math.ceil(Gt(t,e))/e}function ir(t,n){return t**n}class Me extends fe{isNull(){return!0}plus(n){return new C(0,!0).plus(n)}minus(n){return new C(0,!0).minus(n)}multiply(n){return new C(0,!0).multiply(n)}divided(n){return new C(0,!0).divided(n)}compare(n,e){return n.isString()?new X("").compare(n,e):n.isBoolean()?new W(!1).compare(n,e):new C(0,!0).compare(n,e)}concatenateFront(n){return n.isArray()?n.concatenateBack(new X("")):new X(this.concatenate(n.getValue(),Z.FRONT))}concatenateBack(n){return n.isArray()?n.concatenateFront(new X("")):new X(this.concatenate(n.getValue(),Z.BACK))}plusBy(n){return new C(0).plusBy(n)}minusBy(n){return new C(0).minusBy(n)}multiplyBy(n){return new C(0).multiplyBy(n)}dividedBy(n){return new C(0).dividedBy(n)}compareBy(n,e){return typeof n=="string"?new X("").compareBy(n,e):typeof n=="boolean"?new W(!1).compareBy(n,e):new C(0,!0).compareBy(n,e)}pow(n){return new C(0,!0).pow(n)}sqrt(){return new C(0,!0)}cbrt(){return new C(0,!0)}cos(){return new C(0,!0)}acos(){return new C(0,!0)}acosh(){return new C(0,!0)}sin(){return new C(0,!0)}asin(){return new C(0,!0)}asinh(){return new C(0,!0)}tan(){return new C(0,!0)}tanh(){return new C(0,!0)}atan(){return new C(0,!0)}atan2(n){return new C(0,!0).atan2(n)}atanh(){return new C(0,!0)}log(){return d.create(f.NUM)}log10(){return d.create(f.NUM)}exp(){return d.create(f.NUM)}abs(){return d.create(f.NUM)}round(n){return new C(0,!0).round(n)}floor(n){return new C(0,!0).floor(n)}ceil(n){return new C(0,!0).ceil(n)}}class W extends fe{constructor(e,r=!1){super(e);p(this,"_value",!1);if(r){this._value=e;return}if(typeof e=="boolean")this._value=e;else if(typeof e=="string"){const s=e.toLocaleUpperCase();s===De.TRUE?this._value=!0:s===De.FALSE&&(this._value=!1)}else e===1?this._value=!0:this._value=!1}getValue(){return this._value}isBoolean(){return!0}getNegative(){const e=this.getValue();let r=0;return e&&(r=1),new C(-r,!0)}getReciprocal(){return this.getValue()?new C(1,!0):d.create(f.DIV_BY_ZERO)}plus(e){return this._convertTonNumber().plus(e)}minus(e){return this._convertTonNumber().minus(e)}multiply(e){return this._convertTonNumber().multiply(e)}divided(e){return this._convertTonNumber().divided(e)}compare(e,r){return this._convertTonNumber().compare(e,r)}concatenateFront(e){return this._convertTonNumber().concatenateFront(e)}concatenateBack(e){return this._convertTonNumber().concatenateBack(e)}_convertTonNumber(){const e=this.getValue();let r=0;return e&&(r=1),new C(r,!0)}pow(e){return this._convertTonNumber().pow(e)}sqrt(){return this._convertTonNumber()}cbrt(){return this._convertTonNumber()}cos(){return this._convertTonNumber().cos()}acos(){return this._convertTonNumber().acos()}acosh(){return this._convertTonNumber().acosh()}sin(){return this._convertTonNumber().sin()}asin(){return this._convertTonNumber().asin()}asinh(){return this._convertTonNumber().asinh()}tan(){return this._convertTonNumber().tan()}tanh(){return this._convertTonNumber().tanh()}atan(){return this._convertTonNumber().atan()}atan2(e){return this._convertTonNumber().atan2(e)}atanh(){return this._convertTonNumber().atanh()}log(){return this._convertTonNumber().log()}log10(){return this._convertTonNumber().log10()}exp(){return this._convertTonNumber().exp()}abs(){return this._convertTonNumber().abs()}round(e){return this._convertTonNumber().round(e)}floor(e){return this._convertTonNumber().floor(e)}ceil(e){return this._convertTonNumber().ceil(e)}}class C extends fe{constructor(e,r=!1){super(e);p(this,"_value",0);if(r){this._value=e;return}this._value=Number(e)}getValue(){return this._value}setValue(e){this._value=e}isNumber(){return!0}getNegative(){return new C(0).minus(this)}getReciprocal(){return new C(1).divided(this)}plus(e){if(e.isArray())return e.plus(this);const r=this.plusBy(e.getValue());return r.isError()?this:r}equalZero(){return this._value===0}minus(e){if(e.isArray()){const s=e.getNegative();return s.isError()?s:s.plus(this)}const r=this.minusBy(e.getValue());return r.isError()?this:r}multiply(e){return e.isArray()?e.multiply(this):this.multiplyBy(e.getValue())}divided(e){if(e.isArray()){const r=e.getReciprocal();return r.isError()?r:r.multiply(this)}return this.dividedBy(e.getValue())}concatenateFront(e){return e.isArray()?e.concatenateBack(this):new X(this.concatenate(e.getValue(),Z.FRONT))}concatenateBack(e){return e.isArray()?e.concatenateFront(this):new X(this.concatenate(e.getValue(),Z.BACK))}compare(e,r){return e.isArray()?e.compare(this,xt(r)):this.compareBy(e.getValue(),r)}plusBy(e){const r=this.getValue();if(typeof e=="string")return d.create(f.VALUE);if(typeof e=="number"){if(!Number.isFinite(r)||!Number.isFinite(e))return d.create(f.NUM);const s=Y(r).plus(e).toNumber();return Number.isFinite(s)?new C(s):d.create(f.NUM)}return typeof e=="boolean"?new C(Y(r).plus(e?1:0).toNumber()):this}minusBy(e){const r=this.getValue();if(typeof e=="string")return d.create(f.VALUE);if(typeof e=="number"){if(!Number.isFinite(r)||!Number.isFinite(e))return d.create(f.NUM);const s=Y(r).minus(e).toNumber();return Number.isFinite(s)?new C(s):d.create(f.NUM)}return typeof e=="boolean"?new C(Y(r).minus(e?1:0).toNumber()):this}multiplyBy(e){const r=this.getValue();if(typeof e=="string")return d.create(f.VALUE);if(typeof e=="number"){if(!Number.isFinite(r)||!Number.isFinite(e))return d.create(f.NUM);const s=Y(r).times(e).toNumber();return Number.isFinite(s)?new C(s):d.create(f.NUM)}return typeof e=="boolean"?new C(Y(r).times(e?1:0).toNumber()):this}dividedBy(e){const r=this.getValue();if(typeof e=="string")return d.create(f.VALUE);if(typeof e=="number"){if(e===0)return d.create(f.DIV_BY_ZERO);if(!Number.isFinite(r)||!Number.isFinite(e))return d.create(f.NUM);const s=Y(r).div(e).toNumber();return Number.isFinite(s)?new C(s):d.create(f.NUM)}return typeof e=="boolean"?e===!1?d.create(f.DIV_BY_ZERO):new C(Y(r).div(1).toNumber()):this}compareBy(e,r){const s=this.getValue();let i=!1;if(typeof e=="string")switch(r){case y.EQUALS:case y.GREATER_THAN:case y.GREATER_THAN_OR_EQUAL:i=!1;break;case y.LESS_THAN:case y.LESS_THAN_OR_EQUAL:case y.NOT_EQUAL:i=!0;break}else if(typeof e=="number")if(!Number.isFinite(s)||!Number.isFinite(e))i=this._compareInfinity(s,e,r);else switch(r){case y.EQUALS:i=Y(s).eq(e);break;case y.GREATER_THAN:i=Y(s).gt(e);break;case y.GREATER_THAN_OR_EQUAL:i=Y(s).gte(e);break;case y.LESS_THAN:i=Y(s).lt(e);break;case y.LESS_THAN_OR_EQUAL:i=Y(s).lte(e);break;case y.NOT_EQUAL:i=!Y(s).eq(e);break}else if(typeof e=="boolean")switch(r){case y.EQUALS:case y.GREATER_THAN:case y.GREATER_THAN_OR_EQUAL:i=!1;break;case y.LESS_THAN:case y.LESS_THAN_OR_EQUAL:case y.NOT_EQUAL:i=!0;break}return new W(i)}pow(e){if(e.isArray())return e.powInverse(this);const r=this.getValue(),s=e.getValue();if(typeof s=="string")return d.create(f.VALUE);if(typeof s=="number"){if(!Number.isFinite(r)||!Number.isFinite(s))return d.create(f.NUM);const i=ir(r,s);return Number.isFinite(i)?new C(i):d.create(f.NUM)}return typeof s=="boolean"?new C(ir(r,s?1:0)):this}sqrt(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Y(e).sqrt().toNumber();return Number.isFinite(r)?new C(r):d.create(f.NUM)}cbrt(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.cbrt(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}cos(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.cos(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}acos(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.acos(e);return Number.isNaN(r)?d.create(f.NUM):new C(r)}acosh(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.acosh(e);return Number.isNaN(r)?d.create(f.NUM):new C(r)}sin(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.sin(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}asin(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.asin(e);return Number.isNaN(r)?d.create(f.NUM):new C(r)}asinh(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.asinh(e);return Number.isNaN(r)?d.create(f.NUM):new C(r)}tan(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.tan(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}tanh(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.tanh(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}atan(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.atan(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}atan2(e){if(e.isArray())return e.atan2Inverse(this);const r=this.getValue(),s=e.getValue();if(typeof s=="string")return d.create(f.VALUE);if(typeof s=="number"){if(!Number.isFinite(r)||!Number.isFinite(s))return d.create(f.NUM);const i=Math.atan2(r,s);return Number.isFinite(i)?new C(i):d.create(f.NUM)}return typeof s=="boolean"?new C(Math.atan2(r,s?1:0)):this}atanh(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.atanh(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}log(){const e=this.getValue();if(typeof e=="number"&&e<=0||!Number.isFinite(e))return d.create(f.NUM);const r=Math.log(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}log10(){const e=this.getValue();if(typeof e=="number"&&e<=0||!Number.isFinite(e))return d.create(f.NUM);const r=Math.log10(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}exp(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.exp(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}abs(){const e=this.getValue();if(!Number.isFinite(e))return d.create(f.NUM);const r=Math.abs(e);return Number.isFinite(r)?new C(r):d.create(f.NUM)}round(e){if(e.isArray())return e.roundInverse(this);const r=this.getValue(),s=e.getValue();if(typeof s=="string")return d.create(f.VALUE);if(typeof s=="number"){if(!Number.isFinite(r)||!Number.isFinite(s))return d.create(f.NUM);const i=rr(r,s);return Number.isFinite(i)?new C(i):d.create(f.NUM)}return typeof s=="boolean"?new C(rr(r,s?1:0)):this}floor(e){if(e.isArray())return e.floorInverse(this);const r=this.getValue(),s=e.getValue();if(typeof s=="string")return d.create(f.VALUE);if(typeof s=="number"){if(!Number.isFinite(r)||!Number.isFinite(s))return d.create(f.NUM);const i=nr(r,s);return Number.isFinite(i)?new C(i):d.create(f.NUM)}return typeof s=="boolean"?new C(nr(r,s?1:0)):this}ceil(e){if(e.isArray())return e.ceilInverse(this);const r=this.getValue(),s=e.getValue();if(typeof s=="string")return d.create(f.VALUE);if(typeof s=="number"){if(!Number.isFinite(r)||!Number.isFinite(s))return d.create(f.NUM);const i=sr(r,s);return Number.isFinite(i)?new C(i):d.create(f.NUM)}return typeof s=="boolean"?new C(sr(r,s?1:0)):this}_compareInfinity(e,r,s){let i=!1;switch(s){case y.EQUALS:i=e===r;break;case y.GREATER_THAN:i=e>r;break;case y.GREATER_THAN_OR_EQUAL:i=e>=r;break;case y.LESS_THAN:i=e<r;break;case y.LESS_THAN_OR_EQUAL:i=e<=r;break;case y.NOT_EQUAL:i=e!==r;break}return i}}class X extends fe{constructor(e,r=!1){super(e);p(this,"_value");if(r){this._value=e;return}let s=e.toString();s.charAt(0)==='"'&&s.charAt(s.length-1)==='"'&&(s=s.slice(1,-1),s=s.replace(/""/g,'"')),this._value=s}getValue(){return this._value}isString(){return!0}concatenateFront(e){return e.isArray()?e.concatenateBack(this):new X(this.concatenate(e.getValue(),Z.FRONT))}concatenateBack(e){return e.isArray()?e.concatenateFront(this):new X(this.concatenate(e.getValue(),Z.BACK))}compare(e,r){return e.isArray()?e.compare(this,xt(r)):this.compareBy(e.getValue(),r)}wildcard(e,r){return e.isArray()?e.wildcard(this,xt(r)):this._checkWildcard(e.getValue(),r)}compareBy(e,r){const s=this.getValue();let i=!1;if(typeof e=="string")switch(r){case y.EQUALS:i=s===e;break;case y.GREATER_THAN:i=s>e;break;case y.GREATER_THAN_OR_EQUAL:i=s>=e;break;case y.LESS_THAN:i=s<e;break;case y.LESS_THAN_OR_EQUAL:i=s<=e;break;case y.NOT_EQUAL:i=s!==e;break}else if(typeof e=="number")switch(r){case y.EQUALS:case y.GREATER_THAN:case y.GREATER_THAN_OR_EQUAL:i=!0;break;case y.LESS_THAN:case y.LESS_THAN_OR_EQUAL:case y.NOT_EQUAL:i=!1;break}else if(typeof e=="boolean")switch(r){case y.EQUALS:case y.GREATER_THAN:case y.GREATER_THAN_OR_EQUAL:i=!1;break;case y.LESS_THAN:case y.LESS_THAN_OR_EQUAL:case y.NOT_EQUAL:i=!0;break}return new W(i)}_checkWildcard(e,r){const s=this.getValue().toLocaleLowerCase(),i=On(s,e,r);return new W(i)}}function Hn(t){return""}function Yn(t=[]){const n=[];for(let e=0;e<t.length;e++){const r=t[e];n[e]==null&&(n[e]=[]);for(let s=0;s<r.length;s++){const i=r[s];n[e][s]=he.create(i)}}return n}function Xn(t=[]){const n=[];for(let e=0;e<t.length;e++){const r=t[e];n[e]==null&&(n[e]=[]);for(let s=0;s<r.length;s++){const i=r[s];i.isError()?n[e][s]=i.getErrorType():n[e][s]=i.getValue()}}return n}class J extends fe{constructor(e){var n=(...aa)=>(super(...aa),p(this,"_values",[]),p(this,"_rowCount",-1),p(this,"_columnCount",-1),p(this,"_unitId",""),p(this,"_sheetId",""),p(this,"_currentRow",-1),p(this,"_currentColumn",-1),p(this,"_sliceCache",new Map),p(this,"_flattenCache"),this);if(typeof e=="string")n(e);else{const r=Hn();n(r)}this._values=this._formatValue(e)}dispose(){this._values.forEach(e=>{e.forEach(r=>{r.dispose()})}),this._values=[],this._clearCache()}getRowCount(){return this._rowCount}setRowCount(e){this._rowCount=e}getColumnCount(){return this._columnCount}setColumnCount(e){this._columnCount=e}setCurrent(e,r){this._currentRow=e,this._currentColumn=r}setUnitId(e){this._unitId=e}getUnitId(){return this._unitId}setSheetId(e){this._sheetId=e}getSheetId(){return this._sheetId}getCurrentRow(){return this._currentRow}getCurrentColumn(){return this._currentColumn}getArrayValue(){return this._values}setArrayValue(e){this._clearCache(),this._values=e}isArray(){return!0}get(e,r){const s=this._values[e][r];return s??new Me(0)}set(e,r,s){if(e>=this._rowCount||r>=this._columnCount)throw new Error("Exceeding array bounds.");this._clearCache(),this._values[e][r]=s}getRangePosition(){const r=this.getRowCount(),s=0,i=this.getColumnCount();return{startRow:0,endRow:r-1,startColumn:s,endColumn:i-1}}iterator(e){const{startRow:r,endRow:s,startColumn:i,endColumn:a}=this.getRangePosition(),o=this.getArrayValue();for(let u=r;u<=s;u++)for(let c=i;c<=a;c++)if(e(o[u][c],u,c)===!1)return}getFirstCell(){const{startRow:e,startColumn:r}=this.getRangePosition();return this.get(e,r)}pick(e){const r=e.getRowCount(),s=e.getColumnCount();if(r!==this._rowCount||s!==this._columnCount)return this._createNewArray([[new Me(0)]],1,1);const i=[];i[0]=[];for(let a=0;a<r;a++)for(let o=0;o<s;o++){const u=e.get(a,o),c=this.get(a,o);u.isError()||u.getValue()===!0&&i[0].push(c)}return this._createNewArray(i,1,i[0].length)}flatten(){if(this._flattenCache!=null)return this._flattenCache;const e=[];e[0]=[];for(let s=0;s<this._rowCount;s++)for(let i=0;i<this._columnCount;i++){const a=this.get(s,i);e[0].push(a)}const r=this._createNewArray(e,1,e[0].length);return this._flattenCache=r,r}slice(e,r){let s=0,i=this._rowCount,a=1,o=0,u=this._columnCount,c=1;if(e!=null&&(s=e[0]||0,i=e[1]||this._rowCount,a=e[2]||1),r!=null&&(o=r[0]||0,u=r[1]||this._columnCount,c=r[2]||1),s>=this._rowCount||o>=this._columnCount)return;const l=`${s}_${i}_${a}_${o}_${u}_${c}`,h=this._sliceCache.get(l);if(h!=null)return h;const m=[],_=this._values;let E=0,R=0;for(let S=s;S<i;S+=a){R=0,m[E]==null&&(m[E]=[]);for(let L=o;L<u;L+=c)m[E][R]=_[S][L],R++;E++}if(m.length===0||m[0].length===0)return;const D=a>1?-1:s+this._currentRow,b=c>1?-1:o+this._currentColumn,w=this._createNewArray(m,m.length,m[0].length,D,b);return this._sliceCache.set(l,w),w}sum(){let e=new C(0);return this.iterator(r=>{if(r==null)return!0;if(r.isError())return e=r,!1;e=e.plus(r)}),e}max(){let e=new C(-1/0);return this.iterator(r=>{if(r==null)return!0;if(r.isError())return e=r,!1;if(r.isString()||r.isNull())return!0;e.isLessThan(r).getValue()&&(e=r)}),e}min(){let e=new C(1/0);return this.iterator(r=>{if(r==null)return!0;if(r.isError())return e=r,!1;if(r.isString()||r.isNull())return!0;e.isGreaterThan(r).getValue()&&(e=r)}),e}count(){let e=new C(0);return this.iterator(r=>{if(r==null||r.isError()||r.isString()||r.isNull())return!0;e=e.plusBy(1)}),e}countA(){let e=new C(0);return this.iterator(r=>{if(r==null||r.isNull())return!0;e=e.plusBy(1)}),e}countBlank(){let e=new C(0);return this.iterator(r=>{if(r!=null)return!0;e=e.plusBy(1)}),e}sortByRow(e){const r=this._transposeArray(this._values);r.sort(this._sort(e)),this._clearCache(),this._values=this._transposeArray(r)}sortByColumn(e){this._clearCache(),this._values.sort(this._sort(e))}transpose(){const e=this._transposeArray(this._values),r=this._rowCount,s=this._columnCount;return this._createNewArray(e,s,r)}binarySearch(e,r=Te.MIN){if(e.isError())return;const a=this.flatten().getArrayValue()[0],o=Jt(),u=e.getValue().toString();let c=0,l=a.length-1,h=null;for(;c<=l;){const m=Math.floor((c+l)/2),E=a[m].getValue(),R=o(E.toString(),u);if(R===0)return m;R===-1?(c=m+1,r===Te.MIN&&(h=m)):(l=m-1,r===Te.MAX&&(h=m))}return h}getNegative(){return new J("{0}").minus(this)}getReciprocal(){return new J("{1}").divided(this)}plus(e){return this._batchOperator(e,1)}minus(e){return this._batchOperator(e,0)}multiply(e){return this._batchOperator(e,2)}divided(e){return this._batchOperator(e,3)}compare(e,r){return this._batchOperator(e,4,r)}wildcard(e,r){return this._batchOperator(e,8,r)}concatenateFront(e){return this._batchOperator(e,5)}concatenateBack(e){return this._batchOperator(e,6)}product(e,r){return this._batchOperator(e,7,r)}map(e){var a,o;const r=this._rowCount,s=this._columnCount,i=[];for(let u=0;u<r;u++){const c=[];for(let l=0;l<s;l++){const h=(o=(a=this._values)==null?void 0:a[u])==null?void 0:o[l];h?h.isError()?c[l]=h:c[l]=e(h,u,l):c[l]=d.create(f.VALUE)}i.push(c)}return this._createNewArray(i,r,s)}pow(e){return this._batchOperator(e,9)}powInverse(e){return this.map(r=>r.isError()?r:e.pow(r))}sqrt(){return this.map(e=>e.isError()?e:e.sqrt())}cbrt(){return this.map(e=>e.isError()?e:e.cbrt())}cos(){return this.map(e=>e.isError()?e:e.cos())}acos(){return this.map(e=>e.isError()?e:e.acos())}acosh(){return this.map(e=>e.isError()?e:e.acosh())}sin(){return this.map(e=>e.isError()?e:e.sin())}asin(){return this.map(e=>e.isError()?e:e.asin())}asinh(){return this.map(e=>e.isError()?e:e.asinh())}tan(){return this.map(e=>e.isError()?e:e.tan())}tanh(){return this.map(e=>e.isError()?e:e.tanh())}atan(){return this.map(e=>e.isError()?e:e.atan())}atanh(){return this.map(e=>e.isError()?e:e.atanh())}atan2(e){return this._batchOperator(e,13)}atan2Inverse(e){return this.map(r=>r.isError()?r:e.atan2(r))}mean(){const e=this.sum(),r=this.countA();return e.divided(r)}median(){const e=this.flatten(),r=e.getColumnCount();if(r<=1)return e.get(0,0);if(e.sortByRow(0),r%2===0){const s=e.get(0,r/2),i=e.get(0,r/2-1);return s.plus(i).divided(new C(2,!0))}return e.get(0,(r-1)/2)}var(){const e=this.mean(),r=[];this.iterator((h,m,_)=>{(h==null||h.isError()||h.isString())&&(h=new C(0));let E=h.minus(e).pow(new C(2,!0));E.isError()&&(E=new C(0)),r[m]==null&&(r[m]=[]),r[m][_]=E});const{_rowCount:s,_columnCount:i,_unitId:a,_sheetId:o,_currentRow:u,_currentColumn:c}=this;return new J({calculateValueList:r,rowCount:s,columnCount:i,unitId:a,sheetId:o,row:u,column:c}).mean()}std(){const e=this.var();return e.isError()?e:e.sqrt()}log(){return this.map(e=>e.isError()?e:e.log())}log10(){return this.map(e=>e.isError()?e:e.log10())}exp(){return this.map(e=>e.isError()?e:e.exp())}abs(){return this.map(e=>e.isError()?e:e.abs())}round(e){return this._batchOperator(e,10)}roundInverse(e){return this.map(r=>r.isError()?r:e.round(r))}floor(e){return this._batchOperator(e,11)}floorInverse(e){return this.map(r=>r.isError()?r:e.floor(r))}ceil(e){return this._batchOperator(e,12)}ceilInverse(e){return this.map(r=>r.isError()?r:e.ceil(r))}toValue(){return Xn(this._values)}_clearCache(){this._flattenCache=null,this._sliceCache.clear()}_sort(e){const r=Jt();return(s,i)=>{const a=s[e],o=i[e];return a.isError()&&a.isError()?0:a.isError()?1:o.isError()?-1:r(a.getValue(),o.getValue())}}_transposeArray(e){const r=e.length,s=e[0].length,i=[];for(let a=0;a<s;a++){i[a]=[];for(let o=0;o<r;o++)i[a][o]=e[o][a]}return i}_batchOperator(e,r,s){const i=[];let a=this._rowCount,o=this._columnCount;if(e.isArray()){const c=e.getRowCount(),l=e.getColumnCount();if(a=Math.max(c,a),o=Math.max(l,o),c===1&&l===1){const h=e.getFirstCell();for(let m=0;m<o;m++)i.push(h)}else if(c===1&&this._columnCount>1){const h=e.getArrayValue();for(let m=0;m<o;m++)i.push(h[0][m])}else return this._batchOperatorArray(e,r,s)}else for(let c=0;c<o;c++)i.push(e);const u=[];for(let c=0;c<o;c++){const l=i[c];this._batchOperatorValue(l,c,u,r,s)}return this._createNewArray(u,a,o)}_batchOperatorValue(e,r,s,i,a){var _,E;const o=this._rowCount;let u=!1;const c=this.getUnitId(),l=this.getSheetId(),h=this.getCurrentRow(),m=this.getCurrentColumn();if(i===4&&(u=oe.canUseCache(c,l,r+m,h,h+o-1),u===!0)){if(a===y.EQUALS){const R=oe.getCellPositions(c,l,r+m,e.getValue());for(let D=0;D<o;D++)s[D]==null&&(s[D]=[]),R!=null&&R.includes(D+h)?s[D][r]=new W(!0):s[D][r]=new W(!1)}else{const R=oe.getCellValuePositions(c,l,r+m);if(R!=null)R.forEach((D,b)=>{let w;if(typeof b=="string"?w=new X(b):typeof b=="number"?w=new C(b):typeof b=="boolean"&&(w=new W(b)),w==null)return!0;if(w.compare(e,a))for(let L=0;L<o;L++)s[L]==null&&(s[L]=[]),D.includes(L+h)?s[L][r]=new W(!0):s[L][r]=new W(!1)});else for(let D=0;D<o;D++)s[D]==null&&(s[D]=[]),s[D][r]=new W(!1)}return}for(let R=0;R<o;R++){const D=(E=(_=this._values)==null?void 0:_[R])==null?void 0:E[r];if(s[R]==null&&(s[R]=[]),D&&e)if(D.isError())s[R][r]=D;else if(e.isError())s[R][r]=d.create(f.VALUE);else switch(i){case 1:s[R][r]=D.plus(e);break;case 0:s[R][r]=D.minus(e);break;case 2:s[R][r]=D.multiply(e);break;case 3:s[R][r]=D.divided(e);break;case 4:a?s[R][r]=D.compare(e,a):s[R][r]=d.create(f.VALUE);break;case 5:s[R][r]=D.concatenateFront(e);break;case 6:s[R][r]=D.concatenateBack(e);break;case 7:a?s[R][r]=D.product(e,a):s[R][r]=d.create(f.VALUE);break;case 8:a?s[R][r]=D.wildcard(e,a):s[R][r]=d.create(f.VALUE);break;case 9:s[R][r]=D.pow(e);break;case 10:s[R][r]=D.round(e);break;case 11:s[R][r]=D.floor(e);break;case 13:s[R][r]=D.atan2(e);break;case 12:s[R][r]=D.ceil(e);break}else s[R][r]=d.create(f.NA);D!=null&&(D.isError()?oe.set(c,l,r+m,D.getErrorType(),R+h):D.isNull()?oe.set(c,l,r+m,null,R+h):oe.set(c,l,r+m,D.getValue(),R+h))}oe.setContinueBuildingCache(c,l,r+m,h,h+o-1)}_batchOperatorArray(e,r,s){var h,m,_,E,R,D,b,w,S,L,k,j;let i=e.getRowCount(),a=e.getColumnCount();i<this._rowCount&&(i=this._rowCount),a<this._columnCount&&(a=this._columnCount);const o=[],u=e.getArrayValue(),c=this._checkArrayCalculateType(this),l=this._checkArrayCalculateType(e);for(let Q=0;Q<i;Q++){const A=[];for(let P=0;P<a;P++){let B;c===3?B=(m=(h=this._values)==null?void 0:h[0])==null?void 0:m[0]:c===1?B=(E=(_=this._values)==null?void 0:_[0])==null?void 0:E[P]:c===2?B=(D=(R=this._values)==null?void 0:R[Q])==null?void 0:D[0]:B=(w=(b=this._values)==null?void 0:b[Q])==null?void 0:w[P];let M;if(l===3?M=(S=u==null?void 0:u[0])==null?void 0:S[0]:l===1?M=(L=u==null?void 0:u[0])==null?void 0:L[P]:l===2?M=(k=u==null?void 0:u[Q])==null?void 0:k[0]:M=(j=u==null?void 0:u[Q])==null?void 0:j[P],B&&M)if(B.isError())A[P]=B;else if(M.isError())A[P]=M;else switch(r){case 1:A[P]=B.plus(M);break;case 0:A[P]=B.minus(M);break;case 2:A[P]=B.multiply(M);break;case 3:A[P]=B.divided(M);break;case 4:s?A[P]=B.compare(M,s):A[P]=d.create(f.VALUE);break;case 5:A[P]=B.concatenateFront(M);break;case 6:A[P]=B.concatenateBack(M);break;case 7:s?A[P]=B.product(M,s):A[P]=d.create(f.VALUE);break;case 8:s?A[P]=B.wildcard(M,s):A[P]=d.create(f.VALUE);break;case 9:A[P]=B.pow(M);break;case 10:A[P]=B.round(M);break;case 13:A[P]=B.atan2(M);break;case 11:A[P]=B.floor(M);break;case 12:A[P]=B.ceil(M);break}else A[P]=d.create(f.NA)}o.push(A)}return this._createNewArray(o,i,a)}_checkArrayCalculateType(e){return e.getRowCount()===1&&e.getColumnCount()===1?3:e.getRowCount()===1?1:e.getColumnCount()===1?2:0}_formatValue(e){if(typeof e!="string")return e=e,this._rowCount=e.rowCount,this._columnCount=e.columnCount,this._unitId=e.unitId,this._sheetId=e.sheetId,this._currentRow=e.row,this._currentColumn=e.column,e.calculateValueList;e=e.slice(1,-1);const r=e.split(";"),s=r.length,i=[];let a=0;for(let o=0;o<s;o++){const c=r[o].split(","),l=c.length;a<l&&(a=l);const h=[];for(let m=0;m<l;m++){const _=c[m].trim();h.push(he.create(_))}i.push(h)}return this._rowCount=s,this._columnCount=a,i}_createNewArray(e,r,s,i=-1,a=-1){(this._currentColumn===-1||this._currentRow===-1)&&(i=-1,a=-1);const o={calculateValueList:e,rowCount:r,columnCount:s,unitId:this.getUnitId(),sheetId:this.getSheetId(),row:i,column:a};return new J(o)}}class he{static create(n){if(n==null)return new Me(0);if(typeof n=="boolean")return new W(n,!0);if(typeof n=="string"){const e=n.toLocaleUpperCase().trim();return Ut.has(e)?new d(e):e===De.TRUE||e===De.FALSE?new W(e):g.isRealNum(n)?new C(n):new RegExp(bn,"g").test(n.replace(/\n/g,"").replace(/\r/g,""))?new J(n.replace(/\n/g,"").replace(/\r/g,"")):new X(n)}return typeof n=="number"?Number.isFinite(n)?new C(n,!0):d.create(f.NUM):d.create(f.NA)}}const Wn=1e5,vt=new lt(Wn);class ve extends gt{constructor(e){super();p(this,"_forcedSheetId","");p(this,"_forcedSheetName","");p(this,"_defaultSheetId","");p(this,"_rangeData",{startColumn:-1,startRow:-1,endRow:-1,endColumn:-1});p(this,"_unitData",{});p(this,"_defaultUnitId","");p(this,"_forcedUnitId","");p(this,"_runtimeData",{});p(this,"_arrayFormulaCellData",{});p(this,"_runtimeArrayFormulaCellData",{});p(this,"_runtimeFeatureCellData",{});p(this,"_refOffsetX",0);p(this,"_refOffsetY",0);this._token=e}dispose(){this._unitData={},this._runtimeData={}}isExceedRange(){const{startRow:e,endRow:r,startColumn:s,endColumn:i}=this.getRangePosition();return e<0||s<0||r>=this.getRowCount()||i>=this.getColumnCount()}setRefOffset(e=0,r=0){this._refOffsetX=e,this._refOffsetY=r}getRefOffset(){return{x:this._refOffsetX,y:this._refOffsetY}}getRangePosition(){let e=this._rangeData.startRow+this._refOffsetY,r=this._rangeData.endRow+this._refOffsetY,s=this._rangeData.startColumn+this._refOffsetX,i=this._rangeData.endColumn+this._refOffsetX;return isNaN(e)&&(e=0),isNaN(s)&&(s=0),isNaN(r)&&(r=this.getRowCount()-1),isNaN(i)&&(i=this.getColumnCount()-1),{startRow:e,endRow:r,startColumn:s,endColumn:i}}isReferenceObject(){return!0}iterator(e){const{startRow:r,endRow:s,startColumn:i,endColumn:a}=this.getRangePosition();if(this._checkIfWorksheetMiss())return e(new d(f.VALUE),r,i);for(let o=r;o<=s;o++)for(let u=i;u<=a;u++){if(o<0||u<0)return e(new d(f.REF),o,u);const c=this.getCellData(o,u);let l=!1;if(c==null||g.isNullCell(c)){l=e(null,o,u);continue}const h=this.getCellValueObject(c);if(l=e(h,o,u),l===!1)return}}getFirstCell(){const{startRow:e,startColumn:r}=this.getRangePosition(),s=this.getCellData(e,r);return s?this.getCellValueObject(s):new C(0,!0)}getRangeData(){return this._rangeData}setRangeData(e){this._rangeData=e}getUnitId(){return this._forcedUnitId&&this._forcedUnitId.length>0?this._forcedUnitId:this._defaultUnitId}getSheetId(){return this._forcedSheetId&&this._forcedSheetId.length>0?this._forcedSheetId:this._defaultSheetId}setForcedUnitIdDirect(e){e.length>0&&(this._forcedUnitId=e)}getForcedUnitId(){return this._forcedUnitId}setForcedSheetId(e){var r;this._forcedSheetId=(r=e[this.getUnitId()])==null?void 0:r[this._forcedSheetName]}setForcedSheetIdDirect(e){this._forcedSheetId=e}getForcedSheetId(){return this._forcedSheetId}setForcedSheetName(e){e.length>0&&(this._forcedSheetName=e)}getForcedSheetName(){return this._forcedSheetName}setDefaultSheetId(e){this._defaultSheetId=e}getDefaultSheetId(){return this._defaultSheetId}setDefaultUnitId(e){this._defaultUnitId=e}getDefaultUnitId(){return this._defaultUnitId}getUnitData(){return this._unitData}setUnitData(e){this._unitData=e}getRuntimeData(){return this._runtimeData}setRuntimeData(e){this._runtimeData=e}getArrayFormulaCellData(){return this._arrayFormulaCellData}setArrayFormulaCellData(e){this._arrayFormulaCellData=e}getRuntimeArrayFormulaCellData(){return this._runtimeArrayFormulaCellData}setRuntimeArrayFormulaCellData(e){this._runtimeArrayFormulaCellData=e}getRuntimeFeatureCellData(){return this._runtimeFeatureCellData}setRuntimeFeatureCellData(e){this._runtimeFeatureCellData=e}getRowCount(){return this.getCurrentActiveSheetData().rowCount}getColumnCount(){return this.getCurrentActiveSheetData().columnCount}isCell(){return!1}isColumn(){return!1}isRow(){return!1}isRange(){return!1}isTable(){return!1}unionBy(e){return d.create(f.REF)}unionRange(e,r){return{startRow:-1,startColumn:-1,endRow:-1,endColumn:-1}}getCellValueObject(e){const r=e.v||0;return Ut.has(r)?d.create(r):e.t===g.CellValueType.NUMBER?new C(r):e.t===g.CellValueType.STRING||e.t===g.CellValueType.FORCE_STRING?new X(r):e.t===g.CellValueType.BOOLEAN?new W(r):he.create(r)}getCellByRow(e){return this.getCellByPosition(e)}getCellByColumn(e){return this.getCellByPosition(void 0,e)}getCurrentActiveSheetData(){return this._unitData[this.getUnitId()][this.getSheetId()]}getCurrentRuntimeSheetData(){var e,r;return(r=(e=this._runtimeData)==null?void 0:e[this.getUnitId()])==null?void 0:r[this.getSheetId()]}getCurrentActiveArrayFormulaCellData(){var e,r;return(r=(e=this._arrayFormulaCellData)==null?void 0:e[this.getUnitId()])==null?void 0:r[this.getSheetId()]}getCurrentRuntimeActiveArrayFormulaCellData(){var e,r;return(r=(e=this._runtimeArrayFormulaCellData)==null?void 0:e[this.getUnitId()])==null?void 0:r[this.getSheetId()]}getCellData(e,r){const s=this.getCurrentActiveSheetData(),i=this.getCurrentRuntimeSheetData(),a=this.getCurrentActiveArrayFormulaCellData(),o=this.getCurrentRuntimeActiveArrayFormulaCellData();return(i==null?void 0:i.getValue(e,r))||(o==null?void 0:o.getValue(e,r))||this.getRuntimeFeatureCellValue(e,r)||(a==null?void 0:a.getValue(e,r))||s.cellData.getValue(e,r)}getRuntimeFeatureCellValue(e,r){var i;const s=Object.keys(this._runtimeFeatureCellData);for(const a of s){const o=this._runtimeFeatureCellData[a],u=(i=o==null?void 0:o[this.getUnitId()])==null?void 0:i[this.getSheetId()];if(u==null)continue;const c=u.getValue(e,r);if(c!=null)return c}}getCellByPosition(e,r){e||(e=this._rangeData.startRow),r||(r=this._rangeData.startColumn);const s=this.getCellData(e,r);return s?this.getCellValueObject(s):d.create(f.VALUE)}toArrayValueObject(e=!0){var E;const{startRow:r,endRow:s,startColumn:i,endColumn:a}=this.getRangePosition(),o=`${this.getUnitId()}_${this.getSheetId()}_${r}_${s}_${i}_${a}`,u=vt.get(o);if(u&&e)return u;const c=s-r+1,l=a-i+1;if(c<0||l<0)return this._getBlankArrayValueObject();const h=new Array(c);this.iterator((R,D,b)=>{const w=D-r,S=b-i;h[w]||(h[w]=new Array(l)),R==null&&(R=new Me(0)),h[w][S]=R});const m={calculateValueList:h,rowCount:h.length,columnCount:((E=h[0])==null?void 0:E.length)||0,unitId:this.getUnitId(),sheetId:this.getSheetId(),row:r,column:i},_=new J(m);return e&&vt.set(o,_),_}toUnitRange(){return{range:this.getRangePosition(),sheetId:this.getSheetId(),unitId:this.getUnitId()}}_checkIfWorksheetMiss(){return(this._forcedSheetId==null||this._forcedSheetId.length===0)&&this._forcedSheetName.length>0}_getBlankArrayValueObject(){const e={calculateValueList:[],rowCount:0,columnCount:0,unitId:this.getUnitId(),sheetId:this.getSheetId(),row:0,column:0};return new J(e)}}class Tn extends gt{constructor(n){super(),this._promise=n}isAsyncObject(){return!0}async getValue(){return this._promise}}class Kn extends gt{constructor(n){super(),this._promiseList=n}isAsyncArrayObject(){return!0}async getValue(){var r;const n=[];for(let s=0;s<this._promiseList.length;s++){const i=this._promiseList[s];n[s]==null&&(n[s]=[]);for(let a=0;a<i.length;a++){const o=i[a];o.isAsyncObject()?n[s][a]=await o.getValue():n[s][a]=o}}const e={calculateValueList:n,rowCount:n.length,columnCount:((r=n[0])==null?void 0:r.length)||0,unitId:"",sheetId:"",row:0,column:0};return new J(e)}}class et extends ve{constructor(n,e,r){super(""),this.setRangeData(n),e&&this.setForcedSheetIdDirect(e),r&&this.setForcedUnitIdDirect(r)}isRange(){return!0}}const Ar=[];var Gn=(t=>{})();class F extends g.Disposable{constructor(e){super();p(this,"_unitId");p(this,"_subUnitId");p(this,"_row",-1);p(this,"_column",-1);this._name=e}get name(){return this._name}get unitId(){return this._unitId}get subUnitId(){return this._subUnitId}get row(){return this._row}get column(){return this._column}isAsync(){return!1}isAddress(){return!1}isCustom(){return!1}setRefInfo(e,r,s,i){this._unitId=e,this._subUnitId=r,this._row=s,this._column=i}calculateCustom(...e){return null}calculate(...e){return d.create(f.VALUE)}checkArrayType(e){return e.isReferenceObject()||e.isValueObject()&&e.isArray()}getIndexNumValue(e){if(e.isArray()&&(e=e.getFirstCell()),e.isBoolean())return e.getValue()===!1?new d(f.VALUE):1;if(e.isString()){const r=Number(e.getValue());if(isNaN(r))return new d(f.REF)}else if(e.isNumber())return e.getValue();return new d(f.VALUE)}getZeroOrOneByOneDefault(e){if(e==null)return 1;let r=1;if(e.isArray()&&(e=e.getFirstCell()),e.isBoolean())e.getValue()===!1&&(r=0);else{if(e.isString())return;e.isNumber()&&e.getValue()===0&&(r=0)}return r}}const Or=[];var Br=(t=>(t.BETADIST="BETADIST",t.BETAINV="BETAINV",t.BINOMDIST="BINOMDIST",t.CHIDIST="CHIDIST",t.CHIINV="CHIINV",t.CHITEST="CHITEST",t.CONFIDENCE="CONFIDENCE",t.COVAR="COVAR",t.CRITBINOM="CRITBINOM",t.EXPONDIST="EXPONDIST",t.FDIST="FDIST",t.FINV="FINV",t.FTEST="FTEST",t.GAMMADIST="GAMMADIST",t.GAMMAINV="GAMMAINV",t.HYPGEOMDIST="HYPGEOMDIST",t.LOGINV="LOGINV",t.LOGNORMDIST="LOGNORMDIST",t.MODE="MODE",t.NEGBINOMDIST="NEGBINOMDIST",t.NORMDIST="NORMDIST",t.NORMINV="NORMINV",t.NORMSDIST="NORMSDIST",t.NORMSINV="NORMSINV",t.PERCENTILE="PERCENTILE",t.PERCENTRANK="PERCENTRANK",t.POISSON="POISSON",t.QUARTILE="QUARTILE",t.RANK="RANK",t.STDEV="STDEV",t.STDEVP="STDEVP",t.TDIST="TDIST",t.TINV="TINV",t.TTEST="TTEST",t.VAR="VAR",t.VARP="VARP",t.WEIBULL="WEIBULL",t.ZTEST="ZTEST",t))(Br||{});const Ur=[];var Fr=(t=>(t.CUBEKPIMEMBER="CUBEKPIMEMBER",t.CUBEMEMBER="CUBEMEMBER",t.CUBEMEMBERPROPERTY="CUBEMEMBERPROPERTY",t.CUBERANKEDMEMBER="CUBERANKEDMEMBER",t.CUBESET="CUBESET",t.CUBESETCOUNT="CUBESETCOUNT",t.CUBEVALUE="CUBEVALUE",t))(Fr||{});const Mr=[];var kr=(t=>(t.DAVERAGE="DAVERAGE",t.DCOUNT="DCOUNT",t.DCOUNTA="DCOUNTA",t.DGET="DGET",t.DMAX="DMAX",t.DMIN="DMIN",t.DPRODUCT="DPRODUCT",t.DSTDEV="DSTDEV",t.DSTDEVP="DSTDEVP",t.DSUM="DSUM",t.DVAR="DVAR",t.DVARP="DVARP",t))(kr||{});const jr=[];var $r=(t=>(t.DATE="DATE",t.DATEDIF="DATEDIF",t.DATEVALUE="DATEVALUE",t.DAY="DAY",t.DAYS="DAYS",t.DAYS360="DAYS360",t.EDATE="EDATE",t.EOMONTH="EOMONTH",t.HOUR="HOUR",t.ISOWEEKNUM="ISOWEEKNUM",t.MINUTE="MINUTE",t.MONTH="MONTH",t.NETWORKDAYS="NETWORKDAYS",t.NETWORKDAYS_INTL="NETWORKDAYS.INTL",t.NOW="NOW",t.SECOND="SECOND",t.TIME="TIME",t.TIMEVALUE="TIMEVALUE",t.TODAY="TODAY",t.WEEKDAY="WEEKDAY",t.WEEKNUM="WEEKNUM",t.WORKDAY="WORKDAY",t.WORKDAY_INTL="WORKDAY.INTL",t.YEAR="YEAR",t.YEARFRAC="YEARFRAC",t))($r||{});const Qr=[];var Hr=(t=>(t.BESSELI="BESSELI",t.BESSELJ="BESSELJ",t.BESSELK="BESSELK",t.BESSELY="BESSELY",t.BIN2DEC="BIN2DEC",t.BIN2HEX="BIN2HEX",t.BIN2OCT="BIN2OCT",t.BITAND="BITAND",t.BITLSHIFT="BITLSHIFT",t.BITOR="BITOR",t.BITRSHIFT="BITRSHIFT",t.BITXOR="BITXOR",t.COMPLEX="COMPLEX",t.CONVERT="CONVERT",t.DEC2BIN="DEC2BIN",t.DEC2HEX="DEC2HEX",t.DEC2OCT="DEC2OCT",t.DELTA="DELTA",t.ERF="ERF",t.ERF_PRECISE="ERF.PRECISE",t.ERFC="ERFC",t.ERFC_PRECISE="ERFC.PRECISE",t.GESTEP="GESTEP",t.HEX2BIN="HEX2BIN",t.HEX2DEC="HEX2DEC",t.HEX2OCT="HEX2OCT",t.IMABS="IMABS",t.IMAGINARY="IMAGINARY",t.IMARGUMENT="IMARGUMENT",t.IMCONJUGATE="IMCONJUGATE",t.IMCOS="IMCOS",t.IMCOSH="IMCOSH",t.IMCOT="IMCOT",t.IMCSC="IMCSC",t.IMCSCH="IMCSCH",t.IMDIV="IMDIV",t.IMEXP="IMEXP",t.IMLN="IMLN",t.IMLOG10="IMLOG10",t.IMLOG2="IMLOG2",t.IMPOWER="IMPOWER",t.IMPRODUCT="IMPRODUCT",t.IMREAL="IMREAL",t.IMSEC="IMSEC",t.IMSECH="IMSECH",t.IMSIN="IMSIN",t.IMSINH="IMSINH",t.IMSQRT="IMSQRT",t.IMSUB="IMSUB",t.IMSUM="IMSUM",t.IMTAN="IMTAN",t.OCT2BIN="OCT2BIN",t.OCT2DEC="OCT2DEC",t.OCT2HEX="OCT2HEX",t))(Hr||{});const Yr=[];var Xr=(t=>(t.ACCRINT="ACCRINT",t.ACCRINTM="ACCRINTM",t.AMORDEGRC="AMORDEGRC",t.AMORLINC="AMORLINC",t.COUPDAYBS="COUPDAYBS",t.COUPDAYS="COUPDAYS",t.COUPDAYSNC="COUPDAYSNC",t.COUPNCD="COUPNCD",t.COUPNUM="COUPNUM",t.COUPPCD="COUPPCD",t.CUMIPMT="CUMIPMT",t.CUMPRINC="CUMPRINC",t.DB="DB",t.DDB="DDB",t.DISC="DISC",t.DOLLARDE="DOLLARDE",t.DOLLARFR="DOLLARFR",t.DURATION="DURATION",t.EFFECT="EFFECT",t.FV="FV",t.FVSCHEDULE="FVSCHEDULE",t.INTRATE="INTRATE",t.IPMT="IPMT",t.IRR="IRR",t.ISPMT="ISPMT",t.MDURATION="MDURATION",t.MIRR="MIRR",t.NOMINAL="NOMINAL",t.NPER="NPER",t.NPV="NPV",t.ODDFPRICE="ODDFPRICE",t.ODDFYIELD="ODDFYIELD",t.ODDLPRICE="ODDLPRICE",t.ODDLYIELD="ODDLYIELD",t.PDURATION="PDURATION",t.PMT="PMT",t.PPMT="PPMT",t.PRICE="PRICE",t.PRICEDISC="PRICEDISC",t.PRICEMAT="PRICEMAT",t.PV="PV",t.RATE="RATE",t.RECEIVED="RECEIVED",t.RRI="RRI",t.SLN="SLN",t.SYD="SYD",t.TBILLEQ="TBILLEQ",t.TBILLPRICE="TBILLPRICE",t.TBILLYIELD="TBILLYIELD",t.VDB="VDB",t.XIRR="XIRR",t.XNPV="XNPV",t.YIELD="YIELD",t.YIELDDISC="YIELDDISC",t.YIELDMAT="YIELDMAT",t))(Xr||{});const Wr=[];var Tr=(t=>(t.CELL="CELL",t.ERROR_TYPE="ERROR.TYPE",t.INFO="INFO",t.ISBLANK="ISBLANK",t.ISERR="ISERR",t.ISERROR="ISERROR",t.ISEVEN="ISEVEN",t.ISFORMULA="ISFORMULA",t.ISLOGICAL="ISLOGICAL",t.ISNA="ISNA",t.ISNONTEXT="ISNONTEXT",t.ISNUMBER="ISNUMBER",t.ISODD="ISODD",t.ISOMITTED="ISOMITTED",t.ISREF="ISREF",t.ISTEXT="ISTEXT",t.N="N",t.NA="NA",t.SHEET="SHEET",t.SHEETS="SHEETS",t.TYPE="TYPE",t))(Tr||{}),tt=(t=>(t.AND="AND",t.BYCOL="BYCOL",t.BYROW="BYROW",t.FALSE="FALSE",t.IF="IF",t.IFERROR="IFERROR",t.IFNA="IFNA",t.IFS="IFS",t.LAMBDA="LAMBDA",t.LET="LET",t.MAKEARRAY="MAKEARRAY",t.MAP="MAP",t.NOT="NOT",t.OR="OR",t.REDUCE="REDUCE",t.SCAN="SCAN",t.SWITCH="SWITCH",t.TRUE="TRUE",t.XOR="XOR",t))(tt||{});class In extends F{calculate(...n){return new d(f.VALUE)}}class qn extends F{calculate(...n){if(n.length!==3)return new d(f.VALUE);const e=this.getIndexNumValue(n[0]);if(typeof e!="number")return e;const r=this.getIndexNumValue(n[1]);if(typeof r!="number")return r;if(!(n[2].isValueObject()&&n[2].isLambda()))return new d(f.VALUE);const s=n[2],i=[];for(let a=0;a<e;a++){i[a]==null&&(i[a]=[]);for(let o=0;o<r;o++){const u=s.execute(new C(a+1),new C(o+1));i[a][o]=u}}return new Kn(i)}isAsync(){return!0}}const Kr=[[In,tt.LAMBDA],[qn,tt.MAKEARRAY]];class zn extends F{calculate(n,e,r,s,i){if(n.isError()||e.isError())return d.create(f.VALUE);const a=Number(n.getValue())-1,o=Number(e.getValue())-1;if(Number.isNaN(a)||Number.isNaN(o))return d.create(f.VALUE);const u={startRow:a,startColumn:o,endRow:a,endColumn:o,startAbsoluteRefType:g.AbsoluteRefType.ALL,endAbsoluteRefType:g.AbsoluteRefType.ALL},c=g.serializeRange(u);return new X(c)}}var we=(t=>(t.ADDRESS="ADDRESS",t.AREAS="AREAS",t.CHOOSE="CHOOSE",t.CHOOSECOLS="CHOOSECOLS",t.CHOOSEROWS="CHOOSEROWS",t.COLUMN="COLUMN",t.COLUMNS="COLUMNS",t.DROP="DROP",t.EXPAND="EXPAND",t.FILTER="FILTER",t.FORMULATEXT="FORMULATEXT",t.GETPIVOTDATA="GETPIVOTDATA",t.HLOOKUP="HLOOKUP",t.HSTACK="HSTACK",t.HYPERLINK="HYPERLINK",t.IMAGE="IMAGE",t.INDEX="INDEX",t.INDIRECT="INDIRECT",t.LOOKUP="LOOKUP",t.MATCH="MATCH",t.OFFSET="OFFSET",t.ROW="ROW",t.ROWS="ROWS",t.RTD="RTD",t.SORT="SORT",t.SORTBY="SORTBY",t.TAKE="TAKE",t.TOCOL="TOCOL",t.TOROW="TOROW",t.TRANSPOSE="TRANSPOSE",t.UNIQUE="UNIQUE",t.VLOOKUP="VLOOKUP",t.VSTACK="VSTACK",t.WRAPCOLS="WRAPCOLS",t.WRAPROWS="WRAPROWS",t.XLOOKUP="XLOOKUP",t.XMATCH="XMATCH",t))(we||{});class It extends ve{constructor(n){super(n);const e=g.deserializeRangeWithSheet(n);this.setForcedUnitIdDirect(e.unitId),this.setForcedSheetName(e.sheetName),this.setRangeData(e.range)}isCell(){return!0}unionBy(n){if(!n.isCell())return d.create(f.REF);const e=n,r=this.unionRange(this.getRangeData(),e.getRangeData());return this._createRange(r)}unionRange(n,e){const r=n.startRow,s=n.startColumn,i=e.startRow,a=e.startColumn,o={startRow:-1,startColumn:-1,endRow:-1,endColumn:-1};return r>i?(o.startRow=i,o.endRow=r):(o.startRow=r,o.endRow=i),s>a?(o.startColumn=a,o.endColumn=s):(o.startColumn=s,o.endColumn=a),o}_createRange(n){const e=new et(n,this.getForcedSheetId(),this.getForcedUnitId());e.setUnitData(this.getUnitData()),e.setDefaultSheetId(this.getDefaultSheetId()),e.setDefaultUnitId(this.getDefaultUnitId()),e.setRuntimeData(this.getRuntimeData()),e.setArrayFormulaCellData(this.getArrayFormulaCellData()),e.setRuntimeArrayFormulaCellData(this.getRuntimeArrayFormulaCellData()),e.setRuntimeFeatureCellData(this.getRuntimeFeatureCellData());const{x:r,y:s}=this.getRefOffset();e.setRefOffset(r,s);const i=this.getForcedSheetId();e.setForcedSheetName(this.getForcedSheetName()),i!=null&&e.setForcedSheetIdDirect(i);const a=this.getForcedUnitId();return a&&e.setForcedUnitIdDirect(a),e}}class Gr extends ve{constructor(n){super(n);const e=g.deserializeRangeWithSheet(n);this.setForcedUnitIdDirect(e.unitId),this.setForcedSheetName(e.sheetName);const r={startColumn:e.range.startColumn,startRow:NaN,endColumn:-1,endRow:NaN};this.setRangeData(r)}isColumn(){return!0}unionBy(n){if(!n.isColumn())return d.create(f.REF);const e=n;if(e.getForcedSheetName()!==void 0&&e.getForcedSheetName()!=="")return d.create(f.REF);const r=this.getRangeData(),s=e.getRangeData().startColumn,i=r.startColumn;return s>i?r.endColumn=s:(r.startColumn=s,r.endColumn=i),this}}class Ir extends ve{constructor(n){super(n);const e=g.deserializeRangeWithSheet(n);this.setForcedUnitIdDirect(e.unitId),this.setForcedSheetName(e.sheetName);const r={startColumn:NaN,startRow:e.range.startRow,endColumn:NaN,endRow:-1};this.setRangeData(r)}isRow(){return!0}unionBy(n){if(!n.isRow())return d.create(f.REF);const e=n;if(e.getForcedSheetName()!==void 0&&e.getForcedSheetName()!=="")return d.create(f.REF);const r=this.getRangeData(),s=e.getRangeData().startRow,i=r.startRow;return s>i?r.endRow=s:(r.startRow=s,r.endRow=i),this}}class Zn extends F{calculate(n,e){let r=this.getZeroOrOneByOneDefault(e);if(r==null&&(r=1),n.isError())return new d(f.NA);if(n.isArray()){const l=n;if(l.getRowCount()===1&&l.getColumnCount()===1)n=l.getFirstCell();else return l.map(()=>new d(f.VALUE))}if(!n.isString())return new d(f.REF);const s=n.getValue();if(r===0){const l=g.deserializeRangeForR1C1(s),{range:h,sheetName:m,unitId:_}=l,E=new et(h);return E.setForcedUnitIdDirect(_),E.setForcedSheetName(m),this._setDefault(E)}if(new RegExp(ht).test(s))return this._setDefault(new It(s));if(new RegExp(Er).test(s))return this._setDefault(new Ir(s));if(new RegExp(Cr).test(s))return this._setDefault(new Gr(s));const i=g.deserializeRangeWithSheet(s),{range:a,sheetName:o,unitId:u}=i,c=new et(a);return c.setForcedUnitIdDirect(u),c.setForcedSheetName(o),this._setDefault(c)}_setDefault(n){return this.unitId==null||this.subUnitId==null?new d(f.REF):(n.setDefaultUnitId(this.unitId),n.setDefaultSheetId(this.subUnitId),n)}}class Jn extends F{calculate(n,e,r,s,i){return new It("A5")}}class Nn extends F{calculate(n,e,r,s){if(n.isError())return n;if(e.isError())return new d(f.REF);if(!e.isArray())return new d(f.VALUE);if(r.isError())return new d(f.NA);if(s!=null&&s.isError())return new d(f.NA);const i=this.getZeroOrOneByOneDefault(s);if(i==null)return new d(f.VALUE);const a=this.getIndexNumValue(r);if(a instanceof d)return a;const o=e.slice(void 0,[0,1]),u=e.slice(void 0,[a-1,a]);return o==null||u==null?new d(f.VALUE):n.isArray()?n.map(c=>this._handleSingleObject(c,o,u,i)):this._handleSingleObject(n,o,u,i)}_handleSingleObject(n,e,r,s){if(s===0){const o=r.pick(e.isEqual(n)).getFirstCell();return o.isNull()?new d(f.NA):o}const i=e.binarySearch(n);if(i==null)return new d(f.NA);const a=r.get(i,0);return a.isNull()?new d(f.NA):a}}const qr=[[zn,we.ADDRESS],[Zn,we.INDIRECT],[Jn,we.OFFSET],[Nn,we.VLOOKUP]];class es extends F{calculate(n){return n.isError()?d.create(f.VALUE):(n.isReferenceObject()&&(n=n.toArrayValueObject()),n.abs())}}class ts extends F{calculate(n){return n.isError()?d.create(f.VALUE):(n.isReferenceObject()&&(n=n.toArrayValueObject()),n.acos())}}class rs extends F{calculate(n){return n.isError()?d.create(f.VALUE):(n.isReferenceObject()&&(n=n.toArrayValueObject()),n.acosh())}}class ns extends F{calculate(n){return n.isError()?d.create(f.VALUE):(n.isReferenceObject()&&(n=n.toArrayValueObject()),n.isArray()?n.map(e=>e.isError()?e:ar(e)):ar(n))}}function ar(t){let n=t.getValue();if(t.isBoolean()&&(n=n?1:0),!Number.isFinite(n))return d.create(f.VALUE);const e=Math.atan(1/Number(n));return Number.isNaN(e)?d.create(f.VALUE):new C(e)}var z=(t=>(t.ABS="ABS",t.ACOS="ACOS",t.ACOSH="ACOSH",t.ACOT="ACOT",t.ACOTH="ACOTH",t.AGGREGATE="AGGREGATE",t.ARABIC="ARABIC",t.ASIN="ASIN",t.ASINH="ASINH",t.ATAN="ATAN",t.ATAN2="ATAN2",t.ATANH="ATANH",t.BASE="BASE",t.CEILING="CEILING",t.CEILING_MATH="CEILING.MATH",t.CEILING_PRECISE="CEILING.PRECISE",t.COMBIN="COMBIN",t.COMBINA="COMBINA",t.COS="COS",t.COSH="COSH",t.COT="COT",t.COTH="COTH",t.CSC="CSC",t.CSCH="CSCH",t.DECIMAL="DECIMAL",t.DEGREES="DEGREES",t.EVEN="EVEN",t.EXP="EXP",t.FACT="FACT",t.FACTDOUBLE="FACTDOUBLE",t.FLOOR="FLOOR",t.FLOOR_MATH="FLOOR.MATH",t.FLOOR_PRECISE="FLOOR.PRECISE",t.GCD="GCD",t.INT="INT",t.ISO_CEILING="ISO.CEILING",t.LCM="LCM",t.LET="LET",t.LN="LN",t.LOG="LOG",t.LOG10="LOG10",t.MDETERM="MDETERM",t.MINVERSE="MINVERSE",t.MMULT="MMULT",t.MOD="MOD",t.MROUND="MROUND",t.MULTINOMIAL="MULTINOMIAL",t.MUNIT="MUNIT",t.ODD="ODD",t.PI="PI",t.POWER="POWER",t.PRODUCT="PRODUCT",t.QUOTIENT="QUOTIENT",t.RADIANS="RADIANS",t.RAND="RAND",t.RANDARRAY="RANDARRAY",t.RANDBETWEEN="RANDBETWEEN",t.ROMAN="ROMAN",t.ROUND="ROUND",t.ROUNDDOWN="ROUNDDOWN",t.ROUNDUP="ROUNDUP",t.SEC="SEC",t.SECH="SECH",t.SERIESSUM="SERIESSUM",t.SEQUENCE="SEQUENCE",t.SIGN="SIGN",t.SIN="SIN",t.SINH="SINH",t.SQRT="SQRT",t.SQRTPI="SQRTPI",t.SUBTOTAL="SUBTOTAL",t.SUM="SUM",t.SUMIF="SUMIF",t.SUMIFS="SUMIFS",t.SUMPRODUCT="SUMPRODUCT",t.SUMSQ="SUMSQ",t.SUMX2MY2="SUMX2MY2",t.SUMX2PY2="SUMX2PY2",t.SUMXMY2="SUMXMY2",t.TAN="TAN",t.TANH="TANH",t.TRUNC="TRUNC",t))(z||{});class ss extends F{calculate(n,e){return d.create(f.VALUE)}}class is extends F{calculate(...n){let e=new C(0);for(let r=0;r<n.length;r++){let s=n[r];if(s.isError())return s;if(s.isString())return new d(f.VALUE);if(e.isError())return e;s.isArray()&&(s=s.sum()),e=e.plus(s)}return e}}function as(t){const n=[y.EQUALS,y.NOT_EQUAL,y.GREATER_THAN_OR_EQUAL,y.GREATER_THAN,y.LESS_THAN_OR_EQUAL,y.LESS_THAN];for(const e of n)if(t.startsWith(e)){const r=t.substring(e.length);return[e,he.create(r)]}return[y.EQUALS,he.create(t)]}function os(t,n){const e=t.toArrayValueObject(),r=`${n.getValue()}`,[s,i]=as(r);return An(r)?e.wildcard(i,s):e.compare(i,s)}class us extends F{calculate(...n){if(n.length<2||n.length>3)return d.create(f.NA);const e=n[0],r=n[1],s=n[2];if(e.isError()||r.isError()||s&&s.isError())return d.create(f.VALUE);let i=new C(0);if(e.isReferenceObject()||e.isValueObject()&&e.isArray()){const o=os(e,r).getArrayValue(),u=s||e,{startRow:c,startColumn:l}=u.getRangePosition();u.iterator((h,m,_)=>{if(!(h!=null&&h.isError())){const R=o[m-c][_-l].getValue()?h:new C(0);i=i.plus(R)}})}else r.isValueObject()&&(i=this._validator(e,r));return i}_validator(n,e){const r=e.getValue();if(r){const s=r.substring(0,1),i=r.substring(1);n.compare(new C(i),s).getValue()||(n=new C(0))}return n}}class cs extends F{calculate(...n){return d.create(f.VALUE)}}const zr=[[es,z.ABS],[ts,z.ACOS],[rs,z.ACOSH],[ns,z.ACOT],[is,z.SUM],[us,z.SUMIF],[cs,z.SUMIFS],[ss,z.POWER]];class ls extends F{constructor(){super(...arguments);p(this,"_compareType",y.EQUALS)}setCompareType(e){this._compareType=e}calculate(e,r){return e.isError()||r.isError()?e:e.compare(r,this._compareType)}}class hs extends F{calculate(n,e){return n.isError()||e.isError()?n:!e.isArray()&&e.getValue()===0?d.create(f.DIV_BY_ZERO):n.divided(e)}}var T=(t=>(t.COMPARE="COMPARE",t.DIVIDED="DIVIDED",t.MINUS="MINUS",t.MULTIPLY="MULTIPLY",t.PLUS="PLUS",t.UNION="UNION",t))(T||{});class fs extends F{calculate(n,e){return n.isError()||e.isError()?n:n.minus(e)}}class ds extends F{calculate(n,e){return n.isError()?n:e.isError()?e:n.multiply(e)}}class ms extends F{calculate(n,e){return n.isError()?n:e.isError()?e:n.plus(e)}}const Zr=[[ls,T.COMPARE],[hs,T.DIVIDED],[fs,T.MINUS],[ds,T.MULTIPLY],[ms,T.PLUS]];class gs extends F{calculate(...n){let e=new C(0),r=new C(0);for(let s=0;s<n.length;s++){const i=n[s];if(i.isError())return i;if(e.isError())return e;i.isArray()?(e=e.plus(i.sum()),r=r.plus(i.count())):i.isNull()||(r=r.plus(new C(1)))}return e.divided(r)}}class Rs extends F{calculate(...n){let e=new C(0);for(let r=0;r<n.length;r++){let s=n[r];s.isError()||(s.isArray()?(s=s.count(),e=e.plus(s)):!s.isNull()&&!s.isString()&&(e=e.plus(new C(1))))}return e}}class ps extends F{calculate(...n){let e=new C(0);for(let r=0;r<n.length;r++){let s=n[r];if(s.isError()){e=e.plus(new C(1));continue}s.isArray()?(s=s.countA(),e=e.plus(s)):s.isNull()||(e=e.plus(new C(1)))}return e}}var ue=(t=>(t.AVEDEV="AVEDEV",t.AVERAGE="AVERAGE",t.AVERAGEA="AVERAGEA",t.AVERAGEIF="AVERAGEIF",t.AVERAGEIFS="AVERAGEIFS",t.BETA_DIST="BETA.DIST",t.BETA_INV="BETA.INV",t.BINOM_DIST="BINOM.DIST",t.BINOM_DIST_RANGE="BINOM.DIST.RANGE",t.BINOM_INV="BINOM.INV",t.CHISQ_DIST="CHISQ.DIST",t.CHISQ_DIST_RT="CHISQ.DIST.RT",t.CHISQ_INV="CHISQ.INV",t.CHISQ_INV_RT="CHISQ.INV.RT",t.CHISQ_TEST="CHISQ.TEST",t.CONFIDENCE_NORM="CONFIDENCE.NORM",t.CONFIDENCE_T="CONFIDENCE.T",t.CORREL="CORREL",t.COUNT="COUNT",t.COUNTA="COUNTA",t.COUNTBLANK="COUNTBLANK",t.COUNTIF="COUNTIF",t.COUNTIFS="COUNTIFS",t.COVARIANCE_P="COVARIANCE.P",t.COVARIANCE_S="COVARIANCE.S",t.DEVSQ="DEVSQ",t.EXPON_DIST="EXPON.DIST",t.F_DIST="F.DIST",t.F_DIST_RT="F.DIST.RT",t.F_INV="F.INV",t.F_INV_RT="F.INV.RT",t.F_TEST="F.TEST",t.FISHER="FISHER",t.FISHERINV="FISHERINV",t.FORECAST="FORECAST",t.FORECAST_ETS="FORECAST.ETS",t.FORECAST_ETS_CONFINT="FORECAST.ETS.CONFINT",t.FORECAST_ETS_SEASONALITY="FORECAST.ETS.SEASONALITY",t.FORECAST_ETS_STAT="FORECAST.ETS.STAT",t.FORECAST_LINEAR="FORECAST.LINEAR",t.FREQUENCY="FREQUENCY",t.GAMMA="GAMMA",t.GAMMA_DIST="GAMMA.DIST",t.GAMMA_INV="GAMMA.INV",t.GAMMALN="GAMMALN",t.GAMMALN_PRECISE="GAMMALN.PRECISE",t.GAUSS="GAUSS",t.GEOMEAN="GEOMEAN",t.GROWTH="GROWTH",t.HARMEAN="HARMEAN",t.HYPGEOM_DIST="HYPGEOM.DIST",t.INTERCEPT="INTERCEPT",t.KURT="KURT",t.LARGE="LARGE",t.LINEST="LINEST",t.LOGEST="LOGEST",t.LOGNORM_DIST="LOGNORM.DIST",t.LOGNORM_INV="LOGNORM.INV",t.MAX="MAX",t.MAXA="MAXA",t.MAXIFS="MAXIFS",t.MEDIAN="MEDIAN",t.MIN="MIN",t.MINA="MINA",t.MINIFS="MINIFS",t.MODE_MULT="MODE.MULT",t.MODE_SNGL="MODE.SNGL",t.NEGBINOM_DIST="NEGBINOM.DIST",t.NORM_DIST="NORM.DIST",t.NORM_INV="NORM.INV",t.NORM_S_DIST="NORM.S.DIST",t.NORM_S_INV="NORM.S.INV",t.PEARSON="PEARSON",t.PERCENTILE_EXC="PERCENTILE.EXC",t.PERCENTILE_INC="PERCENTILE.INC",t.PERCENTRANK_EXC="PERCENTRANK.EXC",t.PERCENTRANK_INC="PERCENTRANK.INC",t.PERMUT="PERMUT",t.PERMUTATIONA="PERMUTATIONA",t.PHI="PHI",t.POISSON_DIST="POISSON.DIST",t.PROB="PROB",t.QUARTILE_EXC="QUARTILE.EXC",t.QUARTILE_INC="QUARTILE.INC",t.RANK_AVG="RANK.AVG",t.RANK_EQ="RANK.EQ",t.RSQ="RSQ",t.SKEW="SKEW",t.SKEW_P="SKEW.P",t.SLOPE="SLOPE",t.SMALL="SMALL",t.STANDARDIZE="STANDARDIZE",t.STDEV_P="STDEV.P",t.STDEV_S="STDEV.S",t.STDEVA="STDEVA",t.STDEVPA="STDEVPA",t.STEYX="STEYX",t.T_DIST="T.DIST",t.T_DIST_2T="T.DIST.2T",t.T_DIST_RT="T.DIST.RT",t.T_INV="T.INV",t.T_INV_2T="T.INV.2T",t.T_TEST="T.TEST",t.TREND="TREND",t.TRIMMEAN="TRIMMEAN",t.VAR_P="VAR.P",t.VAR_S="VAR.S",t.VARA="VARA",t.VARPA="VARPA",t.WEIBULL_DIST="WEIBULL.DIST",t.Z_TEST="Z.TEST",t))(ue||{});class Ds extends F{calculate(...n){let e=new C(-1/0);for(let r=0;r<n.length;r++){let s=n[r];if(s.isError())return s;s.isArray()&&(s=s.max()),!s.isNull()&&(e=this._validator(e,s))}return e}_validator(n,e){return n.isLessThan(e).getValue()&&(n=e),n}}class or extends F{calculate(...n){let e=new C(1/0);for(let r=0;r<n.length;r++){let s=n[r];if(s.isError())return s;s.isArray()&&(s=s.min()),!s.isNull()&&(e=this._validator(e,s))}return e}_validator(n,e){return n.isGreaterThan(e).getValue()&&(n=e),n}}const Jr=[[gs,ue.AVERAGE],[Rs,ue.COUNT],[Ds,ue.MAX],[or,ue.MIN],[or,ue.MIN],[ps,ue.COUNTA]];class _s extends F{calculate(n,e){return d.create(f.VALUE)}}var pt=(t=>(t.ASC="ASC",t.ARRAYTOTEXT="ARRAYTOTEXT",t.BAHTTEXT="BAHTTEXT",t.CHAR="CHAR",t.CLEAN="CLEAN",t.CODE="CODE",t.CONCAT="CONCAT",t.CONCATENATE="CONCATENATE",t.DBCS="DBCS",t.DOLLAR="DOLLAR",t.EXACT="EXACT",t.FIND="FIND",t.FINDB="FINDB",t.FIXED="FIXED",t.LEFT="LEFT",t.LEFTB="LEFTB",t.LEN="LEN",t.LENB="LENB",t.LOWER="LOWER",t.MID="MID",t.MIDB="MIDB",t.NUMBERVALUE="NUMBERVALUE",t.PHONETIC="PHONETIC",t.PROPER="PROPER",t.REPLACE="REPLACE",t.REPLACEB="REPLACEB",t.REPT="REPT",t.RIGHT="RIGHT",t.RIGHTB="RIGHTB",t.SEARCH="SEARCH",t.SEARCHB="SEARCHB",t.SUBSTITUTE="SUBSTITUTE",t.T="T",t.TEXT="TEXT",t.TEXTAFTER="TEXTAFTER",t.TEXTBEFORE="TEXTBEFORE",t.TEXTJOIN="TEXTJOIN",t.TEXTSPLIT="TEXTSPLIT",t.TRIM="TRIM",t.UNICHAR="UNICHAR",t.UNICODE="UNICODE",t.UPPER="UPPER",t.VALUE="VALUE",t.VALUETOTEXT="VALUETOTEXT",t.CALL="CALL",t.EUROCONVERT="EUROCONVERT",t.REGISTER_ID="REGISTER.ID",t))(pt||{});const Nr=[[_s,pt.CONCATENATE]],en=[];var Es=(t=>{})();const tn=[];var rn=(t=>(t.ENCODEURL="ENCODEURL",t.FILTERXML="FILTERXML",t.WEBSERVICE="WEBSERVICE",t))(rn||{});class Cs extends g.Disposable{constructor(){super(...arguments);p(this,"_definedNameMap",new Map)}dispose(){this._definedNameMap.clear()}registerDefinedName(e,r,s){var a;this._definedNameMap.get(e)==null&&this._definedNameMap.set(e,new Map),(a=this._definedNameMap.get(e))==null||a.set(r,s)}removeDefinedName(e,r){var s;(s=this._definedNameMap.get(e))==null||s.delete(r)}getDefinedNameMap(e){return this._definedNameMap.get(e)}getValue(e,r){var s;return(s=this._definedNameMap.get(e))==null?void 0:s.get(r)}hasDefinedName(e){var s;return(((s=this._definedNameMap.get(e))==null?void 0:s.size)||0)!==0}}const Dt=V.createIdentifier("univer.formula.defined-names.service");var ys=Object.defineProperty,bs=Object.getOwnPropertyDescriptor,ws=(t,n,e,r)=>{for(var s=r>1?void 0:r?bs(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&ys(n,e,s),s},Ls=(t,n)=>(e,r)=>n(e,r,t);let At=class extends g.Disposable{constructor(n){super();p(this,"_unitData",{});p(this,"_arrayFormulaCellData",{});p(this,"_formulaData",{});p(this,"_sheetNameMap",{});p(this,"_forceCalculate",!1);p(this,"_dirtyRanges",[]);p(this,"_dirtyNameMap",{});p(this,"_dirtyUnitFeatureMap",{});p(this,"_excludedCell");this._currentUniverService=n}dispose(){this._unitData={},this._formulaData={},this._arrayFormulaCellData={},this._sheetNameMap={},this._dirtyRanges=[],this._dirtyNameMap={},this._dirtyUnitFeatureMap={},this._excludedCell={}}getExcludedRange(){return this._excludedCell}getUnitData(){return this._unitData}getFormulaData(){return this._formulaData}getArrayFormulaCellData(){return this._arrayFormulaCellData}getSheetNameMap(){return this._sheetNameMap}isForceCalculate(){return this._forceCalculate}getDirtyRanges(){return this._dirtyRanges}getDirtyNameMap(){return this._dirtyNameMap}getDirtyUnitFeatureMap(){return this._dirtyUnitFeatureMap}load(n){if(n.allUnitData&&n.unitSheetNameMap)this._unitData=n.allUnitData,this._sheetNameMap=n.unitSheetNameMap;else{const{allUnitData:e,unitSheetNameMap:r}=this._loadSheetData();this._unitData=e,this._sheetNameMap=r}this._formulaData=n.formulaData,this._arrayFormulaCellData=_r(n.arrayFormulaCellData),this._forceCalculate=n.forceCalculate,this._dirtyRanges=n.dirtyRanges,this._dirtyNameMap=n.dirtyNameMap,this._dirtyUnitFeatureMap=n.dirtyUnitFeatureMap,this._excludedCell=n.excludedCell}loadDirtyRangesAndExcludedCell(n,e){this._dirtyRanges=n,this._excludedCell=e,this._dirtyNameMap={}}registerUnitData(n){this._unitData=n}registerFormulaData(n){this._formulaData=n}registerSheetNameMap(n){this._sheetNameMap=n}_loadSheetData(){const n=this._currentUniverService.getAllUniverSheetsInstance(),e={},r={};for(const s of n){const i=s.getUnitId(),a=s.getSheets(),o={},u={};for(const c of a){const l=c.getSheetId(),h=c.getConfig();o[l]={cellData:new g.ObjectMatrix(h.cellData),rowCount:h.rowCount,columnCount:h.columnCount},u[c.getName()]=c.getSheetId()}e[i]=o,r[i]=u}return{allUnitData:e,unitSheetNameMap:r}}};At=ws([Ls(0,g.IUniverInstanceService)],At);const be=V.createIdentifier("univer.formula.current-data.service");var Ss=Object.defineProperty,Ps=Object.getOwnPropertyDescriptor,Vs=(t,n,e,r)=>{for(var s=r>1?void 0:r?Ps(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Ss(n,e,s),s},xs=(t,n)=>(e,r)=>n(e,r,t),ee=(t=>(t[t.IDLE=0]="IDLE",t[t.START_DEPENDENCY=1]="START_DEPENDENCY",t[t.START_CALCULATION=2]="START_CALCULATION",t[t.CURRENTLY_CALCULATING=3]="CURRENTLY_CALCULATING",t[t.START_DEPENDENCY_ARRAY_FORMULA=4]="START_DEPENDENCY_ARRAY_FORMULA",t[t.START_CALCULATION_ARRAY_FORMULA=5]="START_CALCULATION_ARRAY_FORMULA",t[t.CURRENTLY_CALCULATING_ARRAY_FORMULA=6]="CURRENTLY_CALCULATING_ARRAY_FORMULA",t[t.CALCULATION_COMPLETED=7]="CALCULATION_COMPLETED",t))(ee||{}),Le=(t=>(t[t.INITIAL=0]="INITIAL",t[t.STOP_EXECUTION=1]="STOP_EXECUTION",t[t.NOT_EXECUTED=2]="NOT_EXECUTED",t[t.SUCCESS=3]="SUCCESS",t))(Le||{});let Ot=class extends g.Disposable{constructor(n){super();p(this,"_formulaExecuteStage",0);p(this,"_stopState",!1);p(this,"_currentRow",-1);p(this,"_currentColumn",-1);p(this,"_currentRowCount",-1/0);p(this,"_currentColumnCount",-1/0);p(this,"_currentSubUnitId","");p(this,"_currentUnitId","");p(this,"_runtimeData",{});p(this,"_runtimeOtherData",{});p(this,"_unitArrayFormulaRange",{});p(this,"_runtimeArrayFormulaCellData",{});p(this,"_runtimeClearArrayFormulaCellData",{});p(this,"_runtimeFeatureRange",{});p(this,"_runtimeFeatureCellData",{});p(this,"_functionsExecutedState",0);p(this,"_functionDefinitionPrivacyVar",new Map);p(this,"_totalFormulasToCalculate",0);p(this,"_completedFormulasCount",0);p(this,"_totalArrayFormulasToCalculate",0);p(this,"_completedArrayFormulasCount",0);p(this,"_isCycleDependency",!1);this._currentConfigService=n}get currentRow(){return this._currentRow}get currentColumn(){return this._currentColumn}get currentRowCount(){return this._currentRowCount}get currentColumnCount(){return this._currentColumnCount}get currentSubUnitId(){return this._currentSubUnitId}get currentUnitId(){return this._currentUnitId}dispose(){this.reset(),this._runtimeFeatureCellData={},this._runtimeFeatureRange={}}enableCycleDependency(){this._isCycleDependency=!0}disableCycleDependency(){this._isCycleDependency=!1}isCycleDependency(){return this._isCycleDependency}setTotalArrayFormulasToCalculate(n){this._totalArrayFormulasToCalculate=n}getTotalArrayFormulasToCalculate(){return this._totalArrayFormulasToCalculate}setCompletedArrayFormulasCount(n){this._completedArrayFormulasCount=n}getCompletedArrayFormulasCount(){return this._completedArrayFormulasCount}setTotalFormulasToCalculate(n){this._totalFormulasToCalculate=n}getTotalFormulasToCalculate(){return this._totalFormulasToCalculate}setCompletedFormulasCount(n){this._completedFormulasCount=n}getCompletedFormulasCount(){return this._completedFormulasCount}markedAsSuccessfullyExecuted(){this._functionsExecutedState=3}markedAsNoFunctionsExecuted(){this._functionsExecutedState=2}markedAsStopFunctionsExecuted(){this._functionsExecutedState=1}markedAsInitialFunctionsExecuted(){this._functionsExecutedState=0}stopExecution(){this._stopState=!0,this.setFormulaExecuteStage(0)}isStopExecution(){return this._stopState}setFormulaExecuteStage(n){this._formulaExecuteStage=n}getFormulaExecuteStage(){return this._formulaExecuteStage}reset(){this._formulaExecuteStage=0,this._runtimeData={},this._runtimeOtherData={},this._unitArrayFormulaRange={},this._runtimeArrayFormulaCellData={},this._runtimeClearArrayFormulaCellData={},this._functionDefinitionPrivacyVar.clear(),this.markedAsInitialFunctionsExecuted(),this._isCycleDependency=!1,this._totalFormulasToCalculate=0,this._completedFormulasCount=0}setCurrent(n,e,r,s,i,a){this._currentRow=n,this._currentColumn=e,this._currentRowCount=r,this._currentColumnCount=s,this._currentSubUnitId=i,this._currentUnitId=a}clearFunctionDefinitionPrivacyVar(){this._functionDefinitionPrivacyVar.clear()}registerFunctionDefinitionPrivacyVar(n,e){this._functionDefinitionPrivacyVar.set(n,e)}getFunctionDefinitionPrivacyVar(n){return this._functionDefinitionPrivacyVar.get(n)}setRuntimeOtherData(n,e){const r=this._currentSubUnitId,s=this._currentUnitId;this._runtimeOtherData[s]===void 0&&(this._runtimeOtherData[s]={});const i=this._runtimeOtherData[s];i[r]===void 0&&(i[r]={});const a=i[r];a[n]=this._objectValueToCellValue(e)}setRuntimeData(n){const e=this._currentRow,r=this._currentColumn,s=this._currentRowCount,i=this.currentColumnCount,a=this._currentSubUnitId,o=this._currentUnitId;this._runtimeData[o]==null&&(this._runtimeData[o]={});const u=this._runtimeData[o];u[a]==null&&(u[a]=new g.ObjectMatrix),this._unitArrayFormulaRange[o]==null&&(this._unitArrayFormulaRange[o]={});const c=this._unitArrayFormulaRange[o];let l=new g.ObjectMatrix;c[a]&&(l=new g.ObjectMatrix(c[a])),this._runtimeArrayFormulaCellData[o]===void 0&&(this._runtimeArrayFormulaCellData[o]={});const h=this._runtimeArrayFormulaCellData[o];h[a]==null&&(h[a]=new g.ObjectMatrix),this._runtimeClearArrayFormulaCellData[o]===void 0&&(this._runtimeClearArrayFormulaCellData[o]={});const m=this._runtimeClearArrayFormulaCellData[o];m[a]==null&&(m[a]=new g.ObjectMatrix);const _=u[a],E=h[a],R=m[a];if(n.isReferenceObject()||n.isValueObject()&&n.isArray()){const D=n,{startRow:b,startColumn:w,endRow:S,endColumn:L}=D.getRangePosition();if(b===S&&w===L){const j=this._objectValueToCellValue(D.getFirstCell());_.setValue(e,r,j),R.setValue(e,r,j);return}const k={startRow:e,startColumn:r,endRow:S-b+e,endColumn:L-w+r};if(l.setValue(e,r,k),c[a]=l.getData(),this._checkIfArrayFormulaRangeHasData(o,a,e,r,k)||this._checkIfArrayFormulaExceeded(s,i,k)){const j=this._objectValueToCellValue(new d(f.SPILL));_.setValue(e,r,j),R.setValue(e,r,j)}else{const j=new d(f.SPILL);D.iterator((Q,A,P)=>{const B=this._objectValueToCellValue(Q);if(A===b&&P===w){if(Q!=null&&Q.isError()&&Q.isEqualType(j))return R.setValue(e,r,{}),_.setValue(e,r,{...this._objectValueToCellValue(j)}),!1;_.setValue(e,r,{...B})}E.setValue(A-b+e,P-w+r,B)})}}else{const D=this._objectValueToCellValue(n);_.setValue(e,r,D),R.setValue(e,r,D)}}getUnitData(){return this._runtimeData}getUnitArrayFormula(){return this._unitArrayFormulaRange}getRuntimeOtherData(){return this._runtimeOtherData}getRuntimeArrayFormulaCellData(){return this._runtimeArrayFormulaCellData}getRuntimeClearArrayFormulaCellData(){return this._runtimeClearArrayFormulaCellData}getRuntimeFeatureRange(){return this._runtimeFeatureRange}setRuntimeFeatureRange(n,e){this._runtimeFeatureRange[n]=e}getRuntimeFeatureCellData(){return this._runtimeFeatureCellData}setRuntimeFeatureCellData(n,e){this._runtimeFeatureCellData[n]=e}getAllRuntimeData(){return{unitData:this.getUnitData(),arrayFormulaRange:this.getUnitArrayFormula(),unitOtherData:this.getRuntimeOtherData(),functionsExecutedState:this._functionsExecutedState,arrayFormulaCellData:this.getRuntimeArrayFormulaCellData(),clearArrayFormulaCellData:this.getRuntimeClearArrayFormulaCellData(),runtimeFeatureRange:this.getRuntimeFeatureRange(),runtimeFeatureCellData:this.getRuntimeFeatureCellData()}}getRuntimeState(){return{totalFormulasToCalculate:this.getTotalFormulasToCalculate(),completedFormulasCount:this.getCompletedFormulasCount(),totalArrayFormulasToCalculate:this.getTotalArrayFormulasToCalculate(),completedArrayFormulasCount:this.getCompletedArrayFormulasCount(),stage:this.getFormulaExecuteStage()}}_objectValueToCellValue(n){if(n==null)return{v:0,t:g.CellValueType.NUMBER};if(n.isError())return{v:n.getErrorType(),t:g.CellValueType.STRING};if(n.isValueObject()){const e=n,r=e.getValue();return e.isNumber()?{v:r,t:g.CellValueType.NUMBER}:e.isBoolean()?{v:r,t:g.CellValueType.BOOLEAN}:{v:r,t:g.CellValueType.STRING}}}_checkIfArrayFormulaRangeHasData(n,e,r,s,i){var m,_,E,R,D,b,w,S,L,k,j,Q;const{startRow:a,startColumn:o,endRow:u,endColumn:c}=i,l=this._currentConfigService.getUnitData(),h=(E=(_=(m=this._unitArrayFormulaRange[n])==null?void 0:m[e])==null?void 0:_[r])==null?void 0:E[s];for(let A=a;A<=u;A++)for(let P=o;P<=c;P++){if(A===r&&s===P)continue;const B=(b=(D=(R=this._runtimeData)==null?void 0:R[n])==null?void 0:D[e])==null?void 0:b.getValue(A,P),M=(L=(S=(w=this._runtimeArrayFormulaCellData)==null?void 0:w[n])==null?void 0:S[e])==null?void 0:L.getValue(A,P),dn=(Q=(j=(k=l==null?void 0:l[n])==null?void 0:k[e])==null?void 0:j.cellData)==null?void 0:Q.getValue(A,P);if(!g.isNullCell(B)||!g.isNullCell(M)&&!this._isInArrayFormulaRange(h,A,P)||!g.isNullCell(dn))return!0}return!1}_isInArrayFormulaRange(n,e,r){if(n==null)return!1;const{startRow:s,startColumn:i,endRow:a,endColumn:o}=n;return e>=s&&e<=a&&r>=i&&r<=o}_checkIfArrayFormulaExceeded(n,e,r){return r.endRow>=n||r.endColumn>=e}_isInDirtyRange(n,e,r,s){const i=this._currentConfigService.getDirtyRanges();return i.length===0?!0:Rr(i,n,e,r,s)}};Ot=Vs([xs(0,be)],Ot);const N=V.createIdentifier("univer.formula.runtime.service");var vs=Object.defineProperty,As=Object.getOwnPropertyDescriptor,Os=(t,n,e,r)=>{for(var s=r>1?void 0:r?As(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&vs(n,e,s),s},bt=(t,n)=>(e,r)=>n(e,r,t);let Ee=class extends g.Disposable{constructor(t,n,e){super(),this._definedNamesService=t,this._runtimeService=n,this._lexerTreeBuilder=e}treeBuilder(t,n=!0){return this._lexerTreeBuilder.treeBuilder(t,n,this._injectDefinedName.bind(this))}_injectDefinedName(t){var i;const n=this._runtimeService.currentUnitId;if(!this._definedNamesService.hasDefinedName(n))return{sequenceString:"",hasDefinedName:!1};const e=this._lexerTreeBuilder.getSequenceNode(t);let r="",s=!1;for(let a=0,o=e.length;a<o;a++){const u=e[a];if(typeof u=="string"){r+=u;continue}const{nodeType:c,token:l}=u;if(c===I.REFERENCE||c===I.FUNCTION){const h=(i=this._definedNamesService.getDefinedNameMap(n))==null?void 0:i.get(l);h?(r+=h,s=!0):r+=l}else r+=l}return{sequenceString:r,hasDefinedName:s}}};Ee=Os([bt(0,Dt),bt(1,N),bt(2,V.Inject(ft))],Ee);var v=(t=>(t.REFERENCE="ReferenceNode",t.VALUE="ValueNode",t.OPERATOR="OperatorNode",t.FUNCTION="FunctionNode",t.LAMBDA="LambdaNode",t.LAMBDA_PARAMETER="LambdaNodeParameter",t.ERROR="ErrorNode",t.BASE="Base",t.ROOT="Root",t.UNION="UnionNode",t.PREFIX="PrefixNode",t.SUFFIX="SuffixNode",t.NULL="NullNode",t))(v||{});const re=new Map([["ReferenceNode",7],["ValueNode",9],["OperatorNode",8],["FunctionNode",6],["LambdaNode",1],["LambdaNodeParameter",2],["Root",10],["UnionNode",3],["PrefixNode",4],["SuffixNode",5]]);class G extends g.Disposable{constructor(e){super();p(this,"_children",[]);p(this,"_parent");p(this,"_valueObject");p(this,"_calculateState",!1);p(this,"_async",!1);p(this,"_address",!1);p(this,"_refOffsetX",0);p(this,"_refOffsetY",0);this._token=e}dispose(){var e;this._children.forEach(r=>{r.dispose()}),(e=this._valueObject)==null||e.dispose(),this._parent=null}get nodeType(){return v.BASE}isAsync(){return this._async}isAddress(){return this._address}setAsync(){this._async=!0}setAddress(){this._address=!0}getParent(){return this._parent}setParent(e){this._parent=e,e.addChildren(this)}getChildren(){return this._children}addChildren(...e){this._children.push(...e)}getToken(){return this._token}setValue(e){this._valueObject=e}getValue(){return this._valueObject}isCalculated(){return this._calculateState}setCalculated(){this._calculateState=!0}execute(){}setNotEmpty(e=!0){}setRefOffset(e=0,r=0){this._refOffsetX=e,this._refOffsetY=r}getRefOffset(){return{x:this._refOffsetX,y:this._refOffsetY}}async executeAsync(){return Promise.resolve(pe.SUCCESS)}serialize(){const e=this.getToken(),r=this.getChildren(),s=[],i=r.length;for(let o=0;o<i;o++){const u=r[o];s.push(u.serialize())}const a={token:e,nodeType:this.nodeType};return i>0&&(a.children=s),a}}class H extends G{constructor(e){super(e);p(this,"_errorValueObject");this._errorValueObject=d.create(e)}get nodeType(){return v.ERROR}static create(e){return new H(e)}getValue(){return this._errorValueObject}}const ne=100;class se extends g.Disposable{get zIndex(){return 0}create(n,e,r){let s;return n instanceof x?s=n.getToken():s=n,new G(s)}checkAndCreateNodeType(n){}}class Bt extends G{get nodeType(){return v.ROOT}execute(){const e=this.getChildren()[0];this.setValue(e.getValue())}}class nn extends se{get zIndex(){return re.get(v.ROOT)||ne}checkAndCreateNodeType(n){if(!(n instanceof x))return;if(n.getToken()===ce)return new Bt(ce)}}class sn extends g.Disposable{constructor(){super(...arguments);p(this,"_functionExecutors",new Map);p(this,"_functionDescriptions",new Map)}dispose(){this._functionExecutors.clear(),this._functionDescriptions.clear()}registerExecutors(...e){for(let r=0;r<e.length;r++){const s=e[r];this._functionExecutors.set(s.name,s)}}getExecutors(){return this._functionExecutors}getExecutor(e){return this._functionExecutors.get(e)}hasExecutor(e){return this._functionExecutors.has(e)}unregisterExecutors(...e){for(let r=0;r<e.length;r++){const s=e[r];this._functionExecutors.delete(s)}}registerDescriptions(...e){for(let r=0;r<e.length;r++){const s=e[r];this._functionDescriptions.set(s.functionName,s)}}getDescriptions(){return this._functionDescriptions}getDescription(e){return this._functionDescriptions.get(e)}hasDescription(e){return this._functionDescriptions.has(e)}unregisterDescriptions(...e){for(let r=0;r<e.length;r++){const s=e[r];this._functionDescriptions.delete(s)}}}const ae=V.createIdentifier("univer.formula.function.service");var Bs=Object.defineProperty,Us=Object.getOwnPropertyDescriptor,Fs=(t,n,e,r)=>{for(var s=r>1?void 0:r?Us(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Bs(n,e,s),s},ur=(t,n)=>(e,r)=>n(e,r,t);class rt extends G{constructor(n,e,r){super(e),this._accessor=n,this._operatorString=e,this._functionExecutor=r}get nodeType(){return v.PREFIX}execute(){let e=this.getChildren()[0].getValue(),r;if(e==null)throw new Error("object is null");e.isReferenceObject()&&(e=e.toArrayValueObject()),this._operatorString===$.MINUS?r=this._functionExecutor.calculate(new C(0),e):this._operatorString===$.AT?r=this._handlerAT(e):r=d.create(f.VALUE),this.setValue(r)}_handlerAT(n){if(!n.isReferenceObject())return d.create(f.VALUE);const e=n;if(e.isCell())return d.create(f.VALUE);const r=this._accessor.get(N),s=r.currentRow||0,i=r.currentColumn||0;return e.isRow()?e.getCellByColumn(i):e.isColumn()?e.getCellByRow(s):e.isRange()||e.isTable()?e.getCellByPosition():d.create(f.VALUE)}}let nt=class extends se{constructor(t,n){super(),this._functionService=t,this._injector=n}get zIndex(){return re.get(v.PREFIX)||ne}checkAndCreateNodeType(t){if(!(t instanceof x))return;const n=t.getToken(),e=n.trim();if(e.charAt(0)==='"'&&e.charAt(e.length-1)==='"')return;let r="";if(e===$.MINUS)r=T.MINUS;else return e===$.AT?new rt(this._injector,e):void 0;const s=this._functionService.getExecutor(r);return s?new rt(this._injector,e,s):(console.error(`No function ${n}`),H.create(f.NAME))}};nt=Fs([ur(0,ae),ur(1,V.Inject(V.Injector))],nt);var Ms=Object.defineProperty,ks=Object.getOwnPropertyDescriptor,js=(t,n,e,r)=>{for(var s=r>1?void 0:r?ks(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Ms(n,e,s),s},Qe=(t,n)=>(e,r)=>n(e,r,t);class $s extends G{constructor(n,e,r,s){super(n),this._functionExecutor=e,this._currentConfigService=r,this._runtimeService=s,this._functionExecutor.isAsync()&&this.setAsync(),this._functionExecutor.isAddress()&&this.setAddress()}get nodeType(){return v.FUNCTION}async executeAsync(){const n=[],e=this.getChildren(),r=e.length;for(let a=0;a<r;a++){const o=e[a].getValue();o!=null&&(o.isReferenceObject()?n.push(o.toArrayValueObject()):n.push(o))}const s=this._calculate(n);let i;return s.isAsyncObject()||s.isAsyncArrayObject()?i=await s.getValue():i=s,this._setRefData(i),this.setValue(i),Promise.resolve(pe.SUCCESS)}execute(){const n=[],e=this.getChildren(),r=e.length;for(let i=0;i<r;i++){const a=e[i].getValue();a!=null&&(a.isReferenceObject()?n.push(a.toArrayValueObject()):n.push(a))}const s=this._calculate(n);this._setRefData(s),this.setValue(s)}_calculate(n){var r;let e;if(this._setRefInfo(),this._functionExecutor.isCustom()){const s=this._functionExecutor.calculateCustom(...n.map(i=>i.isArray()?i.toValue():i.getValue()));if(typeof s!="object"||s==null)e=he.create(s);else{const i=Yn(s);e=new J({calculateValueList:i,rowCount:i.length,columnCount:((r=i[0])==null?void 0:r.length)||0,unitId:"",sheetId:"",row:-1,column:-1})}}else e=this._functionExecutor.calculate(...n);return e}_setRefInfo(){const{currentUnitId:n,currentSubUnitId:e,currentRow:r,currentColumn:s}=this._runtimeService;this._functionExecutor.setRefInfo(n,e,r,s)}_setRefData(n){if(!n.isReferenceObject())return;const e=n;e.setForcedSheetId(this._currentConfigService.getSheetNameMap()),e.setUnitData(this._currentConfigService.getUnitData()),e.setArrayFormulaCellData(this._currentConfigService.getArrayFormulaCellData()),e.setRuntimeData(this._runtimeService.getUnitData()),e.setRuntimeArrayFormulaCellData(this._runtimeService.getRuntimeArrayFormulaCellData()),e.setRuntimeFeatureCellData(this._runtimeService.getRuntimeFeatureCellData())}}let st=class extends se{constructor(t,n,e,r){super(),this._functionService=t,this._currentConfigService=n,this._runtimeService=e,this._injector=r}get zIndex(){return re.get(v.FUNCTION)||ne}create(t){const n=this._functionService.getExecutor(t);return n?new $s(t,n,this._currentConfigService,this._runtimeService):(console.error(`No function ${t}`),H.create(f.NAME))}checkAndCreateNodeType(t){if(typeof t=="string")return;let e=t.getToken().trim().toUpperCase(),r,s;const i=e.slice(0,2);let a=0;if(new RegExp($.MINUS,"g").test(i)){const o=this._functionService.getExecutor(T.MINUS);r=new rt(this._injector,$.MINUS,o),a++}if(new RegExp($.AT,"g").test(i)&&(s=new rt(this._injector,$.AT),r&&s.setParent(r),a++),a>0&&(e=e.slice(a)),this._functionService.hasExecutor(e)){const o=this.create(e);return s?o.setParent(s):r&&o.setParent(r),o}}};st=js([Qe(0,ae),Qe(1,be),Qe(2,N),Qe(3,V.Inject(V.Injector))],st);var Qs=Object.defineProperty,Hs=Object.getOwnPropertyDescriptor,Ys=(t,n,e,r)=>{for(var s=r>1?void 0:r?Hs(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Qs(n,e,s),s},Xs=(t,n)=>(e,r)=>n(e,r,t);let Pe=class extends g.Disposable{constructor(t){super(),this._runtimeService=t}dispose(){}async executeAsync(t){if(!t)return d.create(f.VALUE);await this._executeAsync(t);const n=t.getValue();if(n==null)throw new Error("node value is null");return Promise.resolve(n)}execute(t){if(!t)return d.create(f.VALUE);this._execute(t);const n=t.getValue();if(n==null)throw new Error("node value is null");return n}executePreCalculateNode(t){return t.execute(),t.getValue()}checkAsyncNode(t){const n=[];this._checkAsyncNode(t,n);for(let e=0,r=n.length;e<r;e++)if(n[e]===!0)return!0;return!1}_checkAsyncNode(t,n){const e=t.getChildren(),r=e.length;for(let s=0;s<r;s++){const i=e[s];n.push(i.isAsync()),this._checkAsyncNode(i,n)}}async _executeAsync(t){if(this._runtimeService.isStopExecution())return Promise.resolve(pe.ERROR);const n=t.getChildren(),e=n.length;for(let r=0;r<e;r++){const s=n[r];if(s.getToken().toUpperCase()===Fe&&s.isEmptyParamFunction()){s.execute();continue}await this._executeAsync(s)}return t.nodeType===v.FUNCTION&&t.isAsync()?await t.executeAsync():t.execute(),Promise.resolve(pe.SUCCESS)}_execute(t){if(this._runtimeService.isStopExecution())return pe.ERROR;const n=t.getChildren(),e=n.length;for(let r=0;r<e;r++){const s=n[r];if(s.getToken().toUpperCase()===Fe&&s.isEmptyParamFunction()){s.execute();continue}this._execute(s)}return t.execute(),pe.SUCCESS}};Pe=Ys([Xs(0,N)],Pe);function an(t){return t instanceof x?t.getToken()===Se:!1}function Ws(t){return t instanceof x?t.getToken()===br:!1}function on(t){if(!t)return;if(t.getToken()!==je)return t;const n=t,e=n.getCurrentLambdaPrivacyVar(),r=n.getLambdaParameter();if(!e)return;const s=e.get(r);return s==null&&t.getValue()?t:on(s)}class Ts extends fe{constructor(e,r,s){super(0);p(this,"_lambdaPrivacyValueMap",new Map);this._lambdaNode=e,this._interpreter=r,this._lambdaPrivacyVarKeys=s,this._lambdaPrivacyValueMap.clear()}isLambda(){return!0}execute(...e){const r=this._lambdaPrivacyVarKeys.length;if(e.length!==r)return new d(f.VALUE);this._setLambdaPrivacyValueMap(e),this._setLambdaNodeValue(this._lambdaNode),this._lambdaNode.setNotEmpty(!1);let s;if(this._interpreter.checkAsyncNode(this._lambdaNode))s=new Tn(this._interpreter.executeAsync(this._lambdaNode));else{const i=this._interpreter.execute(this._lambdaNode);i.isReferenceObject()?s=i.toArrayValueObject():s=i}return this._lambdaNode.setNotEmpty(!0),s}_setLambdaNodeValue(e){const r=e.getChildren(),s=r.length;for(let i=0;i<s;i++){const a=r[i];if(a.getToken()===je){const u=a.getLambdaParameter(),c=this._lambdaPrivacyValueMap.get(u);if(c)a.setValue(c);else{const l=a.getCurrentLambdaPrivacyVar(),h=on(l.get(u));h!=null&&a.setValue(h.getValue())}continue}this._setLambdaNodeValue(a)}}_setLambdaPrivacyValueMap(e){for(let r=0;r<e.length;r++){const s=e[r],i=this._lambdaPrivacyVarKeys[r];this._lambdaPrivacyValueMap.set(i,s)}}}var Ks=Object.defineProperty,Gs=Object.getOwnPropertyDescriptor,Is=(t,n,e,r)=>{for(var s=r>1?void 0:r?Gs(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Ks(n,e,s),s},cr=(t,n)=>(e,r)=>n(e,r,t);class qs extends G{constructor(e,r,s,i){super(e);p(this,"_isNotEmpty",!0);this._lambdaId=r,this._interpreter=s,this._lambdaPrivacyVarKeys=i}get nodeType(){return v.LAMBDA}setNotEmpty(e=!1){this._isNotEmpty=e}isEmptyParamFunction(){return this.getChildren().length<2&&this._isNotEmpty}isFunctionParameter(){return this._lambdaId===null}getLambdaId(){return this._lambdaId}execute(){if(this.isEmptyParamFunction())this.setValue(new Ts(this,this._interpreter,this._lambdaPrivacyVarKeys));else{const e=this.getChildren(),r=e.length;this.setValue(e[r-1].getValue())}}}let it=class extends se{constructor(t,n){super(),this._runtimeService=t,this._interpreter=n}get zIndex(){return re.get(v.LAMBDA)||ne}create(t){const n=t.getChildren(),e=n[0];let r=n.slice(1,-1);const s=n[n.length-1];if(!(e instanceof x&&s instanceof x))return H.create(f.NAME);if(e.getToken()===Se){const o=e.getChildren();if(r.length!==o.length)return H.create(f.VALUE)}else r=n.slice(0,-1);const i=g.Tools.generateRandomId(8),a=new Map;for(let o=0;o<r.length;o++){const u=r[o];if(u instanceof x){const c=u.getChildren()[0];u.setToken(br),a.set(c.trim(),void 0)}else return H.create(f.VALUE)}return this._runtimeService.registerFunctionDefinitionPrivacyVar(i,a),this._updateLambdaStatement(s,i,a),new qs(t.getToken(),i,this._interpreter,[...a.keys()])}checkAndCreateNodeType(t){if(!(!(t instanceof x)||t.getToken().trim().toUpperCase()!==Fe))return this.create(t)}_updateLambdaStatement(t,n,e){this._updateTree(t,n,e)}_updateTree(t,n,e){const r=t.getChildren(),s=r.length,i=r[0];for(let a=0;a<s;a++){const o=r[a];if(!(an(i)&&a!==0))if(o instanceof x)this._updateTree(o,n,e);else{const u=o.trim();if(e.has(u)){const c=new x;c.setToken(je),c.setLambdaId(n),c.setLambdaPrivacyVar(e),c.setLambdaParameter(u),r[a]=c}}}}};it=Is([cr(0,N),cr(1,V.Inject(Pe))],it);function un(t){if(!t)return;if(t.getToken()!==je)return t;const n=t,e=n.getCurrentLambdaPrivacyVar(),r=n.getLambdaParameter();if(e)return un(e.get(r))}class zs extends G{constructor(n,e,r){super(n),this._lambdaParameter=e,this._currentLambdaPrivacyVar=r}getLambdaParameter(){return this._lambdaParameter}getCurrentLambdaPrivacyVar(){return this._currentLambdaPrivacyVar}get nodeType(){return v.LAMBDA_PARAMETER}execute(){const n=un(this._currentLambdaPrivacyVar.get(this._lambdaParameter));if(n)this.setValue(n.getValue());else{const e=this.getValue();(e==null||e.isError())&&this.setValue(d.create(f.SPILL))}}}class cn extends se{get zIndex(){return re.get(v.LAMBDA_PARAMETER)||ne}create(n){const e=n.getFunctionDefinitionPrivacyVar(),r=n.getLambdaParameter();return e?new zs(n.getToken(),r,e):new H(f.SPILL)}checkAndCreateNodeType(n){if(!(!(n instanceof x)||n.getToken().trim()!==je))return this.create(n)}}class Zs extends G{constructor(n){super(n),this._operatorString=n}get nodeType(){return v.NULL}execute(){this.setValue(new Me(0))}}var Js=Object.defineProperty,Ns=Object.getOwnPropertyDescriptor,ei=(t,n,e,r)=>{for(var s=r>1?void 0:r?Ns(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Js(n,e,s),s},ti=(t,n)=>(e,r)=>n(e,r,t);class ri extends G{constructor(n,e){super(n),this._operatorString=n,this._functionExecutor=e}get nodeType(){return v.OPERATOR}execute(){const n=this.getChildren();this._functionExecutor.name===T.COMPARE&&this._functionExecutor.setCompareType(this.getToken());let e=n[0].getValue(),r=n[1].getValue();if(e==null||r==null)throw new Error("object1 or object2 is null");e.isReferenceObject()&&(e=e.toArrayValueObject()),r.isReferenceObject()&&(r=r.toArrayValueObject()),this.setValue(this._functionExecutor.calculate(e,r))}}let at=class extends se{constructor(t){super(),this._functionService=t}get zIndex(){return re.get(v.OPERATOR)||ne}create(t){let n="";const e=t;e===K.PLUS?n=T.PLUS:e===K.MINUS?n=T.MINUS:e===K.MULTIPLY?n=T.MULTIPLY:e===K.DIVIDED?n=T.DIVIDED:e===K.CONCATENATE?n=pt.CONCATENATE:e===K.POWER?n=z.POWER:Rn.has(e)&&(n=T.COMPARE);const r=this._functionService.getExecutor(n);return r?new ri(e,r):(console.error(`No function ${t}`),H.create(f.NAME))}checkAndCreateNodeType(t){if(t instanceof x)return;const n=t.trim();if(!(n.charAt(0)==='"'&&n.charAt(n.length-1)==='"')&&Oe.has(n))return this.create(n)}};at=ei([ti(0,ae)],at);class ni extends g.Disposable{constructor(){super(...arguments);p(this,"_tableMap",new Map);p(this,"_tableOptionMap",new Map)}dispose(){this._tableMap.clear(),this._tableOptionMap.clear()}remove(e,r){var s;(s=this._tableMap.get(e))==null||s.delete(r)}getTableMap(e){return this._tableMap.get(e)}getTableOptionMap(){return this._tableOptionMap}registerTable(e,r,s){var i;this._tableMap.get(e)==null&&this._tableMap.set(e,new Map),(i=this._tableMap.get(e))==null||i.set(r,s)}registerTableOptionMap(e,r){this._tableOptionMap.set(e,r)}}const qt=V.createIdentifier("univer.formula.super-table.service");class si extends ve{constructor(n,e,r,s){super(n),this._tableData=e,this._columnDataString=r;const i=this._tableData.sheetId,a=this._tableData.range,o=this._tableData.titleMap;this.setForcedSheetIdDirect(i);const u=this._stringToColumnData(this._columnDataString,o,s),c=u.startColumn,l=u.endColumn,h=u.type;let m=-1,_=-1;const E=a.startRow,R=a.startColumn;h===Re.ALL?(m=E,_=R):h===Re.DATA?(m=E+1,_=R):h===Re.HEADERS?(m=E,_=E):h===Re.TOTALS&&(m=R,_=R),this.setRangeData({startColumn:c,endColumn:l,startRow:m,endRow:_})}isTable(){return!0}_stringToColumnData(n,e,r){n=n.substring(1,-1);const s=n.indexOf(O.COMMA);let i=-1,a=-1,o=Re.ALL;if(s===-1){const u=this._columnHandler(n,e);i=u.startColumn,a=u.endColumn}else{const u=n.substring(0,s).substring(1,-1),c=n.substring(s+1),l=this._columnHandler(c,e,!0);i=l.startColumn,a=l.endColumn,o=r.get(u),o||(o=Re.ALL)}return{startColumn:i,endColumn:a,type:o}}_columnHandler(n,e,r=!1){let s=-1,i=-1;const a=n.indexOf(O.COLON);if(new RegExp(yr,"g").test(n)){const o=n.substring(0,a).substring(1,-1),u=n.substring(a+1).substring(1,-1);s=e.get(o)??-1,i=e.get(u)??-1}else r&&(n=n.substring(1,-1)),s=e.get(n)??-1,i=s;return{startColumn:s,endColumn:i}}}var ii=Object.defineProperty,ai=Object.getOwnPropertyDescriptor,oi=(t,n,e,r)=>{for(var s=r>1?void 0:r?ai(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&ii(n,e,s),s},Ae=(t,n)=>(e,r)=>n(e,r,t);class He extends G{constructor(n,e,r){super(e),this._accessor=n,this._operatorString=e,this._referenceObject=r}get nodeType(){return v.REFERENCE}execute(){const n=this._accessor.get(be),e=this._accessor.get(N);this._referenceObject.setDefaultUnitId(e.currentUnitId),this._referenceObject.setDefaultSheetId(e.currentSubUnitId),this._referenceObject.setForcedSheetId(n.getSheetNameMap()),this._referenceObject.setUnitData(n.getUnitData()),this._referenceObject.setArrayFormulaCellData(n.getArrayFormulaCellData()),this._referenceObject.setRuntimeData(e.getUnitData()),this._referenceObject.setRuntimeArrayFormulaCellData(e.getRuntimeArrayFormulaCellData()),this._referenceObject.setRuntimeFeatureCellData(e.getRuntimeFeatureCellData());const{x:r,y:s}=this.getRefOffset();this._referenceObject.setRefOffset(r,s),this._referenceObject.isExceedRange()?this.setValue(new d(f.NAME)):this.setValue(this._referenceObject)}}let ot=class extends se{constructor(t,n,e,r,s){super(),this._definedNamesService=t,this._superTableService=n,this._formulaRuntimeService=e,this._lexer=r,this._injector=s}get zIndex(){return re.get(v.REFERENCE)||ne}checkAndCreateNodeType(t){let n=!1,e;if(t instanceof x?(n=!0,e=t.getToken().trim()):e=t.trim(),!n&&e.charAt(0)==='"'&&e.charAt(e.length-1)==='"')return;if(new RegExp(ht).test(e))return new He(this._injector,e,new It(e));if(n&&new RegExp(Cn).test(e))return new He(this._injector,e,new Ir(e));if(n&&new RegExp(yn).test(e))return new He(this._injector,e,new Gr(e));const r=this._formulaRuntimeService.currentUnitId,s=this._superTableService.getTableMap(r),i=new RegExp(yr,"g"),a=e.replace(i,"");if(!n&&(s!=null&&s.has(a))){const o=i.exec(e);let u="";o&&(u=o[0]);const c=s.get(a),l=this._superTableService.getTableOptionMap();return new He(this._injector,e,new si(e,c,u,l))}}};ot=oi([Ae(0,Dt),Ae(1,qt),Ae(2,N),Ae(3,V.Inject(Ee)),Ae(4,V.Inject(V.Injector))],ot);var ui=Object.defineProperty,ci=Object.getOwnPropertyDescriptor,li=(t,n,e,r)=>{for(var s=r>1?void 0:r?ci(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&ui(n,e,s),s},lr=(t,n)=>(e,r)=>n(e,r,t);class hr extends G{constructor(n,e,r){super(e),this._accessor=n,this._operatorString=e,this._functionExecutor=r}get nodeType(){return v.SUFFIX}execute(){let e=this.getChildren()[0].getValue(),r;if(e==null)throw new Error("object is null");this._operatorString===ie.PERCENTAGE?(e.isReferenceObject()&&(e=e.toArrayValueObject()),r=this._functionExecutor.calculate(e,new C(100))):this._operatorString===ie.POUND?r=this._handlerPound(e):r=d.create(f.VALUE),this.setValue(r)}_handlerPound(n){var l,h,m,_;if(!n.isReferenceObject()||!n.isCell())return d.create(f.VALUE);const e=this._accessor.get(be),r=this._accessor.get(Ee),s=n,i=s.getRangePosition(),a=s.getUnitId(),o=s.getSheetId(),u=e.getFormulaData(),c=(_=(m=(h=(l=u==null?void 0:u[a])==null?void 0:l[o])==null?void 0:h[i.startRow])==null?void 0:m[i.startColumn])==null?void 0:_.f;return c&&r.treeBuilder(c),d.create(f.VALUE)}}let ut=class extends se{constructor(t,n){super(),this._functionService=t,this._injector=n}get zIndex(){return re.get(v.SUFFIX)||ne}checkAndCreateNodeType(t){if(!(t instanceof x))return;const n=t.getToken().trim();if(n.charAt(0)==='"'&&n.charAt(n.length-1)==='"')return;let e="";if(n===ie.PERCENTAGE)e=T.DIVIDED;else return n===ie.POUND?new hr(this._injector,n):void 0;const r=this._functionService.getExecutor(e);return r?new hr(this._injector,n,r):(console.error(`No function ${t}`),H.create(f.NAME))}};ut=li([lr(0,ae),lr(1,V.Inject(V.Injector))],ut);var hi=Object.defineProperty,fi=Object.getOwnPropertyDescriptor,di=(t,n,e,r)=>{for(var s=r>1?void 0:r?fi(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&hi(n,e,s),s},mi=(t,n)=>(e,r)=>n(e,r,t);class gi extends G{constructor(n){super(n),this._operatorString=n}get nodeType(){return v.UNION}execute(){const n=this.getChildren(),e=n[0].getValue(),r=n[1].getValue();if(e==null||r==null)throw new Error("leftNode and rightNode");let s;this._operatorString===O.COLON?s=this._unionFunction(e,r):s=d.create(f.NAME),this.setValue(s)}_unionFunction(n,e){return n.isError()||e.isError()||!n.isReferenceObject()||!e.isReferenceObject()?d.create(f.REF):(n=n,e=e,n.isCell()&&e.isCell()||n.isRow()&&e.isRow()||n.isColumn()&&e.isColumn()?n.unionBy(e):d.create(f.REF))}}let ct=class extends se{constructor(t){super(),this._functionService=t}get zIndex(){return re.get(v.UNION)||ne}create(t){return new gi(t)}checkAndCreateNodeType(t){if(!(t instanceof x))return;const e=t.getToken().trim();if(!(e.charAt(0)==='"'&&e.charAt(e.length-1)==='"')&&e===O.COLON)return this.create(e)}};ct=di([mi(0,ae)],ct);class Ri extends G{constructor(n){super(n),this._operatorString=n}get nodeType(){return v.VALUE}execute(){this.setValue(he.create(this._operatorString))}}class ln extends se{get zIndex(){return re.get(v.VALUE)||ne}_checkValueNode(n){if(isNaN(Number(n))){const e=n.trim(),r=e.charAt(0),s=e.charAt(e.length-1);if(Ut.has(e))return this.create(e);if(r==='"'&&s==='"')return this.create(e);if(r==="{"&&s==="}")return this.create(e);if(e===De.TRUE||e===De.FALSE)return this.create(e)}else return this.create(n)}create(n){return new Ri(n)}checkAndCreateNodeType(n){if(!(n instanceof x))return this._checkValueNode(n)}}var pi=Object.defineProperty,Di=Object.getOwnPropertyDescriptor,_i=(t,n,e,r)=>{for(var s=r>1?void 0:r?Di(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&pi(n,e,s),s},q=(t,n)=>(e,r)=>n(e,r,t);let ke=class extends g.Disposable{constructor(n,e,r,s,i,a,o,u,c,l,h){super();p(this,"_astNodeFactoryList",[]);p(this,"_refOffsetX",0);p(this,"_refOffsetY",0);this._runtimeService=n,this._astRootNodeFactory=e,this._functionNodeFactory=r,this._lambdaNodeFactory=s,this._lambdaParameterNodeFactory=i,this._operatorNodeFactory=a,this._prefixNodeFactory=o,this._referenceNodeFactory=u,this._suffixNodeFactory=c,this._unionNodeFactory=l,this._valueNodeFactory=h,this._initializeAstNode()}dispose(){this._astNodeFactoryList.forEach(n=>{n.dispose()}),this._astNodeFactoryList=[]}parse(n,e=0,r=0){const s=new Bt(ce);return this._refOffsetX=e,this._refOffsetY=r,this._parse(n,s)}_lambdaParameterHandler(n,e){const r=e.getLambdaId(),s=new Bt(ce),i=this._runtimeService.getFunctionDefinitionPrivacyVar(r);if(!i)return!1;const a=[...i.keys()],o=n.getChildren(),u=o.length;for(let h=0;h<u;h++){const m=o[h];if(m instanceof x)this._parse(m,s);else return!1}const c=s.getChildren(),l=c.length;for(let h=0;h<l;h++){const m=c[h];i.set(a[h],m)}return s.setParent(e),e}_changeLetToLambda(n){const e=n.getChildren(),r=e.length;if(r%2!==1||r===0)return;const s=new x;s.setToken(Fe);const i=new x;i.setToken(Se);const a=[...e];for(let u=0;u<r;u++){const c=a[u];if(!(c instanceof x))return;u%2===0?c.changeToParent(s):c.changeToParent(i)}s.addChildrenFirst(i),i.setParent(s);const o=n.getParent();return o==null||o.replaceChild(n,s),s}_getTopParent(n){let e=n;for(;e!=null&&e.getParent();)e=e.getParent();return e}_parse(n,e){const r=n.getChildren(),s=r.length,i=[];let a=null;const o=n.getToken().trim().toUpperCase();if(o===Ln){const l=this._changeLetToLambda(n);return l!=null?this._parse(l,e):H.create(f.ERROR)}if(o===ge){if(a=e,s===0)return new Zs(ce).setParent(e),a}else{if(o===Se){let l=this._lambdaParameterHandler(n,e);return l===!1&&(l=H.create(f.ERROR)),l}if(a=this._checkAstNode(n),a==null)return H.create(f.ERROR)}const u=r[0];for(let l=0;l<s;l++){const h=r[l];if(an(u)){if(l!==0&&l!==s-1)continue}else if(Ws(h)&&l!==s-1)continue;let m=null;if(h instanceof x){if(m=this._parse(h,a),m===a)continue}else m=this._checkAstNode(h);if(m==null)return H.create(f.NAME);if(m=this._getTopParent(m),m==null)return;switch(m.nodeType){case v.ERROR:return m;case v.FUNCTION:i.push(m);break;case v.LAMBDA:i.push(m);break;case v.LAMBDA_PARAMETER:i.push(m);break;case v.OPERATOR:{const _=i.pop(),E=i.pop();if(E)E.setParent(m);else return H.create(f.ERROR);if(_)_.setParent(m);else return H.create(f.ERROR);i.push(m);break}case v.REFERENCE:m.setRefOffset(this._refOffsetX,this._refOffsetY),i.push(m);break;case v.ROOT:i.push(m);break;case v.UNION:i.push(m);break;case v.VALUE:i.push(m);break;case v.PREFIX:i.push(m);break;case v.SUFFIX:i.push(m);break}}const c=i.length;for(let l=0;l<c;l++)i[l].setParent(a);return a}_checkAstNode(n){let e=null;const r=this._astNodeFactoryList.length;for(let s=0;s<r&&(e=this._astNodeFactoryList[s].checkAndCreateNodeType(n),e==null);s++);return e}_initializeAstNode(){this._astNodeFactoryList=[this._astRootNodeFactory,this._functionNodeFactory,this._lambdaNodeFactory,this._lambdaParameterNodeFactory,this._operatorNodeFactory,this._prefixNodeFactory,this._referenceNodeFactory,this._suffixNodeFactory,this._unionNodeFactory,this._valueNodeFactory].sort(g.sortRules)}};ke=_i([q(0,N),q(1,V.Inject(nn)),q(2,V.Inject(st)),q(3,V.Inject(it)),q(4,V.Inject(cn)),q(5,V.Inject(at)),q(6,V.Inject(nt)),q(7,V.Inject(ot)),q(8,V.Inject(ut)),q(9,V.Inject(ct)),q(10,V.Inject(ln))],ke);class hn extends g.Disposable{constructor(){super(...arguments);p(this,"_referenceExecutorMap",new Map)}dispose(){this._referenceExecutorMap.clear()}remove(e){this._referenceExecutorMap.delete(e)}get(e){return this._referenceExecutorMap.get(e)}has(e){return this._referenceExecutorMap.has(e)}register(e,r){this._referenceExecutorMap.set(e,r)}getReferenceExecutorMap(){return this._referenceExecutorMap}}const _t=V.createIdentifier("univer.formula.feature-calculation-manager.service");class fn extends g.Disposable{constructor(){super(...arguments);p(this,"_otherFormulaData",{})}dispose(){this._otherFormulaData={}}remove(e){var a,o,u;const{unitId:r,subUnitId:s,formulaId:i}=e;(u=(o=(a=this._otherFormulaData)==null?void 0:a[r])==null?void 0:o[s])==null||delete u[i]}get(e){var a,o;const{unitId:r,subUnitId:s,formulaId:i}=e;return(o=(a=this._otherFormulaData[r])==null?void 0:a[s])==null?void 0:o[i]}has(e){var a,o;const{unitId:r,subUnitId:s,formulaId:i}=e;return((o=(a=this._otherFormulaData[r])==null?void 0:a[s])==null?void 0:o[i])!=null}register(e){const{unitId:r,subUnitId:s,formulaId:i,item:a}=e;this._otherFormulaData[r]&&(this._otherFormulaData[r]={}),this._otherFormulaData[r][s]&&(this._otherFormulaData[r][s]={}),this._otherFormulaData[r][s][i]=a}getOtherFormulaData(){return this._otherFormulaData}}const zt=V.createIdentifier("univer.formula.other-formula-manager.service");class wt extends g.Disposable{constructor(){super(...arguments);p(this,"node");p(this,"children",[]);p(this,"parents",[]);p(this,"formula","");p(this,"row",-1);p(this,"column",-1);p(this,"rowCount",-1/0);p(this,"columnCount",-1/0);p(this,"subUnitId","");p(this,"unitId","");p(this,"rangeList",[]);p(this,"formulaId");p(this,"featureId");p(this,"getDirtyData");p(this,"_state",0)}dispose(){var e;this.children.forEach(r=>{r.dispose()}),this.rangeList=[],this.parents=[],(e=this.node)==null||e.dispose()}setAdded(){this._state=1}isAdded(){return this._state===1}setSkip(){this._state=2}isSkip(){return this._state===2}inRangeData(e){const r=e.startRow,s=e.startColumn,i=e.endRow,a=e.endColumn;return!(this.row<r||this.row>i||this.column<s||this.column>a)}dependencyRange(e,r,s){var i,a;if(this.rangeList.length===0)return!1;for(let o=0,u=this.rangeList.length;o<u;o++){const c=this.rangeList[o],{unitId:l,sheetId:h,range:m}=c;if(!e.has(l))continue;const _=e.get(l);if(!_.has(h))continue;const E=_.get(h),R=(i=s==null?void 0:s[l])==null?void 0:i[h];let{startRow:D,endRow:b,startColumn:w,endColumn:S}=m;isNaN(D)&&(D=0),isNaN(w)&&(w=0),isNaN(b)&&(b=1/0),isNaN(S)&&(S=1/0);for(const L of E){const{startRow:k,startColumn:j,endRow:Q,endColumn:A}=L;if(!(D>Q||b<k||w>A||S<j)){let P=!0;if(R==null||R.forValue((B,M)=>{if(B>=D&&B<=b&&M>=w&&M<=S)return P=!1,!1}),P)return!0}}if(((a=r[l])==null?void 0:a[h])!=null)return!0}return!1}pushChildren(e){this.children.push(e),e._pushParent(this)}pushRangeList(e){this.rangeList.push(e)}dependency(e){if(this.rangeList.length===0)return!1;for(let r=0,s=this.rangeList.length;r<s;r++){const i=this.rangeList[r],a=i.unitId,o=i.sheetId,u=i.range;if(e.unitId===a&&e.subUnitId===o&&e.inRangeData(u))return!0}return!1}_pushParent(e){this.parents.push(e)}}var Ei=Object.defineProperty,Ci=Object.getOwnPropertyDescriptor,yi=(t,n,e,r)=>{for(var s=r>1?void 0:r?Ci(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Ei(n,e,s),s},de=(t,n)=>(e,r)=>n(e,r,t);const bi=1e5,Lt=new lt(bi);let Be=class extends g.Disposable{constructor(n,e,r,s,i,a,o){super();p(this,"_updateRangeFlattenCache",new Map);p(this,"_dirtyUnitSheetNameMap",{});this._currentConfigService=n,this._runtimeService=e,this._otherFormulaManagerService=r,this._featureCalculationManagerService=s,this._interpreter=i,this._astTreeBuilder=a,this._lexer=o}dispose(){this._updateRangeFlattenCache.clear(),Lt.clear(),this._dirtyUnitSheetNameMap={}}async generate(){this._updateRangeFlatten();const n=this._currentConfigService.getFormulaData(),e=this._otherFormulaManagerService.getOtherFormulaData(),r=this._currentConfigService.getUnitData(),s=await this._generateTreeList(n,e,r),i=this._getUpdateTreeListAndMakeDependency(s);this._checkIsCycleDependency(i)&&this._runtimeService.enableCycleDependency();const o=this._calculateRunList(i);return Promise.resolve(o)}_isCyclicUtil(n,e,r){if(!e.has(n)){e.add(n),r.add(n);for(let s=0;s<n.children.length;s++)if(!e.has(n.children[s])&&this._isCyclicUtil(n.children[s],e,r)||r.has(n.children[s]))return!0}return r.delete(n),!1}_checkIsCycleDependency(n){const e=new Set,r=new Set;for(let s=0,i=n.length;s<i;s++){const a=n[s];if(this._isCyclicUtil(a,e,r)===!0)return!0}return!1}async _generateTreeList(n,e,r){const s=Object.keys(n),i=Object.keys(e),a=[];for(const o of s){const u=n[o];if(u==null)continue;const c=Object.keys(u);for(const l of c)new g.ObjectMatrix(u[l]).forValue((m,_,E)=>{if(E==null)return!0;const{f:R,x:D,y:b}=E,w=this._generateAstNode(R,D,b),S=new wt,L=r[o][l];S.node=w,S.formula=R,S.unitId=o,S.subUnitId=l,S.row=m,S.column=_,S.rowCount=L.rowCount,S.columnCount=L.columnCount,a.push(S)})}for(const o of i){const u=e[o];if(u==null)continue;const c=Object.keys(u);for(const l of c){const h=u[l];if(h==null)continue;const m=Object.keys(h);for(const _ of m){const E=h[_],{f:R}=E,D=this._generateAstNode(R),b=new wt;b.node=D,b.formula=R,b.unitId=o,b.subUnitId=l,b.formulaId=_,a.push(b)}}}this._featureCalculationManagerService.getReferenceExecutorMap().forEach((o,u)=>{const{unitId:c,subUnitId:l,dependencyRanges:h,getDirtyData:m}=o,_=new wt;_.unitId=c,_.subUnitId=l,_.getDirtyData=m,_.featureId=u,_.rangeList=h,a.push(_)});for(let o=0,u=a.length;o<u;o++){const c=a[o];if(this._runtimeService.setCurrent(c.row,c.column,c.rowCount,c.columnCount,c.subUnitId,c.unitId),c.node==null)continue;const l=await this._getRangeListByNode(c.node);for(let h=0,m=l.length;h<m;h++)c.pushRangeList(l[h])}return a}_updateRangeFlatten(){const n=this._currentConfigService.isForceCalculate(),e=this._currentConfigService.getDirtyRanges();if(!n){this._updateRangeFlattenCache.clear();for(let r=0;r<e.length;r++){const s=e[r],i=s.range,a=s.sheetId,o=s.unitId;this._addFlattenCache(o,a,i)}this._dirtyUnitSheetNameMap=this._currentConfigService.getDirtyNameMap()}}_generateAstNode(n,e=0,r=0){let s=Lt.get(`${n}##${e}${r}`);if(s)return s;const i=this._lexer.treeBuilder(n);if(i in f)return H.create(i);if(s=this._astTreeBuilder.parse(i,e,r),s==null)throw new Error("astNode is null");return Lt.set(`${n}##${e}${r}`,s),s}_addFlattenCache(n,e,r){let s=this._updateRangeFlattenCache.get(n);s==null&&(s=new Map,this._updateRangeFlattenCache.set(n,s));let i=s.get(e);i==null&&(i=[],s.set(e,i)),i.push(r)}_isPreCalculateNode(n){return n.nodeType===v.UNION||n.nodeType===v.PREFIX&&n.getToken()===$.AT||n.nodeType===v.SUFFIX&&n.getToken()===ie.POUND}_nodeTraversalRef(n,e){const r=n.getChildren(),s=r.length;for(let i=0;i<s;i++){const a=r[i];if(this._isPreCalculateNode(a)){e.push(a);continue}else a.nodeType===v.REFERENCE&&e.push(a);this._nodeTraversalRef(a,e)}}_nodeTraversalReferenceFunction(n,e){const r=n.getChildren(),s=r.length;for(let i=0;i<s;i++){const a=r[i];if(a.nodeType===v.FUNCTION&&a.isAddress()){e.push(a);continue}this._nodeTraversalReferenceFunction(a,e)}}async _executeNode(n){let e;return this._interpreter.checkAsyncNode(n)?e=await this._interpreter.executeAsync(n):e=this._interpreter.execute(n),e}async _getRangeListByNode(n){const e=[],r=[];this._nodeTraversalRef(n,e),this._nodeTraversalReferenceFunction(n,r);const s=[];for(let i=0,a=e.length;i<a;i++){const o=e[i],c=(await this._executeNode(o)).toUnitRange();s.push(c)}for(let i=0,a=r.length;i<a;i++){const o=r[i],c=(await this._executeNode(o)).toUnitRange();s.push(c)}return s}_getUpdateTreeListAndMakeDependency(n){const e=[],r=new Set,s=this._currentConfigService.isForceCalculate();for(let i=0,a=n.length;i<a;i++){const o=n[i];for(let u=0,c=n.length;u<c;u++){const l=n[u];o!==l&&o.dependency(l)&&o.pushChildren(l)}(s||o.dependencyRange(this._updateRangeFlattenCache,this._dirtyUnitSheetNameMap,this._currentConfigService.getExcludedRange())||this._includeTree(o))&&!r.has(o)&&(e.push(o),r.add(o))}return e}_includeTree(n){var c,l,h,m,_;const e=n.unitId,r=n.subUnitId,s=n.featureId;if(s!=null){const E=this._currentConfigService.getDirtyUnitFeatureMap();if(((l=(c=E==null?void 0:E[e])==null?void 0:c[r])==null?void 0:l[s])!=null)return!0}const i=(m=(h=this._currentConfigService.getExcludedRange())==null?void 0:h[e])==null?void 0:m[r];let a=!1;if(i==null||i.forValue((E,R)=>{if(n.row===E&&n.column===R)return a=!0,!1}),a)return!1;if(((_=this._dirtyUnitSheetNameMap[e])==null?void 0:_[r])!=null)return!0;if(!this._updateRangeFlattenCache.has(e))return!1;const o=this._updateRangeFlattenCache.get(e);if(!o.has(r))return!1;const u=o.get(r);for(const E of u)if(n.inRangeData(E))return!0;return!1}_calculateRunList(n){let e=n;const r=[];for(;e.length>0;){const s=e.pop();if(s===void 0||s.isSkip())continue;if(s.isAdded()){r.push(s);continue}const i=[];for(let a=0,o=s.parents.length;a<o;a++){const u=s.parents[a];i.push(u)}i.length===0?(r.push(s),s.setSkip()):(s.setAdded(),e.push(s),e=e.concat(i))}return r.reverse()}};Be=yi([g.OnLifecycle(g.LifecycleStages.Rendered,Be),de(0,be),de(1,N),de(2,zt),de(3,_t),de(4,V.Inject(Pe)),de(5,V.Inject(ke)),de(6,V.Inject(Ee))],Be);var wi=Object.defineProperty,Li=Object.getOwnPropertyDescriptor,Si=(t,n,e,r)=>{for(var s=r>1?void 0:r?Li(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&wi(n,e,s),s},me=(t,n)=>(e,r)=>n(e,r,t);const Pi=1;exports.CalculateFormulaService=class extends g.Disposable{constructor(e,r,s,i,a,o,u){super();p(this,"_executionStartListener$",new Et.Subject);p(this,"executionStartListener$",this._executionStartListener$.asObservable());p(this,"_executionCompleteListener$",new Et.Subject);p(this,"executionCompleteListener$",this._executionCompleteListener$.asObservable());p(this,"_executionInProgressListener$",new Et.Subject);p(this,"executionInProgressListener$",this._executionInProgressListener$.asObservable());this._configService=e,this._lexer=r,this._currentConfigService=s,this._runtimeService=i,this._formulaDependencyGenerator=a,this._interpreter=o,this._astTreeBuilder=u}dispose(){}stopFormulaExecution(){this._runtimeService.stopExecution()}setRuntimeFeatureCellData(e,r){this._runtimeService.setRuntimeFeatureCellData(e,r)}setRuntimeFeatureRange(e,r){this._runtimeService.setRuntimeFeatureRange(e,r)}async execute(e){this._executionStartListener$.next(!0),this._currentConfigService.load(e),this._runtimeService.reset();const r=this._configService.getConfig("CYCLE_REFERENCE_COUNT")||Pi;for(let s=0;s<r&&(await this._execute(),!!this._runtimeService.isCycleDependency());s++);this._runtimeService.setFormulaExecuteStage(ee.CALCULATION_COMPLETED),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()),this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData()),vt.clear(),oe.clear()}async _execute(){const e=await this._apply();if(e==null)return;const{arrayFormulaRange:r,runtimeFeatureRange:s}=e,{dirtyRanges:i,excludedCell:a}=this._getArrayFormulaDirtyRangeAndExcludedRange(r,s);return i==null||i.length===0||(this._currentConfigService.loadDirtyRangesAndExcludedCell(i,a),await this._apply(!0)),!0}_getArrayFormulaDirtyRangeAndExcludedRange(e,r){const s=[],i={};return Object.keys(e).forEach(a=>{const o=e[a];if(o==null)return!0;Object.keys(o).forEach(u=>{const c=new g.ObjectMatrix(o[u]);if(c==null)return!0;const l=new g.ObjectMatrix;c.forValue((h,m,_)=>{l.setValue(h,m,!0),s.push({unitId:a,sheetId:u,range:_})}),i[a]==null&&(i[a]={}),i[a][u]=l})}),Object.keys(r).forEach(a=>{const o=r[a];Object.keys(o).forEach(u=>{const c=o[u];if(c==null)return!0;Object.keys(c).forEach(l=>{const h=c[l];if(h==null)return!0;for(const m of h)s.push({unitId:u,sheetId:l,range:m})})})}),{dirtyRanges:s,excludedCell:i}}async _apply(e=!1){e?this._runtimeService.setFormulaExecuteStage(ee.START_DEPENDENCY_ARRAY_FORMULA):this._runtimeService.setFormulaExecuteStage(ee.START_DEPENDENCY),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());const r=await this._formulaDependencyGenerator.generate(),s=this._interpreter;e?(this._runtimeService.setFormulaExecuteStage(ee.START_CALCULATION_ARRAY_FORMULA),this._runtimeService.setTotalArrayFormulasToCalculate(r.length)):(this._runtimeService.setFormulaExecuteStage(ee.START_CALCULATION),this._runtimeService.setTotalFormulasToCalculate(r.length)),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());for(let i=0,a=r.length;i<a;i++){if(await new Promise(h=>{g.requestImmediateMacroTask(h)}),this._runtimeService.isStopExecution()){this._runtimeService.setFormulaExecuteStage(ee.IDLE),this._runtimeService.markedAsStopFunctionsExecuted(),this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData());return}const o=r[i],u=o.node,c=o.getDirtyData;let l;if(u==null&&c==null)throw new Error("AstNode or executor is null");if(this._runtimeService.setCurrent(o.row,o.column,o.rowCount,o.columnCount,o.subUnitId,o.unitId),c!=null&&o.featureId!=null){const{runtimeCellData:h,dirtyRanges:m}=c(o);this._runtimeService.setRuntimeFeatureCellData(o.featureId,h),this._runtimeService.setRuntimeFeatureRange(o.featureId,m)}else u!=null&&(s.checkAsyncNode(u)?l=await s.executeAsync(u):l=s.execute(u),o.formulaId!=null?this._runtimeService.setRuntimeOtherData(o.formulaId,l):this._runtimeService.setRuntimeData(l));e?(this._runtimeService.setFormulaExecuteStage(ee.CURRENTLY_CALCULATING_ARRAY_FORMULA),this._runtimeService.setCompletedArrayFormulasCount(i+1)):(this._runtimeService.setFormulaExecuteStage(ee.CURRENTLY_CALCULATING),this._runtimeService.setCompletedFormulasCount(i+1)),this._executionInProgressListener$.next(this._runtimeService.getRuntimeState())}return r.length>0?this._runtimeService.markedAsSuccessfullyExecuted():e||this._runtimeService.markedAsNoFunctionsExecuted(),this._runtimeService.getAllRuntimeData()}calculate(e,r=!0){const s=this._lexer.treeBuilder(e,r);if(Object.values(f).includes(s))return H.create(s);const i=this._astTreeBuilder.parse(s);i==null||i.serialize()}};exports.CalculateFormulaService=Si([g.OnLifecycle(g.LifecycleStages.Rendered,exports.CalculateFormulaService),me(0,g.IConfigService),me(1,V.Inject(Ee)),me(2,be),me(3,N),me(4,V.Inject(Be)),me(5,V.Inject(Pe)),me(6,V.Inject(ke))],exports.CalculateFormulaService);var Vi=Object.defineProperty,xi=Object.getOwnPropertyDescriptor,vi=(t,n,e,r)=>{for(var s=r>1?void 0:r?xi(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Vi(n,e,s),s},Ye=(t,n)=>(e,r)=>n(e,r,t);let Ke=class extends g.Disposable{constructor(t,n,e,r){super(),this._commandService=t,this._calculateFormulaService=n,this._currentUniverService=e,this._formulaDataModel=r,this._initialize()}_initialize(){this._commandExecutedListener(),this._initialExecuteFormulaListener(),this._initialExecuteFormulaProcessListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((t,n)=>{if(t.id===Qt.id)this._calculateFormulaService.stopFormulaExecution();else if(t.id===Yt.id){const e=t.params.formulaData;this._formulaDataModel.setFormulaData(e)}else if(t.id===$t.id){const e=t.params;if(e.forceCalculation===!0)this._calculate(!0);else{const{dirtyRanges:r,dirtyNameMap:s,dirtyUnitFeatureMap:i}=e;this._calculate(!1,r,s,i)}}else if(t.id===Je.id){const e=t.params;if(e==null)return;const{arrayFormulaRange:r,arrayFormulaCellData:s}=e;this._formulaDataModel.setArrayFormulaRange(r),this._formulaDataModel.setArrayFormulaCellData(s)}}))}async _calculate(t=!1,n=[],e={},r={}){if(n.length===0&&Object.keys(e).length===0&&Object.keys(r).length===0&&t===!1)return;const s=this._formulaDataModel.getFormulaData(),i=this._formulaDataModel.getArrayFormulaCellData();this._calculateFormulaService.execute({formulaData:s,arrayFormulaCellData:i,forceCalculate:t,dirtyRanges:n,dirtyNameMap:e,dirtyUnitFeatureMap:r})}_initialExecuteFormulaListener(){this._calculateFormulaService.executionCompleteListener$.subscribe(t=>{const n=t.functionsExecutedState;switch(n){case Le.NOT_EXECUTED:break;case Le.STOP_EXECUTION:break;case Le.SUCCESS:this._applyFormula(t);break;case Le.INITIAL:break}this._commandService.executeCommand(Ne.id,{functionsExecutedState:n},{onlyLocal:!0})})}_initialExecuteFormulaProcessListener(){this._calculateFormulaService.executionInProgressListener$.subscribe(t=>{this._commandService.executeCommand(Ne.id,{stageInfo:t},{onlyLocal:!0})})}async _applyFormula(t){const{unitData:n,unitOtherData:e,arrayFormulaRange:r,arrayFormulaCellData:s,clearArrayFormulaCellData:i}=t;if(!n){console.error("No sheetData from Formula Engine!");return}r&&(this._formulaDataModel.clearPreviousArrayFormulaCellData(i),this._formulaDataModel.mergeArrayFormulaCellData(s),this._formulaDataModel.mergeArrayFormulaRange(r),this._commandService.executeCommand(Je.id,{arrayFormulaRange:this._formulaDataModel.getArrayFormulaRange(),arrayFormulaCellData:this._formulaDataModel.getArrayFormulaCellData()},{onlyLocal:!0})),this._commandService.executeCommand(Ht.id,{unitData:n,unitOtherData:e},{onlyLocal:!0})}};Ke=vi([g.OnLifecycle(g.LifecycleStages.Ready,Ke),Ye(0,g.ICommandService),Ye(1,V.Inject(exports.CalculateFormulaService)),Ye(2,g.IUniverInstanceService),Ye(3,V.Inject(exports.FormulaDataModel))],Ke);var Ai=Object.defineProperty,Oi=Object.getOwnPropertyDescriptor,Bi=(t,n,e,r)=>{for(var s=r>1?void 0:r?Oi(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Ai(n,e,s),s},St=(t,n)=>(e,r)=>n(e,r,t);let Ue=class extends g.Disposable{constructor(t=[],n,e,r){super(),this._function=t,this._commandService=n,this._injector=e,this._functionService=r,this._initialize()}_initialize(){this._registerCommands(),this._registerFunctions()}_registerCommands(){[Yt,Je,$t,Qt,Ne,Ht,dt,mt,kt,jt,Xt,Wt,Pr,Vr,Tt,Ft,Kt].forEach(t=>this.disposeWithMe(this._commandService.registerCommand(t)))}_registerFunctions(){const t=[...Ar,...Or,...Ur,...Mr,...jr,...Qr,...Yr,...Wr,...Kr,...qr,...zr,...Zr,...Jr,...Nr,...en,...tn].concat(this._function).map(n=>{const e=n[0],r=n[1];return new e(r)});this._functionService.registerExecutors(...t)}};Ue=Bi([g.OnLifecycle(g.LifecycleStages.Ready,Ue),St(1,g.ICommandService),St(2,V.Inject(V.Injector)),St(3,ae)],Ue);var Ui=Object.defineProperty,Fi=Object.getOwnPropertyDescriptor,Mi=(t,n,e,r)=>{for(var s=r>1?void 0:r?Fi(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Ui(n,e,s),s},Pt=(t,n)=>(e,r)=>n(e,r,t);let Ge=class extends g.Disposable{constructor(t,n,e){super(),this._commandService=t,this._formulaDataModel=n,this._functionService=e,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((t,n)=>{if(t.id===Ft.id){const e=t.params;if(e==null)return;const{functions:r}=e,s=r.map(i=>{const a=i[0],o=i[1];return ji(a,o)});this._functionService.registerExecutors(...s)}else if(t.id===Kt.id){const e=t.params;if(e==null)return;const{functions:r}=e;this._functionService.unregisterExecutors(...r)}}))}};Ge=Mi([g.OnLifecycle(g.LifecycleStages.Ready,Ge),Pt(0,g.ICommandService),Pt(1,V.Inject(exports.FormulaDataModel)),Pt(2,ae)],Ge);class ki extends F{isCustom(){return!0}}function ji(t,n){const e=new ki(n),r=new Function(`return ${t}`)();return e.calculateCustom=r,e}var $i=Object.defineProperty,Qi=Object.getOwnPropertyDescriptor,Hi=(t,n,e,r)=>{for(var s=r>1?void 0:r?Qi(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&$i(n,e,s),s},fr=(t,n)=>(e,r)=>n(e,r,t);let Ie=class extends g.Disposable{constructor(t,n){super(),this._commandService=t,this._definedNamesService=n,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(t.id===dt.id){const n=t.params;if(n==null)return;const{unitId:e,name:r,formulaOrRefString:s}=n;this._definedNamesService.registerDefinedName(e,r,s)}else if(t.id===mt.id){const n=t.params;if(n==null)return;const{unitId:e,name:r}=n;this._definedNamesService.removeDefinedName(e,r)}}))}};Ie=Hi([g.OnLifecycle(g.LifecycleStages.Ready,Ie),fr(0,g.ICommandService),fr(1,Dt)],Ie);var Yi=Object.defineProperty,Xi=Object.getOwnPropertyDescriptor,Wi=(t,n,e,r)=>{for(var s=r>1?void 0:r?Xi(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Yi(n,e,s),s},dr=(t,n)=>(e,r)=>n(e,r,t);let qe=class extends g.Disposable{constructor(t,n){super(),this._commandService=t,this._featureCalculationManagerService=n,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(t.id===kt.id){const n=t.params;if(n==null)return;const{featureId:e,calculationParam:r}=n;this._featureCalculationManagerService.register(e,r)}else if(t.id===jt.id){const n=t.params;if(n==null)return;const{featureId:e}=n;this._featureCalculationManagerService.remove(e)}}))}};qe=Wi([g.OnLifecycle(g.LifecycleStages.Ready,qe),dr(0,g.ICommandService),dr(1,_t)],qe);var Ti=Object.defineProperty,Ki=Object.getOwnPropertyDescriptor,Gi=(t,n,e,r)=>{for(var s=r>1?void 0:r?Ki(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Ti(n,e,s),s},mr=(t,n)=>(e,r)=>n(e,r,t);let ze=class extends g.Disposable{constructor(t,n){super(),this._commandService=t,this._otherFormulaManagerService=n,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(t.id===Xt.id){const n=t.params;if(n==null)return;this._otherFormulaManagerService.register(n)}else if(t.id===Wt.id){const n=t.params;if(n==null)return;this._otherFormulaManagerService.remove(n)}}))}};ze=Gi([g.OnLifecycle(g.LifecycleStages.Ready,ze),mr(0,g.ICommandService),mr(1,zt)],ze);var Ii=Object.defineProperty,qi=Object.getOwnPropertyDescriptor,zi=(t,n,e,r)=>{for(var s=r>1?void 0:r?qi(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Ii(n,e,s),s},gr=(t,n)=>(e,r)=>n(e,r,t);let Ze=class extends g.Disposable{constructor(t,n){super(),this._commandService=t,this._superTableService=n,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(t.id===dt.id){const n=t.params;if(n==null)return;const{unitId:e,tableName:r,reference:s}=n;this._superTableService.registerTable(e,r,s)}else if(t.id===mt.id){const n=t.params;if(n==null)return;const{unitId:e,tableName:r}=n;this._superTableService.remove(e,r)}else if(t.id===Tt.id){const n=t.params;if(n==null)return;const{tableOption:e,tableOptionType:r}=n;this._superTableService.registerTableOptionMap(e,r)}}))}};Ze=zi([g.OnLifecycle(g.LifecycleStages.Ready,Ze),gr(0,g.ICommandService),gr(1,qt)],Ze);var Zi=Object.defineProperty,Ji=Object.getOwnPropertyDescriptor,Ni=(t,n,e,r)=>{for(var s=r>1?void 0:r?Ji(n,e):n,i=t.length-1,a;i>=0;i--)(a=t[i])&&(s=(r?a(n,e,s):a(s))||s);return r&&s&&Zi(n,e,s),s},ea=(t,n)=>(e,r)=>n(e,r,t);const ta="base-formula-engine";exports.UniverFormulaEnginePlugin=class extends g.Plugin{constructor(n,e){super(ta),this._config=n,this._injector=e}onStarting(){this._initialize()}_initialize(){var e;const n=[[ae,{useClass:sn}],[_t,{useClass:hn}],[Dt,{useClass:Cs}],[exports.FormulaDataModel],[ft],[Ue,{useFactory:()=>{var r;return this._injector.createInstance(Ue,(r=this._config)==null?void 0:r.function)}}],[qe]];(e=this._config)!=null&&e.notExecuteFormula||n.push([exports.CalculateFormulaService],[zt,{useClass:fn}],[qt,{useClass:ni}],[be,{useClass:At}],[N,{useClass:Ot}],[Ke],[Ie],[ze],[Ze],[Ge],[Be],[Pe],[ke],[Ee],[nn],[st],[it],[cn],[at],[nt],[ot],[ut],[ct],[ln]),n.forEach(r=>this._injector.add(r))}onReady(){this._injector.get(exports.FormulaDataModel).initFormulaData()}};exports.UniverFormulaEnginePlugin=Ni([ea(1,V.Inject(V.Injector))],exports.UniverFormulaEnginePlugin);exports.ArrayValueObject=J;exports.BaseFunction=F;exports.BaseReferenceObject=ve;exports.BaseValueObject=fe;exports.BooleanValueObject=W;exports.ErrorType=f;exports.ErrorValueObject=d;exports.FUNCTION_NAMES_ARRAY=Gn;exports.FUNCTION_NAMES_COMPATIBILITY=Br;exports.FUNCTION_NAMES_CUBE=Fr;exports.FUNCTION_NAMES_DATABASE=kr;exports.FUNCTION_NAMES_DATE=$r;exports.FUNCTION_NAMES_ENGINEERING=Hr;exports.FUNCTION_NAMES_FINANCIAL=Xr;exports.FUNCTION_NAMES_INFORMATION=Tr;exports.FUNCTION_NAMES_LOGICAL=tt;exports.FUNCTION_NAMES_LOOKUP=we;exports.FUNCTION_NAMES_MATH=z;exports.FUNCTION_NAMES_STATISTICAL=ue;exports.FUNCTION_NAMES_TEXT=pt;exports.FUNCTION_NAMES_UNIVER=Es;exports.FUNCTION_NAMES_WEB=rn;exports.FeatureCalculationManagerService=hn;exports.FormulaExecuteStageType=ee;exports.FormulaExecutedStateType=Le;exports.FunctionService=sn;exports.FunctionType=pr;exports.IFeatureCalculationManagerService=_t;exports.IFunctionService=ae;exports.LexerNode=x;exports.LexerTreeBuilder=ft;exports.NumberValueObject=C;exports.OtherFormulaManagerService=fn;exports.RangeReferenceObject=et;exports.RegisterFunctionMutation=Ft;exports.RemoveDefinedNameMutation=mt;exports.RemoveFeatureCalculationMutation=jt;exports.RemoveOtherFormulaMutation=Wt;exports.RemoveSuperTableMutation=Vr;exports.SetArrayFormulaDataMutation=Je;exports.SetArrayFormulaDataUndoMutationFactory=xn;exports.SetDefinedNameMutation=dt;exports.SetFeatureCalculationMutation=kt;exports.SetFormulaCalculationNotificationMutation=Ne;exports.SetFormulaCalculationResultMutation=Ht;exports.SetFormulaCalculationStartMutation=$t;exports.SetFormulaCalculationStopMutation=Qt;exports.SetFormulaDataMutation=Yt;exports.SetOtherFormulaMutation=Xt;exports.SetSuperTableMutation=Pr;exports.SetSuperTableOptionMutation=Tt;exports.StringValueObject=X;exports.UnregisterFunctionMutation=Kt;exports.ValueObjectFactory=he;exports.compareToken=y;exports.convertUnitDataToRuntime=_r;exports.functionArray=Ar;exports.functionCompatibility=Or;exports.functionCube=Ur;exports.functionDatabase=Mr;exports.functionDate=jr;exports.functionEngineering=Qr;exports.functionFinancial=Yr;exports.functionInformation=Wr;exports.functionLogical=Kr;exports.functionLookup=qr;exports.functionMath=zr;exports.functionMeta=Zr;exports.functionStatistical=Jr;exports.functionText=Nr;exports.functionUniver=en;exports.functionWeb=tn;exports.generateStringWithSequence=wr;exports.includeFormulaLexerToken=Dn;exports.initSheetFormulaData=Sr;exports.isFormulaLexerToken=We;exports.isInDirtyRange=Rr;exports.matchToken=O;exports.normalizeSheetName=_n;exports.sequenceNodeType=I;
|