@8sheets/data-grid 1.0.0 → 1.0.1

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.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/api/serialize.js +1 -1
  3. package/calc/engine.js +1 -1
  4. package/calc/functions/array.js +1 -1
  5. package/calc/functions/lookup.js +1 -1
  6. package/calc/parser.js +3 -3
  7. package/cells/axis-ops.js +1 -1
  8. package/cells/goto.js +1 -1
  9. package/cells/options.js +1 -1
  10. package/cells/view-options.js +1 -1
  11. package/charts/chartex.js +3 -3
  12. package/core/default-names.js +1 -1
  13. package/core/formula-refs.js +1 -1
  14. package/core/input.js +1 -1
  15. package/core/numfmt.js +1 -1
  16. package/core/sheet-group.js +1 -0
  17. package/core/tables.js +2 -2
  18. package/core/whatif.js +1 -1
  19. package/core/workbook.js +1 -1
  20. package/extras/getdata/persist.js +2 -2
  21. package/extras/getdata/steps.js +1 -1
  22. package/i18n/en/cells.js +1 -1
  23. package/i18n/en/charts.js +1 -1
  24. package/i18n/en/misc.js +1 -1
  25. package/i18n/en/pivot.js +1 -1
  26. package/i18n/en/ribbon.js +1 -1
  27. package/i18n/en/shell.js +1 -1
  28. package/i18n/pl/cells.js +1 -1
  29. package/i18n/pl/charts.js +1 -1
  30. package/i18n/pl/misc.js +1 -1
  31. package/i18n/pl/pivot.js +1 -1
  32. package/i18n/pl/ribbon.js +1 -1
  33. package/i18n/pl/shell.js +1 -1
  34. package/io/client.js +1 -1
  35. package/io/csv.js +8 -5
  36. package/io/export-blocks.js +1 -1
  37. package/io/plan.js +1 -1
  38. package/io/text-split.js +3 -0
  39. package/io/xlsx-read.js +1 -1
  40. package/io/xlsx-tail.js +1 -1
  41. package/io/xlsx-write.js +2 -2
  42. package/objects/chart-model.js +1 -1
  43. package/package.json +1 -1
  44. package/pivot/engine.js +1 -1
  45. package/pivot/xml.js +2 -2
  46. package/print/page-setup.js +1 -1
  47. package/slicers/custom-styles.js +1 -1
  48. package/slicers/table-file.js +1 -1
  49. package/table-view/files.js +1 -1
  50. package/table-view/labels.js +1 -1
  51. package/table-view/version.js +1 -1
  52. package/ui/protection-ui.js +1 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  A data grid for the web in plain JavaScript modules with no runtime dependencies. Open a CSV or Excel file, or pass your records, and search, filter, sort, group, total, pivot and export them as CSV, Excel or PDF. Files are read in a Worker as a stream, the page keeps a bounded DOM, and a million records stay responsive. Server data plugs in through a query contract, so search, filters and totals cover the whole result.
4
4
 
