@agile-team/mach-report 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +21 -12
  2. package/dist/{ExcelBindingWizard-Bs43BGNp.cjs → ExcelBindingWizard-Bq6FYME6.cjs} +1 -1
  3. package/dist/{ExcelBindingWizard-BKH1nGNS.js → ExcelBindingWizard-Co1svTsw.js} +3 -3
  4. package/dist/{ParamEditor-Da4akw6V.cjs → ParamEditor-B5UZRgxv.cjs} +1 -1
  5. package/dist/{ParamEditor-DoAhzJsm.js → ParamEditor-DNNARyeB.js} +1 -1
  6. package/dist/{ReportBatchPanel-wP9m9Pj1.cjs → ReportBatchPanel-Ctvs2t_9.cjs} +1 -1
  7. package/dist/{ReportBatchPanel-BMf6boMA.js → ReportBatchPanel-uQh06usx.js} +3 -3
  8. package/dist/ReportPreview-BdQawRh0.js +4879 -0
  9. package/dist/ReportPreview-CJC_-j2I.cjs +6 -0
  10. package/dist/{ReportTemplateLibrary-Sxr3eD0J.cjs → ReportTemplateLibrary-CnP7_1pH.cjs} +1 -1
  11. package/dist/{ReportTemplateLibrary-C9wutIiT.js → ReportTemplateLibrary-TIL_Oj2l.js} +1 -1
  12. package/dist/RuleEditor-DkRjOLlr.js +2141 -0
  13. package/dist/RuleEditor-h5anGsDB.cjs +1 -0
  14. package/dist/{TemplateOutlinePanel-JTSR53vJ.cjs → TemplateOutlinePanel-BlLxRrfu.cjs} +1 -1
  15. package/dist/{TemplateOutlinePanel-D6Bkny59.js → TemplateOutlinePanel-BouxsuqQ.js} +1 -1
  16. package/dist/{TemplateReusePanel-rVuK1kTz.js → TemplateReusePanel-BEACLPaN.js} +2 -2
  17. package/dist/{TemplateReusePanel-Kx35S0Ql.cjs → TemplateReusePanel-yxsHSO40.cjs} +1 -1
  18. package/dist/{TemplateReviewPanel-B0ar9_zf.js → TemplateReviewPanel-B1OGRY2i.js} +1 -1
  19. package/dist/{TemplateReviewPanel-Dn6X9UmY.cjs → TemplateReviewPanel-D9Cx0m2N.cjs} +1 -1
  20. package/dist/analytics.cjs +1 -1
  21. package/dist/analytics.d.cts +65 -1
  22. package/dist/analytics.d.ts +65 -1
  23. package/dist/analytics.js +4 -4
  24. package/dist/artifact-integrity.json +105 -101
  25. package/dist/assets-BIMVwjQe.js +231 -0
  26. package/dist/assets-Dfs2ElxI.cjs +1 -0
  27. package/dist/auto-BIOmtVhk.js +240 -0
  28. package/dist/auto-DDHflI9v.cjs +1 -0
  29. package/dist/{batch-BfZHN1do.js → batch-WzDIXJAt.js} +1 -1
  30. package/dist/{batch-CLpELXBl.cjs → batch-z6Aw5GEY.cjs} +1 -1
  31. package/dist/codes.d.cts +2 -0
  32. package/dist/codes.d.ts +2 -0
  33. package/dist/component-tree-Ca6YYfHq.js +61 -0
  34. package/dist/component-tree-DkGLEfZC.cjs +1 -0
  35. package/dist/computed-BW5a8QFk.js +612 -0
  36. package/dist/computed-C2GD3XcE.cjs +1 -0
  37. package/dist/config-Dg_o8e7m.cjs +1 -0
  38. package/dist/{config-BVsJXSqS.js → config-XQ4qrQ7Q.js} +66 -64
  39. package/dist/dataset-DL83majE.js +161 -0
  40. package/dist/dataset-IrlXbUvh.cjs +1 -0
  41. package/dist/designer-D9XAxqSc.js +5178 -0
  42. package/dist/designer-uCDo5XSK.cjs +2 -0
  43. package/dist/designer.cjs +1 -1
  44. package/dist/designer.d.cts +178 -3
  45. package/dist/designer.d.ts +178 -3
  46. package/dist/designer.js +1 -1
  47. package/dist/drill-ByN8COs_.cjs +1 -0
  48. package/dist/{drill-ByJviLXS.js → drill-CKW3Xtfa.js} +5 -5
  49. package/dist/encoding-BFMFIc4r.cjs +1 -0
  50. package/dist/encoding-DP_Eaf0A.js +21 -0
  51. package/dist/{font-loader-B_UkxpzC.cjs → font-loader-7FWVlykp.cjs} +1 -1
  52. package/dist/{font-loader-Q3bQjmrI.js → font-loader-CQZowp0I.js} +1 -1
  53. package/dist/index.cjs +8 -9
  54. package/dist/index.d.cts +175 -1
  55. package/dist/index.d.ts +175 -1
  56. package/dist/index.js +1343 -915
  57. package/dist/json-snapshot-D7PE1NsU.cjs +2 -0
  58. package/dist/json-snapshot-DYmEe3sO.js +1779 -0
  59. package/dist/matrix-JLAXlux-.js +302 -0
  60. package/dist/matrix-gTHpDTGm.cjs +1 -0
  61. package/dist/{pdf-CvvrjPQg.cjs → pdf-B8JouyYv.cjs} +48 -50
  62. package/dist/{pdf-BwNyeGpt.js → pdf-l3ea86di.js} +2734 -2748
  63. package/dist/pdf.cjs +1 -1
  64. package/dist/pdf.d.cts +14 -0
  65. package/dist/pdf.d.ts +14 -0
  66. package/dist/pdf.js +2 -2
  67. package/dist/{plugin-Ca_XZG3l.js → plugin-BBp74CQZ.js} +1 -1
  68. package/dist/{plugin-DHO7X8z2.cjs → plugin-CtFX9PFG.cjs} +1 -1
  69. package/dist/prepared-CARicKYh.js +87 -0
  70. package/dist/prepared-Ch1x_Gog.cjs +1 -0
  71. package/dist/progress-BXzlVbIp.js +29 -0
  72. package/dist/progress-DJBd9Rb9.cjs +1 -0
  73. package/dist/{progress-D-OTpEav.js → progress-Hc2vxoCs.js} +2 -2
  74. package/dist/protocol-B5A2uom4.cjs +1 -0
  75. package/dist/protocol-BaiWjq5w.js +90 -0
  76. package/dist/record-bindings-B86Sur_y.cjs +1 -0
  77. package/dist/{record-bindings-Do_b3h4V.js → record-bindings-D4TuMzHs.js} +10 -11
  78. package/dist/{region-binding-workflow-BMhK_TjP.js → region-binding-workflow-BNasF5kz.js} +2 -2
  79. package/dist/{region-binding-workflow-DIYJdCUr.cjs → region-binding-workflow-O2Cni3mF.cjs} +1 -1
  80. package/dist/report-encoding-worker.cjs +1 -0
  81. package/dist/report-encoding-worker.d.ts +1 -0
  82. package/dist/report-encoding-worker.js +2 -0
  83. package/dist/rich-text-layout-ALlMoYOG.cjs +3 -0
  84. package/dist/rich-text-layout-Ct5WrY1g.js +102 -0
  85. package/dist/runtime-DakRXui3.js +170 -0
  86. package/dist/runtime-dL5ygIfa.cjs +1 -0
  87. package/dist/sbom.cdx.json +2 -2
  88. package/dist/server/node.d.cts +132 -1
  89. package/dist/server/node.d.ts +132 -1
  90. package/dist/server-node.cjs +5 -1
  91. package/dist/server-node.js +5177 -463
  92. package/dist/server.cjs +1 -1
  93. package/dist/server.d.cts +182 -2
  94. package/dist/server.d.ts +182 -2
  95. package/dist/server.js +918 -833
  96. package/dist/sha256-BshdOkCC.cjs +1 -0
  97. package/dist/sha256-DTG-Gq8i.js +157 -0
  98. package/dist/style-67OqfNed.js +73 -0
  99. package/dist/style-C22Pbv3T.cjs +1 -0
  100. package/dist/style.css +1 -1
  101. package/dist/template-catalog-Dua8h9ZA.cjs +1 -0
  102. package/dist/{template-catalog-j2B1MJlL.js → template-catalog-wT1fNeAP.js} +10 -10
  103. package/dist/{template-fragments-DcKeiylI.cjs → template-fragments-BajTajb4.cjs} +1 -1
  104. package/dist/{template-fragments-BGbQLGlV.js → template-fragments-DmX5XK4N.js} +2 -2
  105. package/dist/template-registry-CpysHAxy.cjs +1 -0
  106. package/dist/{template-registry-BtaKPELV.js → template-registry-u11fPd8D.js} +389 -321
  107. package/dist/{textwrap-DE1kgcJB.js → textwrap-BEIg2w8y.js} +1 -1
  108. package/dist/textwrap-BI-yJ6Wt.cjs +4 -0
  109. package/dist/{tree-BX380Rr7.cjs → tree-CLpxYbKa.cjs} +1 -1
  110. package/dist/{tree-CjVZLRw7.js → tree-DNJorJUf.js} +1 -1
  111. package/dist/vue/async.d.cts +174 -2
  112. package/dist/vue/async.d.ts +174 -2
  113. package/dist/vue/index.d.cts +218 -3
  114. package/dist/vue/index.d.ts +218 -3
  115. package/dist/vue-async.cjs +1 -1
  116. package/dist/vue-async.js +3 -3
  117. package/dist/vue.cjs +1 -1
  118. package/dist/vue.js +7 -7
  119. package/dist/{workbook-session-BvToI-Fd.js → workbook-session-B8pNW24X.js} +153 -140
  120. package/dist/{workbook-session-Bjv1YCRK.cjs → workbook-session-DN5LSA5C.cjs} +12 -12
  121. package/dist/worker.cjs +1 -1
  122. package/dist/worker.d.cts +84 -1
  123. package/dist/worker.d.ts +84 -1
  124. package/dist/worker.js +12 -157
  125. package/dist/xlsx-node.cjs +33 -33
  126. package/dist/xlsx-node.js +1282 -1289
  127. package/dist/xlsx.cjs +4 -3
  128. package/dist/xlsx.d.cts +90 -2
  129. package/dist/xlsx.d.ts +90 -2
  130. package/dist/xlsx.js +279 -259
  131. package/package.json +6 -3
  132. package/dist/ReportPreview-ChV19HBp.js +0 -4619
  133. package/dist/ReportPreview-DbLvvOUT.cjs +0 -6
  134. package/dist/RuleEditor-C_Clasvd.js +0 -2037
  135. package/dist/RuleEditor-XhGHK8DE.cjs +0 -1
  136. package/dist/assets-B9ImAi6_.cjs +0 -1
  137. package/dist/assets-DEaz4qsp.js +0 -124
  138. package/dist/batch-BaP6pWDE.cjs +0 -1
  139. package/dist/batch-CGyt-b2W.js +0 -273
  140. package/dist/capabilities-CAh2Nrue.cjs +0 -1
  141. package/dist/capabilities-DskCHs3V.js +0 -69
  142. package/dist/computed-C-4C2S5h.js +0 -521
  143. package/dist/computed-CGV2a809.cjs +0 -1
  144. package/dist/config-D10us76d.cjs +0 -1
  145. package/dist/data-explanation-B8MZRYVS.js +0 -16
  146. package/dist/data-explanation-DE55G30w.cjs +0 -1
  147. package/dist/dataset-BkRmwgeJ.cjs +0 -1
  148. package/dist/dataset-H5pFuQGU.js +0 -121
  149. package/dist/defaults-DXhiM1ZD.js +0 -10
  150. package/dist/defaults-xhmcLLrf.cjs +0 -1
  151. package/dist/designer-2bDlcNXQ.js +0 -5136
  152. package/dist/designer-BT7XCdbW.cjs +0 -2
  153. package/dist/drill-DYTxuL3A.cjs +0 -1
  154. package/dist/grid-strokes-Cr7DwUux.cjs +0 -1
  155. package/dist/grid-strokes-DyyG1q_o.js +0 -53
  156. package/dist/json-snapshot-DFb2eWkf.js +0 -1416
  157. package/dist/json-snapshot-WWSGlaHG.cjs +0 -2
  158. package/dist/matrix-CGRGkn5s.js +0 -112
  159. package/dist/matrix-gEO7ZM_u.cjs +0 -1
  160. package/dist/prepared-CFy9B75C.cjs +0 -1
  161. package/dist/prepared-ajM-H-9B.js +0 -69
  162. package/dist/record-bindings-By_UKZ2g.cjs +0 -1
  163. package/dist/render-plan-7xpGrCEl.cjs +0 -1
  164. package/dist/render-plan-Ck6koX9L.js +0 -13
  165. package/dist/sha256-ArEYjaTI.cjs +0 -1
  166. package/dist/sha256-DPEuJ3nh.js +0 -155
  167. package/dist/style-CQ1PK8ZB.js +0 -67
  168. package/dist/style-UgIJSA1F.cjs +0 -1
  169. package/dist/template-catalog-FJE_c9Qe.cjs +0 -1
  170. package/dist/template-registry-Co1zPq5e.cjs +0 -1
  171. package/dist/textwrap-CWHyzkBH.cjs +0 -4
