@8sheets/data-grid 1.0.2 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +1 -1
  2. package/api/serialize.js +1 -1
  3. package/api/theme-core.js +2 -0
  4. package/calc/adjust.js +1 -1
  5. package/calc/compile.js +1 -1
  6. package/calc/engine.js +1 -1
  7. package/calc/functions/array.js +1 -1
  8. package/calc/functions/database.js +1 -1
  9. package/calc/functions/date.js +1 -1
  10. package/calc/functions/financial.js +1 -1
  11. package/calc/functions/helpers.js +1 -1
  12. package/calc/functions/info.js +1 -1
  13. package/calc/functions/logical.js +1 -1
  14. package/calc/functions/lookup.js +1 -1
  15. package/calc/functions/math.js +1 -1
  16. package/calc/functions/stat.js +1 -1
  17. package/calc/functions/text.js +1 -1
  18. package/calc/parser.js +3 -3
  19. package/calc/values.js +1 -1
  20. package/calcx/async.js +1 -1
  21. package/calcx/culture/custom.js +1 -0
  22. package/calcx/culture/format-locale.js +1 -1
  23. package/calcx/culture/separators.js +1 -0
  24. package/calcx/functions/dynamic.js +1 -1
  25. package/calcx/functions/ets.js +1 -1
  26. package/calcx/functions/misc.js +1 -1
  27. package/calcx/lang/convert.js +1 -0
  28. package/cells/axis-ops.js +1 -1
  29. package/cells/block.js +1 -0
  30. package/cells/book-css.js +2 -2
  31. package/cells/cell-defaults.js +1 -1
  32. package/cells/cf-engine.js +1 -1
  33. package/cells/consolidate-links.js +1 -1
  34. package/cells/find-engine.js +2 -2
  35. package/cells/format-panes.js +3 -3
  36. package/cells/format-tabs.js +2 -2
  37. package/cells/outline-column.js +1 -1
  38. package/cells/panes.js +1 -1
  39. package/cells/rich-runs.js +2 -2
  40. package/cells/rich-values.js +1 -1
  41. package/cells/selection-modes.js +1 -1
  42. package/cells/shift-check.js +1 -0
  43. package/cells/table-rows.js +1 -0
  44. package/cells/text-layout.js +9 -8
  45. package/cells/ui-kit.js +15 -0
  46. package/cells/view-options.js +1 -1
  47. package/celltypes/cell-types.js +2 -2
  48. package/celltypes/diagonal.js +1 -1
  49. package/celltypes/dropdowns.js +3 -2
  50. package/celltypes/file-cell.js +2 -2
  51. package/celltypes/range-template.js +2 -2
  52. package/core/autofill.js +1 -1
  53. package/core/axis-styles.js +1 -0
  54. package/core/axis.js +1 -1
  55. package/core/cell-type-rules.js +1 -0
  56. package/core/changes.js +1 -1
  57. package/core/cond-format.js +1 -1
  58. package/core/culture.js +1 -0
  59. package/core/formula-refs.js +1 -1
  60. package/core/input.js +1 -1
  61. package/core/merge.js +1 -0
  62. package/core/numfmt.js +1 -1
  63. package/core/region-input.js +1 -0
  64. package/core/row-fit.js +1 -0
  65. package/core/sheet.js +1 -1
  66. package/core/sparse.js +1 -1
  67. package/core/structure.js +1 -0
  68. package/core/styles.js +1 -1
  69. package/core/tables.js +2 -2
  70. package/core/validation-ranges.js +1 -0
  71. package/core/whatif.js +1 -1
  72. package/core/workbook.js +1 -1
  73. package/datasheets/data-core.js +1 -1
  74. package/datasheets/gantt-paint.js +1 -1
  75. package/datasheets/manager.js +1 -1
  76. package/datasheets/path-binding.js +2 -2
  77. package/datasheets/rules.js +1 -1
  78. package/datasheets/view.js +2 -2
  79. package/i18n/dom.js +1 -1
  80. package/i18n/en/cells.js +1 -1
  81. package/i18n/en/format.js +1 -1
  82. package/i18n/en/misc.js +1 -1
  83. package/i18n/en/shell.js +2 -2
  84. package/i18n/pl/cells.js +1 -1
  85. package/i18n/pl/format.js +1 -1
  86. package/i18n/pl/misc.js +1 -1
  87. package/i18n/pl/shell.js +2 -2
  88. package/io/client.js +1 -1
  89. package/io/csv.js +8 -8
  90. package/io/plan.js +1 -1
  91. package/io/text-split.js +3 -3
  92. package/io/xlsx-read.js +1 -1
  93. package/io/xlsx-write.js +1 -1
  94. package/io/xml-scan.js +2 -1
  95. package/io/zip-reader.js +1 -1
  96. package/objects/chart-model.js +1 -1
  97. package/package.json +1 -1
  98. package/pivot/engine.js +1 -1
  99. package/pivot/xml.js +2 -2
  100. package/print/paginate.js +1 -1
  101. package/print/render-page.js +3 -3
  102. package/slicers/format.js +2 -2
  103. package/slicers/structured.js +1 -1
  104. package/table-view/api.js +1 -1
  105. package/table-view/cell-editor.js +2 -1
  106. package/table-view/chart.js +1 -0
  107. package/table-view/column-drag.js +1 -1
  108. package/table-view/context-menu.js +1 -0
  109. package/table-view/editors.js +1 -0
  110. package/table-view/events.js +1 -1
  111. package/table-view/files.js +1 -1
  112. package/table-view/fill-handle.js +1 -0
  113. package/table-view/filter-builder.js +1 -0
  114. package/table-view/find.js +1 -0
  115. package/table-view/grid-keys.js +2 -2
  116. package/table-view/labels-de.js +1 -0
  117. package/table-view/labels-es.js +1 -0
  118. package/table-view/labels-fr.js +1 -0
  119. package/table-view/labels-ja.js +1 -0
  120. package/table-view/labels.js +1 -1
  121. package/table-view/model.js +1 -1
  122. package/table-view/mount.js +1 -1
  123. package/table-view/panel.js +1 -1
  124. package/table-view/pivot-spec.js +1 -0
  125. package/table-view/pivot.js +1 -1
  126. package/table-view/public.d.ts +277 -28
  127. package/table-view/reader.worker.js +1 -1
  128. package/table-view/remote.js +1 -1
  129. package/table-view/row-drag.js +1 -0
  130. package/table-view/sparkline.js +1 -0
  131. package/table-view/state-check.js +1 -0
  132. package/table-view/table-css.js +380 -0
  133. package/table-view/version.js +1 -1
  134. package/ui/dialogs.js +3 -3
  135. package/ui/menu-base.js +1 -1
  136. package/ui/protection-ui.js +1 -1