5
- This is version 1.0.0. Components for [React](https://www.npmjs.com/package/@8sheets/data-grid-react), [Vue](https://www.npmjs.com/package/@8sheets/data-grid-vue) and [Angular](https://www.npmjs.com/package/@8sheets/data-grid-angular) build on it. For a full Excel-compatible workbook, see the Spreadsheet, [`@8sheets/core`](https://www.npmjs.com/package/@8sheets/core).
5
+ This is version 1.0.1. Components for [React](https://www.npmjs.com/package/@8sheets/data-grid-react), [Vue](https://www.npmjs.com/package/@8sheets/data-grid-vue) and [Angular](https://www.npmjs.com/package/@8sheets/data-grid-angular) build on it. For a full Excel-compatible workbook, see the Spreadsheet, [`@8sheets/core`](https://www.npmjs.com/package/@8sheets/core).
6
6
 
7
7
  ## Install
8
8
 
package/api/serialize.js CHANGED
@@ -1 +1 @@
1
- import{BOOL as E,CHUNK_BITS as X,CHUNK_MASK as Y,CHUNK_SIZE as J,ERR as M,ERRORS as j,FORMULA as G,KIND_MASK as L,NUM as I,SPILL as Z,STR as N,Sheet as U}from"../core/sheet.js";import{MAX_COLS as v}from"../core/address.js";import{defaultStyle as b}from"../core/styles.js";import{Workbook as k}from"../core/workbook.js";import{Engine as ee}from"../calc/engine.js";const T="8sheets",_=1,te=new Set(["uid","name","columns","maxRow","maxCol","rows","cols","formulas","spills","rowStyles","colStyles","merges","mergeIndex","frozenRows","frozenCols","showGridlines","zoom","sourceId","sourceIndex","revision","hidden","tabColor","rtl"]),ne=new Set(["apiObjects","cfEval","structureOps","dataBindings","report","isVirtual","split","onRefresh","onRejected","recorder"]),B={cf:"cfChanged",comments:"commentsChanged",hyperlinks:"hyperlinksChanged",validations:"validationsChanged",pageSetup:"pageSetupChanged",protection:"protectionChanged",scenarios:"scenariosChanged",sparklines:"sparklinesChanged",threads:"threadsChanged",autoFilter:"filterChanged",cellTypes:"cellTypesChanged"},D=new Map;function ze(e,t){D.set(e,t)}const se=new U(""),re=e=>{if(e===null||typeof e!="object")return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null};function d(e,t,n){if(e===null||typeof e=="number"||typeof e=="string"||typeof e=="boolean")return e;if(e===void 0)return;if(typeof e=="function"){t?.push(`${n}: a function was left out`);return}if(Array.isArray(e))return e.map((i,s)=>d(i,t,`${n}[${s}]`)??null);if(e instanceof Map)return{$map:[...e].map(([i,s],o)=>[d(i,t,n),d(s,t,`${n}.${o}`)??null])};if(e instanceof Set)return{$set:[...e].map(i=>d(i,t,n))};if(ArrayBuffer.isView(e))return{$typed:e.constructor.name,v:[...e]};if(e instanceof Date)return{$date:e.toISOString()};if(!re(e)){if(typeof e.toJSON=="function")return d(e.toJSON(),t,n);t?.push(`${n}: a ${e.constructor?.name??"class"} instance was left out`);return}if("$map"in e||"$set"in e)throw new Error(`${n}: a key starting with $ can't be stored`);const r={};for(const i of Object.keys(e)){if(i[0]==="_")continue;const s=d(e[i],t,`${n}.${i}`);s!==void 0&&(r[i]=s)}return r}const ie={Uint8Array,Int8Array,Uint16Array,Int16Array,Uint32Array,Int32Array,Float32Array,Float64Array};function h(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(h);if(e.$map)return new Map(e.$map.map(([n,r])=>[h(n),h(r)]));if(e.$set)return new Set(e.$set.map(h));if(e.$typed)return ie[e.$typed].from(e.v);if(e.$date)return new Date(e.$date);const t={};for(const n of Object.keys(e))t[n]=h(e[n]);return t}function K(e){const t={size:e.defaultSize};if(e.sizes!==null){const n=[],{sizes:r}=e;for(let i=0;i<r.length;i++){if(!e.isCustom(i)||e.isHidden(i))continue;const s=r[i],o=e.isAuto(i);let f=i;for(;f+1<r.length&&r[f+1]===s&&e.isCustom(f+1)&&!e.isHidden(f+1)&&e.isAuto(f+1)===o;)f++;n.push(o?[i,f-i+1,s,1]:[i,f-i+1,s]),i=f}n.length&&(t.runs=n)}return e.hiddenSizes!==null&&e.hiddenSizes.size>0&&(t.hidden=[...e.hiddenSizes]),t}function V(e,t){if(t){t.size!==void 0&&t.size!==e.defaultSize&&e.setDefaultSize(t.size);for(const[n,r,i,s]of t.runs??[])for(let o=n;o<n+r;o++)e.setSize(o,i,s===1);for(const[n,r]of t.hidden??[])r>=0&&e.setSize(n,r),e.setHidden(n,!0)}}const oe=16;function le(e){const t={};for(const n of Object.keys(e))n!=="tpl"&&n[0]!=="_"&&(t[n]=e[n]);return t}function P(e,t,n){switch(t&L){case I:return n;case N:return e.strings.get(n);case E:return n!==0;case M:return{e:j[n]??"#N/A"};default:return null}}function fe(e,t,n,r,i){const s=[],o=[];let f=null,c=-2,m=-1,l=0,u=-1;const{formulas:y}=t,{rich:a}=e.strings,S=i.styles===!1,C=i.formulas===!1;for(let p=0;p<r.length;p++){const F=r[p];if(F===void 0)continue;const Q=p*J,{kinds:W,values:$,styles:A}=F;for(let g=0;g<J;g++){const O=W[g],w=Q+g;if(A!==null&&!S&&A[g]!==0&&(A[g]===l&&w===u+1?u=w:(l!==0&&o.push([m,u-m+1,l]),m=w,u=w,l=A[g])),O===0||O&Z)continue;let z;if(O&G){const x=y.get(w*v+n),R=P(e,O,$[g]);x&&!C?(z={f:le(x)},R!==null&&(z.v=R)):z=R}else(O&L)===N?(z=e.strings.get($[g]),a!==null&&a.has($[g])&&(z={s:z,rich:a.get($[g])})):z=P(e,O,$[g]);const H=w-c-1;if(f===null||H>oe)f={r:w,v:[]},s.push(f);else for(let x=0;x<H;x++)f.v.push(null);f.v.push(z),c=w}}return l!==0&&o.push([m,u-m+1,l]),{blocks:s,styles:o}}function ce(e,t,n,r){for(const{r:i,v:s}of r){let o=null,f=-1;for(let m=0;m<s.length;m++){const l=s[m];if(l===null)continue;const u=i+m,y=u>>>X;y!==f&&(o=t._ensure(u,n),f=y);const a=u&Y;if(typeof l=="number")o.kinds[a]=I,o.values[a]=l;else if(typeof l=="string")o.kinds[a]=N,o.values[a]=e.strings.add(l);else if(typeof l=="boolean")o.kinds[a]=E,o.values[a]=l?1:0;else if(l.e!==void 0)o.kinds[a]=M,o.values[a]=Math.max(0,j.indexOf(l.e));else if(l.s!==void 0){const S=e.strings.add(l.s);o.kinds[a]=N,o.values[a]=S,e.strings.rich??=new Map,e.strings.rich.set(S,l.rich)}else if(l.f!==void 0){let S=G,C=0;const p=l.v;typeof p=="number"?(S|=I,C=p):typeof p=="string"?(S|=N,C=e.strings.add(p)):typeof p=="boolean"?(S|=E,C=p?1:0):p&&p.e!==void 0&&(S|=M,C=Math.max(0,j.indexOf(p.e))),o.kinds[a]=S,o.values[a]=C,t.setFormula(u,n,typeof l.f=="string"?{f:l.f,typed:!0}:l.f)}}const c=i+s.length-1;c>t.maxRow&&(t.maxRow=c)}n>t.maxCol&&(t.maxCol=n)}function ue(e,t,n){for(const[r,i,s]of n)for(let o=r;o<r+i;o++)e.setStyle(o,t,s)}function q(e,t){const n={};for(const r of Object.keys(e)){if(r[0]==="_")continue;const i=e[r];i!==t[r]&&!(typeof i=="object"&&i!==null&&JSON.stringify(i)===JSON.stringify(t[r]))&&(n[r]=i)}return n}function ae(e,t,n,r,i){const s={name:t.name};t.hidden&&(s.hidden=!0),t.tabColor&&(s.tabColor=t.tabColor),t.rtl&&(s.rtl=!0),t.zoom!==1&&(s.zoom=t.zoom),t.frozenRows&&(s.frozenRows=t.frozenRows),t.frozenCols&&(s.frozenCols=t.frozenCols),t.showGridlines===!1&&(s.showGridlines=!1),s.rows=K(t.rows),s.cols=K(t.cols),t.rowStyles?.size&&(s.rowStyles=[...t.rowStyles]),t.colStyles?.size&&(s.colStyles=[...t.colStyles]),t.merges.length&&(s.merges=t.merges.map(({r0:l,c0:u,r1:y,c1:a})=>[l,u,y,a]));const o=[],f=[];t.columns.forEach((l,u)=>{if(r.cells===!1)return;const{blocks:y,styles:a}=fe(e,t,u,l,r);y.length&&o.push({c:u,blocks:y}),a.length&&f.push({c:u,runs:a})}),o.length&&(s.cells=o),f.length&&(s.styles=f);const c={};for(const l of Object.keys(t)){if(te.has(l)||ne.has(l)||l[0]==="_"||l.endsWith("Changed"))continue;const u=t[l];if(u==null||u===se[l])continue;const y=d(u,i,`${t.name}.${l}`);y!==void 0&&(c[l]=y)}Object.keys(c).length&&(s.features=c);const m=n?.objectsOf?.(t);if(m?.length){const l=d(m.map(me),i,`${t.name}.objects`);l.length&&(s.objects=l)}return s}function me(e){const{bitmap:t,blob:n,canvas:r,modelEpoch:i,...s}=e;return n&&(s.imageType=n.type),s}function Oe(e,t=null,n={}){const r=n.warnings??[],i=b(),s={format:T,version:_};s.activeSheet=e.activeSheet,e.fileName&&(s.fileName=e.fileName),e.themeInfo?s.theme=d(e.themeInfo,r,"theme"):e.theme&&(s.themeColors=e.theme);const o=e.styles.list;s.styles=o.length===1&&Object.keys(q(o[0],i)).length===0?[]:o.map(c=>q(c,i)),e.dxfs?.length&&(s.dxfs=d(e.dxfs,r,"dxfs")),e.persons?.length&&(s.persons=d(e.persons,r,"persons")),e.protection&&(s.protection=d(e.protection,r,"protection")),e.calcMode&&(s.calcMode=e.calcMode),e.getDataQueries&&(s.queries=d(e.getDataQueries,r,"queries")),e.customData&&(s.custom=d(e.customData,r,"custom"));const f=e.engine;if(f&&(f.manual&&(s.manualCalc=!0),f.names.size&&(s.names=[...f.names].map(([c,m])=>{const l=c.indexOf("!");return{name:m.name??(l>=0?c.slice(l+1):c),text:m.text,...l>=0?{sheet:Number(c.slice(0,l))}:{}}})),f.tables.size&&(s.tables=[...f.tables.values()].map(c=>{const{sheet:m,source:l,part:u,id:y,isNew:a,dirty:S,...C}=c;return{...d(C,r,`table ${c.name}`),sheet:e.sheets.indexOf(m)}}))),s.sheets=e.sheets.map(c=>ae(e,c,t,n,r)),t?.extrasToJSON){const c=t.extrasToJSON(r);c&&(s.extras=c)}return r.length&&(s.warnings=r),s}function de(e,t){t.hidden&&(e.hidden=!0),t.tabColor&&(e.tabColor=t.tabColor,e.tabColorChanged=!0),t.rtl&&(e.rtl=!0),t.zoom&&(e.zoom=t.zoom),e.frozenRows=t.frozenRows??0,e.frozenCols=t.frozenCols??0,t.showGridlines===!1&&(e.showGridlines=!1),V(e.rows,t.rows),V(e.cols,t.cols),(t.cols?.runs||t.cols?.hidden)&&(e.colsChanged=!0),t.rowStyles&&(e.rowStyles=new Map(t.rowStyles)),t.colStyles&&(e.colStyles=new Map(t.colStyles)),t.merges&&(e.merges=t.merges.map(([n,r,i,s])=>({r0:n,c0:r,r1:i,c1:s}))),e.viewChanged=!0;for(const[n,r]of Object.entries(t.features??{})){const i=h(r);e[n]=D.has(n)?D.get(n)(i):i,B[n]&&(e[B[n]]=!0)}}function pe(e,t){const n=b();t.styles?.length&&e.styles.load(t.styles.map(r=>({...n,...r}))),t.dxfs&&(e.dxfs=h(t.dxfs),e.sourceDxfs=0),t.persons&&(e.persons=h(t.persons),e.personsChanged=!0),t.protection&&(e.protection=h(t.protection),e.protectionChanged=!0),t.calcMode&&(e.calcMode=t.calcMode,e.calcModeChanged=!0),t.queries&&(e.getDataQueries=h(t.queries)),t.custom&&(e.customData=h(t.custom)),t.fileName&&(e.fileName=t.fileName),t.themeColors&&(e.theme=t.themeColors)}function ye(e,t,n={}){const{engine:r}=e;e.formulasEdited=!0,e.activeSheet=Math.min(t.activeSheet??0,e.sheets.length-1),r.sheetsChanged(),t.manualCalc&&(r.manual=!0),r.setNames((t.names??[]).map(i=>({name:i.name,text:i.text,localSheetId:i.sheet}))),t.names?.length&&(e.namesChanged=!0),r.setTables((t.tables??[]).map(i=>{const{sheet:s,...o}=i;return{...h(o),sheet:e.sheets[s],isNew:!0,dirty:!0}})),r.buildGraph({fullCalc:n.recalculate===!0}),e.dirty=!1}function $e(e,t={}){if(e?.format!==T)throw new Error(`This isn't ${T} JSON`);if(e.version>_)throw new Error(`This JSON has version ${e.version}; this code reads up to ${_}`);const n=new k;return n.engine=new ee(n),pe(n,t.styles===!1?{...e,styles:[]}:e),n.sheets=e.sheets.map(r=>new U(r.name)),e.sheets.forEach((r,i)=>{const s=n.sheets[i];de(s,r);for(const o of r.cells??[])ce(n,s,o.c,o.blocks);if(t.styles!==!1)for(const o of r.styles??[])ue(s,o.c,o.runs);if(r.styles?.length)for(const o of r.styles)o.c>s.maxCol&&(s.maxCol=o.c)}),ye(n,e,t),n}export{T as FORMAT_NAME,_ as FORMAT_VERSION,pe as applyBookMeta,de as applySheetMeta,$e as bookFromJSON,Oe as bookToJSON,h as decodeData,d as encodeData,ye as finishLoad,ze as registerFeatureReviver};
1
+ import{BOOL as E,CHUNK_BITS as X,CHUNK_MASK as Y,CHUNK_SIZE as J,ERR as M,ERRORS as j,FORMULA as G,KIND_MASK as L,NUM as I,SPILL as Z,STR as N,Sheet as U}from"../core/sheet.js";import{MAX_COLS as v}from"../core/address.js";import{defaultStyle as b}from"../core/styles.js";import{Workbook as k}from"../core/workbook.js";import{Engine as ee}from"../calc/engine.js";const T="8sheets",_=1,ne=new Set(["uid","name","columns","maxRow","maxCol","rows","cols","formulas","spills","rowStyles","colStyles","merges","mergeIndex","frozenRows","frozenCols","showGridlines","zoom","sourceId","sourceIndex","revision","hidden","tabColor","rtl"]),te=new Set(["apiObjects","cfEval","structureOps","dataBindings","report","isVirtual","split","onRefresh","onRejected","recorder"]),B={cf:"cfChanged",comments:"commentsChanged",hyperlinks:"hyperlinksChanged",validations:"validationsChanged",pageSetup:"pageSetupChanged",protection:"protectionChanged",scenarios:"scenariosChanged",sparklines:"sparklinesChanged",threads:"threadsChanged",autoFilter:"filterChanged",cellTypes:"cellTypesChanged"},D=new Map;function ze(e,n){D.set(e,n)}const se=new U(""),re=e=>{if(e===null||typeof e!="object")return!0;const n=Object.getPrototypeOf(e);return n===Object.prototype||n===null};function m(e,n,t){if(e===null||typeof e=="number"||typeof e=="string"||typeof e=="boolean")return e;if(e===void 0)return;if(typeof e=="function"){n?.push(`${t}: a function was left out`);return}if(Array.isArray(e))return e.map((i,s)=>m(i,n,`${t}[${s}]`)??null);if(e instanceof Map)return{$map:[...e].map(([i,s],o)=>[m(i,n,t),m(s,n,`${t}.${o}`)??null])};if(e instanceof Set)return{$set:[...e].map(i=>m(i,n,t))};if(ArrayBuffer.isView(e))return{$typed:e.constructor.name,v:[...e]};if(e instanceof Date)return{$date:e.toISOString()};if(!re(e)){if(typeof e.toJSON=="function")return m(e.toJSON(),n,t);n?.push(`${t}: a ${e.constructor?.name??"class"} instance was left out`);return}if("$map"in e||"$set"in e)throw new Error(`${t}: a key starting with $ can't be stored`);const r={};for(const i of Object.keys(e)){if(i[0]==="_")continue;const s=m(e[i],n,`${t}.${i}`);s!==void 0&&(r[i]=s)}return r}const ie={Uint8Array,Int8Array,Uint16Array,Int16Array,Uint32Array,Int32Array,Float32Array,Float64Array};function h(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(h);if(e.$map)return new Map(e.$map.map(([t,r])=>[h(t),h(r)]));if(e.$set)return new Set(e.$set.map(h));if(e.$typed)return ie[e.$typed].from(e.v);if(e.$date)return new Date(e.$date);const n={};for(const t of Object.keys(e))n[t]=h(e[t]);return n}function K(e){const n={size:e.defaultSize};if(e.sizes!==null){const t=[],{sizes:r}=e;for(let i=0;i<r.length;i++){if(!e.isCustom(i)||e.isHidden(i))continue;const s=r[i],o=e.isAuto(i);let f=i;for(;f+1<r.length&&r[f+1]===s&&e.isCustom(f+1)&&!e.isHidden(f+1)&&e.isAuto(f+1)===o;)f++;t.push(o?[i,f-i+1,s,1]:[i,f-i+1,s]),i=f}t.length&&(n.runs=t)}return e.hiddenSizes!==null&&e.hiddenSizes.size>0&&(n.hidden=[...e.hiddenSizes]),n}function V(e,n){if(n){n.size!==void 0&&n.size!==e.defaultSize&&e.setDefaultSize(n.size);for(const[t,r,i,s]of n.runs??[])for(let o=t;o<t+r;o++)e.setSize(o,i,s===1);for(const[t,r]of n.hidden??[])r>=0&&e.setSize(t,r),e.setHidden(t,!0)}}const oe=16;function le(e){const n={};for(const t of Object.keys(e))t!=="tpl"&&t[0]!=="_"&&(n[t]=e[t]);return n}function P(e,n,t){switch(n&L){case I:return t;case N:return e.strings.get(t);case E:return t!==0;case M:return{e:j[t]??"#N/A"};default:return null}}function fe(e,n,t,r,i){const s=[],o=[];let f=null,c=-2,d=-1,l=0,u=-1;const{formulas:y}=n,{rich:a}=e.strings,S=i.styles===!1,C=i.formulas===!1;for(let p=0;p<r.length;p++){const H=r[p];if(H===void 0)continue;const Q=p*J,{kinds:W,values:$,styles:A}=H;for(let g=0;g<J;g++){const O=W[g],w=Q+g;if(A!==null&&!S&&A[g]!==0&&(A[g]===l&&w===u+1?u=w:(l!==0&&o.push([d,u-d+1,l]),d=w,u=w,l=A[g])),O===0||O&Z)continue;let z;if(O&G){const x=y.get(w*v+t),R=P(e,O,$[g]);x&&!C?(z={f:le(x)},R!==null&&(z.v=R)):z=R}else(O&L)===N?(z=e.strings.get($[g]),a!==null&&a.has($[g])&&(z={s:z,rich:a.get($[g])})):z=P(e,O,$[g]);const F=w-c-1;if(f===null||F>oe)f={r:w,v:[]},s.push(f);else for(let x=0;x<F;x++)f.v.push(null);f.v.push(z),c=w}}return l!==0&&o.push([d,u-d+1,l]),{blocks:s,styles:o}}function ce(e,n,t,r){for(const{r:i,v:s}of r){let o=null,f=-1;for(let d=0;d<s.length;d++){const l=s[d];if(l===null)continue;const u=i+d,y=u>>>X;y!==f&&(o=n._ensure(u,t),f=y);const a=u&Y;if(typeof l=="number")o.kinds[a]=I,o.values[a]=l;else if(typeof l=="string")o.kinds[a]=N,o.values[a]=e.strings.add(l);else if(typeof l=="boolean")o.kinds[a]=E,o.values[a]=l?1:0;else if(l.e!==void 0)o.kinds[a]=M,o.values[a]=Math.max(0,j.indexOf(l.e));else if(l.s!==void 0){const S=e.strings.add(l.s);o.kinds[a]=N,o.values[a]=S,e.strings.rich??=new Map,e.strings.rich.set(S,l.rich)}else if(l.f!==void 0){let S=G,C=0;const p=l.v;typeof p=="number"?(S|=I,C=p):typeof p=="string"?(S|=N,C=e.strings.add(p)):typeof p=="boolean"?(S|=E,C=p?1:0):p&&p.e!==void 0&&(S|=M,C=Math.max(0,j.indexOf(p.e))),o.kinds[a]=S,o.values[a]=C,n.setFormula(u,t,typeof l.f=="string"?{f:l.f,typed:!0}:l.f)}}const c=i+s.length-1;c>n.maxRow&&(n.maxRow=c)}t>n.maxCol&&(n.maxCol=t)}function ue(e,n,t){for(const[r,i,s]of t)for(let o=r;o<r+i;o++)e.setStyle(o,n,s)}function q(e,n){const t={};for(const r of Object.keys(e)){if(r[0]==="_")continue;const i=e[r];i!==n[r]&&!(typeof i=="object"&&i!==null&&JSON.stringify(i)===JSON.stringify(n[r]))&&(t[r]=i)}return t}function ae(e,n,t,r,i){const s={name:n.name};n.hidden&&(s.hidden=!0),n.hidden&&n.veryHidden&&(s.veryHidden=!0),n.tabColor&&(s.tabColor=n.tabColor),n.rtl&&(s.rtl=!0),n.zoom!==1&&(s.zoom=n.zoom),n.frozenRows&&(s.frozenRows=n.frozenRows),n.frozenCols&&(s.frozenCols=n.frozenCols),n.showGridlines===!1&&(s.showGridlines=!1),s.rows=K(n.rows),s.cols=K(n.cols),n.rowStyles?.size&&(s.rowStyles=[...n.rowStyles]),n.colStyles?.size&&(s.colStyles=[...n.colStyles]),n.merges.length&&(s.merges=n.merges.map(({r0:l,c0:u,r1:y,c1:a})=>[l,u,y,a]));const o=[],f=[];n.columns.forEach((l,u)=>{if(r.cells===!1)return;const{blocks:y,styles:a}=fe(e,n,u,l,r);y.length&&o.push({c:u,blocks:y}),a.length&&f.push({c:u,runs:a})}),o.length&&(s.cells=o),f.length&&(s.styles=f);const c={};for(const l of Object.keys(n)){if(ne.has(l)||te.has(l)||l[0]==="_"||l.endsWith("Changed"))continue;const u=n[l];if(u==null||u===se[l])continue;const y=m(u,i,`${n.name}.${l}`);y!==void 0&&(c[l]=y)}Object.keys(c).length&&(s.features=c);const d=t?.objectsOf?.(n);if(d?.length){const l=m(d.map(de),i,`${n.name}.objects`);l.length&&(s.objects=l)}return s}function de(e){const{bitmap:n,blob:t,canvas:r,modelEpoch:i,...s}=e;return t&&(s.imageType=t.type),s}function Oe(e,n=null,t={}){const r=t.warnings??[],i=b(),s={format:T,version:_};s.activeSheet=e.activeSheet,e.fileName&&(s.fileName=e.fileName),e.themeInfo?s.theme=m(e.themeInfo,r,"theme"):e.theme&&(s.themeColors=e.theme);const o=e.styles.list;s.styles=o.length===1&&Object.keys(q(o[0],i)).length===0?[]:o.map(c=>q(c,i)),e.dxfs?.length&&(s.dxfs=m(e.dxfs,r,"dxfs")),e.persons?.length&&(s.persons=m(e.persons,r,"persons")),e.protection&&(s.protection=m(e.protection,r,"protection")),e.calcMode&&(s.calcMode=e.calcMode),e.getDataQueries&&(s.queries=m(e.getDataQueries,r,"queries")),e.customData&&(s.custom=m(e.customData,r,"custom"));const f=e.engine;if(f&&(f.manual&&(s.manualCalc=!0),f.names.size&&(s.names=[...f.names].map(([c,d])=>{const l=c.indexOf("!");return{name:d.name??(l>=0?c.slice(l+1):c),text:d.text,...l>=0?{sheet:Number(c.slice(0,l))}:{}}})),f.tables.size&&(s.tables=[...f.tables.values()].map(c=>{const{sheet:d,source:l,part:u,id:y,isNew:a,dirty:S,...C}=c;return{...m(C,r,`table ${c.name}`),sheet:e.sheets.indexOf(d)}}))),s.sheets=e.sheets.map(c=>ae(e,c,n,t,r)),n?.extrasToJSON){const c=n.extrasToJSON(r);c&&(s.extras=c)}return r.length&&(s.warnings=r),s}function me(e,n){n.hidden&&(e.hidden=!0),n.hidden&&n.veryHidden&&(e.veryHidden=!0),n.tabColor&&(e.tabColor=n.tabColor,e.tabColorChanged=!0),n.rtl&&(e.rtl=!0),n.zoom&&(e.zoom=n.zoom),e.frozenRows=n.frozenRows??0,e.frozenCols=n.frozenCols??0,n.showGridlines===!1&&(e.showGridlines=!1),V(e.rows,n.rows),V(e.cols,n.cols),(n.cols?.runs||n.cols?.hidden)&&(e.colsChanged=!0),n.rowStyles&&(e.rowStyles=new Map(n.rowStyles)),n.colStyles&&(e.colStyles=new Map(n.colStyles)),n.merges&&(e.merges=n.merges.map(([t,r,i,s])=>({r0:t,c0:r,r1:i,c1:s}))),e.viewChanged=!0;for(const[t,r]of Object.entries(n.features??{})){const i=h(r);e[t]=D.has(t)?D.get(t)(i):i,B[t]&&(e[B[t]]=!0)}}function pe(e,n){const t=b();n.styles?.length&&e.styles.load(n.styles.map(r=>({...t,...r}))),n.dxfs&&(e.dxfs=h(n.dxfs),e.sourceDxfs=0),n.persons&&(e.persons=h(n.persons),e.personsChanged=!0),n.protection&&(e.protection=h(n.protection),e.protectionChanged=!0),n.calcMode&&(e.calcMode=n.calcMode,e.calcModeChanged=!0),n.queries&&(e.getDataQueries=h(n.queries)),n.custom&&(e.customData=h(n.custom)),n.fileName&&(e.fileName=n.fileName),n.themeColors&&(e.theme=n.themeColors)}function ye(e,n,t={}){const{engine:r}=e;e.formulasEdited=!0,e.activeSheet=Math.min(n.activeSheet??0,e.sheets.length-1),r.sheetsChanged(),n.manualCalc&&(r.manual=!0),r.setNames((n.names??[]).map(i=>({name:i.name,text:i.text,localSheetId:i.sheet}))),n.names?.length&&(e.namesChanged=!0),r.setTables((n.tables??[]).map(i=>{const{sheet:s,...o}=i;return{...h(o),sheet:e.sheets[s],isNew:!0,dirty:!0}})),r.buildGraph({fullCalc:t.recalculate===!0}),e.dirty=!1}function $e(e,n={}){if(e?.format!==T)throw new Error(`This isn't ${T} JSON`);if(e.version>_)throw new Error(`This JSON has version ${e.version}; this code reads up to ${_}`);const t=new k;return t.engine=new ee(t),pe(t,n.styles===!1?{...e,styles:[]}:e),t.sheets=e.sheets.map(r=>new U(r.name)),e.sheets.forEach((r,i)=>{const s=t.sheets[i];me(s,r);for(const o of r.cells??[])ce(t,s,o.c,o.blocks);if(n.styles!==!1)for(const o of r.styles??[])ue(s,o.c,o.runs);if(r.styles?.length)for(const o of r.styles)o.c>s.maxCol&&(s.maxCol=o.c)}),ye(t,e,n),t}export{T as FORMAT_NAME,_ as FORMAT_VERSION,pe as applyBookMeta,me as applySheetMeta,$e as bookFromJSON,Oe as bookToJSON,h as decodeData,m as encodeData,ye as finishLoad,ze as registerFeatureReviver};
package/calc/engine.js CHANGED
@@ -1 +1 @@
1
- import{resolveStructuredSpec as yt}from"../slicers/structured.js";import{Arr as C,compareValues as v,ERR as k,ERR_BY_INDEX as Y,Lambda as kt,num as S,power as _t,Ref as q,RefList as $,RichValue as O,str as rt,XlError as x}from"./values.js";import{entityVm as at,richValueAt as gt}from"../cells/rich-values.js";import{Compiler as lt}from"./compile.js";import{FormulaSyntaxError as W,Parser as j,templateKey as bt,tokenize as z,toDisplayFormula as Mt}from"./parser.js";import{BOOL as G,CHUNK_BITS as E,CHUNK_MASK as T,CONTENT_MASK as ot,DIRTY as w,EMPTY as Q,EVALUATING as X,FORMULA as R,KIND_MASK as V,NUM as U,SPILL as H,STR as B,ERR as N}from"../core/sheet.js";import{colName as ct,MAX_COLS as M,MAX_ROWS as J,parseRangeRef as P}from"../core/address.js";import{CellSet as wt}from"./cell-set.js";import{isRowBelow as At}from"./fill-shape.js";import"./functions/index.js";const Z=Symbol("pending"),ht=200,Ct=4096,xt=64,tt=2147483647,D=4;class et{constructor(){this.n=0,this.data=new Int32Array(D*8)}push(t,e,s,n){if((this.n+1)*D>this.data.length){const a=new Int32Array(this.data.length*2);a.set(this.data),this.data=a}const i=this.n++*D,r=this.data;r[i]=t,r[i+1]=e,r[i+2]=s,r[i+3]=n}}function Tt(m,t){if(!m.valueMeta.has(t))return;const e=new Map(m.valueMeta);e.delete(t),m.valueMeta=e.size>0?e:null}function ft(m,t,e){if(m.valueMeta?.get(t)===e)return;const s=new Map(m.valueMeta??[]);s.set(t,e),m.valueMeta=s}function st(m,t){let e=m.get(t);return e===void 0&&(e=new wt,m.set(t,e)),e}class Rt{constructor(){this.buckets=[],this.wide=[],this.all=new et,this.allCols=[]}}class Bt{constructor(t){this.book=t,this.sheetGen=0,this.sheetMap=new Map,this.deps=new Map,this.templates=new Map,this.lastOwn={row:-2,col:-1,text:"",tpl:{cacheKey:void 0}},this.frame=null,this.depth=0,this.legacy=!1,this.pendingSheet=null,this.pendingRow=0,this.pendingCol=0,this.circular=null,this.evalStack=new Int32Array(3*256),this.evalTop=0,this.cycleLow=tt,this.iterate=null,this.cycleFound=[],this.cycleMembers=null,this.iterating=!1,this.sliceMs=10,this.syncLimit=4e3,this.externalLinks=null,this.names=new Map,this.nameTemplates=new Map,this.tables=new Map,this.volatile=new Map,this.visibilityReaders=new Map,this.styleReaders=new Map,this.wakePending=0,this.queue=new Int32Array(4096),this.qHead=0,this.qLen=0,this.sheetsByUid=new Map,this.running=!1,this.timer=0,this.manual=!1,this.graphReady=!0,this.pendingChanges=[],this.waiters=[],this.onChange=null,this.dataTables=[],this.tablesDirty=!1,this.inTables=!1,this.tablesForced=!1,this.onProgress=null,this.lookupCache=new Map,this.colRevisions=new Map,this.channel=null,this.sheetsChanged()}sheetsChanged(){this.sheetGen++,this.sheetMap.clear(),this.sheetsByUid.clear();for(const t of this.book.sheets)this.sheetMap.set(t.name.toUpperCase(),t),this.sheetsByUid.set(t.uid,t),t.rows.watcher=this,t.cols.watcher=this}sheetByName(t){return this.sheetMap.get(t.toUpperCase())??null}externalSheet(t,e){return this.externalLinks?.sheet(t,e)??null}sheetsBetween(t,e){const{sheets:s}=this.book,n=s.findIndex(r=>r.name.toUpperCase()===t.toUpperCase()),i=s.findIndex(r=>r.name.toUpperCase()===e.toUpperCase());return n<0||i<0?null:s.slice(Math.min(n,i),Math.max(n,i)+1)}setNames(t){this.names.clear(),this.nameTemplates.clear();for(const e of t){const s=e.localSheetId!==void 0?`${e.localSheetId}!${e.name.toUpperCase()}`:e.name.toUpperCase();this.names.set(s,{text:e.text,name:e.name,hidden:e.hidden,comment:e.comment})}}setTables(t){this.tables.clear();for(const e of t)this.tables.set(e.name.toUpperCase(),e)}template(t,e,s){let n;try{n=z(t)}catch(a){if(a instanceof W)return this._broken(t);throw a}const i=bt(n,e,s);let r=this.templates.get(i);if(r===void 0){try{const a=new j(n,e,s).parse();r=this._compile(a)}catch(a){if(!(a instanceof W))throw a;r=this._broken(t)}r.cacheKey=i,this.templates.set(i,r)}return r}_ownTemplate(t,e,s){const n=this.lastOwn;let i;return n.row===e-1&&n.col===s&&this.templates.get(n.tpl.cacheKey)===n.tpl&&At(n.text,t)?i=n.tpl:i=this.template(t,e,s),n.row=e,n.col=s,n.text=t,n.tpl=i,i}_compile(t){const e=new lt(this);return{fn:e.compileTop(t),refs:e.refs,names:e.names,tables:e.tables,isVolatile:e.isVolatile,notInExcel:e.notInExcel===!0,mayArray:e.mayArray,external:e.external}}_broken(){return{invalid:!0,fn:()=>k.NAME,refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1,external:!0}}validate(t){it(new j(z(t),0,0).parse())}_templateFor(t,e,s,n){if(n.tpl!==void 0)return n.tpl;let i;return n.t==="dataTable"?i=this._dataTableTemplate():n.f!==void 0&&n.base===void 0?i=this._ownTemplate(n.f,e,s):n.f!==void 0?i=this.template(n.f,Math.floor(n.base/M),n.base%M):n.sf!==void 0?i=this.template(n.sf,Math.floor(n.base/M),n.base%M):i=this._broken(),n.tpl=i,i}_index(t){let e=this.deps.get(t);return e===void 0&&(e=new Rt,this.deps.set(t,e)),e}_addDep(t,e,s,n,i,r,a,o){const l=this._index(t),c=r.uid<<14|o;if(i-s>=xt){l.all.push(a,c,e,n),l.allCols.push(s,i);return}if(n-e>=Ct){for(let p=s;p<=i;p++){let f=l.wide[p];f===void 0&&(f=new et,l.wide[p]=f),f.push(a,c,e,n)}return}const u=e>>>E,d=n>>>E;for(let p=s;p<=i;p++){let f=l.buckets[p];f===void 0&&(f=[],l.buckets[p]=f);for(let h=u;h<=d;h++){let y=f[h];y===void 0&&(y=new et,f[h]=y),y.push(a,c,e,n)}}}register(t,e,s,n){const i=this._templateFor(t,e,s,n);if(i.external)return i;for(const r of i.refs)this._addRefDep(r,t,e,s);for(const r of i.names)this._addNameDeps(r,t,e,s);for(const r of i.tables)this._addTableDep(r,t,e,s);return i.isVolatile&&st(this.volatile,t).add(e,s),i.readsVisibility??=/SUBTOTAL|AGGREGATE|SPARK_/i.test(n.f??n.sf??""),i.readsVisibility&&st(this.visibilityReaders,t).add(e,s),i.readsStyles??=/SPARK_BLOCK/i.test(n.f??n.sf??""),i.readsStyles&&st(this.styleReaders,t).add(e,s),i}_addRefDep(t,e,s,n){const i=t.rAbs0?t.r0:s+t.r0,r=t.rAbs1?t.r1:s+t.r1,a=t.cAbs0?t.c0:n+t.c0,o=t.cAbs1?t.c1:n+t.c1,l=Math.max(0,Math.min(i,r)),c=Math.min(J-1,Math.max(i,r)),u=Math.max(0,Math.min(a,o)),d=Math.min(M-1,Math.max(a,o));if(l>c||u>d)return;if(t.sheet?.sheet2&&(t.sheet.book===null||t.sheet.book===void 0)){for(const f of this.sheetsBetween(t.sheet.sheet,t.sheet.sheet2)??[])this._addDep(f,l,u,c,d,e,s,n);return}if(t.sheet?.book!==null&&t.sheet?.book!==void 0)return;const p=t.sheet?this.sheetByName(t.sheet.sheet):e;p&&this._addDep(p,l,u,c,d,e,s,n)}_addNameDeps(t,e,s,n){const i=this._nameTemplate(t,e);if(i!==null){for(const r of i.refs)this._addRefDep(r,e,s,n);for(const r of i.names)r.toUpperCase()!==t.toUpperCase()&&this._addNameDeps(r,e,s,n)}}_addTableDep(t,e,s,n){const i=this.resolveTable(t.name,t.spec,s,n,e);i instanceof q&&this._addDep(i.sheet,i.r0,i.c0,i.r1,i.c1,e,s,n)}rebuild(){this.deps.clear(),this.volatile.clear(),this.visibilityReaders.clear(),this.styleReaders.clear(),this.lookupCache.clear(),this.qHead=0,this.qLen=0,this.cycleFound=[],this.cycleMembers=null,this.sheetGen++,this.buildGraph({fullCalc:!0})}buildGraph({fullCalc:t=!1,onDone:e}={}){this.graphReady=!1,this.dataTables=[],t&&(this.tablesDirty=!0);const s=this,n=this.book.sheets.map(c=>[c,c.formulas]);let i=0,r=0,a=0,o=0;const l=()=>{const c=performance.now()+s.sliceMs;let u=0;for(;i<n.length;i++,r=0,a=0,o=0){const[p,f]=n[i],{columns:h}=f;for(;r<h.length;r++,a=0,o=0){const y=h[r];if(y!==void 0)for(;a<y.length;a++,o=0){const _=y[a];if(_===void 0)continue;const{ids:g}=_,b=a<<E;for(;o<=T;o++){const L=g[o];if(L===0)continue;const A=f.infos[L],I=b+o;A.t==="dataTable"&&s.dataTables.push({sheet:p,row:I,col:r,info:A});const F=s.register(p,I,r,A);if(s._initFormula(p,I,r,A,F,t),++u%256===0&&performance.now()>c){o++,s.onProgress?.({preparing:!0}),s._later(l);return}}}}}s.graphReady=!0;const d=s.pendingChanges;s.pendingChanges=[];for(const[p,f,h,y]of d)s.cellsChanged(p,f,h,y);s._schedule(),e?.()};l()}_initFormula(t,e,s,n,i,r){const a=t._chunk(e,s);if(a===void 0)return;const o=e&T;if(n.t==="array"&&n.ref&&this._markArrayChildren(t,e,s,n),i.external)return;const l=a.kinds[o];(r||i.isVolatile||(l&V)===Q||i.notInExcel&&(l&V)===N)&&(a.kinds[o]=l|w,this._enqueue(t,e,s))}_markArrayChildren(t,e,s,n){const i=P(n.ref);if(i!==null){t.spills||(t.spills=new Map),t.spills.set(e*M+s,{...i,blocked:!1,fixed:!n.cm});for(let r=i.r0;r<=i.r1;r++)for(let a=i.c0;a<=i.c1;a++){if(r===e&&a===s)continue;const o=t._ensure(r,a);o.kinds[r&T]|=H}}}_enqueue(t,e,s){if(this.qLen+3>this.queue.length)if(this.qHead>this.queue.length>>>1)this.queue.copyWithin(0,this.qHead,this.qLen),this.qLen-=this.qHead,this.qHead=0;else{const n=new Int32Array(this.queue.length*2);n.set(this.queue),this.queue=n}this.queue[this.qLen++]=t.uid,this.queue[this.qLen++]=e,this.queue[this.qLen++]=s}_dirtyFrom(t,e,s,n,i){const r=[t,e,s,n,i];for(;r.length>0;){const a=r.pop(),o=r.pop(),l=r.pop(),c=r.pop(),u=r.pop(),d=this.deps.get(u);if(d===void 0)continue;const p=(y,_)=>{const g=this.sheetsByUid.get(_>>>14);if(g===void 0)return;const b=_&16383,L=g._chunk(y,b);if(L===void 0)return;const A=y&T,I=L.kinds[A];(I&R)===0||(I&w)!==0||(L.kinds[A]=I|w,this._enqueue(g,y,b),r.push(g,b,b,y,y))},f=o>>>E,h=a>>>E;for(let y=c;y<=l;y++){const _=d.buckets[y];if(_!==void 0)for(let b=f;b<=h;b++){const L=_[b];if(L===void 0)continue;const{data:A}=L,I=L.n*D;for(let F=0;F<I;F+=D)a>=A[F+2]&&o<=A[F+3]&&p(A[F],A[F+1])}const g=d.wide[y];if(g!==void 0){const{data:b}=g,L=g.n*D;for(let A=0;A<L;A+=D)a>=b[A+2]&&o<=b[A+3]&&p(b[A],b[A+1])}}if(d.all.n>0){const{data:y}=d.all;for(let _=0;_<d.all.n;_++){const g=_*D;a>=y[g+2]&&o<=y[g+3]&&l>=d.allCols[_*2]&&c<=d.allCols[_*2+1]&&p(y[g],y[g+1])}}}}cellsChanged(t,e,s,n){if(n===0)return;if(this.inTables||(this.tablesDirty=!0),!this.graphReady){this.pendingChanges.push([t,e.slice(0,n),s.slice(0,n),n]);return}this.lookupCache.clear();const i=new Map;for(let r=0;r<n;r++){const a=e[r],o=s[r],l=i.get(o);l===void 0?i.set(o,[a,a]):(a<l[0]&&(l[0]=a),a>l[1]&&(l[1]=a));const c=t._chunk(a,o);if(c===void 0)continue;const u=a&T,d=c.kinds[u];if(d&R){const p=t.formula(a,o);p&&(this.register(t,a,o,p),d&w||(c.kinds[u]=d|w,this._enqueue(t,a,o)))}t.spills&&this._spillTouched(t,a,o)}for(const[r,a]of i)this._dirtyFrom(t,r,r,a[0],a[1]);this._markVolatile(),this._schedule()}_spillTouched(t,e,s){const n=e*M+s;for(const[i,r]of t.spills){const a=Math.floor(i/M),o=i-a*M;if(i===n){(t.kind(a,o)&R)===0&&(this._clearSpill(t,r,a,o),t.spills.delete(i));continue}if(e>=r.r0&&e<=r.r1&&s>=r.c0&&s<=r.c1){const l=t._chunk(a,o);if(l===void 0)continue;const c=a&T,u=l.kinds[c];u&R&&!(u&w)&&(l.kinds[c]=u|w,this._enqueue(t,a,o),this._dirtyFrom(t,o,o,a,a))}}}_markVolatile(){for(const[t,e]of this.volatile)e.forEach((s,n)=>{const i=t._chunk(s,n);if(i===void 0)return;const r=s&T,a=i.kinds[r];if(!(a&R)){e.delete(s,n);return}a&w||(i.kinds[r]=a|w,this._enqueue(t,s,n),this._dirtyFrom(t,n,n,s,s))})}get pending(){return(this.qLen-this.qHead)/3}_later(t){if(this._next=t,typeof MessageChannel>"u"){setTimeout(()=>this._tick(),0);return}this.channel===null&&(this.channel=new MessageChannel,this.channel.port1.onmessage=()=>this._tick()),this.channel.port2.postMessage(0)}_tick(){const t=this._next;this._next=null,t?.(),this._next===null&&this.channel!==null&&(this.channel.port1.close(),this.channel=null)}_schedule(){if(this.manual||this.inTables||this.running||!this.graphReady)return;if(this.pending===0){this._finish();return}const t=this.pending;if(t<=this.syncLimit&&(this._slice(this.syncLimit===1/0?1/0:this.sliceMs),this.pending===0)){this._finish();return}this.running=!0,this._total=t;const e=()=>{this._slice(this.sliceMs),this.pending>0?(this.onProgress?.({remaining:this.pending,total:Math.max(this._total,this.pending)}),this._later(e)):(this.running=!1,this._finish())};this._later(e)}_slice(t){const e=t!==1/0;let s=e?performance.now():0;const n=s+t;let i=1,r=1;for(;this.qHead<this.qLen;){const a=this.queue[this.qHead++],o=this.queue[this.qHead++],l=this.queue[this.qHead++],c=this.sheetsByUid.get(a);if(c!==void 0&&(this._run(c,o,l),e&&--r===0)){const u=performance.now();if(u>n)break;i=u-s<.5?Math.min(i*2,16):1,r=i,s=u}}this.qHead>=this.qLen&&(this.qHead=0,this.qLen=0)}_finish(){for(;this.cycleFound.length>0;)this._iterateCycles();const t=this.tablesForced;this.tablesForced=!1,this.tablesDirty&&this.dataTables.length>0&&(!this.skipTables||t)&&(this.tablesDirty=!1,this._computeDataTables()),this.onChange?.();const e=this.waiters;this.waiters=[];for(const s of e)s()}_dataTableTemplate(){const t=this;return{fn:(s,n,i)=>t._plainValue(i,s,n),refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1}}_plainValue(t,e,s){const n=t.value(e,s);switch(t.kind(e,s)&V){case U:return n;case B:return this.book.strings.get(n);case G:return n!==0;case N:return Y[n];default:return null}}_writePlain(t,e,s,n){const i=t.kind(e,s)&R;n==null?t.setCell(e,s,i|U,0):typeof n=="number"?Number.isFinite(n)?t.setCell(e,s,i|U,n):t.setCell(e,s,i|N,k.NUM.index):typeof n=="boolean"?t.setCell(e,s,i|G,n?1:0):n instanceof x?t.setCell(e,s,i|N,n.index):t.setCell(e,s,i|B,this.book.strings.add(String(n)))}_setInputs(t,e){const s=new Uint32Array(e.length),n=new Uint32Array(e.length);e.forEach((i,r)=>{t.setCell(i.row,i.col,i.kind,i.value),s[r]=i.row,n[r]=i.col}),this.cellsChanged(t,s,n,e.length),this._slice(1/0)}evaluateWith(t,e,s){const n=e.map(({row:r,col:a})=>({row:r,col:a,kind:t.kind(r,a)&(V|R),value:t.value(r,a)})),i=this.inTables;this.inTables=!0;try{return this._setInputs(t,e.map(({row:r,col:a,text:o})=>{const l=Number(o);return o!==""&&Number.isFinite(l)?{row:r,col:a,kind:U,value:l}:{row:r,col:a,kind:B,value:this.book.strings.add(String(o))}})),s()}finally{this._setInputs(t,n),this.inTables=i}}_computeDataTables(){this.inTables=!0;const t=this.dataTables.filter(e=>e.sheet.formula(e.row,e.col)===e.info&&this.book.sheets.includes(e.sheet));this.dataTables=t;try{for(const e of t)this._computeDataTable(e)}finally{this.inTables=!1}}_computeDataTable({sheet:t,info:e}){const s=P(e.ref),n=P(e.r1??"");if(!s||!n)return;const i=e.r2?P(e.r2):null,r=e.dt2D==="1"||e.dt2D==="true",a=e.dtr==="1"||e.dtr==="true",o=(h,y)=>({kind:t.kind(h,y)&V,value:t.value(h,y)}),c=[n,i].filter(Boolean).map(h=>({row:h.r0,col:h.c0,kind:t.kind(h.r0,h.c0)&(V|R),value:t.value(h.r0,h.c0)})),u=[];for(let h=s.r0;h<=s.r1;h++)for(let y=s.c0;y<=s.c1;y++){let _,g;r?(_=[{row:n.r0,col:n.c0,...o(s.r0-1,y)},{row:i.r0,col:i.c0,...o(h,s.c0-1)}],g=[s.r0-1,s.c0-1]):a?(_=[{row:n.r0,col:n.c0,...o(s.r0-1,y)}],g=[h,s.c0-1]):(_=[{row:n.r0,col:n.c0,...o(h,s.c0-1)}],g=[s.r0-1,y]),this._setInputs(t,_);let b=this.read(t,g[0],g[1]);b instanceof C&&(b=b.data[0]),u.push(h,y,b)}this._setInputs(t,c);const d=u.length/3,p=new Uint32Array(d),f=new Uint32Array(d);for(let h=0;h<d;h++)p[h]=u[h*3],f[h]=u[h*3+1],this._writePlain(t,p[h],f[h],u[h*3+2]);this.cellsChanged(t,p,f,d),this._slice(1/0),t.revision++}dataTableAt(t,e,s){for(const n of this.dataTables){if(n.sheet!==t)continue;const i=P(n.info.ref);if(i&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1)return n}return null}calculateNow(){const{manual:t,skipTables:e}=this;this.manual=!1,this.skipTables=!1,this.tablesDirty=!0,this.tablesForced=!0,this._markVolatile(),this._markCycles(),this._schedule(),this.manual=t,this.skipTables=e}whenIdle(){return this.pending===0&&this.graphReady&&!this.running?Promise.resolve():new Promise(t=>{this.waiters.push(t),this._schedule()})}_iterateCycles(){const t=this.cycleFound;this.cycleFound=[];const e=new Map,s=(a,o,l)=>{let c=e.get(a.uid);c===void 0&&(c=new Map,e.set(a.uid,c)),c.set(o*M+l,[a,o,l])};for(let a=0;a<t.length;a+=3)s(t[a],t[a+1],t[a+2]);const n=[];for(const a of this.book.sheets){const o=e.get(a.uid);o&&n.push(...[...o.keys()].sort((l,c)=>l-c).map(l=>o.get(l)))}this.cycleMembers??=new Map;for(const a of n)this.cycleMembers.set(`${a[0].uid}:${a[1]}:${a[2]}`,a);const{count:i,delta:r}=this.iterate;for(let a=1;a<=i;a++){let o=0;for(const[l,c,u]of n){const d=l._chunk(c,u);if(d===void 0)continue;const p=c&T;if(!(d.kinds[p]&R))continue;const f=d.values[p];d.kinds[p]|=w,this.iterating=!0,this._run(l,c,u),this.iterating=!1;const h=Math.abs(d.values[p]-f);h>o&&(o=h)}if(this.onProgress?.({iteration:a,iterations:i}),o<r)break}for(const[a,o,l]of n)this._dirtyFrom(a,l,l,o,o);for(const[a,o,l]of n){const c=a._chunk(o,l);c!==void 0&&(c.kinds[o&T]&=~w)}this._slice(1/0)}_markCycles(){if(!(this.iterate===null||this.cycleMembers===null))for(const[t,e,s]of this.cycleMembers.values()){const n=t._chunk(e,s);n===void 0||!(n.kinds[e&T]&R)||(n.kinds[e&T]|=w,this._enqueue(t,e,s))}}_run(t,e,s){const n=[t,e,s];for(;n.length>0;){const i=n[n.length-1],r=n[n.length-2],a=n[n.length-3];try{this.depth=0,this.evalTop=0,this.cycleLow=tt,this._calc(a,r,i),n.length-=3}catch(o){if(o!==Z)throw o;n.push(this.pendingSheet,this.pendingRow,this.pendingCol)}}}_calc(t,e,s){const n=t._chunk(e,s);if(n===void 0)return;const i=e&T,r=n.kinds[i];if(!(r&w))return;if(r&X){this.circular={sheet:t,row:e,col:s},this.iterating||this._cycleHit(t.uid,e,s);return}if(this.depth>=ht)throw this.pendingSheet=t,this.pendingRow=e,this.pendingCol=s,Z;const a=t.formula(e,s);if(a===void 0||!(r&R)){n.kinds[i]=r&~w;return}const o=this._templateFor(t,e,s,a);if(o.external){n.kinds[i]=r&~w;return}n.kinds[i]=r|X;const l=this.evalTop;l+3>this.evalStack.length&&this._growEvalStack(),this.evalStack[l]=t.uid,this.evalStack[l+1]=e,this.evalStack[l+2]=s,this.evalTop=l+3;const c=this.cycleLow;this.cycleLow=tt;const u=this.legacy,d=this.frame,p=a.typed!==!0&&a.t!=="array";this.legacy=p,this.depth++;let f;try{f=o.fn(e,s,t)}catch(y){if(n.kinds[i]&=~X,this.depth--,this.legacy=u,this.frame=d,this.evalTop=l,this.cycleLow=c,y===Z)throw y;y instanceof x?f=y:(console.error("Formula evaluation failed",y),f=k.VALUE),this._store(t,n,i,e,s,f,a,p);return}this.depth--,this.legacy=u,this.frame=d,this.evalTop=l;const h=this.cycleLow;if(this.cycleLow=h<l&&h<c?h:c,h<=l){if(this.iterate!==null){n.kinds[i]=r&~(w|X),this.cycleFound.push(t,e,s);return}f=0}this._store(t,n,i,e,s,f,a,p)}_cycleHit(t,e,s){const n=this.evalStack;for(let i=this.evalTop-3;i>=0;i-=3)if(n[i]===t&&n[i+1]===e&&n[i+2]===s){i<this.cycleLow&&(this.cycleLow=i);return}}_growEvalStack(){const t=new Int32Array(this.evalStack.length*2);t.set(this.evalStack),this.evalStack=t}_store(t,e,s,n,i,r,a,o){let l=r;(l instanceof q||l instanceof $)&&(l=o?this.refAuto(l,n,i):this.refToValue(l)),l instanceof kt&&(l=k.CALC),l instanceof C?a.t==="array"&&!a.cm&&a.ref?l=this._fillFixedArray(t,n,i,a,l):o||l.rows===1&&l.cols===1?(l=l.data[0],t.spills&&this._releaseSpill(t,n,i)):l=this._spill(t,n,i,a,l):t.spills&&!(a.t==="array"&&!a.cm)&&this._releaseSpill(t,n,i),a.t==="array"&&!a.cm&&a.ref&&!(r instanceof C)&&(l=this._fillFixedArray(t,n,i,a,C.filled(1,1,l)));let c=R,u=0;typeof l=="number"?Number.isFinite(l)?(c|=U,u=l):(c|=N,u=k.NUM.index):typeof l=="string"?(c|=B,u=this.book.strings.add(l)):typeof l=="boolean"?(c|=G,u=l?1:0):l instanceof x?(c|=N,u=l.index):l instanceof O?(c|=N,u=k.VALUE.index):c|=U,l instanceof O?ft(t,n*M+i,at(this.book,l.index)):t.valueMeta!==null&&((e.kinds[s]&ot)!==c||e.values[s]!==u)&&!/IMAGE\(/i.test(a.f??a.sf??"")&&Tt(t,n*M+i),e.kinds[s]=c,e.values[s]=u,n>t.maxRow&&(t.maxRow=n),i>t.maxCol&&(t.maxCol=i)}_writeArrayCell(t,e,s,n){let i=H,r=0;typeof n=="number"?(i|=Number.isFinite(n)?U:N,r=Number.isFinite(n)?n:k.NUM.index):typeof n=="string"?(i|=B,r=this.book.strings.add(n)):typeof n=="boolean"?(i|=G,r=n?1:0):n instanceof x?(i|=N,r=n.index):n==null?i|=U:(i|=N,r=k.VALUE.index,n instanceof O&&ft(t,e*M+s,at(this.book,n.index))),t.setCell(e,s,i,r)}_fillFixedArray(t,e,s,n,i){const r=P(n.ref);if(r===null)return i.data[0];t.spills||(t.spills=new Map),t.spills.set(e*M+s,{...r,blocked:!1,fixed:!0});const a=(l,c)=>{const u=i.rows===1?0:l,d=i.cols===1?0:c;return u>=i.rows||d>=i.cols?k.NA:i.get(u,d)};for(let l=r.r0;l<=r.r1;l++)for(let c=r.c0;c<=r.c1;c++)l===e&&c===s||this._writeArrayCell(t,l,c,a(l-r.r0,c-r.c0));this._dirtyFrom(t,r.c0,r.c1,r.r0,r.r1);const o=a(e-r.r0,s-r.c0);return o===null?0:o}_spill(t,e,s,n,i){const r=e*M+s;t.spills||(t.spills=new Map);const a=t.spills.get(r),o=e+i.rows-1,l=s+i.cols-1,c={r0:e,c0:s,r1:o,c1:l,blocked:!1,fixed:!1},u=(f,h)=>a&&f>=a.r0&&f<=a.r1&&h>=a.c0&&h<=a.c1;let d=o>=J||l>=M;if(!d)t:for(let f=e;f<=o;f++)for(let h=s;h<=l;h++){if(f===e&&h===s)continue;const y=t.kind(f,h);if((y&ot)!==0&&!(y&H&&u(f,h))){d=!0;break t}if(t.merges.length>0&&t.mergeAt(f,h)){d=!0;break t}}if(d)return a&&!a.blocked&&this._clearSpill(t,a,e,s),c.blocked=!0,c.r1=Math.min(o,J-1),c.c1=Math.min(l,M-1),t.spills.set(r,c),k.SPILL;if(a&&!a.blocked){for(let f=a.r0;f<=a.r1;f++)for(let h=a.c0;h<=a.c1;h++)f>=c.r0&&f<=c.r1&&h>=c.c0&&h<=c.c1||(t.kind(f,h)&H)!==0&&t.setCell(f,h,Q,0);this._dirtyFrom(t,a.c0,a.c1,a.r0,a.r1)}t.spills.set(r,c);for(let f=e;f<=o;f++)for(let h=s;h<=l;h++)f===e&&h===s||this._writeArrayCell(t,f,h,i.get(f-e,h-s));n.t="array",n.ref=`${ut(s)}${e+1}:${ut(l)}${o+1}`,n.cm=1,delete n.raw,this._dirtyFrom(t,s,l,e,o);const p=i.data[0];return p===null?0:p}_clearSpill(t,e,s,n){for(let i=e.r0;i<=e.r1;i++)for(let r=e.c0;r<=e.c1;r++)i===s&&r===n||(t.kind(i,r)&H)!==0&&t.setCell(i,r,Q,0);this._dirtyFrom(t,e.c0,e.c1,e.r0,e.r1)}_releaseSpill(t,e,s){const n=e*M+s,i=t.spills.get(n);if(i===void 0)return;i.blocked||this._clearSpill(t,i,e,s),t.spills.delete(n);const r=t.formula(e,s);r&&r.typed&&(delete r.ref,delete r.cm,delete r.t)}spillMaster(t,e,s){if(!t.spills)return null;for(const[n,i]of t.spills)if(!i.blocked&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1){const r=Math.floor(n/M);return{row:r,col:n-r*M,rect:i}}return null}spillRange(t){const{sheet:e,r0:s,c0:n}=t;this.read(e,s,n);const i=e.spills?.get(s*M+n);return!i||i.blocked?k.REF:new q(e,i.r0,i.c0,i.r1,i.c1)}read(t,e,s){const n=t.columns[s];if(n===void 0)return null;const i=n[e>>>E];if(i===void 0)return null;const r=e&T;let a=i.kinds[r];if(a===0)return null;switch(a&w&&(this._calc(t,e,s),a=i.kinds[r]),a&V){case U:return i.values[r];case B:return this.book.strings.get(i.values[r]);case G:return i.values[r]!==0;case N:{if(t.valueMeta!==null&&this.book.richValues){const o=gt(this.book,t,e,s);if(o!==null)return o}return Y[i.values[r]]??k.NA}default:return null}}refToValue(t){return t instanceof $?t.refs.length===1?this.refToValue(t.refs[0]):k.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.toArr(t)}refAuto(t,e,s){return t instanceof $?t.refs.length===1?this.refAuto(t.refs[0],e,s):k.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.legacy?this.intersect(t,e,s):this.toArr(t)}intersect(t,e,s){return t.cols===1&&e>=t.r0&&e<=t.r1?this.read(t.sheet,e,t.c0):t.rows===1&&s>=t.c0&&s<=t.c1?this.read(t.sheet,t.r0,s):k.VALUE}trim(t){const{sheet:e}=t;return{r0:t.r0,c0:t.c0,r1:Math.min(t.r1,Math.max(e.maxRow,t.r0)),c1:Math.min(t.c1,Math.max(e.maxCol,t.c0))}}toArr(t){if(t instanceof C)return t;if(t instanceof q){const{r0:e,c0:s,r1:n,c1:i}=this.trim(t),r=n-e+1,a=i-s+1,o=new Array(r*a);let l=0;for(let c=e;c<=n;c++)for(let u=s;u<=i;u++)o[l++]=this.read(t.sheet,c,u);return new C(r,a,o)}if(t instanceof $){if(t.refs.length===1)return this.toArr(t.refs[0]);throw k.VALUE}if(t instanceof x)throw t;return new C(1,1,[t])}scalar(t,e,s){return t instanceof q?t.isCell?this.read(t.sheet,t.r0,t.c0):this.intersect(t,e,s):t instanceof $?k.VALUE:t instanceof C?t.data[0]:t}scan(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);for(let r=t.c0;r<=n;r++){const a=s.columns[r];if(a!==void 0)for(let o=t.r0>>>E;o<=i>>>E;o++){const l=a[o];if(l===void 0)continue;const c=o<<E,u=Math.max(t.r0-c,0),d=Math.min(i-c,T),{kinds:p}=l;for(let f=u;f<=d;f++){if(p[f]===0)continue;const h=this.read(s,c+f,r);h!==null&&e(h,c+f,r)}}}}sumRange(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);let{sum:r,count:a}=e;for(let o=t.c0;o<=n;o++){const l=s.columns[o];if(l!==void 0)for(let c=t.r0>>>E;c<=i>>>E;c++){const u=l[c];if(u===void 0)continue;const d=c<<E,p=Math.max(t.r0-d,0),f=Math.min(i-d,T),{kinds:h,values:y}=u;for(let _=p;_<=f;_++){let g=h[_];if(g===0)continue;g&w&&(this._calc(s,d+_,o),g=h[_]);const b=g&V;if(b===U)r+=y[_],a++;else if(b===N)throw Y[y[_]]}}}e.sum=r,e.count=a}unary(t,e){if(t instanceof x)return t;if(t instanceof C)return new C(t.rows,t.cols,t.data.map(s=>{try{return s instanceof x?s:e(S(s))}catch(n){return n}}));try{return e(S(t))}catch(s){if(s instanceof x)return s;throw s}}slowBin(t,e,s){if(e instanceof C||s instanceof C)return this._binArr(t,e,s);if(e instanceof x)return e;if(s instanceof x)return s;try{return dt(t,e,s)}catch(n){if(n instanceof x)return n;throw n}}_binArr(t,e,s){const n=e instanceof C?e:null,i=s instanceof C?s:null,r=Math.max(n?n.rows:1,i?i.rows:1),a=Math.max(n?n.cols:1,i?i.cols:1),o=new Array(r*a);for(let l=0;l<r;l++)for(let c=0;c<a;c++){const u=nt(e,l,c),d=nt(s,l,c);let p;if(u instanceof x)p=u;else if(d instanceof x)p=d;else try{p=dt(t,u,d)}catch(f){p=f}o[l*a+c]=p}return new C(r,a,o)}liftArr(t,e,s){let n=1,i=1;for(const l of e)l instanceof C&&(l.rows>n&&(n=l.rows),l.cols>i&&(i=l.cols));const r=new Array(n*i),a=e.length,o=new Array(a);for(let l=0;l<n;l++)for(let c=0;c<i;c++){let u=null;for(let d=0;d<a;d++){const p=nt(e[d],l,c);o[d]=p,!s&&u===null&&p instanceof x&&(u=p)}if(u!==null){r[l*i+c]=u;continue}try{r[l*i+c]=t(...o)}catch(d){if(d instanceof x)r[l*i+c]=d;else throw d}}return new C(n,i,r)}invoke(t,e,s,n,i){if(t.native)return this._invokeNative(t.native,e,s,n,i);const r=t.frame?t.frame.slice():[],{params:a}=t;if(e.length>a.length)return k.VALUE;for(let l=0;l<a.length;l++)r[a[l]]=l<e.length?e[l]:void 0;const o=this.frame;if(this.frame=r,this.depth++,this.depth>=ht*4)return this.depth--,this.frame=o,k.NUM;try{return t.body(s,n,i)}finally{this.depth--,this.frame=o}}_invokeNative(t,e,s,n,i){if(e.length<t.min||e.length>t.max)return k.VALUE;try{if(t.kind==="raw")return t.fn(this,e,s,n,i);if(t.kind==="lazy")return t.fn(this,e.map(a=>()=>a),s,n,i);const r=e.map(a=>a instanceof q||a instanceof $?this.refToValue(a):a);if(r.some(a=>a instanceof C))return this.liftArr(t.fn,r,t.errors);if(!t.errors){for(const a of r)if(a instanceof x)return a}return t.fn(...r)}catch(r){if(r instanceof x)return r;throw r}}_nameEntry(t,e){const s=t.toUpperCase();if(e){const i=this.book.sheets.indexOf(e),r=this.names.get(`${i}!${s}`);if(r)return{key:`${i}!${s}`,entry:r}}const n=this.names.get(s);return n?{key:s,entry:n}:null}_nameTemplate(t,e){const s=this._nameEntry(t,e);if(s===null)return null;let n=this.nameTemplates.get(s.key);if(n===void 0){try{n=this._compile(new j(z(s.entry.text),0,0).parse())}catch(i){if(!(i instanceof W))throw i;n=this._broken()}this.nameTemplates.set(s.key,n)}return n}nameMayYieldRange(t){const e=t.toUpperCase(),s=[];for(const[n,i]of this.names)(n===e||n.endsWith(`!${e}`))&&s.push(i);if(s.length===0||(this._rangeNames??=new Set,this._rangeNames.has(e)))return!0;this._rangeNames.add(e);try{return s.some(n=>{try{return new lt(this).mayYieldRange(new j(z(n.text),0,0).parse())}catch(i){if(i instanceof W)return!1;throw i}})}finally{this._rangeNames.delete(e)}}evalName(t,e,s,n){const i=this._nameTemplate(t,n);return i===null?k.NAME:i.fn(e,s,n)}tableSpecToA1(t,e,s){const n=mt(t,e,s);if(!(n instanceof q))return null;const i=/#This Row|^\[\s*@/i.test(e),r=(a,o)=>i?`${ct(o)}${a+1}`:`$${ct(o)}$${a+1}`;return n.isCell?r(n.r0,n.c0):`${r(n.r0,n.c0)}:${r(n.r1,n.c1)}`}resolveTable(t,e,s,n,i){let r=t?this.tables.get(t.toUpperCase()):null;if(!t){for(const a of this.tables.values())if(a.sheet===i&&s>=a.r0&&s<=a.r1&&n>=a.c0&&n<=a.c1){r=a;break}}return r?mt(r,e,s):k.REF}exactIndex(t){const e=`${t.sheet.uid}:${t.r0}:${t.c0}:${t.r1}:${t.c1}`;let s=this.lookupCache.get(e);if(s!==void 0)return s;s=new Map;const n=t.cols===1;return this.scan(t,(i,r,a)=>{const o=typeof i=="string"?`s${i.toLowerCase()}`:typeof i=="number"?i:`b${i}`;if(i instanceof x)return;const l=n?r-t.r0:a-t.c0,c=s.get(o);(c===void 0||l<c)&&s.set(o,l)}),this.lookupCache.set(e,s),s}visibilityChanged(){this._wakeReaders(this.visibilityReaders)}presentationChanged(){this._wakeLater(2)}axisHiddenChanged(){this._wakeLater(1)}axisResized(){this._wakeLater(2)}_wakeLater(t){(t===1?this.visibilityReaders:this.styleReaders).size!==0&&(this.wakePending===0&&queueMicrotask(()=>{const e=this.wakePending;this.wakePending=0,e&1&&this._wakeReaders(this.visibilityReaders),e&2&&this._wakeReaders(this.styleReaders)}),this.wakePending|=t)}_wakeReaders(t){if(!this.graphReady||t.size===0)return;let e=!1;for(const[s,n]of t)n.forEach((i,r)=>{const a=s._chunk(i,r);if(a===void 0)return;const o=i&T,l=a.kinds[o];if(!(l&R)){n.delete(i,r);return}l&w||(a.kinds[o]=l|w,this._enqueue(s,i,r)),this._dirtyFrom(s,r,r,i,i),e=!0});e&&this._schedule()}isSubtotalCell(t,e,s){if((t.kind(e,s)&R)===0)return!1;const n=t.formula(e,s),i=n?.f??n?.sf??"";return/^\s*(_xlfn\.)?(SUBTOTAL|AGGREGATE)\(/i.test(i)}displayFormula(t){return Mt(t)}}function ut(m){let t="";for(let e=m+1;e>0;e=Math.floor((e-1)/26))t=String.fromCharCode(65+(e-1)%26)+t;return t}function nt(m,t,e){if(!(m instanceof C))return m;const s=m.rows===1?0:t,n=m.cols===1?0:e;return s>=m.rows||n>=m.cols?k.NA:m.data[s*m.cols+n]}function dt(m,t,e){if((t instanceof O||e instanceof O)&&m!=="="&&m!=="<>"&&m!=="&")throw k.VALUE;switch(m){case"+":{const s=S(t),n=s+S(e);return Math.abs(n)<Math.abs(s)*pt?0:K(n)}case"-":{const s=S(t),n=s-S(e);return Math.abs(n)<Math.abs(s)*pt?0:K(n)}case"*":return K(S(t)*S(e));case"/":{const s=S(t),n=S(e);if(n===0)throw k.DIV0;return K(s/n)}case"^":{const s=S(t),n=S(e);if(s===0&&n===0)throw k.NUM;if(s===0&&n<0)throw k.DIV0;const i=_t(s,n);if(Number.isNaN(i))throw k.NUM;return K(i)}case"&":return rt(t)+rt(e);case"=":return v(t,e)===0;case"<>":return v(t,e)!==0;case"<":return v(t,e)<0;case">":return v(t,e)>0;case"<=":return v(t,e)<=0;case">=":return v(t,e)>=0;default:throw k.VALUE}}const pt=5e-16;function K(m){if(!Number.isFinite(m))throw k.NUM;return m}function mt(m,t,e){const s=yt(m,t,e);return s==="REF"?k.REF:s==="VALUE"?k.VALUE:new q(m.sheet,s.top,s.left,s.bottom,s.right)}const Lt={COUNTIF:[0],COUNTIFS:["even",0],SUMIF:[0,2],SUMIFS:[0,"odd",1],AVERAGEIF:[0,2],AVERAGEIFS:[0,"odd",1],MAXIFS:[0,"odd",1],MINIFS:[0,"odd",1],COUNTBLANK:[0],RANK:[1],"RANK.EQ":[1],"RANK.AVG":[1]};function St(m,t){for(let e=0;e<m.length;e++){const s=m[e];if(s===t||s==="odd"&&t>=m[e+1]&&t%2===1||s==="even"&&t>=m[e+1]&&t%2===0)return!0}return!1}function it(m){if(!(m===null||typeof m!="object")){if(Array.isArray(m)){for(const t of m)it(t);return}if(m.t==="call"){const t=Lt[String(m.name).replace(/^_xl(?:fn|ws)\./i,"").toUpperCase()];t&&m.args.forEach((e,s)=>{if(e?.t==="array"&&St(t,s))throw new Error(`${m.name} takes a range here`)})}for(const t of Object.values(m))t!==null&&typeof t=="object"&&it(t)}}export{Bt as Engine};
1
+ import{resolveStructuredSpec as yt}from"../slicers/structured.js";import{Arr as C,compareValues as v,ERR as k,ERR_BY_INDEX as Y,Lambda as kt,num as S,power as _t,Ref as q,RefList as $,RichValue as O,str as rt,XlError as x}from"./values.js";import{entityVm as at,richValueAt as gt}from"../cells/rich-values.js";import{Compiler as lt}from"./compile.js";import{FormulaSyntaxError as W,Parser as j,templateKey as bt,tokenize as z,toDisplayFormula as Mt}from"./parser.js";import{BOOL as G,CHUNK_BITS as E,CHUNK_MASK as T,CONTENT_MASK as ot,DIRTY as w,EMPTY as Q,EVALUATING as X,FORMULA as R,KIND_MASK as V,NUM as U,SPILL as H,STR as B,ERR as N}from"../core/sheet.js";import{colName as ct,MAX_COLS as M,MAX_ROWS as J,parseRangeRef as P}from"../core/address.js";import{CellSet as wt}from"./cell-set.js";import{isRowBelow as At}from"./fill-shape.js";import"./functions/index.js";const Z=Symbol("pending"),ht=200,Ct=4096,xt=64,tt=2147483647,D=4;class et{constructor(){this.n=0,this.data=new Int32Array(D*8)}push(t,e,s,n){if((this.n+1)*D>this.data.length){const a=new Int32Array(this.data.length*2);a.set(this.data),this.data=a}const i=this.n++*D,r=this.data;r[i]=t,r[i+1]=e,r[i+2]=s,r[i+3]=n}}function Tt(m,t){if(!m.valueMeta.has(t))return;const e=new Map(m.valueMeta);e.delete(t),m.valueMeta=e.size>0?e:null}function ft(m,t,e){if(m.valueMeta?.get(t)===e)return;const s=new Map(m.valueMeta??[]);s.set(t,e),m.valueMeta=s}function st(m,t){let e=m.get(t);return e===void 0&&(e=new wt,m.set(t,e)),e}class Rt{constructor(){this.buckets=[],this.wide=[],this.all=new et,this.allCols=[]}}class Bt{constructor(t){this.book=t,this.sheetGen=0,this.sheetMap=new Map,this.deps=new Map,this.templates=new Map,this.lastOwn={row:-2,col:-1,text:"",tpl:{cacheKey:void 0}},this.frame=null,this.depth=0,this.legacy=!1,this.pendingSheet=null,this.pendingRow=0,this.pendingCol=0,this.circular=null,this.evalStack=new Int32Array(3*256),this.evalTop=0,this.cycleLow=tt,this.iterate=null,this.cycleFound=[],this.cycleMembers=null,this.iterating=!1,this.sliceMs=10,this.syncLimit=4e3,this.externalLinks=null,this.names=new Map,this.nameTemplates=new Map,this.tables=new Map,this.volatile=new Map,this.visibilityReaders=new Map,this.styleReaders=new Map,this.wakePending=0,this.queue=new Int32Array(4096),this.qHead=0,this.qLen=0,this.sheetsByUid=new Map,this.running=!1,this.timer=0,this.manual=!1,this.graphReady=!0,this.pendingChanges=[],this.waiters=[],this.onChange=null,this.dataTables=[],this.tablesDirty=!1,this.inTables=!1,this.tablesForced=!1,this.onProgress=null,this.lookupCache=new Map,this.colRevisions=new Map,this.channel=null,this.sheetsChanged()}orderChanged(){this.sheetsChanged(),this.has3D&&this.rebuild()}sheetsChanged(){this.sheetGen++,this.sheetMap.clear(),this.sheetsByUid.clear();for(const t of this.book.sheets)this.sheetMap.set(t.name.toUpperCase(),t),this.sheetsByUid.set(t.uid,t),t.rows.watcher=this,t.cols.watcher=this}sheetByName(t){return this.sheetMap.get(t.toUpperCase())??null}externalSheet(t,e){return this.externalLinks?.sheet(t,e)??null}sheetsBetween(t,e){const{sheets:s}=this.book,n=s.findIndex(r=>r.name.toUpperCase()===t.toUpperCase()),i=s.findIndex(r=>r.name.toUpperCase()===e.toUpperCase());return n<0||i<0?null:s.slice(Math.min(n,i),Math.max(n,i)+1)}setNames(t){this.names.clear(),this.nameTemplates.clear();for(const e of t){const s=e.localSheetId!==void 0?`${e.localSheetId}!${e.name.toUpperCase()}`:e.name.toUpperCase();this.names.set(s,{text:e.text,name:e.name,hidden:e.hidden,comment:e.comment})}}setTables(t){this.tables.clear();for(const e of t)this.tables.set(e.name.toUpperCase(),e)}template(t,e,s){let n;try{n=z(t)}catch(a){if(a instanceof W)return this._broken(t);throw a}const i=bt(n,e,s);let r=this.templates.get(i);if(r===void 0){try{const a=new j(n,e,s).parse();r=this._compile(a)}catch(a){if(!(a instanceof W))throw a;r=this._broken(t)}r.cacheKey=i,this.templates.set(i,r)}return r}_ownTemplate(t,e,s){const n=this.lastOwn;let i;return n.row===e-1&&n.col===s&&this.templates.get(n.tpl.cacheKey)===n.tpl&&At(n.text,t)?i=n.tpl:i=this.template(t,e,s),n.row=e,n.col=s,n.text=t,n.tpl=i,i}_compile(t){const e=new lt(this);return{fn:e.compileTop(t),refs:e.refs,names:e.names,tables:e.tables,isVolatile:e.isVolatile,notInExcel:e.notInExcel===!0,mayArray:e.mayArray,external:e.external}}_broken(){return{invalid:!0,fn:()=>k.NAME,refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1,external:!0}}validate(t){it(new j(z(t),0,0).parse())}_templateFor(t,e,s,n){if(n.tpl!==void 0)return n.tpl;let i;return n.t==="dataTable"?i=this._dataTableTemplate():n.f!==void 0&&n.base===void 0?i=this._ownTemplate(n.f,e,s):n.f!==void 0?i=this.template(n.f,Math.floor(n.base/M),n.base%M):n.sf!==void 0?i=this.template(n.sf,Math.floor(n.base/M),n.base%M):i=this._broken(),n.tpl=i,i}_index(t){let e=this.deps.get(t);return e===void 0&&(e=new Rt,this.deps.set(t,e)),e}_addDep(t,e,s,n,i,r,a,o){const l=this._index(t),c=r.uid<<14|o;if(i-s>=xt){l.all.push(a,c,e,n),l.allCols.push(s,i);return}if(n-e>=Ct){for(let p=s;p<=i;p++){let f=l.wide[p];f===void 0&&(f=new et,l.wide[p]=f),f.push(a,c,e,n)}return}const u=e>>>E,d=n>>>E;for(let p=s;p<=i;p++){let f=l.buckets[p];f===void 0&&(f=[],l.buckets[p]=f);for(let h=u;h<=d;h++){let y=f[h];y===void 0&&(y=new et,f[h]=y),y.push(a,c,e,n)}}}register(t,e,s,n){const i=this._templateFor(t,e,s,n);if(i.external)return i;for(const r of i.refs)this._addRefDep(r,t,e,s);for(const r of i.names)this._addNameDeps(r,t,e,s);for(const r of i.tables)this._addTableDep(r,t,e,s);return i.isVolatile&&st(this.volatile,t).add(e,s),i.readsVisibility??=/SUBTOTAL|AGGREGATE|SPARK_/i.test(n.f??n.sf??""),i.readsVisibility&&st(this.visibilityReaders,t).add(e,s),i.readsStyles??=/SPARK_BLOCK/i.test(n.f??n.sf??""),i.readsStyles&&st(this.styleReaders,t).add(e,s),i}_addRefDep(t,e,s,n){const i=t.rAbs0?t.r0:s+t.r0,r=t.rAbs1?t.r1:s+t.r1,a=t.cAbs0?t.c0:n+t.c0,o=t.cAbs1?t.c1:n+t.c1,l=Math.max(0,Math.min(i,r)),c=Math.min(J-1,Math.max(i,r)),u=Math.max(0,Math.min(a,o)),d=Math.min(M-1,Math.max(a,o));if(l>c||u>d)return;if(t.sheet?.sheet2&&(t.sheet.book===null||t.sheet.book===void 0)){this.has3D=!0;for(const f of this.sheetsBetween(t.sheet.sheet,t.sheet.sheet2)??[])this._addDep(f,l,u,c,d,e,s,n);return}if(t.sheet?.book!==null&&t.sheet?.book!==void 0)return;const p=t.sheet?this.sheetByName(t.sheet.sheet):e;p&&this._addDep(p,l,u,c,d,e,s,n)}_addNameDeps(t,e,s,n){const i=this._nameTemplate(t,e);if(i!==null){for(const r of i.refs)this._addRefDep(r,e,s,n);for(const r of i.names)r.toUpperCase()!==t.toUpperCase()&&this._addNameDeps(r,e,s,n)}}_addTableDep(t,e,s,n){const i=this.resolveTable(t.name,t.spec,s,n,e);i instanceof q&&this._addDep(i.sheet,i.r0,i.c0,i.r1,i.c1,e,s,n)}rebuild(){this.has3D=!1,this.deps.clear(),this.volatile.clear(),this.visibilityReaders.clear(),this.styleReaders.clear(),this.lookupCache.clear(),this.qHead=0,this.qLen=0,this.cycleFound=[],this.cycleMembers=null,this.sheetGen++,this.buildGraph({fullCalc:!0})}buildGraph({fullCalc:t=!1,onDone:e}={}){this.graphReady=!1,this.dataTables=[],t&&(this.tablesDirty=!0);const s=this,n=this.book.sheets.map(c=>[c,c.formulas]);let i=0,r=0,a=0,o=0;const l=()=>{const c=performance.now()+s.sliceMs;let u=0;for(;i<n.length;i++,r=0,a=0,o=0){const[p,f]=n[i],{columns:h}=f;for(;r<h.length;r++,a=0,o=0){const y=h[r];if(y!==void 0)for(;a<y.length;a++,o=0){const _=y[a];if(_===void 0)continue;const{ids:g}=_,b=a<<E;for(;o<=T;o++){const L=g[o];if(L===0)continue;const A=f.infos[L],I=b+o;A.t==="dataTable"&&s.dataTables.push({sheet:p,row:I,col:r,info:A});const F=s.register(p,I,r,A);if(s._initFormula(p,I,r,A,F,t),++u%256===0&&performance.now()>c){o++,s.onProgress?.({preparing:!0}),s._later(l);return}}}}}s.graphReady=!0;const d=s.pendingChanges;s.pendingChanges=[];for(const[p,f,h,y]of d)s.cellsChanged(p,f,h,y);s._schedule(),e?.()};l()}_initFormula(t,e,s,n,i,r){const a=t._chunk(e,s);if(a===void 0)return;const o=e&T;if(n.t==="array"&&n.ref&&this._markArrayChildren(t,e,s,n),i.external)return;const l=a.kinds[o];(r||i.isVolatile||(l&V)===Q||i.notInExcel&&(l&V)===N)&&(a.kinds[o]=l|w,this._enqueue(t,e,s))}_markArrayChildren(t,e,s,n){const i=P(n.ref);if(i!==null){t.spills||(t.spills=new Map),t.spills.set(e*M+s,{...i,blocked:!1,fixed:!n.cm});for(let r=i.r0;r<=i.r1;r++)for(let a=i.c0;a<=i.c1;a++){if(r===e&&a===s)continue;const o=t._ensure(r,a);o.kinds[r&T]|=H}}}_enqueue(t,e,s){if(this.qLen+3>this.queue.length)if(this.qHead>this.queue.length>>>1)this.queue.copyWithin(0,this.qHead,this.qLen),this.qLen-=this.qHead,this.qHead=0;else{const n=new Int32Array(this.queue.length*2);n.set(this.queue),this.queue=n}this.queue[this.qLen++]=t.uid,this.queue[this.qLen++]=e,this.queue[this.qLen++]=s}_dirtyFrom(t,e,s,n,i){const r=[t,e,s,n,i];for(;r.length>0;){const a=r.pop(),o=r.pop(),l=r.pop(),c=r.pop(),u=r.pop(),d=this.deps.get(u);if(d===void 0)continue;const p=(y,_)=>{const g=this.sheetsByUid.get(_>>>14);if(g===void 0)return;const b=_&16383,L=g._chunk(y,b);if(L===void 0)return;const A=y&T,I=L.kinds[A];(I&R)===0||(I&w)!==0||(L.kinds[A]=I|w,this._enqueue(g,y,b),r.push(g,b,b,y,y))},f=o>>>E,h=a>>>E;for(let y=c;y<=l;y++){const _=d.buckets[y];if(_!==void 0)for(let b=f;b<=h;b++){const L=_[b];if(L===void 0)continue;const{data:A}=L,I=L.n*D;for(let F=0;F<I;F+=D)a>=A[F+2]&&o<=A[F+3]&&p(A[F],A[F+1])}const g=d.wide[y];if(g!==void 0){const{data:b}=g,L=g.n*D;for(let A=0;A<L;A+=D)a>=b[A+2]&&o<=b[A+3]&&p(b[A],b[A+1])}}if(d.all.n>0){const{data:y}=d.all;for(let _=0;_<d.all.n;_++){const g=_*D;a>=y[g+2]&&o<=y[g+3]&&l>=d.allCols[_*2]&&c<=d.allCols[_*2+1]&&p(y[g],y[g+1])}}}}cellsChanged(t,e,s,n){if(n===0)return;if(this.inTables||(this.tablesDirty=!0),!this.graphReady){this.pendingChanges.push([t,e.slice(0,n),s.slice(0,n),n]);return}this.lookupCache.clear();const i=new Map;for(let r=0;r<n;r++){const a=e[r],o=s[r],l=i.get(o);l===void 0?i.set(o,[a,a]):(a<l[0]&&(l[0]=a),a>l[1]&&(l[1]=a));const c=t._chunk(a,o);if(c===void 0)continue;const u=a&T,d=c.kinds[u];if(d&R){const p=t.formula(a,o);p&&(this.register(t,a,o,p),d&w||(c.kinds[u]=d|w,this._enqueue(t,a,o)))}t.spills&&this._spillTouched(t,a,o)}for(const[r,a]of i)this._dirtyFrom(t,r,r,a[0],a[1]);this._markVolatile(),this._schedule()}_spillTouched(t,e,s){const n=e*M+s;for(const[i,r]of t.spills){const a=Math.floor(i/M),o=i-a*M;if(i===n){(t.kind(a,o)&R)===0&&(this._clearSpill(t,r,a,o),t.spills.delete(i));continue}if(e>=r.r0&&e<=r.r1&&s>=r.c0&&s<=r.c1){const l=t._chunk(a,o);if(l===void 0)continue;const c=a&T,u=l.kinds[c];u&R&&!(u&w)&&(l.kinds[c]=u|w,this._enqueue(t,a,o),this._dirtyFrom(t,o,o,a,a))}}}_markVolatile(){for(const[t,e]of this.volatile)e.forEach((s,n)=>{const i=t._chunk(s,n);if(i===void 0)return;const r=s&T,a=i.kinds[r];if(!(a&R)){e.delete(s,n);return}a&w||(i.kinds[r]=a|w,this._enqueue(t,s,n),this._dirtyFrom(t,n,n,s,s))})}get pending(){return(this.qLen-this.qHead)/3}_later(t){if(this._next=t,typeof MessageChannel>"u"){setTimeout(()=>this._tick(),0);return}this.channel===null&&(this.channel=new MessageChannel,this.channel.port1.onmessage=()=>this._tick()),this.channel.port2.postMessage(0)}_tick(){const t=this._next;this._next=null,t?.(),this._next===null&&this.channel!==null&&(this.channel.port1.close(),this.channel=null)}_schedule(){if(this.manual||this.inTables||this.running||!this.graphReady)return;if(this.pending===0){this._finish();return}const t=this.pending;if(t<=this.syncLimit&&(this._slice(this.syncLimit===1/0?1/0:this.sliceMs),this.pending===0)){this._finish();return}this.running=!0,this._total=t;const e=()=>{this._slice(this.sliceMs),this.pending>0?(this.onProgress?.({remaining:this.pending,total:Math.max(this._total,this.pending)}),this._later(e)):(this.running=!1,this._finish())};this._later(e)}_slice(t){const e=t!==1/0;let s=e?performance.now():0;const n=s+t;let i=1,r=1;for(;this.qHead<this.qLen;){const a=this.queue[this.qHead++],o=this.queue[this.qHead++],l=this.queue[this.qHead++],c=this.sheetsByUid.get(a);if(c!==void 0&&(this._run(c,o,l),e&&--r===0)){const u=performance.now();if(u>n)break;i=u-s<.5?Math.min(i*2,16):1,r=i,s=u}}this.qHead>=this.qLen&&(this.qHead=0,this.qLen=0)}_finish(){for(;this.cycleFound.length>0;)this._iterateCycles();const t=this.tablesForced;this.tablesForced=!1,this.tablesDirty&&this.dataTables.length>0&&(!this.skipTables||t)&&(this.tablesDirty=!1,this._computeDataTables()),this.onChange?.();const e=this.waiters;this.waiters=[];for(const s of e)s()}_dataTableTemplate(){const t=this;return{fn:(s,n,i)=>t._plainValue(i,s,n),refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1}}_plainValue(t,e,s){const n=t.value(e,s);switch(t.kind(e,s)&V){case U:return n;case B:return this.book.strings.get(n);case G:return n!==0;case N:return Y[n];default:return null}}_writePlain(t,e,s,n){const i=t.kind(e,s)&R;n==null?t.setCell(e,s,i|U,0):typeof n=="number"?Number.isFinite(n)?t.setCell(e,s,i|U,n):t.setCell(e,s,i|N,k.NUM.index):typeof n=="boolean"?t.setCell(e,s,i|G,n?1:0):n instanceof x?t.setCell(e,s,i|N,n.index):t.setCell(e,s,i|B,this.book.strings.add(String(n)))}_setInputs(t,e){const s=new Uint32Array(e.length),n=new Uint32Array(e.length);e.forEach((i,r)=>{t.setCell(i.row,i.col,i.kind,i.value),s[r]=i.row,n[r]=i.col}),this.cellsChanged(t,s,n,e.length),this._slice(1/0)}evaluateWith(t,e,s){const n=e.map(({row:r,col:a})=>({row:r,col:a,kind:t.kind(r,a)&(V|R),value:t.value(r,a)})),i=this.inTables;this.inTables=!0;try{return this._setInputs(t,e.map(({row:r,col:a,text:o})=>{const l=Number(o);return o!==""&&Number.isFinite(l)?{row:r,col:a,kind:U,value:l}:{row:r,col:a,kind:B,value:this.book.strings.add(String(o))}})),s()}finally{this._setInputs(t,n),this.inTables=i}}_computeDataTables(){this.inTables=!0;const t=this.dataTables.filter(e=>e.sheet.formula(e.row,e.col)===e.info&&this.book.sheets.includes(e.sheet));this.dataTables=t;try{for(const e of t)this._computeDataTable(e)}finally{this.inTables=!1}}_computeDataTable({sheet:t,info:e}){const s=P(e.ref),n=P(e.r1??"");if(!s||!n)return;const i=e.r2?P(e.r2):null,r=e.dt2D==="1"||e.dt2D==="true",a=e.dtr==="1"||e.dtr==="true",o=(h,y)=>({kind:t.kind(h,y)&V,value:t.value(h,y)}),c=[n,i].filter(Boolean).map(h=>({row:h.r0,col:h.c0,kind:t.kind(h.r0,h.c0)&(V|R),value:t.value(h.r0,h.c0)})),u=[];for(let h=s.r0;h<=s.r1;h++)for(let y=s.c0;y<=s.c1;y++){let _,g;r?(_=[{row:n.r0,col:n.c0,...o(s.r0-1,y)},{row:i.r0,col:i.c0,...o(h,s.c0-1)}],g=[s.r0-1,s.c0-1]):a?(_=[{row:n.r0,col:n.c0,...o(s.r0-1,y)}],g=[h,s.c0-1]):(_=[{row:n.r0,col:n.c0,...o(h,s.c0-1)}],g=[s.r0-1,y]),this._setInputs(t,_);let b=this.read(t,g[0],g[1]);b instanceof C&&(b=b.data[0]),u.push(h,y,b)}this._setInputs(t,c);const d=u.length/3,p=new Uint32Array(d),f=new Uint32Array(d);for(let h=0;h<d;h++)p[h]=u[h*3],f[h]=u[h*3+1],this._writePlain(t,p[h],f[h],u[h*3+2]);this.cellsChanged(t,p,f,d),this._slice(1/0),t.revision++}dataTableAt(t,e,s){for(const n of this.dataTables){if(n.sheet!==t)continue;const i=P(n.info.ref);if(i&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1)return n}return null}calculateNow(){const{manual:t,skipTables:e}=this;this.manual=!1,this.skipTables=!1,this.tablesDirty=!0,this.tablesForced=!0,this._markVolatile(),this._markCycles(),this._schedule(),this.manual=t,this.skipTables=e}whenIdle(){return this.pending===0&&this.graphReady&&!this.running?Promise.resolve():new Promise(t=>{this.waiters.push(t),this._schedule()})}_iterateCycles(){const t=this.cycleFound;this.cycleFound=[];const e=new Map,s=(a,o,l)=>{let c=e.get(a.uid);c===void 0&&(c=new Map,e.set(a.uid,c)),c.set(o*M+l,[a,o,l])};for(let a=0;a<t.length;a+=3)s(t[a],t[a+1],t[a+2]);const n=[];for(const a of this.book.sheets){const o=e.get(a.uid);o&&n.push(...[...o.keys()].sort((l,c)=>l-c).map(l=>o.get(l)))}this.cycleMembers??=new Map;for(const a of n)this.cycleMembers.set(`${a[0].uid}:${a[1]}:${a[2]}`,a);const{count:i,delta:r}=this.iterate;for(let a=1;a<=i;a++){let o=0;for(const[l,c,u]of n){const d=l._chunk(c,u);if(d===void 0)continue;const p=c&T;if(!(d.kinds[p]&R))continue;const f=d.values[p];d.kinds[p]|=w,this.iterating=!0,this._run(l,c,u),this.iterating=!1;const h=Math.abs(d.values[p]-f);h>o&&(o=h)}if(this.onProgress?.({iteration:a,iterations:i}),o<r)break}for(const[a,o,l]of n)this._dirtyFrom(a,l,l,o,o);for(const[a,o,l]of n){const c=a._chunk(o,l);c!==void 0&&(c.kinds[o&T]&=~w)}this._slice(1/0)}_markCycles(){if(!(this.iterate===null||this.cycleMembers===null))for(const[t,e,s]of this.cycleMembers.values()){const n=t._chunk(e,s);n===void 0||!(n.kinds[e&T]&R)||(n.kinds[e&T]|=w,this._enqueue(t,e,s))}}_run(t,e,s){const n=[t,e,s];for(;n.length>0;){const i=n[n.length-1],r=n[n.length-2],a=n[n.length-3];try{this.depth=0,this.evalTop=0,this.cycleLow=tt,this._calc(a,r,i),n.length-=3}catch(o){if(o!==Z)throw o;n.push(this.pendingSheet,this.pendingRow,this.pendingCol)}}}_calc(t,e,s){const n=t._chunk(e,s);if(n===void 0)return;const i=e&T,r=n.kinds[i];if(!(r&w))return;if(r&X){this.circular={sheet:t,row:e,col:s},this.iterating||this._cycleHit(t.uid,e,s);return}if(this.depth>=ht)throw this.pendingSheet=t,this.pendingRow=e,this.pendingCol=s,Z;const a=t.formula(e,s);if(a===void 0||!(r&R)){n.kinds[i]=r&~w;return}const o=this._templateFor(t,e,s,a);if(o.external){n.kinds[i]=r&~w;return}n.kinds[i]=r|X;const l=this.evalTop;l+3>this.evalStack.length&&this._growEvalStack(),this.evalStack[l]=t.uid,this.evalStack[l+1]=e,this.evalStack[l+2]=s,this.evalTop=l+3;const c=this.cycleLow;this.cycleLow=tt;const u=this.legacy,d=this.frame,p=a.typed!==!0&&a.t!=="array";this.legacy=p,this.depth++;let f;try{f=o.fn(e,s,t)}catch(y){if(n.kinds[i]&=~X,this.depth--,this.legacy=u,this.frame=d,this.evalTop=l,this.cycleLow=c,y===Z)throw y;y instanceof x?f=y:(console.error("Formula evaluation failed",y),f=k.VALUE),this._store(t,n,i,e,s,f,a,p);return}this.depth--,this.legacy=u,this.frame=d,this.evalTop=l;const h=this.cycleLow;if(this.cycleLow=h<l&&h<c?h:c,h<=l){if(this.iterate!==null){n.kinds[i]=r&~(w|X),this.cycleFound.push(t,e,s);return}f=0}this._store(t,n,i,e,s,f,a,p)}_cycleHit(t,e,s){const n=this.evalStack;for(let i=this.evalTop-3;i>=0;i-=3)if(n[i]===t&&n[i+1]===e&&n[i+2]===s){i<this.cycleLow&&(this.cycleLow=i);return}}_growEvalStack(){const t=new Int32Array(this.evalStack.length*2);t.set(this.evalStack),this.evalStack=t}_store(t,e,s,n,i,r,a,o){let l=r;(l instanceof q||l instanceof $)&&(l=o?this.refAuto(l,n,i):this.refToValue(l)),l instanceof kt&&(l=k.CALC),l instanceof C?a.t==="array"&&!a.cm&&a.ref?l=this._fillFixedArray(t,n,i,a,l):o||l.rows===1&&l.cols===1?(l=l.data[0],t.spills&&this._releaseSpill(t,n,i)):l=this._spill(t,n,i,a,l):t.spills&&!(a.t==="array"&&!a.cm)&&this._releaseSpill(t,n,i),a.t==="array"&&!a.cm&&a.ref&&!(r instanceof C)&&(l=this._fillFixedArray(t,n,i,a,C.filled(1,1,l)));let c=R,u=0;typeof l=="number"?Number.isFinite(l)?(c|=U,u=l):(c|=N,u=k.NUM.index):typeof l=="string"?(c|=B,u=this.book.strings.add(l)):typeof l=="boolean"?(c|=G,u=l?1:0):l instanceof x?(c|=N,u=l.index):l instanceof O?(c|=N,u=k.VALUE.index):c|=U,l instanceof O?ft(t,n*M+i,at(this.book,l.index)):t.valueMeta!==null&&((e.kinds[s]&ot)!==c||e.values[s]!==u)&&!/IMAGE\(/i.test(a.f??a.sf??"")&&Tt(t,n*M+i),e.kinds[s]=c,e.values[s]=u,n>t.maxRow&&(t.maxRow=n),i>t.maxCol&&(t.maxCol=i)}_writeArrayCell(t,e,s,n){let i=H,r=0;typeof n=="number"?(i|=Number.isFinite(n)?U:N,r=Number.isFinite(n)?n:k.NUM.index):typeof n=="string"?(i|=B,r=this.book.strings.add(n)):typeof n=="boolean"?(i|=G,r=n?1:0):n instanceof x?(i|=N,r=n.index):n==null?i|=U:(i|=N,r=k.VALUE.index,n instanceof O&&ft(t,e*M+s,at(this.book,n.index))),t.setCell(e,s,i,r)}_fillFixedArray(t,e,s,n,i){const r=P(n.ref);if(r===null)return i.data[0];t.spills||(t.spills=new Map),t.spills.set(e*M+s,{...r,blocked:!1,fixed:!0});const a=(l,c)=>{const u=i.rows===1?0:l,d=i.cols===1?0:c;return u>=i.rows||d>=i.cols?k.NA:i.get(u,d)};for(let l=r.r0;l<=r.r1;l++)for(let c=r.c0;c<=r.c1;c++)l===e&&c===s||this._writeArrayCell(t,l,c,a(l-r.r0,c-r.c0));this._dirtyFrom(t,r.c0,r.c1,r.r0,r.r1);const o=a(e-r.r0,s-r.c0);return o===null?0:o}_spill(t,e,s,n,i){const r=e*M+s;t.spills||(t.spills=new Map);const a=t.spills.get(r),o=e+i.rows-1,l=s+i.cols-1,c={r0:e,c0:s,r1:o,c1:l,blocked:!1,fixed:!1},u=(f,h)=>a&&f>=a.r0&&f<=a.r1&&h>=a.c0&&h<=a.c1;let d=o>=J||l>=M;if(!d)t:for(let f=e;f<=o;f++)for(let h=s;h<=l;h++){if(f===e&&h===s)continue;const y=t.kind(f,h);if((y&ot)!==0&&!(y&H&&u(f,h))){d=!0;break t}if(t.merges.length>0&&t.mergeAt(f,h)){d=!0;break t}}if(d)return a&&!a.blocked&&this._clearSpill(t,a,e,s),c.blocked=!0,c.r1=Math.min(o,J-1),c.c1=Math.min(l,M-1),t.spills.set(r,c),k.SPILL;if(a&&!a.blocked){for(let f=a.r0;f<=a.r1;f++)for(let h=a.c0;h<=a.c1;h++)f>=c.r0&&f<=c.r1&&h>=c.c0&&h<=c.c1||(t.kind(f,h)&H)!==0&&t.setCell(f,h,Q,0);this._dirtyFrom(t,a.c0,a.c1,a.r0,a.r1)}t.spills.set(r,c);for(let f=e;f<=o;f++)for(let h=s;h<=l;h++)f===e&&h===s||this._writeArrayCell(t,f,h,i.get(f-e,h-s));n.t="array",n.ref=`${ut(s)}${e+1}:${ut(l)}${o+1}`,n.cm=1,delete n.raw,this._dirtyFrom(t,s,l,e,o);const p=i.data[0];return p===null?0:p}_clearSpill(t,e,s,n){for(let i=e.r0;i<=e.r1;i++)for(let r=e.c0;r<=e.c1;r++)i===s&&r===n||(t.kind(i,r)&H)!==0&&t.setCell(i,r,Q,0);this._dirtyFrom(t,e.c0,e.c1,e.r0,e.r1)}_releaseSpill(t,e,s){const n=e*M+s,i=t.spills.get(n);if(i===void 0)return;i.blocked||this._clearSpill(t,i,e,s),t.spills.delete(n);const r=t.formula(e,s);r&&r.typed&&(delete r.ref,delete r.cm,delete r.t)}spillMaster(t,e,s){if(!t.spills)return null;for(const[n,i]of t.spills)if(!i.blocked&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1){const r=Math.floor(n/M);return{row:r,col:n-r*M,rect:i}}return null}spillRange(t){const{sheet:e,r0:s,c0:n}=t;this.read(e,s,n);const i=e.spills?.get(s*M+n);return!i||i.blocked?k.REF:new q(e,i.r0,i.c0,i.r1,i.c1)}read(t,e,s){const n=t.columns[s];if(n===void 0)return null;const i=n[e>>>E];if(i===void 0)return null;const r=e&T;let a=i.kinds[r];if(a===0)return null;switch(a&w&&(this._calc(t,e,s),a=i.kinds[r]),a&V){case U:return i.values[r];case B:return this.book.strings.get(i.values[r]);case G:return i.values[r]!==0;case N:{if(t.valueMeta!==null&&this.book.richValues){const o=gt(this.book,t,e,s);if(o!==null)return o}return Y[i.values[r]]??k.NA}default:return null}}refToValue(t){return t instanceof $?t.refs.length===1?this.refToValue(t.refs[0]):k.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.toArr(t)}refAuto(t,e,s){return t instanceof $?t.refs.length===1?this.refAuto(t.refs[0],e,s):k.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.legacy?this.intersect(t,e,s):this.toArr(t)}intersect(t,e,s){return t.cols===1&&e>=t.r0&&e<=t.r1?this.read(t.sheet,e,t.c0):t.rows===1&&s>=t.c0&&s<=t.c1?this.read(t.sheet,t.r0,s):k.VALUE}trim(t){const{sheet:e}=t;return{r0:t.r0,c0:t.c0,r1:Math.min(t.r1,Math.max(e.maxRow,t.r0)),c1:Math.min(t.c1,Math.max(e.maxCol,t.c0))}}toArr(t){if(t instanceof C)return t;if(t instanceof q){const{r0:e,c0:s,r1:n,c1:i}=this.trim(t),r=n-e+1,a=i-s+1,o=new Array(r*a);let l=0;for(let c=e;c<=n;c++)for(let u=s;u<=i;u++)o[l++]=this.read(t.sheet,c,u);return new C(r,a,o)}if(t instanceof $){if(t.refs.length===1)return this.toArr(t.refs[0]);throw k.VALUE}if(t instanceof x)throw t;return new C(1,1,[t])}scalar(t,e,s){return t instanceof q?t.isCell?this.read(t.sheet,t.r0,t.c0):this.intersect(t,e,s):t instanceof $?k.VALUE:t instanceof C?t.data[0]:t}scan(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);for(let r=t.c0;r<=n;r++){const a=s.columns[r];if(a!==void 0)for(let o=t.r0>>>E;o<=i>>>E;o++){const l=a[o];if(l===void 0)continue;const c=o<<E,u=Math.max(t.r0-c,0),d=Math.min(i-c,T),{kinds:p}=l;for(let f=u;f<=d;f++){if(p[f]===0)continue;const h=this.read(s,c+f,r);h!==null&&e(h,c+f,r)}}}}sumRange(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);let{sum:r,count:a}=e;for(let o=t.c0;o<=n;o++){const l=s.columns[o];if(l!==void 0)for(let c=t.r0>>>E;c<=i>>>E;c++){const u=l[c];if(u===void 0)continue;const d=c<<E,p=Math.max(t.r0-d,0),f=Math.min(i-d,T),{kinds:h,values:y}=u;for(let _=p;_<=f;_++){let g=h[_];if(g===0)continue;g&w&&(this._calc(s,d+_,o),g=h[_]);const b=g&V;if(b===U)r+=y[_],a++;else if(b===N)throw Y[y[_]]}}}e.sum=r,e.count=a}unary(t,e){if(t instanceof x)return t;if(t instanceof C)return new C(t.rows,t.cols,t.data.map(s=>{try{return s instanceof x?s:e(S(s))}catch(n){return n}}));try{return e(S(t))}catch(s){if(s instanceof x)return s;throw s}}slowBin(t,e,s){if(e instanceof C||s instanceof C)return this._binArr(t,e,s);if(e instanceof x)return e;if(s instanceof x)return s;try{return dt(t,e,s)}catch(n){if(n instanceof x)return n;throw n}}_binArr(t,e,s){const n=e instanceof C?e:null,i=s instanceof C?s:null,r=Math.max(n?n.rows:1,i?i.rows:1),a=Math.max(n?n.cols:1,i?i.cols:1),o=new Array(r*a);for(let l=0;l<r;l++)for(let c=0;c<a;c++){const u=nt(e,l,c),d=nt(s,l,c);let p;if(u instanceof x)p=u;else if(d instanceof x)p=d;else try{p=dt(t,u,d)}catch(f){p=f}o[l*a+c]=p}return new C(r,a,o)}liftArr(t,e,s){let n=1,i=1;for(const l of e)l instanceof C&&(l.rows>n&&(n=l.rows),l.cols>i&&(i=l.cols));const r=new Array(n*i),a=e.length,o=new Array(a);for(let l=0;l<n;l++)for(let c=0;c<i;c++){let u=null;for(let d=0;d<a;d++){const p=nt(e[d],l,c);o[d]=p,!s&&u===null&&p instanceof x&&(u=p)}if(u!==null){r[l*i+c]=u;continue}try{r[l*i+c]=t(...o)}catch(d){if(d instanceof x)r[l*i+c]=d;else throw d}}return new C(n,i,r)}invoke(t,e,s,n,i){if(t.native)return this._invokeNative(t.native,e,s,n,i);const r=t.frame?t.frame.slice():[],{params:a}=t;if(e.length>a.length)return k.VALUE;for(let l=0;l<a.length;l++)r[a[l]]=l<e.length?e[l]:void 0;const o=this.frame;if(this.frame=r,this.depth++,this.depth>=ht*4)return this.depth--,this.frame=o,k.NUM;try{return t.body(s,n,i)}finally{this.depth--,this.frame=o}}_invokeNative(t,e,s,n,i){if(e.length<t.min||e.length>t.max)return k.VALUE;try{if(t.kind==="raw")return t.fn(this,e,s,n,i);if(t.kind==="lazy")return t.fn(this,e.map(a=>()=>a),s,n,i);const r=e.map(a=>a instanceof q||a instanceof $?this.refToValue(a):a);if(r.some(a=>a instanceof C))return this.liftArr(t.fn,r,t.errors);if(!t.errors){for(const a of r)if(a instanceof x)return a}return t.fn(...r)}catch(r){if(r instanceof x)return r;throw r}}_nameEntry(t,e){const s=t.toUpperCase();if(e){const i=this.book.sheets.indexOf(e),r=this.names.get(`${i}!${s}`);if(r)return{key:`${i}!${s}`,entry:r}}const n=this.names.get(s);return n?{key:s,entry:n}:null}_nameTemplate(t,e){const s=this._nameEntry(t,e);if(s===null)return null;let n=this.nameTemplates.get(s.key);if(n===void 0){try{n=this._compile(new j(z(s.entry.text),0,0).parse())}catch(i){if(!(i instanceof W))throw i;n=this._broken()}this.nameTemplates.set(s.key,n)}return n}nameMayYieldRange(t){const e=t.toUpperCase(),s=[];for(const[n,i]of this.names)(n===e||n.endsWith(`!${e}`))&&s.push(i);if(s.length===0||(this._rangeNames??=new Set,this._rangeNames.has(e)))return!0;this._rangeNames.add(e);try{return s.some(n=>{try{return new lt(this).mayYieldRange(new j(z(n.text),0,0).parse())}catch(i){if(i instanceof W)return!1;throw i}})}finally{this._rangeNames.delete(e)}}evalName(t,e,s,n){const i=this._nameTemplate(t,n);return i===null?k.NAME:i.fn(e,s,n)}tableSpecToA1(t,e,s){const n=mt(t,e,s);if(!(n instanceof q))return null;const i=/#This Row|^\[\s*@/i.test(e),r=(a,o)=>i?`${ct(o)}${a+1}`:`$${ct(o)}$${a+1}`;return n.isCell?r(n.r0,n.c0):`${r(n.r0,n.c0)}:${r(n.r1,n.c1)}`}resolveTable(t,e,s,n,i){let r=t?this.tables.get(t.toUpperCase()):null;if(!t){for(const a of this.tables.values())if(a.sheet===i&&s>=a.r0&&s<=a.r1&&n>=a.c0&&n<=a.c1){r=a;break}}return r?mt(r,e,s):k.REF}exactIndex(t){const e=`${t.sheet.uid}:${t.r0}:${t.c0}:${t.r1}:${t.c1}`;let s=this.lookupCache.get(e);if(s!==void 0)return s;s=new Map;const n=t.cols===1;return this.scan(t,(i,r,a)=>{const o=typeof i=="string"?`s${i.toLowerCase()}`:typeof i=="number"?i:`b${i}`;if(i instanceof x)return;const l=n?r-t.r0:a-t.c0,c=s.get(o);(c===void 0||l<c)&&s.set(o,l)}),this.lookupCache.set(e,s),s}visibilityChanged(){this._wakeReaders(this.visibilityReaders)}presentationChanged(){this._wakeLater(2)}axisHiddenChanged(){this._wakeLater(1)}axisResized(){this._wakeLater(2)}_wakeLater(t){(t===1?this.visibilityReaders:this.styleReaders).size!==0&&(this.wakePending===0&&queueMicrotask(()=>{const e=this.wakePending;this.wakePending=0,e&1&&this._wakeReaders(this.visibilityReaders),e&2&&this._wakeReaders(this.styleReaders)}),this.wakePending|=t)}_wakeReaders(t){if(!this.graphReady||t.size===0)return;let e=!1;for(const[s,n]of t)n.forEach((i,r)=>{const a=s._chunk(i,r);if(a===void 0)return;const o=i&T,l=a.kinds[o];if(!(l&R)){n.delete(i,r);return}l&w||(a.kinds[o]=l|w,this._enqueue(s,i,r)),this._dirtyFrom(s,r,r,i,i),e=!0});e&&this._schedule()}isSubtotalCell(t,e,s){if((t.kind(e,s)&R)===0)return!1;const n=t.formula(e,s),i=n?.f??n?.sf??"";return/^\s*(_xlfn\.)?(SUBTOTAL|AGGREGATE)\(/i.test(i)}displayFormula(t){return Mt(t)}}function ut(m){let t="";for(let e=m+1;e>0;e=Math.floor((e-1)/26))t=String.fromCharCode(65+(e-1)%26)+t;return t}function nt(m,t,e){if(!(m instanceof C))return m;const s=m.rows===1?0:t,n=m.cols===1?0:e;return s>=m.rows||n>=m.cols?k.NA:m.data[s*m.cols+n]}function dt(m,t,e){if((t instanceof O||e instanceof O)&&m!=="="&&m!=="<>"&&m!=="&")throw k.VALUE;switch(m){case"+":{const s=S(t),n=s+S(e);return Math.abs(n)<Math.abs(s)*pt?0:K(n)}case"-":{const s=S(t),n=s-S(e);return Math.abs(n)<Math.abs(s)*pt?0:K(n)}case"*":return K(S(t)*S(e));case"/":{const s=S(t),n=S(e);if(n===0)throw k.DIV0;return K(s/n)}case"^":{const s=S(t),n=S(e);if(s===0&&n===0)throw k.NUM;if(s===0&&n<0)throw k.DIV0;const i=_t(s,n);if(Number.isNaN(i))throw k.NUM;return K(i)}case"&":return rt(t)+rt(e);case"=":return v(t,e)===0;case"<>":return v(t,e)!==0;case"<":return v(t,e)<0;case">":return v(t,e)>0;case"<=":return v(t,e)<=0;case">=":return v(t,e)>=0;default:throw k.VALUE}}const pt=5e-16;function K(m){if(!Number.isFinite(m))throw k.NUM;return m}function mt(m,t,e){const s=yt(m,t,e);return s==="REF"?k.REF:s==="VALUE"?k.VALUE:new q(m.sheet,s.top,s.left,s.bottom,s.right)}const Lt={COUNTIF:[0],COUNTIFS:["even",0],SUMIF:[0,2],SUMIFS:[0,"odd",1],AVERAGEIF:[0,2],AVERAGEIFS:[0,"odd",1],MAXIFS:[0,"odd",1],MINIFS:[0,"odd",1],COUNTBLANK:[0],RANK:[1],"RANK.EQ":[1],"RANK.AVG":[1]};function St(m,t){for(let e=0;e<m.length;e++){const s=m[e];if(s===t||s==="odd"&&t>=m[e+1]&&t%2===1||s==="even"&&t>=m[e+1]&&t%2===0)return!0}return!1}function it(m){if(!(m===null||typeof m!="object")){if(Array.isArray(m)){for(const t of m)it(t);return}if(m.t==="call"){const t=Lt[String(m.name).replace(/^_xl(?:fn|ws)\./i,"").toUpperCase()];t&&m.args.forEach((e,s)=>{if(e?.t==="array"&&St(t,s))throw new Error(`${m.name} takes a range here`)})}for(const t of Object.values(m))t!==null&&typeof t=="object"&&it(t)}}export{Bt as Engine};
@@ -1 +1 @@
1
- import{setCategory as j}from"./registry.js";import{lift as D,raw as m}from"./registry.js";import{Arr as p,bool as V,compareValues as H,ERR as d,num as E,OMITTED as C,Ref as U,str as K,XlError as R}from"../values.js";j("Lookup & Reference");const L=o=>o===void 0||o===C,M=(o,r,s,e,t)=>L(r)?t:Math.trunc(E(o.scalar(r,s,e))),N=(o,r,s,e,t)=>L(r)?t:V(o.scalar(r,s,e)),O=o=>Array.from({length:o.rows},(r,s)=>o.data.slice(s*o.cols,(s+1)*o.cols)),T=o=>Array.from({length:o.cols},(r,s)=>Array.from({length:o.rows},(e,t)=>o.get(t,s))),g=o=>o===null?0:o;D("SEQUENCE",1,4,(o,r,s,e)=>{const t=Math.trunc(E(o)),n=r===void 0||r===C?1:Math.trunc(E(r)),c=s===void 0||s===C?1:E(s),a=e===void 0||e===C?1:E(e);if(t<0||n<0)throw d.VALUE;if(t===0||n===0)throw d.CALC;if(t*n>1<<27)throw d.NUM;const i=new Array(t*n);for(let l=0;l<i.length;l++)i[l]=c+l*a;return new p(t,n,i)}),D("RANDARRAY",0,5,(o,r,s,e,t)=>{const n=o===void 0||o===C?1:Math.trunc(E(o)),c=r===void 0||r===C?1:Math.trunc(E(r)),a=s===void 0||s===C?0:E(s),i=e===void 0||e===C?1:E(e),l=t===void 0||t===C?!1:V(t);if(n<0||c<0||a>i)throw d.VALUE;if(n===0||c===0)throw d.CALC;const f=new Array(n*c);for(let h=0;h<f.length;h++)f[h]=l?Math.ceil(a)+Math.floor(Math.random()*(Math.floor(i)-Math.ceil(a)+1)):a+Math.random()*(i-a);return new p(n,c,f)},{volatile:!0}),m("FILTER",2,3,(o,r,s,e)=>{const t=o.toArr(r[0]),n=o.toArr(r[1]),c=n.cols===1&&n.rows===t.rows,a=n.rows===1&&n.cols===t.cols;if(!c&&!a)throw d.VALUE;const i=n.data.map(u=>{if(u instanceof R)throw u;return u===null?!1:V(u)}),l=c?O(t).filter((u,A)=>i[A]):null,f=c?null:T(t).filter((u,A)=>i[A]);if(c?l.length===0:f.length===0){if(L(r[2]))throw d.CALC;return r[2]}if(c)return p.of2D(l.map(u=>u.map(g)));const w=new p(t.rows,f.length,new Array(t.rows*f.length));return f.forEach((u,A)=>u.forEach((y,S)=>{w.data[S*f.length+A]=g(y)})),w},{array:!0,passes:o=>o===2});function b(o,r){const s=o[0].length,e=Array.from({length:s},(t,n)=>n);return e.sort((t,n)=>{for(let c=0;c<o.length;c++){const a=o[c][t],i=o[c][n],l=a==null||a instanceof R,f=i==null||i instanceof R;if(l||f){if(l&&f)continue;return l?1:-1}const h=H(a,i);if(h!==0)return h*r[c]}return t-n}),e}m("SORT",1,4,(o,r,s,e)=>{const t=o.toArr(r[0]),n=N(o,r[3],s,e,!1),c=L(r[1])?[1]:o.toArr(r[1]).data.map(A=>Math.trunc(E(A))),a=L(r[2])?c.map(()=>1):o.toArr(r[2]).data.map(A=>E(A));if(a.length!==c.length||a.some(A=>A!==1&&A!==-1))throw d.VALUE;const i=n?T(t):O(t),l=n?t.rows:t.cols;for(const A of c)if(A<1||A>l)throw d.VALUE;const f=c.map(A=>i.map(y=>y[A-1])),w=b(f,a).map(A=>i[A]);if(!n)return p.of2D(w.map(A=>A.map(g)));const u=new Array(t.rows*t.cols);return w.forEach((A,y)=>A.forEach((S,W)=>{u[W*t.cols+y]=g(S)})),new p(t.rows,t.cols,u)},{array:!0}),m("SORTBY",2,255,(o,r,s,e)=>{const t=o.toArr(r[0]),n=[],c=[];let a=1;for(;a<r.length;){const w=o.toArr(r[a]),u=a+1<r.length&&!L(r[a+1])&&!(r[a+1]instanceof U)&&!(r[a+1]instanceof p);let A=1,y=1;if(u?(A=E(o.scalar(r[a+1],s,e)),y=2):a+1<r.length&&L(r[a+1])&&(y=2),A!==1&&A!==-1)throw d.VALUE;n.push(w),c.push(A),a+=y}const i=n[0].cols===1;for(const w of n)if(i?w.rows!==t.rows||w.cols!==1:w.cols!==t.cols||w.rows!==1)throw d.VALUE;const l=b(n.map(w=>w.data),c);if(i){const w=O(t);return p.of2D(l.map(u=>w[u].map(g)))}const f=T(t),h=new Array(t.rows*t.cols);return l.forEach((w,u)=>f[w].forEach((A,y)=>{h[y*t.cols+u]=g(A)})),new p(t.rows,t.cols,h)},{array:!0});const k=o=>o.map(r=>r===null?"\0":typeof r=="string"?`s${r.toLowerCase()}`:r instanceof R?`e${r.code}`:`${typeof r}${r}`).join("");m("UNIQUE",1,3,(o,r,s,e)=>{const t=o.toArr(r[0]),n=N(o,r[1],s,e,!1),c=N(o,r[2],s,e,!1),a=n?T(t):O(t),i=new Map;for(const w of a){const u=k(w);i.set(u,(i.get(u)??0)+1)}const l=new Set,f=[];for(const w of a){const u=k(w);(c?i.get(u)!==1:l.has(u))||(l.add(u),f.push(w))}if(f.length===0)throw d.CALC;if(!n)return p.of2D(f.map(w=>w.map(g)));const h=new Array(t.rows*f.length);return f.forEach((w,u)=>w.forEach((A,y)=>{h[y*f.length+u]=g(A)})),new p(t.rows,f.length,h)},{array:!0}),m("TRANSPOSE",1,1,(o,r)=>{const s=o.toArr(r[0]),e=new Array(s.data.length);for(let t=0;t<s.rows;t++)for(let n=0;n<s.cols;n++)e[n*s.rows+t]=g(s.get(t,n));return new p(s.cols,s.rows,e)},{array:!0});function I(o,r,s){const e=r.map(i=>o.toArr(i));if(!s){const i=Math.max(...e.map(f=>f.cols)),l=[];for(const f of e)for(let h=0;h<f.rows;h++){const w=new Array(i);for(let u=0;u<i;u++)w[u]=u<f.cols?g(f.get(h,u)):d.NA;l.push(w)}return p.of2D(l)}const t=Math.max(...e.map(i=>i.rows)),n=e.reduce((i,l)=>i+l.cols,0),c=new Array(t*n);let a=0;for(const i of e){for(let l=0;l<i.cols;l++)for(let f=0;f<t;f++)c[f*n+a+l]=f<i.rows?g(i.get(f,l)):d.NA;a+=i.cols}return new p(t,n,c)}m("VSTACK",1,254,(o,r)=>I(o,r,!1),{array:!0}),m("HSTACK",1,254,(o,r)=>I(o,r,!0),{array:!0});function P(o,r,s,e,t){const n=s-r+1,c=t-e+1,a=new Array(n*c);for(let i=0;i<n;i++)for(let l=0;l<c;l++)a[i*c+l]=g(o.get(r+i,e+l));return new p(n,c,a)}m("TAKE",2,3,(o,r,s,e)=>{const t=o.toArr(r[0]),n=M(o,r[1],s,e,t.rows),c=M(o,r[2],s,e,t.cols);if(n===0||c===0)throw d.CALC;const a=Math.min(Math.abs(n),t.rows),i=Math.min(Math.abs(c),t.cols),l=n<0?t.rows-a:0,f=c<0?t.cols-i:0;return P(t,l,l+a-1,f,f+i-1)},{array:!0}),m("DROP",2,3,(o,r,s,e)=>{const t=o.toArr(r[0]),n=M(o,r[1],s,e,0),c=M(o,r[2],s,e,0),a=t.rows-Math.abs(n),i=t.cols-Math.abs(c);if(a<=0||i<=0)throw d.CALC;const l=n>0?n:0,f=c>0?c:0;return P(t,l,l+a-1,f,f+i-1)},{array:!0}),m("EXPAND",2,4,(o,r,s,e)=>{const t=o.toArr(r[0]),n=M(o,r[1],s,e,t.rows),c=M(o,r[2],s,e,t.cols),a=L(r[3])?d.NA:o.scalar(r[3],s,e);if(n<t.rows||c<t.cols)throw d.VALUE;const i=new Array(n*c);for(let l=0;l<n;l++)for(let f=0;f<c;f++)i[l*c+f]=l<t.rows&&f<t.cols?g(t.get(l,f)):a;return new p(n,c,i)},{array:!0});function _(o,r,s,e,t){const n=o.toArr(r[0]),c=t?O(n):T(n),a=[];for(let l=1;l<r.length;l++)for(const f of o.toArr(r[l]).data){const h=Math.trunc(E(f)),w=h<0?c.length+h:h-1;if(h===0||w<0||w>=c.length)throw d.VALUE;a.push(c[w])}if(t)return p.of2D(a.map(l=>l.map(g)));const i=new Array(n.rows*a.length);return a.forEach((l,f)=>l.forEach((h,w)=>{i[w*a.length+f]=g(h)})),new p(n.rows,a.length,i)}m("CHOOSEROWS",2,255,(o,r,s,e)=>_(o,r,s,e,!0),{array:!0}),m("CHOOSECOLS",2,255,(o,r,s,e)=>_(o,r,s,e,!1),{array:!0});function $(o,r,s,e){const t=o.toArr(r[0]),n=M(o,r[1],s,e,0),c=N(o,r[2],s,e,!1);if(n<0||n>3)throw d.VALUE;const a=[],i=l=>{(n===1||n===3)&&l===null||(n===2||n===3)&&l instanceof R||a.push(g(l))};if(c)for(let l=0;l<t.cols;l++)for(let f=0;f<t.rows;f++)i(t.get(f,l));else for(const l of t.data)i(l);if(a.length===0)throw d.CALC;return a}m("TOCOL",1,3,(o,r,s,e)=>p.column($(o,r,s,e)),{array:!0}),m("TOROW",1,3,(o,r,s,e)=>p.row($(o,r,s,e)),{array:!0});function F(o,r,s,e,t){const n=o.toArr(r[0]);if(n.rows>1&&n.cols>1)throw d.VALUE;const c=M(o,r[1],s,e,0);if(c<1)throw d.NUM;const a=L(r[2])?d.NA:o.scalar(r[2],s,e),i=n.data.length,l=Math.ceil(i/c),f=t?l:c,h=t?c:l,w=new Array(f*h);for(let u=0;u<f*h;u++){const A=u<i?g(n.data[u]):a;t?w[u]=A:w[u%c*h+Math.floor(u/c)]=A}return new p(f,h,w)}m("WRAPROWS",2,3,(o,r,s,e)=>F(o,r,s,e,!0),{array:!0}),m("WRAPCOLS",2,3,(o,r,s,e)=>F(o,r,s,e,!1),{array:!0}),m("TRIMRANGE",1,3,(o,r)=>{const s=r[0];if(!(s instanceof U))return s;let{r0:e,c0:t,r1:n,c1:c}=o.trim(s);const a=(f,h)=>s.sheet.kind(f,h)!==0,i=f=>{for(let h=t;h<=c;h++)if(a(f,h))return!0;return!1},l=f=>{for(let h=e;h<=n;h++)if(a(h,f))return!0;return!1};for(;e<n&&!i(e);)e++;for(;n>e&&!i(n);)n--;for(;t<c&&!l(t);)t++;for(;c>t&&!l(c);)c--;return new U(s.sheet,e,t,n,c)},{refResult:!0}),m("ARRAYTOTEXT",1,2,(o,r,s,e)=>{const t=o.toArr(r[0]),n=M(o,r[1],s,e,0)===1,c=a=>a===null?"":typeof a=="string"?n?`"${a.replace(/"/g,'""')}"`:a:a instanceof R?a.code:K(a);return n?`{${O(t).map(a=>a.map(c).join(",")).join(";")}}`:t.data.map(c).join(", ")},{array:!0}),m("PERCENTOF",2,2,(o,r)=>{const s=t=>{let n=0;for(const c of o.toArr(t).data){if(c instanceof R)throw c;typeof c=="number"&&(n+=c)}return n},e=s(r[1]);if(e===0)throw d.DIV0;return s(r[0])/e},{array:!0}),m("SINGLE",1,1,(o,r,s,e)=>{const t=o.scalar(r[0],s,e);return t===null?0:t}),m("ANCHORARRAY",1,1,(o,r)=>r[0]instanceof U?o.spillRange(r[0]):d.REF,{refResult:!0});
1
+ import{setCategory as j}from"./registry.js";import{lift as _,raw as m}from"./registry.js";import{Arr as p,bool as D,compareValues as G,ERR as A,num as E,OMITTED as L,Ref as N,str as K,XlError as M}from"../values.js";j("Lookup & Reference");const C=r=>r===void 0||r===L,R=(r,t,s,c,o)=>C(t)?o:Math.trunc(E(r.scalar(t,s,c))),U=(r,t,s,c,o)=>C(t)?o:D(r.scalar(t,s,c)),O=r=>Array.from({length:r.rows},(t,s)=>r.data.slice(s*r.cols,(s+1)*r.cols)),T=r=>Array.from({length:r.cols},(t,s)=>Array.from({length:r.rows},(c,o)=>r.get(o,s))),g=r=>r===null?0:r;_("SEQUENCE",1,4,(r,t,s,c)=>{const o=Math.trunc(E(r)),n=t===void 0||t===L?1:Math.trunc(E(t)),e=s===void 0||s===L?1:E(s),a=c===void 0||c===L?1:E(c);if(o<0||n<0)throw A.VALUE;if(o===0||n===0)throw A.CALC;if(o*n>1<<27)throw A.NUM;const f=new Array(o*n);for(let l=0;l<f.length;l++)f[l]=e+l*a;return new p(o,n,f)}),_("RANDARRAY",0,5,(r,t,s,c,o)=>{const n=r===void 0||r===L?1:Math.trunc(E(r)),e=t===void 0||t===L?1:Math.trunc(E(t)),a=s===void 0||s===L?0:E(s),f=c===void 0||c===L?1:E(c),l=o===void 0||o===L?!1:D(o);if(n<0||e<0||a>f)throw A.VALUE;if(n===0||e===0)throw A.CALC;const i=new Array(n*e);for(let d=0;d<i.length;d++)i[d]=l?Math.ceil(a)+Math.floor(Math.random()*(Math.floor(f)-Math.ceil(a)+1)):a+Math.random()*(f-a);return new p(n,e,i)},{volatile:!0}),m("FILTER",2,3,(r,t,s,c)=>{const o=r.toArr(t[0]),n=r.toArr(t[1]),e=n.cols===1&&n.rows===o.rows,a=n.rows===1&&n.cols===o.cols;if(!e&&!a)throw A.VALUE;const f=n.data.map(u=>{if(u instanceof M)throw u;return u===null?!1:D(u)}),l=e?O(o).filter((u,h)=>f[h]):null,i=e?null:T(o).filter((u,h)=>f[h]);if(e?l.length===0:i.length===0){if(C(t[2]))throw A.CALC;return t[2]}if(e)return p.of2D(l.map(u=>u.map(g)));const w=new p(o.rows,i.length,new Array(o.rows*i.length));return i.forEach((u,h)=>u.forEach((y,V)=>{w.data[V*i.length+h]=g(y)})),w},{array:!0,passes:r=>r===2});function b(r,t){const s=r[0].length,c=Array.from({length:s},(o,n)=>n);return c.sort((o,n)=>{for(let e=0;e<r.length;e++){const a=r[e][o],f=r[e][n],l=a==null||a instanceof M,i=f==null||f instanceof M;if(l||i){if(l&&i)continue;return l?1:-1}const d=G(a,f);if(d!==0)return d*t[e]}return o-n}),c}m("SORT",1,4,(r,t,s,c)=>{const o=r.toArr(t[0]),n=U(r,t[3],s,c,!1),e=C(t[1])?[1]:r.toArr(t[1]).data.map(h=>Math.trunc(E(h))),a=C(t[2])?e.map(()=>1):r.toArr(t[2]).data.map(h=>E(h));if(a.length!==e.length||a.some(h=>h!==1&&h!==-1))throw A.VALUE;const f=n?T(o):O(o),l=n?o.rows:o.cols;for(const h of e)if(h<1||h>l)throw A.VALUE;const i=e.map(h=>f.map(y=>y[h-1])),w=b(i,a).map(h=>f[h]);if(!n)return p.of2D(w.map(h=>h.map(g)));const u=new Array(o.rows*o.cols);return w.forEach((h,y)=>h.forEach((V,W)=>{u[W*o.cols+y]=g(V)})),new p(o.rows,o.cols,u)},{array:!0}),m("SORTBY",2,255,(r,t,s,c)=>{const o=r.toArr(t[0]),n=[],e=[];let a=1;for(;a<t.length;){const w=r.toArr(t[a]),u=a+1<t.length&&!C(t[a+1])&&!(t[a+1]instanceof N)&&!(t[a+1]instanceof p);let h=1,y=1;if(u?(h=E(r.scalar(t[a+1],s,c)),y=2):a+1<t.length&&C(t[a+1])&&(y=2),h!==1&&h!==-1)throw A.VALUE;n.push(w),e.push(h),a+=y}const f=n[0].cols===1;for(const w of n)if(f?w.rows!==o.rows||w.cols!==1:w.cols!==o.cols||w.rows!==1)throw A.VALUE;const l=b(n.map(w=>w.data),e);if(f){const w=O(o);return p.of2D(l.map(u=>w[u].map(g)))}const i=T(o),d=new Array(o.rows*o.cols);return l.forEach((w,u)=>i[w].forEach((h,y)=>{d[y*o.cols+u]=g(h)})),new p(o.rows,o.cols,d)},{array:!0});const k=r=>r.map(t=>t===null?"\0":typeof t=="string"?`s${t.toLowerCase()}`:t instanceof M?`e${t.code}`:`${typeof t}${t}`).join("");m("UNIQUE",1,3,(r,t,s,c)=>{const o=r.toArr(t[0]),n=U(r,t[1],s,c,!1),e=U(r,t[2],s,c,!1),a=n?T(o):O(o),f=new Map;for(const w of a){const u=k(w);f.set(u,(f.get(u)??0)+1)}const l=new Set,i=[];for(const w of a){const u=k(w);(e?f.get(u)!==1:l.has(u))||(l.add(u),i.push(w))}if(i.length===0)throw A.CALC;if(!n)return p.of2D(i.map(w=>w.map(g)));const d=new Array(o.rows*i.length);return i.forEach((w,u)=>w.forEach((h,y)=>{d[y*i.length+u]=g(h)})),new p(o.rows,i.length,d)},{array:!0}),m("TRANSPOSE",1,1,(r,t)=>{const s=r.toArr(t[0]),c=new Array(s.data.length);for(let o=0;o<s.rows;o++)for(let n=0;n<s.cols;n++)c[n*s.rows+o]=g(s.get(o,n));return new p(s.cols,s.rows,c)},{array:!0});function I(r,t,s){const c=t.map(f=>r.toArr(f));if(!s){const f=Math.max(...c.map(i=>i.cols)),l=[];for(const i of c)for(let d=0;d<i.rows;d++){const w=new Array(f);for(let u=0;u<f;u++)w[u]=u<i.cols?g(i.get(d,u)):A.NA;l.push(w)}return p.of2D(l)}const o=Math.max(...c.map(f=>f.rows)),n=c.reduce((f,l)=>f+l.cols,0),e=new Array(o*n);let a=0;for(const f of c){for(let l=0;l<f.cols;l++)for(let i=0;i<o;i++)e[i*n+a+l]=i<f.rows?g(f.get(i,l)):A.NA;a+=f.cols}return new p(o,n,e)}m("VSTACK",1,254,(r,t)=>I(r,t,!1),{array:!0}),m("HSTACK",1,254,(r,t)=>I(r,t,!0),{array:!0});function H(r,t,s,c,o){const n=s-t+1,e=o-c+1,a=new Array(n*e);for(let f=0;f<n;f++)for(let l=0;l<e;l++)a[f*e+l]=g(r.get(t+f,c+l));return new p(n,e,a)}m("TAKE",2,3,(r,t,s,c)=>{const o=r.toArr(t[0]),n=R(r,t[1],s,c,o.rows),e=R(r,t[2],s,c,o.cols);if(n===0||e===0)throw A.CALC;const a=Math.min(Math.abs(n),o.rows),f=Math.min(Math.abs(e),o.cols),l=n<0?o.rows-a:0,i=e<0?o.cols-f:0;return H(o,l,l+a-1,i,i+f-1)},{array:!0}),m("DROP",2,3,(r,t,s,c)=>{const o=r.toArr(t[0]),n=R(r,t[1],s,c,0),e=R(r,t[2],s,c,0),a=o.rows-Math.abs(n),f=o.cols-Math.abs(e);if(a<=0||f<=0)throw A.CALC;const l=n>0?n:0,i=e>0?e:0;return H(o,l,l+a-1,i,i+f-1)},{array:!0}),m("EXPAND",2,4,(r,t,s,c)=>{const o=r.toArr(t[0]),n=R(r,t[1],s,c,o.rows),e=R(r,t[2],s,c,o.cols),a=C(t[3])?A.NA:r.scalar(t[3],s,c);if(n<o.rows||e<o.cols)throw A.VALUE;const f=new Array(n*e);for(let l=0;l<n;l++)for(let i=0;i<e;i++)f[l*e+i]=l<o.rows&&i<o.cols?g(o.get(l,i)):a;return new p(n,e,f)},{array:!0});function F(r,t,s,c,o){const n=r.toArr(t[0]),e=o?O(n):T(n),a=[];for(let l=1;l<t.length;l++)for(const i of r.toArr(t[l]).data){const d=Math.trunc(E(i)),w=d<0?e.length+d:d-1;if(d===0||w<0||w>=e.length)throw A.VALUE;a.push(e[w])}if(o)return p.of2D(a.map(l=>l.map(g)));const f=new Array(n.rows*a.length);return a.forEach((l,i)=>l.forEach((d,w)=>{f[w*a.length+i]=g(d)})),new p(n.rows,a.length,f)}m("CHOOSEROWS",2,255,(r,t,s,c)=>F(r,t,s,c,!0),{array:!0}),m("CHOOSECOLS",2,255,(r,t,s,c)=>F(r,t,s,c,!1),{array:!0});function P(r,t,s,c){const o=r.toArr(t[0]),n=R(r,t[1],s,c,0),e=U(r,t[2],s,c,!1);if(n<0||n>3)throw A.VALUE;const a=[],f=l=>{(n===1||n===3)&&l===null||(n===2||n===3)&&l instanceof M||a.push(g(l))};if(e)for(let l=0;l<o.cols;l++)for(let i=0;i<o.rows;i++)f(o.get(i,l));else for(const l of o.data)f(l);if(a.length===0)throw A.CALC;return a}m("TOCOL",1,3,(r,t,s,c)=>p.column(P(r,t,s,c)),{array:!0}),m("TOROW",1,3,(r,t,s,c)=>p.row(P(r,t,s,c)),{array:!0});function $(r,t,s,c,o){const n=r.toArr(t[0]);if(n.rows>1&&n.cols>1)throw A.VALUE;const e=R(r,t[1],s,c,0);if(e<1)throw A.NUM;const a=C(t[2])?A.NA:r.scalar(t[2],s,c),f=n.data.length,l=Math.ceil(f/e),i=o?l:e,d=o?e:l,w=new Array(i*d);for(let u=0;u<i*d;u++){const h=u<f?g(n.data[u]):a;o?w[u]=h:w[u%e*d+Math.floor(u/e)]=h}return new p(i,d,w)}m("WRAPROWS",2,3,(r,t,s,c)=>$(r,t,s,c,!0),{array:!0}),m("WRAPCOLS",2,3,(r,t,s,c)=>$(r,t,s,c,!1),{array:!0});function S(r,t,s,c){if(!(t instanceof N))return t;const o=r.trim(t);let{r0:n,c0:e}=t,a=s&2?o.r1:t.r1,f=c&2?o.c1:t.c1;s&2&&o.r1<n&&(a=n),c&2&&o.c1<e&&(f=e);const l=(u,h)=>t.sheet.kind(u,h)!==0,i=u=>{for(let h=e;h<=f;h++)if(l(u,h))return!0;return!1},d=u=>{for(let h=n;h<=a;h++)if(l(h,u))return!0;return!1};if(s&1)for(;n<a&&!i(n);)n++;if(s&2)for(;a>n&&!i(a);)a--;if(c&1)for(;e<f&&!d(e);)e++;if(c&2)for(;f>e&&!d(f);)f--;if(s?n===a&&!i(n):c?e===f&&!d(e):!1)throw A.REF;return new N(t.sheet,n,e,a,f)}m("TRIMRANGE",1,3,(r,t,s,c)=>{const o=n=>{const e=t[n]===void 0||t[n]===null?3:R(r,t[n],s,c,3);if(e<0||e>3)throw A.VALUE;return e};return S(r,t[0],o(1),o(2))},{refResult:!0}),m("_TRO_ALL",1,1,(r,t)=>S(r,t[0],3,3),{refResult:!0,category:"Hidden"}),m("_TRO_LEADING",1,1,(r,t)=>S(r,t[0],1,1),{refResult:!0,category:"Hidden"}),m("_TRO_TRAILING",1,1,(r,t)=>S(r,t[0],2,2),{refResult:!0,category:"Hidden"}),m("ARRAYTOTEXT",1,2,(r,t,s,c)=>{const o=r.toArr(t[0]),n=R(r,t[1],s,c,0)===1,e=a=>a===null?"":typeof a=="string"?n?`"${a.replace(/"/g,'""')}"`:a:a instanceof M?a.code:K(a);return n?`{${O(o).map(a=>a.map(e).join(",")).join(";")}}`:o.data.map(e).join(", ")},{array:!0}),m("PERCENTOF",2,2,(r,t)=>{const s=o=>{let n=0;for(const e of r.toArr(o).data){if(e instanceof M)throw e;typeof e=="number"&&(n+=e)}return n},c=s(t[1]);if(c===0)throw A.DIV0;return s(t[0])/c},{array:!0}),m("SINGLE",1,1,(r,t,s,c)=>{const o=r.scalar(t[0],s,c);return o===null?0:o}),m("ANCHORARRAY",1,1,(r,t)=>t[0]instanceof N?r.spillRange(t[0]):A.REF,{refResult:!0});
@@ -1 +1 @@
1
- import{setCategory as k}from"./registry.js";import{lazy as K,raw as E}from"./registry.js";import{Arr as p,compareValues as F,ERR as w,num as m,OMITTED as B,Ref as A,RefList as T,str as I,XlError as O}from"../values.js";import{hasWildcards as W,scalarOf as N,wildcardRegex as z}from"./helpers.js";import{colName as j,MAX_COLS as C,MAX_ROWS as _,parseRangeRef as G,sheetPrefix as P}from"../../core/address.js";import{FORMULA as Y}from"../../core/sheet.js";k("Lookup & Reference");const q=64,R=e=>e===void 0||e===B;function y(e,t){if(t instanceof O)throw t;if(t instanceof A){const r=e.trim(t),s=t.cols===1,n=t.rows===1,i=s?t.rows:n?t.cols:t.rows*t.cols;if(s)return{ref:t,length:i,usedLength:r.r1-t.r0+1,at:f=>e.read(t.sheet,t.r0+f,t.c0)};if(n)return{ref:t,length:i,usedLength:r.c1-t.c0+1,at:f=>e.read(t.sheet,t.r0,t.c0+f)};const o=e.toArr(t);return{length:o.data.length,usedLength:o.data.length,at:f=>o.data[f]}}return t instanceof p?{length:t.data.length,usedLength:t.data.length,at:r=>t.data[r]}:{length:1,usedLength:1,at:()=>t}}const U=(e,t)=>typeof e==typeof t;function V(e,t,r,s,n=!1){if(r==null&&(r=0),typeof r=="string"&&s&&W(r)){const i=z(r);if(n)for(let o=t.usedLength-1;o>=0;o--){const f=t.at(o);if(typeof f=="string"&&i.test(f))return o}else for(let o=0;o<t.usedLength;o++){const f=t.at(o);if(typeof f=="string"&&i.test(f))return o}return-1}if(!n&&t.ref&&t.usedLength>q){const i=e.exactIndex(t.ref),o=typeof r=="string"?`s${r.toLowerCase()}`:typeof r=="number"?r:`b${r}`,f=i.get(o);return f===void 0?-1:f}if(n){for(let i=t.usedLength-1;i>=0;i--){const o=t.at(i);if(o!==null&&U(o,r)&&F(o,r)===0)return i}return-1}for(let i=0;i<t.usedLength;i++){const o=t.at(i);if(o!==null&&U(o,r)&&F(o,r)===0)return i}return-1}function S(e,t){let r=0,s=e.usedLength-1,n=-1;for(;r<=s;){let i=r+s>>>1,o=i;for(;o<=s;){const f=e.at(o);if(f!==null&&U(f,t))break;o++}if(o>s){s=i-1;continue}i=o,F(e.at(i),t)<=0?(n=i,r=i+1):s=i-1}return n}function J(e,t){let r=-1;for(let s=0;s<e.usedLength;s++){const n=e.at(s);if(!(n===null||!U(n,t)))if(F(n,t)>=0)r=s;else break}return r}E("MATCH",2,3,(e,t,r,s)=>{const n=N(e,t[0],r,s),i=R(t[2])?1:m(e.scalar(t[2],r,s)),o=t[1]instanceof A&&!(t[1].rows===1||t[1].cols===1)?null:t[1];if(o===null)throw w.NA;if(o instanceof p&&o.rows>1&&o.cols>1)throw w.NA;const f=y(e,o);let c;if(i===0?c=V(e,f,n,!0):i>0?c=S(f,n===null?0:n):c=J(f,n===null?0:n),c<0)throw w.NA;return c+1},{array:!0});function X(e,t,r,s,n){const i=N(e,t[0],r,s);if(t[1]instanceof O)throw t[1];const o=Math.trunc(m(e.scalar(t[2],r,s))),f=R(t[3])?!0:!!m(e.scalar(t[3],r,s));if(o<1)throw w.VALUE;const c=t[1],h=i===null?0:i;let a,l;if(c instanceof A)if(n){if(o>c.cols)throw w.REF;a=y(e,new A(c.sheet,c.r0,c.c0,c.r1,c.c0)),l=g=>e.read(c.sheet,c.r0+g,c.c0+o-1)}else{if(o>c.rows)throw w.REF;a=y(e,new A(c.sheet,c.r0,c.c0,c.r0,c.c1)),l=g=>e.read(c.sheet,c.r0+o-1,c.c0+g)}else{const g=e.toArr(c),b=n?g.rows:g.cols;if(o>(n?g.cols:g.rows))throw w.REF;a={length:b,usedLength:b,at:L=>n?g.get(L,0):g.get(0,L)},l=L=>n?g.get(L,o-1):g.get(o-1,L)}const u=f?S(a,h):V(e,a,h,!0);if(u<0)throw w.NA;const d=l(u);return d===null?0:d}E("VLOOKUP",3,4,(e,t,r,s)=>X(e,t,r,s,!0),{array:!0}),E("HLOOKUP",3,4,(e,t,r,s)=>X(e,t,r,s,!1),{array:!0}),E("LOOKUP",2,3,(e,t,r,s)=>{const n=N(e,t[0],r,s),i=n===null?0:n;let o=t[1],f=R(t[2])?null:t[2];if(f===null){const l=e.toArr(o);l.rows>=l.cols?(o=new p(l.rows,1,Array.from({length:l.rows},(u,d)=>l.get(d,0))),f=new p(l.rows,1,Array.from({length:l.rows},(u,d)=>l.get(d,l.cols-1)))):(o=new p(1,l.cols,Array.from({length:l.cols},(u,d)=>l.get(0,d))),f=new p(1,l.cols,Array.from({length:l.cols},(u,d)=>l.get(l.rows-1,d))))}const c=y(e,o),h=S(c,i);if(h<0)throw w.NA;const a=y(e,f).at(h);return a===null?0:a},{array:!0});function H(e,t,r,s,n){const i=r===null?0:r;if(n===2||n===-2){const a=n===2;let l=0,u=t.usedLength-1,d=-1,g=-1,b=-1;for(;l<=u;){const L=l+u>>>1,M=F(t.at(L),i);if(M===0){d=L;break}(a?M<0:M>0)?(a?g=L:b=L,l=L+1):(a?b=L:g=L,u=L-1)}return d>=0?d:s===-1?g:s===1?b:-1}const o=n===-1;if(s===0)return V(e,t,i,!1,o);if(s===2)return V(e,t,i,!0,o);let f=-1,c=null;const h=t.usedLength;for(let a=0;a<h;a++){const l=o?h-1-a:a,u=t.at(l);if(u===null||!U(u,i))continue;const d=F(u,i);if(d===0)return l;(s===-1&&d<0&&(f<0||F(u,c)>0)||s===1&&d>0&&(f<0||F(u,c)<0))&&(f=l,c=u)}return f}E("XMATCH",2,4,(e,t,r,s)=>{const n=N(e,t[0],r,s),i=R(t[2])?0:Math.trunc(m(e.scalar(t[2],r,s))),o=R(t[3])?1:Math.trunc(m(e.scalar(t[3],r,s)));if(![0,-1,1,2].includes(i)||![1,-1,2,-2].includes(o))throw w.VALUE;const f=H(e,y(e,t[1]),n,i,o);if(f<0)throw w.NA;return f+1},{array:!0}),E("XLOOKUP",3,6,(e,t,r,s)=>{const n=N(e,t[0],r,s),i=R(t[4])?0:Math.trunc(m(e.scalar(t[4],r,s))),o=R(t[5])?1:Math.trunc(m(e.scalar(t[5],r,s)));if(![0,-1,1,2].includes(i)||![1,-1,2,-2].includes(o))throw w.VALUE;if(t[1]instanceof O)throw t[1];const f=t[1]instanceof A?t[1].rows:e.toArr(t[1]).rows,c=t[1]instanceof A?t[1].cols:e.toArr(t[1]).cols;if(f>1&&c>1)throw w.VALUE;const h=H(e,y(e,t[1]),n,i,o);if(h<0){if(R(t[3]))throw w.NA;return t[3]}const a=c===1,l=t[2];if(l instanceof A)return a?new A(l.sheet,l.r0+h,l.c0,l.r0+h,l.c1):new A(l.sheet,l.r0,l.c0+h,l.r1,l.c0+h);const u=e.toArr(l);return a?u.cols===1?u.get(h,0):new p(1,u.cols,u.data.slice(h*u.cols,(h+1)*u.cols)):u.rows===1?u.get(0,h):new p(u.rows,1,Array.from({length:u.rows},(d,g)=>u.get(g,h)))},{array:!0,refResult:!0}),E("INDEX",2,4,(e,t,r,s)=>{let n=t[0];if(n instanceof O)throw n;const i=R(t[1])?0:Math.trunc(m(e.scalar(t[1],r,s))),o=R(t[2])?0:Math.trunc(m(e.scalar(t[2],r,s)));if(n instanceof T){const a=R(t[3])?1:Math.trunc(m(e.scalar(t[3],r,s)));if(a<1||a>n.refs.length)throw w.REF;n=n.refs[a-1]}if(i<0||o<0)throw w.VALUE;if(n instanceof A){let a=i,l=o;if((t.length===2||R(t[2]))&&n.rows===1&&n.cols>1&&(l=a,a=0),a>n.rows||l>n.cols)throw w.REF;const u=a===0?n.r0:n.r0+a-1,d=a===0?n.r1:u,g=l===0?n.c0:n.c0+l-1,b=l===0?n.c1:g;return new A(n.sheet,u,g,d,b)}const f=e.toArr(n);let c=i,h=o;if(t.length===2&&f.rows===1&&(h=c,c=0,h===0))return f;if(t.length===2&&f.cols===1&&(h=1),c>f.rows||h>f.cols)throw w.REF;return c===0&&h===0?f:c===0?new p(f.rows,1,Array.from({length:f.rows},(a,l)=>f.get(l,h-1))):h===0?new p(1,f.cols,f.data.slice((c-1)*f.cols,c*f.cols)):f.get(c-1,h-1)},{array:!0,refResult:!0}),E("OFFSET",3,5,(e,t,r,s)=>{const n=t[0];if(n instanceof O)throw n;if(!(n instanceof A))throw w.VALUE;const i=Math.trunc(m(e.scalar(t[1],r,s))),o=Math.trunc(m(e.scalar(t[2],r,s))),f=R(t[3])?n.rows:Math.trunc(m(e.scalar(t[3],r,s))),c=R(t[4])?n.cols:Math.trunc(m(e.scalar(t[4],r,s)));if(f===0||c===0)throw w.REF;const h=n.r0+i+(f<0?f+1:0),a=n.c0+o+(c<0?c+1:0),l=h+Math.abs(f)-1,u=a+Math.abs(c)-1;if(h<0||a<0||l>=_||u>=C)throw w.REF;return new A(n.sheet,h,a,l,u)},{volatile:!0,refResult:!0}),E("INDIRECT",1,2,(e,t,r,s,n)=>{const i=I(N(e,t[0],r,s)).trim(),o=R(t[1])?!0:!!N(e,t[1],r,s);let f=n,c=i;const h=i.lastIndexOf("!");if(h>=0){if(f=e.sheetByName(i.slice(0,h).replace(/^'|'$/g,"").replace(/''/g,"'")),f===null)throw w.REF;c=i.slice(h+1)}if(!o){const u=/^R(\[-?\d+\]|\d+)?C(\[-?\d+\]|\d+)?(?::R(\[-?\d+\]|\d+)?C(\[-?\d+\]|\d+)?)?$/i.exec(c);if(!u)throw w.REF;const d=($,D)=>$===void 0?D:$[0]==="["?D+Number($.slice(1,-1)):Number($)-1,g=d(u[1],r),b=d(u[2],s),L=u[3]===void 0&&u[4]===void 0?g:d(u[3],r),M=u[3]===void 0&&u[4]===void 0?b:d(u[4],s);if(g<0||b<0||L>=_||M>=C)throw w.REF;return new A(f,Math.min(g,L),Math.min(b,M),Math.max(g,L),Math.max(b,M))}const a=G(c.replace(/\$/g,""));if(a!==null)return new A(f,a.r0,a.c0,a.r1,a.c1);const l=e.evalName(c,r,s,f);if(l instanceof A)return l;throw w.REF},{volatile:!0,refResult:!0}),E("ROW",0,1,(e,t,r)=>{if(t.length===0||R(t[0]))return r+1;const s=t[0];if(s instanceof O)throw s;if(!(s instanceof A))throw w.VALUE;return s.rows===1?s.r0+1:new p(s.rows,1,Array.from({length:s.rows},(n,i)=>s.r0+i+1))}),E("COLUMN",0,1,(e,t,r,s)=>{if(t.length===0||R(t[0]))return s+1;const n=t[0];if(n instanceof O)throw n;if(!(n instanceof A))throw w.VALUE;return n.cols===1?n.c0+1:new p(1,n.cols,Array.from({length:n.cols},(i,o)=>n.c0+o+1))}),E("ROWS",1,1,(e,t)=>{const r=t[0];if(r instanceof O)throw r;if(r instanceof A||r instanceof p)return r.rows;if(r instanceof T)throw w.REF;return 1}),E("COLUMNS",1,1,(e,t)=>{const r=t[0];if(r instanceof O)throw r;if(r instanceof A||r instanceof p)return r.cols;if(r instanceof T)throw w.REF;return 1}),E("AREAS",1,1,(e,t)=>{if(t[0]instanceof O)throw t[0];if(t[0]instanceof T)return t[0].refs.length;if(t[0]instanceof A)return 1;throw w.VALUE}),E("ADDRESS",2,5,(e,t,r,s)=>{const n=Math.trunc(m(e.scalar(t[0],r,s))),i=Math.trunc(m(e.scalar(t[1],r,s))),o=R(t[2])?1:Math.trunc(m(e.scalar(t[2],r,s))),f=R(t[3])?!0:!!e.scalar(t[3],r,s),c=R(t[4])?null:I(e.scalar(t[4],r,s));if(n<1||i<1||n>_||i>C||o<1||o>4)throw w.VALUE;const h=o===1||o===2,a=o===1||o===3,l=f?`${a?"$":""}${j(i-1)}${h?"$":""}${n}`:`R${h?n:`[${n}]`}C${a?i:`[${i}]`}`;if(c===null)return l;if(c==="")return`!${l}`;const u=/^\[([^\]]*)\](.*)$/.exec(c);return`${u?P(u[2],{book:u[1]}):P(c)}${l}`}),K("CHOOSE",2,255,(e,t,r,s,n)=>{const i=e.scalar(t[0](r,s,n),r,s);if(i instanceof O)throw i;const o=Math.trunc(m(i));if(o<1||o>=t.length)throw w.VALUE;return t[o](r,s,n)},{passes:e=>e>0}),E("FORMULATEXT",1,1,(e,t)=>{const r=t[0];if(!(r instanceof A))throw w.NA;if((r.sheet.kind(r.r0,r.c0)&Y)===0)throw w.NA;if(r.sheet.protection&&e.book.styles.get(r.sheet.style(r.r0,r.c0)).hiddenFormula)throw w.NA;return e.book.editText(r.sheet,r.r0,r.c0)}),E("HYPERLINK",1,2,(e,t,r,s)=>{const n=R(t[1])?t[0]:t[1],i=e.scalar(n,r,s);return i===null?0:i}),E("GETPIVOTDATA",2,255,()=>{throw w.REF});
1
+ import{setCategory as H}from"./registry.js";import{lazy as K,raw as E}from"./registry.js";import{Arr as p,compareValues as F,ERR as w,num as m,OMITTED as B,Ref as A,RefList as T,str as I,XlError as O}from"../values.js";import{hasWildcards as W,scalarOf as y,wildcardRegex as j}from"./helpers.js";import{colName as z,MAX_COLS as C,MAX_ROWS as _,parseRangeRef as G,sheetPrefix as P}from"../../core/address.js";import{FORMULA as Y}from"../../core/sheet.js";H("Lookup & Reference");const q=64,R=n=>n===void 0||n===B;function M(n,t){if(t instanceof O)throw t;if(t instanceof A){const r=n.trim(t),s=t.cols===1,e=t.rows===1,i=s?t.rows:e?t.cols:t.rows*t.cols;if(s)return{ref:t,length:i,usedLength:r.r1-t.r0+1,at:f=>n.read(t.sheet,t.r0+f,t.c0)};if(e)return{ref:t,length:i,usedLength:r.c1-t.c0+1,at:f=>n.read(t.sheet,t.r0,t.c0+f)};const o=n.toArr(t);return{length:o.data.length,usedLength:o.data.length,at:f=>o.data[f]}}return t instanceof p?{length:t.data.length,usedLength:t.data.length,at:r=>t.data[r]}:{length:1,usedLength:1,at:()=>t}}const U=(n,t)=>typeof n==typeof t;function V(n,t,r,s,e=!1){if(r==null&&(r=0),typeof r=="string"&&s&&W(r)){const i=j(r);if(e)for(let o=t.usedLength-1;o>=0;o--){const f=t.at(o);if(typeof f=="string"&&i.test(f))return o}else for(let o=0;o<t.usedLength;o++){const f=t.at(o);if(typeof f=="string"&&i.test(f))return o}return-1}if(!e&&t.ref&&t.usedLength>q){const i=n.exactIndex(t.ref),o=typeof r=="string"?`s${r.toLowerCase()}`:typeof r=="number"?r:`b${r}`,f=i.get(o);return f===void 0?-1:f}if(e){for(let i=t.usedLength-1;i>=0;i--){const o=t.at(i);if(o!==null&&U(o,r)&&F(o,r)===0)return i}return-1}for(let i=0;i<t.usedLength;i++){const o=t.at(i);if(o!==null&&U(o,r)&&F(o,r)===0)return i}return-1}function S(n,t){let r=0,s=n.usedLength-1,e=-1;for(;r<=s;){let i=r+s>>>1,o=i;for(;o<=s;){const f=n.at(o);if(f!==null&&U(f,t))break;o++}if(o>s){s=i-1;continue}i=o,F(n.at(i),t)<=0?(e=i,r=i+1):s=i-1}return e}function J(n,t){let r=-1;for(let s=0;s<n.usedLength;s++){const e=n.at(s);if(!(e===null||!U(e,t)))if(F(e,t)>=0)r=s;else break}return r}E("MATCH",2,3,(n,t,r,s)=>{const e=y(n,t[0],r,s),i=R(t[2])?1:m(n.scalar(t[2],r,s)),o=t[1]instanceof A&&!(t[1].rows===1||t[1].cols===1)?null:t[1];if(o===null)throw w.NA;if(o instanceof p&&o.rows>1&&o.cols>1)throw w.NA;const f=M(n,o);let c;if(i===0?c=V(n,f,e,!0):i>0?c=S(f,e===null?0:e):c=J(f,e===null?0:e),c<0)throw w.NA;return c+1},{array:!0});function X(n,t,r,s,e){const i=y(n,t[0],r,s);if(t[1]instanceof O)throw t[1];const o=Math.trunc(m(n.scalar(t[2],r,s))),f=R(t[3])?!0:!!m(n.scalar(t[3],r,s));if(o<1)throw w.VALUE;const c=t[1],h=i===null?0:i;let a,l;if(c instanceof A)if(e){if(o>c.cols)throw w.REF;a=M(n,new A(c.sheet,c.r0,c.c0,c.r1,c.c0)),l=g=>n.read(c.sheet,c.r0+g,c.c0+o-1)}else{if(o>c.rows)throw w.REF;a=M(n,new A(c.sheet,c.r0,c.c0,c.r0,c.c1)),l=g=>n.read(c.sheet,c.r0+o-1,c.c0+g)}else{const g=n.toArr(c),b=e?g.rows:g.cols;if(o>(e?g.cols:g.rows))throw w.REF;a={length:b,usedLength:b,at:L=>e?g.get(L,0):g.get(0,L)},l=L=>e?g.get(L,o-1):g.get(o-1,L)}const u=f?S(a,h):V(n,a,h,!0);if(u<0)throw w.NA;const d=l(u);return d===null?0:d}E("VLOOKUP",3,4,(n,t,r,s)=>X(n,t,r,s,!0),{array:!0}),E("HLOOKUP",3,4,(n,t,r,s)=>X(n,t,r,s,!1),{array:!0}),E("LOOKUP",2,3,(n,t,r,s)=>{const e=y(n,t[0],r,s),i=e===null?0:e;let o=t[1],f=R(t[2])?null:t[2];if(f===null){const l=n.toArr(o);l.rows>=l.cols?(o=new p(l.rows,1,Array.from({length:l.rows},(u,d)=>l.get(d,0))),f=new p(l.rows,1,Array.from({length:l.rows},(u,d)=>l.get(d,l.cols-1)))):(o=new p(1,l.cols,Array.from({length:l.cols},(u,d)=>l.get(0,d))),f=new p(1,l.cols,Array.from({length:l.cols},(u,d)=>l.get(l.rows-1,d))))}const c=M(n,o),h=S(c,i);if(h<0)throw w.NA;const a=M(n,f).at(h);return a===null?0:a},{array:!0});function k(n,t,r,s,e){const i=r===null?0:r;if(e===2||e===-2){const a=e===2;let l=0,u=t.usedLength-1,d=-1,g=-1,b=-1;for(;l<=u;){const L=l+u>>>1,N=F(t.at(L),i);if(N===0){d=L;break}(a?N<0:N>0)?(a?g=L:b=L,l=L+1):(a?b=L:g=L,u=L-1)}return d>=0?d:s===-1?g:s===1?b:-1}const o=e===-1;if(s===0)return V(n,t,i,!1,o);if(s===2)return V(n,t,i,!0,o);let f=-1,c=null;const h=t.usedLength;for(let a=0;a<h;a++){const l=o?h-1-a:a,u=t.at(l);if(u===null||!U(u,i))continue;const d=F(u,i);if(d===0)return l;(s===-1&&d<0&&(f<0||F(u,c)>0)||s===1&&d>0&&(f<0||F(u,c)<0))&&(f=l,c=u)}return f}function Q(n,t){const r=n.length;for(let s=0;s<r;s++){const e=t<0?r-1-s:s;if(n.at(e)===null)return e}return-1}E("XMATCH",2,4,(n,t,r,s)=>{const e=y(n,t[0],r,s),i=R(t[2])?0:Math.trunc(m(n.scalar(t[2],r,s))),o=R(t[3])?1:Math.trunc(m(n.scalar(t[3],r,s)));if(![0,-1,1,2].includes(i)||![1,-1,2,-2].includes(o))throw w.VALUE;const f=k(n,M(n,t[1]),e,i,o);if(f<0)throw w.NA;return f+1},{array:!0}),E("XLOOKUP",3,6,(n,t,r,s)=>{const e=y(n,t[0],r,s),i=R(t[4])?0:Math.trunc(m(n.scalar(t[4],r,s))),o=R(t[5])?1:Math.trunc(m(n.scalar(t[5],r,s)));if(![0,-1,1,2].includes(i)||![1,-1,2,-2].includes(o))throw w.VALUE;if(t[1]instanceof O)throw t[1];const f=t[1]instanceof A?t[1].rows:n.toArr(t[1]).rows,c=t[1]instanceof A?t[1].cols:n.toArr(t[1]).cols;if(f>1&&c>1)throw w.VALUE;const h=R(t[0])?Q(M(n,t[1]),o):k(n,M(n,t[1]),e,i,o);if(h<0){if(R(t[3]))throw w.NA;return t[3]}const a=c===1,l=t[2];if(l instanceof A)return a?new A(l.sheet,l.r0+h,l.c0,l.r0+h,l.c1):new A(l.sheet,l.r0,l.c0+h,l.r1,l.c0+h);const u=n.toArr(l);return a?u.cols===1?u.get(h,0):new p(1,u.cols,u.data.slice(h*u.cols,(h+1)*u.cols)):u.rows===1?u.get(0,h):new p(u.rows,1,Array.from({length:u.rows},(d,g)=>u.get(g,h)))},{array:!0,refResult:!0}),E("INDEX",2,4,(n,t,r,s)=>{let e=t[0];if(e instanceof O)throw e;const i=R(t[1])?0:Math.trunc(m(n.scalar(t[1],r,s))),o=R(t[2])?0:Math.trunc(m(n.scalar(t[2],r,s)));if(e instanceof T){const a=R(t[3])?1:Math.trunc(m(n.scalar(t[3],r,s)));if(a<1||a>e.refs.length)throw w.REF;e=e.refs[a-1]}if(i<0||o<0)throw w.VALUE;if(e instanceof A){let a=i,l=o;if((t.length===2||R(t[2]))&&e.rows===1&&e.cols>1&&(l=a,a=0),a>e.rows||l>e.cols)throw w.REF;const u=a===0?e.r0:e.r0+a-1,d=a===0?e.r1:u,g=l===0?e.c0:e.c0+l-1,b=l===0?e.c1:g;return new A(e.sheet,u,g,d,b)}const f=n.toArr(e);let c=i,h=o;if(t.length===2&&f.rows===1&&(h=c,c=0,h===0))return f;if(t.length===2&&f.cols===1&&(h=1),c>f.rows||h>f.cols)throw w.REF;return c===0&&h===0?f:c===0?new p(f.rows,1,Array.from({length:f.rows},(a,l)=>f.get(l,h-1))):h===0?new p(1,f.cols,f.data.slice((c-1)*f.cols,c*f.cols)):f.get(c-1,h-1)},{array:!0,refResult:!0}),E("OFFSET",3,5,(n,t,r,s)=>{const e=t[0];if(e instanceof O)throw e;if(!(e instanceof A))throw w.VALUE;const i=Math.trunc(m(n.scalar(t[1],r,s))),o=Math.trunc(m(n.scalar(t[2],r,s))),f=R(t[3])?e.rows:Math.trunc(m(n.scalar(t[3],r,s))),c=R(t[4])?e.cols:Math.trunc(m(n.scalar(t[4],r,s)));if(f===0||c===0)throw w.REF;const h=e.r0+i+(f<0?f+1:0),a=e.c0+o+(c<0?c+1:0),l=h+Math.abs(f)-1,u=a+Math.abs(c)-1;if(h<0||a<0||l>=_||u>=C)throw w.REF;return new A(e.sheet,h,a,l,u)},{volatile:!0,refResult:!0}),E("INDIRECT",1,2,(n,t,r,s,e)=>{const i=I(y(n,t[0],r,s)).trim(),o=R(t[1])?!0:!!y(n,t[1],r,s);let f=e,c=i;const h=i.lastIndexOf("!");if(h>=0){if(f=n.sheetByName(i.slice(0,h).replace(/^'|'$/g,"").replace(/''/g,"'")),f===null)throw w.REF;c=i.slice(h+1)}if(!o){const u=/^R(\[-?\d+\]|\d+)?C(\[-?\d+\]|\d+)?(?::R(\[-?\d+\]|\d+)?C(\[-?\d+\]|\d+)?)?$/i.exec(c);if(!u)throw w.REF;const d=($,D)=>$===void 0?D:$[0]==="["?D+Number($.slice(1,-1)):Number($)-1,g=d(u[1],r),b=d(u[2],s),L=u[3]===void 0&&u[4]===void 0?g:d(u[3],r),N=u[3]===void 0&&u[4]===void 0?b:d(u[4],s);if(g<0||b<0||L>=_||N>=C)throw w.REF;return new A(f,Math.min(g,L),Math.min(b,N),Math.max(g,L),Math.max(b,N))}const a=G(c.replace(/\$/g,""));if(a!==null)return new A(f,a.r0,a.c0,a.r1,a.c1);const l=n.evalName(c,r,s,f);if(l instanceof A)return l;throw w.REF},{volatile:!0,refResult:!0}),E("ROW",0,1,(n,t,r)=>{if(t.length===0||R(t[0]))return r+1;const s=t[0];if(s instanceof O)throw s;if(!(s instanceof A))throw w.VALUE;return s.rows===1?s.r0+1:new p(s.rows,1,Array.from({length:s.rows},(e,i)=>s.r0+i+1))}),E("COLUMN",0,1,(n,t,r,s)=>{if(t.length===0||R(t[0]))return s+1;const e=t[0];if(e instanceof O)throw e;if(!(e instanceof A))throw w.VALUE;return e.cols===1?e.c0+1:new p(1,e.cols,Array.from({length:e.cols},(i,o)=>e.c0+o+1))}),E("ROWS",1,1,(n,t)=>{const r=t[0];if(r instanceof O)throw r;if(r instanceof A||r instanceof p)return r.rows;if(r instanceof T)throw w.REF;return 1}),E("COLUMNS",1,1,(n,t)=>{const r=t[0];if(r instanceof O)throw r;if(r instanceof A||r instanceof p)return r.cols;if(r instanceof T)throw w.REF;return 1}),E("AREAS",1,1,(n,t)=>{if(t[0]instanceof O)throw t[0];if(t[0]instanceof T)return t[0].refs.length;if(t[0]instanceof A)return 1;throw w.VALUE}),E("ADDRESS",2,5,(n,t,r,s)=>{const e=Math.trunc(m(n.scalar(t[0],r,s))),i=Math.trunc(m(n.scalar(t[1],r,s))),o=R(t[2])?1:Math.trunc(m(n.scalar(t[2],r,s))),f=R(t[3])?!0:!!n.scalar(t[3],r,s),c=R(t[4])?null:I(n.scalar(t[4],r,s));if(e<1||i<1||e>_||i>C||o<1||o>4)throw w.VALUE;const h=o===1||o===2,a=o===1||o===3,l=f?`${a?"$":""}${z(i-1)}${h?"$":""}${e}`:`R${h?e:`[${e}]`}C${a?i:`[${i}]`}`;if(c===null)return l;if(c==="")return`!${l}`;const u=/^\[([^\]]*)\](.*)$/.exec(c);return`${u?P(u[2],{book:u[1]}):P(c)}${l}`}),K("CHOOSE",2,255,(n,t,r,s,e)=>{const i=n.scalar(t[0](r,s,e),r,s);if(i instanceof O)throw i;const o=Math.trunc(m(i));if(o<1||o>=t.length)throw w.VALUE;return t[o](r,s,e)},{passes:n=>n>0}),E("FORMULATEXT",1,1,(n,t)=>{const r=t[0];if(!(r instanceof A))throw w.NA;if((r.sheet.kind(r.r0,r.c0)&Y)===0)throw w.NA;if(r.sheet.protection&&n.book.styles.get(r.sheet.style(r.r0,r.c0)).hiddenFormula)throw w.NA;return n.book.editText(r.sheet,r.r0,r.c0)}),E("HYPERLINK",1,2,(n,t,r,s)=>{const e=R(t[1])?t[0]:t[1],i=n.scalar(e,r,s);return i===null?0:i}),E("GETPIVOTDATA",2,255,()=>{throw w.REF});
package/calc/parser.js CHANGED
@@ -1,3 +1,3 @@
1
- import{colIndex as T,MAX_COLS as A,MAX_ROWS as w,PLAIN_SHEET as $}from"../core/address.js";import{ERR_BY_CODE as v}from"./values.js";import{FUNCS as g}from"./functions/registry.js";const L=s=>g.has(s);class u extends Error{}const M=/\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6}/y,U=/(\$?)([A-Za-z]{1,3}):(\$?)([A-Za-z]{1,3})/y,F=/(\$?)([1-9][0-9]{0,6}):(\$?)([1-9][0-9]{0,6})/y,k=/(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y,b=/[A-Za-z_\\\u0080-￿][A-Za-z0-9_.\\?\u0080-￿]*/y,D=/#(?:NULL!|DIV\/0!|VALUE!|REF!|NAME\?|NUM!|N\/A|GETTING_DATA|SPILL!|CALC!|BUSY!|CONNECT!|BLOCKED!|FIELD!|UNKNOWN!)/iy,R=/^(?:_xlfn\._xlws\.|_xlfn\.|_xlws\.|_xlpm\.|_xludf\.|_xleta\.)/i,I=s=>s!==void 0&&/[A-Za-z0-9_.\u0080-￿]/.test(s);function f(s,e,t){return s.lastIndex=t,s.exec(e)}function S(s){const e=[];let t=0;const i=s.length,o=(l,c,n,r)=>e.push({t:l,v:c,s:n,e:r});for(;t<i;){const l=s[t];if(l===" "||l===`
2
- `||l==="\r"||l===" "){const n=t;for(;t<i&&(s[t]===" "||s[t]===`
3
- `||s[t]==="\r"||s[t]===" ");)t++;o("ws",null,n,t);continue}if(l==='"'){const n=t;let r="";for(t++;;){if(t>=i)throw new u("Unterminated string");if(s[t]==='"'){if(s[t+1]==='"'){r+='"',t+=2;continue}t++;break}r+=s[t++]}o("str",r,n,t);continue}if(l==="'"||l==="["){const n=N(s,t);if(n){o("sheet",n.value,t,n.end),t=n.end;continue}if(l==="["){const r=p(s,t);o("table",{name:null,spec:s.slice(t,r)},t,r),t=r;continue}throw new u("Unexpected quote")}if(l==="#"){const n=f(D,s,t);n?(o("err",v.get(n[0].toUpperCase()),t,t+n[0].length),t+=n[0].length):(o("op","#",t,t+1),t++);continue}if(l>="0"&&l<="9"||l==="."||l==="$"||/[A-Za-z_\\\u0080-￿]/.test(l)){let n=f(F,s,t);if(n&&!I(s[t+n[0].length])){o("rows",{a0:n[1]==="$",r0:Number(n[2])-1,a1:n[3]==="$",r1:Number(n[4])-1},t,t+n[0].length),t+=n[0].length;continue}if(n=f(U,s,t),n&&!I(s[t+n[0].length])&&s[t+n[0].length]!=="("&&s[t+n[0].length]!=="!"){const r=T(n[2]),h=T(n[4]);if(r<A&&h<A){o("cols",{a0:n[1]==="$",c0:r,a1:n[3]==="$",c1:h},t,t+n[0].length),t+=n[0].length;continue}}if(n=f(M,s,t),n){const r=s[t+n[0].length];if(!I(r)&&r!=="("&&r!=="!"&&r!=="["){const h=E(n[0]);if(h){o("cell",h,t,t+n[0].length),t+=n[0].length;continue}}else if(r==="."&&l==="$"){const h=f(/[A-Za-z0-9_.\\?\u0080-￿]*/y,s,t+n[0].length),a=t+n[0].length+h[0].length;o(s[a]==="["?"table":"name",s[a]==="["?{name:s.slice(t,a),spec:s.slice(a,p(s,a))}:s.slice(t,a),t,s[a]==="["?p(s,a):a),t=e[e.length-1].e;continue}}if(l>="0"&&l<="9"||l==="."){if(n=f(k,s,t),!n)throw new u("Bad number");o("num",Number(n[0]),t,t+n[0].length),t+=n[0].length;continue}if(n=f(b,s,t),n){const r=t+n[0].length,h=s[r];if(h==="!"||h===":"&&_(s,r)){const a=N(s,t);if(a){o("sheet",a.value,t,a.end),t=a.end;continue}}if(h==="(")o("func",n[0].replace(R,"").toUpperCase(),t,r);else if(h==="["){const a=p(s,r);o("table",{name:n[0],spec:s.slice(r,a)},t,a),t=a;continue}else o("name",n[0].replace(R,""),t,r);t=r;continue}}const c=s.slice(t,t+2);if(c==="<="||c===">="||c==="<>"){o("op",c,t,t+2),t+=2;continue}if("+-*/^&=<>%(),;:{}@".includes(l)){o("op",l,t,t+1),t++;continue}throw new u(`Unexpected character ${l}`)}return e}function _(s,e){return/^:'?[^'!:]+'?!/.exec(s.slice(e,e+64))!==null}function p(s,e){let t=0;for(let i=e;i<s.length;i++){if(s[i]==="'"&&s[i+1]!==void 0){i++;continue}if(s[i]==="[")t++;else if(s[i]==="]"&&(t--,t===0))return i+1}throw new u("Unterminated [")}function N(s,e){let t=e,i=null;const o=()=>{if(s[t]==="'"){let h="";for(t++;;){if(t>=s.length)return null;if(s[t]==="'"){if(s[t+1]==="'"){h+="'",t+=2;continue}return t++,h}h+=s[t++]}}const r=t;for(;t<s.length&&!'!:,()+-*/^&=<>%{}; "'.includes(s[t]);)t++;return t>r?s.slice(r,t):null};if(s[t]==="["){const r=s.indexOf("]",t);if(r<0)return null;i=s.slice(t+1,r),t=r+1}let l=o();if(l===null)return null;const c=/\[([^\]]+)\](.*)$/.exec(l);c&&(i=c[1],l=c[2]);let n=null;return s[t]===":"&&(t++,n=o(),n===null)||s[t]!=="!"?null:(t++,{value:{book:i,sheet:l,sheet2:n},end:t})}function E(s){let e=0;const t=s[e]==="$";t&&e++;const i=e;for(;/[A-Za-z]/.test(s[e]);)e++;const o=T(s.slice(i,e)),l=s[e]==="$";l&&e++;const c=Number(s.slice(e))-1;return o>=A||c>=w?null:{r:c,c:o,rAbs:l,cAbs:t}}const P=new Set(["=","<>","<",">","<=",">="]);class Z{constructor(e,t=0,i=0){this.toks=e,this.i=0,this.baseRow=t,this.baseCol=i}peek(){return this.toks[this.i]}skipWs(){for(;this.toks[this.i]?.t==="ws";)this.i++}isOp(e){this.skipWs();const t=this.toks[this.i];return t!==void 0&&t.t==="op"&&t.v===e}eat(e){if(!this.isOp(e))throw new u(`Expected ${e}`);this.i++}parse(){const e=this.expr();if(this.skipWs(),this.i<this.toks.length)throw new u("Unexpected text after the formula");return e}expr(){return this.compare()}compare(){let e=this.concat();for(;;){this.skipWs();const t=this.peek();if(t?.t==="op"&&P.has(t.v))this.i++,e={t:"bin",op:t.v,l:e,r:this.concat()};else return e}}concat(){let e=this.add();for(;this.isOp("&");)this.i++,e={t:"bin",op:"&",l:e,r:this.add()};return e}add(){let e=this.mul();for(;;)if(this.isOp("+"))this.i++,e={t:"bin",op:"+",l:e,r:this.mul()};else if(this.isOp("-"))this.i++,e={t:"bin",op:"-",l:e,r:this.mul()};else return e}mul(){let e=this.pow();for(;;)if(this.isOp("*"))this.i++,e={t:"bin",op:"*",l:e,r:this.pow()};else if(this.isOp("/"))this.i++,e={t:"bin",op:"/",l:e,r:this.pow()};else return e}pow(){let e=this.unary();for(;this.isOp("^");)this.i++,e={t:"bin",op:"^",l:e,r:this.unary()};return e}unary(){return this.isOp("-")?(this.i++,{t:"neg",e:this.unary()}):this.isOp("+")?(this.i++,this.unary()):this.isOp("@")?(this.i++,{t:"implicit",e:this.unary()}):this.postfix()}postfix(){let e=this.refExpr();for(;;)if(this.isOp("%"))this.i++,e={t:"pct",e};else if(this.peek()?.t==="op"&&this.peek().v==="#")this.i++,e={t:"spillRef",e};else return e}refExpr(){let e=this.rangeExpr();for(;;){const t=this.i;if(this.peek()?.t==="ws"){this.skipWs();const i=this.peek();if(i&&this.startsPrimary(i)){e={t:"intersect",l:e,r:this.rangeExpr()};continue}this.i=t}return e}}startsPrimary(e){return e.t==="op"?e.v==="(":e.t==="cell"||e.t==="cols"||e.t==="rows"||e.t==="name"||e.t==="func"||e.t==="sheet"||e.t==="table"}rangeExpr(){let e=this.primary();for(;this.peek()?.t==="op"&&this.peek().v===":";){this.i++;const t=this.primary();e=C(e,t)}return e}cellNode(e,t=null){return{t:"cell",sheet:t,rAbs:e.rAbs,cAbs:e.cAbs,r:e.rAbs?e.r:e.r-this.baseRow,c:e.cAbs?e.c:e.c-this.baseCol}}rowsNode(e,t=null){return{t:"rows",sheet:t,a0:e.a0,a1:e.a1,r0:e.a0?e.r0:e.r0-this.baseRow,r1:e.a1?e.r1:e.r1-this.baseRow}}colsNode(e,t=null){return{t:"cols",sheet:t,a0:e.a0,a1:e.a1,c0:e.a0?e.c0:e.c0-this.baseCol,c1:e.a1?e.c1:e.c1-this.baseCol}}primary(){this.skipWs();const e=this.peek();if(e===void 0)throw new u("Unexpected end of formula");switch(this.i++,e.t){case"num":return{t:"lit",v:e.v};case"str":return{t:"lit",v:e.v};case"err":return{t:"lit",v:e.v};case"cell":return this.cellNode(e.v);case"rows":return this.rowsNode(e.v);case"cols":return this.colsNode(e.v);case"table":return{t:"table",name:e.v.name,spec:e.v.spec};case"sheet":{const t=this.peek();if(t===void 0)throw new u("Expected a reference");if(this.i++,t.t==="cell"){let i=this.cellNode(t.v,e.v);if(this.peek()?.t==="op"&&this.peek().v===":"&&this.toks[this.i+1]?.t==="cell"){this.i++;const o=this.toks[this.i++];i=C(i,this.cellNode(o.v,e.v))}return i}if(t.t==="rows")return this.rowsNode(t.v,e.v);if(t.t==="cols")return this.colsNode(t.v,e.v);if(t.t==="name")return{t:"name",name:t.v,sheet:e.v};if(t.t==="err")return{t:"lit",v:t.v};if(t.t==="func")return this.i--,this.primary();throw new u("Expected a reference after the sheet name")}case"name":{const t=e.v.toUpperCase();if(t==="TRUE")return{t:"lit",v:!0};if(t==="FALSE")return{t:"lit",v:!1};const i=/^\$?([A-Za-z]{1,3})\$?([1-9][0-9]{0,6})\.(.+)$/.exec(e.v),o=i?E(`$${i[1]}$${i[2]}`):null;return o?{t:"call",name:"_FV",args:[this.cellNode(o),...i[3].split(".").map(l=>({t:"lit",v:l}))]}:{t:"name",name:e.v}}case"func":return this.call(e.v);case"op":if(e.v==="("){const t=this.expr(),i=[t];for(;this.isOp(",");)this.i++,i.push(this.expr());return this.eat(")"),i.length===1?{t:"paren",e:t}:{t:"union",items:i}}if(e.v==="{")return this.arrayLiteral();throw new u(`Unexpected ${e.v}`);default:throw new u("Unexpected token")}}call(e){let t=this._callArgs(e);if((e==="_FV"||e==="FIELDVALUE")&&t.t==="call"&&t.args.length===2){const i=t.args[0];i?.t==="call"&&(i.name==="_FV"||i.name==="FIELDVALUE")&&i.args.length>=2&&(t={t:"call",name:"_FV",args:[...i.args,t.args[1]]})}if(e==="PHONETIC"&&t.t==="call"&&t.args[0]?.t==="lit")throw new u("PHONETIC needs a reference");if(e==="CALL"||e==="REGISTER.ID")throw new u(`${e} can't be used in a worksheet formula`);return t}_callArgs(e){this.eat("(");const t=[];if(this.isOp(")")){this.i++;const i={t:"call",name:e,args:t};return this.afterCall(i)}for(;;){if(this.skipWs(),this.isOp(",")||this.isOp(")")?t.push({t:"omit"}):t.push(this.expr()),this.isOp(",")){this.i++;continue}this.eat(")");break}return this.afterCall({t:"call",name:e,args:t})}afterCall(e){let t=e;for(;this.peek()?.t==="op"&&this.peek().v==="(";){this.i++;const i=[];if(this.isOp(")"))this.i++;else for(;;){if(this.skipWs(),this.isOp(",")||this.isOp(")")?i.push({t:"omit"}):i.push(this.expr()),this.isOp(",")){this.i++;continue}this.eat(")");break}t={t:"apply",fn:t,args:i}}return t}arrayLiteral(){const e=[[]];for(;;){this.skipWs();let t=!1;for(;this.isOp("-")||this.isOp("+");)this.peek().v==="-"&&(t=!t),this.i++;this.skipWs();const i=this.peek();if(i===void 0)throw new u("Unterminated array");if(this.i++,i.t==="num")e[e.length-1].push(t?-i.v:i.v);else if(i.t==="str"||i.t==="err")e[e.length-1].push(i.v);else if(i.t==="name"&&/^(true|false)$/i.test(i.v))e[e.length-1].push(i.v.toUpperCase()==="TRUE");else throw new u("Arrays can hold only constants");if(this.isOp(","))this.i++;else if(this.isOp(";"))this.i++,e.push([]);else{this.eat("}");break}}return{t:"array",rows:e}}}function C(s,e){return s.t==="cell"&&e.t==="cell"?{t:"range",sheet:s.sheet??e.sheet,a:s,b:e}:{t:"rangeOp",l:s,r:e}}function Q(s,e,t){let i="";for(let o=0;o<s.length;o++){const l=s[o];switch(l.t){case"cell":{const c=l.v;i+=`R${c.rAbs?c.r:`[${c.r-e}]`}C${c.cAbs?c.c:`[${c.c-t}]`}`;break}case"rows":{const c=l.v;i+=`R${c.a0?c.r0:`[${c.r0-e}]`}:R${c.a1?c.r1:`[${c.r1-e}]`}`;break}case"cols":{const c=l.v;i+=`C${c.a0?c.c0:`[${c.c0-t}]`}:C${c.a1?c.c1:`[${c.c1-t}]`}`;break}case"num":case"func":i+=`${l.t==="num"?"":"~"}${l.v}`;break;case"op":i+=l.v;break;case"ws":i+=" ";break;case"str":i+=JSON.stringify(l.v);break;case"name":i+=`${l.v}`;break;case"err":i+=l.v.code;break;default:i+=`${JSON.stringify(l.v)}`}}return i}const V=new Set(["FILTER","SORT","PY"]),B=new Set("DETECTLANGUAGE ENCODEURL STOCKHISTORY TRANSLATE ACOT ACOTH AGGREGATE ARABIC ARRAYTOTEXT ANCHORARRAY BASE BETA.DIST BETA.INV BINOM.DIST BINOM.DIST.RANGE BINOM.INV BITAND BITLSHIFT BITOR BITRSHIFT BITXOR BYCOL BYROW CEILING.MATH CEILING.PRECISE CHISQ.DIST CHISQ.DIST.RT CHISQ.INV CHISQ.INV.RT CHISQ.TEST CHOOSECOLS CHOOSEROWS COMBINA CONCAT CONFIDENCE.NORM CONFIDENCE.T COT COTH COVARIANCE.P COVARIANCE.S CSC CSCH DAYS DECIMAL DROP ECMA.CEILING ERF.PRECISE ERFC.PRECISE EXPAND EXPON.DIST F.DIST F.DIST.RT F.INV F.INV.RT F.TEST FIELDVALUE FILTERXML FLOOR.MATH FLOOR.PRECISE FORECAST.ETS FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT FORECAST.LINEAR FORMULATEXT GAMMA GAMMA.DIST GAMMA.INV GAMMALN.PRECISE GAUSS GROUPBY HSTACK HYPGEOM.DIST IFNA IFS IMAGE IMCOSH IMCOT IMCSC IMCSCH IMSEC IMSECH IMSINH IMTAN ISFORMULA ISO.CEILING ISOMITTED ISOWEEKNUM LAMBDA LET LOGNORM.DIST LOGNORM.INV MAKEARRAY MAP MAXIFS MINIFS MODE.MULT MODE.SNGL MUNIT NEGBINOM.DIST NETWORKDAYS.INTL NORM.DIST NORM.INV NORM.S.DIST NORM.S.INV NUMBERVALUE PDURATION PERCENTILE.EXC PERCENTILE.INC PERCENTOF PERCENTRANK.EXC PERCENTRANK.INC PERMUTATIONA PHI PIVOTBY POISSON.DIST QUARTILE.EXC QUARTILE.INC QUERYSTRING RANDARRAY RANK.AVG RANK.EQ REDUCE REGEXEXTRACT REGEXREPLACE REGEXTEST RRI SCAN SEC SECH SEQUENCE SHEET SHEETS SINGLE SKEW.P SORTBY STDEV.P STDEV.S SWITCH T.DIST T.DIST.2T T.DIST.RT T.INV T.INV.2T T.TEST TAKE TEXTAFTER TEXTBEFORE TEXTJOIN TEXTSPLIT TOCOL TOROW TRIMRANGE UNICHAR UNICODE UNIQUE VALUETOTEXT VAR.P VAR.S VSTACK WEBSERVICE WEIBULL.DIST WORKDAY.INTL WRAPCOLS WRAPROWS XLOOKUP XMATCH XOR Z.TEST".split(" ")),G=new Set(["BYCOL","BYROW","GROUPBY","MAKEARRAY","MAP","PIVOTBY","REDUCE","SCAN"]);function J(s,e){if(s.indexOf("[")<0)return s;let t;try{t=S(s)}catch{return s}let i="",o=0;for(const l of t){if(l.t!=="table")continue;const c=l.v.name??e()?.name;if(!c)continue;const n=l.v.spec.slice(1,-1).trim();let r=l.v.spec;if(n[0]==="@"){const h=n.slice(1).trim().replace(/^\[|\]$/g,"");r=h?`[[#This Row],[${h}]]`:"[#This Row]"}i+=`${s.slice(o,l.s)}${c}${r}`,o=l.e}return i+s.slice(o)}function y(s){if(s.t==="name"){const e=/^(\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6})\.(.+)$/.exec(s.v);return!e||!E(e[1])||e[2].split(".").some(t=>t==="")?null:{cell:e[1],fields:e[2].split(".")}}if(s.t==="table"&&s.v.name){const e=/^(\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6})\.((?:[A-Za-z_][\w]*\.)*)$/.exec(s.v.name),t=/^\[([^[\]]+)\]$/.exec(s.v.spec);return!e||!t||!E(e[1])?null:{cell:e[1],fields:[...e[2].split(".").filter(Boolean),t[1]]}}return null}const H=String.raw`(?:(?:'(?:[^']|'')*'|${$})!)?\$?[A-Za-z]{1,3}\$?[0-9]+(?:\.(?:[A-Za-z_]\w*|\[[^\]]*\]))*`,W=new RegExp(String.raw`_FV\((${H}),"((?:[^"]|"")*)"\)`,"g");function X(s){let e=s;for(let t=0;t<8&&e.indexOf("_FV(")>=0;t++){const i=e.replace(W,(o,l,c)=>{const n=c.replace(/""/g,'"');return/^[A-Za-z_]\w*$/.test(n)?`${l}.${n}`:/[[\]]/.test(n)?o:`${l}.[${n}]`});if(i===e)break;e=i}return e}function j(s){let e=s.indexOf("#This Row")<0?s:s.replace(/\[\[#This Row\],\[([^\]]+)\]\]/g,(t,i)=>/^[\w.]+$/.test(i)?`[@${i}]`:`[@[${i}]]`);return e.indexOf("_FV(")>=0&&(e=X(e)),e.indexOf("_xl")<0?e:e.replace(/_xlfn\.SINGLE\(([^()]*)\)/g,"@$1").replace(/_xlfn\.ANCHORARRAY\(([^()]*)\)/g,"$1#").replace(/_xlfn\._xlws\.|_xlfn\.|_xlws\.|_xlpm\.|_xludf\.|_xleta\./g,"")}function q(s){if(!/[A-Za-z]/.test(s))return s;let e;try{e=S(s)}catch{return s}const t=Y(e);let i="",o=0;const l=[],c=[];for(let n=0;n<e.length;n++){const r=e[n];r.t==="op"&&r.v==="("?l.push(c.pop()===!0):r.t==="op"&&r.v===")"&&l.pop(),r.t==="func"&&c.push(G.has(r.v)||l.includes(!0));const h=y(r);if(h!==null){const a=e[n-1]?.t==="sheet"&&e[n-1].s>=o?e[n-1].s:r.s,O=s.slice(a,r.s)+h.cell;i+=s.slice(o,a)+h.fields.reduce((d,m)=>`_FV(${d},"${m.replace(/"/g,'""')}")`,O),o=r.e}else if(r.t==="name"&&l.includes(!0)&&!t.has(r.v.toUpperCase())&&L(r.v.toUpperCase()))i+=`${s.slice(o,r.s)}_xleta.${r.v.toUpperCase()}`,o=r.e;else if(r.t==="func")i+=s.slice(o,r.s),t.has(r.v)?i+=`_xlpm.${s.slice(r.s,r.e)}`:V.has(r.v)?i+=`_xlfn._xlws.${r.v}`:B.has(r.v)?i+=`_xlfn.${r.v}`:i+=r.v,o=r.e;else if(r.t==="name"&&t.has(r.v.toUpperCase()))i+=`${s.slice(o,r.s)}_xlpm.${r.v}`,o=r.e;else if(r.t==="op"&&r.v==="@"){const a=e[n+1];a&&(a.t==="cell"||a.t==="name")&&(i+=`${s.slice(o,r.s)}_xlfn.SINGLE(${s.slice(a.s,a.e)})`,o=a.e,n++)}else r.t==="cell"&&e[n+1]?.t==="op"&&e[n+1].v==="#"&&(i+=`${s.slice(o,r.s)}_xlfn.ANCHORARRAY(${s.slice(r.s,r.e)})`,o=e[n+1].e,n++)}return i+s.slice(o)}function Y(s){const e=new Set;for(let t=0;t<s.length;t++){const i=s[t];if(i.t!=="func"||i.v!=="LET"&&i.v!=="LAMBDA")continue;let o=0,l=0,c=!0;const n=[];for(let h=t+1;h<s.length;h++){const a=s[h];if(a.t!=="ws"){if(a.t==="op"&&(a.v==="("||a.v==="{")){if(o++,o===1){c=!0;continue}}else if(a.t==="op"&&(a.v===")"||a.v==="}")){if(o--,o===0)break}else if(a.t==="op"&&a.v===","&&o===1){l++,c=!0;continue}c&&o>=1&&(n.push({argIndex:l,token:a,next:s[h+1]}),c=!1)}}const r=l+1;for(const h of n){if(h.token.t!=="name"||!(h.next===void 0||h.next.t==="ws"||h.next.t==="op"&&(h.next.v===","||h.next.v===")")))continue;(i.v==="LET"?h.argIndex%2===0&&h.argIndex<r-1:h.argIndex<r-1)&&e.add(h.token.v.toUpperCase())}}return e}export{u as FormulaSyntaxError,Z as Parser,J as expandStructured,Q as templateKey,j as toDisplayFormula,q as toFileFormula,S as tokenize};
1
+ import{colIndex as I,MAX_COLS as O,MAX_ROWS as M,PLAIN_SHEET as D}from"../core/address.js";import{ERR_BY_CODE as F}from"./values.js";import{FUNCS as U}from"./functions/registry.js";const C=s=>U.has(s);class u extends Error{}const b=/\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6}/y,G=/(\$?)([A-Za-z]{1,3}):(\$?)([A-Za-z]{1,3})/y,P=/(\$?)([1-9][0-9]{0,6}):(\$?)([1-9][0-9]{0,6})/y,V=/(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y,B=/[A-Za-z_\\\u0080-￿][A-Za-z0-9_.\\?\u0080-￿]*/y,y=/#(?:NULL!|DIV\/0!|VALUE!|REF!|NAME\?|NUM!|N\/A|GETTING_DATA|SPILL!|CALC!|BUSY!|CONNECT!|BLOCKED!|FIELD!|UNKNOWN!)/iy,m=/^(?:_xlfn\._xlws\.|_xlfn\.|_xlws\.|_xlpm\.|_xludf\.|_xleta\.)/i,R=s=>s!==void 0&&/[A-Za-z0-9_.\u0080-￿]/.test(s);function p(s,t,e){return s.lastIndex=e,s.exec(t)}function g(s){if(s.indexOf(".:")<0&&s.indexOf(":.")<0)return d(s);const t=new Set,e=new Map;if(N(s,(c,l)=>{for(const a of c.matchAll(v)){const[,r,h,f]=a;if(!h&&!f)continue;const E=l+a.index+r.length+h.length;h&&t.add(E-1),f&&t.add(E+1),e.set(E,h&&f?"ALL":h?"LEADING":"TRAILING")}return c}),t.size===0)return d(s);let n="";const o=[];for(let c=0;c<s.length;c++)t.has(c)||(o.push(c),n+=s[c]);o.push(s.length);const i=d(n);for(const c of i){const l=o[c.s],a=c.e>0?o[c.e-1]+1:0;for(const[r,h]of e)r>=l&&r<a&&(c.trim=h);c.s=l,c.e=a}return i}function d(s){const t=[];let e=0;const n=s.length,o=(i,c,l,a)=>t.push({t:i,v:c,s:l,e:a});for(;e<n;){const i=s[e];if(i===" "||i===`
2
+ `||i==="\r"||i===" "){const l=e;for(;e<n&&(s[e]===" "||s[e]===`
3
+ `||s[e]==="\r"||s[e]===" ");)e++;o("ws",null,l,e);continue}if(i==='"'){const l=e;let a="";for(e++;;){if(e>=n)throw new u("Unterminated string");if(s[e]==='"'){if(s[e+1]==='"'){a+='"',e+=2;continue}e++;break}a+=s[e++]}o("str",a,l,e);continue}if(i==="'"||i==="["){const l=$(s,e);if(l){o("sheet",l.value,e,l.end),e=l.end;continue}if(i==="["){const a=T(s,e);o("table",{name:null,spec:s.slice(e,a)},e,a),e=a;continue}throw new u("Unexpected quote")}if(i==="#"){const l=p(y,s,e);l?(o("err",F.get(l[0].toUpperCase()),e,e+l[0].length),e+=l[0].length):(o("op","#",e,e+1),e++);continue}if(i>="0"&&i<="9"||i==="."||i==="$"||/[A-Za-z_\\\u0080-￿]/.test(i)){let l=p(P,s,e);if(l&&!R(s[e+l[0].length])){o("rows",{a0:l[1]==="$",r0:Number(l[2])-1,a1:l[3]==="$",r1:Number(l[4])-1},e,e+l[0].length),e+=l[0].length;continue}if(l=p(G,s,e),l&&!R(s[e+l[0].length])&&s[e+l[0].length]!=="("&&s[e+l[0].length]!=="!"){const a=I(l[2]),r=I(l[4]);if(a<O&&r<O){o("cols",{a0:l[1]==="$",c0:a,a1:l[3]==="$",c1:r},e,e+l[0].length),e+=l[0].length;continue}}if(l=p(b,s,e),l){const a=s[e+l[0].length];if(!R(a)&&a!=="("&&a!=="!"&&a!=="["){const r=A(l[0]);if(r){o("cell",r,e,e+l[0].length),e+=l[0].length;continue}}else if(a==="."&&i==="$"){const r=p(/[A-Za-z0-9_.\\?\u0080-￿]*/y,s,e+l[0].length),h=e+l[0].length+r[0].length;o(s[h]==="["?"table":"name",s[h]==="["?{name:s.slice(e,h),spec:s.slice(h,T(s,h))}:s.slice(e,h),e,s[h]==="["?T(s,h):h),e=t[t.length-1].e;continue}}if(i>="0"&&i<="9"||i==="."){if(l=p(V,s,e),!l)throw new u("Bad number");o("num",Number(l[0]),e,e+l[0].length),e+=l[0].length;continue}if(l=p(B,s,e),l){const a=e+l[0].length,r=s[a];if(r==="!"||r===":"&&H(s,a)){const h=$(s,e);if(h){o("sheet",h.value,e,h.end),e=h.end;continue}}if(r==="(")o("func",l[0].replace(m,"").toUpperCase(),e,a);else if(r==="["){const h=T(s,a);o("table",{name:l[0],spec:s.slice(a,h)},e,h),e=h;continue}else o("name",l[0].replace(m,""),e,a);e=a;continue}}const c=s.slice(e,e+2);if(c==="<="||c===">="||c==="<>"){o("op",c,e,e+2),e+=2;continue}if("+-*/^&=<>%(),;:{}@".includes(i)){o("op",i,e,e+1),e++;continue}throw new u(`Unexpected character ${i}`)}return t}function H(s,t){return/^:'?[^'!:]+'?!/.exec(s.slice(t,t+64))!==null}function T(s,t){let e=0;for(let n=t;n<s.length;n++){if(s[n]==="'"&&s[n+1]!==void 0){n++;continue}if(s[n]==="[")e++;else if(s[n]==="]"&&(e--,e===0))return n+1}throw new u("Unterminated [")}function $(s,t){let e=t,n=null;const o=()=>{if(s[e]==="'"){let r="";for(e++;;){if(e>=s.length)return null;if(s[e]==="'"){if(s[e+1]==="'"){r+="'",e+=2;continue}return e++,r}r+=s[e++]}}const a=e;for(;e<s.length&&!'!:,()+-*/^&=<>%{}; "'.includes(s[e]);)e++;return e>a?s.slice(a,e):null};if(s[e]==="["){const a=s.indexOf("]",e);if(a<0)return null;n=s.slice(e+1,a),e=a+1}let i=o();if(i===null)return null;const c=/\[([^\]]+)\](.*)$/.exec(i);c&&(n=c[1],i=c[2]);let l=null;return s[e]===":"&&(e++,l=o(),l===null)||s[e]!=="!"?null:(e++,{value:{book:n,sheet:i,sheet2:l},end:e})}function A(s){let t=0;const e=s[t]==="$";e&&t++;const n=t;for(;/[A-Za-z]/.test(s[t]);)t++;const o=I(s.slice(n,t)),i=s[t]==="$";i&&t++;const c=Number(s.slice(t))-1;return o>=O||c>=M?null:{r:c,c:o,rAbs:i,cAbs:e}}const W=new Set(["=","<>","<",">","<=",">="]);class ie{constructor(t,e=0,n=0){this.toks=t,this.i=0,this.baseRow=e,this.baseCol=n}peek(){return this.toks[this.i]}skipWs(){for(;this.toks[this.i]?.t==="ws";)this.i++}isOp(t){this.skipWs();const e=this.toks[this.i];return e!==void 0&&e.t==="op"&&e.v===t}eat(t){if(!this.isOp(t))throw new u(`Expected ${t}`);this.i++}parse(){const t=this.expr();if(this.skipWs(),this.i<this.toks.length)throw new u("Unexpected text after the formula");return t}expr(){return this.compare()}compare(){let t=this.concat();for(;;){this.skipWs();const e=this.peek();if(e?.t==="op"&&W.has(e.v))this.i++,t={t:"bin",op:e.v,l:t,r:this.concat()};else return t}}concat(){let t=this.add();for(;this.isOp("&");)this.i++,t={t:"bin",op:"&",l:t,r:this.add()};return t}add(){let t=this.mul();for(;;)if(this.isOp("+"))this.i++,t={t:"bin",op:"+",l:t,r:this.mul()};else if(this.isOp("-"))this.i++,t={t:"bin",op:"-",l:t,r:this.mul()};else return t}mul(){let t=this.pow();for(;;)if(this.isOp("*"))this.i++,t={t:"bin",op:"*",l:t,r:this.pow()};else if(this.isOp("/"))this.i++,t={t:"bin",op:"/",l:t,r:this.pow()};else return t}pow(){let t=this.unary();for(;this.isOp("^");)this.i++,t={t:"bin",op:"^",l:t,r:this.unary()};return t}unary(){return this.isOp("-")?(this.i++,{t:"neg",e:this.unary()}):this.isOp("+")?(this.i++,this.unary()):this.isOp("@")?(this.i++,{t:"implicit",e:this.unary()}):this.postfix()}postfix(){let t=this.refExpr();for(;;)if(this.isOp("%"))this.i++,t={t:"pct",e:t};else if(this.peek()?.t==="op"&&this.peek().v==="#")this.i++,t={t:"spillRef",e:t};else return t}refExpr(){let t=this.rangeExpr();for(;;){const e=this.i;if(this.peek()?.t==="ws"){this.skipWs();const n=this.peek();if(n&&this.startsPrimary(n)){t={t:"intersect",l:t,r:this.rangeExpr()};continue}this.i=e}return t}}startsPrimary(t){return t.t==="op"?t.v==="(":t.t==="cell"||t.t==="cols"||t.t==="rows"||t.t==="name"||t.t==="func"||t.t==="sheet"||t.t==="table"}rangeExpr(){let t=this.trimmed(this.primary());for(;this.peek()?.t==="op"&&this.peek().v===":";){const e=this.toks[this.i++],n=this.primary();t=w(t,n),e.trim&&(t=S(t,e.trim)),t=this.trimmed(t)}return t}trimmed(t){const e=this.pendingTrim;return this.pendingTrim=null,e?S(t,e):t}cellNode(t,e=null){return{t:"cell",sheet:e,rAbs:t.rAbs,cAbs:t.cAbs,r:t.rAbs?t.r:t.r-this.baseRow,c:t.cAbs?t.c:t.c-this.baseCol}}rowsNode(t,e=null){return{t:"rows",sheet:e,a0:t.a0,a1:t.a1,r0:t.a0?t.r0:t.r0-this.baseRow,r1:t.a1?t.r1:t.r1-this.baseRow}}colsNode(t,e=null){return{t:"cols",sheet:e,a0:t.a0,a1:t.a1,c0:t.a0?t.c0:t.c0-this.baseCol,c1:t.a1?t.c1:t.c1-this.baseCol}}primary(){this.skipWs();const t=this.peek();if(t===void 0)throw new u("Unexpected end of formula");switch(this.i++,t.t){case"num":return{t:"lit",v:t.v};case"str":return{t:"lit",v:t.v};case"err":return{t:"lit",v:t.v};case"cell":return this.cellNode(t.v);case"rows":return this.pendingTrim=t.trim??null,this.rowsNode(t.v);case"cols":return this.pendingTrim=t.trim??null,this.colsNode(t.v);case"table":return{t:"table",name:t.v.name,spec:t.v.spec};case"sheet":{const e=this.peek();if(e===void 0)throw new u("Expected a reference");if(this.i++,e.t==="cell"){let n=this.cellNode(e.v,t.v);if(this.peek()?.t==="op"&&this.peek().v===":"&&this.toks[this.i+1]?.t==="cell"){const o=this.toks[this.i++],i=this.toks[this.i++];n=w(n,this.cellNode(i.v,t.v)),o.trim&&(n=S(n,o.trim))}return n}if(e.t==="rows")return this.pendingTrim=e.trim??null,this.rowsNode(e.v,t.v);if(e.t==="cols")return this.pendingTrim=e.trim??null,this.colsNode(e.v,t.v);if(e.t==="name")return{t:"name",name:e.v,sheet:t.v};if(e.t==="err")return{t:"lit",v:e.v};if(e.t==="func")return this.i--,this.primary();throw new u("Expected a reference after the sheet name")}case"name":{const e=t.v.toUpperCase();if(e==="TRUE")return{t:"lit",v:!0};if(e==="FALSE")return{t:"lit",v:!1};const n=/^\$?([A-Za-z]{1,3})\$?([1-9][0-9]{0,6})\.(.+)$/.exec(t.v),o=n?A(`$${n[1]}$${n[2]}`):null;return o?{t:"call",name:"_FV",args:[this.cellNode(o),...n[3].split(".").map(i=>({t:"lit",v:i}))]}:{t:"name",name:t.v}}case"func":return this.call(t.v);case"op":if(t.v==="("){const e=this.expr(),n=[e];for(;this.isOp(",");)this.i++,n.push(this.expr());return this.eat(")"),n.length===1?{t:"paren",e}:{t:"union",items:n}}if(t.v==="{")return this.arrayLiteral();throw new u(`Unexpected ${t.v}`);default:throw new u("Unexpected token")}}call(t){let e=this._callArgs(t);if((t==="_FV"||t==="FIELDVALUE")&&e.t==="call"&&e.args.length===2){const n=e.args[0];n?.t==="call"&&(n.name==="_FV"||n.name==="FIELDVALUE")&&n.args.length>=2&&(e={t:"call",name:"_FV",args:[...n.args,e.args[1]]})}if(t==="PHONETIC"&&e.t==="call"&&e.args[0]?.t==="lit")throw new u("PHONETIC needs a reference");if(t==="CALL"||t==="REGISTER.ID")throw new u(`${t} can't be used in a worksheet formula`);return e}_callArgs(t){this.eat("(");const e=[];if(this.isOp(")")){this.i++;const n={t:"call",name:t,args:e};return this.afterCall(n)}for(;;){if(this.skipWs(),this.isOp(",")||this.isOp(")")?e.push({t:"omit"}):e.push(this.expr()),this.isOp(",")){this.i++;continue}this.eat(")");break}return this.afterCall({t:"call",name:t,args:e})}afterCall(t){let e=t;for(;this.peek()?.t==="op"&&this.peek().v==="(";){this.i++;const n=[];if(this.isOp(")"))this.i++;else for(;;){if(this.skipWs(),this.isOp(",")||this.isOp(")")?n.push({t:"omit"}):n.push(this.expr()),this.isOp(",")){this.i++;continue}this.eat(")");break}e={t:"apply",fn:e,args:n}}return e}arrayLiteral(){const t=[[]];for(;;){this.skipWs();let e=!1;for(;this.isOp("-")||this.isOp("+");)this.peek().v==="-"&&(e=!e),this.i++;this.skipWs();const n=this.peek();if(n===void 0)throw new u("Unterminated array");if(this.i++,n.t==="num")t[t.length-1].push(e?-n.v:n.v);else if(n.t==="str"||n.t==="err")t[t.length-1].push(n.v);else if(n.t==="name"&&/^(true|false)$/i.test(n.v))t[t.length-1].push(n.v.toUpperCase()==="TRUE");else throw new u("Arrays can hold only constants");if(this.isOp(","))this.i++;else if(this.isOp(";"))this.i++,t.push([]);else{this.eat("}");break}}return{t:"array",rows:t}}}function w(s,t){return s.t==="cell"&&t.t==="cell"?{t:"range",sheet:s.sheet??t.sheet,a:s,b:t}:{t:"rangeOp",l:s,r:t}}function re(s,t,e){let n="";for(let o=0;o<s.length;o++){const i=s[o];switch(i.t){case"cell":{const c=i.v;n+=`R${c.rAbs?c.r:`[${c.r-t}]`}C${c.cAbs?c.c:`[${c.c-e}]`}`;break}case"rows":{const c=i.v;n+=`R${c.a0?c.r0:`[${c.r0-t}]`}:R${c.a1?c.r1:`[${c.r1-t}]`}`;break}case"cols":{const c=i.v;n+=`C${c.a0?c.c0:`[${c.c0-e}]`}:C${c.a1?c.c1:`[${c.c1-e}]`}`;break}case"num":case"func":n+=`${i.t==="num"?"":"~"}${i.v}`;break;case"op":n+=i.v;break;case"ws":n+=" ";break;case"str":n+=JSON.stringify(i.v);break;case"name":n+=`${i.v}`;break;case"err":n+=i.v.code;break;default:n+=`${JSON.stringify(i.v)}`}}return n}const X=new Set(["FILTER","SORT","PY"]),Y=new Set("_TRO_ALL _TRO_LEADING _TRO_TRAILING DETECTLANGUAGE ENCODEURL STOCKHISTORY TRANSLATE ACOT ACOTH AGGREGATE ARABIC ARRAYTOTEXT ANCHORARRAY BASE BETA.DIST BETA.INV BINOM.DIST BINOM.DIST.RANGE BINOM.INV BITAND BITLSHIFT BITOR BITRSHIFT BITXOR BYCOL BYROW CEILING.MATH CEILING.PRECISE CHISQ.DIST CHISQ.DIST.RT CHISQ.INV CHISQ.INV.RT CHISQ.TEST CHOOSECOLS CHOOSEROWS COMBINA CONCAT CONFIDENCE.NORM CONFIDENCE.T COT COTH COVARIANCE.P COVARIANCE.S CSC CSCH DAYS DECIMAL DROP ECMA.CEILING ERF.PRECISE ERFC.PRECISE EXPAND EXPON.DIST F.DIST F.DIST.RT F.INV F.INV.RT F.TEST FIELDVALUE FILTERXML FLOOR.MATH FLOOR.PRECISE FORECAST.ETS FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT FORECAST.LINEAR FORMULATEXT GAMMA GAMMA.DIST GAMMA.INV GAMMALN.PRECISE GAUSS GROUPBY HSTACK HYPGEOM.DIST IFNA IFS IMAGE IMCOSH IMCOT IMCSC IMCSCH IMSEC IMSECH IMSINH IMTAN ISFORMULA ISO.CEILING ISOMITTED ISOWEEKNUM LAMBDA LET LOGNORM.DIST LOGNORM.INV MAKEARRAY MAP MAXIFS MINIFS MODE.MULT MODE.SNGL MUNIT NEGBINOM.DIST NETWORKDAYS.INTL NORM.DIST NORM.INV NORM.S.DIST NORM.S.INV NUMBERVALUE PDURATION PERCENTILE.EXC PERCENTILE.INC PERCENTOF PERCENTRANK.EXC PERCENTRANK.INC PERMUTATIONA PHI PIVOTBY POISSON.DIST QUARTILE.EXC QUARTILE.INC QUERYSTRING RANDARRAY RANK.AVG RANK.EQ REDUCE REGEXEXTRACT REGEXREPLACE REGEXTEST RRI SCAN SEC SECH SEQUENCE SHEET SHEETS SINGLE SKEW.P SORTBY STDEV.P STDEV.S SWITCH T.DIST T.DIST.2T T.DIST.RT T.INV T.INV.2T T.TEST TAKE TEXTAFTER TEXTBEFORE TEXTJOIN TEXTSPLIT TOCOL TOROW TRIMRANGE UNICHAR UNICODE UNIQUE VALUETOTEXT VAR.P VAR.S VSTACK WEBSERVICE WEIBULL.DIST WORKDAY.INTL WRAPCOLS WRAPROWS XLOOKUP XMATCH XOR Z.TEST".split(" ")),z=new Set(["BYCOL","BYROW","GROUPBY","MAKEARRAY","MAP","PIVOTBY","REDUCE","SCAN"]);function le(s,t){if(s.indexOf("[")<0)return s;let e;try{e=g(s)}catch{return s}let n="",o=0;for(const i of e){if(i.t!=="table")continue;const c=i.v.name??t()?.name;if(!c)continue;const l=i.v.spec.slice(1,-1).trim();let a=i.v.spec;if(l[0]==="@"){const r=l.slice(1).trim().replace(/^\[|\]$/g,"");a=r?`[[#This Row],[${r}]]`:"[#This Row]"}n+=`${s.slice(o,i.s)}${c}${a}`,o=i.e}return n+s.slice(o)}function x(s){if(s.t==="name"){const t=/^(\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6})\.(.+)$/.exec(s.v);return!t||!A(t[1])||t[2].split(".").some(e=>e==="")?null:{cell:t[1],fields:t[2].split(".")}}if(s.t==="table"&&s.v.name){const t=/^(\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6})\.((?:[A-Za-z_][\w]*\.)*)$/.exec(s.v.name),e=/^\[([^[\]]+)\]$/.exec(s.v.spec);return!t||!e||!A(t[1])?null:{cell:t[1],fields:[...t[2].split(".").filter(Boolean),e[1]]}}return null}const Z=String.raw`(?:(?:'(?:[^']|'')*'|${D})!)?\$?[A-Za-z]{1,3}\$?[0-9]+(?:\.(?:[A-Za-z_]\w*|\[[^\]]*\]))*`,K=new RegExp(String.raw`_FV\((${Z}),"((?:[^"]|"")*)"\)`,"g");function Q(s){let t=s;for(let e=0;e<8&&t.indexOf("_FV(")>=0;e++){const n=t.replace(K,(o,i,c)=>{const l=c.replace(/""/g,'"');return/^[A-Za-z_]\w*$/.test(l)?`${i}.${l}`:/[[\]]/.test(l)?o:`${i}.[${l}]`});if(n===t)break;t=n}return t}function oe(s){let t=s.indexOf("#This Row")<0?s:s.replace(/\[\[#This Row\],\[([^\]]+)\]\]/g,(e,n)=>/^[\w.]+$/.test(n)?`[@${n}]`:`[@[${n}]]`);return t.indexOf("_FV(")>=0&&(t=Q(t)),t.indexOf("_xl")<0?t:(t.indexOf("_TRO_")>=0&&(t=ee(t)),t.replace(/_xlfn\.SINGLE\(([^()]*)\)/g,"@$1").replace(/_xlfn\.ANCHORARRAY\(([^()]*)\)/g,"$1#").replace(/_xlfn\._xlws\.|_xlfn\.|_xlws\.|_xlpm\.|_xludf\.|_xleta\./g,""))}function ce(s,t=null){if(!/[A-Za-z]/.test(s))return s;s=q(s);let e;try{e=g(s)}catch{return s}const n=J(e);let o="",i=0;const c=[],l=[];for(let a=0;a<e.length;a++){const r=e[a];r.t==="op"&&r.v==="("?c.push(l.pop()===!0):r.t==="op"&&r.v===")"&&c.pop(),r.t==="func"&&l.push(z.has(r.v)||c.includes(!0));const h=x(r);if(h!==null){const f=e[a-1]?.t==="sheet"&&e[a-1].s>=i?e[a-1].s:r.s,E=s.slice(f,r.s)+h.cell;o+=s.slice(i,f)+h.fields.reduce((_,k)=>`_FV(${_},"${k.replace(/"/g,'""')}")`,E),i=r.e}else if(r.t==="name"&&c.includes(!0)&&!n.has(r.v.toUpperCase())&&C(r.v.toUpperCase()))o+=`${s.slice(i,r.s)}_xleta.${r.v.toUpperCase()}`,i=r.e;else if(r.t==="func")o+=s.slice(i,r.s),n.has(r.v)?o+=`_xlpm.${s.slice(r.s,r.e)}`:X.has(r.v)?o+=`_xlfn._xlws.${r.v}`:Y.has(r.v)?o+=`_xlfn.${r.v}`:o+=!C(r.v)&&t?.get(r.v)?.name?t.get(r.v).name:r.v,i=r.e;else if(r.t==="name"&&n.has(r.v.toUpperCase()))o+=`${s.slice(i,r.s)}_xlpm.${r.v}`,i=r.e;else if(r.t==="op"&&r.v==="@"){const f=e[a+1];f&&(f.t==="cell"||f.t==="name")&&(o+=`${s.slice(i,r.s)}_xlfn.SINGLE(${s.slice(f.s,f.e)})`,i=f.e,a++)}else r.t==="cell"&&e[a+1]?.t==="op"&&e[a+1].v==="#"&&(o+=`${s.slice(i,r.s)}_xlfn.ANCHORARRAY(${s.slice(r.s,r.e)})`,i=e[a+1].e,a++)}return o+s.slice(i)}function J(s){const t=new Set;for(let e=0;e<s.length;e++){const n=s[e];if(n.t!=="func"||n.v!=="LET"&&n.v!=="LAMBDA")continue;let o=0,i=0,c=!0;const l=[];for(let r=e+1;r<s.length;r++){const h=s[r];if(h.t!=="ws"){if(h.t==="op"&&(h.v==="("||h.v==="{")){if(o++,o===1){c=!0;continue}}else if(h.t==="op"&&(h.v===")"||h.v==="}")){if(o--,o===0)break}else if(h.t==="op"&&h.v===","&&o===1){i++,c=!0;continue}c&&o>=1&&(l.push({argIndex:i,token:h,next:s[r+1]}),c=!1)}}const a=i+1;for(const r of l){if(r.token.t!=="name"||!(r.next===void 0||r.next.t==="ws"||r.next.t==="op"&&(r.next.v===","||r.next.v===")")))continue;(n.v==="LET"?r.argIndex%2===0&&r.argIndex<a-1:r.argIndex<a-1)&&t.add(r.token.v.toUpperCase())}}return t}const j=String.raw`(?:'(?:[^']|'')+'|[A-Za-z_À-￿][\w.À-￿]*)!`,L=String.raw`\$?[A-Za-z]{1,3}\$?\d{1,7}|\$?[A-Za-z]{1,3}|\$?\d{1,7}`,v=new RegExp(String.raw`(?<![\w.$!'])((?:${j})?(?:${L}))(\.?):(\.?)(${L})(?![\w(!])`,"g");function N(s,t){let e="",n=0;const o=/"(?:[^"]|"")*"/g;for(let i=o.exec(s);i!==null;i=o.exec(s))e+=t(s.slice(n,i.index),n)+i[0],n=i.index+i[0].length;return e+t(s.slice(n),n)}const S=(s,t)=>({t:"call",name:`_TRO_${t}`,args:[s]});function q(s){return s.indexOf(".:")<0&&s.indexOf(":.")<0?s:N(s,t=>t.replace(v,(e,n,o,i,c)=>!o&&!i?e:`_xlfn._TRO_${o&&i?"ALL":o?"LEADING":"TRAILING"}(${n}:${c})`))}function ee(s){return N(s,t=>t.replace(/(?:_xlfn\.)?_TRO_(ALL|LEADING|TRAILING)\(((?:'(?:[^']|'')*'|[^()'])*)\)/g,(e,n,o)=>{const i=o.lastIndexOf(":");if(i<0)return e;const c=n!=="TRAILING"?".":"",l=n!=="LEADING"?".":"";return`${o.slice(0,i)}${c}:${l}${o.slice(i+1)}`}))}export{u as FormulaSyntaxError,ie as Parser,le as expandStructured,re as templateKey,oe as toDisplayFormula,ce as toFileFormula,g as tokenize,q as trimRefsToFile};
package/cells/axis-ops.js CHANGED
@@ -1 +1 @@
1
- import{openFormatCells as W,promptNumber as O}from"../ui/dialogs.js";import{guardOption as b}from"../ui/protection-ui.js";import{MAX_COLS as w,MAX_ROWS as C}from"../core/address.js";import{CHUNK_BITS as F}from"../core/sheet.js";import{wrapsByAlign as T}from"./text-layout.js";import{canResize as k}from"./axis-limits.js";import{openTrackSize as R}from"./cell-options-ui.js";import{openHeaderColors as z}from"./header-colors.js";const a=o=>o==="col"?"cols":"rows";function _(o){const e=o.grid.selection.ranges[0];e.c0===0&&e.c1===w-1?z(o,"row",e.r0,e.r1):z(o,"col",e.c0,e.c1)}function h(o,e,s){return()=>{const t=o[e];return o[e]=s,e==="cols"&&(o.colsChanged=!0),o.revision++,h(o,e,t)}}function g(o,e){const{book:s,grid:t}=o;e==="col"&&(s.sheet.colsChanged=!0),s.dirty=!0,o.objects?.geometryChanged?.(),t.invalidate()}function I(o,e){const{sheet:s,styles:t}=o.book,n=new Set,r=new Map,c=l=>{let i=r.get(l);if(i===void 0){const f=t.get(l);i=!!(f.wrap||T(f)),r.set(l,i)}return i};o:for(const l of e.slice(0,256)){const i=s.columns[l];if(i===void 0)continue;const f=s.colStyles?.get(l)??0;for(let d=0;d<i.length;d++){const u=i[d];if(u!==void 0)for(let m=0;m<u.kinds.length;m++){if(u.kinds[m]===0)continue;const H=u.styles===null||u.styles[m]===0?f:u.styles[m];if(!(H===0||!c(H))&&(n.add((d<<F)+m),n.size>=U))break o}}}for(const l of n)o.commands._growRow(l);return n.size>0}const U=2e3;function x(o,e,s){const t=o.book.sheet,n=t.rows.reshaped();if(!I(o,e))return s;const r=(c,l)=>()=>{const i=c(),f=l();return r(f,i)};return r(h(t,"rows",n),s)}function y(o,e,s,t=null){const{book:n}=o,r=n.sheet,c=a(e);n.transact("axis",()=>{const l=r[c].reshaped();s(),r.revision++;const i=h(r,c,l);return t!==null&&e==="col"?x(o,t,i):i}),g(o,e),t!==null&&n.collab?.changed?.()}const A=(o,e)=>o==="col"?e.r0===0&&e.r1===C-1:e.c0===0&&e.c1===w-1,S=(o,e)=>o==="col"?[e.c0,e.c1]:[e.r0,e.r1];function v(o,e,s){const t=new Set,n=e==="col"?w-1:C-1;for(const r of s.ranges){const[c,l]=S(e,r),i=e==="col"?o.maxCol:o.maxRow,f=l>=n?Math.max(c,i):l;for(let d=c;d<=f;d++)t.add(d)}return[...t]}function B(o,e,s,t){const n=[];let r=!1;for(const c of t.ranges){if(!A(e,c))continue;const[l,i]=S(e,c);s>=l&&s<=i&&(r=!0);const f=Math.min(i,l+2e4);for(let d=l;d<=f;d++)n.push(d)}return r?n:[s]}function P(o,e,s,t){const n=B(o,e,s,t),r=o[a(e)];return{list:n,saved:r.reshaped(),starts:n.map(c=>r.sizeOf(c))}}function Q(o,e,s,t){const n=o[a(e)];for(const r of s.group.list)n.isHidden(r)&&n.setHidden(r,!1),n.setSize(r,t)}function V(o,e){const{book:s}=o,t=s.sheet,n=e.type==="colResize"?"col":"row",r=a(n),c=t[r],{list:l,starts:i,saved:f}=e.group;l.forEach((d,u)=>{c.sizeOf(d)===0&&!c.isHidden(d)&&(i[u]>0&&c.setSize(d,i[u]),c.setHidden(d,!0))}),s.transact("axis",()=>n==="col"?x(o,l,h(t,r,f)):h(t,r,f)),g(o,n),n==="col"&&s.collab?.changed?.()}function Y(o,e,s){if(!b(o,e==="row"?"formatRows":"formatColumns"))return;const t=o.book.sheet,n=t[a(e)],r=v(t,e,o.grid.selection).filter(c=>k(t,e,c));y(o,e,()=>{for(const c of r)s===0?n.setHidden(c,!0):(n.setHidden(c,!1),n.setSize(c,s))},e==="col"?r:null)}function Z(o,e,s){if(!b(o,e==="row"?"formatRows":"formatColumns"))return;const t=o.book.sheet,n=t[a(e)];y(o,e,()=>{for(const r of o.grid.selection.ranges){const[c,l]=S(e,r);if(s)for(let i=c;i<=l;i++)n.setHidden(i,!0);else if(n.hiddenSizes)for(const i of[...n.hiddenSizes.keys()])i<c||i>l||e==="row"&&t.filteredRows?.has(i)||n.setHidden(i,!1)}})}function M(o,e){const{book:s,commands:t,grid:n}=o,r=s.sheet,c=v(r,e,n.selection);if(e==="row"){t.fitAxis("row",c);return}const l=n.selection.ranges[n.selection.ranges.length-1];t.fitAxis("col",c,A("col",l)?null:l)}const j=o=>o<=5?0:Math.round((o-5)/6*100)/100,D=o=>o<=0?0:Math.round(o*6+5);function E(o){const{book:e,grid:s}=o,t=e.sheet;O(o,"Standard Width","Standard column width:",j(t.cols.defaultSize),0,255,n=>{e.transact("axis",()=>{const r=t.cols;return t.cols=r.reshaped(r.count,Math.max(1,D(n))),t.standardWidthChanged=!0,h(t,"cols",r)}),g(o,"col"),s.invalidate()})}function $(o){const e=o.commands;return{items:[["Row Height…",()=>R(o,"row")],["AutoFit Row Height",()=>M(o,"row")],null,["Column Width…",()=>R(o,"col")],["AutoFit Selection",()=>M(o,"col")],["Standard Width…",()=>E(o)],null,["Hide & Unhide",()=>{},{items:()=>({items:[["Hide Rows",()=>e.setHidden("row",!0)],["Hide Columns",()=>e.setHidden("col",!0)],null,["Unhide Rows",()=>e.setHidden("row",!1)],["Unhide Columns",()=>e.setHidden("col",!1)]]})}],null,["Header Color…",()=>_(o)],["Format Cells…",()=>W(o)]]}}function oo(o,e){const s=o.book.sheet,t=e.type==="colResize"?"col":"row";h(s,a(t),e.group.saved)(),t==="col"&&(s.colsChanged=!0),o.objects?.geometryChanged?.(),o.grid.invalidate()}export{y as axisStep,k as canResize,oo as cancelAxisDrag,D as charsToWidth,P as dragGroup,Q as dragSize,V as endAxisDrag,M as fitSelected,$ as formatMenu,Z as hideSelected,E as openStandardWidth,B as selectedAround,Y as setSelectedSize,j as widthToChars};
1
+ import{selectedSheets as C}from"../core/sheet-group.js";import{openFormatCells as O,promptNumber as F}from"../ui/dialogs.js";import{guardOption as R}from"../ui/protection-ui.js";import{MAX_COLS as S,MAX_ROWS as z}from"../core/address.js";import{CHUNK_BITS as T}from"../core/sheet.js";import{wrapsByAlign as _}from"./text-layout.js";import{canResize as b}from"./axis-limits.js";import{openTrackSize as y}from"./cell-options-ui.js";import{openHeaderColors as v}from"./header-colors.js";const h=o=>o==="col"?"cols":"rows";function I(o){const e=o.grid.selection.ranges[0];e.c0===0&&e.c1===S-1?v(o,"row",e.r0,e.r1):v(o,"col",e.c0,e.c1)}function m(o,e,r){return()=>{const s=o[e];return o[e]=r,e==="cols"&&(o.colsChanged=!0),o.revision++,m(o,e,s)}}function g(o,e){const{book:r,grid:s}=o;e==="col"&&(r.sheet.colsChanged=!0),r.dirty=!0,o.objects?.geometryChanged?.(),s.invalidate()}function U(o,e){const{sheet:r,styles:s}=o.book,n=new Set,i=new Map,l=t=>{let c=i.get(t);if(c===void 0){const f=s.get(t);c=!!(f.wrap||_(f)),i.set(t,c)}return c};o:for(const t of e.slice(0,256)){const c=r.columns[t];if(c===void 0)continue;const f=r.colStyles?.get(t)??0;for(let d=0;d<c.length;d++){const u=c[d];if(u!==void 0)for(let a=0;a<u.kinds.length;a++){if(u.kinds[a]===0)continue;const w=u.styles===null||u.styles[a]===0?f:u.styles[a];if(!(w===0||!l(w))&&(n.add((d<<T)+a),n.size>=B))break o}}}for(const t of n)o.commands._growRow(t);return n.size>0}const B=2e3;function H(o,e,r){const s=o.book.sheet,n=s.rows.reshaped();if(!U(o,e))return r;const i=(l,t)=>()=>{const c=l(),f=t();return i(f,c)};return i(m(s,"rows",n),r)}function A(o,e,r,s=null){const{book:n}=o,i=n.sheet,l=h(e);n.transact("axis",()=>{const t=i[l].reshaped();r(),i.revision++;const c=m(i,l,t);return s!==null&&e==="col"?H(o,s,c):c}),g(o,e),s!==null&&n.collab?.changed?.()}const M=(o,e)=>o==="col"?e.r0===0&&e.r1===z-1:e.c0===0&&e.c1===S-1,k=(o,e)=>o==="col"?[e.c0,e.c1]:[e.r0,e.r1];function x(o,e,r){const s=new Set,n=e==="col"?S-1:z-1;for(const i of r.ranges){const[l,t]=k(e,i),c=e==="col"?o.maxCol:o.maxRow,f=t>=n?Math.max(l,c):t;for(let d=l;d<=f;d++)s.add(d)}return[...s]}function j(o,e,r,s){const n=[];let i=!1;for(const l of s.ranges){if(!M(e,l))continue;const[t,c]=k(e,l);r>=t&&r<=c&&(i=!0);const f=Math.min(c,t+2e4);for(let d=t;d<=f;d++)n.push(d)}return i?n:[r]}function Y(o,e,r,s){const n=j(o,e,r,s),i=o[h(e)];return{list:n,saved:i.reshaped(),starts:n.map(l=>i.sizeOf(l))}}function Z(o,e,r,s){const n=o[h(e)];for(const i of r.group.list)n.isHidden(i)&&n.setHidden(i,!1),n.setSize(i,s)}function $(o,e){const{book:r}=o,s=r.sheet,n=e.type==="colResize"?"col":"row",i=h(n),l=s[i],{list:t,starts:c,saved:f}=e.group;t.forEach((d,u)=>{l.sizeOf(d)===0&&!l.isHidden(d)&&(c[u]>0&&l.setSize(d,c[u]),l.setHidden(d,!0))}),r.transact("axis",()=>n==="col"?H(o,t,m(s,i,f)):m(s,i,f)),g(o,n),n==="col"&&r.collab?.changed?.()}function p(o,e,r){if(!R(o,e==="row"?"formatRows":"formatColumns"))return;const s=o.book.sheet,n=s[h(e)],i=x(s,e,o.grid.selection).filter(t=>b(s,e,t)),l=C(o.book);if(l.length>1){const t=h(e);o.book.transact("axis",()=>{const c=l.map(d=>{const u=d[t].reshaped();for(const w of i)b(d,e,w)&&(r===0?d[t].setHidden(w,!0):(d[t].setHidden(w,!1),d[t].setSize(w,r)));d.revision++,t==="cols"&&(d.colsChanged=!0);const a=m(d,t,u);return e==="col"&&d===s?H(o,i,a):a}),f=d=>()=>f(d.map(u=>u()));return f(c)}),g(o,e),e==="col"&&o.book.collab?.changed?.();return}A(o,e,()=>{for(const t of i)r===0?n.setHidden(t,!0):(n.setHidden(t,!1),n.setSize(t,r))},e==="col"?i:null)}function oo(o,e,r){if(!R(o,e==="row"?"formatRows":"formatColumns"))return;const s=o.book.sheet,n=s[h(e)];A(o,e,()=>{for(const i of o.grid.selection.ranges){const[l,t]=k(e,i);if(r)for(let c=l;c<=t;c++)n.setHidden(c,!0);else if(n.hiddenSizes)for(const c of[...n.hiddenSizes.keys()])c<l||c>t||e==="row"&&s.filteredRows?.has(c)||n.setHidden(c,!1)}})}function W(o,e){const{book:r,commands:s,grid:n}=o,i=r.sheet,l=x(i,e,n.selection);if(e==="row"){s.fitAxis("row",l);return}const t=n.selection.ranges[n.selection.ranges.length-1];s.fitAxis("col",l,M("col",t)?null:t)}const D=o=>o<=5?0:Math.round((o-5)/6*100)/100,E=o=>o<=0?0:Math.round(o*6+5);function L(o){const{book:e,grid:r}=o,s=e.sheet;F(o,"Standard Width","Standard column width:",D(s.cols.defaultSize),0,255,n=>{const i=C(e);e.transact("axis",()=>{const l=i.map(c=>{const f=c.cols;return c.cols=f.reshaped(f.count,Math.max(1,E(n))),c.standardWidthChanged=!0,m(c,"cols",f)}),t=c=>()=>t(c.map(f=>f()));return t(l)}),g(o,"col"),r.invalidate()})}function eo(o){const e=o.commands;return{items:[["Row Height…",()=>y(o,"row")],["AutoFit Row Height",()=>W(o,"row")],null,["Column Width…",()=>y(o,"col")],["AutoFit Selection",()=>W(o,"col")],["Standard Width…",()=>L(o)],null,["Hide & Unhide",()=>{},{items:()=>({items:[["Hide Rows",()=>e.setHidden("row",!0)],["Hide Columns",()=>e.setHidden("col",!0)],null,["Unhide Rows",()=>e.setHidden("row",!1)],["Unhide Columns",()=>e.setHidden("col",!1)]]})}],null,["Header Color…",()=>I(o)],["Format Cells…",()=>O(o)]]}}function to(o,e){const r=o.book.sheet,s=e.type==="colResize"?"col":"row";m(r,h(s),e.group.saved)(),s==="col"&&(r.colsChanged=!0),o.objects?.geometryChanged?.(),o.grid.invalidate()}export{A as axisStep,b as canResize,to as cancelAxisDrag,E as charsToWidth,Y as dragGroup,Z as dragSize,$ as endAxisDrag,W as fitSelected,eo as formatMenu,oo as hideSelected,L as openStandardWidth,j as selectedAround,p as setSelectedSize,D as widthToChars};