@@ -1 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=require("node:worker_threads"),j=require("node:crypto"),h=require("node:fs"),v=require("node:path");function z(e,t,r){if(!r?.aborted)try{const o=e?.({...t});o&&typeof o.then=="function"&&Promise.resolve(o).catch(()=>{})}catch{}}function H(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e,r=o=>typeof o=="string"&&o.trim().length>0&&o.length<=256;return!r(t.datasetId)||!r(t.field)||t.tableId!==void 0&&!r(t.tableId)||t.reportScope!==void 0&&(typeof t.reportScope!="string"||!t.reportScope.trim()||t.reportScope.length>4096)?!1:t.rowKey===void 0?!0:typeof t.rowKey=="string"?t.rowKey.trim().length>0&&t.rowKey.length<=1024:typeof t.rowKey=="number"&&Number.isFinite(t.rowKey)}function Z(e){return e==="missing-source"||e==="not-applicable"||e==="not-calculable"}function Q(e){return e.target!==void 0&&!H(e.target)?!1:e.valueState===void 0||Z(e.valueState)&&e.target!==void 0}function V(e,t,r){e!==void 0&&(typeof e!="string"||!e.trim()||e.length>4096)&&r.push({path:t,message:"来源范围应为不超过 4096 字符的非空字符串"})}function G(e,t,r){e.editable!==void 0&&typeof e.editable!="boolean"&&r.push({path:`${t}.editable`,message:"编辑控制应为布尔值"}),e.valueType!==void 0&&!["text","number","boolean"].includes(e.valueType)&&r.push({path:`${t}.valueType`,message:"编辑类型应为 text、number 或 boolean"})}function X(e,t,r){G(e,t,r),e.indentMm!==void 0&&(typeof e.indentMm!="number"||!Number.isFinite(e.indentMm)||e.indentMm<0)&&r.push({path:`${t}.indentMm`,message:"单元格缩进应为有限非负数"}),e.derived!==void 0&&typeof e.derived!="boolean"&&r.push({path:`${t}.derived`,message:"派生结果标记应为布尔值"}),F(e.source,`${t}.source`,r,!0),e.formula!==void 0&&typeof e.formula!="string"&&r.push({path:`${t}.formula`,message:"单元格公式应为字符串"})}function F(e,t,r,o=!1){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e)){r.push({path:t,message:"业务来源应为对象"});return}const n=e;V(n.sourceScope,`${t}.sourceScope`,r);for(const s of["datasetId",...o?["field"]:[]])(typeof n[s]!="string"||!n[s].trim())&&r.push({path:`${t}.${s}`,message:"业务标识应为非空字符串"});for(const s of["rowKey","revision"]){const i=n[s];i===void 0&&!(o&&s==="rowKey")||typeof i!="string"&&!(typeof i=="number"&&Number.isFinite(i))&&r.push({path:`${t}.${s}`,message:"业务键及修订号应为字符串或有限数字"})}n.sourceToken!==void 0&&typeof n.sourceToken!="string"&&r.push({path:`${t}.sourceToken`,message:"来源令牌应为字符串"})}function Y(e){const t=[];return e.value!==void 0&&typeof e.value!="string"&&t.push({path:"value",message:"Symbol value must be a string."}),e.symbology!==void 0&&!["code128","code39","ean13","ean8"].includes(e.symbology)&&t.push({path:"symbology",message:"Unsupported barcode symbology."}),e.errorCorrection!==void 0&&!["L","M","Q","H"].includes(e.errorCorrection)&&t.push({path:"errorCorrection",message:"Unsupported QR error correction."}),e.showText!==void 0&&typeof e.showText!="boolean"&&t.push({path:"showText",message:"showText must be a boolean."}),t}function ee(e,t){const r=[];return t!=="barcode"&&t!=="qrcode"&&r.push({path:"",message:"code is only supported by barcode and qrcode components."}),t==="qrcode"&&e.symbology!==void 0&&r.push({path:"symbology",message:"QR components do not use a linear symbology."}),t==="qrcode"&&e.showText===!0&&r.push({path:"showText",message:"Use a separate text component below a QR code."}),t==="barcode"&&e.errorCorrection!==void 0&&r.push({path:"errorCorrection",message:"Linear barcodes do not use QR error correction."}),r}function te(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return[{path:"",message:"code must be an object."}];const r=e,o=[...Y(r),...ee(r,t)];for(const i of Object.keys(r))["value","symbology","errorCorrection","quietZoneModules","showText"].includes(i)||o.push({path:i,message:"Unknown symbol option."});const n=r.symbology==="ean13"||r.symbology==="ean8",s=t==="qrcode"?4:n?11:10;return r.quietZoneModules!==void 0&&(!Number.isSafeInteger(r.quietZoneModules)||Number(r.quietZoneModules)<s||Number(r.quietZoneModules)>64)&&o.push({path:"quietZoneModules",message:`Quiet zone must contain ${s}–64 whole modules.`}),o}const re=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function A(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ne(e,t,r,o){const n=e[t];(typeof n!="number"||!Number.isFinite(n))&&o.push({path:`${r}.${t}`,message:`应为有限数字,实际 ${JSON.stringify(n)}`})}function oe(e,t,r){if(e!==void 0){const o=`${t}.table`;if(!A(e))r.push({path:o,message:"逻辑表来源应为对象"});else{F(e.source,`${o}.source`,r),(typeof e.id!="string"||!e.id.trim())&&r.push({path:`${o}.id`,message:"逻辑表 ID 应为非空字符串"});const n=e.role;["header","body","group-header","subtotal","grand-total"].includes(n)||r.push({path:`${o}.role`,message:"未知逻辑表行角色"});const s=e.rowIndex;(typeof s!="number"||!Number.isInteger(s)||(n==="header"?s!==-1:s<0))&&r.push({path:`${o}.rowIndex`,message:"表头索引应为 -1,内容行索引应为非负整数"}),(!Array.isArray(e.columnKeys)||e.columnKeys.some(i=>typeof i!="string"))&&r.push({path:`${o}.columnKeys`,message:"逻辑列字段应为字符串数组"}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${o}.layout`,message:"布局应为 page 或 wide"}),e.title!==void 0&&typeof e.title!="string"&&r.push({path:`${o}.title`,message:"逻辑表名称应为字符串"})}}}function se(e,t,r,o){if(e!==void 0)if(!A(e)||!Array.isArray(e.cells))r.push({path:`${t}.grid.cells`,message:"grid.cells 应为二维数组"});else{const n=e.paddingMm;n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<0)&&r.push({path:`${t}.grid.paddingMm`,message:"单元格内距应为有限非负数"}),e.cells.forEach((s,i)=>{if(!Array.isArray(s)){r.push({path:`${t}.grid.cells.${i}`,message:"行应为数组"});return}s.forEach((d,y)=>{if(d==null)return;const u=`${t}.grid.cells.${i}.${y}`;if(!A(d)){r.push({path:u,message:"网格单元格应为对象或 null"});return}X(d,u,r),Array.isArray(d.children)&&d.children.forEach((b,$)=>{U(b,`${t}.grid.cells.${i}.${y}.children.${$}`,r,o)})})})}}function ie(e,t,r){e!==void 0&&(Array.isArray(e)?e.forEach((o,n)=>{(!A(o)||!Array.isArray(o.segments))&&r.push({path:`${t}.richParagraphs.${n}`,message:"段落缺少 segments 数组"})}):r.push({path:`${t}.richParagraphs`,message:"richParagraphs 应为数组"}))}function U(e,t,r,o=[]){if(!A(e)){r.push({path:t,message:"组件应为对象"});return}const n=e.kind;typeof n!="string"?r.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):re.has(n)||o.push({path:`${t}.kind`,message:`未知组件类型 ${JSON.stringify(n)},将以兜底方式渲染`});for(const s of["leftMm","topMm","widthMm","heightMm"])ne(e,s,t,r);typeof e.leftMm=="number"&&e.leftMm<-100&&r.push({path:`${t}.leftMm`,message:"几何数值异常(leftMm<-100)"});for(const s of["widthMm","heightMm"])typeof e[s]=="number"&&e[s]<0&&r.push({path:`${t}.${s}`,message:"组件尺寸不能为负数"});oe(e.table,t,r),ae(e.code,n,t,r),e.pageAnchor!==void 0&&!["header","footer"].includes(e.pageAnchor)&&r.push({path:`${t}.pageAnchor`,message:"页面锚点应为 header 或 footer"}),e.lineDirection!==void 0&&!["down","up"].includes(e.lineDirection)&&r.push({path:`${t}.lineDirection`,message:"线段方向应为 down 或 up"}),se(e.grid,t,r,o),ie(e.richParagraphs,t,r)}function ae(e,t,r,o){if(e!==void 0)for(const n of te(e,t))o.push({path:`${r}.code${n.path?`.${n.path}`:""}`,message:n.message})}function D(e,t,r){if(!A(e))return;e.binding!==void 0&&r.push({path:`${t}.binding`,message:"渲染计划不允许未解析字段绑定"});const o=e.grid;!A(o)||!Array.isArray(o.cells)||o.cells.forEach((n,s)=>{Array.isArray(n)&&n.forEach((i,d)=>{!A(i)||!Array.isArray(i.children)||i.children.forEach((y,u)=>D(y,`${t}.grid.cells.${s}.${d}.children.${u}`,r))})})}function ce(e,t,r,o=[]){if(!A(e)){r.push({path:t,message:"页应为对象"});return}const n=e.pageWidthMm,s=e.pageHeightMm;(typeof n!="number"||!Number.isFinite(n)||n<=0)&&r.push({path:`${t}.pageWidthMm`,message:`页宽非法: ${JSON.stringify(n)}`}),(typeof s!="number"||!(s>0&&s<5e3))&&r.push({path:`${t}.pageHeightMm`,message:`页高非法: ${JSON.stringify(s)}`}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${t}.layout`,message:"布局应为 page 或 wide"});const i=e.components;Array.isArray(i)?Array.isArray(i)&&i.forEach((d,y)=>{U(d,`${t}.components.${y}`,r,o),D(d,`${t}.components.${y}`,r)}):r.push({path:`${t}.components`,message:"components 应为数组"})}function fe(e){const t=[],r=[],o=A(e)?e.pages:void 0;if(A(e)&&e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean"&&t.push({path:"$.requiresRecalculation",message:"重算能力要求应为布尔值"}),!Array.isArray(o))t.push({path:"$.pages",message:e==null?"渲染计划为空":"渲染计划缺少 pages 数组"});else{o.forEach((s,i)=>ce(s,`$.pages.${i}`,t,r)),o.length>2e3&&r.push({path:"$.pages",message:`页数异常大(${o.length} 页),渲染与打印耗时可能显著增加`});const n=o.reduce((s,i)=>s+(A(i)&&Array.isArray(i.components)?i.components.length:0),0);n>5e4&&r.push({path:"$.pages",message:`组件总数异常大(${n} 个),可能触发浏览器性能限制`})}return{ok:t.length===0,errors:t,warnings:r}}const ue=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),S=(e,t)=>e>>>t|e<<32-t;function pe(e,t,r){const o=new DataView(e.buffer,e.byteOffset+t,64);for(let n=0;n<16;n++)r[n]=o.getUint32(n*4);for(let n=16;n<64;n++){const s=r[n-15],i=r[n-2],d=S(s,7)^S(s,18)^s>>>3,y=S(i,17)^S(i,19)^i>>>10;r[n]=r[n-16]+d+r[n-7]+y}}function de(e,t){let r=e[0],o=e[1],n=e[2],s=e[3],i=e[4],d=e[5],y=e[6],u=e[7];for(let b=0;b<64;b++){const $=S(i,6)^S(i,11)^S(i,25),p=i&d^~i&y,f=u+$+p+ue[b]+t[b]>>>0,c=S(r,2)^S(r,13)^S(r,22),m=r&o^r&n^o&n,g=c+m>>>0;u=y,y=d,d=i,i=s+f>>>0,s=n,n=o,o=r,r=f+g>>>0}e[0]=e[0]+r,e[1]=e[1]+o,e[2]=e[2]+n,e[3]=e[3]+s,e[4]=e[4]+i,e[5]=e[5]+d,e[6]=e[6]+y,e[7]=e[7]+u}function me(e){const t=new Uint8Array(Math.ceil((e.byteLength+9)/64)*64);t.set(e),t[e.byteLength]=128;const r=new DataView(t.buffer);return r.setUint32(t.length-8,Math.floor(e.byteLength/536870912)),r.setUint32(t.length-4,e.byteLength*8>>>0),t}const ye=()=>new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),le=e=>Array.from(e,t=>t.toString(16).padStart(8,"0")).join("");async function he(e){const t=me(e),r=ye(),o=new Uint32Array(64);for(let n=0;n<t.length;n+=64)n>0&&n%262144===0&&await new Promise(s=>setTimeout(s,0)),pe(t,n,o),de(r,o);return le(r)}function ge(e){if(e===void 0)return!0;if(!Array.isArray(e))return!1;const t=new Set;return e.every(r=>!r||typeof r!="object"||Array.isArray(r)||typeof r.reportId!="string"||!r.reportId.trim()||!Number.isSafeInteger(r.reportIndex)||r.reportIndex<0||t.has(r.reportIndex)||typeof r.reportScope!="string"||!r.reportScope.trim()||r.reportScope.length>4096||r.revision!==void 0&&typeof r.revision!="string"||r.sourceToken!==void 0&&typeof r.sourceToken!="string"?!1:(t.add(r.reportIndex),!0))}const I="mach-report-worker/1";class J extends Error{constructor(t){super(t.message),this.name=t.name,this.code=t.code,this.path=t.path,this.issues=t.issues,this.diagnostics=t.diagnostics}}function R(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function we(e){return R(e)?["rows","pages","cells"].every(t=>typeof e[t]=="number"&&Number.isSafeInteger(e[t])&&e[t]>=0)&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0:!1}function be(e){return Array.isArray(e)&&e.every(t=>R(t)&&typeof t.code=="string"&&typeof t.message=="string"&&["info","warning","error"].includes(t.severity)&&Q(t))}function Ae(e){return R(e)&&Object.values(e).every(t=>R(t)&&(t.revision===void 0||typeof t.revision=="string")&&(t.sourceToken===void 0||typeof t.sourceToken=="string"))}function xe(e){return e===void 0?!0:R(e)&&["heuristic","provided","font-bytes"].includes(e.textMetrics)&&(e.fontFingerprint===void 0||typeof e.fontFingerprint=="string"&&/^[a-f0-9]{64}$/.test(e.fontFingerprint))}function Se(e,t){if(!R(e)||!we(e.stats)||!be(e.diagnostics)||!Ae(e.revisions)||!xe(e.layout)||!ge(e.sources))return!1;if(t==="prepare")return fe(e.plan).ok;const r=e.format==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";return e.bytes instanceof Uint8Array&&(e.format==="pdf"||e.format==="xlsx")&&e.contentType===r}function C(e){if(!e||typeof e!="object")return{message:String(e)};const t={};for(const r of["code","path","field","message"]){const o=e[r];typeof o=="string"&&(t[r]=o)}return t}function $e(e){const t=C(e);if(!R(e))return t;for(const r of["format","severity","kind","nid"])typeof e[r]=="string"&&(t[r]=e[r]);for(const r of["pageIndex","componentIndex"])Number.isSafeInteger(e[r])&&e[r]>=0&&(t[r]=e[r]);return Array.isArray(e.componentPath)&&e.componentPath.every(r=>Number.isSafeInteger(r)&&r>=0)&&(t.componentPath=e.componentPath),t}function ke(e){if(!(e instanceof Error))return{name:"Error",message:String(e)};const t=e;return{name:e.name,message:e.message,...typeof t.code=="string"?{code:t.code}:{},...typeof t.path=="string"?{path:t.path}:{},...Array.isArray(t.issues)?{issues:t.issues.map(C)}:{},...Array.isArray(t.diagnostics)?{diagnostics:t.diagnostics.map($e)}:{}}}function Ne(e){if(!e||typeof e!="object")return!1;const t=e;return t.protocol===I&&typeof t.id=="string"&&(t.operation==="prepare"||t.operation==="export"||t.operation==="exportPrepared")&&!!t.input&&typeof t.input=="object"}async function ve(e,t,r){try{const o=t.operation==="prepare"?await e.prepare({...t.input,onEvent:r}):t.operation==="exportPrepared"?await e.exportPrepared({...t.input,onEvent:r}):await e.export({...t.input,onEvent:r});return{protocol:I,id:t.id,result:o}}catch(o){return{protocol:I,id:t.id,error:ke(o)}}}function Re(e){const t=e.result;return!t||!("bytes"in t)||!(t.bytes.buffer instanceof ArrayBuffer)?[]:[t.bytes.buffer]}function Ie(e,t){if(!R(e)||typeof e.taskId!="string"||!e.taskId||t.taskId!==void 0&&e.taskId!==t.taskId||e.correlationId!==t.correlationId||e.reportId!==void 0&&(typeof e.reportId!="string"||!("reportIds"in t&&t.reportIds.includes(e.reportId)))||!["query","validate","layout","assets","encode"].includes(e.stage)||!["started","completed","failed"].includes(e.status))return!1;for(const r of["completed","total"])if(e[r]!==void 0&&(typeof e[r]!="number"||!Number.isFinite(e[r])||e[r]<0))return!1;return e.completed===void 0||e.total===void 0||e.completed<=e.total}let Me=0;function B(e){const t=new Error("报表 Worker 任务已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e}),t}function Ee(e,t){if(!e||typeof e!="object")return;const r=e;return r.protocol===I&&r.id===t?r:void 0}function Oe(e,t={}){const r=t.timeoutMs??12e4;if(!Number.isFinite(r)||r<=0||r>2147483647)throw new RangeError("Worker timeoutMs 应为正有限数字,且不能超过 2147483647");const o=(n,s,i,d)=>i?.aborted?Promise.reject(B(i.reason)):new Promise((y,u)=>{let b;try{b=e()}catch(l){u(l);return}const $=`mach-report-${Date.now()}-${++Me}`;let p=!1,f=()=>{},c;const m=(l,w)=>{p||(p=!0,c&&clearTimeout(c),f(),i?.removeEventListener("abort",g),Promise.resolve().then(()=>b.terminate()).then(()=>l===void 0?y(w):u(l),k=>u(l??k)))},g=()=>m(B(i?.reason)),x=l=>{const w=Ee(l,$);if(!(!w||p)){if("type"in w&&w.type==="event"){const k="event"in w?w.event:void 0;Ie(k,s)?z(d,k,i):m(new Error("报表 Worker 返回无效阶段事件"));return}w.error&&typeof w.error.name=="string"&&typeof w.error.message=="string"?m(new J(w.error)):Se(w.result,n)&&(n==="prepare"||"format"in w.result&&"format"in s&&w.result.format===s.format)?m(void 0,w.result):m(new Error("报表 Worker 返回无效响应"))}};try{if(f=b.subscribe(x,l=>m(l??new Error("报表 Worker 执行失败"))),p){f();return}if(i?.addEventListener("abort",g,{once:!0}),c=setTimeout(()=>m(new J({name:"ReportRuntimeError",code:"timeout",message:`报表 Worker 执行超过 ${r}ms`})),r),i?.aborted)g();else{const{onEvent:l,signal:w,...k}=s;b.postMessage({protocol:I,id:$,operation:n,input:k})}}catch(l){m(l)}});return{exportPrepared:(n,s,i)=>o("exportPrepared",n,s,i),prepare:(n,s,i)=>o("prepare",n,s,i),export:(n,s,i)=>o("export",n,s,i)}}class a extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportJobError"}}function T(e,t){if(typeof e!="string"||!e.trim()||e.length>256||typeof t!="string"||t!==t.trim()||!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(t))throw new a("input","任务范围应非空,ID应为1–128位安全标识")}function Te(e){const t=Array.isArray(e),r=Object.getPrototypeOf(e),o=Object.keys(e);if(r!==(t?Array.prototype:Object.prototype)&&!(r===null&&!t))throw new a("input","任务对象应为普通 JSON 对象");if(Object.getOwnPropertySymbols(e).length)throw new a("input","任务不能包含Symbol");if(Object.getOwnPropertyNames(e).filter(s=>!(t&&s==="length")).length!==o.length)throw new a("input","任务不能包含不可枚举属性");if(t&&(o.length!==e.length||o.some(s=>s!==String(Number(s))||!Number.isSafeInteger(Number(s))||Number(s)<0||Number(s)>=e.length)))throw new a("input","任务数组不能稀疏或包含额外属性");return o.sort()}function je(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(["__proto__","prototype","constructor"].includes(t)||r.get||r.set)throw new a("input","任务不能包含危险键或访问器");return r.value}function N(e,t={}){const r=t.maxNodes??2e4,o=t.maxCharacters??1e6;if(!Number.isSafeInteger(r)||r<1||r>2e4||!Number.isSafeInteger(o)||o<1||o>1e6)throw new a("input","任务JSON预算无效");let n=0,s=0;const i=new Set;function d(u,b){if(++n>r||b>32)throw new a("input","任务数据超过节点或深度预算");if(typeof u=="string"){if(s+=u.length,s>o)throw new a("input","任务文本超过预算");return u}if(u===null||typeof u=="boolean"||typeof u=="number"&&Number.isFinite(u))return u;if(!u||typeof u!="object"||i.has(u))throw new a("input","任务只允许无循环的有限 JSON 值");const $=Array.isArray(u),p=Te(u);i.add(u);const f=Object.create(null);for(const c of p){if(s+=c.length,s>o)throw new a("input","任务文本超过预算");f[c]=d(je(u,c),b+1)}return i.delete(u),$?Array.from({length:u.length},(c,m)=>f[String(m)]):f}const y=JSON.stringify(d(e,0));if(y.length>o)throw new a("input","任务序列化数据超过字符预算");return y}function q(e){return JSON.parse(JSON.stringify(e))}function _(e,t,r,o){if(T(t,r),e.scope!==t||e.id!==r||e.revision!==(o??0)+1||!Number.isSafeInteger(e.revision))throw new a("input","任务身份或修订不匹配");if(![e.createdAt,e.updatedAt,e.attempt].every(n=>Number.isSafeInteger(n)&&n>=0)||!["queued","running","completed","failed","cancelled"].includes(e.status))throw new a("input","任务状态无效");if(e.lease&&(!e.lease.owner||!Number.isSafeInteger(e.lease.expiresAt)))throw new a("input","任务租约无效");if(!e.request||typeof e.request.kind!="string"||!e.request.kind.trim()||e.request.kind.length>128)throw new a("input","任务类型无效");N(e.request.payload,{maxNodes:19e3,maxCharacters:75e4}),N(e)}function qe(e,t){if(e&&(e.createdAt!==t.createdAt||N(e.request)!==N(t.request)))throw new a("input","任务创建时间与请求不可变更,请使用新任务ID")}function Je(e,t){return e.status==="queued"||e.status==="running"&&(e.lease?.expiresAt??0)<=t}function Pe(e={}){const t={maxRecords:e.maxRecords??1e4,maxBytes:e.maxBytes??67108864,maxResultBytes:e.maxResultBytes??262144,controlReserveBytes:e.controlReserveBytes??4096,maxTombstones:e.maxTombstones??1e4,maxTombstoneBytes:e.maxTombstoneBytes??16777216};if(!Object.values(t).every(r=>Number.isSafeInteger(r)&&r>0)||t.controlReserveBytes<4096)throw new a("input","任务容量应为正整数,控制状态预留至少4096字节");return t}function M(e){return new TextEncoder().encode(N(e)).byteLength}function K(e,t){const r={scope:e.scope,id:e.id,revision:1,request:e.request,status:"queued",createdAt:e.createdAt,updatedAt:e.createdAt,attempt:0},o={...e};delete o.result;const n=e.result===void 0?0:M(e.result);if(n>t.maxResultBytes)throw new a("capacity","任务结果超过独立预算,请保存文件引用");return Math.max(M(r)+t.controlReserveBytes,M(o))+n}function L(e){return e.status!=="queued"&&e.status!=="running"}function Be(e){const t={...e,tombstoneRetentionMs:e.tombstoneRetentionMs??6048e5,limit:e.limit??100};if(![t.now,t.terminalBefore].every(r=>Number.isSafeInteger(r)&&r>=0)||t.terminalBefore>t.now)throw new a("input","终态清理时间应为不超过当前时间的非负整数");if(![t.tombstoneRetentionMs,t.limit].every(r=>Number.isSafeInteger(r)&&r>0)||!Number.isSafeInteger(t.now+t.tombstoneRetentionMs))throw new a("input","幂等保留期与清理批量应为正整数");return t}async function We(e){const t=new TextEncoder().encode(N(e)),r=globalThis.crypto?.subtle;if(!r)return he(t);const o=await r.digest("SHA-256",t);return Array.from(new Uint8Array(o),n=>n.toString(16).padStart(2,"0")).join("")}async function Fe(e,t){if(!L(e))throw new a("input","只能归档终态任务");return{scope:e.scope,id:e.id,revision:e.revision,status:e.status,createdAt:e.createdAt,updatedAt:e.updatedAt,attempt:e.attempt,requestHash:await We(e.request),expiresAt:t}}function Ue(e){if(!e||!["completed","failed","cancelled"].includes(e.status)||!/^[a-f0-9]{64}$/.test(e.requestHash))throw new a("input","任务幂等摘要无效");if(![e.revision,e.createdAt,e.updatedAt,e.attempt,e.expiresAt].every(t=>Number.isSafeInteger(t)&&t>=0)||e.revision<1)throw new a("input","任务幂等摘要时间或修订无效")}function O(e){return e?.code}function E(e,t){return j.createHash("sha256").update(JSON.stringify([e,t])).digest("hex")+".json"}async function P(e){try{return await h.promises.readFile(e,"utf8")}catch(t){if(O(t)==="ENOENT")return;throw t}}async function De(e,t){const r=await P(e);if(r===void 0)return;let o;try{o=JSON.parse(r)}catch{throw new a("conflict","任务锁尚未完整写入或已损坏,拒绝自动移除")}if(!o||!Number.isSafeInteger(o.pid)||o.pid<1)throw new a("conflict","任务锁身份无效,拒绝自动移除");try{process.kill(o.pid,0)}catch(n){if(O(n)==="ESRCH"){await h.promises.unlink(e);return}throw n}throw new a("conflict","任务目录的写入进程仍在运行")}async function Ce(e,t){if(!t)throw new a("conflict","任务目录已有写入进程;多实例请使用数据库CAS适配器");const r=e+".recovery";let o;try{o=await h.promises.open(r,"wx",384)}catch(n){throw O(n)==="EEXIST"?new a("conflict","任务目录恢复正在进行,请稍后重试"):n}try{return await o.writeFile(JSON.stringify({pid:process.pid})),await De(e,!0),await h.promises.open(e,"wx",384)}finally{await o.close(),await h.promises.unlink(r)}}async function _e(e,t){const r=v.join(e,".writer-lock"),o=j.randomUUID();let n;try{n=await h.promises.open(r,"wx",384)}catch(s){if(O(s)!=="EEXIST")throw s;n=await Ce(r,t)}try{await n.writeFile(JSON.stringify({pid:process.pid,token:o})),await n.sync()}catch(s){throw await n.close(),await h.promises.unlink(r).catch(()=>{}),s}return{file:r,token:o,handle:n}}function Ke(e,t,r,o){if("tombstone"in r){const n=r.tombstone;if(Ue(n),T(n.scope,n.id),E(n.scope,n.id)!==t)throw new a("input","持久任务摘要身份不匹配");const s=M(n);e.tombstoneBytes+=s,e.tombstones.set(t,{value:n,bytes:s})}else{if(_(r,r.scope,r.id,r.revision-1),E(r.scope,r.id)!==t)throw new a("input","持久任务文件身份不匹配");const n=K(r,o);e.bytes+=n,e.records.set(t,{record:r,bytes:n})}if(e.bytes>o.maxBytes||e.records.size>o.maxRecords||e.tombstoneBytes>o.maxTombstoneBytes||e.tombstones.size>o.maxTombstones)throw new a("capacity","持久任务及控制状态预留超过目录预算")}async function Le(e,t){const r=await h.promises.readdir(e);for(const s of r.filter(i=>/^\.pending-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(i)))await h.promises.unlink(v.join(e,s));const o=r.filter(s=>/^[a-f0-9]{64}\.json$/.test(s));if(o.length>t.maxRecords+t.maxTombstones)throw new a("capacity","持久任务数量超过目录预算");const n={records:new Map,tombstones:new Map,bytes:0,tombstoneBytes:0};for(const s of o){const i=v.join(e,s);if((await h.promises.stat(i)).size>4e6)throw new a("capacity","持久任务文件超过单文件预算");Ke(n,s,JSON.parse(await h.promises.readFile(i,"utf8")),t)}return n}async function ze(e,t,r){const o=v.join(e,`.pending-${j.randomUUID()}`);try{const n=await h.promises.open(o,"wx",384);try{await n.writeFile(r),await n.sync()}finally{await n.close()}await h.promises.rename(o,v.join(e,t));const s=await h.promises.open(e,"r");try{await s.sync()}finally{await s.close()}}finally{await h.promises.unlink(o).catch(n=>{if(O(n)!=="ENOENT")throw n})}}async function He(e){const t=v.resolve(e.directory),r=Pe(e);await h.promises.mkdir(t,{recursive:!0,mode:448});const o=await _e(t,e.recoverDeadOwner??!1);let n;try{n=await Le(t,r)}catch(p){throw await o.handle.close(),await h.promises.unlink(o.file),p}let s=!1,i=Promise.resolve();const d=()=>{if(s)throw new a("closed","持久任务存储已关闭")},y=p=>{d();const f=i.then(async()=>{if(JSON.parse(await h.promises.readFile(o.file,"utf8")).token!==o.token)throw new a("closed","持久任务存储写入锁已失效");return p()});return i=f.then(()=>{},()=>{}),f},u=async(p,f,c)=>{try{await ze(t,p,f)}catch(m){throw await P(v.join(t,p))===f&&c(),m}c()};return{read:async(p,f)=>{d(),T(p,f),await i;const c=n.records.get(E(p,f));return c?q(c.record):void 0},readTombstone:async(p,f)=>{d(),T(p,f),await i;const c=n.tombstones.get(E(p,f));return c?q(c.value):void 0},candidates:async(p,f)=>(d(),await i,Array.from(n.records.values(),c=>c.record).filter(c=>Je(c,p)).sort((c,m)=>c.createdAt-m.createdAt).slice(0,f).map(q)),compareAndSwap:async(p,f,c,m)=>{const g=JSON.parse(N(m));return _(g,p,f,c),y(async()=>{const x=E(p,f),l=n.records.get(x);if((l?.record.revision??null)!==c||n.tombstones.has(x))return!1;qe(l?.record,g);const w=K(g,r),k=n.bytes-(l?.bytes??0)+w;if(k>r.maxBytes||!l&&n.records.size>=r.maxRecords)throw new a("capacity","持久任务容量已满,请清理终态任务或扩大显式预算");return await u(x,N(g),()=>{n.records.set(x,{record:g,bytes:w}),n.bytes=k}),!0})},prune:async p=>{const f=Be(p);return y(async()=>{const c={archived:0,expired:0};for(const[m,g]of n.tombstones)g.value.expiresAt>f.now||c.expired>=f.limit||(await h.promises.unlink(v.join(t,m)),n.tombstones.delete(m),n.tombstoneBytes-=g.bytes,c.expired++);for(const[m,g]of n.records){if(!L(g.record)||g.record.updatedAt>f.terminalBefore||c.archived+c.expired>=f.limit)continue;const x=await Fe(g.record,f.now+f.tombstoneRetentionMs),l=M(x);if(n.tombstones.size>=r.maxTombstones||n.tombstoneBytes+l>r.maxTombstoneBytes)break;await u(m,N({tombstone:x}),()=>{n.tombstones.set(m,{value:x,bytes:l}),n.tombstoneBytes+=l,n.records.delete(m),n.bytes-=g.bytes}),c.archived++}if(c.expired){const m=await h.promises.open(t,"r");try{await m.sync()}finally{await m.close()}}return c})},close:async()=>{if(s)return;s=!0,await i,await o.handle.close();const p=await P(o.file);p&&JSON.parse(p).token===o.token&&await h.promises.unlink(o.file)}}}function Ze(e){const t=e.filename??e.workerUrl;if(!t||e.filename&&e.workerUrl)throw new TypeError("请且仅请指定 filename 或 workerUrl");return Oe(()=>{const r=new W.Worker(t,e.workerOptions);return{postMessage:o=>r.postMessage(o),terminate:()=>r.terminate(),subscribe:(o,n)=>{const s=i=>n(new Error(`报表 Worker 在响应前退出(code ${i})`));return r.on("message",o),r.on("error",n),r.on("messageerror",n),r.on("exit",s),()=>{r.off("message",o),r.off("error",n),r.off("messageerror",n),r.off("exit",s)}}}},e)}function Qe(e){const t=W.parentPort;if(!t)throw new Error("serveNodeReportWorker 只能在 worker_threads 中调用");const r=o=>{Ne(o)&&ve(e,o,n=>t.postMessage({protocol:I,id:o.id,type:"event",event:n})).then(n=>t.postMessage(n,Re(n)))};return t.on("message",r),()=>t.off("message",r)}function Ve(e){return j.createHash("sha256").update(e).digest("hex")}exports.ReportWorkerError=J;exports.createNodeReportExecutor=Ze;exports.openFileReportJobStore=He;exports.reportArtifactSha256=Ve;exports.serveNodeReportWorker=Qe;
1
+ "use strict";var si=Object.create;var Or=Object.defineProperty;var ai=Object.getOwnPropertyDescriptor;var ci=Object.getOwnPropertyNames;var ui=Object.getPrototypeOf,fi=Object.prototype.hasOwnProperty;var li=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ci(t))!fi.call(e,o)&&o!==r&&Or(e,o,{get:()=>t[o],enumerable:!(n=ai(t,o))||n.enumerable});return e};var We=(e,t,r)=>(r=e!=null?si(ui(e)):{},li(t||!e||!e.__esModule?Or(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ce=require("./progress-DJBd9Rb9.cjs"),Se=require("node:worker_threads"),le=require("node:crypto"),A=require("node:fs"),j=require("node:path");var Ft=typeof document<"u"?document.currentScript:null;const mt=1.35,or=10.5,mn='"Microsoft YaHei", sans-serif',di="1.0.0-mach",ve=di,gn=/[\u3000-\u9fff\uff00-\uffef]/,me=new Uint8Array(128);{for(const e of"iljtf.,:;'`|!()[]")me[e.charCodeAt(0)]=1;for(const e of"mwMW@")me[e.charCodeAt(0)]=2;for(let e=48;e<=57;e++)me[e]=3;for(let e=65;e<=90;e++)me[e]=4;me[32]=5}const mi=[.54,.26,.95,.59,.67,.3];function gi(e){const t=e.charCodeAt(0);return t<128?mi[me[t]]:gn.test(e)?1:/[A-Z]/.test(e)?.67:.54}const ir={measureMm(e,t){const{fontSizePt:r,bold:n=!1,letterSpacingPt:o=0}=t,i=25.4/72;let s=0;for(const a of e)s+=gi(a);return n&&(s*=1.04),(s*r+o*Math.max(0,Array.from(e).length-1))*i}};function hi(e,t,r){const n=[];let o="";const i=()=>{o&&(n.push({text:o,widthMm:r.measureMm(o,t),cjk:!1}),o="")};for(const s of e){if(s===`
2
+ `){i(),n.push({text:`
3
+ `,widthMm:0,cjk:!1,br:!0});continue}if(s===" "){i(),n.push({text:s,widthMm:r.measureMm(s,t),cjk:!1,space:!0});continue}if(gn.test(s)){i(),n.push({text:s,widthMm:r.measureMm(s,t),cjk:!0});continue}o+=s}return i(),n}function De(e,t,r,n=ir){if(!e)return[""];e=e.replace(/\r\n?/g,`
4
+ `);const o=[];let i="",s=0;const a=(r.letterSpacingPt??0)*25.4/72,c=()=>{o.push(i),i="",s=0};for(const u of hi(e,r,n)){if(u.br){c();continue}const f=i.length>0?a:0;if(s+f+u.widthMm<=t){i+=u.text,s+=f+u.widthMm;continue}if(u.space){c();continue}if(u.cjk){i.length>0&&c(),i=u.text,s=u.widthMm;continue}if(i.length>0&&c(),u.widthMm<=t){i=u.text,s=u.widthMm;continue}for(const d of u.text)n.measureMm(i+d,r)>t&&i.length>0&&c(),i+=d,s=n.measureMm(i,r)}return c(),o}const pi=4096,Rr=128*1024;function yi(e){const t=new Map;let r=0;return{measureMm(n,o){const i=JSON.stringify([n,o.fontSizePt,o.fontFamily,o.bold,o.italic,o.letterSpacingPt]),s=t.get(i);if(s!==void 0)return t.delete(i),t.set(i,s),s;const a=e.measureMm(n,o);if(Number.isFinite(a)&&i.length<=Rr){for(;t.size>=pi||r+i.length>Rr;){const c=t.keys().next().value;r-=c.length,t.delete(c)}t.set(i,a),r+=i.length}return a}}}const Xe=1e3;function fe(e){if(!Number.isSafeInteger(e)||e<0||e>Xe*2)throw new Error("十进制精度超出预算");return 10n**BigInt(e)}function gt(e){if(e.coefficient.toString().length>Xe*2||e.scale>Xe*2)throw new Error("十进制结果超出精度预算");return e}function q(e){if(typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("十进制参数必须是有限数字或十进制文本");const t=String(e);if(t.length>Xe)throw new Error("十进制文本超出精度预算");const r=/^([+-]?)(\d+)(?:\.(\d*))?(?:[eE]([+-]?\d{1,4}))?$/.exec(t);if(!r)throw new Error("无效十进制文本");const n=r[3]??"",o=Number(r[4]??0),i=n.length-o,s=BigInt(`${r[1]==="-"?"-":""}${r[2]}${n}`);return gt(i<0?{coefficient:s*fe(-i),scale:0}:{coefficient:s,scale:i})}function hn(e,t){const r=Math.max(e.scale,t.scale);return[e.coefficient*fe(r-e.scale),t.coefficient*fe(r-t.scale),r]}function Ct(e,t){const[r,n]=hn(e,t);return r<n?-1:r>n?1:0}function Ze(e,t){const[r,n,o]=hn(e,t);return gt({coefficient:r+n,scale:o})}function sr(e,t){return gt({coefficient:e.coefficient*t.coefficient,scale:e.scale+t.scale})}function pn(e,t){const r=e/t,n=e%t,o=i=>i<0n?-i:i;return o(n)*2n<o(t)?r:r+(e<0n==t<0n?1n:-1n)}function ht(e){if(!Number.isInteger(e)||e<0||e>100)throw new Error("十进制小数位应为 0–100 的整数")}function Lt(e,t,r=20){if(ht(r),t.coefficient===0n)throw new Error("不能除以零");const n=t.scale-e.scale+r,o=e.coefficient*fe(Math.max(0,n)),i=t.coefficient*fe(Math.max(0,-n));return gt({coefficient:pn(o,i),scale:r})}function ar(e,t){let r=e.coefficient,n=e.scale;t!==void 0&&(ht(t),r=t>=n?r*fe(t-n):pn(r,fe(n-t)),n=t);const o=r<0n,i=(o?-r:r).toString().padStart(n+1,"0");let s=n?i.slice(-n):"";return t===void 0&&(s=s.replace(/0+$/,"")),`${o?"-":""}${n?i.slice(0,-n):i}${s?`.${s}`:""}`}function Tr(e,t,r=!1,n=!1){let o=q(e);n&&(o=sr(o,{coefficient:100n,scale:0}));const[i,s]=ar(o,t).split(".");return`${r?i.replace(/\B(?=(\d{3})+(?!\d))/g,","):i}${s===void 0?"":`.${s}`}${n?"%":""}`}function yn(e){if(!e||e.kind==="date")return;const t=e.digits;if(!(t!==void 0&&(!Number.isInteger(t)||t<0||t>100))){if(e.kind==="percent"){const r=t??2;return`0${r?`.${"0".repeat(r)}`:""}%`}return t===void 0?e.thousands?"#,##0.###############":void 0:`${e.thousands?"#,##0":"0"}${t?`.${"0".repeat(t)}`:""}`}}function wi(e){const t=/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/.exec(e.trim());if(t){const n=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(n.getTime())?null:n}const r=new Date(e);return Number.isNaN(r.getTime())?null:r}function Dt(e,t){return e.toLocaleString("en-US",{minimumFractionDigits:t,maximumFractionDigits:t})}function bi(e,t){const r=n=>String(n).padStart(2,"0");return t.replace(/YYYY/g,String(e.getFullYear())).replace(/MM/g,r(e.getMonth()+1)).replace(/DD/g,r(e.getDate())).replace(/hh/g,r(e.getHours())).replace(/mm/g,r(e.getMinutes())).replace(/ss/g,r(e.getSeconds()))}function xi(e,t,r){return r!=null?t?Dt(e,r):e.toFixed(r):t?Dt(e):String(e)}function jr(e){const t=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(t)?t:null}function cr(e,t){if(e==null||e===""||!t)return String(e??"");switch(t.kind){case"number":{if(typeof e=="string")try{return Tr(e,t.digits,t.thousands===!0)}catch{return e}const r=jr(e);return r==null?String(e):xi(r,t.thousands===!0,t.digits)}case"percent":{if(typeof e=="string")try{return Tr(e,t.digits??2,!0,!0)}catch{return e}const r=jr(e);return r==null?String(e):`${Dt(r*100,t.digits??2)}%`}case"date":{const r=t.pattern??"YYYY-MM-DD",n=e instanceof Date?e:wi(String(e));return n?bi(n,r):String(e)}default:return String(e)}}function Ae(e,t){const r=e[t.field];if(r==null||r==="")return!1;if(typeof t.value=="number"||t.numeric!==void 0){let i;try{i=Ct(q(r),q(t.value))}catch{return!1}if(!Number.isFinite(i))return!1;switch(t.op){case">":return i>0;case">=":return i>=0;case"<":return i<0;case"<=":return i<=0;case"==":return i===0;case"!=":return i!==0}}const n=String(r),o=String(t.value);switch(t.op){case"==":return n===o;case"!=":return n!==o;case">":return n>o;case">=":return n>=o;case"<":return n<o;case"<=":return n<=o}return!1}const $i=["sum","count","avg","min","max","weightedAvg"];function Cr(e){if(typeof e!="number"||!Number.isFinite(e))throw new Error("聚合度量必须是有限数字,不能隐式转换;小数文本请显式选择 decimal");return e}function Qe(e,t){return t&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function vi(e){let t=0,r=0,n=0,o=0,i=1/0,s=-1/0;const a=c=>{const u=c-n,f=r+u;n=f-r-u,r=f};return{add(c){const u=Qe(c,e.field);if(e.op==="count"){(!e.field||u!=null)&&t++;return}if(u==null)return;const f=Cr(u),d=e.op==="weightedAvg"?Qe(c,e.weightField):1;if(d==null)return;const l=Cr(d);if(e.op==="weightedAvg"&&l<0)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&a(f*l),o+=l,i=Math.min(i,f),s=Math.max(s,f),t++},value(){if(e.op==="count")return t;if(!t)return null;const c=e.op==="min"?i:e.op==="max"?s:e.op==="avg"?r/t:e.op==="weightedAvg"?o===0?null:r/o:r;if(c!==null&&!Number.isFinite(c))throw new Error("聚合计算溢出");return c}}}function Mi(e){let t=0,r=q("0"),n=q("0"),o,i;return{add(s){const a=Qe(s,e.field);if(e.op==="count"){(!e.field||a!=null)&&t++;return}if(a==null)return;const c=e.op==="weightedAvg"?Qe(s,e.weightField):"1";if(c==null)return;const u=q(a),f=q(c);if(e.op==="weightedAvg"&&f.coefficient<0n)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&(r=Ze(r,sr(u,f))),e.op==="weightedAvg"&&(n=Ze(n,f)),(!o||Ct(u,o)<0)&&(o=u),(!i||Ct(u,i)>0)&&(i=u),t++},value(){if(e.op==="count")return t;if(!t||e.op==="weightedAvg"&&n.coefficient===0n)return null;let s=e.op==="min"?o:e.op==="max"?i:r;return e.op==="avg"&&(s=Lt(r,q(t),e.digits)),e.op==="weightedAvg"&&(s=Lt(r,n,e.digits)),ar(s,e.digits)}}}function de(e){if(e.digits!==void 0&&ht(e.digits),e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal")throw new Error("未知聚合数值模式");if(!$i.includes(e.op))throw new Error("未知聚合操作");if(e.op!=="count"&&!e.field)throw new Error("聚合需要度量字段");if(e.op==="weightedAvg"&&!e.weightField)throw new Error("加权平均需要权重字段");return e.numeric==="decimal"?Mi(e):vi(e)}function Bt(e,t){const r=de(t);for(const n of e)r.add(n);return r.value()}const Si=new Set(["__proto__","prototype","constructor"]);function be(e){if(typeof e!="string"||!e.trim()||Si.has(e))throw new Error("计算字段应为安全的非空字段名")}function ur(e){return e===null||["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function Ai(e){if(e.some(t=>typeof t!="number"||!Number.isFinite(t)))throw new Error("算术参数必须是有限数字;空值和小数文本不会隐式转换");return e}function ki(e,t){const r=Ai(t);let n;if(e==="add")n=r.reduce((o,i)=>o+i,0);else if(e==="multiply")n=r.reduce((o,i)=>o*i,1);else if(e==="subtract")n=r[0]-r[1];else{if(r[1]===0)throw new Error("不能除以零");n=r[0]/r[1]}if(!Number.isFinite(n))throw new Error("计算结果不是有限数字");return n}function Ei(e,t,r){const n=t.map(q);let o;return e==="add"?o=n.reduce(Ze):e==="multiply"?o=n.reduce(sr):e==="subtract"?o=Ze(n[0],{...n[1],coefficient:-n[1].coefficient}):o=Lt(n[0],n[1],r),ar(o,r)}function Pi(e,t,r){return r.nulls!=="error"&&t.some(n=>n==null)||e==="divide"&&r.divisionByZero==="null"&&(r.numeric==="decimal"?q(t[1]).coefficient===0n:t[1]===0)?null:r.numeric==="decimal"?Ei(e,t,r.digits):ki(e,t)}function Fi(e,t){e.field!==void 0&&be(e.field),e.weightField!==void 0&&be(e.weightField);const r={op:e.aggregate,field:e.field,weightField:e.weightField,numeric:t.numeric,digits:t.digits};Bt([],r);const n=new WeakMap;return o=>{let i=n.get(o.rows);if(!i){try{i={value:Bt(o.rows,r)}}catch(s){i={error:s instanceof Error?s:new Error(String(s))}}n.set(o.rows,i)}if(i.error)throw i.error;return i.value}}function Ni(e,t){for(const r of e){const n=r(t);if(n!=null)return n}return null}function fr(e,t={},r={nodes:0},n=0){if(++r.nodes>256||n>16)throw new Error("计算表达式超出深度或节点预算");if(!e||typeof e!="object"||Array.isArray(e))throw new Error("计算表达式应为声明式对象");if("aggregate"in e)return Fi(e,t);if("field"in e){be(e.field);const o=e.field;return({row:i})=>Object.prototype.hasOwnProperty.call(i,o)?i[o]:void 0}if("value"in e){if(!ur(e.value))throw new Error("常量应为有限 JSON 标量");return()=>e.value}return Ii(e,t,r,n)}function Ii(e,t,r,n){if(!["add","subtract","multiply","divide","coalesce"].includes(e.op)||!Array.isArray(e.args))throw new Error("未知计算操作");if(e.args.length>256||Object.keys(e.args).length!==e.args.length)throw new Error("计算参数超出预算或包含空位");if(e.args.length<2||["subtract","divide"].includes(e.op)&&e.args.length!==2)throw new Error("运算参数数量不正确");const o=e.args.map(i=>fr(i,t,r,n+1));return e.op==="coalesce"?i=>Ni(o,i):i=>Pi(e.op,o.map(s=>s(i)),t)}function Oi(e){fr(e);const t=new Set,r=n=>{"field"in n&&n.field&&t.add(n.field),"aggregate"in n&&n.weightField&&t.add(n.weightField),"args"in n&&n.args.forEach(r)};return r(e),[...t]}const Ri=16,_t=1024*1024,Lr=5e5,et=new WeakMap,se=Symbol("uncacheable-computation-definition");function ze(e,t,r=0){if(++t.nodes>1e4||r>32)throw se;if(e==null)return[String(e)];if(typeof e=="number")return["number",Object.is(e,-0)?"-0":String(e)];if(typeof e=="boolean")return["boolean",e];if(typeof e=="string"){if(t.units+=e.length,t.units>_t)throw se;return["string",e]}if(typeof e!="object")throw se;if(Array.isArray(e)){if(Object.getPrototypeOf(e)!==Array.prototype||Object.keys(e).length!==e.length)throw se;return["array",Array.from({length:e.length},(n,o)=>ze(Dr(e,String(o)),t,r+1))]}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw se;return["object",Object.keys(e).map(n=>[ze(n,t,r+1),ze(Dr(e,n),t,r+1)])]}function Dr(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw se;return r.value}function Ti(e){try{return JSON.stringify(ze(e,{nodes:0,units:0}))}catch(t){if(t!==se)throw t;return}}function ji(e){et.set(e,{programs:new Map,units:0,slots:0})}function Ci(e,t){const r=et.get(e);if(!r)return;const n={programs:new Map,units:r.units,slots:r.slots};for(const[o,i]of r.programs){const s=new WeakMap;t.forEach((a,c)=>{const u=i.rows.get(e[c]);u&&s.set(a,u)}),n.programs.set(o,{...i,rows:s})}et.set(t,n)}function Li(e,t,r){const n=et.get(e);if(!n||t.some(u=>typeof u.expression=="string"))return;const o=Ti(t);if(o===void 0||o.length>_t)return;const i=n.programs.get(o);if(i)return i;const s=r(),a=e.length*s.reduce((u,f)=>u+f.dependencies.length+1,0),c={fields:s,rows:new WeakMap,slots:a,cacheRows:a<=Lr};if(!c.cacheRows)return c;for(;n.programs.size>=Ri||n.units+o.length>_t||n.slots+a>Lr;){const u=n.programs.keys().next().value;n.slots-=n.programs.get(u).slots,n.units-=u.length,n.programs.delete(u)}return n.programs.set(o,c),n.units+=o.length,n.slots+=a,c}function Di(e,t,r,n){if((r.definition.scope??"row")!=="row")return;const o=e.program?.rows.get(t)?.get(r.definition.field);return o?.dependencies.every((i,s)=>Object.is(n[r.dependencies[s]],i))?o:void 0}function Bi(e,t,r,n,o){const i=e.program;if(!i?.cacheRows||(r.definition.scope??"row")!=="row")return;let s=e.writes.get(t);s||(s=new Map(i.rows.get(t)),e.writes.set(t,s),i.rows.set(t,s)),s.set(r.definition.field,{dependencies:r.dependencies.map(a=>n[a]),value:n[r.definition.field],...o?{issue:{field:o.field,message:o.message}}:{}})}function _i(e){if(be(e.field),e.scope!==void 0&&!["row","group","dataset"].includes(e.scope))throw new Error("未知计算范围");if(e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal")throw new Error("未知数值模式");if(e.digits!==void 0&&ht(e.digits),e.nulls!==void 0&&e.nulls!=="propagate"&&e.nulls!=="error")throw new Error("未知空值规则");if(e.divisionByZero!==void 0&&e.divisionByZero!=="null"&&e.divisionByZero!=="error")throw new Error("未知除零规则");if(e.scope==="group"&&(!Array.isArray(e.groupBy)||!e.groupBy.length))throw new Error("分组计算需要 groupBy 字段");Wi(e)}function Wi(e){if(e.groupBy!==void 0){if(!Array.isArray(e.groupBy)||e.groupBy.length>16)throw new Error("计算分组最多 16 级");e.groupBy.forEach(be)}if(e.dependsOn!==void 0){if(!Array.isArray(e.dependsOn)||e.dependsOn.length>2048)throw new Error("计算依赖超出预算");e.dependsOn.forEach(be)}}function lr(e){return[...new Set([...typeof e.expression=="string"?e.dependsOn??[]:Oi(e.expression),...e.groupBy??[]])]}function wn(e){if(!Array.isArray(e)||e.length>2048)throw new Error("计算字段应为数组且最多2048项");const t=new Map;for(const s of e){if(_i(s),t.has(s.field))throw new Error(`计算字段重复:${s.field}`);t.set(s.field,s)}const r=new Set,n=new Set,o=[];function i(s){if(!n.has(s.field)){if(r.has(s.field))throw new Error(`计算字段存在循环依赖:${[...r,s.field].join(" → ")}`);r.add(s.field);for(const a of lr(s)){const c=t.get(a);c&&i(c)}r.delete(s.field),n.add(s.field),o.push(s)}}return e.forEach(i),o}function Ki(e){try{const t=wn(e);return{valid:!0,errors:[],order:t.map(r=>r.field),fields:e.map(r=>({field:r.field,dependencies:lr(r),scope:r.scope??"row"}))}}catch(t){return{valid:!1,errors:[t instanceof Error?t.message:String(t)],fields:[],order:[]}}}function Br(e){return wn(e.fields).map(t=>{const r=lr(t);if(typeof t.expression!="string")return{definition:t,dependencies:r,read:fr(t.expression,t)};if(!e.formula)throw new Error("字符串公式需要显式配置 formula adapter");const n=t.expression;return{definition:t,dependencies:r,read:o=>e.formula.evaluate(n,o)}})}function Hi(e,t){return JSON.stringify(t.map(r=>{const n=Object.prototype.hasOwnProperty.call(e,r)?e[r]:null;if(n!=null&&!ur(n))throw new Error("分组字段应为有限 JSON 标量");return[typeof n,n??null]}))}function Ji(e,t){if(t.scope==="dataset")return()=>e;if(t.scope!=="group"){const o=new WeakMap;return i=>{let s=o.get(i);return s||(s=[i],o.set(i,s)),s}}const r=new Map,n=new WeakMap;for(const o of e){const i=Hi(o,t.groupBy);n.set(o,i);const s=r.get(i);s?s.push(o):r.set(i,[o])}return o=>r.get(n.get(o))}function zi(e,t){const r=t.maxRows??1e5,n=t.maxCells??2e6;if(!Array.isArray(e)||!Number.isSafeInteger(r)||r<1||e.length>r)throw new Error("计算数据行数超出预算或输入不是数组");if(!Array.isArray(t.fields)||t.fields.length>2048)throw new Error("计算字段应为数组且最多2048项");if(!Number.isSafeInteger(n)||n<1||e.length*t.fields.length>n)throw new Error("计算单元格超出 maxCells 预算")}function _r(e){if(e?.aborted){const t=new Error("数据计算已取消");throw t.name="AbortError",t}}function Vi(e,t,r,n,o,i){try{const s=e.read({row:t,rowIndex:r,rows:n});if(s!==void 0&&!ur(s))throw new Error("计算结果应为有限 JSON 标量,异步公式请先在数据源中求值");t[e.definition.field]=s??null}catch(s){const a=s instanceof Error?s.message:String(s);if(o.onError!=="null")throw Object.assign(new Error(`第 ${r+1} 行 ${e.definition.field}:${a}`),{cause:s});t[e.definition.field]=null,i.push({rowIndex:r,field:e.definition.field,message:a})}}function Ui(e,t,r,n,o,i,s,a){const c=Di(e,t,r,n);if(c&&(!c.issue||s.onError==="null")){n[r.definition.field]=c.value,c.issue&&a.push({...c.issue,rowIndex:o});return}const u=a.length;Vi(r,n,o,i,s,a),Bi(e,t,r,n,a.length>u?a[a.length-1]:void 0)}function dr(e,t){zi(e,t),_r(t.signal);const r=Li(e,t.fields,()=>Br(t)),n={program:r,writes:new WeakMap},o=r?.fields??Br(t),i=[],s=e.map((a,c)=>{if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`第 ${c+1} 行应为对象`);return{...a}});for(const a of o){const c=Ji(s,a.definition);s.forEach((u,f)=>{_r(t.signal),Ui(n,e[f],a,u,f,c(u),t,i)})}return{rows:s,issues:i}}function ke(e,t){return JSON.stringify([e.slice(0,t.length),t.map(r=>[r===null?"null":typeof r,r])])}function bn(e,t){return t.map(r=>{const n=Object.prototype.hasOwnProperty.call(e,r)?e[r]:null;if(n==null)return null;if(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return n;throw new Error("矩阵维度必须是有限 JSON 标量")})}function Gi(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("矩阵层级应为对象");for(const n of[e.emptyLabel,e.subtotalLabel,e.totalLabel])if(n!==void 0&&typeof n!="string")throw new Error("矩阵层级标签应为字符串");Wr(e.row,t.length),Wr(e.column,r.length)}function Wr(e,t){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("矩阵轴配置应为对象");if(e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.length!==t||e.labels.some(r=>typeof r!="string")))throw new Error("矩阵维度标签必须与维度字段一一对应");if(e.sort!==void 0&&(!Array.isArray(e.sort)||e.sort.length>t||e.sort.some(r=>!["source","asc","desc"].includes(r))))throw new Error("矩阵维度排序应为 source、asc 或 desc");if(e.subtotals!==void 0&&(!Array.isArray(e.subtotals)||new Set(e.subtotals).size!==e.subtotals.length||e.subtotals.some(r=>!Number.isInteger(r)||r<1||r>=t)))throw new Error("矩阵小计深度应唯一且位于 1 至末级之前")}}function Kr(e,t,r){return{fields:e,options:t??{},hierarchy:r,root:{values:[],children:new Map},leaves:0,expanded:0}}function Hr(e,t){const r=bn(t,e.fields);let n=e.root;for(let o=1;o<=r.length;o++){const i=r.slice(0,o),s=ke(e.fields,i);let a=n.children.get(s);a||(a={values:i,children:new Map},n.children.set(s,a),o===r.length?(e.leaves++,e.expanded++):e.options.subtotals?.includes(o)&&e.expanded++),n=a}}function qi(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;if(typeof e=="number"&&typeof t=="number")return e-t;const r=`${typeof e}:${e}`,n=`${typeof t}:${t}`;return r<n?-1:1}function Yi(e,t){const r=[...e.children.values()];return t&&t!=="source"&&r.sort((n,o)=>qi(n.values[n.values.length-1],o.values[o.values.length-1])*(t==="desc"?-1:1)),r}function Nt(e,t,r){return{key:ke(e.fields,t),kind:r,depth:t.length,fields:e.fields.slice(0,t.length),values:t,labels:t.map(n=>n===null?e.hierarchy.emptyLabel??"(空)":String(n))}}function Jr(e,t){const r=[];function n(o){for(const i of Yi(o,e.options.sort?.[o.values.length]))i.children.size?(n(i),e.options.subtotals?.includes(i.values.length)&&r.push(Nt(e,i.values,"subtotal"))):r.push(Nt(e,i.values,"member"))}return n(e.root),t&&e.leaves&&r.push(Nt(e,[],"total")),r}function zr(e,t,r){const n=bn(t,e.fields),o=[ke(e.fields,n),...(e.options.subtotals??[]).map(i=>ke(e.fields,n.slice(0,i)))];return r&&o.push(ke(e.fields,[])),o}function Xi(e,t,r){if(!(e.kind!=="member"&&t>e.depth))return e.kind==="total"?{key:"total",text:r.totalLabel??"合计",rowSpan:0}:e.kind==="subtotal"&&t===e.depth?{key:e.key,text:r.subtotalLabel??"小计",rowSpan:0}:{key:JSON.stringify(e.values.slice(0,t+1).map(n=>[typeof n,n])),text:e.labels[t],rowSpan:1}}function Zi(e,t){const r=e.columnFields.length+1,n=e.rowFields.length,o=Array.from({length:r},()=>Array(n+t.length).fill(null));for(let i=0;i<e.columnFields.length;i++){let s;t.forEach((a,c)=>{const u=Xi(a,i,e.hierarchy);if(!u){s=void 0;return}if(s?.key===u.key){s.cell.colSpan=(s.cell.colSpan??1)+1;return}const f={text:u.text,rowSpan:u.rowSpan||e.columnFields.length-i,editable:!1,derived:!0};o[i][n+c]=f,s={key:u.key,cell:f}})}return e.rowFields.forEach((i,s)=>{o[0][s]={text:e.hierarchy.row?.labels?.[s]??i,rowSpan:r,editable:!1,derived:!0}}),t.forEach((i,s)=>{const a=e.measures[i.measure];o[r-1][n+s]={text:a.label??`${a.field} (${a.op})`,editable:!1,derived:!0}}),{cells:o.map(i=>i.filter(s=>s!==null)),colWidthsMm:[...e.rowFields.map(()=>e.rowWidthMm??40),...t.map(()=>e.columnWidthMm??28)]}}function Vr(e,t,r,n){const o=+(!!t.totals&&e>0),i=r.expanded+o,s=(n.expanded+o)*t.measures.length+t.rowFields.length;if(i>(t.maxRows??1e3)||n.expanded+o>(t.maxColumns??200))throw new Error("矩阵层级展开数量超出预算(包含小计/总计)");if(i*s>(t.maxCells??2e6))throw new Error("矩阵输出超出 maxCells 预算");return{rowCount:i,columnCount:s,cells:i*s}}function xn(e,t){if(!Array.isArray(e)||e.length>(t.maxInputRows??1e5))throw new Error("矩阵输入超出预算");const r=Kr(t.rowFields,t.hierarchy.row,t.hierarchy),n=Kr(t.columnFields,t.hierarchy.column,t.hierarchy);if(e.length*(1+(r.options.subtotals?.length??0)+ +!!t.totals)*(1+(n.options.subtotals?.length??0)+ +!!t.totals)*t.measures.length>(t.maxAggregateUpdates??1e7))throw new Error("矩阵聚合更新超出 maxAggregateUpdates 预算");let i=Vr(0,t,r,n);for(const s of e){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("矩阵数据行应为对象");Hr(r,s),Hr(n,s),i=Vr(e.length,t,r,n)}return{row:r,column:n,shape:i}}function Qi(e,t){return xn(e,t).shape}function es(e,t,r){const n=new Map;for(const o of e){const i=zr(r.row,o,!!t.totals),s=zr(r.column,o,!!t.totals);for(const a of i){let c=n.get(a);c||(c=new Map,n.set(a,c));for(const u of s){let f=c.get(u);f||(f=t.measures.map(d=>de({...d,field:d.valueField??d.field})),c.set(u,f)),f.forEach(d=>d.add(o))}}}return n}function ts(e,t){return e.flatMap((r,n)=>t.measures.map((o,i)=>({...r,field:r.kind==="total"?`total_${i}`:`c${n}_${i}`,measure:i,measureField:o.field,valueField:o.valueField??o.field,operation:o.op})))}function rs(e,t){return e.kind==="total"?t.hierarchy.totalLabel??"合计":[...e.labels,...e.kind==="subtotal"?[t.hierarchy.subtotalLabel??"小计"]:[]].join(" / ")}function ns(e,t){return[...t.rowFields.map((r,n)=>({field:`r${n}`,header:t.hierarchy.row?.labels?.[n]??r,semanticRole:"dimension"})),...e.map(r=>{const n=t.measures[r.measure];return{field:r.field,header:`${rs(r,t)} · ${n.label??`${n.field} (${n.op})`}`,semanticRole:"measure",...n.digits===void 0?{}:{format:{kind:"number",digits:n.digits}}}})]}function os(e,t,r,n){return e.map(o=>{const i={};r.rowFields.forEach((s,a)=>{i[`r${a}`]=o.kind==="total"?a===0?r.hierarchy.totalLabel??"合计":null:o.labels[a]??(a===o.depth?r.hierarchy.subtotalLabel??"小计":null)});for(const s of t)i[s.field]=n.get(o.key)?.get(s.key)?.[s.measure]?.value()??(r.measures[s.measure].op==="count"?0:null);return i})}function is(e,t){const r=xn(e,t),n=Jr(r.row,!!t.totals),o=ts(Jr(r.column,!!t.totals),t),i=es(e,t,r);return{columns:ns(o,t),rows:os(n,o,t,i),headerGrid:Zi(t,o),metadata:{rowFields:[...t.rowFields],rowLabels:[...t.hierarchy.row?.labels??t.rowFields],columnFields:[...t.columnFields],columnLabels:[...t.hierarchy.column?.labels??t.columnFields],rows:n,columns:o}}}function ss(e,t){const r=()=>t.measures.map(c=>de(c)),n=new Map,o=new Map,i=new Map,s=t.totals?r():void 0,a=(c,u)=>c?.forEach(f=>f.add(u));for(const c of e){const u=t.row(c),f=t.column(c);o.has(f.key)||o.set(f.key,f.label);let d=n.get(u.key);d||(d={label:u.label,cells:new Map,...t.totals?{totals:r()}:{}},n.set(u.key,d)),t.check(n.size,o.size);let l=d.cells.get(f.key);if(l||(l=r(),d.cells.set(f.key,l)),a(l,c),!t.totals)continue;let m=i.get(f.key);m||(m=r(),i.set(f.key,m)),a(d.totals,c),a(m,c),a(s,c)}return{groups:n,columns:o,columnTotals:i,totals:s}}function tt(e,t){const r=t.map(n=>Object.prototype.hasOwnProperty.call(e,n)?e[n]:null);if(r.some(n=>n!=null&&typeof n!="string"&&typeof n!="boolean"&&!(typeof n=="number"&&Number.isFinite(n))))throw new Error("矩阵维度必须是有限 JSON 标量");return{key:JSON.stringify(r.map(n=>[typeof n,n??null])),label:r.map(n=>n==null?"":String(n)).join(" / ")}}function as(e){for(const t of["maxRows","maxColumns","maxInputRows","maxCells","maxAggregateUpdates"])if(e[t]!==void 0&&(!Number.isSafeInteger(e[t])||e[t]<1))throw new Error("矩阵预算应为正安全整数");for(const t of["columnWidthMm","rowWidthMm"])if(e[t]!==void 0&&(!Number.isFinite(e[t])||e[t]<=0))throw new Error("矩阵列宽应为正数")}function mr(e){if(!e||!Array.isArray(e.rowFields)||!Array.isArray(e.columnFields)||!Array.isArray(e.measures))throw new Error("矩阵需要行维度、列维度和度量数组");for(const r of[e.rowFields,e.columnFields])if(r.some(n=>typeof n!="string"||!n.trim())||new Set(r).size!==r.length)throw new Error("矩阵维度字段应非空且唯一");if(as(e),!e.rowFields.length||!e.columnFields.length||e.rowFields.length>16||e.columnFields.length>16)throw new Error("矩阵需要 1–16 个行/列维度");if(!e.measures.length||e.measures.length>32)throw new Error("矩阵需要 1–32 个度量");if(e.measures.map(r=>{if(!r||typeof r!="object")throw new Error("矩阵度量应为对象");if(de({...r,field:r.valueField??r.field}),r.label!==void 0&&typeof r.label!="string")throw new Error("矩阵度量标签应为字符串");return r.field}).some(r=>typeof r!="string"||!r.trim()))throw new Error("矩阵度量字段应非空");e.hierarchy!==void 0&&Gi(e.hierarchy,e.rowFields,e.columnFields)}function $n(e,t){if(mr(t),t.hierarchy)return Qi(e,t);if(!Array.isArray(e)||e.length>(t.maxInputRows??1e5))throw new Error("矩阵输入超出预算");const r=new Set,n=new Set;for(const s of e){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("矩阵数据行应为对象");if(r.add(tt(s,t.rowFields).key),n.add(tt(s,t.columnFields).key),r.size>(t.maxRows??1e3)||n.size>(t.maxColumns??200))throw new Error("矩阵维度数量超出预算");if((r.size+ +!!t.totals)*((n.size+ +!!t.totals)*t.measures.length+1)>(t.maxCells??2e6))throw new Error("矩阵输出超出 maxCells 预算")}const o=r.size+ +(!!t.totals&&e.length>0),i=(n.size+ +!!t.totals)*t.measures.length+1;return{rowCount:o,columnCount:i,cells:o*i}}function cs(e,t){if(t?.hierarchy)return mr(t),is(e,t);$n(e,t);const r=ss(e,{row:s=>tt(s,t.rowFields),column:s=>tt(s,t.columnFields),measures:t.measures.map(s=>({...s,field:s.valueField??s.field})),totals:t.totals,check:()=>{}}),n=[...r.groups.values()].map(s=>({rowLabel:s.label})),o=[{field:"rowLabel",header:t.rowHeader??t.rowFields.join(" / "),semanticRole:"dimension"}],i={rowLabel:"合计"};return t.measures.forEach((s,a)=>{const c=[...r.columns.entries()].map(([u,f],d)=>({key:u,label:f,field:`c${d}_${a}`}));t.totals&&c.push({key:"",label:"合计",field:`total_${a}`});for(const u of c){const f=u.field===`total_${a}`;o.push({field:u.field,header:`${u.label} · ${s.label??`${s.field} (${s.op})`}`,semanticRole:"measure",...s.digits===void 0?{}:{format:{kind:"number",digits:s.digits}}});let d=0;for(const l of r.groups.values())n[d++][u.field]=(f?l.totals?.[a]:l.cells.get(u.key)?.[a])?.value()??(s.op==="count"?0:null);i[u.field]=(f?r.totals?.[a]:r.columnTotals.get(u.key)?.[a])?.value()??(s.op==="count"?0:null)}}),t.totals&&e.length&&n.push(i),{rows:n,columns:o}}const us=96;function fs(e,t=us){return e*t/72}function pt(e,t=96,r=or){if(e?.fontSizePx!=null)return{fontSizePt:e.fontSizePx*72/t,fontSizePx:e.fontSizePx};const n=e?.fontSize??r;return{fontSizePt:n,fontSizePx:fs(n,t)}}function ls(e){return e?.lineHeight??mt}function Y(e,t){const r={...e,...t};return t?.fontSize!=null&&t.fontSizePx==null&&delete r.fontSizePx,t?.fontSizePx!=null&&t.fontSize==null&&delete r.fontSize,r}function ds(e,t){const r=e.length;if(r===0)return[];const n=e.reduce((a,c)=>a+c,0),o=n>0&&t>0?t/n:1,i=[];let s=0;for(let a=0;a<r;a++){const c=Math.max(0,e[a]*o);i.push({pos:s,size:c}),s+=c}return i}function Ur(e,t,r){return e?.length?ds(e,t):Array.from({length:r},(n,o)=>({pos:t*o/r,size:t/r}))}function vn(e,t,r){const n=e.cells??[],o=Math.max(n.length,1),i=e.colWidthsMm?.length??Math.max(1,...n.map(y=>Array.isArray(y)?y.length:0)),s=Ur(e.colWidthsMm,t,i),a=y=>y<=0?0:y>=i?s[s.length-1].pos+s[s.length-1].size:s[y].pos,c=Ur(e.rowHeightsMm,r,o),u=y=>y<=0?0:y>=o?c[c.length-1].pos+c[c.length-1].size:c[y].pos,f=new Set,d=(y,$)=>`${y}:${$}`,l=[],m=new Set,g=new Set,h=(y,$)=>`v${y}:${$}`,p=(y,$)=>`h${y}:${$}`;n.forEach((y,$)=>{if(!Array.isArray(y))return;let w=0;for(const M of y){for(;w<i&&f.has(d($,w));)w++;if(w>=i)break;const C=Math.max(1,Math.min(M?.colSpan??1,i-w)),R=Math.max(1,M?.rowSpan??1),x=Math.min(o,$+R),v=Math.min(i,w+C);for(let I=$;I<x;I++)for(let T=w;T<v;T++)f.add(d(I,T));for(let I=w+1;I<v;I++)for(let T=$;T<x;T++)m.add(h(I,T));for(let I=$+1;I<x;I++)for(let T=w;T<v;T++)g.add(p(I,T));const E=a(w),L=u($);l.push({ri:$,ci:w,cell:M??{},xMm:E,yMm:L,widthMm:a(v)-E,heightMm:u(x)-L}),w=v}});const b=[];for(let y=1;y<i;y++){let $=-1;for(let w=0;w<=o;w++){const M=w<o&&!m.has(h(y,w));M&&$<0&&($=w),!M&&$>=0&&(b.push({kind:"v",pos:a(y),from:u($),to:u(w)}),$=-1)}}for(let y=1;y<o;y++){let $=-1;for(let w=0;w<=i;w++){const M=w<i&&!g.has(p(y,w));M&&$<0&&($=w),!M&&$>=0&&(b.push({kind:"h",pos:u(y),from:a($),to:a(w)}),$=-1)}}return{columns:s,rows:c,cells:l,edges:b}}function ms(e,t,r,n=e.paddingMm??1){return t.field!==e.tree.labelField?0:Math.min(r.depth*(e.tree.indentMm??3),Math.max(0,t.widthMm-n*2-4))}function gs(e,t,r,n){const o=n.tree;(o.input==="nested"||[o.idField,o.parentField].includes(t.field))&&(e.editable=!1),r.hasChildren&&o.parentValues==="leaf-aggregate"&&o.aggregates?.some(i=>i.field===t.field)&&(e.derived=!0,e.editable=!1)}function Mn(e,t,r){return r==="identifier"||r==="dimension"||r==="date"?"center":r==="measure"?"right":r==="text"?"left":t?.kind==="number"||t?.kind==="percent"?"right":t?.kind==="date"||e instanceof Date||typeof e=="boolean"?"center":typeof e=="number"&&Number.isFinite(e)?"right":"left"}function gr(e){if(e==null)return"";if(typeof e=="string"||typeof e=="number")return String(e);if(typeof e=="boolean")return e?"是":"否";if(e instanceof Date)return e.toISOString().slice(0,10);try{return JSON.stringify(e)}catch{return String(e)}}function Sn(e,t){let r=Y({fontSize:e.fontSizePt??or,bold:e.headerBold??!0,align:"center",verticalAlign:"middle",backgroundColor:e.headerBackgroundColor},t.style);return e.headerAlign!==void 0&&(r.align=e.headerAlign),r=Y(r,e.headerStyle),t.headerAlign!==void 0&&(r.align=t.headerAlign),Y(r,t.headerStyle)}function hs(e,t){return{member:"body",subtotal:"subtotal",total:"grand-total"}[e?.rows.get(t)?.kind??"member"]}function ps(e){const t=e.matrix;if(!t.hierarchy)return t;const r=new Map(e.columns.map(o=>[o.field,o.header])),n={sum:"求和",count:"计数",avg:"平均",min:"最小",max:"最大",weightedAvg:"加权平均"};return{...t,hierarchy:{...t.hierarchy,row:{...t.hierarchy.row,labels:t.hierarchy.row?.labels??t.rowFields.map(o=>r.get(o)??o)},column:{...t.hierarchy.column,labels:t.hierarchy.column?.labels??t.columnFields.map(o=>r.get(o)??o)}},measures:t.measures.map(o=>{const i=r.get(o.field)??r.get(o.valueField??o.field);return o.label===void 0&&i?{...o,label:`${i}(${n[o.op]})`}:o})}}function ys(e,t){if(!e.matrix)return{list:e,rows:t};if(e.detail||e.groupBy||e.groups?.length||e.grandTotal)throw new Error("矩阵不能同时配置普通分组、总计或主从明细");const r=cs(t,ps(e)),n=r.columns.map(a=>({...a,widthMm:a.semanticRole==="dimension"?e.matrix.rowWidthMm??40:e.matrix.columnWidthMm??28,editable:!1,align:a.semanticRole==="dimension"?"center":"right"})),o={...e,columns:n,headerGrid:r.headerGrid,rowKey:void 0,revisionField:void 0,sourceTokenField:void 0};e.layout==="wide"&&(o.widthMm=n.reduce((a,c)=>a+c.widthMm,0));const i=r.metadata,s=i?{rows:new WeakMap(r.rows.map((a,c)=>[a,i.rows[c]])),header:{columns:i.columns,rowFields:i.rowFields,rowLabels:i.rowLabels,columnFields:i.columnFields,columnLabels:i.columnLabels}}:void 0;return{list:o,rows:r.rows,...s?{matrix:s}:{}}}function ws(e,t){if(!e.matrix?.hierarchy||!e.headerGrid)return e.headerGrid;const r=e.paddingMm??1,n=e.headerGrid.cells.map(()=>e.rowHeightMm??0),o=e.columns.map(c=>c.widthMm),i=vn({...e.headerGrid,colWidthsMm:o},o.reduce((c,u)=>c+u,0),n.length),s=new WeakMap;for(const{cell:c,ci:u,ri:f,widthMm:d}of i.cells){const l={...Sn(e,e.columns[u]),...c.style},m=pt(l).fontSizePt,h=(De(c.text??"",Math.max(1,d-r*2),{fontSizePt:m,fontFamily:l.fontFamily,bold:l.bold,italic:l.italic,letterSpacingPt:l.letterSpacing},t).length*m*(l.lineHeight??mt)*25.4/72+r*2)/(c.rowSpan??1);for(let p=f;p<f+(c.rowSpan??1);p++)n[p]=Math.max(n[p]??0,h);s.set(c,l)}const a=e.headerGrid.cells.map(c=>c.map(u=>u?{...u,style:s.get(u)}:null));return{...e.headerGrid,cells:a,rowHeightsMm:n}}class An extends Error{constructor(t){super(`树节点超出行数预算 ${t}`),this.limit=t,this.code="tree-row-limit",this.name="TreeRowLimitError"}}function It(e,t,r,n){const o=e??t;if(!Number.isInteger(o)||o<1||o>r)throw new Error(`${n}应为 1–${r} 的整数`);return o}function hr(e){return{rows:It(e.maxRows,1e5,1e6,"树行数预算"),depth:It(e.maxDepth,64,256,"树深度预算"),visits:It(e.maxAggregationVisits,1e6,1e7,"树聚合访问预算")}}function kn(e){return typeof e=="string"&&!!e.trim()}function ge(e){return kn(e)&&!["__proto__","prototype","constructor"].includes(e)}function En(e){if(kn(e)||typeof e=="number"&&Number.isFinite(e))return e;throw new Error("树节点业务键应为非空字符串或有限数字")}function Pn(e){return JSON.stringify([typeof e,e])}function Fn(e){return[e.idField,...e.input==="flat"?[e.parentField??""]:[e.childrenField??"children"]]}function pr(e,t){const r=Fn(e);if(t?.some(n=>n.scope&&n.scope!=="row"||r.includes(n.field)))throw new Error("树形布局仅支持不覆盖结构键的当前行计算")}function xe(e){if(!e?.aborted)return;const t=new Error("树报表处理已取消");throw t.name="AbortError",t}function bs(e){const t=e.aggregates??[];if(!Array.isArray(t)||t.length>32)throw new Error("树聚合最多 32 项");if(e.parentValues!=="leaf-aggregate"&&t.length)throw new Error("树聚合需显式选择 leaf-aggregate 父级取值策略");if(e.parentValues==="leaf-aggregate"&&!t.length)throw new Error("叶子聚合策略至少需要一个聚合字段");const r=new Set;for(const n of t){if(!n||!ge(n.field)||r.has(n.field))throw new Error("树聚合输出字段应安全、非空且唯一");for(const o of[n.valueField,n.weightField])if(o!==void 0&&!ge(o))throw new Error("树聚合来源字段应安全且非空");if([...Fn(e),e.labelField].includes(n.field))throw new Error("树聚合不能覆盖结构键或标签字段");r.add(n.field),de({...n,field:n.valueField??n.field})}}function xs(e){if(!ge(e.idField)||!ge(e.labelField))throw new Error("树需要安全的业务键和标签字段");if(e.input==="flat"&&(!ge(e.parentField)||e.parentField===e.idField))throw new Error("扁平树需要独立的父键字段");if(e.childrenField!==void 0&&!ge(e.childrenField))throw new Error("子节点字段应安全且非空");if(e.input==="nested"&&[e.idField,e.labelField].includes(e.childrenField??"children"))throw new Error("子节点字段不能覆盖业务键或标签字段")}function Nn(e){if(!e||typeof e!="object"||!["flat","nested"].includes(e.input))throw new Error("树输入应为 flat 或 nested");if(xs(e),e.orphan!==void 0&&!["error","root"].includes(e.orphan))throw new Error("树孤儿策略应为 error 或 root");if(e.parentValues!==void 0&&!["source","leaf-aggregate"].includes(e.parentValues))throw new Error("未知树父级取值策略");if(e.indentMm!==void 0&&(!Number.isFinite(e.indentMm)||e.indentMm<0||e.indentMm>20))throw new Error("树每级缩进应为 0–20 mm");hr(e),bs(e)}function In(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("树节点应为对象");if(r.size>=n.rows)throw new An(n.rows);const o=En(e[t.idField]),i=Pn(o);if(r.has(i))throw new Error(`树节点业务键重复:${String(o)}`);const s={original:e,row:e,key:o,depth:0,children:[]};return r.set(i,s),s}function $s(e,t,r,n,o){for(const s of e)xe(o),In(s,t,r,n);const i=[];for(const s of r.values()){xe(o);const a=s.row[t.parentField];if(a==null){i.push(s);continue}const c=r.get(Pn(En(a)));if(!c){if(t.orphan!=="root")throw new Error(`树节点 ${String(s.key)} 的父节点不存在`);i.push(s);continue}if(c===s)throw new Error("树节点不能以自身为父节点");s.parent=c,c.children.push(s)}return i}function vs(e,t,r,n,o){const i=[],s=[{rows:e,next:0}];for(;s.length;){xe(o);const a=s[s.length-1];if(a.next>=a.rows.length){s.pop();continue}const c=In(a.rows[a.next++],t,r,n);if(c.parent=a.parent,c.depth=s.length-1,s.length>n.depth)throw new Error(`树节点超出深度预算 ${n.depth}`);(a.parent?.children??i).push(c);const u=c.row[t.childrenField??"children"];if(u!=null){if(!Array.isArray(u))throw new Error("嵌套树 children 字段应为数组");u.length&&s.push({rows:u,next:0,parent:c})}}return i}function Ms(e,t,r,n){const o=[],i=[{nodes:e,next:0}];for(;i.length;){xe(n);const s=i[i.length-1];if(s.next>=s.nodes.length){i.pop();continue}if(i.length>r.depth)throw new Error(`树节点超出深度预算 ${r.depth}`);const a=s.nodes[s.next++];a.depth=i.length-1,o.push(a),a.children.length&&i.push({nodes:a.children,next:0})}if(o.length!==t)throw new Error("树父子关系存在循环");return o}function Ss(e,t,r,n){if(t.parentValues!=="leaf-aggregate")return;const o=t.aggregates,i=new Map;for(const a of e)a.children.length&&i.set(a,o.map(c=>de({...c,field:c.valueField??c.field})));let s=0;for(const a of e)if(!a.children.length)for(let c=a.parent;c;c=c.parent){if(xe(n),s+=o.length,s>r.visits)throw new Error(`树聚合超出访问预算 ${r.visits}`);for(const u of i.get(c))u.add(a.row)}for(const[a,c]of i)a.row={...a.row},o.forEach((u,f)=>{a.row[u.field]=c[f].value()})}function On(e,t,r){if(Nn(t),xe(r),!Array.isArray(e))throw new Error("树数据应为节点数组");const n=hr(t),o=new Map,i=t.input==="flat"?$s(e,t,o,n,r):vs(e,t,o,n,r);return Ms(i,o.size,n,r)}function Rn(e,t,r){return On(e,t,r).map(n=>n.original)}function As(e,t,r={}){const n=On(e,t,r.signal);if(pr(t,r.computed?.fields),r.computed?.fields.length){const o=dr(n.map(i=>i.row),{...r.computed,signal:r.signal}).rows;n.forEach((i,s)=>{i.row=o[s]})}return Ss(n,t,hr(t),r.signal),{rows:n.map(o=>o.row),entries:n.map(o=>({row:o.row,original:o.original,key:o.key,depth:o.depth,hasChildren:!!o.children.length})),leaves:n.filter(o=>!o.children.length).map(o=>o.row)}}function ks(e,t,r){const n=new Set,o=e.cells.map((i,s)=>{const a=[];let c=0;for(const u of i){for(;n.has(`${s}:${c}`);)c++;const f=u?.colSpan??1,d=u?.rowSpan??1;let l=0;for(let m=c;m<c+f;m++){t.has(m)&&l++;for(let g=s+1;g<s+d;g++)n.add(`${g}:${m}`)}l&&a.push(u?{...u,colSpan:l}:null),c+=f}return a});return{...e,cells:o,colWidthsMm:r}}function Es(e){if(!e.columns.some(n=>n.hidden))return e;const t=new Set,r=e.columns.filter((n,o)=>n.hidden?!1:(t.add(o),!0));if(!r.length)throw new Error("列表至少需要一列可见列");return{...e,columns:r,...e.headerGrid?{headerGrid:ks(e.headerGrid,t,r.map(n=>n.widthMm))}:{}}}function yr(e){return e.kind==="list"?e.id:e.nid}function Ps(e){return e.kind==="list"?!1:e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&/\{(?:page|totalPages)\}/.test(e.text)}function Fs(e,t){const r=e.filter(o=>t.componentIds.includes(yr(o)??""));if(r.filter(o=>o.kind==="list"&&o.cardinality!=="record").length&&r.length!==1)throw new Error("纵向重复区域必须独占流式分段,不能与静态或单记录区域并排");for(const o of r){const i=o.kind==="list"?o.topMm+(o.rowHeightMm??0):o.topMm+o.heightMm;if(o.topMm<t.topMm-.001||i>t.topMm+t.heightMm+.001)throw new Error("流式分段应完整包含其组件的原始纵向范围")}}function Ns(e,t){if(!t)return e.map(n=>({components:[n]}));const r=new Map(e.map(n=>[yr(n),n]));return t.bands.map(n=>({band:n,components:n.componentIds.map(o=>{const i=r.get(o);if(!i)throw new Error(`流式区域引用不存在的组件:${o}`);return i})}))}function Tn(e,t){if(!t||!Array.isArray(t.bands)||!t.bands.length||t.bands.length>1e4)throw new Error("流式排版应包含 1–10000 个区域");const r=new Set,n=new Set;for(const o of e){if(Ps(o))continue;const i=yr(o);if(!i||r.has(i))throw new Error("流式排版组件应具有唯一标识");r.add(i)}if(Is(e,t,r,n),n.size!==r.size)throw new Error("流式排版必须显式包含每个非锚点组件")}function Is(e,t,r,n){let o=-1/0;for(const i of t.bands){if(!Number.isFinite(i.topMm)||!Number.isFinite(i.heightMm)||i.topMm<0||i.heightMm<=0||i.topMm<o-.001)throw new Error("流式区域应按原始位置排序,尺寸有效且不重叠");if(!Array.isArray(i.componentIds)||!i.componentIds.length)throw new Error("流式区域不能没有组件");for(const s of i.componentIds){if(!r.has(s)||n.has(s))throw new Error(`流式区域组件缺失、重复或包含页锚点:${s}`);n.add(s)}Fs(e,i),o=i.topMm+i.heightMm}}function*Os(e){const{page:t}=e;Tn(t.components,t.flow);let r=0,n=0;for(const o of Ns(t.components,t.flow)){e.active();const i=o.band,s=o.components.some(f=>f.kind==="list"&&f.cardinality!=="record"),a=s?0:o.components.reduce((f,d)=>Math.max(f,d.topMm-i.topMm+(d.kind==="list"?e.height(d):d.heightMm)),i.heightMm);let c=Math.max(e.top(),n+i.topMm-r);if(!s&&a>e.bottom()-e.top()+.001)throw new Error(`静态区域 ${i.componentIds.join(",")} 高度超出单页可用范围`);!s&&c+a>e.bottom()+.001&&(e.nextPage(),yield*e.takePages(),e.active(),c=e.top());let u=c+a;for(const f of o.components){const d=c+f.topMm-i.topMm;f.kind==="list"?(yield*e.list(f,d,l=>{u=s?l:Math.max(u,l)}),e.active()):e.append({...f,topMm:d})}n=u,r=i.topMm+i.heightMm}}function Rs(e){return!!(e.computed?.length||e.groups?.length||e.groupBy||e.grandTotal||e.rowVisibleWhen||e.matrix||e.tree||e.detail||e.columns.some(t=>t.rules?.length||t.visibleWhen))}function yt(e){return e.pages.some(t=>t.components.some(r=>r.kind==="list"&&Rs(r)))}const Ts=new Set(["__proto__","prototype","constructor"]);function Z(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ve(e){return typeof e=="string"&&!!e.trim()&&!Ts.has(e)}function rt(e,t,r,n){for(const o of Object.keys(e))t.includes(o)||n.push({path:`${r}.${o}`,message:"存在未知配置字段"})}function js(e,t,r){if(e!==void 0){if(!Z(e)||!["number","percent","date"].includes(String(e.kind))){r.push({path:t,message:"绑定格式应为 number、percent 或 date"});return}rt(e,e.kind==="date"?["kind","pattern"]:e.kind==="number"?["kind","digits","thousands"]:["kind","digits"],t,r),e.digits!==void 0&&(!Number.isInteger(e.digits)||Number(e.digits)<0||Number(e.digits)>100)&&r.push({path:`${t}.digits`,message:"精度应为 0..100 整数"}),e.thousands!==void 0&&typeof e.thousands!="boolean"&&r.push({path:`${t}.thousands`,message:"千分位开关应为布尔值"}),e.pattern!==void 0&&typeof e.pattern!="string"&&r.push({path:`${t}.pattern`,message:"日期格式应为字符串"})}}function Cs(e,t,r){const n=e.binding;if(n===void 0)return;const o=`${t}.binding`;if(!Z(n)){r.push({path:o,message:"字段绑定应为对象"});return}(!["text","image","barcode","qrcode"].includes(String(e.kind))||e.grid!==void 0)&&r.push({path:o,message:"绑定仅支持独立文本、图片、条码与二维码组件"}),rt(n,["field","format","prefix","suffix","emptyText"],o,r),Ve(n.field)||r.push({path:`${o}.field`,message:"绑定字段应为安全的非空字段名(按字面读取自有字段)"});for(const i of["prefix","suffix","emptyText"])n[i]!==void 0&&typeof n[i]!="string"&&r.push({path:`${o}.${i}`,message:"应为字符串"});js(n.format,`${o}.format`,r),e.kind==="image"&&["format","prefix","suffix"].some(i=>n[i]!==void 0)&&r.push({path:o,message:"图片绑定直接读取 PNG/JPEG data URL,不支持文本格式或前后缀"})}function Ls(e,t){if(!Z(e)){t.push({path:"$.repeat",message:"逐记录配置应为对象"});return}rt(e,["dataset","rowKey","copies"],"$.repeat",t),Ve(e.dataset)||t.push({path:"$.repeat.dataset",message:"数据集应为安全的非空名称"}),e.rowKey!==void 0&&!Ve(e.rowKey)&&t.push({path:"$.repeat.rowKey",message:"业务主键应为安全的非空字段名"});const r=e.copies;r!==void 0&&(Z(r)?(rt(r,["field"],"$.repeat.copies",t),Ve(r.field)||t.push({path:"$.repeat.copies.field",message:"复制数字段应为安全的非空字段名"})):(!Number.isSafeInteger(r)||Number(r)<1||Number(r)>1e3)&&t.push({path:"$.repeat.copies",message:"每条记录复制数应为 1..1000 整数"}))}function jn(e,t,r,n){if(!Z(e))return;Cs(e,t,n),e.binding!==void 0&&!r&&n.push({path:`${t}.binding`,message:"字段绑定需要模板 repeat 数据集;普通报表请使用列表字段"}),r&&e.kind==="list"&&n.push({path:t,message:"逐记录标签使用固定组件;动态列表请使用普通报表模板"});const o=e.grid;Z(o)&&Array.isArray(o.cells)&&o.cells.forEach((i,s)=>{Array.isArray(i)&&i.forEach((a,c)=>{Z(a)&&Array.isArray(a.children)&&a.children.forEach((u,f)=>jn(u,`${t}.grid.cells.${s}.${c}.children.${f}`,r,n))})})}function Cn(e,t){const r=e.repeat!==void 0;r&&Ls(e.repeat,t),Array.isArray(e.pages)&&e.pages.forEach((n,o)=>{if(!Z(n))return;const i=`$.pages.${o}`;r&&(n.layout==="wide"||n.flow!==void 0)&&t.push({path:i,message:"逐记录标签仅支持固定尺寸页面,不支持宽表或流式分区"}),Array.isArray(n.components)&&n.components.forEach((s,a)=>{const c=`${i}.components.${a}`;if(jn(s,c,r,t),!r||!Z(s))return;const{leftMm:u,topMm:f,widthMm:d,heightMm:l}=s;[u,f,d,l,n.widthMm,n.heightMm].every(m=>typeof m=="number"&&Number.isFinite(m))&&(Number(u)<0||Number(f)<0||Number(u)+Number(d)>Number(n.widthMm)+.001||Number(f)+Number(l)>Number(n.heightMm)+.001)&&t.push({path:c,message:"标签组件超出纸张边界,请调整位置或尺寸"})})})}const Ds=512,Gr=256*1024;function Bs(){const e=new Map;let t=0,r;return(n,o,i,s)=>{s!==r&&(e.clear(),t=0,r=s);const a=JSON.stringify([n,o,i.fontSizePt,i.fontFamily,i.bold,i.italic,i.letterSpacingPt]),c=e.get(a);if(c)return e.delete(a),e.set(a,c),c.lines.slice();const u=De(n,o,i,s),f=a.length+u.reduce((d,l)=>d+l.length,0);if(f<=Gr){for(;e.size>=Ds||t+f>Gr;){const d=e.keys().next().value;t-=e.get(d).units,e.delete(d)}e.set(a,{lines:u.slice(),units:f}),t+=f}return u}}function _s(e){return typeof e=="string"&&/^data:image\/(png|jpe?g);base64,[A-Za-z0-9+/\r\n]+=*$/.test(e)}class J extends Error{constructor(t,r,n,o){super(`${t}: ${r}`),this.path=t,this.rowIndex=n,this.field=o,this.code="report-binding",this.name="ReportBindingError"}}function wr(e,t,r={}){const n=r.rowIndex??0,i=`$.datasets.${r.dataset??"label"}[${n}].${t}`,s=Object.getOwnPropertyDescriptor(e,t);if(!s||s.get||s.set)throw new J(i,"字段必须是记录的自有数据字段,不能缺失、使用访问器或从原型继承",n,t);const a=s.value;if(a==null||typeof a=="string"||typeof a=="boolean"||typeof a=="number"&&Number.isFinite(a))return a;throw new J(i,"绑定值应为字符串、有限数字、布尔值或空值",n,t)}function Ws(e,t,r={}){const n=wr(t,e.field,r);return n==null||n===""?e.emptyText??"":`${e.prefix??""}${cr(n,e.format)}${e.suffix??""}`}class ue extends Error{constructor(t,r){super(`报表页数超出上限 ${t}(至少 ${r} 页)`),this.limit=t,this.actual=r,this.code="page-limit",this.name="PaginatePageLimitError"}}class ye extends Error{constructor(t,r){super(`报表单元格数量超出上限 ${t}(至少 ${r} 格)`),this.limit=t,this.actual=r,this.code="cell-limit",this.name="PaginateCellLimitError"}}const Ks=1e4,qr=25e4;function br(e){if(e?.aborted)throw e.reason??new DOMException("标签生成已取消","AbortError")}function Ln(e,t,r){const n=typeof e.copies=="object"?wr(t,e.copies.field,r):e.copies??1;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>1e3)throw new J(`$.datasets.${r.dataset}[${r.rowIndex}]`,"每条记录复制数必须是 1..1000 的数值型整数",r.rowIndex,typeof e.copies=="object"?e.copies.field:void 0);return n}function Dn(e,t,r){if(e.rowKey===void 0)return;const n=wr(t,e.rowKey,r);if(typeof n=="string"&&n.trim()||typeof n=="number"&&Number.isFinite(n))return n;throw new J(`$.datasets.${r.dataset}[${r.rowIndex}].${e.rowKey}`,"业务主键必须是非空字符串或有限数字",r.rowIndex,e.rowKey)}function Hs(e){const t=r=>1+(r.grid?.cells.reduce((n,o)=>n+1+o.length+o.reduce((i,s)=>i+(s?.children?.reduce((a,c)=>a+t(c),0)??0),0),0)??0);return e.pages.reduce((r,n)=>r+n.components.reduce((o,i)=>o+t(i),0),0)}function Js(e,t,r){const n=e.repeat,o=Object.prototype.hasOwnProperty.call(t,n.dataset)?t[n.dataset]:void 0;if(!Array.isArray(o))throw new J(`$.datasets.${n.dataset}`,"逐记录标签数据集缺失,应提供对象数组(允许空数组)");const i=new Set,s=r.maxPages??Ks,a=Hs(e);let c=0,u=0;for(const[f,d]of o.entries()){if(br(r.signal),!d||typeof d!="object"||Array.isArray(d))throw new J(`$.datasets.${n.dataset}[${f}]`,"标签记录应为对象",f);const l={rowIndex:f,dataset:n.dataset},m=Dn(n,d,l);if(m!==void 0){const h=JSON.stringify([typeof m,m]);if(i.has(h))throw new J(`$.datasets.${n.dataset}[${f}].${n.rowKey}`,"业务主键重复;请先确认记录来源,避免重复打印标签",f,n.rowKey);i.add(h)}const g=Ln(n,d,l);if(c+=g*e.pages.length,u+=g*a,c>s)throw new ue(s,c);if(u>qr)throw new J("$.repeat",`标签组件总量(含网格行、槽位及嵌套组件)超过安全预算 ${qr},请分批生成`,f)}return o}function zs(e,t,r){if(!e.binding)return e;const{binding:n,...o}=e,i=Ws(n,t.row,t);if(e.kind==="image"){if(!i)return;if(!_s(i))throw new J(`${r}.binding`,"图片字段只接受 PNG/JPEG base64 data URL;业务 URL 应由宿主安全加载后转换",t.rowIndex,n.field);return{...o,imageData:i}}return e.kind==="barcode"||e.kind==="qrcode"?(delete o.imageData,{...o,code:{...o.code,value:i},fallbackText:i}):(delete o.lines,delete o.richParagraphs,{...o,text:i})}function Vs(e,t,r){if(e.kind!=="text"||e.grid||e.richParagraphs?.length)return e;const n=e.style??{},o=pt(n).fontSizePt,i=e.text??e.lines?.join(`
5
+ `)??"";if(i.length>16384)throw new J(r,"标签文本超过 16384 字符预算,请缩小字段内容",t.rowIndex);const s=t.wrapText(i,e.widthMm,{fontSizePt:o,bold:n.bold,italic:n.italic,fontFamily:n.fontFamily,letterSpacingPt:n.letterSpacing},t.options.measurer??ir),a=s.length*o*ls(n)*25.4/72;if(a>e.heightMm+.05)throw new J(r,`标签文字需要约 ${a.toFixed(2)}mm 高,超出 ${e.heightMm}mm;请增大文本区域、减少内容或调整字号`,t.rowIndex,e.binding?.field);return{...e,lines:s}}function Bn(e,t,r){br(t.options.signal);const n=zs(e,t,r);if(!n)return;let o=n.grid;return o&&(o={...o,cells:o.cells.map((i,s)=>i.map((a,c)=>a?.children?.length?{...a,children:a.children.flatMap((u,f)=>{const d=Bn(u,t,`${r}.grid.cells.${s}.${c}.children.${f}`);return d?[d]:[]})}:a))}),Vs(o===n.grid?n:{...n,grid:o},t,r)}function Us(e,t,r,n,o,i){return{...e,components:e.components.flatMap((s,a)=>{const c=Bn(s,r,`$.pages.${t}.components.${a}`);return c?[{...c,meta:{...c.meta,labelSource:{pageIndex:t,componentIndex:a}}}]:[]}),meta:{...e.meta,record:{dataset:r.dataset,rowIndex:r.rowIndex,...i===void 0?{}:{rowKey:i},copyIndex:n,copyCount:o,templatePageIndex:t}}}}function*Gs(e,t,r){const n=[];if(Cn(e,n),n.length)throw new J(n[0].path,n[0].message);if(!e.repeat){for(const[a,c]of e.pages.entries())yield{page:c,pageIndex:a};return}const o=e.repeat,i=Js(e,t,r),s=Bs();for(const[a,c]of i.entries()){const u={row:c,rowIndex:a,dataset:o.dataset,options:r,wrapText:s},f=Ln(o,c,u),d=Dn(o,c,u);for(let l=0;l<f;l++)for(const[m,g]of e.pages.entries())br(r.signal),yield{page:Us(g,m,u,l,f,d),pageIndex:m}}}function qs(e){return{widthMm:e.widthMm,heightMm:e.heightMm,marginTopMm:e.marginTopMm??0,marginBottomMm:e.marginBottomMm??0,marginLeftMm:e.marginLeftMm??0,marginRightMm:e.marginRightMm??0,components:[]}}function nt(e,t){const r=t.heightMm-(e.layout==="wide"?t.marginBottomMm:e.marginBottomMm??t.marginBottomMm);return e.components.reduce((n,o)=>o.kind!=="list"&&o.pageAnchor==="footer"?Math.min(n,o.topMm):n,r)}function je(e){return e.components.reduce((t,r)=>r.kind!=="list"&&r.pageAnchor==="header"?Math.max(t,r.topMm+r.heightMm):t,0)}function _n(e,t){let r=e.textMetrics.get(t);if(!r){const n=pt(t).fontSizePt;r={measureOptions:{fontSizePt:n,fontFamily:t.fontFamily??mn,italic:t.italic,bold:t.bold,letterSpacingPt:t.letterSpacing},lineMm:n*(t.lineHeight??mt)*25.4/72},e.textMetrics.set(t,r)}return r}function Ys(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function xr(e,t){const r=e.fontSizePt??or,n=e.paddingMm??1,o=e.columns.map(h=>h.align??h.style?.align??e.align??"left"),i=e.columns.map((h,p)=>({...Y({fontSize:r,verticalAlign:"middle"},h.style),align:o[p]==="auto"?"left":o[p]})),s=i.map((h,p)=>o[p]==="auto"?{left:h,center:{...h,align:"center"},right:{...h,align:"right"}}:void 0),a=e.columns.map((h,p)=>h.rules?.map(b=>{const y=s[p];if(y)return{left:Y(y.left,b.style),center:Y(y.center,b.style),right:Y(y.right,b.style)};const $=Y(i[p],b.style);return{left:$,center:$,right:$}})),c=e.columns.map(h=>Sn(e,h)),u=e.columns.map(h=>h.header);let f=e.rowHeightMm??0;for(let h=0;h<u.length;h++){const p=c[h],b=pt(p).fontSizePt,y=De(u[h],e.columns[h].widthMm-n*2,{fontSizePt:b,fontFamily:p.fontFamily??mn,italic:p.italic,bold:p.bold,letterSpacingPt:p.letterSpacing},t),$=b*(p.lineHeight??mt)*25.4/72;f=Math.max(f,Math.max(y.length,1)*$+n*2)}const d=u.map((h,p)=>({text:h,style:c[p]})),l=e.border===!1?{borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}:{borderBottom:!0,borderLeft:!0,borderRight:!0,borderTop:!0},m=e.columns.map(h=>h.widthMm),g=Xs(ws(e,t),m,{cells:[d],colWidthsMm:m,rowHeightsMm:[f],paddingMm:n});return{fontSizePt:r,paddingMm:n,cellStyles:i,autoStyles:s,ruleStyles:a,textMetrics:new WeakMap,numberFormats:e.columns.map(h=>yn(h.format)),derivedFields:new Set(e.computed?.map(h=>h.field)),borderStyle:l,headerHeightMm:g.rowHeightsMm.reduce((h,p)=>h+p,0),headerGrid:g,colWidthsMm:m,columns:e.columns}}function Xs(e,t,r){if(!e)return r;if(!e.cells.length)throw new Error("自定义列表表头至少需要一行");const n=e.rowHeightsMm??e.cells.map(()=>r.rowHeightsMm[0]);if(n.length!==e.cells.length||n.some(o=>!Number.isFinite(o)||o<=0))throw new Error("自定义列表表头行高无效");return{...e,colWidthsMm:t,rowHeightsMm:n}}function Zs(e,t,r){const n=t.format?.kind==="number"||t.format?.kind==="percent";t.valueType!==void 0?e.valueType=t.valueType:n&&(e.valueType="number"),t.editable!==void 0&&(e.editable=t.editable),(typeof e.value=="number"||e.value==null)&&r!==void 0&&(e.numberFormat=r)}function Ce(e,t,r){const n=e.columns,o=e.tree?.rows.get(t);let i=e.rowHeightFloorMm;const s=new Array(n.length);for(let a=0;a<n.length;a++){const c=n[a],u=c.visibleWhen&&!Ae(t,c.visibleWhen)?null:t[c.field],f=e.autoStyles[a]?Mn(u,c.format,c.semanticRole):"left";let d=e.autoStyles[a]?.[f]??e.cellStyles[a];if(c.rules)for(let y=0;y<c.rules.length;y++){const $=c.rules[y];if(Ae(t,$.when)){d=e.ruleStyles[a][y][f];break}}const l=c.format?cr(u,c.format):gr(u),m=Qs(e,c,o);d=ea(e,c,d,o);const g=_n(e,d),h=De(l,Math.max(1,c.widthMm-e.paddingMm*2-m),g.measureOptions,r);i=Math.max(i,h.length*g.lineMm+e.paddingMm*2);const p=Ys(u),b={text:l,style:d};p!==void 0&&(b.value=p),Zs(b,c,e.numberFormats[a]),ta(b,c,e,o,m),e.derivedFields.has(c.field)&&(b.derived=!0,b.editable=!1),c.visibleWhen&&u===null&&!Ae(t,c.visibleWhen)&&(b.editable=!1),s[a]=b}return{grid:{cells:[s],colWidthsMm:e.colWidthsMm,rowHeightsMm:[i],paddingMm:e.paddingMm},heightMm:i,...e.matrix?{meta:{matrix:{row:e.matrix.rows.get(t)}}}:{}}}function Qs(e,t,r){return!r||t.field!==e.tree.list.tree.labelField?0:ms(e.tree.list,t,r,e.paddingMm)}function ea(e,t,r,n){return!n||t.field!==e.tree.list.tree.labelField||r.align==="left"?r:{...r,align:"left"}}function ta(e,t,r,n,o=0){n&&(o&&(e.indentMm=o),gs(e,t,n,r.tree.list))}function Wn(e){if(e!=null&&typeof e!="string"&&typeof e!="boolean"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("分组字段应为有限 JSON 标量");return JSON.stringify([typeof e,e??null])}function*Kn(e,t,r=0){const n=t[r];if(!n){for(const i of e)yield{kind:"row",row:i};return}const o=new Map;for(const i of e){const s=Wn(i[n.field]),a=o.get(s);a?a.push(i):o.set(s,[i])}for(const i of o.values())yield{kind:"groupHeader",label:(n.headerTemplate??"{value}").replace(/\{value\}/g,gr(i[0][n.field])),firstRow:i[0],group:n,depth:r,rows:i},yield*Kn(i,t,r+1),(n.subtotal?.length||n.aggregates?.length)&&(yield{kind:"subtotal",label:n.subtotalLabel??"小计",rows:i,group:n,depth:r}),yield{kind:"groupEnd",depth:r}}function Hn(e,t,r,n=[]){const o=[...r.filter(i=>!n.some(s=>s.field===i)).map(i=>({field:i,op:"sum"})),...n];return new Map(o.map(i=>{const s=e.find(c=>c.field===i.field)?.format??{kind:"number",thousands:!0},a=Bt(t,{...i,field:i.valueField??i.field});return[i.field,{text:cr(a,s),...a===null?{}:{value:a},...typeof a=="number"?{numberFormat:yn(s)}:{}}]}))}function Jn(e,t){const r=e.findIndex(n=>t.includes(n.field));return r<0?1:r}function Ee(e,t,r,n,o,i){const s=[],a=Math.max(0,Math.min(i,e.columns.length)),c=Y({fontSize:e.fontSizePt},o);a&&s.push({text:r,colSpan:a,style:{bold:!0,...c}});for(let l=a;l<e.columns.length;l++){const m=e.columns[l],g=n.get(m.field),h=e.autoStyles[l]?.[Mn(g?.value,m.format)]??e.cellStyles[l];s.push({...g,text:g?.text??"",style:Y(h,o)})}const u={text:r,colSpan:e.columns.length,style:{bold:!0,...c}},f=a?[s]:[[u],s],d=f.map(l=>ra(e,l,t));return{grid:{cells:f,colWidthsMm:e.colWidthsMm,rowHeightsMm:d,paddingMm:e.paddingMm},heightMm:d.reduce((l,m)=>l+m,0)}}function ra(e,t,r){let n=e.rowHeightFloorMm,o=0;for(const i of t){let s=0;const a=o+(i.colSpan??1);for(;o<a;o++)s+=e.colWidthsMm[o]??0;const c=_n(e,i.style),u=De(i.text??"",s-e.paddingMm*2,c.measureOptions,r);n=Math.max(n,u.length*c.lineMm+e.paddingMm*2)}return n}function na(e,t,r){const{templatePage:n,current:o,warnings:i,nextId:s,pushCurrent:a}=r,c=()=>nt(n,o),u=Math.max(o.marginTopMm,je(n)),f=n.layout==="wide"?je(n):u,d={id:r.tableId,columnKeys:e.columns.map(x=>x.field),...e.layout===void 0?{}:{layout:e.layout},...e.title===void 0?{}:{title:e.title}},l=new Map,m=new Map,g={kind:"rect",leftMm:e.leftMm,topMm:0,widthMm:e.widthMm,heightMm:t.headerHeightMm,grid:t.headerGrid,nid:s("listh"),table:{...d,role:"header",rowIndex:-1},style:t.borderStyle,...e.meta||t.matrix?{meta:{...e.meta,...t.matrix?{matrix:t.matrix.header}:{}}}:{}},h=x=>o.components.push({...g,topMm:x});if(r.flow&&e.header!==!1&&t.headerHeightMm>c()-u+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的表头高度超出单页可用范围`);let p=Math.max(r.startTop??e.topMm,u);e.header!==!1&&(h(p),p+=t.headerHeightMm+r.mmPerRow);function b(){const x=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);return(e.header!==!1&&e.headerEveryPage!==!1?x+t.headerHeightMm:f)+[...m.values()].reduce((E,L)=>E+L.heightMm,0)}function y(){const x=n.layout==="wide"?0:o.marginBottomMm;return Math.min(n.heightMm-x,nt(n,o))-b()}function $(x){if(p+x<=c())return;a(),o.components=[],o.heightMm=n.heightMm,n.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0);const v=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);e.header!==!1&&e.headerEveryPage!==!1?(h(v),p=v+t.headerHeightMm):p=f;for(const E of m.values())M(E,"listgr","group-header")}function w(x,v,E,L){const I=y();if(r.flow&&x.heightMm>I+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的单行高度超出单页可用范围`);x.heightMm>I&&i.push(`列表 ${e.id??e.dataset} 行高 ${x.heightMm.toFixed(2)}mm 超出单页可用高度 ${I.toFixed(2)}mm,预览与打印可能截断内容`),$(x.heightMm),M(x,v,E,L)}function M(x,v,E,L){const I=x.table?.id??d.id,T=E==="header"?-1:l.get(I)??0;E!=="header"&&l.set(I,T+x.grid.cells.length),o.components.push({kind:"rect",leftMm:e.leftMm,topMm:p,widthMm:e.widthMm,heightMm:x.heightMm,grid:x.grid,nid:s(v),table:{...d,...x.table,role:E,rowIndex:T,...L?{source:L}:{}},style:t.borderStyle,...e.meta||x.meta?{meta:{...e.meta,...x.meta}}:{}}),p+=x.heightMm}function C(x){x<=y()&&$(x)}return{keepTogether:C,placeGridRow:w,setGroupHeader:(x,v)=>{v?m.set(x,v):m.delete(x)},bottom:()=>p}}function oa(e,t){if(!e.rowKey)return;const r=t[e.rowKey];if((typeof r!="string"||!r.trim())&&!(typeof r=="number"&&Number.isFinite(r)))throw new Error(`数据集 ${e.dataset} 的 ${e.rowKey} 应为稳定的字符串或有限数字主键`);const n=e.revisionField?t[e.revisionField]:void 0,o=e.sourceTokenField?t[e.sourceTokenField]:void 0;if(n!==void 0&&typeof n!="string"&&!(typeof n=="number"&&Number.isFinite(n)))throw new Error("业务修订号应为字符串或有限数字");if(o!==void 0&&typeof o!="string")throw new Error("来源令牌应为字符串");return{datasetId:e.dataset,rowKey:r,...n===void 0?{}:{revision:n},...o===void 0?{}:{sourceToken:o}}}function wt(e,t){const r=new Map;if(!e.rowKey)return r;const n=new Set;for(const o of t){const i=oa(e,o),s=JSON.stringify(i.rowKey);if(n.has(s))throw new Error(`数据集 ${e.dataset} 的业务主键重复:${String(i.rowKey)}`);n.add(s),r.set(o,i)}return r}function ia(e,t,r,n,o){if(!e.grandTotal)return;const i=typeof e.grandTotal=="object"?e.grandTotal:void 0,s=bt(e)[0],a=i?.fields??s?.subtotal??[],c=i?.aggregates??s?.aggregates??[];if(a.length===0&&c.length===0){n.warnings.push(`列表 ${e.id??""} 配置了 grandTotal 但未提供合计字段(groupBy.subtotal 或 grandTotal.fields)`);return}const u=Ee(r,n.measurer,i?.label??"合计",Hn(e.columns,t,a,c),i?.style??{},Jn(e.columns,[...a,...c.map(f=>f.field)]));o.placeGridRow(u,"listgt","grand-total")}function Le(e){if(e?.aborted){const t=new Error("报表排版已取消");throw t.name="AbortError",t}}function bt(e){const t=e.groups??(e.groupBy?[e.groupBy]:[]);if(t.length>16)throw new Error("列表最多支持 16 级分组");return t}function $r(e){const t=Es(e),r=t.columns.reduce((o,i)=>o+i.widthMm,0),n=r>t.widthMm?t.widthMm/r:1;return n===1?t:{...t,columns:t.columns.map(o=>({...o,widthMm:o.widthMm*n}))}}function sa(e,t,r){const n=e.detail;if(!n)return;const o=new Set;for(const u of t){const f=Wt(u[n.parentKey]);if(o.has(f))throw new Error("主从明细的主表关联键重复");o.add(f)}const i=r.datasets[n.dataset]??[],s=new Map,a=[];for(const u of i){const f=u[n.foreignKey];if(!zn(f)&&n.unmatched==="ignore")continue;const d=Wt(f);if(!o.has(d)){if(n.unmatched!=="ignore")throw new Error(`明细数据集 ${n.dataset} 存在未关联的业务键`);continue}const l=s.get(d);l?l.push(u):s.set(d,[u]),a.push(u)}const c=$r({...e,id:`${e.id??e.dataset}:detail`,dataset:n.dataset,rowKey:n.rowKey,revisionField:n.revisionField,sourceTokenField:n.sourceTokenField,computed:void 0,columns:n.columns,headerGrid:void 0,rowHeightMm:n.rowHeightMm??e.rowHeightMm,detail:void 0});return{list:c,inter:{...xr(c,r.measurer),rowHeightFloorMm:c.rowHeightMm??0},rows:s,sources:wt(c,a)}}function zn(e){return typeof e=="string"&&!!e.trim()||typeof e=="number"&&Number.isFinite(e)}function Wt(e){if(!zn(e))throw new Error("主从关联键必须是非空字符串或有限数字");return Wn(e)}function*aa(e,t,r,n,o){if(!r)return;const i=r.rows.get(Wt(t[e.detail.parentKey]))??[];if(!i.length)return;const s={id:`${n.tableId}:detail`,columnKeys:r.list.columns.map(a=>a.field),title:e.detail.label};e.detail.label&&o.placeGridRow({...Ee(r.inter,n.measurer,e.detail.label,new Map,{},r.list.columns.length),table:s},"listdl","group-header"),e.detail.header!==!1&&o.placeGridRow({grid:r.inter.headerGrid,heightMm:r.inter.headerHeightMm,table:s},"listdh","header"),yield*n.takePages();for(const a of i)Le(n.signal),o.placeGridRow({...Ce(r.inter,a,n.measurer),table:s},"listdr","body",r.sources.get(a)),yield*n.takePages()}function Vn(e){if(e.matrix||e.detail||e.groups?.length||e.groupBy||e.rowVisibleWhen)throw new Error("树形布局不能同时配置普通分组、矩阵、主从或行可见条件");if(e.rowKey&&e.rowKey!==e.tree.idField)throw new Error("树形布局的 rowKey 应与 idField 一致");if(!e.columns.some(t=>t.field===e.tree.labelField&&!t.hidden))throw new Error("树形布局需要可见的标签列");pr(e.tree,e.computed)}function ca(e,t,r){Vn(e);const n=As(t,e.tree,{signal:r.signal,computed:e.computed?.length?{fields:e.computed,formula:r.formula}:void 0}),o={...e,rowKey:e.tree.idField},i=wt(o,n.entries.map(c=>c.original)),s=new Map,a=new WeakMap;for(const c of n.entries)s.set(c.row,i.get(c.original)),a.set(c.row,c);return{list:o,rows:n.rows,sources:s,treeRows:a,totalRows:n.leaves}}function ua(e,t){if(e.cardinality==="record"){if(t.length>1)throw new Error(`单记录区域 ${e.id??e.dataset} 仅允许 0 或 1 行数据`);if(e.tree||e.matrix||e.detail||e.groups?.length||e.groupBy||e.grandTotal||e.rowVisibleWhen)throw new Error("单记录区域不能配置树、矩阵、主从、分组、总计或行过滤");if(!t.length)return{list:{...e,columns:e.columns.map(r=>({...r,editable:!1}))},rows:[{}],sources:new Map}}}function Un(e,t,r){const n=r.prepared.get(e);if(n)return n;const o=ua(e,t);if(o)return r.prepared.set(e,o),o;if(e.tree){const c=ca(e,t,r);return r.prepared.set(e,c),c}let i=e.computed?.length?dr(t,{fields:e.computed,signal:r.signal,formula:r.formula}).rows:t;const s=i===t?void 0:new Map(i.map((c,u)=>[c,t[u]]));e.rowVisibleWhen&&(i=i.filter(c=>Ae(c,e.rowVisibleWhen)));const a=ys(e,i);if(!e.matrix){const c=wt(e,s?i.map(u=>s.get(u)):i);a.sources=s?new Map(i.map(u=>[u,c.get(s.get(u))])):c}return r.prepared.set(e,a),a}function fa(e,t,r,n){if(!n.flow)return;const{current:o,templatePage:i}=n,s=Math.max(o.marginTopMm,je(i)),a=Math.max(n.startTop??e.topMm,s),c=(e.header===!1?0:t.headerHeightMm)+(r[0]?Ce(t,r[0],n.measurer).heightMm:0);a+c<=nt(i,o)+.001||a<=s+.001||(n.pushCurrent(),o.components=[],o.heightMm=i.heightMm,i.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0),n.startTop=Math.max(o.marginTopMm,je(i)))}function*la(e,t,r){const n=Un(e,t,r),o=n.rows;e=n.list,e.layout==="wide"&&(r.current.widthMm=Math.max(r.current.widthMm,e.leftMm+e.widthMm+r.current.marginRightMm));const i=n.sources??wt(e,o),s=$r(e),a=bt(s),c={...xr(s,r.measurer),rowHeightFloorMm:s.rowHeightMm??0,matrix:n.matrix,...n.treeRows?{tree:{list:s,rows:n.treeRows}}:{}};fa(s,c,o,r);const u=na(s,c,r),f=sa(s,o,r);let d;for(const l of Kn(o,a)){if(Le(r.signal),l.kind==="row")u.placeGridRow(d??Ce(c,l.row,r.measurer),"listr",hs(n.matrix,l.row),i.get(l.row)),d=void 0,yield*r.takePages(),yield*aa(s,l.row,f,r,u);else if(l.kind==="groupHeader"){const m=Ee(c,r.measurer,l.label,new Map,l.group.headerStyle??{},s.columns.length);d??=Ce(c,l.firstRow,r.measurer);const g=a.slice(l.depth+1).reduce((h,p)=>h+Ee(c,r.measurer,(p.headerTemplate??"{value}").replace(/\{value\}/g,gr(l.firstRow[p.field])),new Map,p.headerStyle??{},s.columns.length).heightMm,0);l.group.keepWithNext!==!1&&u.keepTogether(m.heightMm+g+d.heightMm),u.placeGridRow(m,"listg","group-header"),l.group.repeatHeader&&u.setGroupHeader(l.depth,m)}else if(l.kind==="subtotal"){const m=l.group.subtotal??[],g=l.group.aggregates??[],h=Ee(c,r.measurer,l.label,Hn(s.columns,l.rows,m,g),l.group.subtotalStyle??{},Jn(s.columns,[...m,...g.map(p=>p.field)]));u.placeGridRow(h,"listst","subtotal")}else u.setGroupHeader(l.depth);yield*r.takePages()}ia(s,n.totalRows??o,c,r,u),r.finished?.(u.bottom()),yield*r.takePages()}function xt(e){return e.kind!=="list"&&(e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&(e.text.includes("{page}")||e.text.includes("{totalPages}")))}function $t(e,t){return{...e,...e.text===void 0?{}:{text:t(e.text)},...e.lines?{lines:e.lines.map(t)}:{},...e.richParagraphs?{richParagraphs:e.richParagraphs.map(r=>({...r,segments:r.segments.map(n=>({...n,...n.text===void 0?{}:{text:t(n.text)}}))}))}:{},...e.grid?{grid:{...e.grid,cells:e.grid.cells.map(r=>r.map(n=>n?{...n,...n.text===void 0?{}:{text:t(n.text)},...n.children?{children:n.children.map(o=>$t(o,t))}:{}}:null))}}:{}}}function da(e){let t=!1;for(const r of e.pages)for(const n of r.components)xt(n)&&$t(n,o=>(o.includes("{totalPages}")&&(t=!0),o));return t}function ma(e,t,r,n,o,i){const s={pageWidthMm:t.widthMm,pageHeightMm:t.heightMm,...e.layout===void 0?{}:{layout:e.layout},marginTopMm:t.marginTopMm,marginBottomMm:t.marginBottomMm,marginLeftMm:t.marginLeftMm,marginRightMm:t.marginRightMm,components:t.components,...e.meta?{meta:e.meta}:{}},a=c=>{const u=c.replace(/\{page\}/g,String(n));return i===void 0?u:u.replace(/\{totalPages\}/g,String(i))};for(const c of r)s.components.push($t(c,a));if(e.layout==="wide"){const c=s.components.reduce((u,f)=>Math.max(u,f.topMm+f.heightMm),0);s.marginBottomMm=o?e.marginBottomMm??0:0,s.pageHeightMm=Math.max(1,c+s.marginBottomMm)}return s}function vr(e){return e.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+Gn(s),0)??0):0),0),0)}function Gn(e){return e.grid?vr(e.grid):0}function qn(e){for(const t of["maxPages","maxCells","knownTotalPages"])if(e[t]!==void 0&&(!Number.isSafeInteger(e[t])||e[t]<1))throw new RangeError(`${t} 应为正安全整数`)}function ga(e,t){const r=Un(e,t.datasets[e.dataset]??[],t),n=$r(r.list),o={...xr(n,t.measurer),rowHeightFloorMm:n.rowHeightMm??0};return(n.header===!1?0:o.headerHeightMm)+r.rows.reduce((i,s)=>i+Ce(o,s,t.measurer).heightMm,0)}function*ha(e){const{templatePage:t,current:r}=e,n=new Map(t.components.map((i,s)=>[i,s])),o=(i,s,a)=>{const c=e.datasets[i.dataset];return Array.isArray(c)||e.warnings.push(`数据集 ${i.dataset} 未提供数据,列表 ${i.id??""} 输出为空`),la(i,Array.isArray(c)?c:[],{...e,tableId:`${e.tableId}:${n.get(i)}`,startTop:s,finished:a,flow:!!t.flow})};if(t.flow){yield*Os({page:t,active:()=>Le(e.signal),top:()=>Math.max(r.marginTopMm,je(t)),bottom:()=>nt(t,r),append:i=>{r.components.push(i)},nextPage:()=>{e.pushCurrent(),r.components=[],r.heightMm=t.heightMm,t.layout==="wide"&&(r.marginTopMm=0,r.marginBottomMm=0)},takePages:e.takePages,height:i=>ga(i,e),list:o});return}for(const i of t.components)xt(i)||(i.kind==="list"?yield*o(i):r.components.push(i))}function*Kt(e,t,r,n,o,i=new WeakMap){let s=0,a=0,c=0;const u=yi(r.measurer??ir),f=d=>`${d}_${(++s).toString(36)}`;for(const{pageIndex:d,page:l}of Gs(e,t,r)){Le(r.signal);const m=qs(l),g=l.components.filter(xt);let h=[];const p=(y=!1)=>{if(Le(r.signal),r.maxPages!==void 0&&a>=r.maxPages)throw new ue(r.maxPages,a+1);if(r.maxCells!==void 0&&(c+=[...m.components,...g].reduce(($,w)=>$+Gn(w),0),c>r.maxCells))throw new ye(r.maxCells,c);h.push(ma(l,m,g,++a,y,o))},b=()=>{const y=h;return h=[],y};yield*ha({templatePage:l,current:m,warnings:n,nextId:f,pushCurrent:p,takePages:b,datasets:t,signal:r.signal,formula:r.formula,prepared:i,measurer:u,mmPerRow:r.mmPerRow??0,tableId:`table:${d}`}),p(!0),yield*b()}}function*pa(e,t,r={}){qn(r);const n=da(e),o=new WeakMap;let i=r.knownTotalPages;if(n&&i===void 0){i=0;for(const c of Kt(e,t,r,[],void 0,o))i++}const s=[];let a=0;for(const c of Kt(e,t,r,s,i,o)){for(;a<s.length;a++)r.onWarning?.(s[a]);yield c}}function ya(e,t,r={}){const n=typeof r=="number"?{mmPerRow:r}:r;qn(n);const o=[],i=[...Kt(e,t,n,o,n.knownTotalPages)];for(const s of i)s.components=s.components.map(a=>xt(a)?$t(a,c=>c.replace(/\{totalPages\}/g,String(i.length))):a);return o.forEach(s=>n.onWarning?.(s)),{plan:{schemaVersion:ve,...yt(e)?{requiresRecalculation:!0}:{},pages:i},warnings:o}}function wa(e){const t=e.columns.find(i=>!i.hidden)?.field;if(!t)return{groups:0,total:0};const r=bt(e),n=(i=[],s=[])=>i.includes(t)||s.some(a=>a.field===t),o=typeof e.grandTotal=="object"?e.grandTotal:void 0;return{groups:r.filter(i=>n(i.subtotal,i.aggregates)).length,total:Number(n(o?.fields??r[0]?.subtotal,o?.aggregates??r[0]?.aggregates))}}function ba(e,t,r){Vn(e);const n=Rn(t[e.dataset]??[],e.tree,r),o=e.columns.filter(s=>!s.hidden).length,i=e.header===!1?0:e.headerGrid?vr(e.headerGrid):o;return n.length*o+i+ +!!e.grandTotal*2*o}function xa(e,t,r={}){if(e.tree)return ba(e,t,r.signal);if(e.matrix){let c=t[e.dataset]??[];e.computed?.length&&(c=dr(c,{fields:e.computed,...r}).rows),e.rowVisibleWhen&&(c=c.filter(f=>Ae(f,e.rowVisibleWhen)));const u=$n(c,e.matrix);return u.cells+(e.header===!1?0:u.columnCount*(e.matrix.hierarchy?e.matrix.columnFields.length+1:1))}const n=t[e.dataset]?.length??0,o=e.columns.filter(c=>!c.hidden).length,i=bt(e).length,s=wa(e);let a=(n*(1+2*i+s.groups)+ +!!e.grandTotal*(1+s.total))*o;if(a+=e.header===!1?0:e.headerGrid?vr(e.headerGrid):o,e.cardinality==="record"&&n===0&&(a+=o),e.detail){const c=t[e.detail.dataset]?.length??0,u=e.detail.columns.filter(f=>!f.hidden).length;a+=(c+n*(+(e.detail.header!==!1)+ +!!e.detail.label))*u}if(!Number.isSafeInteger(a))throw new RangeError("报表单元格估算超出安全整数预算");return a}function Ue(e){return!!e&&typeof e=="object"}function Yn(e,t,r,n,o){if(++o.nodes>1e6)return{path:t,message:"组件树超过100万个结构节点预算"};if(Ue(e)){if(r>64)return{path:t,message:"组件嵌套超过64层预算"};if(n.has(e))return{path:t,message:"组件树包含循环引用"};if(!(!Ue(e.grid)||!Array.isArray(e.grid.cells))){n.add(e);try{for(const[i,s]of e.grid.cells.entries())if(Array.isArray(s))for(const[a,c]of s.entries()){if(++o.nodes>1e6)return{path:t,message:"组件树超过100万个结构节点预算"};if(!(!Ue(c)||!Array.isArray(c.children)))for(const[u,f]of c.children.entries()){const d=Yn(f,`${t}.grid.cells.${i}.${a}.children.${u}`,r+1,n,o);if(d)return d}}}finally{n.delete(e)}}}}function Mr(e,t="$.components",r={nodes:0}){for(const[n,o]of e.entries()){const i=Yn(o,`${t}.${n}`,0,new Set,r);if(i)return i}}function Xn(e){const t={nodes:0};for(const[r,n]of e.entries()){if(!Ue(n)||!Array.isArray(n.components))continue;const o=Mr(n.components,`$.pages.${r}.components`,t);if(o)return o}}function $a(e){const t=Xn(e.pages);if(t)throw new TypeError(`${t.path}: ${t.message}`)}function va(e,t,r){e!==void 0&&(typeof e!="string"||!e.trim()||e.length>4096)&&r.push({path:t,message:"来源范围应为不超过 4096 字符的非空字符串"})}function Zn(e,t,r){e.editable!==void 0&&typeof e.editable!="boolean"&&r.push({path:`${t}.editable`,message:"编辑控制应为布尔值"}),e.valueType!==void 0&&!["text","number","boolean"].includes(e.valueType)&&r.push({path:`${t}.valueType`,message:"编辑类型应为 text、number 或 boolean"})}function Ma(e,t,r){Zn(e,t,r),e.indentMm!==void 0&&(typeof e.indentMm!="number"||!Number.isFinite(e.indentMm)||e.indentMm<0)&&r.push({path:`${t}.indentMm`,message:"单元格缩进应为有限非负数"}),e.derived!==void 0&&typeof e.derived!="boolean"&&r.push({path:`${t}.derived`,message:"派生结果标记应为布尔值"}),Qn(e.source,`${t}.source`,r,!0),e.formula!==void 0&&typeof e.formula!="string"&&r.push({path:`${t}.formula`,message:"单元格公式应为字符串"})}function Qn(e,t,r,n=!1){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e)){r.push({path:t,message:"业务来源应为对象"});return}const o=e;va(o.sourceScope,`${t}.sourceScope`,r);for(const i of["datasetId",...n?["field"]:[]])(typeof o[i]!="string"||!o[i].trim())&&r.push({path:`${t}.${i}`,message:"业务标识应为非空字符串"});for(const i of["rowKey","revision"]){const s=o[i];s===void 0&&!(n&&i==="rowKey")||typeof s!="string"&&!(typeof s=="number"&&Number.isFinite(s))&&r.push({path:`${t}.${i}`,message:"业务键及修订号应为字符串或有限数字"})}o.sourceToken!==void 0&&typeof o.sourceToken!="string"&&r.push({path:`${t}.sourceToken`,message:"来源令牌应为字符串"})}function Sa(e){const t=[];return e.value!==void 0&&typeof e.value!="string"&&t.push({path:"value",message:"Symbol value must be a string."}),e.symbology!==void 0&&!["code128","code39","ean13","ean8"].includes(e.symbology)&&t.push({path:"symbology",message:"Unsupported barcode symbology."}),e.errorCorrection!==void 0&&!["L","M","Q","H"].includes(e.errorCorrection)&&t.push({path:"errorCorrection",message:"Unsupported QR error correction."}),e.showText!==void 0&&typeof e.showText!="boolean"&&t.push({path:"showText",message:"showText must be a boolean."}),t}function Aa(e,t){const r=[];return t!=="barcode"&&t!=="qrcode"&&r.push({path:"",message:"code is only supported by barcode and qrcode components."}),t==="qrcode"&&e.symbology!==void 0&&r.push({path:"symbology",message:"QR components do not use a linear symbology."}),t==="qrcode"&&e.showText===!0&&r.push({path:"showText",message:"Use a separate text component below a QR code."}),t==="barcode"&&e.errorCorrection!==void 0&&r.push({path:"errorCorrection",message:"Linear barcodes do not use QR error correction."}),r}function ka(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return[{path:"",message:"code must be an object."}];const r=e,n=[...Sa(r),...Aa(r,t)];for(const s of Object.keys(r))["value","symbology","errorCorrection","quietZoneModules","showText"].includes(s)||n.push({path:s,message:"Unknown symbol option."});const o=r.symbology==="ean13"||r.symbology==="ean8",i=t==="qrcode"?4:o?11:10;return r.quietZoneModules!==void 0&&(!Number.isSafeInteger(r.quietZoneModules)||Number(r.quietZoneModules)<i||Number(r.quietZoneModules)>64)&&n.push({path:"quietZoneModules",message:`Quiet zone must contain ${i}–64 whole modules.`}),n}const Ea=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ot(e){return e===null?"null":typeof e=="string"?JSON.stringify(e.slice(0,120)):["number","boolean","undefined"].includes(typeof e)?String(e):`[${typeof e}]`}function Pa(e,t,r,n){const o=e[t];(typeof o!="number"||!Number.isFinite(o))&&n.push({path:`${r}.${t}`,message:`应为有限数字,实际 ${ot(o)}`})}function Fa(e,t,r){if(e!==void 0){const n=`${t}.table`;if(!H(e))r.push({path:n,message:"逻辑表来源应为对象"});else{Qn(e.source,`${n}.source`,r),(typeof e.id!="string"||!e.id.trim())&&r.push({path:`${n}.id`,message:"逻辑表 ID 应为非空字符串"});const o=e.role;["header","body","group-header","subtotal","grand-total"].includes(o)||r.push({path:`${n}.role`,message:"未知逻辑表行角色"});const i=e.rowIndex;(typeof i!="number"||!Number.isInteger(i)||(o==="header"?i!==-1:i<0))&&r.push({path:`${n}.rowIndex`,message:"表头索引应为 -1,内容行索引应为非负整数"}),(!Array.isArray(e.columnKeys)||e.columnKeys.some(s=>typeof s!="string"))&&r.push({path:`${n}.columnKeys`,message:"逻辑列字段应为字符串数组"}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${n}.layout`,message:"布局应为 page 或 wide"}),e.title!==void 0&&typeof e.title!="string"&&r.push({path:`${n}.title`,message:"逻辑表名称应为字符串"})}}}function Na(e,t,r,n){if(e!==void 0)if(!H(e)||!Array.isArray(e.cells))r.push({path:`${t}.grid.cells`,message:"grid.cells 应为二维数组"});else{const o=e.paddingMm;o!==void 0&&(typeof o!="number"||!Number.isFinite(o)||o<0)&&r.push({path:`${t}.grid.paddingMm`,message:"单元格内距应为有限非负数"}),e.cells.forEach((i,s)=>{if(!Array.isArray(i)){r.push({path:`${t}.grid.cells.${s}`,message:"行应为数组"});return}i.forEach((a,c)=>{if(a==null)return;const u=`${t}.grid.cells.${s}.${c}`;if(!H(a)){r.push({path:u,message:"网格单元格应为对象或 null"});return}Ma(a,u,r),eo(a.richParagraphs,u,r),Array.isArray(a.children)&&a.children.forEach((f,d)=>{Sr(f,`${t}.grid.cells.${s}.${c}.children.${d}`,r,n)})})})}}function it(e,t,r,n){e!==void 0&&!t.includes(e)&&n.push({path:r,message:"未知富文本属性值"})}function Ht(e,t,r,n,o=0){for(const i of t){const s=e[i];s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||s<o)&&n.push({path:`${r}.${i}`,message:"富文本数值应为范围内有限数字"})}}function Ia(e,t,r){if(e!==void 0){if(!H(e)){r.push({path:t,message:"富文本样式应为对象"});return}for(const n of["fontFamily","color","backgroundColor","lineColor","borderColor"])e[n]!==void 0&&typeof e[n]!="string"&&r.push({path:`${t}.${n}`,message:"富文本样式应为字符串"});for(const n of["bold","italic","underline","borderTop","borderRight","borderBottom","borderLeft"])e[n]!==void 0&&typeof e[n]!="boolean"&&r.push({path:`${t}.${n}`,message:"富文本样式应为布尔值"});Ht(e,["fontSize","fontSizePx","lineWidthPt","lineHeight","opacity"],t,r),Ht(e,["letterSpacing","rotateDeg"],t,r,-1/0),typeof e.opacity=="number"&&e.opacity>1&&r.push({path:`${t}.opacity`,message:"透明度不能大于1"}),it(e.align,["left","center","right","justify"],`${t}.align`,r),it(e.verticalAlign,["top","middle","bottom"],`${t}.verticalAlign`,r)}}function Oa(e,t,r){if(!H(e)){r.push({path:t,message:"富文本片段应为对象"});return}it(e.kind,["text","field"],`${t}.kind`,r);for(const n of["text","field"])e[n]!==void 0&&typeof e[n]!="string"&&r.push({path:`${t}.${n}`,message:"富文本内容应为字符串"});Ia(e.style,`${t}.style`,r)}function eo(e,t,r){if(e!==void 0){if(!Array.isArray(e)){r.push({path:`${t}.richParagraphs`,message:"richParagraphs 应为数组"});return}e.forEach((n,o)=>{const i=`${t}.richParagraphs.${o}`;if(!H(n)||!Array.isArray(n.segments)){r.push({path:i,message:"段落缺少 segments 数组"});return}it(n.align,["left","center","right","justify"],`${i}.align`,r),Ht(n,["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"],i,r),n.segments.forEach((s,a)=>Oa(s,`${i}.segments.${a}`,r))})}}function to(e,t,r,n=[]){const o=Mr([e],t);if(o){r.push(o);return}Sr(e,t,r,n)}function Sr(e,t,r,n=[]){if(!H(e)){r.push({path:t,message:"组件应为对象"});return}const o=e.kind;typeof o!="string"?r.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):Ea.has(o)||n.push({path:`${t}.kind`,message:`未知组件类型 ${ot(o)},将以兜底方式渲染`});for(const i of["leftMm","topMm","widthMm","heightMm"])Pa(e,i,t,r);typeof e.leftMm=="number"&&e.leftMm<-100&&r.push({path:`${t}.leftMm`,message:"几何数值异常(leftMm<-100)"});for(const i of["widthMm","heightMm"])typeof e[i]=="number"&&e[i]<0&&r.push({path:`${t}.${i}`,message:"组件尺寸不能为负数"});Fa(e.table,t,r),Ra(e.code,o,t,r),e.pageAnchor!==void 0&&!["header","footer"].includes(e.pageAnchor)&&r.push({path:`${t}.pageAnchor`,message:"页面锚点应为 header 或 footer"}),e.lineDirection!==void 0&&!["down","up"].includes(e.lineDirection)&&r.push({path:`${t}.lineDirection`,message:"线段方向应为 down 或 up"}),Na(e.grid,t,r,n),eo(e.richParagraphs,t,r)}function Ra(e,t,r,n){if(e!==void 0)for(const o of ka(e,t))n.push({path:`${r}.code${o.path?`.${o.path}`:""}`,message:o.message})}function ro(e,t,r){if(!H(e))return;e.binding!==void 0&&r.push({path:`${t}.binding`,message:"渲染计划不允许未解析字段绑定"});const n=e.grid;!H(n)||!Array.isArray(n.cells)||n.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((s,a)=>{!H(s)||!Array.isArray(s.children)||s.children.forEach((c,u)=>ro(c,`${t}.grid.cells.${i}.${a}.children.${u}`,r))})})}function Ta(e,t,r,n=[]){if(!H(e)){r.push({path:t,message:"页应为对象"});return}const o=e.pageWidthMm,i=e.pageHeightMm;(typeof o!="number"||!Number.isFinite(o)||o<=0)&&r.push({path:`${t}.pageWidthMm`,message:`页宽非法: ${ot(o)}`}),(typeof i!="number"||!(i>0&&i<5e3))&&r.push({path:`${t}.pageHeightMm`,message:`页高非法: ${ot(i)}`}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${t}.layout`,message:"布局应为 page 或 wide"});const s=e.components;if(!Array.isArray(s))r.push({path:`${t}.components`,message:"components 应为数组"});else if(Array.isArray(s)){const a=Mr(s,`${t}.components`);if(a){r.push(a);return}s.forEach((c,u)=>{Sr(c,`${t}.components.${u}`,r,n),ro(c,`${t}.components.${u}`,r)})}}function Be(e){const t=[],r=[],n=H(e)?e.pages:void 0;if(H(e)&&e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean"&&t.push({path:"$.requiresRecalculation",message:"重算能力要求应为布尔值"}),!Array.isArray(n))t.push({path:"$.pages",message:e==null?"渲染计划为空":"渲染计划缺少 pages 数组"});else{const o=Xn(n);if(o)return{ok:!1,errors:[...t,o],warnings:r};n.forEach((s,a)=>Ta(s,`$.pages.${a}`,t,r)),n.length>2e3&&r.push({path:"$.pages",message:`页数异常大(${n.length} 页),渲染与打印耗时可能显著增加`});const i=n.reduce((s,a)=>s+(H(a)&&Array.isArray(a.components)?a.components.length:0),0);i>5e4&&r.push({path:"$.pages",message:`组件总数异常大(${i} 个),可能触发浏览器性能限制`})}return{ok:t.length===0,errors:t,warnings:r}}function ja(e){const t=[];return e.optionsSource!==void 0&&((e.type!=="select"||typeof e.optionsSource!="string"||!/^[\w][\w.:-]{0,127}$/.test(e.optionsSource))&&t.push("远程选项来源应为 select 的有效来源键(最多 128 字符)"),e.options!==void 0&&t.push("远程选项来源与静态选项不能同时配置")),e.dependsOn!==void 0&&(!e.optionsSource||!Array.isArray(e.dependsOn)||e.dependsOn.length>32||e.dependsOn.some(r=>typeof r!="string"||!r)||new Set(e.dependsOn).size!==e.dependsOn.length)&&t.push("联动依赖应为远程选项的最多 32 个唯一参数名"),t}function Ca(e){const t=new Map(e.map((o,i)=>[o.field,{def:o,index:i,degree:0,children:[]}])),r=[];for(const o of t.values())for(const i of o.def.dependsOn??[]){const s=t.get(i);if(!s){r.push({index:o.index,message:`联动依赖参数 ${i} 未声明`});continue}o.degree++,s.children.push(o.def.field)}const n=[...t.values()].filter(o=>o.degree===0);for(let o=0;o<n.length;o++)for(const i of n[o].children){const s=t.get(i);--s.degree===0&&n.push(s)}for(const o of t.values())o.degree>0&&r.push({index:o.index,message:"联动依赖不能形成循环"});return r}function st(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e)||e.startsWith("0000-"))return!1;const t=new Date(`${e}T00:00:00.000Z`);return Number.isFinite(t.getTime())&&t.toISOString().slice(0,10)===e}function Ar(e){return e.length===4&&/^\d{4}$/.test(e)&&e!=="0000"}function no(e){return e.length===7&&/^\d{4}-(?:0[1-9]|1[0-2])$/.test(e)&&Ar(e.slice(0,4))}function oo(e){const[t,r,n]=e.split("/");if(!(n!==void 0||!t||!r||!st(t)||!st(r)||t>r))return{start:t,end:r}}function io(e,t){return typeof t!="string"?!1:e==="month"?no(t):e==="year"?Ar(t):(e==="date"||e==="dateRange")&&st(t)}function La(e,t){if(e==="date"&&!st(t))return"应为有效的 YYYY-MM-DD 日期";if(e==="month"&&!no(t))return"应为有效的 YYYY-MM 月份";if(e==="year"&&!Ar(t))return"应为 0001 至 9999 的四位年份";if(e==="dateRange"&&!oo(t))return"应为完整且有序的 YYYY-MM-DD/YYYY-MM-DD 日期范围"}class vt extends Error{constructor(t){super(t.map(r=>`${r.field}: ${r.message}`).join("; ")),this.issues=t,this.code="params",this.name="ReportParamValidationError"}}function so(e){return/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))}function ao(e,t){if(e.type==="number"&&!so(t))return[["type","应为有限数字"]];const r=La(e.type,t);if(r)return[["type",r]];const n=[];e.type==="select"&&e.options&&!e.options.some(i=>i.value===t)&&n.push(["option","不在允许的选项中"]);const o=Array.from(t).length;return e.minLength!==void 0&&o<e.minLength&&n.push(["minLength",`至少 ${e.minLength} 个字符`]),e.maxLength!==void 0&&o>e.maxLength&&n.push(["maxLength",`最多 ${e.maxLength} 个字符`]),n.push(...Da(e,t)),n}function Da(e,t){const r=e.type==="dateRange"?oo(t):void 0,n=r?.start??(e.type==="number"?Number(t):t),o=r?.end??n,i=[];return e.min!==void 0&&n<e.min&&i.push(["minimum",`不能小于 ${e.min}`]),e.max!==void 0&&o>e.max&&i.push(["maximum",`不能大于 ${e.max}`]),i}function Ba(e){const t=[];for(const o of["min","max"]){const i=e[o];if(i===void 0)continue;io(e.type,i)||e.type==="number"&&typeof i=="number"&&Number.isFinite(i)||t.push(`${o} 应为数字的有限边界或日期/月/年的规范字符串边界`)}const r=typeof e.min=="number"&&typeof e.max=="number"&&e.min>e.max,n=typeof e.min=="string"&&typeof e.max=="string"&&e.min>e.max;return(r||n)&&t.push("最小边界不能大于最大边界"),[...t,..._a(e)]}function _a(e){const t=[];e.type==="number"&&(e.minLength!==void 0||e.maxLength!==void 0)&&t.push("number 参数使用 min/max 而不是文本长度约束");for(const r of["minLength","maxLength"]){const n=e[r];n!==void 0&&(!Number.isSafeInteger(n)||n<0)&&t.push(`${r} 应为非负整数`)}return typeof e.minLength=="number"&&typeof e.maxLength=="number"&&e.minLength>e.maxLength&&t.push("最小长度不能大于最大长度"),t}function Mt(e){if(!Array.isArray(e))return[{code:"definition",field:"",path:"$.paramDefs",message:"参数定义应为数组"}];const t=new Set,r=e.flatMap((n,o)=>{const i=n&&typeof n.field=="string"?n.field:"";return Ha(n,t).map(a=>({code:"definition",field:i,path:`$.paramDefs.${o}`,message:a}))});return r.length?r:Ca(e).map(({index:n,message:o})=>({code:"definition",field:e[n].field,path:`$.paramDefs.${n}`,message:o}))}function Wa(e){return Array.isArray(e)&&e.every(t=>!!t&&typeof t=="object"&&typeof t.value=="string"&&typeof t.label=="string")}function Ka(e){const t=[];return e.type!==void 0&&!["text","number","date","month","year","dateRange","select"].includes(e.type)&&t.push("未知参数类型"),e.label!==void 0&&typeof e.label!="string"&&t.push("参数标签应为字符串"),e.placeholder!==void 0&&typeof e.placeholder!="string"&&t.push("提示文字应为字符串"),e.required!==void 0&&typeof e.required!="boolean"&&t.push("required 应为布尔值"),e.defaultValue!==void 0&&typeof e.defaultValue!="string"&&t.push("默认值应为字符串"),e.options!==void 0&&!Wa(e.options)&&t.push("选项应为包含字符串 label/value 的数组"),[...t,...ja(e)]}function Ha(e,t){if(!e||typeof e!="object"||Array.isArray(e))return["参数定义项应为对象"];const r=Ka(e);return typeof e.field!="string"||!e.field.trim()||t.has(e.field)?r.push("参数名应为非空且不重复的字符串"):t.add(e.field),r.length||(r.push(...Ba(e)),r.length)||(e.options&&new Set(e.options.map(n=>n.value)).size!==e.options.length&&r.push("选项值不能重复"),e.defaultValue!==void 0&&(e.required&&!e.defaultValue.trim()?r.push("必填参数的默认值不能为空"):e.defaultValue.trim()&&r.push(...ao(e,e.defaultValue).map(([,n])=>`默认值${n}`)))),r}function Ja(e,t,r){for(const[n,o]of Object.entries(e))(typeof o=="string"||typeof o=="number"&&Number.isFinite(o))&&(Object.defineProperty(t,n,{value:String(o),writable:!0,enumerable:!0,configurable:!0}),Object.defineProperty(r,n,{value:o,writable:!0,enumerable:!0,configurable:!0}))}function Jt(e){return e==null||typeof e=="string"&&!e.trim()}function zt(e,t={}){const r=Object.create(null),n=Object.create(null),o=Mt(e);if((!t||typeof t!="object"||Array.isArray(t))&&o.push({code:"type",field:"",path:"$.params",message:"参数应为对象"}),o.length)return{ok:!1,values:r,typedValues:n,issues:o};Ja(t,r,n);for(const i of e){const s=Object.prototype.hasOwnProperty.call(t,i.field)&&t[i.field]!==void 0?t[i.field]:i.defaultValue,a=(f,d)=>o.push({code:f,path:`$.params.${i.field}`,field:i.field,message:d});if(Jt(s)){i.required&&a("required","此参数为必填项"),typeof s=="string"&&(r[i.field]=s),delete n[i.field];continue}if(typeof s!="string"&&!(typeof s=="number"&&Number.isFinite(s))){a("type","参数应为字符串或有限数字");continue}const c=String(s);r[i.field]=c,ao(i,c).forEach(([f,d])=>a(f,d)),n[i.field]=i.type==="number"&&so(c)?Number(c):c}return o.push(...za(e,r)),{ok:o.length===0,values:r,typedValues:n,issues:o}}function za(e,t){return e.flatMap(r=>!Jt(t[r.field])&&r.dependsOn?.some(n=>Jt(t[n]))?[{code:"dependency",path:`$.params.${r.field}`,field:r.field,message:"请先填写联动依赖的上级参数"}]:[])}function Yr(e,t={}){const r=zt(e,t);if(!r.ok)throw new vt(r.issues);return r.values}function Va(e){const t={},r="(?![\\s\\S])";return e.type==="date"&&(t.format="date"),e.type==="month"&&(t.pattern=`^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])${r}`),e.type==="year"&&(t.pattern=`^(?!0000)[0-9]{4}${r}`),e.type==="dateRange"&&(t.pattern=`^[0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9]{4}-[0-9]{2}-[0-9]{2}${r}`),e.type==="dateRange"&&(t["x-report-date-range"]={separator:"/",ordered:!0,calendarDates:!0}),t}function Ua(e){const t={type:e.type==="number"?"number":"string",title:e.label??e.field,...Va(e)};return e.required&&e.type!=="number"&&!t.pattern&&(t.pattern="\\S"),e.type==="select"&&e.options&&(t.enum=e.options.map(r=>r.value)),Object.assign(t,Ga(e)),e.defaultValue!==void 0&&(e.type!=="number"||e.defaultValue.trim())&&(t.default=e.type==="number"?Number(e.defaultValue):e.defaultValue),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),typeof e.min=="number"&&(t.minimum=e.min),typeof e.max=="number"&&(t.maximum=e.max),typeof e.min=="string"&&(t["x-report-minimum"]=e.min),typeof e.max=="string"&&(t["x-report-maximum"]=e.max),t}function Ga(e){return{...e.optionsSource?{"x-report-options-source":e.optionsSource}:{},...e.dependsOn?.length?{"x-report-depends-on":[...e.dependsOn]}:{}}}function qa(e){const t=Mt(e);if(t.length)throw new vt(t);return{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:Object.fromEntries(e.map(r=>[r.field,Ua(r)])),required:e.filter(r=>r.required).map(r=>r.field),additionalProperties:!0}}function at(e,t){const r=new Set;return t.flatMap(n=>{const o=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0,i=o?.params??(typeof o?.template=="function"?[]:o?.template.params)??[],s=Mt(i);if(s.length)throw new vt(s);return i.filter(a=>r.has(a.field)?!1:(r.add(a.field),!0))})}function co(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Vt(e,t,r){if(e!==void 0){if(!co(e)){r.push({path:t,message:"条件应为对象"});return}(typeof e.field!="string"||!e.field.trim())&&r.push({path:`${t}.field`,message:"条件需要字段"}),e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal"&&r.push({path:`${t}.numeric`,message:"未知条件数值模式"}),[">",">=","<","<=","==","!="].includes(e.op)||r.push({path:`${t}.op`,message:"未知条件运算符"}),typeof e.value!="string"&&!(typeof e.value=="number"&&Number.isFinite(e.value))&&r.push({path:`${t}.value`,message:"条件值应为字符串或有限数字"})}}function uo(e,t,r){if(e===void 0)return;if(!Array.isArray(e)||e.length>2048){r.push({path:t,message:"聚合应为数组且最多 2048 项"});return}const n=new Set;e.forEach((o,i)=>{const s=`${t}.${i}`;if(!co(o)){r.push({path:s,message:"聚合应为对象"});return}const a=o.field;typeof a!="string"||!a.trim()||n.has(a)?r.push({path:`${s}.field`,message:"聚合输出字段应非空且唯一"}):n.add(a),o.numeric!==void 0&&o.numeric!=="number"&&o.numeric!=="decimal"&&r.push({path:`${s}.numeric`,message:"数值模式应为 number 或 decimal"}),o.digits!==void 0&&(!Number.isInteger(o.digits)||Number(o.digits)<0||Number(o.digits)>100)&&r.push({path:`${s}.digits`,message:"小数位应为 0–100 的整数"});try{de({...o,field:o.valueField??a})}catch(c){r.push({path:s,message:c instanceof Error?c.message:String(c)})}})}function Ya(e,t,r){if(e===void 0)return;const n=Ki(e);for(const o of n.errors)r.push({path:t,message:o})}function Xa(e,t,r){if(e!==void 0)try{mr(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function Za(e,t,r){if(e.tree===void 0)return;const n=`${t}.tree`;try{Nn(e.tree);const o=e.tree;if(e.matrix||e.detail||e.groupBy||Array.isArray(e.groups)&&e.groups.length||e.rowVisibleWhen)throw new Error("树形布局不能同时配置普通分组、矩阵、主从或行可见条件");if(e.rowKey!==void 0&&e.rowKey!==o.idField)throw new Error("树形 rowKey 应与 idField 一致");if(!Array.isArray(e.columns)||!e.columns.some(i=>i&&i.field===o.labelField&&!i.hidden))throw new Error("树形布局需要可见的标签列");Array.isArray(e.computed)&&pr(o,e.computed)}catch(o){r.push({path:n,message:o instanceof Error?o.message:String(o)})}}class Qa extends Error{constructor(t){super(`模板校验失败:${t.slice(0,3).map(r=>`${r.path}: ${r.message}`).join("; ")}`),this.errors=t,this.name="ReportTemplateError"}}const ec=new Set(["__proto__","prototype","constructor"]),tc=new Set(["left","center","right","justify"]),Ge=2e5,rc=64,nc=1e7;function O(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function oc(e,t,r){const n=Object.getPrototypeOf(e),o=Array.isArray(e);if(o?n!==Array.prototype:n!==Object.prototype&&n!==null)return r.push({path:t,message:"模板对象必须使用普通 JSON 对象原型"}),!1;if(o){const i=Object.keys(e);if(i.length!==e.length||i.some(s=>!/^(0|[1-9]\d*)$/.test(s)||Number(s)>=e.length))return r.push({path:t,message:"模板数组不能包含空位或额外属性"}),!1}return Object.getOwnPropertySymbols(e).length>0?(r.push({path:t,message:"模板不能包含 Symbol 键"}),!1):!0}function ic(e,t,r,n){return ec.has(e)?(n.push({path:r,message:"模板不能包含可能污染原型的键"}),!1):t.get||t.set||!t.enumerable?(n.push({path:r,message:"模板不能包含访问器或不可枚举字段"}),!1):!0}function sc(e){return e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)}function ac(e,t){const r=new Set;let n=0,o=0,i=!1;const s=(a,c,u)=>{if(!i){if(++n>Ge){n===Ge+1&&t.push({path:c,message:"模板超过 JSON 节点安全上限"});return}if(u>rc){t.push({path:c,message:"模板嵌套层级过深"});return}if(typeof a=="string"){o+=a.length,o>nc&&(i=!0,t.push({path:c,message:"模板文本超过 1000 万字符的安全上限"}));return}if(!sc(a)){if(!a||typeof a!="object"){t.push({path:c,message:"模板只允许 JSON 值,不允许函数、undefined 或非有限数字"});return}if(r.has(a)){t.push({path:c,message:"模板不能包含循环引用"});return}if(oc(a,c,t)){r.add(a);for(const[f,d]of Object.entries(Object.getOwnPropertyDescriptors(a))){if(Array.isArray(a)&&f==="length")continue;const l=`${c}.${f}`;if(ic(f,d,l,t)&&s(d.value,l,u+1),n>Ge||i)break}r.delete(a)}}}};s(e,"$",0)}function D(e,t,r,n,o=!1){const i=e[t];i===void 0&&!o||(typeof i!="string"||o&&!i.trim())&&n.push({path:`${r}.${t}`,message:o?"应为非空字符串":"应为字符串"})}function W(e,t,r,n,o=0,i=!1){const s=e[t];s===void 0&&!i||(typeof s!="number"||!Number.isFinite(s)||s<o)&&n.push({path:`${r}.${t}`,message:`应为大于等于 ${o} 的有限数字`})}function re(e,t,r,n){e[t]!==void 0&&typeof e[t]!="boolean"&&n.push({path:`${r}.${t}`,message:"应为布尔值"})}function $e(e,t,r,n=!1){e!==void 0&&!tc.has(e)&&!(n&&e==="auto")&&r.push({path:t,message:`未知对齐方式${n?"(支持 auto)":""}`})}function Q(e,t,r){if(e!==void 0){if(!O(e)){r.push({path:t,message:"样式应为对象"});return}$e(e.align,`${t}.align`,r),e.verticalAlign!==void 0&&!["top","middle","bottom"].includes(e.verticalAlign)&&r.push({path:`${t}.verticalAlign`,message:"未知垂直对齐方式"});for(const n of["fontSize","fontSizePx","lineWidthPt","lineHeight"])W(e,n,t,r);for(const n of["letterSpacing","rotateDeg"])W(e,n,t,r,-1/0);W(e,"opacity",t,r),typeof e.opacity=="number"&&e.opacity>1&&r.push({path:`${t}.opacity`,message:"透明度不能大于 1"});for(const n of["bold","italic","underline","borderTop","borderRight","borderBottom","borderLeft"])re(e,n,t,r);for(const n of["fontFamily","color","backgroundColor","lineColor","borderColor"])D(e,n,t,r)}}function cc(e,t,r){if(e===void 0)return;if(!Array.isArray(e)){r.push({path:t,message:"参数定义应为数组"});return}const n=new Set,o=r.length;e.forEach((i,s)=>{const a=`${t}.${s}`;if(!O(i)){r.push({path:a,message:"参数定义应为对象"});return}D(i,"field",a,r,!0),typeof i.field=="string"&&(n.has(i.field)&&r.push({path:`${a}.field`,message:"参数名重复"}),n.add(i.field)),i.type!==void 0&&!["text","number","date","month","year","dateRange","select"].includes(i.type)&&r.push({path:`${a}.type`,message:"未知参数类型"});for(const c of["label","defaultValue","placeholder"])D(i,c,a,r);re(i,"required",a,r);for(const c of["minLength","maxLength"]){const u=i[c];u!==void 0&&(typeof u!="number"||!Number.isSafeInteger(u)||u<0)&&r.push({path:`${a}.${c}`,message:"长度边界应为非负整数"})}uc(i,a,r),i.options!==void 0&&(Array.isArray(i.options)?i.options.forEach((c,u)=>{const f=`${a}.options.${u}`;if(!O(c))r.push({path:f,message:"选项应为对象"});else for(const d of["label","value"])typeof c[d]!="string"&&r.push({path:`${f}.${d}`,message:"选项标签与值应为字符串(允许空白选项)"})}):r.push({path:`${a}.options`,message:"选项应为数组"}))}),r.length===o&&r.push(...Mt(e).map(i=>({path:i.path.replace("$.paramDefs",t),message:i.message})))}function uc(e,t,r){for(const i of["min","max"]){const s=e[i];if(s===void 0)continue;io(e.type,s)||e.type==="number"&&typeof s=="number"&&Number.isFinite(s)||r.push({path:`${t}.${i}`,message:"数字使用有限数字边界,日期/月/年使用对应规范字符串边界"})}const n=typeof e.min=="number"&&typeof e.max=="number"&&e.min>e.max,o=typeof e.min=="string"&&typeof e.max=="string"&&e.min>e.max;(n||o)&&r.push({path:t,message:"最小边界不能大于最大边界"}),typeof e.minLength=="number"&&typeof e.maxLength=="number"&&e.minLength>e.maxLength&&r.push({path:t,message:"最小长度不能大于最大长度"})}function fo(e,t,r){if(!Array.isArray(e)||e.length===0){r.push({path:t,message:"列表至少需要一列"});return}e.every(n=>O(n)&&n.hidden===!0)&&r.push({path:t,message:"列表至少需要一列可见列"}),e.forEach((n,o)=>{const i=`${t}.${o}`;if(!O(n)){r.push({path:i,message:"列应为对象"});return}if(Zn(n,i,r),re(n,"hidden",i,r),Vt(n.visibleWhen,`${i}.visibleWhen`,r),typeof n.header!="string"&&r.push({path:`${i}.header`,message:"表头应为字符串(允许空白表头)"}),D(n,"field",i,r,!0),W(n,"widthMm",i,r,Number.MIN_VALUE,!0),Q(n.style,`${i}.style`,r),Q(n.headerStyle,`${i}.headerStyle`,r),$e(n.align,`${i}.align`,r,!0),$e(n.headerAlign,`${i}.headerAlign`,r),n.semanticRole!==void 0&&!["identifier","dimension","measure","date","text"].includes(n.semanticRole)&&r.push({path:`${i}.semanticRole`,message:"未知列语义"}),n.format!==void 0)if(!O(n.format)||!["number","percent","date"].includes(n.format.kind))r.push({path:`${i}.format`,message:"未知列格式"});else{const s=n.format.digits;s!==void 0&&(typeof s!="number"||!Number.isInteger(s)||s<0||s>100)&&r.push({path:`${i}.format.digits`,message:"小数位应为 0–100 的整数"}),re(n.format,"thousands",`${i}.format`,r),D(n.format,"pattern",`${i}.format`,r)}n.rules!==void 0&&(Array.isArray(n.rules)?n.rules.forEach((s,a)=>{const c=`${i}.rules.${a}`;if(!O(s)||!O(s.when)){r.push({path:c,message:"条件格式缺少 when 对象"});return}Vt(s.when,`${c}.when`,r),D(s.when,"field",`${c}.when`,r,!0),[">",">=","<","<=","==","!="].includes(s.when.op)||r.push({path:`${c}.when.op`,message:"未知条件运算符"}),typeof s.when.value!="number"&&typeof s.when.value!="string"&&r.push({path:`${c}.when.value`,message:"条件值应为数字或字符串"}),Q(s.style,`${c}.style`,r)}):r.push({path:`${i}.rules`,message:"条件格式应为数组"}))})}function lo(e,t,r){if(e!==void 0){if(!O(e)){r.push({path:t,message:"分组应为对象"});return}D(e,"field",t,r,!0);for(const n of["headerTemplate","subtotalLabel"])D(e,n,t,r);for(const n of["headerStyle","subtotalStyle"])Q(e[n],`${t}.${n}`,r);re(e,"keepWithNext",t,r),re(e,"repeatHeader",t,r),uo(e.aggregates,`${t}.aggregates`,r),e.subtotal!==void 0&&(!Array.isArray(e.subtotal)||e.subtotal.some(n=>typeof n!="string"))&&r.push({path:`${t}.subtotal`,message:"小计字段应为字符串数组"})}}function fc(e,t,r){if(!(e===void 0||typeof e=="boolean")){if(!O(e)){r.push({path:t,message:"合计应为布尔值或对象"});return}D(e,"label",t,r),uo(e.aggregates,`${t}.aggregates`,r),Q(e.style,`${t}.style`,r),e.fields!==void 0&&(!Array.isArray(e.fields)||e.fields.some(n=>typeof n!="string"))&&r.push({path:`${t}.fields`,message:"合计字段应为字符串数组"})}}function lc(e,t,r,n){const o={kind:"rect",leftMm:0,topMm:0,widthMm:1,heightMm:1,grid:e};if(to(o,r,n,[]),kr(o,r,n),!O(e)||!Array.isArray(e.cells))return;const i=e.cells,s=Array.isArray(t)?t.length:0;if(i.length*s>Ge){n.push({path:r,message:"表头逻辑网格超过 20 万格安全上限"});return}e.cells.length||n.push({path:`${r}.cells`,message:"表头至少需要一行"}),Array.isArray(e.colWidthsMm)&&e.colWidthsMm.length!==s&&n.push({path:`${r}.colWidthsMm`,message:"表头列宽数量应与列表列数一致"}),Array.isArray(e.rowHeightsMm)&&e.rowHeightsMm.length!==e.cells.length&&n.push({path:`${r}.rowHeightsMm`,message:"表头行高数量应与行数一致"}),dc(i,s,r,n)}function dc(e,t,r,n){const o=new Set;e.forEach((i,s)=>{if(!Array.isArray(i))return;let a=0;i.forEach((c,u)=>{for(;o.has(`${s}:${a}`);)a++;const f=O(c)&&typeof c.colSpan=="number"?c.colSpan:1,d=O(c)&&typeof c.rowSpan=="number"?c.rowSpan:1;(a+f>t||s+d>e.length)&&n.push({path:`${r}.cells.${s}.${u}`,message:"表头合并区域超出表头边界"});for(let l=s;l<Math.min(e.length,s+d);l++)for(let m=a;m<Math.min(t,a+f);m++)o.has(`${l}:${m}`)&&n.push({path:`${r}.cells.${s}.${u}`,message:"表头合并区域重叠"}),o.add(`${l}:${m}`);a+=f})})}function mc(e,t,r){if(Za(e,t,r),Ya(e.computed,`${t}.computed`,r),Xa(e.matrix,`${t}.matrix`,r),e.matrix&&(e.detail||e.groupBy||Array.isArray(e.groups)&&e.groups.length||e.grandTotal)&&r.push({path:`${t}.matrix`,message:"矩阵请使用自身 totals 汇总,不能同时配置普通分组、总计或主从明细"}),Vt(e.rowVisibleWhen,`${t}.rowVisibleWhen`,r),e.groups!==void 0&&(!Array.isArray(e.groups)||e.groups.length>16?r.push({path:`${t}.groups`,message:"分组应为数组,最多 16 级"}):e.groups.forEach((i,s)=>lo(i,`${t}.groups.${s}`,r))),e.detail===void 0)return;const n=e.detail,o=`${t}.detail`;if(!O(n)){r.push({path:o,message:"主从关联应为对象"});return}for(const i of["dataset","parentKey","foreignKey"])D(n,i,o,r,!0);for(const i of["rowKey","revisionField","sourceTokenField"])D(n,i,o,r,n[i]!==void 0);D(n,"label",o,r),re(n,"header",o,r),W(n,"rowHeightMm",o,r,Number.MIN_VALUE),fo(n.columns,`${o}.columns`,r),n.unmatched!==void 0&&n.unmatched!=="error"&&n.unmatched!=="ignore"&&r.push({path:`${o}.unmatched`,message:"未关联明细策略应为 error 或 ignore"})}function gc(e,t,r){for(const n of["leftMm","topMm"])W(e,n,t,r,-1/0,!0);W(e,"widthMm",t,r,Number.MIN_VALUE,!0),D(e,"dataset",t,r,!0),D(e,"title",t,r);for(const n of["rowKey","revisionField","sourceTokenField"])D(e,n,t,r,e[n]!==void 0);e.headerGrid!==void 0&&lc(e.headerGrid,e.columns,`${t}.headerGrid`,r),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${t}.layout`,message:"布局应为 page 或 wide"}),fo(e.columns,`${t}.columns`,r);for(const n of["fontSizePt","rowHeightMm"])W(e,n,t,r,Number.MIN_VALUE);W(e,"paddingMm",t,r);for(const n of["header","headerBold","headerEveryPage","border"])re(e,n,t,r);e.cardinality!==void 0&&e.cardinality!=="record"&&r.push({path:`${t}.cardinality`,message:"单记录区域类型应为 record"}),D(e,"headerBackgroundColor",t,r),$e(e.align,`${t}.align`,r,!0),$e(e.headerAlign,`${t}.headerAlign`,r),Q(e.headerStyle,`${t}.headerStyle`,r),mc(e,t,r),lo(e.groupBy,`${t}.groupBy`,r),fc(e.grandTotal,`${t}.grandTotal`,r)}function Xr(e,t,r){Array.isArray(e.richParagraphs)&&e.richParagraphs.forEach((n,o)=>{if(!O(n))return;const i=`${t}.richParagraphs.${o}`;$e(n.align,`${i}.align`,r);for(const s of["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"])W(n,s,i,r);Array.isArray(n.segments)&&n.segments.forEach((s,a)=>{const c=`${i}.segments.${a}`;if(!O(s)){r.push({path:c,message:"富文本片段应为对象"});return}s.kind!==void 0&&s.kind!=="text"&&s.kind!=="field"&&r.push({path:`${c}.kind`,message:"未知富文本片段类型"});for(const u of["text","field"])D(s,u,c,r);Q(s.style,`${c}.style`,r)})})}function kr(e,t,r){Q(e.style,`${t}.style`,r);for(const o of["text","rawText","imageData","fallbackText","nid","rkey"])D(e,o,t,r);if(e.lines!==void 0&&(!Array.isArray(e.lines)||e.lines.some(o=>typeof o!="string"))&&r.push({path:`${t}.lines`,message:"文本行应为字符串数组"}),Xr(e,t,r),!O(e.grid))return;const n=e.grid;W(n,"gapMm",`${t}.grid`,r),W(n,"paddingMm",`${t}.grid`,r);for(const o of["colWidthsMm","rowHeightsMm"]){const i=n[o];i!==void 0&&(!Array.isArray(i)||i.some(s=>typeof s!="number"||!Number.isFinite(s)||s<0))&&r.push({path:`${t}.grid.${o}`,message:"网格尺寸应为有限非负数字数组"})}Array.isArray(n.cells)&&n.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((s,a)=>{const c=`${t}.grid.cells.${i}.${a}`;if(s!==null){if(!O(s)){r.push({path:c,message:"网格单元格应为对象或 null"});return}for(const u of["text","rawText","numberFormat"])D(s,u,c,r);for(const u of["colSpan","rowSpan"]){const f=s[u];f!==void 0&&(typeof f!="number"||!Number.isInteger(f)||f<=0)&&r.push({path:`${c}.${u}`,message:"跨度应为正整数"})}s.value!==void 0&&s.value!==null&&!["string","number","boolean"].includes(typeof s.value)&&r.push({path:`${c}.value`,message:"Excel 原始值应为字符串、数字、布尔值或 null"}),Q(s.style,`${c}.style`,r),Xr(s,c,r),s.children!==void 0&&(Array.isArray(s.children)?s.children.forEach((u,f)=>{O(u)&&kr(u,`${c}.children.${f}`,r)}):r.push({path:`${c}.children`,message:"嵌套组件应为数组"}))}})})}function hc(e,t,r){if(!(e.flow===void 0||!Array.isArray(e.components)))try{Tn(e.components,e.flow)}catch(n){r.push({path:`${t}.flow`,message:n instanceof Error?n.message:String(n)})}}function pc(e){const t=[],r=[];return ac(e,t),t.length?{ok:!1,errors:t,warnings:r}:(O(e)?(e.schemaVersion!==void 0&&e.schemaVersion!==ve&&t.push({path:"$.schemaVersion",message:"不支持的模板 schemaVersion"}),cc(e.params,"$.params",t),Cn(e,t),!Array.isArray(e.pages)||e.pages.length===0?t.push({path:"$.pages",message:"模板至少需要一页"}):e.pages.forEach((n,o)=>{const i=`$.pages.${o}`;if(!O(n)){t.push({path:i,message:"页应为对象"});return}W(n,"widthMm",i,t,Number.MIN_VALUE,!0),W(n,"heightMm",i,t,Number.MIN_VALUE,!0),n.layout!==void 0&&n.layout!=="page"&&n.layout!=="wide"&&t.push({path:`${i}.layout`,message:"布局应为 page 或 wide"}),typeof n.heightMm=="number"&&n.heightMm>=5e3&&t.push({path:`${i}.heightMm`,message:"页高应小于 5000mm"});for(const s of["marginTopMm","marginBottomMm","marginLeftMm","marginRightMm"])W(n,s,i,t);typeof n.widthMm=="number"&&Number(n.marginLeftMm??0)+Number(n.marginRightMm??0)>=n.widthMm&&t.push({path:i,message:"横向页边距占满页面"}),typeof n.heightMm=="number"&&Number(n.marginTopMm??0)+Number(n.marginBottomMm??0)>=n.heightMm&&t.push({path:i,message:"纵向页边距占满页面"}),Array.isArray(n.components)?n.components.forEach((s,a)=>{const c=`${i}.components.${a}`;O(s)&&s.kind==="list"?gc(s,c,t):(to(s,c,t,r),O(s)&&kr(s,c,t))}):t.push({path:`${i}.components`,message:"组件应为数组"}),hc(n,i,t)})):t.push({path:"$",message:"模板应为对象"}),{ok:t.length===0,errors:t,warnings:r})}function yc(e){return!e||typeof e!="object"?!1:[e.pageIndex,e.componentIndex,e.rowIndex,e.columnIndex].every(t=>Number.isInteger(t)&&t>=0)}function wc(e){return e.value!==void 0?e.value:e.rawText??e.text??null}function bc(e,t){return e.valueType?e.valueType:typeof t=="number"?"number":typeof t=="boolean"?"boolean":t===null&&e.numberFormat&&/[0#?]/.test(e.numberFormat)?"number":"text"}function xc(e,t){if(e.derived)return"derived";if(e.editable===!1)return"cell";if(e.formula!==void 0)return"formula";if(e.children?.length||e.richParagraphs?.length)return"complex";if(t.table&&t.table.role!=="body"&&e.editable!==!0)return"structure"}function $c(e,t){const r=e.table;if(r)return{id:r.id,rowIndex:r.rowIndex+t.rowIndex,role:r.role,columnKey:r.columnKeys[t.columnIndex]}}function vc(e,t,r){if(e.derived)return;if(e.source)return{...e.source};const n=t.table?.source,o=t.table?.columnKeys[r.columnIndex];if(!(!n||n.rowKey===void 0||o===void 0))return{...n,rowKey:n.rowKey,field:o}}function Mc(e,t,r){const n=wc(r),o=xc(r,e);return{address:{...t},cell:r,component:e,value:n,valueType:bc(r,n),table:$c(e,t),source:vc(r,e,t),editable:o===void 0,readOnlyReason:o}}function mo(e){const t=new Map;return r=>{if(!yc(r))return null;const n=e.pages[r.pageIndex]?.components[r.componentIndex];if(!n?.grid)return null;let o=t.get(n);if(!o){const s=new Map;o=new Map;for(const a of vn(n.grid,n.widthMm,n.heightMm).cells){const c=s.get(a.ri)??0;s.set(a.ri,c+1);const u=n.grid.cells[a.ri]?.[c];u&&o.set(`${a.ri}:${a.ci}`,u)}t.set(n,o)}const i=o.get(`${r.rowIndex}:${r.columnIndex}`);return i?Mc(n,r,i):null}}function Sc(e){const t=[""];let r=!1,n=!1;for(const o of e)o===";"&&!r&&!n?t.push(""):t[t.length-1]+=o,o==='"'&&!n&&(r=!r),n=o==="\\"&&!n;return t}function Ac(e,t){const r=Sc(t),n=e===0&&r.length>2?2:e<0&&r.length>1?1:0;return{pattern:r[n],magnitude:Math.abs(e),negative:e<0&&n===0}}function kc(e){const t=[];return{text:e.replace(/"([^"]*)"|\\(.)/g,(n,o,i)=>(t.push(o??i??""),String.fromCharCode(57344+t.length-1))).replace(/\[(Black|Blue|Cyan|Green|Magenta|Red|White|Yellow|Color\d+)\]/gi,""),literals:t}}function Pe(e,t){return/[0#?@_*%[\]"\\.,/]/.test(e)?null:e.replace(/[\uE000-\uF8FF]/g,r=>t.literals[r.charCodeAt(0)-57344]??"")}function Ec(e,t){const r=/^(.*?)(0)(?:\.([0#]+))?E([+-])(0+)(.*?)$/i.exec(t.text);if(!r)return null;const n=Pe(r[1],t),o=Pe(r[6],t),i=r[3]??"";if(n===null||o===null||i.length>100)return null;const[s,a]=e.magnitude.toExponential(i.length).split("e"),c=i.replace(/#/g,"").length,[u,f=""]=s.split("."),d=f.replace(/0+$/,"").padEnd(c,"0"),l=Number(a),m=l<0?"-":r[4]==="+"?"+":"",g=String(Math.abs(l)).padStart(r[5].length,"0");return`${e.negative?"-":""}${n}${u}${d?`.${d}`:""}E${m}${g}${o}`}function Pc(e,t){const r=/^(.*?)([#,]*0[0#]*)(?:\.([0#]+))?(%)?(.*?)$/.exec(t.text);if(!r)return Pe(t.text,t);const n=Pe(r[1],t),o=Pe(r[5],t),i=r[2],s=r[3]??"";if(n===null||o===null||s.length>100||!/^(?:0+|#+0+|#,##0+)$/.test(i))return null;const a=e.magnitude*(r[4]?100:1);if(!Number.isFinite(a))return null;const c=a.toLocaleString("en-US",{useGrouping:i.includes(","),minimumIntegerDigits:Math.min(21,i.replace(/[^0]/g,"").length),minimumFractionDigits:s.replace(/#/g,"").length,maximumFractionDigits:s.length});return`${e.negative?"-":""}${n}${c}${r[4]??""}${o}`}function Fc(e,t,r){if(!t||/^(General|@)$/i.test(t))return String(e);const n=Ac(e,t);if(n.pattern==="")return"";const o=kc(n.pattern),i=Ec(n,o)??Pc(n,o);return i!==null?i:String(e)}function Nc(e){return e!==void 0&&e.replace(/"[^"]*"|\\./g,"").includes("%")}class P extends Error{constructor(t){super(`Invalid report cell edit: ${t}`),this.code=t,this.name="ReportCellEditError"}}function Ic(e,t){let r=e.trim();const n=t&&r.endsWith("%");if(n&&(r=r.slice(0,-1).trim()),/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d*)?(?:[eE][+-]?\d+)?$/.test(r)&&(r=r.replace(/,/g,"")),!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(r))throw new P("number");return Number(r)/(n?100:1)}function Oc(e,t){if(e===null||typeof e=="string"&&e.trim()==="")return null;if(typeof e!="string"&&typeof e!="number")throw new P("number");const r=typeof e=="number"?e:Ic(e,Nc(t.cell.numberFormat));if(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r))throw new P("number");return r}function Rc(e){if(e===null||typeof e=="string"&&e.trim()==="")return null;if(typeof e=="boolean")return e;const t=String(e).trim().toLowerCase();if(["true","yes","是","1"].includes(t))return!0;if(["false","no","否","0"].includes(t))return!1;throw new P("boolean")}function Tc(e,t){return e.valueType==="number"?Oc(t,e):e.valueType==="boolean"?Rc(t):t===null?null:String(t)}function jc(e,t){const r=t.cell.text,o=[["是","否"],["TRUE","FALSE"],["True","False"],["true","false"],["1","0"]].find(i=>i.includes(r??""));return o?o[e?0:1]:String(e)}function go(e,t){return t===null?"":typeof t=="boolean"?jc(t,e):typeof t=="number"?Fc(t,e.cell.numberFormat):String(t)}function ho(e,t){if(!e.editable)throw new P("readonly");const r=Tc(e,t);return{address:{...e.address},table:e.table,source:e.source,previousValue:e.value,previousText:e.cell.text??"",value:r,text:go(e,r)}}function Cc(e,t){const r=t.source;if(!r)return!1;const n=e.source;return!n||["sourceScope","datasetId","rowKey","field","revision","sourceToken"].some(o=>!Object.is(n[o],r[o]))}function po(e){const t=[];for(const r of e.template.pages)for(const n of r.components)n.kind==="list"&&(t.push(n.tree?{...n,rowKey:n.tree.idField}:n),n.detail&&t.push({...n.detail,relation:{detail:n.detail,parentRows:e.datasets[n.dataset]??[]}}));return t}function Me(e){return JSON.stringify([e.sourceScope,e.datasetId])}function Zr(e){return JSON.stringify([e.sourceScope,e.datasetId,e.rowKey])}function yo(e){const t=new Map,r=new Set;return e.forEach((n,o)=>{for(const i of po(n)){if(!i.rowKey)continue;const s=i.relation,a=s?new Set(s.parentRows.map(c=>JSON.stringify(c[s.detail.parentKey]))):void 0;(n.datasets[i.dataset]??[]).forEach((c,u)=>{if(s&&!a.has(JSON.stringify(c[s.detail.foreignKey])))return;const f=c[i.rowKey];if(typeof f!="string"&&typeof f!="number")return;const d=`${o}:${i.dataset}:${u}:${i.rowKey}`;if(r.has(d))return;r.add(d);const l=Zr({sourceScope:n.sourceScope,datasetId:i.dataset,rowKey:f}),m=t.get(l)??[];m.push({partIndex:o,dataset:i.dataset,rowIndex:u,row:c,binding:i}),t.set(l,m)})}}),n=>{const o=t.get(Zr(n));if(!o?.length)throw new P("missing");if(new Set(o.map(i=>`${i.partIndex}:${i.dataset}`)).size!==o.length)throw new P("conflict");return o}}function wo(e,t){const r=e.map(o=>({...o,datasets:{...o.datasets}})),n=new Set;for(const{row:o,field:i,value:s}of t){const a=r[o.partIndex],c=JSON.stringify([o.partIndex,o.dataset]);n.has(c)||(a.datasets[o.dataset]=[...a.datasets[o.dataset]],n.add(c)),a.datasets[o.dataset][o.rowIndex]={...a.datasets[o.dataset][o.rowIndex],[i]:s}}for(const o of n){const[i,s]=JSON.parse(o);Ci(e[i].datasets[s],r[i].datasets[s])}return r}function Lc(e,t,r){const n=[],o=new Set;return e.forEach((i,s)=>{for(const a of po(i))t.has(Me({sourceScope:i.sourceScope,datasetId:a.dataset}))&&(i.datasets[a.dataset]??[]).forEach((c,u)=>{const f={partIndex:s,dataset:a.dataset,rowIndex:u,row:c,binding:a};for(const[d,l]of[[a.revisionField,r.revision],[a.sourceTokenField,r.sourceToken]]){if(!d||l===void 0)continue;const m=`${s}:${a.dataset}:${u}:${d}`;o.has(m)||(o.add(m),n.push({row:f,field:d,value:l}))}})}),n}function Dc(e,t,r){if(!r||r.revision===void 0&&r.sourceToken===void 0)return e;const n=new Set(t.edits.flatMap(o=>o.source?[Me(o.source)]:[]));return bo(e,new Map([...n].map(o=>[o,r])))}function bo(e,t){if(!t.size)return e;function r(i){const s=i.datasetId&&t.get(Me({...i,datasetId:i.datasetId}));return!s||(s.revision===void 0||Object.is(s.revision,i.revision))&&(s.sourceToken===void 0||s.sourceToken===i.sourceToken)?i:{...i,...s.revision!==void 0?{revision:s.revision}:{},...s.sourceToken!==void 0?{sourceToken:s.sourceToken}:{}}}function n(i){const s=i.map(a=>{const c=a.table?.source?r(a.table.source):void 0,u=a.table&&c!==a.table.source?{...a.table,source:c}:a.table,f=a.grid?.cells.map(l=>{const m=l.map(g=>{if(!g)return g;const h=g.source?r(g.source):void 0,p=g.children?n(g.children):void 0;return h===g.source&&p===g.children?g:{...g,source:h,children:p}});return m.some((g,h)=>g!==l[h])?m:l}),d=a.grid&&f?.some((l,m)=>l!==a.grid.cells[m])?{...a.grid,cells:f}:a.grid;return u!==a.table||d!==a.grid?{...a,table:u,grid:d}:a});return s.some((a,c)=>a!==i[c])?s:i}const o=e.pages.map(i=>{const s=n(i.components);return s!==i.components?{...i,components:s}:i});return o.some((i,s)=>i!==e.pages[s])?{...e,pages:o}:e}function ct(e){const t=e.source;if(t)return JSON.stringify([t.sourceScope,t.datasetId,t.rowKey,t.field]);const r=e.table;if(r?.columnKey!==void 0)return JSON.stringify([r.id,r.role,r.rowIndex,r.columnKey]);const n=e.address;return JSON.stringify([n.pageIndex,n.componentIndex,n.rowIndex,n.columnIndex])}function Bc(e){const t=new Map,r=mo(e);return e.pages.forEach((n,o)=>n.components.forEach((i,s)=>{if(!(!i.grid||i.table?.role!=="body"))for(let a=0;a<i.grid.cells.length;a++)for(let c=0;c<i.table.columnKeys.length;c++){const u=r({pageIndex:o,componentIndex:s,rowIndex:a,columnIndex:c});u?.source&&u.editable&&t.set(ct(u),u)}})),t}function xo(e,t){if(++e.nodes>1e6||t>128)throw new P("limit")}function ut(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw new P("conflict");return r.value}function $o(e){if(Object.getOwnPropertyDescriptor(e,"toJSON"))throw new P("conflict");const t=Object.getPrototypeOf(e);if(Array.isArray(e)&&(t!==Array.prototype||Object.keys(e).length!==e.length))throw new P("conflict");if(!(e instanceof Date)&&!Array.isArray(e)&&t!==Object.prototype&&t!==null)throw new P("conflict");for(const r of Reflect.ownKeys(e))if(!(Array.isArray(e)&&r==="length")){if(typeof r=="symbol"||!Object.getOwnPropertyDescriptor(e,r)?.enumerable)throw new P("conflict");if(e instanceof Date||Array.isArray(e)&&!/^(0|[1-9]\d*)$/.test(r))throw new P("conflict")}}function vo(e,t,r,n,o){if(xo(n,o),typeof e=="function"||typeof e=="symbol")throw new P("conflict");if(e===null||typeof e!="object")return;if($o(e),r.has(e))throw new P("conflict");r.add(e);const i=Object.keys(e),s=i.map(a=>ut(e,a));t.push({object:e,prototype:Object.getPrototypeOf(e),keys:i,values:s,...e instanceof Date?{date:Date.prototype.getTime.call(e)}:{},...Array.isArray(e)?{length:e.length}:{}});for(const a of s)vo(a,t,r,n,o+1);r.delete(e)}function _c(e){const{object:t,keys:r,values:n}=e;if($o(t),Object.getPrototypeOf(t)!==e.prototype||Object.getOwnPropertyDescriptor(t,"toJSON")||e.date!==void 0&&!Object.is(Date.prototype.getTime.call(t),e.date)||e.length!==void 0&&t.length!==e.length)return!1;const o=Object.keys(t);return o.length===r.length&&r.every((i,s)=>o[s]===i&&Object.is(ut(t,i),n[s]))}function Wc(e){const t=[];return vo(e,t,new Set,{nodes:0},0),()=>{try{return t.every(_c)}catch{return!1}}}function Ut(e,t,r){if(xo(t,r),e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(Date.prototype.getTime.call(e));if(Array.isArray(e)){const n=[];for(let o=0;o<e.length;o++)n[o]=Ut(ut(e,String(o)),t,r+1);return n}return Object.fromEntries(Object.keys(e).map(n=>[n,Ut(ut(e,n),t,r+1)]))}function Kc(e){const t=Ut(e,{nodes:0},0);for(const r of t)for(const n of Object.values(r.datasets))ji(n);return t}async function Hc(e,t,r={}){const n=[],o={...r,knownTotalPages:void 0};for(const i of pa(e,t,o))n.push(i),n.length%8===0&&await new Promise(s=>setTimeout(s,0));if(r.signal?.aborted){const i=new Error("报表重算已取消");throw i.name="AbortError",i}return{schemaVersion:ve,...yt(e)?{requiresRecalculation:!0}:{},pages:n}}const Qr=new WeakMap;function Ke(e){if(e?.aborted){const t=new Error("报表重算已取消");throw t.name="AbortError",t}}function Mo(e,t){return e[t]===void 0?"":e[t]}function Jc(e,t){if(t.edits.length>1e4)throw new P("limit");const r=mo(e),n=new Set,o=[],i=t.edits.map(s=>{const a=r(s.address);if(!a?.source)throw new P("missing");const c=ct(s);if(n.has(c))throw new P("duplicate");if(n.add(c),Cc(a,s)||!Object.is(a.value,s.previousValue)||(a.cell.text??"")!==s.previousText)throw new P("conflict");return o.push(a),ho(a,s.value)});return{batch:{requestId:t.requestId,edits:i},contexts:o}}function zc(e,t){const r=yo(e);return t.flatMap(n=>{if(!n.source)throw new P("missing");return r(n.source).map(o=>{if(!Object.is(Mo(o.row,n.source.field),n.previousValue))throw new P("conflict");if(o.binding.rowKey===n.source.field)throw new P("readonly");return{row:o,field:n.source.field,value:n.value}})})}function Ot(e,t,r){const n={...e,value:t,source:{...e.source,...r?.revision===void 0?{}:{revision:r.revision},...r?.sourceToken===void 0?{}:{sourceToken:r.sourceToken}}};return n.cell={...e.cell,value:n.value,text:go(n,n.value)},n}function Vc(e,t,r){if(!r||r.revision===void 0&&r.sourceToken===void 0)return[...e];const n=new Set(t.edits.flatMap(o=>o.source?[Me(o.source)]:[]));return wo(e,Lc(e,n,r))}function Uc(e,t,r){const n=new Set(t.edits.map(o=>Me(o.source)));for(const o of n)e.set(o,{...e.get(o),...r.revision!==void 0?{revision:r.revision}:{},...r.sourceToken!==void 0?{sourceToken:r.sourceToken}:{}});return n}function Gc(e,t){let r=t.parts;const n=t.rebuild;let o=Wc(r),i=e,s;const a=new Map,c=new Map;function u(l){if(l!==i)throw new P("conflict");if(s)return s;if(!o?.())throw new P("conflict");return Kc(r)}async function f(l,m,g,h={}){Ke(h.signal),m={requestId:m.requestId,edits:m.edits.map(w=>({...w,address:{...w.address},source:w.source?{...w.source}:void 0,table:w.table?{...w.table}:void 0}))},g=g.map(w=>({...w,address:{...w.address},source:w.source?{...w.source}:void 0,table:w.table?{...w.table}:void 0,cell:{...w.cell}})),await new Promise(w=>setTimeout(w,0)),Ke(h.signal);const p=u(l),b=wo(p,zc(p,m.edits)),y=bo(await n(b,h.signal),c);Ke(h.signal);let $=!1;return{plan:y,commit(w){if(Ke(h.signal),$||i!==l)throw new P("conflict");if(w?.conflicts?.length)throw new P("conflict");const M=Vc(b,m,w),C=Dc(y,m,w);if(w){const R=Uc(c,m,w);for(const[x,v]of a)R.has(Me(v.source))&&a.set(x,Ot(v,v.value,w))}return g.forEach((R,x)=>a.set(ct(R),Ot(R,m.edits[x].value,w))),$=!0,s=M,r=void 0,o=void 0,i=C,Qr.set(i,d),i}}}const d={get plan(){return i},async prepare(l,m,g){const h=Jc(l,m);return f(l,h.batch,h.contexts,g)},async prepareHistory(l,m,g,h,p){if(!h.trim()||m.length>1e4)throw new P("limit");const b=u(l),y=yo(b),$=Bc(l),w=new Set,C=m.map(v=>{if(!v.source)throw new P("missing");const E=ct(v);if(w.has(E))throw new P("duplicate");w.add(E);const L=$.get(E)??a.get(E);if(!L?.source)throw new P("missing");const I=y(L.source)[0];return Ot(L,Mo(I.row,L.source.field))}).map((v,E)=>({context:v,edit:ho(v,m[E][g])})).filter(({edit:v})=>!Object.is(v.previousValue,v.value)),R={requestId:h,edits:C.map(({edit:v})=>v)},x=C.map(({context:v})=>v);return{batch:R,contexts:x,prepared:await f(l,R,x,p)}}};return Qr.set(e,d),d}let qc=0;function qe(){return`report-${Date.now()}-${++qc}`}function we(e,t,r){if(!r?.aborted)try{const n=e?.({...t});n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{})}catch{}}function ae(e){const t=e.taskId??qe(),r=(n,o,i)=>{we(e.onEvent,{taskId:t,...e.correlationId===void 0?{}:{correlationId:e.correlationId},stage:n,status:o,...i===void 0?{}:{reportId:i}},e.signal)};return{taskId:t,progress(n,o,i){we(e.onEvent,{taskId:t,...e.correlationId===void 0?{}:{correlationId:e.correlationId},stage:n,status:"started",completed:o,total:i},e.signal)},async run(n,o,i){r(n,"started",i);try{const s=await o();return r(n,"completed",i),s}catch(s){throw r(n,"failed",i),s}},runSync(n,o,i){r(n,"started",i);try{const s=o();return r(n,"completed",i),s}catch(s){throw r(n,"failed",i),s}}}}function z(e){throw new Error(`数据契约无效:${e}`)}function Gt(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}function Yc(e){for(const t of["description","missingMeaning"])e[t]!==void 0&&!Gt(e[t])&&z(`${t} 应为 1–4096 位非空字符串`);e.aggregation!==void 0&&!["sum","avg","min","max","count","none"].includes(e.aggregation)&&z("未知字段聚合语义"),e.aggregation&&!["count","none"].includes(e.aggregation)&&!["number","decimal"].includes(e.type)&&z("数值聚合仅适用于 number/decimal"),e.format!==void 0&&Xc(e),e.calculation!==void 0&&(!e.calculation||!Gt(e.calculation.description)||!Array.isArray(e.calculation.dependsOn)||!e.calculation.dependsOn.length||e.calculation.dependsOn.length>256||e.calculation.dependsOn.some(t=>typeof t!="string"||!t.trim())||new Set(e.calculation.dependsOn).size!==e.calculation.dependsOn.length)&&z("计算说明需包含说明及 1–256 个唯一依赖字段")}function Xc(e){const t=e.format;if((!t||!["number","percent","date"].includes(t.kind))&&z("未知字段显示格式"),t.kind==="date"){(e.type!=="date"||t.pattern!==void 0&&(!Gt(t.pattern)||t.pattern.length>128))&&z("日期格式仅适用于日期,pattern 最多 128 位");return}["number","decimal"].includes(e.type)||z("数值显示格式仅适用于 number/decimal"),t.digits!==void 0&&(!Number.isSafeInteger(t.digits)||t.digits<0||t.digits>100)&&z("显示小数位应为 0–100 的整数"),t.kind==="number"&&t.thousands!==void 0&&typeof t.thousands!="boolean"&&z("thousands 应为布尔值")}function Zc(e){const t=new Map(e.map(n=>[n.field,n])),r=new Set;for(const n of e){const o=[{field:n.field,exit:!1}],i=new Set;for(;o.length;){const s=o.pop();if(s.exit){i.delete(s.field),r.add(s.field);continue}if(i.has(s.field)&&z("字段计算依赖存在循环"),r.has(s.field))continue;const a=t.get(s.field);a||z(`计算依赖字段未声明:${s.field}`),i.add(s.field),o.push({field:s.field,exit:!0});for(const c of a.calculation?.dependsOn??[])o.push({field:c,exit:!1})}}}const Qc=["text","number","boolean","date","decimal"],eu=new Set(["__proto__","prototype","constructor"]);function K(e){throw new Error(`数据契约无效:${e}`)}function So(e){(!e||!Array.isArray(e.fields)||!e.fields.length||e.fields.length>2048)&&K("fields 应包含 1–2048 个字段");const t=new Set;for(const r of e.fields)(!r||typeof r.field!="string"||!r.field.trim()||eu.has(r.field)||t.has(r.field))&&K("字段名应安全、非空且唯一"),t.add(r.field),Qc.includes(r.type)||K(`未知字段类型 ${r.type}`),ou(r),nu(r),Yc(r),tu(r);ru(e,t),Zc(e.fields)}function tu(e){e.enum!==void 0&&(!Array.isArray(e.enum)||!e.enum.length||e.enum.some(t=>!Ao(t,e.type)))&&K("enum 应为匹配字段类型的非空标量数组")}function ru(e,t){e.rowKey!==void 0&&((typeof e.rowKey!="string"||!e.rowKey.trim()||!t.has(e.rowKey))&&K("rowKey 应为引用已声明字段的非空字符串"),e.fields.find(r=>r.field===e.rowKey)?.type==="boolean"&&K("布尔字段不能作为业务主键"))}function nu(e){for(const t of["label","unit"])e[t]!==void 0&&typeof e[t]!="string"&&K(`${t} 应为字符串`);for(const t of["required","nullable"])e[t]!==void 0&&typeof e[t]!="boolean"&&K(`${t} 应为布尔值`);e.semanticRole!==void 0&&!["identifier","dimension","measure","date","text"].includes(e.semanticRole)&&K("未知字段语义")}function ou(e){for(const t of["min","max","minLength","maxLength"]){const r=e[t];r!==void 0&&(!Number.isFinite(r)||t.includes("Length")&&(!Number.isInteger(r)||r<0))&&K(`${t} 无效`)}e.min!==void 0&&e.max!==void 0&&e.min>e.max&&K("min 不能超过 max"),e.minLength!==void 0&&e.maxLength!==void 0&&e.minLength>e.maxLength&&K("minLength 不能超过 maxLength"),e.type!=="number"&&(e.min!==void 0||e.max!==void 0)&&K("min/max 仅适用于 number,精确小数文本需业务校验"),["number","boolean"].includes(e.type)&&(e.minLength!==void 0||e.maxLength!==void 0)&&K("长度约束仅适用于文本类型")}function iu(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;const r=Number(t[1]),n=Number(t[2]),o=Number(t[3]),i=r%4===0&&(r%100!==0||r%400===0);return r>0&&n>=1&&n<=12&&o>=1&&o<=[31,i?29:28,31,30,31,30,31,31,30,31,30,31][n-1]}function Ao(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":typeof e!="string"?!1:t==="date"?iu(e):t==="decimal"?e.length<=1e4&&/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e):!0}function su(e,t){if(e==null)return t.required||e===null&&t.nullable===!1?{code:"required",message:"缺少必需字段值"}:void 0;if(!Ao(e,t.type))return{code:"type",message:`值应为 ${t.type},不会自动转换原始值`};if(t.enum&&!t.enum.includes(e))return{code:"enum",message:"值不在允许的枚举中"};if(typeof e=="number"&&(t.min!==void 0&&e<t.min||t.max!==void 0&&e>t.max))return{code:"range",message:"数值超出范围"};if(typeof e=="string"&&!au(e,t))return{code:"range",message:"文本长度超出范围"}}function au(e,t){if(t.minLength===void 0&&t.maxLength===void 0)return!0;let r=0;for(const n of e)r++;return(t.minLength===void 0||r>=t.minLength)&&(t.maxLength===void 0||r<=t.maxLength)}function Rt(e,t){const r=e??t;if(!Number.isInteger(r)||r<1)throw new Error("数据校验预算应为正整数");return r}function cu(e,t,r){const n=Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;if((typeof n!="string"||!n.trim())&&!(typeof n=="number"&&Number.isFinite(n)))return"业务主键应为非空字符串或有限数字";const o=JSON.stringify([typeof n,n]);if(r.has(o))return"业务主键重复";r.add(o)}function uu(e,t,r={}){So(t);const n=r.path??"$.rows",o=[],i=Rt(r.maxIssues,100);if(!Array.isArray(e))return{ok:!1,issues:[{code:"row",path:n,message:"数据集应为对象数组"}]};if(e.length>Rt(r.maxRows,1e5)||e.length*t.fields.length>Rt(r.maxCells,2e6))return{ok:!1,issues:[{code:"budget",path:n,message:"数据校验超出行数或单元格预算"}]};const s=new Set;for(let a=0;a<e.length&&o.length<i;a++){const c=e[a];if(!c||typeof c!="object"||Array.isArray(c)){o.push({code:"row",path:`${n}[${a}]`,rowIndex:a,message:"行应为对象"});continue}fu(c,t,a,n,s,o,i)}return{ok:o.length===0,issues:o}}function fu(e,t,r,n,o,i,s){for(const a of t.fields){if(i.length>=s)return;const c=su(Object.prototype.hasOwnProperty.call(e,a.field)?e[a.field]:void 0,a);c&&i.push({...c,rowIndex:r,field:a.field,path:`${n}[${r}].${a.field}`})}if(t.rowKey&&i.length<s){const a=cu(e,t.rowKey,o);a&&i.push({code:"row-key",path:`${n}[${r}].${t.rowKey}`,message:a,rowIndex:r,field:t.rowKey})}}function lu(e){return So(e),{$schema:"https://json-schema.org/draft/2020-12/schema",type:"array",items:{type:"object",properties:Object.fromEntries(e.fields.map(r=>[r.field,du(r,r.field===e.rowKey)])),required:e.fields.filter(r=>r.required||r.field===e.rowKey).map(r=>r.field),additionalProperties:!0},...e.rowKey?{"x-report-rowKey":e.rowKey}:{}}}function du(e,t){const r=!t&&e.nullable!==!1&&!e.required;return{type:r?[en(e.type),"null"]:en(e.type),...e.label?{title:e.label}:{},...e.description?{description:e.description}:{},...e.type==="date"?{format:"date"}:{},...e.type==="decimal"?{pattern:"^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$"}:{},...e.enum?{enum:r?[...e.enum,null]:[...e.enum]}:{},...e.min===void 0?{}:{minimum:e.min},...e.max===void 0?{}:{maximum:e.max},...mu(e,t),...t&&e.type==="text"?{pattern:"\\S"}:{},...e.unit?{"x-report-unit":e.unit}:{},...e.semanticRole?{"x-report-semanticRole":e.semanticRole}:{},...e.aggregation?{"x-report-aggregation":e.aggregation}:{},...e.format?{"x-report-format":{...e.format}}:{},...e.missingMeaning?{"x-report-missingMeaning":e.missingMeaning}:{},...e.calculation?{"x-report-calculation":{description:e.calculation.description,dependsOn:[...e.calculation.dependsOn]}}:{}}}function mu(e,t){const r={};return(e.minLength!==void 0||t&&e.type!=="number")&&(r.minLength=Math.max(e.minLength??0,t?1:0)),e.type==="decimal"?r.maxLength=Math.min(e.maxLength??1e4,1e4):e.maxLength!==void 0&&(r.maxLength=e.maxLength),r}function en(e){return e==="text"||e==="date"||e==="decimal"?"string":e}function gu(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e,r=n=>typeof n=="string"&&n.trim().length>0&&n.length<=256;return!r(t.datasetId)||!r(t.field)||t.tableId!==void 0&&!r(t.tableId)||t.reportScope!==void 0&&(typeof t.reportScope!="string"||!t.reportScope.trim()||t.reportScope.length>4096)?!1:t.rowKey===void 0?!0:typeof t.rowKey=="string"?t.rowKey.trim().length>0&&t.rowKey.length<=1024:typeof t.rowKey=="number"&&Number.isFinite(t.rowKey)}function hu(e){return e==="missing-source"||e==="not-applicable"||e==="not-calculable"}function Er(e){return e.target!==void 0&&!gu(e.target)?!1:e.valueState===void 0||hu(e.valueState)&&e.target!==void 0}function ko(e,t,r={}){const n=new Map;for(const i of e.pages)for(const s of i.components){if(s.kind!=="list"||s.tree?.input!=="nested")continue;const a=n.get(s.dataset);if(a&&(a.childrenField??"children")!==(s.tree.childrenField??"children"))throw new Error("同一数据集的嵌套树应使用相同 childrenField");n.set(s.dataset,s.tree)}if(!n.size)return t;const o={...t};for(const[i,s]of n){const a=Math.min(s.maxRows??1e5,r.maxRows??1/0);o[i]=Rn(t[i]??[],{...s,maxRows:a},r.signal)}return o}function pu(e,t,r={}){return Object.values(ko(e,t,r)).reduce((n,o)=>n+o.length,0)}function yu(e,t,r){const n=lu(r),o=e?.pages.flatMap(a=>a.components).find(a=>a.kind==="list"&&a.dataset===t&&a.tree?.input==="nested");if(!o||o.kind!=="list"||!o.tree)return n;const i=n.items,s=o.tree.childrenField??"children";return{...n,items:{$ref:"#/$defs/treeNode"},$defs:{treeNode:{...i,properties:{...i.properties,[s]:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/treeNode"}}]}}}}}}function Pr(e,t){return JSON.stringify([e,t])}function Eo(e,t,r){return r===void 0?Pr(e,t):JSON.stringify(["shared",r])}function Po(e,t,r){return e.map(n=>{const o=n.table?{...n.table,id:r(n.table.id),...n.table.source?{source:{...n.table.source,sourceScope:t}}:{}}:void 0,i=n.grid?.cells.map(s=>s.map(a=>!a||!a.source&&!a.children?a:{...a,...a.source?{source:{...a.source,sourceScope:t}}:{},...a.children?{children:Po(a.children,t,r)}:{}}));return o||i?{...n,...o?{table:o}:{},...i?{grid:{...n.grid,cells:i}}:{}}:n})}class S extends Error{constructor(t,r,n){super(r),this.name="ReportSourceError",this.code=t,this.cause=n}}function St(e){const t=new Error("报表加载已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function U(e){if(e?.aborted)throw St(e)}function qt(e,t){return t?new Promise((r,n)=>{const o=()=>t.removeEventListener("abort",i),i=()=>{o(),n(St(t))};t.addEventListener("abort",i,{once:!0}),t.aborted&&i(),Promise.resolve(e).then(s=>{o(),r(s)},s=>{o(),n(s)})}):Promise.resolve(e)}function wu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new S("validate",`报表 ${t} 的数据集应为对象`);for(const[r,n]of Object.entries(e))if(!Array.isArray(n)||n.some(o=>!o||typeof o!="object"||Array.isArray(o)))throw new S("validate",`报表 ${t} 的数据集 ${r} 应为对象数组`)}async function bu(e,t,r){const{reportId:n,signal:o}=t;try{const i=await qt(e(t),o);U(o);const s=pc(i);if(!s.ok)throw new S("validate",`报表 ${n} 模板校验失败:${s.errors.slice(0,3).map(a=>`${a.path}: ${a.message}`).join("; ")}`);return r.push(...s.warnings.map(a=>`${n}: ${a.path}: ${a.message}`)),i}catch(i){throw o?.aborted?St(o):i instanceof S?i:i instanceof Qa?new S("validate",`报表 ${n} 模板校验失败:${i.message}`,i):new S("fetch",`报表 ${n} 模板加载失败:${i instanceof Error?i.message:String(i)}`,i)}}async function xu(e,t,r,n){const o=t.signal;let i;try{if(e.load)i=await qt(e.load(t),o);else if(e.provider){const s=await qt(e.provider.query(t),o);U(o),$u(s,r),i=s.datasets,n?.(r,s)}else i=e.datasets??{}}catch(s){throw o?.aborted?St(o):s instanceof S?s:new S("fetch",`报表 ${r} 取数失败:${s instanceof Error?s.message:String(s)}`,s)}return U(o),i}function $u(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new S("validate",`报表 ${t} Provider 应返回 datasets 结果对象`);for(const r of["revision","sourceToken"])if(e[r]!==void 0&&typeof e[r]!="string")throw new S("validate",`报表 ${t} Provider ${r} 应为字符串`);if(e.diagnostics!==void 0&&(!Array.isArray(e.diagnostics)||e.diagnostics.some(r=>!r||typeof r.code!="string"||typeof r.message!="string"||!["info","warning","error"].includes(r.severity))))throw new S("validate",`报表 ${t} Provider diagnostics 不符合结构化诊断契约`);if(e.diagnostics?.some(r=>!Er(r)))throw new S("validate",`报表 ${t} Provider 数据说明缺少有效的字段身份或值状态`)}function vu(e,t,r,n,o){try{t=ko(n,t,{maxRows:e.dataValidation?.maxRows,signal:o})}catch(i){throw new S("validate",`报表 ${r} 树形数据无效:${i instanceof Error?i.message:String(i)}`,i)}for(const[i,s]of Object.entries(e.dataSchema??{})){let a;try{a=uu(Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0,s,{...e.dataValidation,path:`$.datasets.${i}`})}catch(c){throw new S("config",`报表 ${r} 数据集 ${i} 字段契约配置无效`,c)}if(!a.ok)throw new S("validate",`报表 ${r} 数据集 ${i} 不符合字段契约:${a.issues[0]?.message}`,{issues:a.issues})}}function Fo(e,t){if(!e.repeat)return!1;const r=Object.prototype.hasOwnProperty.call(t,e.repeat.dataset)?t[e.repeat.dataset]:void 0;return Array.isArray(r)&&r.length===0}function No(e){const t=r=>r.grid?.cells.reduce((n,o)=>n+o.reduce((i,s)=>i+(s?1+(s.children?.reduce((a,c)=>a+t(c),0)??0):0),0),0)??0;return e.pages.reduce((r,n)=>r+n.components.reduce((o,i)=>o+t(i),0),0)}function Io(e,t,r,n){return{...e,signal:n??e?.signal,...t===void 0?{}:{maxPages:Math.max(1,Math.min(t,e?.maxPages??t))},...r===void 0?{}:{maxCells:Math.max(1,Math.min(r,e?.maxCells??r))}}}function Mu(e,t,r,n,o,i){const s=o.maxPages===void 0?void 0:o.maxPages-o.usedPages,a=o.maxCells===void 0?void 0:o.maxCells-o.usedCells;try{if(s!==void 0&&s<1&&e.pages.length&&!Fo(e,t))throw new ue(0,1);const c=Io(r.pagination,s,a,i),u=ya(e,t,c),f=No(u.plan);if(a!==void 0&&f>a)throw new ye(a,f);return{...u,cells:f}}catch(c){let u=c;throw c instanceof ue&&o.maxPages!==void 0&&c.limit===s&&(u=new ue(o.maxPages,o.usedPages+c.actual)),c instanceof ye&&o.maxCells!==void 0&&(u=new ye(o.maxCells,o.usedCells+c.actual)),new S("validate",`报表 ${n} 排版失败:${u instanceof Error?u.message:String(u)}`,u)}}function Oo(e,t,r,n,o){const i=new Map,s=a=>{let c=i.get(a);return c===void 0&&(c=JSON.stringify([r,n,a]),i.set(a,c)),c};for(const a of t.pages)e.push({...a,meta:{...a.meta,reportScope:Pr(r,n)},components:Po(a.components,o??Eo(r,n),s)})}async function Su(e,t,r,n,o){const i=[];let s=0;for(const[u,f]of e.entries()){U(o);const d=n.maxPages===void 0?void 0:n.maxPages-i.length,l=n.maxCells===void 0?void 0:n.maxCells-s;if(d!==void 0&&d<1&&f.template.pages.length&&!Fo(f.template,f.datasets))throw new ue(n.maxPages,i.length+1);const m=await Hc(f.template,f.datasets,Io(t[u]?.pagination,d,l,o));if(s+=No(m),n.maxCells!==void 0&&s>n.maxCells)throw new ye(n.maxCells,s);Oo(i,m,u,r[u],f.sourceScope)}const a={schemaVersion:ve,...e.some(u=>yt(u.template))?{requiresRecalculation:!0}:{},pages:i},c=Be(a);if(!c.ok)throw new S("validate",`重算渲染计划校验失败:${c.errors[0]?.message}`);return a}function Au(e,t={}){if(t.maxPages!==void 0&&(!Number.isSafeInteger(t.maxPages)||t.maxPages<1))throw new S("config","maxPages 应为正安全整数");if(t.maxCells!==void 0&&(!Number.isSafeInteger(t.maxCells)||t.maxCells<1))throw new S("config","maxCells 应为正安全整数");function r(o){const i=Object.prototype.hasOwnProperty.call(e,o)?e[o]:void 0;if(!i)throw new S("config",`未注册报表 ${o}`);if(i.sourceScope!==void 0&&(typeof i.sourceScope!="string"||!i.sourceScope.trim()||i.sourceScope.length>512))throw new S("config","sourceScope 应为不超过 512 字符的非空字符串");return i}return Object.assign(async({reportIds:o,params:i,signal:s,onWarning:a,onQueryResult:c,...u})=>{U(s);const f=ae({...u,signal:s}),d=[...o],l={...i};if(d.length===0)throw new S("config","缺少报表 ID");const m=d.map(r),g=f.runSync("validate",()=>m.map(x=>Yr(x.params??(typeof x.template=="function"?[]:x.template.params)??[],l))),h=[],p=[];let b=0;const y=[];for(const[x,v]of m.entries()){U(s);const E=d[x],L={reportId:E,params:g[x],signal:s},I=typeof v.template=="function"?await f.run("query",()=>bu(v.template,L,y),E):v.template;L.params=f.runSync("validate",()=>Yr(v.params??I.params??[],L.params),E);const T=await f.run("query",()=>xu(v,L,E,(Pt,ii)=>c?.(Pt,ii,x)),E);f.runSync("validate",()=>{wu(T,E),t.onDatasets?.(E,T,I),vu(v,T,E,I,s)},E),U(s);const Et=f.runSync("layout",()=>Mu(I,T,v,E,{maxPages:t.maxPages,usedPages:h.length,maxCells:t.maxCells,usedCells:b},s),E);b+=Et.cells;const Ir=Eo(x,E,v.sourceScope);p.push({template:I,datasets:T,sourceScope:Ir}),Oo(h,Et.plan,x,E,Ir),y.push(...Et.warnings.map(Pt=>`${E}: ${Pt}`))}U(s);const $={schemaVersion:ve,...p.some(x=>yt(x.template))?{requiresRecalculation:!0}:{},pages:h},w=f.runSync("validate",()=>{const x=Be($);if(!x.ok)throw new S("validate",`渲染计划校验失败:${x.errors.slice(0,3).map(v=>`${v.path}: ${v.message}`).join("; ")}`);return x});y.push(...w.warnings.map(x=>`${x.path}: ${x.message}`));const M=m.map(x=>({...x,pagination:{...x.pagination}})),C={maxPages:t.maxPages,maxCells:t.maxCells};try{Gc($,{parts:p,rebuild:(x,v)=>Su(x,M,d,C,v)})}catch{y.push("来源数据无法建立本地重算口径;当前预览仅支持计划内编辑,请使用可序列化模板数据启用规则重算")}const R=a??t.onWarning??(x=>console.warn("[mach-report]",x));for(const x of y)U(s),R(x);return U(s),$},{getParamDefs:o=>at(e,o)})}const Fr=Object.freeze({maxRows:1e5,maxPages:1e4,maxCells:2e6,maxOutputBytes:1e8,maxPreparedBytes:64e6,maxDurationMs:12e4});class _ extends Error{constructor(t,r,n){super(r),this.code=t,this.path=n,this.name="ReportRuntimeError"}}function N(e){if(!e?.aborted)return;if(e.reason instanceof _)throw e.reason;const t=new Error("报表执行已取消");throw t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function B(e,t,r){if(!Number.isFinite(r)||r<0)throw new _("budget",`${t} 的执行统计无效`,`$.budget.${t}`);const n=e[t];if(n!==void 0&&r>n)throw new _("budget",`${t} 超出预算 ${n}(实际 ${r})`,`$.budget.${t}`)}function Ro(e){for(const[t,r]of Object.entries(e)){if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new _("budget",`${t} 应为正有限数字`,`$.budget.${t}`);if(t!=="maxDurationMs"&&r!==void 0&&!Number.isSafeInteger(r))throw new _("budget",`${t} 应为正安全整数`,`$.budget.${t}`);if(t==="maxDurationMs"&&r!==void 0&&r>2147483647)throw new _("budget","maxDurationMs 不能超过 2147483647",`$.budget.${t}`)}}async function Fe(e,t,r){const n=new AbortController,o=()=>n.abort(e?.reason);e?.addEventListener("abort",o,{once:!0}),e?.aborted&&o();const i=Date.now(),s=t===void 0?void 0:setTimeout(()=>n.abort(new _("timeout",`报表执行超过 ${t}ms`)),t);let a;try{N(n.signal);const c=new Promise((f,d)=>{a=()=>{try{N(n.signal)}catch(l){d(l)}},n.signal.addEventListener("abort",a,{once:!0})}),u=await Promise.race([r(n.signal),c]);if(N(n.signal),t!==void 0&&Date.now()-i>t)throw new _("timeout",`报表执行超过 ${t}ms`);return u}finally{s!==void 0&&clearTimeout(s),a&&n.signal.removeEventListener("abort",a),e?.removeEventListener("abort",o)}}function To(e,t){ce.assertOutputActive(t.signal),ce.observeOutput(()=>t.onDiagnostic?.(e)),ce.assertOutputActive(t.signal)}class ku extends Error{constructor(t){super(`Output contains ${t.length} known fidelity issue(s): ${t[0]?.code}`),this.diagnostics=t,this.code="output-fidelity",this.name="OutputFidelityError"}}class At extends Error{constructor(t,r){super(r),this.code=t,this.name="ImageMediaError"}}const Tt={maxImageBytes:16*1024*1024,maxTotalImageBytes:32*1024*1024,maxImages:1e3,maxImagePixels:16e6,maxTotalImagePixels:64e6,maxImageDimension:16384};function X(e){throw new At("invalid-image-data",e)}function Ne(e){throw new At("image-budget-exceeded",e)}function Eu(e){const t={...Tt};for(const r of Object.keys(Tt)){const n=e[r]??Tt[r];if(!Number.isSafeInteger(n)||n<=0||n>2147483647)throw new RangeError(`${r} 图片预算须为1至2147483647的整数。`);t[r]=n}return t}function Pu(e){if(e.length<33||![137,80,78,71,13,10,26,10].every((r,n)=>e[n]===r))return X("图片内容与 PNG/JPEG 类型不一致。");const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return t.getUint32(8)!==13||String.fromCharCode(...e.subarray(12,16))!=="IHDR"?X("PNG must begin with an IHDR header."):[t.getUint32(16),t.getUint32(20)]}const Fu=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function Nu(e){if(e[0]!==255||e[1]!==216)return X("图片内容与 PNG/JPEG 类型不一致。");let t=2;for(;t+3<e.length;){if(e[t++]!==255)return X("JPEG marker is malformed.");for(;e[t]===255;)t++;const r=e[t++];if(r===217||r===218)break;if(r===1||r>=208&&r<=215)continue;const n=e[t]*256+e[t+1];if(n<2||t+n>e.length)return X("JPEG segment exceeds its data boundary.");if(Fu.has(r))return n<8?X("JPEG frame header is incomplete."):[e[t+5]*256+e[t+6],e[t+3]*256+e[t+4]];t+=n}return X("JPEG has no supported dimension header.")}function Iu(e,t){if(e.length>Math.ceil(t.maxImageBytes/3)*4+64)return Ne("单张图片超过字节预算。");const r=/^data:image\/(png|jpe?g);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(e);if(!r||r[2].length%4)return X("Image must contain valid PNG/JPEG base64 data.");const n=r[2],o=n.length/4*3-(n.endsWith("==")?2:n.endsWith("=")?1:0);if(o>t.maxImageBytes)return Ne("单张图片超过字节预算。");const i=r[1].toLowerCase()==="png"?"png":"jpeg",s=atob(n),a=new Uint8Array(o);for(let f=0;f<o;f++)a[f]=s.charCodeAt(f);const[c,u]=i==="png"?Pu(a):Nu(a);return!c||!u?X("Image dimensions must be positive."):c>t.maxImageDimension||u>t.maxImageDimension||c*u>t.maxImagePixels?Ne("Image exceeds its decoded dimension or pixel budget."):{dataUrl:`data:image/${i};base64,${n}`,bytes:a,extension:i,width:c,height:u}}function Ou(e={}){const t=Eu(e),r=new Map;let n=0,o=0;return i=>{const s=i.replace(/^data:image\/(png|jpe?g);base64,/i,(u,f)=>`data:image/${f.toLowerCase()==="png"?"png":"jpeg"};base64,`),a=r.get(s);if(a)return a;if(r.size>=t.maxImages)return Ne("唯一图片数量超过预算。");const c=Iu(i,t);return n+c.bytes.length>t.maxTotalImageBytes||o+c.width*c.height>t.maxTotalImagePixels?Ne("图片总字节或总像素超过预算。"):(n+=c.bytes.length,o+=c.width*c.height,r.set(s,c),c)}}class Nr extends Error{constructor(t,r){super(t.message),this.name="OutputAssetError",this.diagnostic=t,this.cause=r}}function ft(e){if(e.aborted)throw e.reason??new DOMException("The operation was aborted.","AbortError")}function Ru(e){const t={maxAssets:1e3,maxImageBytes:33554432,maxTotalImageBytes:134217728,maxDurationMs:3e4,...e.assetBudget};for(const[r,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0||n>2147483647)throw new RangeError(`${r} must be a positive safe integer at most 2147483647.`);return t}function Tu(e){const t=/^data:image\/[a-z0-9.+-]+(;base64)?,(.*)$/is.exec(e);if(!t)throw new TypeError("Asset renderers must return an image data URL.");return t[1]?Math.ceil(t[2].length*3/4):new TextEncoder().encode(decodeURIComponent(t[2])).byteLength}function He(e,t,r,n,o){const i={code:r,message:n,severity:"warning",format:e.options.format??"dom",pageIndex:t.pageIndex,componentIndex:t.componentIndex,componentPath:t.componentPath,kind:t.component.kind,nid:t.component.nid};if(e.diagnostics.push(i),To(i,{...e.options,signal:e.signal}),e.options.assetFailure!=="placeholder")throw new Nr(i,o)}async function ju(e,t,r){const n=e.options.assetRegistry?.rendererFor(t)??e.options.assetRenderers?.[t.kind];if(t.imageData||!n)return t.imageData;if(++e.rendered>e.budget.maxAssets)return He(e,r,"asset-budget-exceeded","Output exceeded the asset count budget.");let o;try{if(e.active=r,o=await ce.waitForOutput(n({...r,signal:e.signal}),e.signal),ft(e.signal),o.length>e.budget.maxImageBytes*4+1024)return He(e,r,"asset-budget-exceeded","Output exceeded the image payload byte budget.");const i=Tu(o);if(i>e.budget.maxImageBytes||e.bytes+i>e.budget.maxTotalImageBytes)return He(e,r,"asset-budget-exceeded","Output exceeded the encoded image byte budget.");/^data:image\/(png|jpe?g);base64,/i.test(o)&&e.inspectImage(o),e.bytes+=i}catch(i){if(e.signal.aborted||i instanceof Nr||i instanceof At&&i.code==="image-budget-exceeded")throw i;return He(e,r,"asset-render-failed",`Asset renderer failed for ${t.kind}; output was not silently omitted.`,i)}return o}function Cu(e,t){const r=e.active;if(!r){t.abort(new Error("Asset rendering exceeded maxDurationMs."));return}const n={code:"asset-budget-exceeded",message:"Asset rendering exceeded maxDurationMs.",severity:"warning",format:e.options.format??"dom",pageIndex:r.pageIndex,componentIndex:r.componentIndex,componentPath:r.componentPath,kind:r.component.kind,nid:r.component.nid};e.diagnostics.push(n);try{To(n,{...e.options,signal:e.signal})}catch(o){t.abort(o);return}t.abort(new Nr(n))}async function Lu(e,t,r,n,o){if(!t?.children?.length)return t;const i=[];for(const[s,a]of t.children.entries())i.push(await jo(e,a,{...r,component:a,componentPath:[...n,s]},o));return i.some((s,a)=>s!==t.children[a])?{...t,children:i}:t}async function jo(e,t,r,n){if(ft(e.signal),n.has(t))throw new TypeError("Cyclic grid children cannot be rendered.");let o=e.cache.get(t);o||(o=ju(e,t,r),e.cache.set(t,o));const i=await o;ft(e.signal);let s=t.grid;if(s){const a=new Set(n).add(t),c=[];for(const[u,f]of s.cells.entries()){const d=[];for(const[l,m]of f.entries())d.push(await Lu(e,m,r,[...r.componentPath,u,l],a));c.push(d)}c.some((u,f)=>u.some((d,l)=>d!==s.cells[f][l]))&&(s={...s,cells:c})}return i!==t.imageData||s!==t.grid?{...t,imageData:i,grid:s}:t}function Du(e,t,r){const n=new Set,o=i=>{if(ce.assertOutputActive(r),!n.has(i)){if(n.add(i),i.imageData&&/^data:image\/(png|jpe?g);base64,/i.test(i.imageData))try{t(i.imageData)}catch(s){if(!(s instanceof At)||s.code==="image-budget-exceeded")throw s}for(const s of i.grid?.cells??[])for(const a of s)for(const c of a?.children??[])o(c)}};for(const i of e.pages)for(const s of i.components)o(s)}function Bu(e){if(e.options.fidelity==="strict"&&e.diagnostics.length)throw new ku(e.diagnostics)}async function tn(e,t={}){ce.assertOutputActive(t.signal),$a(e);const r=Ru(t),n=Ou(t);if(Du(e,n,t.signal),t.signal?.aborted)throw t.signal.reason??new DOMException("The operation was aborted.","AbortError");const o=new AbortController,i=()=>o.abort(t.signal?.reason);if(t.signal?.addEventListener("abort",i,{once:!0}),!t.assetRegistry&&(!t.assetRenderers||!Object.keys(t.assetRenderers).length))return t.signal?.removeEventListener("abort",i),{plan:e,diagnostics:[]};const s={options:t,signal:o.signal,diagnostics:[],rendered:0,bytes:0,budget:r,cache:new WeakMap,inspectImage:n},a=setTimeout(()=>Cu(s,o),r.maxDurationMs);try{const c=[];for(const[u,f]of e.pages.entries()){if(u<(t.start??0)||u>(t.end??e.pages.length-1)){c.push(f);continue}const d=[];for(const[l,m]of f.components.entries())d.push(await jo(s,m,{component:m,pageIndex:u,componentIndex:l,componentPath:[]},new Set));c.push(d.some((l,m)=>l!==f.components[m])?{...f,components:d}:f)}return ft(s.signal),Bu(s),{plan:c.some((u,f)=>u!==e.pages[f])?{...e,pages:c}:e,diagnostics:s.diagnostics}}finally{clearTimeout(a),t.signal?.removeEventListener("abort",i)}}function lt(e=[]){return e.map(({code:t,message:r,severity:n,pageIndex:o,componentIndex:i})=>({code:t,message:r,severity:n,path:i<0?`$.pages.${o}`:`$.pages.${o}.components.${i}`}))}async function rn(e,t,r=Date.now()){const n=e.prepared;if(e.fidelity==="strict"&&n.diagnostics.some(d=>d.code==="asset-render-failed"||d.code==="asset-budget-exceeded"))throw new S("validate","严格输出拒绝已有资产渲染降级,请修复组件后重新准备报表。");const o=e.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;N(e.signal);const i=e.pdf?.customFontFaces??(e.pdf?.customFontBytes?{regular:e.pdf.customFontBytes}:void 0),s=o&&i?o.createFontBytesMeasurer(i):void 0,a=ae(e),c=await a.run("encode",async()=>{let d;if(e.format==="pdf"){N(e.signal);const l=await o.renderPlanToPdf(n.plan,{...e.pdf,...s?{measurer:s}:{},fidelity:e.fidelity,signal:e.signal,onProgress:(m,g)=>a.progress("encode",m,g)});d=l.bytes,n.diagnostics.push(...lt(l.diagnostics)),n.diagnostics.push(...l.fidelityWarnings.map(m=>({code:"pdf-fidelity",message:m,severity:"warning"})),...l.pageErrors.map(m=>({code:"pdf-page",message:m,severity:"error"}))),l.unsupportedTextCount&&n.diagnostics.push({code:"pdf-font",message:`${l.unsupportedTextCount} 段文本包含当前字体不支持的字符`,severity:"warning"})}else{const{renderPlanToXlsx:l}=await import("@agile-team/mach-report/xlsx");N(e.signal);const m=await l(n.plan,{...e.xlsx,fidelity:e.fidelity,signal:e.signal,onProgress:(g,h)=>a.progress("encode",g,h)});d=new Uint8Array(m.buffer),n.diagnostics.push(...lt(m.diagnostics)),n.diagnostics.push(...m.warnings.map(g=>({code:"xlsx-fidelity",message:g,severity:"warning"})))}return N(e.signal),d});B(t,"maxOutputBytes",c.byteLength);const{plan:u,...f}=n;return{...f,bytes:c,format:e.format,contentType:e.format==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",stats:{...f.stats,durationMs:Date.now()-r,outputBytes:c.byteLength}}}function Co(e,t){const r=t.maxNodes??1e6;if(![t.maxBytes,r].every(f=>Number.isSafeInteger(f)&&f>0))throw t.error("budget","快照预算应为正安全整数");let n=0,o=0;const i=new Set;function s(f){if(o+=f,o>t.maxBytes)throw t.error("budget","快照超过字节预算")}function a(f,d){if(++n>r||d>64)throw t.error("budget","快照节点或深度超过预算");if(n%1024===0&&t.check?.(),typeof f=="string")return s(f.length+2),f;if(f===null||typeof f=="boolean"||typeof f=="number"&&Number.isFinite(f))return s(String(f).length),f;if(!f||typeof f!="object"||i.has(f))throw t.error("input","快照应为无循环的有限 JSON 值");return c(f,d)}function c(f,d){const l=Array.isArray(f),m=Object.getPrototypeOf(f);if(m!==(l?Array.prototype:Object.prototype)&&!(m===null&&!l)||Object.getOwnPropertySymbols(f).length)throw t.error("input","快照应为普通 JSON 对象");const g=Object.getOwnPropertyNames(f).filter(b=>!(l&&b==="length"));if(l&&(g.length!==f.length||g.some((b,y)=>b!==String(y))))throw t.error("input","快照数组应为连续数组");i.add(f),s(2);const h=Object.create(null);let p=0;for(const b of g){const y=Object.getOwnPropertyDescriptor(f,b);if(y.get||y.set||!y.enumerable||["__proto__","constructor","prototype"].includes(b))throw t.error("input","快照不允许访问器或危险键");y.value===void 0&&!l||(s((p++?1:0)+(l?0:b.length+3)),h[b]=a(y.value===void 0?null:y.value,d+1))}return i.delete(f),l?g.map(b=>h[b]):h}t.check?.();const u=JSON.stringify(a(e,0));if(new TextEncoder().encode(u).byteLength>t.maxBytes)throw t.error("budget","快照超过字节预算");return JSON.parse(u)}const _u=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),G=(e,t)=>e>>>t|e<<32-t;function Lo(e,t,r){const n=new DataView(e.buffer,e.byteOffset+t,64);for(let o=0;o<16;o++)r[o]=n.getUint32(o*4);for(let o=16;o<64;o++){const i=r[o-15],s=r[o-2],a=G(i,7)^G(i,18)^i>>>3,c=G(s,17)^G(s,19)^s>>>10;r[o]=r[o-16]+a+r[o-7]+c}}function Do(e,t){let r=e[0],n=e[1],o=e[2],i=e[3],s=e[4],a=e[5],c=e[6],u=e[7];for(let f=0;f<64;f++){const d=G(s,6)^G(s,11)^G(s,25),l=s&a^~s&c,m=u+d+l+_u[f]+t[f]>>>0,g=G(r,2)^G(r,13)^G(r,22),h=r&n^r&o^n&o,p=g+h>>>0;u=c,c=a,a=s,s=i+m>>>0,i=o,o=n,n=r,r=m+p>>>0}e[0]=e[0]+r,e[1]=e[1]+n,e[2]=e[2]+o,e[3]=e[3]+i,e[4]=e[4]+s,e[5]=e[5]+a,e[6]=e[6]+c,e[7]=e[7]+u}function Bo(e){const t=new Uint8Array(Math.ceil((e.byteLength+9)/64)*64);t.set(e),t[e.byteLength]=128;const r=new DataView(t.buffer);return r.setUint32(t.length-8,Math.floor(e.byteLength/536870912)),r.setUint32(t.length-4,e.byteLength*8>>>0),t}const _o=()=>new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Wo=e=>Array.from(e,t=>t.toString(16).padStart(8,"0")).join("");function nn(e){const t=Bo(e),r=_o(),n=new Uint32Array(64);for(let o=0;o<t.length;o+=64)Lo(t,o,n),Do(r,n);return Wo(r)}async function Wu(e){const t=Bo(e),r=_o(),n=new Uint32Array(64);for(let o=0;o<t.length;o+=64)o>0&&o%262144===0&&await new Promise(i=>setTimeout(i,0)),Lo(t,o,n),Do(r,n);return Wo(r)}function Yt(e){return e&&{...e}}function Ie(e){if(!e)return;const t=r=>{if(!(r instanceof Uint8Array)&&!(r instanceof ArrayBuffer))throw new S("validate","字体应为 Uint8Array 或 ArrayBuffer");if(r.byteLength>32e6)throw new _("budget","单份字体超过 32 MB","$.pdf");return new Uint8Array(r instanceof Uint8Array?r:new Uint8Array(r))};if(e.customFontFaces){const r=e.customFontFaces;return{customFontName:e.customFontName,customFontFaces:{regular:t(r.regular),...r.bold?{bold:t(r.bold)}:{},...r.italic?{italic:t(r.italic)}:{},...r.boldItalic?{boldItalic:t(r.boldItalic)}:{}}}}return{customFontName:e.customFontName,...e.customFontBytes?{customFontBytes:t(e.customFontBytes)}:{}}}function Ko(e){const t=e?.customFontFaces??(e?.customFontBytes?{regular:e.customFontBytes}:void 0);if(!t)return;const r=["regular","bold","italic","boldItalic"].map(n=>{const o=t[n];if(!o)return[n,null];const i=o instanceof Uint8Array?o:new Uint8Array(o);if(i.byteLength>32e6)throw new _("budget","单份字体超过 32 MB","$.pdf");return[n,nn(i)]});return nn(new TextEncoder().encode(JSON.stringify(r)))}const Xt=new WeakMap;function Ku(e,t,r){const n=Ho(e,t,r);let o=!0;return{prepared:n,forward(){if(!o)throw new Error("报表快照只能交接一次");return o=!1,Xt.set(n,t),n}}}function Ho(e,t,r){if(N(r),!Number.isSafeInteger(t)||t<=0)throw new _("budget","快照预算应为正安全整数","$.budget.maxPreparedBytes");const n=Xt.get(e);if(Xt.delete(e),n!==void 0&&n<=t)return e;const o=Co(e,{maxBytes:t,maxNodes:t,check:()=>N(r),error:(i,s)=>i==="budget"?new _("budget",s,"$.budget.maxPreparedBytes"):new S("validate",s)});return zo(o),o}function Jo(e){if(e===void 0)return!0;if(!Array.isArray(e))return!1;const t=new Set;return e.every(r=>!r||typeof r!="object"||Array.isArray(r)||typeof r.reportId!="string"||!r.reportId.trim()||!Number.isSafeInteger(r.reportIndex)||r.reportIndex<0||t.has(r.reportIndex)||typeof r.reportScope!="string"||!r.reportScope.trim()||r.reportScope.length>4096||r.revision!==void 0&&typeof r.revision!="string"||r.sourceToken!==void 0&&typeof r.sourceToken!="string"?!1:(t.add(r.reportIndex),!0))}function zo(e){if(!Jo(e.sources))throw new S("validate","准备结果来源清单无效");if(!e?.stats||["rows","pages","cells"].some(t=>!Number.isSafeInteger(e.stats[t])||e.stats[t]<0)||!Number.isFinite(e.stats.durationMs)||e.stats.durationMs<0)throw new S("validate","准备结果统计无效");if(!Array.isArray(e.diagnostics)||e.diagnostics.some(t=>!t||typeof t.code!="string"||typeof t.message!="string"||!["info","warning","error"].includes(t.severity)||!Er(t)))throw new S("validate","准备结果诊断无效");if(!e.revisions||typeof e.revisions!="object"||Array.isArray(e.revisions)||Object.values(e.revisions).some(t=>!t||typeof t!="object"||t.revision!==void 0&&typeof t.revision!="string"||t.sourceToken!==void 0&&typeof t.sourceToken!="string"))throw new S("validate","准备结果修订无效");if(e.layout&&(!["heuristic","provided","font-bytes"].includes(e.layout.textMetrics)||e.layout.fontFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.layout.fontFingerprint)))throw new S("validate","准备结果字体度量标识无效")}function Hu(e){if(e.layoutPolicy!==void 0&&!["verify","preserve"].includes(e.layoutPolicy))throw new S("validate","无效的 layoutPolicy");if(e.format!=="pdf")return;if(e.layoutPolicy==="preserve"&&!e.prepared.layout?.fontFingerprint){e.prepared.diagnostics.push({code:"prepared-layout-preserved",severity:"info",message:"显式保持现有分页与几何;未验证排版字体身份,实际 PDF 输出仍遵循 fidelity 校验。"});return}const t=e.prepared.layout?.fontFingerprint,r=Ko(e.pdf);if(t===r&&(t!==void 0||e.prepared.layout?.textMetrics==="heuristic"&&!r))return;const n="已准备计划的字体度量无法与本次 PDF 字体确认一致;保持现有分页,未重新查询或排版。请在 prepare 和 exportPrepared 提供相同字体字节。";if(e.fidelity==="strict")throw new S("validate",n);e.prepared.diagnostics.push({code:"prepared-font-metrics",severity:"warning",message:n})}function on(e){return{...e,reportIds:[...e.reportIds],...e.params?{params:{...e.params}}:{}}}function Vo(e,t){if(t.length===0)throw new S("config","缺少报表 ID");return t.map(r=>{if(!Object.prototype.hasOwnProperty.call(e,r))throw new S("config",`未注册报表 ${r}`);return e[r]})}function kt(e){return e.grid?.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+kt(s),0)??0):0),0),0)??0}function Ju(e,t,r){return e.pages.reduce((n,o)=>n+o.components.reduce((i,s)=>s.kind!=="list"?i+kt(s):i+xa(s,t,r),0),0)}function zu(e,t=Object.keys(e)){return Vo(e,t).map((r,n)=>{const o=t[n],i=at(e,[o]);return{id:o,params:JSON.parse(JSON.stringify(i)),paramsSchema:qa(i),datasetsSchema:Object.fromEntries(Object.entries(r.dataSchema??{}).map(([s,a])=>[s,yu(typeof r.template=="function"?void 0:r.template,s,a)])),capabilities:{save:!!r.provider?.save,export:!!r.provider?.export,templates:!!r.provider?.templates}}})}function Uo(e,t){Vo(e,t.reportIds);const r=zt(at(e,t.reportIds),t.params),n=t.reportIds.flatMap(i=>zt(at(e,[i]),t.params).issues),o=new Map(n.map(i=>[JSON.stringify(i),i]));return{...r,ok:o.size===0,issues:[...o.values()]}}function Zt(e,t){const r=Be(e.plan);if(!r.ok)throw new S("validate",`执行器返回无效计划:${r.errors[0]?.path}`);const n=e.plan.pages.length,o=e.plan.pages.reduce((i,s)=>i+s.components.reduce((a,c)=>a+kt(c),0),0);return B(t,"maxRows",e.stats.rows),B(t,"maxPages",n),B(t,"maxCells",o),{...e,stats:{...e.stats,pages:n,cells:o}}}function sn(e,t){const r=Uo(e.reports,t);if(!r.ok)throw new vt(r.issues)}function Go(e){const t={...Fr,...e.budget};Ro(t);const r=async(o,i)=>{const s=Date.now();let a=0,c=0;const u=[],f={},d=[],l=Object.fromEntries(Object.entries(e.reports).map(([w,M])=>[w,{...M,pagination:{...e.pagination,...M.pagination,...i?{measurer:i}:{}},dataValidation:{...M.dataValidation,maxRows:Math.min(t.maxRows??1e5,M.dataValidation?.maxRows??1/0),maxCells:Math.min(t.maxCells??2e6,M.dataValidation?.maxCells??1/0)}}])),g=await Au(l,{maxPages:t.maxPages,maxCells:t.maxCells,onDatasets:(w,M,C)=>{try{a+=pu(C,M,{maxRows:t.maxRows,signal:o.signal})}catch(R){throw R instanceof An?new _("budget",R.message,"$.budget.maxRows"):R}B(t,"maxRows",a),c+=Ju(C,M,l[w]?.pagination),B(t,"maxCells",c)}})({...o,params:o.params??{},onWarning:w=>u.push({code:"layout",message:w,severity:"warning"}),onQueryResult:(w,M,C=0)=>{const R=Pr(C,w);Object.defineProperty(f,w,{value:{revision:M.revision,sourceToken:M.sourceToken},enumerable:!0,writable:!0}),d.push({reportId:w,reportIndex:C,reportScope:R,...M.revision===void 0?{}:{revision:M.revision},...M.sourceToken===void 0?{}:{sourceToken:M.sourceToken}}),u.push(...(M.diagnostics??[]).map(x=>({...x,...x.target?{target:{...x.target,reportScope:R,...x.target.tableId?{tableId:JSON.stringify([C,w,x.target.tableId])}:{}}}:{}})))}}).catch(w=>{throw w instanceof S&&w.cause instanceof ue?new _("budget",w.cause.message,"$.budget.maxPages"):w instanceof S&&w.cause instanceof ye?new _("budget",w.cause.message,"$.budget.maxCells"):w});N(o.signal);const h=e.assets?await ae(o).run("assets",()=>tn(g,{...e.assets,signal:o.signal})):{plan:g,diagnostics:[]},p=h.plan;u.push(...lt(h.diagnostics));const b=p.pages.reduce((w,M)=>w+M.components.reduce((C,R)=>C+kt(R),0),0);B(t,"maxPages",p.pages.length),B(t,"maxCells",b);const y=Ko(o.pdf),$=e.pagination?.measurer||Object.values(e.reports).some(w=>w.pagination?.measurer);return{plan:p,diagnostics:u,revisions:f,sources:d,layout:{textMetrics:y?"font-bytes":$?"provided":"heuristic",...y?{fontFingerprint:y}:{}},stats:{rows:a,pages:p.pages.length,cells:b,durationMs:Date.now()-s}}},n=async o=>{const i=Date.now();if(o.format!=="pdf"&&o.format!=="xlsx")throw new S("config","不支持的报表导出格式");const s=o.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;N(o.signal);const a=o.pdf?.customFontFaces??(o.pdf?.customFontBytes?{regular:o.pdf.customFontBytes}:void 0),c=s&&a?s.createFontBytesMeasurer(a):void 0,u=await r(o,c);return N(o.signal),rn({...o,prepared:u},t,i)};return{describe:o=>zu(e.reports,o),validate:o=>Uo(e.reports,o),prepare:o=>Fe(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=on(o),u={...c,...c.pdf?{pdf:Ie(c.pdf)}:{},taskId:c.taskId??qe()},f=a?h=>we(a,h,i):void 0,d={...u,signal:i,onEvent:f};ae(d).runSync("validate",()=>sn(e,u));let l;const m=u.pdf?.customFontFaces??(u.pdf?.customFontBytes?{regular:u.pdf.customFontBytes}:void 0);if(!e.executor&&m){const h=await import("@agile-team/mach-report/pdf");N(i),l=h.createFontBytesMeasurer(m)}const g=e.executor?await e.executor.prepare(u,i,f):await r(d,l);return Zt(g,t)}),exportPrepared:o=>Fe(o.signal,t.maxDurationMs,async i=>{const s=Date.now(),{signal:a,onEvent:c,...u}=o,f=Zt(Ho(o.prepared,t.maxPreparedBytes??64e6,i),t),d={...u,xlsx:Yt(u.xlsx),prepared:f,...u.pdf?{pdf:Ie(u.pdf)}:{},taskId:u.taskId??qe()};if(d.format!=="pdf"&&d.format!=="xlsx")throw new S("config","不支持的报表导出格式");const l=c?g=>we(c,g,i):void 0;if(e.executor){if(!e.executor.exportPrepared)throw new S("config","执行器未实现 exportPrepared;请升级执行器或显式使用本地运行时");const g=await e.executor.exportPrepared(d,i,l);return B(t,"maxRows",g.stats.rows),B(t,"maxPages",g.stats.pages),B(t,"maxCells",g.stats.cells),B(t,"maxOutputBytes",g.bytes.byteLength),{...g,stats:{...g.stats,outputBytes:g.bytes.byteLength}}}const m={...d,signal:i,onEvent:l};if(ae(m).runSync("validate",()=>Hu(m)),e.assets){const g=await ae(m).run("assets",()=>tn(f.plan,{...e.assets,signal:i}));f.plan=g.plan,f.diagnostics.push(...lt(g.diagnostics))}return rn(m,t,s)}),export:o=>Fe(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=on(o),u={...c,xlsx:Yt(c.xlsx),...c.pdf?{pdf:Ie(c.pdf)}:{},taskId:c.taskId??qe()},f=a?m=>we(a,m,i):void 0,d={...u,signal:i,onEvent:f};if(ae(d).runSync("validate",()=>sn(e,u)),u.format!=="pdf"&&u.format!=="xlsx")throw new S("config","不支持的报表导出格式");const l=e.executor?await e.executor.export(u,i,f):await n(d);return B(t,"maxRows",l.stats.rows),B(t,"maxPages",l.stats.pages),B(t,"maxCells",l.stats.cells),B(t,"maxOutputBytes",l.bytes.byteLength),{...l,stats:{...l.stats,outputBytes:l.bytes.byteLength}}})}}const Vu={cells:2e4,pages:20,bytes:2e6};function Oe(e){return e.cells>=e.limits.cells||e.pages>=e.limits.pages||e.bytes>=e.limits.bytes||e.capped}function he(e){return++e.visits>=1e5&&(e.capped=!0),!Oe(e)}function te(e){return typeof e=="string"?e.length*2:0}function an(e,t){for(const r of e??[]){if(!he(t))return;for(const n of r.segments){if(!he(t))return;t.bytes+=te(n.text)}}}function qo(e,t,r){if(r>32){t.capped=!0;return}if(he(t)){t.bytes+=te(e.text)+te(e.rawText)+te(e.imageData),an(e.richParagraphs,t);for(const n of e.lines??[]){if(!he(t))return;t.bytes+=te(n)}for(const n of e.grid?.cells??[]){if(!he(t))return;for(const o of n){if(!he(t))return;if(o){t.cells++,t.bytes+=te(o.text)+te(o.rawText)+te(o.value),an(o.richParagraphs,t);for(const i of o.children??[]){if(Oe(t))return;qo(i,t,r+1)}}}}}}function Uu(e){const t={...Vu,...e.thresholds};for(const r of Object.values(t))if(!Number.isSafeInteger(r)||r<=0)throw new RangeError("导出隔离阈值应为正安全整数");return t}function Gu(e,t){const r=Uu(t),n=e.pdf?.customFontFaces?Object.values(e.pdf.customFontFaces):[e.pdf?.customFontBytes],o={pages:e.prepared.plan.pages.length,cells:0,bytes:n.reduce((a,c)=>a+(c?.byteLength??0),0),visits:0,capped:!1,limits:r};for(const a of e.prepared.plan.pages){if(Oe(o))break;for(const c of a.components){if(Oe(o))break;qo(c,o,0)}}let i=Oe(o)?"worker":"local",s=o.capped?"scan-limit":i==="worker"?"threshold":"small-task";return t.mode==="local"&&(i="local",s="explicit-local"),t.mode==="worker"&&(i="worker",s="explicit-worker"),Object.values(e.xlsx??{}).some(a=>typeof a=="function")&&(i="local",s="nonserializable-options"),{mode:i,reason:s,estimate:{pages:o.pages,cells:o.cells,bytes:o.bytes},hardCancellation:i==="worker"}}const ne="mach-report-worker/1";class Qt extends Error{constructor(t){super(t.message),this.name=t.name,this.code=t.code,this.path=t.path,this.issues=t.issues,this.diagnostics=t.diagnostics}}function oe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function qu(e){return oe(e)?["rows","pages","cells"].every(t=>typeof e[t]=="number"&&Number.isSafeInteger(e[t])&&e[t]>=0)&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0:!1}function Yu(e){return Array.isArray(e)&&e.every(t=>oe(t)&&typeof t.code=="string"&&typeof t.message=="string"&&["info","warning","error"].includes(t.severity)&&Er(t))}function Xu(e){return oe(e)&&Object.values(e).every(t=>oe(t)&&(t.revision===void 0||typeof t.revision=="string")&&(t.sourceToken===void 0||typeof t.sourceToken=="string"))}function Zu(e){return e===void 0?!0:oe(e)&&["heuristic","provided","font-bytes"].includes(e.textMetrics)&&(e.fontFingerprint===void 0||typeof e.fontFingerprint=="string"&&/^[a-f0-9]{64}$/.test(e.fontFingerprint))}function Qu(e,t){if(!oe(e)||!qu(e.stats)||!Yu(e.diagnostics)||!Xu(e.revisions)||!Zu(e.layout)||!Jo(e.sources))return!1;if(t==="prepare")return Be(e.plan).ok;const r=e.format==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";return e.bytes instanceof Uint8Array&&(e.format==="pdf"||e.format==="xlsx")&&e.contentType===r}function Yo(e){if(!e||typeof e!="object")return{message:String(e)};const t={};for(const r of["code","path","field","message"]){const n=e[r];typeof n=="string"&&(t[r]=n)}return t}function ef(e){const t=Yo(e);if(!oe(e))return t;for(const r of["format","severity","kind","nid"])typeof e[r]=="string"&&(t[r]=e[r]);for(const r of["pageIndex","componentIndex"])Number.isSafeInteger(e[r])&&e[r]>=0&&(t[r]=e[r]);return Array.isArray(e.componentPath)&&e.componentPath.every(r=>Number.isSafeInteger(r)&&r>=0)&&(t.componentPath=e.componentPath),t}function Xo(e){if(!(e instanceof Error))return{name:"Error",message:String(e)};const t=e;return{name:e.name,message:e.message,...typeof t.code=="string"?{code:t.code}:{},...typeof t.path=="string"?{path:t.path}:{},...Array.isArray(t.issues)?{issues:t.issues.map(Yo)}:{},...Array.isArray(t.diagnostics)?{diagnostics:t.diagnostics.map(ef)}:{}}}function Zo(e){if(!e||typeof e!="object")return!1;const t=e;return t.protocol===ne&&typeof t.id=="string"&&(t.operation==="prepare"||t.operation==="export"||t.operation==="exportPrepared")&&!!t.input&&typeof t.input=="object"}async function Qo(e,t,r){try{const n=t.operation==="prepare"?await e.prepare({...t.input,onEvent:r}):t.operation==="exportPrepared"?await e.exportPrepared({...t.input,onEvent:r}):await e.export({...t.input,onEvent:r});return{protocol:ne,id:t.id,result:n}}catch(n){return{protocol:ne,id:t.id,error:Xo(n)}}}function ei(e){const t=e.result;return!t||!("bytes"in t)||!(t.bytes.buffer instanceof ArrayBuffer)?[]:[t.bytes.buffer]}function tf(e,t){if(!oe(e)||typeof e.taskId!="string"||!e.taskId||t.taskId!==void 0&&e.taskId!==t.taskId||e.correlationId!==t.correlationId||e.reportId!==void 0&&(typeof e.reportId!="string"||!("reportIds"in t&&t.reportIds.includes(e.reportId)))||!["query","validate","layout","assets","encode"].includes(e.stage)||!["started","completed","failed"].includes(e.status))return!1;for(const r of["completed","total"])if(e[r]!==void 0&&(typeof e[r]!="number"||!Number.isFinite(e[r])||e[r]<0))return!1;return e.completed===void 0||e.total===void 0||e.completed<=e.total}class er extends Error{constructor(t){super("报表 Worker 无法启动"),this.cause=t,this.name="ReportWorkerStartError"}}let rf=0;function cn(e){const t=new Error("报表 Worker 任务已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e}),t}function nf(e,t){if(!e||typeof e!="object")return;const r=e;return r.protocol===ne&&r.id===t?r:void 0}function of(e,t={}){const r=t.timeoutMs??12e4;if(!Number.isFinite(r)||r<=0||r>2147483647)throw new RangeError("Worker timeoutMs 应为正有限数字,且不能超过 2147483647");const n=(o,i,s,a)=>s?.aborted?Promise.reject(cn(s.reason)):new Promise((c,u)=>{let f;try{f=e()}catch(y){u(new er(y));return}const d=`mach-report-${Date.now()}-${++rf}`;let l=!1,m=()=>{},g;const h=(y,$)=>{if(l)return;l=!0,g&&clearTimeout(g);let w;try{m()}catch(M){w=M}s?.removeEventListener("abort",p),y??=w,Promise.resolve().then(()=>f.terminate()).then(()=>y===void 0?c($):u(y),M=>u(y??M))},p=()=>h(cn(s?.reason)),b=y=>{const $=nf(y,d);if(!(!$||l)){if("type"in $&&$.type==="event"){const w="event"in $?$.event:void 0;tf(w,i)?we(a,w,s):h(new Error("报表 Worker 返回无效阶段事件"));return}$.error&&typeof $.error.name=="string"&&typeof $.error.message=="string"?h(new Qt($.error)):Qu($.result,o)&&(o==="prepare"||"format"in $.result&&"format"in i&&$.result.format===i.format)?h(void 0,$.result):h(new Error("报表 Worker 返回无效响应"))}};try{if(m=f.subscribe(b,y=>h(y??new Error("报表 Worker 执行失败"))),l){m();return}if(s?.addEventListener("abort",p,{once:!0}),g=setTimeout(()=>h(new Qt({name:"ReportRuntimeError",code:"timeout",message:`报表 Worker 执行超过 ${r}ms`})),r),s?.aborted)p();else{const{onEvent:y,signal:$,...w}=i,M=sf(w);f.postMessage({protocol:ne,id:d,operation:o,input:w,...t.budget?{budget:t.budget}:{}},M)}}catch(y){h(y)}});return{exportPrepared:(o,i,s)=>n("exportPrepared",o,i,s),prepare:(o,i,s)=>n("prepare",o,i,s),export:(o,i,s)=>n("export",o,i,s)}}function sf(e){return e.pdf?(e.pdf=Ie(e.pdf),(e.pdf?.customFontFaces?Object.values(e.pdf.customFontFaces):[e.pdf?.customFontBytes]).filter(r=>r instanceof Uint8Array).map(r=>r.buffer)):[]}function af(e){if(e.mode!==void 0&&!["auto","local","worker"].includes(e.mode))throw new TypeError("无效的导出执行模式");if(e.fallback!==void 0&&!["local","error"].includes(e.fallback))throw new TypeError("无效的导出回退策略");Ro({...e.budget,maxDurationMs:e.timeoutMs??e.budget?.maxDurationMs??12e4})}function un(e,t){ce.observeOutput(()=>e.onDecision?.({...t,estimate:{...t.estimate}}))}function fn(e,t){return{...e,mode:"local",reason:t,hardCancellation:!1}}function cf(e,t){const r={...Fr,...t.budget},n=Ku(e.prepared,r.maxPreparedBytes,e.signal),o=Zt(n.prepared,r);n.prepared.stats=o.stats;const i={...e,prepared:n.prepared,pdf:Ie(e.pdf),xlsx:Yt(e.xlsx)};return{request:i,forward:()=>({...i,prepared:n.forward()})}}function uf(e,t){af(e);const r={...e,thresholds:{...e.thresholds},budget:{...Fr,...e.budget}},n=r.timeoutMs??r.budget.maxDurationMs??12e4,o=Go({reports:{},budget:{...r.budget,maxDurationMs:n}}),i=new Set;let s=!1;const a=r.mode!=="worker"&&r.fallback!=="error";async function c(u,f){const d=Date.now(),l=()=>{const b=n-(Date.now()-d);if(b<=0)throw new _("timeout",`报表执行超过 ${n}ms`);return b};let m=Gu(u,r);if(m.reason==="nonserializable-options"&&r.mode==="worker")throw new TypeError("Worker 模式不接受函数选项;请使用本地模式或可序列化配置");if(m.mode==="worker"&&!t){if(!a)throw new er(new Error("未配置 workerFactory"));m=fn(m,"worker-unavailable")}const g=cf(u,r),h=g.request;if(un(r,m),N(u.signal),m.mode==="worker")try{const b=t(l());if(!b.exportPrepared)throw new TypeError("隔离执行器缺少 exportPrepared");const{signal:y,onEvent:$,...w}=h,M=await b.exportPrepared(w,y,$);return N(y),B(r.budget,"maxOutputBytes",M.bytes.byteLength),{...M,execution:m}}catch(b){if(!(b instanceof er)||!a)throw b;N(u.signal),m=fn(m,"worker-start-failed"),un(r,m)}const p=f?await Fe(u.signal,l(),b=>f({...h,signal:b})):await Fe(u.signal,l(),b=>o.exportPrepared({...g.forward(),signal:b}));return N(u.signal),B(r.budget,"maxOutputBytes",p.bytes.byteLength),{...p,execution:m}}return{async exportPrepared(u,f){if(s)throw new _("closed","导出执行器已释放");if(N(u.signal),i.size>=2)throw new _("queue-full","同时导出的任务已达 2 个,请等待完成后重试");const d=new AbortController;i.add(d);const l=()=>d.abort(u.signal?.reason);u.signal?.addEventListener("abort",l,{once:!0});try{return await c({...u,signal:d.signal},f)}finally{u.signal?.removeEventListener("abort",l),i.delete(d)}},cancel(){for(const u of i)u.abort()},dispose(){s=!0;for(const u of i)u.abort()}}}async function ff(e,t){try{if(e.operation!=="exportPrepared")throw new TypeError("内置编码 Worker 仅接受 exportPrepared");return await Qo(Go({reports:{},budget:e.budget}),e,t)}catch(r){return{protocol:ne,id:e.id,error:Xo(r)}}}class k extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportJobError"}}function dt(e,t){if(typeof e!="string"||!e.trim()||e.length>256||typeof t!="string"||t!==t.trim()||!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(t))throw new k("input","任务范围应非空,ID应为1–128位安全标识")}function lf(e){const t=Array.isArray(e),r=Object.getPrototypeOf(e),n=Object.keys(e);if(r!==(t?Array.prototype:Object.prototype)&&!(r===null&&!t))throw new k("input","任务对象应为普通 JSON 对象");if(Object.getOwnPropertySymbols(e).length)throw new k("input","任务不能包含Symbol");if(Object.getOwnPropertyNames(e).filter(i=>!(t&&i==="length")).length!==n.length)throw new k("input","任务不能包含不可枚举属性");if(t&&(n.length!==e.length||n.some(i=>i!==String(Number(i))||!Number.isSafeInteger(Number(i))||Number(i)<0||Number(i)>=e.length)))throw new k("input","任务数组不能稀疏或包含额外属性");return n.sort()}function df(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(["__proto__","prototype","constructor"].includes(t)||r.get||r.set)throw new k("input","任务不能包含危险键或访问器");return r.value}function ee(e,t={}){const r=t.maxNodes??2e4,n=t.maxCharacters??1e6;if(!Number.isSafeInteger(r)||r<1||r>2e4||!Number.isSafeInteger(n)||n<1||n>1e6)throw new k("input","任务JSON预算无效");let o=0,i=0;const s=new Set;function a(u,f){if(++o>r||f>32)throw new k("input","任务数据超过节点或深度预算");if(typeof u=="string"){if(i+=u.length,i>n)throw new k("input","任务文本超过预算");return u}if(u===null||typeof u=="boolean"||typeof u=="number"&&Number.isFinite(u))return u;if(!u||typeof u!="object"||s.has(u))throw new k("input","任务只允许无循环的有限 JSON 值");const d=Array.isArray(u),l=lf(u);s.add(u);const m=Object.create(null);for(const g of l){if(i+=g.length,i>n)throw new k("input","任务文本超过预算");m[g]=a(df(u,g),f+1)}return s.delete(u),d?Array.from({length:u.length},(g,h)=>m[String(h)]):m}const c=JSON.stringify(a(e,0));if(c.length>n)throw new k("input","任务序列化数据超过字符预算");return c}function jt(e){return JSON.parse(JSON.stringify(e))}function ti(e,t,r,n){if(dt(t,r),e.scope!==t||e.id!==r||e.revision!==(n??0)+1||!Number.isSafeInteger(e.revision))throw new k("input","任务身份或修订不匹配");if(![e.createdAt,e.updatedAt,e.attempt].every(o=>Number.isSafeInteger(o)&&o>=0)||!["queued","running","completed","failed","cancelled"].includes(e.status))throw new k("input","任务状态无效");if(e.lease&&(!e.lease.owner||!Number.isSafeInteger(e.lease.expiresAt)))throw new k("input","任务租约无效");if(!e.request||typeof e.request.kind!="string"||!e.request.kind.trim()||e.request.kind.length>128)throw new k("input","任务类型无效");ee(e.request.payload,{maxNodes:19e3,maxCharacters:75e4}),ee(e)}function mf(e,t){if(e&&(e.createdAt!==t.createdAt||ee(e.request)!==ee(t.request)))throw new k("input","任务创建时间与请求不可变更,请使用新任务ID")}function gf(e,t){return e.status==="queued"||e.status==="running"&&(e.lease?.expiresAt??0)<=t}function hf(e={}){const t={maxRecords:e.maxRecords??1e4,maxBytes:e.maxBytes??67108864,maxResultBytes:e.maxResultBytes??262144,controlReserveBytes:e.controlReserveBytes??4096,maxTombstones:e.maxTombstones??1e4,maxTombstoneBytes:e.maxTombstoneBytes??16777216};if(!Object.values(t).every(r=>Number.isSafeInteger(r)&&r>0)||t.controlReserveBytes<4096)throw new k("input","任务容量应为正整数,控制状态预留至少4096字节");return t}function Re(e){return new TextEncoder().encode(ee(e)).byteLength}function ri(e,t){const r={scope:e.scope,id:e.id,revision:1,request:e.request,status:"queued",createdAt:e.createdAt,updatedAt:e.createdAt,attempt:0},n={...e};delete n.result;const o=e.result===void 0?0:Re(e.result);if(o>t.maxResultBytes)throw new k("capacity","任务结果超过独立预算,请保存文件引用");return Math.max(Re(r)+t.controlReserveBytes,Re(n))+o}function ni(e){return e.status!=="queued"&&e.status!=="running"}function pf(e){const t={...e,tombstoneRetentionMs:e.tombstoneRetentionMs??6048e5,limit:e.limit??100};if(![t.now,t.terminalBefore].every(r=>Number.isSafeInteger(r)&&r>=0)||t.terminalBefore>t.now)throw new k("input","终态清理时间应为不超过当前时间的非负整数");if(![t.tombstoneRetentionMs,t.limit].every(r=>Number.isSafeInteger(r)&&r>0)||!Number.isSafeInteger(t.now+t.tombstoneRetentionMs))throw new k("input","幂等保留期与清理批量应为正整数");return t}async function yf(e){const t=new TextEncoder().encode(ee(e)),r=globalThis.crypto?.subtle;if(!r)return Wu(t);const n=await r.digest("SHA-256",t);return Array.from(new Uint8Array(n),o=>o.toString(16).padStart(2,"0")).join("")}async function wf(e,t){if(!ni(e))throw new k("input","只能归档终态任务");return{scope:e.scope,id:e.id,revision:e.revision,status:e.status,createdAt:e.createdAt,updatedAt:e.updatedAt,attempt:e.attempt,requestHash:await yf(e.request),expiresAt:t}}function bf(e){if(!e||!["completed","failed","cancelled"].includes(e.status)||!/^[a-f0-9]{64}$/.test(e.requestHash))throw new k("input","任务幂等摘要无效");if(![e.revision,e.createdAt,e.updatedAt,e.attempt,e.expiresAt].every(t=>Number.isSafeInteger(t)&&t>=0)||e.revision<1)throw new k("input","任务幂等摘要时间或修订无效")}function _e(e){return e?.code}function Te(e,t){return le.createHash("sha256").update(JSON.stringify([e,t])).digest("hex")+".json"}async function tr(e){try{return await A.promises.readFile(e,"utf8")}catch(t){if(_e(t)==="ENOENT")return;throw t}}async function xf(e,t){const r=await tr(e);if(r===void 0)return;let n;try{n=JSON.parse(r)}catch{throw new k("conflict","任务锁尚未完整写入或已损坏,拒绝自动移除")}if(!n||!Number.isSafeInteger(n.pid)||n.pid<1)throw new k("conflict","任务锁身份无效,拒绝自动移除");try{process.kill(n.pid,0)}catch(o){if(_e(o)==="ESRCH"){await A.promises.unlink(e);return}throw o}throw new k("conflict","任务目录的写入进程仍在运行")}async function $f(e,t){if(!t)throw new k("conflict","任务目录已有写入进程;多实例请使用数据库CAS适配器");const r=e+".recovery";let n;try{n=await A.promises.open(r,"wx",384)}catch(o){throw _e(o)==="EEXIST"?new k("conflict","任务目录恢复正在进行,请稍后重试"):o}try{return await n.writeFile(JSON.stringify({pid:process.pid})),await xf(e,!0),await A.promises.open(e,"wx",384)}finally{await n.close(),await A.promises.unlink(r)}}async function vf(e,t){const r=j.join(e,".writer-lock"),n=le.randomUUID();let o;try{o=await A.promises.open(r,"wx",384)}catch(i){if(_e(i)!=="EEXIST")throw i;o=await $f(r,t)}try{await o.writeFile(JSON.stringify({pid:process.pid,token:n})),await o.sync()}catch(i){throw await o.close(),await A.promises.unlink(r).catch(()=>{}),i}return{file:r,token:n,handle:o}}function Mf(e,t,r,n){if("tombstone"in r){const o=r.tombstone;if(bf(o),dt(o.scope,o.id),Te(o.scope,o.id)!==t)throw new k("input","持久任务摘要身份不匹配");const i=Re(o);e.tombstoneBytes+=i,e.tombstones.set(t,{value:o,bytes:i})}else{if(ti(r,r.scope,r.id,r.revision-1),Te(r.scope,r.id)!==t)throw new k("input","持久任务文件身份不匹配");const o=ri(r,n);e.bytes+=o,e.records.set(t,{record:r,bytes:o})}if(e.bytes>n.maxBytes||e.records.size>n.maxRecords||e.tombstoneBytes>n.maxTombstoneBytes||e.tombstones.size>n.maxTombstones)throw new k("capacity","持久任务及控制状态预留超过目录预算")}async function Sf(e,t){const r=await A.promises.readdir(e);for(const i of r.filter(s=>/^\.pending-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(s)))await A.promises.unlink(j.join(e,i));const n=r.filter(i=>/^[a-f0-9]{64}\.json$/.test(i));if(n.length>t.maxRecords+t.maxTombstones)throw new k("capacity","持久任务数量超过目录预算");const o={records:new Map,tombstones:new Map,bytes:0,tombstoneBytes:0};for(const i of n){const s=j.join(e,i);if((await A.promises.stat(s)).size>4e6)throw new k("capacity","持久任务文件超过单文件预算");Mf(o,i,JSON.parse(await A.promises.readFile(s,"utf8")),t)}return o}async function Af(e,t,r){const n=j.join(e,`.pending-${le.randomUUID()}`);try{const o=await A.promises.open(n,"wx",384);try{await o.writeFile(r),await o.sync()}finally{await o.close()}await A.promises.rename(n,j.join(e,t));const i=await A.promises.open(e,"r");try{await i.sync()}finally{await i.close()}}finally{await A.promises.unlink(n).catch(o=>{if(_e(o)!=="ENOENT")throw o})}}async function kf(e){const t=j.resolve(e.directory),r=hf(e);await A.promises.mkdir(t,{recursive:!0,mode:448});const n=await vf(t,e.recoverDeadOwner??!1);let o;try{o=await Sf(t,r)}catch(l){throw await n.handle.close(),await A.promises.unlink(n.file),l}let i=!1,s=Promise.resolve();const a=()=>{if(i)throw new k("closed","持久任务存储已关闭")},c=l=>{a();const m=s.then(async()=>{if(JSON.parse(await A.promises.readFile(n.file,"utf8")).token!==n.token)throw new k("closed","持久任务存储写入锁已失效");return l()});return s=m.then(()=>{},()=>{}),m},u=async(l,m,g)=>{try{await Af(t,l,m)}catch(h){throw await tr(j.join(t,l))===m&&g(),h}g()};return{read:async(l,m)=>{a(),dt(l,m),await s;const g=o.records.get(Te(l,m));return g?jt(g.record):void 0},readTombstone:async(l,m)=>{a(),dt(l,m),await s;const g=o.tombstones.get(Te(l,m));return g?jt(g.value):void 0},candidates:async(l,m)=>(a(),await s,Array.from(o.records.values(),g=>g.record).filter(g=>gf(g,l)).sort((g,h)=>g.createdAt-h.createdAt).slice(0,m).map(jt)),compareAndSwap:async(l,m,g,h)=>{const p=JSON.parse(ee(h));return ti(p,l,m,g),c(async()=>{const b=Te(l,m),y=o.records.get(b);if((y?.record.revision??null)!==g||o.tombstones.has(b))return!1;mf(y?.record,p);const $=ri(p,r),w=o.bytes-(y?.bytes??0)+$;if(w>r.maxBytes||!y&&o.records.size>=r.maxRecords)throw new k("capacity","持久任务容量已满,请清理终态任务或扩大显式预算");return await u(b,ee(p),()=>{o.records.set(b,{record:p,bytes:$}),o.bytes=w}),!0})},prune:async l=>{const m=pf(l);return c(async()=>{const g={archived:0,expired:0};for(const[h,p]of o.tombstones)p.value.expiresAt>m.now||g.expired>=m.limit||(await A.promises.unlink(j.join(t,h)),o.tombstones.delete(h),o.tombstoneBytes-=p.bytes,g.expired++);for(const[h,p]of o.records){if(!ni(p.record)||p.record.updatedAt>m.terminalBefore||g.archived+g.expired>=m.limit)continue;const b=await wf(p.record,m.now+m.tombstoneRetentionMs),y=Re(b);if(o.tombstones.size>=r.maxTombstones||o.tombstoneBytes+y>r.maxTombstoneBytes)break;await u(h,ee({tombstone:b}),()=>{o.tombstones.set(h,{value:b,bytes:y}),o.tombstoneBytes+=y,o.records.delete(h),o.bytes-=p.bytes}),g.archived++}if(g.expired){const h=await A.promises.open(t,"r");try{await h.sync()}finally{await h.close()}}return g})},close:async()=>{if(i)return;i=!0,await s,await n.handle.close();const l=await tr(n.file);l&&JSON.parse(l).token===n.token&&await A.promises.unlink(n.file)}}}class F extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportDocumentError"}}function Ef(e={}){const t={maxDocuments:e.maxDocuments??32,maxBytes:e.maxBytes??64e6,maxPages:e.maxPages??1e4,maxPageBytes:e.maxPageBytes??4e6,maxManifestBytes:e.maxManifestBytes??1e6};if(Object.values(t).some(r=>!Number.isSafeInteger(r)||r<1))throw new F("input","文档预算应为正安全整数");return t}function ie(e,t,r){if([e,t,...r===void 0?[]:[r]].some(n=>typeof n!="string"||!n.trim()||n.length>256))throw new F("input","文档 scope、id、version 应为 1–256 位非空字符串");return JSON.stringify([e,t])}function V(e,t,r){return Co(e,{maxBytes:t,maxNodes:t,check:()=>N(r),error:(n,o)=>new F(n==="budget"?"capacity":"input",o)})}function pe(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}function ln(e){if(!e||e.schemaVersion!==ve||"pages"in e||e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean")throw new F("input","文档计划头应使用当前版本,且不得携带 pages")}function Je(e,t){e.bytes=0;for(let r=0;r<8;r++){const n=t+pe(e);if(n===e.bytes)return;e.bytes=n}throw new F("capacity","文档容量统计无效")}function Pf(e,t,r=[]){const n=new Map;let o=0,i=Promise.resolve();for(const f of r){const d=ie(f.scope,f.id,f.version);if(ln(f.plan),n.has(d)||!Number.isSafeInteger(f.bytes)||f.bytes<0||!Number.isSafeInteger(f.pageCount)||f.pageCount<0||f.pageCount>t.maxPages||!["building","complete","failed"].includes(f.state)||f.revision!==f.pageCount+(f.state==="building"?0:1))throw new F("input","文档清单无效");n.set(d,V(f,t.maxManifestBytes)),o+=f.bytes}function s(f,d){if(o-(d?.bytes??0)+f.bytes>t.maxBytes||!d&&n.size>=t.maxDocuments)throw new F("capacity","文档存储容量已满,请显式清理旧文档")}if(n.size>t.maxDocuments||o>t.maxBytes)throw new F("capacity","已存文档超过预算");const a=f=>{const d=i.then(f);return i=d.then(()=>{},()=>{}),d},c=(f,d,l,m)=>{const g=n.get(ie(f,d,l));if(!g)throw new F("missing","文档不存在");if(g.version!==l||m!==void 0&&g.revision!==m)throw new F("conflict","文档已变化,请重新读取清单");return g},u=async(f,d,l)=>{const m=V(f,t.maxManifestBytes);return s(m,d),await e.write(m,l),n.set(ie(f.scope,f.id),m),o+=f.bytes-(d?.bytes??0),V(m,t.maxManifestBytes)};return{create:(f,d)=>{const l=V(f,t.maxManifestBytes,d),m=ie(l.scope,l.id,l.version);return ln(l.plan),a(async()=>{if(N(d),n.has(m))throw new F("conflict","文档已存在,不可覆盖");const g={...l,revision:0,state:"building",pageCount:0,bytes:0};return Je(g,0),u(g)})},append:(f,d,l,m,g,h)=>{const p=V(g,t.maxPageBytes,h),b=Be({pages:[p]});if(!b.ok)throw new F("input",b.errors[0].message);return a(async()=>{N(h);const y=c(f,d,l,m);if(y.state!=="building")throw new F("conflict","已完成文档不可追加");if(y.pageCount>=t.maxPages)throw new F("capacity","文档页数超过预算");const $={...y,revision:m+1,pageCount:y.pageCount+1};return Je($,y.bytes-pe(y)+pe(p)),u($,y,{index:y.pageCount,value:p})})},complete:(f,d,l,m,g,h)=>{const p=g===void 0?void 0:V(g,t.maxManifestBytes,h);return p&&zo({...p}),a(async()=>{N(h);const b=c(f,d,l,m);if(b.state!=="building")throw new F("conflict","文档已完成");if(p&&p.stats.pages!==b.pageCount)throw new F("input","准备结果页数与文档页数不一致");const y={...b,revision:m+1,state:"complete",...p?{metadata:p}:{}};return Je(y,b.bytes-pe(b)),u(y,b)})},fail:(f,d,l,m,g)=>{const h=V(g,4096);if(!h||!["cancelled","generation"].includes(h.code)||typeof h.message!="string"||!h.message.trim()||h.message.length>1024)throw new F("input","文档失败状态无效");return a(async()=>{const p=c(f,d,l,m);if(p.state!=="building")throw new F("conflict","终态文档不可变更");const b={...p,state:"failed",revision:m+1,failure:h};return Je(b,p.bytes-pe(p)),u(b,p)})},read:async(f,d,l)=>{N(l);const m=ie(f,d);await i,N(l);const g=n.get(m);return g?V(g,t.maxManifestBytes):void 0},readPage:(f,d,l,m,g)=>a(async()=>{N(g);const h=c(f,d,l);if(!Number.isSafeInteger(m)||m<0)throw new F("input","页索引应为非负安全整数");if(m>=h.pageCount)return;const p=await e.readPage(f,d,m);if(N(g),!p)throw new F("missing","已提交的文档页缺失");return V(p,t.maxPageBytes,g)}),remove:(f,d,l,m)=>a(async()=>{N(m);const g=ie(f,d,l),h=n.get(g);return h?(c(f,d,l),await e.remove(h),n.delete(g),o-=h.bytes,!0):!1})}}const rr=e=>e?.code,Ye=(e,t)=>le.createHash("sha256").update(ie(e,t)).digest("hex");async function nr(e,t){const r=await A.promises.lstat(e);if(!r.isFile()||r.size>t)throw new F("capacity","文档文件类型或大小无效");return V(JSON.parse(await A.promises.readFile(e,"utf8")),t)}async function dn(e,t){const r=`${e}.pending-${le.randomUUID()}`;try{await A.promises.writeFile(r,JSON.stringify(t),{flag:"wx",mode:384}),await A.promises.rename(r,e)}finally{await A.promises.unlink(r).catch(n=>{if(rr(n)!=="ENOENT")throw n})}}async function Ff(e,t){const r=(await A.promises.readdir(e)).filter(o=>/^[a-f0-9]{64}$/.test(o));if(r.length>t.maxDocuments)throw new F("capacity","文档数量超过目录预算");const n=[];for(const o of r){const i=j.join(e,o);if(!(await A.promises.lstat(i)).isDirectory())throw new F("input","文档目录不允许符号链接");const a=await nr(j.join(i,"manifest.json"),t.maxManifestBytes);if(Ye(a.scope,a.id)!==o||!Number.isSafeInteger(a.pageCount)||a.pageCount<0||a.pageCount>t.maxPages)throw new F("input","文档清单身份或页数无效");let c=pe(a);for(let u=0;u<a.pageCount;u++){const f=await A.promises.lstat(j.join(i,`${u}.json`));if(!f.isFile()||f.size>t.maxPageBytes)throw new F("capacity","文档页文件类型或大小无效");c+=f.size}if(c!==a.bytes)throw new F("input","文档字节数与已提交页不一致");for(const u of await A.promises.readdir(i)){const f=/^(\d+)\.json$/.exec(u);(f&&Number(f[1])>=a.pageCount||/\.pending-[a-f0-9-]{36}$/.test(u))&&await A.promises.unlink(j.join(i,u))}n.push(a)}return n}async function Nf(e){const t=Ef(e),r=j.resolve(e.directory);await A.promises.mkdir(r,{recursive:!0,mode:448});const n=j.join(r,".document-writer-lock"),o=le.randomUUID();let i;try{i=await A.promises.open(n,"wx",384)}catch(l){throw rr(l)==="EEXIST"?new F("conflict","文档目录已被占用;多实例请实现共享存储原子CAS"):l}try{await i.writeFile(JSON.stringify({pid:process.pid,token:o}))}catch(l){throw await i.close(),await A.promises.unlink(n),l}const s=async()=>{try{return(await nr(n,1024)).token===o}catch(l){if(rr(l)==="ENOENT")return!1;throw l}},a=async()=>{if(!await s())throw new F("closed","文档存储写入锁已失效")};let c=Promise.resolve(),u=!1;const f=l=>{if(u)return Promise.reject(new F("closed","文档存储已关闭"));const m=l();return c=Promise.allSettled([c,m]).then(()=>{}),m};let d;try{const l=await Ff(r,t);d=Pf({write:async(m,g)=>{await a();const h=j.join(r,Ye(m.scope,m.id));await A.promises.mkdir(h,{recursive:!0,mode:448}),g&&await dn(j.join(h,`${g.index}.json`),g.value);try{await dn(j.join(h,"manifest.json"),m)}catch(p){throw g?await A.promises.unlink(j.join(h,`${g.index}.json`)):m.revision===0&&await A.promises.rm(h,{recursive:!0}),p}},readPage:async(m,g,h)=>(await a(),nr(j.join(r,Ye(m,g),`${h}.json`),t.maxPageBytes)),remove:async m=>{await a(),await A.promises.rm(j.join(r,Ye(m.scope,m.id)),{recursive:!0})}},t,l)}catch(l){throw await i.close(),await A.promises.unlink(n),l}return{create:(...l)=>f(()=>d.create(...l)),append:(...l)=>f(()=>d.append(...l)),complete:(...l)=>f(()=>d.complete(...l)),fail:(...l)=>f(()=>d.fail(...l)),read:(...l)=>f(()=>d.read(...l)),readPage:(...l)=>f(()=>d.readPage(...l)),remove:(...l)=>f(()=>d.remove(...l)),close:async()=>{u||(u=!0,await c,await i.close(),await s()&&await A.promises.unlink(n))}}}function oi(e){const t=e.filename??e.workerUrl;if(!t||e.filename&&e.workerUrl)throw new TypeError("请且仅请指定 filename 或 workerUrl");return of(()=>{const r=new Se.Worker(t,e.workerOptions);return{postMessage:(n,o)=>r.postMessage(n,o),terminate:()=>r.terminate(),subscribe:(n,o)=>{const i=s=>o(new Error(`报表 Worker 在响应前退出(code ${s})`));return r.on("message",n),r.on("error",o),r.on("messageerror",o),r.on("exit",i),()=>{r.off("message",n),r.off("error",o),r.off("messageerror",o),r.off("exit",i)}}}},e)}function If(e){const t=Se.parentPort;if(!t)throw new Error("serveNodeReportWorker 只能在 worker_threads 中调用");const r=n=>{Zo(n)&&Qo(e,n,o=>t.postMessage({protocol:ne,id:n.id,type:"event",event:o})).then(o=>t.postMessage(o,ei(o)))};return t.on("message",r),()=>t.off("message",r)}function Of(e){return le.createHash("sha256").update(e).digest("hex")}function Rf(e={}){const t={timeoutMs:e.timeoutMs??e.budget?.maxDurationMs,budget:{...e.budget}};return uf(e,r=>oi({filename:typeof __filename=="string"?__filename:new URL(typeof document>"u"?require("url").pathToFileURL(__filename).href:Ft&&Ft.tagName.toUpperCase()==="SCRIPT"&&Ft.src||new URL("server-node.cjs",document.baseURI).href),workerOptions:{workerData:{machReportEncoding:"prepared-v1"}},...t,timeoutMs:r}))}if(Se.parentPort&&Se.workerData?.machReportEncoding==="prepared-v1"){const e=Se.parentPort;e.on("message",t=>{Zo(t)&&ff(t,r=>e.postMessage({protocol:ne,id:t.id,type:"event",event:r})).then(r=>e.postMessage(r,ei(r)))})}exports.ReportWorkerError=Qt;exports.createNodeAutoReportExporter=Rf;exports.createNodeReportExecutor=oi;exports.openFileReportDocumentStore=Nf;exports.openFileReportJobStore=kf;exports.reportArtifactSha256=Of;exports.serveNodeReportWorker=If;