@allyhub/sdk 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/node_modules/@allyhub/audio/dist/plan.d.ts +3 -0
  3. package/dist/node_modules/@allyhub/audio/dist/render.js +1 -1
  4. package/dist/node_modules/@allyhub/audio/package.json +1 -1
  5. package/dist/node_modules/@allyhub/chart/dist/chart-file.d.ts +2 -0
  6. package/dist/node_modules/@allyhub/chart/dist/chart-file.js +1 -1
  7. package/dist/node_modules/@allyhub/chart/dist/chart-xml.js +3 -2
  8. package/dist/node_modules/@allyhub/chart/dist/chart.d.ts +5 -12
  9. package/dist/node_modules/@allyhub/chart/dist/chart.js +2 -1
  10. package/dist/node_modules/@allyhub/chart/dist/color.d.ts +37 -0
  11. package/dist/node_modules/@allyhub/chart/dist/color.js +2 -0
  12. package/dist/node_modules/@allyhub/chart/dist/index.d.ts +1 -0
  13. package/dist/node_modules/@allyhub/chart/dist/index.js +1 -1
  14. package/dist/node_modules/@allyhub/chart/dist/svg.js +1 -1
  15. package/dist/node_modules/@allyhub/chart/package.json +1 -1
  16. package/dist/node_modules/@allyhub/diagnostics/package.json +1 -1
  17. package/dist/node_modules/@allyhub/formats/dist/data/deck-code.d.ts +130 -0
  18. package/dist/node_modules/@allyhub/formats/dist/data/deck-code.js +1 -1
  19. package/dist/node_modules/@allyhub/formats/dist/data/gen.d.ts +3 -1
  20. package/dist/node_modules/@allyhub/formats/dist/data/gen.js +1 -1
  21. package/dist/node_modules/@allyhub/formats/dist/data/sheet.d.ts +512 -166
  22. package/dist/node_modules/@allyhub/formats/dist/data/sheet.js +1 -1
  23. package/dist/node_modules/@allyhub/formats/dist/data/slides.d.ts +2523 -136
  24. package/dist/node_modules/@allyhub/formats/dist/data/slides.js +1 -1
  25. package/dist/node_modules/@allyhub/formats/dist/files.d.ts +9 -2
  26. package/dist/node_modules/@allyhub/formats/dist/files.js +1 -1
  27. package/dist/node_modules/@allyhub/formats/dist/note-shape.d.ts +9 -0
  28. package/dist/node_modules/@allyhub/formats/dist/note-shape.js +1 -1
  29. package/dist/node_modules/@allyhub/formats/dist/schemas.d.ts +931 -87
  30. package/dist/node_modules/@allyhub/formats/dist/schemas.js +1 -1
  31. package/dist/node_modules/@allyhub/formats/package.json +1 -1
  32. package/dist/node_modules/@allyhub/image-draw/package.json +1 -1
  33. package/dist/node_modules/@allyhub/image-measure/package.json +1 -1
  34. package/dist/node_modules/@allyhub/image-sdk/package.json +1 -1
  35. package/dist/node_modules/@allyhub/measure/package.json +1 -1
  36. package/dist/node_modules/@allyhub/ooxml/dist/color.d.ts +11 -0
  37. package/dist/node_modules/@allyhub/ooxml/dist/color.js +1 -1
  38. package/dist/node_modules/@allyhub/ooxml/dist/ext.d.ts +43 -0
  39. package/dist/node_modules/@allyhub/ooxml/dist/ext.js +1 -1
  40. package/dist/node_modules/@allyhub/ooxml/dist/index.d.ts +2 -1
  41. package/dist/node_modules/@allyhub/ooxml/dist/index.js +1 -1
  42. package/dist/node_modules/@allyhub/ooxml/dist/transform.d.ts +13 -0
  43. package/dist/node_modules/@allyhub/ooxml/dist/transform.js +2 -0
  44. package/dist/node_modules/@allyhub/ooxml/package.json +5 -1
  45. package/dist/node_modules/@allyhub/piece/dist/gen.d.ts +4 -4
  46. package/dist/node_modules/@allyhub/piece/dist/media.d.ts +2 -2
  47. package/dist/node_modules/@allyhub/piece/package.json +1 -1
  48. package/dist/node_modules/@allyhub/protocol/dist/account.d.ts +35 -0
  49. package/dist/node_modules/@allyhub/protocol/dist/account.js +1 -1
  50. package/dist/node_modules/@allyhub/protocol/dist/cloud.d.ts +19 -0
  51. package/dist/node_modules/@allyhub/protocol/dist/cloud.js +1 -1
  52. package/dist/node_modules/@allyhub/protocol/dist/editor.d.ts +35 -20
  53. package/dist/node_modules/@allyhub/protocol/dist/editor.js +1 -1
  54. package/dist/node_modules/@allyhub/protocol/dist/events.d.ts +3 -3
  55. package/dist/node_modules/@allyhub/protocol/dist/frame.d.ts +28 -2
  56. package/dist/node_modules/@allyhub/protocol/dist/frame.js +1 -1
  57. package/dist/node_modules/@allyhub/protocol/dist/jobs.d.ts +6 -6
  58. package/dist/node_modules/@allyhub/protocol/dist/snapshots.d.ts +73 -10
  59. package/dist/node_modules/@allyhub/protocol/dist/snapshots.js +1 -1
  60. package/dist/node_modules/@allyhub/protocol/dist/tools.d.ts +45 -9
  61. package/dist/node_modules/@allyhub/protocol/dist/tools.js +1 -1
  62. package/dist/node_modules/@allyhub/protocol/package.json +1 -1
  63. package/dist/node_modules/@allyhub/runtimes/package.json +1 -1
  64. package/dist/node_modules/@allyhub/scenery/package.json +1 -1
  65. package/dist/node_modules/@allyhub/sheet/dist/annotations.d.ts +14 -0
  66. package/dist/node_modules/@allyhub/sheet/dist/annotations.js +2 -0
  67. package/dist/node_modules/@allyhub/sheet/dist/api/capabilities.js +1 -1
  68. package/dist/node_modules/@allyhub/sheet/dist/api/index.d.ts +1 -1
  69. package/dist/node_modules/@allyhub/sheet/dist/api/index.js +1 -1
  70. package/dist/node_modules/@allyhub/sheet/dist/api/rules.d.ts +24 -0
  71. package/dist/node_modules/@allyhub/sheet/dist/api/rules.js +1 -1
  72. package/dist/node_modules/@allyhub/sheet/dist/api/styles.d.ts +12 -0
  73. package/dist/node_modules/@allyhub/sheet/dist/api/styles.js +1 -1
  74. package/dist/node_modules/@allyhub/sheet/dist/api/workbook.d.ts +3 -1
  75. package/dist/node_modules/@allyhub/sheet/dist/api/workbook.js +1 -1
  76. package/dist/node_modules/@allyhub/sheet/dist/arrange.d.ts +28 -1
  77. package/dist/node_modules/@allyhub/sheet/dist/arrange.js +1 -1
  78. package/dist/node_modules/@allyhub/sheet/dist/data-tools.d.ts +42 -0
  79. package/dist/node_modules/@allyhub/sheet/dist/data-tools.js +2 -0
  80. package/dist/node_modules/@allyhub/sheet/dist/edit.d.ts +43 -2
  81. package/dist/node_modules/@allyhub/sheet/dist/edit.js +1 -1
  82. package/dist/node_modules/@allyhub/sheet/dist/fill.d.ts +10 -0
  83. package/dist/node_modules/@allyhub/sheet/dist/fill.js +1 -1
  84. package/dist/node_modules/@allyhub/sheet/dist/filter.js +1 -1
  85. package/dist/node_modules/@allyhub/sheet/dist/formula/rewrite.d.ts +14 -0
  86. package/dist/node_modules/@allyhub/sheet/dist/formula/rewrite.js +1 -1
  87. package/dist/node_modules/@allyhub/sheet/dist/html.js +10 -10
  88. package/dist/node_modules/@allyhub/sheet/dist/index.d.ts +6 -1
  89. package/dist/node_modules/@allyhub/sheet/dist/index.js +1 -1
  90. package/dist/node_modules/@allyhub/sheet/dist/outline.d.ts +30 -0
  91. package/dist/node_modules/@allyhub/sheet/dist/outline.js +2 -0
  92. package/dist/node_modules/@allyhub/sheet/dist/rich.d.ts +29 -0
  93. package/dist/node_modules/@allyhub/sheet/dist/rich.js +2 -0
  94. package/dist/node_modules/@allyhub/sheet/dist/rules.js +1 -1
  95. package/dist/node_modules/@allyhub/sheet/dist/table-style.d.ts +6 -0
  96. package/dist/node_modules/@allyhub/sheet/dist/table-style.js +1 -1
  97. package/dist/node_modules/@allyhub/sheet/dist/table-styles.js +1 -1
  98. package/dist/node_modules/@allyhub/sheet/dist/workbook.d.ts +5 -1
  99. package/dist/node_modules/@allyhub/sheet/dist/workbook.js +1 -1
  100. package/dist/node_modules/@allyhub/sheet/dist/xlsx/charts.js +1 -1
  101. package/dist/node_modules/@allyhub/sheet/dist/xlsx/import.js +1 -1
  102. package/dist/node_modules/@allyhub/sheet/dist/xlsx/read.d.ts +17 -1
  103. package/dist/node_modules/@allyhub/sheet/dist/xlsx/read.js +2 -2
  104. package/dist/node_modules/@allyhub/sheet/dist/xlsx/runs.d.ts +56 -0
  105. package/dist/node_modules/@allyhub/sheet/dist/xlsx/runs.js +2 -0
  106. package/dist/node_modules/@allyhub/sheet/dist/xlsx/styles.d.ts +6 -0
  107. package/dist/node_modules/@allyhub/sheet/dist/xlsx/styles.js +1 -1
  108. package/dist/node_modules/@allyhub/sheet/dist/xlsx/write.js +1 -1
  109. package/dist/node_modules/@allyhub/sheet/package.json +1 -1
  110. package/dist/node_modules/@allyhub/slides-core/dist/animation.d.ts +117 -21
  111. package/dist/node_modules/@allyhub/slides-core/dist/animation.js +1 -1
  112. package/dist/node_modules/@allyhub/slides-core/dist/api.d.ts +181 -30
  113. package/dist/node_modules/@allyhub/slides-core/dist/api.js +3 -3
  114. package/dist/node_modules/@allyhub/slides-core/dist/capabilities.js +1 -1
  115. package/dist/node_modules/@allyhub/slides-core/dist/chart-api.d.ts +28 -2
  116. package/dist/node_modules/@allyhub/slides-core/dist/chart-api.js +1 -1
  117. package/dist/node_modules/@allyhub/slides-core/dist/check.js +1 -1
  118. package/dist/node_modules/@allyhub/slides-core/dist/enums.d.ts +222 -4
  119. package/dist/node_modules/@allyhub/slides-core/dist/enums.js +1 -1
  120. package/dist/node_modules/@allyhub/slides-core/dist/file.d.ts +6 -0
  121. package/dist/node_modules/@allyhub/slides-core/dist/file.js +3 -3
  122. package/dist/node_modules/@allyhub/slides-core/dist/generated/table-styles.d.ts +3 -0
  123. package/dist/node_modules/@allyhub/slides-core/dist/generated/table-styles.js +2 -0
  124. package/dist/node_modules/@allyhub/slides-core/dist/index.d.ts +3 -0
  125. package/dist/node_modules/@allyhub/slides-core/dist/index.js +1 -1
  126. package/dist/node_modules/@allyhub/slides-core/dist/merge.js +1 -1
  127. package/dist/node_modules/@allyhub/slides-core/dist/model.d.ts +98 -10
  128. package/dist/node_modules/@allyhub/slides-core/dist/numbering.d.ts +6 -0
  129. package/dist/node_modules/@allyhub/slides-core/dist/numbering.js +2 -0
  130. package/dist/node_modules/@allyhub/slides-core/dist/office.d.ts +53 -0
  131. package/dist/node_modules/@allyhub/slides-core/dist/office.js +1 -1
  132. package/dist/node_modules/@allyhub/slides-core/dist/patterns.d.ts +8 -0
  133. package/dist/node_modules/@allyhub/slides-core/dist/patterns.js +2 -0
  134. package/dist/node_modules/@allyhub/slides-core/dist/resolve.d.ts +36 -6
  135. package/dist/node_modules/@allyhub/slides-core/dist/resolve.js +1 -1
  136. package/dist/node_modules/@allyhub/slides-core/dist/script.d.ts +11 -0
  137. package/dist/node_modules/@allyhub/slides-core/dist/script.js +2 -2
  138. package/dist/node_modules/@allyhub/slides-core/dist/sdk.d.ts +1 -1
  139. package/dist/node_modules/@allyhub/slides-core/dist/sdk.js +1 -1
  140. package/dist/node_modules/@allyhub/slides-core/dist/table-style.d.ts +48 -0
  141. package/dist/node_modules/@allyhub/slides-core/dist/table-style.js +2 -0
  142. package/dist/node_modules/@allyhub/slides-core/package.json +1 -1
  143. package/dist/node_modules/@allyhub/video-core/dist/mix-plan.js +1 -1
  144. package/dist/node_modules/@allyhub/video-core/dist/timeline.d.ts +4 -0
  145. package/dist/node_modules/@allyhub/video-core/package.json +1 -1
  146. package/dist/node_modules/@allyhub/video-sdk/package.json +1 -1
  147. package/docs/defaults.md +78 -4
  148. package/docs/image.md +1 -1
  149. package/docs/pictures.md +1 -1
  150. package/docs/project.md +1 -1
  151. package/docs/sheets.md +19 -9
  152. package/docs/slides.md +30 -16
  153. package/docs/speech.md +1 -1
  154. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{SHEET_FILE as ie,SHEET_NOTE_AUTHOR as le,SHEET_PICTURE_HEIGHT as P,SHEET_SEPARATOR as fe}from"@allyhub/formats";import{cellName as $,columnLetter as M,contains as T,overlaps as z,rangeName as v,readAddress as ae,readArea as W}from"../address.js";import{rectangles as O}from"../api/rectangles.js";import{chartAfter as ce}from"../chart.js";import{analyse as ue}from"../calc/analyse.js";import{ITERATION_DEFAULTS as de}from"../calc/engine.js";import{FUNCTIONS as he}from"../calc/functions/index.js";import{checkWorkbook as me}from"../check.js";import{writeCsv as pe}from"@allyhub/formats";import{pictureSize as we}from"../files.js";import{isDateCode as N}from"../format.js";import{moveFormula as ge,relativeKey as ke}from"../formula/move.js";import{printFormula as S,sheetPrefix as B}from"../formula/print.js";import{mapNode as U,walk as R}from"../formula/walk.js";import{CellError as _,isoOfSerial as be,readTyped as I,writeTyped as H}from"../values.js";import{FormulaCell as V,validName as q}from"../workbook.js";import{writeYaml as ye}from"../write.js";import{readFileFormula as $e}from"./formula.js";import{hasDate as J}from"./numfmt.js";import{placesLine as F,readXlsx as xe}from"./read.js";import{LISTS_SHEET as Le}from"./write.js";const K=100,ve=.5,Y=1462,Z=64,X=1e4;export const COMPARE_TOLERANCE=1e-9;const G=f=>f.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/gu,"")||"rows",b=f=>{for(const e in f)if(Object.hasOwn(f,e))return!1;return!0},Q=(f,e)=>`${String(f)} ${e}${f===1?"":"s"}`,C=f=>({row:f.row,col:f.col});function ee(f){return f===""||f.length>255||/^[/\\]|^[A-Za-z]:|\\|\0/u.test(f)?!1:f.split("/").every(e=>e!==""&&e!=="."&&e!=="..")}class Se{cells;starts;first;constructor(e){let o=!0;for(let t=1;t<e.length&&o;t++){const n=e[t-1],i=e[t];n&&i&&(i.row<n.row||i.row===n.row&&i.col<=n.col)&&(o=!1)}if(!o){e.sort((t,n)=>t.row-n.row||t.col-n.col);for(let t=e.length-1;t>0;t--){const n=e[t-1],i=e[t];i&&n?.row===i.row&&n.col===i.col&&e.splice(t-1,1)}}this.cells=e;const s=e[0]?.row??0,l=e[e.length-1]?.row??-1;this.first=s,this.starts=new Int32Array(Math.max(0,l-s+2));let r=0;for(let t=0;t<this.starts.length;t++){for(;r<e.length&&(e[r]?.row??0)<s+t;)r++;this.starts[t]=r}}get(e,o){const s=e-this.first;if(s<0||s>=this.starts.length-1)return;let l=this.starts[s]??0,r=(this.starts[s+1]??0)-1;for(;l<=r;){const t=l+r>>1,n=this.cells[t];if(!n)return;if(n.col===o)return n;n.col<o?l=t+1:r=t-1}}}class te{list=[];add(e){this.list.push(e)}has(e,o){for(const s of this.list)if(T(s,e,o))return!0;return!1}}function oe(f,e){const o=e.toLowerCase();return U(f,s=>s.kind!=="structured"||s.table?.toLowerCase()!==o?s:Object.fromEntries(Object.entries(s).filter(([l])=>l!=="table")))}function Ce(f){const e=new Map;for(const s of f.sheets)for(const l of s.tables)l.totals>0&&e.set(l.name.toLowerCase(),{t:l,sheet:s.name});if(e.size===0)return;const o=(s,l)=>{const r=l.table===void 0?void 0:e.get(l.table.toLowerCase());if(!r||l.thisRow)return;const{t}=r,n=l.sections,i=n.includes("#All");if(!i&&!n.includes("#Totals"))return;const a=y=>t.columns.findIndex(x=>x.name.toLowerCase()===y.toLowerCase()),[c,u]=l.columns,d=c===void 0?0:a(c),m=c===void 0?t.columns.length-1:u===void 0?d:a(u);if(d<0||m<0)return;const p=i?t.ref.top:n.includes("#Data")?t.ref.top+t.headers:n.includes("#Headers")?t.ref.top:t.ref.bottom-t.totals+1,g=t.ref.bottom,h=t.ref.left+Math.min(d,m),w=t.ref.left+Math.max(d,m),k=p!==g||h!==w;return{kind:"ref",...r.sheet===s?{}:{sheet:r.sheet},col:{index:h,abs:!0},row:{index:p,abs:!0},...k?{col2:{index:w,abs:!0},row2:{index:g,abs:!0}}:{},range:k}};for(const s of f.sheets)for(const l of s.cells)l.node&&(l.node=U(l.node,r=>r.kind==="structured"?o(s.name,r)??r:r.kind==="unary"&&r.op==="@"&&r.arg.kind==="ref"&&!r.arg.range?r.arg:r))}const Ee=1e3;function ne(f){return f.headers===0?"has no header row":f.columns.length!==f.ref.right-f.ref.left+1||!q(f.name)?"cannot be held as a table":new Set(f.columns.map(e=>e.name.toLowerCase())).size===f.columns.length?void 0:"has two columns of one name"}function j(f,e,o){let s;const l=new Set;R(f,t=>{t.kind==="call"&&(t.name==="LET"||t.name==="LAMBDA")&&t.args.forEach(n=>{n.kind==="name"&&l.add(n.name.toLowerCase())})});const r=t=>l.has(t)||o===void 0||o.names.has(t)||o.tables.has(t);return R(f,t=>{s===void 0&&(t.kind==="call"&&!he.has(t.name)&&(r(t.written.toLowerCase())||(s=`no function ${t.name}`)),t.kind==="name"&&!r(t.name.toLowerCase())&&(s=`no name ${t.name}`),t.kind==="structured"&&t.table!==void 0&&!r(t.table.toLowerCase())&&(s=`no table ${t.table}`),(t.kind==="ref"||t.kind==="name"||t.kind==="error")&&t.sheet!==void 0&&(t.sheet.startsWith("[")?s="it reads another workbook":e.has(t.sheet.toLowerCase())||(s=`no sheet ${t.sheet}`)))}),s}function Me(f){const e=new Set(f.book.sheets.map(o=>o.name.toLowerCase()));for(const o of f.book.sheets){const s=new Map,l=(t,n)=>{const i=s.get(n),a=$(t);i?i.push(a):s.set(n,[a])},r=[];for(const t of o.cells){if(t.unread!==void 0){l(t,/^\[|[!']\[|\[\d+\]/u.test(t.unread)?"it reads another workbook":`it could not be read: ${t.unread}`);continue}if(!t.node)continue;const n=j(t.node,e,f);n!==void 0?(delete t.node,l(t,n)):(f.carried.set(t,o),t.array&&v(t.array)!==$(t)&&r.push(t))}Oe(f,o,r);for(const[t,n]of s)f.lost.push(`${o.name}: ${Q(n.length,"formula")} kept as ${n.length===1?"its value":"their values"}, as ${t} (${F(n)})`)}}function Oe(f,e,o){if(o.length===0)return;const s=new Set;for(const l of o){const{array:r}=l;if(r)for(const t of e.cells)t!==l&&!t.node&&T(r,t.row,t.col)&&s.add(t)}e.cells=e.cells.filter(l=>!s.has(l));for(const l of s)f.spilled.set(l,e)}function E(f,e){const{value:o}=e;if(!f.book.date1904||typeof o!="number")return o;const s=f.book.looks[e.style]?.format;return N(s)&&s!==void 0&&J(s)?o+Y:o}function D(f,e){if(typeof f!="number"||e===void 0||!N(e)||!J(e)||f<1)return;const o=be(f);return I(o).value===f?o:void 0}const _e=(f,e)=>D(f,e)??H(f??null);function se(f,e){const o=D(f,e);return o!==void 0?o:f==null?null:typeof f=="number"||typeof f=="boolean"?f:H(f)}function Ae(f){const e=[];for(let n=0;n<f.length;n++){const i=f[n];if(!i)continue;const a=e[e.length-1];a?.row===i.row&&a.right===i.col-1?(a.right=i.col,a.last=n):e.push({row:i.row,left:i.col,right:i.col,first:n,last:n})}const o=e.map((n,i)=>i),s=n=>{let i=n;for(;o[i]!==i;){const a=o[o[i]??i]??i;o[i]=a,i=a}return i};let l=0,r=0;for(let n=0;n<e.length;n++){const i=e[n];if(i){n>0&&e[n-1]?.row!==i.row&&(l=e[n-1]?.row===i.row-1?r:n,r=n);for(let a=l;a<r;a++){const c=e[a];c?.row===i.row-1&&c.right>=i.left&&c.left<=i.right&&(o[s(n)]=s(a))}}}const t=new Map;return e.forEach((n,i)=>{const a=s(i),c=t.get(a),u=n.right-n.left+1;c?(c.box.top=Math.min(c.box.top,n.row),c.box.bottom=Math.max(c.box.bottom,n.row),c.box.left=Math.min(c.box.left,n.left),c.box.right=Math.max(c.box.right,n.right),c.count+=u,c.runs.push(i)):t.set(a,{box:{top:n.row,bottom:n.row,left:n.left,right:n.right},count:u,runs:[i]})}),[...t.values()].map(n=>({box:n.box,count:n.count,cells:()=>n.runs.flatMap(i=>{const a=e[i];return a?f.slice(a.first,a.last+1):[]})}))}const re=f=>JSON.stringify(f);class Te{ctx;read;cells;inTables=new te;columnLooks=new Map;rowLooks=new Map;lookDone=new te;tables=[];areas=[];filtered=[];ownLooks=new Map;fileColumns=new Map;pictured=new Map;over=[];keys=new Map;constructor(e,o){this.ctx=e,this.read=o,this.cells=new Se(o.cells)}at(e,o){return this.cells.get(e,o)}look(e){return this.ctx.book.looks[e.style]??{}}code(e){return this.look(e).format}text(e){return e.node?S(e.node):_e(E(this.ctx,e),this.code(e))}baseLooks(){const{read:e}=this,{looks:o}=this.ctx.book;let s=-1;for(const r of e.cells)r.col>s&&(s=r.col);for(const r of e.columns){if(r.style===void 0)continue;const t=o[r.style];if(!(!t||b(t)))for(let n=r.min;n<=Math.min(r.max,s);n++)this.columnLooks.set(n,t)}for(const r of e.rows){const t=r.style===void 0?void 0:o[r.style];t&&!b(t)&&this.rowLooks.set(r.row,t)}const l=(r,t)=>{for(const n in t)if(!(n in r))return!1;return!0};for(const r of e.cells){const t=this.look(r),n=this.columnLooks.get(r.col);n&&!l(t,n)&&this.columnLooks.delete(r.col);const i=this.rowLooks.get(r.row);i&&!l(t,i)&&this.rowLooks.delete(r.row)}}ownLook(e){const o=this.columnLooks.get(e.col),s=this.rowLooks.get(e.row),l=this.look(e),r=l.format!==void 0&&N(l.format);if(!o&&!s&&!r){let a=this.ownLooks.get(e.style);return a||(a={look:l,key:re(l)},this.ownLooks.set(e.style,a)),a}const t={...o,...s},n={};for(const[a,c]of Object.entries(l))JSON.stringify(c)!==JSON.stringify(t[a])&&(n[a]=c);const i=n.format;if(typeof i=="string"){const a=e.node?void 0:D(E(this.ctx,e),i);a!==void 0&&I(a).format===i&&delete n.format}return{look:n,key:re(n)}}keyOf(e,o){if(e.key!==void 0)return e.key;const s=ke(o,e.row,e.col),l=this.keys.get(s);return l!==void 0?e.key=l:(this.keys.set(s,s),e.key=s)}columnFormula(e,o,s){const l=new Map,r=s-o+1;for(let n=o;n<=s;n++){const i=this.at(n,e);if(!i||i.value===void 0&&!i.node||i.value===null&&!i.node)return;if(!i.node)continue;const a=this.keyOf(i,i.node),c=l.get(a);c?c.n+=1:l.set(a,{n:1,cell:i})}let t;for(const n of l.values())(!t||n.n>t.n)&&(t=n);return t&&t.n*2>r?t.cell:void 0}csv(e,o){const s=[];for(let l=0;l<e;l+=X){const r=[];for(let t=l;t<Math.min(e,l+X);t++)r.push(o(t));s.push(pe(r))}return s.join("")}table(e){const{read:o,ctx:s}=this,l=h=>s.lost.push(`${o.name}: table ${e.name} ${h}`),r=e.ref.right-e.ref.left+1,t=ne(e);if(t!==void 0)return l(`${t}, so its cells are kept and it is no table`),!1;const n=e.ref.top,i=n+1;let a=e.ref.bottom-e.totals;if(e.totals===0){let h=n;for(const w of o.cells)w.col>=e.ref.left&&w.col<=e.ref.right&&w.row>h&&(h=w.row);a-h>Ee&&(l(`runs ${String(a-h)} empty rows past what it holds, which are left out`),a=h)}e.totals>0&&l("has a totals row, kept as plain cells under it");const c=e.columns.map((h,w)=>a>=i?this.columnFormula(e.ref.left+w,i,a):void 0),u=h=>{const w=c[h];if(!w)return!1;for(let k=i;k<=a;k++)if(this.at(k,e.ref.left+h)?.key!==w.key)return!1;return!0};let d=r;for(;d>1&&u(d-1);)d-=1;const m={},p=this.path(e.name);s.files.set(p,this.csv(a-i+2,h=>{if(h===0)return e.columns.slice(0,d).map(y=>y.name);const w=i+h-1,k=[];for(let y=0;y<d;y++){const x=this.at(w,e.ref.left+y),L=c[y];x?L&&x.key===L.key?k.push(""):x.node?k.push(S(oe(x.node,e.name))):k.push(this.text(x)):k.push("")}return k})),this.inTables.add({...e.ref,bottom:a}),e.columns.forEach((h,w)=>{const k=e.ref.left+w,y=this.columnLook(k,i,a),x=c[w];x?.node&&(y.formula=S(oe(ge(x.node,i-x.row,0),e.name)));const L=this.fileColumns.get(k);L!==void 0&&i<=a&&(y.files=L===P?!0:{height:L}),b(y)||(m[h.name]=y)});const g=new Map;for(const[h,w]of e.filter?.columns??[]){const k=e.columns[h]?.name;k!==void 0&&g.set(k,w)}return(e.filter?.unread??0)>0&&l(`has ${Q(e.filter?.unread??0,"filter")} by condition, its rows left as they were hidden`),this.tables.push({name:e.name,at:$({row:n,col:e.ref.left}),rows:p,...e.style!==void 0&&e.style!=="TableStyleMedium2"?{style:e.style}:{},...b(m)?{}:{columns:m},...e.filter===void 0?{filter:!1}:g.size>0?{filter:{columns:Object.fromEntries(g)}}:{}}),e.filter?.unread===0&&e.filter.columns.size>0&&this.filtered.push({...e.ref,bottom:a}),this.areas.push({...e.ref,bottom:a}),!0}columnLook(e,o,s){let l,r={};for(let t=o;t<=s;t++){const n=this.at(t,e),i=n?this.ownLook(n):{look:{},key:"{}"};if(l===void 0)l=i.key,r=i.look;else if(l!==i.key)return{}}return b(r)?{}:(this.lookDone.add({top:o,bottom:s,left:e,right:e}),{...r})}path(e){const o=G(e);let s=`${o}.csv`;for(let l=2;this.ctx.files.has(s)||this.ctx.taken(s);l++)s=`${o}-${String(l)}.csv`;return s}loose(){const e=[],o=[];for(const s of this.read.cells)this.inTables.has(s.row,s.col)||(s.node?e.push(s):s.value!==void 0&&s.value!==null&&o.push(s));return{formulas:e,typed:o}}blockAreas(e,o){const s=[],l=O(o.map(C)),r=n=>!s.some(i=>z(i,n))&&!this.areas.some(i=>z(i,n))&&!l.some(i=>z(i,n)),t=n=>(n.bottom-n.top+1)*(n.right-n.left+1);for(const n of Ae(e)){const{box:i}=n;if(!(t(i)<K)){if(n.count/t(i)>=ve&&r(i)){s.push(i);continue}for(const a of O(n.cells().map(C)))t(a)>=K&&r(a)&&s.push(a)}}return s.sort((n,i)=>n.top-i.top||n.left-i.left)}cells_(e){const{formulas:o,typed:s}=this.loose(),l=this.blockAreas(s,o),r=i=>l.some(a=>T(a,i.row,i.col));l.length>0&&(e.blocks=l.map(i=>{const a=this.path(this.read.name);return this.ctx.files.set(a,this.csv(i.bottom-i.top+1,c=>{const u=[];for(let d=i.left;d<=i.right;d++){const m=this.at(i.top+c,d);u.push(m?this.text(m):"")}return u})),{at:$({row:i.top,col:i.left}),rows:a}}));const t=[],n=new Map;for(const i of o){if(!i.node)continue;const a=this.keyOf(i,i.node),c=n.get(a);c?c.push(i):n.set(a,[i])}for(const i of n.values())for(const a of O(i.map(C))){const c=this.at(a.top,a.left);c?.node&&t.push([{row:a.top,col:a.left},v(a),S(c.node)])}for(const i of s)l.length>0&&r(i)||t.push([C(i),$(i),se(E(this.ctx,i),this.code(i))]);t.sort(([i],[a])=>i.row-a.row||i.col-a.col),t.length>0&&(e.cells=Object.fromEntries(t.map(([,i,a])=>[i,a])))}formats(e){const o=new Map,s=this.lookDone.list.length>0;for(const r of this.read.cells){if(s&&this.lookDone.has(r.row,r.col))continue;const t=this.ownLook(r);if(b(t.look))continue;const n=o.get(t.key);n?n.places.push(C(r)):o.set(t.key,{look:t.look,places:[C(r)]})}const l=[];for(const{look:r,places:t}of o.values())for(const n of O(t))l.push({range:v(n),...r});l.length>0&&(e.format=l)}columns(e){const{read:o}=this,s=new Map;let l=0;for(const t of o.cells)t.col>l&&(l=t.col);const r=[];for(const t of o.columns){if(t.width===void 0&&t.hidden!==!0&&t.level===void 0)continue;const n=t.max-Math.max(t.min,l+1)+1>Z?Math.max(l,t.min+Z-1):t.max;n<t.max&&r.push(`${M(n+1)}:${M(t.max)}`);const i=t.width!==void 0&&t.width<=0;for(let a=t.min;a<=n;a++)s.set(a,{...t.width===void 0||i?{}:{width:t.width},...t.hidden===!0||i?{hidden:!0}:{},...t.level===void 0?{}:{level:t.level}})}for(const[t,n]of this.columnLooks)s.set(t,{...s.get(t),...n});for(const[t,n]of this.fileColumns)this.tableColumn(t)||s.set(t,{...s.get(t),files:n===P?!0:{height:n}});s.size>0&&(e.columns=Object.fromEntries([...s.keys()].sort((t,n)=>t-n).map(t=>[M(t),s.get(t)??{}]))),r.length>0&&this.ctx.lost.push(`${o.name}: the size of columns ${F(r)}, past those that hold anything`)}tableColumn(e){return this.areas.some(o=>e>=o.left&&e<=o.right)}rows(e){const o={};for(const s of this.read.rows){const l=this.rowLooks.get(s.row),r=this.filtered.some(a=>s.row>a.top&&s.row<=a.bottom),t=s.height!==void 0&&this.pictured.get(s.row)!==s.height?s.height:void 0,n=t!==void 0&&t<=0,i={...t===void 0||n?{}:{height:t},...(s.hidden===!0||n)&&!r?{hidden:!0}:{},...s.level===void 0?{}:{level:s.level},...l};b(i)||(o[String(s.row+1)]=i)}b(o)||(e.rows=o)}assetPath(e,o){const s=t=>{const n=this.ctx.assets.get(t);return n?ze(n,o.bytes):!this.ctx.taken(t)};if(e!==void 0&&ee(e)&&s(e))return e;const l=G((o.name??"picture").replace(/\.[A-Za-z0-9]+$/u,""));let r=`${l}.${o.type}`;for(let t=2;!s(r);t++)r=`${l}-${String(t)}.${o.type}`;return r}pictures(){const e=this.over;for(const o of this.read.pictures){const s=this.at(o.row,o.col),l=typeof s?.value=="string"?s.value:"";if(o.y===void 0&&o.descr!==void 0&&ee(o.descr)&&l.split(fe).includes(o.descr)&&o.descr!==void 0){this.ctx.assets.set(o.descr,o.bytes),this.fileColumns.set(o.col,Math.max(this.fileColumns.get(o.col)??0,o.height)),this.pictured.set(o.row,Math.max(this.pictured.get(o.row)??0,o.height));continue}if(o.width<=0||o.height<=0){this.ctx.lost.push(`${this.read.name}: a picture of no size at ${$({row:o.row,col:o.col})}`);continue}const t=this.assetPath(o.descr,o);this.ctx.assets.set(t,o.bytes);const n=we(o.bytes),i=n?.width===o.width&&n.height===o.height;e.push({file:t,at:$({row:o.row,col:o.col}),...o.x===void 0?{}:{x:o.x},...o.y===void 0?{}:{y:o.y},...i?{}:{width:o.width,height:o.height}})}}build(){const{read:e}=this;this.baseLooks(),this.pictures();for(const s of e.tables)this.table(s);const o={name:e.name};return e.state!=="visible"&&(o.hidden=!0),e.gridlines===!1&&(o.gridlines=!1),e.tab!==void 0&&(o.tab=e.tab),e.state==="veryHidden"&&this.ctx.lost.push(`${e.name}: being very hidden; it is hidden`),e.freeze&&(e.freeze.row>0||e.freeze.col>0)&&(o.freeze=$(e.freeze)),this.tables.length>0&&(o.tables=this.tables),this.filter(o),this.columns(o),this.rows(o),this.cells_(o),e.merges.length>0&&(o.merges=e.merges.map(v)),this.formats(o),e.conditional.length>0&&(o.conditional=e.conditional),e.validations.length>0&&(o.validations=e.validations),e.charts.length>0&&(o.charts=e.charts.map(s=>this.chart(s))),this.over.length>0&&(o.pictures=this.over),b(e.links)||(o.links=e.links),e.notes.length>0&&(o.notes=Object.fromEntries(e.notes.map(s=>[s.ref,s.author===void 0||s.author===le?s.text:{text:s.text,author:s.author}]))),e.print&&(o.print=e.print),e.protect===!0&&(o.protect=!0),o}chart(e){return ce(e,o=>{const s=this.chartReference(o.replace(/^=/u,""));return o.startsWith("=")?`=${s}`:s})}chartReference(e){const o=e.lastIndexOf("!"),l=(o<0?this.read.name:e.slice(0,o)).replace(/^'|'$/gu,"").replaceAll("''","'"),r=W(e.slice(o+1).replaceAll("$",""));if(!r)return e;const t=this.ctx.book.sheets.find(n=>n.name.toLowerCase()===l.toLowerCase());for(const n of t?.tables??[]){const i=n.ref.top+1,c=r.left===r.right&&r.top===i&&r.bottom===n.ref.bottom&&r.left>=n.ref.left&&r.left<=n.ref.right?n.columns[r.left-n.ref.left]:void 0;if(c&&this.ctx.tables.has(n.name.toLowerCase()))return`${n.name}[${c.name}]`}return`${t===this.read||o<0?"":`${e.slice(0,o)}!`}${v(r)}`}filter(e){const{filter:o}=this.read;if(!o)return;const s={};for(const[l,r]of o.columns)s[M(o.ref.left+l)]=r;e.filter={range:v(o.ref),...b(s)?{}:{columns:s}},o.unread===0&&!b(s)&&this.filtered.push(o.ref)}}const ze=(f,e)=>f.length===e.length&&f.every((o,s)=>o===e[s]),Ne=new Set(["_xlnm._FilterDatabase","_xlnm.Print_Area","_xlnm.Print_Titles"]);function Re(f){const e={},o=[],s=new Map,{book:l,lost:r}=f,t=new Set(l.sheets.map(u=>u.name.toLowerCase())),n=new Set,i=[];let a;const c=u=>{a=void 0;const d=Fe(u.text);if(d!==void 0)return typeof d=="string"?H(d):d;const m=$e(u.text,!0),p=m.ok?j(m.node,t):"it could not be read";if(!m.ok||p!==void 0||He(m.node)){r.push(`the name ${u.name} (${u.text})${p===void 0?"":`: ${p}`}`);return}return a=m.node,S(m.node)};for(const u of l.names){if(u.name.startsWith("_xlnm.")){Ne.has(u.name)||r.push(`Excel's name ${u.name}`);continue}if(/^_xl(?:fn|pm|ws|udf)/iu.test(u.name))continue;const d=u.name.toLowerCase(),m=u.sheet===void 0?"":String(u.sheet);if(!q(u.name)||f.tables.has(d)){r.push(`the name ${u.name}, which cannot be held here`);continue}if(n.has(`${m}|${d}`)){r.push(`a second name ${u.name}${m===""?"":` of ${l.sheets[u.sheet??0]?.name??""}`}`);continue}const p=c(u);if(p===void 0)continue;n.add(`${m}|${d}`),f.names.add(d);const g=u.sheet===void 0?void 0:s.get(u.sheet)??{names:{},hidden:[]},h=g?.names??e;h[u.name]=p,u.hidden===!0&&(g?.hidden??o).push(u.name),g&&u.sheet!==void 0&&s.set(u.sheet,g),a&&i.push({held:h,n:u,node:a})}for(const{held:u,n:d,node:m}of i){const p=j(m,t,{names:f.names,tables:f.tables});p!==void 0&&(u[d.name]="=#NAME?",r.push(`the name ${d.name} (${d.text}): ${p}; it holds #NAME?, as in Excel`))}return{names:e,hidden:o,sheets:s}}function Ie(f,e){const o={},s=new Map;for(const[l,r]of Object.entries(e))typeof r=="string"&&r.startsWith("=")&&s.set(r.slice(1).replaceAll("$","").toLowerCase(),l);for(const l of f.book.sheets)for(const r of l.scenarios){const t={};let n=!0;for(const{at:i,value:a}of r.cells){const c=ae(i),u=c&&l.cells.find(p=>p.row===c.row&&p.col===c.col);String(u?.value??"")!==a&&(n=!1);const d=s.get(`${B(l.name)}${i}`.toLowerCase())??s.get(i.toLowerCase()),m=I(a);d===void 0?f.lost.push(`${l.name}: scenario ${r.name}'s cell ${i}, which has no name`):t[d]=typeof m.value=="number"?m.value:a}!n&&!b(t)&&(o[r.name]={...o[r.name],...t})}return o}function He(f){let e=!1;return R(f,o=>{e||=o.kind==="error"&&o.code==="#REF!"}),e}function Fe(f){const e=f.trim();return/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/u.test(e)?Number(e):/^true$/iu.test(e)?!0:/^false$/iu.test(e)?!1:/^"((?:[^"]|"")*)"$/u.exec(e)?.[1]?.replaceAll('""','"')}const je=new RegExp(`^${Le.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}(?: \\(\\d+\\))?$`,"u");function De(f){const e=f.sheets.find(r=>r.state==="veryHidden"&&je.test(r.name));if(!e)return;const o=B(e.name).toLowerCase(),s=r=>{const t=r.replace(/^=/u,"");if(!t.toLowerCase().startsWith(o))return;const n=W(t.slice(o.length).replaceAll("$",""));if(!n||n.left!==n.right)return;const i=[];for(let a=n.top;a<=n.bottom;a++){const c=e.cells.find(u=>u.row===a&&u.col===n.left);i.push(typeof c?.value=="string"?c.value:"")}return i};for(const r of f.sheets)r.validations=r.validations.map(t=>{const[n]=t.formula??[],i=t.type==="list"&&typeof n=="string"?s(n):void 0;if(!i)return t;const a={...t,values:i};return delete a.formula,a});const l=f.sheets.indexOf(e);f.sheets=f.sheets.filter(r=>r!==e),f.names=f.names.flatMap(r=>r.sheet===void 0||r.sheet<l?[r]:r.sheet===l?[]:[{...r,sheet:r.sheet-1}])}const A=f=>f instanceof _?f.code:f??null,Pe=new Map([["#SPILL!","#VALUE!"],["#CALC!","#VALUE!"]]);export function sameValue(f,e,o){if(typeof f=="number"&&typeof e=="number")return f===e?!0:Math.abs(f-e)<=Math.max(Math.abs(f),Math.abs(e))*o;if(f instanceof _||e instanceof _){const s=l=>l instanceof _?Pe.get(l.code)??l.code:void 0;return s(f)===s(e)}if(f===null||e===null){const s=f??e;return s===null||s===""||s===0||s===!1}return f===e}function We(f,e){const o=[];for(const r of e.sheets)for(const t of r.formulas)t.shared.node&&ue(e,t.shared,r).volatile&&o.push(t);const s=new Set(o),l=[...o];for(;;){const r=l.pop();if(!r)return s;for(const t of f.readers(r.sheet,r.row,r.col))s.has(t)||(s.add(t),l.push(t))}}function Be(f){const e=f.file.iteration;return(e===void 0||e===!0?void 0:e.max_change)??de.max_change}function Ue(f,e,o,s){const l={formulas:0,same:0,uncached:0,moving:0,differences:[]},r=We(o,e);for(const[t,n]of f.carried){if(!t.node)continue;const i=e.sheet(n.name);if(!i)continue;l.formulas+=1;const a=i.at(t.row,t.col);if(a instanceof V&&r.has(a)){l.moving+=1;continue}const c=E(f,t);if(c===void 0){l.uncached+=1;continue}const u=o.value(i,t.row,t.col);a instanceof V&&o.iterates(a)&&typeof c=="number"&&typeof u=="number"&&Math.abs(c-u)<=Be(e)||sameValue(c,u,s)?l.same+=1:l.differences.push({sheet:n.name,cell:$(t),formula:S(t.node),file:A(c),engine:A(u)})}for(const[t,n]of f.spilled){const i=e.sheet(n.name);if(!i)continue;l.formulas+=1;const a=i.spillAt(t.row,t.col);if(a&&r.has(a)){l.moving+=1;continue}const c=E(f,t),u=o.value(i,t.row,t.col);c===void 0?l.uncached+=1:sameValue(c,u,s)?l.same+=1:l.differences.push({sheet:n.name,cell:$(t),formula:a?`${$(a)}#`:"",file:A(c),engine:A(u)})}return l}function Ve(f,e){const o=new Map,s=[];for(const l of f){const r=e.find(i=>l.startsWith(`${i}: `));if(r===void 0){s.push(l);continue}const t=l.slice(r.length+2),n=o.get(t);n?n.push(r):o.set(t,[r])}for(const[l,r]of o)s.push(r.length===1?`${r[0]??""}: ${l}`:`${l}, on ${String(r.length)} sheets (${F(r)})`);return s}function qe(f,e,o){const s=o.circularCells();if(s.length===0)return!1;const l=new Map;for(const[n,i]of f.carried)l.set(`${i.name}|${String(n.row)}|${String(n.col)}`,n);let r=0,t=0;for(const n of s){const i=l.get(`${n.sheet.name}|${String(n.row)}|${String(n.col)}`),a=i===void 0?void 0:E(f,i),c=e[n.sheet.index],u=n.shared.source.path??[];if(a===void 0||!c||u[2]!=="cells"){a!==void 0&&(t+=1);continue}const d=se(a,void 0),m=c.cells??={},p=$(n),g=m[p],h=m[String(u[3])],w=h!==null&&typeof h=="object"?h:{};m[p]=g!==null&&typeof g=="object"?{...g,start:d}:{...w,formula:n.text,start:d},r+=1}return t>0&&f.lost.push(`where ${String(t)} cells of a table or a block start iterative calculation: they start from 0`),r>0}export function importXlsx(f,e){const o=xe(f,e.zip);if(De(o),Ce(o),o.sheets.length===0)throw new Error("It holds no sheets.");const s={book:o,taken:e.taken??(()=>!1),files:new Map,assets:new Map,lost:[...o.lost],tables:new Set(o.sheets.flatMap(p=>p.tables.filter(g=>ne(g)===void 0).map(g=>g.name.toLowerCase()))),names:new Set,carried:new Map,spilled:new Map};o.date1904&&s.lost.push(`the 1904 date system: dates are moved to the 1900 one, ${String(Y)} days on`),(o.font.name!==void 0&&o.font.name!=="Calibri"||o.font.size!==void 0&&o.font.size!==11)&&s.lost.push(`its default font, ${o.font.name??""} ${String(o.font.size??"")}`);const l=Re(s);Me(s);const r=o.sheets.map((p,g)=>{const h=new Te(s,p).build(),w=l.sheets.get(g);return w&&!b(w.names)&&(h.names=w.names),w&&w.hidden.length>0&&(h.hidden_names=w.hidden),h}),t=Ie(s,l.names),n={title:o.title??e.name,...b(l.names)?{}:{names:l.names},...l.hidden.length>0?{hidden_names:l.hidden}:{},sheets:r,...b(t)?{}:{scenarios:t},...o.iteration===void 0?{}:{iteration:o.iteration}},i=()=>{const p=ye(n),g=new Map([[ie,p],...s.files]);return{files:g,...me({text:p,read:h=>g.get(h),exists:h=>g.has(h)||s.assets.has(h)})}};let a=i();a.calc&&qe(s,r,a.calc)&&(a=i());const{files:c,workbook:u,calc:d,problems:m}=a;return{files:c,assets:s.assets,lost:Ve(s.lost,o.sheets.map(p=>p.name)),problems:m,compared:u&&d?Ue(s,u,d,e.tolerance??COMPARE_TOLERANCE):{formulas:0,same:0,uncached:0,moving:0,differences:[]},sheets:o.sheets.length,tables:s.tables.size}}
2
+ import{SHEET_FILE as ie,SHEET_NOTE_AUTHOR as le,SHEET_PICTURE_HEIGHT as W,SHEET_SEPARATOR as fe}from"@allyhub/formats";import{cellName as $,columnLetter as M,contains as z,overlaps as R,rangeName as v,readAddress as ae,readArea as B}from"../address.js";import{rectangles as O}from"../api/rectangles.js";import{chartAfter as ce}from"../chart.js";import{analyse as ue}from"../calc/analyse.js";import{ITERATION_DEFAULTS as he}from"../calc/engine.js";import{FUNCTIONS as de}from"../calc/functions/index.js";import{checkWorkbook as me}from"../check.js";import{writeCsv as pe}from"@allyhub/formats";import{pictureSize as we}from"../files.js";import{isDateCode as N}from"../format.js";import{moveFormula as ge,relativeKey as ke}from"../formula/move.js";import{printFormula as S,sheetPrefix as U}from"../formula/print.js";import{mapNode as V,walk as I}from"../formula/walk.js";import{CellError as _,isoOfSerial as be,readTyped as H,writeTyped as j}from"../values.js";import{joinedRuns as ye,plainRuns as $e}from"../rich.js";import{runsOver as xe}from"./runs.js";import{FormulaCell as q,validName as J}from"../workbook.js";import{writeYaml as Le}from"../write.js";import{readFileFormula as ve}from"./formula.js";import{hasDate as K}from"./numfmt.js";import{placesLine as A,readXlsx as Se}from"./read.js";import{LISTS_SHEET as Ce}from"./write.js";const Y=100,Ee=.5,Z=1462,X=64,G=1e4;export const COMPARE_TOLERANCE=1e-9;const Q=f=>f.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/gu,"")||"rows",b=f=>{for(const e in f)if(Object.hasOwn(f,e))return!1;return!0},F=(f,e)=>`${String(f)} ${e}${f===1?"":"s"}`,C=f=>({row:f.row,col:f.col});function ee(f){return f===""||f.length>255||/^[/\\]|^[A-Za-z]:|\\|\0/u.test(f)?!1:f.split("/").every(e=>e!==""&&e!=="."&&e!=="..")}class Me{cells;starts;first;constructor(e){let o=!0;for(let t=1;t<e.length&&o;t++){const s=e[t-1],l=e[t];s&&l&&(l.row<s.row||l.row===s.row&&l.col<=s.col)&&(o=!1)}if(!o){e.sort((t,s)=>t.row-s.row||t.col-s.col);for(let t=e.length-1;t>0;t--){const s=e[t-1],l=e[t];l&&s?.row===l.row&&s.col===l.col&&e.splice(t-1,1)}}this.cells=e;const n=e[0]?.row??0,i=e[e.length-1]?.row??-1;this.first=n,this.starts=new Int32Array(Math.max(0,i-n+2));let r=0;for(let t=0;t<this.starts.length;t++){for(;r<e.length&&(e[r]?.row??0)<n+t;)r++;this.starts[t]=r}}get(e,o){const n=e-this.first;if(n<0||n>=this.starts.length-1)return;let i=this.starts[n]??0,r=(this.starts[n+1]??0)-1;for(;i<=r;){const t=i+r>>1,s=this.cells[t];if(!s)return;if(s.col===o)return s;s.col<o?i=t+1:r=t-1}}}class te{list=[];add(e){this.list.push(e)}has(e,o){for(const n of this.list)if(z(n,e,o))return!0;return!1}}function oe(f,e){const o=e.toLowerCase();return V(f,n=>n.kind!=="structured"||n.table?.toLowerCase()!==o?n:Object.fromEntries(Object.entries(n).filter(([i])=>i!=="table")))}function Oe(f){const e=new Map;for(const n of f.sheets)for(const i of n.tables)i.totals>0&&e.set(i.name.toLowerCase(),{t:i,sheet:n.name});if(e.size===0)return;const o=(n,i)=>{const r=i.table===void 0?void 0:e.get(i.table.toLowerCase());if(!r||i.thisRow)return;const{t}=r,s=i.sections,l=s.includes("#All");if(!l&&!s.includes("#Totals"))return;const a=y=>t.columns.findIndex(x=>x.name.toLowerCase()===y.toLowerCase()),[c,u]=i.columns,h=c===void 0?0:a(c),p=c===void 0?t.columns.length-1:u===void 0?h:a(u);if(h<0||p<0)return;const m=l?t.ref.top:s.includes("#Data")?t.ref.top+t.headers:s.includes("#Headers")?t.ref.top:t.ref.bottom-t.totals+1,w=t.ref.bottom,d=t.ref.left+Math.min(h,p),g=t.ref.left+Math.max(h,p),k=m!==w||d!==g;return{kind:"ref",...r.sheet===n?{}:{sheet:r.sheet},col:{index:d,abs:!0},row:{index:m,abs:!0},...k?{col2:{index:g,abs:!0},row2:{index:w,abs:!0}}:{},range:k}};for(const n of f.sheets)for(const i of n.cells)i.node&&(i.node=V(i.node,r=>r.kind==="structured"?o(n.name,r)??r:r.kind==="unary"&&r.op==="@"&&r.arg.kind==="ref"&&!r.arg.range?r.arg:r))}const _e=1e3;function ne(f){return f.headers===0?"has no header row":f.columns.length!==f.ref.right-f.ref.left+1||!J(f.name)?"cannot be held as a table":new Set(f.columns.map(e=>e.name.toLowerCase())).size===f.columns.length?void 0:"has two columns of one name"}function D(f,e,o){let n;const i=new Set;I(f,t=>{t.kind==="call"&&(t.name==="LET"||t.name==="LAMBDA")&&t.args.forEach(s=>{s.kind==="name"&&i.add(s.name.toLowerCase())})});const r=t=>i.has(t)||o===void 0||o.names.has(t)||o.tables.has(t);return I(f,t=>{n===void 0&&(t.kind==="call"&&!de.has(t.name)&&(r(t.written.toLowerCase())||(n=`no function ${t.name}`)),t.kind==="name"&&!r(t.name.toLowerCase())&&(n=`no name ${t.name}`),t.kind==="structured"&&t.table!==void 0&&!r(t.table.toLowerCase())&&(n=`no table ${t.table}`),(t.kind==="ref"||t.kind==="name"||t.kind==="error")&&t.sheet!==void 0&&(t.sheet.startsWith("[")?n="it reads another workbook":e.has(t.sheet.toLowerCase())||(n=`no sheet ${t.sheet}`)))}),n}function Ae(f){const e=new Set(f.book.sheets.map(o=>o.name.toLowerCase()));for(const o of f.book.sheets){const n=new Map,i=(t,s)=>{const l=n.get(s),a=$(t);l?l.push(a):n.set(s,[a])},r=[];for(const t of o.cells){if(t.unread!==void 0){i(t,/^\[|[!']\[|\[\d+\]/u.test(t.unread)?"it reads another workbook":`it could not be read: ${t.unread}`);continue}if(!t.node)continue;const s=D(t.node,e,f);s!==void 0?(delete t.node,i(t,s)):(f.carried.set(t,o),t.array&&v(t.array)!==$(t)&&r.push(t))}Te(f,o,r);for(const[t,s]of n)f.lost.push(`${o.name}: ${F(s.length,"formula")} kept as ${s.length===1?"its value":"their values"}, as ${t} (${A(s)})`)}}function Te(f,e,o){if(o.length===0)return;const n=new Set;for(const i of o){const{array:r}=i;if(r)for(const t of e.cells)t!==i&&!t.node&&z(r,t.row,t.col)&&n.add(t)}e.cells=e.cells.filter(i=>!n.has(i));for(const i of n)f.spilled.set(i,e)}function E(f,e){const{value:o}=e;if(!f.book.date1904||typeof o!="number")return o;const n=f.book.looks[e.style]?.format;return N(n)&&n!==void 0&&K(n)?o+Z:o}function P(f,e){if(typeof f!="number"||e===void 0||!N(e)||!K(e)||f<1)return;const o=be(f);return H(o).value===f?o:void 0}const ze=(f,e)=>P(f,e)??j(f??null);function se(f,e){const o=P(f,e);return o!==void 0?o:f==null?null:typeof f=="number"||typeof f=="boolean"?f:j(f)}function Re(f){const e=[];for(let s=0;s<f.length;s++){const l=f[s];if(!l)continue;const a=e[e.length-1];a?.row===l.row&&a.right===l.col-1?(a.right=l.col,a.last=s):e.push({row:l.row,left:l.col,right:l.col,first:s,last:s})}const o=e.map((s,l)=>l),n=s=>{let l=s;for(;o[l]!==l;){const a=o[o[l]??l]??l;o[l]=a,l=a}return l};let i=0,r=0;for(let s=0;s<e.length;s++){const l=e[s];if(l){s>0&&e[s-1]?.row!==l.row&&(i=e[s-1]?.row===l.row-1?r:s,r=s);for(let a=i;a<r;a++){const c=e[a];c?.row===l.row-1&&c.right>=l.left&&c.left<=l.right&&(o[n(s)]=n(a))}}}const t=new Map;return e.forEach((s,l)=>{const a=n(l),c=t.get(a),u=s.right-s.left+1;c?(c.box.top=Math.min(c.box.top,s.row),c.box.bottom=Math.max(c.box.bottom,s.row),c.box.left=Math.min(c.box.left,s.left),c.box.right=Math.max(c.box.right,s.right),c.count+=u,c.runs.push(l)):t.set(a,{box:{top:s.row,bottom:s.row,left:s.left,right:s.right},count:u,runs:[l]})}),[...t.values()].map(s=>({box:s.box,count:s.count,cells:()=>s.runs.flatMap(l=>{const a=e[l];return a?f.slice(a.first,a.last+1):[]})}))}const re=f=>JSON.stringify(f);class Ne{ctx;read;cells;inTables=new te;columnLooks=new Map;rowLooks=new Map;lookDone=new te;tables=[];areas=[];filtered=[];ownLooks=new Map;fileColumns=new Map;pictured=new Map;over=[];keys=new Map;constructor(e,o){this.ctx=e,this.read=o,this.cells=new Me(o.cells)}at(e,o){return this.cells.get(e,o)}look(e){return this.ctx.book.looks[e.style]??{}}runs(e){if(!e.runs||e.node||typeof e.value!="string")return;const o=ye(xe(e.runs,this.look(e),this.ctx.book.font));return o.length===0||$e(o)?void 0:o}code(e){return this.look(e).format}text(e){return e.node?S(e.node):ze(E(this.ctx,e),this.code(e))}baseLooks(){const{read:e}=this,{looks:o}=this.ctx.book;let n=-1;for(const r of e.cells)r.col>n&&(n=r.col);for(const r of e.columns){if(r.style===void 0)continue;const t=o[r.style];if(!(!t||b(t)))for(let s=r.min;s<=Math.min(r.max,n);s++)this.columnLooks.set(s,t)}for(const r of e.rows){const t=r.style===void 0?void 0:o[r.style];t&&!b(t)&&this.rowLooks.set(r.row,t)}const i=(r,t)=>{for(const s in t)if(!(s in r))return!1;return!0};for(const r of e.cells){const t=this.look(r),s=this.columnLooks.get(r.col);s&&!i(t,s)&&this.columnLooks.delete(r.col);const l=this.rowLooks.get(r.row);l&&!i(t,l)&&this.rowLooks.delete(r.row)}}ownLook(e){const o=this.columnLooks.get(e.col),n=this.rowLooks.get(e.row),i=this.look(e),r=i.format!==void 0&&N(i.format);if(!o&&!n&&!r){let a=this.ownLooks.get(e.style);return a||(a={look:i,key:re(i)},this.ownLooks.set(e.style,a)),a}const t={...o,...n},s={};for(const[a,c]of Object.entries(i))JSON.stringify(c)!==JSON.stringify(t[a])&&(s[a]=c);const l=s.format;if(typeof l=="string"){const a=e.node?void 0:P(E(this.ctx,e),l);a!==void 0&&H(a).format===l&&delete s.format}return{look:s,key:re(s)}}keyOf(e,o){if(e.key!==void 0)return e.key;const n=ke(o,e.row,e.col),i=this.keys.get(n);return i!==void 0?e.key=i:(this.keys.set(n,n),e.key=n)}columnFormula(e,o,n){const i=new Map,r=n-o+1;for(let s=o;s<=n;s++){const l=this.at(s,e);if(!l||l.value===void 0&&!l.node||l.value===null&&!l.node)return;if(!l.node)continue;const a=this.keyOf(l,l.node),c=i.get(a);c?c.n+=1:i.set(a,{n:1,cell:l})}let t;for(const s of i.values())(!t||s.n>t.n)&&(t=s);return t&&t.n*2>r?t.cell:void 0}csv(e,o){const n=[];for(let i=0;i<e;i+=G){const r=[];for(let t=i;t<Math.min(e,i+G);t++)r.push(o(t));n.push(pe(r))}return n.join("")}table(e){const{read:o,ctx:n}=this,i=d=>n.lost.push(`${o.name}: table ${e.name} ${d}`),r=e.ref.right-e.ref.left+1,t=ne(e);if(t!==void 0)return i(`${t}, so its cells are kept and it is no table`),!1;const s=e.ref.top,l=s+1;let a=e.ref.bottom-e.totals;if(e.totals===0){let d=s;for(const g of o.cells)g.col>=e.ref.left&&g.col<=e.ref.right&&g.row>d&&(d=g.row);a-d>_e&&(i(`runs ${String(a-d)} empty rows past what it holds, which are left out`),a=d)}e.totals>0&&i("has a totals row, kept as plain cells under it");const c=e.columns.map((d,g)=>a>=l?this.columnFormula(e.ref.left+g,l,a):void 0),u=d=>{const g=c[d];if(!g)return!1;for(let k=l;k<=a;k++)if(this.at(k,e.ref.left+d)?.key!==g.key)return!1;return!0};let h=r;for(;h>1&&u(h-1);)h-=1;const p={},m=this.path(e.name);n.files.set(m,this.csv(a-l+2,d=>{if(d===0)return e.columns.slice(0,h).map(y=>y.name);const g=l+d-1,k=[];for(let y=0;y<h;y++){const x=this.at(g,e.ref.left+y),L=c[y];x?L&&x.key===L.key?k.push(""):x.node?k.push(S(oe(x.node,e.name))):k.push(this.text(x)):k.push("")}return k})),this.inTables.add({...e.ref,bottom:a}),e.columns.forEach((d,g)=>{const k=e.ref.left+g,y=this.columnLook(k,l,a),x=c[g];x?.node&&(y.formula=S(oe(ge(x.node,l-x.row,0),e.name)));const L=this.fileColumns.get(k);L!==void 0&&l<=a&&(y.files=L===W?!0:{height:L}),b(y)||(p[d.name]=y)});const w=new Map;for(const[d,g]of e.filter?.columns??[]){const k=e.columns[d]?.name;k!==void 0&&w.set(k,g)}return(e.filter?.unread??0)>0&&i(`has ${F(e.filter?.unread??0,"filter")} by condition, its rows left as they were hidden`),this.tables.push({name:e.name,at:$({row:s,col:e.ref.left}),rows:m,...e.style!==void 0&&e.style!=="TableStyleMedium2"?{style:e.style}:{},...e.options,...b(p)?{}:{columns:p},...e.filter===void 0?{filter:!1}:w.size>0?{filter:{columns:Object.fromEntries(w)}}:{}}),e.filter?.unread===0&&e.filter.columns.size>0&&this.filtered.push({...e.ref,bottom:a}),this.areas.push({...e.ref,bottom:a}),!0}columnLook(e,o,n){let i,r={};for(let t=o;t<=n;t++){const s=this.at(t,e),l=s?this.ownLook(s):{look:{},key:"{}"};if(i===void 0)i=l.key,r=l.look;else if(i!==l.key)return{}}return b(r)?{}:(this.lookDone.add({top:o,bottom:n,left:e,right:e}),{...r})}path(e){const o=Q(e);let n=`${o}.csv`;for(let i=2;this.ctx.files.has(n)||this.ctx.taken(n);i++)n=`${o}-${String(i)}.csv`;return n}loose(){const e=[],o=[];for(const n of this.read.cells)this.inTables.has(n.row,n.col)||(n.node?e.push(n):n.value!==void 0&&n.value!==null&&o.push(n));return{formulas:e,typed:o}}blockAreas(e,o){const n=[],i=O(o.map(C)),r=s=>!n.some(l=>R(l,s))&&!this.areas.some(l=>R(l,s))&&!i.some(l=>R(l,s)),t=s=>(s.bottom-s.top+1)*(s.right-s.left+1);for(const s of Re(e)){const{box:l}=s;if(!(t(l)<Y)){if(s.count/t(l)>=Ee&&r(l)){n.push(l);continue}for(const a of O(s.cells().map(C)))t(a)>=Y&&r(a)&&n.push(a)}}return n.sort((s,l)=>s.top-l.top||s.left-l.left)}cells_(e){const{formulas:o,typed:n}=this.loose(),i=new Map;for(const c of n){const u=this.runs(c);u&&i.set(c,u)}const r=this.read.cells.filter(c=>this.inTables.has(c.row,c.col)&&this.runs(c)!==void 0);r.length>0&&this.ctx.lost.push(`${this.read.name}: ${F(r.length,"cell")} of rich text in a table, kept as plain text (${A(r.map(c=>$(c)))})`);const t=this.blockAreas(n.filter(c=>!i.has(c)),[...o,...i.keys()]),s=c=>t.some(u=>z(u,c.row,c.col));t.length>0&&(e.blocks=t.map(c=>{const u=this.path(this.read.name);return this.ctx.files.set(u,this.csv(c.bottom-c.top+1,h=>{const p=[];for(let m=c.left;m<=c.right;m++){const w=this.at(c.top+h,m);p.push(w?this.text(w):"")}return p})),{at:$({row:c.top,col:c.left}),rows:u}}));const l=[],a=new Map;for(const c of o){if(!c.node)continue;const u=this.keyOf(c,c.node),h=a.get(u);h?h.push(c):a.set(u,[c])}for(const c of a.values())for(const u of O(c.map(C))){const h=this.at(u.top,u.left);h?.node&&l.push([{row:u.top,col:u.left},v(u),S(h.node)])}for(const c of n){if(t.length>0&&s(c))continue;const u=i.get(c);l.push([C(c),$(c),u?{runs:u}:se(E(this.ctx,c),this.code(c))])}l.sort(([c],[u])=>c.row-u.row||c.col-u.col),l.length>0&&(e.cells=Object.fromEntries(l.map(([,c,u])=>[c,u])))}formats(e){const o=new Map,n=this.lookDone.list.length>0;for(const r of this.read.cells){if(n&&this.lookDone.has(r.row,r.col))continue;const t=this.ownLook(r);if(b(t.look))continue;const s=o.get(t.key);s?s.places.push(C(r)):o.set(t.key,{look:t.look,places:[C(r)]})}const i=[];for(const{look:r,places:t}of o.values())for(const s of O(t))i.push({range:v(s),...r});i.length>0&&(e.format=i)}columns(e){const{read:o}=this,n=new Map;let i=0;for(const t of o.cells)t.col>i&&(i=t.col);const r=[];for(const t of o.columns){if(t.width===void 0&&t.hidden!==!0&&t.level===void 0)continue;const s=t.max-Math.max(t.min,i+1)+1>X?Math.max(i,t.min+X-1):t.max;s<t.max&&r.push(`${M(s+1)}:${M(t.max)}`);const l=t.width!==void 0&&t.width<=0;for(let a=t.min;a<=s;a++)n.set(a,{...t.width===void 0||l?{}:{width:t.width},...t.hidden===!0||l?{hidden:!0}:{},...t.level===void 0?{}:{level:t.level}})}for(const[t,s]of this.columnLooks)n.set(t,{...n.get(t),...s});for(const[t,s]of this.fileColumns)this.tableColumn(t)||n.set(t,{...n.get(t),files:s===W?!0:{height:s}});n.size>0&&(e.columns=Object.fromEntries([...n.keys()].sort((t,s)=>t-s).map(t=>[M(t),n.get(t)??{}]))),r.length>0&&this.ctx.lost.push(`${o.name}: the size of columns ${A(r)}, past those that hold anything`)}tableColumn(e){return this.areas.some(o=>e>=o.left&&e<=o.right)}rows(e){const o={};for(const n of this.read.rows){const i=this.rowLooks.get(n.row),r=this.filtered.some(a=>n.row>a.top&&n.row<=a.bottom),t=n.height!==void 0&&this.pictured.get(n.row)!==n.height?n.height:void 0,s=t!==void 0&&t<=0,l={...t===void 0||s?{}:{height:t},...(n.hidden===!0||s)&&!r?{hidden:!0}:{},...n.level===void 0?{}:{level:n.level},...i};b(l)||(o[String(n.row+1)]=l)}b(o)||(e.rows=o)}assetPath(e,o){const n=t=>{const s=this.ctx.assets.get(t);return s?Ie(s,o.bytes):!this.ctx.taken(t)};if(e!==void 0&&ee(e)&&n(e))return e;const i=Q((o.name??"picture").replace(/\.[A-Za-z0-9]+$/u,""));let r=`${i}.${o.type}`;for(let t=2;!n(r);t++)r=`${i}-${String(t)}.${o.type}`;return r}pictures(){const e=this.over;for(const o of this.read.pictures){const n=this.at(o.row,o.col),i=typeof n?.value=="string"?n.value:"";if(o.y===void 0&&o.descr!==void 0&&ee(o.descr)&&i.split(fe).includes(o.descr)&&o.descr!==void 0){this.ctx.assets.set(o.descr,o.bytes),this.fileColumns.set(o.col,Math.max(this.fileColumns.get(o.col)??0,o.height)),this.pictured.set(o.row,Math.max(this.pictured.get(o.row)??0,o.height));continue}if(o.width<=0||o.height<=0){this.ctx.lost.push(`${this.read.name}: a picture of no size at ${$({row:o.row,col:o.col})}`);continue}const t=this.assetPath(o.descr,o);this.ctx.assets.set(t,o.bytes);const s=we(o.bytes),l=s?.width===o.width&&s.height===o.height;e.push({file:t,at:$({row:o.row,col:o.col}),...o.x===void 0?{}:{x:o.x},...o.y===void 0?{}:{y:o.y},...l?{}:{width:o.width,height:o.height}})}}build(){const{read:e}=this;this.baseLooks(),this.pictures();for(const n of e.tables)this.table(n);const o={name:e.name};return e.state!=="visible"&&(o.hidden=!0),e.gridlines===!1&&(o.gridlines=!1),e.tab!==void 0&&(o.tab=e.tab),e.state==="veryHidden"&&this.ctx.lost.push(`${e.name}: being very hidden; it is hidden`),e.freeze&&(e.freeze.row>0||e.freeze.col>0)&&(o.freeze=$(e.freeze)),this.tables.length>0&&(o.tables=this.tables),this.filter(o),this.columns(o),this.rows(o),this.cells_(o),e.merges.length>0&&(o.merges=e.merges.map(v)),this.formats(o),e.conditional.length>0&&(o.conditional=e.conditional),e.validations.length>0&&(o.validations=e.validations),e.charts.length>0&&(o.charts=e.charts.map(n=>this.chart(n))),this.over.length>0&&(o.pictures=this.over),b(e.links)||(o.links=e.links),e.notes.length>0&&(o.notes=Object.fromEntries(e.notes.map(n=>[n.ref,n.author===void 0||n.author===le?n.text:{text:n.text,author:n.author}]))),e.print&&(o.print=e.print),e.protect===!0&&(o.protect=!0),e.outline&&(o.outline=e.outline),o}chart(e){return ce(e,o=>{const n=this.chartReference(o.replace(/^=/u,""));return o.startsWith("=")?`=${n}`:n})}chartReference(e){const o=e.lastIndexOf("!"),i=(o<0?this.read.name:e.slice(0,o)).replace(/^'|'$/gu,"").replaceAll("''","'"),r=B(e.slice(o+1).replaceAll("$",""));if(!r)return e;const t=this.ctx.book.sheets.find(s=>s.name.toLowerCase()===i.toLowerCase());for(const s of t?.tables??[]){const l=s.ref.top+1,c=r.left===r.right&&r.top===l&&r.bottom===s.ref.bottom&&r.left>=s.ref.left&&r.left<=s.ref.right?s.columns[r.left-s.ref.left]:void 0;if(c&&this.ctx.tables.has(s.name.toLowerCase()))return`${s.name}[${c.name}]`}return`${t===this.read||o<0?"":`${e.slice(0,o)}!`}${v(r)}`}filter(e){const{filter:o}=this.read;if(!o)return;const n={};for(const[i,r]of o.columns)n[M(o.ref.left+i)]=r;e.filter={range:v(o.ref),...b(n)?{}:{columns:n}},o.unread===0&&!b(n)&&this.filtered.push(o.ref)}}const Ie=(f,e)=>f.length===e.length&&f.every((o,n)=>o===e[n]),He=new Set(["_xlnm._FilterDatabase","_xlnm.Print_Area","_xlnm.Print_Titles"]);function je(f){const e={},o=[],n=new Map,{book:i,lost:r}=f,t=new Set(i.sheets.map(u=>u.name.toLowerCase())),s=new Set,l=[];let a;const c=u=>{a=void 0;const h=Pe(u.text);if(h!==void 0)return typeof h=="string"?j(h):h;const p=ve(u.text,!0),m=p.ok?D(p.node,t):"it could not be read";if(!p.ok||m!==void 0||De(p.node)){r.push(`the name ${u.name} (${u.text})${m===void 0?"":`: ${m}`}`);return}return a=p.node,S(p.node)};for(const u of i.names){if(u.name.startsWith("_xlnm.")){He.has(u.name)||r.push(`Excel's name ${u.name}`);continue}if(/^_xl(?:fn|pm|ws|udf)/iu.test(u.name))continue;const h=u.name.toLowerCase(),p=u.sheet===void 0?"":String(u.sheet);if(!J(u.name)||f.tables.has(h)){r.push(`the name ${u.name}, which cannot be held here`);continue}if(s.has(`${p}|${h}`)){r.push(`a second name ${u.name}${p===""?"":` of ${i.sheets[u.sheet??0]?.name??""}`}`);continue}const m=c(u);if(m===void 0)continue;s.add(`${p}|${h}`),f.names.add(h);const w=u.sheet===void 0?void 0:n.get(u.sheet)??{names:{},hidden:[]},d=w?.names??e;d[u.name]=m,u.hidden===!0&&(w?.hidden??o).push(u.name),w&&u.sheet!==void 0&&n.set(u.sheet,w),a&&l.push({held:d,n:u,node:a})}for(const{held:u,n:h,node:p}of l){const m=D(p,t,{names:f.names,tables:f.tables});m!==void 0&&(u[h.name]="=#NAME?",r.push(`the name ${h.name} (${h.text}): ${m}; it holds #NAME?, as in Excel`))}return{names:e,hidden:o,sheets:n}}function Fe(f,e){const o={},n=new Map;for(const[i,r]of Object.entries(e))typeof r=="string"&&r.startsWith("=")&&n.set(r.slice(1).replaceAll("$","").toLowerCase(),i);for(const i of f.book.sheets)for(const r of i.scenarios){const t={};let s=!0;for(const{at:l,value:a}of r.cells){const c=ae(l),u=c&&i.cells.find(m=>m.row===c.row&&m.col===c.col);String(u?.value??"")!==a&&(s=!1);const h=n.get(`${U(i.name)}${l}`.toLowerCase())??n.get(l.toLowerCase()),p=H(a);h===void 0?f.lost.push(`${i.name}: scenario ${r.name}'s cell ${l}, which has no name`):t[h]=typeof p.value=="number"?p.value:a}!s&&!b(t)&&(o[r.name]={...o[r.name],...t})}return o}function De(f){let e=!1;return I(f,o=>{e||=o.kind==="error"&&o.code==="#REF!"}),e}function Pe(f){const e=f.trim();return/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/u.test(e)?Number(e):/^true$/iu.test(e)?!0:/^false$/iu.test(e)?!1:/^"((?:[^"]|"")*)"$/u.exec(e)?.[1]?.replaceAll('""','"')}const We=new RegExp(`^${Ce.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}(?: \\(\\d+\\))?$`,"u");function Be(f){const e=f.sheets.find(r=>r.state==="veryHidden"&&We.test(r.name));if(!e)return;const o=U(e.name).toLowerCase(),n=r=>{const t=r.replace(/^=/u,"");if(!t.toLowerCase().startsWith(o))return;const s=B(t.slice(o.length).replaceAll("$",""));if(!s||s.left!==s.right)return;const l=[];for(let a=s.top;a<=s.bottom;a++){const c=e.cells.find(u=>u.row===a&&u.col===s.left);l.push(typeof c?.value=="string"?c.value:"")}return l};for(const r of f.sheets)r.validations=r.validations.map(t=>{const[s]=t.formula??[],l=t.type==="list"&&typeof s=="string"?n(s):void 0;if(!l)return t;const a={...t,values:l};return delete a.formula,a});const i=f.sheets.indexOf(e);f.sheets=f.sheets.filter(r=>r!==e),f.names=f.names.flatMap(r=>r.sheet===void 0||r.sheet<i?[r]:r.sheet===i?[]:[{...r,sheet:r.sheet-1}])}const T=f=>f instanceof _?f.code:f??null,Ue=new Map([["#SPILL!","#VALUE!"],["#CALC!","#VALUE!"]]);export function sameValue(f,e,o){if(typeof f=="number"&&typeof e=="number")return f===e?!0:Math.abs(f-e)<=Math.max(Math.abs(f),Math.abs(e))*o;if(f instanceof _||e instanceof _){const n=i=>i instanceof _?Ue.get(i.code)??i.code:void 0;return n(f)===n(e)}if(f===null||e===null){const n=f??e;return n===null||n===""||n===0||n===!1}return f===e}function Ve(f,e){const o=[];for(const r of e.sheets)for(const t of r.formulas)t.shared.node&&ue(e,t.shared,r).volatile&&o.push(t);const n=new Set(o),i=[...o];for(;;){const r=i.pop();if(!r)return n;for(const t of f.readers(r.sheet,r.row,r.col))n.has(t)||(n.add(t),i.push(t))}}function qe(f){const e=f.file.iteration;return(e===void 0||e===!0?void 0:e.max_change)??he.max_change}function Je(f,e,o,n){const i={formulas:0,same:0,uncached:0,moving:0,differences:[]},r=Ve(o,e);for(const[t,s]of f.carried){if(!t.node)continue;const l=e.sheet(s.name);if(!l)continue;i.formulas+=1;const a=l.at(t.row,t.col);if(a instanceof q&&r.has(a)){i.moving+=1;continue}const c=E(f,t);if(c===void 0){i.uncached+=1;continue}const u=o.value(l,t.row,t.col);a instanceof q&&o.iterates(a)&&typeof c=="number"&&typeof u=="number"&&Math.abs(c-u)<=qe(e)||sameValue(c,u,n)?i.same+=1:i.differences.push({sheet:s.name,cell:$(t),formula:S(t.node),file:T(c),engine:T(u)})}for(const[t,s]of f.spilled){const l=e.sheet(s.name);if(!l)continue;i.formulas+=1;const a=l.spillAt(t.row,t.col);if(a&&r.has(a)){i.moving+=1;continue}const c=E(f,t),u=o.value(l,t.row,t.col);c===void 0?i.uncached+=1:sameValue(c,u,n)?i.same+=1:i.differences.push({sheet:s.name,cell:$(t),formula:a?`${$(a)}#`:"",file:T(c),engine:T(u)})}return i}function Ke(f,e){const o=new Map,n=[];for(const i of f){const r=e.find(l=>i.startsWith(`${l}: `));if(r===void 0){n.push(i);continue}const t=i.slice(r.length+2),s=o.get(t);s?s.push(r):o.set(t,[r])}for(const[i,r]of o)n.push(r.length===1?`${r[0]??""}: ${i}`:`${i}, on ${String(r.length)} sheets (${A(r)})`);return n}function Ye(f,e,o){const n=o.circularCells();if(n.length===0)return!1;const i=new Map;for(const[s,l]of f.carried)i.set(`${l.name}|${String(s.row)}|${String(s.col)}`,s);let r=0,t=0;for(const s of n){const l=i.get(`${s.sheet.name}|${String(s.row)}|${String(s.col)}`),a=l===void 0?void 0:E(f,l),c=e[s.sheet.index],u=s.shared.source.path??[];if(a===void 0||!c||u[2]!=="cells"){a!==void 0&&(t+=1);continue}const h=se(a,void 0),p=c.cells??={},m=$(s),w=p[m],d=p[String(u[3])],g=d!==null&&typeof d=="object"?d:{};p[m]=w!==null&&typeof w=="object"?{...w,start:h}:{...g,formula:s.text,start:h},r+=1}return t>0&&f.lost.push(`where ${String(t)} cells of a table or a block start iterative calculation: they start from 0`),r>0}export function importXlsx(f,e){const o=Se(f,e.zip);if(Be(o),Oe(o),o.sheets.length===0)throw new Error("It holds no sheets.");const n={book:o,taken:e.taken??(()=>!1),files:new Map,assets:new Map,lost:[...o.lost],tables:new Set(o.sheets.flatMap(m=>m.tables.filter(w=>ne(w)===void 0).map(w=>w.name.toLowerCase()))),names:new Set,carried:new Map,spilled:new Map};o.date1904&&n.lost.push(`the 1904 date system: dates are moved to the 1900 one, ${String(Z)} days on`),(o.font.name!==void 0&&o.font.name!=="Calibri"||o.font.size!==void 0&&o.font.size!==11)&&n.lost.push(`its default font, ${o.font.name??""} ${String(o.font.size??"")}`);const i=je(n);Ae(n);const r=o.sheets.map((m,w)=>{const d=new Ne(n,m).build(),g=i.sheets.get(w);return g&&!b(g.names)&&(d.names=g.names),g&&g.hidden.length>0&&(d.hidden_names=g.hidden),d}),t=Fe(n,i.names),s={title:o.title??e.name,...b(i.names)?{}:{names:i.names},...i.hidden.length>0?{hidden_names:i.hidden}:{},sheets:r,...b(t)?{}:{scenarios:t},...o.iteration===void 0?{}:{iteration:o.iteration}},l=()=>{const m=Le(s),w=new Map([[ie,m],...n.files]);return{files:w,...me({text:m,read:d=>w.get(d),exists:d=>w.has(d)||n.assets.has(d)})}};let a=l();a.calc&&Ye(n,r,a.calc)&&(a=l());const{files:c,workbook:u,calc:h,problems:p}=a;return{files:c,assets:n.assets,lost:Ke(n.lost,o.sheets.map(m=>m.name)),problems:p,compared:u&&h?Je(n,u,h,e.tolerance??COMPARE_TOLERANCE):{formulas:0,same:0,uncached:0,moving:0,differences:[]},sheets:o.sheets.length,tables:n.tables.size}}
@@ -5,6 +5,7 @@ import type { Node } from "../formula/ast.js";
5
5
  import { type Scalar } from "../values.js";
6
6
  import type { CellLook } from "../workbook.js";
7
7
  import { type ReadChart } from "./charts.js";
8
+ import { type ReadRun } from "./runs.js";
8
9
  export interface ReadCell {
9
10
  row: number;
10
11
  col: number;
@@ -22,7 +23,8 @@ export interface ReadCell {
22
23
  dynamic?: boolean;
23
24
  /** Into `looks`. */
24
25
  style: number;
25
- rich?: boolean;
26
+ /** Its rich text's runs, when its string has them. */
27
+ runs?: ReadRun[];
26
28
  }
27
29
  export interface ReadColumn {
28
30
  /** Ends included, from 0. */
@@ -60,9 +62,18 @@ export interface ReadTable {
60
62
  calculated: boolean;
61
63
  }[];
62
64
  style?: string;
65
+ /** Table Style Options, where they are not a new table's. */
66
+ options: TableOptions;
63
67
  /** Its filter buttons; nothing when it has none. */
64
68
  filter?: ReadFilter;
65
69
  }
70
+ /** Table Style Options as sheet.yaml names them, each said only when it is not Excel's default. */
71
+ export interface TableOptions {
72
+ banded_rows?: false;
73
+ banded_columns?: true;
74
+ first_column?: true;
75
+ last_column?: true;
76
+ }
66
77
  /** A Note on a cell. */
67
78
  export interface ReadNote {
68
79
  ref: string;
@@ -120,6 +131,11 @@ export interface ReadSheet {
120
131
  protect?: boolean;
121
132
  /** Page Layout. */
122
133
  print?: SheetPrint;
134
+ /** Outline settings where they are not Excel's own. */
135
+ outline?: {
136
+ summary_below?: false;
137
+ summary_right?: false;
138
+ };
123
139
  }
124
140
  export interface ReadName {
125
141
  name: string;
@@ -1,3 +1,3 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{ZipLimitError as Ne}from"@allyhub/formats";import{SHEET_ICONS as Ie,SHEET_MARGINS as fe,SHEET_OPERATORS as Le,SHEET_PAPERS as Me,SHEET_VALIDATIONS as Re}from"@allyhub/formats";import{MAX_COLUMNS as Z,MAX_ROWS as Q,cellName as ee,columnLetter as le,readAddress as ue,readArea as B,readAreas as te}from"../address.js";import{ITERATION_DEFAULTS as he}from"../calc/engine.js";import{SHEET_CHART_DEFAULTS as pe}from"../chart.js";import{moveFormula as Fe,relativeKey as me}from"../formula/move.js";import{parseFormula as De}from"../formula/parse.js";import{printFormula as ge}from"../formula/print.js";import{ERR as je,errorOf as Pe,serialOfDate as _e}from"../values.js";import{OFFICE_THEME as ze,colorOf as D,paletteOf as be,themeColors as He}from"./colors.js";import{chartAnchors as Ve,readChart as Ue}from"./charts.js";import{isRangeText as Be,readFileFormula as ne}from"./formula.js";import{BUILTIN_FORMATS as We}from"./numfmt.js";import{XmlStream as we}from"./sax.js";import{attr as l,flag as v,numberAttr as k,readXml as xe,readXstring as N,tag as d,tags as x,textOf as E}from"./xml.js";import{ZipIn as Xe}from"./zip.js";function qe(r){if(v(r,"iterate")!==!0)return;const e=k(r,"iterateCount"),t=k(r,"iterateDelta"),o=e===void 0?void 0:Math.min(32767,Math.max(1,Math.round(e))),n=t===void 0?void 0:Math.max(0,t),s={...o===void 0||o===he.max_iterations?{}:{max_iterations:o},...n===void 0||n===he.max_change?{}:{max_change:n}};return Object.keys(s).length>0?s:!0}const ye=7,Ge=r=>Math.floor((256*r+Math.floor(128/ye))/256*ye),Ze=r=>Math.round(r*4/3),oe=5;export function placesLine(r){const e=r.slice(0,oe).join(", ");return r.length>oe?`${e} and ${String(r.length-oe)} more`:e}const V=(r,e,t=`${e}s`)=>`${String(r)} ${r===1?e:t}`;export const GRID_END=`Excel's grid ends at ${le(Z-1)}${String(Q)} (${Q.toLocaleString("en-US")} rows, ${Z.toLocaleString("en-US")} columns)`;function Je(r,e){let t=0,o=0;const n=r.length;for(;t<n;t++){const i=r.charCodeAt(t),c=i>=65&&i<=90,a=i>=97&&i<=122;if(!c&&!a)break;o=o*26+(c?i-64:i-96)}if(t===0||t===n)return;let s=0;for(let i=t;i<n;i++){const c=r.charCodeAt(i);if(c<48||c>57)return;s=s*10+c-48}if(s!==0){if(t>3||o>Z||s>Q)throw new Error(`${e} has a cell at ${r}, and ${GRID_END}.`);return{row:s-1,col:o-1}}}class Ke{zip;constructor(e,t){this.zip=new Xe(e,t)}get names(){return this.zip.names}has(e){return this.zip.has(e)}text(e){return this.zip.text(e)}bytes(e){return this.zip.bytesOf(e)}xml(e){const t=this.text(e);return t===void 0?void 0:xe(t)}stream(e,t){const o=this.zip.streamText(e,n=>{t.push(n)});return o&&t.end(),o}rels(e){const t=e.lastIndexOf("/"),o=`${e.slice(0,t+1)}_rels/${e.slice(t+1)}.rels`,n=this.xml(o);return x(d(n?.Relationships)?.Relationship).map(s=>{const i=l(s,"Type")??"",c=l(s,"Target")??"",a=l(s,"TargetMode")==="External";return{id:l(s,"Id")??"",type:i.slice(i.lastIndexOf("/")+1),target:a?c:Qe(e,c),external:a}})}count(e){return this.names.filter(t=>e.test(t)).length}}function Qe(r,e){if(e.startsWith("/"))return e.slice(1);const t=r.split("/").slice(0,-1);for(const o of e.split("/"))o===".."?t.pop():o!=="."&&t.push(o);return t.join("/")}function Ye(r,e){const t=[];if(e===void 0)return t;let o,n=0,s=!1;const i={open(c){if(c==="si"){o={text:"",rich:!1};return}if(o){if(n>0||c==="rPh"||c==="phoneticPr"||c==="extLst"){n+=1;return}c==="r"&&(o.rich=!0),c==="t"&&(s=!0)}},close(c){if(n>0){n-=1;return}if(c==="si"){o&&t.push({...o,text:N(o.text)}),o=void 0;return}c==="t"&&(s=!1)},text(c){o&&s&&n===0&&(o.text+=c)}};return r.stream(e,new we(i)),t}function W(r,e){const t=r[e];if(t===void 0)return!1;const o=l(d(t),"val");return o===void 0||o!=="0"&&o!=="false"}const et=new Set(["double","singleAccounting","doubleAccounting"]);function tt(r,e,t){const o={},n=(a,f)=>l(d(a?.[f]),"val");if(W(r,"b")&&(o.bold=!0),W(r,"i")&&(o.italic=!0),W(r,"strike")&&(o.strike=!0),W(r,"u")){const a=n(r,"u");o.underline=a!==void 0&&et.has(a)?a:!0}const s=n(r,"name");s!==void 0&&s!==n(e,"name")&&(o.font=s);const i=n(r,"sz");i!==void 0&&i!==n(e,"sz")&&(o.size=Number(i));const c=D(d(r.color),t);return c!==void 0&&c!==D(d(e?.color),t)&&(o.color=c),o}function nt(r,e){const t=d(r.patternFill),o=l(t,"patternType");if(o===void 0||o==="none")return;const n=D(d(t?.fgColor),e),s=D(d(t?.bgColor),e);return o==="solid"&&n!==void 0?n:{pattern:o,...n===void 0?{}:{color:n},...s===void 0?{}:{background:s}}}function $e(r,e){const t={};for(const o of["left","right","top","bottom"]){const n=d(r[o]),s=l(n,"style");if(s===void 0||s==="none")continue;const i=D(d(n?.color),e);t[o]={style:s,...i===void 0?{}:{color:i}}}return Object.keys(t).length===0?void 0:t}function ot(r){const e={},t=l(r,"horizontal");t!==void 0&&t!=="general"&&(e.align=t);const o=l(r,"vertical");o!==void 0&&o!=="bottom"&&(e.valign=o),v(r,"wrapText")===!0&&(e.wrap=!0),v(r,"shrinkToFit")===!0&&(e.shrink=!0);const n=k(r,"indent");n!==void 0&&n>0&&(e.indent=n);const s=k(r,"textRotation");return s!==void 0&&s>0&&s<=180&&(e.rotation=s),e}function ke(r,e){const t={},o=d(r.font);if(o){const a=(h,u)=>{o[h]!==void 0&&(t[u]=W(o,h))};a("b","bold"),a("i","italic"),a("strike","strike"),o.u!==void 0&&(t.underline=W(o,"u"));const f=D(d(o.color),e);f!==void 0&&(t.color=f)}const n=d(d(r.fill)?.patternFill),s=D(d(n?.bgColor),e)??D(d(n?.fgColor),e);s!==void 0&&(t.fill=s);const i=d(r.border),c=i&&$e(i,e);return c!==void 0&&(t.border=c),t}function rt(r,e){const t=d(r?.styleSheet),o=be(e,t),n=new Map(x(d(t?.numFmts)?.numFmt).map(m=>[k(m,"numFmtId")??-1,l(m,"formatCode")?.replace(/^$/u,"General")??"General"])),s=x(d(t?.fonts)?.font),i=x(d(t?.fills)?.fill),c=x(d(t?.borders)?.border),a=x(d(t?.cellXfs)?.xf),f=s[k(a[0],"fontId")??0],h=new Set;i.some(m=>m.gradientFill!==void 0)&&h.add("gradient fills");const u=a.map(m=>{const $={},g=s[k(m,"fontId")??0];g&&(Object.assign($,tt(g,f,o)),g.vertAlign!==void 0&&h.add("superscript and subscript"));const S=i[k(m,"fillId")??0],C=S&&nt(S,o);C!==void 0&&($.fill=C);const I=c[k(m,"borderId")??0],M=I&&$e(I,o);M!==void 0&&($.border=M),I&&l(d(I.diagonal),"style")!==void 0&&h.add("diagonal borders");const R=d(m.alignment);R&&(Object.assign($,ot(R)),k(R,"textRotation")===255&&h.add("vertical text"));const j=k(m,"numFmtId")??0,O=n.get(j)??We[j];return O!==void 0&&O!=="General"&&($.format=O),$}),b=l(d(f?.name),"val"),p=l(d(f?.sz),"val");return{looks:u,dxfs:x(d(t?.dxfs)?.dxf).map(m=>ke(m,o)),font:{...b===void 0?{}:{name:b},...p===void 0?{}:{size:Number(p)}},lost:[...h]}}function ve(r){const e=new Map;let t=0;for(const o of x(r.filterColumn)){const n=k(o,"colId")??0,s=d(o.filters);if(!s){Object.keys(o).some(c=>c!=="colId"&&c!=="hiddenButton")&&(t+=1);continue}if(s.dateGroupItem!==void 0){t+=1;continue}const i=x(s.filter).map(c=>N(l(c,"val")??""));e.set(n,{...i.length===0?{}:{values:i},...v(s,"blank")===!0?{blanks:!0}:{}})}return{columns:e,unread:t}}function st(r){const e=d(r?.table),t=B(l(e,"ref")??""),o=l(e,"displayName")??l(e,"name");if(!t||o===void 0)return;const n=d(e?.tableStyleInfo),s=d(e?.autoFilter);return{name:o,ref:t,headers:k(e,"headerRowCount")??1,totals:k(e,"totalsRowCount")??0,columns:x(d(e?.tableColumns)?.tableColumn).map(i=>({name:N(l(i,"name")??"").trim(),calculated:i.calculatedColumnFormula!==void 0})),style:l(n,"name")??"none",...s?{filter:ve(s)}:{}}}function re(r){const e=r.trim();if(e==="")return;const t=/^"((?:[^"]|"")*)"$/u.exec(e);if(t)return(t[1]??"").replaceAll('""','"');const o=Number(e);if(!Number.isNaN(o))return o;const n=ne(e,!0);return n.ok?ge(n.node):void 0}const Se=r=>r!==void 0&&Le.includes(r);function se(r){const e=l(r,"type")??"num",t=l(r,"val")??(r.f===void 0?void 0:E(r.f)),o=t===void 0?void 0:re(t);return{at:e,...o===void 0?{}:{value:o}}}const it=Ie,at=r=>{const e=r.formula??r.f;return(Array.isArray(e)?e:e===void 0?[]:[e]).map(E)};function dt(r,e,t,o){const n=l(r,"type")??"",s={range:e,...v(r,"stopIfTrue")===!0?{stop:!0}:{}},i={...t.bold===void 0?{}:{bold:t.bold},...t.italic===void 0?{}:{italic:t.italic},...t.underline===void 0?{}:{underline:t.underline!==!1},...t.strike===void 0?{}:{strike:t.strike},...t.color===void 0?{}:{color:t.color},...typeof t.fill=="string"?{fill:t.fill}:{},...t.border===void 0?{}:{border:t.border}},c=at(r);switch(n){case"cellIs":{const a=l(r,"operator"),f=c.flatMap(h=>{const u=re(h);return u===void 0?[]:[u]});return!Se(a)||f.length===0?`a cellIs rule of ${a??"no operator"}`:{...s,...i,type:"cellIs",operator:a,formula:f}}case"containsText":case"notContainsText":case"beginsWith":case"endsWith":{const a=l(r,"text");return a===void 0?`a ${n} rule with no text`:{...s,...i,type:"containsText",...n==="containsText"?{}:{operator:n==="notContainsText"?"notContains":n},text:N(a)}}case"duplicateValues":case"uniqueValues":return{...s,...i,type:n};case"top10":return{...s,...i,type:"top10",rank:k(r,"rank")??10,...v(r,"percent")===!0?{percent:!0}:{},...v(r,"bottom")===!0?{bottom:!0}:{}};case"aboveAverage":return{...s,...i,type:"aboveAverage",...v(r,"aboveAverage")===!1?{below:!0}:{},...v(r,"equalAverage")===!0?{equal:!0}:{}};case"expression":{const a=c[0]===void 0?void 0:ne(c[0],!0);return a?.ok?{...s,...i,type:"expression",formula:ge(a.node)}:"an expression rule that cannot be read"}case"dataBar":{const a=d(r.dataBar),f=D(d(a?.color??a?.fillColor),o),[h,u]=x(a?.cfvo).map(se);return f===void 0?"a data bar with no colour":{...s,type:"dataBar",color:f,...h&&h.at!=="min"?{min:h}:{},...u&&u.at!=="max"?{max:u}:{},...v(a,"showValue")===!1?{show:!1}:{}}}case"colorScale":{const a=d(r.colorScale),f=x(a?.cfvo).map(se),h=x(a?.color).map(b=>D(b,o)),u=f.flatMap((b,p)=>{const m=h[p];return m===void 0?[]:[{...b,color:m}]});return u.length<2?"a colour scale with too few stops":{...s,type:"colorScale",stops:u.slice(0,3)}}case"iconSet":{const a=d(r.iconSet),f=l(a,"iconSet")??"3TrafficLights1";if(!it.includes(f))return`the icon set ${f}`;if(a?.cfIcon!==void 0)return"an icon set of icons chosen one by one";const h=x(a?.cfvo).map(se);return{...s,type:"iconSet",icons:f,...h.length>=3?{stops:h.slice(0,5)}:{},...v(a,"reverse")===!0?{reverse:!0}:{},...v(a,"showValue")===!1?{show:!1}:{}}}default:return`a ${n} rule`}}const Ce={conditional:"{78C0D931-6437-407d-A8EE-F0AAD7539E65}",validations:"{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}"},Te=(r,e)=>x(d(r.extLst)?.ext).find(t=>l(t,"uri")?.toUpperCase()===e.toUpperCase());function ct(r,e,t){const o=[],n=[],s=new Set,i=(a,f,h)=>{const u=dt(a,f,h,t);typeof u=="string"?n.push(`${u} on ${f}`):o.push({priority:k(a,"priority")??0,rule:u})};for(const a of x(r.conditionalFormatting)){const f=l(a,"sqref")??"";if(!te(f)){n.push(`a rule on ${f}`);continue}for(const h of x(a.cfRule)){const u=E(d(d(h.extLst)?.ext)?.id);u!==""&&s.add(u.toUpperCase());const b=k(h,"dxfId");i(h,f,b===void 0?{}:e[b]??{})}}const c=d(Te(r,Ce.conditional)?.conditionalFormattings);for(const a of x(c?.conditionalFormatting)){const f=E(a.sqref).trim();for(const h of x(a.cfRule)){if(s.has((l(h,"id")??"").toUpperCase()))continue;if(!te(f)){n.push(`a rule on ${f}`);continue}const u=d(h.dxf);i(h,f,u?ke(u,t):{})}}return{rules:o.sort((a,f)=>a.priority-f.priority).map(a=>a.rule),unread:n}}const ft=Re;function Ee(r,e,t,o){const n=l(r,"type")??"none";if(n==="none"&&l(r,"prompt")===void 0)return;if(!ft.includes(n)||!te(e))return`a ${n} rule on ${e}`;const s=/^"((?:[^"]|"")*)"$/u.exec(t.trim()),i=n==="list"&&s?(s[1]??"").replaceAll('""','"').split(","):void 0,c=[t,o].flatMap(m=>{const $=re(m);return $===void 0?[]:[$]}),a=l(r,"operator"),f=m=>Object.fromEntries(Object.entries(m).filter(([,$])=>$!==void 0)),h=f({title:l(r,"promptTitle"),message:l(r,"prompt")}),u=f({style:l(r,"errorStyle"),title:l(r,"errorTitle"),message:l(r,"error")}),b=v(r,"showInputMessage")!==!0,p=v(r,"showErrorMessage")!==!0;return{range:e,type:n,...Se(a)&&a!=="between"?{operator:a}:{},...i?{values:i}:{formula:c},...v(r,"allowBlank")===!0?{}:{blank:!1},...v(r,"showDropDown")===!0?{dropdown:!1}:{},...b||Object.keys(h).length>0?{prompt:{...h,...b?{show:!1}:{}}}:{},...p||Object.keys(u).length>0?{error:{...u,...p?{show:!1}:{}}}:{}}}function lt(r){const e=[],t=[],o=s=>{typeof s=="string"?t.push(s):s&&e.push(s)};for(const s of x(d(r.dataValidations)?.dataValidation))o(Ee(s,l(s,"sqref")??"",E(s.formula1),E(s.formula2)));const n=d(Te(r,Ce.validations)?.dataValidations);for(const s of x(n?.dataValidation))o(Ee(s,E(s.sqref).trim(),E(d(s.formula1)?.f),E(d(s.formula2)?.f)));return{rules:e,unread:t}}function ut(r){const e=/^(-?\d{4,})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?)?(?:Z|[+-]\d{2}:?\d{2})?$/u.exec(r)??/^()()()(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/u.exec(r);if(!e)return;const t=e[1]==="",o=t?1899:Number(e[1]),n=t?12:Number(e[2]),s=t?30:Number(e[3]),i=Number(e[4]??0)*3600+Number(e[5]??0)*60+Number(e[6]??0)+Number(e[7]??0),c=new Date(Date.UTC(o,n-1,s)+i*1e3);if(Number.isNaN(c.getTime()))return;const a=_e(c);return t?a-Math.floor(a):a}let ie;function Oe(r,e){const t=r.row-e.row,o=r.col-e.col;Object.defineProperty(r,"node",{get:()=>(ie?.cell!==r&&(ie={cell:r,node:Fe(e.node,t,o)}),ie.node),set:n=>{Object.defineProperty(r,"node",{value:n,writable:!0,enumerable:!0,configurable:!0})},enumerable:!0,configurable:!0}),r.key=e.key}function ae(r,e,t){const o=ne(r,e,t);return o.ok?{node:o.node}:{unread:r}}function ht(r){const e=B(r.ref??""),t=f=>{if(f===void 0||f==="")return"";const h=ue(f.replaceAll("$",""));return h?`$${le(h.col)}$${String(h.row+1)}`:void 0},o=t(r.r1),n=t(r.r2);if(!e||o===void 0||o===""||n===void 0)return;const s=r.dt2D==="1"||r.dt2D==="true",i=r.dtr==="1"||r.dtr==="true",c=s?`${o},${n}`:i?`${o},`:`,${o}`,a=De(`=TABLE(${c})`);return a.ok?{ref:e,node:a.node}:void 0}function pt(r){for(const{ref:e,node:t}of r.dataTables){const o=new Set;for(const n of r.cells)n.row<e.top||n.row>e.bottom||n.col<e.left||n.col>e.right||(n.node=t,Reflect.deleteProperty(n,"unread"),o.add(`${String(n.row)}:${String(n.col)}`));for(let n=e.top;n<=e.bottom;n++)for(let s=e.left;s<=e.right;s++)o.has(`${String(n)}:${String(s)}`)||r.cells.push({row:n,col:s,value:void 0,node:t,style:0})}}class mt{cells=[];rows=[];dataTables=[];rich=[];outlined=!1;rest=[];xml;masters=new Map;above=new Map;left;strings;name;isRangeName;inData=!1;row=-1;nextRow=0;nextCol=0;cell;target;buffer="";skip=0;constructor(e,t,o){this.strings=e,this.name=t,this.isRangeName=o,this.xml=new we(this),this.xml.capture=this.rest}open(e,t){if(!this.inData){e==="sheetData"&&(this.inData=!0,this.xml.capture=void 0);return}const o=this.cell;if(o){if(this.skip>0){this.skip+=1;return}switch(e){case"v":this.target="v",this.buffer="";return;case"f":o.f={...t,text:""},this.target="f",this.buffer="";return;case"is":o.inline={text:"",rich:!1};return;case"r":o.inline&&(o.inline.rich=!0);return;case"t":o.inline&&(this.target="t",this.buffer="");return;case"rPh":case"phoneticPr":case"extLst":this.skip=1;return;default:return}}e==="row"?this.openRow(t):e==="c"&&(this.cell={r:t.r,s:t.s,t:t.t,cm:t.cm,v:void 0,f:void 0,inline:void 0})}close(e){if(!this.inData)return;const t=this.cell;if(!t){e==="sheetData"&&(this.inData=!1,this.xml.capture=this.rest);return}if(this.skip>0){this.skip-=1;return}if(e===this.target){e==="v"?t.v=this.buffer:e==="f"&&t.f?t.f.text=this.buffer:t.inline&&(t.inline.text+=this.buffer),this.target=void 0;return}e==="c"&&(this.cell=void 0,this.readCell(t))}text(e){this.target!==void 0&&this.skip===0&&(this.buffer+=e)}openRow(e){const t=e.r,o=t===void 0?void 0:Number(t);if(o!==void 0&&Number.isInteger(o)&&o>Q)throw new Error(`${this.name} has a row ${t??""}, and ${GRID_END}.`);const n=o!==void 0&&Number.isInteger(o)&&o>0?o-1:this.nextRow;this.row=n,this.nextRow=n+1,this.nextCol=0;const s={row:n},i=e.ht===void 0?void 0:Number(e.ht),c=h=>h==="1"||h==="true";i!==void 0&&Number.isFinite(i)&&c(e.customHeight)&&(s.height=Ze(i)),c(e.hidden)&&(s.hidden=!0);const a=e.s===void 0?void 0:Number(e.s);a!==void 0&&a!==0&&c(e.customFormat)&&(s.style=a);const f=Number(e.outlineLevel??0);f>0&&(s.level=Math.min(7,f),this.outlined=!0),Object.keys(s).length>1&&this.rows.push(s)}value(e,t){const o=e.t??"n";if(o==="inlineStr"){const s=e.inline;return s?{value:N(s.text),...s.rich?{rich:!0}:{}}:{value:e.v===void 0?"":N(e.v)}}const n=e.v;if(n===void 0)return{value:void 0};switch(o){case"s":{const s=this.strings[Number(n)];return s?{value:s.text,...s.rich?{rich:!0}:{}}:{value:""}}case"str":return{value:N(n)};case"b":return{value:n.trim()==="1"||n.trim()==="true"};case"e":return{value:Pe(n.trim())??je.VALUE};case"d":return{value:ut(n.trim())??n};default:{if(n.trim()==="")return{value:void 0};const s=Number(n);if(Number.isNaN(s))throw new Error(`${t} says it holds a number and holds ${n}.`);return{value:s}}}}formula(e,t,o,n){const s=e.f;if(s===void 0)return;const i=s.t??"normal",c=s.text;if(i==="dataTable"){const p=ht(s);p?this.dataTables.push(p):n.unread=`a data table's {=TABLE(${s.r1??""})}`;return}if(i==="array"){Object.assign(n,ae(c,!0,this.isRangeName));const p=B(s.ref??"");p&&(n.array=p),e.cm!==void 0&&(n.dynamic=!0);return}if(i==="shared"){const p=s.si??"";if(c!==""){const $=ae(c,!1,this.isRangeName),g=$.node?me($.node,t,o):"";this.masters.set(p,{node:$.node,unread:$.unread,row:t,col:o,key:g}),Object.assign(n,$),$.node&&(n.key=g);return}const m=this.masters.get(p);if(!m){n.unread=`a shared formula of a group that has no first cell (${p})`;return}m.node?Oe(n,{node:m.node,row:m.row,col:m.col,key:m.key}):m.unread!==void 0&&(n.unread=m.unread);return}if(c==="")return;const a=ae(c,!1,this.isRangeName);if(!a.node){Object.assign(n,a);return}const f=me(a.node,t,o),h=this.left?.row===t?this.left:void 0,u=[this.above.get(o),h].find(p=>p?.key===f);u?Oe(n,u):(n.node=a.node,n.key=f);const b=u??{node:a.node,row:t,col:o,key:f};this.above.set(o,b),this.left=b}readCell(e){const t=e.r===void 0?void 0:Je(e.r,this.name),o=t?.row??this.row,n=t?.col??this.nextCol;if(n>=Z)throw new Error(`${this.name} has a cell past its last column, and ${GRID_END}.`);this.nextCol=n+1;const s=e.r??ee({row:o,col:n}),{value:i,rich:c}=this.value(e,s),a={row:o,col:n,value:i,style:e.s===void 0?0:Number(e.s)||0};c===!0&&(a.rich=!0,this.rich.push(s)),this.formula(e,o,n,a),this.cells.push(a)}}function gt(r,e,t){const o=[],n=u=>o.push(`${r}: ${u}`);t.length>0&&n(`${V(t.length,"cell")} of rich text, kept as plain text (${placesLine(t)})`);const s=x(d(e.hyperlinks)?.hyperlink).filter(u=>l(u,"tooltip")!==void 0);s.length>0&&n(`the tooltips of ${V(s.length,"link")} (${placesLine(s.map(u=>l(u,"ref")??""))})`),e.sortState!==void 0&&n("a sort");const i=d(e.sheetProtection);v(i,"sheet")===!0&&(l(i,"password")!==void 0||l(i,"hashValue")!==void 0)&&n("its protection's password: it is protected with none"),e.protectedRanges!==void 0&&n("protected ranges");const c=d(e.headerFooter);(c?.evenHeader!==void 0||c?.evenFooter!==void 0||c?.firstHeader!==void 0||c?.firstFooter!==void 0)&&n("its print header and footer of the first or even pages");const a=d(e.printOptions);a&&["gridLines","headings","horizontalCentered","verticalCentered"].some(u=>v(a,u)===!0)&&n("its print options (gridlines, headings, centring)"),(e.rowBreaks!==void 0||e.colBreaks!==void 0)&&n("its page breaks"),e.oleObjects!==void 0&&n("embedded objects"),e.controls!==void 0&&n("form controls"),e.dataConsolidate!==void 0&&n("a consolidation"),e.customSheetViews!==void 0&&n("custom views"),x(d(e.sheetViews)?.sheetView).some(u=>l(d(u.pane),"state")==="split")&&n("a split, not frozen, window");const h=JSON.stringify(e.extLst??"");return h.includes("sparklineGroups")&&n("sparklines"),h.includes("slicerList")&&n("slicers"),o}function bt(r,e){const t=[],o=(s,i,c)=>{const a=r.count(s);a>0&&t.push(V(a,i,c))};r.has("xl/vbaProject.bin")&&t.push("VBA macros"),o(/^xl\/pivotTables\/pivotTable\d*\.xml$/u,"pivot table"),o(/^xl\/chartsheets\/[^/]+\.xml$/u,"chart sheet"),o(/^xl\/dialogsheets\/[^/]+\.xml$/u,"dialog sheet"),o(/^xl\/macrosheets\/[^/]+\.xml$/u,"macro sheet");const n=r.names.filter(s=>s.startsWith("xl/media/")&&!e.has(s)).length;return n>0&&t.push(V(n,"image")),o(/^xl\/embeddings\//u,"embedded object"),o(/^xl\/slicers\/[^/]+\.xml$/u,"slicer part"),o(/^xl\/timelines\/[^/]+\.xml$/u,"timeline part"),o(/^xl\/ctrlProps\/[^/]+\.xml$/u,"form control"),o(/^xl\/activeX\/[^/]+\.xml$/u,"ActiveX control"),o(/^xl\/queryTables\/[^/]+\.xml$/u,"query table"),r.has("xl/connections.xml")&&t.push("data connections"),r.names.some(s=>s.startsWith("xl/richData/"))&&t.push("rich values (data types, pictures in cells)"),r.names.some(s=>/^customXml\/item\d+\.xml$/u.test(s)&&(r.text(s)??"").includes("DataMashup"))&&t.push("Power Query queries"),t}export function readHeaderFooter(r){const e={left:"",center:"",right:""};let t="center",o=new Set;for(let n=0;n<r.length;n++){const s=r[n],i=r[n+1];if(s==="&"&&(i==="L"||i==="C"||i==="R")){t=i==="L"?"left":i==="C"?"center":"right",o=new Set([...o,t]),n+=1;continue}if(s==="&"&&i==="&"){e[t]+="&&",n+=1;continue}e[t]+=s??""}return Object.fromEntries(Object.entries(e).filter(([n,s])=>s!==""||o.has(n)))}const wt=new Map(Object.entries(Me).map(([r,e])=>[e,r]));function xt(r,e,t){const o={},n=d(r.pageSetup),s=l(n,"orientation");(s==="portrait"||s==="landscape")&&(o.orientation=s);const i=k(n,"paperSize");if(i!==void 0){const b=wt.get(i);b?o.paper=b:t.push(`${e}: its paper size, Excel's number ${String(i)}`)}v(d(d(r.sheetPr)?.pageSetUpPr),"fitToPage")===!0&&(o.fit={width:k(n,"fitToWidth")??1,height:k(n,"fitToHeight")??1});const c=d(r.pageMargins),a={};for(const b of Object.keys(fe)){const p=k(c,b);p!==void 0&&p!==fe[b]&&(a[b]=p)}Object.keys(a).length>0&&(o.margins=a);const f=d(r.headerFooter),h=E(f?.oddHeader),u=E(f?.oddFooter);return h!==""&&(o.header=readHeaderFooter(N(h))),u!==""&&(o.footer=readHeaderFooter(N(u))),o}function yt(r,e,t,o,n){const s=r.rels(e),i=new Map;for(const a of s.filter(f=>f.type==="comments")){const f=d(r.xml(a.target)?.comments),h=d(f?.authors)?.author,u=(Array.isArray(h)?h:h===void 0?[]:[h]).map(b=>N(E(b)));for(const b of x(d(f?.commentList)?.comment)){const p=l(b,"ref")??"",m=d(b.text),$=x(m?.r),g=N($.length>0?$.map(C=>E(C.t)).join(""):E(m?.t)),S=u[k(b,"authorId")??-1];p!==""&&g!==""&&i.set(p,{ref:p,text:g,...S===void 0||S===""?{}:{author:S}})}}let c=0;for(const a of s.filter(f=>f.type==="threadedComment")){const f=d(r.xml(a.target)?.ThreadedComments),h=new Map;for(const u of x(f?.threadedComment)){const b=l(u,"ref")??"",p=N(E(u.text)),m=h.get(b)??{texts:[]};if(m.texts.length===0){const $=o.get(l(u,"personId")??"");$!==void 0&&(m.author=$)}m.texts.push(p),h.set(b,m)}for(const[u,b]of h)c+=1,i.set(u,{ref:u,text:b.texts.join(`
3
- `),...b.author===void 0?{}:{author:b.author}})}return c>0&&n.push(`${t}: ${V(c,"threaded comment")}, kept as notes, replies after the first line`),[...i.values()]}function $t(r,e,t,o,n,s,i,c,a,f,h){const u=new mt(n,t,a);if(!r.stream(e,u.xml))throw new Error(`${e} is not in the file.`);pt(u);const b=xe(u.rest.join("")),p=d(b.worksheet);if(!p)throw new Error(`${e} is not a worksheet.`);const m=x(d(p.cols)?.col).map(y=>{const T=k(y,"width"),F=k(y,"style"),_=k(y,"outlineLevel")??0,A=(k(y,"min")??1)-1,de=(k(y,"max")??1)-1;if(de>=Z)throw new Error(`${t} sets a column past its last, and ${GRID_END}.`);const ce=v(y,"customWidth"),Y=T===void 0?void 0:Ge(T);return{min:A,max:de,...Y!==void 0&&(ce===!0||ce===void 0&&Y!==Ae)?{width:Y}:{},...v(y,"hidden")===!0?{hidden:!0}:{},...F===void 0||F===0?{}:{style:F},..._>0?{level:Math.min(7,_)}:{}}}),$=x(d(p.mergeCells)?.mergeCell).flatMap(y=>{const T=B(l(y,"ref")??"");return T?[T]:[]}),g=x(d(p.sheetViews)?.sheetView)[0],S=d(g?.pane);let C;const I=l(S,"state");if(I==="frozen"||I==="frozenSplit"){const y=ue(l(g,"topLeftCell")??"A1")??{row:0,col:0};C={row:y.row+(k(S,"ySplit")??0),col:y.col+(k(S,"xSplit")??0)}}const M=r.rels(e),R=M.filter(y=>y.type==="table").flatMap(y=>{const T=st(r.xml(y.target));return T?[T]:[]}),j=D(d(d(p.sheetPr)?.tabColor),s),O=gt(t,p,u.rich),X=ct(p,i,s),q=lt(p);for(const y of X.unread)O.push(`${t}: a conditional format, ${y}`);for(const y of q.unread)O.push(`${t}: a data validation, ${y}`);const z=d(p.autoFilter),J=B(l(z,"ref")??""),P=z&&J?{ref:J,...ve(z)}:void 0;P&&P.unread>0&&O.push(`${t}: ${V(P.unread,"filter")} by condition on ${l(z,"ref")??""}, its rows left as they were hidden`);const{charts:G,pictures:K}=vt(r,e,t,m,u.rows,O,f,h),U={},w=new Map(M.map(y=>[y.id,y]));for(const y of x(d(p.hyperlinks)?.hyperlink)){const T=l(y,"ref");if(T===void 0)continue;const F=l(y,"location"),_=l(y,"id"),A=_===void 0?void 0:w.get(_)?.target;A!==void 0?U[T]=F===void 0?A:`${A}#${F}`:F!==void 0&&(U[T]=`#${F}`)}const L=d(p.sheetProtection),H=xt(p,t,O);return{sheet:{name:t,state:o,cells:u.cells,merges:$,...C?{freeze:C}:{},...l(g,"showGridLines")==="0"?{gridlines:!1}:{},...j===void 0?{}:{tab:j},columns:m,rows:u.rows,tables:R,conditional:X.rules,validations:q.rules,scenarios:x(d(p.scenarios)?.scenario).map(y=>({name:l(y,"name")??"",cells:x(y.inputCells).map(T=>({at:l(T,"r")??"",value:l(T,"val")??""}))})),...P?{filter:P}:{},charts:G,links:U,notes:yt(r,e,t,c,O),pictures:K,...v(L,"sheet")===!0?{protect:!0}:{},...Object.keys(H).length>0?{print:H}:{}},lost:O}}const Ae=64,kt=20;function vt(r,e,t,o,n,s,i,c){const a=p=>o.find(m=>p>=m.min&&p<=m.max)?.width??Ae,f=new Map(n.map(p=>[p.row,p.height])),h=p=>f.get(p)??kt,u=[],b=[];for(const p of r.rels(e).filter(m=>m.type==="drawing")){const m=Ve(r.xml(p.target),a,h),$=r.rels(p.target);for(const g of m.anchors){const S=$.find(R=>R.id===g.id),C=ee(g.at);if(g.width<=0||g.height<=0){s.push(`${t}: the chart at ${C}, of no size`);continue}const I=[],M=Ue(S?r.xml(S.target):void 0,I,c);if(typeof M=="string"){s.push(`${t}: the chart at ${C}, as ${M}`);continue}for(const R of I)s.push(`${t}: the chart at ${C} without its ${R}`);u.push({...M,at:C,...g.x===void 0?{}:{x:g.x},...g.y===void 0?{}:{y:g.y},...g.width===pe.width?{}:{width:g.width},...g.height===pe.height?{}:{height:g.height}})}for(const g of m.pictures){const S=$.find(M=>M.id===g.id),C=S&&!S.external?r.bytes(S.target):void 0;if(!S||!C){s.push(`${t}: the picture at ${ee(g.at)}, whose image is not in the file`);continue}i.add(S.target);const I=S.target.slice(S.target.lastIndexOf(".")+1).toLowerCase();b.push({row:g.at.row,col:g.at.col,...g.x===void 0?{}:{x:g.x},...g.y===void 0?{}:{y:g.y},width:g.width,height:g.height,...g.name===void 0?{}:{name:g.name},...g.descr===void 0?{}:{descr:g.descr},bytes:C,type:I})}m.others>0&&s.push(`${t}: ${V(m.others,"shape")} of its drawing`)}return{charts:u,pictures:b}}function St(r,e,t){for(const o of r){if(o.sheet===void 0)continue;const n=e[o.sheet];if(!n)continue;const s=o.text.split(",").map(i=>i.slice(i.lastIndexOf("!")+1).replaceAll("$",""));if(o.name==="_xlnm.Print_Area"){const[i]=s;s.length>1&&t.push(`${n.name}: its print area's ranges after the first`),i!==void 0&&B(i)&&(n.print={...n.print,area:i})}else if(o.name==="_xlnm.Print_Titles")for(const i of s)/^\d+:\d+$/u.test(i)?n.print={...n.print,title_rows:i}:/^[A-Za-z]+:[A-Za-z]+$/u.test(i)&&(n.print={...n.print,title_cols:i})}}export function readXlsx(r,e){let t;try{t=new Ke(r,e)}catch(w){throw w instanceof Ne?w:new Error("It is not a zip file, as an .xlsx file is.")}const o=t.rels(""),n=o.find(w=>w.type==="officeDocument")?.target??"xl/workbook.xml";if(n.endsWith(".bin"))throw new Error("It is a binary workbook (.xlsb): save it as .xlsx.");const s=t.xml(n),i=d(s?.workbook);if(!i)throw new Error("It has no workbook part.");const c=t.rels(n),a=w=>c.find(L=>L.type===w)?.target,f=(()=>{const w=a("theme");return w===void 0?void 0:t.text(w)})(),h=f===void 0?ze:He(f),u=a("styles"),b=u===void 0?void 0:t.xml(u),p=rt(b,h),m=be(h,d(b?.styleSheet)),$=Ye(t,a("sharedStrings")),g=[];for(const w of p.lost)g.push(w);const S=d(i.workbookPr),C=qe(d(i.calcPr)),I=d(i.workbookProtection);(v(I,"lockStructure")===!0||v(I,"lockWindows")===!0)&&g.push("the workbook's protection"),i.fileSharing!==void 0&&g.push("its write protection");const M=new Map,R=a("person");if(R!==void 0)for(const w of x(d(t.xml(R)?.personList)?.person))M.set(l(w,"id")??"",N(l(w,"displayName")??""));const j=x(d(i.definedNames)?.definedName).map(w=>{const L=k(w,"localSheetId");return{name:l(w,"name")??"",text:N(E(w)),...L===void 0?{}:{sheet:L},...v(w,"hidden")===!0?{hidden:!0}:{}}}),O=[],X=new Set,q=new Map(c.map(w=>[w.id,w])),z=x(d(i.sheets)?.sheet),J=new Set(z.filter(w=>q.get(l(w,"id")??"")?.type==="worksheet").map(w=>N(l(w,"name")??"").toLowerCase()));for(const[w,L]of z.entries()){const H=q.get(l(L,"id")??""),y=N(l(L,"name")??"");if(H?.type!=="worksheet"){H?.type!=="chartsheet"&&H?.type!=="dialogsheet"&&g.push(`${y}: a sheet of a kind this cannot read`);continue}const T=new Map;for(const A of j)(A.sheet===void 0||A.sheet===w)&&(A.sheet!==void 0||!T.has(A.name.toLowerCase()))&&T.set(A.name.toLowerCase(),Be(A.text));const F=l(L,"state"),_=$t(t,H.target,y,F==="hidden"||F==="veryHidden"?F:"visible",$,m,p.dxfs,M,A=>T.get(A.toLowerCase())===!0,X,A=>J.has(A.toLowerCase()));O[w]=_.sheet,g.push(..._.lost)}St(j,O,g);const P=o.find(w=>w.type==="core-properties")?.target,G=P===void 0?void 0:E(d(t.xml(P)?.coreProperties)?.title).trim(),K=O.filter(w=>w!==void 0),U=new Map;return O.forEach((w,L)=>{w!==void 0&&U.set(L,K.indexOf(w))}),{sheets:K,names:j.flatMap(w=>{if(w.sheet===void 0)return[w];const L=U.get(w.sheet);return L===void 0?[]:[{...w,sheet:L}]}),looks:p.looks,dxfs:p.dxfs,date1904:v(S,"date1904")===!0,font:p.font,...G===void 0||G===""?{}:{title:G},...C===void 0?{}:{iteration:C},lost:[...bt(t,X),...g]}}
2
+ import{ZipLimitError as Le}from"@allyhub/formats";import{SHEET_FILTER_OPERATORS as Re,SHEET_ICONS as Me,SHEET_MARGINS as ce,SHEET_OPERATORS as _e,SHEET_PAPERS as Pe,SHEET_VALIDATIONS as De}from"@allyhub/formats";import{MAX_COLUMNS as J,MAX_ROWS as Q,cellName as ee,columnLetter as te,readAddress as fe,readArea as q,readAreas as ne}from"../address.js";import{ITERATION_DEFAULTS as he}from"../calc/engine.js";import{SHEET_CHART_DEFAULTS as pe}from"../chart.js";import{moveFormula as je,relativeKey as me}from"../formula/move.js";import{parseFormula as ze}from"../formula/parse.js";import{printFormula as ge}from"../formula/print.js";import{ERR as He,errorOf as Be,serialOfDate as Ve}from"../values.js";import{OFFICE_THEME as Ue,colorOf as P,paletteOf as be,themeColors as We}from"./colors.js";import{chartAnchors as qe,readChart as Xe}from"./charts.js";import{isRangeText as Ge,readFileFormula as oe}from"./formula.js";import{BUILTIN_FORMATS as we}from"./numfmt.js";import{XmlStream as xe}from"./sax.js";import{attr as c,flag as y,numberAttr as $,readXml as ye,readXstring as E,tag as d,tags as v,textOf as O}from"./xml.js";import{RunsCollector as $e,readRuns as ve}from"./runs.js";import{ZipIn as Ze}from"./zip.js";function Je(n){if(y(n,"iterate")!==!0)return;const t=$(n,"iterateCount"),e=$(n,"iterateDelta"),o=t===void 0?void 0:Math.min(32767,Math.max(1,Math.round(t))),r=e===void 0?void 0:Math.max(0,e),s={...o===void 0||o===he.max_iterations?{}:{max_iterations:o},...r===void 0||r===he.max_change?{}:{max_change:r}};return Object.keys(s).length>0?s:!0}const ke=7,Ke=n=>Math.floor((256*n+Math.floor(128/ke))/256*ke),Qe=n=>Math.round(n*4/3),re=5;export function placesLine(n){const t=n.slice(0,re).join(", ");return n.length>re?`${t} and ${String(n.length-re)} more`:t}const X=(n,t,e=`${t}s`)=>`${String(n)} ${n===1?t:e}`;export const GRID_END=`Excel's grid ends at ${te(J-1)}${String(Q)} (${Q.toLocaleString("en-US")} rows, ${J.toLocaleString("en-US")} columns)`;function Ye(n,t){let e=0,o=0;const r=n.length;for(;e<r;e++){const i=n.charCodeAt(e),u=i>=65&&i<=90,a=i>=97&&i<=122;if(!u&&!a)break;o=o*26+(u?i-64:i-96)}if(e===0||e===r)return;let s=0;for(let i=e;i<r;i++){const u=n.charCodeAt(i);if(u<48||u>57)return;s=s*10+u-48}if(s!==0){if(e>3||o>J||s>Q)throw new Error(`${t} has a cell at ${n}, and ${GRID_END}.`);return{row:s-1,col:o-1}}}class et{zip;constructor(t,e){this.zip=new Ze(t,e)}get names(){return this.zip.names}has(t){return this.zip.has(t)}text(t){return this.zip.text(t)}bytes(t){return this.zip.bytesOf(t)}xml(t){const e=this.text(t);return e===void 0?void 0:ye(e)}stream(t,e){const o=this.zip.streamText(t,r=>{e.push(r)});return o&&e.end(),o}rels(t){const e=t.lastIndexOf("/"),o=`${t.slice(0,e+1)}_rels/${t.slice(e+1)}.rels`,r=this.xml(o);return v(d(r?.Relationships)?.Relationship).map(s=>{const i=c(s,"Type")??"",u=c(s,"Target")??"",a=c(s,"TargetMode")==="External";return{id:c(s,"Id")??"",type:i.slice(i.lastIndexOf("/")+1),target:a?u:tt(t,u),external:a}})}count(t){return this.names.filter(e=>t.test(e)).length}}function tt(n,t){if(t.startsWith("/"))return t.slice(1);const e=n.split("/").slice(0,-1);for(const o of t.split("/"))o===".."?e.pop():o!=="."&&e.push(o);return e.join("/")}function nt(n,t,e){const o=[];if(t===void 0)return o;let r,s=0,i=!1;const u={open(a,l){if(a==="si"){r={text:"",runs:new $e};return}if(r){if(s>0||a==="rPh"||a==="phoneticPr"||a==="extLst"){s+=1;return}r.runs.open(a,l)||a==="t"&&(i=!0)}},close(a){if(s>0){s-=1;return}if(a==="si"){if(r){const{runs:l}=r.runs;o.push({text:E(r.text),...l.length>0?{runs:ve(l,e)}:{}})}r=void 0;return}r?.runs.close(a),a==="t"&&(i=!1)},text(a){r&&i&&s===0&&(r.text+=a,r.runs.text(a))}};return n.stream(t,new xe(u)),o}function G(n,t){const e=n[t];if(e===void 0)return!1;const o=c(d(e),"val");return o===void 0||o!=="0"&&o!=="false"}const ot=new Set(["double","singleAccounting","doubleAccounting"]);function rt(n,t,e){const o={},r=(a,l)=>c(d(a?.[l]),"val");if(G(n,"b")&&(o.bold=!0),G(n,"i")&&(o.italic=!0),G(n,"strike")&&(o.strike=!0),G(n,"u")){const a=r(n,"u");o.underline=a!==void 0&&ot.has(a)?a:!0}const s=r(n,"name");s!==void 0&&s!==r(t,"name")&&(o.font=s);const i=r(n,"sz");i!==void 0&&i!==r(t,"sz")&&(o.size=Number(i));const u=P(d(n.color),e);return u!==void 0&&u!==P(d(t?.color),e)&&(o.color=u),o}function st(n,t){const e=d(n.patternFill),o=c(e,"patternType");if(o===void 0||o==="none")return;const r=P(d(e?.fgColor),t),s=P(d(e?.bgColor),t);return o==="solid"&&r!==void 0?r:{pattern:o,...r===void 0?{}:{color:r},...s===void 0?{}:{background:s}}}function Se(n,t){const e={};for(const o of["left","right","top","bottom"]){const r=d(n[o]),s=c(r,"style");if(s===void 0||s==="none")continue;const i=P(d(r?.color),t);e[o]={style:s,...i===void 0?{}:{color:i}}}return Object.keys(e).length===0?void 0:e}function it(n){const t={},e=c(n,"horizontal");e!==void 0&&e!=="general"&&(t.align=e);const o=c(n,"vertical");o!==void 0&&o!=="bottom"&&(t.valign=o),y(n,"wrapText")===!0&&(t.wrap=!0),y(n,"shrinkToFit")===!0&&(t.shrink=!0);const r=$(n,"indent");r!==void 0&&r>0&&(t.indent=r);const s=$(n,"textRotation");return s!==void 0&&s>0&&s<=180&&(t.rotation=s),t}function Ce(n,t){const e={},o=d(n.font);if(o){const f=(b,h)=>{o[b]!==void 0&&(e[h]=G(o,b))};f("b","bold"),f("i","italic"),f("strike","strike"),o.u!==void 0&&(e.underline=G(o,"u"));const g=P(d(o.color),t);g!==void 0&&(e.color=g)}const r=d(d(n.fill)?.patternFill),s=P(d(r?.bgColor),t)??P(d(r?.fgColor),t);s!==void 0&&(e.fill=s);const i=d(n.border),u=i&&Se(i,t);u!==void 0&&(e.border=u);const a=d(n.numFmt),l=c(a,"formatCode")??we[$(a,"numFmtId")??-1];return a&&l!==void 0&&l!==""&&l!=="General"&&(e.format=l),e}function at(n,t){const e=d(n?.styleSheet),o=be(t,e),r=new Map(v(d(e?.numFmts)?.numFmt).map(m=>[$(m,"numFmtId")??-1,c(m,"formatCode")?.replace(/^$/u,"General")??"General"])),s=v(d(e?.fonts)?.font),i=v(d(e?.fills)?.fill),u=v(d(e?.borders)?.border),a=v(d(e?.cellXfs)?.xf),l=s[$(a[0],"fontId")??0],f=new Set;i.some(m=>m.gradientFill!==void 0)&&f.add("gradient fills");const g=v(d(e?.cellStyles)?.cellStyle),b=new Set(a.map(m=>$(m,"xfId")??0)),h=g.filter(m=>$(m,"builtinId")!==0&&b.has($(m,"xfId")??-1)).map(m=>E(c(m,"name")??"")).filter(m=>m!=="");h.length>0&&f.add(`the names of cell styles (${h.slice(0,5).join(", ")}${h.length>5?", …":""}): their looks are kept`);const w=a.map(m=>{const C={},F=s[$(m,"fontId")??0];F&&(Object.assign(C,rt(F,l,o)),F.vertAlign!==void 0&&f.add("superscript and subscript"));const L=i[$(m,"fillId")??0],M=L&&st(L,o);M!==void 0&&(C.fill=M);const _=u[$(m,"borderId")??0],N=_&&Se(_,o);N!==void 0&&(C.border=N),_&&c(d(_.diagonal),"style")!==void 0&&f.add("diagonal borders");const j=d(m.alignment);j&&(Object.assign(C,it(j)),$(j,"textRotation")===255&&f.add("vertical text"));const z=d(m.protection);y(z,"locked")===!1&&(C.locked=!1),y(z,"hidden")===!0&&(C.hide_formula=!0);const D=$(m,"numFmtId")??0,H=r.get(D)??we[D];return H!==void 0&&H!=="General"&&(C.format=H),C}),S=c(d(l?.name),"val"),p=c(d(l?.sz),"val");return{looks:w,dxfs:v(d(e?.dxfs)?.dxf).map(m=>Ce(m,o)),font:{...S===void 0?{}:{name:S},...p===void 0?{}:{size:Number(p)}},lost:[...f]}}const dt=n=>{const t=Number(n);return n.trim()!==""&&Number.isFinite(t)?t:n};function lt(n,t){const e=d(n.customFilters);if(e){const i=v(e.customFilter).map(u=>({operator:c(u,"operator")??"equal",value:dt(E(c(u,"val")??""))}));return i.length===0||i.length>2||i.some(u=>!Re.includes(u.operator))?void 0:{conditions:i,...i.length===2&&y(e,"and")!==!0?{or:!0}:{}}}const o=d(n.top10);if(o){const i=$(o,"val");return i===void 0||i<=0?void 0:{top:{count:i,...y(o,"percent")===!0?{percent:!0}:{},...y(o,"top")===!1?{bottom:!0}:{}}}}const r=c(d(n.dynamicFilter),"type");if(r==="aboveAverage")return{average:"above"};if(r==="belowAverage")return{average:"below"};const s=d(n.colorFilter);if(s){const i=t[$(s,"dxfId")??-1];return y(s,"cellColor")===!1?i?.color?{color:{font:i.color}}:void 0:typeof i?.fill=="string"?{color:{fill:i.fill}}:void 0}}function Te(n,t=[]){const e=new Map;let o=0;for(const r of v(n.filterColumn)){const s=$(r,"colId")??0,i=d(r.filters);if(!i){const a=lt(r,t);a?e.set(s,a):Object.keys(r).some(l=>l!=="colId"&&l!=="hiddenButton")&&(o+=1);continue}if(i.dateGroupItem!==void 0){o+=1;continue}const u=v(i.filter).map(a=>E(c(a,"val")??""));e.set(s,{...u.length===0?{}:{values:u},...y(i,"blank")===!0?{blanks:!0}:{}})}return{columns:e,unread:o}}function ut(n,t=[]){const e=d(n?.table),o=q(c(e,"ref")??""),r=c(e,"displayName")??c(e,"name");if(!o||r===void 0)return;const s=d(e?.tableStyleInfo),i=d(e?.autoFilter);return{name:r,ref:o,headers:$(e,"headerRowCount")??1,totals:$(e,"totalsRowCount")??0,columns:v(d(e?.tableColumns)?.tableColumn).map(u=>({name:E(c(u,"name")??"").trim(),calculated:u.calculatedColumnFormula!==void 0})),style:c(s,"name")??"none",options:{...y(s,"showRowStripes")===!1?{banded_rows:!1}:{},...y(s,"showColumnStripes")===!0?{banded_columns:!0}:{},...y(s,"showFirstColumn")===!0?{first_column:!0}:{},...y(s,"showLastColumn")===!0?{last_column:!0}:{}},...i?{filter:Te(i,t)}:{}}}function se(n){const t=n.trim();if(t==="")return;const e=/^"((?:[^"]|"")*)"$/u.exec(t);if(e)return(e[1]??"").replaceAll('""','"');const o=Number(t);if(!Number.isNaN(o))return o;const r=oe(t,!0);return r.ok?ge(r.node):void 0}const Ee=n=>n!==void 0&&_e.includes(n);function ie(n){const t=c(n,"type")??"num",e=c(n,"val")??(n.f===void 0?void 0:O(n.f)),o=e===void 0?void 0:se(e);return{at:t,...o===void 0?{}:{value:o}}}const ct=Me,ft=n=>{const t=n.formula??n.f;return(Array.isArray(t)?t:t===void 0?[]:[t]).map(O)};function ht(n,t,e,o){const r=c(n,"type")??"",s={range:t,...y(n,"stopIfTrue")===!0?{stop:!0}:{}},i={...e.bold===void 0?{}:{bold:e.bold},...e.italic===void 0?{}:{italic:e.italic},...e.underline===void 0?{}:{underline:e.underline!==!1},...e.strike===void 0?{}:{strike:e.strike},...e.color===void 0?{}:{color:e.color},...typeof e.fill=="string"?{fill:e.fill}:{},...e.border===void 0?{}:{border:e.border},...e.format===void 0?{}:{format:e.format}},u=ft(n);switch(r){case"cellIs":{const a=c(n,"operator"),l=u.flatMap(f=>{const g=se(f);return g===void 0?[]:[g]});return!Ee(a)||l.length===0?`a cellIs rule of ${a??"no operator"}`:{...s,...i,type:"cellIs",operator:a,formula:l}}case"containsText":case"notContainsText":case"beginsWith":case"endsWith":{const a=c(n,"text");return a===void 0?`a ${r} rule with no text`:{...s,...i,type:"containsText",...r==="containsText"?{}:{operator:r==="notContainsText"?"notContains":r},text:E(a)}}case"duplicateValues":case"uniqueValues":return{...s,...i,type:r};case"top10":return{...s,...i,type:"top10",rank:$(n,"rank")??10,...y(n,"percent")===!0?{percent:!0}:{},...y(n,"bottom")===!0?{bottom:!0}:{}};case"aboveAverage":return $(n,"stdDev")!==void 0?"an above or below average rule by standard deviations":{...s,...i,type:"aboveAverage",...y(n,"aboveAverage")===!1?{below:!0}:{},...y(n,"equalAverage")===!0?{equal:!0}:{}};case"expression":{const a=u[0]===void 0?void 0:oe(u[0],!0);return a?.ok?{...s,...i,type:"expression",formula:ge(a.node)}:"an expression rule that cannot be read"}case"dataBar":{const a=d(n.dataBar),l=P(d(a?.color??a?.fillColor),o),[f,g]=v(a?.cfvo).map(ie);return l===void 0?"a data bar with no colour":{...s,type:"dataBar",color:l,...f&&f.at!=="min"?{min:f}:{},...g&&g.at!=="max"?{max:g}:{},...y(a,"showValue")===!1?{show:!1}:{}}}case"colorScale":{const a=d(n.colorScale),l=v(a?.cfvo).map(ie),f=v(a?.color).map(b=>P(b,o)),g=l.flatMap((b,h)=>{const w=f[h];return w===void 0?[]:[{...b,color:w}]});return g.length<2?"a colour scale with too few stops":{...s,type:"colorScale",stops:g.slice(0,3)}}case"iconSet":{const a=d(n.iconSet),l=c(a,"iconSet")??"3TrafficLights1";if(!ct.includes(l))return`the icon set ${l}`;if(a?.cfIcon!==void 0)return"an icon set of icons chosen one by one";const f=v(a?.cfvo).map(ie);return{...s,type:"iconSet",icons:l,...f.length>=3?{stops:f.slice(0,5)}:{},...y(a,"reverse")===!0?{reverse:!0}:{},...y(a,"showValue")===!1?{show:!1}:{}}}default:return`a ${r} rule`}}const Oe={conditional:"{78C0D931-6437-407d-A8EE-F0AAD7539E65}",validations:"{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}"},Ae=(n,t)=>v(d(n.extLst)?.ext).find(e=>c(e,"uri")?.toUpperCase()===t.toUpperCase());function pt(n,t,e){const o=[],r=[],s=new Set,i=(a,l,f)=>{const g=ht(a,l,f,e);typeof g=="string"?r.push(`${g} on ${l}`):o.push({priority:$(a,"priority")??0,rule:g})};for(const a of v(n.conditionalFormatting)){const l=c(a,"sqref")??"";if(!ne(l)){r.push(`a rule on ${l}`);continue}for(const f of v(a.cfRule)){const g=O(d(d(f.extLst)?.ext)?.id);g!==""&&s.add(g.toUpperCase());const b=$(f,"dxfId");i(f,l,b===void 0?{}:t[b]??{})}}const u=d(Ae(n,Oe.conditional)?.conditionalFormattings);for(const a of v(u?.conditionalFormatting)){const l=O(a.sqref).trim();for(const f of v(a.cfRule)){if(s.has((c(f,"id")??"").toUpperCase())){const b=mt(d(f.dataBar));b!==void 0&&r.push(`a data bar's ${b} on ${l}`);continue}if(!ne(l)){r.push(`a rule on ${l}`);continue}const g=d(f.dxf);i(f,l,g?Ce(g,e):{})}}return{rules:o.sort((a,l)=>a.priority-l.priority).map(a=>a.rule),unread:r}}function mt(n){if(!n)return;const t=[];y(n,"gradient")===!1&&t.push("solid fill"),y(n,"border")===!0&&t.push("border");const e=c(n,"axisPosition");e!==void 0&&e!=="automatic"&&t.push(`axis ${e}`),y(n,"negativeBarColorSameAsPositive")===!0&&t.push("negative bars in its colour");const o=c(d(n.negativeFillColor),"rgb");return o!==void 0&&o.toUpperCase()!=="FFFF0000"&&t.push("negative bars' colour"),c(n,"direction")==="rightToLeft"&&t.push("right to left"),t.length===0?void 0:t.join(", ")}const gt=De;function Ne(n,t,e,o){const r=c(n,"type")??"none";if(r==="none"&&c(n,"prompt")===void 0)return;if(!gt.includes(r)||!ne(t))return`a ${r} rule on ${t}`;const s=/^"((?:[^"]|"")*)"$/u.exec(e.trim()),i=r==="list"&&s?(s[1]??"").replaceAll('""','"').split(","):void 0,u=[e,o].flatMap(w=>{const S=se(w);return S===void 0?[]:[S]}),a=c(n,"operator"),l=w=>Object.fromEntries(Object.entries(w).filter(([,S])=>S!==void 0)),f=l({title:c(n,"promptTitle"),message:c(n,"prompt")}),g=l({style:c(n,"errorStyle"),title:c(n,"errorTitle"),message:c(n,"error")}),b=y(n,"showInputMessage")!==!0,h=y(n,"showErrorMessage")!==!0;return{range:t,type:r,...Ee(a)&&a!=="between"?{operator:a}:{},...i?{values:i}:{formula:u},...y(n,"allowBlank")===!0?{}:{blank:!1},...y(n,"showDropDown")===!0?{dropdown:!1}:{},...b||Object.keys(f).length>0?{prompt:{...f,...b?{show:!1}:{}}}:{},...h||Object.keys(g).length>0?{error:{...g,...h?{show:!1}:{}}}:{}}}function bt(n){const t=[],e=[],o=s=>{typeof s=="string"?e.push(s):s&&t.push(s)};for(const s of v(d(n.dataValidations)?.dataValidation))o(Ne(s,c(s,"sqref")??"",O(s.formula1),O(s.formula2)));const r=d(Ae(n,Oe.validations)?.dataValidations);for(const s of v(r?.dataValidation))o(Ne(s,O(s.sqref).trim(),O(d(s.formula1)?.f),O(d(s.formula2)?.f)));return{rules:t,unread:e}}function wt(n){const t=/^(-?\d{4,})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?)?(?:Z|[+-]\d{2}:?\d{2})?$/u.exec(n)??/^()()()(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/u.exec(n);if(!t)return;const e=t[1]==="",o=e?1899:Number(t[1]),r=e?12:Number(t[2]),s=e?30:Number(t[3]),i=Number(t[4]??0)*3600+Number(t[5]??0)*60+Number(t[6]??0)+Number(t[7]??0),u=new Date(Date.UTC(o,r-1,s)+i*1e3);if(Number.isNaN(u.getTime()))return;const a=Ve(u);return e?a-Math.floor(a):a}let ae;function Ie(n,t){const e=n.row-t.row,o=n.col-t.col;Object.defineProperty(n,"node",{get:()=>(ae?.cell!==n&&(ae={cell:n,node:je(t.node,e,o)}),ae.node),set:r=>{Object.defineProperty(n,"node",{value:r,writable:!0,enumerable:!0,configurable:!0})},enumerable:!0,configurable:!0}),n.key=t.key}function de(n,t,e){const o=oe(n,t,e);return o.ok?{node:o.node}:{unread:n}}function xt(n){const t=q(n.ref??""),e=l=>{if(l===void 0||l==="")return"";const f=fe(l.replaceAll("$",""));return f?`$${te(f.col)}$${String(f.row+1)}`:void 0},o=e(n.r1),r=e(n.r2);if(!t||o===void 0||o===""||r===void 0)return;const s=n.dt2D==="1"||n.dt2D==="true",i=n.dtr==="1"||n.dtr==="true",u=s?`${o},${r}`:i?`${o},`:`,${o}`,a=ze(`=TABLE(${u})`);return a.ok?{ref:t,node:a.node}:void 0}function yt(n){for(const{ref:t,node:e}of n.dataTables){const o=new Set;for(const r of n.cells)r.row<t.top||r.row>t.bottom||r.col<t.left||r.col>t.right||(r.node=e,Reflect.deleteProperty(r,"unread"),o.add(`${String(r.row)}:${String(r.col)}`));for(let r=t.top;r<=t.bottom;r++)for(let s=t.left;s<=t.right;s++)o.has(`${String(r)}:${String(s)}`)||n.cells.push({row:r,col:s,value:void 0,node:e,style:0})}}class $t{cells=[];rows=[];dataTables=[];outlined=!1;rest=[];xml;masters=new Map;above=new Map;left;strings;palette;name;isRangeName;inData=!1;row=-1;nextRow=0;nextCol=0;cell;target;buffer="";skip=0;constructor(t,e,o,r){this.strings=t,this.palette=e,this.name=o,this.isRangeName=r,this.xml=new xe(this),this.xml.capture=this.rest}open(t,e){if(!this.inData){t==="sheetData"&&(this.inData=!0,this.xml.capture=void 0);return}const o=this.cell;if(o){if(this.skip>0){this.skip+=1;return}switch(t){case"v":this.target="v",this.buffer="";return;case"f":o.f={...e,text:""},this.target="f",this.buffer="";return;case"is":o.inline={text:"",runs:new $e};return;case"t":o.inline&&(this.target="t",this.buffer="");return;case"rPh":case"phoneticPr":case"extLst":this.skip=1;return;default:o.inline?.runs.open(t,e);return}}t==="row"?this.openRow(e):t==="c"&&(this.cell={r:e.r,s:e.s,t:e.t,cm:e.cm,v:void 0,f:void 0,inline:void 0})}close(t){if(!this.inData)return;const e=this.cell;if(!e){t==="sheetData"&&(this.inData=!1,this.xml.capture=this.rest);return}if(this.skip>0){this.skip-=1;return}if(t===this.target){t==="v"?e.v=this.buffer:t==="f"&&e.f?e.f.text=this.buffer:e.inline&&(e.inline.text+=this.buffer,e.inline.runs.text(this.buffer)),this.target=void 0;return}e.inline?.runs.close(t),t==="c"&&(this.cell=void 0,this.readCell(e))}text(t){this.target!==void 0&&this.skip===0&&(this.buffer+=t)}openRow(t){const e=t.r,o=e===void 0?void 0:Number(e);if(o!==void 0&&Number.isInteger(o)&&o>Q)throw new Error(`${this.name} has a row ${e??""}, and ${GRID_END}.`);const r=o!==void 0&&Number.isInteger(o)&&o>0?o-1:this.nextRow;this.row=r,this.nextRow=r+1,this.nextCol=0;const s={row:r},i=t.ht===void 0?void 0:Number(t.ht),u=f=>f==="1"||f==="true";i!==void 0&&Number.isFinite(i)&&u(t.customHeight)&&(s.height=Qe(i)),u(t.hidden)&&(s.hidden=!0);const a=t.s===void 0?void 0:Number(t.s);a!==void 0&&a!==0&&u(t.customFormat)&&(s.style=a);const l=Number(t.outlineLevel??0);l>0&&(s.level=Math.min(7,l),this.outlined=!0),Object.keys(s).length>1&&this.rows.push(s)}value(t,e){const o=t.t??"n";if(o==="inlineStr"){const s=t.inline;if(!s)return{value:t.v===void 0?"":E(t.v)};const{runs:i}=s.runs;return{value:E(s.text),...i.length>0?{runs:ve(i,this.palette)}:{}}}const r=t.v;if(r===void 0)return{value:void 0};switch(o){case"s":{const s=this.strings[Number(r)];return s?{value:s.text,...s.runs?{runs:s.runs}:{}}:{value:""}}case"str":return{value:E(r)};case"b":return{value:r.trim()==="1"||r.trim()==="true"};case"e":return{value:Be(r.trim())??He.VALUE};case"d":return{value:wt(r.trim())??r};default:{if(r.trim()==="")return{value:void 0};const s=Number(r);if(Number.isNaN(s))throw new Error(`${e} says it holds a number and holds ${r}.`);return{value:s}}}}formula(t,e,o,r){const s=t.f;if(s===void 0)return;const i=s.t??"normal",u=s.text;if(i==="dataTable"){const h=xt(s);h?this.dataTables.push(h):r.unread=`a data table's {=TABLE(${s.r1??""})}`;return}if(i==="array"){Object.assign(r,de(u,!0,this.isRangeName));const h=q(s.ref??"");h&&(r.array=h),t.cm!==void 0&&(r.dynamic=!0);return}if(i==="shared"){const h=s.si??"";if(u!==""){const S=de(u,!1,this.isRangeName),p=S.node?me(S.node,e,o):"";this.masters.set(h,{node:S.node,unread:S.unread,row:e,col:o,key:p}),Object.assign(r,S),S.node&&(r.key=p);return}const w=this.masters.get(h);if(!w){r.unread=`a shared formula of a group that has no first cell (${h})`;return}w.node?Ie(r,{node:w.node,row:w.row,col:w.col,key:w.key}):w.unread!==void 0&&(r.unread=w.unread);return}if(u==="")return;const a=de(u,!1,this.isRangeName);if(!a.node){Object.assign(r,a);return}const l=me(a.node,e,o),f=this.left?.row===e?this.left:void 0,g=[this.above.get(o),f].find(h=>h?.key===l);g?Ie(r,g):(r.node=a.node,r.key=l);const b=g??{node:a.node,row:e,col:o,key:l};this.above.set(o,b),this.left=b}readCell(t){const e=t.r===void 0?void 0:Ye(t.r,this.name),o=e?.row??this.row,r=e?.col??this.nextCol;if(r>=J)throw new Error(`${this.name} has a cell past its last column, and ${GRID_END}.`);this.nextCol=r+1;const s=t.r??ee({row:o,col:r}),{value:i,runs:u}=this.value(t,s),a={row:o,col:r,value:i,style:t.s===void 0?0:Number(t.s)||0};u&&(a.runs=u),this.formula(t,o,r,a),this.cells.push(a)}}function vt(n,t){const e=[],o=f=>e.push(`${n}: ${f}`),r=v(d(t.hyperlinks)?.hyperlink).filter(f=>c(f,"tooltip")!==void 0);r.length>0&&o(`the tooltips of ${X(r.length,"link")} (${placesLine(r.map(f=>c(f,"ref")??""))})`),t.sortState!==void 0&&o("a sort");const s=d(t.sheetProtection);y(s,"sheet")===!0&&(c(s,"password")!==void 0||c(s,"hashValue")!==void 0)&&o("its protection's password: it is protected with none"),t.protectedRanges!==void 0&&o("protected ranges");const i=d(t.headerFooter);(i?.evenHeader!==void 0||i?.evenFooter!==void 0||i?.firstHeader!==void 0||i?.firstFooter!==void 0)&&o("its print header and footer of the first or even pages");const u=d(t.printOptions);u&&["gridLines","headings","horizontalCentered","verticalCentered"].some(f=>y(u,f)===!0)&&o("its print options (gridlines, headings, centring)"),t.oleObjects!==void 0&&o("embedded objects"),t.controls!==void 0&&o("form controls"),t.dataConsolidate!==void 0&&o("a consolidation"),t.customSheetViews!==void 0&&o("custom views"),v(d(t.sheetViews)?.sheetView).some(f=>c(d(f.pane),"state")==="split")&&o("a split, not frozen, window");const l=JSON.stringify(t.extLst??"");return l.includes("sparklineGroups")&&o("sparklines"),l.includes("slicerList")&&o("slicers"),e}function kt(n,t){const e=[],o=(s,i,u)=>{const a=n.count(s);a>0&&e.push(X(a,i,u))};n.has("xl/vbaProject.bin")&&e.push("VBA macros"),o(/^xl\/pivotTables\/pivotTable\d*\.xml$/u,"pivot table"),o(/^xl\/chartsheets\/[^/]+\.xml$/u,"chart sheet"),o(/^xl\/dialogsheets\/[^/]+\.xml$/u,"dialog sheet"),o(/^xl\/macrosheets\/[^/]+\.xml$/u,"macro sheet");const r=n.names.filter(s=>s.startsWith("xl/media/")&&!t.has(s)).length;return r>0&&e.push(X(r,"image")),o(/^xl\/embeddings\//u,"embedded object"),o(/^xl\/slicers\/[^/]+\.xml$/u,"slicer part"),o(/^xl\/timelines\/[^/]+\.xml$/u,"timeline part"),o(/^xl\/ctrlProps\/[^/]+\.xml$/u,"form control"),o(/^xl\/activeX\/[^/]+\.xml$/u,"ActiveX control"),o(/^xl\/queryTables\/[^/]+\.xml$/u,"query table"),n.has("xl/connections.xml")&&e.push("data connections"),n.names.some(s=>s.startsWith("xl/richData/"))&&e.push("rich values (data types, pictures in cells)"),n.names.some(s=>/^customXml\/item\d+\.xml$/u.test(s)&&(n.text(s)??"").includes("DataMashup"))&&e.push("Power Query queries"),e}export function readHeaderFooter(n){const t={left:"",center:"",right:""};let e="center",o=new Set;for(let r=0;r<n.length;r++){const s=n[r],i=n[r+1];if(s==="&"&&(i==="L"||i==="C"||i==="R")){e=i==="L"?"left":i==="C"?"center":"right",o=new Set([...o,e]),r+=1;continue}if(s==="&"&&i==="&"){t[e]+="&&",r+=1;continue}t[e]+=s??""}return Object.fromEntries(Object.entries(t).filter(([r,s])=>s!==""||o.has(r)))}const St=new Map(Object.entries(Pe).map(([n,t])=>[t,n]));function Ct(n,t,e){const o={},r=d(n.pageSetup),s=c(r,"orientation");(s==="portrait"||s==="landscape")&&(o.orientation=s);const i=$(r,"paperSize");if(i!==void 0){const p=St.get(i);p?o.paper=p:e.push(`${t}: its paper size, Excel's number ${String(i)}`)}y(d(d(n.sheetPr)?.pageSetUpPr),"fitToPage")===!0&&(o.fit={width:$(r,"fitToWidth")??1,height:$(r,"fitToHeight")??1});const u=$(r,"scale");u!==void 0&&u!==100&&u>=10&&u<=400&&(o.scale=Math.round(u));const a=p=>v(d(n[p])?.brk).filter(m=>y(m,"man")===!0).map(m=>$(m,"id")).filter(m=>m!==void 0&&m>0).sort((m,C)=>m-C),l=a("rowBreaks").map(p=>p+1),f=a("colBreaks").map(p=>te(p));(l.length>0||f.length>0)&&(o.breaks={...l.length>0?{rows:l}:{},...f.length>0?{cols:f}:{}});const g=d(n.pageMargins),b={};for(const p of Object.keys(ce)){const m=$(g,p);m!==void 0&&m!==ce[p]&&(b[p]=m)}Object.keys(b).length>0&&(o.margins=b);const h=d(n.headerFooter),w=O(h?.oddHeader),S=O(h?.oddFooter);return w!==""&&(o.header=readHeaderFooter(E(w))),S!==""&&(o.footer=readHeaderFooter(E(S))),o}function Tt(n,t,e,o,r){const s=n.rels(t),i=new Map;for(const a of s.filter(l=>l.type==="comments")){const l=d(n.xml(a.target)?.comments),f=d(l?.authors)?.author,g=(Array.isArray(f)?f:f===void 0?[]:[f]).map(b=>E(O(b)));for(const b of v(d(l?.commentList)?.comment)){const h=c(b,"ref")??"",w=d(b.text),S=v(w?.r),p=E(S.length>0?S.map(C=>O(C.t)).join(""):O(w?.t)),m=g[$(b,"authorId")??-1];h!==""&&p!==""&&i.set(h,{ref:h,text:p,...m===void 0||m===""?{}:{author:m}})}}let u=0;for(const a of s.filter(l=>l.type==="threadedComment")){const l=d(n.xml(a.target)?.ThreadedComments),f=new Map;for(const g of v(l?.threadedComment)){const b=c(g,"ref")??"",h=E(O(g.text)),w=f.get(b)??{texts:[]};if(w.texts.length===0){const S=o.get(c(g,"personId")??"");S!==void 0&&(w.author=S)}w.texts.push(h),f.set(b,w)}for(const[g,b]of f)u+=1,i.set(g,{ref:g,text:b.texts.join(`
3
+ `),...b.author===void 0?{}:{author:b.author}})}return u>0&&r.push(`${e}: ${X(u,"threaded comment")}, kept as notes, replies after the first line`),[...i.values()]}function Et(n,t,e,o,r,s,i,u,a,l,f){const g=new $t(r,s,e,a);if(!n.stream(t,g.xml))throw new Error(`${t} is not in the file.`);yt(g);const b=ye(g.rest.join("")),h=d(b.worksheet);if(!h)throw new Error(`${t} is not a worksheet.`);const w=v(d(h.cols)?.col).map(k=>{const T=$(k,"width"),R=$(k,"style"),V=$(k,"outlineLevel")??0,A=($(k,"min")??1)-1,le=($(k,"max")??1)-1;if(le>=J)throw new Error(`${e} sets a column past its last, and ${GRID_END}.`);const ue=y(k,"customWidth"),Y=T===void 0?void 0:Ke(T);return{min:A,max:le,...Y!==void 0&&(ue===!0||ue===void 0&&Y!==Fe)?{width:Y}:{},...y(k,"hidden")===!0?{hidden:!0}:{},...R===void 0||R===0?{}:{style:R},...V>0?{level:Math.min(7,V)}:{}}}),S=v(d(h.mergeCells)?.mergeCell).flatMap(k=>{const T=q(c(k,"ref")??"");return T?[T]:[]}),p=v(d(h.sheetViews)?.sheetView)[0],m=d(p?.pane);let C;const F=c(m,"state");if(F==="frozen"||F==="frozenSplit"){const k=fe(c(p,"topLeftCell")??"A1")??{row:0,col:0};C={row:k.row+($(m,"ySplit")??0),col:k.col+($(m,"xSplit")??0)}}const L=n.rels(t),M=L.filter(k=>k.type==="table").flatMap(k=>{const T=ut(n.xml(k.target),i);return T?[T]:[]}),_=P(d(d(h.sheetPr)?.tabColor),s),N=vt(e,h),j=pt(h,i,s),z=bt(h);for(const k of j.unread)N.push(`${e}: a conditional format, ${k}`);for(const k of z.unread)N.push(`${e}: a data validation, ${k}`);const D=d(h.autoFilter),H=q(c(D,"ref")??""),B=D&&H?{ref:H,...Te(D,i)}:void 0;B&&B.unread>0&&N.push(`${e}: ${X(B.unread,"filter")} by condition on ${c(D,"ref")??""}, its rows left as they were hidden`);const{charts:Z,pictures:K}=Nt(n,t,e,w,g.rows,N,l,f),W={},x=new Map(L.map(k=>[k.id,k]));for(const k of v(d(h.hyperlinks)?.hyperlink)){const T=c(k,"ref");if(T===void 0)continue;const R=c(k,"location"),V=c(k,"id"),A=V===void 0?void 0:x.get(V)?.target;A!==void 0?W[T]=R===void 0?A:`${A}#${R}`:R!==void 0&&(W[T]=`#${R}`)}const I=d(h.sheetProtection),U=Ct(h,e,N);return{sheet:{name:e,state:o,cells:g.cells,merges:S,...C?{freeze:C}:{},...c(p,"showGridLines")==="0"?{gridlines:!1}:{},..._===void 0?{}:{tab:_},columns:w,rows:g.rows,tables:M,conditional:j.rules,validations:z.rules,scenarios:v(d(h.scenarios)?.scenario).map(k=>({name:c(k,"name")??"",cells:v(k.inputCells).map(T=>({at:c(T,"r")??"",value:c(T,"val")??""}))})),...B?{filter:B}:{},charts:Z,links:W,notes:Tt(n,t,e,u,N),pictures:K,...y(I,"sheet")===!0?{protect:!0}:{},...Object.keys(U).length>0?{print:U}:{},...Ot(d(d(h.sheetPr)?.outlinePr))},lost:N}}function Ot(n){const t=y(n,"summaryBelow")===!1,e=y(n,"summaryRight")===!1;return t||e?{outline:{...t?{summary_below:!1}:{},...e?{summary_right:!1}:{}}}:{}}const Fe=64,At=20;function Nt(n,t,e,o,r,s,i,u){const a=h=>o.find(w=>h>=w.min&&h<=w.max)?.width??Fe,l=new Map(r.map(h=>[h.row,h.height])),f=h=>l.get(h)??At,g=[],b=[];for(const h of n.rels(t).filter(w=>w.type==="drawing")){const w=qe(n.xml(h.target),a,f),S=n.rels(h.target);for(const p of w.anchors){const m=S.find(M=>M.id===p.id),C=ee(p.at);if(p.width<=0||p.height<=0){s.push(`${e}: the chart at ${C}, of no size`);continue}const F=[],L=Xe(m?n.xml(m.target):void 0,F,u);if(typeof L=="string"){s.push(`${e}: the chart at ${C}, as ${L}`);continue}for(const M of F)s.push(`${e}: the chart at ${C} without its ${M}`);g.push({...L,at:C,...p.x===void 0?{}:{x:p.x},...p.y===void 0?{}:{y:p.y},...p.width===pe.width?{}:{width:p.width},...p.height===pe.height?{}:{height:p.height}})}for(const p of w.pictures){const m=S.find(L=>L.id===p.id),C=m&&!m.external?n.bytes(m.target):void 0;if(!m||!C){s.push(`${e}: the picture at ${ee(p.at)}, whose image is not in the file`);continue}i.add(m.target);const F=m.target.slice(m.target.lastIndexOf(".")+1).toLowerCase();b.push({row:p.at.row,col:p.at.col,...p.x===void 0?{}:{x:p.x},...p.y===void 0?{}:{y:p.y},width:p.width,height:p.height,...p.name===void 0?{}:{name:p.name},...p.descr===void 0?{}:{descr:p.descr},bytes:C,type:F})}w.others>0&&s.push(`${e}: ${X(w.others,"shape")} of its drawing`)}return{charts:g,pictures:b}}function It(n,t,e){for(const o of n){if(o.sheet===void 0)continue;const r=t[o.sheet];if(!r)continue;const s=o.text.split(",").map(i=>i.slice(i.lastIndexOf("!")+1).replaceAll("$",""));if(o.name==="_xlnm.Print_Area"){const[i]=s;s.length>1&&e.push(`${r.name}: its print area's ranges after the first`),i!==void 0&&q(i)&&(r.print={...r.print,area:i})}else if(o.name==="_xlnm.Print_Titles")for(const i of s)/^\d+:\d+$/u.test(i)?r.print={...r.print,title_rows:i}:/^[A-Za-z]+:[A-Za-z]+$/u.test(i)&&(r.print={...r.print,title_cols:i})}}export function readXlsx(n,t){let e;try{e=new et(n,t)}catch(x){throw x instanceof Le?x:new Error("It is not a zip file, as an .xlsx file is.")}const o=e.rels(""),r=o.find(x=>x.type==="officeDocument")?.target??"xl/workbook.xml";if(r.endsWith(".bin"))throw new Error("It is a binary workbook (.xlsb): save it as .xlsx.");const s=e.xml(r),i=d(s?.workbook);if(!i)throw new Error("It has no workbook part.");const u=e.rels(r),a=x=>u.find(I=>I.type===x)?.target,l=(()=>{const x=a("theme");return x===void 0?void 0:e.text(x)})(),f=l===void 0?Ue:We(l),g=a("styles"),b=g===void 0?void 0:e.xml(g),h=at(b,f),w=be(f,d(b?.styleSheet)),S=nt(e,a("sharedStrings"),w),p=[];for(const x of h.lost)p.push(x);const m=d(i.workbookPr),C=Je(d(i.calcPr));c(d(i.calcPr),"calcMode")==="manual"&&p.push("manual calculation: it computes as its cells change");const F=d(i.workbookProtection);(y(F,"lockStructure")===!0||y(F,"lockWindows")===!0)&&p.push("the workbook's protection"),i.fileSharing!==void 0&&p.push("its write protection");const L=new Map,M=a("person");if(M!==void 0)for(const x of v(d(e.xml(M)?.personList)?.person))L.set(c(x,"id")??"",E(c(x,"displayName")??""));const _=v(d(i.definedNames)?.definedName).map(x=>{const I=$(x,"localSheetId");return{name:c(x,"name")??"",text:E(O(x)),...I===void 0?{}:{sheet:I},...y(x,"hidden")===!0?{hidden:!0}:{}}}),N=[],j=new Set,z=new Map(u.map(x=>[x.id,x])),D=v(d(i.sheets)?.sheet),H=new Set(D.filter(x=>z.get(c(x,"id")??"")?.type==="worksheet").map(x=>E(c(x,"name")??"").toLowerCase()));for(const[x,I]of D.entries()){const U=z.get(c(I,"id")??""),k=E(c(I,"name")??"");if(U?.type!=="worksheet"){U?.type!=="chartsheet"&&U?.type!=="dialogsheet"&&p.push(`${k}: a sheet of a kind this cannot read`);continue}const T=new Map;for(const A of _)(A.sheet===void 0||A.sheet===x)&&(A.sheet!==void 0||!T.has(A.name.toLowerCase()))&&T.set(A.name.toLowerCase(),Ge(A.text));const R=c(I,"state"),V=Et(e,U.target,k,R==="hidden"||R==="veryHidden"?R:"visible",S,w,h.dxfs,L,A=>T.get(A.toLowerCase())===!0,j,A=>H.has(A.toLowerCase()));N[x]=V.sheet,p.push(...V.lost)}It(_,N,p);const B=o.find(x=>x.type==="core-properties")?.target,Z=B===void 0?void 0:O(d(e.xml(B)?.coreProperties)?.title).trim(),K=N.filter(x=>x!==void 0),W=new Map;return N.forEach((x,I)=>{x!==void 0&&W.set(I,K.indexOf(x))}),{sheets:K,names:_.flatMap(x=>{if(x.sheet===void 0)return[x];const I=W.get(x.sheet);return I===void 0?[]:[{...x,sheet:I}]}),looks:h.looks,dxfs:h.dxfs,date1904:y(m,"date1904")===!0,font:h.font,...Z===void 0||Z===""?{}:{title:Z},...C===void 0?{}:{iteration:C},lost:[...kt(e,j),...p]}}
@@ -0,0 +1,56 @@
1
+ import type { SheetRun } from "@allyhub/formats";
2
+ import { type Palette } from "./colors.js";
3
+ import type { XmlAttrs } from "./sax.js";
4
+ /** A run as the file says it: its text, and its font's elements by name. */
5
+ export interface RawRun {
6
+ text: string;
7
+ props: Record<string, XmlAttrs> | undefined;
8
+ }
9
+ /** A run's whole font, as the file gives it. */
10
+ export interface RunFont {
11
+ bold: boolean;
12
+ italic: boolean;
13
+ strike: boolean;
14
+ underline: NonNullable<SheetRun["underline"]>;
15
+ size: number | undefined;
16
+ color: string | undefined;
17
+ name: string | undefined;
18
+ script: SheetRun["script"];
19
+ }
20
+ /** A run read: its text, and its font when it has one. */
21
+ export interface ReadRun {
22
+ text: string;
23
+ font?: RunFont;
24
+ }
25
+ /** The runs of an `<si>` or an `<is>` as its elements stream in. */
26
+ export declare class RunsCollector {
27
+ readonly runs: RawRun[];
28
+ private inProps;
29
+ /** Whether the element was a run's: `<r>`, `<rPr>` or what is in it. */
30
+ open(name: string, attrs: XmlAttrs): boolean;
31
+ close(name: string): void;
32
+ /** A `<t>`'s text, the run's it is in. */
33
+ text(text: string): void;
34
+ }
35
+ /** The runs of a string read: their text, and each one's font. */
36
+ export declare function readRuns(raw: readonly RawRun[], p: Palette): ReadRun[];
37
+ /** What a cell's own font is, as a run's is set against it. */
38
+ export interface CellFont {
39
+ bold?: boolean | undefined;
40
+ italic?: boolean | undefined;
41
+ strike?: boolean | undefined;
42
+ underline?: SheetRun["underline"];
43
+ size?: number | undefined;
44
+ color?: string | undefined;
45
+ font?: string | undefined;
46
+ }
47
+ /**
48
+ * sheet.yaml's runs of a string: each says what its font has that the
49
+ * cell's does not. `base` is the workbook's body font, what a cell is in
50
+ * unless its look says.
51
+ */
52
+ export declare function runsOver(runs: readonly ReadRun[], cell: CellFont, base: {
53
+ name?: string | undefined;
54
+ size?: number | undefined;
55
+ }): SheetRun[];
56
+ //# sourceMappingURL=runs.d.ts.map
@@ -0,0 +1,2 @@
1
+ /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
+ import{colorOf as g}from"./colors.js";import{readXstring as z}from"./xml.js";export class RunsCollector{runs=[];inProps=!1;open(i,r){if(i==="r")return this.runs.push({text:"",props:void 0}),!0;const e=this.runs[this.runs.length-1];return i==="rPr"&&e?(e.props={},this.inProps=!0,!0):this.inProps&&e?.props?(e.props[i]=r,!0):!1}close(i){i==="rPr"&&(this.inProps=!1)}text(i){const r=this.runs[this.runs.length-1];r&&(r.text+=i)}}const a=(u,i)=>{const r=u[i];if(r===void 0)return!1;const e=r.val;return e===void 0||e!=="0"&&e!=="false"},b=new Set(["double","singleAccounting","doubleAccounting"]);export function readRuns(u,i){return u.map(({text:r,props:e})=>{const n={text:z(r)};if(!e)return n;const t=e.u,s=t?.val,o=Number(e.sz?.val),l=e.vertAlign?.val;return n.font={bold:a(e,"b"),italic:a(e,"i"),strike:a(e,"strike"),underline:t===void 0||s==="none"?!1:s!==void 0&&b.has(s)?s:!0,size:Number.isFinite(o)&&o>0?o:void 0,color:g(e.color,i),name:e.rFont?.val,script:l==="superscript"||l==="subscript"?l:void 0},n})}export function runsOver(u,i,r){return u.map(({text:e,font:n})=>{const t={text:e};if(!n)return t;const s=(h,m)=>m===(i[h]===!0)?void 0:m,o=s("bold",n.bold);o!==void 0&&(t.bold=o);const l=s("italic",n.italic);l!==void 0&&(t.italic=l);const c=i.underline??!1;n.underline===c||n.underline===!0&&c==="single"||n.underline==="single"&&c===!0||(t.underline=n.underline);const p=s("strike",n.strike);p!==void 0&&(t.strike=p);const d=n.name??r.name;d!==void 0&&d!==(i.font??r.name)&&(t.font=d);const f=n.size??r.size;return f!==void 0&&f!==(i.size??r.size)&&(t.size=f),n.color!==void 0&&n.color.toUpperCase()!==(i.color??"#000000").toUpperCase()&&(t.color=n.color),n.script!==void 0&&(t.script=n.script),t})}
@@ -1,3 +1,4 @@
1
+ import type { SheetRun } from "@allyhub/formats";
1
2
  import type { CellLook } from "../workbook.js";
2
3
  /** The body font of a workbook, whatever its cells say. */
3
4
  export declare const DEFAULT_FONT: {
@@ -10,6 +11,11 @@ export declare const DEFAULT_FONT: {
10
11
  * New Roman") is its first face.
11
12
  */
12
13
  export declare function fontName(name: string): string;
14
+ /**
15
+ * A rich string's run as `<r>`: its font whole, the cell's with the run's
16
+ * over it (`<rPr>`, whose font is `rFont`), or none when it says nothing.
17
+ */
18
+ export declare function runXml(run: SheetRun, cell: CellLook): string;
13
19
  export declare class Styles {
14
20
  private readonly fonts;
15
21
  private readonly fills;
@@ -1,2 +1,2 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{FIRST_CUSTOM as g,builtinId as x}from"./numfmt.js";import{NS as y,el as e}from"./xml.js";export const DEFAULT_FONT={name:"Calibri",size:11};export function fontName(t){if(t.length<=31)return t;const n=t.split(/[;,]/u)[0]?.trim()??"";return(n===""?t:n).slice(0,31)}const s=t=>`FF${t.slice(1).toUpperCase()}`;class f{items=[];index=new Map;add(n){const i=this.index.get(n);if(i!==void 0)return i;const r=this.items.length;return this.items.push(n),this.index.set(n,r),r}}function b(t){const{underline:n}=t;return e("font",{},t.bold===!0?"<b/>":"",t.italic===!0?"<i/>":"",t.strike===!0?"<strike/>":"",n===!0||n==="single"?"<u/>":n?e("u",{val:n}):"",e("sz",{val:t.size??DEFAULT_FONT.size}),t.color===void 0?e("color",{theme:1}):e("color",{rgb:s(t.color)}),e("name",{val:fontName(t.font??DEFAULT_FONT.name)}),e("family",{val:2}),t.font===void 0?e("scheme",{val:"minor"}):"")}function F(t){const{pattern:n,color:i,background:r}=typeof t=="string"?{pattern:"solid",color:t,background:void 0}:t;return e("fill",{},e("patternFill",{patternType:n},i===void 0?"":e("fgColor",{rgb:s(i)}),r===void 0?n==="solid"?e("bgColor",{indexed:64}):"":e("bgColor",{rgb:s(r)})))}function o(t,n){return n?e(t,{style:n.style},n.color===void 0?e("color",{auto:1}):e("color",{rgb:s(n.color)})):e(t)}function h(t){return e("border",{},o("left",t.left),o("right",t.right),o("top",t.top),o("bottom",t.bottom),e("diagonal"))}function p(t,n="dxf"){const{underline:i}=t,r=[t.bold===void 0?"":e("b",{val:t.bold}),t.italic===void 0?"":e("i",{val:t.italic}),t.strike===void 0?"":e("strike",{val:t.strike}),i===!0?"<u/>":"",t.color===void 0?"":e("color",{rgb:s(t.color)})].join(""),{fill:d,border:l}=t;return e(n,{},r===""?"":e("font",{},r),typeof d=="string"?e("fill",{},e("patternFill",{},e("bgColor",{rgb:s(d)}))):"",l?h(l):"")}const I=t=>t<0?90-t:t;function v(t){const n={horizontal:t.align,vertical:t.valign,textRotation:t.rotation===void 0?void 0:I(t.rotation),wrapText:t.wrap===!0?!0:void 0,indent:t.indent,shrinkToFit:t.shrink===!0?!0:void 0};return Object.values(n).every(i=>i===void 0)?"":e("alignment",n)}export class Styles{fonts=new f;fills=new f;borders=new f;formats=new Map;xfs=new f;byLook=new Map;dxfs=new f;constructor(){this.fonts.add(b({})),this.fills.add(e("fill",{},e("patternFill",{patternType:"none"}))),this.fills.add(e("fill",{},e("patternFill",{patternType:"gray125"}))),this.borders.add(e("border",{},e("left"),e("right"),e("top"),e("bottom"),e("diagonal"))),this.xfs.add(e("xf",{numFmtId:0,fontId:0,fillId:0,borderId:0,xfId:0}))}format(n){if(n===void 0)return 0;const i=x(n);if(i!==void 0)return i;let r=this.formats.get(n);return r===void 0&&(r=g+this.formats.size,this.formats.set(n,r)),r}xf(n){const i=JSON.stringify(n),r=this.byLook.get(i);if(r!==void 0)return r;const d=this.format(n.format),l=this.fonts.add(b(n)),u=n.fill===void 0?0:this.fills.add(F(n.fill)),a=n.border===void 0?0:this.borders.add(h(n.border)),c=v(n),m=this.xfs.add(e("xf",{numFmtId:d,fontId:l,fillId:u,borderId:a,xfId:0,applyNumberFormat:d===0?void 0:!0,applyFont:l===0?void 0:!0,applyFill:u===0?void 0:!0,applyBorder:a===0?void 0:!0,applyAlignment:c===""?void 0:!0},c));return this.byLook.set(i,m),m}dxf(n){return this.dxfs.add(p(n))}dxfXml(n,i){return p(n,i)}xml(){const n=(r,d)=>e(r,{count:d.length},d.join("")),i=[...this.formats].map(([r,d])=>e("numFmt",{numFmtId:d,formatCode:r}));return e("styleSheet",{xmlns:y.main},i.length>0?n("numFmts",i):"",n("fonts",this.fonts.items),n("fills",this.fills.items),n("borders",this.borders.items),n("cellStyleXfs",[e("xf",{numFmtId:0,fontId:0,fillId:0,borderId:0})]),n("cellXfs",this.xfs.items),n("cellStyles",[e("cellStyle",{name:"Normal",xfId:0,builtinId:0})]),this.dxfs.items.length===0?e("dxfs",{count:0}):n("dxfs",this.dxfs.items),e("tableStyles",{count:0,defaultTableStyle:"TableStyleMedium2",defaultPivotStyle:"PivotStyleLight16"}))}}
2
+ import{RUN_FIELDS as x,runLook as y}from"../rich.js";import{FIRST_CUSTOM as v,builtinId as F}from"./numfmt.js";import{NS as I,el as e,xstring as S}from"./xml.js";export const DEFAULT_FONT={name:"Calibri",size:11};export function fontName(t){if(t.length<=31)return t;const n=t.split(/[;,]/u)[0]?.trim()??"";return(n===""?t:n).slice(0,31)}const f=t=>`FF${t.slice(1).toUpperCase()}`;class o{items=[];index=new Map;add(n){const r=this.index.get(n);if(r!==void 0)return r;const i=this.items.length;return this.items.push(n),this.index.set(n,i),i}}function h(t){const{underline:n}=t;return e("font",{},t.bold===!0?"<b/>":"",t.italic===!0?"<i/>":"",t.strike===!0?"<strike/>":"",n===!0||n==="single"?"<u/>":n?e("u",{val:n}):"",e("sz",{val:t.size??DEFAULT_FONT.size}),t.color===void 0?e("color",{theme:1}):e("color",{rgb:f(t.color)}),e("name",{val:fontName(t.font??DEFAULT_FONT.name)}),e("family",{val:2}),t.font===void 0?e("scheme",{val:"minor"}):"")}export function runXml(t,n){const r=`<t${/^\s|\s$|\n/u.test(t.text)?' xml:space="preserve"':""}>${S(t.text)}</t>`;if(x.every(s=>t[s]===void 0))return e("r",{},r);const i={...n,...y(t)},{underline:d}=i;return e("r",{},e("rPr",{},i.bold===!0?"<b/>":"",i.italic===!0?"<i/>":"",i.strike===!0?"<strike/>":"",d===!0||d==="single"?"<u/>":d?e("u",{val:d}):"",t.script===void 0?"":e("vertAlign",{val:t.script}),e("sz",{val:i.size??DEFAULT_FONT.size}),i.color===void 0?e("color",{theme:1}):e("color",{rgb:f(i.color)}),e("rFont",{val:fontName(i.font??DEFAULT_FONT.name)}),e("family",{val:2}),i.font===void 0?e("scheme",{val:"minor"}):""),r)}function w(t){const{pattern:n,color:r,background:i}=typeof t=="string"?{pattern:"solid",color:t,background:void 0}:t;return e("fill",{},e("patternFill",{patternType:n},r===void 0?"":e("fgColor",{rgb:f(r)}),i===void 0?n==="solid"?e("bgColor",{indexed:64}):"":e("bgColor",{rgb:f(i)})))}function u(t,n){return n?e(t,{style:n.style},n.color===void 0?e("color",{auto:1}):e("color",{rgb:f(n.color)})):e(t)}function b(t){return e("border",{},u("left",t.left),u("right",t.right),u("top",t.top),u("bottom",t.bottom),e("diagonal"))}function g(t,n="dxf",r){const{underline:i}=t,d=[t.bold===void 0?"":e("b",{val:t.bold}),t.italic===void 0?"":e("i",{val:t.italic}),t.strike===void 0?"":e("strike",{val:t.strike}),i===!0?"<u/>":"",t.color===void 0?"":e("color",{rgb:f(t.color)})].join(""),{fill:s,border:l}=t;return e(n,{},d===""?"":e("font",{},d),t.format===void 0||r===void 0?"":e("numFmt",{numFmtId:r,formatCode:t.format}),typeof s=="string"?e("fill",{},e("patternFill",{},e("bgColor",{rgb:f(s)}))):"",l?b(l):"")}const T=t=>t<0?90-t:t;function X(t){const n={horizontal:t.align,vertical:t.valign,textRotation:t.rotation===void 0?void 0:T(t.rotation),wrapText:t.wrap===!0?!0:void 0,indent:t.indent,shrinkToFit:t.shrink===!0?!0:void 0};return Object.values(n).every(r=>r===void 0)?"":e("alignment",n)}function z(t){const n={locked:t.locked===!1?!1:void 0,hidden:t.hide_formula===!0?!0:void 0};return n.locked===void 0&&n.hidden===void 0?"":e("protection",n)}export class Styles{fonts=new o;fills=new o;borders=new o;formats=new Map;xfs=new o;byLook=new Map;dxfs=new o;constructor(){this.fonts.add(h({})),this.fills.add(e("fill",{},e("patternFill",{patternType:"none"}))),this.fills.add(e("fill",{},e("patternFill",{patternType:"gray125"}))),this.borders.add(e("border",{},e("left"),e("right"),e("top"),e("bottom"),e("diagonal"))),this.xfs.add(e("xf",{numFmtId:0,fontId:0,fillId:0,borderId:0,xfId:0}))}format(n){if(n===void 0)return 0;const r=F(n);if(r!==void 0)return r;let i=this.formats.get(n);return i===void 0&&(i=v+this.formats.size,this.formats.set(n,i)),i}xf(n){const r=JSON.stringify(n),i=this.byLook.get(r);if(i!==void 0)return i;const d=this.format(n.format),s=this.fonts.add(h(n)),l=n.fill===void 0?0:this.fills.add(w(n.fill)),a=n.border===void 0?0:this.borders.add(b(n.border)),c=X(n),m=z(n),p=this.xfs.add(e("xf",{numFmtId:d,fontId:s,fillId:l,borderId:a,xfId:0,applyNumberFormat:d===0?void 0:!0,applyFont:s===0?void 0:!0,applyFill:l===0?void 0:!0,applyBorder:a===0?void 0:!0,applyAlignment:c===""?void 0:!0,applyProtection:m===""?void 0:!0},c,m));return this.byLook.set(r,p),p}dxf(n){return this.dxfs.add(g(n,"dxf",this.format(n.format)))}dxfXml(n,r){return g(n,r,this.format(n.format))}xml(){const n=(i,d)=>e(i,{count:d.length},d.join("")),r=[...this.formats].map(([i,d])=>e("numFmt",{numFmtId:d,formatCode:i}));return e("styleSheet",{xmlns:I.main},r.length>0?n("numFmts",r):"",n("fonts",this.fonts.items),n("fills",this.fills.items),n("borders",this.borders.items),n("cellStyleXfs",[e("xf",{numFmtId:0,fontId:0,fillId:0,borderId:0})]),n("cellXfs",this.xfs.items),n("cellStyles",[e("cellStyle",{name:"Normal",xfId:0,builtinId:0})]),this.dxfs.items.length===0?e("dxfs",{count:0}):n("dxfs",this.dxfs.items),e("tableStyles",{count:0,defaultTableStyle:"TableStyleMedium2",defaultPivotStyle:"PivotStyleLight16"}))}}