@evotecit/canopyx 0.3.16 → 0.3.20

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 (150) hide show
  1. package/CanopyX.Html/Assets/canopyx-board.css +50 -0
  2. package/CanopyX.Html/Assets/canopyx-board.js +39 -0
  3. package/CanopyX.Html/Assets/canopyx-buckets.js +15 -0
  4. package/CanopyX.Html/Assets/canopyx-calculations.css +7 -0
  5. package/CanopyX.Html/Assets/canopyx-calculations.js +52 -0
  6. package/CanopyX.Html/Assets/canopyx-calendar-edit.js +3 -3
  7. package/CanopyX.Html/Assets/canopyx-calendar.css +74 -80
  8. package/CanopyX.Html/Assets/canopyx-calendar.js +26 -31
  9. package/CanopyX.Html/Assets/canopyx-cell-range.css +4 -4
  10. package/CanopyX.Html/Assets/canopyx-cell-range.js +16 -14
  11. package/CanopyX.Html/Assets/canopyx-changes.css +61 -79
  12. package/CanopyX.Html/Assets/canopyx-changes.js +18 -15
  13. package/CanopyX.Html/Assets/canopyx-column-groups.css +5 -1
  14. package/CanopyX.Html/Assets/canopyx-column-groups.js +15 -9
  15. package/CanopyX.Html/Assets/canopyx-compare.css +37 -0
  16. package/CanopyX.Html/Assets/canopyx-compare.js +12 -0
  17. package/CanopyX.Html/Assets/canopyx-data.js +3 -3
  18. package/CanopyX.Html/Assets/canopyx-detail-rows.css +4 -4
  19. package/CanopyX.Html/Assets/canopyx-detail-rows.js +1 -1
  20. package/CanopyX.Html/Assets/canopyx-editing.css +5 -5
  21. package/CanopyX.Html/Assets/canopyx-editing.js +2 -2
  22. package/CanopyX.Html/Assets/canopyx-enhance.js +5 -5
  23. package/CanopyX.Html/Assets/canopyx-export.js +54 -13
  24. package/CanopyX.Html/Assets/canopyx-facets.css +32 -22
  25. package/CanopyX.Html/Assets/canopyx-facets.js +19 -15
  26. package/CanopyX.Html/Assets/canopyx-filter-editor.css +75 -89
  27. package/CanopyX.Html/Assets/canopyx-filter-editor.js +20 -16
  28. package/CanopyX.Html/Assets/canopyx-flow-checks.css +3 -3
  29. package/CanopyX.Html/Assets/canopyx-flow-checks.js +1 -1
  30. package/CanopyX.Html/Assets/canopyx-flow-command.css +3 -3
  31. package/CanopyX.Html/Assets/canopyx-flow-command.js +1 -1
  32. package/CanopyX.Html/Assets/canopyx-flow-dialog.css +4 -4
  33. package/CanopyX.Html/Assets/canopyx-flow-dialog.js +1 -1
  34. package/CanopyX.Html/Assets/canopyx-flow-drafts.css +2 -2
  35. package/CanopyX.Html/Assets/canopyx-flow-drafts.js +1 -1
  36. package/CanopyX.Html/Assets/canopyx-flow-entry.css +142 -17
  37. package/CanopyX.Html/Assets/canopyx-flow-entry.js +5 -5
  38. package/CanopyX.Html/Assets/canopyx-flow-host.css +2 -2
  39. package/CanopyX.Html/Assets/canopyx-flow-host.js +1 -1
  40. package/CanopyX.Html/Assets/canopyx-flow-module.mjs +5 -5
  41. package/CanopyX.Html/Assets/canopyx-flow-pick.css +4 -4
  42. package/CanopyX.Html/Assets/canopyx-flow-pick.js +1 -1
  43. package/CanopyX.Html/Assets/canopyx-flow-preview.css +1 -1
  44. package/CanopyX.Html/Assets/canopyx-flow-preview.js +1 -1
  45. package/CanopyX.Html/Assets/canopyx-flow-records.css +2 -2
  46. package/CanopyX.Html/Assets/canopyx-flow-records.js +1 -1
  47. package/CanopyX.Html/Assets/canopyx-flow-tasks.css +4 -4
  48. package/CanopyX.Html/Assets/canopyx-flow-tasks.js +1 -1
  49. package/CanopyX.Html/Assets/canopyx-flow.css +41 -41
  50. package/CanopyX.Html/Assets/canopyx-flow.js +1 -1
  51. package/CanopyX.Html/Assets/canopyx-format-editor.css +9 -9
  52. package/CanopyX.Html/Assets/canopyx-format-editor.js +2 -2
  53. package/CanopyX.Html/Assets/canopyx-formatting.css +13 -13
  54. package/CanopyX.Html/Assets/canopyx-formatting.js +12 -11
  55. package/CanopyX.Html/Assets/canopyx-forms.css +3 -3
  56. package/CanopyX.Html/Assets/canopyx-forms.js +1 -1
  57. package/CanopyX.Html/Assets/canopyx-grid-module.mjs +220 -155
  58. package/CanopyX.Html/Assets/canopyx-grid-options.css +8 -8
  59. package/CanopyX.Html/Assets/canopyx-grid-options.js +9 -2
  60. package/CanopyX.Html/Assets/canopyx-grid.css +285 -150
  61. package/CanopyX.Html/Assets/canopyx-grid.js +220 -155
  62. package/CanopyX.Html/Assets/canopyx-grouping.css +23 -16
  63. package/CanopyX.Html/Assets/canopyx-grouping.js +24 -17
  64. package/CanopyX.Html/Assets/canopyx-highlight.css +10 -10
  65. package/CanopyX.Html/Assets/canopyx-highlight.js +1 -1
  66. package/CanopyX.Html/Assets/canopyx-interactive.css +215 -91
  67. package/CanopyX.Html/Assets/canopyx-interactive.js +47 -52
  68. package/CanopyX.Html/Assets/canopyx-labels-de.js +177 -9
  69. package/CanopyX.Html/Assets/canopyx-labels-es.js +177 -9
  70. package/CanopyX.Html/Assets/canopyx-labels-fr.js +176 -8
  71. package/CanopyX.Html/Assets/canopyx-labels-it.js +176 -8
  72. package/CanopyX.Html/Assets/canopyx-labels-pl.js +176 -8
  73. package/CanopyX.Html/Assets/canopyx-layouts.css +49 -21
  74. package/CanopyX.Html/Assets/canopyx-layouts.js +36 -14
  75. package/CanopyX.Html/Assets/canopyx-link.css +3 -3
  76. package/CanopyX.Html/Assets/canopyx-link.js +4 -4
  77. package/CanopyX.Html/Assets/canopyx-links.js +2 -2
  78. package/CanopyX.Html/Assets/canopyx-live.css +3 -5
  79. package/CanopyX.Html/Assets/canopyx-live.js +3 -3
  80. package/CanopyX.Html/Assets/canopyx-matrix.css +32 -39
  81. package/CanopyX.Html/Assets/canopyx-matrix.js +11 -11
  82. package/CanopyX.Html/Assets/canopyx-module.mjs +47 -52
  83. package/CanopyX.Html/Assets/canopyx-office-export.js +2936 -0
  84. package/CanopyX.Html/Assets/canopyx-pager.css +1 -1
  85. package/CanopyX.Html/Assets/canopyx-pager.js +1 -1
  86. package/CanopyX.Html/Assets/canopyx-path.css +45 -0
  87. package/CanopyX.Html/Assets/canopyx-path.js +28 -0
  88. package/CanopyX.Html/Assets/canopyx-pivot.css +75 -0
  89. package/CanopyX.Html/Assets/canopyx-pivot.js +72 -0
  90. package/CanopyX.Html/Assets/canopyx-plan.css +63 -0
  91. package/CanopyX.Html/Assets/canopyx-plan.js +71 -0
  92. package/CanopyX.Html/Assets/canopyx-presenters.js +2 -2
  93. package/CanopyX.Html/Assets/canopyx-record-panel.css +51 -45
  94. package/CanopyX.Html/Assets/canopyx-record-panel.js +30 -22
  95. package/CanopyX.Html/Assets/canopyx-reporting-module.mjs +262 -197
  96. package/CanopyX.Html/Assets/canopyx-reporting.css +300 -164
  97. package/CanopyX.Html/Assets/canopyx-reporting.js +262 -197
  98. package/CanopyX.Html/Assets/canopyx-stack.css +35 -0
  99. package/CanopyX.Html/Assets/canopyx-stack.js +24 -0
  100. package/CanopyX.Html/Assets/canopyx-time-slider.css +18 -0
  101. package/CanopyX.Html/Assets/canopyx-time-slider.js +27 -0
  102. package/CanopyX.Html/Assets/canopyx-timeline.css +19 -19
  103. package/CanopyX.Html/Assets/canopyx-timeline.js +6 -5
  104. package/CanopyX.Html/Assets/canopyx-tree-tools.css +47 -46
  105. package/CanopyX.Html/Assets/canopyx-tree-tools.js +15 -12
  106. package/CanopyX.Html/Assets/canopyx-ui-menu.css +41 -0
  107. package/CanopyX.Html/Assets/canopyx-ui-menu.js +64 -0
  108. package/CanopyX.Html/Assets/canopyx-ui-navigation.css +73 -0
  109. package/CanopyX.Html/Assets/canopyx-ui-navigation.js +39 -0
  110. package/CanopyX.Html/Assets/canopyx-ui-overlays.css +79 -0
  111. package/CanopyX.Html/Assets/canopyx-ui-overlays.js +45 -0
  112. package/CanopyX.Html/Assets/canopyx-ui-picker.css +12 -0
  113. package/CanopyX.Html/Assets/canopyx-ui-picker.js +6 -0
  114. package/CanopyX.Html/Assets/canopyx-ui-stepper.css +174 -0
  115. package/CanopyX.Html/Assets/canopyx-ui-stepper.js +48 -0
  116. package/CanopyX.Html/Assets/canopyx-ui-tabs.css +153 -0
  117. package/CanopyX.Html/Assets/canopyx-ui-tabs.js +47 -0
  118. package/CanopyX.Html/Assets/canopyx-values.css +5 -0
  119. package/CanopyX.Html/Assets/canopyx-values.js +13 -0
  120. package/CanopyX.Html/Assets/canopyx-view-intents.css +12 -0
  121. package/CanopyX.Html/Assets/canopyx-view-intents.js +56 -0
  122. package/CanopyX.Html/Assets/canopyx.css +212 -85
  123. package/CanopyX.Html/Assets/canopyx.js +38 -26
  124. package/JavaScript/board.d.ts +30 -0
  125. package/JavaScript/changes.d.ts +4 -1
  126. package/JavaScript/column-groups.d.ts +24 -4
  127. package/JavaScript/facets.d.ts +5 -3
  128. package/JavaScript/grid.d.ts +161 -17
  129. package/JavaScript/hosts.d.ts +16 -1
  130. package/JavaScript/index.d.ts +4 -2
  131. package/JavaScript/locales/de.mjs +177 -9
  132. package/JavaScript/locales/es.mjs +177 -9
  133. package/JavaScript/locales/fr.mjs +176 -8
  134. package/JavaScript/locales/it.mjs +176 -8
  135. package/JavaScript/locales/pl.mjs +176 -8
  136. package/JavaScript/matrix.d.ts +4 -1
  137. package/JavaScript/path.d.ts +33 -0
  138. package/JavaScript/pivot.d.ts +135 -0
  139. package/JavaScript/plan.d.ts +23 -0
  140. package/JavaScript/protocol.d.ts +18 -3
  141. package/JavaScript/records.d.ts +4 -0
  142. package/JavaScript/stack.d.ts +28 -0
  143. package/JavaScript/time-slider.d.ts +58 -0
  144. package/JavaScript/ui.d.ts +261 -0
  145. package/JavaScript/view-intents.d.ts +45 -0
  146. package/README.md +76 -187
  147. package/README.nuget.md +63 -87
  148. package/ThirdParty/OfficeIMO/LICENSE +21 -0
  149. package/ThirdParty/OfficeIMO/README.md +13 -0
  150. package/package.json +76 -3
@@ -0,0 +1,2936 @@
1
+ /*
2
+ MIT License
3
+
4
+ Copyright (c) 2022 Evotec
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ */
24
+ (function(global){"use strict";const installed=new WeakSet();const part={version:"4fb7a4d570390ee9",install(context){if(installed.has(context.EXPORT_IMPL))return;const{EXPORT_IMPL}=context;(function(root){"use strict";const officeimo=root.OfficeIMO||(root.OfficeIMO={});const cacheKey=Symbol.for("@evotecit/officeimo/modules");const _modules=officeimo[cacheKey]||new Map();if(!officeimo[cacheKey])Object.defineProperty(officeimo,cacheKey,{value:_modules});const _m2=_modules.get("d5c945064d81fdd257960f48c421125e106e5f270427d170bb05587dd96a44ea")??(()=>{const errorBrand=Symbol.for("@evotecit/officeimo/OfficeIMOError");const unsupportedBrand=Symbol.for("@evotecit/officeimo/NotSupportedError");class OfficeIMOError extends Error{code;static[Symbol.hasInstance](value){if(this!==OfficeIMOError)
25
+ return Function.prototype[Symbol.hasInstance].call(this,value);return!!value&&typeof value==="object"&&value[errorBrand]===true}
26
+ constructor(code,message,options){super(message,options);this.code=code;Object.defineProperty(this,errorBrand,{value:true});this.name="OfficeIMOError"}}
27
+ class NotSupportedError extends OfficeIMOError{feature;static[Symbol.hasInstance](value){if(this!==NotSupportedError)
28
+ return Function.prototype[Symbol.hasInstance].call(this,value);return!!value&&typeof value==="object"&&value[unsupportedBrand]===true}
29
+ constructor(feature){super("NOT_SUPPORTED",feature+" is not supported yet.");this.feature=feature;Object.defineProperty(this,unsupportedBrand,{value:true});this.name="NotSupportedError"}}
30
+ const _exports=Object.freeze({OfficeIMOError:OfficeIMOError,NotSupportedError:NotSupportedError});_modules.set("d5c945064d81fdd257960f48c421125e106e5f270427d170bb05587dd96a44ea",_exports);return _exports})();const _m4=_modules.get("87c24efeaa0f1579c19afeeb4918caeb4f8f65a88d24a246e2cfd712b37dbac3")??(()=>{function checkAbort(signal){if(signal?.aborted)
31
+ throw signal.reason}
32
+ function withAbort(promise,signal){if(!signal)
33
+ return Promise.resolve(promise);return new Promise((resolve,reject)=>{const cleanup=()=>signal.removeEventListener("abort",abort);const abort=()=>{cleanup();reject(signal.reason)};signal.addEventListener("abort",abort,{once:true});Promise.resolve(promise).then(value=>{cleanup();resolve(value)},error=>{cleanup();reject(error)});if(signal.aborted)
34
+ abort()})}
35
+ async function*inputRows(input,signal){checkAbort(signal);const iterator=input?.[Symbol.asyncIterator]?.()??input?.[Symbol.iterator]?.();if(!iterator)
36
+ throw new TypeError("Rows must be a synchronous or asynchronous iterable.");let done=false,failed=false;try{while(true){checkAbort(signal);const item=await withAbort(Promise.resolve(iterator.next()),signal);checkAbort(signal);if(item.done){done=true;return}
37
+ yield item.value}}
38
+ catch(error){failed=true;throw error}
39
+ finally{if(!done&&iterator.return){try{const returned=iterator.return();if(signal?.aborted||failed)
40
+ Promise.resolve(returned).catch(()=>{});else
41
+ await withAbort(Promise.resolve(returned),signal)}
42
+ catch(error){if(!signal?.aborted&&!failed)
43
+ throw error}}}}
44
+ const rowConsumers=new WeakMap();function rowsFromBatches(batches){let consumed=false;const claim=()=>{if(consumed)
45
+ throw new TypeError("A row source can be consumed only once.");consumed=true};const rows={[Symbol.asyncIterator](){claim();return iterate()}};async function*iterate(){for await(const batch of inputRows(batches))
46
+ yield*batch}
47
+ rowConsumers.set(rows,(signal,accept)=>{claim();return consumeRows(batches,signal,batch=>consumeRows(batch,signal,accept))});return rows}
48
+ function concatRows(...sources){const rows={async*[Symbol.asyncIterator](){for(const source of sources)
49
+ yield*source}};rowConsumers.set(rows,async(signal,accept)=>{for(const source of sources)
50
+ await consumeRows(source,signal,accept)});return rows}
51
+ async function consumeRows(input,signal,accept){checkAbort(signal);const consume=rowConsumers.get(input);if(consume)
52
+ return consume(signal,accept);const iterator=input?.[Symbol.asyncIterator]?.()??input?.[Symbol.iterator]?.();if(!iterator)
53
+ throw new TypeError("Rows must be a synchronous or asynchronous iterable.");let done=false;try{while(true){checkAbort(signal);let item=iterator.next();const next=item;if(typeof next?.then==="function")
54
+ item=await withAbort(next,signal);checkAbort(signal);const result=item;if(result.done){done=true;return}
55
+ let value=result.value;if(typeof value?.then==="function")
56
+ value=await withAbort(value,signal);checkAbort(signal);const pending=accept(value);if(pending!==undefined)
57
+ await withAbort(pending,signal)}}
58
+ finally{if(!done&&iterator.return){try{void Promise.resolve(iterator.return()).catch(()=>{})}
59
+ catch{/* Preserve the original failure. */ }
60
+ }}}
61
+ let taskDeadline;const taskBudgetMs=32;function beginTask(){taskDeadline=performance.now()+ taskBudgetMs}
62
+ function taskYieldDue(){const now=performance.now();taskDeadline??=now+taskBudgetMs;return now>=taskDeadline}
63
+ function pause(){const scheduler=globalThis.scheduler;if(typeof scheduler?.postTask==="function")
64
+ return scheduler.postTask(()=>{taskDeadline=performance.now()+ taskBudgetMs},{priority:"user-visible"});return new Promise(resolve=>{setTimeout(function finish(){taskDeadline=performance.now()+ taskBudgetMs;resolve()},0)})}
65
+ const _exports=Object.freeze({checkAbort:checkAbort,withAbort:withAbort,inputRows:inputRows,rowsFromBatches:rowsFromBatches,concatRows:concatRows,consumeRows:consumeRows,beginTask:beginTask,taskYieldDue:taskYieldDue,pause:pause});_modules.set("87c24efeaa0f1579c19afeeb4918caeb4f8f65a88d24a246e2cfd712b37dbac3",_exports);return _exports})();const _m3=_modules.get("5337d1e3bd5ae0c1d10a476fcd31540d20337ccf7aa93c7e9e26c2b1a7dab92b")??(()=>{const{checkAbort,consumeRows,withAbort,pause,taskYieldDue}=_m4;const{OfficeIMOError}=_m2;async function withDestination(destination,operation){if(destination&&typeof destination.getWriter==="function"){const writer=destination.getWriter();try{return await operation({write:bytes=>writer.write(new Uint8Array(bytes))})}
66
+ finally{writer.releaseLock()}}
67
+ if(!destination||typeof destination.write!=="function")
68
+ throw new TypeError("Destination must be a ByteSink or WritableStream.");return operation(destination)}
69
+ class BlobByteSink{parts=[];state="open";result;write(bytes){if(this.state!=="open")
70
+ throw new OfficeIMOError("INVALID_STATE","Byte sink is closed.");this.parts.push(new Uint8Array(bytes))}
71
+ toBlob(type="application/octet-stream"){if(this.state==="discarded")
72
+ throw new OfficeIMOError("INVALID_STATE","Byte sink was discarded.");this.state="closed";if(!this.result){this.result=new Blob(this.parts,{type});this.parts=[]}
73
+ return this.result.type===type?this.result:new Blob([this.result],{type})}
74
+ takeChunks(){if(this.state!=="open")
75
+ throw new OfficeIMOError("INVALID_STATE","Byte sink is closed.");const parts=this.parts;this.parts=[];this.state="discarded";return parts}
76
+ discard(){this.parts=[];this.result=undefined;this.state="discarded"}}
77
+ class ChunkedTextSink{sink;signal;chunkSize;text="";encoder=new TextEncoder();constructor(sink,signal,chunkSize=32768){this.sink=sink;this.signal=signal;this.chunkSize=chunkSize;if(!Number.isInteger(chunkSize)||chunkSize<2)
78
+ throw new RangeError("Text chunk size must be at least 2.")}
79
+ append(value){checkAbort(this.signal);this.text +=value;return this.text.length>=this.chunkSize||taskYieldDue()}
80
+ async flush(final=false){checkAbort(this.signal);while(this.text.length){let end=Math.min(this.text.length,this.chunkSize);if(/[\ud800-\udbff]/.test(this.text[end - 1]) && (end < this.text.length || !final))
81
+ end--;if(!end)
82
+ break;const bytes=this.encoder.encode(this.text.slice(0,end));this.text=this.text.slice(end);await withAbort(Promise.resolve(this.sink.write(bytes)),this.signal);if(taskYieldDue())
83
+ await pause();checkAbort(this.signal)}}
84
+ async write(text){if(this.append(text))
85
+ await this.flush()}
86
+ async close(){await this.flush(true)}}
87
+ async function writeBytes(source,sink,signal){await consumeRows(source instanceof Uint8Array?[source]:source,signal,bytes=>{if(!(bytes instanceof Uint8Array))
88
+ throw new TypeError("Byte sources must yield Uint8Array chunks.");const pending=sink.write(bytes);if(taskYieldDue())
89
+ return Promise.resolve(pending).then(()=>{checkAbort(signal);return pause()});return pending})}
90
+ const _exports=Object.freeze({withDestination:withDestination,BlobByteSink:BlobByteSink,ChunkedTextSink:ChunkedTextSink,writeBytes:writeBytes});_modules.set("5337d1e3bd5ae0c1d10a476fcd31540d20337ccf7aa93c7e9e26c2b1a7dab92b",_exports);return _exports})();const _m6=_modules.get("501f5fccaecb27d9e514b74cf64893649e50616692250593d120ca315b510c04")??(()=>{function isDate(value){if(value===null||typeof value!=="object")
91
+ return false;try{if(!(value instanceof Date)&&!(Symbol.toStringTag in value)&&Object.prototype.toString.call(value)!=="[object Date]")
92
+ return false;Date.prototype.getTime.call(value);return true}
93
+ catch{return false}}
94
+ const _exports=Object.freeze({isDate:isDate});_modules.set("501f5fccaecb27d9e514b74cf64893649e50616692250593d120ca315b510c04",_exports);return _exports})();const _m7=_modules.get("d363b84eac65064b2e372063af61a4e9e5c576501693c862628297c812ba7832")??(()=>{function copyExportLink(link){if(!link||typeof link!=="object")
95
+ throw new TypeError("Hyperlinks require an absolute HTTP, HTTPS or mailto target without whitespace or controls.");const{target,tooltip}=link;if(typeof target!=="string"||!/^(?:https?:\/\/|mailto:)/i.test(target) || /[\u0000-\u0020\u007f]/.test(target))
96
+ throw new TypeError("Hyperlinks require an absolute HTTP, HTTPS or mailto target without whitespace or controls.");const url=new URL(target);if((url.protocol==="http:"||url.protocol==="https:")&&(!url.hostname||url.username||url.password))
97
+ throw new TypeError("Hyperlink HTTP targets need a host and must not contain credentials.");if(tooltip!==undefined&&typeof tooltip!=="string")
98
+ throw new TypeError("Hyperlink tooltip must be text.");return Object.freeze({target:url.href,...(tooltip===undefined?{}:{tooltip})})}
99
+ const _exports=Object.freeze({copyExportLink:copyExportLink});_modules.set("d363b84eac65064b2e372063af61a4e9e5c576501693c862628297c812ba7832",_exports);return _exports})();const _m5=_modules.get("732224f6995c2478cf33a6ed01f3e3d3dcccb159a731d6db9280104bd5040fc5")??(()=>{const{isDate}=_m6;const{copyExportLink}=_m7;const exportCellBrand=Symbol.for("@evotecit/officeimo/ExportCell");function copyCellPresentation(value){if(!value||typeof value!=="object"||Array.isArray(value))
100
+ throw new TypeError("Cell presentation must be an object.");const result={};for(const key of["background","color","numberFormat","bold","italic","wrapText","alignment"]){const field=value[key];if(field===undefined)
101
+ continue;if(["bold","italic","wrapText"].includes(key)){if(typeof field!=="boolean")
102
+ throw new TypeError("Cell presentation "+key+" must be boolean.")}
103
+ else if(typeof field!=="string")
104
+ throw new TypeError("Cell presentation "+key+" must be text.");if(key==="alignment"&&!["left","center","right","fill","justify","distributed"].includes(field))
105
+ throw new TypeError("Invalid cell presentation alignment.");result[key]=field}
106
+ return Object.freeze(result)}
107
+ class ExportCell{value;static[Symbol.hasInstance](value){return!!value&&typeof value==="object"&&value[exportCellBrand]===true}
108
+ text;presentation;link;constructor(value,options={}){this.value=value;const{text,presentation,link}=options;if(text!==undefined&&typeof text!=="string")
109
+ throw new TypeError("Display text must be a string.");assertScalar(value);this.text=text;this.presentation=presentation===undefined?undefined:copyCellPresentation(presentation);this.link=link===undefined?undefined:copyExportLink(link);Object.defineProperty(this,exportCellBrand,{value:true});Object.freeze(this)}}
110
+ function assertScalar(value){const kind=typeof value;if(value==null||kind==="string"||kind==="number"||kind==="boolean"||isDate(value))
111
+ return;if(typeof value.then==="function")
112
+ void Promise.resolve(value).catch(()=>{});throw new TypeError("Export values and formatter results must be synchronous strings, numbers, booleans, Dates or null.")}
113
+ function assertExportValue(value){if(value!==null&&typeof value==="object"&&value instanceof ExportCell)
114
+ return;assertScalar(value)}
115
+ const _exports=Object.freeze({copyCellPresentation:copyCellPresentation,ExportCell:ExportCell,assertScalar:assertScalar,assertExportValue:assertExportValue});_modules.set("732224f6995c2478cf33a6ed01f3e3d3dcccb159a731d6db9280104bd5040fc5",_exports);return _exports})();const _m10=_modules.get("50b3c10b690ceff693c8c5f809195ba6845b20e60f408e791a750d2ecbd5c669")??(()=>{function captureFields(input,fields){const captured={...input};for(const field of fields){if(Object.hasOwn(captured,field))
116
+ continue;const value=input[field];if(value!==undefined)
117
+ captured[field]=value}
118
+ return captured}
119
+ const _exports=Object.freeze({captureFields:captureFields});_modules.set("50b3c10b690ceff693c8c5f809195ba6845b20e60f408e791a750d2ecbd5c669",_exports);return _exports})();const _m9=_modules.get("42faf379960e5674a6fdfa8c8fca0bb68bbd74587231248d2524d7004def3671")??(()=>{const{OfficeIMOError}=_m2;const{captureFields}=_m10;class ExportBudget{cells=0;text=0;reservedCells=0;reservedText=0;limits;constructor(limits={}){if(!limits||typeof limits!=="object"||Array.isArray(limits))
120
+ throw new TypeError("Export limits must be an object.");const captured=captureFields(limits,["maxRows","maxCells","maxTextCharacters","maxOutputBytes"]);for(const[key,value]of Object.entries(captured))
121
+ if(value!==undefined&&(!Number.isSafeInteger(value)||value<0))
122
+ throw new RangeError(key+" must be a nonnegative safe integer.");this.limits=Object.freeze(captured)}
123
+ check(kind,value){const maximum=this.limits[kind];if(maximum!==undefined&&value>maximum)
124
+ throw new OfficeIMOError("RESOURCE_LIMIT",kind+" exceeded ("+value+" > "+maximum+").")}
125
+ row(count){this.check("maxRows",count)}
126
+ reserve(cells,characters){this.check("maxCells",this.cells+this.reservedCells+cells);this.check("maxTextCharacters",this.text+this.reservedText+characters);this.reservedCells +=cells;this.reservedText +=characters}
127
+ release(cells,characters){this.reservedCells -=cells;this.reservedText -=characters}
128
+ cell(value,reservedCharacters){if(reservedCharacters!==undefined)
129
+ this.release(1,reservedCharacters);if(this.limits.maxCells===undefined&&this.limits.maxTextCharacters===undefined)
130
+ return;this.check("maxCells",this.cells+this.reservedCells+1);const length=typeof value==="string"?value.length:0;this.check("maxTextCharacters",this.text+this.reservedText+length);this.cells++;this.text +=length}}
131
+ function boundedSink(sink,budget){let bytes=0;return{write(chunk){budget.check("maxOutputBytes",bytes+chunk.length);bytes +=chunk.length;return sink.write(chunk)}}}
132
+ const _exports=Object.freeze({ExportBudget:ExportBudget,boundedSink:boundedSink});_modules.set("42faf379960e5674a6fdfa8c8fca0bb68bbd74587231248d2524d7004def3671",_exports);return _exports})();const _m11=_modules.get("0391fe35ea7d02b25804ab4d0e7543136d6bb615f368f268c74aa135f23aa6bc")??(()=>{const{assertExportValue}=_m5;const{checkAbort}=_m4;const{isDate}=_m6;const{captureFields}=_m10;function createRowProjector(columns,worksheet,signal,validate=assertExportValue){const getters=columns.some(column=>column.value);return(row,rowIndex=0)=>{if(Array.isArray(row)&&!getters){const length=row.length;if(length>columns.length)
133
+ throw new RangeError("Row has more values than declared columns.");const values=new Array(length);for(let index=0;index<length;index++){const value=row[index];validate(value);values[index]=value}
134
+ return values}
135
+ if(!row||typeof row!=="object"||isDate(row))
136
+ throw new TypeError("A row must be an array or object.");if(Array.isArray(row)&&row.length>columns.length&&!columns.every(column=>column.value))
137
+ throw new RangeError("Project every column explicitly when selecting from a wider array row.");return columns.map((c,columnIndex)=>{if(c.value){checkAbort(signal);const context={rowIndex,columnIndex,column:c,...(worksheet?{sheetName:worksheet.sheetName,worksheetRow:worksheet.firstDataRow+rowIndex}:{})};const result=c.value(row,context);validate(result);checkAbort(signal);return result}
138
+ if(Array.isArray(row)){const result=row[columnIndex];validate(result);return result}
139
+ const key=c.key??c.header;const result=Object.prototype.hasOwnProperty.call(row,key)?row[key]:undefined;validate(result);return result})}}
140
+ const columnOptionFields=["header","key","value","width","type","format","wrapText","alignment","rowHeader","groups","style","valueFormatter"];function copyColumns(columns,workbookStyles=false){if(!Array.isArray(columns))
141
+ throw new TypeError("Declare the columns in export order.");return columns.map(c=>{if(!c||typeof c!=="object"&&typeof c!=="function")
142
+ throw new TypeError("Each column needs a string header and an optional string key.");const captured=captureFields(c,columnOptionFields);if(!workbookStyles&&captured.style!==undefined)
143
+ throw new TypeError("Workbook-local column styles require the advanced Workbook API; use portable ExportCell presentation.");if(typeof captured.header!=="string"||(captured.key!==undefined&&typeof captured.key!=="string"))
144
+ throw new TypeError("Each column needs a string header and an optional string key.");if(captured.value!==undefined&&typeof captured.value!=="function")
145
+ throw new TypeError("Column value getters must be functions.");if(captured.rowHeader!==undefined&&typeof captured.rowHeader!=="boolean")
146
+ throw new TypeError("Column rowHeader must be boolean.");if(captured.groups!==undefined){if(!Array.isArray(captured.groups))
147
+ throw new TypeError("Column groups must be an array of strings.");const groups=Array.from(captured.groups);if(groups.some(group=>typeof group!=="string"))
148
+ throw new TypeError("Column groups must be an array of strings.");return{...captured,groups:Object.freeze(groups)}}
149
+ return captured})}
150
+ const _exports=Object.freeze({createRowProjector:createRowProjector,columnOptionFields:columnOptionFields,copyColumns:copyColumns});_modules.set("0391fe35ea7d02b25804ab4d0e7543136d6bb615f368f268c74aa135f23aa6bc",_exports);return _exports})();const _m12=_modules.get("c9fde2c438e186da56f740105fcd41c265fdfdd855a4f1b811d556a02387479b")??(()=>{class NumericAggregate{operation;count=0;sum=0;mean=0;min=Infinity;max=-Infinity;constructor(operation){this.operation=operation}
151
+ accept(value){if(!this.operation||typeof value!=="number"||!Number.isFinite(value))
152
+ return;this.count++;if(this.operation==="sum"){this.sum +=value;if(!Number.isFinite(this.sum))
153
+ throw new RangeError("Numeric total exceeds finite number range.")}
154
+ else if(this.operation==="average"){const delta=value-this.mean;this.mean=this.count===1?value:Number.isFinite(delta)?this.mean+delta / this.count : this.mean * ((this.count - 1) / this.count) + value / this.count;
155
+ }
156
+ else if(this.operation==="min")
157
+ this.min=Math.min(this.min,value);else if(this.operation==="max")
158
+ this.max=Math.max(this.max,value)}
159
+ value(){return this.operation==="count"?this.count:this.operation==="sum"?this.sum:!this.count?null:this.operation==="average"?this.mean:this.operation==="min"?this.min:this.max}}
160
+ function createTotals(columns,totals={}){const keys=columns.map(c=>c.key??c.header);for(const[key,operation]of Object.entries(totals)){if(keys.filter(k=>k===key).length!==1)
161
+ throw new TypeError("Totals need an unambiguous declared column key: "+key);if(!["sum","count","average","min","max"].includes(operation))
162
+ throw new TypeError("Invalid total operation.")}
163
+ return keys.map(key=>new NumericAggregate(Object.prototype.hasOwnProperty.call(totals,key)?totals[key]:undefined))}
164
+ const _exports=Object.freeze({NumericAggregate:NumericAggregate,createTotals:createTotals});_modules.set("c9fde2c438e186da56f740105fcd41c265fdfdd855a4f1b811d556a02387479b",_exports);return _exports})();const _m13=_modules.get("e95bb0e3f342d1379b67a3d541fa808e06361da8460169a6aec152ee7deb69b2")??(()=>{const{ExportCell,assertExportValue}=_m5;const{isDate}=_m6;function copyExportValue(value){assertExportValue(value);if(isDate(value))
165
+ return new Date(Date.prototype.getTime.call(value));if(value instanceof ExportCell){const{value:scalar,text,presentation,link}=value;return new ExportCell(isDate(scalar)?new Date(Date.prototype.getTime.call(scalar)):scalar,{...(text===undefined?{}:{text}),...(presentation===undefined?{}:{presentation}),...(link===undefined?{}:{link})})}
166
+ return value}
167
+ const _exports=Object.freeze({copyExportValue:copyExportValue});_modules.set("e95bb0e3f342d1379b67a3d541fa808e06361da8460169a6aec152ee7deb69b2",_exports);return _exports})();const _m8=_modules.get("046b305cdccf817d847addb75a778131622de23f2840830bbe1c0c26053a68c0")??(()=>{const{ExportCell,assertScalar}=_m5;const{isDate}=_m6;const{checkAbort,inputRows,pause,taskYieldDue}=_m4;const{ExportBudget}=_m9;const{OfficeIMOError}=_m2;const{copyColumns,createRowProjector}=_m11;const{createTotals}=_m12;const{copyExportValue}=_m13;const sources=new WeakMap();function assertGroupedReportSource(value){if(!value||typeof value!=="object"||!sources.has(value))
168
+ throw new TypeError("Create grouped report sources with createGroupedReport.")}
169
+ function groupedReportEvents(source,signal){assertGroupedReportSource(source);return{async*[Symbol.asyncIterator](){const operation=groupedReportOperation(source,signal);try{yield*operation.events}
170
+ finally{operation.dispose()}}}}
171
+ function groupedReportOperation(source,signal){assertGroupedReportSource(source);const factory=sources.get(source),linked=linkedSignals(factory.signal,signal);return{signal:linked.signal,events:factory.events(linked.signal),dispose:linked.dispose}}
172
+ function linkedSignals(source,consumer){if(!source||!consumer||source===consumer)
173
+ return{signal:source??consumer,dispose(){}};const controller=new AbortController(),abortSource=()=>controller.abort(source.reason),abortConsumer=()=>controller.abort(consumer.reason);source.addEventListener("abort",abortSource,{once:true});consumer.addEventListener("abort",abortConsumer,{once:true});if(source.aborted)
174
+ abortSource();else if(consumer.aborted)
175
+ abortConsumer();return{signal:controller.signal,dispose(){source.removeEventListener("abort",abortSource);consumer.removeEventListener("abort",abortConsumer)}}}
176
+ function maximum(value,fallback,name){const result=value??fallback;if(!Number.isSafeInteger(result)||result<0)
177
+ throw new RangeError(name+" must be a nonnegative safe integer.");return result}
178
+ function scalar(value){return value instanceof ExportCell?value.value:value}
179
+ function identity(value){if(value==null)
180
+ return{key:null,id:"null",text:""};if(isDate(value)){const time=Date.prototype.getTime.call(value);if(!Number.isFinite(time))
181
+ throw new TypeError("A group key date must be valid.");return{key:new Date(time),id:"date:"+time,text:new Date(time).toISOString()}}
182
+ if(typeof value==="number"&&!Number.isFinite(value))
183
+ throw new TypeError("A numeric group key must be finite.");const text=String(value);return{key:value,id:typeof value+":"+text,text}}
184
+ function eventKey(value){return isDate(value)?new Date(Date.prototype.getTime.call(value)):value}
185
+ function result(aggregates){return Object.freeze(aggregates.map(aggregate=>aggregate.operation===undefined?null:aggregate.value()))}
186
+ function groupingLevels(input,keys,groupLabel){const selected=typeof input==="string"?[input]:Array.isArray(input)?Array.from(input):undefined;if(!selected||selected.length<1||selected.length>4)
187
+ throw new TypeError("groupBy must declare between one and four grouping levels.");if(groupLabel!==undefined&&typeof groupLabel!=="function")
188
+ throw new TypeError("groupLabel must be a synchronous function.");if(groupLabel&&selected.length!==1)
189
+ throw new TypeError("groupLabel is only available for one grouping level; use descriptor labels for a hierarchy.");const seen=new Set();return Object.freeze(selected.map(level=>{if(typeof level!=="string"&&(!level||typeof level!=="object"||Array.isArray(level)))
190
+ throw new TypeError("A grouping level must name a stable column key or provide a descriptor.");const{key,value,label}=typeof level==="string"?{key:level,value:undefined,label:undefined}:level;if(typeof key!=="string"||!key.length||seen.has(key))
191
+ throw new TypeError("Grouping levels need unique, nonempty stable keys.");seen.add(key);if(value!==undefined&&typeof value!=="function")
192
+ throw new TypeError("Grouping value getters must be synchronous functions.");if(label!==undefined&&typeof label!=="function")
193
+ throw new TypeError("Grouping labels must be synchronous functions.");if(label&&groupLabel)
194
+ throw new TypeError("Specify either groupLabel or the grouping descriptor label.");const column=keys.indexOf(key);if(column>=0&&value!==undefined)
195
+ throw new TypeError("A declared grouping column reuses its projected value; do not provide another value getter.");if(column<0&&value===undefined)
196
+ throw new TypeError("groupBy must name a declared stable column key; hidden grouping fields need an explicit value getter.");return Object.freeze({key,column,value,label:label??groupLabel})}))}
197
+ function groupPath(active){return Object.freeze(active.map(({group})=>Object.freeze({...group,key:eventKey(group.key)})))}
198
+ function labelText(format,key,fallback){if(!format)
199
+ return fallback;const formatted=format(eventKey(key));if(typeof formatted?.then==="function")
200
+ void Promise.resolve(formatted).catch(()=>{});if(typeof formatted!=="string")
201
+ throw new TypeError("Grouping labels must return synchronous text.");return formatted}
202
+ function createGroupedReport(rows,options){if(!options||typeof options!=="object")
203
+ throw new TypeError("Grouped report options are required.");const{columns:selected,groupBy,totals:selectedTotals,groupLabel,maxGroups:requestedGroups,maxGroupKeyCharacters:requestedCharacters,signal:sourceSignal,limits}=options;if(limits!==undefined&&(!limits||typeof limits!=="object"||Array.isArray(limits)))
204
+ throw new TypeError("Grouped source limits must be an object.");if(limits!==undefined&&"maxOutputBytes" in limits)
205
+ throw new TypeError("Set maxOutputBytes on the format writer, not the grouped source.");if(!Array.isArray(selected)||!selected.length)
206
+ throw new TypeError("A grouped report needs declared columns.");const columns=copyColumns(selected);const keys=columns.map(column=>column.key);if(keys.some(key=>typeof key!=="string"||key.length===0)||new Set(keys).size!==keys.length)
207
+ throw new TypeError("Grouped report columns need unique, nonempty stable keys.");const levels=groupingLevels(groupBy,keys,groupLabel);const totals=Object.freeze({...selectedTotals});const grand=createTotals(columns,totals);for(let column=0;column<columns.length;column++)
208
+ if(grand[column].operation!==undefined&&columns[column].type!=="number")
209
+ throw new TypeError("Grouped numeric totals require a column declared with type:number.");const maxGroups=maximum(requestedGroups,1000,"maxGroups");const maxCharacters=maximum(requestedCharacters,1000000,"maxGroupKeyCharacters");const budget=new ExportBudget(limits);const portable=Object.freeze(columns.map(column=>{const{value:_getter,...metadata}=column;return Object.freeze(metadata)}));for(const column of columns){budget.cell(column.header);for(const group of column.groups??[])
210
+ budget.reserve(0,group.length);Object.freeze(column)}
211
+ let consumed=false;const eventsFor=(signal)=>Object.freeze({[Symbol.asyncIterator](){if(consumed)
212
+ throw new TypeError("A grouped report source can be consumed only once.");consumed=true;return iterate(signal)}});const events=eventsFor(sourceSignal);async function*iterate(signal){const project=createRowProjector(columns,undefined,signal);const seen=new Set(),active=[];let characters=0,rowCount=0,groups=0;for await(const input of inputRows(rows,signal)){const snapshot=Array.isArray(input)?Array.from(input):input;const projected=project(snapshot,rowCount),values=[];for(let column=0;column<columns.length;column++)
213
+ values.push(copyExportValue(projected[column])??null);checkAbort(signal);const next=levels.map((level,index)=>{checkAbort(signal);const value=level.column>=0?scalar(values[level.column]):level.value(snapshot,Object.freeze({rowIndex:rowCount,level:index,key:level.key}));assertScalar(value);checkAbort(signal);return identity(value)});budget.row(rowCount+1);for(let column=0;column<values.length;column++){const value=values[column],raw=scalar(value);if(grand[column].operation!==undefined&&raw!=null&&(typeof raw!=="number"||!Number.isFinite(raw)))
214
+ throw new TypeError("Grouped numeric metrics must resolve to finite numbers or null.");budget.cell(raw);if(value instanceof ExportCell&&value.text!==undefined)
215
+ budget.reserve(0,value.text.length)}
216
+ let common=0;while(common<active.length&&active[common].id===next[common].id)
217
+ common++;const pending=[];for(let level=common;level<levels.length;level++){const value=next[level],parent=pending.at(-1)??active[level-1];const scopedId=(parent?.group.groupIndex??-1)+ ":"+value.id;if(seen.has(scopedId))
218
+ throw new TypeError("Grouped rows must be contiguous; a closed group key occurred again within the same parent.");if(groups===maxGroups)
219
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxGroups exceeded.");const label=labelText(levels[level].label,value.key,value.text);checkAbort(signal);const nextCharacters=characters+scopedId.length+label.length;if(!Number.isSafeInteger(nextCharacters)||nextCharacters>maxCharacters)
220
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxGroupKeyCharacters exceeded.");budget.reserve(0,label.length);pending.push({id:value.id,group:Object.freeze({groupIndex:groups,key:value.key,label,level}),rows:0,aggregates:createTotals(columns,totals)});characters=nextCharacters;seen.add(scopedId);groups++}
221
+ while(active.length>common){checkAbort(signal);const path=groupPath(active),ending=active.pop();yield Object.freeze({kind:"groupEnd",...path.at(-1),path,rows:ending.rows,totals:result(ending.aggregates)})}
222
+ for(const opening of pending){checkAbort(signal);active.push(opening);const path=groupPath(active);yield Object.freeze({kind:"groupStart",...path.at(-1),path})}
223
+ for(let column=0;column<values.length;column++){const raw=scalar(values[column]);for(const group of active)
224
+ group.aggregates[column].accept(raw);grand[column].accept(raw)}
225
+ for(const group of active)
226
+ group.rows++;checkAbort(signal);yield Object.freeze({kind:"row",values:Object.freeze(values),rowIndex:rowCount,groupIndex:active.at(-1).group.groupIndex,path:groupPath(active)});rowCount++;if(taskYieldDue()){await pause();checkAbort(signal)}}
227
+ checkAbort(signal);while(active.length){checkAbort(signal);const path=groupPath(active),ending=active.pop();yield Object.freeze({kind:"groupEnd",...path.at(-1),path,rows:ending.rows,totals:result(ending.aggregates)})}
228
+ checkAbort(signal);yield Object.freeze({kind:"complete",rows:rowCount,groups,totals:result(grand)})}
229
+ const source=Object.freeze({columns:portable,groupBy:Object.freeze(levels.map(level=>level.key)),totals,events});sources.set(source,{signal:sourceSignal,events:eventsFor});return source}
230
+ const _exports=Object.freeze({assertGroupedReportSource:assertGroupedReportSource,groupedReportEvents:groupedReportEvents,groupedReportOperation:groupedReportOperation,createGroupedReport:createGroupedReport});_modules.set("046b305cdccf817d847addb75a778131622de23f2840830bbe1c0c26053a68c0",_exports);return _exports})();const _m1=_modules.get("81b3d47c02b7d8443b79e02b3cfb52032d6b73d9a3fb592b777ebe028ad0ef00")??(()=>{const{OfficeIMOError}=_m2;function detectFeatures(){let deflateRaw=false;if(typeof CompressionStream==="function"){try{new CompressionStream("deflate-raw");deflateRaw=true}
231
+ catch{/* stored fallback */ }
232
+ }
233
+ return{blob:typeof Blob==="function",streams:typeof WritableStream==="function",deflateRaw,download:typeof document!=="undefined"&&typeof URL.createObjectURL==="function"}}
234
+ function saveBlob(blob,fileName){if(!(blob instanceof Blob)||typeof fileName!=="string"||!fileName)
235
+ throw new TypeError("A Blob and file name are required.");if(typeof document==="undefined"||typeof URL.createObjectURL!=="function")
236
+ throw new OfficeIMOError("PLATFORM_UNAVAILABLE","saveBlob requires a browser document and object URLs.");const url=URL.createObjectURL(blob),link=document.createElement("a");try{link.href=url;link.download=fileName;document.body.append(link);link.click()}
237
+ finally{link.remove();setTimeout(()=>URL.revokeObjectURL(url),30000)}}
238
+ const _exports=Object.freeze({OfficeIMOError:_m2.OfficeIMOError,NotSupportedError:_m2.NotSupportedError,BlobByteSink:_m3.BlobByteSink,ChunkedTextSink:_m3.ChunkedTextSink,writeBytes:_m3.writeBytes,ExportCell:_m5.ExportCell,createGroupedReport:_m8.createGroupedReport,checkAbort:_m4.checkAbort,withAbort:_m4.withAbort,inputRows:_m4.inputRows,pause:_m4.pause,detectFeatures:detectFeatures,saveBlob:saveBlob});_modules.set("81b3d47c02b7d8443b79e02b3cfb52032d6b73d9a3fb592b777ebe028ad0ef00",_exports);return _exports})();const _m14=_modules.get("6cfd3e806439f6301003a2d1699a74fdfa574d935550ab62b97b528728eaee1f")??(()=>{function notifyProgress(callback,progress){if(!callback)
239
+ return;const result=callback(progress);if(result&&typeof result.then==="function"){void Promise.resolve(result).catch(()=>{});throw new TypeError("onProgress must be synchronous.")}}
240
+ const _exports=Object.freeze({notifyProgress:notifyProgress});_modules.set("6cfd3e806439f6301003a2d1699a74fdfa574d935550ab62b97b528728eaee1f",_exports);return _exports})();const _m16=_modules.get("f0627ba89e5c8fcb376ebe3ce72dcc8d68c34952981f8703e36b8bb1a9894208")??(()=>{const{captureFields}=_m10;function captureCsvOptions(input){if(!input||typeof input!=="object")
241
+ throw new TypeError("CSV options are required.");return captureFields(input,["columns","signal","limits","onProgress","valueMode","delimiter","lineEnding","bom","includeHeader","headerRows","footer","spanMode","formulaInjectionProtection","quote","nullValue","booleanText"])}
242
+ const _exports=Object.freeze({captureCsvOptions:captureCsvOptions});_modules.set("f0627ba89e5c8fcb376ebe3ce72dcc8d68c34952981f8703e36b8bb1a9894208",_exports);return _exports})();const _m18=_modules.get("d56b24243cff6f3552a2f7b45521af4491494375ec76117e9ac1ebb047ce02da")??(()=>{const{assertExportValue}=_m5;const{copyExportValue}=_m13;function captureTableSpans(rows,columns){if(!Array.isArray(rows)||!rows.length||rows.length>16)
243
+ throw new RangeError("Spanned headings/footers need from 1 through 16 rows.");const captured=rows.map(row=>{if(!Array.isArray(row)||row.length!==columns)
244
+ throw new TypeError("Spanned rows must have the declared column count.");return Object.freeze(row.map(cell=>{if(cell===null)
245
+ return null;if(!cell||typeof cell!=="object")
246
+ throw new TypeError("Uncovered heading/footer cells need an anchor value.");const{value,columnSpan,rowSpan}=cell;return Object.freeze({value:copyExportValue(value),...(columnSpan===undefined?{}:{columnSpan}),...(rowSpan===undefined?{}:{rowSpan})})}))});tableSpans(captured,columns);return Object.freeze(captured)}
247
+ function tableSpans(rows,columns){if(!Array.isArray(rows)||!rows.length||rows.length>16)
248
+ throw new RangeError("Spanned headings/footers need from 1 through 16 rows.");const covered=Array.from({length:rows.length},()=>new Uint8Array(columns));return rows.map((row,level)=>{if(!Array.isArray(row)||row.length!==columns)
249
+ throw new TypeError("Spanned rows must have the declared column count.");const anchors=[];for(let first=0;first<columns;first++){const cell=row[first];if(covered[level][first]){if(cell!==null)
250
+ throw new TypeError("Covered heading/footer cells must be null.");continue}
251
+ if(!cell||typeof cell!=="object")
252
+ throw new TypeError("Uncovered heading/footer cells need an anchor value.");const span=cell.columnSpan??1,rowSpan=cell.rowSpan??1;if(!Number.isInteger(span)||!Number.isInteger(rowSpan)||span<1||rowSpan<1||first+span>columns||level+rowSpan>rows.length)
253
+ throw new RangeError("Heading/footer spans must stay inside the declared matrix.");const value=cell.value;assertExportValue(value);for(let r=level;r<level+rowSpan;r++)
254
+ for(let c=first;c<first+span;c++){if(covered[r][c])
255
+ throw new TypeError("Heading/footer spans overlap.");if((r!==level||c!==first)&&rows[r]?.[c]!==null)
256
+ throw new TypeError("Covered heading/footer cells must be null.");covered[r][c]=1}
257
+ anchors.push(Object.freeze({first,span,rowSpan,value}))}
258
+ return Object.freeze(anchors)})}
259
+ const _exports=Object.freeze({captureTableSpans:captureTableSpans,tableSpans:tableSpans});_modules.set("d56b24243cff6f3552a2f7b45521af4491494375ec76117e9ac1ebb047ce02da",_exports);return _exports})();const _m20=_modules.get("49927994ccf68595c9211828bccb16a874fa149bda2ea904d369d9943e93bc58")??(()=>{const{captureFields}=_m10;function positive(value,name,max=14400){if(!Number.isFinite(value)||value<=0||value>max)
260
+ throw new RangeError(name+" must be positive and at most "+max+".");return value}
261
+ function color(value){if(typeof value!=="string"||!/^#?[0-9a-f]{6}$/i.test(value))
262
+ throw new TypeError("PDF colors must be six-digit RGB hex strings.");const hex=value.replace(/^#/, "");
263
+ return[0,2,4].map(i=>String(Math.round(parseInt(hex.slice(i,i+2),16)/ 255 * 10000) / 10000)).join(" ");
264
+ }
265
+ function presentation(value={}){if(!value||typeof value!=="object")
266
+ throw new TypeError("PDF presentation must be an object.");const snapshot=captureFields(value,["background","color","numberFormat","bold","italic","wrapText","alignment"]);if(snapshot.background!==undefined)
267
+ color(snapshot.background);if(snapshot.color!==undefined)
268
+ color(snapshot.color);for(const key of["bold","italic","wrapText"])
269
+ if(snapshot[key]!==undefined&&typeof snapshot[key]!=="boolean")
270
+ throw new TypeError("PDF presentation "+key+" must be boolean.");if(snapshot.alignment!==undefined&&!["left","center","right"].includes(snapshot.alignment))
271
+ throw new TypeError("PDF table alignment supports left, center and right.");return Object.freeze(snapshot)}
272
+ const _exports=Object.freeze({positive:positive,color:color,presentation:presentation});_modules.set("49927994ccf68595c9211828bccb16a874fa149bda2ea904d369d9943e93bc58",_exports);return _exports})();const _m19=_modules.get("278e6adc6a5d4491e688589ef165bd1aa9cc74f557da6f9d6bdf53ecc0c6df47")??(()=>{const{OfficeIMOError}=_m2;const{positive,presentation}=_m20;const fields=["fontSize","presentation","keepTogether","keepWithNext","spaceBefore","spaceAfter"];const presentationFields=["bold","italic","color","alignment"];function captureParagraphStyle(input){if(input&&typeof input.then==="function"){void Promise.resolve(input).catch(()=>{});throw new TypeError("PDF paragraph styles must be synchronous objects.")}
273
+ if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some(key=>!fields.includes(key)))
274
+ throw new TypeError("PDF paragraph styles support fontSize, presentation, keepTogether, keepWithNext, spaceBefore and spaceAfter.");const{fontSize,presentation:inputPresentation,keepTogether,keepWithNext,spaceBefore,spaceAfter}=input;if(fontSize!==undefined)
275
+ positive(fontSize,"Paragraph font size",144);for(const[name,flag]of[["keepTogether",keepTogether],["keepWithNext",keepWithNext]])
276
+ if(flag!==undefined&&typeof flag!=="boolean")
277
+ throw new TypeError("Paragraph "+name+" must be boolean.");for(const value of[spaceBefore,spaceAfter])
278
+ if(value!==undefined&&(!Number.isFinite(value)||value<0||value>14400))
279
+ throw new RangeError("Paragraph spacing must be from zero through 14,400 points.");if(inputPresentation!==undefined&&(!inputPresentation||typeof inputPresentation!=="object"||Array.isArray(inputPresentation)||
280
+ Object.keys(inputPresentation).some(key=>!presentationFields.includes(key))))
281
+ throw new TypeError("PDF paragraph presentation supports bold, italic, color and alignment.");return Object.freeze({...(fontSize===undefined?{}:{fontSize}),...(inputPresentation===undefined?{}:{presentation:presentation(inputPresentation)}),...(keepTogether===undefined?{}:{keepTogether}),...(keepWithNext===undefined?{}:{keepWithNext}),...(spaceBefore===undefined?{}:{spaceBefore}),...(spaceAfter===undefined?{}:{spaceAfter})})}
282
+ function captureParagraphStyles(input,maximum){if(!Number.isSafeInteger(maximum)||maximum<0)
283
+ throw new RangeError("maxParagraphStyles must be a nonnegative safe integer.");const result=Object.create(null);if(input===undefined)
284
+ return Object.freeze(result);if(input&&typeof input.then==="function"){void Promise.resolve(input).catch(()=>{});throw new TypeError("paragraphStyles must be a synchronous record.")}
285
+ if(!input||typeof input!=="object"||Array.isArray(input))
286
+ throw new TypeError("paragraphStyles must be a record of named paragraph styles.");const names=Object.keys(input);if(names.length>maximum)
287
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxParagraphStyles exceeded.");for(const name of names){if(!name.trim())
288
+ throw new TypeError("Paragraph style names must be nonempty text.");result[name]=captureParagraphStyle(input[name])}
289
+ return Object.freeze(result)}
290
+ function resolveParagraphStyle(name,overrides,styles){let named={};if(name!==undefined){if(typeof name!=="string"||!Object.prototype.hasOwnProperty.call(styles,name))
291
+ throw new TypeError("Unknown PDF paragraph style: "+String(name));named=styles[name]}
292
+ const captured=captureParagraphStyle(overrides);return Object.freeze({...named,...captured,...(named.presentation||captured.presentation?{presentation:Object.freeze({...named.presentation,...captured.presentation})}:{})})}
293
+ const _exports=Object.freeze({captureParagraphStyle:captureParagraphStyle,captureParagraphStyles:captureParagraphStyles,resolveParagraphStyle:resolveParagraphStyle});_modules.set("278e6adc6a5d4491e688589ef165bd1aa9cc74f557da6f9d6bdf53ecc0c6df47",_exports);return _exports})();const _m21=_modules.get("9b33d9107e62ba8299c576072de40d24a261464f118de4ace64f23154fc78307")??(()=>{const defaultBooleanText=Object.freeze({true:"True",false:"False"});function captureBooleanText(input){if(input===undefined)
294
+ return defaultBooleanText;if(!input||typeof input!=="object")
295
+ throw new TypeError("booleanText must contain true and false strings.");const yes=input.true,no=input.false;if(typeof yes!=="string"||typeof no!=="string")
296
+ throw new TypeError("booleanText must contain true and false strings.");return Object.freeze({true:yes,false:no})}
297
+ const _exports=Object.freeze({defaultBooleanText:defaultBooleanText,captureBooleanText:captureBooleanText});_modules.set("9b33d9107e62ba8299c576072de40d24a261464f118de4ace64f23154fc78307",_exports);return _exports})();const _m17=_modules.get("4a089607f7cbe50e13d4382d1cc4e5f6ce32c5773bbec2df84178710f54d9a38")??(()=>{const{OfficeIMOError}=_m2;const{ExportBudget}=_m9;const{copyColumns}=_m11;const{captureTableSpans}=_m18;const{copyExportValue}=_m13;const{captureFields}=_m10;const{captureParagraphStyles}=_m19;const{captureBooleanText}=_m21;const{positive,color,presentation}=_m20;const sizes={A3:{width:841.89,height:1190.551},A4:{width:595.276,height:841.89},A5:{width:419.528,height:595.276},LETTER:{width:612,height:792},LEGAL:{width:612,height:1008},TABLOID:{width:792,height:1224}};const pdfOptionFields=["columns","signal","onProgress","limits","textShaper","textDirection","pageSize","orientation","margins","fonts","tagged","fontSize","title","messageTop","messageBottom","includeHeader","headerRows","footer","headerPresentation","footerPresentation","alternateRowColor","padding","columnWidths","wideTable","pageHeader","pageFooter","pageNumbers","pageNumberLabels","booleanText","formatValue","formatRuns","compression","paragraphStyles"];const pdfLimitFields=["maxRows","maxCells","maxTextCharacters","maxOutputBytes","maxPages","maxColumns","maxTableBands","maxTableWindowRows","maxCellCharacters","maxTextRuns","maxGroupBlocks","maxRowLines","maxFontBytes","maxPageBytes","maxHyperlinks","maxImageBytes","maxImagePixels","maxImageWorkingBytes","maxVectorCommands","maxDrawingElements","maxStructureElements","maxMarkedContentReferences","maxSections","maxBookmarks","maxListItems","maxParagraphStyles"];function capturePdfOptions(input){if(!input||typeof input!=="object"||Array.isArray(input))
298
+ throw new TypeError("PDF options must be an object.");const captured=captureFields(input,pdfOptionFields);const policy=captured.wideTable;return{...captured,...(policy===undefined?{}:{wideTable:captureWideTable(policy)})}}
299
+ function capturePdfLimits(input){if(!input||typeof input!=="object"||Array.isArray(input))
300
+ throw new TypeError("PDF limits must be an object.");const captured=captureFields(input,pdfLimitFields);for(const[key,value]of Object.entries(captured))
301
+ if(value!==undefined&&(!Number.isSafeInteger(value)||value<0))
302
+ throw new RangeError(key+" must be a nonnegative safe integer.");return Object.freeze(captured)}
303
+ function captureFooter(input,columns){if(!input||typeof input!=="object"||Array.isArray(input))
304
+ throw new TypeError("PDF footer must be an object.");const{values,totals,rows}=input;if(values!==undefined&&!Array.isArray(values))
305
+ throw new TypeError("PDF footer values must be an array.");return Object.freeze({...(values===undefined?{}:{values:Object.freeze(values.map(copyExportValue))}),...(totals===undefined?{}:{totals:Object.freeze({...totals})}),...(rows===undefined?{}:{rows:captureTableSpans(rows,columns)})})}
306
+ function captureWideTable(input){if(input===undefined||input==="fit"||input==="reject")
307
+ return input;if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some(key=>!["mode","minimumColumnWidth","repeatColumns"].includes(key)))
308
+ throw new TypeError("wideTable must be fit, reject or a bands policy.");const{mode,minimumColumnWidth,repeatColumns}=input;if(mode!=="bands")
309
+ throw new TypeError("wideTable.mode must be bands.");if(minimumColumnWidth!==undefined)
310
+ positive(minimumColumnWidth,"Minimum PDF column width");if(repeatColumns!==undefined&&!Array.isArray(repeatColumns))
311
+ throw new TypeError("repeatColumns must be an array.");const repeats=repeatColumns===undefined?[]:[...repeatColumns];if(repeats.some(value=>typeof value==="number"?!Number.isSafeInteger(value)||value<0:typeof value!=="string"||!value.length))
312
+ throw new RangeError("repeatColumns must contain nonnegative indices or nonempty stable keys.");if(repeats.every(value=>typeof value==="number")&&repeats.some((value,index)=>index>0&&value<=repeats[index-1]))
313
+ throw new RangeError("Numeric repeatColumns must contain sorted unique nonnegative indices.");return Object.freeze({mode,...(minimumColumnWidth===undefined?{}:{minimumColumnWidth}),repeatColumns:Object.freeze(repeats)})}
314
+ function repeatedColumns(policy,columns){if(typeof policy!=="object")
315
+ return Object.freeze([]);const selected=new Set();for(const selector of policy.repeatColumns??[]){let position;if(typeof selector==="number")
316
+ position=selector;else{position=columns.findIndex(column=>column.key===selector);if(position<0||columns.some((column,index)=>index!==position&&column.key===selector))
317
+ throw new TypeError("repeatColumns requires an unambiguous selected column key: "+selector)}
318
+ if(position>=columns.length)
319
+ throw new RangeError("repeatColumns index exceeds the declared columns.");if(selected.has(position))
320
+ throw new TypeError("repeatColumns selects the same column more than once.");selected.add(position)}
321
+ return Object.freeze([...selected].sort((left,right)=>left-right))}
322
+ function settings(input,document=false){const configuration={...capturePdfOptions(input)};configuration.booleanText=captureBooleanText(configuration.booleanText);if(configuration.limits!==undefined)
323
+ configuration.limits=capturePdfLimits(configuration.limits);if(configuration.pageSize&&typeof configuration.pageSize==="object")
324
+ configuration.pageSize=Object.freeze(captureFields(configuration.pageSize,["width","height"]));if(configuration.margins&&typeof configuration.margins==="object")
325
+ configuration.margins=Object.freeze(captureFields(configuration.margins,["top","right","bottom","left"]));if(configuration.pageNumberLabels!==undefined){const labels=configuration.pageNumberLabels;if(!labels||typeof labels!=="object"||Array.isArray(labels))
326
+ throw new TypeError("pageNumberLabels must provide literal text.");const{prefix="Page ",separator=" of ",suffix=""}=labels;if([prefix,separator,suffix].some(value=>typeof value!=="string"))
327
+ throw new TypeError("Page-number labels must be text.");configuration.pageNumberLabels=Object.freeze({prefix,separator,suffix})}
328
+ const textShaper=configuration.textShaper,shapeLine=textShaper?.shapeLine;if(textShaper!==undefined&&(!textShaper||typeof shapeLine!=="function"))
329
+ throw new TypeError("textShaper must provide shapeLine.");if(configuration.textDirection!==undefined&&!["auto","ltr","rtl"].includes(configuration.textDirection))
330
+ throw new TypeError("textDirection must be auto, ltr or rtl.");const columns=document?[]:copyColumns(configuration.columns).map(c=>Object.freeze(c));if(document)
331
+ configuration.includeHeader=false;if(!columns.length&&!document)
332
+ throw new TypeError("PDF tables need at least one declared column.");const capturedFonts=configuration.fonts===undefined?undefined:captureFields(configuration.fonts,["regular","bold","italic","boldItalic"]);const options={...configuration,columns,...(textShaper?{textShaper:Object.freeze({shapeLine:shapeLine.bind(textShaper)})}:{}),...(configuration.tagged?{tagged:Object.freeze(captureFields(configuration.tagged,["language"]))}:{}),...(configuration.headerRows?{headerRows:captureTableSpans(configuration.headerRows,columns.length)}:{}),...(capturedFonts?{fonts:Object.freeze(capturedFonts)}:{}),...(configuration.columnWidths?{columnWidths:Object.freeze([...configuration.columnWidths])}:{}),...(configuration.footer===undefined?{}:{footer:captureFooter(configuration.footer,columns.length)}),headerPresentation:Object.freeze({background:"e7edf5",bold:true,...presentation(configuration.headerPresentation)}),footerPresentation:Object.freeze({background:"eef2f6",bold:true,...presentation(configuration.footerPresentation)})};const budget=new ExportBudget(options.limits);const limits={maxPages:10000,maxColumns:1024,maxTableBands:64,maxTableWindowRows:256,maxCellCharacters:1000000,maxTextRuns:10000,maxGroupBlocks:256,maxRowLines:100000,maxFontBytes:16*1024*1024,maxPageBytes:8*1024*1024,maxHyperlinks:100000,maxImageBytes:32*1024*1024,maxImagePixels:16*1024*1024,maxVectorCommands:100000,maxDrawingElements:100000,maxStructureElements:1000000,maxMarkedContentReferences:2000000,maxListItems:100000,maxParagraphStyles:256,maxSections:1000,maxBookmarks:10000};for(const key of Object.keys(limits)){const override=options.limits?.[key];if(override!==undefined)
333
+ limits[key]=override}
334
+ const paragraphStyles=captureParagraphStyles(options.paragraphStyles,limits.maxParagraphStyles);if(columns.length>limits.maxColumns)
335
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxColumns exceeded.");const size=typeof options.pageSize==="string"||options.pageSize===undefined?sizes[options.pageSize??"A4"]:options.pageSize;if(!size)
336
+ throw new TypeError("Unsupported PDF page size.");positive(size.width,"Page width");positive(size.height,"Page height");if(options.orientation!==undefined&&!["portrait","landscape"].includes(options.orientation))
337
+ throw new TypeError("Invalid PDF orientation.");const landscape=options.orientation==="landscape",page={width:landscape?Math.max(size.width,size.height):Math.min(size.width,size.height),height:landscape?Math.min(size.width,size.height):Math.max(size.width,size.height)};const margins={top:36,right:36,bottom:36,left:36,...(typeof options.margins==="number"?{top:options.margins,right:options.margins,bottom:options.margins,left:options.margins}:options.margins)};for(const value of Object.values(margins))
338
+ if(!Number.isFinite(value)||value<0)
339
+ throw new RangeError("PDF margins must be finite and nonnegative.");if(margins.left+margins.right>=page.width||margins.top+margins.bottom>=page.height)
340
+ throw new RangeError("PDF margins leave no content area.");const fontSize=positive(options.fontSize??9,"Font size",144),padding=options.padding??4;if(!Number.isFinite(padding)||padding<0||padding>72)
341
+ throw new RangeError("PDF padding must be from 0 through 72 points.");for(const key of["title","messageTop","messageBottom"])
342
+ if(options[key]!==undefined&&typeof options[key]!=="string")
343
+ throw new TypeError(key+" must be text.");for(const key of["pageHeader","pageFooter"])
344
+ if(options[key]!==undefined&&typeof options[key]!=="string"&&typeof options[key]!=="function")
345
+ throw new TypeError(key+" must be text or a synchronous callback.");for(const key of["formatValue","formatRuns"])
346
+ if(options[key]!==undefined&&typeof options[key]!=="function")
347
+ throw new TypeError(key+" must be a synchronous function.");for(const key of["compression","includeHeader","pageNumbers"])
348
+ if(options[key]!==undefined&&typeof options[key]!=="boolean")
349
+ throw new TypeError(key+" must be boolean.");if(options.alternateRowColor!==undefined)
350
+ color(options.alternateRowColor);if(options.footer?.values&&options.footer.values.length>columns.length)
351
+ throw new RangeError("Footer has more values than declared columns.");if(options.footer?.rows&&(options.footer.values!==undefined||options.footer.totals!==undefined))
352
+ throw new TypeError("Structured footer rows cannot be combined with values/totals.");if(options.headerRows&&options.includeHeader===false)
353
+ throw new TypeError("headerRows requires includeHeader.");if(options.tagged!==undefined){if(!options.tagged||typeof options.tagged!=="object"||typeof options.tagged.language!=="string"||options.tagged.language.length>63)
354
+ throw new TypeError("tagged.language must be a language tag such as en or en-US.");try{if(Intl.getCanonicalLocales(options.tagged.language).length!==1)
355
+ throw new RangeError()}
356
+ catch{throw new TypeError("tagged.language must be a language tag such as en or en-US.")}}
357
+ const maxImageWorkingBytes=options.limits?.maxImageWorkingBytes;return{options:{...options,paragraphStyles},paragraphStyles,page,margins,fontSize,padding,repeatedColumns:document?Object.freeze([]):repeatedColumns(options.wideTable,columns),limits:{...limits,...(maxImageWorkingBytes===undefined?{}:{maxImageWorkingBytes})},budget}}
358
+ const _exports=Object.freeze({positive:_m20.positive,color:_m20.color,presentation:_m20.presentation,pdfOptionFields:pdfOptionFields,pdfLimitFields:pdfLimitFields,capturePdfOptions:capturePdfOptions,capturePdfLimits:capturePdfLimits,captureWideTable:captureWideTable,settings:settings});_modules.set("4a089607f7cbe50e13d4382d1cc4e5f6ce32c5773bbec2df84178710f54d9a38",_exports);return _exports})();const _m22=_modules.get("e00bc0213b723678d050e3e1f11b39ed3d6b0b0fd6a39b403beb1a6bef69e282")??(()=>{const{captureFields}=_m10;const workbookOptionFields=["signal","onProgress","limits","sink","dateMode","compression","invalidCharacterPolicy","appProperties","cellValueWriters","oversizedText","creator","title","subject","description","created","modified"];const sheetOptionFields=["columns","includeHeader","headerRows","freezeHeader","autoFilter","boldHeader","headerFill","headerStyle","alternatingRowStyle","rowStyle","cellStyle","rowOutline","maxOutlineLevel","rowHeight","headerHeight","defaultColumnWidth","freezeColumns","table","autoSize","footer","print","title","mergedCells","hyperlinks","conditionalFormats","dataValidation"];const workbookLimitFields=["maxRows","maxCells","maxTextCharacters","maxOutputBytes","maxStyles","maxSheets","maxOverflowCharacters","maxHyperlinks","maxImageBytes","maxBufferedCells","maxBufferedCharacters","maxMergedRanges","maxConditionalFormats","maxDifferentialStyles","maxCharts","maxChartPoints","maxChartTextCharacters","maxFormulaCharacters","maxDataValidations","maxValidationTextCharacters"];function captureWorkbookLimits(limits){return captureFields(limits,workbookLimitFields)}
359
+ function captureWorkbookOptions(options){const captured=captureFields(options,workbookOptionFields);return{...captured,...(captured.limits===undefined?{}:{limits:captureWorkbookLimits(captured.limits)})}}
360
+ const _exports=Object.freeze({workbookOptionFields:workbookOptionFields,sheetOptionFields:sheetOptionFields,workbookLimitFields:workbookLimitFields,captureWorkbookLimits:captureWorkbookLimits,captureWorkbookOptions:captureWorkbookOptions});_modules.set("e00bc0213b723678d050e3e1f11b39ed3d6b0b0fd6a39b403beb1a6bef69e282",_exports);return _exports})();const _m15=_modules.get("58066519dce31ad3bb7f5f5c377585d3374a84578358ad519e2c021efa1a26f8")??(()=>{const{captureFields}=_m10;const{ExportBudget}=_m9;const{captureCsvOptions:captureCsv}=_m16;const{capturePdfOptions:capturePdf,capturePdfLimits,pdfLimitFields}=_m17;const{captureWorkbookLimits,workbookLimitFields,workbookOptionFields,sheetOptionFields}=_m22;const limitFields=[...new Set([...workbookLimitFields,...pdfLimitFields])];const portableWorkbookFields=workbookOptionFields.filter((key)=>key!=="sink");function captureCommonLimits(input){return input===undefined?undefined:new ExportBudget(captureFields(input,limitFields)).limits}
361
+ function mergeAdapterLimits(format,common){const result={...format};for(const[key,value]of Object.entries(common??{}))
362
+ if(value!==undefined)
363
+ result[key]=value;return result}
364
+ function captureXlsxOptions(input={}){const options=captureFields(input,[...portableWorkbookFields,"sheet"]);const sheet=options.sheet&&captureFields(options.sheet,[...sheetOptionFields,"name"]);const footer=sheet?.footer&&captureFields(sheet.footer,["rows","values","totals","style"]);return{...options,...(sheet===undefined?{}:{sheet:{...sheet,...(footer===undefined?{}:{footer})}}),...(options.limits===undefined?{}:{limits:captureWorkbookLimits(options.limits)})}}
365
+ function captureCsvOptions(input={}){const options=captureCsv(input);return{...options,...(options.limits===undefined?{}:{limits:new ExportBudget(options.limits).limits})}}
366
+ function capturePdfOptions(input={}){const options=capturePdf(input);return{...options,...(options.limits===undefined?{}:{limits:capturePdfLimits(options.limits)})}}
367
+ const _exports=Object.freeze({captureCommonLimits:captureCommonLimits,mergeAdapterLimits:mergeAdapterLimits,captureXlsxOptions:captureXlsxOptions,captureCsvOptions:captureCsvOptions,capturePdfOptions:capturePdfOptions});_modules.set("58066519dce31ad3bb7f5f5c377585d3374a84578358ad519e2c021efa1a26f8",_exports);return _exports})();const _m26=_modules.get("8ece66b561682170c879991995105163f4c484c8355d5e451fc6f52a9fbc3f82")??(()=>{const{OfficeIMOError}=_m2;function partUri(value){const bad=()=>new OfficeIMOError("INVALID_PART_URI","Invalid OPC part URI: "+value);if(typeof value!=="string"||!value.startsWith("/")||/[^A-Za-z0-9\-._~!$&'()*+,;=:@%/]/.test(value))
368
+ throw bad();if(value.split("/").slice(1).some(s=>!s||s.endsWith(".")||/^\.+$/.test(s)))
369
+ throw bad();if(/%(?![\da-f]{2})/i.test(value))
370
+ throw bad();for(const match of value.matchAll(/%([\da-f]{2})/gi)) {
371
+ const char=String.fromCharCode(parseInt(match[1],16));if(/[A-Za-z0-9_.~\-/\\]/.test(char))
372
+ throw bad()}
373
+ try{decodeURIComponent(value)}
374
+ catch{throw bad()}
375
+ return value.replace(/%[\da-f]{2}/gi, s => s.toUpperCase());
376
+ }
377
+ function relationshipPartUri(source){if(source==="/")
378
+ return "/_rels/.rels";const uri=partUri(source),slash=uri.lastIndexOf("/");return uri.slice(0,slash+1)+ "_rels/"+uri.slice(slash+1)+ ".rels"}
379
+ function relativePartTarget(source,target){const to=partUri(target).slice(1).split("/");const from=source==="/"?[]:partUri(source).slice(1).split("/").slice(0,-1);while(from.length&&from[0]===to[0]){from.shift();to.shift()}
380
+ const relative="../".repeat(from.length)+ to.join("/");return relative.split("/",1)[0].includes(":")?"./"+relative:relative}
381
+ const _exports=Object.freeze({partUri:partUri,relationshipPartUri:relationshipPartUri,relativePartTarget:relativePartTarget});_modules.set("8ece66b561682170c879991995105163f4c484c8355d5e451fc6f52a9fbc3f82",_exports);return _exports})();const _m28=_modules.get("227236fd7adc9472e188831b8f16fdc69338c4d779f2b69a8abbd8dbfa95b585")??(()=>{const{OfficeIMOError}=_m2;const{ChunkedTextSink}=_m3;const xmlDeclaration='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';const xmlEscapes={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;","\r":"&#13;","\n":"&#10;","\t":"&#9;"};function cleanXml(value,policy="strip"){if(policy!=="strip"&&policy!=="reject")
382
+ throw new TypeError("Invalid XML character policy.");const text=String(value),invalid=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ud800-\udfff\ufffe\uffff]/gu;
383
+ if(policy==="reject"&&invalid.test(text))
384
+ throw new OfficeIMOError("INVALID_XML","Text contains XML 1.0-invalid characters.");return text.replace(invalid,"")}
385
+ function escapeXml(value,policy="strip"){return cleanXml(value,policy).replace(/[&<>"'\r\n\t]/g, c => xmlEscapes[c]);
386
+ }
387
+ function escapeOoxmlAttribute(value,policy="strip"){const whitespace={"\r":"_x000D_","\n":"_x000A_","\t":"_x0009_"};const text=cleanXml(value,policy).replace(/_(?=x[0-9a-f]{4}_)|[\r\n\t]/gi, token => token === "_" ? "_x005F_" : whitespace[token]);
388
+ return escapeXml(text,policy)}
389
+ function validateXmlName(name){if(typeof name!=="string"||!/^[A-Za-z_][A-Za-z0-9_.-]*(?::[A-Za-z_][A-Za-z0-9_.-]*)?$/.test(name))
390
+ throw new OfficeIMOError("INVALID_XML","Invalid XML name: "+name);return name}
391
+ class XmlWriter{policy;sink;stack=[];roots=0;closed=false;constructor(sink,policy="strip",signal){this.policy=policy;cleanXml("",policy);this.sink=new ChunkedTextSink(sink,signal);this.sink.append(xmlDeclaration)}
392
+ async startElement(name,attributes={}){this.open();validateXmlName(name);const text="<"+name+Object.entries(attributes).map(([key,value])=>" "+validateXmlName(key)+ '="'+escapeXml(value,this.policy)+ '"').join("")+ ">";if(!this.stack.length&&this.roots++)
393
+ throw new OfficeIMOError("INVALID_XML","XML must have one root element.");this.stack.push(name);await this.sink.write(text)}
394
+ async text(value){this.open();if(!this.stack.length)
395
+ throw new OfficeIMOError("INVALID_XML","Text needs an open element.");await this.sink.write(escapeXml(value,this.policy))}
396
+ async endElement(){this.open();const name=this.stack.pop();if(!name)
397
+ throw new OfficeIMOError("INVALID_XML","No open XML element.");await this.sink.write("</"+name+">")}
398
+ async close(){this.open();if(this.stack.length||this.roots!==1)
399
+ throw new OfficeIMOError("INVALID_XML","XML document is incomplete.");await this.sink.close();this.closed=true}
400
+ open(){if(this.closed)
401
+ throw new OfficeIMOError("INVALID_STATE","XML writer is closed.")}}
402
+ const _exports=Object.freeze({xmlDeclaration:xmlDeclaration,cleanXml:cleanXml,escapeXml:escapeXml,escapeOoxmlAttribute:escapeOoxmlAttribute,validateXmlName:validateXmlName,XmlWriter:XmlWriter});_modules.set("227236fd7adc9472e188831b8f16fdc69338c4d779f2b69a8abbd8dbfa95b585",_exports);return _exports})();const _m27=_modules.get("56b2057461a668e8c90abd1fbf4f13ff93efd9854e590c82a195799f0f842c2a")??(()=>{const{escapeXml,xmlDeclaration}=_m28;const{isDate}=_m6;function corePropertiesXml(properties={},policy="strip"){const created=properties.created??new Date(),modified=properties.modified??created;if(!isDate(created)||!isDate(modified)||!Number.isFinite(created.getTime())||!Number.isFinite(modified.getTime()))
403
+ throw new TypeError("Invalid workbook property date.");return xmlDeclaration+'<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties"' +
404
+ ' xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
405
+ '<dc:creator>'+escapeXml(properties.creator??"",policy)+ '</dc:creator><dc:title>'+escapeXml(properties.title??"",policy)+ '</dc:title>' +
406
+ (properties.subject===undefined?"":'<dc:subject>'+escapeXml(properties.subject,policy)+ '</dc:subject>')+
407
+ (properties.description===undefined?"":'<dc:description>'+escapeXml(properties.description,policy)+ '</dc:description>')+
408
+ '<dcterms:created xsi:type="dcterms:W3CDTF">'+created.toISOString()+ '</dcterms:created>' +
409
+ '<dcterms:modified xsi:type="dcterms:W3CDTF">'+modified.toISOString()+ '</dcterms:modified></cp:coreProperties>'}
410
+ function appPropertiesXml(properties={},policy="strip"){return xmlDeclaration+'<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">' +
411
+ '<Application>'+escapeXml(properties.application??"OfficeIMO",policy)+ '</Application><Company>'+escapeXml(properties.company??"",policy)+ '</Company></Properties>'}
412
+ const _exports=Object.freeze({corePropertiesXml:corePropertiesXml,appPropertiesXml:appPropertiesXml});_modules.set("56b2057461a668e8c90abd1fbf4f13ff93efd9854e590c82a195799f0f842c2a",_exports);return _exports})();const _m31=_modules.get("790c15edc51b308be3e7d8222630d407f8c79c31ab21ba0b9f92c00f44ab4021")??(()=>{const crcTable=new Uint32Array(256).map((_,index)=>{let value=index;for(let bit=0;bit<8;bit++)
413
+ value=value&1?0xedb88320^(value>>>1):value>>>1;return value>>>0});class Crc32{crc=0xffffffff;update(bytes){let crc=this.crc;for(let index=0;index<bytes.length;index++)
414
+ crc=crcTable[(crc^bytes[index])&255]^(crc>>>8);this.crc=crc}
415
+ get value(){return(this.crc^0xffffffff)>>>0}}
416
+ const _exports=Object.freeze({Crc32:Crc32});_modules.set("790c15edc51b308be3e7d8222630d407f8c79c31ab21ba0b9f92c00f44ab4021",_exports);return _exports})();const _m30=_modules.get("597d152d20a2a28ee5cd6d4243a79a71ce8b83769a77441bfc944aadc0a6efbd")??(()=>{const{checkAbort,withAbort}=_m4;const{OfficeIMOError}=_m2;const{Crc32}=_m31;const zipLimit=0xffffffff;function zipSize(value){if(!Number.isSafeInteger(value)||value<0||value>=zipLimit)
417
+ throw new OfficeIMOError("ZIP64_REQUIRED","Classic ZIP entries and archives must stay below 4 GiB; ZIP64 is not supported yet.");return value}
418
+ class EntryWriter{sink;signal;method;writer;reader;drain;crc=new Crc32();size=0;compressedSize=0;failed=false;failure;closed=false;cleaned=false;lifetime=new AbortController();abort=()=>{this.fail(this.signal?.reason)};constructor(compression,sink,signal){this.sink=sink;this.signal=signal;if(compression!=="auto"&&compression!=="store")
419
+ throw new RangeError("compression must be auto or store.");checkAbort(signal);let stream;if(compression==="auto"&&typeof CompressionStream==="function"){try{stream=new CompressionStream("deflate-raw")}
420
+ catch(error){if(!(error instanceof TypeError))
421
+ throw error}}
422
+ this.method=stream?8:0;this.writer=stream?.writable.getWriter();this.reader=stream?.readable.getReader();signal?.addEventListener("abort",this.abort,{once:true});this.drain=this.reader?this.consume(this.reader):Promise.resolve()}
423
+ async consume(reader){try{while(true){const{value,done}=await withAbort(reader.read(),this.lifetime.signal);if(done)
424
+ return;checkAbort(this.signal);this.compressedSize=zipSize(this.compressedSize+value.length);await withAbort(Promise.resolve(this.sink.write(value)),this.lifetime.signal)}}
425
+ catch(error){this.fail(error)}}
426
+ fail(error){if(this.failed)
427
+ return;this.failed=true;this.failure=error;this.lifetime.abort(error);if(!this.cleaned){this.writer?.abort(error).catch(()=>{});this.reader?.cancel(error).catch(()=>{})}}
428
+ async write(bytes){checkAbort(this.signal);if(this.failed)
429
+ throw this.failure;if(this.closed)
430
+ throw new OfficeIMOError("INVALID_STATE","ZIP entry is closed.");if(!(bytes instanceof Uint8Array))
431
+ throw new TypeError("ZIP chunks must be Uint8Array.");this.size=zipSize(this.size+bytes.length);this.crc.update(bytes);if(this.writer)
432
+ await withAbort(this.writer.write(new Uint8Array(bytes)),this.lifetime.signal);else{await withAbort(Promise.resolve(this.sink.write(bytes)),this.lifetime.signal);this.compressedSize=this.size}}
433
+ async close(){try{checkAbort(this.signal);if(this.failed)
434
+ throw this.failure;if(this.closed)
435
+ throw new OfficeIMOError("INVALID_STATE","ZIP entry is closed.");this.closed=true;if(this.writer)
436
+ await withAbort(this.writer.close(),this.lifetime.signal);await this.drain;if(this.failed)
437
+ throw this.failure;checkAbort(this.signal);return{crc:this.crc.value,size:this.size,compressedSize:this.compressedSize,method:this.method}}
438
+ finally{this.cleanup()}}
439
+ async discard(error){this.fail(error);await this.drain;this.closed=true;this.cleanup()}
440
+ cleanup(){if(this.cleaned)
441
+ return;this.cleaned=true;this.signal?.removeEventListener("abort",this.abort);this.writer?.releaseLock();this.reader?.releaseLock()}}
442
+ const _exports=Object.freeze({Crc32:_m31.Crc32,zipLimit:zipLimit,zipSize:zipSize,EntryWriter:EntryWriter});_modules.set("597d152d20a2a28ee5cd6d4243a79a71ce8b83769a77441bfc944aadc0a6efbd",_exports);return _exports})();const _m29=_modules.get("699a019e0c3f317a62bf3a6e59b76b6cf1645908b0f1b1f157c18f4d4f368dfb")??(()=>{const{EntryWriter,zipSize}=_m30;const{checkAbort,withAbort,pause,taskYieldDue}=_m4;const{OfficeIMOError}=_m2;const{BlobByteSink,writeBytes}=_m3;const{captureFields}=_m10;const encoder=new TextEncoder();function validateEntryName(name){if(typeof name!=="string"||!name||/[\u0000-\u001f\\]/.test(name) || name.startsWith("/") ||
443
+ /^[A-Za-z]:/.test(name) || name.split("/").some(s => !s || s === "." || s === ".."))
444
+ throw new TypeError("ZIP entry names must be relative paths without empty, dot or parent segments.");for(let i=0;i<name.length;i++){const unit=name.charCodeAt(i);if(unit>=0xd800&&unit<=0xdbff){const next=name.charCodeAt(++i);if(!(next>=0xdc00&&next<=0xdfff))
445
+ throw new TypeError("ZIP entry names must contain well-formed Unicode.")}
446
+ else if(unit>=0xdc00&&unit<=0xdfff)
447
+ throw new TypeError("ZIP entry names must contain well-formed Unicode.")}
448
+ if(encoder.encode(name).length>65535)
449
+ throw new RangeError("ZIP entry name exceeds 65,535 UTF-8 bytes.");return name}
450
+ function header(signature,length,name=new Uint8Array()){const bytes=new Uint8Array(length+name.length),data=new DataView(bytes.buffer);data.setUint32(0,signature,true);bytes.set(name,length);return{bytes,data}}
451
+ class ZipWriter{sink;owned;names=new Set();central=[];offset=0;active;state="open";options;lifetime=new AbortController();disposal;constructor(sink,options={}){const captured=captureFields(options,["compression","signal","maxOutputBytes"]);const{compression,maxOutputBytes}=captured;if(maxOutputBytes!==undefined&&(!Number.isSafeInteger(maxOutputBytes)||maxOutputBytes<0))
452
+ throw new RangeError("maxOutputBytes must be a nonnegative safe integer.");if(compression!==undefined&&compression!=="auto"&&compression!=="store")
453
+ throw new RangeError("compression must be auto or store.");this.options=Object.freeze(captured);this.owned=sink?undefined:new BlobByteSink();this.sink=sink??this.owned}
454
+ async acceptance(operation){const signal=this.options.signal;const abort=()=>this.lifetime.abort(signal?.reason);signal?.addEventListener("abort",abort,{once:true});try{checkAbort(signal);checkAbort(this.lifetime.signal);return await withAbort(Promise.resolve(operation()),this.lifetime.signal)}
455
+ finally{signal?.removeEventListener("abort",abort)}}
456
+ async emit(bytes){if(this.options.maxOutputBytes!==undefined&&this.offset+bytes.length>this.options.maxOutputBytes)
457
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxOutputBytes exceeded.");this.offset=zipSize(this.offset+bytes.length);await this.acceptance(()=>this.sink.write(bytes))}
458
+ reserve(name){checkAbort(this.options.signal);if(this.state!=="open")
459
+ throw new OfficeIMOError("INVALID_STATE","ZIP writer is busy, failed or finalized.");validateEntryName(name);if(this.names.has(name))
460
+ throw new TypeError("Duplicate ZIP entry: "+name);if(this.names.size>=65534)
461
+ throw new OfficeIMOError("ZIP64_REQUIRED","ZIP64 is required for 65,535 entries.");this.names.add(name);this.state="writing";return encoder.encode(name)}
462
+ local(name,info,descriptor){const h=header(0x04034b50,30,name);h.data.setUint16(4,20,true);h.data.setUint16(6,descriptor?0x808:0x800,true);h.data.setUint16(8,info.method,true);h.data.setUint16(12,33,true);h.data.setUint16(26,name.length,true);return h.bytes}
463
+ record(name,info,offset,descriptor){const h=header(0x02014b50,46,name);h.data.setUint16(4,20,true);h.data.setUint16(6,20,true);h.data.setUint16(8,descriptor?0x808:0x800,true);h.data.setUint16(10,info.method,true);h.data.setUint16(14,33,true);h.data.setUint32(16,info.crc,true);h.data.setUint32(20,info.compressedSize,true);h.data.setUint32(24,info.size,true);h.data.setUint16(28,name.length,true);h.data.setUint32(42,offset,true);this.central.push(h.bytes)}
464
+ async openEntry(name){const encoded=this.reserve(name),offset=this.offset;let entry;try{entry=new EntryWriter(this.options.compression??"auto",{write:bytes=>this.emit(bytes)},this.options.signal);await this.emit(this.local(encoded,entry,true));const writer=entry;let busy=false,closed=false,completion;const discard=async(error)=>{closed=true;this.state="failed";this.lifetime.abort(error);await writer.discard(error);this.owned?.discard();this.active=undefined};return this.active={write:async(bytes)=>{if(busy||closed||this.state!=="writing")
465
+ throw new OfficeIMOError("INVALID_STATE","Await the current ZIP entry operation.");busy=true;try{await writer.write(bytes)}
466
+ catch(error){await discard(error);throw error}
467
+ finally{busy=false}},close:()=>{if(completion)
468
+ return completion;if(busy||closed||this.state!=="writing")
469
+ throw new OfficeIMOError("INVALID_STATE","ZIP entry is busy or closed.");closed=true;completion=(async()=>{try{const info=await writer.close(),descriptor=header(0x08074b50,16);descriptor.data.setUint32(4,info.crc,true);descriptor.data.setUint32(8,info.compressedSize,true);descriptor.data.setUint32(12,info.size,true);await this.emit(descriptor.bytes);this.record(encoded,info,offset,true);this.state="open";this.active=undefined;return info}
470
+ catch(error){await discard(error);throw error}})();return completion},discard}}
471
+ catch(error){this.state="failed";await entry?.discard(error);this.owned?.discard();throw error}}
472
+ async add(name,source){const entry=await this.openEntry(name);try{if(typeof source==="function")
473
+ await this.acceptance(()=>source(entry));else
474
+ await this.acceptance(()=>writeBytes(source,entry,this.lifetime.signal));await entry.close()}
475
+ catch(error){await entry.discard(error);throw error}}
476
+ get bytesWritten(){return this.offset}
477
+ discard(error){this.state="failed";this.lifetime.abort(error);return this.disposal??=(async()=>{await this.active?.discard(error);this.owned?.discard()})()}
478
+ async addPrepared(name,entry){const encoded=this.reserve(name),offset=this.offset;try{const local=this.local(encoded,entry,false),data=new DataView(local.buffer);data.setUint32(14,entry.crc,true);data.setUint32(18,entry.compressedSize,true);data.setUint32(22,entry.size,true);await this.emit(local);for(const bytes of entry.chunks){checkAbort(this.options.signal);await this.emit(bytes)}
479
+ this.record(encoded,entry,offset,false);this.state="open"}
480
+ catch(error){this.state="failed";this.owned?.discard();throw error}}
481
+ async finish(){checkAbort(this.options.signal);if(this.state!=="open")
482
+ throw new OfficeIMOError("INVALID_STATE","ZIP writer is busy, failed or finalized.");this.state="writing";const offset=this.offset;try{for(let i=0;i<this.central.length;i++){await this.emit(this.central[i]);if(i%256===255&&taskYieldDue())
483
+ await pause()}
484
+ const end=header(0x06054b50,22);end.data.setUint16(8,this.central.length,true);end.data.setUint16(10,this.central.length,true);end.data.setUint32(12,this.offset-offset,true);end.data.setUint32(16,offset,true);await this.emit(end.bytes);checkAbort(this.options.signal);this.state="finished"}
485
+ catch(error){this.state="failed";this.owned?.discard();throw error}}
486
+ async toBlob(type="application/zip"){if(!this.owned)
487
+ throw new OfficeIMOError("INVALID_STATE","This ZIP uses a caller-owned sink; use finish().");if(this.state!=="finished")
488
+ await this.finish();return this.owned.toBlob(type)}}
489
+ const _exports=Object.freeze({Crc32:_m30.Crc32,validateEntryName:validateEntryName,ZipWriter:ZipWriter});_modules.set("699a019e0c3f317a62bf3a6e59b76b6cf1645908b0f1b1f157c18f4d4f368dfb",_exports);return _exports})();const _m25=_modules.get("4d4856357f94ecbeea67d111ff5e97f916ccc6be6aaefde219d461c6ad10a8c5")??(()=>{const{partUri,relationshipPartUri,relativePartTarget}=_m26;const{corePropertiesXml,appPropertiesXml}=_m27;const{ZipWriter}=_m29;const{ChunkedTextSink}=_m3;const{OfficeIMOError}=_m2;const{escapeXml,xmlDeclaration}=_m28;const{checkAbort,pause,taskYieldDue}=_m4;const{captureFields}=_m10;const relationshipsNamespace="http://schemas.openxmlformats.org/package/2006/relationships";const officeRelationshipsNamespace="http://schemas.openxmlformats.org/officeDocument/2006/relationships";const contentTypesNamespace="http://schemas.openxmlformats.org/package/2006/content-types";const relationshipTypes={officeDocument:officeRelationshipsNamespace+"/officeDocument",worksheet:officeRelationshipsNamespace+"/worksheet",styles:officeRelationshipsNamespace+"/styles",theme:officeRelationshipsNamespace+"/theme",customXml:officeRelationshipsNamespace+"/customXml",coreProperties:relationshipsNamespace+"/metadata/core-properties",appProperties:officeRelationshipsNamespace+"/extended-properties"};function contentType(value){if(typeof value!=="string"||!/^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/.test(value))
490
+ throw new TypeError("Invalid content type.");return value}
491
+ class ContentTypes{defaults=new Map([["rels","application/vnd.openxmlformats-package.relationships+xml"],["xml","application/xml"]]);overrides=new Map();addDefault(extension,type){if(!/^[A-Za-z0-9]+$/.test(extension))
492
+ throw new TypeError("Invalid part extension.");const key=extension.toLowerCase(),previous=this.defaults.get(key);if(previous!==undefined&&previous!==type)
493
+ throw new TypeError("Conflicting default content type.");this.defaults.set(key,contentType(type))}
494
+ addOverride(uri,type){uri=partUri(uri);if(this.overrides.has(uri.toLowerCase()))
495
+ throw new TypeError("Duplicate content-type override.");this.overrides.set(uri.toLowerCase(),{uri,type:contentType(type)})}
496
+ toXml(){return xmlDeclaration+'<Types xmlns="'+contentTypesNamespace+'">' +[...this.defaults].map(([ext,type])=>'<Default Extension="'+escapeXml(ext)+ '" ContentType="'+escapeXml(type)+ '"/>').join("")+[...this.overrides.values()].map(({uri,type})=>'<Override PartName="'+escapeXml(uri)+ '" ContentType="'+escapeXml(type)+ '"/>').join("")+ '</Types>'}}
497
+ class OpcPackage{types=new ContentTypes();parts=new Map();directories=new Set();relationships=new Map();state="open";result;zip;options;constructor(options={}){this.options=Object.freeze(captureFields(options,["compression","signal","maxOutputBytes","invalidCharacterPolicy","sink"]));this.zip=new ZipWriter(this.options.sink,this.options)}
498
+ open(){if(this.state!=="open")
499
+ throw new OfficeIMOError("INVALID_STATE","OPC package is finalized.")}
500
+ reserve(uri,type){this.open();uri=partUri(uri);if(/\/_rels(?:\/|$)/i.test(uri) || uri.toLowerCase() === "/[content_types].xml")
501
+ throw new TypeError("Package metadata part names are reserved.");const key=uri.toLowerCase();if(this.parts.has(key))
502
+ throw new TypeError("Duplicate OPC part: "+uri);if(this.directories.has(key))
503
+ throw new TypeError("OPC part-name prefix collision: "+uri+" is an ancestor of an existing part.");const ancestors=[];for(let slash=key.lastIndexOf("/");slash>0;slash=key.lastIndexOf("/",slash-1)){const ancestor=key.slice(0,slash);if(this.parts.has(ancestor))
504
+ throw new TypeError("OPC part-name prefix collision: "+uri+" descends from "+this.parts.get(ancestor).uri);ancestors.push(ancestor)}
505
+ this.types.addOverride(uri,type);for(const ancestor of ancestors)
506
+ this.directories.add(ancestor);return uri}
507
+ addPart(part){const{uri:requestedUri,contentType,data}=part;const capturedData=data instanceof Uint8Array?new Uint8Array(data):data;const uri=this.reserve(requestedUri,contentType);this.parts.set(uri.toLowerCase(),{uri,contentType,data:capturedData})}
508
+ addPrepared(uri,type,prepared){uri=this.reserve(uri,type);this.parts.set(uri.toLowerCase(),{uri,prepared})}
509
+ async openPart(uri,type){if(!this.options.sink)
510
+ throw new OfficeIMOError("INVALID_STATE","openPart requires a caller-owned package sink.");uri=this.reserve(uri,type);this.parts.set(uri.toLowerCase(),{uri,written:true});try{return await this.zip.openEntry(uri.slice(1))}
511
+ catch(error){await this.discard(error);throw error}}
512
+ addRelationship(source,relationship){checkAbort(this.options.signal);this.open();source=source==="/"?source:partUri(source);const{id,type,target:requestedTarget,external}=relationship;this.open();if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(id))
513
+ throw new TypeError("Relationship id must be an XML ID.");if(!/^[A-Za-z][A-Za-z0-9+.-]*:[^\s<>"']+$/.test(type))
514
+ throw new TypeError("Relationship type must be an absolute URI.");const target=external?requestedTarget:partUri(requestedTarget);if(external&&(!target||/[\u0000-\u0020]/.test(target)))
515
+ throw new TypeError("Invalid external relationship target.");const key=source.toLowerCase(),list=this.relationships.get(key)??new Map();if(list.has(id))
516
+ throw new TypeError("Duplicate relationship id: "+id);list.set(id,{id,type,target,...(external===undefined?{}:{external})});this.relationships.set(key,list)}
517
+ setProperties(core={},app={}){const coreXml=corePropertiesXml(core,this.options.invalidCharacterPolicy),appXml=appPropertiesXml(app,this.options.invalidCharacterPolicy);this.addPart({uri:"/docProps/core.xml",contentType:"application/vnd.openxmlformats-package.core-properties+xml",data:coreXml});this.addPart({uri:"/docProps/app.xml",contentType:"application/vnd.openxmlformats-officedocument.extended-properties+xml",data:appXml});this.addRelationship("/",{id:"core",type:relationshipTypes.coreProperties,target:"/docProps/core.xml"});this.addRelationship("/",{id:"app",type:relationshipTypes.appProperties,target:"/docProps/app.xml"})}
518
+ source(data){if(typeof data==="string")
519
+ return async(sink)=>{const text=new ChunkedTextSink(sink,this.options.signal);await text.write(data);await text.close()};if(data instanceof Blob)
520
+ return(async function*(){for(let i=0;i<data.size;i +=65536){let buffer;try{buffer=await data.slice(i,i+65536).arrayBuffer()}
521
+ catch(error){if(error?.name!=="NotReadableError")
522
+ throw error;throw new OfficeIMOError("PLATFORM_UNAVAILABLE","This environment cannot read Blob part data. Supply text or byte chunks; read Blobs before sending data to a worker.",{cause:error})}
523
+ yield new Uint8Array(buffer)}})();return data}
524
+ finish(){if(this.result)
525
+ return this.result;this.open();this.state="finalizing";this.result=(async()=>{const zip=this.zip;try{for(const[source,list]of this.relationships){if(source!=="/"&&!this.parts.has(source))
526
+ throw new TypeError("Missing relationship source part: "+source);let checked=0;for(const rel of list.values()){checkAbort(this.options.signal);if(!rel.external&&!this.parts.has(rel.target.toLowerCase()))
527
+ throw new TypeError("Missing relationship target: "+rel.target);if((++checked&255)===0&&taskYieldDue()){await pause();checkAbort(this.options.signal)}}}
528
+ for(const part of this.parts.values()){if("written" in part)
529
+ continue;if("prepared" in part)
530
+ await zip.addPrepared(part.uri.slice(1),part.prepared);else
531
+ await zip.add(part.uri.slice(1),this.source(part.data))}
532
+ for(const[key,list]of this.relationships){const source=key==="/"?"/":this.parts.get(key).uri;await zip.add(relationshipPartUri(source).slice(1),async(sink)=>{const text=new ChunkedTextSink(sink,this.options.signal);await text.write(xmlDeclaration+'<Relationships xmlns="'+relationshipsNamespace+'">');for(const r of list.values()){const xml='<Relationship Id="'+escapeXml(r.id)+ '" Type="'+escapeXml(r.type)+ '" Target="' +
533
+ escapeXml(r.external?r.target:relativePartTarget(source,r.target))+ '"' +(r.external?' TargetMode="External"':"")+ '/>';if(text.append(xml))
534
+ await text.flush()}
535
+ await text.write('</Relationships>');await text.close()})}
536
+ await zip.add("[Content_Types].xml",this.source(this.types.toXml()));await zip.finish();this.state="complete";return zip.bytesWritten}
537
+ catch(error){await this.discard(error);throw error}
538
+ finally{this.parts.clear();this.directories.clear();this.relationships.clear()}})();return this.result}
539
+ async toBlob(type="application/zip"){if(this.options.sink)
540
+ throw new OfficeIMOError("INVALID_STATE","This package uses a caller-owned sink; use finish().");await this.finish();return this.zip.toBlob(type)}
541
+ async discard(error){this.state="failed";this.parts.clear();this.directories.clear();this.relationships.clear();await this.zip.discard(error)}}
542
+ const _exports=Object.freeze({partUri:_m26.partUri,relationshipPartUri:_m26.relationshipPartUri,relativePartTarget:_m26.relativePartTarget,corePropertiesXml:_m27.corePropertiesXml,appPropertiesXml:_m27.appPropertiesXml,relationshipsNamespace:relationshipsNamespace,officeRelationshipsNamespace:officeRelationshipsNamespace,contentTypesNamespace:contentTypesNamespace,relationshipTypes:relationshipTypes,ContentTypes:ContentTypes,OpcPackage:OpcPackage});_modules.set("4d4856357f94ecbeea67d111ff5e97f916ccc6be6aaefde219d461c6ad10a8c5",_exports);return _exports})();const _m33=_modules.get("204def412284dfb11df9aececd57c8c0455db2927ebdb483dd255e7b29f6f359")??(()=>{function colorArgb(value){if(typeof value!=="string"||!/^#?(?:[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value))
543
+ throw new TypeError("Color must be RGB or ARGB hex.");const color=value.replace(/^#/, "").toUpperCase();
544
+ return color.length===6?"FF"+color:color}
545
+ const _exports=Object.freeze({colorArgb:colorArgb});_modules.set("204def412284dfb11df9aececd57c8c0455db2927ebdb483dd255e7b29f6f359",_exports);return _exports})();const _m34=_modules.get("6ae88f25e1c09d00fbb828917498569f883fae88ec25d37caebaf8a2b802b148")??(()=>{const{OfficeIMOError}=_m2;const{cleanXml,escapeOoxmlAttribute}=_m28;const{colorArgb}=_m33;function fields(value,allowed,label){if(!value||typeof value!=="object"||Array.isArray(value))
546
+ throw new TypeError(label+" must be an object.");if(typeof value.then==="function"){void Promise.resolve(value).catch(()=>{});throw new TypeError(label+" must be synchronous.")}
547
+ for(const key of Object.keys(value))
548
+ if(!allowed.includes(key))
549
+ throw new TypeError("Unsupported "+label+" property: "+key)}
550
+ function optionalBoolean(value,name){if(value!==undefined&&typeof value!=="boolean")
551
+ throw new TypeError(name+" must be boolean.")}
552
+ class DifferentialStyles{policy;maximum;numberFormat;definitions=new Map();constructor(policy,maximum,numberFormat){this.policy=policy;this.maximum=maximum;this.numberFormat=numberFormat}
553
+ keys(styles){const keys=styles.map(style=>differentialXml(style,this.policy,()=>164));const pending=new Set(keys.filter(definition=>!this.definitions.has(definition)));if(this.definitions.size+pending.size>this.maximum)
554
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxDifferentialStyles exceeded.");return keys}
555
+ check(styles){this.keys(styles)}
556
+ add(styles){const keys=this.keys(styles);for(let i=0;i<styles.length;i++)
557
+ if(!this.definitions.has(keys[i]))
558
+ this.definitions.set(keys[i],{id:this.definitions.size,xml:differentialXml(styles[i],this.policy,this.numberFormat)});return keys.map(key=>this.definitions.get(key).id)}
559
+ toXml(){return this.definitions.size?'<dxfs count="'+this.definitions.size+'">' +[...this.definitions.values()].map(style=>'<dxf>'+style.xml+'</dxf>').join("")+ '</dxfs>':""}}
560
+ function differentialXml(style,policy,numberFormat){fields(style,["font","fill","border","numberFormat"],"conditional style");let xml="";if(style.font!==undefined){fields(style.font,["bold","italic","underline","strike","color"],"conditional font");let font="";for(const[name,tag]of[["bold","b"],["italic","i"],["strike","strike"]]){optionalBoolean(style.font[name],name);if(style.font[name]!==undefined)
561
+ font +='<'+tag+' val="' +(style.font[name]?1:0)+ '"/>'}
562
+ optionalBoolean(style.font.underline,"underline");if(style.font.underline!==undefined)
563
+ font +='<u val="' +(style.font.underline?"single":"none")+ '"/>';if(style.font.color!==undefined)
564
+ font +='<color rgb="'+colorArgb(style.font.color)+ '"/>';if(font)
565
+ xml +='<font>'+font+'</font>'}
566
+ if(style.numberFormat!==undefined){const format=style.numberFormat;if(typeof format!=="string"||!format||format.length>255||!cleanXml(format,policy))
567
+ throw new TypeError("Conditional number format requires 1 through 255 XML-valid characters.");xml +='<numFmt numFmtId="'+numberFormat(format)+ '" formatCode="'+escapeOoxmlAttribute(format,policy)+ '"/>'}
568
+ if(style.fill!==undefined){fields(style.fill,["color"],"conditional fill");const color=colorArgb(style.fill.color);xml +='<fill><patternFill patternType="solid"><fgColor rgb="'+color+'"/><bgColor rgb="'+color+'"/></patternFill></fill>'}
569
+ if(style.border!==undefined){fields(style.border,["left","right","top","bottom"],"conditional border");let border="";for(const side of["left","right","top","bottom"]){const edge=style.border[side];if(edge!==undefined){fields(edge,["style","color"],"conditional border edge");if(!["thin","medium","dashed","dotted","thick","double","hair","dashDot","dashDotDot","slantDashDot","mediumDashed","mediumDashDot","mediumDashDotDot"].includes(edge.style))
570
+ throw new TypeError("Invalid conditional border style.");border +='<'+side+' style="'+edge.style+'">' +(edge.color!==undefined?'<color rgb="'+colorArgb(edge.color)+ '"/>':"")+ '</'+side+'>'}}
571
+ if(border)
572
+ xml +='<border>'+border+'</border>'}
573
+ if(!xml)
574
+ throw new TypeError("A conditional style must change at least one property.");return xml}
575
+ const _exports=Object.freeze({fields:fields,optionalBoolean:optionalBoolean,DifferentialStyles:DifferentialStyles,differentialXml:differentialXml});_modules.set("6ae88f25e1c09d00fbb828917498569f883fae88ec25d37caebaf8a2b802b148",_exports);return _exports})();const _m32=_modules.get("077c3c668f1457253dba044e6f6be7f7afd28a8976ed20c764bd5d5dc7c41889")??(()=>{const{escapeOoxmlAttribute,cleanXml,xmlDeclaration}=_m28;const{OfficeIMOError}=_m2;const{colorArgb}=_m33;const{DifferentialStyles}=_m34;const spreadsheetNamespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main";const NumberFormats={General:"General",Integer:"0",Decimal:"0.00",Percent:"0.00%",Date:"yyyy-mm-dd",DateTime:"yyyy-mm-dd hh:mm:ss"};function index(value,count,kind){if(!Number.isInteger(value)||value<0||value>=count)
576
+ throw new RangeError("Unknown "+kind+" index.");return value}
577
+ function deduplicate(items,indexes,item,maximum){const key=JSON.stringify(item),found=indexes.get(key);if(found!==undefined)
578
+ return found;if(items.length>=maximum)
579
+ throw new OfficeIMOError("RESOURCE_LIMIT","Style component limit exceeded.");const id=items.length;items.push(item);indexes.set(key,id);return id}
580
+ function validateStylePatch(patch){if(!patch||typeof patch!=="object"||Array.isArray(patch))
581
+ throw new TypeError("A style patch must be a CellStyle object.");if(typeof patch.then==="function"){void Promise.resolve(patch).catch(()=>{});throw new TypeError("Style patches must be synchronous CellStyle objects.")}}
582
+ function copyStylePatch(patch){validateStylePatch(patch);return Object.freeze({...patch,...(typeof patch.font==="object"?{font:Object.freeze({...patch.font})}:{}),...(typeof patch.fill==="object"?{fill:Object.freeze({...patch.fill})}:{}),...(typeof patch.border==="object"?{border:Object.freeze(Object.fromEntries(Object.entries(patch.border).map(([side,edge])=>[side,Object.freeze({...edge})])))}:{})})}
583
+ class StyleRegistry{policy;maximum;differential;fonts=[{name:"Calibri",size:11,bold:false,italic:false,underline:false,strike:false,color:""}];fills=[{pattern:"none",color:""},{pattern:"gray125",color:""}];borders=[{}];formats=new Map();styles=[];indexes=new Map();fontIndexes=new Map(this.fonts.map((v,i)=>[JSON.stringify(v),i]));fillIndexes=new Map(this.fills.map((v,i)=>[JSON.stringify(v),i]));borderIndexes=new Map(this.borders.map((v,i)=>[JSON.stringify(v),i]));constructor(policy="strip",maximum=64000,maximumDifferential=1000){this.policy=policy;this.maximum=maximum;if(!Number.isSafeInteger(maximum)||maximum<1||maximum>64000)
584
+ throw new RangeError("maxStyles must be from 1 through 64,000.");if(!Number.isSafeInteger(maximumDifferential)||maximumDifferential<0)
585
+ throw new RangeError("maxDifferentialStyles must be a nonnegative safe integer.");this.differential=new DifferentialStyles(policy,maximumDifferential,format=>this.addNumberFormat(format));cleanXml("",policy);this.add()}
586
+ checkDifferentials(styles){const formats=new Set(styles.flatMap(style=>style.numberFormat===undefined?[]:[cleanXml(style.numberFormat,this.policy)])
587
+ .filter(format=>format!=="General"&&!this.formats.has(format)));if(this.formats.size+formats.size>65372)
588
+ throw new RangeError("Too many number formats.");this.differential.check(styles)}
589
+ addDifferentials(styles){this.checkDifferentials(styles);return this.differential.add(styles)}
590
+ addFont(font){if(font.name!==undefined&&typeof font.name!=="string")
591
+ throw new TypeError("Font name must be a string.");const name=cleanXml(font.name??"Calibri",this.policy),size=font.size??11;if(typeof name!=="string"||!name||name.length>31)
592
+ throw new TypeError("Font name must contain 1 through 31 characters.");if(!Number.isFinite(size)||size<=0||size>409)
593
+ throw new RangeError("Font size must be positive and at most 409.");return deduplicate(this.fonts,this.fontIndexes,{name,size,bold:!!font.bold,italic:!!font.italic,underline:!!font.underline,strike:!!font.strike,color:font.color?colorArgb(font.color):""},this.maximum)}
594
+ addFill(fill){const pattern=fill.pattern??(fill.color?"solid":"none");if(!["none","gray125","solid"].includes(pattern)||(pattern==="solid"&&!fill.color)||(pattern!=="solid"&&fill.color))
595
+ throw new TypeError("A solid fill requires a color; none and gray125 have no color.");return deduplicate(this.fills,this.fillIndexes,{pattern,color:fill.color?colorArgb(fill.color):""},this.maximum+1)}
596
+ addBorder(border){const result={};for(const side of["left","right","top","bottom"]){const edge=border[side];if(edge){if(!["thin","medium","dashed","dotted","thick","double","hair","dashDot","dashDotDot","slantDashDot","mediumDashed","mediumDashDot","mediumDashDotDot"].includes(edge.style))
597
+ throw new TypeError("Invalid border style.");result[side]={style:edge.style,...(edge.color?{color:colorArgb(edge.color)}:{})}}}
598
+ return deduplicate(this.borders,this.borderIndexes,result,this.maximum)}
599
+ addNumberFormat(format){if(typeof format!=="string"||!format||format.length>255)
600
+ throw new TypeError("Number format must contain 1 through 255 characters.");format=cleanXml(format,this.policy);if(!format)
601
+ throw new TypeError("Number format must contain XML-valid characters.");if(format==="General")
602
+ return 0;let id=this.formats.get(format);if(id===undefined){if(this.formats.size>=65372)
603
+ throw new RangeError("Too many number formats.");id=this.formats.size+164;this.formats.set(format,id)}
604
+ return id}
605
+ add(style={}){const font=typeof style.font==="number"?index(style.font,this.fonts.length,"font"):style.font?this.addFont(style.font):0;const fill=typeof style.fill==="number"?index(style.fill,this.fills.length,"fill"):style.fill?this.addFill(style.fill):0;const border=typeof style.border==="number"?index(style.border,this.borders.length,"border"):style.border?this.addBorder(style.border):0;let numberFormat=0;if(typeof style.numberFormat==="string")
606
+ numberFormat=this.addNumberFormat(style.numberFormat);else if(style.numberFormat!==undefined){numberFormat=style.numberFormat;if(!Number.isInteger(numberFormat)||numberFormat<0||(numberFormat>163&&![...this.formats.values()].includes(numberFormat)))
607
+ throw new RangeError("Unknown number format index.")}
608
+ if(style.alignment!==undefined&&!["left","center","right","fill","justify","distributed"].includes(style.alignment))
609
+ throw new TypeError("Invalid horizontal alignment.");if(style.verticalAlignment!==undefined&&!["top","center","bottom","justify","distributed"].includes(style.verticalAlignment))
610
+ throw new TypeError("Invalid vertical alignment.");const registered={font,fill,border,numberFormat,wrapText:!!style.wrapText,alignment:style.alignment??"",verticalAlignment:style.verticalAlignment??""};const key=JSON.stringify(registered),found=this.indexes.get(key);if(found!==undefined)
611
+ return found;if(this.styles.length>=this.maximum)
612
+ throw new OfficeIMOError("RESOURCE_LIMIT","Workbook exceeds its cell style limit.");const id=this.styles.length;this.styles.push(registered);this.indexes.set(key,id);return id}
613
+ validateStyle(id){return index(id,this.styles.length,"cell style")}
614
+ compose(base,overlay){validateStylePatch(overlay);const source=this.styles[this.validateStyle(base)];return this.add({font:source.font,fill:source.fill,border:source.border,numberFormat:source.numberFormat,wrapText:source.wrapText,...(source.alignment?{alignment:source.alignment}:{}),...(source.verticalAlignment?{verticalAlignment:source.verticalAlignment}:{}),...overlay,...(typeof overlay.font==="object"?{font:{...this.fonts[source.font],...overlay.font}}:{}),...(typeof overlay.border==="object"?{border:{...this.borders[source.border],...overlay.border}}:{})})}
615
+ dateHeader(base,dateStyle){return this.compose(base,{numberFormat:this.styles[this.validateStyle(dateStyle)].numberFormat})}
616
+ forColumn(column,header=false,fill,date=false){const base=!header&&column.style!==undefined?this.styles[this.validateStyle(column.style)]:undefined;const format=column.format!==undefined?column.format||NumberFormats.General:base?.numberFormat||(column.type==="date"||date?NumberFormats.DateTime:NumberFormats.General);return this.add({...(base?{font:base.font,fill:base.fill,border:base.border}:{}),numberFormat:format,wrapText:column.wrapText??base?.wrapText??false,...(column.alignment?{alignment:column.alignment}:base?.alignment?{alignment:base.alignment}:{}),...(base?.verticalAlignment?{verticalAlignment:base.verticalAlignment}:{}),...(header?{font:{bold:true}}:{}),...(fill?{fill:{color:fill}}:{})})}
617
+ toXml(){const fontXml=(f)=>'<font>' +(f.bold?'<b/>':"")+(f.italic?'<i/>':"")+(f.underline?'<u/>':"")+(f.strike?'<strike/>':"")+ '<sz val="'+f.size+'"/>' +
618
+ (f.color?'<color rgb="'+f.color+'"/>':"")+ '<name val="'+escapeOoxmlAttribute(f.name,this.policy)+ '"/></font>';const borderXml=(b)=>'<border>' +["left","right","top","bottom"].map(side=>{const edge=b[side];return edge?'<'+side+' style="'+edge.style+'">' +(edge.color?'<color rgb="'+edge.color+'"/>':"")+ '</'+side+'>':'<'+side+'/>'}).join("")+ '<diagonal/></border>';return xmlDeclaration+'<styleSheet xmlns="'+spreadsheetNamespace+'">' +
619
+ '<numFmts count="'+this.formats.size+'">' +[...this.formats].map(([format,id])=>'<numFmt numFmtId="'+id+'" formatCode="'+escapeOoxmlAttribute(format,this.policy)+ '"/>').join("")+ '</numFmts>' +
620
+ '<fonts count="'+this.fonts.length+'">'+this.fonts.map(fontXml).join("")+ '</fonts>' +
621
+ '<fills count="'+this.fills.length+'">'+this.fills.map(f=>'<fill><patternFill patternType="'+f.pattern+'">' +
622
+ (f.color?'<fgColor rgb="'+f.color+'"/><bgColor indexed="64"/>':"")+ '</patternFill></fill>').join("")+ '</fills>' +
623
+ '<borders count="'+this.borders.length+'">'+this.borders.map(borderXml).join("")+ '</borders>' +
624
+ '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
625
+ '<cellXfs count="'+this.styles.length+'">'+this.styles.map(s=>{const alignment=s.wrapText||s.alignment||s.verticalAlignment?'<alignment' +(s.wrapText?' wrapText="1"':"")+(s.alignment?' horizontal="'+s.alignment+'"':"")+(s.verticalAlignment?' vertical="'+s.verticalAlignment+'"':"")+ '/>':"";return '<xf numFmtId="'+s.numberFormat+'" fontId="'+s.font+'" fillId="'+s.fill+'" borderId="'+s.border+'" xfId="0"' +
626
+ (s.numberFormat?' applyNumberFormat="1"':"")+(s.font?' applyFont="1"':"")+(s.fill?' applyFill="1"':"")+
627
+ (s.border?' applyBorder="1"':"")+(alignment?' applyAlignment="1"':"")+ '>'+alignment+'</xf>'}).join("")+ '</cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'+this.differential.toXml()+ '</styleSheet>'}}
628
+ const _exports=Object.freeze({colorArgb:_m33.colorArgb,spreadsheetNamespace:spreadsheetNamespace,NumberFormats:NumberFormats,validateStylePatch:validateStylePatch,copyStylePatch:copyStylePatch,StyleRegistry:StyleRegistry});_modules.set("077c3c668f1457253dba044e6f6be7f7afd28a8976ed20c764bd5d5dc7c41889",_exports);return _exports})();const _m36=_modules.get("f1de2157d2aefa347a314940eb7f89c16545e11f69923920e605409433742f93")??(()=>{const{NotSupportedError}=_m2;const{cleanXml,escapeXml}=_m28;const formulaCells=new WeakSet();const nestedAggregateCells=new WeakSet();function inspectReferences(formula){let subtotal=false;const identifier=/[\p{L}_\\][\p{L}\p{N}\p{M}_.\\]*/uy;
629
+ for(let i=0;i<formula.length;i++){const character=formula[i];if(character==='"'){while(++i<formula.length)
630
+ if(formula[i]==='"'){if(formula[i+1]!=='"')
631
+ break;i++}}
632
+ else if(character==="'"){let quoted="";while(++i<formula.length){if(formula[i]==="'"){if(formula[i+1]!=="'")
633
+ break;i++}
634
+ quoted +=formula[i]}
635
+ if(formula.slice(i+1).trimStart().startsWith("!")&&/[\[\]]/.test(quoted))
636
+ throw new NotSupportedError("external-workbook formulas")}
637
+ else if(character==="["){let depth=1;while(++i<formula.length&&depth){if(formula[i]==="'"){i++;continue}
638
+ if(formula[i]==="[")
639
+ depth++;else if(formula[i]==="]")
640
+ depth--}
641
+ if(/^[A-Za-z0-9_.]*!/.test(formula.slice(i)))
642
+ throw new NotSupportedError("external-workbook formulas");i--}
643
+ else if(character==="|")
644
+ throw new NotSupportedError("DDE formulas");else{identifier.lastIndex=i;const token=identifier.exec(formula);if(token){if(["SUBTOTAL","AGGREGATE","_XLFN.AGGREGATE"].includes(token[0].toUpperCase())&&/^\s*\(/.test(formula.slice(identifier.lastIndex)))
645
+ subtotal=true;i=identifier.lastIndex-1}}}
646
+ return subtotal}
647
+ function captureFormula(value){if(typeof value!=="string")
648
+ throw new TypeError("Formula text must be a string.");const text=value.trim().replace(/^=/, "");
649
+ if(!text.trim()||text.length>8192)
650
+ throw new RangeError("Formulas require 1 through 8,192 characters.");cleanXml(text,"reject");return{text,subtotal:inspectReferences(text)}}
651
+ class FormulaCell{cachedValue;style;static[Symbol.hasInstance](value){return value!==null&&typeof value==="object"&&formulaCells.has(value)}
652
+ formula;constructor(formula,cachedValue,style){this.cachedValue=cachedValue;this.style=style;const captured=captureFormula(formula);this.formula=captured.text;if(cachedValue!==null&&(typeof cachedValue!=="number"||!Number.isFinite(cachedValue)))
653
+ throw new TypeError("Formula caches must be finite numbers or null for a blank result.");if(style!==undefined&&(!Number.isSafeInteger(style)||style<0))
654
+ throw new RangeError("Formula style indexes must be nonnegative safe integers.");formulaCells.add(this);if(captured.subtotal)
655
+ nestedAggregateCells.add(this);Object.freeze(this)}}
656
+ function isSubtotalFormula(cell){return nestedAggregateCells.has(cell)}
657
+ function formulaXml(cell){if(!(cell instanceof FormulaCell))
658
+ throw new TypeError("Formula cells must be created with FormulaCell.");return "<f>"+escapeXml(cell.formula,"reject")+ "</f><v>" +(cell.cachedValue??"")+ "</v>"}
659
+ const _exports=Object.freeze({FormulaCell:FormulaCell,isSubtotalFormula:isSubtotalFormula,formulaXml:formulaXml});_modules.set("f1de2157d2aefa347a314940eb7f89c16545e11f69923920e605409433742f93",_exports);return _exports})();const _m35=_modules.get("4bce839e90e3ef590aa1b224ffd9c4bdf24d7639b93bdf879f9a0d79de4cd0e4")??(()=>{const{cleanXml,escapeXml}=_m28;const{assertExportValue,assertScalar}=_m5;const{FormulaCell}=_m36;const{copyExportValue}=_m13;class Cell{value;style;constructor(value,style){this.value=value;this.style=style}}
660
+ function assertXlsxValue(value){if(value instanceof FormulaCell)
661
+ return;if(value instanceof Cell)
662
+ assertScalar(value.value);else
663
+ assertExportValue(value)}
664
+ function copyValue(value){if(value instanceof FormulaCell)
665
+ return value;if(value instanceof Cell)
666
+ return Object.freeze(new Cell(copyExportValue(value.value),value.style));return copyExportValue(value)}
667
+ function cellText(value,policy="strip"){const text=cleanXml(value,policy);if(text.length>32767)
668
+ throw new RangeError("Excel cell text exceeds 32,767 UTF-16 code units.");return text}
669
+ function inlineText(value,policy){const text=cellText(value,policy),node=(part)=>'<t xml:space="preserve">'+escapeXml(part,policy)+ '</t>';return /_x[0-9a-f]{4}_/i.test(text)
670
+ ?text.split(/(?<=_)(?=x[0-9a-f]{4}_)/gi).map(part => '<r>' + node(part) + '</r>').join("") : node(text);
671
+ }
672
+ function columnName(index){if(!Number.isInteger(index)||index<1||index>16384)
673
+ throw new RangeError("Column index must be from 1 through 16,384.");let name="";while(index){index--;name=String.fromCharCode(65+index%26)+ name;index=Math.floor(index / 26);
674
+ }
675
+ return name}
676
+ function clipName(text,length){return text.slice(0,length).replace(/[\ud800-\udbff]$/, ""); }
677
+ function sheetName(requested,names,policy,register=true){if(typeof requested!=="string")
678
+ throw new TypeError("Sheet name must be a string.");let base=cleanXml(requested,policy).replace(/[\[\]:*?/\\]/g, "_").replace(/^[\s']+|[\s']+$/g, "");
679
+ base=clipName(base,31).replace(/[\s']+$/g, "");
680
+ if(!base)
681
+ base="Sheet";if(base.toLowerCase()==="history")
682
+ base +="_";let name=base,suffix=2;while(names.has(name.toLowerCase())){const tail=" ("+suffix++ + ")";name=clipName(base,31-tail.length)+ tail}
683
+ if(register)
684
+ names.add(name.toLowerCase());return name}
685
+ function excelDate(date,mode){if(!Number.isFinite(date.getTime()))
686
+ return null;const utc=mode==="utc",year=utc?date.getUTCFullYear():date.getFullYear();if(year<1900||year>9999)
687
+ throw new RangeError("Excel dates must be in years 1900 through 9999.");const wall=new Date(0);wall.setUTCFullYear(year,utc?date.getUTCMonth():date.getMonth(),utc?date.getUTCDate():date.getDate());wall.setUTCHours(utc?date.getUTCHours():date.getHours(),utc?date.getUTCMinutes():date.getMinutes(),utc?date.getUTCSeconds():date.getSeconds(),utc?date.getUTCMilliseconds():date.getMilliseconds());const time=wall.getTime();return(time-Date.UTC(1899,11,31))/ 86400000 + (time >= Date.UTC(1900, 2, 1) ? 1 : 0);
688
+ }
689
+ const _exports=Object.freeze({Cell:Cell,assertXlsxValue:assertXlsxValue,copyValue:copyValue,cellText:cellText,inlineText:inlineText,columnName:columnName,sheetName:sheetName,excelDate:excelDate});_modules.set("4bce839e90e3ef590aa1b224ffd9c4bdf24d7639b93bdf879f9a0d79de4cd0e4",_exports);return _exports})();const _m39=_modules.get("84c16159c55cf4c0af5d3c67510302694946ae99c6c685fc09314069ee3da5c5")??(()=>{const{ChunkedTextSink}=_m3;const{escapeXml,xmlDeclaration}=_m28;const{officeRelationshipsNamespace}=_m25;const{columnName}=_m35;const chartNamespace="http://schemas.openxmlformats.org/drawingml/2006/chart";const chartContentType="application/vnd.openxmlformats-officedocument.drawingml.chart+xml";function chartAnchorXml(chart,objectId,policy){const size=' cx="'+Math.round(chart.width*9525)+ '" cy="'+Math.round(chart.height*9525)+ '"';return '<xdr:oneCellAnchor><xdr:from><xdr:col>' +(chart.column-1)+ '</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>' +(chart.row-1)+ '</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>' +
690
+ '<xdr:ext'+size+'/><xdr:graphicFrame macro=""><xdr:nvGraphicFramePr><xdr:cNvPr id="'+objectId+'" name="Chart '+chart.id+'" descr="'+escapeXml(chart.description??chart.title??"",policy)+ '"/>' +
691
+ '<xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic><a:graphicData uri="'+chartNamespace+'">' +
692
+ '<c:chart xmlns:c="'+chartNamespace+'" r:id="chart'+chart.id+'"/></a:graphicData></a:graphic></xdr:graphicFrame><xdr:clientData/></xdr:oneCellAnchor>'}
693
+ function titleXml(value,policy){return '<c:title><c:tx><c:rich><a:bodyPr/><a:lstStyle/><a:p><a:pPr><a:defRPr/></a:pPr><a:r><a:t xml:space="preserve">' +
694
+ escapeXml(value,policy)+ '</a:t></a:r></a:p></c:rich></c:tx><c:overlay val="0"/></c:title>'}
695
+ function*reference(kind,formula,values,policy){yield '<c:'+kind+'Ref><c:f>'+escapeXml(formula,policy)+ '</c:f><c:'+kind+'Cache>';if(kind==="num")
696
+ yield '<c:formatCode>General</c:formatCode>';yield '<c:ptCount val="'+values.length+'"/>';for(let i=0;i<values.length;i++)
697
+ yield '<c:pt idx="'+i+'"><c:v xml:space="preserve">'+escapeXml(String(values[i]),policy)+ '</c:v></c:pt>';yield '</c:'+kind+'Cache></c:'+kind+'Ref>'}
698
+ function labelsXml(chart,policy){const labels=chart.dataLabels;if(!labels)
699
+ return "";const positions={center:"ctr",insideEnd:"inEnd",outsideEnd:"outEnd",bestFit:"bestFit",above:"t",below:"b",left:"l",right:"r"};return '<c:dLbls>' +(labels.numberFormat===undefined?"":'<c:numFmt formatCode="'+escapeXml(labels.numberFormat,policy)+ '" sourceLinked="0"/>')+
700
+ (labels.position===undefined?"":'<c:dLblPos val="'+positions[labels.position]+ '"/>')+ '<c:showLegendKey val="0"/><c:showVal val="' +(labels.showValue===false?0:1)+
701
+ '"/><c:showCatName val="' +(labels.showCategoryName?1:0)+ '"/><c:showSerName val="' +(labels.showSeriesName?1:0)+
702
+ '"/><c:showPercent val="' +(labels.showPercent?1:0)+ '"/><c:showBubbleSize val="0"/></c:dLbls>'}
703
+ function axesXml(chart,policy){const horizontal=chart.type==="barClustered",value=chart.valueAxis;const scaling='<c:scaling><c:orientation val="minMax"/>' +(value?.maximum===undefined?"":'<c:max val="'+value.maximum+'"/>')+
704
+ (value?.minimum===undefined?"":'<c:min val="'+value.minimum+'"/>')+ '</c:scaling>';const ticks='<c:majorTickMark val="none"/><c:minorTickMark val="none"/><c:tickLblPos val="nextTo"/>';return '<c:catAx><c:axId val="1"/><c:scaling><c:orientation val="minMax"/></c:scaling><c:delete val="0"/><c:axPos val="' +(horizontal?"l":"b")+ '"/>' +
705
+ (chart.categoryAxis?.title?titleXml(chart.categoryAxis.title,policy):"")+ '<c:numFmt formatCode="General" sourceLinked="1"/>'+ticks +
706
+ '<c:crossAx val="2"/><c:crosses val="autoZero"/><c:auto val="1"/><c:lblAlgn val="ctr"/><c:lblOffset val="100"/><c:noMultiLvlLbl val="0"/></c:catAx>' +
707
+ '<c:valAx><c:axId val="2"/>'+scaling+'<c:delete val="0"/><c:axPos val="' +(horizontal?"b":"l")+ '"/><c:majorGridlines/>' +
708
+ (value?.title?titleXml(value.title,policy):"")+ '<c:numFmt formatCode="'+escapeXml(value?.numberFormat??"General",policy)+ '" sourceLinked="' +(value?.numberFormat===undefined?1:0)+ '"/>'+ticks +
709
+ '<c:crossAx val="1"/><c:crosses val="autoZero"/><c:crossBetween val="between"/></c:valAx>'}
710
+ function*chartXml(chart,policy){const pie=chart.type==="pie",line=chart.type==="line",tag=pie?"pieChart":line?"lineChart":"barChart";const source="'"+chart.dataSheetName.replace(/'/g, "''") + "'!", end = chart.data.categories.length + 1;
711
+ yield xmlDeclaration+'<c:chartSpace xmlns:c="'+chartNamespace+'" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="'+officeRelationshipsNamespace+'"><c:date1904 val="0"/>' +
712
+ (chart.language===undefined?"":'<c:lang val="'+escapeXml(chart.language,policy)+ '"/>')+ '<c:chart>';if(chart.title)
713
+ yield titleXml(chart.title,policy);yield '<c:autoTitleDeleted val="' +(chart.title?0:1)+ '"/><c:plotArea><c:layout/><c:'+tag+'>';if(!pie)
714
+ yield line?'<c:grouping val="standard"/>':'<c:barDir val="' +(chart.type==="barClustered"?"bar":"col")+ '"/><c:grouping val="clustered"/>';yield '<c:varyColors val="' +(pie?1:0)+ '"/>';for(let i=0;i<chart.data.series.length;i++){const series=chart.data.series[i],column="$"+columnName(i+2);yield '<c:ser><c:idx val="'+i+'"/><c:order val="'+i+'"/><c:tx>';const nameFormula=chart.binding?chart.binding.references.names[i]:source+column+"$1";if(nameFormula===undefined)
715
+ yield '<c:v>'+escapeXml(series.name,policy)+ '</c:v>';else
716
+ yield*reference("str",nameFormula,[series.name],policy);yield '</c:tx>';if(series.color)
717
+ yield '<c:spPr>' +(line?'<a:ln w="25400">':"")+ '<a:solidFill><a:srgbClr val="'+series.color+'"/></a:solidFill>' +(line?'</a:ln>':"")+ '</c:spPr>';if(!line&&!pie)
718
+ yield '<c:invertIfNegative val="0"/>';yield '<c:cat>';yield*reference("str",chart.binding?.references.categories??source+'$A$2:$A$'+end,chart.data.categories,policy);yield '</c:cat><c:val>';yield*reference("num",chart.binding?.references.values[i]??source+column+"$2:"+column+"$"+end,series.values,policy);yield '</c:val>' +(line?'<c:smooth val="0"/>':"")+ '</c:ser>'}
719
+ yield labelsXml(chart,policy);if(!pie&&!line)
720
+ yield '<c:gapWidth val="150"/><c:overlap val="0"/>';if(!pie)
721
+ yield '<c:axId val="1"/><c:axId val="2"/>';yield '</c:'+tag+'>';if(!pie)
722
+ yield axesXml(chart,policy);yield '</c:plotArea>';if(chart.legend!==false){const position={right:"r",bottom:"b",left:"l",top:"t"}[chart.legend??"right"];yield '<c:legend><c:legendPos val="'+position+'"/><c:layout/><c:overlay val="0"/></c:legend>'}
723
+ yield '<c:plotVisOnly val="' +(chart.binding?1:0)+ '"/><c:dispBlanksAs val="gap"/><c:showDLblsOverMax val="0"/></c:chart></c:chartSpace>'}
724
+ async function writeChartXml(chart,destination,policy,signal){const text=new ChunkedTextSink(destination,signal);for(const fragment of chartXml(chart,policy))
725
+ if(text.append(fragment))
726
+ await text.flush();await text.close()}
727
+ const _exports=Object.freeze({chartNamespace:chartNamespace,chartContentType:chartContentType,chartAnchorXml:chartAnchorXml,writeChartXml:writeChartXml});_modules.set("84c16159c55cf4c0af5d3c67510302694946ae99c6c685fc09314069ee3da5c5",_exports);return _exports})();const _m38=_modules.get("9d4496a1ff3d58ac0b9dcd7304e6861184df30700c344329157899639df7b5e4")??(()=>{const{cleanXml,escapeXml,escapeOoxmlAttribute,xmlDeclaration}=_m28;const{copyExportLink}=_m7;const{officeRelationshipsNamespace}=_m25;const{chartAnchorXml}=_m39;const{captureFields}=_m10;function copyDrawingAnchor(anchor,policy){anchor=captureFields(anchor,["row","column","width","height","description"]);if(!Number.isInteger(anchor.row)||anchor.row<1||anchor.row>1048576||!Number.isInteger(anchor.column)||anchor.column<1||anchor.column>16384)
728
+ throw new RangeError("Drawing anchors must be one-based worksheet rows and columns.");for(const size of[anchor.width,anchor.height])
729
+ if(!Number.isFinite(size)||size<=0||size>100000)
730
+ throw new RangeError("Drawing display dimensions must be positive and at most 100,000 pixels.");if(anchor.description!==undefined&&typeof anchor.description!=="string")
731
+ throw new TypeError("Drawing description must be a string.");return Object.freeze({row:anchor.row,column:anchor.column,width:anchor.width,height:anchor.height,...(anchor.description===undefined?{}:{description:cleanXml(anchor.description,policy)})})}
732
+ function cellPosition(reference){const match=typeof reference==="string"&&/^([A-Z]{1,3})([1-9][0-9]{0,6})$/.exec(reference);
733
+ if(!match)
734
+ throw new TypeError("Use a single uppercase A1 cell reference.");const row=Number(match[2]);let column=0;for(const letter of match[1])
735
+ column=column*26+letter.charCodeAt(0)- 64;if(column>16384||row>1048576)
736
+ throw new RangeError("Cell reference exceeds Excel's worksheet bounds.");return{row,column}}
737
+ function copyHyperlink(link,policy){link=captureFields(link,["cell","target","tooltip"]);cellPosition(link.cell);const copied=copyExportLink(link);return Object.freeze({cell:link.cell,target:copied.target,...(copied.tooltip===undefined?{}:{tooltip:cleanXml(copied.tooltip,policy)})})}
738
+ function copyImage(image,policy,checkBytes){image=captureFields(image,["data","row","column","width","height","description"]);if(image.data instanceof Uint8Array)
739
+ checkBytes?.(image.data.length);if(!(image.data instanceof Uint8Array)||image.data.length<33||
740
+ ![137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82].every((byte,i)=>image.data[i]===byte))
741
+ throw new TypeError("Images require PNG bytes with a valid signature and IHDR header.");const header=new DataView(image.data.buffer,image.data.byteOffset,image.data.byteLength);if(!header.getUint32(16)||!header.getUint32(20))
742
+ throw new RangeError("PNG dimensions must be positive.");return Object.freeze({...copyDrawingAnchor(image,policy),data:new Uint8Array(image.data)})}
743
+ function hyperlinksXml(links,policy,internal=[]){return '<hyperlinks>'+links.map((link,i)=>'<hyperlink ref="'+link.cell+'" r:id="link' +(i+1)+ '"' +
744
+ (link.tooltip===undefined?"":' tooltip="'+escapeOoxmlAttribute(link.tooltip,policy)+ '"')+ '/>').join("")+
745
+ internal.map(link=>'<hyperlink ref="'+link.cell+'" location="'+escapeOoxmlAttribute(link.location,policy)+ '"/>').join("")+ '</hyperlinks>'}
746
+ function drawingXml(images,policy,charts=[]){const ns="http://schemas.openxmlformats.org/drawingml/2006/";return xmlDeclaration+'<xdr:wsDr xmlns:xdr="'+ns+'spreadsheetDrawing" xmlns:a="'+ns+'main" xmlns:r="'+officeRelationshipsNamespace+'">' +
747
+ images.map((image,i)=>{const size=' cx="'+Math.round(image.width*9525)+ '" cy="'+Math.round(image.height*9525)+ '"';return '<xdr:oneCellAnchor><xdr:from><xdr:col>' +(image.column-1)+ '</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>' +(image.row-1)+ '</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>' +
748
+ '<xdr:ext'+size+'/><xdr:pic><xdr:nvPicPr><xdr:cNvPr id="' +(i+1)+ '" name="Image ' +(i+1)+ '" descr="'+escapeXml(image.description??"",policy)+ '"/><xdr:cNvPicPr/></xdr:nvPicPr>' +
749
+ '<xdr:blipFill><a:blip r:embed="image' +(i+1)+ '"/><a:stretch><a:fillRect/></a:stretch></xdr:blipFill>' +
750
+ '<xdr:spPr><a:xfrm><a:off x="0" y="0"/><a:ext'+size+'/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic><xdr:clientData/></xdr:oneCellAnchor>'}).join("")+ charts.map((chart,i)=>chartAnchorXml(chart,images.length+i+1,policy)).join("")+ '</xdr:wsDr>'}
751
+ const drawingContentType="application/vnd.openxmlformats-officedocument.drawing+xml";const _exports=Object.freeze({copyDrawingAnchor:copyDrawingAnchor,cellPosition:cellPosition,copyHyperlink:copyHyperlink,copyImage:copyImage,hyperlinksXml:hyperlinksXml,drawingXml:drawingXml,drawingContentType:drawingContentType});_modules.set("9d4496a1ff3d58ac0b9dcd7304e6861184df30700c344329157899639df7b5e4",_exports);return _exports})();const _m41=_modules.get("4c91e257806f805b473340527db7ce3404c98ac27db0a775ff047dc3dded10cc")??(()=>{const{OfficeIMOError}=_m2;const{cellPosition}=_m38;function indexRows(regions){if(!regions.length)
752
+ return undefined;const ordered=[...regions].sort((a,b)=>a.top-b.top),middle=ordered[Math.floor(ordered.length / 2)].top;
753
+ const crossing=[],before=[],after=[];for(const region of ordered)
754
+ (region.bottom<middle?before:region.top>middle?after:crossing).push(region);const left=indexRows(before),right=indexRows(after);return{middle,starts:crossing,ends:[...crossing].sort((a,b)=>b.bottom-a.bottom),...(left?{before:left}:{}),...(right?{after:right}:{})}}
755
+ function rowRegions(index,row,output){if(!index)
756
+ return;for(const region of row<=index.middle?index.starts:index.ends){if(row<=index.middle?region.top>row:region.bottom<row)
757
+ break;output.push(region)}
758
+ rowRegions(row<index.middle?index.before:row>index.middle?index.after:undefined,row,output)}
759
+ class MergeRegions{references;index;currentRow=-1;current=[];lastRow;constructor(references,columns,maximum){if(references.length>maximum)
760
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxMergedRanges exceeded.");if(!references.length){this.references=Object.freeze([]);this.lastRow=0;this.index=undefined;return}
761
+ const regions=references.map(ref=>{if(typeof ref!=="string"||ref.split(":").length!==2)
762
+ throw new TypeError("Merged ranges require uppercase A1:B2 references.");const[first,last]=ref.split(":"),start=cellPosition(first),end=cellPosition(last);if(end.row<start.row||end.column<start.column||(end.row===start.row&&end.column===start.column))
763
+ throw new RangeError("Merged ranges require ordered distinct cells.");if(end.column>columns)
764
+ throw new RangeError("Merged ranges must stay within declared columns.");return{ref,top:start.row,bottom:end.row,left:start.column,right:end.column}});const events=regions.flatMap(r=>[{row:r.top,delta:1,region:r},{row:r.bottom+1,delta:-1,region:r}]).sort((a,b)=>a.row-b.row||a.delta-b.delta);const counts=new Int32Array(65536),lazy=new Int32Array(65536);function update(node,first,last,left,right,delta){if(left<=first&&last<=right){counts[node]=counts[node]+ delta;lazy[node]=lazy[node]+ delta;return}
765
+ const middle=(first+last)>>>1;if(left<=middle)
766
+ update(node*2,first,middle,left,right,delta);if(right>middle)
767
+ update(node*2+1,middle+1,last,left,right,delta);counts[node]=lazy[node]+ Math.max(counts[node*2],counts[node*2+1])}
768
+ for(const event of events){update(1,1,16384,event.region.left,event.region.right,event.delta);if(counts[1]>1)
769
+ throw new TypeError("Merged ranges must not overlap: "+event.region.ref)}
770
+ this.references=Object.freeze(regions.map(r=>r.ref));this.lastRow=regions.reduce((last,r)=>Math.max(last,r.bottom),0);this.index=indexRows(regions)}
771
+ covered(column,row){if(!this.index||row>this.lastRow)
772
+ return false;if(this.currentRow!==row){this.current=[];rowRegions(this.index,row,this.current);this.current.sort((a,b)=>a.left-b.left);this.currentRow=row}
773
+ let first=0,last=this.current.length-1;while(first<=last){const middle=(first+last)>>>1,region=this.current[middle];if(column<region.left)
774
+ last=middle-1;else if(column>region.right)
775
+ first=middle+1;else
776
+ return row!==region.top||column!==region.left}
777
+ return false}
778
+ validateRows(rows){if(this.lastRow>rows)
779
+ throw new RangeError("Merged ranges must stay within exported rows.")}}
780
+ const _exports=Object.freeze({MergeRegions:MergeRegions});_modules.set("4c91e257806f805b473340527db7ce3404c98ac27db0a775ff047dc3dded10cc",_exports);return _exports})();const _m42=_modules.get("47efdc8f108b0e995accdd63fd1addea0e4de507010cbf0975417e7151636360")??(()=>{const{ExportCell}=_m5;const{tableSpans}=_m18;const{copyValue,columnName}=_m35;class StructuredRows{values;ranges;constructor(rows,columns){const anchors=tableSpans(rows,columns),ranges=[];this.values=anchors.map((row,level)=>{const values=Array(columns).fill(undefined);for(const anchor of row){values[anchor.first]=copyValue(anchor.value);if(anchor.span>1||anchor.rowSpan>1)
781
+ ranges.push({first:anchor.first+1,last:anchor.first+anchor.span,top:level+1,bottom:level+anchor.rowSpan})}
782
+ return Object.freeze(values)});this.ranges=ranges}
783
+ get mergeCount(){return this.ranges.length}
784
+ merges(offset){return this.ranges.map(r=>columnName(r.first)+(r.top+offset)+ ":"+columnName(r.last)+(r.bottom+offset))}
785
+ matchesLeaf(headers){const last=this.values.length;return!this.ranges.some(r=>r.bottom===last)&&this.values[last-1].every((value,index)=>(value instanceof ExportCell?value.value:value)===headers[index])}}
786
+ const _exports=Object.freeze({StructuredRows:StructuredRows});_modules.set("47efdc8f108b0e995accdd63fd1addea0e4de507010cbf0975417e7151636360",_exports);return _exports})();const _m40=_modules.get("23615ba776e7025e5e40cde325ad13799a7eeae6c88cb2ed74395222f91e6a81")??(()=>{const{ExportCell}=_m5;const{isDate}=_m6;const{Cell,cellText,columnName}=_m35;const{FormulaCell}=_m36;const{escapeOoxmlAttribute}=_m28;const{MergeRegions}=_m41;const{OfficeIMOError}=_m2;const{createTotals}=_m12;const{StructuredRows}=_m42;class ComputedTotal{value;formula;operation;constructor(value,formula,operation){this.value=value;this.formula=formula;this.operation=operation}}
787
+ class ReportLayout{columns;options;headings;merges;headerRows;firstHeaderRow;regions;widths;sampleRows;structuredFooter;footerRows;mergeCount;aggregates;constructor(columns,options,policy,maximumMerges=10000,maximumSampleCells=100000){this.columns=columns;this.options=options;const titleRows=options.title===undefined?0:1;if(options.title!==undefined){if(!columns.length)
788
+ throw new TypeError("Report titles require declared columns.");if(typeof options.title.text!=="string")
789
+ throw new TypeError("Report title text must be a string.");cellText(options.title.text,policy);if(options.title.height!==undefined&&(!Number.isFinite(options.title.height)||options.title.height<=0||options.title.height>409))
790
+ throw new RangeError("Title height must be positive and at most 409 points.")}
791
+ const depth=Math.max(0,...columns.map(c=>c.groups?.length??0));if(options.headerRows===undefined){if(depth>16)
792
+ throw new RangeError("Grouped headings support at most 16 levels.");if(depth&&options.includeHeader===false)
793
+ throw new TypeError("Grouped headings require leaf headers.")}
794
+ const headings=[],merges=[];if(titleRows&&columns.length>1)
795
+ merges.push("A1:"+columnName(columns.length)+ "1");if(options.headerRows!==undefined&&options.includeHeader!==false){const structured=new StructuredRows(options.headerRows,columns.length);if((options.table||options.autoFilter)&&!structured.matchesLeaf(columns.map(c=>c.header)))
796
+ throw new TypeError("Native tables and autofilters require an unmerged final heading row matching the declared leaf headers.");headings.push(...structured.values);merges.push(...structured.merges(titleRows))}
797
+ else if(options.includeHeader!==false){for(let level=0;level<depth;level++){const values=columns.map(c=>c.groups?.[level]??"");for(const value of values)
798
+ cellText(value,policy);for(let first=0;first<columns.length;){let last=first;const prefix=JSON.stringify(columns[first].groups?.slice(0,level+1));while(last+1<columns.length&&values[first]&&JSON.stringify(columns[last+1].groups?.slice(0,level+1))===prefix)
799
+ last++;if(last>first){merges.push(columnName(first+1)+(level+1+titleRows)+ ":"+columnName(last+1)+(level+1+titleRows));for(let i=first+1;i<=last;i++)
800
+ values[i]=""}
801
+ first=last+1}
802
+ headings.push(values)}
803
+ if(columns.length)
804
+ headings.push(columns.map(c=>c.header))}
805
+ this.headerRows=titleRows+headings.length;this.firstHeaderRow=columns.length&&options.includeHeader!==false?titleRows+1:0;if(options.mergedCells!==undefined&&!Array.isArray(options.mergedCells))
806
+ throw new TypeError("Merged ranges must be an array.");if(options.footer?.rows!==undefined&&(options.footer.values!==undefined||options.footer.totals!==undefined))
807
+ throw new TypeError("Structured footer rows cannot accompany footer values or totals.");this.structuredFooter=options.footer?.rows===undefined?undefined:new StructuredRows(options.footer.rows,columns.length);this.footerRows=this.structuredFooter?.values.length??(options.footer?1:0);this.mergeCount=merges.length +(options.mergedCells?.length??0)+(this.structuredFooter?.mergeCount??0);if(this.mergeCount>maximumMerges)
808
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxMergedRanges exceeded.");this.regions=new MergeRegions([...merges,...(options.mergedCells??[])],columns.length,maximumMerges);if(options.table)
809
+ for(const ref of options.mergedCells??[])
810
+ if(Number(ref.split(":")[1].match(/\d+$/)[0]) >= this.headerRows)
811
+ throw new TypeError("Merged ranges cannot intersect a native table.");this.headings=headings;this.merges=this.regions.references;const sizing=options.autoSize;this.sampleRows=sizing?sizing.sampleRows??Math.min(100,Math.floor(maximumSampleCells / Math.max(1, columns.length))) : 0;
812
+ if(!Number.isInteger(this.sampleRows)||this.sampleRows<0||this.sampleRows>1048576)
813
+ throw new RangeError("Width sampling must use from 0 through 1,048,576 rows within its buffer budgets.");const min=sizing?.minWidth??8,max=sizing?.maxWidth??60;if(!Number.isFinite(min)||!Number.isFinite(max)||min<0||min>max||max>255)
814
+ throw new RangeError("Width bounds must satisfy 0 <= minWidth <= maxWidth <= 255.");this.widths=columns.map(c=>c.width??(sizing?Math.max(min,Math.min(max,c.header.length+2)):undefined));if(options.footer?.values&&options.footer.values.length>columns.length)
815
+ throw new RangeError("Footer has more values than declared columns.");this.aggregates=createTotals(columns,options.footer?.totals);if(options.print)
816
+ validatePrint(options.print,policy)}
817
+ finalRegions(rows,maximumMerges){return this.structuredFooter?new MergeRegions([...this.merges,...this.structuredFooter.merges(this.headerRows+rows)],this.columns.length,maximumMerges):this.regions}
818
+ sample(values){const min=this.options.autoSize?.minWidth??8,max=this.options.autoSize?.maxWidth??60;values.forEach((value,i)=>{if(!this.columns[i]||this.columns[i].width!==undefined)
819
+ return;const raw=value instanceof FormulaCell?value.cachedValue:value instanceof ExportCell?value.text??value.value:value instanceof Cell?value.value:value;const text=isDate(raw)?Number.isFinite(raw.getTime())?raw.toISOString():"":raw==null?"":String(raw);const length=Math.max(0,...text.slice(0,Math.ceil(max*4)).split(/\r?\n/).map(line => [...line].length));
820
+ this.widths[i]=Math.max(this.widths[i]??min,Math.min(max,length+2))})}
821
+ accept(index,value){this.aggregates[index].accept(value)}
822
+ footer(rows){return this.columns.map((_,i)=>{const total=this.aggregates[i],operation=total.operation;if(!operation)
823
+ return this.options.footer?.values?.[i];const value=total.value();return new ComputedTotal(value,totalFormula(operation,columnName(i+1),this.headerRows,rows),operation)})}}
824
+ function totalFormula(operation,letter,headerRows,rows){const code={sum:109,count:102,average:101,min:105,max:104}[operation];const guarded=["average","min","max"].includes(operation);const range=letter +(headerRows+1)+ ":"+letter +(headerRows+rows),subtotal="SUBTOTAL("+code+","+range+")";return!rows?guarded?'""':"0":guarded?'IF(SUBTOTAL(102,'+range+')=0,"",'+subtotal+')':subtotal}
825
+ function validatePrint(options,policy){if(options.paper!==undefined&&!["A4","Letter"].includes(options.paper))
826
+ throw new TypeError("Print paper must be A4 or Letter.");if(options.orientation!==undefined&&!["portrait","landscape"].includes(options.orientation))
827
+ throw new TypeError("Invalid print orientation.");for(const value of[options.fitToWidth,options.fitToHeight])
828
+ if(value!==undefined&&(!Number.isInteger(value)||value<0||value>32767))
829
+ throw new RangeError("Print fit dimensions must be integers from 0 through 32,767.");for(const value of Object.values(options.margins??{}))
830
+ if(!Number.isFinite(value)||value<0||value>10)
831
+ throw new RangeError("Print margins must be from 0 through 10 inches.");for(const text of[options.header,options.footer])
832
+ if(text!==undefined){if(typeof text!=="string"||text.length>250)
833
+ throw new TypeError("Print header/footer must be strings of at most 250 UTF-16 units.");cellText(text,policy);if(("&C"+text.replace(/&/g, "&&")).length > 255)
834
+ throw new RangeError("Encoded print header/footer exceeds Excel's 255-character limit.")}}
835
+ function printXml(options,policy){if(!options)
836
+ return "";const margins={left:.25,right:.25,top:.5,bottom:.5,header:.2,footer:.2,...options.margins};return '<pageMargins'+Object.entries(margins).map(([key,value])=>' '+key+'="'+value+'"').join("")+ '/>' +
837
+ '<pageSetup paperSize="' +(options.paper==="Letter"?1:9)+ '" orientation="' +(options.orientation??"landscape")+ '" fitToWidth="' +(options.fitToWidth??1)+ '" fitToHeight="' +(options.fitToHeight??0)+ '"/>' +
838
+ (options.header!==undefined||options.footer!==undefined?'<headerFooter>' +
839
+ (options.header===undefined?"":'<oddHeader>'+escapeOoxmlAttribute("&C"+options.header.replace(/&/g, "&&"), policy) + '</oddHeader>') +
840
+ (options.footer===undefined?"":'<oddFooter>'+escapeOoxmlAttribute("&C"+options.footer.replace(/&/g, "&&"), policy) + '</oddFooter>') + '</headerFooter>' : "");
841
+ }
842
+ const _exports=Object.freeze({ComputedTotal:ComputedTotal,ReportLayout:ReportLayout,totalFormula:totalFormula,printXml:printXml});_modules.set("23615ba776e7025e5e40cde325ad13799a7eeae6c88cb2ed74395222f91e6a81",_exports);return _exports})();const _m44=_modules.get("7845d79cd22590bbefc767802abfe3f805e8f68807521cef8d07ecc42db0b491")??(()=>{const{columnName}=_m35;function resolveDataColumn(columns,value,context="Data"){if(typeof value==="string"){const matches=columns.flatMap((column,index)=>column.key===value?[index+1]:[]);if(matches.length!==1)
843
+ throw new TypeError(context+" column keys must identify exactly one declared column.");return matches[0]}
844
+ if(!Number.isInteger(value)||value<1||value>columns.length)
845
+ throw new RangeError(context+" column numbers must be one-based and within declared columns.");return value}
846
+ function qualifiedColumnRange(sheetName,column,firstRow,rows){if(!Number.isSafeInteger(firstRow)||firstRow<1||!Number.isSafeInteger(rows)||rows<1||firstRow+rows-1>1048576)
847
+ throw new RangeError("A data range must fit within Excel's worksheet rows.");const letter=columnName(column);return "'"+sheetName.replace(/'/g, "''") + "'!$" + letter + "$" + firstRow + ":$" + letter + "$" + (firstRow + rows - 1);
848
+ }
849
+ function qualifiedCell(sheetName,column,row){return qualifiedColumnRange(sheetName,column,row,1).split(":")[0]}
850
+ const _exports=Object.freeze({resolveDataColumn:resolveDataColumn,qualifiedColumnRange:qualifiedColumnRange,qualifiedCell:qualifiedCell});_modules.set("7845d79cd22590bbefc767802abfe3f805e8f68807521cef8d07ecc42db0b491",_exports);return _exports})();const _m45=_modules.get("4892a7dafefc4d82567cd2bd4cc8da5470cee4dbf546e6473f782f44bd4bbe35")??(()=>{const{OfficeIMOError}=_m2;const{columnName}=_m35;const scopes=new WeakMap();function retainDataRowRanges(worksheet,ranges){scopes.set(worksheet,ranges)}
851
+ function dataRowRanges(worksheet){return scopes.get(worksheet)}
852
+ function dataRowCount(worksheet,headerRows,serializedRows){const ranges=scopes.get(worksheet);if(ranges===undefined)
853
+ return serializedRows;const lastSerialized=headerRows+serializedRows;let rows=0;for(const range of ranges){if(range.firstRow>lastSerialized)
854
+ break;rows +=Math.min(range.lastRow,lastSerialized)- range.firstRow+1}
855
+ return rows}
856
+ function dataRowReference(firstColumn,lastColumn,headerRows,dataRows,ranges){if(ranges===undefined)
857
+ return dataRows?columnName(firstColumn)+(headerRows+1)+ ":"+columnName(lastColumn)+(headerRows+dataRows):undefined;const first=columnName(firstColumn),last=columnName(lastColumn);let reference="",previous=headerRows;for(const range of ranges){if(!Number.isSafeInteger(range.firstRow)||!Number.isSafeInteger(range.lastRow)||range.firstRow<=previous||
858
+ range.lastRow<range.firstRow||range.lastRow>headerRows+dataRows)
859
+ throw new RangeError("Detail editing ranges must be ordered within serialized worksheet rows.");const next=first+range.firstRow+":"+last+range.lastRow;if(reference.length +(reference?1:0)+ next.length>32767)
860
+ throw new OfficeIMOError("RESOURCE_LIMIT","Detail editing references exceed 32,767 UTF-16 characters; split the worksheet.");reference +=(reference?" ":"")+ next;previous=range.lastRow}
861
+ return reference||undefined}
862
+ const _exports=Object.freeze({retainDataRowRanges:retainDataRowRanges,dataRowRanges:dataRowRanges,dataRowCount:dataRowCount,dataRowReference:dataRowReference});_modules.set("4892a7dafefc4d82567cd2bd4cc8da5470cee4dbf546e6473f782f44bd4bbe35",_exports);return _exports})();const _m43=_modules.get("736b2b2fc3489642263dbaf677544e8a270eea6b8efb0cc26c67346e66cab118")??(()=>{const{cleanXml,escapeXml,escapeOoxmlAttribute}=_m28;const{cellPosition}=_m38;const{colorArgb}=_m33;const{fields,optionalBoolean,differentialXml}=_m34;const{resolveDataColumn}=_m44;const{dataRowReference}=_m45;function target(range,columns){if(typeof range==="string"){const parts=range.split(":");if(parts.length>2)
863
+ throw new TypeError("Conditional ranges require one uppercase A1 cell or rectangle.");const first=cellPosition(parts[0]),last=cellPosition(parts[1]??parts[0]);if(last.row<first.row||last.column<first.column||last.column>columns.length)
864
+ throw new RangeError("Conditional ranges require ordered cells within declared columns.");return{first:first.column,last:last.column,reference:range,bottom:last.row}}
865
+ fields(range,["column","through"],"conditional data range");const first=resolveDataColumn(columns,range.column,"Conditional"),last=range.through===undefined?first:resolveDataColumn(columns,range.through,"Conditional");if(last<first)
866
+ throw new RangeError("Conditional data ranges require ordered columns.");return{first,last}}
867
+ function finite(value){if(typeof value!=="number"||!Number.isFinite(value))
868
+ throw new TypeError("Conditional values must be finite numbers.");return String(value)}
869
+ function comparisonValue(value,operator){if(typeof value!=="string")
870
+ return finite(value);if(operator!=="equal"&&operator!=="notEqual")
871
+ throw new TypeError("Text conditional comparisons support only equal and notEqual.");if(value.length>8190)
872
+ throw new RangeError("Conditional comparison formulas must fit 8,192 characters including quotes.");cleanXml(value,"reject");const literal='"'+value.replace(/"/g, '""') + '"';
873
+ if(literal.length>8192)
874
+ throw new RangeError("Conditional comparison formulas must fit 8,192 characters including quotes.");return literal}
875
+ function formula(value){if(typeof value!=="string")
876
+ throw new TypeError("Conditional formulas must be strings.");const text=value.trim().replace(/^=/, "");
877
+ if(!text.trim()||text.length>8192)
878
+ throw new RangeError("Conditional formulas require 1 through 8,192 characters.");cleanXml(text,"reject");return text}
879
+ function threshold(value,position){fields(value,value.type==="min"||value.type==="max"?["type"]:["type","value"],"conditional threshold");if(value.type==="min"||value.type==="max"){if(value.type!==(position==="first"?"min":position==="last"?"max":""))
880
+ throw new TypeError("Use min only at the start and max only at the end of a scale.");return '<cfvo type="'+value.type+'"/>'}
881
+ if(value.type==="formula")
882
+ return '<cfvo type="formula" val="'+escapeOoxmlAttribute(formula(value.value),"reject")+ '"/>';if(!["number","percent","percentile"].includes(value.type))
883
+ throw new TypeError("Unsupported conditional threshold type.");if(!("value" in value))
884
+ throw new TypeError("A numeric threshold requires a value.");const number=finite(value.value);if(value.type!=="number"&&(value.value<0||value.value>100))
885
+ throw new RangeError("Conditional percent/percentile thresholds must be from 0 through 100.");return '<cfvo type="' +(value.type==="number"?"num":value.type)+ '" val="'+number+'"/>'}
886
+ function ordered(values){for(let i=1;i<values.length;i++){const before=values[i-1],after=values[i];if("value" in before&&"value" in after&&before.type===after.type&&typeof before.value==="number"&&typeof after.value==="number"&&before.value>after.value)
887
+ throw new RangeError("Conditional thresholds of the same numeric type must be ordered.")}}
888
+ function prepareConditionalFormats(rules,columns,policy){if(rules===undefined)
889
+ return[];if(!Array.isArray(rules))
890
+ throw new TypeError("conditionalFormats must be an array.");return rules.map(rule=>{const common=["type","range"],highlighting=["style","stopIfTrue"];fields(rule,[...common,...(rule?.type==="cellIs"?[...highlighting,"operator","value","values"]:rule?.type==="expression"?[...highlighting,"formula"]:rule?.type==="colorScale"?["stops"]:rule?.type==="dataBar"?["color","minimum","maximum","showValue"]:[])],"conditional rule");const selected=target(rule.range,columns);let attributes="",body="",style;if(rule.type==="cellIs"||rule.type==="expression"){optionalBoolean(rule.stopIfTrue,"stopIfTrue");differentialXml(rule.style,policy,()=>164);style={...rule.style,...(rule.style.font?{font:{...rule.style.font}}:{}),...(rule.style.fill?{fill:{...rule.style.fill}}:{}),...(rule.style.border?{border:Object.fromEntries(Object.entries(rule.style.border).filter(([,edge])=>edge!==undefined).map(([side,edge])=>[side,{...edge}]))}:{})};if(rule.stopIfTrue!==undefined)
891
+ attributes +=' stopIfTrue="' +(rule.stopIfTrue?1:0)+ '"';if(rule.type==="expression")
892
+ body='<formula>'+escapeXml(formula(rule.formula),"reject")+ '</formula>';else{const pair=rule.operator==="between"||rule.operator==="notBetween";if(!["equal","notEqual","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual","between","notBetween"].includes(rule.operator))
893
+ throw new TypeError("Unsupported conditional comparison operator.");if(pair){if("value" in rule||!Array.isArray(rule.values)||rule.values.length!==2)
894
+ throw new TypeError("between/notBetween require exactly two values.");body=rule.values.map(value=>'<formula>'+finite(value)+ '</formula>').join("");if(rule.values[0]>rule.values[1])
895
+ throw new RangeError("Conditional comparison bounds must be ordered.")}
896
+ else{if("values" in rule||!("value" in rule))
897
+ throw new TypeError("A conditional comparison requires one value.");body='<formula>'+escapeXml(comparisonValue(rule.value,rule.operator),"reject")+ '</formula>'}
898
+ attributes +=' operator="'+rule.operator+'"'}}
899
+ else if(rule.type==="colorScale"){if(!Array.isArray(rule.stops)||(rule.stops.length!==2&&rule.stops.length!==3))
900
+ throw new TypeError("Color scales require two or three stops.");const colors=[],thresholds=[];body='<colorScale>'+rule.stops.map((stop,i)=>{fields(stop,["threshold","color"],"color stop");colors.push(colorArgb(stop.color));thresholds.push(stop.threshold);return threshold(stop.threshold,i===0?"first":i===rule.stops.length-1?"last":"middle")}).join("")+ colors.map(color=>'<color rgb="'+color+'"/>').join("")+ '</colorScale>';ordered(thresholds)}
901
+ else if(rule.type==="dataBar"){optionalBoolean(rule.showValue,"showValue");const lower=rule.minimum===undefined?{type:"min"}:rule.minimum,upper=rule.maximum===undefined?{type:"max"}:rule.maximum;body='<dataBar showValue="' +(rule.showValue===false?0:1)+ '">'+threshold(lower,"first")+ threshold(upper,"last")+ '<color rgb="'+colorArgb(rule.color)+ '"/></dataBar>';ordered([lower,upper])}
902
+ else
903
+ throw new TypeError("Unsupported conditional rule type.");return{target:selected,type:rule.type,attributes,body,...(style?{style}:{})}})}
904
+ class ConditionalFormats{rules;constructor(prepared,styles){const differential=styles.addDifferentials(prepared.flatMap(rule=>rule.style?[rule.style]:[]));let styleIndex=0;this.rules=prepared.map((rule,i)=>({target:rule.target,xml:'<cfRule type="'+rule.type+'" priority="' +(i+1)+ '"' +(rule.style?' dxfId="'+differential[styleIndex++]+ '"':"")+ rule.attributes+'>'+rule.body+'</cfRule>'}))}
905
+ get count(){return this.rules.length}
906
+ *xml(headerRows,dataRows,totalRows,ranges){for(const rule of this.rules){if(rule.target.bottom!==undefined&&rule.target.bottom>totalRows)
907
+ throw new RangeError("Conditional ranges must stay within exported rows.");const reference=rule.target.reference??dataRowReference(rule.target.first,rule.target.last,headerRows,dataRows,ranges);if(!reference)
908
+ continue;yield '<conditionalFormatting sqref="'+reference+'">'+rule.xml+'</conditionalFormatting>'}}}
909
+ const _exports=Object.freeze({prepareConditionalFormats:prepareConditionalFormats,ConditionalFormats:ConditionalFormats});_modules.set("736b2b2fc3489642263dbaf677544e8a270eea6b8efb0cc26c67346e66cab118",_exports);return _exports})();const _m46=_modules.get("860c88d97ba76e8713c14d56967152e369d2f08f50ffada68827a9c220881c61")??(()=>{const{OfficeIMOError}=_m2;const{checkAbort}=_m4;const{cleanXml,escapeOoxmlAttribute,escapeXml}=_m28;const{fields,optionalBoolean}=_m34;const{resolveDataColumn}=_m44;const{dataRowReference}=_m45;function message(value,maximum,name){if(value===undefined)
910
+ return undefined;if(typeof value!=="string")
911
+ throw new TypeError(name+" must be text.");if(value.length>maximum)
912
+ throw new RangeError(name+" exceeds "+maximum+" UTF-16 units.");return cleanXml(value,"reject")}
913
+ function prepareDataValidations(rules,columns,availableCount=1000,availableText=1000000,signal){checkAbort(signal);if(rules===undefined)
914
+ return Object.freeze({rules:Object.freeze([]),count:0,textCharacters:0});if(!Array.isArray(rules))
915
+ throw new TypeError("dataValidation must be an array.");const count=rules.length;if(count>availableCount)
916
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxDataValidations exceeded.");const prepared=[];const usedColumns=new Set();let textCharacters=0;const acceptText=(length)=>{if(textCharacters+length>availableText)
917
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxValidationTextCharacters exceeded.");textCharacters +=length};for(let index=0;index<count;index++){checkAbort(signal);const rule=rules[index];fields(rule,["type","column","items","allowBlank","showErrorMessage","errorStyle","errorTitle","errorMessage"],"data validation");const{type,column,items,allowBlank,showErrorMessage,errorStyle,errorTitle,errorMessage}=rule;if(type!=="list")
918
+ throw new TypeError("Only inline-list data validation is supported.");const selected=resolveDataColumn(columns,column,"Validation");if(usedColumns.has(selected))
919
+ throw new TypeError("A data column cannot have multiple validation rules.");usedColumns.add(selected);optionalBoolean(allowBlank,"allowBlank");optionalBoolean(showErrorMessage,"showErrorMessage");if(errorStyle!==undefined&&!["stop","warning","information"].includes(errorStyle))
920
+ throw new TypeError("Unsupported validation error style.");if(!Array.isArray(items))
921
+ throw new TypeError("Inline validation lists require a nonempty string array.");const itemCount=items.length;if(!itemCount)
922
+ throw new TypeError("Inline validation lists require a nonempty string array.");if(itemCount>254)
923
+ throw new RangeError("Inline validation lists must fit 255 UTF-16 units including quotes and separators.");let formula='"';for(let item=0;item<itemCount;item++){checkAbort(signal);const value=items[item];if(typeof value!=="string")
924
+ throw new TypeError("Inline validation choices must be strings.");if(value.length>253||value.includes(","))
925
+ throw new RangeError("Inline validation choices cannot contain commas and must fit the 255-character list source.");cleanXml(value,"reject");const escaped=value.replace(/"/g, '""');
926
+ if(formula.length +(item?1:0)+ escaped.length+1>255)
927
+ throw new RangeError("Inline validation lists must fit 255 UTF-16 units including quotes and separators.");formula +=(item?",":"")+ escaped}
928
+ formula +='"';const title=message(errorTitle,32,"Validation error title"),error=message(errorMessage,255,"Validation error message");acceptText(formula.length +(title?.length??0)+(error?.length??0));const attributes=' type="list" allowBlank="' +(allowBlank===false?0:1)+ '" showErrorMessage="' +(showErrorMessage===false?0:1)+
929
+ '" errorStyle="' +(errorStyle??"stop")+ '"' +(title===undefined?"":' errorTitle="'+escapeOoxmlAttribute(title,"reject")+ '"')+
930
+ (error===undefined?"":' error="'+escapeOoxmlAttribute(error,"reject")+ '"');prepared.push(Object.freeze({column:selected,attributes,formula}))}
931
+ checkAbort(signal);return Object.freeze({rules:Object.freeze(prepared),count,textCharacters})}
932
+ function*dataValidationsXml(prepared,headerRows,dataRows,ranges){if(!prepared.count||!dataRows||ranges?.length===0)
933
+ return;yield '<dataValidations count="'+prepared.count+'">';for(const rule of prepared.rules){const reference=dataRowReference(rule.column,rule.column,headerRows,dataRows,ranges);yield '<dataValidation'+rule.attributes+' sqref="'+reference+'"><formula1>'+escapeXml(rule.formula,"reject")+ '</formula1></dataValidation>'}
934
+ yield '</dataValidations>'}
935
+ const _exports=Object.freeze({prepareDataValidations:prepareDataValidations,dataValidationsXml:dataValidationsXml});_modules.set("860c88d97ba76e8713c14d56967152e369d2f08f50ffada68827a9c220881c61",_exports);return _exports})();const _m37=_modules.get("b99287e3e329b75007119103112a699c368d8237b37fa79e083b0014a21952e4")??(()=>{const{checkAbort,consumeRows,inputRows,pause,taskYieldDue}=_m4;const{ChunkedTextSink,BlobByteSink}=_m3;const{OfficeIMOError}=_m2;const{notifyProgress}=_m14;const{copyColumns,createRowProjector}=_m11;const{EntryWriter}=_m30;const{xmlDeclaration}=_m28;const{officeRelationshipsNamespace}=_m25;const{Cell,cellText,columnName,inlineText,excelDate,copyValue}=_m35;const{spreadsheetNamespace,colorArgb,validateStylePatch,copyStylePatch}=_m32;const{copyHyperlink,copyImage,hyperlinksXml,cellPosition}=_m38;const{ExportCell,assertScalar}=_m5;const{ReportLayout,ComputedTotal,printXml}=_m40;const{cleanXml}=_m28;const{ConditionalFormats,prepareConditionalFormats}=_m43;const{isDate}=_m6;const{FormulaCell,formulaXml,isSubtotalFormula}=_m36;const{prepareDataValidations,dataValidationsXml}=_m46;const{qualifiedCell,qualifiedColumnRange,resolveDataColumn}=_m44;const{dataRowRanges,dataRowCount}=_m45;const maximumHyperlinks=65530;function checkHyperlinkCount(count){if(count>maximumHyperlinks)
936
+ throw new RangeError("Excel supports at most 65,530 hyperlinks per worksheet; split the sheet.")}
937
+ class Worksheet{book;table;preserved;chartData;validations;columns;project;name;declared;options;entry;completion;prepared;buffer;output=new BlobByteSink();started=false;busy=false;failed=false;error;count=0;headerRows;layout;completedRegions;titleStyle;pending=[];pendingCharacters=0;reservedLayout=false;internalLinks=[];links=[];linkedCells=new Set();pictures=[];nativeCharts=[];conditional;completed=false;chartSources=[];constructor(book,name,options,table,preserved=false,conditional=[],chartData=false,validations={rules:[],count:0,textCharacters:0}){this.book=book;this.table=table;this.preserved=preserved;this.chartData=chartData;this.validations=validations;this.columns=copyColumns(options.columns??[],true).map(c=>Object.freeze(c));const alternate=options.alternatingRowStyle;this.options={...options,...(options.autoSize?{autoSize:{...options.autoSize}}:{}),...(options.mergedCells?{mergedCells:[...options.mergedCells]}:{}),...(options.title?{title:{...options.title,...(options.title.style?{style:copyStylePatch(options.title.style)}:{})}}:{}),...(options.print?{print:{...options.print,...(options.print.margins?{margins:{...options.print.margins}}:{})}}:{}),...(options.footer?{footer:{...options.footer,...(options.footer.values?{values:options.footer.values.map(copyValue)}:{}),...(options.footer.totals?{totals:{...options.footer.totals}}:{}),...(options.footer.style?{style:copyStylePatch(options.footer.style)}:{})}}:{}),...(alternate?{alternatingRowStyle:copyStylePatch(alternate)}:{})};this.layout=new ReportLayout(this.columns,this.options,book.settings.invalidCharacterPolicy,book.settings.limits?.maxMergedRanges??10000,book.settings.limits?.maxBufferedCells??100000);this.titleStyle=options.title?book.styles.compose(book.styles.compose(0,{font:{bold:true,size:18}}),this.options.title.style??{}):0;this.headerRows=this.layout.headerRows;for(const link of options.hyperlinks??[]){const copied=copyHyperlink(link,book.settings.invalidCharacterPolicy);this.links.push(copied);this.linkedCells.add(copied.cell)}
938
+ book.checkLinks(this.links.length);this.declared=this.columns.map((column,i)=>({column,letter:columnName(i+1),style:book.styles.forColumn(column),dateStyle:book.styles.forColumn(column,false,undefined,true),headerStyle:this.headerRows?options.headerStyle??book.styles.forColumn({header:column.header,...(column.wrapText===undefined?{}:{wrapText:column.wrapText}),...(column.alignment===undefined?{}:{alignment:column.alignment})},options.boldHeader!==false,options.headerFill):0}));this.conditional=new ConditionalFormats(conditional,book.styles);book.retainLink(this.links.length);this.name=typeof name==="function"?name():name;this.project=createRowProjector(this.columns,{sheetName:this.name,firstDataRow:this.headerRows+1},book.settings.signal,book.valueValidator)}
939
+ static create(book,name,options,table,preserved=false,conditional,validations){return new Worksheet(book,name,options,table,preserved,conditional,false,validations)}
940
+ static createChartData(book,chart){return new Worksheet(book,chart.dataSheetName,{columns:[{header:"Category"},...chart.data.series.map(series=>({header:series.name,type:"number"}))]},undefined,false,[],true)}
941
+ static validate(book,options){const columns=copyColumns(options.columns??[],true);const validations=prepareDataValidations(options.dataValidation,columns,book.availableDataValidations,book.availableValidationTextCharacters,book.settings.signal);book.checkConditionalFormats(options.conditionalFormats?.length??0);const conditional=prepareConditionalFormats(options.conditionalFormats,columns,book.settings.invalidCharacterPolicy);book.styles.checkDifferentials(conditional.flatMap(rule=>rule.style?[rule.style]:[]));const layout=new ReportLayout(columns,options,book.settings.invalidCharacterPolicy,book.settings.limits?.maxMergedRanges??10000,book.settings.limits?.maxBufferedCells??100000);book.checkMerges(layout.mergeCount);if(options.title?.style)
942
+ validateStylePatch(options.title.style);if(options.title)
943
+ book.styles.compose(book.styles.compose(0,{font:{bold:true,size:18}}),options.title.style??{});if(options.footer?.style)
944
+ book.styles.compose(0,options.footer.style);if(options.hyperlinks!==undefined){if(!Array.isArray(options.hyperlinks))
945
+ throw new TypeError("Hyperlinks must be an array.");checkHyperlinkCount(options.hyperlinks.length);const seen=new Set();for(const requested of options.hyperlinks){const link=copyHyperlink(requested,book.settings.invalidCharacterPolicy);const position=cellPosition(link.cell);if(layout.regions.covered(position.column,position.row))
946
+ throw new TypeError("Hyperlinks cannot address a covered merged cell.");if(seen.has(link.cell))
947
+ throw new TypeError("Duplicate hyperlink cell: "+link.cell);seen.add(link.cell)}}
948
+ if(columns.length>16384)
949
+ throw new RangeError("Excel supports at most 16,384 columns.");if(options.includeHeader===false&&(options.freezeHeader||options.autoFilter))
950
+ throw new TypeError("A frozen header or autofilter requires a header row.");if(options.headerFill!==undefined)
951
+ colorArgb(options.headerFill);if(options.headerStyle!==undefined)
952
+ book.styles.validateStyle(options.headerStyle);if(options.alternatingRowStyle!==undefined)
953
+ book.styles.compose(0,options.alternatingRowStyle);for(const callback of[options.rowStyle,options.cellStyle,options.rowOutline])
954
+ if(callback!==undefined&&typeof callback!=="function")
955
+ throw new TypeError("Row and style callbacks must be functions.");if(options.maxOutlineLevel!==undefined&&(!Number.isInteger(options.maxOutlineLevel)||options.maxOutlineLevel<0||options.maxOutlineLevel>7))
956
+ throw new RangeError("Maximum outline level must be an integer from zero through seven.");if(options.rowOutline&&options.maxOutlineLevel===undefined)
957
+ throw new TypeError("A row outline callback requires maxOutlineLevel before streamed rows are written.");if(!options.rowOutline&&options.maxOutlineLevel!==undefined)
958
+ throw new TypeError("maxOutlineLevel requires a row outline callback.");for(const height of[options.rowHeight,options.headerHeight])
959
+ if(height!==undefined&&(!Number.isFinite(height)||height<=0||height>409))
960
+ throw new RangeError("Row height must be positive and at most 409 points.");if(options.freezeColumns!==undefined&&(!Number.isInteger(options.freezeColumns)||options.freezeColumns<0||options.freezeColumns>columns.length||options.freezeColumns>=16384))
961
+ throw new RangeError("Frozen columns must be within the declared columns and leave a valid scrollable column.");if(options.table&&options.includeHeader===false)
962
+ throw new TypeError("Excel tables require a header row.");if(options.defaultColumnWidth!==undefined&&(!Number.isFinite(options.defaultColumnWidth)||options.defaultColumnWidth<0||options.defaultColumnWidth>255))
963
+ throw new RangeError("Default column width must be from 0 through 255 characters.");for(const c of columns){if(c.width!==undefined&&(!Number.isFinite(c.width)||c.width<0||c.width>255))
964
+ throw new RangeError("Column width must be from 0 through 255 characters.");if(c.type!==undefined&&!["string","number","boolean","date"].includes(c.type)&&!book.writerFor(c.type))
965
+ throw new TypeError("Invalid column type: "+c.type);if(c.alignment!==undefined&&!["left","center","right","fill","justify","distributed"].includes(c.alignment))
966
+ throw new TypeError("Invalid horizontal alignment.");cellText(c.header,book.settings.invalidCharacterPolicy);if(c.style!==undefined)
967
+ book.styles.validateStyle(c.style);if(c.format!==undefined&&(typeof c.format!=="string"||c.format.length>255))
968
+ throw new TypeError("Column format must be a string of at most 255 characters.")}
969
+ return{conditional,validations}}
970
+ cell(value,i,row,header=false,rowStyle,context,rowStyles,footer=false,title=false,visible=true){const col=this.declared[i];const total=value instanceof ComputedTotal?value:undefined;if(total)
971
+ value=total.value;let formula=value instanceof FormulaCell?value:undefined;if(formula)
972
+ value=formula.cachedValue;let presentation=value instanceof ExportCell?value.presentation:undefined;let link=value instanceof ExportCell?value.link:undefined;if(value instanceof ExportCell)
973
+ value=value.value;const suppliedStyle=formula?.style??(value instanceof Cell?value.style:undefined);const covered=(this.completedRegions??this.layout.regions).covered(i+1,row);const input=value instanceof Cell?value.value:value,emptyCovered=covered&&(input==null||input==="");if(!header&&!footer&&col.column.type&&!emptyCovered){const writer=this.book.writerFor(col.column.type);if(writer){if(formula)
974
+ throw new TypeError("An explicit FormulaCell cannot also pass through a custom cell value writer; return it from the writer instead.");value=writer(value instanceof Cell?value.value:value,{column:col.column,rowIndex:row-this.headerRows-1,worksheetRow:row,columnIndex:i,sheetName:this.name})}}
975
+ if(value instanceof FormulaCell){formula=value;value=formula.cachedValue}
976
+ if(value instanceof ExportCell){presentation=value.presentation;link=value.link;value=value.value}
977
+ const explicitStyle=formula?.style??(value instanceof Cell?value.style??suppliedStyle:suppliedStyle);if(value instanceof Cell)
978
+ value=value.value;assertScalar(value);if(covered){if(link)
979
+ throw new TypeError("Hyperlinks cannot address a covered merged cell.");if(formula||total||(value!=null&&value!==""))
980
+ throw new TypeError("A merged range would hide the value at "+col.letter+row+"; covered cells must be empty.");value=undefined;// An empty string in a covered typed column is an empty cell, not a type mismatch.
981
+ }
982
+ const type=isDate(value)?"date":typeof value;if(!header&&!footer&&value!=null&&col.column.type&&!this.book.writerFor(col.column.type)&&col.column.type!==type)
983
+ throw new TypeError("Cell "+col.letter+row+" does not match column type "+col.column.type+".");let style=explicitStyle===undefined?header?col.headerStyle:total?.operation==="count"?0:type==="date"?col.dateStyle:col.style:this.book.styles.validateStyle(explicitStyle);if(header&&type==="date"&&explicitStyle===undefined&&this.options.headerStyle===undefined)
984
+ style=this.book.styles.dateHeader(style,col.dateStyle);if(title)
985
+ style=this.titleStyle;if(!header&&!footer){if(explicitStyle===undefined){const base=style,cached=rowStyles?.get(base);if(cached!==undefined)
986
+ style=cached;else{if((row-this.headerRows)%2===0&&this.options.alternatingRowStyle)
987
+ style=this.book.styles.compose(style,this.options.alternatingRowStyle);if(rowStyle!==undefined)
988
+ style=this.book.styles.compose(style,rowStyle);rowStyles?.set(base,style)}}
989
+ const patch=context&&this.options.cellStyle?.({...context,value:value,column:col.column,columnIndex:i});if(patch!==undefined)
990
+ style=this.book.styles.compose(style,patch)}
991
+ if(footer&&this.options.footer?.style&&explicitStyle===undefined)
992
+ style=this.book.styles.compose(style,this.options.footer.style);if(presentation&&explicitStyle===undefined)
993
+ style=this.book.styles.compose(style,{...(presentation.background===undefined?{}:{fill:{color:presentation.background}}),...(presentation.color===undefined&&presentation.bold===undefined&&presentation.italic===undefined?{}:{font:{...(presentation.color===undefined?{}:{color:presentation.color}),...(presentation.bold===undefined?{}:{bold:presentation.bold}),...(presentation.italic===undefined?{}:{italic:presentation.italic})}}),...(presentation.wrapText===undefined?{}:{wrapText:presentation.wrapText}),...(presentation.alignment===undefined?{}:{alignment:presentation.alignment}),...(presentation.numberFormat===undefined?{}:{numberFormat:presentation.numberFormat})});const originalCharacters=typeof value==="string"?value.length:0;let reservedCharacters=this.preserved||header||footer?originalCharacters:undefined;if(type==="string"&&originalCharacters>32767&&cleanXml(value,this.book.settings.invalidCharacterPolicy).length>32767){const cell=col.letter+row;if(link||this.linkedCells.has(cell))
994
+ throw new TypeError("A text-preservation cell cannot also have an external hyperlink.");checkHyperlinkCount(this.links.length+this.internalLinks.length+1);this.book.checkLinks(1);if(reservedCharacters!==undefined){this.book.budget.release(1,reservedCharacters);reservedCharacters=undefined}
995
+ const preserved=this.book.preserveText(this.name,cell,value);this.book.retainLink();this.internalLinks.push({cell,location:preserved.location});this.linkedCells.add(cell);value=preserved.preview}
996
+ if(link)
997
+ this.appendHyperlink({cell:col.letter+row,...link});if(type==="date")
998
+ value=excelDate(value,this.book.settings.dateMode);if(!header&&!footer&&visible&&(!formula||!isSubtotalFormula(formula)))
999
+ this.layout.accept(i,value);if(!header&&!footer&&this.chartSources.length)
1000
+ for(const binding of this.chartSources)
1001
+ binding.observe(row-this.headerRows-1,i+1,value);const prefix='<c r="'+col.letter+row+'" s="'+style+'"';if(formula)
1002
+ this.book.retainFormula(formula.formula.length);this.book.budget.cell(formula?formula.formula:value,reservedCharacters);if(formula)
1003
+ return prefix +(value===null?' t="str"':"")+ '>'+formulaXml(formula)+ '</c>';if(total)
1004
+ return prefix +(value===null?' t="str"':"")+ '><f>'+total.formula.replace(/"/g, "&quot;") + '</f><v>' + (value ?? "") + '</v></c>';
1005
+ if(value==null||(type==="number"&&!Number.isFinite(value)))
1006
+ return prefix+'/>';if(value==null)
1007
+ return prefix+'/>';if(type==="string")
1008
+ return prefix+' t="inlineStr"><is>'+inlineText(value,this.book.settings.invalidCharacterPolicy)+ '</is></c>';if(type==="boolean")
1009
+ return prefix+' t="b"><v>' +(value?1:0)+ '</v></c>';if(type!=="number"&&type!=="date")
1010
+ throw new TypeError("Excel cells must be strings, numbers, booleans, Dates or null.");return prefix+'><v>'+value+'</v></c>'}
1011
+ *rowXml(values,number,header,footer=false,title=false){const height=title?this.options.title?.height??28:header?this.options.headerHeight:this.options.rowHeight;const context=!header&&!footer&&(this.options.rowStyle||this.options.cellStyle||this.options.rowOutline)?Object.freeze({rowIndex:number-this.headerRows-1,worksheetRow:number,sheetName:this.name,values:Object.freeze(this.columns.map((_,i)=>values[i]instanceof FormulaCell?values[i].cachedValue:values[i]instanceof Cell||values[i]instanceof ExportCell?values[i].value:values[i]))}):undefined;const rowStyle=context&&this.options.rowStyle?.(context);if(rowStyle!==undefined)
1012
+ validateStylePatch(rowStyle);const outline=this.outline(context);const rowStyles=!header&&(rowStyle||this.options.alternatingRowStyle)?new Map():undefined;yield '<row r="'+number+'"' +(height===undefined?"":' ht="'+height+'" customHeight="1"')+
1013
+ (outline?.level?' outlineLevel="'+outline.level+'"':"")+(outline?.hidden?' hidden="1"':"")+(outline?.collapsed?' collapsed="1"':"")+ '>';for(let i=0;i<this.columns.length;i++)
1014
+ yield this.cell(values[i],i,number,header,rowStyle,context,rowStyles,footer,title,outline?.hidden!==true);yield '</row>'}
1015
+ outline(context){if(!context||!this.options.rowOutline)
1016
+ return undefined;const requested=this.options.rowOutline(context);if(requested===undefined)
1017
+ return undefined;if(requested===null||typeof requested!=="object"||Array.isArray(requested))
1018
+ throw new TypeError("Row outline callbacks must return metadata or undefined.");if(typeof requested.then==="function"){void Promise.resolve(requested).catch(()=>{});throw new TypeError("Row outline callbacks must return synchronous metadata.")}
1019
+ const{level:requestedLevel,hidden,collapsed}=requested,level=requestedLevel??0;if(!Number.isInteger(level)||level<0||level>this.options.maxOutlineLevel)
1020
+ throw new RangeError("Row outline level exceeds the declared maximum.");for(const value of[hidden,collapsed])
1021
+ if(value!==undefined&&typeof value!=="boolean")
1022
+ throw new TypeError("Row outline flags must be booleans.");return Object.freeze({level,...(hidden===undefined?{}:{hidden}),...(collapsed===undefined?{}:{collapsed})})}
1023
+ writeRow(values,number,header,footer=false,title=false){const chunks=this.rowXml(values,number,header,footer,title);const append=()=>{while(true){const next=chunks.next();if(next.done)
1024
+ return;if(this.buffer.append(next.value))
1025
+ return this.buffer.flush().then(append)}};return append()}
1026
+ async sampleRow(values){if((this.pending.length+1)*this.columns.length>(this.book.settings.limits?.maxBufferedCells??100000))
1027
+ throw new OfficeIMOError("RESOURCE_LIMIT","Width sampling cell limit exceeded; reduce sampleRows or raise its bounded limit.");const encoded=[];let chunks=0;for(const chunk of this.rowXml(values,this.count+this.headerRows+1,false)){if(!this.started&&this.pendingCharacters+chunk.length>(this.book.settings.limits?.maxBufferedCharacters??1000000)){if(this.options.autoSize?.sampleRows!==undefined)
1028
+ throw new OfficeIMOError("RESOURCE_LIMIT","Width sampling text limit exceeded; reduce sampleRows or raise its bounded limit.");this.layout.sample(values);await this.start();for(const retained of encoded)
1029
+ if(this.buffer.append(retained))
1030
+ await this.buffer.flush();encoded.length=0}
1031
+ if(this.started){if(this.buffer.append(chunk))
1032
+ await this.buffer.flush()}
1033
+ else{this.pendingCharacters +=chunk.length;encoded.push(chunk)}
1034
+ if(!this.started&&(++chunks&127)===0&&taskYieldDue()){await pause();checkAbort(this.book.settings.signal)}}
1035
+ if(!this.started){this.layout.sample(values);this.pending.push(encoded)}}
1036
+ reserveLayout(){if(this.reservedLayout)
1037
+ return;if(!this.preserved){let characters=0;if(this.options.title)
1038
+ characters +=this.options.title.text.length;if(this.layout.firstHeaderRow){for(const heading of this.layout.headings)
1039
+ for(const value of heading){const raw=value instanceof ExportCell||value instanceof Cell?value.value:value;if(typeof raw==="string")
1040
+ characters +=raw.length}}
1041
+ if(this.layout.structuredFooter){for(const row of this.layout.structuredFooter.values)
1042
+ for(const value of row){const raw=value instanceof ExportCell?value.value:value;if(typeof raw==="string")
1043
+ characters +=raw.length}}
1044
+ else if(this.options.footer)
1045
+ for(let i=0;i<this.columns.length;i++){const column=this.columns[i],totals=this.options.footer.totals;if(totals&&Object.prototype.hasOwnProperty.call(totals,column.key??column.header))
1046
+ continue;const value=this.options.footer.values?.[i],raw=value instanceof ExportCell||value instanceof Cell?value.value:value;if(typeof raw==="string")
1047
+ characters +=raw.length}
1048
+ this.book.budget.reserve(this.columns.length*(this.headerRows+this.layout.footerRows),characters)}
1049
+ this.reservedLayout=true}
1050
+ async start(){if(this.started)
1051
+ return;this.reserveLayout();this.started=true;this.entry=this.book.settings.sink?await this.book.openSheet(this):new EntryWriter(this.book.settings.compression,{write:bytes=>{this.book.retainBufferedBytes(bytes.length);this.output.write(bytes)}},this.book.settings.signal);const buffer=this.buffer=new ChunkedTextSink(this.entry,this.book.settings.signal),opts=this.options;const x=opts.freezeColumns??0,y=opts.freezeHeader?this.headerRows:0;const pane=x&&y?"bottomRight":x?"topRight":"bottomLeft",cell=columnName(x+1)+(y+1);await buffer.write(xmlDeclaration+'<worksheet xmlns="'+spreadsheetNamespace+'" xmlns:r="'+officeRelationshipsNamespace+'">' +
1052
+ (opts.print||opts.rowOutline?'<sheetPr>' +(opts.rowOutline?'<outlinePr summaryBelow="1" showOutlineSymbols="1"/>':"")+(opts.print?'<pageSetUpPr fitToPage="1"/>':"")+ '</sheetPr>':"")+ '<sheetViews><sheetView workbookViewId="0">' +
1053
+ (x||y?'<pane' +(x?' xSplit="'+x+'"':"")+(y?' ySplit="'+y+'"':"")+ ' topLeftCell="'+cell+'" activePane="'+pane+'" state="frozen"/><selection pane="'+pane+'" activeCell="'+cell+'" sqref="'+cell+'"/>':"")+ '</sheetView></sheetViews>' +
1054
+ (opts.rowOutline?'<sheetFormatPr defaultRowHeight="15" outlineLevelRow="'+opts.maxOutlineLevel+'"/>':""));const defaultWidth=opts.defaultColumnWidth??(this.table?20:undefined);if(this.columns.some((_,i)=>this.layout.widths[i]!==undefined||defaultWidth!==undefined)){await buffer.write('<cols>');for(let i=0;i<this.columns.length;i++){const width=this.layout.widths[i]??defaultWidth;if(width!==undefined)
1055
+ await buffer.write('<col min="' +(i+1)+ '" max="' +(i+1)+ '" width="'+width+'" customWidth="1"/>')}
1056
+ await buffer.write('</cols>')}
1057
+ await buffer.write('<sheetData>');if(opts.title)
1058
+ await this.writeRow(this.columns.map((_,i)=>i?"":opts.title.text),1,true,false,true);if(this.layout.firstHeaderRow){for(let i=0;i<this.layout.headings.length;i++)
1059
+ await this.writeRow(this.layout.headings[i],i+this.layout.firstHeaderRow,true)}
1060
+ for(const row of this.pending)
1061
+ for(const chunk of row)
1062
+ if(buffer.append(chunk))
1063
+ await buffer.flush();this.pending=[];this.pendingCharacters=0}
1064
+ async addRows(rows){this.book.assertOpen();if(this.completion)
1065
+ throw new OfficeIMOError("INVALID_STATE","Worksheet is closed.");if(this.busy)
1066
+ throw new OfficeIMOError("INVALID_STATE","Await the current addRows call before writing more rows to this sheet.");if(this.failed)
1067
+ throw this.error;this.busy=true;try{this.reserveLayout();if(!this.layout.sampleRows)
1068
+ await this.start();let checkpoint=performance.now();const progress=()=>{if(performance.now()- checkpoint>=50){this.progress();checkpoint=performance.now()}};const completed=()=>{this.count++;if(!this.started&&this.pending.length>=this.layout.sampleRows)
1069
+ return this.start().then(progress);if(!this.started&&taskYieldDue())
1070
+ return pause().then(()=>{checkAbort(this.book.settings.signal);progress()});progress()};await consumeRows(rows,this.book.settings.signal,row=>{if(this.count+this.headerRows+this.layout.footerRows>=1048576)
1071
+ throw new RangeError("Excel supports at most 1,048,576 rows including headers and footers; split the sheet.");this.book.budget.row(this.count+1);if(!this.columns.length)
1072
+ throw new RangeError("Declare columns before adding rows.");const values=this.project(row,this.count);const pending=!this.started?this.sampleRow(values):this.writeRow(values,this.count+this.headerRows+1,false);return pending?pending.then(completed):completed()});if(this.buffer)
1073
+ await this.buffer.flush();this.progress();checkAbort(this.book.settings.signal)}
1074
+ catch(error){this.failed=true;this.error=error;await this.book.discard(error);throw error}
1075
+ finally{this.busy=false}}
1076
+ progress(){if(!this.preserved&&!this.chartData)
1077
+ notifyProgress(this.book.settings.onProgress,{phase:"rows",rows:this.book.rowCount,sheetRows:this.reportRowCount,sheetName:this.name})}
1078
+ get rowCount(){return this.count}
1079
+ dataRange(column){if(this.failed)
1080
+ throw this.error;if(!this.completed)
1081
+ throw new OfficeIMOError("INVALID_STATE","Close the worksheet before resolving its data range.");const selected=resolveDataColumn(this.columns,column);const ranges=dataRowRanges(this);if(ranges!==undefined){if(ranges.length>1)
1082
+ throw new OfficeIMOError("INVALID_STATE","Grouped details are discontiguous; use the grouped result's detailRanges for explicit formula references.");const range=ranges[0];return range?qualifiedColumnRange(this.name,selected,range.firstRow,range.lastRow-range.firstRow+1):undefined}
1083
+ return this.count?qualifiedColumnRange(this.name,selected,this.headerRows+1,this.count):undefined}
1084
+ get chartBindingMetadata(){const leaf=this.layout.headings.at(-1);return{name:this.name,columns:this.columns,headerRows:this.headerRows,rows:this.count,closed:this.completed||!!this.completion,headerReferences:this.columns.map((column,index)=>{const cell=leaf?.[index],raw=cell instanceof ExportCell?cell.value:cell;return this.layout.firstHeaderRow&&raw===column.header&&!this.layout.regions.covered(index+1,this.headerRows)
1085
+ ?qualifiedCell(this.name,index+1,this.headerRows):undefined})}}
1086
+ retainChartBinding(binding){this.chartSources.push(binding)}
1087
+ get reportRowCount(){return this.preserved||this.chartData?0:dataRowCount(this,this.headerRows,this.count)}
1088
+ get hidden(){return this.chartData}
1089
+ addChart(chart){this.book.assertOpen();if(this.completion)
1090
+ throw new OfficeIMOError("INVALID_STATE","Worksheet is closed.");if(this.failed)
1091
+ throw this.error;this.nativeCharts.push(this.book.registerChart(chart))}
1092
+ get charts(){return this.nativeCharts}
1093
+ releaseCharts(){this.nativeCharts.length=0}
1094
+ addImage(image){this.book.assertOpen();if(this.completion)
1095
+ throw new OfficeIMOError("INVALID_STATE","Worksheet is closed.");if(this.failed)
1096
+ throw this.error;const copied=copyImage(image,this.book.settings.invalidCharacterPolicy,bytes=>this.book.checkImage(bytes));this.book.retainImage(copied.data.length);this.pictures.push(copied)}
1097
+ addHyperlink(link){this.book.assertOpen();if(this.completion)
1098
+ throw new OfficeIMOError("INVALID_STATE","Worksheet is closed.");if(this.failed)
1099
+ throw this.error;this.appendHyperlink(link)}
1100
+ appendHyperlink(link){const copied=copyHyperlink(link,this.book.settings.invalidCharacterPolicy);const position=cellPosition(copied.cell);if(this.layout.regions.covered(position.column,position.row))
1101
+ throw new TypeError("Hyperlinks cannot address a covered merged cell.");if(this.linkedCells.has(copied.cell))
1102
+ throw new TypeError("Duplicate hyperlink cell: "+copied.cell);checkHyperlinkCount(this.links.length+this.internalLinks.length+1);this.book.retainLink();this.links.push(copied);this.linkedCells.add(copied.cell)}
1103
+ get hyperlinks(){return this.links}
1104
+ get images(){return this.pictures}
1105
+ get tableDefinition(){return this.count?this.table:undefined}
1106
+ get isBusy(){return this.busy}
1107
+ get headerRowCount(){return this.headerRows}
1108
+ get firstHeaderRow(){return this.layout.firstHeaderRow}
1109
+ get mergeCount(){return this.layout.mergeCount}
1110
+ get conditionalFormatCount(){return this.conditional.count}
1111
+ get dataValidations(){return this.validations}
1112
+ get totalRows(){return Math.max(1,this.headerRows+this.count+this.layout.footerRows)}
1113
+ get lastColumn(){return columnName(Math.max(1,this.columns.length))}
1114
+ get printSettings(){return this.options.print}
1115
+ get footerSettings(){return this.layout.structuredFooter?undefined:this.options.footer}
1116
+ async close(){this.book.assertOpen();if(this.busy)
1117
+ throw new OfficeIMOError("INVALID_STATE","Await addRows before closing the worksheet.");try{await this.finish()}
1118
+ catch(error){await this.book.discard(error);throw error}}
1119
+ finish(preservedRows){if(this.completion)
1120
+ return this.completion;if(this.failed)
1121
+ throw this.error;return this.completion=(async()=>{try{const regions=this.completedRegions=this.layout.finalRegions(this.count,this.book.settings.limits?.maxMergedRanges??10000);regions.validateRows(this.totalRows);for(const binding of this.chartSources)
1122
+ binding.finish();this.chartSources.length=0;for(const link of this.links){const position=cellPosition(link.cell);if(position.column>this.columns.length||position.row>this.totalRows)
1123
+ throw new RangeError("Hyperlinks must address cells within the exported rows and columns.");if(regions.covered(position.column,position.row))
1124
+ throw new TypeError("Hyperlinks cannot address a covered merged cell.")}
1125
+ await this.start();if(preservedRows)
1126
+ for await(const row of inputRows(preservedRows,this.book.settings.signal)){this.book.budget.row(this.count+1);await this.writeRow(this.project(row,this.count),this.headerRows+this.count+1,false);this.count++}
1127
+ if(this.layout.structuredFooter){for(let index=0;index<this.layout.footerRows;index++)
1128
+ await this.writeRow(this.layout.structuredFooter.values[index],this.headerRows+this.count+index+1,false,true)}
1129
+ else if(this.options.footer)
1130
+ await this.writeRow(this.layout.footer(this.count),this.headerRows+this.count+1,false,true);await this.buffer.write('</sheetData>');if(this.options.autoFilter&&this.headerRows&&!this.tableDefinition)
1131
+ await this.buffer.write('<autoFilter ref="A'+this.headerRows+':'+columnName(this.columns.length)+(this.count+this.headerRows)+ '"/>');if(regions.references.length)
1132
+ await this.buffer.write('<mergeCells count="'+regions.references.length+'">'+regions.references.map(ref=>'<mergeCell ref="'+ref+'"/>').join("")+ '</mergeCells>');const detailRanges=dataRowRanges(this);for(const xml of this.conditional.xml(this.headerRows,this.count,this.totalRows,detailRanges))
1133
+ await this.buffer.write(xml);for(const xml of dataValidationsXml(this.validations,this.headerRows,this.count,detailRanges))
1134
+ await this.buffer.write(xml);if(this.links.length||this.internalLinks.length)
1135
+ await this.buffer.write(hyperlinksXml(this.links,this.book.settings.invalidCharacterPolicy,this.internalLinks));await this.buffer.write(printXml(this.options.print,this.book.settings.invalidCharacterPolicy));if(this.pictures.length||this.nativeCharts.length)
1136
+ await this.buffer.write('<drawing r:id="drawing"/>');if(this.tableDefinition)
1137
+ await this.buffer.write('<tableParts count="1"><tablePart r:id="table"/></tableParts>');await this.buffer.write('</worksheet>');await this.buffer.close();const info=await this.entry.close();if(!this.book.settings.sink&&!this.failed)
1138
+ this.prepared={...info,chunks:this.output.takeChunks()};this.completed=true}
1139
+ catch(error){await this.discard(error);throw error}})()}
1140
+ takePrepared(){const prepared=this.prepared;this.prepared=undefined;return prepared}
1141
+ async discard(error){this.failed=true;this.error=error;this.pending=[];this.pendingCharacters=0;this.prepared=undefined;this.buffer=undefined;this.nativeCharts.length=0;this.chartSources.length=0;this.output.discard();await this.entry?.discard(error)}}
1142
+ const _exports=Object.freeze({Worksheet:Worksheet});_modules.set("b99287e3e329b75007119103112a699c368d8237b37fa79e083b0014a21952e4",_exports);return _exports})();const _m47=_modules.get("7f1b6bb321e8055ba5269c0fe0933cf02f9a4ce269d3b8e4a64cc63d8398954a")??(()=>{const{escapeOoxmlAttribute,escapeXml,xmlDeclaration}=_m28;const{cellText,columnName}=_m35;const{spreadsheetNamespace}=_m32;const{ExportCell}=_m5;const{Cell}=_m35;const{totalFormula}=_m40;function defineTable(id,options,columns,policy){const name=options.name??"Table"+id;if(typeof name!=="string"||name.length>255||!/^[A-Za-z_][A-Za-z0-9_.]*$/.test(name) ||
1143
+ /^(?:[A-Za-z]{1,3}[1-9][0-9]*|R[1-9][0-9]*C[1-9][0-9]*|R|C)$/i.test(name))
1144
+ throw new TypeError("Table names must be ASCII identifiers, at most 255 characters, and cannot be cell references.");const style=options.style??"TableStyleMedium2",match=/^TableStyle(Light|Medium|Dark)([1-9][0-9]?)$/.exec(style);
1145
+ if(!match||Number(match[2])>({Light:21,Medium:28,Dark:11}[match[1]]??0))
1146
+ throw new TypeError("Unknown built-in Excel table style.");const headers=columns.map(column=>cellText(column.header,policy));if(!headers.length||headers.some(header=>!header.trim()||header.length>255)||new Set(headers.map(header=>header.toLowerCase())).size!==headers.length)
1147
+ throw new TypeError("Excel tables require nonblank, unique headers of at most 255 characters.");return Object.freeze({id,name,headers:Object.freeze(headers),keys:Object.freeze(columns.map(c=>c.key??c.header)),options:Object.freeze({...options,style})})}
1148
+ function tableXml(table,rowCount,policy,headerRow=1,footer){const dataRef="A"+headerRow+":"+columnName(table.headers.length)+(rowCount+headerRow),ref="A"+headerRow+":"+columnName(table.headers.length)+(rowCount+headerRow +(footer?1:0)),options=table.options;const name=escapeOoxmlAttribute(table.name,policy);return xmlDeclaration+'<table xmlns="'+spreadsheetNamespace+'" id="'+table.id+'" name="'+name+'" displayName="'+name+'" ref="'+ref+'"' +(footer?' totalsRowCount="1"':' totalsRowShown="0"')+ '>' +
1149
+ '<autoFilter ref="'+dataRef+'"/><tableColumns count="'+table.headers.length+'">' +
1150
+ table.headers.map((header,i)=>{const key=table.keys[i],operation=footer?.totals&&Object.prototype.hasOwnProperty.call(footer.totals,key)?footer.totals[key]:undefined,supplied=footer?.values?.[i],value=supplied instanceof Cell||supplied instanceof ExportCell?supplied.value:supplied;const custom=operation&&["average","min","max"].includes(operation);const attributes=operation?' totalsRowFunction="' +(custom?"custom":operation==="count"?"countNums":operation)+ '"':typeof value==="string"?' totalsRowLabel="'+escapeOoxmlAttribute(value,policy)+ '"':"";return '<tableColumn id="' +(i+1)+ '" name="'+escapeOoxmlAttribute(header,policy)+ '"'+attributes +
1151
+ (custom?'><totalsRowFormula>'+escapeXml(totalFormula(operation,columnName(i+1),headerRow,rowCount),policy)+ '</totalsRowFormula></tableColumn>':'/>')}).join("")+
1152
+ '</tableColumns><tableStyleInfo name="'+options.style+'" showFirstColumn="' +(options.firstColumn?1:0)+
1153
+ '" showLastColumn="' +(options.lastColumn?1:0)+ '" showRowStripes="' +(options.bandedRows!==false?1:0)+
1154
+ '" showColumnStripes="' +(options.bandedColumns?1:0)+ '"/></table>'}
1155
+ const _exports=Object.freeze({defineTable:defineTable,tableXml:tableXml});_modules.set("7f1b6bb321e8055ba5269c0fe0933cf02f9a4ce269d3b8e4a64cc63d8398954a",_exports);return _exports})();const _m48=_modules.get("0c395783b9d7cc62dd39a21adeb698ad4a61e2c89f7b1fc8712e2eb2ccfe9d92")??(()=>{const{OfficeIMOError}=_m2;const{cleanXml}=_m28;class TextOverflow{sheetName;maximum;policy;reserve;entries=[];characters=0;rows=0;constructor(sheetName,maximum,policy,reserve){this.sheetName=sheetName;this.maximum=maximum;this.policy=policy;this.reserve=reserve}
1156
+ add(sheet,cell,value){const text=cleanXml(value,this.policy);if(this.characters+text.length>this.maximum)
1157
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxOverflowCharacters exceeded; use CSV or raise the bounded preservation limit.");let parts=0;for(const _ of splitText(text)){void _;parts++}
1158
+ if(this.rows+parts>1048575)
1159
+ throw new OfficeIMOError("RESOURCE_LIMIT","Text overflow exceeds the worksheet row limit.");this.reserve(parts*5,text.length+parts*(sheet.length+cell.length),this.rows+parts);const first=this.rows+2;this.entries.push({sheet,cell,text,first,parts});this.rows +=parts;this.characters +=text.length;const marker="\n[Full text: "+this.sheetName+"!D"+first+"; "+parts+" parts]";return{preview:clipText(text,32767-marker.length)+ marker,location:"'"+this.sheetName.replace(/'/g, "''") + "'!D" + first };
1160
+ }
1161
+ *values(){for(const entry of this.entries){let part=0;for(const text of splitText(entry.text))
1162
+ yield[entry.sheet,entry.cell,++part,text,entry.parts]}}
1163
+ clear(){this.entries=[];this.characters=0;this.rows=0}}
1164
+ function clipText(text,maximum){let end=Math.min(maximum,text.length);if(end<text.length&&/[\ud800-\udbff]/.test(text[end - 1] ?? ""))
1165
+ end--;return text.slice(0,end)}
1166
+ function*splitText(text){let offset=0;while(offset<text.length){const part=clipText(text.slice(offset,offset+32768),32767);offset +=part.length;yield part}}
1167
+ const _exports=Object.freeze({TextOverflow:TextOverflow,clipText:clipText});_modules.set("0c395783b9d7cc62dd39a21adeb698ad4a61e2c89f7b1fc8712e2eb2ccfe9d92",_exports);return _exports})();const _m50=_modules.get("35db01801a6b2e3e0c5acd7493e56f04b5b41b1d57afa8be28b8358378ad6494")??(()=>{const{checkAbort}=_m4;const{NotSupportedError,OfficeIMOError}=_m2;const{cleanXml}=_m28;const{captureFields}=_m10;function record(value,allowed,context){if(!value||typeof value!=="object"||Array.isArray(value))
1168
+ throw new TypeError(context+" must be an object.");for(const key of Object.keys(value))
1169
+ if(!allowed.includes(key))
1170
+ throw new NotSupportedError(context+"."+key);return captureFields(value,allowed)}
1171
+ function column(value){if(typeof value==="string"?!value.length:typeof value!=="number"||!Number.isInteger(value)||value<1||value>16384)
1172
+ throw new TypeError("Chart columns require a declared key or a one-based column number.")}
1173
+ function captureChartRange(input){const value=record(input,["kind","sheet","firstRow","rowCount","categoryColumn","series"],"chart.data");if(value.kind!=="range")
1174
+ throw new TypeError("A chart range must declare kind: range.");if(!value.sheet||typeof value.sheet!=="object"||Array.isArray(value.sheet))
1175
+ throw new TypeError("A chart range needs its owning worksheet.");const firstRow=value.firstRow===undefined?0:value.firstRow,rowCount=value.rowCount;if(!Number.isSafeInteger(firstRow)||firstRow<0||!Number.isSafeInteger(rowCount)||rowCount<1||
1176
+ firstRow+rowCount>1048576)
1177
+ throw new RangeError("Chart data rows must form a nonempty finite Excel range.");column(value.categoryColumn);if(!Array.isArray(value.series)||value.series.length<1||value.series.length>255)
1178
+ throw new RangeError("A chart needs from 1 through 255 series.");const series=value.series.map(item=>{const copy=record(item,["column","name","color"],"chart.data.series");column(copy.column);if(copy.name!==undefined&&typeof copy.name!=="string")
1179
+ throw new TypeError("Chart series name must be a string.");if(copy.color!==undefined&&(typeof copy.color!=="string"||!/^#?[0-9a-fA-F]{6}$/.test(copy.color)))
1180
+ throw new TypeError("Chart colors must be opaque six-digit RGB hex values.");return Object.freeze(copy)});return Object.freeze({kind:"range",sheet:value.sheet,firstRow,rowCount,categoryColumn:value.categoryColumn,series:Object.freeze(series)})}
1181
+ function prepareChartBinding(input,descriptor,budgets,signal,type="columnClustered"){checkAbort(signal);const count=input.rowCount,first=input.firstRow??0,points=count*input.series.length,categoryColumn=descriptor.categoryColumn;if(points>budgets.availablePoints)
1182
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxChartPoints exceeded.");if(descriptor.source!==input.sheet||!Number.isInteger(descriptor.headerRows)||descriptor.headerRows<0||descriptor.headerRows+first+count>1048576||
1183
+ descriptor.seriesColumns.length!==input.series.length||descriptor.seriesNames.length!==input.series.length||
1184
+ descriptor.valueFormulas.length!==input.series.length||descriptor.nameFormulas.length!==input.series.length)
1185
+ throw new TypeError("Resolved chart range does not match its declared columns and data rows.");for(const index of[descriptor.categoryColumn,...descriptor.seriesColumns])
1186
+ if(!Number.isInteger(index)||index<1||index>16384)
1187
+ throw new RangeError("Resolved chart columns must be one-based Excel columns.");if(descriptor.seriesColumns.includes(categoryColumn))
1188
+ throw new TypeError("Chart category and numeric series must use different columns.");let textCharacters=0;const names=input.series.map((series,i)=>{const name=series.name??descriptor.seriesNames[i];if(typeof name!=="string"||name.length>32767)
1189
+ throw new TypeError("Chart series names must fit Excel text cells.");textCharacters +=name.length;if(textCharacters>budgets.availableText)
1190
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxChartTextCharacters exceeded.");return cleanXml(name,budgets.policy)});const colors=input.series.map(series=>series.color?.replace(/^#/, "").toUpperCase());
1191
+ const categories=new Array(count),values=input.series.map(()=>new Array(count));const captured=input.series.map(()=>0),positive=input.series.map(()=>false);let categoryCount=0,completed;const finish=()=>{checkAbort(signal);if(completed)
1192
+ return;if(categoryCount!==count||captured.some(value=>value!==count))
1193
+ throw new TypeError("Chart range did not receive every declared data row and numeric value.");if(type==="pie"&&!positive[0])
1194
+ throw new RangeError("A pie chart needs at least one positive value.");completed=Object.freeze({categories:Object.freeze(categories),series:Object.freeze(values.map((points,i)=>Object.freeze({name:names[i],values:Object.freeze(points),...(colors[i]===undefined?{}:{color:colors[i]})})))})};const data=Object.freeze({get categories(){finish();return completed.categories},get series(){finish();return completed.series}});const seriesByColumn=new Map();descriptor.seriesColumns.forEach((index,i)=>{const indexes=seriesByColumn.get(index)??[];indexes.push(i);seriesByColumn.set(index,indexes)});return Object.freeze({source:descriptor.source,points,textCharacters,data,references:Object.freeze({categories:descriptor.categoryFormula,values:Object.freeze([...descriptor.valueFormulas]),names:Object.freeze(descriptor.nameFormulas.map((formula,i)=>input.series[i].name===undefined?formula:undefined))}),observe(dataRowIndex,columnIndex,value){checkAbort(signal);const position=dataRowIndex-first;if(position<0||position>=count)
1195
+ return;if(completed)
1196
+ throw new OfficeIMOError("INVALID_STATE","Chart cache is already finalized.");if(columnIndex===categoryColumn){if(typeof value!=="string"||value.length>32767)
1197
+ throw new TypeError("Chart category cells must contain strings of at most 32,767 UTF-16 units.");if(categories[position]!==undefined)
1198
+ throw new OfficeIMOError("INVALID_STATE","A chart category cell was observed more than once.");budgets.retainText(value.length);categories[position]=cleanXml(value,budgets.policy);categoryCount++}
1199
+ for(const i of seriesByColumn.get(columnIndex)??[]){if(typeof value!=="number"||!Number.isFinite(value))
1200
+ throw new TypeError("Chart series cells require finite numbers or numeric formula caches.");if(type==="pie"&&value<0)
1201
+ throw new RangeError("Pie charts require nonnegative values.");if(values[i][position]!==undefined)
1202
+ throw new OfficeIMOError("INVALID_STATE","A chart value cell was observed more than once.");values[i][position]=value;captured[i]=captured[i]+ 1;if(value>0)
1203
+ positive[i]=true}},finish})}
1204
+ const _exports=Object.freeze({captureChartRange:captureChartRange,prepareChartBinding:prepareChartBinding});_modules.set("35db01801a6b2e3e0c5acd7493e56f04b5b41b1d57afa8be28b8358378ad6494",_exports);return _exports})();const _m49=_modules.get("6ff482aba6cf0b524cf20f6a4f8af16b842a49f36448b14e73beaf838885d219")??(()=>{const{checkAbort}=_m4;const{NotSupportedError,OfficeIMOError}=_m2;const{cleanXml}=_m28;const{copyDrawingAnchor}=_m38;const{captureFields}=_m10;const{captureChartRange,prepareChartBinding}=_m50;function fields(value,allowed,context){if(!value||typeof value!=="object"||Array.isArray(value))
1205
+ throw new TypeError(context+" must be an object.");for(const key of Object.keys(value))
1206
+ if(!allowed.includes(key))
1207
+ throw new NotSupportedError(context+"."+key)}
1208
+ function snapshot(value,allowed,context){fields(value,allowed,context);return captureFields(value,allowed)}
1209
+ function prepareChart(input,policy,availablePoints,availableText,signal,resolveBinding){checkAbort(signal);input=snapshot(input,["type","data","row","column","width","height","description","title","language","legend","dataLabels","categoryAxis","valueAxis"],"chart");if(!["columnClustered","barClustered","line","pie"].includes(input.type))
1210
+ throw new NotSupportedError("chart type "+input.type);const type=input.type;const requested=snapshot(input.data,["kind","sheet","firstRow","rowCount","categoryColumn","categories","series"],"chart.data");const bound=requested.kind==="range"?captureChartRange(requested):undefined;if(!bound)
1211
+ fields(requested,["categories","series"],"chart.data");const categories=bound?undefined:requested.categories,series=bound?.series??requested.series;if(!bound&&!Array.isArray(categories))
1212
+ throw new TypeError("Chart categories must be a nonempty array of strings.");if(!Array.isArray(series))
1213
+ throw new RangeError("A chart needs from 1 through 255 series.");const categoryCount=bound?.rowCount??categories.length,seriesCount=series.length;if(!categoryCount)
1214
+ throw new TypeError("Chart categories must be a nonempty array of strings.");if(!seriesCount||seriesCount>255)
1215
+ throw new RangeError("A chart needs from 1 through 255 series.");if(!bound&&categoryCount>1048575)
1216
+ throw new RangeError("Chart data must fit Excel's rows including its header.");if(type==="pie"&&seriesCount!==1)
1217
+ throw new TypeError("A pie chart supports exactly one series.");const points=categoryCount*seriesCount;if(points>availablePoints)
1218
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxChartPoints exceeded.");let textCharacters=0;const text=(value,context)=>{if(typeof value!=="string")
1219
+ throw new TypeError(context+" must be a string.");if(value.length>32767)
1220
+ throw new RangeError(context+" exceeds 32,767 UTF-16 units.");textCharacters +=value.length;if(textCharacters>availableText)
1221
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxChartTextCharacters exceeded.");return cleanXml(value,policy)};const optionalText=(value,context)=>value===undefined?undefined:text(value,context);const title=optionalText(input.title,"Chart title"),description=optionalText(input.description,"Chart description");const requestedLanguage=optionalText(input.language,"Chart language");let language;if(requestedLanguage!==undefined){try{language=Intl.getCanonicalLocales(requestedLanguage)[0];if(!language)
1222
+ throw new RangeError()}
1223
+ catch{throw new TypeError("Chart language must be a language tag such as pl or pl-PL.")}}
1224
+ const anchor=copyDrawingAnchor({row:input.row,column:input.column,width:input.width,height:input.height,...(description===undefined?{}:{description})},policy);if(input.legend!==undefined&&input.legend!==false&&!["right","bottom","left","top"].includes(input.legend))
1225
+ throw new TypeError("Unsupported chart legend position.");let dataLabels;if(input.dataLabels!==undefined){const labels=snapshot(input.dataLabels,["showValue","showCategoryName","showSeriesName","showPercent","position","numberFormat"],"chart.dataLabels");for(const key of["showValue","showCategoryName","showSeriesName","showPercent"])
1226
+ if(labels[key]!==undefined&&typeof labels[key]!=="boolean")
1227
+ throw new TypeError("Chart label flags must be booleans.");if(labels.showPercent&&type!=="pie")
1228
+ throw new TypeError("Percent data labels require a pie chart.");const positions=type==="pie"?["center","insideEnd","outsideEnd","bestFit"]:type==="line"?["center","above","below","left","right"]:["center","insideEnd","outsideEnd"];if(labels.position!==undefined&&!positions.includes(labels.position))
1229
+ throw new TypeError("Data label position is unsupported for this chart type.");const numberFormat=optionalText(labels.numberFormat,"Data label number format");if(numberFormat!==undefined&&!numberFormat.trim())
1230
+ throw new TypeError("Data label number format cannot be blank.");dataLabels=Object.freeze({...labels,...(numberFormat===undefined?{}:{numberFormat})})}
1231
+ if(type==="pie"&&(input.categoryAxis!==undefined||input.valueAxis!==undefined))
1232
+ throw new TypeError("Pie charts have no axes.");let categoryAxis,valueAxis;if(input.categoryAxis!==undefined){const axisTitle=optionalText(snapshot(input.categoryAxis,["title"],"chart.categoryAxis").title,"Category axis title");categoryAxis=Object.freeze(axisTitle===undefined?{}:{title:axisTitle})}
1233
+ if(input.valueAxis!==undefined){const axis=snapshot(input.valueAxis,["title","minimum","maximum","numberFormat"],"chart.valueAxis");for(const value of[axis.minimum,axis.maximum])
1234
+ if(value!==undefined&&!Number.isFinite(value))
1235
+ throw new TypeError("Chart axis bounds must be finite numbers.");if(axis.minimum!==undefined&&axis.maximum!==undefined&&axis.minimum>=axis.maximum)
1236
+ throw new RangeError("Chart axis minimum must be below its maximum.");const axisTitle=optionalText(axis.title,"Value axis title"),numberFormat=optionalText(axis.numberFormat,"Value axis number format");if(numberFormat!==undefined&&!numberFormat.trim())
1237
+ throw new TypeError("Value axis number format cannot be blank.");valueAxis=Object.freeze({...axis,...(axisTitle===undefined?{}:{title:axisTitle}),...(numberFormat===undefined?{}:{numberFormat})})}
1238
+ const common={...anchor,type,...(language===undefined?{}:{language}),...(title===undefined?{}:{title}),...(description===undefined?{}:{description}),...(input.legend===undefined?{}:{legend:input.legend}),...(dataLabels===undefined?{}:{dataLabels}),...(categoryAxis===undefined?{}:{categoryAxis}),...(valueAxis===undefined?{}:{valueAxis})};if(bound){if(!resolveBinding)
1239
+ throw new TypeError("A chart range must belong to the current workbook.");const{descriptor,retainText}=resolveBinding(bound);const binding=prepareChartBinding(bound,descriptor,{availablePoints,availableText:availableText-textCharacters,retainText,policy},signal,type);return Object.freeze({...common,data:binding.data,binding,points,textCharacters:textCharacters+binding.textCharacters})}
1240
+ const categoryValues=categories;const copiedCategories=[],copiedSeries=[];for(let i=0;i<categoryCount;i++){if((i&255)===0)
1241
+ checkAbort(signal);copiedCategories.push(text(categoryValues[i],"Chart category"))}
1242
+ for(let seriesIndex=0;seriesIndex<seriesCount;seriesIndex++){const item=series[seriesIndex];const captured=snapshot(item,["name","values","color"],"chart.series");const name=text(captured.name,"Chart series name"),values=captured.values,color=captured.color;if(!Array.isArray(values)||values.length!==categoryCount)
1243
+ throw new TypeError("Chart series values must match the category count.");if(color!==undefined&&(typeof color!=="string"||!/^#?[0-9a-fA-F]{6}$/.test(color)))
1244
+ throw new TypeError("Chart colors must be opaque six-digit RGB hex values.");let positive=false;const copiedValues=[];for(let i=0;i<categoryCount;i++){if((i&255)===0)
1245
+ checkAbort(signal);const value=values[i];if(typeof value!=="number"||!Number.isFinite(value))
1246
+ throw new TypeError("Chart values must be finite numbers.");if(type==="pie"&&value<0)
1247
+ throw new RangeError("Pie charts require nonnegative values.");if(value>0)
1248
+ positive=true;copiedValues.push(value)}
1249
+ if(type==="pie"&&!positive)
1250
+ throw new RangeError("A pie chart needs at least one positive value.");copiedSeries.push(Object.freeze({name,values:Object.freeze(copiedValues),...(color===undefined?{}:{color:color.replace(/^#/, "").toUpperCase() }) }));
1251
+ }
1252
+ return Object.freeze({...common,data:Object.freeze({categories:Object.freeze(copiedCategories),series:Object.freeze(copiedSeries)}),points,textCharacters})}
1253
+ const _exports=Object.freeze({prepareChart:prepareChart});_modules.set("6ff482aba6cf0b524cf20f6a4f8af16b842a49f36448b14e73beaf838885d219",_exports);return _exports})();const _m24=_modules.get("0f11efc0d52501e827898643b33f7fa42365115a892aa801634ecea3f3603681")??(()=>{const{beginTask,checkAbort,pause,taskYieldDue}=_m4;const{OfficeIMOError}=_m2;const{notifyProgress}=_m14;const{ChunkedTextSink}=_m3;const{ExportBudget}=_m9;const{OpcPackage,officeRelationshipsNamespace,relationshipTypes,corePropertiesXml}=_m25;const{escapeOoxmlAttribute,cleanXml,xmlDeclaration}=_m28;const{StyleRegistry,spreadsheetNamespace}=_m32;const{sheetName,assertXlsxValue,copyValue}=_m35;const{copyColumns}=_m11;const{captureFields}=_m10;const{captureTableSpans}=_m18;const{assertExportValue}=_m5;const{Worksheet}=_m37;const{defineTable,tableXml}=_m47;const{copyHyperlink,drawingXml,drawingContentType}=_m38;const{TextOverflow}=_m48;const{captureWorkbookOptions,sheetOptionFields}=_m22;const{prepareChart}=_m49;const{qualifiedColumnRange,resolveDataColumn}=_m44;const{chartContentType,writeChartXml}=_m39;const xlsxMime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";const formatType=(name)=>"application/vnd.openxmlformats-officedocument.spreadsheetml."+name+"+xml";function captureSheet(options,policy){const captured=captureFields(options,sheetOptionFields);const columns=copyColumns(captured.columns??[],true);const footer=captured.footer&&captureFields(captured.footer,["rows","values","totals","style"]);const print=captured.print&&captureFields(captured.print,["paper","orientation","fitToWidth","fitToHeight","repeatHeaders","margins","header","footer"]);return{...captured,columns,...(captured.headerRows===undefined?{}:{headerRows:captureTableSpans(captured.headerRows,columns.length)}),...(footer?{footer:{...footer,...(footer.rows===undefined?{}:{rows:captureTableSpans(footer.rows,columns.length)}),...(footer.values===undefined?{}:{values:footer.values.map(copyValue)})}}:{}),...(captured.table?{table:captureFields(captured.table,["name","style","bandedRows","bandedColumns","firstColumn","lastColumn"])}:{}),...(captured.autoSize?{autoSize:captureFields(captured.autoSize,["sampleRows","minWidth","maxWidth"])}:{}),...(captured.title?{title:captureFields(captured.title,["text","style","height"])}:{}),...(print?{print:{...print,...(print.margins===undefined?{}:{margins:captureFields(print.margins,["left","right","top","bottom","header","footer"])})}}:{}),...(captured.hyperlinks?{hyperlinks:captured.hyperlinks.map(link=>copyHyperlink(link,policy))}:{})}}
1254
+ class Workbook{portableValues=false;static forTable(options){const book=new Workbook(options);book.portableValues=true;return book}
1255
+ get valueValidator(){return this.portableValues?assertExportValue:assertXlsxValue}
1256
+ styles;names=new Set();sheets=[];tableNames=new Set();tableCount=0;writers;package;state="open";result;completion;activeSheet;failure;overflow;links=0;imageBytes=0;bufferedBytes=0;mergedRanges=0;conditionalFormats=0;dataValidationCount=0;validationTextCharacters=0;formulaCharacters=0;hasAuthoredFormulas=false;nativeCharts=[];chartSourceSheets=0;chartPoints=0;chartTextCharacters=0;registering=false;registration(action){this.assertOpen();if(this.registering)
1257
+ throw new OfficeIMOError("INVALID_STATE","Workbook registrations cannot be reentered from input getters.");this.registering=true;try{return action()}
1258
+ finally{this.registering=false}}
1259
+ budget;settings;constructor(options={}){options=captureWorkbookOptions(options);const dateMode=options.dateMode??"local",compression=options.compression??"auto",policy=options.invalidCharacterPolicy??"strip";if(dateMode!=="local"&&dateMode!=="utc")
1260
+ throw new RangeError("dateMode must be local or utc.");if(compression!=="auto"&&compression!=="store")
1261
+ throw new RangeError("compression must be auto or store.");if(options.oversizedText!==undefined&&!["reject","preserve"].includes(options.oversizedText))
1262
+ throw new RangeError("oversizedText must be reject or preserve.");cleanXml("",policy);corePropertiesXml(options,policy);this.budget=new ExportBudget(options.limits);this.styles=new StyleRegistry(policy,options.limits?.maxStyles,options.limits?.maxDifferentialStyles);if(options.sink!==undefined&&typeof options.sink.write!=="function")
1263
+ throw new TypeError("sink must be a ByteSink.");this.settings=Object.freeze({...options,...(options.limits?{limits:Object.freeze({...options.limits})}:{}),dateMode,compression,invalidCharacterPolicy:policy});this.writers=Object.freeze({...options.cellValueWriters});for(const writer of Object.values(this.writers))
1264
+ if(typeof writer!=="function")
1265
+ throw new TypeError("Cell value writers must be functions.");beginTask();this.package=new OpcPackage({compression,invalidCharacterPolicy:policy,...(options.signal?{signal:options.signal}:{}),...(options.sink?{sink:options.sink}:{}),...(options.limits?.maxOutputBytes===undefined?{}:{maxOutputBytes:options.limits.maxOutputBytes})});this.package.setProperties(options,options.appProperties);this.addXmlPart("/xl/workbook.xml",formatType("sheet.main"),()=>this.workbookXml());this.addXmlPart("/xl/styles.xml",formatType("styles"),()=>this.styles.toXml())}
1266
+ addXmlPart(uri,contentType,xml){this.package.addPart({uri,contentType,data:async(sink)=>{const text=new ChunkedTextSink(sink,this.settings.signal);await text.write(xml());await text.close()}})}
1267
+ workbookXml(){return xmlDeclaration+'<workbook xmlns="'+spreadsheetNamespace+'" xmlns:r="'+officeRelationshipsNamespace+'"><workbookPr date1904="0"/><bookViews><workbookView/></bookViews><sheets>' +
1268
+ this.sheets.map((s,i)=>'<sheet name="'+escapeOoxmlAttribute(s.name,this.settings.invalidCharacterPolicy)+ '" sheetId="' +(i+1)+ '"' +(s.hidden?' state="hidden"':"")+ ' r:id="rId' +(i+1)+ '"/>').join("")+ '</sheets>' +
1269
+ (this.sheets.some(s=>s.printSettings)?'<definedNames>'+this.sheets.map((s,i)=>{const quoted="'"+s.name.replace(/'/g, "''") + "'!";
1270
+ return s.printSettings?'<definedName name="_xlnm.Print_Area" localSheetId="'+i+'">'+escapeOoxmlAttribute(quoted+'$A$1:$'+s.lastColumn+'$'+s.totalRows,this.settings.invalidCharacterPolicy)+ '</definedName>' +
1271
+ (s.printSettings.repeatHeaders&&s.firstHeaderRow?'<definedName name="_xlnm.Print_Titles" localSheetId="'+i+'">'+escapeOoxmlAttribute(quoted+'$'+s.firstHeaderRow+':$'+s.headerRowCount,this.settings.invalidCharacterPolicy)+ '</definedName>':""):""}).join("")+ '</definedNames>':"")+(this.hasAuthoredFormulas?'<calcPr calcMode="auto" fullCalcOnLoad="1" forceFullCalc="1"/>':"")+ '</workbook>'}
1272
+ assertOpen(){try{checkAbort(this.settings.signal)}
1273
+ catch(error){void this.discard(error).catch(()=>{});throw error}
1274
+ if(this.state==="failed")
1275
+ throw this.failure;if(this.state!=="open")
1276
+ throw new OfficeIMOError("INVALID_STATE","Workbook is already finalized.")}
1277
+ writerFor(type){return Object.prototype.hasOwnProperty.call(this.writers,type)?this.writers[type]:undefined}
1278
+ preserveText(sheet,cell,text){if(this.settings.oversizedText!=="preserve")
1279
+ throw new RangeError("Excel cell text exceeds 32,767 UTF-16 code units.");if(!this.overflow){this.checkSheetLimit(this.sheets.length+this.chartSourceSheets+1);this.budget.reserve(5,"SheetCellPartTextParts".length);this.overflow=new TextOverflow(sheetName("Text overflow",this.names,this.settings.invalidCharacterPolicy),this.settings.limits?.maxOverflowCharacters??4000000,this.settings.invalidCharacterPolicy,(cells,characters,rows)=>{this.budget.row(rows);this.budget.reserve(cells,characters)})}
1280
+ return this.overflow.add(sheet,cell,text)}
1281
+ checkSheetLimit(count){if(count>65526)
1282
+ throw new RangeError("Workbook has too many sheets.");if(this.settings.limits?.maxSheets!==undefined&&count>this.settings.limits.maxSheets)
1283
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxSheets exceeded.")}
1284
+ checkLinks(count){if(this.settings.limits?.maxHyperlinks!==undefined&&this.links+count>this.settings.limits.maxHyperlinks)
1285
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxHyperlinks exceeded.")}
1286
+ retainLink(count=1){this.checkLinks(count);this.links +=count}
1287
+ checkImage(bytes){if(this.settings.limits?.maxImageBytes!==undefined&&this.imageBytes+bytes>this.settings.limits.maxImageBytes)
1288
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxImageBytes exceeded.")}
1289
+ retainImage(bytes){this.checkImage(bytes);this.imageBytes +=bytes}
1290
+ retainBufferedBytes(bytes){this.budget.check("maxOutputBytes",this.bufferedBytes+bytes);this.bufferedBytes +=bytes}
1291
+ checkMerges(count){if(this.mergedRanges+count>(this.settings.limits?.maxMergedRanges??10000))
1292
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxMergedRanges exceeded.")}
1293
+ checkConditionalFormats(count){if(this.conditionalFormats+count>(this.settings.limits?.maxConditionalFormats??1000))
1294
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxConditionalFormats exceeded.")}
1295
+ get availableDataValidations(){return(this.settings.limits?.maxDataValidations??1000)- this.dataValidationCount}
1296
+ get availableValidationTextCharacters(){return(this.settings.limits?.maxValidationTextCharacters??1000000)- this.validationTextCharacters}
1297
+ retainFormula(characters){if(this.formulaCharacters+characters>(this.settings.limits?.maxFormulaCharacters??1000000))
1298
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxFormulaCharacters exceeded.");this.formulaCharacters +=characters;this.hasAuthoredFormulas=true}
1299
+ checkChartText(characters){if(this.chartTextCharacters+characters>(this.settings.limits?.maxChartTextCharacters??1000000))
1300
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxChartTextCharacters exceeded.")}
1301
+ retainChartText(characters){this.checkChartText(characters);this.chartTextCharacters +=characters}
1302
+ resolveChartBinding(input){const source=input.sheet;if(!this.sheets.includes(source)||source.hidden)
1303
+ throw new TypeError("Bound charts require a visible worksheet in the same workbook.");const metadata=source.chartBindingMetadata,first=input.firstRow??0;if(source.isBusy||metadata.closed||first<metadata.rows)
1304
+ throw new OfficeIMOError("INVALID_STATE","Register a chart before its first selected data row is written, while the source worksheet is idle.");const category=resolveDataColumn(metadata.columns,input.categoryColumn,"Chart");const series=input.series.map(item=>resolveDataColumn(metadata.columns,item.column,"Chart"));const start=metadata.headerRows+first+1;return{descriptor:{source,sheetName:metadata.name,headerRows:metadata.headerRows,categoryColumn:category,seriesColumns:series,seriesNames:series.map(column=>metadata.columns[column-1].header),categoryFormula:qualifiedColumnRange(metadata.name,category,start,input.rowCount),valueFormulas:series.map(column=>qualifiedColumnRange(metadata.name,column,start,input.rowCount)),nameFormulas:series.map((column,index)=>input.series[index].name===undefined
1305
+ ?metadata.headerReferences[column-1]:undefined)},retainText:characters=>this.retainChartText(characters)}}
1306
+ registerChart(input){return this.registration(()=>{if(this.nativeCharts.length>=(this.settings.limits?.maxCharts??100))
1307
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxCharts exceeded.");const chart=prepareChart(input,this.settings.invalidCharacterPolicy,(this.settings.limits?.maxChartPoints??100000)- this.chartPoints,(this.settings.limits?.maxChartTextCharacters??1000000)- this.chartTextCharacters,this.settings.signal,value=>this.resolveChartBinding(value));this.assertOpen();this.checkChartText(chart.textCharacters);this.checkSheetLimit(this.sheets.length+this.chartSourceSheets +(chart.binding?0:1)+(this.overflow?1:0));const registered=Object.freeze({...chart,id:this.nativeCharts.length+1,dataSheetName:chart.binding?chart.binding.source.name:sheetName("Chart data " +(this.nativeCharts.length+1),this.names,this.settings.invalidCharacterPolicy)});this.nativeCharts.push(registered);this.chartPoints +=chart.points;this.chartTextCharacters +=chart.textCharacters;if(chart.binding)
1308
+ chart.binding.source.retainChartBinding(chart.binding);else
1309
+ this.chartSourceSheets++;return registered})}
1310
+ async openSheet(sheet){if(this.activeSheet&&this.activeSheet!==sheet){if(this.activeSheet.isBusy)
1311
+ throw new OfficeIMOError("INVALID_STATE","Await the active streamed worksheet before starting another.");await this.activeSheet.finish()}
1312
+ this.activeSheet=sheet;return this.package.openPart("/xl/worksheets/sheet" +(this.sheets.indexOf(sheet)+ 1)+ ".xml",formatType("worksheet"))}
1313
+ async discard(error){this.state="failed";this.failure=error;await Promise.allSettled(this.sheets.map(sheet=>sheet.discard(error)));await this.package.discard(error);this.overflow?.clear();this.nativeCharts.length=0}
1314
+ get worksheets(){return Object.freeze([...this.sheets])}
1315
+ get rowCount(){return this.sheets.reduce((sum,sheet)=>sum+sheet.reportRowCount,0)}
1316
+ addWorksheet(name,options={}){return this.registration(()=>{this.checkSheetLimit(this.sheets.length+this.chartSourceSheets+1 +(this.overflow?1:0));const metadata=captureSheet(options,this.settings.invalidCharacterPolicy);const prepared=Worksheet.validate(this,metadata);let tableOptions=metadata.table;if(tableOptions&&tableOptions.name===undefined){let suffix=this.tableCount+1;while(this.tableNames.has(("Table"+suffix).toLowerCase()))
1317
+ suffix++;tableOptions={...tableOptions,name:"Table"+suffix}}
1318
+ const table=tableOptions?defineTable(this.tableCount+1,tableOptions,metadata.columns??[],this.settings.invalidCharacterPolicy):undefined;if(table&&this.tableNames.has(table.name.toLowerCase()))
1319
+ throw new TypeError("Duplicate Excel table name: "+table.name);sheetName(name,this.names,this.settings.invalidCharacterPolicy,false);const sheet=Worksheet.create(this,()=>sheetName(name,this.names,this.settings.invalidCharacterPolicy,false),metadata,table,false,prepared.conditional,prepared.validations);this.assertOpen();this.checkSheetLimit(this.sheets.length+this.chartSourceSheets+1 +(this.overflow?1:0));this.names.add(sheet.name.toLowerCase());this.mergedRanges +=sheet.mergeCount;this.conditionalFormats +=sheet.conditionalFormatCount;this.dataValidationCount +=sheet.dataValidations.count;this.validationTextCharacters +=sheet.dataValidations.textCharacters;if(table){this.tableNames.add(table.name.toLowerCase());this.tableCount++}
1320
+ this.sheets.push(sheet);return sheet})}
1321
+ addPart(part){this.assertOpen();const{uri,contentType,data,relationship}=part;const capturedRelationship=relationship&&{id:relationship.id,type:relationship.type,source:relationship.source};this.assertOpen();this.package.addPart({uri,contentType,data});if(capturedRelationship){const{source,id,type}=capturedRelationship;this.package.addRelationship(source??"/xl/workbook.xml",{id,type,target:uri})}}
1322
+ finish(){try{checkAbort(this.settings.signal)}
1323
+ catch(error){return this.discard(error).then(()=>{throw error})}
1324
+ if(this.completion)
1325
+ return this.completion;if(this.state==="failed")
1326
+ return Promise.reject(this.failure);this.assertOpen();if(this.sheets.some(s=>s.isBusy))
1327
+ throw new OfficeIMOError("INVALID_STATE","Await addRows before finalizing the workbook.");if(!this.sheets.length)
1328
+ this.addWorksheet("Sheet1");this.state="finalizing";this.completion=(async()=>{try{const rows=this.rowCount;for(let i=0;i<this.sheets.length;i++){const sheet=this.sheets[i],uri="/xl/worksheets/sheet" +(i+1)+ ".xml";await sheet.finish();const prepared=sheet.takePrepared();if(prepared)
1329
+ this.package.addPrepared(uri,formatType("worksheet"),prepared);const table=sheet.tableDefinition;if(table){const tableUri="/xl/tables/table"+table.id+".xml";this.addXmlPart(tableUri,formatType("table"),()=>tableXml(table,sheet.rowCount,this.settings.invalidCharacterPolicy,sheet.headerRowCount,sheet.footerSettings));this.package.addRelationship(uri,{id:"table",type:officeRelationshipsNamespace+"/table",target:tableUri})}
1330
+ for(let j=0;j<sheet.hyperlinks.length;j++){checkAbort(this.settings.signal);this.package.addRelationship(uri,{id:"link" +(j+1),type:officeRelationshipsNamespace+"/hyperlink",target:sheet.hyperlinks[j].target,external:true});if((j&255)===255&&taskYieldDue()){await pause();checkAbort(this.settings.signal)}}
1331
+ if(sheet.images.length||sheet.charts.length){const drawingUri="/xl/drawings/drawing" +(i+1)+ ".xml";this.addXmlPart(drawingUri,drawingContentType,()=>drawingXml(sheet.images,this.settings.invalidCharacterPolicy,sheet.charts));this.package.addRelationship(uri,{id:"drawing",type:officeRelationshipsNamespace+"/drawing",target:drawingUri});for(let j=0;j<sheet.images.length;j++){checkAbort(this.settings.signal);const imageUri="/xl/media/sheet" +(i+1)+ "-image" +(j+1)+ ".png";this.package.addPart({uri:imageUri,contentType:"image/png",data:sheet.images[j].data});this.package.addRelationship(drawingUri,{id:"image" +(j+1),type:officeRelationshipsNamespace+"/image",target:imageUri});if((j&255)===255&&taskYieldDue()){await pause();checkAbort(this.settings.signal)}}
1332
+ for(const chart of sheet.charts){checkAbort(this.settings.signal);const chartUri="/xl/charts/chart"+chart.id+".xml";this.package.addPart({uri:chartUri,contentType:chartContentType,data:sink=>writeChartXml(chart,sink,this.settings.invalidCharacterPolicy,this.settings.signal)});this.package.addRelationship(drawingUri,{id:"chart"+chart.id,type:officeRelationshipsNamespace+"/chart",target:chartUri})}}}
1333
+ if(this.overflow){const sheet=Worksheet.create(this,this.overflow.sheetName,{columns:[{header:"Sheet"},{header:"Cell"},{header:"Part"},{header:"Text",width:80,wrapText:true},{header:"Parts"}],freezeHeader:true},undefined,true);this.sheets.push(sheet);await sheet.finish(this.overflow.values());const prepared=sheet.takePrepared();if(prepared)
1334
+ this.package.addPrepared("/xl/worksheets/sheet"+this.sheets.length+".xml",formatType("worksheet"),prepared);this.overflow.clear()}
1335
+ for(const chart of this.nativeCharts){checkAbort(this.settings.signal);if(chart.binding)
1336
+ continue;const sheet=Worksheet.createChartData(this,chart);this.sheets.push(sheet);function*rows(){for(let i=0;i<chart.data.categories.length;i++)
1337
+ yield[chart.data.categories[i],...chart.data.series.map(series=>series.values[i])]}
1338
+ await sheet.finish(rows());const prepared=sheet.takePrepared();if(prepared)
1339
+ this.package.addPrepared("/xl/worksheets/sheet"+this.sheets.length+".xml",formatType("worksheet"),prepared)}
1340
+ this.package.addRelationship("/",{id:"workbook",type:relationshipTypes.officeDocument,target:"/xl/workbook.xml"});for(let i=0;i<this.sheets.length;i++){checkAbort(this.settings.signal);this.package.addRelationship("/xl/workbook.xml",{id:"rId" +(i+1),type:relationshipTypes.worksheet,target:"/xl/worksheets/sheet" +(i+1)+ ".xml"});if((i&255)===255&&taskYieldDue()){await pause();checkAbort(this.settings.signal)}}
1341
+ this.package.addRelationship("/xl/workbook.xml",{id:"styles",type:relationshipTypes.styles,target:"/xl/styles.xml"});const bytes=await this.package.finish();for(const sheet of this.sheets)
1342
+ sheet.releaseCharts();this.nativeCharts.length=0;notifyProgress(this.settings.onProgress,{phase:"complete",rows,bytes});checkAbort(this.settings.signal);this.state="complete";return{rows,sheets:this.sheets.length,bytes}}
1343
+ catch(error){await this.discard(error);throw error}})();return this.completion}
1344
+ toBlob(){try{checkAbort(this.settings.signal)}
1345
+ catch(error){return this.discard(error).then(()=>{throw error})}
1346
+ if(this.settings.sink)
1347
+ throw new OfficeIMOError("INVALID_STATE","This workbook uses a caller-owned sink; use finish().");if(!this.result){const completion=this.finish();this.result=completion.then(()=>this.package.toBlob(xlsxMime))}
1348
+ return this.result}}
1349
+ const _exports=Object.freeze({Workbook:Workbook});_modules.set("0f11efc0d52501e827898643b33f7fa42365115a892aa801634ecea3f3603681",_exports);return _exports})();const _m52=_modules.get("89111eab1f3857529c2d0cd849f16598097e62bd73841211b9c66ccc7b1b7ca2")??(()=>{const{ExportCell,assertScalar}=_m5;const{captureWorkbookOptions,sheetOptionFields}=_m22;const{captureFields}=_m10;function style(patch){for(const component of["font","fill","border","numberFormat"])
1350
+ if(typeof patch?.[component]==="number")
1351
+ throw new TypeError("Workbook-local style indexes require the advanced Workbook API; use style definitions.");return patch}
1352
+ function value(result){if(!(result instanceof ExportCell))
1353
+ assertScalar(result);return result}
1354
+ function portableSheet(options={}){options=captureFields(options,sheetOptionFields);if(options.headerStyle!==undefined)
1355
+ throw new TypeError("Workbook-local header styles require the advanced Workbook API; use boldHeader and headerFill.");style(options.alternatingRowStyle);style(options.title?.style);style(options.footer?.style);options.footer?.values?.forEach(value);const rowStyle=options.rowStyle,cellStyle=options.cellStyle;for(const callback of[rowStyle,cellStyle])
1356
+ if(callback!==undefined&&typeof callback!=="function")
1357
+ throw new TypeError("Style callbacks must be functions.");return{...options,...(rowStyle?{rowStyle:(context)=>style(rowStyle(context))}:{}),...(cellStyle?{cellStyle:(context)=>style(cellStyle(context))}:{})}}
1358
+ function portableWorkbook(options={}){options=captureWorkbookOptions(options);const writers=options.cellValueWriters;if(!writers)
1359
+ return options;const wrapped=Object.create(null);for(const[type,writer]of Object.entries(writers)){if(typeof writer!=="function")
1360
+ throw new TypeError("Cell value writers must be functions.");wrapped[type]=(input,context)=>value(writer(input,context))}
1361
+ return{...options,cellValueWriters:wrapped}}
1362
+ const _exports=Object.freeze({portableSheet:portableSheet,portableWorkbook:portableWorkbook});_modules.set("89111eab1f3857529c2d0cd849f16598097e62bd73841211b9c66ccc7b1b7ca2",_exports);return _exports})();const _m51=_modules.get("8d425cd3abec2c5e0140f71239bbeacbae0e57524ed70a8e545f80286c4a1308")??(()=>{const{withDestination}=_m3;const{copyColumns}=_m11;const{Workbook}=_m24;const{portableSheet,portableWorkbook}=_m52;const{captureFields}=_m10;const{sheetOptionFields,workbookOptionFields}=_m22;function prepare(options){options=captureFields(options,[...workbookOptionFields,"columns","sheet"]);const columns=copyColumns(options.columns),sheet=options.sheet&&captureFields(options.sheet,[...sheetOptionFields,"name"]);return{...portableWorkbook(options),columns,sheet:{...portableSheet(sheet),...(sheet?.name===undefined?{}:{name:sheet.name})}}}
1363
+ function worksheet(book,options){const{name="Data",...sheet}=options.sheet??{};return book.addWorksheet(name,{boldHeader:true,autoFilter:sheet.includeHeader!==false,autoSize:{minWidth:6,maxWidth:54},...sheet,columns:options.columns})}
1364
+ async function writeXlsx(rows,configuration){const options=prepare(configuration);const{columns:_columns,sheet:_sheet,...settings}=options;const book=Workbook.forTable(settings);try{await worksheet(book,options).addRows(rows);return await book.toBlob()}
1365
+ catch(error){await book.discard(error);throw error}}
1366
+ async function writeXlsxTo(rows,destination,configuration){const options=prepare(configuration);return withDestination(destination,async(sink)=>{const{columns:_columns,sheet:_sheet,...settings}=options;const book=Workbook.forTable({...settings,sink});try{const sheet=worksheet(book,options);const columns=options.columns.length;await sheet.addRows(rows);const result=await book.finish();return{rows:result.rows,columns,bytes:result.bytes}}
1367
+ catch(error){await book.discard(error);throw error}})}
1368
+ const _exports=Object.freeze({writeXlsx:writeXlsx,writeXlsxTo:writeXlsxTo});_modules.set("8d425cd3abec2c5e0140f71239bbeacbae0e57524ed70a8e545f80286c4a1308",_exports);return _exports})();const _m54=_modules.get("02f1b8fe9368420b22d79efc01f2b37794fc40aaf8150161b3b7623fcdc0d71f")??(()=>{const{assertGroupedReportSource}=_m8;const{captureFields}=_m10;const{OfficeIMOError}=_m2;const{fields}=_m34;const{sheetOptionFields}=_m22;const{portableSheet}=_m52;const{resolveDataColumn}=_m44;const{copyStylePatch}=_m32;const groupedOptionFields=["labelColumn","subtotalLabel","grandTotalLabel","includeGrandTotal","collapseGroups","sheet","groupStyle","subtotalStyle","grandTotalStyle","conditionalFormats","dataValidation"];const unsupported=["columns","headerRows","footer","table","mergedCells","hyperlinks","conditionalFormats","dataValidation","rowStyle","cellStyle","rowOutline","maxOutlineLevel"];function detailColumn(report,selector){return resolveDataColumn(report.columns,selector,"Grouped detail")+ 1}
1369
+ function conditionalRules(report,rules,maximum){if(rules===undefined)
1370
+ return undefined;if(!Array.isArray(rules))
1371
+ throw new TypeError("conditionalFormats must be an array.");if(rules.length>maximum)
1372
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxConditionalFormats exceeded.");return rules.map(input=>{const rule=captureFields(input,["type","range","style","stopIfTrue","operator","value","values","formula","stops","color","minimum","maximum","showValue"]);const inputRange=rule.range;if(typeof inputRange==="string")
1373
+ throw new TypeError("Grouped conditional formats require detail-column selectors rather than A1 or generated-row ranges.");fields(inputRange,["column","through"],"grouped conditional range");const range=captureFields(inputRange,["column","through"]);return{...rule,range:{column:detailColumn(report,range.column),...(range.through===undefined?{}:{through:detailColumn(report,range.through)})}}})}
1374
+ function validationRules(report,rules,maximum){if(rules===undefined)
1375
+ return undefined;if(!Array.isArray(rules))
1376
+ throw new TypeError("dataValidation must be an array.");if(rules.length>maximum)
1377
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxDataValidations exceeded.");return rules.map(input=>{const rule=captureFields(input,["type","column","items","allowBlank","showErrorMessage","errorStyle","errorTitle","errorMessage"]);return{...rule,column:detailColumn(report,rule.column)}})}
1378
+ function prepareGroupedSheet(report,configuration,maxConditionalFormats=1000,maxDataValidations=1000){assertGroupedReportSource(report);if(!configuration||typeof configuration!=="object")
1379
+ throw new TypeError("Grouped XLSX options require host-authored labels.");const options=captureFields(configuration,groupedOptionFields);const sheet=captureFields(options.sheet??{},[...sheetOptionFields,"name"]);if(!options.labelColumn||typeof options.labelColumn!=="object")
1380
+ throw new TypeError("Grouped XLSX needs a leading label column.");const labelColumn=captureFields(options.labelColumn,["header","width","wrapText","alignment"]);if(typeof labelColumn.header!=="string")
1381
+ throw new TypeError("The leading label column needs a string header.");for(const label of[options.subtotalLabel,options.grandTotalLabel])
1382
+ if(typeof label!=="function")
1383
+ throw new TypeError("Grouped summary labels must be functions.");for(const flag of[options.includeGrandTotal,options.collapseGroups])
1384
+ if(flag!==undefined&&typeof flag!=="boolean")
1385
+ throw new TypeError("Grouped XLSX flags must be booleans.");for(const key of unsupported)
1386
+ if(sheet[key]!==undefined)
1387
+ throw new TypeError("Grouped XLSX owns worksheet "+key+".");if(sheet.autoFilter!==undefined&&sheet.autoFilter!==false)
1388
+ throw new TypeError("Grouped summary rows cannot use a native table or autofilter.");for(const style of[options.groupStyle,options.subtotalStyle,options.grandTotalStyle])
1389
+ if(style!==undefined)
1390
+ portableSheet({alternatingRowStyle:style});for(const column of report.columns)
1391
+ if(Object.prototype.hasOwnProperty.call(report.totals,column.key)&&column.type!=="number")
1392
+ throw new TypeError("Editable grouped totals require explicitly numeric columns.");const conditionalFormats=conditionalRules(report,options.conditionalFormats,maxConditionalFormats),dataValidation=validationRules(report,options.dataValidation,maxDataValidations);return{...options,labelColumn,sheet:portableSheet(sheet),...(conditionalFormats===undefined?{}:{conditionalFormats}),...(dataValidation===undefined?{}:{dataValidation}),...(options.groupStyle?{groupStyle:copyStylePatch(options.groupStyle)}:{}),...(options.subtotalStyle?{subtotalStyle:copyStylePatch(options.subtotalStyle)}:{}),...(options.grandTotalStyle?{grandTotalStyle:copyStylePatch(options.grandTotalStyle)}:{})}}
1393
+ const _exports=Object.freeze({groupedOptionFields:groupedOptionFields,prepareGroupedSheet:prepareGroupedSheet});_modules.set("02f1b8fe9368420b22d79efc01f2b37794fc40aaf8150161b3b7623fcdc0d71f",_exports);return _exports})();const _m53=_modules.get("6b646c4d57b8f8f452eaa7e61d2935bab09681aceb6064b8600bf73ca10b8f4e")??(()=>{const{groupedReportOperation}=_m8;const{checkAbort,withAbort}=_m4;const{withDestination}=_m3;const{captureFields}=_m10;const{Workbook}=_m24;const{FormulaCell}=_m36;const{columnName}=_m35;const{captureWorkbookLimits,workbookOptionFields}=_m22;const{retainDataRowRanges}=_m45;const{groupedOptionFields,prepareGroupedSheet}=_m54;const subtotalOperations={average:1,count:2,max:4,min:5,sum:9};function label(value){if(typeof value?.then==="function")
1394
+ void Promise.resolve(value).catch(()=>{});if(typeof value!=="string")
1395
+ throw new TypeError("Grouped summary labels must return strings.");return value}
1396
+ function subtotal(operation,letter,first,last,cached){const range=letter+first+":"+letter+last;const expression="SUBTOTAL("+subtotalOperations[operation]+ ","+range+")";return new FormulaCell(operation==="average"||operation==="min"||operation==="max"
1397
+ ?"IF(SUBTOTAL(2,"+range+")=0,\"\","+expression+")":expression,cached,operation==="count"?0:undefined)}
1398
+ async function append(book,report,options,operation,accepted){checkAbort(operation.signal);const{labelColumn,subtotalLabel,grandTotalLabel,includeGrandTotal,collapseGroups,sheet:sheetOptions,groupStyle,subtotalStyle,grandTotalStyle,conditionalFormats,dataValidation}=options;let rows=0,current;const groups=[],stack=[],detailRanges=[];let firstDetail=0,lastDetail=0,grandTotalRow;let grandSummary;const{name="Data",...sheetSettings}=sheetOptions??{};const columns=[{...labelColumn,type:"string"},...report.columns];const styles={groupStart:groupStyle??{font:{bold:true}},groupEnd:subtotalStyle??{font:{bold:true}},complete:grandTotalStyle??{font:{bold:true}}};const sheet=book.addWorksheet(name,{boldHeader:true,autoSize:{minWidth:6,maxWidth:54},...sheetSettings,columns,...(conditionalFormats===undefined?{}:{conditionalFormats}),...(dataValidation===undefined?{}:{dataValidation}),maxOutlineLevel:report.groupBy.length,rowStyle:()=>current&&current.kind!=="row"?styles[current.kind]:undefined,rowOutline:()=>{if(!current||current.kind==="complete")
1399
+ return undefined;const level=current.kind==="row"?current.path.length:current.level;return{level,hidden:!!collapseGroups&&level>0,collapsed:!!collapseGroups&&current.kind==="groupEnd"}}});retainDataRowRanges(sheet,detailRanges);const operations=report.columns.map(column=>Object.prototype.hasOwnProperty.call(report.totals,column.key)?report.totals[column.key]:undefined);async function*values(){for await(const event of operation.events){current=event;const worksheetRow=sheet.rowCount+sheet.headerRowCount+1;if(event.kind==="groupStart"){const group={groupIndex:event.groupIndex,level:event.level,key:event.key,label:event.label,path:event.path,rows:0,totals:Object.freeze([]),startRow:worksheetRow,firstDetailRow:0,lastDetailRow:0,summaryRow:0};groups.push(group);stack.push(group);yield[event.label,...report.columns.map(()=>null)]}
1400
+ else if(event.kind==="row"){rows++;accepted?.(rows);firstDetail||=worksheetRow;lastDetail=worksheetRow;const previous=detailRanges.at(-1);if(previous&&previous.lastRow+1===worksheetRow)
1401
+ previous.lastRow=worksheetRow;else
1402
+ detailRanges.push({firstRow:worksheetRow,lastRow:worksheetRow});for(const group of stack){group.firstDetailRow||=worksheetRow;group.lastDetailRow=worksheetRow}
1403
+ yield[null,...event.values]}
1404
+ else if(event.kind==="groupEnd"){const group=stack.pop();group.summaryRow=worksheetRow;group.rows=event.rows;group.totals=event.totals;yield[label(subtotalLabel(event)),...operations.map((operation,index)=>operation
1405
+ ?subtotal(operation,columnName(index+2),group.firstDetailRow,group.lastDetailRow,event.totals[index]):null)]}
1406
+ else{grandSummary=Object.freeze({rows:event.rows,groups:event.groups,totals:event.totals});if(includeGrandTotal!==false){grandTotalRow=worksheetRow;yield[label(grandTotalLabel(event)),...operations.map((operation,index)=>operation
1407
+ ?firstDetail?subtotal(operation,columnName(index+2),firstDetail,lastDetail,event.totals[index]):event.totals[index]:null)]}}}}
1408
+ try{checkAbort(operation.signal);await withAbort(sheet.addRows(values()),operation.signal);await withAbort(sheet.close(),operation.signal);return Object.freeze({worksheet:sheet,rows,columns:columns.length,detailRanges:Object.freeze(detailRanges.map(range=>Object.freeze({...range}))),groups:Object.freeze(groups.map(group=>Object.freeze({...group}))),grandSummary:grandSummary,...(grandTotalRow===undefined?{}:{grandTotalRow})})}
1409
+ catch(error){await book.discard(error);throw error}}
1410
+ async function addGroupedXlsx(book,report,options){const prepared=prepareGroupedSheet(report,options,book.settings.limits?.maxConditionalFormats??1000,book.availableDataValidations),operation=groupedReportOperation(report,book.settings.signal);try{return await append(book,report,prepared,operation)}
1411
+ finally{operation.dispose()}}
1412
+ function prepare(report,configuration){if(!configuration||typeof configuration!=="object")
1413
+ throw new TypeError("Grouped XLSX options require host-authored labels.");const options=captureFields(configuration,[...workbookOptionFields,...groupedOptionFields]);if(options.sink!==undefined||options.cellValueWriters!==undefined)
1414
+ throw new TypeError("Grouped XLSX owns its destination and uses already resolved source values.");const limits=options.limits===undefined?undefined:captureWorkbookLimits(options.limits);return{...options,...(limits===undefined?{}:{limits}),...prepareGroupedSheet(report,options,limits?.maxConditionalFormats??1000,limits?.maxDataValidations??1000)}}
1415
+ async function write(report,options,sink){const{labelColumn:_labelColumn,subtotalLabel:_subtotalLabel,grandTotalLabel:_grandTotalLabel,includeGrandTotal:_includeGrandTotal,collapseGroups:_collapseGroups,sheet:_sheet,groupStyle:_groupStyle,subtotalStyle:_subtotalStyle,grandTotalStyle:_grandTotalStyle,conditionalFormats:_conditionalFormats,dataValidation:_dataValidation,onProgress,...settings}=options;const operation=groupedReportOperation(report,settings.signal);let rows=0,book;const progress=onProgress?(event)=>onProgress({...event,rows,...(event.sheetRows===undefined?{}:{sheetRows:rows})}):undefined;try{book=new Workbook({...settings,...(operation.signal?{signal:operation.signal}:{}),...(progress?{onProgress:progress}:{}),...(sink?{sink}:{})});const result=await append(book,report,options,operation,accepted=>{rows=accepted});if(sink){const completion=await book.finish();return{result:{rows,columns:result.columns,bytes:completion.bytes}}}
1416
+ const blob=await book.toBlob();return{blob,result:{rows,columns:result.columns,bytes:blob.size}}}
1417
+ catch(error){await book?.discard(error);throw error}
1418
+ finally{operation.dispose()}}
1419
+ async function writeGroupedXlsx(report,options){return(await write(report,prepare(report,options))).blob}
1420
+ async function writeGroupedXlsxTo(report,destination,options){const prepared=prepare(report,options);return withDestination(destination,async(sink)=>(await write(report,prepared,sink)).result)}
1421
+ const _exports=Object.freeze({addGroupedXlsx:addGroupedXlsx,writeGroupedXlsx:writeGroupedXlsx,writeGroupedXlsxTo:writeGroupedXlsxTo});_modules.set("6b646c4d57b8f8f452eaa7e61d2935bab09681aceb6064b8600bf73ca10b8f4e",_exports);return _exports})();const _m23=_modules.get("9fbdb5c6f6af75d87ac6cb47771fe48fa6527be2cb7d16dbad56e4213e2f7195")??(()=>{const _exports=Object.freeze({Workbook:_m24.Workbook,writeXlsx:_m51.writeXlsx,writeXlsxTo:_m51.writeXlsxTo,writeGroupedXlsx:_m53.writeGroupedXlsx,writeGroupedXlsxTo:_m53.writeGroupedXlsxTo,addGroupedXlsx:_m53.addGroupedXlsx,createGroupedReport:_m8.createGroupedReport,Worksheet:_m37.Worksheet,Cell:_m35.Cell,FormulaCell:_m36.FormulaCell,StyleRegistry:_m32.StyleRegistry,NumberFormats:_m32.NumberFormats,saveBlob:_m1.saveBlob,ExportCell:_m5.ExportCell});_modules.set("9fbdb5c6f6af75d87ac6cb47771fe48fa6527be2cb7d16dbad56e4213e2f7195",_exports);return _exports})();const _m56=_modules.get("2f5c0823847e9209017d01b2a753f36056df2a9988fae1f3a1bd5fd186545220")??(()=>{const{captureTableSpans,tableSpans}=_m18;function csvStructuredRows(rows,columns,mode){const anchors=tableSpans(captureTableSpans(rows,columns),columns),output=anchors.map(()=>Array(columns).fill(""));for(let row=0;row<anchors.length;row++)
1422
+ for(const anchor of anchors[row]){if((anchor.span>1||anchor.rowSpan>1)&&mode===undefined)
1423
+ throw new TypeError("CSV spanned headings/footers require an explicit spanMode: repeat or anchors.");const value=anchor.value;for(let r=row;r<row +(mode==="repeat"?anchor.rowSpan:1);r++)
1424
+ for(let c=anchor.first;c<anchor.first +(mode==="repeat"?anchor.span:1);c++)
1425
+ output[r][c]=value}
1426
+ return output}
1427
+ const _exports=Object.freeze({csvStructuredRows:csvStructuredRows});_modules.set("2f5c0823847e9209017d01b2a753f36056df2a9988fae1f3a1bd5fd186545220",_exports);return _exports})();const _m55=_modules.get("b48bcab805d4c75294dd8d8e8dc57f96d9db3f5af31a8f0ddc6562f010f566e4")??(()=>{const{beginTask,checkAbort,consumeRows,taskYieldDue,withAbort}=_m4;const{BlobByteSink,ChunkedTextSink,withDestination}=_m3;const{ExportBudget,boundedSink}=_m9;const{ExportCell}=_m5;const{isDate}=_m6;const{notifyProgress}=_m14;const{copyColumns,createRowProjector}=_m11;const{csvStructuredRows}=_m56;const{captureBooleanText}=_m21;const{captureCsvOptions}=_m16;function csvField(value,delimiter,protect,quote,booleanText){const kind=typeof value;let text;if(value==null)
1428
+ text="";else if(kind==="string")
1429
+ text=value;else if(kind==="number"){text=Number.isFinite(value)?String(value):"";return quote==="all"?'"'+text+'"':text}
1430
+ else if(kind==="boolean")
1431
+ text=booleanText[value?"true":"false"];else if(isDate(value))
1432
+ text=Number.isFinite(value.getTime())?value.toISOString():"";else{if(typeof value.then==="function")
1433
+ void Promise.resolve(value).catch(()=>{});throw new TypeError("CSV cells and formatter results must be synchronous strings, numbers, booleans, Dates or null.")}
1434
+ if(protect&&(kind==="string"||kind==="boolean")&&text.charCodeAt(0)<=64&&/^ *[=+\-@\t\r\n]/.test(text))
1435
+ text="'"+text;return quote==="all"||(quote==="strings"&&kind==="string")||text.includes(delimiter)||/["\r\n]/.test(text)
1436
+ ?'"' +(text.includes('"')?text.replace(/"/g, '""') : text) + '"' : text;
1437
+ }
1438
+ async function writeCsvTo(rows,destination,configuration){const options=captureCsvOptions(configuration);return withDestination(destination,sink=>write(rows,sink,options))}
1439
+ async function write(rows,sink,options){beginTask();const columns=copyColumns(options.columns).map(c=>Object.freeze(c)),delimiter=options.delimiter??",",lineEnding=options.lineEnding??"\r\n",quote=options.quote??"minimal";const booleanText=captureBooleanText(options.booleanText);if(![",",";","\t"].includes(delimiter))
1440
+ throw new RangeError("Delimiter must be comma, semicolon or tab.");if(!["\r\n","\n","\r"].includes(lineEnding))
1441
+ throw new RangeError("Invalid line ending.");if(!["minimal","all","strings"].includes(quote))
1442
+ throw new RangeError("Quoting must be minimal, all or strings.");if(options.valueMode!==undefined&&!["raw","display"].includes(options.valueMode))
1443
+ throw new RangeError("valueMode must be raw or display.");if(options.nullValue!==undefined&&typeof options.nullValue!=="string")
1444
+ throw new TypeError("nullValue must be a string.");if(options.spanMode!==undefined&&options.spanMode!=="repeat"&&options.spanMode!=="anchors")
1445
+ throw new TypeError("CSV spanMode must be repeat or anchors.");const headings=options.includeHeader===false?[]:options.headerRows===undefined?columns.length?[columns.map(c=>c.header)]:[]:csvStructuredRows(options.headerRows,columns.length,options.spanMode);const footers=options.footer===undefined?[]:csvStructuredRows(options.footer.rows,columns.length,options.spanMode);for(const column of columns)
1446
+ if(column.valueFormatter!==undefined&&typeof column.valueFormatter!=="function")
1447
+ throw new TypeError("CSV value formatters must be functions.");const budget=new ExportBudget(options.limits);let bytes=0;const accepted=sink;sink=boundedSink({async write(chunk){await accepted.write(chunk);bytes +=chunk.byteLength}},budget);const project=createRowProjector(columns,undefined,options.signal);const hasFormatters=columns.some(column=>column.valueFormatter);const signal=options.signal,protect=options.formulaInjectionProtection!==false,buffer=new ChunkedTextSink(sink,signal);checkAbort(signal);if(options.bom)
1448
+ await withAbort(Promise.resolve(sink.write(new Uint8Array([239,187,191]))),signal);let count=0;const resolved=(value)=>value!==null&&typeof value==="object"&&value instanceof ExportCell?options.valueMode==="display"&&value.text!==undefined?value.text:value.value:value;function record(values,header=false,first=0,snapshot){if(!header&&hasFormatters&&first===0)
1449
+ snapshot=Object.freeze(columns.map((_,i)=>resolved(values[i])));let text="";for(let i=first;i<columns.length;i++){checkAbort(signal);const column=columns[i];const raw=resolved(values[i]);let value=!header&&column.valueFormatter?column.valueFormatter(raw,{rowIndex:count,columnIndex:i,column,values:snapshot}):raw;if(value==null&&options.nullValue!==undefined)
1450
+ value=options.nullValue;budget.cell(typeof value==="boolean"?booleanText[value?"true":"false"]:value);checkAbort(signal);text +=(i?delimiter:"")+ csvField(value,delimiter,protect,quote,booleanText);if(text.length>=buffer.chunkSize||(i&127)===127&&taskYieldDue()){if(buffer.append(text))
1451
+ return buffer.flush().then(()=>record(values,header,i+1,snapshot));text=""}}
1452
+ if(buffer.append(text+lineEnding))
1453
+ return buffer.flush().then(()=>{notifyProgress(options.onProgress,{phase:"rows",rows:count +(header?0:1)})})}
1454
+ for(const heading of headings)
1455
+ await record(heading,true);await consumeRows(rows,signal,row=>{budget.row(count+1);const pending=record(project(row,count));if(pending)
1456
+ return pending.then(()=>{count++});count++});for(const footer of footers)
1457
+ await record(footer,true);await buffer.close();notifyProgress(options.onProgress,{phase:"complete",rows:count,bytes});checkAbort(signal);return{rows:count,columns:columns.length,bytes}}
1458
+ async function writeCsv(rows,configuration){const options=captureCsvOptions(configuration);const sink=new BlobByteSink();try{let completedRows=0;await write(rows,sink,{...options,onProgress:p=>{if(p.phase==="complete")
1459
+ completedRows=p.rows;else
1460
+ notifyProgress(options.onProgress,p)}});const blob=sink.toBlob("text/csv;charset=utf-8");notifyProgress(options.onProgress,{phase:"complete",rows:completedRows,bytes:blob.size});checkAbort(options.signal);return blob}
1461
+ catch(error){sink.discard();throw error}}
1462
+ const _exports=Object.freeze({saveBlob:_m1.saveBlob,ExportCell:_m5.ExportCell,writeCsvTo:writeCsvTo,writeCsv:writeCsv});_modules.set("b48bcab805d4c75294dd8d8e8dc57f96d9db3f5af31a8f0ddc6562f010f566e4",_exports);return _exports})();const _m61=_modules.get("e3d39f39aebcbaf063fd8221df0d9cb5902ad2545a9d9e474bb59d47f15e2c01")??(()=>{const pdfXrefEntryBytes=11;function unsigned(bytes,offset,value,width){if(!Number.isSafeInteger(value)||value<0||value>=2**(width*8))
1463
+ throw new RangeError("Invalid PDF cross-reference field.");for(let index=width-1;index>=0;index--){bytes[offset+index]=value%256;value=Math.floor(value / 256);
1464
+ }}
1465
+ function*pdfXrefChunks(locations,indices){if(locations.length!==indices.length)
1466
+ throw new Error("PDF cross-reference locations must align.");const perChunk=Math.floor(32768 / pdfXrefEntryBytes);
1467
+ for(let first=0;first<locations.length;first +=perChunk){const count=Math.min(perChunk,locations.length-first),bytes=new Uint8Array(count*pdfXrefEntryBytes);for(let index=0;index<count;index++){const id=first+index,position=index*pdfXrefEntryBytes,location=locations[id],member=indices.at(id);if(location===undefined)
1468
+ throw new Error("PDF contains unwritten objects.");bytes[position]=id===0?0:member===undefined?1:2;unsigned(bytes,position+1,location,8);unsigned(bytes,position+9,id===0?65535:member??0,2)}
1469
+ yield bytes}}
1470
+ const _exports=Object.freeze({pdfXrefEntryBytes:pdfXrefEntryBytes,pdfXrefChunks:pdfXrefChunks});_modules.set("e3d39f39aebcbaf063fd8221df0d9cb5902ad2545a9d9e474bb59d47f15e2c01",_exports);return _exports})();const _m60=_modules.get("e716b8b1da464094622f5f671518493c78e63ff22a029d61544d2d193b63ce8f")??(()=>{const{checkAbort,withAbort,pause,taskYieldDue}=_m4;const{OfficeIMOError}=_m2;const{pdfXrefChunks,pdfXrefEntryBytes}=_m61;const compactObjectCount=256,compactObjectBytes=32768;const compactIndexChunkEntries=4096;class PdfCompactIndices{count;chunks=[];constructor(count){this.count=count}
1471
+ get length(){return this.count}
1472
+ reserve(){this.count++}
1473
+ set(id,member){const chunk=this.chunks[Math.floor(id / compactIndexChunkEntries)] ??= new Uint16Array(compactIndexChunkEntries);
1474
+ chunk[id%compactIndexChunkEntries]=member+1}
1475
+ at(id){const encoded=this.chunks[Math.floor(id / compactIndexChunkEntries)]?.[id % compactIndexChunkEntries] ?? 0;
1476
+ return encoded?encoded-1:undefined}}
1477
+ function pdfNumber(value){if(!Number.isFinite(value)||Math.abs(value)>1e9)
1478
+ throw new RangeError("PDF coordinates and metrics must be finite and bounded.");return String(Math.round(value*1000)/ 1000);
1479
+ }
1480
+ function unicodeHex(text){let hex="";for(let i=0;i<text.length;i++){const code=text.charCodeAt(i);if(code>=0xd800&&code<=0xdbff&&!(text.charCodeAt(i+1)>=0xdc00&&text.charCodeAt(i+1)<=0xdfff)||
1481
+ code>=0xdc00&&code<=0xdfff&&!(text.charCodeAt(i-1)>=0xd800&&text.charCodeAt(i-1)<=0xdbff))
1482
+ throw new TypeError("PDF text contains an unpaired UTF-16 surrogate.");hex +=code.toString(16).padStart(4,"0")}
1483
+ return hex}
1484
+ class PdfObjects{sink;signal;maxBytes;compressObjects;offsets=[0];compactIndices;compactBatch;compactArena;compactUnavailable=false;encoder=new TextEncoder();buffer=new Uint8Array(32768);buffered=0;bytes=0;constructor(sink,signal,maxBytes=Number.MAX_SAFE_INTEGER,compressObjects=false){this.sink=sink;this.signal=signal;this.maxBytes=maxBytes;this.compressObjects=compressObjects}
1485
+ reserve(){this.offsets.push(undefined);this.compactIndices?.reserve();return this.offsets.length-1}
1486
+ async raw(bytes){checkAbort(this.signal);if(!Number.isSafeInteger(this.bytes+bytes.length)||this.bytes+bytes.length>this.maxBytes)
1487
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxOutputBytes exceeded.");this.bytes +=bytes.length;for(let offset=0;offset<bytes.length;){const n=Math.min(this.buffer.length-this.buffered,bytes.length-offset);this.buffer.set(bytes.subarray(offset,offset+n),this.buffered);offset +=n;this.buffered +=n;if(this.buffered===this.buffer.length)
1488
+ await this.flushBytes()}}
1489
+ async text(text){await this.raw(this.encoder.encode(text))}
1490
+ async flush(){await this.flushCompact();await this.flushBytes()}
1491
+ async flushBytes(){if(this.buffered){const bytes=this.buffer.subarray(0,this.buffered);await withAbort(Promise.resolve(this.sink.write(bytes)),this.signal);this.buffered=0}
1492
+ if(taskYieldDue())
1493
+ await pause();checkAbort(this.signal)}
1494
+ tryCompactObject(id,body){checkAbort(this.signal);this.validateObject(id);const batch=this.compactBatch;if(!batch||!this.compressObjects||this.compactUnavailable||typeof CompressionStream!=="function"||
1495
+ body.length>compactObjectBytes||batch.ids.length+1>=compactObjectCount)
1496
+ return false;const indexBytes=String(id).length+String(batch.bodyBytes).length+2;const written=this.encodeCompactBody(body,batch.bodyBytes,compactObjectBytes-batch.indexBytes-indexBytes-batch.bodyBytes-2);if(written===undefined)
1497
+ return false;this.storeCompactBody(batch,id,written);return true}
1498
+ async compactObject(id,body){checkAbort(this.signal);this.validateObject(id);if(!this.compressObjects||this.compactUnavailable||body.length>compactObjectBytes)
1499
+ return this.object(id,body);if(typeof CompressionStream!=="function"){if(this.compactIndices)
1500
+ throw new Error("PDF object compression became unavailable.");this.compactUnavailable=true;return this.object(id,body)}
1501
+ const firstIndexBytes=String(id).length+4;let batch=this.compactBatch;const indexBytes=String(id).length+String(batch?.bodyBytes??0).length+2;let written=batch&&batch.ids.length<compactObjectCount?this.encodeCompactBody(body,batch.bodyBytes,compactObjectBytes-batch.indexBytes-indexBytes-batch.bodyBytes-2):undefined;if(batch&&written===undefined){await this.flushCompact();batch=undefined;checkAbort(this.signal)}
1502
+ if(!batch){written=this.encodeCompactBody(body,0,compactObjectBytes-firstIndexBytes-1);if(written===undefined)
1503
+ return this.object(id,body);let compressor;if(!this.compactIndices){try{compressor=new CompressionStream("deflate")}
1504
+ catch{this.compactUnavailable=true;return this.object(id,body)}}
1505
+ batch={id:this.reserve(),compressor,ids:[],bodyOffsets:[],bodyBytes:0,indexBytes:1};this.compactIndices??=new PdfCompactIndices(this.offsets.length);this.compactBatch=batch}
1506
+ this.storeCompactBody(batch,id,written);if(batch.ids.length===compactObjectCount)
1507
+ await this.flushCompact()}
1508
+ storeCompactBody(batch,id,written){this.offsets[id]=batch.id;this.compactIndices.set(id,batch.ids.length);batch.indexBytes +=String(id).length+String(batch.bodyBytes).length+2;batch.ids.push(id);batch.bodyOffsets.push(batch.bodyBytes);this.compactArena[batch.bodyBytes+written]=10;batch.bodyBytes +=written+1}
1509
+ encodeCompactBody(body,offset,available){if(available<0)
1510
+ return undefined;const destination=(this.compactArena??=new Uint8Array(compactObjectBytes)).subarray(offset,offset+available);if(typeof this.encoder.encodeInto==="function"){const result=this.encoder.encodeInto(body,destination);return result.read===body.length?result.written:undefined}
1511
+ const bytes=this.encoder.encode(body);if(bytes.length>available)
1512
+ return undefined;destination.set(bytes);return bytes.length}
1513
+ async flushCompact(){const batch=this.compactBatch;if(!batch)
1514
+ return;this.compactBatch=undefined;let index="";for(let member=0;member<batch.ids.length;member++)
1515
+ index +=batch.ids[member]+ " "+batch.bodyOffsets[member]+ " ";const header=this.encoder.encode(index+"\n"),count=batch.ids.length;const body=this.compactArena.subarray(0,batch.bodyBytes);batch.ids.length=0;batch.bodyOffsets.length=0;if(batch.compressor){await this.compressedStream(batch.id,body,"/Type /ObjStm /N "+count+" /First "+header.length,batch.compressor,header)}
1516
+ else{this.start(batch.id);await this.text(batch.id+" 0 obj\n<< /Length " +(header.length+body.length)+ " /Type /ObjStm /N "+count+" /First "+header.length+" >>\nstream\n");await this.raw(header);await this.raw(body);await this.text("\nendstream\nendobj\n")}}
1517
+ async object(id,body){this.start(id);if(typeof body==="string"){await this.text(id+" 0 obj\n"+body+"\nendobj\n");return}
1518
+ let chunk=id+" 0 obj\n";for(const part of body){for(let offset=0;offset<part.length;){const end=Math.min(part.length,offset+32768-chunk.length);chunk +=part.slice(offset,end);offset=end;if(chunk.length===32768){const code=chunk.charCodeAt(chunk.length-1),length=code>=0xd800&&code<=0xdbff?chunk.length-1:chunk.length;await this.text(chunk.slice(0,length));chunk=chunk.slice(length)}}}
1519
+ await this.text(chunk+"\nendobj\n")}
1520
+ validateObject(id){if(!Number.isSafeInteger(id)||id<=0||id>=this.offsets.length||this.offsets[id]!==undefined)
1521
+ throw new Error("Invalid PDF object state.")}
1522
+ start(id){this.validateObject(id);this.offsets[id]=this.bytes}
1523
+ async stream(id,source,dictionary="",compression=true,owned=false){const bytes=typeof source==="string"?this.encoder.encode(source):source;let compressor;if(compression&&typeof CompressionStream==="function"&&bytes.length){try{compressor=new CompressionStream("deflate")}
1524
+ catch{/* PDF streams can remain uncompressed. */ }
1525
+ }
1526
+ if(!compressor){this.start(id);await this.text(id+" 0 obj\n<< /Length "+bytes.length+" "+dictionary+" >>\nstream\n");await this.raw(bytes);await this.text("\nendstream\nendobj\n");return}
1527
+ const sourceBytes=typeof source==="string"||owned?bytes:new Uint8Array(bytes);await this.compressedStream(id,sourceBytes,dictionary,compressor)}
1528
+ async compressedStream(id,sourceBytes,dictionary,compressor,prefix){const input=new ReadableStream({start(controller){if(prefix)
1529
+ controller.enqueue(prefix);controller.enqueue(sourceBytes);controller.close()}});const reader=input.pipeThrough(compressor).getReader(),lengthId=this.reserve();let length=0,complete=false;try{this.start(id);await this.text(id+" 0 obj\n<< /Length "+lengthId+" 0 R /Filter /FlateDecode "+dictionary+" >>\nstream\n");while(true){const next=await withAbort(reader.read(),this.signal);if(next.done){complete=true;break}
1530
+ length +=next.value.length;await this.raw(next.value)}
1531
+ await this.text("\nendstream\nendobj\n");await this.object(lengthId,String(length))}
1532
+ finally{if(!complete)
1533
+ void reader.cancel(this.signal?.reason).catch(()=>{});reader.releaseLock()}}
1534
+ async finish(root,info){await this.flushCompact();for(let id=1;id<this.offsets.length;id++)
1535
+ if(this.offsets[id]===undefined)
1536
+ throw new Error("PDF contains unwritten objects.");if(this.bytes>9999999999)
1537
+ throw new OfficeIMOError("RESOURCE_LIMIT","PDF exceeds classic cross-reference offset capacity.");if(this.compactIndices)
1538
+ return this.finishCompact(root,info);const start=this.bytes;await this.text("xref\n0 "+this.offsets.length+"\n0000000000 65535 f \n");for(let i=1;i<this.offsets.length;i++)
1539
+ await this.text(String(this.offsets[i]).padStart(10,"0")+ " 00000 n \n");await this.text("trailer\n<< /Size "+this.offsets.length+" /Root "+root+" 0 R /Info "+info+" 0 R >>\nstartxref\n"+start+"\n%%EOF\n");await this.flush()}
1540
+ async finishCompact(root,info){const id=this.reserve(),start=this.bytes,length=this.offsets.length*pdfXrefEntryBytes;if(!Number.isSafeInteger(length))
1541
+ throw new OfficeIMOError("RESOURCE_LIMIT","PDF cross-reference stream is too large.");this.start(id);await this.text(id+" 0 obj\n<< /Type /XRef /Size "+this.offsets.length+" /W [1 8 2] /Root "+root+" 0 R /Info "+info +
1542
+ " 0 R /Length "+length+" >>\nstream\n");for(const chunk of pdfXrefChunks(this.offsets,this.compactIndices))
1543
+ await this.raw(chunk);await this.text("\nendstream\nendobj\nstartxref\n"+start+"\n%%EOF\n");await this.flushBytes()}}
1544
+ const _exports=Object.freeze({pdfNumber:pdfNumber,unicodeHex:unicodeHex,PdfObjects:PdfObjects});_modules.set("e716b8b1da464094622f5f671518493c78e63ff22a029d61544d2d193b63ce8f",_exports);return _exports})();const _m65=_modules.get("1e169e6ecdeceff319b5da4bf01f4c653c1a3d9e8ad696b141bf8ac52d9f446c")??(()=>{class FontReader{bytes;view;constructor(bytes){this.bytes=bytes;this.view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength)}
1545
+ range(offset,length){if(!Number.isSafeInteger(offset)||!Number.isSafeInteger(length)||offset<0||length<0||offset+length>this.bytes.length)
1546
+ throw new TypeError("Truncated or invalid TrueType table.")}
1547
+ u16(offset){this.range(offset,2);return this.view.getUint16(offset)}
1548
+ i16(offset){this.range(offset,2);return this.view.getInt16(offset)}
1549
+ u32(offset){this.range(offset,4);return this.view.getUint32(offset)}
1550
+ tag(offset){this.range(offset,4);return String.fromCharCode(...this.bytes.subarray(offset,offset+4))}}
1551
+ function checksum(bytes){let sum=0;for(let i=0;i<bytes.length;i +=4)
1552
+ sum=(sum +(((bytes[i]??0)*0x1000000)+((bytes[i+1]??0)<<16)+((bytes[i+2]??0)<<8)+(bytes[i+3]??0)))>>>0;return sum}
1553
+ const align4=(value)=>Math.ceil(value / 4) * 4;
1554
+ const _exports=Object.freeze({FontReader:FontReader,checksum:checksum,align4:align4});_modules.set("1e169e6ecdeceff319b5da4bf01f4c653c1a3d9e8ad696b141bf8ac52d9f446c",_exports);return _exports})();const _m66=_modules.get("ecf6c6ab2f9c5f747338d0d59d9f2cae0b006d9d2a210bcb1545db1f046eb80c")??(()=>{const{align4}=_m65;const{checkAbort,pause,taskYieldDue}=_m4;function subsetTrueType(font,requested,characters){const scanner=subsetSteps(font,requested,characters);while(true){const next=scanner.next();if(next.done)
1555
+ return next.value}}
1556
+ async function subsetTrueTypeCooperatively(font,requested,characters,signal){checkAbort(signal);const scanner=subsetSteps(font,requested,characters);while(true){const next=scanner.next();if(next.done){checkAbort(signal);return next.value}
1557
+ if(taskYieldDue())
1558
+ await pause();checkAbort(signal)}}
1559
+ function*subsetSteps(font,requested,characters){const glyphs=new Set([0,...requested]),glyfTable=font.table("glyf"),queue=[...glyphs];const dependencies=new Map();let scanned=0;for(let i=0;i<queue.length;i++){if((++scanned&1023)===0)
1560
+ yield;const glyph=queue[i];if(!Number.isInteger(glyph)||glyph<0||glyph>=font.glyphCount)
1561
+ throw new TypeError("Invalid subset glyph.");const start=font.offsets[glyph],end=font.offsets[glyph+1];if(start===end)
1562
+ continue;if(end-start<10)
1563
+ throw new TypeError("Truncated TrueType glyph header.");if(font.i16(glyfTable.offset+start)>=0)
1564
+ continue;let cursor=glyfTable.offset+start+10,flags;const children=[];dependencies.set(glyph,children);const limit=glyfTable.offset+end;do{if(cursor+4>limit)
1565
+ throw new TypeError("Truncated TrueType composite.");flags=font.u16(cursor);const component=font.u16(cursor+2);if(component>=font.glyphCount)
1566
+ throw new TypeError("Invalid TrueType composite dependency.");children.push(component);if((++scanned&1023)===0)
1567
+ yield;if(!glyphs.has(component)){glyphs.add(component);queue.push(component)}
1568
+ cursor +=4 +(flags&1?4:2)+(flags&8?2:flags&64?4:flags&128?8:0);if(cursor>limit)
1569
+ throw new TypeError("Truncated TrueType composite transform.")}while(flags&32);if(flags&256){if(cursor+2>limit||cursor+2+font.u16(cursor)>limit)
1570
+ throw new TypeError("Truncated composite instructions.")}}
1571
+ const visited=new Set(),visiting=new Set();function*visit(glyph,depth){if((++scanned&1023)===0)
1572
+ yield;if(visiting.has(glyph))
1573
+ throw new TypeError("Cyclic TrueType composite dependency.");if(depth>64)
1574
+ throw new TypeError("TrueType composite nesting exceeds 64 levels.");if(visited.has(glyph))
1575
+ return;visiting.add(glyph);for(const child of dependencies.get(glyph)??[])
1576
+ yield*visit(child,depth+1);visiting.delete(glyph);visited.add(glyph)}
1577
+ for(const glyph of glyphs)
1578
+ yield*visit(glyph,0);const offsets=new Uint32Array(font.glyphCount+1);let length=0;for(let glyph=0;glyph<font.glyphCount;glyph++){offsets[glyph]=length;if(glyphs.has(glyph))
1579
+ length +=align4(font.offsets[glyph+1]- font.offsets[glyph]);if((glyph&1023)===1023)
1580
+ yield}
1581
+ offsets[font.glyphCount]=length;const glyf=new Uint8Array(length);for(const glyph of glyphs){yield*copyBytes(font.bytes.subarray(glyfTable.offset+font.offsets[glyph],glyfTable.offset+font.offsets[glyph+1]),glyf,offsets[glyph]);if((++scanned&1023)===0)
1582
+ yield}
1583
+ const loca=new Uint8Array(offsets.length*4),locaView=new DataView(loca.buffer);for(let i=0;i<offsets.length;i++){locaView.setUint32(i*4,offsets[i]);if((i&1023)===1023)
1584
+ yield}
1585
+ const retained=new Set(["OS/2","cmap","cvt ","fpgm","gasp","glyf","head","hhea","hmtx","loca","maxp","name","post","prep"]);const cmap=yield*subsetCmap(characters),hmtx=yield*subsetMetrics(font,glyphs);const tables=[];for(const[tag,table]of[...font.tables].filter(([tag])=>retained.has(tag)).sort(([a],[b])=>a<b?-1:1)){const existing=tag==="glyf"?glyf:tag==="loca"?loca:tag==="cmap"?cmap:tag==="hmtx"?hmtx:undefined;const bytes=existing??new Uint8Array(table.length);if(!existing)
1586
+ yield*copyBytes(font.bytes.subarray(table.offset,table.offset+table.length),bytes);if(tag==="head"){const view=new DataView(bytes.buffer);view.setUint32(8,0);view.setInt16(50,1)}
1587
+ tables.push({tag,bytes})}
1588
+ const size=12+tables.length*16+tables.reduce((n,t)=>n+align4(t.bytes.length),0),output=new Uint8Array(size),view=new DataView(output.buffer);view.setUint32(0,0x10000);view.setUint16(4,tables.length);const power=2**Math.floor(Math.log2(tables.length));view.setUint16(6,power*16);view.setUint16(8,Math.log2(power));view.setUint16(10,tables.length*16-power*16);let cursor=12+tables.length*16,head=0;for(let i=0;i<tables.length;i++){const table=tables[i];const p=12+i*16;for(let j=0;j<4;j++)
1589
+ output[p+j]=table.tag.charCodeAt(j);view.setUint32(p+4,yield*checksumSteps(table.bytes));view.setUint32(p+8,cursor);view.setUint32(p+12,table.bytes.length);yield*copyBytes(table.bytes,output,cursor);if(table.tag==="head")
1590
+ head=cursor;cursor +=align4(table.bytes.length)}
1591
+ view.setUint32(head+8,(0xb1b0afba -(yield*checksumSteps(output)))>>>0);return output}
1592
+ function*subsetMetrics(font,glyphs){let scanned=0;const metrics=font.u16(font.table("hhea").offset+34),table=font.table("hmtx");const result=new Uint8Array(metrics*4 +(font.glyphCount-metrics)*2);for(const glyph of glyphs){if((++scanned&1023)===0)
1593
+ yield;const first=glyph<metrics?glyph*4:metrics*4 +(glyph-metrics)*2,length=glyph<metrics?4:2;result.set(font.bytes.subarray(table.offset+first,table.offset+first+length),first);if(glyph>=metrics){const advance=(metrics-1)*4;result.set(font.bytes.subarray(table.offset+advance,table.offset+advance+2),advance)}}
1594
+ return result}
1595
+ function*subsetCmap(characters){let scanned=0;const entries=[...characters].sort(([a],[b])=>a-b),groups=[];for(const[scalar,glyph]of entries){if((++scanned&1023)===0)
1596
+ yield;const previous=groups.at(-1);if(previous&&scalar===previous.last+1&&glyph===previous.glyph+scalar-previous.first)
1597
+ previous.last=scalar;else
1598
+ groups.push({first:scalar,last:scalar,glyph})}
1599
+ const result=new Uint8Array(12+16+groups.length*12),view=new DataView(result.buffer);view.setUint16(2,1);view.setUint16(4,3);view.setUint16(6,10);view.setUint32(8,12);view.setUint16(12,12);view.setUint32(16,result.length-12);view.setUint32(24,groups.length);for(let i=0;i<groups.length;i++){const group=groups[i];const p=28+i*12;view.setUint32(p,group.first);view.setUint32(p+4,group.last);view.setUint32(p+8,group.glyph);if((i&1023)===1023)
1600
+ yield}
1601
+ return result}
1602
+ function*copyBytes(source,target,offset=0){for(let first=0;first<source.length;first +=65536){target.set(source.subarray(first,Math.min(source.length,first+65536)),offset+first);yield}}
1603
+ function*checksumSteps(bytes){let sum=0;for(let i=0;i<bytes.length;i +=4){sum=(sum +(((bytes[i]??0)*0x1000000)+((bytes[i+1]??0)<<16)+((bytes[i+2]??0)<<8)+(bytes[i+3]??0)))>>>0;if((i&65535)===65532)
1604
+ yield}
1605
+ return sum}
1606
+ const _exports=Object.freeze({subsetTrueType:subsetTrueType,subsetTrueTypeCooperatively:subsetTrueTypeCooperatively});_modules.set("ecf6c6ab2f9c5f747338d0d59d9f2cae0b006d9d2a210bcb1545db1f046eb80c",_exports);return _exports})();const _m64=_modules.get("2e1fa1582af797386e2e2914c0a27237309b1692a3cc2be688f46590eb74480d")??(()=>{const{NotSupportedError}=_m2;const{FontReader}=_m65;const{subsetTrueType,subsetTrueTypeCooperatively}=_m66;const{checkAbort,pause,taskYieldDue}=_m4;class TrueTypeFont extends FontReader{tables;glyphCount;units;ascent;descent;bbox;widths;offsets;canSubset;cmaps;constructor(bytes,prepared){super(bytes);const scanner=parseFont(this);let data=prepared;if(!data)
1607
+ while(true){const next=scanner.next();if(next.done){data=next.value;break}}
1608
+ this.tables=data.tables;this.glyphCount=data.glyphCount;this.units=data.units;this.ascent=data.ascent;this.descent=data.descent;this.bbox=data.bbox;this.widths=data.widths;this.offsets=data.offsets;this.canSubset=data.canSubset;this.cmaps=data.cmaps}
1609
+ static async create(bytes,signal){checkAbort(signal);const scanner=parseFont(new FontReader(bytes));while(true){const next=scanner.next();if(next.done){checkAbort(signal);return new TrueTypeFont(bytes,next.value)}
1610
+ if(taskYieldDue())
1611
+ await pause();checkAbort(signal)}}
1612
+ table(tag,minimum=0){const table=this.tables.get(tag);if(!table||table.length<minimum)
1613
+ throw new TypeError("Missing or truncated TrueType table: "+tag);return table}
1614
+ glyph(scalar){for(const map of this.cmaps){const p=map.offset,type=this.u16(p);let glyph=0;if(type===12){let left=0,right=this.u32(p+12)- 1;while(left<=right){const middle=(left+right)>>>1,q=p+16+middle*12,start=this.u32(q),end=this.u32(q+4);if(scalar<start)
1615
+ right=middle-1;else if(scalar>end)
1616
+ left=middle+1;else{glyph=this.u32(q+8)+ scalar-start;break}}}
1617
+ else if(scalar<=0xffff){const n=this.u16(p+6)/ 2;
1618
+ let left=0,right=n-1;while(left<right){const mid=(left+right)>>>1;if(scalar>this.u16(p+14+mid*2))
1619
+ left=mid+1;else
1620
+ right=mid}
1621
+ const start=this.u16(p+16+n*2+left*2);if(scalar>=start&&scalar<=this.u16(p+14+left*2)){const delta=this.i16(p+16+n*4+left*2),address=p+16+n*6+left*2,range=this.u16(address);if(!range)
1622
+ glyph=(scalar+delta)&0xffff;else{const q=address+range +(scalar-start)*2;if(q+2>p+map.length)
1623
+ throw new TypeError("cmap glyph array exceeds its table.");glyph=this.u16(q);if(glyph)
1624
+ glyph=(glyph+delta)&0xffff}}}
1625
+ if(glyph>=this.glyphCount)
1626
+ throw new TypeError("cmap references an invalid glyph.");if(glyph)
1627
+ return glyph}
1628
+ return 0}
1629
+ subset(glyphs,characters){return this.canSubset?subsetTrueType(this,glyphs,characters):this.bytes}
1630
+ async subsetCooperatively(glyphs,characters,signal){checkAbort(signal);return this.canSubset?subsetTrueTypeCooperatively(this,glyphs,characters,signal):this.bytes}}
1631
+ function*parseFont(reader){const tables=new Map();const table=(tag,minimum=0)=>{const result=tables.get(tag);if(!result||result.length<minimum)
1632
+ throw new TypeError("Missing or truncated TrueType table: "+tag);return result};if(reader.u32(0)!==0x10000)
1633
+ throw new NotSupportedError("PDF fonts require a static TrueType .ttf with glyf outlines; collections, CFF and WOFF are unsupported.");const count=reader.u16(4);if(!count||count>256)
1634
+ throw new TypeError("Invalid TrueType table count.");reader.range(12,count*16);for(let i=0;i<count;i++){const p=12+i*16,tag=reader.tag(p),offset=reader.u32(p+8),length=reader.u32(p+12);reader.range(offset,length);if(tables.has(tag))
1635
+ throw new TypeError("Duplicate TrueType table: "+tag);tables.set(tag,{offset,length})}
1636
+ if(tables.has("fvar"))
1637
+ throw new NotSupportedError("Instantiate a variable font as a static TrueType font before PDF export.");const head=table("head",54),maxp=table("maxp",6),hhea=table("hhea",36),os2=table("OS/2",10);if(reader.u32(head.offset+12)!==0x5f0f3cf5)
1638
+ throw new TypeError("Invalid TrueType head magic.");const glyphCount=reader.u16(maxp.offset+4);const units=reader.u16(head.offset+18);if(!glyphCount||units<16||units>16384)
1639
+ throw new TypeError("Invalid TrueType metrics.");const fsType=reader.u16(os2.offset+8);if(fsType&0x202)
1640
+ throw new NotSupportedError("The font's embedding permissions prohibit outline embedding.");const canSubset=!(fsType&0x100);const scale=1000 / units;
1641
+ const ascent=reader.i16(hhea.offset+4)*scale;const descent=reader.i16(hhea.offset+6)*scale;const bbox=[36,38,40,42].map(p=>reader.i16(head.offset+p)*scale);const metrics=reader.u16(hhea.offset+34);if(!metrics||metrics>glyphCount)
1642
+ throw new TypeError("Invalid TrueType horizontal metric count.");const hmtx=table("hmtx",metrics*4 +(glyphCount-metrics)*2);const widths=[];for(let i=0;i<glyphCount;i++){widths.push(reader.u16(hmtx.offset+Math.min(i,metrics-1)*4)*scale);if((i&1023)===1023)
1643
+ yield}
1644
+ const format=reader.i16(head.offset+50);if(format!==0&&format!==1)
1645
+ throw new TypeError("Unsupported TrueType loca index.");const loca=table("loca",(glyphCount+1)*(format?4:2)),glyf=table("glyf");const offsets=[];for(let i=0;i<=glyphCount;i++){offsets.push(format?reader.u32(loca.offset+i*4):reader.u16(loca.offset+i*2)*2);if((i&1023)===1023)
1646
+ yield}
1647
+ for(let i=0;i<=glyphCount;i++)
1648
+ if(offsets[i]>glyf.length||(i&&offsets[i]<offsets[i-1]))
1649
+ throw new TypeError("Invalid TrueType glyph offsets.");const cmap=table("cmap",4),maps=[],validated=new Set();const encodings=reader.u16(cmap.offset+2);if(4+encodings*8>cmap.length)
1650
+ throw new TypeError("Invalid TrueType cmap directory.");for(let i=0;i<encodings;i++){const p=cmap.offset+4+i*8,platform=reader.u16(p),encoding=reader.u16(p+2),relative=reader.u32(p+4);if(platform!==0&&!(platform===3&&(encoding===1||encoding===10)))
1651
+ continue;if(relative+4>cmap.length)
1652
+ throw new TypeError("Invalid cmap subtable offset.");const offset=cmap.offset+relative,type=reader.u16(offset);if(type!==4&&type!==12)
1653
+ continue;if(validated.has(offset))
1654
+ continue;if(type===12&&relative+16>cmap.length)
1655
+ throw new TypeError("Truncated cmap format 12.");const length=type===12?reader.u32(offset+4):reader.u16(offset+2);if(length<(type===12?16:16)||relative+length>cmap.length)
1656
+ throw new TypeError("Invalid cmap length.");if(type===12){const groups=reader.u32(offset+12);if(16+groups*12>length)
1657
+ throw new TypeError("Invalid cmap groups.");let previous=-1;for(let j=0;j<groups;j++){const q=offset+16+j*12,start=reader.u32(q),end=reader.u32(q+4),glyph=reader.u32(q+8);if(start<=previous||start>end||end>0x10ffff||glyph+end-start>=glyphCount)
1658
+ throw new TypeError("Invalid cmap scalar/glyph group.");previous=end;if((j&1023)===1023)
1659
+ yield}}
1660
+ else{const segments=reader.u16(offset+6)/ 2;
1661
+ if(!Number.isInteger(segments)||!segments||16+segments*8>length)
1662
+ throw new TypeError("Invalid cmap segments.");let previous=-1;for(let j=0;j<segments;j++){const end=reader.u16(offset+14+j*2),start=reader.u16(offset+16+segments*2+j*2);if(end<=previous||start>end)
1663
+ throw new TypeError("Invalid cmap segment ordering.");previous=end;if((j&1023)===1023)
1664
+ yield}}
1665
+ validated.add(offset);maps.push({offset,length})}
1666
+ const cmaps=maps.sort((a,b)=>reader.u16(b.offset)- reader.u16(a.offset));if(!maps.length)
1667
+ throw new NotSupportedError("TrueType font needs a Unicode cmap format 4 or 12.");return{tables,glyphCount,units,ascent,descent,bbox,widths,offsets,canSubset,cmaps}}
1668
+ const _exports=Object.freeze({TrueTypeFont:TrueTypeFont});_modules.set("2e1fa1582af797386e2e2914c0a27237309b1692a3cc2be688f46590eb74480d",_exports);return _exports})();const _m63=_modules.get("d9c1509dff0538488752433e47cd0927ece5f93c559ad0e32dc56602dfd44596")??(()=>{const{TrueTypeFont}=_m64;const{beginTask,checkAbort}=_m4;const programs=new WeakMap();const fontBrand=Symbol.for("@evotecit/officeimo/PdfFont");function fontProgram(font){let program=programs.get(font);if(!program){if(!(font instanceof PdfFont)||typeof font.toBytes!=="function")
1669
+ throw new TypeError("Invalid PdfFont instance.");const copied=new PdfFont(font.toBytes());program=programs.get(copied);programs.set(font,program)}
1670
+ return program}
1671
+ class PdfFont{static[Symbol.hasInstance](value){return!!value&&typeof value==="object"&&value[fontBrand]===true}
1672
+ brand=true;constructor(bytes){if(!(bytes instanceof Uint8Array))
1673
+ throw new TypeError("PdfFont requires TrueType bytes as a Uint8Array.");if(bytes.length>64*1024*1024)
1674
+ throw new RangeError("A TrueType font must not exceed 64 MiB.");programs.set(this,new TrueTypeFont(bytes.slice()));void this.brand;Object.defineProperty(this,fontBrand,{value:true});Object.freeze(this)}
1675
+ static async create(bytes,options={}){checkAbort(options.signal);if(!(bytes instanceof Uint8Array))
1676
+ throw new TypeError("PdfFont requires TrueType bytes as a Uint8Array.");const maximum=options.maxBytes??16*1024*1024;if(!Number.isSafeInteger(maximum)||maximum<0||maximum>64*1024*1024)
1677
+ throw new RangeError("Font preparation maxBytes must be a nonnegative safe integer at most 64 MiB.");if(bytes.length>maximum)
1678
+ throw new RangeError("TrueType font exceeds the preparation byte limit.");beginTask();const program=await TrueTypeFont.create(new Uint8Array(bytes),options.signal);checkAbort(options.signal);const font=Object.create(PdfFont.prototype);programs.set(font,program);Object.defineProperty(font,"brand",{value:true});Object.defineProperty(font,fontBrand,{value:true});Object.freeze(font);return font}
1679
+ toBytes(){return fontProgram(this).bytes.slice()}}
1680
+ const _exports=Object.freeze({fontProgram:fontProgram,PdfFont:PdfFont});_modules.set("d9c1509dff0538488752433e47cd0927ece5f93c559ad0e32dc56602dfd44596",_exports);return _exports})();const _m68=_modules.get("1ed4965a6e2963a91190baa8a58ada8ce0edde8fe653bcb6609002e872af0d61")??(()=>{const helveticaWidths=new Map([[32,[278,278]],[33,[278,333]],[34,[355,474]],[35,[556,556]],[36,[556,556]],[37,[889,889]],[38,[667,722]],[39,[191,238]],[40,[333,333]],[41,[333,333]],[42,[389,389]],[43,[584,584]],[44,[278,278]],[45,[333,333]],[46,[278,278]],[47,[278,278]],[48,[556,556]],[49,[556,556]],[50,[556,556]],[51,[556,556]],[52,[556,556]],[53,[556,556]],[54,[556,556]],[55,[556,556]],[56,[556,556]],[57,[556,556]],[58,[278,333]],[59,[278,333]],[60,[584,584]],[61,[584,584]],[62,[584,584]],[63,[556,611]],[64,[1015,975]],[65,[667,722]],[66,[667,722]],[67,[722,722]],[68,[722,722]],[69,[667,667]],[70,[611,611]],[71,[778,778]],[72,[722,722]],[73,[278,278]],[74,[500,556]],[75,[667,722]],[76,[556,611]],[77,[833,833]],[78,[722,722]],[79,[778,778]],[80,[667,667]],[81,[778,778]],[82,[722,722]],[83,[667,667]],[84,[611,611]],[85,[722,722]],[86,[667,667]],[87,[944,944]],[88,[667,667]],[89,[667,667]],[90,[611,611]],[91,[278,333]],[92,[278,278]],[93,[278,333]],[94,[469,584]],[95,[556,556]],[96,[333,333]],[97,[556,556]],[98,[556,611]],[99,[500,556]],[100,[556,611]],[101,[556,556]],[102,[278,333]],[103,[556,611]],[104,[556,611]],[105,[222,278]],[106,[222,278]],[107,[500,556]],[108,[222,278]],[109,[833,889]],[110,[556,611]],[111,[556,611]],[112,[556,611]],[113,[556,611]],[114,[333,389]],[115,[500,556]],[116,[278,333]],[117,[556,611]],[118,[500,556]],[119,[722,778]],[120,[500,556]],[121,[500,556]],[122,[500,500]],[123,[334,389]],[124,[260,280]],[125,[334,389]],[126,[584,584]],[161,[333,333]],[162,[556,556]],[163,[556,556]],[164,[556,556]],[165,[556,556]],[166,[260,280]],[167,[556,556]],[168,[333,333]],[169,[737,737]],[170,[370,370]],[171,[556,556]],[172,[584,584]],[174,[737,737]],[175,[333,333]],[176,[400,400]],[177,[584,584]],[178,[333,333]],[179,[333,333]],[180,[333,333]],[181,[556,611]],[182,[537,556]],[183,[278,278]],[184,[333,333]],[185,[333,333]],[186,[365,365]],[187,[556,556]],[188,[834,834]],[189,[834,834]],[190,[834,834]],[191,[611,611]],[192,[667,722]],[193,[667,722]],[194,[667,722]],[195,[667,722]],[196,[667,722]],[197,[667,722]],[198,[1000,1000]],[199,[722,722]],[200,[667,667]],[201,[667,667]],[202,[667,667]],[203,[667,667]],[204,[278,278]],[205,[278,278]],[206,[278,278]],[207,[278,278]],[208,[722,722]],[209,[722,722]],[210,[778,778]],[211,[778,778]],[212,[778,778]],[213,[778,778]],[214,[778,778]],[215,[584,584]],[216,[778,778]],[217,[722,722]],[218,[722,722]],[219,[722,722]],[220,[722,722]],[221,[667,667]],[222,[667,667]],[223,[611,611]],[224,[556,556]],[225,[556,556]],[226,[556,556]],[227,[556,556]],[228,[556,556]],[229,[556,556]],[230,[889,889]],[231,[500,556]],[232,[556,556]],[233,[556,556]],[234,[556,556]],[235,[556,556]],[236,[278,278]],[237,[278,278]],[238,[278,278]],[239,[278,278]],[240,[556,611]],[241,[556,611]],[242,[556,611]],[243,[556,611]],[244,[556,611]],[245,[556,611]],[246,[556,611]],[247,[584,584]],[248,[611,611]],[249,[556,611]],[250,[556,611]],[251,[556,611]],[252,[556,611]],[253,[500,556]],[254,[556,611]],[255,[500,556]],[256,[667,722]],[257,[556,556]],[258,[667,722]],[259,[556,556]],[260,[667,722]],[261,[556,556]],[262,[722,722]],[263,[500,556]],[268,[722,722]],[269,[500,556]],[270,[722,722]],[271,[643,743]],[272,[722,722]],[273,[556,611]],[274,[667,667]],[275,[556,556]],[278,[667,667]],[279,[556,556]],[280,[667,667]],[281,[556,556]],[282,[667,667]],[283,[556,556]],[286,[778,778]],[287,[556,611]],[290,[778,778]],[291,[556,611]],[298,[278,278]],[299,[278,278]],[302,[278,278]],[303,[222,278]],[304,[278,278]],[305,[278,278]],[310,[667,722]],[311,[500,556]],[313,[556,611]],[314,[222,278]],[315,[556,611]],[316,[222,278]],[317,[556,611]],[318,[299,400]],[321,[556,611]],[322,[222,278]],[323,[722,722]],[324,[556,611]],[325,[722,722]],[326,[556,611]],[327,[722,722]],[328,[556,611]],[332,[778,778]],[333,[556,611]],[336,[778,778]],[337,[556,611]],[338,[1000,1000]],[339,[944,944]],[340,[722,722]],[341,[333,389]],[342,[722,722]],[343,[333,389]],[344,[722,722]],[345,[333,389]],[346,[667,667]],[347,[500,556]],[350,[667,667]],[351,[500,556]],[352,[667,667]],[353,[500,556]],[354,[611,611]],[355,[278,333]],[356,[611,611]],[357,[317,389]],[362,[722,722]],[363,[556,611]],[366,[722,722]],[367,[556,611]],[368,[722,722]],[369,[556,611]],[370,[722,722]],[371,[556,611]],[376,[667,667]],[377,[611,611]],[378,[500,500]],[379,[611,611]],[380,[500,500]],[381,[611,611]],[382,[500,500]],[402,[556,556]],[536,[667,667]],[537,[500,556]],[710,[333,333]],[711,[333,333]],[728,[333,333]],[729,[333,333]],[730,[333,333]],[731,[333,333]],[732,[333,333]],[733,[333,333]],[8211,[556,556]],[8212,[1000,1000]],[8216,[222,278]],[8217,[222,278]],[8218,[222,278]],[8220,[333,500]],[8221,[333,500]],[8222,[333,500]],[8224,[556,556]],[8225,[556,556]],[8226,[350,350]],[8230,[1000,1000]],[8240,[1000,1000]],[8249,[333,333]],[8250,[333,333]],[8260,[167,167]],[8364,[556,556]],[8482,[1000,1000]],[8706,[476,494]],[8710,[612,612]],[8721,[600,600]],[8722,[584,584]],[8730,[453,549]],[8800,[549,549]],[8804,[549,549]],[8805,[549,549]],[9674,[471,494]],[64257,[500,611]],[64258,[500,611]],]);const _exports=Object.freeze({helveticaWidths:helveticaWidths});_modules.set("1ed4965a6e2963a91190baa8a58ada8ce0edde8fe653bcb6609002e872af0d61",_exports);return _exports})();const _m67=_modules.get("59911f0fe023545e9e97521b268551078bdc4c5f303e446a13b7d52f905e8070")??(()=>{const{OfficeIMOError}=_m2;const{PdfFont,fontProgram}=_m63;const{helveticaWidths}=_m68;const winAnsiExtras=new Map([0x20ac,0,0x201a,0x192,0x201e,0x2026,0x2020,0x2021,0x2c6,0x2030,0x160,0x2039,0x152,0,0x17d,0,0,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x2dc,0x2122,0x161,0x203a,0x153,0,0x17e,0x178].map((cp,i)=>[cp,i+128]));function standardCode(scalar){if((scalar>=32&&scalar<=126)||(scalar>=160&&scalar<=255))
1681
+ return scalar;return scalar?winAnsiExtras.get(scalar):undefined}
1682
+ function resolveScalar(scalar,program,bold){if(scalar>=0xd800&&scalar<=0xdfff)
1683
+ return{supported:false,code:"unpaired-surrogate",message:"PDF text contains an unpaired UTF-16 surrogate."};if(scalar<32||(scalar>=127&&scalar<160))
1684
+ return{supported:false,code:"unsupported-control",message:"PDF text contains an unsupported control character."};const character=String.fromCodePoint(scalar);if(/[\p{Mark}\p{Format}]/u.test(character) || !/[\p{Script=Latin}\p{Script=Greek}\p{Script=Cyrillic}\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Common}]/u.test(character) ||
1685
+ (scalar>=0x1100&&scalar<=0x11ff)||(scalar>=0x1f3fb&&scalar<=0x1f3ff))
1686
+ return{supported:false,code:"unsupported-layout",message:"This PDF table writer supports Unicode scalar layout; complex shaping, combining sequences and bidirectional text require a shaping-capable writer."};if(!program){if(standardCode(scalar)===undefined)
1687
+ return{supported:false,code:"embedded-font-required",message:"Text U+"+scalar.toString(16).toUpperCase()+ " needs an embedded Unicode TrueType font; supply fonts.regular."};const metric=helveticaWidths.get(scalar===160?32:scalar===173?45:scalar);if(!metric)
1688
+ return{supported:false,code:"missing-glyph",message:"Standard font has no metric for this character."};return{supported:true,width:metric[bold?1:0]}}
1689
+ let glyph=program.glyph(scalar);if(!glyph&&scalar===0x202f){const thin=program.glyph(0x2009);if(thin&&program.offsets[thin]===program.offsets[thin+1])
1690
+ glyph=thin}
1691
+ if(!glyph)
1692
+ return{supported:false,code:"missing-glyph",message:"The supplied font has no glyph for U+"+scalar.toString(16).toUpperCase()+ "."};return{supported:true,glyph,width:program.widths[glyph]}}
1693
+ function validateFonts(fonts,maxBytes){if(!fonts)
1694
+ return;if(!(fonts.regular instanceof PdfFont))
1695
+ throw new TypeError("fonts.regular must be a PdfFont.");const unique=new Set();for(const[key,font]of Object.entries(fonts)){if(!["regular","bold","italic","boldItalic"].includes(key)||!(font instanceof PdfFont))
1696
+ throw new TypeError("Invalid PDF font family.");unique.add(font)}
1697
+ if(maxBytes!==undefined&&[...unique].reduce((n,f)=>n+fontProgram(f).bytes.length,0)>maxBytes)
1698
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxFontBytes exceeded.")}
1699
+ function selectFont(fonts,bold,italic){const exact=fonts&&(bold&&italic?fonts.boldItalic:bold?fonts.bold:italic?fonts.italic:fonts.regular);const font=exact??fonts?.regular;return{font,syntheticBold:!!font&&bold&&!exact,syntheticItalic:!!font&&italic&&!exact}}
1700
+ const _exports=Object.freeze({standardCode:standardCode,resolveScalar:resolveScalar,validateFonts:validateFonts,selectFont:selectFont});_modules.set("59911f0fe023545e9e97521b268551078bdc4c5f303e446a13b7d52f905e8070",_exports);return _exports})();const _m62=_modules.get("4d4736e6b8e2aaecc6f6c1b124b7e6bc0a5e141dcc725edf0ad4847d87fca1b3")??(()=>{const{NotSupportedError,OfficeIMOError}=_m2;const{fontProgram}=_m63;const{resolveScalar,selectFont,standardCode,validateFonts}=_m67;const{pdfNumber,unicodeHex}=_m60;const{checkAbort,pause,taskYieldDue}=_m4;const hexBytes=Object.freeze(Array.from({length:256},(_,byte)=>byte.toString(16).padStart(2,"0")));function cidHex(cid){return hexBytes[cid>>>8]+ hexBytes[cid&255]}
1701
+ class PdfFontResource{index;bold;italic;font;shared;signal;name;object;program;syntheticBold;syntheticItalic;mappings=new Map();standardWidths=new Map();constructor(index,bold,italic,font,objects,syntheticBold,syntheticItalic,shared,signal){this.index=index;this.bold=bold;this.italic=italic;this.font=font;this.shared=shared;this.signal=signal;this.name=shared?.name??"F"+index;this.object=shared?.object??objects.reserve();this.program=font?fontProgram(font):undefined;this.syntheticBold=syntheticBold;this.syntheticItalic=syntheticItalic}
1702
+ width(scalar){if(this.shared)
1703
+ return this.shared.width(scalar);if(this.program){const existing=this.mappings.get(scalar);if(existing)
1704
+ return existing.width}
1705
+ else{const standard=this.standardWidths.get(scalar);if(standard!==undefined)
1706
+ return standard}
1707
+ const resolved=resolveScalar(scalar,this.program,this.bold);if(!resolved.supported){if(resolved.code==="unpaired-surrogate")
1708
+ throw new TypeError(resolved.message);throw new NotSupportedError(resolved.message)}
1709
+ if(!this.program){this.standardWidths.set(scalar,resolved.width);return resolved.width}
1710
+ if(this.mappings.size>=65535)
1711
+ throw new OfficeIMOError("RESOURCE_LIMIT","A PDF font supports at most 65,535 distinct Unicode scalars.");const cid=this.mappings.size+1;const mapping={cid,hex:cidHex(cid),glyph:resolved.glyph,width:resolved.width,text:String.fromCodePoint(scalar)};this.mappings.set(scalar,mapping);return mapping.width}
1712
+ lineHeight(size){return Math.max(1.3,this.program?(this.program.ascent-this.program.descent)/ 1000 + .1 : 1.3) * size;
1713
+ }
1714
+ encode(text){if(this.shared)
1715
+ return this.shared.encode(text);let hex="";for(const char of text){const cp=char.codePointAt(0);if(this.program){let mapping=this.mappings.get(cp);if(!mapping){this.width(cp);mapping=this.mappings.get(cp)}
1716
+ hex +=mapping.hex}
1717
+ else{if(!this.standardWidths.has(cp))
1718
+ this.width(cp);hex +=hexBytes[standardCode(cp)]}}
1719
+ return "<"+hex+">"}
1720
+ encodeGlyph(glyph,text){if(this.shared)
1721
+ return this.shared.encodeGlyph(glyph,text);if(!this.program||!Number.isSafeInteger(glyph)||glyph<=0||glyph>=this.program.glyphCount)
1722
+ throw new TypeError("Invalid shaped TrueType glyph.");const key=glyph+":"+text;let mapping=this.mappings.get(key);if(!mapping){if(this.mappings.size>=65535)
1723
+ throw new OfficeIMOError("RESOURCE_LIMIT","A PDF font supports at most 65,535 distinct CID mappings.");const cid=this.mappings.size+1;mapping={cid,hex:cidHex(cid),glyph,width:this.program.widths[glyph],text};this.mappings.set(key,mapping)}
1724
+ return "<"+mapping.hex+">"}
1725
+ async write(objects,compression){checkAbort(this.signal);if(!this.program){const name="Helvetica" +(this.bold&&this.italic?"-BoldOblique":this.bold?"-Bold":this.italic?"-Oblique":"");await objects.object(this.object,"<< /Type /Font /Subtype /Type1 /BaseFont /"+name+" /Encoding /WinAnsiEncoding >>");return}
1726
+ const program=this.program,entries=[...this.mappings],glyphs=new Set(entries.map(([,m])=>m.glyph));const fontName=(program.canSubset?"OIMOAA+":"")+ "OfficeIMOFont"+this.index;const file=objects.reserve(),descriptor=objects.reserve(),cidFont=objects.reserve(),map=objects.reserve(),unicode=objects.reserve();const characters=new Map();for(const[key,mapping]of entries){if(typeof key==="number")
1727
+ characters.set(key,mapping.glyph);else
1728
+ for(const character of mapping.text){const scalar=character.codePointAt(0),glyph=program.glyph(scalar);if(glyph){characters.set(scalar,glyph);glyphs.add(glyph)}}}
1729
+ const subset=await program.subsetCooperatively(glyphs,characters,this.signal);await objects.stream(file,subset,"/Length1 "+subset.length,compression,true);await objects.object(descriptor,"<< /Type /FontDescriptor /FontName /"+fontName+" /Flags 32 /FontBBox ["+program.bbox.map(pdfNumber).join(" ")+
1730
+ "] /ItalicAngle 0 /Ascent "+pdfNumber(program.ascent)+ " /Descent "+pdfNumber(program.descent)+ " /CapHeight "+pdfNumber(program.ascent)+ " /StemV 80 /FontFile2 "+file+" 0 R >>");const mapping=new Uint8Array((entries.length+1)*2),view=new DataView(mapping.buffer);for(let i=0;i<entries.length;i++){const entry=entries[i][1];view.setUint16(entry.cid*2,entry.glyph);if((i&1023)===1023){if(taskYieldDue())
1731
+ await pause();checkAbort(this.signal)}}
1732
+ await objects.stream(map,mapping,"",compression,true);await objects.object(cidFont,"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /"+fontName +
1733
+ " /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor "+descriptor+" 0 R /CIDToGIDMap "+map+" 0 R" +
1734
+ (entries.length?" /W [1 ["+entries.map(([,m])=>pdfNumber(m.width)).join(" ")+ "]]":"")+ " >>");let cmap="/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /OfficeIMOUnicode def\n/CMapType 2 def\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n";const mapped=entries.filter(([,mapping])=>mapping.text.length);for(let i=0;i<mapped.length;i +=100){const batch=mapped.slice(i,i+100);cmap +=batch.length+" beginbfchar\n";for(const[,m]of batch)
1735
+ cmap +="<"+m.hex+"> <"+unicodeHex(m.text)+ ">\n";cmap +="endbfchar\n";if(taskYieldDue())
1736
+ await pause();checkAbort(this.signal)}
1737
+ cmap +="endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n";await objects.stream(unicode,cmap,"",compression);await objects.object(this.object,"<< /Type /Font /Subtype /Type0 /BaseFont /"+fontName+" /Encoding /Identity-H /DescendantFonts ["+cidFont+" 0 R] /ToUnicode "+unicode+" 0 R >>")}}
1738
+ class PdfFontResources{objects;fonts;maxBytes;signal;resources=[];selections=new Map();programs=new Map();explicitSelections=new Map();registered=new Set();fontBytes=0;constructor(objects,fonts,maxBytes=16*1024*1024,signal){this.objects=objects;this.fonts=fonts;this.maxBytes=maxBytes;this.signal=signal;validateFonts(fonts,maxBytes);for(const font of Object.values(fonts??{}))
1739
+ this.registerFont(font)}
1740
+ registerFont(font){if(this.registered.has(font))
1741
+ return;const bytes=fontProgram(font).bytes.length;if(this.fontBytes+bytes>this.maxBytes)
1742
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxFontBytes exceeded.");this.fontBytes +=bytes;this.registered.add(font)}
1743
+ select(bold=false,italic=false,explicit){if(explicit)
1744
+ this.registerFont(explicit);let selections=this.selections;if(explicit){const found=this.explicitSelections.get(explicit);selections=found??new Map();if(!found)
1745
+ this.explicitSelections.set(explicit,selections)}
1746
+ const key=(bold?2:0)|(italic?1:0),existing=selections.get(key);if(existing)
1747
+ return existing;const{font,syntheticBold,syntheticItalic}=explicit?{font:explicit,syntheticBold:bold,syntheticItalic:italic}:selectFont(this.fonts,bold,italic);const shared=font?this.programs.get(font):undefined;const resource=new PdfFontResource(this.resources.length+1,bold,italic,font,this.objects,syntheticBold,syntheticItalic,shared,this.signal);if(!shared){this.resources.push(resource);if(font)
1748
+ this.programs.set(font,resource)}
1749
+ selections.set(key,resource);return resource}
1750
+ dictionary(){return "<< "+this.resources.map(f=>"/"+f.name+" "+f.object+" 0 R").join(" ")+ " >>"}}
1751
+ const _exports=Object.freeze({PdfFontResource:PdfFontResource,PdfFontResources:PdfFontResources});_modules.set("4d4736e6b8e2aaecc6f6c1b124b7e6bc0a5e141dcc725edf0ad4847d87fca1b3",_exports);return _exports})();const _m70=_modules.get("253db2c0eab1f298fda61fb40a5ddaacbf6ad12a7408ee3d8c12d27f88e7ca27")??(()=>{const{OfficeIMOError}=_m2;const{ExportCell,assertExportValue}=_m5;const{checkAbort,pause,taskYieldDue}=_m4;const{isDate}=_m6;const{defaultBooleanText}=_m21;function pdfBudgetText(text,budget){return budget.limits.maxTextCharacters===undefined?text:text.replace(/[\t\r\n]/g, character => character === "\t" ? " " : "");
1752
+ }
1753
+ function synchronousText(value,name){if(typeof value==="string")
1754
+ return value;if(value&&typeof value.then==="function")
1755
+ void Promise.resolve(value).catch(()=>{});throw new TypeError(name+" must return a synchronous string.")}
1756
+ function displayText(value,options,context){assertExportValue(value);if(value instanceof ExportCell&&value.text!==undefined)
1757
+ return value.text;const raw=value instanceof ExportCell?value.value:value;if(options.formatValue)
1758
+ return synchronousText(options.formatValue(raw,context),"formatValue");return raw==null?"":isDate(raw)?Number.isFinite(raw.getTime())?raw.toISOString():"":typeof raw==="number"&&!Number.isFinite(raw)?"":typeof raw==="boolean"?(options.booleanText??defaultBooleanText)[raw?"true":"false"]:String(raw)}
1759
+ function wrapText(text,font,size,width,maxCharacters,maxLines,wrap=true){const scanner=wrapSteps(text,font,size,width,maxCharacters,maxLines,wrap);while(true){const next=scanner.next();if(next.done)
1760
+ return next.value}}
1761
+ async function wrapTextCooperatively(text,font,size,width,maxCharacters,maxLines,wrap=true,signal){checkAbort(signal);const scanner=wrapSteps(text,font,size,width,maxCharacters,maxLines,wrap);while(true){const next=scanner.next();if(next.done)
1762
+ return next.value;if(taskYieldDue())
1763
+ await pause();checkAbort(signal)}}
1764
+ function*wrapSteps(text,font,size,width,maxCharacters,maxLines,wrap){if(text.length>maxCharacters)
1765
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxCellCharacters exceeded.");const lines=[];let scanned=0;function emit(chars,measure){if(lines.length>=maxLines)
1766
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxRowLines exceeded.");lines.push({text:chars.join(""),width:measure})}
1767
+ for(const paragraph of text.replace(/\r\n?/g, "\n").replace(/\t/g, " ").split("\n")) {
1768
+ let chars=[],advances=[],measured=0,breakAt=-1;for(const character of paragraph){if((++scanned&4095)===0)
1769
+ yield;const advance=font.width(character.codePointAt(0))*size / 1000;
1770
+ if(advance>width+.001)
1771
+ throw new RangeError("PDF column is too narrow for a glyph. Increase page/column width or reduce padding/font size.");if(measured+advance>width+.001){if(!wrap)
1772
+ throw new RangeError("Unwrapped PDF cell exceeds its column width.");const end=breakAt>=0?breakAt+1:chars.length;const used=advances.slice(0,end).reduce((n,a)=>n+a,0);emit(chars.slice(0,end),used);chars=chars.slice(end);advances=advances.slice(end);measured=advances.reduce((n,a)=>n+a,0);breakAt=-1;for(let i=0;i<chars.length;i++)
1773
+ if(chars[i]===" ")
1774
+ breakAt=i;if(measured+advance>width+.001){emit(chars,measured);chars=[];advances=[];measured=0;breakAt=-1}}
1775
+ chars.push(character);advances.push(advance);measured +=advance;if(character===" ")
1776
+ breakAt=chars.length-1}
1777
+ emit(chars,measured);if((++scanned&4095)===0)
1778
+ yield}
1779
+ return lines}
1780
+ const _exports=Object.freeze({pdfBudgetText:pdfBudgetText,synchronousText:synchronousText,displayText:displayText,wrapText:wrapText,wrapTextCooperatively:wrapTextCooperatively});_modules.set("253db2c0eab1f298fda61fb40a5ddaacbf6ad12a7408ee3d8c12d27f88e7ca27",_exports);return _exports})();const _m72=_modules.get("8be3fb029e08d100ce8ffcf50916d5ba7f7bc00d62156cc33815fd58554a9ed6")??(()=>{const{NotSupportedError,OfficeIMOError}=_m2;const{checkAbort,pause,taskYieldDue,withAbort}=_m4;const boundary=(text,at)=>at===0||at===text.length||!(text.charCodeAt(at)>=0xdc00&&text.charCodeAt(at)<=0xdfff&&text.charCodeAt(at-1)>=0xd800&&text.charCodeAt(at-1)<=0xdbff);function parts(captured,maxLines){const result=[{text:"",owners:[]}];let owner=0,end=captured.runs[0]?.text.length??0;for(let offset=0;offset<captured.text.length;){while(offset>=end&&owner<captured.runs.length-1)
1781
+ end +=captured.runs[++owner].text.length;const scalar=captured.text.codePointAt(offset),character=String.fromCodePoint(scalar);offset +=character.length;if(scalar>=0xd800&&scalar<=0xdfff)
1782
+ throw new TypeError("PDF text contains an unpaired UTF-16 surrogate.");if(offset>end&&owner<captured.runs.length-1)
1783
+ throw new NotSupportedError("A shaped presentation boundary cannot split a UTF-16 scalar.");if(character==="\n"||character==="\r"){if(character==="\r"&&captured.text[offset]==="\n")
1784
+ offset++;if(result.length>=maxLines)
1785
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxRowLines exceeded.");result.push({text:"",owners:[]});continue}
1786
+ if(scalar<32&&scalar!==9||scalar>=127&&scalar<160)
1787
+ throw new NotSupportedError("PDF text contains an unsupported control character.");const value=character==="\t"?" ":character,part=result.at(-1);if(part.text.length+value.length>4096)
1788
+ throw new OfficeIMOError("RESOURCE_LIMIT","Shaped PDF text supports at most 4,096 UTF-16 units per physical paragraph.");part.text +=value;for(let i=0;i<value.length;i++)
1789
+ part.owners.push(owner)}
1790
+ return result}
1791
+ function validate(output,part,start,end,faces,captured){if(!Array.isArray(output)||output.length>32768)
1792
+ throw new TypeError("Invalid shaped run array.");let count=0,width=0;const covered=new Uint8Array(end-start),intervals=new Map(),advances=new Map();const copied=[];for(const run of output){if(!run||!Array.isArray(run.glyphs)||!faces.some(face=>face.font===run.font))
1793
+ throw new TypeError("Shaping must use an exact registered PdfFont identity.");count +=run.glyphs.length;if(count>32768)
1794
+ throw new OfficeIMOError("RESOURCE_LIMIT","Shaped PDF text exceeded 32,768 glyphs.");const glyphs=[];for(const glyph of run.glyphs){const{id,clusterStart:a,clusterEnd:b,xAdvance,yAdvance,xOffset,yOffset}=glyph??{};const face=faces[part.owners[a]??-1];if(!face||face.font!==run.font||!face.program||!Number.isSafeInteger(id)||id<=0||id>=face.program.glyphCount)
1795
+ throw new TypeError("Shaping returned an invalid glyph or font identity.");if(!Number.isSafeInteger(a)||!Number.isSafeInteger(b)||a<start||b<=a||b>end||!boundary(part.text,a)||!boundary(part.text,b))
1796
+ throw new TypeError("Shaping returned an invalid UTF-16 cluster range.");if(![xAdvance,yAdvance,xOffset,yOffset].every(value=>Number.isFinite(value)&&Math.abs(value)<=100000)||xAdvance<0||yAdvance!==0)
1797
+ throw new TypeError("Shaping requires finite bounded horizontal glyph metrics.");const first=captured.runs[part.owners[a]];for(let i=a;i<b;i++){const other=captured.runs[part.owners[i]];if(faces[part.owners[i]].font!==run.font||first.style.bold!==other.style.bold||first.style.italic!==other.style.italic||first.style.color!==other.style.color||first.link!==other.link)
1798
+ throw new NotSupportedError("A PDF presentation, font or link boundary cannot split an indivisible shaped cluster.");covered[i-start]=1}
1799
+ const previous=intervals.get(a);if(previous!==undefined&&previous!==b)
1800
+ throw new TypeError("Inconsistent shaped cluster ranges.");intervals.set(a,b);advances.set(a,(advances.get(a)??0)+ xAdvance);width +=xAdvance;glyphs.push(Object.freeze({id,clusterStart:a,clusterEnd:b,xAdvance,yAdvance,xOffset,yOffset}))}
1801
+ copied.push(Object.freeze({font:run.font,glyphs:Object.freeze(glyphs)}))}
1802
+ if(covered.some(value=>!value))
1803
+ throw new TypeError("Shaping omitted logical source text.");const sorted=[...intervals].sort((a,b)=>a[0]- b[0]);let cursor=start;for(const[a,b]of sorted){if(a!==cursor)
1804
+ throw new TypeError("Shaped clusters overlap or leave a logical gap.");cursor=b}
1805
+ return{runs:copied,boundaries:sorted.map(([,b])=>b),advances,width}}
1806
+ async function wrapShapedPdfText(captured,fonts,size,width,settings,wrap){const faces=captured.runs.map(run=>fonts.select(run.style.bold,run.style.italic,run.font)),fallback=fonts.select();if(faces.some((face,i)=>!face.font&&captured.runs[i].text.length))
1807
+ throw new NotSupportedError("Shaped PDF text requires explicit embedded TrueType fonts.");const lines=[],provider=settings.options.textShaper,signal=settings.options.signal;const emit=(part,start,end,shaped)=>{if(lines.length>=settings.limits.maxRowLines)
1808
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxRowLines exceeded.");const segments=[];let lineHeight=fallback.lineHeight(size),ascent=(fallback.program?.ascent??800)*size / 1000;
1809
+ const seen=new Set();let owner=-1,segmentFont,glyphs=[],segmentWidth=0;const flush=()=>{if(owner<0||!segmentFont)
1810
+ return;const run=captured.runs[owner];const logical=glyphs.filter(glyph=>glyph.logicalText).sort((a,b)=>a.clusterStart-b.clusterStart);const actualText=logical.map(glyph=>glyph.logicalText).join("");segments.push({text:actualText,actualText,logicalStart:Math.min(...glyphs.map(glyph=>glyph.clusterStart)),width:segmentWidth*size / 1000, font: segmentFont, glyphs,
1811
+ ...(run.style.color===undefined?{}:{color:run.style.color}),...(run.link?{link:run.link}:{})});glyphs=[];segmentWidth=0};for(const run of shaped?.runs??[])
1812
+ for(const glyph of run.glyphs){const nextOwner=part.owners[glyph.clusterStart],face=faces[nextOwner];if(owner!==nextOwner||segmentFont!==face){flush();owner=nextOwner;segmentFont=face}
1813
+ const logicalText=seen.has(glyph.clusterStart)?"":part.text.slice(glyph.clusterStart,glyph.clusterEnd);seen.add(glyph.clusterStart);glyphs.push({...glyph,logicalText});segmentWidth +=glyph.xAdvance;lineHeight=Math.max(lineHeight,face.lineHeight(size));ascent=Math.max(ascent,face.program.ascent*size / 1000);
1814
+ }
1815
+ flush();const text=part.text.slice(start,end);lines.push({text,actualText:text,segments,width:(shaped?.width??0)*size / 1000, lineHeight, ascent });
1816
+ };for(const part of parts(captured,settings.limits.maxRowLines)){checkAbort(signal);if(!part.text){emit(part,0,0);continue}
1817
+ const runs=[];for(let start=0;start<part.text.length;){const owner=part.owners[start];let end=start+1;while(end<part.text.length&&part.owners[end]===owner)
1818
+ end++;runs.push(Object.freeze({start,end,font:faces[owner].font}));start=end}
1819
+ Object.freeze(runs);let calls=0;const shape=async(start,end)=>{if(++calls>16385)
1820
+ throw new OfficeIMOError("RESOURCE_LIMIT","Shaped line fitting exceeded its bounded work limit.");if(taskYieldDue())
1821
+ await pause();checkAbort(signal);const output=await withAbort(Promise.resolve(provider.shapeLine(Object.freeze({text:part.text,start,end,runs,direction:settings.options.textDirection??"auto",...(signal?{signal}:{})}))),signal);checkAbort(signal);return validate(output,part,start,end,faces,captured)};const initial=await shape(0,part.text.length),boundaries=initial.boundaries;if(!wrap){if(initial.width*size / 1000 > width + .001)
1822
+ throw new RangeError("Unwrapped PDF cell exceeds its column width.");emit(part,0,part.text.length,initial);continue}
1823
+ let from=0;while(from<boundaries.length){const start=from?boundaries[from-1]:0;let to=from,measured=0,space=-1;while(to<boundaries.length){const at=to?boundaries[to-1]:0,advance=initial.advances.get(at)*size / 1000;
1824
+ if(measured+advance>width+.001&&to>from)
1825
+ break;measured +=advance;if(part.text[boundaries[to]- 1]===" ")
1826
+ space=to+1;to++;if(measured>width+.001)
1827
+ break}
1828
+ if(to<boundaries.length&&space>from)
1829
+ to=space;let final=start===0&&to===boundaries.length?initial:await shape(start,boundaries[to-1]);if(final.width*size / 1000 > width + .001) {
1830
+ let low=from+1,high=to-1,best,bestEnd=0;while(low<=high){const mid=Math.floor((low+high)/ 2), candidate = await shape(start, boundaries[mid - 1]);
1831
+ if(candidate.width*size / 1000 <= width + .001) {
1832
+ best=candidate;bestEnd=mid;low=mid+1}
1833
+ else
1834
+ high=mid-1}
1835
+ if(!best)
1836
+ throw new RangeError("PDF column is too narrow for an indivisible shaped cluster.");final=best;to=bestEnd}
1837
+ emit(part,start,boundaries[to-1],final);from=to}}
1838
+ return lines}
1839
+ const _exports=Object.freeze({wrapShapedPdfText:wrapShapedPdfText});_modules.set("8be3fb029e08d100ce8ffcf50916d5ba7f7bc00d62156cc33815fd58554a9ed6",_exports);return _exports})();const _m71=_modules.get("0a1c79b51ac9a164b86197239117df6497f45ca2892b423b1ec77a663ccc1c47")??(()=>{const{NotSupportedError,OfficeIMOError}=_m2;const{copyExportLink}=_m7;const{checkAbort,pause,taskYieldDue}=_m4;const{presentation,color}=_m17;const{wrapShapedPdfText}=_m72;const{PdfFont}=_m63;const{pdfBudgetText}=_m70;function capturePdfText(value,base,settings,fonts,countEmpty=true,reserveBudget=true){if(typeof value==="string"){if(value.length>settings.limits.maxCellCharacters)
1840
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxCellCharacters exceeded.");if(reserveBudget&&(value.length||countEmpty))
1841
+ settings.budget.reserve(1,pdfBudgetText(value,settings.budget).length);return Object.freeze({text:value,runs:Object.freeze([Object.freeze({text:value,style:base})])})}
1842
+ const input=value;if(!Array.isArray(input)){if(input&&typeof input.then==="function")
1843
+ void Promise.resolve(input).catch(()=>{});throw new TypeError("PDF text must be a string or a synchronous array of text runs.")}
1844
+ if(input.length>settings.limits.maxTextRuns)
1845
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxTextRuns exceeded.");let characters=0,budgetCharacters=0;const runs=[];for(const run of input){if(!run||typeof run!=="object"||Object.keys(run).some(key=>!["text","bold","italic","color","link","font"].includes(key)))
1846
+ throw new TypeError("PDF text runs support text, bold, italic, color, link and font.");const{text,bold,italic,color,link,font}=run;if(typeof text!=="string")
1847
+ throw new TypeError("PDF run text must be a string.");if(font!==undefined){if(!(font instanceof PdfFont))
1848
+ throw new TypeError("A PDF run font must be a PdfFont.");fonts.registerFont(font)}
1849
+ characters +=text.length;if(characters>settings.limits.maxCellCharacters)
1850
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxCellCharacters exceeded.");if(reserveBudget)
1851
+ budgetCharacters +=pdfBudgetText(text,settings.budget).length;const style=presentation({...base,...(bold===undefined?{}:{bold}),...(italic===undefined?{}:{italic}),...(color===undefined?{}:{color})});if(settings.options.tagged&&link!==undefined&&text.length&&!text.trim())
1852
+ throw new TypeError("Tagged PDF inline links require nonempty displayed text.");runs.push(Object.freeze({text,style,...(font===undefined?{}:{font}),...(link===undefined?{}:{link:copyExportLink(link)})}))}
1853
+ if(reserveBudget&&(characters||countEmpty))
1854
+ settings.budget.reserve(1,budgetCharacters);return Object.freeze({text:runs.map(run=>run.text).join(""),runs:Object.freeze(runs)})}
1855
+ async function wrapPdfText(captured,fonts,size,width,settings,wrap=true){if(settings.options.textShaper)
1856
+ return wrapShapedPdfText(captured,fonts,size,width,settings,wrap);const{signal}=settings.options,{text,runs}=captured;checkAbort(signal);const single=runs.length===1?runs[0]:undefined;const singleFace=single&&fonts.select(single.style.bold,single.style.italic,single.font);const selectedFaces=singleFace?undefined:runs.map(run=>fonts.select(run.style.bold,run.style.italic,run.font));const fallback=fonts.select();if(single&&text.length>0&&text.length<4096){const run=single,font=singleFace;let widthSoFar=0,fits=true;for(let offset=0;offset<text.length;){const scalar=text.codePointAt(offset);if(scalar===9||scalar===10||scalar===13){fits=false;break}
1857
+ const advance=font.width(scalar)*size / 1000;
1858
+ if(advance>width+.001||widthSoFar+advance>width+.001){fits=false;break}
1859
+ widthSoFar +=advance;offset +=scalar>0xffff?2:1}
1860
+ if(fits){if(settings.limits.maxRowLines<1)
1861
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxRowLines exceeded.");return[{text,width:widthSoFar,segments:[{text,width:widthSoFar,font,...(run.style.color===undefined?{}:{color:run.style.color}),...(run.link?{link:run.link}:{})}],lineHeight:font.lineHeight(size),ascent:Math.max(0,(font.program?.ascent??800)*size / 1000) }];
1862
+ }}
1863
+ const faces=selectedFaces??[singleFace],lines=[];let chars=[],advances=[],owners=[],measured=0,breakAt=-1;let runIndex=0,runEnd=runs[0]?.text.length??0,scanned=0;const emit=(count)=>{if(lines.length>=settings.limits.maxRowLines)
1864
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxRowLines exceeded.");const segments=[];let lineWidth=0,lineHeight=0,ascent=0;for(let begin=0;begin<count;){const owner=owners[begin],run=runs[owner],font=faces[owner];let end=begin+1;while(end<count&&owners[end]===owner)
1865
+ end++;const segmentWidth=advances.slice(begin,end).reduce((total,advance)=>total+advance,0);segments.push({text:chars.slice(begin,end).join(""),width:segmentWidth,font,...(run.style.color===undefined?{}:{color:run.style.color}),...(run.link?{link:run.link}:{})});lineWidth +=segmentWidth;lineHeight=Math.max(lineHeight,font.lineHeight(size));ascent=Math.max(ascent,(font.program?.ascent??800)*size / 1000);
1866
+ begin=end}
1867
+ if(!segments.length){const font=faces[0]??fallback;segments.push({text:"",width:0,font,...(runs[0]?.style.color===undefined?{}:{color:runs[0].style.color})});lineHeight=font.lineHeight(size);ascent=(font.program?.ascent??800)*size / 1000;
1868
+ }
1869
+ lines.push({text:chars.slice(0,count).join(""),width:lineWidth,segments,lineHeight,ascent});chars=chars.slice(count);advances=advances.slice(count);owners=owners.slice(count);measured=advances.reduce((total,advance)=>total+advance,0);breakAt=-1;for(let i=0;i<chars.length;i++)
1870
+ if(chars[i]===" ")
1871
+ breakAt=i};const append=(character,owner)=>{const advance=faces[owner].width(character.codePointAt(0))*size / 1000;
1872
+ if(advance>width+.001)
1873
+ throw new RangeError("PDF column is too narrow for a glyph. Increase page/column width or reduce padding/font size.");if(measured+advance>width+.001){if(!wrap)
1874
+ throw new RangeError("Unwrapped PDF cell exceeds its column width.");emit(breakAt>=0?breakAt+1:chars.length);if(measured+advance>width+.001)
1875
+ emit(chars.length)}
1876
+ chars.push(character);advances.push(advance);owners.push(owner);measured +=advance;if(character===" ")
1877
+ breakAt=chars.length-1};for(let offset=0;offset<text.length;){while(offset>=runEnd&&runIndex<runs.length-1)
1878
+ runEnd +=runs[++runIndex].text.length;const owner=runIndex,scalar=text.codePointAt(offset),character=String.fromCodePoint(scalar);if(offset+character.length>runEnd&&runIndex<runs.length-1){let next=runIndex+1;while(!runs[next].text.length)
1879
+ next++;const first=runs[owner],other=runs[next],firstFace=faces[owner],nextFace=faces[next];const sameFace=firstFace.font===nextFace.font&&(firstFace.font?
1880
+ firstFace.syntheticBold===nextFace.syntheticBold&&firstFace.syntheticItalic===nextFace.syntheticItalic:
1881
+ firstFace.bold===nextFace.bold&&firstFace.italic===nextFace.italic);if(!sameFace||color(first.style.color??"111827")!==color(other.style.color??"111827")||
1882
+ first.link?.target!==other.link?.target||first.link?.tooltip!==other.link?.tooltip)
1883
+ throw new NotSupportedError("A PDF presentation boundary cannot split a UTF-16 scalar.")}
1884
+ offset +=character.length;if(character==="\r"||character==="\n"){if(character==="\r"&&text[offset]==="\n")
1885
+ offset++;emit(chars.length)}
1886
+ else if(character==="\t"){for(let i=0;i<4;i++)
1887
+ append(" ",owner)}
1888
+ else
1889
+ append(character,owner);if((++scanned&4095)===0){if(taskYieldDue())
1890
+ await pause();checkAbort(signal)}}
1891
+ emit(chars.length);return lines}
1892
+ const _exports=Object.freeze({capturePdfText:capturePdfText,wrapPdfText:wrapPdfText});_modules.set("0a1c79b51ac9a164b86197239117df6497f45ca2892b423b1ec77a663ccc1c47",_exports);return _exports})();const _m73=_modules.get("2f40af05ba09102fe440c1d46385b64cecdd233371771796c9ae4e8d523f2cea")??(()=>{const{OfficeIMOError}=_m2;const{wrapPdfText}=_m71;function planTableBands(widths,settings){const policy=settings.options.wideTable;if(typeof policy!=="object")
1893
+ return undefined;const available=settings.page.width-settings.margins.left-settings.margins.right,repeats=settings.repeatedColumns;const repeated=new Set(repeats),rest=widths.map((_,index)=>index).filter(index=>!repeated.has(index));const prefix=repeats.reduce((sum,index)=>sum+widths[index],0);if(prefix>available+.001)
1894
+ throw new RangeError("Repeated PDF columns exceed the printable width.");const groups=[];let current=[...repeats],used=prefix;for(const index of rest){const width=widths[index];if(prefix+width>available+.001)
1895
+ throw new RangeError("A PDF column and its repeated identifiers cannot fit a band.");if(used+width>available+.001){groups.push(current);current=[...repeats];used=prefix}
1896
+ current.push(index);used +=width}
1897
+ if(current.length)
1898
+ groups.push(current);if(groups.length>settings.limits.maxTableBands)
1899
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxTableBands exceeded.");if(settings.limits.maxTableWindowRows<1)
1900
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxTableWindowRows must allow at least one row fragment.");return Object.freeze(groups.map(columns=>{let x=settings.margins.left;const lefts=columns.map(index=>{const left=x;x +=widths[index];return left});return Object.freeze({columns:Object.freeze(columns),lefts:Object.freeze(lefts)})}))}
1901
+ async function projectBandRows(rows,band,widths,settings,fonts){const result=[];for(const row of rows){const cells=[];for(const cell of row.cells){if(cell.span===1){const first=band.columns.indexOf(cell.first);if(first>=0)
1902
+ cells.push({...cell,source:cell.source??cell,first});continue}
1903
+ for(let first=0;first<band.columns.length;){const source=band.columns[first];if(source<cell.first||source>=cell.first+cell.span){first++;continue}
1904
+ let end=first+1;while(end<band.columns.length&&band.columns[end]===band.columns[end-1]+ 1&&band.columns[end]<cell.first+cell.span)
1905
+ end++;const width=band.columns.slice(first,end).reduce((sum,index)=>sum+widths[index],0);const lines=await wrapPdfText(cell.captured,fonts,settings.fontSize,width-settings.padding*2,settings,cell.style.wrapText!==false);cells.push({...cell,source:cell.source??cell,first,span:end-first,width,lines,lineHeight:lines.reduce((height,line)=>Math.max(height,line.lineHeight),cell.font.lineHeight(settings.fontSize))});first=end}}
1906
+ cells.sort((a,b)=>a.first-b.first);result.push({...row,source:row.source??row,cells})}
1907
+ return result}
1908
+ function alignBandBlocks(bands,settings){if(!bands.length||!bands[0].length)
1909
+ return bands;const rows=bands[0].length;const heights=Array.from({length:rows},(_,index)=>Math.max(...bands.map(band=>Math.max(settings.padding*2+band[index].lineHeight,...band[index].cells.filter(cell=>(cell.rowSpan??1)===1).map(cell=>cell.lines.length*cell.lineHeight+settings.padding*2)))));for(const band of bands)
1910
+ for(const[index,row]of band.entries())
1911
+ for(const cell of row.cells){const span=cell.rowSpan??1,height=heights.slice(index,index+span).reduce((sum,value)=>sum+value,0),needed=cell.lines.length*cell.lineHeight+settings.padding*2;if(needed>height)
1912
+ for(let i=index;i<index+span;i++)
1913
+ heights[i]+=(needed-height)/ span;
1914
+ }
1915
+ return bands.map(band=>band.map((row,index)=>({...row,structured:true,height:heights[index],cells:row.cells.map(cell=>({...cell,height:heights.slice(index,index +(cell.rowSpan??1)).reduce((sum,value)=>sum+value,0)}))})))}
1916
+ const _exports=Object.freeze({planTableBands:planTableBands,projectBandRows:projectBandRows,alignBandBlocks:alignBandBlocks});_modules.set("2f40af05ba09102fe440c1d46385b64cecdd233371771796c9ae4e8d523f2cea",_exports);return _exports})();const _m69=_modules.get("ad81357e627d3100e1068a8ce521aa1c1cd65de5c6c6ab36f807a3e5da50d874")??(()=>{const{ExportCell}=_m5;const{copyExportLink}=_m7;const{tableSpans}=_m18;const{createTotals}=_m12;const{presentation,positive}=_m17;const{displayText,pdfBudgetText}=_m70;const{capturePdfText,wrapPdfText}=_m71;const{planTableBands,projectBandRows,alignBandBlocks}=_m73;class PdfTableLayout{settings;fonts;bands;widths;lefts;lineHeight;headings;totals;repeatedColumns;structuredBandRows=new WeakMap();dataPresentations=[];constructor(settings,fonts){this.settings=settings;this.fonts=fonts;const{options,padding,fontSize,page,margins}=settings,columns=options.columns,available=page.width-margins.left-margins.right;this.repeatedColumns=new Set(settings.repeatedColumns);let digit;if(options.columnWidths&&options.columnWidths.length!==columns.length)
1917
+ throw new RangeError("columnWidths must declare one point width per column.");const minimum=typeof options.wideTable==="object"?options.wideTable.minimumColumnWidth??72:0;const widths=columns.map((column,i)=>positive(options.columnWidths?.[i]??Math.max(minimum,column.width===undefined?available / columns.length :
1918
+ positive(column.width,"Column width",255)*(digit??=fonts.select().width(48)*fontSize / 1000) + padding * 2), "PDF column width"));
1919
+ const sum=widths.reduce((n,w)=>n+w,0);if(sum>available+.001&&options.wideTable==="reject")
1920
+ throw new RangeError("Table widths exceed the printable page width.");this.bands=planTableBands(widths,settings);this.widths=!this.bands&&sum>available?widths.map(w=>w*available / sum) : widths;
1921
+ let left=margins.left;this.lefts=this.widths.map(width=>{const position=left;left +=width;return position});if(this.widths.some(w=>w<=padding*2))
1922
+ throw new RangeError("Page is too narrow for this many columns and the requested padding.");this.lineHeight=fonts.select().lineHeight(fontSize);const depth=columns.reduce((n,c)=>Math.max(n,c.groups?.length??0),0);if(depth>16)
1923
+ throw new RangeError("Grouped headings support at most 16 levels.");if(depth&&options.includeHeader===false)
1924
+ throw new TypeError("Grouped headings require leaf headings.");const headings=[];if(options.includeHeader!==false){for(let level=0;level<depth;level++){const cells=[];for(let first=0;first<columns.length;){let last=first;const group=columns[first].groups?.[level]??"",prefix=JSON.stringify(columns[first].groups?.slice(0,level+1));while(group&&last+1<columns.length&&JSON.stringify(columns[last+1].groups?.slice(0,level+1))===prefix)
1925
+ last++;cells.push({first,span:last-first+1,text:group});first=last+1}
1926
+ headings.push(cells)}
1927
+ headings.push(columns.map((c,first)=>({first,span:1,text:c.header})))}
1928
+ this.headings=headings;this.totals=createTotals(columns,options.footer?.totals)}
1929
+ async cell(value,first,span,row,style,ordinaryData=false){const{options,padding,fontSize,budget}=this.settings,column=options.columns[first];const own=value instanceof ExportCell?value.presentation:undefined;const link=value instanceof ExportCell&&value.link?copyExportLink(value.link):undefined;const alternate=ordinaryData&&row%2&&options.alternateRowColor?options.alternateRowColor:undefined;const slot=first*2 +(alternate?1:0),reusable=ordinaryData&&own===undefined;let combined=reusable?this.dataPresentations[slot]:undefined;if(!combined){const rowStyle=ordinaryData?alternate?{background:alternate}:{}:style;combined=presentation({...(column.alignment===undefined?{}:{alignment:column.alignment}),...(column.wrapText===undefined?{}:{wrapText:column.wrapText}),...rowStyle,...own});if(reusable)
1930
+ this.dataPresentations[slot]=combined}
1931
+ const font=this.fonts.select(combined.bold,combined.italic),width=span===1?this.widths[first]:this.widths.slice(first,first+span).reduce((n,w)=>n+w,0);const context={rowIndex:row,columnIndex:first,column},raw=value instanceof ExportCell?value.value:value;let text;if(options.formatRuns&&row>=0&&!(value instanceof ExportCell&&value.text!==undefined)){const runs=options.formatRuns(raw,context);if(!Array.isArray(runs)){if(runs&&typeof runs.then==="function")
1932
+ void Promise.resolve(runs).catch(()=>{});throw new TypeError("formatRuns must return a synchronous array of PDF text runs.")}
1933
+ text=runs}
1934
+ else
1935
+ text=displayText(value,options,context);const captured=capturePdfText(text,combined,this.settings,this.fonts);if(options.tagged&&link&&!captured.text.trim())
1936
+ throw new TypeError("Tagged PDF cell links require nonempty displayed text.");if(link&&captured.runs.some(run=>run.link))
1937
+ throw new TypeError("A PDF cell link cannot be combined with inline run links.");const budgetText=pdfBudgetText(captured.text,budget);if(this.bands)
1938
+ budget.release(1,budgetText.length);else
1939
+ budget.cell(budgetText,budgetText.length);const lines=await wrapPdfText(captured,this.fonts,fontSize,width-padding*2,this.settings,combined.wrapText!==false);return{first,span,width,font,style:combined,lineHeight:lines.reduce((height,line)=>Math.max(height,line.lineHeight),font.lineHeight(fontSize)),...(link?{link}:{}),...(this.bands?{captured}:{}),lines}}
1940
+ row(cells){let lines=1,lineHeight=this.lineHeight;for(let index=0;index<cells.length;index++){const cell=cells[index];lines=Math.max(lines,cell.lines.length);lineHeight=Math.max(lineHeight,cell.lineHeight)}
1941
+ return{cells,lines,lineHeight,height:lines*lineHeight+this.settings.padding*2}}
1942
+ async headers(){if(this.settings.options.headerRows)
1943
+ return this.block(this.settings.options.headerRows,this.settings.options.headerPresentation??{});const{formatValue:_format,...options}=this.settings.options;const rows=[];for(const heading of this.headings){const cells=[];for(const c of heading)
1944
+ cells.push(await this.cell(new ExportCell(c.text,{text:c.text}),c.first,c.span,-1,options.headerPresentation??{}));rows.push(this.row(cells))}
1945
+ return rows}
1946
+ async block(matrix,style){const anchors=tableSpans(matrix,this.settings.options.columns.length);const{formatValue:_format,...literalOptions}=this.settings.options;const cells=[];for(const row of anchors){const laidOut=[];for(const c of row){const value=c.value instanceof ExportCell?c.value:new ExportCell(c.value);const literal=new ExportCell(value.value,{text:displayText(value,literalOptions,{rowIndex:-1,columnIndex:c.first,column:literalOptions.columns[c.first]}),...(value.presentation?{presentation:value.presentation}:{}),...(value.link?{link:value.link}:{})});laidOut.push({...await this.cell(literal,c.first,c.span,-1,style),rowSpan:c.rowSpan})}
1947
+ cells.push(laidOut)}
1948
+ const heights=cells.map(row=>Math.max(this.lineHeight+this.settings.padding*2,...row.filter(c=>c.rowSpan===1).map(c=>c.lines.length*c.lineHeight+this.settings.padding*2)));cells.forEach((row,r)=>row.forEach(c=>{const existing=heights.slice(r,r+c.rowSpan).reduce((n,h)=>n+h,0),needed=c.lines.length*c.lineHeight+this.settings.padding*2;if(needed>existing)
1949
+ for(let i=r;i<r+c.rowSpan;i++)
1950
+ heights[i]+=(needed-existing)/ c.rowSpan;
1951
+ }));return cells.map((row,r)=>({cells:row.map(c=>({...c,height:heights.slice(r,r+c.rowSpan).reduce((n,h)=>n+h,0)})),lines:Math.max(1,Math.ceil((heights[r]- this.settings.padding*2)/ this.lineHeight)), lineHeight: this.lineHeight, height: heights[r], structured: true }));
1952
+ }
1953
+ minimumRowLines(row){let lines=1;if(this.bands)
1954
+ for(const cell of row.cells)
1955
+ if(this.repeatedColumns.has(cell.first))
1956
+ lines=Math.max(lines,cell.lines.length);return lines}
1957
+ minimumRowHeight(row){return this.minimumRowLines(row)*row.lineHeight+this.settings.padding*2}
1958
+ repeatedColumn(index){return this.repeatedColumns.has(index)}
1959
+ async blockHeight(rows){const physical=this.bands?(await this.bandRows(rows,true))[0]:rows;return physical.reduce((height,row)=>height+row.height,0)}
1960
+ async bandRows(rows,structured=false){if(!this.bands)
1961
+ throw new Error("Horizontal bands were not planned.");if(!structured)
1962
+ return this.projectBandRows(rows,false);let prepared=this.structuredBandRows.get(rows);if(!prepared){prepared=this.projectBandRows(rows,true);this.structuredBandRows.set(rows,prepared)}
1963
+ return prepared}
1964
+ async projectBandRows(rows,structured){const projected=[],seen=new Set();for(const band of this.bands){const physical=await projectBandRows(rows,band,this.widths,this.settings,this.fonts);projected.push(physical.map(row=>({...row,cells:row.cells.map(cell=>{const source=cell.source,repeated=seen.has(source);seen.add(source);return repeated?{...cell,semanticArtifact:true}:cell})})))}
1965
+ return structured?alignBandBlocks(projected,this.settings):projected}
1966
+ async data(values,index,footer=false){const{options}=this.settings;const cells=[];for(let column=0;column<options.columns.length;column++){const value=values[column],raw=value instanceof ExportCell?value.value:value;if(!footer)
1967
+ this.totals[column].accept(raw);const cell=await this.cell(value,column,1,index,footer?options.footerPresentation??{}:undefined,!footer);cells.push(!footer&&options.columns[column].rowHeader?{...cell,rowHeader:true}:cell)}
1968
+ return this.row(cells)}
1969
+ async footer(index){if(!this.settings.options.footer)
1970
+ return undefined;if(this.settings.options.footer.rows)
1971
+ return this.block(this.settings.options.footer.rows,this.settings.options.footerPresentation??{});const values=this.totals.map((total,i)=>total.operation?total.value():this.settings.options.footer?.values?.[i]);return[await this.data(values,index,true)]}}
1972
+ const _exports=Object.freeze({PdfTableLayout:PdfTableLayout});_modules.set("ad81357e627d3100e1068a8ce521aa1c1cd65de5c6c6ab36f807a3e5da50d874",_exports);return _exports})();const _m75=_modules.get("9ea74d93c18250e809a7be745444b886bcd5ec924a78e6ab004d649789db1f72")??(()=>{const{OfficeIMOError}=_m2;const{checkAbort}=_m4;class PdfTableBandFlow{layout;headings;painter;caption;continuation;entries=[];height=0;count=0;firstWindow=true;firstCapacity;painted=false;constructor(layout,headings,painter,caption,continuation){this.layout=layout;this.headings=headings;this.painter=painter;this.caption=caption;this.continuation=continuation;this.firstCapacity=painter.firstCapacity}
1973
+ get capacity(){return this.firstWindow?this.firstCapacity:this.painter.continuationCapacity}
1974
+ async accept(entry){if(this.entries.length&&(this.height+entry.height>this.capacity+.001||this.count+entry.count>this.layout.settings.limits.maxTableWindowRows))
1975
+ await this.flush();if(this.firstWindow&&!this.entries.length&&entry.height>this.capacity+.001&&entry.height<=this.painter.firstFullCapacity+.001){await this.painter.moveFirstToFreshPage();this.firstCapacity=this.painter.firstFullCapacity}
1976
+ if(entry.height>this.capacity+.001)
1977
+ throw new RangeError("PDF band window cannot fit the requested table fragment.");this.entries.push(entry);this.height +=entry.height;this.count +=entry.count;if(this.count>=this.layout.settings.limits.maxTableWindowRows)
1978
+ await this.flush()}
1979
+ async row(row,allowFirstFragment=false){const{padding,fontSize,options}=this.layout.settings,minimumLines=this.layout.minimumRowLines(row),minimumHeight=minimumLines*row.lineHeight+padding*2;if(minimumHeight>this.painter.firstFullCapacity+.001||minimumHeight>this.painter.continuationCapacity+.001)
1980
+ throw new RangeError("Repeated PDF identifiers must fit intact below the first and continued band headings/context.");if(this.entries.length&&row.height<=this.painter.continuationCapacity+.001&&row.height>this.capacity-this.height+.001)
1981
+ await this.flush();if(!allowFirstFragment&&this.firstWindow&&!this.entries.length&&row.height>this.capacity+.001&&row.height<=this.painter.firstFullCapacity+.001){await this.painter.moveFirstToFreshPage();this.firstCapacity=this.painter.firstFullCapacity}
1982
+ await this.painter.prepareRow?.(row);let first=0;while(first<row.lines){checkAbort(options.signal);if(this.entries.length&&this.capacity-this.height+.001<minimumHeight)
1983
+ await this.flush();if(this.firstWindow&&!this.entries.length&&this.capacity+.001<minimumHeight){await this.painter.moveFirstToFreshPage();this.firstCapacity=this.painter.firstFullCapacity}
1984
+ if(this.capacity-this.height+.001<minimumHeight)
1985
+ throw new RangeError("PDF band window cannot fit its complete repeated identifiers.");const lines=Math.min(row.lines-first,Math.floor((this.capacity-this.height-padding*2+.001)/ row.lineHeight));
1986
+ if(lines<1)
1987
+ throw new RangeError("PDF page cannot fit a table line below horizontal band headings.");const reservedLines=Math.max(lines,minimumLines),height=reservedLines*row.lineHeight+padding*2;const projected=await this.layout.bandRows([row]);const exhaustedBands=[];const fragments=projected.map((rows,index)=>{let remaining=false;const cells=rows[0].cells.map(cell=>{const source=this.layout.bands[index].columns[cell.first];const repeated=this.layout.repeatedColumn(source),reusable=cell.span===1&&(cell.source?.span??1)===1&&(cell.rowSpan??1)===1&&
1988
+ cell.height===undefined&&first===0&&(repeated||lines>=cell.lines.length);const visible=repeated||reusable?cell.lines:cell.lines.slice(first,first+lines);if(!repeated&&(visible.length>0||cell.link!==undefined))
1989
+ remaining=true;if(reusable)
1990
+ return cell;const{height:_height,...plain}=cell;return{...plain,lines:visible,lineHeight:visible.reduce((value,line)=>Math.max(value,line.lineHeight),cell.font.lineHeight(fontSize)),...(first>0&&repeated?{semanticArtifact:true}:{})}});const fragmentLines=Math.max(1,...cells.map(cell=>cell.lines.length));const lineHeight=Math.max(this.layout.lineHeight,...cells.filter(cell=>cell.lines.length>0).map(cell=>cell.lineHeight));exhaustedBands.push(first>0&&!remaining);return[{...rows[0],cells,lines:fragmentLines,lineHeight,height:fragmentLines*lineHeight+padding*2}]});await this.accept({rows:fragments,height,count:1,completed:first+lines>=row.lines?[row]:[],exhaustedBands});first +=lines;if(first<row.lines)
1991
+ await this.flush()}}
1992
+ async block(rows){const projected=await this.layout.bandRows(rows,true),height=projected[0].reduce((sum,row)=>sum+row.height,0);if(rows.length>this.layout.settings.limits.maxTableWindowRows)
1993
+ throw new OfficeIMOError("RESOURCE_LIMIT","A structured PDF block exceeds maxTableWindowRows.");for(const row of rows)
1994
+ await this.painter.prepareRow?.(row);await this.accept({rows:projected,height,count:rows.length,completed:rows,exhaustedBands:projected.map(()=>false)})}
1995
+ async keptRows(rows,allowFirstFragment=false){const height=rows.reduce((sum,row)=>sum+row.height,0),fits=height<=this.painter.continuationCapacity+.001;if(this.entries.length&&fits&&height>this.capacity-this.height+.001)
1996
+ await this.flush();for(const[index,row]of rows.entries())
1997
+ await this.row(row,!fits&&index===0&&allowFirstFragment)}
1998
+ async flush(forceHeadings=false){if(!this.entries.length&&(!forceHeadings||this.painted||!this.headings.some(rows=>rows.length)))
1999
+ return;for(let band=0;band<this.layout.bands.length;band++){checkAbort(this.layout.settings.options.signal);if(!this.firstWindow&&this.entries.length>0&&this.entries.every(entry=>entry.exhaustedBands[band]))
2000
+ continue;await this.painter.paint(band,this.headings[band],this.entries.flatMap(entry=>entry.rows[band]),this.firstWindow?this.caption:this.continuation,this.firstWindow,band===0)}
2001
+ for(const entry of this.entries)
2002
+ for(const row of entry.completed)
2003
+ await this.painter.completeRow?.(row);this.entries=[];this.height=0;this.count=0;this.firstWindow=false;this.painted=true}}
2004
+ const _exports=Object.freeze({PdfTableBandFlow:PdfTableBandFlow});_modules.set("9ea74d93c18250e809a7be745444b886bcd5ec924a78e6ab004d649789db1f72",_exports);return _exports})();const _m76=_modules.get("9deed79565a5da5009f7a01579df8d6a3f019b78eb7b17d831c7964840e9a6bf")??(()=>{class PdfTableStructure{structure;table;headers;cells=new WeakMap();rows=new WeakMap();columnHeaders=[];ordinaryAttributes=[];headerCount=0;headersPrepared=false;constructor(structure,table,headers){this.structure=structure;this.table=table;this.headers=headers}
2005
+ async prepareHeaders(){if(this.headersPrepared)
2006
+ return;for(let rowIndex=0;rowIndex<this.headers.length;rowIndex++){const row=this.headers[rowIndex],parent=this.structure.element("TR",this.table);this.rows.set(row,parent);for(const cell of row.cells){const header=cell.lines.some(line=>line.text.trim().length>0);const associations=this.associations(cell,rowIndex);const id=this.structure.element(header?"TH":"TD",parent,this.attributes(cell,associations,header?"Column":undefined));this.cells.set(cell,id);if(header){const heading={row:rowIndex,order:this.headerCount++,identifier:await this.structure.identifier(id)};for(let column=cell.first;column<cell.first+cell.span;column++)
2007
+ (this.columnHeaders[column]??=[]).push(heading)}}}
2008
+ this.headersPrepared=true}
2009
+ async completeHeaders(){for(const row of this.headers)
2010
+ await this.completeRow(row)}
2011
+ async prepareRow(row,_kind="data",parent=this.table,rowHeaderIndex){const existing=this.rows.get(row);if(existing!==undefined)
2012
+ return row.cells.map(cell=>this.cells.get(cell));const rowId=this.structure.element("TR",parent);this.rows.set(row,rowId);const ids=row.cells.map((cell,index)=>{const header=rowHeaderIndex===undefined?cell.rowHeader===true:index===rowHeaderIndex;const id=this.structure.element(header?"TH":"TD",rowId);this.cells.set(cell,id);return id});let rowHeaders;for(let index=0;index<ids.length;index++)
2013
+ if(rowHeaderIndex===undefined?row.cells[index].rowHeader===true:index===rowHeaderIndex)
2014
+ (rowHeaders??=[]).push(await this.structure.identifier(ids[index]));for(let index=0;index<row.cells.length;index++){const cell=row.cells[index];if(!rowHeaders&&cell.span===1&&(cell.rowSpan??1)===1){const attributes=this.ordinaryAttributes[cell.first]??=
2015
+ await this.structure.attributeReference(this.attributeDictionary(cell,this.associations(cell)));this.structure.setAttributes(ids[index],attributes);continue}
2016
+ const associations=this.associations(cell);const header=rowHeaderIndex===undefined?cell.rowHeader===true:index===rowHeaderIndex;if(!header&&rowHeaders)
2017
+ associations.push(...rowHeaders);this.structure.setAttributes(ids[index],this.attributes(cell,associations,header?"Row":undefined))}
2018
+ return ids}
2019
+ owner(cell){return this.cells.get(cell)}
2020
+ async completeRow(row){await this.structure.complete(this.rows.get(row))}
2021
+ async finish(){await this.completeHeaders();await this.structure.complete(this.table)}
2022
+ associations(cell,beforeRow=Number.POSITIVE_INFINITY){if(cell.span===1)
2023
+ return(this.columnHeaders[cell.first]??[]).filter(header=>header.row<beforeRow).map(header=>header.identifier);const headers=new Set();for(let column=cell.first;column<cell.first+cell.span;column++)
2024
+ for(const header of this.columnHeaders[column]??[])
2025
+ if(header.row<beforeRow)
2026
+ headers.add(header);return[...headers].sort((left,right)=>left.order-right.order).map(header=>header.identifier)}
2027
+ attributes(cell,headers,scope){return " /A "+this.attributeDictionary(cell,headers,scope)}
2028
+ attributeDictionary(cell,headers,scope){return "<< /O /Table" +(scope===undefined?"":" /Scope /"+scope)+
2029
+ (cell.span>1?" /ColSpan "+cell.span:"")+((cell.rowSpan??1)>1?" /RowSpan "+cell.rowSpan:"")+
2030
+ (headers.length?" /Headers ["+headers.map(id=>"("+id+")").join(" ")+ "]":"")+ " >>"}}
2031
+ const _exports=Object.freeze({PdfTableStructure:PdfTableStructure});_modules.set("9deed79565a5da5009f7a01579df8d6a3f019b78eb7b17d831c7964840e9a6bf",_exports);return _exports})();const _m77=_modules.get("09c712096a1028af340e275d5a273e870546413797e71ed709657ad0482ea170")??(()=>{const{OfficeIMOError}=_m2;const{pdfNumber,unicodeHex}=_m60;const encoder=new TextEncoder();function linkAnnotation(link,x,bottom,width,height,maxBytes,structParent,page){const prefix="<< /Type /Annot /Subtype /Link /F 4 /Border [0 0 0] /Rect [" +
2032
+ [x,bottom,x+width,bottom+height].map(pdfNumber).join(" ")+ "]" +
2033
+ (structParent===undefined?"":" /StructParent "+structParent)+(page===undefined?"":" /P "+page+" 0 R")+ " /A << /S /URI /URI <";const suffix="> >>" +(link.tooltip===undefined?"":" /Contents <feff")+ " >>";const fixedBytes=prefix.length+suffix.length +(link.tooltip===undefined?0:link.tooltip.length*4+1);const limit=()=>{throw new OfficeIMOError("RESOURCE_LIMIT","maxPageBytes exceeded.")};if(fixedBytes+link.target.length*2>maxBytes)
2034
+ limit();let uriBytes=0;for(let i=0;i<link.target.length;i++){const code=link.target.charCodeAt(i);if(code<0x80)
2035
+ uriBytes++;else if(code<0x800)
2036
+ uriBytes +=2;else if(code>=0xd800&&code<=0xdbff&&i+1<link.target.length&&
2037
+ link.target.charCodeAt(i+1)>=0xdc00&&link.target.charCodeAt(i+1)<=0xdfff){uriBytes +=4;i++}
2038
+ else
2039
+ uriBytes +=3;if(fixedBytes+uriBytes*2>maxBytes)
2040
+ limit()}
2041
+ let uri="";for(const byte of encoder.encode(link.target))
2042
+ uri +=byte.toString(16).padStart(2,"0");return prefix+uri+"> >>" +
2043
+ (link.tooltip===undefined?"":" /Contents <feff"+unicodeHex(link.tooltip)+ ">")+ " >>"}
2044
+ const _exports=Object.freeze({linkAnnotation:linkAnnotation});_modules.set("09c712096a1028af340e275d5a273e870546413797e71ed709657ad0482ea170",_exports);return _exports})();const _m78=_modules.get("c68d18d668366fb9b96d1b53c79dc6305f84cb83c05e4942fcf1cdf96ed1a73f")??(()=>{const{OfficeIMOError}=_m2;const{unicodeHex}=_m60;const{captureFields}=_m10;function captureBookmark(value,settings){if(value===undefined)
2045
+ return undefined;if(!value||typeof value!=="object")
2046
+ throw new TypeError("PDF bookmark must provide a title and optional level.");const{title,level=1}=value;if(typeof title!=="string"||!title.trim())
2047
+ throw new TypeError("PDF bookmark title must be nonempty text.");if(title.length>settings.limits.maxCellCharacters)
2048
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxCellCharacters exceeded by bookmark title.");if(!Number.isInteger(level)||level<1||level>6)
2049
+ throw new TypeError("PDF bookmark level must be an integer from 1 through 6.");unicodeHex(title);return Object.freeze({title,level})}
2050
+ function captureSection(block,settings){if(!block||block.kind!=="section")
2051
+ throw new TypeError("PDF section boundary required.");if(Object.keys(block).some(key=>!["kind","title","level","includeHeading","bookmark","headingStyle","pageSize","orientation","margins","pageHeader","pageFooter","pageNumbers"].includes(key)))
2052
+ throw new TypeError("PDF sections support title, heading/bookmark controls, page geometry and decorations only.");const{title,level,includeHeading=true,bookmark=true,headingStyle,pageSize,orientation,margins,pageHeader,pageFooter,pageNumbers}=block;const checked=captureBookmark({title,...(level===undefined?{}:{level})},settings);for(const[name,value]of[["includeHeading",includeHeading],["bookmark",bookmark],["pageNumbers",pageNumbers]])
2053
+ if(value!==undefined&&typeof value!=="boolean")
2054
+ throw new TypeError("PDF section "+name+" must be boolean.");if(headingStyle!==undefined&&(typeof headingStyle!=="string"||!headingStyle.trim()))
2055
+ throw new TypeError("PDF section headingStyle must be nonempty text.");return Object.freeze({kind:"section",title:checked.title,level:checked.level,includeHeading,bookmark,...(headingStyle===undefined?{}:{headingStyle}),...(pageSize===undefined?{}:{pageSize:typeof pageSize==="object"?Object.freeze(captureFields(pageSize,["width","height"])):pageSize}),...(orientation===undefined?{}:{orientation}),...(margins===undefined?{}:{margins:typeof margins==="object"?Object.freeze(captureFields(margins,["top","right","bottom","left"])):margins}),...(pageHeader===undefined?{}:{pageHeader}),...(pageFooter===undefined?{}:{pageFooter}),...(pageNumbers===undefined?{}:{pageNumbers})})}
2056
+ const _exports=Object.freeze({captureBookmark:captureBookmark,captureSection:captureSection});_modules.set("c68d18d668366fb9b96d1b53c79dc6305f84cb83c05e4942fcf1cdf96ed1a73f",_exports);return _exports})();const _m79=_modules.get("a66257a32f03d958aa57be4de9da7f80b708cebca26b5cc6404de0ee11bfe052")??(()=>{const{settings}=_m17;function sectionSettings(base,section){const{pageSize,orientation,margins,pageHeader,pageFooter,pageNumbers}=section;const options={...base.options,...(pageSize===undefined?{}:{pageSize}),...(orientation===undefined?{}:{orientation}),...(margins===undefined?{}:{margins}),...(pageHeader===undefined?{}:{pageHeader}),...(pageFooter===undefined?{}:{pageFooter}),...(pageNumbers===undefined?{}:{pageNumbers})};const derived=settings(options,true);return{...base,page:derived.page,margins:derived.margins,options}}
2057
+ const _exports=Object.freeze({sectionSettings:sectionSettings});_modules.set("a66257a32f03d958aa57be4de9da7f80b708cebca26b5cc6404de0ee11bfe052",_exports);return _exports})();const _m74=_modules.get("3ed7114181be5a3066742336da574fef7f2fc04ee6dfc5e64211f3bedad4cab9")??(()=>{const{OfficeIMOError}=_m2;const{checkAbort}=_m4;const{pdfNumber}=_m60;const{color}=_m17;const{PdfTableBandFlow}=_m75;const{PdfTableStructure}=_m76;const{wrapText,wrapTextCooperatively,synchronousText,pdfBudgetText}=_m70;const{linkAnnotation}=_m77;const{unicodeHex}=_m60;const{captureSection,captureBookmark}=_m78;const{sectionSettings}=_m79;class PdfPages{objects;baseSettings;fonts;parent;resources;layout;structure;outlines;references=[];current=0;commands="";commandParts=[];commandBytes=0;annotations=[];hyperlinks=0;y=0;dataTop=0;continuationTop=0;totalPages;numberSettings;activeSettings;pendingPage;bodyAdded=false;sectionCount=0;sectionPages=0;sectionTitle;pendingBookmarks=[];pageNumberWidth=0;colors=new Map();textFont;textSize=0;textColor="";textPrefix="";rectangleLefts;rectangleColumns=[];externalObjects=new Map();bandFlow;bandCellBudget=false;tableElement;tableStructure;activeHeadings;paintedHeaderCells=new WeakSet();paintedHeaderBudgetCells=new WeakSet();summaryRows=new WeakSet();groups=[];continuationCaption;tableCaptionOwner;continuationCaptionPaints=0;constructor(objects,baseSettings,fonts,parent,resources,layout,structure,outlines){this.objects=objects;this.baseSettings=baseSettings;this.fonts=fonts;this.parent=parent;this.resources=resources;this.layout=layout;this.structure=structure;this.outlines=outlines;this.activeSettings=baseSettings}
2058
+ measurePageNumbers(){const settings=this.settings,font=this.fonts.select(),max=settings.limits.maxPages;const digitWidth=Math.max(...Array.from({length:Math.min(10,max)},(_,i)=>font.width(max<10?49+i:48+i)));const countWidth=digitWidth*String(max).length*settings.fontSize / 1000;
2059
+ const labels=settings.options.pageNumberLabels;const literals=wrapText((labels?.prefix??"Page ")+(labels?.separator??" of ")+(labels?.suffix??""),font,settings.fontSize,Number.MAX_SAFE_INTEGER,settings.limits.maxCellCharacters,1,false)[0].width;return literals+countWidth*2+2}
2060
+ get settings(){return this.activeSettings}
2061
+ async ensureStarted(){if(!this.current)
2062
+ await this.start(false)}
2063
+ async beginSection(block){const captured=captureSection(block,this.baseSettings),active=sectionSettings(this.baseSettings,captured);if(++this.sectionCount>this.baseSettings.limits.maxSections)
2064
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxSections exceeded.");if(this.current){if(this.bodyAdded)
2065
+ await this.finishPage();else{this.pendingPage=this.current;this.current=0}}
2066
+ this.activeSettings=active;this.sectionPages=0;this.sectionTitle=captured.title;await this.structure?.beginSection();return captured}
2067
+ addBookmark(bookmark){const captured=captureBookmark(bookmark,this.settings);if((this.outlines?.count??0)+ this.pendingBookmarks.length>=this.settings.limits.maxBookmarks)
2068
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxBookmarks exceeded.");this.settings.budget.cell(captured.title);if(this.current)
2069
+ this.outlines?.add(captured,this.current,this.y);else
2070
+ this.pendingBookmarks.push(captured)}
2071
+ add(command){this.retainPageBytes(command.length);this.commands +=command}
2072
+ retainPageBytes(length){this.commandBytes +=length;if(this.commandBytes>this.settings.limits.maxPageBytes)
2073
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxPageBytes exceeded.")}
2074
+ rgb(hex){let rgb=this.colors.get(hex);if(!rgb){rgb=color(hex);if(this.colors.size<1024)
2075
+ this.colors.set(hex,rgb)}
2076
+ return rgb}
2077
+ artifact(command,type="Layout"){return this.structure?"/Artifact << /Type /"+type+" >> BDC\n"+command+"EMC\n":command}
2078
+ text(text,font,size,x,baseline,foreground="111827",element){const n=pdfNumber;if(font!==this.textFont||size!==this.textSize||foreground!==this.textColor){const shear=font.syntheticItalic?.213:0,rgb=this.rgb(foreground);this.textPrefix="q "+rgb+" rg "+rgb+" RG\nBT /"+font.name+" "+n(size)+ " Tf " +
2079
+ (font.syntheticBold?n(size*.025)+ " w 2 Tr ":"0 Tr ")+ "1 0 "+n(shear)+ " 1 ";this.textFont=font;this.textSize=size;this.textColor=foreground}
2080
+ const command=this.textPrefix+n(x)+ " "+n(baseline)+ " Tm "+font.encode(text)+ " Tj ET Q\n";this.add(this.structure&&element!==undefined?this.structure.mark(element)+ command+"EMC\n":this.artifact(command,"Pagination"))}
2081
+ link(link,x,bottom,width,height,element){if(width<=0)
2082
+ return;if(++this.hyperlinks>this.settings.limits.maxHyperlinks)
2083
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxHyperlinks exceeded.");const id=this.objects.reserve();const parentKey=this.structure&&element!==undefined?this.structure.annotation(element,id):undefined;const annotation=linkAnnotation(link,x,bottom,width,height,this.settings.limits.maxPageBytes-this.commandBytes,parentKey,this.structure?this.current:undefined);this.retainPageBytes(annotation.length);this.annotations.push({id,body:annotation})}
2084
+ inline(line,size,x,baseline,element,annotationParent=element){const lineActualText=!this.structure&&line.actualText!==undefined&&line.actualText.length>0;if(lineActualText)
2085
+ this.add("/Span << /ActualText <FEFF"+unicodeHex(line.actualText)+ "> >> BDC\n");let marks;if(line.actualText!==undefined&&this.structure&&element!==undefined){marks=new Map();for(const segment of[...line.segments].sort((a,b)=>(a.logicalStart??0)-(b.logicalStart??0))){const owner=segment.link?this.structure.link(element,segment.link):element;marks.set(segment,{owner,mark:this.structure.mark(owner,segment.actualText)})}}
2086
+ for(const segment of line.segments){const registered=marks?.get(segment),owner=registered?.owner??(segment.link&&this.structure&&element!==undefined?this.structure.link(element,segment.link):element);if(segment.glyphs){const font=segment.font,n=pdfNumber,shear=font.syntheticItalic?.213:0,rgb=this.rgb(segment.color??"111827");let cursor=x,command="q "+rgb+" rg "+rgb+" RG\nBT /"+font.name+" "+n(size)+ " Tf " +
2087
+ (font.syntheticBold?n(size*.025)+ " w 2 Tr ":"0 Tr ");for(const glyph of segment.glyphs){command +="1 0 "+n(shear)+ " 1 "+n(cursor +(glyph.xOffset+shear*glyph.yOffset)*size / 1000) + " " + n(baseline + glyph.yOffset * size / 1000) + " Tm " + font.encodeGlyph(glyph.id, glyph.logicalText) + " Tj\n";
2088
+ cursor +=glyph.xAdvance*size / 1000;
2089
+ }
2090
+ command +="ET Q\n";this.add(this.structure&&owner!==undefined?(registered?.mark??this.structure.mark(owner,segment.actualText))+ command+"EMC\n":this.artifact(command,"Pagination"))}
2091
+ else
2092
+ this.text(segment.text,segment.font,size,x,baseline,segment.color,owner);if(segment.link){const ascent=(segment.font.program?.ascent??800)*size / 1000;
2093
+ const descent=(segment.font.program?.descent??-200)*size / 1000;
2094
+ const annotationOwner=owner??(this.structure&&annotationParent!==undefined?this.structure.link(annotationParent,segment.link):undefined);this.link(segment.link,x,baseline+descent,segment.width,ascent-descent,annotationOwner)}
2095
+ x +=segment.width}
2096
+ if(lineActualText)
2097
+ this.add("EMC\n")}
2098
+ decorationText(value){if(value===undefined)
2099
+ return "";checkAbort(this.settings.options.signal);return synchronousText(typeof value==="function"?value(Object.freeze({pageNumber:this.references.length,sectionNumber:this.sectionCount||1,sectionPageNumber:this.sectionPages,...(this.sectionTitle===undefined?{}:{sectionTitle:this.sectionTitle})})):value,"Page header/footer")}
2100
+ decoration(text,x,y,width){if(!text)
2101
+ return;this.settings.budget.cell(pdfBudgetText(text,this.settings.budget));const font=this.fonts.select(),lines=wrapText(text,font,this.settings.fontSize,width,this.settings.limits.maxCellCharacters,1,false);this.text(lines[0].text,font,this.settings.fontSize,x,y)}
2102
+ async start(tableHeadings=true,preparedHeadings){if(this.pendingPage===undefined&&this.references.length>=this.settings.limits.maxPages)
2103
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxPages exceeded.");const{page,margins,options,fontSize}=this.settings;const lineHeight=this.fonts.select().lineHeight(fontSize);if(this.pendingPage!==undefined){this.current=this.pendingPage;this.pendingPage=undefined}
2104
+ else{this.current=this.objects.reserve();this.references.push(this.current)}
2105
+ this.commands="";this.commandParts=[];this.annotations=[];this.commandBytes=0;this.bodyAdded=false;this.sectionPages++;if(options.pageNumbers!==false){this.totalPages??=this.objects.reserve();this.numberSettings??=this.settings;if(!this.pageNumberWidth)
2106
+ this.pageNumberWidth=this.measurePageNumbers();if(this.pageNumberWidth>page.width-margins.left-margins.right)
2107
+ throw new RangeError("Page is too narrow for page numbers at the declared maxPages and font size.")}
2108
+ this.structure?.beginPage(this.current);this.y=page.height-margins.top;const header=this.decorationText(options.pageHeader),footer=this.decorationText(options.pageFooter);if(header&&margins.top<lineHeight+4)
2109
+ throw new RangeError("Top margin is too small for a page header.");if((footer||options.pageNumbers!==false)&&margins.bottom<lineHeight+4)
2110
+ throw new RangeError("Bottom margin is too small for page decorations.");const font=this.fonts.select(),centerOffset=((font.program?.ascent??800)+(font.program?.descent??-200))*fontSize / 2000;
2111
+ this.decoration(header,margins.left,page.height-margins.top / 2 - centerOffset, page.width - margins.left - margins.right);
2112
+ const footerWidth=page.width-margins.left-margins.right -(options.pageNumbers!==false?this.pageNumberWidth+this.settings.padding*2:0);if(footerWidth<=0&&footer)
2113
+ throw new RangeError("Page is too narrow for both footer text and page numbers.");this.decoration(footer,margins.left,margins.bottom / 2 - centerOffset, footerWidth);
2114
+ if(options.pageNumbers!==false){const labels=options.pageNumberLabels,suffix=labels?.suffix??"";const x=page.width-margins.right-this.pageNumberWidth+1,y=margins.bottom / 2 - centerOffset, label = (labels?.prefix ?? "Page ") + this.references.length + (labels?.separator ?? " of ");
2115
+ const line=wrapText(label,font,fontSize,this.pageNumberWidth,this.settings.limits.maxCellCharacters,1,false)[0];this.settings.budget.cell(label+suffix);this.text(label,font,fontSize,x,y);this.add(this.artifact("q 1 0 0 1 "+pdfNumber(x+line.width)+ " "+pdfNumber(y)+ " cm /TotalPages Do Q\n","Pagination"))}
2116
+ for(const bookmark of this.pendingBookmarks.splice(0))
2117
+ this.outlines?.add(bookmark,this.current,this.y);if(this.references.length===1){if(options.title)
2118
+ await this.paragraph(options.title,{bold:true},fontSize*1.5,false,1);if(options.messageTop)
2119
+ await this.paragraph(options.messageTop,{},fontSize,false)}
2120
+ const headers=preparedHeadings??(tableHeadings&&this.layout?this.activeHeadings??=await this.layout.headers():[]),headerHeight=headers.reduce((n,h)=>n+h.height,0),continuation=tableHeadings&&this.layout?this.continuationCaption:undefined;if(continuation?.lines.length){if(this.continuationCaptionPaints++===0)
2121
+ this.tableCaptionOwner=this.captionAnnotations(continuation,this.tableCaptionOwner);await this.paragraphs([continuation],headerHeight+lineHeight+this.settings.padding*2,true,{artifact:true,...(this.tableCaptionOwner===undefined?{}:{annotationParent:this.tableCaptionOwner})})}
2122
+ this.continuationTop=page.height-margins.top-headerHeight -(continuation?.height??0);if(this.y-headerHeight-lineHeight-this.settings.padding*2<margins.bottom)
2123
+ throw new RangeError("PDF title and repeated headings leave no room for a data line.");if(tableHeadings&&this.layout&&this.structure&&this.tableElement===undefined){this.tableElement=this.structure.element("Table",this.groupParent);this.tableStructure=new PdfTableStructure(this.structure,this.tableElement,headers);await this.tableStructure.prepareHeaders()}
2124
+ await this.drawHeadings(headers);this.dataTop=this.y}
2125
+ async drawHeadings(headers){for(const header of headers){for(const cell of header.cells)
2126
+ if(!this.bandCellBudget&&this.paintedHeaderBudgetCells.has(cell.source??cell))
2127
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters===undefined?"":cell.lines.map(line=>line.text).join(""));const elements=this.tableStructure?header.cells.map(cell=>this.tableStructure.owner(cell.source??cell)):undefined;const repeated=header.cells.map(cell=>this.paintedHeaderCells.has(cell.source??cell));this.draw(header,0,header.lines,elements,repeated);for(const cell of header.cells){this.paintedHeaderCells.add(cell.source??cell);this.paintedHeaderBudgetCells.add(cell.source??cell)}}}
2128
+ async rowElements(row){const source=row.source??row;return this.tableStructure?.prepareRow(source,"data",this.tableElement,this.summaryRows.has(source)?0:undefined)}
2129
+ draw(row,firstLine,lineCount,elements,repeated=[]){if(!this.layout)
2130
+ throw new Error("A table layout is required before drawing rows.");this.bodyAdded=true;const{padding,fontSize}=this.settings,n=pdfNumber,height=lineCount*row.lineHeight+padding*2,lefts=this.layout.lefts;if(this.rectangleLefts!==lefts){this.rectangleLefts=lefts;this.rectangleColumns=[]}
2131
+ let rectangleHeight,rectangleBottom="",rectangleHeightText="";for(const[index,cell]of row.cells.entries()){if(this.bandCellBudget)
2132
+ this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters===undefined?"":
2133
+ (cell.height===undefined?cell.lines.slice(firstLine,firstLine+lineCount):cell.lines).map(line=>line.text).join(""));const x=lefts[cell.first],cellHeight=cell.height??height;if(cellHeight!==rectangleHeight){rectangleBottom=n(this.y-cellHeight);rectangleHeightText=n(cellHeight);rectangleHeight=cellHeight}
2134
+ let horizontal=this.rectangleColumns[cell.first];if(!horizontal||horizontal.x!==x||horizontal.width!==cell.width){horizontal={x,width:cell.width,left:n(x),widthText:n(cell.width)};this.rectangleColumns[cell.first]=horizontal}
2135
+ const rectangle=horizontal.left+" "+rectangleBottom+" "+horizontal.widthText+" "+rectangleHeightText;if(cell.style.background)
2136
+ this.add(this.artifact("q "+this.rgb(cell.style.background)+ " rg "+rectangle+" re f Q\n"));this.add(this.artifact("q 0.82 0.85 0.89 RG 0.4 w "+rectangle+" re S Q\n"));const element=elements?.[index],artifact=cell.semanticArtifact||repeated[index],owner=cell.link&&this.structure&&element!==undefined?this.structure.link(element,cell.link):element;for(let line=firstLine;line<Math.min(cell.lines.length,cell.height?cell.lines.length:firstLine+lineCount);line++){const text=cell.lines[line],left=cell.style.alignment==="right"?cell.width-padding-text.width:cell.style.alignment==="center"?(cell.width-text.width)/ 2 : padding;
2137
+ this.inline(text,fontSize,x+left,this.y-padding-text.ascent -(line-firstLine)*(row.structured?cell.lineHeight:row.lineHeight),artifact?undefined:owner,owner)}
2138
+ if(cell.link)
2139
+ this.link(cell.link,x,this.y-cellHeight,cell.width,cellHeight,owner)}
2140
+ this.y -=row.structured?row.height:height;this.sealCommands()}
2141
+ async block(rows){if(this.bandFlow)
2142
+ return this.bandFlow.block(rows);const height=rows.reduce((n,row)=>n+row.height,0),bottom=this.settings.margins.bottom;if(height>this.y-bottom){await this.finishPage();await this.start()}
2143
+ if(height>this.dataTop-bottom)
2144
+ throw new RangeError("A structured footer must fit on one page below the repeated headings.");for(const row of rows){const elements=await this.rowElements(row);this.draw(row,0,row.lines,elements);await this.tableStructure?.completeRow(row.source??row)}}
2145
+ async row(row,allowFirstFragment=false){if(this.bandFlow)
2146
+ return this.bandFlow.row(row,allowFirstFragment);const elements=await this.rowElements(row);const{margins,padding}=this.settings,full=this.continuationTop-margins.bottom;if(!allowFirstFragment&&row.height<=full+.001&&row.height>this.y-margins.bottom+.001){await this.finishPage();await this.start()}
2147
+ let first=0;while(first<row.lines){let lines=Math.min(row.lines-first,Math.floor((this.y-margins.bottom-padding*2+.001)/ row.lineHeight));
2148
+ if(lines<=0){await this.finishPage();await this.start();lines=Math.min(row.lines-first,Math.floor((this.y-margins.bottom-padding*2+.001)/ row.lineHeight));
2149
+ }
2150
+ if(lines<=0)
2151
+ throw new RangeError("PDF page cannot fit a table line.");this.draw(row,first,lines,elements);first +=lines;if(first<row.lines){await this.finishPage();await this.start()}}
2152
+ await this.tableStructure?.completeRow(row.source??row)}
2153
+ async keptRows(rows,allowFirstFragment=false){if(this.bandFlow)
2154
+ return this.bandFlow.keptRows(rows,allowFirstFragment);const height=rows.reduce((total,row)=>total+row.height,0),bottom=this.settings.margins.bottom;const fits=height<=this.continuationTop-bottom+.001;if(fits&&height>this.y-bottom+.001){await this.finishPage();await this.start()}
2155
+ for(const[index,row]of rows.entries())
2156
+ await this.row(row,!fits&&index===0&&allowFirstFragment)}
2157
+ async paragraph(text,style={},size=this.settings.fontSize,paginate=true,headingLevel){await this.ensureStarted();const{margins,page,limits}=this.settings,font=this.fonts.select(style.bold,style.italic),lineHeight=font.lineHeight(size);this.settings.budget.cell(pdfBudgetText(text,this.settings.budget));const lines=await wrapTextCooperatively(text,font,size,page.width-margins.left-margins.right,limits.maxCellCharacters,limits.maxRowLines,true,this.settings.options.signal);if(lineHeight>page.height-margins.top-margins.bottom)
2158
+ throw new RangeError("PDF page cannot fit a paragraph line at the selected font metrics.");if(!paginate&&this.y-lines.length*lineHeight-8<margins.bottom)
2159
+ throw new RangeError("PDF title/message exceeds the first page's content area.");const element=this.structure?.element(headingLevel?"H"+headingLevel:"P");for(const line of lines){if(this.y-lineHeight<margins.bottom){await this.finishPage();await this.start(false)}
2160
+ const x=style.alignment==="right"?page.width-margins.right-line.width:style.alignment==="center"?margins.left +(page.width-margins.left-margins.right-line.width)/ 2 : margins.left;
2161
+ this.bodyAdded=true;this.text(line.text,font,size,x,this.y -(font.program?.ascent??800)*size / 1000, style.color, element);
2162
+ this.y -=lineHeight}
2163
+ this.y -=8;await this.structure?.complete(element)}
2164
+ async reserveSpace(height,label="Kept PDF content"){await this.ensureStarted();const{page,margins}=this.settings,full=page.height-margins.top-margins.bottom;if(height>full+.001)
2165
+ throw new RangeError(label+" exceeds a fresh page's content area.");if(height>this.y-margins.bottom+.001)
2166
+ await this.pageBreak()}
2167
+ async paragraphs(paragraphs,nextHeight=0,keepTogether=false,frame={}){const visible=paragraphs.filter(paragraph=>paragraph.lines.length>0);if(!visible.length)
2168
+ return;await this.ensureStarted();const reservations=new Array(visible.length).fill(0);for(let i=visible.length-1;i>=0;i--){const paragraph=visible[i],next=visible[i+1];reservations[i]=paragraph.keepWithNext?next?next.keepTogether||next.keepWithNext?next.height+reservations[i+1]:next.firstHeight:nextHeight:0}
2169
+ if(keepTogether&&visible.length)
2170
+ await this.reserveSpace(visible.reduce((height,paragraph)=>height+paragraph.height,0)+ reservations.at(-1),"Kept PDF paragraph group");for(const[index,paragraph]of visible.entries()){if(paragraph.budgetOnPaint)
2171
+ this.settings.budget.cell(pdfBudgetText(paragraph.text.text,this.settings.budget));if(paragraph.keepTogether||paragraph.keepWithNext)
2172
+ await this.reserveSpace(paragraph.height+reservations[index],"Kept PDF paragraph chain");const{margins,page}=this.settings;if(paragraph.firstHeight>page.height-margins.top-margins.bottom+.001)
2173
+ throw new RangeError("PDF page cannot fit a paragraph line and its leading spacing.");if(this.y-paragraph.firstHeight<margins.bottom)
2174
+ await this.pageBreak();this.y -=paragraph.spaceBefore;if(paragraph.bookmark)
2175
+ this.addBookmark(paragraph.bookmark);const element=frame.artifact?undefined:frame.owner??this.structure?.element(frame.role??(paragraph.headingLevel?"H"+paragraph.headingLevel:"P"),frame.parent??this.groupParent);let firstLine=true;for(const line of paragraph.lines){if(line.lineHeight>page.height-margins.top-margins.bottom+.001)
2176
+ throw new RangeError("PDF page cannot fit a paragraph line at the selected font metrics.");if(this.y-line.lineHeight<margins.bottom)
2177
+ await this.pageBreak();const left=margins.left +(frame.indent??0),width=page.width-margins.right-left;const x=paragraph.style.alignment==="right"?page.width-margins.right-line.width:paragraph.style.alignment==="center"?left +(width-line.width)/ 2 : left;
2178
+ if(firstLine&&frame.marker)
2179
+ this.inline(frame.marker.line,paragraph.size,left-frame.marker.gap-frame.marker.line.width,this.y-line.ascent,frame.marker.owner);this.bodyAdded=true;this.inline(line,paragraph.size,x,this.y-line.ascent,element,frame.annotationParent??element);this.y -=line.lineHeight;firstLine=false}
2180
+ this.y -=paragraph.spaceAfter;if(!frame.keepOpen)
2181
+ await this.structure?.complete(element)}}
2182
+ get groupParent(){return this.groups.at(-1)?.element}
2183
+ async beginGroup(level,heading,minimumNextHeight){if(level!==this.groups.length)
2184
+ throw new Error("PDF analytical groups must open in hierarchical order.");await this.ensureStarted();const element=this.structure?.element("Sect",this.groupParent);this.groups.push({level,headingLevel:heading.headingLevel??level+2,element});await this.paragraphs([heading],minimumNextHeight,true,{role:"H" +(heading.headingLevel??level+2),...(element===undefined?{}:{parent:element})})}
2185
+ async endGroup(level){const current=this.groups.at(-1);if(!current||current.level!==level)
2186
+ throw new Error("PDF analytical groups must close in hierarchical order.");await this.structure?.complete(current.element);this.outlines?.closeGroup(current.headingLevel);this.groups.pop()}
2187
+ summary(row){this.summaryRows.add(row)}
2188
+ async beginTable(layout,preparedHeadings,minimumDataHeight=layout.lineHeight+this.settings.padding*2,caption,continuationCaption,headingsOnNewPageOnly=false,captionArtifact=false,openingContextAlreadyPainted=false){if(layout.bands)
2189
+ return this.beginBands(layout,preparedHeadings,minimumDataHeight,caption,continuationCaption,captionArtifact,openingContextAlreadyPainted);await this.ensureStarted();this.layout=layout;this.paintedHeaderCells=new WeakSet();this.continuationCaption=continuationCaption;this.continuationCaptionPaints=0;this.tableCaptionOwner=undefined;this.tableElement=this.structure?.element("Table",this.groupParent);const headings=preparedHeadings??await layout.headers();this.activeHeadings=headings;const initialHeadings=headingsOnNewPageOnly&&this.bodyAdded&&!this.structure?[]:headings;const height=initialHeadings.reduce((n,row)=>n+row.height,0);if(caption&&!(captionArtifact&&openingContextAlreadyPainted)){await this.reserveSpace(caption.height+height+minimumDataHeight,"Kept PDF table caption and first data fragment");this.tableCaptionOwner=captionArtifact?this.captionAnnotations(caption)
2190
+ :caption.lines.length?this.structure?.element("Caption",this.tableElement):undefined;await this.paragraphs([caption],height+minimumDataHeight,true,captionArtifact
2191
+ ?{artifact:true,...(this.tableCaptionOwner===undefined?{}:{annotationParent:this.tableCaptionOwner})}
2192
+ :{role:"Caption",keepOpen:true,...(this.tableCaptionOwner===undefined?{}:{owner:this.tableCaptionOwner})})}
2193
+ if(this.structure){this.tableStructure=new PdfTableStructure(this.structure,this.tableElement,headings);await this.tableStructure.prepareHeaders()}
2194
+ if(this.y-height-minimumDataHeight<this.settings.margins.bottom){await this.finishPage();await this.start(true,headings);return}
2195
+ this.continuationTop=this.settings.page.height-this.settings.margins.top-headings.reduce((n,row)=>n+row.height,0)-(continuationCaption?.height??0);await this.drawHeadings(initialHeadings);this.dataTop=this.y}
2196
+ async beginBands(layout,preparedHeadings,minimumDataHeight,caption,continuation,captionArtifact,openingContextAlreadyPainted){await this.ensureStarted();const logicalHeadings=preparedHeadings??await layout.headers(),headings=await layout.bandRows(logicalHeadings,true);const headerHeight=headings[0].reduce((sum,row)=>sum+row.height,0),{page,margins,padding}=this.settings;const firstFullCapacity=page.height-margins.top-margins.bottom-headerHeight -(caption?.height??0);const minimum=minimumDataHeight<=firstFullCapacity+.001?minimumDataHeight:layout.lineHeight+padding*2;const continuationCapacity=page.height-margins.top-margins.bottom-headerHeight -(continuation?.height??0);if(continuationCapacity+.001<layout.lineHeight+padding*2)
2197
+ throw new RangeError("PDF band headings and continuation context leave no room for a data line.");let openingContextPainted=captionArtifact&&openingContextAlreadyPainted;if(this.y-margins.bottom-headerHeight -(openingContextPainted?0:caption?.height??0)+ .001<minimum){await this.pageBreak();openingContextPainted=false}
2198
+ const firstCapacity=this.y-margins.bottom-headerHeight -(openingContextPainted?0:caption?.height??0);if(firstCapacity+.001<minimum)
2199
+ throw new RangeError("PDF band caption and headings leave no room for a data line.");let continuationPaints=0;this.tableElement=this.structure?.element("Table",this.groupParent);this.paintedHeaderCells=new WeakSet();let captionElement=this.structure&&caption?.lines.length?captionArtifact?this.captionAnnotations(caption)
2200
+ :this.structure.element("Caption",this.tableElement):undefined;if(this.structure){this.tableStructure=new PdfTableStructure(this.structure,this.tableElement,logicalHeadings)}
2201
+ this.layout=undefined;this.continuationCaption=undefined;this.activeHeadings=undefined;this.bandFlow=new PdfTableBandFlow(layout,headings,{firstCapacity,firstFullCapacity,continuationCapacity,prepareRow:async(row)=>{await this.tableStructure?.prepareHeaders();await this.rowElements(row)},completeRow:async(row)=>{await this.tableStructure?.completeRow(row.source??row)},moveFirstToFreshPage:async()=>{await this.pageBreak();openingContextPainted=false},paint:async(band,headers,rows,currentCaption,firstWindow,firstBand)=>{if(!(firstWindow&&firstBand))
2202
+ await this.pageBreak();const frame=layout.bands[band];this.layout={lefts:frame.lefts,lineHeight:layout.lineHeight,headers:async()=>headers};this.bandCellBudget=true;try{if(currentCaption?.lines.length&&!(firstWindow&&firstBand&&openingContextPainted)){if(!firstWindow&&continuationPaints++===0)
2203
+ captionElement=this.captionAnnotations(currentCaption,captionElement);const annotationParent=captionElement;await this.paragraphs([currentCaption],headerHeight+minimum,true,firstWindow&&firstBand&&!captionArtifact?{role:"Caption",keepOpen:true,...(captionElement===undefined?{}:{owner:captionElement})}
2204
+ :{artifact:true,...(annotationParent===undefined?{}:{annotationParent})})}
2205
+ await this.tableStructure?.prepareHeaders();await this.drawHeadings(headers);this.dataTop=this.y;for(const row of rows){checkAbort(this.settings.options.signal);const elements=this.tableStructure?row.cells.map(cell=>this.tableStructure.owner(cell.source??cell)):undefined;this.draw(row,0,row.lines,elements)}}
2206
+ finally{this.bandCellBudget=false}}},caption,continuation)}
2207
+ async endTable(){if(this.bandFlow){const flow=this.bandFlow;await flow.flush(true);this.bandFlow=undefined}
2208
+ await this.tableStructure?.finish();this.layout=undefined;this.tableElement=undefined;this.tableStructure=undefined;this.activeHeadings=undefined;this.continuationCaption=undefined;this.tableCaptionOwner=undefined;this.continuationCaptionPaints=0;this.y -=8}
2209
+ captionAnnotations(caption,existingOwner){if(!this.structure||!caption.text.runs.some(run=>run.link&&run.text.trim()))
2210
+ return existingOwner;const owner=existingOwner??this.structure.element("Caption",this.tableElement);for(const run of caption.text.runs)
2211
+ if(run.link&&run.text.trim())
2212
+ this.structure.link(owner,run.link,run.text);return owner}
2213
+ async pageBreak(){await this.ensureStarted();await this.finishPage();await this.start(false)}
2214
+ registerXObject(name,id){this.externalObjects.set(name,id)}
2215
+ graphicHeight(width,height){const{page,margins}=this.settings;return height*Math.min(1,(page.width-margins.left-margins.right)/ width, (page.height - margins.top - margins.bottom) / height);
2216
+ }
2217
+ async graphic(width,height,alignment,paint,alternativeText,caption){await this.ensureStarted();const{page,margins}=this.settings,available=page.width-margins.left-margins.right;const scale=Math.min(1,available / width, (page.height - margins.top - margins.bottom) / height);
2218
+ width*=scale;height*=scale;const element=this.structure&&alternativeText!==undefined?this.structure.element("Figure",undefined," /Alt <feff"+unicodeHex(alternativeText)+ ">"):undefined;if(caption){if(alternativeText===undefined)
2219
+ throw new TypeError("A captioned PDF graphic requires alternativeText and cannot be decorative.");await this.reserveSpace(caption.height+height,"Kept PDF graphic and caption");await this.paragraphs([caption],height,true,{role:"Caption",...(element===undefined?{}:{parent:element})})}
2220
+ if(this.y-height<margins.bottom)
2221
+ await this.pageBreak();const left=alignment==="right"?page.width-margins.right-width:alignment==="center"?margins.left +(available-width)/ 2 : margins.left;
2222
+ const command=paint(left,this.y-height,width,height);this.bodyAdded=true;this.add(this.structure&&element!==undefined?this.structure.mark(element)+ command+"EMC\n":this.artifact(command));this.y -=height+8;await this.structure?.complete(element)}
2223
+ async listItem(item,listOwner){await this.ensureStarted();if(this.structure&&listOwner===undefined)
2224
+ throw new Error("A tagged list item requires a logical list owner.");const li=this.structure?.element("LI",listOwner),label=li===undefined?undefined:this.structure.element("Lbl",li),body=li===undefined?undefined:this.structure.element("LBody",li);await this.paragraphs([item.paragraph],0,false,{...(body===undefined?{}:{parent:body}),role:"P",indent:item.indent,marker:{line:item.marker,gap:item.markerGap,...(label===undefined?{}:{owner:label})}});await this.structure?.complete(li)}
2225
+ sealCommands(){if(this.commands){this.commandParts.push(this.commands);this.commands=""}}
2226
+ takeCommands(){this.sealCommands();const content=this.commandParts.join("");this.commandParts=[];return content}
2227
+ async finishPage(){const contents=this.objects.reserve(),{page,options}=this.settings;await this.objects.stream(contents,this.takeCommands(),"",options.compression!==false);const annotations=[];for(const annotation of this.annotations){annotations.push(annotation.id);await this.objects.object(annotation.id,annotation.body)}
2228
+ await this.objects.object(this.current,"<< /Type /Page /Parent "+this.parent+" 0 R /MediaBox [0 0 "+pdfNumber(page.width)+ " "+pdfNumber(page.height)+
2229
+ "] /Resources "+this.resources+" 0 R /Contents "+contents+" 0 R" +
2230
+ (this.structure?.pageDictionary??"")+
2231
+ (annotations.length?" /Annots ["+annotations.map(id=>id+" 0 R").join(" ")+ "]":"")+ " >>");if(this.structure)
2232
+ await this.structure.finishPage();this.annotations=[];this.commandBytes=0;this.current=0;await this.objects.flushBytes()}
2233
+ async finish(){if(this.bandFlow){const flow=this.bandFlow;await flow.flush(true);this.bandFlow=undefined}
2234
+ await this.ensureStarted();await this.tableStructure?.finish();await this.finishPage();if(this.totalPages){const font=this.fonts.select(),count=String(this.references.length),text=count +(this.numberSettings.options.pageNumberLabels?.suffix??""),size=this.numberSettings.fontSize;this.settings.budget.cell(count);const content="BT /"+font.name+" "+pdfNumber(size)+ " Tf 1 0 0 1 0 0 Tm "+font.encode(text)+ " Tj ET\n";const width=wrapText(text,font,size,this.numberSettings.page.width,this.settings.limits.maxCellCharacters,1,false)[0].width;const bottom=(font.program?.bbox[1]??-250)*size / 1000 - 1, top = (font.program?.bbox[3] ?? 1000) * size / 1000 + 1;
2235
+ await this.objects.stream(this.totalPages,content,"/Type /XObject /Subtype /Form /BBox [-1 "+pdfNumber(bottom)+ " "+pdfNumber(width+1)+ " "+pdfNumber(top)+ "] /Resources << /Font "+this.fonts.dictionary()+ " >>",this.settings.options.compression!==false)}}
2236
+ xobjects(){const entries=[...this.externalObjects].map(([name,id])=>"/"+name+" "+id+" 0 R");if(this.totalPages)
2237
+ entries.push("/TotalPages "+this.totalPages+" 0 R");return entries.length?" /XObject << "+entries.join(" ")+ " >>":""}}
2238
+ const _exports=Object.freeze({PdfPages:PdfPages});_modules.set("3ed7114181be5a3066742336da574fef7f2fc04ee6dfc5e64211f3bedad4cab9",_exports);return _exports})();const _m81=_modules.get("7a58e8ccb5164de51db14e39ca9695af6487c354df909509f0ae6bfac8ae3887")??(()=>{class PdfParentTree{objects;root;entries=[];levels=[];lastKey=-1;constructor(objects,root){this.objects=objects;this.root=root}
2239
+ async append(key,value){if(key<=this.lastKey)
2240
+ throw new Error("PDF ParentTree keys must be appended in increasing order.");this.lastKey=key;this.entries.push({key,value});if(this.entries.length===64)
2241
+ await this.leaf()}
2242
+ async leaf(){if(!this.entries.length)
2243
+ return;const id=this.objects.reserve(),first=this.entries[0].key,last=this.entries.at(-1).key;const body="<< /Limits ["+first+" "+last+"] /Nums ["+this.entries.map(entry=>entry.key+" "+entry.value+" 0 R").join(" ")+ "] >>";this.entries.length=0;await this.objects.object(id,body);await this.node({id,first,last},0)}
2244
+ async node(node,level){const nodes=this.levels[level]??=[];nodes.push(node);if(nodes.length===64){const parent=await this.branch(nodes);nodes.length=0;await this.node(parent,level+1)}}
2245
+ async branch(nodes){const id=this.objects.reserve(),first=nodes[0].first,last=nodes.at(-1).last;await this.objects.object(id,"<< /Limits ["+first+" "+last+"] /Kids ["+nodes.map(node=>node.id+" 0 R").join(" ")+ "] >>");return{id,first,last}}
2246
+ async finish(){await this.leaf();for(let level=0;level<this.levels.length-1;level++){const nodes=this.levels[level];if(nodes.length){const parent=await this.branch(nodes);nodes.length=0;await this.node(parent,level+1)}}
2247
+ const nodes=this.levels.at(-1)??[];await this.objects.object(this.root,nodes.length?"<< /Kids ["+nodes.map(node=>node.id+" 0 R").join(" ")+ "] >>":"<< /Nums [] >>")}}
2248
+ const _exports=Object.freeze({PdfParentTree:PdfParentTree});_modules.set("7a58e8ccb5164de51db14e39ca9695af6487c354df909509f0ae6bfac8ae3887",_exports);return _exports})();const _m80=_modules.get("1c1828a3d6dfc2edda674566203e7aa8e97c984114b7928df13cb373859977d0")??(()=>{const{OfficeIMOError}=_m2;const{checkAbort}=_m4;const{unicodeHex}=_m60;const{PdfParentTree}=_m81;function structureChild(child){return typeof child==="number"?(child<0?-child-1+" ":child+" 0 R "):child+" "}
2249
+ function structurePrefix(element){return "<< /Type /StructElem /S /"+element.role+" /P "+element.parent+" 0 R" +
2250
+ (element.markedPage===undefined?"":" /Pg "+element.markedPage+" 0 R")+
2251
+ (element.identifier===undefined?"":" /ID ("+element.identifier+")")+ " /K ["}
2252
+ function compactStructureBody(element,prefix){const remaining=32768-prefix.length-element.attributes.length-4;if(remaining<0)
2253
+ return undefined;let children="";for(const child of element.children){const token=structureChild(child);if(children.length+token.length>remaining)
2254
+ return undefined;children +=token}
2255
+ return prefix+children+"]"+element.attributes+" >>"}
2256
+ class PdfStructureIds{objects;root;entries=[];levels=[];lastKey="";constructor(objects,root){this.objects=objects;this.root=root}
2257
+ async append(key,value){if(key<=this.lastKey)
2258
+ throw new Error("PDF structure IDs must be appended in increasing order.");this.lastKey=key;this.entries.push({key,value});if(this.entries.length===64)
2259
+ await this.leaf()}
2260
+ async leaf(){if(!this.entries.length)
2261
+ return;const id=this.objects.reserve(),first=this.entries[0].key,last=this.entries.at(-1).key;const body="<< /Limits [("+first+") ("+last+")] /Names [" +
2262
+ this.entries.map(entry=>"("+entry.key+") "+entry.value+" 0 R").join(" ")+ "] >>";this.entries.length=0;await this.objects.object(id,body);await this.node({id,first,last},0)}
2263
+ async node(node,level){const nodes=this.levels[level]??=[];nodes.push(node);if(nodes.length===64){const parent=await this.branch(nodes);nodes.length=0;await this.node(parent,level+1)}}
2264
+ async branch(nodes){const id=this.objects.reserve(),first=nodes[0].first,last=nodes.at(-1).last;await this.objects.object(id,"<< /Limits [("+first+") ("+last+")] /Kids [" +
2265
+ nodes.map(node=>node.id+" 0 R").join(" ")+ "] >>");return{id,first,last}}
2266
+ async finish(){await this.leaf();for(let level=0;level<this.levels.length-1;level++){const nodes=this.levels[level];if(nodes.length){const parent=await this.branch(nodes);nodes.length=0;await this.node(parent,level+1)}}
2267
+ const nodes=this.levels.at(-1)??[];await this.objects.object(this.root,nodes.length?"<< /Kids ["+nodes.map(node=>node.id+" 0 R").join(" ")+ "] >>":"<< /Names [] >>")}}
2268
+ class PdfStructure{objects;settings;root;document;parentTree;elements=new Map();parentTreeWriter;annotations=[];links=new WeakMap();identifiers;pageParents=[];pageId=0;pageKey=0;nextParentKey=0;references=0;allocated=0;section;constructor(objects,settings){this.objects=objects;this.settings=settings;this.root=objects.reserve();this.parentTree=objects.reserve();this.parentTreeWriter=new PdfParentTree(objects,this.parentTree);this.document=this.element("Document",this.root)}
2269
+ element(role,parent=this.section??this.document,attributes=""){checkAbort(this.settings.options.signal);if(++this.allocated>this.settings.limits.maxStructureElements)
2270
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxStructureElements exceeded.");const id=this.objects.reserve(),element={id,parent,role,children:[],attributes};this.elements.set(id,element);const owner=this.elements.get(parent);if(role==="Caption"&&owner?.role==="Table")
2271
+ owner.children.unshift(id);else
2272
+ owner?.children.push(id);return id}
2273
+ setAttributes(elementId,attributes){const element=this.elements.get(elementId);if(!element)
2274
+ throw new Error("PDF structure attributes require an open logical owner.");element.attributes=attributes}
2275
+ async attributeReference(dictionary){checkAbort(this.settings.options.signal);const id=this.objects.reserve();await this.objects.object(id,dictionary);return " /A "+id+" 0 R"}
2276
+ async beginSection(){await this.complete(this.section);this.section=this.element("Sect",this.document)}
2277
+ async identifier(elementId){checkAbort(this.settings.options.signal);const element=this.elements.get(elementId);if(!element)
2278
+ throw new Error("PDF structure IDs require an open logical owner.");if(element.identifier!==undefined)
2279
+ return element.identifier;const identifier="e"+String(elementId).padStart(16,"0");this.identifiers??=new PdfStructureIds(this.objects,this.objects.reserve());await this.identifiers.append(identifier,elementId);element.identifier=identifier;return identifier}
2280
+ beginPage(pageId){this.pageId=pageId;this.pageParents=[];this.pageKey=this.nextParentKey++}
2281
+ link(parent,identity,alternativeText){let parents=this.links.get(identity);if(!parents){parents=new Map();this.links.set(identity,parents)}
2282
+ const existing=parents.get(parent);if(existing!==undefined)
2283
+ return existing;const id=this.element("Link",parent,alternativeText===undefined?"":" /Alt <feff"+unicodeHex(alternativeText)+ ">");parents.set(parent,id);const owner=this.elements.get(parent);(owner.linkIdentities??=[]).push(identity);return id}
2284
+ annotation(elementId,annotationId){checkAbort(this.settings.options.signal);const element=this.elements.get(elementId);if(!element||element.role!=="Link")
2285
+ throw new Error("Tagged link annotations require a logical Link owner.");const key=this.nextParentKey++;element.children.push("<< /Type /OBJR /Obj "+annotationId+" 0 R /Pg "+this.pageId+" 0 R >>");this.annotations.push({key,owner:elementId});return key}
2286
+ mark(elementId,actualText){if(++this.references>this.settings.limits.maxMarkedContentReferences)
2287
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxMarkedContentReferences exceeded.");const element=this.elements.get(elementId);if(!element)
2288
+ throw new Error("Marked content requires an open logical owner.");const mcid=this.pageParents.length;this.pageParents.push(elementId);element.markedPage??=this.pageId;element.children.push(element.markedPage===this.pageId?-(mcid+1):
2289
+ "<< /Type /MCR /Pg "+this.pageId+" 0 R /MCID "+mcid+" >>");return "/"+element.role+" << /MCID "+mcid +(actualText===undefined?"":" /ActualText <FEFF"+unicodeHex(actualText)+ ">")+ " >> BDC\n"}
2290
+ get pageDictionary(){return " /StructParents "+this.pageKey+" /Tabs /S"}
2291
+ get catalogDictionary(){return " /MarkInfo << /Marked true >> /Lang <feff"+unicodeHex(this.settings.options.tagged.language)+ "> /StructTreeRoot "+this.root+" 0 R"}
2292
+ async finishPage(){const array=this.objects.reserve();await this.objects.object(array,"["+this.pageParents.map(id=>id+" 0 R").join(" ")+ "]");await this.parentTreeWriter.append(this.pageKey,array);for(const annotation of this.annotations)
2293
+ await this.parentTreeWriter.append(annotation.key,annotation.owner);this.annotations.length=0;this.pageParents=[]}
2294
+ async complete(id){if(id===undefined)
2295
+ return;const element=this.elements.get(id);if(!element)
2296
+ return;for(const child of element.children)
2297
+ if(typeof child==="number"&&child>0&&!this.completeBuffered(child))
2298
+ await this.complete(child);checkAbort(this.settings.options.signal);const prefix=structurePrefix(element),body=compactStructureBody(element,prefix);if(body!==undefined){if(!this.objects.tryCompactObject(id,body))
2299
+ await this.objects.compactObject(id,body)}
2300
+ else
2301
+ await this.objects.object(id,this.body(element,prefix));this.releaseElement(element)}
2302
+ completeBuffered(id){const element=this.elements.get(id);if(!element)
2303
+ return true;for(const child of element.children)
2304
+ if(typeof child==="number"&&child>0&&!this.completeBuffered(child))
2305
+ return false;checkAbort(this.settings.options.signal);const body=compactStructureBody(element,structurePrefix(element));if(body===undefined||!this.objects.tryCompactObject(id,body))
2306
+ return false;this.releaseElement(element);return true}
2307
+ releaseElement(element){if(element.linkIdentities)
2308
+ for(const identity of element.linkIdentities){const parents=this.links.get(identity);parents?.delete(element.id);if(!parents?.size)
2309
+ this.links.delete(identity)}
2310
+ this.elements.delete(element.id)}
2311
+ *body(element,prefix){yield prefix;for(const child of element.children)
2312
+ yield structureChild(child);yield "]"+element.attributes+" >>"}
2313
+ async completeRow(cells){if(cells?.length)
2314
+ await this.complete(this.elements.get(cells[0])?.parent)}
2315
+ async finish(){await this.complete(this.document);await this.parentTreeWriter.finish();await this.identifiers?.finish();await this.objects.object(this.root,"<< /Type /StructTreeRoot /K ["+this.document+" 0 R] /ParentTree " +
2316
+ this.parentTree+" 0 R /ParentTreeNextKey "+this.nextParentKey +
2317
+ (this.identifiers?" /IDTree "+this.identifiers.root+" 0 R":"")+ " >>")}}
2318
+ function graphicAlternative(value,settings){const decorative=value.decorative,alternativeText=value.alternativeText;if(decorative!==undefined&&typeof decorative!=="boolean")
2319
+ throw new TypeError("Graphic decorative must be boolean.");if(alternativeText!==undefined){if(typeof alternativeText!=="string"||!alternativeText.trim())
2320
+ throw new TypeError("Graphic alternativeText must be nonempty text.");if(alternativeText.length>settings.limits.maxCellCharacters)
2321
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxCellCharacters exceeded by graphic alternativeText.");unicodeHex(alternativeText);if(decorative)
2322
+ throw new TypeError("A decorative graphic cannot also have alternativeText.")}
2323
+ if(settings.options.tagged&&alternativeText===undefined&&decorative!==true)
2324
+ throw new TypeError("Tagged PDF graphics require alternativeText or decorative:true.");if(settings.options.tagged&&alternativeText!==undefined)
2325
+ settings.budget.cell(alternativeText);return alternativeText}
2326
+ const _exports=Object.freeze({PdfStructure:PdfStructure,graphicAlternative:graphicAlternative});_modules.set("1c1828a3d6dfc2edda674566203e7aa8e97c984114b7928df13cb373859977d0",_exports);return _exports})();const _m82=_modules.get("52c78ca6833cee7e5a96b657e2c00172d550176daf2c95e742692f8416977bea")??(()=>{const{OfficeIMOError}=_m2;const{checkAbort}=_m4;const{pdfNumber,unicodeHex}=_m60;class PdfOutlines{objects;settings;root;items=[];top=[];stack=[];constructor(objects,settings){this.objects=objects;this.settings=settings}
2327
+ add(bookmark,page,y){checkAbort(this.settings.options.signal);if(this.items.length>=this.settings.limits.maxBookmarks)
2328
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxBookmarks exceeded.");this.root??=this.objects.reserve();const level=bookmark.level??1;while(this.stack.length&&this.stack.at(-1).level>=level)
2329
+ this.stack.pop();const parent=this.stack.at(-1),siblings=parent?.children??this.top,previous=siblings.at(-1);const item={id:this.objects.reserve(),title:bookmark.title,page,y,level,parent:parent?.id??this.root,children:[],previous:previous?.id,next:undefined};if(previous)
2330
+ previous.next=item.id;siblings.push(item);this.items.push(item);this.stack.push(item)}
2331
+ get count(){return this.items.length}
2332
+ closeGroup(level){while(this.stack.length&&this.stack.at(-1).level>=level)
2333
+ this.stack.pop()}
2334
+ get catalogDictionary(){return this.root===undefined?"":" /Outlines "+this.root+" 0 R"}
2335
+ async finish(){if(this.root===undefined)
2336
+ return;const descendants=new Map();for(const item of[...this.items].reverse())
2337
+ descendants.set(item.id,item.children.reduce((n,child)=>n+1+descendants.get(child.id),0));for(const item of this.items){checkAbort(this.settings.options.signal);await this.objects.object(item.id,"<< /Title <feff"+unicodeHex(item.title)+ "> /Parent "+item.parent+" 0 R" +
2338
+ (item.previous===undefined?"":" /Prev "+item.previous+" 0 R")+(item.next===undefined?"":" /Next "+item.next+" 0 R")+
2339
+ (item.children.length?" /First "+item.children[0].id+" 0 R /Last "+item.children.at(-1).id+" 0 R /Count "+descendants.get(item.id):"")+
2340
+ " /Dest ["+item.page+" 0 R /XYZ null "+pdfNumber(item.y)+ " null] >>")}
2341
+ await this.objects.object(this.root,"<< /Type /Outlines /First "+this.top[0].id+" 0 R /Last "+this.top.at(-1).id+" 0 R /Count "+this.items.length+" >>")}}
2342
+ const _exports=Object.freeze({PdfOutlines:PdfOutlines});_modules.set("52c78ca6833cee7e5a96b657e2c00172d550176daf2c95e742692f8416977bea",_exports);return _exports})();const _m59=_modules.get("afdad27eb363e8de0c3bd69ebf358860eb76f5c6fb29f43a87635807cb7fc273")??(()=>{const{PdfObjects,unicodeHex}=_m60;const{PdfFontResources}=_m62;const{PdfTableLayout}=_m69;const{PdfPages}=_m74;const{PdfStructure}=_m80;const{PdfOutlines}=_m82;class PdfWriteSession{settings;objects;fonts;pages;layout;structure;outlines;root;parent;resources;info;constructor(sink,settings,table=false){this.settings=settings;this.objects=new PdfObjects(sink,settings.options.signal,settings.budget.limits.maxOutputBytes,settings.options.compression!==false);this.root=this.objects.reserve();this.parent=this.objects.reserve();this.resources=this.objects.reserve();this.info=this.objects.reserve();this.structure=settings.options.tagged?new PdfStructure(this.objects,settings):undefined;this.outlines=new PdfOutlines(this.objects,settings);this.fonts=new PdfFontResources(this.objects,settings.options.fonts,settings.limits.maxFontBytes,settings.options.signal);this.layout=table?new PdfTableLayout(settings,this.fonts):undefined;this.pages=new PdfPages(this.objects,settings,this.fonts,this.parent,this.resources,this.layout,this.structure,this.outlines)}
2343
+ async start(){await this.objects.text("%PDF-1.7\n");await this.objects.raw(Uint8Array.of(0x25,0xe2,0xe3,0xcf,0xd3,0x0a));if(this.layout?.bands)
2344
+ await this.pages.beginTable(this.layout);else if(this.layout)
2345
+ await this.pages.start(true)}
2346
+ async finish(){const{options}=this.settings,{objects,fonts,pages}=this;await pages.finish();for(const font of fonts.resources)
2347
+ await font.write(objects,options.compression!==false);await objects.object(this.resources,"<< /Font "+fonts.dictionary()+ pages.xobjects()+ " >>");await objects.object(this.parent,"<< /Type /Pages /Count "+pages.references.length+" /Kids ["+pages.references.map(id=>id+" 0 R").join(" ")+ "] >>");if(this.structure)
2348
+ await this.structure.finish();await this.outlines.finish();await objects.object(this.root,"<< /Type /Catalog /Pages "+this.parent+" 0 R" +(this.structure?.catalogDictionary??"")+ this.outlines.catalogDictionary+" >>");await objects.object(this.info,"<< /Producer (OfficeIMO.js)" +(options.title===undefined?"":" /Title <feff"+unicodeHex(options.title)+ ">")+ " >>");await objects.finish(this.root,this.info)}}
2349
+ const _exports=Object.freeze({PdfWriteSession:PdfWriteSession});_modules.set("afdad27eb363e8de0c3bd69ebf358860eb76f5c6fb29f43a87635807cb7fc273",_exports);return _exports})();const _m58=_modules.get("45cf9fd6b6293c1a83bc8554e1bcb5cf119f44701fbad7849f39a712cab5074b")??(()=>{const{BlobByteSink,withDestination}=_m3;const{beginTask,checkAbort,consumeRows,pause,taskYieldDue}=_m4;const{notifyProgress}=_m14;const{createRowProjector}=_m11;const{settings}=_m17;const{PdfWriteSession}=_m59;async function writePdf(rows,configuration){const sink=new BlobByteSink();try{await writePdfTo(rows,sink,configuration);return sink.toBlob("application/pdf")}
2350
+ catch(error){sink.discard();throw error}}
2351
+ async function writePdfTo(rows,destination,configuration){const prepared=settings(configuration),{options,budget}=prepared;beginTask();checkAbort(options.signal);return withDestination(destination,async(sink)=>{const session=new PdfWriteSession(sink,prepared,true),{objects,pages}=session,layout=session.layout;const project=createRowProjector(options.columns,undefined,options.signal);let count=0;await session.start();const completed=()=>{count++;if(count%256===0){notifyProgress(options.onProgress,{phase:"rows",rows:count,bytes:objects.bytes});if(taskYieldDue())
2352
+ return pause().then(()=>{checkAbort(options.signal)})}
2353
+ checkAbort(options.signal)};await consumeRows(rows,options.signal,async(row)=>{budget.row(count+1);const values=project(row,count);return pages.row(await layout.data(values,count)).then(completed)});const footer=await layout.footer(count);if(footer){if(options.footer?.rows)
2354
+ await pages.block(footer);else
2355
+ await pages.row(footer[0])}
2356
+ if(layout.bands)
2357
+ await pages.endTable();if(options.messageBottom)
2358
+ await pages.paragraph(options.messageBottom);await session.finish();notifyProgress(options.onProgress,{phase:"complete",rows:count,bytes:objects.bytes});checkAbort(options.signal);return{rows:count,columns:options.columns.length,bytes:objects.bytes}})}
2359
+ const _exports=Object.freeze({writePdf:writePdf,writePdfTo:writePdfTo});_modules.set("45cf9fd6b6293c1a83bc8554e1bcb5cf119f44701fbad7849f39a712cab5074b",_exports);return _exports})();const _m86=_modules.get("749d1ec5422c0087787f525ef42e3b8d3a94d2b70eb5e42d2e3723a870777ad6")??(()=>{const{NotSupportedError,OfficeIMOError}=_m2;const{checkAbort,pause,taskYieldDue,withAbort}=_m4;const{Crc32}=_m31;const signature=[137,80,78,71,13,10,26,10];const unsupportedChunks=new Set(["PLTE","tRNS","iCCP","sRGB","gAMA","cHRM","cICP","mDCV","cLLI","sBIT","eXIf","acTL","fcTL","fdAT"]);async function pngPixels(inputSource,maxPixels,signal,maxWorkingBytes){checkAbort(signal);const shape=pngShape(inputSource,maxPixels);const imagePixels=shape.width*shape.height;const workingBytes=inputSource.length+imagePixels*shape.components +(shape.components===4?shape.width*8:0);if(maxWorkingBytes!==undefined&&workingBytes>maxWorkingBytes)
2360
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxImageWorkingBytes exceeded by PNG source, image planes and scanlines.");const source=new Uint8Array(inputSource);const header=await pngHeader(source,shape,signal);checkAbort(signal);let stream;try{if(typeof DecompressionStream!=="function")
2361
+ throw new TypeError("Missing DecompressionStream");stream=new DecompressionStream("deflate")}
2362
+ catch(cause){throw new OfficeIMOError("PLATFORM_UNAVAILABLE","PNG intake requires native DecompressionStream(\"deflate\").",{cause})}
2363
+ const{width,height,components}=header,rowBytes=width*components;const expected=(rowBytes+1)*height;if(!Number.isSafeInteger(expected)||expected>0x7fffffff)
2364
+ throw new OfficeIMOError("RESOURCE_LIMIT","PNG filtered data exceeds the supported decoded byte length.");const pixels=new Uint8Array(width*height*3),alpha=components===4?new Uint8Array(imagePixels):undefined;let previous=components===4?new Uint8Array(rowBytes):undefined,current=components===4?new Uint8Array(rowBytes):undefined;const reader=pngCompressedInput(source,header,signal).pipeThrough(stream).getReader();let inflated=0,output=0,rgbOutput=0,alphaOutput=0,column=0,filter=0;try{while(true){const item=await withAbort(reader.read(),signal).catch(cause=>{checkAbort(signal);throw new TypeError("Invalid PNG zlib image data.",{cause})});checkAbort(signal);if(item.done)
2365
+ break;if(item.value.length>expected-inflated)
2366
+ throw new TypeError("PNG inflated bytes exceed the exact IHDR scanline length.");for(let p=0;p<item.value.length;p++){const value=item.value[p];if(column===0){filter=value;if(filter>4)
2367
+ throw new TypeError("Invalid PNG scanline filter.")}
2368
+ else{const index=column-1;let decoded=value;if(filter!==0){const left=column>components?current?current[index-components]:pixels[output-components]:0;const up=previous?previous[index]:output>=rowBytes?pixels[output-rowBytes]:0;const upperLeft=column>components?previous?previous[index-components]:output>=rowBytes?pixels[output-rowBytes-components]:0:0;decoded=(value +(filter===1?left:filter===2?up:
2369
+ filter===3?Math.floor((left+up)/ 2) : paeth(left, up, upperLeft))) & 255;
2370
+ }
2371
+ if(current)
2372
+ current[index]=decoded;else
2373
+ pixels[output]=decoded;output++}
2374
+ if(column===rowBytes){column=0;if(current&&alpha){for(let c=0;c<rowBytes;c +=4){pixels[rgbOutput++]=current[c];pixels[rgbOutput++]=current[c+1];pixels[rgbOutput++]=current[c+2];alpha[alphaOutput++]=current[c+3];if((c&16383)===16380){if(taskYieldDue())
2375
+ await pause();checkAbort(signal)}}
2376
+ const completed=current;current=previous;previous=completed}}
2377
+ else
2378
+ column++;if((p&16383)===16383){if(taskYieldDue())
2379
+ await pause();checkAbort(signal)}}
2380
+ inflated +=item.value.length;if(taskYieldDue())
2381
+ await pause();checkAbort(signal)}
2382
+ if(inflated!==expected)
2383
+ throw new TypeError("PNG inflated bytes must match the exact IHDR scanline length.");await verifyPngZlibEnd(source,header,expected,signal);return{width,height,components:3,data:pixels,...(alpha?{alpha}:{})}}
2384
+ catch(error){void reader.cancel(error).catch(()=>{});throw error}
2385
+ finally{reader.releaseLock()}}
2386
+ function pngCompressedInput(source,header,signal,changeLastByte=false){const view=new DataView(source.buffer,source.byteOffset,source.byteLength);let chunk=header.firstData,position=chunk+8,end=position+view.getUint32(chunk);return new ReadableStream({pull(controller){checkAbort(signal);while(position===end){chunk=end+4;if(chunk===header.dataEnd){controller.close();return}
2387
+ position=chunk+8;end=position+view.getUint32(chunk)}
2388
+ if(changeLastByte&&position===header.lastDataByte){controller.enqueue(Uint8Array.of(source[position++]^1));return}
2389
+ const next=Math.min(end,position+4096,changeLastByte&&position<header.lastDataByte?header.lastDataByte:end);controller.enqueue(source.subarray(position,next));position=next}},{highWaterMark:0})}
2390
+ async function verifyPngZlibEnd(source,header,expected,signal){const reader=pngCompressedInput(source,header,signal,true).pipeThrough(new DecompressionStream("deflate")).getReader();let rejected=false,output=0;try{while(true){let item;try{item=await withAbort(reader.read(),signal)}
2391
+ catch{checkAbort(signal);rejected=true;break}
2392
+ checkAbort(signal);if(item.done)
2393
+ break;output +=item.value.length;if(output>expected)
2394
+ throw new TypeError("Invalid PNG zlib image data.");if(taskYieldDue())
2395
+ await pause();checkAbort(signal)}
2396
+ if(!rejected)
2397
+ throw new TypeError("Invalid PNG zlib image data: trailing bytes after the checksum.")}
2398
+ finally{void reader.cancel().catch(()=>{});reader.releaseLock()}}
2399
+ async function pngHeader(source,shape,signal){const view=new DataView(source.buffer,source.byteOffset,source.byteLength);let firstData=0,dataEnd=0,lastDataByte=-1,dataClosed=false;for(let offset=8;offset<source.length;){checkAbort(signal);if(offset+12>source.length)
2400
+ throw new TypeError("Truncated PNG chunk.");const length=view.getUint32(offset),end=offset+12+length;if(length>0x7fffffff||end>source.length)
2401
+ throw new TypeError("Truncated or oversized PNG chunk.");const type=String.fromCharCode(...source.subarray(offset+4,offset+8));if(!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type))
2402
+ throw new TypeError("Invalid PNG chunk type.");const crc=new Crc32();for(let p=offset+4;p<end-4;p +=65536){crc.update(source.subarray(p,Math.min(end-4,p+65536)));if(taskYieldDue())
2403
+ await pause();checkAbort(signal)}
2404
+ if(crc.value!==view.getUint32(end-4))
2405
+ throw new TypeError("PNG chunk CRC mismatch: "+type+".");if(offset===8&&type!=="IHDR")
2406
+ throw new TypeError("PNG IHDR must be the first chunk.");if(type==="IHDR"){if(offset!==8||length!==13)
2407
+ throw new TypeError("PNG requires one 13-byte IHDR first.")}
2408
+ else if(type==="IDAT"){if(dataClosed)
2409
+ throw new TypeError("PNG IDAT chunks must be consecutive.");firstData||=offset;dataEnd=end;if(length)
2410
+ lastDataByte=end-5}
2411
+ else{if(firstData)
2412
+ dataClosed=true;if(type==="IEND"){if(length!==0||!firstData||end!==source.length)
2413
+ throw new TypeError("PNG requires a final empty IEND after IDAT.");return{...shape,firstData,dataEnd,lastDataByte}}
2414
+ if(unsupportedChunks.has(type))
2415
+ throw new NotSupportedError("PNG chunk "+type+"; normalize color, orientation, transparency or animation first");if((source[offset+4]&32)===0)
2416
+ throw new NotSupportedError("Required PNG chunk "+type)}
2417
+ offset=end}
2418
+ throw new TypeError("PNG requires a complete final IEND chunk.")}
2419
+ function pngShape(source,maxPixels){if(source.length<33||signature.some((value,index)=>source[index]!==value))
2420
+ throw new TypeError("Invalid PNG signature or truncated IHDR.");const view=new DataView(source.buffer,source.byteOffset,source.byteLength);if(view.getUint32(8)!==13||String.fromCharCode(...source.subarray(12,16))!=="IHDR")
2421
+ throw new TypeError("PNG requires one 13-byte IHDR first.");const width=view.getUint32(16),height=view.getUint32(20);if(!width||!height||width>0x7fffffff||height>0x7fffffff)
2422
+ throw new TypeError("Invalid PNG dimensions.");if(!Number.isSafeInteger(width*height)||width*height>maxPixels)
2423
+ throw new OfficeIMOError("RESOURCE_LIMIT","PNG dimensions exceed maxImagePixels.");if(source[24]!==8||![2,6].includes(source[25]))
2424
+ throw new NotSupportedError("PNG intake requires 8-bit RGB or RGBA pixels");if(source[26]!==0||source[27]!==0)
2425
+ throw new NotSupportedError("PNG compression or filter method");if(source[28]!==0)
2426
+ throw new NotSupportedError("Interlaced PNG intake");const components=source[25]===6?4:3;if(!Number.isSafeInteger((width*components+1)*height)||(width*components+1)*height>0x7fffffff)
2427
+ throw new OfficeIMOError("RESOURCE_LIMIT","PNG filtered data exceeds the supported decoded byte length.");return{width,height,components}}
2428
+ function paeth(left,up,upperLeft){const prediction=left+up-upperLeft;const a=Math.abs(prediction-left),b=Math.abs(prediction-up),c=Math.abs(prediction-upperLeft);return a<=b&&a<=c?left:b<=c?up:upperLeft}
2429
+ const _exports=Object.freeze({pngPixels:pngPixels});_modules.set("749d1ec5422c0087787f525ef42e3b8d3a94d2b70eb5e42d2e3723a870777ad6",_exports);return _exports})();const _m85=_modules.get("7dca2d9ca5c43893abdaf86df5b1bcb1f3de3d5d33532d082fdfe04711999d21")??(()=>{const{NotSupportedError,OfficeIMOError}=_m2;const{checkAbort,pause,taskYieldDue}=_m4;const{pngPixels}=_m86;class PdfDocumentImages{objects;settings;images=new Map();bytes=0;constructor(objects,settings){this.objects=objects;this.settings=settings}
2430
+ async prepare(image){const existing=this.images.get(image);if(existing)
2431
+ return existing;const{limits,options}=this.settings;if(!image||typeof image!=="object")
2432
+ throw new TypeError("PDF images require a byte array.");const data=image.data,format=image.format;if(!(data instanceof Uint8Array))
2433
+ throw new TypeError("PDF images require a byte array.");const byteLength=data.length;if(this.bytes+byteLength>limits.maxImageBytes)
2434
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxImageBytes exceeded.");let width,height,components,decoded,decodedAlpha;const maximumWorkingBytes=limits.maxImageWorkingBytes;if(format==="png")
2435
+ ({width,height,components,data:decoded,alpha:decodedAlpha}=await pngPixels(data,limits.maxImagePixels,options.signal,maximumWorkingBytes));else if(format==="jpeg")
2436
+ ({width,height,components}=jpegSize(data));else if(format==="rgb"||format==="rgba"){({width,height}=image);components=format==="rgba"?4:3}
2437
+ else
2438
+ throw new NotSupportedError("PDF images support unprofiled PNG/JPEG or decoded RGB/RGBA pixels.");if(!Number.isSafeInteger(width)||!Number.isSafeInteger(height)||width<1||height<1||
2439
+ !Number.isSafeInteger(width*height)||width*height>limits.maxImagePixels)
2440
+ throw new OfficeIMOError("RESOURCE_LIMIT","Image dimensions must be positive integers within maxImagePixels.");if((format==="rgb"||format==="rgba")&&byteLength!==width*height*components)
2441
+ throw new RangeError("Raw image bytes must match width × height × channels exactly.");if(format!=="png"&&maximumWorkingBytes!==undefined&&byteLength +(components===4?width*height:0)>maximumWorkingBytes)
2442
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxImageWorkingBytes exceeded by image snapshot and alpha plane.");checkAbort(options.signal);const id=this.objects.reserve(),name="Image" +(this.images.size+1);this.bytes +=byteLength;const captured=decoded??new Uint8Array(data);let pixels=captured,alpha=decodedAlpha,mask;if(components===4){pixels=captured.subarray(0,width*height*3);alpha=new Uint8Array(width*height);for(let p=0;p<alpha.length;p++){pixels[p*3]=captured[p*4];pixels[p*3+1]=captured[p*4+1];pixels[p*3+2]=captured[p*4+2];alpha[p]=captured[p*4+3];if((p&16383)===16383){if(taskYieldDue())
2443
+ await pause();checkAbort(options.signal)}}}
2444
+ if(alpha){mask=this.objects.reserve();await this.objects.stream(mask,alpha,"/Type /XObject /Subtype /Image /Width "+width+" /Height "+height+" /ColorSpace /DeviceGray /BitsPerComponent 8",options.compression!==false,true)}
2445
+ const dictionary="/Type /XObject /Subtype /Image /Width "+width+" /Height "+height+" /ColorSpace /" +
2446
+ (components===1?"DeviceGray":"DeviceRGB")+ " /BitsPerComponent 8" +(mask?" /SMask "+mask+" 0 R":"")+
2447
+ (format==="jpeg"?" /Filter /DCTDecode":"");await this.objects.stream(id,pixels,dictionary,format==="jpeg"?false:options.compression!==false,true);const resource={name,id,width,height};this.images.set(image,resource);return resource}}
2448
+ function jpegSize(bytes){if(bytes.length<4||bytes[0]!==255||bytes[1]!==216||bytes[bytes.length-2]!==255||bytes[bytes.length-1]!==217)
2449
+ throw new TypeError("JPEG images need complete SOI/EOI markers.");let result;for(let p=2;p<bytes.length;){if(bytes[p++]!==255)
2450
+ throw new TypeError("Invalid JPEG marker.");while(bytes[p]===255)
2451
+ p++;const marker=bytes[p++];if(marker===218){if(!result)
2452
+ throw new TypeError("JPEG scan precedes its frame header.");return result}
2453
+ if(marker===217)
2454
+ break;if(p+2>bytes.length)
2455
+ throw new TypeError("Truncated JPEG segment.");const length=bytes[p]*256+bytes[p+1],end=p+length;if(length<2||end>bytes.length)
2456
+ throw new TypeError("Truncated JPEG segment.");if(marker===226&&length>=14&&String.fromCharCode(...bytes.subarray(p+2,p+14))==="ICC_PROFILE\0")
2457
+ throw new NotSupportedError("Normalize ICC-profiled JPEG colors before PDF embedding.");if(marker===225&&length>=8&&String.fromCharCode(...bytes.subarray(p+2,p+8))==="Exif\0\0")
2458
+ throw new NotSupportedError("Normalize JPEG EXIF orientation before PDF embedding.");if(marker>=192&&marker<=207&&![196,200,204].includes(marker)){if(![192,193,194].includes(marker)||length<8||bytes[p+2]!==8)
2459
+ throw new NotSupportedError("PDF JPEG images require 8-bit baseline, sequential or progressive frames.");const components=bytes[p+7];if(![1,3].includes(components)||length!==8+components*3)
2460
+ throw new NotSupportedError("PDF JPEG images require grayscale or RGB components; CMYK is unsupported.");if(components===3){const ids=[bytes[p+8],bytes[p+11],bytes[p+14]].join(",");if(ids!=="1,2,3"&&ids!=="82,71,66")
2461
+ throw new NotSupportedError("Unsupported JPEG component color layout.")}
2462
+ if(result)
2463
+ throw new NotSupportedError("Multiple JPEG frame headers are unsupported.");result={width:bytes[p+5]*256+bytes[p+6],height:bytes[p+3]*256+bytes[p+4],components}}
2464
+ p=end}
2465
+ throw new TypeError("JPEG image has no complete frame and scan.")}
2466
+ const _exports=Object.freeze({PdfDocumentImages:PdfDocumentImages});_modules.set("7dca2d9ca5c43893abdaf86df5b1bcb1f3de3d5d33532d082fdfe04711999d21",_exports);return _exports})();const _m87=_modules.get("3290c84fdf80725af802f497d947bc088aa8d93d9db0a33f6f829f9153aa6fd6")??(()=>{const{OfficeIMOError}=_m2;const{checkAbort,pause,taskYieldDue}=_m4;const{color,positive}=_m17;const{pdfNumber:n}=_m60;async function vectorCommands(block,settings,used){const width=positive(block.width,"Vector width"),height=positive(block.height,"Vector height");const source=block.commands;if(!Array.isArray(source))
2467
+ throw new TypeError("Vector commands must be an array.");if(used+source.length>settings.limits.maxVectorCommands)
2468
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxVectorCommands exceeded.");const input=source.map(c=>{if(!c||typeof c!=="object")
2469
+ throw new TypeError("Invalid vector command.");const op=c.op;if(op==="move"||op==="line")
2470
+ return{op,x:c.x,y:c.y};if(op==="cubic")
2471
+ return{op,x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,x:c.x,y:c.y};if(op==="close")
2472
+ return{op};throw new TypeError("Unsupported vector command.")});const fillValue=block.fill,strokeValue=block.stroke;const fill=fillValue===undefined?undefined:color(fillValue),stroke=strokeValue===undefined?undefined:color(strokeValue);if(fill===undefined&&stroke===undefined)
2473
+ throw new TypeError("A vector path requires fill or stroke.");const strokeWidth=positive(block.strokeWidth??1,"Vector stroke width",144);const fillRule=block.fillRule;if(fillRule!==undefined&&!["nonzero","evenodd"].includes(fillRule))
2474
+ throw new TypeError("Invalid vector fill rule.");const commands=[];let bytes=0,started=false;const coordinate=(value,bound)=>{if(!Number.isFinite(value)||value<0||value>bound)
2475
+ throw new RangeError("Vector coordinates must stay inside their declared bounds.");return n(value)};for(let i=0;i<input.length;i++){const c=input[i];let command;if(!c||typeof c!=="object")
2476
+ throw new TypeError("Invalid vector command.");if(c.op==="move"||c.op==="line"){if(c.op==="line"&&!started)
2477
+ throw new TypeError("A vector subpath must begin with move.");command=coordinate(c.x,width)+ " "+coordinate(c.y,height)+(c.op==="move"?" m\n":" l\n");started=true}
2478
+ else if(c.op==="cubic"){if(!started)
2479
+ throw new TypeError("A vector subpath must begin with move.");command=[coordinate(c.x1,width),coordinate(c.y1,height),coordinate(c.x2,width),coordinate(c.y2,height),coordinate(c.x,width),coordinate(c.y,height)].join(" ")+ " c\n"}
2480
+ else if(c.op==="close"){if(!started)
2481
+ throw new TypeError("Cannot close an empty vector path.");command="h\n"}
2482
+ else
2483
+ throw new TypeError("Unsupported vector command.");bytes +=command.length;if(bytes>settings.limits.maxPageBytes-256)
2484
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxPageBytes exceeded by vector commands.");commands.push(command);if((i&1023)===1023){if(taskYieldDue())
2485
+ await pause();checkAbort(settings.options.signal)}}
2486
+ if(!started)
2487
+ throw new TypeError("A vector path needs at least one command.");return{width,height,count:input.length,content:(fill===undefined?"":fill+" rg\n")+(stroke===undefined?"":stroke+" RG\n"+n(strokeWidth)+ " w\n")+
2488
+ commands.join("")+(fill!==undefined&&stroke!==undefined?"B":fill!==undefined?"f":"S")+(fill!==undefined&&fillRule==="evenodd"?"*":"")+ "\n"}}
2489
+ const _exports=Object.freeze({vectorCommands:vectorCommands});_modules.set("3290c84fdf80725af802f497d947bc088aa8d93d9db0a33f6f829f9153aa6fd6",_exports);return _exports})();const _m88=_modules.get("da9ad00f94b9ae28e2e3de796928ff0c4eab1d73382b1441e7d779fad4278ef7")??(()=>{const{NotSupportedError,OfficeIMOError}=_m2;const{checkAbort,pause,taskYieldDue}=_m4;const{color,positive}=_m17;const{pdfNumber:n}=_m60;function record(value,keys,name){if(!value||typeof value!=="object"||Array.isArray(value)||Reflect.ownKeys(value).some(key=>typeof key!=="string"||!keys.includes(key)))
2490
+ throw new TypeError("Unsupported "+name+" properties.");return value}
2491
+ function checkDrawingBlock(value){record(value,["kind","drawing","alignment","alternativeText","decorative","caption"],"drawing block")}
2492
+ function coordinate(value){if(typeof value!=="number"||!Number.isFinite(value)||Math.abs(value)>1000000)
2493
+ throw new RangeError("Drawing coordinates must be finite and within -1,000,000 through 1,000,000 points.");return value}
2494
+ function clipRectangle(value){const clip=record(value,["x","y","width","height"],"drawing clip");return{x:coordinate(clip.x),y:coordinate(clip.y),width:positive(clip.width,"Drawing clip width",1000000),height:positive(clip.height,"Drawing clip height",1000000)}}
2495
+ async function cooperate(settings){if(taskYieldDue())
2496
+ await pause();checkAbort(settings.options.signal)}
2497
+ function captureDrawing(drawing,settings,used){checkAbort(settings.options.signal);const root=record(drawing,["version","width","height","elements"],"drawing");if(root.version!==1)
2498
+ throw new NotSupportedError("Only portable drawing version 1 is supported.");const width=positive(root.width,"Drawing width"),height=positive(root.height,"Drawing height");let commands=used.commands,elements=used.elements;const ancestors=new Set();function path(value){record(value,["kind","commands","fill","stroke","strokeWidth","fillRule","lineCap","lineJoin"],"drawing path");const source=value.commands;if(!Array.isArray(source))
2499
+ throw new TypeError("Drawing path commands must be an array.");if(commands+source.length>settings.limits.maxVectorCommands)
2500
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxVectorCommands exceeded.");checkAbort(settings.options.signal);const snapshot=source.slice(),copied=[];let started=false;commands +=snapshot.length;const fillValue=value.fill,strokeValue=value.stroke;const fill=fillValue===undefined?undefined:color(fillValue),stroke=strokeValue===undefined?undefined:color(strokeValue);if(fill===undefined&&stroke===undefined)
2501
+ throw new TypeError("A drawing path requires fill or stroke.");const strokeWidth=positive(value.strokeWidth??1,"Drawing stroke width");const fillRule=value.fillRule,lineCap=value.lineCap,lineJoin=value.lineJoin;if(fillRule!==undefined&&!["nonzero","evenodd"].includes(fillRule))
2502
+ throw new TypeError("Invalid drawing fillRule.");if(lineCap!==undefined&&!["butt","round","square"].includes(lineCap))
2503
+ throw new TypeError("Invalid drawing lineCap.");if(lineJoin!==undefined&&!["miter","round","bevel"].includes(lineJoin))
2504
+ throw new TypeError("Invalid drawing lineJoin.");for(let i=0;i<snapshot.length;i++){const c=snapshot[i];if(!c||typeof c!=="object")
2505
+ throw new TypeError("Invalid drawing path command.");const op=c.op;if(op==="move"||op==="line"){record(c,["op","x","y"],"drawing path command");if(op==="line"&&!started)
2506
+ throw new TypeError("A drawing subpath must begin with move.");copied.push({op,x:coordinate(c.x),y:coordinate(c.y)});started=true}
2507
+ else if(op==="cubic"){record(c,["op","x1","y1","x2","y2","x","y"],"drawing path command");if(!started)
2508
+ throw new TypeError("A drawing subpath must begin with move.");copied.push({op:"cubic",x1:coordinate(c.x1),y1:coordinate(c.y1),x2:coordinate(c.x2),y2:coordinate(c.y2),x:coordinate(c.x),y:coordinate(c.y)})}
2509
+ else if(op==="close"){record(c,["op"],"drawing path command");if(!started)
2510
+ throw new TypeError("Cannot close an empty drawing path.");copied.push({op:"close"})}
2511
+ else
2512
+ throw new TypeError("Unsupported drawing path command.");if((i&1023)===1023)
2513
+ checkAbort(settings.options.signal)}
2514
+ if(!started)
2515
+ throw new TypeError("A drawing path needs at least one command.");return{kind:"path",commands:copied,style:(fill===undefined?"":fill+" rg\n")+(stroke===undefined?"":stroke+" RG\n"+n(strokeWidth)+ " w\n")+
2516
+ String(["butt","round","square"].indexOf(lineCap??"butt"))+ " J\n"+String(["miter","round","bevel"].indexOf(lineJoin??"miter"))+ " j\n10 M\n",paint:(fill!==undefined&&stroke!==undefined?"B":fill!==undefined?"f":"S")+(fill!==undefined&&fillRule==="evenodd"?"*":"")+ "\n"}}
2517
+ function text(value){record(value,["kind","text","x","y","font","fontSize","color"],"drawing text");const snapshot=value.text,slot=value.font;if(typeof snapshot!=="string")
2518
+ throw new TypeError("Drawing text must be a string.");if(snapshot.length>settings.limits.maxCellCharacters)
2519
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxCellCharacters exceeded.");if(/[\r\n\u2028\u2029]/.test(snapshot))
2520
+ throw new NotSupportedError("Drawing text must be a single baseline without line breaks.");if(!["regular","bold","italic","boldItalic"].includes(slot))
2521
+ throw new TypeError("Invalid drawing font slot.");const x=coordinate(value.x),y=coordinate(value.y),size=positive(value.fontSize,"Drawing font size"),foreground=color(value.color);settings.budget.cell(snapshot);return{kind:"text",text:snapshot,x,y,size,color:foreground,font:slot}}
2522
+ function children(input,depth){if(!Array.isArray(input))
2523
+ throw new TypeError("Drawing elements must be an array.");if(depth>32&&input.length)
2524
+ throw new RangeError("Drawing groups support at most 32 element levels.");if(elements+input.length>settings.limits.maxDrawingElements)
2525
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxDrawingElements exceeded.");checkAbort(settings.options.signal);const snapshot=input.slice(),output=[];for(let i=0;i<snapshot.length;i++){if(++elements>settings.limits.maxDrawingElements)
2526
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxDrawingElements exceeded.");const value=snapshot[i];if(!value||typeof value!=="object")
2527
+ throw new TypeError("Invalid drawing element.");if(ancestors.has(value))
2528
+ throw new TypeError("Drawing groups cannot contain cycles.");const kind=value.kind;if(kind==="path")
2529
+ output.push(path(value));else if(kind==="text")
2530
+ output.push(text(value));else if(kind==="group"){record(value,["kind","clip","elements"],"drawing group");const clipValue=value.clip,clip=clipValue===undefined?undefined:clipRectangle(clipValue);ancestors.add(value);output.push({kind:"group",...(clip?{clip}:{}),children:children(value.elements,depth+1)});ancestors.delete(value)}
2531
+ else
2532
+ throw new TypeError("Unsupported drawing element kind.");if((i&255)===255)
2533
+ checkAbort(settings.options.signal)}
2534
+ return output}
2535
+ const plan=children(root.elements,1);checkAbort(settings.options.signal);return{width,height,plan,commands:commands-used.commands,elements:elements-used.elements}}
2536
+ async function prepareDrawing(drawing,settings,fonts,used){const captured=captureDrawing(drawing,settings,used),drawingFonts=new Map();function fontFor(slot){const existing=drawingFonts.get(slot);if(existing)
2537
+ return existing;const font=fonts.select(slot==="bold"||slot==="boldItalic",slot==="italic"||slot==="boldItalic");if(!font.program||font.syntheticBold||font.syntheticItalic)
2538
+ throw new NotSupportedError("Drawing text without an exact embedded font face at fonts."+slot);drawingFonts.set(slot,font);return font}
2539
+ let preflightCharacters=0,preflightElements=0;async function preflight(nodes){for(let i=0;i<nodes.length;i++){const node=nodes[i];if(node.kind==="group")
2540
+ await preflight(node.children);else if(node.kind==="text"){const font=fontFor(node.font);for(const character of node.text){font.width(character.codePointAt(0));if((++preflightCharacters&1023)===0)
2541
+ await cooperate(settings)}}
2542
+ if((++preflightElements&255)===0)
2543
+ await cooperate(settings)}}
2544
+ await preflight(captured.plan);const fragments=[];let bytes=0;function add(fragment){bytes +=fragment.length;if(bytes>settings.limits.maxPageBytes-256)
2545
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxPageBytes exceeded by drawing content.");fragments.push(fragment)}
2546
+ let paintedCharacters=0,paintedCommands=0,paintedElements=0;async function paint(nodes){for(let i=0;i<nodes.length;i++){const node=nodes[i];add("q\n");if(node.kind==="group"){if(node.clip)
2547
+ add([node.clip.x,node.clip.y,node.clip.width,node.clip.height].map(n).join(" ")+ " re W n\n");await paint(node.children)}
2548
+ else if(node.kind==="path"){add(node.style);for(let j=0;j<node.commands.length;j++){const c=node.commands[j];add(c.op==="move"||c.op==="line"?n(c.x)+ " "+n(c.y)+(c.op==="move"?" m\n":" l\n"):
2549
+ c.op==="cubic"?[c.x1,c.y1,c.x2,c.y2,c.x,c.y].map(n).join(" ")+ " c\n":"h\n");if((++paintedCommands&1023)===0)
2550
+ await cooperate(settings)}
2551
+ add(node.paint)}
2552
+ else{const font=fontFor(node.font);add(node.color+" rg\nBT /"+font.name+" "+n(node.size)+ " Tf 0 Tr 1 0 0 -1 "+n(node.x)+ " "+n(node.y)+ " Tm <");let chunk="";for(const character of node.text){chunk +=character;if((++paintedCharacters&1023)===0){add(font.encode(chunk).slice(1,-1));chunk="";await cooperate(settings)}}
2553
+ if(chunk)
2554
+ add(font.encode(chunk).slice(1,-1));add("> Tj ET\n")}
2555
+ add("Q\n");if((++paintedElements&255)===0)
2556
+ await cooperate(settings)}}
2557
+ await paint(captured.plan);checkAbort(settings.options.signal);return{width:captured.width,height:captured.height,content:fragments.join(""),commands:captured.commands,elements:captured.elements}}
2558
+ const _exports=Object.freeze({checkDrawingBlock:checkDrawingBlock,prepareDrawing:prepareDrawing});_modules.set("da9ad00f94b9ae28e2e3de796928ff0c4eab1d73382b1441e7d779fad4278ef7",_exports);return _exports})();const _m89=_modules.get("5e4503b77b357ee6d9fad1f52690085b0f0b140cd3b550b63c5100ed95a92f88")??(()=>{const{OfficeIMOError}=_m2;const{capturePdfText,wrapPdfText}=_m71;const{positive}=_m17;const{resolveParagraphStyle}=_m19;const{captureBookmark}=_m78;const{captureFields}=_m10;const{pdfBudgetText}=_m70;function captureParagraph(block,settings,fonts,budgetOnPaint=false){if(!block||block.kind!=="paragraph")
2559
+ throw new TypeError("PDF paragraph groups accept paragraph blocks only.");const{text,headingLevel,presentation:inputStyle,fontSize,keepTogether,keepWithNext,spaceBefore,spaceAfter,style:styleName,bookmark:inputBookmark}=block;if(headingLevel!==undefined&&(!Number.isInteger(headingLevel)||headingLevel<1||headingLevel>6))
2560
+ throw new TypeError("Paragraph headingLevel must be an integer from 1 through 6.");const resolved=resolveParagraphStyle(styleName,{...(fontSize===undefined?{}:{fontSize}),...(inputStyle===undefined?{}:{presentation:inputStyle}),...(keepTogether===undefined?{}:{keepTogether}),...(keepWithNext===undefined?{}:{keepWithNext}),...(spaceBefore===undefined?{}:{spaceBefore}),...(spaceAfter===undefined?{}:{spaceAfter})},settings.paragraphStyles);const style=resolved.presentation??Object.freeze({}),size=positive(resolved.fontSize??settings.fontSize,"Paragraph font size",144);const bookmark=captureBookmark(inputBookmark,settings);return Object.freeze({text:capturePdfText(text,style,settings,fonts,false,!budgetOnPaint),style,size,...(budgetOnPaint?{budgetOnPaint:true}:{}),...(headingLevel===undefined?{}:{headingLevel}),...(bookmark===undefined?{}:{bookmark}),keepTogether:resolved.keepTogether??false,keepWithNext:resolved.keepWithNext??false,spaceBefore:resolved.spaceBefore??0,spaceAfter:resolved.spaceAfter??8})}
2561
+ function captureCaption(caption,settings,fonts){if(!caption||typeof caption!=="object"||Array.isArray(caption)||
2562
+ Object.keys(caption).some(key=>!["text","style","fontSize","presentation","spaceBefore","spaceAfter"].includes(key)))
2563
+ throw new TypeError("PDF captions support text, style, fontSize, presentation, spaceBefore and spaceAfter.");return captureParagraph({...captureFields(caption,["text","style","fontSize","presentation","spaceBefore","spaceAfter"]),kind:"paragraph",keepTogether:true,keepWithNext:true},settings,fonts,true)}
2564
+ async function prepareParagraph(captured,settings,fonts,width=settings.page.width-settings.margins.left-settings.margins.right){if(!captured.text.text)
2565
+ return{...captured,lines:[],height:0,firstHeight:0};if(!captured.budgetOnPaint){const budgetText=pdfBudgetText(captured.text.text,settings.budget);settings.budget.cell(budgetText,budgetText.length)}
2566
+ const lines=await wrapPdfText(captured.text,fonts,captured.size,positive(width,"Paragraph width"),settings);return{...captured,lines,height:captured.spaceBefore+lines.reduce((height,line)=>height+line.lineHeight,0)+ captured.spaceAfter,firstHeight:captured.spaceBefore+lines[0].lineHeight}}
2567
+ function checkParagraphBuffer(paragraphs,settings){if(paragraphs.length>settings.limits.maxGroupBlocks)
2568
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxGroupBlocks exceeded.");let characters=0,runs=0;for(const paragraph of paragraphs){characters +=paragraph.text.text.length;runs +=paragraph.text.runs.length;if(characters>settings.limits.maxCellCharacters)
2569
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxCellCharacters exceeded by a paragraph group or keep chain.");if(runs>settings.limits.maxTextRuns)
2570
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxTextRuns exceeded by a paragraph group or keep chain.")}}
2571
+ function paragraphStartHeight(paragraphs){const visible=paragraphs.filter(paragraph=>paragraph.lines.length>0);let required=0;for(let i=visible.length-1;i>=0;i--){const paragraph=visible[i];required=paragraph.keepWithNext?paragraph.height+required:paragraph.keepTogether?paragraph.height:paragraph.firstHeight}
2572
+ return required}
2573
+ const _exports=Object.freeze({captureParagraph:captureParagraph,captureCaption:captureCaption,prepareParagraph:prepareParagraph,checkParagraphBuffer:checkParagraphBuffer,paragraphStartHeight:paragraphStartHeight});_modules.set("5e4503b77b357ee6d9fad1f52690085b0f0b140cd3b550b63c5100ed95a92f88",_exports);return _exports})();const _m90=_modules.get("1d57c429705ae0cbc14d98dcfef4c8a6c2df06f391c8f58e99cacb02f2d1cbc7")??(()=>{const{capturePdfText,wrapPdfText}=_m71;const{captureParagraph,prepareParagraph}=_m89;const{resolveParagraphStyle}=_m19;function captureListOptions(block,settings){const{items,ordered=false,start:inputStart,itemStyle,indent,markerGap}=block;const start=inputStart===undefined?1:inputStart;if(typeof ordered!=="boolean")
2574
+ throw new TypeError("PDF list ordered must be boolean.");if(!Number.isSafeInteger(start)||start<1)
2575
+ throw new RangeError("PDF list start must be a positive safe integer.");if(!ordered&&inputStart!==undefined)
2576
+ throw new TypeError("PDF list start requires ordered:true.");for(const[name,value]of[["indent",indent],["markerGap",markerGap]])
2577
+ if(value!==undefined&&(!Number.isFinite(value)||value<0||value>14400))
2578
+ throw new RangeError("PDF list "+name+" must be from zero through 14,400 points.");if(resolveParagraphStyle(itemStyle,{},settings.paragraphStyles).keepWithNext)
2579
+ throw new TypeError("PDF list item styles cannot use keepWithNext.");return Object.freeze({items,ordered,start,...(itemStyle===undefined?{}:{itemStyle}),...(indent===undefined?{}:{indent}),...(markerGap===undefined?{}:{markerGap})})}
2580
+ async function prepareListItem(item,index,options,settings,fonts){if(!item||typeof item!=="object"||Array.isArray(item)||Object.keys(item).some(key=>!["text","style","keepTogether"].includes(key)))
2581
+ throw new TypeError("PDF list items support text, style and keepTogether.");if(!Number.isSafeInteger(index)||index<0||!Number.isSafeInteger(options.start+index))
2582
+ throw new RangeError("PDF list numbering must remain within positive safe integers.");const{text,style=options.itemStyle,keepTogether}=item;const captured=captureParagraph({kind:"paragraph",text,...(style===undefined?{}:{style}),...(keepTogether===undefined?{}:{keepTogether})},settings,fonts);if(captured.keepWithNext)
2583
+ throw new TypeError("PDF list item styles cannot use keepWithNext.");if(!captured.text.text.trim().length)
2584
+ throw new TypeError("PDF list items require nonempty text.");const markerText=options.ordered?String(options.start+index)+ ".":"•";const capturedMarker=capturePdfText(markerText,captured.style,settings,fonts);settings.budget.cell(markerText,markerText.length);const width=settings.page.width-settings.margins.left-settings.margins.right;const marker=(await wrapPdfText(capturedMarker,fonts,captured.size,width,settings,false))[0];const markerGap=options.markerGap??captured.size / 2, indent = options.indent ?? Math.max(captured.size * 2, marker.width + markerGap);
2585
+ if(marker.width+markerGap>indent+.001)
2586
+ throw new RangeError("PDF list indent cannot fit its marker and gap.");if(indent>=width)
2587
+ throw new RangeError("PDF list indent leaves no body text area.");const paragraph=await prepareParagraph(captured,settings,fonts,width-indent),first=paragraph.lines[0];const lineHeight=Math.max(first.lineHeight,marker.lineHeight),ascent=Math.max(first.ascent,marker.ascent);return{marker,indent,markerGap,paragraph:{...paragraph,lines:[{...first,lineHeight,ascent},...paragraph.lines.slice(1)],height:paragraph.height+lineHeight-first.lineHeight,firstHeight:paragraph.spaceBefore+lineHeight}}}
2588
+ const _exports=Object.freeze({captureListOptions:captureListOptions,prepareListItem:prepareListItem});_modules.set("1d57c429705ae0cbc14d98dcfef4c8a6c2df06f391c8f58e99cacb02f2d1cbc7",_exports);return _exports})();const _m92=_modules.get("d04686d2c067355dfd215333b83eb5f79f96e9e4be49f942e050f21ac0795343")??(()=>{const{assertGroupedReportSource}=_m8;const{captureFields}=_m10;const{captureWideTable}=_m17;const{presentation}=_m20;const groupedPdfLabelFields=["labelColumn","subtotalLabel","grandTotalLabel","includeGrandTotal","continuationLabel","groupHeadingLevel"];const groupedPdfTableFields=["includeHeader","headerPresentation","footerPresentation","alternateRowColor","columnWidths","wideTable","formatValue","formatRuns",...groupedPdfLabelFields];function pdfGroupedTable(report,options){assertGroupedReportSource(report);return Object.freeze({kind:"groupedTable",report,options:captureGroupedPdfTableOptions(options)})}
2589
+ function captureGroupedPdfTableOptions(configuration){if(!configuration||typeof configuration!=="object"||Array.isArray(configuration)||
2590
+ Object.keys(configuration).some(key=>!groupedPdfTableFields.includes(key)))
2591
+ throw new TypeError("Grouped PDF table options support table presentation and labels; document settings belong on writePdfDocument.");const captured=captureFields(configuration,groupedPdfTableFields);const{labelColumn,subtotalLabel,grandTotalLabel,includeGrandTotal,continuationLabel,groupHeadingLevel}=captured;if(!labelColumn||typeof labelColumn!=="object")
2592
+ throw new TypeError("Grouped PDF needs a leading labelColumn.");const{header,width}=labelColumn;if(typeof header!=="string")
2593
+ throw new TypeError("The grouped label column header must be text.");for(const[name,value]of[["subtotalLabel",subtotalLabel],["grandTotalLabel",grandTotalLabel]])
2594
+ if(typeof value!=="function")
2595
+ throw new TypeError(name+" must be a synchronous text callback.");if(continuationLabel!==undefined&&typeof continuationLabel!=="function")
2596
+ throw new TypeError("continuationLabel must be a synchronous text callback.");if(includeGrandTotal!==undefined&&typeof includeGrandTotal!=="boolean")
2597
+ throw new TypeError("includeGrandTotal must be boolean.");if(groupHeadingLevel!==undefined&&(!Number.isInteger(groupHeadingLevel)||groupHeadingLevel<1||groupHeadingLevel>6))
2598
+ throw new TypeError("groupHeadingLevel must be an integer from 1 through 6.");return Object.freeze({...captured,...(captured.wideTable===undefined?{}:{wideTable:captureWideTable(captured.wideTable)}),labelColumn:Object.freeze({header,...(width===undefined?{}:{width})}),...(captured.columnWidths===undefined?{}:{columnWidths:Object.freeze([...captured.columnWidths])}),...(captured.headerPresentation===undefined?{}:{headerPresentation:presentation(captured.headerPresentation)}),...(captured.footerPresentation===undefined?{}:{footerPresentation:presentation(captured.footerPresentation)})})}
2599
+ const _exports=Object.freeze({groupedPdfLabelFields:groupedPdfLabelFields,groupedPdfTableFields:groupedPdfTableFields,pdfGroupedTable:pdfGroupedTable,captureGroupedPdfTableOptions:captureGroupedPdfTableOptions});_modules.set("d04686d2c067355dfd215333b83eb5f79f96e9e4be49f942e050f21ac0795343",_exports);return _exports})();const _m91=_modules.get("289fa3a052c7fbab2a3ca0fb91fb9974db709d24b7d850f1175810258f0409a0")??(()=>{const{assertGroupedReportSource,groupedReportOperation}=_m8;const{consumeRows}=_m4;const{ExportCell}=_m5;const{captureGroupedPdfTableOptions}=_m92;const{settings}=_m17;const{PdfTableLayout}=_m69;const{captureCaption,captureParagraph,prepareParagraph}=_m89;const{synchronousText}=_m70;async function renderGroupedPdfTable(block,context){const{report}=block,{pages,fonts,prepared,controller}=context;assertGroupedReportSource(report);const semantic=prepared.options.tagged!==undefined;const captured=captureGroupedPdfTableOptions(block.options);const{labelColumn,subtotalLabel,grandTotalLabel,includeGrandTotal=true,continuationLabel,groupHeadingLevel=2,...input}=captured;const columns=Object.freeze([Object.freeze({...labelColumn}),...report.columns]);let rowIndex=-1;const sourceContext=(value)=>({rowIndex,columnIndex:value.columnIndex-1,column:report.columns[value.columnIndex-1]});const table=settings({...pages.settings.options,...input,columns,includeHeader:input.includeHeader??true,...(input.formatValue===undefined?{}:{formatValue:(value,position)=>input.formatValue(value,sourceContext(position))}),...(input.formatRuns===undefined?{}:{formatRuns:(value,position)=>input.formatRuns(value,sourceContext(position))})});const sharedTable={...table,budget:prepared.budget},layout=new PdfTableLayout(sharedTable,fonts);context.acceptColumns(columns.length);const operation=groupedReportOperation(report,controller.signal),abort=()=>controller.abort(operation.signal?.reason);operation.signal?.addEventListener("abort",abort,{once:true});if(operation.signal?.aborted)
2600
+ abort();try{const headings=await layout.headers(),headingHeight=await layout.blockHeight(headings);let path=[],started=false,firstFragment=false,firstBundleOversized=false,semanticDepth=0;const continuationLabels=new WeakMap();let pending;const closing=[];const aggregatePositions=report.columns.flatMap((column,index)=>Object.hasOwn(report.totals,column.key)?[index]:[]);const summaryValues=(label,values,positions)=>Object.freeze([new ExportCell(label,{text:label,presentation:table.options.footerPresentation}),...(positions?positions.map(index=>values[index]):values).map(value=>new ExportCell(value,{presentation:table.options.footerPresentation}))]);const summaryLayouts=new Map();const summaryLayout=(grand)=>{const existing=summaryLayouts.get(grand);if(existing)
2601
+ return existing;const positions=[0,...aggregatePositions.map(index=>index+1)];const projected=positions.map(position=>{const column=columns[position];if(!grand)
2602
+ return column;const{groups:_groups,...leaf}=column;return leaf});const originalPosition=(position)=>{const columnIndex=positions[position.columnIndex];return{...position,columnIndex,column:columns[columnIndex]}};const repeatColumns=positions.flatMap((position,index)=>position===0||table.repeatedColumns.includes(position)?[index]:[]);const wideTable=table.options.wideTable;const projectedSettings={...sharedTable,repeatedColumns:Object.freeze(repeatColumns),options:{...table.options,columns:projected,...(table.options.columnWidths===undefined?{}:{columnWidths:positions.map(position=>table.options.columnWidths[position])}),...(typeof wideTable!=="object"?{}:{wideTable:{...wideTable,repeatColumns}}),...(table.options.formatValue===undefined?{}:{formatValue:(value,position)=>table.options.formatValue(value,originalPosition(position))}),...(table.options.formatRuns===undefined?{}:{formatRuns:(value,position)=>table.options.formatRuns(value,originalPosition(position))})}};const projectedLayout=new PdfTableLayout(projectedSettings,fonts);summaryLayouts.set(grand,projectedLayout);return projectedLayout};const prepareGroupContext=async()=>{const caption=await prepareParagraph(captureCaption({text:path.map(group=>group.label).join("\n"),presentation:{bold:true},spaceAfter:4},pages.settings,fonts),pages.settings,fonts);const continuation=await prepareParagraph(captureCaption({text:path.map(group=>{if(continuationLabel===undefined)
2603
+ return group.label;const existing=semantic?continuationLabels.get(group):undefined;if(existing!==undefined)
2604
+ return existing;const label=synchronousText(continuationLabel(group),"continuationLabel");if(semantic)
2605
+ continuationLabels.set(group,label);return label}).join("\n"),presentation:{bold:true},spaceAfter:4},pages.settings,fonts),pages.settings,fonts);return{caption,continuation}};const flushLastDetail=async()=>{if(pending){if(!started)
2606
+ await startLeaf(pending);if(closing.length&&!firstBundleOversized)
2607
+ await pages.keptRows([pending,...closing],firstFragment);else if(closing.length){await pages.row(pending,firstFragment);for(const row of closing)
2608
+ await pages.row(row)}
2609
+ else
2610
+ await pages.row(pending,firstFragment)}
2611
+ else
2612
+ for(const row of closing)
2613
+ await pages.row(row);pending=undefined;closing.length=0;firstFragment=false;firstBundleOversized=false};const finishLeaf=async()=>{if(!started&&!pending)
2614
+ return;await flushLastDetail();await pages.endTable();started=false};const startLeaf=async(row)=>{const{caption,continuation}=await prepareGroupContext();const bundleHeight=row.height+closing.reduce((height,summary)=>height+summary.height,0);const available=table.page.height-table.margins.top-table.margins.bottom-headingHeight-Math.max(caption?.height??0,continuation.height);firstBundleOversized=closing.length>0&&bundleHeight>available+.001;const minimum=closing.length>0&&!firstBundleOversized?bundleHeight:layout.minimumRowHeight(row);const groupHeadings=[];if(semantic)
2615
+ for(const group of path.slice(semanticDepth))
2616
+ groupHeadings.push(await prepareParagraph(captureParagraph({kind:"paragraph",text:group.label.trim()?group.label:"",headingLevel:(groupHeadingLevel+group.level),presentation:{bold:true},keepTogether:true,keepWithNext:true,spaceAfter:4,...(group.label.trim()?{bookmark:{title:group.label,level:(groupHeadingLevel+group.level)}}:{})},pages.settings,fonts),pages.settings,fonts));const groupHeight=groupHeadings.reduce((height,heading)=>height+heading.height,0);const ancestorCaption=semantic&&semanticDepth>0?await prepareParagraph(captureCaption({text:path.slice(0,semanticDepth).map(group=>group.label).join("\n"),presentation:{bold:true},spaceAfter:4},pages.settings,fonts),pages.settings,fonts):undefined;const openingHeight=semantic?(ancestorCaption?.height??0)+ groupHeight:caption.height;await context.flushParagraphs(openingHeight+headingHeight+minimum);if(ancestorCaption)
2617
+ await pages.paragraphs([ancestorCaption],groupHeight+headingHeight+minimum,true,{artifact:true});let followingHeight=groupHeight +(semantic?0:caption.height)+ headingHeight+minimum;for(const heading of groupHeadings){followingHeight -=heading.height;await pages.beginGroup(semanticDepth++,heading,followingHeight)}
2618
+ await pages.beginTable(layout,headings,minimum,caption,continuation,false,semantic,semantic);started=true;firstFragment=(caption?.lines.length??0)>0||groupHeadings.some(heading=>heading.lines.length>0)};const semanticSubtotal=async(row,level,values)=>{if(level===report.groupBy.length-1){pages.summary(row);closing.push(row);await finishLeaf();await pages.endGroup(level);semanticDepth=level;path=path.slice(0,level);return}
2619
+ await finishLeaf();const{caption,continuation}=await prepareGroupContext();const projected=summaryLayout(false),summaryHeadings=await projected.headers();const summaryRow=await projected.data(values,0,true),minimum=projected.minimumRowHeight(summaryRow);await context.flushParagraphs(caption.height+await projected.blockHeight(summaryHeadings)+ minimum);await pages.beginTable(projected,summaryHeadings,minimum,caption,continuation,false,true);pages.summary(summaryRow);await pages.row(summaryRow,caption.lines.length>0||summaryHeadings.length>0);await pages.endTable();await pages.endGroup(level);semanticDepth=level;path=path.slice(0,level)};const complete=async(summary)=>{await finishLeaf();if(!includeGrandTotal&&summary.rows!==0)
2620
+ return;const completeLayout=summary.rows===0?layout:summaryLayout(true);const completeHeadings=summary.rows===0?headings:await completeLayout.headers();rowIndex=-1;let total;if(includeGrandTotal){context.acceptRow(false);total=await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary),"grandTotalLabel"),summary.totals,summary.rows===0?undefined:aggregatePositions),0,true)}
2621
+ if(!completeHeadings.length&&!total)
2622
+ return;const minimum=total?completeLayout.minimumRowHeight(total):0;await context.flushParagraphs(await completeLayout.blockHeight(completeHeadings)+ minimum);await pages.beginTable(completeLayout,completeHeadings,minimum);if(total){if(semantic)
2623
+ pages.summary(total);await pages.row(total)}
2624
+ await pages.endTable()};await consumeRows(operation.events,operation.signal,async(event)=>{switch(event.kind){case "groupStart":
2625
+ await finishLeaf();if(semantic&&groupHeadingLevel+event.level>6)
2626
+ throw new RangeError("groupHeadingLevel and the opened group depth exceed heading level 6.");path=Object.freeze([...path.slice(0,event.level),event]);break;case "row":{if(pending)
2627
+ await flushLastDetail();rowIndex=event.rowIndex;context.acceptRow(true);const row=await layout.data([new ExportCell("",{text:""}),...event.values],event.rowIndex);pending=row;break}
2628
+ case "groupEnd":{rowIndex=-1;context.acceptRow(false);const separate=semantic&&event.level!==report.groupBy.length-1;const values=summaryValues(synchronousText(subtotalLabel(event),"subtotalLabel"),event.totals,separate?aggregatePositions:undefined);const row=separate?undefined:await layout.data(values,0,true);if(semantic)
2629
+ await semanticSubtotal(row,event.level,values);else
2630
+ closing.push(row);break}
2631
+ case "complete":
2632
+ await complete(event);break}})}
2633
+ finally{operation.signal?.removeEventListener("abort",abort);operation.dispose()}}
2634
+ const _exports=Object.freeze({renderGroupedPdfTable:renderGroupedPdfTable});_modules.set("289fa3a052c7fbab2a3ca0fb91fb9974db709d24b7d850f1175810258f0409a0",_exports);return _exports})();const _m84=_modules.get("9051bf9fc3168e24b53b16c123a42816198456846003fb49191c03a18cdab904")??(()=>{const{BlobByteSink,withDestination}=_m3;const{OfficeIMOError}=_m2;const{beginTask,checkAbort,consumeRows,pause,taskYieldDue}=_m4;const{notifyProgress}=_m14;const{copyColumns,createRowProjector}=_m11;const{captureFields}=_m10;const{settings,captureWideTable}=_m17;const{pdfNumber:n}=_m60;const{PdfTableLayout}=_m69;const{PdfWriteSession}=_m59;const{PdfDocumentImages}=_m85;const{vectorCommands}=_m87;const{graphicAlternative}=_m80;const{checkDrawingBlock,prepareDrawing}=_m88;const{captureParagraph,captureCaption,prepareParagraph,checkParagraphBuffer,paragraphStartHeight}=_m89;const{captureListOptions,prepareListItem}=_m90;const{captureSection}=_m78;const{renderGroupedPdfTable}=_m91;const tableOptionFields=["columns","includeHeader","headerRows","footer","headerPresentation","footerPresentation","alternateRowColor","columnWidths","wideTable","formatValue","formatRuns"];function pdfTable(rows,options){const captured=captureTableOptions(options);return Object.freeze({kind:"table",rows,options:Object.freeze({...captured,columns:Object.freeze(copyColumns(captured.columns))})})}
2635
+ async function writePdfDocument(blocks,options={}){const sink=new BlobByteSink();try{await writePdfDocumentTo(blocks,sink,options);return sink.toBlob("application/pdf")}
2636
+ catch(error){sink.discard();throw error}}
2637
+ async function writePdfDocumentTo(blocks,destination,configuration={}){const captured=settings(configuration,true),controller=new AbortController();const parentSignal=captured.options.signal,abort=()=>controller.abort(parentSignal?.reason);parentSignal?.addEventListener("abort",abort,{once:true});if(parentSignal?.aborted)
2638
+ abort();const prepared={...captured,options:{...captured.options,signal:controller.signal}},{options,budget}=prepared;try{beginTask();checkAbort(options.signal);return await withDestination(destination,async(sink)=>{const session=new PdfWriteSession(sink,prepared),{objects,pages,fonts}=session,images=new PdfDocumentImages(objects,prepared);let rows=0,budgetRows=0,columns=0,commands=0,drawingElements=0,listItems=0;let pending=[];const flushParagraphs=async(nextHeight=0)=>{const paragraphs=[];for(const paragraph of pending)
2639
+ paragraphs.push(await prepareParagraph(paragraph,pages.settings,fonts));pending=[];await pages.paragraphs(paragraphs,nextHeight)};const enqueueParagraph=async(block)=>{const paragraph=captureParagraph(block,pages.settings,fonts);if(!paragraph.text.text)
2640
+ return;if(pending.length||paragraph.keepWithNext){pending.push(paragraph);checkParagraphBuffer(pending,pages.settings);if(!paragraph.keepWithNext)
2641
+ await flushParagraphs()}
2642
+ else
2643
+ await pages.paragraphs([await prepareParagraph(paragraph,pages.settings,fonts)])};const prepareCaption=async(captured)=>captured===undefined?undefined:prepareParagraph(captured,pages.settings,fonts);const snapshotCaption=(caption)=>caption===undefined?undefined:captureCaption(caption,pages.settings,fonts);await session.start();await consumeRows(blocks,options.signal,async(block)=>{if(!block||typeof block!=="object")
2644
+ throw new TypeError("PDF document blocks must be objects.");switch(block.kind){case "section":{const capturedSection=captureSection(block,prepared);await flushParagraphs();const section=await pages.beginSection(capturedSection);if(section.includeHeading)
2645
+ await enqueueParagraph({kind:"paragraph",text:section.title,headingLevel:section.level,...(section.headingStyle===undefined?
2646
+ {fontSize:pages.settings.fontSize*1.5,presentation:{bold:true}}:{style:section.headingStyle}),keepTogether:true,keepWithNext:true,...(section.bookmark?{bookmark:{title:section.title,level:section.level}}:{})});else if(section.bookmark)
2647
+ pages.addBookmark({title:section.title,level:section.level});break}
2648
+ case "paragraph":
2649
+ await enqueueParagraph(block);break;case "list":{const captured=captureListOptions(block,pages.settings);let count=0,owner;await consumeRows(captured.items,options.signal,async(item)=>{if(++listItems>prepared.limits.maxListItems)
2650
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxListItems exceeded.");const laidOut=await prepareListItem(item,count++,captured,pages.settings,fonts);if(count===1){await flushParagraphs(laidOut.paragraph.keepTogether?laidOut.paragraph.height:laidOut.paragraph.firstHeight);owner=session.structure?.element("L")}
2651
+ await pages.listItem(laidOut,owner);if(taskYieldDue())
2652
+ await pause();checkAbort(options.signal)});await session.structure?.complete(owner);break}
2653
+ case "group":{const blocks=block.blocks,keepTogether=block.keepTogether;if(!Array.isArray(blocks))
2654
+ throw new TypeError("PDF paragraph group blocks must be an array.");if(keepTogether!==undefined&&typeof keepTogether!=="boolean")
2655
+ throw new TypeError("PDF paragraph group keepTogether must be boolean.");if(blocks.length>prepared.limits.maxGroupBlocks)
2656
+ throw new OfficeIMOError("RESOURCE_LIMIT","maxGroupBlocks exceeded.");const captured=[];for(const paragraph of blocks){captured.push(captureParagraph(paragraph,pages.settings,fonts));checkParagraphBuffer(captured,prepared)}
2657
+ if(captured.filter(paragraph=>paragraph.text.text).at(-1)?.keepWithNext)
2658
+ throw new TypeError("The last paragraph in a group cannot keepWithNext beyond the group's boundary.");const paragraphs=[];for(const paragraph of captured)
2659
+ paragraphs.push(await prepareParagraph(paragraph,pages.settings,fonts));if(!paragraphs.some(paragraph=>paragraph.lines.length>0))
2660
+ break;await flushParagraphs(keepTogether!==false?paragraphs.reduce((height,paragraph)=>height+paragraph.height,0):paragraphStartHeight(paragraphs));await pages.paragraphs(paragraphs,0,keepTogether!==false);break}
2661
+ case "pageBreak":
2662
+ await flushParagraphs();await pages.pageBreak();break;case "groupedTable":
2663
+ await renderGroupedPdfTable(block,{prepared,pages,fonts,controller,flushParagraphs,acceptColumns:count=>{columns=Math.max(columns,count)},acceptRow:source=>{budget.row(++budgetRows);if(source&&++rows%256===0)
2664
+ notifyProgress(options.onProgress,{phase:"rows",rows,bytes:objects.bytes})}});break;case "table":{const{options:inputTableOptions,rows:source,caption:inputCaption,continuationCaption:inputContinuationCaption}=block;const tableOptions=captureTableOptions(inputTableOptions);const capturedCaption=snapshotCaption(inputCaption);const capturedContinuationCaption=snapshotCaption(inputContinuationCaption);const table=settings({...pages.settings.options,...tableOptions,columns:tableOptions?.columns,includeHeader:tableOptions?.includeHeader??true}),layout=new PdfTableLayout({...table,budget},fonts);const caption=await prepareCaption(capturedCaption);const continuationCaption=await prepareCaption(capturedContinuationCaption);const project=createRowProjector(table.options.columns,undefined,options.signal);let count=0,started=false;columns=Math.max(columns,table.options.columns.length);const headings=await layout.headers(),headingHeight=await layout.blockHeight(headings);await consumeRows(source,options.signal,async(row)=>{budget.row(++budgetRows);const laidOut=await layout.data(project(row,count),count),keptHeading=!started&&(pending.length>0||!!caption?.lines.length);if(!started){const minimum=layout.minimumRowHeight(laidOut);await flushParagraphs((caption?.height??0)+ headingHeight+minimum);await pages.beginTable(layout,headings,minimum,caption,continuationCaption);started=true}
2665
+ await pages.row(laidOut,keptHeading);count++;rows++;if(rows%256===0)
2666
+ notifyProgress(options.onProgress,{phase:"rows",rows,bytes:objects.bytes});if(taskYieldDue())
2667
+ await pause();checkAbort(options.signal)});const footer=await layout.footer(count),keptFooterHeading=!started&&(pending.length>0||!!caption?.lines.length);if(!started){if(!headings.length&&!footer?.length)
2668
+ break;const minimum=footer?.length?table.options.footer?.rows?await layout.blockHeight(footer):
2669
+ layout.minimumRowHeight(footer[0]):0;await flushParagraphs((caption?.height??0)+ headingHeight+minimum);await pages.beginTable(layout,headings,minimum,caption,continuationCaption)}
2670
+ if(footer){if(table.options.footer?.rows)
2671
+ await pages.block(footer);else
2672
+ await pages.row(footer[0],keptFooterHeading)}
2673
+ await pages.endTable();break}
2674
+ case "image":{const{width:displayWidth,height:displayHeight,image:inputImage,caption:inputCaption}=block;const capturedCaption=snapshotCaption(inputCaption),alternative=graphicAlternative(block,pages.settings),alignment=graphicAlignment(block.alignment);if(capturedCaption&&alternative===undefined)
2675
+ throw new TypeError("A captioned PDF graphic requires alternativeText and cannot be decorative.");const image=await images.prepare(inputImage),caption=await prepareCaption(capturedCaption);const width=displayWidth??(displayHeight===undefined?image.width*.75:displayHeight*image.width / image.height);
2676
+ const height=displayHeight??width*image.height / image.width;
2677
+ if(!Number.isFinite(width)||width<=0||!Number.isFinite(height)||height<=0)
2678
+ throw new RangeError("Image display dimensions must be finite and positive.");await flushParagraphs((caption?.height??0)+ pages.graphicHeight(width,height));pages.registerXObject(image.name,image.id);await pages.graphic(width,height,alignment,(x,y,w,h)=>"q " +[w,0,0,h,x,y].map(n).join(" ")+ " cm /"+image.name+" Do Q\n",alternative,caption);break}
2679
+ case "vector":{const capturedCaption=snapshotCaption(block.caption),alternative=graphicAlternative(block,pages.settings),alignment=graphicAlignment(block.alignment);if(capturedCaption&&alternative===undefined)
2680
+ throw new TypeError("A captioned PDF graphic requires alternativeText and cannot be decorative.");const path=await vectorCommands(block,pages.settings,commands),caption=await prepareCaption(capturedCaption);commands +=path.count;await flushParagraphs((caption?.height??0)+ pages.graphicHeight(path.width,path.height));await pages.graphic(path.width,path.height,alignment,(x,y,w,h)=>"q " +[w / path.width, 0, 0, -h / path.height, x, y + h].map(n).join(" ") +
2681
+ " cm 0 0 "+n(path.width)+ " "+n(path.height)+ " re W n\n"+path.content+"Q\n",alternative,caption);break}
2682
+ case "drawing":{checkDrawingBlock(block);const inputDrawing=block.drawing,capturedCaption=snapshotCaption(block.caption),alternative=graphicAlternative(block,pages.settings),alignment=graphicAlignment(block.alignment);if(capturedCaption&&alternative===undefined)
2683
+ throw new TypeError("A captioned PDF graphic requires alternativeText and cannot be decorative.");const drawing=await prepareDrawing(inputDrawing,pages.settings,fonts,{commands,elements:drawingElements}),caption=await prepareCaption(capturedCaption);commands +=drawing.commands;drawingElements +=drawing.elements;await flushParagraphs((caption?.height??0)+ pages.graphicHeight(drawing.width,drawing.height));await pages.graphic(drawing.width,drawing.height,alignment,(x,y,w,h)=>"q " +[w / drawing.width, 0, 0, -h / drawing.height, x, y + h].map(n).join(" ") +
2684
+ " cm 0 0 "+n(drawing.width)+ " "+n(drawing.height)+ " re W n\n"+drawing.content+"Q\n",alternative,caption);break}
2685
+ default:throw new TypeError("Unsupported PDF document block.")}
2686
+ if(taskYieldDue())
2687
+ await pause();checkAbort(options.signal)});await flushParagraphs();if(options.messageBottom)
2688
+ await pages.paragraph(options.messageBottom);await session.finish();notifyProgress(options.onProgress,{phase:"complete",rows,bytes:objects.bytes});checkAbort(options.signal);return{rows,columns,bytes:objects.bytes}})}
2689
+ finally{parentSignal?.removeEventListener("abort",abort)}}
2690
+ function graphicAlignment(value){if(value!==undefined&&!["left","center","right"].includes(value))
2691
+ throw new TypeError("Invalid graphic alignment.");return value??"left"}
2692
+ function captureTableOptions(options){if(!options||typeof options!=="object"||Object.keys(options).some(key=>!tableOptionFields.includes(key)))
2693
+ throw new TypeError("Table options support columns, headings, footers, widths and presentation; document settings belong on writePdfDocument.");const captured=captureFields(options,tableOptionFields);return{...captured,...(captured.wideTable===undefined?{}:{wideTable:captureWideTable(captured.wideTable)})}}
2694
+ const _exports=Object.freeze({pdfTable:pdfTable,writePdfDocument:writePdfDocument,writePdfDocumentTo:writePdfDocumentTo});_modules.set("9051bf9fc3168e24b53b16c123a42816198456846003fb49191c03a18cdab904",_exports);return _exports})();const _m83=_modules.get("abe76e52ffeed11ab42477c83ddde1d1d7de28b803096436b5b23cb153af58ba")??(()=>{const{assertGroupedReportSource}=_m8;const{BlobByteSink}=_m3;const{writePdfDocumentTo}=_m84;const{pdfOptionFields}=_m17;const{captureFields}=_m10;const{pdfGroupedTable,groupedPdfLabelFields,groupedPdfTableFields}=_m92;const groupedOptionFields=[...pdfOptionFields,...groupedPdfLabelFields];async function writeGroupedPdf(report,configuration){const sink=new BlobByteSink();try{await writeGroupedPdfTo(report,sink,configuration);return sink.toBlob("application/pdf")}
2695
+ catch(error){sink.discard();throw error}}
2696
+ async function writeGroupedPdfTo(report,destination,configuration){assertGroupedReportSource(report);if(!configuration||typeof configuration!=="object")
2697
+ throw new TypeError("Grouped PDF options are required.");const captured=captureFields(configuration,groupedOptionFields);const tableOptions=Object.fromEntries(groupedPdfTableFields.filter(name=>Object.hasOwn(captured,name)).map(name=>[name,captured[name]]));const documentOptions={...captured};for(const name of groupedPdfTableFields)
2698
+ delete documentOptions[name];delete documentOptions.columns;delete documentOptions.headerRows;delete documentOptions.footer;return writePdfDocumentTo([pdfGroupedTable(report,tableOptions)],destination,documentOptions)}
2699
+ const _exports=Object.freeze({pdfGroupedTable:_m92.pdfGroupedTable,writeGroupedPdf:writeGroupedPdf,writeGroupedPdfTo:writeGroupedPdfTo});_modules.set("abe76e52ffeed11ab42477c83ddde1d1d7de28b803096436b5b23cb153af58ba",_exports);return _exports})();const _m93=_modules.get("3d777096288d1be55a05a80bc015d4674212e587703f25a7e7cf99a8065feb86")??(()=>{const{fontProgram}=_m63;const{resolveScalar,selectFont,validateFonts}=_m67;function preflightPdfText(text,options={}){if(typeof text!=="string")
2700
+ throw new TypeError("PDF preflight text must be a string.");if(!options||typeof options!=="object")
2701
+ throw new TypeError("PDF preflight options must be an object.");for(const key of["bold","italic"])
2702
+ if(options[key]!==undefined&&typeof options[key]!=="boolean")
2703
+ throw new TypeError("PDF preflight "+key+" must be boolean.");validateFonts(options.fonts);const bold=options.bold??false,{font}=selectFont(options.fonts,bold,options.italic??false);const program=font?fontProgram(font):undefined,checked=new Set();for(let index=0;index<text.length;){const scalar=text.codePointAt(index);const displayed=scalar===9?32:scalar;if(scalar!==10&&scalar!==13&&!checked.has(displayed)){const result=resolveScalar(displayed,program,bold);if(!result.supported)
2704
+ return{...result,index,...(result.code==="unpaired-surrogate"?{}:{scalar})};checked.add(displayed)}
2705
+ index +=scalar>0xffff?2:1}
2706
+ return{supported:true}}
2707
+ const _exports=Object.freeze({preflightPdfText:preflightPdfText});_modules.set("3d777096288d1be55a05a80bc015d4674212e587703f25a7e7cf99a8065feb86",_exports);return _exports})();const _m57=_modules.get("027aafa08408056b10d7d717d63d1f7c0ee20ecfc68213aa66feacc75ec525fe")??(()=>{const _exports=Object.freeze({writePdf:_m58.writePdf,writePdfTo:_m58.writePdfTo,writeGroupedPdf:_m83.writeGroupedPdf,writeGroupedPdfTo:_m83.writeGroupedPdfTo,pdfGroupedTable:_m83.pdfGroupedTable,createGroupedReport:_m8.createGroupedReport,writePdfDocument:_m84.writePdfDocument,writePdfDocumentTo:_m84.writePdfDocumentTo,pdfTable:_m84.pdfTable,PdfFont:_m63.PdfFont,preflightPdfText:_m93.preflightPdfText,ExportCell:_m5.ExportCell,saveBlob:_m1.saveBlob});_modules.set("027aafa08408056b10d7d717d63d1f7c0ee20ecfc68213aa66feacc75ec525fe",_exports);return _exports})();const _m95=_modules.get("c0aee2c5df0df3e62ca31fc685243cdd4b449f083834e8d28cf92c20dfa7b27f")??(()=>{function datetime(value,mode,clock){if(mode==="text")
2708
+ return value;const match=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:\d{2})$/.exec(value);
2709
+ if(!match)
2710
+ throw new TypeError("Canopy datetime values require an ISO timestamp with an explicit time zone.");const date=new Date(value);const offset=match[8]==="Z"?0:(match[8][0]==="+"?1:-1)*(Number(match[8].slice(1,3))*60+Number(match[8].slice(4)));const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]);const hour=Number(match[4]),minute=Number(match[5]),second=Number(match[6]??"0"),fraction=match[7]??"";const wall=new Date(0);wall.setUTCFullYear(year,month-1,day);if(!Number.isFinite(date.getTime())||Number(match[8].slice(1,3))>23||Number(match[8].slice(4))>59||
2711
+ wall.getUTCFullYear()!==year||wall.getUTCMonth()+ 1!==month||wall.getUTCDate()!==day||
2712
+ hour>24||minute>59||second>59||hour===24&&(minute!==0||second!==0||/[1-9]/.test(fraction)))
2713
+ throw new TypeError("Invalid Canopy datetime value.");wall.setUTCHours(hour,minute,second,Number((fraction+"000").slice(0,3)));if(wall.getTime()!==date.getTime()+ offset*60000)
2714
+ throw new TypeError("Invalid Canopy datetime value.");if(/[1-9]/.test(fraction.slice(3))) {
2715
+ if(mode==="typed")
2716
+ throw new TypeError("Typed Excel dates cannot preserve sub-millisecond precision; use datetime: preserve or text.");return value}
2717
+ const excelYear=clock==="utc"?date.getUTCFullYear():date.getFullYear();if(excelYear<1900||excelYear>9999){if(mode==="typed")
2718
+ throw new TypeError("Typed Excel dates require years 1900 through 9999; use datetime: preserve or text.");return value}
2719
+ return date}
2720
+ const _exports=Object.freeze({datetime:datetime});_modules.set("c0aee2c5df0df3e62ca31fc685243cdd4b449f083834e8d28cf92c20dfa7b27f",_exports);return _exports})();const _m96=_modules.get("3d1862d8ab32171bca4b3ba5fe0bdcc073f67ce940aaff0ee735635893f86ee8")??(()=>{function canopyDiagnostics(format,options){const policy=options.unsupportedPresentation??(format==="csv"?"text":"reject"),notify=options.onDiagnostic;if(policy!=="reject"&&policy!=="text")
2721
+ throw new TypeError("unsupportedPresentation must be reject or text.");if(notify!==undefined&&typeof notify!=="function")
2722
+ throw new TypeError("onDiagnostic must be a synchronous function.");return diagnostic=>{if(policy==="reject")
2723
+ throw new TypeError("Unsupported Canopy presentation: "+diagnostic.code +(diagnostic.columnId?" ("+diagnostic.columnId+")":""));const result=notify?.(Object.freeze(diagnostic));if(result&&typeof result.then==="function"){void Promise.resolve(result).catch(()=>{});throw new TypeError("onDiagnostic must be synchronous.")}}}
2724
+ const _exports=Object.freeze({canopyDiagnostics:canopyDiagnostics});_modules.set("3d1862d8ab32171bca4b3ba5fe0bdcc073f67ce940aaff0ee735635893f86ee8",_exports);return _exports})();const _m97=_modules.get("040752afe195985e6f2e91f8c62fc13464c455fc44034b8cef4828851e05b83d")??(()=>{function canopyXlsxWidth(pixels){const width=Math.floor((pixels<12?pixels / 12 : (pixels - 5) / 7) * 256) / 256;
2725
+ if(!Number.isFinite(width)||width<=0||width>255)
2726
+ throw new RangeError("Captured width exceeds the Calibri-11 XLSX width profile.");return width}
2727
+ function canopyNumberFormat(input,report,id){if(!input||typeof input!=="object"||Array.isArray(input))
2728
+ throw new TypeError("Canopy numeric format must be an object.");if(Object.keys(input).some(key=>!["minimumFractionDigits","maximumFractionDigits","prefix","suffix"].includes(key))){report({code:"UNSUPPORTED_NUMBER_FORMAT",columnId:id});return undefined}
2729
+ const{minimumFractionDigits:minimum=0,maximumFractionDigits:maximum=3,prefix="",suffix=""}=input;if(!Number.isInteger(minimum)||!Number.isInteger(maximum)||minimum<0||maximum<minimum||maximum>10||
2730
+ typeof prefix!=="string"||typeof suffix!=="string"||prefix.length>16||suffix.length>16)
2731
+ throw new TypeError("Canopy numeric fraction bounds must be ordered integers from zero through ten, with literal affixes of at most sixteen characters.");const literal=(value)=>value?'"'+value.replace(/"/g, '"\\""') + '"' : "";
2732
+ return literal(prefix)+ "0" +(maximum?"."+"0".repeat(minimum)+ "#".repeat(maximum-minimum):"")+ literal(suffix)}
2733
+ function canopyPins(columns,report){let leading=0,ended=false;for(const column of columns){const pin=column.pinned;if(pin!==undefined&&pin!==null&&pin!=="left"&&pin!=="right")
2734
+ throw new TypeError("Invalid Canopy pin.");if(!ended&&pin==="left")
2735
+ leading++;else{ended=true;if(pin==="left"||pin==="right")
2736
+ report({code:"UNREPRESENTABLE_PIN:"+pin,columnId:column.id})}}
2737
+ return leading}
2738
+ const _exports=Object.freeze({canopyXlsxWidth:canopyXlsxWidth,canopyNumberFormat:canopyNumberFormat,canopyPins:canopyPins});_modules.set("040752afe195985e6f2e91f8c62fc13464c455fc44034b8cef4828851e05b83d",_exports);return _exports})();const _m94=_modules.get("a92d57114c08988b60d7dc46d24aeea3096cb6c695c12a7ea26761010692ef43")??(()=>{const{ExportCell,checkAbort,inputRows}=_m1;const{datetime}=_m95;const{captureFields}=_m10;const{copyColumns}=_m11;const{copyCellPresentation}=_m5;const{canopyDiagnostics}=_m96;const{canopyNumberFormat,canopyXlsxWidth}=_m97;const columnFields=["width","format","wrapText","alignment","rowHeader","groups"];function createCanopyExport(capture,format,options={}){return prepareCanopyExport(capture,format,options).source}
2739
+ function prepareCanopyExport(capture,format,options={}){options=captureFields(options,["tones","columnOptions","unsupportedPresentation","datetime","xlsx","signal","onDiagnostic"]);if(format!=="xlsx"&&format!=="csv"&&format!=="pdf")
2740
+ throw new TypeError("Canopy export format must be xlsx, csv or pdf.");if(!capture||typeof capture.rows!=="function"||!capture.request)
2741
+ throw new TypeError("A portable CanopyX capture with request and rows() is required.");const request=captureFields(capture.request,["columns","recordCount","values","presentation","timeZone","revision","scope","total","matched","selection","query","generatedAt","grouping","formatRules"]);const signal=options.signal,values=request.values;if(!Array.isArray(request.columns)||!request.columns.length||(request.recordCount!==null&&(!Number.isSafeInteger(request.recordCount)||request.recordCount<0))||
2742
+ (values!=="raw"&&values!=="display")||(request.timeZone!=="utc"&&request.timeZone!=="local")||typeof request.revision!=="string")
2743
+ throw new TypeError("Invalid portable CanopyX capture metadata.");const dateMode=options.datetime??"preserve",report=canopyDiagnostics(format,options);const clock=options.xlsx?.dateMode??request.timeZone;if(clock!=="utc"&&clock!=="local")
2744
+ throw new TypeError("XLSX dateMode must be utc or local.");if(dateMode!=="preserve"&&dateMode!=="typed"&&dateMode!=="text")
2745
+ throw new TypeError("datetime must be preserve, typed or text.");const diagnostics=(items,rowId,columnId)=>{if(items===undefined)
2746
+ return;if(!Array.isArray(items)||items.some(item=>typeof item!=="string"))
2747
+ throw new TypeError("Canopy presentation diagnostics must be strings.");for(const code of items)
2748
+ report({code,...(rowId===undefined?{}:{rowId}),...(columnId===undefined?{}:{columnId})})};if(request.presentation!=="text"&&request.presentation!=="semantic")
2749
+ throw new TypeError("Canopy captures must declare text or semantic presentation.");const tones=new Map(Object.entries(options.tones??{}).map(([name,style])=>{if(!style||typeof style!=="object"||Array.isArray(style))
2750
+ throw new TypeError("Tone mappings must be portable presentation objects.");return[name,copyCellPresentation(style)]}));const tone=(name,rowId,columnId)=>{if(name===undefined)
2751
+ return undefined;if(typeof name!=="string")
2752
+ throw new TypeError("Canopy tones must be strings.");const style=tones.get(name);if(!style&&name!=="neutral")
2753
+ report({code:"UNMAPPED_TONE:"+name,rowId,...(columnId===undefined?{}:{columnId})});return style};const ids=new Set();const specs=request.columns.map(input=>{const fields=captureFields(input,["id","title","kind","width","pinned","format","wrap","alignment","diagnostics"]);const column=Object.freeze({...fields,...(fields.width===undefined?{}:{width:Object.freeze(captureFields(fields.width,["unit","preferred","minimum","maximum"]))}),...(fields.format===undefined?{}:{format:Object.freeze(captureFields(fields.format,["minimumFractionDigits","maximumFractionDigits","prefix","suffix"]))})});if(!column||typeof column.id!=="string"||!column.id||ids.has(column.id)||typeof column.title!=="string"||
2754
+ !["text","number","datetime"].includes(column.kind)||
2755
+ (column.wrap!==undefined&&typeof column.wrap!=="boolean")||(column.alignment!==undefined&&!["left","right"].includes(column.alignment))||
2756
+ (column.width!==undefined&&(column.width.unit!=="css-px"||!Number.isFinite(column.width.preferred)||
2757
+ !Number.isFinite(column.width.minimum)||column.width.minimum<=0||column.width.preferred<column.width.minimum||
2758
+ column.width.maximum!==undefined&&(!Number.isFinite(column.width.maximum)||column.width.maximum<column.width.preferred)))||
2759
+ (request.presentation==="semantic"&&(column.wrap===undefined||column.alignment===undefined||column.width===undefined)))
2760
+ throw new TypeError("Invalid or duplicate Canopy export column.");ids.add(column.id);diagnostics(column.diagnostics,undefined,column.id);const selected=Object.hasOwn(options.columnOptions??{},column.id)?options.columnOptions[column.id]:{};for(const key of Object.keys(selected))
2761
+ if(!columnFields.includes(key))
2762
+ throw new TypeError("Unsupported Canopy column option: "+key);const override=captureFields(selected,columnFields);const numericFormat=format==="xlsx"&&values==="raw"&&column.kind==="number"&&column.format!==undefined&&override.format===undefined
2763
+ ?canopyNumberFormat(column.format,report,column.id):undefined;const[captured]=copyColumns([{...override,key:column.id,header:column.title,...(format==="xlsx"&&override.width===undefined&&column.width!==undefined?{width:canopyXlsxWidth(column.width.preferred)}:{}),...(override.format===undefined&&numericFormat!==undefined?{format:numericFormat}:{}),...(format==="xlsx"&&values==="raw"&&column.kind==="datetime"&&override.format===undefined?{format:"yyyy-mm-dd hh:mm:ss.000"}:{}),...(values==="raw"&&column.kind==="number"?{type:"number"}:{}),...(override.wrapText===undefined&&column.wrap===undefined?{}:{wrapText:override.wrapText??column.wrap}),...(override.alignment===undefined&&column.alignment===undefined?{}:{alignment:override.alignment??column.alignment})}]);return Object.freeze({id:column.id,kind:column.kind,input:column,column:Object.freeze(captured)})});const rowCount=request.recordCount;const source=Object.freeze({columns:Object.freeze(specs.map(spec=>spec.column)),rowCount,async*rows(){checkAbort(signal);let count=0;for await(const row of inputRows(capture.rows(signal?{signal}:{}),signal)){checkAbort(signal);if(!row||typeof row.id!=="string"||!row.cells||typeof row.cells!=="object")
2764
+ throw new TypeError("Invalid Canopy export record.");diagnostics(row.diagnostics,row.id);const rowStyle=tone(row.tone,row.id),result=[];for(const spec of specs){if(!Object.hasOwn(row.cells,spec.id))
2765
+ throw new TypeError("Canopy record is missing column "+spec.id+".");const cell=row.cells[spec.id];if(!cell||typeof cell!=="object"||typeof cell.text!=="string"||
2766
+ (cell.value!==null&&!["string","number","boolean"].includes(typeof cell.value))||
2767
+ (typeof cell.value==="number"&&(!Number.isFinite(cell.value)||Math.abs(cell.value)>Number.MAX_SAFE_INTEGER)))
2768
+ throw new TypeError("A portable Canopy GridExportCell with scalar value and resolved text is required.");diagnostics(cell.diagnostics,row.id,spec.id);let value=values==="display"?cell.text:cell.value;if(format==="xlsx"&&values==="raw"&&spec.kind==="datetime"&&typeof value==="string")
2769
+ value=datetime(value,dateMode,clock);const cellStyle=tone(cell.tone,row.id,spec.id),presentation=rowStyle||cellStyle?{...rowStyle,...cellStyle}:undefined;result.push(format==="csv"?value:new ExportCell(value,{text:cell.text,...(presentation?{presentation}:{}),...(cell.link===undefined?{}:{link:cell.link})}))}
2770
+ if(rowCount!==null&&count>=rowCount)
2771
+ throw new TypeError("Canopy capture exceeded its declared recordCount.");count++;yield result}
2772
+ if(rowCount!==null&&count!==rowCount)
2773
+ throw new TypeError("Canopy capture did not produce its declared recordCount.")}});return Object.freeze({source,request:Object.freeze({...request,columns:Object.freeze(specs.map(spec=>spec.input))}),report,tones})}
2774
+ const _exports=Object.freeze({createCanopyExport:createCanopyExport,prepareCanopyExport:prepareCanopyExport});_modules.set("a92d57114c08988b60d7dc46d24aeea3096cb6c695c12a7ea26761010692ef43",_exports);return _exports})();const _m99=_modules.get("237239bcf5fa7675f75c53d2f367d843e089051bfd9f586770330a2c504ce1f7")??(()=>{const{columnName,excelDate}=_m35;const{captureFields}=_m10;const{datetime}=_m95;function canopyPredicate(request,grouped,options,root,unsupported,cellTypes){let nodes=0;const operations={eq:"=",ne:"<>",gt:">",ge:">=",lt:"<",le:"<="};const numeric=(value)=>{const number=typeof value==="boolean"?Number(value):typeof value==="string"?Number(value):value;if(typeof value==="string"){const text=value.trim().toLowerCase();if(Number.parseFloat(value)!==number||["0x","0b","0o"].some(prefix=>text.startsWith(prefix)))
2775
+ return unsupported("UNSUPPORTED_NUMERIC_RULE_LITERAL")}
2776
+ if(!Number.isFinite(number)||Math.abs(number)>Number.MAX_SAFE_INTEGER)
2777
+ throw new TypeError("Canopy rule comparison values must be finite safe-range numbers.");return number};const date=(value)=>{if(options.datetime!=="typed"||(options.xlsx?.dateMode??request.timeZone)!=="utc")
2778
+ return unsupported("DATETIME_RULE_REQUIRES_TYPED_UTC");if(typeof value==="boolean")
2779
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");if(typeof value==="number"&&!Number.isSafeInteger(value))
2780
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");try{const literal=typeof value==="number"?new Date(value).toISOString():value;const captured=datetime(literal,"typed","utc");if(!(captured instanceof Date))
2781
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");const serial=excelDate(captured,"utc");if(serial===null)
2782
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");return serial}
2783
+ catch(error){if(!(error instanceof TypeError)&&!(error instanceof RangeError))
2784
+ throw error;return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL")}};const leaf=(input)=>{if(++nodes>64)
2785
+ return unsupported("RULE_PREDICATE_LIMIT");const filter=captureFields(input,["column","operator","values"]),operation=operations[filter.operator];if(Object.keys(filter).some(key=>!["column","operator","values"].includes(key)))
2786
+ return unsupported("UNSUPPORTED_RULE_FILTER_OPTIONS");const index=request.columns.findIndex(column=>column.id===filter.column);if(index<0)
2787
+ return unsupported("RULE_COLUMN_NOT_EXPORTED:"+filter.column);const column=request.columns[index],letter=columnName(index+1 +(grouped?1:0));const reference="INDEX($"+letter+":$"+letter+",ROW())",present="NOT(ISBLANK("+reference+"))";if(column.kind==="number")
2788
+ cellTypes.set(index,"number");if(column.kind==="datetime"){if(options.datetime!=="typed"||(options.xlsx?.dateMode??request.timeZone)!=="utc")
2789
+ return unsupported("DATETIME_RULE_REQUIRES_TYPED_UTC");cellTypes.set(index,"date")}
2790
+ if(filter.operator==="isNull"||filter.operator==="isNotNull"){if(filter.values!==undefined&&filter.values.length)
2791
+ return unsupported("UNSUPPORTED_NULL_RULE_OPERANDS");return filter.operator==="isNull"?"ISBLANK("+reference+")":present}
2792
+ if(!operation||!Array.isArray(filter.values)||filter.values.length!==1)
2793
+ return unsupported("UNSUPPORTED_RULE_FILTER:"+filter.operator);const value=filter.values[0];if(typeof value!=="string"&&typeof value!=="number"&&typeof value!=="boolean")
2794
+ throw new TypeError("Canopy rule values must be portable scalars.");if(column.kind==="number"||column.kind==="datetime"){const operand=column.kind==="number"?numeric(value):date(value);return "AND("+present+",ISNUMBER("+reference+"),"+reference+operation+String(operand)+ ")"}
2795
+ if(filter.operator!=="eq"&&filter.operator!=="ne")
2796
+ return unsupported("UNSUPPORTED_TEXT_RULE_COMPARISON");if(typeof value==="string")
2797
+ return unsupported("UNQUALIFIED_NATIVE_TEXT_COMPARISON");const kind=typeof value==="boolean"?"ISLOGICAL":"ISNUMBER";const literal=typeof value==="boolean"?value?"TRUE":"FALSE":String(numeric(value));const sameType=kind+"("+reference+")",comparison=reference+operation+literal;return filter.operator==="eq"?"AND("+present+","+sameType+","+comparison+")"
2798
+ :"AND("+present+",OR(NOT("+sameType+"),"+comparison+"))"};const visit=(input,depth)=>{if(depth>4||++nodes>64)
2799
+ return unsupported("RULE_PREDICATE_LIMIT");if(!input||typeof input!=="object")
2800
+ throw new TypeError("Canopy rule predicate must be an object.");const captured=captureFields(input,["operator","filters","groups"]);if(captured.operator!=="and"&&captured.operator!=="or")
2801
+ return unsupported("UNSUPPORTED_RULE_BOOLEAN:"+captured.operator);const filters=captured.filters??[],groups=captured.groups??[];if(!Array.isArray(filters)||!Array.isArray(groups))
2802
+ throw new TypeError("Canopy predicate filters and groups must be arrays.");const terms=[];for(const filter of filters)
2803
+ terms.push(leaf(filter));for(const group of groups)
2804
+ terms.push(visit(group,depth+1));if(!terms.length)
2805
+ return unsupported("EMPTY_RULE_PREDICATE");return captured.operator.toUpperCase()+ "("+terms.join(",")+ ")"};const formula=visit(root,1);if(formula.length>8192)
2806
+ return unsupported("RULE_FORMULA_LIMIT");return formula}
2807
+ const _exports=Object.freeze({canopyPredicate:canopyPredicate});_modules.set("237239bcf5fa7675f75c53d2f367d843e089051bfd9f586770330a2c504ce1f7",_exports);return _exports})();const _m98=_modules.get("13582dc7ba6ecf2a33722c6fee326b500408542ffdaa5cdac26ae72c310ea1ba")??(()=>{const{captureFields}=_m10;const{canopyPredicate}=_m99;const palette={info:{color:"4472C4",background:"DDEBF7",foreground:"1F4E78"},success:{color:"70AD47",background:"E2F0D9",foreground:"375623"},warning:{color:"FFC000",background:"FFF2CC",foreground:"9C6500"},danger:{color:"C00000",background:"FFC7CE",foreground:"9C0006"}};class UnsupportedRule extends Error{}
2808
+ const unsupported=(message)=>{throw new UnsupportedRule(message)};function canopyRules(request,format,grouped,tones,report,options={},cellTypes){if(request.formatRules===undefined||format==="csv")
2809
+ return[];if(!Array.isArray(request.formatRules)||request.formatRules.length>1000)
2810
+ throw new TypeError("Canopy formatRules must be a bounded array of at most 1,000 declarations.");const visuals=[],cells=[],rows=[],ids=new Set(),columns=request.columns;const inputs=request.formatRules;const declarations=inputs.map(input=>{if(!input||typeof input!=="object")
2811
+ throw new TypeError("Canopy rule declarations must be objects.");const rule=captureFields(input,["id","enabled","stopIfTrue","column","when","target","style"]);if(typeof rule.id!=="string"||!rule.id||ids.has(rule.id))
2812
+ throw new TypeError("Canopy rule IDs must be unique nonempty strings.");ids.add(rule.id);if(rule.enabled!==undefined&&typeof rule.enabled!=="boolean"||rule.stopIfTrue!==undefined&&typeof rule.stopIfTrue!=="boolean")
2813
+ throw new TypeError("Canopy rule flags must be boolean.");const style=rule.style&&typeof rule.style==="object"?captureFields(rule.style,["tone","bar","scale"]):rule.style;return{...rule,style}});if(format==="pdf"){for(const rule of declarations)
2814
+ if(rule.enabled!==false)
2815
+ report({code:"PDF_NATIVE_RULE_NOT_RENDERED:"+rule.id});return[]}
2816
+ const hasStops=declarations.some(rule=>rule.enabled!==false&&rule.stopIfTrue);if(hasStops&&declarations.some(rule=>rule.enabled!==false&&(rule.style?.bar!==undefined||rule.style?.scale!==undefined))){report({code:"UNSUPPORTED_GLOBAL_STOP_WITH_NATIVE_VISUALS"});return[]}
2817
+ const barColumns=new Set(declarations.filter(rule=>rule.enabled!==false&&rule.style?.bar!==undefined).map(rule=>rule.column));const barTone=declarations.find(rule=>rule.enabled!==false&&rule.target!=="row"&&rule.style?.tone!==undefined&&rule.column!==undefined&&barColumns.has(rule.column));if(barTone){report({code:"UNSUPPORTED_CELL_TONE_WITH_DATA_BAR",columnId:barTone.column});return[]}
2818
+ const priorStops=[];const priorRows=[],priorCells=new Map();const requiredCells=new Map();const column=(id)=>{const index=columns.findIndex(column=>column.id===id);if(index<0)
2819
+ return unsupported("RULE_COLUMN_NOT_EXPORTED:"+id);return index};const numeric=(id)=>{if(columns[column(id)].kind!=="number")
2820
+ unsupported("RULE_COLUMN_NOT_NUMERIC:"+id)};const color=(name)=>{const mapping=tones.get(name),value=mapping?.background??mapping?.color??palette[name]?.color;if(value===undefined)
2821
+ return unsupported("UNMAPPED_RULE_TONE:"+name);return value};const style=(name)=>{const defaults=palette[name];const mapping=tones.get(name)??(defaults?{background:defaults.background,color:defaults.foreground}:undefined);if(!mapping)
2822
+ return unsupported("UNMAPPED_RULE_TONE:"+name);if("alignment" in mapping||"wrapText" in mapping)
2823
+ return unsupported("UNSUPPORTED_RULE_TONE_STYLE:"+name);return{...("background" in mapping&&mapping.background!==undefined?{fill:{color:mapping.background}}:{}),font:{...(mapping.color===undefined?{}:{color:mapping.color}),...("bold" in mapping&&mapping.bold!==undefined?{bold:mapping.bold}:{}),...("italic" in mapping&&mapping.italic!==undefined?{italic:mapping.italic}:{})},...("numberFormat" in mapping&&mapping.numberFormat!==undefined?{numberFormat:mapping.numberFormat}:{})}};for(const rule of declarations){if(rule.enabled===false)
2824
+ continue;try{if(request.values!=="raw")
2825
+ unsupported("NATIVE_RULE_REQUIRES_RAW_VALUES");if(rule.target==="columns"||"columns" in rule&&rule.columns!==undefined)
2826
+ unsupported("UNSUPPORTED_RULE_COLUMNS_TARGET");if(!rule.style||typeof rule.style!=="object"||Array.isArray(rule.style))
2827
+ throw new TypeError("Canopy rule style must be an object.");const styleInput=captureFields(rule.style,["tone","bar","scale"]);if(Object.keys(styleInput).some(key=>!["tone","bar","scale"].includes(key)))
2828
+ unsupported("UNSUPPORTED_RULE_STYLE");const supplied=[styleInput.bar,styleInput.scale,styleInput.tone].filter(value=>value!==undefined);if(supplied.length!==1)
2829
+ unsupported("UNSUPPORTED_RULE_STYLE_COMBINATION");if(styleInput.bar!==undefined){if(rule.column===undefined||rule.when!==undefined||rule.target==="row")
2830
+ unsupported("UNSUPPORTED_BAR_TARGET");numeric(rule.column);if(rule.stopIfTrue)
2831
+ unsupported("UNSUPPORTED_BAR_STOP");const{minimum,maximum,tone="info",showValue}=captureFields(styleInput.bar,["minimum","maximum","tone","showValue"]);if(minimum===undefined||maximum===undefined)
2832
+ return unsupported("UNBOUNDED_CANOPY_BAR");if(!Number.isFinite(minimum)||!Number.isFinite(maximum)||maximum<=minimum)
2833
+ throw new TypeError("Canopy bar bounds must be finite and increasing.");visuals.push({type:"dataBar",range:{column:rule.column},color:color(tone),minimum:{type:"number",value:minimum},maximum:{type:"number",value:maximum},...(showValue===undefined?{}:{showValue})});requiredCells.set(column(rule.column),"number")}
2834
+ else if(styleInput.scale!==undefined){if(rule.stopIfTrue)
2835
+ unsupported("UNSUPPORTED_SCALE_STOP");if(rule.column===undefined||rule.when!==undefined||rule.target==="row")
2836
+ unsupported("UNSUPPORTED_SCALE_TARGET");numeric(rule.column);const{stops}=captureFields(styleInput.scale,["stops"]);if(!Array.isArray(stops)||stops.length<2||stops.length>3)
2837
+ unsupported("UNSUPPORTED_SCALE_STOPS");const mapped=stops.map((input)=>{const stop=captureFields(input,["type","value","tone"]);if(!["min","max","number","percent","percentile"].includes(stop.type))
2838
+ unsupported("UNSUPPORTED_SCALE_THRESHOLD:"+stop.type);const threshold=stop.type==="min"||stop.type==="max"?{type:stop.type}
2839
+ :{type:stop.type,value:stop.value};return{threshold,color:color(stop.tone)}});visuals.push({type:"colorScale",range:{column:rule.column},stops:mapped});requiredCells.set(column(rule.column),"number")}
2840
+ else{if(rule.when===undefined||styleInput.tone===undefined||rule.target!=="row"&&rule.column===undefined)
2841
+ unsupported("UNSUPPORTED_HIGHLIGHT_TARGET");if(rule.target!==undefined&&rule.target!=="row"&&rule.target!=="cell")
2842
+ unsupported("UNSUPPORTED_RULE_TARGET");const range=rule.target==="row"?{column:columns[0].id,through:columns.at(-1).id}:{column:rule.column};if(rule.column!==undefined)
2843
+ column(rule.column);const ruleCells=new Map();const ownPredicate=canopyPredicate(request,grouped,options,rule.when,unsupported,ruleCells);const reachable=priorStops.length?"AND("+ownPredicate+",NOT(OR("+priorStops.join(",")+ ")))":ownPredicate;const previous=rule.target==="row"?priorRows:priorCells.get(rule.column)??[];const formula=previous.length?"AND("+reachable+",NOT(OR("+previous.join(",")+ ")))":reachable;if(formula.length>8192)
2844
+ unsupported("RULE_FORMULA_LIMIT");(rule.target==="row"?rows:cells).push({type:"expression",range,formula,style:style(styleInput.tone)});previous.push(ownPredicate);if(rule.target!=="row")
2845
+ priorCells.set(rule.column,previous);for(const[column,type]of ruleCells)
2846
+ requiredCells.set(column,type);if(rule.stopIfTrue)
2847
+ priorStops.push(ownPredicate)}}
2848
+ catch(error){if(!(error instanceof UnsupportedRule))
2849
+ throw error;report({code:error.message+":"+rule.id,...(rule.column===undefined?{}:{columnId:rule.column})});if(hasStops)
2850
+ return[];// A partial sequence cannot claim to preserve its row-global stopping behavior.
2851
+ }}
2852
+ for(const[column,type]of requiredCells)
2853
+ cellTypes?.set(column,type);return Object.freeze([...visuals,...cells,...rows])}
2854
+ const _exports=Object.freeze({canopyRules:canopyRules});_modules.set("13582dc7ba6ecf2a33722c6fee326b500408542ffdaa5cdac26ae72c310ea1ba",_exports);return _exports})();const _m100=_modules.get("0f2b50bd606bf0a3273e7a3bec7ed6255f23cfee522a7cfeb2cb676c062ad40e")??(()=>{const{createGroupedReport}=_m8;const{ExportCell}=_m5;const{checkAbort}=_m4;const{createTotals}=_m12;const{captureFields}=_m10;const{datetime}=_m95;const identity=(value)=>value instanceof Date?"date:"+value.getTime():typeof value+":"+String(value);const scalar=(value)=>value instanceof ExportCell?value.value:value;function canopyGrouped(source,request,options,limits,report,format){const input=request.grouping;if(input===undefined)
2855
+ return undefined;// query.groupBy never manufactures a group snapshot.
2856
+ if(request.values!=="raw"){report({code:"GROUPING_REQUIRES_RAW_VALUES"});return undefined}
2857
+ if(source.rowCount===null)
2858
+ throw new TypeError("Captured grouping requires its exact scope recordCount.");const grouping=captureFields(input,["levels","aggregates","totals","groups"]);if(!Array.isArray(grouping.levels)||grouping.levels.length<1||grouping.levels.length>4||!Array.isArray(grouping.aggregates)||!Array.isArray(grouping.groups))
2859
+ throw new TypeError("Canopy grouping needs one through four levels, aggregates and ordered groups.");const levels=grouping.levels.map(level=>Object.freeze(captureFields(level,["column","direction","title"])));if(levels.some(level=>typeof level.column!=="string"||!level.column||level.direction!=="asc"&&level.direction!=="desc")||
2860
+ new Set(levels.map(level=>level.column)).size!==levels.length)
2861
+ throw new TypeError("Canopy grouping levels need unique stable columns and directions.");const declarations=grouping.aggregates.map(aggregate=>Object.freeze(captureFields(aggregate,["id","column","operation","label"])));const ids=new Set(),totals=Object.create(null);const operations={sum:"sum",count:"count",average:"average",minimum:"min",maximum:"max"};for(const aggregate of declarations){if(typeof aggregate.id!=="string"||!aggregate.id||ids.has(aggregate.id))
2862
+ throw new TypeError("Canopy aggregate IDs must be unique nonempty strings.");ids.add(aggregate.id);const column=source.columns.find(column=>column.key===aggregate.column);if(!column||column.type!=="number")
2863
+ throw new TypeError("Canopy aggregate declarations require an exported raw numeric column.");if(Object.hasOwn(totals,aggregate.column))
2864
+ throw new TypeError("The grouped report supports one aggregate operation per column.");const operation=operations[aggregate.operation];if(operation===undefined){report({code:"UNSUPPORTED_GROUP_AGGREGATE:"+aggregate.operation,columnId:aggregate.column});return undefined}
2865
+ totals[aggregate.column]=operation}
2866
+ createTotals(source.columns,totals);const expected=(input)=>{if(!input||typeof input!=="object"||Array.isArray(input))
2867
+ throw new TypeError("Canopy aggregate values must be an ID-keyed object.");const snapshot={...input};if(Object.keys(snapshot).some(key=>!ids.has(key))||declarations.some(aggregate=>!Object.hasOwn(snapshot,aggregate.id)))
2868
+ throw new TypeError("Canopy aggregate values must reference exactly the captured declarations.");for(const value of Object.values(snapshot))
2869
+ if(value!==null&&(typeof value!=="number"||!Number.isFinite(value)))
2870
+ throw new TypeError("Canopy aggregate values must be finite numbers or null.");return Object.freeze(snapshot)};const grandExpected=expected(grouping.totals),byDepth=levels.map(()=>[]),labels=levels.map(()=>new Map());let groups=0,characters=0;const ranges=(inputs,offset,end,depth)=>{if(!Array.isArray(inputs))
2871
+ throw new TypeError("Canopy groups must be ordered arrays.");let cursor=offset;const keys=new Set(),values=new Set();for(const input of inputs){const group=captureFields(input,["key","value","text","offset","count","aggregates","groups"]);if(!group||typeof group.key!=="string"||keys.has(group.key)||!Number.isSafeInteger(group.offset)||!Number.isSafeInteger(group.count)||
2872
+ group.count<=0||group.offset!==cursor||group.count>end-group.offset)
2873
+ throw new TypeError("Canopy group ranges must be nonempty contiguous half-open partitions within their parent.");if(group.value!==null&&!["string","number","boolean"].includes(typeof group.value)||
2874
+ typeof group.value==="number"&&!Number.isFinite(group.value))
2875
+ throw new TypeError("Canopy group values must be portable finite scalars.");const dateColumn=request.columns.find(column=>column.id===levels[depth].column)?.kind==="datetime";const value=format==="xlsx"&&dateColumn&&typeof group.value==="string"
2876
+ ?datetime(group.value,options.datetime??"preserve",options.xlsx?.dateMode??request.timeZone):group.value;const key=identity(value),text=group.text??String(group.value??"");if(typeof text!=="string"||values.has(key))
2877
+ throw new TypeError("A Canopy group key cannot recur within the same parent.");const previousLabel=labels[depth].get(key);if(previousLabel!==undefined&&previousLabel!==text)
2878
+ throw new TypeError("The same grouping value needs consistent captured text at one level.");labels[depth].set(key,text);keys.add(group.key);values.add(key);if(++groups>1000||(characters +=group.key.length+key.length+text.length)>1000000)
2879
+ throw new RangeError("Canopy group metadata exceeds the existing bounded report profile.");const next=group.offset+group.count;byDepth[depth].push(Object.freeze({offset:group.offset,end:next,value,text,expected:expected(group.aggregates)}));if(depth+1<levels.length)
2880
+ ranges(group.groups??[],group.offset,next,depth+1);else if(group.groups!==undefined&&group.groups.length)
2881
+ throw new TypeError("Canopy nested groups exceed their declared levels.");cursor=next}
2882
+ if(cursor!==end)
2883
+ throw new TypeError("Canopy grouping does not cover its complete exported detail range.")};ranges(grouping.groups,0,source.rowCount,0);const wireTotals=()=>{const ordinary=createTotals(source.columns,totals),sums=source.columns.map(()=>0),corrections=source.columns.map(()=>0),counts=source.columns.map(()=>0);return{accept(values){for(let index=0;index<values.length;index++){const value=scalar(values[index]),operation=totals[source.columns[index].key];if(operation!=="sum"&&operation!=="average"){ordinary[index].accept(value);continue}
2884
+ if(typeof value!=="number"||!Number.isFinite(value))
2885
+ continue;counts[index]=counts[index]+ 1;const next=value-corrections[index],total=sums[index]+ next;corrections[index]=total-sums[index]- next;sums[index]=total}},value(index){const operation=totals[source.columns[index].key];return operation==="sum"||operation==="average"?!counts[index]?null
2886
+ :operation==="sum"?sums[index]:sums[index]/ counts[index] : ordinary[index].value();
2887
+ }}};const indexes=levels.map(()=>0),active=levels.map(()=>undefined);const at=(depth,row)=>{const list=byDepth[depth];while(list[indexes[depth]]&&list[indexes[depth]].end<=row)
2888
+ indexes[depth]=indexes[depth]+ 1;const range=list[indexes[depth]];if(!range||row<range.offset||row>=range.end)
2889
+ throw new TypeError("A detail row is outside its captured Canopy grouping.");return range};const verify=(actual,expected)=>{for(const declaration of declarations){const position=source.columns.findIndex(column=>column.key===declaration.column),observed=actual.value(position),declared=expected[declaration.id];if(observed!==declared)
2890
+ throw new TypeError("Canopy captured aggregate differs from its consumed rows: "+declaration.id+".")}};const same=(actual,expected)=>actual instanceof Date&&expected instanceof Date
2891
+ ?actual.getTime()===expected.getTime():actual===expected;async function*rows(){let index=0;const grand=wireTotals();for await(const values of source.rows()){checkAbort(options.signal);for(let depth=0;depth<levels.length;depth++){const range=at(depth,index),column=source.columns.findIndex(column=>column.key===levels[depth].column);if(column>=0&&!same(scalar(values[column]),range.value))
2892
+ throw new TypeError("Canopy detail value disagrees with its captured group range.");if(range.offset===index)
2893
+ active[depth]={range,aggregates:wireTotals()}}
2894
+ grand.accept(values);for(const group of active)
2895
+ group.aggregates.accept(values);yield values;index++;for(let depth=levels.length-1;depth>=0;depth--){const group=active[depth];if(group.range.end===index){verify(group.aggregates,group.range.expected);active[depth]=undefined}}}
2896
+ verify(grand,grandExpected)}
2897
+ const groupBy=levels.map((level,depth)=>{const visible=source.columns.some(column=>column.key===level.column);return{key:level.column,...(visible?{}:{value:(_row,context)=>at(depth,context.rowIndex).value}),label:(value)=>labels[depth].get(identity(value))??String(value??"")}});const sourceLimits=limits===undefined?undefined:{...(limits.maxRows===undefined?{}:{maxRows:limits.maxRows}),...(limits.maxCells===undefined?{}:{maxCells:limits.maxCells}),...(limits.maxTextCharacters===undefined?{}:{maxTextCharacters:limits.maxTextCharacters})};return createGroupedReport(rows(),{columns:source.columns,groupBy,totals,...(options.signal===undefined?{}:{signal:options.signal}),...(sourceLimits===undefined?{}:{limits:sourceLimits})})}
2898
+ const _exports=Object.freeze({canopyGrouped:canopyGrouped});_modules.set("0f2b50bd606bf0a3273e7a3bec7ed6255f23cfee522a7cfeb2cb676c062ad40e",_exports);return _exports})();const _m101=_modules.get("c3e14cc7c7a8367d216ab1ca0b2a41751cc8775866d730cb941d062509dd4886")??(()=>{const{cellText}=_m35;const{cleanXml}=_m28;function canopyAbout(request,options){const result=[["revision",request.revision],["recordCount",request.recordCount===null?"unknown":request.recordCount]];if(request.scope!==undefined){if(!["filtered","selected","all"].includes(request.scope))
2899
+ throw new TypeError("Invalid Canopy export scope.");result.push(["scope",request.scope])}
2900
+ for(const key of["total","matched"])
2901
+ if(request[key]!==undefined){const value=request[key];if(value===null){result.push([key,"unknown"]);continue}
2902
+ if(!Number.isSafeInteger(value)||value<0)
2903
+ throw new TypeError("Canopy metadata counts must be nonnegative safe integers.");result.push([key,value])}
2904
+ if(request.generatedAt!==undefined){if(typeof request.generatedAt!=="string"||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z$/.test(request.generatedAt) || !Number.isFinite(new Date(request.generatedAt).getTime()))
2905
+ throw new TypeError("Canopy generatedAt must be a captured UTC ISO instant.");result.push(["generatedAt",request.generatedAt])}
2906
+ if(request.selection!==undefined){if(!Array.isArray(request.selection)||request.selection.some(id=>typeof id!=="string"))
2907
+ throw new TypeError("Canopy selection metadata must contain stable string IDs.");result.push(["selection",JSON.stringify(request.selection)])}
2908
+ if(request.query!==undefined){if(!request.query||typeof request.query!=="object"||Array.isArray(request.query))
2909
+ throw new TypeError("Canopy accepted query must be a captured object.");const query=JSON.stringify(request.query);if(typeof query!=="string")
2910
+ throw new TypeError("Canopy accepted query must serialize as JSON metadata.");result.push(["query",query])}
2911
+ if(result.reduce((sum,row)=>sum+row[0].length+String(row[1]).length,0)>65536)
2912
+ throw new RangeError("Canopy About metadata exceeds 65,536 captured characters.");for(const[field,value]of result){cellText(field,options.invalidCharacterPolicy);if(options.oversizedText==="preserve")
2913
+ cleanXml(value,options.invalidCharacterPolicy);else
2914
+ cellText(value,options.invalidCharacterPolicy)}
2915
+ return Object.freeze(result.map(row=>Object.freeze(row)))}
2916
+ const _exports=Object.freeze({canopyAbout:canopyAbout});_modules.set("c3e14cc7c7a8367d216ab1ca0b2a41751cc8775866d730cb941d062509dd4886",_exports);return _exports})();const _m102=_modules.get("e9bef8c7399cd0b119a8802014687efc2004572db8fa3045f2dbfe3c37ab6fb9")??(()=>{const{Workbook,addGroupedXlsx}=_m23;const{portableWorkbook}=_m52;const{withDestination}=_m3;async function writeCanopyWorkbook(source,grouped,destination,options,labels,about){const{sheet:sheetSettings={},columns:_columns,...settings}=options;const{name="Data",...sheet}=sheetSettings;if(about&&name.toLowerCase()==="about")
2917
+ throw new TypeError("The optional About worksheet needs a distinct data-sheet name.");if(grouped&&settings.cellValueWriters!==undefined)
2918
+ throw new TypeError("Grouped Canopy exports use resolved source values rather than custom cellValueWriters.");return withDestination(destination,async(sink)=>{const workbookOptions={...portableWorkbook(settings),sink};const book=grouped?new Workbook(workbookOptions):Workbook.forTable(workbookOptions);try{let rows,columns;if(grouped){const{conditionalFormats,...groupedSheet}=sheet;const written=await addGroupedXlsx(book,grouped,{labelColumn:{header:labels?.labelColumn?.header??"Group",width:18},subtotalLabel:labels?.subtotalLabel??(group=>group.label+" total"),grandTotalLabel:labels?.grandTotalLabel??(()=>"Grand total"),...(labels?.includeGrandTotal===undefined?{}:{includeGrandTotal:labels.includeGrandTotal}),sheet:{...groupedSheet,name},...(conditionalFormats===undefined?{}:{conditionalFormats})});rows=written.rows;columns=written.columns}
2919
+ else{const data=book.addWorksheet(name,{boldHeader:true,autoFilter:sheet.includeHeader!==false,autoSize:{minWidth:6,maxWidth:54},...sheet,columns:source.columns});await data.addRows(source.rows());await data.close();rows=data.rowCount;columns=source.columns.length}
2920
+ if(about){const metadata=book.addWorksheet("About",{columns:[{header:"Field",width:18},{header:"Value",width:72,wrapText:true}],boldHeader:true,freezeHeader:true});await metadata.addRows(about);await metadata.close()}
2921
+ const result=await book.finish();return{rows,columns,bytes:result.bytes}}
2922
+ catch(error){await book.discard(error);throw error}})}
2923
+ const _exports=Object.freeze({writeCanopyWorkbook:writeCanopyWorkbook});_modules.set("e9bef8c7399cd0b119a8802014687efc2004572db8fa3045f2dbfe3c37ab6fb9",_exports);return _exports})();const _m0=_modules.get("06222f91ea59fdd2aff673ab351a19c8b3372e05c612adf6136ffa05ee8bf037")??(()=>{const{BlobByteSink,ExportCell}=_m1;const{notifyProgress}=_m14;const{captureFields}=_m10;const{captureCommonLimits,captureXlsxOptions,captureCsvOptions,capturePdfOptions,mergeAdapterLimits}=_m15;const{writeXlsxTo}=_m23;const{writeCsvTo}=_m55;const{writePdfTo,writeGroupedPdfTo}=_m57;const{prepareCanopyExport}=_m94;const{canopyPins}=_m97;const{canopyRules}=_m98;const{canopyGrouped}=_m100;const{canopyAbout}=_m101;const{writeCanopyWorkbook}=_m102;async function writeCanopyTo(capture,format,destination,options={}){const selected=captureFields(options,["tones","columnOptions","unsupportedPresentation","datetime","xlsx","csv","pdf","signal","onDiagnostic","limits","onProgress","grouped","about"]);const{signal,onProgress}=selected,limits=captureCommonLimits(selected.limits);const xlsx=captureXlsxOptions(format==="xlsx"?selected.xlsx:undefined);const csv=captureCsvOptions(format==="csv"?selected.csv:undefined);const pdf=capturePdfOptions(format==="pdf"?selected.pdf:undefined);const prepared=prepareCanopyExport(capture,format,{...selected,xlsx}),{request,report,tones}=prepared;if(selected.about!==undefined&&typeof selected.about!=="boolean")
2924
+ throw new TypeError("Canopy about must be boolean.");const labels=selected.grouped===undefined?undefined:captureFields(selected.grouped,["labelColumn","subtotalLabel","grandTotalLabel","includeGrandTotal","continuationLabel","groupHeadingLevel"]);const capturedLabels=labels&&{...labels,...(labels.labelColumn===undefined?{}:{labelColumn:Object.freeze({header:labels.labelColumn.header})})};const about=format==="xlsx"&&selected.about?canopyAbout(request,xlsx):undefined;const ruleCellTypes=new Map();let consumed=0;const source=Object.freeze({...prepared.source,async*rows(){for await(const row of prepared.source.rows()){for(const[column,type]of ruleCellTypes){const cell=row[column],raw=cell instanceof ExportCell?cell.value:cell;if(raw==null||type==="number"&&typeof raw==="number"&&Number.isFinite(raw)||type==="date"&&raw instanceof Date&&Number.isFinite(raw.getTime()))
2925
+ continue;const code="UNSUPPORTED_NATIVE_RULE_CELL_TYPE:"+type;report({code,columnId:source.columns[column].key});throw new TypeError("Unsupported Canopy presentation: "+code+" ("+source.columns[column].key+")")}
2926
+ consumed++;yield row}}});const progress=onProgress?{onProgress:(event)=>{notifyProgress(onProgress,{...event,rows:consumed,...(event.sheetRows===undefined?{}:{sheetRows:about!==undefined&&event.sheetName==="About"?0:consumed}),...(source.rowCount===null?{}:{totalRows:source.rowCount})})}}:{};const stream={...(signal?{signal}:{}),...progress};if(format==="xlsx"){const formatLimits=mergeAdapterLimits(xlsx.limits,limits),grouped=canopyGrouped(source,request,{...selected,xlsx},formatLimits,report,format);const pinned=canopyPins(request.columns,report),rules=canopyRules(request,format,grouped!==undefined,tones,report,{...selected,xlsx},ruleCellTypes);const sheet={...xlsx.sheet,freezeHeader:xlsx.sheet?.freezeHeader??(xlsx.sheet?.includeHeader!==false),freezeColumns:xlsx.sheet?.freezeColumns??(pinned?pinned +(grouped?1:0):0),conditionalFormats:[...rules,...(xlsx.sheet?.conditionalFormats??[])]};const settings={...xlsx,...stream,columns:source.columns,sheet,dateMode:xlsx.dateMode??request.timeZone,limits:formatLimits};if(grouped||about)
2927
+ return writeCanopyWorkbook(source,grouped,destination,settings,capturedLabels,about);return writeXlsxTo(source.rows(),destination,settings)}
2928
+ if(format==="pdf"){const formatLimits=mergeAdapterLimits(pdf.limits,limits),grouped=canopyGrouped(source,request,selected,formatLimits,report,format);canopyRules(request,format,grouped!==undefined,tones,report,selected);const fitted=request.columns.every(column=>column.width!==undefined)?request.columns.map(column=>column.width.preferred*72 / 96) : undefined;
2929
+ const widths=pdf.columnWidths??fitted;const settings={...(fitted===undefined?{}:{orientation:"landscape",wideTable:"fit"}),...pdf,...stream,limits:formatLimits};if(grouped){if(pdf.headerRows!==undefined||pdf.footer!==undefined)
2930
+ throw new TypeError("Grouped Canopy PDF owns heading and summary rows.");const{headerRows:_headers,footer:_footer,...groupedSettings}=settings;return writeGroupedPdfTo(grouped,destination,{...groupedSettings,...(widths===undefined?{}:{columnWidths:[72,...widths]}),labelColumn:{header:capturedLabels?.labelColumn?.header??"Group",width:12},subtotalLabel:capturedLabels?.subtotalLabel??(group=>group.label+" total"),grandTotalLabel:capturedLabels?.grandTotalLabel??(()=>"Grand total"),...(capturedLabels?.includeGrandTotal===undefined?{}:{includeGrandTotal:capturedLabels.includeGrandTotal}),...(capturedLabels?.continuationLabel===undefined?{}:{continuationLabel:capturedLabels.continuationLabel}),...(capturedLabels?.groupHeadingLevel===undefined?{}:{groupHeadingLevel:capturedLabels.groupHeadingLevel})})}
2931
+ return writePdfTo(source.rows(),destination,{...settings,columns:source.columns,...(widths===undefined?{}:{columnWidths:widths})})}
2932
+ return writeCsvTo(source.rows(),destination,{...csv,...stream,columns:source.columns,valueMode:request.values,limits:mergeAdapterLimits(csv.limits,limits)})}
2933
+ async function exportCanopy(capture,format,options={}){const sink=new BlobByteSink();try{await writeCanopyTo(capture,format,sink,options);return sink.toBlob(format==="xlsx"?"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":format==="pdf"?"application/pdf":"text/csv;charset=utf-8")}
2934
+ catch(error){sink.discard();throw error}}
2935
+ const _exports=Object.freeze({createCanopyExport:_m94.createCanopyExport,ExportCell:_m5.ExportCell,PdfFont:_m63.PdfFont,writeCanopyTo:writeCanopyTo,exportCanopy:exportCanopy});_modules.set("06222f91ea59fdd2aff673ab351a19c8b3372e05c612adf6136ffa05ee8bf037",_exports);return _exports})();Object.assign(officeimo,_m0)})(globalThis);const officeWrite=global.OfficeIMO.exportCanopy;EXPORT_IMPL.office=(capture,context)=>{return officeWrite(capture,context.format,{signal:context.signal,about:context.includeMetadata,onProgress:progress=>context.progress(progress.rows),...(context.format==="pdf"?{unsupportedPresentation:"text",columnOptions:Object.fromEntries(capture.request.columns.map(column=>[column.id,{wrapText:true}]))}:{}),onDiagnostic:value=>{if(context.format==="pdf"&&!value.code.startsWith("PDF_NATIVE_RULE_NOT_RENDERED:"))
2936
+ throw new Error("CanopyX: unsupported PDF presentation: "+value.code);context.diagnostic(value)}})};installed.add(context.EXPORT_IMPL)}};(global.CanopyXParts||=[]).push(["office-export",part])})(typeof window!=="undefined"?window:globalThis);