package/io/csv.js CHANGED
@@ -1,8 +1,8 @@
1
- import{BATCH_CELLS as _}from"./xlsx-read.js";import{BOOL as G,CHUNK_BITS as P,CHUNK_SIZE as W,EMPTY as V,NUM as K,STR as X}from"../core/sheet.js";import{parseInput as q}from"../core/input.js";import{dateSerial as tt,formatGeneral as et}from"../core/numfmt.js";import{cutFixed as it,fixedCuts as st,sniffDelimiter as O}from"./text-split.js";function Y(){return{count:0,rows:new Uint32Array(_),cols:new Uint16Array(_),kinds:new Uint8Array(_),values:new Float64Array(_),styles:new Uint16Array(_),formulas:null,valueMeta:null,rowMeta:null}}async function wt(h,{delimiter:n,addString:s,styleFor:l,onBatch:f,onProgress:d,preserveIdentifiers:b=!1,textColumns:x,delimiters:v,consecutive:R=!1,qualifier:w='"',fixed:m=null,startRow:k=0,skipColumns:M=null,dateColumns:T=null}){v?.length&&(n=v[0]),m&&(n=`
2
- `);const Z=new Set((v?.length?v:[]).map(o=>o.charCodeAt(0))),F=w?w.charCodeAt(0):-1;let Q=o=>o;if(M?.size){const o=Math.max(...M),e=new Int32Array(o+1);let a=0;for(let t=0;t<=o;t++)M.has(t)?(e[t]=-1,a++):e[t]=t-a;Q=t=>t<=o?e[t]:t-a}const D=h.stream().pipeThrough(new TextDecoderStream).getReader();let r=Y(),p=0,g=0,C=new Uint32Array(0);const j=(o,e)=>{if(g*2>=C.length){const a=new Uint32Array(Math.max(64,C.length*2));a.set(C),C=a}C[g*2]=o,C[g*2+1]=e,g++};let y=0,c="",L=!1,H=!1,B=n,S=!1;B===void 0&&h.slice&&(B=O(await h.slice(0,65536).text()));let $=!0,U="";if(B===void 0){for(;U.length<65536;){const{done:o,value:e}=await D.read();if(o)break;U+=e}B=O(U.slice(0,65536))}const E=async()=>{r.count>0&&(await f(r),r=Y())},I=()=>{const o=c!==""&&p>=k?Q(y):-1;if(o>=0){const e=c[0]==="="&&!x?.has(y);e&&j(p-k,o);const a=x?.has(y)||e||b&&/^0\d+$/.test(c),t=T?.has(y)?tt(c,T.get(y)):null,i=t!==null?{kind:K,value:t,format:"m/d/yyyy"}:q(a?`'${c}`:c),u=r.count++;r.rows[u]=p-k,r.cols[u]=o,i.kind===K?(r.kinds[u]=K,r.values[u]=i.value,r.styles[u]=i.format?l(i.format):0):i.kind===G?(r.kinds[u]=G,r.values[u]=i.value,r.styles[u]=0):i.kind===V?r.count--:(r.kinds[u]=X,r.values[u]=s(i.text??c),r.styles[u]=0)}c="",y++};if(m)return J();let N=!1;for(;;){const o=U?{value:U}:await D.read();if(U="",o.done)break;let e=o.value;$&&e.charCodeAt(0)===65279&&(e=e.slice(1)),$=!1,S&&e.length&&(e[0]===`
3
- `&&(e=e.slice(1)),S=!1);let a=0;for(let t=0;t<e.length;t++){const i=e.charCodeAt(t);if(L){i===F&&(c+=e.slice(a,t),e.charCodeAt(t+1)===F?(c+=w,t++,a=t+1):t+1>=e.length?(H=!0,L=!1,a=t+1):(L=!1,a=t+1));continue}if(H&&(H=!1,i===F)){c+=w,L=!0,a=t+1;continue}if(i===F&&c===""&&a===t)L=!0,a=t+1;else if(i===B.charCodeAt(0)||Z.has(i)){if(R&&N&&c===""&&a===t){a=t+1;continue}c+=e.slice(a,t),I(),a=t+1,N=!0}else(i===10||i===13)&&(N=!1,c+=e.slice(a,t),I(),i===13&&(e.charCodeAt(t+1)===10?t++:t+1===e.length&&(S=!0)),p++,y=0,a=t+1,r.count>=_-16384&&await E())}c+=e.slice(a),d?.(p)}return(c!==""||y>0)&&I(),await E(),{rows:Math.max(0,p+1-k),formulas:g,formulaCells:C.slice(0,g*2)};async function J(){const o=st(m);let e="";const a=async()=>{for(const t of it(e,o))c=t,I();p++,y=0,e="",r.count>=_-16384&&await E()};for(;;){const t=await D.read();if(t.done)break;let i=t.value;$&&i.charCodeAt(0)===65279&&(i=i.slice(1)),$=!1,S&&i.length&&(i[0]===`
4
- `&&(i=i.slice(1)),S=!1);let u=0;for(let A=0;A<i.length;A++){const z=i.charCodeAt(A);z!==10&&z!==13||(e+=i.slice(u,A),await a(),z===13&&(i.charCodeAt(A+1)===10?A++:A+1===i.length&&(S=!0)),u=A+1)}e+=i.slice(u),d?.(p)}return e!==""&&await a(),await E(),{rows:Math.max(0,p-k),formulas:g,formulaCells:C.slice(0,g*2)}}}const at=(h,n)=>h.includes(n)||h.includes('"')||h.includes(`
5
- `)||h.includes("\r");function*nt(h,n){let s=[],l=0;const{maxRow:f,maxCol:d,columns:b}=h;for(let x=0;x<=f;x+=W){const v=[];for(let w=0;w<=d;w++){const m=b[w]?.[x>>>P];m&&v.push([w,m])}const R=Math.min(W,f-x+1);for(let w=0;w<R;w++)for(const[m,k]of v){if(!k.kinds[w])continue;const M=x+w,T=n(h,M,m);s.push([M,m,T]),l+=T.length,(s.length>=2048||l>=262144)&&(yield s,s=[],l=0)}yield s,s=[],l=0}}class ot{constructor(n,s=",",{bom:l=!1,width:f=0}={}){this.sink=n,this.delimiter=s,this.row=0,this.col=0,this.encoder=new TextEncoder,this.bom=l,this.width=f,this.emptyRow=s.repeat(Math.max(0,f-1))}_pad(){return this.delimiter.repeat(Math.max(0,this.width-1-this.col))}async _write(n){this.bom&&(n=`\uFEFF${n}`,this.bom=!1),await this.sink.write(this.encoder.encode(n))}async batch(n){let s="";for(const[l,f,d]of n)l>this.row&&(s+=this._pad(),l-this.row>1&&(await this._write(s),s="",await this._emptyRows(l-this.row-1)),s+=`\r
6
- `,this.row=l,this.col=0),s+=this.delimiter.repeat(f-this.col),s+=at(d,this.delimiter)?`"${d.replace(/"/g,'""')}"`:d,this.col=f,s.length>=1<<20&&(await this._write(s),s="");s&&await this._write(s)}async _emptyRows(n){const s=`\r
7
- ${this.emptyRow}`,l=Math.max(1,Math.floor((1<<20)/s.length));for(let f=n;f>0;f-=l)await this._write(s.repeat(Math.min(f,l)))}async finish(n){if(n<this.row){this.bom&&await this._write("");return}await this._write(this._pad()),await this._emptyRows(n-this.row),await this._write(`\r
8
- `)}}async function dt(h,n,s,l=",",f={}){const d=new ot(s,l,f);for(const b of nt(h,n))await d.batch(b);await d.finish(h.maxRow)}export{ot as CsvWriter,nt as csvBatches,et as formatGeneral,wt as readCsv,O as sniffDelimiter,dt as writeCsv};
1
+ import{MAX_COLS as W,MAX_ROWS as et}from"../core/address.js";import{BATCH_CELLS as v}from"./xlsx-read.js";import{BOOL as Z,CHUNK_BITS as it,CHUNK_SIZE as j,EMPTY as st,NUM as X,STR as nt}from"../core/sheet.js";import{parseInput as at}from"../core/input.js";import{regionInput as lt}from"../core/region-input.js";import{dateSerial as ot,formatGeneral as rt}from"../core/numfmt.js";import{cutFixed as ct,fixedCuts as ft,sniffDelimiter as G}from"./text-split.js";function J(){return{count:0,rows:new Uint32Array(v),cols:new Uint16Array(v),kinds:new Uint8Array(v),values:new Float64Array(v),styles:new Uint16Array(v),formulas:null,valueMeta:null,rowMeta:null}}async function gt(u,{delimiter:l,addString:i,styleFor:r,onBatch:h,onProgress:m,preserveIdentifiers:b=!1,textColumns:A,delimiters:k,consecutive:D=!1,qualifier:d='"',fixed:y=null,startRow:C=0,skipColumns:M=null,dateColumns:L=null,region:T=null,maxRows:H=et}){const P=T?lt(T):a=>a;k?.length&&(l=k[0]),y&&(l=`
2
+ `);const V=new Set((k?.length?k:[]).map(a=>a.charCodeAt(0))),I=d?d.charCodeAt(0):-1;let Y=a=>a;if(M?.size){const a=Math.max(...M),e=new Int32Array(a+1);let s=0;for(let t=0;t<=a;t++)M.has(t)?(e[t]=-1,s++):e[t]=t-s;Y=t=>t<=a?e[t]:t-s}const N=u.stream().pipeThrough(new TextDecoderStream).getReader();let c=J(),p=0,R=!1,_=0,g=new Uint32Array(0);const q=(a,e)=>{if(_*2>=g.length){const s=new Uint32Array(Math.max(64,g.length*2));s.set(g),g=s}g[_*2]=a,g[_*2+1]=e,_++};let x=0,f="",B=!1,z=!1,F=l,S=!1;F===void 0&&u.slice&&(F=G(await u.slice(0,65536).text(),T?.listSep));let $=!0,U="";if(F===void 0){for(;U.length<65536;){const{done:a,value:e}=await N.read();if(a)break;U+=e}F=G(U.slice(0,65536),T?.listSep)}const E=async()=>{c.count>0&&(await h(c),c=J())},O=()=>{const a=p>=C?Y(x):-1,e=a>=0&&f!=="";if(e&&(p-C>=H||a>=W))R=!0;else if(e){const s=f[0]==="="&&!A?.has(x);s&&q(p-C,a);const t=A?.has(x)||s||b&&/^0\d+$/.test(f),n=L?.has(x)?ot(f,L.get(x)):null,w=n!==null?{kind:X,value:n,format:"m/d/yyyy"}:at(t?`'${f}`:P(f),T?.currency),o=c.count++;c.rows[o]=p-C,c.cols[o]=a,w.kind===X?(c.kinds[o]=X,c.values[o]=w.value,c.styles[o]=w.format?r(w.format):0):w.kind===Z?(c.kinds[o]=Z,c.values[o]=w.value,c.styles[o]=0):w.kind===st?c.count--:(c.kinds[o]=nt,c.values[o]=i(w.text??f),c.styles[o]=0)}f="",x++};if(y)return tt();let K=!1;for(;;){const a=U?{value:U}:await N.read();if(U="",a.done)break;let e=a.value;$&&e.charCodeAt(0)===65279&&(e=e.slice(1)),$=!1,S&&e.length&&(e[0]===`
3
+ `&&(e=e.slice(1)),S=!1);let s=0;for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(B){n===I&&(f+=e.slice(s,t),e.charCodeAt(t+1)===I?(f+=d,t++,s=t+1):t+1>=e.length?(z=!0,B=!1,s=t+1):(B=!1,s=t+1));continue}if(z&&(z=!1,n===I)){f+=d,B=!0,s=t+1;continue}if(n===I&&f===""&&s===t)B=!0,s=t+1;else if(n===F.charCodeAt(0)||V.has(n)){if(D&&K&&f===""&&s===t){s=t+1;continue}f+=e.slice(s,t),O(),s=t+1,K=!0}else(n===10||n===13)&&(K=!1,f+=e.slice(s,t),O(),n===13&&(e.charCodeAt(t+1)===10?t++:t+1===e.length&&(S=!0)),p++,x=0,s=t+1,c.count>=v-W&&await E())}f+=e.slice(s),m?.(p)}return(f!==""||x>0)&&(O(),p++),await E(),{rows:Math.min(H,Math.max(0,p-C)),truncated:R,formulas:_,formulaCells:g.slice(0,_*2)};async function tt(){const a=ft(y);let e="";const s=async()=>{for(const t of ct(e,a))f=t,O();p++,x=0,e="",c.count>=v-W&&await E()};for(;;){const t=await N.read();if(t.done)break;let n=t.value;$&&n.charCodeAt(0)===65279&&(n=n.slice(1)),$=!1,S&&n.length&&(n[0]===`
4
+ `&&(n=n.slice(1)),S=!1);let w=0;for(let o=0;o<n.length;o++){const Q=n.charCodeAt(o);Q!==10&&Q!==13||(e+=n.slice(w,o),await s(),Q===13&&(n.charCodeAt(o+1)===10?o++:o+1===n.length&&(S=!0)),w=o+1)}e+=n.slice(w),m?.(p)}return e!==""&&await s(),await E(),{rows:Math.min(H,Math.max(0,p-C)),truncated:R,formulas:_,formulaCells:g.slice(0,_*2)}}}const ht=(u,l)=>u.includes(l)||u.includes('"')||u.includes(`
5
+ `)||u.includes("\r");function*ut(u,l){let i=[],r=0;const{maxRow:h,maxCol:m,columns:b}=u;for(let A=0;A<=h;A+=j){const k=[];for(let d=0;d<=m;d++){const y=b[d]?.[A>>>it];y&&k.push([d,y])}const D=Math.min(j,h-A+1);for(let d=0;d<D;d++)for(const[y,C]of k){if(!C.kinds[d])continue;const M=A+d,L=l(u,M,y);i.push([M,y,L]),r+=L.length,(i.length>=2048||r>=262144)&&(yield i,i=[],r=0)}yield i,i=[],r=0}}class dt{constructor(l,i=",",{bom:r=!1,width:h=0}={}){this.sink=l,this.delimiter=i,this.row=0,this.col=0,this.encoder=new TextEncoder,this.bom=r,this.width=h,this.emptyRow=i.repeat(Math.max(0,h-1))}_pad(){return this.delimiter.repeat(Math.max(0,this.width-1-this.col))}async _write(l){this.bom&&(l=`\uFEFF${l}`,this.bom=!1),await this.sink.write(this.encoder.encode(l))}async batch(l){let i="";for(const[r,h,m]of l)r>this.row&&(i+=this._pad(),r-this.row>1&&(await this._write(i),i="",await this._emptyRows(r-this.row-1)),i+=`\r
6
+ `,this.row=r,this.col=0),i+=this.delimiter.repeat(h-this.col),i+=ht(m,this.delimiter)?`"${m.replace(/"/g,'""')}"`:m,this.col=h,i.length>=1<<20&&(await this._write(i),i="");i&&await this._write(i)}async _emptyRows(l){const i=`\r
7
+ ${this.emptyRow}`,r=Math.max(1,Math.floor((1<<20)/i.length));for(let h=l;h>0;h-=r)await this._write(i.repeat(Math.min(h,r)))}async finish(l){if(l<this.row){this.bom&&await this._write("");return}await this._write(this._pad()),await this._emptyRows(l-this.row),await this._write(`\r
8
+ `)}}async function kt(u,l,i,r=",",h={}){const m=new dt(i,r,h);for(const b of ut(u,l))await m.batch(b);await m.finish(u.maxRow)}export{dt as CsvWriter,ut as csvBatches,rt as formatGeneral,gt as readCsv,G as sniffDelimiter,kt as writeCsv};
package/io/plan.js CHANGED
@@ -1 +1 @@
1
- import{ignoredErrorsXml as c}from"./xlsx-tail.js";import{colRecords as u}from"./export-blocks.js";import"../core/address.js";import{richExtras as h}from"../cells/rich-xml.js";import{prepareDefaultsForSave as f}from"../cells/cell-defaults.js";import{tablePatch as p,tableXml as g}from"../core/tables.js";import{printNameEntries as C}from"../print/page-setup.js";import{notesWithAnchors as w}from"../cells/note-xml.js";import{autoFilterXml as x,filterNameEntries as S,sheetFilterXml as P,sheetProps as y}from"../cells/filter-file.js";import{bookViewPlan as v,sheetViewPlan as E}from"../cells/view-xml.js";import{backgroundPlan as N}from"../cells/background-xml.js";import{watermarkPlan as V}from"../api/watermark-xml.js";import{docPropsPlan as X}from"../cells/docprops-xml.js";import{namedStylesPlan as z}from"../cells/cell-styles-xml.js";import{dataConsolidateXml as R}from"../cells/consolidate-links.js";import{customSheetViewsXml as I,customWorkbookViewsXml as O,viewNameEntries as A}from"../core/custom-views.js";import{externalLinkPlan as D}from"../calcx/external-write.js";const o=t=>t.map(r=>{const a={};for(const l of Object.keys(r))l[0]!=="_"&&(a[l]=r[l]);return a});function F(t){for(const r of t.formulas.descriptors())if(r.typed&&(r.cm||r.tpl?.mayArray))return!0;return!1}function M(t){const r={};for(const a of Object.keys(t))a[0]!=="_"&&(r[a]=t[a]);return r}function T(t){return[...t.engine.names].map(([r,a])=>{const l=r.indexOf("!");return{name:a.name??(l>=0?r.slice(l+1):r),localSheetId:l>=0?Number(r.slice(0,l)):void 0,text:a.text,hidden:a.hidden,comment:a.comment}})}function H(t){if(!t.engine)return[];const r=[],a=[...t.engine.tables.values()];let l=a.reduce((n,i)=>Math.max(n,i.id??0),0)+1,s=1e3;const e=new Set([...a.map(n=>n.part),...(t.removedTables??[]).map(n=>n.part)]),d=()=>{let n;do n=`xl/tables/table${s++}.xml`;while(e.has(n));return e.add(n),n};for(const n of a){if(!n.dirty)continue;const i=t.sheets.indexOf(n.sheet);if(i<0)continue;n.id===void 0&&(n.id=l++);const m=n.part??d();n.part=m,r.push({part:m,sheetIndex:i,isNew:n.isNew===!0,xml:n.source&&!n.columnsChanged?null:g(n,n.id),patch:p(n)})}return r}function ne(t,r){f(t);const a=[];for(let e=r.strings;e<t.strings.size;e++)a.push(t.strings.get(e));const s=t.source!==null?t.styles.list.slice(r.styles):t.styles.list;return{bookView:v(t),docProps:X(t),namedStyles:z(t),activeSheet:t.activeSheet,formulasEdited:t.formulasEdited,dynamicArrays:t.sheets.some(e=>F(e)),newDxfs:(t.dxfs??[]).slice(t.sourceDxfs??0),definedNames:t.namesChanged?T(t):null,calcMode:t.calcModeChanged?t.calcMode:null,calcSettings:t.calcSettingsChanged?t.calcSettings:null,persons:t.personsChanged?t.persons:null,workbookProtection:t.protectionChanged?t.protection??{}:null,fileSharing:t.fileSharingChanged?t.fileSharing??{}:null,externalLinks:D(t),customViews:t.customViewsChanged||t.namesChanged&&t.customViews?.length?{workbookXml:O(t),names:A(t)}:null,workbookType:t.fileKind??null,tables:H(t),removedTables:t.removedTables??[],printNames:C(t.sheets),filterNames:S(t.sheets),themeXml:t.themeChanged?t.themeXml:null,extraStrings:a,extraRich:h(t.strings,r.strings),styles:s.map(M),sheets:t.sheets.map((e,d)=>({name:e.name,chartSheet:e.isChartSheet===!0,sourceIndex:e.sourceIndex!==void 0?e.sourceIndex:-1,tabColor:e.tabColorChanged?e.tabColor??"":null,hidden:e.hidden===!0,veryHidden:e.hidden===!0&&e.veryHidden===!0,cols:u(e),colsChanged:e.colsChanged===!0,structureOps:e.structureOps??[],autoFilter:e.filterChanged?P(e):null,sheetProps:y(e),cf:e.cfChanged?o(e.cf??[]):null,validations:e.validationsChanged?o(e.validations??[]):null,hyperlinks:e.hyperlinksChanged?(e.hyperlinks??[]).map(({_ranges:n,...i})=>i):null,protection:e.protectionChanged?e.protection??!1:null,scenarios:e.scenariosChanged?e.scenarios??{items:[]}:null,ignoredErrors:e.ignoredErrorsChanged?c(e.ignoredErrors):null,dataConsolidate:e.dataConsolidateChanged?R(e.dataConsolidate):null,customSheetViews:t.customViewsChanged?I(t,e,n=>x(n,!1)):null,threads:e.threadsChanged?e.threads??[]:null,comments:e.commentsChanged?w(e):null,sparklines:e.sparklinesChanged?e.sparklines??[]:null,pageSetup:e.pageSetupChanged?e.pageSetup:null,viewChanged:e.viewChanged===!0,merges:e.merges,defaultHeight:e.rows.defaultSize,defaultsChanged:e.defaultsChanged===!0,frozenRows:e.frozenRows,frozenCols:e.frozenCols,showGridlines:e.showGridlines,rtl:e.rtl===!0,...E(e,t),sheetPicture:N(e,t),headerPicture:V(e,d),zoom:e.zoom,maxRow:e.maxRow,maxCol:e.maxCol,cellEstimate:(e.maxRow+1)*(e.maxCol+1)}))}}export{ne as buildPlan};
1
+ import{defaultTheme as u,themeXml as c}from"../api/theme-core.js";import{ignoredErrorsXml as h}from"./xlsx-tail.js";import{colRecords as f}from"./export-blocks.js";import"../core/address.js";import{richExtras as p}from"../cells/rich-xml.js";import{prepareDefaultsForSave as g}from"../cells/cell-defaults.js";import{tablePatch as C,tableXml as w}from"../core/tables.js";import{printNameEntries as x}from"../print/page-setup.js";import{notesWithAnchors as S}from"../cells/note-xml.js";import{autoFilterXml as P,filterNameEntries as y,sheetFilterXml as v,sheetProps as E}from"../cells/filter-file.js";import{bookViewPlan as X,sheetViewPlan as N}from"../cells/view-xml.js";import{backgroundPlan as V}from"../cells/background-xml.js";import{watermarkPlan as R}from"../api/watermark-xml.js";import{docPropsPlan as z}from"../cells/docprops-xml.js";import{namedStylesPlan as I}from"../cells/cell-styles-xml.js";import{dataConsolidateXml as O}from"../cells/consolidate-links.js";import{customSheetViewsXml as T,customWorkbookViewsXml as D,viewNameEntries as A}from"../core/custom-views.js";import{externalLinkPlan as F}from"../calcx/external-write.js";const o=t=>t.map(r=>{const a={};for(const l of Object.keys(r))l[0]!=="_"&&(a[l]=r[l]);return a});function M(t){for(const r of t.formulas.descriptors())if(r.typed&&(r.cm||r.tpl?.mayArray))return!0;return!1}function H(t){const r={};for(const a of Object.keys(t))a[0]!=="_"&&(r[a]=t[a]);return r}function L(t){return[...t.engine.names].map(([r,a])=>{const l=r.indexOf("!");return{name:a.name??(l>=0?r.slice(l+1):r),localSheetId:l>=0?Number(r.slice(0,l)):void 0,text:a.text,hidden:a.hidden,comment:a.comment}})}function _(t){if(!t.engine)return[];const r=[],a=[...t.engine.tables.values()];let l=a.reduce((n,i)=>Math.max(n,i.id??0),0)+1,s=1e3;const m=new Set([...a.map(n=>n.part),...(t.removedTables??[]).map(n=>n.part)]),e=()=>{let n;do n=`xl/tables/table${s++}.xml`;while(m.has(n));return m.add(n),n};for(const n of a){if(!n.dirty)continue;const i=t.sheets.indexOf(n.sheet);if(i<0)continue;n.id===void 0&&(n.id=l++);const d=n.part??e();n.part=d,r.push({part:d,sheetIndex:i,isNew:n.isNew===!0,xml:n.source&&!n.columnsChanged?null:w(n,n.id),patch:C(n)})}return r}function le(t,r){g(t);const a=[];for(let e=r.strings;e<t.strings.size;e++)a.push(t.strings.get(e));const l=t.source!==null,s=l?t.styles.list.slice(r.styles):t.styles.list,m=!l&&!t.theme?.length&&s.some(e=>e.themeRefs);return{bookView:X(t),docProps:z(t),namedStyles:I(t),activeSheet:t.activeSheet,date1904:t.date1904,formulasEdited:t.formulasEdited,dynamicArrays:t.sheets.some(e=>M(e)),newDxfs:(t.dxfs??[]).slice(t.sourceDxfs??0),definedNames:t.namesChanged?L(t):null,calcMode:t.calcModeChanged?t.calcMode:null,calcSettings:t.calcSettingsChanged?t.calcSettings:null,persons:t.personsChanged?t.persons:null,workbookProtection:t.protectionChanged?t.protection??{}:null,fileSharing:t.fileSharingChanged?t.fileSharing??{}:null,externalLinks:F(t),customViews:t.customViewsChanged||t.namesChanged&&t.customViews?.length?{workbookXml:D(t),names:A(t)}:null,workbookType:t.fileKind??null,tables:_(t),removedTables:t.removedTables??[],printNames:x(t.sheets),filterNames:y(t.sheets),themeXml:t.themeChanged?t.themeXml:m?c(u()):null,extraStrings:a,extraRich:p(t.strings,r.strings),styles:s.map(H),sheets:t.sheets.map((e,n)=>({name:e.name,chartSheet:e.isChartSheet===!0,sourceIndex:e.sourceIndex!==void 0?e.sourceIndex:-1,tabColor:e.tabColorChanged?e.tabColor??"":null,hidden:e.hidden===!0,veryHidden:e.hidden===!0&&e.veryHidden===!0,cols:f(e),colsChanged:e.colsChanged===!0,structureOps:e.structureOps??[],autoFilter:e.filterChanged?v(e):null,sheetProps:E(e),cf:e.cfChanged?o(e.cf??[]):null,validations:e.validationsChanged?o(e.validations??[]):null,hyperlinks:e.hyperlinksChanged?(e.hyperlinks??[]).map(({_ranges:i,...d})=>d):null,protection:e.protectionChanged?e.protection??!1:null,scenarios:e.scenariosChanged?e.scenarios??{items:[]}:null,ignoredErrors:e.ignoredErrorsChanged?h(e.ignoredErrors):null,dataConsolidate:e.dataConsolidateChanged?O(e.dataConsolidate):null,customSheetViews:t.customViewsChanged?T(t,e,i=>P(i,!1)):null,threads:e.threadsChanged?e.threads??[]:null,comments:e.commentsChanged?S(e):null,sparklines:e.sparklinesChanged?e.sparklines??[]:null,pageSetup:e.pageSetupChanged?e.pageSetup:null,viewChanged:e.viewChanged===!0,merges:e.merges,defaultHeight:e.rows.defaultSize,defaultsChanged:e.defaultsChanged===!0,frozenRows:e.frozenRows,frozenCols:e.frozenCols,showGridlines:e.showGridlines,rtl:e.rtl===!0,...N(e,t),sheetPicture:V(e,t),headerPicture:R(e,n),zoom:e.zoom,maxRow:e.maxRow,maxCol:e.maxCol,cellEstimate:(e.maxRow+1)*(e.maxCol+1)}))}}export{le as buildPlan};
package/io/text-split.js CHANGED
@@ -1,3 +1,3 @@
1
- function c(e){const n=e.replace(/"(?:[^"]|"")*(?:"|$)/g,"").split(/\r\n|[\r\n]/).slice(0,10);let r=",",t=0;for(const i of[",",";"," ","|"]){const o=n.map(l=>l.split(i).length-1),s=Math.min(...o.slice(0,Math.max(1,o.length-1)));s>t&&(r=i,t=s)}return r}function f(e){return[0,...e.filter(n=>n>0).sort((n,r)=>n-r)]}function u(e,n){const r=[];for(let t=0;t<n.length&&!(t>0&&n[t]>=e.length);t++)r.push(e.slice(n[t],n[t+1]).trim());return r}function h(e,n='"'){const r=[];let t=0,i=!1;for(let o=0;o<e.length;o++){const s=e[o];n&&s===n?i=!i:!i&&(s===`
2
- `||s==="\r")&&(r.push(e.slice(t,o)),s==="\r"&&e[o+1]===`
3
- `&&o++,t=o+1)}return t<e.length&&r.push(e.slice(t)),r}export{u as cutFixed,f as fixedCuts,c as sniffDelimiter,h as splitRecords};
1
+ function f(e,n=","){const o=e.replace(/"(?:[^"]|"")*(?:"|$)/g,"").split(/\r\n|[\r\n]/).slice(0,10);let t=",",i=0;for(const r of[",",";"," ","|"]){const s=o.map(c=>c.split(r).length-1),l=Math.min(...s.slice(0,Math.max(1,s.length-1)));if(r===n&&r!==","&&l>0)return r;l>i&&(t=r,i=l)}return t}function u(e){return[0,...e.filter(n=>n>0).sort((n,o)=>n-o)]}function h(e,n){const o=[];for(let t=0;t<n.length&&!(t>0&&n[t]>=e.length);t++)o.push(e.slice(n[t],n[t+1]).trim());return o}function p(e,n='"'){const o=[];let t=0,i=!1;for(let r=0;r<e.length;r++){const s=e[r];n&&s===n?i=!i:!i&&(s===`
2
+ `||s==="\r")&&(o.push(e.slice(t,r)),s==="\r"&&e[r+1]===`
3
+ `&&r++,t=r+1)}return t<e.length&&o.push(e.slice(t)),o}export{h as cutFixed,u as fixedCuts,f as sniffDelimiter,p as splitRecords};
package/io/xlsx-read.js CHANGED
@@ -1 +1 @@
1
- import{openZip as ce}from"./zip-reader.js";import{child as T,children as S,decodeRange as R,indexOfSeq as de,nameIs as x,parseAttrs as C,parseTree as P,unescapeOoxml as M,unescapeXml as L,XmlScanner as D}from"./xml-scan.js";import{relsPathOf as X,resolveTarget as A}from"./package-paths.js";import{parseStyles as fe,parseTheme as K,resolveColor as G}from"./xlsx-styles.js";import{parseComments as me,parseDxfs as ue,parseSheetFeatures as pe}from"./xlsx-tail.js";import{readSplitPane as we}from"../cells/view-xml.js";import{parseSparklines as ye}from"../core/sparklines.js";import{readSheetFilter as ge,readTableFilter as xe}from"../cells/filter-file.js";import{readRunProp as Te}from"../cells/rich-xml.js";import{applyCfExt as Se}from"../cells/cf-file.js";import{readSheetViewAttrs as Ne}from"../cells/view-xml.js";import{readExternalLinks as ve}from"../calcx/external-read.js";import{BOOL as Ie,EMPTY as Z,ERR as _e,ERRORS as Re,FORMULA as ke,NUM as Q,STR as ee}from"../core/sheet.js";import{parseRangeRef as te,MAX_COLS as $}from"../core/address.js";const F=65536,Pe=16384,se=65536,B=6,U=new TextEncoder;async function ie(c,e){const s=c.getReader();for(;;){const{done:t,value:r}=await s.read();if(t)return;const i=e(r);i!==void 0&&await i}}const j=new Float64Array(23);for(let c=0,e=1;c<23;c++,e*=10)j[c]=e;function O(c,e,s){let t=e,r=!1;c[t]===45?(r=!0,t++):c[t]===43&&t++;let i=0,o=0,l=0,a=t<s;for(;t<s;t++){const h=c[t]-48;if(h>=0&&h<=9)i=i*10+h,i!==0&&o++;else break}if(t<s&&c[t]===46)for(t++;t<s;t++){const h=c[t]-48;if(h>=0&&h<=9)i=i*10+h,i!==0&&o++,l++;else break}let u=0;if(t<s&&(c[t]===69||c[t]===101)){t++;let h=!1;for(c[t]===45?(h=!0,t++):c[t]===43&&t++;t<s;t++){const f=c[t]-48;if(f>=0&&f<=9)u=u*10+f;else{a=!1;break}}h&&(u=-u)}else t<s&&(a=!1);const d=u-l;if(a&&o<=15&&d>=-22&&d<=22){const h=d<0?i/j[-d]:i*j[d];return r?-h:h}return Number(R(c,e,s))}class Ce{constructor(e){this.sink=e,this.bytes=new Uint8Array(1<<20),this.len=0,this.offsets=new Uint32Array(se+1),this.count=0,this.total=0,this.rich=null}addRich(e,s){const t=this.bytes.subarray(this.offsets[this.count-1],this.offsets[this.count]),r=new TextDecoder;for(const i of s)i.at=r.decode(t.subarray(0,i.at)).length;(this.rich??=[]).push([e,s])}_reserve(e){if(this.len+e>this.bytes.length){const s=new Uint8Array(Math.max(this.bytes.length*2,this.len+e));s.set(this.bytes.subarray(0,this.len)),this.bytes=s}}appendXml(e,s,t){let r=!0;for(let i=s;i<t;i++){const o=e[i];if(o===38||o===95&&e[i+1]===120){r=!1;break}}if(r)this._reserve(t-s),this.bytes.set(e.subarray(s,t),this.len),this.len+=t-s;else{const i=U.encode(M(L(R(e,s,t))));this._reserve(i.length),this.bytes.set(i,this.len),this.len+=i.length}}appendText(e){const s=U.encode(e);this._reserve(s.length),this.bytes.set(s,this.len),this.len+=s.length}finish(){const e=this.total++;if(this.count++,this.count>=this.offsets.length){const s=new Uint32Array(this.offsets.length*2);s.set(this.offsets),this.offsets=s}return this.offsets[this.count]=this.len,e}get pending(){return this.count}flush(){if(this.count===0)return;const e=this.bytes.slice(0,this.len),s=this.offsets.slice(0,this.count+1);this.len=0,this.count=0,this.offsets[0]=0;const{rich:t}=this;return this.rich=null,this.sink.strings(e,s,t)}}const ae=new TextDecoder;class Me{constructor(e){this.pages=e,this.inT=!1,this.phonetic=0,this.runs=null,this.run=null,this.inProps=!1}_finish(){const e=this.pages.finish();this.runs!==null&&(this.pages.addRich(e,this.runs),this.runs=null)}open(e,s,t,r,i,o){const l=t-s;this.inProps?this._runProp(e,s,t,r,i):l===1&&e[s]===116?this.inT=!o&&this.phonetic===0:l===1&&e[s]===114&&!o&&this.phonetic===0?(this.run={at:this.pages.len-this.pages.offsets[this.pages.count]},(this.runs??=[]).push(this.run)):l===3&&x(e,s,t,"rPh")&&!o?this.phonetic++:l===3&&x(e,s,t,"rPr")&&!o&&this.run!==null?this.inProps=!0:l===2&&o&&x(e,s,t,"si")&&this._finish()}_runProp(e,s,t,r,i){const o=ae.decode(e.subarray(s,t)),l={};for(const a of ae.decode(e.subarray(r,i)).matchAll(/([\w:]+)="([^"]*)"/g))l[a[1]]=a[2];Te(this.run,o,l)}close(e,s,t){const r=t-s;r===1&&e[s]===116?this.inT=!1:r===2&&x(e,s,t,"si")?this._finish():r===3&&x(e,s,t,"rPh")?this.phonetic--:r===3&&x(e,s,t,"rPr")&&(this.inProps=!1)}text(e,s,t){this.inT&&this.pages.appendXml(e,s,t)}}function Ae(){return{count:0,rows:new Uint32Array(F),cols:new Uint16Array(F),kinds:new Uint8Array(F),values:new Float64Array(F),styles:new Uint16Array(F),formulas:null,valueMeta:null,rowMeta:null}}class be{constructor(e){this.ctx=e,this.scanner=null,this.batch=e.nextBatch(),this.row=-1,this.col=-1,this.style=0,this.type=0,this.typeLong=!1,this.kind=Z,this.value=0,this.inV=!1,this.inF=!1,this.inT=!1,this.inIs=!1,this.phonetic=0,this.formula=null,this.formulaText="",this.pendingText=null,this.flushes=[],this.sharedByIndex=new Map}open(e,s,t,r,i,o){const l=t-s;if(l===1){const a=e[s];a===99?this._cellOpen(e,r,i,o):a===118?this.inV=!o:a===102?this._formulaOpen(e,r,i,o):a===116&&this.inIs&&this.phonetic===0&&(this.inT=!o)}else l===3&&e[s]===114&&e[s+1]===111?this._rowOpen(e,r,i):l===2&&e[s]===105&&e[s+1]===115?(this.inIs=!o,this.pendingText=""):l===3&&x(e,s,t,"rPh")&&!o?this.phonetic++:l===9&&o&&x(e,s,t,"sheetData")&&(this.scanner.stopped=!0)}close(e,s,t){const r=t-s;if(r===1){const i=e[s];i===99?this._commit():i===118?this.inV=!1:i===102?this._formulaClose():i===116&&(this.inT=!1)}else r===2&&e[s]===105&&e[s+1]===115?this.inIs=!1:r===3&&x(e,s,t,"rPh")?this.phonetic--:r===9&&x(e,s,t,"sheetData")&&(this.scanner.stopped=!0)}text(e,s,t){this.inV?this._value(e,s,t):this.inF?this.formulaText+=R(e,s,t):this.inT&&(this.pendingText+=L(R(e,s,t)))}_rowOpen(e,s,t){let r=-1,i=0,o=0,l=!1,a=!1,u=null,d=s,h=-1;for(;d<t;){for(;d<t&&e[d]<=32;)d++;if(d>=t)break;const f=d;for(;d<t&&e[d]!==61;)d++;const g=d;d+=2;const p=d;for(;d<t&&e[d]!==34&&e[d]!==39;)d++;const w=d;d++;const m=g-f;if(m===1&&e[f]===114)h=O(e,p,w)-1;else if(m===1&&e[f]===115)o=O(e,p,w);else if(m===2&&e[f]===104&&e[f+1]===116)r=O(e,p,w);else if(m===6&&x(e,f,g,"hidden"))i=e[p]===49||e[p]===116?1:0;else if(m===12&&x(e,f,g,"customFormat"))l=e[p]===49||e[p]===116;else if(m===12&&x(e,f,g,"customHeight"))a=e[p]===49||e[p]===116;else if(!(m===5&&x(e,f,g,"spans"))){const I=R(e,f,w+1);u=u===null?I:`${u} ${I}`}}if(this.row=h>=0?h:this.row+1,this.col=-1,i||u!==null||l&&o||r>=0&&r!==this.ctx.defaultHeight){const f=this.batch;f.rowMeta===null&&(f.rowMeta=[]),f.rowMeta.push(this.row,r>=0?r:-1,i,l?o:0,a?1:0,u)}}_cellOpen(e,s,t,r){let i=-1,o=0,l=0,a=!1,u=0,d=0,h=s;for(;h<t;){for(;h<t&&e[h]<=32;)h++;if(h>=t)break;const f=e[h],g=e[h+1]===61,p=e[h+1]===109&&e[h+2]===61&&(f===99||f===118);for(;h<t&&e[h]!==61;)h++;if(h+=2,g&&f===114){let w=0,m=e[h];for(;m>=65&&m<=90;)w=w*26+m-64,m=e[++h];i=w-1;let I=0;for(;m>=48&&m<=57;)I=I*10+m-48,m=e[++h];I>0&&(this.row=I-1)}else if(g&&f===115){let w=0,m=e[h];for(;m>=48&&m<=57;)w=w*10+m-48,m=e[++h];o=w}else if(g&&f===116)l=e[h],a=e[h+1]!==34&&e[h+1]!==39;else if(p){let w=0,m=e[h];for(;m>=48&&m<=57;)w=w*10+m-48,m=e[++h];f===99?u=w:d=w}for(;h<t&&e[h]!==34&&e[h]!==39;)h++;h++}this.col=i>=0?i:this.col+1,this.style=o,this.type=l,this.typeLong=a,this.cm=u,this.vm=d,this.kind=Z,this.value=0,this.formula=null,this.pendingText=null,r&&this._commit()}_value(e,s,t){if(s!==t)switch(this.type){case 0:case 110:this.kind=Q,this.value=O(e,s,t);break;case 115:this.typeLong?this.pendingText=(this.pendingText??"")+L(R(e,s,t)):(this.kind=ee,this.value=O(e,s,t));break;case 98:this.kind=Ie,this.value=e[s]===49||e[s]===116?1:0;break;case 101:{const r=Re.indexOf(R(e,s,t));this.kind=_e,this.value=r<0?6:r;break}case 100:{const r=Date.parse(R(e,s,t));this.kind=Q,this.value=r/864e5+25569;break}default:{const r=R(e,s,t);this.pendingText=(this.pendingText??"")+L(r)}}}_formulaOpen(e,s,t,r){const i=C(e,s,t),o={};if(i.t&&(o.t=i.t),i.si!==void 0&&(o.si=Number(i.si)),i.ref&&(o.ref=i.ref),i.ca&&(o.ca=i.ca),i.t==="dataTable")for(const l of["dt2D","dtr","r1","r2","del1","del2"])i[l]!==void 0&&(o[l]=i[l]);else{const l=R(e,s,t).trim();l&&(o.raw=l)}this.formula=o,this.formulaText="",this.inF=!r,r&&o.t==="shared"&&this._resolveShared(o)}_formulaClose(){this.inF=!1;const e=this.formula;e!==null&&(this.formulaText&&(e.f=L(this.formulaText)),e.t==="shared"&&this._resolveShared(e))}_resolveShared(e){if(e.f!==void 0)e.base=this.row*$+this.col,this.sharedByIndex.set(e.si,e);else{const s=this.sharedByIndex.get(e.si);s!==void 0&&(s.child===void 0&&(s.child={t:"shared",si:e.si,sf:s.f,base:s.base}),this.formula=s.child)}}_commit(){let e=this.kind,s=this.value;this.pendingText!==null&&(s=this.ctx.addString(M(this.pendingText)),e=ee,this.pendingText=null);const t=this.batch,r=this.formula;if(r!==null)e|=ke,this.cm!==0&&(r.cm=this.cm),t.formulas===null&&(t.formulas=[]),t.formulas.push([this.row*$+this.col,r]);else if(e===Z&&this.style===0)return;this.vm!==0&&(t.valueMeta===null&&(t.valueMeta=[]),t.valueMeta.push([this.row*$+this.col,this.vm]));const i=t.count++;t.rows[i]=this.row,t.cols[i]=this.col,t.kinds[i]=e,t.values[i]=s,t.styles[i]=this.style,this.formula=null,(t.count===F||t.formulas!==null&&t.formulas.length>=Pe)&&(this.flushes.push(t),this.batch=this.ctx.nextBatch())}}function V(c){const e={defaultHeight:16,defaultWidth:65,cols:[],frozenRows:0,frozenCols:0,showGridlines:!0,zoom:1,tabColor:null};return new D({open(t,r,i,o,l){if(x(t,r,i,"outlinePr")){const a=C(t,o,l);e.summaryAbove=a.summaryBelow==="0"||a.summaryBelow==="false",e.outlineAutoStyles=a.applyStyles==="1"||a.applyStyles==="true",e.summaryLeft=a.summaryRight==="0"||a.summaryRight==="false"}else if(x(t,r,i,"tabColor")){const a=C(t,o,l);a.rgb?e.tabColor=`#${a.rgb.slice(-6)}`:e.tabColorRef=a}else if(x(t,r,i,"sheetFormatPr")){const a=C(t,o,l);a.defaultRowHeight&&(e.defaultHeight=Math.round(Number(a.defaultRowHeight))),a.defaultColWidth?e.defaultWidth=ne(Number(a.defaultColWidth)):e.defaultWidth=Number(a.baseColWidth??8)*B+5}else if(x(t,r,i,"col")){const a=C(t,o,l),u=[];for(const d of["bestFit","outlineLevel","collapsed","phonetic"])a[d]!==void 0&&u.push(`${d}="${a[d]}"`);e.cols.push({min:Number(a.min)-1,max:Math.min(Number(a.max)-1,$-1),width:a.width!==void 0?ne(Number(a.width)):-1,hidden:a.hidden==="1"||a.hidden==="true",style:Number(a.style??0),extra:u.length?u.join(" "):null})}else if(x(t,r,i,"sheetView")){const a=C(t,o,l);(a.showGridLines==="0"||a.showGridLines==="false")&&(e.showGridlines=!1),a.tabSelected==="1"&&(e.tabSelected=!0),(a.rightToLeft==="1"||a.rightToLeft==="true")&&(e.rtl=!0),a.zoomScale&&(e.zoom=Number(a.zoomScale)/100),Ne(a,e)}else if(x(t,r,i,"pane")){const a=C(t,o,l);a.state==="frozen"||a.state==="frozenSplit"?(e.frozenRows=Number(a.ySplit??0),e.frozenCols=Number(a.xSplit??0)):we(a,e)}},close(){},text(){}}).feed(U.encode(c)),e}function ne(c){return Math.trunc((256*c+Math.trunc(128/B))/256*B)}function Qe(c){return Math.trunc(c/B*256)/256}function Fe(c){const e=[];return c.indexOf("mergeCell")<0||new D({open(t,r,i,o,l){if(x(t,r,i,"mergeCell")){const a=te(C(t,o,l).ref??"");a&&e.push(a)}},close(){},text(){}}).feed(U.encode(c)),e}const Le=[..."sheetData"].map(c=>c.charCodeAt(0));async function Oe(c,e,s,t,r){let i=[],o=!1,l=null,a=null,u=null;const d=new TextDecoder,h=y=>{const v=V(y);return t.defaultHeight=v.defaultHeight,a=new be(t),u=new D(a),a.scanner=u,v},f=async()=>{if(a.flushes.length===0)return;const y=a.flushes;a.flushes=[];for(const v of y)await t.sendCells(s,v)};if(await ie(await c.stream(e),async y=>{if(l!==null){l.push(y);return}if(!o){i.push(y);const v=z(i),E=de(v,Le,0);if(E<0){i=[v];return}let b=E;for(;b>0&&v[b]!==60;)b--;const H=d.decode(v.subarray(0,b)),W=h(H);await r.sheetStart(s,{...W,head:H}),o=!0,y=v.subarray(b)}u.feed(y),await f(),u.stopped&&(l=[u.rest.slice()])}),o)await f();else{const y=d.decode(z(i));h(y),await r.sheetStart(s,{...V(y),head:y})}(a.batch.count>0||a.batch.rowMeta!==null)&&await t.sendCells(s,a.batch);const g=l===null?"":d.decode(z(l)),p=pe(g);p.sparklines=ye(g,y=>G(y,t.theme)),p.filter=ge(g),Se(p,g,y=>G(y,t.theme));const{comments:w,links:m,threads:I}=await Ee(c,e);p.threads=I;for(const y of p.hyperlinks)y.rid&&m.has(y.rid)&&(y.target=m.get(y.rid));await r.sheetEnd(s,{merges:Fe(g),tail:g,features:p,comments:w})}function z(c){if(c.length===1)return c[0];let e=0;for(const r of c)e+=r.length;const s=new Uint8Array(e);let t=0;for(const r of c)s.set(r,t),t+=r.length;return s}async function Ee(c,e){const s={comments:[],links:new Map,threads:[]},t=X(e);if(!c.has(t))return s;const r=P(await c.bytes(t));for(const i of S(r,"Relationship"))if(/\/hyperlink$/.test(i.a.Type))s.links.set(i.a.Id,i.a.Target);else if(/\/threadedComment$/.test(i.a.Type)){const o=A(e,i.a.Target);c.has(o)&&(s.threads=S(P(await c.bytes(o)),"threadedComment").map(l=>({id:l.a.id,ref:l.a.ref,personId:l.a.personId,date:l.a.dT??"",text:M(T(l,"text")?.t??""),parentId:l.a.parentId??null,done:l.a.done==="1",mentions:S(T(l,"mentions"),"mention").map(a=>({personId:a.a.mentionpersonId,id:a.a.mentionId,start:Number(a.a.startIndex),length:Number(a.a.length)}))})))}else if(/\/comments$/.test(i.a.Type)){const o=A(e,i.a.Target);c.has(o)&&(s.comments=me(await c.bytes(o)))}return s}async function He(c,e){const s=[];for(let t=0;t<e.length;t++){const r=e[t].part;if(!r)continue;const i=X(r);if(!c.has(i))continue;const o=P(await c.bytes(i));for(const l of S(o,"Relationship")){if(!/\/table$/.test(l.a.Type))continue;const a=A(r,l.a.Target);if(!c.has(a))continue;const u=await c.bytes(a),d=P(u),h=te(d.a.ref??"");if(!h)continue;const f=T(d,"tableStyleInfo")?.a??{};s.push({id:Number(d.a.id),part:a,source:!0,styleName:M(f.name??null),showRowStripes:f.showRowStripes!=="0",showColumnStripes:f.showColumnStripes==="1",showFirstColumn:f.showFirstColumn==="1",showLastColumn:f.showLastColumn==="1",hasFilter:T(d,"autoFilter")!==void 0,fileFilter:xe(u),name:d.a.displayName??d.a.name,sheetIndex:t,...h,headerRows:d.a.headerRowCount!==void 0?Number(d.a.headerRowCount):1,totalsRows:Number(d.a.totalsRowCount??0),columns:S(T(d,"tableColumns"),"tableColumn").map(g=>M(g.a.name))})}}return s}async function et(c,e){const s=await ce(c),t=P(await s.bytes("_rels/.rels")),r=S(t,"Relationship").find(n=>/officeDocument$/.test(n.a.Type));if(!r)throw new Error("This file has no workbook part");const i=A("",r.a.Target),o=P(await s.bytes(i)),l=X(i),a=P(await s.bytes(l)),u=new Map,d=new Set;let h=null,f=null,g=null;for(const n of S(a,"Relationship")){const N=A(i,n.a.Target);u.set(n.a.Id,N),/\/chartsheet$/.test(n.a.Type)&&d.add(n.a.Id),/\/sharedStrings$/.test(n.a.Type)?h=N:/\/styles$/.test(n.a.Type)?f=N:/\/theme$/.test(n.a.Type)&&(g=N)}const p=S(T(o,"sheets"),"sheet").map(n=>({name:M(n.a.name),rid:n.a.id,part:u.get(n.a.id),hidden:n.a.state==="hidden"||n.a.state==="veryHidden",veryHidden:n.a.state==="veryHidden",sheetId:n.a.sheetId,chart:d.has(n.a.id)})),w=g&&s.has(g)?K(await s.bytes(g)):K(new TextEncoder().encode("<a/>")),m=f&&s.has(f)?fe(await s.bytes(f),w):[],I=Number(T(T(o,"bookViews"),"workbookView")?.a.activeTab??0),y=n=>/^Z_.*\.wvu\.[A-Za-z]+$/.test(n.a.name),v=S(T(o,"definedNames"),"definedName").filter(y).map(n=>({name:n.a.name,text:n.t,localSheetId:Number(n.a.localSheetId)})),E=S(T(o,"customWorkbookViews"),"customWorkbookView").map(n=>({...n.a})),b=S(T(o,"definedNames"),"definedName").filter(n=>!n.a.name.startsWith("_xlnm.")&&!y(n)).map(n=>({name:n.a.name,text:n.t,localSheetId:n.a.localSheetId!==void 0?Number(n.a.localSheetId):void 0,hidden:n.a.hidden==="1"||void 0,comment:M(n.a.comment)})),H=S(T(o,"definedNames"),"definedName").filter(n=>n.a.name==="_xlnm.Print_Area"||n.a.name==="_xlnm.Print_Titles").map(n=>({name:n.a.name,text:n.t,localSheetId:Number(n.a.localSheetId)})),W=S(T(o,"definedNames"),"definedName").filter(n=>n.a.name==="_xlnm._FilterDatabase"||n.a.name==="_xlnm.Criteria"||n.a.name==="_xlnm.Extract").map(n=>({name:n.a.name,text:n.t,localSheetId:Number(n.a.localSheetId)})),_=T(o,"calcPr")?.a??{},re=S(T(o,"pivotCaches"),"pivotCache").reduce((n,N)=>Math.max(n,Number(N.a.cacheId??0)),0),q={};if(f&&s.has(f))for(const n of S(T(P(await s.bytes(f)),"numFmts"),"numFmt"))q[n.a.numFmtId]=n.a.formatCode;const oe=await He(s,p),le=f&&s.has(f)?ue(await s.bytes(f),n=>G(n,w)):[];await e.meta({sheets:p,styles:m,activeTab:I,workbookPart:i,stringsPart:h,stylesPart:f,names:b,maxPivotCacheId:re,numFmts:q,workbookProtection:T(o,"workbookProtection")?.a??null,fileSharing:T(o,"fileSharing")?.a??null,persons:await De(s,a,i),printNames:H,filterNames:W,viewNames:v,customViews:E,tables:oe,theme:w,themeName:w.themeName,dxfs:le,fullCalcOnLoad:_.fullCalcOnLoad==="1"||_.fullCalcOnLoad==="true",manualCalc:_.calcMode==="manual",calcMode:_.calcMode??"auto",iterate:_.iterate==="1"||_.iterate==="true",iterateCount:_.iterateCount!==void 0?Number(_.iterateCount):100,iterateDelta:_.iterateDelta!==void 0?Number(_.iterateDelta):.001,externalLinks:await ve(s,o,a,i,{child:T,children:S,resolveTarget:A})});const k=new Ce(e);if(h&&s.has(h)){const n=new D(new Me(k));await ie(await s.stream(h),N=>{if(n.feed(N),k.pending>=se||k.len>=1<<22)return k.flush()})}await k.flush(),await e.stringsEnd?.(k.total);const Y=new Map,he={theme:w,defaultHeight:16,nextBatch:()=>e.recycle?.()??Ae(),addString(n){let N=Y.get(n);return N===void 0&&(k.appendText(n),N=k.finish(),Y.set(n,N)),N},async sendCells(n,N){await k.flush(),await e.cells(n,N)}};let J=0;for(let n=0;n<p.length;n++){if(p[n].chart){await e.sheetStart(n,{...V(""),head:"",chartSheet:!0}),await e.sheetEnd(n,{merges:[],tail:s.has(p[n].part)?new TextDecoder().decode(await s.bytes(p[n].part)):""});continue}if(!p[n].part||!s.has(p[n].part)){await e.sheetStart(n,{...V(""),head:""}),await e.sheetEnd(n,{merges:[],tail:""});continue}await Oe(s,p[n].part,n,he,e),J++}return{zip:s,sheets:p,workbookPart:i,wbRelsPath:l,stringsPart:h,stylesPart:f,sheetsRead:J}}async function De(c,e,s){const t=e?S(e,"Relationship").find(i=>/\/person$/.test(i.a.Type)):null,r=t?A(s,t.a.Target):"xl/persons/person.xml";return c.has(r)?S(P(await c.bytes(r)),"person").map(i=>{const o=M(i.a.displayName);return{displayName:o,id:i.a.id,userId:i.a.userId??o,providerId:i.a.providerId??"None"}}):[]}export{F as BATCH_CELLS,ie as pump,Qe as pxToWidth,et as readXlsx,A as resolveTarget,ne as widthToPx};
1
+ import{openZip as we}from"./zip-reader.js";import{child as T,children as N,decodeRange as _,indexOfSeq as ye,nameIs as x,parseAttrs as b,parseTree as P,unescapeOoxml as M,unescapeXml as E,XmlScanner as H}from"./xml-scan.js";import{relsPathOf as G,resolveTarget as C}from"./package-paths.js";import{parseStyles as ge,parseTheme as ee,resolveColor as Z}from"./xlsx-styles.js";import{parseComments as xe,parseDxfs as Te,parseSheetFeatures as Se}from"./xlsx-tail.js";import{readSplitPane as Ne}from"../cells/view-xml.js";import{parseSparklines as ve}from"../core/sparklines.js";import{readSheetFilter as Ie,readTableFilter as _e}from"../cells/filter-file.js";import{readRunProp as ke}from"../cells/rich-xml.js";import{applyCfExt as Re}from"../cells/cf-file.js";import{readSheetViewAttrs as Pe}from"../cells/view-xml.js";import{readExternalLinks as Ce}from"../calcx/external-read.js";import{BOOL as be,EMPTY as z,ERR as Me,ERRORS as Ae,FORMULA as Fe,NUM as te,STR as se}from"../core/sheet.js";import{parseRangeRef as ie,MAX_COLS as B}from"../core/address.js";import{DATE_1904_OFFSET as Le}from"../core/numfmt.js";const F=65536,Oe=16384,ae=65536,U=6,V=new TextEncoder;function Ee(h,e){const t=/^(?:(\d{4}-\d{2}-\d{2})(?:T|(?=Z|$))|T)?(?:(\d{2}):(\d{2})(?::(\d{2}(?:\.\d+)?))?)?(Z|[+-]\d{2}:?\d{2})?$/.exec(h);if(!t||!t[1]&&!t[2])return NaN;const[,s,r="0",i="0",o="0",l]=t;let n=Number(r)*3600+Number(i)*60+Number(o);if(l&&l!=="Z"){const c=Number(l.slice(1,3))*60+Number(l.slice(-2));n-=(l[0]==="-"?-c:c)*60}if(!s)return n/86400;const m=Date.parse(s)/864e5+25569;return(e?m-Le:m<61?m-1:m)+n/86400}async function ne(h,e){const t=h.getReader();for(;;){const{done:s,value:r}=await t.read();if(s)return;const i=e(r);i!==void 0&&await i}}const j=new Float64Array(23);for(let h=0,e=1;h<23;h++,e*=10)j[h]=e;function $(h,e,t){let s=e,r=!1;h[s]===45?(r=!0,s++):h[s]===43&&s++;let i=0,o=0,l=0,n=s<t;for(;s<t;s++){const c=h[s]-48;if(c>=0&&c<=9)i=i*10+c,i!==0&&o++;else break}if(s<t&&h[s]===46)for(s++;s<t;s++){const c=h[s]-48;if(c>=0&&c<=9)i=i*10+c,i!==0&&o++,l++;else break}let m=0;if(s<t&&(h[s]===69||h[s]===101)){s++;let c=!1;for(h[s]===45?(c=!0,s++):h[s]===43&&s++;s<t;s++){const f=h[s]-48;if(f>=0&&f<=9)m=m*10+f;else{n=!1;break}}c&&(m=-m)}else s<t&&(n=!1);const d=m-l;if(n&&o<=15&&d>=-22&&d<=22){const c=d<0?i/j[-d]:i*j[d];return r?-c:c}return Number(_(h,e,t))}class $e{constructor(e){this.sink=e,this.bytes=new Uint8Array(1<<20),this.len=0,this.offsets=new Uint32Array(ae+1),this.count=0,this.total=0,this.rich=null}addRich(e,t){const s=this.bytes.subarray(this.offsets[this.count-1],this.offsets[this.count]),r=new TextDecoder;for(const i of t)i.at=r.decode(s.subarray(0,i.at)).length;(this.rich??=[]).push([e,t])}_reserve(e){if(this.len+e>this.bytes.length){const t=new Uint8Array(Math.max(this.bytes.length*2,this.len+e));t.set(this.bytes.subarray(0,this.len)),this.bytes=t}}appendXml(e,t,s,r){if(!r){for(;t<s&&e[t]<=32;)t++;for(;s>t&&e[s-1]<=32;)s--}let i=!0;for(let o=t;o<s;o++){const l=e[o];if(l===13||l===38||l===95&&e[o+1]===120){i=!1;break}}if(i)this._reserve(s-t),this.bytes.set(e.subarray(t,s),this.len),this.len+=s-t;else{const o=V.encode(M(E(_(e,t,s))));this._reserve(o.length),this.bytes.set(o,this.len),this.len+=o.length}}appendText(e){const t=V.encode(e);this._reserve(t.length),this.bytes.set(t,this.len),this.len+=t.length}finish(){const e=this.total++;if(this.count++,this.count>=this.offsets.length){const t=new Uint32Array(this.offsets.length*2);t.set(this.offsets),this.offsets=t}return this.offsets[this.count]=this.len,e}get pending(){return this.count}flush(){if(this.count===0)return;const e=this.bytes.slice(0,this.len),t=this.offsets.slice(0,this.count+1);this.len=0,this.count=0,this.offsets[0]=0;const{rich:s}=this;return this.rich=null,this.sink.strings(e,t,s)}}const re=new TextDecoder,oe=(h,e,t)=>t>e&&/\bxml:space\s*=\s*['"]preserve['"]/.test(_(h,e,t));class De{constructor(e){this.pages=e,this.inT=!1,this.phonetic=0,this.runs=null,this.run=null,this.inProps=!1}_finish(){const e=this.pages.finish();this.runs!==null&&(this.pages.addRich(e,this.runs),this.runs=null)}open(e,t,s,r,i,o){const l=s-t;this.inProps?this._runProp(e,t,s,r,i):l===1&&e[t]===116?(this.inT=!o&&this.phonetic===0,this.preserveSpace=this.inT&&oe(e,r,i)):l===1&&e[t]===114&&!o&&this.phonetic===0?(this.run={at:this.pages.len-this.pages.offsets[this.pages.count]},(this.runs??=[]).push(this.run)):l===3&&x(e,t,s,"rPh")&&!o?this.phonetic++:l===3&&x(e,t,s,"rPr")&&!o&&this.run!==null?this.inProps=!0:l===2&&o&&x(e,t,s,"si")&&this._finish()}_runProp(e,t,s,r,i){const o=re.decode(e.subarray(t,s)),l={};for(const n of re.decode(e.subarray(r,i)).matchAll(/([\w:]+)="([^"]*)"/g))l[n[1]]=n[2];ke(this.run,o,l)}close(e,t,s){const r=s-t;r===1&&e[t]===116?this.inT=!1:r===2&&x(e,t,s,"si")?this._finish():r===3&&x(e,t,s,"rPh")?this.phonetic--:r===3&&x(e,t,s,"rPr")&&(this.inProps=!1)}text(e,t,s){this.inT&&this.pages.appendXml(e,t,s,this.preserveSpace)}}function He(){return{count:0,rows:new Uint32Array(F),cols:new Uint16Array(F),kinds:new Uint8Array(F),values:new Float64Array(F),styles:new Uint16Array(F),formulas:null,valueMeta:null,rowMeta:null}}class Be{constructor(e){this.ctx=e,this.scanner=null,this.batch=e.nextBatch(),this.row=-1,this.col=-1,this.style=0,this.type=0,this.typeLong=!1,this.kind=z,this.value=0,this.inV=!1,this.inF=!1,this.inT=!1,this.inIs=!1,this.phonetic=0,this.formula=null,this.formulaText="",this.pendingText=null,this.flushes=[],this.sharedByIndex=new Map}open(e,t,s,r,i,o){const l=s-t;if(l===1){const n=e[t];n===99?this._cellOpen(e,r,i,o):n===118?(this.inV=!o,this.type===115&&this.typeLong&&(this.pendingText="")):n===102?this._formulaOpen(e,r,i,o):n===116&&this.inIs&&this.phonetic===0&&(this.inT=!o,this.preserveSpace=this.inT&&oe(e,r,i))}else l===3&&e[t]===114&&e[t+1]===111?this._rowOpen(e,r,i):l===2&&e[t]===105&&e[t+1]===115?(this.inIs=!o,this.pendingText=""):l===3&&x(e,t,s,"rPh")&&!o?this.phonetic++:l===9&&o&&x(e,t,s,"sheetData")&&(this.scanner.stopped=!0)}close(e,t,s){const r=s-t;if(r===1){const i=e[t];i===99?this._commit():i===118?this.inV=!1:i===102?this._formulaClose():i===116&&(this.inT=!1)}else r===2&&e[t]===105&&e[t+1]===115?this.inIs=!1:r===3&&x(e,t,s,"rPh")?this.phonetic--:r===9&&x(e,t,s,"sheetData")&&(this.scanner.stopped=!0)}text(e,t,s){if(this.inV)this._value(e,t,s);else if(this.inF)this.formulaText+=_(e,t,s);else if(this.inT){if(!this.preserveSpace){for(;t<s&&e[t]<=32;)t++;for(;s>t&&e[s-1]<=32;)s--}this.pendingText+=E(_(e,t,s))}}_rowOpen(e,t,s){let r=-1,i=0,o=0,l=!1,n=!1,m=null,d=t,c=-1;for(;d<s;){for(;d<s&&e[d]<=32;)d++;if(d>=s)break;const f=d;for(;d<s&&e[d]!==61;)d++;const w=d;d+=2;const y=d;for(;d<s&&e[d]!==34&&e[d]!==39;)d++;const u=d;d++;const p=w-f;if(p===1&&e[f]===114)c=$(e,y,u)-1;else if(p===1&&e[f]===115)o=$(e,y,u);else if(p===2&&e[f]===104&&e[f+1]===116)r=$(e,y,u);else if(p===6&&x(e,f,w,"hidden"))i=e[y]===49||e[y]===116?1:0;else if(p===12&&x(e,f,w,"customFormat"))l=e[y]===49||e[y]===116;else if(p===12&&x(e,f,w,"customHeight"))n=e[y]===49||e[y]===116;else if(!(p===5&&x(e,f,w,"spans"))){const v=_(e,f,u+1);m=m===null?v:`${m} ${v}`}}if(this.row=c>=0?c:this.row+1,this.col=-1,i||m!==null||l&&o||r>=0&&r!==this.ctx.defaultHeight){const f=this.batch;f.rowMeta===null&&(f.rowMeta=[]),f.rowMeta.push(this.row,r>=0?r:-1,i,l?o:0,n?1:0,m)}}_cellOpen(e,t,s,r){let i=-1,o=0,l=0,n=!1,m=0,d=0,c=t;for(;c<s;){for(;c<s&&e[c]<=32;)c++;if(c>=s)break;const f=e[c],w=e[c+1]===61,y=e[c+1]===109&&e[c+2]===61&&(f===99||f===118);for(;c<s&&e[c]!==61;)c++;if(c+=2,w&&f===114){let u=0,p=e[c];for(;p>=65&&p<=90;)u=u*26+p-64,p=e[++c];i=u-1;let v=0;for(;p>=48&&p<=57;)v=v*10+p-48,p=e[++c];v>0&&(this.row=v-1)}else if(w&&f===115){let u=0,p=e[c];for(;p>=48&&p<=57;)u=u*10+p-48,p=e[++c];o=u}else if(w&&f===116)l=e[c],n=e[c+1]!==34&&e[c+1]!==39;else if(y){let u=0,p=e[c];for(;p>=48&&p<=57;)u=u*10+p-48,p=e[++c];f===99?m=u:d=u}for(;c<s&&e[c]!==34&&e[c]!==39;)c++;c++}this.col=i>=0?i:this.col+1,this.style=o,this.type=l,this.typeLong=n,this.cm=m,this.vm=d,this.kind=z,this.value=0,this.formula=null,this.pendingText=null,r&&this._commit()}_value(e,t,s){if(t!==s)switch(this.type){case 0:case 110:this.kind=te,this.value=$(e,t,s);break;case 115:this.typeLong?this.pendingText=(this.pendingText??"")+E(_(e,t,s)):(this.kind=se,this.value=$(e,t,s));break;case 98:this.kind=be,this.value=e[t]===49||e[t]===116?1:0;break;case 101:{const r=Ae.indexOf(_(e,t,s));this.kind=Me,this.value=r<0?6:r;break}case 100:{const r=_(e,t,s),i=Ee(r,this.ctx.date1904);Number.isFinite(i)?(this.kind=te,this.value=i):this.pendingText=r;break}default:{const r=_(e,t,s);this.pendingText=(this.pendingText??"")+E(r)}}}_formulaOpen(e,t,s,r){const i=b(e,t,s),o={};if(i.t&&(o.t=i.t),i.si!==void 0&&(o.si=Number(i.si)),i.ref&&(o.ref=i.ref),i.ca&&(o.ca=i.ca),i.t==="dataTable")for(const l of["dt2D","dtr","r1","r2","del1","del2"])i[l]!==void 0&&(o[l]=i[l]);else{const l=_(e,t,s).trim();l&&(o.raw=l)}this.formula=o,this.formulaText="",this.inF=!r,r&&o.t==="shared"&&this._resolveShared(o)}_formulaClose(){this.inF=!1;const e=this.formula;e!==null&&(this.formulaText&&(e.f=E(this.formulaText)),e.t==="shared"&&this._resolveShared(e))}_resolveShared(e){if(e.f!==void 0)e.base=this.row*B+this.col,this.sharedByIndex.set(e.si,e);else{const t=this.sharedByIndex.get(e.si);t!==void 0&&(t.child===void 0&&(t.child={t:"shared",si:e.si,sf:t.f,base:t.base}),this.formula=t.child)}}_commit(){let e=this.kind,t=this.value;this.pendingText!==null&&(t=this.ctx.addString(M(this.pendingText)),e=se,this.pendingText=null);const s=this.batch,r=this.formula;if(r!==null&&(r.f!==void 0||r.t==="shared"||r.t==="array"||r.t==="dataTable"))e|=Fe,this.cm!==0&&(r.cm=this.cm),s.formulas===null&&(s.formulas=[]),s.formulas.push([this.row*B+this.col,r]);else if(e===z&&this.style===0)return;this.vm!==0&&(s.valueMeta===null&&(s.valueMeta=[]),s.valueMeta.push([this.row*B+this.col,this.vm]));const i=s.count++;s.rows[i]=this.row,s.cols[i]=this.col,s.kinds[i]=e,s.values[i]=t,s.styles[i]=this.style,this.formula=null,(s.count===F||s.formulas!==null&&s.formulas.length>=Oe)&&(this.flushes.push(s),this.batch=this.ctx.nextBatch())}}function W(h){const e={defaultHeight:16,defaultWidth:65,cols:[],frozenRows:0,frozenCols:0,showGridlines:!0,zoom:1,tabColor:null};return new H({open(s,r,i,o,l){if(x(s,r,i,"outlinePr")){const n=b(s,o,l);e.summaryAbove=n.summaryBelow==="0"||n.summaryBelow==="false",e.outlineAutoStyles=n.applyStyles==="1"||n.applyStyles==="true",e.summaryLeft=n.summaryRight==="0"||n.summaryRight==="false"}else if(x(s,r,i,"tabColor")){const n=b(s,o,l);n.rgb?e.tabColor=`#${n.rgb.slice(-6)}`:e.tabColorRef=n}else if(x(s,r,i,"sheetFormatPr")){const n=b(s,o,l);n.defaultRowHeight&&(e.defaultHeight=Math.round(Number(n.defaultRowHeight))),n.defaultColWidth?e.defaultWidth=le(Number(n.defaultColWidth)):e.defaultWidth=Number(n.baseColWidth??8)*U+5}else if(x(s,r,i,"col")){const n=b(s,o,l),m=[];for(const d of["bestFit","outlineLevel","collapsed","phonetic"])n[d]!==void 0&&m.push(`${d}="${n[d]}"`);e.cols.push({min:Number(n.min)-1,max:Math.min(Number(n.max)-1,B-1),width:n.width!==void 0?le(Number(n.width)):-1,hidden:n.hidden==="1"||n.hidden==="true",style:Number(n.style??0),extra:m.length?m.join(" "):null})}else if(x(s,r,i,"sheetView")){const n=b(s,o,l);(n.showGridLines==="0"||n.showGridLines==="false")&&(e.showGridlines=!1),n.tabSelected==="1"&&(e.tabSelected=!0),(n.rightToLeft==="1"||n.rightToLeft==="true")&&(e.rtl=!0),n.zoomScale&&(e.zoom=Number(n.zoomScale)/100),Pe(n,e)}else if(x(s,r,i,"pane")){const n=b(s,o,l);n.state==="frozen"||n.state==="frozenSplit"?(e.frozenRows=Number(n.ySplit??0),e.frozenCols=Number(n.xSplit??0)):Ne(n,e)}},close(){},text(){}}).feed(V.encode(h)),e}function le(h){return Math.trunc((256*h+Math.trunc(128/U))/256*U)}function lt(h){return Math.trunc(h/U*256)/256}function Ue(h){const e=[];return h.indexOf("mergeCell")<0||new H({open(s,r,i,o,l){if(x(s,r,i,"mergeCell")){const n=ie(b(s,o,l).ref??"");n&&e.push(n)}},close(){},text(){}}).feed(V.encode(h)),e}const Ve=[..."sheetData"].map(h=>h.charCodeAt(0));async function We(h,e,t,s,r){let i=[],o=!1,l=null,n=null,m=null;const d=new TextDecoder,c=g=>{const I=W(g);return s.defaultHeight=I.defaultHeight,n=new Be(s),m=new H(n),n.scanner=m,I},f=async()=>{if(n.flushes.length===0)return;const g=n.flushes;n.flushes=[];for(const I of g)await s.sendCells(t,I)};if(await ne(await h.stream(e),async g=>{if(l!==null){l.push(g);return}if(!o){i.push(g);const I=q(i),L=ye(I,Ve,0);if(L<0){i=[I];return}let A=L;for(;A>0&&I[A]!==60;)A--;const D=d.decode(I.subarray(0,A)),X=c(D);await r.sheetStart(t,{...X,head:D}),o=!0,g=I.subarray(A)}m.feed(g),await f(),m.stopped&&(l=[m.rest.slice()])}),o)await f();else{const g=d.decode(q(i));c(g),await r.sheetStart(t,{...W(g),head:g})}(n.batch.count>0||n.batch.rowMeta!==null)&&await s.sendCells(t,n.batch);const w=l===null?"":d.decode(q(l)),y=Se(w);y.sparklines=ve(w,g=>Z(g,s.theme)),y.filter=Ie(w),Re(y,w,g=>Z(g,s.theme));const{comments:u,links:p,threads:v}=await Xe(h,e);y.threads=v;for(const g of y.hyperlinks)g.rid&&p.has(g.rid)&&(g.target=p.get(g.rid));await r.sheetEnd(t,{merges:Ue(w),tail:w,features:y,comments:u})}function q(h){if(h.length===1)return h[0];let e=0;for(const r of h)e+=r.length;const t=new Uint8Array(e);let s=0;for(const r of h)t.set(r,s),s+=r.length;return t}async function Xe(h,e){const t={comments:[],links:new Map,threads:[]},s=G(e);if(!h.has(s))return t;const r=P(await h.bytes(s));for(const i of N(r,"Relationship"))if(/\/hyperlink$/.test(i.a.Type))t.links.set(i.a.Id,i.a.Target);else if(/\/threadedComment$/.test(i.a.Type)){const o=C(e,i.a.Target);h.has(o)&&(t.threads=N(P(await h.bytes(o)),"threadedComment").map(l=>({id:l.a.id,ref:l.a.ref,personId:l.a.personId,date:l.a.dT??"",text:M(T(l,"text")?.t??""),parentId:l.a.parentId??null,done:l.a.done==="1",mentions:N(T(l,"mentions"),"mention").map(n=>({personId:n.a.mentionpersonId,id:n.a.mentionId,start:Number(n.a.startIndex),length:Number(n.a.length)}))})))}else if(/\/comments$/.test(i.a.Type)){const o=C(e,i.a.Target);h.has(o)&&(t.comments=xe(await h.bytes(o)))}return t}async function Ge(h,e){const t=[];for(let s=0;s<e.length;s++){const r=e[s].part;if(!r)continue;const i=G(r);if(!h.has(i))continue;const o=P(await h.bytes(i));for(const l of N(o,"Relationship")){if(!/\/table$/.test(l.a.Type))continue;const n=C(r,l.a.Target);if(!h.has(n))continue;const m=await h.bytes(n),d=P(m),c=ie(d.a.ref??"");if(!c)continue;const f=T(d,"tableStyleInfo")?.a??{};t.push({id:Number(d.a.id),part:n,source:!0,styleName:M(f.name??null),showRowStripes:f.showRowStripes!=="0",showColumnStripes:f.showColumnStripes==="1",showFirstColumn:f.showFirstColumn==="1",showLastColumn:f.showLastColumn==="1",hasFilter:T(d,"autoFilter")!==void 0,fileFilter:_e(m),name:d.a.displayName??d.a.name,sheetIndex:s,...c,headerRows:d.a.headerRowCount!==void 0?Number(d.a.headerRowCount):1,totalsRows:Number(d.a.totalsRowCount??0),columns:N(T(d,"tableColumns"),"tableColumn").map(w=>M(w.a.name))})}}return t}async function ht(h,e){const t=await we(h),s=P(await t.bytes("_rels/.rels")),r=N(s,"Relationship").find(a=>/officeDocument$/.test(a.a.Type));if(!r)throw new Error("This file has no workbook part");const i=C("",r.a.Target),o=P(await t.bytes(i)),l=G(i),n=P(await t.bytes(l)),m=new Map,d=new Set,c=new Set;let f=null,w=null,y=null;for(const a of N(n,"Relationship")){const S=C(i,a.a.Target);m.set(a.a.Id,S),/\/chartsheet$/.test(a.a.Type)&&d.add(a.a.Id),/\/worksheet$/.test(a.a.Type)&&c.add(a.a.Id),/\/sharedStrings$/.test(a.a.Type)?f=S:/\/styles$/.test(a.a.Type)?w=S:/\/theme$/.test(a.a.Type)&&(y=S)}const u=N(T(o,"sheets"),"sheet").map(a=>({name:M(a.a.name),rid:a.a.id,part:m.get(a.a.id),hidden:a.a.state==="hidden"||a.a.state==="veryHidden",veryHidden:a.a.state==="veryHidden",sheetId:a.a.sheetId,chart:d.has(a.a.id)})),p=new Set(u.map(a=>a.part).filter(Boolean));for(const a of u){if(a.rid||!/^\d+$/.test(a.sheetId))continue;const S="rId"+a.sheetId,O=m.get(S),pe=C(i,`worksheets/sheet${a.sheetId}.xml`);c.has(S)&&O===pe&&t.has(O)&&!p.has(O)&&(a.rid=S,a.part=O,p.add(O))}const v=y&&t.has(y)?ee(await t.bytes(y)):ee(new TextEncoder().encode("<a/>")),g=w&&t.has(w)?ge(await t.bytes(w),v):[],I=Number(T(T(o,"bookViews"),"workbookView")?.a.activeTab??0),L=a=>/^Z_.*\.wvu\.[A-Za-z]+$/.test(a.a.name),A=N(T(o,"definedNames"),"definedName").filter(L).map(a=>({name:a.a.name,text:a.t,localSheetId:Number(a.a.localSheetId)})),D=N(T(o,"customWorkbookViews"),"customWorkbookView").map(a=>({...a.a})),X=N(T(o,"definedNames"),"definedName").filter(a=>a.a.name==="_xlnm.Criteria"||!a.a.name.startsWith("_xlnm.")&&!L(a)).map(a=>({name:a.a.name,text:a.t,localSheetId:a.a.localSheetId!==void 0?Number(a.a.localSheetId):void 0,hidden:a.a.hidden==="1"||void 0,comment:M(a.a.comment)})),he=N(T(o,"definedNames"),"definedName").filter(a=>a.a.name==="_xlnm.Print_Area"||a.a.name==="_xlnm.Print_Titles").map(a=>({name:a.a.name,text:a.t,localSheetId:Number(a.a.localSheetId)})),ce=N(T(o,"definedNames"),"definedName").filter(a=>a.a.name==="_xlnm._FilterDatabase"||a.a.name==="_xlnm.Criteria"||a.a.name==="_xlnm.Extract").map(a=>({name:a.a.name,text:a.t,localSheetId:Number(a.a.localSheetId)})),k=T(o,"calcPr")?.a??{},Y=["1","true"].includes(T(o,"workbookPr")?.a.date1904),de=N(T(o,"pivotCaches"),"pivotCache").reduce((a,S)=>Math.max(a,Number(S.a.cacheId??0)),0),J={};if(w&&t.has(w))for(const a of N(T(P(await t.bytes(w)),"numFmts"),"numFmt"))J[a.a.numFmtId]=a.a.formatCode;const fe=await Ge(t,u),me=w&&t.has(w)?Te(await t.bytes(w),a=>Z(a,v)):[];await e.meta({sheets:u,styles:g,activeTab:I,workbookPart:i,stringsPart:f,stylesPart:w,names:X,maxPivotCacheId:de,numFmts:J,date1904:Y,workbookProtection:T(o,"workbookProtection")?.a??null,fileSharing:T(o,"fileSharing")?.a??null,persons:await Ze(t,n,i),printNames:he,filterNames:ce,viewNames:A,customViews:D,tables:fe,theme:v,themeName:v.themeName,dxfs:me,fullCalcOnLoad:k.fullCalcOnLoad==="1"||k.fullCalcOnLoad==="true",manualCalc:k.calcMode==="manual",calcMode:k.calcMode??"auto",iterate:k.iterate==="1"||k.iterate==="true",iterateCount:k.iterateCount!==void 0?Number(k.iterateCount):100,iterateDelta:k.iterateDelta!==void 0?Number(k.iterateDelta):.001,externalLinks:await Ce(t,o,n,i,{child:T,children:N,resolveTarget:C})});const R=new $e(e);if(f&&t.has(f)){const a=new H(new De(R));await ne(await t.stream(f),S=>{if(a.feed(S),R.pending>=ae||R.len>=1<<22)return R.flush()})}await R.flush(),await e.stringsEnd?.(R.total);const K=new Map,ue={theme:v,date1904:Y,defaultHeight:16,nextBatch:()=>e.recycle?.()??He(),addString(a){let S=K.get(a);return S===void 0&&(R.appendText(a),S=R.finish(),K.set(a,S)),S},async sendCells(a,S){await R.flush(),await e.cells(a,S)}};let Q=0;for(let a=0;a<u.length;a++){if(u[a].chart){await e.sheetStart(a,{...W(""),head:"",chartSheet:!0}),await e.sheetEnd(a,{merges:[],tail:t.has(u[a].part)?new TextDecoder().decode(await t.bytes(u[a].part)):""});continue}if(!u[a].part||!t.has(u[a].part)){await e.sheetStart(a,{...W(""),head:""}),await e.sheetEnd(a,{merges:[],tail:""});continue}await We(t,u[a].part,a,ue,e),Q++}return{zip:t,sheets:u,workbookPart:i,wbRelsPath:l,stringsPart:f,stylesPart:w,sheetsRead:Q}}async function Ze(h,e,t){const s=e?N(e,"Relationship").find(i=>/\/person$/.test(i.a.Type)):null,r=s?C(t,s.a.Target):"xl/persons/person.xml";return h.has(r)?N(P(await h.bytes(r)),"person").map(i=>{const o=M(i.a.displayName);return{displayName:o,id:i.a.id,userId:i.a.userId??o,providerId:i.a.providerId??"None"}}):[]}export{F as BATCH_CELLS,ne as pump,lt as pxToWidth,ht as readXlsx,C as resolveTarget,le as widthToPx};
package/io/xlsx-write.js CHANGED
@@ -1,2 +1,2 @@
1
1
  import{ZipWriter as et}from"./zip-writer.js";import{splitPaneXml as tt}from"../cells/view-xml.js";import{setSheetPicture as st}from"../cells/background-xml.js";import{calcPrAnchor as ie,setIterationAttributes as ne}from"../calcx/external-read.js";import{writeThemePart as le}from"../api/style-refs.js";import{buildStylesXml as at,patchStylesXml as rt}from"./xlsx-styles.js";import{pxToWidth as ot,pump as it}from"./xlsx-read.js";import{relativeTarget as E,relsPathOf as V,resolveTarget as B}from"./package-paths.js";import{BOOL as ee,ERR as Z,ERRORS as nt,FORMULA as lt,KIND_MASK as ce,NUM as me,STR as te}from"../core/sheet.js";import{colName as de,MAX_COLS as ct,parseRangeRef as he,rangeRef as se}from"../core/address.js";import{adjustRange as mt}from"../calc/adjust.js";import{patchSparklines as dt}from"../core/sparklines.js";import{ensureDrawingElement as ht,mergeContentTypes as X}from"../objects/drawing-xml.js";import{applyControls as pt}from"../shapes/form-xml.js";import{relationshipsXml as ft}from"../pivot/xml.js";import{applySlicerSheet as ut,patchSlicerContentTypes as pe,patchSlicerWorkbook as fe,patchSlicerWorkbookRels as ue,removedSlicerParts as wt,writeSlicerParts as xt}from"../slicers/write.js";import{patchCustomStyles as we}from"../slicers/custom-styles.js";import{patchTableXml as gt}from"../core/tables.js";import{addCellTypeEntries as ae,dropCellTypeParts as $t}from"../celltypes/persist.js";import{dropQueryParts as bt}from"../extras/getdata/persist.js";import{richSiXml as yt}from"../cells/rich-xml.js";import{isRichError as xe}from"../cells/rich-data-xml.js";import{patchDataSheetContentTypes as ge,patchDataSheetWorkbookRels as $e,skipOldDataSheetParts as Pt,writeDataSheetParts as kt}from"../datasheets/persist-writer.js";import{patchChartSheetPageSetup as be,patchWorkbookPrintNames as ye,patchWorksheetHead as Tt,patchWorksheetTail as St}from"../print/page-setup.js";import{patchFilterNames as Pe,patchSheetProps as Rt}from"../cells/filter-file.js";import{patchCf as vt}from"../cells/cf-file.js";import{dxfXml as ke,hyperlinksXml as Ct,protectionXml as It,replaceElement as D,scenariosXml as Nt,validationsXml as Et}from"./xlsx-tail.js";import{patchCustomViews as At}from"../core/custom-views.js";import{escapeMarkup as T,xmlAttr as L,xmlText as K}from"./xml-escape.js";import{dropExternalReferences as Ot,patchExternalLinkParts as Dt}from"../calcx/external-write.js";import{applyKeptSheet as _t,clearKeptShapeIds as Vt,declareKeptNamespaces as jt,keptTableRels as zt,keptTableXml as Mt,planKeptParts as Xt,writeKeptParts as Lt}from"./foreign-sheets.js";const F=new TextEncoder,Bt=new TextDecoder,O=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
