@agile-team/mach-report 2.22.0 → 2.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/README.md +7 -6
  2. package/dist/{ExcelBindingWizard-CZyppD7I.js → ExcelBindingWizard-D4FLind-.js} +3 -3
  3. package/dist/{ExcelBindingWizard-CW79I6Gl.cjs → ExcelBindingWizard-D4RS5Bpg.cjs} +1 -1
  4. package/dist/{ParamEditor-CiYCJI0b.cjs → ParamEditor-C-6C9rd2.cjs} +1 -1
  5. package/dist/{ParamEditor-DQit-Gdf.js → ParamEditor-CASZt-Ma.js} +2 -2
  6. package/dist/{ReportBatchPanel-DKTpV7MU.js → ReportBatchPanel-Bq7t8a5r.js} +2 -2
  7. package/dist/{ReportBatchPanel-Db6TAfG5.cjs → ReportBatchPanel-YVj5IO5y.cjs} +1 -1
  8. package/dist/ReportLabelStudio-Cqhita1b.cjs +1 -0
  9. package/dist/{ReportLabelStudio-BYnRqmje.js → ReportLabelStudio-Dj7GXhuv.js} +295 -292
  10. package/dist/ReportParamPanel-DZbFVmDL.cjs +1 -0
  11. package/dist/{ReportParamPanel-BHSKVL8k.js → ReportParamPanel-Dgmqro1Y.js} +93 -79
  12. package/dist/ReportPreview-DeWzG8jQ.js +6257 -0
  13. package/dist/ReportPreview-FFIryrIr.cjs +6 -0
  14. package/dist/{ReportTemplateLibrary-DEXH07ND.cjs → ReportTemplateLibrary-BaWodmpm.cjs} +1 -1
  15. package/dist/{ReportTemplateLibrary-BZuKn0YK.js → ReportTemplateLibrary-DdAAAD2I.js} +1 -1
  16. package/dist/{RuleEditor-CIQn547x.js → RuleEditor-D2UwQGF6.js} +59 -59
  17. package/dist/{RuleEditor-zSUmPjKa.cjs → RuleEditor-DcT9xI1v.cjs} +1 -1
  18. package/dist/TemplateOutlinePanel-CUHFFiNM.cjs +1 -0
  19. package/dist/{TemplateOutlinePanel-D0PgOSQE.js → TemplateOutlinePanel-DrT7XN0m.js} +2 -2
  20. package/dist/{TemplateReusePanel-BKlAEF8-.js → TemplateReusePanel-4eejkNqi.js} +2 -2
  21. package/dist/{TemplateReusePanel-DAy_Hwqz.cjs → TemplateReusePanel-DZMyiX5I.cjs} +1 -1
  22. package/dist/{TemplateReviewPanel-div-EH_m.js → TemplateReviewPanel-BIhNLeNw.js} +2 -2
  23. package/dist/{TemplateReviewPanel-CowmHaQQ.cjs → TemplateReviewPanel-DnYImiXu.cjs} +1 -1
  24. package/dist/analytics.cjs +1 -1
  25. package/dist/analytics.js +26 -26
  26. package/dist/artifact-integrity.json +106 -104
  27. package/dist/assets-D2gHc4Mz.cjs +1 -0
  28. package/dist/assets-T_gDeFaz.js +132 -0
  29. package/dist/auto-4pK9HePf.cjs +1 -0
  30. package/dist/auto-CTIJ6PnR.js +257 -0
  31. package/dist/capabilities-DiBj4Qgl.cjs +1 -0
  32. package/dist/capabilities-pg7j7VLT.js +106 -0
  33. package/dist/charts-Cjw5AYkg.cjs +1 -0
  34. package/dist/{charts-Dlv8j2AG.js → charts-CxJZ0XaY.js} +1 -1
  35. package/dist/computed-DK6BruFz.cjs +1 -0
  36. package/dist/{computed-C8NRZQss.js → computed-f3pOqWLX.js} +381 -301
  37. package/dist/data-bar-CeZuFmYl.cjs +1 -0
  38. package/dist/{data-bar-8baGYEZ9.js → data-bar-IkI6VvMQ.js} +1 -1
  39. package/dist/designer-DhrE7jzw.js +7169 -0
  40. package/dist/designer-IAZu6kBX.cjs +2 -0
  41. package/dist/designer.cjs +1 -1
  42. package/dist/designer.d.cts +98 -45
  43. package/dist/designer.d.ts +98 -45
  44. package/dist/designer.js +3 -3
  45. package/dist/dom-ChE5D-L-.cjs +1 -0
  46. package/dist/dom-JWrchIre.js +452 -0
  47. package/dist/dom-cell-address-DLD1mkTB.cjs +1 -0
  48. package/dist/dom-cell-address-Fn-8nk7D.js +11 -0
  49. package/dist/{encoding-ncQAvyOv.cjs → encoding-BefcaHdp.cjs} +1 -1
  50. package/dist/{encoding-DbnhbwI8.js → encoding-CL6rXEkR.js} +2 -2
  51. package/dist/{font-loader-Di0lQKFf.js → font-loader-BT5baV-o.js} +1 -1
  52. package/dist/{font-loader-BB372_XN.cjs → font-loader-Ga51c2VC.cjs} +1 -1
  53. package/dist/grid-strokes-Be24LGuV.cjs +1 -0
  54. package/dist/grid-strokes-EoY66L2f.js +53 -0
  55. package/dist/index.cjs +8 -8
  56. package/dist/index.d.cts +6 -1
  57. package/dist/index.d.ts +6 -1
  58. package/dist/index.js +944 -1259
  59. package/dist/json-snapshot-1tvQNzQE.cjs +2 -0
  60. package/dist/{json-snapshot-DvQbZlD7.js → json-snapshot-OqkPyUk5.js} +763 -776
  61. package/dist/matrix-B8QWbsGM.cjs +1 -0
  62. package/dist/matrix-C6e_r_vp.js +302 -0
  63. package/dist/{pdf-CARdBcuw.cjs → pdf-HiEeXe9H.cjs} +42 -42
  64. package/dist/{pdf-DmlnL5eB.js → pdf-aobetCsy.js} +20 -20
  65. package/dist/pdf.cjs +1 -1
  66. package/dist/pdf.js +2 -2
  67. package/dist/{plugin-AcAQ2m9X.cjs → plugin-BFANt-i8.cjs} +1 -1
  68. package/dist/{plugin-w5Nyt08U.js → plugin-DeYYAL6F.js} +1 -1
  69. package/dist/{prefill-BXBxx5We.js → prefill-Dk4C6S5R.js} +21 -21
  70. package/dist/prefill-DsUD5OoK.cjs +1 -0
  71. package/dist/prepared-DCIxhKFo.js +94 -0
  72. package/dist/prepared-Dv-XM3i1.cjs +1 -0
  73. package/dist/progress-ByiOxUD3.js +250 -0
  74. package/dist/progress-WomPRP3B.cjs +1 -0
  75. package/dist/{protocol-C9ZaylID.cjs → protocol-B9YgfQ_d.cjs} +1 -1
  76. package/dist/{protocol-fjaeKkjf.js → protocol-DxeUKGYG.js} +3 -3
  77. package/dist/record-bindings-DatJZv_e.js +200 -0
  78. package/dist/record-bindings-MBxbeBsi.cjs +1 -0
  79. package/dist/{region-binding-workflow-aA8nxmkZ.js → region-binding-workflow-DjrXuR1q.js} +2 -2
  80. package/dist/{region-binding-workflow-BiJQ7NU6.cjs → region-binding-workflow-l7NGfagJ.cjs} +2 -2
  81. package/dist/report-encoding-worker.cjs +1 -1
  82. package/dist/report-encoding-worker.js +1 -1
  83. package/dist/rich-text-layout-Ciwa6D2o.js +52 -0
  84. package/dist/rich-text-layout-DK7A_a5r.cjs +3 -0
  85. package/dist/{runtime-BTtpjF3D.js → runtime-75Y5Oq5B.js} +52 -51
  86. package/dist/runtime-DKlGd_D4.cjs +1 -0
  87. package/dist/sbom.cdx.json +1 -1
  88. package/dist/server-node.cjs +5 -5
  89. package/dist/server-node.js +1642 -1586
  90. package/dist/server.cjs +1 -1
  91. package/dist/server.js +24 -24
  92. package/dist/style.css +1 -1
  93. package/dist/{template-catalog-JSxSqk5y.js → template-catalog--cjxzgH7.js} +17 -17
  94. package/dist/template-catalog-CoT7jm_6.cjs +1 -0
  95. package/dist/{template-fragments-D2JFj7Du.js → template-fragments-CPpGpQoz.js} +12 -12
  96. package/dist/template-fragments-GVjpew_q.cjs +1 -0
  97. package/dist/template-registry-DI59PXVK.cjs +1 -0
  98. package/dist/{template-registry-Do1Uav2Z.js → template-registry-O0hNIOfB.js} +17 -17
  99. package/dist/{template-serialization-CU4n_Miu.js → template-serialization-CWmHq7lX.js} +1 -1
  100. package/dist/{template-serialization-CgqBo6s-.cjs → template-serialization-CqQY4zDg.cjs} +1 -1
  101. package/dist/{textwrap-CkGjRFT3.js → textwrap-BIjtEWmq.js} +1 -1
  102. package/dist/textwrap-Cy7o1hIR.cjs +4 -0
  103. package/dist/vue/async.d.cts +24 -0
  104. package/dist/vue/async.d.ts +24 -0
  105. package/dist/vue/index.d.cts +25 -1
  106. package/dist/vue/index.d.ts +25 -1
  107. package/dist/vue-async.cjs +1 -1
  108. package/dist/vue-async.js +3 -3
  109. package/dist/vue.cjs +1 -1
  110. package/dist/vue.js +52 -47
  111. package/dist/{workbook-session-BvEBRRMz.cjs → workbook-session-C6-SrnCT.cjs} +4 -4
  112. package/dist/{workbook-session-f0wVlzst.js → workbook-session-C9ZmCBwY.js} +15 -16
  113. package/dist/worker.cjs +1 -1
  114. package/dist/worker.js +4 -4
  115. package/dist/xlsx.cjs +4 -4
  116. package/dist/xlsx.js +184 -179
  117. package/package.json +1 -1
  118. package/dist/ReportLabelStudio-B0i9ohQj.cjs +0 -1
  119. package/dist/ReportParamPanel-lngONOEz.cjs +0 -1
  120. package/dist/ReportPreview-BDgKssYR.js +0 -5887
  121. package/dist/ReportPreview-Dw-4icG6.cjs +0 -6
  122. package/dist/TemplateOutlinePanel-B5SfGYVN.cjs +0 -1
  123. package/dist/assets-CxHunY_9.js +0 -232
  124. package/dist/assets-vbjAGgk8.cjs +0 -1
  125. package/dist/auto-DcUHlKob.cjs +0 -1
  126. package/dist/auto-moShblh1.js +0 -240
  127. package/dist/charts-aCtoswXq.cjs +0 -1
  128. package/dist/component-tree-1_QCiQJX.js +0 -67
  129. package/dist/component-tree-BjZIp6w9.cjs +0 -1
  130. package/dist/computed-4TnxzgIh.cjs +0 -1
  131. package/dist/data-bar-YltqGTaC.cjs +0 -1
  132. package/dist/designer-B7jJeAeG.js +0 -6914
  133. package/dist/designer-BWQVpJeN.cjs +0 -2
  134. package/dist/grid-geometry-D3SJgWFv.js +0 -136
  135. package/dist/grid-geometry-D8ReblRV.cjs +0 -1
  136. package/dist/json-snapshot-nyV63AbB.cjs +0 -2
  137. package/dist/matrix-0hywp0-F.cjs +0 -1
  138. package/dist/matrix-Dy-tyY7E.js +0 -381
  139. package/dist/prefill-DUvejVt1.cjs +0 -1
  140. package/dist/prepared-YXy-fVLw.cjs +0 -1
  141. package/dist/prepared-rXCKqdHY.js +0 -88
  142. package/dist/progress-B0ctFpKf.cjs +0 -1
  143. package/dist/progress-Hc2vxoCs.js +0 -52
  144. package/dist/record-bindings-Ct1HkPrc.cjs +0 -1
  145. package/dist/record-bindings-VZGS-Qd8.js +0 -155
  146. package/dist/rich-text-layout-K48VHUoW.cjs +0 -3
  147. package/dist/rich-text-layout-wxBhnAS7.js +0 -102
  148. package/dist/runtime-Dq0LUsyS.cjs +0 -1
  149. package/dist/template-catalog-CLAM4w7H.cjs +0 -1
  150. package/dist/template-fragments-Ca25Jt7e.cjs +0 -1
  151. package/dist/template-outline-CDWXptuj.js +0 -88
  152. package/dist/template-outline-K4jGhATu.cjs +0 -1
  153. package/dist/template-registry-CWnuGqyP.cjs +0 -1
  154. package/dist/textwrap-OTOUMr4f.cjs +0 -4
@@ -1,6 +1,6 @@
1
- "use strict";var Xi=Object.create;var rn=Object.defineProperty;var Zi=Object.getOwnPropertyDescriptor;var Qi=Object.getOwnPropertyNames;var es=Object.getPrototypeOf,ts=Object.prototype.hasOwnProperty;var rs=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qi(t))!ts.call(e,o)&&o!==r&&rn(e,o,{get:()=>t[o],enumerable:!(n=Zi(t,o))||n.enumerable});return e};var Ye=(e,t,r)=>(r=e!=null?Xi(es(e)):{},rs(t||!e||!e.__esModule?rn(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const me=require("./progress-DJBd9Rb9.cjs"),Ne=require("node:worker_threads"),ge=require("node:crypto"),A=require("node:fs"),D=require("node:path");var zt=typeof document<"u"?document.currentScript:null;const Pt=1.35,Sr=10.5,zn='"Microsoft YaHei", sans-serif',ns="1.0.0-mach",ze=ns,Vn=/[\u3000-\u9fff\uff00-\uffef]/,ye=new Uint8Array(128);{for(const e of"iljtf.,:;'`|!()[]")ye[e.charCodeAt(0)]=1;for(const e of"mwMW@")ye[e.charCodeAt(0)]=2;for(let e=48;e<=57;e++)ye[e]=3;for(let e=65;e<=90;e++)ye[e]=4;ye[32]=5}const os=[.54,.26,.95,.59,.67,.3];function is(e){const t=e.charCodeAt(0);return t<128?os[ye[t]]:Vn.test(e)?1:/[A-Z]/.test(e)?.67:.54}const Er={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+=is(a);return n&&(s*=1.04),(s*r+o*Math.max(0,Array.from(e).length-1))*i}};function ss(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===`
1
+ "use strict";var Qi=Object.create;var nn=Object.defineProperty;var es=Object.getOwnPropertyDescriptor;var ts=Object.getOwnPropertyNames;var rs=Object.getPrototypeOf,ns=Object.prototype.hasOwnProperty;var os=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ts(t))!ns.call(e,o)&&o!==r&&nn(e,o,{get:()=>t[o],enumerable:!(n=es(t,o))||n.enumerable});return e};var Ye=(e,t,r)=>(r=e!=null?Qi(rs(e)):{},os(t||!e||!e.__esModule?nn(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const he=require("./progress-DJBd9Rb9.cjs"),Ne=require("node:worker_threads"),pe=require("node:crypto"),A=require("node:fs"),L=require("node:path");var Jt=typeof document<"u"?document.currentScript:null;const Pt=1.35,Sr=10.5,Hn='"Microsoft YaHei", sans-serif',is="1.0.0-mach",Je=is,Un=/[\u3000-\u9fff\uff00-\uffef]/,we=new Uint8Array(128);{for(const e of"iljtf.,:;'`|!()[]")we[e.charCodeAt(0)]=1;for(const e of"mwMW@")we[e.charCodeAt(0)]=2;for(let e=48;e<=57;e++)we[e]=3;for(let e=65;e<=90;e++)we[e]=4;we[32]=5}const ss=[.54,.26,.95,.59,.67,.3];function as(e){const t=e.charCodeAt(0);return t<128?ss[we[t]]:Un.test(e)?1:/[A-Z]/.test(e)?.67:.54}const Er={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+=as(a);return n&&(s*=1.04),(s*r+o*Math.max(0,Array.from(e).length-1))*i}};function cs(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
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(Vn.test(s)){i(),n.push({text:s,widthMm:r.measureMm(s,t),cjk:!0});continue}o+=s}return i(),n}function Ve(e,t,r,n=Er){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 ss(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 as=4096,nn=128*1024;function cs(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<=nn){for(;t.size>=as||r+i.length>nn;){const c=t.keys().next().value;r-=c.length,t.delete(c)}t.set(i,a),r+=i.length}return a}}}const at=1e3;function he(e){if(!Number.isSafeInteger(e)||e<0||e>at*2)throw new Error("十进制精度超出预算");return 10n**BigInt(e)}function Ft(e){if(e.coefficient.toString().length>at*2||e.scale>at*2)throw new Error("十进制结果超出精度预算");return e}function V(e){if(typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("十进制参数必须是有限数字或十进制文本");const t=String(e);if(t.length>at)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 Ft(i<0?{coefficient:s*he(-i),scale:0}:{coefficient:s,scale:i})}function Hn(e,t){const r=Math.max(e.scale,t.scale);return[e.coefficient*he(r-e.scale),t.coefficient*he(r-t.scale),r]}function ct(e,t){const[r,n]=Hn(e,t);return r<n?-1:r>n?1:0}function ut(e,t){const[r,n,o]=Hn(e,t);return Ft({coefficient:r+n,scale:o})}function Ar(e,t){return Ft({coefficient:e.coefficient*t.coefficient,scale:e.scale+t.scale})}function Un(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 He(e){if(!Number.isInteger(e)||e<0||e>100)throw new Error("十进制小数位应为 0–100 的整数")}function tr(e,t,r=20){if(He(r),t.coefficient===0n)throw new Error("不能除以零");const n=t.scale-e.scale+r,o=e.coefficient*he(Math.max(0,n)),i=t.coefficient*he(Math.max(0,-n));return Ft({coefficient:Un(o,i),scale:r})}function Ot(e,t){let r=e.coefficient,n=e.scale;t!==void 0&&(He(t),r=t>=n?r*he(t-n):Un(r,he(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 on(e,t,r=!1,n=!1){let o=V(e);n&&(o=Ar(o,{coefficient:100n,scale:0}));const[i,s]=Ot(o,t).split(".");return`${r?i.replace(/\B(?=(\d{3})+(?!\d))/g,","):i}${s===void 0?"":`.${s}`}${n?"%":""}`}const Gn=new Set(["__proto__","prototype","constructor"]);function Yn(e){if(!e||typeof e!="object"||Array.isArray(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new Error("条件应为普通声明式对象");for(const[t,r]of Object.entries(Object.getOwnPropertyDescriptors(e)))if(Gn.has(t)||!Object.prototype.hasOwnProperty.call(r,"value"))throw new Error("条件不允许访问器或不安全属性")}function sn(e){if(typeof e!="string"||!e.trim()||e.length>512||Gn.has(e))throw new Error("条件字段应为安全的非空字段名")}function Vt(e){if(e!==null&&typeof e!="boolean"&&typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("条件常量应为有限 JSON 标量");if(typeof e=="string"&&e.length>16384)throw new Error("条件文本超出预算")}function rr(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))throw new Error("日期条件使用 YYYY-MM-DD 日历日");const[t,r,n]=e.split("-").map(Number),o=new Date(0);if(o.setUTCFullYear(t,r-1,n),o.setUTCHours(0,0,0,0),o.getUTCFullYear()!==t||o.getUTCMonth()!==r-1||o.getUTCDate()!==n)throw new Error("无效日历日");return e}function an(e){return["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function cn(e){return e==null||e===""}function us(e){const t=e.values?.[0]??(e.right&&"value"in e.right?e.right.value:e.value);return e.valueType??e.numeric??(typeof t=="number"?"decimal":typeof t=="boolean"?"boolean":"text")}function Qe(e,t,r){if(cn(e)||cn(t))return;const n=us(r);try{if(n==="decimal")return ct(V(e),V(t));if(n==="number")return!["number","string"].includes(typeof e)||!["number","string"].includes(typeof t)?void 0:ct(V(e),V(t));if(n==="date"&&(e=rr(e),t=rr(t)),n==="boolean"&&(typeof e!="boolean"||typeof t!="boolean")||n==="text"&&(!an(e)||!an(t)))return;const o=String(e),i=String(t);return o<i?-1:o>i?1:0}catch{return}}function fs(e){if(sn(e.field),![">",">=","<","<=","==","!=","between","contains","isNull","isNotNull"].includes(e.op))throw new Error("未知条件运算符");if(e.numeric!==void 0&&!["number","decimal"].includes(e.numeric))throw new Error("未知条件数值模式");if(e.valueType!==void 0&&!["number","decimal","text","date","boolean"].includes(e.valueType))throw new Error("未知条件值类型");if(!(e.op==="isNull"||e.op==="isNotNull"))if(e.op==="between"){if(!Array.isArray(e.values)||e.values.length!==2||Object.keys(e.values).length!==2)throw new Error("范围条件需要两个明确边界");e.values.forEach(Vt);const t=Qe(e.values[0],e.values[1],e);if(t===void 0||t>0)throw new Error("范围边界无效或顺序颠倒")}else if(e.right!==void 0){if(Yn(e.right),Object.keys(e.right).length!==1)throw new Error("条件 right 只能指定一个 field 或 value");if("field"in e.right?sn(e.right.field):Vt(e.right.value),e.value!==void 0)throw new Error("条件不能同时指定 value 和 right")}else Vt(e.value)}function Ht(e,t){if(t===void 0)return!1;switch(e){case">":return t>0;case">=":return t>=0;case"<":return t<0;case"<=":return t<=0;case"==":return t===0;case"!=":return t!==0;default:return!1}}function ls(e){fs(e),e={...e,right:e.right?{...e.right}:void 0,values:e.values?[e.values[0],e.values[1]]:void 0};const t=(r,n)=>Object.prototype.hasOwnProperty.call(r,n)?r[n]:void 0;return r=>{const n=t(r,e.field);if(e.op==="isNull")return n==null;if(e.op==="isNotNull")return n!=null;if(e.op==="between")return Ht(">=",Qe(n,e.values[0],e))&&Ht("<=",Qe(n,e.values[1],e));const o=e.right?"field"in e.right?t(r,e.right.field):e.right.value:e.value;return e.op==="contains"?typeof n=="string"&&typeof o=="string"&&n.includes(o):Ht(e.op,Qe(n,o,e))}}function q(e,t={nodes:0},r=0){if(++t.nodes>256||r>16)throw new Error("条件超出深度或节点预算");if(Yn(e),["all","any","not","field"].filter(o=>Object.prototype.hasOwnProperty.call(e,o)).length!==1)throw new Error("条件只能指定一种组合或比较");if("not"in e){const o=q(e.not,t,r+1);return i=>!o(i)}if("all"in e||"any"in e){const o="all"in e?e.all:e.any;if(!Array.isArray(o)||o.length<1||o.length>256||Object.keys(o).length!==o.length)throw new Error("组合条件需要有界、无空位的非空数组");const i=o.map(s=>q(s,t,r+1));return"all"in e?s=>i.every(a=>a(s)):s=>i.some(a=>a(s))}return ls(e)}function ds(e){q(e);const t=new Set;function r(n){"all"in n?n.all.forEach(r):"any"in n?n.any.forEach(r):"not"in n?r(n.not):(t.add(n.field),n.right&&"field"in n.right&&t.add(n.right.field))}return r(e),[...t]}function qn(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 ms(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 nr(e,t){return e.toLocaleString("en-US",{minimumFractionDigits:t,maximumFractionDigits:t})}function hs(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 gs(e,t,r){return r!=null?t?nr(e,r):e.toFixed(r):t?nr(e):String(e)}function un(e){const t=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(t)?t:null}function kr(e,t){if(e==null||e===""||!t)return String(e??"");switch(t.kind){case"number":{if(typeof e=="string")try{return on(e,t.digits,t.thousands===!0)}catch{return e}const r=un(e);return r==null?String(e):gs(r,t.thousands===!0,t.digits)}case"percent":{if(typeof e=="string")try{return on(e,t.digits??2,!0,!0)}catch{return e}const r=un(e);return r==null?String(e):`${nr(r*100,t.digits??2)}%`}case"date":{const r=t.pattern??"YYYY-MM-DD",n=e instanceof Date?e:ms(String(e));return n?hs(n,r):String(e)}default:return String(e)}}const ps=[{name:"add",minArgs:2,maxArgs:256,input:"numeric",output:"numeric",example:"add(quantity, adjustment)"},{name:"subtract",minArgs:2,maxArgs:2,input:"numeric",output:"numeric",example:"subtract(input, output)"},{name:"multiply",minArgs:2,maxArgs:256,input:"numeric",output:"numeric",example:"multiply(quantity, price)"},{name:"divide",minArgs:2,maxArgs:2,input:"numeric",output:"numeric",example:"divide(amount, quantity)"},{name:"coalesce",minArgs:2,maxArgs:256,input:"scalar",output:"scalar",example:"coalesce(actual, planned)"},{name:"if",minArgs:2,maxArgs:2,input:"condition + branches",output:"scalar",example:"if(quantity > 0, divide(amount, quantity), null)"},{name:"round",minArgs:1,maxArgs:2,input:"numeric, digits?",output:"numeric",example:"round(amount, 2)"},{name:"abs",minArgs:1,maxArgs:1,input:"numeric",output:"numeric",example:"abs(difference)"},{name:"concat",minArgs:2,maxArgs:256,input:"text",output:"text",example:"concat(plant, '-' , heat)"},{name:"trim",minArgs:1,maxArgs:1,input:"text",output:"text",example:"trim(heat)"},{name:"upper",minArgs:1,maxArgs:1,input:"text",output:"text",example:"upper(grade)"},{name:"lower",minArgs:1,maxArgs:1,input:"text",output:"text",example:"lower(code)"},{name:"dateYear",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateYear(reportDate)"},{name:"dateMonth",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateMonth(reportDate)"},{name:"dateDay",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateDay(reportDate)"}],ys=Object.freeze(ps.map(e=>Object.freeze(e)));function ws(e,t,r,n,o){if(t.some(a=>a==null)){if(o==="error")throw new Error("函数参数包含空值");return null}if(e==="round"||e==="abs")return bs(e,t,r,n);if(e.startsWith("date")){const a=rr(t[0]);return Number(a.slice(e==="dateYear"?0:e==="dateMonth"?5:8,e==="dateYear"?4:e==="dateMonth"?7:10))}if(t.some(a=>typeof a!="string"))throw new Error("文本函数只接受文本,不隐式转换数字或空值");if(t.reduce((a,c)=>a+c.length,0)>1e6)throw new Error("计算文本超出长度预算");const i=t[0],s=e==="concat"?t.join(""):e==="trim"?i.trim():e==="upper"?i.toUpperCase():i.toLowerCase();if(s.length>1e6)throw new Error("计算文本超出长度预算");return s}function bs(e,t,r,n){const o=t[0];if(r!=="decimal"&&(typeof o!="number"||!Number.isFinite(o)))throw new Error("普通数值函数需要有限数字");const i=V(o);e==="abs"&&(i.coefficient=i.coefficient<0n?-i.coefficient:i.coefficient);const s=e==="round"?t.length===2?t[1]:n??0:n;if(s!==void 0){if(typeof s!="number")throw new Error("小数位必须为数字");He(s)}const a=Ot(i,s),c=Number(a);if(r!=="decimal"&&!Number.isFinite(c))throw new Error("计算结果不是有限数字");return r==="decimal"?a:c}const xs=["sum","count","avg","min","max","weightedAvg"];function fn(e){if(typeof e!="number"||!Number.isFinite(e))throw new Error("聚合度量必须是有限数字,不能隐式转换;小数文本请显式选择 decimal");return e}function ft(e,t){return t&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function vs(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=ft(c,e.field);if(e.op==="count"){(!e.field||u!=null)&&t++;return}if(u==null)return;const f=fn(u),d=e.op==="weightedAvg"?ft(c,e.weightField):1;if(d==null)return;const l=fn(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 Ms(e){let t=0,r=V("0"),n=V("0"),o,i;return{add(s){const a=ft(s,e.field);if(e.op==="count"){(!e.field||a!=null)&&t++;return}if(a==null)return;const c=e.op==="weightedAvg"?ft(s,e.weightField):"1";if(c==null)return;const u=V(a),f=V(c);if(e.op==="weightedAvg"&&f.coefficient<0n)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&(r=ut(r,Ar(u,f))),e.op==="weightedAvg"&&(n=ut(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=tr(r,V(t),e.digits)),e.op==="weightedAvg"&&(s=tr(r,n,e.digits)),Ot(s,e.digits)}}}function oe(e){if(e.digits!==void 0&&He(e.digits),e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal")throw new Error("未知聚合数值模式");if(!xs.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"?Ms(e):vs(e)}function Be(e,t){const r=oe(t);for(const n of e)r.add(n);return r.value()}const $s=new Set(["__proto__","prototype","constructor"]);function K(e){if(typeof e!="string"||!e.trim()||$s.has(e))throw new Error("计算字段应为安全的非空字段名")}function Nr(e){return e===null||["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function Ss(e){if(e.some(t=>typeof t!="number"||!Number.isFinite(t)))throw new Error("算术参数必须是有限数字;空值和小数文本不会隐式转换");return e}function Es(e,t){const r=Ss(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 As(e,t,r){const n=t.map(V);let o;return e==="add"?o=n.reduce(ut):e==="multiply"?o=n.reduce(Ar):e==="subtract"?o=ut(n[0],{...n[1],coefficient:-n[1].coefficient}):o=tr(n[0],n[1],r),Ot(o,r)}function ks(e,t,r){return r.nulls!=="error"&&t.some(n=>n==null)||e==="divide"&&r.divisionByZero==="null"&&(r.numeric==="decimal"?V(t[1]).coefficient===0n:t[1]===0)?null:r.numeric==="decimal"?As(e,t,r.digits):Es(e,t)}function Ns(e,t){e.field!==void 0&&K(e.field),e.weightField!==void 0&&K(e.weightField);const r={op:e.aggregate,field:e.field,weightField:e.weightField,numeric:t.numeric,digits:t.digits};Be([],r);const n=new WeakMap;return o=>{let i=n.get(o.rows);if(!i){try{i={value:Be(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 Ps(e,t){for(const r of e){const n=r(t);if(n!=null)return n}return null}function Pr(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 Ns(e,t);if("field"in e){K(e.field);const o=e.field;return({row:i})=>Object.prototype.hasOwnProperty.call(i,o)?i[o]:void 0}if("value"in e){if(!Nr(e.value))throw new Error("常量应为有限 JSON 标量");return()=>e.value}return Fs(e,t,r,n)}function Fs(e,t,r,n){const o=ys.find(a=>a.name===e.op);if(!o||!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<o.minArgs||e.args.length>o.maxArgs)throw new Error("运算参数数量不正确");const i=e.op==="if"?q(e.condition,r,n+1):void 0;if(e.op!=="if"&&e.condition!==void 0)throw new Error("仅 IF 运算接受 condition");const s=e.args.map(a=>Pr(a,t,r,n+1));return i?a=>s[i(a.row)?0:1](a):["add","subtract","multiply","divide","coalesce"].includes(e.op)?e.op==="coalesce"?a=>Ps(s,a):a=>ks(e.op,s.map(c=>c(a)),t):a=>ws(e.op,s.map(c=>c(a)),t.numeric,t.digits,t.nulls)}function Os(e){Pr(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),n.condition&&ds(n.condition).forEach(o=>t.add(o)))};return r(e),[...t]}const Rs=16,or=1024*1024,ln=5e5,lt=new WeakMap,le=Symbol("uncacheable-computation-definition");function et(e,t,r=0){if(++t.nodes>1e4||r>32)throw le;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>or)throw le;return["string",e]}if(typeof e!="object")throw le;if(Array.isArray(e)){if(Object.getPrototypeOf(e)!==Array.prototype||Object.keys(e).length!==e.length)throw le;return["array",Array.from({length:e.length},(n,o)=>et(dn(e,String(o)),t,r+1))]}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw le;return["object",Object.keys(e).map(n=>[et(n,t,r+1),et(dn(e,n),t,r+1)])]}function dn(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw le;return r.value}function Is(e){try{return JSON.stringify(et(e,{nodes:0,units:0}))}catch(t){if(t!==le)throw t;return}}function Cs(e){lt.set(e,{programs:new Map,units:0,slots:0})}function Ts(e,t){const r=lt.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})}lt.set(t,n)}function js(e,t,r){const n=lt.get(e);if(!n||t.some(u=>typeof u.expression=="string"))return;const o=Is(t);if(o===void 0||o.length>or)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<=ln};if(!c.cacheRows)return c;for(;n.programs.size>=Rs||n.units+o.length>or||n.slots+a>ln;){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 Ds(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 Ls(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 Bs(e){if(K(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&&He(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 字段");_s(e)}function _s(e){if(e.groupBy!==void 0){if(!Array.isArray(e.groupBy)||e.groupBy.length>16)throw new Error("计算分组最多 16 级");e.groupBy.forEach(K)}if(e.dependsOn!==void 0){if(!Array.isArray(e.dependsOn)||e.dependsOn.length>2048)throw new Error("计算依赖超出预算");e.dependsOn.forEach(K)}}function Fr(e){return[...new Set([...typeof e.expression=="string"?e.dependsOn??[]:Os(e.expression),...e.groupBy??[]])]}function Xn(e){if(!Array.isArray(e)||e.length>2048)throw new Error("计算字段应为数组且最多2048项");const t=new Map;for(const s of e){if(Bs(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 Fr(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 Ks(e){try{const t=Xn(e);return{valid:!0,errors:[],order:t.map(r=>r.field),fields:e.map(r=>({field:r.field,dependencies:Fr(r),scope:r.scope??"row"}))}}catch(t){return{valid:!1,errors:[t instanceof Error?t.message:String(t)],fields:[],order:[]}}}function mn(e){return Xn(e.fields).map(t=>{const r=Fr(t);if(typeof t.expression!="string")return{definition:t,dependencies:r,read:Pr(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 Ws(e,t){return JSON.stringify(t.map(r=>{const n=Object.prototype.hasOwnProperty.call(e,r)?e[r]:null;if(n!=null&&!Nr(n))throw new Error("分组字段应为有限 JSON 标量");return[typeof n,n??null]}))}function Js(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=Ws(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 zs(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 hn(e){if(e?.aborted){const t=new Error("数据计算已取消");throw t.name="AbortError",t}}function Vs(e,t,r,n,o,i){try{const s=e.read({row:t,rowIndex:r,rows:n});if(s!==void 0&&!Nr(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 Hs(e,t,r,n,o,i,s,a){const c=Ds(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;Vs(r,n,o,i,s,a),Ls(e,t,r,n,a.length>u?a[a.length-1]:void 0)}function Rt(e,t){zs(e,t),hn(t.signal);const r=js(e,t.fields,()=>mn(t)),n={program:r,writes:new WeakMap},o=r?.fields??mn(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=Js(s,a.definition);s.forEach((u,f)=>{hn(t.signal),Hs(n,e[f],a,u,f,c(u),t,i)})}return{rows:s,issues:i}}function Pe(e,t,r){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype||e.length>t)throw new TypeError(`${r}应为有界普通数组`);if(Reflect.ownKeys(e).length!==e.length+1)throw new TypeError(`${r}不支持自定义数组方法或迭代器`);const n=[];for(let o=0;o<e.length;o++){const i=Object.getOwnPropertyDescriptor(e,String(o));if(!i||!Object.prototype.hasOwnProperty.call(i,"value"))throw new TypeError(`${r}不支持空洞或访问器`);n.push(i.value)}return n}const $e=["#2563eb","#0d9488","#d97706","#7c3aed","#dc2626","#0284c7"];function Us(e){if(!["bar","line","stackedBar","percentBar"].includes(e.type))throw new Error("未知图表类型");if(!Array.isArray(e.categories)||!Array.isArray(e.series)||!e.categories.length||e.categories.length>200||!e.series.length||e.series.length>12)throw new Error("图表支持 1–200 个分类、1–12 个系列;大数据应先聚合");const t=Pe(e.categories,200,"图表分类"),r=Pe(e.series,12,"图表系列").map(n=>({...n,values:Pe(n?.values,200,"图表数值")}));for(const n of t)if(typeof n!="string")throw new Error("图表分类应为字符串");Gs(e);for(const n of r)Ys(n,t.length);return{...e,categories:t,series:r}}function Gs(e){for(const t of["leftMm","topMm","widthMm","heightMm"])if(!Number.isFinite(e[t])||e[t]<0)throw new Error(`${t} 应为有限非负数`);if(e.widthMm<45||e.heightMm<35)throw new Error("图表至少需要 45×35mm");if(!Number.isFinite(e.leftMm+e.widthMm)||!Number.isFinite(e.topMm+e.heightMm))throw new Error("图表几何范围溢出")}function Ys(e,t){if(!e||typeof e.name!="string"||!Array.isArray(e.values)||e.values.length!==t)throw new Error("图表系列应提供名称及逐分类的有限数字或 null");for(const r of e.values)if(r!==null&&!Number.isFinite(r))throw new Error("图表系列应提供名称及逐分类的有限数字或 null");if(e.color!==void 0&&!/^#[\da-f]{6}$/i.test(e.color))throw new Error("图表颜色应为 #RRGGBB")}function ir(e,t,r,n,o,i=.8){return{kind:"line",leftMm:Math.min(e,r),topMm:Math.min(t,n),widthMm:Math.abs(r-e),heightMm:Math.abs(n-t),lineDirection:n<t?"up":"down",style:{lineColor:o,lineWidthPt:i}}}function we(e,t,r,n,o="center"){return{kind:"text",text:e,leftMm:t,topMm:r,widthMm:n,heightMm:5,style:{fontSize:8,color:"#475569",align:o,verticalAlign:"middle"}}}function dt(e){return Number(e.toPrecision(5)).toString()}function qs(e){let t=0,r=0;const n=Zn(e)?Xs(e):void 0;if(n)t=n.min,r=n.max;else for(const d of e.series)for(const l of d.values)l!==null&&(t=Math.min(t,l),r=Math.max(r,l));t===r&&(r=t+1);const o=e.leftMm+13,i=e.topMm+8,s=e.widthMm-17,a=e.heightMm-23,c=Math.max(Math.abs(t),Math.abs(r),1),u=t/c,f=r/c-u;return{left:o,top:i,width:s,height:a,min:t,max:r,y:d=>i+a*(1-(d/c-u)/f)}}function Zn(e){return e.type==="stackedBar"||e.type==="percentBar"}function Xs(e){let t=0,r=e.type==="percentBar"?100:0;for(let n=0;n<e.categories.length;n++){let o=0,i=0;for(const s of e.series){const a=s.values[n]??0;a<0?i+=a:o+=a}if(!Number.isFinite(o)||!Number.isFinite(i))throw new Error("图表堆叠合计溢出,请先明确缩放单位");t=Math.min(t,i),r=Math.max(r,o)}return{min:t,max:r}}function Zs(e){if(e.type!=="percentBar")return e;const t=e.categories.map((r,n)=>{let o=0;for(const i of e.series){const s=i.values[n];if(s!==null&&s<0)throw new Error("占比图需要非负度量,负数口径应由业务明确处理");o=Math.max(o,s??0)}return{scale:o,total:o?e.series.reduce((i,s)=>i+(s.values[n]??0)/o,0):0}});return{...e,series:e.series.map(r=>({...r,values:r.values.map((n,o)=>{if(n===null)return null;const{scale:i,total:s}=t[o];return i&&s?n/i/s*100:0})}))}}function Qs(e,t){const r=[],n=t.width/e.categories.length;return e.categories.forEach((o,i)=>{let s=0,a=0;e.series.forEach((c,u)=>{const f=c.values[i];if(f==null)return;const d=f<0?a:s,l=d+f;f<0?a=l:s=l;const m=Math.min(t.y(d),t.y(l)),h=Math.abs(t.y(l)-t.y(d)),p=c.color??$e[u%$e.length],w=t.left+n*(i+.15),y=n*.7;r.push({kind:"rect",leftMm:w,topMm:m,widthMm:y,heightMm:h,style:{backgroundColor:p,borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}}),e.showValues&&h>=5&&r.push({...we(e.type==="percentBar"?`${dt(f)}%`:dt(f),w,m+h/2-2.5,y),style:{fontSize:7,color:"#ffffff",align:"center"}})})}),r}function ea(e,t){const r=[];e.title&&r.push({...we(e.title,e.leftMm,e.topMm,e.widthMm),style:{fontSize:10,bold:!0,align:"left"}});for(let i=0;i<=4;i++){const s=i/4,a=t.min*(1-s)+t.max*s,c=t.y(a);r.push(ir(t.left,c,t.left+t.width,c,"#e2e8f0",.4),we(`${dt(a)}${e.type==="percentBar"?"%":""}`,e.leftMm,c-2.5,11,"right"))}r.push(ir(t.left,t.top,t.left,t.top+t.height,"#94a3b8"));const n=Math.max(1,Math.ceil(e.categories.length/Math.max(1,Math.floor(t.width/14))));e.categories.forEach((i,s)=>{s%n===0&&r.push(we(i,t.left+(s+.5)*t.width/e.categories.length-7,t.top+t.height+1,14))});const o=t.width/e.series.length;return e.series.forEach((i,s)=>{r.push({...we(i.name,t.left+s*o,e.topMm+e.heightMm-5,o),style:{fontSize:8,color:i.color??$e[s%$e.length],align:"center"}})}),r}function ta(e,t,r,n){const o=[],i=r.color??$e[n%$e.length],s=t.width/e.categories.length,a=s*.75/e.series.length;let c;return r.values.forEach((u,f)=>{if(u===null){c=void 0;return}const d=t.left+(f+.5)*s,l=t.y(u);e.type==="bar"?o.push({kind:"rect",leftMm:t.left+f*s+s*.125+n*a,topMm:Math.min(l,t.y(0)),widthMm:a,heightMm:Math.abs(t.y(0)-l),style:{backgroundColor:i,borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}}):(c&&o.push(ir(c.x,c.y,d,l,i,1.2)),o.push({kind:"ellipse",leftMm:d-.7,topMm:l-.7,widthMm:1.4,heightMm:1.4,style:{backgroundColor:i,borderColor:i}}),c={x:d,y:l}),e.showValues&&o.push({...we(dt(u),d-s/2,Math.max(t.top,l-5),s),style:{fontSize:7,color:i,align:"center"}})}),o}function ra(e,t){let r=0,n=!1;for(const o of t.values){if(o===null){n=!1;continue}r+=1+ +!!e.showValues,e.type==="line"&&n&&r++,n=!0}return r}function na(e){const t=e.categories.length,r=Math.max(1,Math.ceil(t/Math.max(1,Math.floor((e.widthMm-17)/14)))),n=11+ +!!e.title+Math.ceil(t/r)+e.series.length;return e.series.reduce((o,i)=>o+ra(e,i),n)}function oa(e){e=Zs(Us(e));const t=qs(e);return[...ea(e,t),...Zn(e)?Qs(e,t):e.series.flatMap((r,n)=>ta(e,t,r,n))]}function mt(e,t,r){if(e===void 0)return t;if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>r)throw new RangeError("图表预算超出允许范围");return Number(e)}function Qn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("图表绑定应为对象");if(K(e.dataset),K(e.categoryField),!["bar","line","stackedBar","percentBar"].includes(e.type))throw new TypeError("图表类型无效");if(e.sort!==void 0&&!["asc","desc"].includes(e.sort))throw new TypeError("图表排序无效");if(e.title!==void 0&&(typeof e.title!="string"||e.title.length>512))throw new TypeError("图表标题过长");if(e.showValues!==void 0&&typeof e.showValues!="boolean")throw new TypeError("图表数值标签应为布尔值");if(!Array.isArray(e.measures)||!e.measures.length||e.measures.length>12)throw new RangeError("图表支持 1–12 个度量");for(const t of Pe(e.measures,12,"图表度量"))ia(t);mt(e.maxRows,1e5,1e5),mt(e.maxCategories,200,200)}function ia(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("图表度量应为对象");if(e.field!==void 0&&K(e.field),e.weightField!==void 0&&K(e.weightField),e.label!==void 0&&(typeof e.label!="string"||e.label.length>256))throw new TypeError("图表系列名称过长");if(e.color!==void 0&&!/^#[\da-f]{6}$/i.test(e.color))throw new TypeError("图表颜色应为 #RRGGBB");oe(e)}function sa(e){if(e==null)return{key:"null",label:"—"};if(typeof e!="string"&&typeof e!="boolean"&&!(typeof e=="number"&&Number.isFinite(e)))throw new TypeError("图表分类应为文本、布尔或有限数字");const t=String(e);if(t.length>512)throw new RangeError("图表分类名称过长");return{key:JSON.stringify([typeof e,e]),label:t}}function aa(e){if(e===null)return null;const t=Number(e);if(!Number.isFinite(t))throw new RangeError("聚合结果超出图表有限数值范围");return t}function ca(e,t,r){if(r?.aborted){const a=new Error("图表数据处理已取消");throw a.name="AbortError",a}Qn(t);const n=Pe(t.measures,12,"图表度量");if(!Array.isArray(e)||e.length>mt(t.maxRows,1e5,1e5))throw new RangeError("图表数据超出行数预算");const o=new Map,i=mt(t.maxCategories,200,200);for(let a=0;a<e.length;a++){if(r?.aborted){const d=new Error("图表数据处理已取消");throw d.name="AbortError",d}const c=e[a];if(!c||typeof c!="object"||Array.isArray(c))throw new TypeError("图表数据行应为对象");const u=sa(Object.prototype.hasOwnProperty.call(c,t.categoryField)?c[t.categoryField]:null);let f=o.get(u.key);if(!f){if(o.size>=i)throw new RangeError("图表分类超出预算,请明确筛选或聚合数据");f={label:u.label,accumulators:n.map(oe)},o.set(u.key,f)}f.accumulators.forEach(d=>d.add(c))}const s=[...o.values()];return t.sort&&s.sort((a,c)=>(t.sort==="desc"?-1:1)*(a.label<c.label?-1:a.label>c.label?1:0)),{categories:s.map(a=>a.label),series:n.map((a,c)=>({name:a.label??`${a.field??"记录"} · ${a.op}`,values:s.map(u=>aa(u.accumulators[c].value())),...a.color?{color:a.color}:{}}))}}class Se extends Error{constructor(t,r){super(`报表页数超出上限 ${t}(至少 ${r} 页)`),this.limit=t,this.actual=r,this.code="page-limit",this.name="PaginatePageLimitError"}}class _e extends Error{constructor(t,r){super(`报表单元格数量超出上限 ${t}(至少 ${r} 格)`),this.limit=t,this.actual=r,this.code="cell-limit",this.name="PaginateCellLimitError"}}class Ke extends Error{constructor(t,r){super(`报表图表图元数量预计超出上限 ${t}(本次估算 ${r})`),this.limit=t,this.estimated=r,this.code="chart-component-limit",this.name="PaginateChartComponentLimitError"}}const Or=5e4;function It(e=Or){if(!Number.isSafeInteger(e)||e<1||e>1e6)throw new RangeError("maxChartComponents 应为 1..1000000 的安全整数")}function ua(e,t,r){const n=e.chartBinding;if(e.kind!=="chart"||e.grid||e.imageData||e.binding||e.pageAnchor)throw new TypeError("绑定图表不能同时设置图片、网格、记录绑定或页眉页脚");const o=Object.prototype.hasOwnProperty.call(t,n.dataset)?t[n.dataset]:void 0;if(!Array.isArray(o))throw new TypeError(`图表数据集 ${n.dataset} 未提供`);return{...ca(o,n,r),type:n.type,leftMm:e.leftMm,topMm:e.topMm,widthMm:e.widthMm,heightMm:e.heightMm,title:n.title,showValues:n.showValues}}function fa(e,t,r=Or){It(r);let n=0;return Object.assign(i=>{if(!i.chartBinding)return[i];const s=ua(i,e,t),a=n+(s.categories.length?na(s):1);if(!Number.isSafeInteger(a))throw new RangeError("图表图元估算应为有限安全整数");if(a>r)throw new Ke(r,a);const c=s.categories.length?oa(s):[{kind:"text",leftMm:i.leftMm,topMm:i.topMm,widthMm:i.widthMm,heightMm:i.heightMm,text:"—",style:{align:"center",verticalAlign:"middle",color:"#94a3b8",fontSize:10}}];return n+=c.length,c},{used:()=>n})}function Fe(e,t){return JSON.stringify([e.slice(0,t.length),t.map(r=>[r===null?"null":typeof r,r])])}function eo(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 la(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("矩阵层级标签应为字符串");gn(e.row,t.length),gn(e.column,r.length)}function gn(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 pn(e,t,r){return{fields:e,options:t??{},hierarchy:r,root:{values:[],children:new Map},leaves:0,expanded:0}}function yn(e,t){const r=eo(t,e.fields);let n=e.root;for(let o=1;o<=r.length;o++){const i=r.slice(0,o),s=Fe(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 da(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 ma(e,t){const r=[...e.children.values()];return t&&t!=="source"&&r.sort((n,o)=>da(n.values[n.values.length-1],o.values[o.values.length-1])*(t==="desc"?-1:1)),r}function Ut(e,t,r){return{key:Fe(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 wn(e,t){const r=[];function n(o){for(const i of ma(o,e.options.sort?.[o.values.length]))i.children.size?(n(i),e.options.subtotals?.includes(i.values.length)&&r.push(Ut(e,i.values,"subtotal"))):r.push(Ut(e,i.values,"member"))}return n(e.root),t&&e.leaves&&r.push(Ut(e,[],"total")),r}function bn(e,t,r){const n=eo(t,e.fields),o=[Fe(e.fields,n),...(e.options.subtotals??[]).map(i=>Fe(e.fields,n.slice(0,i)))];return r&&o.push(Fe(e.fields,[])),o}function ha(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 ga(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=ha(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 xn(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 to(e,t){if(!Array.isArray(e)||e.length>(t.maxInputRows??1e5))throw new Error("矩阵输入超出预算");const r=pn(t.rowFields,t.hierarchy.row,t.hierarchy),n=pn(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=xn(0,t,r,n);for(const s of e){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("矩阵数据行应为对象");yn(r,s),yn(n,s),i=xn(e.length,t,r,n)}return{row:r,column:n,shape:i}}function pa(e,t){return to(e,t).shape}function ya(e,t,r){const n=new Map;for(const o of e){const i=bn(r.row,o,!!t.totals),s=bn(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=>oe({...d,field:d.valueField??d.field})),c.set(u,f)),f.forEach(d=>d.add(o))}}}return n}function wa(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 ba(e,t){return e.kind==="total"?t.hierarchy.totalLabel??"合计":[...e.labels,...e.kind==="subtotal"?[t.hierarchy.subtotalLabel??"小计"]:[]].join(" / ")}function xa(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:`${ba(r,t)} · ${n.label??`${n.field} (${n.op})`}`,semanticRole:"measure",...n.digits===void 0?{}:{format:{kind:"number",digits:n.digits}}}})]}function va(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 Ma(e,t){const r=to(e,t),n=wn(r.row,!!t.totals),o=wa(wn(r.column,!!t.totals),t),i=ya(e,t,r);return{columns:xa(o,t),rows:va(n,o,t,i),headerGrid:ga(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 $a(e,t){const r=()=>t.measures.map(c=>oe(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 ht(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 Sa(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 Rr(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(Sa(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(oe({...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&&la(e.hierarchy,e.rowFields,e.columnFields)}function ro(e,t){if(Rr(t),t.hierarchy)return pa(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(ht(s,t.rowFields).key),n.add(ht(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 Ea(e,t){if(t?.hierarchy)return Rr(t),Ma(e,t);ro(e,t);const r=$a(e,{row:s=>ht(s,t.rowFields),column:s=>ht(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 Aa=96;function ka(e,t=Aa){return e*t/72}function Ct(e,t=96,r=Sr){if(e?.fontSizePx!=null)return{fontSizePt:e.fontSizePx*72/t,fontSizePx:e.fontSizePx};const n=e?.fontSize??r;return{fontSizePt:n,fontSizePx:ka(n,t)}}function Na(e){return e?.lineHeight??Pt}function Q(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 Pa(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 vn(e,t,r){return e?.length?Pa(e,t):Array.from({length:r},(n,o)=>({pos:t*o/r,size:t/r}))}function no(e,t,r){const n=e.cells??[],o=Math.max(n.length,1),i=e.colWidthsMm?.length??Math.max(1,...n.map(g=>Array.isArray(g)?g.length:0)),s=vn(e.colWidthsMm,t,i),a=g=>g<=0?0:g>=i?s[s.length-1].pos+s[s.length-1].size:s[g].pos,c=vn(e.rowHeightsMm,r,o),u=g=>g<=0?0:g>=o?c[c.length-1].pos+c[c.length-1].size:c[g].pos,f=new Set,d=(g,x)=>`${g}:${x}`,l=[],m=new Set,h=new Set,p=(g,x)=>`v${g}:${x}`,w=(g,x)=>`h${g}:${x}`;n.forEach((g,x)=>{if(!Array.isArray(g))return;let b=0;for(const $ of g){for(;b<i&&f.has(d(x,b));)b++;if(b>=i)break;const T=Math.max(1,Math.min($?.colSpan??1,i-b)),j=Math.max(1,$?.rowSpan??1),v=Math.min(o,x+j),M=Math.min(i,b+T);for(let N=x;N<v;N++)for(let R=b;R<M;R++)f.add(d(N,R));for(let N=b+1;N<M;N++)for(let R=x;R<v;R++)m.add(p(N,R));for(let N=x+1;N<v;N++)for(let R=b;R<M;R++)h.add(w(N,R));const S=a(b),I=u(x);l.push({ri:x,ci:b,cell:$??{},xMm:S,yMm:I,widthMm:a(M)-S,heightMm:u(v)-I}),b=M}});const y=[];for(let g=1;g<i;g++){let x=-1;for(let b=0;b<=o;b++){const $=b<o&&!m.has(p(g,b));$&&x<0&&(x=b),!$&&x>=0&&(y.push({kind:"v",pos:a(g),from:u(x),to:u(b)}),x=-1)}}for(let g=1;g<o;g++){let x=-1;for(let b=0;b<=i;b++){const $=b<i&&!h.has(w(g,b));$&&x<0&&(x=b),!$&&x>=0&&(y.push({kind:"h",pos:u(g),from:a(x),to:a(b)}),x=-1)}}return{columns:s,rows:c,cells:l,edges:y}}function Fa(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 Oa(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 oo(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 Ir(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 io(e,t){let r=Q({fontSize:e.fontSizePt??Sr,bold:e.headerBold??!0,align:"center",verticalAlign:"middle",backgroundColor:e.headerBackgroundColor},t.style);return e.headerAlign!==void 0&&(r.align=e.headerAlign),r=Q(r,e.headerStyle),t.headerAlign!==void 0&&(r.align=t.headerAlign),Q(r,t.headerStyle)}function Ra(e,t){return{member:"body",subtotal:"subtotal",total:"grand-total"}[e?.rows.get(t)?.kind??"member"]}function Ia(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 Ca(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=Ea(t,Ia(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 Ta(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=no({...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={...io(e,e.columns[u]),...c.style},m=Ct(l).fontSizePt,p=(Ve(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??Pt)*25.4/72+r*2)/(c.rowSpan??1);for(let w=f;w<f+(c.rowSpan??1);w++)n[w]=Math.max(n[w]??0,p);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 so extends Error{constructor(t){super(`树节点超出行数预算 ${t}`),this.limit=t,this.code="tree-row-limit",this.name="TreeRowLimitError"}}function Gt(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 Cr(e){return{rows:Gt(e.maxRows,1e5,1e6,"树行数预算"),depth:Gt(e.maxDepth,64,256,"树深度预算"),visits:Gt(e.maxAggregationVisits,1e6,1e7,"树聚合访问预算")}}function ao(e){return typeof e=="string"&&!!e.trim()}function be(e){return ao(e)&&!["__proto__","prototype","constructor"].includes(e)}function co(e){if(ao(e)||typeof e=="number"&&Number.isFinite(e))return e;throw new Error("树节点业务键应为非空字符串或有限数字")}function uo(e){return JSON.stringify([typeof e,e])}function fo(e){return[e.idField,...e.input==="flat"?[e.parentField??""]:[e.childrenField??"children"]]}function Tr(e,t){const r=fo(e);if(t?.some(n=>n.scope&&n.scope!=="row"||r.includes(n.field)))throw new Error("树形布局仅支持不覆盖结构键的当前行计算")}function Ee(e){if(!e?.aborted)return;const t=new Error("树报表处理已取消");throw t.name="AbortError",t}function ja(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||!be(n.field)||r.has(n.field))throw new Error("树聚合输出字段应安全、非空且唯一");for(const o of[n.valueField,n.weightField])if(o!==void 0&&!be(o))throw new Error("树聚合来源字段应安全且非空");if([...fo(e),e.labelField].includes(n.field))throw new Error("树聚合不能覆盖结构键或标签字段");r.add(n.field),oe({...n,field:n.valueField??n.field})}}function Da(e){if(!be(e.idField)||!be(e.labelField))throw new Error("树需要安全的业务键和标签字段");if(e.input==="flat"&&(!be(e.parentField)||e.parentField===e.idField))throw new Error("扁平树需要独立的父键字段");if(e.childrenField!==void 0&&!be(e.childrenField))throw new Error("子节点字段应安全且非空");if(e.input==="nested"&&[e.idField,e.labelField].includes(e.childrenField??"children"))throw new Error("子节点字段不能覆盖业务键或标签字段")}function lo(e){if(!e||typeof e!="object"||!["flat","nested"].includes(e.input))throw new Error("树输入应为 flat 或 nested");if(Da(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");Cr(e),ja(e)}function mo(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("树节点应为对象");if(r.size>=n.rows)throw new so(n.rows);const o=co(e[t.idField]),i=uo(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 La(e,t,r,n,o){for(const s of e)Ee(o),mo(s,t,r,n);const i=[];for(const s of r.values()){Ee(o);const a=s.row[t.parentField];if(a==null){i.push(s);continue}const c=r.get(uo(co(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 Ba(e,t,r,n,o){const i=[],s=[{rows:e,next:0}];for(;s.length;){Ee(o);const a=s[s.length-1];if(a.next>=a.rows.length){s.pop();continue}const c=mo(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 _a(e,t,r,n){const o=[],i=[{nodes:e,next:0}];for(;i.length;){Ee(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 Ka(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=>oe({...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(Ee(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 ho(e,t,r){if(lo(t),Ee(r),!Array.isArray(e))throw new Error("树数据应为节点数组");const n=Cr(t),o=new Map,i=t.input==="flat"?La(e,t,o,n,r):Ba(e,t,o,n,r);return _a(i,o.size,n,r)}function go(e,t,r){return ho(e,t,r).map(n=>n.original)}function po(e,t,r={}){const n=ho(e,t,r.signal);if(Tr(t,r.computed?.fields),r.computed?.fields.length){const o=Rt(n.map(i=>i.row),{...r.computed,signal:r.signal}).rows;n.forEach((i,s)=>{i.row=o[s]})}return Ka(n,t,Cr(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 Wa(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 h=s+1;h<s+d;h++)n.add(`${h}:${m}`)}l&&a.push(u?{...u,colSpan:l}:null),c+=f}return a});return{...e,cells:o,colWidthsMm:r}}function Ja(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:Wa(e.headerGrid,t,r.map(n=>n.widthMm))}:{}}}function jr(e){return e.kind==="list"?e.id:e.nid}function za(e){return e.kind==="list"?!1:e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&/\{(?:page|totalPages)\}/.test(e.text)}function Va(e,t){const r=e.filter(o=>t.componentIds.includes(jr(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 Ha(e,t){if(!t)return e.map(n=>({components:[n]}));const r=new Map(e.map(n=>[jr(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 yo(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(za(o))continue;const i=jr(o);if(!i||r.has(i))throw new Error("流式排版组件应具有唯一标识");r.add(i)}if(Ua(e,t,r,n),n.size!==r.size)throw new Error("流式排版必须显式包含每个非锚点组件")}function Ua(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)}Va(e,i),o=i.topMm+i.heightMm}}function*Ga(e){const{page:t}=e;yo(t.components,t.flow);let r=0,n=0;for(const o of Ha(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 Ya(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||t.visual))}function Dr(e){return e.pages.some(t=>t.components.some(r=>r.kind==="list"?Ya(r):!!r.chartBinding))}const qa=new Set(["__proto__","prototype","constructor"]);function te(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tt(e){return typeof e=="string"&&!!e.trim()&&!qa.has(e)}function gt(e,t,r,n){for(const o of Object.keys(e))t.includes(o)||n.push({path:`${r}.${o}`,message:"存在未知配置字段"})}function Xa(e,t,r){if(e!==void 0){if(!te(e)||!["number","percent","date"].includes(String(e.kind))){r.push({path:t,message:"绑定格式应为 number、percent 或 date"});return}gt(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 Za(e,t,r){const n=e.binding;if(n===void 0)return;const o=`${t}.binding`;if(!te(n)){r.push({path:o,message:"字段绑定应为对象"});return}(!["text","image","barcode","qrcode"].includes(String(e.kind))||e.grid!==void 0)&&r.push({path:o,message:"绑定仅支持独立文本、图片、条码与二维码组件"}),gt(n,["field","format","prefix","suffix","emptyText"],o,r),tt(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:"应为字符串"});Xa(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 Qa(e,t){if(!te(e)){t.push({path:"$.repeat",message:"逐记录配置应为对象"});return}gt(e,["dataset","rowKey","copies"],"$.repeat",t),tt(e.dataset)||t.push({path:"$.repeat.dataset",message:"数据集应为安全的非空名称"}),e.rowKey!==void 0&&!tt(e.rowKey)&&t.push({path:"$.repeat.rowKey",message:"业务主键应为安全的非空字段名"});const r=e.copies;r!==void 0&&(te(r)?(gt(r,["field"],"$.repeat.copies",t),tt(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 wo(e,t,r,n){if(!te(e))return;Za(e,t,n),e.binding!==void 0&&!r&&n.push({path:`${t}.binding`,message:"字段绑定需要模板 repeat 数据集;普通报表请使用列表字段"}),r&&e.kind==="list"&&n.push({path:t,message:"逐记录标签使用固定组件;动态列表请使用普通报表模板"}),e.chartBinding!==void 0&&(r||t.includes(".children."))&&n.push({path:`${t}.chartBinding`,message:"数据图表应放在普通报表的页面或流式分区,不放在逐记录标签或嵌套单元格内"});const o=e.grid;te(o)&&Array.isArray(o.cells)&&o.cells.forEach((i,s)=>{Array.isArray(i)&&i.forEach((a,c)=>{te(a)&&Array.isArray(a.children)&&a.children.forEach((u,f)=>wo(u,`${t}.grid.cells.${s}.${c}.children.${f}`,r,n))})})}function bo(e,t){const r=e.repeat!==void 0;r&&Qa(e.repeat,t),Array.isArray(e.pages)&&e.pages.forEach((n,o)=>{if(!te(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(wo(s,c,r,t),!r||!te(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 ec=512,Mn=256*1024;function tc(){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=Ve(n,o,i,s),f=a.length+u.reduce((d,l)=>d+l.length,0);if(f<=Mn){for(;e.size>=ec||t+f>Mn;){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 rc(e){return typeof e=="string"&&/^data:image\/(png|jpe?g);base64,[A-Za-z0-9+/\r\n]+=*$/.test(e)}class H 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 Lr(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 H(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 H(i,"绑定值应为字符串、有限数字、布尔值或空值",n,t)}function nc(e,t,r={}){const n=Lr(t,e.field,r);return n==null||n===""?e.emptyText??"":`${e.prefix??""}${kr(n,e.format)}${e.suffix??""}`}const oc=1e4,$n=25e4;function Br(e){if(e?.aborted)throw e.reason??new DOMException("标签生成已取消","AbortError")}function xo(e,t,r){const n=typeof e.copies=="object"?Lr(t,e.copies.field,r):e.copies??1;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>1e3)throw new H(`$.datasets.${r.dataset}[${r.rowIndex}]`,"每条记录复制数必须是 1..1000 的数值型整数",r.rowIndex,typeof e.copies=="object"?e.copies.field:void 0);return n}function vo(e,t,r){if(e.rowKey===void 0)return;const n=Lr(t,e.rowKey,r);if(typeof n=="string"&&n.trim()||typeof n=="number"&&Number.isFinite(n))return n;throw new H(`$.datasets.${r.dataset}[${r.rowIndex}].${e.rowKey}`,"业务主键必须是非空字符串或有限数字",r.rowIndex,e.rowKey)}function ic(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 sc(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 H(`$.datasets.${n.dataset}`,"逐记录标签数据集缺失,应提供对象数组(允许空数组)");const i=new Set,s=r.maxPages??oc,a=ic(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 H(`$.datasets.${n.dataset}[${f}]`,"标签记录应为对象",f);const l={rowIndex:f,dataset:n.dataset},m=vo(n,d,l);if(m!==void 0){const p=JSON.stringify([typeof m,m]);if(i.has(p))throw new H(`$.datasets.${n.dataset}[${f}].${n.rowKey}`,"业务主键重复;请先确认记录来源,避免重复打印标签",f,n.rowKey);i.add(p)}const h=xo(n,d,l);if(c+=h*e.pages.length,u+=h*a,c>s)throw new Se(s,c);if(u>$n)throw new H("$.repeat",`标签组件总量(含网格行、槽位及嵌套组件)超过安全预算 ${$n},请分批生成`,f)}return o}function ac(e,t,r){if(!e.binding)return e;const{binding:n,...o}=e,i=nc(n,t.row,t);if(e.kind==="image"){if(!i)return;if(!rc(i))throw new H(`${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 cc(e,t,r){if(e.kind!=="text"||e.grid||e.richParagraphs?.length)return e;const n=e.style??{},o=Ct(n).fontSizePt,i=e.text??e.lines?.join(`
5
- `)??"";if(i.length>16384)throw new H(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??Er),a=s.length*o*Na(n)*25.4/72;if(a>e.heightMm+.05)throw new H(r,`标签文字需要约 ${a.toFixed(2)}mm 高,超出 ${e.heightMm}mm;请增大文本区域、减少内容或调整字号`,t.rowIndex,e.binding?.field);return{...e,lines:s}}function Mo(e,t,r){Br(t.options.signal);const n=ac(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=Mo(u,t,`${r}.grid.cells.${s}.${c}.children.${f}`);return d?[d]:[]})}:a))}),cc(o===n.grid?n:{...n,grid:o},t,r)}function uc(e,t,r,n,o,i){return{...e,components:e.components.flatMap((s,a)=>{const c=Mo(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*fc(e,t,r){const n=[];if(bo(e,n),n.length)throw new H(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=sc(e,t,r),s=tc();for(const[a,c]of i.entries()){const u={row:c,rowIndex:a,dataset:o.dataset,options:r,wrapText:s},f=xo(o,c,u),d=vo(o,c,u);for(let l=0;l<f;l++)for(const[m,h]of e.pages.entries())Br(r.signal),yield{page:uc(h,m,u,l,f,d),pageIndex:m}}}const lc=/^#[0-9a-f]{6}$/i;function $o(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return t.kind!=="colorScale"&&t.kind!=="dataBar"||t.field!==void 0&&(typeof t.field!="string"||!t.field.trim())||t.numeric!==void 0&&!["number","decimal"].includes(t.numeric)||[t.min,t.max].some(r=>r!==void 0&&(typeof r!="number"||!Number.isFinite(r)))||t.min!==void 0&&t.max!==void 0&&t.min>t.max?!1:Object.entries(t).every(([r,n])=>!["color","negativeColor","lowColor","highColor"].includes(r)||typeof n=="string"&&lc.test(n))}function So(e,t){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(t!=="decimal"||typeof e!="string"||e.length>1024||!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e))return;const r=Number(e);return Number.isFinite(r)?r:void 0}function dc(e,t,r){let n="#";for(const o of[1,3,5]){const i=parseInt(e.slice(o,o+2),16),s=parseInt(t.slice(o,o+2),16);n+=Math.round(i+(s-i)*r).toString(16).padStart(2,"0")}return n}function Yt(e,t,r){if(t===r)return e<t?0:e>r?1:.5;if(e<=t)return 0;if(e>=r)return 1;const n=r-t;return Number.isFinite(n)?(e-t)/n:(e/2-t/2)/(r/2-t/2)}function mc(e,t,r,n){const o=new WeakMap;return{apply(i,s){const a=So(s[t],e.numeric);if(a===void 0)return;if(e.kind==="dataBar"){const l=Math.min(r,0),m=Math.max(n,0),h=Yt(0,l,m),p=l===m?h:Yt(a,l,m);i.dataBar={start:Math.min(h,p),end:Math.max(h,p),color:a<0?e.negativeColor??"#f3bcc3":e.color??"#bad8fa"};return}const c=dc(e.lowColor??"#f0f7ff",e.highColor??"#8bbcf1",Yt(a,r,n)),u=i.style??{},f=o.get(u)??new Map;o.set(u,f);let d=f.get(c);d||(d={...u,backgroundColor:c},f.set(c,d)),i.style=d}}}function hc(e,t,r){return e.map(n=>{Sn(r);const o=n.visual;if(!o)return;if(!$o(o))throw new TypeError("Invalid column visual rule");const i=o.field??n.field;let s=1/0,a=-1/0,c=0;if(o.min===void 0||o.max===void 0)for(const d of t){(c++&1023)===0&&Sn(r);const l=So(d[i],o.numeric);l!==void 0&&(s=Math.min(s,l),a=Math.max(a,l))}let u=o.min??s,f=o.max??a;if(!(!Number.isFinite(u)||!Number.isFinite(f)))return u>f&&(o.min!==void 0?f=u:u=f),mc(o,i,u,f)})}function Sn(e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError")}function gc(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 pt(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 We(e){return e.components.reduce((t,r)=>r.kind!=="list"&&r.pageAnchor==="header"?Math.max(t,r.topMm+r.heightMm):t,0)}function Eo(e,t){let r=e.textMetrics.get(t);if(!r){const n=Ct(t).fontSizePt;r={measureOptions:{fontSizePt:n,fontFamily:t.fontFamily??zn,italic:t.italic,bold:t.bold,letterSpacingPt:t.letterSpacing},lineMm:n*(t.lineHeight??Pt)*25.4/72},e.textMetrics.set(t,r)}return r}function pc(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function _r(e,t,r=[],n){const o=e.fontSizePt??Sr,i=e.paddingMm??1,s=e.columns.map(y=>y.align??y.style?.align??e.align??"left"),a=e.columns.map((y,g)=>({...Q({fontSize:o,verticalAlign:"middle"},y.style),align:s[g]==="auto"?"left":s[g]})),c=a.map((y,g)=>s[g]==="auto"?{left:y,center:{...y,align:"center"},right:{...y,align:"right"}}:void 0),u=e.columns.map((y,g)=>y.rules?.map(x=>{const b=c[g];if(b)return{left:Q(b.left,x.style),center:Q(b.center,x.style),right:Q(b.right,x.style)};const $=Q(a[g],x.style);return{left:$,center:$,right:$}})),f=e.columns.map(y=>io(e,y)),d=e.columns.map(y=>y.header);let l=e.rowHeightMm??0;for(let y=0;y<d.length;y++){const g=f[y],x=Ct(g).fontSizePt,b=Ve(d[y],e.columns[y].widthMm-i*2,{fontSizePt:x,fontFamily:g.fontFamily??zn,italic:g.italic,bold:g.bold,letterSpacingPt:g.letterSpacing},t),$=x*(g.lineHeight??Pt)*25.4/72;l=Math.max(l,Math.max(b.length,1)*$+i*2)}const m=d.map((y,g)=>({text:y,style:f[g]})),h=e.border===!1?{borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}:{borderBottom:!0,borderLeft:!0,borderRight:!0,borderTop:!0},p=e.columns.map(y=>y.widthMm),w=yc(Ta(e,t),p,{cells:[m],colWidthsMm:p,rowHeightsMm:[l],paddingMm:i});return{fontSizePt:o,paddingMm:i,visuals:hc(e.columns,r,n),visibility:e.columns.map(y=>y.visibleWhen?q(y.visibleWhen):void 0),ruleReaders:e.columns.map(y=>y.rules?.map(g=>q(g.when))),cellStyles:a,autoStyles:c,ruleStyles:u,textMetrics:new WeakMap,numberFormats:e.columns.map(y=>qn(y.format)),derivedFields:new Set(e.computed?.map(y=>y.field)),borderStyle:h,headerHeightMm:w.rowHeightsMm.reduce((y,g)=>y+g,0),headerGrid:w,colWidthsMm:p,columns:e.columns}}function yc(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 wc(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 Je(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=e.visibility[a]?.(t)!==!1,f=u?t[c.field]:null,d=e.autoStyles[a]?oo(f,c.format,c.semanticRole):"left";let l=e.autoStyles[a]?.[d]??e.cellStyles[a];if(c.rules){for(let x=0;x<c.rules.length;x++)if(e.ruleReaders[a][x](t)){l=e.ruleStyles[a][x][d];break}}const m=c.format?kr(f,c.format):Ir(f),h=bc(e,c,o);l=xc(e,c,l,o);const p=Eo(e,l),w=Ve(m,Math.max(1,c.widthMm-e.paddingMm*2-h),p.measureOptions,r);i=Math.max(i,w.length*p.lineMm+e.paddingMm*2);const y=pc(f),g={text:m,style:l};f!=null&&e.visuals[a]?.apply(g,t),y!==void 0&&(g.value=y),wc(g,c,e.numberFormats[a]),vc(g,c,e,o,h),e.derivedFields.has(c.field)&&(g.derived=!0,g.editable=!1),u||(g.editable=!1),s[a]=g}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 bc(e,t,r){return!r||t.field!==e.tree.list.tree.labelField?0:Fa(e.tree.list,t,r,e.paddingMm)}function xc(e,t,r,n){return!n||t.field!==e.tree.list.tree.labelField||r.align==="left"?r:{...r,align:"left"}}function vc(e,t,r,n,o=0){n&&(o&&(e.indentMm=o),Oa(e,t,n,r.tree.list))}function Ao(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*ko(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=Ao(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,Ir(i[0][n.field])),firstRow:i[0],group:n,depth:r,rows:i},yield*ko(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 No(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=Be(t,{...i,field:i.valueField??i.field});return[i.field,{text:kr(a,s),...a===null?{}:{value:a},...typeof a=="number"?{numberFormat:qn(s)}:{}}]}))}function Po(e,t){const r=e.findIndex(n=>t.includes(n.field));return r<0?1:r}function Oe(e,t,r,n,o,i){const s=[],a=Math.max(0,Math.min(i,e.columns.length)),c=Q({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],h=n.get(m.field),p=e.autoStyles[l]?.[oo(h?.value,m.format)]??e.cellStyles[l];s.push({...h,text:h?.text??"",style:Q(p,o)})}const u={text:r,colSpan:e.columns.length,style:{bold:!0,...c}},f=a?[s]:[[u],s],d=f.map(l=>Mc(e,l,t));return{grid:{cells:f,colWidthsMm:e.colWidthsMm,rowHeightsMm:d,paddingMm:e.paddingMm},heightMm:d.reduce((l,m)=>l+m,0)}}function Mc(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=Eo(e,i.style),u=Ve(i.text??"",s-e.paddingMm*2,c.measureOptions,r);n=Math.max(n,u.length*c.lineMm+e.paddingMm*2)}return n}function $c(e,t,r){const{templatePage:n,current:o,warnings:i,nextId:s,pushCurrent:a}=r,c=()=>pt(n,o),u=Math.max(o.marginTopMm,We(n)),f=n.layout==="wide"?We(n):u,d={id:r.tableId,columnKeys:e.columns.map(v=>v.field),...e.layout===void 0?{}:{layout:e.layout},...e.title===void 0?{}:{title:e.title}},l=new Map,m=new Map,h={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}:{}}}:{}},p=v=>o.components.push({...h,topMm:v});if(r.flow&&e.header!==!1&&t.headerHeightMm>c()-u+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的表头高度超出单页可用范围`);let w=Math.max(r.startTop??e.topMm,u);e.header!==!1&&(p(w),w+=t.headerHeightMm+r.mmPerRow);function y(){const v=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);return(e.header!==!1&&e.headerEveryPage!==!1?v+t.headerHeightMm:f)+[...m.values()].reduce((S,I)=>S+I.heightMm,0)}function g(){const v=n.layout==="wide"?0:o.marginBottomMm;return Math.min(n.heightMm-v,pt(n,o))-y()}function x(v){if(w+v<=c())return;a(),o.components=[],o.heightMm=n.heightMm,n.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0);const M=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);e.header!==!1&&e.headerEveryPage!==!1?(p(M),w=M+t.headerHeightMm):w=f;for(const S of m.values())$(S,"listgr","group-header")}function b(v,M,S,I){const N=g();if(r.flow&&v.heightMm>N+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的单行高度超出单页可用范围`);v.heightMm>N&&i.push(`列表 ${e.id??e.dataset} 行高 ${v.heightMm.toFixed(2)}mm 超出单页可用高度 ${N.toFixed(2)}mm,预览与打印可能截断内容`),x(v.heightMm),$(v,M,S,I)}function $(v,M,S,I){const N=v.table?.id??d.id,R=S==="header"?-1:l.get(N)??0;S!=="header"&&l.set(N,R+v.grid.cells.length),o.components.push({kind:"rect",leftMm:e.leftMm,topMm:w,widthMm:e.widthMm,heightMm:v.heightMm,grid:v.grid,nid:s(M),table:{...d,...v.table,role:S,rowIndex:R,...I?{source:I}:{}},style:t.borderStyle,...e.meta||v.meta?{meta:{...e.meta,...v.meta}}:{}}),w+=v.heightMm}function T(v){v<=g()&&x(v)}return{keepTogether:T,placeGridRow:b,setGroupHeader:(v,M)=>{M?m.set(v,M):m.delete(v)},bottom:()=>w}}function Sc(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 Tt(e,t){const r=new Map;if(!e.rowKey)return r;const n=new Set;for(const o of t){const i=Sc(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 Ec(e,t,r,n,o){if(!e.grandTotal)return;const i=typeof e.grandTotal=="object"?e.grandTotal:void 0,s=jt(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=Oe(r,n.measurer,i?.label??"合计",No(e.columns,t,a,c),i?.style??{},Po(e.columns,[...a,...c.map(f=>f.field)]));o.placeGridRow(u,"listgt","grand-total")}function se(e){if(e?.aborted){const t=new Error("报表排版已取消");throw t.name="AbortError",t}}function jt(e){const t=e.groups??(e.groupBy?[e.groupBy]:[]);if(t.length>16)throw new Error("列表最多支持 16 级分组");return t}function Kr(e){const t=Ja(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 Ac(e,t,r){const n=e.detail;if(!n)return;const o=new Set;for(const u of t){const f=sr(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(!Fo(f)&&n.unmatched==="ignore")continue;const d=sr(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=Kr({...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:{..._r(c,r.measurer,a,r.signal),rowHeightFloorMm:c.rowHeightMm??0},rows:s,sources:Tt(c,a)}}function Fo(e){return typeof e=="string"&&!!e.trim()||typeof e=="number"&&Number.isFinite(e)}function sr(e){if(!Fo(e))throw new Error("主从关联键必须是非空字符串或有限数字");return Ao(e)}function*kc(e,t,r,n,o){if(!r)return;const i=r.rows.get(sr(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({...Oe(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)se(n.signal),o.placeGridRow({...Je(r.inter,a,n.measurer),table:s},"listdr","body",r.sources.get(a)),yield*n.takePages()}function Oo(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("树形布局需要可见的标签列");Tr(e.tree,e.computed)}function Nc(e,t,r){Oo(e);const n=po(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=Tt(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 Pc(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 Ro(e,t,r){const n=r.prepared.get(e);if(n)return n;const o=Pc(e,t);if(o)return r.prepared.set(e,o),o;if(e.tree){const c=Nc(e,t,r);return r.prepared.set(e,c),c}let i=e.computed?.length?Rt(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(q(e.rowVisibleWhen)));const a=Ca(e,i);if(!e.matrix){const c=Tt(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 Fc(e,t,r,n){if(!n.flow)return;const{current:o,templatePage:i}=n,s=Math.max(o.marginTopMm,We(i)),a=Math.max(n.startTop??e.topMm,s),c=(e.header===!1?0:t.headerHeightMm)+(r[0]?Je(t,r[0],n.measurer).heightMm:0);a+c<=pt(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,We(i)))}function*Oc(e,t,r){const n=Ro(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??Tt(e,o),s=Kr(e),a=jt(s),c={..._r(s,r.measurer,o,r.signal),rowHeightFloorMm:s.rowHeightMm??0,matrix:n.matrix,...n.treeRows?{tree:{list:s,rows:n.treeRows}}:{}};Fc(s,c,o,r);const u=$c(s,c,r),f=Ac(s,o,r);let d;for(const l of ko(o,a)){if(se(r.signal),l.kind==="row")u.placeGridRow(d??Je(c,l.row,r.measurer),"listr",Ra(n.matrix,l.row),i.get(l.row)),d=void 0,yield*r.takePages(),yield*kc(s,l.row,f,r,u);else if(l.kind==="groupHeader"){const m=Oe(c,r.measurer,l.label,new Map,l.group.headerStyle??{},s.columns.length);d??=Je(c,l.firstRow,r.measurer);const h=a.slice(l.depth+1).reduce((p,w)=>p+Oe(c,r.measurer,(w.headerTemplate??"{value}").replace(/\{value\}/g,Ir(l.firstRow[w.field])),new Map,w.headerStyle??{},s.columns.length).heightMm,0);l.group.keepWithNext!==!1&&u.keepTogether(m.heightMm+h+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??[],h=l.group.aggregates??[],p=Oe(c,r.measurer,l.label,No(s.columns,l.rows,m,h),l.group.subtotalStyle??{},Po(s.columns,[...m,...h.map(w=>w.field)]));u.placeGridRow(p,"listst","subtotal")}else u.setGroupHeader(l.depth);yield*r.takePages()}Ec(s,n.totalRows??o,c,r,u),r.finished?.(u.bottom()),yield*r.takePages()}function Wr(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 Jr(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=>Jr(o,t))}:{}}:null))}}:{}}}function Rc(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(Jr(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 zr(e){return e.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+Io(s),0)??0):0),0),0)}function Io(e){return e.grid?zr(e.grid):0}function Co(e){for(const t of["maxPages","maxCells","knownTotalPages"])if(e[t]!==void 0&&(!Number.isSafeInteger(e[t])||e[t]<1))throw new RangeError(`${t} 应为正安全整数`);It(e.maxChartComponents)}function Ic(e,t){const r=Ro(e,t.datasets[e.dataset]??[],t),n=Kr(r.list),o={..._r(n,t.measurer,r.rows,t.signal),rowHeightFloorMm:n.rowHeightMm??0};return(n.header===!1?0:o.headerHeightMm)+r.rows.reduce((i,s)=>i+Je(o,s,t.measurer).heightMm,0)}function*Cc(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??""} 输出为空`),Oc(i,Array.isArray(c)?c:[],{...e,tableId:`${e.tableId}:${n.get(i)}`,startTop:s,finished:a,flow:!!t.flow})};if(t.flow){yield*Ga({page:t,active:()=>se(e.signal),top:()=>Math.max(r.marginTopMm,We(t)),bottom:()=>pt(t,r),append:i=>{r.components.push(...e.resolveChart(i))},nextPage:()=>{e.pushCurrent(),r.components=[],r.heightMm=t.heightMm,t.layout==="wide"&&(r.marginTopMm=0,r.marginBottomMm=0)},takePages:e.takePages,height:i=>Ic(i,e),list:o});return}for(const i of t.components)Wr(i)||(i.kind==="list"?yield*o(i):r.components.push(...e.resolveChart(i)))}function*To(e,t,r,n,o,i=new WeakMap,s){let a=0,c=0,u=0;const f=cs(r.measurer??Er),d=fa(t,r.signal,r.maxChartComponents),l=m=>`${m}_${(++a).toString(36)}`;for(const{pageIndex:m,page:h}of fc(e,t,r)){se(r.signal);const p=gc(h),w=h.components.filter(Wr);let y=[];const g=(b=!1)=>{if(se(r.signal),r.maxPages!==void 0&&c>=r.maxPages)throw new Se(r.maxPages,c+1);if(r.maxCells!==void 0&&(u+=[...p.components,...w].reduce(($,T)=>$+Io(T),0),u>r.maxCells))throw new _e(r.maxCells,u);y.push(Rc(h,p,w,++c,b,o))},x=()=>{const b=y;return y=[],b};yield*Cc({templatePage:h,current:p,warnings:n,nextId:l,pushCurrent:g,takePages:x,datasets:t,resolveChart:d,signal:r.signal,formula:r.formula,prepared:i,measurer:f,mmPerRow:r.mmPerRow??0,tableId:`table:${m}`}),g(!0),yield*x()}s&&(s.chartComponents=d.used())}function Tc(e,t,r={}){const n=typeof r=="number"?{mmPerRow:r}:r;Co(n);const o=[],i={chartComponents:0},s=[...To(e,t,n,o,n.knownTotalPages,void 0,i)];return Do(e,n,s,o,i)}async function jo(e,t,r={}){Co(r),se(r.signal);const n=[],o=[],i={chartComponents:0};let s=performance.now(),a=0;for(const c of To(e,t,r,n,r.knownTotalPages,void 0,i))o.push(c),(++a>=8||performance.now()-s>=8)&&(await new Promise(u=>setTimeout(u,0)),se(r.signal),s=performance.now(),a=0);return se(r.signal),Do(e,r,o,n,i)}function Do(e,t,r,n,o){for(const i of r)i.components=i.components.map(s=>Wr(s)?Jr(s,a=>a.replace(/\{totalPages\}/g,String(r.length))):s);return n.forEach(i=>t.onWarning?.(i)),{plan:{schemaVersion:ze,...Dr(e)?{requiresRecalculation:!0}:{},pages:r},warnings:n,...o}}function jc(e){const t=e.columns.find(i=>!i.hidden)?.field;if(!t)return{groups:0,total:0};const r=jt(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 Dc(e,t,r){Oo(e);const n=go(t[e.dataset]??[],e.tree,r),o=e.columns.filter(s=>!s.hidden).length,i=e.header===!1?0:e.headerGrid?zr(e.headerGrid):o;return n.length*o+i+ +!!e.grandTotal*2*o}function Lc(e,t,r={}){if(e.tree)return Dc(e,t,r.signal);if(e.matrix){let c=t[e.dataset]??[];e.computed?.length&&(c=Rt(c,{fields:e.computed,...r}).rows),e.rowVisibleWhen&&(c=c.filter(q(e.rowVisibleWhen)));const u=ro(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=jt(e).length,s=jc(e);let a=(n*(1+2*i+s.groups)+ +!!e.grandTotal*(1+s.total))*o;if(a+=e.header===!1?0:e.headerGrid?zr(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 Bc(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const{start:t,end:r,color:n}=e;return typeof t=="number"&&typeof r=="number"&&Number.isFinite(t)&&Number.isFinite(r)&&t>=0&&r<=1&&t<=r&&typeof n=="string"&&/^#[0-9a-f]{6}$/i.test(n)}function rt(e){return!!e&&typeof e=="object"}function Lo(e,t,r,n,o){if(++o.nodes>1e6)return{path:t,message:"组件树超过100万个结构节点预算"};if(rt(e)){if(r>64)return{path:t,message:"组件嵌套超过64层预算"};if(n.has(e))return{path:t,message:"组件树包含循环引用"};if(!(!rt(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(!(!rt(c)||!Array.isArray(c.children)))for(const[u,f]of c.children.entries()){const d=Lo(f,`${t}.grid.cells.${i}.${a}.children.${u}`,r+1,n,o);if(d)return d}}}finally{n.delete(e)}}}}function Vr(e,t="$.components",r={nodes:0}){for(const[n,o]of e.entries()){const i=Lo(o,`${t}.${n}`,0,new Set,r);if(i)return i}}function Bo(e){const t={nodes:0};for(const[r,n]of e.entries()){if(!rt(n)||!Array.isArray(n.components))continue;const o=Vr(n.components,`$.pages.${r}.components`,t);if(o)return o}}function _c(e){const t=Bo(e.pages);if(t)throw new TypeError(`${t.path}: ${t.message}`)}function Kc(e,t,r){e!==void 0&&(typeof e!="string"||!e.trim()||e.length>4096)&&r.push({path:t,message:"来源范围应为不超过 4096 字符的非空字符串"})}function _o(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 Wc(e,t,r){_o(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:"派生结果标记应为布尔值"}),Ko(e.source,`${t}.source`,r,!0),e.formula!==void 0&&typeof e.formula!="string"&&r.push({path:`${t}.formula`,message:"单元格公式应为字符串"})}function Ko(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;Kc(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 Jc(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 zc(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 Vc(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return[{path:"",message:"code must be an object."}];const r=e,n=[...Jc(r),...zc(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 Hc=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yt(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 Uc(e,t,r,n){const o=e[t];(typeof o!="number"||!Number.isFinite(o))&&n.push({path:`${r}.${t}`,message:`应为有限数字,实际 ${yt(o)}`})}function Gc(e,t,r){if(e!==void 0){const n=`${t}.table`;if(!z(e))r.push({path:n,message:"逻辑表来源应为对象"});else{Ko(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 Yc(e,t,r,n){if(e!==void 0)if(!z(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(!z(a)){r.push({path:u,message:"网格单元格应为对象或 null"});return}Wc(a,u,r),a.dataBar!==void 0&&!Bc(a.dataBar)&&r.push({path:`${u}.dataBar`,message:"数据条应包含 0–1 有序比例与 #RRGGBB 颜色"}),Wo(a.richParagraphs,u,r),Array.isArray(a.children)&&a.children.forEach((f,d)=>{Hr(f,`${t}.grid.cells.${s}.${c}.children.${d}`,r,n)})})})}}function wt(e,t,r,n){e!==void 0&&!t.includes(e)&&n.push({path:r,message:"未知富文本属性值"})}function ar(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 qc(e,t,r){if(e!==void 0){if(!z(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:"富文本样式应为布尔值"});ar(e,["fontSize","fontSizePx","lineWidthPt","lineHeight","opacity"],t,r),ar(e,["letterSpacing","rotateDeg"],t,r,-1/0),typeof e.opacity=="number"&&e.opacity>1&&r.push({path:`${t}.opacity`,message:"透明度不能大于1"}),wt(e.align,["left","center","right","justify"],`${t}.align`,r),wt(e.verticalAlign,["top","middle","bottom"],`${t}.verticalAlign`,r)}}function Xc(e,t,r){if(!z(e)){r.push({path:t,message:"富文本片段应为对象"});return}wt(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:"富文本内容应为字符串"});qc(e.style,`${t}.style`,r)}function Wo(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(!z(n)||!Array.isArray(n.segments)){r.push({path:i,message:"段落缺少 segments 数组"});return}wt(n.align,["left","center","right","justify"],`${i}.align`,r),ar(n,["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"],i,r),n.segments.forEach((s,a)=>Xc(s,`${i}.segments.${a}`,r))})}}function Jo(e,t,r,n=[]){const o=Vr([e],t);if(o){r.push(o);return}Hr(e,t,r,n)}function Hr(e,t,r,n=[]){if(!z(e)){r.push({path:t,message:"组件应为对象"});return}const o=e.kind;typeof o!="string"?r.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):Hc.has(o)||n.push({path:`${t}.kind`,message:`未知组件类型 ${yt(o)},将以兜底方式渲染`});for(const i of["leftMm","topMm","widthMm","heightMm"])Uc(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:"组件尺寸不能为负数"});Gc(e.table,t,r),Qc(e.code,o,t,r),Zc(e,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"}),Yc(e.grid,t,r,n),Wo(e.richParagraphs,t,r)}function Zc(e,t,r){if(e.chartBinding!==void 0)try{if(Qn(e.chartBinding),e.kind!=="chart"||["binding","imageData","grid","pageAnchor"].some(n=>e[n]!==void 0))throw new Error("绑定图表不能设置图片、网格、记录绑定或页眉页脚");if(typeof e.widthMm!="number"||e.widthMm<45||typeof e.heightMm!="number"||e.heightMm<35)throw new Error("绑定图表至少需要 45×35mm")}catch(n){r.push({path:`${t}.chartBinding`,message:n instanceof Error?n.message:String(n)})}}function Qc(e,t,r,n){if(e!==void 0)for(const o of Vc(e,t))n.push({path:`${r}.code${o.path?`.${o.path}`:""}`,message:o.message})}function zo(e,t,r){if(!z(e))return;e.binding!==void 0&&r.push({path:`${t}.binding`,message:"渲染计划不允许未解析字段绑定"}),e.chartBinding!==void 0&&r.push({path:`${t}.chartBinding`,message:"渲染计划不允许未解析图表绑定"});const n=e.grid;!z(n)||!Array.isArray(n.cells)||n.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((s,a)=>{!z(s)||!Array.isArray(s.children)||s.children.forEach((c,u)=>zo(c,`${t}.grid.cells.${i}.${a}.children.${u}`,r))})})}function eu(e,t,r,n=[]){if(!z(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:`页宽非法: ${yt(o)}`}),(typeof i!="number"||!(i>0&&i<5e3))&&r.push({path:`${t}.pageHeightMm`,message:`页高非法: ${yt(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=Vr(s,`${t}.components`);if(a){r.push(a);return}s.forEach((c,u)=>{Hr(c,`${t}.components.${u}`,r,n),zo(c,`${t}.components.${u}`,r)})}}function Ue(e){const t=[],r=[],n=z(e)?e.pages:void 0;if(z(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=Bo(n);if(o)return{ok:!1,errors:[...t,o],warnings:r};n.forEach((s,a)=>eu(s,`$.pages.${a}`,t,r)),n.length>2e3&&r.push({path:"$.pages",message:`页数异常大(${n.length} 页),渲染与打印耗时可能显著增加`});const i=n.reduce((s,a)=>s+(z(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 bt(e,t){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)return;const r=Object.getOwnPropertyDescriptor(e,"length")?.value;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||r>t||Reflect.ownKeys(e).length!==r+1)return;const o=[];for(let i=0;i<r;i++){const s=Object.getOwnPropertyDescriptor(e,String(i));if(!s||!Object.prototype.hasOwnProperty.call(s,"value"))return;o.push(s.value)}return o}const Ur=100,Vo=16,cr=104857;function Ho(e,t,r){if(typeof e=="string"){if(e.length>cr)return;try{e=JSON.parse(e)}catch{return}}const n=bt(e,t);if(!n)return;const o=[];let i=2;for(const s of n){if(typeof s!="string"||!s.trim()||s.length>1024||r&&o.includes(s)||(i+=JSON.stringify(s).length+(o.length?1:0),i>cr))return;o.push(s)}return o}function tu(e){return Ho(e,Ur,!0)}function ru(e){return Ho(e,Vo,!1)}function nu(e){if(typeof e=="string"){if(e.length>2048)return;try{e=JSON.parse(e)}catch{return}}const t=bt(e,2);if(!t||t.length!==2)return;const r=t[0],n=t[1];return typeof r=="number"&&typeof n=="number"&&Number.isFinite(r)&&Number.isFinite(n)&&r<=n?[r,n]:void 0}function U(e){return["multiSelect","cascader","numberRange"].includes(e.type??"")}function Dt(e,t){return e.type==="numberRange"?nu(t):e.type==="cascader"?ru(t):tu(t)}function ou(e,t,r=!1){const n=bt(e,1e3);if(!n)return!1;const o=[{items:n,depth:1}],i=new Set;let s=0;for(let a=0;a<o.length;a++){const{items:c,depth:u}=o[a];if(u>Vo)return!1;const f=new Set;for(const d of c){const l=iu(d,r);if(++s>1e3||!l||i.has(d)||f.has(l.value))return!1;if(i.add(d),f.add(l.value),l.children!==void 0){const m=bt(l.children,1e3);if(!t||!m)return!1;m.length&&o.push({items:m,depth:u+1})}}}return!0}function Uo(e){return e.map(t=>({value:t.value,label:t.label,...t.children?{children:Uo(t.children)}:{}}))}function iu(e,t){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))return;const r=Object.getOwnPropertyDescriptors(e);if(Object.values(r).some(i=>!Object.prototype.hasOwnProperty.call(i,"value")))return;const n=r.value?.value,o=r.label?.value;if(!(typeof n!="string"||!t&&!n.trim()||n.length>1024||typeof o!="string"||o.length>1024))return{value:n,label:o,...r.children?{children:r.children.value}:{}}}function su(e,t){let r=e;for(const[n,o]of t.entries()){const i=r.find(s=>s.value===o);if(!i)return!1;if(r=i.children??[],n===t.length-1)return r.length===0}return!1}function au(e,t){const r=Dt(e,t);if(!r)return[["type",e.type==="numberRange"?"请填写完整数字范围,最小值不能大于最大值":e.type==="cascader"?"请选择完整的末级路径":"请选择有效选项,不能重复或超出数量限制"]];if(e.type==="numberRange")return cu(e,r);const n=r,o=[];return e.type==="cascader"&&e.options&&!su(e.options,n)&&o.push(["option","应为允许选项中的完整叶节点路径"]),e.type==="multiSelect"&&(e.options&&n.some(i=>!e.options.some(s=>s.value===i))&&o.push(["option","不在允许的选项中"]),e.minItems!==void 0&&n.length<e.minItems&&o.push(["minItems",`至少选择 ${e.minItems} 项`]),e.maxItems!==void 0&&n.length>e.maxItems&&o.push(["maxItems",`最多选择 ${e.maxItems} 项`])),o}function cu(e,t){const r=[];return typeof e.min=="number"&&t[0]<e.min&&r.push(["minimum",`不能小于 ${e.min}`]),typeof e.max=="number"&&t[1]>e.max&&r.push(["maximum",`不能大于 ${e.max}`]),r}function uu(e){const t=[];for(const r of["minItems","maxItems"])e[r]!==void 0&&(e.type!=="multiSelect"||!Number.isSafeInteger(e[r])||e[r]<0||e[r]>Ur)&&t.push(`${r} 应为多选参数的 0–100 整数边界`);return e.minItems!==void 0&&e.maxItems!==void 0&&e.minItems>e.maxItems&&t.push("最少项目数不能大于最多项目数"),t}function fu(e){if(e.type==="numberRange"){const r={type:"number",...typeof e.min=="number"?{minimum:e.min}:{},...typeof e.max=="number"?{maximum:e.max}:{}};return{type:"array",minItems:2,maxItems:2,prefixItems:[r,{...r}],items:!1,"x-report-number-range":{ordered:!0},"x-report-wire-encoding":"json"}}const t={"x-report-wire-encoding":"json","x-report-wire-max-code-units":cr,type:"array",minItems:Math.max(e.required?1:0,e.minItems??0),maxItems:e.type==="cascader"?16:e.maxItems??Ur,items:{type:"string",minLength:1,maxLength:1024,pattern:"\\S","x-report-max-code-units":1024}};return e.type==="multiSelect"?(t.uniqueItems=!0,e.options&&(t.items={...t.items,enum:e.options.map(r=>r.value)})):t["x-report-cascader"]={leafOnly:!0,...e.options?{options:Uo(e.options)}:{}},t}function lu(e){const t=[];return e.optionsSource!==void 0&&((!["select","multiSelect","cascader"].includes(e.type??"")||typeof e.optionsSource!="string"||!/^[\w][\w.:-]{0,127}$/.test(e.optionsSource))&&t.push("远程选项来源应为选择参数的有效来源键(最多 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 du(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 xt(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 Gr(e){return e.length===4&&/^\d{4}$/.test(e)&&e!=="0000"}function Go(e){return e.length===7&&/^\d{4}-(?:0[1-9]|1[0-2])$/.test(e)&&Gr(e.slice(0,4))}function Yo(e){const[t,r,n]=e.split("/");if(!(n!==void 0||!t||!r||!xt(t)||!xt(r)||t>r))return{start:t,end:r}}function qo(e,t){return typeof t!="string"?!1:e==="month"?Go(t):e==="year"?Gr(t):(e==="date"||e==="dateRange")&&xt(t)}function mu(e,t){if(e==="date"&&!xt(t))return"应为有效的 YYYY-MM-DD 日期";if(e==="month"&&!Go(t))return"应为有效的 YYYY-MM 月份";if(e==="year"&&!Gr(t))return"应为 0001 至 9999 的四位年份";if(e==="dateRange"&&!Yo(t))return"应为完整且有序的 YYYY-MM-DD/YYYY-MM-DD 日期范围"}class Lt extends Error{constructor(t){super(t.map(r=>`${r.field}: ${r.message}`).join("; ")),this.issues=t,this.code="params",this.name="ReportParamValidationError"}}function Xo(e){return/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))}function Zo(e,t){if(U(e))return au(e,t);if(e.type==="number"&&!Xo(t))return[["type","应为有限数字"]];const r=mu(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(...hu(e,t)),n}function hu(e,t){const r=e.type==="dateRange"?Yo(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 gu(e){const t=[];for(const o of["min","max"]){const i=e[o];if(i===void 0)continue;qo(e.type,i)||["number","numberRange"].includes(e.type??"")&&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,...pu(e),...uu(e)]}function pu(e){const t=[];U(e)&&(e.minLength!==void 0||e.maxLength!==void 0)&&t.push("复合参数使用项目数或数值边界,而不是文本长度约束"),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 Bt(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 wu(n,t).map(a=>({code:"definition",field:i,path:`$.paramDefs.${o}`,message:a}))});return r.length?r:du(e).map(({index:n,message:o})=>({code:"definition",field:e[n].field,path:`$.paramDefs.${n}`,message:o}))}function yu(e){const t=[];return e.type!==void 0&&!["text","number","date","month","year","dateRange","select","multiSelect","cascader","numberRange"].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&&!ou(e.options,e.type==="cascader",!U(e))&&t.push("选项应为包含字符串 label/value 的数组"),[...t,...lu(e)]}function wu(e,t){if(!e||typeof e!="object"||Array.isArray(e))return["参数定义项应为对象"];const r=yu(e);return typeof e.field!="string"||!e.field.trim()||t.has(e.field)?r.push("参数名应为非空且不重复的字符串"):t.add(e.field),r.length||(r.push(...gu(e)),r.length)||e.defaultValue!==void 0&&(e.required&&(!e.defaultValue.trim()||U(e)&&Dt(e,e.defaultValue)?.length===0)?r.push("必填参数的默认值不能为空"):e.defaultValue.trim()&&r.push(...Zo(e,e.defaultValue).map(([,n])=>`默认值${n}`))),r}function bu(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 vt(e){return e==null||typeof e=="string"&&!e.trim()}function ur(e,t={}){const r=Object.create(null),n=Object.create(null),o=Bt(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};bu(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;xu(i,s,{values:r,typedValues:n,issues:o})}return o.push(...vu(e,r)),{ok:o.length===0,values:r,typedValues:n,issues:o}}function xu(e,t,r){const{values:n,typedValues:o,issues:i}=r,s=(f,d)=>i.push({code:f,path:`$.params.${e.field}`,field:e.field,message:d}),a=U(e)&&!vt(t)?Dt(e,t):void 0;if(vt(t)||a?.length===0){e.required&&s("required","此参数为必填项"),(typeof t=="string"||a)&&(n[e.field]=a?"":String(t)),delete o[e.field];return}if(!a&&typeof t!="string"&&!(typeof t=="number"&&Number.isFinite(t))){s("type","参数应为字符串、有限数字或当前控件的规范数组");return}const c=a?JSON.stringify(a):String(t);n[e.field]=c;const u=Zo(e,c);u.forEach(([f,d])=>s(f,d)),u.length&&U(e)?delete o[e.field]:o[e.field]=a??(e.type==="number"&&Xo(c)?Number(c):c)}function vu(e,t){return e.flatMap(r=>!vt(t[r.field])&&r.dependsOn?.some(n=>vt(t[n]))?[{code:"dependency",path:`$.params.${r.field}`,field:r.field,message:"请先填写联动依赖的上级参数"}]:[])}function En(e,t={}){const r=ur(e,t);if(!r.ok)throw new Lt(r.issues);return r.values}function Mu(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 $u(e){const t={type:e.type==="number"?"number":"string",title:e.label??e.field,...Mu(e)};return U(e)&&Object.assign(t,fu(e)),e.required&&!U(e)&&e.type!=="number"&&!t.pattern&&(t.pattern="\\S"),e.type==="select"&&e.options&&(t.enum=e.options.map(r=>r.value)),Object.assign(t,Eu(e)),Object.assign(t,Su(e)),t}function Su(e){const t={};return e.defaultValue!==void 0&&(!(e.type==="number"||U(e))||e.defaultValue.trim())&&(t.default=U(e)?Dt(e,e.defaultValue):e.type==="number"?Number(e.defaultValue):e.defaultValue),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),!U(e)&&typeof e.min=="number"&&(t.minimum=e.min),!U(e)&&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 Eu(e){return{...e.optionsSource?{"x-report-options-source":e.optionsSource}:{},...e.dependsOn?.length?{"x-report-depends-on":[...e.dependsOn]}:{}}}function Au(e){const t=Bt(e);if(t.length)throw new Lt(t);return{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:Object.fromEntries(e.map(r=>[r.field,$u(r)])),required:e.filter(r=>r.required).map(r=>r.field),additionalProperties:!0}}function Mt(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=Bt(i);if(s.length)throw new Lt(s);return i.filter(a=>r.has(a.field)?!1:(r.add(a.field),!0))})}function ku(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fr(e,t,r){if(e!==void 0)try{q(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function Qo(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(!ku(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{oe({...o,field:o.valueField??a})}catch(c){r.push({path:s,message:c instanceof Error?c.message:String(c)})}})}function Nu(e,t,r){if(e===void 0)return;const n=Ks(e);for(const o of n.errors)r.push({path:t,message:o})}function Pu(e,t,r){if(e!==void 0)try{Rr(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function Fu(e,t,r){if(e.tree===void 0)return;const n=`${t}.tree`;try{lo(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)&&Tr(o,e.computed)}catch(o){r.push({path:n,message:o instanceof Error?o.message:String(o)})}}const Ou=1e7,Ru=new Set(["__proto__","prototype","constructor"]),Iu=new Set(["text","number","boolean","date","decimal"]);function nt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function lr(e){return typeof e=="string"&&!!e.trim()&&e.length<=4096&&!Ru.has(e)}function Cu(e,t,r){if(!Array.isArray(e)||!e.length||e.length>2048){r.push({path:t,message:"绑定契约应包含 1–2048 个字段"});return}const n=new Set;e.forEach((o,i)=>{const s=`${t}.${i}`;if(!nt(o)||!lr(o.field)||n.has(o.field)){r.push({path:s,message:"字段名应安全、非空且唯一"});return}n.add(o.field);for(const a of["label","semanticKey","unit"])o[a]!==void 0&&(typeof o[a]!="string"||String(o[a]).length>4096)&&r.push({path:`${s}.${a}`,message:"应为不超过 4096 位的字符串"});o.type!==void 0&&!Iu.has(String(o.type))&&r.push({path:`${s}.type`,message:"未知绑定字段类型"})})}function Tu(e,t,r){if(e===void 0)return;if(!nt(e)||!nt(e.datasets)){r.push({path:t,message:"模板数据契约应声明 datasets"});return}e.source!==void 0&&!lr(e.source)&&r.push({path:`${t}.source`,message:"来源应为安全的非空业务标识"});const n=Object.entries(e.datasets);(!n.length||n.length>256)&&r.push({path:`${t}.datasets`,message:"应声明 1–256 个数据集"});for(const[o,i]of n){const s=`${t}.datasets.${o}`;!lr(o)||!nt(i)?r.push({path:s,message:"数据集应使用安全名称和字段契约"}):Cu(i.fields,`${s}.fields`,r)}}class ju extends Error{constructor(t){super(`模板校验失败:${t.slice(0,3).map(r=>`${r.path}: ${r.message}`).join("; ")}`),this.errors=t,this.name="ReportTemplateError"}}const Du=new Set(["__proto__","prototype","constructor"]),Lu=new Set(["left","center","right","justify"]),ot=2e5,Bu=64;function C(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function _u(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 Ku(e,t,r,n){return Du.has(e)?(n.push({path:r,message:"模板不能包含可能污染原型的键"}),!1):t.get||t.set||!t.enumerable?(n.push({path:r,message:"模板不能包含访问器或不可枚举字段"}),!1):!0}function Wu(e){return e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)}function Ju(e,t){const r=new Set;let n=0,o=0,i=!1;const s=(a,c,u)=>{if(!i){if(++n>ot){n===ot+1&&t.push({path:c,message:"模板超过 JSON 节点安全上限"});return}if(u>Bu){t.push({path:c,message:"模板嵌套层级过深"});return}if(typeof a=="string"){o+=a.length,o>Ou&&(i=!0,t.push({path:c,message:"模板文本超过 1000 万字符的安全上限"}));return}if(!Wu(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(_u(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(Ku(f,d,l,t)&&s(d.value,l,u+1),n>ot||i)break}r.delete(a)}}}};s(e,"$",0)}function _(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 ae(e,t,r,n){e[t]!==void 0&&typeof e[t]!="boolean"&&n.push({path:`${r}.${t}`,message:"应为布尔值"})}function Ae(e,t,r,n=!1){e!==void 0&&!Lu.has(e)&&!(n&&e==="auto")&&r.push({path:t,message:`未知对齐方式${n?"(支持 auto)":""}`})}function re(e,t,r){if(e!==void 0){if(!C(e)){r.push({path:t,message:"样式应为对象"});return}Ae(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"])ae(e,n,t,r);for(const n of["fontFamily","color","backgroundColor","lineColor","borderColor"])_(e,n,t,r)}}function zu(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(!C(i)){r.push({path:a,message:"参数定义应为对象"});return}_(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","multiSelect","cascader","numberRange"].includes(i.type)&&r.push({path:`${a}.type`,message:"未知参数类型"});for(const c of["label","defaultValue","placeholder"])_(i,c,a,r);ae(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:"长度边界应为非负整数"})}Vu(i,a,r),i.options!==void 0&&(Array.isArray(i.options)?i.options.forEach((c,u)=>{const f=`${a}.options.${u}`;if(!C(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(...Bt(e).map(i=>({path:i.path.replace("$.paramDefs",t),message:i.message})))}function Vu(e,t,r){for(const i of["min","max"]){const s=e[i];if(s===void 0)continue;qo(e.type,s)||["number","numberRange"].includes(e.type)&&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 ei(e,t,r){if(!Array.isArray(e)||e.length===0){r.push({path:t,message:"列表至少需要一列"});return}e.every(n=>C(n)&&n.hidden===!0)&&r.push({path:t,message:"列表至少需要一列可见列"}),e.forEach((n,o)=>{const i=`${t}.${o}`;if(!C(n)){r.push({path:i,message:"列应为对象"});return}if(_o(n,i,r),n.visual!==void 0&&!$o(n.visual)&&r.push({path:`${i}.visual`,message:"列可视化配置无效,请检查类型、数值范围和颜色"}),ae(n,"hidden",i,r),fr(n.visibleWhen,`${i}.visibleWhen`,r),typeof n.header!="string"&&r.push({path:`${i}.header`,message:"表头应为字符串(允许空白表头)"}),_(n,"field",i,r,!0),W(n,"widthMm",i,r,Number.MIN_VALUE,!0),re(n.style,`${i}.style`,r),re(n.headerStyle,`${i}.headerStyle`,r),Ae(n.align,`${i}.align`,r,!0),Ae(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(!C(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 的整数"}),ae(n.format,"thousands",`${i}.format`,r),_(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(!C(s)||!C(s.when)){r.push({path:c,message:"条件格式缺少 when 对象"});return}fr(s.when,`${c}.when`,r),re(s.style,`${c}.style`,r)}):r.push({path:`${i}.rules`,message:"条件格式应为数组"}))})}function ti(e,t,r){if(e!==void 0){if(!C(e)){r.push({path:t,message:"分组应为对象"});return}_(e,"field",t,r,!0);for(const n of["headerTemplate","subtotalLabel"])_(e,n,t,r);for(const n of["headerStyle","subtotalStyle"])re(e[n],`${t}.${n}`,r);ae(e,"keepWithNext",t,r),ae(e,"repeatHeader",t,r),Qo(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 Hu(e,t,r){if(!(e===void 0||typeof e=="boolean")){if(!C(e)){r.push({path:t,message:"合计应为布尔值或对象"});return}_(e,"label",t,r),Qo(e.aggregates,`${t}.aggregates`,r),re(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 Uu(e,t,r,n){const o={kind:"rect",leftMm:0,topMm:0,widthMm:1,heightMm:1,grid:e};if(Jo(o,r,n,[]),Yr(o,r,n),!C(e)||!Array.isArray(e.cells))return;const i=e.cells,s=Array.isArray(t)?t.length:0;if(i.length*s>ot){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:"表头行高数量应与行数一致"}),Gu(i,s,r,n)}function Gu(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=C(c)&&typeof c.colSpan=="number"?c.colSpan:1,d=C(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 Yu(e,t,r){if(Fu(e,t,r),Nu(e.computed,`${t}.computed`,r),Pu(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 汇总,不能同时配置普通分组、总计或主从明细"}),fr(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)=>ti(i,`${t}.groups.${s}`,r))),e.detail===void 0)return;const n=e.detail,o=`${t}.detail`;if(!C(n)){r.push({path:o,message:"主从关联应为对象"});return}for(const i of["dataset","parentKey","foreignKey"])_(n,i,o,r,!0);for(const i of["rowKey","revisionField","sourceTokenField"])_(n,i,o,r,n[i]!==void 0);_(n,"label",o,r),ae(n,"header",o,r),W(n,"rowHeightMm",o,r,Number.MIN_VALUE),ei(n.columns,`${o}.columns`,r),n.unmatched!==void 0&&n.unmatched!=="error"&&n.unmatched!=="ignore"&&r.push({path:`${o}.unmatched`,message:"未关联明细策略应为 error 或 ignore"})}function qu(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),_(e,"dataset",t,r,!0),_(e,"title",t,r);for(const n of["rowKey","revisionField","sourceTokenField"])_(e,n,t,r,e[n]!==void 0);e.headerGrid!==void 0&&Uu(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"}),ei(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"])ae(e,n,t,r);e.cardinality!==void 0&&e.cardinality!=="record"&&r.push({path:`${t}.cardinality`,message:"单记录区域类型应为 record"}),_(e,"headerBackgroundColor",t,r),Ae(e.align,`${t}.align`,r,!0),Ae(e.headerAlign,`${t}.headerAlign`,r),re(e.headerStyle,`${t}.headerStyle`,r),Yu(e,t,r),ti(e.groupBy,`${t}.groupBy`,r),Hu(e.grandTotal,`${t}.grandTotal`,r)}function An(e,t,r){Array.isArray(e.richParagraphs)&&e.richParagraphs.forEach((n,o)=>{if(!C(n))return;const i=`${t}.richParagraphs.${o}`;Ae(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(!C(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"])_(s,u,c,r);re(s.style,`${c}.style`,r)})})}function Yr(e,t,r){re(e.style,`${t}.style`,r);for(const o of["text","rawText","imageData","fallbackText","nid","rkey"])_(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:"文本行应为字符串数组"}),An(e,t,r),!C(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(!C(s)){r.push({path:c,message:"网格单元格应为对象或 null"});return}for(const u of["text","rawText","numberFormat"])_(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"}),re(s.style,`${c}.style`,r),An(s,c,r),s.children!==void 0&&(Array.isArray(s.children)?s.children.forEach((u,f)=>{C(u)&&Yr(u,`${c}.children.${f}`,r)}):r.push({path:`${c}.children`,message:"嵌套组件应为数组"}))}})})}function Xu(e,t,r){if(!(e.flow===void 0||!Array.isArray(e.components)))try{yo(e.components,e.flow)}catch(n){r.push({path:`${t}.flow`,message:n instanceof Error?n.message:String(n)})}}function Zu(e){const t=[],r=[];return Ju(e,t),t.length?{ok:!1,errors:t,warnings:r}:(C(e)?(e.schemaVersion!==void 0&&e.schemaVersion!==ze&&t.push({path:"$.schemaVersion",message:"不支持的模板 schemaVersion"}),zu(e.params,"$.params",t),Tu(e.dataContract,"$.dataContract",t),bo(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(!C(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}`;C(s)&&s.kind==="list"?qu(s,c,t):(Jo(s,c,t,r),C(s)&&Yr(s,c,t))}):t.push({path:`${i}.components`,message:"组件应为数组"}),Xu(n,i,t)})):t.push({path:"$",message:"模板应为对象"}),{ok:t.length===0,errors:t,warnings:r})}class Qu extends Error{constructor(t){super(t.map(r=>r.message).join(";")),this.issues=t,this.name="ReportValidationError"}}function kn(e,t,r){if(!Number.isSafeInteger(e)||e<1||e>r)throw new Error(`校验 ${t} 超出预算`);return e}function ef(e){if(e.aggregates&&e.scope!=="dataset")throw new Error("仅数据集规则允许汇总");if(e.aggregates&&(!Array.isArray(e.aggregates)||e.aggregates.length>64))throw new Error("校验汇总最多 64 项");const t=new Set;for(const r of e.aggregates??[]){if(K(r.field),t.has(r.field))throw new Error("校验汇总字段重复");t.add(r.field),r.valueField!==void 0&&K(r.valueField),r.weightField!==void 0&&K(r.weightField),Be([],{...r,field:r.valueField??r.field})}}function ri(e){if(!Array.isArray(e)||e.length>256||Object.keys(e).length!==e.length)throw new Error("校验规则最多 256 条且不允许空位");const t=new Set;return e.map(r=>{if(!r||typeof r!="object")throw new Error("校验规则应为声明式对象");if(K(r.id),t.has(r.id))throw new Error("校验规则 id 重复");if(t.add(r.id),r.field!==void 0&&K(r.field),r.dataset!==void 0&&K(r.dataset),typeof r.message!="string"||!r.message.trim()||r.message.length>2048)throw new Error("校验规则需要有界提示文案");if(r.severity!==void 0&&!["error","warning"].includes(r.severity))throw new Error("未知校验严重程度");if(r.scope!==void 0&&!["row","dataset"].includes(r.scope))throw new Error("未知校验范围");ef(r);const n={nodes:0},o=q(r.assert,n),i=r.when?q(r.when,n):void 0;return{rule:r,assert:o,when:i,checks:n.nodes}})}function Nn(e){if(e?.aborted){const t=new Error("报表校验已取消");throw t.name="AbortError",t}}function tf(e,t,r,n){const o=n&&Object.prototype.hasOwnProperty.call(t,n)?t[n]:void 0;if(o!==void 0&&typeof o!="string"&&!(typeof o=="number"&&Number.isFinite(o)))throw new Error("校验定位需要稳定的文本或数值业务键");return{ruleId:e.id,rowIndex:r,...o===void 0?{}:{rowKey:o},field:e.field,severity:e.severity??"error",message:e.message}}function rf(e,t){const r=t.computed?.length?{fields:t.computed,formula:t.formula,signal:t.signal}:void 0;if(t.tree){const o=po(e,t.tree,{signal:t.signal,computed:r});if(o.rows.length>1e5)throw new Error("校验展开后数据最多 100000 行");return{rows:o.rows,summaryRows:o.leaves,rowKey:t.tree.idField}}const n=r?Rt(e,r).rows:e;return{rows:n,summaryRows:n,rowKey:t.rowKey}}function nf(e,t){const r=new Set;e.forEach(n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("校验数据行应为对象");if(!t)return;const o=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0;if(!(typeof o=="string"&&o.trim())&&!(typeof o=="number"&&Number.isFinite(o)))throw new Error("校验定位需要稳定业务键");if(r.has(o))throw new Error("校验业务键重复");r.add(o)})}function of(e,t,r){if(!Array.isArray(e)||e.length>1e5)throw new Error("校验数据最多 100000 行");Nn(t.signal);const n=kn(t.maxChecks??2e6,"maxChecks",1e7),o=kn(t.maxIssues??1e3,"maxIssues",1e4);t.rowKey!==void 0&&K(t.rowKey);const i=rf(e,t),{rows:s,summaryRows:a,rowKey:c}=i;nf(s,c);const u=ri(t.rules),f=u.reduce((l,m)=>l+(m.rule.scope==="dataset"?m.checks+a.length*(m.rule.aggregates?.length??0):s.length*m.checks),0);if(r.checks+=f,r.checks>n)throw new Error("整批校验超出 maxChecks 预算");const d=[];for(const l of u)(l.rule.scope==="dataset"?[Object.fromEntries((l.rule.aggregates??[]).map(h=>[h.field,Be(a,{...h,field:h.valueField??h.field})]))]:s).forEach((h,p)=>{if(Nn(t.signal),!h||typeof h!="object"||Array.isArray(h))throw new Error("校验数据行应为对象");if(!(l.when&&!l.when(h)||l.assert(h))){if(d.length>=o)throw new Error("校验问题超出 maxIssues 预算,请缩小范围");d.push(tf(l.rule,h,l.rule.scope==="dataset"?void 0:p,l.rule.scope==="dataset"?void 0:c))}});return d}function sf(e,t="allow"){if(!["allow","block"].includes(t))throw new Error("未知校验警告策略");if(!Array.isArray(e)||e.length>1e4||e.some(r=>!r||!["error","warning"].includes(r.severity)||typeof r.ruleId!="string"||!r.ruleId.trim()||typeof r.message!="string"||!r.message.trim()))throw new Error("校验问题结构无效");if(e.some(r=>r.severity==="error"||t==="block"))throw new Qu(e)}function Pn(e,t,r){const n=e.get(t);if(n&&JSON.stringify(n)!==JSON.stringify(r))throw new Error("同一数据集的校验计算/业务键存在歧义,请统一绑定");e.set(t,r)}function af(e,t,r,n=[]){ri(t.rules);const o=[],i={checks:0};for(const[a,c]of e.entries()){const u=new Map;for(const f of c.template.pages)for(const d of f.components)d.kind==="list"&&(Pn(u,d.dataset,{rowKey:d.tree?.idField??d.rowKey,computed:d.computed,tree:d.tree}),d.detail&&Pn(u,d.detail.dataset,{rowKey:d.detail.rowKey}));for(const[f,d]of u){const l=t.rules.filter(m=>!m.dataset||m.dataset===f);if(l.length&&(o.push(...of(c.datasets[f]??[],{...t,rules:l,...d,formula:n[a],signal:r},i).map(m=>({...m,dataset:f,sourceScope:c.sourceScope}))),o.length>(t.maxIssues??1e3)))throw new Error("整批候选校验问题超出 maxIssues 预算")}}const s=new Set(e.flatMap(a=>a.template.pages.flatMap(c=>c.components.flatMap(u=>u.kind==="list"?[u.dataset,...u.detail?[u.detail.dataset]:[]]:[]))));if(t.rules.some(a=>a.dataset&&!s.has(a.dataset)))throw new Error("校验目标数据集不存在");return o}function cf(e){return!e||typeof e!="object"?!1:[e.pageIndex,e.componentIndex,e.rowIndex,e.columnIndex].every(t=>Number.isInteger(t)&&t>=0)}function uf(e){return e.value!==void 0?e.value:e.rawText??e.text??null}function ff(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 lf(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 df(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 mf(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 hf(e,t,r){const n=uf(r),o=lf(r,e);return{address:{...t},cell:r,component:e,value:n,valueType:ff(r,n),table:df(e,t),source:mf(r,e,t),editable:o===void 0,readOnlyReason:o}}function ni(e){const t=new Map;return r=>{if(!cf(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 no(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?hf(n,r,i):null}}function gf(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 pf(e,t){const r=gf(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 yf(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 Re(e,t){return/[0#?@_*%[\]"\\.,/]/.test(e)?null:e.replace(/[\uE000-\uF8FF]/g,r=>t.literals[r.charCodeAt(0)-57344]??"")}function wf(e,t){const r=/^(.*?)(0)(?:\.([0#]+))?E([+-])(0+)(.*?)$/i.exec(t.text);if(!r)return null;const n=Re(r[1],t),o=Re(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]==="+"?"+":"",h=String(Math.abs(l)).padStart(r[5].length,"0");return`${e.negative?"-":""}${n}${u}${d?`.${d}`:""}E${m}${h}${o}`}function bf(e,t){const r=/^(.*?)([#,]*0[0#]*)(?:\.([0#]+))?(%)?(.*?)$/.exec(t.text);if(!r)return Re(t.text,t);const n=Re(r[1],t),o=Re(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 xf(e,t,r){if(!t||/^(General|@)$/i.test(t))return String(e);const n=pf(e,t);if(n.pattern==="")return"";const o=yf(n.pattern),i=wf(n,o)??bf(n,o);return i!==null?i:String(e)}function vf(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 Mf(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 $f(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:Mf(e,vf(t.cell.numberFormat));if(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r))throw new P("number");return r}function Sf(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 Ef(e,t){return e.valueType==="number"?$f(t,e):e.valueType==="boolean"?Sf(t):t===null?null:String(t)}function Af(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 oi(e,t){return t===null?"":typeof t=="boolean"?Af(t,e):typeof t=="number"?xf(t,e.cell.numberFormat):String(t)}function ii(e,t){if(!e.editable)throw new P("readonly");const r=Ef(e,t);return{address:{...e.address},table:e.table,source:e.source,previousValue:e.value,previousText:e.cell.text??"",value:r,text:oi(e,r)}}function kf(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 si(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 ke(e){return JSON.stringify([e.sourceScope,e.datasetId])}function Fn(e){return JSON.stringify([e.sourceScope,e.datasetId,e.rowKey])}function ai(e){const t=new Map,r=new Set;return e.forEach((n,o)=>{for(const i of si(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=Fn({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(Fn(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 ci(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);Ts(e[i].datasets[s],r[i].datasets[s])}return r}function Nf(e,t,r){const n=[],o=new Set;return e.forEach((i,s)=>{for(const a of si(i))t.has(ke({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 Pf(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?[ke(o.source)]:[]));return ui(e,new Map([...n].map(o=>[o,r])))}function ui(e,t){if(!t.size)return e;function r(i){const s=i.datasetId&&t.get(ke({...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(h=>{if(!h)return h;const p=h.source?r(h.source):void 0,w=h.children?n(h.children):void 0;return p===h.source&&w===h.children?h:{...h,source:p,children:w}});return m.some((h,p)=>h!==l[p])?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 $t(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 Ff(e){const t=new Map,r=ni(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($t(u),u)}})),t}function fi(e,t){if(++e.nodes>1e6||t>128)throw new P("limit")}function St(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw new P("conflict");return r.value}function qr(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 li(e,t,r,n,o){if(fi(n,o),typeof e=="function"||typeof e=="symbol")throw new P("conflict");if(e===null||typeof e!="object")return;if(qr(e),r.has(e))throw new P("conflict");r.add(e);const i=Object.keys(e),s=i.map(a=>St(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)li(a,t,r,n,o+1);r.delete(e)}function Of(e){const{object:t,keys:r,values:n}=e;if(qr(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(St(t,i),n[s]))}function Rf(e){const t=[];return li(e,t,new Set,{nodes:0},0),()=>{try{return t.every(Of)}catch{return!1}}}function Et(e,t,r,n=!1){if(fi(t,r),n){if(typeof e=="function"||typeof e=="symbol")throw new P("conflict");e!==null&&typeof e=="object"&&qr(e)}if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(Date.prototype.getTime.call(e));if(Array.isArray(e)){const o=[];for(let i=0;i<e.length;i++)o[i]=Et(St(e,String(i)),t,r+1,n);return o}return Object.fromEntries(Object.keys(e).map(o=>[o,Et(St(e,o),t,r+1,n)]))}function If(e){return Et(e,{nodes:0},0,!0)}function Cf(e){const t=Et(e,{nodes:0},0);for(const r of t)for(const n of Object.values(r.datasets))Cs(n);return t}async function Tf(e,t,r={}){return jo(e,t,{...r,knownTotalPages:void 0})}const On=new WeakMap;function qe(e){if(e?.aborted){const t=new Error("报表重算已取消");throw t.name="AbortError",t}}function di(e,t){return e[t]===void 0?"":e[t]}function jf(e,t){if(t.edits.length>1e4)throw new P("limit");const r=ni(e),n=new Set,o=[],i=t.edits.map(s=>{const a=r(s.address);if(!a?.source)throw new P("missing");const c=$t(s);if(n.has(c))throw new P("duplicate");if(n.add(c),kf(a,s)||!Object.is(a.value,s.previousValue)||(a.cell.text??"")!==s.previousText)throw new P("conflict");return o.push(a),ii(a,s.value)});return{batch:{requestId:t.requestId,edits:i},contexts:o}}function Df(e,t){const r=ai(e);return t.flatMap(n=>{if(!n.source)throw new P("missing");return r(n.source).map(o=>{if(!Object.is(di(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 qt(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:oi(n,n.value)},n}function Lf(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?[ke(o.source)]:[]));return ci(e,Nf(e,n,r))}function Bf(e,t,r){const n=new Set(t.edits.map(o=>ke(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 _f(e,t){let r=t.parts;const n=t.rebuild,o=[...t.validationFormulas??[]];let i=Rf(r),s=e,a;const c=new Map,u=new Map;function f(m){if(m!==s)throw new P("conflict");if(a)return a;if(!i?.())throw new P("conflict");return Cf(r)}async function d(m,h,p,w={}){qe(w.signal),h={requestId:h.requestId,edits:h.edits.map(M=>({...M,address:{...M.address},source:M.source?{...M.source}:void 0,table:M.table?{...M.table}:void 0}))},p=p.map(M=>({...M,address:{...M.address},source:M.source?{...M.source}:void 0,table:M.table?{...M.table}:void 0,cell:{...M.cell}})),await new Promise(M=>setTimeout(M,0)),qe(w.signal);const y=f(m),g=ci(y,Df(y,h.edits)),x=ui(await n(g,w.signal),u);qe(w.signal);let b=!1,$=[],T="allow",j=!1;function v(M){return j=!0,$=Object.freeze(af(g,M,w.signal,o).map(S=>Object.freeze({...S}))),j=!1,T=M.warningPolicy??"allow",$}return w.validation&&v(w.validation),{plan:x,get validationIssues(){return $},validate:v,commit(M){if(qe(w.signal),b||s!==m)throw new P("conflict");if(M?.conflicts?.length)throw new P("conflict");if(j)throw new Error("候选规则校验未完成,不能提交");sf($,T);const S=Lf(g,h,M),I=Pf(x,h,M);if(M){const N=Bf(u,h,M);for(const[R,pe]of c)N.has(ke(pe.source))&&c.set(R,qt(pe,pe.value,M))}return p.forEach((N,R)=>c.set($t(N),qt(N,h.edits[R].value,M))),b=!0,a=S,r=void 0,i=void 0,s=I,On.set(s,l),s}}}const l={get plan(){return s},async prepare(m,h,p){const w=jf(m,h);return d(m,w.batch,w.contexts,p)},async prepareHistory(m,h,p,w,y){if(!w.trim()||h.length>1e4)throw new P("limit");const g=f(m),x=ai(g),b=Ff(m),$=new Set,j=h.map(S=>{if(!S.source)throw new P("missing");const I=$t(S);if($.has(I))throw new P("duplicate");$.add(I);const N=b.get(I)??c.get(I);if(!N?.source)throw new P("missing");const R=x(N.source)[0];return qt(N,di(R.row,N.source.field))}).map((S,I)=>({context:S,edit:ii(S,h[I][p])})).filter(({edit:S})=>!Object.is(S.previousValue,S.value)),v={requestId:w,edits:j.map(({edit:S})=>S)},M=j.map(({context:S})=>S);return{batch:v,contexts:M,prepared:await d(m,v,M,y)}}};return On.set(e,l),l}let Kf=0;function it(){return`report-${Date.now()}-${++Kf}`}function Me(e,t,r){if(!r?.aborted)try{const n=e?.({...t});n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{})}catch{}}function de(e){const t=e.taskId??it(),r=(n,o,i)=>{Me(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){Me(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 Y(e){throw new Error(`数据契约无效:${e}`)}function dr(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}function Wf(e){for(const t of["description","missingMeaning"])e[t]!==void 0&&!dr(e[t])&&Y(`${t} 应为 1–4096 位非空字符串`);e.aggregation!==void 0&&!["sum","avg","min","max","count","none"].includes(e.aggregation)&&Y("未知字段聚合语义"),e.aggregation&&!["count","none"].includes(e.aggregation)&&!["number","decimal"].includes(e.type)&&Y("数值聚合仅适用于 number/decimal"),e.format!==void 0&&Jf(e),e.calculation!==void 0&&(!e.calculation||!dr(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)&&Y("计算说明需包含说明及 1–256 个唯一依赖字段")}function Jf(e){const t=e.format;if((!t||!["number","percent","date"].includes(t.kind))&&Y("未知字段显示格式"),t.kind==="date"){(e.type!=="date"||t.pattern!==void 0&&(!dr(t.pattern)||t.pattern.length>128))&&Y("日期格式仅适用于日期,pattern 最多 128 位");return}["number","decimal"].includes(e.type)||Y("数值显示格式仅适用于 number/decimal"),t.digits!==void 0&&(!Number.isSafeInteger(t.digits)||t.digits<0||t.digits>100)&&Y("显示小数位应为 0–100 的整数"),t.kind==="number"&&t.thousands!==void 0&&typeof t.thousands!="boolean"&&Y("thousands 应为布尔值")}function zf(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)&&Y("字段计算依赖存在循环"),r.has(s.field))continue;const a=t.get(s.field);a||Y(`计算依赖字段未声明:${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 Vf=["text","number","boolean","date","decimal"],Hf=new Set(["__proto__","prototype","constructor"]);function J(e){throw new Error(`数据契约无效:${e}`)}function mi(e){(!e||!Array.isArray(e.fields)||!e.fields.length||e.fields.length>2048)&&J("fields 应包含 1–2048 个字段");const t=new Set;for(const r of e.fields)(!r||typeof r.field!="string"||!r.field.trim()||Hf.has(r.field)||t.has(r.field))&&J("字段名应安全、非空且唯一"),t.add(r.field),Vf.includes(r.type)||J(`未知字段类型 ${r.type}`),qf(r),Yf(r),Wf(r),Uf(r);Gf(e,t),zf(e.fields)}function Uf(e){e.enum!==void 0&&(!Array.isArray(e.enum)||!e.enum.length||e.enum.some(t=>!hi(t,e.type)))&&J("enum 应为匹配字段类型的非空标量数组")}function Gf(e,t){e.rowKey!==void 0&&((typeof e.rowKey!="string"||!e.rowKey.trim()||!t.has(e.rowKey))&&J("rowKey 应为引用已声明字段的非空字符串"),e.fields.find(r=>r.field===e.rowKey)?.type==="boolean"&&J("布尔字段不能作为业务主键"))}function Yf(e){for(const t of["label","unit"])e[t]!==void 0&&typeof e[t]!="string"&&J(`${t} 应为字符串`);for(const t of["required","nullable"])e[t]!==void 0&&typeof e[t]!="boolean"&&J(`${t} 应为布尔值`);e.semanticRole!==void 0&&!["identifier","dimension","measure","date","text"].includes(e.semanticRole)&&J("未知字段语义")}function qf(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))&&J(`${t} 无效`)}e.min!==void 0&&e.max!==void 0&&e.min>e.max&&J("min 不能超过 max"),e.minLength!==void 0&&e.maxLength!==void 0&&e.minLength>e.maxLength&&J("minLength 不能超过 maxLength"),e.type!=="number"&&(e.min!==void 0||e.max!==void 0)&&J("min/max 仅适用于 number,精确小数文本需业务校验"),["number","boolean"].includes(e.type)&&(e.minLength!==void 0||e.maxLength!==void 0)&&J("长度约束仅适用于文本类型")}function Xf(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 hi(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":typeof e!="string"?!1:t==="date"?Xf(e):t==="decimal"?e.length<=1e4&&/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e):!0}function Zf(e,t){if(e==null)return t.required||e===null&&t.nullable===!1?{code:"required",message:"缺少必需字段值"}:void 0;if(!hi(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"&&!Qf(e,t))return{code:"range",message:"文本长度超出范围"}}function Qf(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 Xt(e,t){const r=e??t;if(!Number.isInteger(r)||r<1)throw new Error("数据校验预算应为正整数");return r}function el(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 tl(e,t,r={}){mi(t);const n=r.path??"$.rows",o=[],i=Xt(r.maxIssues,100);if(!Array.isArray(e))return{ok:!1,issues:[{code:"row",path:n,message:"数据集应为对象数组"}]};if(e.length>Xt(r.maxRows,1e5)||e.length*t.fields.length>Xt(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}rl(c,t,a,n,s,o,i)}return{ok:o.length===0,issues:o}}function rl(e,t,r,n,o,i,s){for(const a of t.fields){if(i.length>=s)return;const c=Zf(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=el(e,t.rowKey,o);a&&i.push({code:"row-key",path:`${n}[${r}].${t.rowKey}`,message:a,rowIndex:r,field:t.rowKey})}}function nl(e){return mi(e),{$schema:"https://json-schema.org/draft/2020-12/schema",type:"array",items:{type:"object",properties:Object.fromEntries(e.fields.map(r=>[r.field,ol(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 ol(e,t){const r=!t&&e.nullable!==!1&&!e.required;return{type:r?[Rn(e.type),"null"]:Rn(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},...il(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 il(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 Rn(e){return e==="text"||e==="date"||e==="decimal"?"string":e}function sl(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 al(e){return e==="missing-source"||e==="not-applicable"||e==="not-calculable"}function Xr(e){return e.target!==void 0&&!sl(e.target)?!1:e.valueState===void 0||al(e.valueState)&&e.target!==void 0}function gi(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]=go(t[i]??[],{...s,maxRows:a},r.signal)}return o}function cl(e,t,r={}){return Object.values(gi(e,t,r)).reduce((n,o)=>n+o.length,0)}function ul(e,t,r){const n=nl(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 Zr(e,t){return JSON.stringify([e,t])}function pi(e,t,r){return r===void 0?Zr(e,t):JSON.stringify(["shared",r])}function yi(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:yi(a.children,t,r)}:{}}));return o||i?{...n,...o?{table:o}:{},...i?{grid:{...n.grid,cells:i}}:{}}:n})}function mr(e){return It(e.maxChartComponents),{maxPages:e.maxPages,maxCells:e.maxCells,maxChartComponents:e.maxChartComponents??Or,usedPages:0,usedCells:0,usedChartComponents:0}}function fl(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 ll(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 hr(e,t){return e===void 0?void 0:e-t}function Zt(e,t){return e===void 0?t:Math.max(1,Math.min(e,t??e))}function wi(e,t,r,n,o){It(e?.maxChartComponents);const i=hr(t.maxPages,t.usedPages),s=t.maxChartComponents-t.usedChartComponents;if(i!==void 0&&i<1&&r.pages.length&&!fl(r,n))throw new Se(0,1);if(s<1&&r.pages.some(a=>a.components.some(c=>c.kind!=="list"&&c.chartBinding)))throw new Ke(s,1);return{...e,signal:o??e?.signal,maxPages:Zt(i,e?.maxPages),maxCells:Zt(hr(t.maxCells,t.usedCells),e?.maxCells),maxChartComponents:Zt(s,e?.maxChartComponents)}}function bi(e,t){const r=ll(t.plan),n=hr(e.maxCells,e.usedCells);if(n!==void 0&&r>n)throw new _e(n,r);e.usedPages+=t.plan.pages.length,e.usedCells+=r,e.usedChartComponents+=t.chartComponents}function xi(e,t){return e instanceof Se&&t.maxPages!==void 0&&(e.limit===t.maxPages-t.usedPages||e.limit===0)?new Se(t.maxPages,t.usedPages+e.actual):e instanceof _e&&t.maxCells!==void 0?new _e(t.maxCells,t.usedCells+e.actual):e instanceof Ke&&e.limit===t.maxChartComponents-t.usedChartComponents?new Ke(t.maxChartComponents,t.usedChartComponents+e.estimated):e}class E extends Error{constructor(t,r,n){super(r),this.name="ReportSourceError",this.code=t,this.cause=n}}function _t(e){const t=new Error("报表加载已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function G(e){if(e?.aborted)throw _t(e)}function gr(e,t){return t?new Promise((r,n)=>{const o=()=>t.removeEventListener("abort",i),i=()=>{o(),n(_t(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 dl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new E("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 E("validate",`报表 ${t} 的数据集 ${r} 应为对象数组`)}async function ml(e,t,r){const{reportId:n,signal:o}=t;try{const i=await gr(e(t),o);G(o);const s=Zu(i);if(!s.ok)throw new E("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?_t(o):i instanceof E?i:i instanceof ju?new E("validate",`报表 ${n} 模板校验失败:${i.message}`,i):new E("fetch",`报表 ${n} 模板加载失败:${i instanceof Error?i.message:String(i)}`,i)}}async function hl(e,t,r,n){const o=t.signal;let i;try{if(e.load)i=await gr(e.load(t),o);else if(e.provider){const s=await gr(e.provider.query(t),o);G(o),gl(s,r),i=s.datasets,n?.(r,s)}else i=e.datasets??{}}catch(s){throw o?.aborted?_t(o):s instanceof E?s:new E("fetch",`报表 ${r} 取数失败:${s instanceof Error?s.message:String(s)}`,s)}return G(o),i}function gl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new E("validate",`报表 ${t} Provider 应返回 datasets 结果对象`);for(const r of["revision","sourceToken"])if(e[r]!==void 0&&typeof e[r]!="string")throw new E("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 E("validate",`报表 ${t} Provider diagnostics 不符合结构化诊断契约`);if(e.diagnostics?.some(r=>!Xr(r)))throw new E("validate",`报表 ${t} Provider 数据说明缺少有效的字段身份或值状态`)}function pl(e,t,r,n,o){try{t=gi(n,t,{maxRows:e.dataValidation?.maxRows,signal:o})}catch(i){throw new E("validate",`报表 ${r} 树形数据无效:${i instanceof Error?i.message:String(i)}`,i)}for(const[i,s]of Object.entries(e.dataSchema??{})){let a;try{a=tl(Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0,s,{...e.dataValidation,path:`$.datasets.${i}`})}catch(c){throw new E("config",`报表 ${r} 数据集 ${i} 字段契约配置无效`,c)}if(!a.ok)throw new E("validate",`报表 ${r} 数据集 ${i} 不符合字段契约:${a.issues[0]?.message}`,{issues:a.issues})}}async function yl(e,t,r,n,o){try{let i;try{i=If(e)}catch{}const s=i??e,a=wi(t.pagination,n,s.template,s.datasets,o),c=i?await jo(s.template,s.datasets,a):Tc(s.template,s.datasets,a);return bi(n,c),{result:c,part:s}}catch(i){G(o);const s=xi(i,n);throw new E("validate",`报表 ${r} 排版失败:${s instanceof Error?s.message:String(s)}`,s)}}function vi(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:Zr(r,n)},components:yi(a.components,o??pi(r,n),s)})}async function wl(e,t,r,n,o){const i=[],s=mr(n);for(const[u,f]of e.entries()){G(o);try{const d=await Tf(f.template,f.datasets,wi(t[u]?.pagination,s,f.template,f.datasets,o));bi(s,d),vi(i,d.plan,u,r[u],f.sourceScope)}catch(d){throw xi(d,s)}}const a={schemaVersion:ze,...e.some(u=>Dr(u.template))?{requiresRecalculation:!0}:{},pages:i},c=Ue(a);if(!c.ok)throw new E("validate",`重算渲染计划校验失败:${c.errors[0]?.message}`);return a}function bl(e,t={}){if(t.maxPages!==void 0&&(!Number.isSafeInteger(t.maxPages)||t.maxPages<1))throw new E("config","maxPages 应为正安全整数");if(t.maxCells!==void 0&&(!Number.isSafeInteger(t.maxCells)||t.maxCells<1))throw new E("config","maxCells 应为正安全整数");try{mr(t)}catch(o){throw new E("config","maxChartComponents 应为 1..1000000 的安全整数",o)}function r(o){const i=Object.prototype.hasOwnProperty.call(e,o)?e[o]:void 0;if(!i)throw new E("config",`未注册报表 ${o}`);if(i.sourceScope!==void 0&&(typeof i.sourceScope!="string"||!i.sourceScope.trim()||i.sourceScope.length>512))throw new E("config","sourceScope 应为不超过 512 字符的非空字符串");return i}return Object.assign(async({reportIds:o,params:i,signal:s,onWarning:a,onQueryResult:c,...u})=>{G(s);const f=de({...u,signal:s}),d=[...o],l={...i};if(d.length===0)throw new E("config","缺少报表 ID");const m=d.map(r),h=f.runSync("validate",()=>m.map(v=>En(v.params??(typeof v.template=="function"?[]:v.template.params)??[],l))),p=[],w=[],y=mr(t),g=[];for(const[v,M]of m.entries()){G(s);const S=d[v],I={reportId:S,params:h[v],signal:s},N=typeof M.template=="function"?await f.run("query",()=>ml(M.template,I,g),S):M.template;I.params=f.runSync("validate",()=>En(M.params??N.params??[],I.params),S);const R=await f.run("query",()=>hl(M,I,S,(Jt,qi)=>c?.(Jt,qi,v)),S);f.runSync("validate",()=>{dl(R,S),t.onDatasets?.(S,R,N),pl(M,R,S,N,s)},S),G(s);const pe=pi(v,S,M.sourceScope),{result:tn,part:Yi}=await f.run("layout",()=>yl({template:N,datasets:R,sourceScope:pe},M,S,y,s),S);w.push(Yi),vi(p,tn.plan,v,S,pe),g.push(...tn.warnings.map(Jt=>`${S}: ${Jt}`))}G(s);const x={schemaVersion:ze,...w.some(v=>Dr(v.template))?{requiresRecalculation:!0}:{},pages:p},b=f.runSync("validate",()=>{const v=Ue(x);if(!v.ok)throw new E("validate",`渲染计划校验失败:${v.errors.slice(0,3).map(M=>`${M.path}: ${M.message}`).join("; ")}`);return v});g.push(...b.warnings.map(v=>`${v.path}: ${v.message}`));const $=m.map(v=>({...v,pagination:{...v.pagination}})),T={maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents};try{_f(x,{parts:w,validationFormulas:$.map(v=>v.pagination?.formula),rebuild:(v,M)=>wl(v,$,d,T,M)})}catch{g.push("来源数据无法建立本地重算口径;当前预览仅支持计划内编辑,请使用可序列化模板数据启用规则重算")}const j=a??t.onWarning??(v=>console.warn("[mach-report]",v));for(const v of g)G(s),j(v);return G(s),x},{getParamDefs:o=>Mt(e,o)})}const Qr=Object.freeze({maxRows:1e5,maxPages:1e4,maxCells:2e6,maxChartComponents:5e4,maxOutputBytes:1e8,maxPreparedBytes:64e6,maxDurationMs:12e4});class L extends Error{constructor(t,r,n){super(r),this.code=t,this.path=n,this.name="ReportRuntimeError"}}function O(e){if(!e?.aborted)return;if(e.reason instanceof L)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 L("budget",`${t} 的执行统计无效`,`$.budget.${t}`);const n=e[t];if(n!==void 0&&r>n)throw new L("budget",`${t} 超出预算 ${n}(实际 ${r})`,`$.budget.${t}`)}function Mi(e){for(const[t,r]of Object.entries(e)){if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new L("budget",`${t} 应为正有限数字`,`$.budget.${t}`);if(t!=="maxDurationMs"&&r!==void 0&&!Number.isSafeInteger(r))throw new L("budget",`${t} 应为正安全整数`,`$.budget.${t}`);if(t==="maxDurationMs"&&r!==void 0&&r>2147483647)throw new L("budget","maxDurationMs 不能超过 2147483647",`$.budget.${t}`);if(t==="maxChartComponents"&&r!==void 0&&r>1e6)throw new L("budget","maxChartComponents 不能超过 1000000","$.budget.maxChartComponents")}}async function Ie(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 L("timeout",`报表执行超过 ${t}ms`)),t);let a;try{O(n.signal);const c=new Promise((f,d)=>{a=()=>{try{O(n.signal)}catch(l){d(l)}},n.signal.addEventListener("abort",a,{once:!0})}),u=await Promise.race([r(n.signal),c]);if(O(n.signal),t!==void 0&&Date.now()-i>t)throw new L("timeout",`报表执行超过 ${t}ms`);return u}finally{s!==void 0&&clearTimeout(s),a&&n.signal.removeEventListener("abort",a),e?.removeEventListener("abort",o)}}function $i(e,t){me.assertOutputActive(t.signal),me.observeOutput(()=>t.onDiagnostic?.(e)),me.assertOutputActive(t.signal)}class xl 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 Kt extends Error{constructor(t,r){super(r),this.code=t,this.name="ImageMediaError"}}const Qt={maxImageBytes:16*1024*1024,maxTotalImageBytes:32*1024*1024,maxImages:1e3,maxImagePixels:16e6,maxTotalImagePixels:64e6,maxImageDimension:16384};function ee(e){throw new Kt("invalid-image-data",e)}function Ce(e){throw new Kt("image-budget-exceeded",e)}function vl(e){const t={...Qt};for(const r of Object.keys(Qt)){const n=e[r]??Qt[r];if(!Number.isSafeInteger(n)||n<=0||n>2147483647)throw new RangeError(`${r} 图片预算须为1至2147483647的整数。`);t[r]=n}return t}function Ml(e){if(e.length<33||![137,80,78,71,13,10,26,10].every((r,n)=>e[n]===r))return ee("图片内容与 PNG/JPEG 类型不一致。");const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return t.getUint32(8)!==13||String.fromCharCode(...e.subarray(12,16))!=="IHDR"?ee("PNG must begin with an IHDR header."):[t.getUint32(16),t.getUint32(20)]}const $l=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function Sl(e){if(e[0]!==255||e[1]!==216)return ee("图片内容与 PNG/JPEG 类型不一致。");let t=2;for(;t+3<e.length;){if(e[t++]!==255)return ee("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 ee("JPEG segment exceeds its data boundary.");if($l.has(r))return n<8?ee("JPEG frame header is incomplete."):[e[t+5]*256+e[t+6],e[t+3]*256+e[t+4]];t+=n}return ee("JPEG has no supported dimension header.")}function El(e,t){if(e.length>Math.ceil(t.maxImageBytes/3)*4+64)return Ce("单张图片超过字节预算。");const r=/^data:image\/(png|jpe?g);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(e);if(!r||r[2].length%4)return ee("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 Ce("单张图片超过字节预算。");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"?Ml(a):Sl(a);return!c||!u?ee("Image dimensions must be positive."):c>t.maxImageDimension||u>t.maxImageDimension||c*u>t.maxImagePixels?Ce("Image exceeds its decoded dimension or pixel budget."):{dataUrl:`data:image/${i};base64,${n}`,bytes:a,extension:i,width:c,height:u}}function Al(e={}){const t=vl(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 Ce("唯一图片数量超过预算。");const c=El(i,t);return n+c.bytes.length>t.maxTotalImageBytes||o+c.width*c.height>t.maxTotalImagePixels?Ce("图片总字节或总像素超过预算。"):(n+=c.bytes.length,o+=c.width*c.height,r.set(s,c),c)}}class en extends Error{constructor(t,r){super(t.message),this.name="OutputAssetError",this.diagnostic=t,this.cause=r}}function At(e){if(e.aborted)throw e.reason??new DOMException("The operation was aborted.","AbortError")}function kl(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 Nl(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 Xe(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),$i(i,{...e.options,signal:e.signal}),e.options.assetFailure!=="placeholder")throw new en(i,o)}async function Pl(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 Xe(e,r,"asset-budget-exceeded","Output exceeded the asset count budget.");let o;try{if(e.active=r,o=await me.waitForOutput(n({...r,signal:e.signal}),e.signal),At(e.signal),o.length>e.budget.maxImageBytes*4+1024)return Xe(e,r,"asset-budget-exceeded","Output exceeded the image payload byte budget.");const i=Nl(o);if(i>e.budget.maxImageBytes||e.bytes+i>e.budget.maxTotalImageBytes)return Xe(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 en||i instanceof Kt&&i.code==="image-budget-exceeded")throw i;return Xe(e,r,"asset-render-failed",`Asset renderer failed for ${t.kind}; output was not silently omitted.`,i)}return o}function Fl(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{$i(n,{...e.options,signal:e.signal})}catch(o){t.abort(o);return}t.abort(new en(n))}async function Ol(e,t,r,n,o){if(!t?.children?.length)return t;const i=[];for(const[s,a]of t.children.entries())i.push(await Si(e,a,{...r,component:a,componentPath:[...n,s]},o));return i.some((s,a)=>s!==t.children[a])?{...t,children:i}:t}async function Si(e,t,r,n){if(At(e.signal),n.has(t))throw new TypeError("Cyclic grid children cannot be rendered.");let o=e.cache.get(t);o||(o=Pl(e,t,r),e.cache.set(t,o));const i=await o;At(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 Ol(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 Rl(e,t,r){const n=new Set,o=i=>{if(me.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 Kt)||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 Il(e){if(e.options.fidelity==="strict"&&e.diagnostics.length)throw new xl(e.diagnostics)}async function In(e,t={}){me.assertOutputActive(t.signal),_c(e);const r=kl(t),n=Al(t);if(Rl(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(()=>Fl(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 Si(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 At(s.signal),Il(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 kt(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 Cn(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 E("validate","严格输出拒绝已有资产渲染降级,请修复组件后重新准备报表。");const o=e.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;O(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=de(e),c=await a.run("encode",async()=>{let d;if(e.format==="pdf"){O(e.signal);const l=await o.renderPlanToPdf(n.plan,{...e.pdf,...s?{measurer:s}:{},fidelity:e.fidelity,signal:e.signal,onProgress:(m,h)=>a.progress("encode",m,h)});d=l.bytes,n.diagnostics.push(...kt(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");O(e.signal);const m=await l(n.plan,{...e.xlsx,fidelity:e.fidelity,signal:e.signal,onProgress:(h,p)=>a.progress("encode",h,p)});d=new Uint8Array(m.buffer),n.diagnostics.push(...kt(m.diagnostics)),n.diagnostics.push(...m.warnings.map(h=>({code:"xlsx-fidelity",message:h,severity:"warning"}))),n.diagnostics.push(...(m.notes??[]).map(h=>({code:"xlsx-snapshot",message:h,severity:"info"})))}return O(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 Ei(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 h=Object.getOwnPropertyNames(f).filter(y=>!(l&&y==="length"));if(l&&(h.length!==f.length||h.some((y,g)=>y!==String(g))))throw t.error("input","快照数组应为连续数组");i.add(f),s(2);const p=Object.create(null);let w=0;for(const y of h){const g=Object.getOwnPropertyDescriptor(f,y);if(g.get||g.set||!g.enumerable||["__proto__","constructor","prototype"].includes(y))throw t.error("input","快照不允许访问器或危险键");g.value===void 0&&!l||(s((w++?1:0)+(l?0:y.length+3)),p[y]=a(g.value===void 0?null:g.value,d+1))}return i.delete(f),l?h.map(y=>p[y]):p}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 Cl=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]),Z=(e,t)=>e>>>t|e<<32-t;function Ai(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=Z(i,7)^Z(i,18)^i>>>3,c=Z(s,17)^Z(s,19)^s>>>10;r[o]=r[o-16]+a+r[o-7]+c}}function ki(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=Z(s,6)^Z(s,11)^Z(s,25),l=s&a^~s&c,m=u+d+l+Cl[f]+t[f]>>>0,h=Z(r,2)^Z(r,13)^Z(r,22),p=r&n^r&o^n&o,w=h+p>>>0;u=c,c=a,a=s,s=i+m>>>0,i=o,o=n,n=r,r=m+w>>>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 Ni(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 Pi=()=>new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Fi=e=>Array.from(e,t=>t.toString(16).padStart(8,"0")).join("");function Tn(e){const t=Ni(e),r=Pi(),n=new Uint32Array(64);for(let o=0;o<t.length;o+=64)Ai(t,o,n),ki(r,n);return Fi(r)}async function Tl(e){const t=Ni(e),r=Pi(),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)),Ai(t,o,n),ki(r,n);return Fi(r)}function Oi(e){if(typeof e!="string"||!e.trim()||e.length>31||/[\\/*?:[\]]/.test(e)||/^'|'$/.test(e))throw new TypeError("工作表名称无效");return e}function jl(e){if(e!==void 0){if(!Array.isArray(e)||e.length>1e4)throw new RangeError("工作表名称列表最多 10000 项");return Array.from(e,Oi)}}function Dl(e){if(!Array.isArray(e)||e.length>16384)throw new TypeError("附加工作表行应为最多 16384 列的标量数组");return Array.from(e,t=>{if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&t.length<=32767&&t.split(`
6
- `).length<=254)return t;throw new TypeError("附加工作表仅接受 Excel 范围内的文本、有限数值、布尔或空值")})}function Ll(e){if(e===void 0)return;if(!Array.isArray(e)||e.length>100)throw new RangeError("附加工作表最多 100 张");let t=0,r=0,n=0;const o=new Set;return Array.from(e,i=>{if(!i)throw new TypeError("附加工作表声明无效");const a=Oi(i.name).toLowerCase();if(o.has(a))throw new TypeError(`附加工作表名称重复 ${i.name}`);if(o.add(a),!Array.isArray(i.rows)||i.rows.length>1e5)throw new RangeError("附加工作表最多 100000 行");if(n+=i.rows.length,n>1e5)throw new RangeError("附加工作表总行数超过 100000");const c=Array.from(i.rows,f=>{const d=Dl(f);if(t+=d.length,t>1e5)throw new RangeError("附加工作表总单元格超过 100000");for(const l of d)typeof l=="string"&&(r+=l.length);if(r>4e6)throw new RangeError("附加工作表文本超过 4000000 字符");return d}),u=i.columnWidths;if(u&&(!Array.isArray(u)||u.length>16384||Array.from(u).some(f=>!Number.isFinite(f)||f<=0||f>255)))throw new RangeError("附加工作表列宽应在 0 到 255 之间");return{name:i.name,rows:c,...u?{columnWidths:[...u]}:{}}})}function pr(e){return e&&{...e,sheetNames:jl(e.sheetNames),additionalSheets:Ll(e.additionalSheets)}}function Te(e){if(!e)return;const t=r=>{if(!(r instanceof Uint8Array)&&!(r instanceof ArrayBuffer))throw new E("validate","字体应为 Uint8Array 或 ArrayBuffer");if(r.byteLength>32e6)throw new L("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 Ri(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 L("budget","单份字体超过 32 MB","$.pdf");return[n,Tn(i)]});return Tn(new TextEncoder().encode(JSON.stringify(r)))}const yr=new WeakMap;function Bl(e,t,r){const n=Ii(e,t,r);let o=!0;return{prepared:n,forward(){if(!o)throw new Error("报表快照只能交接一次");return o=!1,yr.set(n,t),n}}}function Ii(e,t,r){if(O(r),!Number.isSafeInteger(t)||t<=0)throw new L("budget","快照预算应为正安全整数","$.budget.maxPreparedBytes");const n=yr.get(e);if(yr.delete(e),n!==void 0&&n<=t)return e;const o=Ei(e,{maxBytes:t,maxNodes:t,check:()=>O(r),error:(i,s)=>i==="budget"?new L("budget",s,"$.budget.maxPreparedBytes"):new E("validate",s)});return Ti(o),o}function Ci(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 Ti(e){if(!Ci(e.sources))throw new E("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 E("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)||!Xr(t)))throw new E("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 E("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 E("validate","准备结果字体度量标识无效")}function _l(e){if(e.layoutPolicy!==void 0&&!["verify","preserve"].includes(e.layoutPolicy))throw new E("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=Ri(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 E("validate",n);e.prepared.diagnostics.push({code:"prepared-font-metrics",severity:"warning",message:n})}function jn(e){return{...e,reportIds:[...e.reportIds],...e.params?{params:{...e.params}}:{}}}function ji(e,t){if(t.length===0)throw new E("config","缺少报表 ID");return t.map(r=>{if(!Object.prototype.hasOwnProperty.call(e,r))throw new E("config",`未注册报表 ${r}`);return e[r]})}function Wt(e){return e.grid?.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+Wt(s),0)??0):0),0),0)??0}function Kl(e,t,r){return e.pages.reduce((n,o)=>n+o.components.reduce((i,s)=>s.kind!=="list"?i+Wt(s):i+Lc(s,t,r),0),0)}function Wl(e,t=Object.keys(e)){return ji(e,t).map((r,n)=>{const o=t[n],i=Mt(e,[o]);return{id:o,params:JSON.parse(JSON.stringify(i)),paramsSchema:Au(i),datasetsSchema:Object.fromEntries(Object.entries(r.dataSchema??{}).map(([s,a])=>[s,ul(typeof r.template=="function"?void 0:r.template,s,a)])),capabilities:{save:!!r.provider?.save,export:!!r.provider?.export,templates:!!r.provider?.templates}}})}function Di(e,t){ji(e,t.reportIds);const r=ur(Mt(e,t.reportIds),t.params),n=t.reportIds.flatMap(i=>ur(Mt(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 wr(e,t){const r=Ue(e.plan);if(!r.ok)throw new E("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+Wt(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 Dn(e,t){const r=Di(e.reports,t);if(!r.ok)throw new Lt(r.issues)}function Li(e){const t={...Qr,...e.budget};Mi(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(([b,$])=>[b,{...$,pagination:{...e.pagination,...$.pagination,...i?{measurer:i}:{}},dataValidation:{...$.dataValidation,maxRows:Math.min(t.maxRows??1e5,$.dataValidation?.maxRows??1/0),maxCells:Math.min(t.maxCells??2e6,$.dataValidation?.maxCells??1/0)}}])),h=await bl(l,{maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents,onDatasets:(b,$,T)=>{try{a+=cl(T,$,{maxRows:t.maxRows,signal:o.signal})}catch(j){throw j instanceof so?new L("budget",j.message,"$.budget.maxRows"):j}B(t,"maxRows",a),c+=Kl(T,$,l[b]?.pagination),B(t,"maxCells",c)}})({...o,params:o.params??{},onWarning:b=>u.push({code:"layout",message:b,severity:"warning"}),onQueryResult:(b,$,T=0)=>{const j=Zr(T,b);Object.defineProperty(f,b,{value:{revision:$.revision,sourceToken:$.sourceToken},enumerable:!0,writable:!0}),d.push({reportId:b,reportIndex:T,reportScope:j,...$.revision===void 0?{}:{revision:$.revision},...$.sourceToken===void 0?{}:{sourceToken:$.sourceToken}}),u.push(...($.diagnostics??[]).map(v=>({...v,...v.target?{target:{...v.target,reportScope:j,...v.target.tableId?{tableId:JSON.stringify([T,b,v.target.tableId])}:{}}}:{}})))}}).catch(b=>{throw b instanceof E&&b.cause instanceof Se?new L("budget",b.cause.message,"$.budget.maxPages"):b instanceof E&&b.cause instanceof _e?new L("budget",b.cause.message,"$.budget.maxCells"):b instanceof E&&b.cause instanceof Ke?new L("budget",b.cause.message,"$.budget.maxChartComponents"):b});O(o.signal);const p=e.assets?await de(o).run("assets",()=>In(h,{...e.assets,signal:o.signal})):{plan:h,diagnostics:[]},w=p.plan;u.push(...kt(p.diagnostics));const y=w.pages.reduce((b,$)=>b+$.components.reduce((T,j)=>T+Wt(j),0),0);B(t,"maxPages",w.pages.length),B(t,"maxCells",y);const g=Ri(o.pdf),x=e.pagination?.measurer||Object.values(e.reports).some(b=>b.pagination?.measurer);return{plan:w,diagnostics:u,revisions:f,sources:d,layout:{textMetrics:g?"font-bytes":x?"provided":"heuristic",...g?{fontFingerprint:g}:{}},stats:{rows:a,pages:w.pages.length,cells:y,durationMs:Date.now()-s}}},n=async o=>{const i=Date.now();if(o.format!=="pdf"&&o.format!=="xlsx")throw new E("config","不支持的报表导出格式");const s=o.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;O(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 O(o.signal),Cn({...o,prepared:u},t,i)};return{describe:o=>Wl(e.reports,o),validate:o=>Di(e.reports,o),prepare:o=>Ie(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=jn(o),u={...c,...c.pdf?{pdf:Te(c.pdf)}:{},taskId:c.taskId??it()},f=a?p=>Me(a,p,i):void 0,d={...u,signal:i,onEvent:f};de(d).runSync("validate",()=>Dn(e,u));let l;const m=u.pdf?.customFontFaces??(u.pdf?.customFontBytes?{regular:u.pdf.customFontBytes}:void 0);if(!e.executor&&m){const p=await import("@agile-team/mach-report/pdf");O(i),l=p.createFontBytesMeasurer(m)}const h=e.executor?await e.executor.prepare(u,i,f):await r(d,l);return wr(h,t)}),exportPrepared:o=>Ie(o.signal,t.maxDurationMs,async i=>{const s=Date.now(),{signal:a,onEvent:c,...u}=o,f=wr(Ii(o.prepared,t.maxPreparedBytes??64e6,i),t),d={...u,xlsx:pr(u.xlsx),prepared:f,...u.pdf?{pdf:Te(u.pdf)}:{},taskId:u.taskId??it()};if(d.format!=="pdf"&&d.format!=="xlsx")throw new E("config","不支持的报表导出格式");const l=c?h=>Me(c,h,i):void 0;if(e.executor){if(!e.executor.exportPrepared)throw new E("config","执行器未实现 exportPrepared;请升级执行器或显式使用本地运行时");const h=await e.executor.exportPrepared(d,i,l);return B(t,"maxRows",h.stats.rows),B(t,"maxPages",h.stats.pages),B(t,"maxCells",h.stats.cells),B(t,"maxOutputBytes",h.bytes.byteLength),{...h,stats:{...h.stats,outputBytes:h.bytes.byteLength}}}const m={...d,signal:i,onEvent:l};if(de(m).runSync("validate",()=>_l(m)),e.assets){const h=await de(m).run("assets",()=>In(f.plan,{...e.assets,signal:i}));f.plan=h.plan,f.diagnostics.push(...kt(h.diagnostics))}return Cn(m,t,s)}),export:o=>Ie(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=jn(o),u={...c,xlsx:pr(c.xlsx),...c.pdf?{pdf:Te(c.pdf)}:{},taskId:c.taskId??it()},f=a?m=>Me(a,m,i):void 0,d={...u,signal:i,onEvent:f};if(de(d).runSync("validate",()=>Dn(e,u)),u.format!=="pdf"&&u.format!=="xlsx")throw new E("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 Jl={cells:2e4,pages:20,bytes:2e6};function je(e){return e.cells>=e.limits.cells||e.pages>=e.limits.pages||e.bytes>=e.limits.bytes||e.capped}function xe(e){return++e.visits>=1e5&&(e.capped=!0),!je(e)}function ie(e){return typeof e=="string"?e.length*2:0}function Ln(e,t){for(const r of e??[]){if(!xe(t))return;for(const n of r.segments){if(!xe(t))return;t.bytes+=ie(n.text)}}}function Bi(e,t,r){if(r>32){t.capped=!0;return}if(xe(t)){t.bytes+=ie(e.text)+ie(e.rawText)+ie(e.imageData),Ln(e.richParagraphs,t);for(const n of e.lines??[]){if(!xe(t))return;t.bytes+=ie(n)}for(const n of e.grid?.cells??[]){if(!xe(t))return;for(const o of n){if(!xe(t))return;if(o){t.cells++,t.bytes+=ie(o.text)+ie(o.rawText)+ie(o.value),Ln(o.richParagraphs,t);for(const i of o.children??[]){if(je(t))return;Bi(i,t,r+1)}}}}}}function zl(e){const t={...Jl,...e.thresholds};for(const r of Object.values(t))if(!Number.isSafeInteger(r)||r<=0)throw new RangeError("导出隔离阈值应为正安全整数");return t}function Vl(e,t){const r=zl(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(je(o))break;for(const c of a.components){if(je(o))break;Bi(c,o,0)}}let i=je(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 ce="mach-report-worker/1";class br 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 ue(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Hl(e){return ue(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 Ul(e){return Array.isArray(e)&&e.every(t=>ue(t)&&typeof t.code=="string"&&typeof t.message=="string"&&["info","warning","error"].includes(t.severity)&&Xr(t))}function Gl(e){return ue(e)&&Object.values(e).every(t=>ue(t)&&(t.revision===void 0||typeof t.revision=="string")&&(t.sourceToken===void 0||typeof t.sourceToken=="string"))}function Yl(e){return e===void 0?!0:ue(e)&&["heuristic","provided","font-bytes"].includes(e.textMetrics)&&(e.fontFingerprint===void 0||typeof e.fontFingerprint=="string"&&/^[a-f0-9]{64}$/.test(e.fontFingerprint))}function ql(e,t){if(!ue(e)||!Hl(e.stats)||!Ul(e.diagnostics)||!Gl(e.revisions)||!Yl(e.layout)||!Ci(e.sources))return!1;if(t==="prepare")return Ue(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 _i(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 Xl(e){const t=_i(e);if(!ue(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 Ki(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(_i)}:{},...Array.isArray(t.diagnostics)?{diagnostics:t.diagnostics.map(Xl)}:{}}}function Wi(e){if(!e||typeof e!="object")return!1;const t=e;return t.protocol===ce&&typeof t.id=="string"&&(t.operation==="prepare"||t.operation==="export"||t.operation==="exportPrepared")&&!!t.input&&typeof t.input=="object"}async function Ji(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:ce,id:t.id,result:n}}catch(n){return{protocol:ce,id:t.id,error:Ki(n)}}}function zi(e){const t=e.result;return!t||!("bytes"in t)||!(t.bytes.buffer instanceof ArrayBuffer)?[]:[t.bytes.buffer]}function Zl(e,t){if(!ue(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 xr extends Error{constructor(t){super("报表 Worker 无法启动"),this.cause=t,this.name="ReportWorkerStartError"}}let Ql=0;function Bn(e){const t=new Error("报表 Worker 任务已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e}),t}function ed(e,t){if(!e||typeof e!="object")return;const r=e;return r.protocol===ce&&r.id===t?r:void 0}function td(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(Bn(s.reason)):new Promise((c,u)=>{let f;try{f=e()}catch(g){u(new xr(g));return}const d=`mach-report-${Date.now()}-${++Ql}`;let l=!1,m=()=>{},h;const p=(g,x)=>{if(l)return;l=!0,h&&clearTimeout(h);let b;try{m()}catch($){b=$}s?.removeEventListener("abort",w),g??=b,Promise.resolve().then(()=>f.terminate()).then(()=>g===void 0?c(x):u(g),$=>u(g??$))},w=()=>p(Bn(s?.reason)),y=g=>{const x=ed(g,d);if(!(!x||l)){if("type"in x&&x.type==="event"){const b="event"in x?x.event:void 0;Zl(b,i)?Me(a,b,s):p(new Error("报表 Worker 返回无效阶段事件"));return}x.error&&typeof x.error.name=="string"&&typeof x.error.message=="string"?p(new br(x.error)):ql(x.result,o)&&(o==="prepare"||"format"in x.result&&"format"in i&&x.result.format===i.format)?p(void 0,x.result):p(new Error("报表 Worker 返回无效响应"))}};try{if(m=f.subscribe(y,g=>p(g??new Error("报表 Worker 执行失败"))),l){m();return}if(s?.addEventListener("abort",w,{once:!0}),h=setTimeout(()=>p(new br({name:"ReportRuntimeError",code:"timeout",message:`报表 Worker 执行超过 ${r}ms`})),r),s?.aborted)w();else{const{onEvent:g,signal:x,...b}=i,$=rd(b);f.postMessage({protocol:ce,id:d,operation:o,input:b,...t.budget?{budget:t.budget}:{}},$)}}catch(g){p(g)}});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 rd(e){return e.pdf?(e.pdf=Te(e.pdf),(e.pdf?.customFontFaces?Object.values(e.pdf.customFontFaces):[e.pdf?.customFontBytes]).filter(r=>r instanceof Uint8Array).map(r=>r.buffer)):[]}function nd(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("无效的导出回退策略");Mi({...e.budget,maxDurationMs:e.timeoutMs??e.budget?.maxDurationMs??12e4})}function _n(e,t){me.observeOutput(()=>e.onDecision?.({...t,estimate:{...t.estimate}}))}function Kn(e,t){return{...e,mode:"local",reason:t,hardCancellation:!1}}function od(e,t){const r={...Qr,...t.budget},n=Bl(e.prepared,r.maxPreparedBytes,e.signal),o=wr(n.prepared,r);n.prepared.stats=o.stats;const i={...e,prepared:n.prepared,pdf:Te(e.pdf),xlsx:pr(e.xlsx)};return{request:i,forward:()=>({...i,prepared:n.forward()})}}function id(e,t){nd(e);const r={...e,thresholds:{...e.thresholds},budget:{...Qr,...e.budget}},n=r.timeoutMs??r.budget.maxDurationMs??12e4,o=Li({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 y=n-(Date.now()-d);if(y<=0)throw new L("timeout",`报表执行超过 ${n}ms`);return y};let m=Vl(u,r);if(m.reason==="nonserializable-options"&&r.mode==="worker")throw new TypeError("Worker 模式不接受函数选项;请使用本地模式或可序列化配置");if(m.mode==="worker"&&!t){if(!a)throw new xr(new Error("未配置 workerFactory"));m=Kn(m,"worker-unavailable")}const h=od(u,r),p=h.request;if(_n(r,m),O(u.signal),m.mode==="worker")try{const y=t(l());if(!y.exportPrepared)throw new TypeError("隔离执行器缺少 exportPrepared");const{signal:g,onEvent:x,...b}=p,$=await y.exportPrepared(b,g,x);return O(g),B(r.budget,"maxOutputBytes",$.bytes.byteLength),{...$,execution:m}}catch(y){if(!(y instanceof xr)||!a)throw y;O(u.signal),m=Kn(m,"worker-start-failed"),_n(r,m)}const w=f?await Ie(u.signal,l(),y=>f({...p,signal:y})):await Ie(u.signal,l(),y=>o.exportPrepared({...h.forward(),signal:y}));return O(u.signal),B(r.budget,"maxOutputBytes",w.bytes.byteLength),{...w,execution:m}}return{async exportPrepared(u,f){if(s)throw new L("closed","导出执行器已释放");if(O(u.signal),i.size>=2)throw new L("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 sd(e,t){try{if(e.operation!=="exportPrepared")throw new TypeError("内置编码 Worker 仅接受 exportPrepared");return await Ji(Li({reports:{},budget:e.budget}),e,t)}catch(r){return{protocol:ce,id:e.id,error:Ki(r)}}}class k extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportJobError"}}function Nt(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 ad(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 cd(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 ne(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=ad(u);s.add(u);const m=Object.create(null);for(const h of l){if(i+=h.length,i>n)throw new k("input","任务文本超过预算");m[h]=a(cd(u,h),f+1)}return s.delete(u),d?Array.from({length:u.length},(h,p)=>m[String(p)]):m}const c=JSON.stringify(a(e,0));if(c.length>n)throw new k("input","任务序列化数据超过字符预算");return c}function er(e){return JSON.parse(JSON.stringify(e))}function Vi(e,t,r,n){if(Nt(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","任务类型无效");ne(e.request.payload,{maxNodes:19e3,maxCharacters:75e4}),ne(e)}function ud(e,t){if(e&&(e.createdAt!==t.createdAt||ne(e.request)!==ne(t.request)))throw new k("input","任务创建时间与请求不可变更,请使用新任务ID")}function fd(e,t){return e.status==="queued"||e.status==="running"&&(e.lease?.expiresAt??0)<=t}function ld(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 De(e){return new TextEncoder().encode(ne(e)).byteLength}function Hi(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:De(e.result);if(o>t.maxResultBytes)throw new k("capacity","任务结果超过独立预算,请保存文件引用");return Math.max(De(r)+t.controlReserveBytes,De(n))+o}function Ui(e){return e.status!=="queued"&&e.status!=="running"}function dd(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 md(e){const t=new TextEncoder().encode(ne(e)),r=globalThis.crypto?.subtle;if(!r)return Tl(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 hd(e,t){if(!Ui(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 md(e.request),expiresAt:t}}function gd(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 Ge(e){return e?.code}function Le(e,t){return ge.createHash("sha256").update(JSON.stringify([e,t])).digest("hex")+".json"}async function vr(e){try{return await A.promises.readFile(e,"utf8")}catch(t){if(Ge(t)==="ENOENT")return;throw t}}async function pd(e,t){const r=await vr(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(Ge(o)==="ESRCH"){await A.promises.unlink(e);return}throw o}throw new k("conflict","任务目录的写入进程仍在运行")}async function yd(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 Ge(o)==="EEXIST"?new k("conflict","任务目录恢复正在进行,请稍后重试"):o}try{return await n.writeFile(JSON.stringify({pid:process.pid})),await pd(e,!0),await A.promises.open(e,"wx",384)}finally{await n.close(),await A.promises.unlink(r)}}async function wd(e,t){const r=D.join(e,".writer-lock"),n=ge.randomUUID();let o;try{o=await A.promises.open(r,"wx",384)}catch(i){if(Ge(i)!=="EEXIST")throw i;o=await yd(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 bd(e,t,r,n){if("tombstone"in r){const o=r.tombstone;if(gd(o),Nt(o.scope,o.id),Le(o.scope,o.id)!==t)throw new k("input","持久任务摘要身份不匹配");const i=De(o);e.tombstoneBytes+=i,e.tombstones.set(t,{value:o,bytes:i})}else{if(Vi(r,r.scope,r.id,r.revision-1),Le(r.scope,r.id)!==t)throw new k("input","持久任务文件身份不匹配");const o=Hi(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 xd(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(D.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=D.join(e,i);if((await A.promises.stat(s)).size>4e6)throw new k("capacity","持久任务文件超过单文件预算");bd(o,i,JSON.parse(await A.promises.readFile(s,"utf8")),t)}return o}async function vd(e,t,r){const n=D.join(e,`.pending-${ge.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,D.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(Ge(o)!=="ENOENT")throw o})}}async function Md(e){const t=D.resolve(e.directory),r=ld(e);await A.promises.mkdir(t,{recursive:!0,mode:448});const n=await wd(t,e.recoverDeadOwner??!1);let o;try{o=await xd(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,h)=>{try{await vd(t,l,m)}catch(p){throw await vr(D.join(t,l))===m&&h(),p}h()};return{read:async(l,m)=>{a(),Nt(l,m),await s;const h=o.records.get(Le(l,m));return h?er(h.record):void 0},readTombstone:async(l,m)=>{a(),Nt(l,m),await s;const h=o.tombstones.get(Le(l,m));return h?er(h.value):void 0},candidates:async(l,m)=>(a(),await s,Array.from(o.records.values(),h=>h.record).filter(h=>fd(h,l)).sort((h,p)=>h.createdAt-p.createdAt).slice(0,m).map(er)),compareAndSwap:async(l,m,h,p)=>{const w=JSON.parse(ne(p));return Vi(w,l,m,h),c(async()=>{const y=Le(l,m),g=o.records.get(y);if((g?.record.revision??null)!==h||o.tombstones.has(y))return!1;ud(g?.record,w);const x=Hi(w,r),b=o.bytes-(g?.bytes??0)+x;if(b>r.maxBytes||!g&&o.records.size>=r.maxRecords)throw new k("capacity","持久任务容量已满,请清理终态任务或扩大显式预算");return await u(y,ne(w),()=>{o.records.set(y,{record:w,bytes:x}),o.bytes=b}),!0})},prune:async l=>{const m=dd(l);return c(async()=>{const h={archived:0,expired:0};for(const[p,w]of o.tombstones)w.value.expiresAt>m.now||h.expired>=m.limit||(await A.promises.unlink(D.join(t,p)),o.tombstones.delete(p),o.tombstoneBytes-=w.bytes,h.expired++);for(const[p,w]of o.records){if(!Ui(w.record)||w.record.updatedAt>m.terminalBefore||h.archived+h.expired>=m.limit)continue;const y=await hd(w.record,m.now+m.tombstoneRetentionMs),g=De(y);if(o.tombstones.size>=r.maxTombstones||o.tombstoneBytes+g>r.maxTombstoneBytes)break;await u(p,ne({tombstone:y}),()=>{o.tombstones.set(p,{value:y,bytes:g}),o.tombstoneBytes+=g,o.records.delete(p),o.bytes-=w.bytes}),h.archived++}if(h.expired){const p=await A.promises.open(t,"r");try{await p.sync()}finally{await p.close()}}return h})},close:async()=>{if(i)return;i=!0,await s,await n.handle.close();const l=await vr(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 $d(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 fe(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 X(e,t,r){return Ei(e,{maxBytes:t,maxNodes:t,check:()=>O(r),error:(n,o)=>new F(n==="budget"?"capacity":"input",o)})}function ve(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}function Wn(e){if(!e||e.schemaVersion!==ze||"pages"in e||e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean")throw new F("input","文档计划头应使用当前版本,且不得携带 pages")}function Ze(e,t){e.bytes=0;for(let r=0;r<8;r++){const n=t+ve(e);if(n===e.bytes)return;e.bytes=n}throw new F("capacity","文档容量统计无效")}function Sd(e,t,r=[]){const n=new Map;let o=0,i=Promise.resolve();for(const f of r){const d=fe(f.scope,f.id,f.version);if(Wn(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,X(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 h=n.get(fe(f,d,l));if(!h)throw new F("missing","文档不存在");if(h.version!==l||m!==void 0&&h.revision!==m)throw new F("conflict","文档已变化,请重新读取清单");return h},u=async(f,d,l)=>{const m=X(f,t.maxManifestBytes);return s(m,d),await e.write(m,l),n.set(fe(f.scope,f.id),m),o+=f.bytes-(d?.bytes??0),X(m,t.maxManifestBytes)};return{create:(f,d)=>{const l=X(f,t.maxManifestBytes,d),m=fe(l.scope,l.id,l.version);return Wn(l.plan),a(async()=>{if(O(d),n.has(m))throw new F("conflict","文档已存在,不可覆盖");const h={...l,revision:0,state:"building",pageCount:0,bytes:0};return Ze(h,0),u(h)})},append:(f,d,l,m,h,p)=>{const w=X(h,t.maxPageBytes,p),y=Ue({pages:[w]});if(!y.ok)throw new F("input",y.errors[0].message);return a(async()=>{O(p);const g=c(f,d,l,m);if(g.state!=="building")throw new F("conflict","已完成文档不可追加");if(g.pageCount>=t.maxPages)throw new F("capacity","文档页数超过预算");const x={...g,revision:m+1,pageCount:g.pageCount+1};return Ze(x,g.bytes-ve(g)+ve(w)),u(x,g,{index:g.pageCount,value:w})})},complete:(f,d,l,m,h,p)=>{const w=h===void 0?void 0:X(h,t.maxManifestBytes,p);return w&&Ti({...w}),a(async()=>{O(p);const y=c(f,d,l,m);if(y.state!=="building")throw new F("conflict","文档已完成");if(w&&w.stats.pages!==y.pageCount)throw new F("input","准备结果页数与文档页数不一致");const g={...y,revision:m+1,state:"complete",...w?{metadata:w}:{}};return Ze(g,y.bytes-ve(y)),u(g,y)})},fail:(f,d,l,m,h)=>{const p=X(h,4096);if(!p||!["cancelled","generation"].includes(p.code)||typeof p.message!="string"||!p.message.trim()||p.message.length>1024)throw new F("input","文档失败状态无效");return a(async()=>{const w=c(f,d,l,m);if(w.state!=="building")throw new F("conflict","终态文档不可变更");const y={...w,state:"failed",revision:m+1,failure:p};return Ze(y,w.bytes-ve(w)),u(y,w)})},read:async(f,d,l)=>{O(l);const m=fe(f,d);await i,O(l);const h=n.get(m);return h?X(h,t.maxManifestBytes):void 0},readPage:(f,d,l,m,h)=>a(async()=>{O(h);const p=c(f,d,l);if(!Number.isSafeInteger(m)||m<0)throw new F("input","页索引应为非负安全整数");if(m>=p.pageCount)return;const w=await e.readPage(f,d,m);if(O(h),!w)throw new F("missing","已提交的文档页缺失");return X(w,t.maxPageBytes,h)}),remove:(f,d,l,m)=>a(async()=>{O(m);const h=fe(f,d,l),p=n.get(h);return p?(c(f,d,l),await e.remove(p),n.delete(h),o-=p.bytes,!0):!1})}}const Mr=e=>e?.code,st=(e,t)=>ge.createHash("sha256").update(fe(e,t)).digest("hex");async function $r(e,t){const r=await A.promises.lstat(e);if(!r.isFile()||r.size>t)throw new F("capacity","文档文件类型或大小无效");return X(JSON.parse(await A.promises.readFile(e,"utf8")),t)}async function Jn(e,t){const r=`${e}.pending-${ge.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(Mr(n)!=="ENOENT")throw n})}}async function Ed(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=D.join(e,o);if(!(await A.promises.lstat(i)).isDirectory())throw new F("input","文档目录不允许符号链接");const a=await $r(D.join(i,"manifest.json"),t.maxManifestBytes);if(st(a.scope,a.id)!==o||!Number.isSafeInteger(a.pageCount)||a.pageCount<0||a.pageCount>t.maxPages)throw new F("input","文档清单身份或页数无效");let c=ve(a);for(let u=0;u<a.pageCount;u++){const f=await A.promises.lstat(D.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(D.join(i,u))}n.push(a)}return n}async function Ad(e){const t=$d(e),r=D.resolve(e.directory);await A.promises.mkdir(r,{recursive:!0,mode:448});const n=D.join(r,".document-writer-lock"),o=ge.randomUUID();let i;try{i=await A.promises.open(n,"wx",384)}catch(l){throw Mr(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 $r(n,1024)).token===o}catch(l){if(Mr(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 Ed(r,t);d=Sd({write:async(m,h)=>{await a();const p=D.join(r,st(m.scope,m.id));await A.promises.mkdir(p,{recursive:!0,mode:448}),h&&await Jn(D.join(p,`${h.index}.json`),h.value);try{await Jn(D.join(p,"manifest.json"),m)}catch(w){throw h?await A.promises.unlink(D.join(p,`${h.index}.json`)):m.revision===0&&await A.promises.rm(p,{recursive:!0}),w}},readPage:async(m,h,p)=>(await a(),$r(D.join(r,st(m,h),`${p}.json`),t.maxPageBytes)),remove:async m=>{await a(),await A.promises.rm(D.join(r,st(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 Gi(e){const t=e.filename??e.workerUrl;if(!t||e.filename&&e.workerUrl)throw new TypeError("请且仅请指定 filename 或 workerUrl");return td(()=>{const r=new Ne.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 kd(e){const t=Ne.parentPort;if(!t)throw new Error("serveNodeReportWorker 只能在 worker_threads 中调用");const r=n=>{Wi(n)&&Ji(e,n,o=>t.postMessage({protocol:ce,id:n.id,type:"event",event:o})).then(o=>t.postMessage(o,zi(o)))};return t.on("message",r),()=>t.off("message",r)}function Nd(e){return ge.createHash("sha256").update(e).digest("hex")}function Pd(e={}){const t={timeoutMs:e.timeoutMs??e.budget?.maxDurationMs,budget:{...e.budget}};return id(e,r=>Gi({filename:typeof __filename=="string"?__filename:new URL(typeof document>"u"?require("url").pathToFileURL(__filename).href:zt&&zt.tagName.toUpperCase()==="SCRIPT"&&zt.src||new URL("server-node.cjs",document.baseURI).href),workerOptions:{workerData:{machReportEncoding:"prepared-v1"}},...t,timeoutMs:r}))}if(Ne.parentPort&&Ne.workerData?.machReportEncoding==="prepared-v1"){const e=Ne.parentPort;e.on("message",t=>{Wi(t)&&sd(t,r=>e.postMessage({protocol:ce,id:t.id,type:"event",event:r})).then(r=>e.postMessage(r,zi(r)))})}exports.ReportWorkerError=br;exports.createNodeAutoReportExporter=Pd;exports.createNodeReportExecutor=Gi;exports.openFileReportDocumentStore=Ad;exports.openFileReportJobStore=Md;exports.reportArtifactSha256=Nd;exports.serveNodeReportWorker=kd;
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(Un.test(s)){i(),n.push({text:s,widthMm:r.measureMm(s,t),cjk:!0});continue}o+=s}return i(),n}function Ve(e,t,r,n=Er){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 f of cs(e,r,n)){if(f.br){c();continue}const u=i.length>0?a:0;if(s+u+f.widthMm<=t){i+=f.text,s+=u+f.widthMm;continue}if(f.space){c();continue}if(f.cjk){i.length>0&&c(),i=f.text,s=f.widthMm;continue}if(i.length>0&&c(),f.widthMm<=t){i=f.text,s=f.widthMm;continue}for(const d of f.text)n.measureMm(i+d,r)>t&&i.length>0&&c(),i+=d,s=n.measureMm(i,r)}return c(),o}const fs=4096,on=128*1024;function us(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<=on){for(;t.size>=fs||r+i.length>on;){const c=t.keys().next().value;r-=c.length,t.delete(c)}t.set(i,a),r+=i.length}return a}}}const at=1e3;function ge(e){if(!Number.isSafeInteger(e)||e<0||e>at*2)throw new Error("十进制精度超出预算");return 10n**BigInt(e)}function Ft(e){if(e.coefficient.toString().length>at*2||e.scale>at*2)throw new Error("十进制结果超出精度预算");return e}function V(e){if(typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("十进制参数必须是有限数字或十进制文本");const t=String(e);if(t.length>at)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 Ft(i<0?{coefficient:s*ge(-i),scale:0}:{coefficient:s,scale:i})}function Gn(e,t){const r=Math.max(e.scale,t.scale);return[e.coefficient*ge(r-e.scale),t.coefficient*ge(r-t.scale),r]}function ct(e,t){const[r,n]=Gn(e,t);return r<n?-1:r>n?1:0}function ft(e,t){const[r,n,o]=Gn(e,t);return Ft({coefficient:r+n,scale:o})}function Ar(e,t){return Ft({coefficient:e.coefficient*t.coefficient,scale:e.scale+t.scale})}function Yn(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 He(e){if(!Number.isInteger(e)||e<0||e>100)throw new Error("十进制小数位应为 0–100 的整数")}function tr(e,t,r=20){if(He(r),t.coefficient===0n)throw new Error("不能除以零");const n=t.scale-e.scale+r,o=e.coefficient*ge(Math.max(0,n)),i=t.coefficient*ge(Math.max(0,-n));return Ft({coefficient:Yn(o,i),scale:r})}function Ot(e,t){let r=e.coefficient,n=e.scale;t!==void 0&&(He(t),r=t>=n?r*ge(t-n):Yn(r,ge(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 sn(e,t,r=!1,n=!1){let o=V(e);n&&(o=Ar(o,{coefficient:100n,scale:0}));const[i,s]=Ot(o,t).split(".");return`${r?i.replace(/\B(?=(\d{3})+(?!\d))/g,","):i}${s===void 0?"":`.${s}`}${n?"%":""}`}const qn=new Set(["__proto__","prototype","constructor"]);function Xn(e){if(!e||typeof e!="object"||Array.isArray(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new Error("条件应为普通声明式对象");for(const[t,r]of Object.entries(Object.getOwnPropertyDescriptors(e)))if(qn.has(t)||!Object.prototype.hasOwnProperty.call(r,"value"))throw new Error("条件不允许访问器或不安全属性")}function an(e){if(typeof e!="string"||!e.trim()||e.length>512||qn.has(e))throw new Error("条件字段应为安全的非空字段名")}function Vt(e){if(e!==null&&typeof e!="boolean"&&typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("条件常量应为有限 JSON 标量");if(typeof e=="string"&&e.length>16384)throw new Error("条件文本超出预算")}function rr(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))throw new Error("日期条件使用 YYYY-MM-DD 日历日");const[t,r,n]=e.split("-").map(Number),o=new Date(0);if(o.setUTCFullYear(t,r-1,n),o.setUTCHours(0,0,0,0),o.getUTCFullYear()!==t||o.getUTCMonth()!==r-1||o.getUTCDate()!==n)throw new Error("无效日历日");return e}function cn(e){return["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function fn(e){return e==null||e===""}function ls(e){const t=e.values?.[0]??(e.right&&"value"in e.right?e.right.value:e.value);return e.valueType??e.numeric??(typeof t=="number"?"decimal":typeof t=="boolean"?"boolean":"text")}function Qe(e,t,r){if(fn(e)||fn(t))return;const n=ls(r);try{if(n==="decimal")return ct(V(e),V(t));if(n==="number")return!["number","string"].includes(typeof e)||!["number","string"].includes(typeof t)?void 0:ct(V(e),V(t));if(n==="date"&&(e=rr(e),t=rr(t)),n==="boolean"&&(typeof e!="boolean"||typeof t!="boolean")||n==="text"&&(!cn(e)||!cn(t)))return;const o=String(e),i=String(t);return o<i?-1:o>i?1:0}catch{return}}function ds(e){if(an(e.field),![">",">=","<","<=","==","!=","between","contains","isNull","isNotNull"].includes(e.op))throw new Error("未知条件运算符");if(e.numeric!==void 0&&!["number","decimal"].includes(e.numeric))throw new Error("未知条件数值模式");if(e.valueType!==void 0&&!["number","decimal","text","date","boolean"].includes(e.valueType))throw new Error("未知条件值类型");if(!(e.op==="isNull"||e.op==="isNotNull"))if(e.op==="between"){if(!Array.isArray(e.values)||e.values.length!==2||Object.keys(e.values).length!==2)throw new Error("范围条件需要两个明确边界");e.values.forEach(Vt);const t=Qe(e.values[0],e.values[1],e);if(t===void 0||t>0)throw new Error("范围边界无效或顺序颠倒")}else if(e.right!==void 0){if(Xn(e.right),Object.keys(e.right).length!==1)throw new Error("条件 right 只能指定一个 field 或 value");if("field"in e.right?an(e.right.field):Vt(e.right.value),e.value!==void 0)throw new Error("条件不能同时指定 value 和 right")}else Vt(e.value)}function Ht(e,t){if(t===void 0)return!1;switch(e){case">":return t>0;case">=":return t>=0;case"<":return t<0;case"<=":return t<=0;case"==":return t===0;case"!=":return t!==0;default:return!1}}function ms(e){ds(e),e={...e,right:e.right?{...e.right}:void 0,values:e.values?[e.values[0],e.values[1]]:void 0};const t=(r,n)=>Object.prototype.hasOwnProperty.call(r,n)?r[n]:void 0;return r=>{const n=t(r,e.field);if(e.op==="isNull")return n==null;if(e.op==="isNotNull")return n!=null;if(e.op==="between")return Ht(">=",Qe(n,e.values[0],e))&&Ht("<=",Qe(n,e.values[1],e));const o=e.right?"field"in e.right?t(r,e.right.field):e.right.value:e.value;return e.op==="contains"?typeof n=="string"&&typeof o=="string"&&n.includes(o):Ht(e.op,Qe(n,o,e))}}function q(e,t={nodes:0},r=0){if(++t.nodes>256||r>16)throw new Error("条件超出深度或节点预算");if(Xn(e),["all","any","not","field"].filter(o=>Object.prototype.hasOwnProperty.call(e,o)).length!==1)throw new Error("条件只能指定一种组合或比较");if("not"in e){const o=q(e.not,t,r+1);return i=>!o(i)}if("all"in e||"any"in e){const o="all"in e?e.all:e.any;if(!Array.isArray(o)||o.length<1||o.length>256||Object.keys(o).length!==o.length)throw new Error("组合条件需要有界、无空位的非空数组");const i=o.map(s=>q(s,t,r+1));return"all"in e?s=>i.every(a=>a(s)):s=>i.some(a=>a(s))}return ms(e)}function hs(e){q(e);const t=new Set;function r(n){"all"in n?n.all.forEach(r):"any"in n?n.any.forEach(r):"not"in n?r(n.not):(t.add(n.field),n.right&&"field"in n.right&&t.add(n.right.field))}return r(e),[...t]}function Zn(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 gs(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 nr(e,t){return e.toLocaleString("en-US",{minimumFractionDigits:t,maximumFractionDigits:t})}function ps(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 ys(e,t,r){return r!=null?t?nr(e,r):e.toFixed(r):t?nr(e):String(e)}function un(e){const t=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(t)?t:null}function kr(e,t){if(e==null||e===""||!t)return String(e??"");switch(t.kind){case"number":{if(typeof e=="string")try{return sn(e,t.digits,t.thousands===!0)}catch{return e}const r=un(e);return r==null?String(e):ys(r,t.thousands===!0,t.digits)}case"percent":{if(typeof e=="string")try{return sn(e,t.digits??2,!0,!0)}catch{return e}const r=un(e);return r==null?String(e):`${nr(r*100,t.digits??2)}%`}case"date":{const r=t.pattern??"YYYY-MM-DD",n=e instanceof Date?e:gs(String(e));return n?ps(n,r):String(e)}default:return String(e)}}const ws=[{name:"add",minArgs:2,maxArgs:256,input:"numeric",output:"numeric",example:"add(quantity, adjustment)"},{name:"subtract",minArgs:2,maxArgs:2,input:"numeric",output:"numeric",example:"subtract(input, output)"},{name:"multiply",minArgs:2,maxArgs:256,input:"numeric",output:"numeric",example:"multiply(quantity, price)"},{name:"divide",minArgs:2,maxArgs:2,input:"numeric",output:"numeric",example:"divide(amount, quantity)"},{name:"coalesce",minArgs:2,maxArgs:256,input:"scalar",output:"scalar",example:"coalesce(actual, planned)"},{name:"if",minArgs:2,maxArgs:2,input:"condition + branches",output:"scalar",example:"if(quantity > 0, divide(amount, quantity), null)"},{name:"round",minArgs:1,maxArgs:2,input:"numeric, digits?",output:"numeric",example:"round(amount, 2)"},{name:"abs",minArgs:1,maxArgs:1,input:"numeric",output:"numeric",example:"abs(difference)"},{name:"concat",minArgs:2,maxArgs:256,input:"text",output:"text",example:"concat(plant, '-' , heat)"},{name:"trim",minArgs:1,maxArgs:1,input:"text",output:"text",example:"trim(heat)"},{name:"upper",minArgs:1,maxArgs:1,input:"text",output:"text",example:"upper(grade)"},{name:"lower",minArgs:1,maxArgs:1,input:"text",output:"text",example:"lower(code)"},{name:"dateYear",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateYear(reportDate)"},{name:"dateMonth",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateMonth(reportDate)"},{name:"dateDay",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateDay(reportDate)"}],bs=Object.freeze(ws.map(e=>Object.freeze(e)));function xs(e,t,r,n,o){if(t.some(a=>a==null)){if(o==="error")throw new Error("函数参数包含空值");return null}if(e==="round"||e==="abs")return vs(e,t,r,n);if(e.startsWith("date")){const a=rr(t[0]);return Number(a.slice(e==="dateYear"?0:e==="dateMonth"?5:8,e==="dateYear"?4:e==="dateMonth"?7:10))}if(t.some(a=>typeof a!="string"))throw new Error("文本函数只接受文本,不隐式转换数字或空值");if(t.reduce((a,c)=>a+c.length,0)>1e6)throw new Error("计算文本超出长度预算");const i=t[0],s=e==="concat"?t.join(""):e==="trim"?i.trim():e==="upper"?i.toUpperCase():i.toLowerCase();if(s.length>1e6)throw new Error("计算文本超出长度预算");return s}function vs(e,t,r,n){const o=t[0];if(r!=="decimal"&&(typeof o!="number"||!Number.isFinite(o)))throw new Error("普通数值函数需要有限数字");const i=V(o);e==="abs"&&(i.coefficient=i.coefficient<0n?-i.coefficient:i.coefficient);const s=e==="round"?t.length===2?t[1]:n??0:n;if(s!==void 0){if(typeof s!="number")throw new Error("小数位必须为数字");He(s)}const a=Ot(i,s),c=Number(a);if(r!=="decimal"&&!Number.isFinite(c))throw new Error("计算结果不是有限数字");return r==="decimal"?a:c}const Ms=["sum","count","avg","min","max","weightedAvg"];function ln(e){if(typeof e!="number"||!Number.isFinite(e))throw new Error("聚合度量必须是有限数字,不能隐式转换;小数文本请显式选择 decimal");return e}function ut(e,t){return t&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function $s(e){let t=0,r=0,n=0,o=0,i=1/0,s=-1/0;const a=c=>{const f=c-n,u=r+f;n=u-r-f,r=u};return{add(c){const f=ut(c,e.field);if(e.op==="count"){(!e.field||f!=null)&&t++;return}if(f==null)return;const u=ln(f),d=e.op==="weightedAvg"?ut(c,e.weightField):1;if(d==null)return;const l=ln(d);if(e.op==="weightedAvg"&&l<0)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&a(u*l),o+=l,i=Math.min(i,u),s=Math.max(s,u),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 Ss(e){let t=0,r=V("0"),n=V("0"),o,i;return{add(s){const a=ut(s,e.field);if(e.op==="count"){(!e.field||a!=null)&&t++;return}if(a==null)return;const c=e.op==="weightedAvg"?ut(s,e.weightField):"1";if(c==null)return;const f=V(a),u=V(c);if(e.op==="weightedAvg"&&u.coefficient<0n)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&(r=ft(r,Ar(f,u))),e.op==="weightedAvg"&&(n=ft(n,u)),(!o||ct(f,o)<0)&&(o=f),(!i||ct(f,i)>0)&&(i=f),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=tr(r,V(t),e.digits)),e.op==="weightedAvg"&&(s=tr(r,n,e.digits)),Ot(s,e.digits)}}}function se(e){if(e.digits!==void 0&&He(e.digits),e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal")throw new Error("未知聚合数值模式");if(!Ms.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"?Ss(e):$s(e)}function Be(e,t){const r=se(t);for(const n of e)r.add(n);return r.value()}const Es=new Set(["__proto__","prototype","constructor"]);function K(e){if(typeof e!="string"||!e.trim()||Es.has(e))throw new Error("计算字段应为安全的非空字段名")}function Nr(e){return e===null||["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function As(e){if(e.some(t=>typeof t!="number"||!Number.isFinite(t)))throw new Error("算术参数必须是有限数字;空值和小数文本不会隐式转换");return e}function ks(e,t){const r=As(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 Ns(e,t,r){const n=t.map(V);let o;return e==="add"?o=n.reduce(ft):e==="multiply"?o=n.reduce(Ar):e==="subtract"?o=ft(n[0],{...n[1],coefficient:-n[1].coefficient}):o=tr(n[0],n[1],r),Ot(o,r)}function Ps(e,t,r){return r.nulls!=="error"&&t.some(n=>n==null)||e==="divide"&&r.divisionByZero==="null"&&(r.numeric==="decimal"?V(t[1]).coefficient===0n:t[1]===0)?null:r.numeric==="decimal"?Ns(e,t,r.digits):ks(e,t)}function Fs(e,t){e.field!==void 0&&K(e.field),e.weightField!==void 0&&K(e.weightField);const r={op:e.aggregate,field:e.field,weightField:e.weightField,numeric:t.numeric,digits:t.digits};Be([],r);const n=new WeakMap;return o=>{let i=n.get(o.rows);if(!i){try{i={value:Be(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 Os(e,t){for(const r of e){const n=r(t);if(n!=null)return n}return null}function Pr(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 Fs(e,t);if("field"in e){K(e.field);const o=e.field;return({row:i})=>Object.prototype.hasOwnProperty.call(i,o)?i[o]:void 0}if("value"in e){if(!Nr(e.value))throw new Error("常量应为有限 JSON 标量");return()=>e.value}return Rs(e,t,r,n)}function Rs(e,t,r,n){const o=bs.find(a=>a.name===e.op);if(!o||!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<o.minArgs||e.args.length>o.maxArgs)throw new Error("运算参数数量不正确");const i=e.op==="if"?q(e.condition,r,n+1):void 0;if(e.op!=="if"&&e.condition!==void 0)throw new Error("仅 IF 运算接受 condition");const s=e.args.map(a=>Pr(a,t,r,n+1));return i?a=>s[i(a.row)?0:1](a):["add","subtract","multiply","divide","coalesce"].includes(e.op)?e.op==="coalesce"?a=>Os(s,a):a=>Ps(e.op,s.map(c=>c(a)),t):a=>xs(e.op,s.map(c=>c(a)),t.numeric,t.digits,t.nulls)}function Is(e){Pr(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),n.condition&&hs(n.condition).forEach(o=>t.add(o)))};return r(e),[...t]}const Cs=16,or=1024*1024,dn=5e5,lt=new WeakMap,de=Symbol("uncacheable-computation-definition");function et(e,t,r=0){if(++t.nodes>1e4||r>32)throw de;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>or)throw de;return["string",e]}if(typeof e!="object")throw de;if(Array.isArray(e)){if(Object.getPrototypeOf(e)!==Array.prototype||Object.keys(e).length!==e.length)throw de;return["array",Array.from({length:e.length},(n,o)=>et(mn(e,String(o)),t,r+1))]}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw de;return["object",Object.keys(e).map(n=>[et(n,t,r+1),et(mn(e,n),t,r+1)])]}function mn(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw de;return r.value}function Ts(e){try{return JSON.stringify(et(e,{nodes:0,units:0}))}catch(t){if(t!==de)throw t;return}}function js(e){lt.set(e,{programs:new Map,units:0,slots:0})}function Ds(e,t){const r=lt.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 f=i.rows.get(e[c]);f&&s.set(a,f)}),n.programs.set(o,{...i,rows:s})}lt.set(t,n)}function Ls(e,t,r){const n=lt.get(e);if(!n||t.some(f=>typeof f.expression=="string"))return;const o=Ts(t);if(o===void 0||o.length>or)return;const i=n.programs.get(o);if(i)return i;const s=r(),a=e.length*s.reduce((f,u)=>f+u.dependencies.length+1,0),c={fields:s,rows:new WeakMap,slots:a,cacheRows:a<=dn};if(!c.cacheRows)return c;for(;n.programs.size>=Cs||n.units+o.length>or||n.slots+a>dn;){const f=n.programs.keys().next().value;n.slots-=n.programs.get(f).slots,n.units-=f.length,n.programs.delete(f)}return n.programs.set(o,c),n.units+=o.length,n.slots+=a,c}function Bs(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 _s(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 Ks(e){if(K(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&&He(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 字段");Ws(e)}function Ws(e){if(e.groupBy!==void 0){if(!Array.isArray(e.groupBy)||e.groupBy.length>16)throw new Error("计算分组最多 16 级");e.groupBy.forEach(K)}if(e.dependsOn!==void 0){if(!Array.isArray(e.dependsOn)||e.dependsOn.length>2048)throw new Error("计算依赖超出预算");e.dependsOn.forEach(K)}}function Fr(e){return[...new Set([...typeof e.expression=="string"?e.dependsOn??[]:Is(e.expression),...e.groupBy??[]])]}function Qn(e){if(!Array.isArray(e)||e.length>2048)throw new Error("计算字段应为数组且最多2048项");const t=new Map;for(const s of e){if(Ks(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 Fr(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 zs(e){try{const t=Qn(e);return{valid:!0,errors:[],order:t.map(r=>r.field),fields:e.map(r=>({field:r.field,dependencies:Fr(r),scope:r.scope??"row"}))}}catch(t){return{valid:!1,errors:[t instanceof Error?t.message:String(t)],fields:[],order:[]}}}function hn(e){return Qn(e.fields).map(t=>{const r=Fr(t);if(typeof t.expression!="string")return{definition:t,dependencies:r,read:Pr(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 Js(e,t){return JSON.stringify(t.map(r=>{const n=Object.prototype.hasOwnProperty.call(e,r)?e[r]:null;if(n!=null&&!Nr(n))throw new Error("分组字段应为有限 JSON 标量");return[typeof n,n??null]}))}function Vs(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=Js(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 Hs(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 gn(e){if(e?.aborted){const t=new Error("数据计算已取消");throw t.name="AbortError",t}}function Us(e,t,r,n,o,i){try{const s=e.read({row:t,rowIndex:r,rows:n});if(s!==void 0&&!Nr(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 Gs(e,t,r,n,o,i,s,a){const c=Bs(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 f=a.length;Us(r,n,o,i,s,a),_s(e,t,r,n,a.length>f?a[a.length-1]:void 0)}function Rt(e,t){Hs(e,t),gn(t.signal);const r=Ls(e,t.fields,()=>hn(t)),n={program:r,writes:new WeakMap},o=r?.fields??hn(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=Vs(s,a.definition);s.forEach((f,u)=>{gn(t.signal),Gs(n,e[u],a,f,u,c(f),t,i)})}return{rows:s,issues:i}}function Pe(e,t,r){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype||e.length>t)throw new TypeError(`${r}应为有界普通数组`);if(Reflect.ownKeys(e).length!==e.length+1)throw new TypeError(`${r}不支持自定义数组方法或迭代器`);const n=[];for(let o=0;o<e.length;o++){const i=Object.getOwnPropertyDescriptor(e,String(o));if(!i||!Object.prototype.hasOwnProperty.call(i,"value"))throw new TypeError(`${r}不支持空洞或访问器`);n.push(i.value)}return n}const $e=["#2563eb","#0d9488","#d97706","#7c3aed","#dc2626","#0284c7"];function Ys(e){if(!["bar","line","stackedBar","percentBar"].includes(e.type))throw new Error("未知图表类型");if(!Array.isArray(e.categories)||!Array.isArray(e.series)||!e.categories.length||e.categories.length>200||!e.series.length||e.series.length>12)throw new Error("图表支持 1–200 个分类、1–12 个系列;大数据应先聚合");const t=Pe(e.categories,200,"图表分类"),r=Pe(e.series,12,"图表系列").map(n=>({...n,values:Pe(n?.values,200,"图表数值")}));for(const n of t)if(typeof n!="string")throw new Error("图表分类应为字符串");qs(e);for(const n of r)Xs(n,t.length);return{...e,categories:t,series:r}}function qs(e){for(const t of["leftMm","topMm","widthMm","heightMm"])if(!Number.isFinite(e[t])||e[t]<0)throw new Error(`${t} 应为有限非负数`);if(e.widthMm<45||e.heightMm<35)throw new Error("图表至少需要 45×35mm");if(!Number.isFinite(e.leftMm+e.widthMm)||!Number.isFinite(e.topMm+e.heightMm))throw new Error("图表几何范围溢出")}function Xs(e,t){if(!e||typeof e.name!="string"||!Array.isArray(e.values)||e.values.length!==t)throw new Error("图表系列应提供名称及逐分类的有限数字或 null");for(const r of e.values)if(r!==null&&!Number.isFinite(r))throw new Error("图表系列应提供名称及逐分类的有限数字或 null");if(e.color!==void 0&&!/^#[\da-f]{6}$/i.test(e.color))throw new Error("图表颜色应为 #RRGGBB")}function ir(e,t,r,n,o,i=.8){return{kind:"line",leftMm:Math.min(e,r),topMm:Math.min(t,n),widthMm:Math.abs(r-e),heightMm:Math.abs(n-t),lineDirection:n<t?"up":"down",style:{lineColor:o,lineWidthPt:i}}}function be(e,t,r,n,o="center"){return{kind:"text",text:e,leftMm:t,topMm:r,widthMm:n,heightMm:5,style:{fontSize:8,color:"#475569",align:o,verticalAlign:"middle"}}}function dt(e){return Number(e.toPrecision(5)).toString()}function Zs(e){let t=0,r=0;const n=eo(e)?Qs(e):void 0;if(n)t=n.min,r=n.max;else for(const d of e.series)for(const l of d.values)l!==null&&(t=Math.min(t,l),r=Math.max(r,l));t===r&&(r=t+1);const o=e.leftMm+13,i=e.topMm+8,s=e.widthMm-17,a=e.heightMm-23,c=Math.max(Math.abs(t),Math.abs(r),1),f=t/c,u=r/c-f;return{left:o,top:i,width:s,height:a,min:t,max:r,y:d=>i+a*(1-(d/c-f)/u)}}function eo(e){return e.type==="stackedBar"||e.type==="percentBar"}function Qs(e){let t=0,r=e.type==="percentBar"?100:0;for(let n=0;n<e.categories.length;n++){let o=0,i=0;for(const s of e.series){const a=s.values[n]??0;a<0?i+=a:o+=a}if(!Number.isFinite(o)||!Number.isFinite(i))throw new Error("图表堆叠合计溢出,请先明确缩放单位");t=Math.min(t,i),r=Math.max(r,o)}return{min:t,max:r}}function ea(e){if(e.type!=="percentBar")return e;const t=e.categories.map((r,n)=>{let o=0;for(const i of e.series){const s=i.values[n];if(s!==null&&s<0)throw new Error("占比图需要非负度量,负数口径应由业务明确处理");o=Math.max(o,s??0)}return{scale:o,total:o?e.series.reduce((i,s)=>i+(s.values[n]??0)/o,0):0}});return{...e,series:e.series.map(r=>({...r,values:r.values.map((n,o)=>{if(n===null)return null;const{scale:i,total:s}=t[o];return i&&s?n/i/s*100:0})}))}}function ta(e,t){const r=[],n=t.width/e.categories.length;return e.categories.forEach((o,i)=>{let s=0,a=0;e.series.forEach((c,f)=>{const u=c.values[i];if(u==null)return;const d=u<0?a:s,l=d+u;u<0?a=l:s=l;const m=Math.min(t.y(d),t.y(l)),h=Math.abs(t.y(l)-t.y(d)),g=c.color??$e[f%$e.length],y=t.left+n*(i+.15),w=n*.7;r.push({kind:"rect",leftMm:y,topMm:m,widthMm:w,heightMm:h,style:{backgroundColor:g,borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}}),e.showValues&&h>=5&&r.push({...be(e.type==="percentBar"?`${dt(u)}%`:dt(u),y,m+h/2-2.5,w),style:{fontSize:7,color:"#ffffff",align:"center"}})})}),r}function ra(e,t){const r=[];e.title&&r.push({...be(e.title,e.leftMm,e.topMm,e.widthMm),style:{fontSize:10,bold:!0,align:"left"}});for(let i=0;i<=4;i++){const s=i/4,a=t.min*(1-s)+t.max*s,c=t.y(a);r.push(ir(t.left,c,t.left+t.width,c,"#e2e8f0",.4),be(`${dt(a)}${e.type==="percentBar"?"%":""}`,e.leftMm,c-2.5,11,"right"))}r.push(ir(t.left,t.top,t.left,t.top+t.height,"#94a3b8"));const n=Math.max(1,Math.ceil(e.categories.length/Math.max(1,Math.floor(t.width/14))));e.categories.forEach((i,s)=>{s%n===0&&r.push(be(i,t.left+(s+.5)*t.width/e.categories.length-7,t.top+t.height+1,14))});const o=t.width/e.series.length;return e.series.forEach((i,s)=>{r.push({...be(i.name,t.left+s*o,e.topMm+e.heightMm-5,o),style:{fontSize:8,color:i.color??$e[s%$e.length],align:"center"}})}),r}function na(e,t,r,n){const o=[],i=r.color??$e[n%$e.length],s=t.width/e.categories.length,a=s*.75/e.series.length;let c;return r.values.forEach((f,u)=>{if(f===null){c=void 0;return}const d=t.left+(u+.5)*s,l=t.y(f);e.type==="bar"?o.push({kind:"rect",leftMm:t.left+u*s+s*.125+n*a,topMm:Math.min(l,t.y(0)),widthMm:a,heightMm:Math.abs(t.y(0)-l),style:{backgroundColor:i,borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}}):(c&&o.push(ir(c.x,c.y,d,l,i,1.2)),o.push({kind:"ellipse",leftMm:d-.7,topMm:l-.7,widthMm:1.4,heightMm:1.4,style:{backgroundColor:i,borderColor:i}}),c={x:d,y:l}),e.showValues&&o.push({...be(dt(f),d-s/2,Math.max(t.top,l-5),s),style:{fontSize:7,color:i,align:"center"}})}),o}function oa(e,t){let r=0,n=!1;for(const o of t.values){if(o===null){n=!1;continue}r+=1+ +!!e.showValues,e.type==="line"&&n&&r++,n=!0}return r}function ia(e){const t=e.categories.length,r=Math.max(1,Math.ceil(t/Math.max(1,Math.floor((e.widthMm-17)/14)))),n=11+ +!!e.title+Math.ceil(t/r)+e.series.length;return e.series.reduce((o,i)=>o+oa(e,i),n)}function sa(e){e=ea(Ys(e));const t=Zs(e);return[...ra(e,t),...eo(e)?ta(e,t):e.series.flatMap((r,n)=>na(e,t,r,n))]}function mt(e,t,r){if(e===void 0)return t;if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>r)throw new RangeError("图表预算超出允许范围");return Number(e)}function to(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("图表绑定应为对象");if(K(e.dataset),K(e.categoryField),!["bar","line","stackedBar","percentBar"].includes(e.type))throw new TypeError("图表类型无效");if(e.sort!==void 0&&!["asc","desc"].includes(e.sort))throw new TypeError("图表排序无效");if(e.title!==void 0&&(typeof e.title!="string"||e.title.length>512))throw new TypeError("图表标题过长");if(e.showValues!==void 0&&typeof e.showValues!="boolean")throw new TypeError("图表数值标签应为布尔值");if(!Array.isArray(e.measures)||!e.measures.length||e.measures.length>12)throw new RangeError("图表支持 1–12 个度量");for(const t of Pe(e.measures,12,"图表度量"))aa(t);mt(e.maxRows,1e5,1e5),mt(e.maxCategories,200,200)}function aa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("图表度量应为对象");if(e.field!==void 0&&K(e.field),e.weightField!==void 0&&K(e.weightField),e.label!==void 0&&(typeof e.label!="string"||e.label.length>256))throw new TypeError("图表系列名称过长");if(e.color!==void 0&&!/^#[\da-f]{6}$/i.test(e.color))throw new TypeError("图表颜色应为 #RRGGBB");se(e)}function ca(e){if(e==null)return{key:"null",label:"—"};if(typeof e!="string"&&typeof e!="boolean"&&!(typeof e=="number"&&Number.isFinite(e)))throw new TypeError("图表分类应为文本、布尔或有限数字");const t=String(e);if(t.length>512)throw new RangeError("图表分类名称过长");return{key:JSON.stringify([typeof e,e]),label:t}}function fa(e){if(e===null)return null;const t=Number(e);if(!Number.isFinite(t))throw new RangeError("聚合结果超出图表有限数值范围");return t}function ua(e,t,r){if(r?.aborted){const a=new Error("图表数据处理已取消");throw a.name="AbortError",a}to(t);const n=Pe(t.measures,12,"图表度量");if(!Array.isArray(e)||e.length>mt(t.maxRows,1e5,1e5))throw new RangeError("图表数据超出行数预算");const o=new Map,i=mt(t.maxCategories,200,200);for(let a=0;a<e.length;a++){if(r?.aborted){const d=new Error("图表数据处理已取消");throw d.name="AbortError",d}const c=e[a];if(!c||typeof c!="object"||Array.isArray(c))throw new TypeError("图表数据行应为对象");const f=ca(Object.prototype.hasOwnProperty.call(c,t.categoryField)?c[t.categoryField]:null);let u=o.get(f.key);if(!u){if(o.size>=i)throw new RangeError("图表分类超出预算,请明确筛选或聚合数据");u={label:f.label,accumulators:n.map(se)},o.set(f.key,u)}u.accumulators.forEach(d=>d.add(c))}const s=[...o.values()];return t.sort&&s.sort((a,c)=>(t.sort==="desc"?-1:1)*(a.label<c.label?-1:a.label>c.label?1:0)),{categories:s.map(a=>a.label),series:n.map((a,c)=>({name:a.label??`${a.field??"记录"} · ${a.op}`,values:s.map(f=>fa(f.accumulators[c].value())),...a.color?{color:a.color}:{}}))}}class Se extends Error{constructor(t,r){super(`报表页数超出上限 ${t}(至少 ${r} 页)`),this.limit=t,this.actual=r,this.code="page-limit",this.name="PaginatePageLimitError"}}class _e extends Error{constructor(t,r){super(`报表单元格数量超出上限 ${t}(至少 ${r} 格)`),this.limit=t,this.actual=r,this.code="cell-limit",this.name="PaginateCellLimitError"}}class Ke extends Error{constructor(t,r){super(`报表图表图元数量预计超出上限 ${t}(本次估算 ${r})`),this.limit=t,this.estimated=r,this.code="chart-component-limit",this.name="PaginateChartComponentLimitError"}}const Or=5e4;function It(e=Or){if(!Number.isSafeInteger(e)||e<1||e>1e6)throw new RangeError("maxChartComponents 应为 1..1000000 的安全整数")}function la(e,t,r){const n=e.chartBinding;if(e.kind!=="chart"||e.grid||e.imageData||e.binding||e.pageAnchor)throw new TypeError("绑定图表不能同时设置图片、网格、记录绑定或页眉页脚");const o=Object.prototype.hasOwnProperty.call(t,n.dataset)?t[n.dataset]:void 0;if(!Array.isArray(o))throw new TypeError(`图表数据集 ${n.dataset} 未提供`);return{...ua(o,n,r),type:n.type,leftMm:e.leftMm,topMm:e.topMm,widthMm:e.widthMm,heightMm:e.heightMm,title:n.title,showValues:n.showValues}}function da(e,t,r=Or){It(r);let n=0;return Object.assign(i=>{if(!i.chartBinding)return[i];const s=la(i,e,t),a=n+(s.categories.length?ia(s):1);if(!Number.isSafeInteger(a))throw new RangeError("图表图元估算应为有限安全整数");if(a>r)throw new Ke(r,a);const c=s.categories.length?sa(s):[{kind:"text",leftMm:i.leftMm,topMm:i.topMm,widthMm:i.widthMm,heightMm:i.heightMm,text:"—",style:{align:"center",verticalAlign:"middle",color:"#94a3b8",fontSize:10}}];return n+=c.length,c},{used:()=>n})}function Fe(e,t){return JSON.stringify([e.slice(0,t.length),t.map(r=>[r===null?"null":typeof r,r])])}function ro(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 ma(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("矩阵层级标签应为字符串");pn(e.row,t.length),pn(e.column,r.length)}function pn(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 yn(e,t,r){return{fields:e,options:t??{},hierarchy:r,root:{values:[],children:new Map},leaves:0,expanded:0}}function wn(e,t){const r=ro(t,e.fields);let n=e.root;for(let o=1;o<=r.length;o++){const i=r.slice(0,o),s=Fe(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 ha(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 ga(e,t){const r=[...e.children.values()];return t&&t!=="source"&&r.sort((n,o)=>ha(n.values[n.values.length-1],o.values[o.values.length-1])*(t==="desc"?-1:1)),r}function Ut(e,t,r){return{key:Fe(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 bn(e,t){const r=[];function n(o){for(const i of ga(o,e.options.sort?.[o.values.length]))i.children.size?(n(i),e.options.subtotals?.includes(i.values.length)&&r.push(Ut(e,i.values,"subtotal"))):r.push(Ut(e,i.values,"member"))}return n(e.root),t&&e.leaves&&r.push(Ut(e,[],"total")),r}function xn(e,t,r){const n=ro(t,e.fields),o=[Fe(e.fields,n),...(e.options.subtotals??[]).map(i=>Fe(e.fields,n.slice(0,i)))];return r&&o.push(Fe(e.fields,[])),o}function pa(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 ya(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 f=pa(a,i,e.hierarchy);if(!f){s=void 0;return}if(s?.key===f.key){s.cell.colSpan=(s.cell.colSpan??1)+1;return}const u={text:f.text,rowSpan:f.rowSpan||e.columnFields.length-i,editable:!1,derived:!0};o[i][n+c]=u,s={key:f.key,cell:u}})}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 vn(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 no(e,t){if(!Array.isArray(e)||e.length>(t.maxInputRows??1e5))throw new Error("矩阵输入超出预算");const r=yn(t.rowFields,t.hierarchy.row,t.hierarchy),n=yn(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=vn(0,t,r,n);for(const s of e){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("矩阵数据行应为对象");wn(r,s),wn(n,s),i=vn(e.length,t,r,n)}return{row:r,column:n,shape:i}}function wa(e,t){return no(e,t).shape}function ba(e,t,r){const n=new Map;for(const o of e){const i=xn(r.row,o,!!t.totals),s=xn(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 f of s){let u=c.get(f);u||(u=t.measures.map(d=>se({...d,field:d.valueField??d.field})),c.set(f,u)),u.forEach(d=>d.add(o))}}}return n}function xa(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 va(e,t){return e.kind==="total"?t.hierarchy.totalLabel??"合计":[...e.labels,...e.kind==="subtotal"?[t.hierarchy.subtotalLabel??"小计"]:[]].join(" / ")}function Ma(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:`${va(r,t)} · ${n.label??`${n.field} (${n.op})`}`,semanticRole:"measure",...n.digits===void 0?{}:{format:{kind:"number",digits:n.digits}}}})]}function $a(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 Sa(e,t){const r=no(e,t),n=bn(r.row,!!t.totals),o=xa(bn(r.column,!!t.totals),t),i=ba(e,t,r);return{columns:Ma(o,t),rows:$a(n,o,t,i),headerGrid:ya(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 Ea(e,t){const r=()=>t.measures.map(c=>se(c)),n=new Map,o=new Map,i=new Map,s=t.totals?r():void 0,a=(c,f)=>c?.forEach(u=>u.add(f));for(const c of e){const f=t.row(c),u=t.column(c);o.has(u.key)||o.set(u.key,u.label);let d=n.get(f.key);d||(d={label:f.label,cells:new Map,...t.totals?{totals:r()}:{}},n.set(f.key,d)),t.check(n.size,o.size);let l=d.cells.get(u.key);if(l||(l=r(),d.cells.set(u.key,l)),a(l,c),!t.totals)continue;let m=i.get(u.key);m||(m=r(),i.set(u.key,m)),a(d.totals,c),a(m,c),a(s,c)}return{groups:n,columns:o,columnTotals:i,totals:s}}function ht(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 Aa(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 Rr(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(Aa(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(se({...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&&ma(e.hierarchy,e.rowFields,e.columnFields)}function oo(e,t){if(Rr(t),t.hierarchy)return wa(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(ht(s,t.rowFields).key),n.add(ht(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 ka(e,t){if(t?.hierarchy)return Rr(t),Sa(e,t);oo(e,t);const r=Ea(e,{row:s=>ht(s,t.rowFields),column:s=>ht(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(([f,u],d)=>({key:f,label:u,field:`c${d}_${a}`}));t.totals&&c.push({key:"",label:"合计",field:`total_${a}`});for(const f of c){const u=f.field===`total_${a}`;o.push({field:f.field,header:`${f.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++][f.field]=(u?l.totals?.[a]:l.cells.get(f.key)?.[a])?.value()??(s.op==="count"?0:null);i[f.field]=(u?r.totals?.[a]:r.columnTotals.get(f.key)?.[a])?.value()??(s.op==="count"?0:null)}}),t.totals&&e.length&&n.push(i),{rows:n,columns:o}}const Na=96;function Pa(e,t=Na){return e*t/72}function Ct(e,t=96,r=Sr){if(e?.fontSizePx!=null)return{fontSizePt:e.fontSizePx*72/t,fontSizePx:e.fontSizePx};const n=e?.fontSize??r;return{fontSizePt:n,fontSizePx:Pa(n,t)}}function Fa(e){return e?.lineHeight??Pt}function ee(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 Oa(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 Mn(e,t,r){return e?.length?Oa(e,t):Array.from({length:r},(n,o)=>({pos:t*o/r,size:t/r}))}function io(e,t,r){const n=e.cells??[],o=Math.max(n.length,1),i=e.colWidthsMm?.length??n.reduce((p,b)=>Math.max(p,Array.isArray(b)?b.length:0),1),s=Mn(e.colWidthsMm,t,i),a=p=>p<=0?0:p>=i?s[s.length-1].pos+s[s.length-1].size:s[p].pos,c=Mn(e.rowHeightsMm,r,o),f=p=>p<=0?0:p>=o?c[c.length-1].pos+c[c.length-1].size:c[p].pos,u=new Set,d=(p,b)=>`${p}:${b}`,l=[],m=new Set,h=new Set,g=(p,b)=>`v${p}:${b}`,y=(p,b)=>`h${p}:${b}`;n.forEach((p,b)=>{if(!Array.isArray(p))return;let x=0;for(const $ of p){for(;x<i&&u.has(d(b,x));)x++;if(x>=i)break;const j=Math.max(1,Math.min($?.colSpan??1,i-x)),D=Math.max(1,$?.rowSpan??1),v=Math.min(o,b+D),M=Math.min(i,x+j);for(let N=b;N<v;N++)for(let R=x;R<M;R++)u.add(d(N,R));for(let N=x+1;N<M;N++)for(let R=b;R<v;R++)m.add(g(N,R));for(let N=b+1;N<v;N++)for(let R=x;R<M;R++)h.add(y(N,R));const S=a(x),I=f(b);l.push({ri:b,ci:x,cell:$??{},xMm:S,yMm:I,widthMm:a(M)-S,heightMm:f(v)-I}),x=M}});const w=[];for(let p=1;p<i;p++){let b=-1;for(let x=0;x<=o;x++){const $=x<o&&!m.has(g(p,x));$&&b<0&&(b=x),!$&&b>=0&&(w.push({kind:"v",pos:a(p),from:f(b),to:f(x)}),b=-1)}}for(let p=1;p<o;p++){let b=-1;for(let x=0;x<=i;x++){const $=x<i&&!h.has(y(p,x));$&&b<0&&(b=x),!$&&b>=0&&(w.push({kind:"h",pos:f(p),from:a(b),to:a(x)}),b=-1)}}return{columns:s,rows:c,cells:l,edges:w}}function Ra(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 Ia(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 so(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 Ir(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 ao(e,t){let r=ee({fontSize:e.fontSizePt??Sr,bold:e.headerBold??!0,align:"center",verticalAlign:"middle",backgroundColor:e.headerBackgroundColor},t.style);return e.headerAlign!==void 0&&(r.align=e.headerAlign),r=ee(r,e.headerStyle),t.headerAlign!==void 0&&(r.align=t.headerAlign),ee(r,t.headerStyle)}function Ca(e,t){return{member:"body",subtotal:"subtotal",total:"grand-total"}[e?.rows.get(t)?.kind??"member"]}function Ta(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 ja(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=ka(t,Ta(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 Da(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=io({...e.headerGrid,colWidthsMm:o},o.reduce((c,f)=>c+f,0),n.length),s=new WeakMap;for(const{cell:c,ci:f,ri:u,widthMm:d}of i.cells){const l={...ao(e,e.columns[f]),...c.style},m=Ct(l).fontSizePt,g=(Ve(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??Pt)*25.4/72+r*2)/(c.rowSpan??1);for(let y=u;y<u+(c.rowSpan??1);y++)n[y]=Math.max(n[y]??0,g);s.set(c,l)}const a=e.headerGrid.cells.map(c=>c.map(f=>f?{...f,style:s.get(f)}:null));return{...e.headerGrid,cells:a,rowHeightsMm:n}}class co extends Error{constructor(t){super(`树节点超出行数预算 ${t}`),this.limit=t,this.code="tree-row-limit",this.name="TreeRowLimitError"}}function Gt(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 Cr(e){return{rows:Gt(e.maxRows,1e5,1e6,"树行数预算"),depth:Gt(e.maxDepth,64,256,"树深度预算"),visits:Gt(e.maxAggregationVisits,1e6,1e7,"树聚合访问预算")}}function fo(e){return typeof e=="string"&&!!e.trim()}function xe(e){return fo(e)&&!["__proto__","prototype","constructor"].includes(e)}function uo(e){if(fo(e)||typeof e=="number"&&Number.isFinite(e))return e;throw new Error("树节点业务键应为非空字符串或有限数字")}function lo(e){return JSON.stringify([typeof e,e])}function mo(e){return[e.idField,...e.input==="flat"?[e.parentField??""]:[e.childrenField??"children"]]}function Tr(e,t){const r=mo(e);if(t?.some(n=>n.scope&&n.scope!=="row"||r.includes(n.field)))throw new Error("树形布局仅支持不覆盖结构键的当前行计算")}function Ee(e){if(!e?.aborted)return;const t=new Error("树报表处理已取消");throw t.name="AbortError",t}function La(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||!xe(n.field)||r.has(n.field))throw new Error("树聚合输出字段应安全、非空且唯一");for(const o of[n.valueField,n.weightField])if(o!==void 0&&!xe(o))throw new Error("树聚合来源字段应安全且非空");if([...mo(e),e.labelField].includes(n.field))throw new Error("树聚合不能覆盖结构键或标签字段");r.add(n.field),se({...n,field:n.valueField??n.field})}}function Ba(e){if(!xe(e.idField)||!xe(e.labelField))throw new Error("树需要安全的业务键和标签字段");if(e.input==="flat"&&(!xe(e.parentField)||e.parentField===e.idField))throw new Error("扁平树需要独立的父键字段");if(e.childrenField!==void 0&&!xe(e.childrenField))throw new Error("子节点字段应安全且非空");if(e.input==="nested"&&[e.idField,e.labelField].includes(e.childrenField??"children"))throw new Error("子节点字段不能覆盖业务键或标签字段")}function ho(e){if(!e||typeof e!="object"||!["flat","nested"].includes(e.input))throw new Error("树输入应为 flat 或 nested");if(Ba(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");Cr(e),La(e)}function go(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("树节点应为对象");if(r.size>=n.rows)throw new co(n.rows);const o=uo(e[t.idField]),i=lo(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 _a(e,t,r,n,o){for(const s of e)Ee(o),go(s,t,r,n);const i=[];for(const s of r.values()){Ee(o);const a=s.row[t.parentField];if(a==null){i.push(s);continue}const c=r.get(lo(uo(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 Ka(e,t,r,n,o){const i=[],s=[{rows:e,next:0}];for(;s.length;){Ee(o);const a=s[s.length-1];if(a.next>=a.rows.length){s.pop();continue}const c=go(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 f=c.row[t.childrenField??"children"];if(f!=null){if(!Array.isArray(f))throw new Error("嵌套树 children 字段应为数组");f.length&&s.push({rows:f,next:0,parent:c})}}return i}function Wa(e,t,r,n){const o=[],i=[{nodes:e,next:0}];for(;i.length;){Ee(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 za(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=>se({...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(Ee(n),s+=o.length,s>r.visits)throw new Error(`树聚合超出访问预算 ${r.visits}`);for(const f of i.get(c))f.add(a.row)}for(const[a,c]of i)a.row={...a.row},o.forEach((f,u)=>{a.row[f.field]=c[u].value()})}function po(e,t,r){if(ho(t),Ee(r),!Array.isArray(e))throw new Error("树数据应为节点数组");const n=Cr(t),o=new Map,i=t.input==="flat"?_a(e,t,o,n,r):Ka(e,t,o,n,r);return Wa(i,o.size,n,r)}function yo(e,t,r){return po(e,t,r).map(n=>n.original)}function wo(e,t,r={}){const n=po(e,t,r.signal);if(Tr(t,r.computed?.fields),r.computed?.fields.length){const o=Rt(n.map(i=>i.row),{...r.computed,signal:r.signal}).rows;n.forEach((i,s)=>{i.row=o[s]})}return za(n,t,Cr(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 Ja(e,t,r){const n=new Set,o=e.cells.map((i,s)=>{const a=[];let c=0;for(const f of i){for(;n.has(`${s}:${c}`);)c++;const u=f?.colSpan??1,d=f?.rowSpan??1;let l=0;for(let m=c;m<c+u;m++){t.has(m)&&l++;for(let h=s+1;h<s+d;h++)n.add(`${h}:${m}`)}l&&a.push(f?{...f,colSpan:l}:null),c+=u}return a});return{...e,cells:o,colWidthsMm:r}}function Va(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:Ja(e.headerGrid,t,r.map(n=>n.widthMm))}:{}}}function jr(e){return e.kind==="list"?e.id:e.nid}function Ha(e){return e.kind==="list"?!1:e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&/\{(?:page|totalPages)\}/.test(e.text)}function Ua(e,t){const r=e.filter(o=>t.componentIds.includes(jr(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 Ga(e,t){if(!t)return e.map(n=>({components:[n]}));const r=new Map(e.map(n=>[jr(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 bo(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(Ha(o))continue;const i=jr(o);if(!i||r.has(i))throw new Error("流式排版组件应具有唯一标识");r.add(i)}if(Ya(e,t,r,n),n.size!==r.size)throw new Error("流式排版必须显式包含每个非锚点组件")}function Ya(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)}Ua(e,i),o=i.topMm+i.heightMm}}function*qa(e){const{page:t}=e;bo(t.components,t.flow);let r=0,n=0;for(const o of Ga(t.components,t.flow)){e.active();const i=o.band,s=o.components.some(u=>u.kind==="list"&&u.cardinality!=="record"),a=s?0:o.components.reduce((u,d)=>Math.max(u,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 f=c+a;for(const u of o.components){const d=c+u.topMm-i.topMm;u.kind==="list"?(yield*e.list(u,d,l=>{f=s?l:Math.max(f,l)}),e.active()):e.append({...u,topMm:d})}n=f,r=i.topMm+i.heightMm}}function Xa(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||t.visual))}function Dr(e){return e.pages.some(t=>t.components.some(r=>r.kind==="list"?Xa(r):!!r.chartBinding))}const Za=new Set(["__proto__","prototype","constructor"]);function ne(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tt(e){return typeof e=="string"&&!!e.trim()&&!Za.has(e)}function gt(e,t,r,n){for(const o of Object.keys(e))t.includes(o)||n.push({path:`${r}.${o}`,message:"存在未知配置字段"})}function Qa(e,t,r){if(e!==void 0){if(!ne(e)||!["number","percent","date"].includes(String(e.kind))){r.push({path:t,message:"绑定格式应为 number、percent 或 date"});return}gt(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 ec(e,t,r){const n=e.binding;if(n===void 0)return;const o=`${t}.binding`;if(!ne(n)){r.push({path:o,message:"字段绑定应为对象"});return}(!["text","image","barcode","qrcode"].includes(String(e.kind))||e.grid!==void 0)&&r.push({path:o,message:"绑定仅支持独立文本、图片、条码与二维码组件"}),gt(n,["field","format","prefix","suffix","emptyText"],o,r),tt(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:"应为字符串"});Qa(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 tc(e,t){if(!ne(e)){t.push({path:"$.repeat",message:"逐记录配置应为对象"});return}gt(e,["dataset","rowKey","copies"],"$.repeat",t),tt(e.dataset)||t.push({path:"$.repeat.dataset",message:"数据集应为安全的非空名称"}),e.rowKey!==void 0&&!tt(e.rowKey)&&t.push({path:"$.repeat.rowKey",message:"业务主键应为安全的非空字段名"});const r=e.copies;r!==void 0&&(ne(r)?(gt(r,["field"],"$.repeat.copies",t),tt(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 xo(e,t,r,n){if(!ne(e))return;ec(e,t,n),e.binding!==void 0&&!r&&n.push({path:`${t}.binding`,message:"字段绑定需要模板 repeat 数据集;普通报表请使用列表字段"}),r&&e.kind==="list"&&n.push({path:t,message:"逐记录标签使用固定组件;动态列表请使用普通报表模板"}),e.chartBinding!==void 0&&(r||t.includes(".children."))&&n.push({path:`${t}.chartBinding`,message:"数据图表应放在普通报表的页面或流式分区,不放在逐记录标签或嵌套单元格内"});const o=e.grid;ne(o)&&Array.isArray(o.cells)&&o.cells.forEach((i,s)=>{Array.isArray(i)&&i.forEach((a,c)=>{ne(a)&&Array.isArray(a.children)&&a.children.forEach((f,u)=>xo(f,`${t}.grid.cells.${s}.${c}.children.${u}`,r,n))})})}function vo(e,t){const r=e.repeat!==void 0;r&&tc(e.repeat,t),Array.isArray(e.pages)&&e.pages.forEach((n,o)=>{if(!ne(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(xo(s,c,r,t),!r||!ne(s))return;const{leftMm:f,topMm:u,widthMm:d,heightMm:l}=s;[f,u,d,l,n.widthMm,n.heightMm].every(m=>typeof m=="number"&&Number.isFinite(m))&&(Number(f)<0||Number(u)<0||Number(f)+Number(d)>Number(n.widthMm)+.001||Number(u)+Number(l)>Number(n.heightMm)+.001)&&t.push({path:c,message:"标签组件超出纸张边界,请调整位置或尺寸"})})})}const rc=512,$n=256*1024;function nc(){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 f=Ve(n,o,i,s),u=a.length+f.reduce((d,l)=>d+l.length,0);if(u<=$n){for(;e.size>=rc||t+u>$n;){const d=e.keys().next().value;t-=e.get(d).units,e.delete(d)}e.set(a,{lines:f.slice(),units:u}),t+=u}return f}}function oc(e){return typeof e=="string"&&/^data:image\/(png|jpe?g);base64,[A-Za-z0-9+/\r\n]+=*$/.test(e)}class H 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 Lr(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 H(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 H(i,"绑定值应为字符串、有限数字、布尔值或空值",n,t)}function ic(e,t,r={}){const n=Lr(t,e.field,r);return n==null||n===""?e.emptyText??"":`${e.prefix??""}${kr(n,e.format)}${e.suffix??""}`}const sc=1e4,Sn=25e4;function Br(e){if(e?.aborted)throw e.reason??new DOMException("标签生成已取消","AbortError")}function Mo(e,t,r){const n=typeof e.copies=="object"?Lr(t,e.copies.field,r):e.copies??1;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>1e3)throw new H(`$.datasets.${r.dataset}[${r.rowIndex}]`,"每条记录复制数必须是 1..1000 的数值型整数",r.rowIndex,typeof e.copies=="object"?e.copies.field:void 0);return n}function $o(e,t,r){if(e.rowKey===void 0)return;const n=Lr(t,e.rowKey,r);if(typeof n=="string"&&n.trim()||typeof n=="number"&&Number.isFinite(n))return n;throw new H(`$.datasets.${r.dataset}[${r.rowIndex}].${e.rowKey}`,"业务主键必须是非空字符串或有限数字",r.rowIndex,e.rowKey)}function ac(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 cc(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 H(`$.datasets.${n.dataset}`,"逐记录标签数据集缺失,应提供对象数组(允许空数组)");const i=new Set,s=r.maxPages??sc,a=ac(e);let c=0,f=0;for(const[u,d]of o.entries()){if(Br(r.signal),!d||typeof d!="object"||Array.isArray(d))throw new H(`$.datasets.${n.dataset}[${u}]`,"标签记录应为对象",u);const l={rowIndex:u,dataset:n.dataset},m=$o(n,d,l);if(m!==void 0){const g=JSON.stringify([typeof m,m]);if(i.has(g))throw new H(`$.datasets.${n.dataset}[${u}].${n.rowKey}`,"业务主键重复;请先确认记录来源,避免重复打印标签",u,n.rowKey);i.add(g)}const h=Mo(n,d,l);if(c+=h*e.pages.length,f+=h*a,c>s)throw new Se(s,c);if(f>Sn)throw new H("$.repeat",`标签组件总量(含网格行、槽位及嵌套组件)超过安全预算 ${Sn},请分批生成`,u)}return o}function fc(e,t,r){if(!e.binding)return e;const{binding:n,...o}=e,i=ic(n,t.row,t);if(e.kind==="image"){if(!i)return;if(!oc(i))throw new H(`${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 uc(e,t,r){if(e.kind!=="text"||e.grid||e.richParagraphs?.length)return e;const n=e.style??{},o=Ct(n).fontSizePt,i=e.text??e.lines?.join(`
5
+ `)??"";if(i.length>16384)throw new H(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??Er),a=s.length*o*Fa(n)*25.4/72;if(a>e.heightMm+.05)throw new H(r,`标签文字需要约 ${a.toFixed(2)}mm 高,超出 ${e.heightMm}mm;请增大文本区域、减少内容或调整字号`,t.rowIndex,e.binding?.field);return{...e,lines:s}}function So(e,t,r){Br(t.options.signal);const n=fc(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((f,u)=>{const d=So(f,t,`${r}.grid.cells.${s}.${c}.children.${u}`);return d?[d]:[]})}:a))}),uc(o===n.grid?n:{...n,grid:o},t,r)}function lc(e,t,r,n,o,i){return{...e,components:e.components.flatMap((s,a)=>{const c=So(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*dc(e,t,r){const n=[];if(vo(e,n),n.length)throw new H(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=cc(e,t,r),s=nc();for(const[a,c]of i.entries()){const f={row:c,rowIndex:a,dataset:o.dataset,options:r,wrapText:s},u=Mo(o,c,f),d=$o(o,c,f);for(let l=0;l<u;l++)for(const[m,h]of e.pages.entries())Br(r.signal),yield{page:lc(h,m,f,l,u,d),pageIndex:m}}}const mc=/^#[0-9a-f]{6}$/i;function Eo(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return t.kind!=="colorScale"&&t.kind!=="dataBar"||t.field!==void 0&&(typeof t.field!="string"||!t.field.trim())||t.numeric!==void 0&&!["number","decimal"].includes(t.numeric)||[t.min,t.max].some(r=>r!==void 0&&(typeof r!="number"||!Number.isFinite(r)))||t.min!==void 0&&t.max!==void 0&&t.min>t.max?!1:Object.entries(t).every(([r,n])=>!["color","negativeColor","lowColor","highColor"].includes(r)||typeof n=="string"&&mc.test(n))}function Ao(e,t){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(t!=="decimal"||typeof e!="string"||e.length>1024||!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e))return;const r=Number(e);return Number.isFinite(r)?r:void 0}function hc(e,t,r){let n="#";for(const o of[1,3,5]){const i=parseInt(e.slice(o,o+2),16),s=parseInt(t.slice(o,o+2),16);n+=Math.round(i+(s-i)*r).toString(16).padStart(2,"0")}return n}function Yt(e,t,r){if(t===r)return e<t?0:e>r?1:.5;if(e<=t)return 0;if(e>=r)return 1;const n=r-t;return Number.isFinite(n)?(e-t)/n:(e/2-t/2)/(r/2-t/2)}function gc(e,t,r,n){const o=new WeakMap;return{apply(i,s){const a=Ao(s[t],e.numeric);if(a===void 0)return;if(e.kind==="dataBar"){const l=Math.min(r,0),m=Math.max(n,0),h=Yt(0,l,m),g=l===m?h:Yt(a,l,m);i.dataBar={start:Math.min(h,g),end:Math.max(h,g),color:a<0?e.negativeColor??"#f3bcc3":e.color??"#bad8fa"};return}const c=hc(e.lowColor??"#f0f7ff",e.highColor??"#8bbcf1",Yt(a,r,n)),f=i.style??{},u=o.get(f)??new Map;o.set(f,u);let d=u.get(c);d||(d={...f,backgroundColor:c},u.set(c,d)),i.style=d}}}function pc(e,t,r){return e.map(n=>{En(r);const o=n.visual;if(!o)return;if(!Eo(o))throw new TypeError("Invalid column visual rule");const i=o.field??n.field;let s=1/0,a=-1/0,c=0;if(o.min===void 0||o.max===void 0)for(const d of t){(c++&1023)===0&&En(r);const l=Ao(d[i],o.numeric);l!==void 0&&(s=Math.min(s,l),a=Math.max(a,l))}let f=o.min??s,u=o.max??a;if(!(!Number.isFinite(f)||!Number.isFinite(u)))return f>u&&(o.min!==void 0?u=f:f=u),gc(o,i,f,u)})}function En(e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError")}function yc(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 pt(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 We(e){return e.components.reduce((t,r)=>r.kind!=="list"&&r.pageAnchor==="header"?Math.max(t,r.topMm+r.heightMm):t,0)}function ko(e,t){let r=e.textMetrics.get(t);if(!r){const n=Ct(t).fontSizePt;r={measureOptions:{fontSizePt:n,fontFamily:t.fontFamily??Hn,italic:t.italic,bold:t.bold,letterSpacingPt:t.letterSpacing},lineMm:n*(t.lineHeight??Pt)*25.4/72},e.textMetrics.set(t,r)}return r}function wc(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function _r(e,t,r=[],n){const o=e.fontSizePt??Sr,i=e.paddingMm??1,s=e.columns.map(w=>w.align??w.style?.align??e.align??"left"),a=e.columns.map((w,p)=>({...ee({fontSize:o,verticalAlign:"middle"},w.style),align:s[p]==="auto"?"left":s[p]})),c=a.map((w,p)=>s[p]==="auto"?{left:w,center:{...w,align:"center"},right:{...w,align:"right"}}:void 0),f=e.columns.map((w,p)=>w.rules?.map(b=>{const x=c[p];if(x)return{left:ee(x.left,b.style),center:ee(x.center,b.style),right:ee(x.right,b.style)};const $=ee(a[p],b.style);return{left:$,center:$,right:$}})),u=e.columns.map(w=>ao(e,w)),d=e.columns.map(w=>w.header);let l=e.rowHeightMm??0;for(let w=0;w<d.length;w++){const p=u[w],b=Ct(p).fontSizePt,x=Ve(d[w],e.columns[w].widthMm-i*2,{fontSizePt:b,fontFamily:p.fontFamily??Hn,italic:p.italic,bold:p.bold,letterSpacingPt:p.letterSpacing},t),$=b*(p.lineHeight??Pt)*25.4/72;l=Math.max(l,Math.max(x.length,1)*$+i*2)}const m=d.map((w,p)=>({text:w,style:u[p]})),h=e.border===!1?{borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}:{borderBottom:!0,borderLeft:!0,borderRight:!0,borderTop:!0},g=e.columns.map(w=>w.widthMm),y=bc(Da(e,t),g,{cells:[m],colWidthsMm:g,rowHeightsMm:[l],paddingMm:i});return{fontSizePt:o,paddingMm:i,visuals:pc(e.columns,r,n),visibility:e.columns.map(w=>w.visibleWhen?q(w.visibleWhen):void 0),ruleReaders:e.columns.map(w=>w.rules?.map(p=>q(p.when))),cellStyles:a,autoStyles:c,ruleStyles:f,textMetrics:new WeakMap,numberFormats:e.columns.map(w=>Zn(w.format)),derivedFields:new Set(e.computed?.map(w=>w.field)),borderStyle:h,headerHeightMm:y.rowHeightsMm.reduce((w,p)=>w+p,0),headerGrid:y,colWidthsMm:g,columns:e.columns}}function bc(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 xc(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 ze(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],f=e.visibility[a]?.(t)!==!1,u=f?t[c.field]:null,d=e.autoStyles[a]?so(u,c.format,c.semanticRole):"left";let l=e.autoStyles[a]?.[d]??e.cellStyles[a];if(c.rules){for(let b=0;b<c.rules.length;b++)if(e.ruleReaders[a][b](t)){l=e.ruleStyles[a][b][d];break}}const m=c.format?kr(u,c.format):Ir(u),h=vc(e,c,o);l=Mc(e,c,l,o);const g=ko(e,l),y=Ve(m,Math.max(1,c.widthMm-e.paddingMm*2-h),g.measureOptions,r);i=Math.max(i,y.length*g.lineMm+e.paddingMm*2);const w=wc(u),p={text:m,style:l};u!=null&&e.visuals[a]?.apply(p,t),w!==void 0&&(p.value=w),xc(p,c,e.numberFormats[a]),$c(p,c,e,o,h),e.derivedFields.has(c.field)&&(p.derived=!0,p.editable=!1),f||(p.editable=!1),s[a]=p}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 vc(e,t,r){return!r||t.field!==e.tree.list.tree.labelField?0:Ra(e.tree.list,t,r,e.paddingMm)}function Mc(e,t,r,n){return!n||t.field!==e.tree.list.tree.labelField||r.align==="left"?r:{...r,align:"left"}}function $c(e,t,r,n,o=0){n&&(o&&(e.indentMm=o),Ia(e,t,n,r.tree.list))}function No(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*Po(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=No(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,Ir(i[0][n.field])),firstRow:i[0],group:n,depth:r,rows:i},yield*Po(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 Fo(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=Be(t,{...i,field:i.valueField??i.field});return[i.field,{text:kr(a,s),...a===null?{}:{value:a},...typeof a=="number"?{numberFormat:Zn(s)}:{}}]}))}function Oo(e,t){const r=e.findIndex(n=>t.includes(n.field));return r<0?1:r}function Oe(e,t,r,n,o,i){const s=[],a=Math.max(0,Math.min(i,e.columns.length)),c=ee({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],h=n.get(m.field),g=e.autoStyles[l]?.[so(h?.value,m.format)]??e.cellStyles[l];s.push({...h,text:h?.text??"",style:ee(g,o)})}const f={text:r,colSpan:e.columns.length,style:{bold:!0,...c}},u=a?[s]:[[f],s],d=u.map(l=>Sc(e,l,t));return{grid:{cells:u,colWidthsMm:e.colWidthsMm,rowHeightsMm:d,paddingMm:e.paddingMm},heightMm:d.reduce((l,m)=>l+m,0)}}function Sc(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=ko(e,i.style),f=Ve(i.text??"",s-e.paddingMm*2,c.measureOptions,r);n=Math.max(n,f.length*c.lineMm+e.paddingMm*2)}return n}function Ec(e,t,r){const{templatePage:n,current:o,warnings:i,nextId:s,pushCurrent:a}=r,c=()=>pt(n,o),f=Math.max(o.marginTopMm,We(n)),u=n.layout==="wide"?We(n):f,d={id:r.tableId,columnKeys:e.columns.map(v=>v.field),...e.layout===void 0?{}:{layout:e.layout},...e.title===void 0?{}:{title:e.title}},l=new Map,m=new Map,h={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}:{}}}:{}},g=v=>o.components.push({...h,topMm:v});if(r.flow&&e.header!==!1&&t.headerHeightMm>c()-f+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的表头高度超出单页可用范围`);let y=Math.max(r.startTop??e.topMm,f);e.header!==!1&&(g(y),y+=t.headerHeightMm+r.mmPerRow);function w(){const v=Math.max(r.flow||n.layout==="wide"?0:e.topMm,u);return(e.header!==!1&&e.headerEveryPage!==!1?v+t.headerHeightMm:u)+[...m.values()].reduce((S,I)=>S+I.heightMm,0)}function p(){const v=n.layout==="wide"?0:o.marginBottomMm;return Math.min(n.heightMm-v,pt(n,o))-w()}function b(v){if(y+v<=c())return;a(),o.components=[],o.heightMm=n.heightMm,n.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0);const M=Math.max(r.flow||n.layout==="wide"?0:e.topMm,u);e.header!==!1&&e.headerEveryPage!==!1?(g(M),y=M+t.headerHeightMm):y=u;for(const S of m.values())$(S,"listgr","group-header")}function x(v,M,S,I){const N=p();if(r.flow&&v.heightMm>N+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的单行高度超出单页可用范围`);v.heightMm>N&&i.push(`列表 ${e.id??e.dataset} 行高 ${v.heightMm.toFixed(2)}mm 超出单页可用高度 ${N.toFixed(2)}mm,预览与打印可能截断内容`),b(v.heightMm),$(v,M,S,I)}function $(v,M,S,I){const N=v.table?.id??d.id,R=S==="header"?-1:l.get(N)??0;S!=="header"&&l.set(N,R+v.grid.cells.length),o.components.push({kind:"rect",leftMm:e.leftMm,topMm:y,widthMm:e.widthMm,heightMm:v.heightMm,grid:v.grid,nid:s(M),table:{...d,...v.table,role:S,rowIndex:R,...I?{source:I}:{}},style:t.borderStyle,...e.meta||v.meta?{meta:{...e.meta,...v.meta}}:{}}),y+=v.heightMm}function j(v){v<=p()&&b(v)}return{keepTogether:j,placeGridRow:x,setGroupHeader:(v,M)=>{M?m.set(v,M):m.delete(v)},bottom:()=>y}}function Ac(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 Tt(e,t){const r=new Map;if(!e.rowKey)return r;const n=new Set;for(const o of t){const i=Ac(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 kc(e,t,r,n,o){if(!e.grandTotal)return;const i=typeof e.grandTotal=="object"?e.grandTotal:void 0,s=jt(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 f=Oe(r,n.measurer,i?.label??"合计",Fo(e.columns,t,a,c),i?.style??{},Oo(e.columns,[...a,...c.map(u=>u.field)]));o.placeGridRow(f,"listgt","grand-total")}function ae(e){if(e?.aborted){const t=new Error("报表排版已取消");throw t.name="AbortError",t}}function jt(e){const t=e.groups??(e.groupBy?[e.groupBy]:[]);if(t.length>16)throw new Error("列表最多支持 16 级分组");return t}function Kr(e){const t=Va(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 Nc(e,t,r){const n=e.detail;if(!n)return;const o=new Set;for(const f of t){const u=sr(f[n.parentKey]);if(o.has(u))throw new Error("主从明细的主表关联键重复");o.add(u)}const i=r.datasets[n.dataset]??[],s=new Map,a=[];for(const f of i){const u=f[n.foreignKey];if(!Ro(u)&&n.unmatched==="ignore")continue;const d=sr(u);if(!o.has(d)){if(n.unmatched!=="ignore")throw new Error(`明细数据集 ${n.dataset} 存在未关联的业务键`);continue}const l=s.get(d);l?l.push(f):s.set(d,[f]),a.push(f)}const c=Kr({...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:{..._r(c,r.measurer,a,r.signal),rowHeightFloorMm:c.rowHeightMm??0},rows:s,sources:Tt(c,a)}}function Ro(e){return typeof e=="string"&&!!e.trim()||typeof e=="number"&&Number.isFinite(e)}function sr(e){if(!Ro(e))throw new Error("主从关联键必须是非空字符串或有限数字");return No(e)}function*Pc(e,t,r,n,o){if(!r)return;const i=r.rows.get(sr(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({...Oe(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)ae(n.signal),o.placeGridRow({...ze(r.inter,a,n.measurer),table:s},"listdr","body",r.sources.get(a)),yield*n.takePages()}function Io(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("树形布局需要可见的标签列");Tr(e.tree,e.computed)}function Fc(e,t,r){Io(e);const n=wo(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=Tt(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 Oc(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 Co(e,t,r){const n=r.prepared.get(e);if(n)return n;const o=Oc(e,t);if(o)return r.prepared.set(e,o),o;if(e.tree){const c=Fc(e,t,r);return r.prepared.set(e,c),c}let i=e.computed?.length?Rt(t,{fields:e.computed,signal:r.signal,formula:r.formula}).rows:t;const s=i===t?void 0:new Map(i.map((c,f)=>[c,t[f]]));e.rowVisibleWhen&&(i=i.filter(q(e.rowVisibleWhen)));const a=ja(e,i);if(!e.matrix){const c=Tt(e,s?i.map(f=>s.get(f)):i);a.sources=s?new Map(i.map(f=>[f,c.get(s.get(f))])):c}return r.prepared.set(e,a),a}function Rc(e,t,r,n){if(!n.flow)return;const{current:o,templatePage:i}=n,s=Math.max(o.marginTopMm,We(i)),a=Math.max(n.startTop??e.topMm,s),c=(e.header===!1?0:t.headerHeightMm)+(r[0]?ze(t,r[0],n.measurer).heightMm:0);a+c<=pt(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,We(i)))}function*Ic(e,t,r){const n=Co(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??Tt(e,o),s=Kr(e),a=jt(s),c={..._r(s,r.measurer,o,r.signal),rowHeightFloorMm:s.rowHeightMm??0,matrix:n.matrix,...n.treeRows?{tree:{list:s,rows:n.treeRows}}:{}};Rc(s,c,o,r);const f=Ec(s,c,r),u=Nc(s,o,r);let d;for(const l of Po(o,a)){if(ae(r.signal),l.kind==="row")f.placeGridRow(d??ze(c,l.row,r.measurer),"listr",Ca(n.matrix,l.row),i.get(l.row)),d=void 0,yield*r.takePages(),yield*Pc(s,l.row,u,r,f);else if(l.kind==="groupHeader"){const m=Oe(c,r.measurer,l.label,new Map,l.group.headerStyle??{},s.columns.length);d??=ze(c,l.firstRow,r.measurer);const h=a.slice(l.depth+1).reduce((g,y)=>g+Oe(c,r.measurer,(y.headerTemplate??"{value}").replace(/\{value\}/g,Ir(l.firstRow[y.field])),new Map,y.headerStyle??{},s.columns.length).heightMm,0);l.group.keepWithNext!==!1&&f.keepTogether(m.heightMm+h+d.heightMm),f.placeGridRow(m,"listg","group-header"),l.group.repeatHeader&&f.setGroupHeader(l.depth,m)}else if(l.kind==="subtotal"){const m=l.group.subtotal??[],h=l.group.aggregates??[],g=Oe(c,r.measurer,l.label,Fo(s.columns,l.rows,m,h),l.group.subtotalStyle??{},Oo(s.columns,[...m,...h.map(y=>y.field)]));f.placeGridRow(g,"listst","subtotal")}else f.setGroupHeader(l.depth);yield*r.takePages()}kc(s,n.totalRows??o,c,r,f),r.finished?.(f.bottom()),yield*r.takePages()}function Wr(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 zr(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=>zr(o,t))}:{}}:null))}}:{}}}function Cc(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 f=c.replace(/\{page\}/g,String(n));return i===void 0?f:f.replace(/\{totalPages\}/g,String(i))};for(const c of r)s.components.push(zr(c,a));if(e.layout==="wide"){const c=s.components.reduce((f,u)=>Math.max(f,u.topMm+u.heightMm),0);s.marginBottomMm=o?e.marginBottomMm??0:0,s.pageHeightMm=Math.max(1,c+s.marginBottomMm)}return s}function Jr(e){return e.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+To(s),0)??0):0),0),0)}function To(e){return e.grid?Jr(e.grid):0}function jo(e){for(const t of["maxPages","maxCells","knownTotalPages"])if(e[t]!==void 0&&(!Number.isSafeInteger(e[t])||e[t]<1))throw new RangeError(`${t} 应为正安全整数`);It(e.maxChartComponents)}function Tc(e,t){const r=Co(e,t.datasets[e.dataset]??[],t),n=Kr(r.list),o={..._r(n,t.measurer,r.rows,t.signal),rowHeightFloorMm:n.rowHeightMm??0};return(n.header===!1?0:o.headerHeightMm)+r.rows.reduce((i,s)=>i+ze(o,s,t.measurer).heightMm,0)}function*jc(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??""} 输出为空`),Ic(i,Array.isArray(c)?c:[],{...e,tableId:`${e.tableId}:${n.get(i)}`,startTop:s,finished:a,flow:!!t.flow})};if(t.flow){yield*qa({page:t,active:()=>ae(e.signal),top:()=>Math.max(r.marginTopMm,We(t)),bottom:()=>pt(t,r),append:i=>{r.components.push(...e.resolveChart(i))},nextPage:()=>{e.pushCurrent(),r.components=[],r.heightMm=t.heightMm,t.layout==="wide"&&(r.marginTopMm=0,r.marginBottomMm=0)},takePages:e.takePages,height:i=>Tc(i,e),list:o});return}for(const i of t.components)Wr(i)||(i.kind==="list"?yield*o(i):r.components.push(...e.resolveChart(i)))}function*Do(e,t,r,n,o,i=new WeakMap,s){let a=0,c=0,f=0;const u=us(r.measurer??Er),d=da(t,r.signal,r.maxChartComponents),l=m=>`${m}_${(++a).toString(36)}`;for(const{pageIndex:m,page:h}of dc(e,t,r)){ae(r.signal);const g=yc(h),y=h.components.filter(Wr);let w=[];const p=(x=!1)=>{if(ae(r.signal),r.maxPages!==void 0&&c>=r.maxPages)throw new Se(r.maxPages,c+1);if(r.maxCells!==void 0&&(f+=[...g.components,...y].reduce(($,j)=>$+To(j),0),f>r.maxCells))throw new _e(r.maxCells,f);w.push(Cc(h,g,y,++c,x,o))},b=()=>{const x=w;return w=[],x};yield*jc({templatePage:h,current:g,warnings:n,nextId:l,pushCurrent:p,takePages:b,datasets:t,resolveChart:d,signal:r.signal,formula:r.formula,prepared:i,measurer:u,mmPerRow:r.mmPerRow??0,tableId:`table:${m}`}),p(!0),yield*b()}s&&(s.chartComponents=d.used())}function Dc(e,t,r={}){const n=typeof r=="number"?{mmPerRow:r}:r;jo(n);const o=[],i={chartComponents:0},s=[...Do(e,t,n,o,n.knownTotalPages,void 0,i)];return Bo(e,n,s,o,i)}async function Lo(e,t,r={}){jo(r),ae(r.signal);const n=[],o=[],i={chartComponents:0};let s=performance.now(),a=0;for(const c of Do(e,t,r,n,r.knownTotalPages,void 0,i))o.push(c),(++a>=8||performance.now()-s>=8)&&(await new Promise(f=>setTimeout(f,0)),ae(r.signal),s=performance.now(),a=0);return ae(r.signal),Bo(e,r,o,n,i)}function Bo(e,t,r,n,o){for(const i of r)i.components=i.components.map(s=>Wr(s)?zr(s,a=>a.replace(/\{totalPages\}/g,String(r.length))):s);return n.forEach(i=>t.onWarning?.(i)),{plan:{schemaVersion:Je,...Dr(e)?{requiresRecalculation:!0}:{},pages:r},warnings:n,...o}}function Lc(e){const t=e.columns.find(i=>!i.hidden)?.field;if(!t)return{groups:0,total:0};const r=jt(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 Bc(e,t,r){Io(e);const n=yo(t[e.dataset]??[],e.tree,r),o=e.columns.filter(s=>!s.hidden).length,i=e.header===!1?0:e.headerGrid?Jr(e.headerGrid):o;return n.length*o+i+ +!!e.grandTotal*2*o}function _c(e,t,r={}){if(e.tree)return Bc(e,t,r.signal);if(e.matrix){let c=t[e.dataset]??[];e.computed?.length&&(c=Rt(c,{fields:e.computed,...r}).rows),e.rowVisibleWhen&&(c=c.filter(q(e.rowVisibleWhen)));const f=oo(c,e.matrix);return f.cells+(e.header===!1?0:f.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=jt(e).length,s=Lc(e);let a=(n*(1+2*i+s.groups)+ +!!e.grandTotal*(1+s.total))*o;if(a+=e.header===!1?0:e.headerGrid?Jr(e.headerGrid):o,e.cardinality==="record"&&n===0&&(a+=o),e.detail){const c=t[e.detail.dataset]?.length??0,f=e.detail.columns.filter(u=>!u.hidden).length;a+=(c+n*(+(e.detail.header!==!1)+ +!!e.detail.label))*f}if(!Number.isSafeInteger(a))throw new RangeError("报表单元格估算超出安全整数预算");return a}function Kc(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const{start:t,end:r,color:n}=e;return typeof t=="number"&&typeof r=="number"&&Number.isFinite(t)&&Number.isFinite(r)&&t>=0&&r<=1&&t<=r&&typeof n=="string"&&/^#[0-9a-f]{6}$/i.test(n)}function rt(e){return!!e&&typeof e=="object"}function _o(e,t,r,n,o){if(++o.nodes>1e6)return{path:t,message:"组件树超过100万个结构节点预算"};if(rt(e)){if(r>64)return{path:t,message:"组件嵌套超过64层预算"};if(n.has(e))return{path:t,message:"组件树包含循环引用"};if(!(!rt(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(!(!rt(c)||!Array.isArray(c.children)))for(const[f,u]of c.children.entries()){const d=_o(u,`${t}.grid.cells.${i}.${a}.children.${f}`,r+1,n,o);if(d)return d}}}finally{n.delete(e)}}}}function Vr(e,t="$.components",r={nodes:0}){for(const[n,o]of e.entries()){const i=_o(o,`${t}.${n}`,0,new Set,r);if(i)return i}}function Ko(e){const t={nodes:0};for(const[r,n]of e.entries()){if(!rt(n)||!Array.isArray(n.components))continue;const o=Vr(n.components,`$.pages.${r}.components`,t);if(o)return o}}function Wc(e){const t=Ko(e.pages);if(t)throw new TypeError(`${t.path}: ${t.message}`)}function zc(e,t,r){e!==void 0&&(typeof e!="string"||!e.trim()||e.length>4096)&&r.push({path:t,message:"来源范围应为不超过 4096 字符的非空字符串"})}function Wo(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 Jc(e,t,r){Wo(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:"派生结果标记应为布尔值"}),zo(e.source,`${t}.source`,r,!0),e.formula!==void 0&&typeof e.formula!="string"&&r.push({path:`${t}.formula`,message:"单元格公式应为字符串"})}function zo(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;zc(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 Vc(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 Hc(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 Uc(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return[{path:"",message:"code must be an object."}];const r=e,n=[...Vc(r),...Hc(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 Gc=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yt(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 Yc(e,t,r,n){const o=e[t];(typeof o!="number"||!Number.isFinite(o))&&n.push({path:`${r}.${t}`,message:`应为有限数字,实际 ${yt(o)}`})}function qc(e,t,r){if(e!==void 0){const n=`${t}.table`;if(!J(e))r.push({path:n,message:"逻辑表来源应为对象"});else{zo(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 Xc(e,t,r,n){if(e!==void 0)if(!J(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 f=`${t}.grid.cells.${s}.${c}`;if(!J(a)){r.push({path:f,message:"网格单元格应为对象或 null"});return}Jc(a,f,r),a.dataBar!==void 0&&!Kc(a.dataBar)&&r.push({path:`${f}.dataBar`,message:"数据条应包含 0–1 有序比例与 #RRGGBB 颜色"}),Jo(a.richParagraphs,f,r),Array.isArray(a.children)&&a.children.forEach((u,d)=>{Hr(u,`${t}.grid.cells.${s}.${c}.children.${d}`,r,n)})})})}}function wt(e,t,r,n){e!==void 0&&!t.includes(e)&&n.push({path:r,message:"未知富文本属性值"})}function ar(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 Zc(e,t,r){if(e!==void 0){if(!J(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:"富文本样式应为布尔值"});ar(e,["fontSize","fontSizePx","lineWidthPt","lineHeight","opacity"],t,r),ar(e,["letterSpacing","rotateDeg"],t,r,-1/0),typeof e.opacity=="number"&&e.opacity>1&&r.push({path:`${t}.opacity`,message:"透明度不能大于1"}),wt(e.align,["left","center","right","justify"],`${t}.align`,r),wt(e.verticalAlign,["top","middle","bottom"],`${t}.verticalAlign`,r)}}function Qc(e,t,r){if(!J(e)){r.push({path:t,message:"富文本片段应为对象"});return}wt(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:"富文本内容应为字符串"});Zc(e.style,`${t}.style`,r)}function Jo(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(!J(n)||!Array.isArray(n.segments)){r.push({path:i,message:"段落缺少 segments 数组"});return}wt(n.align,["left","center","right","justify"],`${i}.align`,r),ar(n,["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"],i,r),n.segments.forEach((s,a)=>Qc(s,`${i}.segments.${a}`,r))})}}function Vo(e,t,r,n=[]){const o=Vr([e],t);if(o){r.push(o);return}Hr(e,t,r,n)}function Hr(e,t,r,n=[]){if(!J(e)){r.push({path:t,message:"组件应为对象"});return}const o=e.kind;typeof o!="string"?r.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):Gc.has(o)||n.push({path:`${t}.kind`,message:`未知组件类型 ${yt(o)},将以兜底方式渲染`});for(const i of["leftMm","topMm","widthMm","heightMm"])Yc(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:"组件尺寸不能为负数"});qc(e.table,t,r),tf(e.code,o,t,r),ef(e,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"}),Xc(e.grid,t,r,n),Jo(e.richParagraphs,t,r)}function ef(e,t,r){if(e.chartBinding!==void 0)try{if(to(e.chartBinding),e.kind!=="chart"||["binding","imageData","grid","pageAnchor"].some(n=>e[n]!==void 0))throw new Error("绑定图表不能设置图片、网格、记录绑定或页眉页脚");if(typeof e.widthMm!="number"||e.widthMm<45||typeof e.heightMm!="number"||e.heightMm<35)throw new Error("绑定图表至少需要 45×35mm")}catch(n){r.push({path:`${t}.chartBinding`,message:n instanceof Error?n.message:String(n)})}}function tf(e,t,r,n){if(e!==void 0)for(const o of Uc(e,t))n.push({path:`${r}.code${o.path?`.${o.path}`:""}`,message:o.message})}function Ho(e,t,r){if(!J(e))return;e.binding!==void 0&&r.push({path:`${t}.binding`,message:"渲染计划不允许未解析字段绑定"}),e.chartBinding!==void 0&&r.push({path:`${t}.chartBinding`,message:"渲染计划不允许未解析图表绑定"});const n=e.grid;!J(n)||!Array.isArray(n.cells)||n.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((s,a)=>{!J(s)||!Array.isArray(s.children)||s.children.forEach((c,f)=>Ho(c,`${t}.grid.cells.${i}.${a}.children.${f}`,r))})})}function rf(e,t,r,n=[]){if(!J(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:`页宽非法: ${yt(o)}`}),(typeof i!="number"||!(i>0&&i<5e3))&&r.push({path:`${t}.pageHeightMm`,message:`页高非法: ${yt(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=Vr(s,`${t}.components`);if(a){r.push(a);return}s.forEach((c,f)=>{Hr(c,`${t}.components.${f}`,r,n),Ho(c,`${t}.components.${f}`,r)})}}function Ue(e){const t=[],r=[],n=J(e)?e.pages:void 0;if(J(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=Ko(n);if(o)return{ok:!1,errors:[...t,o],warnings:r};n.forEach((s,a)=>rf(s,`$.pages.${a}`,t,r)),n.length>2e3&&r.push({path:"$.pages",message:`页数异常大(${n.length} 页),渲染与打印耗时可能显著增加`});const i=n.reduce((s,a)=>s+(J(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 bt(e,t){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)return;const r=Object.getOwnPropertyDescriptor(e,"length")?.value;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||r>t||Reflect.ownKeys(e).length!==r+1)return;const o=[];for(let i=0;i<r;i++){const s=Object.getOwnPropertyDescriptor(e,String(i));if(!s||!Object.prototype.hasOwnProperty.call(s,"value"))return;o.push(s.value)}return o}const Ur=100,Uo=16,cr=104857;function Go(e,t,r){if(typeof e=="string"){if(e.length>cr)return;try{e=JSON.parse(e)}catch{return}}const n=bt(e,t);if(!n)return;const o=[];let i=2;for(const s of n){if(typeof s!="string"||!s.trim()||s.length>1024||r&&o.includes(s)||(i+=JSON.stringify(s).length+(o.length?1:0),i>cr))return;o.push(s)}return o}function nf(e){return Go(e,Ur,!0)}function of(e){return Go(e,Uo,!1)}function sf(e){if(typeof e=="string"){if(e.length>2048)return;try{e=JSON.parse(e)}catch{return}}const t=bt(e,2);if(!t||t.length!==2)return;const r=t[0],n=t[1];return typeof r=="number"&&typeof n=="number"&&Number.isFinite(r)&&Number.isFinite(n)&&r<=n?[r,n]:void 0}function U(e){return["multiSelect","cascader","numberRange"].includes(e.type??"")}function Dt(e,t){return e.type==="numberRange"?sf(t):e.type==="cascader"?of(t):nf(t)}function af(e,t,r=!1){const n=bt(e,1e3);if(!n)return!1;const o=[{items:n,depth:1}],i=new Set;let s=0;for(let a=0;a<o.length;a++){const{items:c,depth:f}=o[a];if(f>Uo)return!1;const u=new Set;for(const d of c){const l=cf(d,r);if(++s>1e3||!l||i.has(d)||u.has(l.value))return!1;if(i.add(d),u.add(l.value),l.children!==void 0){const m=bt(l.children,1e3);if(!t||!m)return!1;m.length&&o.push({items:m,depth:f+1})}}}return!0}function Yo(e){return e.map(t=>({value:t.value,label:t.label,...t.children?{children:Yo(t.children)}:{}}))}function cf(e,t){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))return;const r=Object.getOwnPropertyDescriptors(e);if(Object.values(r).some(i=>!Object.prototype.hasOwnProperty.call(i,"value")))return;const n=r.value?.value,o=r.label?.value;if(!(typeof n!="string"||!t&&!n.trim()||n.length>1024||typeof o!="string"||o.length>1024))return{value:n,label:o,...r.children?{children:r.children.value}:{}}}function ff(e,t){let r=e;for(const[n,o]of t.entries()){const i=r.find(s=>s.value===o);if(!i)return!1;if(r=i.children??[],n===t.length-1)return r.length===0}return!1}function uf(e,t){const r=Dt(e,t);if(!r)return[["type",e.type==="numberRange"?"请填写完整数字范围,最小值不能大于最大值":e.type==="cascader"?"请选择完整的末级路径":"请选择有效选项,不能重复或超出数量限制"]];if(e.type==="numberRange")return lf(e,r);const n=r,o=[];return e.type==="cascader"&&e.options&&!ff(e.options,n)&&o.push(["option","应为允许选项中的完整叶节点路径"]),e.type==="multiSelect"&&(e.options&&n.some(i=>!e.options.some(s=>s.value===i))&&o.push(["option","不在允许的选项中"]),e.minItems!==void 0&&n.length<e.minItems&&o.push(["minItems",`至少选择 ${e.minItems} 项`]),e.maxItems!==void 0&&n.length>e.maxItems&&o.push(["maxItems",`最多选择 ${e.maxItems} 项`])),o}function lf(e,t){const r=[];return typeof e.min=="number"&&t[0]<e.min&&r.push(["minimum",`不能小于 ${e.min}`]),typeof e.max=="number"&&t[1]>e.max&&r.push(["maximum",`不能大于 ${e.max}`]),r}function df(e){const t=[];for(const r of["minItems","maxItems"])e[r]!==void 0&&(e.type!=="multiSelect"||!Number.isSafeInteger(e[r])||e[r]<0||e[r]>Ur)&&t.push(`${r} 应为多选参数的 0–100 整数边界`);return e.minItems!==void 0&&e.maxItems!==void 0&&e.minItems>e.maxItems&&t.push("最少项目数不能大于最多项目数"),t}function mf(e){if(e.type==="numberRange"){const r={type:"number",...typeof e.min=="number"?{minimum:e.min}:{},...typeof e.max=="number"?{maximum:e.max}:{}};return{type:"array",minItems:2,maxItems:2,prefixItems:[r,{...r}],items:!1,"x-report-number-range":{ordered:!0},"x-report-wire-encoding":"json"}}const t={"x-report-wire-encoding":"json","x-report-wire-max-code-units":cr,type:"array",minItems:Math.max(e.required?1:0,e.minItems??0),maxItems:e.type==="cascader"?16:e.maxItems??Ur,items:{type:"string",minLength:1,maxLength:1024,pattern:"\\S","x-report-max-code-units":1024}};return e.type==="multiSelect"?(t.uniqueItems=!0,e.options&&(t.items={...t.items,enum:e.options.map(r=>r.value)})):t["x-report-cascader"]={leafOnly:!0,...e.options?{options:Yo(e.options)}:{}},t}function hf(e){const t=[];return e.optionsSource!==void 0&&((!["select","multiSelect","cascader"].includes(e.type??"")||typeof e.optionsSource!="string"||!/^[\w][\w.:-]{0,127}$/.test(e.optionsSource))&&t.push("远程选项来源应为选择参数的有效来源键(最多 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 gf(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 xt(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 Gr(e){return e.length===4&&/^\d{4}$/.test(e)&&e!=="0000"}function qo(e){return e.length===7&&/^\d{4}-(?:0[1-9]|1[0-2])$/.test(e)&&Gr(e.slice(0,4))}function Xo(e){const[t,r,n]=e.split("/");if(!(n!==void 0||!t||!r||!xt(t)||!xt(r)||t>r))return{start:t,end:r}}function Zo(e,t){return typeof t!="string"?!1:e==="month"?qo(t):e==="year"?Gr(t):(e==="date"||e==="dateRange")&&xt(t)}function pf(e,t){if(e==="date"&&!xt(t))return"应为有效的 YYYY-MM-DD 日期";if(e==="month"&&!qo(t))return"应为有效的 YYYY-MM 月份";if(e==="year"&&!Gr(t))return"应为 0001 至 9999 的四位年份";if(e==="dateRange"&&!Xo(t))return"应为完整且有序的 YYYY-MM-DD/YYYY-MM-DD 日期范围"}class Lt extends Error{constructor(t){super(t.map(r=>`${r.field}: ${r.message}`).join("; ")),this.issues=t,this.code="params",this.name="ReportParamValidationError"}}function Qo(e){return/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))}function ei(e,t){if(U(e))return uf(e,t);if(e.type==="number"&&!Qo(t))return[["type","应为有限数字"]];const r=pf(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(...yf(e,t)),n}function yf(e,t){const r=e.type==="dateRange"?Xo(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 wf(e){const t=[];for(const o of["min","max"]){const i=e[o];if(i===void 0)continue;Zo(e.type,i)||["number","numberRange"].includes(e.type??"")&&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,...bf(e),...df(e)]}function bf(e){const t=[];U(e)&&(e.minLength!==void 0||e.maxLength!==void 0)&&t.push("复合参数使用项目数或数值边界,而不是文本长度约束"),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 Bt(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 vf(n,t).map(a=>({code:"definition",field:i,path:`$.paramDefs.${o}`,message:a}))});return r.length?r:gf(e).map(({index:n,message:o})=>({code:"definition",field:e[n].field,path:`$.paramDefs.${n}`,message:o}))}function xf(e){const t=[];return e.type!==void 0&&!["text","number","date","month","year","dateRange","select","multiSelect","cascader","numberRange"].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&&!af(e.options,e.type==="cascader",!U(e))&&t.push("选项应为包含字符串 label/value 的数组"),[...t,...hf(e)]}function vf(e,t){if(!e||typeof e!="object"||Array.isArray(e))return["参数定义项应为对象"];const r=xf(e);return typeof e.field!="string"||!e.field.trim()||t.has(e.field)?r.push("参数名应为非空且不重复的字符串"):t.add(e.field),r.length||(r.push(...wf(e)),r.length)||e.defaultValue!==void 0&&(e.required&&(!e.defaultValue.trim()||U(e)&&Dt(e,e.defaultValue)?.length===0)?r.push("必填参数的默认值不能为空"):e.defaultValue.trim()&&r.push(...ei(e,e.defaultValue).map(([,n])=>`默认值${n}`))),r}function Mf(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 vt(e){return e==null||typeof e=="string"&&!e.trim()}function fr(e,t={}){const r=Object.create(null),n=Object.create(null),o=Bt(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};Mf(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;$f(i,s,{values:r,typedValues:n,issues:o})}return o.push(...Sf(e,r)),{ok:o.length===0,values:r,typedValues:n,issues:o}}function $f(e,t,r){const{values:n,typedValues:o,issues:i}=r,s=(u,d)=>i.push({code:u,path:`$.params.${e.field}`,field:e.field,message:d}),a=U(e)&&!vt(t)?Dt(e,t):void 0;if(vt(t)||a?.length===0){e.required&&s("required","此参数为必填项"),(typeof t=="string"||a)&&(n[e.field]=a?"":String(t)),delete o[e.field];return}if(!a&&typeof t!="string"&&!(typeof t=="number"&&Number.isFinite(t))){s("type","参数应为字符串、有限数字或当前控件的规范数组");return}const c=a?JSON.stringify(a):String(t);n[e.field]=c;const f=ei(e,c);f.forEach(([u,d])=>s(u,d)),f.length&&U(e)?delete o[e.field]:o[e.field]=a??(e.type==="number"&&Qo(c)?Number(c):c)}function Sf(e,t){return e.flatMap(r=>!vt(t[r.field])&&r.dependsOn?.some(n=>vt(t[n]))?[{code:"dependency",path:`$.params.${r.field}`,field:r.field,message:"请先填写联动依赖的上级参数"}]:[])}function An(e,t={}){const r=fr(e,t);if(!r.ok)throw new Lt(r.issues);return r.values}function Ef(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 Af(e){const t={type:e.type==="number"?"number":"string",title:e.label??e.field,...Ef(e)};return U(e)&&Object.assign(t,mf(e)),e.required&&!U(e)&&e.type!=="number"&&!t.pattern&&(t.pattern="\\S"),e.type==="select"&&e.options&&(t.enum=e.options.map(r=>r.value)),Object.assign(t,Nf(e)),Object.assign(t,kf(e)),t}function kf(e){const t={};return e.defaultValue!==void 0&&(!(e.type==="number"||U(e))||e.defaultValue.trim())&&(t.default=U(e)?Dt(e,e.defaultValue):e.type==="number"?Number(e.defaultValue):e.defaultValue),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),!U(e)&&typeof e.min=="number"&&(t.minimum=e.min),!U(e)&&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 Nf(e){return{...e.optionsSource?{"x-report-options-source":e.optionsSource}:{},...e.dependsOn?.length?{"x-report-depends-on":[...e.dependsOn]}:{}}}function Pf(e){const t=Bt(e);if(t.length)throw new Lt(t);return{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:Object.fromEntries(e.map(r=>[r.field,Af(r)])),required:e.filter(r=>r.required).map(r=>r.field),additionalProperties:!0}}function Mt(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=Bt(i);if(s.length)throw new Lt(s);return i.filter(a=>r.has(a.field)?!1:(r.add(a.field),!0))})}function Ff(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ur(e,t,r){if(e!==void 0)try{q(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function ti(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(!Ff(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{se({...o,field:o.valueField??a})}catch(c){r.push({path:s,message:c instanceof Error?c.message:String(c)})}})}function Of(e,t,r){if(e===void 0)return;const n=zs(e);for(const o of n.errors)r.push({path:t,message:o})}function Rf(e,t,r){if(e!==void 0)try{Rr(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function If(e,t,r){if(e.tree===void 0)return;const n=`${t}.tree`;try{ho(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)&&Tr(o,e.computed)}catch(o){r.push({path:n,message:o instanceof Error?o.message:String(o)})}}const Cf=1e7,Tf=new Set(["__proto__","prototype","constructor"]),jf=new Set(["text","number","boolean","date","decimal"]);function nt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function lr(e){return typeof e=="string"&&!!e.trim()&&e.length<=4096&&!Tf.has(e)}function Df(e,t,r){if(!Array.isArray(e)||!e.length||e.length>2048){r.push({path:t,message:"绑定契约应包含 1–2048 个字段"});return}const n=new Set;e.forEach((o,i)=>{const s=`${t}.${i}`;if(!nt(o)||!lr(o.field)||n.has(o.field)){r.push({path:s,message:"字段名应安全、非空且唯一"});return}n.add(o.field);for(const a of["label","semanticKey","unit"])o[a]!==void 0&&(typeof o[a]!="string"||String(o[a]).length>4096)&&r.push({path:`${s}.${a}`,message:"应为不超过 4096 位的字符串"});o.type!==void 0&&!jf.has(String(o.type))&&r.push({path:`${s}.type`,message:"未知绑定字段类型"})})}function Lf(e,t,r){if(e===void 0)return;if(!nt(e)||!nt(e.datasets)){r.push({path:t,message:"模板数据契约应声明 datasets"});return}e.source!==void 0&&!lr(e.source)&&r.push({path:`${t}.source`,message:"来源应为安全的非空业务标识"});const n=Object.entries(e.datasets);(!n.length||n.length>256)&&r.push({path:`${t}.datasets`,message:"应声明 1–256 个数据集"});for(const[o,i]of n){const s=`${t}.datasets.${o}`;!lr(o)||!nt(i)?r.push({path:s,message:"数据集应使用安全名称和字段契约"}):Df(i.fields,`${s}.fields`,r)}}class Bf extends Error{constructor(t){super(`模板校验失败:${t.slice(0,3).map(r=>`${r.path}: ${r.message}`).join("; ")}`),this.errors=t,this.name="ReportTemplateError"}}const _f=new Set(["__proto__","prototype","constructor"]),Kf=new Set(["left","center","right","justify"]),ot=2e5,Wf=64;function C(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zf(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 Jf(e,t,r,n){return _f.has(e)?(n.push({path:r,message:"模板不能包含可能污染原型的键"}),!1):t.get||t.set||!t.enumerable?(n.push({path:r,message:"模板不能包含访问器或不可枚举字段"}),!1):!0}function Vf(e){return e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)}function Hf(e,t){const r=new Set;let n=0,o=0,i=!1;const s=(a,c,f)=>{if(!i){if(++n>ot){n===ot+1&&t.push({path:c,message:"模板超过 JSON 节点安全上限"});return}if(f>Wf){t.push({path:c,message:"模板嵌套层级过深"});return}if(typeof a=="string"){o+=a.length,o>Cf&&(i=!0,t.push({path:c,message:"模板文本超过 1000 万字符的安全上限"}));return}if(!Vf(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(zf(a,c,t)){r.add(a);for(const[u,d]of Object.entries(Object.getOwnPropertyDescriptors(a))){if(Array.isArray(a)&&u==="length")continue;const l=`${c}.${u}`;if(Jf(u,d,l,t)&&s(d.value,l,f+1),n>ot||i)break}r.delete(a)}}}};s(e,"$",0)}function _(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 ce(e,t,r,n){e[t]!==void 0&&typeof e[t]!="boolean"&&n.push({path:`${r}.${t}`,message:"应为布尔值"})}function Ae(e,t,r,n=!1){e!==void 0&&!Kf.has(e)&&!(n&&e==="auto")&&r.push({path:t,message:`未知对齐方式${n?"(支持 auto)":""}`})}function oe(e,t,r){if(e!==void 0){if(!C(e)){r.push({path:t,message:"样式应为对象"});return}Ae(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"])ce(e,n,t,r);for(const n of["fontFamily","color","backgroundColor","lineColor","borderColor"])_(e,n,t,r)}}function Uf(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(!C(i)){r.push({path:a,message:"参数定义应为对象"});return}_(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","multiSelect","cascader","numberRange"].includes(i.type)&&r.push({path:`${a}.type`,message:"未知参数类型"});for(const c of["label","defaultValue","placeholder"])_(i,c,a,r);ce(i,"required",a,r);for(const c of["minLength","maxLength"]){const f=i[c];f!==void 0&&(typeof f!="number"||!Number.isSafeInteger(f)||f<0)&&r.push({path:`${a}.${c}`,message:"长度边界应为非负整数"})}Gf(i,a,r),i.options!==void 0&&(Array.isArray(i.options)?i.options.forEach((c,f)=>{const u=`${a}.options.${f}`;if(!C(c))r.push({path:u,message:"选项应为对象"});else for(const d of["label","value"])typeof c[d]!="string"&&r.push({path:`${u}.${d}`,message:"选项标签与值应为字符串(允许空白选项)"})}):r.push({path:`${a}.options`,message:"选项应为数组"}))}),r.length===o&&r.push(...Bt(e).map(i=>({path:i.path.replace("$.paramDefs",t),message:i.message})))}function Gf(e,t,r){for(const i of["min","max"]){const s=e[i];if(s===void 0)continue;Zo(e.type,s)||["number","numberRange"].includes(e.type)&&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 ri(e,t,r){if(!Array.isArray(e)||e.length===0){r.push({path:t,message:"列表至少需要一列"});return}e.every(n=>C(n)&&n.hidden===!0)&&r.push({path:t,message:"列表至少需要一列可见列"}),e.forEach((n,o)=>{const i=`${t}.${o}`;if(!C(n)){r.push({path:i,message:"列应为对象"});return}if(Wo(n,i,r),n.visual!==void 0&&!Eo(n.visual)&&r.push({path:`${i}.visual`,message:"列可视化配置无效,请检查类型、数值范围和颜色"}),ce(n,"hidden",i,r),ur(n.visibleWhen,`${i}.visibleWhen`,r),typeof n.header!="string"&&r.push({path:`${i}.header`,message:"表头应为字符串(允许空白表头)"}),_(n,"field",i,r,!0),W(n,"widthMm",i,r,Number.MIN_VALUE,!0),oe(n.style,`${i}.style`,r),oe(n.headerStyle,`${i}.headerStyle`,r),Ae(n.align,`${i}.align`,r,!0),Ae(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(!C(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 的整数"}),ce(n.format,"thousands",`${i}.format`,r),_(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(!C(s)||!C(s.when)){r.push({path:c,message:"条件格式缺少 when 对象"});return}ur(s.when,`${c}.when`,r),oe(s.style,`${c}.style`,r)}):r.push({path:`${i}.rules`,message:"条件格式应为数组"}))})}function ni(e,t,r){if(e!==void 0){if(!C(e)){r.push({path:t,message:"分组应为对象"});return}_(e,"field",t,r,!0);for(const n of["headerTemplate","subtotalLabel"])_(e,n,t,r);for(const n of["headerStyle","subtotalStyle"])oe(e[n],`${t}.${n}`,r);ce(e,"keepWithNext",t,r),ce(e,"repeatHeader",t,r),ti(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 Yf(e,t,r){if(!(e===void 0||typeof e=="boolean")){if(!C(e)){r.push({path:t,message:"合计应为布尔值或对象"});return}_(e,"label",t,r),ti(e.aggregates,`${t}.aggregates`,r),oe(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 qf(e,t,r,n){const o={kind:"rect",leftMm:0,topMm:0,widthMm:1,heightMm:1,grid:e};if(Vo(o,r,n,[]),Yr(o,r,n),!C(e)||!Array.isArray(e.cells))return;const i=e.cells,s=Array.isArray(t)?t.length:0;if(i.length*s>ot){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:"表头行高数量应与行数一致"}),Xf(i,s,r,n)}function Xf(e,t,r,n){const o=new Set;e.forEach((i,s)=>{if(!Array.isArray(i))return;let a=0;i.forEach((c,f)=>{for(;o.has(`${s}:${a}`);)a++;const u=C(c)&&typeof c.colSpan=="number"?c.colSpan:1,d=C(c)&&typeof c.rowSpan=="number"?c.rowSpan:1;(a+u>t||s+d>e.length)&&n.push({path:`${r}.cells.${s}.${f}`,message:"表头合并区域超出表头边界"});for(let l=s;l<Math.min(e.length,s+d);l++)for(let m=a;m<Math.min(t,a+u);m++)o.has(`${l}:${m}`)&&n.push({path:`${r}.cells.${s}.${f}`,message:"表头合并区域重叠"}),o.add(`${l}:${m}`);a+=u})})}function Zf(e,t,r){if(If(e,t,r),Of(e.computed,`${t}.computed`,r),Rf(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 汇总,不能同时配置普通分组、总计或主从明细"}),ur(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)=>ni(i,`${t}.groups.${s}`,r))),e.detail===void 0)return;const n=e.detail,o=`${t}.detail`;if(!C(n)){r.push({path:o,message:"主从关联应为对象"});return}for(const i of["dataset","parentKey","foreignKey"])_(n,i,o,r,!0);for(const i of["rowKey","revisionField","sourceTokenField"])_(n,i,o,r,n[i]!==void 0);_(n,"label",o,r),ce(n,"header",o,r),W(n,"rowHeightMm",o,r,Number.MIN_VALUE),ri(n.columns,`${o}.columns`,r),n.unmatched!==void 0&&n.unmatched!=="error"&&n.unmatched!=="ignore"&&r.push({path:`${o}.unmatched`,message:"未关联明细策略应为 error 或 ignore"})}function Qf(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),_(e,"dataset",t,r,!0),_(e,"title",t,r);for(const n of["rowKey","revisionField","sourceTokenField"])_(e,n,t,r,e[n]!==void 0);e.headerGrid!==void 0&&qf(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"}),ri(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"])ce(e,n,t,r);e.cardinality!==void 0&&e.cardinality!=="record"&&r.push({path:`${t}.cardinality`,message:"单记录区域类型应为 record"}),_(e,"headerBackgroundColor",t,r),Ae(e.align,`${t}.align`,r,!0),Ae(e.headerAlign,`${t}.headerAlign`,r),oe(e.headerStyle,`${t}.headerStyle`,r),Zf(e,t,r),ni(e.groupBy,`${t}.groupBy`,r),Yf(e.grandTotal,`${t}.grandTotal`,r)}function kn(e,t,r){Array.isArray(e.richParagraphs)&&e.richParagraphs.forEach((n,o)=>{if(!C(n))return;const i=`${t}.richParagraphs.${o}`;Ae(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(!C(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 f of["text","field"])_(s,f,c,r);oe(s.style,`${c}.style`,r)})})}function Yr(e,t,r){oe(e.style,`${t}.style`,r);for(const o of["text","rawText","imageData","fallbackText","nid","rkey"])_(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:"文本行应为字符串数组"}),kn(e,t,r),!C(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(!C(s)){r.push({path:c,message:"网格单元格应为对象或 null"});return}for(const f of["text","rawText","numberFormat"])_(s,f,c,r);for(const f of["colSpan","rowSpan"]){const u=s[f];u!==void 0&&(typeof u!="number"||!Number.isInteger(u)||u<=0)&&r.push({path:`${c}.${f}`,message:"跨度应为正整数"})}s.value!==void 0&&s.value!==null&&!["string","number","boolean"].includes(typeof s.value)&&r.push({path:`${c}.value`,message:"Excel 原始值应为字符串、数字、布尔值或 null"}),oe(s.style,`${c}.style`,r),kn(s,c,r),s.children!==void 0&&(Array.isArray(s.children)?s.children.forEach((f,u)=>{C(f)&&Yr(f,`${c}.children.${u}`,r)}):r.push({path:`${c}.children`,message:"嵌套组件应为数组"}))}})})}function eu(e,t,r){if(!(e.flow===void 0||!Array.isArray(e.components)))try{bo(e.components,e.flow)}catch(n){r.push({path:`${t}.flow`,message:n instanceof Error?n.message:String(n)})}}function tu(e){const t=[],r=[];return Hf(e,t),t.length?{ok:!1,errors:t,warnings:r}:(C(e)?(e.schemaVersion!==void 0&&e.schemaVersion!==Je&&t.push({path:"$.schemaVersion",message:"不支持的模板 schemaVersion"}),Uf(e.params,"$.params",t),Lf(e.dataContract,"$.dataContract",t),vo(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(!C(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}`;C(s)&&s.kind==="list"?Qf(s,c,t):(Vo(s,c,t,r),C(s)&&Yr(s,c,t))}):t.push({path:`${i}.components`,message:"组件应为数组"}),eu(n,i,t)})):t.push({path:"$",message:"模板应为对象"}),{ok:t.length===0,errors:t,warnings:r})}class ru extends Error{constructor(t){super(t.map(r=>r.message).join(";")),this.issues=t,this.name="ReportValidationError"}}function Nn(e,t,r){if(!Number.isSafeInteger(e)||e<1||e>r)throw new Error(`校验 ${t} 超出预算`);return e}function nu(e){if(e.aggregates&&e.scope!=="dataset")throw new Error("仅数据集规则允许汇总");if(e.aggregates&&(!Array.isArray(e.aggregates)||e.aggregates.length>64))throw new Error("校验汇总最多 64 项");const t=new Set;for(const r of e.aggregates??[]){if(K(r.field),t.has(r.field))throw new Error("校验汇总字段重复");t.add(r.field),r.valueField!==void 0&&K(r.valueField),r.weightField!==void 0&&K(r.weightField),Be([],{...r,field:r.valueField??r.field})}}function oi(e){if(!Array.isArray(e)||e.length>256||Object.keys(e).length!==e.length)throw new Error("校验规则最多 256 条且不允许空位");const t=new Set;return e.map(r=>{if(!r||typeof r!="object")throw new Error("校验规则应为声明式对象");if(K(r.id),t.has(r.id))throw new Error("校验规则 id 重复");if(t.add(r.id),r.field!==void 0&&K(r.field),r.dataset!==void 0&&K(r.dataset),typeof r.message!="string"||!r.message.trim()||r.message.length>2048)throw new Error("校验规则需要有界提示文案");if(r.severity!==void 0&&!["error","warning"].includes(r.severity))throw new Error("未知校验严重程度");if(r.scope!==void 0&&!["row","dataset"].includes(r.scope))throw new Error("未知校验范围");nu(r);const n={nodes:0},o=q(r.assert,n),i=r.when?q(r.when,n):void 0;return{rule:r,assert:o,when:i,checks:n.nodes}})}function Pn(e){if(e?.aborted){const t=new Error("报表校验已取消");throw t.name="AbortError",t}}function ou(e,t,r,n){const o=n&&Object.prototype.hasOwnProperty.call(t,n)?t[n]:void 0;if(o!==void 0&&typeof o!="string"&&!(typeof o=="number"&&Number.isFinite(o)))throw new Error("校验定位需要稳定的文本或数值业务键");return{ruleId:e.id,rowIndex:r,...o===void 0?{}:{rowKey:o},field:e.field,severity:e.severity??"error",message:e.message}}function iu(e,t){const r=t.computed?.length?{fields:t.computed,formula:t.formula,signal:t.signal}:void 0;if(t.tree){const o=wo(e,t.tree,{signal:t.signal,computed:r});if(o.rows.length>1e5)throw new Error("校验展开后数据最多 100000 行");return{rows:o.rows,summaryRows:o.leaves,rowKey:t.tree.idField}}const n=r?Rt(e,r).rows:e;return{rows:n,summaryRows:n,rowKey:t.rowKey}}function su(e,t){const r=new Set;e.forEach(n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("校验数据行应为对象");if(!t)return;const o=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0;if(!(typeof o=="string"&&o.trim())&&!(typeof o=="number"&&Number.isFinite(o)))throw new Error("校验定位需要稳定业务键");if(r.has(o))throw new Error("校验业务键重复");r.add(o)})}function au(e,t,r){if(!Array.isArray(e)||e.length>1e5)throw new Error("校验数据最多 100000 行");Pn(t.signal);const n=Nn(t.maxChecks??2e6,"maxChecks",1e7),o=Nn(t.maxIssues??1e3,"maxIssues",1e4);t.rowKey!==void 0&&K(t.rowKey);const i=iu(e,t),{rows:s,summaryRows:a,rowKey:c}=i;su(s,c);const f=oi(t.rules),u=f.reduce((l,m)=>l+(m.rule.scope==="dataset"?m.checks+a.length*(m.rule.aggregates?.length??0):s.length*m.checks),0);if(r.checks+=u,r.checks>n)throw new Error("整批校验超出 maxChecks 预算");const d=[];for(const l of f)(l.rule.scope==="dataset"?[Object.fromEntries((l.rule.aggregates??[]).map(h=>[h.field,Be(a,{...h,field:h.valueField??h.field})]))]:s).forEach((h,g)=>{if(Pn(t.signal),!h||typeof h!="object"||Array.isArray(h))throw new Error("校验数据行应为对象");if(!(l.when&&!l.when(h)||l.assert(h))){if(d.length>=o)throw new Error("校验问题超出 maxIssues 预算,请缩小范围");d.push(ou(l.rule,h,l.rule.scope==="dataset"?void 0:g,l.rule.scope==="dataset"?void 0:c))}});return d}function cu(e,t="allow"){if(!["allow","block"].includes(t))throw new Error("未知校验警告策略");if(!Array.isArray(e)||e.length>1e4||e.some(r=>!r||!["error","warning"].includes(r.severity)||typeof r.ruleId!="string"||!r.ruleId.trim()||typeof r.message!="string"||!r.message.trim()))throw new Error("校验问题结构无效");if(e.some(r=>r.severity==="error"||t==="block"))throw new ru(e)}function Fn(e,t,r){const n=e.get(t);if(n&&JSON.stringify(n)!==JSON.stringify(r))throw new Error("同一数据集的校验计算/业务键存在歧义,请统一绑定");e.set(t,r)}function fu(e,t,r,n=[]){oi(t.rules);const o=[],i={checks:0};for(const[a,c]of e.entries()){const f=new Map;for(const u of c.template.pages)for(const d of u.components)d.kind==="list"&&(Fn(f,d.dataset,{rowKey:d.tree?.idField??d.rowKey,computed:d.computed,tree:d.tree}),d.detail&&Fn(f,d.detail.dataset,{rowKey:d.detail.rowKey}));for(const[u,d]of f){const l=t.rules.filter(m=>!m.dataset||m.dataset===u);if(l.length&&(o.push(...au(c.datasets[u]??[],{...t,rules:l,...d,formula:n[a],signal:r},i).map(m=>({...m,dataset:u,sourceScope:c.sourceScope}))),o.length>(t.maxIssues??1e3)))throw new Error("整批候选校验问题超出 maxIssues 预算")}}const s=new Set(e.flatMap(a=>a.template.pages.flatMap(c=>c.components.flatMap(f=>f.kind==="list"?[f.dataset,...f.detail?[f.detail.dataset]:[]]:[]))));if(t.rules.some(a=>a.dataset&&!s.has(a.dataset)))throw new Error("校验目标数据集不存在");return o}function uu(e){return!e||typeof e!="object"?!1:[e.pageIndex,e.componentIndex,e.rowIndex,e.columnIndex].every(t=>Number.isInteger(t)&&t>=0)}function lu(e){return e.value!==void 0?e.value:e.rawText??e.text??null}function du(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 mu(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 hu(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 gu(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 pu(e,t,r){const n=lu(r),o=mu(r,e);return{address:{...t},cell:r,component:e,value:n,valueType:du(r,n),table:hu(e,t),source:gu(r,e,t),editable:o===void 0,readOnlyReason:o}}function ii(e){const t=new Map;return r=>{if(!uu(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 io(n.grid,n.widthMm,n.heightMm).cells){const c=s.get(a.ri)??0;s.set(a.ri,c+1);const f=n.grid.cells[a.ri]?.[c];f&&o.set(`${a.ri}:${a.ci}`,f)}t.set(n,o)}const i=o.get(`${r.rowIndex}:${r.columnIndex}`);return i?pu(n,r,i):null}}function yu(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 wu(e,t){const r=yu(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 bu(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 Re(e,t){return/[0#?@_*%[\]"\\.,/]/.test(e)?null:e.replace(/[\uE000-\uF8FF]/g,r=>t.literals[r.charCodeAt(0)-57344]??"")}function xu(e,t){const r=/^(.*?)(0)(?:\.([0#]+))?E([+-])(0+)(.*?)$/i.exec(t.text);if(!r)return null;const n=Re(r[1],t),o=Re(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,[f,u=""]=s.split("."),d=u.replace(/0+$/,"").padEnd(c,"0"),l=Number(a),m=l<0?"-":r[4]==="+"?"+":"",h=String(Math.abs(l)).padStart(r[5].length,"0");return`${e.negative?"-":""}${n}${f}${d?`.${d}`:""}E${m}${h}${o}`}function vu(e,t){const r=/^(.*?)([#,]*0[0#]*)(?:\.([0#]+))?(%)?(.*?)$/.exec(t.text);if(!r)return Re(t.text,t);const n=Re(r[1],t),o=Re(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 Mu(e,t,r){if(!t||/^(General|@)$/i.test(t))return String(e);const n=wu(e,t);if(n.pattern==="")return"";const o=bu(n.pattern),i=xu(n,o)??vu(n,o);return i!==null?i:String(e)}function $u(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 Su(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 Eu(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:Su(e,$u(t.cell.numberFormat));if(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r))throw new P("number");return r}function Au(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 ku(e,t){return e.valueType==="number"?Eu(t,e):e.valueType==="boolean"?Au(t):t===null?null:String(t)}function Nu(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 si(e,t){return t===null?"":typeof t=="boolean"?Nu(t,e):typeof t=="number"?Mu(t,e.cell.numberFormat):String(t)}function ai(e,t){if(!e.editable)throw new P("readonly");const r=ku(e,t);return{address:{...e.address},table:e.table,source:e.source,previousValue:e.value,previousText:e.cell.text??"",value:r,text:si(e,r)}}function Pu(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 ci(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 ke(e){return JSON.stringify([e.sourceScope,e.datasetId])}function On(e){return JSON.stringify([e.sourceScope,e.datasetId,e.rowKey])}function fi(e){const t=new Map,r=new Set;return e.forEach((n,o)=>{for(const i of ci(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,f)=>{if(s&&!a.has(JSON.stringify(c[s.detail.foreignKey])))return;const u=c[i.rowKey];if(typeof u!="string"&&typeof u!="number")return;const d=`${o}:${i.dataset}:${f}:${i.rowKey}`;if(r.has(d))return;r.add(d);const l=On({sourceScope:n.sourceScope,datasetId:i.dataset,rowKey:u}),m=t.get(l)??[];m.push({partIndex:o,dataset:i.dataset,rowIndex:f,row:c,binding:i}),t.set(l,m)})}}),n=>{const o=t.get(On(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 ui(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);Ds(e[i].datasets[s],r[i].datasets[s])}return r}function Fu(e,t,r){const n=[],o=new Set;return e.forEach((i,s)=>{for(const a of ci(i))t.has(ke({sourceScope:i.sourceScope,datasetId:a.dataset}))&&(i.datasets[a.dataset]??[]).forEach((c,f)=>{const u={partIndex:s,dataset:a.dataset,rowIndex:f,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}:${f}:${d}`;o.has(m)||(o.add(m),n.push({row:u,field:d,value:l}))}})}),n}function Ou(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?[ke(o.source)]:[]));return li(e,new Map([...n].map(o=>[o,r])))}function li(e,t){if(!t.size)return e;function r(i){const s=i.datasetId&&t.get(ke({...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,f=a.table&&c!==a.table.source?{...a.table,source:c}:a.table,u=a.grid?.cells.map(l=>{const m=l.map(h=>{if(!h)return h;const g=h.source?r(h.source):void 0,y=h.children?n(h.children):void 0;return g===h.source&&y===h.children?h:{...h,source:g,children:y}});return m.some((h,g)=>h!==l[g])?m:l}),d=a.grid&&u?.some((l,m)=>l!==a.grid.cells[m])?{...a.grid,cells:u}:a.grid;return f!==a.table||d!==a.grid?{...a,table:f,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 $t(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 Ru(e){const t=new Map,r=ii(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 f=r({pageIndex:o,componentIndex:s,rowIndex:a,columnIndex:c});f?.source&&f.editable&&t.set($t(f),f)}})),t}function di(e,t){if(++e.nodes>1e6||t>128)throw new P("limit")}function St(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw new P("conflict");return r.value}function qr(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 mi(e,t,r,n,o){if(di(n,o),typeof e=="function"||typeof e=="symbol")throw new P("conflict");if(e===null||typeof e!="object")return;if(qr(e),r.has(e))throw new P("conflict");r.add(e);const i=Object.keys(e),s=i.map(a=>St(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)mi(a,t,r,n,o+1);r.delete(e)}function Iu(e){const{object:t,keys:r,values:n}=e;if(qr(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(St(t,i),n[s]))}function Cu(e){const t=[];return mi(e,t,new Set,{nodes:0},0),()=>{try{return t.every(Iu)}catch{return!1}}}function Et(e,t,r,n=!1){if(di(t,r),n){if(typeof e=="function"||typeof e=="symbol")throw new P("conflict");e!==null&&typeof e=="object"&&qr(e)}if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(Date.prototype.getTime.call(e));if(Array.isArray(e)){const o=[];for(let i=0;i<e.length;i++)o[i]=Et(St(e,String(i)),t,r+1,n);return o}return Object.fromEntries(Object.keys(e).map(o=>[o,Et(St(e,o),t,r+1,n)]))}function Tu(e){return Et(e,{nodes:0},0,!0)}function ju(e){const t=Et(e,{nodes:0},0);for(const r of t)for(const n of Object.values(r.datasets))js(n);return t}async function Du(e,t,r={}){return Lo(e,t,{...r,knownTotalPages:void 0})}const Rn=new WeakMap;function qe(e){if(e?.aborted){const t=new Error("报表重算已取消");throw t.name="AbortError",t}}function hi(e,t){return e[t]===void 0?"":e[t]}function Lu(e,t){if(t.edits.length>1e4)throw new P("limit");const r=ii(e),n=new Set,o=[],i=t.edits.map(s=>{const a=r(s.address);if(!a?.source)throw new P("missing");const c=$t(s);if(n.has(c))throw new P("duplicate");if(n.add(c),Pu(a,s)||!Object.is(a.value,s.previousValue)||(a.cell.text??"")!==s.previousText)throw new P("conflict");return o.push(a),ai(a,s.value)});return{batch:{requestId:t.requestId,edits:i},contexts:o}}function Bu(e,t){const r=fi(e);return t.flatMap(n=>{if(!n.source)throw new P("missing");return r(n.source).map(o=>{if(!Object.is(hi(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 qt(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:si(n,n.value)},n}function _u(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?[ke(o.source)]:[]));return ui(e,Fu(e,n,r))}function Ku(e,t,r){const n=new Set(t.edits.map(o=>ke(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 Wu(e,t){let r=t.parts;const n=t.rebuild,o=[...t.validationFormulas??[]];let i=Cu(r),s=e,a;const c=new Map,f=new Map;function u(m){if(m!==s)throw new P("conflict");if(a)return a;if(!i?.())throw new P("conflict");return ju(r)}async function d(m,h,g,y={}){qe(y.signal),h={requestId:h.requestId,edits:h.edits.map(M=>({...M,address:{...M.address},source:M.source?{...M.source}:void 0,table:M.table?{...M.table}:void 0}))},g=g.map(M=>({...M,address:{...M.address},source:M.source?{...M.source}:void 0,table:M.table?{...M.table}:void 0,cell:{...M.cell}})),await new Promise(M=>setTimeout(M,0)),qe(y.signal);const w=u(m),p=ui(w,Bu(w,h.edits)),b=li(await n(p,y.signal),f);qe(y.signal);let x=!1,$=[],j="allow",D=!1;function v(M){return D=!0,$=Object.freeze(fu(p,M,y.signal,o).map(S=>Object.freeze({...S}))),D=!1,j=M.warningPolicy??"allow",$}return y.validation&&v(y.validation),{plan:b,get validationIssues(){return $},validate:v,commit(M){if(qe(y.signal),x||s!==m)throw new P("conflict");if(M?.conflicts?.length)throw new P("conflict");if(D)throw new Error("候选规则校验未完成,不能提交");cu($,j);const S=_u(p,h,M),I=Ou(b,h,M);if(M){const N=Ku(f,h,M);for(const[R,ye]of c)N.has(ke(ye.source))&&c.set(R,qt(ye,ye.value,M))}return g.forEach((N,R)=>c.set($t(N),qt(N,h.edits[R].value,M))),x=!0,a=S,r=void 0,i=void 0,s=I,Rn.set(s,l),s}}}const l={get plan(){return s},async prepare(m,h,g){const y=Lu(m,h);return d(m,y.batch,y.contexts,g)},async prepareHistory(m,h,g,y,w){if(!y.trim()||h.length>1e4)throw new P("limit");const p=u(m),b=fi(p),x=Ru(m),$=new Set,D=h.map(S=>{if(!S.source)throw new P("missing");const I=$t(S);if($.has(I))throw new P("duplicate");$.add(I);const N=x.get(I)??c.get(I);if(!N?.source)throw new P("missing");const R=b(N.source)[0];return qt(N,hi(R.row,N.source.field))}).map((S,I)=>({context:S,edit:ai(S,h[I][g])})).filter(({edit:S})=>!Object.is(S.previousValue,S.value)),v={requestId:y,edits:D.map(({edit:S})=>S)},M=D.map(({context:S})=>S);return{batch:v,contexts:M,prepared:await d(m,v,M,w)}}};return Rn.set(e,l),l}let zu=0;function it(){return`report-${Date.now()}-${++zu}`}function Me(e,t,r){if(!r?.aborted)try{const n=e?.({...t});n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{})}catch{}}function me(e){const t=e.taskId??it(),r=(n,o,i)=>{Me(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){Me(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 Y(e){throw new Error(`数据契约无效:${e}`)}function dr(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}function Ju(e){for(const t of["description","missingMeaning"])e[t]!==void 0&&!dr(e[t])&&Y(`${t} 应为 1–4096 位非空字符串`);e.aggregation!==void 0&&!["sum","avg","min","max","count","none"].includes(e.aggregation)&&Y("未知字段聚合语义"),e.aggregation&&!["count","none"].includes(e.aggregation)&&!["number","decimal"].includes(e.type)&&Y("数值聚合仅适用于 number/decimal"),e.format!==void 0&&Vu(e),e.calculation!==void 0&&(!e.calculation||!dr(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)&&Y("计算说明需包含说明及 1–256 个唯一依赖字段")}function Vu(e){const t=e.format;if((!t||!["number","percent","date"].includes(t.kind))&&Y("未知字段显示格式"),t.kind==="date"){(e.type!=="date"||t.pattern!==void 0&&(!dr(t.pattern)||t.pattern.length>128))&&Y("日期格式仅适用于日期,pattern 最多 128 位");return}["number","decimal"].includes(e.type)||Y("数值显示格式仅适用于 number/decimal"),t.digits!==void 0&&(!Number.isSafeInteger(t.digits)||t.digits<0||t.digits>100)&&Y("显示小数位应为 0–100 的整数"),t.kind==="number"&&t.thousands!==void 0&&typeof t.thousands!="boolean"&&Y("thousands 应为布尔值")}function Hu(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)&&Y("字段计算依赖存在循环"),r.has(s.field))continue;const a=t.get(s.field);a||Y(`计算依赖字段未声明:${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 Uu=["text","number","boolean","date","decimal"],Gu=new Set(["__proto__","prototype","constructor"]);function z(e){throw new Error(`数据契约无效:${e}`)}function gi(e){(!e||!Array.isArray(e.fields)||!e.fields.length||e.fields.length>2048)&&z("fields 应包含 1–2048 个字段");const t=new Set;for(const r of e.fields)(!r||typeof r.field!="string"||!r.field.trim()||Gu.has(r.field)||t.has(r.field))&&z("字段名应安全、非空且唯一"),t.add(r.field),Uu.includes(r.type)||z(`未知字段类型 ${r.type}`),Zu(r),Xu(r),Ju(r),Yu(r);qu(e,t),Hu(e.fields)}function Yu(e){e.enum!==void 0&&(!Array.isArray(e.enum)||!e.enum.length||e.enum.some(t=>!pi(t,e.type)))&&z("enum 应为匹配字段类型的非空标量数组")}function qu(e,t){e.rowKey!==void 0&&((typeof e.rowKey!="string"||!e.rowKey.trim()||!t.has(e.rowKey))&&z("rowKey 应为引用已声明字段的非空字符串"),e.fields.find(r=>r.field===e.rowKey)?.type==="boolean"&&z("布尔字段不能作为业务主键"))}function Xu(e){for(const t of["label","unit"])e[t]!==void 0&&typeof e[t]!="string"&&z(`${t} 应为字符串`);for(const t of["required","nullable"])e[t]!==void 0&&typeof e[t]!="boolean"&&z(`${t} 应为布尔值`);e.semanticRole!==void 0&&!["identifier","dimension","measure","date","text"].includes(e.semanticRole)&&z("未知字段语义")}function Zu(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))&&z(`${t} 无效`)}e.min!==void 0&&e.max!==void 0&&e.min>e.max&&z("min 不能超过 max"),e.minLength!==void 0&&e.maxLength!==void 0&&e.minLength>e.maxLength&&z("minLength 不能超过 maxLength"),e.type!=="number"&&(e.min!==void 0||e.max!==void 0)&&z("min/max 仅适用于 number,精确小数文本需业务校验"),["number","boolean"].includes(e.type)&&(e.minLength!==void 0||e.maxLength!==void 0)&&z("长度约束仅适用于文本类型")}function Qu(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 pi(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":typeof e!="string"?!1:t==="date"?Qu(e):t==="decimal"?e.length<=1e4&&/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e):!0}function el(e,t){if(e==null)return t.required||e===null&&t.nullable===!1?{code:"required",message:"缺少必需字段值"}:void 0;if(!pi(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"&&!tl(e,t))return{code:"range",message:"文本长度超出范围"}}function tl(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 Xt(e,t){const r=e??t;if(!Number.isInteger(r)||r<1)throw new Error("数据校验预算应为正整数");return r}function rl(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 nl(e,t,r={}){gi(t);const n=r.path??"$.rows",o=[],i=Xt(r.maxIssues,100);if(!Array.isArray(e))return{ok:!1,issues:[{code:"row",path:n,message:"数据集应为对象数组"}]};if(e.length>Xt(r.maxRows,1e5)||e.length*t.fields.length>Xt(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}ol(c,t,a,n,s,o,i)}return{ok:o.length===0,issues:o}}function ol(e,t,r,n,o,i,s){for(const a of t.fields){if(i.length>=s)return;const c=el(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=rl(e,t.rowKey,o);a&&i.push({code:"row-key",path:`${n}[${r}].${t.rowKey}`,message:a,rowIndex:r,field:t.rowKey})}}function il(e){return gi(e),{$schema:"https://json-schema.org/draft/2020-12/schema",type:"array",items:{type:"object",properties:Object.fromEntries(e.fields.map(r=>[r.field,sl(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 sl(e,t){const r=!t&&e.nullable!==!1&&!e.required;return{type:r?[In(e.type),"null"]:In(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},...al(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 al(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 In(e){return e==="text"||e==="date"||e==="decimal"?"string":e}function cl(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 fl(e){return e==="missing-source"||e==="not-applicable"||e==="not-calculable"}function Xr(e){return e.target!==void 0&&!cl(e.target)?!1:e.valueState===void 0||fl(e.valueState)&&e.target!==void 0}function yi(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]=yo(t[i]??[],{...s,maxRows:a},r.signal)}return o}function ul(e,t,r={}){return Object.values(yi(e,t,r)).reduce((n,o)=>n+o.length,0)}function ll(e,t,r){const n=il(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 Zr(e,t){return JSON.stringify([e,t])}function wi(e,t,r){return r===void 0?Zr(e,t):JSON.stringify(["shared",r])}function bi(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:bi(a.children,t,r)}:{}}));return o||i?{...n,...o?{table:o}:{},...i?{grid:{...n.grid,cells:i}}:{}}:n})}function mr(e){return It(e.maxChartComponents),{maxPages:e.maxPages,maxCells:e.maxCells,maxChartComponents:e.maxChartComponents??Or,usedPages:0,usedCells:0,usedChartComponents:0}}function dl(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 ml(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 hr(e,t){return e===void 0?void 0:e-t}function Zt(e,t){return e===void 0?t:Math.max(1,Math.min(e,t??e))}function xi(e,t,r,n,o){It(e?.maxChartComponents);const i=hr(t.maxPages,t.usedPages),s=t.maxChartComponents-t.usedChartComponents;if(i!==void 0&&i<1&&r.pages.length&&!dl(r,n))throw new Se(0,1);if(s<1&&r.pages.some(a=>a.components.some(c=>c.kind!=="list"&&c.chartBinding)))throw new Ke(s,1);return{...e,signal:o??e?.signal,maxPages:Zt(i,e?.maxPages),maxCells:Zt(hr(t.maxCells,t.usedCells),e?.maxCells),maxChartComponents:Zt(s,e?.maxChartComponents)}}function vi(e,t){const r=ml(t.plan),n=hr(e.maxCells,e.usedCells);if(n!==void 0&&r>n)throw new _e(n,r);e.usedPages+=t.plan.pages.length,e.usedCells+=r,e.usedChartComponents+=t.chartComponents}function Mi(e,t){return e instanceof Se&&t.maxPages!==void 0&&(e.limit===t.maxPages-t.usedPages||e.limit===0)?new Se(t.maxPages,t.usedPages+e.actual):e instanceof _e&&t.maxCells!==void 0?new _e(t.maxCells,t.usedCells+e.actual):e instanceof Ke&&e.limit===t.maxChartComponents-t.usedChartComponents?new Ke(t.maxChartComponents,t.usedChartComponents+e.estimated):e}class E extends Error{constructor(t,r,n){super(r),this.name="ReportSourceError",this.code=t,this.cause=n}}function _t(e){const t=new Error("报表加载已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function G(e){if(e?.aborted)throw _t(e)}function gr(e,t){return t?new Promise((r,n)=>{const o=()=>t.removeEventListener("abort",i),i=()=>{o(),n(_t(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 hl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new E("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 E("validate",`报表 ${t} 的数据集 ${r} 应为对象数组`)}async function gl(e,t,r){const{reportId:n,signal:o}=t;try{const i=await gr(e(t),o);G(o);const s=tu(i);if(!s.ok)throw new E("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?_t(o):i instanceof E?i:i instanceof Bf?new E("validate",`报表 ${n} 模板校验失败:${i.message}`,i):new E("fetch",`报表 ${n} 模板加载失败:${i instanceof Error?i.message:String(i)}`,i)}}async function pl(e,t,r,n){const o=t.signal;let i;try{if(e.load)i=await gr(e.load(t),o);else if(e.provider){const s=await gr(e.provider.query(t),o);G(o),yl(s,r),i=s.datasets,n?.(r,s)}else i=e.datasets??{}}catch(s){throw o?.aborted?_t(o):s instanceof E?s:new E("fetch",`报表 ${r} 取数失败:${s instanceof Error?s.message:String(s)}`,s)}return G(o),i}function yl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new E("validate",`报表 ${t} Provider 应返回 datasets 结果对象`);for(const r of["revision","sourceToken"])if(e[r]!==void 0&&typeof e[r]!="string")throw new E("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 E("validate",`报表 ${t} Provider diagnostics 不符合结构化诊断契约`);if(e.diagnostics?.some(r=>!Xr(r)))throw new E("validate",`报表 ${t} Provider 数据说明缺少有效的字段身份或值状态`)}function wl(e,t,r,n,o){try{t=yi(n,t,{maxRows:e.dataValidation?.maxRows,signal:o})}catch(i){throw new E("validate",`报表 ${r} 树形数据无效:${i instanceof Error?i.message:String(i)}`,i)}for(const[i,s]of Object.entries(e.dataSchema??{})){let a;try{a=nl(Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0,s,{...e.dataValidation,path:`$.datasets.${i}`})}catch(c){throw new E("config",`报表 ${r} 数据集 ${i} 字段契约配置无效`,c)}if(!a.ok)throw new E("validate",`报表 ${r} 数据集 ${i} 不符合字段契约:${a.issues[0]?.message}`,{issues:a.issues})}}async function bl(e,t,r,n,o){try{let i;try{i=Tu(e)}catch{}const s=i??e,a=xi(t.pagination,n,s.template,s.datasets,o),c=i?await Lo(s.template,s.datasets,a):Dc(s.template,s.datasets,a);return vi(n,c),{result:c,part:s}}catch(i){G(o);const s=Mi(i,n);throw new E("validate",`报表 ${r} 排版失败:${s instanceof Error?s.message:String(s)}`,s)}}function $i(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:Zr(r,n)},components:bi(a.components,o??wi(r,n),s)})}async function xl(e,t,r,n,o){const i=[],s=mr(n);for(const[f,u]of e.entries()){G(o);try{const d=await Du(u.template,u.datasets,xi(t[f]?.pagination,s,u.template,u.datasets,o));vi(s,d),$i(i,d.plan,f,r[f],u.sourceScope)}catch(d){throw Mi(d,s)}}const a={schemaVersion:Je,...e.some(f=>Dr(f.template))?{requiresRecalculation:!0}:{},pages:i},c=Ue(a);if(!c.ok)throw new E("validate",`重算渲染计划校验失败:${c.errors[0]?.message}`);return a}function vl(e,t={}){if(t.maxPages!==void 0&&(!Number.isSafeInteger(t.maxPages)||t.maxPages<1))throw new E("config","maxPages 应为正安全整数");if(t.maxCells!==void 0&&(!Number.isSafeInteger(t.maxCells)||t.maxCells<1))throw new E("config","maxCells 应为正安全整数");try{mr(t)}catch(o){throw new E("config","maxChartComponents 应为 1..1000000 的安全整数",o)}function r(o){const i=Object.prototype.hasOwnProperty.call(e,o)?e[o]:void 0;if(!i)throw new E("config",`未注册报表 ${o}`);if(i.sourceScope!==void 0&&(typeof i.sourceScope!="string"||!i.sourceScope.trim()||i.sourceScope.length>512))throw new E("config","sourceScope 应为不超过 512 字符的非空字符串");return i}return Object.assign(async({reportIds:o,params:i,signal:s,onWarning:a,onQueryResult:c,...f})=>{G(s);const u=me({...f,signal:s}),d=[...o],l={...i};if(d.length===0)throw new E("config","缺少报表 ID");const m=d.map(r),h=u.runSync("validate",()=>m.map(v=>An(v.params??(typeof v.template=="function"?[]:v.template.params)??[],l))),g=[],y=[],w=mr(t),p=[];for(const[v,M]of m.entries()){G(s);const S=d[v],I={reportId:S,params:h[v],signal:s},N=typeof M.template=="function"?await u.run("query",()=>gl(M.template,I,p),S):M.template;I.params=u.runSync("validate",()=>An(M.params??N.params??[],I.params),S);const R=await u.run("query",()=>pl(M,I,S,(zt,Zi)=>c?.(zt,Zi,v)),S);u.runSync("validate",()=>{hl(R,S),t.onDatasets?.(S,R,N),wl(M,R,S,N,s)},S),G(s);const ye=wi(v,S,M.sourceScope),{result:rn,part:Xi}=await u.run("layout",()=>bl({template:N,datasets:R,sourceScope:ye},M,S,w,s),S);y.push(Xi),$i(g,rn.plan,v,S,ye),p.push(...rn.warnings.map(zt=>`${S}: ${zt}`))}G(s);const b={schemaVersion:Je,...y.some(v=>Dr(v.template))?{requiresRecalculation:!0}:{},pages:g},x=u.runSync("validate",()=>{const v=Ue(b);if(!v.ok)throw new E("validate",`渲染计划校验失败:${v.errors.slice(0,3).map(M=>`${M.path}: ${M.message}`).join("; ")}`);return v});p.push(...x.warnings.map(v=>`${v.path}: ${v.message}`));const $=m.map(v=>({...v,pagination:{...v.pagination}})),j={maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents};try{Wu(b,{parts:y,validationFormulas:$.map(v=>v.pagination?.formula),rebuild:(v,M)=>xl(v,$,d,j,M)})}catch{p.push("来源数据无法建立本地重算口径;当前预览仅支持计划内编辑,请使用可序列化模板数据启用规则重算")}const D=a??t.onWarning??(v=>console.warn("[mach-report]",v));for(const v of p)G(s),D(v);return G(s),b},{getParamDefs:o=>Mt(e,o)})}const Qr=Object.freeze({maxRows:1e5,maxPages:1e4,maxCells:2e6,maxChartComponents:5e4,maxOutputBytes:1e8,maxPreparedBytes:64e6,maxDurationMs:12e4});class B extends Error{constructor(t,r,n){super(r),this.code=t,this.path=n,this.name="ReportRuntimeError"}}function O(e){if(!e?.aborted)return;if(e.reason instanceof B)throw e.reason;const t=new Error("报表执行已取消");throw t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function T(e,t,r){if(!Number.isFinite(r)||r<0)throw new B("budget",`${t} 的执行统计无效`,`$.budget.${t}`);const n=e[t];if(n!==void 0&&r>n)throw new B("budget",`${t} 超出预算 ${n}(实际 ${r})`,`$.budget.${t}`)}function Si(e){for(const[t,r]of Object.entries(e)){if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new B("budget",`${t} 应为正有限数字`,`$.budget.${t}`);if(t!=="maxDurationMs"&&r!==void 0&&!Number.isSafeInteger(r))throw new B("budget",`${t} 应为正安全整数`,`$.budget.${t}`);if(t==="maxDurationMs"&&r!==void 0&&r>2147483647)throw new B("budget","maxDurationMs 不能超过 2147483647",`$.budget.${t}`);if(t==="maxChartComponents"&&r!==void 0&&r>1e6)throw new B("budget","maxChartComponents 不能超过 1000000","$.budget.maxChartComponents")}}async function Ie(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 B("timeout",`报表执行超过 ${t}ms`)),t);let a;try{O(n.signal);const c=new Promise((u,d)=>{a=()=>{try{O(n.signal)}catch(l){d(l)}},n.signal.addEventListener("abort",a,{once:!0})}),f=await Promise.race([r(n.signal),c]);if(O(n.signal),t!==void 0&&Date.now()-i>t)throw new B("timeout",`报表执行超过 ${t}ms`);return f}finally{s!==void 0&&clearTimeout(s),a&&n.signal.removeEventListener("abort",a),e?.removeEventListener("abort",o)}}function Ei(e,t){he.assertOutputActive(t.signal),he.observeOutput(()=>t.onDiagnostic?.(e)),he.assertOutputActive(t.signal)}class Ml 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 Kt extends Error{constructor(t,r){super(r),this.code=t,this.name="ImageMediaError"}}const Qt={maxImageBytes:16*1024*1024,maxTotalImageBytes:32*1024*1024,maxImages:1e3,maxImagePixels:16e6,maxTotalImagePixels:64e6,maxImageDimension:16384};function te(e){throw new Kt("invalid-image-data",e)}function Ce(e){throw new Kt("image-budget-exceeded",e)}function $l(e){const t={...Qt};for(const r of Object.keys(Qt)){const n=e[r]??Qt[r];if(!Number.isSafeInteger(n)||n<=0||n>2147483647)throw new RangeError(`${r} 图片预算须为1至2147483647的整数。`);t[r]=n}return t}function Sl(e){if(e.length<33||![137,80,78,71,13,10,26,10].every((r,n)=>e[n]===r))return te("图片内容与 PNG/JPEG 类型不一致。");const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return t.getUint32(8)!==13||String.fromCharCode(...e.subarray(12,16))!=="IHDR"?te("PNG must begin with an IHDR header."):[t.getUint32(16),t.getUint32(20)]}const El=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function Al(e){if(e[0]!==255||e[1]!==216)return te("图片内容与 PNG/JPEG 类型不一致。");let t=2;for(;t+3<e.length;){if(e[t++]!==255)return te("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 te("JPEG segment exceeds its data boundary.");if(El.has(r))return n<8?te("JPEG frame header is incomplete."):[e[t+5]*256+e[t+6],e[t+3]*256+e[t+4]];t+=n}return te("JPEG has no supported dimension header.")}function kl(e,t){if(e.length>Math.ceil(t.maxImageBytes/3)*4+64)return Ce("单张图片超过字节预算。");const r=/^data:image\/(png|jpe?g);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(e);if(!r||r[2].length%4)return te("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 Ce("单张图片超过字节预算。");const i=r[1].toLowerCase()==="png"?"png":"jpeg",s=atob(n),a=new Uint8Array(o);for(let u=0;u<o;u++)a[u]=s.charCodeAt(u);const[c,f]=i==="png"?Sl(a):Al(a);return!c||!f?te("Image dimensions must be positive."):c>t.maxImageDimension||f>t.maxImageDimension||c*f>t.maxImagePixels?Ce("Image exceeds its decoded dimension or pixel budget."):{dataUrl:`data:image/${i};base64,${n}`,bytes:a,extension:i,width:c,height:f}}function Nl(e={}){const t=$l(e),r=new Map;let n=0,o=0;return i=>{const s=i.replace(/^data:image\/(png|jpe?g);base64,/i,(f,u)=>`data:image/${u.toLowerCase()==="png"?"png":"jpeg"};base64,`),a=r.get(s);if(a)return a;if(r.size>=t.maxImages)return Ce("唯一图片数量超过预算。");const c=kl(i,t);return n+c.bytes.length>t.maxTotalImageBytes||o+c.width*c.height>t.maxTotalImagePixels?Ce("图片总字节或总像素超过预算。"):(n+=c.bytes.length,o+=c.width*c.height,r.set(s,c),c)}}class en extends Error{constructor(t,r){super(t.message),this.name="OutputAssetError",this.diagnostic=t,this.cause=r}}function At(e){if(e.aborted)throw e.reason??new DOMException("The operation was aborted.","AbortError")}function Pl(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 Fl(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 Xe(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),Ei(i,{...e.options,signal:e.signal}),e.options.assetFailure!=="placeholder")throw new en(i,o)}async function Ol(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 Xe(e,r,"asset-budget-exceeded","Output exceeded the asset count budget.");let o;try{if(e.active=r,o=await he.waitForOutput(n({...r,signal:e.signal}),e.signal),At(e.signal),o.length>e.budget.maxImageBytes*4+1024)return Xe(e,r,"asset-budget-exceeded","Output exceeded the image payload byte budget.");const i=Fl(o);if(i>e.budget.maxImageBytes||e.bytes+i>e.budget.maxTotalImageBytes)return Xe(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 en||i instanceof Kt&&i.code==="image-budget-exceeded")throw i;return Xe(e,r,"asset-render-failed",`Asset renderer failed for ${t.kind}; output was not silently omitted.`,i)}return o}function Rl(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{Ei(n,{...e.options,signal:e.signal})}catch(o){t.abort(o);return}t.abort(new en(n))}async function Il(e,t,r,n,o){if(!t?.children?.length)return t;const i=[];for(const[s,a]of t.children.entries())i.push(await Ai(e,a,{...r,component:a,componentPath:[...n,s]},o));return i.some((s,a)=>s!==t.children[a])?{...t,children:i}:t}async function Ai(e,t,r,n){if(At(e.signal),n.has(t))throw new TypeError("Cyclic grid children cannot be rendered.");let o=e.cache.get(t);o||(o=Ol(e,t,r),e.cache.set(t,o));const i=await o;At(e.signal);let s=t.grid;if(s){const a=new Set(n).add(t),c=[];for(const[f,u]of s.cells.entries()){if(!u.some(l=>l?.children?.length)){c.push(u);continue}const d=[];for(const[l,m]of u.entries())d.push(m?.children?.length?await Il(e,m,r,[...r.componentPath,f,l],a):m);c.push(d.some((l,m)=>l!==u[m])?d:u)}c.some((f,u)=>f!==s.cells[u])&&(s={...s,cells:c})}return i!==t.imageData||s!==t.grid?{...t,imageData:i,grid:s}:t}function Cl(e,t,r){const n=new Set,o=i=>{if(he.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 Kt)||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 Tl(e){if(e.options.fidelity==="strict"&&e.diagnostics.length)throw new Ml(e.diagnostics)}async function Cn(e,t={}){he.assertOutputActive(t.signal),Wc(e);const r=Pl(t),n=Nl(t);if(Cl(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(()=>Rl(s,o),r.maxDurationMs);try{const c=[];for(const[f,u]of e.pages.entries()){if(f<(t.start??0)||f>(t.end??e.pages.length-1)){c.push(u);continue}const d=[];for(const[l,m]of u.components.entries())d.push(await Ai(s,m,{component:m,pageIndex:f,componentIndex:l,componentPath:[]},new Set));c.push(d.some((l,m)=>l!==u.components[m])?{...u,components:d}:u)}return At(s.signal),Tl(s),{plan:c.some((f,u)=>f!==e.pages[u])?{...e,pages:c}:e,diagnostics:s.diagnostics}}finally{clearTimeout(a),t.signal?.removeEventListener("abort",i)}}const jl=new Set([8,9,10,12,13]);function Dl(e,t){const r=Array.isArray(e),n=Object.getPrototypeOf(e);if(n!==(r?Array.prototype:Object.prototype)&&!(n===null&&!r)||Object.getOwnPropertySymbols(e).length)throw t("input","快照应为普通 JSON 对象");const o=Object.getOwnPropertyNames(e).filter(i=>!(r&&i==="length"));if(r&&(o.length!==e.length||o.some((i,s)=>i!==String(s))))throw t("input","快照数组应为连续数组");return{array:r,keys:o}}function Ll(e){if(/^[\u0020-\u007e]*$/.test(e)&&!/["\\]/.test(e))return e.length+2;let t=2;for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);if(n<32)t+=jl.has(n)?2:6;else if(n===34||n===92)t+=2;else if(n<128)t++;else if(n<2048)t+=2;else if(n>=55296&&n<=57343){const o=e.charCodeAt(r+1);n<=56319&&o>=56320&&o<=57343?(t+=4,r++):t+=6}else t+=3}return t}function ki(e,t){const r=t.maxNodes??1e6;if(![t.maxBytes,r].every(l=>Number.isSafeInteger(l)&&l>0))throw t.error("budget","快照预算应为正安全整数");let n=0,o=0;const i=new Set,s=new Map;function a(l){if(l.length+2>t.maxBytes-o)throw t.error("budget","快照超过字节预算");const m=s.get(l);if(m!==void 0)return m;const h=Ll(l);return l.length<=256&&s.size<4096&&s.set(l,h),h}function c(l){if(o+=l,o>t.maxBytes)throw t.error("budget","快照超过字节预算")}function f(l,m){if(++n>r||m>64)throw t.error("budget","快照节点或深度超过预算");if(n%1024===0&&t.check?.(),typeof l=="string")return c(a(l)),l;if(l===null||typeof l=="boolean"||typeof l=="number"&&Number.isFinite(l))return c(String(l).length),typeof l=="number"&&Object.is(l,-0)?0:l;if(!l||typeof l!="object"||i.has(l))throw t.error("input","快照应为无循环的有限 JSON 值");return u(l,m)}function u(l,m){const{array:h,keys:g}=Dl(l,t.error);i.add(l),c(2);const y=h?[]:{};let w=0;for(const p of g){const b=Object.getOwnPropertyDescriptor(l,p);if(b.get||b.set||!b.enumerable||["__proto__","constructor","prototype"].includes(p))throw t.error("input","快照不允许访问器或危险键");if(b.value===void 0&&!h)continue;c((w++?1:0)+(h?0:a(p)+1));const x=f(b.value===void 0?null:b.value,m+1);p in y?Object.defineProperty(y,p,{value:x,enumerable:!0,configurable:!0,writable:!0}):y[p]=x}return i.delete(l),y}t.check?.();const d=f(e,0);return t.check?.(),d}const Bl=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]),Q=(e,t)=>e>>>t|e<<32-t;function Ni(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=Q(i,7)^Q(i,18)^i>>>3,c=Q(s,17)^Q(s,19)^s>>>10;r[o]=r[o-16]+a+r[o-7]+c}}function Pi(e,t){let r=e[0],n=e[1],o=e[2],i=e[3],s=e[4],a=e[5],c=e[6],f=e[7];for(let u=0;u<64;u++){const d=Q(s,6)^Q(s,11)^Q(s,25),l=s&a^~s&c,m=f+d+l+Bl[u]+t[u]>>>0,h=Q(r,2)^Q(r,13)^Q(r,22),g=r&n^r&o^n&o,y=h+g>>>0;f=c,c=a,a=s,s=i+m>>>0,i=o,o=n,n=r,r=m+y>>>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]+f}function Fi(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 Oi=()=>new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ri=e=>Array.from(e,t=>t.toString(16).padStart(8,"0")).join("");function Tn(e){const t=Fi(e),r=Oi(),n=new Uint32Array(64);for(let o=0;o<t.length;o+=64)Ni(t,o,n),Pi(r,n);return Ri(r)}async function _l(e){const t=Fi(e),r=Oi(),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)),Ni(t,o,n),Pi(r,n);return Ri(r)}function Ii(e){if(typeof e!="string"||!e.trim()||e.length>31||/[\\/*?:[\]]/.test(e)||/^'|'$/.test(e))throw new TypeError("工作表名称无效");return e}function Kl(e){if(e!==void 0){if(!Array.isArray(e)||e.length>1e4)throw new RangeError("工作表名称列表最多 10000 项");return Array.from(e,Ii)}}function Wl(e){if(!Array.isArray(e)||e.length>16384)throw new TypeError("附加工作表行应为最多 16384 列的标量数组");return Array.from(e,t=>{if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&t.length<=32767&&t.split(`
6
+ `).length<=254)return t;throw new TypeError("附加工作表仅接受 Excel 范围内的文本、有限数值、布尔或空值")})}function zl(e){if(e===void 0)return;if(!Array.isArray(e)||e.length>100)throw new RangeError("附加工作表最多 100 张");let t=0,r=0,n=0;const o=new Set;return Array.from(e,i=>{if(!i)throw new TypeError("附加工作表声明无效");const a=Ii(i.name).toLowerCase();if(o.has(a))throw new TypeError(`附加工作表名称重复 ${i.name}`);if(o.add(a),!Array.isArray(i.rows)||i.rows.length>1e5)throw new RangeError("附加工作表最多 100000 行");if(n+=i.rows.length,n>1e5)throw new RangeError("附加工作表总行数超过 100000");const c=Array.from(i.rows,u=>{const d=Wl(u);if(t+=d.length,t>1e5)throw new RangeError("附加工作表总单元格超过 100000");for(const l of d)typeof l=="string"&&(r+=l.length);if(r>4e6)throw new RangeError("附加工作表文本超过 4000000 字符");return d}),f=i.columnWidths;if(f&&(!Array.isArray(f)||f.length>16384||Array.from(f).some(u=>!Number.isFinite(u)||u<=0||u>255)))throw new RangeError("附加工作表列宽应在 0 到 255 之间");return{name:i.name,rows:c,...f?{columnWidths:[...f]}:{}}})}function pr(e){return e&&{...e,sheetNames:Kl(e.sheetNames),additionalSheets:zl(e.additionalSheets)}}function tn(e,t){if(e.format!=="xlsx")return;const r=e.xlsx?.additionalSheets?.reduce((n,o)=>n+o.rows.reduce((i,s)=>i+s.length,0),0)??0;T(t,"maxCells",e.prepared.stats.cells+r)}function Te(e){if(!e)return;const t=r=>{if(!(r instanceof Uint8Array)&&!(r instanceof ArrayBuffer))throw new E("validate","字体应为 Uint8Array 或 ArrayBuffer");if(r.byteLength>32e6)throw new B("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 Ci(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 B("budget","单份字体超过 32 MB","$.pdf");return[n,Tn(i)]});return Tn(new TextEncoder().encode(JSON.stringify(r)))}const yr=new WeakMap;function Jl(e,t,r){const n=Ti(e,t,r);let o=!0;return{prepared:n,forward(){if(!o)throw new Error("报表快照只能交接一次");return o=!1,yr.set(n,t),n}}}function Ti(e,t,r){if(O(r),!Number.isSafeInteger(t)||t<=0)throw new B("budget","快照预算应为正安全整数","$.budget.maxPreparedBytes");const n=yr.get(e);if(yr.delete(e),n!==void 0&&n<=t)return e;const o=ki(e,{maxBytes:t,maxNodes:t,check:()=>O(r),error:(i,s)=>i==="budget"?new B("budget",s,"$.budget.maxPreparedBytes"):new E("validate",s)});return Di(o),o}function ji(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 Di(e){if(!ji(e.sources))throw new E("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 E("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)||!Xr(t)))throw new E("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 E("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 E("validate","准备结果字体度量标识无效")}function Vl(e){if(e.layoutPolicy!==void 0&&!["verify","preserve"].includes(e.layoutPolicy))throw new E("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=Ci(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 E("validate",n);e.prepared.diagnostics.push({code:"prepared-font-metrics",severity:"warning",message:n})}function kt(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 jn(e,t,r=Date.now()){const n=e.prepared;if(tn(e,t),e.fidelity==="strict"&&n.diagnostics.some(d=>d.code==="asset-render-failed"||d.code==="asset-budget-exceeded"))throw new E("validate","严格输出拒绝已有资产渲染降级,请修复组件后重新准备报表。");const o=e.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;O(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=me(e),c=await a.run("encode",async()=>{let d;if(e.format==="pdf"){O(e.signal);const l=await o.renderPlanToPdf(n.plan,{...e.pdf,...s?{measurer:s}:{},fidelity:e.fidelity,signal:e.signal,onProgress:(m,h)=>a.progress("encode",m,h)});d=l.bytes,n.diagnostics.push(...kt(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");O(e.signal);const m=await l(n.plan,{...e.xlsx,fidelity:e.fidelity,signal:e.signal,onProgress:(h,g)=>a.progress("encode",h,g)});d=new Uint8Array(m.buffer),n.diagnostics.push(...kt(m.diagnostics)),n.diagnostics.push(...m.warnings.map(h=>({code:"xlsx-fidelity",message:h,severity:"warning"}))),n.diagnostics.push(...(m.notes??[]).map(h=>({code:"xlsx-snapshot",message:h,severity:"info"})))}return O(e.signal),d});T(t,"maxOutputBytes",c.byteLength);const{plan:f,...u}=n;return{...u,bytes:c,format:e.format,contentType:e.format==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",stats:{...u.stats,durationMs:Date.now()-r,outputBytes:c.byteLength}}}function Dn(e){return{...e,reportIds:[...e.reportIds],...e.params?{params:{...e.params}}:{}}}function Li(e,t){if(t.length===0)throw new E("config","缺少报表 ID");return t.map(r=>{if(!Object.prototype.hasOwnProperty.call(e,r))throw new E("config",`未注册报表 ${r}`);return e[r]})}function Wt(e){return e.grid?.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+Wt(s),0)??0):0),0),0)??0}function Hl(e,t,r){return e.pages.reduce((n,o)=>n+o.components.reduce((i,s)=>s.kind!=="list"?i+Wt(s):i+_c(s,t,r),0),0)}function Ul(e,t=Object.keys(e)){return Li(e,t).map((r,n)=>{const o=t[n],i=Mt(e,[o]);return{id:o,params:JSON.parse(JSON.stringify(i)),paramsSchema:Pf(i),datasetsSchema:Object.fromEntries(Object.entries(r.dataSchema??{}).map(([s,a])=>[s,ll(typeof r.template=="function"?void 0:r.template,s,a)])),capabilities:{save:!!r.provider?.save,export:!!r.provider?.export,templates:!!r.provider?.templates}}})}function Bi(e,t){Li(e,t.reportIds);const r=fr(Mt(e,t.reportIds),t.params),n=t.reportIds.flatMap(i=>fr(Mt(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 wr(e,t){const r=Ue(e.plan);if(!r.ok)throw new E("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+Wt(c),0),0);return T(t,"maxRows",e.stats.rows),T(t,"maxPages",n),T(t,"maxCells",o),{...e,stats:{...e.stats,pages:n,cells:o}}}function Ln(e,t){const r=Bi(e.reports,t);if(!r.ok)throw new Lt(r.issues)}function _i(e){const t={...Qr,...e.budget};Si(t);const r=async(o,i)=>{const s=Date.now();let a=0,c=0;const f=[],u={},d=[],l=Object.fromEntries(Object.entries(e.reports).map(([x,$])=>[x,{...$,pagination:{...e.pagination,...$.pagination,...i?{measurer:i}:{}},dataValidation:{...$.dataValidation,maxRows:Math.min(t.maxRows??1e5,$.dataValidation?.maxRows??1/0),maxCells:Math.min(t.maxCells??2e6,$.dataValidation?.maxCells??1/0)}}])),h=await vl(l,{maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents,onDatasets:(x,$,j)=>{try{a+=ul(j,$,{maxRows:t.maxRows,signal:o.signal})}catch(D){throw D instanceof co?new B("budget",D.message,"$.budget.maxRows"):D}T(t,"maxRows",a),c+=Hl(j,$,l[x]?.pagination),T(t,"maxCells",c)}})({...o,params:o.params??{},onWarning:x=>f.push({code:"layout",message:x,severity:"warning"}),onQueryResult:(x,$,j=0)=>{const D=Zr(j,x);Object.defineProperty(u,x,{value:{revision:$.revision,sourceToken:$.sourceToken},enumerable:!0,writable:!0}),d.push({reportId:x,reportIndex:j,reportScope:D,...$.revision===void 0?{}:{revision:$.revision},...$.sourceToken===void 0?{}:{sourceToken:$.sourceToken}}),f.push(...($.diagnostics??[]).map(v=>({...v,...v.target?{target:{...v.target,reportScope:D,...v.target.tableId?{tableId:JSON.stringify([j,x,v.target.tableId])}:{}}}:{}})))}}).catch(x=>{throw x instanceof E&&x.cause instanceof Se?new B("budget",x.cause.message,"$.budget.maxPages"):x instanceof E&&x.cause instanceof _e?new B("budget",x.cause.message,"$.budget.maxCells"):x instanceof E&&x.cause instanceof Ke?new B("budget",x.cause.message,"$.budget.maxChartComponents"):x});O(o.signal);const g=e.assets?await me(o).run("assets",()=>Cn(h,{...e.assets,signal:o.signal})):{plan:h,diagnostics:[]},y=g.plan;f.push(...kt(g.diagnostics));const w=y.pages.reduce((x,$)=>x+$.components.reduce((j,D)=>j+Wt(D),0),0);T(t,"maxPages",y.pages.length),T(t,"maxCells",w);const p=Ci(o.pdf),b=e.pagination?.measurer||Object.values(e.reports).some(x=>x.pagination?.measurer);return{plan:y,diagnostics:f,revisions:u,sources:d,layout:{textMetrics:p?"font-bytes":b?"provided":"heuristic",...p?{fontFingerprint:p}:{}},stats:{rows:a,pages:y.pages.length,cells:w,durationMs:Date.now()-s}}},n=async o=>{const i=Date.now();if(o.format!=="pdf"&&o.format!=="xlsx")throw new E("config","不支持的报表导出格式");const s=o.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;O(o.signal);const a=o.pdf?.customFontFaces??(o.pdf?.customFontBytes?{regular:o.pdf.customFontBytes}:void 0),c=s&&a?s.createFontBytesMeasurer(a):void 0,f=await r(o,c);return O(o.signal),jn({...o,prepared:f},t,i)};return{describe:o=>Ul(e.reports,o),validate:o=>Bi(e.reports,o),prepare:o=>Ie(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=Dn(o),f={...c,...c.pdf?{pdf:Te(c.pdf)}:{},taskId:c.taskId??it()},u=a?g=>Me(a,g,i):void 0,d={...f,signal:i,onEvent:u};me(d).runSync("validate",()=>Ln(e,f));let l;const m=f.pdf?.customFontFaces??(f.pdf?.customFontBytes?{regular:f.pdf.customFontBytes}:void 0);if(!e.executor&&m){const g=await import("@agile-team/mach-report/pdf");O(i),l=g.createFontBytesMeasurer(m)}const h=e.executor?await e.executor.prepare(f,i,u):await r(d,l);return wr(h,t)}),exportPrepared:o=>Ie(o.signal,t.maxDurationMs,async i=>{const s=Date.now(),{signal:a,onEvent:c,...f}=o,u=wr(Ti(o.prepared,t.maxPreparedBytes??64e6,i),t),d={...f,xlsx:pr(f.xlsx),prepared:u,...f.pdf?{pdf:Te(f.pdf)}:{},taskId:f.taskId??it()};if(d.format!=="pdf"&&d.format!=="xlsx")throw new E("config","不支持的报表导出格式");const l=c?h=>Me(c,h,i):void 0;if(e.executor){if(!e.executor.exportPrepared)throw new E("config","执行器未实现 exportPrepared;请升级执行器或显式使用本地运行时");const h=await e.executor.exportPrepared(d,i,l);return T(t,"maxRows",h.stats.rows),T(t,"maxPages",h.stats.pages),T(t,"maxCells",h.stats.cells),T(t,"maxOutputBytes",h.bytes.byteLength),{...h,stats:{...h.stats,outputBytes:h.bytes.byteLength}}}const m={...d,signal:i,onEvent:l};if(me(m).runSync("validate",()=>Vl(m)),e.assets){const h=await me(m).run("assets",()=>Cn(u.plan,{...e.assets,signal:i}));u.plan=h.plan,u.diagnostics.push(...kt(h.diagnostics))}return jn(m,t,s)}),export:o=>Ie(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=Dn(o),f={...c,xlsx:pr(c.xlsx),...c.pdf?{pdf:Te(c.pdf)}:{},taskId:c.taskId??it()},u=a?m=>Me(a,m,i):void 0,d={...f,signal:i,onEvent:u};if(me(d).runSync("validate",()=>Ln(e,f)),f.format!=="pdf"&&f.format!=="xlsx")throw new E("config","不支持的报表导出格式");const l=e.executor?await e.executor.export(f,i,u):await n(d);return T(t,"maxRows",l.stats.rows),T(t,"maxPages",l.stats.pages),T(t,"maxCells",l.stats.cells),T(t,"maxOutputBytes",l.bytes.byteLength),{...l,stats:{...l.stats,outputBytes:l.bytes.byteLength}}})}}const Gl={cells:2e4,pages:20,bytes:2e6};function je(e){return e.cells>=e.limits.cells||e.pages>=e.limits.pages||e.bytes>=e.limits.bytes||e.capped}function re(e){return++e.visits>=1e5&&(e.capped=!0),!je(e)}function Z(e){return typeof e=="string"?e.length*2:0}function Bn(e,t){for(const r of e??[]){if(!re(t))return;for(const n of r.segments){if(!re(t))return;t.bytes+=Z(n.text)}}}function Ki(e,t,r){if(r>32){t.capped=!0;return}if(re(t)){t.bytes+=Z(e.text)+Z(e.rawText)+Z(e.imageData),Bn(e.richParagraphs,t);for(const n of e.lines??[]){if(!re(t))return;t.bytes+=Z(n)}for(const n of e.grid?.cells??[]){if(!re(t))return;for(const o of n){if(!re(t))return;if(o){t.cells++,t.bytes+=Z(o.text)+Z(o.rawText)+Z(o.value),Bn(o.richParagraphs,t);for(const i of o.children??[]){if(je(t))return;Ki(i,t,r+1)}}}}}}function Yl(e,t){if(e.format==="xlsx")for(const r of e.xlsx?.additionalSheets??[]){if(!re(t))return;t.bytes+=Z(r?.name);for(const n of r?.rows??[]){if(!re(t))return;for(const o of n??[]){if(!re(t))return;t.cells++,t.bytes+=Z(o)}}}}function ql(e){const t={...Gl,...e.thresholds};for(const r of Object.values(t))if(!Number.isSafeInteger(r)||r<=0)throw new RangeError("导出隔离阈值应为正安全整数");return t}function Xl(e,t){const r=ql(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(je(o))break;for(const c of a.components){if(je(o))break;Ki(c,o,0)}}Yl(e,o);let i=je(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 fe="mach-report-worker/1";class br 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 ue(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Zl(e){return ue(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 Ql(e){return Array.isArray(e)&&e.every(t=>ue(t)&&typeof t.code=="string"&&typeof t.message=="string"&&["info","warning","error"].includes(t.severity)&&Xr(t))}function ed(e){return ue(e)&&Object.values(e).every(t=>ue(t)&&(t.revision===void 0||typeof t.revision=="string")&&(t.sourceToken===void 0||typeof t.sourceToken=="string"))}function td(e){return e===void 0?!0:ue(e)&&["heuristic","provided","font-bytes"].includes(e.textMetrics)&&(e.fontFingerprint===void 0||typeof e.fontFingerprint=="string"&&/^[a-f0-9]{64}$/.test(e.fontFingerprint))}function rd(e,t){if(!ue(e)||!Zl(e.stats)||!Ql(e.diagnostics)||!ed(e.revisions)||!td(e.layout)||!ji(e.sources))return!1;if(t==="prepare")return Ue(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 Wi(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 nd(e){const t=Wi(e);if(!ue(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 zi(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(Wi)}:{},...Array.isArray(t.diagnostics)?{diagnostics:t.diagnostics.map(nd)}:{}}}function Ji(e){if(!e||typeof e!="object")return!1;const t=e;return t.protocol===fe&&typeof t.id=="string"&&(t.operation==="prepare"||t.operation==="export"||t.operation==="exportPrepared")&&!!t.input&&typeof t.input=="object"}async function Vi(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:fe,id:t.id,result:n}}catch(n){return{protocol:fe,id:t.id,error:zi(n)}}}function Hi(e){const t=e.result;return!t||!("bytes"in t)||!(t.bytes.buffer instanceof ArrayBuffer)?[]:[t.bytes.buffer]}function od(e,t){if(!ue(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 xr extends Error{constructor(t){super("报表 Worker 无法启动"),this.cause=t,this.name="ReportWorkerStartError"}}let id=0;function _n(e){const t=new Error("报表 Worker 任务已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e}),t}function sd(e,t){if(!e||typeof e!="object")return;const r=e;return r.protocol===fe&&r.id===t?r:void 0}function ad(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(_n(s.reason)):new Promise((c,f)=>{let u;try{u=e()}catch(p){f(new xr(p));return}const d=`mach-report-${Date.now()}-${++id}`;let l=!1,m=()=>{},h;const g=(p,b)=>{if(l)return;l=!0,h&&clearTimeout(h);let x;try{m()}catch($){x=$}s?.removeEventListener("abort",y),p??=x,Promise.resolve().then(()=>u.terminate()).then(()=>p===void 0?c(b):f(p),$=>f(p??$))},y=()=>g(_n(s?.reason)),w=p=>{const b=sd(p,d);if(!(!b||l)){if("type"in b&&b.type==="event"){const x="event"in b?b.event:void 0;od(x,i)?Me(a,x,s):g(new Error("报表 Worker 返回无效阶段事件"));return}b.error&&typeof b.error.name=="string"&&typeof b.error.message=="string"?g(new br(b.error)):rd(b.result,o)&&(o==="prepare"||"format"in b.result&&"format"in i&&b.result.format===i.format)?g(void 0,b.result):g(new Error("报表 Worker 返回无效响应"))}};try{if(m=u.subscribe(w,p=>g(p??new Error("报表 Worker 执行失败"))),l){m();return}if(s?.addEventListener("abort",y,{once:!0}),h=setTimeout(()=>g(new br({name:"ReportRuntimeError",code:"timeout",message:`报表 Worker 执行超过 ${r}ms`})),r),s?.aborted)y();else{const{onEvent:p,signal:b,...x}=i,$=cd(x);u.postMessage({protocol:fe,id:d,operation:o,input:x,...t.budget?{budget:t.budget}:{}},$)}}catch(p){g(p)}});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 cd(e){return e.pdf?(e.pdf=Te(e.pdf),(e.pdf?.customFontFaces?Object.values(e.pdf.customFontFaces):[e.pdf?.customFontBytes]).filter(r=>r instanceof Uint8Array).map(r=>r.buffer)):[]}function fd(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("无效的导出回退策略");Si({...e.budget,maxDurationMs:e.timeoutMs??e.budget?.maxDurationMs??12e4})}function Kn(e,t){he.observeOutput(()=>e.onDecision?.({...t,estimate:{...t.estimate}}))}function Wn(e,t){return{...e,mode:"local",reason:t,hardCancellation:!1}}function zn(e,t,r){T(r,"maxRows",e.stats.rows),T(r,"maxPages",e.stats.pages),T(r,"maxCells",e.stats.cells),T(r,"maxOutputBytes",e.bytes.byteLength),tn({...t,prepared:{...t.prepared,stats:e.stats}},r)}function ud(e,t){const r={...Qr,...t.budget},n=Jl(e.prepared,r.maxPreparedBytes,e.signal),o={...e,prepared:n.prepared,pdf:Te(e.pdf),xlsx:pr(e.xlsx)};return{request:o,forward:()=>({...o,prepared:n.forward()})}}function ld(e,t){fd(e);const r={...e,thresholds:{...e.thresholds},budget:{...Qr,...e.budget}},n=r.timeoutMs??r.budget.maxDurationMs??12e4,o=_i({reports:{},budget:{...r.budget,maxDurationMs:n}}),i=new Set;let s=!1;const a=r.mode!=="worker"&&r.fallback!=="error";async function c(f,u){const d=Date.now(),l=()=>{const w=n-(Date.now()-d);if(w<=0)throw new B("timeout",`报表执行超过 ${n}ms`);return w};let m=Xl(f,r);if(m.reason==="nonserializable-options"&&r.mode==="worker")throw new TypeError("Worker 模式不接受函数选项;请使用本地模式或可序列化配置");if(m.mode==="worker"&&!t){if(!a)throw new xr(new Error("未配置 workerFactory"));m=Wn(m,"worker-unavailable")}const h=ud(f,r),g=h.request;if(Kn(r,m),O(f.signal),m.mode==="worker")try{const w=t(l());if(!w.exportPrepared)throw new TypeError("隔离执行器缺少 exportPrepared");const{signal:p,onEvent:b,...x}=g,$=await w.exportPrepared(x,p,b);return O(p),zn($,g,r.budget),{...$,execution:m}}catch(w){if(!(w instanceof xr)||!a)throw w;O(f.signal),m=Wn(m,"worker-start-failed"),Kn(r,m)}u&&(g.prepared=wr(g.prepared,r.budget),tn(g,r.budget));const y=u?await Ie(f.signal,l(),w=>u({...g,signal:w})):await Ie(f.signal,l(),w=>o.exportPrepared({...h.forward(),signal:w}));return O(f.signal),zn(y,g,r.budget),{...y,execution:m}}return{async exportPrepared(f,u){if(s)throw new B("closed","导出执行器已释放");if(O(f.signal),i.size>=2)throw new B("queue-full","同时导出的任务已达 2 个,请等待完成后重试");const d=new AbortController;i.add(d);const l=()=>d.abort(f.signal?.reason);f.signal?.addEventListener("abort",l,{once:!0});try{return await c({...f,signal:d.signal},u)}finally{f.signal?.removeEventListener("abort",l),i.delete(d)}},cancel(){for(const f of i)f.abort()},dispose(){s=!0;for(const f of i)f.abort()}}}async function dd(e,t){try{if(e.operation!=="exportPrepared")throw new TypeError("内置编码 Worker 仅接受 exportPrepared");return await Vi(_i({reports:{},budget:e.budget}),e,t)}catch(r){return{protocol:fe,id:e.id,error:zi(r)}}}class k extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportJobError"}}function Nt(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 md(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 hd(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 ie(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(f,u){if(++o>r||u>32)throw new k("input","任务数据超过节点或深度预算");if(typeof f=="string"){if(i+=f.length,i>n)throw new k("input","任务文本超过预算");return f}if(f===null||typeof f=="boolean"||typeof f=="number"&&Number.isFinite(f))return f;if(!f||typeof f!="object"||s.has(f))throw new k("input","任务只允许无循环的有限 JSON 值");const d=Array.isArray(f),l=md(f);s.add(f);const m=Object.create(null);for(const h of l){if(i+=h.length,i>n)throw new k("input","任务文本超过预算");m[h]=a(hd(f,h),u+1)}return s.delete(f),d?Array.from({length:f.length},(h,g)=>m[String(g)]):m}const c=JSON.stringify(a(e,0));if(c.length>n)throw new k("input","任务序列化数据超过字符预算");return c}function er(e){return JSON.parse(JSON.stringify(e))}function Ui(e,t,r,n){if(Nt(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","任务类型无效");ie(e.request.payload,{maxNodes:19e3,maxCharacters:75e4}),ie(e)}function gd(e,t){if(e&&(e.createdAt!==t.createdAt||ie(e.request)!==ie(t.request)))throw new k("input","任务创建时间与请求不可变更,请使用新任务ID")}function pd(e,t){return e.status==="queued"||e.status==="running"&&(e.lease?.expiresAt??0)<=t}function yd(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 De(e){return new TextEncoder().encode(ie(e)).byteLength}function Gi(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:De(e.result);if(o>t.maxResultBytes)throw new k("capacity","任务结果超过独立预算,请保存文件引用");return Math.max(De(r)+t.controlReserveBytes,De(n))+o}function Yi(e){return e.status!=="queued"&&e.status!=="running"}function wd(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 bd(e){const t=new TextEncoder().encode(ie(e)),r=globalThis.crypto?.subtle;if(!r)return _l(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 xd(e,t){if(!Yi(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 bd(e.request),expiresAt:t}}function vd(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 Ge(e){return e?.code}function Le(e,t){return pe.createHash("sha256").update(JSON.stringify([e,t])).digest("hex")+".json"}async function vr(e){try{return await A.promises.readFile(e,"utf8")}catch(t){if(Ge(t)==="ENOENT")return;throw t}}async function Md(e,t){const r=await vr(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(Ge(o)==="ESRCH"){await A.promises.unlink(e);return}throw o}throw new k("conflict","任务目录的写入进程仍在运行")}async function $d(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 Ge(o)==="EEXIST"?new k("conflict","任务目录恢复正在进行,请稍后重试"):o}try{return await n.writeFile(JSON.stringify({pid:process.pid})),await Md(e,!0),await A.promises.open(e,"wx",384)}finally{await n.close(),await A.promises.unlink(r)}}async function Sd(e,t){const r=L.join(e,".writer-lock"),n=pe.randomUUID();let o;try{o=await A.promises.open(r,"wx",384)}catch(i){if(Ge(i)!=="EEXIST")throw i;o=await $d(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 Ed(e,t,r,n){if("tombstone"in r){const o=r.tombstone;if(vd(o),Nt(o.scope,o.id),Le(o.scope,o.id)!==t)throw new k("input","持久任务摘要身份不匹配");const i=De(o);e.tombstoneBytes+=i,e.tombstones.set(t,{value:o,bytes:i})}else{if(Ui(r,r.scope,r.id,r.revision-1),Le(r.scope,r.id)!==t)throw new k("input","持久任务文件身份不匹配");const o=Gi(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 Ad(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(L.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=L.join(e,i);if((await A.promises.stat(s)).size>4e6)throw new k("capacity","持久任务文件超过单文件预算");Ed(o,i,JSON.parse(await A.promises.readFile(s,"utf8")),t)}return o}async function kd(e,t,r){const n=L.join(e,`.pending-${pe.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,L.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(Ge(o)!=="ENOENT")throw o})}}async function Nd(e){const t=L.resolve(e.directory),r=yd(e);await A.promises.mkdir(t,{recursive:!0,mode:448});const n=await Sd(t,e.recoverDeadOwner??!1);let o;try{o=await Ad(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},f=async(l,m,h)=>{try{await kd(t,l,m)}catch(g){throw await vr(L.join(t,l))===m&&h(),g}h()};return{read:async(l,m)=>{a(),Nt(l,m),await s;const h=o.records.get(Le(l,m));return h?er(h.record):void 0},readTombstone:async(l,m)=>{a(),Nt(l,m),await s;const h=o.tombstones.get(Le(l,m));return h?er(h.value):void 0},candidates:async(l,m)=>(a(),await s,Array.from(o.records.values(),h=>h.record).filter(h=>pd(h,l)).sort((h,g)=>h.createdAt-g.createdAt).slice(0,m).map(er)),compareAndSwap:async(l,m,h,g)=>{const y=JSON.parse(ie(g));return Ui(y,l,m,h),c(async()=>{const w=Le(l,m),p=o.records.get(w);if((p?.record.revision??null)!==h||o.tombstones.has(w))return!1;gd(p?.record,y);const b=Gi(y,r),x=o.bytes-(p?.bytes??0)+b;if(x>r.maxBytes||!p&&o.records.size>=r.maxRecords)throw new k("capacity","持久任务容量已满,请清理终态任务或扩大显式预算");return await f(w,ie(y),()=>{o.records.set(w,{record:y,bytes:b}),o.bytes=x}),!0})},prune:async l=>{const m=wd(l);return c(async()=>{const h={archived:0,expired:0};for(const[g,y]of o.tombstones)y.value.expiresAt>m.now||h.expired>=m.limit||(await A.promises.unlink(L.join(t,g)),o.tombstones.delete(g),o.tombstoneBytes-=y.bytes,h.expired++);for(const[g,y]of o.records){if(!Yi(y.record)||y.record.updatedAt>m.terminalBefore||h.archived+h.expired>=m.limit)continue;const w=await xd(y.record,m.now+m.tombstoneRetentionMs),p=De(w);if(o.tombstones.size>=r.maxTombstones||o.tombstoneBytes+p>r.maxTombstoneBytes)break;await f(g,ie({tombstone:w}),()=>{o.tombstones.set(g,{value:w,bytes:p}),o.tombstoneBytes+=p,o.records.delete(g),o.bytes-=y.bytes}),h.archived++}if(h.expired){const g=await A.promises.open(t,"r");try{await g.sync()}finally{await g.close()}}return h})},close:async()=>{if(i)return;i=!0,await s,await n.handle.close();const l=await vr(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 Pd(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 le(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 X(e,t,r){return ki(e,{maxBytes:t,maxNodes:t,check:()=>O(r),error:(n,o)=>new F(n==="budget"?"capacity":"input",o)})}function ve(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}function Jn(e){if(!e||e.schemaVersion!==Je||"pages"in e||e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean")throw new F("input","文档计划头应使用当前版本,且不得携带 pages")}function Ze(e,t){e.bytes=0;for(let r=0;r<8;r++){const n=t+ve(e);if(n===e.bytes)return;e.bytes=n}throw new F("capacity","文档容量统计无效")}function Fd(e,t,r=[]){const n=new Map;let o=0,i=Promise.resolve();for(const u of r){const d=le(u.scope,u.id,u.version);if(Jn(u.plan),n.has(d)||!Number.isSafeInteger(u.bytes)||u.bytes<0||!Number.isSafeInteger(u.pageCount)||u.pageCount<0||u.pageCount>t.maxPages||!["building","complete","failed"].includes(u.state)||u.revision!==u.pageCount+(u.state==="building"?0:1))throw new F("input","文档清单无效");n.set(d,X(u,t.maxManifestBytes)),o+=u.bytes}function s(u,d){if(o-(d?.bytes??0)+u.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=u=>{const d=i.then(u);return i=d.then(()=>{},()=>{}),d},c=(u,d,l,m)=>{const h=n.get(le(u,d,l));if(!h)throw new F("missing","文档不存在");if(h.version!==l||m!==void 0&&h.revision!==m)throw new F("conflict","文档已变化,请重新读取清单");return h},f=async(u,d,l)=>{const m=X(u,t.maxManifestBytes);return s(m,d),await e.write(m,l),n.set(le(u.scope,u.id),m),o+=u.bytes-(d?.bytes??0),X(m,t.maxManifestBytes)};return{create:(u,d)=>{const l=X(u,t.maxManifestBytes,d),m=le(l.scope,l.id,l.version);return Jn(l.plan),a(async()=>{if(O(d),n.has(m))throw new F("conflict","文档已存在,不可覆盖");const h={...l,revision:0,state:"building",pageCount:0,bytes:0};return Ze(h,0),f(h)})},append:(u,d,l,m,h,g)=>{const y=X(h,t.maxPageBytes,g),w=Ue({pages:[y]});if(!w.ok)throw new F("input",w.errors[0].message);return a(async()=>{O(g);const p=c(u,d,l,m);if(p.state!=="building")throw new F("conflict","已完成文档不可追加");if(p.pageCount>=t.maxPages)throw new F("capacity","文档页数超过预算");const b={...p,revision:m+1,pageCount:p.pageCount+1};return Ze(b,p.bytes-ve(p)+ve(y)),f(b,p,{index:p.pageCount,value:y})})},complete:(u,d,l,m,h,g)=>{const y=h===void 0?void 0:X(h,t.maxManifestBytes,g);return y&&Di({...y}),a(async()=>{O(g);const w=c(u,d,l,m);if(w.state!=="building")throw new F("conflict","文档已完成");if(y&&y.stats.pages!==w.pageCount)throw new F("input","准备结果页数与文档页数不一致");const p={...w,revision:m+1,state:"complete",...y?{metadata:y}:{}};return Ze(p,w.bytes-ve(w)),f(p,w)})},fail:(u,d,l,m,h)=>{const g=X(h,4096);if(!g||!["cancelled","generation"].includes(g.code)||typeof g.message!="string"||!g.message.trim()||g.message.length>1024)throw new F("input","文档失败状态无效");return a(async()=>{const y=c(u,d,l,m);if(y.state!=="building")throw new F("conflict","终态文档不可变更");const w={...y,state:"failed",revision:m+1,failure:g};return Ze(w,y.bytes-ve(y)),f(w,y)})},read:async(u,d,l)=>{O(l);const m=le(u,d);await i,O(l);const h=n.get(m);return h?X(h,t.maxManifestBytes):void 0},readPage:(u,d,l,m,h)=>a(async()=>{O(h);const g=c(u,d,l);if(!Number.isSafeInteger(m)||m<0)throw new F("input","页索引应为非负安全整数");if(m>=g.pageCount)return;const y=await e.readPage(u,d,m);if(O(h),!y)throw new F("missing","已提交的文档页缺失");return X(y,t.maxPageBytes,h)}),remove:(u,d,l,m)=>a(async()=>{O(m);const h=le(u,d,l),g=n.get(h);return g?(c(u,d,l),await e.remove(g),n.delete(h),o-=g.bytes,!0):!1})}}const Mr=e=>e?.code,st=(e,t)=>pe.createHash("sha256").update(le(e,t)).digest("hex");async function $r(e,t){const r=await A.promises.lstat(e);if(!r.isFile()||r.size>t)throw new F("capacity","文档文件类型或大小无效");return X(JSON.parse(await A.promises.readFile(e,"utf8")),t)}async function Vn(e,t){const r=`${e}.pending-${pe.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(Mr(n)!=="ENOENT")throw n})}}async function Od(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=L.join(e,o);if(!(await A.promises.lstat(i)).isDirectory())throw new F("input","文档目录不允许符号链接");const a=await $r(L.join(i,"manifest.json"),t.maxManifestBytes);if(st(a.scope,a.id)!==o||!Number.isSafeInteger(a.pageCount)||a.pageCount<0||a.pageCount>t.maxPages)throw new F("input","文档清单身份或页数无效");let c=ve(a);for(let f=0;f<a.pageCount;f++){const u=await A.promises.lstat(L.join(i,`${f}.json`));if(!u.isFile()||u.size>t.maxPageBytes)throw new F("capacity","文档页文件类型或大小无效");c+=u.size}if(c!==a.bytes)throw new F("input","文档字节数与已提交页不一致");for(const f of await A.promises.readdir(i)){const u=/^(\d+)\.json$/.exec(f);(u&&Number(u[1])>=a.pageCount||/\.pending-[a-f0-9-]{36}$/.test(f))&&await A.promises.unlink(L.join(i,f))}n.push(a)}return n}async function Rd(e){const t=Pd(e),r=L.resolve(e.directory);await A.promises.mkdir(r,{recursive:!0,mode:448});const n=L.join(r,".document-writer-lock"),o=pe.randomUUID();let i;try{i=await A.promises.open(n,"wx",384)}catch(l){throw Mr(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 $r(n,1024)).token===o}catch(l){if(Mr(l)==="ENOENT")return!1;throw l}},a=async()=>{if(!await s())throw new F("closed","文档存储写入锁已失效")};let c=Promise.resolve(),f=!1;const u=l=>{if(f)return Promise.reject(new F("closed","文档存储已关闭"));const m=l();return c=Promise.allSettled([c,m]).then(()=>{}),m};let d;try{const l=await Od(r,t);d=Fd({write:async(m,h)=>{await a();const g=L.join(r,st(m.scope,m.id));await A.promises.mkdir(g,{recursive:!0,mode:448}),h&&await Vn(L.join(g,`${h.index}.json`),h.value);try{await Vn(L.join(g,"manifest.json"),m)}catch(y){throw h?await A.promises.unlink(L.join(g,`${h.index}.json`)):m.revision===0&&await A.promises.rm(g,{recursive:!0}),y}},readPage:async(m,h,g)=>(await a(),$r(L.join(r,st(m,h),`${g}.json`),t.maxPageBytes)),remove:async m=>{await a(),await A.promises.rm(L.join(r,st(m.scope,m.id)),{recursive:!0})}},t,l)}catch(l){throw await i.close(),await A.promises.unlink(n),l}return{create:(...l)=>u(()=>d.create(...l)),append:(...l)=>u(()=>d.append(...l)),complete:(...l)=>u(()=>d.complete(...l)),fail:(...l)=>u(()=>d.fail(...l)),read:(...l)=>u(()=>d.read(...l)),readPage:(...l)=>u(()=>d.readPage(...l)),remove:(...l)=>u(()=>d.remove(...l)),close:async()=>{f||(f=!0,await c,await i.close(),await s()&&await A.promises.unlink(n))}}}function qi(e){const t=e.filename??e.workerUrl;if(!t||e.filename&&e.workerUrl)throw new TypeError("请且仅请指定 filename 或 workerUrl");return ad(()=>{const r=new Ne.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 Id(e){const t=Ne.parentPort;if(!t)throw new Error("serveNodeReportWorker 只能在 worker_threads 中调用");const r=n=>{Ji(n)&&Vi(e,n,o=>t.postMessage({protocol:fe,id:n.id,type:"event",event:o})).then(o=>t.postMessage(o,Hi(o)))};return t.on("message",r),()=>t.off("message",r)}function Cd(e){return pe.createHash("sha256").update(e).digest("hex")}function Td(e={}){const t={timeoutMs:e.timeoutMs??e.budget?.maxDurationMs,budget:{...e.budget}};return ld(e,r=>qi({filename:typeof __filename=="string"?__filename:new URL(typeof document>"u"?require("url").pathToFileURL(__filename).href:Jt&&Jt.tagName.toUpperCase()==="SCRIPT"&&Jt.src||new URL("server-node.cjs",document.baseURI).href),workerOptions:{workerData:{machReportEncoding:"prepared-v1"}},...t,timeoutMs:r}))}if(Ne.parentPort&&Ne.workerData?.machReportEncoding==="prepared-v1"){const e=Ne.parentPort;e.on("message",t=>{Ji(t)&&dd(t,r=>e.postMessage({protocol:fe,id:t.id,type:"event",event:r})).then(r=>e.postMessage(r,Hi(r)))})}exports.ReportWorkerError=br;exports.createNodeAutoReportExporter=Td;exports.createNodeReportExecutor=qi;exports.openFileReportDocumentStore=Rd;exports.openFileReportJobStore=Nd;exports.reportArtifactSha256=Cd;exports.serveNodeReportWorker=Id;