@8sheets/data-grid 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/README.md +1 -1
  2. package/a11y/cell-alt-text.js +1 -1
  3. package/api/serialize.js +1 -1
  4. package/api/style-refs.js +1 -1
  5. package/calc/adjust.js +1 -1
  6. package/calc/compile.js +1 -1
  7. package/calc/engine.js +1 -1
  8. package/calc/functions/array.js +1 -1
  9. package/calc/functions/database.js +1 -1
  10. package/calc/functions/date.js +1 -1
  11. package/calc/functions/engineering.js +1 -1
  12. package/calc/functions/financial.js +1 -1
  13. package/calc/functions/helpers.js +1 -1
  14. package/calc/functions/index.js +3 -2
  15. package/calc/functions/info.js +1 -1
  16. package/calc/functions/logical.js +1 -1
  17. package/calc/functions/lookup.js +1 -1
  18. package/calc/functions/math.js +1 -1
  19. package/calc/functions/stat.js +1 -1
  20. package/calc/functions/text.js +1 -1
  21. package/calc/parser.js +2 -2
  22. package/calc/shown-refs.js +1 -0
  23. package/calc/values.js +1 -1
  24. package/calcx/calc-control.js +1 -0
  25. package/calcx/external-read.js +1 -1
  26. package/calcx/external.js +1 -1
  27. package/cells/axis-ops.js +1 -1
  28. package/cells/cell-styles-xml.js +1 -1
  29. package/cells/cf-engine.js +1 -1
  30. package/cells/cf-file.js +1 -1
  31. package/cells/docprops-xml.js +2 -2
  32. package/cells/filter-eval.js +1 -0
  33. package/cells/filter-file.js +1 -1
  34. package/cells/find-engine.js +1 -1
  35. package/cells/goto.js +1 -1
  36. package/cells/name-box.js +1 -1
  37. package/cells/note-box.js +3 -0
  38. package/cells/options.js +1 -1
  39. package/cells/outline-column.js +1 -1
  40. package/cells/protected-menu.js +1 -0
  41. package/cells/rich-data-xml.js +1 -1
  42. package/cells/sheet-views-file.js +2 -0
  43. package/cells/shift-check.js +1 -1
  44. package/cells/sort-compare.js +1 -0
  45. package/cells/ui-kit.js +1 -1
  46. package/cells/undo-group.js +1 -1
  47. package/celltypes/dropdowns.js +2 -2
  48. package/core/address.js +1 -1
  49. package/core/autofill.js +1 -1
  50. package/core/axis.js +1 -1
  51. package/core/cond-format.js +1 -1
  52. package/core/culture.js +5 -1
  53. package/core/custom-views.js +1 -1
  54. package/core/data-tools.js +1 -0
  55. package/core/date-codes.js +1 -0
  56. package/core/default-names.js +1 -1
  57. package/core/formula-refs.js +1 -1
  58. package/core/input.js +1 -1
  59. package/core/numfmt.js +1 -1
  60. package/core/precision.js +1 -0
  61. package/core/region-input.js +1 -1
  62. package/core/rule-refs.js +1 -0
  63. package/core/shared-view.js +1 -0
  64. package/core/sheet.js +1 -1
  65. package/core/sparklines.js +1 -1
  66. package/core/sparse.js +1 -1
  67. package/core/spills.js +1 -0
  68. package/core/strings.js +1 -1
  69. package/core/structure.js +1 -1
  70. package/core/table-columns.js +1 -0
  71. package/core/tables.js +2 -2
  72. package/core/validation-ranges.js +1 -1
  73. package/core/whatif.js +1 -1
  74. package/core/workbook.js +1 -1
  75. package/datasheets/formula.js +1 -1
  76. package/datasheets/path-binding.js +1 -1
  77. package/datasheets/persist-writer.js +1 -1
  78. package/datasheets/report.js +1 -1
  79. package/extras/getdata/persist.js +2 -2
  80. package/extras/getdata/rows.js +1 -1
  81. package/extras/getdata/shared-steps.js +1 -0
  82. package/extras/getdata/steps-formula.js +1 -0
  83. package/extras/getdata/steps-more.js +1 -0
  84. package/extras/getdata/steps-tables.js +1 -0
  85. package/extras/getdata/steps.js +1 -1
  86. package/i18n/de/a11y.js +1 -0
  87. package/i18n/de/cells.js +2 -0
  88. package/i18n/de/charts.js +1 -0
  89. package/i18n/de/common.js +1 -0
  90. package/i18n/de/datasheets.js +1 -0
  91. package/i18n/de/format.js +1 -0
  92. package/i18n/de/misc.js +1 -0
  93. package/i18n/de/pivot.js +1 -0
  94. package/i18n/de/proofing.js +1 -0
  95. package/i18n/de/ribbon.js +1 -0
  96. package/i18n/de/shapes.js +1 -0
  97. package/i18n/de/shell.js +3 -0
  98. package/i18n/de/touch.js +1 -0
  99. package/i18n/de.js +1 -0
  100. package/i18n/en/cells.js +2 -1
  101. package/i18n/en/charts.js +1 -1
  102. package/i18n/en/format.js +1 -1
  103. package/i18n/en/misc.js +1 -1
  104. package/i18n/en/pivot.js +1 -1
  105. package/i18n/en/proofing.js +1 -1
  106. package/i18n/en/ribbon.js +1 -1
  107. package/i18n/en/shapes.js +1 -1
  108. package/i18n/en/shell.js +3 -2
  109. package/i18n/en/touch.js +1 -1
  110. package/i18n/es/a11y.js +1 -0
  111. package/i18n/es/cells.js +2 -0
  112. package/i18n/es/charts.js +1 -0
  113. package/i18n/es/common.js +1 -0
  114. package/i18n/es/datasheets.js +1 -0
  115. package/i18n/es/format.js +1 -0
  116. package/i18n/es/misc.js +1 -0
  117. package/i18n/es/pivot.js +1 -0
  118. package/i18n/es/proofing.js +1 -0
  119. package/i18n/es/ribbon.js +1 -0
  120. package/i18n/es/shapes.js +1 -0
  121. package/i18n/es/shell.js +3 -0
  122. package/i18n/es/touch.js +1 -0
  123. package/i18n/es.js +1 -0
  124. package/i18n/fr/a11y.js +1 -0
  125. package/i18n/fr/cells.js +2 -0
  126. package/i18n/fr/charts.js +1 -0
  127. package/i18n/fr/common.js +1 -0
  128. package/i18n/fr/datasheets.js +1 -0
  129. package/i18n/fr/format.js +1 -0
  130. package/i18n/fr/misc.js +1 -0
  131. package/i18n/fr/pivot.js +1 -0
  132. package/i18n/fr/proofing.js +1 -0
  133. package/i18n/fr/ribbon.js +1 -0
  134. package/i18n/fr/shapes.js +1 -0
  135. package/i18n/fr/shell.js +3 -0
  136. package/i18n/fr/touch.js +1 -0
  137. package/i18n/fr.js +1 -0
  138. package/i18n/index.js +1 -1
  139. package/i18n/languages.js +1 -1
  140. package/i18n/pl/cells.js +2 -1
  141. package/i18n/pl/charts.js +1 -1
  142. package/i18n/pl/format.js +1 -1
  143. package/i18n/pl/misc.js +1 -1
  144. package/i18n/pl/pivot.js +1 -1
  145. package/i18n/pl/proofing.js +1 -1
  146. package/i18n/pl/ribbon.js +1 -1
  147. package/i18n/pl/shapes.js +1 -1
  148. package/i18n/pl/shell.js +3 -2
  149. package/i18n/pl/touch.js +1 -1
  150. package/io/blob-sink.js +1 -0
  151. package/io/canonical-xml.js +1 -0
  152. package/io/client.js +1 -1
  153. package/io/crypto/cfb-build.js +1 -0
  154. package/io/crypto/cfb-read.js +1 -1
  155. package/io/crypto/cfb-write.js +1 -1
  156. package/io/crypto/errors.js +1 -1
  157. package/io/csv.js +8 -8
  158. package/io/foreign-sheets.js +2 -2
  159. package/io/io.worker.js +1 -1
  160. package/io/open-package.js +1 -0
  161. package/io/package-paths.js +1 -1
  162. package/io/plan.js +1 -1
  163. package/io/text-split.js +3 -3
  164. package/io/xls/chart-sheet.js +1 -0
  165. package/io/xls/chart.js +1 -0
  166. package/io/xls/crypt.js +1 -0
  167. package/io/xls/dml-color.js +1 -0
  168. package/io/xls/drawing.js +1 -0
  169. package/io/xls/formula.js +1 -0
  170. package/io/xls/geometry.js +1 -0
  171. package/io/xls/index.js +1 -0
  172. package/io/xls/pictures.js +1 -0
  173. package/io/xls/pivot.js +1 -0
  174. package/io/xls/props.js +1 -0
  175. package/io/xls/records.js +1 -0
  176. package/io/xls/shapes.js +1 -0
  177. package/io/xls/sheet-ext.js +1 -0
  178. package/io/xls/sheet.js +1 -0
  179. package/io/xls/styles.js +1 -0
  180. package/io/xls/vba.js +1 -0
  181. package/io/xls/workbook.js +1 -0
  182. package/io/xlsb/filter.js +1 -0
  183. package/io/xlsb/formula.js +2 -0
  184. package/io/xlsb/functions.js +1 -0
  185. package/io/xlsb/index.js +1 -0
  186. package/io/xlsb/parts.js +1 -0
  187. package/io/xlsb/pivot.js +1 -0
  188. package/io/xlsb/records.js +1 -0
  189. package/io/xlsb/sheet-ext.js +1 -0
  190. package/io/xlsb/sheet.js +1 -0
  191. package/io/xlsb/slicer.js +1 -0
  192. package/io/xlsb/styles.js +1 -0
  193. package/io/xlsb/workbook.js +1 -0
  194. package/io/xlsb/xml.js +2 -0
  195. package/io/xlsx-read.js +1 -1
  196. package/io/xlsx-styles.js +2 -2
  197. package/io/xlsx-tail.js +1 -1
  198. package/io/xlsx-write.js +2 -2
  199. package/io/xml-escape.js +1 -1
  200. package/io/xml-scan.js +2 -2
  201. package/io/zip-reader.js +1 -1
  202. package/objects/chart-model.js +1 -1
  203. package/objects/drawing-xml.js +1 -1
  204. package/package.json +1 -1
  205. package/pivot/calc-items.js +1 -0
  206. package/pivot/engine.js +1 -1
  207. package/pivot/xml.js +2 -2
  208. package/print/note-pages.js +2 -2
  209. package/print/page-setup.js +1 -1
  210. package/print/paginate.js +1 -1
  211. package/print/pdf-crypt.js +1 -0
  212. package/print/pdf-tags.js +1 -0
  213. package/print/pdf.js +24 -13
  214. package/print/render-page.js +3 -3
  215. package/print/shown-notes.js +1 -0
  216. package/shapes/form-xml.js +1 -1
  217. package/slicers/custom-styles.js +1 -1
  218. package/slicers/format.js +1 -1
  219. package/slicers/structured.js +1 -1
  220. package/slicers/write.js +1 -1
  221. package/table-view/files.js +1 -1
  222. package/table-view/mount.js +1 -1
  223. package/table-view/version.js +1 -1
  224. package/ui/icons.js +1 -1
  225. package/ui/menu-base.js +1 -1
  226. package/ui/protection-ui.js +1 -1