- `,q="http://schemas.openxmlformats.org/spreadsheetml/2006/main",A="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Ft="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",Ht="http://schemas.openxmlformats.org/markup-compatibility/2006",Wt="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac",Ut=6e7;class Kt{constructor(e){this.write=e,this.buf=new Uint8Array(1<<20),this.pos=0}async flush(){this.pos>0&&(await this.write(this.buf.subarray(0,this.pos)),this.pos=0)}async text(e){if(e.length*3+this.pos>this.buf.length&&(await this.flush(),e.length*3>this.buf.length)){await this.write(F.encode(e));return}this.pos+=F.encodeInto(e,this.buf.subarray(this.pos)).written}}const Te=[];function qt(t){let e=Te[t];return e===void 0&&(e=F.encode(de(t)),Te[t]=e),e}const _=t=>F.encode(t),Gt=_('<c r="'),Yt=_('" s="'),G=_('" t="'),Q=_('"><v>'),J=_("</v></c>"),Zt=_('"/>'),Se=_("</c>"),Re=_('">'),Qt=_('" cm="'),ve=_('" vm="');function S(t,e,s){for(let a=0;a<s.length;a++)t[e+a]=s[a];return e+s.length}function H(t,e,s){if(s<10)return t[e]=48+s,e+1;let a=0;for(let c=s;c>0;c=Math.floor(c/10))a++;for(let c=e+a-1,o=s;c>=e;c--){const l=Math.floor(o/10);t[c]=48+(o-l*10),o=l}return e+a}function Jt(t,e,s){if(Number.isInteger(s)&&Math.abs(s)<1e15)return s<0&&(t[e++]=45,s=-s),H(t,e,s);const a=String(s);for(let c=0;c<a.length;c++)t[e+c]=a.charCodeAt(c);return e+a.length}function Ce(t){if(t.raw!==void 0)return` ${t.raw}`;let e="";t.t&&(e+=` t="${t.t}"`),t.si!==void 0&&(e+=` si="${t.si}"`),t.ref&&(e+=` ref="${T(t.ref)}"`);for(const s of["dt2D","dtr","r1","r2","del1","del2"])t[s]!==void 0&&(e+=` ${s}="${T(t[s])}"`);return t.ca&&(e+=` ca="${t.ca}"`),e}const Ie=t=>xe(t)?"#VALUE!":nt[t];async function es(t,e,s){const{rows:a,cols:c,kinds:o,values:l,styles:p,count:f,formulas:w,valueMeta:b,rowMeta:d}=e,m=e.inlineText??null;let x=0,u=0,$=0;const g=d?d.length:0,R=async(h,r)=>{let n=`<row r="${h+1}"`;if($<g&&d[$]===h){const i=d[$+1];i>=0&&(n+=d[$+4]?` ht="${i}" customHeight="1"`:` ht="${i}"`),d[$+2]&&(n+=' hidden="1"'),d[$+3]&&(n+=` s="${d[$+3]}" customFormat="1"`),d[$+5]&&(n+=` ${d[$+5]}`),$+=6}await t.text(n+(r?">":"/>"))},j=async h=>{for(;$<g&&d[$]<h;)await R(d[$],!1)};let N=s.row;for(let h=0;h<f;h++){const r=a[h];r!==N&&(N>=0&&await t.text("</row>"),await j(r),await R(r,!0),N=r),t.pos+512>t.buf.length&&await t.flush();const n=t.buf;let i=S(n,t.pos,Gt);i=S(n,i,qt(c[h])),i=H(n,i,r+1);const k=p[h];k!==0&&(i=S(n,i,Yt),i=H(n,i,k)),b!==null&&u<b.length&&b[u][0]===h?(i=S(n,i,ve),i=H(n,i,b[u][1]),u++):(o[h]&ce)===Z&&s.errorVms&&xe(l[h])&&s.errorVms[l[h]]!==void 0&&(i=S(n,i,ve),i=H(n,i,s.errorVms[l[h]]));const C=o[h],y=C&ce,P=l[h];if(C&lt){const[z,M,Y]=w[x];if(z!==h)throw new Error("Formula list out of order");x++,M.cm&&(i=S(n,i,Qt),i=H(n,i,M.cm)),y===te?(i=S(n,i,G),n[i++]=115,n[i++]=116,n[i++]=114):y===ee?(i=S(n,i,G),n[i++]=98):y===Z&&(i=S(n,i,G),n[i++]=101),t.pos=S(n,i,Re);const v=M.f!==void 0?`<f${Ce(M)}>${T(M.f)}</f>`:`<f${Ce(M)}/>`;let I="";y===me?I=`<v>${P}</v>`:y===te?I=`<v>${K(Y??"")}</v>`:y===ee?I=`<v>${P}</v>`:y===Z&&(I=`<v>${Ie(P)}</v>`),await t.text(v+I),t.pos+8>t.buf.length&&await t.flush(),t.pos=S(t.buf,t.pos,Se);continue}switch(y){case me:i=S(n,i,Q),i=Jt(n,i,P),t.pos=S(n,i,J);break;case te:if(i=S(n,i,G),n[i++]=115,m!==null&&m.has(h)){n[i++]=116,n[i++]=114,t.pos=S(n,i,Re),await t.text(`<v>${K(m.get(h))}</v>`),t.pos+8>t.buf.length&&await t.flush(),t.pos=S(t.buf,t.pos,Se);continue}i=S(n,i,Q),i=H(n,i,P),t.pos=S(n,i,J);break;case ee:i=S(n,i,G),n[i++]=98,i=S(n,i,Q),i=H(n,i,P),t.pos=S(n,i,J);break;case Z:i=S(n,i,G),n[i++]=101,i=S(n,i,Q),i=S(n,i,_(Ie(P))),t.pos=S(n,i,J);break;default:t.pos=S(n,i,Zt)}}s.row=N,$<g&&(N>=0&&await t.text("</row>"),s.row=-1,await j(1/0))}const Ne=t=>t.startsWith("xl/chartsheets/"),Ee=t=>Ne(t)?ts:Ft,ts="application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml";async function ss(t,e,s,a,c,o,l,p,f){const w=await Ae("</worksheet>",e,s,a,o,p),b=a===c.activeSheet||e.tabSelected===!0;if(l){const d=await o.zip.text(s);let m=d;if(/\btabSelected="(?:1|true)"/.test(d)!==b&&(m=m.replace(/<sheetView\b[^>]*>/,x=>{const u=x.replace(/\s+tabSelected="[^"]*"/,"");return b?u.replace("<sheetView",'<sheetView tabSelected="1"'):u})),e.pageSetup&&(m=be(m,e.pageSetup)),m===d)return;await t.addBytes(s,new TextEncoder().encode(m))}else{let d=`${O}<chartsheet xmlns="${q}" xmlns:r="${A}"><sheetPr/><sheetViews><sheetView${b?' tabSelected="1"':""} workbookViewId="0" zoomToFit="1"/></sheetViews><pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>${w.replace("</worksheet>","</chartsheet>")}`;e.pageSetup&&(d=be(d,e.pageSetup)),await t.addBytes(s,new TextEncoder().encode(d))}f.add(s)}async function Ae(t,e,s,a,c,o){let l=t;e.cf!==null&&e.cf!==void 0&&(l=vt(l,e.cf,D)),e.validations!==null&&e.validations!==void 0&&(l=D(l,"dataValidations",Et(e.validations))),e.sparklines!==null&&e.sparklines!==void 0&&(l=dt(l,e.sparklines)),e.scenarios!==null&&e.scenarios!==void 0&&(l=D(l,"scenarios",Nt(e.scenarios))),e.dataConsolidate!==null&&e.dataConsolidate!==void 0&&(l=D(l,"dataConsolidate",e.dataConsolidate)),e.customSheetViews!==null&&e.customSheetViews!==void 0&&(l=D(l,"customSheetViews",e.customSheetViews)),e.protection!==null&&e.protection!==void 0&&(l=D(l,"sheetProtection",It(e.protection))),e.ignoredErrors!==null&&e.ignoredErrors!==void 0&&(l=D(l,"ignoredErrors",e.ignoredErrors));const p=V(s);e.sheetPicture&&(l=st(l,e.sheetPicture),e.sheetPicture.path&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${e.sheetPicture.rid}"`)||(o.rels.has(p)||o.rels.set(p,[]),o.rels.get(p).push(`<Relationship Id="${e.sheetPicture.rid}" Type="${A}/image" Target="${T(E(s,e.sheetPicture.path))}"/>`)))),e.headerPicture&&(l=D(l,"legacyDrawingHF",e.headerPicture.rid?`<legacyDrawingHF r:id="${e.headerPicture.rid}"/>`:""),e.headerPicture.rid&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${e.headerPicture.rid}"`)||(o.rels.has(p)||o.rels.set(p,[]),o.rels.get(p).push(`<Relationship Id="${e.headerPicture.rid}" Type="${A}/vmlDrawing" Target="${T(E(s,e.headerPicture.vml))}"/>`))));for(const m of o.plan.removedTableRids?.[a]??[])l=l.replace(new RegExp(`<tablePart\\b[^>]*r:id="${m}"[^>]*/>`),"");if(o.plan.removedTableRids?.[a]){const m=(l.match(/<tablePart\b/g)??[]).length;l=m===0?l.replace(/<tableParts\b[^>]*\/>|<tableParts\b[^>]*>\s*<\/tableParts>/,""):l.replace(/(<tableParts\b[^>]*\bcount=")\d+/,`$1${m}`)}const f=(o.plan.tables??[]).filter(m=>m.isNew&&m.sheetIndex===a),w=(m,x,u,$)=>{o.rels.has(p)||o.rels.set(p,[]);const g=x==="threadedCommentExternal"?bs:`${A}/${x}`;o.rels.get(p).push(`<Relationship Id="${m}" Type="${g}" Target="${T(u)}"${$?' TargetMode="External"':""}/>`)};if(f.length>0){const m=[...l.matchAll(/<tablePart\b[^>]*\/>/g)].map($=>$[0]),x=f.map(($,g)=>{const R=`rIdTable${a}_${g}`;return w(R,"table",E(s,$.part),!1),`<tablePart r:id="${R}"/>`}),u=[...m,...x];l=D(l,"tableParts",`<tableParts count="${u.length}">${u.join("")}</tableParts>`)}if(e.hyperlinks!==null&&e.hyperlinks!==void 0){const m=e.hyperlinks.map((x,u)=>{if(x.rid||!x.target)return x;const $=`rIdLink${a}_${u}`;return w($,"hyperlink",x.target,!0),{...x,rid:$}});l=D(l,"hyperlinks",Ct(m))}if(e.threads){const m=o.plan.threadParts?.[a];m&&(o.parts.push({path:m.path,xml:ks(e.threads)}),m.existing||w(`rIdThreads${a+1}`,"threadedCommentExternal",E(s,m.path),!1))}const b=o.plan.noteParts?.[a];if(b&&e.comments){if(b.existing)o.parts.push({path:b.comments,xml:Oe(e.comments)}),b.vml&&o.parts.push({path:b.vml,xml:_e(b.vmlSource,e.comments)}),b.threaded&&o.parts.push({path:b.threaded,xml:Le(b.threadedSource,e.structureOps??[])});else if(e.comments.length>0){const{comments:m,vml:x,n:u}=b;o.parts.push({path:m,xml:Oe(e.comments)}),w(`rIdComments${u}`,"comments",E(s,m),!1);const $=/<legacyDrawing\b[^>]*r:id="([^"]+)"/.exec(l)?.[1],g=$&&c?.zip.has(p)?await c.zip.text(p):"",R=g?[...g.matchAll(/<Relationship\b[^>]*\/>/g)].map(h=>h[0]).find(h=>h.includes(`Id="${$}"`)):null,j=R?/Target="([^"]+)"/.exec(R)?.[1]:null,N=j?B(s,j):null;N&&c.zip.has(N)?o.parts.push({path:N,xml:_e(await c.zip.text(N),e.comments)}):(o.parts.push({path:x,xml:as(e.comments)}),w(`rIdVml${u}`,"vmlDrawing",E(s,x),!1),l=D(l,"legacyDrawing",`<legacyDrawing r:id="rIdVml${u}"/>`))}}const d=e.objects;if(d){o.parts.push({path:d.path,xml:d.xml}),d.relsXml&&o.parts.push({path:d.relsPath,xml:d.relsXml});for(const m of d.parts)o.parts.push({path:m.path,xml:m.data instanceof Blob?new Uint8Array(await m.data.arrayBuffer()):m.data});d.isNew&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${d.sheetRel.id}"`)||w(d.sheetRel.id,"drawing",d.sheetRel.target,!1),l=ht(l,d.sheetDrawingXml)),d.controls&&(o.rels.has(p)||o.rels.set(p,[]),l=await pt(l,d.controls,{source:c,part:s,relsName:p,addRel:w,extraParts:o.parts,pendingRels:o.rels.get(p),relativeTo:E,resolveTarget:B}))}return ut({tail:l,index:a,info:e,source:c,extra:o,relsName:p})}function Oe(t){const e=[...new Set(t.map(s=>s.author||"Author"))];return`${O}<comments xmlns="${q}"><authors>${e.map(s=>`<author>${K(s)}</author>`).join("")}</authors><commentList>${t.map(s=>`<comment ref="${s.ref}" authorId="${e.indexOf(s.author||"Author")}"><text>${ps(s,K)}</text></comment>`).join("")}</commentList></comments>`}function De(t,e=1025){return t.map((s,a)=>hs(s,e+a,a+1,he(s.ref))).join("")}function _e(t,e){const s=t.replace(/<v:shape\b(?:(?!<\/v:shape>)[\s\S])*?ObjectType="Note"[\s\S]*?<\/v:shape>/g,"");let a=1024;for(const c of s.matchAll(/_x0000_s(\d+)/g))a=Math.max(a,Number(c[1]));return s.replace("</xml>",`${De(e,a+1)}</xml>`)}function as(t){return`<xml xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1"/></o:shapelayout><v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter"/><v:path gradientshapeok="t" o:connecttype="rect"/></v:shapetype>${De(t)}</xml>`}function Ve(t){return!t||t.length===0?"":`<cols>${t.map(s=>{let a=`<col min="${s.min+1}" max="${s.max+1}" width="${ot(s.px)}"`;return s.custom&&(a+=' customWidth="1"'),s.hidden&&(a+=' hidden="1"'),s.style&&(a+=` style="${s.style}"`),s.extra&&(a+=` ${s.extra}`),a+"/>"}).join("")}</cols>`}function je(t,e){const s=cs(t,e);let a="";if(t.frozenRows||t.frozenCols){const c=t.frozenRows&&t.frozenCols?"bottomRight":t.frozenRows?"bottomLeft":"topRight",o=(t.frozenCols?` xSplit="${t.frozenCols}"`:"")+(t.frozenRows?` ySplit="${t.frozenRows}"`:""),l=de(t.frozenCols)+(t.frozenRows+1);a=`<pane${o} topLeftCell="${l}" activePane="${c}" state="frozen"/>`}else t.split&&(a=tt(t));return`<sheetViews><sheetView${s} workbookViewId="0">${a}</sheetView></sheetViews>`}function ze(t){return t.maxRow<0||t.maxCol<0?"A1":se({r0:0,c0:0,r1:t.maxRow,c1:t.maxCol})}function rs(t,e){const s=t.tabColor?`<sheetPr><tabColor rgb="FF${t.tabColor.slice(1)}"/></sheetPr>`:"";return`${O}<worksheet xmlns="${q}" xmlns:r="${A}" xmlns:mc="${Ht}" mc:Ignorable="x14ac" xmlns:x14ac="${Wt}">${s}<dimension ref="${ze(t)}"/>${je(t,e)}<sheetFormatPr baseColWidth="10" defaultRowHeight="${t.defaultHeight}"/>${Ve(t.cols)}`}function os(t,e){let s=t;if(e.tabColor!==null&&e.tabColor!==void 0&&(s=s.replace(/<tabColor\b[^>]*\/>/,""),e.tabColor)){const c=`<tabColor rgb="FF${e.tabColor.slice(1)}"/>`;/<sheetPr\b[^>]*\/>/.test(s)?s=s.replace(/<sheetPr\b([^>]*)\/>/,`<sheetPr$1>${c}</sheetPr>`):/<sheetPr\b[^>]*>/.test(s)?s=s.replace(/(<sheetPr\b[^>]*>)/,`$1${c}`):s=s.replace(/(<worksheet\b[^>]*>)/,`$1<sheetPr>${c}</sheetPr>`)}const a=`<dimension ref="${ze(e)}"/>`;if(/<dimension\b[^>]*\/>/.test(s)&&(s=s.replace(/<dimension\b[^>]*\/>/,a)),e.viewChanged?/<sheetViews\b[\s\S]*<\/sheetViews>/.test(s)&&(s=s.replace(/<sheetViews\b[\s\S]*<\/sheetViews>/,je(e,e.tabSelected))):s=ls(s,e),e.defaultsChanged&&(s=s.replace(/(<sheetFormatPr\b[^>]*?\bdefaultRowHeight=")[^"]*"/,`$1${e.defaultHeight}"`)),e.colsChanged){const c=Ve(e.cols);/<cols\b[\s\S]*<\/cols>/.test(s)?s=s.replace(/<cols\b[\s\S]*<\/cols>/,c):s+=c}return s}import{bookViewsXml as is,patchBookViews as ns,patchTabSelected as ls,sheetViewAttrs as cs}from"../cells/view-xml.js";import{docPropsRels as ms,docPropsTypes as Me,writeDocProps as ds}from"../cells/docprops-xml.js";import{noteShapeXml as hs,noteTextXml as ps}from"../cells/note-xml.js";const fs=/<(phoneticPr|conditionalFormatting|dataValidations|hyperlinks|printOptions|pageMargins|pageSetup|headerFooter|rowBreaks|colBreaks|customProperties|cellWatches|ignoredErrors|smartTags|drawing|legacyDrawing|legacyDrawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst)\b|<\/worksheet>/;function Xe(t){return t.length===0?"":`<mergeCells count="${t.length}">${t.map(e=>`<mergeCell ref="${se(e)}"/>`).join("")}</mergeCells>`}function Le(t,e){return e.length===0?t:t.replace(/\b(sqref|ref)="([^"]*)"/g,(s,a,c)=>{const o=c.split(/\s+/).map(p=>{let f=he(p);if(f===null)return null;for(const w of e){if(f===null)break;f=mt(f,w)}return f===null?"":se(f)});if(o.includes(null))return s;const l=o.filter(p=>p!=="");return l.length?`${a}="${l.join(" ")}"`:`${a}="A1048576"`})}function us(t,e,s=[]){t=Le(t,s);const a=Xe(e),c=/<mergeCells\b[\s\S]*?<\/mergeCells>/;if(c.test(t))return t.replace(c,a);if(!a)return t;const o=fs.exec(t);return o?t.slice(0,o.index)+a+t.slice(o.index):t+a}const ws=new TextDecoder("latin1");async function xs(t,e,s,a){let o=new Uint8Array(0),l=!0;await it(await e.stream(s),async b=>{let d=b;if(l){l=!1;const m=Bt.decode(d.subarray(0,Math.min(d.length,512))),x=/<sst\b[^>]*>/.exec(m);if(x){const u=x[0].replace(/\s(count|uniqueCount)="\d+"/g,""),$=F.encode(m.slice(0,x.index)+u),g=F.encode(m.slice(0,x.index+x[0].length)).length;await t($),d=d.subarray(g)}}if(d.length>=16)o.length&&await t(o),await t(d.subarray(0,d.length-16)),o=d.slice(d.length-16);else{const m=new Uint8Array(o.length+d.length);m.set(o),m.set(d,o.length),o=m}});const p=ws.decode(o),f=F.encode(a),w=p.lastIndexOf("</sst>");w>=0?(await t(o.subarray(0,w)),await t(f),await t(o.subarray(w))):p.endsWith("/>")?(await t(o.subarray(0,o.length-2)),await t(F.encode(`>${a}</sst>`))):(await t(o),await t(f))}const W="xl/metadata.xml",Be="application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",Fe=`${O}<metadata xmlns="${q}" xmlns:xda="http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray"><metadataTypes count="1"><metadataType name="XLDAPR" minSupportedVersion="120000" copy="1" pasteAll="1" pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1" clearComments="1" assign="1" coerce="1" cellMeta="1"/></metadataTypes><futureMetadata name="XLDAPR" count="1"><bk><extLst><ext uri="{bdbb8cdc-fa1e-496e-a857-3c3f30c029c3}"><xda:dynamicArrayProperties fDynamic="1" fCollapsed="0"/></ext></extLst></bk></futureMetadata><cellMetadata count="1"><bk><rc t="1" v="0"/></bk></cellMetadata></metadata>`,gs=(t,e)=>e?yt(t,e,K):`<si><t xml:space="preserve">${K(t)}</t></si>`;async function pa(t,e,s,a=null,c=null){const o=new et(t),l=[],p=new Set;a&&e.dataSheets&&Pt(a.zip,p,e.dataSheets);for(const r of e.sheets)if(r.objects)for(const n of r.objects.removedParts)p.add(n);const f=e.pivots??null,w=new Set([...e.sheets.flatMap(r=>(r.objects?.removedParts??[]).filter(n=>n.startsWith("xl/ctrlProps/"))),...f?.replaced??[],...wt(e),...(e.removedTables??[]).map(r=>r.part)]);for(const r of w)p.add(r),p.add(V(r));e.sheetRefs=e.sheets.map((r,n)=>({rid:`rId${n+1}`,sheetId:n+1})),e.written=[];const b=new Set(a?a.sheets.map(r=>r.part):[]),d=new Set(e.sheets.filter(r=>r.sourceIndex>=0).map(r=>a.sheets[r.sourceIndex].part)),m=new Set(a?a.sheets.map(r=>r.part).filter(r=>!d.has(r)):[]);let x=1;const u=e.sheets.map(r=>{if(r.sourceIndex>=0)return a.sheets[r.sourceIndex].part;let n;do n=`xl/${r.chartSheet?"chartsheets":"worksheets"}/sheet${x++}.xml`;while(b.has(n));return b.add(n),l.push(n),n}),$=a?.stringsPart??"xl/sharedStrings.xml",g=a?.stylesPart??"xl/styles.xml";e.noteParts=await $s(e,u,a),{threads:e.threadParts,personPart:e.personPart}=await Ss(e,u,a);let R=null;if(a)await Rs(o,a,e,u,l,$,g,p);else{let r=vs(u,e.dynamicArrays,e);for(const P of e.sheets)P.objects&&(r=X(r,P.objects.contentTypes,P.objects.removedOverrides));f&&(r=X(r,f.contentTypes,[])),r=pe(r,e),r=X(r,We(e),[]),{types:r}=ae(r,"</Relationships>",e.cellTypes),r=Me(r,e.docProps),e.dataSheets&&(r=ge(r,e.dataSheets));let n=null;e.themeXml&&({types:r,rels:n}=await le(o,{types:r,rels:"</Relationships>"},e.themeXml));const i=c?.plan??null;i&&(r=X(r,[...i.overrides,...i.defaults],[])),R=Xt(i,e),R&&(r=X(r,R.types,[])),r=Ye(r,e.workbookType),i?.macro&&(r=r.replace(/application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)\.main\+xml/,Cs)),await o.addBytes("[Content_Types].xml",r);const k=(i?.rootRels??[]).map((P,z)=>`<Relationship Id="rIdForeign${z+1}" Type="${T(P.type)}" Target="${T(P.target)}"/>`).join("");await o.addBytes("_rels/.rels",`${O}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${A}/officeDocument" Target="xl/workbook.xml"/>${ms(e.docProps)}${k}</Relationships>`);let C=Ge(ne(Ke(Ze(Is(Es(e),i?.codeNames.workbook),e.workbookProtection),e.calcMode),e.calcSettings),e.fileSharing),y=ae("</Types>",As(u,e.dynamicArrays),e.cellTypes).rels;n&&(y=y.replace("</Relationships>",n)),e.personPart&&(y=y.replace("</Relationships>",`<Relationship Id="rIdPersons" Type="${He}" Target="${E("xl/workbook.xml",e.personPart.path)}"/></Relationships>`)),f&&(y=y.replace("</Relationships>",`${Qe(f)}</Relationships>`),C=Je(C,f)),y=ue(y,e),await o.addBytes("xl/workbook.xml",fe(C,e)),e.dataSheets&&(y=$e(y,e.dataSheets)),i?.workbookRels.length&&(y=y.replace("</Relationships>",`${i.workbookRels.map((P,z)=>`<Relationship Id="rIdForeign${z+1}" Type="${T(P.type)}" Target="${T(E("xl/workbook.xml",P.target))}"/>`).join("")}</Relationships>`)),await o.addBytes("xl/_rels/workbook.xml.rels",y),e.dynamicArrays&&await o.addBytes(W,Fe),await o.addBytes(g,we(at(e.styles,(e.newDxfs??[]).map(ke),e),e.customStyles))}const j=e.extraRich?new Map(e.extraRich):null,N=e.extraStrings.map((r,n)=>gs(r,j?.get(n))).join("");a?.stringsPart&&a.zip.has(a.stringsPart)?await o.add($,r=>xs(r,a.zip,a.stringsPart,N)):await o.addBytes($,`${O}<sst xmlns="${q}">${N}</sst>`),p.add($);const h={rels:new Map,parts:[],next:1,plan:e};if(e.removedTableRids={},a&&(e.removedTables??[]).length>0)for(const r of e.removedTables){const n=V(u[r.sheetIndex]);if(!a.zip.has(n))continue;const i=await a.zip.text(n);for(const k of i.matchAll(/<Relationship\b[^>]*\/>/g)){const C=/\bTarget="([^"]+)"/.exec(k[0])?.[1],y=/\bId="([^"]+)"/.exec(k[0])?.[1];C&&y&&B(u[r.sheetIndex],C)===r.part&&(e.removedTableRids[r.sheetIndex]??=[]).push(y)}h.rels.has(n)||h.rels.set(n,[])}for(let r=0;r<e.sheets.length;r++){const n=e.sheets[r],i=n.sourceIndex>=0?a.sheets[n.sourceIndex]:null;if(n.chartSheet){await ss(o,n,u[r],r,e,a,i,h,p),e.written[r]={head:"",tail:""},e.onSheetDone?.(r);continue}p.add(u[r]);const k=n.cellEstimate>Ut;await o.add(u[r],async C=>{const y=new Kt(C);let P=i?.head?os(i.head,n):rs(n,r===e.activeSheet||n.tabSelected===!0);P=Rt(P,n.sheetProps),!i&&c?.plan.codeNames.sheets[n.name]&&(P=Ns(P,c.plan.codeNames.sheets[n.name])),n.pageSetup&&(P=Tt(P,n.pageSetup));const z=i?null:R?.sheets.get(r);z&&(P=jt(P,z),Vt(n.objects,z)),e.written[r]={head:P},await y.text(P),await y.text("<sheetData>");const M={row:-1,errorVms:e.errorVms??null};for(let I=0;I>=0;){const U=await s.block(r,I);await es(y,U,M),I=U.nextRow,s.recycle?.(U)}M.row>=0&&await y.text("</row>"),await y.text("</sheetData>");const Y=n.autoFilter??"";let v=i?us(i.tail??"</worksheet>",n.merges,n.structureOps??[]):`${Y}${Xe(n.merges)}</worksheet>`;if(!i&&!/xmlns:r=/.test(v)&&(v=`${v}`),i&&n.autoFilter!==null&&n.autoFilter!==void 0){v=v.replace(/<autoFilter\b[^>]*?(?:\/>|>[\s\S]*?<\/autoFilter>)/,"").replace(/<sortState\b[^>]*?(?:\/>|>[\s\S]*?<\/sortState>)/,"");const I=/<mergeCells\b|<(?:sortState|dataConsolidate|customSheetViews|phoneticPr|conditionalFormatting|dataValidations|hyperlinks|printOptions|pageMargins|pageSetup|headerFooter|rowBreaks|colBreaks|customProperties|cellWatches|ignoredErrors|smartTags|drawing|legacyDrawing|legacyDrawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst)\b|<\/worksheet>/.exec(v);v=I?v.slice(0,I.index)+Y+v.slice(I.index):v+Y}if(v=await Ae(v,n,u[r],r,a,h),n.pageSetup&&(v=St(v,n.pageSetup)),!i){v=v.replace(/(<pageSetup\b[^>]*?)\sr:id="[^"]*"/,"$1");const I=R?.sheets.get(r);if(I){const U=V(u[r]);h.rels.has(U)||h.rels.set(U,[]),v=await _t(v,{group:I,part:u[r],pending:h.rels.get(U),extraParts:h.parts,foreignZip:c.zip,names:R.names,kept:R.kept})}}e.written[r].tail=v,await y.text(v),await y.flush()},{large:k}),e.onSheetDone?.(r)}if(f){for(const i of f.parts)await o.addBytes(i.name,i.xml),p.add(i.name);const r=new Map;let n=0;for(const i of f.relationships)if(i.from!==null)r.has(i.from)||r.set(i.from,[]),r.get(i.from).push(i);else if(i.sheetIndex>=0){const k=V(u[i.sheetIndex]);h.rels.has(k)||h.rels.set(k,[]),h.rels.get(k).push(`<Relationship Id="rIdPivot${++n}" Type="${i.type}" Target="${T(i.target)}"/>`)}for(const[i,k]of r){const C=V(i);await o.addBytes(C,ft(k)),p.add(C)}for(const i of u){const k=V(i);a?.zip.has(k)&&!h.rels.has(k)&&h.rels.set(k,[])}}if(e.slicers?.removedParts.length)for(const r of u){const n=V(r);a?.zip.has(n)&&!h.rels.has(n)&&h.rels.set(n,[])}await xt(o,e,p);for(const r of e.tables??[]){let n=r.xml;n===null&&(n=gt(await a.zip.text(r.part),r.patch));const i=R?.tables.get(r.part);if(i){n=Mt(n,i);const k=zt(r.part,i,R.names);await o.addBytes(k.path,k.xml),p.add(k.path)}await o.addBytes(r.part,n),p.add(r.part)}for(const r of e.cellTypes??[])await o.addBytes(r.path,r.xml),p.add(r.path);e.personPart&&(await o.addBytes(e.personPart.path,Ts(e.persons)),p.add(e.personPart.path));for(const r of h.parts)await o.addBytes(r.path,r.xml),p.add(r.path);for(const[r,n]of h.rels){let i=a?.zip.has(r)?await a.zip.text(r):`${O}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>`;if(w.size>0){const C=r.replace("_rels/","").replace(/\.rels$/,"");i=oe(i,C,w)}const k=i.replace("</Relationships>",`${n.join("")}</Relationships>`);await o.addBytes(r,k),p.add(r)}if(await ds(o,a?.zip??null,e.docProps,p),await kt(o,e.dataSheets,p),a)for(const[r,n]of a.zip.entries)p.has(r)||r===a.calcChainPart||m.has(r)||await o.copyRaw(a.zip,n);if(!a&&c){const r=new Set(o.central.map(n=>n.name));for(const n of c.plan.entries){const i=c.zip.entries.get(n);i&&!r.has(n)&&await o.copyRaw(c.zip,i)}R&&await Lt(o,R,c.zip,r)}await o.finish(),e.result={sheets:e.sheets.map((r,n)=>({name:r.name,part:u[n],rid:e.sheetRefs[n].rid,sheetId:e.sheetRefs[n].sheetId,hidden:r.hidden,veryHidden:r.veryHidden,head:e.written[n].head,tail:e.written[n].tail})),workbookPart:a?.workbookPart??"xl/workbook.xml",wbRelsPath:a?.wbRelsPath??"xl/_rels/workbook.xml.rels",stringsPart:$,stylesPart:g}}async function $s(t,e,s){const a={};let c=1;for(let o=0;o<t.sheets.length;o++){const l=t.sheets[o];if(!l.comments)continue;const p=V(e[o]);if(s?.zip.has(p)&&l.sourceIndex>=0){const f=await s.zip.text(p),w=d=>{const m=[...f.matchAll(/<Relationship\b[^>]*\/>/g)].map(u=>u[0]).find(u=>new RegExp(`\\bType="[^"]*/${d}"`).test(u)),x=m&&/\bTarget="([^"]+)"/.exec(m)?.[1];return x?B(e[o],x):null},b=w("comments");if(b){const d=w("vmlDrawing"),m=w("threadedComment");a[o]={existing:!0,comments:b,vml:d,vmlSource:d?await s.zip.text(d):null,threaded:m,threadedSource:m?await s.zip.text(m):null};continue}}if(l.comments.length!==0){for(;s?.zip.has(`xl/comments${100+c}.xml`)||s?.zip.has(`xl/drawings/vmlDrawing${100+c}.vml`);)c++;a[o]={existing:!1,comments:`xl/comments${100+c}.xml`,vml:`xl/drawings/vmlDrawing${100+c}.vml`,n:c},c++}}return a}const bs="http://schemas.microsoft.com/office/2017/10/relationships/threadedComment",He="http://schemas.microsoft.com/office/2017/10/relationships/person",ys="application/vnd.ms-excel.threadedcomments+xml",Ps="application/vnd.ms-excel.person+xml";function ks(t){const e=t.map(s=>`<threadedComment ref="${s.ref}" dT="${T(s.date)}" personId="${T(s.personId)}" id="${T(s.id)}"${s.parentId?` parentId="${T(s.parentId)}"`:""}${s.done?' done="1"':""}><text>${K(s.text)}</text>${s.mentions?.length?`<mentions>${s.mentions.map(a=>`<mention mentionpersonId="${T(a.personId)}" mentionId="${T(a.id??s.id.replace(/^.{9}/,`{${String(a.start).padStart(8,"0")}`))}" startIndex="${a.start}" length="${a.length}"/>`).join("")}</mentions>`:""}</threadedComment>`).join("");return`${O}<ThreadedComments xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">${e}</ThreadedComments>`}function Ts(t){const e=t.map(s=>`<person displayName="${L(s.displayName)}" id="${T(s.id)}" userId="${T(s.userId)}" providerId="${T(s.providerId)}"/>`).join("");return`${O}<personList xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">${e}</personList>`}async function Ss(t,e,s){const a={};let c=1;for(let l=0;l<t.sheets.length;l++){const p=t.sheets[l];if(!p.threads)continue;const f=V(e[l]);let w=null;if(s?.zip.has(f)&&p.sourceIndex>=0){const d=[...(await s.zip.text(f)).matchAll(/<Relationship\b[^>]*\/>/g)].map(x=>x[0]).find(x=>/\/threadedComment"/.test(x)),m=d&&/\bTarget="([^"]+)"/.exec(d)?.[1];m&&(w=B(e[l],m))}if(w){a[l]={path:w,existing:!0};continue}if(p.threads.length!==0){for(;s?.zip.has(`xl/threadedComments/threadedComment${100+c}.xml`);)c++;a[l]={path:`xl/threadedComments/threadedComment${100+c}.xml`,existing:!1},c++}}let o=null;if(t.persons){let l=null;if(s?.zip.has(s.wbRelsPath)){const f=[...(await s.zip.text(s.wbRelsPath)).matchAll(/<Relationship\b[^>]*\/>/g)].map(b=>b[0]).find(b=>/\/person"/.test(b)),w=f&&/\bTarget="([^"]+)"/.exec(f)?.[1];w&&(l=B(s.workbookPart,w))}o=l?{path:l,existing:!0}:{path:"xl/persons/person.xml",existing:!1}}return{threads:a,personPart:o}}const We=t=>[...Object.values(t.threadParts??{}).filter(e=>!e.existing).map(e=>({partName:`/${e.path}`,contentType:ys})),...t.personPart&&!t.personPart.existing?[{partName:`/${t.personPart.path}`,contentType:Ps}]:[]],Ue="application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",re=t=>Object.values(t.noteParts??{}).filter(e=>!e.existing);function Ke(t,e){if(e==null)return t;const s=e==="auto"?"":` calcMode="${e}"`;if(/<calcPr\b/.test(t))return t.replace(/<calcPr\b([^>]*?)\/>/,(c,o)=>`<calcPr${o.replace(/\s*calcMode="[^"]*"/,"")}${s}/>`);if(!s)return t;const a=ie(t);return t.replace(a,`${a}<calcPr${s}/>`)}const qe=(t,e)=>e.customViews?At(t,e.customViews.workbookXml,e.customViews.names):t;function Ge(t,e){if(e==null)return t;const s=t.replace(/<fileSharing\b[^>]*\/>/,""),a=Object.keys(e).filter(f=>e[f]!==void 0&&e[f]!==null&&e[f]!=="");if(a.length===0)return s;const c=`<fileSharing ${a.map(f=>`${f}="${T(e[f])}"`).join(" ")}/>`,o=/<fileVersion\b[^>]*\/>/.exec(s),l=/<workbook\b[^>]*>/.exec(s),p=o?o.index+o[0].length:l.index+l[0].length;return s.slice(0,p)+c+s.slice(p)}function Ye(t,e){if(!e)return t;const s=e==="template"?"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":e==="macro"?"application/vnd.ms-excel.sheet.macroEnabled.main+xml":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",a=e==="workbook"?/application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)\.main\+xml/:/application\/vnd\.(?:openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)|ms-excel\.sheet\.macroEnabled)\.main\+xml/;return t.replace(a,s)}function Ze(t,e){if(e==null)return t;const s=t.replace(/<workbookProtection\b[^>]*\/>/,""),a=Object.keys(e);if(a.length===0)return s;const c=`<workbookProtection ${a.map(l=>`${l}="${T(e[l])}"`).join(" ")}/>`,o=/<bookViews\b|<sheets\b/.exec(s);return s.slice(0,o.index)+c+s.slice(o.index)}const Qe=t=>t.caches.map(e=>`<Relationship Id="${e.relId}" Type="${e.type}" Target="${T(e.target)}"/>`).join("");function oe(t,e,s){return t.replace(/<Relationship\b[^>]*\/>/g,a=>{const c=/\bTarget="([^"]+)"/.exec(a);return c&&s.has(B(e,c[1]))?"":a})}function Je(t,e,s=null){let a="";const c=/<pivotCaches\b[^>]*>([\s\S]*?)<\/pivotCaches>/.exec(t);c&&s&&(a=[...c[1].matchAll(/<pivotCache\b[^>]*\/>/g)].map(w=>w[0]).filter(w=>s.has(/r:id="([^"]+)"/.exec(w)?.[1])).join(""));const o=e.caches.map(w=>`<pivotCache cacheId="${w.cacheId}" r:id="${w.relId}"/>`).join(""),l=t.replace(/<pivotCaches\b[^>]*>[\s\S]*?<\/pivotCaches>/,""),p=a||o?`<pivotCaches>${a}${o}</pivotCaches>`:"";if(!p)return l;const f=/<(?:smartTagPr|smartTagTypes|webPublishing|fileRecoveryPr|webPublishObjects|extLst)\b|<\/workbook>/.exec(l);return f?l.slice(0,f.index)+p+l.slice(f.index):l+p}async function Rs(t,e,s,a,c,o,l,p){const f=e.zip,w=await f.text(e.wbRelsPath);let b=null,d=w.replace(/<Relationship\b[^>]*calcChain[^>]*\/>/g,h=>{const r=/Target="([^"]+)"/.exec(h);return r&&(b=B(e.workbookPart,r[1])),""});e.calcChainPart=b;let m=await f.text("[Content_Types].xml");m=m.replace(/<Override\b[^>]*calcChain[^>]*\/>/g,"");const x=c.map(h=>`<Override PartName="/${h}" ContentType="${Ee(h)}"/>`);if(f.has(o)||(x.push(`<Override PartName="/${o}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>`),d=d.replace("</Relationships>",`<Relationship Id="rIdStrings" Type="${A}/sharedStrings" Target="${E(e.workbookPart,o)}"/></Relationships>`)),re(s).length>0){/Extension="vml"/.test(m)||(m=m.replace(/(<Types\b[^>]*>)/,'$1<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>'));for(const h of re(s))x.push(`<Override PartName="/${h.comments}" ContentType="${Ue}"/>`)}s.dynamicArrays&&!f.has(W)&&(x.push(`<Override PartName="/${W}" ContentType="${Be}"/>`),d=d.replace("</Relationships>",`<Relationship Id="rIdMetadata" Type="${A}/sheetMetadata" Target="${E(e.workbookPart,W)}"/></Relationships>`),await t.addBytes(W,Fe),p.add(W)),s.dynamicArrays&&f.has(W);for(const h of s.tables??[])h.isNew&&x.push(`<Override PartName="/${h.part}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/>`);m=m.replace("</Types>",`${x.join("")}</Types>`);for(const h of s.sheets)h.objects&&(m=X(m,h.objects.contentTypes,h.objects.removedOverrides));m=X(m,We(s),[]),s.personPart&&!s.personPart.existing&&(d=d.replace("</Relationships>",`<Relationship Id="rIdPersons" Type="${He}" Target="${E(e.workbookPart,s.personPart.path)}"/></Relationships>`)),s.dataSheets&&(m=ge(m,s.dataSheets),d=$e(d,s.dataSheets)),{types:m,rels:d}=await $t(f,m,d,p),{types:m,rels:d}=await bt(f,m,d,p),{types:m,rels:d}=ae(m,d,s.cellTypes,e.workbookPart),m=Me(m,s.docProps);const u=s.pivots??null;m=X(m,[],[...u?.replaced??[],...(s.removedTables??[]).map(h=>h.part)].map(h=>`/${h}`)),m=pe(m,s),s.slicers&&(d=ue(oe(d,e.workbookPart,new Set(s.slicers.removedParts)),s)),u&&(m=X(m,u.contentTypes,[]),d=oe(d,e.workbookPart,new Set(u.replaced)),d=d.replace("</Relationships>",`${Qe(u)}</Relationships>`));let $=[];s.externalLinks?.length&&({types:m,rels:d,removedIds:$}=await Dt(t,m,d,p,s.externalLinks,e.workbookPart,E));let g=Ot(await f.text(e.workbookPart),$),R=0;for(const h of e.sheets)R=Math.max(R,Number(h.sheetId));const j=s.sheets.map((h,r)=>{if(h.sourceIndex>=0){const i=e.sheets[h.sourceIndex];s.sheetRefs[r]={rid:i.rid,sheetId:i.sheetId};const k=h.veryHidden?' state="veryHidden"':h.hidden?' state="hidden"':"";return`<sheet name="${L(h.name)}" sheetId="${i.sheetId}"${k} r:id="${i.rid}"/>`}const n=`rIdNew${r}`;return d=d.replace("</Relationships>",`<Relationship Id="${n}" Type="${A}/${h.chartSheet?"chartsheet":"worksheet"}" Target="${E(e.workbookPart,a[r])}"/></Relationships>`),s.sheetRefs[r]={rid:n,sheetId:R+1},`<sheet name="${L(h.name)}" sheetId="${++R}" r:id="${n}"/>`});g=g.replace(/<sheets\b[\s\S]*?<\/sheets>/,`<sheets>${j.join("")}</sheets>`);const N=h=>qe(Pe(ye(h,s.printNames??[]),s.filterNames,s.sheets),s);if(s.definedNames){const h=[...g.matchAll(/<definedName\b[^>]*name="_xlnm\.[^>]*>[\s\S]*?<\/definedName>/g)].map(i=>i[0]),r=s.definedNames.map(i=>`<definedName name="${T(i.name)}"${i.comment?` comment="${L(i.comment)}"`:""}${i.localSheetId!==void 0?` localSheetId="${i.localSheetId}"`:""}${i.hidden?' hidden="1"':""}>${T(i.text)}</definedName>`),n=h.length+r.length?`<definedNames>${[...h,...r].join("")}</definedNames>`:"";/<definedNames\b/.test(g)?g=g.replace(/<definedNames\b[\s\S]*?<\/definedNames>/,n):g=g.replace("</sheets>",`</sheets>${n}`)}if(s.formulasEdited){if(/<calcPr\b/.test(g))g=g.replace(/<calcPr\b([^>]*?)\/>/,(h,r)=>/fullCalcOnLoad/.test(r)?h:`<calcPr${r} fullCalcOnLoad="1"/>`);else if(/<\/sheets>/.test(g)){const h=ie(g);g=g.replace(h,`${h}<calcPr fullCalcOnLoad="1"/>`)}}if(s.themeXml&&({types:m,rels:d}=await le(t,{types:m,rels:d,handled:p},s.themeXml)),await t.addBytes("[Content_Types].xml",Ye(m,s.workbookType)),p.add("[Content_Types].xml"),u){const h=new Set([...d.matchAll(/\bId="([^"]+)"/g)].map(r=>r[1]));g=Je(g,u,h)}g=Ge(ne(Ke(Ze(g,s.workbookProtection),s.calcMode),s.calcSettings),s.fileSharing),g=ns(g,s.bookView),await t.addBytes(e.workbookPart,fe(N(g),s)),p.add(e.workbookPart),await t.addBytes(e.wbRelsPath,d),p.add(e.wbRelsPath),l&&f.has(l)&&(s.styles.length>0||(s.newDxfs??[]).length>0||(s.pivotNumFmts??[]).length>0||s.customStyles||s.namedStyles?.some(h=>!h.keep)?await t.addBytes(l,we(rt(await f.text(l),s.styles,(s.newDxfs??[]).map(ke),s),s.customStyles)):await t.copyRaw(f,f.entries.get(l)),p.add(l))}function vs(t,e,s){const a=(s.tables??[]).map(l=>`<Override PartName="/${l.part}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/>`).join(""),c=re(s).map(l=>`<Override PartName="/${l.comments}" ContentType="${Ue}"/>`).join(""),o=t.map(l=>`<Override PartName="/${l}" ContentType="${Ee(l)}"/>`).join("");return`${O}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>${c?'<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>':""}${c}<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>${o}<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/><Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>${a}${e?`<Override PartName="/${W}" ContentType="${Be}"/>`:""}</Types>`}const Cs="application/vnd.ms-excel.sheet.macroEnabled.main+xml";function Is(t,e){if(!e)return t;const s=`<workbookPr codeName="${L(e)}"/>`;if(/<workbookPr\b/.test(t))return t.replace(/<workbookPr\b([^>]*?)(\/?)>/,(c,o,l)=>`<workbookPr${o.replace(/\scodeName="[^"]*"/,"")} codeName="${L(e)}"${l}>`);const a=/<(?:workbookProtection|bookViews|sheets)\b/.exec(t);return a?t.slice(0,a.index)+s+t.slice(a.index):t}function Ns(t,e){const s=L(e);return/<sheetPr\b/.test(t)?t.replace(/<sheetPr\b([^>]*?)(\/?)>/,(a,c,o)=>`<sheetPr${c.replace(/\scodeName="[^"]*"/,"")} codeName="${s}"${o}>`):t.replace(/(<worksheet\b[^>]*>)/,`$1<sheetPr codeName="${s}"/>`)}function Es(t){const e=t.sheets.map((o,l)=>`<sheet name="${L(o.name)}" sheetId="${l+1}"${o.veryHidden?' state="veryHidden"':o.hidden?' state="hidden"':""} r:id="rId${l+1}"/>`).join(""),s=t.definedNames?.length?`<definedNames>${t.definedNames.map(o=>`<definedName name="${T(o.name)}"${o.comment?` comment="${L(o.comment)}"`:""}${o.localSheetId!==void 0?` localSheetId="${o.localSheetId}"`:""}${o.hidden?' hidden="1"':""}>${T(o.text)}</definedName>`).join("")}</definedNames>`:"",a=is(t),c=t.formulasEdited?'<calcPr fullCalcOnLoad="1"/>':"";return qe(Pe(ye(`${O}<workbook xmlns="${q}" xmlns:r="${A}">${a}<sheets>${e}</sheets>${s}${c}</workbook>`,t.printNames??[]),t.filterNames,t.sheets),t)}function As(t,e){const s=t.map((c,o)=>`<Relationship Id="rId${o+1}" Type="${A}/${Ne(c)?"chartsheet":"worksheet"}" Target="${c.slice(3)}"/>`).join(""),a=t.length;return`${O}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${s}<Relationship Id="rId${a+1}" Type="${A}/styles" Target="styles.xml"/><Relationship Id="rId${a+2}" Type="${A}/sharedStrings" Target="sharedStrings.xml"/>${e?`<Relationship Id="rId${a+3}" Type="${A}/sheetMetadata" Target="metadata.xml"/>`:""}</Relationships>`}export{ct as MAX_COLS,pa as writeXlsx};
2
+ `,q="http://schemas.openxmlformats.org/spreadsheetml/2006/main",A="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Ft="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",Ht="http://schemas.openxmlformats.org/markup-compatibility/2006",Wt="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac",Ut=6e7;class Kt{constructor(e){this.write=e,this.buf=new Uint8Array(1<<20),this.pos=0}async flush(){this.pos>0&&(await this.write(this.buf.subarray(0,this.pos)),this.pos=0)}async text(e){if(e.length*3+this.pos>this.buf.length&&(await this.flush(),e.length*3>this.buf.length)){await this.write(F.encode(e));return}this.pos+=F.encodeInto(e,this.buf.subarray(this.pos)).written}}const Te=[];function qt(t){let e=Te[t];return e===void 0&&(e=F.encode(de(t)),Te[t]=e),e}const _=t=>F.encode(t),Gt=_('<c r="'),Yt=_('" s="'),G=_('" t="'),Q=_('"><v>'),J=_("</v></c>"),Zt=_('"/>'),Se=_("</c>"),Re=_('">'),Qt=_('" cm="'),ve=_('" vm="');function S(t,e,s){for(let a=0;a<s.length;a++)t[e+a]=s[a];return e+s.length}function H(t,e,s){if(s<10)return t[e]=48+s,e+1;let a=0;for(let c=s;c>0;c=Math.floor(c/10))a++;for(let c=e+a-1,n=s;c>=e;c--){const l=Math.floor(n/10);t[c]=48+(n-l*10),n=l}return e+a}function Jt(t,e,s){if(Number.isInteger(s)&&Math.abs(s)<1e15)return s<0&&(t[e++]=45,s=-s),H(t,e,s);const a=String(s);for(let c=0;c<a.length;c++)t[e+c]=a.charCodeAt(c);return e+a.length}function Ce(t){if(t.raw!==void 0)return` ${t.raw}`;let e="";t.t&&(e+=` t="${t.t}"`),t.si!==void 0&&(e+=` si="${t.si}"`),t.ref&&(e+=` ref="${T(t.ref)}"`);for(const s of["dt2D","dtr","r1","r2","del1","del2"])t[s]!==void 0&&(e+=` ${s}="${T(t[s])}"`);return t.ca&&(e+=` ca="${t.ca}"`),e}const Ie=t=>xe(t)?"#VALUE!":nt[t];async function es(t,e,s){const{rows:a,cols:c,kinds:n,values:l,styles:p,count:f,formulas:w,valueMeta:b,rowMeta:d}=e,m=e.inlineText??null;let x=0,u=0,$=0;const g=d?d.length:0,R=async(h,r)=>{let i=`<row r="${h+1}"`;if($<g&&d[$]===h){const o=d[$+1];o>=0&&(i+=d[$+4]?` ht="${o}" customHeight="1"`:` ht="${o}"`),d[$+2]&&(i+=' hidden="1"'),d[$+3]&&(i+=` s="${d[$+3]}" customFormat="1"`),d[$+5]&&(i+=` ${d[$+5]}`),$+=6}await t.text(i+(r?">":"/>"))},j=async h=>{for(;$<g&&d[$]<h;)await R(d[$],!1)};let N=s.row;for(let h=0;h<f;h++){const r=a[h];r!==N&&(N>=0&&await t.text("</row>"),await j(r),await R(r,!0),N=r),t.pos+512>t.buf.length&&await t.flush();const i=t.buf;let o=S(i,t.pos,Gt);o=S(i,o,qt(c[h])),o=H(i,o,r+1);const k=p[h];k!==0&&(o=S(i,o,Yt),o=H(i,o,k)),b!==null&&u<b.length&&b[u][0]===h?(o=S(i,o,ve),o=H(i,o,b[u][1]),u++):(n[h]&ce)===Z&&s.errorVms&&xe(l[h])&&s.errorVms[l[h]]!==void 0&&(o=S(i,o,ve),o=H(i,o,s.errorVms[l[h]]));const C=n[h],y=C&ce,P=l[h];if(C&lt){const[z,M,Y]=w[x];if(z!==h)throw new Error("Formula list out of order");x++,M.cm&&(o=S(i,o,Qt),o=H(i,o,M.cm)),y===te?(o=S(i,o,G),i[o++]=115,i[o++]=116,i[o++]=114):y===ee?(o=S(i,o,G),i[o++]=98):y===Z&&(o=S(i,o,G),i[o++]=101),t.pos=S(i,o,Re);const v=M.f!==void 0?`<f${Ce(M)}>${T(M.f)}</f>`:`<f${Ce(M)}/>`;let I="";y===me?I=`<v>${P}</v>`:y===te?I=`<v>${K(Y??"")}</v>`:y===ee?I=`<v>${P}</v>`:y===Z&&(I=`<v>${Ie(P)}</v>`),await t.text(v+I),t.pos+8>t.buf.length&&await t.flush(),t.pos=S(t.buf,t.pos,Se);continue}switch(y){case me:o=S(i,o,Q),o=Jt(i,o,P),t.pos=S(i,o,J);break;case te:if(o=S(i,o,G),i[o++]=115,m!==null&&m.has(h)){i[o++]=116,i[o++]=114,t.pos=S(i,o,Re),await t.text(`<v>${K(m.get(h))}</v>`),t.pos+8>t.buf.length&&await t.flush(),t.pos=S(t.buf,t.pos,Se);continue}o=S(i,o,Q),o=H(i,o,P),t.pos=S(i,o,J);break;case ee:o=S(i,o,G),i[o++]=98,o=S(i,o,Q),o=H(i,o,P),t.pos=S(i,o,J);break;case Z:o=S(i,o,G),i[o++]=101,o=S(i,o,Q),o=S(i,o,_(Ie(P))),t.pos=S(i,o,J);break;default:t.pos=S(i,o,Zt)}}s.row=N,$<g&&(N>=0&&await t.text("</row>"),s.row=-1,await j(1/0))}const Ne=t=>t.startsWith("xl/chartsheets/"),Ee=t=>Ne(t)?ts:Ft,ts="application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml";async function ss(t,e,s,a,c,n,l,p,f){const w=await Ae("</worksheet>",e,s,a,n,p),b=a===c.activeSheet||e.tabSelected===!0;if(l){const d=await n.zip.text(s);let m=d;if(/\btabSelected="(?:1|true)"/.test(d)!==b&&(m=m.replace(/<sheetView\b[^>]*>/,x=>{const u=x.replace(/\s+tabSelected="[^"]*"/,"");return b?u.replace("<sheetView",'<sheetView tabSelected="1"'):u})),e.pageSetup&&(m=be(m,e.pageSetup)),m===d)return;await t.addBytes(s,new TextEncoder().encode(m))}else{let d=`${O}<chartsheet xmlns="${q}" xmlns:r="${A}"><sheetPr/><sheetViews><sheetView${b?' tabSelected="1"':""} workbookViewId="0" zoomToFit="1"/></sheetViews><pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>${w.replace("</worksheet>","</chartsheet>")}`;e.pageSetup&&(d=be(d,e.pageSetup)),await t.addBytes(s,new TextEncoder().encode(d))}f.add(s)}async function Ae(t,e,s,a,c,n){let l=t;e.cf!==null&&e.cf!==void 0&&(l=vt(l,e.cf,D)),e.validations!==null&&e.validations!==void 0&&(l=D(l,"dataValidations",Et(e.validations))),e.sparklines!==null&&e.sparklines!==void 0&&(l=dt(l,e.sparklines)),e.scenarios!==null&&e.scenarios!==void 0&&(l=D(l,"scenarios",Nt(e.scenarios))),e.dataConsolidate!==null&&e.dataConsolidate!==void 0&&(l=D(l,"dataConsolidate",e.dataConsolidate)),e.customSheetViews!==null&&e.customSheetViews!==void 0&&(l=D(l,"customSheetViews",e.customSheetViews)),e.protection!==null&&e.protection!==void 0&&(l=D(l,"sheetProtection",It(e.protection))),e.ignoredErrors!==null&&e.ignoredErrors!==void 0&&(l=D(l,"ignoredErrors",e.ignoredErrors));const p=V(s);e.sheetPicture&&(l=st(l,e.sheetPicture),e.sheetPicture.path&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${e.sheetPicture.rid}"`)||(n.rels.has(p)||n.rels.set(p,[]),n.rels.get(p).push(`<Relationship Id="${e.sheetPicture.rid}" Type="${A}/image" Target="${T(E(s,e.sheetPicture.path))}"/>`)))),e.headerPicture&&(l=D(l,"legacyDrawingHF",e.headerPicture.rid?`<legacyDrawingHF r:id="${e.headerPicture.rid}"/>`:""),e.headerPicture.rid&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${e.headerPicture.rid}"`)||(n.rels.has(p)||n.rels.set(p,[]),n.rels.get(p).push(`<Relationship Id="${e.headerPicture.rid}" Type="${A}/vmlDrawing" Target="${T(E(s,e.headerPicture.vml))}"/>`))));for(const m of n.plan.removedTableRids?.[a]??[])l=l.replace(new RegExp(`<tablePart\\b[^>]*r:id="${m}"[^>]*/>`),"");if(n.plan.removedTableRids?.[a]){const m=(l.match(/<tablePart\b/g)??[]).length;l=m===0?l.replace(/<tableParts\b[^>]*\/>|<tableParts\b[^>]*>\s*<\/tableParts>/,""):l.replace(/(<tableParts\b[^>]*\bcount=")\d+/,`$1${m}`)}const f=(n.plan.tables??[]).filter(m=>m.isNew&&m.sheetIndex===a),w=(m,x,u,$)=>{n.rels.has(p)||n.rels.set(p,[]);const g=x==="threadedCommentExternal"?bs:`${A}/${x}`;n.rels.get(p).push(`<Relationship Id="${m}" Type="${g}" Target="${T(u)}"${$?' TargetMode="External"':""}/>`)};if(f.length>0){const m=[...l.matchAll(/<tablePart\b[^>]*\/>/g)].map($=>$[0]),x=f.map(($,g)=>{const R=`rIdTable${a}_${g}`;return w(R,"table",E(s,$.part),!1),`<tablePart r:id="${R}"/>`}),u=[...m,...x];l=D(l,"tableParts",`<tableParts count="${u.length}">${u.join("")}</tableParts>`)}if(e.hyperlinks!==null&&e.hyperlinks!==void 0){const m=e.hyperlinks.map((x,u)=>{if(x.rid||!x.target)return x;const $=`rIdLink${a}_${u}`;return w($,"hyperlink",x.target,!0),{...x,rid:$}});l=D(l,"hyperlinks",Ct(m))}if(e.threads){const m=n.plan.threadParts?.[a];m&&(n.parts.push({path:m.path,xml:ks(e.threads)}),m.existing||w(`rIdThreads${a+1}`,"threadedCommentExternal",E(s,m.path),!1))}const b=n.plan.noteParts?.[a];if(b&&e.comments){if(b.existing)n.parts.push({path:b.comments,xml:Oe(e.comments)}),b.vml&&n.parts.push({path:b.vml,xml:_e(b.vmlSource,e.comments)}),b.threaded&&n.parts.push({path:b.threaded,xml:Le(b.threadedSource,e.structureOps??[])});else if(e.comments.length>0){const{comments:m,vml:x,n:u}=b;n.parts.push({path:m,xml:Oe(e.comments)}),w(`rIdComments${u}`,"comments",E(s,m),!1);const $=/<legacyDrawing\b[^>]*r:id="([^"]+)"/.exec(l)?.[1],g=$&&c?.zip.has(p)?await c.zip.text(p):"",R=g?[...g.matchAll(/<Relationship\b[^>]*\/>/g)].map(h=>h[0]).find(h=>h.includes(`Id="${$}"`)):null,j=R?/Target="([^"]+)"/.exec(R)?.[1]:null,N=j?B(s,j):null;N&&c.zip.has(N)?n.parts.push({path:N,xml:_e(await c.zip.text(N),e.comments)}):(n.parts.push({path:x,xml:as(e.comments)}),w(`rIdVml${u}`,"vmlDrawing",E(s,x),!1),l=D(l,"legacyDrawing",`<legacyDrawing r:id="rIdVml${u}"/>`))}}const d=e.objects;if(d){n.parts.push({path:d.path,xml:d.xml}),d.relsXml&&n.parts.push({path:d.relsPath,xml:d.relsXml});for(const m of d.parts)n.parts.push({path:m.path,xml:m.data instanceof Blob?new Uint8Array(await m.data.arrayBuffer()):m.data});d.isNew&&((c?.zip.has(p)?await c.zip.text(p):"").includes(`Id="${d.sheetRel.id}"`)||w(d.sheetRel.id,"drawing",d.sheetRel.target,!1),l=ht(l,d.sheetDrawingXml)),d.controls&&(n.rels.has(p)||n.rels.set(p,[]),l=await pt(l,d.controls,{source:c,part:s,relsName:p,addRel:w,extraParts:n.parts,pendingRels:n.rels.get(p),relativeTo:E,resolveTarget:B}))}return ut({tail:l,index:a,info:e,source:c,extra:n,relsName:p})}function Oe(t){const e=[...new Set(t.map(s=>s.author??""))];return`${O}<comments xmlns="${q}"><authors>${e.map(s=>`<author>${K(s)}</author>`).join("")}</authors><commentList>${t.map(s=>`<comment ref="${s.ref}" authorId="${e.indexOf(s.author??"")}"><text>${ps(s,K)}</text></comment>`).join("")}</commentList></comments>`}function De(t,e=1025){return t.map((s,a)=>hs(s,e+a,a+1,he(s.ref))).join("")}function _e(t,e){const s=t.replace(/<v:shape\b(?:(?!<\/v:shape>)[\s\S])*?ObjectType="Note"[\s\S]*?<\/v:shape>/g,"");let a=1024;for(const c of s.matchAll(/_x0000_s(\d+)/g))a=Math.max(a,Number(c[1]));return s.replace("</xml>",`${De(e,a+1)}</xml>`)}function as(t){return`<xml xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1"/></o:shapelayout><v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter"/><v:path gradientshapeok="t" o:connecttype="rect"/></v:shapetype>${De(t)}</xml>`}function Ve(t){return!t||t.length===0?"":`<cols>${t.map(s=>{let a=`<col min="${s.min+1}" max="${s.max+1}" width="${ot(s.px)}"`;return s.custom&&(a+=' customWidth="1"'),s.hidden&&(a+=' hidden="1"'),s.style&&(a+=` style="${s.style}"`),s.extra&&(a+=` ${s.extra}`),a+"/>"}).join("")}</cols>`}function je(t,e){const s=cs(t,e);let a="";if(t.frozenRows||t.frozenCols){const c=t.frozenRows&&t.frozenCols?"bottomRight":t.frozenRows?"bottomLeft":"topRight",n=(t.frozenCols?` xSplit="${t.frozenCols}"`:"")+(t.frozenRows?` ySplit="${t.frozenRows}"`:""),l=de(t.frozenCols)+(t.frozenRows+1);a=`<pane${n} topLeftCell="${l}" activePane="${c}" state="frozen"/>`}else t.split&&(a=tt(t));return`<sheetViews><sheetView${s} workbookViewId="0">${a}</sheetView></sheetViews>`}function ze(t){return t.maxRow<0||t.maxCol<0?"A1":se({r0:0,c0:0,r1:t.maxRow,c1:t.maxCol})}function rs(t,e){const s=t.tabColor?`<sheetPr><tabColor rgb="FF${t.tabColor.slice(1)}"/></sheetPr>`:"";return`${O}<worksheet xmlns="${q}" xmlns:r="${A}" xmlns:mc="${Ht}" mc:Ignorable="x14ac" xmlns:x14ac="${Wt}">${s}<dimension ref="${ze(t)}"/>${je(t,e)}<sheetFormatPr baseColWidth="10" defaultRowHeight="${t.defaultHeight}"/>${Ve(t.cols)}`}function os(t,e){let s=t;if(e.tabColor!==null&&e.tabColor!==void 0&&(s=s.replace(/<tabColor\b[^>]*\/>/,""),e.tabColor)){const c=`<tabColor rgb="FF${e.tabColor.slice(1)}"/>`;/<sheetPr\b[^>]*\/>/.test(s)?s=s.replace(/<sheetPr\b([^>]*)\/>/,`<sheetPr$1>${c}</sheetPr>`):/<sheetPr\b[^>]*>/.test(s)?s=s.replace(/(<sheetPr\b[^>]*>)/,`$1${c}`):s=s.replace(/(<worksheet\b[^>]*>)/,`$1<sheetPr>${c}</sheetPr>`)}const a=`<dimension ref="${ze(e)}"/>`;if(/<dimension\b[^>]*\/>/.test(s)&&(s=s.replace(/<dimension\b[^>]*\/>/,a)),e.viewChanged?/<sheetViews\b[\s\S]*<\/sheetViews>/.test(s)&&(s=s.replace(/<sheetViews\b[\s\S]*<\/sheetViews>/,je(e,e.tabSelected))):s=ls(s,e),e.defaultsChanged&&(s=s.replace(/(<sheetFormatPr\b[^>]*?\bdefaultRowHeight=")[^"]*"/,`$1${e.defaultHeight}"`)),e.colsChanged){const c=Ve(e.cols);/<cols\b[\s\S]*<\/cols>/.test(s)?s=s.replace(/<cols\b[\s\S]*<\/cols>/,c):s+=c}return s}import{bookViewsXml as is,patchBookViews as ns,patchTabSelected as ls,sheetViewAttrs as cs}from"../cells/view-xml.js";import{docPropsRels as ms,docPropsTypes as Me,writeDocProps as ds}from"../cells/docprops-xml.js";import{noteShapeXml as hs,noteTextXml as ps}from"../cells/note-xml.js";const fs=/<(phoneticPr|conditionalFormatting|dataValidations|hyperlinks|printOptions|pageMargins|pageSetup|headerFooter|rowBreaks|colBreaks|customProperties|cellWatches|ignoredErrors|smartTags|drawing|legacyDrawing|legacyDrawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst)\b|<\/worksheet>/;function Xe(t){return t.length===0?"":`<mergeCells count="${t.length}">${t.map(e=>`<mergeCell ref="${se(e)}"/>`).join("")}</mergeCells>`}function Le(t,e){return e.length===0?t:t.replace(/\b(sqref|ref)="([^"]*)"/g,(s,a,c)=>{const n=c.split(/\s+/).map(p=>{let f=he(p);if(f===null)return null;for(const w of e){if(f===null)break;f=mt(f,w)}return f===null?"":se(f)});if(n.includes(null))return s;const l=n.filter(p=>p!=="");return l.length?`${a}="${l.join(" ")}"`:`${a}="A1048576"`})}function us(t,e,s=[]){t=Le(t,s);const a=Xe(e),c=/<mergeCells\b[\s\S]*?<\/mergeCells>/;if(c.test(t))return t.replace(c,a);if(!a)return t;const n=fs.exec(t);return n?t.slice(0,n.index)+a+t.slice(n.index):t+a}const ws=new TextDecoder("latin1");async function xs(t,e,s,a){let n=new Uint8Array(0),l=!0;await it(await e.stream(s),async b=>{let d=b;if(l){l=!1;const m=Bt.decode(d.subarray(0,Math.min(d.length,512))),x=/<sst\b[^>]*>/.exec(m);if(x){const u=x[0].replace(/\s(count|uniqueCount)="\d+"/g,""),$=F.encode(m.slice(0,x.index)+u),g=F.encode(m.slice(0,x.index+x[0].length)).length;await t($),d=d.subarray(g)}}if(d.length>=16)n.length&&await t(n),await t(d.subarray(0,d.length-16)),n=d.slice(d.length-16);else{const m=new Uint8Array(n.length+d.length);m.set(n),m.set(d,n.length),n=m}});const p=ws.decode(n),f=F.encode(a),w=p.lastIndexOf("</sst>");w>=0?(await t(n.subarray(0,w)),await t(f),await t(n.subarray(w))):p.endsWith("/>")?(await t(n.subarray(0,n.length-2)),await t(F.encode(`>${a}</sst>`))):(await t(n),await t(f))}const W="xl/metadata.xml",Be="application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",Fe=`${O}<metadata xmlns="${q}" xmlns:xda="http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray"><metadataTypes count="1"><metadataType name="XLDAPR" minSupportedVersion="120000" copy="1" pasteAll="1" pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1" clearComments="1" assign="1" coerce="1" cellMeta="1"/></metadataTypes><futureMetadata name="XLDAPR" count="1"><bk><extLst><ext uri="{bdbb8cdc-fa1e-496e-a857-3c3f30c029c3}"><xda:dynamicArrayProperties fDynamic="1" fCollapsed="0"/></ext></extLst></bk></futureMetadata><cellMetadata count="1"><bk><rc t="1" v="0"/></bk></cellMetadata></metadata>`,gs=(t,e)=>e?yt(t,e,K):`<si><t xml:space="preserve">${K(t)}</t></si>`;async function pa(t,e,s,a=null,c=null){const n=new et(t),l=[],p=new Set;a&&e.dataSheets&&Pt(a.zip,p,e.dataSheets);for(const r of e.sheets)if(r.objects)for(const i of r.objects.removedParts)p.add(i);const f=e.pivots??null,w=new Set([...e.sheets.flatMap(r=>(r.objects?.removedParts??[]).filter(i=>i.startsWith("xl/ctrlProps/"))),...f?.replaced??[],...wt(e),...(e.removedTables??[]).map(r=>r.part)]);for(const r of w)p.add(r),p.add(V(r));e.sheetRefs=e.sheets.map((r,i)=>({rid:`rId${i+1}`,sheetId:i+1})),e.written=[];const b=new Set(a?a.sheets.map(r=>r.part):[]),d=new Set(e.sheets.filter(r=>r.sourceIndex>=0).map(r=>a.sheets[r.sourceIndex].part)),m=new Set(a?a.sheets.map(r=>r.part).filter(r=>!d.has(r)):[]);let x=1;const u=e.sheets.map(r=>{if(r.sourceIndex>=0)return a.sheets[r.sourceIndex].part;let i;do i=`xl/${r.chartSheet?"chartsheets":"worksheets"}/sheet${x++}.xml`;while(b.has(i));return b.add(i),l.push(i),i}),$=a?.stringsPart??"xl/sharedStrings.xml",g=a?.stylesPart??"xl/styles.xml";e.noteParts=await $s(e,u,a),{threads:e.threadParts,personPart:e.personPart}=await Ss(e,u,a);let R=null;if(a)await Rs(n,a,e,u,l,$,g,p);else{let r=vs(u,e.dynamicArrays,e);for(const P of e.sheets)P.objects&&(r=X(r,P.objects.contentTypes,P.objects.removedOverrides));f&&(r=X(r,f.contentTypes,[])),r=pe(r,e),r=X(r,We(e),[]),{types:r}=ae(r,"</Relationships>",e.cellTypes),r=Me(r,e.docProps),e.dataSheets&&(r=ge(r,e.dataSheets));let i=null;e.themeXml&&({types:r,rels:i}=await le(n,{types:r,rels:"</Relationships>"},e.themeXml));const o=c?.plan??null;o&&(r=X(r,[...o.overrides,...o.defaults],[])),R=Xt(o,e),R&&(r=X(r,R.types,[])),r=Ye(r,e.workbookType),o?.macro&&(r=r.replace(/application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)\.main\+xml/,Cs)),await n.addBytes("[Content_Types].xml",r);const k=(o?.rootRels??[]).map((P,z)=>`<Relationship Id="rIdForeign${z+1}" Type="${T(P.type)}" Target="${T(P.target)}"/>`).join("");await n.addBytes("_rels/.rels",`${O}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${A}/officeDocument" Target="xl/workbook.xml"/>${ms(e.docProps)}${k}</Relationships>`);let C=Ge(ne(Ke(Ze(Is(Es(e),o?.codeNames.workbook),e.workbookProtection),e.calcMode),e.calcSettings),e.fileSharing),y=ae("</Types>",As(u,e.dynamicArrays),e.cellTypes).rels;i&&(y=y.replace("</Relationships>",i)),e.personPart&&(y=y.replace("</Relationships>",`<Relationship Id="rIdPersons" Type="${He}" Target="${E("xl/workbook.xml",e.personPart.path)}"/></Relationships>`)),f&&(y=y.replace("</Relationships>",`${Qe(f)}</Relationships>`),C=Je(C,f)),y=ue(y,e),await n.addBytes("xl/workbook.xml",fe(C,e)),e.dataSheets&&(y=$e(y,e.dataSheets)),o?.workbookRels.length&&(y=y.replace("</Relationships>",`${o.workbookRels.map((P,z)=>`<Relationship Id="rIdForeign${z+1}" Type="${T(P.type)}" Target="${T(E("xl/workbook.xml",P.target))}"/>`).join("")}</Relationships>`)),await n.addBytes("xl/_rels/workbook.xml.rels",y),e.dynamicArrays&&await n.addBytes(W,Fe),await n.addBytes(g,we(at(e.styles,(e.newDxfs??[]).map(ke),e),e.customStyles))}const j=e.extraRich?new Map(e.extraRich):null,N=e.extraStrings.map((r,i)=>gs(r,j?.get(i))).join("");a?.stringsPart&&a.zip.has(a.stringsPart)?await n.add($,r=>xs(r,a.zip,a.stringsPart,N)):await n.addBytes($,`${O}<sst xmlns="${q}">${N}</sst>`),p.add($);const h={rels:new Map,parts:[],next:1,plan:e};if(e.removedTableRids={},a&&(e.removedTables??[]).length>0)for(const r of e.removedTables){const i=V(u[r.sheetIndex]);if(!a.zip.has(i))continue;const o=await a.zip.text(i);for(const k of o.matchAll(/<Relationship\b[^>]*\/>/g)){const C=/\bTarget="([^"]+)"/.exec(k[0])?.[1],y=/\bId="([^"]+)"/.exec(k[0])?.[1];C&&y&&B(u[r.sheetIndex],C)===r.part&&(e.removedTableRids[r.sheetIndex]??=[]).push(y)}h.rels.has(i)||h.rels.set(i,[])}for(let r=0;r<e.sheets.length;r++){const i=e.sheets[r],o=i.sourceIndex>=0?a.sheets[i.sourceIndex]:null;if(i.chartSheet){await ss(n,i,u[r],r,e,a,o,h,p),e.written[r]={head:"",tail:""},e.onSheetDone?.(r);continue}p.add(u[r]);const k=i.cellEstimate>Ut;await n.add(u[r],async C=>{const y=new Kt(C);let P=o?.head?os(o.head,i):rs(i,r===e.activeSheet||i.tabSelected===!0);P=Rt(P,i.sheetProps),!o&&c?.plan.codeNames.sheets[i.name]&&(P=Ns(P,c.plan.codeNames.sheets[i.name])),i.pageSetup&&(P=Tt(P,i.pageSetup));const z=o?null:R?.sheets.get(r);z&&(P=jt(P,z),Vt(i.objects,z)),e.written[r]={head:P},await y.text(P),await y.text("<sheetData>");const M={row:-1,errorVms:e.errorVms??null};for(let I=0;I>=0;){const U=await s.block(r,I);await es(y,U,M),I=U.nextRow,s.recycle?.(U)}M.row>=0&&await y.text("</row>"),await y.text("</sheetData>");const Y=i.autoFilter??"";let v=o?us(o.tail??"</worksheet>",i.merges,i.structureOps??[]):`${Y}${Xe(i.merges)}</worksheet>`;if(!o&&!/xmlns:r=/.test(v)&&(v=`${v}`),o&&i.autoFilter!==null&&i.autoFilter!==void 0){v=v.replace(/<autoFilter\b[^>]*?(?:\/>|>[\s\S]*?<\/autoFilter>)/,"").replace(/<sortState\b[^>]*?(?:\/>|>[\s\S]*?<\/sortState>)/,"");const I=/<mergeCells\b|<(?:sortState|dataConsolidate|customSheetViews|phoneticPr|conditionalFormatting|dataValidations|hyperlinks|printOptions|pageMargins|pageSetup|headerFooter|rowBreaks|colBreaks|customProperties|cellWatches|ignoredErrors|smartTags|drawing|legacyDrawing|legacyDrawingHF|picture|oleObjects|controls|webPublishItems|tableParts|extLst)\b|<\/worksheet>/.exec(v);v=I?v.slice(0,I.index)+Y+v.slice(I.index):v+Y}if(v=await Ae(v,i,u[r],r,a,h),i.pageSetup&&(v=St(v,i.pageSetup)),!o){v=v.replace(/(<pageSetup\b[^>]*?)\sr:id="[^"]*"/,"$1");const I=R?.sheets.get(r);if(I){const U=V(u[r]);h.rels.has(U)||h.rels.set(U,[]),v=await _t(v,{group:I,part:u[r],pending:h.rels.get(U),extraParts:h.parts,foreignZip:c.zip,names:R.names,kept:R.kept})}}e.written[r].tail=v,await y.text(v),await y.flush()},{large:k}),e.onSheetDone?.(r)}if(f){for(const o of f.parts)await n.addBytes(o.name,o.xml),p.add(o.name);const r=new Map;let i=0;for(const o of f.relationships)if(o.from!==null)r.has(o.from)||r.set(o.from,[]),r.get(o.from).push(o);else if(o.sheetIndex>=0){const k=V(u[o.sheetIndex]);h.rels.has(k)||h.rels.set(k,[]),h.rels.get(k).push(`<Relationship Id="rIdPivot${++i}" Type="${o.type}" Target="${T(o.target)}"/>`)}for(const[o,k]of r){const C=V(o);await n.addBytes(C,ft(k)),p.add(C)}for(const o of u){const k=V(o);a?.zip.has(k)&&!h.rels.has(k)&&h.rels.set(k,[])}}if(e.slicers?.removedParts.length)for(const r of u){const i=V(r);a?.zip.has(i)&&!h.rels.has(i)&&h.rels.set(i,[])}await xt(n,e,p);for(const r of e.tables??[]){let i=r.xml;i===null&&(i=gt(await a.zip.text(r.part),r.patch));const o=R?.tables.get(r.part);if(o){i=Mt(i,o);const k=zt(r.part,o,R.names);await n.addBytes(k.path,k.xml),p.add(k.path)}await n.addBytes(r.part,i),p.add(r.part)}for(const r of e.cellTypes??[])await n.addBytes(r.path,r.xml),p.add(r.path);e.personPart&&(await n.addBytes(e.personPart.path,Ts(e.persons)),p.add(e.personPart.path));for(const r of h.parts)await n.addBytes(r.path,r.xml),p.add(r.path);for(const[r,i]of h.rels){let o=a?.zip.has(r)?await a.zip.text(r):`${O}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>`;if(w.size>0){const C=r.replace("_rels/","").replace(/\.rels$/,"");o=oe(o,C,w)}const k=o.replace("</Relationships>",`${i.join("")}</Relationships>`);await n.addBytes(r,k),p.add(r)}if(await ds(n,a?.zip??null,e.docProps,p),await kt(n,e.dataSheets,p),a){const r=new Set([...p,a.calcChainPart,...m].map(i=>a.zip.entry(i)?.name).filter(Boolean));for(const[i,o]of a.zip.entries)r.has(i)||await n.copyRaw(a.zip,o)}if(!a&&c){const r=new Set(n.central.map(i=>i.name));for(const i of c.plan.entries){const o=c.zip.entries.get(i);o&&!r.has(i)&&await n.copyRaw(c.zip,o)}R&&await Lt(n,R,c.zip,r)}await n.finish(),e.result={sheets:e.sheets.map((r,i)=>({name:r.name,part:u[i],rid:e.sheetRefs[i].rid,sheetId:e.sheetRefs[i].sheetId,hidden:r.hidden,veryHidden:r.veryHidden,head:e.written[i].head,tail:e.written[i].tail})),workbookPart:a?.workbookPart??"xl/workbook.xml",wbRelsPath:a?.wbRelsPath??"xl/_rels/workbook.xml.rels",stringsPart:$,stylesPart:g}}async function $s(t,e,s){const a={};let c=1;for(let n=0;n<t.sheets.length;n++){const l=t.sheets[n];if(!l.comments)continue;const p=V(e[n]);if(s?.zip.has(p)&&l.sourceIndex>=0){const f=await s.zip.text(p),w=d=>{const m=[...f.matchAll(/<Relationship\b[^>]*\/>/g)].map(u=>u[0]).find(u=>new RegExp(`\\bType="[^"]*/${d}"`).test(u)),x=m&&/\bTarget="([^"]+)"/.exec(m)?.[1];return x?B(e[n],x):null},b=w("comments");if(b){const d=w("vmlDrawing"),m=w("threadedComment");a[n]={existing:!0,comments:b,vml:d,vmlSource:d?await s.zip.text(d):null,threaded:m,threadedSource:m?await s.zip.text(m):null};continue}}if(l.comments.length!==0){for(;s?.zip.has(`xl/comments${100+c}.xml`)||s?.zip.has(`xl/drawings/vmlDrawing${100+c}.vml`);)c++;a[n]={existing:!1,comments:`xl/comments${100+c}.xml`,vml:`xl/drawings/vmlDrawing${100+c}.vml`,n:c},c++}}return a}const bs="http://schemas.microsoft.com/office/2017/10/relationships/threadedComment",He="http://schemas.microsoft.com/office/2017/10/relationships/person",ys="application/vnd.ms-excel.threadedcomments+xml",Ps="application/vnd.ms-excel.person+xml";function ks(t){const e=t.map(s=>`<threadedComment ref="${s.ref}" dT="${T(s.date)}" personId="${T(s.personId)}" id="${T(s.id)}"${s.parentId?` parentId="${T(s.parentId)}"`:""}${s.done?' done="1"':""}><text>${K(s.text)}</text>${s.mentions?.length?`<mentions>${s.mentions.map(a=>`<mention mentionpersonId="${T(a.personId)}" mentionId="${T(a.id??s.id.replace(/^.{9}/,`{${String(a.start).padStart(8,"0")}`))}" startIndex="${a.start}" length="${a.length}"/>`).join("")}</mentions>`:""}</threadedComment>`).join("");return`${O}<ThreadedComments xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">${e}</ThreadedComments>`}function Ts(t){const e=t.map(s=>`<person displayName="${L(s.displayName)}" id="${T(s.id)}" userId="${T(s.userId)}" providerId="${T(s.providerId)}"/>`).join("");return`${O}<personList xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">${e}</personList>`}async function Ss(t,e,s){const a={};let c=1;for(let l=0;l<t.sheets.length;l++){const p=t.sheets[l];if(!p.threads)continue;const f=V(e[l]);let w=null;if(s?.zip.has(f)&&p.sourceIndex>=0){const d=[...(await s.zip.text(f)).matchAll(/<Relationship\b[^>]*\/>/g)].map(x=>x[0]).find(x=>/\/threadedComment"/.test(x)),m=d&&/\bTarget="([^"]+)"/.exec(d)?.[1];m&&(w=B(e[l],m))}if(w){a[l]={path:w,existing:!0};continue}if(p.threads.length!==0){for(;s?.zip.has(`xl/threadedComments/threadedComment${100+c}.xml`);)c++;a[l]={path:`xl/threadedComments/threadedComment${100+c}.xml`,existing:!1},c++}}let n=null;if(t.persons){let l=null;if(s?.zip.has(s.wbRelsPath)){const f=[...(await s.zip.text(s.wbRelsPath)).matchAll(/<Relationship\b[^>]*\/>/g)].map(b=>b[0]).find(b=>/\/person"/.test(b)),w=f&&/\bTarget="([^"]+)"/.exec(f)?.[1];w&&(l=B(s.workbookPart,w))}n=l?{path:l,existing:!0}:{path:"xl/persons/person.xml",existing:!1}}return{threads:a,personPart:n}}const We=t=>[...Object.values(t.threadParts??{}).filter(e=>!e.existing).map(e=>({partName:`/${e.path}`,contentType:ys})),...t.personPart&&!t.personPart.existing?[{partName:`/${t.personPart.path}`,contentType:Ps}]:[]],Ue="application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",re=t=>Object.values(t.noteParts??{}).filter(e=>!e.existing);function Ke(t,e){if(e==null)return t;const s=e==="auto"?"":` calcMode="${e}"`;if(/<calcPr\b/.test(t))return t.replace(/<calcPr\b([^>]*?)\/>/,(c,n)=>`<calcPr${n.replace(/\s*calcMode="[^"]*"/,"")}${s}/>`);if(!s)return t;const a=ie(t);return t.replace(a,`${a}<calcPr${s}/>`)}const qe=(t,e)=>e.customViews?At(t,e.customViews.workbookXml,e.customViews.names):t;function Ge(t,e){if(e==null)return t;const s=t.replace(/<fileSharing\b[^>]*\/>/,""),a=Object.keys(e).filter(f=>e[f]!==void 0&&e[f]!==null&&e[f]!=="");if(a.length===0)return s;const c=`<fileSharing ${a.map(f=>`${f}="${T(e[f])}"`).join(" ")}/>`,n=/<fileVersion\b[^>]*\/>/.exec(s),l=/<workbook\b[^>]*>/.exec(s),p=n?n.index+n[0].length:l.index+l[0].length;return s.slice(0,p)+c+s.slice(p)}function Ye(t,e){if(!e)return t;const s=e==="template"?"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":e==="macro"?"application/vnd.ms-excel.sheet.macroEnabled.main+xml":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",a=e==="workbook"?/application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)\.main\+xml/:/application\/vnd\.(?:openxmlformats-officedocument\.spreadsheetml\.(?:sheet|template)|ms-excel\.sheet\.macroEnabled)\.main\+xml/;return t.replace(a,s)}function Ze(t,e){if(e==null)return t;const s=t.replace(/<workbookProtection\b[^>]*\/>/,""),a=Object.keys(e);if(a.length===0)return s;const c=`<workbookProtection ${a.map(l=>`${l}="${T(e[l])}"`).join(" ")}/>`,n=/<bookViews\b|<sheets\b/.exec(s);return s.slice(0,n.index)+c+s.slice(n.index)}const Qe=t=>t.caches.map(e=>`<Relationship Id="${e.relId}" Type="${e.type}" Target="${T(e.target)}"/>`).join("");function oe(t,e,s){return t.replace(/<Relationship\b[^>]*\/>/g,a=>{const c=/\bTarget="([^"]+)"/.exec(a);return c&&s.has(B(e,c[1]))?"":a})}function Je(t,e,s=null){let a="";const c=/<pivotCaches\b[^>]*>([\s\S]*?)<\/pivotCaches>/.exec(t);c&&s&&(a=[...c[1].matchAll(/<pivotCache\b[^>]*\/>/g)].map(w=>w[0]).filter(w=>s.has(/r:id="([^"]+)"/.exec(w)?.[1])).join(""));const n=e.caches.map(w=>`<pivotCache cacheId="${w.cacheId}" r:id="${w.relId}"/>`).join(""),l=t.replace(/<pivotCaches\b[^>]*>[\s\S]*?<\/pivotCaches>/,""),p=a||n?`<pivotCaches>${a}${n}</pivotCaches>`:"";if(!p)return l;const f=/<(?:smartTagPr|smartTagTypes|webPublishing|fileRecoveryPr|webPublishObjects|extLst)\b|<\/workbook>/.exec(l);return f?l.slice(0,f.index)+p+l.slice(f.index):l+p}async function Rs(t,e,s,a,c,n,l,p){const f=e.zip,w=await f.text(e.wbRelsPath);let b=null,d=w.replace(/<Relationship\b[^>]*calcChain[^>]*\/>/g,h=>{const r=/Target="([^"]+)"/.exec(h);return r&&(b=B(e.workbookPart,r[1])),""});e.calcChainPart=b;let m=await f.text("[Content_Types].xml");m=m.replace(/<Override\b[^>]*calcChain[^>]*\/>/g,"");const x=c.map(h=>`<Override PartName="/${h}" ContentType="${Ee(h)}"/>`);if(f.has(n)||(x.push(`<Override PartName="/${n}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>`),d=d.replace("</Relationships>",`<Relationship Id="rIdStrings" Type="${A}/sharedStrings" Target="${E(e.workbookPart,n)}"/></Relationships>`)),re(s).length>0){/Extension="vml"/.test(m)||(m=m.replace(/(<Types\b[^>]*>)/,'$1<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>'));for(const h of re(s))x.push(`<Override PartName="/${h.comments}" ContentType="${Ue}"/>`)}s.dynamicArrays&&!f.has(W)&&(x.push(`<Override PartName="/${W}" ContentType="${Be}"/>`),d=d.replace("</Relationships>",`<Relationship Id="rIdMetadata" Type="${A}/sheetMetadata" Target="${E(e.workbookPart,W)}"/></Relationships>`),await t.addBytes(W,Fe),p.add(W)),s.dynamicArrays&&f.has(W);for(const h of s.tables??[])h.isNew&&x.push(`<Override PartName="/${h.part}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/>`);m=m.replace("</Types>",`${x.join("")}</Types>`);for(const h of s.sheets)h.objects&&(m=X(m,h.objects.contentTypes,h.objects.removedOverrides));m=X(m,We(s),[]),s.personPart&&!s.personPart.existing&&(d=d.replace("</Relationships>",`<Relationship Id="rIdPersons" Type="${He}" Target="${E(e.workbookPart,s.personPart.path)}"/></Relationships>`)),s.dataSheets&&(m=ge(m,s.dataSheets),d=$e(d,s.dataSheets)),{types:m,rels:d}=await $t(f,m,d,p),{types:m,rels:d}=await bt(f,m,d,p),{types:m,rels:d}=ae(m,d,s.cellTypes,e.workbookPart),m=Me(m,s.docProps);const u=s.pivots??null;m=X(m,[],[...u?.replaced??[],...(s.removedTables??[]).map(h=>h.part)].map(h=>`/${h}`)),m=pe(m,s),s.slicers&&(d=ue(oe(d,e.workbookPart,new Set(s.slicers.removedParts)),s)),u&&(m=X(m,u.contentTypes,[]),d=oe(d,e.workbookPart,new Set(u.replaced)),d=d.replace("</Relationships>",`${Qe(u)}</Relationships>`));let $=[];s.externalLinks?.length&&({types:m,rels:d,removedIds:$}=await Dt(t,m,d,p,s.externalLinks,e.workbookPart,E));let g=Ot(await f.text(e.workbookPart),$),R=0;for(const h of e.sheets)R=Math.max(R,Number(h.sheetId));const j=s.sheets.map((h,r)=>{if(h.sourceIndex>=0){const o=e.sheets[h.sourceIndex];s.sheetRefs[r]={rid:o.rid,sheetId:o.sheetId};const k=h.veryHidden?' state="veryHidden"':h.hidden?' state="hidden"':"";return`<sheet name="${L(h.name)}" sheetId="${o.sheetId}"${k} r:id="${o.rid}"/>`}const i=`rIdNew${r}`;return d=d.replace("</Relationships>",`<Relationship Id="${i}" Type="${A}/${h.chartSheet?"chartsheet":"worksheet"}" Target="${E(e.workbookPart,a[r])}"/></Relationships>`),s.sheetRefs[r]={rid:i,sheetId:R+1},`<sheet name="${L(h.name)}" sheetId="${++R}" r:id="${i}"/>`});g=g.replace(/<sheets\b[\s\S]*?<\/sheets>/,`<sheets>${j.join("")}</sheets>`);const N=h=>qe(Pe(ye(h,s.printNames??[]),s.filterNames,s.sheets),s);if(s.definedNames){const h=[...g.matchAll(/<definedName\b[^>]*name="_xlnm\.[^>]*>[\s\S]*?<\/definedName>/g)].map(o=>o[0]),r=s.definedNames.map(o=>`<definedName name="${T(o.name)}"${o.comment?` comment="${L(o.comment)}"`:""}${o.localSheetId!==void 0?` localSheetId="${o.localSheetId}"`:""}${o.hidden?' hidden="1"':""}>${T(o.text)}</definedName>`),i=h.length+r.length?`<definedNames>${[...h,...r].join("")}</definedNames>`:"";/<definedNames\b/.test(g)?g=g.replace(/<definedNames\b[\s\S]*?<\/definedNames>/,i):g=g.replace("</sheets>",`</sheets>${i}`)}if(s.formulasEdited){if(/<calcPr\b/.test(g))g=g.replace(/<calcPr\b([^>]*?)\/>/,(h,r)=>/fullCalcOnLoad/.test(r)?h:`<calcPr${r} fullCalcOnLoad="1"/>`);else if(/<\/sheets>/.test(g)){const h=ie(g);g=g.replace(h,`${h}<calcPr fullCalcOnLoad="1"/>`)}}if(s.themeXml&&({types:m,rels:d}=await le(t,{types:m,rels:d,handled:p},s.themeXml)),await t.addBytes("[Content_Types].xml",Ye(m,s.workbookType)),p.add("[Content_Types].xml"),u){const h=new Set([...d.matchAll(/\bId="([^"]+)"/g)].map(r=>r[1]));g=Je(g,u,h)}g=Ge(ne(Ke(Ze(g,s.workbookProtection),s.calcMode),s.calcSettings),s.fileSharing),g=ns(g,s.bookView),await t.addBytes(e.workbookPart,fe(N(g),s)),p.add(e.workbookPart),await t.addBytes(e.wbRelsPath,d),p.add(e.wbRelsPath),l&&f.has(l)&&(s.styles.length>0||(s.newDxfs??[]).length>0||(s.pivotNumFmts??[]).length>0||s.customStyles||s.namedStyles?.some(h=>!h.keep)?await t.addBytes(l,we(rt(await f.text(l),s.styles,(s.newDxfs??[]).map(ke),s),s.customStyles)):await t.copyRaw(f,f.entry(l)),p.add(l))}function vs(t,e,s){const a=(s.tables??[]).map(l=>`<Override PartName="/${l.part}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/>`).join(""),c=re(s).map(l=>`<Override PartName="/${l.comments}" ContentType="${Ue}"/>`).join(""),n=t.map(l=>`<Override PartName="/${l}" ContentType="${Ee(l)}"/>`).join("");return`${O}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>${c?'<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>':""}${c}<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>${n}<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/><Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>${a}${e?`<Override PartName="/${W}" ContentType="${Be}"/>`:""}</Types>`}const Cs="application/vnd.ms-excel.sheet.macroEnabled.main+xml";function Is(t,e){if(!e)return t;const s=`<workbookPr codeName="${L(e)}"/>`;if(/<workbookPr\b/.test(t))return t.replace(/<workbookPr\b([^>]*?)(\/?)>/,(c,n,l)=>`<workbookPr${n.replace(/\scodeName="[^"]*"/,"")} codeName="${L(e)}"${l}>`);const a=/<(?:workbookProtection|bookViews|sheets)\b/.exec(t);return a?t.slice(0,a.index)+s+t.slice(a.index):t}function Ns(t,e){const s=L(e);return/<sheetPr\b/.test(t)?t.replace(/<sheetPr\b([^>]*?)(\/?)>/,(a,c,n)=>`<sheetPr${c.replace(/\scodeName="[^"]*"/,"")} codeName="${s}"${n}>`):t.replace(/(<worksheet\b[^>]*>)/,`$1<sheetPr codeName="${s}"/>`)}function Es(t){const e=t.sheets.map((l,p)=>`<sheet name="${L(l.name)}" sheetId="${p+1}"${l.veryHidden?' state="veryHidden"':l.hidden?' state="hidden"':""} r:id="rId${p+1}"/>`).join(""),s=t.definedNames?.length?`<definedNames>${t.definedNames.map(l=>`<definedName name="${T(l.name)}"${l.comment?` comment="${L(l.comment)}"`:""}${l.localSheetId!==void 0?` localSheetId="${l.localSheetId}"`:""}${l.hidden?' hidden="1"':""}>${T(l.text)}</definedName>`).join("")}</definedNames>`:"",a=is(t),c=t.date1904?'<workbookPr date1904="1"/>':"",n=t.formulasEdited?'<calcPr fullCalcOnLoad="1"/>':"";return qe(Pe(ye(`${O}<workbook xmlns="${q}" xmlns:r="${A}">${c}${a}<sheets>${e}</sheets>${s}${n}</workbook>`,t.printNames??[]),t.filterNames,t.sheets),t)}function As(t,e){const s=t.map((c,n)=>`<Relationship Id="rId${n+1}" Type="${A}/${Ne(c)?"chartsheet":"worksheet"}" Target="${c.slice(3)}"/>`).join(""),a=t.length;return`${O}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${s}<Relationship Id="rId${a+1}" Type="${A}/styles" Target="styles.xml"/><Relationship Id="rId${a+2}" Type="${A}/sharedStrings" Target="sharedStrings.xml"/>${e?`<Relationship Id="rId${a+3}" Type="${A}/sheetMetadata" Target="metadata.xml"/>`:""}</Relationships>`}export{ct as MAX_COLS,pa as writeXlsx};
package/io/xml-scan.js CHANGED
@@ -1 +1,2 @@
1
- const y=new TextDecoder;class C{constructor(i){this.h=i,this.carry=null,this.stopped=!1,this.rest=null}feed(i){let e=i;this.carry!==null&&(e=new Uint8Array(this.carry.length+i.length),e.set(this.carry,0),e.set(i,this.carry.length),this.carry=null);const s=this.h,t=e.length;let r=0;for(;r<t;){if(e[r]!==60){const o=e.indexOf(60,r);if(o<0)break;s.text(e,r,o),r=o;continue}if(r+1>=t)break;const f=e[r+1];if(f===47){const o=e.indexOf(62,r+2);if(o<0)break;let d=r+2,p=o;for(;p>d&&e[p-1]<=32;)p--;for(let x=d;x<p;x++)if(e[x]===58){d=x+1;break}if(s.close(e,d,p),r=o+1,this.stopped){this.rest=e.subarray(r);return}continue}if(f===33){if(r+3>=t)break;if(e[r+2]===91){const o=k(e,A,r+9);if(o<0)break;s.text(e,r+9,o),r=o+3}else if(e[r+2]===45){const o=k(e,I,r+4);if(o<0)break;r=o+3}else{const o=e.indexOf(62,r+2);if(o<0)break;r=o+1}continue}if(f===63){const o=k(e,_,r+2);if(o<0)break;r=o+2;continue}let c=r+1,h=c,l=0;for(;c<t&&(l=e[c],!(l<=32||l===62||l===47));c++)l===58&&(h=c+1);if(c>=t)break;const a=c;let u=0;for(;c<t;c++)if(l=e[c],u!==0)l===u&&(u=0);else if(l===34||l===39)u=l;else if(l===62)break;if(c>=t)break;const w=e[c-1]===47;if(s.open(e,h,a,a,w?c-1:c,w),r=c+1,this.stopped){this.rest=e.subarray(r);return}}r<t&&(this.carry=e.slice(r))}}const A=[93,93,62],I=[45,45,62],_=[63,62];function k(n,i,e){const s=i[0];let t=n.indexOf(s,e);for(;t>=0;){let r=t+i.length<=n.length;for(let f=1;r&&f<i.length;f++)r=n[t+f]===i[f];if(r)return t;t=n.indexOf(s,t+1)}return-1}function T(n,i,e,s){if(e-i!==s.length)return!1;for(let t=0;t<s.length;t++)if(n[i+t]!==s.charCodeAt(t))return!1;return!0}function g(n,i,e){let s=!0;for(let t=i;t<e;t++)if(n[t]>=128){s=!1;break}return s&&e-i<4096?String.fromCharCode.apply(null,n.subarray(i,e)):y.decode(n.subarray(i,e))}const m={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function O(n){return n.indexOf("&")<0?n:n.replace(/&(#x[0-9a-fA-F]+|#\d+|[a-zA-Z]+);/g,(i,e)=>{if(e[0]==="#"){const s=e[1]==="x"?parseInt(e.slice(2),16):parseInt(e.slice(1),10);return String.fromCodePoint(s)}return m[e]??i})}function E(n){return typeof n!="string"||n.indexOf("_x")<0?n:n.replace(/_x([0-9A-Fa-f]{4})_/g,(i,e)=>String.fromCharCode(parseInt(e,16)))}function D(n){return E(O(n))}function S(n,i,e){const s={};let t=i;for(;t<e;){for(;t<e&&n[t]<=32;)t++;if(t>=e)break;let r=t;for(;t<e&&n[t]!==61&&n[t]>32;)n[t]===58&&(r=t+1),t++;const f=t;for(;t<e&&n[t]!==34&&n[t]!==39;)t++;if(t>=e)break;const c=n[t++],h=t,l=n.indexOf(c,t),a=l<0||l>e?e:l;s[g(n,r,f)]=O(g(n,h,a)),t=a+1}return s}function N(n){const i={n:"#root",a:{},c:[],t:""},e=[i];return new C({open(t,r,f,c,h,l){const a={n:g(t,r,f),a:S(t,c,h),c:[],t:""};e[e.length-1].c.push(a),l||e.push(a)},close(){e.length>1&&e.pop()},text(t,r,f){e[e.length-1].t+=O(g(t,r,f))}}).feed(n),i.c[0]??i}const q=(n,i)=>n?.c.find(e=>e.n===i),X=(n,i)=>n?n.c.filter(e=>e.n===i):[];export{C as XmlScanner,q as child,X as children,g as decodeRange,k as indexOfSeq,T as nameIs,S as parseAttrs,N as parseTree,E as unescapeOoxml,O as unescapeXml,D as unescapeXstring};
1
+ const y=new TextDecoder;class C{constructor(i){this.h=i,this.carry=null,this.stopped=!1,this.rest=null}feed(i){let e=i;this.carry!==null&&(e=new Uint8Array(this.carry.length+i.length),e.set(this.carry,0),e.set(i,this.carry.length),this.carry=null);const s=this.h,t=e.length;let r=0;for(;r<t;){if(e[r]!==60){const o=e.indexOf(60,r);if(o<0)break;s.text(e,r,o),r=o;continue}if(r+1>=t)break;const f=e[r+1];if(f===47){const o=e.indexOf(62,r+2);if(o<0)break;let d=r+2,p=o;for(;p>d&&e[p-1]<=32;)p--;for(let g=d;g<p;g++)if(e[g]===58){d=g+1;break}if(s.close(e,d,p),r=o+1,this.stopped){this.rest=e.subarray(r);return}continue}if(f===33){if(r+3>=t)break;if(e[r+2]===91){const o=k(e,A,r+9);if(o<0)break;s.text(e,r+9,o),r=o+3}else if(e[r+2]===45){const o=k(e,I,r+4);if(o<0)break;r=o+3}else{const o=e.indexOf(62,r+2);if(o<0)break;r=o+1}continue}if(f===63){const o=k(e,_,r+2);if(o<0)break;r=o+2;continue}let c=r+1,h=c,l=0;for(;c<t&&(l=e[c],!(l<=32||l===62||l===47));c++)l===58&&(h=c+1);if(c>=t)break;const a=c;let u=0;for(;c<t;c++)if(l=e[c],u!==0)l===u&&(u=0);else if(l===34||l===39)u=l;else if(l===62)break;if(c>=t)break;const w=e[c-1]===47;if(s.open(e,h,a,a,w?c-1:c,w),r=c+1,this.stopped){this.rest=e.subarray(r);return}}r<t&&(this.carry=e.slice(r))}}const A=[93,93,62],I=[45,45,62],_=[63,62];function k(n,i,e){const s=i[0];let t=n.indexOf(s,e);for(;t>=0;){let r=t+i.length<=n.length;for(let f=1;r&&f<i.length;f++)r=n[t+f]===i[f];if(r)return t;t=n.indexOf(s,t+1)}return-1}function T(n,i,e,s){if(e-i!==s.length)return!1;for(let t=0;t<s.length;t++)if(n[i+t]!==s.charCodeAt(t))return!1;return!0}function x(n,i,e){let s=!0;for(let t=i;t<e;t++)if(n[t]>=128){s=!1;break}return s&&e-i<4096?String.fromCharCode.apply(null,n.subarray(i,e)):y.decode(n.subarray(i,e))}const m={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function O(n){return n.includes("\r")&&(n=n.replace(/\r\n?/g,`
2
+ `)),n.indexOf("&")<0?n:n.replace(/&(#x[0-9a-fA-F]+|#\d+|[a-zA-Z]+);/g,(i,e)=>{if(e[0]==="#"){const s=e[1]==="x"?parseInt(e.slice(2),16):parseInt(e.slice(1),10);return String.fromCodePoint(s)}return m[e]??i})}function E(n){return typeof n!="string"||n.indexOf("_x")<0?n:n.replace(/_x([0-9A-Fa-f]{4})_/g,(i,e)=>String.fromCharCode(parseInt(e,16)))}function D(n){return E(O(n))}function S(n,i,e){const s={};let t=i;for(;t<e;){for(;t<e&&n[t]<=32;)t++;if(t>=e)break;let r=t;for(;t<e&&n[t]!==61&&n[t]>32;)n[t]===58&&(r=t+1),t++;const f=t;for(;t<e&&n[t]!==34&&n[t]!==39;)t++;if(t>=e)break;const c=n[t++],h=t,l=n.indexOf(c,t),a=l<0||l>e?e:l;s[x(n,r,f)]=O(x(n,h,a)),t=a+1}return s}function N(n){const i={n:"#root",a:{},c:[],t:""},e=[i];return new C({open(t,r,f,c,h,l){const a={n:x(t,r,f),a:S(t,c,h),c:[],t:""};e[e.length-1].c.push(a),l||e.push(a)},close(){e.length>1&&e.pop()},text(t,r,f){e[e.length-1].t+=O(x(t,r,f))}}).feed(n),i.c[0]??i}const q=(n,i)=>n?.c.find(e=>e.n===i),X=(n,i)=>n?n.c.filter(e=>e.n===i):[];export{C as XmlScanner,q as child,X as children,x as decodeRange,k as indexOfSeq,T as nameIs,S as parseAttrs,N as parseTree,E as unescapeOoxml,O as unescapeXml,D as unescapeXstring};
package/io/zip-reader.js CHANGED
@@ -1 +1 @@
1
- const T=101010256,Z=117853008,V=101075792,_=33639248,y=new TextDecoder;async function p(i,t,e){return new Uint8Array(await i.slice(t,e).arrayBuffer())}const w=(i,t)=>i.getUint32(t,!0)+i.getUint32(t+4,!0)*2**32;class R{constructor(t,e){this.blob=t,this.entries=e}has(t){return this.entries.has(t)}async stream(t){const e=this.entries.get(t);if(!e)throw new Error(`Missing ZIP entry: ${t}`);const a=await this.rawStream(e);if(e.method===0)return a;if(e.method!==8)throw new Error(`Unsupported compression method ${e.method} in ${t}`);return a.pipeThrough(new DecompressionStream("deflate-raw"))}async rawStream(t){const e=await this._dataStart(t);return this.blob.slice(e,e+t.compressedSize).stream()}async _dataStart(t){if(t.dataStart===void 0){const e=await p(this.blob,t.headerOffset,t.headerOffset+30),a=new DataView(e.buffer);if(a.getUint32(0,!0)!==67324752)throw new Error(`Bad local header for ${t.name}`);t.dataStart=t.headerOffset+30+a.getUint16(26,!0)+a.getUint16(28,!0)}return t.dataStart}async bytes(t){const e=(await this.stream(t)).getReader(),a=[];let f=0;for(;;){const{done:c,value:d}=await e.read();if(c)break;a.push(d),f+=d.length}const o=new Uint8Array(f);let l=0;for(const c of a)o.set(c,l),l+=c.length;return o}async text(t){return y.decode(await this.bytes(t))}}async function $(i){const t=i.size,e=Math.max(0,t-65557),a=await p(i,e,t),f=new DataView(a.buffer);let o=-1;for(let s=a.length-22;s>=0;s--)if(f.getUint32(s,!0)===101010256){o=s;break}if(o<0)throw new Error("Not a ZIP file (no end of central directory record)");let l=f.getUint16(o+10,!0),c=f.getUint32(o+12,!0),d=f.getUint32(o+16,!0);if(l===65535||c===4294967295||d===4294967295){const s=o-20;if(s>=0&&f.getUint32(s,!0)===117853008){const m=w(f,s+8),g=await p(i,m,m+56),u=new DataView(g.buffer);if(u.getUint32(0,!0)!==101075792)throw new Error("Bad ZIP64 end of central directory");l=w(u,32),c=w(u,40),d=w(u,48)}}const x=await p(i,d,d+c),r=new DataView(x.buffer),E=new Map;let n=0;for(;n+46<=x.length&&r.getUint32(n,!0)===33639248;){const s=r.getUint16(n+10,!0),m=r.getUint32(n+16,!0);let g=r.getUint32(n+20,!0),u=r.getUint32(n+24,!0);const b=r.getUint16(n+28,!0),C=r.getUint16(n+30,!0),z=r.getUint16(n+32,!0);let O=r.getUint32(n+42,!0);const D=y.decode(x.subarray(n+46,n+46+b));let h=n+46+b;const S=h+C;for(;h+4<=S;){const A=r.getUint16(h,!0),L=r.getUint16(h+2,!0);if(A===1){let U=h+4;u===4294967295&&(u=w(r,U),U+=8),g===4294967295&&(g=w(r,U),U+=8),O===4294967295&&(O=w(r,U))}h+=4+L}E.set(D,{name:D,method:s,crc:m,compressedSize:g,size:u,headerOffset:O}),n=S+z}return new R(i,E)}export{R as ZipReader,$ as openZip};
1
+ const T=101010256,Z=117853008,M=101075792,V=33639248,D=new TextDecoder;async function E(a,t,e){return new Uint8Array(await a.slice(t,e).arrayBuffer())}const h=(a,t)=>a.getUint32(t,!0)+a.getUint32(t+4,!0)*2**32;class R{constructor(t,e){this.blob=t,this.entries=e,this.foldedEntries=null}has(t){return this.entry(t)!==void 0}entry(t){const e=this.entries.get(t);if(e||typeof t!="string")return e;if(!this.foldedEntries){this.foldedEntries=new Map;for(const[r,f]of this.entries){const i=r.toLowerCase();this.foldedEntries.set(i,this.foldedEntries.has(i)?void 0:f)}}return this.foldedEntries.get(t.toLowerCase())}async stream(t){const e=this.entry(t);if(!e)throw new Error(`Missing ZIP entry: ${t}`);const r=await this.rawStream(e);if(e.method===0)return r;if(e.method!==8)throw new Error(`Unsupported compression method ${e.method} in ${t}`);return r.pipeThrough(new DecompressionStream("deflate-raw"))}async rawStream(t){const e=await this._dataStart(t);return this.blob.slice(e,e+t.compressedSize).stream()}async _dataStart(t){if(t.dataStart===void 0){const e=await E(this.blob,t.headerOffset,t.headerOffset+30),r=new DataView(e.buffer);if(r.getUint32(0,!0)!==67324752)throw new Error(`Bad local header for ${t.name}`);t.dataStart=t.headerOffset+30+r.getUint16(26,!0)+r.getUint16(28,!0)}return t.dataStart}async bytes(t){const e=(await this.stream(t)).getReader(),r=[];let f=0;for(;;){const{done:c,value:u}=await e.read();if(c)break;r.push(u),f+=u.length}const i=new Uint8Array(f);let l=0;for(const c of r)i.set(c,l),l+=c.length;return i}async text(t){return D.decode(await this.bytes(t))}}async function _(a){const t=a.size,e=Math.max(0,t-65557),r=await E(a,e,t),f=new DataView(r.buffer);let i=-1;for(let o=r.length-22;o>=0;o--)if(f.getUint32(o,!0)===101010256){i=o;break}if(i<0)throw new Error("Not a ZIP file (no end of central directory record)");let l=f.getUint16(i+10,!0),c=f.getUint32(i+12,!0),u=f.getUint32(i+16,!0);if(l===65535||c===4294967295||u===4294967295){const o=i-20;if(o>=0&&f.getUint32(o,!0)===117853008){const p=h(f,o+8),g=await E(a,p,p+56),d=new DataView(g.buffer);if(d.getUint32(0,!0)!==101075792)throw new Error("Bad ZIP64 end of central directory");l=h(d,32),c=h(d,40),u=h(d,48)}}const x=await E(a,u,u+c),n=new DataView(x.buffer),y=new Map;let s=0;for(;s+46<=x.length&&n.getUint32(s,!0)===33639248;){const o=n.getUint16(s+10,!0),p=n.getUint32(s+16,!0);let g=n.getUint32(s+20,!0),d=n.getUint32(s+24,!0);const O=n.getUint16(s+28,!0),S=n.getUint16(s+30,!0),L=n.getUint16(s+32,!0);let m=n.getUint32(s+42,!0);const b=D.decode(x.subarray(s+46,s+46+O));let w=s+46+O;const C=w+S;for(;w+4<=C;){const z=n.getUint16(w,!0),A=n.getUint16(w+2,!0);if(z===1){let U=w+4;d===4294967295&&(d=h(n,U),U+=8),g===4294967295&&(g=h(n,U),U+=8),m===4294967295&&(m=h(n,U))}w+=4+A}y.set(b,{name:b,method:o,crc:p,compressedSize:g,size:d,headerOffset:m}),s=C+L}return new R(a,y)}export{R as ZipReader,_ as openZip};