@rowsncolumns/toolkit 24.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (456) hide show
  1. package/LICENSE.md +100 -0
  2. package/Readme.md +27 -0
  3. package/dist/cjs/autofilter-condition.d.ts +43 -0
  4. package/dist/cjs/autofilter-condition.d.ts.map +1 -0
  5. package/dist/cjs/autofilter-condition.js +155 -0
  6. package/dist/cjs/csv-export.d.ts +49 -0
  7. package/dist/cjs/csv-export.d.ts.map +1 -0
  8. package/dist/cjs/csv-export.js +142 -0
  9. package/dist/cjs/csv-import-worker.d.ts +16 -0
  10. package/dist/cjs/csv-import-worker.d.ts.map +1 -0
  11. package/dist/cjs/csv-import-worker.js +60 -0
  12. package/dist/cjs/csv-import.d.ts +38 -0
  13. package/dist/cjs/csv-import.d.ts.map +1 -0
  14. package/dist/cjs/csv-import.js +166 -0
  15. package/dist/cjs/csv-parser/helpers.d.ts +14 -0
  16. package/dist/cjs/csv-parser/helpers.d.ts.map +1 -0
  17. package/dist/cjs/csv-parser/helpers.js +145 -0
  18. package/dist/cjs/csv-parser/types.d.ts +66 -0
  19. package/dist/cjs/csv-parser/types.d.ts.map +1 -0
  20. package/dist/cjs/csv-parser/types.js +14 -0
  21. package/dist/cjs/csv-parser/worker.d.ts +2 -0
  22. package/dist/cjs/csv-parser/worker.d.ts.map +1 -0
  23. package/dist/cjs/csv-parser/worker.js +200 -0
  24. package/dist/cjs/excel-export.d.ts +11 -0
  25. package/dist/cjs/excel-export.d.ts.map +1 -0
  26. package/dist/cjs/excel-export.js +22 -0
  27. package/dist/cjs/excel-import-session.d.ts +51 -0
  28. package/dist/cjs/excel-import-session.d.ts.map +1 -0
  29. package/dist/cjs/excel-import-session.js +307 -0
  30. package/dist/cjs/excel-import-worker.d.ts +7 -0
  31. package/dist/cjs/excel-import-worker.d.ts.map +1 -0
  32. package/dist/cjs/excel-import-worker.js +119 -0
  33. package/dist/cjs/excel-parser/builtin-numfmts.d.ts +24 -0
  34. package/dist/cjs/excel-parser/builtin-numfmts.d.ts.map +1 -0
  35. package/dist/cjs/excel-parser/builtin-numfmts.js +63 -0
  36. package/dist/cjs/excel-parser/cfb-decryptor.d.ts +53 -0
  37. package/dist/cjs/excel-parser/cfb-decryptor.d.ts.map +1 -0
  38. package/dist/cjs/excel-parser/cfb-decryptor.js +553 -0
  39. package/dist/cjs/excel-parser/cfb-encryptor.d.ts +23 -0
  40. package/dist/cjs/excel-parser/cfb-encryptor.d.ts.map +1 -0
  41. package/dist/cjs/excel-parser/cfb-encryptor.js +200 -0
  42. package/dist/cjs/excel-parser/dv-cell-stamp.d.ts +29 -0
  43. package/dist/cjs/excel-parser/dv-cell-stamp.d.ts.map +1 -0
  44. package/dist/cjs/excel-parser/dv-cell-stamp.js +239 -0
  45. package/dist/cjs/excel-parser/helpers.d.ts +28 -0
  46. package/dist/cjs/excel-parser/helpers.d.ts.map +1 -0
  47. package/dist/cjs/excel-parser/helpers.js +188 -0
  48. package/dist/cjs/excel-parser/interface.d.ts +179 -0
  49. package/dist/cjs/excel-parser/interface.d.ts.map +1 -0
  50. package/dist/cjs/excel-parser/interface.js +1 -0
  51. package/dist/cjs/excel-parser/plugins/base/index.d.ts +31 -0
  52. package/dist/cjs/excel-parser/plugins/base/index.d.ts.map +1 -0
  53. package/dist/cjs/excel-parser/plugins/base/index.js +101 -0
  54. package/dist/cjs/excel-parser/plugins/ods/conditional-formatting.d.ts +16 -0
  55. package/dist/cjs/excel-parser/plugins/ods/conditional-formatting.d.ts.map +1 -0
  56. package/dist/cjs/excel-parser/plugins/ods/conditional-formatting.js +488 -0
  57. package/dist/cjs/excel-parser/plugins/ods/data-validations.d.ts +15 -0
  58. package/dist/cjs/excel-parser/plugins/ods/data-validations.d.ts.map +1 -0
  59. package/dist/cjs/excel-parser/plugins/ods/data-validations.js +353 -0
  60. package/dist/cjs/excel-parser/plugins/ods/formula.d.ts +8 -0
  61. package/dist/cjs/excel-parser/plugins/ods/formula.d.ts.map +1 -0
  62. package/dist/cjs/excel-parser/plugins/ods/formula.js +82 -0
  63. package/dist/cjs/excel-parser/plugins/ods/index.d.ts +122 -0
  64. package/dist/cjs/excel-parser/plugins/ods/index.d.ts.map +1 -0
  65. package/dist/cjs/excel-parser/plugins/ods/index.js +3642 -0
  66. package/dist/cjs/excel-parser/plugins/ods/sparklines.d.ts +25 -0
  67. package/dist/cjs/excel-parser/plugins/ods/sparklines.d.ts.map +1 -0
  68. package/dist/cjs/excel-parser/plugins/ods/sparklines.js +221 -0
  69. package/dist/cjs/excel-parser/plugins/ods/styles.d.ts +60 -0
  70. package/dist/cjs/excel-parser/plugins/ods/styles.d.ts.map +1 -0
  71. package/dist/cjs/excel-parser/plugins/ods/styles.js +808 -0
  72. package/dist/cjs/excel-parser/plugins/ods/types.d.ts +7 -0
  73. package/dist/cjs/excel-parser/plugins/ods/types.d.ts.map +1 -0
  74. package/dist/cjs/excel-parser/plugins/ods/types.js +1 -0
  75. package/dist/cjs/excel-parser/plugins/xls/index.d.ts +5 -0
  76. package/dist/cjs/excel-parser/plugins/xls/index.d.ts.map +1 -0
  77. package/dist/cjs/excel-parser/plugins/xls/index.js +19 -0
  78. package/dist/cjs/excel-parser/plugins/xlsb/biff-record-reader.d.ts +13 -0
  79. package/dist/cjs/excel-parser/plugins/xlsb/biff-record-reader.d.ts.map +1 -0
  80. package/dist/cjs/excel-parser/plugins/xlsb/biff-record-reader.js +49 -0
  81. package/dist/cjs/excel-parser/plugins/xlsb/index.d.ts +117 -0
  82. package/dist/cjs/excel-parser/plugins/xlsb/index.d.ts.map +1 -0
  83. package/dist/cjs/excel-parser/plugins/xlsb/index.js +2972 -0
  84. package/dist/cjs/excel-parser/plugins/xlsb/rgce-parser.d.ts +18 -0
  85. package/dist/cjs/excel-parser/plugins/xlsb/rgce-parser.d.ts.map +1 -0
  86. package/dist/cjs/excel-parser/plugins/xlsb/rgce-parser.js +527 -0
  87. package/dist/cjs/excel-parser/plugins/xlsm/index.d.ts +5 -0
  88. package/dist/cjs/excel-parser/plugins/xlsm/index.d.ts.map +1 -0
  89. package/dist/cjs/excel-parser/plugins/xlsm/index.js +10 -0
  90. package/dist/cjs/excel-parser/plugins/xlsx/charts.d.ts +60 -0
  91. package/dist/cjs/excel-parser/plugins/xlsx/charts.d.ts.map +1 -0
  92. package/dist/cjs/excel-parser/plugins/xlsx/charts.js +2178 -0
  93. package/dist/cjs/excel-parser/plugins/xlsx/conditional-formatting.d.ts +18 -0
  94. package/dist/cjs/excel-parser/plugins/xlsx/conditional-formatting.d.ts.map +1 -0
  95. package/dist/cjs/excel-parser/plugins/xlsx/conditional-formatting.js +620 -0
  96. package/dist/cjs/excel-parser/plugins/xlsx/data-validations.d.ts +4 -0
  97. package/dist/cjs/excel-parser/plugins/xlsx/data-validations.d.ts.map +1 -0
  98. package/dist/cjs/excel-parser/plugins/xlsx/data-validations.js +515 -0
  99. package/dist/cjs/excel-parser/plugins/xlsx/drawing.d.ts +39 -0
  100. package/dist/cjs/excel-parser/plugins/xlsx/drawing.d.ts.map +1 -0
  101. package/dist/cjs/excel-parser/plugins/xlsx/drawing.js +941 -0
  102. package/dist/cjs/excel-parser/plugins/xlsx/index.d.ts +320 -0
  103. package/dist/cjs/excel-parser/plugins/xlsx/index.d.ts.map +1 -0
  104. package/dist/cjs/excel-parser/plugins/xlsx/index.js +6056 -0
  105. package/dist/cjs/excel-parser/plugins/xlsx/numfmt.d.ts +2 -0
  106. package/dist/cjs/excel-parser/plugins/xlsx/numfmt.d.ts.map +1 -0
  107. package/dist/cjs/excel-parser/plugins/xlsx/numfmt.js +3 -0
  108. package/dist/cjs/excel-parser/plugins/xlsx/pivots.d.ts +40 -0
  109. package/dist/cjs/excel-parser/plugins/xlsx/pivots.d.ts.map +1 -0
  110. package/dist/cjs/excel-parser/plugins/xlsx/pivots.js +342 -0
  111. package/dist/cjs/excel-parser/plugins/xlsx/relationships.d.ts +8 -0
  112. package/dist/cjs/excel-parser/plugins/xlsx/relationships.d.ts.map +1 -0
  113. package/dist/cjs/excel-parser/plugins/xlsx/relationships.js +26 -0
  114. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.d.ts +26 -0
  115. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.d.ts.map +1 -0
  116. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.js +59 -0
  117. package/dist/cjs/excel-parser/plugins/xlsx/styles.d.ts +44 -0
  118. package/dist/cjs/excel-parser/plugins/xlsx/styles.d.ts.map +1 -0
  119. package/dist/cjs/excel-parser/plugins/xlsx/styles.js +1377 -0
  120. package/dist/cjs/excel-parser/plugins/xlsx/theme.d.ts +50 -0
  121. package/dist/cjs/excel-parser/plugins/xlsx/theme.d.ts.map +1 -0
  122. package/dist/cjs/excel-parser/plugins/xlsx/theme.js +150 -0
  123. package/dist/cjs/excel-parser/plugins/xlsx/threaded-comments.d.ts +47 -0
  124. package/dist/cjs/excel-parser/plugins/xlsx/threaded-comments.d.ts.map +1 -0
  125. package/dist/cjs/excel-parser/plugins/xlsx/threaded-comments.js +141 -0
  126. package/dist/cjs/excel-parser/plugins/xlsx/value-type-detection.d.ts +44 -0
  127. package/dist/cjs/excel-parser/plugins/xlsx/value-type-detection.d.ts.map +1 -0
  128. package/dist/cjs/excel-parser/plugins/xlsx/value-type-detection.js +407 -0
  129. package/dist/cjs/excel-parser/registry.d.ts +5 -0
  130. package/dist/cjs/excel-parser/registry.d.ts.map +1 -0
  131. package/dist/cjs/excel-parser/registry.js +21 -0
  132. package/dist/cjs/excel-parser/style-registry.d.ts +51 -0
  133. package/dist/cjs/excel-parser/style-registry.d.ts.map +1 -0
  134. package/dist/cjs/excel-parser/style-registry.js +175 -0
  135. package/dist/cjs/excel-parser/theme-default.d.ts +3 -0
  136. package/dist/cjs/excel-parser/theme-default.d.ts.map +1 -0
  137. package/dist/cjs/excel-parser/theme-default.js +19 -0
  138. package/dist/cjs/excel-parser/types.d.ts +365 -0
  139. package/dist/cjs/excel-parser/types.d.ts.map +1 -0
  140. package/dist/cjs/excel-parser/types.js +59 -0
  141. package/dist/cjs/excel-parser/utils.d.ts +6 -0
  142. package/dist/cjs/excel-parser/utils.d.ts.map +1 -0
  143. package/dist/cjs/excel-parser/utils.js +30 -0
  144. package/dist/cjs/excel-parser/workbook.d.ts +51 -0
  145. package/dist/cjs/excel-parser/workbook.d.ts.map +1 -0
  146. package/dist/cjs/excel-parser/workbook.js +317 -0
  147. package/dist/cjs/excel-parser/worker.d.ts +2 -0
  148. package/dist/cjs/excel-parser/worker.d.ts.map +1 -0
  149. package/dist/cjs/excel-parser/worker.js +1149 -0
  150. package/dist/cjs/excel-parser/zip-parser-streaming.d.ts +13 -0
  151. package/dist/cjs/excel-parser/zip-parser-streaming.d.ts.map +1 -0
  152. package/dist/cjs/excel-parser/zip-parser-streaming.js +200 -0
  153. package/dist/cjs/excel-parser/zip-parser.d.ts +11 -0
  154. package/dist/cjs/excel-parser/zip-parser.d.ts.map +1 -0
  155. package/dist/cjs/excel-parser/zip-parser.js +49 -0
  156. package/dist/cjs/exporter/invalid-data-validation.d.ts +19 -0
  157. package/dist/cjs/exporter/invalid-data-validation.d.ts.map +1 -0
  158. package/dist/cjs/exporter/invalid-data-validation.js +39 -0
  159. package/dist/cjs/exporter/ods/ods-export.d.ts +26 -0
  160. package/dist/cjs/exporter/ods/ods-export.d.ts.map +1 -0
  161. package/dist/cjs/exporter/ods/ods-export.js +3714 -0
  162. package/dist/cjs/exporter/ods/sparkline-builder.d.ts +33 -0
  163. package/dist/cjs/exporter/ods/sparkline-builder.d.ts.map +1 -0
  164. package/dist/cjs/exporter/ods/sparkline-builder.js +221 -0
  165. package/dist/cjs/exporter/xlsx/chart-builder.d.ts +3 -0
  166. package/dist/cjs/exporter/xlsx/chart-builder.d.ts.map +1 -0
  167. package/dist/cjs/exporter/xlsx/chart-builder.js +1901 -0
  168. package/dist/cjs/exporter/xlsx/chart-templates.d.ts +1781 -0
  169. package/dist/cjs/exporter/xlsx/chart-templates.d.ts.map +1 -0
  170. package/dist/cjs/exporter/xlsx/chart-templates.js +1798 -0
  171. package/dist/cjs/exporter/xlsx/future-functions.d.ts +10 -0
  172. package/dist/cjs/exporter/xlsx/future-functions.d.ts.map +1 -0
  173. package/dist/cjs/exporter/xlsx/future-functions.js +264 -0
  174. package/dist/cjs/exporter/xlsx/pivot-builder.d.ts +58 -0
  175. package/dist/cjs/exporter/xlsx/pivot-builder.d.ts.map +1 -0
  176. package/dist/cjs/exporter/xlsx/pivot-builder.js +277 -0
  177. package/dist/cjs/exporter/xlsx/power-query-builder.d.ts +26 -0
  178. package/dist/cjs/exporter/xlsx/power-query-builder.d.ts.map +1 -0
  179. package/dist/cjs/exporter/xlsx/power-query-builder.js +306 -0
  180. package/dist/cjs/exporter/xlsx/slicer-builder.d.ts +11 -0
  181. package/dist/cjs/exporter/xlsx/slicer-builder.d.ts.map +1 -0
  182. package/dist/cjs/exporter/xlsx/slicer-builder.js +87 -0
  183. package/dist/cjs/exporter/xlsx/sparkline-builder.d.ts +61 -0
  184. package/dist/cjs/exporter/xlsx/sparkline-builder.d.ts.map +1 -0
  185. package/dist/cjs/exporter/xlsx/sparkline-builder.js +489 -0
  186. package/dist/cjs/exporter/xlsx/style-builder.d.ts +93 -0
  187. package/dist/cjs/exporter/xlsx/style-builder.d.ts.map +1 -0
  188. package/dist/cjs/exporter/xlsx/style-builder.js +813 -0
  189. package/dist/cjs/exporter/xlsx/threaded-comments-builder.d.ts +58 -0
  190. package/dist/cjs/exporter/xlsx/threaded-comments-builder.d.ts.map +1 -0
  191. package/dist/cjs/exporter/xlsx/threaded-comments-builder.js +189 -0
  192. package/dist/cjs/exporter/xlsx/xlsx-export.d.ts +121 -0
  193. package/dist/cjs/exporter/xlsx/xlsx-export.d.ts.map +1 -0
  194. package/dist/cjs/exporter/xlsx/xlsx-export.js +4596 -0
  195. package/dist/cjs/helpers/theme-xml-generator.d.ts +8 -0
  196. package/dist/cjs/helpers/theme-xml-generator.d.ts.map +1 -0
  197. package/dist/cjs/helpers/theme-xml-generator.js +33 -0
  198. package/dist/cjs/helpers.d.ts +34 -0
  199. package/dist/cjs/helpers.d.ts.map +1 -0
  200. package/dist/cjs/helpers.js +189 -0
  201. package/dist/cjs/index.d.ts +16 -0
  202. package/dist/cjs/index.d.ts.map +1 -0
  203. package/dist/cjs/index.js +15 -0
  204. package/dist/cjs/indexed-colors.d.ts +2 -0
  205. package/dist/cjs/indexed-colors.d.ts.map +1 -0
  206. package/dist/cjs/indexed-colors.js +75 -0
  207. package/dist/cjs/ods-export.d.ts +24 -0
  208. package/dist/cjs/ods-export.d.ts.map +1 -0
  209. package/dist/cjs/ods-export.js +23 -0
  210. package/dist/cjs/parse.d.ts +24 -0
  211. package/dist/cjs/parse.d.ts.map +1 -0
  212. package/dist/cjs/parse.js +68 -0
  213. package/dist/cjs/power-query.d.ts +41 -0
  214. package/dist/cjs/power-query.d.ts.map +1 -0
  215. package/dist/cjs/power-query.js +22 -0
  216. package/dist/cjs/server.d.ts +9 -0
  217. package/dist/cjs/server.d.ts.map +1 -0
  218. package/dist/cjs/server.js +8 -0
  219. package/dist/cjs/theme1.d.ts +3 -0
  220. package/dist/cjs/theme1.d.ts.map +1 -0
  221. package/dist/cjs/theme1.js +2 -0
  222. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -0
  223. package/dist/cjs/types.d.ts +14 -0
  224. package/dist/cjs/types.d.ts.map +1 -0
  225. package/dist/cjs/types.js +14 -0
  226. package/dist/cjs/vitest.config.d.ts +3 -0
  227. package/dist/cjs/vitest.config.d.ts.map +1 -0
  228. package/dist/cjs/vitest.config.js +16 -0
  229. package/dist/esm/autofilter-condition.d.ts +43 -0
  230. package/dist/esm/autofilter-condition.d.ts.map +1 -0
  231. package/dist/esm/autofilter-condition.js +145 -0
  232. package/dist/esm/csv-export.d.ts +49 -0
  233. package/dist/esm/csv-export.d.ts.map +1 -0
  234. package/dist/esm/csv-export.js +126 -0
  235. package/dist/esm/csv-import-worker.d.ts +16 -0
  236. package/dist/esm/csv-import-worker.d.ts.map +1 -0
  237. package/dist/esm/csv-import-worker.js +60 -0
  238. package/dist/esm/csv-import.d.ts +38 -0
  239. package/dist/esm/csv-import.d.ts.map +1 -0
  240. package/dist/esm/csv-import.js +132 -0
  241. package/dist/esm/csv-parser/helpers.d.ts +14 -0
  242. package/dist/esm/csv-parser/helpers.d.ts.map +1 -0
  243. package/dist/esm/csv-parser/helpers.js +0 -0
  244. package/dist/esm/csv-parser/types.d.ts +66 -0
  245. package/dist/esm/csv-parser/types.d.ts.map +1 -0
  246. package/dist/esm/csv-parser/types.js +14 -0
  247. package/dist/esm/csv-parser/worker.d.ts +2 -0
  248. package/dist/esm/csv-parser/worker.d.ts.map +1 -0
  249. package/dist/esm/csv-parser/worker.js +154 -0
  250. package/dist/esm/excel-export.d.ts +11 -0
  251. package/dist/esm/excel-export.d.ts.map +1 -0
  252. package/dist/esm/excel-export.js +13 -0
  253. package/dist/esm/excel-import-session.d.ts +51 -0
  254. package/dist/esm/excel-import-session.d.ts.map +1 -0
  255. package/dist/esm/excel-import-session.js +255 -0
  256. package/dist/esm/excel-import-worker.d.ts +7 -0
  257. package/dist/esm/excel-import-worker.d.ts.map +1 -0
  258. package/dist/esm/excel-import-worker.js +116 -0
  259. package/dist/esm/excel-parser/builtin-numfmts.d.ts +24 -0
  260. package/dist/esm/excel-parser/builtin-numfmts.d.ts.map +1 -0
  261. package/dist/esm/excel-parser/builtin-numfmts.js +59 -0
  262. package/dist/esm/excel-parser/cfb-decryptor.d.ts +53 -0
  263. package/dist/esm/excel-parser/cfb-decryptor.d.ts.map +1 -0
  264. package/dist/esm/excel-parser/cfb-decryptor.js +493 -0
  265. package/dist/esm/excel-parser/cfb-encryptor.d.ts +23 -0
  266. package/dist/esm/excel-parser/cfb-encryptor.d.ts.map +1 -0
  267. package/dist/esm/excel-parser/cfb-encryptor.js +181 -0
  268. package/dist/esm/excel-parser/dv-cell-stamp.d.ts +29 -0
  269. package/dist/esm/excel-parser/dv-cell-stamp.d.ts.map +1 -0
  270. package/dist/esm/excel-parser/dv-cell-stamp.js +155 -0
  271. package/dist/esm/excel-parser/helpers.d.ts +28 -0
  272. package/dist/esm/excel-parser/helpers.d.ts.map +1 -0
  273. package/dist/esm/excel-parser/helpers.js +160 -0
  274. package/dist/esm/excel-parser/interface.d.ts +179 -0
  275. package/dist/esm/excel-parser/interface.d.ts.map +1 -0
  276. package/dist/esm/excel-parser/interface.js +1 -0
  277. package/dist/esm/excel-parser/plugins/base/index.d.ts +31 -0
  278. package/dist/esm/excel-parser/plugins/base/index.d.ts.map +1 -0
  279. package/dist/esm/excel-parser/plugins/base/index.js +64 -0
  280. package/dist/esm/excel-parser/plugins/ods/conditional-formatting.d.ts +16 -0
  281. package/dist/esm/excel-parser/plugins/ods/conditional-formatting.d.ts.map +1 -0
  282. package/dist/esm/excel-parser/plugins/ods/conditional-formatting.js +405 -0
  283. package/dist/esm/excel-parser/plugins/ods/data-validations.d.ts +15 -0
  284. package/dist/esm/excel-parser/plugins/ods/data-validations.d.ts.map +1 -0
  285. package/dist/esm/excel-parser/plugins/ods/data-validations.js +331 -0
  286. package/dist/esm/excel-parser/plugins/ods/formula.d.ts +8 -0
  287. package/dist/esm/excel-parser/plugins/ods/formula.d.ts.map +1 -0
  288. package/dist/esm/excel-parser/plugins/ods/formula.js +82 -0
  289. package/dist/esm/excel-parser/plugins/ods/index.d.ts +122 -0
  290. package/dist/esm/excel-parser/plugins/ods/index.d.ts.map +1 -0
  291. package/dist/esm/excel-parser/plugins/ods/index.js +2896 -0
  292. package/dist/esm/excel-parser/plugins/ods/sparklines.d.ts +25 -0
  293. package/dist/esm/excel-parser/plugins/ods/sparklines.d.ts.map +1 -0
  294. package/dist/esm/excel-parser/plugins/ods/sparklines.js +188 -0
  295. package/dist/esm/excel-parser/plugins/ods/styles.d.ts +60 -0
  296. package/dist/esm/excel-parser/plugins/ods/styles.d.ts.map +1 -0
  297. package/dist/esm/excel-parser/plugins/ods/styles.js +732 -0
  298. package/dist/esm/excel-parser/plugins/ods/types.d.ts +7 -0
  299. package/dist/esm/excel-parser/plugins/ods/types.d.ts.map +1 -0
  300. package/dist/esm/excel-parser/plugins/ods/types.js +1 -0
  301. package/dist/esm/excel-parser/plugins/xls/index.d.ts +5 -0
  302. package/dist/esm/excel-parser/plugins/xls/index.d.ts.map +1 -0
  303. package/dist/esm/excel-parser/plugins/xls/index.js +7 -0
  304. package/dist/esm/excel-parser/plugins/xlsb/biff-record-reader.d.ts +13 -0
  305. package/dist/esm/excel-parser/plugins/xlsb/biff-record-reader.d.ts.map +1 -0
  306. package/dist/esm/excel-parser/plugins/xlsb/biff-record-reader.js +48 -0
  307. package/dist/esm/excel-parser/plugins/xlsb/index.d.ts +117 -0
  308. package/dist/esm/excel-parser/plugins/xlsb/index.d.ts.map +1 -0
  309. package/dist/esm/excel-parser/plugins/xlsb/index.js +2339 -0
  310. package/dist/esm/excel-parser/plugins/xlsb/rgce-parser.d.ts +18 -0
  311. package/dist/esm/excel-parser/plugins/xlsb/rgce-parser.d.ts.map +1 -0
  312. package/dist/esm/excel-parser/plugins/xlsb/rgce-parser.js +522 -0
  313. package/dist/esm/excel-parser/plugins/xlsm/index.d.ts +5 -0
  314. package/dist/esm/excel-parser/plugins/xlsm/index.d.ts.map +1 -0
  315. package/dist/esm/excel-parser/plugins/xlsm/index.js +6 -0
  316. package/dist/esm/excel-parser/plugins/xlsx/charts.d.ts +60 -0
  317. package/dist/esm/excel-parser/plugins/xlsx/charts.d.ts.map +1 -0
  318. package/dist/esm/excel-parser/plugins/xlsx/charts.js +2036 -0
  319. package/dist/esm/excel-parser/plugins/xlsx/conditional-formatting.d.ts +18 -0
  320. package/dist/esm/excel-parser/plugins/xlsx/conditional-formatting.d.ts.map +1 -0
  321. package/dist/esm/excel-parser/plugins/xlsx/conditional-formatting.js +621 -0
  322. package/dist/esm/excel-parser/plugins/xlsx/data-validations.d.ts +4 -0
  323. package/dist/esm/excel-parser/plugins/xlsx/data-validations.d.ts.map +1 -0
  324. package/dist/esm/excel-parser/plugins/xlsx/data-validations.js +493 -0
  325. package/dist/esm/excel-parser/plugins/xlsx/drawing.d.ts +39 -0
  326. package/dist/esm/excel-parser/plugins/xlsx/drawing.d.ts.map +1 -0
  327. package/dist/esm/excel-parser/plugins/xlsx/drawing.js +905 -0
  328. package/dist/esm/excel-parser/plugins/xlsx/index.d.ts +320 -0
  329. package/dist/esm/excel-parser/plugins/xlsx/index.d.ts.map +1 -0
  330. package/dist/esm/excel-parser/plugins/xlsx/index.js +4654 -0
  331. package/dist/esm/excel-parser/plugins/xlsx/numfmt.d.ts +2 -0
  332. package/dist/esm/excel-parser/plugins/xlsx/numfmt.d.ts.map +1 -0
  333. package/dist/esm/excel-parser/plugins/xlsx/numfmt.js +3 -0
  334. package/dist/esm/excel-parser/plugins/xlsx/pivots.d.ts +40 -0
  335. package/dist/esm/excel-parser/plugins/xlsx/pivots.d.ts.map +1 -0
  336. package/dist/esm/excel-parser/plugins/xlsx/pivots.js +254 -0
  337. package/dist/esm/excel-parser/plugins/xlsx/relationships.d.ts +8 -0
  338. package/dist/esm/excel-parser/plugins/xlsx/relationships.d.ts.map +1 -0
  339. package/dist/esm/excel-parser/plugins/xlsx/relationships.js +13 -0
  340. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.d.ts +26 -0
  341. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.d.ts.map +1 -0
  342. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.js +64 -0
  343. package/dist/esm/excel-parser/plugins/xlsx/styles.d.ts +44 -0
  344. package/dist/esm/excel-parser/plugins/xlsx/styles.d.ts.map +1 -0
  345. package/dist/esm/excel-parser/plugins/xlsx/styles.js +1365 -0
  346. package/dist/esm/excel-parser/plugins/xlsx/theme.d.ts +50 -0
  347. package/dist/esm/excel-parser/plugins/xlsx/theme.d.ts.map +1 -0
  348. package/dist/esm/excel-parser/plugins/xlsx/theme.js +127 -0
  349. package/dist/esm/excel-parser/plugins/xlsx/threaded-comments.d.ts +47 -0
  350. package/dist/esm/excel-parser/plugins/xlsx/threaded-comments.d.ts.map +1 -0
  351. package/dist/esm/excel-parser/plugins/xlsx/threaded-comments.js +103 -0
  352. package/dist/esm/excel-parser/plugins/xlsx/value-type-detection.d.ts +44 -0
  353. package/dist/esm/excel-parser/plugins/xlsx/value-type-detection.d.ts.map +1 -0
  354. package/dist/esm/excel-parser/plugins/xlsx/value-type-detection.js +399 -0
  355. package/dist/esm/excel-parser/registry.d.ts +5 -0
  356. package/dist/esm/excel-parser/registry.d.ts.map +1 -0
  357. package/dist/esm/excel-parser/registry.js +20 -0
  358. package/dist/esm/excel-parser/style-registry.d.ts +51 -0
  359. package/dist/esm/excel-parser/style-registry.d.ts.map +1 -0
  360. package/dist/esm/excel-parser/style-registry.js +163 -0
  361. package/dist/esm/excel-parser/theme-default.d.ts +3 -0
  362. package/dist/esm/excel-parser/theme-default.d.ts.map +1 -0
  363. package/dist/esm/excel-parser/theme-default.js +19 -0
  364. package/dist/esm/excel-parser/types.d.ts +365 -0
  365. package/dist/esm/excel-parser/types.d.ts.map +1 -0
  366. package/dist/esm/excel-parser/types.js +59 -0
  367. package/dist/esm/excel-parser/utils.d.ts +6 -0
  368. package/dist/esm/excel-parser/utils.d.ts.map +1 -0
  369. package/dist/esm/excel-parser/utils.js +25 -0
  370. package/dist/esm/excel-parser/workbook.d.ts +51 -0
  371. package/dist/esm/excel-parser/workbook.d.ts.map +1 -0
  372. package/dist/esm/excel-parser/workbook.js +192 -0
  373. package/dist/esm/excel-parser/worker.d.ts +2 -0
  374. package/dist/esm/excel-parser/worker.d.ts.map +1 -0
  375. package/dist/esm/excel-parser/worker.js +862 -0
  376. package/dist/esm/excel-parser/zip-parser-streaming.d.ts +13 -0
  377. package/dist/esm/excel-parser/zip-parser-streaming.d.ts.map +1 -0
  378. package/dist/esm/excel-parser/zip-parser-streaming.js +119 -0
  379. package/dist/esm/excel-parser/zip-parser.d.ts +11 -0
  380. package/dist/esm/excel-parser/zip-parser.d.ts.map +1 -0
  381. package/dist/esm/excel-parser/zip-parser.js +43 -0
  382. package/dist/esm/exporter/invalid-data-validation.d.ts +19 -0
  383. package/dist/esm/exporter/invalid-data-validation.d.ts.map +1 -0
  384. package/dist/esm/exporter/invalid-data-validation.js +37 -0
  385. package/dist/esm/exporter/ods/ods-export.d.ts +26 -0
  386. package/dist/esm/exporter/ods/ods-export.d.ts.map +1 -0
  387. package/dist/esm/exporter/ods/ods-export.js +3238 -0
  388. package/dist/esm/exporter/ods/sparkline-builder.d.ts +33 -0
  389. package/dist/esm/exporter/ods/sparkline-builder.d.ts.map +1 -0
  390. package/dist/esm/exporter/ods/sparkline-builder.js +165 -0
  391. package/dist/esm/exporter/xlsx/chart-builder.d.ts +3 -0
  392. package/dist/esm/exporter/xlsx/chart-builder.d.ts.map +1 -0
  393. package/dist/esm/exporter/xlsx/chart-builder.js +1805 -0
  394. package/dist/esm/exporter/xlsx/chart-templates.d.ts +1781 -0
  395. package/dist/esm/exporter/xlsx/chart-templates.d.ts.map +1 -0
  396. package/dist/esm/exporter/xlsx/chart-templates.js +1798 -0
  397. package/dist/esm/exporter/xlsx/future-functions.d.ts +10 -0
  398. package/dist/esm/exporter/xlsx/future-functions.d.ts.map +1 -0
  399. package/dist/esm/exporter/xlsx/future-functions.js +264 -0
  400. package/dist/esm/exporter/xlsx/pivot-builder.d.ts +58 -0
  401. package/dist/esm/exporter/xlsx/pivot-builder.d.ts.map +1 -0
  402. package/dist/esm/exporter/xlsx/pivot-builder.js +230 -0
  403. package/dist/esm/exporter/xlsx/power-query-builder.d.ts +26 -0
  404. package/dist/esm/exporter/xlsx/power-query-builder.d.ts.map +1 -0
  405. package/dist/esm/exporter/xlsx/power-query-builder.js +257 -0
  406. package/dist/esm/exporter/xlsx/slicer-builder.d.ts +11 -0
  407. package/dist/esm/exporter/xlsx/slicer-builder.d.ts.map +1 -0
  408. package/dist/esm/exporter/xlsx/slicer-builder.js +84 -0
  409. package/dist/esm/exporter/xlsx/sparkline-builder.d.ts +61 -0
  410. package/dist/esm/exporter/xlsx/sparkline-builder.d.ts.map +1 -0
  411. package/dist/esm/exporter/xlsx/sparkline-builder.js +437 -0
  412. package/dist/esm/exporter/xlsx/style-builder.d.ts +93 -0
  413. package/dist/esm/exporter/xlsx/style-builder.d.ts.map +1 -0
  414. package/dist/esm/exporter/xlsx/style-builder.js +795 -0
  415. package/dist/esm/exporter/xlsx/threaded-comments-builder.d.ts +58 -0
  416. package/dist/esm/exporter/xlsx/threaded-comments-builder.d.ts.map +1 -0
  417. package/dist/esm/exporter/xlsx/threaded-comments-builder.js +175 -0
  418. package/dist/esm/exporter/xlsx/xlsx-export.d.ts +121 -0
  419. package/dist/esm/exporter/xlsx/xlsx-export.d.ts.map +1 -0
  420. package/dist/esm/exporter/xlsx/xlsx-export.js +4062 -0
  421. package/dist/esm/helpers/theme-xml-generator.d.ts +8 -0
  422. package/dist/esm/helpers/theme-xml-generator.d.ts.map +1 -0
  423. package/dist/esm/helpers/theme-xml-generator.js +33 -0
  424. package/dist/esm/helpers.d.ts +34 -0
  425. package/dist/esm/helpers.d.ts.map +1 -0
  426. package/dist/esm/helpers.js +182 -0
  427. package/dist/esm/index.d.ts +16 -0
  428. package/dist/esm/index.d.ts.map +1 -0
  429. package/dist/esm/index.js +15 -0
  430. package/dist/esm/indexed-colors.d.ts +2 -0
  431. package/dist/esm/indexed-colors.d.ts.map +1 -0
  432. package/dist/esm/indexed-colors.js +75 -0
  433. package/dist/esm/ods-export.d.ts +24 -0
  434. package/dist/esm/ods-export.d.ts.map +1 -0
  435. package/dist/esm/ods-export.js +12 -0
  436. package/dist/esm/parse.d.ts +24 -0
  437. package/dist/esm/parse.d.ts.map +1 -0
  438. package/dist/esm/parse.js +55 -0
  439. package/dist/esm/power-query.d.ts +41 -0
  440. package/dist/esm/power-query.d.ts.map +1 -0
  441. package/dist/esm/power-query.js +19 -0
  442. package/dist/esm/server.d.ts +9 -0
  443. package/dist/esm/server.d.ts.map +1 -0
  444. package/dist/esm/server.js +8 -0
  445. package/dist/esm/theme1.d.ts +3 -0
  446. package/dist/esm/theme1.d.ts.map +1 -0
  447. package/dist/esm/theme1.js +2 -0
  448. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -0
  449. package/dist/esm/types.d.ts +14 -0
  450. package/dist/esm/types.d.ts.map +1 -0
  451. package/dist/esm/types.js +14 -0
  452. package/dist/esm/vitest.config.d.ts +3 -0
  453. package/dist/esm/vitest.config.d.ts.map +1 -0
  454. package/dist/esm/vitest.config.js +16 -0
  455. package/package.json +62 -0
  456. package/xlsx.d.ts +52 -0
@@ -0,0 +1,4596 @@
1
+ import { __assign, __awaiter, __generator, __read, __spreadArray, __values } from "tslib";
2
+ import { cellRangeToAddress, cellToAddress, escapeCharacters, getCellEffectiveFormat, getCellEffectiveValue, getCellFormattedValue, getCellUserEnteredFormat, getCellUserEnteredValue, getExtendedValueBool, getExtendedValueError, getExtendedValueFormula, getExtendedValueNumber, getExtendedValueString, isNil, sortSheetsByIndex, } from "@rowsncolumns/utils";
3
+ import { zipSync } from "fflate";
4
+ import { omitInvalidDataValidationError } from "../invalid-data-validation";
5
+ import { buildAutoFilterConditionXml } from "../../autofilter-condition";
6
+ import { applyPowerQueryParts } from "./power-query-builder";
7
+ import { qualifyFutureFunctions } from "./future-functions";
8
+ import { PERSON_CONTENT_TYPE, PERSON_REL_TYPE, PersonRegistry, THREADED_COMMENT_REL_TYPE, THREADED_COMMENTS_CONTENT_TYPE, ThreadedCommentsCollector, } from "./threaded-comments-builder";
9
+ import { CFBEncryptor } from "../../excel-parser/cfb-encryptor";
10
+ import { columnPixelToChars, imageUrlToBase64 } from "../../helpers";
11
+ import { generateThemeXml } from "../../helpers/theme-xml-generator";
12
+ import theme1Xml from "../../theme1";
13
+ import { tokenize as defaultTokenizer } from "@rowsncolumns/calculator";
14
+ import { CellXfsRegistry, deriveEffectiveNumberFormatFromFormula, } from "@rowsncolumns/spreadsheet-state";
15
+ import { buildChartXml } from "./chart-builder";
16
+ import { buildPivotCacheDefinitionXml, buildPivotTableRelsXml, buildPivotTableXml, } from "./pivot-builder";
17
+ import { buildSlicerCacheXml, buildSlicerXml } from "./slicer-builder";
18
+ import { buildSparklineGroupsXml } from "./sparkline-builder";
19
+ import { StyleBuilder } from "./style-builder";
20
+ var BLANK_LABEL = "(Blanks)";
21
+ var isStyleReference = function (value) {
22
+ return !!value && typeof value === "object" && "sid" in value;
23
+ };
24
+ var DEFAULT_COLUMN_WIDTH_PX = 100;
25
+ var DEFAULT_ROW_HEIGHT_PX = 21;
26
+ var pixelToPoints = function (px) {
27
+ return Math.max(1, Number(((px * 72) / 96).toFixed(2)));
28
+ };
29
+ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
30
+ var sortedSheets, sharedStrings, personRegistry, styleBuilder, exportableTables, tableIdMap, preparedTables, embedsBySheet, textBoxesBySheet, shapesBySheet, chartsBySheet, remappedSlicers, slicersBySheet, workbookSheetNames, sheetNameById, dataValidationsById, globalSlicerIndex, slicerCacheEntries, slicerEntries, globalPivotIndex, pivotCacheEntries, pivotCacheRelsEntries, pivotTableEntries, pivotTableRelsEntries, pivotsByTargetSheet, pivotTables_1, pivotTables_1_1, p, sid, list, workbookPivotCacheRefs, worksheetEntries, _d, workbookRelationshipsXml, sheetRelationshipIds, slicerCacheRelationshipIds, pivotCacheRelationshipIds, externalLinkRelationshipIds, workbookXml, sharedStringsXml, rootRelationshipsXml, appXml, coreXml, stylesXml, themeXml, files, worksheetEntries_1, worksheetEntries_1_1, entry, personsXml, preparedTables_1, preparedTables_1_1, table, rows, tableXml, globalImageIndex, globalChartIndex, drawingSheets, imageExtensions, chartEntries, worksheetEntries_2, worksheetEntries_2_1, entry, placements, textBoxesForSheet, shapesForSheet, chartsForSheet, slicersForSheet, drawingParts, _e, _f, media, _g, _h, chartEntry, e_1_1, chartEntries_1, chartEntries_1_1, chartEntry, slicerCacheEntries_1, slicerCacheEntries_1_1, slicerCacheEntry, slicerEntries_1, slicerEntries_1_1, slicerEntry, pivotCacheEntries_1, pivotCacheEntries_1_1, cacheEntry, pivotCacheRelsEntries_1, pivotCacheRelsEntries_1_1, cacheRels, pivotTableEntries_1, pivotTableEntries_1_1, tableEntry, pivotTableRelsEntries_1, pivotTableRelsEntries_1_1, tableRels, i, link, linkPath, relsPath, commentsSheets, threadedCommentsSheets, contentTypesXml, zipBytes;
31
+ var e_2, _j, e_3, _k, e_4, _l, e_1, _m, e_5, _o, e_6, _p, e_7, _q, e_8, _s, e_9, _t, e_10, _u, e_11, _v, e_12, _w, e_13, _x;
32
+ var _y, _z, _0, _1, _2, _3;
33
+ var _conditionalFormats = _b.conditionalFormats, _dataValidations = _b.dataValidations, sheets = _b.sheets, sheetData = _b.sheetData, sourceSharedStrings = _b.sharedStrings, _4 = _b.tables, _tables = _4 === void 0 ? [] : _4, cellXfs = _b.cellXfs, theme = _b.theme, defaultFont = _b.defaultFont, _5 = _b.embeds, embeds = _5 === void 0 ? [] : _5, _6 = _b.charts, charts = _6 === void 0 ? [] : _6, _7 = _b.slicers, slicers = _7 === void 0 ? [] : _7, _8 = _b.pivotTables, pivotTables = _8 === void 0 ? [] : _8, _9 = _b.externalLinks, externalLinks = _9 === void 0 ? [] : _9, _10 = _b.namedRanges, namedRanges = _10 === void 0 ? [] : _10, namedCellStyles = _b.namedCellStyles, customTableStyles = _b.customTableStyles, iterativeCalculationOptions = _b.iterativeCalculationOptions, ignoreFormulaPatterns = _b.ignoreFormulaPatterns, citations = _b.citations, comments = _b.comments, password = _b.password, locale = _b.locale, _11 = _b.use1904, use1904 = _11 === void 0 ? false : _11, properties = _b.properties, powerQuery = _b.powerQuery;
34
+ return __generator(this, function (_12) {
35
+ switch (_12.label) {
36
+ case 0:
37
+ sortedSheets = sortSheetsByIndex(sheets, true);
38
+ sharedStrings = new SharedStrings();
39
+ personRegistry = new PersonRegistry();
40
+ styleBuilder = new StyleBuilder();
41
+ if (defaultFont) {
42
+ styleBuilder.setDefaultFont(defaultFont);
43
+ }
44
+ if (namedCellStyles && namedCellStyles.length > 0) {
45
+ styleBuilder.setNamedCellStyles(namedCellStyles);
46
+ }
47
+ if (customTableStyles && customTableStyles.length > 0) {
48
+ styleBuilder.setCustomTableStyles(customTableStyles);
49
+ }
50
+ exportableTables = filterExportableTables(_tables !== null && _tables !== void 0 ? _tables : []);
51
+ tableIdMap = new Map();
52
+ exportableTables.forEach(function (table, index) {
53
+ tableIdMap.set(table.id, index + 1);
54
+ tableIdMap.set(String(table.id), index + 1);
55
+ });
56
+ preparedTables = prepareTables(exportableTables);
57
+ embedsBySheet = groupEmbedsBySheet(embeds !== null && embeds !== void 0 ? embeds : []);
58
+ textBoxesBySheet = groupTextBoxesBySheet(embeds !== null && embeds !== void 0 ? embeds : []);
59
+ shapesBySheet = groupShapesBySheet(embeds !== null && embeds !== void 0 ? embeds : []);
60
+ chartsBySheet = groupChartsBySheet(charts !== null && charts !== void 0 ? charts : []);
61
+ remappedSlicers = slicers.map(function (slicer) {
62
+ if (slicer.spec.type !== "table")
63
+ return slicer;
64
+ var remappedTableIds = slicer.spec.tableIds
65
+ .map(function (tid) { return tableIdMap.get(tid); })
66
+ .filter(function (id) { return id !== undefined; })
67
+ .map(String); // Keep as strings for consistency
68
+ return __assign(__assign({}, slicer), { spec: __assign(__assign({}, slicer.spec), { tableIds: remappedTableIds }) });
69
+ });
70
+ slicersBySheet = groupSlicersBySheet(remappedSlicers !== null && remappedSlicers !== void 0 ? remappedSlicers : []);
71
+ workbookSheetNames = buildWorkbookSheetNames(sortedSheets);
72
+ sheetNameById = new Map();
73
+ sortedSheets.forEach(function (sheet, index) {
74
+ var _a;
75
+ sheetNameById.set((_a = sheet.sheetId) !== null && _a !== void 0 ? _a : index + 1, workbookSheetNames[index]);
76
+ });
77
+ dataValidationsById = (_y = _dataValidations === null || _dataValidations === void 0 ? void 0 : _dataValidations.reduce(function (acc, rule) {
78
+ acc[rule.id] = rule;
79
+ return acc;
80
+ }, {})) !== null && _y !== void 0 ? _y : undefined;
81
+ globalSlicerIndex = 1;
82
+ slicerCacheEntries = [];
83
+ slicerEntries = [];
84
+ globalPivotIndex = 1;
85
+ pivotCacheEntries = [];
86
+ pivotCacheRelsEntries = [];
87
+ pivotTableEntries = [];
88
+ pivotTableRelsEntries = [];
89
+ pivotsByTargetSheet = new Map();
90
+ try {
91
+ for (pivotTables_1 = __values(pivotTables), pivotTables_1_1 = pivotTables_1.next(); !pivotTables_1_1.done; pivotTables_1_1 = pivotTables_1.next()) {
92
+ p = pivotTables_1_1.value;
93
+ sid = (_z = p.targetPosition) === null || _z === void 0 ? void 0 : _z.sheetId;
94
+ if (sid == null)
95
+ continue;
96
+ list = pivotsByTargetSheet.get(sid);
97
+ if (list)
98
+ list.push(p);
99
+ else
100
+ pivotsByTargetSheet.set(sid, [p]);
101
+ }
102
+ }
103
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
104
+ finally {
105
+ try {
106
+ if (pivotTables_1_1 && !pivotTables_1_1.done && (_j = pivotTables_1.return)) _j.call(pivotTables_1);
107
+ }
108
+ finally { if (e_2) throw e_2.error; }
109
+ }
110
+ workbookPivotCacheRefs = [];
111
+ worksheetEntries = sortedSheets.map(function (sheet, index) {
112
+ var e_14, _a, e_15, _b;
113
+ var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
114
+ var rows = getRowsForSheet(sheetData, sheet.sheetId);
115
+ var sheetRelationships = new RelationshipsBuilder();
116
+ var sheetTables = preparedTables.filter(function (table) { return table.sheetId === sheet.sheetId; });
117
+ var embedImages = (_d = embedsBySheet.get(sheet.sheetId)) !== null && _d !== void 0 ? _d : [];
118
+ var textBoxes = (_e = textBoxesBySheet.get(sheet.sheetId)) !== null && _e !== void 0 ? _e : [];
119
+ var sheetShapes = (_f = shapesBySheet.get(sheet.sheetId)) !== null && _f !== void 0 ? _f : [];
120
+ var sheetCharts = (_g = chartsBySheet.get(sheet.sheetId)) !== null && _g !== void 0 ? _g : [];
121
+ var sheetSlicers = (_h = slicersBySheet.get(sheet.sheetId)) !== null && _h !== void 0 ? _h : [];
122
+ var worksheetSlicerRelIds = [];
123
+ var drawingSlicers = [];
124
+ var sheetConditionalFormats = (_conditionalFormats !== null && _conditionalFormats !== void 0 ? _conditionalFormats : []).filter(function (rule) { var _a; return (_a = rule.ranges) === null || _a === void 0 ? void 0 : _a.some(function (range) { return range.sheetId === sheet.sheetId; }); });
125
+ var drawingContext = new DrawingContext(sheetRelationships, "../drawings/drawing".concat(index + 1, ".xml"), embedImages.length > 0 ||
126
+ textBoxes.length > 0 ||
127
+ sheetShapes.length > 0 ||
128
+ sheetCharts.length > 0 ||
129
+ sheetSlicers.length > 0);
130
+ var sheetCitations = citations === null || citations === void 0 ? void 0 : citations.filter(function (citation) { return citation.range.sheetId === sheet.sheetId; });
131
+ try {
132
+ // Generate slicer XML for this sheet
133
+ for (var sheetSlicers_1 = __values(sheetSlicers), sheetSlicers_1_1 = sheetSlicers_1.next(); !sheetSlicers_1_1.done; sheetSlicers_1_1 = sheetSlicers_1.next()) {
134
+ var placement = sheetSlicers_1_1.value;
135
+ var slicer = placement.slicer;
136
+ var cacheIndex = globalSlicerIndex;
137
+ var slicerIndex = globalSlicerIndex;
138
+ var cacheName = buildSlicerCacheName(slicer.spec.title || "Slicer".concat(slicerIndex));
139
+ // Create slicer cache XML
140
+ var slicerCacheXml = buildSlicerCacheXml(slicer, sheetTables, cacheName);
141
+ if (slicerCacheXml) {
142
+ slicerCacheEntries.push({
143
+ path: "xl/slicerCaches/slicerCache".concat(cacheIndex, ".xml"),
144
+ xml: slicerCacheXml,
145
+ });
146
+ // Create slicer XML
147
+ var slicerXml = buildSlicerXml(slicer, cacheName);
148
+ slicerEntries.push({
149
+ path: "xl/slicers/slicer".concat(slicerIndex, ".xml"),
150
+ xml: slicerXml,
151
+ });
152
+ // Add relationship from worksheet to slicer
153
+ var worksheetSlicerRelId = sheetRelationships.add(SLICER_REL_TYPE, "../slicers/slicer".concat(slicerIndex, ".xml"));
154
+ worksheetSlicerRelIds.push(worksheetSlicerRelId);
155
+ drawingSlicers.push({
156
+ slicerIndex: slicerIndex,
157
+ title: slicer.spec.title || "Slicer ".concat(slicerIndex),
158
+ rowIndex: placement.rowIndex,
159
+ columnIndex: placement.columnIndex,
160
+ offsetX: placement.offsetX,
161
+ offsetY: placement.offsetY,
162
+ width: placement.width,
163
+ height: placement.height,
164
+ });
165
+ globalSlicerIndex += 1;
166
+ }
167
+ }
168
+ }
169
+ catch (e_14_1) { e_14 = { error: e_14_1 }; }
170
+ finally {
171
+ try {
172
+ if (sheetSlicers_1_1 && !sheetSlicers_1_1.done && (_a = sheetSlicers_1.return)) _a.call(sheetSlicers_1);
173
+ }
174
+ finally { if (e_14) throw e_14.error; }
175
+ }
176
+ // Phase D2 — emit pivot table XMLs + relationships for this
177
+ // sheet. PivotTable lives on the rendering sheet; its cache
178
+ // definition is workbook-scoped (added to <pivotCaches> after
179
+ // this loop).
180
+ var sheetPivots = (_j = pivotsByTargetSheet.get(sheet.sheetId)) !== null && _j !== void 0 ? _j : [];
181
+ var _loop_1 = function (pivot) {
182
+ var e_16, _q, e_17, _s, e_18, _t;
183
+ var cacheIndex = globalPivotIndex;
184
+ var tableIndex = globalPivotIndex;
185
+ var sourceSheet = sortedSheets.find(function (s) { var _a; return s.sheetId === ((_a = pivot.source) === null || _a === void 0 ? void 0 : _a.sheetId); });
186
+ var sourceSheetName = (_l = (_k = sourceSheet === null || sourceSheet === void 0 ? void 0 : sourceSheet.title) !== null && _k !== void 0 ? _k : sheet.title) !== null && _l !== void 0 ? _l : "Sheet".concat(sheet.sheetId);
187
+ // Field universe: union of every field referenced by the
188
+ // pivot. PivotCacheDefinition requires one <cacheField>
189
+ // entry per field, and pivotTable.fld indices reference them.
190
+ var fieldNameList = [];
191
+ var fieldIndex = new Map();
192
+ var registerField = function (name) {
193
+ if (!name || fieldIndex.has(name))
194
+ return;
195
+ fieldIndex.set(name, fieldNameList.length);
196
+ fieldNameList.push(name);
197
+ };
198
+ try {
199
+ for (var _u = (e_16 = void 0, __values((_m = pivot.rows) !== null && _m !== void 0 ? _m : [])), _v = _u.next(); !_v.done; _v = _u.next()) {
200
+ var r = _v.value;
201
+ registerField(r.field);
202
+ }
203
+ }
204
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
205
+ finally {
206
+ try {
207
+ if (_v && !_v.done && (_q = _u.return)) _q.call(_u);
208
+ }
209
+ finally { if (e_16) throw e_16.error; }
210
+ }
211
+ try {
212
+ for (var _w = (e_17 = void 0, __values((_o = pivot.columns) !== null && _o !== void 0 ? _o : [])), _x = _w.next(); !_x.done; _x = _w.next()) {
213
+ var c = _x.value;
214
+ registerField(c.field);
215
+ }
216
+ }
217
+ catch (e_17_1) { e_17 = { error: e_17_1 }; }
218
+ finally {
219
+ try {
220
+ if (_x && !_x.done && (_s = _w.return)) _s.call(_w);
221
+ }
222
+ finally { if (e_17) throw e_17.error; }
223
+ }
224
+ try {
225
+ for (var _y = (e_18 = void 0, __values((_p = pivot.values) !== null && _p !== void 0 ? _p : [])), _z = _y.next(); !_z.done; _z = _y.next()) {
226
+ var v = _z.value;
227
+ registerField(v.field);
228
+ }
229
+ }
230
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
231
+ finally {
232
+ try {
233
+ if (_z && !_z.done && (_t = _y.return)) _t.call(_y);
234
+ }
235
+ finally { if (e_18) throw e_18.error; }
236
+ }
237
+ var cacheXml = buildPivotCacheDefinitionXml(pivot, sourceSheetName, fieldNameList);
238
+ var tableXml = buildPivotTableXml(pivot, cacheIndex, fieldIndex);
239
+ if (!cacheXml || !tableXml)
240
+ return "continue";
241
+ pivotCacheEntries.push({
242
+ path: "xl/pivotCache/pivotCacheDefinition".concat(cacheIndex, ".xml"),
243
+ xml: cacheXml,
244
+ });
245
+ pivotTableEntries.push({
246
+ path: "xl/pivotTables/pivotTable".concat(tableIndex, ".xml"),
247
+ xml: tableXml,
248
+ });
249
+ // pivotTable<N>.xml.rels → links to its cache definition.
250
+ pivotTableRelsEntries.push({
251
+ path: "xl/pivotTables/_rels/pivotTable".concat(tableIndex, ".xml.rels"),
252
+ xml: buildPivotTableRelsXml("rId1", "../pivotCache/pivotCacheDefinition".concat(cacheIndex, ".xml")),
253
+ });
254
+ // sheet → pivotTable relationship.
255
+ sheetRelationships.add(PIVOT_TABLE_REL_TYPE, "../pivotTables/pivotTable".concat(tableIndex, ".xml"));
256
+ // Record the cache for the workbook-level <pivotCaches> list.
257
+ workbookPivotCacheRefs.push({ cacheIndex: cacheIndex });
258
+ globalPivotIndex += 1;
259
+ };
260
+ try {
261
+ for (var sheetPivots_1 = __values(sheetPivots), sheetPivots_1_1 = sheetPivots_1.next(); !sheetPivots_1_1.done; sheetPivots_1_1 = sheetPivots_1.next()) {
262
+ var pivot = sheetPivots_1_1.value;
263
+ _loop_1(pivot);
264
+ }
265
+ }
266
+ catch (e_15_1) { e_15 = { error: e_15_1 }; }
267
+ finally {
268
+ try {
269
+ if (sheetPivots_1_1 && !sheetPivots_1_1.done && (_b = sheetPivots_1.return)) _b.call(sheetPivots_1);
270
+ }
271
+ finally { if (e_15) throw e_15.error; }
272
+ }
273
+ var result = buildWorksheetXml({
274
+ sheet: sheet,
275
+ rows: rows,
276
+ sharedStrings: sharedStrings,
277
+ sourceSharedStrings: sourceSharedStrings,
278
+ cellXfs: cellXfs,
279
+ styleBuilder: styleBuilder,
280
+ tables: sheetTables,
281
+ relationships: sheetRelationships,
282
+ drawingContext: drawingContext,
283
+ conditionalFormats: sheetConditionalFormats,
284
+ dataValidationsById: dataValidationsById,
285
+ dataValidations: _dataValidations,
286
+ ignoreFormulaPatterns: ignoreFormulaPatterns,
287
+ citations: sheetCitations,
288
+ comments: comments,
289
+ personRegistry: personRegistry,
290
+ slicerRelIds: worksheetSlicerRelIds,
291
+ sheetData: sheetData,
292
+ sheets: sortedSheets,
293
+ locale: locale,
294
+ });
295
+ return {
296
+ index: index,
297
+ path: "xl/worksheets/sheet".concat(index + 1, ".xml"),
298
+ relationshipsPath: "xl/worksheets/_rels/sheet".concat(index + 1, ".xml.rels"),
299
+ content: result.xml,
300
+ relationshipsXml: result.relationshipsXml,
301
+ drawingPath: "xl/drawings/drawing".concat(index + 1, ".xml"),
302
+ drawingRelsPath: "xl/drawings/_rels/drawing".concat(index + 1, ".xml.rels"),
303
+ cellImages: result.images,
304
+ embedImages: embedImages,
305
+ textBoxes: textBoxes,
306
+ shapes: sheetShapes,
307
+ charts: sheetCharts,
308
+ slicers: drawingSlicers,
309
+ sheet: sheet,
310
+ commentsXml: result.commentsXml,
311
+ vmlDrawingXml: result.vmlDrawingXml,
312
+ threadedCommentsXml: result.threadedCommentsXml,
313
+ };
314
+ });
315
+ _d = buildWorkbookRelationships(worksheetEntries.length, slicerCacheEntries.length, externalLinks.length, pivotCacheEntries.length, !personRegistry.isEmpty()), workbookRelationshipsXml = _d.xml, sheetRelationshipIds = _d.sheetRelationshipIds, slicerCacheRelationshipIds = _d.slicerCacheRelationshipIds, pivotCacheRelationshipIds = _d.pivotCacheRelationshipIds, externalLinkRelationshipIds = _d.externalLinkRelationshipIds;
316
+ workbookXml = buildWorkbookXml(sortedSheets, sheetRelationshipIds, workbookSheetNames, namedRanges, iterativeCalculationOptions, slicerCacheRelationshipIds, use1904, externalLinkRelationshipIds, pivotCacheRelationshipIds);
317
+ sharedStringsXml = buildSharedStringsXml(sharedStrings);
318
+ rootRelationshipsXml = buildRootRelationshipsXml();
319
+ appXml = buildAppXml(workbookSheetNames, properties);
320
+ coreXml = buildCoreXml(properties);
321
+ stylesXml = styleBuilder.toXml();
322
+ themeXml = theme ? generateThemeXml(theme) : theme1Xml;
323
+ files = {
324
+ "_rels/.rels": encodeXml(rootRelationshipsXml),
325
+ "docProps/app.xml": encodeXml(appXml),
326
+ "docProps/core.xml": encodeXml(coreXml),
327
+ "xl/workbook.xml": encodeXml(workbookXml),
328
+ "xl/_rels/workbook.xml.rels": encodeXml(workbookRelationshipsXml),
329
+ "xl/sharedStrings.xml": encodeXml(sharedStringsXml),
330
+ "xl/styles.xml": encodeXml(stylesXml),
331
+ "xl/theme/theme1.xml": encodeXml(themeXml),
332
+ };
333
+ try {
334
+ for (worksheetEntries_1 = __values(worksheetEntries), worksheetEntries_1_1 = worksheetEntries_1.next(); !worksheetEntries_1_1.done; worksheetEntries_1_1 = worksheetEntries_1.next()) {
335
+ entry = worksheetEntries_1_1.value;
336
+ files[entry.path] = encodeXml(entry.content);
337
+ if (entry.relationshipsXml) {
338
+ files[entry.relationshipsPath] = encodeXml(entry.relationshipsXml);
339
+ }
340
+ if (entry.commentsXml) {
341
+ files["xl/comments".concat(entry.sheet.sheetId, ".xml")] = encodeXml(entry.commentsXml);
342
+ }
343
+ if (entry.vmlDrawingXml) {
344
+ files["xl/drawings/vmlDrawing".concat(entry.sheet.sheetId, ".vml")] = encodeXml(entry.vmlDrawingXml);
345
+ }
346
+ if (entry.threadedCommentsXml) {
347
+ files["xl/threadedComments/threadedComment".concat(entry.sheet.sheetId, ".xml")] =
348
+ encodeXml(entry.threadedCommentsXml);
349
+ }
350
+ }
351
+ }
352
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
353
+ finally {
354
+ try {
355
+ if (worksheetEntries_1_1 && !worksheetEntries_1_1.done && (_k = worksheetEntries_1.return)) _k.call(worksheetEntries_1);
356
+ }
357
+ finally { if (e_3) throw e_3.error; }
358
+ }
359
+ personsXml = personRegistry.toXml();
360
+ if (personsXml) {
361
+ files["xl/persons/person.xml"] = encodeXml(personsXml);
362
+ }
363
+ try {
364
+ for (preparedTables_1 = __values(preparedTables), preparedTables_1_1 = preparedTables_1.next(); !preparedTables_1_1.done; preparedTables_1_1 = preparedTables_1.next()) {
365
+ table = preparedTables_1_1.value;
366
+ rows = getRowsForSheet(sheetData, table.sheetId);
367
+ tableXml = buildTableXml(table, rows, sourceSharedStrings, styleBuilder);
368
+ if (tableXml) {
369
+ files[table.path] = encodeXml(tableXml);
370
+ }
371
+ }
372
+ }
373
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
374
+ finally {
375
+ try {
376
+ if (preparedTables_1_1 && !preparedTables_1_1.done && (_l = preparedTables_1.return)) _l.call(preparedTables_1);
377
+ }
378
+ finally { if (e_4) throw e_4.error; }
379
+ }
380
+ globalImageIndex = 1;
381
+ globalChartIndex = 1;
382
+ drawingSheets = [];
383
+ imageExtensions = new Set();
384
+ chartEntries = [];
385
+ _12.label = 1;
386
+ case 1:
387
+ _12.trys.push([1, 6, 7, 8]);
388
+ worksheetEntries_2 = __values(worksheetEntries), worksheetEntries_2_1 = worksheetEntries_2.next();
389
+ _12.label = 2;
390
+ case 2:
391
+ if (!!worksheetEntries_2_1.done) return [3 /*break*/, 5];
392
+ entry = worksheetEntries_2_1.value;
393
+ placements = __spreadArray(__spreadArray([], __read(entry.cellImages), false), __read(entry.embedImages), false);
394
+ textBoxesForSheet = (_0 = entry.textBoxes) !== null && _0 !== void 0 ? _0 : [];
395
+ shapesForSheet = (_1 = entry.shapes) !== null && _1 !== void 0 ? _1 : [];
396
+ chartsForSheet = (_2 = entry.charts) !== null && _2 !== void 0 ? _2 : [];
397
+ slicersForSheet = (_3 = entry.slicers) !== null && _3 !== void 0 ? _3 : [];
398
+ if (!placements.length &&
399
+ !textBoxesForSheet.length &&
400
+ !shapesForSheet.length &&
401
+ !chartsForSheet.length &&
402
+ !slicersForSheet.length)
403
+ return [3 /*break*/, 4];
404
+ return [4 /*yield*/, buildDrawingParts({
405
+ sheet: entry.sheet,
406
+ placements: placements,
407
+ textBoxes: textBoxesForSheet,
408
+ shapes: shapesForSheet,
409
+ startImageIndex: globalImageIndex,
410
+ startChartIndex: globalChartIndex,
411
+ charts: chartsForSheet,
412
+ slicers: slicersForSheet,
413
+ sheetNameById: sheetNameById,
414
+ })];
415
+ case 3:
416
+ drawingParts = _12.sent();
417
+ if (!drawingParts)
418
+ return [3 /*break*/, 4];
419
+ files[entry.drawingPath] = encodeXml(drawingParts.xml);
420
+ if (drawingParts.relsXml) {
421
+ files[entry.drawingRelsPath] = encodeXml(drawingParts.relsXml);
422
+ }
423
+ try {
424
+ for (_e = (e_5 = void 0, __values(drawingParts.media)), _f = _e.next(); !_f.done; _f = _e.next()) {
425
+ media = _f.value;
426
+ files[media.path] = media.data;
427
+ imageExtensions.add(media.extension);
428
+ }
429
+ }
430
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
431
+ finally {
432
+ try {
433
+ if (_f && !_f.done && (_o = _e.return)) _o.call(_e);
434
+ }
435
+ finally { if (e_5) throw e_5.error; }
436
+ }
437
+ try {
438
+ for (_g = (e_6 = void 0, __values(drawingParts.charts)), _h = _g.next(); !_h.done; _h = _g.next()) {
439
+ chartEntry = _h.value;
440
+ chartEntries.push(chartEntry);
441
+ }
442
+ }
443
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
444
+ finally {
445
+ try {
446
+ if (_h && !_h.done && (_p = _g.return)) _p.call(_g);
447
+ }
448
+ finally { if (e_6) throw e_6.error; }
449
+ }
450
+ globalImageIndex = drawingParts.nextImageIndex;
451
+ globalChartIndex = drawingParts.nextChartIndex;
452
+ drawingSheets.push(entry.index + 1);
453
+ _12.label = 4;
454
+ case 4:
455
+ worksheetEntries_2_1 = worksheetEntries_2.next();
456
+ return [3 /*break*/, 2];
457
+ case 5: return [3 /*break*/, 8];
458
+ case 6:
459
+ e_1_1 = _12.sent();
460
+ e_1 = { error: e_1_1 };
461
+ return [3 /*break*/, 8];
462
+ case 7:
463
+ try {
464
+ if (worksheetEntries_2_1 && !worksheetEntries_2_1.done && (_m = worksheetEntries_2.return)) _m.call(worksheetEntries_2);
465
+ }
466
+ finally { if (e_1) throw e_1.error; }
467
+ return [7 /*endfinally*/];
468
+ case 8:
469
+ try {
470
+ for (chartEntries_1 = __values(chartEntries), chartEntries_1_1 = chartEntries_1.next(); !chartEntries_1_1.done; chartEntries_1_1 = chartEntries_1.next()) {
471
+ chartEntry = chartEntries_1_1.value;
472
+ files[chartEntry.path] = encodeXml(chartEntry.xml);
473
+ }
474
+ }
475
+ catch (e_7_1) { e_7 = { error: e_7_1 }; }
476
+ finally {
477
+ try {
478
+ if (chartEntries_1_1 && !chartEntries_1_1.done && (_q = chartEntries_1.return)) _q.call(chartEntries_1);
479
+ }
480
+ finally { if (e_7) throw e_7.error; }
481
+ }
482
+ try {
483
+ for (slicerCacheEntries_1 = __values(slicerCacheEntries), slicerCacheEntries_1_1 = slicerCacheEntries_1.next(); !slicerCacheEntries_1_1.done; slicerCacheEntries_1_1 = slicerCacheEntries_1.next()) {
484
+ slicerCacheEntry = slicerCacheEntries_1_1.value;
485
+ files[slicerCacheEntry.path] = encodeXml(slicerCacheEntry.xml);
486
+ }
487
+ }
488
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
489
+ finally {
490
+ try {
491
+ if (slicerCacheEntries_1_1 && !slicerCacheEntries_1_1.done && (_s = slicerCacheEntries_1.return)) _s.call(slicerCacheEntries_1);
492
+ }
493
+ finally { if (e_8) throw e_8.error; }
494
+ }
495
+ try {
496
+ for (slicerEntries_1 = __values(slicerEntries), slicerEntries_1_1 = slicerEntries_1.next(); !slicerEntries_1_1.done; slicerEntries_1_1 = slicerEntries_1.next()) {
497
+ slicerEntry = slicerEntries_1_1.value;
498
+ files[slicerEntry.path] = encodeXml(slicerEntry.xml);
499
+ }
500
+ }
501
+ catch (e_9_1) { e_9 = { error: e_9_1 }; }
502
+ finally {
503
+ try {
504
+ if (slicerEntries_1_1 && !slicerEntries_1_1.done && (_t = slicerEntries_1.return)) _t.call(slicerEntries_1);
505
+ }
506
+ finally { if (e_9) throw e_9.error; }
507
+ }
508
+ try {
509
+ // Phase D2 — emit pivot files.
510
+ for (pivotCacheEntries_1 = __values(pivotCacheEntries), pivotCacheEntries_1_1 = pivotCacheEntries_1.next(); !pivotCacheEntries_1_1.done; pivotCacheEntries_1_1 = pivotCacheEntries_1.next()) {
511
+ cacheEntry = pivotCacheEntries_1_1.value;
512
+ files[cacheEntry.path] = encodeXml(cacheEntry.xml);
513
+ }
514
+ }
515
+ catch (e_10_1) { e_10 = { error: e_10_1 }; }
516
+ finally {
517
+ try {
518
+ if (pivotCacheEntries_1_1 && !pivotCacheEntries_1_1.done && (_u = pivotCacheEntries_1.return)) _u.call(pivotCacheEntries_1);
519
+ }
520
+ finally { if (e_10) throw e_10.error; }
521
+ }
522
+ try {
523
+ for (pivotCacheRelsEntries_1 = __values(pivotCacheRelsEntries), pivotCacheRelsEntries_1_1 = pivotCacheRelsEntries_1.next(); !pivotCacheRelsEntries_1_1.done; pivotCacheRelsEntries_1_1 = pivotCacheRelsEntries_1.next()) {
524
+ cacheRels = pivotCacheRelsEntries_1_1.value;
525
+ files[cacheRels.path] = encodeXml(cacheRels.xml);
526
+ }
527
+ }
528
+ catch (e_11_1) { e_11 = { error: e_11_1 }; }
529
+ finally {
530
+ try {
531
+ if (pivotCacheRelsEntries_1_1 && !pivotCacheRelsEntries_1_1.done && (_v = pivotCacheRelsEntries_1.return)) _v.call(pivotCacheRelsEntries_1);
532
+ }
533
+ finally { if (e_11) throw e_11.error; }
534
+ }
535
+ try {
536
+ for (pivotTableEntries_1 = __values(pivotTableEntries), pivotTableEntries_1_1 = pivotTableEntries_1.next(); !pivotTableEntries_1_1.done; pivotTableEntries_1_1 = pivotTableEntries_1.next()) {
537
+ tableEntry = pivotTableEntries_1_1.value;
538
+ files[tableEntry.path] = encodeXml(tableEntry.xml);
539
+ }
540
+ }
541
+ catch (e_12_1) { e_12 = { error: e_12_1 }; }
542
+ finally {
543
+ try {
544
+ if (pivotTableEntries_1_1 && !pivotTableEntries_1_1.done && (_w = pivotTableEntries_1.return)) _w.call(pivotTableEntries_1);
545
+ }
546
+ finally { if (e_12) throw e_12.error; }
547
+ }
548
+ try {
549
+ for (pivotTableRelsEntries_1 = __values(pivotTableRelsEntries), pivotTableRelsEntries_1_1 = pivotTableRelsEntries_1.next(); !pivotTableRelsEntries_1_1.done; pivotTableRelsEntries_1_1 = pivotTableRelsEntries_1.next()) {
550
+ tableRels = pivotTableRelsEntries_1_1.value;
551
+ files[tableRels.path] = encodeXml(tableRels.xml);
552
+ }
553
+ }
554
+ catch (e_13_1) { e_13 = { error: e_13_1 }; }
555
+ finally {
556
+ try {
557
+ if (pivotTableRelsEntries_1_1 && !pivotTableRelsEntries_1_1.done && (_x = pivotTableRelsEntries_1.return)) _x.call(pivotTableRelsEntries_1);
558
+ }
559
+ finally { if (e_13) throw e_13.error; }
560
+ }
561
+ // Add external link files (for formulas referencing other workbooks)
562
+ for (i = 0; i < externalLinks.length; i++) {
563
+ link = externalLinks[i];
564
+ linkPath = "xl/externalLinks/externalLink".concat(i + 1, ".xml");
565
+ files[linkPath] = encodeXml(link.xmlContent);
566
+ // Add the relationship file if present
567
+ if (link.relsContent) {
568
+ relsPath = "xl/externalLinks/_rels/externalLink".concat(i + 1, ".xml.rels");
569
+ files[relsPath] = encodeXml(link.relsContent);
570
+ }
571
+ }
572
+ commentsSheets = worksheetEntries
573
+ .filter(function (entry) { return entry.commentsXml; })
574
+ .map(function (entry) { var _a; return (_a = entry.sheet.sheetId) !== null && _a !== void 0 ? _a : entry.index + 1; });
575
+ threadedCommentsSheets = worksheetEntries
576
+ .filter(function (entry) { return entry.threadedCommentsXml; })
577
+ .map(function (entry) { var _a; return (_a = entry.sheet.sheetId) !== null && _a !== void 0 ? _a : entry.index + 1; });
578
+ contentTypesXml = buildContentTypesXml({
579
+ sheetCount: worksheetEntries.length,
580
+ tableCount: preparedTables.length,
581
+ drawingSheets: drawingSheets,
582
+ mediaExtensions: Array.from(imageExtensions),
583
+ chartCount: chartEntries.length,
584
+ slicerCount: slicerEntries.length,
585
+ slicerCacheCount: slicerCacheEntries.length,
586
+ pivotTableCount: pivotTableEntries.length,
587
+ pivotCacheCount: pivotCacheEntries.length,
588
+ commentsSheets: commentsSheets,
589
+ threadedCommentsSheets: threadedCommentsSheets,
590
+ hasPersons: !personRegistry.isEmpty(),
591
+ externalLinkCount: externalLinks.length,
592
+ });
593
+ files["[Content_Types].xml"] = encodeXml(contentTypesXml);
594
+ // Preserved Power Query machinery (DataMashup customXml, connections.xml, queryTable parts) is
595
+ // re-emitted verbatim as a post-pass over the assembled files, re-attaching each queryTable to
596
+ // its regenerated table part when the table still matches. No-op without an envelope.
597
+ applyPowerQueryParts(files, powerQuery);
598
+ zipBytes = zipSync(files);
599
+ if (password === null || password === void 0 ? void 0 : password.trim()) {
600
+ return [2 /*return*/, CFBEncryptor.encrypt(zipBytes, password.trim())];
601
+ }
602
+ return [2 /*return*/, zipBytes];
603
+ }
604
+ });
605
+ }); };
606
+ var XML_DECLARATION = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
607
+ var WORKSHEET_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
608
+ var REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
609
+ var PACKAGE_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships";
610
+ var DEFAULT_PAGE_MARGINS = '<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>';
611
+ var TABLE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/table";
612
+ var DRAWING_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing";
613
+ var IMAGE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
614
+ var CHART_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart";
615
+ var SLICER_REL_TYPE = "http://schemas.microsoft.com/office/2007/relationships/slicer";
616
+ var SLICER_CACHE_REL_TYPE = "http://schemas.microsoft.com/office/2007/relationships/slicerCache";
617
+ // Phase D2 — XLSX pivot relationship types (ECMA-376).
618
+ var PIVOT_TABLE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotTable";
619
+ var PIVOT_CACHE_DEFINITION_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition";
620
+ var HYPERLINK_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
621
+ var COMMENTS_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
622
+ var EMUS_PER_PIXEL = 9525;
623
+ var CREATOR = "Rows n Columns";
624
+ var textEncoder = new TextEncoder();
625
+ var RelationshipsBuilder = /** @class */ (function () {
626
+ function RelationshipsBuilder() {
627
+ this.nextId = 1;
628
+ this.entries = [];
629
+ }
630
+ RelationshipsBuilder.prototype.add = function (type, target, mode) {
631
+ var id = "rId".concat(this.nextId++);
632
+ this.entries.push({ id: id, type: type, target: target, mode: mode });
633
+ return id;
634
+ };
635
+ RelationshipsBuilder.prototype.isEmpty = function () {
636
+ return this.entries.length === 0;
637
+ };
638
+ RelationshipsBuilder.prototype.toXml = function () {
639
+ if (!this.entries.length) {
640
+ return undefined;
641
+ }
642
+ var relationships = this.entries
643
+ .map(function (entry) {
644
+ return "<Relationship Id=\"".concat(entry.id, "\" Type=\"").concat(entry.type, "\" Target=\"").concat(escapeXmlAttr(entry.target), "\"").concat(entry.mode ? " TargetMode=\"".concat(entry.mode, "\"") : "", "/>");
645
+ })
646
+ .join("");
647
+ return "".concat(XML_DECLARATION, "<Relationships xmlns=\"").concat(PACKAGE_REL_NS, "\">").concat(relationships, "</Relationships>");
648
+ };
649
+ return RelationshipsBuilder;
650
+ }());
651
+ var DrawingContext = /** @class */ (function () {
652
+ function DrawingContext(relationships, target, hasExisting) {
653
+ this.relationships = relationships;
654
+ this.target = target;
655
+ if (hasExisting) {
656
+ this.relId = this.relationships.add(DRAWING_REL_TYPE, this.target);
657
+ }
658
+ }
659
+ DrawingContext.prototype.ensureRel = function () {
660
+ if (!this.relId) {
661
+ this.relId = this.relationships.add(DRAWING_REL_TYPE, this.target);
662
+ }
663
+ return this.relId;
664
+ };
665
+ DrawingContext.prototype.hasDrawing = function () {
666
+ return !!this.relId;
667
+ };
668
+ return DrawingContext;
669
+ }());
670
+ var SQREF_A1_RANGE = /^\$?([A-Z]+)\$?(\d+)(?::\$?([A-Z]+)\$?(\d+))?$/;
671
+ var sqrefColNumber = function (letters) {
672
+ return letters.split("").reduce(function (acc, ch) { return acc * 26 + (ch.charCodeAt(0) - 64); }, 0);
673
+ };
674
+ /**
675
+ * Normalize a dataValidation sqref list: collapse degenerate ranges
676
+ * (`C7:C7` → `C7`), drop exact duplicates, and drop members fully contained
677
+ * in another member. The collector receives both range-form refs and
678
+ * per-cell addresses for the same rule, which otherwise emits noisy
679
+ * `sqref="C7:C7 C8:C8 C7 C8"` lists.
680
+ */
681
+ export var normalizeSqrefMembers = function (refs) {
682
+ var parsed = refs.map(function (raw) {
683
+ var m = SQREF_A1_RANGE.exec(raw);
684
+ if (!m)
685
+ return { ref: raw };
686
+ var c1 = sqrefColNumber(m[1]);
687
+ var r1 = Number(m[2]);
688
+ var c2 = m[3] ? sqrefColNumber(m[3]) : c1;
689
+ var r2 = m[4] ? Number(m[4]) : r1;
690
+ var rect = {
691
+ c1: Math.min(c1, c2),
692
+ r1: Math.min(r1, r2),
693
+ c2: Math.max(c1, c2),
694
+ r2: Math.max(r1, r2),
695
+ };
696
+ var ref = rect.c1 === rect.c2 && rect.r1 === rect.r2
697
+ ? "".concat(m[1]).concat(m[2])
698
+ : raw;
699
+ return { ref: ref, rect: rect };
700
+ });
701
+ var contains = function (a, b) {
702
+ return a.c1 <= b.c1 && a.r1 <= b.r1 && a.c2 >= b.c2 && a.r2 >= b.r2;
703
+ };
704
+ var out = [];
705
+ var seen = new Set();
706
+ var _loop_2 = function (i) {
707
+ var _a = parsed[i], ref = _a.ref, rect = _a.rect;
708
+ if (seen.has(ref))
709
+ return "continue";
710
+ if (rect) {
711
+ var covered = parsed.some(function (other, j) {
712
+ return j !== i &&
713
+ other.rect &&
714
+ contains(other.rect, rect) &&
715
+ // ties (identical rects) keep the earliest occurrence only
716
+ !(contains(rect, other.rect) && j > i);
717
+ });
718
+ if (covered)
719
+ return "continue";
720
+ }
721
+ seen.add(ref);
722
+ out.push(ref);
723
+ };
724
+ for (var i = 0; i < parsed.length; i++) {
725
+ _loop_2(i);
726
+ }
727
+ return out;
728
+ };
729
+ var DataValidationCollector = /** @class */ (function () {
730
+ function DataValidationCollector() {
731
+ this.entries = new Map();
732
+ }
733
+ DataValidationCollector.prototype.add = function (address, rule) {
734
+ var config = convertDataValidationRule(rule);
735
+ if (!config)
736
+ return;
737
+ var key = getDataValidationKey(config);
738
+ var existing = this.entries.get(key);
739
+ if (existing) {
740
+ existing.refs.push(address);
741
+ return;
742
+ }
743
+ this.entries.set(key, {
744
+ config: config,
745
+ refs: [address],
746
+ });
747
+ };
748
+ DataValidationCollector.prototype.toXml = function () {
749
+ if (!this.entries.size) {
750
+ return "";
751
+ }
752
+ var items = Array.from(this.entries.values()).map(function (entry) {
753
+ return buildDataValidationXml(entry.config, entry.refs);
754
+ });
755
+ return "<dataValidations count=\"".concat(this.entries.size, "\">").concat(items.join(""), "</dataValidations>");
756
+ };
757
+ return DataValidationCollector;
758
+ }());
759
+ var CommentsCollector = /** @class */ (function () {
760
+ function CommentsCollector() {
761
+ this.entries = [];
762
+ }
763
+ CommentsCollector.prototype.add = function (address, text, author) {
764
+ if (author === void 0) { author = "System"; }
765
+ this.entries.push({ address: address, text: text, author: author });
766
+ };
767
+ CommentsCollector.prototype.isEmpty = function () {
768
+ return this.entries.length === 0;
769
+ };
770
+ CommentsCollector.prototype.toXml = function () {
771
+ if (!this.entries.length) {
772
+ return undefined;
773
+ }
774
+ var authors = Array.from(new Set(this.entries.map(function (e) { return e.author; })));
775
+ var authorsXml = authors
776
+ .map(function (a) { return "<author>".concat(escapeXmlText(a), "</author>"); })
777
+ .join("");
778
+ var commentsXml = this.entries
779
+ .map(function (entry) {
780
+ var authorId = authors.indexOf(entry.author);
781
+ return "<comment ref=\"".concat(entry.address, "\" authorId=\"").concat(authorId, "\"><text><r><rPr><b/><sz val=\"9\"/><color indexed=\"81\"/><rFont val=\"Tahoma\"/><charset val=\"1\"/></rPr><t>").concat(escapeXmlText(entry.text), "</t></r></text></comment>");
782
+ })
783
+ .join("");
784
+ return "".concat(XML_DECLARATION, "<comments xmlns=\"").concat(WORKSHEET_NS, "\"><authors>").concat(authorsXml, "</authors><commentList>").concat(commentsXml, "</commentList></comments>");
785
+ };
786
+ CommentsCollector.prototype.toVmlXml = function () {
787
+ if (!this.entries.length) {
788
+ return undefined;
789
+ }
790
+ var shapes = this.entries
791
+ .map(function (entry, index) {
792
+ var shapeId = "_x0000_s".concat(1026 + index);
793
+ // Parse cell address to get row and column
794
+ var match = entry.address.match(/^([A-Z]+)(\d+)$/);
795
+ if (!match)
796
+ return "";
797
+ var col = match[1];
798
+ var row = parseInt(match[2]);
799
+ var colIndex = col
800
+ .split("")
801
+ .reduce(function (acc, char) { return acc * 26 + (char.charCodeAt(0) - 64); }, 0) - 1;
802
+ return "<v:shape id=\"".concat(shapeId, "\" type=\"#_x0000_t202\" style='position:absolute;margin-left:59.25pt;margin-top:1.5pt;width:108pt;height:59.25pt;z-index:").concat(index + 1, ";visibility:hidden' fillcolor=\"#ffffe1\" o:insetmode=\"auto\"><v:fill color2=\"#ffffe1\"/><v:shadow on=\"t\" color=\"black\" obscured=\"t\"/><v:path o:connecttype=\"none\"/><v:textbox style='mso-direction-alt:auto'><div style='text-align:left'></div></v:textbox><x:ClientData ObjectType=\"Note\"><x:MoveWithCells/><x:SizeWithCells/><x:Anchor>1, 15, 0, 2, 3, 15, 3, 16</x:Anchor><x:AutoFill>False</x:AutoFill><x:Row>").concat(row - 1, "</x:Row><x:Column>").concat(colIndex, "</x:Column></x:ClientData></v:shape>");
803
+ })
804
+ .join("");
805
+ return "<xml xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"><o:shapelayout v:ext=\"edit\"><o:idmap v:ext=\"edit\" data=\"1\"/></o:shapelayout><v:shapetype id=\"_x0000_t202\" coordsize=\"21600,21600\" o:spt=\"202\" path=\"m,l,21600r21600,l21600,xe\"><v:stroke joinstyle=\"miter\"/><v:path gradientshapeok=\"t\" o:connecttype=\"rect\"/></v:shapetype>".concat(shapes, "</xml>");
806
+ };
807
+ return CommentsCollector;
808
+ }());
809
+ var INVALID_XML_CHAR_REGEX = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g;
810
+ var sanitizeXmlText = function (value) {
811
+ if (!value)
812
+ return value;
813
+ return value.replace(INVALID_XML_CHAR_REGEX, "");
814
+ };
815
+ var SharedStrings = /** @class */ (function () {
816
+ function SharedStrings() {
817
+ this.plainIndex = new Map();
818
+ this.entries = [];
819
+ this.totalCount = 0;
820
+ }
821
+ Object.defineProperty(SharedStrings.prototype, "values", {
822
+ /**
823
+ * Compatibility shim: existing callers iterate `sharedStrings.values`
824
+ * (a `string[]`). Plain entries surface their text; rich entries
825
+ * surface the concatenated text so existing consumers still see a
826
+ * sensible plain string.
827
+ */
828
+ get: function () {
829
+ return this.entries.map(function (e) { return e.text; });
830
+ },
831
+ enumerable: false,
832
+ configurable: true
833
+ });
834
+ SharedStrings.prototype.add = function (value) {
835
+ var normalized = sanitizeXmlText(value !== null && value !== void 0 ? value : "");
836
+ var existing = this.plainIndex.get(normalized);
837
+ this.totalCount += 1;
838
+ if (typeof existing === "number") {
839
+ return existing;
840
+ }
841
+ var nextIndex = this.entries.length;
842
+ this.plainIndex.set(normalized, nextIndex);
843
+ this.entries.push({ kind: "plain", text: normalized });
844
+ return nextIndex;
845
+ };
846
+ /**
847
+ * Reserve a fresh sharedStrings slot carrying per-segment runs. Skips
848
+ * dedup so two cells with the same plain text but different runs get
849
+ * separate slots.
850
+ */
851
+ SharedStrings.prototype.addRich = function (value, runs) {
852
+ var normalized = sanitizeXmlText(value !== null && value !== void 0 ? value : "");
853
+ this.totalCount += 1;
854
+ var nextIndex = this.entries.length;
855
+ this.entries.push({ kind: "rich", text: normalized, runs: runs });
856
+ return nextIndex;
857
+ };
858
+ return SharedStrings;
859
+ }());
860
+ var encodeXml = function (content) { return textEncoder.encode(content); };
861
+ var getRowsForSheet = function (sheetData, sheetId) {
862
+ var _a, _b, _d;
863
+ return ((_d = (_b = (_a = sheetData[sheetId]) !== null && _a !== void 0 ? _a : sheetData[String(sheetId)]) !== null && _b !== void 0 ? _b : sheetData[Number(sheetId)]) !== null && _d !== void 0 ? _d : []);
864
+ };
865
+ var buildWorksheetXml = function (_a) {
866
+ var e_19, _b, e_20, _d, e_21, _e, e_22, _f, e_23, _g, e_24, _h;
867
+ var _j, _k;
868
+ var sheet = _a.sheet, rows = _a.rows, sharedStrings = _a.sharedStrings, sourceSharedStrings = _a.sourceSharedStrings, cellXfs = _a.cellXfs, styleBuilder = _a.styleBuilder, tables = _a.tables, relationships = _a.relationships, drawingContext = _a.drawingContext, conditionalFormats = _a.conditionalFormats, dataValidationsById = _a.dataValidationsById, dataValidations = _a.dataValidations, ignoreFormulaPatterns = _a.ignoreFormulaPatterns, citations = _a.citations, comments = _a.comments, personRegistry = _a.personRegistry, slicerRelIds = _a.slicerRelIds, sheetData = _a.sheetData, sheets = _a.sheets, locale = _a.locale;
869
+ var tableNameMap = buildTableNameMap(tables);
870
+ var bounds = {
871
+ minRow: Number.POSITIVE_INFINITY,
872
+ maxRow: 0,
873
+ minColumn: Number.POSITIVE_INFINITY,
874
+ maxColumn: 0,
875
+ };
876
+ var rowMetadata = (_j = sheet.rowMetadata) !== null && _j !== void 0 ? _j : [];
877
+ var maxRows = Math.max(rows.length, rowMetadata.length);
878
+ var defaultRowHeightPx = getDefaultRowHeightPx(sheet);
879
+ var rowXmlChunks = [];
880
+ var collectedImages = [];
881
+ var dataValidationCollector = new DataValidationCollector();
882
+ var hyperlinkEntries = [];
883
+ var commentsCollector = new CommentsCollector();
884
+ var threadedCommentsCollector = new ThreadedCommentsCollector(comments, personRegistry !== null && personRegistry !== void 0 ? personRegistry : new PersonRegistry());
885
+ // Process citations for this sheet
886
+ if (citations) {
887
+ try {
888
+ for (var citations_1 = __values(citations), citations_1_1 = citations_1.next(); !citations_1_1.done; citations_1_1 = citations_1.next()) {
889
+ var citation = citations_1_1.value;
890
+ if (citation.range.sheetId !== sheet.sheetId)
891
+ continue;
892
+ // Citation ranges are worksheet-based (1-based).
893
+ for (var rowIndex = citation.range.startRowIndex; rowIndex <= citation.range.endRowIndex; rowIndex++) {
894
+ for (var colIndex = citation.range.startColumnIndex; colIndex <= citation.range.endColumnIndex; colIndex++) {
895
+ var address = cellToAddress({ rowIndex: rowIndex, columnIndex: colIndex });
896
+ if (address) {
897
+ commentsCollector.add(address, "".concat(citation.citation_string), citation.created_by || "System");
898
+ }
899
+ }
900
+ }
901
+ }
902
+ }
903
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
904
+ finally {
905
+ try {
906
+ if (citations_1_1 && !citations_1_1.done && (_b = citations_1.return)) _b.call(citations_1);
907
+ }
908
+ finally { if (e_19) throw e_19.error; }
909
+ }
910
+ }
911
+ if (dataValidations) {
912
+ try {
913
+ for (var dataValidations_1 = __values(dataValidations), dataValidations_1_1 = dataValidations_1.next(); !dataValidations_1_1.done; dataValidations_1_1 = dataValidations_1.next()) {
914
+ var rule = dataValidations_1_1.value;
915
+ if (!rule.ranges)
916
+ continue;
917
+ try {
918
+ for (var _l = (e_21 = void 0, __values(rule.ranges)), _m = _l.next(); !_m.done; _m = _l.next()) {
919
+ var range = _m.value;
920
+ if (range.sheetId !== sheet.sheetId)
921
+ continue;
922
+ // Ranges from the DV import are already 1-indexed (addressToSelection
923
+ // produces 1-indexed coords). cellRangeToAddress also expects
924
+ // 1-indexed input, so pass through verbatim. The previous `+1` on
925
+ // every coordinate produced sqrefs shifted by one row + one column.
926
+ var address = cellRangeToAddress(undefined, range);
927
+ if (address) {
928
+ dataValidationCollector.add(address, rule);
929
+ }
930
+ }
931
+ }
932
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
933
+ finally {
934
+ try {
935
+ if (_m && !_m.done && (_e = _l.return)) _e.call(_l);
936
+ }
937
+ finally { if (e_21) throw e_21.error; }
938
+ }
939
+ }
940
+ }
941
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
942
+ finally {
943
+ try {
944
+ if (dataValidations_1_1 && !dataValidations_1_1.done && (_d = dataValidations_1.return)) _d.call(dataValidations_1);
945
+ }
946
+ finally { if (e_20) throw e_20.error; }
947
+ }
948
+ }
949
+ // Pre-scan for valid shared-formula leaders in this sheet. The cell-emit
950
+ // path uses this set to decide whether a follower (`sf.si` without `ref`)
951
+ // can safely emit as `<f t="shared" si="N"/>` or must fall back to its
952
+ // expanded standalone formula. A follower's leader can be missing if:
953
+ // (a) the user edited the leader (its `sf` was dropped by
954
+ // `setFormulaValue`'s invalidation), or
955
+ // (b) the source had a malformed reference and the leader never imported.
956
+ // Emitting an orphaned follower would produce a broken xlsx — Excel would
957
+ // see `<f t="shared" si="N"/>` with no corresponding leader and read the
958
+ // cell as having no formula at all.
959
+ var validSharedFormulaLeaders = new Set();
960
+ for (var rowIndex = 1; rowIndex < maxRows; rowIndex++) {
961
+ var row = rows[rowIndex];
962
+ var rowValues = row === null || row === void 0 ? void 0 : row.values;
963
+ if (!Array.isArray(rowValues))
964
+ continue;
965
+ try {
966
+ for (var rowValues_1 = (e_22 = void 0, __values(rowValues)), rowValues_1_1 = rowValues_1.next(); !rowValues_1_1.done; rowValues_1_1 = rowValues_1.next()) {
967
+ var cell = rowValues_1_1.value;
968
+ var sf = cell === null || cell === void 0 ? void 0 : cell.sf;
969
+ if (sf && sf.ref && Number.isFinite(sf.si)) {
970
+ validSharedFormulaLeaders.add(sf.si);
971
+ }
972
+ }
973
+ }
974
+ catch (e_22_1) { e_22 = { error: e_22_1 }; }
975
+ finally {
976
+ try {
977
+ if (rowValues_1_1 && !rowValues_1_1.done && (_f = rowValues_1.return)) _f.call(rowValues_1);
978
+ }
979
+ finally { if (e_22) throw e_22.error; }
980
+ }
981
+ }
982
+ for (var rowIndex = 1; rowIndex < maxRows; rowIndex++) {
983
+ var row = rows[rowIndex];
984
+ var metadata = rowMetadata[rowIndex];
985
+ var result = buildWorksheetRow({
986
+ rowNumber: rowIndex,
987
+ row: row,
988
+ rowMetadata: metadata,
989
+ defaultRowHeightPx: defaultRowHeightPx,
990
+ sharedStrings: sharedStrings,
991
+ sourceSharedStrings: sourceSharedStrings,
992
+ cellXfs: cellXfs,
993
+ styleBuilder: styleBuilder,
994
+ dataValidationsById: dataValidationsById,
995
+ tableNameMap: tableNameMap,
996
+ tables: tables,
997
+ ignoreFormulaPatterns: ignoreFormulaPatterns,
998
+ commentsCollector: commentsCollector,
999
+ sheetId: sheet.sheetId,
1000
+ sheetData: sheetData,
1001
+ sheets: sheets,
1002
+ locale: locale,
1003
+ validSharedFormulaLeaders: validSharedFormulaLeaders,
1004
+ onImage: function (image) {
1005
+ collectedImages.push(image);
1006
+ drawingContext.ensureRel();
1007
+ },
1008
+ onHyperlink: function (entry) {
1009
+ hyperlinkEntries.push(entry);
1010
+ },
1011
+ onDataValidation: function (entry) {
1012
+ dataValidationCollector.add(entry.address, entry.rule);
1013
+ },
1014
+ onCommentThread: function (address, threadId) {
1015
+ threadedCommentsCollector.addCell(address, threadId);
1016
+ },
1017
+ });
1018
+ if (!result)
1019
+ continue;
1020
+ rowXmlChunks.push(result.xml);
1021
+ if (result.minColumn) {
1022
+ bounds.minColumn = Math.min(bounds.minColumn, result.minColumn);
1023
+ }
1024
+ if (result.maxColumn) {
1025
+ bounds.maxColumn = Math.max(bounds.maxColumn, result.maxColumn);
1026
+ }
1027
+ bounds.minRow = Math.min(bounds.minRow, rowIndex);
1028
+ bounds.maxRow = Math.max(bounds.maxRow, rowIndex);
1029
+ }
1030
+ var merges = normalizeMergeRanges((_k = sheet.merges) !== null && _k !== void 0 ? _k : []).map(function (range) {
1031
+ bounds.minRow = Math.min(bounds.minRow, range.startRowIndex);
1032
+ bounds.maxRow = Math.max(bounds.maxRow, range.endRowIndex);
1033
+ bounds.minColumn = Math.min(bounds.minColumn, range.startColumnIndex);
1034
+ bounds.maxColumn = Math.max(bounds.maxColumn, range.endColumnIndex);
1035
+ return cellRangeToAddress(undefined, range);
1036
+ });
1037
+ var dimension = buildDimension(bounds);
1038
+ var sheetViews = buildSheetViewsXml(sheet);
1039
+ var sheetPrXml = buildSheetPropertiesXml(sheet);
1040
+ var columnXml = buildColumnsXml(sheet, bounds);
1041
+ var mergeXml = merges.length
1042
+ ? "<mergeCells count=\"".concat(merges.length, "\">").concat(merges
1043
+ .map(function (ref) { return "<mergeCell ref=\"".concat(ref, "\"/>"); })
1044
+ .join(""), "</mergeCells>")
1045
+ : "";
1046
+ var basicFilterXml = buildWorksheetAutoFilterXml(sheet, rows, styleBuilder);
1047
+ var dataValidationsXml = dataValidationCollector.toXml();
1048
+ var hyperlinksXml = buildHyperlinksXml(hyperlinkEntries, relationships);
1049
+ var conditionalFormattingXml = buildConditionalFormattingXml({
1050
+ sheetId: sheet.sheetId,
1051
+ conditionalFormats: conditionalFormats,
1052
+ styleBuilder: styleBuilder,
1053
+ });
1054
+ var tablePartsXml = buildTablePartsXml(tables, relationships);
1055
+ var drawingXml = drawingContext.hasDrawing()
1056
+ ? "<drawing r:id=\"".concat(drawingContext.relId, "\"/>")
1057
+ : "";
1058
+ // Threaded comments (Excel's "Comments"). Build the modern part, then push
1059
+ // each thread's down-level mirror into the legacy notes collector so the
1060
+ // comments part + VML + relationships below cover both. Order matters: feed
1061
+ // the mirror BEFORE serializing commentsCollector.
1062
+ var threadedCommentsXml = threadedCommentsCollector.toXml();
1063
+ if (threadedCommentsXml) {
1064
+ try {
1065
+ for (var _o = __values(threadedCommentsCollector.legacyEntries()), _p = _o.next(); !_p.done; _p = _o.next()) {
1066
+ var entry = _p.value;
1067
+ commentsCollector.add(entry.address, entry.text, entry.author);
1068
+ }
1069
+ }
1070
+ catch (e_23_1) { e_23 = { error: e_23_1 }; }
1071
+ finally {
1072
+ try {
1073
+ if (_p && !_p.done && (_g = _o.return)) _g.call(_o);
1074
+ }
1075
+ finally { if (e_23) throw e_23.error; }
1076
+ }
1077
+ relationships.add(THREADED_COMMENT_REL_TYPE, "../threadedComments/threadedComment".concat(sheet.sheetId, ".xml"));
1078
+ }
1079
+ // Generate comments XML (notes) and add relationships if there are comments
1080
+ var commentsXml = commentsCollector.toXml();
1081
+ var legacyDrawingXml = "";
1082
+ if (commentsXml) {
1083
+ relationships.add(COMMENTS_REL_TYPE, "../comments".concat(sheet.sheetId, ".xml"));
1084
+ var legacyDrawingRelId = relationships.add("http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing", "../drawings/vmlDrawing".concat(sheet.sheetId, ".vml"));
1085
+ legacyDrawingXml = "<legacyDrawing r:id=\"".concat(legacyDrawingRelId, "\"/>");
1086
+ }
1087
+ var sheetDataXml = "<sheetData>".concat(rowXmlChunks.join(""), "</sheetData>");
1088
+ var pageMargins = DEFAULT_PAGE_MARGINS;
1089
+ // Build row data map for sparkline detection
1090
+ var rowDataMap = {};
1091
+ for (var rowIndex = 1; rowIndex < maxRows; rowIndex++) {
1092
+ var row = rows[rowIndex];
1093
+ if (row === null || row === void 0 ? void 0 : row.values) {
1094
+ var rowValues = {};
1095
+ try {
1096
+ for (var _q = (e_24 = void 0, __values(Object.entries(row.values))), _s = _q.next(); !_s.done; _s = _q.next()) {
1097
+ var _t = __read(_s.value, 2), colIndex = _t[0], cell = _t[1];
1098
+ if (cell) {
1099
+ rowValues[parseInt(colIndex, 10)] = cell;
1100
+ }
1101
+ }
1102
+ }
1103
+ catch (e_24_1) { e_24 = { error: e_24_1 }; }
1104
+ finally {
1105
+ try {
1106
+ if (_s && !_s.done && (_h = _q.return)) _h.call(_q);
1107
+ }
1108
+ finally { if (e_24) throw e_24.error; }
1109
+ }
1110
+ if (Object.keys(rowValues).length > 0) {
1111
+ rowDataMap[rowIndex] = rowValues;
1112
+ }
1113
+ }
1114
+ }
1115
+ // Build sparkline XML from SPARKLINE formulas
1116
+ var sparklineXml = buildSparklineGroupsXml(sheet, rowDataMap);
1117
+ // Build combined extLst with sparklines and slicers
1118
+ var extLstXml = buildWorksheetExtLstXml(sparklineXml, slicerRelIds !== null && slicerRelIds !== void 0 ? slicerRelIds : []);
1119
+ var defaultRowHeightPt = pixelToPoints(getDefaultRowHeightPx(sheet));
1120
+ // Only emit ``defaultColWidth`` when the sheet has an explicit
1121
+ // workbook-level override. Emitting the engine's internal default for
1122
+ // every export forces Excel to use that value as the workbook default,
1123
+ // overriding the user's "Default Width" preference and producing
1124
+ // visibly narrower / wider columns than untouched openpyxl output.
1125
+ var explicitDefaultColumnWidthPx = sheet === null || sheet === void 0 ? void 0 : sheet.defaultColumnWidth;
1126
+ var sheetFormatPrAttrs = ["defaultRowHeight=\"".concat(defaultRowHeightPt, "\"")];
1127
+ if (typeof explicitDefaultColumnWidthPx === "number" &&
1128
+ explicitDefaultColumnWidthPx > 0) {
1129
+ sheetFormatPrAttrs.push("defaultColWidth=\"".concat(columnPixelToChars(explicitDefaultColumnWidthPx).toFixed(2), "\""));
1130
+ }
1131
+ var worksheetXml = "".concat(XML_DECLARATION, "<worksheet xmlns=\"").concat(WORKSHEET_NS, "\" xmlns:r=\"").concat(REL_NS, "\">").concat(sheetPrXml, "<dimension ref=\"").concat(dimension, "\"/>").concat(sheetViews, "<sheetFormatPr ").concat(sheetFormatPrAttrs.join(" "), "/>").concat(columnXml).concat(sheetDataXml).concat(basicFilterXml).concat(mergeXml).concat(conditionalFormattingXml).concat(dataValidationsXml).concat(hyperlinksXml).concat(pageMargins).concat(drawingXml).concat(legacyDrawingXml).concat(tablePartsXml).concat(extLstXml, "</worksheet>");
1132
+ return {
1133
+ xml: worksheetXml,
1134
+ relationshipsXml: relationships.toXml(),
1135
+ images: collectedImages,
1136
+ commentsXml: commentsXml,
1137
+ vmlDrawingXml: commentsCollector.toVmlXml(),
1138
+ threadedCommentsXml: threadedCommentsXml,
1139
+ };
1140
+ };
1141
+ /**
1142
+ * Build combined extLst XML for worksheet (sparklines + slicers)
1143
+ */
1144
+ var buildWorksheetExtLstXml = function (sparklineExtXml, slicerRelIds) {
1145
+ var parts = [];
1146
+ // Add sparkline ext if present
1147
+ if (sparklineExtXml) {
1148
+ parts.push(sparklineExtXml);
1149
+ }
1150
+ // Add slicer ext if present
1151
+ if (slicerRelIds.length > 0) {
1152
+ var slicersXml = slicerRelIds
1153
+ .map(function (relId) { return "<x14:slicer r:id=\"".concat(relId, "\"/>"); })
1154
+ .join("");
1155
+ parts.push("<ext uri=\"{3A4CF648-6AED-40f4-86FF-DC5316D8AED3}\" xmlns:x15=\"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main\"><x14:slicerList xmlns:x14=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main\">".concat(slicersXml, "</x14:slicerList></ext>"));
1156
+ }
1157
+ if (parts.length === 0) {
1158
+ return "";
1159
+ }
1160
+ return "<extLst>".concat(parts.join(""), "</extLst>");
1161
+ };
1162
+ var sanitizeMergeRange = function (range) {
1163
+ var startRow = sanitizeIndex(range === null || range === void 0 ? void 0 : range.startRowIndex);
1164
+ var endRow = sanitizeIndex(range === null || range === void 0 ? void 0 : range.endRowIndex);
1165
+ var startColumn = sanitizeIndex(range === null || range === void 0 ? void 0 : range.startColumnIndex);
1166
+ var endColumn = sanitizeIndex(range === null || range === void 0 ? void 0 : range.endColumnIndex);
1167
+ if (startRow == null ||
1168
+ endRow == null ||
1169
+ startColumn == null ||
1170
+ endColumn == null) {
1171
+ return null;
1172
+ }
1173
+ if (startRow > endRow || startColumn > endColumn) {
1174
+ return null;
1175
+ }
1176
+ if (startRow === endRow && startColumn === endColumn) {
1177
+ return null;
1178
+ }
1179
+ return {
1180
+ startRowIndex: startRow,
1181
+ endRowIndex: endRow,
1182
+ startColumnIndex: startColumn,
1183
+ endColumnIndex: endColumn,
1184
+ };
1185
+ };
1186
+ var sanitizeIndex = function (value) {
1187
+ if (typeof value !== "number" || !Number.isFinite(value))
1188
+ return null;
1189
+ return Math.max(1, Math.floor(value));
1190
+ };
1191
+ var normalizeMergeRanges = function (ranges) {
1192
+ var e_25, _a;
1193
+ if (!(ranges === null || ranges === void 0 ? void 0 : ranges.length))
1194
+ return [];
1195
+ var sanitized = ranges
1196
+ .map(function (range) { return sanitizeMergeRange(range); })
1197
+ .filter(function (range) { return Boolean(range); });
1198
+ if (!sanitized.length)
1199
+ return [];
1200
+ var sorted = sanitized.sort(function (a, b) {
1201
+ if (a.startRowIndex !== b.startRowIndex) {
1202
+ return a.startRowIndex - b.startRowIndex;
1203
+ }
1204
+ if (a.startColumnIndex !== b.startColumnIndex) {
1205
+ return a.startColumnIndex - b.startColumnIndex;
1206
+ }
1207
+ if (a.endRowIndex !== b.endRowIndex) {
1208
+ return b.endRowIndex - a.endRowIndex;
1209
+ }
1210
+ return b.endColumnIndex - a.endColumnIndex;
1211
+ });
1212
+ var valid = [];
1213
+ var active = [];
1214
+ var _loop_3 = function (merge) {
1215
+ if (active.length) {
1216
+ active = active.filter(function (entry) { return entry.endRowIndex >= merge.startRowIndex; });
1217
+ }
1218
+ var isContained = active.some(function (entry) {
1219
+ return entry.startColumnIndex <= merge.startColumnIndex &&
1220
+ entry.endColumnIndex >= merge.endColumnIndex &&
1221
+ entry.endRowIndex >= merge.endRowIndex;
1222
+ });
1223
+ if (!isContained) {
1224
+ valid.push(merge);
1225
+ active.push(merge);
1226
+ }
1227
+ };
1228
+ try {
1229
+ for (var sorted_1 = __values(sorted), sorted_1_1 = sorted_1.next(); !sorted_1_1.done; sorted_1_1 = sorted_1.next()) {
1230
+ var merge = sorted_1_1.value;
1231
+ _loop_3(merge);
1232
+ }
1233
+ }
1234
+ catch (e_25_1) { e_25 = { error: e_25_1 }; }
1235
+ finally {
1236
+ try {
1237
+ if (sorted_1_1 && !sorted_1_1.done && (_a = sorted_1.return)) _a.call(sorted_1);
1238
+ }
1239
+ finally { if (e_25) throw e_25.error; }
1240
+ }
1241
+ return valid;
1242
+ };
1243
+ var convertDataValidationRule = function (rule) {
1244
+ var _a, _b, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5;
1245
+ if (!rule)
1246
+ return undefined;
1247
+ var allowBlank = rule.allowBlank !== false;
1248
+ var alert = rule.alert;
1249
+ var inputMessage = rule.inputMessage;
1250
+ var baseConfig = {
1251
+ allowBlank: allowBlank,
1252
+ showInputMessage: Boolean((inputMessage === null || inputMessage === void 0 ? void 0 : inputMessage.message) || (inputMessage === null || inputMessage === void 0 ? void 0 : inputMessage.title)),
1253
+ showErrorMessage: Boolean(alert),
1254
+ errorStyle: alert === null || alert === void 0 ? void 0 : alert.style,
1255
+ errorTitle: (_b = (_a = alert === null || alert === void 0 ? void 0 : alert.message) === null || _a === void 0 ? void 0 : _a.title) !== null && _b !== void 0 ? _b : undefined,
1256
+ error: (_e = (_d = alert === null || alert === void 0 ? void 0 : alert.message) === null || _d === void 0 ? void 0 : _d.message) !== null && _e !== void 0 ? _e : undefined,
1257
+ promptTitle: (_f = inputMessage === null || inputMessage === void 0 ? void 0 : inputMessage.title) !== null && _f !== void 0 ? _f : undefined,
1258
+ prompt: (_g = inputMessage === null || inputMessage === void 0 ? void 0 : inputMessage.message) !== null && _g !== void 0 ? _g : undefined,
1259
+ };
1260
+ // Round-trip path: when the rule was imported from xlsx, replay the
1261
+ // verbatim source representation. Preserves type/operator/formulas
1262
+ // exactly, including `whole`/`textLength`/`time` types and user-written
1263
+ // custom formulas without `INDIRECT("RC",FALSE)` rewriting.
1264
+ var src = rule.xlsxSource;
1265
+ if (src && src.type && typeof src.formula1 === "string" && src.formula1) {
1266
+ return __assign({ type: src.type, operator: src.operator, formula1: src.formula1, formula2: src.formula2, showDropDown: src.type === "list" && rule.displayStyle === "plain" ? true : undefined }, baseConfig);
1267
+ }
1268
+ if (!((_h = rule.condition) === null || _h === void 0 ? void 0 : _h.type)) {
1269
+ // Prompt-only DV (no validation rule, just an input-message tooltip
1270
+ // and/or an error alert). Emit it with no type/formula so Excel still
1271
+ // shows the tooltip when the cell is selected.
1272
+ if (baseConfig.showInputMessage || baseConfig.showErrorMessage) {
1273
+ return baseConfig;
1274
+ }
1275
+ return undefined;
1276
+ }
1277
+ var condition = rule.condition;
1278
+ var values = (_j = condition.values) !== null && _j !== void 0 ? _j : [];
1279
+ var currentCell = 'INDIRECT("RC",FALSE)';
1280
+ var escapeFormulaText = function (value) { return value.replace(/"/g, '""'); };
1281
+ var ensureFormula = function (value) {
1282
+ return value.startsWith("=") ? value : "=".concat(value);
1283
+ };
1284
+ var ifErrorWrap = function (formula) { return "IFERROR(".concat(formula, ",TRUE)"); };
1285
+ if (condition.type === "ONE_OF_LIST") {
1286
+ var entries = values
1287
+ .map(function (value) { return value.userEnteredValue; })
1288
+ .filter(function (value) { return typeof value === "string"; });
1289
+ if (!entries.length)
1290
+ return undefined;
1291
+ var sanitized = entries.map(function (entry) { return entry.replace(/"/g, '""'); });
1292
+ return __assign({ type: "list", formula1: "\"".concat(sanitized.join(","), "\""), showDropDown: rule.displayStyle === "plain" ? true : undefined }, baseConfig);
1293
+ }
1294
+ if (condition.type === "ONE_OF_RANGE") {
1295
+ var references = values
1296
+ .map(function (value) { return value.userEnteredValue; })
1297
+ .filter(function (value) { return typeof value === "string"; });
1298
+ if (!references.length)
1299
+ return undefined;
1300
+ var formula1 = references.join(",");
1301
+ return __assign({ type: "list", formula1: formula1.startsWith("=") ? formula1 : "=".concat(formula1), showDropDown: rule.displayStyle === "plain" ? true : undefined }, baseConfig);
1302
+ }
1303
+ if (condition.type === "CUSTOM_FORMULA") {
1304
+ var raw = (_l = (_k = values[0]) === null || _k === void 0 ? void 0 : _k.userEnteredValue) !== null && _l !== void 0 ? _l : "";
1305
+ if (!raw)
1306
+ return undefined;
1307
+ return __assign({ type: "custom", formula1: ensureFormula(raw) }, baseConfig);
1308
+ }
1309
+ if (condition.type === "BOOLEAN") {
1310
+ return __assign({ type: "custom", formula1: "=OR(".concat(currentCell, "=TRUE,").concat(currentCell, "=FALSE)") }, baseConfig);
1311
+ }
1312
+ if (condition.type === "BLANK") {
1313
+ return __assign({ type: "custom", formula1: "=".concat(currentCell, "=\"\"") }, baseConfig);
1314
+ }
1315
+ if (condition.type === "NOT_BLANK") {
1316
+ return __assign({ type: "custom", formula1: "=".concat(currentCell, "<>\"\"") }, baseConfig);
1317
+ }
1318
+ if (condition.type === "TEXT_EQ" || condition.type === "TEXT_NOT_EQ") {
1319
+ var raw = (_o = (_m = values[0]) === null || _m === void 0 ? void 0 : _m.userEnteredValue) !== null && _o !== void 0 ? _o : "";
1320
+ if (!raw)
1321
+ return undefined;
1322
+ var op = condition.type === "TEXT_EQ" ? "=" : "<>";
1323
+ return __assign({ type: "custom", formula1: "=".concat(currentCell).concat(op, "\"").concat(escapeFormulaText(raw), "\"") }, baseConfig);
1324
+ }
1325
+ if (condition.type === "TEXT_CONTAINS") {
1326
+ var raw = (_q = (_p = values[0]) === null || _p === void 0 ? void 0 : _p.userEnteredValue) !== null && _q !== void 0 ? _q : "";
1327
+ if (!raw)
1328
+ return undefined;
1329
+ return __assign({ type: "custom", formula1: "=ISNUMBER(SEARCH(\"".concat(escapeFormulaText(raw), "\",").concat(currentCell, "))") }, baseConfig);
1330
+ }
1331
+ if (condition.type === "TEXT_NOT_CONTAINS") {
1332
+ var raw = (_t = (_s = values[0]) === null || _s === void 0 ? void 0 : _s.userEnteredValue) !== null && _t !== void 0 ? _t : "";
1333
+ if (!raw)
1334
+ return undefined;
1335
+ return __assign({ type: "custom", formula1: "=ISERROR(SEARCH(\"".concat(escapeFormulaText(raw), "\",").concat(currentCell, "))") }, baseConfig);
1336
+ }
1337
+ if (condition.type === "TEXT_STARTS_WITH") {
1338
+ var raw = (_v = (_u = values[0]) === null || _u === void 0 ? void 0 : _u.userEnteredValue) !== null && _v !== void 0 ? _v : "";
1339
+ if (!raw)
1340
+ return undefined;
1341
+ var text = escapeFormulaText(raw);
1342
+ return __assign({ type: "custom", formula1: "=LEFT(".concat(currentCell, ",LEN(\"").concat(text, "\"))=\"").concat(text, "\"") }, baseConfig);
1343
+ }
1344
+ if (condition.type === "TEXT_ENDS_WITH") {
1345
+ var raw = (_x = (_w = values[0]) === null || _w === void 0 ? void 0 : _w.userEnteredValue) !== null && _x !== void 0 ? _x : "";
1346
+ if (!raw)
1347
+ return undefined;
1348
+ var text = escapeFormulaText(raw);
1349
+ return __assign({ type: "custom", formula1: "=RIGHT(".concat(currentCell, ",LEN(\"").concat(text, "\"))=\"").concat(text, "\"") }, baseConfig);
1350
+ }
1351
+ if (condition.type === "TEXT_IS_EMAIL") {
1352
+ return __assign({ type: "custom", formula1: "=AND(ISNUMBER(SEARCH(\"@\",".concat(currentCell, ")),ISNUMBER(SEARCH(\".\",").concat(currentCell, ")))") }, baseConfig);
1353
+ }
1354
+ if (condition.type === "TEXT_IS_URL") {
1355
+ return __assign({ type: "custom", formula1: "=OR(LEFT(".concat(currentCell, ",7)=\"http://\",LEFT(").concat(currentCell, ",8)=\"https://\")") }, baseConfig);
1356
+ }
1357
+ if (condition.type === "NUMBER_BETWEEN" ||
1358
+ condition.type === "NUMBER_NOT_BETWEEN" ||
1359
+ condition.type === "NUMBER_EQ" ||
1360
+ condition.type === "NUMBER_NOT_EQ" ||
1361
+ condition.type === "NUMBER_GREATER" ||
1362
+ condition.type === "NUMBER_GREATER_THAN_EQ" ||
1363
+ condition.type === "NUMBER_LESS" ||
1364
+ condition.type === "NUMBER_LESS_THAN_EQ") {
1365
+ var first = (_z = (_y = values[0]) === null || _y === void 0 ? void 0 : _y.userEnteredValue) !== null && _z !== void 0 ? _z : "";
1366
+ if (!first)
1367
+ return undefined;
1368
+ var second = (_1 = (_0 = values[1]) === null || _0 === void 0 ? void 0 : _0.userEnteredValue) !== null && _1 !== void 0 ? _1 : "";
1369
+ var operatorMap = {
1370
+ NUMBER_BETWEEN: "between",
1371
+ NUMBER_NOT_BETWEEN: "notBetween",
1372
+ NUMBER_EQ: "equal",
1373
+ NUMBER_NOT_EQ: "notEqual",
1374
+ NUMBER_GREATER: "greaterThan",
1375
+ NUMBER_GREATER_THAN_EQ: "greaterThanOrEqual",
1376
+ NUMBER_LESS: "lessThan",
1377
+ NUMBER_LESS_THAN_EQ: "lessThanOrEqual",
1378
+ };
1379
+ return __assign({ type: "decimal", operator: operatorMap[condition.type], formula1: first, formula2: condition.type === "NUMBER_BETWEEN" ||
1380
+ condition.type === "NUMBER_NOT_BETWEEN"
1381
+ ? second
1382
+ : undefined }, baseConfig);
1383
+ }
1384
+ if (condition.type === "NUMBER_GREATER_THAN_PREVIOUS" ||
1385
+ condition.type === "NUMBER_GREATER_THAN_EQ_PREVIOUS" ||
1386
+ condition.type === "NUMBER_LESS_THAN_PREVIOUS" ||
1387
+ condition.type === "NUMBER_LESS_THAN_EQ_PREVIOUS") {
1388
+ var opMap = {
1389
+ NUMBER_GREATER_THAN_PREVIOUS: ">",
1390
+ NUMBER_GREATER_THAN_EQ_PREVIOUS: ">=",
1391
+ NUMBER_LESS_THAN_PREVIOUS: "<",
1392
+ NUMBER_LESS_THAN_EQ_PREVIOUS: "<=",
1393
+ };
1394
+ var op = opMap[condition.type];
1395
+ return __assign({ type: "custom", formula1: "=".concat(ifErrorWrap("".concat(currentCell).concat(op, "INDIRECT(\"R[-1]C\",FALSE)"))) }, baseConfig);
1396
+ }
1397
+ if (condition.type === "DATE_EQ" ||
1398
+ condition.type === "DATE_NOT_EQ" ||
1399
+ condition.type === "DATE_BEFORE" ||
1400
+ condition.type === "DATE_AFTER" ||
1401
+ condition.type === "DATE_ON_OR_BEFORE" ||
1402
+ condition.type === "DATE_ON_OR_AFTER" ||
1403
+ condition.type === "DATE_BETWEEN" ||
1404
+ condition.type === "DATE_NOT_BETWEEN") {
1405
+ var first = (_3 = (_2 = values[0]) === null || _2 === void 0 ? void 0 : _2.userEnteredValue) !== null && _3 !== void 0 ? _3 : "";
1406
+ if (!first)
1407
+ return undefined;
1408
+ var second = (_5 = (_4 = values[1]) === null || _4 === void 0 ? void 0 : _4.userEnteredValue) !== null && _5 !== void 0 ? _5 : "";
1409
+ var operatorMap = {
1410
+ DATE_EQ: "equal",
1411
+ DATE_NOT_EQ: "notEqual",
1412
+ DATE_BEFORE: "lessThan",
1413
+ DATE_AFTER: "greaterThan",
1414
+ DATE_ON_OR_BEFORE: "lessThanOrEqual",
1415
+ DATE_ON_OR_AFTER: "greaterThanOrEqual",
1416
+ DATE_BETWEEN: "between",
1417
+ DATE_NOT_BETWEEN: "notBetween",
1418
+ };
1419
+ return __assign({ type: "date", operator: operatorMap[condition.type], formula1: first, formula2: condition.type === "DATE_BETWEEN" ||
1420
+ condition.type === "DATE_NOT_BETWEEN"
1421
+ ? second
1422
+ : undefined }, baseConfig);
1423
+ }
1424
+ if (condition.type === "DATE_IS_VALID") {
1425
+ return __assign({ type: "custom", formula1: "=ISNUMBER(".concat(currentCell, ")") }, baseConfig);
1426
+ }
1427
+ return undefined;
1428
+ };
1429
+ var getDataValidationKey = function (config) {
1430
+ var _a, _b, _d, _e, _f, _g, _h;
1431
+ return [
1432
+ config.type,
1433
+ (_a = config.operator) !== null && _a !== void 0 ? _a : "",
1434
+ config.allowBlank ? "1" : "0",
1435
+ config.formula1,
1436
+ (_b = config.formula2) !== null && _b !== void 0 ? _b : "",
1437
+ config.showInputMessage ? "1" : "0",
1438
+ config.showErrorMessage ? "1" : "0",
1439
+ (_d = config.errorStyle) !== null && _d !== void 0 ? _d : "",
1440
+ (_e = config.errorTitle) !== null && _e !== void 0 ? _e : "",
1441
+ (_f = config.error) !== null && _f !== void 0 ? _f : "",
1442
+ (_g = config.promptTitle) !== null && _g !== void 0 ? _g : "",
1443
+ (_h = config.prompt) !== null && _h !== void 0 ? _h : "",
1444
+ config.showDropDown ? "1" : "0",
1445
+ ].join("|");
1446
+ };
1447
+ var buildDataValidationXml = function (config, refs) {
1448
+ var _a;
1449
+ var attrs = [];
1450
+ if (config.type) {
1451
+ attrs.push("type=\"".concat(config.type, "\""));
1452
+ }
1453
+ if (config.operator) {
1454
+ attrs.push("operator=\"".concat(config.operator, "\""));
1455
+ }
1456
+ if (config.allowBlank) {
1457
+ attrs.push("allowBlank=\"1\"");
1458
+ }
1459
+ if (config.showInputMessage) {
1460
+ attrs.push("showInputMessage=\"1\"");
1461
+ }
1462
+ if (config.showErrorMessage) {
1463
+ attrs.push("showErrorMessage=\"1\"");
1464
+ }
1465
+ if (config.errorStyle) {
1466
+ attrs.push("errorStyle=\"".concat(config.errorStyle, "\""));
1467
+ }
1468
+ if (config.errorTitle) {
1469
+ attrs.push("errorTitle=\"".concat(escapeXmlAttr(config.errorTitle), "\""));
1470
+ }
1471
+ if (config.error) {
1472
+ attrs.push("error=\"".concat(escapeXmlAttr(config.error), "\""));
1473
+ }
1474
+ if (config.promptTitle) {
1475
+ attrs.push("promptTitle=\"".concat(escapeXmlAttr(config.promptTitle), "\""));
1476
+ }
1477
+ if (config.prompt) {
1478
+ attrs.push("prompt=\"".concat(escapeXmlAttr(config.prompt), "\""));
1479
+ }
1480
+ if (config.showDropDown) {
1481
+ attrs.push("showDropDown=\"1\"");
1482
+ }
1483
+ var sqref = normalizeSqrefMembers(refs).join(" ");
1484
+ // Prompt-only DVs have no formula; emit a self-closing tag in that case.
1485
+ if (!config.type && !config.formula1) {
1486
+ return "<dataValidation ".concat(attrs.join(" "), " sqref=\"").concat(sqref, "\"/>");
1487
+ }
1488
+ var formula2 = config.formula2
1489
+ ? "<formula2>".concat(escapeXmlText(config.formula2), "</formula2>")
1490
+ : "";
1491
+ return "<dataValidation ".concat(attrs.join(" "), " sqref=\"").concat(sqref, "\"><formula1>").concat(escapeXmlText((_a = config.formula1) !== null && _a !== void 0 ? _a : ""), "</formula1>").concat(formula2, "</dataValidation>");
1492
+ };
1493
+ var resolveCellDataValidation = function (cell, map) {
1494
+ if (!cell)
1495
+ return undefined;
1496
+ var raw = cell === null || cell === void 0 ? void 0 : cell.dataValidation;
1497
+ if (!raw)
1498
+ return undefined;
1499
+ if (typeof raw === "string" || typeof raw === "number") {
1500
+ return map === null || map === void 0 ? void 0 : map[raw];
1501
+ }
1502
+ return raw;
1503
+ };
1504
+ var buildWorksheetRow = function (_a) {
1505
+ var _b, _d;
1506
+ var rowNumber = _a.rowNumber, row = _a.row, rowMetadata = _a.rowMetadata, defaultRowHeightPx = _a.defaultRowHeightPx, sharedStrings = _a.sharedStrings, sourceSharedStrings = _a.sourceSharedStrings, cellXfs = _a.cellXfs, styleBuilder = _a.styleBuilder, onImage = _a.onImage, onHyperlink = _a.onHyperlink, dataValidationsById = _a.dataValidationsById, onDataValidation = _a.onDataValidation, tableNameMap = _a.tableNameMap, tables = _a.tables, ignoreFormulaPatterns = _a.ignoreFormulaPatterns, commentsCollector = _a.commentsCollector, onCommentThread = _a.onCommentThread, sheetId = _a.sheetId, sheetData = _a.sheetData, sheets = _a.sheets, locale = _a.locale, validSharedFormulaLeaders = _a.validSharedFormulaLeaders;
1507
+ var values = (_b = row === null || row === void 0 ? void 0 : row.values) !== null && _b !== void 0 ? _b : [];
1508
+ var cellXmlChunks = [];
1509
+ var minColumn = Number.POSITIVE_INFINITY;
1510
+ var maxColumn = 0;
1511
+ for (var columnIndex = 1; columnIndex < values.length; columnIndex++) {
1512
+ var cell = values[columnIndex];
1513
+ var cellXml = buildCellXml({
1514
+ rowNumber: rowNumber,
1515
+ columnIndex: columnIndex,
1516
+ cell: cell,
1517
+ sharedStrings: sharedStrings,
1518
+ sourceSharedStrings: sourceSharedStrings,
1519
+ cellXfs: cellXfs,
1520
+ styleBuilder: styleBuilder,
1521
+ onImage: onImage,
1522
+ onHyperlink: onHyperlink,
1523
+ dataValidationsById: dataValidationsById,
1524
+ onDataValidation: onDataValidation,
1525
+ tableNameMap: tableNameMap,
1526
+ tables: tables,
1527
+ ignoreFormulaPatterns: ignoreFormulaPatterns,
1528
+ commentsCollector: commentsCollector,
1529
+ onCommentThread: onCommentThread,
1530
+ sheetId: sheetId,
1531
+ sheetData: sheetData,
1532
+ sheets: sheets,
1533
+ locale: locale,
1534
+ validSharedFormulaLeaders: validSharedFormulaLeaders,
1535
+ });
1536
+ if (!cellXml)
1537
+ continue;
1538
+ cellXmlChunks.push(cellXml);
1539
+ minColumn = Math.min(minColumn, columnIndex);
1540
+ maxColumn = Math.max(maxColumn, columnIndex);
1541
+ }
1542
+ var hasCells = cellXmlChunks.length > 0;
1543
+ var rowSize = (rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.size) && rowMetadata.size > 0 ? rowMetadata.size : undefined;
1544
+ var hasHiddenFlag = Boolean((rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.hiddenByUser) ||
1545
+ (rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.hiddenByFilter) ||
1546
+ (rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.hiddenByGroup));
1547
+ // Emit ``ht`` / ``customHeight`` when either:
1548
+ // (a) the row height differs from the workbook default, OR
1549
+ // (b) the import-side captured the source xlsx's ``customHeight="1"``
1550
+ // marker — Excel preserves that flag on round-trip even when the
1551
+ // value matches the default, and the fidelity comparator catches
1552
+ // its loss as a regression.
1553
+ // The `customHeight="1"` marker is emitted in two distinct cases:
1554
+ // 1. The import-only `customHeight` flag is set — preserves the source
1555
+ // xlsx's `customHeight="1"` verbatim, even when the height equals
1556
+ // the sheet default (xlsx files do carry that combination; Excel
1557
+ // reads it as "user locked this row even though it happens to
1558
+ // match the default").
1559
+ // 2. `resizedByUser=true` AND the height is non-default — covers the
1560
+ // UI/runtime path where a user explicitly resized a row to a
1561
+ // non-default value. We deliberately exclude `resizedByUser` on
1562
+ // default-height rows because that flag is shared with runtime
1563
+ // engine state (autofit chains, column-resize side effects) and
1564
+ // a stray flip there used to stamp every default-height row with
1565
+ // `customHeight="1"`, which Excel reads as "user locked this row"
1566
+ // and refuses to auto-fit.
1567
+ var hasExplicitHeight = Boolean(rowSize && Math.abs(rowSize - defaultRowHeightPx) > 0.01);
1568
+ var hasUserLockedHeight = Boolean(rowSize &&
1569
+ ((rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.customHeight) ||
1570
+ (hasExplicitHeight && (rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.resizedByUser))));
1571
+ var outlineLevel = (_d = rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.outlineLevel) !== null && _d !== void 0 ? _d : 0;
1572
+ var isCollapsed = Boolean(rowMetadata === null || rowMetadata === void 0 ? void 0 : rowMetadata.collapsed);
1573
+ var hasOutlineMetadata = outlineLevel > 0 || isCollapsed;
1574
+ var needsMetadata = hasHiddenFlag ||
1575
+ hasExplicitHeight ||
1576
+ hasUserLockedHeight ||
1577
+ hasOutlineMetadata;
1578
+ if (!hasCells && !needsMetadata) {
1579
+ return null;
1580
+ }
1581
+ var attrs = ["r=\"".concat(rowNumber, "\"")];
1582
+ if ((hasExplicitHeight || hasUserLockedHeight) && rowSize) {
1583
+ var height = pixelToPoints(rowSize);
1584
+ if (hasUserLockedHeight) {
1585
+ attrs.push("customHeight=\"1\"");
1586
+ }
1587
+ attrs.push("ht=\"".concat(height, "\""));
1588
+ }
1589
+ if (hasHiddenFlag) {
1590
+ attrs.push("hidden=\"1\"");
1591
+ }
1592
+ if (outlineLevel > 0) {
1593
+ attrs.push("outlineLevel=\"".concat(Math.min(7, Math.trunc(outlineLevel)), "\""));
1594
+ }
1595
+ if (isCollapsed) {
1596
+ attrs.push("collapsed=\"1\"");
1597
+ }
1598
+ var rowXml = "<row ".concat(attrs.join(" "), ">").concat(cellXmlChunks.join(""), "</row>");
1599
+ return {
1600
+ xml: rowXml,
1601
+ minColumn: isFinite(minColumn) ? minColumn : undefined,
1602
+ maxColumn: maxColumn || undefined,
1603
+ };
1604
+ };
1605
+ var buildCellXml = function (_a) {
1606
+ var e_26, _b;
1607
+ var _d, _e, _f, _g, _h, _j, _k, _l;
1608
+ var rowNumber = _a.rowNumber, columnIndex = _a.columnIndex, cell = _a.cell, sharedStrings = _a.sharedStrings, sourceSharedStrings = _a.sourceSharedStrings, cellXfs = _a.cellXfs, styleBuilder = _a.styleBuilder, onImage = _a.onImage, onHyperlink = _a.onHyperlink, dataValidationsById = _a.dataValidationsById, onDataValidation = _a.onDataValidation, tableNameMap = _a.tableNameMap, tables = _a.tables, ignoreFormulaPatterns = _a.ignoreFormulaPatterns, commentsCollector = _a.commentsCollector, onCommentThread = _a.onCommentThread, sheetId = _a.sheetId, sheetData = _a.sheetData, sheets = _a.sheets, locale = _a.locale, validSharedFormulaLeaders = _a.validSharedFormulaLeaders;
1609
+ var normalizedCell = cell;
1610
+ if (!normalizedCell)
1611
+ return undefined;
1612
+ var userEnteredValue = getCellUserEnteredValue(normalizedCell);
1613
+ var effectiveValue = (_d = getCellEffectiveValue(normalizedCell)) !== null && _d !== void 0 ? _d : userEnteredValue;
1614
+ // Excel-style: only `uf` is serialized. Read `uf` first, fall back to
1615
+ // legacy `ef` so old saved data still exports with its original format.
1616
+ var effectiveFormat = (_e = getCellUserEnteredFormat(normalizedCell)) !== null && _e !== void 0 ? _e : getCellEffectiveFormat(normalizedCell);
1617
+ if (effectiveFormat && isStyleReference(effectiveFormat)) {
1618
+ var styleId_1 = (_f = effectiveFormat.sid) !== null && _f !== void 0 ? _f : effectiveFormat.styleId;
1619
+ effectiveFormat = styleId_1 ? cellXfs === null || cellXfs === void 0 ? void 0 : cellXfs.get(styleId_1) : undefined;
1620
+ }
1621
+ var formattedValue = getCellFormattedValue(normalizedCell);
1622
+ // The data-validation Invalid marker is UI-only and must never export as
1623
+ // a real error cell — strip it so the cell's underlying value exports.
1624
+ var valueSource = (_g = omitInvalidDataValidationError(effectiveValue)) !== null && _g !== void 0 ? _g : omitInvalidDataValidationError(userEnteredValue);
1625
+ var numberValue = getExtendedValueNumber(valueSource);
1626
+ var boolValue = getExtendedValueBool(valueSource);
1627
+ var rawFormulaValue = getExtendedValueFormula(userEnteredValue);
1628
+ var formulaValue = shouldIgnoreFormula(rawFormulaValue, ignoreFormulaPatterns)
1629
+ ? undefined
1630
+ : rawFormulaValue;
1631
+ var exportedFormulaValue = formulaValue
1632
+ ? rewriteStructuredReferenceFormula(formulaValue, tableNameMap, tables, rowNumber, columnIndex)
1633
+ : formulaValue;
1634
+ // If formula contains property references (e.g., =A1.propertyName),
1635
+ // use formatted value instead of exporting unsupported formula
1636
+ if (hasPropertyReference(exportedFormulaValue)) {
1637
+ exportedFormulaValue = undefined;
1638
+ }
1639
+ var errorValue = getExtendedValueError(valueSource);
1640
+ var stringValue = getExtendedValueString(valueSource);
1641
+ var sharedStringIndex = normalizedCell === null || normalizedCell === void 0 ? void 0 : normalizedCell.ss;
1642
+ var sharedStringValue = sharedStringIndex != null && sourceSharedStrings
1643
+ ? sourceSharedStrings.get(String(sharedStringIndex))
1644
+ : null;
1645
+ if (sharedStringValue != null) {
1646
+ // SharedStrings entries can be either plain strings or rich
1647
+ // `{ text, runs }` objects. Surface the text for the cell value;
1648
+ // the rich runs are picked up separately below to write `<si><r>`.
1649
+ stringValue =
1650
+ typeof sharedStringValue === "string"
1651
+ ? sharedStringValue
1652
+ : (_h = sharedStringValue.text) !== null && _h !== void 0 ? _h : "";
1653
+ formattedValue = undefined;
1654
+ }
1655
+ var isDateLike = ((_j = effectiveFormat === null || effectiveFormat === void 0 ? void 0 : effectiveFormat.numberFormat) === null || _j === void 0 ? void 0 : _j.type) === "DATE" ||
1656
+ ((_k = effectiveFormat === null || effectiveFormat === void 0 ? void 0 : effectiveFormat.numberFormat) === null || _k === void 0 ? void 0 : _k.type) === "DATE_TIME";
1657
+ // Only treat as date string if the number is a valid Excel date serial
1658
+ // Large numbers outside the valid date range should export as numbers
1659
+ if (isDateLike && formattedValue && isValidExcelDateSerial(numberValue)) {
1660
+ stringValue = formattedValue;
1661
+ }
1662
+ if (formulaValue &&
1663
+ (stringValue != null || formattedValue != null) &&
1664
+ stringValue == null) {
1665
+ stringValue = String(formattedValue !== null && formattedValue !== void 0 ? formattedValue : "");
1666
+ }
1667
+ var hasExplicitValue = !isNil(numberValue) ||
1668
+ !isNil(boolValue) ||
1669
+ !isNil(formulaValue) ||
1670
+ !isNil(errorValue) ||
1671
+ stringValue != null;
1672
+ if (!hasExplicitValue && formattedValue === "") {
1673
+ formattedValue = undefined;
1674
+ }
1675
+ // For formula cells with no explicit number format, derive the format
1676
+ // Excel/Sheets would auto-apply from precedents and pass it into the
1677
+ // style registration. The cellData itself stays untouched. Without this,
1678
+ // Excel displays formula results without their inherited format until
1679
+ // the user manually recalculates.
1680
+ //
1681
+ // Skip cells whose `uf` is a `{ sid }` style reference: that's the shape
1682
+ // xlsx import produces, and an untouched imported cell's source xf already
1683
+ // says what Excel showed — General there is a decision, not a gap, and
1684
+ // deriving from precedents would restyle it away from the source file.
1685
+ var importedStyleRef = typeof normalizedCell.uf === "object" &&
1686
+ normalizedCell.uf !== null &&
1687
+ "sid" in normalizedCell.uf;
1688
+ var derivedNumberFormat;
1689
+ if (formulaValue &&
1690
+ !importedStyleRef &&
1691
+ !(effectiveFormat === null || effectiveFormat === void 0 ? void 0 : effectiveFormat.numberFormat) &&
1692
+ sheetData &&
1693
+ sheets &&
1694
+ sheetId != null) {
1695
+ var sheetIdByName_1 = new Map();
1696
+ try {
1697
+ for (var sheets_1 = __values(sheets), sheets_1_1 = sheets_1.next(); !sheets_1_1.done; sheets_1_1 = sheets_1.next()) {
1698
+ var s = sheets_1_1.value;
1699
+ if (s === null || s === void 0 ? void 0 : s.title)
1700
+ sheetIdByName_1.set(s.title, s.sheetId);
1701
+ }
1702
+ }
1703
+ catch (e_26_1) { e_26 = { error: e_26_1 }; }
1704
+ finally {
1705
+ try {
1706
+ if (sheets_1_1 && !sheets_1_1.done && (_b = sheets_1.return)) _b.call(sheets_1);
1707
+ }
1708
+ finally { if (e_26) throw e_26.error; }
1709
+ }
1710
+ // A real CellXfsRegistry so `SheetCell.assign` inside the derive
1711
+ // helper can resolve precedent cells whose `uf` is a `{ sid }` style
1712
+ // reference (the shape xlsx-imported workbooks produce).
1713
+ var cellXfsRegistry = cellXfs ? new CellXfsRegistry(cellXfs) : undefined;
1714
+ derivedNumberFormat =
1715
+ (_l = deriveEffectiveNumberFormatFromFormula(formulaValue, sheetId, rowNumber, columnIndex, sheetData, function (input) { return defaultTokenizer(input); }, function (name) { var _a; return (_a = sheetIdByName_1.get(name)) !== null && _a !== void 0 ? _a : sheetId; }, locale, cellXfsRegistry, undefined, typeof numberValue === "number" ? numberValue : null)) !== null && _l !== void 0 ? _l : undefined;
1716
+ }
1717
+ var styleId = styleBuilder.registerCell(normalizedCell, cellXfs, derivedNumberFormat);
1718
+ var address = cellToAddress({
1719
+ rowIndex: rowNumber,
1720
+ columnIndex: columnIndex,
1721
+ });
1722
+ if (!address)
1723
+ return undefined;
1724
+ // Check if cell has a note and add it to comments collector
1725
+ if (normalizedCell.note) {
1726
+ commentsCollector.add(address, normalizedCell.note, "User");
1727
+ }
1728
+ // A cell that anchors a comment thread carries only the thread id; the
1729
+ // resolver matches it against the workbook's threads to emit threaded
1730
+ // comments (+ a down-level note mirror).
1731
+ if (normalizedCell.commentThreadId != null) {
1732
+ onCommentThread === null || onCommentThread === void 0 ? void 0 : onCommentThread(address, normalizedCell.commentThreadId);
1733
+ }
1734
+ var hyperlinkValue = normalizeHyperlinkValue(normalizedCell === null || normalizedCell === void 0 ? void 0 : normalizedCell.hyperlink);
1735
+ if (hyperlinkValue) {
1736
+ onHyperlink({ ref: address, hyperlink: hyperlinkValue });
1737
+ }
1738
+ var validationRule = resolveCellDataValidation(normalizedCell, dataValidationsById);
1739
+ if (validationRule) {
1740
+ onDataValidation === null || onDataValidation === void 0 ? void 0 : onDataValidation({ address: address, rule: validationRule });
1741
+ }
1742
+ if (normalizedCell.imageUrl) {
1743
+ onImage({
1744
+ kind: "cell",
1745
+ imageUrl: normalizedCell.imageUrl,
1746
+ rowIndex: rowNumber,
1747
+ columnIndex: columnIndex,
1748
+ });
1749
+ }
1750
+ var xmlParts = [];
1751
+ var typeAttr = "";
1752
+ if (exportedFormulaValue) {
1753
+ // Array formula anchor: emit <f t="array" ref="..."/>. Spilled cells in
1754
+ // the range carry no `ue` formula (they're populated by the calculator
1755
+ // as side-effects of the anchor's evaluation), so they never reach this
1756
+ // branch and correctly emit only <v>.
1757
+ var arrayRef = normalizedCell.af;
1758
+ // Shared formula: emit `<f t="shared" si="N" ref="A1:A10">FORMULA</f>`
1759
+ // on the leader cell (carries both `si` and `ref`) and
1760
+ // `<f t="shared" si="N"/>` on followers (carries only `si` — no formula
1761
+ // text, no `ref`). Excel rebuilds the followers' formulas from the
1762
+ // leader's expression. Array takes precedence if both somehow apply
1763
+ // since they're mutually exclusive `t="…"` types.
1764
+ var sharedSpec = normalizedCell.sf;
1765
+ if (arrayRef) {
1766
+ xmlParts.push("<f t=\"array\" ref=\"".concat(escapeXmlAttr(arrayRef), "\">").concat(escapeXmlText(stripFormula(exportedFormulaValue)), "</f>"));
1767
+ }
1768
+ else if (sharedSpec && Number.isFinite(sharedSpec.si)) {
1769
+ if (sharedSpec.ref) {
1770
+ // Leader cell — emit full formula plus the shared-range ref.
1771
+ xmlParts.push("<f t=\"shared\" ref=\"".concat(escapeXmlAttr(sharedSpec.ref), "\" si=\"").concat(sharedSpec.si, "\">").concat(escapeXmlText(stripFormula(exportedFormulaValue)), "</f>"));
1772
+ }
1773
+ else if (validSharedFormulaLeaders === null || validSharedFormulaLeaders === void 0 ? void 0 : validSharedFormulaLeaders.has(sharedSpec.si)) {
1774
+ // Follower cell with a known leader — self-closing, no formula text.
1775
+ // Excel reads `si` back through the leader's expression and applies
1776
+ // relative-ref adjustments based on cell position.
1777
+ xmlParts.push("<f t=\"shared\" si=\"".concat(sharedSpec.si, "\"/>"));
1778
+ }
1779
+ else {
1780
+ // Follower whose leader is missing (typically because the leader
1781
+ // was edited by the user and lost its `sf` provenance). Falling
1782
+ // back to the standalone formula keeps the cell evaluating — the
1783
+ // `exportedFormulaValue` was already expanded with the right
1784
+ // relative refs on import via `formulaToRelativeReference`.
1785
+ xmlParts.push("<f>".concat(escapeXmlText(stripFormula(exportedFormulaValue)), "</f>"));
1786
+ }
1787
+ }
1788
+ else {
1789
+ xmlParts.push("<f>".concat(escapeXmlText(stripFormula(exportedFormulaValue)), "</f>"));
1790
+ }
1791
+ }
1792
+ if (errorValue) {
1793
+ typeAttr = " t=\"e\"";
1794
+ var errorText = typeof errorValue === "string"
1795
+ ? errorValue
1796
+ : (errorValue === null || errorValue === void 0 ? void 0 : errorValue.name) ||
1797
+ (errorValue === null || errorValue === void 0 ? void 0 : errorValue.type) ||
1798
+ (errorValue === null || errorValue === void 0 ? void 0 : errorValue.message) ||
1799
+ "#VALUE!";
1800
+ xmlParts.push("<v>".concat(escapeXmlText(normalizeExcelError(errorText)), "</v>"));
1801
+ }
1802
+ else if (!isNil(numberValue)) {
1803
+ xmlParts.push("<v>".concat(numberValue, "</v>"));
1804
+ }
1805
+ else if (!isNil(boolValue)) {
1806
+ typeAttr = " t=\"b\"";
1807
+ xmlParts.push("<v>".concat(boolValue ? 1 : 0, "</v>"));
1808
+ }
1809
+ else if (formulaValue && stringValue != null) {
1810
+ typeAttr = " t=\"str\"";
1811
+ xmlParts.push("<v>".concat(escapeXmlText(String(stringValue)), "</v>"));
1812
+ }
1813
+ else if (stringValue != null || formattedValue != null) {
1814
+ var text = stringValue !== null && stringValue !== void 0 ? stringValue : formattedValue;
1815
+ if (text == null) {
1816
+ return undefined;
1817
+ }
1818
+ // If this cell references a shared-string entry that carries runs
1819
+ // (rich SST entry in `sourceSharedStrings`), reuse that entry so
1820
+ // the formatting persists; otherwise intern a plain entry.
1821
+ var sourceEntry = normalizedCell.ss != null
1822
+ ? sourceSharedStrings === null || sourceSharedStrings === void 0 ? void 0 : sourceSharedStrings.get(String(normalizedCell.ss))
1823
+ : undefined;
1824
+ var richRuns = sourceEntry &&
1825
+ typeof sourceEntry === "object" &&
1826
+ Array.isArray(sourceEntry.runs)
1827
+ ? sourceEntry.runs
1828
+ : undefined;
1829
+ var stringIndex = richRuns
1830
+ ? sharedStrings.addRich(String(text), richRuns)
1831
+ : sharedStrings.add(String(text));
1832
+ typeAttr = " t=\"s\"";
1833
+ xmlParts.push("<v>".concat(stringIndex, "</v>"));
1834
+ }
1835
+ var styleAttr = styleId ? " s=\"".concat(styleId, "\"") : "";
1836
+ if (!xmlParts.length) {
1837
+ if (!styleId && !hyperlinkValue) {
1838
+ return undefined;
1839
+ }
1840
+ return "<c r=\"".concat(address, "\"").concat(styleAttr, "/>");
1841
+ }
1842
+ return "<c r=\"".concat(address, "\"").concat(typeAttr).concat(styleAttr, ">").concat(xmlParts.join(""), "</c>");
1843
+ };
1844
+ var normalizeHyperlinkValue = function (hyperlink) {
1845
+ if (!hyperlink) {
1846
+ return undefined;
1847
+ }
1848
+ if (typeof hyperlink === "string") {
1849
+ return { kind: "external", url: hyperlink };
1850
+ }
1851
+ return hyperlink;
1852
+ };
1853
+ // Excel rejects hyperlink targets that aren't valid URIs. Targets seen in the
1854
+ // wild that need normalizing: `<email@host>` (angle-bracket form), bare emails
1855
+ // (`user@host` without `mailto:`), and comma-separated lists. Returns undefined
1856
+ // to skip emitting the hyperlink rel entirely when we can't make it valid.
1857
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1858
+ var sanitizeHyperlinkUrl = function (url) {
1859
+ if (!url || typeof url !== "string")
1860
+ return undefined;
1861
+ var t = url.trim();
1862
+ if (!t)
1863
+ return undefined;
1864
+ if (t.startsWith("<") && t.endsWith(">")) {
1865
+ t = t.slice(1, -1).trim();
1866
+ }
1867
+ if (t.includes(",")) {
1868
+ t = t.split(",")[0].trim();
1869
+ }
1870
+ if (/^(https?|mailto|ftp|file):/i.test(t) || t.startsWith("#")) {
1871
+ return t;
1872
+ }
1873
+ if (EMAIL_RE.test(t)) {
1874
+ return "mailto:".concat(t);
1875
+ }
1876
+ return undefined;
1877
+ };
1878
+ var buildHyperlinksXml = function (entries, relationships) {
1879
+ if (!entries.length) {
1880
+ return "";
1881
+ }
1882
+ var items = entries
1883
+ .map(function (entry) {
1884
+ var hyperlink = entry.hyperlink;
1885
+ var displayAttr = hyperlink.display
1886
+ ? " display=\"".concat(escapeXmlAttr(hyperlink.display), "\"")
1887
+ : "";
1888
+ var tooltipAttr = hyperlink.tooltip
1889
+ ? " tooltip=\"".concat(escapeXmlAttr(hyperlink.tooltip), "\"")
1890
+ : "";
1891
+ if (hyperlink.kind === "external") {
1892
+ var url = sanitizeHyperlinkUrl(hyperlink.url);
1893
+ if (!url) {
1894
+ return "";
1895
+ }
1896
+ var relId = relationships.add(HYPERLINK_REL_TYPE, url, "External");
1897
+ return "<hyperlink ref=\"".concat(entry.ref, "\" r:id=\"").concat(relId, "\"").concat(displayAttr).concat(tooltipAttr, "/>");
1898
+ }
1899
+ if (!hyperlink.location) {
1900
+ return "";
1901
+ }
1902
+ return "<hyperlink ref=\"".concat(entry.ref, "\" location=\"").concat(escapeXmlAttr(hyperlink.location), "\"").concat(displayAttr).concat(tooltipAttr, "/>");
1903
+ })
1904
+ .filter(Boolean)
1905
+ .join("");
1906
+ if (!items) {
1907
+ return "";
1908
+ }
1909
+ return "<hyperlinks>".concat(items, "</hyperlinks>");
1910
+ };
1911
+ function shouldIgnoreFormula(formula, patterns) {
1912
+ if (!formula)
1913
+ return false;
1914
+ // Always ignore SPARKLINE formulas - they're exported as native Excel sparklines
1915
+ if (formula.toUpperCase().startsWith("=SPARKLINE(")) {
1916
+ return true;
1917
+ }
1918
+ if (!patterns)
1919
+ return false;
1920
+ var normalized = formula.startsWith("=") ? formula.slice(1) : formula;
1921
+ var list = Array.isArray(patterns) ? patterns : [patterns];
1922
+ return list.some(function (pattern) { return pattern.test(formula) || pattern.test(normalized); });
1923
+ }
1924
+ function stripFormula(formula) {
1925
+ var trimmed = formula.startsWith("=") ? formula.slice(1) : formula;
1926
+ return sanitizeFormulaText(trimmed);
1927
+ }
1928
+ function hasPropertyReference(formula) {
1929
+ if (!formula)
1930
+ return false;
1931
+ // Detects cell references with property access: A1.property, $A$1.nested.value, etc.
1932
+ var propertyReferencePattern = /[$]?[A-Za-z]{1,3}[$]?[1-9][0-9]*\./;
1933
+ return propertyReferencePattern.test(formula);
1934
+ }
1935
+ // Excel date serial: 1 = Jan 1, 1900, max ~2958465 = Dec 31, 9999
1936
+ // Numbers outside this range should not be treated as dates
1937
+ var MIN_EXCEL_DATE_SERIAL = 0;
1938
+ var MAX_EXCEL_DATE_SERIAL = 2958465;
1939
+ function isValidExcelDateSerial(value) {
1940
+ if (value == null || !Number.isFinite(value))
1941
+ return false;
1942
+ return value >= MIN_EXCEL_DATE_SERIAL && value <= MAX_EXCEL_DATE_SERIAL;
1943
+ }
1944
+ function rewriteTableNamesInFormula(formula, tableNameMap) {
1945
+ var e_27, _a;
1946
+ if (!(tableNameMap === null || tableNameMap === void 0 ? void 0 : tableNameMap.size))
1947
+ return formula;
1948
+ var normalized = formula;
1949
+ try {
1950
+ for (var tableNameMap_1 = __values(tableNameMap), tableNameMap_1_1 = tableNameMap_1.next(); !tableNameMap_1_1.done; tableNameMap_1_1 = tableNameMap_1.next()) {
1951
+ var _b = __read(tableNameMap_1_1.value, 2), tableName = _b[0], exportedName = _b[1];
1952
+ if (!tableName || tableName === exportedName)
1953
+ continue;
1954
+ var escaped = escapeCharacters(tableName);
1955
+ if (!escaped)
1956
+ continue;
1957
+ normalized = normalized.replace(new RegExp("".concat(escaped, "(?=\\[)"), "g"), exportedName);
1958
+ }
1959
+ }
1960
+ catch (e_27_1) { e_27 = { error: e_27_1 }; }
1961
+ finally {
1962
+ try {
1963
+ if (tableNameMap_1_1 && !tableNameMap_1_1.done && (_a = tableNameMap_1.return)) _a.call(tableNameMap_1);
1964
+ }
1965
+ finally { if (e_27) throw e_27.error; }
1966
+ }
1967
+ return normalized;
1968
+ }
1969
+ function findTableForCell(tables, rowNumber, columnIndex) {
1970
+ if (!(tables === null || tables === void 0 ? void 0 : tables.length))
1971
+ return undefined;
1972
+ return tables.find(function (table) {
1973
+ var range = table.range;
1974
+ if (!range)
1975
+ return false;
1976
+ return (rowNumber >= range.startRowIndex &&
1977
+ rowNumber <= range.endRowIndex &&
1978
+ columnIndex >= range.startColumnIndex &&
1979
+ columnIndex <= range.endColumnIndex);
1980
+ });
1981
+ }
1982
+ function prefixUnqualifiedStructuredReferences(formula, tableName) {
1983
+ if (!tableName)
1984
+ return formula;
1985
+ var normalized = "";
1986
+ var inString = false;
1987
+ var depth = 0;
1988
+ for (var i = 0; i < formula.length; i++) {
1989
+ var char = formula[i];
1990
+ if (char === '"') {
1991
+ normalized += char;
1992
+ if (inString) {
1993
+ if (formula[i + 1] === '"') {
1994
+ normalized += '"';
1995
+ i += 1;
1996
+ }
1997
+ else {
1998
+ inString = false;
1999
+ }
2000
+ }
2001
+ else {
2002
+ inString = true;
2003
+ }
2004
+ continue;
2005
+ }
2006
+ if (inString) {
2007
+ normalized += char;
2008
+ continue;
2009
+ }
2010
+ if (char === "[") {
2011
+ var prev = i > 0 ? formula[i - 1] : "";
2012
+ if (depth === 0 && !/[A-Za-z0-9_\]\[]/.test(prev)) {
2013
+ normalized += tableName;
2014
+ }
2015
+ depth += 1;
2016
+ normalized += char;
2017
+ continue;
2018
+ }
2019
+ if (char === "]" && depth > 0) {
2020
+ depth -= 1;
2021
+ normalized += char;
2022
+ continue;
2023
+ }
2024
+ normalized += char;
2025
+ }
2026
+ return normalized;
2027
+ }
2028
+ function normalizeThisRowStructuredReferences(formula, tableName) {
2029
+ if (!tableName)
2030
+ return formula;
2031
+ var normalized = formula;
2032
+ var escapedTable = escapeCharacters(tableName);
2033
+ if (!escapedTable)
2034
+ return normalized;
2035
+ var bracketed = new RegExp("".concat(escapedTable, "\\[\\@\\[([^\\]]+)\\]\\]"), "g");
2036
+ var simple = new RegExp("".concat(escapedTable, "\\[\\@([^\\]]+)\\]"), "g");
2037
+ normalized = normalized.replace(bracketed, "".concat(tableName, "[[#This Row],[$1]]"));
2038
+ normalized = normalized.replace(simple, "".concat(tableName, "[[#This Row],[$1]]"));
2039
+ return normalized;
2040
+ }
2041
+ function normalizeCalculatedColumnFormula(formula, table) {
2042
+ var _a;
2043
+ var tableNameMap = new Map();
2044
+ var tableTitle = (_a = table.title) !== null && _a !== void 0 ? _a : table.name;
2045
+ if (tableTitle && tableTitle !== table.name) {
2046
+ tableNameMap.set(tableTitle, table.name);
2047
+ }
2048
+ var normalized = rewriteTableNamesInFormula(formula, tableNameMap.size ? tableNameMap : undefined);
2049
+ normalized = prefixUnqualifiedStructuredReferences(normalized, table.name);
2050
+ normalized = normalizeThisRowStructuredReferences(normalized, table.name);
2051
+ return normalized;
2052
+ }
2053
+ function rewriteStructuredReferenceFormula(formula, tableNameMap, tables, rowNumber, columnIndex) {
2054
+ var normalized = rewriteTableNamesInFormula(formula, tableNameMap);
2055
+ var table = findTableForCell(tables, rowNumber, columnIndex);
2056
+ if (!(table === null || table === void 0 ? void 0 : table.name))
2057
+ return normalized;
2058
+ var qualified = prefixUnqualifiedStructuredReferences(normalized, table.name);
2059
+ return normalizeThisRowStructuredReferences(qualified, table.name);
2060
+ }
2061
+ function sanitizeFormulaText(formula) {
2062
+ var normalized = sanitizeXmlText(formula);
2063
+ return qualifyFutureFunctions(normalized.replace(/\r\n|\r|\n/g, " "));
2064
+ }
2065
+ function escapeXmlBase(value) {
2066
+ return sanitizeXmlText(value)
2067
+ .replace(/&/g, "&amp;")
2068
+ .replace(/</g, "&lt;")
2069
+ .replace(/>/g, "&gt;")
2070
+ .replace(/"/g, "&quot;")
2071
+ .replace(/'/g, "&apos;");
2072
+ }
2073
+ /**
2074
+ * Escape a value for an XML attribute. Newlines must be written as
2075
+ * character references (`&#10;`) because attribute-value normalization
2076
+ * folds raw line breaks into spaces.
2077
+ */
2078
+ function escapeXmlAttr(value) {
2079
+ return escapeXmlBase(value)
2080
+ .replace(/\r\n/g, "&#10;")
2081
+ .replace(/\r/g, "&#10;")
2082
+ .replace(/\n/g, "&#10;");
2083
+ }
2084
+ /**
2085
+ * Escape a value for XML element text. Raw LF is legal and preserved
2086
+ * verbatim in text nodes (Excel, rust_xlsxwriter, and the ODS exporter
2087
+ * all write raw newlines there); emitting `&#10;` instead leaks a
2088
+ * literal entity into importers that don't decode numeric character
2089
+ * references.
2090
+ */
2091
+ function escapeXmlText(value) {
2092
+ return escapeXmlBase(value).replace(/\r\n|\r/g, "\n");
2093
+ }
2094
+ var EXCEL_ERROR_VALUES = new Set([
2095
+ "#NULL!",
2096
+ "#DIV/0!",
2097
+ "#VALUE!",
2098
+ "#REF!",
2099
+ "#NAME?",
2100
+ "#NUM!",
2101
+ "#N/A",
2102
+ "#GETTING_DATA",
2103
+ "#SPILL!",
2104
+ "#CALC!",
2105
+ "#CONNECT!",
2106
+ "#BLOCKED!",
2107
+ "#FIELD!",
2108
+ ]);
2109
+ function normalizeExcelError(value) {
2110
+ if (!value)
2111
+ return "#VALUE!";
2112
+ var trimmed = value.trim();
2113
+ if (!trimmed)
2114
+ return "#VALUE!";
2115
+ if (EXCEL_ERROR_VALUES.has(trimmed)) {
2116
+ return trimmed;
2117
+ }
2118
+ return "#VALUE!";
2119
+ }
2120
+ var serializeColorXml = function (color) {
2121
+ if (!color)
2122
+ return undefined;
2123
+ if (typeof color === "string") {
2124
+ var hex = normalizeHex(color);
2125
+ return "rgb=\"".concat(hex, "\"");
2126
+ }
2127
+ var tintAttr = typeof color.tint === "number" ? " tint=\"".concat(color.tint, "\"") : "";
2128
+ return "theme=\"".concat(color.theme, "\"").concat(tintAttr);
2129
+ };
2130
+ var normalizeHex = function (color) {
2131
+ var normalized = color.startsWith("#") ? color.slice(1) : color;
2132
+ return normalized.length === 6 ? "FF".concat(normalized) : normalized;
2133
+ };
2134
+ var buildDimension = function (bounds) {
2135
+ if (!isFinite(bounds.minRow) ||
2136
+ !isFinite(bounds.minColumn) ||
2137
+ bounds.maxRow === 0 ||
2138
+ bounds.maxColumn === 0) {
2139
+ return "A1";
2140
+ }
2141
+ var startCol = columnIndexToLetter(bounds.minColumn);
2142
+ var endCol = columnIndexToLetter(bounds.maxColumn);
2143
+ return "".concat(startCol).concat(bounds.minRow, ":").concat(endCol).concat(bounds.maxRow);
2144
+ };
2145
+ var buildColumnsXml = function (sheet, bounds) {
2146
+ var _a, _b;
2147
+ var metadata = (_a = sheet.columnMetadata) !== null && _a !== void 0 ? _a : [];
2148
+ var maxColumns = Math.max(metadata.length - 1, bounds.maxColumn || 0);
2149
+ if (!maxColumns) {
2150
+ return "";
2151
+ }
2152
+ // Only emit ``<col>`` entries for columns the caller actually customized
2153
+ // (explicit width, hidden, or outline level). Emitting a `<col>` with the
2154
+ // engine's internal default width for every column — and stamping it with
2155
+ // ``customWidth="1"`` — overrides Excel's natural default-column-width
2156
+ // behavior and makes columns visibly narrower / wider than the equivalent
2157
+ // untouched openpyxl output. This matches stock openpyxl, which omits
2158
+ // ``<col>`` for non-customized columns and relies on Excel's default.
2159
+ var cols = [];
2160
+ for (var columnIndex = 1; columnIndex <= maxColumns; columnIndex += 1) {
2161
+ var props = metadata[columnIndex];
2162
+ if (!props)
2163
+ continue;
2164
+ var hasExplicitSize = Boolean(props.size && props.size > 0);
2165
+ var hasHiddenFlag = Boolean(props.hiddenByUser || props.hiddenByFilter || props.hiddenByGroup);
2166
+ var outlineLevel = (_b = props.outlineLevel) !== null && _b !== void 0 ? _b : 0;
2167
+ var isCollapsed = Boolean(props.collapsed);
2168
+ var hasOutlineMetadata = outlineLevel > 0 || isCollapsed;
2169
+ if (!hasExplicitSize && !hasHiddenFlag && !hasOutlineMetadata)
2170
+ continue;
2171
+ var attributes = ["min=\"".concat(columnIndex, "\""), "max=\"".concat(columnIndex, "\"")];
2172
+ if (hasExplicitSize) {
2173
+ var width = columnPixelToChars(getColumnWidthPx(sheet, columnIndex - 1));
2174
+ attributes.push("width=\"".concat(width.toFixed(2), "\""));
2175
+ attributes.push("customWidth=\"1\"");
2176
+ }
2177
+ if (hasHiddenFlag) {
2178
+ attributes.push("hidden=\"1\"");
2179
+ }
2180
+ if (outlineLevel > 0) {
2181
+ attributes.push("outlineLevel=\"".concat(Math.min(7, Math.trunc(outlineLevel)), "\""));
2182
+ }
2183
+ if (isCollapsed) {
2184
+ attributes.push("collapsed=\"1\"");
2185
+ }
2186
+ cols.push("<col ".concat(attributes.join(" "), "/>"));
2187
+ }
2188
+ if (!cols.length)
2189
+ return "";
2190
+ return "<cols>".concat(cols.join(""), "</cols>");
2191
+ };
2192
+ var buildTablePartsXml = function (tables, relationships) {
2193
+ if (!tables.length) {
2194
+ return "";
2195
+ }
2196
+ var parts = tables
2197
+ .map(function (table) {
2198
+ var relId = relationships.add(TABLE_REL_TYPE, table.target);
2199
+ return "<tablePart r:id=\"".concat(relId, "\"/>");
2200
+ })
2201
+ .join("");
2202
+ return "<tableParts count=\"".concat(tables.length, "\">").concat(parts, "</tableParts>");
2203
+ };
2204
+ var buildSheetViewsXml = function (sheet) {
2205
+ var _a, _b, _d, _e, _f;
2206
+ var showGridLines = (_a = sheet.showGridLines) !== null && _a !== void 0 ? _a : true;
2207
+ var showRowColHeaders = (_b = sheet.showRowColHeaders) !== null && _b !== void 0 ? _b : true;
2208
+ var showZeros = (_d = sheet.showZeros) !== null && _d !== void 0 ? _d : true;
2209
+ var zoomScale = sheet.zoomScale;
2210
+ var attrs = ["workbookViewId=\"0\""];
2211
+ if (!showGridLines) {
2212
+ attrs.push("showGridLines=\"0\"");
2213
+ }
2214
+ if (!showRowColHeaders) {
2215
+ attrs.push("showRowColHeaders=\"0\"");
2216
+ }
2217
+ if (!showZeros) {
2218
+ attrs.push("showZeros=\"0\"");
2219
+ }
2220
+ // Only emit zoomScale when set to a non-default value (Excel default = 100).
2221
+ if (typeof zoomScale === "number" &&
2222
+ zoomScale >= 10 &&
2223
+ zoomScale <= 400 &&
2224
+ zoomScale !== 100) {
2225
+ attrs.push("zoomScale=\"".concat(zoomScale, "\""));
2226
+ }
2227
+ var panes = [];
2228
+ var frozenRows = (_e = sheet.frozenRowCount) !== null && _e !== void 0 ? _e : 0;
2229
+ var frozenColumns = (_f = sheet.frozenColumnCount) !== null && _f !== void 0 ? _f : 0;
2230
+ if (frozenRows > 0 || frozenColumns > 0) {
2231
+ var paneAttrs = ["state=\"frozen\""];
2232
+ if (frozenColumns > 0) {
2233
+ paneAttrs.push("xSplit=\"".concat(frozenColumns, "\""));
2234
+ }
2235
+ if (frozenRows > 0) {
2236
+ paneAttrs.push("ySplit=\"".concat(frozenRows, "\""));
2237
+ }
2238
+ // Default view anchor = the first unfrozen cell. A preserved source
2239
+ // scroll position (`sheet.paneTopLeftCell`) wins when it's a valid A1
2240
+ // ref at or beyond that anchor, so an untouched import/export keeps the
2241
+ // user's saved scroll instead of snapping back to the freeze corner.
2242
+ var topLeftCell = "".concat(columnIndexToLetter(Math.max(1, frozenColumns + 1))).concat(frozenRows + 1);
2243
+ var savedTopLeft = sheet
2244
+ .paneTopLeftCell;
2245
+ if (typeof savedTopLeft === "string") {
2246
+ var m = /^([A-Z]+)([0-9]+)$/.exec(savedTopLeft);
2247
+ if (m) {
2248
+ var col = m[1]
2249
+ .split("")
2250
+ .reduce(function (acc, ch) { return acc * 26 + (ch.charCodeAt(0) - 64); }, 0);
2251
+ var row = Number(m[2]);
2252
+ if (row >= frozenRows + 1 && col >= Math.max(1, frozenColumns + 1)) {
2253
+ topLeftCell = savedTopLeft;
2254
+ }
2255
+ }
2256
+ }
2257
+ paneAttrs.push("topLeftCell=\"".concat(topLeftCell, "\""));
2258
+ // Anchor active selection in the unfrozen quadrant. Excel writes
2259
+ // `pane="bottomRight"` when both rows AND columns are frozen,
2260
+ // `bottomLeft` when only rows, `topRight` when only columns. Without
2261
+ // this the cursor lands in A1 (the frozen region) on first open.
2262
+ var activePane = void 0;
2263
+ if (frozenRows > 0 && frozenColumns > 0) {
2264
+ activePane = "bottomRight";
2265
+ }
2266
+ else if (frozenRows > 0) {
2267
+ activePane = "bottomLeft";
2268
+ }
2269
+ else {
2270
+ activePane = "topRight";
2271
+ }
2272
+ paneAttrs.push("activePane=\"".concat(activePane, "\""));
2273
+ panes.push("<pane ".concat(paneAttrs.join(" "), "/>"));
2274
+ panes.push("<selection pane=\"".concat(activePane, "\" activeCell=\"").concat(topLeftCell, "\" sqref=\"").concat(topLeftCell, "\"/>"));
2275
+ }
2276
+ return "<sheetViews><sheetView ".concat(attrs.join(" "), ">").concat(panes.join(""), "</sheetView></sheetViews>");
2277
+ };
2278
+ var columnIndexToLetter = function (index) {
2279
+ var dividend = Math.max(1, index);
2280
+ var columnName = "";
2281
+ while (dividend > 0) {
2282
+ var modulo = (dividend - 1) % 26;
2283
+ columnName = String.fromCharCode(65 + modulo) + columnName;
2284
+ dividend = Math.floor((dividend - modulo) / 26);
2285
+ }
2286
+ return columnName;
2287
+ };
2288
+ /**
2289
+ * Build the `<rPr>` block for one rich-text run. Maps our internal
2290
+ * TextFormat keys to OOXML run-properties. Only emits properties that
2291
+ * differ from the cell-level base — Excel falls back to the parent
2292
+ * cell's `<xf>` style for anything absent, matching what users expect.
2293
+ */
2294
+ var buildRichRunProperties = function (format) {
2295
+ var parts = [];
2296
+ if (format === null || format === void 0 ? void 0 : format.bold)
2297
+ parts.push("<b/>");
2298
+ if (format === null || format === void 0 ? void 0 : format.italic)
2299
+ parts.push("<i/>");
2300
+ if (format === null || format === void 0 ? void 0 : format.underline)
2301
+ parts.push("<u/>");
2302
+ if (format === null || format === void 0 ? void 0 : format.strikethrough)
2303
+ parts.push("<strike/>");
2304
+ if ((format === null || format === void 0 ? void 0 : format.baselineOffset) === "superscript") {
2305
+ parts.push("<vertAlign val=\"superscript\"/>");
2306
+ }
2307
+ else if ((format === null || format === void 0 ? void 0 : format.baselineOffset) === "subscript") {
2308
+ parts.push("<vertAlign val=\"subscript\"/>");
2309
+ }
2310
+ if (typeof (format === null || format === void 0 ? void 0 : format.fontSize) === "number") {
2311
+ parts.push("<sz val=\"".concat(format.fontSize, "\"/>"));
2312
+ }
2313
+ if (typeof (format === null || format === void 0 ? void 0 : format.fontFamily) === "string" && format.fontFamily) {
2314
+ parts.push("<rFont val=\"".concat(escapeXmlAttr(format.fontFamily), "\"/>"));
2315
+ }
2316
+ if (format === null || format === void 0 ? void 0 : format.color) {
2317
+ // Color may be a string ("#RRGGBB" or "rgb(...)") or a theme/tint
2318
+ // object. We only emit the simple `rgb=` form for now — theme
2319
+ // colors round-trip lossless via `<color theme="N" tint="X"/>`
2320
+ // but require additional resolution we don't need yet.
2321
+ var colorValue = format.color;
2322
+ if (typeof colorValue === "string") {
2323
+ var hex = colorValue.replace(/^#/, "").toUpperCase();
2324
+ // Excel expects ARGB; default alpha = FF if a 6-digit hex.
2325
+ var rgb = hex.length === 6 ? "FF".concat(hex) : hex;
2326
+ if (/^[0-9A-F]{8}$/.test(rgb)) {
2327
+ parts.push("<color rgb=\"".concat(rgb, "\"/>"));
2328
+ }
2329
+ }
2330
+ else if (typeof colorValue === "object" && colorValue !== null) {
2331
+ var c = colorValue;
2332
+ if (typeof c.rgba === "string") {
2333
+ var hex = c.rgba.replace(/^#/, "").toUpperCase();
2334
+ var rgb = hex.length === 6 ? "FF".concat(hex) : hex;
2335
+ if (/^[0-9A-F]{8}$/.test(rgb)) {
2336
+ parts.push("<color rgb=\"".concat(rgb, "\"/>"));
2337
+ }
2338
+ }
2339
+ else if (typeof c.theme === "number") {
2340
+ var tintAttr = typeof c.tint === "number" && c.tint !== 0
2341
+ ? " tint=\"".concat(c.tint, "\"")
2342
+ : "";
2343
+ parts.push("<color theme=\"".concat(c.theme, "\"").concat(tintAttr, "/>"));
2344
+ }
2345
+ }
2346
+ }
2347
+ return parts.length ? "<rPr>".concat(parts.join(""), "</rPr>") : "";
2348
+ };
2349
+ /**
2350
+ * Slice a value string into `<r>` blocks based on the run array. Runs
2351
+ * are assumed non-overlapping and sorted; gaps between runs become
2352
+ * unformatted `<r><t>...</t></r>` blocks (matching how Excel emits
2353
+ * sequential plain segments). Newline characters survive verbatim in
2354
+ * `<t>` — Excel honours them only when the cell carries the wrap
2355
+ * style flag, but that's a cell-style concern, not a sharedString one.
2356
+ */
2357
+ var buildRichTextRuns = function (text, runs) {
2358
+ var e_28, _a;
2359
+ var sorted = __spreadArray([], __read(runs), false).sort(function (a, b) { return a.startIndex - b.startIndex; });
2360
+ var out = [];
2361
+ var cursor = 0;
2362
+ var emit = function (segment, rPr) {
2363
+ if (!segment)
2364
+ return;
2365
+ var needsSpace = /^\s|\s$|[\r\n]/.test(segment);
2366
+ var spaceAttr = needsSpace ? ' xml:space="preserve"' : "";
2367
+ out.push("<r>".concat(rPr, "<t").concat(spaceAttr, ">").concat(escapeXmlText(segment), "</t></r>"));
2368
+ };
2369
+ try {
2370
+ for (var sorted_2 = __values(sorted), sorted_2_1 = sorted_2.next(); !sorted_2_1.done; sorted_2_1 = sorted_2.next()) {
2371
+ var run = sorted_2_1.value;
2372
+ var start = Math.max(0, Math.min(text.length, run.startIndex));
2373
+ var end = Math.max(start, Math.min(text.length, run.endIndex));
2374
+ if (start > cursor) {
2375
+ emit(text.slice(cursor, start), "");
2376
+ }
2377
+ if (start < end) {
2378
+ if (run.nodeType === "mention") {
2379
+ // Mentions don't carry inline formatting on the XLSX side —
2380
+ // emit as plain text (their label is already inline in the value).
2381
+ emit(text.slice(start, end), "");
2382
+ }
2383
+ else {
2384
+ emit(text.slice(start, end), buildRichRunProperties(run.format));
2385
+ }
2386
+ }
2387
+ if (end > cursor)
2388
+ cursor = end;
2389
+ }
2390
+ }
2391
+ catch (e_28_1) { e_28 = { error: e_28_1 }; }
2392
+ finally {
2393
+ try {
2394
+ if (sorted_2_1 && !sorted_2_1.done && (_a = sorted_2.return)) _a.call(sorted_2);
2395
+ }
2396
+ finally { if (e_28) throw e_28.error; }
2397
+ }
2398
+ if (cursor < text.length) {
2399
+ emit(text.slice(cursor), "");
2400
+ }
2401
+ return out.join("");
2402
+ };
2403
+ var buildSharedStringsXml = function (sharedStrings) {
2404
+ var entries = sharedStrings.entries
2405
+ .map(function (entry) {
2406
+ if (entry.kind === "rich") {
2407
+ return "<si>".concat(buildRichTextRuns(entry.text, entry.runs), "</si>");
2408
+ }
2409
+ var needsSpace = /^\s|\s$|[\r\n]/.test(entry.text);
2410
+ var spaceAttr = needsSpace ? ' xml:space="preserve"' : "";
2411
+ return "<si><t".concat(spaceAttr, ">").concat(escapeXmlText(entry.text), "</t></si>");
2412
+ })
2413
+ .join("");
2414
+ return "".concat(XML_DECLARATION, "<sst xmlns=\"").concat(WORKSHEET_NS, "\" count=\"").concat(sharedStrings.totalCount, "\" uniqueCount=\"").concat(sharedStrings.entries.length, "\">").concat(entries, "</sst>");
2415
+ };
2416
+ var buildTableNameMap = function (tables) {
2417
+ var e_29, _a;
2418
+ var _b;
2419
+ var map = new Map();
2420
+ try {
2421
+ for (var tables_1 = __values(tables), tables_1_1 = tables_1.next(); !tables_1_1.done; tables_1_1 = tables_1.next()) {
2422
+ var table = tables_1_1.value;
2423
+ var tableTitle = (_b = table.title) !== null && _b !== void 0 ? _b : table.name;
2424
+ if (!tableTitle || tableTitle === table.name)
2425
+ continue;
2426
+ map.set(tableTitle, table.name);
2427
+ }
2428
+ }
2429
+ catch (e_29_1) { e_29 = { error: e_29_1 }; }
2430
+ finally {
2431
+ try {
2432
+ if (tables_1_1 && !tables_1_1.done && (_a = tables_1.return)) _a.call(tables_1);
2433
+ }
2434
+ finally { if (e_29) throw e_29.error; }
2435
+ }
2436
+ return map;
2437
+ };
2438
+ // Excel rejects tables whose range starts at row/column 0 (1-indexed only) or
2439
+ // whose box intersects another table on the same sheet. Drop both before
2440
+ // emitting so the workbook opens without "We found a problem" recovery prompts.
2441
+ var filterExportableTables = function (tables) {
2442
+ var e_30, _a;
2443
+ var _b;
2444
+ var isValidBox = function (range) {
2445
+ if (!range)
2446
+ return false;
2447
+ var startRowIndex = range.startRowIndex, startColumnIndex = range.startColumnIndex, endRowIndex = range.endRowIndex, endColumnIndex = range.endColumnIndex;
2448
+ if (typeof startRowIndex !== "number" ||
2449
+ typeof startColumnIndex !== "number" ||
2450
+ typeof endRowIndex !== "number" ||
2451
+ typeof endColumnIndex !== "number") {
2452
+ return false;
2453
+ }
2454
+ if (startRowIndex < 1 || startColumnIndex < 1)
2455
+ return false;
2456
+ if (endRowIndex < startRowIndex || endColumnIndex < startColumnIndex) {
2457
+ return false;
2458
+ }
2459
+ return true;
2460
+ };
2461
+ var boxesIntersect = function (a, b) {
2462
+ return !(a.endRowIndex < b.startRowIndex ||
2463
+ b.endRowIndex < a.startRowIndex ||
2464
+ a.endColumnIndex < b.startColumnIndex ||
2465
+ b.endColumnIndex < a.startColumnIndex);
2466
+ };
2467
+ var keptBySheet = new Map();
2468
+ var result = [];
2469
+ var _loop_4 = function (table) {
2470
+ if (!isValidBox(table.range))
2471
+ return "continue";
2472
+ var sheetKept = (_b = keptBySheet.get(table.sheetId)) !== null && _b !== void 0 ? _b : [];
2473
+ if (sheetKept.some(function (r) { return boxesIntersect(table.range, r); }))
2474
+ return "continue";
2475
+ sheetKept.push(table.range);
2476
+ keptBySheet.set(table.sheetId, sheetKept);
2477
+ result.push(table);
2478
+ };
2479
+ try {
2480
+ for (var tables_2 = __values(tables), tables_2_1 = tables_2.next(); !tables_2_1.done; tables_2_1 = tables_2.next()) {
2481
+ var table = tables_2_1.value;
2482
+ _loop_4(table);
2483
+ }
2484
+ }
2485
+ catch (e_30_1) { e_30 = { error: e_30_1 }; }
2486
+ finally {
2487
+ try {
2488
+ if (tables_2_1 && !tables_2_1.done && (_a = tables_2.return)) _a.call(tables_2);
2489
+ }
2490
+ finally { if (e_30) throw e_30.error; }
2491
+ }
2492
+ return result;
2493
+ };
2494
+ var prepareTables = function (tables) {
2495
+ var result = [];
2496
+ tables.forEach(function (table, index) {
2497
+ var _a;
2498
+ var ref = gridRangeToRef(table.range);
2499
+ if (!ref)
2500
+ return;
2501
+ var id = index + 1;
2502
+ var sanitized = sanitizeTableName((_a = table.title) !== null && _a !== void 0 ? _a : "Table".concat(id));
2503
+ result.push(__assign(__assign({}, table), { id: id, ref: ref, path: "xl/tables/table".concat(id, ".xml"), target: "../tables/table".concat(id, ".xml"), name: sanitized, displayName: sanitized }));
2504
+ });
2505
+ return result;
2506
+ };
2507
+ var sanitizeTableName = function (name) {
2508
+ var cleaned = name.replace(/[^A-Za-z0-9_]/g, "") || "Table";
2509
+ if (/^\d/.test(cleaned)) {
2510
+ return "T".concat(cleaned);
2511
+ }
2512
+ return cleaned;
2513
+ };
2514
+ var buildTableXml = function (table, rows, sourceSharedStrings, styleBuilder) {
2515
+ var _a, _b, _d;
2516
+ var rangeRef = table.ref;
2517
+ var columnCount = Math.max((_b = (_a = table.columns) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0, ((_d = table.range.endColumnIndex) !== null && _d !== void 0 ? _d : table.range.startColumnIndex) -
2518
+ table.range.startColumnIndex +
2519
+ 1);
2520
+ var headerRowCount = table.headerRow === false ? 0 : 1;
2521
+ var totalsRowCount = table.totalRow ? 1 : 0;
2522
+ var headerRowIndex = table.range.startRowIndex;
2523
+ var columnNames = Array.from({ length: columnCount }, function (_, index) {
2524
+ var _a, _b, _d, _e, _f;
2525
+ // Always read from cell data first - this is the source of truth for what Excel sees
2526
+ if (headerRowCount > 0) {
2527
+ var columnIndex = table.range.startColumnIndex + index;
2528
+ var cell = (_b = (_a = rows[headerRowIndex]) === null || _a === void 0 ? void 0 : _a.values) === null || _b === void 0 ? void 0 : _b[columnIndex];
2529
+ // Check shared string first - this matches what gets written to the cell XML
2530
+ var sharedStringIndex = cell === null || cell === void 0 ? void 0 : cell.ss;
2531
+ if (sharedStringIndex != null && sourceSharedStrings) {
2532
+ var raw = sourceSharedStrings.get(String(sharedStringIndex));
2533
+ var sharedStringValue = typeof raw === "string"
2534
+ ? raw
2535
+ : raw && typeof raw === "object"
2536
+ ? raw.text
2537
+ : undefined;
2538
+ if (sharedStringValue != null && sharedStringValue.trim() !== "") {
2539
+ return sharedStringValue;
2540
+ }
2541
+ }
2542
+ // Try formattedValue first, then extract string from effectiveValue/userEnteredValue
2543
+ var formattedValue = getCellFormattedValue(cell);
2544
+ if (formattedValue != null && String(formattedValue).trim() !== "") {
2545
+ return String(formattedValue);
2546
+ }
2547
+ var effectiveValue = getCellEffectiveValue(cell);
2548
+ var effectiveString = getExtendedValueString(effectiveValue);
2549
+ if (effectiveString != null && effectiveString.trim() !== "") {
2550
+ return effectiveString;
2551
+ }
2552
+ var userEnteredValue = getCellUserEnteredValue(cell);
2553
+ var userEnteredString = getExtendedValueString(userEnteredValue);
2554
+ if (userEnteredString != null && userEnteredString.trim() !== "") {
2555
+ return userEnteredString;
2556
+ }
2557
+ }
2558
+ // Fallback to table.columns name or generic name
2559
+ return (_f = (_e = (_d = table.columns) === null || _d === void 0 ? void 0 : _d[index]) === null || _e === void 0 ? void 0 : _e.name) !== null && _f !== void 0 ? _f : "Column".concat(index + 1);
2560
+ });
2561
+ var tableColumns = "<tableColumns count=\"".concat(columnCount, "\">").concat(columnNames
2562
+ .map(function (name, idx) {
2563
+ var _a, _b;
2564
+ var columnFormula = (_b = (_a = table.columns) === null || _a === void 0 ? void 0 : _a[idx]) === null || _b === void 0 ? void 0 : _b.formula;
2565
+ var normalizedFormula = columnFormula
2566
+ ? normalizeCalculatedColumnFormula(columnFormula, table)
2567
+ : undefined;
2568
+ var formulaXml = normalizedFormula
2569
+ ? "<calculatedColumnFormula>".concat(escapeXmlText(stripFormula(normalizedFormula)), "</calculatedColumnFormula>")
2570
+ : "";
2571
+ return "<tableColumn id=\"".concat(idx + 1, "\" name=\"").concat(escapeXmlAttr(name), "\">").concat(formulaXml, "</tableColumn>");
2572
+ })
2573
+ .join(""), "</tableColumns>");
2574
+ var isBuiltInStyle = table.theme && /^TableStyle(Light|Medium|Dark)\d+$/.test(table.theme);
2575
+ var tableStyleName = isBuiltInStyle ? table.theme : "TableStyleMedium2";
2576
+ var tableStyleInfo = "<tableStyleInfo name=\"".concat(tableStyleName, "\" showFirstColumn=\"").concat(table.showFirstColumn ? 1 : 0, "\" showLastColumn=\"").concat(table.showLastColumn ? 1 : 0, "\" showRowStripes=\"").concat(table.showRowStripes ? 1 : 0, "\" showColumnStripes=\"").concat(table.showColumnStripes ? 1 : 0, "\"/>");
2577
+ var autoFilter = headerRowCount > 0 && table.filterButton !== false
2578
+ ? (function () {
2579
+ var _a, _b, _d;
2580
+ var filterColumns = buildFilterColumnsXml((_a = table.filterSpecs) !== null && _a !== void 0 ? _a : [], table.range, rows, (_b = table.headerRow) !== null && _b !== void 0 ? _b : true, (_d = table.totalRow) !== null && _d !== void 0 ? _d : false, styleBuilder);
2581
+ return filterColumns
2582
+ ? "<autoFilter ref=\"".concat(rangeRef, "\">").concat(filterColumns, "</autoFilter>")
2583
+ : "<autoFilter ref=\"".concat(rangeRef, "\"/>");
2584
+ })()
2585
+ : "";
2586
+ return "".concat(XML_DECLARATION, "<table xmlns=\"").concat(WORKSHEET_NS, "\" id=\"").concat(table.id, "\" name=\"").concat(escapeXmlAttr(table.name), "\" displayName=\"").concat(escapeXmlAttr(table.displayName), "\" ref=\"").concat(rangeRef, "\" totalsRowCount=\"").concat(totalsRowCount, "\" headerRowCount=\"").concat(headerRowCount, "\">").concat(autoFilter).concat(tableColumns).concat(tableStyleInfo, "</table>");
2587
+ };
2588
+ var getFilterVisibleValues = function (spec, range, rows, headerRow, totalRow) {
2589
+ var _a, _b, _d;
2590
+ if (headerRow === void 0) { headerRow = true; }
2591
+ if (totalRow === void 0) { totalRow = false; }
2592
+ var values = new Set();
2593
+ var startRowIndex = range.startRowIndex + (headerRow ? 1 : 0);
2594
+ var endRowIndex = range.endRowIndex - (totalRow ? 1 : 0);
2595
+ var columnIndex = range.startColumnIndex + spec.columnIndex;
2596
+ for (var rowIndex = startRowIndex; rowIndex <= endRowIndex; rowIndex++) {
2597
+ var cell = (_b = (_a = rows[rowIndex]) === null || _a === void 0 ? void 0 : _a.values) === null || _b === void 0 ? void 0 : _b[columnIndex];
2598
+ var formattedValue = getCellFormattedValue(cell);
2599
+ var fallbackValue = (_d = formattedValue !== null && formattedValue !== void 0 ? formattedValue : getCellEffectiveValue(cell)) !== null && _d !== void 0 ? _d : getCellUserEnteredValue(cell);
2600
+ if (isNil(fallbackValue) || fallbackValue === "") {
2601
+ values.add(BLANK_LABEL);
2602
+ continue;
2603
+ }
2604
+ values.add(String(fallbackValue));
2605
+ }
2606
+ return __spreadArray([], __read(values), false);
2607
+ };
2608
+ var buildWorksheetAutoFilterXml = function (sheet, rows, styleBuilder) {
2609
+ var basicFilter = sheet.basicFilter;
2610
+ if (!(basicFilter === null || basicFilter === void 0 ? void 0 : basicFilter.range))
2611
+ return "";
2612
+ var ref = cellRangeToAddress(undefined, basicFilter.range);
2613
+ if (!ref)
2614
+ return "";
2615
+ var filterColumns = buildFilterColumnsXml(basicFilter.filterSpecs, basicFilter.range, rows, true, false, styleBuilder);
2616
+ if (filterColumns) {
2617
+ return "<autoFilter ref=\"".concat(ref, "\">").concat(filterColumns, "</autoFilter>");
2618
+ }
2619
+ return "<autoFilter ref=\"".concat(ref, "\"/>");
2620
+ };
2621
+ var buildSheetPropertiesXml = function (sheet) {
2622
+ var _a;
2623
+ var tabColor = serializeColorXml((_a = sheet.tabColor) !== null && _a !== void 0 ? _a : undefined);
2624
+ // <outlinePr> mirrors the sheet's `outlinePr` setting; both attrs
2625
+ // default to true in Excel, so only emit when explicitly false. If
2626
+ // the user only customised one half, the other half stays implicit.
2627
+ var outlinePr = sheet.outlinePr;
2628
+ var outlineAttrs = [];
2629
+ if ((outlinePr === null || outlinePr === void 0 ? void 0 : outlinePr.summaryBelow) === false) {
2630
+ outlineAttrs.push("summaryBelow=\"0\"");
2631
+ }
2632
+ if ((outlinePr === null || outlinePr === void 0 ? void 0 : outlinePr.summaryRight) === false) {
2633
+ outlineAttrs.push("summaryRight=\"0\"");
2634
+ }
2635
+ var outlineXml = outlineAttrs.length
2636
+ ? "<outlinePr ".concat(outlineAttrs.join(" "), "/>")
2637
+ : "";
2638
+ if (!tabColor && !outlineXml)
2639
+ return "";
2640
+ var inner = "".concat(tabColor ? "<tabColor ".concat(tabColor, "/>") : "").concat(outlineXml);
2641
+ return "<sheetPr>".concat(inner, "</sheetPr>");
2642
+ };
2643
+ var buildFilterColumnsXml = function (filterSpecs, range, rows, headerRow, totalRow, styleBuilder) {
2644
+ if (headerRow === void 0) { headerRow = true; }
2645
+ if (totalRow === void 0) { totalRow = false; }
2646
+ if (!(filterSpecs === null || filterSpecs === void 0 ? void 0 : filterSpecs.length))
2647
+ return "";
2648
+ var entries = filterSpecs
2649
+ .map(function (spec) {
2650
+ return buildFilterColumnXml(spec, range, rows, headerRow, totalRow, styleBuilder);
2651
+ })
2652
+ .filter(function (entry) { return Boolean(entry); });
2653
+ return entries.join("");
2654
+ };
2655
+ var buildFilterColumnXml = function (spec, range, rows, headerRow, totalRow, styleBuilder) {
2656
+ var _a, _b, _d, _e, _f, _g;
2657
+ if (headerRow === void 0) { headerRow = true; }
2658
+ if (totalRow === void 0) { totalRow = false; }
2659
+ var parts = [];
2660
+ // <colorFilter dxfId="N" cellColor="1|0"/> — Excel matches against the
2661
+ // dxf table. We register the color as a dxf and emit the resulting id.
2662
+ var colorFilter = (_a = spec.filterCriteria) === null || _a === void 0 ? void 0 : _a.colorFilter;
2663
+ if (colorFilter && styleBuilder) {
2664
+ var dxfId = colorFilter.mode === "cellColor"
2665
+ ? styleBuilder.registerDifferentialFormat({
2666
+ backgroundColor: colorFilter.color,
2667
+ })
2668
+ : styleBuilder.registerDifferentialFormat({
2669
+ textFormat: { color: colorFilter.color },
2670
+ });
2671
+ if (typeof dxfId === "number") {
2672
+ var cellColorAttr = colorFilter.mode === "cellColor" ? "1" : "0";
2673
+ parts.push("<colorFilter dxfId=\"".concat(dxfId, "\" cellColor=\"").concat(cellColorAttr, "\"/>"));
2674
+ }
2675
+ }
2676
+ // <iconFilter iconSet="…" iconId="…"/>
2677
+ var iconFilter = (_b = spec.filterCriteria) === null || _b === void 0 ? void 0 : _b.iconFilter;
2678
+ if (iconFilter === null || iconFilter === void 0 ? void 0 : iconFilter.iconSet) {
2679
+ parts.push("<iconFilter iconSet=\"".concat(escapeXmlAttr(iconFilter.iconSet), "\" iconId=\"").concat((_d = iconFilter.iconId) !== null && _d !== void 0 ? _d : 0, "\"/>"));
2680
+ }
2681
+ // A condition filter (greater-than / contains / between / relative-date /
2682
+ // above-average …) takes precedence over a value-list and is emitted as
2683
+ // <customFilters> or <dynamicFilter>. Falls back to the value list when the
2684
+ // condition has no AutoFilter representation.
2685
+ var conditionXml = buildAutoFilterConditionXml((_e = spec.filterCriteria) === null || _e === void 0 ? void 0 : _e.condition);
2686
+ if (conditionXml) {
2687
+ parts.push(conditionXml);
2688
+ }
2689
+ else {
2690
+ // <filters><filter val=…/></filters>
2691
+ var values = (_g = (_f = spec.filterCriteria) === null || _f === void 0 ? void 0 : _f.visibleValues) !== null && _g !== void 0 ? _g : getFilterVisibleValues(spec, range, rows, headerRow, totalRow);
2692
+ if (values === null || values === void 0 ? void 0 : values.length) {
2693
+ var filters = values
2694
+ .map(function (value) { return "<filter val=\"".concat(escapeXmlAttr(value), "\"/>"); })
2695
+ .join("");
2696
+ parts.push("<filters>".concat(filters, "</filters>"));
2697
+ }
2698
+ }
2699
+ if (!parts.length)
2700
+ return "";
2701
+ return "<filterColumn colId=\"".concat(spec.columnIndex, "\">").concat(parts.join(""), "</filterColumn>");
2702
+ };
2703
+ var gridRangeToRef = function (range) {
2704
+ if (!range)
2705
+ return undefined;
2706
+ try {
2707
+ var ref = cellRangeToAddress(undefined, range);
2708
+ return ref !== null && ref !== void 0 ? ref : undefined;
2709
+ }
2710
+ catch (_a) {
2711
+ return undefined;
2712
+ }
2713
+ };
2714
+ var groupEmbedsBySheet = function (embeds) {
2715
+ var e_31, _a;
2716
+ var _b, _d, _e, _f, _g, _h, _j;
2717
+ var result = new Map();
2718
+ try {
2719
+ for (var _k = __values(embeds !== null && embeds !== void 0 ? embeds : []), _l = _k.next(); !_l.done; _l = _k.next()) {
2720
+ var embed = _l.value;
2721
+ if (!((_b = embed.position) === null || _b === void 0 ? void 0 : _b.overlayPosition))
2722
+ continue;
2723
+ if (((_d = embed.spec) === null || _d === void 0 ? void 0 : _d.type) !== "image")
2724
+ continue;
2725
+ var overlay = embed.position.overlayPosition;
2726
+ var placement = {
2727
+ kind: "embed",
2728
+ imageUrl: embed.spec.imageUrl,
2729
+ rowIndex: overlay.anchorCell.rowIndex,
2730
+ columnIndex: overlay.anchorCell.columnIndex,
2731
+ offsetX: (_e = overlay.offsetXPixels) !== null && _e !== void 0 ? _e : 0,
2732
+ offsetY: (_f = overlay.offsetYPixels) !== null && _f !== void 0 ? _f : 0,
2733
+ width: (_g = overlay.widthPixels) !== null && _g !== void 0 ? _g : 120,
2734
+ height: (_h = overlay.heightPixels) !== null && _h !== void 0 ? _h : 120,
2735
+ };
2736
+ var list = (_j = result.get(embed.position.sheetId)) !== null && _j !== void 0 ? _j : [];
2737
+ list.push(placement);
2738
+ result.set(embed.position.sheetId, list);
2739
+ }
2740
+ }
2741
+ catch (e_31_1) { e_31 = { error: e_31_1 }; }
2742
+ finally {
2743
+ try {
2744
+ if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
2745
+ }
2746
+ finally { if (e_31) throw e_31.error; }
2747
+ }
2748
+ return result;
2749
+ };
2750
+ var groupTextBoxesBySheet = function (embeds) {
2751
+ var e_32, _a;
2752
+ var _b, _d, _e, _f, _g, _h, _j;
2753
+ var result = new Map();
2754
+ try {
2755
+ for (var _k = __values(embeds !== null && embeds !== void 0 ? embeds : []), _l = _k.next(); !_l.done; _l = _k.next()) {
2756
+ var embed = _l.value;
2757
+ if (!((_b = embed.position) === null || _b === void 0 ? void 0 : _b.overlayPosition))
2758
+ continue;
2759
+ if (((_d = embed.spec) === null || _d === void 0 ? void 0 : _d.type) !== "textbox")
2760
+ continue;
2761
+ var overlay = embed.position.overlayPosition;
2762
+ var placement = {
2763
+ textBox: embed,
2764
+ rowIndex: overlay.anchorCell.rowIndex,
2765
+ columnIndex: overlay.anchorCell.columnIndex,
2766
+ offsetX: (_e = overlay.offsetXPixels) !== null && _e !== void 0 ? _e : 0,
2767
+ offsetY: (_f = overlay.offsetYPixels) !== null && _f !== void 0 ? _f : 0,
2768
+ width: (_g = overlay.widthPixels) !== null && _g !== void 0 ? _g : 120,
2769
+ height: (_h = overlay.heightPixels) !== null && _h !== void 0 ? _h : 60,
2770
+ };
2771
+ var list = (_j = result.get(embed.position.sheetId)) !== null && _j !== void 0 ? _j : [];
2772
+ list.push(placement);
2773
+ result.set(embed.position.sheetId, list);
2774
+ }
2775
+ }
2776
+ catch (e_32_1) { e_32 = { error: e_32_1 }; }
2777
+ finally {
2778
+ try {
2779
+ if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
2780
+ }
2781
+ finally { if (e_32) throw e_32.error; }
2782
+ }
2783
+ return result;
2784
+ };
2785
+ var groupShapesBySheet = function (embeds) {
2786
+ var e_33, _a;
2787
+ var _b, _d, _e, _f, _g, _h, _j;
2788
+ var result = new Map();
2789
+ try {
2790
+ for (var _k = __values(embeds !== null && embeds !== void 0 ? embeds : []), _l = _k.next(); !_l.done; _l = _k.next()) {
2791
+ var embed = _l.value;
2792
+ if (!((_b = embed.position) === null || _b === void 0 ? void 0 : _b.overlayPosition))
2793
+ continue;
2794
+ if (((_d = embed.spec) === null || _d === void 0 ? void 0 : _d.type) !== "shape")
2795
+ continue;
2796
+ var overlay = embed.position.overlayPosition;
2797
+ var placement = {
2798
+ shape: embed,
2799
+ rowIndex: overlay.anchorCell.rowIndex,
2800
+ columnIndex: overlay.anchorCell.columnIndex,
2801
+ offsetX: (_e = overlay.offsetXPixels) !== null && _e !== void 0 ? _e : 0,
2802
+ offsetY: (_f = overlay.offsetYPixels) !== null && _f !== void 0 ? _f : 0,
2803
+ width: (_g = overlay.widthPixels) !== null && _g !== void 0 ? _g : 120,
2804
+ height: (_h = overlay.heightPixels) !== null && _h !== void 0 ? _h : 60,
2805
+ };
2806
+ var list = (_j = result.get(embed.position.sheetId)) !== null && _j !== void 0 ? _j : [];
2807
+ list.push(placement);
2808
+ result.set(embed.position.sheetId, list);
2809
+ }
2810
+ }
2811
+ catch (e_33_1) { e_33 = { error: e_33_1 }; }
2812
+ finally {
2813
+ try {
2814
+ if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
2815
+ }
2816
+ finally { if (e_33) throw e_33.error; }
2817
+ }
2818
+ return result;
2819
+ };
2820
+ var groupChartsBySheet = function (charts) {
2821
+ var e_34, _a;
2822
+ var _b, _d, _e, _f, _g, _h;
2823
+ var result = new Map();
2824
+ try {
2825
+ for (var _j = __values(charts !== null && charts !== void 0 ? charts : []), _k = _j.next(); !_k.done; _k = _j.next()) {
2826
+ var chart = _k.value;
2827
+ var overlay = (_b = chart.position) === null || _b === void 0 ? void 0 : _b.overlayPosition;
2828
+ if (!overlay)
2829
+ continue;
2830
+ var placement = {
2831
+ chart: chart,
2832
+ rowIndex: overlay.anchorCell.rowIndex,
2833
+ columnIndex: overlay.anchorCell.columnIndex,
2834
+ offsetX: (_d = overlay.offsetXPixels) !== null && _d !== void 0 ? _d : 0,
2835
+ offsetY: (_e = overlay.offsetYPixels) !== null && _e !== void 0 ? _e : 0,
2836
+ width: (_f = overlay.widthPixels) !== null && _f !== void 0 ? _f : 300,
2837
+ height: (_g = overlay.heightPixels) !== null && _g !== void 0 ? _g : 200,
2838
+ };
2839
+ var list = (_h = result.get(chart.position.sheetId)) !== null && _h !== void 0 ? _h : [];
2840
+ list.push(placement);
2841
+ result.set(chart.position.sheetId, list);
2842
+ }
2843
+ }
2844
+ catch (e_34_1) { e_34 = { error: e_34_1 }; }
2845
+ finally {
2846
+ try {
2847
+ if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
2848
+ }
2849
+ finally { if (e_34) throw e_34.error; }
2850
+ }
2851
+ return result;
2852
+ };
2853
+ var groupSlicersBySheet = function (slicers) {
2854
+ var e_35, _a;
2855
+ var _b, _d, _e, _f, _g, _h;
2856
+ var result = new Map();
2857
+ try {
2858
+ for (var _j = __values(slicers !== null && slicers !== void 0 ? slicers : []), _k = _j.next(); !_k.done; _k = _j.next()) {
2859
+ var slicer = _k.value;
2860
+ var overlay = (_b = slicer.position) === null || _b === void 0 ? void 0 : _b.overlayPosition;
2861
+ if (!overlay || typeof slicer.position !== "object")
2862
+ continue;
2863
+ var placement = {
2864
+ slicer: slicer,
2865
+ rowIndex: overlay.anchorCell.rowIndex,
2866
+ columnIndex: overlay.anchorCell.columnIndex,
2867
+ offsetX: (_d = overlay.offsetXPixels) !== null && _d !== void 0 ? _d : 0,
2868
+ offsetY: (_e = overlay.offsetYPixels) !== null && _e !== void 0 ? _e : 0,
2869
+ width: (_f = overlay.widthPixels) !== null && _f !== void 0 ? _f : 200,
2870
+ height: (_g = overlay.heightPixels) !== null && _g !== void 0 ? _g : 200,
2871
+ };
2872
+ var list = (_h = result.get(slicer.position.sheetId)) !== null && _h !== void 0 ? _h : [];
2873
+ list.push(placement);
2874
+ result.set(slicer.position.sheetId, list);
2875
+ }
2876
+ }
2877
+ catch (e_35_1) { e_35 = { error: e_35_1 }; }
2878
+ finally {
2879
+ try {
2880
+ if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
2881
+ }
2882
+ finally { if (e_35) throw e_35.error; }
2883
+ }
2884
+ return result;
2885
+ };
2886
+ var buildConditionalFormattingXml = function (_a) {
2887
+ var e_36, _b;
2888
+ var _d, _e, _f;
2889
+ var conditionalFormats = _a.conditionalFormats, sheetId = _a.sheetId, styleBuilder = _a.styleBuilder;
2890
+ if (!(conditionalFormats === null || conditionalFormats === void 0 ? void 0 : conditionalFormats.length)) {
2891
+ return "";
2892
+ }
2893
+ var priority = 1;
2894
+ var orderedRules = conditionalFormats
2895
+ .map(function (rule, index) { return ({ rule: rule, index: index }); })
2896
+ .sort(function (left, right) {
2897
+ var leftPriority = left.rule.priority;
2898
+ var rightPriority = right.rule.priority;
2899
+ if (leftPriority == null && rightPriority == null) {
2900
+ return left.index - right.index;
2901
+ }
2902
+ if (leftPriority == null) {
2903
+ return 1;
2904
+ }
2905
+ if (rightPriority == null) {
2906
+ return -1;
2907
+ }
2908
+ if (leftPriority === rightPriority) {
2909
+ return left.index - right.index;
2910
+ }
2911
+ return leftPriority - rightPriority;
2912
+ })
2913
+ .map(function (_a) {
2914
+ var rule = _a.rule;
2915
+ return rule;
2916
+ });
2917
+ var parts = [];
2918
+ try {
2919
+ for (var orderedRules_1 = __values(orderedRules), orderedRules_1_1 = orderedRules_1.next(); !orderedRules_1_1.done; orderedRules_1_1 = orderedRules_1.next()) {
2920
+ var rule = orderedRules_1_1.value;
2921
+ if (rule.enabled === false)
2922
+ continue;
2923
+ var ranges = ((_d = rule.ranges) !== null && _d !== void 0 ? _d : []).filter(function (range) { return range.sheetId === sheetId; });
2924
+ var sqrefParts = ranges
2925
+ .map(function (range) { return cellRangeToAddress(undefined, range); })
2926
+ .filter(function (ref) { return Boolean(ref); });
2927
+ if (!sqrefParts.length)
2928
+ continue;
2929
+ var baseCellAddress = ranges.length
2930
+ ? (_e = cellToAddress({
2931
+ rowIndex: ranges[0].startRowIndex,
2932
+ columnIndex: ranges[0].startColumnIndex,
2933
+ })) !== null && _e !== void 0 ? _e : undefined
2934
+ : undefined;
2935
+ var basePriority = (_f = rule.priority) !== null && _f !== void 0 ? _f : priority;
2936
+ var cfRulesXml = buildConditionalFormattingRuleXml({
2937
+ rule: rule,
2938
+ styleBuilder: styleBuilder,
2939
+ priority: basePriority,
2940
+ baseCellAddress: baseCellAddress,
2941
+ });
2942
+ if (!(cfRulesXml === null || cfRulesXml === void 0 ? void 0 : cfRulesXml.length))
2943
+ continue;
2944
+ var ruleXmlEntries = Array.isArray(cfRulesXml)
2945
+ ? cfRulesXml
2946
+ : [cfRulesXml];
2947
+ priority = Math.max(priority, basePriority + ruleXmlEntries.length);
2948
+ parts.push("<conditionalFormatting sqref=\"".concat(sqrefParts.join(" "), "\">").concat(ruleXmlEntries.join(""), "</conditionalFormatting>"));
2949
+ }
2950
+ }
2951
+ catch (e_36_1) { e_36 = { error: e_36_1 }; }
2952
+ finally {
2953
+ try {
2954
+ if (orderedRules_1_1 && !orderedRules_1_1.done && (_b = orderedRules_1.return)) _b.call(orderedRules_1);
2955
+ }
2956
+ finally { if (e_36) throw e_36.error; }
2957
+ }
2958
+ return parts.join("");
2959
+ };
2960
+ // Lazy-loaded XMLBuilder for re-serializing opaque cfRule subtrees
2961
+ // (colorScale/dataBar/iconSet) captured from the source xlsx during import.
2962
+ var _cfChildBuilder = null;
2963
+ var getCfChildBuilder = function () {
2964
+ if (_cfChildBuilder)
2965
+ return _cfChildBuilder;
2966
+ // Defer the require so this module stays tree-shakeable when the cf
2967
+ // passthrough path isn't exercised.
2968
+ var XMLBuilder = require("fast-xml-parser").XMLBuilder;
2969
+ _cfChildBuilder = new XMLBuilder({
2970
+ ignoreAttributes: false,
2971
+ attributesGroupName: "a$",
2972
+ textNodeName: "t$",
2973
+ suppressEmptyNode: true,
2974
+ format: false,
2975
+ });
2976
+ return _cfChildBuilder;
2977
+ };
2978
+ var buildXlsxSourceCfRuleXml = function (rule, styleBuilder, priority) {
2979
+ var _a, _b, _d, _e, _f, _g, _h;
2980
+ // Round-trip path for imported rules: build the cfRule XML directly from
2981
+ // the verbatim source attrs/formulas in `xlsxSource`. Preserves the
2982
+ // original cfRule type, operator, formula text, and `text`/`timePeriod`/
2983
+ // `rank`/`percent`/`aboveAverage`/etc. attributes that the synthesizer
2984
+ // would otherwise drop or rewrite.
2985
+ var src = rule.xlsxSource;
2986
+ if (!(src === null || src === void 0 ? void 0 : src.type))
2987
+ return undefined;
2988
+ // Format → dxfId via the existing CellFormat path. We pull the format from
2989
+ // whichever rule shape currently holds it (booleanRule/topBottomRule/
2990
+ // distinctRule) — the import always populates one of these alongside
2991
+ // xlsxSource for non-colorScale rules, so we get a faithful dxfId.
2992
+ var format = (_e = (_b = (_a = rule.booleanRule) === null || _a === void 0 ? void 0 : _a.format) !== null && _b !== void 0 ? _b : (_d = rule.topBottomRule) === null || _d === void 0 ? void 0 : _d.format) !== null && _e !== void 0 ? _e : (_f = rule.distinctRule) === null || _f === void 0 ? void 0 : _f.format;
2993
+ var dxfId = format !== undefined
2994
+ ? styleBuilder.registerDifferentialFormat(format)
2995
+ : undefined;
2996
+ var stopIfTrueAttr = rule.stopIfTrue ? ' stopIfTrue="1"' : "";
2997
+ var attrs = ["type=\"".concat(src.type, "\"")];
2998
+ if (dxfId != null) {
2999
+ attrs.push("dxfId=\"".concat(dxfId, "\""));
3000
+ }
3001
+ attrs.push("priority=\"".concat(priority, "\""));
3002
+ if (src.operator) {
3003
+ attrs.push("operator=\"".concat(src.operator, "\""));
3004
+ }
3005
+ if (src.text !== undefined) {
3006
+ attrs.push("text=\"".concat(escapeXmlAttr(src.text), "\""));
3007
+ }
3008
+ if (src.timePeriod) {
3009
+ attrs.push("timePeriod=\"".concat(src.timePeriod, "\""));
3010
+ }
3011
+ if (typeof src.rank === "number") {
3012
+ attrs.push("rank=\"".concat(src.rank, "\""));
3013
+ }
3014
+ if (src.percent) {
3015
+ attrs.push("percent=\"1\"");
3016
+ }
3017
+ if (src.bottom) {
3018
+ attrs.push("bottom=\"1\"");
3019
+ }
3020
+ if (src.aboveAverage === false) {
3021
+ attrs.push("aboveAverage=\"0\"");
3022
+ }
3023
+ if (src.equalAverage) {
3024
+ attrs.push("equalAverage=\"1\"");
3025
+ }
3026
+ if (typeof src.stdDev === "number") {
3027
+ attrs.push("stdDev=\"".concat(src.stdDev, "\""));
3028
+ }
3029
+ if (rule.stopIfTrue) {
3030
+ // already added via stopIfTrueAttr below — placeholder kept to mirror
3031
+ // intent if attr ordering changes
3032
+ }
3033
+ var formulasXml = (_h = (_g = src.formulas) === null || _g === void 0 ? void 0 : _g.map(function (f) { return "<formula>".concat(escapeXmlText(f), "</formula>"); }).join("")) !== null && _h !== void 0 ? _h : "";
3034
+ // Re-emit any opaque child subtrees (colorScale/dataBar/iconSet) captured
3035
+ // verbatim during import. These elements have rich structure (cfvo stops,
3036
+ // colors, value thresholds, icon set IDs) that the high-level model
3037
+ // can't fully represent — the only way to round-trip them losslessly is
3038
+ // to serialize the parsed XML back as-is.
3039
+ var builder = src.colorScale || src.dataBar || src.iconSet
3040
+ ? getCfChildBuilder()
3041
+ : null;
3042
+ var childXmlParts = [];
3043
+ if (src.colorScale && builder) {
3044
+ childXmlParts.push(builder.build({ colorScale: src.colorScale }));
3045
+ }
3046
+ if (src.dataBar && builder) {
3047
+ childXmlParts.push(builder.build({ dataBar: src.dataBar }));
3048
+ }
3049
+ if (src.iconSet && builder) {
3050
+ childXmlParts.push(builder.build({ iconSet: src.iconSet }));
3051
+ }
3052
+ return "<cfRule ".concat(attrs.join(" ")).concat(stopIfTrueAttr, ">").concat(formulasXml).concat(childXmlParts.join(""), "</cfRule>");
3053
+ };
3054
+ var buildConditionalFormattingRuleXml = function (_a) {
3055
+ var _b;
3056
+ var rule = _a.rule, styleBuilder = _a.styleBuilder, priority = _a.priority, baseCellAddress = _a.baseCellAddress;
3057
+ // Round-trip via xlsxSource when present (imported rules). Falls through
3058
+ // to synthesizer for rules without source metadata (UI-created).
3059
+ if ((_b = rule.xlsxSource) === null || _b === void 0 ? void 0 : _b.type) {
3060
+ var xml = buildXlsxSourceCfRuleXml(rule, styleBuilder, priority);
3061
+ if (xml)
3062
+ return xml;
3063
+ }
3064
+ var rules = [];
3065
+ var baseCell = baseCellAddress !== null && baseCellAddress !== void 0 ? baseCellAddress : undefined;
3066
+ var stopIfTrueAttr = rule.stopIfTrue ? ' stopIfTrue="1"' : "";
3067
+ var escapeFormulaText = function (value) { return value.replace(/"/g, '""'); };
3068
+ var buildCellIsRule = function (dxfId, operator, formula1, formula2) {
3069
+ var parts = [
3070
+ "<cfRule type=\"cellIs\" operator=\"".concat(operator, "\" dxfId=\"").concat(dxfId, "\" priority=\"").concat(priority + rules.length, "\"").concat(stopIfTrueAttr, ">"),
3071
+ "<formula>".concat(escapeXmlText(formula1), "</formula>"),
3072
+ ];
3073
+ if (formula2) {
3074
+ parts.push("<formula>".concat(escapeXmlText(formula2), "</formula>"));
3075
+ }
3076
+ parts.push("</cfRule>");
3077
+ return parts.join("");
3078
+ };
3079
+ var buildExpressionRule = function (dxfId, formula) {
3080
+ return "<cfRule type=\"expression\" dxfId=\"".concat(dxfId, "\" priority=\"").concat(priority + rules.length, "\"").concat(stopIfTrueAttr, "><formula>").concat(escapeXmlText(formula), "</formula></cfRule>");
3081
+ };
3082
+ var buildBooleanRuleXml = function () {
3083
+ var _a, _b, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _s;
3084
+ var booleanRule = rule.booleanRule;
3085
+ if (!((_a = booleanRule === null || booleanRule === void 0 ? void 0 : booleanRule.condition) === null || _a === void 0 ? void 0 : _a.type)) {
3086
+ return undefined;
3087
+ }
3088
+ var dxfId = styleBuilder.registerDifferentialFormat(booleanRule.format);
3089
+ if (dxfId == null)
3090
+ return undefined;
3091
+ var condition = booleanRule.condition;
3092
+ var values = (_b = condition.values) !== null && _b !== void 0 ? _b : [];
3093
+ if (condition.type === "CUSTOM_FORMULA") {
3094
+ var formula = (_f = (_e = (_d = condition.values) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.userEnteredValue) !== null && _f !== void 0 ? _f : booleanRule.formula;
3095
+ if (!formula)
3096
+ return undefined;
3097
+ var cleanedFormula = stripFormula(formula);
3098
+ return buildExpressionRule(dxfId, cleanedFormula);
3099
+ }
3100
+ if (condition.type === "NUMBER_ABOVE_AVERAGE" ||
3101
+ condition.type === "NUMBER_BELOW_AVERAGE") {
3102
+ var attrs = [
3103
+ "type=\"aboveAverage\"",
3104
+ "dxfId=\"".concat(dxfId, "\""),
3105
+ "priority=\"".concat(priority + rules.length, "\""),
3106
+ ];
3107
+ if (rule.stopIfTrue) {
3108
+ attrs.push("stopIfTrue=\"1\"");
3109
+ }
3110
+ if (condition.type === "NUMBER_BELOW_AVERAGE") {
3111
+ attrs.push("aboveAverage=\"0\"");
3112
+ }
3113
+ return "<cfRule ".concat(attrs.join(" "), "/>");
3114
+ }
3115
+ if (condition.type === "ERROR" || condition.type === "NOT_ERROR") {
3116
+ var type = condition.type === "ERROR" ? "containsErrors" : "notContainsErrors";
3117
+ return "<cfRule type=\"".concat(type, "\" dxfId=\"").concat(dxfId, "\" priority=\"").concat(priority + rules.length, "\"").concat(stopIfTrueAttr, "/>");
3118
+ }
3119
+ if (condition.type === "DATE_TODAY" ||
3120
+ condition.type === "DATE_YESTERDAY" ||
3121
+ condition.type === "DATE_TOMORROW" ||
3122
+ condition.type === "DATE_LAST_7_DAYS" ||
3123
+ condition.type === "DATE_LAST_WEEK" ||
3124
+ condition.type === "DATE_THIS_WEEK" ||
3125
+ condition.type === "DATE_NEXT_WEEK" ||
3126
+ condition.type === "DATE_LAST_MONTH" ||
3127
+ condition.type === "DATE_THIS_MONTH" ||
3128
+ condition.type === "DATE_NEXT_MONTH") {
3129
+ if (!baseCell)
3130
+ return undefined;
3131
+ var timePeriodMap = {
3132
+ DATE_TODAY: "today",
3133
+ DATE_YESTERDAY: "yesterday",
3134
+ DATE_TOMORROW: "tomorrow",
3135
+ DATE_LAST_7_DAYS: "last7Days",
3136
+ DATE_LAST_WEEK: "lastWeek",
3137
+ DATE_THIS_WEEK: "thisWeek",
3138
+ DATE_NEXT_WEEK: "nextWeek",
3139
+ DATE_LAST_MONTH: "lastMonth",
3140
+ DATE_THIS_MONTH: "thisMonth",
3141
+ DATE_NEXT_MONTH: "nextMonth",
3142
+ };
3143
+ var normalizedCell = "INT(".concat(baseCell, ")");
3144
+ var weekStart = "TODAY()-WEEKDAY(TODAY(),2)+1";
3145
+ var periodFormulaMap = {
3146
+ DATE_TODAY: "".concat(normalizedCell, "=TODAY()"),
3147
+ DATE_YESTERDAY: "".concat(normalizedCell, "=TODAY()-1"),
3148
+ DATE_TOMORROW: "".concat(normalizedCell, "=TODAY()+1"),
3149
+ DATE_LAST_7_DAYS: "AND(".concat(normalizedCell, ">=TODAY()-6,").concat(normalizedCell, "<=TODAY())"),
3150
+ DATE_THIS_WEEK: "AND(".concat(normalizedCell, ">=").concat(weekStart, ",").concat(normalizedCell, "<=").concat(weekStart, "+6)"),
3151
+ DATE_LAST_WEEK: "AND(".concat(normalizedCell, ">=").concat(weekStart, "-7,").concat(normalizedCell, "<=").concat(weekStart, "-1)"),
3152
+ DATE_NEXT_WEEK: "AND(".concat(normalizedCell, ">=").concat(weekStart, "+7,").concat(normalizedCell, "<=").concat(weekStart, "+13)"),
3153
+ DATE_THIS_MONTH: "AND(".concat(normalizedCell, ">=EOMONTH(TODAY(),-1)+1,").concat(normalizedCell, "<=EOMONTH(TODAY(),0))"),
3154
+ DATE_LAST_MONTH: "AND(".concat(normalizedCell, ">=EOMONTH(TODAY(),-2)+1,").concat(normalizedCell, "<=EOMONTH(TODAY(),-1))"),
3155
+ DATE_NEXT_MONTH: "AND(".concat(normalizedCell, ">=EOMONTH(TODAY(),0)+1,").concat(normalizedCell, "<=EOMONTH(TODAY(),1))"),
3156
+ };
3157
+ var timePeriod = timePeriodMap[condition.type];
3158
+ var periodFormula = periodFormulaMap[condition.type];
3159
+ if (!timePeriod || !periodFormula)
3160
+ return undefined;
3161
+ return "<cfRule type=\"timePeriod\" timePeriod=\"".concat(timePeriod, "\" dxfId=\"").concat(dxfId, "\" priority=\"").concat(priority + rules.length, "\"").concat(stopIfTrueAttr, "><formula>").concat(escapeXmlText(periodFormula), "</formula></cfRule>");
3162
+ }
3163
+ if (condition.type === "TEXT_EQ" || condition.type === "TEXT_NOT_EQ") {
3164
+ var raw = (_h = (_g = values[0]) === null || _g === void 0 ? void 0 : _g.userEnteredValue) !== null && _h !== void 0 ? _h : "";
3165
+ if (!raw)
3166
+ return undefined;
3167
+ var op = condition.type === "TEXT_EQ" ? "equal" : "notEqual";
3168
+ var text = "\"".concat(escapeFormulaText(raw), "\"");
3169
+ return buildCellIsRule(dxfId, op, text);
3170
+ }
3171
+ if (condition.type === "NUMBER_BETWEEN" ||
3172
+ condition.type === "NUMBER_NOT_BETWEEN" ||
3173
+ condition.type === "NUMBER_EQ" ||
3174
+ condition.type === "NUMBER_NOT_EQ" ||
3175
+ condition.type === "NUMBER_GREATER" ||
3176
+ condition.type === "NUMBER_GREATER_THAN_EQ" ||
3177
+ condition.type === "NUMBER_LESS" ||
3178
+ condition.type === "NUMBER_LESS_THAN_EQ") {
3179
+ var firstRaw = (_k = (_j = values[0]) === null || _j === void 0 ? void 0 : _j.userEnteredValue) !== null && _k !== void 0 ? _k : "";
3180
+ if (!firstRaw)
3181
+ return undefined;
3182
+ var secondRaw = (_m = (_l = values[1]) === null || _l === void 0 ? void 0 : _l.userEnteredValue) !== null && _m !== void 0 ? _m : "";
3183
+ var operatorMap = {
3184
+ NUMBER_BETWEEN: "between",
3185
+ NUMBER_NOT_BETWEEN: "notBetween",
3186
+ NUMBER_EQ: "equal",
3187
+ NUMBER_NOT_EQ: "notEqual",
3188
+ NUMBER_GREATER: "greaterThan",
3189
+ NUMBER_GREATER_THAN_EQ: "greaterThanOrEqual",
3190
+ NUMBER_LESS: "lessThan",
3191
+ NUMBER_LESS_THAN_EQ: "lessThanOrEqual",
3192
+ };
3193
+ var operator = operatorMap[condition.type];
3194
+ var first = stripFormula(firstRaw);
3195
+ var second = stripFormula(secondRaw);
3196
+ if ((operator === "between" || operator === "notBetween") && !secondRaw) {
3197
+ return undefined;
3198
+ }
3199
+ return buildCellIsRule(dxfId, operator, first, operator === "between" || operator === "notBetween"
3200
+ ? second
3201
+ : undefined);
3202
+ }
3203
+ if (condition.type === "DATE_EQ" ||
3204
+ condition.type === "DATE_NOT_EQ" ||
3205
+ condition.type === "DATE_BEFORE" ||
3206
+ condition.type === "DATE_AFTER" ||
3207
+ condition.type === "DATE_ON_OR_BEFORE" ||
3208
+ condition.type === "DATE_ON_OR_AFTER" ||
3209
+ condition.type === "DATE_BETWEEN" ||
3210
+ condition.type === "DATE_NOT_BETWEEN") {
3211
+ var firstRaw = (_p = (_o = values[0]) === null || _o === void 0 ? void 0 : _o.userEnteredValue) !== null && _p !== void 0 ? _p : "";
3212
+ if (!firstRaw)
3213
+ return undefined;
3214
+ var secondRaw = (_s = (_q = values[1]) === null || _q === void 0 ? void 0 : _q.userEnteredValue) !== null && _s !== void 0 ? _s : "";
3215
+ var operatorMap = {
3216
+ DATE_EQ: "equal",
3217
+ DATE_NOT_EQ: "notEqual",
3218
+ DATE_BEFORE: "lessThan",
3219
+ DATE_AFTER: "greaterThan",
3220
+ DATE_ON_OR_BEFORE: "lessThanOrEqual",
3221
+ DATE_ON_OR_AFTER: "greaterThanOrEqual",
3222
+ DATE_BETWEEN: "between",
3223
+ DATE_NOT_BETWEEN: "notBetween",
3224
+ };
3225
+ var normalizeDateValue = function (raw) {
3226
+ var trimmed = raw.trim();
3227
+ if (!trimmed)
3228
+ return "";
3229
+ if (trimmed.startsWith("=")) {
3230
+ return stripFormula(trimmed);
3231
+ }
3232
+ if (!isNaN(Number(trimmed))) {
3233
+ return trimmed;
3234
+ }
3235
+ return "DATEVALUE(\"".concat(escapeFormulaText(trimmed), "\")");
3236
+ };
3237
+ var first = normalizeDateValue(firstRaw);
3238
+ var second = normalizeDateValue(secondRaw);
3239
+ var operator = operatorMap[condition.type];
3240
+ if ((operator === "between" || operator === "notBetween") && !secondRaw) {
3241
+ return undefined;
3242
+ }
3243
+ return buildCellIsRule(dxfId, operator, first, operator === "between" || operator === "notBetween"
3244
+ ? second
3245
+ : undefined);
3246
+ }
3247
+ if (!baseCell)
3248
+ return undefined;
3249
+ var buildExpressionFormula = function () {
3250
+ var _a, _b, _d, _e;
3251
+ var raw = (_b = (_a = values[0]) === null || _a === void 0 ? void 0 : _a.userEnteredValue) !== null && _b !== void 0 ? _b : "";
3252
+ var text = raw ? "\"".concat(escapeFormulaText(raw), "\"") : '""';
3253
+ switch (condition.type) {
3254
+ case "TEXT_CONTAINS":
3255
+ return raw ? "ISNUMBER(SEARCH(".concat(text, ",").concat(baseCell, "))") : undefined;
3256
+ case "TEXT_NOT_CONTAINS":
3257
+ return raw ? "ISERROR(SEARCH(".concat(text, ",").concat(baseCell, "))") : undefined;
3258
+ case "TEXT_STARTS_WITH":
3259
+ return raw ? "LEFT(".concat(baseCell, ",LEN(").concat(text, "))=").concat(text) : undefined;
3260
+ case "TEXT_ENDS_WITH":
3261
+ return raw ? "RIGHT(".concat(baseCell, ",LEN(").concat(text, "))=").concat(text) : undefined;
3262
+ case "TEXT_IS_EMAIL":
3263
+ return "AND(ISNUMBER(SEARCH(\"@\",".concat(baseCell, ")),ISNUMBER(SEARCH(\".\",").concat(baseCell, ")))");
3264
+ case "TEXT_IS_URL":
3265
+ return "OR(LEFT(".concat(baseCell, ",7)=\"http://\",LEFT(").concat(baseCell, ",8)=\"https://\")");
3266
+ case "BLANK":
3267
+ return "".concat(baseCell, "=\"\"");
3268
+ case "NOT_BLANK":
3269
+ return "".concat(baseCell, "<>\"\"");
3270
+ case "BOOLEAN":
3271
+ return "OR(".concat(baseCell, "=TRUE,").concat(baseCell, "=FALSE)");
3272
+ case "DATE_IS_VALID":
3273
+ return "ISNUMBER(".concat(baseCell, ")");
3274
+ case "NUMBER_GREATER_THAN_PREVIOUS":
3275
+ return "IFERROR(".concat(baseCell, ">INDIRECT(\"R[-1]C\",FALSE),TRUE)");
3276
+ case "NUMBER_GREATER_THAN_EQ_PREVIOUS":
3277
+ return "IFERROR(".concat(baseCell, ">=INDIRECT(\"R[-1]C\",FALSE),TRUE)");
3278
+ case "NUMBER_LESS_THAN_PREVIOUS":
3279
+ return "IFERROR(".concat(baseCell, "<INDIRECT(\"R[-1]C\",FALSE),TRUE)");
3280
+ case "NUMBER_LESS_THAN_EQ_PREVIOUS":
3281
+ return "IFERROR(".concat(baseCell, "<=INDIRECT(\"R[-1]C\",FALSE),TRUE)");
3282
+ case "ONE_OF_LIST": {
3283
+ var entries = values
3284
+ .map(function (value) { return value.userEnteredValue; })
3285
+ .filter(function (value) { return typeof value === "string"; });
3286
+ if (!entries.length)
3287
+ return undefined;
3288
+ var conditions = entries.map(function (entry) {
3289
+ if (entry.startsWith("=")) {
3290
+ return "".concat(baseCell, "=").concat(stripFormula(entry));
3291
+ }
3292
+ if (!isNaN(Number(entry))) {
3293
+ return "".concat(baseCell, "=").concat(entry);
3294
+ }
3295
+ return "".concat(baseCell, "=\"").concat(escapeFormulaText(entry), "\"");
3296
+ });
3297
+ return "OR(".concat(conditions.join(","), ")");
3298
+ }
3299
+ case "ONE_OF_RANGE": {
3300
+ var rangeRef = (_e = (_d = values[0]) === null || _d === void 0 ? void 0 : _d.userEnteredValue) !== null && _e !== void 0 ? _e : "";
3301
+ if (!rangeRef)
3302
+ return undefined;
3303
+ return "COUNTIF(".concat(stripFormula(rangeRef), ",").concat(baseCell, ")>0");
3304
+ }
3305
+ default:
3306
+ return undefined;
3307
+ }
3308
+ };
3309
+ var expression = buildExpressionFormula();
3310
+ return expression ? buildExpressionRule(dxfId, expression) : undefined;
3311
+ };
3312
+ var buildGradientRuleXml = function () {
3313
+ var gradientRule = rule.gradientRule;
3314
+ if (!gradientRule)
3315
+ return undefined;
3316
+ var points = [
3317
+ gradientRule.minpoint,
3318
+ gradientRule.midpoint,
3319
+ gradientRule.maxpoint,
3320
+ ].filter(Boolean);
3321
+ if (!points.length)
3322
+ return undefined;
3323
+ var typeMap = {
3324
+ MIN: "min",
3325
+ MAX: "max",
3326
+ NUMBER: "num",
3327
+ PERCENT: "percent",
3328
+ PERCENTILE: "percentile",
3329
+ };
3330
+ var cfvos = [];
3331
+ var colors = [];
3332
+ points.forEach(function (point) {
3333
+ var _a;
3334
+ if (!(point === null || point === void 0 ? void 0 : point.type) || !point.color)
3335
+ return;
3336
+ var type = (_a = typeMap[String(point.type).toUpperCase()]) !== null && _a !== void 0 ? _a : "num";
3337
+ var valueAttr = point.value !== undefined && point.value !== null
3338
+ ? " val=\"".concat(escapeXmlAttr(String(point.value)), "\"")
3339
+ : "";
3340
+ cfvos.push("<cfvo type=\"".concat(type, "\"").concat(valueAttr, "/>"));
3341
+ var colorAttr = serializeColorXml(point.color);
3342
+ if (colorAttr) {
3343
+ colors.push("<color ".concat(colorAttr, "/>"));
3344
+ }
3345
+ });
3346
+ if (!cfvos.length || !colors.length)
3347
+ return undefined;
3348
+ return "<cfRule type=\"colorScale\" priority=\"".concat(priority + rules.length, "\"><colorScale>").concat(cfvos.join("")).concat(colors.join(""), "</colorScale></cfRule>");
3349
+ };
3350
+ var buildTopBottomRuleXml = function () {
3351
+ var topBottomRule = rule.topBottomRule;
3352
+ if (!topBottomRule)
3353
+ return undefined;
3354
+ var dxfId = styleBuilder.registerDifferentialFormat(topBottomRule.format);
3355
+ if (dxfId == null)
3356
+ return undefined;
3357
+ var rank = Number.isFinite(topBottomRule.rank)
3358
+ ? Math.max(1, topBottomRule.rank)
3359
+ : 10;
3360
+ var attrs = [
3361
+ "type=\"top10\"",
3362
+ "dxfId=\"".concat(dxfId, "\""),
3363
+ "priority=\"".concat(priority + rules.length, "\""),
3364
+ "rank=\"".concat(rank, "\""),
3365
+ ];
3366
+ if (rule.stopIfTrue) {
3367
+ attrs.push("stopIfTrue=\"1\"");
3368
+ }
3369
+ if (topBottomRule.isPercent) {
3370
+ attrs.push("percent=\"1\"");
3371
+ }
3372
+ if (topBottomRule.type === "BOTTOM") {
3373
+ attrs.push("bottom=\"1\"");
3374
+ }
3375
+ return "<cfRule ".concat(attrs.join(" "), "/>");
3376
+ };
3377
+ var buildDistinctRuleXml = function () {
3378
+ var distinctRule = rule.distinctRule;
3379
+ if (!distinctRule)
3380
+ return undefined;
3381
+ var dxfId = styleBuilder.registerDifferentialFormat(distinctRule.format);
3382
+ if (dxfId == null)
3383
+ return undefined;
3384
+ var type = distinctRule.type === "UNIQUE" ? "uniqueValues" : "duplicateValues";
3385
+ return "<cfRule type=\"".concat(type, "\" dxfId=\"").concat(dxfId, "\" priority=\"").concat(priority + rules.length, "\"").concat(stopIfTrueAttr, "/>");
3386
+ };
3387
+ var cfThresholdTypeMap = {
3388
+ MIN: "min",
3389
+ MAX: "max",
3390
+ NUMBER: "num",
3391
+ PERCENT: "percent",
3392
+ PERCENTILE: "percentile",
3393
+ FORMULA: "formula",
3394
+ };
3395
+ var buildCfvo = function (t) {
3396
+ var _a;
3397
+ if (!(t === null || t === void 0 ? void 0 : t.type))
3398
+ return "";
3399
+ var type = (_a = cfThresholdTypeMap[String(t.type).toUpperCase()]) !== null && _a !== void 0 ? _a : "num";
3400
+ var valueAttr = t.value !== undefined && t.value !== null
3401
+ ? " val=\"".concat(escapeXmlAttr(String(t.value)), "\"")
3402
+ : "";
3403
+ return "<cfvo type=\"".concat(type, "\"").concat(valueAttr, "/>");
3404
+ };
3405
+ var buildIconSetRuleXml = function () {
3406
+ var iconSetRule = rule.iconSetRule;
3407
+ if (!iconSetRule)
3408
+ return undefined;
3409
+ // OOXML expects (iconCount) cfvos with a leading 0% min stop. Our engine
3410
+ // model keeps only the (iconCount - 1) user-meaningful thresholds, so we
3411
+ // prepend a synthetic 0% cfvo on export.
3412
+ var cfvos = __spreadArray([
3413
+ "<cfvo type=\"percent\" val=\"0\"/>"
3414
+ ], __read(iconSetRule.thresholds.map(buildCfvo)), false).join("");
3415
+ var attrs = __spreadArray(__spreadArray([
3416
+ "iconSet=\"".concat(iconSetRule.iconSet, "\"")
3417
+ ], __read((iconSetRule.reverse ? ["reverse=\"1\""] : [])), false), __read((iconSetRule.showValue === false ? ["showValue=\"0\""] : [])), false);
3418
+ return "<cfRule type=\"iconSet\" priority=\"".concat(priority + rules.length, "\"").concat(stopIfTrueAttr, "><iconSet ").concat(attrs.join(" "), ">").concat(cfvos, "</iconSet></cfRule>");
3419
+ };
3420
+ var buildDataBarRuleXml = function () {
3421
+ var dataBarRule = rule.dataBarRule;
3422
+ if (!dataBarRule)
3423
+ return undefined;
3424
+ var cfvos = buildCfvo(dataBarRule.minpoint) + buildCfvo(dataBarRule.maxpoint);
3425
+ var colorAttr = serializeColorXml(dataBarRule.color);
3426
+ if (!colorAttr)
3427
+ return undefined;
3428
+ var showValueAttr = dataBarRule.showValue === false ? " showValue=\"0\"" : "";
3429
+ return "<cfRule type=\"dataBar\" priority=\"".concat(priority + rules.length, "\"").concat(stopIfTrueAttr, "><dataBar").concat(showValueAttr, ">").concat(cfvos, "<color ").concat(colorAttr, "/></dataBar></cfRule>");
3430
+ };
3431
+ var booleanXml = buildBooleanRuleXml();
3432
+ if (booleanXml)
3433
+ rules.push(booleanXml);
3434
+ var gradientXml = buildGradientRuleXml();
3435
+ if (gradientXml)
3436
+ rules.push(gradientXml);
3437
+ var topBottomXml = buildTopBottomRuleXml();
3438
+ if (topBottomXml)
3439
+ rules.push(topBottomXml);
3440
+ var distinctXml = buildDistinctRuleXml();
3441
+ if (distinctXml)
3442
+ rules.push(distinctXml);
3443
+ var iconSetXml = buildIconSetRuleXml();
3444
+ if (iconSetXml)
3445
+ rules.push(iconSetXml);
3446
+ var dataBarXml = buildDataBarRuleXml();
3447
+ if (dataBarXml)
3448
+ rules.push(dataBarXml);
3449
+ return rules.length ? rules : undefined;
3450
+ };
3451
+ var buildDrawingParts = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
3452
+ var anchors, relationships, media, imageIndex, chartIndex, pictureId, frameId, chartEntries, charts_1, charts_1_1, placement, chartXml, relId, slicers_1, slicers_1_1, placement, textBoxes_1, textBoxes_1_1, placement, shapes_1, shapes_1_1, placement, placements_1, placements_1_1, placement, dataUrl, buffer, mediaPath, relId, e_37_1, drawingXml;
3453
+ var e_38, _d, e_39, _e, e_40, _f, e_41, _g, e_37, _h;
3454
+ var placements = _b.placements, textBoxes = _b.textBoxes, _j = _b.shapes, shapes = _j === void 0 ? [] : _j, startImageIndex = _b.startImageIndex, startChartIndex = _b.startChartIndex, charts = _b.charts, slicers = _b.slicers, sheet = _b.sheet, sheetNameById = _b.sheetNameById;
3455
+ return __generator(this, function (_k) {
3456
+ switch (_k.label) {
3457
+ case 0:
3458
+ if (!placements.length &&
3459
+ !textBoxes.length &&
3460
+ !shapes.length &&
3461
+ !charts.length &&
3462
+ !slicers.length)
3463
+ return [2 /*return*/, null];
3464
+ anchors = [];
3465
+ relationships = new RelationshipsBuilder();
3466
+ media = [];
3467
+ imageIndex = startImageIndex;
3468
+ chartIndex = startChartIndex;
3469
+ pictureId = 1;
3470
+ frameId = 1;
3471
+ chartEntries = [];
3472
+ try {
3473
+ for (charts_1 = __values(charts), charts_1_1 = charts_1.next(); !charts_1_1.done; charts_1_1 = charts_1.next()) {
3474
+ placement = charts_1_1.value;
3475
+ chartXml = buildChartXml(placement.chart, sheetNameById);
3476
+ if (!chartXml)
3477
+ continue;
3478
+ relId = relationships.add(CHART_REL_TYPE, "../charts/chart".concat(chartIndex, ".xml"));
3479
+ anchors.push(createChartAnchor({
3480
+ sheet: sheet,
3481
+ placement: placement,
3482
+ relId: relId,
3483
+ frameId: frameId,
3484
+ }));
3485
+ chartEntries.push({
3486
+ path: "xl/charts/chart".concat(chartIndex, ".xml"),
3487
+ xml: chartXml,
3488
+ });
3489
+ chartIndex += 1;
3490
+ frameId += 1;
3491
+ }
3492
+ }
3493
+ catch (e_38_1) { e_38 = { error: e_38_1 }; }
3494
+ finally {
3495
+ try {
3496
+ if (charts_1_1 && !charts_1_1.done && (_d = charts_1.return)) _d.call(charts_1);
3497
+ }
3498
+ finally { if (e_38) throw e_38.error; }
3499
+ }
3500
+ try {
3501
+ for (slicers_1 = __values(slicers), slicers_1_1 = slicers_1.next(); !slicers_1_1.done; slicers_1_1 = slicers_1.next()) {
3502
+ placement = slicers_1_1.value;
3503
+ anchors.push(createSlicerAnchor({
3504
+ sheet: sheet,
3505
+ placement: placement,
3506
+ frameId: frameId,
3507
+ }));
3508
+ frameId += 1;
3509
+ }
3510
+ }
3511
+ catch (e_39_1) { e_39 = { error: e_39_1 }; }
3512
+ finally {
3513
+ try {
3514
+ if (slicers_1_1 && !slicers_1_1.done && (_e = slicers_1.return)) _e.call(slicers_1);
3515
+ }
3516
+ finally { if (e_39) throw e_39.error; }
3517
+ }
3518
+ try {
3519
+ for (textBoxes_1 = __values(textBoxes), textBoxes_1_1 = textBoxes_1.next(); !textBoxes_1_1.done; textBoxes_1_1 = textBoxes_1.next()) {
3520
+ placement = textBoxes_1_1.value;
3521
+ anchors.push(createTextBoxAnchor({
3522
+ sheet: sheet,
3523
+ placement: placement,
3524
+ frameId: frameId,
3525
+ }));
3526
+ frameId += 1;
3527
+ }
3528
+ }
3529
+ catch (e_40_1) { e_40 = { error: e_40_1 }; }
3530
+ finally {
3531
+ try {
3532
+ if (textBoxes_1_1 && !textBoxes_1_1.done && (_f = textBoxes_1.return)) _f.call(textBoxes_1);
3533
+ }
3534
+ finally { if (e_40) throw e_40.error; }
3535
+ }
3536
+ try {
3537
+ for (shapes_1 = __values(shapes), shapes_1_1 = shapes_1.next(); !shapes_1_1.done; shapes_1_1 = shapes_1.next()) {
3538
+ placement = shapes_1_1.value;
3539
+ anchors.push(createShapeAnchor({
3540
+ sheet: sheet,
3541
+ placement: placement,
3542
+ frameId: frameId,
3543
+ }));
3544
+ frameId += 1;
3545
+ }
3546
+ }
3547
+ catch (e_41_1) { e_41 = { error: e_41_1 }; }
3548
+ finally {
3549
+ try {
3550
+ if (shapes_1_1 && !shapes_1_1.done && (_g = shapes_1.return)) _g.call(shapes_1);
3551
+ }
3552
+ finally { if (e_41) throw e_41.error; }
3553
+ }
3554
+ _k.label = 1;
3555
+ case 1:
3556
+ _k.trys.push([1, 6, 7, 8]);
3557
+ placements_1 = __values(placements), placements_1_1 = placements_1.next();
3558
+ _k.label = 2;
3559
+ case 2:
3560
+ if (!!placements_1_1.done) return [3 /*break*/, 5];
3561
+ placement = placements_1_1.value;
3562
+ return [4 /*yield*/, resolveImageDataUrl(placement.imageUrl)];
3563
+ case 3:
3564
+ dataUrl = _k.sent();
3565
+ if (!dataUrl)
3566
+ return [3 /*break*/, 4];
3567
+ buffer = dataUriToBuffer(dataUrl, placement.imageUrl);
3568
+ if (!buffer)
3569
+ return [3 /*break*/, 4];
3570
+ mediaPath = "xl/media/image".concat(imageIndex, ".").concat(buffer.extension);
3571
+ media.push({
3572
+ path: mediaPath,
3573
+ data: buffer.data,
3574
+ extension: buffer.extension,
3575
+ });
3576
+ relId = relationships.add(IMAGE_REL_TYPE, "../media/image".concat(imageIndex, ".").concat(buffer.extension));
3577
+ anchors.push(createTwoCellAnchor({
3578
+ sheet: sheet,
3579
+ placement: placement,
3580
+ relId: relId,
3581
+ pictureId: pictureId,
3582
+ }));
3583
+ imageIndex += 1;
3584
+ pictureId += 1;
3585
+ _k.label = 4;
3586
+ case 4:
3587
+ placements_1_1 = placements_1.next();
3588
+ return [3 /*break*/, 2];
3589
+ case 5: return [3 /*break*/, 8];
3590
+ case 6:
3591
+ e_37_1 = _k.sent();
3592
+ e_37 = { error: e_37_1 };
3593
+ return [3 /*break*/, 8];
3594
+ case 7:
3595
+ try {
3596
+ if (placements_1_1 && !placements_1_1.done && (_h = placements_1.return)) _h.call(placements_1);
3597
+ }
3598
+ finally { if (e_37) throw e_37.error; }
3599
+ return [7 /*endfinally*/];
3600
+ case 8:
3601
+ drawingXml = "".concat(XML_DECLARATION, "<xdr:wsDr xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"").concat(REL_NS, "\">").concat(anchors.join(""), "</xdr:wsDr>");
3602
+ return [2 /*return*/, {
3603
+ xml: drawingXml,
3604
+ relsXml: relationships.toXml(),
3605
+ media: media,
3606
+ charts: chartEntries,
3607
+ nextImageIndex: imageIndex,
3608
+ nextChartIndex: chartIndex,
3609
+ }];
3610
+ }
3611
+ });
3612
+ }); };
3613
+ var createTwoCellAnchor = function (_a) {
3614
+ var _b, _d, _e, _f;
3615
+ var placement = _a.placement, relId = _a.relId, pictureId = _a.pictureId, sheet = _a.sheet;
3616
+ var fromRow = Math.max(0, placement.rowIndex - 1);
3617
+ var fromColumn = Math.max(0, placement.columnIndex - 1);
3618
+ var offsetX = Math.max(0, (_b = placement.offsetX) !== null && _b !== void 0 ? _b : 0);
3619
+ var offsetY = Math.max(0, (_d = placement.offsetY) !== null && _d !== void 0 ? _d : 0);
3620
+ var defaultWidth = placement.kind === "cell" ? getColumnWidthPx(sheet, fromColumn) : 120;
3621
+ var defaultHeight = placement.kind === "cell" ? getRowHeightPx(sheet, fromRow) : 120;
3622
+ var widthPx = Math.max(5, (_e = placement.width) !== null && _e !== void 0 ? _e : defaultWidth);
3623
+ var heightPx = Math.max(5, (_f = placement.height) !== null && _f !== void 0 ? _f : defaultHeight);
3624
+ var toColumn = resolveAnchorEndpoint({
3625
+ startIndex: fromColumn,
3626
+ startOffset: offsetX,
3627
+ span: widthPx,
3628
+ getSize: function (index) { return getColumnWidthPx(sheet, index, true); },
3629
+ });
3630
+ var toRow = resolveAnchorEndpoint({
3631
+ startIndex: fromRow,
3632
+ startOffset: offsetY,
3633
+ span: heightPx,
3634
+ getSize: function (index) { return getRowHeightPx(sheet, index, true); },
3635
+ });
3636
+ var fromXml = "<xdr:from><xdr:col>".concat(fromColumn, "</xdr:col><xdr:colOff>").concat(Math.round(offsetX * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(fromRow, "</xdr:row><xdr:rowOff>").concat(Math.round(offsetY * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:from>");
3637
+ var toXml = "<xdr:to><xdr:col>".concat(toColumn.index, "</xdr:col><xdr:colOff>").concat(Math.round(toColumn.offset * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(toRow.index, "</xdr:row><xdr:rowOff>").concat(Math.round(toRow.offset * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:to>");
3638
+ return "<xdr:twoCellAnchor editAs=\"oneCell\">".concat(fromXml).concat(toXml, "<xdr:pic><xdr:nvPicPr><xdr:cNvPr id=\"").concat(pictureId, "\" name=\"Picture ").concat(pictureId, "\"/><xdr:cNvPicPr/></xdr:nvPicPr><xdr:blipFill><a:blip r:embed=\"").concat(relId, "\"/><a:stretch><a:fillRect/></a:stretch></xdr:blipFill><xdr:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"").concat(Math.round(widthPx * EMUS_PER_PIXEL), "\" cy=\"").concat(Math.round(heightPx * EMUS_PER_PIXEL), "\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic><xdr:clientData/></xdr:twoCellAnchor>");
3639
+ };
3640
+ var createChartAnchor = function (_a) {
3641
+ var _b, _d, _e, _f;
3642
+ var placement = _a.placement, relId = _a.relId, frameId = _a.frameId, sheet = _a.sheet;
3643
+ var fromRow = Math.max(0, placement.rowIndex - 1);
3644
+ var fromColumn = Math.max(0, placement.columnIndex - 1);
3645
+ var offsetX = Math.max(0, (_b = placement.offsetX) !== null && _b !== void 0 ? _b : 0);
3646
+ var offsetY = Math.max(0, (_d = placement.offsetY) !== null && _d !== void 0 ? _d : 0);
3647
+ var widthPx = Math.max(5, (_e = placement.width) !== null && _e !== void 0 ? _e : 300);
3648
+ var heightPx = Math.max(5, (_f = placement.height) !== null && _f !== void 0 ? _f : 200);
3649
+ var toColumn = resolveAnchorEndpoint({
3650
+ startIndex: fromColumn,
3651
+ startOffset: offsetX,
3652
+ span: widthPx,
3653
+ getSize: function (index) { return getColumnWidthPx(sheet, index, true); },
3654
+ });
3655
+ var toRow = resolveAnchorEndpoint({
3656
+ startIndex: fromRow,
3657
+ startOffset: offsetY,
3658
+ span: heightPx,
3659
+ getSize: function (index) { return getRowHeightPx(sheet, index, true); },
3660
+ });
3661
+ var fromXml = "<xdr:from><xdr:col>".concat(fromColumn, "</xdr:col><xdr:colOff>").concat(Math.round(offsetX * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(fromRow, "</xdr:row><xdr:rowOff>").concat(Math.round(offsetY * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:from>");
3662
+ var toXml = "<xdr:to><xdr:col>".concat(toColumn.index, "</xdr:col><xdr:colOff>").concat(Math.round(toColumn.offset * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(toRow.index, "</xdr:row><xdr:rowOff>").concat(Math.round(toRow.offset * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:to>");
3663
+ return "<xdr:twoCellAnchor>".concat(fromXml).concat(toXml, "<xdr:graphicFrame><xdr:nvGraphicFramePr><xdr:cNvPr id=\"").concat(frameId, "\" name=\"Chart ").concat(frameId, "\"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"").concat(Math.round(widthPx * EMUS_PER_PIXEL), "\" cy=\"").concat(Math.round(heightPx * EMUS_PER_PIXEL), "\"/></xdr:xfrm><a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\" xmlns:r=\"").concat(REL_NS, "\" r:id=\"").concat(relId, "\"/></a:graphicData></a:graphic></xdr:graphicFrame><xdr:clientData/></xdr:twoCellAnchor>");
3664
+ };
3665
+ var createSlicerAnchor = function (_a) {
3666
+ var _b, _d, _e, _f;
3667
+ var placement = _a.placement, frameId = _a.frameId, sheet = _a.sheet;
3668
+ var fromRow = Math.max(0, placement.rowIndex - 1);
3669
+ var fromColumn = Math.max(0, placement.columnIndex - 1);
3670
+ var offsetX = Math.max(0, (_b = placement.offsetX) !== null && _b !== void 0 ? _b : 0);
3671
+ var offsetY = Math.max(0, (_d = placement.offsetY) !== null && _d !== void 0 ? _d : 0);
3672
+ var widthPx = Math.max(50, (_e = placement.width) !== null && _e !== void 0 ? _e : 200);
3673
+ var heightPx = Math.max(50, (_f = placement.height) !== null && _f !== void 0 ? _f : 200);
3674
+ var toColumn = resolveAnchorEndpoint({
3675
+ startIndex: fromColumn,
3676
+ startOffset: offsetX,
3677
+ span: widthPx,
3678
+ getSize: function (index) { return getColumnWidthPx(sheet, index, true); },
3679
+ });
3680
+ var toRow = resolveAnchorEndpoint({
3681
+ startIndex: fromRow,
3682
+ startOffset: offsetY,
3683
+ span: heightPx,
3684
+ getSize: function (index) { return getRowHeightPx(sheet, index, true); },
3685
+ });
3686
+ var fromXml = "<xdr:from><xdr:col>".concat(fromColumn, "</xdr:col><xdr:colOff>").concat(Math.round(offsetX * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(fromRow, "</xdr:row><xdr:rowOff>").concat(Math.round(offsetY * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:from>");
3687
+ var toXml = "<xdr:to><xdr:col>".concat(toColumn.index, "</xdr:col><xdr:colOff>").concat(Math.round(toColumn.offset * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(toRow.index, "</xdr:row><xdr:rowOff>").concat(Math.round(toRow.offset * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:to>");
3688
+ return "<xdr:twoCellAnchor editAs=\"absolute\">".concat(fromXml).concat(toXml, "<mc:AlternateContent xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"><mc:Choice xmlns:sle15=\"http://schemas.microsoft.com/office/drawing/2012/slicer\" Requires=\"sle15\"><xdr:graphicFrame macro=\"\"><xdr:nvGraphicFramePr><xdr:cNvPr id=\"").concat(frameId, "\" name=\"").concat(escapeXmlAttr(placement.title), "\"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"").concat(Math.round(widthPx * EMUS_PER_PIXEL), "\" cy=\"").concat(Math.round(heightPx * EMUS_PER_PIXEL), "\"/></xdr:xfrm><a:graphic><a:graphicData uri=\"http://schemas.microsoft.com/office/drawing/2010/slicer\"><sle:slicer xmlns:sle=\"http://schemas.microsoft.com/office/drawing/2010/slicer\" name=\"").concat(escapeXmlAttr(placement.title), "\"/></a:graphicData></a:graphic></xdr:graphicFrame></mc:Choice></mc:AlternateContent><xdr:clientData/></xdr:twoCellAnchor>");
3689
+ };
3690
+ var createTextBoxAnchor = function (_a) {
3691
+ var _b, _d, _e, _f;
3692
+ var placement = _a.placement, frameId = _a.frameId, sheet = _a.sheet;
3693
+ var fromRow = Math.max(0, placement.rowIndex - 1);
3694
+ var fromColumn = Math.max(0, placement.columnIndex - 1);
3695
+ var offsetX = Math.max(0, (_b = placement.offsetX) !== null && _b !== void 0 ? _b : 0);
3696
+ var offsetY = Math.max(0, (_d = placement.offsetY) !== null && _d !== void 0 ? _d : 0);
3697
+ var widthPx = Math.max(50, (_e = placement.width) !== null && _e !== void 0 ? _e : 200);
3698
+ var heightPx = Math.max(50, (_f = placement.height) !== null && _f !== void 0 ? _f : 60);
3699
+ var toColumn = resolveAnchorEndpoint({
3700
+ startIndex: fromColumn,
3701
+ startOffset: offsetX,
3702
+ span: widthPx,
3703
+ getSize: function (index) { return getColumnWidthPx(sheet, index, true); },
3704
+ });
3705
+ var toRow = resolveAnchorEndpoint({
3706
+ startIndex: fromRow,
3707
+ startOffset: offsetY,
3708
+ span: heightPx,
3709
+ getSize: function (index) { return getRowHeightPx(sheet, index, true); },
3710
+ });
3711
+ var fromXml = "<xdr:from><xdr:col>".concat(fromColumn, "</xdr:col><xdr:colOff>").concat(Math.round(offsetX * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(fromRow, "</xdr:row><xdr:rowOff>").concat(Math.round(offsetY * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:from>");
3712
+ var toXml = "<xdr:to><xdr:col>".concat(toColumn.index, "</xdr:col><xdr:colOff>").concat(Math.round(toColumn.offset * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(toRow.index, "</xdr:row><xdr:rowOff>").concat(Math.round(toRow.offset * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:to>");
3713
+ var spec = placement.textBox.spec;
3714
+ var textBodyXml = buildTextBodyXml(spec);
3715
+ var shapePropertiesXml = buildShapePropertiesXml(spec, widthPx, heightPx);
3716
+ return "<xdr:twoCellAnchor editAs=\"oneCell\">".concat(fromXml).concat(toXml, "<xdr:sp><xdr:nvSpPr><xdr:cNvPr id=\"").concat(frameId, "\" name=\"TextBox ").concat(frameId, "\"/><xdr:cNvSpPr txBox=\"1\"/></xdr:nvSpPr>").concat(shapePropertiesXml).concat(textBodyXml, "</xdr:sp><xdr:clientData/></xdr:twoCellAnchor>");
3717
+ };
3718
+ /** ColorIndex slots → canonical DrawingML scheme names (inverse of the importer's map). */
3719
+ var THEME_INDEX_TO_SCHEME = [
3720
+ "lt1",
3721
+ "dk1",
3722
+ "lt2",
3723
+ "dk2",
3724
+ "accent1",
3725
+ "accent2",
3726
+ "accent3",
3727
+ "accent4",
3728
+ "accent5",
3729
+ "accent6",
3730
+ "hlink",
3731
+ ];
3732
+ /**
3733
+ * Serialize a `Color` (+optional 0–1 opacity) as a DrawingML color element.
3734
+ * Theme colors keep their scheme reference; a positive tint exports as
3735
+ * Excel's lumMod/lumOff pair ("lighter N%"), a negative one as lumMod alone
3736
+ * ("darker N%") — the exact encodings the importer maps back onto `tint`.
3737
+ */
3738
+ var buildDrawingColorXml = function (color, opacity) {
3739
+ var _a, _b;
3740
+ var mods = [];
3741
+ if (opacity !== undefined && opacity !== null && opacity < 1) {
3742
+ mods.push("<a:alpha val=\"".concat(Math.round(opacity * 100000), "\"/>"));
3743
+ }
3744
+ if (typeof color === "string") {
3745
+ var val = escapeXmlAttr(color.replace("#", "").toUpperCase());
3746
+ return mods.length
3747
+ ? "<a:srgbClr val=\"".concat(val, "\">").concat(mods.join(""), "</a:srgbClr>")
3748
+ : "<a:srgbClr val=\"".concat(val, "\"/>");
3749
+ }
3750
+ var scheme = (_a = THEME_INDEX_TO_SCHEME[color.theme]) !== null && _a !== void 0 ? _a : "accent1";
3751
+ var tint = (_b = color.tint) !== null && _b !== void 0 ? _b : 0;
3752
+ if (tint > 0) {
3753
+ mods.push("<a:lumMod val=\"".concat(Math.round((1 - tint) * 100000), "\"/>"), "<a:lumOff val=\"".concat(Math.round(tint * 100000), "\"/>"));
3754
+ }
3755
+ else if (tint < 0) {
3756
+ mods.push("<a:lumMod val=\"".concat(Math.round((1 + tint) * 100000), "\"/>"));
3757
+ }
3758
+ return mods.length
3759
+ ? "<a:schemeClr val=\"".concat(scheme, "\">").concat(mods.join(""), "</a:schemeClr>")
3760
+ : "<a:schemeClr val=\"".concat(scheme, "\"/>");
3761
+ };
3762
+ /** Renderer preset names → OOXML `prst` values where they differ. */
3763
+ var PRESET_TO_OOXML = {
3764
+ rightTriangle: "rtTriangle",
3765
+ snipSingleCornerRect: "snip1Rect",
3766
+ };
3767
+ var SHAPE_DASH_TO_OOXML = {
3768
+ solid: "solid",
3769
+ dot: "dot",
3770
+ dash: "dash",
3771
+ dashDot: "dashDot",
3772
+ longDash: "lgDash",
3773
+ longDashDot: "lgDashDot",
3774
+ longDashDotDot: "lgDashDotDot",
3775
+ };
3776
+ var buildShapeFillXml = function (fill) {
3777
+ var _a;
3778
+ if (!fill)
3779
+ return "";
3780
+ switch (fill.kind) {
3781
+ case "none":
3782
+ return "<a:noFill/>";
3783
+ case "solid":
3784
+ return "<a:solidFill>".concat(buildDrawingColorXml(fill.color, fill.opacity), "</a:solidFill>");
3785
+ case "gradient": {
3786
+ var stops = fill.stops
3787
+ .map(function (stop) {
3788
+ return "<a:gs pos=\"".concat(Math.round(stop.position * 100000), "\">").concat(buildDrawingColorXml(stop.color, stop.opacity), "</a:gs>");
3789
+ })
3790
+ .join("");
3791
+ var direction = fill.shading === "radial"
3792
+ ? "<a:path path=\"circle\"><a:fillToRect l=\"50000\" t=\"50000\" r=\"50000\" b=\"50000\"/></a:path>"
3793
+ : "<a:lin ang=\"".concat(Math.round(((_a = fill.angle) !== null && _a !== void 0 ? _a : 90) * 60000), "\" scaled=\"1\"/>");
3794
+ return "<a:gradFill><a:gsLst>".concat(stops, "</a:gsLst>").concat(direction, "</a:gradFill>");
3795
+ }
3796
+ }
3797
+ };
3798
+ var buildShapeOutlineXml = function (outline) {
3799
+ if (!outline)
3800
+ return "";
3801
+ if (outline.width === 0)
3802
+ return "<a:ln><a:noFill/></a:ln>";
3803
+ var wAttr = outline.width
3804
+ ? " w=\"".concat(Math.round(outline.width * EMUS_PER_PIXEL), "\"")
3805
+ : "";
3806
+ var fill = outline.color
3807
+ ? "<a:solidFill>".concat(buildDrawingColorXml(outline.color, outline.opacity), "</a:solidFill>")
3808
+ : "";
3809
+ var dash = outline.dash
3810
+ ? "<a:prstDash val=\"".concat(SHAPE_DASH_TO_OOXML[outline.dash], "\"/>")
3811
+ : "";
3812
+ return "<a:ln".concat(wAttr, ">").concat(fill).concat(dash, "</a:ln>");
3813
+ };
3814
+ var buildShapeShadowXml = function (shadow) {
3815
+ var _a, _b, _d, _e;
3816
+ if (!shadow)
3817
+ return "";
3818
+ var dx = (_a = shadow.offsetXPixels) !== null && _a !== void 0 ? _a : 0;
3819
+ var dy = (_b = shadow.offsetYPixels) !== null && _b !== void 0 ? _b : 0;
3820
+ var dist = Math.round(Math.hypot(dx, dy) * EMUS_PER_PIXEL);
3821
+ var dirDeg = (Math.atan2(dy, dx) * 180) / Math.PI;
3822
+ var dir = Math.round(((dirDeg + 360) % 360) * 60000);
3823
+ var blur = Math.round(((_d = shadow.blurRadius) !== null && _d !== void 0 ? _d : 0) * EMUS_PER_PIXEL);
3824
+ var color = buildDrawingColorXml((_e = shadow.color) !== null && _e !== void 0 ? _e : "#000000", shadow.opacity);
3825
+ return "<a:effectLst><a:outerShdw blurRad=\"".concat(blur, "\" dist=\"").concat(dist, "\" dir=\"").concat(dir, "\">").concat(color, "</a:outerShdw></a:effectLst>");
3826
+ };
3827
+ var buildShapeStyleRefXml = function (tag, ref) {
3828
+ return ref
3829
+ ? "<a:".concat(tag, " idx=\"").concat(ref.index, "\">").concat(buildDrawingColorXml(ref.color), "</a:").concat(tag, ">")
3830
+ : "<a:".concat(tag, " idx=\"0\"/>");
3831
+ };
3832
+ /** Export an `EmbedShapeSpec` embed as an `<xdr:sp>` two-cell anchor. */
3833
+ var createShapeAnchor = function (_a) {
3834
+ var _b, _d, _e, _f, _g, _h, _j, _k;
3835
+ var placement = _a.placement, frameId = _a.frameId, sheet = _a.sheet;
3836
+ var spec = placement.shape.spec;
3837
+ var fromRow = Math.max(0, placement.rowIndex - 1);
3838
+ var fromColumn = Math.max(0, placement.columnIndex - 1);
3839
+ var offsetX = Math.max(0, (_b = placement.offsetX) !== null && _b !== void 0 ? _b : 0);
3840
+ var offsetY = Math.max(0, (_d = placement.offsetY) !== null && _d !== void 0 ? _d : 0);
3841
+ var widthPx = Math.max(10, (_e = placement.width) !== null && _e !== void 0 ? _e : 120);
3842
+ var heightPx = Math.max(10, (_f = placement.height) !== null && _f !== void 0 ? _f : 60);
3843
+ var toColumn = resolveAnchorEndpoint({
3844
+ startIndex: fromColumn,
3845
+ startOffset: offsetX,
3846
+ span: widthPx,
3847
+ getSize: function (index) { return getColumnWidthPx(sheet, index, true); },
3848
+ });
3849
+ var toRow = resolveAnchorEndpoint({
3850
+ startIndex: fromRow,
3851
+ startOffset: offsetY,
3852
+ span: heightPx,
3853
+ getSize: function (index) { return getRowHeightPx(sheet, index, true); },
3854
+ });
3855
+ var fromXml = "<xdr:from><xdr:col>".concat(fromColumn, "</xdr:col><xdr:colOff>").concat(Math.round(offsetX * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(fromRow, "</xdr:row><xdr:rowOff>").concat(Math.round(offsetY * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:from>");
3856
+ var toXml = "<xdr:to><xdr:col>".concat(toColumn.index, "</xdr:col><xdr:colOff>").concat(Math.round(toColumn.offset * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(toRow.index, "</xdr:row><xdr:rowOff>").concat(Math.round(toRow.offset * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:to>");
3857
+ var xfrmAttrs = [
3858
+ placement.shape.rotation
3859
+ ? " rot=\"".concat(Math.round(placement.shape.rotation * 60000), "\"")
3860
+ : "",
3861
+ spec.flipHorizontal ? ' flipH="1"' : "",
3862
+ spec.flipVertical ? ' flipV="1"' : "",
3863
+ ].join("");
3864
+ var xfrm = "<a:xfrm".concat(xfrmAttrs, "><a:off x=\"0\" y=\"0\"/><a:ext cx=\"").concat(Math.round(widthPx * EMUS_PER_PIXEL), "\" cy=\"").concat(Math.round(heightPx * EMUS_PER_PIXEL), "\"/></a:xfrm>");
3865
+ var prst = (_g = PRESET_TO_OOXML[spec.geometry.preset]) !== null && _g !== void 0 ? _g : spec.geometry.preset;
3866
+ var adjustments = (_h = spec.geometry.adjustments) !== null && _h !== void 0 ? _h : {};
3867
+ var gds = Object.entries(adjustments)
3868
+ .map(function (_a) {
3869
+ var _b = __read(_a, 2), gdName = _b[0], value = _b[1];
3870
+ return "<a:gd name=\"".concat(escapeXmlAttr(gdName), "\" fmla=\"val ").concat(Math.round(value), "\"/>");
3871
+ })
3872
+ .join("");
3873
+ var geometry = "<a:prstGeom prst=\"".concat(escapeXmlAttr(prst), "\"><a:avLst>").concat(gds, "</a:avLst></a:prstGeom>");
3874
+ var spPr = "<xdr:spPr>".concat(xfrm).concat(geometry).concat(buildShapeFillXml(spec.fill)).concat(buildShapeOutlineXml(spec.outline)).concat(buildShapeShadowXml(spec.shadow), "</xdr:spPr>");
3875
+ // <xdr:style> child order is fixed by the schema: ln, fill, effect, font.
3876
+ var styleXml = "";
3877
+ if (spec.styleRefs) {
3878
+ var font = spec.styleRefs.font;
3879
+ var fontXml = "<a:fontRef idx=\"".concat((_j = font === null || font === void 0 ? void 0 : font.scheme) !== null && _j !== void 0 ? _j : "minor", "\">").concat((font === null || font === void 0 ? void 0 : font.color) ? buildDrawingColorXml(font.color) : "", "</a:fontRef>");
3880
+ styleXml = "<xdr:style>".concat(buildShapeStyleRefXml("lnRef", spec.styleRefs.line)).concat(buildShapeStyleRefXml("fillRef", spec.styleRefs.fill)).concat(buildShapeStyleRefXml("effectRef", spec.styleRefs.effect)).concat(fontXml, "</xdr:style>");
3881
+ }
3882
+ var textBodyXml = spec.textBody
3883
+ ? buildTextBodyXml(spec.textBody)
3884
+ : "<xdr:txBody><a:bodyPr vertOverflow=\"clip\" horzOverflow=\"clip\" rtlCol=\"0\" anchor=\"t\"/><a:lstStyle/><a:p><a:endParaRPr lang=\"en-US\"/></a:p></xdr:txBody>";
3885
+ var name = escapeXmlAttr((_k = spec.name) !== null && _k !== void 0 ? _k : "Shape ".concat(frameId));
3886
+ return "<xdr:twoCellAnchor editAs=\"oneCell\">".concat(fromXml).concat(toXml, "<xdr:sp><xdr:nvSpPr><xdr:cNvPr id=\"").concat(frameId, "\" name=\"").concat(name, "\"/><xdr:cNvSpPr/></xdr:nvSpPr>").concat(spPr).concat(styleXml).concat(textBodyXml, "</xdr:sp><xdr:clientData/></xdr:twoCellAnchor>");
3887
+ };
3888
+ var buildTextWithTabs = function (text, rPrXml) {
3889
+ var parts = text.split("\t");
3890
+ if (parts.length === 1) {
3891
+ return "<a:r>".concat(rPrXml, "<a:t>").concat(escapeXmlText(text), "</a:t></a:r>");
3892
+ }
3893
+ return parts
3894
+ .map(function (part, index) {
3895
+ if (index === 0) {
3896
+ return "<a:r>".concat(rPrXml, "<a:t>").concat(escapeXmlText(part), "</a:t></a:r>");
3897
+ }
3898
+ return "<a:r>".concat(rPrXml, "<a:tab/></a:r><a:r>").concat(rPrXml, "<a:t>").concat(escapeXmlText(part), "</a:t></a:r>");
3899
+ })
3900
+ .join("");
3901
+ };
3902
+ var buildTextBodyXml = function (spec) {
3903
+ var e_42, _a;
3904
+ var richText = spec.richText || [];
3905
+ var plainText = spec.text || "";
3906
+ // Build vertical alignment and wrap attributes
3907
+ var bodyPrAttrs = "";
3908
+ if (spec.verticalAlignment === "top") {
3909
+ bodyPrAttrs += ' anchor="t"';
3910
+ }
3911
+ else if (spec.verticalAlignment === "bottom") {
3912
+ bodyPrAttrs += ' anchor="b"';
3913
+ }
3914
+ else if (spec.verticalAlignment === "middle") {
3915
+ bodyPrAttrs += ' anchor="ctr"';
3916
+ }
3917
+ // Add wrap strategy
3918
+ if (spec.wrapStrategy === "wrap") {
3919
+ bodyPrAttrs += ' wrap="square"';
3920
+ }
3921
+ else if (spec.wrapStrategy === "overflow") {
3922
+ bodyPrAttrs += ' wrap="none"';
3923
+ }
3924
+ // Add padding (convert pixels to EMUs)
3925
+ if (spec.padding) {
3926
+ var paddingEmu = Math.round(spec.padding * EMUS_PER_PIXEL);
3927
+ bodyPrAttrs += " lIns=\"".concat(paddingEmu, "\" rIns=\"").concat(paddingEmu, "\" tIns=\"").concat(paddingEmu, "\" bIns=\"").concat(paddingEmu, "\"");
3928
+ }
3929
+ var paragraphsXml = "";
3930
+ if (richText.length > 0) {
3931
+ // Group runs into paragraphs by newlines
3932
+ var paragraphs = [[]];
3933
+ try {
3934
+ for (var richText_1 = __values(richText), richText_1_1 = richText_1.next(); !richText_1_1.done; richText_1_1 = richText_1.next()) {
3935
+ var run = richText_1_1.value;
3936
+ if (run.text === "\n") {
3937
+ paragraphs.push([]);
3938
+ }
3939
+ else {
3940
+ paragraphs[paragraphs.length - 1].push(run);
3941
+ }
3942
+ }
3943
+ }
3944
+ catch (e_42_1) { e_42 = { error: e_42_1 }; }
3945
+ finally {
3946
+ try {
3947
+ if (richText_1_1 && !richText_1_1.done && (_a = richText_1.return)) _a.call(richText_1);
3948
+ }
3949
+ finally { if (e_42) throw e_42.error; }
3950
+ }
3951
+ paragraphsXml = paragraphs
3952
+ .filter(function (runs) { return runs.length > 0; })
3953
+ .map(function (runs) {
3954
+ // Detect indentation and bullets from first run
3955
+ var firstRun = runs[0];
3956
+ var pPrXml = "";
3957
+ var processedRuns = runs;
3958
+ if (firstRun && firstRun.text) {
3959
+ var text = firstRun.text;
3960
+ // Detect bullet (expanded to support more types)
3961
+ var bulletMatch = text.match(/^([•\-◦▪○●✓✔✖✗➢►▶→⇒❯»*+>§¶])\s/);
3962
+ if (bulletMatch) {
3963
+ pPrXml = "<a:pPr><a:buChar char=\"".concat(escapeXmlAttr(bulletMatch[1]), "\"/></a:pPr>");
3964
+ // Remove bullet from text
3965
+ processedRuns = __spreadArray([
3966
+ __assign(__assign({}, firstRun), { text: text.substring(bulletMatch[0].length) })
3967
+ ], __read(runs.slice(1)), false);
3968
+ }
3969
+ else {
3970
+ // Detect indentation (leading spaces)
3971
+ var spaceMatch = text.match(/^(\s+)/);
3972
+ if (spaceMatch) {
3973
+ var spaces = spaceMatch[1].length;
3974
+ var indentEmu = Math.round(spaces * 90000);
3975
+ pPrXml = "<a:pPr marL=\"".concat(indentEmu, "\"/>");
3976
+ // Remove leading spaces
3977
+ processedRuns = __spreadArray([
3978
+ __assign(__assign({}, firstRun), { text: text.substring(spaces) })
3979
+ ], __read(runs.slice(1)), false);
3980
+ }
3981
+ }
3982
+ }
3983
+ var runsXml = processedRuns
3984
+ .map(function (run) {
3985
+ var rPrXml = buildRunPropertiesXml(run.format);
3986
+ return buildTextWithTabs(run.text, rPrXml);
3987
+ })
3988
+ .join("");
3989
+ return "<a:p>".concat(pPrXml).concat(runsXml, "</a:p>");
3990
+ })
3991
+ .join("");
3992
+ }
3993
+ else {
3994
+ // Plain text - split by newlines
3995
+ var lines = plainText.split("\n");
3996
+ paragraphsXml = lines
3997
+ .map(function (line) {
3998
+ var pPrXml = "";
3999
+ var processedText = line;
4000
+ // Detect bullet (expanded to support more types)
4001
+ var bulletMatch = line.match(/^([•\-◦▪○●✓✔✖✗➢►▶→⇒❯»*+>§¶])\s/);
4002
+ if (bulletMatch) {
4003
+ pPrXml = "<a:pPr><a:buChar char=\"".concat(escapeXmlAttr(bulletMatch[1]), "\"/></a:pPr>");
4004
+ processedText = line.substring(bulletMatch[0].length);
4005
+ }
4006
+ else {
4007
+ // Detect indentation
4008
+ var spaceMatch = line.match(/^(\s+)/);
4009
+ if (spaceMatch) {
4010
+ var spaces = spaceMatch[1].length;
4011
+ var indentEmu = Math.round(spaces * 90000);
4012
+ pPrXml = "<a:pPr marL=\"".concat(indentEmu, "\"/>");
4013
+ processedText = line.substring(spaces);
4014
+ }
4015
+ }
4016
+ var rPrXml = buildRunPropertiesXml(spec.textFormat);
4017
+ var runsXml = buildTextWithTabs(processedText, rPrXml);
4018
+ return "<a:p>".concat(pPrXml).concat(runsXml, "</a:p>");
4019
+ })
4020
+ .join("");
4021
+ }
4022
+ return "<xdr:txBody><a:bodyPr".concat(bodyPrAttrs, "/><a:lstStyle/>").concat(paragraphsXml, "</xdr:txBody>");
4023
+ };
4024
+ var buildRunPropertiesXml = function (format) {
4025
+ if (!format)
4026
+ return "<a:rPr/>";
4027
+ var attrs = "";
4028
+ var childElements = "";
4029
+ // Font size (convert points to hundredths of a point)
4030
+ if (format.fontSize) {
4031
+ attrs += " sz=\"".concat(Math.round(format.fontSize * 100), "\"");
4032
+ }
4033
+ // Bold
4034
+ if (format.bold) {
4035
+ attrs += ' b="1"';
4036
+ }
4037
+ // Italic
4038
+ if (format.italic) {
4039
+ attrs += ' i="1"';
4040
+ }
4041
+ // Underline
4042
+ if (format.underline) {
4043
+ attrs += ' u="sng"';
4044
+ }
4045
+ // Strikethrough
4046
+ if (format.strikethrough) {
4047
+ attrs += ' strike="sngStrike"';
4048
+ }
4049
+ // Font family
4050
+ if (format.fontFamily) {
4051
+ childElements += "<a:latin typeface=\"".concat(escapeXmlAttr(format.fontFamily), "\"/>");
4052
+ }
4053
+ // Text color
4054
+ if (format.color) {
4055
+ var colorHex = "000000";
4056
+ if (typeof format.color === "string") {
4057
+ colorHex = format.color.replace("#", "");
4058
+ }
4059
+ else if (format.color.rgbColor) {
4060
+ colorHex = format.color.rgbColor.replace("#", "");
4061
+ }
4062
+ else if (format.color.red !== undefined &&
4063
+ format.color.green !== undefined &&
4064
+ format.color.blue !== undefined) {
4065
+ var r = Math.round(format.color.red * 255)
4066
+ .toString(16)
4067
+ .padStart(2, "0");
4068
+ var g = Math.round(format.color.green * 255)
4069
+ .toString(16)
4070
+ .padStart(2, "0");
4071
+ var b = Math.round(format.color.blue * 255)
4072
+ .toString(16)
4073
+ .padStart(2, "0");
4074
+ colorHex = "".concat(r).concat(g).concat(b).toUpperCase();
4075
+ }
4076
+ childElements += "<a:solidFill><a:srgbClr val=\"".concat(colorHex, "\"/></a:solidFill>");
4077
+ }
4078
+ return "<a:rPr".concat(attrs, ">").concat(childElements, "</a:rPr>");
4079
+ };
4080
+ var buildShapePropertiesXml = function (spec, widthPx, heightPx) {
4081
+ var _a, _b, _d, _e;
4082
+ var fillXml = "";
4083
+ // Background color
4084
+ if (spec.backgroundColor) {
4085
+ var bgColor = "FFFFFF";
4086
+ if (typeof spec.backgroundColor === "string") {
4087
+ bgColor = spec.backgroundColor.replace("#", "");
4088
+ }
4089
+ else if (spec.backgroundColor.rgbColor) {
4090
+ bgColor = spec.backgroundColor.rgbColor.replace("#", "");
4091
+ }
4092
+ else if (spec.backgroundColor.red !== undefined &&
4093
+ spec.backgroundColor.green !== undefined &&
4094
+ spec.backgroundColor.blue !== undefined) {
4095
+ var r = Math.round(spec.backgroundColor.red * 255)
4096
+ .toString(16)
4097
+ .padStart(2, "0");
4098
+ var g = Math.round(spec.backgroundColor.green * 255)
4099
+ .toString(16)
4100
+ .padStart(2, "0");
4101
+ var b = Math.round(spec.backgroundColor.blue * 255)
4102
+ .toString(16)
4103
+ .padStart(2, "0");
4104
+ bgColor = "".concat(r).concat(g).concat(b).toUpperCase();
4105
+ }
4106
+ fillXml = "<a:solidFill><a:srgbClr val=\"".concat(bgColor, "\"/></a:solidFill>");
4107
+ }
4108
+ else {
4109
+ fillXml = "<a:noFill/>";
4110
+ }
4111
+ // Borders (outline)
4112
+ var outlineXml = "<a:ln><a:noFill/></a:ln>";
4113
+ if (spec.borders) {
4114
+ // For simplicity, use the first available border style
4115
+ var border = spec.borders.top ||
4116
+ spec.borders.right ||
4117
+ spec.borders.bottom ||
4118
+ spec.borders.left;
4119
+ if (border) {
4120
+ var borderColor = "000000";
4121
+ if (typeof border.color === "string") {
4122
+ borderColor = border.color.replace("#", "");
4123
+ }
4124
+ else if ((_a = border.color) === null || _a === void 0 ? void 0 : _a.rgbColor) {
4125
+ borderColor = border.color.rgbColor.replace("#", "");
4126
+ }
4127
+ else if (((_b = border.color) === null || _b === void 0 ? void 0 : _b.red) !== undefined &&
4128
+ ((_d = border.color) === null || _d === void 0 ? void 0 : _d.green) !== undefined &&
4129
+ ((_e = border.color) === null || _e === void 0 ? void 0 : _e.blue) !== undefined) {
4130
+ var r = Math.round(border.color.red * 255)
4131
+ .toString(16)
4132
+ .padStart(2, "0");
4133
+ var g = Math.round(border.color.green * 255)
4134
+ .toString(16)
4135
+ .padStart(2, "0");
4136
+ var b = Math.round(border.color.blue * 255)
4137
+ .toString(16)
4138
+ .padStart(2, "0");
4139
+ borderColor = "".concat(r).concat(g).concat(b).toUpperCase();
4140
+ }
4141
+ var borderWidth = Math.round((border.width || 1) * 12700); // Convert to EMUs
4142
+ outlineXml = "<a:ln w=\"".concat(borderWidth, "\"><a:solidFill><a:srgbClr val=\"").concat(borderColor, "\"/></a:solidFill></a:ln>");
4143
+ }
4144
+ }
4145
+ return "<xdr:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"".concat(Math.round(widthPx * EMUS_PER_PIXEL), "\" cy=\"").concat(Math.round(heightPx * EMUS_PER_PIXEL), "\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom>").concat(fillXml).concat(outlineXml, "</xdr:spPr>");
4146
+ };
4147
+ var resolveAnchorEndpoint = function (_a) {
4148
+ var startIndex = _a.startIndex, startOffset = _a.startOffset, span = _a.span, getSize = _a.getSize;
4149
+ var index = startIndex;
4150
+ var offset = Math.max(0, startOffset);
4151
+ var remaining = Math.max(0, span);
4152
+ while (remaining > 0) {
4153
+ var rawSize = getSize(index);
4154
+ // Hidden rows/columns have 0 size - skip over them
4155
+ if (rawSize <= 0) {
4156
+ index += 1;
4157
+ offset = 0;
4158
+ continue;
4159
+ }
4160
+ var size = Math.max(5, rawSize);
4161
+ var available = Math.max(0, size - offset);
4162
+ if (remaining <= available) {
4163
+ return {
4164
+ index: index,
4165
+ offset: Math.min(size, offset + remaining),
4166
+ };
4167
+ }
4168
+ remaining -= available;
4169
+ index += 1;
4170
+ offset = 0;
4171
+ }
4172
+ return {
4173
+ index: index,
4174
+ offset: offset,
4175
+ };
4176
+ };
4177
+ var getDefaultColumnWidthPx = function (sheet) {
4178
+ if (sheet === null || sheet === void 0 ? void 0 : sheet.defaultColumnWidth) {
4179
+ return Number(sheet.defaultColumnWidth) || DEFAULT_COLUMN_WIDTH_PX;
4180
+ }
4181
+ return DEFAULT_COLUMN_WIDTH_PX;
4182
+ };
4183
+ var getDefaultRowHeightPx = function (sheet) {
4184
+ if (sheet === null || sheet === void 0 ? void 0 : sheet.defaultRowHeight) {
4185
+ return Number(sheet.defaultRowHeight) || DEFAULT_ROW_HEIGHT_PX;
4186
+ }
4187
+ return DEFAULT_ROW_HEIGHT_PX;
4188
+ };
4189
+ var getColumnWidthPx = function (sheet, columnIndex, forAnchor) {
4190
+ var _a;
4191
+ if (forAnchor === void 0) { forAnchor = false; }
4192
+ var metadata = (_a = sheet.columnMetadata) === null || _a === void 0 ? void 0 : _a[columnIndex + 1];
4193
+ // For anchor calculations, hidden columns have 0 width
4194
+ if (forAnchor && ((metadata === null || metadata === void 0 ? void 0 : metadata.hiddenByUser) || (metadata === null || metadata === void 0 ? void 0 : metadata.hiddenByFilter))) {
4195
+ return 0;
4196
+ }
4197
+ if ((metadata === null || metadata === void 0 ? void 0 : metadata.size) && metadata.size > 0) {
4198
+ return metadata.size;
4199
+ }
4200
+ return getDefaultColumnWidthPx(sheet);
4201
+ };
4202
+ var getRowHeightPx = function (sheet, rowIndex, forAnchor) {
4203
+ var _a;
4204
+ if (forAnchor === void 0) { forAnchor = false; }
4205
+ var metadata = (_a = sheet.rowMetadata) === null || _a === void 0 ? void 0 : _a[rowIndex + 1];
4206
+ // For anchor calculations, hidden rows have 0 height
4207
+ if (forAnchor && ((metadata === null || metadata === void 0 ? void 0 : metadata.hiddenByUser) || (metadata === null || metadata === void 0 ? void 0 : metadata.hiddenByFilter))) {
4208
+ return 0;
4209
+ }
4210
+ if ((metadata === null || metadata === void 0 ? void 0 : metadata.size) && metadata.size > 0) {
4211
+ return metadata.size;
4212
+ }
4213
+ return getDefaultRowHeightPx(sheet);
4214
+ };
4215
+ var resolveImageDataUrl = function (imageUrl) { return __awaiter(void 0, void 0, void 0, function () {
4216
+ var _a;
4217
+ return __generator(this, function (_b) {
4218
+ switch (_b.label) {
4219
+ case 0:
4220
+ if (imageUrl.startsWith("data:")) {
4221
+ return [2 /*return*/, imageUrl];
4222
+ }
4223
+ _b.label = 1;
4224
+ case 1:
4225
+ _b.trys.push([1, 3, , 4]);
4226
+ return [4 /*yield*/, imageUrlToBase64(imageUrl)];
4227
+ case 2: return [2 /*return*/, _b.sent()];
4228
+ case 3:
4229
+ _a = _b.sent();
4230
+ return [2 /*return*/, undefined];
4231
+ case 4: return [2 /*return*/];
4232
+ }
4233
+ });
4234
+ }); };
4235
+ var dataUriToBuffer = function (dataUrl, fallbackName) {
4236
+ var _a, _b;
4237
+ var match = /^data:(.+?);base64,(.+)$/.exec(dataUrl);
4238
+ if (!match)
4239
+ return undefined;
4240
+ var _d = __read(match, 3), mime = _d[1], base64 = _d[2];
4241
+ var binaryString = decodeBase64(base64);
4242
+ var buffer = new Uint8Array(binaryString.length);
4243
+ for (var i = 0; i < binaryString.length; i++) {
4244
+ buffer[i] = binaryString.charCodeAt(i);
4245
+ }
4246
+ var extension = (_b = (_a = mime.split("/")[1]) !== null && _a !== void 0 ? _a : fallbackName === null || fallbackName === void 0 ? void 0 : fallbackName.split(".").pop()) !== null && _b !== void 0 ? _b : "bin";
4247
+ return {
4248
+ data: buffer,
4249
+ extension: extension.toLowerCase(),
4250
+ contentType: mime,
4251
+ };
4252
+ };
4253
+ var decodeBase64 = function (value) {
4254
+ if (typeof atob === "function") {
4255
+ return atob(value);
4256
+ }
4257
+ var bufferCtor = globalThis.Buffer;
4258
+ if (bufferCtor) {
4259
+ return bufferCtor.from(value, "base64").toString("binary");
4260
+ }
4261
+ throw new Error("Base64 decoding is not supported in this environment");
4262
+ };
4263
+ var sanitizeSheetName = function (name, used, fallback) {
4264
+ var invalidChars = /[\\/:?*\[\]]/g;
4265
+ var controlChars = /[\u0000-\u001F]/g;
4266
+ var cleaned = sanitizeXmlText(name)
4267
+ .replace(invalidChars, " ")
4268
+ .replace(controlChars, "")
4269
+ .replace(/^'+|'+$/g, "");
4270
+ // Preserve trailing/internal whitespace in sheet names (Excel allows
4271
+ // them — "Total Bookings " is a valid name and round-trip identity
4272
+ // lookups (shared-formula keys, named-range refs) depend on byte-equal
4273
+ // sheet names). Fall back to default only when the result is fully empty
4274
+ // after whitespace.
4275
+ if (!cleaned.trim())
4276
+ cleaned = fallback;
4277
+ if (cleaned.length > 31) {
4278
+ cleaned = cleaned.slice(0, 31);
4279
+ }
4280
+ var unique = cleaned;
4281
+ var suffix = 1;
4282
+ while (used.has(unique)) {
4283
+ suffix += 1;
4284
+ var tail = " (".concat(suffix, ")");
4285
+ var baseLength = Math.max(0, 31 - tail.length);
4286
+ unique = "".concat(cleaned.slice(0, baseLength)).concat(tail);
4287
+ }
4288
+ used.add(unique);
4289
+ return unique;
4290
+ };
4291
+ var buildWorkbookSheetNames = function (sheets) {
4292
+ var usedNames = new Set();
4293
+ return sheets.map(function (sheet, index) {
4294
+ var _a;
4295
+ var sheetId = index + 1;
4296
+ var fallback = "Sheet".concat(sheetId);
4297
+ return sanitizeSheetName((_a = sheet.title) !== null && _a !== void 0 ? _a : fallback, usedNames, fallback);
4298
+ });
4299
+ };
4300
+ var buildSlicerCacheName = function (value) {
4301
+ var normalized = sanitizeXmlText(value)
4302
+ .replace(/[^A-Za-z0-9_]/g, "_")
4303
+ .replace(/^_+|_+$/g, "");
4304
+ var base = normalized || "Slicer";
4305
+ return base.startsWith("Slicer_") ? base : "Slicer_".concat(base);
4306
+ };
4307
+ var buildCalcPrXml = function (iterativeCalculationOptions) {
4308
+ if (!iterativeCalculationOptions)
4309
+ return "";
4310
+ var attrs = [
4311
+ "iterate=\"".concat(iterativeCalculationOptions.enabled ? 1 : 0, "\""),
4312
+ ];
4313
+ if (typeof iterativeCalculationOptions.maxIterations === "number") {
4314
+ attrs.push("iterateCount=\"".concat(Math.max(0, Math.floor(iterativeCalculationOptions.maxIterations)), "\""));
4315
+ }
4316
+ if (typeof iterativeCalculationOptions.maxChange === "number") {
4317
+ attrs.push("iterateDelta=\"".concat(iterativeCalculationOptions.maxChange, "\""));
4318
+ }
4319
+ return "<calcPr ".concat(attrs.join(" "), "/>");
4320
+ };
4321
+ var buildWorkbookXml = function (sheets, sheetRelIds, sheetNames, namedRanges, iterativeCalculationOptions, slicerCacheRelIds, use1904, externalLinkRelIds, pivotCacheRelIds) {
4322
+ if (slicerCacheRelIds === void 0) { slicerCacheRelIds = []; }
4323
+ if (use1904 === void 0) { use1904 = false; }
4324
+ if (externalLinkRelIds === void 0) { externalLinkRelIds = []; }
4325
+ if (pivotCacheRelIds === void 0) { pivotCacheRelIds = []; }
4326
+ var sheetEntries = sheets
4327
+ .map(function (sheet, index) {
4328
+ var _a, _b;
4329
+ var relId = sheetRelIds[index];
4330
+ // Preserve the source's sheetId verbatim. Real-world workbooks have
4331
+ // non-sequential sheetIds (gaps left behind after sheet deletions —
4332
+ // Excel never renumbers), and tools that compare bytes (diff,
4333
+ // sensitivity-label scanners, version control) flag any renumber.
4334
+ // Display order is controlled by iteration order, not by sheetId
4335
+ // value, so preserving it has no UX impact. Fall back to index+1
4336
+ // only for newly-created sheets that don't carry one yet.
4337
+ var sheetId = (_a = sheet.sheetId) !== null && _a !== void 0 ? _a : index + 1;
4338
+ var fallbackName = "Sheet".concat(index + 1);
4339
+ var name = (_b = sheetNames[index]) !== null && _b !== void 0 ? _b : fallbackName;
4340
+ // visibility is the rich source of truth (visible/hidden/veryHidden).
4341
+ // Fall back to the legacy `hidden` boolean when the field isn't set.
4342
+ var state = sheet.visibility === "veryHidden"
4343
+ ? "veryHidden"
4344
+ : sheet.visibility === "hidden" || sheet.hidden
4345
+ ? "hidden"
4346
+ : "visible";
4347
+ return "<sheet name=\"".concat(escapeXmlAttr(name), "\" sheetId=\"").concat(sheetId, "\" r:id=\"").concat(relId, "\" state=\"").concat(state, "\"/>");
4348
+ })
4349
+ .join("");
4350
+ var sheetNameById = new Map();
4351
+ sheets.forEach(function (sheet, index) {
4352
+ var _a;
4353
+ sheetNameById.set((_a = sheet.sheetId) !== null && _a !== void 0 ? _a : index + 1, sheetNames[index]);
4354
+ });
4355
+ var definedNamesXml = buildDefinedNamesXml(namedRanges, sheetNameById);
4356
+ var calcPrXml = buildCalcPrXml(iterativeCalculationOptions);
4357
+ var slicerCachesXml = buildWorkbookSlicerCachesXml(slicerCacheRelIds);
4358
+ // Phase D2 — <pivotCaches> element. Each <pivotCache> pairs a
4359
+ // workbook-unique cacheId (we use 1-based sequential matching the
4360
+ // order pivotCacheDefinition<N>.xml files were emitted) with the
4361
+ // workbook-level relationship rId pointing at that cache XML.
4362
+ var pivotCachesXml = pivotCacheRelIds.length
4363
+ ? "<pivotCaches>".concat(pivotCacheRelIds
4364
+ .map(function (rId, i) {
4365
+ return "<pivotCache cacheId=\"".concat(i + 1, "\" r:id=\"").concat(rId, "\"/>");
4366
+ })
4367
+ .join(""), "</pivotCaches>")
4368
+ : "";
4369
+ // External-link references — needed so Excel knows `[1]Sheet!A1`
4370
+ // formulas resolve through the relationships we wrote into the rels
4371
+ // file. The position in the externalLinkRelIds array determines the
4372
+ // formula's `[N]` index (1-based).
4373
+ var externalReferencesXml = externalLinkRelIds.length
4374
+ ? "<externalReferences>".concat(externalLinkRelIds
4375
+ .map(function (id) { return "<externalReference r:id=\"".concat(id, "\"/>"); })
4376
+ .join(""), "</externalReferences>")
4377
+ : "";
4378
+ // `date1904="1"` shifts every date serial by 1462 days. Emit only when
4379
+ // the workbook is explicitly 1904-anchored so the default file matches
4380
+ // Excel's own writer (no attribute → 1900 epoch).
4381
+ var workbookPrXml = use1904
4382
+ ? "<workbookPr date1904=\"1\"/>"
4383
+ : "<workbookPr/>";
4384
+ return "".concat(XML_DECLARATION, "<workbook xmlns=\"").concat(WORKSHEET_NS, "\" xmlns:r=\"").concat(REL_NS, "\">").concat(workbookPrXml).concat(calcPrXml, "<bookViews><workbookView activeTab=\"0\" firstSheet=\"0\"/></bookViews><sheets>").concat(sheetEntries, "</sheets>").concat(definedNamesXml).concat(externalReferencesXml).concat(pivotCachesXml).concat(slicerCachesXml, "</workbook>");
4385
+ };
4386
+ var buildDefinedNamesXml = function (namedRanges, sheetNameById) {
4387
+ var e_43, _a;
4388
+ var _b;
4389
+ if (!(namedRanges === null || namedRanges === void 0 ? void 0 : namedRanges.length))
4390
+ return "";
4391
+ var entries = [];
4392
+ try {
4393
+ for (var namedRanges_1 = __values(namedRanges), namedRanges_1_1 = namedRanges_1.next(); !namedRanges_1_1.done; namedRanges_1_1 = namedRanges_1.next()) {
4394
+ var namedRange = namedRanges_1_1.value;
4395
+ if (!(namedRange === null || namedRange === void 0 ? void 0 : namedRange.name))
4396
+ continue;
4397
+ var hiddenAttr = namedRange.hidden ? " hidden=\"1\"" : "";
4398
+ if ((_b = namedRange.range) === null || _b === void 0 ? void 0 : _b.sheetId) {
4399
+ var sheetName = sheetNameById.get(namedRange.range.sheetId);
4400
+ if (!sheetName)
4401
+ continue;
4402
+ var ref = cellRangeToAddress(undefined, namedRange.range);
4403
+ if (!ref)
4404
+ continue;
4405
+ var address = "".concat(escapeSheetName(sheetName), "!").concat(toAbsoluteRef(ref));
4406
+ entries.push("<definedName name=\"".concat(escapeXmlAttr(namedRange.name), "\"").concat(hiddenAttr, ">").concat(escapeXmlText(address), "</definedName>"));
4407
+ continue;
4408
+ }
4409
+ var rawValue = namedRange.value;
4410
+ if (typeof rawValue !== "string")
4411
+ continue;
4412
+ var trimmed = rawValue.trim();
4413
+ if (!trimmed)
4414
+ continue;
4415
+ var expression = trimmed.startsWith("=") ? trimmed.slice(1) : trimmed;
4416
+ entries.push("<definedName name=\"".concat(escapeXmlAttr(namedRange.name), "\"").concat(hiddenAttr, ">").concat(escapeXmlText(expression), "</definedName>"));
4417
+ }
4418
+ }
4419
+ catch (e_43_1) { e_43 = { error: e_43_1 }; }
4420
+ finally {
4421
+ try {
4422
+ if (namedRanges_1_1 && !namedRanges_1_1.done && (_a = namedRanges_1.return)) _a.call(namedRanges_1);
4423
+ }
4424
+ finally { if (e_43) throw e_43.error; }
4425
+ }
4426
+ if (!entries.length)
4427
+ return "";
4428
+ return "<definedNames>".concat(entries.join(""), "</definedNames>");
4429
+ };
4430
+ var toAbsoluteRef = function (ref) {
4431
+ return ref
4432
+ .split(":")
4433
+ .map(function (part) {
4434
+ return part.replace(/(\$?)([A-Za-z]+)(\$?)(\d+)/g, function (_match, _c, col, _r, row) {
4435
+ return "$".concat(col, "$").concat(row);
4436
+ });
4437
+ })
4438
+ .join(":");
4439
+ };
4440
+ var escapeSheetName = function (name) {
4441
+ if (/[^A-Za-z0-9_]/.test(name)) {
4442
+ return "'".concat(name.replace(/'/g, "''"), "'");
4443
+ }
4444
+ return name;
4445
+ };
4446
+ var buildWorkbookSlicerCachesXml = function (slicerCacheRelIds) {
4447
+ if (!slicerCacheRelIds.length) {
4448
+ return "";
4449
+ }
4450
+ var cacheEntries = slicerCacheRelIds
4451
+ .map(function (relId) {
4452
+ return "<x14:slicerCache xmlns:x14=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main\" r:id=\"".concat(relId, "\"/>");
4453
+ })
4454
+ .join("");
4455
+ return "<extLst><ext uri=\"{46BE6895-7355-4a93-B00E-2C351335B9C9}\" xmlns:x15=\"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main\"><x15:slicerCaches xmlns:x14=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main\">".concat(cacheEntries, "</x15:slicerCaches></ext></extLst>");
4456
+ };
4457
+ var buildWorkbookRelationships = function (sheetCount, slicerCacheCount, externalLinkCount, pivotCacheCount, hasPersons) {
4458
+ if (slicerCacheCount === void 0) { slicerCacheCount = 0; }
4459
+ if (externalLinkCount === void 0) { externalLinkCount = 0; }
4460
+ if (pivotCacheCount === void 0) { pivotCacheCount = 0; }
4461
+ if (hasPersons === void 0) { hasPersons = false; }
4462
+ var relationships = [];
4463
+ var sheetRelIds = [];
4464
+ var slicerCacheRelIds = [];
4465
+ for (var i = 0; i < sheetCount; i++) {
4466
+ var relId = "rId".concat(i + 1);
4467
+ sheetRelIds.push(relId);
4468
+ relationships.push("<Relationship Id=\"".concat(relId, "\" Type=\"").concat(REL_NS, "/worksheet\" Target=\"worksheets/sheet").concat(i + 1, ".xml\"/>"));
4469
+ }
4470
+ var stylesId = "rId".concat(sheetCount + 1);
4471
+ var themeId = "rId".concat(sheetCount + 2);
4472
+ var sharedStringsId = "rId".concat(sheetCount + 3);
4473
+ relationships.push("<Relationship Id=\"".concat(stylesId, "\" Type=\"").concat(REL_NS, "/styles\" Target=\"styles.xml\"/>"));
4474
+ relationships.push("<Relationship Id=\"".concat(themeId, "\" Type=\"").concat(REL_NS, "/theme\" Target=\"theme/theme1.xml\"/>"));
4475
+ relationships.push("<Relationship Id=\"".concat(sharedStringsId, "\" Type=\"").concat(REL_NS, "/sharedStrings\" Target=\"sharedStrings.xml\"/>"));
4476
+ var nextRelId = sheetCount + 4;
4477
+ for (var i = 0; i < slicerCacheCount; i++) {
4478
+ var relId = "rId".concat(nextRelId++);
4479
+ slicerCacheRelIds.push(relId);
4480
+ relationships.push("<Relationship Id=\"".concat(relId, "\" Type=\"").concat(SLICER_CACHE_REL_TYPE, "\" Target=\"slicerCaches/slicerCache").concat(i + 1, ".xml\"/>"));
4481
+ }
4482
+ // Add external link relationships. Capture the rIds so the workbook
4483
+ // XML can reference them in <externalReferences>; without that element
4484
+ // Excel can't resolve `[1]Sheet!A1` formulas even though the files exist.
4485
+ var externalLinkRelIds = [];
4486
+ for (var i = 0; i < externalLinkCount; i++) {
4487
+ var relId = "rId".concat(nextRelId++);
4488
+ externalLinkRelIds.push(relId);
4489
+ relationships.push("<Relationship Id=\"".concat(relId, "\" Type=\"").concat(REL_NS, "/externalLink\" Target=\"externalLinks/externalLink").concat(i + 1, ".xml\"/>"));
4490
+ }
4491
+ // Phase D2 — pivotCacheDefinition relationships. workbook.xml's
4492
+ // <pivotCaches> element references these by rId. The corresponding
4493
+ // <pivotCache> entry pairs cacheId (sequential, starts at 1) with
4494
+ // r:id (the relationship rId we collect here).
4495
+ var pivotCacheRelIds = [];
4496
+ for (var i = 0; i < pivotCacheCount; i++) {
4497
+ var relId = "rId".concat(nextRelId++);
4498
+ pivotCacheRelIds.push(relId);
4499
+ relationships.push("<Relationship Id=\"".concat(relId, "\" Type=\"").concat(PIVOT_CACHE_DEFINITION_REL_TYPE, "\" Target=\"pivotCache/pivotCacheDefinition").concat(i + 1, ".xml\"/>"));
4500
+ }
4501
+ // Workbook → persons part (threaded-comment authors).
4502
+ if (hasPersons) {
4503
+ relationships.push("<Relationship Id=\"rId".concat(nextRelId++, "\" Type=\"").concat(PERSON_REL_TYPE, "\" Target=\"persons/person.xml\"/>"));
4504
+ }
4505
+ return {
4506
+ xml: "".concat(XML_DECLARATION, "<Relationships xmlns=\"").concat(PACKAGE_REL_NS, "\">").concat(relationships.join(""), "</Relationships>"),
4507
+ sheetRelationshipIds: sheetRelIds,
4508
+ pivotCacheRelationshipIds: pivotCacheRelIds,
4509
+ externalLinkRelationshipIds: externalLinkRelIds,
4510
+ slicerCacheRelationshipIds: slicerCacheRelIds,
4511
+ };
4512
+ };
4513
+ var buildContentTypesXml = function (_a) {
4514
+ var sheetCount = _a.sheetCount, tableCount = _a.tableCount, drawingSheets = _a.drawingSheets, mediaExtensions = _a.mediaExtensions, chartCount = _a.chartCount, _b = _a.slicerCount, slicerCount = _b === void 0 ? 0 : _b, _d = _a.slicerCacheCount, slicerCacheCount = _d === void 0 ? 0 : _d, _e = _a.pivotTableCount, pivotTableCount = _e === void 0 ? 0 : _e, _f = _a.pivotCacheCount, pivotCacheCount = _f === void 0 ? 0 : _f, _g = _a.commentsSheets, commentsSheets = _g === void 0 ? [] : _g, _h = _a.threadedCommentsSheets, threadedCommentsSheets = _h === void 0 ? [] : _h, _j = _a.hasPersons, hasPersons = _j === void 0 ? false : _j, _k = _a.externalLinkCount, externalLinkCount = _k === void 0 ? 0 : _k;
4515
+ var sheetOverrides = Array.from({ length: sheetCount }, function (_, index) {
4516
+ return "<Override PartName=\"/xl/worksheets/sheet".concat(index + 1, ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\"/>");
4517
+ }).join("");
4518
+ var tableOverrides = Array.from({ length: tableCount }, function (_, index) {
4519
+ return "<Override PartName=\"/xl/tables/table".concat(index + 1, ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml\"/>");
4520
+ }).join("");
4521
+ var drawingOverrides = drawingSheets
4522
+ .map(function (sheetIndex) {
4523
+ return "<Override PartName=\"/xl/drawings/drawing".concat(sheetIndex, ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.drawing+xml\"/>");
4524
+ })
4525
+ .join("");
4526
+ var chartOverrides = Array.from({ length: chartCount }, function (_, index) {
4527
+ return "<Override PartName=\"/xl/charts/chart".concat(index + 1, ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.drawingml.chart+xml\"/>");
4528
+ }).join("");
4529
+ var slicerOverrides = Array.from({ length: slicerCount }, function (_, index) {
4530
+ return "<Override PartName=\"/xl/slicers/slicer".concat(index + 1, ".xml\" ContentType=\"application/vnd.ms-excel.slicer+xml\"/>");
4531
+ }).join("");
4532
+ var slicerCacheOverrides = Array.from({ length: slicerCacheCount }, function (_, index) {
4533
+ return "<Override PartName=\"/xl/slicerCaches/slicerCache".concat(index + 1, ".xml\" ContentType=\"application/vnd.ms-excel.slicerCache+xml\"/>");
4534
+ }).join("");
4535
+ // Phase D2 — pivotTable + pivotCacheDefinition overrides.
4536
+ var pivotTableOverrides = Array.from({ length: pivotTableCount }, function (_, index) {
4537
+ return "<Override PartName=\"/xl/pivotTables/pivotTable".concat(index + 1, ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml\"/>");
4538
+ }).join("");
4539
+ var pivotCacheOverrides = Array.from({ length: pivotCacheCount }, function (_, index) {
4540
+ return "<Override PartName=\"/xl/pivotCache/pivotCacheDefinition".concat(index + 1, ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml\"/>");
4541
+ }).join("");
4542
+ var commentsOverrides = commentsSheets
4543
+ .map(function (sheetId) {
4544
+ return "<Override PartName=\"/xl/comments".concat(sheetId, ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml\"/>");
4545
+ })
4546
+ .join("");
4547
+ var threadedCommentsOverrides = threadedCommentsSheets
4548
+ .map(function (sheetId) {
4549
+ return "<Override PartName=\"/xl/threadedComments/threadedComment".concat(sheetId, ".xml\" ContentType=\"").concat(THREADED_COMMENTS_CONTENT_TYPE, "\"/>");
4550
+ })
4551
+ .join("");
4552
+ var personOverride = hasPersons
4553
+ ? "<Override PartName=\"/xl/persons/person.xml\" ContentType=\"".concat(PERSON_CONTENT_TYPE, "\"/>")
4554
+ : "";
4555
+ var externalLinkOverrides = Array.from({ length: externalLinkCount }, function (_, index) {
4556
+ return "<Override PartName=\"/xl/externalLinks/externalLink".concat(index + 1, ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml\"/>");
4557
+ }).join("");
4558
+ var mediaDefaults = mediaExtensions
4559
+ .map(function (extension) {
4560
+ return "<Default Extension=\"".concat(extension, "\" ContentType=\"image/").concat(extension, "\"/>");
4561
+ })
4562
+ .join("");
4563
+ var vmlDefault = commentsSheets.length
4564
+ ? "<Default Extension=\"vml\" ContentType=\"application/vnd.openxmlformats-officedocument.vmlDrawing\"/>"
4565
+ : "";
4566
+ return "".concat(XML_DECLARATION, "<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\"><Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/><Default Extension=\"xml\" ContentType=\"application/xml\"/>").concat(vmlDefault).concat(mediaDefaults, "<Override PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\"/>").concat(sheetOverrides).concat(tableOverrides).concat(drawingOverrides).concat(chartOverrides).concat(slicerOverrides).concat(slicerCacheOverrides).concat(pivotTableOverrides).concat(pivotCacheOverrides).concat(externalLinkOverrides).concat(commentsOverrides).concat(threadedCommentsOverrides).concat(personOverride, "<Override PartName=\"/xl/theme/theme1.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.theme+xml\"/><Override PartName=\"/xl/styles.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml\"/><Override PartName=\"/xl/sharedStrings.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml\"/><Override PartName=\"/docProps/core.xml\" ContentType=\"application/vnd.openxmlformats-package.core-properties+xml\"/><Override PartName=\"/docProps/app.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.extended-properties+xml\"/></Types>");
4567
+ };
4568
+ var buildRootRelationshipsXml = function () {
4569
+ return "".concat(XML_DECLARATION, "<Relationships xmlns=\"").concat(PACKAGE_REL_NS, "\"><Relationship Id=\"rId1\" Type=\"").concat(REL_NS, "/officeDocument\" Target=\"xl/workbook.xml\"/><Relationship Id=\"rId2\" Type=\"").concat(REL_NS, "/extended-properties\" Target=\"docProps/app.xml\"/><Relationship Id=\"rId3\" Type=\"").concat(REL_NS, "/core-properties\" Target=\"docProps/core.xml\"/></Relationships>");
4570
+ };
4571
+ var buildAppXml = function (sheetNames, properties) {
4572
+ var _a;
4573
+ var titles = sheetNames
4574
+ .map(function (name) { return "<vt:lpstr>".concat(escapeXmlText(name), "</vt:lpstr>"); })
4575
+ .join("");
4576
+ var application = (_a = properties === null || properties === void 0 ? void 0 : properties.application) !== null && _a !== void 0 ? _a : CREATOR;
4577
+ var companyTag = (properties === null || properties === void 0 ? void 0 : properties.company)
4578
+ ? "<Company>".concat(escapeXmlText(properties.company), "</Company>")
4579
+ : "";
4580
+ var managerTag = (properties === null || properties === void 0 ? void 0 : properties.manager)
4581
+ ? "<Manager>".concat(escapeXmlText(properties.manager), "</Manager>")
4582
+ : "";
4583
+ return "".concat(XML_DECLARATION, "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\"><Application>").concat(escapeXmlText(application), "</Application><DocSecurity>0</DocSecurity><ScaleCrop>false</ScaleCrop><HeadingPairs><vt:vector size=\"2\" baseType=\"variant\"><vt:variant><vt:lpstr>Worksheets</vt:lpstr></vt:variant><vt:variant><vt:i4>").concat(sheetNames.length, "</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size=\"").concat(sheetNames.length, "\" baseType=\"lpstr\">").concat(titles, "</vt:vector></TitlesOfParts>").concat(companyTag).concat(managerTag, "</Properties>");
4584
+ };
4585
+ var buildCoreXml = function (properties) {
4586
+ var _a, _b, _d, _e;
4587
+ var now = new Date().toISOString();
4588
+ var creator = (_a = properties === null || properties === void 0 ? void 0 : properties.creator) !== null && _a !== void 0 ? _a : CREATOR;
4589
+ var lastModifiedBy = (_b = properties === null || properties === void 0 ? void 0 : properties.lastModifiedBy) !== null && _b !== void 0 ? _b : creator;
4590
+ var created = (_d = properties === null || properties === void 0 ? void 0 : properties.created) !== null && _d !== void 0 ? _d : now;
4591
+ var modified = (_e = properties === null || properties === void 0 ? void 0 : properties.modified) !== null && _e !== void 0 ? _e : now;
4592
+ var tag = function (name, value) {
4593
+ return value ? "<".concat(name, ">").concat(escapeXmlText(value), "</").concat(name, ">") : "";
4594
+ };
4595
+ return "".concat(XML_DECLARATION, "<cp:coreProperties xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">").concat(tag("dc:title", properties === null || properties === void 0 ? void 0 : properties.title)).concat(tag("dc:subject", properties === null || properties === void 0 ? void 0 : properties.subject), "<dc:creator>").concat(escapeXmlText(creator), "</dc:creator>").concat(tag("cp:keywords", properties === null || properties === void 0 ? void 0 : properties.keywords)).concat(tag("dc:description", properties === null || properties === void 0 ? void 0 : properties.description), "<cp:lastModifiedBy>").concat(escapeXmlText(lastModifiedBy), "</cp:lastModifiedBy>").concat(tag("cp:category", properties === null || properties === void 0 ? void 0 : properties.category), "<dcterms:created xsi:type=\"dcterms:W3CDTF\">").concat(escapeXmlText(created), "</dcterms:created><dcterms:modified xsi:type=\"dcterms:W3CDTF\">").concat(escapeXmlText(modified), "</dcterms:modified></cp:coreProperties>");
4596
+ };