package/pivot/engine.js CHANGED
@@ -1 +1 @@
1
- import{withNoDataItems as ee}from"../slicers/pivot-file.js";import{dateOptionFlags as se}from"../slicers/date-filters.js";import{BOOL as at,CHUNK_BITS as Tt,CHUNK_MASK as Ct,EMPTY as H,ERR as ct,ERRORS as Ft,KIND_MASK as St,NUM as B,STR as Z}from"../core/sheet.js";import{formatGeneral as Vt,getFormatter as Pt,partsToSerial as ne,serialToParts as pt}from"../core/numfmt.js";import{MAX_COLS as re,MAX_ROWS as oe}from"../core/address.js";import{compareText as Ut,ERR as P,ERR_BY_INDEX as Rt,numberToText as le,XlError as $}from"../calc/values.js";import{FUNCS as ie}from"../calc/functions/registry.js";import"../calc/functions/index.js";import{t as G}from"../i18n/index.js";const k=-2,Qe=["sum","count","average","max","min","product","countNums","stdDev","stdDevp","var","varp"],Lt={sum:"Sum",count:"Count",average:"Average",max:"Max",min:"Min",product:"Product",countNums:"Count Numbers",stdDev:"StdDev",stdDevp:"StdDevp",var:"Var",varp:"Varp"},ae={...Lt,countNums:"Count"};function kt(c,t){switch(c){case"count":case"countNums":return G("pivot|Count of {field}",{field:t});case"average":return G("pivot|Average of {field}",{field:t});case"max":return G("pivot|Max of {field}",{field:t});case"min":return G("pivot|Min of {field}",{field:t});case"product":return G("pivot|Product of {field}",{field:t});case"stdDev":return G("pivot|StdDev of {field}",{field:t});case"stdDevp":return G("pivot|StdDevp of {field}",{field:t});case"var":return G("pivot|Var of {field}",{field:t});case"varp":return G("pivot|Varp of {field}",{field:t});default:return G("pivot|Sum of {field}",{field:t})}}const ze=[["normal","No Calculation"],["percentOfTotal","% of Grand Total"],["percentOfCol","% of Column Total"],["percentOfRow","% of Row Total"],["percent","% Of"],["percentOfParentRow","% of Parent Row Total"],["percentOfParentCol","% of Parent Column Total"],["percentOfParent","% of Parent Total"],["difference","Difference From"],["percentDiff","% Difference From"],["runTotal","Running Total In"],["percentOfRunningTotal","% Running Total In"],["rankAscending","Rank Smallest to Largest"],["rankDescending","Rank Largest to Smallest"],["index","Index"]],ce=new Set(["percent","percentOfParent","difference","percentDiff","runTotal","percentOfRunningTotal","rankAscending","rankDescending"]),Je=c=>ce.has(c),Ze=c=>c==="percent"||c==="difference"||c==="percentDiff",ue=new Set(["percentOfTotal","percentOfCol","percentOfRow","percent","percentOfParentRow","percentOfParentCol","percentOfParent","percentDiff","percentOfRunningTotal"]),ts=["captionEqual","captionNotEqual","captionBeginsWith","captionNotBeginsWith","captionEndsWith","captionNotEndsWith","captionContains","captionNotContains","captionGreaterThan","captionGreaterThanOrEqual","captionLessThan","captionLessThanOrEqual","captionBetween","captionNotBetween"],es=["valueEqual","valueNotEqual","valueGreaterThan","valueGreaterThanOrEqual","valueLessThan","valueLessThanOrEqual","valueBetween","valueNotBetween"],E={NONE:0,PAGE_LABEL:1,PAGE_VALUE:2,CORNER:3,HEADER_BLANK:4,COL_CAPTION:5,ROW_CAPTION:6,COL_ITEM:7,COL_SUBTOTAL:8,COL_GRAND:9,DATA_HEADER:10,ROW_ITEM:11,ROW_PARENT:12,ROW_SUBTOTAL:13,ROW_GRAND:14,DATA:15,DATA_PARENT:16,DATA_SUBTOTAL:17,DATA_GRAND_ROW:18,DATA_GRAND_COL:19,PLACEHOLDER:20},X=0,lt=1,st=2,mt=3,ss={ITEM:X,SUBTOTAL:lt,GRAND:st,BLANK:mt},Bt=1<<23,fe=1<<24,Nt="";class I extends Error{constructor(t,e){super(G(t,e))}}function ut(c){if(c==null)return"blank";switch(typeof c){case"number":return`n${c}`;case"string":return`s${c.toLowerCase()}`;case"boolean":return c?"b1":"b0";default:return`e${c.code}`}}const $t=c=>c===null?4:typeof c=="number"?0:typeof c=="string"?1:typeof c=="boolean"?2:3,he=[["sun","mon","tue","wed","thu","fri","sat"],["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],["january","february","march","april","may","june","july","august","september","october","november","december"]].map(c=>new Map(c.map((t,e)=>[t,e])));function de(c){let t=he,e=!1;for(const s of c){if(typeof s!="string")continue;e=!0;const n=s.toLowerCase();if(t=t.filter(r=>r.has(n)),t.length===0)return null}return e?t[0]:null}const Gt=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Wt=[31,29,31,30,31,30,31,31,30,31,30,31],pe=["seconds","minutes","hours","days","months","quarters","years"],me={seconds:"Seconds",minutes:"Minutes",hours:"Hours",days:"Days",months:"Months",quarters:"Quarters",years:"Years"};function we(c,t){let e=0;for(let s=0;s<c-1;s++)e+=Wt[s];return e+t-1}function ge(c,t,e){switch(c){case"years":{const s=[];for(let n=t;n<=e;n++)s.push(String(n));return s}case"quarters":return["Qtr1","Qtr2","Qtr3","Qtr4"];case"months":return Gt;case"days":{const s=[];return Wt.forEach((n,r)=>{for(let o=1;o<=n;o++)s.push(`${o}-${Gt[r]}`)}),s}case"hours":{const s=[];for(let n=0;n<24;n++)s.push(`${n%12===0?12:n%12} ${n<12?"AM":"PM"}`);return s}default:{const s=[];for(let n=0;n<60;n++)s.push(`:${n<10?"0":""}${n}`);return s}}}function ye(c,t,e){switch(c){case"years":return t.year-e;case"quarters":return Math.floor((t.month-1)/3);case"months":return t.month-1;case"days":return we(t.month,t.day);case"hours":return Math.floor(t.ms/36e5);case"minutes":return Math.floor(t.ms/6e4)%60;default:return Math.floor(t.ms/1e3)%60}}class ft{constructor(t,e,s){this.cache=t,this.index=e,this.name=s,this.numFmt="General",this.isDate=!1,this.kinds=null,this.uniformKind=H,this.nums=null,this.strs=null,this.shared=null,this.rawIds=null,this.ids=null,this.items=null,this.group=null,this.base=-1,this.par=-1,this.formula=null,this.calc=null,this.removed=!1,this.xml=null,this._keys=null,this._rank=null}get isVirtual(){return this.base>=0||this.formula!==null}get isCalculated(){return this.formula!==null}reset(){this.shared=null,this.rawIds=null,this.invalidate()}invalidate(){this.ids=null,this.items=null,this._keys=null,this._rank=null}ensureRaw(){if(this.rawIds!==null)return this;if(this.cache.load(),this.base>=0){const l=this.cache.fields[this.base].ensureRaw();return this.rawIds=l.rawIds,this.shared=l.shared,this}const t=this.cache.recordCount,e=new Int32Array(t),s=[],{kinds:n,nums:r,strs:o}=this;if(o!==null)Ae(this.cache,o,null,null,t,e,s);else if(r!==null&&n===null&&this.uniformKind===B){const l=new Map;let i=NaN,u=-1;for(let f=0;f<t;f++){const m=r[f];if(m!==i){let y=l.get(m);y===void 0&&(y=s.length,s.push(m),l.set(m,y)),i=m,u=y}e[f]=u}}else n!==null?ve(this.cache,n,r,t,e,s):t>0&&s.push(null);return this.rawIds=e,this.shared=s,this}ensure(){if(this.ids!==null)return this;if(this.ensureRaw(),this.group===null)return this.ids=this.rawIds,this.items=this.shared,this;const{map:t,labels:e}=_e(this),s=this.rawIds,n=s.length,r=new Int32Array(n);for(let o=0;o<n;o++)r[o]=t[s[o]];return this.ids=r,this.items=e,this.groupMap=t,this}ensureColumn(){if(this.nums!==null||this.strs!==null||this.rawIds===null)return this;if(this.base>=0)return this;const t=this.rawIds.length,e=new Uint8Array(t),s=new Float64Array(t),n=this.rawIds,r=this.shared,o=new Uint8Array(r.length),l=new Float64Array(r.length);r.forEach((i,u)=>{typeof i=="number"?(o[u]=B,l[u]=i):typeof i=="string"?o[u]=Z:typeof i=="boolean"?(o[u]=at,l[u]=i?1:0):i instanceof $&&(o[u]=ct,l[u]=i.index)});for(let i=0;i<t;i++){const u=n[i];e[i]=o[u],s[i]=l[u]}return this.kinds=e,this.nums=s,this}get keyIndex(){if(this._keys===null){this.ensure();const t=new Map;this.items.forEach((e,s)=>{const n=ut(e);t.has(n)||t.set(n,s)}),this._keys=t}return this._keys}keyOf(t){return ut(this.items[t])}labelOf(t){return this.labelOfValue(this.items[t])}labelOfValue(t){return t==null?"(blank)":typeof t=="string"?t:typeof t=="number"?this.numFmt!=="General"?Pt(this.numFmt).number(t):Vt(t):typeof t=="boolean"?t?"TRUE":"FALSE":t.code}rank(){if(this._rank!==null)return this._rank;this.ensure();const{items:t}=this,e=new Int32Array(t.length);if(this.group!==null&&this.group.kind!=="discrete")for(let s=0;s<e.length;s++)e[s]=s;else{const s=de(t),n=Array.from(t.keys());n.sort((r,o)=>be(t[r],t[o],s)),n.forEach((r,o)=>{e[r]=o})}return this._rank=e,e}}function be(c,t,e){const s=$t(c),n=$t(t);return s!==n?s-n:s===0?c-t:s===1?e!==null?e.get(c.toLowerCase())-e.get(t.toLowerCase()):Ut(c,t):s===2?c===t?0:c?1:-1:s===3?c.index-t.index:0}function Ae(c,t,e,s,n,r,o){let l=-1;for(let f=0;f<n;f++)t[f]>l&&(l=t[f]);const i=new Int32Array(l+1).fill(-1),u=new Map;for(let f=0;f<n;f++){const m=t[f];let y=i[m];if(y<0){const h=c.getString(m),a=h.toLowerCase();y=u.get(a),y===void 0&&(y=o.length,o.push(h),u.set(a,y)),i[m]=y}r[f]=y}}function ve(c,t,e,s,n,r){const o=new Map,l=new Map,i=new Map,u=new Map;let f=-1;for(let m=0;m<s;m++){const y=t[m];let h;if(y===B){const a=e[m];h=o.get(a),h===void 0&&(h=r.length,r.push(a),o.set(a,h))}else if(y===Z){const a=e[m];if(h=i.get(a),h===void 0){const d=c.getString(a),p=d.toLowerCase();h=l.get(p),h===void 0&&(h=r.length,r.push(d),l.set(p,h)),i.set(a,h)}}else if(y===H)f<0&&(f=r.length,r.push(null)),h=f;else{const a=y*100+e[m];h=u.get(a),h===void 0&&(h=r.length,r.push(y===at?e[m]!==0:Rt[e[m]]??P.NA),u.set(a,h))}n[m]=h}}function _e(c){const t=c.group,e=c.shared,s=new Int32Array(e.length);if(t.kind==="date"){const l=pt(t.start),i=pt(t.end),u=`<${qt(t.start)}`,f=`>${qt(t.end+1)}`,m=ge(t.part,l.year,i.year);let y=[u,...m,f];t.labels&&t.labels.length===y.length&&(y=t.labels);for(let h=0;h<e.length;h++){const a=e[h];typeof a!="number"||a<t.start?s[h]=0:a>=t.end+1?s[h]=y.length-1:s[h]=1+ye(t.part,pt(a),l.year)}return{map:s,labels:y}}if(t.kind==="bins"){const{start:l,end:i,interval:u}=t,f=Math.max(1,Math.ceil((i-l)/u-1e-9)),m=[`<${At(l)}`];for(let h=0;h<f;h++){const a=l+h*u,d=t.integer?Math.max(a+u-1,h===f-1?i:0):a+u;m.push(`${At(a)}-${At(d)}`)}m.push(`>${At(i)}`);const y=t.labels&&t.labels.length===m.length?t.labels:m;for(let h=0;h<e.length;h++){const a=e[h];typeof a!="number"||a<l?s[h]=0:a>i?s[h]=f+1:s[h]=1+Math.min(f-1,Math.floor((a-l)/u+1e-9))}return{map:s,labels:y}}const n=t.groups.map(l=>l.name),r=new Map;t.groups.forEach((l,i)=>{for(const u of l.keys)r.set(u,i)});const o=new Map;for(let l=0;l<e.length;l++){const i=ut(e[l]);let u=r.get(i);u===void 0&&(u=o.get(i),u===void 0&&(u=n.length,n.push(e[l]),o.set(i,u))),s[l]=u}return{map:s,labels:n}}const At=c=>le(Number(c.toPrecision(12)));function qt(c){const t=pt(c);return`${t.month}/${t.day}/${t.year}`}class Te{constructor(){this.list=[],this.index=new Map}get size(){return this.list.length}get(t){return this.list[t]??""}add(t){let e=this.index.get(t);return e===void 0&&(e=this.list.length,this.list.push(t),this.index.set(t,e)),e}}function Ce(c,t,e,s,n,r){const o=c.columns[t];if(o===void 0)return;const l=e+s;for(let i=e>>>Tt;i<=l-1>>>Tt;i++){const u=o[i];if(u===void 0)continue;const f=i<<Tt,m=Math.max(e,f)&Ct,y=Math.min(l-1,f+Ct)&Ct,h=f-e,a=u.kinds,d=u.values;for(let p=m;p<=y;p++)n[h+p]=a[p]&St,r[h+p]=d[p]}}function Re(c,t,e){const s=new Int32Array(t);let n=0;for(let r=0;r<t;r++)e(c+r)||(s[n++]=r);return n===t?null:s.subarray(0,n)}class gt{constructor(){this.fields=[],this.recordCount=0,this.strings=new Te,this.source=null,this.generation=0,this.xml=null,this.id=0,this.needsRefresh=!1,this.deferred=!1}getString(t){return this.strings.get(t)}field(t){if(typeof t=="number")return this.fields[t];const e=String(t).toLowerCase();return this.fields.find(s=>s.name.toLowerCase()===e&&!s.removed)}fieldIndex(t){if(typeof t=="number")return t;const e=this.field(t);if(!e)throw new I("Unknown field: {name}",{name:t});return e.index}static fromSheet(t,e,s){const n=new gt;return n.strings=t.strings,n.source={type:"range",book:t,sheet:e,range:s},n.refresh(),n}static fromTable(t,e){const s=new gt;return s.strings=t.strings,s.source={type:"table",book:t,table:e},s.refresh(),s}static fromRows(t,e){const s=new gt,n=e.length;return s.recordCount=n,t.forEach((r,o)=>{const l=new Uint8Array(n),i=new Float64Array(n);for(let f=0;f<n;f++){const m=e[f][o];typeof m=="number"?(l[f]=B,i[f]=m):typeof m=="string"?(l[f]=Z,i[f]=s.strings.add(m)):typeof m=="boolean"?(l[f]=at,i[f]=m?1:0):m instanceof $&&(l[f]=ct,i[f]=m.index)}const u=new ft(s,o,r);Ht(u,l,i,n),s.fields.push(u)}),s}static fromColumns(t,e,s){const n=new gt;return s&&(n.strings=s),n.recordCount=e,t.forEach((r,o)=>{const l=new ft(n,o,r.name);l.kinds=r.kinds??null,l.nums=r.nums??null,l.strs=r.strs??null,l.uniformKind=r.strs?Z:r.kinds?H:B,r.numFmt&&jt(l,r.numFmt),n.fields.push(l)}),n}require(){if(this.deferred&&!this.refresh())throw new I("The PivotTable report was saved without the underlying data. Its source is not available.")}snapshot(){const{fields:t,recordCount:e,strings:s,generation:n,needsRefresh:r,deferred:o}=this,l=t.map(i=>({f:i,state:{...i,group:i.group&&{...i.group}}}));return()=>{Object.assign(this,{fields:l.map(({f:i,state:u})=>Object.assign(i,u)),recordCount:e,strings:s,generation:n,needsRefresh:r,deferred:o})}}load(){if(!(!this.deferred||this.source===null))try{this.refresh()}catch(t){if(!(t instanceof I))throw t}}refresh(){const t=this.source;if(t===null){for(const a of this.fields)a.invalidate();return this.generation++,!1}const{book:e}=t;this.strings=e.strings;let s,n,r,o,l;if(t.type==="table"){const a=t.table;s=a.sheet??e.sheets[a.sheetIndex],n=a.r0,r=a.c0,o=a.r1-(a.totalsRows??0),l=a.c1}else{if({sheet:s}=t,typeof s=="string"&&(s=e.sheets.find(a=>a.name===t.sheet)),!s)throw new I("The PivotTable source sheet no longer exists.");({r0:n,c0:r,r1:o,c1:l}=t.range),o=Math.min(o,s.maxRow),l=Math.min(l,s.maxCol)}if(o<=n)throw new I("The PivotTable source needs a header row and at least one row of data.");if(t.headers&&t.headers.length!==l-r+1)throw new I("The PivotTable source needs a header for every column.");const i=o-n,u=t.skipRow?Re(n+1,i,t.skipRow):null,f=u?u.length:i;if(f===0)throw new I("The PivotTable source needs a header row and at least one row of data.");const m=new Map,y=[];for(let a=r;a<=l;a++){const d=t.headers?String(t.headers[a-r]).trim():Le(e,s,n,a);if(d==="")throw new I("The PivotTable field name is not valid: every source column needs a header.");const p=d.toLowerCase(),b=(m.get(p)??0)+1;m.set(p,b),y.push(b>1?`${d}${b}`:d)}const h=new Map(this.fields.filter(a=>!a.isVirtual).map(a=>[a.name.toLowerCase(),a]));this.recordCount=f,y.forEach((a,d)=>{let p=h.get(a.toLowerCase());p?h.delete(a.toLowerCase()):(p=new ft(this,this.fields.length,a),this.fields.push(p));const b=r+d;let w=new Uint8Array(i),g=new Float64Array(i);Ce(s,b,n+1,i,w,g),u&&(w=Uint8Array.from(u,A=>w[A]),g=Float64Array.from(u,A=>g[A])),Ht(p,w,g,f),p.removed=!1,p.reset();for(let A=0;A<f;A++)if(w[A]!==H){jt(p,e.styles.get(s.style(n+1+(u?u[A]:A),b)).numFmt);break}});for(const a of h.values())a.removed=!0,a.kinds=null,a.nums=null,a.strs=null,a.uniformKind=H,a.reset();for(const a of this.fields)a.isVirtual&&a.reset();return this.needsRefresh=!1,this.deferred=!1,this._rescaleGroups(),this.generation++,!0}_rescaleGroups(){for(const t of this.fields){const e=t.group;if(t.base>=0||t.removed||e===null||e.kind==="discrete"||!(e.autoStart||e.autoEnd))continue;let s;try{s=this._numericRange(t)}catch{continue}for(let n=t;n;n=n.par>=0?this.fields[n.par]:null){const r=n.group;r.autoStart&&(r.start=e.kind==="date"?Math.floor(s.min):s.min),r.autoEnd&&(r.end=e.kind==="date"?Math.floor(s.max):s.max),r.labels=void 0}}}renameFields(t){const e=new Map(Object.entries(t).map(([s,n])=>[s.toLowerCase(),n]));for(const s of this.fields)s.isCalculated?(s.formula=Ne(s.formula,e),s.calc=null):s.isVirtual||(s.name=e.get(s.name.toLowerCase())??s.name);this.generation++}addCalculatedField(t,e){const s=new ft(this,this.fields.length,this._uniqueName(t));return s.formula=e.replace(/^\s*=\s*/,""),s.calc=Et(s.formula,this),this.fields.push(s),s.index}updateCalculatedField(t,e){const s=this.fields[t],n=e.replace(/^\s*=\s*/,"");s.calc=Et(n,this),s.formula=n,this.generation++}_uniqueName(t){let e=t,s=2;for(;this.fields.some(n=>n.name.toLowerCase()===e.toLowerCase());)e=`${t}${s++}`;return e}_numericRange(t){t.ensureRaw();let e=1/0,s=-1/0,n=!0;for(const r of t.shared){if(typeof r!="number")throw new I("Cannot group that selection.");r<e&&(e=r),r>s&&(s=r),Number.isInteger(r)||(n=!1)}if(e===1/0)throw new I("Cannot group that selection.");return{min:e,max:s,integer:n}}groupDates(t,e,{start:s,end:n}={}){const r=this.fields[t];if(r.isCalculated||r.base>=0)throw new I("Cannot group that selection.");const{min:o,max:l}=this._numericRange(r),i=pe.filter(y=>e.includes(y));if(i.length===0)throw new I("Choose at least one grouping unit.");this.ungroup(t);const u={start:s??Math.floor(o),end:n??Math.floor(l)};r.group={kind:"date",part:i[0],...u,autoStart:s===void 0,autoEnd:n===void 0},r.invalidate();const f=[t];let m=r;for(const y of i.slice(1)){const h=new ft(this,this.fields.length,this._uniqueName(me[y]));h.base=t,h.group={kind:"date",part:y,...u,autoStart:s===void 0,autoEnd:n===void 0},this.fields.push(h),m.par=h.index,m=h,f.unshift(h.index)}return f}groupNumbers(t,{start:e,end:s,interval:n=10}={}){const r=this.fields[t];if(r.isCalculated||r.base>=0)throw new I("Cannot group that selection.");if(!(n>0))throw new I("The grouping interval must be greater than zero.");const{min:o,max:l,integer:i}=this._numericRange(r);this.ungroup(t);const u=e??o,f=s??l;if(f<=u)throw new I("The ending value must be greater than the starting value.");return r.group={kind:"bins",start:u,end:f,interval:n,integer:i&&Number.isInteger(u)&&Number.isInteger(n),autoStart:e===void 0,autoEnd:s===void 0},r.invalidate(),t}groupText(t,e,s){const n=this.fields[t];if(n.isCalculated)throw new I("Cannot group that selection.");n.ensureRaw();let r=n.par>=0?this.fields[n.par]:null;if(r&&r.group?.kind!=="discrete")throw new I("Cannot group that selection.");return r?(r.group.groups.push(...e),r.invalidate(),r.index):(r=new ft(this,this.fields.length,this._uniqueName(s??`${n.name}2`)),r.base=t,r.group={kind:"discrete",groups:e.map(o=>({name:o.name,keys:[...o.keys]}))},this.fields.push(r),n.par=r.index,r.index)}ungroup(t){const e=this.fields[t];if(e.base>=0&&e.group?.kind==="discrete"){this.fields[e.base].par=-1,e.removed=!0,e.group={kind:"discrete",groups:[]},e.invalidate();return}e.group=null,e.invalidate();let s=e.par;for(e.par=-1;s>=0;){const n=this.fields[s];n.removed=!0,s=n.par,n.par=-1}}}function jt(c,t){c.numFmt=t??"General";try{c.isDate=c.numFmt!=="General"&&Pt(c.numFmt).isDate===!0}catch{c.isDate=!1}}function Le(c,t,e,s){const n=t.kind(e,s)&St,r=t.value(e,s);return n===Z?c.strings.get(r).trim():n===B?Vt(r):n===at?r?"TRUE":"FALSE":n===ct?Ft[r]??"":""}function Ht(c,t,e,s){let n=0,r=0;for(let o=0;o<s;o++){const l=t[o];l===B?n++:l===Z&&r++}if(c.strs=null,c.kinds=null,c.nums=null,n===s&&s>0)c.uniformKind=B,c.nums=e;else if(r===s&&s>0){c.uniformKind=Z;const o=new Int32Array(s);for(let l=0;l<s;l++)o[l]=e[l];c.strs=o}else c.uniformKind=H,c.kinds=t,c.nums=e}const ke=["<=",">=","<>","+","-","*","/","^","%","(",")",",","=","<",">","&"];function Ne(c,t){return c.replace(/"(?:[^"]|"")*"|'((?:[^']|'')*)'|[\p{L}_\\][\p{L}\p{N}_.\\]*(?!\s*\(|[\p{L}\p{N}_.\\])/gu,(e,s)=>{if(e[0]==='"')return e;const n=t.get((s===void 0?e:s.replace(/''/g,"'")).toLowerCase());return n===void 0?e:`'${n.replace(/'/g,"''")}'`})}function xe(c){const t=[];let e=0;for(;e<c.length;){const s=c[e];if(s<=" ")e++;else if(s>="0"&&s<="9"||s==="."&&c[e+1]>="0"&&c[e+1]<="9"){const n=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(c.slice(e));t.push({t:"num",v:Number(n[0])}),e+=n[0].length}else if(s==="'"||s==='"'){let n=e+1,r="";for(;;){if(n>=c.length)throw new I("The formula has an unmatched quote.");if(c[n]===s){if(c[n+1]!==s)break;n++}r+=c[n++]}t.push({t:s==="'"?"name":"str",v:r}),e=n+1}else if(/[\p{L}_\\]/u.test(s)){const n=/^[\p{L}\p{N}_.\\]+/u.exec(c.slice(e));t.push({t:"name",v:n[0],bare:!0}),e+=n[0].length}else{const n=ke.find(r=>c.startsWith(r,e));if(!n)throw new I("The formula has an unexpected character: {char}",{char:s});t.push({t:"op",v:n}),e+=n.length}}return t}const Kt=c=>c instanceof $?c:null,S=c=>{if(typeof c=="number")return c;if(typeof c=="boolean")return c?1:0;if(c===null)return 0;if(c instanceof $)throw c;const t=Number(c);if(typeof c=="string"&&c.trim()!==""&&!Number.isNaN(t))return t;throw P.VALUE},Yt={IF:c=>{const t=c[0]();if(Kt(t))throw t;return(typeof t=="number"?t!==0:t===!0)?c[1]?c[1]():!0:c[2]?c[2]():!1},IFERROR:c=>{try{const t=c[0]();return Kt(t)?c[1]():t}catch(t){if(t instanceof $)return c[1]();throw t}},AND:c=>c.every(t=>S(t())!==0),OR:c=>c.some(t=>S(t())!==0),NOT:c=>S(c[0]())===0,SUM:c=>c.reduce((t,e)=>t+S(e()),0),MIN:c=>Math.min(...c.map(t=>S(t()))),MAX:c=>Math.max(...c.map(t=>S(t()))),AVERAGE:c=>c.reduce((t,e)=>t+S(e()),0)/c.length,COUNT:c=>c.length,TRUE:()=>!0,FALSE:()=>!1},xt=new Set;function Xt(c,t){if(c.calc)return c.calc;if(xt.has(c))throw new I("The formula is not valid.");xt.add(c);try{c.calc=Et(c.formula,t)}finally{xt.delete(c)}return c.calc}function Et(c,t){const e=xe(c);let s=0;const n=new Set,r=w=>e[s]?.t==="op"&&e[s].v===w,o=()=>new I("The formula is not valid."),l=w=>{const g=t.fields.find(v=>v.name.toLowerCase()===w.v.toLowerCase()&&!v.isCalculated),A=t.fields.find(v=>v.name.toLowerCase()===w.v.toLowerCase()&&v.isCalculated);if(A){Xt(A,t);for(const v of A.calc.refs)n.add(v);return v=>A.calc.fn(v)}if(!g)throw new I("The formula refers to an unknown field: {name}",{name:w.v});n.add(g.index);const _=g.index;return v=>v(_)},i=()=>{const w=e[s];if(!w)throw o();if(w.t==="num"){s++;const g=w.v;return()=>g}if(w.t==="str"){s++;const g=w.v;return()=>g}if(w.t==="name"){if(s++,w.bare&&r("(")){s++;const g=[];if(!r(")"))for(g.push(a());r(",");)s++,g.push(a());if(!r(")"))throw o();return s++,d(w.v.toUpperCase(),g)}if(w.bare&&p.has(w.v.toUpperCase())&&!t.field(w.v)){const g=Yt[w.v.toUpperCase()];return()=>g([])}return l(w)}if(r("(")){s++;const g=a();if(!r(")"))throw o();return s++,g}throw o()},u=()=>{let w=i();for(;r("%");){s++;const g=w;w=A=>S(g(A))/100}return w},f=()=>{if(r("-")){s++;const w=f();return g=>-S(w(g))}return r("+")?(s++,f()):u()},m=()=>{let w=f();for(;r("^");){s++;const g=w,A=f();w=_=>{const v=S(g(_))**S(A(_));if(!Number.isFinite(v))throw P.NUM;return v}}return w},y=()=>{let w=m();for(;r("*")||r("/");){const g=e[s++].v,A=w,_=m();w=g==="*"?v=>S(A(v))*S(_(v)):v=>{const N=S(_(v));if(N===0)throw P.DIV0;return S(A(v))/N}}return w},h=()=>{let w=y();for(;r("+")||r("-");){const g=e[s++].v,A=w,_=y();w=g==="+"?v=>S(A(v))+S(_(v)):v=>S(A(v))-S(_(v))}return w},a=()=>{let w=h();for(;e[s]?.t==="op"&&["=","<>","<",">","<=",">="].includes(e[s].v);){const g=e[s++].v,A=w,_=h();w=v=>{const N=S(A(v)),R=S(_(v));switch(g){case"=":return N===R;case"<>":return N!==R;case"<":return N<R;case">":return N>R;case"<=":return N<=R;default:return N>=R}}}return w},d=(w,g)=>{const A=Yt[w];if(A)return v=>A(g.map(N=>()=>N(v)));const _=ie.get(w);if(!_||_.kind!=="lift")throw new I("The formula uses a function a calculated field can't call: {name}",{name:w});if(g.length<_.min||g.length>_.max)throw o();return v=>{const N=g.map(R=>R(v));for(const R of N)if(R instanceof $)throw R;return _.fn(...N)}},p=new Set(["TRUE","FALSE"]),b=a();if(s<e.length)throw o();return{fn:b,refs:[...n]}}const Ee={sum:"sum",average:"sum",count:"",countNums:"",max:"mm",min:"mm",product:"prod",stdDev:"var",stdDevp:"var",var:"var",varp:"var"};class Ot{constructor(t,e){this.size=t,this.cnt=new Int32Array(t),this.num=new Int32Array(t),this.sum=e.sum?new Float64Array(t):null,this.min=e.mm?new Float64Array(t).fill(1/0):null,this.max=e.mm?new Float64Array(t).fill(-1/0):null,this.prod=e.prod?new Float64Array(t).fill(1):null,this.mean=e.var?new Float64Array(t):null,this.m2=e.var?new Float64Array(t):null,this.err=null}merge(t,e,s){const n=e.cnt[s];if(n===0)return;this.cnt[t]+=n;const r=e.num[s],o=this.num[t];if(this.num[t]=o+r,e.err!==null&&e.err[s]!==0&&(this.err===null&&(this.err=new Int8Array(this.size)),this.err[t]===0&&(this.err[t]=e.err[s])),r!==0&&(this.sum!==null&&(this.sum[t]+=e.sum[s]),this.min!==null&&(e.min[s]<this.min[t]&&(this.min[t]=e.min[s]),e.max[s]>this.max[t]&&(this.max[t]=e.max[s])),this.prod!==null&&(this.prod[t]*=e.prod[s]),this.mean!==null)){const l=e.mean[s]-this.mean[t],i=o+r;this.m2[t]+=e.m2[s]+l*l*o*r/i,this.mean[t]+=l*r/i}}value(t,e){const s=this.cnt[t];if(s===0)return null;if(e==="count")return s;if(e==="countNums")return this.num[t];if(this.err!==null&&this.err[t]!==0)return Rt[this.err[t]-1];const n=this.num[t];switch(e){case"sum":return this.sum[t];case"average":return n===0?P.DIV0:this.sum[t]/n;case"max":return n===0?0:this.max[t];case"min":return n===0?0:this.min[t];case"product":return n===0?0:this.prod[t];case"stdDev":return n<2?P.DIV0:Math.sqrt(this.m2[t]/(n-1));case"stdDevp":return n<1?P.DIV0:Math.sqrt(this.m2[t]/n);case"var":return n<2?P.DIV0:this.m2[t]/(n-1);case"varp":return n<1?P.DIV0:this.m2[t]/n;default:return null}}}function Oe(c,t,e,s){const{cnt:n,num:r}=c;t.base<0&&t.ensureColumn();const{kinds:o,nums:l}=t;if(l===null||t.base>=0){for(let a=0;a<s;a++){const d=e[a];d>=0&&n[d]++}return}if(o===null){for(let a=0;a<s;a++){const d=e[a];d>=0&&n[d]++}r.set(n)}else for(let a=0;a<s;a++){const d=e[a];if(d<0)continue;const p=o[a];p!==H&&(n[d]++,p===B?r[d]++:p===ct&&(c.err===null&&(c.err=new Int8Array(c.size)),c.err[d]===0&&(c.err[d]=l[a]+1)))}const{sum:i,min:u,max:f,prod:m,mean:y,m2:h}=c;if(i!==null)if(o===null)for(let a=0;a<s;a++){const d=e[a];d>=0&&(i[d]+=l[a])}else for(let a=0;a<s;a++){const d=e[a];d>=0&&o[a]===B&&(i[d]+=l[a])}if(u!==null)for(let a=0;a<s;a++){const d=e[a];if(d<0||o!==null&&o[a]!==B)continue;const p=l[a];p<u[d]&&(u[d]=p),p>f[d]&&(f[d]=p)}if(m!==null)for(let a=0;a<s;a++){const d=e[a];d>=0&&(o===null||o[a]===B)&&(m[d]*=l[a])}if(y!==null){const a=new Int32Array(c.size);for(let d=0;d<s;d++){const p=e[d];if(p<0||o!==null&&o[d]!==B)continue;const b=++a[p],w=l[d]-y[p];y[p]+=w/b,h[p]+=w*(l[d]-y[p])}}}class Ie{constructor(t,e,s){this.fields=e,this.slots=s,this.k=e.length,this.leaf=null,this.nLeaves=1,this.levelBase=[1],this.nNodes=1,this.parent=new Int32Array([-1]),this.item=new Int32Array([-1]),this.depth=new Uint8Array(1),this.cache=t,this.alive=null,this.childStart=null,this.childList=null,this.pos=null,this._childIndex=null,this.lines=null}leafNode(t){return this.k===0?0:this.levelBase[this.k-1]+t}ancestorAt(t,e){let s=t;for(;this.depth[s]>e;)s=this.parent[s];return this.depth[s]===e?s:-1}fieldAt(t){return this.cache.fields[this.fields[t-1]]}children(t){return this.childList.subarray(this.childStart[t],this.childStart[t+1])}findChild(t,e){if(this._childIndex===null){const s=new Map;this.stride=1;for(const n of this.fields)this.stride=Math.max(this.stride,this.cache.fields[n].items.length+1);for(let n=1;n<this.nNodes;n++)this.alive[n]&&s.set(this.parent[n]*this.stride+this.item[n],n);this._childIndex=s}return this._childIndex.get(t*this.stride+e)??-1}pathKeys(t){const e=[];for(let s=t;s>0;s=this.parent[s])e.push(this.fieldAt(this.depth[s]).keyOf(this.item[s]));return e.reverse()}peer(t,e,s){if(s<0)return-1;if(this.depth[t]===e)return s;const n=[];for(let o=t;this.depth[o]>e;o=this.parent[o])n.push(this.item[o]);let r=s;for(let o=n.length-1;o>=0&&r>=0;o--)r=this.findChild(r,n[o]);return r}}function Qt(c,t,e,s,n,r=null){const o=new Ie(c,t,e),l=t.length;if(l===0)return o;let i=null,u=1;const f=[];for(let h=0;h<l;h++){const a=c.fields[t[h]].ensure(),d=a.ids,p=a.items.length,b=u*p,w=new Int32Array(s),g=Math.min(b,Math.max(s,1)),A=new Int32Array(g),_=new Int32Array(g);let v=0;if(b<=Bt){const F=new Int32Array(b).fill(-1);if(i===null)for(let C=0;C<s;C++){if(n!==null&&n[C]===0){w[C]=-1;continue}const x=d[C];let U=F[x];U<0&&(U=v++,F[x]=U,_[U]=x),w[C]=U}else for(let C=0;C<s;C++){const x=i[C];if(x<0){w[C]=-1;continue}const U=x*p+d[C];let M=F[U];M<0&&(M=v++,F[U]=M,A[M]=x,_[M]=d[C]),w[C]=M}}else{const F=new Map;for(let C=0;C<s;C++){const x=i===null?0:i[C];if(x<0||i===null&&n!==null&&n[C]===0){w[C]=-1;continue}const U=x*p+d[C];let M=F.get(U);M===void 0&&(M=v++,F.set(U,M),A[M]=x,_[M]=d[C]),w[C]=M}}const N=r?.(t[h]),R=N?ee({parents:A,items:_,count:v},u,p,N.hide):{parents:A,items:_,count:v};f.push(R),i=w,u=Math.max(R.count,1)}o.leaf=i,o.nLeaves=f[l-1].count;let m=1;const y=[];for(const h of f)y.push(m),m+=h.count;return o.levelBase=y,o.nNodes=m,o.parent=new Int32Array(m),o.item=new Int32Array(m),o.depth=new Uint8Array(m),o.parent[0]=-1,o.item[0]=-1,f.forEach((h,a)=>{const d=y[a],p=a===0?0:y[a-1];for(let b=0;b<h.count;b++)o.parent[d+b]=a===0?0:p+h.parents[b],o.item[d+b]=h.items[b],o.depth[d+b]=a+1}),o}class Me{constructor(t=1024){this.count=0,this.capacity=t,this.rows=new Int32Array(t),this.cols=new Int32Array(t),this.kinds=new Uint8Array(t),this.values=new Float64Array(t),this.roles=new Uint8Array(t),this.levels=new Uint8Array(t),this.formats=new Uint16Array(t),this.texts=[],this._textIndex=new Map,this.formatList=["General"],this._formatIndex=new Map([["General",0]])}_grow(){const t=this.capacity*2,e=(s,n)=>{const r=new s(t);return r.set(n),r};this.rows=e(Int32Array,this.rows),this.cols=e(Int32Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.values=e(Float64Array,this.values),this.roles=e(Uint8Array,this.roles),this.levels=e(Uint8Array,this.levels),this.formats=e(Uint16Array,this.formats),this.capacity=t}format(t){let e=this._formatIndex.get(t);return e===void 0&&(e=this.formatList.length,this.formatList.push(t),this._formatIndex.set(t,e)),e}text(t){let e=this._textIndex.get(t);return e===void 0&&(e=this.texts.length,this.texts.push(t),this._textIndex.set(t,e)),e}push(t,e,s,n,r,o=0,l=0){this.count===this.capacity&&this._grow();const i=this.count++;this.rows[i]=t,this.cols[i]=e,this.kinds[i]=s,this.values[i]=n,this.roles[i]=r,this.levels[i]=o,this.formats[i]=l}pushValue(t,e,s,n,r=0,o=0){s==null?this.push(t,e,H,0,n,r,o):typeof s=="number"?this.push(t,e,B,s,n,r,o):typeof s=="string"?this.push(t,e,Z,this.text(s),n,r,o):typeof s=="boolean"?this.push(t,e,at,s?1:0,n,r,o):this.push(t,e,ct,s.index,n,r,o)}valueAt(t){switch(this.kinds[t]){case B:return this.values[t];case Z:return this.texts[this.values[t]];case at:return this.values[t]!==0;case ct:return Ft[this.values[t]]??"#N/A";default:return null}}}function zt(c){const t=c.replace(/[.+^${}()|[\]\\*?~]/g,e=>e==="*"?".*":e==="?"?".":`\\${e}`);return new RegExp(`^${t}$`,"is")}const Jt=c=>c.replace(/[.+^${}()|[\]\\]/g,"\\$&");function De(c){const{op:t}=c,e=String(c.value??""),s=String(c.value2??""),n=e.split(/([*?])/).map(o=>o==="*"?".*":o==="?"?".":Jt(o)).join(""),r=(o,l,i)=>{const u=typeof l=="number"?l:Number.NaN,f=i.trim()===""?Number.NaN:Number(i);return!Number.isNaN(u)&&!Number.isNaN(f)?u-f:Ut(o,i)};switch(t){case"captionEqual":{const o=zt(e);return l=>o.test(l)}case"captionNotEqual":{const o=zt(e);return l=>!o.test(l)}case"captionBeginsWith":{const o=new RegExp(`^${n}`,"is");return l=>o.test(l)}case"captionNotBeginsWith":{const o=new RegExp(`^${n}`,"is");return l=>!o.test(l)}case"captionEndsWith":{const o=new RegExp(`${n}$`,"is");return l=>o.test(l)}case"captionNotEndsWith":{const o=new RegExp(`${n}$`,"is");return l=>!o.test(l)}case"captionContains":{const o=new RegExp(n,"is");return l=>o.test(l)}case"captionNotContains":{const o=new RegExp(n,"is");return l=>!o.test(l)}case"captionGreaterThan":return(o,l)=>r(o,l,e)>0;case"captionGreaterThanOrEqual":return(o,l)=>r(o,l,e)>=0;case"captionLessThan":return(o,l)=>r(o,l,e)<0;case"captionLessThanOrEqual":return(o,l)=>r(o,l,e)<=0;case"captionBetween":return(o,l)=>r(o,l,e)>=0&&r(o,l,s)<=0;case"captionNotBetween":return(o,l)=>r(o,l,e)<0||r(o,l,s)>0;default:return()=>!0}}function Fe(c){const t=Number(c.value),e=Number(c.value2);switch(c.op){case"valueEqual":return s=>s===t;case"valueNotEqual":return s=>s!==t;case"valueGreaterThan":return s=>s>t;case"valueGreaterThanOrEqual":return s=>s>=t;case"valueLessThan":return s=>s<t;case"valueLessThanOrEqual":return s=>s<=t;case"valueBetween":return s=>s>=Math.min(t,e)&&s<=Math.max(t,e);case"valueNotBetween":return s=>s<Math.min(t,e)||s>Math.max(t,e);default:return()=>!0}}function wt(c,t){if(!t)return null;const e=t.hidden&&t.hidden.length>0;if(!e&&!t.labelFilter)return null;c.ensure();const s=new Uint8Array(c.items.length);if(e){const n=c.keyIndex;for(const r of t.hidden){const o=n.get(r);o!==void 0&&(s[o]=1)}}if(t.labelFilter){const n=De(t.labelFilter);c.items.forEach((r,o)=>{n(c.labelOfValue(r),r)||(s[o]=1)})}return s}function Zt(c,t){return c.ensureRaw(),se(c.shared,t)}class Se{constructor(t,e){this.rows=t,this.cols=e,this.dense=t*e<=fe,this.map=this.dense?null:new Map,this.size=this.dense?t*e:0}ensure(t,e){const s=t*this.cols+e;if(this.dense)return s;let n=this.map.get(s);return n===void 0&&(n=this.size++,this.map.set(s,n)),n}get(t,e){const s=t*this.cols+e;return this.dense?s:this.map.get(s)??-1}}class Ve{constructor(t){this.pivot=t,this.cache=t.cache,this.spec=t.spec,this._aggregate(),this._arrange()}opts(t){return this.spec.fieldOptions[t]??null}_resolveData(){const{cache:t,spec:e}=this,s=new Map,n=(o,l)=>{let i=s.get(o);i===void 0&&(i={sum:!1,mm:!1,prod:!1,var:!1},s.set(o,i));const u=Ee[l];u&&(i[u]=!0)},r=new Set;for(const o of Object.keys(e.fieldOptions)){const l=e.fieldOptions[o].subtotals;if(Array.isArray(l))for(const i of l)r.add(i)}this.data=e.values.map((o,l)=>{const i=t.fields[o.field],u={index:l,field:o.field,name:o.name,agg:o.agg,showAs:o.showAs??null,numFmt:o.numFmt??null,calc:null};if(i.isCalculated){u.calc=Xt(i,t);for(const f of u.calc.refs)n(f,"sum")}else{n(o.field,o.agg);for(const f of r)n(o.field,f)}return u}),this.needs=s}_recordMask(t){const{spec:e,cache:s}=this;let n=null;for(const r of Object.keys(e.fieldOptions)){const o=s.fields[r];if(!o||o.removed||o.isCalculated)continue;const l=wt(o,e.fieldOptions[r]);if(l!==null){n===null&&(n=new Uint8Array(t).fill(1));const i=o.ensure().ids;for(let u=0;u<t;u++)l[i[u]]===1&&(n[u]=0)}if(e.fieldOptions[r].range||e.fieldOptions[r].dateFilter){n===null&&(n=new Uint8Array(t).fill(1));const i=Zt(o,e.fieldOptions[r]),u=o.rawIds;for(let f=0;f<t;f++)i[u[f]]===1&&(n[f]=0)}}return n}_aggregate(){const{cache:t,spec:e}=this,s=t.recordCount;this._resolveData();const n=this.data.length,r=g=>g.filter(A=>A!==k||n>1);let o=r(e.rows),l=r(e.cols);n>1&&!o.includes(k)&&!l.includes(k)&&(l=[...l,k]),o=o.filter(g=>g===k||!t.fields[g].removed),l=l.filter(g=>g===k||!t.fields[g].removed);const i=this._recordMask(s);this.mask=i;const u=g=>{const A=e.fieldOptions[g];return A?.showAll?{hide:wt(t.fields[g],A)}:null},f=Qt(t,o.filter(g=>g!==k),o,s,i,u),m=Qt(t,l.filter(g=>g!==k),l,s,i,u);this.rows=f,this.cols=m;let y,h,a,d;const p=f.nLeaves,b=m.nLeaves;if(f.leaf!==null&&m.leaf!==null){const g=f.leaf,A=m.leaf;y=new Int32Array(s);const _=p*b,v=Math.min(_,Math.max(s,1));if(h=new Int32Array(v),a=new Int32Array(v),d=0,_<=Bt){const N=new Int32Array(_).fill(-1);for(let R=0;R<s;R++){const F=g[R];if(F<0){y[R]=-1;continue}const C=F*b+A[R];let x=N[C];x<0&&(x=d++,N[C]=x,h[x]=F,a[x]=A[R]),y[R]=x}}else{const N=new Map;for(let R=0;R<s;R++){const F=g[R];if(F<0){y[R]=-1;continue}const C=F*b+A[R];let x=N.get(C);x===void 0&&(x=d++,N.set(C,x),h[x]=F,a[x]=A[R]),y[R]=x}}}else if(f.leaf!==null||m.leaf!==null){y=f.leaf??m.leaf,d=f.leaf!==null?p:b;const g=new Int32Array(d);for(let _=0;_<d;_++)g[_]=_;const A=new Int32Array(d);h=f.leaf!==null?g:A,a=f.leaf!==null?A:g}else{if(y=new Int32Array(s),d=1,i!==null)for(let g=0;g<s;g++)i[g]===0&&(y[g]=-1);h=new Int32Array(1),a=new Int32Array(1)}this.cellCount=d,this.cellRow=h,this.cellCol=a,this.cells=y;const w=new Map;for(const[g,A]of this.needs){const _=new Ot(d,A);Oe(_,t.fields[g],y,s),w.set(g,_)}this.leafAccs=w,this._applyValueFilters(),this._rollUp()}_slotValue(t,e,s,n){if(t.calc!==null){let r=!1;const o=l=>{const i=e.get(l);if(i.cnt[s]!==0&&(r=!0),i.err!==null&&i.err[s]!==0)throw Rt[i.err[s]-1];return i.sum[s]};try{const l=t.calc.fn(o);return r?typeof l=="number"?Number.isFinite(l)?l:P.NUM:typeof l=="boolean"?l?1:0:l instanceof $?l:P.VALUE:null}catch(l){if(l instanceof $)return l;throw l}}return e.get(t.field).value(s,n??t.agg)}_applyValueFilters(){const{rows:t,cols:e,data:s}=this;this.rowDead=new Uint8Array(t.nNodes),this.colDead=new Uint8Array(e.nNodes);const n=(r,o,l)=>{for(let i=1;i<=r.k;i++){const u=r.fields[i-1],f=this.opts(u);if(!f||!f.valueFilter&&!f.top)continue;const m=f.valueFilter??f.top,y=s[m.data??0];if(!y)continue;const h=this._nodeAccs(r,y,l),a=r.levelBase[i-1],d=i<r.k?r.levelBase[i]:r.nNodes,p=new Map;for(let b=a;b<d;b++){if(o[b]||o[r.parent[b]]){o[b]=1;continue}const w=r.parent[b];let g=p.get(w);g===void 0&&(g=[],p.set(w,g)),g.push(b)}for(const b of p.values()){const w=g=>{const A=this._slotValue(y,h,g,null);return typeof A=="number"?A:null};if(f.valueFilter){const g=Fe(f.valueFilter);for(const A of b){const _=w(A);(_===null||!g(_))&&(o[A]=1)}}if(f.top){const g=b.filter(A=>!o[A]);for(const A of Ue(g,w,f.top,!0))o[A]=1}}for(let b=d;b<r.nNodes;b++)o[r.parent[b]]&&(o[b]=1)}};n(t,this.rowDead,!0),n(e,this.colDead,!1)}_nodeAccs(t,e,s){const n=e.calc!==null?e.calc.refs:[e.field],r=new Map;for(const a of n)r.set(a,new Ot(t.nNodes,this.needs.get(a)));const o=[...r.entries()].map(([a,d])=>[d,this.leafAccs.get(a)]),{cellRow:l,cellCol:i,rows:u,cols:f,rowDead:m,colDead:y}=this,h=s?l:i;for(let a=0;a<this.cellCount;a++){const d=u.leafNode(l[a]),p=f.leafNode(i[a]);if(m[d]||y[p])continue;let b=t.leafNode(h[a]);for(;b>=0;){for(const[w,g]of o)w.merge(b,g,a);b=t.parent[b]}}return r}_rollUp(){const{rows:t,cols:e,cellRow:s,cellCol:n,rowDead:r,colDead:o,cellCount:l}=this,i=new Uint8Array(t.nNodes),u=new Uint8Array(e.nNodes),f=new Se(t.nNodes,e.nNodes),m=t.parent,y=e.parent,h=new Uint8Array(l);for(let w=0;w<l;w++){const g=t.leafNode(s[w]),A=e.leafNode(n[w]);if(!(r[g]||o[A])){h[w]=1;for(let _=g;_>=0;_=m[_])if(i[_]=1,!f.dense)for(let v=A;v>=0;v=y[v])f.ensure(_,v);for(let _=A;_>=0;_=y[_])u[_]=1}}t.alive=i,e.alive=u;const a=new Map,d=[];for(const[w,g]of this.needs){const A=new Ot(Math.max(f.size,1),g);a.set(w,A),d.push([A,this.leafAccs.get(w)])}const p=f.dense,b=f.cols;for(let w=0;w<l;w++){if(h[w]===0)continue;const g=t.leafNode(s[w]),A=e.leafNode(n[w]);for(let _=g;_>=0;_=m[_])for(let v=A;v>=0;v=y[v]){const N=p?_*b+v:f.get(_,v);for(let R=0;R<d.length;R++)d[R][0].merge(N,d[R][1],w)}}this.slots=f,this.accs=a,this.cells=null,t.leaf=null,e.leaf=null}raw(t,e,s,n=null){if(e<0||s<0)return null;const r=this.slots.get(e,s);return r<0?null:this._slotValue(t,this.accs,r,n)}_baseLoc(t){if(t._loc!==void 0)return t._loc;const e=t.showAs?.baseField;let s=null;if(e!=null&&e>=0){let n=this.rows.fields.indexOf(e);n>=0?s={tree:this.rows,isRow:!0,depth:n+1}:(n=this.cols.fields.indexOf(e),n>=0&&(s={tree:this.cols,isRow:!1,depth:n+1}))}return t._loc=s,s}show(t,e,s,n=null){const r=t.showAs?.type;if(!r||r==="normal")return this.raw(t,e,s,n);const o=this.raw(t,e,s,n);if(o instanceof $)return o;const l=(p,b)=>this.raw(t,p,b,n),i=p=>p instanceof $?p:o===null?p===null?null:0:p===null||p===0?P.DIV0:o/p;switch(r){case"percentOfTotal":return i(l(0,0));case"percentOfCol":return i(l(0,s));case"percentOfRow":return i(l(e,0));case"percentOfParentRow":return i(e===0?o:l(this.rows.parent[e],s));case"percentOfParentCol":return i(s===0?o:l(e,this.cols.parent[s]));case"index":{const p=l(0,0),b=l(e,0),w=l(0,s);return[p,b,w].some(g=>g instanceof $)?P.VALUE:!b||!w?P.DIV0:(o??0)*p/(b*w)}default:}const u=this._baseLoc(t);if(u===null)return P.NA;const{tree:f,isRow:m,depth:y}=u,h=m?e:s;if(f.depth[h]<y)return null;const a=p=>m?l(p,s):l(e,p),d=f.ancestorAt(h,y);switch(r){case"percentOfParent":return i(a(d));case"percent":case"difference":case"percentDiff":{const p=this._baseSibling(t,f,d,y);if(p==="missing")return P.NA;if(p===-1)return r==="percent"?o===null?null:1:null;const b=a(f.peer(h,y,p));return p===d?r==="percent"?o===null?null:1:null:b instanceof $?b:r==="percent"&&o===null?P.NULL:r==="difference"?o===null&&b===null?null:(o??0)-(b??0):o===null||b===null?null:b===0?P.DIV0:r==="percent"?o/b:(o-b)/b}case"runTotal":case"percentOfRunningTotal":{const p=this._running(t,f,m,y,h,m?s:e,d,n);if(p instanceof $||r==="runTotal")return p;const b=f.children(f.parent[d]),w=this._running(t,f,m,y,h,m?s:e,b[b.length-1],n);return w instanceof $?w:w===0?P.DIV0:p/w}case"rankAscending":case"rankDescending":return o===null?null:this._rank(t,f,m,y,h,m?s:e,o,r==="rankAscending",n);default:return o}}_baseSibling(t,e,s,n){const r=t.showAs.baseItem,o=e.parent[s];if(r==="prev"||r==="next"){const f=e.children(o),m=e.pos[s]+(r==="prev"?-1:1);return m>=0&&m<f.length?f[m]:-1}const i=e.fieldAt(n).keyIndex.get(r);if(i===void 0)return"missing";const u=e.findChild(o,i);return u<0?"missing":u}_running(t,e,s,n,r,o,l,i){t._run===void 0&&(t._run=new Map);let u=t._run.get(i);u===void 0&&(u=new Map,t._run.set(i,u));const f=e.children(e.parent[l]),m=e.pos[l],y=s?this.cols.nNodes:this.rows.nNodes;let h=m,a=0;for(;h>=0;){const d=e.peer(r,n,f[h]),p=d>=0?u.get(d*y+o):void 0;if(p!==void 0){a=p;break}h--}for(let d=h+1;d<=m;d++){const p=e.peer(r,n,f[d]);if(p<0)continue;const b=s?this.raw(t,p,o,i):this.raw(t,o,p,i);if(b instanceof $)return b;typeof b=="number"&&(a+=b),u.set(p*y+o,a)}return a}_rank(t,e,s,n,r,o,l,i,u){t._ranks===void 0&&(t._ranks=new Map);const f=e.ancestorAt(r,n),m=e.pathKeys(r).slice(n).join(Nt),y=`${e.parent[f]}|${o}|${m}`;let h=t._ranks.get(y);if(h===void 0){const p=[];for(const b of e.children(e.parent[f])){const w=e.peer(r,n,b);if(w<0)continue;const g=s?this.raw(t,w,o,u):this.raw(t,o,w,u);typeof g=="number"&&p.push(g)}h=Float64Array.from(p).sort(),t._ranks.set(y,h)}let a=0,d=h.length;if(i){for(;a<d;){const p=a+d>>1;h[p]<l?a=p+1:d=p}return a+1}for(;a<d;){const p=a+d>>1;h[p]<=l?a=p+1:d=p}return h.length-a+1}_arrange(){for(const t of this.data)t._run=void 0,t._ranks=void 0;this._buildChildren(this.rows,!0),this._buildChildren(this.cols,!1),this.rows.lines=this._buildLines(this.rows,!0),this.cols.lines=this._buildLines(this.cols,!1),this._layout()}rearrange(){return this._arrange(),this}_buildChildren(t,e){const{nNodes:s,parent:n,alive:r}=t,o=new Int32Array(s+1);for(let u=1;u<s;u++)r[u]&&o[n[u]+1]++;for(let u=0;u<s;u++)o[u+1]+=o[u];const l=new Int32Array(o[s]),i=o.slice();for(let u=1;u<s;u++)r[u]&&(l[i[n[u]]++]=u);t.childStart=o,t.childList=l,t.pos=new Int32Array(s),t._childIndex=null;for(let u=0;u<t.k;u++){const f=this._sortCompare(t,u+1,e),m=u===0?0:t.levelBase[u-1],y=u===0?1:t.levelBase[u];for(let h=m;h<y;h++){const a=o[h],d=o[h+1];if(d-a>1){const p=Array.from(l.subarray(a,d));p.sort(f),l.set(p,a)}for(let p=a;p<d;p++)t.pos[l[p]]=p-a}}}_sortCompare(t,e,s){const n=t.fields[e-1],r=this.cache.fields[n].ensure(),o=r.rank(),{item:l}=t,i=this.opts(n)?.sort;if((!i||i.order==="asc"||i.order===void 0)&&(!i||i.data===void 0||i.data===null))return(d,p)=>o[l[d]]-o[l[p]];if(i.order==="manual"){const d=i.keys??[],p=new Map(d.map((w,g)=>[w,g])),b=new Float64Array(r.items.length);return r.items.forEach((w,g)=>{const A=p.get(ut(w));b[g]=A===void 0?d.length+o[g]:A}),(w,g)=>b[l[w]]-b[l[g]]}const u=i.order==="desc"?-1:1;if(i.data===void 0||i.data===null)return(d,p)=>u*(o[l[d]]-o[l[p]]);const f=this.data[i.data];if(!f)return(d,p)=>o[l[d]]-o[l[p]];let m=0;if(i.path){const d=s?this.cols:this.rows;this._ensureItems(d);for(let p=0;p<i.path.length&&m>=0;p++){const w=d.fieldAt(p+1).keyIndex.get(i.path[p]);m=w===void 0?-1:d.findChild(m,w)}}const y=d=>{const p=s?this.raw(f,d,m):this.raw(f,m,d);return typeof p=="number"?p:null},h=new Map,a=d=>{let p=h.get(d);return p===void 0&&(p=y(d),h.set(d,p)),p};return(d,p)=>{const b=a(d),w=a(p);return b===null||w===null?b===w?o[l[d]]-o[l[p]]:b===null?1:-1:b===w?o[l[d]]-o[l[p]]:u*(b-w)}}_ensureItems(t){for(const e of t.fields)this.cache.fields[e].ensure()}_form(t){return this.opts(t)?.layout??this.spec.layout}_isCollapsed(t,e,s){const n=t.depth[e],r=s[n];return r===null?!1:!!(r.items!==null&&r.items.has(t.fieldAt(n).keyOf(t.item[e]))||r.paths!==null&&r.paths.has(t.pathKeys(e).join(Nt)))}_buildLines(t,e){const{slots:s}=t,n=this.data.length,r={node:[],data:[],type:[],level:[],first:[],func:[],top:[],parentLine:[]},o=(h,a,d,p,b,w,g,A)=>{r.node.push(h),r.data.push(a),r.type.push(d),r.level.push(p),r.first.push(b),r.func.push(w),r.top.push(g?1:0),r.parentLine.push(A?1:0)},l=s.length-1,i=h=>e?s[h]===k?this.spec.layout:this._form(s[h]):"tabular",u=[null];for(let h=1;h<=t.k;h++){const a=this.opts(t.fields[h-1]),d=a?.collapsedItems?.length?new Set(a.collapsedItems):null,p=a?.collapsed?.length?new Set(a.collapsed):null;u.push(d||p?{items:d,paths:p}:null)}const f=h=>this.opts(h)?.subtotalTop??this.spec.subtotalTop,m=(h,a,d,p)=>{const b=s[a];if(b===k){for(let _=0;_<n;_++){const v=_===0&&p!==-1?p:a;a===l?o(h,_,X,a,v,null,!1,!1):i(a)==="tabular"?m(h,a+1,_,v):(o(h,_,X,a,v,null,!1,!0),r.noValues??=new Set,r.noValues.add(r.node.length-1),m(h,a+1,_,-1))}return}const w=t.children(h),g=this.opts(b),A=g?.blankLine===!0&&e;for(let _=0;_<w.length;_++){const v=w[_],N=_===0&&p!==-1?p:a;if(a===l){o(v,d,X,a,N,null,!1,!1);continue}const R=i(a),F=d<0&&s.indexOf(k,a+1)>=0;if(this._isCollapsed(t,v,u)){if(F)for(let z=0;z<n;z++)o(v,z,X,a,z===0?N:a,null,!1,R!=="tabular");else o(v,d,X,a,N,null,!1,R!=="tabular");r.collapsed??=new Set,r.collapsed.add(v),A&&o(v,d,mt,a,a,null,!1,!1);continue}const C=g?.subtotals??"auto",x=Array.isArray(C),U=C!=="none"&&!(x&&C.length===0),M=R!=="tabular"&&!F&&!x&&U&&f(b);if(R==="tabular"?m(v,a+1,d,N):(o(v,d,X,a,N,null,M,!0),M||(r.noValues??=new Set,r.noValues.add(r.node.length-1)),m(v,a+1,d,-1)),!M&&U&&!(a+1===l&&s[a+1]===k&&!x)){const yt=x?C:[null];if(F)for(let tt=0;tt<n;tt++)for(const vt of yt)o(v,tt,lt,a,a,vt,!1,!1);else for(const tt of yt)o(v,d,lt,a,a,tt,!1,!1)}A&&o(v,d,mt,a,a,null,!1,!1)}};if(s.length===0)return o(0,-1,X,-1,0,null,!1,!1),r;if(m(0,0,-1,-1),t.k>0&&(e?this.spec.grandRow:this.spec.grandCol))if(s.includes(k))for(let h=0;h<n;h++)o(0,h,st,0,0,null,!1,!1);else o(0,-1,st,0,0,null,!1,!1);return r}fieldCaption(t){return t===k?this.spec.dataCaption:this.opts(t)?.caption??this.cache.fields[t].name}itemCaption(t,e){const s=t.fieldAt(t.depth[e]),n=t.item[e],r=this.opts(s.index)?.itemCaptions;if(r){const o=r[s.keyOf(n)];if(o!==void 0)return o}return null}_labelValue(t,e){const s=this.itemCaption(t,e);if(s!==null)return s===""?null:s;const n=t.fieldAt(t.depth[e]).items[t.item[e]];return n===""?null:n??"(blank)"}_labelText(t,e){const s=this.itemCaption(t,e);return s!==null?s:t.fieldAt(t.depth[e]).labelOf(t.item[e])}_subtotalLabel(t,e,s){const n=this._labelText(t,e.node[s]),r=e.data[s],o=e.func[s];return o!==null&&r>=0?`${n} ${Lt[o]} of ${this.data[r].name}`:o!==null?`${n} ${Lt[o]}`:r>=0?`${n} ${this.data[r].name}`:`${n} Total`}_pageValue(t){const e=this.cache.fields[t].ensure(),s=wt(e,this.opts(t));if(s===null)return{text:"(All)",value:"(All)"};let n=0,r=-1;for(let o=0;o<s.length;o++)s[o]===0&&(n++,r=o);return n===s.length?{text:"(All)",value:"(All)"}:n===1?{text:e.labelOf(r),value:e.items[r]??"(blank)"}:{text:"(Multiple Items)",value:"(Multiple Items)"}}_layout(){const{spec:t,rows:e,cols:s,data:n}=this,r=new Me;this.buffer=r;const o=n.length,l=t.filters.filter(T=>!this.cache.fields[T].removed),i=l.length>0?l.length+1:0,u=e.slots.length===0&&s.slots.length===0&&o===0;l.forEach((T,L)=>{r.pushValue(L,0,this.fieldCaption(T),E.PAGE_LABEL);const O=this.cache.fields[T],W=this._pageValue(T);r.pushValue(L,1,W.value,E.PAGE_VALUE,0,typeof W.value=="number"?r.format(O.numFmt):0)});const f=[],m=[];let y=0;if(e.slots.length>0){let T=0,L=0;for(let W=0;W<e.slots.length;W++)f.push(T),m.push(L),(e.slots[W]===k?t.layout:this._form(e.slots[W]))==="compact"?L++:(T++,L=0);y=(e.slots[e.slots.length-1]===k?t.layout:this._form(e.slots[e.slots.length-1]))==="compact"?T+1:T}else o<=1&&s.slots.length>0&&!(s.slots.length===1&&s.slots[0]===k)&&(y=1);const h=e.lines,a=s.lines,d=a.node.length,p=h.node.length,b=s.slots.length===1&&s.slots[0]===k,w=b&&!t.hideValuesRow&&e.slots.length>0,g=s.slots.length>0&&(!b||w),A=u?0:g?1+s.slots.length:1,_=g?t.layout==="compact"?1:s.slots.length:0,v=y+Math.max(o>0||g?d:0,_),N=o>0||e.slots.length>0?p:0,R=i,F=new Uint8Array(A*Math.max(v,1)),C=(T,L,O,W,j=0,V=0)=>{r.pushValue(R+T,L,O,W,V,j),F[T*v+L]=1},x=T=>t.layout==="compact"?null:T.map(L=>this.fieldCaption(L));u&&r.pushValue(R,0,t.name,E.PLACEHOLDER);const U=A-1;if(e.slots.length>0){const T=x(e.slots);T===null?C(U,0,t.rowCaption??G("Row Labels"),E.ROW_CAPTION):e.slots.forEach((L,O)=>{(L===k?t.layout:this._form(L))==="compact"&&O>0&&f[O]===f[O-1]||F[U*v+f[O]]||C(U,f[O],T[O],E.ROW_CAPTION)})}if(g){o===1&&e.slots.length>0&&C(0,0,n[0].name,E.CORNER);const T=x(s.slots);w?C(0,y,t.dataCaption,E.COL_CAPTION):T===null?C(0,y,t.colCaption??G("Column Labels"),E.COL_CAPTION):T.forEach((L,O)=>C(0,y+O,L,E.COL_CAPTION))}else o===1&&!b&&!e.slots.includes(k)&&C(0,y,n[0].name,E.DATA_HEADER);const M=g?1:0;if(o>0||g)for(let T=0;T<d;T++){const L=a.type[T],O=y+T,W=a.node[T];if(L===st){const V=a.data[T],ht=V>=0?`Total ${n[V].name}`:t.grandCaption??G("Grand Total");C(M,O,ht,E.COL_GRAND);continue}if(L===lt){C(M+a.level[T],O,this._subtotalLabel(s,a,T),E.COL_SUBTOTAL);continue}const j=a.level[T];for(let V=a.first[T];V<=j;V++){if(V<0||V>=s.slots.length)continue;if(s.slots[V]===k){const K=a.data[T];K>=0&&C(M+V,O,n[K].name,E.DATA_HEADER)}else{const K=It(s.slots,V),J=s.ancestorAt(W,K);if(V===j&&a.collapsed?.has(J))C(M+V,O,`${this._labelText(s,J)} Total`,E.COL_ITEM);else{const bt=this._labelValue(s,J);C(M+V,O,bt,E.COL_ITEM,typeof bt=="number"?r.format(s.fieldAt(K).numFmt):0,t.showExpandButtons&&K<s.k?1:0)}}}}for(let T=0;T<A;T++)for(let L=0;L<v;L++)F[T*v+L]===0&&r.push(R+T,L,H,0,E.HEADER_BLANK);const z=R+A,yt=n.map(T=>{const L=T.numFmt??Pe(T);return r.format(L)}),tt=h.noValues??null,vt=T=>e.slots[T];for(let T=0;T<N;T++){const L=z+T,O=h.type[T];if(O===mt)continue;const W=h.node[T],j=h.level[T],V=h.parentLine[T]===1;let ht=E.ROW_ITEM,K=E.DATA;O===lt?(ht=E.ROW_SUBTOTAL,K=E.DATA_SUBTOTAL):O===st?(ht=E.ROW_GRAND,K=E.DATA_GRAND_ROW):V&&(K=E.DATA_PARENT);const J=Math.max(j,0);if(y>0)if(e.slots.length===0)o===1&&r.pushValue(L,0,n[0].name,E.ROW_ITEM);else if(O===st){const q=h.data[T];r.pushValue(L,0,q>=0?`Total ${n[q].name}`:t.grandCaption??G("Grand Total"),E.ROW_GRAND);for(let D=1;D<y;D++)r.push(L,D,H,0,E.ROW_GRAND)}else if(O===lt){const q=f[j];for(let D=0;D<y;D++)D===q?r.pushValue(L,D,this._subtotalLabel(e,h,T),E.ROW_SUBTOTAL,m[j]):r.push(L,D,H,0,E.ROW_SUBTOTAL)}else{const q=this._labelStart(h,T,e);for(let D=q;D<=j;D++){const dt=vt(D),nt=f[D],rt=D===j&&V?E.ROW_PARENT:E.ROW_ITEM;if(dt===k){const Q=h.data[T];Q>=0&&r.pushValue(L,nt,n[Q].name,rt,m[D])}else{const Q=It(e.slots,D),ot=e.ancestorAt(W,Q),Y=t.showExpandButtons&&Q<e.k?1:0;if(D===j&&h.collapsed?.has(ot)&&this._form(dt)==="tabular")r.pushValue(L,nt,`${this._labelText(e,ot)} Total`,rt,m[D]+Y);else{const et=this._labelValue(e,ot),te=typeof et=="number"?r.format(e.fieldAt(Q).numFmt):0;r.pushValue(L,nt,et,rt,m[D]+Y,te)}}}}if(o===0||tt!==null&&tt.has(T))continue;const _t=h.data[T],bt=h.func[T];for(let q=0;q<d;q++){const D=a.type[q];if(D===mt)continue;const dt=a.data[q],nt=_t>=0?_t:dt>=0?dt:o===1?0:-1;if(nt<0)continue;const rt=n[nt],Q=bt??a.func[q],ot=this.show(rt,W,a.node[q],Q);let Y=K;O!==st&&D===st?Y=E.DATA_GRAND_COL:O===X&&!V&&D===lt&&(Y=E.DATA);const it=y+q,et=Q&&Q!==rt.agg&&!rt.numFmt?0:yt[nt];ot===null?t.showMissing===!1?r.pushValue(L,it,0,Y,J,et):t.emptyText!==""?r.pushValue(L,it,t.emptyText,Y,J,et):Y!==E.DATA&&r.push(L,it,H,0,Y,J,et):ot instanceof $&&t.errorText!==null?r.pushValue(L,it,t.errorText,Y,J,et):r.pushValue(L,it,ot,Y,J,et)}}const Mt=u?R+1:z+N,Dt=Math.max(v,l.length>0?2:0,u?1:0);if(Mt>oe||Dt>re)throw new I("The PivotTable is too large for a worksheet.");this.layout={cells:r,rows:Mt,cols:Dt,bodyCols:v,pageRows:i,pageFields:l,headerRows:A,labelCols:y,bodyTop:z,dataRows:N,colForLevel:f,indentForLevel:m,colRowBase:M,firstHeaderRow:u||g?1:o>1?0:1,firstDataRow:u?1:A,firstDataCol:y}}_labelStart(t,e,s){const n=t.level[e],r=t.first[e];if(r===0)return 0;for(let o=0;o<r;o++){const l=s.slots[o];if(l!==k&&this.opts(l)?.repeatLabels||l!==k&&this.spec.repeatLabels&&this._form(l)!=="compact")return o}return Math.min(r,n)}toRows(){const{cells:t,rows:e,cols:s}=this.layout,n=[];for(let r=0;r<e;r++)n.push(new Array(s).fill(null));for(let r=0;r<t.count;r++)n[t.rows[r]][t.cols[r]]=t.valueAt(r);return n}hitTest(t,e){const s=this.layout,{spec:n,rows:r,cols:o}=this;if(t<s.pageRows-1){const i=s.pageFields[t];return i!==void 0&&e===1?{kind:"pageFilter",field:i}:null}const l=t-s.pageRows;if(l<0||t>=s.rows)return null;if(l===s.headerRows-1&&e<s.labelCols&&r.fields.length>0){const i=n.layout==="compact"?r.fields:r.slots.filter((u,f)=>u!==k&&s.colForLevel[f]===e);if(i.length>0)return{kind:"filter",axis:"row",fields:i}}if(l===0&&e>=s.labelCols&&o.fields.length>0&&s.colRowBase===1){const i=n.layout==="compact"?e===s.labelCols?o.fields:[]:o.slots.filter((u,f)=>u!==k&&f===e-s.labelCols);if(i.length>0)return{kind:"filter",axis:"col",fields:i}}if(l>=s.headerRows&&e<s.labelCols){const i=this._rowLabelAt(l-s.headerRows,e);if(i!==null)return i}if(l>=s.colRowBase&&l<s.headerRows&&e>=s.labelCols){const i=this._colLabelAt(e-s.labelCols,l-s.colRowBase);if(i!==null)return i}return l>=s.headerRows&&e>=s.labelCols?{kind:"value",rowLine:l-s.headerRows,colLine:e-s.labelCols}:null}_rowLabelAt(t,e){const{rows:s}=this,n=s.lines;if(t>=n.node.length||n.type[t]!==X)return null;const r=this.layout.colForLevel;for(let o=n.level[t];o>=this._labelStart(n,t,s);o--)if(r[o]===e)return this._labelHit(s,n,t,o,"row");return null}_colLabelAt(t,e){const{cols:s}=this,n=s.lines;return t>=n.node.length||n.type[t]!==X||e<n.first[t]||e>n.level[t]?null:this._labelHit(s,n,t,e,"col")}_labelHit(t,e,s,n,r){const o=t.slots[n];if(o===k||o===void 0)return null;const l=It(t.slots,n),i=t.ancestorAt(e.node[s],l),u=l<t.k;return{kind:"label",axis:r,node:i,field:o,path:t.pathKeys(i),expandable:u,collapsed:u&&e.collapsed?.has(i)===!0}}togglesIn(t,e,s,n){const r=[],o=this.layout,{rows:l,cols:i}=this;if(this.spec.showExpandButtons===!1)return r;if(l.k>1)for(let u=Math.max(t,o.bodyTop);u<=Math.min(s,o.rows-1);u++)for(let f=e;f<=Math.min(n,o.labelCols-1);f++){const m=this._rowLabelAt(u-o.bodyTop,f);m!==null&&m.expandable&&r.push({row:u,col:f,collapsed:m.collapsed,indent:this._levelIndent(m)})}if(i.k>1){const u=o.pageRows+o.colRowBase;for(let f=Math.max(t,u);f<=Math.min(s,o.pageRows+o.headerRows-1);f++)for(let m=Math.max(e,o.labelCols);m<=Math.min(n,o.cols-1);m++){const y=this._colLabelAt(m-o.labelCols,f-u);y!==null&&y.expandable&&r.push({row:f,col:m,collapsed:y.collapsed,indent:0})}}return r}_levelIndent(t){const e=this.rows.slots.indexOf(t.field);return e>=0?this.layout.indentForLevel[e]:0}filterButtons(){const t=this.layout,{rows:e,cols:s,spec:n}=this,r=[];if(t.pageFields.forEach((o,l)=>r.push({row:l,col:1,axis:"page",fields:[o]})),e.fields.length>0&&n.showFieldHeaders!==!1){const o=t.pageRows+t.headerRows-1;n.layout==="compact"?r.push({row:o,col:0,axis:"row",fields:e.fields}):e.slots.forEach((l,i)=>{l!==k&&(i===0||t.colForLevel[i]!==t.colForLevel[i-1])&&r.push({row:o,col:t.colForLevel[i],axis:"row",fields:[l]})})}if(s.fields.length>0&&n.showFieldHeaders!==!1&&t.colRowBase===1){const o=t.pageRows;n.layout==="compact"?r.push({row:o,col:t.labelCols,axis:"col",fields:s.fields}):s.slots.forEach((l,i)=>{l!==k&&r.push({row:o,col:t.labelCols+i,axis:"col",fields:[l]})})}return r}}function It(c,t){let e=0;for(let s=0;s<=t;s++)c[s]!==k&&e++;return e}function Pe(c){const t=c.showAs?.type;return ue.has(t)?"0.00%":t==="index"?"0.00":"General"}function Ue(c,t,e,s){const n=e.count??10,r=e.by??"items",o=e.bottom===!0,l=c.map(u=>[u,t(u)]).filter(u=>u[1]!==null);l.sort((u,f)=>o?u[1]-f[1]:f[1]-u[1]);const i=new Set;if(r==="items"){if(l.length>0&&n>0){const u=l[Math.min(n,l.length)-1][1];for(const[f,m]of l)(o?m<=u:m>=u)&&i.add(f)}}else{const u=l.reduce((y,h)=>y+h[1],0),f=r==="percent"?u*n/100:n;let m=0;for(const[y,h]of l)if(i.add(y),m+=h,m>=f)break}return s?c.filter(u=>!i.has(u)):c.filter(u=>i.has(u))}function Be(c){return{name:"PivotTable1",rows:[],cols:[],values:[],filters:[],fieldOptions:{},layout:"compact",subtotalTop:!0,grandRow:!0,grandCol:!0,repeatLabels:!1,rowCaption:null,colCaption:null,dataCaption:G("Values"),grandCaption:null,emptyText:"",errorText:null,style:{name:"PivotStyleLight16",rowHeaders:!0,colHeaders:!0,rowStripes:!1,colStripes:!1,lastColumn:!0},showExpandButtons:!0,showFieldHeaders:!0,hideValuesRow:!0,...c}}class ns{constructor(t,e={}){this.cache=t,this.spec=Be(e),this.rememberLayout(),this.result=null,this.listeners=new Set,this.anchor=null,this.xml=null,this.dirty=!0}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(){this.dirty=!0;for(const t of this.listeners)t(this)}rememberLayout(){this.renderedLayout={cache:this.cache,spec:structuredClone(this.spec)}}update(){if(this.cache.needsRefresh){if(this.cache.source===null)throw new I("The PivotTable report was saved without the underlying data. Its source is not available.");this.cache.refresh()}return this._dropRemoved(),this.result=new Ve(this),this._emit(),this.result}rearrange(){return this.result===null?this.update():(this.result.rearrange(),this._emit(),this.result)}refresh(){return this.cache.refresh(),this.update()}_dropRemoved(){const{spec:t,cache:e}=this,s=n=>n===k||!e.fields[n]?.removed;t.rows=t.rows.filter(s),t.cols=t.cols.filter(s),t.filters=t.filters.filter(s),t.values=t.values.filter(n=>s(n.field))}options(t){const{fieldOptions:e}=this.spec;let s=e[t];return s===void 0&&(s={},e[t]=s),s}defaultAgg(t){this.cache.load();const e=this.cache.fields[t];return e.isCalculated?"sum":e.base>=0||e.isDate?"count":this._allNumeric(e)?"sum":"count"}_allNumeric(t){return t.strs!==null?!1:t.rawIds!==null?t.shared.every(e=>typeof e=="number"):t.kinds===null?t.nums!==null:t.kinds.every(e=>e===B)}uniqueDataName(t,e=-1){let s=t,n=2;const r=o=>this.spec.values.some((l,i)=>i!==e&&l.name.toLowerCase()===o.toLowerCase());for(;r(s);)s=`${t}${n++}`;return s}addValue(t,e=this.defaultAgg(t),s=this.spec.values.length){const n=this.cache.fields[t],r=kt(n.isCalculated?"sum":e,n.name);return this.spec.values.splice(s,0,{field:t,agg:e,name:this.uniqueDataName(r)}),this.spec.values.length>1&&!this.spec.rows.includes(k)&&!this.spec.cols.includes(k)&&this.spec.cols.push(k),this.spec.values.length-1}setValueAgg(t,e){const s=this.spec.values[t],n=this.cache.fields[s.field],r=[kt(s.agg,n.name),`${ae[s.agg]} of ${n.name}`].some(o=>new RegExp(`^${Jt(o)}\\d*$`).test(s.name));s.agg=e,r&&(s.name=this.uniqueDataName(kt(e,n.name),t))}place(t,e,s){const{spec:n}=this;for(const o of["rows","cols","filters"])n[o]=n[o].filter(l=>l!==t);if(t===k&&e==="filters")return;const r=n[e];s===void 0||s>r.length?r.push(t):r.splice(s,0,t)}removeFromLayout(t){const{spec:e}=this;for(const s of["rows","cols","filters"])e[s]=e[s].filter(n=>n!==t);e.values=e.values.filter(s=>s.field!==t),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==k),e.cols=e.cols.filter(s=>s!==k))}removeValue(t){const{spec:e}=this;e.values.splice(t,1),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==k),e.cols=e.cols.filter(s=>s!==k))}moveValue(t,e){const s=this.spec.values,[n]=s.splice(t,1);s.splice(Math.max(0,Math.min(e,s.length)),0,n)}isUsed(t){const{spec:e}=this;return e.rows.includes(t)||e.cols.includes(t)||e.filters.includes(t)||e.values.some(s=>s.field===t)}itemsOf(t){this.cache.load();const e=this.cache.fields[t].ensure(),s=e.rank(),n=wt(e,{hidden:this.spec.fieldOptions[t]?.hidden})??new Uint8Array(e.items.length),r=new Array(e.items.length);for(let o=0;o<r.length;o++)r[s[o]]={id:o,key:ut(e.items[o]),label:e.labelOf(o),value:e.items[o],hidden:n[o]===1};return r}itemsWithData(t){const e=this.cache.fields[t].ensure(),s=new Uint8Array(e.items.length),n=this.cache.recordCount,r=[];for(const l of Object.keys(this.spec.fieldOptions)){if(Number(l)===t)continue;const i=this.cache.fields[l];if(!i||i.removed||i.isCalculated)continue;const u=wt(i,this.spec.fieldOptions[l]);if(u!==null&&r.push([i.ensure().ids,u]),this.spec.fieldOptions[l].range||this.spec.fieldOptions[l].dateFilter){const f=Zt(i,this.spec.fieldOptions[l]);r.push([i.rawIds,f])}}const{ids:o}=e;t:for(let l=0;l<n;l++){for(let i=0;i<r.length;i++)if(r[i][1][r[i][0][l]]===1)continue t;s[o[l]]=1}return s}setHidden(t,e){const s=this.options(t);s.hidden=[...e]}clearFilters(t){const e=this.options(t);delete e.hidden,delete e.labelFilter,delete e.valueFilter,delete e.top,delete e.range,delete e.dateFilter}hasFilter(t){const e=this.spec.fieldOptions[t];return!!e&&(e.hidden&&e.hidden.length>0||!!e.labelFilter||!!e.valueFilter||!!e.top||!!e.range||!!e.dateFilter)}toggleCollapse(t){const e=this.options(t.field),s=t.path.join(Nt),n=new Set(e.collapsed??[]),r=t.path[t.path.length-1];return t.collapsed?(n.delete(s),e.collapsedItems&&(e.collapsedItems=e.collapsedItems.filter(o=>o!==r))):n.add(s),e.collapsed=[...n],this.rearrange()}setFieldCollapsed(t,e){const s=this.options(t);s.collapsed=[];const n=this.cache.fields[t].ensure();return s.collapsedItems=e?n.items.map(r=>ut(r)):[],this.rearrange()}}export{Qe as AGGS,Lt as AGG_LABEL,Me as CellBuffer,ts as LABEL_FILTERS,ss as LINE,gt as PivotCache,I as PivotError,ft as PivotField,Ve as PivotResult,ns as PivotTable,E as ROLE,ze as SHOW_AS,k as VALUES,es as VALUE_FILTERS,jt as applyNumFmt,Et as compileCalc,wt as hiddenItemFlags,ut as itemKey,ne as partsToSerial,pt as serialToParts,Je as showAsNeedsBaseField,Ze as showAsNeedsBaseItem,Ht as storeColumn,kt as valueFieldName};
1
+ import{withNoDataItems as ue}from"../slicers/pivot-file.js";import{dateOptionFlags as fe}from"../slicers/date-filters.js";import{BOOL as pt,CHUNK_BITS as It,CHUNK_MASK as Rt,EMPTY as j,ERR as mt,ERRORS as Ut,KIND_MASK as $t,NUM as U,STR as Q}from"../core/sheet.js";import{formatGeneral as Bt,getFormatter as Gt,partsToSerial as he,serialToParts as it}from"../core/numfmt.js";import{MAX_COLS as de,MAX_ROWS as pe}from"../core/address.js";import{compareText as qt,ERR as V,ERR_BY_INDEX as Ct,numberToText as me,XlError as $}from"../calc/values.js";import{FUNCS as we}from"../calc/functions/registry.js";import{compileItem as jt,hasCalcItems as xt,placeCalcItems as ge,solveCalcItems as ye,solveOrder as be}from"./calc-items.js";import"../calc/functions/index.js";import{t as B}from"../i18n/index.js";const x=-2,fs=["sum","count","average","max","min","product","countNums","stdDev","stdDevp","var","varp"],Lt={sum:"Sum",count:"Count",average:"Average",max:"Max",min:"Min",product:"Product",countNums:"Count Numbers",stdDev:"StdDev",stdDevp:"StdDevp",var:"Var",varp:"Varp"},Ae={...Lt,countNums:"Count"};function Et(c,t){switch(c){case"count":case"countNums":return B("pivot|Count of {field}",{field:t});case"average":return B("pivot|Average of {field}",{field:t});case"max":return B("pivot|Max of {field}",{field:t});case"min":return B("pivot|Min of {field}",{field:t});case"product":return B("pivot|Product of {field}",{field:t});case"stdDev":return B("pivot|StdDev of {field}",{field:t});case"stdDevp":return B("pivot|StdDevp of {field}",{field:t});case"var":return B("pivot|Var of {field}",{field:t});case"varp":return B("pivot|Varp of {field}",{field:t});default:return B("pivot|Sum of {field}",{field:t})}}const hs=[["normal","No Calculation"],["percentOfTotal","% of Grand Total"],["percentOfCol","% of Column Total"],["percentOfRow","% of Row Total"],["percent","% Of"],["percentOfParentRow","% of Parent Row Total"],["percentOfParentCol","% of Parent Column Total"],["percentOfParent","% of Parent Total"],["difference","Difference From"],["percentDiff","% Difference From"],["runTotal","Running Total In"],["percentOfRunningTotal","% Running Total In"],["rankAscending","Rank Smallest to Largest"],["rankDescending","Rank Largest to Smallest"],["index","Index"]],ve=new Set(["percent","percentOfParent","difference","percentDiff","runTotal","percentOfRunningTotal","rankAscending","rankDescending"]),ds=c=>ve.has(c),ps=c=>c==="percent"||c==="difference"||c==="percentDiff",_e=new Set(["percentOfTotal","percentOfCol","percentOfRow","percent","percentOfParentRow","percentOfParentCol","percentOfParent","percentDiff","percentOfRunningTotal"]),ms=["captionEqual","captionNotEqual","captionBeginsWith","captionNotBeginsWith","captionEndsWith","captionNotEndsWith","captionContains","captionNotContains","captionGreaterThan","captionGreaterThanOrEqual","captionLessThan","captionLessThanOrEqual","captionBetween","captionNotBetween"],ws=["valueEqual","valueNotEqual","valueGreaterThan","valueGreaterThanOrEqual","valueLessThan","valueLessThanOrEqual","valueBetween","valueNotBetween"],N={NONE:0,PAGE_LABEL:1,PAGE_VALUE:2,CORNER:3,HEADER_BLANK:4,COL_CAPTION:5,ROW_CAPTION:6,COL_ITEM:7,COL_SUBTOTAL:8,COL_GRAND:9,DATA_HEADER:10,ROW_ITEM:11,ROW_PARENT:12,ROW_SUBTOTAL:13,ROW_GRAND:14,DATA:15,DATA_PARENT:16,DATA_SUBTOTAL:17,DATA_GRAND_ROW:18,DATA_GRAND_COL:19,PLACEHOLDER:20},W=0,lt=1,st=2,bt=3,gs={ITEM:W,SUBTOTAL:lt,GRAND:st,BLANK:bt};let Ce=0;const J=()=>++Ce,Wt=1<<23,ke=1<<24,Nt="";class L extends Error{constructor(t,e){super(B(t,e))}}function at(c){if(c==null)return"blank";switch(typeof c){case"number":return`n${c}`;case"string":return`s${c.toLowerCase()}`;case"boolean":return c?"b1":"b0";default:return`e${c.code}`}}function Te(c){const t=Math.round(c*86400),e=Math.floor(t/86400);return e+(t-e*86400)/86400}const Ht=c=>c===null?4:typeof c=="number"?0:typeof c=="string"?1:typeof c=="boolean"?2:3,Ie=[["sun","mon","tue","wed","thu","fri","sat"],["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],["january","february","march","april","may","june","july","august","september","october","november","december"]].map(c=>new Map(c.map((t,e)=>[t,e])));function Kt(c){let t=Ie,e=!1;for(const s of c){if(typeof s!="string")continue;e=!0;const n=s.toLowerCase();if(t=t.filter(r=>r.has(n)),t.length===0)return null}return e?t[0]:null}const zt=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Yt=[31,29,31,30,31,30,31,31,30,31,30,31],Re=["seconds","minutes","hours","days","months","quarters","years"],Xt={seconds:"Seconds",minutes:"Minutes",hours:"Hours",days:"Days",months:"Months",quarters:"Quarters",years:"Years"};function xe(c,t){let e=0;for(let s=0;s<c-1;s++)e+=Yt[s];return e+t-1}function Le(c,t,e){switch(c){case"years":{const s=[];for(let n=t;n<=e;n++)s.push(String(n));return s}case"quarters":return["Qtr1","Qtr2","Qtr3","Qtr4"];case"months":return zt;case"days":{const s=[];return Yt.forEach((n,r)=>{for(let o=1;o<=n;o++)s.push(`${o}-${zt[r]}`)}),s}case"hours":{const s=[];for(let n=0;n<24;n++)s.push(`${n%12===0?12:n%12} ${n<12?"AM":"PM"}`);return s}default:{const s=[];for(let n=0;n<60;n++)s.push(`:${n<10?"0":""}${n}`);return s}}}function Ee(c,t,e){switch(c){case"years":return t.year-e;case"quarters":return Math.floor((t.month-1)/3);case"months":return t.month-1;case"days":return xe(t.month,t.day);case"hours":return Math.floor(t.ms/36e5);case"minutes":return Math.floor(t.ms/6e4)%60;default:return Math.floor(t.ms/1e3)%60}}class ct{constructor(t,e,s){this.cache=t,this.index=e,this.name=s,this.numFmt="General",this.isDate=!1,this.kinds=null,this.uniformKind=j,this.nums=null,this.strs=null,this.shared=null,this.rawIds=null,this.ids=null,this.items=null,this.group=null,this.base=-1,this.par=-1,this.calcItems=null,this.formula=null,this.calc=null,this.removed=!1,this.xml=null,this._keys=null,this._rank=null,this.known=[]}get isVirtual(){return this.base>=0||this.formula!==null}get isCalculated(){return this.formula!==null}reset(){this.shared=null,this.rawIds=null,this.invalidate()}invalidate(){this.ids=null,this.items=null,this._keys=null,this._rank=null}ensureRaw(){if(this.rawIds!==null)return this;if(this.cache.load(),this.base>=0){const i=this.cache.fields[this.base].ensureRaw();return this.rawIds=i.rawIds,this.shared=i.shared,this}const t=this.cache.recordCount,e=new Int32Array(t),s=[],{kinds:n,nums:r,strs:o}=this;if(o!==null)Ne(this.cache,o,null,null,t,e,s);else if(r!==null&&n===null&&this.uniformKind===U){const i=new Map;let l=NaN,u=-1;for(let f=0;f<t;f++){const m=r[f];if(m!==l){const y=this.itemValue(m);let p=i.get(y);p===void 0&&(p=s.length,s.push(y),i.set(y,p)),l=m,u=p}e[f]=u}}else n!==null?Oe(this,t,e,s):t>0&&s.push(null);return this.rawIds=e,this.shared=s,this}ensure(){if(this.ids!==null)return this;if(this.ensureRaw(),this.group===null)return this.ids=this.rawIds,this.items=this.calcItems?[...this.shared,...this.calcItems.map(o=>o.name)]:this.shared,this;const{map:t,labels:e}=Me(this),s=this.rawIds,n=s.length,r=new Int32Array(n);for(let o=0;o<n;o++)r[o]=t[s[o]];return this.ids=r,this.items=e,this.groupMap=t,this}ensureColumn(){if(this.nums!==null||this.strs!==null||this.rawIds===null)return this;if(this.base>=0)return this;const t=this.rawIds.length,e=new Uint8Array(t),s=new Float64Array(t),n=this.rawIds,r=this.shared,o=new Uint8Array(r.length),i=new Float64Array(r.length);r.forEach((l,u)=>{typeof l=="number"?(o[u]=U,i[u]=l):typeof l=="string"?o[u]=Q:typeof l=="boolean"?(o[u]=pt,i[u]=l?1:0):l instanceof $&&(o[u]=mt,i[u]=l.index)});for(let l=0;l<t;l++){const u=n[l];e[l]=o[u],s[l]=i[u]}return this.kinds=e,this.nums=s,this}get keyIndex(){if(this._keys===null){this.ensure();const t=new Map;this.items.forEach((e,s)=>{const n=at(e);t.has(n)||t.set(n,s)}),this._keys=t}return this._keys}keyOf(t){return at(this.items[t])}itemValue(t){return this.isDate?Te(t):t}keyOfValue(t){return at(typeof t=="number"?this.itemValue(t):t)}labelOf(t){return this.labelOfValue(this.items[t])}labelOfValue(t){return t==null?"(blank)":typeof t=="string"?t:typeof t=="number"?this.numFmt!=="General"?Gt(this.numFmt).number(t):Bt(t):typeof t=="boolean"?t?"TRUE":"FALSE":t.code}rank(t=!1){if(t&&this.calcItems)return this._rankAll();if(this._rank!==null)return this._rank;this.ensure();const{items:e}=this,s=new Int32Array(e.length);if(this.group!==null&&this.group.kind!=="discrete")for(let n=0;n<s.length;n++)s[n]=n;else{const n=e.length-(this.calcItems?.length??0),r=Kt(e),o=Array.from(e.keys());o.sort((i,l)=>i>=n||l>=n?i-l:Qt(e[i],e[l],r)),o.forEach((i,l)=>{s[i]=l})}return this._rank=s,s}_rankAll(){const{items:t}=this.ensure(),e=Kt(t),s=new Int32Array(t.length);return Array.from(t.keys()).sort((n,r)=>Qt(t[n],t[r],e)).forEach((n,r)=>{s[n]=r}),s}}function Qt(c,t,e){const s=Ht(c),n=Ht(t);return s!==n?s-n:s===0?c-t:s===1?e!==null?e.get(c.toLowerCase())-e.get(t.toLowerCase()):qt(c,t):s===2?c===t?0:c?1:-1:s===3?c.index-t.index:0}function Ne(c,t,e,s,n,r,o){let i=-1;for(let f=0;f<n;f++)t[f]>i&&(i=t[f]);const l=new Int32Array(i+1).fill(-1),u=new Map;for(let f=0;f<n;f++){const m=t[f];let y=l[m];if(y<0){const p=c.getString(m),a=p.toLowerCase();y=u.get(a),y===void 0&&(y=o.length,o.push(p),u.set(a,y)),l[m]=y}r[f]=y}}function Oe(c,t,e,s){const{cache:n,kinds:r,nums:o}=c,i=new Map,l=new Map,u=new Map,f=new Map;let m=-1;for(let y=0;y<t;y++){const p=r[y];let a;if(p===U){const h=c.itemValue(o[y]);a=i.get(h),a===void 0&&(a=s.length,s.push(h),i.set(h,a))}else if(p===Q){const h=o[y];if(a=u.get(h),a===void 0){const d=n.getString(h),b=d.toLowerCase();a=l.get(b),a===void 0&&(a=s.length,s.push(d),l.set(b,a)),u.set(h,a)}}else if(p===j)m<0&&(m=s.length,s.push(null)),a=m;else{const h=p*100+o[y];a=f.get(h),a===void 0&&(a=s.length,s.push(p===pt?o[y]!==0:Ct[o[y]]??V.NA),f.set(h,a))}e[y]=a}}function Me(c){const t=c.group,e=c.shared,s=new Int32Array(e.length);if(t.kind==="date"){const i=it(t.start),l=it(t.end),u=`<${Jt(t.start)}`,f=t.autoEnd?a=>a>=t.end+1:a=>a>t.end,m=`>${Jt(t.autoEnd?t.end+1:t.end)}`,y=Le(t.part,i.year,l.year);let p=[u,...y,m];t.labels&&t.labels.length===p.length&&(p=t.labels);for(let a=0;a<e.length;a++){const h=e[a];typeof h!="number"||h<t.start?s[a]=0:f(h)?s[a]=p.length-1:s[a]=1+Ee(t.part,it(h),i.year)}return{map:s,labels:p}}if(t.kind==="bins"){const{start:i,end:l,interval:u}=t,f=Math.max(1,Math.ceil((l-i)/u-1e-9)),m=[`<${kt(i)}`];for(let p=0;p<f;p++){const a=i+p*u,h=t.integer?Math.max(a+u-1,p===f-1?l:0):a+u;m.push(`${kt(a)}-${kt(h)}`)}m.push(`>${kt(l)}`);const y=t.labels&&t.labels.length===m.length?t.labels:m;for(let p=0;p<e.length;p++){const a=e[p];typeof a!="number"||a<i?s[p]=0:a>l?s[p]=f+1:s[p]=1+Math.min(f-1,Math.floor((a-i)/u+1e-9))}return{map:s,labels:y}}const n=t.groups.map(i=>i.name),r=new Map;t.groups.forEach((i,l)=>{for(const u of i.keys)r.set(u,l)});const o=new Map;for(let i=0;i<e.length;i++){const l=at(e[i]);let u=r.get(l);u===void 0&&(u=o.get(l),u===void 0&&(u=n.length,n.push(e[i]),o.set(l,u))),s[i]=u}return{map:s,labels:n}}const kt=c=>me(Number(c.toPrecision(12)));function Jt(c){const t=it(c);return`${t.month}/${t.day}/${t.year}`}class Se{constructor(){this.list=[],this.index=new Map}get size(){return this.list.length}get(t){return this.list[t]??""}add(t){let e=this.index.get(t);return e===void 0&&(e=this.list.length,this.list.push(t),this.index.set(t,e)),e}}function De(c,t,e,s,n,r){const o=c.columns[t];if(o===void 0)return;const i=e+s;for(let l=e>>>It;l<=i-1>>>It;l++){const u=o[l];if(u===void 0)continue;const f=l<<It,m=Math.max(e,f)&Rt,y=Math.min(i-1,f+Rt)&Rt,p=f-e,a=u.kinds,h=u.values;for(let d=m;d<=y;d++)n[p+d]=a[d]&$t,r[p+d]=h[d]}}function Fe(c,t,e){const s=new Int32Array(t);let n=0;for(let r=0;r<t;r++)e(c+r)||(s[n++]=r);return n===t?null:s.subarray(0,n)}function Zt(c){const t=c.book.engine?.tables;if(!t)return c.table;const e=t.get(c.table.name.toUpperCase());return e&&(c.table=e),e??null}function te(c){if(c.locate){const s=c.locate();if(!s)return null;Object.assign(c,s)}const{book:t,sheet:e}=c;return t.sheets.find(s=>typeof e=="string"?s.name===e:s===e)??null}class At{constructor(){this.fields=[],this.recordCount=0,this.strings=new Se,this.source=null,this.generation=0,this.xml=null,this.id=0,this.recordsPart=null,this.links=[],this.needsRefresh=!1,this.deferred=!1}getString(t){return this.strings.get(t)}field(t){if(typeof t=="number")return this.fields[t];const e=String(t).toLowerCase();return this.fields.find(s=>s.name.toLowerCase()===e&&!s.removed)}fieldIndex(t){if(typeof t=="number")return t;const e=this.field(t);if(!e)throw new L("Unknown field: {name}",{name:t});return e.index}static fromSheet(t,e,s){const n=new At;return n.strings=t.strings,n.source={type:"range",book:t,sheet:e,range:s},n.refresh(),n}static fromTable(t,e){const s=new At;return s.strings=t.strings,s.source={type:"table",book:t,table:e},s.refresh(),s}static fromRows(t,e){const s=new At,n=e.length;return s.recordCount=n,t.forEach((r,o)=>{const i=new Uint8Array(n),l=new Float64Array(n);for(let f=0;f<n;f++){const m=e[f][o];typeof m=="number"?(i[f]=U,l[f]=m):typeof m=="string"?(i[f]=Q,l[f]=s.strings.add(m)):typeof m=="boolean"?(i[f]=pt,l[f]=m?1:0):m instanceof $&&(i[f]=mt,l[f]=m.index)}const u=new ct(s,o,r);se(u,i,l,n),s.fields.push(u)}),s}static fromColumns(t,e,s){const n=new At;return s&&(n.strings=s),n.recordCount=e,t.forEach((r,o)=>{const i=new ct(n,o,r.name);i.kinds=r.kinds??null,i.nums=r.nums??null,i.strs=r.strs??null,i.uniformKind=r.strs?Q:r.kinds?j:U,r.numFmt&&ee(i,r.numFmt),n.fields.push(i)}),n}require(){if(this.deferred&&!this.refresh())throw new L("The PivotTable report was saved without the underlying data. Its source is not available.")}snapshot(){const{fields:t,recordCount:e,strings:s,generation:n,needsRefresh:r,deferred:o}=this,i=t.map(l=>({f:l,state:{...l,group:l.group&&{...l.group}}}));return()=>{Object.assign(this,{fields:i.map(({f:l,state:u})=>Object.assign(l,u)),recordCount:e,strings:s,generation:n,needsRefresh:r,deferred:o})}}load(){if(!(!this.deferred||this.source===null))try{this.refresh()}catch(t){if(!(t instanceof L))throw t}}get hasSource(){const t=this.source;return t!==null&&!t.deleted&&(t.type==="table"?Zt(t):te(t))!==null}refresh(){const t=this.source;if(t===null){for(const a of this.fields)a.invalidate();return this.generation=J(),!1}const{book:e}=t;this.strings=e.strings;let s,n,r,o,i;if(t.type==="table"){const a=Zt(t);if(!a)throw new L("The PivotTable source table no longer exists.");s=a.sheet??e.sheets[a.sheetIndex],n=a.r0,r=a.c0,o=a.r1-(a.totalsRows??0),i=a.c1}else{if(s=te(t),!s)throw new L("The PivotTable source sheet no longer exists.");if(t.deleted)throw new L("The PivotTable source range no longer exists.");({r0:n,c0:r,r1:o,c1:i}=t.range),o=Math.min(o,s.maxRow),i=Math.min(i,s.maxCol)}if(o<=n)throw new L("The PivotTable source needs a header row and at least one row of data.");if(t.headers&&t.headers.length!==i-r+1)throw new L("The PivotTable source needs a header for every column.");const l=o-n,u=t.skipRow?Fe(n+1,l,t.skipRow):null,f=u?u.length:l;if(f===0)throw new L("The PivotTable source needs a header row and at least one row of data.");const m=new Set,y=[];for(let a=r;a<=i;a++){const h=t.headers?String(t.headers[a-r]).trim():Ve(e,s,n,a);if(h==="")throw new L("The PivotTable field name is not valid: every source column needs a header.");let d=h;for(let b=2;m.has(d.toLowerCase());b++)d=`${h}${b}`;m.add(d.toLowerCase()),y.push(d)}for(const a of this.fields)(a.items!==null||a.shared!==null)&&(a.known=[...a.known.slice(-7),{generation:this.generation,keys:new Set(a.keyIndex.keys())}]);const p=new Map(this.fields.filter(a=>!a.isVirtual).map(a=>[a.name.toLowerCase(),a]));this.recordCount=f,y.forEach((a,h)=>{let d=p.get(a.toLowerCase());d?p.delete(a.toLowerCase()):(d=new ct(this,this.fields.length,a),this.fields.push(d));const b=r+h;let v=new Uint8Array(l),w=new Float64Array(l);De(s,b,n+1,l,v,w),u&&(v=Uint8Array.from(u,g=>v[g]),w=Float64Array.from(u,g=>w[g])),se(d,v,w,f),d.removed=!1,d.reset();for(let g=0;g<f;g++)if(v[g]!==j){ee(d,e.styles.get(s.style(n+1+(u?u[g]:g),b)).numFmt);break}});for(const a of p.values())a.removed=!0,a.kinds=null,a.nums=null,a.strs=null,a.uniformKind=j,a.reset();for(const a of this.fields)a.isVirtual&&a.reset();return this.needsRefresh=!1,this.deferred=!1,this._rescaleGroups(),this.generation=J(),!0}_rescaleGroups(){for(const t of this.fields){const e=t.group;if(t.base<0&&!t.removed&&e===null&&t.par>=0&&this.fields[t.par].group?.kind==="date"){this._rescaleAbove(t);continue}if(t.base>=0||t.removed||e===null||e.kind==="discrete"||!(e.autoStart||e.autoEnd))continue;let s;try{s=this._numericRange(t)}catch{continue}for(let n=t;n;n=n.par>=0?this.fields[n.par]:null){const r=n.group;r.autoStart&&(r.start=e.kind==="date"?Math.floor(s.min):s.min),r.autoEnd&&(r.end=e.kind==="date"?Math.floor(s.max):s.max),r.labels=void 0}}}_rescaleAbove(t){let e;try{e=this._numericRange(t,{blanks:!0})}catch{return}for(const{group:s}of this.fields.filter(n=>n.base===t.index&&!n.removed&&n.group?.kind==="date"))s.autoStart&&(s.start=Math.floor(e.min)),s.autoEnd&&(s.end=Math.floor(e.max)),s.labels=void 0}renameFields(t){const e=new Map(Object.entries(t).map(([s,n])=>[s.toLowerCase(),n]));for(const s of this.fields)s.isCalculated?(s.formula=Ue(s.formula,e),s.calc=null):s.isVirtual||(s.name=e.get(s.name.toLowerCase())??s.name);this.generation=J()}addCalculatedField(t,e){const s=new ct(this,this.fields.length,this._uniqueName(t));return s.formula=e.replace(/^\s*=\s*/,""),s.calc=Mt(s.formula,this),this.fields.push(s),s.index}addCalculatedItem(t,e,s,n=[]){const r=this.fields[t];if(r.isVirtual||r.removed)throw new L("A calculated item can't be added to this field.");if(r.group!==null||r.par>=0)throw new L("A calculated item can't be added to a grouped field. Ungroup it first.");const o=e.trim();if(o==="")throw new L("Enter a name.");if(r.ensure(),r.items.some((u,f)=>r.labelOf(f).toLowerCase()===o.toLowerCase()))throw new L("The field already has an item with this name.");for(const u of n)u.cache===this&&Tt(u.spec,this,r.index);const i={name:o,formula:s.replace(/^\s*=\s*/,""),order:1+Math.max(-1,...be(this).map(u=>u.item.order))},l=r.calcItems;r.calcItems=[...l??[],i],r.invalidate();try{jt(this,r,i.formula,o)}catch(u){throw r.calcItems=l,r.invalidate(),u}return this.generation=J(),r.items.length-1}updateCalculatedItem(t,e,s){const n=this.fields[t],r=s.replace(/^\s*=\s*/,"");jt(this,n,r,e),n.calcItems=n.calcItems.map(o=>o.name===e?{...o,formula:r}:o),this.generation=J()}removeCalculatedItem(t,e){const s=this.fields[t],n=(s.calcItems??[]).filter(r=>r.name!==e);s.calcItems=n.length?n:null,s.invalidate(),this.generation=J()}setSolveOrder(t){for(const e of this.fields)e.calcItems&&(e.calcItems=e.calcItems.map(s=>{const n=t.findIndex(r=>r.field===e.index&&r.name===s.name);return{...s,order:n<0?t.length:n}}));this.generation=J()}updateCalculatedField(t,e){const s=this.fields[t],n=e.replace(/^\s*=\s*/,"");s.calc=Mt(n,this),s.formula=n,this.generation=J()}_uniqueName(t){let e=t,s=2;for(;this.fields.some(n=>n.name.toLowerCase()===e.toLowerCase());)e=`${t}${s++}`;return e}_numericRange(t,{blanks:e=!1}={}){t.ensureRaw();let s=1/0,n=-1/0,r=!0;for(const o of t.shared)if(!(o===null&&e)){if(typeof o!="number")throw new L("Cannot group that selection.");o<s&&(s=o),o>n&&(n=o),Number.isInteger(o)||(r=!1)}if(s===1/0)throw new L("Cannot group that selection.");return{min:s,max:n,integer:r}}groupDates(t,e,{start:s,end:n}={}){const r=this.fields[t];if(r.isCalculated||r.base>=0||r.calcItems)throw new L("Cannot group that selection.");const{min:o,max:i}=this._numericRange(r),l=Re.filter(y=>e.includes(y));if(l.length===0)throw new L("Choose at least one grouping unit.");this.ungroup(t);const u={start:s??Math.floor(o),end:n??Math.floor(i)};r.group={kind:"date",part:l[0],...u,autoStart:s===void 0,autoEnd:n===void 0},r.invalidate();const f=[t];let m=r;for(const y of l.slice(1)){const p=new ct(this,this.fields.length,this._uniqueName(Xt[y]));p.base=t,p.group={kind:"date",part:y,...u,autoStart:s===void 0,autoEnd:n===void 0},this.fields.push(p),m.par=p.index,m=p,f.unshift(p.index)}return f}autoGroupDates(t){const e=this.fields[t];if(!e.isDate||e.isCalculated||e.base>=0||e.group!==null||e.par>=0||e.calcItems)return null;let s;try{s=this._numericRange(e,{blanks:!0})}catch{return null}const n=it(s.min),r=it(s.max);let o;if(n.year!==r.year)o=["months","quarters","years"];else if(n.month!==r.month)o=["days","months"];else if(n.day!==r.day&&!s.integer)o=[...e.shared.some(f=>f!==null&&Math.round(f*86400)%60!==0)?["seconds"]:[],"minutes","hours","days"];else return null;const i=[t];let l=e;for(const u of o){let f=this.fields.find(m=>m.removed&&m.base===t&&m.group?.kind==="date"&&m.group.part===u);f||(f=new ct(this,this.fields.length,this._uniqueName(`${Xt[u]} (${e.name})`)),this.fields.push(f)),f.removed=!1,f.par=-1,f.invalidate(),f.base=t,f.group={kind:"date",part:u,start:Math.floor(s.min),end:Math.floor(s.max),autoStart:!0,autoEnd:!0},l.par=f.index,l=f,i.unshift(f.index)}return i}groupState(){return this.fields.map(t=>({group:t.group&&{...t.group,...t.group.groups?{groups:[...t.group.groups]}:{}},par:t.par,removed:t.removed}))}restoreGroups(t){this.fields.forEach((e,s)=>{const n=t[s]??(e.base>=0?{group:e.group,par:-1,removed:!0}:null);n&&(e.group=n.group&&{...n.group},e.par=n.par,e.removed=n.removed,e.invalidate())}),this.renderedGroups=this.groupState(),this.generation=J()}groupNumbers(t,{start:e,end:s,interval:n=10}={}){const r=this.fields[t];if(r.isCalculated||r.base>=0||r.calcItems)throw new L("Cannot group that selection.");if(!(n>0))throw new L("The grouping interval must be greater than zero.");const{min:o,max:i,integer:l}=this._numericRange(r);this.ungroup(t);const u=e??o,f=s??i;if(f<=u)throw new L("The ending value must be greater than the starting value.");return r.group={kind:"bins",start:u,end:f,interval:n,integer:l&&Number.isInteger(u)&&Number.isInteger(n),autoStart:e===void 0,autoEnd:s===void 0},r.invalidate(),t}groupText(t,e,s){const n=this.fields[t];if(n.isCalculated||n.calcItems)throw new L("Cannot group that selection.");n.ensureRaw();let r=n.par>=0?this.fields[n.par]:null;if(r&&r.group?.kind!=="discrete")throw new L("Cannot group that selection.");return r?(r.group.groups.push(...e),r.invalidate(),r.index):(r=new ct(this,this.fields.length,this._uniqueName(s??`${n.name}2`)),r.base=t,r.group={kind:"discrete",groups:e.map(o=>({name:o.name,keys:[...o.keys]}))},this.fields.push(r),n.par=r.index,r.index)}ungroup(t){const e=this.fields[t];if(e.base>=0&&e.group?.kind==="discrete"){this.fields[e.base].par=-1,e.removed=!0,e.group={kind:"discrete",groups:[]},e.invalidate();return}e.group=null,e.invalidate();let s=e.par;for(e.par=-1;s>=0;){const n=this.fields[s];n.removed=!0,s=n.par,n.par=-1}}}function ee(c,t){c.numFmt=t??"General";try{c.isDate=c.numFmt!=="General"&&Gt(c.numFmt).isDate===!0}catch{c.isDate=!1}}function Ve(c,t,e,s){const n=t.kind(e,s)&$t,r=t.value(e,s);return n===Q?c.strings.get(r).trim():n===U?Bt(r):n===pt?r?"TRUE":"FALSE":n===mt?Ut[r]??"":""}function se(c,t,e,s){let n=0,r=0;for(let o=0;o<s;o++){const i=t[o];i===U?n++:i===Q&&r++}if(c.strs=null,c.kinds=null,c.nums=null,n===s&&s>0)c.uniformKind=U,c.nums=e;else if(r===s&&s>0){c.uniformKind=Q;const o=new Int32Array(s);for(let i=0;i<s;i++)o[i]=e[i];c.strs=o}else c.uniformKind=j,c.kinds=t,c.nums=e}const Pe=["<=",">=","<>","+","-","*","/","^","%","(",")",",","=","<",">","&"];function Ue(c,t){return c.replace(/"(?:[^"]|"")*"|'((?:[^']|'')*)'|[\p{L}_\\][\p{L}\p{N}_.\\]*(?!\s*\(|[\p{L}\p{N}_.\\])/gu,(e,s)=>{if(e[0]==='"')return e;const n=t.get((s===void 0?e:s.replace(/''/g,"'")).toLowerCase());return n===void 0?e:`'${n.replace(/'/g,"''")}'`})}function $e(c){const t=[];let e=0;for(;e<c.length;){const s=c[e];if(s<=" ")e++;else if(s>="0"&&s<="9"||s==="."&&c[e+1]>="0"&&c[e+1]<="9"){const n=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(c.slice(e));t.push({t:"num",v:Number(n[0])}),e+=n[0].length}else if(s==="'"||s==='"'){let n=e+1,r="";for(;;){if(n>=c.length)throw new L("The formula has an unmatched quote.");if(c[n]===s){if(c[n+1]!==s)break;n++}r+=c[n++]}t.push({t:s==="'"?"name":"str",v:r,start:e,end:n+1}),e=n+1}else if(/[\p{L}_\\]/u.test(s)){const n=/^[\p{L}\p{N}_.\\]+/u.exec(c.slice(e));t.push({t:"name",v:n[0],bare:!0,start:e,end:e+n[0].length}),e+=n[0].length}else if(s==="["&&t.at(-1)?.t==="name"&&t.at(-1).end===e&&t.at(-1).item===void 0){const n=/^\[\s*(?:'((?:[^']|'')*)'|([^\]']*))\s*\]/u.exec(c.slice(e));if(!n)throw new L("The formula is not valid.");const r=t.at(-1);r.item=n[1]!==void 0?n[1].replace(/''/g,"'"):n[2].trim(),r.quoted=n[1]!==void 0,r.bare=!1,e+=n[0].length,r.end=e}else{const n=Pe.find(r=>c.startsWith(r,e));if(!n)throw new L("The formula has an unexpected character: {char}",{char:s});t.push({t:"op",v:n}),e+=n.length}}return t}const ne=c=>c instanceof $?c:null,D=c=>{if(typeof c=="number")return c;if(typeof c=="boolean")return c?1:0;if(c===null)return 0;if(c instanceof $)throw c;const t=Number(c);if(typeof c=="string"&&c.trim()!==""&&!Number.isNaN(t))return t;throw V.VALUE},re={IF:c=>{const t=c[0]();if(ne(t))throw t;return(typeof t=="number"?t!==0:t===!0)?c[1]?c[1]():!0:c[2]?c[2]():!1},IFERROR:c=>{try{const t=c[0]();return ne(t)?c[1]():t}catch(t){if(t instanceof $)return c[1]();throw t}},AND:c=>c.every(t=>D(t())!==0),OR:c=>c.some(t=>D(t())!==0),NOT:c=>D(c[0]())===0,SUM:c=>c.reduce((t,e)=>t+D(e()),0),MIN:c=>Math.min(...c.map(t=>D(t()))),MAX:c=>Math.max(...c.map(t=>D(t()))),AVERAGE:c=>c.reduce((t,e)=>t+D(e()),0)/c.length,COUNT:c=>c.length,TRUE:()=>!0,FALSE:()=>!1},Ot=new Set;function oe(c,t){if(c.calc)return c.calc;if(Ot.has(c))throw new L("The formula is not valid.");Ot.add(c);try{c.calc=Mt(c.formula,t)}finally{Ot.delete(c)}return c.calc}function Mt(c,t,e=null){const s=$e(c);let n=0;const r=new Set,o=w=>s[n]?.t==="op"&&s[n].v===w,i=()=>new L("The formula is not valid."),l=w=>{const g=t.fields.find(_=>_.name.toLowerCase()===w.v.toLowerCase()&&!_.isCalculated),C=t.fields.find(_=>_.name.toLowerCase()===w.v.toLowerCase()&&_.isCalculated);if(C){oe(C,t);for(const _ of C.calc.refs)r.add(_);return _=>C.calc.fn(_)}if(!g||w.item!==void 0)throw new L("The formula refers to an unknown field: {name}",{name:w.item??w.v});r.add(g.index);const A=g.index;return _=>_(A)},u=()=>{const w=s[n];if(!w)throw i();if(w.t==="num"){n++;const g=w.v;return()=>g}if(w.t==="str"){n++;const g=w.v;return()=>g}if(w.t==="name"){if(n++,w.bare&&o("(")){n++;const g=[];if(!o(")"))for(g.push(h());o(",");)n++,g.push(h());if(!o(")"))throw i();return n++,d(w.v.toUpperCase(),g)}if(w.bare&&b.has(w.v.toUpperCase())&&(e||!t.field(w.v))){const g=re[w.v.toUpperCase()];return()=>g([])}return e?e(w):l(w)}if(o("(")){n++;const g=h();if(!o(")"))throw i();return n++,g}throw i()},f=()=>{let w=u();for(;o("%");){n++;const g=w;w=C=>D(g(C))/100}return w},m=()=>{if(o("-")){n++;const w=m();return g=>-D(w(g))}return o("+")?(n++,m()):f()},y=()=>{let w=m();for(;o("^");){n++;const g=w,C=m();w=A=>{const _=D(g(A))**D(C(A));if(!Number.isFinite(_))throw V.NUM;return _}}return w},p=()=>{let w=y();for(;o("*")||o("/");){const g=s[n++].v,C=w,A=y();w=g==="*"?_=>D(C(_))*D(A(_)):_=>{const k=D(A(_));if(k===0)throw V.DIV0;return D(C(_))/k}}return w},a=()=>{let w=p();for(;o("+")||o("-");){const g=s[n++].v,C=w,A=p();w=g==="+"?_=>D(C(_))+D(A(_)):_=>D(C(_))-D(A(_))}return w},h=()=>{let w=a();for(;s[n]?.t==="op"&&["=","<>","<",">","<=",">="].includes(s[n].v);){const g=s[n++].v,C=w,A=a();w=_=>{const k=D(C(_)),I=D(A(_));switch(g){case"=":return k===I;case"<>":return k!==I;case"<":return k<I;case">":return k>I;case"<=":return k<=I;default:return k>=I}}}return w},d=(w,g)=>{const C=re[w];if(C)return _=>C(g.map(k=>()=>k(_)));const A=we.get(w);if(!A||A.kind!=="lift")throw new L("The formula uses a function a calculated field can't call: {name}",{name:w});if(g.length<A.min||g.length>A.max)throw i();return _=>{const k=g.map(I=>I(_));for(const I of k)if(I instanceof $)throw I;return A.fn(...k)}},b=new Set(["TRUE","FALSE"]),v=h();if(n<s.length)throw i();return{fn:v,refs:[...r]}}const Be={sum:"sum",average:"sum",count:"",countNums:"",max:"mm",min:"mm",product:"prod",stdDev:"var",stdDevp:"var",var:"var",varp:"var"},Ge={count:"cnt",countNums:"num",sum:"sum",average:"sum",max:"max",min:"min",product:"prod",stdDev:"mean",stdDevp:"mean",var:"mean",varp:"mean"};class St{constructor(t,e){this.size=t,this.cnt=new Int32Array(t),this.num=new Int32Array(t),this.sum=e.sum?new Float64Array(t):null,this.min=e.mm?new Float64Array(t).fill(1/0):null,this.max=e.mm?new Float64Array(t).fill(-1/0):null,this.prod=e.prod?new Float64Array(t).fill(1):null,this.mean=e.var?new Float64Array(t):null,this.m2=e.var?new Float64Array(t):null,this.err=null,this.cntMore=null,this.numMore=null,this.calcErrs=null}setCalculated(t,e,s){this.cnt[t]=1,this.num[t]=1,this.cntMore??=new Float64Array(this.size),this.numMore??=new Float64Array(this.size),this.cntMore[t]=(e.cnt??1)-1,this.numMore[t]=(e.num??1)-1;for(const n of["sum","min","max","prod","mean"])this[n]!==null&&(this[n][t]=e[n]??0);this.m2!==null&&(this.m2[t]=0);for(const n of Object.keys(s))this._calcErrsOf(n)[t]=s[n]}_calcErrsOf(t){return this.calcErrs??={},this.calcErrs[t]??=new Int8Array(this.size)}merge(t,e,s){const n=e.cnt[s];if(n===0)return;this.cnt[t]+=n;const r=e.num[s],o=this.num[t];if(this.num[t]=o+r,e.cntMore!==null&&(this.cntMore??=new Float64Array(this.size),this.numMore??=new Float64Array(this.size),this.cntMore[t]+=e.cntMore[s],this.numMore[t]+=e.numMore[s]),e.calcErrs!==null)for(const i in e.calcErrs){const l=e.calcErrs[i][s];if(l===0)continue;const u=this._calcErrsOf(i);u[t]===0&&(u[t]=l)}if(e.err!==null&&e.err[s]!==0&&(this.err===null&&(this.err=new Int8Array(this.size)),this.err[t]===0&&(this.err[t]=e.err[s])),r!==0&&(this.sum!==null&&(this.sum[t]+=e.sum[s]),this.min!==null&&(e.min[s]<this.min[t]&&(this.min[t]=e.min[s]),e.max[s]>this.max[t]&&(this.max[t]=e.max[s])),this.prod!==null&&(this.prod[t]*=e.prod[s]),this.mean!==null)){const i=e.mean[s]-this.mean[t],l=o+r;this.m2[t]+=e.m2[s]+i*i*o*r/l,this.mean[t]+=i*r/l}}value(t,e){const s=this.cnt[t];if(s===0)return null;const n=this.calcErrs?.[Ge[e]]?.[t]??0;if(n!==0)return Ct[n-1];if(e==="count")return s+(this.cntMore?.[t]??0);if(e==="countNums")return this.num[t]+(this.numMore?.[t]??0);if(this.err!==null&&this.err[t]!==0)return Ct[this.err[t]-1];const r=this.num[t];switch(e){case"sum":return this.sum[t];case"average":return r===0?V.DIV0:this.sum[t]/r;case"max":return r===0?0:this.max[t];case"min":return r===0?0:this.min[t];case"product":return r===0?0:this.prod[t];case"stdDev":return r<2?V.DIV0:Math.sqrt(this.m2[t]/(r-1));case"stdDevp":return r<1?V.DIV0:Math.sqrt(this.m2[t]/r);case"var":return r<2?V.DIV0:this.m2[t]/(r-1);case"varp":return r<1?V.DIV0:this.m2[t]/r;default:return null}}}function qe(c,t,e,s){const{cnt:n,num:r}=c;t.base<0&&t.ensureColumn();const{kinds:o,nums:i}=t;if(i===null||t.base>=0){for(let a=0;a<s;a++){const h=e[a];h>=0&&n[h]++}return}if(o===null){for(let a=0;a<s;a++){const h=e[a];h>=0&&n[h]++}r.set(n)}else for(let a=0;a<s;a++){const h=e[a];if(h<0)continue;const d=o[a];d!==j&&(n[h]++,d===U?r[h]++:d===mt&&(c.err===null&&(c.err=new Int8Array(c.size)),c.err[h]===0&&(c.err[h]=i[a]+1)))}const{sum:l,min:u,max:f,prod:m,mean:y,m2:p}=c;if(l!==null)if(o===null)for(let a=0;a<s;a++){const h=e[a];h>=0&&(l[h]+=i[a])}else for(let a=0;a<s;a++){const h=e[a];h>=0&&o[a]===U&&(l[h]+=i[a])}if(u!==null)for(let a=0;a<s;a++){const h=e[a];if(h<0||o!==null&&o[a]!==U)continue;const d=i[a];d<u[h]&&(u[h]=d),d>f[h]&&(f[h]=d)}if(m!==null)for(let a=0;a<s;a++){const h=e[a];h>=0&&(o===null||o[a]===U)&&(m[h]*=i[a])}if(y!==null){const a=new Int32Array(c.size);for(let h=0;h<s;h++){const d=e[h];if(d<0||o!==null&&o[h]!==U)continue;const b=++a[d],v=i[h]-y[d];y[d]+=v/b,p[d]+=v*(i[h]-y[d])}}}class je{constructor(t,e,s){this.fields=e,this.slots=s,this.k=e.length,this.levels=[],this.leaf=null,this.nLeaves=1,this.levelBase=[1],this.noData=[],this.nNodes=1,this.parent=new Int32Array([-1]),this.item=new Int32Array([-1]),this.depth=new Uint8Array(1),this.cache=t,this.alive=null,this.childStart=null,this.childList=null,this.pos=null,this._childIndex=null,this.lines=null}leafNode(t){return this.k===0?0:this.levelBase[this.k-1]+t}ancestorAt(t,e){let s=t;for(;this.depth[s]>e;)s=this.parent[s];return this.depth[s]===e?s:-1}fieldAt(t){return this.cache.fields[this.fields[t-1]]}children(t){return this.childList.subarray(this.childStart[t],this.childStart[t+1])}findChild(t,e){if(this._childIndex===null){const s=new Map;this.stride=1;for(const n of this.fields)this.stride=Math.max(this.stride,this.cache.fields[n].items.length+1);for(let n=1;n<this.nNodes;n++)this.alive[n]&&s.set(this.parent[n]*this.stride+this.item[n],n);this._childIndex=s}return this._childIndex.get(t*this.stride+e)??-1}pathKeys(t){const e=[];for(let s=t;s>0;s=this.parent[s])e.push(this.fieldAt(this.depth[s]).keyOf(this.item[s]));return e.reverse()}peer(t,e,s){if(s<0)return-1;if(this.depth[t]===e)return s;const n=[];for(let o=t;this.depth[o]>e;o=this.parent[o])n.push(this.item[o]);let r=s;for(let o=n.length-1;o>=0&&r>=0;o--)r=this.findChild(r,n[o]);return r}}function ie(c,t,e,s,n,r=null){const o=new je(c,t,e),i=t.length;if(i===0)return o;let l=null,u=1;const f=[];for(let m=0;m<i;m++){const y=c.fields[t[m]].ensure(),p=y.ids,a=y.items.length,h=u*a,d=new Int32Array(s),b=Math.min(h,Math.max(s,1)),v=new Int32Array(b),w=new Int32Array(b);let g=0;if(h<=Wt){const _=new Int32Array(h).fill(-1);if(l===null)for(let k=0;k<s;k++){if(n!==null&&n[k]===0){d[k]=-1;continue}const I=p[k];let E=_[I];E<0&&(E=g++,_[I]=E,w[E]=I),d[k]=E}else for(let k=0;k<s;k++){const I=l[k];if(I<0){d[k]=-1;continue}const E=I*a+p[k];let O=_[E];O<0&&(O=g++,_[E]=O,v[O]=I,w[O]=p[k]),d[k]=O}}else{const _=new Map;for(let k=0;k<s;k++){const I=l===null?0:l[k];if(I<0||l===null&&n!==null&&n[k]===0){d[k]=-1;continue}const E=I*a+p[k];let O=_.get(E);O===void 0&&(O=g++,_.set(E,O),v[O]=I,w[O]=p[k]),d[k]=O}}const C=r?.(t[m]),A=C?ue({parents:v,items:w,count:g},m===0?1:f[m-1].count,a,C.hide):{parents:v,items:w,count:g};A.recorded=g,f.push(A),l=d,u=Math.max(A.count,1)}return o.leaf=l,Dt(o,f),o}function Dt(c,t){c.levels=t,c.nLeaves=t[t.length-1].count;let e=1;const s=[];for(const n of t)s.push(e),e+=n.count;c.levelBase=s,c.noData=t.map((n,r)=>[s[r]+n.recorded,s[r]+(n.listed??n.count)]),c.nNodes=e,c.parent=new Int32Array(e),c.item=new Int32Array(e),c.depth=new Uint8Array(e),c.parent[0]=-1,c.item[0]=-1,t.forEach((n,r)=>{const o=s[r],i=r===0?0:s[r-1];for(let l=0;l<n.count;l++)c.parent[o+l]=r===0?0:i+n.parents[l],c.item[o+l]=n.items[l],c.depth[o+l]=r+1})}class We{constructor(t=1024){this.count=0,this.capacity=t,this.rows=new Int32Array(t),this.cols=new Int32Array(t),this.kinds=new Uint8Array(t),this.values=new Float64Array(t),this.roles=new Uint8Array(t),this.levels=new Uint8Array(t),this.formats=new Uint16Array(t),this.texts=[],this._textIndex=new Map,this.formatList=["General"],this._formatIndex=new Map([["General",0]])}_grow(){const t=this.capacity*2,e=(s,n)=>{const r=new s(t);return r.set(n),r};this.rows=e(Int32Array,this.rows),this.cols=e(Int32Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.values=e(Float64Array,this.values),this.roles=e(Uint8Array,this.roles),this.levels=e(Uint8Array,this.levels),this.formats=e(Uint16Array,this.formats),this.capacity=t}format(t){let e=this._formatIndex.get(t);return e===void 0&&(e=this.formatList.length,this.formatList.push(t),this._formatIndex.set(t,e)),e}text(t){let e=this._textIndex.get(t);return e===void 0&&(e=this.texts.length,this.texts.push(t),this._textIndex.set(t,e)),e}push(t,e,s,n,r,o=0,i=0){this.count===this.capacity&&this._grow();const l=this.count++;this.rows[l]=t,this.cols[l]=e,this.kinds[l]=s,this.values[l]=n,this.roles[l]=r,this.levels[l]=o,this.formats[l]=i}pushValue(t,e,s,n,r=0,o=0){s==null?this.push(t,e,j,0,n,r,o):typeof s=="number"?this.push(t,e,U,s,n,r,o):typeof s=="string"?this.push(t,e,Q,this.text(s),n,r,o):typeof s=="boolean"?this.push(t,e,pt,s?1:0,n,r,o):this.push(t,e,mt,s.index,n,r,o)}valueAt(t){switch(this.kinds[t]){case U:return this.values[t];case Q:return this.texts[this.values[t]];case pt:return this.values[t]!==0;case mt:return Ut[this.values[t]]??"#N/A";default:return null}}}function le(c){const t=c.replace(/[.+^${}()|[\]\\*?~]/g,e=>e==="*"?".*":e==="?"?".":`\\${e}`);return new RegExp(`^${t}$`,"is")}const ae=c=>c.replace(/[.+^${}()|[\]\\]/g,"\\$&");function He(c){const{op:t}=c,e=String(c.value??""),s=String(c.value2??""),n=e.split(/([*?])/).map(o=>o==="*"?".*":o==="?"?".":ae(o)).join(""),r=(o,i,l)=>{const u=typeof i=="number"?i:Number.NaN,f=l.trim()===""?Number.NaN:Number(l);return!Number.isNaN(u)&&!Number.isNaN(f)?u-f:qt(o,l)};switch(t){case"captionEqual":{const o=le(e);return i=>o.test(i)}case"captionNotEqual":{const o=le(e);return i=>!o.test(i)}case"captionBeginsWith":{const o=new RegExp(`^${n}`,"is");return i=>o.test(i)}case"captionNotBeginsWith":{const o=new RegExp(`^${n}`,"is");return i=>!o.test(i)}case"captionEndsWith":{const o=new RegExp(`${n}$`,"is");return i=>o.test(i)}case"captionNotEndsWith":{const o=new RegExp(`${n}$`,"is");return i=>!o.test(i)}case"captionContains":{const o=new RegExp(n,"is");return i=>o.test(i)}case"captionNotContains":{const o=new RegExp(n,"is");return i=>!o.test(i)}case"captionGreaterThan":return(o,i)=>r(o,i,e)>0;case"captionGreaterThanOrEqual":return(o,i)=>r(o,i,e)>=0;case"captionLessThan":return(o,i)=>r(o,i,e)<0;case"captionLessThanOrEqual":return(o,i)=>r(o,i,e)<=0;case"captionBetween":return(o,i)=>r(o,i,e)>=0&&r(o,i,s)<=0;case"captionNotBetween":return(o,i)=>r(o,i,e)<0||r(o,i,s)>0;default:return()=>!0}}function Ke(c){const t=Number(c.value),e=Number(c.value2);switch(c.op){case"valueEqual":return s=>s===t;case"valueNotEqual":return s=>s!==t;case"valueGreaterThan":return s=>s>t;case"valueGreaterThanOrEqual":return s=>s>=t;case"valueLessThan":return s=>s<t;case"valueLessThanOrEqual":return s=>s<=t;case"valueBetween":return s=>s>=Math.min(t,e)&&s<=Math.max(t,e);case"valueNotBetween":return s=>s<Math.min(t,e)||s>Math.max(t,e);default:return()=>!0}}function ut(c,t){if(!t)return null;const e=t.hidden&&t.hidden.length>0;if(!e&&!t.labelFilter)return null;c.ensure();const s=new Uint8Array(c.items.length);if(e){const n=c.keyIndex;for(const r of t.hidden){const o=n.get(r);o!==void 0&&(s[o]=1)}}if(t.labelFilter){const n=He(t.labelFilter);c.items.forEach((r,o)=>{n(c.labelOfValue(r),r)||(s[o]=1)})}return s}function Ft(c,t){return c.ensureRaw(),fe(c.shared,t)}class ze{constructor(t,e){this.rows=t,this.cols=e,this.dense=t*e<=ke,this.map=this.dense?null:new Map,this.size=this.dense?t*e:0}ensure(t,e){const s=t*this.cols+e;if(this.dense)return s;let n=this.map.get(s);return n===void 0&&(n=this.size++,this.map.set(s,n)),n}get(t,e){const s=t*this.cols+e;return this.dense?s:this.map.get(s)??-1}}class Ye{constructor(t){this.pivot=t,this.cache=t.cache,this.spec=t.spec,this._aggregate(),this._arrange()}opts(t){return this.spec.fieldOptions[t]??null}_resolveData(){const{cache:t,spec:e}=this,s=new Map,n=(o,i)=>{let l=s.get(o);l===void 0&&(l={sum:!1,mm:!1,prod:!1,var:!1},s.set(o,l));const u=Be[i];u&&(l[u]=!0)},r=new Set;for(const o of Object.keys(e.fieldOptions)){const i=e.fieldOptions[o].subtotals;if(Array.isArray(i))for(const l of i)r.add(l)}this.data=e.values.map((o,i)=>{const l=t.fields[o.field],u={index:i,field:o.field,name:o.name,agg:o.agg,showAs:o.showAs??null,numFmt:o.numFmt??null,calc:null};if(l.isCalculated){u.calc=oe(l,t);for(const f of u.calc.refs)n(f,"sum")}else{n(o.field,o.agg);for(const f of r)n(o.field,f)}return u}),this.needs=s}_recordMask(t){const{spec:e,cache:s}=this;let n=null;for(const r of Object.keys(e.fieldOptions)){const o=s.fields[r];if(!o||o.removed||o.isCalculated)continue;const i=this.calcFields.has(o.index)?null:ut(o,e.fieldOptions[r]);if(i!==null){n===null&&(n=new Uint8Array(t).fill(1));const l=o.ensure().ids;for(let u=0;u<t;u++)i[l[u]]===1&&(n[u]=0)}if(e.fieldOptions[r].range||e.fieldOptions[r].dateFilter){n===null&&(n=new Uint8Array(t).fill(1));const l=Ft(o,e.fieldOptions[r]),u=o.rawIds;for(let f=0;f<t;f++)l[u[f]]===1&&(n[f]=0)}}return n}_itemsShown(t,e){const s=this.cache.fields[t].ensure(),n=this.spec.fieldOptions[t],r=new Uint8Array(s.items.length),o=n?.range||n?.dateFilter?Ft(s,n):null;for(let u=0;u<e;u++)(o===null||o[s.rawIds[u]]===0)&&(r[s.ids[u]]=1);s.calcItems&&r.fill(1,s.items.length-s.calcItems.length);const i=this.calcFields.has(t)?null:ut(s,n),l=[];return r.forEach((u,f)=>{u&&!i?.[f]&&l.push(f)}),l}_aggregate(){const{cache:t,spec:e}=this,s=t.recordCount;this._resolveData();const n=this.data.length,r=g=>g.filter(C=>C!==x||n>1);let o=r(e.rows),i=r(e.cols);n>1&&!o.includes(x)&&!i.includes(x)&&(i=[...i,x]),o=o.filter(g=>g===x||!t.fields[g].removed),i=i.filter(g=>g===x||!t.fields[g].removed),this.calcFields=new Set([...o,...i].filter(g=>g!==x&&t.fields[g].calcItems));const l=this._recordMask(s);this.mask=l;const u=g=>{const C=e.fieldOptions[g];return C?.showAll?{hide:ut(t.fields[g],C)}:null},f=ie(t,o.filter(g=>g!==x),o,s,l,u),m=ie(t,i.filter(g=>g!==x),i,s,l,u);this.rows=f,this.cols=m;let y,p,a,h;const d=f.nLeaves,b=m.nLeaves;if(f.leaf!==null&&m.leaf!==null){const g=f.leaf,C=m.leaf;y=new Int32Array(s);const A=d*b,_=Math.min(A,Math.max(s,1));if(p=new Int32Array(_),a=new Int32Array(_),h=0,A<=Wt){const k=new Int32Array(A).fill(-1);for(let I=0;I<s;I++){const E=g[I];if(E<0){y[I]=-1;continue}const O=E*b+C[I];let F=k[O];F<0&&(F=h++,k[O]=F,p[F]=E,a[F]=C[I]),y[I]=F}}else{const k=new Map;for(let I=0;I<s;I++){const E=g[I];if(E<0){y[I]=-1;continue}const O=E*b+C[I];let F=k.get(O);F===void 0&&(F=h++,k.set(O,F),p[F]=E,a[F]=C[I]),y[I]=F}}}else if(f.leaf!==null||m.leaf!==null){y=f.leaf??m.leaf,h=f.leaf!==null?d:b;const g=new Int32Array(h);for(let A=0;A<h;A++)g[A]=A;const C=new Int32Array(h);p=f.leaf!==null?g:C,a=f.leaf!==null?C:g}else{if(y=new Int32Array(s),h=1,l!==null)for(let g=0;g<s;g++)l[g]===0&&(y[g]=-1);p=new Int32Array(1),a=new Int32Array(1)}const v=this.calcFields.size>0?ge(t,f,m,{row:p,col:a,count:h},g=>this._itemsShown(g,s)):null;v&&(f.k>0&&Dt(f,v.rows),m.k>0&&Dt(m,v.cols),{row:p,col:a,count:h}=v.cells),this.cellCount=h,this.cellRow=p,this.cellCol=a,this.cells=y;const w=new Map;for(const[g,C]of this.needs){const A=new St(h,C);qe(A,t.fields[g],y,s),w.set(g,A)}v&&ye(v.steps,[...w.values()]),this.leafAccs=w,this._applyValueFilters(),this._rollUp()}_slotValue(t,e,s,n){if(t.calc!==null){let r=!1;const o=i=>{const l=e.get(i);if(l.cnt[s]!==0&&(r=!0),l.err!==null&&l.err[s]!==0)throw Ct[l.err[s]-1];return l.sum[s]};try{const i=t.calc.fn(o);return r?typeof i=="number"?Number.isFinite(i)?i:V.NUM:typeof i=="boolean"?i?1:0:i instanceof $?i:V.VALUE:null}catch(i){if(i instanceof $)return i;throw i}}return e.get(t.field).value(s,n??t.agg)}_applyValueFilters(){const{rows:t,cols:e,data:s}=this;this.rowDead=new Uint8Array(t.nNodes),this.colDead=new Uint8Array(e.nNodes),this.calcFields.size>0&&(this._hideItems(t,this.rowDead),this._hideItems(e,this.colDead));const n=(r,o,i)=>{for(let l=1;l<=r.k;l++){const u=r.fields[l-1],f=this.opts(u);if(!f||!f.valueFilter&&!f.top)continue;const m=f.valueFilter??f.top,y=s[m.data??0];if(!y)continue;const p=this._nodeAccs(r,y,i),a=r.levelBase[l-1],h=l<r.k?r.levelBase[l]:r.nNodes,d=new Map;for(let b=a;b<h;b++){if(o[b]||o[r.parent[b]]){o[b]=1;continue}const v=r.parent[b];let w=d.get(v);w===void 0&&(w=[],d.set(v,w)),w.push(b)}for(const b of d.values()){const v=w=>{const g=this._slotValue(y,p,w,null);return typeof g=="number"?g:null};if(f.valueFilter){const w=Ke(f.valueFilter);for(const g of b){const C=v(g);(C===null||!w(C))&&(o[g]=1)}}if(f.top){const w=b.filter(g=>!o[g]);for(const g of Je(w,v,f.top,!0))o[g]=1}}for(let b=h;b<r.nNodes;b++)o[r.parent[b]]&&(o[b]=1)}};n(t,this.rowDead,!0),n(e,this.colDead,!1)}_hideItems(t,e){const s=t.fields.map(n=>this.calcFields.has(n)?ut(this.cache.fields[n],this.opts(n)):null);for(let n=1;n<t.nNodes;n++)(e[t.parent[n]]||s[t.depth[n]-1]?.[t.item[n]])&&(e[n]=1)}_nodeAccs(t,e,s){const n=e.calc!==null?e.calc.refs:[e.field],r=new Map;for(const a of n)r.set(a,new St(t.nNodes,this.needs.get(a)));const o=[...r.entries()].map(([a,h])=>[h,this.leafAccs.get(a)]),{cellRow:i,cellCol:l,rows:u,cols:f,rowDead:m,colDead:y}=this,p=s?i:l;for(let a=0;a<this.cellCount;a++){const h=u.leafNode(i[a]),d=f.leafNode(l[a]);if(m[h]||y[d])continue;let b=t.leafNode(p[a]);for(;b>=0;){for(const[v,w]of o)v.merge(b,w,a);b=t.parent[b]}}return r}_rollUp(){const{rows:t,cols:e,cellRow:s,cellCol:n,rowDead:r,colDead:o,cellCount:i}=this,l=new Uint8Array(t.nNodes),u=new Uint8Array(e.nNodes),f=new ze(t.nNodes,e.nNodes),m=t.parent,y=e.parent,p=new Uint8Array(i);for(let w=0;w<i;w++){const g=t.leafNode(s[w]),C=e.leafNode(n[w]);if(!r[g])for(let A=g;A>=0;A=m[A])l[A]=1;if(!o[C])for(let A=C;A>=0;A=y[A])u[A]=1;if(!(r[g]||o[C])&&(p[w]=1,!f.dense))for(let A=g;A>=0;A=m[A])for(let _=C;_>=0;_=y[_])f.ensure(A,_)}const a=(w,g,C)=>{for(const[A,_]of w.noData)for(let k=A;k<_;k++)C[k]===0&&(w.parent[k]===0||g[w.parent[k]])&&(g[k]=1)};a(t,l,r),a(e,u,o),t.alive=l,e.alive=u;const h=new Map,d=[];for(const[w,g]of this.needs){const C=new St(Math.max(f.size,1),g);h.set(w,C),d.push([C,this.leafAccs.get(w)])}const b=f.dense,v=f.cols;for(let w=0;w<i;w++){if(p[w]===0)continue;const g=t.leafNode(s[w]),C=e.leafNode(n[w]);for(let A=g;A>=0;A=m[A])for(let _=C;_>=0;_=y[_]){const k=b?A*v+_:f.get(A,_);for(let I=0;I<d.length;I++)d[I][0].merge(k,d[I][1],w)}}this.slots=f,this.accs=h,this.cells=null,t.leaf=null,e.leaf=null}raw(t,e,s,n=null){if(e<0||s<0)return null;const r=this.slots.get(e,s);return r<0?null:this._slotValue(t,this.accs,r,n)}_baseLoc(t){if(t._loc!==void 0)return t._loc;const e=t.showAs?.baseField;let s=null;if(e!=null&&e>=0){let n=this.rows.fields.indexOf(e);n>=0?s={tree:this.rows,isRow:!0,depth:n+1}:(n=this.cols.fields.indexOf(e),n>=0&&(s={tree:this.cols,isRow:!1,depth:n+1}))}return t._loc=s,s}show(t,e,s,n=null){const r=t.showAs?.type;if(!r||r==="normal")return this.raw(t,e,s,n);const o=this.raw(t,e,s,n);if(o instanceof $)return o;const i=(d,b)=>this.raw(t,d,b,n),l=d=>d instanceof $?d:o===null?d===null?null:0:d===null||d===0?V.DIV0:o/d;switch(r){case"percentOfTotal":return l(i(0,0));case"percentOfCol":return l(i(0,s));case"percentOfRow":return l(i(e,0));case"percentOfParentRow":return l(e===0?o:i(this.rows.parent[e],s));case"percentOfParentCol":return l(s===0?o:i(e,this.cols.parent[s]));case"index":{const d=i(0,0),b=i(e,0),v=i(0,s);return[d,b,v].some(w=>w instanceof $)?V.VALUE:!b||!v?V.DIV0:(o??0)*d/(b*v)}default:}const u=this._baseLoc(t);if(u===null)return V.NA;const{tree:f,isRow:m,depth:y}=u,p=m?e:s;if(f.depth[p]<y)return null;const a=d=>m?i(d,s):i(e,d),h=f.ancestorAt(p,y);switch(r){case"percentOfParent":return l(a(h));case"percent":case"difference":case"percentDiff":{const d=this._baseSibling(t,f,h,y);if(d==="missing")return V.NA;if(d===-1)return r==="percent"?o===null?null:1:null;const b=a(f.peer(p,y,d));return d===h?r==="percent"?o===null?null:1:null:b instanceof $?b:r==="percent"&&o===null?V.NULL:r==="difference"?o===null&&b===null?null:(o??0)-(b??0):o===null||b===null?null:b===0?V.DIV0:r==="percent"?o/b:(o-b)/b}case"runTotal":case"percentOfRunningTotal":{const d=this._running(t,f,m,y,p,m?s:e,h,n);if(d instanceof $||r==="runTotal")return d;const b=f.children(f.parent[h]),v=this._running(t,f,m,y,p,m?s:e,b[b.length-1],n);return v instanceof $?v:v===0?V.DIV0:d/v}case"rankAscending":case"rankDescending":return o===null?null:this._rank(t,f,m,y,p,m?s:e,o,r==="rankAscending",n);default:return o}}_baseSibling(t,e,s,n){const r=t.showAs.baseItem,o=e.parent[s];if(r==="prev"||r==="next"){const f=e.children(o),m=e.pos[s]+(r==="prev"?-1:1);return m>=0&&m<f.length?f[m]:-1}const l=e.fieldAt(n).keyIndex.get(r);if(l===void 0)return"missing";const u=e.findChild(o,l);return u<0?"missing":u}_running(t,e,s,n,r,o,i,l){t._run===void 0&&(t._run=new Map);let u=t._run.get(l);u===void 0&&(u=new Map,t._run.set(l,u));const f=e.children(e.parent[i]),m=e.pos[i],y=s?this.cols.nNodes:this.rows.nNodes;let p=m,a=0;for(;p>=0;){const h=e.peer(r,n,f[p]),d=h>=0?u.get(h*y+o):void 0;if(d!==void 0){a=d;break}p--}for(let h=p+1;h<=m;h++){const d=e.peer(r,n,f[h]);if(d<0)continue;const b=s?this.raw(t,d,o,l):this.raw(t,o,d,l);if(b instanceof $)return b;typeof b=="number"&&(a+=b),u.set(d*y+o,a)}return a}_rank(t,e,s,n,r,o,i,l,u){t._ranks===void 0&&(t._ranks=new Map);const f=e.ancestorAt(r,n),m=e.pathKeys(r).slice(n).join(Nt),y=`${u??""}|${e.parent[f]}|${o}|${m}`;let p=t._ranks.get(y);if(p===void 0){const d=[];for(const b of e.children(e.parent[f])){const v=e.peer(r,n,b);if(v<0)continue;const w=s?this.raw(t,v,o,u):this.raw(t,o,v,u);typeof w=="number"&&d.push(w)}p=Float64Array.from(d).sort(),t._ranks.set(y,p)}let a=0,h=p.length;if(l){for(;a<h;){const d=a+h>>1;p[d]<i?a=d+1:h=d}return a+1}for(;a<h;){const d=a+h>>1;p[d]<=i?a=d+1:h=d}return p.length-a+1}_arrange(){for(const t of this.data)t._run=void 0,t._ranks=void 0;this._buildChildren(this.rows,!0),this._buildChildren(this.cols,!1),this.rows.lines=this._buildLines(this.rows,!0),this.cols.lines=this._buildLines(this.cols,!1),this._layout()}rearrange(){return this._arrange(),this}_buildChildren(t,e){const{nNodes:s,parent:n,alive:r}=t,o=new Int32Array(s+1);for(let u=1;u<s;u++)r[u]&&o[n[u]+1]++;for(let u=0;u<s;u++)o[u+1]+=o[u];const i=new Int32Array(o[s]),l=o.slice();for(let u=1;u<s;u++)r[u]&&(i[l[n[u]]++]=u);t.childStart=o,t.childList=i,t.pos=new Int32Array(s),t._childIndex=null;for(let u=0;u<t.k;u++){const f=this._sortCompare(t,u+1,e),m=u===0?0:t.levelBase[u-1],y=u===0?1:t.levelBase[u];for(let p=m;p<y;p++){const a=o[p],h=o[p+1];if(h-a>1){const d=Array.from(i.subarray(a,h));d.sort(f),i.set(d,a)}for(let d=a;d<h;d++)t.pos[i[d]]=d-a}}}_sortCompare(t,e,s){const n=t.fields[e-1],r=this.cache.fields[n].ensure(),{item:o}=t,i=this.opts(n)?.sort,l=r.rank(Xe(i));if((!i||i.order==="asc"||i.order===void 0)&&(!i||i.data===void 0||i.data===null))return(h,d)=>l[o[h]]-l[o[d]];if(i.order==="manual"){const h=i.keys??[],d=new Map(h.map((v,w)=>[v,w])),b=new Float64Array(r.items.length);return r.items.forEach((v,w)=>{const g=d.get(at(v));b[w]=g===void 0?h.length+l[w]:g}),(v,w)=>b[o[v]]-b[o[w]]}const u=i.order==="desc"?-1:1;if(i.data===void 0||i.data===null)return(h,d)=>u*(l[o[h]]-l[o[d]]);const f=this.data[i.data];if(!f)return(h,d)=>l[o[h]]-l[o[d]];let m=0;if(i.path){const h=s?this.cols:this.rows;this._ensureItems(h);for(let d=0;d<i.path.length&&m>=0;d++){const v=h.fieldAt(d+1).keyIndex.get(i.path[d]);m=v===void 0?-1:h.findChild(m,v)}}const y=h=>{const d=s?this.raw(f,h,m):this.raw(f,m,h);return typeof d=="number"?d:null},p=new Map,a=h=>{let d=p.get(h);return d===void 0&&(d=y(h),p.set(h,d)),d};return(h,d)=>{const b=a(h),v=a(d);return b===null||v===null?b===v?l[o[h]]-l[o[d]]:b===null?1:-1:b===v?l[o[h]]-l[o[d]]:u*(b-v)}}_ensureItems(t){for(const e of t.fields)this.cache.fields[e].ensure()}_form(t){return this.opts(t)?.layout??this.spec.layout}_isCollapsed(t,e,s){const n=t.depth[e],r=s[n];return r===null?!1:!!(r.items!==null&&r.items.has(t.fieldAt(n).keyOf(t.item[e]))||r.paths!==null&&r.paths.has(t.pathKeys(e).join(Nt)))}_buildLines(t,e){const{slots:s}=t,n=this.data.length,r={node:[],data:[],type:[],level:[],first:[],func:[],top:[],parentLine:[]},o=(p,a,h,d,b,v,w,g)=>{r.node.push(p),r.data.push(a),r.type.push(h),r.level.push(d),r.first.push(b),r.func.push(v),r.top.push(w?1:0),r.parentLine.push(g?1:0)},i=s.length-1,l=p=>e?s[p]===x?this.spec.layout:this._form(s[p]):"tabular",u=[null];for(let p=1;p<=t.k;p++){const a=this.opts(t.fields[p-1]),h=a?.collapsedItems?.length?new Set(a.collapsedItems):null,d=a?.collapsed?.length?new Set(a.collapsed):null;u.push(h||d?{items:h,paths:d}:null)}const f=p=>this.opts(p)?.subtotalTop??this.spec.subtotalTop,m=(p,a,h,d)=>{const b=s[a];if(b===x){for(let C=0;C<n;C++){const A=C===0&&d!==-1?d:a;a===i?o(p,C,W,a,A,null,!1,!1):l(a)==="tabular"?m(p,a+1,C,A):(o(p,C,W,a,A,null,!1,!0),r.noValues??=new Set,r.noValues.add(r.node.length-1),m(p,a+1,C,-1))}return}const v=t.children(p),w=this.opts(b),g=w?.blankLine===!0&&e;for(let C=0;C<v.length;C++){const A=v[C],_=C===0&&d!==-1?d:a;if(a===i){o(A,h,W,a,_,null,!1,!1);continue}const k=l(a),I=h<0&&s.indexOf(x,a+1)>=0,E=this._isCollapsed(t,A,u);if(E||t.depth[A]<t.k&&t.children(A).length===0){if(I){const wt=s.indexOf(x,a+1);k!=="tabular"&&(o(A,h,W,a,_,null,!1,!0),r.noValues??=new Set,r.noValues.add(r.node.length-1));for(let K=0;K<n;K++)o(A,K,W,wt,k==="tabular"&&K===0?_:wt,null,!1,!1)}else o(A,h,W,a,_,null,!1,k!=="tabular");E&&(r.collapsed??=new Set,r.collapsed.add(A)),g&&o(A,h,bt,a,a,null,!1,!1);continue}const O=w?.subtotals??"auto",F=Array.isArray(O),Z=O!=="none"&&!(F&&O.length===0),nt=k!=="tabular"&&!I&&!F&&Z&&f(b);if(k==="tabular"?m(A,a+1,h,_):(o(A,h,W,a,_,null,nt,!0),nt||(r.noValues??=new Set,r.noValues.add(r.node.length-1)),m(A,a+1,h,-1)),!nt&&Z&&!(a+1===i&&s[a+1]===x&&!F)){const K=F?O:[null];if(I)for(let rt=0;rt<n;rt++)for(const vt of K)o(A,rt,lt,a,a,vt,!1,!1);else for(const rt of K)o(A,h,lt,a,a,rt,!1,!1)}g&&o(A,h,bt,a,a,null,!1,!1)}};if(s.length===0)return o(0,-1,W,-1,0,null,!1,!1),r;if(m(0,0,-1,-1),t.k>0&&(e?this.spec.grandRow:this.spec.grandCol))if(s.includes(x))for(let p=0;p<n;p++)o(0,p,st,0,0,null,!1,!1);else o(0,-1,st,0,0,null,!1,!1);return r}fieldCaption(t){return t===x?this.spec.dataCaption:this.opts(t)?.caption??this.cache.fields[t].name}itemCaption(t,e){const s=t.fieldAt(t.depth[e]),n=t.item[e],r=this.opts(s.index)?.itemCaptions;if(r){const o=r[s.keyOf(n)];if(o!==void 0)return o}return null}_labelValue(t,e){const s=this.itemCaption(t,e);if(s!==null)return s===""?null:s;const n=t.fieldAt(t.depth[e]),r=n.items[t.item[e]];return r===""?null:typeof r=="number"?r:n.labelOfValue(r)}_labelText(t,e){const s=this.itemCaption(t,e);return s!==null?s:t.fieldAt(t.depth[e]).labelOf(t.item[e])}_subtotalLabel(t,e,s){const n=this._labelText(t,e.node[s]),o=t.slots.indexOf(x)<e.level[s]?-1:e.data[s],i=e.func[s];return i!==null&&o>=0?`${n} ${Lt[i]} of ${this.data[o].name}`:i!==null?`${n} ${Lt[i]}`:o>=0?`${n} ${this.data[o].name}`:`${n} Total`}_pageValue(t){const e=this.cache.fields[t].ensure(),s=ut(e,this.opts(t));if(s===null)return{text:"(All)",value:"(All)"};let n=0,r=-1;for(let o=0;o<s.length;o++)s[o]===0&&(n++,r=o);return n===s.length?{text:"(All)",value:"(All)"}:n===1?{text:e.labelOf(r),value:typeof e.items[r]=="number"?e.items[r]:e.labelOf(r)}:{text:"(Multiple Items)",value:"(Multiple Items)"}}_layout(){const{spec:t,rows:e,cols:s,data:n}=this,r=new We;this.buffer=r;const o=n.length,i=t.filters.filter(T=>!this.cache.fields[T].removed),l=i.length>0?i.length+1:0,u=e.slots.length===0&&s.slots.length===0&&o===0;i.forEach((T,R)=>{r.pushValue(R,0,this.fieldCaption(T),N.PAGE_LABEL);const S=this.cache.fields[T],G=this._pageValue(T);r.pushValue(R,1,G.value,N.PAGE_VALUE,0,typeof G.value=="number"?r.format(S.numFmt):0)});const f=[],m=[];let y=0;if(e.slots.length>0){let T=0,R=0;for(let G=0;G<e.slots.length;G++)f.push(T),m.push(R),(e.slots[G]===x?t.layout:this._form(e.slots[G]))==="compact"?R++:(T++,R=0);y=(e.slots[e.slots.length-1]===x?t.layout:this._form(e.slots[e.slots.length-1]))==="compact"?T+1:T}else o<=1&&s.slots.length>0&&!(s.slots.length===1&&s.slots[0]===x)&&(y=1);const p=e.lines,a=s.lines,h=a.node.length,d=p.node.length,b=s.slots.length===1&&s.slots[0]===x,v=b&&!t.hideValuesRow&&e.slots.length>0,w=s.slots.length>0&&(!b||v),g=u?0:w?1+s.slots.length:1,C=w?t.layout==="compact"?1:s.slots.length:0,A=y+Math.max(o>0||w?h:0,C),_=o>0||e.slots.length>0?d:0,k=l,I=new Uint8Array(g*Math.max(A,1)),E=(T,R,S,G,z=0,P=0)=>{r.pushValue(k+T,R,S,G,P,z),I[T*A+R]=1},O=T=>t.layout==="compact"?null:T.map(R=>this.fieldCaption(R));u&&r.pushValue(k,0,t.name,N.PLACEHOLDER);const F=g-1;if(e.slots.length>0&&e.slots.forEach((T,R)=>{if(R>0&&f[R]===f[R-1])return;const S=R===0&&t.layout==="compact"&&e.fields.length>0?t.rowCaption??B("Row Labels"):this.fieldCaption(T);E(F,f[R],S,N.ROW_CAPTION)}),w){o===1&&e.slots.length>0&&E(0,0,n[0].name,N.CORNER);const T=O(s.slots);v?E(0,y,t.dataCaption,N.COL_CAPTION):T===null?E(0,y,t.colCaption??B("Column Labels"),N.COL_CAPTION):T.forEach((R,S)=>E(0,y+S,R,N.COL_CAPTION))}else o===1&&!b&&!e.slots.includes(x)&&E(0,y,n[0].name,N.DATA_HEADER);const Z=w?1:0;if(o>0||w)for(let T=0;T<h;T++){const R=a.type[T],S=y+T,G=a.node[T];if(R===st){const P=a.data[T],gt=P>=0?`Total ${n[P].name}`:t.grandCaption??B("Grand Total");E(Z,S,gt,N.COL_GRAND);continue}if(R===lt){E(Z+a.level[T],S,this._subtotalLabel(s,a,T),N.COL_SUBTOTAL);continue}const z=a.level[T];for(let P=a.first[T];P<=z;P++){if(P<0||P>=s.slots.length)continue;if(s.slots[P]===x){const H=a.data[T];H>=0&&E(Z+P,S,n[H].name,N.DATA_HEADER)}else{const H=Vt(s.slots,P),tt=s.ancestorAt(G,H);if(tt<0)continue;const yt=this._labelValue(s,tt);E(Z+P,S,yt,N.COL_ITEM,typeof yt=="number"?r.format(s.fieldAt(H).numFmt):0,t.showExpandButtons&&H<s.k?1:0)}}}for(let T=0;T<g;T++)for(let R=0;R<A;R++)I[T*A+R]===0&&r.push(k+T,R,j,0,N.HEADER_BLANK);const nt=k+g,wt=n.map(T=>{const R=T.numFmt??Qe(T);return r.format(R)}),K=p.noValues??null,rt=T=>e.slots[T];for(let T=0;T<_;T++){const R=nt+T,S=p.type[T];if(S===bt)continue;const G=p.node[T],z=p.level[T],P=p.parentLine[T]===1;let gt=N.ROW_ITEM,H=N.DATA;S===lt?(gt=N.ROW_SUBTOTAL,H=N.DATA_SUBTOTAL):S===st?(gt=N.ROW_GRAND,H=N.DATA_GRAND_ROW):P&&(H=N.DATA_PARENT);const tt=Math.max(z,0);if(y>0)if(e.slots.length===0)o===1&&r.pushValue(R,0,n[0].name,N.ROW_ITEM);else if(S===st){const q=p.data[T];r.pushValue(R,0,q>=0?`Total ${n[q].name}`:t.grandCaption??B("Grand Total"),N.ROW_GRAND);for(let M=1;M<y;M++)r.push(R,M,j,0,N.ROW_GRAND)}else if(S===lt){const q=f[z];for(let M=0;M<y;M++)M===q?r.pushValue(R,M,this._subtotalLabel(e,p,T),N.ROW_SUBTOTAL,m[z]):r.push(R,M,j,0,N.ROW_SUBTOTAL)}else{const q=this._labelStart(p,T,e);for(let M=q;M<=z;M++){const _t=rt(M),ft=f[M],ht=M===z&&P?N.ROW_PARENT:N.ROW_ITEM;if(_t===x){const Y=p.data[T];Y>=0&&r.pushValue(R,ft,n[Y].name,ht,m[M])}else{const Y=Vt(e.slots,M),dt=e.ancestorAt(G,Y);if(dt<0)continue;const X=t.showExpandButtons&&Y<e.k?1:0,et=this._labelValue(e,dt),ot=typeof et=="number"?r.format(e.fieldAt(Y).numFmt):0;r.pushValue(R,ft,et,ht,m[M]+X,ot)}}}if(o===0||K!==null&&K.has(T))continue;const yt=p.data[T],ce=p.func[T];for(let q=0;q<h;q++){const M=a.type[q];if(M===bt)continue;const _t=a.data[q],ft=yt>=0?yt:_t>=0?_t:o===1?0:-1;if(ft<0)continue;const ht=n[ft],Y=ce??a.func[q],dt=this.show(ht,G,a.node[q],Y);let X=H;S!==st&&M===st?X=N.DATA_GRAND_COL:S===W&&!P&&M===lt&&(X=N.DATA);const et=y+q,ot=Y&&Y!==ht.agg&&!ht.numFmt?0:wt[ft];dt===null?t.showMissing===!1?r.pushValue(R,et,0,X,tt,ot):t.emptyText!==""?r.pushValue(R,et,t.emptyText,X,tt,ot):X!==N.DATA&&r.push(R,et,j,0,X,tt,ot):dt instanceof $&&t.errorText!==null?r.pushValue(R,et,t.errorText,X,tt,ot):r.pushValue(R,et,dt,X,tt,ot)}}const vt=u?k+1:nt+_,Pt=Math.max(A,i.length>0?2:0,u?1:0);if(vt>pe||Pt>de)throw new L("The PivotTable is too large for a worksheet.");this.layout={cells:r,rows:vt,cols:Pt,bodyCols:A,pageRows:l,pageFields:i,headerRows:g,labelCols:y,bodyTop:nt,dataRows:_,colForLevel:f,indentForLevel:m,colRowBase:Z,firstHeaderRow:u||w?1:o>1?0:1,firstDataRow:u?1:g,firstDataCol:y}}_labelStart(t,e,s){const n=t.level[e],r=t.first[e];if(r===0)return 0;for(let o=0;o<r;o++){const i=s.slots[o];if(i!==x&&this.opts(i)?.repeatLabels||i!==x&&this.spec.repeatLabels&&this._form(i)!=="compact")return o}return Math.min(r,n)}toRows(){const{cells:t,rows:e,cols:s}=this.layout,n=[];for(let r=0;r<e;r++)n.push(new Array(s).fill(null));for(let r=0;r<t.count;r++)n[t.rows[r]][t.cols[r]]=t.valueAt(r);return n}hitTest(t,e){const s=this.layout,{spec:n,rows:r,cols:o}=this;if(t<s.pageRows-1){const l=s.pageFields[t];return l!==void 0&&e===1?{kind:"pageFilter",field:l}:null}const i=t-s.pageRows;if(i<0||t>=s.rows)return null;if(i===s.headerRows-1&&e<s.labelCols&&r.fields.length>0){const l=r.slots.filter((u,f)=>u!==x&&s.colForLevel[f]===e);if(l.length>0)return{kind:"filter",axis:"row",fields:l}}if(i===0&&e>=s.labelCols&&o.fields.length>0&&s.colRowBase===1){const l=n.layout==="compact"?e===s.labelCols?o.fields:[]:o.slots.filter((u,f)=>u!==x&&f===e-s.labelCols);if(l.length>0)return{kind:"filter",axis:"col",fields:l}}if(i>=s.headerRows&&e<s.labelCols){const l=this._rowLabelAt(i-s.headerRows,e);if(l!==null)return l}if(i>=s.colRowBase&&i<s.headerRows&&e>=s.labelCols){const l=this._colLabelAt(e-s.labelCols,i-s.colRowBase);if(l!==null)return l}return i>=s.headerRows&&e>=s.labelCols?{kind:"value",rowLine:i-s.headerRows,colLine:e-s.labelCols}:null}_rowLabelAt(t,e){const{rows:s}=this,n=s.lines;if(t>=n.node.length||n.type[t]!==W)return null;const r=this.layout.colForLevel;for(let o=n.level[t];o>=this._labelStart(n,t,s);o--)if(r[o]===e)return this._labelHit(s,n,t,o,"row");return null}_colLabelAt(t,e){const{cols:s}=this,n=s.lines;return t>=n.node.length||n.type[t]!==W||e<n.first[t]||e>n.level[t]?null:this._labelHit(s,n,t,e,"col")}_labelHit(t,e,s,n,r){const o=t.slots[n];if(o===x||o===void 0)return null;const i=Vt(t.slots,n),l=t.ancestorAt(e.node[s],i);if(l<0)return null;const u=i<t.k;return{kind:"label",axis:r,node:l,field:o,path:t.pathKeys(l),expandable:u,collapsed:u&&e.collapsed?.has(l)===!0}}togglesIn(t,e,s,n){const r=[],o=this.layout,{rows:i,cols:l}=this;if(this.spec.showExpandButtons===!1)return r;if(i.k>1)for(let u=Math.max(t,o.bodyTop);u<=Math.min(s,o.rows-1);u++)for(let f=e;f<=Math.min(n,o.labelCols-1);f++){const m=this._rowLabelAt(u-o.bodyTop,f);m!==null&&m.expandable&&r.push({row:u,col:f,collapsed:m.collapsed,indent:this._levelIndent(m)})}if(l.k>1){const u=o.pageRows+o.colRowBase;for(let f=Math.max(t,u);f<=Math.min(s,o.pageRows+o.headerRows-1);f++)for(let m=Math.max(e,o.labelCols);m<=Math.min(n,o.cols-1);m++){const y=this._colLabelAt(m-o.labelCols,f-u);y!==null&&y.expandable&&r.push({row:f,col:m,collapsed:y.collapsed,indent:0})}}return r}_levelIndent(t){const e=this.rows.slots.indexOf(t.field);return e>=0?this.layout.indentForLevel[e]:0}filterButtons(){const t=this.layout,{rows:e,cols:s,spec:n}=this,r=[];if(t.pageFields.forEach((o,i)=>r.push({row:i,col:1,axis:"page",fields:[o]})),e.fields.length>0&&n.showFieldHeaders!==!1){const o=t.pageRows+t.headerRows-1;for(let i=0;i<t.labelCols;i++){const l=e.slots.filter((u,f)=>u!==x&&t.colForLevel[f]===i);l.length>0&&r.push({row:o,col:i,axis:"row",fields:l})}}if(s.fields.length>0&&n.showFieldHeaders!==!1&&t.colRowBase===1){const o=t.pageRows;n.layout==="compact"?r.push({row:o,col:t.labelCols,axis:"col",fields:s.fields}):s.slots.forEach((i,l)=>{i!==x&&r.push({row:o,col:t.labelCols+l,axis:"col",fields:[i]})})}return r}}const Xe=c=>c?.order==="asc"||c?.order==="desc";function Vt(c,t){let e=0;for(let s=0;s<=t;s++)c[s]!==x&&e++;return e}function Qe(c){const t=c.showAs?.type;return _e.has(t)?"0.00%":t==="index"?"0.00":"General"}function Je(c,t,e,s){const n=e.count??10,r=e.by??"items",o=e.bottom===!0,i=c.map(u=>[u,t(u)]).filter(u=>u[1]!==null);i.sort((u,f)=>o?u[1]-f[1]:f[1]-u[1]);const l=new Set;if(r==="items"){if(i.length>0&&n>0){const u=i[Math.min(n,i.length)-1][1];for(const[f,m]of i)(o?m<=u:m>=u)&&l.add(f)}}else{const u=i.reduce((y,p)=>y+p[1],0),f=r==="percent"?u*n/100:n;let m=0;for(const[y,p]of i)if(l.add(y),m+=p,m>=f)break}return s?c.filter(u=>!l.has(u)):c.filter(u=>l.has(u))}const Ze=new Set(["average","stdDev","stdDevp","var","varp"]);function Tt(c,t,e=null){const s=n=>n!==x&&(n===e||t.fields[n].calcItems);if(!(e===null&&!xt(t))){if(c.values.some(n=>Ze.has(n.agg)&&!t.fields[n.field].isCalculated))throw new L("Averages, standard deviations and variances are not supported when a PivotTable has calculated items.");if(new Set(c.values.map(n=>n.field)).size<c.values.length)throw new L("A field can't be in the Values area twice when a PivotTable has calculated items.");if(c.filters.some(s))throw new L("A field with a calculated item can't be in the Filters area.")}}function ts(c){return{name:"PivotTable1",rows:[],cols:[],values:[],filters:[],fieldOptions:{},layout:"compact",subtotalTop:!0,grandRow:!0,grandCol:!0,repeatLabels:!1,rowCaption:null,colCaption:null,dataCaption:B("Values"),grandCaption:null,emptyText:"",errorText:null,style:{name:"PivotStyleLight16",rowHeaders:!0,colHeaders:!0,rowStripes:!1,colStripes:!1,lastColumn:!0},showExpandButtons:!0,showFieldHeaders:!0,hideValuesRow:!0,...c}}class ys{constructor(t,e={}){this.cache=t,this.spec=ts(e),this.rememberLayout(),this.result=null,this.generation=t.generation,this.listeners=new Set,this.anchor=null,this.xml=null,this.dirty=!0}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(){this.dirty=!0;for(const t of this.listeners)t(this)}rememberLayout(){this.renderedLayout={cache:this.cache,spec:structuredClone(this.spec)}}update(){if(this.cache.needsRefresh){if(this.cache.source===null)throw new L("The PivotTable report was saved without the underlying data. Its source is not available.");this.cache.refresh()}return this._dropRemoved(),this._hideNewItems(),this.result=new Ye(this),this._emit(),this.result}rearrange(){return this.result===null?this.update():(this.result.rearrange(),this._emit(),this.result)}refresh(){return this.cache.refresh(),this.update()}_dropRemoved(){const{spec:t,cache:e}=this,s=n=>n===x||!e.fields[n]?.removed;t.rows=t.rows.filter(s),t.cols=t.cols.filter(s),t.filters=t.filters.filter(s),t.values.every(n=>s(n.field))||this.setValues(t.values.filter(n=>s(n.field)))}_hideNewItems(){const{cache:t}=this,e=this.generation;if(e!==t.generation){this.generation=t.generation;for(const[s,n]of Object.entries(this.spec.fieldOptions)){const r=t.fields[s];if(!n.hidden?.length||n.includeNewItems||!r||r.removed)continue;const o=r.known.find(l=>l.generation>=e)?.keys;if(!o)continue;r.ensure();const i=new Set(n.hidden);for(const l of r.keyIndex.keys())o.has(l)||i.add(l);[...r.keyIndex.keys()].some(l=>!i.has(l))&&(n.hidden=[...i])}}}options(t){const{fieldOptions:e}=this.spec;let s=e[t];return s===void 0&&(s={},e[t]=s),s}defaultAgg(t){this.cache.load();const e=this.cache.fields[t];return e.isCalculated?"sum":e.base>=0||e.isDate?"count":this._allNumeric(e)?"sum":"count"}_allNumeric(t){return t.strs!==null?!1:t.rawIds!==null?t.shared.every(e=>typeof e=="number"):t.kinds===null?t.nums!==null:t.kinds.every(e=>e===U)}uniqueDataName(t,e=-1){let s=t,n=2;const r=o=>this.spec.values.some((i,l)=>l!==e&&i.name.toLowerCase()===o.toLowerCase());for(;r(s);)s=`${t}${n++}`;return s}addValue(t,e=this.defaultAgg(t),s=this.spec.values.length){const n=this.cache.fields[t];xt(this.cache)&&Tt({...this.spec,values:[...this.spec.values,{field:t,agg:e}]},this.cache);const r=Et(n.isCalculated?"sum":e,n.name);s=Math.min(s,this.spec.values.length);const o=this.spec.values.slice();return o.splice(s,0,{field:t,agg:e,name:this.uniqueDataName(r)}),this.setValues(o),this.spec.values.length>1&&!this.spec.rows.includes(x)&&!this.spec.cols.includes(x)&&this.spec.cols.push(x),this.spec.values.length-1}setValueAgg(t,e){const s=this.spec.values[t],n=this.cache.fields[s.field];xt(this.cache)&&Tt({...this.spec,values:[{...s,agg:e}]},this.cache);const r=[Et(s.agg,n.name),`${Ae[s.agg]} of ${n.name}`].some(o=>new RegExp(`^${ae(o)}\\d*$`).test(s.name));s.agg=e,r&&(s.name=this.uniqueDataName(Et(e,n.name),t))}checkPlace(t,e){e==="filters"&&this.cache.fields[t]?.calcItems&&Tt({...this.spec,values:[],filters:[t]},this.cache)}place(t,e,s){const{spec:n}=this;this.checkPlace(t,e);for(const o of["rows","cols","filters"])n[o]=n[o].filter(i=>i!==t);if(t===x&&e==="filters")return;const r=n[e];s===void 0||s>r.length?r.push(t):r.splice(s,0,t)}removeFromLayout(t){const{spec:e}=this;for(const s of["rows","cols","filters"])e[s]=e[s].filter(n=>n!==t);this.setValues(e.values.filter(s=>s.field!==t)),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==x),e.cols=e.cols.filter(s=>s!==x))}removeValue(t){const{spec:e}=this;this.setValues(e.values.filter((s,n)=>n!==t)),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==x),e.cols=e.cols.filter(s=>s!==x))}moveValue(t,e){const s=this.spec.values.slice(),[n]=s.splice(t,1);s.splice(Math.max(0,Math.min(e,s.length)),0,n),this.setValues(s)}setValues(t,e=s=>t.indexOf(s)){const{spec:s}=this,n=s.values.map(e),r=i=>n[i.data??0]===-1,o=i=>({...i,data:n[i.data??0]??i.data});for(const i of Object.values(s.fieldOptions)){i.sort?.data!==void 0&&i.sort.data!==null&&(r(i.sort)?delete i.sort:i.sort=o(i.sort));for(const l of["valueFilter","top"])i[l]&&(r(i[l])?delete i[l]:i[l]=o(i[l]))}s.conditionalFormats&&(s.conditionalFormats=s.conditionalFormats.filter(i=>n[i.dataIndex]!==-1).map(i=>({...i,dataIndex:n[i.dataIndex]??i.dataIndex}))),s.values=t}isUsed(t){const{spec:e}=this;return e.rows.includes(t)||e.cols.includes(t)||e.filters.includes(t)||e.values.some(s=>s.field===t)}itemsOf(t){this.cache.load();const e=this.cache.fields[t].ensure(),s=e.rank(),n=ut(e,{hidden:this.spec.fieldOptions[t]?.hidden})??new Uint8Array(e.items.length),r=new Array(e.items.length);for(let o=0;o<r.length;o++)r[s[o]]={id:o,key:at(e.items[o]),label:e.labelOf(o),value:e.items[o],hidden:n[o]===1};return r}itemsWithData(t){const e=this.cache.fields[t].ensure(),s=new Uint8Array(e.items.length),n=this.cache.recordCount,r=[];for(const i of Object.keys(this.spec.fieldOptions)){if(Number(i)===t)continue;const l=this.cache.fields[i];if(!l||l.removed||l.isCalculated)continue;const u=ut(l,this.spec.fieldOptions[i]);if(u!==null&&r.push([l.ensure().ids,u]),this.spec.fieldOptions[i].range||this.spec.fieldOptions[i].dateFilter){const f=Ft(l,this.spec.fieldOptions[i]);r.push([l.rawIds,f])}}e.calcItems&&s.fill(1,e.items.length-e.calcItems.length);const{ids:o}=e;t:for(let i=0;i<n;i++){for(let l=0;l<r.length;l++)if(r[l][1][r[l][0][i]]===1)continue t;s[o[i]]=1}return s}setHidden(t,e){const s=this.options(t);s.hidden=[...e]}clearFilters(t){const e=this.options(t);delete e.hidden,delete e.labelFilter,delete e.valueFilter,delete e.top,delete e.range,delete e.dateFilter}hasFilter(t){const e=this.spec.fieldOptions[t];return!!e&&(e.hidden&&e.hidden.length>0||!!e.labelFilter||!!e.valueFilter||!!e.top||!!e.range||!!e.dateFilter)}toggleCollapse(t){const e=this.options(t.field),s=t.path.join(Nt),n=new Set(e.collapsed??[]),r=t.path[t.path.length-1];return t.collapsed?(n.delete(s),e.collapsedItems&&(e.collapsedItems=e.collapsedItems.filter(o=>o!==r))):n.add(s),e.collapsed=[...n],this.rearrange()}setFieldCollapsed(t,e){const s=this.options(t);s.collapsed=[];const n=this.cache.fields[t].ensure();return s.collapsedItems=e?n.items.map(r=>at(r)):[],this.rearrange()}}export{fs as AGGS,Lt as AGG_LABEL,We as CellBuffer,ms as LABEL_FILTERS,gs as LINE,At as PivotCache,L as PivotError,ct as PivotField,Ye as PivotResult,ys as PivotTable,N as ROLE,hs as SHOW_AS,x as VALUES,ws as VALUE_FILTERS,ee as applyNumFmt,Mt as compileCalc,ut as hiddenItemFlags,Xe as isSorted,at as itemKey,J as newGeneration,he as partsToSerial,Tt as refuseWithCalcItems,it as serialToParts,ds as showAsNeedsBaseField,ps as showAsNeedsBaseItem,se as storeColumn,Et as valueFieldName,Te as wholeSeconds};
package/pivot/xml.js CHANGED
@@ -1,2 +1,2 @@
1
- import{pivotCfNode as $e,pivotChartFormatsNode as _e}from"../slicers/pivot-file.js";import{dateFilterNodes as qe,isDateFilterType as He,parseDateFilter as Ve}from"../slicers/date-filters.js";import{MAX_COLS as Ge,parseRangeRef as de,rangeRef as fe}from"../core/address.js";import{BUILTIN_FORMATS as Y,partsToSerial as Xe,serialToParts as je}from"../core/numfmt.js";import{BOOL as Ue,EMPTY as We,ERR as Ke,ERRORS as Ye,NUM as pe,STR as Je}from"../core/sheet.js";import{decodeRange as B,unescapeXml as Qe,unescapeXstring as he,XmlScanner as me}from"../io/xml-scan.js";import{escapeMarkup as J,xmlAttr as ge}from"../io/xml-escape.js";import{relsPathOf as Ze,resolveTarget as ze}from"../io/package-paths.js";import{ERR_BY_CODE as we,ERR_BY_INDEX as be,XlError as et}from"../calc/values.js";import{applyNumFmt as Q,itemKey as $,LINE as j,PivotCache as tt,PivotField as nt,PivotTable as st,storeColumn as at,VALUES as Z,compileCalc as ot,valueFieldName as rt}from"./engine.js";const U="http://schemas.openxmlformats.org/spreadsheetml/2006/main",V="http://schemas.openxmlformats.org/officeDocument/2006/relationships",z="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main",it="{E15A36E0-9728-4e99-A89B-3F7291B0FE68}",lt="{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}",ct="{2946ED86-A175-432a-8AC1-64E0C546D7DE}",ee={table:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",definition:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml",records:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml"},_={table:`${V}/pivotTable`,definition:`${V}/pivotCacheDefinition`,records:`${V}/pivotCacheRecords`},xe=1048828,ye=1048829,ve=4294967294,ut=new Set(["percentOfParent","percentOfParentRow","percentOfParentCol","percentOfRunningTotal","rankAscending","rankDescending"]),te={sum:"sumSubtotal",count:"countASubtotal",average:"avgSubtotal",max:"maxSubtotal",min:"minSubtotal",product:"productSubtotal",countNums:"countSubtotal",stdDev:"stdDevSubtotal",stdDevp:"stdDevPSubtotal",var:"varSubtotal",varp:"varPSubtotal"},Fe={sum:"sum",count:"countA",average:"avg",max:"max",min:"min",product:"product",countNums:"count",stdDev:"stdDev",stdDevp:"stdDevP",var:"var",varp:"varP"},m=(t,e={},s=[])=>({n:t,a:e,c:s,t:""}),y=(t,e)=>t?.c.find(s=>s.n===e)??null,A=(t,e)=>t?t.c.filter(s=>s.n===e):[],S=(t,e)=>t===void 0?e:t==="1"||t==="true";function Se(t,e,s){const a={};let n=e;for(;n<s;){for(;n<s&&t[n]<=32;)n++;if(n>=s)break;const l=n;for(;n<s&&t[n]!==61&&t[n]>32;)n++;const o=n;for(;n<s&&t[n]!==34&&t[n]!==39;)n++;if(n>=s)break;const c=t[n++],r=n,i=t.indexOf(c,n),d=i<0||i>s?s:i;a[B(t,l,o)]=he(B(t,r,d)),n=d+1}return a}function dt(t,e,s){let a=e;for(;a>0&&t[a-1]!==60;)a--;return B(t,a,s)}function ne(t,e=[]){e.push("<",t.n);for(const s of Object.keys(t.a)){const a=t.a[s];a!=null&&e.push(" ",s,'="',ge(a),'"')}if(t.c.length===0&&t.t==="")return e.push("/>"),e;e.push(">"),t.t&&e.push(J(t.t));for(const s of t.c)typeof s=="string"?e.push(s):ne(s,e);return e.push("</",t.n,">"),e}const ft=new Set(["s","n","d","b","e","m"]);function Te(t,e){switch(t){case"n":return Number(e.v);case"s":return e.v??"";case"d":return W(e.v);case"b":return e.v==="1"||e.v==="true";case"e":return we.get(e.v)??be[6];default:return null}}class Ie{constructor(){this.root=m("#root"),this.stack=[this.root],this.shared=null,this.sharedDepth=0,this.scanner=new me(this)}feed(e){this.scanner.feed(e)}finish(){return this.root.c[0]??null}open(e,s,a,n,l,o){const c=this.stack[this.stack.length-1];if(this.shared!==null&&c===this.shared){const f=B(e,s,a);if(ft.has(f)){const u=Se(e,n,l);c.items.push(Te(f,u)),o||this.sharedDepth++;return}}if(this.sharedDepth>0){o||this.sharedDepth++;return}const r=Se(e,n,l);let i=dt(e,s,a);const d=i.indexOf(":");if(d>=0){const f="xmlns:"+i.slice(0,d);let u=r[f];for(let h=this.stack.length-1;u===void 0&&h>0;h--)u=this.stack[h].a[f];u===U&&(i=i.slice(d+1))}const p=m(i,r);p.n==="sharedItems"&&(p.items=[],this.shared=p),c.c.push(p),o?p.n==="sharedItems"&&(this.shared=null):this.stack.push(p)}close(){if(this.sharedDepth>0){this.sharedDepth--;return}this.stack.pop()===this.shared&&(this.shared=null),this.stack.length===0&&this.stack.push(this.root)}text(e,s,a){if(this.sharedDepth>0)return;let n=!0;for(let l=s;l<a;l++)if(e[l]>32){n=!1;break}n||(this.stack[this.stack.length-1].t+=Qe(B(e,s,a)))}}function Ne(t){const e=new Ie;return e.feed(typeof t=="string"?new TextEncoder().encode(t):t),e.finish()}async function Ce(t,e){if(t instanceof Uint8Array)e.feed(t);else if(t.getReader){const s=t.getReader();for(;;){const{done:a,value:n}=await s.read();if(a)break;e.feed(n)}}else for await(const s of t)e.feed(s);return e.finish()}function W(t){const e=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(\.\d+)?)?/.exec(t??"");if(!e)return 0;const s=Xe(Number(e[1]),Number(e[2]),Number(e[3]));return e[4]===void 0?s:s+(Number(e[4])*3600+Number(e[5])*60+Number(e[6])+Number(e[7]??0))/86400}const q=(t,e=2)=>String(t).padStart(e,"0");function H(t){const e=je(t),s=Math.floor(e.ms/1e3);return`${q(e.year,4)}-${q(e.month)}-${q(e.day)}T${q(Math.floor(s/3600))}:${q(Math.floor(s/60)%60)}:${q(s%60)}`}class pt{constructor(e){this.positions=e.fields.filter(a=>a.a.databaseField===void 0||S(a.a.databaseField,!0));const s=e.c?Number(e.a.recordCount??1024):1024;this.capacity=Math.max(s,16),this.count=0,this.columns=this.positions.map(()=>({ids:null,kinds:null,nums:null})),this.pool=new Map,this.strings=[],this.at=-1,this.scanner=new me(this),this.inRecord=!1}feed(e){this.scanner.feed(e)}_grow(){this.capacity*=2;const e=(s,a)=>{if(a===null)return null;const n=new s(this.capacity);return n.set(a),n};for(const s of this.columns)s.ids=e(Int32Array,s.ids),s.kinds=e(Uint8Array,s.kinds),s.nums=e(Float64Array,s.nums)}open(e,s,a,n,l){if(a-s!==1)return;const o=e[s];if(o===114){this.count===this.capacity&&this._grow(),this.count++,this.at=0;return}if(this.at<0)return;const c=this.at++,r=this.columns[c];if(r===void 0)return;const i=this.count-1;if(o===120){r.ids===null&&(r.ids=new Int32Array(this.capacity));let u=0,h=Ee(e,n,l);if(h>=0)for(;h<l;h++){const g=e[h]-48;if(g<0||g>9)break;u=u*10+g}r.ids[i]=u;return}if(r.kinds===null&&(r.kinds=new Uint8Array(this.capacity),r.nums=new Float64Array(this.capacity)),o===109)return;const d=Ee(e,n,l);if(d<0)return;let p=d;const f=e[d-1];for(;p<l&&e[p]!==f;)p++;switch(o){case 110:r.kinds[i]=pe,r.nums[i]=Number(B(e,d,p));break;case 115:{const u=he(B(e,d,p));let h=this.pool.get(u);h===void 0&&(h=this.strings.length,this.strings.push(u),this.pool.set(u,h)),r.kinds[i]=Je,r.nums[i]=h;break}case 100:r.kinds[i]=pe,r.nums[i]=W(B(e,d,p)),r.dates=!0;break;case 98:r.kinds[i]=Ue,r.nums[i]=e[d]===49||e[d]===116?1:0;break;case 101:{const u=we.get(B(e,d,p));r.kinds[i]=Ke,r.nums[i]=u?u.index:6;break}default:}}close(e,s,a){a-s===1&&e[s]===114&&(this.at=-1)}text(){}finish(){return this}}function Ee(t,e,s){for(let a=e;a<s-2;a++)if(t[a]===118&&t[a+1]===61&&t[a-1]<=32)return a+3;return-1}async function ht(t){const e=await Ce(t,new Ie),s=y(e,"cacheFields");return{root:e,fields:s?A(s,"cacheField"):[],a:e.a,c:e.c}}async function mt(t,e){return Ce(t,new pt(e))}function Re(t){const e=y(t,"groupItems");return e?e.c.map(s=>Te(s.n,s.a)):[]}function gt(t,e){const s=Number(t.numFmtId??0);return Y[s]??e?.(s)??"General"}function wt(t,e,{numFmtOf:s}={}){const a=new tt,{fields:n}=t;a.xml={root:t.root},a.needsRefresh=e==null;const l=e?e.count:0;a.recordCount=l,e&&(a.strings.list=e.strings,a.strings.index=e.pool);let o=0;n.forEach((c,r)=>{const i=new nt(a,r,c.a.name??`Field${r+1}`);i.xml={node:c},Q(i,gt(c.a,s));const d=y(c,"sharedItems"),p=d?.items??[],f=c.a.databaseField===void 0||S(c.a.databaseField,!0);if(d&&S(d.a.containsDate,!1)&&i.numFmt==="General"&&Q(i,"m/d/yyyy"),c.a.formula!==void 0)i.formula=c.a.formula;else if(f&&e){const u=e.columns[o];u?.ids?(i.rawIds=u.ids.subarray(0,l),i.shared=p.slice()):u?.kinds&&(at(i,u.kinds.subarray(0,l),u.nums.subarray(0,l),l),u.dates&&i.numFmt==="General"&&Q(i,"m/d/yyyy"))}else f&&(i.shared=p.slice(),i.rawIds=new Int32Array(0));f&&o++,a.fields.push(i)}),n.forEach((c,r)=>{const i=y(c,"fieldGroup");if(!i)return;const d=a.fields[r],p=i.a.base!==void 0?Number(i.a.base):r;i.a.par!==void 0&&(d.par=Number(i.a.par)),p!==r&&(d.base=p);const f=y(i,"rangePr"),u=y(i,"discretePr"),h=Re(i);if(f){const g=f.a.groupBy??"range",x=S(f.a.autoStart,!0),T=S(f.a.autoEnd,!0);if(g==="range"){const w=Number(f.a.startNum??0),b=Number(f.a.endNum??0),v=Number(f.a.groupInterval??1),F=h.length>1&&/^-?\d+--?\d+$/.test(String(h[1]))&&Number.isInteger(w)&&Number.isInteger(v)&&Number(String(h[1]).match(/^-?\d+-(-?\d+)$/)?.[1])===w+v-1;d.group={kind:"bins",start:w,end:b,interval:v,integer:F,autoStart:x,autoEnd:T,labels:h}}else d.group={kind:"date",part:g,start:Math.floor(W(f.a.startDate)),end:Math.floor(W(f.a.endDate))-1,autoStart:x,autoEnd:T,labels:h}}else if(u&&p!==r){const g=a.fields[p],x=A(u,"x").map(v=>Number(v.a.v??0)),T=h.map(()=>[]),w=y(n[p],"sharedItems")?.items??g.shared??[];x.forEach((v,F)=>{T[v]&&T[v].push($(w[F]??null))});const b=[];h.forEach((v,F)=>{T[F].length===1&&T[F][0]===$(v)||b.push({name:String(v),keys:T[F]})}),d.group={kind:"discrete",groups:b}}});for(const c of a.fields)if(c.formula!==null)try{c.calc=ot(c.formula,a)}catch{c.calc={fn:()=>{throw be[4]},refs:[]}}return a}function se(t,e){const s=t.fields[e].xml?.node,a=s?y(s,"fieldGroup"):null,n=a?Re(a):[];return n.length>0?n:(s?y(s,"sharedItems"):null)?.items??[]}function bt(t){const e=t.a.type??"",s=y(y(t,"autoFilter"),"filterColumn");if(e==="count"||e==="percent"||e==="sum"){const a=y(s,"top10");return a?{top:{count:Number(a.a.val??10),by:e==="count"?"items":e,bottom:a.a.top==="0"||a.a.top==="false",data:Number(t.a.iMeasureFld??0)}}:null}if(He(e))return{dateFilter:Ve(t)};if(e.startsWith("caption"))return{labelFilter:{op:e,value:t.a.stringValue1??"",value2:t.a.stringValue2??""}};if(e.startsWith("value")){const a=A(y(s,"customFilters"),"customFilter");return a.length===0?null:{valueFilter:{op:e,data:Number(t.a.iMeasureFld??0),value:Number(a[0].a.val),value2:a[1]?Number(a[1].a.val):void 0}}}return null}function xt(t){for(const e of A(y(t,"extLst"),"ext")){const s=y(e,"x14:pivotTableDefinition");if(s)return s}return null}function yt(t,e){const s=t?y(t,"extLst"):null,a=[];let n=!1;for(const l of s?.c??[]){const o=y(l,"x14:pivotTableDefinition");if(!o){a.push(l);continue}n=!0;const c={...o.a};delete c.hideValuesRow,e&&(c.hideValuesRow="1"),a.push(m("ext",l.a,l.c.map(r=>r===o?m(o.n,c,o.c):r)))}return!n&&e&&a.push(m("ext",{uri:lt,"xmlns:x14":z},[m("x14:pivotTableDefinition",{hideValuesRow:"1"})])),a.length>0?m("extLst",{},a):null}function vt(t,e,{numFmtOf:s,sheet:a}={}){const n={name:t.a.name??"PivotTable1",fieldOptions:{},rows:A(y(t,"rowFields"),"field").map(u=>Number(u.a.x)),cols:A(y(t,"colFields"),"field").map(u=>Number(u.a.x)),filters:[],values:[],grandRow:S(t.a.colGrandTotals,!0),grandCol:S(t.a.rowGrandTotals,!0),rowCaption:t.a.rowHeaderCaption??null,colCaption:t.a.colHeaderCaption??null,dataCaption:t.a.dataCaption??"Values",grandCaption:t.a.grandTotalCaption??null,emptyText:S(t.a.showMissing,!0)?t.a.missingCaption??"":"",showMissing:S(t.a.showMissing,!0),errorText:S(t.a.showError,!1)?t.a.errorCaption??"":null,showExpandButtons:S(t.a.showDrill,!0),showFieldHeaders:S(t.a.showHeaders,!0),hideValuesRow:S(xt(t)?.a.hideValuesRow,!1)},l=A(y(t,"pivotFields"),"pivotField"),o={root:t,fields:l,itemAttrs:[],pageFields:new Map,rawFilters:[]},c=[];l.forEach((u,h)=>{const g={},x=se(e,h),T=A(y(u,"items"),"item"),w=[],b=[],v=[],F={},N=new Map;for(const C of T){if(C.a.t!==void 0&&C.a.t!=="data")continue;const k=Number(C.a.x??0),R=$(x[k]??null);v.push(R),N.set(R,C.a),S(C.a.h,!1)&&w.push(R),C.a.sd!==void 0&&!S(C.a.sd,!0)&&b.push(R),C.a.n!==void 0&&(F[R]=C.a.n)}o.itemAttrs[h]=N,w.length&&(g.hidden=w),b.length&&(g.collapsedItems=b),Object.keys(F).length&&(g.itemCaptions=F),u.a.name!==void 0&&(g.caption=u.a.name);const D=u.a.sortType??"manual";if(D==="ascending"||D==="descending"){g.sort={order:D==="ascending"?"asc":"desc"};const C=y(y(u,"autoSortScope"),"pivotArea"),k=y(y(C,"references"),"reference");k&&Number(k.a.field)===ve&&(g.sort.data=Number(y(k,"x")?.a.v??0))}else v.length>0&&u.a.axis&&(g.sort={order:"manual",keys:v});const P=Object.entries(te).filter(([,C])=>S(u.a[C],!1)).map(([C])=>C);P.length>0?g.subtotals=P:S(u.a.defaultSubtotal,!0)||(g.subtotals="none"),u.a.subtotalTop!==void 0&&(g.subtotalTop=S(u.a.subtotalTop,!0)),S(u.a.insertBlankRow,!1)&&(g.blankLine=!0),u.a.axis&&S(u.a.showAll,!0)&&(g.showAll=!0),S(u.a.insertPageBreak,!1)&&(g.pageBreak=!0);for(const C of A(y(u,"extLst"),"ext"))S(y(C,"x14:pivotField")?.a.fillDownLabels,!1)&&(g.repeatLabels=!0);if(u.a.axis==="axisRow"||u.a.axis==="axisCol"){const C=S(u.a.compact,!0)?"compact":S(u.a.outline,!0)?"outline":"tabular";c.push([h,C])}Object.keys(g).length>0&&(n.fieldOptions[h]=g)});const r=new Map;for(const[,u]of c)r.set(u,(r.get(u)??0)+1);n.layout=[...r.entries()].sort((u,h)=>h[1]-u[1])[0]?.[0]??"compact";for(const[u,h]of c)h!==n.layout&&(n.fieldOptions[u]??={},n.fieldOptions[u].layout=h);for(const u of A(y(t,"pageFields"),"pageField")){const h=Number(u.a.fld);if(n.filters.push(h),o.pageFields.set(h,u.a),u.a.item!==void 0){const g=A(y(l[h],"items"),"item"),x=g[Number(u.a.item)],T=se(e,h);if(x){const w=$(T[Number(x.a.x??0)]??null),b=[];for(const v of g){if(v.a.t!==void 0&&v.a.t!=="data")continue;const F=$(T[Number(v.a.x??0)]??null);F!==w&&b.push(F)}n.fieldOptions[h]??={},n.fieldOptions[h].hidden=b}}}for(const u of A(y(t,"dataFields"),"dataField")){const h=Number(u.a.fld),g={field:h,name:u.a.name??rt(u.a.subtotal??"sum",e.fields[h].name),agg:u.a.subtotal??"sum",xml:u};let x=u.a.showDataAs??"normal";const T=y(y(u,"extLst"),"ext"),w=T?y(T,"x14:dataField"):null;if(w?.a.pivotShowAs&&(x=w.a.pivotShowAs),x!=="normal"&&(g.showAs={type:x},u.a.baseField!==void 0&&(g.showAs.baseField=Number(u.a.baseField)),u.a.baseItem!==void 0)){const b=Number(u.a.baseItem);if(b===xe)g.showAs.baseItem="prev";else if(b===ye)g.showAs.baseItem="next";else{const v=g.showAs.baseField,F=A(y(l[v],"items"),"item"),N=se(e,v),D=F[b];g.showAs.baseItem=D?$(N[Number(D.a.x??0)]??null):"prev"}}if(u.a.numFmtId!==void 0){const b=Number(u.a.numFmtId),v=Y[b]??s?.(b);v&&(g.numFmt=v)}n.values.push(g)}for(const u of A(y(t,"filters"),"filter")){const h=bt(u),g=Number(u.a.fld);if(h===null){o.rawFilters.push(u);continue}n.fieldOptions[g]??={},Object.assign(n.fieldOptions[g],h)}S(t.a.mergeItem,!1)&&(n.mergeLabels=!0);const i=y(t,"pivotTableStyleInfo");i&&(n.style={name:i.a.name??"PivotStyleLight16",rowHeaders:S(i.a.showRowHeaders,!0),colHeaders:S(i.a.showColHeaders,!0),rowStripes:S(i.a.showRowStripes,!1),colStripes:S(i.a.showColStripes,!1),lastColumn:S(i.a.showLastColumn,!0)});const d=new st(e,n);d.xml=o,d.dirty=!1;const p=y(t,"location"),f=p?de(p.a.ref??""):null;if(f){const u=n.filters.length>0?n.filters.length+1:0;d.anchor={sheet:a??null,row:Math.max(0,f.r0-u),col:f.c0},d.renderedRange={r0:d.anchor.row,c0:f.c0,r1:f.r1,c1:f.c1}}return d}async function ae(t,e){const s=Ze(e);if(!t.has(s))return[];const a=Ne(await t.bytes(s));return A(a,"Relationship").map(n=>({id:n.a.Id,type:n.a.Type,target:ze(e,n.a.Target??"")}))}async function zt(t,{sheets:e,book:s,tables:a=[],numFmtOf:n,readRecords:l=!0}){const o=new Map,c=[];for(const{part:r,sheet:i}of e)if(r)for(const d of await ae(t,r)){if(d.type!==_.table||!t.has(d.target))continue;const p=Ne(await t.bytes(d.target)),u=(await ae(t,d.target)).find(x=>x.type===_.definition);if(!u||!t.has(u.target))continue;let h=o.get(u.target);if(h===void 0){const x=await ht(await t.stream(u.target)),w=(await ae(t,u.target)).find(v=>v.type===_.records);let b=null;l&&w&&t.has(w.target)&&(b=await mt(await t.stream(w.target),x)),h=wt(x,b,{numFmtOf:n}),h.refreshOnLoad=["1","true"].includes(x.a.refreshOnLoad),h.part=u.target,h.id=p.a.cacheId!==void 0?Number(p.a.cacheId):0,Ft(h,x,s,a),o.set(u.target,h)}const g=vt(p,h,{numFmtOf:n,sheet:i});g.part=d.target,c.push(g)}return{caches:[...o.values()],pivots:c}}function Ft(t,e,s,a){if(!s)return;const n=y(y(e.root,"cacheSource"),"worksheetSource");if(!n)return;if(n.a.name!==void 0){const c=a.find(r=>r.name?.toLowerCase()===n.a.name.toLowerCase());c&&(t.source={type:"table",book:s,table:c});return}const l=de(n.a.ref??""),o=s.sheets.find(c=>c.name===n.a.sheet);l&&o&&(t.source={type:"range",book:s,sheet:o,range:l})}const K=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
- `,oe=new TextEncoder;function ke(t){for(const[e,s]of Object.entries(Y))if(s===t)return Number(e);return null}function re(t,e){if(t==null)return"<m/>";switch(typeof t){case"number":return e?`<d v="${H(t)}"/>`:`<n v="${t}"/>`;case"string":return`<s v="${ge(t)}"/>`;case"boolean":return`<b v="${t?1:0}"/>`;default:return`<e v="${J(t.code)}"/>`}}function Ae(t,e){const{hasNum:s,hasInt:a,hasText:n,hasBlank:l,hasOther:o,min:c,max:r,longText:i}=e,d=t.isDate&&s&&!n&&!o,p={};return!n&&!l&&!o&&(p.containsSemiMixedTypes="0"),d&&!l&&(p.containsNonDate="0"),d&&(p.containsDate="1"),n||(p.containsString="0"),l&&(p.containsBlank="1"),(s?1:0)+(n?1:0)+(o?1:0)>1&&(p.containsMixedTypes="1"),s&&!d&&(p.containsNumber="1",a&&(p.containsInteger="1"),p.minValue=String(c),p.maxValue=String(r)),d&&(p.minDate=H(c),p.maxDate=H(Math.floor(r)+1)),i&&(p.longText="1"),{attrs:p,date:d}}function St(t){const e={hasNum:!1,hasInt:!0,hasText:!1,hasBlank:!1,hasOther:!1,min:1/0,max:-1/0,longText:!1};for(const s of t)typeof s=="number"?(e.hasNum=!0,Number.isInteger(s)||(e.hasInt=!1),s<e.min&&(e.min=s),s>e.max&&(e.max=s)):typeof s=="string"?(e.hasText=!0,s.length>255&&(e.longText=!0)):s==null?e.hasBlank=!0:e.hasOther=!0;return e}function Tt(t){const e={hasNum:t.length>0,hasInt:!0,hasText:!1,hasBlank:!1,hasOther:!1,min:1/0,max:-1/0,longText:!1};for(let s=0;s<t.length;s++){const a=t[s];a<e.min&&(e.min=a),a>e.max&&(e.max=a),e.hasInt&&Math.floor(a)!==a&&(e.hasInt=!1)}return e}function De(t){return t.ensureColumn(),t.rawIds!==null?!0:!(t.nums!==null&&t.kinds===null)}function It(t,e){const s=e.group;if(s===null)return e.par>=0?m("fieldGroup",{par:String(e.par)}):null;e.ensure();const a={};e.par>=0&&(a.par=String(e.par)),a.base=String(e.base>=0?e.base:e.index);const n=[],l=e.items.map(c=>re(c,!1)).join("");if(s.kind==="date"){const c={groupBy:s.part,startDate:H(s.start),endDate:H(s.end+1)};s.autoStart||(c.autoStart="0"),s.autoEnd||(c.autoEnd="0"),n.push(m("rangePr",c))}else if(s.kind==="bins"){const c={startNum:String(s.start),endNum:String(s.end),groupInterval:String(s.interval)};s.autoStart||(c.autoStart="0"),s.autoEnd||(c.autoEnd="0"),n.push(m("rangePr",c))}else{const c=e.groupMap,r=m("discretePr",{count:String(c.length)});for(let i=0;i<c.length;i++)r.c.push(m("x",{v:String(c[i])}));n.push(r)}const o=m("groupItems",{count:String(e.items.length)});return o.c.push(l),n.push(o),m("fieldGroup",a,n)}function Nt(t,e,s){const a=e.xml?.node??null,n={...a?.a??{}};if(n.name=e.name,n.numFmtId===void 0){const c=e.numFmt!=="General"?ke(e.numFmt)??s.numFmtId?.(e.numFmt)??(e.isDate?14:0):0;n.numFmtId=String(c)}const l=[];if(e.isCalculated)n.formula=e.formula,n.databaseField="0",delete n.uniqueList;else if(e.base>=0)n.databaseField="0";else if(t.recordCount===0&&a&&y(a,"sharedItems")){const c=y(a,"sharedItems"),r=m("sharedItems",{...c.a}),i=S(c.a.containsDate,!1);c.items.length>0&&r.c.push(c.items.map(d=>re(d,i&&typeof d=="number")).join("")),l.push(r)}else if(De(e)){e.ensureRaw();const{attrs:c,date:r}=Ae(e,St(e.shared)),i=m("sharedItems",{...c,count:String(e.shared.length)});i.c.push(e.shared.map(d=>re(d,r&&typeof d=="number")).join("")),l.push(i)}else{const{attrs:c}=Ae(e,Tt(e.nums));l.push(m("sharedItems",c))}const o=It(t,e);if(o&&l.push(o),a)for(const c of a.c)c.n!=="sharedItems"&&c.n!=="fieldGroup"&&l.push(c);return m("cacheField",n,l)}function Ct(t,{recordsRel:e=null,numFmtId:s,refreshOnLoad:a=!0,sourceSheetName:n}={}){const l=t.xml?.root??null,o={...l?.a??{}};o.xmlns??=U,o["xmlns:r"]??=V,e?o["r:id"]=e:delete o["r:id"],a&&(o.refreshOnLoad="1"),o.refreshedBy??="8sheets",o.refreshedDate=String(Et()),o.createdVersion??="6",o.refreshedVersion??="6",o.minRefreshableVersion??="3",o.recordCount=String(t.recordCount),e?delete o.saveData:o.saveData="0";const c=[],r=l?y(l,"cacheSource"):null;c.push(Rt(t,r,n));const i=m("cacheFields",{count:"0"}),d=t.fields;for(const p of d)i.c.push(Nt(t,p,{numFmtId:s}));if(i.a.count=String(d.length),c.push(i),l)for(const p of l.c)p.n!=="cacheSource"&&p.n!=="cacheFields"&&c.push(p);return K+ne(m("pivotCacheDefinition",o,c)).join("")}function Et(){return Math.round((Date.now()/864e5+25569)*1e5)/1e5}function Rt(t,e,s){const a=t.source;if(a===null)return e??m("cacheSource",{type:"worksheet"},[m("worksheetSource",{ref:"A1",sheet:"Sheet1"})]);const n={};if(a.type==="table")n.name=a.table.name;else{const i=a.range,d=s??(typeof a.sheet=="string"?a.sheet:a.sheet.name);n.ref=fe({r0:i.r0,c0:i.c0,r1:i.r1,c1:Math.min(i.c1,Ge-1)}),n.sheet=d}const l=e?{...e.a}:{type:"worksheet"},o=e?e.c.filter(i=>i.n!=="worksheetSource"):[],c=e?y(e,"worksheetSource"):null,r=c?{...c.a,...n}:n;return a.type==="table"&&(delete r.ref,delete r.sheet),m("cacheSource",l,[m("worksheetSource",r),...o])}const kt=4096;async function Oe(t,e){const s=t.recordCount,a=[];for(const l of t.fields)l.isVirtual||(De(l)?(l.ensureRaw(),a.push(At(l.rawIds))):a.push(Dt(l.nums,l.isDate)));await e(oe.encode(`${K}<pivotCacheRecords xmlns="${U}" xmlns:r="${V}" count="${s}">`));const n=[];for(let l=0;l<s;l++){n.push("<r>");for(let o=0;o<a.length;o++)n.push(a[o](l));n.push("</r>"),(l+1)%kt===0&&(await e(oe.encode(n.join(""))),n.length=0)}n.push("</pivotCacheRecords>"),await e(oe.encode(n.join("")))}function At(t){return e=>`<x v="${t[e]}"/>`}function Dt(t,e){return e?s=>`<d v="${H(t[s])}"/>`:s=>`<n v="${t[s]}"/>`}async function en(t){const e="application/xml";let s=new Blob([],{type:e}),a=[],n=0;return await Oe(t,l=>{a.push(l),n+=l.length,n>=1<<24&&(s=new Blob([s,...a],{type:e}),a=[],n=0)}),new Blob([s,...a],{type:e})}const Le=["location","pivotFields","rowFields","rowItems","colFields","colItems","pageFields","dataFields","formats","conditionalFormats","chartFormats","pivotHierarchies","pivotTableStyleInfo","filters","rowHierarchiesUsage","colHierarchiesUsage","extLst"];function Ot(t,e){const s=t.cache.fields[e].ensure(),a=s.rank(),n=Array.from(s.items.keys()),o=t.spec.fieldOptions[e]?.sort;if(o?.order==="manual"){const r=new Map((o.keys??[]).map((p,f)=>[p,f])),i=r.size,d=p=>r.get($(s.items[p]))??i+a[p];n.sort((p,f)=>d(p)-d(f))}else o?.order==="desc"&&(o.data===void 0||o.data===null)?n.sort((r,i)=>a[i]-a[r]):n.sort((r,i)=>a[r]-a[i]);const c=new Int32Array(n.length);return n.forEach((r,i)=>{c[r]=i}),{order:n,position:c}}function Lt(t){return t.group!==null||t.base>=0}function Pt(t,e){return t.spec.fieldOptions[e]?.layout??t.spec.layout}const Bt=["axis","dataField","compact","outline","subtotalTop","sortType","defaultSubtotal","insertBlankRow","name","showDropDowns","dragToRow","dragToCol","dragToPage",...Object.values(te)];function Mt(t,e,s){const{spec:a,cache:n}=t,l=n.fields[e],o=a.fieldOptions[e]??{},c=t.xml?.fields?.[e]??null,r={...c?.a??{}};for(const F of Bt)delete r[F];o.caption!==void 0&&(r.name=o.caption);const i=a.rows.includes(e),d=a.cols.includes(e),p=a.filters.includes(e),f=a.values.some(F=>F.field===e);i?r.axis="axisRow":d?r.axis="axisCol":p&&(r.axis="axisPage"),f&&(r.dataField="1");const u=Pt(t,e);u!=="compact"&&(r.compact="0"),u==="tabular"&&(r.outline="0"),l.isCalculated&&(r.dragToRow="0",r.dragToCol="0",r.dragToPage="0"),r.showAll=o.showAll?"1":"0",o.pageBreak?r.insertPageBreak="1":delete r.insertPageBreak,(o.subtotalTop??a.subtotalTop)===!1&&(i||d)&&(r.subtotalTop="0"),o.blankLine&&(r.insertBlankRow="1"),o.sort?.order==="asc"?r.sortType="ascending":o.sort?.order==="desc"&&(r.sortType="descending");const h=o.subtotals??"auto",g=i||d||p,x=(o.hidden?.length??0)>0,T=g||Lt(l)||x||!!(o.range||o.dateFilter);if((l.isCalculated||h==="none"||Array.isArray(h)||l.base>=0&&!g)&&(r.defaultSubtotal="0"),Array.isArray(h))for(const F of h)r[te[F]]="1";const w=[];if(T&&!l.isCalculated){const{order:F}=s(e),N=m("items",{}),D=new Set(o.hidden??[]),P=new Set(o.collapsedItems??[]),C=t.xml?.itemAttrs?.[e]??null,k=o.itemCaptions??null;for(const R of F){const O=l.keyOf(R),L={...C?.get(O)??{}};delete L.h,delete L.sd,delete L.n,L.x=String(R),D.has(O)&&(L.h="1"),P.has(O)&&(L.sd="0"),k&&k[O]!==void 0&&(L.n=k[O]),N.c.push(m("item",L))}if((g||x||o.range||o.dateFilter)&&r.defaultSubtotal===void 0&&N.c.push(m("item",{t:"default"})),Array.isArray(h))for(const R of h)N.c.push(m("item",{t:Fe[R]}));N.a.count=String(N.c.length),w.push(N)}if(o.sort?.data!==void 0&&o.sort?.data!==null&&(o.sort.order==="asc"||o.sort.order==="desc")&&w.push(m("autoSortScope",{},[m("pivotArea",{dataOnly:"0",outline:"0",fieldPosition:"0"},[m("references",{count:"1"},[m("reference",{field:String(ve),count:"1",selected:"0"},[m("x",{v:String(o.sort.data)})])])])])),c)for(const F of c.c)F.n!=="items"&&F.n!=="autoSortScope"&&F.n!=="extLst"&&w.push(F);const b=o.repeatLabels===!0||a.repeatLabels===!0&&i&&u!=="compact",v=$t(c,b);return v&&w.push(v),m("pivotField",r,w)}function $t(t,e){const s=[];let a=!1;for(const n of A(t?y(t,"extLst"):null,"ext")){const l=y(n,"x14:pivotField");if(!l){s.push(n);continue}a=!0;const o={...l.a};delete o.fillDownLabels,e&&(o.fillDownLabels="1"),s.push(m("ext",n.a,n.c.map(c=>c===l?m(l.n,o,l.c):c)))}return!a&&e&&s.push(m("ext",{uri:ct,"xmlns:x14":z},[m("x14:pivotField",{fillDownLabels:"1"})])),s.length>0?m("extLst",{},s):null}function Pe(t,e,s,a){const n=s.lines,l=m(t,{}),{slots:o}=s;let c=[];for(let r=0;r<n.node.length;r++){const i=n.type[r],d=n.level[r],p={},f=[];if(o.length===0){l.c.push(m("i",{}));continue}if(i===j.GRAND){p.t="grand";const x=n.data[r];x>0&&(p.i=String(x));const T=m("i",p,[m("x",x>0?{v:String(x)}:{})]);l.c.push(T),c=[];continue}i===j.BLANK?p.t="blank":i===j.SUBTOTAL&&(p.t=n.func[r]?Fe[n.func[r]]:"default");let u=0;for(let x=0;x<=d;x++)if(o[x]===Z)f.push(n.data[r]>=0?n.data[r]:0);else{u++;const T=s.ancestorAt(n.node[r],u);f.push(a(o[x]).position[s.item[T]])}n.data[r]>0&&(p.i=String(n.data[r]));let h=0;if(i===j.ITEM)for(;h<f.length-1&&h<c.length&&c[h]===f[h];)h++;h>0&&(p.r=String(h));const g=m("i",p);for(let x=h;x<f.length;x++)g.c.push(m("x",f[x]===0?{}:{v:String(f[x])}));l.c.push(g),c=f}return l.c.length===0&&l.c.push(m("i",{})),l.a.count=String(l.c.length),l}function _t(t,e){const{spec:s}=t,a=[];let n=1;const l=(c,r,i,d)=>m("filter",{fld:String(c),type:r,evalOrder:"-1",id:String(n++),...i},[m("autoFilter",{ref:"A1"},[m("filterColumn",{colId:"0"},[d])])]),o=(c,r)=>m("customFilters",r?{and:"1"}:{},c.map(i=>m("customFilter",i)));for(const c of e){const r=s.fieldOptions[c];if(r){if(r.labelFilter){const i=r.labelFilter,d=String(i.value??""),p=String(i.value2??""),f={stringValue1:d};(i.op==="captionBetween"||i.op==="captionNotBetween")&&(f.stringValue2=p);const u={captionEqual:()=>o([{val:d}]),captionNotEqual:()=>o([{operator:"notEqual",val:d}]),captionBeginsWith:()=>o([{val:`${d}*`}]),captionNotBeginsWith:()=>o([{operator:"notEqual",val:`${d}*`}]),captionEndsWith:()=>o([{val:`*${d}`}]),captionNotEndsWith:()=>o([{operator:"notEqual",val:`*${d}`}]),captionContains:()=>o([{val:`*${d}*`}]),captionNotContains:()=>o([{operator:"notEqual",val:`*${d}*`}]),captionGreaterThan:()=>o([{operator:"greaterThan",val:d}]),captionGreaterThanOrEqual:()=>o([{operator:"greaterThanOrEqual",val:d}]),captionLessThan:()=>o([{operator:"lessThan",val:d}]),captionLessThanOrEqual:()=>o([{operator:"lessThanOrEqual",val:d}]),captionBetween:()=>o([{operator:"greaterThanOrEqual",val:d},{operator:"lessThanOrEqual",val:p}],!0),captionNotBetween:()=>o([{operator:"lessThan",val:d},{operator:"greaterThan",val:p}])}[i.op];u&&a.push(l(c,i.op,f,u()))}if(r.valueFilter){const i=r.valueFilter,d=String(i.value),p=String(i.value2??""),f={valueEqual:[[{val:d}]],valueNotEqual:[[{operator:"notEqual",val:d}]],valueGreaterThan:[[{operator:"greaterThan",val:d}]],valueGreaterThanOrEqual:[[{operator:"greaterThanOrEqual",val:d}]],valueLessThan:[[{operator:"lessThan",val:d}]],valueLessThanOrEqual:[[{operator:"lessThanOrEqual",val:d}]],valueBetween:[[{operator:"greaterThanOrEqual",val:d},{operator:"lessThanOrEqual",val:p}],!0],valueNotBetween:[[{operator:"lessThan",val:d},{operator:"greaterThan",val:p}]]}[i.op];f&&a.push(l(c,i.op,{iMeasureFld:String(i.data??0)},o(f[0],f[1]===!0)))}if(a.push(...qe(r,c,m,()=>n++)),r.top){const i=r.top,d={val:String(i.count??10),filterVal:String(i.count??10)};i.by==="percent"&&(d.percent="1"),i.bottom&&(d.top="0");const p=i.by==="percent"?"percent":i.by==="sum"?"sum":"count";a.push(l(c,p,{iMeasureFld:String(i.data??0)},m("top10",d)))}}}return a}function qt(t,e,s,a){const n=e.xml??null,l={...n?.a??{}};l.name=e.name,l.fld=String(e.field),e.agg&&e.agg!=="sum"?l.subtotal=e.agg:delete l.subtotal,delete l.showDataAs;const o=e.showAs?.type??"normal",c=n?n.c.filter(g=>g.n!=="extLst"):[];let r=null;ut.has(o)?r=o:o!=="normal"&&(l.showDataAs=o);const i=e.showAs?.baseField??0;l.baseField=String(i>=0?i:0);let d=0;const p=e.showAs?.baseItem;if(p==="prev")d=xe;else if(p==="next")d=ye;else if(p!==void 0&&e.showAs?.baseField>=0){const g=t.cache.fields[e.showAs.baseField].ensure(),x=g.keyIndex.get(p);x!==void 0&&(d=s(g.index).position[x])}l.baseItem=String(d);const f=e.numFmt??(o!=="normal"&&!o.startsWith("rank")&&o!=="difference"&&o!=="runTotal"?o==="index"?"0.00":"0.00%":null);if(f){const g=ke(f)??a.numFmtId?.(f);g!=null&&(l.numFmtId=String(g))}else delete l.numFmtId;const u=[],h=n?y(n,"extLst"):null;if(h)for(const g of h.c)if(y(g,"x14:dataField")){const x={...y(g,"x14:dataField").a};delete x.pivotShowAs,r&&(x.pivotShowAs=r),u.push(m("ext",g.a,[m("x14:dataField",x)])),r=null}else u.push(g);return r&&u.push(m("ext",{uri:it,"xmlns:x14":z},[m("x14:dataField",{pivotShowAs:r})])),u.length&&c.push(m("extLst",{},u)),m("dataField",l,c)}function Ht(t,{cacheId:e,numFmtId:s}={}){const a=t.result??t.update(),{spec:n,cache:l}=t,{layout:o,rows:c,cols:r}=a,i=new Map,d=I=>{let E=i.get(I);return E===void 0&&(E=Ot(t,I),i.set(I,E)),E},p=t.xml?.root??null,f={...p?.a??{}};f.xmlns??=U,f.name=n.name,f.cacheId=String(e??l.id??1),f.applyNumberFormats??="0",f.applyBorderFormats??="0",f.applyFontFormats??="0",f.applyPatternFormats??="0",f.applyAlignmentFormats??="0",f.applyWidthHeightFormats??="1",f.dataCaption=n.dataCaption,f.updatedVersion??="6",f.minRefreshableVersion??="3",f.useAutoFormatting??="1",f.itemPrintTitles??="1",f.createdVersion??="6",f.indent??="0",n.mergeLabels?f.mergeItem="1":delete f.mergeItem,t.fileAttrs&&Object.assign(f,t.fileAttrs);const u=(I,E,G)=>{E===G?delete f[I]:f[I]=E?"1":"0"};u("compact",n.layout==="compact",!0),u("compactData",n.layout==="compact",!0),f.outline=n.layout==="tabular"?f.outline??"1":"1",f.outlineData=n.layout==="tabular"?f.outlineData??"1":"1",u("colGrandTotals",n.grandRow,!0),u("rowGrandTotals",n.grandCol,!0),n.rowCaption!=null?f.rowHeaderCaption=n.rowCaption:delete f.rowHeaderCaption,n.colCaption!=null?f.colHeaderCaption=n.colCaption:delete f.colHeaderCaption,n.grandCaption!=null?f.grandTotalCaption=n.grandCaption:delete f.grandTotalCaption,n.emptyText!==""&&n.showMissing!==!1?f.missingCaption=n.emptyText:delete f.missingCaption,n.showMissing===!1?f.showMissing="0":delete f.showMissing,n.errorText!==null?(f.showError="1",f.errorCaption=n.errorText):(delete f.showError,delete f.errorCaption),c.slots.includes(Z)?(f.dataOnRows="1",f.dataPosition=String(c.slots.indexOf(Z))):(delete f.dataOnRows,delete f.dataPosition);const h=Object.keys(n.fieldOptions).map(Number),g=h.some(I=>{const E=n.fieldOptions[I];return(E.labelFilter?1:0)+(E.valueFilter?1:0)+(E.top?1:0)>1});f.multipleFieldFilters=g?"1":"0";const x=t.anchor??{row:0,col:0},T=x.row+o.pageRows,w={ref:fe({r0:T,c0:x.col,r1:x.row+o.rows-1,c1:x.col+Math.max(o.bodyCols,1)-1}),firstHeaderRow:String(o.firstHeaderRow),firstDataRow:String(o.firstDataRow),firstDataCol:String(o.firstDataCol)};n.filters.length>0&&(w.rowPageCount=String(n.filters.length),w.colPageCount="1");const b=new Map;b.set("location",m("location",w));const v=m("pivotFields",{count:String(l.fields.length)});for(let I=0;I<l.fields.length;I++)v.c.push(Mt(t,I,d));b.set("pivotFields",v);const F=(I,E)=>m(I,{count:String(E.length)},E.map(G=>m("field",{x:String(G)})));if(c.slots.length>0&&b.set("rowFields",F("rowFields",c.slots)),b.set("rowItems",Pe("rowItems",a,c,d)),r.slots.length>0&&b.set("colFields",F("colFields",r.slots)),b.set("colItems",Pe("colItems",a,r,d)),n.filters.length>0){const I=m("pageFields",{count:String(n.filters.length)});for(const E of n.filters){const X={...t.xml?.pageFields?.get(E)??{},fld:String(E)};delete X.item,X.hier??="-1";const le=l.fields[E].ensure(),ce=n.fieldOptions[E]?.hidden??[];if(ce.length===le.items.length-1){const Be=new Set(ce),ue=d(E).order.findIndex(Me=>!Be.has(le.keyOf(Me)));ue>=0&&(X.item=String(ue))}I.c.push(m("pageField",X))}b.set("pageFields",I)}n.values.length>0&&b.set("dataFields",m("dataFields",{count:String(n.values.length)},n.values.map(I=>qt(t,I,d,{numFmtId:s}))));const N=n.style,D=p?y(p,"pivotTableStyleInfo"):null;b.set("pivotTableStyleInfo",m("pivotTableStyleInfo",{...D?.a??{},name:N.name,showRowHeaders:N.rowHeaders?"1":"0",showColHeaders:N.colHeaders?"1":"0",showRowStripes:N.rowStripes?"1":"0",showColStripes:N.colStripes?"1":"0",showLastColumn:N.lastColumn===!1?"0":"1"}));const P=_t(t,h),C=t.xml?.rawFilters??[],k=[...P,...C];k.length>0&&b.set("filters",m("filters",{count:String(k.length)},k));const R=$e(t,m);R&&b.set("conditionalFormats",R);const O=_e(t,m);O&&b.set("chartFormats",O);const L=yt(p,n.hideValuesRow);L&&b.set("extLst",L);const M=[];for(const I of Le)if(b.has(I))M.push(b.get(I));else if(p&&!Vt.has(I)){const E=y(p,I);E&&M.push(E)}if(p)for(const I of p.c)Le.includes(I.n)||M.splice(M.length-(M[M.length-1]?.n==="extLst"?1:0),0,I);return K+ne(m("pivotTableDefinition",f,M)).join("")}const Vt=new Set(["extLst","location","pivotFields","rowFields","rowItems","colFields","colItems","pageFields","dataFields","pivotTableStyleInfo","filters"]);function ie(t,e){for(let s=1;;s++){const a=e(s);if(!t.has(a))return t.add(a),a}}function tn(t){const e=t.map(s=>`<Relationship Id="${s.id}" Type="${s.type}" Target="${J(s.target)}"/>`).join("");return`${K}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${e}</Relationships>`}function nn(t,{existing:e=[],saveRecords:s=!0,numFmtId:a,refreshOnLoad:n=!0,firstCacheId:l=1}={}){const o=new Set(e),c=[],r=[],i=[],d=[],p=new Map;let f=l;const u=w=>{c.push(w),i.push({partName:`/${w.name}`,contentType:w.contentType})},h=({result:w,cache:b})=>(w||b.load(),w||!b.deferred),g=t.filter(w=>(w.dirty||!w.part)&&h(w)),x=[];for(const w of t)!w.dirty||!w.part||g.includes(w)||(x.push(w.part),w.part=null);const T=new Set(t.filter(w=>!g.includes(w)&&w.part).map(w=>w.cache));for(const w of g){const{cache:b}=w;w.part&&x.push(w.part),b.part&&!T.has(b)&&(x.push(b.part),b.part=null);let v=p.get(b);if(v===void 0){const N=f++,D=ie(o,R=>`xl/pivotCache/pivotCacheDefinition${R}.xml`);b.id=N;let P=null;if(s&&b.recordCount>0){const R=ie(o,O=>`xl/pivotCache/pivotCacheRecords${O}.xml`);P="rId1",r.push({from:D,id:P,type:_.records,target:`/${R}`}),u({name:R,contentType:ee.records,large:!0,produce:O=>Oe(b,O)})}const k={name:D,contentType:ee.definition,xml:null};u(k),v={cacheId:N,defName:D,defPart:k,recordsRel:P},p.set(b,v),d.push({cacheId:N,target:`/${D}`,type:_.definition})}w.result||w.update();const F=ie(o,N=>`xl/pivotTables/pivotTable${N}.xml`);u({name:F,contentType:ee.table,xml:Ht(w,{cacheId:v.cacheId,numFmtId:a})}),r.push({from:F,id:"rId1",type:_.definition,target:`/${v.defName}`}),r.push({from:null,sheet:w.anchor?.sheet??null,id:null,type:_.table,target:`/${F}`}),w.part=F}for(const[w,b]of p)b.defPart.xml=Ct(w,{recordsRel:b.recordsRel,numFmtId:a,refreshOnLoad:n});return{parts:c,relationships:r,contentTypes:i,replaced:x,workbook:{pivotCaches:d,pivotCachesXml(w){return d.length===0?"":`<pivotCaches>${d.map(b=>`<pivotCache cacheId="${b.cacheId}" r:id="${w(b.cacheId)}"/>`).join("")}</pivotCaches>`}}}}export{ee as CONTENT_TYPE,pt as CacheRecordsReader,We as EMPTY,Ye as ERRORS,Ie as NodeReader,_ as REL_TYPE,et as XlError,nn as buildPivotPackage,Ct as cacheDefinitionXml,wt as cacheFromXml,W as isoToSerial,Ne as parseNode,vt as pivotFromXml,Ht as pivotTableXml,ht as readCacheDefinition,mt as readCacheRecords,zt as readPivotParts,en as recordsBlob,tn as relationshipsXml,H as serialToIso,ne as serializeNode,Oe as writeCacheRecords};
1
+ import{pivotCfNode as Ve,pivotChartFormatsNode as Xe}from"../slicers/pivot-file.js";import{dateFilterNodes as je,isDateFilterType as Ge,parseDateFilter as Ue}from"../slicers/date-filters.js";import{MAX_COLS as We,parseRangeRef as te,rangeRef as ne}from"../core/address.js";import{BUILTIN_FORMATS as se}from"../core/numfmt.js";import{BOOL as Ke,EMPTY as Ye,ERR as Ze,ERRORS as ze,NUM as he,STR as Je}from"../core/sheet.js";import{decodeRange as _,unescapeXml as Qe,unescapeXstring as pe,XmlScanner as me}from"../io/xml-scan.js";import{escapeMarkup as ae,xmlAttr as ge}from"../io/xml-escape.js";import{relsPathOf as et,resolveTarget as tt}from"../io/package-paths.js";import{ERR_BY_CODE as we,ERR_BY_INDEX as xe,XlError as nt}from"../calc/values.js";import{fileFormula as st,solveOrder as at,typedFormula as ot}from"./calc-items.js";import{applyNumFmt as oe,isSorted as rt,itemKey as q,LINE as Z,PivotCache as it,PivotError as lt,PivotField as ct,PivotTable as ut,storeColumn as dt,VALUES as V,compileCalc as ft,valueFieldName as ht,wholeSeconds as pt}from"./engine.js";const z="http://schemas.openxmlformats.org/spreadsheetml/2006/main",G="http://schemas.openxmlformats.org/officeDocument/2006/relationships",re="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main",mt="{E15A36E0-9728-4e99-A89B-3F7291B0FE68}",gt="{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}",wt="{2946ED86-A175-432a-8AC1-64E0C546D7DE}",U={table:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",definition:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml",records:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml"},H={table:`${G}/pivotTable`,definition:`${G}/pivotCacheDefinition`,records:`${G}/pivotCacheRecords`},be=1048828,ye=1048829,Se=4294967294,xt=new Set(["percentOfParent","percentOfParentRow","percentOfParentCol","percentOfRunningTotal","rankAscending","rankDescending"]),ie={sum:"sumSubtotal",count:"countASubtotal",average:"avgSubtotal",max:"maxSubtotal",min:"minSubtotal",product:"productSubtotal",countNums:"countSubtotal",stdDev:"stdDevSubtotal",stdDevp:"stdDevPSubtotal",var:"varSubtotal",varp:"varPSubtotal"},ve={sum:"sum",count:"countA",average:"avg",max:"max",min:"min",product:"product",countNums:"count",stdDev:"stdDev",stdDevp:"stdDevP",var:"var",varp:"varP"},m=(t,e={},s=[])=>({n:t,a:e,c:s,t:""}),S=(t,e)=>t?.c.find(s=>s.n===e)??null,L=(t,e)=>t?t.c.filter(s=>s.n===e):[],k=(t,e)=>t===void 0?e:t==="1"||t==="true";function Te(t,e,s){const a={};let n=e;for(;n<s;){for(;n<s&&t[n]<=32;)n++;if(n>=s)break;const i=n;for(;n<s&&t[n]!==61&&t[n]>32;)n++;const o=n;for(;n<s&&t[n]!==34&&t[n]!==39;)n++;if(n>=s)break;const l=t[n++],r=n,c=t.indexOf(l,n),d=c<0||c>s?s:c;a[_(t,i,o)]=pe(_(t,r,d)),n=d+1}return a}function bt(t,e,s){let a=e;for(;a>0&&t[a-1]!==60;)a--;return _(t,a,s)}function J(t,e=[]){e.push("<",t.n);for(const s of Object.keys(t.a)){const a=t.a[s];a!=null&&e.push(" ",s,'="',ge(a),'"')}if(t.c.length===0&&t.t==="")return e.push("/>"),e;e.push(">"),t.t&&e.push(ae(t.t));for(const s of t.c)typeof s=="string"?e.push(s):J(s,e);return e.push("</",t.n,">"),e}const yt=new Set(["s","n","d","b","e","m"]);function Fe(t,e){switch(t){case"n":return Number(e.v);case"s":return e.v??"";case"d":return W(e.v);case"b":return e.v==="1"||e.v==="true";case"e":return we.get(e.v)??xe[6];default:return null}}class Ie{constructor(){this.root=m("#root"),this.stack=[this.root],this.shared=null,this.sharedDepth=0,this.scanner=new me(this)}feed(e){this.scanner.feed(e)}finish(){return this.root.c[0]??null}open(e,s,a,n,i,o){const l=this.stack[this.stack.length-1];if(this.shared!==null&&l===this.shared){const f=_(e,s,a);if(yt.has(f)){const x=Te(e,n,i);(x.f==="1"||x.f==="true")&&(l.calculated??=new Set).add(l.items.length),l.items.push(Fe(f,x)),o||this.sharedDepth++;return}}if(this.sharedDepth>0){o||this.sharedDepth++;return}const r=Te(e,n,i);let c=bt(e,s,a);const d=c.indexOf(":");if(d>=0){const f="xmlns:"+c.slice(0,d);let x=r[f];for(let w=this.stack.length-1;x===void 0&&w>0;w--)x=this.stack[w].a[f];x===z&&(c=c.slice(d+1))}const u=m(c,r);u.n==="sharedItems"&&(u.items=[],this.shared=u),l.c.push(u),o?u.n==="sharedItems"&&(this.shared=null):this.stack.push(u)}close(){if(this.sharedDepth>0){this.sharedDepth--;return}this.stack.pop()===this.shared&&(this.shared=null),this.stack.length===0&&this.stack.push(this.root)}text(e,s,a){if(this.sharedDepth>0)return;let n=!0;for(let i=s;i<a;i++)if(e[i]>32){n=!1;break}n||(this.stack[this.stack.length-1].t+=Qe(_(e,s,a)))}}function Ne(t){const e=new Ie;return e.feed(typeof t=="string"?new TextEncoder().encode(t):t),e.finish()}async function Ce(t,e){if(t instanceof Uint8Array)e.feed(t);else if(t.getReader){const s=t.getReader();for(;;){const{done:a,value:n}=await s.read();if(a)break;e.feed(n)}}else for await(const s of t)e.feed(s);return e.finish()}const Ee=Date.UTC(1899,11,30);function W(t){const e=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(\.\d+)?)?/.exec(t??"");if(!e)return 0;const s=(Date.UTC(Number(e[1]),Number(e[2])-1,Number(e[3]))-Ee)/864e5;return e[4]===void 0?s:pt(s+(Number(e[4])*3600+Number(e[5])*60+Number(e[6])+Number(e[7]??0))/86400)}function X(t){return new Date(Ee+Math.round(t*86400)*1e3).toISOString().slice(0,19)}class St{constructor(e){this.positions=e.fields.filter(a=>a.a.databaseField===void 0||k(a.a.databaseField,!0));const s=e.c?Number(e.a.recordCount??1024):1024;this.capacity=Math.max(s,16),this.count=0,this.columns=this.positions.map(()=>({ids:null,kinds:null,nums:null})),this.pool=new Map,this.strings=[],this.at=-1,this.scanner=new me(this),this.inRecord=!1}feed(e){this.scanner.feed(e)}_grow(){this.capacity*=2;const e=(s,a)=>{if(a===null)return null;const n=new s(this.capacity);return n.set(a),n};for(const s of this.columns)s.ids=e(Int32Array,s.ids),s.kinds=e(Uint8Array,s.kinds),s.nums=e(Float64Array,s.nums)}open(e,s,a,n,i){if(a-s!==1)return;const o=e[s];if(o===114){this.count===this.capacity&&this._grow(),this.count++,this.at=0;return}if(this.at<0)return;const l=this.at++,r=this.columns[l];if(r===void 0)return;const c=this.count-1;if(o===120){r.ids===null&&(r.ids=new Int32Array(this.capacity));let x=0,w=ke(e,n,i);if(w>=0)for(;w<i;w++){const h=e[w]-48;if(h<0||h>9)break;x=x*10+h}r.ids[c]=x;return}if(r.kinds===null&&(r.kinds=new Uint8Array(this.capacity),r.nums=new Float64Array(this.capacity)),o===109)return;const d=ke(e,n,i);if(d<0)return;let u=d;const f=e[d-1];for(;u<i&&e[u]!==f;)u++;switch(o){case 110:r.kinds[c]=he,r.nums[c]=Number(_(e,d,u));break;case 115:{const x=pe(_(e,d,u));let w=this.pool.get(x);w===void 0&&(w=this.strings.length,this.strings.push(x),this.pool.set(x,w)),r.kinds[c]=Je,r.nums[c]=w;break}case 100:r.kinds[c]=he,r.nums[c]=W(_(e,d,u)),r.dates=!0;break;case 98:r.kinds[c]=Ke,r.nums[c]=e[d]===49||e[d]===116?1:0;break;case 101:{const x=we.get(_(e,d,u));r.kinds[c]=Ze,r.nums[c]=x?x.index:6;break}default:}}close(e,s,a){a-s===1&&e[s]===114&&(this.at=-1)}text(){}finish(){return this}}function ke(t,e,s){for(let a=e;a<s-2;a++)if(t[a]===118&&t[a+1]===61&&t[a-1]<=32)return a+3;return-1}async function vt(t){const e=await Ce(t,new Ie),s=S(e,"cacheFields");return{root:e,fields:s?L(s,"cacheField"):[],a:e.a,c:e.c}}async function Tt(t,e){return Ce(t,new St(e))}function Ae(t){const e=S(t,"groupItems");return e?e.c.map(s=>Fe(s.n,s.a)):[]}function Ft(t,e){const s=Number(t.numFmtId??0);return se[s]??e?.(s)??"General"}function It(t,e,{numFmtOf:s}={}){const a=new it,{fields:n}=t;a.xml={root:t.root},a.needsRefresh=e==null;const i=e?e.count:0;a.recordCount=i,e&&(a.strings.list=e.strings,a.strings.index=e.pool);let o=0;n.forEach((l,r)=>{const c=new ct(a,r,l.a.name??`Field${r+1}`);c.xml={node:l},oe(c,Ft(l.a,s));const d=S(l,"sharedItems"),{items:u,ids:f,calculated:x}=Nt(d);x.length&&(c.calcItems=x.map(h=>({name:h,formula:"0",order:0})));const w=l.a.databaseField===void 0||k(l.a.databaseField,!0);if(d&&k(d.a.containsDate,!1)&&c.numFmt==="General"&&oe(c,"m/d/yyyy"),l.a.formula!==void 0)c.formula=l.a.formula;else if(w&&e){const h=e.columns[o];h?.ids?(c.rawIds=f?h.ids.subarray(0,i).map(g=>f[g]):h.ids.subarray(0,i),c.shared=u.slice()):h?.kinds&&(dt(c,h.kinds.subarray(0,i),h.nums.subarray(0,i),i),h.dates&&c.numFmt==="General"&&oe(c,"m/d/yyyy"))}else w&&(c.shared=u.slice(),c.rawIds=new Int32Array(0));w&&o++,a.fields.push(c)}),n.forEach((l,r)=>{const c=S(l,"fieldGroup");if(!c)return;const d=a.fields[r],u=c.a.base!==void 0?Number(c.a.base):r;c.a.par!==void 0&&(d.par=Number(c.a.par)),u!==r&&(d.base=u);const f=S(c,"rangePr"),x=S(c,"discretePr"),w=Ae(c);if(f){const h=f.a.groupBy??"range",g=k(f.a.autoStart,!0),b=k(f.a.autoEnd,!0);if(h==="range"){const E=Number(f.a.startNum??0),T=Number(f.a.endNum??0),I=Number(f.a.groupInterval??1),v=w.length>1&&/^-?\d+--?\d+$/.test(String(w[1]))&&Number.isInteger(E)&&Number.isInteger(I)&&Number(String(w[1]).match(/^-?\d+-(-?\d+)$/)?.[1])===E+I-1;d.group={kind:"bins",start:E,end:T,interval:I,integer:v,autoStart:g,autoEnd:b,labels:w}}else d.group={kind:"date",part:h,start:Math.floor(W(f.a.startDate)),end:b?Math.floor(W(f.a.endDate))-1:W(f.a.endDate),autoStart:g,autoEnd:b,labels:w}}else if(x&&u!==r){const h=a.fields[u],g=L(x,"x").map(I=>Number(I.a.v??0)),b=w.map(()=>[]),E=S(n[u],"sharedItems")?.items??h.shared??[];g.forEach((I,v)=>{b[I]&&b[I].push(q(E[v]??null))});const T=[];w.forEach((I,v)=>{b[v].length===1&&b[v][0]===q(I)||T.push({name:String(I),keys:b[v]})}),d.group={kind:"discrete",groups:T}}}),Ct(a,t);for(const l of a.fields)if(l.formula!==null)try{l.calc=ft(l.formula,a)}catch{l.calc={fn:()=>{throw xe[4]},refs:[]}}return a}function Nt(t){const e=t?.items??[],s=t?.calculated;if(!s)return{items:e,ids:null,calculated:[]};const a=[],n=[],i=e.map((o,l)=>s.has(l)?(n.push(String(o??"")),0):a.push(o)-1);return{items:a,ids:i,calculated:n}}function Ct(t,e){L(S(e.root,"calculatedItems"),"calculatedItem").forEach((a,n)=>{const i=S(a,"pivotArea"),o=L(S(i,"references"),"reference")[0],l=t.fields[Number(a.a.field??o?.a.field)],r=Number(S(o,"x")?.a.v??-1),c=S(l?.xml?.node,"sharedItems")?.items?.[r];if(!l?.calcItems||c===void 0)return;const d=a.a.formula??"0";l.calcItems=l.calcItems.map(u=>u.name===String(c)?{...u,formula:ot(t,l,d.trim()),order:n}:u)})}function Q(t,e){const s=t.fields[e].xml?.node,a=s?S(s,"fieldGroup"):null,n=a?Ae(a):[];return n.length>0?n:(s?S(s,"sharedItems"):null)?.items??[]}function Et(t){const e=t.a.type??"",s=S(S(t,"autoFilter"),"filterColumn");if(e==="count"||e==="percent"||e==="sum"){const a=S(s,"top10");return a?{top:{count:Number(a.a.val??10),by:e==="count"?"items":e,bottom:a.a.top==="0"||a.a.top==="false",data:Number(t.a.iMeasureFld??0)}}:null}if(Ge(e))return{dateFilter:Ue(t)};if(e.startsWith("caption"))return{labelFilter:{op:e,value:t.a.stringValue1??"",value2:t.a.stringValue2??""}};if(e.startsWith("value")){const a=L(S(s,"customFilters"),"customFilter");return a.length===0?null:{valueFilter:{op:e,data:Number(t.a.iMeasureFld??0),value:Number(a[0].a.val),value2:a[1]?Number(a[1].a.val):void 0}}}return null}function kt(t){for(const e of L(S(t,"extLst"),"ext")){const s=S(e,"x14:pivotTableDefinition");if(s)return s}return null}function At(t,e){const s=t?S(t,"extLst"):null,a=[];let n=!1;for(const i of s?.c??[]){const o=S(i,"x14:pivotTableDefinition");if(!o){a.push(i);continue}n=!0;const l={...o.a};delete l.hideValuesRow,e&&(l.hideValuesRow="1"),a.push(m("ext",i.a,i.c.map(r=>r===o?m(o.n,l,o.c):r)))}return!n&&e&&a.push(m("ext",{uri:gt,"xmlns:x14":re},[m("x14:pivotTableDefinition",{hideValuesRow:"1"})])),a.length>0?m("extLst",{},a):null}const Oe=t=>t.filters.length>0?t.filters.length+1:0;function Ot(t,e,{numFmtOf:s,sheet:a}={}){const n={name:t.a.name??"PivotTable1",fieldOptions:{},rows:L(S(t,"rowFields"),"field").map(h=>Number(h.a.x)),cols:L(S(t,"colFields"),"field").map(h=>Number(h.a.x)),filters:[],values:[],grandRow:k(t.a.rowGrandTotals,!0),grandCol:k(t.a.colGrandTotals,!0),rowCaption:t.a.rowHeaderCaption??null,colCaption:t.a.colHeaderCaption??null,dataCaption:t.a.dataCaption??"Values",grandCaption:t.a.grandTotalCaption??null,emptyText:k(t.a.showMissing,!0)?t.a.missingCaption??"":"",showMissing:k(t.a.showMissing,!0),errorText:k(t.a.showError,!1)?t.a.errorCaption??"":null,showExpandButtons:k(t.a.showDrill,!0),showFieldHeaders:k(t.a.showHeaders,!0),hideValuesRow:k(kt(t)?.a.hideValuesRow,!1)},i=L(S(t,"pivotFields"),"pivotField"),o={root:t,fields:i,itemAttrs:[],pageFields:new Map,rawFilters:[]},l=[],r=(h,g)=>{const b=L(S(i[h],"items"),"item")[g];return b?q(Q(e,h)[Number(b.a.x??0)]??null):void 0},c=(h,g)=>{const b=[];for(const E of g){if(E===V)continue;const T=h.find(v=>Number(v.a.field)===E),I=T&&r(E,Number(S(T,"x")?.a.v??0));if(I===void 0)break;b.push(I)}return b};i.forEach((h,g)=>{const b={},E=Q(e,g),T=L(S(h,"items"),"item"),I=[],v=[],F=[],P={},p=new Map;for(const C of T){if(C.a.t!==void 0&&C.a.t!=="data")continue;const D=Number(C.a.x??0),N=q(E[D]??null);F.push(N),p.set(N,C.a),k(C.a.h,!1)&&I.push(N),C.a.sd!==void 0&&!k(C.a.sd,!0)&&v.push(N),C.a.n!==void 0&&(P[N]=C.a.n)}o.itemAttrs[g]=p,I.length&&(b.hidden=I),v.length&&(b.collapsedItems=v),Object.keys(P).length&&(b.itemCaptions=P),h.a.name!==void 0&&(b.caption=h.a.name);const y=h.a.sortType??"manual";if(y==="ascending"||y==="descending"){b.sort={order:y==="ascending"?"asc":"desc"};const C=S(S(h,"autoSortScope"),"pivotArea"),D=L(S(C,"references"),"reference"),N=D.find($=>Number($.a.field)===Se);if(N){b.sort.data=Number(S(N,"x")?.a.v??0);const $=c(D,n.rows.includes(g)?n.cols:n.rows);$.length>0&&(b.sort.path=$)}}else F.length>0&&h.a.axis&&(b.sort={order:"manual",keys:F});const O=Object.entries(ie).filter(([,C])=>k(h.a[C],!1)).map(([C])=>C);O.length>0?b.subtotals=O:k(h.a.defaultSubtotal,!0)||(b.subtotals="none"),h.a.subtotalTop!==void 0&&(b.subtotalTop=k(h.a.subtotalTop,!0)),k(h.a.includeNewItemsInFilter,!1)&&(b.includeNewItems=!0),k(h.a.insertBlankRow,!1)&&(b.blankLine=!0),h.a.axis&&k(h.a.showAll,!0)&&(b.showAll=!0),k(h.a.insertPageBreak,!1)&&(b.pageBreak=!0);for(const C of L(S(h,"extLst"),"ext"))k(S(C,"x14:pivotField")?.a.fillDownLabels,!1)&&(b.repeatLabels=!0);if(h.a.axis==="axisRow"||h.a.axis==="axisCol"){const C=k(h.a.outline,!0)?k(h.a.compact,!0)?"compact":"outline":"tabular";l.push([g,C])}Object.keys(b).length>0&&(n.fieldOptions[g]=b)});const d=new Set(l.map(([,h])=>h));k(t.a.compact,!0)?n.layout="compact":d.size===1&&!d.has("compact")&&!n.rows.includes(V)?[n.layout]=d:n.layout=k(t.a.outline,!1)?"outline":"tabular";for(const[h,g]of l)g!==n.layout&&(n.fieldOptions[h]??={},n.fieldOptions[h].layout=g);for(const h of L(S(t,"pageFields"),"pageField")){const g=Number(h.a.fld);if(n.filters.push(g),o.pageFields.set(g,h.a),h.a.item!==void 0){const b=L(S(i[g],"items"),"item"),E=b[Number(h.a.item)],T=Q(e,g);if(E){const I=q(T[Number(E.a.x??0)]??null),v=[];for(const F of b){if(F.a.t!==void 0&&F.a.t!=="data")continue;const P=q(T[Number(F.a.x??0)]??null);P!==I&&v.push(P)}n.fieldOptions[g]??={},n.fieldOptions[g].hidden=v}}}for(const h of L(S(t,"dataFields"),"dataField")){const g=Number(h.a.fld),b={field:g,name:h.a.name??ht(h.a.subtotal??"sum",e.fields[g].name),agg:h.a.subtotal??"sum",xml:h};let E=h.a.showDataAs??"normal";const T=S(S(h,"extLst"),"ext"),I=T?S(T,"x14:dataField"):null;if(I?.a.pivotShowAs&&(E=I.a.pivotShowAs),E!=="normal"&&(b.showAs={type:E},h.a.baseField!==void 0&&(b.showAs.baseField=Number(h.a.baseField)),h.a.baseItem!==void 0)){const v=Number(h.a.baseItem);if(v===be)b.showAs.baseItem="prev";else if(v===ye)b.showAs.baseItem="next";else{const F=b.showAs.baseField,P=L(S(i[F],"items"),"item"),p=Q(e,F),y=P[v];b.showAs.baseItem=y?q(p[Number(y.a.x??0)]??null):"prev"}}if(h.a.numFmtId!==void 0){const v=Number(h.a.numFmtId),F=se[v]??s?.(v);F&&(b.numFmt=F)}n.values.push(b)}for(const h of L(S(t,"filters"),"filter")){const g=Et(h),b=Number(h.a.fld);if(g===null){o.rawFilters.push(h);continue}n.fieldOptions[b]??={},Object.assign(n.fieldOptions[b],g)}k(t.a.mergeItem,!1)&&(n.mergeLabels=!0);const u=S(t,"pivotTableStyleInfo");u&&(n.style={name:u.a.name??"PivotStyleLight16",rowHeaders:k(u.a.showRowHeaders,!0),colHeaders:k(u.a.showColHeaders,!0),rowStripes:k(u.a.showRowStripes,!1),colStripes:k(u.a.showColStripes,!1),lastColumn:k(u.a.showLastColumn,!0)});const f=new ut(e,n);f.xml=o,f.dirty=!1;const x=S(t,"location"),w=x?te(x.a.ref??""):null;if(w){const h=Oe(n);f.anchor={sheet:a??null,row:Math.max(0,w.r0-h),col:w.c0},f.renderedRange={r0:f.anchor.row,c0:w.c0,r1:w.r1,c1:w.c1}}return f}async function le(t,e){const s=et(e);if(!t.has(s))return[];const a=Ne(await t.bytes(s));return L(a,"Relationship").map(n=>{const i=n.a.TargetMode==="External";return{id:n.a.Id,type:n.a.Type,external:i,target:i?n.a.Target??"":tt(e,n.a.Target??"")}})}async function xn(t,{sheets:e,book:s,tables:a=[],numFmtOf:n,readRecords:i=!0}){const o=new Map,l=[];for(const{part:r,sheet:c}of e)if(r)for(const d of await le(t,r)){if(d.type!==H.table||!t.has(d.target))continue;const u=Ne(await t.bytes(d.target)),f=await le(t,d.target),x=f.find(g=>g.type===H.definition);if(!x||!t.has(x.target))continue;let w=o.get(x.target);if(w===void 0){const g=await vt(await t.stream(x.target)),b=await le(t,x.target),E=b.find(I=>I.type===H.records);let T=null;i&&E&&t.has(E.target)&&(T=await Tt(await t.stream(E.target),g)),w=It(g,T,{numFmtOf:n}),w.refreshOnLoad=["1","true"].includes(g.a.refreshOnLoad),w.part=x.target,w.recordsPart=E?.target??null,w.links=b.filter(I=>I.external),w.id=u.a.cacheId!==void 0?Number(u.a.cacheId):0,Lt(w,g,s,a),o.set(x.target,w)}const h=Ot(u,w,{numFmtOf:n,sheet:c});h.part=d.target,h.links=f.filter(g=>g!==x),l.push(h)}for(const r of o.values())Rt(r,l.filter(c=>c.cache===r));return{caches:[...o.values()],pivots:l}}function Rt(t,e){for(const s of t.fields){if(s.base<0)continue;let a=t.fields[s.base];for(let n=t.fields.length;a&&a!==s&&n>0;n--)a=t.fields[a.par];a!==s&&!e.some(n=>n.isUsed(s.index))&&(s.removed=!0)}}function Dt(t,e,s){const a=()=>{const i=t.engine?.names,o=s===void 0?-1:t.sheets.findIndex(u=>u.name===s),l=(i?.get(`${o}!${e.toUpperCase()}`)??i?.get(e.toUpperCase()))?.text??"",r=/^=?(?:'((?:[^']|'')+)'|([^'!]+))!(\$?[A-Za-z]+\$?\d+:\$?[A-Za-z]+\$?\d+)$/.exec(l.trim());if(!r)return null;const c=t.sheets.find(u=>u.name.toLowerCase()===(r[1]?.replace(/''/g,"'")??r[2]).toLowerCase()),d=te(r[3].replace(/\$/g,""));return c&&d?{sheet:c,range:d}:null},n=a();return n&&{type:"range",book:t,...n,name:{name:e,sheet:s},locate:a}}function Lt(t,e,s,a){if(!s)return;const n=S(S(e.root,"cacheSource"),"worksheetSource");if(!n||n.a["r:id"]!==void 0)return;if(n.a.name!==void 0){const l=a.find(r=>r.name?.toLowerCase()===n.a.name.toLowerCase());l?t.source={type:"table",book:s,table:l}:t.source=Dt(s,n.a.name,n.a.sheet);return}const i=te(n.a.ref??""),o=s.sheets.find(l=>l.name===n.a.sheet);i&&o&&(t.source={type:"range",book:s,sheet:o,range:i})}const K=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ `,ce=new TextEncoder;function Re(t){for(const[e,s]of Object.entries(se))if(s===t)return Number(e);return null}function ee(t,e){if(t==null)return"<m/>";switch(typeof t){case"number":return e?`<d v="${X(t)}"/>`:`<n v="${t}"/>`;case"string":return`<s v="${ge(t)}"/>`;case"boolean":return`<b v="${t?1:0}"/>`;default:return`<e v="${ae(t.code)}"/>`}}const Pt=2958466;function ue(t,e){const{hasNum:s,hasInt:a,hasText:n,hasBlank:i,hasOther:o,min:l,max:r,longText:c}=e,d=t.isDate&&s&&!n&&!o&&l>=0&&r<Pt,u={};return!n&&!i&&!o&&(u.containsSemiMixedTypes="0"),d&&!i&&(u.containsNonDate="0"),d&&(u.containsDate="1"),n||(u.containsString="0"),i&&(u.containsBlank="1"),(s?1:0)+(n?1:0)+(o?1:0)>1&&(u.containsMixedTypes="1"),s&&!d&&(u.containsNumber="1",a&&(u.containsInteger="1"),u.minValue=String(l),u.maxValue=String(r)),d&&(u.minDate=X(l),u.maxDate=X(Math.floor(r)+1)),c&&(u.longText="1"),{attrs:u,date:d}}function $t(t){const e={hasNum:!1,hasInt:!0,hasText:!1,hasBlank:!1,hasOther:!1,min:1/0,max:-1/0,longText:!1};for(const s of t)typeof s=="number"?(e.hasNum=!0,Number.isInteger(s)||(e.hasInt=!1),s<e.min&&(e.min=s),s>e.max&&(e.max=s)):typeof s=="string"?(e.hasText=!0,s.length>255&&(e.longText=!0)):s==null?e.hasBlank=!0:e.hasOther=!0;return e}function De(t){const e={hasNum:t.length>0,hasInt:!0,hasText:!1,hasBlank:!1,hasOther:!1,min:1/0,max:-1/0,longText:!1};for(let s=0;s<t.length;s++){const a=t[s];a<e.min&&(e.min=a),a>e.max&&(e.max=a),e.hasInt&&Math.floor(a)!==a&&(e.hasInt=!1)}return e}function Le(t){return t.calcItems||(t.ensureColumn(),t.rawIds!==null)?!0:!(t.nums!==null&&t.kinds===null)}function Mt(t,e){const s=e.group;if(s===null)return e.par>=0?m("fieldGroup",{par:String(e.par)}):null;e.ensure();const a={};e.par>=0&&(a.par=String(e.par)),a.base=String(e.base>=0?e.base:e.index);const n=[],i=e.items.map(l=>ee(l,!1)).join("");if(s.kind==="date"){const l={groupBy:s.part,startDate:X(s.start),endDate:X(s.autoEnd?s.end+1:s.end)};s.autoStart||(l.autoStart="0"),s.autoEnd||(l.autoEnd="0"),n.push(m("rangePr",l))}else if(s.kind==="bins"){const l={startNum:String(s.start),endNum:String(s.end),groupInterval:String(s.interval)};s.autoStart||(l.autoStart="0"),s.autoEnd||(l.autoEnd="0"),n.push(m("rangePr",l))}else{const l=e.groupMap,r=m("discretePr",{count:String(l.length)});for(let c=0;c<l.length;c++)r.c.push(m("x",{v:String(l[c])}));n.push(r)}const o=m("groupItems",{count:String(e.items.length)});return o.c.push(i),n.push(o),m("fieldGroup",a,n)}const Bt=new Set(["cacheHierarchies","kpis","tupleCache"]),Pe=t=>ee(String(t),!1).replace(/\/>$/,' f="1"/>');function _t(t){return t.containsSemiMixedTypes!=="0"?{}:{containsSemiMixedTypes:void 0,containsString:void 0,containsMixedTypes:"1"}}function Ht(t){const e=at(t);return e.length===0?null:m("calculatedItems",{count:String(e.length)},e.map(({field:s,item:a})=>{s.ensure();const n=s.items.length-s.calcItems.length+s.calcItems.indexOf(a);return m("calculatedItem",{formula:st(t,s,a.formula)},[m("pivotArea",{cacheIndex:"1",outline:"0",fieldPosition:"0"},[m("references",{count:"1"},[m("reference",{field:String(s.index),count:"1"},[m("x",{v:String(n)})])])])])}))}function qt(t,e,s){const a=e.xml?.node??null,n={...a?.a??{}};if(n.name=e.name,n.numFmtId===void 0){const l=e.numFmt!=="General"?Re(e.numFmt)??s.numFmtId?.(e.numFmt)??(e.isDate?14:0):0;n.numFmtId=String(l)}const i=[];if(e.isCalculated)n.formula=e.formula,n.databaseField="0",delete n.uniqueList;else if(e.base>=0)n.databaseField="0";else if(t.recordCount===0&&a&&S(a,"sharedItems")){const l=S(a,"sharedItems"),r=m("sharedItems",{...l.a}),c=k(l.a.containsDate,!1);l.items.length>0&&r.c.push(l.items.map((d,u)=>l.calculated?.has(u)?Pe(d):ee(d,c&&typeof d=="number")).join("")),i.push(r)}else if(Le(e)){e.ensureRaw();const{attrs:l,date:r}=ue(e,$t(e.shared)),c=e.calcItems??[],d=m("sharedItems",{...l,...c.length?_t(l):{},count:String(e.shared.length+c.length)});d.c.push(e.shared.map(u=>ee(u,r&&typeof u=="number")).join("")+c.map(u=>Pe(u.name)).join("")),i.push(d)}else{const{attrs:l}=ue(e,De(e.nums));i.push(m("sharedItems",l))}const o=Mt(t,e);if(o&&i.push(o),a)for(const l of a.c)l.n!=="sharedItems"&&l.n!=="fieldGroup"&&i.push(l);return m("cacheField",n,i)}function Vt(t,{recordsRel:e=null,numFmtId:s,refreshOnLoad:a=!0,sourceSheetName:n}={}){const i=t.xml?.root??null,o={...i?.a??{}};o.xmlns??=z,o["xmlns:r"]??=G,e?o["r:id"]=e:delete o["r:id"],a?o.refreshOnLoad="1":t.source!==null&&delete o.refreshOnLoad,o.refreshedBy??="8sheets",o.refreshedDate=String(Xt()),o.createdVersion??="6",o.refreshedVersion??="6",o.minRefreshableVersion??="3",o.recordCount=String(t.recordCount),e?delete o.saveData:o.saveData="0";const l=[],r=i?S(i,"cacheSource"):null;l.push(jt(t,r,n));const c=m("cacheFields",{count:"0"}),d=t.fields;for(const f of d)c.c.push(qt(t,f,{numFmtId:s}));c.a.count=String(d.length),l.push(c);const u=Ht(t);if(i)for(const f of i.c)f.n==="cacheSource"||f.n==="cacheFields"||f.n==="calculatedItems"||(u&&!l.includes(u)&&!Bt.has(f.n)&&l.push(u),l.push(f));return u&&!l.includes(u)&&l.push(u),K+J(m("pivotCacheDefinition",o,l)).join("")}function Xt(){return Math.round((Date.now()/864e5+25569)*1e5)/1e5}function jt(t,e,s){const a=t.source;if(a===null)return e??m("cacheSource",{type:"worksheet"},[m("worksheetSource",{ref:"A1",sheet:"Sheet1"})]);const n={};if(a.type==="table")n.name=a.table.name;else if(a.name)Object.assign(n,a.name);else{const c=a.range,d=s??(typeof a.sheet=="string"?a.sheet:a.sheet.name);a.deleted||(n.ref=ne({r0:c.r0,c0:c.c0,r1:c.r1,c1:Math.min(c.c1,We-1)})),n.sheet=d}const i=e?{...e.a}:{type:"worksheet"},o=e?e.c.filter(c=>c.n!=="worksheetSource"):[],r={...(e?S(e,"worksheetSource"):null)?.a};for(const c of["ref","sheet","name","r:id"])delete r[c];return Object.assign(r,n),m("cacheSource",i,[m("worksheetSource",r),...o])}const Gt=4096;async function $e(t,e){const s=t.recordCount,a=[];for(const i of t.fields)i.isVirtual||(Le(i)?(i.ensureRaw(),a.push(Ut(i.rawIds))):a.push(Wt(i.nums,ue(i,De(i.nums)).date)));await e(ce.encode(`${K}<pivotCacheRecords xmlns="${z}" xmlns:r="${G}" count="${s}">`));const n=[];for(let i=0;i<s;i++){n.push("<r>");for(let o=0;o<a.length;o++)n.push(a[o](i));n.push("</r>"),(i+1)%Gt===0&&(await e(ce.encode(n.join(""))),n.length=0)}n.push("</pivotCacheRecords>"),await e(ce.encode(n.join("")))}function Ut(t){return e=>`<x v="${t[e]}"/>`}function Wt(t,e){return e?s=>`<d v="${X(t[s])}"/>`:s=>`<n v="${t[s]}"/>`}const bn=t=>Kt(e=>$e(t,e));async function Kt(t){const e="application/xml";let s=new Blob([],{type:e}),a=[],n=0;return await t(i=>{a.push(i),n+=i.length,n>=1<<24&&(s=new Blob([s,...a],{type:e}),a=[],n=0)}),new Blob([s,...a],{type:e})}const Me=["location","pivotFields","rowFields","rowItems","colFields","colItems","pageFields","dataFields","formats","conditionalFormats","chartFormats","pivotHierarchies","pivotTableStyleInfo","filters","rowHierarchiesUsage","colHierarchiesUsage","extLst"];function Yt(t,e){const s=t.cache.fields[e].ensure(),a=Array.from(s.items.keys()),i=t.spec.fieldOptions[e]?.sort,o=s.rank(rt(i));if(i?.order==="manual"){const r=new Map((i.keys??[]).map((u,f)=>[u,f])),c=r.size,d=u=>r.get(q(s.items[u]))??c+o[u];a.sort((u,f)=>d(u)-d(f))}else i?.order==="desc"&&(i.data===void 0||i.data===null)?a.sort((r,c)=>o[c]-o[r]):a.sort((r,c)=>o[r]-o[c]);const l=new Int32Array(a.length);return a.forEach((r,c)=>{l[r]=c}),{order:a,position:l}}function Zt(t){return t.group!==null||t.base>=0}function zt(t,e){return t.spec.fieldOptions[e]?.layout??t.spec.layout}const Jt=["axis","dataField","compact","outline","subtotalTop","sortType","defaultSubtotal","insertBlankRow","name","showDropDowns","dragToRow","dragToCol","dragToPage",...Object.values(ie)];function Qt(t,e,s){const{spec:a,cache:n}=t,i=n.fields[e],o=a.fieldOptions[e]??{},l=t.xml?.fields?.[e]??null,r={...l?.a??{}};for(const v of Jt)delete r[v];o.caption!==void 0&&(r.name=o.caption);const c=a.rows.includes(e),d=a.cols.includes(e),u=a.filters.includes(e),f=a.values.some(v=>v.field===e);c?r.axis="axisRow":d?r.axis="axisCol":u&&(r.axis="axisPage"),f&&(r.dataField="1");const x=zt(t,e);x!=="compact"&&(r.compact="0"),x==="tabular"&&(r.outline="0"),i.isCalculated&&(r.dragToRow="0",r.dragToCol="0",r.dragToPage="0"),r.showAll=o.showAll?"1":"0",o.pageBreak?r.insertPageBreak="1":delete r.insertPageBreak,(o.subtotalTop??a.subtotalTop)===!1&&(c||d)&&(r.subtotalTop="0"),o.blankLine&&(r.insertBlankRow="1"),o.sort?.order==="asc"?r.sortType="ascending":o.sort?.order==="desc"&&(r.sortType="descending");const w=o.subtotals??"auto",h=c||d||u,g=(o.hidden?.length??0)>0,b=h||Zt(i)||g||!!(o.range||o.dateFilter);if((i.isCalculated||w==="none"||Array.isArray(w)||i.base>=0&&!h)&&(r.defaultSubtotal="0"),Array.isArray(w))for(const v of w)r[ie[v]]="1";const E=[];if(b&&!i.isCalculated){const{order:v}=s(e),F=m("items",{}),P=new Set(o.hidden??[]),p=new Set(o.collapsedItems??[]),y=t.xml?.itemAttrs?.[e]??null,O=o.itemCaptions??null;for(const C of v){const D=i.keyOf(C),N={...y?.get(D)??{}};delete N.h,delete N.sd,delete N.n,delete N.f,i.calcItems&&C>=i.items.length-i.calcItems.length&&(N.f="1"),N.x=String(C),P.has(D)&&(N.h="1"),p.has(D)&&(N.sd="0"),O&&O[D]!==void 0&&(N.n=O[D]),F.c.push(m("item",N))}if((h||g||o.range||o.dateFilter)&&r.defaultSubtotal===void 0&&F.c.push(m("item",{t:"default"})),Array.isArray(w))for(const C of w)F.c.push(m("item",{t:ve[C]}));F.a.count=String(F.c.length),E.push(F)}if(o.sort?.data!==void 0&&o.sort?.data!==null&&(o.sort.order==="asc"||o.sort.order==="desc")){const v=(p,y)=>m("reference",{field:String(p),count:"1",selected:"0"},[m("x",{v:String(y)})]),F=[v(Se,o.sort.data)],P=(c?a.cols:a.rows).filter(p=>p!==V);(o.sort.path??[]).forEach((p,y)=>{const O=P[y]===void 0?void 0:n.fields[P[y]].keyIndex.get(p);O!==void 0&&F.push(v(P[y],s(P[y]).position[O]))}),E.push(m("autoSortScope",{},[m("pivotArea",{dataOnly:"0",outline:"0",fieldPosition:"0"},[m("references",{count:String(F.length)},F)])]))}if(l)for(const v of l.c)v.n!=="items"&&v.n!=="autoSortScope"&&v.n!=="extLst"&&E.push(v);const T=o.repeatLabels===!0||a.repeatLabels===!0&&c&&x!=="compact",I=en(l,T);return I&&E.push(I),m("pivotField",r,E)}function en(t,e){const s=[];let a=!1;for(const n of L(t?S(t,"extLst"):null,"ext")){const i=S(n,"x14:pivotField");if(!i){s.push(n);continue}a=!0;const o={...i.a};delete o.fillDownLabels,e&&(o.fillDownLabels="1"),s.push(m("ext",n.a,n.c.map(l=>l===i?m(i.n,o,i.c):l)))}return!a&&e&&s.push(m("ext",{uri:wt,"xmlns:x14":re},[m("x14:pivotField",{fillDownLabels:"1"})])),s.length>0?m("extLst",{},s):null}const tn=1048832;function Be(t,e,s,a){const n=s.lines,i=m(t,{}),{slots:o}=s;let l=[];for(let r=0;r<n.node.length;r++){const c=n.type[r],d=n.level[r],u={},f=[];if(o.length===0){i.c.push(m("i",{}));continue}if(c===Z.GRAND){u.t="grand";const g=n.data[r];g>0&&(u.i=String(g));const b=m("i",u,[m("x",g>0?{v:String(g)}:{})]);i.c.push(b),l=[];continue}c===Z.BLANK?u.t="blank":c===Z.SUBTOTAL&&(u.t=n.func[r]?ve[n.func[r]]:"default");let x=0;for(let g=0;g<=d;g++)if(o[g]===V)f.push(n.data[r]>=0?n.data[r]:0);else{x++;const b=s.ancestorAt(n.node[r],x);f.push(b<0?tn:a(o[g]).position[s.item[b]])}n.data[r]>0&&(u.i=String(n.data[r]));let w=0;if(c===Z.ITEM)for(;w<f.length-1&&w<l.length&&l[w]===f[w];)w++;w>0&&(u.r=String(w));const h=m("i",u);for(let g=w;g<f.length;g++)h.c.push(m("x",f[g]===0?{}:{v:String(f[g])}));i.c.push(h),l=f}return i.c.length===0&&i.c.push(m("i",{})),i.a.count=String(i.c.length),i}function nn(t,e){const{spec:s}=t,a=[];let n=1;const i=(l,r,c,d)=>m("filter",{fld:String(l),type:r,evalOrder:"-1",id:String(n++),...c},[m("autoFilter",{ref:"A1"},[m("filterColumn",{colId:"0"},[d])])]),o=(l,r)=>m("customFilters",r?{and:"1"}:{},l.map(c=>m("customFilter",c)));for(const l of e){const r=s.fieldOptions[l];if(r){if(r.labelFilter){const c=r.labelFilter,d=String(c.value??""),u=String(c.value2??""),f={stringValue1:d};(c.op==="captionBetween"||c.op==="captionNotBetween")&&(f.stringValue2=u);const x={captionEqual:()=>o([{val:d}]),captionNotEqual:()=>o([{operator:"notEqual",val:d}]),captionBeginsWith:()=>o([{val:`${d}*`}]),captionNotBeginsWith:()=>o([{operator:"notEqual",val:`${d}*`}]),captionEndsWith:()=>o([{val:`*${d}`}]),captionNotEndsWith:()=>o([{operator:"notEqual",val:`*${d}`}]),captionContains:()=>o([{val:`*${d}*`}]),captionNotContains:()=>o([{operator:"notEqual",val:`*${d}*`}]),captionGreaterThan:()=>o([{operator:"greaterThan",val:d}]),captionGreaterThanOrEqual:()=>o([{operator:"greaterThanOrEqual",val:d}]),captionLessThan:()=>o([{operator:"lessThan",val:d}]),captionLessThanOrEqual:()=>o([{operator:"lessThanOrEqual",val:d}]),captionBetween:()=>o([{operator:"greaterThanOrEqual",val:d},{operator:"lessThanOrEqual",val:u}],!0),captionNotBetween:()=>o([{operator:"lessThan",val:d},{operator:"greaterThan",val:u}])}[c.op];x&&a.push(i(l,c.op,f,x()))}if(r.valueFilter){const c=r.valueFilter,d=String(c.value),u=String(c.value2??""),f={valueEqual:[[{val:d}]],valueNotEqual:[[{operator:"notEqual",val:d}]],valueGreaterThan:[[{operator:"greaterThan",val:d}]],valueGreaterThanOrEqual:[[{operator:"greaterThanOrEqual",val:d}]],valueLessThan:[[{operator:"lessThan",val:d}]],valueLessThanOrEqual:[[{operator:"lessThanOrEqual",val:d}]],valueBetween:[[{operator:"greaterThanOrEqual",val:d},{operator:"lessThanOrEqual",val:u}],!0],valueNotBetween:[[{operator:"lessThan",val:d},{operator:"greaterThan",val:u}]]}[c.op];f&&a.push(i(l,c.op,{iMeasureFld:String(c.data??0)},o(f[0],f[1]===!0)))}if(a.push(...je(r,l,m,()=>n++)),r.top){const c=r.top,d={val:String(c.count??10),filterVal:String(c.count??10)};c.by==="percent"&&(d.percent="1"),c.bottom&&(d.top="0");const u=c.by==="percent"?"percent":c.by==="sum"?"sum":"count";a.push(i(l,u,{iMeasureFld:String(c.data??0)},m("top10",d)))}}}return a}function sn(t,e,s,a){const n=e.xml??null,i={...n?.a??{}};i.name=e.name,i.fld=String(e.field),e.agg&&e.agg!=="sum"?i.subtotal=e.agg:delete i.subtotal,delete i.showDataAs;const o=e.showAs?.type??"normal",l=n?n.c.filter(h=>h.n!=="extLst"):[];let r=null;xt.has(o)?r=o:o!=="normal"&&(i.showDataAs=o);const c=e.showAs?.baseField??0;i.baseField=String(c>=0?c:0);let d=0;const u=e.showAs?.baseItem;if(u==="prev")d=be;else if(u==="next")d=ye;else if(u!==void 0&&e.showAs?.baseField>=0){const h=t.cache.fields[e.showAs.baseField].ensure(),g=h.keyIndex.get(u);g!==void 0&&(d=s(h.index).position[g])}i.baseItem=String(d);const f=e.numFmt??(o!=="normal"&&!o.startsWith("rank")&&o!=="difference"&&o!=="runTotal"?o==="index"?"0.00":"0.00%":null);if(f){const h=Re(f)??a.numFmtId?.(f);h!=null&&(i.numFmtId=String(h))}else delete i.numFmtId;const x=[],w=n?S(n,"extLst"):null;if(w)for(const h of w.c)if(S(h,"x14:dataField")){const g={...S(h,"x14:dataField").a};delete g.pivotShowAs,r&&(g.pivotShowAs=r),x.push(m("ext",h.a,[m("x14:dataField",g)])),r=null}else x.push(h);return r&&x.push(m("ext",{uri:mt,"xmlns:x14":re},[m("x14:dataField",{pivotShowAs:r})])),x.length&&l.push(m("extLst",{},x)),m("dataField",i,l)}function an(t,{cacheId:e,numFmtId:s}={}){const a=t.result??t.update(),{spec:n,cache:i}=t,{layout:o,rows:l,cols:r}=a,c=new Map,d=A=>{let R=c.get(A);return R===void 0&&(R=Yt(t,A),c.set(A,R)),R},u=t.xml?.root??null,f={...u?.a??{}};f.xmlns??=z,f.name=n.name,f.cacheId=String(e??i.id??1),f.applyNumberFormats??="0",f.applyBorderFormats??="0",f.applyFontFormats??="0",f.applyPatternFormats??="0",f.applyAlignmentFormats??="0",f.applyWidthHeightFormats??="1",f.dataCaption=n.dataCaption,f.updatedVersion??="6",f.minRefreshableVersion??="3",f.useAutoFormatting??="1",f.itemPrintTitles??="1",f.createdVersion??="6",f.indent??="0",n.mergeLabels?f.mergeItem="1":delete f.mergeItem,t.fileAttrs&&Object.assign(f,t.fileAttrs);const x=(A,R,M)=>{R===M?delete f[A]:f[A]=R?"1":"0"};x("compact",n.layout==="compact",!0),x("compactData",n.layout==="compact",!0),x("outline",n.layout!=="tabular",!1),x("outlineData",n.layout!=="tabular",!1),x("rowGrandTotals",n.grandRow,!0),x("colGrandTotals",n.grandCol,!0),x("showDrill",n.showExpandButtons!==!1,!0),x("showHeaders",n.showFieldHeaders!==!1,!0),n.rowCaption!=null?f.rowHeaderCaption=n.rowCaption:delete f.rowHeaderCaption,n.colCaption!=null?f.colHeaderCaption=n.colCaption:delete f.colHeaderCaption,n.grandCaption!=null?f.grandTotalCaption=n.grandCaption:delete f.grandTotalCaption,n.emptyText!==""&&n.showMissing!==!1?f.missingCaption=n.emptyText:delete f.missingCaption,n.showMissing===!1?f.showMissing="0":delete f.showMissing,n.errorText!==null?(f.showError="1",f.errorCaption=n.errorText):(delete f.showError,delete f.errorCaption),l.slots.includes(V)?(f.dataOnRows="1",f.dataPosition=String(l.slots.indexOf(V))):(delete f.dataOnRows,delete f.dataPosition);const w=Object.keys(n.fieldOptions).map(Number),h=w.some(A=>{const R=n.fieldOptions[A];return(R.labelFilter?1:0)+(R.valueFilter?1:0)+(R.top?1:0)>1});f.multipleFieldFilters=h?"1":"0";const g=t.anchor??{row:0,col:0},b=g.row+o.pageRows,E={ref:ne({r0:b,c0:g.col,r1:g.row+o.rows-1,c1:g.col+Math.max(o.bodyCols,1)-1}),firstHeaderRow:String(o.firstHeaderRow),firstDataRow:String(o.firstDataRow),firstDataCol:String(o.firstDataCol)};n.filters.length>0&&(E.rowPageCount=String(n.filters.length),E.colPageCount="1");const T=new Map;T.set("location",m("location",E));const I=m("pivotFields",{count:String(i.fields.length)});for(let A=0;A<i.fields.length;A++)I.c.push(Qt(t,A,d));T.set("pivotFields",I);const v=(A,R)=>m(A,{count:String(R.length)},R.map(M=>m("field",{x:String(M)})));if(l.slots.length>0&&T.set("rowFields",v("rowFields",l.slots)),T.set("rowItems",Be("rowItems",a,l,d)),r.slots.length>0&&T.set("colFields",v("colFields",r.slots)),T.set("colItems",Be("colItems",a,r,d)),n.filters.length>0){const A=m("pageFields",{count:String(n.filters.length)});for(const R of n.filters){const B={...t.xml?.pageFields?.get(R)??{},fld:String(R)};delete B.item,B.hier??="-1";const Y=i.fields[R].ensure(),de=n.fieldOptions[R]?.hidden??[];if(de.length===Y.items.length-1){const He=new Set(de),fe=d(R).order.findIndex(qe=>!He.has(Y.keyOf(qe)));fe>=0&&(B.item=String(fe))}A.c.push(m("pageField",B))}T.set("pageFields",A)}n.values.length>0&&T.set("dataFields",m("dataFields",{count:String(n.values.length)},n.values.map(A=>sn(t,A,d,{numFmtId:s}))));const F=n.style,P=u?S(u,"pivotTableStyleInfo"):null;T.set("pivotTableStyleInfo",m("pivotTableStyleInfo",{...P?.a??{},name:F.name,showRowHeaders:F.rowHeaders?"1":"0",showColHeaders:F.colHeaders?"1":"0",showRowStripes:F.rowStripes?"1":"0",showColStripes:F.colStripes?"1":"0",showLastColumn:F.lastColumn===!1?"0":"1"}));const p=nn(t,w),y=t.xml?.rawFilters??[],O=[...p,...y];O.length>0&&T.set("filters",m("filters",{count:String(O.length)},O));const C=Ve(t,m);C&&T.set("conditionalFormats",C);const D=Xe(t,m);D&&T.set("chartFormats",D);const N=At(u,n.hideValuesRow);N&&T.set("extLst",N);const $=[];for(const A of Me)if(T.has(A))$.push(T.get(A));else if(u&&!on.has(A)){const R=S(u,A);R&&$.push(R)}if(u)for(const A of u.c)Me.includes(A.n)||$.splice($.length-($[$.length-1]?.n==="extLst"?1:0),0,A);return K+J(m("pivotTableDefinition",f,$)).join("")}function _e(t,e=t.xml.root.a.cacheId){const{root:s}=t.xml,a=t.renderedRange,n=i=>i.n==="location"&&a?m("location",{...i.a,ref:ne({...a,r0:a.r0+Oe(t.spec)})},i.c):i;return K+J(m(s.n,{...s.a,name:t.spec.name,cacheId:String(e)},s.c.map(n))).join("")}const on=new Set(["extLst","location","pivotFields","rowFields","rowItems","colFields","colItems","pageFields","dataFields","pivotTableStyleInfo","filters"]);function j(t,e){for(let s=1;;s++){const a=e(s);if(!t.has(a))return t.add(a),a}}function yn(t){const e=t.map(s=>`<Relationship Id="${s.id}" Type="${s.type}" Target="${ae(s.target)}"${s.external?' TargetMode="External"':""}/>`).join("");return`${K}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${e}</Relationships>`}function Sn(t,{existing:e=[],saveRecords:s=!0,numFmtId:a,refreshOnLoad:n=!0,firstCacheId:i=1}={}){const o=new Set(e),l=[],r=[],c=[],d=[],u=new Map;let f=i;const x=p=>{l.push(p),c.push({partName:`/${p.name}`,contentType:p.contentType})},w=(p,y,O)=>{const C=y.links??[],D=j(new Set(C.map(N=>N.id)),N=>`rId${N}`);r.push({from:p,id:D,type:H.definition,target:`/${O}`});for(const N of C)r.push({from:p,id:N.id,type:N.type,target:N.external?N.target:`/${N.target.replace(/^\//,"")}`,external:N.external})},h=p=>{if(p.result)return!0;if(p.cache.load(),p.cache.deferred)return!1;try{return p.update(),!0}catch(y){if(y instanceof lt&&p.xml)return!1;throw y}},g=new Set(t.filter(p=>p.dirty||!p.part).map(p=>p.cache)),b=t.filter(p=>g.has(p.cache)),E=p=>!p.dirty&&p.part&&p.xml&&p.cache.part&&p.cache.generation===0&&!p.cache.fields.some(y=>y.calcItems),T=b.filter(E),I=b.filter(p=>!T.includes(p)&&h(p));for(const p of[...T])I.some(y=>y.cache===p.cache)||T.splice(T.indexOf(p),1);const v=b.filter(p=>p.xml&&p.cache.part&&(p.dirty||!p.part)&&!I.includes(p)),F=[];for(const p of t)!p.dirty||!p.part||I.includes(p)||v.includes(p)||(F.push(p.part),p.part=null);const P=new Set(t.filter(p=>!I.includes(p)&&!T.includes(p)&&p.part).map(p=>p.cache));for(const p of v){const y=j(o,O=>`xl/pivotTables/pivotTable${O}.xml`);p.part&&F.push(p.part),x({name:y,contentType:U.table,xml:_e(p)}),w(y,p,p.cache.part),r.push({from:null,sheet:p.anchor?.sheet??null,id:null,type:H.table,target:`/${y}`}),p.part=y}for(const p of I){const{cache:y}=p;p.part&&F.push(p.part),y.part&&!P.has(y)&&(F.push(y.part),y.recordsPart&&F.push(y.recordsPart),y.part=null,y.recordsPart=null);let O=u.get(y);if(O===void 0){const D=f++,N=j(o,M=>`xl/pivotCache/pivotCacheDefinition${M}.xml`);y.id=D;let $=null;const A=(s||!y.hasSource)&&y.recordCount>0;for(const{id:M,type:B,target:Y}of y.source===null?y.links??[]:[])r.push({from:N,id:M,type:B,target:Y,external:!0});if(A){const M=j(o,B=>`xl/pivotCache/pivotCacheRecords${B}.xml`);$="rIdRecords",y.recordsPart=M,r.push({from:N,id:$,type:H.records,target:`/${M}`}),x({name:M,contentType:U.records,large:!0,produce:B=>$e(y,B)})}const R={name:N,contentType:U.definition,xml:null};x(R),O={cacheId:D,defName:N,defPart:R,recordsRel:$},u.set(y,O),d.push({cacheId:D,target:`/${N}`,type:H.definition})}const C=j(o,D=>`xl/pivotTables/pivotTable${D}.xml`);x({name:C,contentType:U.table,xml:an(p,{cacheId:O.cacheId,numFmtId:a})}),w(C,p,O.defName),r.push({from:null,sheet:p.anchor?.sheet??null,id:null,type:H.table,target:`/${C}`}),p.part=C}for(const p of T){const y=u.get(p.cache),O=j(o,C=>`xl/pivotTables/pivotTable${C}.xml`);F.push(p.part),x({name:O,contentType:U.table,xml:_e(p,y.cacheId)}),w(O,p,y.defName),r.push({from:null,sheet:p.anchor?.sheet??null,id:null,type:H.table,target:`/${O}`}),p.part=O}for(const[p,y]of u)y.defPart.xml=Vt(p,{recordsRel:y.recordsRel,numFmtId:a,refreshOnLoad:n&&p.hasSource});return{parts:l,relationships:r,contentTypes:c,replaced:F,workbook:{pivotCaches:d,pivotCachesXml(p){return d.length===0?"":`<pivotCaches>${d.map(y=>`<pivotCache cacheId="${y.cacheId}" r:id="${p(y.cacheId)}"/>`).join("")}</pivotCaches>`}}}}export{U as CONTENT_TYPE,St as CacheRecordsReader,Ye as EMPTY,ze as ERRORS,Ie as NodeReader,H as REL_TYPE,nt as XlError,Sn as buildPivotPackage,Vt as cacheDefinitionXml,It as cacheFromXml,W as isoToSerial,Ne as parseNode,Kt as partBlob,Ot as pivotFromXml,an as pivotTableXml,vt as readCacheDefinition,Tt as readCacheRecords,xn as readPivotParts,bn as recordsBlob,yn as relationshipsXml,X as serialToIso,J as serializeNode,$e as writeCacheRecords};
@@ -1,2 +1,2 @@
1
- import{cellRef as E}from"../core/address.js";const y=10,d=13,g=64,w="10px Arial, 'Liberation Sans', Helvetica, sans-serif";function u(t){let e=0;for(const o of t)e+=/[ilj.,:;'|!]/.test(o)?.28:/[MWmw@%]/.test(o)?.86:/[A-Z]/.test(o)?.68:o.codePointAt(0)>11903?1:.56;return e*y}function M(t,e){const o=[];for(const s of t.split(/\r?\n/)){let r="";for(const n of s.split(/(?<=\s)/)){let l=n;for(r&&u(r+l.trimEnd())>e&&(o.push(r.trimEnd()),r="");u(l.trimEnd())>e&&l.length>1;){let i=1;for(;i<l.length&&u(l.slice(0,i+1))<=e;)i++;o.push(l.slice(0,i)),l=l.slice(i)}r+=l}o.push(r.trimEnd())}return o}function N(t,e,o){if(!o.author?.startsWith("tc="))return o.text??"";const s=o.author.slice(3),r=new Map((t?.persons??[]).map(n=>[n.id,n.displayName]));return(e.threads??[]).filter(n=>n.id===s||n.parentId===s).map(n=>[r.get(n.personId)??n.author,n.text].filter(Boolean).join(": ")).join(`
2
- `)}function I(t,e,o,s){const r=[];for(const[f,a]of e.comments??[]){const c=Math.floor(f/16384),p=f-c*16384;(o===null||o.some(h=>c>=h.r0&&c<=h.r1&&p>=h.c0&&p<=h.c1))&&r.push({row:c,col:p,text:N(t,e,a)})}r.sort((f,a)=>f.row-a.row||f.col-a.col);const n=Math.max(1,Math.floor(s.h/d)),l=[];let i=null;const m=f=>{(i===null||i.length>=n)&&l.push(i=[]),i.push(f)};for(const{row:f,col:a,text:c}of r)i?.length&&m({label:"",text:""}),M(c,Math.max(40,s.w-g)).forEach((p,h)=>m({label:h===0?E(f,a):"",text:p}));return l}function P(t,e){t.save(),t.translate(e.originX,e.originY),t.beginPath(),t.rect(0,0,e.bodyW,e.bodyH),t.clip(),t.fillStyle="#000000",t.textAlign="left",t.textBaseline="alphabetic",e.noteLines.forEach(({label:o,text:s},r)=>{const n=(r+1)*d-3;o&&(t.font=`bold ${w}`,t.fillText(o,0,n)),s&&(t.font=w,t.fillText(s,g,n))}),t.restore()}export{I as notePages,P as paintNotePage};
1
+ import{cellRef as E}from"../core/address.js";const M=10,m=13,g=64,w="10px Arial, 'Liberation Sans', Helvetica, sans-serif";function u(t){let e=0;for(const o of t)e+=/[ilj.,:;'|!]/.test(o)?.28:/[MWmw@%]/.test(o)?.86:/[A-Z]/.test(o)?.68:o.codePointAt(0)>11903?1:.56;return e*M}function b(t,e){const o=[];for(const s of t.split(/\r?\n/)){let r="";for(const n of s.split(/(?<=\s)/)){let i=n;for(r&&u(r+i.trimEnd())>e&&(o.push(r.trimEnd()),r="");u(i.trimEnd())>e&&i.length>1;){let l=1;for(;l<i.length&&u(i.slice(0,l+1))<=e;)l++;o.push(i.slice(0,l)),i=i.slice(l)}r+=i}o.push(r.trimEnd())}return o}function y(t,e,o){if(!o.author?.startsWith("tc="))return o.text??"";const s=o.author.slice(3),r=new Map((t?.persons??[]).map(n=>[n.id,n.displayName]));return(e.threads??[]).filter(n=>n.id===s||n.parentId===s).map(n=>[r.get(n.personId)??n.author,n.text].filter(Boolean).join(": ")).join(`
2
+ `)}function P(t,e,o,s){const r=[];for(const[f,a]of e.comments??[]){const c=Math.floor(f/16384),p=f-c*16384;(o===null||o.some(h=>c>=h.r0&&c<=h.r1&&p>=h.c0&&p<=h.c1))&&r.push({row:c,col:p,text:y(t,e,a)})}r.sort((f,a)=>f.row-a.row||f.col-a.col);const n=Math.max(1,Math.floor(s.h/m)),i=[];let l=null;const d=f=>{(l===null||l.length>=n)&&i.push(l=[]),l.push(f)};for(const{row:f,col:a,text:c}of r)l?.length&&d({label:"",text:""}),b(c,Math.max(40,s.w-g)).forEach((p,h)=>d({label:h===0?E(f,a):"",text:p}));return i}function I(t,e){t.save(),t.translate(e.originX,e.originY),t.beginPath(),t.rect(0,0,e.bodyW,e.bodyH),t.clip(),t.fillStyle="#000000",t.textAlign="left",t.textBaseline="alphabetic",e.noteLines.forEach(({label:o,text:s},r)=>{const n=(r+1)*m-3;t.beginParagraph?.(),o&&(t.font=`bold ${w}`,t.fillText(o,0,n)),s&&(t.font=w,t.fillText(s,g,n)),t.endMark?.()}),t.restore()}export{P as notePages,I as paintNotePage};