@agile-team/mach-report 2.23.1 → 2.25.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.
- package/README.md +10 -4
- package/dist/{ExcelBindingWizard-BrTmdo7f.cjs → ExcelBindingWizard-BgJG-T6k.cjs} +1 -1
- package/dist/{ExcelBindingWizard-CcDMLO8Q.js → ExcelBindingWizard-NQ_v396s.js} +3 -3
- package/dist/ParamEditor-DEP38mBp.cjs +1 -0
- package/dist/ParamEditor-Z-3yodp5.js +750 -0
- package/dist/{ReportBatchPanel-CHxBtG9R.cjs → ReportBatchPanel-D33LjMrA.cjs} +1 -1
- package/dist/{ReportBatchPanel-CJB67WNd.js → ReportBatchPanel-DG8FV-5X.js} +2 -2
- package/dist/{ReportLabelStudio-Tplc1TLJ.js → ReportLabelStudio-BZp23_hA.js} +68 -68
- package/dist/ReportLabelStudio-Bz-xAayk.cjs +1 -0
- package/dist/ReportParamPanel-B27IGJjk.cjs +1 -0
- package/dist/{ReportParamPanel-GI43aGa0.js → ReportParamPanel-DGXzBzl2.js} +328 -298
- package/dist/ReportPreview-CilFAS9U.js +7170 -0
- package/dist/ReportPreview-dOOzPts2.cjs +6 -0
- package/dist/{ReportTemplateLibrary-KqX4E2sN.js → ReportTemplateLibrary-DpSGgvFa.js} +28 -28
- package/dist/{ReportTemplateLibrary-BFQIX0sg.cjs → ReportTemplateLibrary-uG1gENaW.cjs} +1 -1
- package/dist/{RuleEditor-OPX1awrH.js → RuleEditor-BONALh1Q.js} +846 -835
- package/dist/RuleEditor-bLXiRcxL.cjs +1 -0
- package/dist/{TemplateOutlinePanel-CVYKVLv_.cjs → TemplateOutlinePanel-C3nfHuaR.cjs} +1 -1
- package/dist/{TemplateOutlinePanel-DQS-eOs6.js → TemplateOutlinePanel-JGBKeF3e.js} +10 -10
- package/dist/{TemplateReusePanel-CY6O93Zk.cjs → TemplateReusePanel-BKhgp6kg.cjs} +1 -1
- package/dist/{TemplateReusePanel-DKXiFTyB.js → TemplateReusePanel-DXQUO6nQ.js} +2 -2
- package/dist/TemplateReviewPanel-5RWFUUEf.cjs +1 -0
- package/dist/TemplateReviewPanel-DhL7Hapy.js +602 -0
- package/dist/analytics.d.cts +1 -1
- package/dist/analytics.d.ts +1 -1
- package/dist/artifact-integrity.json +98 -98
- package/dist/assets-BYdpkTIt.cjs +1 -0
- package/dist/assets-C4MIvzQ4.js +137 -0
- package/dist/auto-D-eDZa_V.cjs +1 -0
- package/dist/{auto-BB99S802.js → auto-umW_ozwr.js} +10 -10
- package/dist/capabilities-CN_kSVjO.js +121 -0
- package/dist/capabilities-D4nfhcvB.cjs +1 -0
- package/dist/cell-style-B6Qffrx8.js +37 -0
- package/dist/cell-style-y_uh1pZp.cjs +1 -0
- package/dist/{data-bar-IkI6VvMQ.js → data-bar-Bfh54sT4.js} +1 -1
- package/dist/data-bar-DzceAVeR.cjs +1 -0
- package/dist/designer-CCyj5WYS.js +7595 -0
- package/dist/designer-Cj7fn4Hh.cjs +2 -0
- package/dist/designer.cjs +1 -1
- package/dist/designer.d.cts +143 -10
- package/dist/designer.d.ts +143 -10
- package/dist/designer.js +5 -5
- package/dist/diagnostic-collector-gB07PHy2.js +392 -0
- package/dist/diagnostic-collector-wASg6Fzs.cjs +1 -0
- package/dist/dom-CXWMmwh-.cjs +1 -0
- package/dist/{dom-JWrchIre.js → dom-DxdCMLzs.js} +185 -185
- package/dist/{encoding-CEd-dq9A.js → encoding-CEkBtlUP.js} +2 -2
- package/dist/{encoding-7lquyj0w.cjs → encoding-Cipno7dq.cjs} +1 -1
- package/dist/{font-loader-CNWXomuV.js → font-loader-D4NLIKJL.js} +1 -1
- package/dist/{font-loader-D8pI87fL.cjs → font-loader-p_SyTvqt.cjs} +1 -1
- package/dist/{grid-strokes-EoY66L2f.js → grid-strokes-DkZEZvcI.js} +1 -1
- package/dist/grid-strokes-RFMR91jn.cjs +1 -0
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +48 -9
- package/dist/index.d.ts +48 -9
- package/dist/index.js +137 -136
- package/dist/json-snapshot-DQdkA_At.cjs +2 -0
- package/dist/{json-snapshot-BRnzKudk.js → json-snapshot-x0JpllWL.js} +919 -791
- package/dist/{pdf-DpMkW72B.cjs → pdf-C060D5UY.cjs} +31 -31
- package/dist/{pdf-CJToa81Z.js → pdf-DU8HelKd.js} +2499 -2492
- package/dist/pdf.cjs +1 -1
- package/dist/pdf.d.cts +18 -0
- package/dist/pdf.d.ts +18 -0
- package/dist/pdf.js +2 -2
- package/dist/{plugin-BWTp-X7b.cjs → plugin-B_k23hut.cjs} +1 -1
- package/dist/{plugin-_BkUVc2z.js → plugin-CttO46hc.js} +1 -1
- package/dist/{prefill-CWGdnqQd.js → prefill-BkF9Fw_p.js} +13 -13
- package/dist/prefill-BvkuwooY.cjs +1 -0
- package/dist/prepared-CSywIEAZ.cjs +1 -0
- package/dist/prepared-Cyuh61fJ.js +128 -0
- package/dist/protocol-BwbJNVZl.cjs +1 -0
- package/dist/protocol-DwtxjXzO.js +96 -0
- package/dist/record-bindings-B7djSjNs.cjs +1 -0
- package/dist/{record-bindings-DatJZv_e.js → record-bindings-Cv7lFiof.js} +47 -47
- package/dist/{region-binding-workflow-l7NGfagJ.cjs → region-binding-workflow-COD8nISZ.cjs} +1 -1
- package/dist/{region-binding-workflow-DjrXuR1q.js → region-binding-workflow-D8I4QWRh.js} +2 -2
- package/dist/report-encoding-worker.cjs +1 -1
- package/dist/report-encoding-worker.js +1 -1
- package/dist/{rich-text-layout-Ciwa6D2o.js → rich-text-layout-Ch_N0Ubu.js} +1 -1
- package/dist/rich-text-layout-yJGuThtC.cjs +3 -0
- package/dist/runtime-BE30icyB.js +227 -0
- package/dist/runtime-DRSuy_SQ.cjs +1 -0
- package/dist/sbom.cdx.json +1 -1
- package/dist/server/node.d.cts +55 -7
- package/dist/server/node.d.ts +55 -7
- package/dist/server-node.cjs +5 -5
- package/dist/server-node.js +2742 -2417
- package/dist/server.cjs +1 -1
- package/dist/server.d.cts +51 -16
- package/dist/server.d.ts +51 -16
- package/dist/server.js +8 -8
- package/dist/style.css +1 -1
- package/dist/{template-catalog-DtrtT1FY.cjs → template-catalog-C0riwrx7.cjs} +1 -1
- package/dist/{template-catalog-CRuZL3pi.js → template-catalog-D_gl93va.js} +3 -3
- package/dist/template-fragments-CgzPdFKB.cjs +1 -0
- package/dist/{template-fragments-CPpGpQoz.js → template-fragments-D94ZZmPc.js} +2 -2
- package/dist/template-registry-BMScUmM4.cjs +1 -0
- package/dist/{template-registry-O0hNIOfB.js → template-registry-DZOtRY7t.js} +19 -19
- package/dist/{textwrap-D4ZksyMK.js → textwrap-BywMBMXM.js} +1 -1
- package/dist/textwrap-LhJkHWb1.cjs +4 -0
- package/dist/vue/async.d.cts +101 -22
- package/dist/vue/async.d.ts +101 -22
- package/dist/vue/index.d.cts +133 -34
- package/dist/vue/index.d.ts +133 -34
- package/dist/vue-async.cjs +1 -1
- package/dist/vue-async.js +3 -3
- package/dist/vue.cjs +1 -1
- package/dist/vue.js +192 -162
- package/dist/{workbook-session-C6-SrnCT.cjs → workbook-session-DR2j6Hxm.cjs} +3 -3
- package/dist/{workbook-session-C9ZmCBwY.js → workbook-session-SzfILBJJ.js} +106 -107
- package/dist/worker.cjs +1 -1
- package/dist/worker.d.cts +55 -7
- package/dist/worker.d.ts +55 -7
- package/dist/worker.js +4 -4
- package/dist/xlsx/node.d.cts +30 -1
- package/dist/xlsx/node.d.ts +30 -1
- package/dist/xlsx-node.cjs +42 -42
- package/dist/xlsx-node.js +3908 -3889
- package/dist/xlsx.cjs +4 -4
- package/dist/xlsx.d.cts +20 -3
- package/dist/xlsx.d.ts +20 -3
- package/dist/xlsx.js +302 -295
- package/package.json +1 -1
- package/dist/ParamEditor-BGjovFUe.js +0 -737
- package/dist/ParamEditor-CeNp4_zQ.cjs +0 -1
- package/dist/ReportLabelStudio-g8PkqJWn.cjs +0 -1
- package/dist/ReportParamPanel-C7fZTllk.cjs +0 -1
- package/dist/ReportPreview-BoGBGyRr.cjs +0 -6
- package/dist/ReportPreview-QLONCyci.js +0 -6257
- package/dist/RuleEditor-BZUP9yvL.cjs +0 -1
- package/dist/TemplateReviewPanel-DbeNC8Ms.cjs +0 -1
- package/dist/TemplateReviewPanel-Dijwm9YE.js +0 -593
- package/dist/assets-D2gHc4Mz.cjs +0 -1
- package/dist/assets-T_gDeFaz.js +0 -132
- package/dist/auto-BrPWo7Xm.cjs +0 -1
- package/dist/capabilities-DiBj4Qgl.cjs +0 -1
- package/dist/capabilities-pg7j7VLT.js +0 -106
- package/dist/data-bar-CeZuFmYl.cjs +0 -1
- package/dist/designer-BZoVWTgl.js +0 -7172
- package/dist/designer-zS2uKJmY.cjs +0 -2
- package/dist/dom-ChE5D-L-.cjs +0 -1
- package/dist/grid-strokes-Be24LGuV.cjs +0 -1
- package/dist/json-snapshot-DNiIbpOr.cjs +0 -2
- package/dist/prefill-PaAy6wLk.cjs +0 -1
- package/dist/prepared-CJy_qk7d.js +0 -94
- package/dist/prepared-D0yCSxSO.cjs +0 -1
- package/dist/progress-BXzlVbIp.js +0 -29
- package/dist/progress-ByiOxUD3.js +0 -250
- package/dist/progress-DJBd9Rb9.cjs +0 -1
- package/dist/progress-WomPRP3B.cjs +0 -1
- package/dist/protocol-BG16rz6D.js +0 -90
- package/dist/protocol-wzhl1Fim.cjs +0 -1
- package/dist/record-bindings-MBxbeBsi.cjs +0 -1
- package/dist/rich-text-layout-DK7A_a5r.cjs +0 -3
- package/dist/runtime-DYMOS_gz.cjs +0 -1
- package/dist/runtime-PiCax9zQ.js +0 -171
- package/dist/template-fragments-GVjpew_q.cjs +0 -1
- package/dist/template-registry-DI59PXVK.cjs +0 -1
- package/dist/textwrap-DEHqAjKZ.cjs +0 -4
package/dist/server-node.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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]/,ss=/[ \n\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 as=[.54,.26,.95,.59,.67,.3];function cs(e){const t=e.charCodeAt(0);return t<128?as[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,a=0;for(const c of e)s+=cs(c),a++;return n&&(s*=1.04),(s*r+o*Math.max(0,a-1))*i}};function fs(e,t,r){if(!ss.test(e))return[{text:e,widthMm:r.measureMm(e,t),cjk:!1}];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 Es=Object.create;var wn=Object.defineProperty;var As=Object.getOwnPropertyDescriptor;var ks=Object.getOwnPropertyNames;var Ps=Object.getPrototypeOf,Ns=Object.prototype.hasOwnProperty;var Os=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ks(t))!Ns.call(e,o)&&o!==r&&wn(e,o,{get:()=>t[o],enumerable:!(n=As(t,o))||n.enumerable});return e};var at=(e,t,r)=>(r=e!=null?Es(Ps(e)):{},Os(t||!e||!e.__esModule?wn(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ue=require("./cell-style-y_uh1pZp.cjs"),Le=require("node:worker_threads"),be=require("node:crypto"),E=require("node:fs"),D=require("node:path");var Qt=typeof document<"u"?document.currentScript:null;const Ye=200,ho=1e3,go=128,De="other",po=new Set(["__proto__","prototype","constructor"]),Is={"invalid-image-data":!0,"image-budget-exceeded":!0,"component-render-failed":!0,"unsupported-text":!0,"output-degraded":!0,"missing-image":!0,"unsupported-component":!0,"unsupported-image-format":!0,"unsupported-style":!0,"rich-text-flattened":!0,"nested-components-omitted":!0,"async-image-required":!0,"image-decode-failed":!0,"asset-render-failed":!0,"asset-budget-exceeded":!0},Dr=new Set([...Object.keys(Is),"pdf-page","pdf-font","pdf-fidelity","xlsx-fidelity","xlsx-snapshot","prepared-layout-preserved","prepared-font-metrics","layout"]);function Fs(e){if(e===void 0)return 1/0;if(!Number.isInteger(e)||e<0||e>ho)throw new RangeError("diagnosticLimit must be an integer between 0 and 1000");return e}function rt(e){const t=Fs(e),r=[],n=[],o=Object.create(null),i=new Map,s=Object.create(null);let a=0,c=0,u=0;function f(g,y){const w=g.length<=128&&!po.has(g)&&(o[g]!==void 0||u<go||Dr.has(g))?g:De;return o[w]===void 0&&u++,o[w]=(o[w]??0)+y,w}function d(g,y){if(t===1/0){r.push(g);return}const w=`${lr(g)?"e":"o"}:${y}`;if(r.length<t){r.push(g),n.push(w),i.set(w,(i.get(w)??0)+1);return}if(!(!t||i.has(w)))for(let p=r.length-1;p>=0;p--){const x=n[p],b=i.get(x)??0;if(!(b<=1)){r[p]=g,n[p]=w,i.set(x,b-1),i.set(w,1);return}}}function l(g){c++;const y=f(g.code,1);lr(g)&&(a++,s[y]=(s[y]??0)+1),d(g,y)}function m(g){c+=g.total;const y=new Map;for(const[p,x]of Object.entries(g.counts)){const b=f(p,x),S=g.explanations?.counts[p]??0;y.set(p,b),S&&(a+=S,s[b]=(s[b]??0)+S)}if(t===1/0){for(const p of g.entries)r.push(p);return}const w=new Map;for(const p of g.entries){const x=wo(g,p,w);x!==void 0&&d(p,y.get(x))}}function h(){return{total:c,counts:{...o},entries:r.slice(),omitted:c-r.length,...a?{explanations:{total:a,counts:{...s}}}:{}}}return{entries:r,push:l,merge:m,snapshot:h,get total(){return c}}}function yo(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;if(!Number.isSafeInteger(t.total)||t.total<0||!Number.isSafeInteger(t.omitted)||t.omitted<0||!Array.isArray(t.entries)||t.entries.length>ho||t.total!==t.entries.length+t.omitted||!t.counts||typeof t.counts!="object"||Array.isArray(t.counts)||Object.keys(t.counts).some(n=>n.length>128||po.has(n)))return!1;const r=Object.values(t.counts);return r.length>go+Dr.size+1||r.some(n=>!Number.isSafeInteger(n)||n<=0)||r.reduce((n,o)=>n+o,0)!==t.total?!1:Cs(t)&&Rs(t)}function Rs(e){const t=new Map;return e.entries.every(r=>wo(e,r,t)!==void 0)}function bn(e,t,r,n){const o=`${r?"e":"o"}:${t}`,i=(n.get(o)??0)+1,s=e.explanations?.counts[t]??0;return(r?s:(e.counts[t]??0)-s)<i?!1:(n.set(o,i),!0)}function wo(e,t,r){const n=t&&typeof t=="object"&&typeof t.code=="string"?t.code:"unknown",o=Object.prototype.hasOwnProperty.call(e.counts,n)?n:De,i=!!t&&typeof t=="object"&&lr(t);if(bn(e,o,i,r))return o;if(o!==De&&!Dr.has(n)&&bn(e,De,i,r))return De}function lr(e){return e.valueState!==void 0}function Cs(e){if(e.explanations===void 0)return!0;const t=e.explanations;if(!t||typeof t!="object"||Array.isArray(t)||!Number.isSafeInteger(t.total)||t.total<0||t.total>e.total||!t.counts||typeof t.counts!="object"||Array.isArray(t.counts))return!1;const r=Object.entries(t.counts);return r.every(([n,o])=>Number.isSafeInteger(o)&&o>0&&o<=(e.counts[n]??0))&&r.reduce((n,[,o])=>n+o,0)===t.total}function Y(e){throw new Error(`数据契约无效:${e}`)}function dr(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}function Ts(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&&js(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 js(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 Ds(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 Ls=["text","number","boolean","date","decimal"],Bs=new Set(["__proto__","prototype","constructor"]);function z(e){throw new Error(`数据契约无效:${e}`)}function bo(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()||Bs.has(r.field)||t.has(r.field))&&z("字段名应安全、非空且唯一"),t.add(r.field),Ls.includes(r.type)||z(`未知字段类型 ${r.type}`),zs(r),Ws(r),Ts(r),_s(r);Ks(e,t),Ds(e.fields)}function _s(e){e.enum!==void 0&&(!Array.isArray(e.enum)||!e.enum.length||e.enum.some(t=>!xo(t,e.type)))&&z("enum 应为匹配字段类型的非空标量数组")}function Ks(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 Ws(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 zs(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 Vs(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 xo(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":typeof e!="string"?!1:t==="date"?Vs(e):t==="decimal"?e.length<=1e4&&/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e):!0}function Hs(e,t){if(e==null)return t.required||e===null&&t.nullable===!1?{code:"required",message:"缺少必需字段值"}:void 0;if(!xo(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"&&!Js(e,t))return{code:"range",message:"文本长度超出范围"}}function Js(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 er(e,t){const r=e??t;if(!Number.isInteger(r)||r<1)throw new Error("数据校验预算应为正整数");return r}function Us(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 Gs(e,t,r={}){bo(t);const n=r.path??"$.rows",o=[],i=er(r.maxIssues,100);if(!Array.isArray(e))return{ok:!1,issues:[{code:"row",path:n,message:"数据集应为对象数组"}]};if(e.length>er(r.maxRows,1e5)||e.length*t.fields.length>er(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}Ys(c,t,a,n,s,o,i)}return{ok:o.length===0,issues:o}}function Ys(e,t,r,n,o,i,s){for(const a of t.fields){if(i.length>=s)return;const c=Hs(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=Us(e,t.rowKey,o);a&&i.push({code:"row-key",path:`${n}[${r}].${t.rowKey}`,message:a,rowIndex:r,field:t.rowKey})}}function qs(e){return bo(e),{$schema:"https://json-schema.org/draft/2020-12/schema",type:"array",items:{type:"object",properties:Object.fromEntries(e.fields.map(r=>[r.field,Xs(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 Xs(e,t){const r=!t&&e.nullable!==!1&&!e.required;return{type:r?[xn(e.type),"null"]:xn(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},...Zs(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 Zs(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 xn(e){return e==="text"||e==="date"||e==="decimal"?"string":e}function Qs(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 ea(e){return e==="missing-source"||e==="not-applicable"||e==="not-calculable"}function Fe(e){return e.target!==void 0&&!Qs(e.target)?!1:e.valueState===void 0||ea(e.valueState)&&e.target!==void 0}function mr(e,t,r,n){if(n===void 0&&!e.diagnosticSummary&&!r){t.forEach(i=>e.diagnostics.push(i));return}const o=rt(n??Ye);e.diagnosticSummary?o.merge(e.diagnosticSummary):e.diagnostics.forEach(i=>o.push(i)),r?o.merge(r):t.forEach(i=>o.push(i)),e.diagnostics=o.entries,e.diagnosticSummary=o.snapshot()}function ta(e,t){return!Fe(e)||!Lr(e)||["code","message","severity","path","format","pageIndex","componentIndex","kind","nid","valueState"].some(n=>e[n]!==t[n])||e.componentPath?.length!==t.componentPath?.length||e.componentPath?.some((n,o)=>n!==t.componentPath?.[o])||["datasetId","field","rowKey","tableId","reportScope"].some(n=>e.target?.[n]!==t.target?.[n])?!1:e.extension?.id===t.extension?.id&&e.extension?.version===t.extension?.version}function vo(e,t){return!yo(e)||e.entries.length!==t.length?!1:e.entries.every((r,n)=>!!r&&typeof r=="object"&&ta(r,t[n]))}function tr(e,t,r,n,o=r.length){o&&e.merge({total:o,counts:{[t]:o},entries:r.map(i=>({code:t,message:i,severity:n})),omitted:o-r.length})}function vn(e,t){return e===void 0||typeof e=="number"&&Number.isSafeInteger(e)&&e>=t}function Lr(e){return!(e.format!==void 0&&!["dom","canvas","pdf","xlsx"].includes(e.format)||!vn(e.pageIndex,0)||!vn(e.componentIndex,-1)||e.componentPath!==void 0&&!ra(e.componentPath)||e.extension!==void 0&&(!e.extension||typeof e.extension.id!="string"||typeof e.extension.version!="string"))}function ra(e){if(!Array.isArray(e)||e.length>192)return!1;for(const t of e)if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)return!1;return!0}const _t=1.35,Br=10.5,_r='"Microsoft YaHei", sans-serif',na="1.0.0-mach",nt=na,Mo=/[\u3000-\u9fff\uff00-\uffef]/,oa=/[ \n\u3000-\u9fff\uff00-\uffef]/,xe=new Uint8Array(128);{for(const e of"iljtf.,:;'`|!()[]")xe[e.charCodeAt(0)]=1;for(const e of"mwMW@")xe[e.charCodeAt(0)]=2;for(let e=48;e<=57;e++)xe[e]=3;for(let e=65;e<=90;e++)xe[e]=4;xe[32]=5}const ia=[.54,.26,.95,.59,.67,.3];function sa(e){const t=e.charCodeAt(0);return t<128?ia[xe[t]]:Mo.test(e)?1:/[A-Z]/.test(e)?.67:.54}const qe={measureMm(e,t){const{fontSizePt:r,bold:n=!1,letterSpacingPt:o=0}=t,i=25.4/72;let s=0,a=0;for(const c of e)s+=sa(c),a++;return n&&(s*=1.04),(s*r+o*Math.max(0,a-1))*i}};function aa(e,t,r){if(!oa.test(e))return[{text:e,widthMm:r.measureMm(e,t),cjk:!1}];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(
|
|
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 fs(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 us=4096,on=128*1024;function ls(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>=us||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 ds(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=ds(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 ms(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 hs(e){ms(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 hs(e)}function gs(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 ps(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 ys(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 ws(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):ws(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:ps(String(e));return n?ys(n,r):String(e)}default:return String(e)}}const bs=[{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)"}],xs=Object.freeze(bs.map(e=>Object.freeze(e)));function vs(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 Ms(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 Ms(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 $s=["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 Ss(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 Es(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(!$s.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"?Es(e):Ss(e)}function Be(e,t){const r=se(t);for(const n of e)r.add(n);return r.value()}const As=new Set(["__proto__","prototype","constructor"]);function K(e){if(typeof e!="string"||!e.trim()||As.has(e))throw new Error("计算字段应为安全的非空字段名")}function Nr(e){return e===null||["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function ks(e){if(e.some(t=>typeof t!="number"||!Number.isFinite(t)))throw new Error("算术参数必须是有限数字;空值和小数文本不会隐式转换");return e}function Ns(e,t){const r=ks(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 Ps(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 Fs(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"?Ps(e,t,r.digits):Ns(e,t)}function Os(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 Rs(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 Os(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 Is(e,t,r,n)}function Is(e,t,r,n){const o=xs.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=>Rs(s,a):a=>Fs(e.op,s.map(c=>c(a)),t):a=>vs(e.op,s.map(c=>c(a)),t.numeric,t.digits,t.nulls)}function Cs(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&&gs(n.condition).forEach(o=>t.add(o)))};return r(e),[...t]}const Ts=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 js(e){try{return JSON.stringify(et(e,{nodes:0,units:0}))}catch(t){if(t!==de)throw t;return}}function Ds(e){lt.set(e,{programs:new Map,units:0,slots:0})}function Ls(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 Bs(e,t,r){const n=lt.get(e);if(!n||t.some(f=>typeof f.expression=="string"))return;const o=js(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>=Ts||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 _s(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 Ks(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 Ws(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 字段");zs(e)}function zs(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??[]:Cs(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(Ws(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 Js(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 Vs(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 Hs(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=Vs(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 Us(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 Gs(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 Ys(e,t,r,n,o,i,s,a){const c=_s(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;Gs(r,n,o,i,s,a),Ks(e,t,r,n,a.length>f?a[a.length-1]:void 0)}function Rt(e,t){Us(e,t),gn(t.signal);const r=Bs(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=Hs(s,a.definition);s.forEach((f,u)=>{gn(t.signal),Ys(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 qs(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("图表分类应为字符串");Xs(e);for(const n of r)Zs(n,t.length);return{...e,categories:t,series:r}}function Xs(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 Zs(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 Qs(e){let t=0,r=0;const n=eo(e)?ea(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 ea(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 ta(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 ra(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 na(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 oa(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 ia(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 sa(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+ia(e,i),n)}function aa(e){e=ta(qs(e));const t=Qs(e);return[...na(e,t),...eo(e)?ra(e,t):e.series.flatMap((r,n)=>oa(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,"图表度量"))ca(t);mt(e.maxRows,1e5,1e5),mt(e.maxCategories,200,200)}function ca(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 fa(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 ua(e){if(e===null)return null;const t=Number(e);if(!Number.isFinite(t))throw new RangeError("聚合结果超出图表有限数值范围");return t}function la(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=fa(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=>ua(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 da(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{...la(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 ma(e,t,r=Or){It(r);let n=0;return Object.assign(i=>{if(!i.chartBinding)return[i];const s=da(i,e,t),a=n+(s.categories.length?sa(s):1);if(!Number.isSafeInteger(a))throw new RangeError("图表图元估算应为有限安全整数");if(a>r)throw new Ke(r,a);const c=s.categories.length?aa(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 ha(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 ga(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 pa(e,t){const r=[...e.children.values()];return t&&t!=="source"&&r.sort((n,o)=>ga(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 pa(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 ya(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 wa(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=ya(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 ba(e,t){return no(e,t).shape}function xa(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 va(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 Ma(e,t){return e.kind==="total"?t.hierarchy.totalLabel??"合计":[...e.labels,...e.kind==="subtotal"?[t.hierarchy.subtotalLabel??"小计"]:[]].join(" / ")}function $a(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:`${Ma(r,t)} · ${n.label??`${n.field} (${n.op})`}`,semanticRole:"measure",...n.digits===void 0?{}:{format:{kind:"number",digits:n.digits}}}})]}function Sa(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 Ea(e,t){const r=no(e,t),n=bn(r.row,!!t.totals),o=va(bn(r.column,!!t.totals),t),i=xa(e,t,r);return{columns:$a(o,t),rows:Sa(n,o,t,i),headerGrid:wa(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 Aa(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 ka(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(ka(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&&ha(e.hierarchy,e.rowFields,e.columnFields)}function oo(e,t){if(Rr(t),t.hierarchy)return ba(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 Na(e,t){if(t?.hierarchy)return Rr(t),Ea(e,t);oo(e,t);const r=Aa(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 Pa=96;function Fa(e,t=Pa){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:Fa(n,t)}}function Oa(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 Ra(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?Ra(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 Ia(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 Ca(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 Ta(e,t){return{member:"body",subtotal:"subtotal",total:"grand-total"}[e?.rows.get(t)?.kind??"member"]}function ja(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 Da(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=Na(t,ja(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 La(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 Ba(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 _a(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(_a(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),Ba(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 Ka(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 Wa(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 za(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 Ja(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"?Ka(e,t,o,n,r):Wa(e,t,o,n,r);return za(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 Ja(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 Va(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 Ha(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:Va(e.headerGrid,t,r.map(n=>n.widthMm))}:{}}}function jr(e){return e.kind==="list"?e.id:e.nid}function Ua(e){return e.kind==="list"?!1:e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&/\{(?:page|totalPages)\}/.test(e.text)}function Ga(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 Ya(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(Ua(o))continue;const i=jr(o);if(!i||r.has(i))throw new Error("流式排版组件应具有唯一标识");r.add(i)}if(qa(e,t,r,n),n.size!==r.size)throw new Error("流式排版必须显式包含每个非锚点组件")}function qa(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)}Ga(e,i),o=i.topMm+i.heightMm}}function*Xa(e){const{page:t}=e;bo(t.components,t.flow);let r=0,n=0;for(const o of Ya(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 Za(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"?Za(r):!!r.chartBinding))}const Qa=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()&&!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 ec(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 tc(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:"应为字符串"});ec(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 rc(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;tc(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&&rc(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 nc=512,$n=256*1024;function oc(){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>=nc||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 ic(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 sc(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 ac=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 cc(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 fc(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??ac,a=cc(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 uc(e,t,r){if(!e.binding)return e;const{binding:n,...o}=e,i=sc(n,t.row,t);if(e.kind==="image"){if(!i)return;if(!ic(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 lc(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*Oa(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=uc(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))}),lc(o===n.grid?n:{...n,grid:o},t,r)}function dc(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*mc(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=fc(e,t,r),s=oc();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:dc(h,m,f,l,u,d),pageIndex:m}}}const hc=/^#[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"&&hc.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 gc(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 pc(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=gc(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 yc(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),pc(o,i,f,u)})}function En(e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError")}function wc(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 bc(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=xc(La(e,t),g,{cells:[m],colWidthsMm:g,rowHeightsMm:[l],paddingMm:i});return{fontSizePt:o,paddingMm:i,visuals:yc(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 xc(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 vc(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=Mc(e,c,o);l=$c(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=bc(u),p={text:m,style:l};u!=null&&e.visuals[a]?.apply(p,t),w!==void 0&&(p.value=w),vc(p,c,e.numberFormats[a]),Sc(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 Mc(e,t,r){return!r||t.field!==e.tree.list.tree.labelField?0:Ia(e.tree.list,t,r,e.paddingMm)}function $c(e,t,r,n){return!n||t.field!==e.tree.list.tree.labelField||r.align==="left"?r:{...r,align:"left"}}function Sc(e,t,r,n,o=0){n&&(o&&(e.indentMm=o),Ca(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=>Ec(e,l,t));return{grid:{cells:u,colWidthsMm:e.colWidthsMm,rowHeightsMm:d,paddingMm:e.paddingMm},heightMm:d.reduce((l,m)=>l+m,0)}}function Ec(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 Ac(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 kc(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=kc(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 Nc(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=Ha(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 Pc(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*Fc(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 Oc(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 Rc(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=Rc(e,t);if(o)return r.prepared.set(e,o),o;if(e.tree){const c=Oc(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=Da(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 Ic(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*Cc(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}}:{}};Ic(s,c,o,r);const f=Ac(s,c,r),u=Pc(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",Ta(n.matrix,l.row),i.get(l.row)),d=void 0,yield*r.takePages(),yield*Fc(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()}Nc(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 Tc(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 jc(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*Dc(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??""} 输出为空`),Cc(i,Array.isArray(c)?c:[],{...e,tableId:`${e.tableId}:${n.get(i)}`,startTop:s,finished:a,flow:!!t.flow})};if(t.flow){yield*Xa({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=>jc(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=ls(r.measurer??Er),d=ma(t,r.signal,r.maxChartComponents),l=m=>`${m}_${(++a).toString(36)}`;for(const{pageIndex:m,page:h}of mc(e,t,r)){ae(r.signal);const g=wc(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(Tc(h,g,y,++c,x,o))},b=()=>{const x=w;return w=[],x};yield*Dc({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 Lc(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 Bc(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 _c(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 Kc(e,t,r={}){if(e.tree)return _c(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=Bc(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 Wc(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 zc(e){const t=Ko(e.pages);if(t)throw new TypeError(`${t.path}: ${t.message}`)}function Jc(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 Vc(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;Jc(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 Hc(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 Uc(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 Gc(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return[{path:"",message:"code must be an object."}];const r=e,n=[...Hc(r),...Uc(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 Yc=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 qc(e,t,r,n){const o=e[t];(typeof o!="number"||!Number.isFinite(o))&&n.push({path:`${r}.${t}`,message:`应为有限数字,实际 ${yt(o)}`})}function Xc(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 Zc(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}Vc(a,f,r),a.dataBar!==void 0&&!Wc(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 Qc(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 ef(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:"富文本内容应为字符串"});Qc(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)=>ef(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 字符串"}):Yc.has(o)||n.push({path:`${t}.kind`,message:`未知组件类型 ${yt(o)},将以兜底方式渲染`});for(const i of["leftMm","topMm","widthMm","heightMm"])qc(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:"组件尺寸不能为负数"});Xc(e.table,t,r),rf(e.code,o,t,r),tf(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"}),Zc(e.grid,t,r,n),Jo(e.richParagraphs,t,r)}function tf(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 rf(e,t,r,n){if(e!==void 0)for(const o of Gc(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 nf(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)=>nf(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 of(e){return Go(e,Ur,!0)}function sf(e){return Go(e,Uo,!1)}function af(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"?af(t):e.type==="cascader"?sf(t):of(t)}function cf(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=ff(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 ff(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 uf(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 lf(e,t){const r=Dt(e,t);if(!r)return[["type",e.type==="numberRange"?"请填写完整数字范围,最小值不能大于最大值":e.type==="cascader"?"请选择完整的末级路径":"请选择有效选项,不能重复或超出数量限制"]];if(e.type==="numberRange")return df(e,r);const n=r,o=[];return e.type==="cascader"&&e.options&&!uf(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 df(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 mf(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 hf(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 gf(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 pf(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 yf(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 lf(e,t);if(e.type==="number"&&!Qo(t))return[["type","应为有限数字"]];const r=yf(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(...wf(e,t)),n}function wf(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 bf(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,...xf(e),...mf(e)]}function xf(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 Mf(n,t).map(a=>({code:"definition",field:i,path:`$.paramDefs.${o}`,message:a}))});return r.length?r:pf(e).map(({index:n,message:o})=>({code:"definition",field:e[n].field,path:`$.paramDefs.${n}`,message:o}))}function vf(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&&!cf(e.options,e.type==="cascader",!U(e))&&t.push("选项应为包含字符串 label/value 的数组"),[...t,...gf(e)]}function Mf(e,t){if(!e||typeof e!="object"||Array.isArray(e))return["参数定义项应为对象"];const r=vf(e);return typeof e.field!="string"||!e.field.trim()||t.has(e.field)?r.push("参数名应为非空且不重复的字符串"):t.add(e.field),r.length||(r.push(...bf(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 $f(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};$f(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;Sf(i,s,{values:r,typedValues:n,issues:o})}return o.push(...Ef(e,r)),{ok:o.length===0,values:r,typedValues:n,issues:o}}function Sf(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 Ef(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 Af(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 kf(e){const t={type:e.type==="number"?"number":"string",title:e.label??e.field,...Af(e)};return U(e)&&Object.assign(t,hf(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,Pf(e)),Object.assign(t,Nf(e)),t}function Nf(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 Pf(e){return{...e.optionsSource?{"x-report-options-source":e.optionsSource}:{},...e.dependsOn?.length?{"x-report-depends-on":[...e.dependsOn]}:{}}}function Ff(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,kf(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 Of(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(!Of(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 Rf(e,t,r){if(e===void 0)return;const n=Js(e);for(const o of n.errors)r.push({path:t,message:o})}function If(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 Cf(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 Tf=1e7,jf=new Set(["__proto__","prototype","constructor"]),Df=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&&!jf.has(e)}function Lf(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&&!Df.has(String(o.type))&&r.push({path:`${s}.type`,message:"未知绑定字段类型"})})}function Bf(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:"数据集应使用安全名称和字段契约"}):Lf(i.fields,`${s}.fields`,r)}}class _f extends Error{constructor(t){super(`模板校验失败:${t.slice(0,3).map(r=>`${r.path}: ${r.message}`).join("; ")}`),this.errors=t,this.name="ReportTemplateError"}}const Kf=new Set(["__proto__","prototype","constructor"]),Wf=new Set(["left","center","right","justify"]),ot=2e5,zf=64;function C(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Jf(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 Vf(e,t,r,n){return Kf.has(e)?(n.push({path:r,message:"模板不能包含可能污染原型的键"}),!1):t.get||t.set||!t.enumerable?(n.push({path:r,message:"模板不能包含访问器或不可枚举字段"}),!1):!0}function Hf(e){return e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)}function Uf(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>zf){t.push({path:c,message:"模板嵌套层级过深"});return}if(typeof a=="string"){o+=a.length,o>Tf&&(i=!0,t.push({path:c,message:"模板文本超过 1000 万字符的安全上限"}));return}if(!Hf(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(Jf(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(Vf(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&&!Wf.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 Gf(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:"长度边界应为非负整数"})}Yf(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 Yf(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 qf(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 Xf(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:"表头行高数量应与行数一致"}),Zf(i,s,r,n)}function Zf(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 Qf(e,t,r){if(Cf(e,t,r),Rf(e.computed,`${t}.computed`,r),If(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 eu(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&&Xf(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),Qf(e,t,r),ni(e.groupBy,`${t}.groupBy`,r),qf(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 tu(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 ru(e){const t=[],r=[];return Uf(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"}),Gf(e.params,"$.params",t),Bf(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"?eu(s,c,t):(Vo(s,c,t,r),C(s)&&Yr(s,c,t))}):t.push({path:`${i}.components`,message:"组件应为数组"}),tu(n,i,t)})):t.push({path:"$",message:"模板应为对象"}),{ok:t.length===0,errors:t,warnings:r})}class nu 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 ou(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("未知校验范围");ou(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 iu(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 su(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 au(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 cu(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=su(e,t),{rows:s,summaryRows:a,rowKey:c}=i;au(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(iu(l.rule,h,l.rule.scope==="dataset"?void 0:g,l.rule.scope==="dataset"?void 0:c))}});return d}function fu(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 nu(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 uu(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(...cu(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 lu(e){return!e||typeof e!="object"?!1:[e.pageIndex,e.componentIndex,e.rowIndex,e.columnIndex].every(t=>Number.isInteger(t)&&t>=0)}function du(e){return e.value!==void 0?e.value:e.rawText??e.text??null}function mu(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 hu(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 gu(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 pu(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 yu(e,t,r){const n=du(r),o=hu(r,e);return{address:{...t},cell:r,component:e,value:n,valueType:mu(r,n),table:gu(e,t),source:pu(r,e,t),editable:o===void 0,readOnlyReason:o}}function ii(e){const t=new Map;return r=>{if(!lu(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?yu(n,r,i):null}}function wu(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 bu(e,t){const r=wu(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 xu(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 vu(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 Mu(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 $u(e,t,r){if(!t||/^(General|@)$/i.test(t))return String(e);const n=bu(e,t);if(n.pattern==="")return"";const o=xu(n.pattern),i=vu(n,o)??Mu(n,o);return i!==null?i:String(e)}function Su(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 Eu(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 Au(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:Eu(e,Su(t.cell.numberFormat));if(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r))throw new P("number");return r}function ku(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 Nu(e,t){return e.valueType==="number"?Au(t,e):e.valueType==="boolean"?ku(t):t===null?null:String(t)}function Pu(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"?Pu(t,e):typeof t=="number"?$u(t,e.cell.numberFormat):String(t)}function ai(e,t){if(!e.editable)throw new P("readonly");const r=Nu(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 Fu(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);Ls(e[i].datasets[s],r[i].datasets[s])}return r}function Ou(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 Ru(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 Iu(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 Cu(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 Tu(e){const t=[];return mi(e,t,new Set,{nodes:0},0),()=>{try{return t.every(Cu)}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 ju(e){return Et(e,{nodes:0},0,!0)}function Du(e){const t=Et(e,{nodes:0},0);for(const r of t)for(const n of Object.values(r.datasets))Ds(n);return t}async function Lu(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 Bu(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),Fu(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 _u(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 Ku(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,Ou(e,n,r))}function Wu(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 zu(e,t){let r=t.parts;const n=t.rebuild,o=[...t.validationFormulas??[]];let i=Tu(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 Du(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,_u(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(uu(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("候选规则校验未完成,不能提交");fu($,j);const S=Ku(p,h,M),I=Ru(b,h,M);if(M){const N=Wu(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=Bu(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=Iu(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 Ju=0;function it(){return`report-${Date.now()}-${++Ju}`}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 Vu(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&&Hu(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 Hu(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 Uu(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 Gu=["text","number","boolean","date","decimal"],Yu=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()||Yu.has(r.field)||t.has(r.field))&&z("字段名应安全、非空且唯一"),t.add(r.field),Gu.includes(r.type)||z(`未知字段类型 ${r.type}`),Qu(r),Zu(r),Vu(r),qu(r);Xu(e,t),Uu(e.fields)}function qu(e){e.enum!==void 0&&(!Array.isArray(e.enum)||!e.enum.length||e.enum.some(t=>!pi(t,e.type)))&&z("enum 应为匹配字段类型的非空标量数组")}function Xu(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 Zu(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 Qu(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 el(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"?el(e):t==="decimal"?e.length<=1e4&&/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e):!0}function tl(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"&&!rl(e,t))return{code:"range",message:"文本长度超出范围"}}function rl(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 nl(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 ol(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}il(c,t,a,n,s,o,i)}return{ok:o.length===0,issues:o}}function il(e,t,r,n,o,i,s){for(const a of t.fields){if(i.length>=s)return;const c=tl(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=nl(e,t.rowKey,o);a&&i.push({code:"row-key",path:`${n}[${r}].${t.rowKey}`,message:a,rowIndex:r,field:t.rowKey})}}function sl(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,al(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 al(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},...cl(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 cl(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 fl(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 ul(e){return e==="missing-source"||e==="not-applicable"||e==="not-calculable"}function Xr(e){return e.target!==void 0&&!fl(e.target)?!1:e.valueState===void 0||ul(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 ll(e,t,r={}){return Object.values(yi(e,t,r)).reduce((n,o)=>n+o.length,0)}function dl(e,t,r){const n=sl(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 ml(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 hl(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&&!ml(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=hl(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 gl(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 pl(e,t,r){const{reportId:n,signal:o}=t;try{const i=await gr(e(t),o);G(o);const s=ru(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 _f?new E("validate",`报表 ${n} 模板校验失败:${i.message}`,i):new E("fetch",`报表 ${n} 模板加载失败:${i instanceof Error?i.message:String(i)}`,i)}}async function yl(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),wl(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 wl(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 bl(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=ol(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 xl(e,t,r,n,o){try{let i;try{i=ju(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):Lc(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 vl(e,t,r,n,o){const i=[],s=mr(n);for(const[f,u]of e.entries()){G(o);try{const d=await Lu(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 Ml(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",()=>pl(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",()=>yl(M,I,S,(zt,Zi)=>c?.(zt,Zi,v)),S);u.runSync("validate",()=>{gl(R,S),t.onDatasets?.(S,R,N),bl(M,R,S,N,s)},S),G(s);const ye=wi(v,S,M.sourceScope),{result:rn,part:Xi}=await u.run("layout",()=>xl({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{zu(b,{parts:y,validationFormulas:$.map(v=>v.pagination?.formula),rebuild:(v,M)=>vl(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 $l 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 Sl(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 El(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 Al=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function kl(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(Al.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 Nl(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"?El(a):kl(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 Pl(e={}){const t=Sl(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=Nl(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 Fl(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 Ol(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 Rl(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=Ol(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 Il(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 Cl(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=Rl(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 Cl(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 Tl(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 jl(e){if(e.options.fidelity==="strict"&&e.diagnostics.length)throw new $l(e.diagnostics)}async function Cn(e,t={}){he.assertOutputActive(t.signal),zc(e);const r=Fl(t),n=Pl(t);if(Tl(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(()=>Il(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),jl(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 Dl=new Set([8,9,10,12,13]);function Ll(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 Bl(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+=Dl.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=Bl(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}=Ll(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 _l=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+_l[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 Kl(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 Wl(e){if(e!==void 0){if(!Array.isArray(e)||e.length>1e4)throw new RangeError("工作表名称列表最多 10000 项");return Array.from(e,Ii)}}function zl(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 Jl(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=zl(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:Wl(e.sheetNames),additionalSheets:Jl(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 Vl(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 Hl(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 Ul(e,t,r){return e.pages.reduce((n,o)=>n+o.components.reduce((i,s)=>s.kind!=="list"?i+Wt(s):i+Kc(s,t,r),0),0)}function Gl(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:Ff(i),datasetsSchema:Object.fromEntries(Object.entries(r.dataSchema??{}).map(([s,a])=>[s,dl(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 Ml(l,{maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents,onDatasets:(x,$,j)=>{try{a+=ll(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+=Ul(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=>Gl(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",()=>Hl(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 Yl={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 ql(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 Xl(e){const t={...Yl,...e.thresholds};for(const r of Object.values(t))if(!Number.isSafeInteger(r)||r<=0)throw new RangeError("导出隔离阈值应为正安全整数");return t}function Zl(e,t){const r=Xl(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)}}ql(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 Ql(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 ed(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 td(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 rd(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 nd(e,t){if(!ue(e)||!Ql(e.stats)||!ed(e.diagnostics)||!td(e.revisions)||!rd(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 od(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(od)}:{}}}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 id(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 sd=0;function _n(e){const t=new Error("报表 Worker 任务已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e}),t}function ad(e,t){if(!e||typeof e!="object")return;const r=e;return r.protocol===fe&&r.id===t?r:void 0}function cd(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()}-${++sd}`;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=ad(p,d);if(!(!b||l)){if("type"in b&&b.type==="event"){const x="event"in b?b.event:void 0;id(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)):nd(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,$=fd(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 fd(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 ud(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 ld(e,t){const r={...Qr,...t.budget},n=Vl(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 dd(e,t){ud(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=Zl(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=ld(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 md(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 hd(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 gd(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=hd(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(gd(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 pd(e,t){if(e&&(e.createdAt!==t.createdAt||ie(e.request)!==ie(t.request)))throw new k("input","任务创建时间与请求不可变更,请使用新任务ID")}function yd(e,t){return e.status==="queued"||e.status==="running"&&(e.lease?.expiresAt??0)<=t}function wd(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 bd(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 xd(e){const t=new TextEncoder().encode(ie(e)),r=globalThis.crypto?.subtle;if(!r)return Kl(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 vd(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 xd(e.request),expiresAt:t}}function Md(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 $d(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 Sd(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 $d(e,!0),await A.promises.open(e,"wx",384)}finally{await n.close(),await A.promises.unlink(r)}}async function Ed(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 Sd(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 Ad(e,t,r,n){if("tombstone"in r){const o=r.tombstone;if(Md(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 kd(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","持久任务文件超过单文件预算");Ad(o,i,JSON.parse(await A.promises.readFile(s,"utf8")),t)}return o}async function Nd(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 Pd(e){const t=L.resolve(e.directory),r=wd(e);await A.promises.mkdir(t,{recursive:!0,mode:448});const n=await Ed(t,e.recoverDeadOwner??!1);let o;try{o=await kd(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 Nd(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=>yd(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;pd(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=bd(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 vd(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 Fd(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 Od(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 Rd(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 Id(e){const t=Fd(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 Rd(r,t);d=Od({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 cd(()=>{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 Cd(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 Td(e){return pe.createHash("sha256").update(e).digest("hex")}function jd(e={}){const t={timeoutMs:e.timeoutMs??e.budget?.maxDurationMs,budget:{...e.budget}};return dd(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)&&md(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=jd;exports.createNodeReportExecutor=qi;exports.openFileReportDocumentStore=Id;exports.openFileReportJobStore=Pd;exports.reportArtifactSha256=Td;exports.serveNodeReportWorker=Cd;
|
|
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(Mo.test(s)){i(),n.push({text:s,widthMm:r.measureMm(s,t),cjk:!0});continue}o+=s}return i(),n}function ye(e,t,r,n=qe){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 aa(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 ca=4096,Mn=128*1024;function ua(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<=Mn){for(;t.size>=ca||r+i.length>Mn;){const c=t.keys().next().value;r-=c.length,t.delete(c)}t.set(i,a),r+=i.length}return a}}}const wt=1e3;function we(e){if(!Number.isSafeInteger(e)||e<0||e>wt*2)throw new Error("十进制精度超出预算");return 10n**BigInt(e)}function Kt(e){if(e.coefficient.toString().length>wt*2||e.scale>wt*2)throw new Error("十进制结果超出精度预算");return e}function H(e){if(typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("十进制参数必须是有限数字或十进制文本");const t=String(e);if(t.length>wt)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 Kt(i<0?{coefficient:s*we(-i),scale:0}:{coefficient:s,scale:i})}function So(e,t){const r=Math.max(e.scale,t.scale);return[e.coefficient*we(r-e.scale),t.coefficient*we(r-t.scale),r]}function bt(e,t){const[r,n]=So(e,t);return r<n?-1:r>n?1:0}function xt(e,t){const[r,n,o]=So(e,t);return Kt({coefficient:r+n,scale:o})}function Kr(e,t){return Kt({coefficient:e.coefficient*t.coefficient,scale:e.scale+t.scale})}function $o(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 ot(e){if(!Number.isInteger(e)||e<0||e>100)throw new Error("十进制小数位应为 0–100 的整数")}function hr(e,t,r=20){if(ot(r),t.coefficient===0n)throw new Error("不能除以零");const n=t.scale-e.scale+r,o=e.coefficient*we(Math.max(0,n)),i=t.coefficient*we(Math.max(0,-n));return Kt({coefficient:$o(o,i),scale:r})}function Wt(e,t){let r=e.coefficient,n=e.scale;t!==void 0&&(ot(t),r=t>=n?r*we(t-n):$o(r,we(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=H(e);n&&(o=Kr(o,{coefficient:100n,scale:0}));const[i,s]=Wt(o,t).split(".");return`${r?i.replace(/\B(?=(\d{3})+(?!\d))/g,","):i}${s===void 0?"":`.${s}`}${n?"%":""}`}const Eo=new Set(["__proto__","prototype","constructor"]);function Ao(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(Eo.has(t)||!Object.prototype.hasOwnProperty.call(r,"value"))throw new Error("条件不允许访问器或不安全属性")}function $n(e){if(typeof e!="string"||!e.trim()||e.length>512||Eo.has(e))throw new Error("条件字段应为安全的非空字段名")}function rr(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 gr(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 En(e){return["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function An(e){return e==null||e===""}function fa(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 ft(e,t,r){if(An(e)||An(t))return;const n=fa(r);try{if(n==="decimal")return bt(H(e),H(t));if(n==="number")return!["number","string"].includes(typeof e)||!["number","string"].includes(typeof t)?void 0:bt(H(e),H(t));if(n==="date"&&(e=gr(e),t=gr(t)),n==="boolean"&&(typeof e!="boolean"||typeof t!="boolean")||n==="text"&&(!En(e)||!En(t)))return;const o=String(e),i=String(t);return o<i?-1:o>i?1:0}catch{return}}function la(e){if($n(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(rr);const t=ft(e.values[0],e.values[1],e);if(t===void 0||t>0)throw new Error("范围边界无效或顺序颠倒")}else if(e.right!==void 0){if(Ao(e.right),Object.keys(e.right).length!==1)throw new Error("条件 right 只能指定一个 field 或 value");if("field"in e.right?$n(e.right.field):rr(e.right.value),e.value!==void 0)throw new Error("条件不能同时指定 value 和 right")}else rr(e.value)}function nr(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 da(e){la(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 nr(">=",ft(n,e.values[0],e))&&nr("<=",ft(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):nr(e.op,ft(n,o,e))}}function q(e,t={nodes:0},r=0){if(++t.nodes>256||r>16)throw new Error("条件超出深度或节点预算");if(Ao(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 da(e)}function ma(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 ko(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 ha(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 pr(e,t){return e.toLocaleString("en-US",{minimumFractionDigits:t,maximumFractionDigits:t})}function ga(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 pa(e,t,r){return r!=null?t?pr(e,r):e.toFixed(r):t?pr(e):String(e)}function kn(e){const t=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(t)?t:null}function Wr(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=kn(e);return r==null?String(e):pa(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=kn(e);return r==null?String(e):`${pr(r*100,t.digits??2)}%`}case"date":{const r=t.pattern??"YYYY-MM-DD",n=e instanceof Date?e:ha(String(e));return n?ga(n,r):String(e)}default:return String(e)}}const ya=[{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)"}],wa=Object.freeze(ya.map(e=>Object.freeze(e)));function ba(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 xa(e,t,r,n);if(e.startsWith("date")){const a=gr(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 xa(e,t,r,n){const o=t[0];if(r!=="decimal"&&(typeof o!="number"||!Number.isFinite(o)))throw new Error("普通数值函数需要有限数字");const i=H(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("小数位必须为数字");ot(s)}const a=Wt(i,s),c=Number(a);if(r!=="decimal"&&!Number.isFinite(c))throw new Error("计算结果不是有限数字");return r==="decimal"?a:c}const va=["sum","count","avg","min","max","weightedAvg"];function Pn(e){if(typeof e!="number"||!Number.isFinite(e))throw new Error("聚合度量必须是有限数字,不能隐式转换;小数文本请显式选择 decimal");return e}function vt(e,t){return t&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ma(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=vt(c,e.field);if(e.op==="count"){(!e.field||u!=null)&&t++;return}if(u==null)return;const f=Pn(u),d=e.op==="weightedAvg"?vt(c,e.weightField):1;if(d==null)return;const l=Pn(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 Sa(e){let t=0,r=H("0"),n=H("0"),o,i;return{add(s){const a=vt(s,e.field);if(e.op==="count"){(!e.field||a!=null)&&t++;return}if(a==null)return;const c=e.op==="weightedAvg"?vt(s,e.weightField):"1";if(c==null)return;const u=H(a),f=H(c);if(e.op==="weightedAvg"&&f.coefficient<0n)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&(r=xt(r,Kr(u,f))),e.op==="weightedAvg"&&(n=xt(n,f)),(!o||bt(u,o)<0)&&(o=u),(!i||bt(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=hr(r,H(t),e.digits)),e.op==="weightedAvg"&&(s=hr(r,n,e.digits)),Wt(s,e.digits)}}}function ce(e){if(e.digits!==void 0&&ot(e.digits),e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal")throw new Error("未知聚合数值模式");if(!va.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"?Sa(e):Ma(e)}function Xe(e,t){const r=ce(t);for(const n of e)r.add(n);return r.value()}const $a=new Set(["__proto__","prototype","constructor"]);function K(e){if(typeof e!="string"||!e.trim()||$a.has(e))throw new Error("计算字段应为安全的非空字段名")}function zr(e){return e===null||["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function Ea(e){if(e.some(t=>typeof t!="number"||!Number.isFinite(t)))throw new Error("算术参数必须是有限数字;空值和小数文本不会隐式转换");return e}function Aa(e,t){const r=Ea(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 ka(e,t,r){const n=t.map(H);let o;return e==="add"?o=n.reduce(xt):e==="multiply"?o=n.reduce(Kr):e==="subtract"?o=xt(n[0],{...n[1],coefficient:-n[1].coefficient}):o=hr(n[0],n[1],r),Wt(o,r)}function Pa(e,t,r){return r.nulls!=="error"&&t.some(n=>n==null)||e==="divide"&&r.divisionByZero==="null"&&(r.numeric==="decimal"?H(t[1]).coefficient===0n:t[1]===0)?null:r.numeric==="decimal"?ka(e,t,r.digits):Aa(e,t)}function Na(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};Xe([],r);const n=new WeakMap;return o=>{let i=n.get(o.rows);if(!i){try{i={value:Xe(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 Oa(e,t){for(const r of e){const n=r(t);if(n!=null)return n}return null}function Vr(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 Na(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(!zr(e.value))throw new Error("常量应为有限 JSON 标量");return()=>e.value}return Ia(e,t,r,n)}function Ia(e,t,r,n){const o=wa.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=>Vr(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=>Oa(s,a):a=>Pa(e.op,s.map(c=>c(a)),t):a=>ba(e.op,s.map(c=>c(a)),t.numeric,t.digits,t.nulls)}function Fa(e){Vr(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&&ma(n.condition).forEach(o=>t.add(o)))};return r(e),[...t]}const Ra=16,yr=1024*1024,Nn=5e5,Mt=new WeakMap,ge=Symbol("uncacheable-computation-definition");function lt(e,t,r=0){if(++t.nodes>1e4||r>32)throw ge;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>yr)throw ge;return["string",e]}if(typeof e!="object")throw ge;if(Array.isArray(e)){if(Object.getPrototypeOf(e)!==Array.prototype||Object.keys(e).length!==e.length)throw ge;return["array",Array.from({length:e.length},(n,o)=>lt(On(e,String(o)),t,r+1))]}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw ge;return["object",Object.keys(e).map(n=>[lt(n,t,r+1),lt(On(e,n),t,r+1)])]}function On(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw ge;return r.value}function Ca(e){try{return JSON.stringify(lt(e,{nodes:0,units:0}))}catch(t){if(t!==ge)throw t;return}}function Ta(e){Mt.set(e,{programs:new Map,units:0,slots:0})}function ja(e,t){const r=Mt.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})}Mt.set(t,n)}function Da(e,t,r){const n=Mt.get(e);if(!n||t.some(u=>typeof u.expression=="string"))return;const o=Ca(t);if(o===void 0||o.length>yr)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<=Nn};if(!c.cacheRows)return c;for(;n.programs.size>=Ra||n.units+o.length>yr||n.slots+a>Nn;){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 La(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 Ba(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 _a(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&&ot(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 字段");Ka(e)}function Ka(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 Hr(e){return[...new Set([...typeof e.expression=="string"?e.dependsOn??[]:Fa(e.expression),...e.groupBy??[]])]}function Po(e){if(!Array.isArray(e)||e.length>2048)throw new Error("计算字段应为数组且最多2048项");const t=new Map;for(const s of e){if(_a(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 Hr(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 Wa(e){try{const t=Po(e);return{valid:!0,errors:[],order:t.map(r=>r.field),fields:e.map(r=>({field:r.field,dependencies:Hr(r),scope:r.scope??"row"}))}}catch(t){return{valid:!1,errors:[t instanceof Error?t.message:String(t)],fields:[],order:[]}}}function In(e){return Po(e.fields).map(t=>{const r=Hr(t);if(typeof t.expression!="string")return{definition:t,dependencies:r,read:Vr(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 za(e,t){return JSON.stringify(t.map(r=>{const n=Object.prototype.hasOwnProperty.call(e,r)?e[r]:null;if(n!=null&&!zr(n))throw new Error("分组字段应为有限 JSON 标量");return[typeof n,n??null]}))}function Va(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=za(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 Ha(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 Fn(e){if(e?.aborted){const t=new Error("数据计算已取消");throw t.name="AbortError",t}}function Ja(e,t,r,n,o,i){try{const s=e.read({row:t,rowIndex:r,rows:n});if(s!==void 0&&!zr(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 Ua(e,t,r,n,o,i,s,a){const c=La(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;Ja(r,n,o,i,s,a),Ba(e,t,r,n,a.length>u?a[a.length-1]:void 0)}function zt(e,t){Ha(e,t),Fn(t.signal);const r=Da(e,t.fields,()=>In(t)),n={program:r,writes:new WeakMap},o=r?.fields??In(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=Va(s,a.definition);s.forEach((u,f)=>{Fn(t.signal),Ua(n,e[f],a,u,f,c(u),t,i)})}return{rows:s,issues:i}}function Be(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 ke=["#2563eb","#0d9488","#d97706","#7c3aed","#dc2626","#0284c7"];function Ga(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=Be(e.categories,200,"图表分类"),r=Be(e.series,12,"图表系列").map(n=>({...n,values:Be(n?.values,200,"图表数值")}));for(const n of t)if(typeof n!="string")throw new Error("图表分类应为字符串");Ya(e);for(const n of r)qa(n,t.length);return{...e,categories:t,series:r}}function Ya(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 qa(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 wr(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 ve(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 St(e){return Number(e.toPrecision(5)).toString()}function Xa(e){let t=0,r=0;const n=No(e)?Za(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 No(e){return e.type==="stackedBar"||e.type==="percentBar"}function Za(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 Qa(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 ec(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)),g=c.color??ke[u%ke.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({...ve(e.type==="percentBar"?`${St(f)}%`:St(f),y,m+h/2-2.5,w),style:{fontSize:7,color:"#ffffff",align:"center"}})})}),r}function tc(e,t){const r=[];e.title&&r.push({...ve(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(wr(t.left,c,t.left+t.width,c,"#e2e8f0",.4),ve(`${St(a)}${e.type==="percentBar"?"%":""}`,e.leftMm,c-2.5,11,"right"))}r.push(wr(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(ve(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({...ve(i.name,t.left+s*o,e.topMm+e.heightMm-5,o),style:{fontSize:8,color:i.color??ke[s%ke.length],align:"center"}})}),r}function rc(e,t,r,n){const o=[],i=r.color??ke[n%ke.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(wr(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({...ve(St(u),d-s/2,Math.max(t.top,l-5),s),style:{fontSize:7,color:i,align:"center"}})}),o}function nc(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 oc(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+nc(e,i),n)}function ic(e){e=Qa(Ga(e));const t=Xa(e);return[...tc(e,t),...No(e)?ec(e,t):e.series.flatMap((r,n)=>rc(e,t,r,n))]}function $t(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 Oo(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 Be(e.measures,12,"图表度量"))sc(t);$t(e.maxRows,1e5,1e5),$t(e.maxCategories,200,200)}function sc(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");ce(e)}function ac(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 cc(e){if(e===null)return null;const t=Number(e);if(!Number.isFinite(t))throw new RangeError("聚合结果超出图表有限数值范围");return t}function uc(e,t,r){if(r?.aborted){const a=new Error("图表数据处理已取消");throw a.name="AbortError",a}Oo(t);const n=Be(t.measures,12,"图表度量");if(!Array.isArray(e)||e.length>$t(t.maxRows,1e5,1e5))throw new RangeError("图表数据超出行数预算");const o=new Map,i=$t(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=ac(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(ce)},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=>cc(u.accumulators[c].value())),...a.color?{color:a.color}:{}}))}}class Pe extends Error{constructor(t,r){super(`报表页数超出上限 ${t}(至少 ${r} 页)`),this.limit=t,this.actual=r,this.code="page-limit",this.name="PaginatePageLimitError"}}class Ze extends Error{constructor(t,r){super(`报表单元格数量超出上限 ${t}(至少 ${r} 格)`),this.limit=t,this.actual=r,this.code="cell-limit",this.name="PaginateCellLimitError"}}class Qe extends Error{constructor(t,r){super(`报表图表图元数量预计超出上限 ${t}(本次估算 ${r})`),this.limit=t,this.estimated=r,this.code="chart-component-limit",this.name="PaginateChartComponentLimitError"}}const Jr=5e4;function Vt(e=Jr){if(!Number.isSafeInteger(e)||e<1||e>1e6)throw new RangeError("maxChartComponents 应为 1..1000000 的安全整数")}function fc(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{...uc(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 lc(e,t,r=Jr){Vt(r);let n=0;return Object.assign(i=>{if(!i.chartBinding)return[i];const s=fc(i,e,t),a=n+(s.categories.length?oc(s):1);if(!Number.isSafeInteger(a))throw new RangeError("图表图元估算应为有限安全整数");if(a>r)throw new Qe(r,a);const c=s.categories.length?ic(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 _e(e,t){return JSON.stringify([e.slice(0,t.length),t.map(r=>[r===null?"null":typeof r,r])])}function Io(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 dc(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("矩阵层级标签应为字符串");Rn(e.row,t.length),Rn(e.column,r.length)}function Rn(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 Cn(e,t,r){return{fields:e,options:t??{},hierarchy:r,root:{values:[],children:new Map},leaves:0,expanded:0}}function Tn(e,t){const r=Io(t,e.fields);let n=e.root;for(let o=1;o<=r.length;o++){const i=r.slice(0,o),s=_e(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 mc(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 hc(e,t){const r=[...e.children.values()];return t&&t!=="source"&&r.sort((n,o)=>mc(n.values[n.values.length-1],o.values[o.values.length-1])*(t==="desc"?-1:1)),r}function or(e,t,r){return{key:_e(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 jn(e,t){const r=[];function n(o){for(const i of hc(o,e.options.sort?.[o.values.length]))i.children.size?(n(i),e.options.subtotals?.includes(i.values.length)&&r.push(or(e,i.values,"subtotal"))):r.push(or(e,i.values,"member"))}return n(e.root),t&&e.leaves&&r.push(or(e,[],"total")),r}function Dn(e,t,r){const n=Io(t,e.fields),o=[_e(e.fields,n),...(e.options.subtotals??[]).map(i=>_e(e.fields,n.slice(0,i)))];return r&&o.push(_e(e.fields,[])),o}function gc(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 pc(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=gc(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 Ln(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 Fo(e,t){if(!Array.isArray(e)||e.length>(t.maxInputRows??1e5))throw new Error("矩阵输入超出预算");const r=Cn(t.rowFields,t.hierarchy.row,t.hierarchy),n=Cn(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=Ln(0,t,r,n);for(const s of e){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("矩阵数据行应为对象");Tn(r,s),Tn(n,s),i=Ln(e.length,t,r,n)}return{row:r,column:n,shape:i}}function yc(e,t){return Fo(e,t).shape}function wc(e,t,r){const n=new Map;for(const o of e){const i=Dn(r.row,o,!!t.totals),s=Dn(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=>ce({...d,field:d.valueField??d.field})),c.set(u,f)),f.forEach(d=>d.add(o))}}}return n}function bc(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 xc(e,t){return e.kind==="total"?t.hierarchy.totalLabel??"合计":[...e.labels,...e.kind==="subtotal"?[t.hierarchy.subtotalLabel??"小计"]:[]].join(" / ")}function vc(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:`${xc(r,t)} · ${n.label??`${n.field} (${n.op})`}`,semanticRole:"measure",...n.digits===void 0?{}:{format:{kind:"number",digits:n.digits}}}})]}function Mc(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 Sc(e,t){const r=Fo(e,t),n=jn(r.row,!!t.totals),o=bc(jn(r.column,!!t.totals),t),i=wc(e,t,r);return{columns:vc(o,t),rows:Mc(n,o,t,i),headerGrid:pc(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 $c(e,t){const r=()=>t.measures.map(c=>ce(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 Et(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 Ec(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 Ur(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(Ec(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(ce({...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&&dc(e.hierarchy,e.rowFields,e.columnFields)}function Ro(e,t){if(Ur(t),t.hierarchy)return yc(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(Et(s,t.rowFields).key),n.add(Et(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 Ac(e,t){if(t?.hierarchy)return Ur(t),Sc(e,t);Ro(e,t);const r=$c(e,{row:s=>Et(s,t.rowFields),column:s=>Et(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 kc=96;function Pc(e,t=kc){return e*t/72}function it(e,t=96,r=Br){if(e?.fontSizePx!=null)return{fontSizePt:e.fontSizePx*72/t,fontSizePx:e.fontSizePx};const n=e?.fontSize??r;return{fontSizePt:n,fontSizePx:Pc(n,t)}}function Nc(e){return e?.lineHeight??_t}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 Oc(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 Bn(e,t,r){return e?.length?Oc(e,t):Array.from({length:r},(n,o)=>({pos:t*o/r,size:t/r}))}function br(e,t,r){const n=e.cells??[],o=Math.max(n.length,1),i=e.colWidthsMm?.length??n.reduce((p,x)=>Math.max(p,Array.isArray(x)?x.length:0),1),s=Bn(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=Bn(e.rowHeightsMm,r,o),u=p=>p<=0?0:p>=o?c[c.length-1].pos+c[c.length-1].size:c[p].pos,f=new Set,d=(p,x)=>`${p}:${x}`,l=[],m=new Set,h=new Set,g=(p,x)=>`v${p}:${x}`,y=(p,x)=>`h${p}:${x}`;n.forEach((p,x)=>{if(!Array.isArray(p))return;let b=0;for(const S of p){for(;b<i&&f.has(d(x,b));)b++;if(b>=i)break;const C=Math.max(1,Math.min(S?.colSpan??1,i-b)),B=Math.max(1,S?.rowSpan??1),v=Math.min(o,x+B),k=Math.min(i,b+C);for(let M=x;M<v;M++)for(let O=b;O<k;O++)f.add(d(M,O));for(let M=b+1;M<k;M++)for(let O=x;O<v;O++)m.add(g(M,O));for(let M=x+1;M<v;M++)for(let O=b;O<k;O++)h.add(y(M,O));const P=a(b),j=u(x);l.push({ri:x,ci:b,cell:S??{},xMm:P,yMm:j,widthMm:a(k)-P,heightMm:u(v)-j}),b=k}});const w=[];for(let p=1;p<i;p++){let x=-1;for(let b=0;b<=o;b++){const S=b<o&&!m.has(g(p,b));S&&x<0&&(x=b),!S&&x>=0&&(w.push({kind:"v",pos:a(p),from:u(x),to:u(b)}),x=-1)}}for(let p=1;p<o;p++){let x=-1;for(let b=0;b<=i;b++){const S=b<i&&!h.has(y(p,b));S&&x<0&&(x=b),!S&&x>=0&&(w.push({kind:"h",pos:u(p),from:a(x),to:a(b)}),x=-1)}}return{columns:s,rows:c,cells:l,edges:w}}function Ic(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 Fc(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 Co(e,t,r,n){return r==="identifier"||r==="dimension"||r==="date"||r==="measure"?"center":r==="text"?"left":ue.automaticCellAlignment(e,t?.kind==="number"||t?.kind==="percent"||t?.kind==="date"||n==="number"||n==="boolean")}function Gr(e){if(e==null)return"";if(typeof e=="string"||typeof e=="number")return String(e);if(typeof e=="boolean")return e?"是":"否";if(e instanceof Date)return e.toISOString().slice(0,10);try{return JSON.stringify(e)}catch{return String(e)}}function To(e,t){let r=ee({fontSize:e.fontSizePt??Br,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 Rc(e,t){return{member:"body",subtotal:"subtotal",total:"grand-total"}[e?.rows.get(t)?.kind??"member"]}function Cc(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 Tc(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=Ac(t,Cc(e)),n=r.columns.map(a=>({...a,widthMm:a.semanticRole==="dimension"?e.matrix.rowWidthMm??40:e.matrix.columnWidthMm??28,editable:!1,align:e.align??"auto"})),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 jc(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=br({...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={...To(e,e.columns[u]),...c.style},m=it(l).fontSizePt,g=(ye(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??_t)*25.4/72+r*2)/(c.rowSpan??1);for(let y=f;y<f+(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(u=>u?{...u,style:s.get(u)}:null));return{...e.headerGrid,cells:a,rowHeightsMm:n}}class jo extends Error{constructor(t){super(`树节点超出行数预算 ${t}`),this.limit=t,this.code="tree-row-limit",this.name="TreeRowLimitError"}}function ir(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 Yr(e){return{rows:ir(e.maxRows,1e5,1e6,"树行数预算"),depth:ir(e.maxDepth,64,256,"树深度预算"),visits:ir(e.maxAggregationVisits,1e6,1e7,"树聚合访问预算")}}function Do(e){return typeof e=="string"&&!!e.trim()}function Me(e){return Do(e)&&!["__proto__","prototype","constructor"].includes(e)}function Lo(e){if(Do(e)||typeof e=="number"&&Number.isFinite(e))return e;throw new Error("树节点业务键应为非空字符串或有限数字")}function Bo(e){return JSON.stringify([typeof e,e])}function _o(e){return[e.idField,...e.input==="flat"?[e.parentField??""]:[e.childrenField??"children"]]}function qr(e,t){const r=_o(e);if(t?.some(n=>n.scope&&n.scope!=="row"||r.includes(n.field)))throw new Error("树形布局仅支持不覆盖结构键的当前行计算")}function Ne(e){if(!e?.aborted)return;const t=new Error("树报表处理已取消");throw t.name="AbortError",t}function Dc(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||!Me(n.field)||r.has(n.field))throw new Error("树聚合输出字段应安全、非空且唯一");for(const o of[n.valueField,n.weightField])if(o!==void 0&&!Me(o))throw new Error("树聚合来源字段应安全且非空");if([..._o(e),e.labelField].includes(n.field))throw new Error("树聚合不能覆盖结构键或标签字段");r.add(n.field),ce({...n,field:n.valueField??n.field})}}function Lc(e){if(!Me(e.idField)||!Me(e.labelField))throw new Error("树需要安全的业务键和标签字段");if(e.input==="flat"&&(!Me(e.parentField)||e.parentField===e.idField))throw new Error("扁平树需要独立的父键字段");if(e.childrenField!==void 0&&!Me(e.childrenField))throw new Error("子节点字段应安全且非空");if(e.input==="nested"&&[e.idField,e.labelField].includes(e.childrenField??"children"))throw new Error("子节点字段不能覆盖业务键或标签字段")}function Ko(e){if(!e||typeof e!="object"||!["flat","nested"].includes(e.input))throw new Error("树输入应为 flat 或 nested");if(Lc(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");Yr(e),Dc(e)}function Wo(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("树节点应为对象");if(r.size>=n.rows)throw new jo(n.rows);const o=Lo(e[t.idField]),i=Bo(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 Bc(e,t,r,n,o){for(const s of e)Ne(o),Wo(s,t,r,n);const i=[];for(const s of r.values()){Ne(o);const a=s.row[t.parentField];if(a==null){i.push(s);continue}const c=r.get(Bo(Lo(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 _c(e,t,r,n,o){const i=[],s=[{rows:e,next:0}];for(;s.length;){Ne(o);const a=s[s.length-1];if(a.next>=a.rows.length){s.pop();continue}const c=Wo(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 Kc(e,t,r,n){const o=[],i=[{nodes:e,next:0}];for(;i.length;){Ne(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 Wc(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=>ce({...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(Ne(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 zo(e,t,r){if(Ko(t),Ne(r),!Array.isArray(e))throw new Error("树数据应为节点数组");const n=Yr(t),o=new Map,i=t.input==="flat"?Bc(e,t,o,n,r):_c(e,t,o,n,r);return Kc(i,o.size,n,r)}function Vo(e,t,r){return zo(e,t,r).map(n=>n.original)}function Ho(e,t,r={}){const n=zo(e,t,r.signal);if(qr(t,r.computed?.fields),r.computed?.fields.length){const o=zt(n.map(i=>i.row),{...r.computed,signal:r.signal}).rows;n.forEach((i,s)=>{i.row=o[s]})}return Wc(n,t,Yr(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 zc(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 Vc(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:zc(e.headerGrid,t,r.map(n=>n.widthMm))}:{}}}function Xr(e){return e.kind==="list"?e.id:e.nid}function Hc(e){return e.kind==="list"?!1:e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&/\{(?:page|totalPages)\}/.test(e.text)}function Jc(e,t){const r=e.filter(o=>t.componentIds.includes(Xr(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 Uc(e,t){if(!t)return e.map(n=>({components:[n]}));const r=new Map(e.map(n=>[Xr(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 Jo(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(Hc(o))continue;const i=Xr(o);if(!i||r.has(i))throw new Error("流式排版组件应具有唯一标识");r.add(i)}if(Gc(e,t,r,n),n.size!==r.size)throw new Error("流式排版必须显式包含每个非锚点组件")}function Gc(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)}Jc(e,i),o=i.topMm+i.heightMm}}function*Yc(e){const{page:t}=e;Jo(t.components,t.flow);let r=0,n=0;for(const o of Uc(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 qc(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 Zr(e){return e.pages.some(t=>t.components.some(r=>r.kind==="list"?qc(r):!!r.chartBinding))}const Xc=new Set(["__proto__","prototype","constructor"]);function ie(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function dt(e){return typeof e=="string"&&!!e.trim()&&!Xc.has(e)}function At(e,t,r,n){for(const o of Object.keys(e))t.includes(o)||n.push({path:`${r}.${o}`,message:"存在未知配置字段"})}function Zc(e,t,r){if(e!==void 0){if(!ie(e)||!["number","percent","date"].includes(String(e.kind))){r.push({path:t,message:"绑定格式应为 number、percent 或 date"});return}At(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 Qc(e,t,r){const n=e.binding;if(n===void 0)return;const o=`${t}.binding`;if(!ie(n)){r.push({path:o,message:"字段绑定应为对象"});return}(!["text","image","barcode","qrcode"].includes(String(e.kind))||e.grid!==void 0)&&r.push({path:o,message:"绑定仅支持独立文本、图片、条码与二维码组件"}),At(n,["field","format","prefix","suffix","emptyText"],o,r),dt(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:"应为字符串"});Zc(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 eu(e,t){if(!ie(e)){t.push({path:"$.repeat",message:"逐记录配置应为对象"});return}At(e,["dataset","rowKey","copies"],"$.repeat",t),dt(e.dataset)||t.push({path:"$.repeat.dataset",message:"数据集应为安全的非空名称"}),e.rowKey!==void 0&&!dt(e.rowKey)&&t.push({path:"$.repeat.rowKey",message:"业务主键应为安全的非空字段名"});const r=e.copies;r!==void 0&&(ie(r)?(At(r,["field"],"$.repeat.copies",t),dt(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 Uo(e,t,r,n){if(!ie(e))return;Qc(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;ie(o)&&Array.isArray(o.cells)&&o.cells.forEach((i,s)=>{Array.isArray(i)&&i.forEach((a,c)=>{ie(a)&&Array.isArray(a.children)&&a.children.forEach((u,f)=>Uo(u,`${t}.grid.cells.${s}.${c}.children.${f}`,r,n))})})}function Go(e,t){const r=e.repeat!==void 0;r&&eu(e.repeat,t),Array.isArray(e.pages)&&e.pages.forEach((n,o)=>{if(!ie(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(Uo(s,c,r,t),!r||!ie(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 tu=512,_n=256*1024;function ru(){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=ye(n,o,i,s),f=a.length+u.reduce((d,l)=>d+l.length,0);if(f<=_n){for(;e.size>=tu||t+f>_n;){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 nu(e){return typeof e=="string"&&/^data:image\/(png|jpe?g);base64,[A-Za-z0-9+/\r\n]+=*$/.test(e)}class J extends Error{constructor(t,r,n,o){super(`${t}: ${r}`),this.path=t,this.rowIndex=n,this.field=o,this.code="report-binding",this.name="ReportBindingError"}}function Qr(e,t,r={}){const n=r.rowIndex??0,i=`$.datasets.${r.dataset??"label"}[${n}].${t}`,s=Object.getOwnPropertyDescriptor(e,t);if(!s||s.get||s.set)throw new J(i,"字段必须是记录的自有数据字段,不能缺失、使用访问器或从原型继承",n,t);const a=s.value;if(a==null||typeof a=="string"||typeof a=="boolean"||typeof a=="number"&&Number.isFinite(a))return a;throw new J(i,"绑定值应为字符串、有限数字、布尔值或空值",n,t)}function ou(e,t,r={}){const n=Qr(t,e.field,r);return n==null||n===""?e.emptyText??"":`${e.prefix??""}${Wr(n,e.format)}${e.suffix??""}`}const iu=1e4,Kn=25e4;function en(e){if(e?.aborted)throw e.reason??new DOMException("标签生成已取消","AbortError")}function Yo(e,t,r){const n=typeof e.copies=="object"?Qr(t,e.copies.field,r):e.copies??1;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>1e3)throw new J(`$.datasets.${r.dataset}[${r.rowIndex}]`,"每条记录复制数必须是 1..1000 的数值型整数",r.rowIndex,typeof e.copies=="object"?e.copies.field:void 0);return n}function qo(e,t,r){if(e.rowKey===void 0)return;const n=Qr(t,e.rowKey,r);if(typeof n=="string"&&n.trim()||typeof n=="number"&&Number.isFinite(n))return n;throw new J(`$.datasets.${r.dataset}[${r.rowIndex}].${e.rowKey}`,"业务主键必须是非空字符串或有限数字",r.rowIndex,e.rowKey)}function su(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 au(e,t,r){const n=e.repeat,o=Object.prototype.hasOwnProperty.call(t,n.dataset)?t[n.dataset]:void 0;if(!Array.isArray(o))throw new J(`$.datasets.${n.dataset}`,"逐记录标签数据集缺失,应提供对象数组(允许空数组)");const i=new Set,s=r.maxPages??iu,a=su(e);let c=0,u=0;for(const[f,d]of o.entries()){if(en(r.signal),!d||typeof d!="object"||Array.isArray(d))throw new J(`$.datasets.${n.dataset}[${f}]`,"标签记录应为对象",f);const l={rowIndex:f,dataset:n.dataset},m=qo(n,d,l);if(m!==void 0){const g=JSON.stringify([typeof m,m]);if(i.has(g))throw new J(`$.datasets.${n.dataset}[${f}].${n.rowKey}`,"业务主键重复;请先确认记录来源,避免重复打印标签",f,n.rowKey);i.add(g)}const h=Yo(n,d,l);if(c+=h*e.pages.length,u+=h*a,c>s)throw new Pe(s,c);if(u>Kn)throw new J("$.repeat",`标签组件总量(含网格行、槽位及嵌套组件)超过安全预算 ${Kn},请分批生成`,f)}return o}function cu(e,t,r){if(!e.binding)return e;const{binding:n,...o}=e,i=ou(n,t.row,t);if(e.kind==="image"){if(!i)return;if(!nu(i))throw new J(`${r}.binding`,"图片字段只接受 PNG/JPEG base64 data URL;业务 URL 应由宿主安全加载后转换",t.rowIndex,n.field);return{...o,imageData:i}}return e.kind==="barcode"||e.kind==="qrcode"?(delete o.imageData,{...o,code:{...o.code,value:i},fallbackText:i}):(delete o.lines,delete o.richParagraphs,{...o,text:i})}function uu(e,t,r){if(e.kind!=="text"||e.grid||e.richParagraphs?.length)return e;const n=e.style??{},o=it(n).fontSizePt,i=e.text??e.lines?.join(`
|
|
5
|
+
`)??"";if(i.length>16384)throw new J(r,"标签文本超过 16384 字符预算,请缩小字段内容",t.rowIndex);const s=t.wrapText(i,e.widthMm,{fontSizePt:o,bold:n.bold,italic:n.italic,fontFamily:n.fontFamily,letterSpacingPt:n.letterSpacing},t.options.measurer??qe),a=s.length*o*Nc(n)*25.4/72;if(a>e.heightMm+.05)throw new J(r,`标签文字需要约 ${a.toFixed(2)}mm 高,超出 ${e.heightMm}mm;请增大文本区域、减少内容或调整字号`,t.rowIndex,e.binding?.field);return{...e,lines:s}}function Xo(e,t,r){en(t.options.signal);const n=cu(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=Xo(u,t,`${r}.grid.cells.${s}.${c}.children.${f}`);return d?[d]:[]})}:a))}),uu(o===n.grid?n:{...n,grid:o},t,r)}function fu(e,t,r,n,o,i){return{...e,components:e.components.flatMap((s,a)=>{const c=Xo(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*lu(e,t,r){const n=[];if(Go(e,n),n.length)throw new J(n[0].path,n[0].message);if(!e.repeat){for(const[a,c]of e.pages.entries())yield{page:c,pageIndex:a};return}const o=e.repeat,i=au(e,t,r),s=ru();for(const[a,c]of i.entries()){const u={row:c,rowIndex:a,dataset:o.dataset,options:r,wrapText:s},f=Yo(o,c,u),d=qo(o,c,u);for(let l=0;l<f;l++)for(const[m,h]of e.pages.entries())en(r.signal),yield{page:fu(h,m,u,l,f,d),pageIndex:m}}}const du=/^#[0-9a-f]{6}$/i;function Zo(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"&&du.test(n))}function Qo(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 mu(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 sr(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 hu(e,t,r,n){const o=new WeakMap;return{apply(i,s){const a=Qo(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=sr(0,l,m),g=l===m?h:sr(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=mu(e.lowColor??"#f0f7ff",e.highColor??"#8bbcf1",sr(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 gu(e,t,r){return e.map(n=>{Wn(r);const o=n.visual;if(!o)return;if(!Zo(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&&Wn(r);const l=Qo(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),hu(o,i,u,f)})}function Wn(e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError")}function pu(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 kt(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 et(e){return e.components.reduce((t,r)=>r.kind!=="list"&&r.pageAnchor==="header"?Math.max(t,r.topMm+r.heightMm):t,0)}function ei(e,t){let r=e.textMetrics.get(t);if(!r){const n=it(t).fontSizePt;r={measureOptions:{fontSizePt:n,fontFamily:t.fontFamily??_r,italic:t.italic,bold:t.bold,letterSpacingPt:t.letterSpacing},lineMm:n*(t.lineHeight??_t)*25.4/72},e.textMetrics.set(t,r)}return r}function yu(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function tn(e,t,r=[],n){const o=e.fontSizePt??Br,i=e.paddingMm??1,s=e.columns.map(w=>w.align??w.style?.align??e.align??"auto"),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),u=e.columns.map((w,p)=>w.rules?.map(x=>{const b=c[p];if(b)return{left:ee(b.left,x.style),center:ee(b.center,x.style),right:ee(b.right,x.style)};const S=ee(a[p],x.style);return{left:S,center:S,right:S}})),f=e.columns.map(w=>To(e,w)),d=e.columns.map(w=>w.header);let l=e.rowHeightMm??0;for(let w=0;w<d.length;w++){const p=f[w],x=it(p).fontSizePt,b=ye(d[w],e.columns[w].widthMm-i*2,{fontSizePt:x,fontFamily:p.fontFamily??_r,italic:p.italic,bold:p.bold,letterSpacingPt:p.letterSpacing},t),S=x*(p.lineHeight??_t)*25.4/72;l=Math.max(l,Math.max(b.length,1)*S+i*2)}const m=d.map((w,p)=>({text:w,style:f[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=wu(jc(e,t),g,{cells:[m],colWidthsMm:g,rowHeightsMm:[l],paddingMm:i});return{fontSizePt:o,paddingMm:i,visuals:gu(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:u,textMetrics:new WeakMap,numberFormats:e.columns.map(w=>ko(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 wu(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 bu(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 tt(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]?Co(f,c.format,c.semanticRole,c.valueType):"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?Wr(f,c.format):Gr(f),h=xu(e,c,o);l=vu(e,c,l,o);const g=ei(e,l),y=ye(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=yu(f),p={text:m,style:l};f!=null&&e.visuals[a]?.apply(p,t),w!==void 0&&(p.value=w),bu(p,c,e.numberFormats[a]),Mu(p,c,e,o,h),e.derivedFields.has(c.field)&&(p.derived=!0,p.editable=!1),u||(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 xu(e,t,r){return!r||t.field!==e.tree.list.tree.labelField?0:Ic(e.tree.list,t,r,e.paddingMm)}function vu(e,t,r,n){return!n||t.field!==e.tree.list.tree.labelField||r.align==="left"?r:{...r,align:"left"}}function Mu(e,t,r,n,o=0){n&&(o&&(e.indentMm=o),Fc(e,t,n,r.tree.list))}function ti(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*ri(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=ti(i[n.field]),a=o.get(s);a?a.push(i):o.set(s,[i])}for(const i of o.values())yield{kind:"groupHeader",label:(n.headerTemplate??"{value}").replace(/\{value\}/g,Gr(i[0][n.field])),firstRow:i[0],group:n,depth:r,rows:i},yield*ri(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 ni(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=Xe(t,{...i,field:i.valueField??i.field});return[i.field,{text:Wr(a,s),...a===null?{}:{value:a},...typeof a=="number"?{numberFormat:ko(s)}:{}}]}))}function oi(e,t){const r=e.findIndex(n=>t.includes(n.field));return r<0?1:r}function Ke(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]?.[Co(h?.value,m.format,m.semanticRole,m.valueType)]??e.cellStyles[l];s.push({...h,text:h?.text??"",style:ee(g,o)})}const u={text:r,colSpan:e.columns.length,style:{bold:!0,...c}},f=a?[s]:[[u],s],d=f.map(l=>Su(e,l,t));return{grid:{cells:f,colWidthsMm:e.colWidthsMm,rowHeightsMm:d,paddingMm:e.paddingMm},heightMm:d.reduce((l,m)=>l+m,0)}}function Su(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=ei(e,i.style),u=ye(i.text??"",s-e.paddingMm*2,c.measureOptions,r);n=Math.max(n,u.length*c.lineMm+e.paddingMm*2)}return n}function $u(e,t,r){const{templatePage:n,current:o,warnings:i,nextId:s,pushCurrent:a}=r,c=()=>kt(n,o),u=Math.max(o.marginTopMm,et(n)),f=n.layout==="wide"?et(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}:{}}}:{}},g=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 y=Math.max(r.startTop??e.topMm,u);e.header!==!1&&(g(y),y+=t.headerHeightMm+r.mmPerRow);function w(){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((P,j)=>P+j.heightMm,0)}function p(){const v=n.layout==="wide"?0:o.marginBottomMm;return Math.min(n.heightMm-v,kt(n,o))-w()}function x(v){if(y+v<=c())return;a(),o.components=[],o.heightMm=n.heightMm,n.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0);const k=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);e.header!==!1&&e.headerEveryPage!==!1?(g(k),y=k+t.headerHeightMm):y=f;for(const P of m.values())S(P,"listgr","group-header")}function b(v,k,P,j){const M=p();if(r.flow&&v.heightMm>M+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的单行高度超出单页可用范围`);v.heightMm>M&&i.push(`列表 ${e.id??e.dataset} 行高 ${v.heightMm.toFixed(2)}mm 超出单页可用高度 ${M.toFixed(2)}mm,预览与打印可能截断内容`),x(v.heightMm),S(v,k,P,j)}function S(v,k,P,j){const M=v.table?.id??d.id,O=P==="header"?-1:l.get(M)??0;P!=="header"&&l.set(M,O+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(k),table:{...d,...v.table,role:P,rowIndex:O,...j?{source:j}:{}},style:t.borderStyle,...e.meta||v.meta?{meta:{...e.meta,...v.meta}}:{}}),y+=v.heightMm}function C(v){v<=p()&&x(v)}return{keepTogether:C,placeGridRow:b,setGroupHeader:(v,k)=>{k?m.set(v,k):m.delete(v)},bottom:()=>y}}function Eu(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 Ht(e,t){const r=new Map;if(!e.rowKey)return r;const n=new Set;for(const o of t){const i=Eu(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 Au(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=Ke(r,n.measurer,i?.label??"合计",ni(e.columns,t,a,c),i?.style??{},oi(e.columns,[...a,...c.map(f=>f.field)]));o.placeGridRow(u,"listgt","grand-total")}function fe(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 rn(e){const t=Vc(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 ku(e,t,r){const n=e.detail;if(!n)return;const o=new Set;for(const u of t){const f=xr(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(!ii(f)&&n.unmatched==="ignore")continue;const d=xr(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=rn({...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:{...tn(c,r.measurer,a,r.signal),rowHeightFloorMm:c.rowHeightMm??0},rows:s,sources:Ht(c,a)}}function ii(e){return typeof e=="string"&&!!e.trim()||typeof e=="number"&&Number.isFinite(e)}function xr(e){if(!ii(e))throw new Error("主从关联键必须是非空字符串或有限数字");return ti(e)}function*Pu(e,t,r,n,o){if(!r)return;const i=r.rows.get(xr(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({...Ke(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)fe(n.signal),o.placeGridRow({...tt(r.inter,a,n.measurer),table:s},"listdr","body",r.sources.get(a)),yield*n.takePages()}function si(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("树形布局需要可见的标签列");qr(e.tree,e.computed)}function Nu(e,t,r){si(e);const n=Ho(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=Ht(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 Ou(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 ai(e,t,r){const n=r.prepared.get(e);if(n)return n;const o=Ou(e,t);if(o)return r.prepared.set(e,o),o;if(e.tree){const c=Nu(e,t,r);return r.prepared.set(e,c),c}let i=e.computed?.length?zt(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=Tc(e,i);if(!e.matrix){const c=Ht(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 Iu(e,t,r,n){if(!n.flow)return;const{current:o,templatePage:i}=n,s=Math.max(o.marginTopMm,et(i)),a=Math.max(n.startTop??e.topMm,s),c=(e.header===!1?0:t.headerHeightMm)+(r[0]?tt(t,r[0],n.measurer).heightMm:0);a+c<=kt(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,et(i)))}function*Fu(e,t,r){const n=ai(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??Ht(e,o),s=rn(e),a=Jt(s),c={...tn(s,r.measurer,o,r.signal),rowHeightFloorMm:s.rowHeightMm??0,matrix:n.matrix,...n.treeRows?{tree:{list:s,rows:n.treeRows}}:{}};Iu(s,c,o,r);const u=$u(s,c,r),f=ku(s,o,r);let d;for(const l of ri(o,a)){if(fe(r.signal),l.kind==="row")u.placeGridRow(d??tt(c,l.row,r.measurer),"listr",Rc(n.matrix,l.row),i.get(l.row)),d=void 0,yield*r.takePages(),yield*Pu(s,l.row,f,r,u);else if(l.kind==="groupHeader"){const m=Ke(c,r.measurer,l.label,new Map,l.group.headerStyle??{},s.columns.length);d??=tt(c,l.firstRow,r.measurer);const h=a.slice(l.depth+1).reduce((g,y)=>g+Ke(c,r.measurer,(y.headerTemplate??"{value}").replace(/\{value\}/g,Gr(l.firstRow[y.field])),new Map,y.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??[],g=Ke(c,r.measurer,l.label,ni(s.columns,l.rows,m,h),l.group.subtotalStyle??{},oi(s.columns,[...m,...h.map(y=>y.field)]));u.placeGridRow(g,"listst","subtotal")}else u.setGroupHeader(l.depth);yield*r.takePages()}Au(s,n.totalRows??o,c,r,u),r.finished?.(u.bottom()),yield*r.takePages()}function nn(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 on(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=>on(o,t))}:{}}:null))}}:{}}}function Ru(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(on(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 sn(e){return e.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+ci(s),0)??0):0),0),0)}function ci(e){return e.grid?sn(e.grid):0}function ui(e){for(const t of["maxPages","maxCells","knownTotalPages"])if(e[t]!==void 0&&(!Number.isSafeInteger(e[t])||e[t]<1))throw new RangeError(`${t} 应为正安全整数`);Vt(e.maxChartComponents)}function Cu(e,t){const r=ai(e,t.datasets[e.dataset]??[],t),n=rn(r.list),o={...tn(n,t.measurer,r.rows,t.signal),rowHeightFloorMm:n.rowHeightMm??0};return(n.header===!1?0:o.headerHeightMm)+r.rows.reduce((i,s)=>i+tt(o,s,t.measurer).heightMm,0)}function*Tu(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??""} 输出为空`),Fu(i,Array.isArray(c)?c:[],{...e,tableId:`${e.tableId}:${n.get(i)}`,startTop:s,finished:a,flow:!!t.flow})};if(t.flow){yield*Yc({page:t,active:()=>fe(e.signal),top:()=>Math.max(r.marginTopMm,et(t)),bottom:()=>kt(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=>Cu(i,e),list:o});return}for(const i of t.components)nn(i)||(i.kind==="list"?yield*o(i):r.components.push(...e.resolveChart(i)))}function*fi(e,t,r,n,o,i=new WeakMap,s){let a=0,c=0,u=0;const f=ua(r.measurer??qe),d=lc(t,r.signal,r.maxChartComponents),l=m=>`${m}_${(++a).toString(36)}`;for(const{pageIndex:m,page:h}of lu(e,t,r)){fe(r.signal);const g=pu(h),y=h.components.filter(nn);let w=[];const p=(b=!1)=>{if(fe(r.signal),r.maxPages!==void 0&&c>=r.maxPages)throw new Pe(r.maxPages,c+1);if(r.maxCells!==void 0&&(u+=[...g.components,...y].reduce((S,C)=>S+ci(C),0),u>r.maxCells))throw new Ze(r.maxCells,u);w.push(Ru(h,g,y,++c,b,o))},x=()=>{const b=w;return w=[],b};yield*Tu({templatePage:h,current:g,warnings:n,nextId:l,pushCurrent:p,takePages:x,datasets:t,resolveChart:d,signal:r.signal,formula:r.formula,prepared:i,measurer:f,mmPerRow:r.mmPerRow??0,tableId:`table:${m}`}),p(!0),yield*x()}s&&(s.chartComponents=d.used())}function ju(e,t,r={}){const n=typeof r=="number"?{mmPerRow:r}:r;ui(n);const o=[],i={chartComponents:0},s=[...fi(e,t,n,o,n.knownTotalPages,void 0,i)];return di(e,n,s,o,i)}async function li(e,t,r={}){ui(r),fe(r.signal);const n=[],o=[],i={chartComponents:0};let s=performance.now(),a=0;for(const c of fi(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)),fe(r.signal),s=performance.now(),a=0);return fe(r.signal),di(e,r,o,n,i)}function di(e,t,r,n,o){for(const i of r)i.components=i.components.map(s=>nn(s)?on(s,a=>a.replace(/\{totalPages\}/g,String(r.length))):s);return n.forEach(i=>t.onWarning?.(i)),{plan:{schemaVersion:nt,...Zr(e)?{requiresRecalculation:!0}:{},pages:r},warnings:n,...o}}function Du(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 Lu(e,t,r){si(e);const n=Vo(t[e.dataset]??[],e.tree,r),o=e.columns.filter(s=>!s.hidden).length,i=e.header===!1?0:e.headerGrid?sn(e.headerGrid):o;return n.length*o+i+ +!!e.grandTotal*2*o}function Bu(e,t,r={}){if(e.tree)return Lu(e,t,r.signal);if(e.matrix){let c=t[e.dataset]??[];e.computed?.length&&(c=zt(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=Du(e);let a=(n*(1+2*i+s.groups)+ +!!e.grandTotal*(1+s.total))*o;if(a+=e.header===!1?0:e.headerGrid?sn(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 _u(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 mt(e){return!!e&&typeof e=="object"}function mi(e,t,r,n,o){if(++o.nodes>1e6)return{path:t,message:"组件树超过100万个结构节点预算"};if(mt(e)){if(r>64)return{path:t,message:"组件嵌套超过64层预算"};if(n.has(e))return{path:t,message:"组件树包含循环引用"};if(!(!mt(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(!(!mt(c)||!Array.isArray(c.children)))for(const[u,f]of c.children.entries()){const d=mi(f,`${t}.grid.cells.${i}.${a}.children.${u}`,r+1,n,o);if(d)return d}}}finally{n.delete(e)}}}}function an(e,t="$.components",r={nodes:0}){for(const[n,o]of e.entries()){const i=mi(o,`${t}.${n}`,0,new Set,r);if(i)return i}}function hi(e){const t={nodes:0};for(const[r,n]of e.entries()){if(!mt(n)||!Array.isArray(n.components))continue;const o=an(n.components,`$.pages.${r}.components`,t);if(o)return o}}function Ku(e){const t=hi(e.pages);if(t)throw new TypeError(`${t.path}: ${t.message}`)}function Wu(e,t,r){e!==void 0&&(typeof e!="string"||!e.trim()||e.length>4096)&&r.push({path:t,message:"来源范围应为不超过 4096 字符的非空字符串"})}function gi(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 zu(e,t,r){gi(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:"派生结果标记应为布尔值"}),pi(e.source,`${t}.source`,r,!0),e.formula!==void 0&&typeof e.formula!="string"&&r.push({path:`${t}.formula`,message:"单元格公式应为字符串"})}function pi(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;Wu(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 Vu(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 Hu(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 Ju(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return[{path:"",message:"code must be an object."}];const r=e,n=[...Vu(r),...Hu(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 Uu=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function V(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pt(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 Gu(e,t,r,n){const o=e[t];(typeof o!="number"||!Number.isFinite(o))&&n.push({path:`${r}.${t}`,message:`应为有限数字,实际 ${Pt(o)}`})}function Yu(e,t,r){if(e!==void 0){const n=`${t}.table`;if(!V(e))r.push({path:n,message:"逻辑表来源应为对象"});else{pi(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 qu(e,t,r,n){if(e!==void 0)if(!V(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(!V(a)){r.push({path:u,message:"网格单元格应为对象或 null"});return}zu(a,u,r),a.dataBar!==void 0&&!_u(a.dataBar)&&r.push({path:`${u}.dataBar`,message:"数据条应包含 0–1 有序比例与 #RRGGBB 颜色"}),yi(a.richParagraphs,u,r),Array.isArray(a.children)&&a.children.forEach((f,d)=>{cn(f,`${t}.grid.cells.${s}.${c}.children.${d}`,r,n)})})})}}function Nt(e,t,r,n){e!==void 0&&!t.includes(e)&&n.push({path:r,message:"未知富文本属性值"})}function vr(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 Xu(e,t,r){if(e!==void 0){if(!V(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:"富文本样式应为布尔值"});vr(e,["fontSize","fontSizePx","lineWidthPt","lineHeight","opacity"],t,r),vr(e,["letterSpacing","rotateDeg"],t,r,-1/0),typeof e.opacity=="number"&&e.opacity>1&&r.push({path:`${t}.opacity`,message:"透明度不能大于1"}),Nt(e.align,["left","center","right","justify"],`${t}.align`,r),Nt(e.verticalAlign,["top","middle","bottom"],`${t}.verticalAlign`,r)}}function Zu(e,t,r){if(!V(e)){r.push({path:t,message:"富文本片段应为对象"});return}Nt(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:"富文本内容应为字符串"});Xu(e.style,`${t}.style`,r)}function yi(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(!V(n)||!Array.isArray(n.segments)){r.push({path:i,message:"段落缺少 segments 数组"});return}Nt(n.align,["left","center","right","justify"],`${i}.align`,r),vr(n,["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"],i,r),n.segments.forEach((s,a)=>Zu(s,`${i}.segments.${a}`,r))})}}function wi(e,t,r,n=[]){const o=an([e],t);if(o){r.push(o);return}cn(e,t,r,n)}function cn(e,t,r,n=[]){if(!V(e)){r.push({path:t,message:"组件应为对象"});return}const o=e.kind;typeof o!="string"?r.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):Uu.has(o)||n.push({path:`${t}.kind`,message:`未知组件类型 ${Pt(o)},将以兜底方式渲染`});for(const i of["leftMm","topMm","widthMm","heightMm"])Gu(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:"组件尺寸不能为负数"});Yu(e.table,t,r),ef(e.code,o,t,r),Qu(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"}),qu(e.grid,t,r,n),yi(e.richParagraphs,t,r)}function Qu(e,t,r){if(e.chartBinding!==void 0)try{if(Oo(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 ef(e,t,r,n){if(e!==void 0)for(const o of Ju(e,t))n.push({path:`${r}.code${o.path?`.${o.path}`:""}`,message:o.message})}function bi(e,t,r){if(!V(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;!V(n)||!Array.isArray(n.cells)||n.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((s,a)=>{!V(s)||!Array.isArray(s.children)||s.children.forEach((c,u)=>bi(c,`${t}.grid.cells.${i}.${a}.children.${u}`,r))})})}function tf(e,t,r,n=[]){if(!V(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:`页宽非法: ${Pt(o)}`}),(typeof i!="number"||!(i>0&&i<5e3))&&r.push({path:`${t}.pageHeightMm`,message:`页高非法: ${Pt(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=an(s,`${t}.components`);if(a){r.push(a);return}s.forEach((c,u)=>{cn(c,`${t}.components.${u}`,r,n),bi(c,`${t}.components.${u}`,r)})}}function Re(e){const t=[],r=[],n=V(e)?e.pages:void 0;if(V(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=hi(n);if(o)return{ok:!1,errors:[...t,o],warnings:r};n.forEach((s,a)=>tf(s,`$.pages.${a}`,t,r)),n.length>2e3&&r.push({path:"$.pages",message:`页数异常大(${n.length} 页),渲染与打印耗时可能显著增加`});const i=n.reduce((s,a)=>s+(V(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 Ot(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 un=100,xi=16,Mr=104857;function vi(e,t,r){if(typeof e=="string"){if(e.length>Mr)return;try{e=JSON.parse(e)}catch{return}}const n=Ot(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>Mr))return;o.push(s)}return o}function rf(e){return vi(e,un,!0)}function nf(e){return vi(e,xi,!1)}function of(e){if(typeof e=="string"){if(e.length>2048)return;try{e=JSON.parse(e)}catch{return}}const t=Ot(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 Ut(e,t){return e.type==="numberRange"?of(t):e.type==="cascader"?nf(t):rf(t)}function sf(e,t,r=!1){const n=Ot(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>xi)return!1;const f=new Set;for(const d of c){const l=af(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=Ot(l.children,1e3);if(!t||!m)return!1;m.length&&o.push({items:m,depth:u+1})}}}return!0}function Mi(e){return e.map(t=>({value:t.value,label:t.label,...t.children?{children:Mi(t.children)}:{}}))}function af(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 cf(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=Ut(e,t);if(!r)return[["type",e.type==="numberRange"?"请填写完整数字范围,最小值不能大于最大值":e.type==="cascader"?"请选择完整的末级路径":"请选择有效选项,不能重复或超出数量限制"]];if(e.type==="numberRange")return ff(e,r);const n=r,o=[];return e.type==="cascader"&&e.options&&!cf(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 ff(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 lf(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]>un)&&t.push(`${r} 应为多选参数的 0–100 整数边界`);return e.minItems!==void 0&&e.maxItems!==void 0&&e.minItems>e.maxItems&&t.push("最少项目数不能大于最多项目数"),t}function df(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":Mr,type:"array",minItems:Math.max(e.required?1:0,e.minItems??0),maxItems:e.type==="cascader"?16:e.maxItems??un,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:Mi(e.options)}:{}},t}function mf(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 hf(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 It(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 fn(e){return e.length===4&&/^\d{4}$/.test(e)&&e!=="0000"}function Si(e){return e.length===7&&/^\d{4}-(?:0[1-9]|1[0-2])$/.test(e)&&fn(e.slice(0,4))}function $i(e){const[t,r,n]=e.split("/");if(!(n!==void 0||!t||!r||!It(t)||!It(r)||t>r))return{start:t,end:r}}function Ei(e,t){return typeof t!="string"?!1:e==="month"?Si(t):e==="year"?fn(t):(e==="date"||e==="dateRange")&&It(t)}function gf(e,t){if(e==="date"&&!It(t))return"应为有效的 YYYY-MM-DD 日期";if(e==="month"&&!Si(t))return"应为有效的 YYYY-MM 月份";if(e==="year"&&!fn(t))return"应为 0001 至 9999 的四位年份";if(e==="dateRange"&&!$i(t))return"应为完整且有序的 YYYY-MM-DD/YYYY-MM-DD 日期范围"}class Gt extends Error{constructor(t){super(t.map(r=>`${r.field}: ${r.message}`).join("; ")),this.issues=t,this.code="params",this.name="ReportParamValidationError"}}function Ai(e){return/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))}function ki(e,t){if(U(e))return uf(e,t);if(e.type==="number"&&!Ai(t))return[["type","应为有限数字"]];const r=gf(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(...pf(e,t)),n}function pf(e,t){const r=e.type==="dateRange"?$i(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 yf(e){const t=[];for(const o of["min","max"]){const i=e[o];if(i===void 0)continue;Ei(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,...wf(e),...lf(e)]}function wf(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 Yt(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 xf(n,t).map(a=>({code:"definition",field:i,path:`$.paramDefs.${o}`,message:a}))});return r.length?r:hf(e).map(({index:n,message:o})=>({code:"definition",field:e[n].field,path:`$.paramDefs.${n}`,message:o}))}function bf(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&&!sf(e.options,e.type==="cascader",!U(e))&&t.push("选项应为包含字符串 label/value 的数组"),[...t,...mf(e)]}function xf(e,t){if(!e||typeof e!="object"||Array.isArray(e))return["参数定义项应为对象"];const r=bf(e);return typeof e.field!="string"||!e.field.trim()||t.has(e.field)?r.push("参数名应为非空且不重复的字符串"):t.add(e.field),r.length||(r.push(...yf(e)),r.length)||e.defaultValue!==void 0&&(e.required&&(!e.defaultValue.trim()||U(e)&&Ut(e,e.defaultValue)?.length===0)?r.push("必填参数的默认值不能为空"):e.defaultValue.trim()&&r.push(...ki(e,e.defaultValue).map(([,n])=>`默认值${n}`))),r}function vf(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 Ft(e){return e==null||typeof e=="string"&&!e.trim()}function Sr(e,t={}){const r=Object.create(null),n=Object.create(null),o=Yt(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};vf(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;Mf(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 Mf(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)&&!Ft(t)?Ut(e,t):void 0;if(Ft(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=ki(e,c);u.forEach(([f,d])=>s(f,d)),u.length&&U(e)?delete o[e.field]:o[e.field]=a??(e.type==="number"&&Ai(c)?Number(c):c)}function Sf(e,t){return e.flatMap(r=>!Ft(t[r.field])&&r.dependsOn?.some(n=>Ft(t[n]))?[{code:"dependency",path:`$.params.${r.field}`,field:r.field,message:"请先填写联动依赖的上级参数"}]:[])}function zn(e,t={}){const r=Sr(e,t);if(!r.ok)throw new Gt(r.issues);return r.values}function $f(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 Ef(e){const t={type:e.type==="number"?"number":"string",title:e.label??e.field,...$f(e)};return U(e)&&Object.assign(t,df(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,kf(e)),Object.assign(t,Af(e)),t}function Af(e){const t={};return e.defaultValue!==void 0&&(!(e.type==="number"||U(e))||e.defaultValue.trim())&&(t.default=U(e)?Ut(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 kf(e){return{...e.optionsSource?{"x-report-options-source":e.optionsSource}:{},...e.dependsOn?.length?{"x-report-depends-on":[...e.dependsOn]}:{}}}function Pf(e){const t=Yt(e);if(t.length)throw new Gt(t);return{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:Object.fromEntries(e.map(r=>[r.field,Ef(r)])),required:e.filter(r=>r.required).map(r=>r.field),additionalProperties:!0}}function Rt(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=Yt(i);if(s.length)throw new Gt(s);return i.filter(a=>r.has(a.field)?!1:(r.add(a.field),!0))})}function Nf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $r(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 Pi(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(!Nf(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{ce({...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=Wa(e);for(const o of n.errors)r.push({path:t,message:o})}function If(e,t,r){if(e!==void 0)try{Ur(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function Ff(e,t,r){if(e.tree===void 0)return;const n=`${t}.tree`;try{Ko(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)&&qr(o,e.computed)}catch(o){r.push({path:n,message:o instanceof Error?o.message:String(o)})}}const Rf=1e7,Cf=new Set(["__proto__","prototype","constructor"]),Tf=new Set(["text","number","boolean","date","decimal"]);function ht(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Er(e){return typeof e=="string"&&!!e.trim()&&e.length<=4096&&!Cf.has(e)}function jf(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(!ht(o)||!Er(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&&!Tf.has(String(o.type))&&r.push({path:`${s}.type`,message:"未知绑定字段类型"})})}function Df(e,t,r){if(e===void 0)return;if(!ht(e)||!ht(e.datasets)){r.push({path:t,message:"模板数据契约应声明 datasets"});return}e.source!==void 0&&!Er(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}`;!Er(o)||!ht(i)?r.push({path:s,message:"数据集应使用安全名称和字段契约"}):jf(i.fields,`${s}.fields`,r)}}class Lf extends Error{constructor(t){super(`模板校验失败:${t.slice(0,3).map(r=>`${r.path}: ${r.message}`).join("; ")}`),this.errors=t,this.name="ReportTemplateError"}}const Bf=new Set(["__proto__","prototype","constructor"]),_f=new Set(["left","center","right","justify"]),gt=2e5,Kf=64;function R(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Wf(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 zf(e,t,r,n){return Bf.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,u)=>{if(!i){if(++n>gt){n===gt+1&&t.push({path:c,message:"模板超过 JSON 节点安全上限"});return}if(u>Kf){t.push({path:c,message:"模板嵌套层级过深"});return}if(typeof a=="string"){o+=a.length,o>Rf&&(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(Wf(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(zf(f,d,l,t)&&s(d.value,l,u+1),n>gt||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 le(e,t,r,n){e[t]!==void 0&&typeof e[t]!="boolean"&&n.push({path:`${r}.${t}`,message:"应为布尔值"})}function Oe(e,t,r,n=!1){e!==void 0&&!_f.has(e)&&!(n&&e==="auto")&&r.push({path:t,message:`未知对齐方式${n?"(支持 auto)":""}`})}function se(e,t,r){if(e!==void 0){if(!R(e)){r.push({path:t,message:"样式应为对象"});return}Oe(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"])le(e,n,t,r);for(const n of["fontFamily","color","backgroundColor","lineColor","borderColor"])_(e,n,t,r)}}function Jf(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(!R(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);le(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:"长度边界应为非负整数"})}Uf(i,a,r),i.options!==void 0&&(Array.isArray(i.options)?i.options.forEach((c,u)=>{const f=`${a}.options.${u}`;if(!R(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(...Yt(e).map(i=>({path:i.path.replace("$.paramDefs",t),message:i.message})))}function Uf(e,t,r){for(const i of["min","max"]){const s=e[i];if(s===void 0)continue;Ei(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 Ni(e,t,r){if(!Array.isArray(e)||e.length===0){r.push({path:t,message:"列表至少需要一列"});return}e.every(n=>R(n)&&n.hidden===!0)&&r.push({path:t,message:"列表至少需要一列可见列"}),e.forEach((n,o)=>{const i=`${t}.${o}`;if(!R(n)){r.push({path:i,message:"列应为对象"});return}if(gi(n,i,r),n.visual!==void 0&&!Zo(n.visual)&&r.push({path:`${i}.visual`,message:"列可视化配置无效,请检查类型、数值范围和颜色"}),le(n,"hidden",i,r),$r(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),se(n.style,`${i}.style`,r),se(n.headerStyle,`${i}.headerStyle`,r),Oe(n.align,`${i}.align`,r,!0),Oe(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(!R(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 的整数"}),le(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(!R(s)||!R(s.when)){r.push({path:c,message:"条件格式缺少 when 对象"});return}$r(s.when,`${c}.when`,r),se(s.style,`${c}.style`,r)}):r.push({path:`${i}.rules`,message:"条件格式应为数组"}))})}function Oi(e,t,r){if(e!==void 0){if(!R(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"])se(e[n],`${t}.${n}`,r);le(e,"keepWithNext",t,r),le(e,"repeatHeader",t,r),Pi(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 Gf(e,t,r){if(!(e===void 0||typeof e=="boolean")){if(!R(e)){r.push({path:t,message:"合计应为布尔值或对象"});return}_(e,"label",t,r),Pi(e.aggregates,`${t}.aggregates`,r),se(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 Yf(e,t,r,n){const o={kind:"rect",leftMm:0,topMm:0,widthMm:1,heightMm:1,grid:e};if(wi(o,r,n,[]),ln(o,r,n),!R(e)||!Array.isArray(e.cells))return;const i=e.cells,s=Array.isArray(t)?t.length:0;if(i.length*s>gt){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:"表头行高数量应与行数一致"}),qf(i,s,r,n)}function qf(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=R(c)&&typeof c.colSpan=="number"?c.colSpan:1,d=R(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 Xf(e,t,r){if(Ff(e,t,r),Of(e.computed,`${t}.computed`,r),If(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 汇总,不能同时配置普通分组、总计或主从明细"}),$r(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)=>Oi(i,`${t}.groups.${s}`,r))),e.detail===void 0)return;const n=e.detail,o=`${t}.detail`;if(!R(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),le(n,"header",o,r),W(n,"rowHeightMm",o,r,Number.MIN_VALUE),Ni(n.columns,`${o}.columns`,r),n.unmatched!==void 0&&n.unmatched!=="error"&&n.unmatched!=="ignore"&&r.push({path:`${o}.unmatched`,message:"未关联明细策略应为 error 或 ignore"})}function Zf(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&&Yf(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"}),Ni(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"])le(e,n,t,r);e.cardinality!==void 0&&e.cardinality!=="record"&&r.push({path:`${t}.cardinality`,message:"单记录区域类型应为 record"}),_(e,"headerBackgroundColor",t,r),Oe(e.align,`${t}.align`,r,!0),Oe(e.headerAlign,`${t}.headerAlign`,r),se(e.headerStyle,`${t}.headerStyle`,r),Xf(e,t,r),Oi(e.groupBy,`${t}.groupBy`,r),Gf(e.grandTotal,`${t}.grandTotal`,r)}function Vn(e,t,r){Array.isArray(e.richParagraphs)&&e.richParagraphs.forEach((n,o)=>{if(!R(n))return;const i=`${t}.richParagraphs.${o}`;Oe(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(!R(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);se(s.style,`${c}.style`,r)})})}function ln(e,t,r){se(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:"文本行应为字符串数组"}),Vn(e,t,r),!R(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(!R(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"}),se(s.style,`${c}.style`,r),Vn(s,c,r),s.children!==void 0&&(Array.isArray(s.children)?s.children.forEach((u,f)=>{R(u)&&ln(u,`${c}.children.${f}`,r)}):r.push({path:`${c}.children`,message:"嵌套组件应为数组"}))}})})}function Qf(e,t,r){if(!(e.flow===void 0||!Array.isArray(e.components)))try{Jo(e.components,e.flow)}catch(n){r.push({path:`${t}.flow`,message:n instanceof Error?n.message:String(n)})}}function el(e){const t=[],r=[];return Hf(e,t),t.length?{ok:!1,errors:t,warnings:r}:(R(e)?(e.schemaVersion!==void 0&&e.schemaVersion!==nt&&t.push({path:"$.schemaVersion",message:"不支持的模板 schemaVersion"}),Jf(e.params,"$.params",t),Df(e.dataContract,"$.dataContract",t),Go(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(!R(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}`;R(s)&&s.kind==="list"?Zf(s,c,t):(wi(s,c,t,r),R(s)&&ln(s,c,t))}):t.push({path:`${i}.components`,message:"组件应为数组"}),Qf(n,i,t)})):t.push({path:"$",message:"模板应为对象"}),{ok:t.length===0,errors:t,warnings:r})}class tl extends Error{constructor(t){super(t.map(r=>r.message).join(";")),this.issues=t,this.name="ReportValidationError"}}function Hn(e,t,r){if(!Number.isSafeInteger(e)||e<1||e>r)throw new Error(`校验 ${t} 超出预算`);return e}function rl(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),Xe([],{...r,field:r.valueField??r.field})}}function Ii(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("未知校验范围");rl(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 Jn(e){if(e?.aborted){const t=new Error("报表校验已取消");throw t.name="AbortError",t}}function nl(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 ol(e,t){const r=t.computed?.length?{fields:t.computed,formula:t.formula,signal:t.signal}:void 0;if(t.tree){const o=Ho(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?zt(e,r).rows:e;return{rows:n,summaryRows:n,rowKey:t.rowKey}}function il(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 sl(e,t,r){if(!Array.isArray(e)||e.length>1e5)throw new Error("校验数据最多 100000 行");Jn(t.signal);const n=Hn(t.maxChecks??2e6,"maxChecks",1e7),o=Hn(t.maxIssues??1e3,"maxIssues",1e4);t.rowKey!==void 0&&K(t.rowKey);const i=ol(e,t),{rows:s,summaryRows:a,rowKey:c}=i;il(s,c);const u=Ii(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,Xe(a,{...h,field:h.valueField??h.field})]))]:s).forEach((h,g)=>{if(Jn(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(nl(l.rule,h,l.rule.scope==="dataset"?void 0:g,l.rule.scope==="dataset"?void 0:c))}});return d}function al(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 tl(e)}function Un(e,t,r){const n=e.get(t);if(n&&JSON.stringify(n)!==JSON.stringify(r))throw new Error("同一数据集的校验计算/业务键存在歧义,请统一绑定");e.set(t,r)}function cl(e,t,r,n=[]){Ii(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"&&(Un(u,d.dataset,{rowKey:d.tree?.idField??d.rowKey,computed:d.computed,tree:d.tree}),d.detail&&Un(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(...sl(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 ul(e){return!e||typeof e!="object"?!1:[e.pageIndex,e.componentIndex,e.rowIndex,e.columnIndex].every(t=>Number.isInteger(t)&&t>=0)}function fl(e){return e.value!==void 0?e.value:e.rawText??e.text??null}function ll(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 dl(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 ml(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 hl(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 Gn(e,t,r){const n=fl(r),o=dl(r,e);return{address:{...t},cell:r,component:e,value:n,valueType:ll(r,n),table:ml(e,t),source:hl(r,e,t),editable:o===void 0,readOnlyReason:o}}function gl(e,t=!0){const r=new Map;function n(a){if(!a.grid)return;let c=r.get(a);if(!c){const u=br(a.grid,a.widthMm,a.heightMm),f=new Map,d=new Map;for(const l of u.cells){const m=f.get(l.ri)??0;f.set(l.ri,m+1);const h=a.grid.cells[l.ri]?.[m];h&&d.set(`${l.ri}:${l.ci}`,h)}c={layout:t?u:void 0,cells:d},r.set(a,c)}return c}function o(a){if(!ul(a))return null;const c=e.pages[a.pageIndex]?.components[a.componentIndex];if(!c)return null;const u=n(c)?.cells.get(`${a.rowIndex}:${a.columnIndex}`);return u?Gn(c,a,u):null}function*i(a,c){const u=e.pages[a]?.components[c],f=u&&n(u);if(f)for(const d of s(u).cells){const l=f.cells.get(`${d.ri}:${d.ci}`);l&&(yield Gn(u,{pageIndex:a,componentIndex:c,rowIndex:d.ri,columnIndex:d.ci},l))}}function s(a){const c=n(a);return c&&(c.layout??br(a.grid,a.widthMm,a.heightMm))}return{resolve:o,entries:i,layout:s}}function Fi(e){return gl(e,!1).resolve}function pl(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 yl(e,t){const r=pl(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 wl(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 We(e,t){return/[0#?@_*%[\]"\\.,/]/.test(e)?null:e.replace(/[\uE000-\uF8FF]/g,r=>t.literals[r.charCodeAt(0)-57344]??"")}function bl(e,t){const r=/^(.*?)(0)(?:\.([0#]+))?E([+-])(0+)(.*?)$/i.exec(t.text);if(!r)return null;const n=We(r[1],t),o=We(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 xl(e,t){const r=/^(.*?)([#,]*0[0#]*)(?:\.([0#]+))?(%)?(.*?)$/.exec(t.text);if(!r)return We(t.text,t);const n=We(r[1],t),o=We(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 vl(e,t,r){if(!t||/^(General|@)$/i.test(t))return String(e);const n=yl(e,t);if(n.pattern==="")return"";const o=wl(n.pattern),i=bl(n,o)??xl(n,o);return i!==null?i:String(e)}function Ml(e){return e!==void 0&&e.replace(/"[^"]*"|\\./g,"").includes("%")}class N extends Error{constructor(t){super(`Invalid report cell edit: ${t}`),this.code=t,this.name="ReportCellEditError"}}function Sl(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 N("number");return Number(r)/(n?100:1)}function $l(e,t){if(e===null||typeof e=="string"&&e.trim()==="")return null;if(typeof e!="string"&&typeof e!="number")throw new N("number");const r=typeof e=="number"?e:Sl(e,Ml(t.cell.numberFormat));if(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r))throw new N("number");return r}function El(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 N("boolean")}function Al(e,t){return e.valueType==="number"?$l(t,e):e.valueType==="boolean"?El(t):t===null?null:String(t)}function kl(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 Ri(e,t){return t===null?"":typeof t=="boolean"?kl(t,e):typeof t=="number"?vl(t,e.cell.numberFormat):String(t)}function Ci(e,t){if(!e.editable)throw new N("readonly");const r=Al(e,t);return{address:{...e.address},table:e.table,source:e.source,previousValue:e.value,previousText:e.cell.text??"",value:r,text:Ri(e,r)}}function Pl(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 Ti(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 Ce(e){return JSON.stringify([e.sourceScope,e.datasetId])}function Ct(e){return JSON.stringify([e.sourceScope,e.datasetId,e.rowKey])}function ji(e){const t=new Map,r=new Set;return e.forEach((n,o)=>{for(const i of Ti(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=Ct({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(Ct(n));if(!o?.length)throw new N("missing");if(new Set(o.map(i=>`${i.partIndex}:${i.dataset}`)).size!==o.length)throw new N("conflict");return o}}function Di(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);ja(e[i].datasets[s],r[i].datasets[s])}return r}function Nl(e,t,r){const n=[],o=new Set;return e.forEach((i,s)=>{for(const a of Ti(i))t.has(Ce({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 Ol(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?[Ce(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(Ce({...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 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&&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 Tt(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 Il(e){const t=new Map,r=Fi(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(Tt(u),u)}})),t}function Bi(e,t){if(++e.nodes>1e6||t>128)throw new N("limit")}function jt(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw new N("conflict");return r.value}function dn(e){if(Object.getOwnPropertyDescriptor(e,"toJSON"))throw new N("conflict");const t=Object.getPrototypeOf(e);if(Array.isArray(e)&&(t!==Array.prototype||Object.keys(e).length!==e.length))throw new N("conflict");if(!(e instanceof Date)&&!Array.isArray(e)&&t!==Object.prototype&&t!==null)throw new N("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 N("conflict");if(e instanceof Date||Array.isArray(e)&&!/^(0|[1-9]\d*)$/.test(r))throw new N("conflict")}}function _i(e,t,r,n,o,i){if(Bi(n,o),typeof e=="function"||typeof e=="symbol")throw new N("conflict");if(e===null||typeof e!="object")return;if(dn(e),r.has(e))throw new N("conflict");if(i?.has(e))return;i?.add(e),r.add(e);const s=Object.keys(e),a=s.map(c=>jt(e,c));t.push({object:e,prototype:Object.getPrototypeOf(e),keys:s,values:a,...e instanceof Date?{date:Date.prototype.getTime.call(e)}:{},...Array.isArray(e)?{length:e.length}:{}});for(const c of a)_i(c,t,r,n,o+1,i);r.delete(e)}function Fl(e){const{object:t,keys:r,values:n}=e;if(dn(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(jt(t,i),n[s]))}function Rl(e){return Ki(e)}function Cl(e){return Ki(e,new Set)}function Ki(e,t){const r=[];return _i(e,r,new Set,{nodes:0},0,t),()=>{try{return r.every(Fl)}catch{return!1}}}function Dt(e,t,r,n=!1){if(Bi(t,r),n){if(typeof e=="function"||typeof e=="symbol")throw new N("conflict");e!==null&&typeof e=="object"&&dn(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]=Dt(jt(e,String(i)),t,r+1,n);return o}return Object.fromEntries(Object.keys(e).map(o=>[o,Dt(jt(e,o),t,r+1,n)]))}function Tl(e){return Dt(e,{nodes:0},0,!0)}function jl(e){const t=Dt(e,{nodes:0},0);for(const r of t)for(const n of Object.values(r.datasets))Ta(n);return t}async function Dl(e,t,r={}){return li(e,t,{...r,knownTotalPages:void 0})}function Ll(e){return e.computed||e.groupBy||e.groups||e.grandTotal||e.tree||e.matrix||e.detail||e.rowVisibleWhen||e.headerGrid?!1:e.columns.every(t=>!t.format&&!t.rules&&!t.visibleWhen&&!t.visual)}function Bl(e,t){return e.length!==t.length||t.some(r=>r?.measurer||r?.formula||r?.mmPerRow||r?.knownTotalPages!==void 0)?!1:e.every(r=>!r.template.repeat&&r.template.pages.every(n=>!n.flow&&n.components.every(o=>o.kind==="list"?Ll(o):!o.binding&&!o.chartBinding&&!o.grid&&!o.table&&!o.richParagraphs)))}function _l(e){const t=new Map;for(const r of e){if(!r.source||typeof r.value!="string"||typeof r.previousValue!="string"||r.previousText!==r.previousValue||![r.previousValue,r.value].every(i=>i.trim().length&&i.length<=16384&&!/[\r\n]/.test(i)))return null;const n=Ct(r.source),o=t.get(n)??new Map;o.set(r.source.field,r),t.set(n,o)}return t}function mn(e){return!e.source&&!e.formula&&!e.derived&&!e.richParagraphs&&!e.children&&!e.dataBar&&!e.numberFormat&&!e.colSpan&&!e.rowSpan&&!e.indentMm&&!e.style?.rotateDeg}function Kl(e){return e.pages.every(t=>t.components.every(r=>!r.grid||r.grid.cells.every(n=>n.every(o=>!!o&&mn(o)))))}function Wl(e,t,r,n){if(!mn(e)||e.value!==t.previousValue||e.text!==t.previousText)return!1;const o=r-n*2,i=e.style,s=it(i).fontSizePt;if(!Number.isFinite(o)||o<1||!Number.isFinite(s)||s<=0)return!1;const a={fontSizePt:s,fontFamily:i?.fontFamily??_r,italic:i?.italic,bold:i?.bold,letterSpacingPt:i?.letterSpacing};return ye(t.previousText,o,a,qe).length===ye(t.value,o,a,qe).length}function zl(e,t){const r=e.colWidthsMm;if(!r||r.length!==e.cells[0].length||r.length!==t.table.columnKeys.length)return!1;const n=r.reduce((o,i)=>o+i,0);return Number.isFinite(n)&&Math.abs(n-t.widthMm)<=Math.max(1e-7,n*1e-10)}function Vl(e,t,r){const n=e.table?.source;if(e.table?.role!=="body"||n?.rowKey===void 0)return e;const o=t.get(Ct({...n,rowKey:n.rowKey}));if(!o)return e;const i=e.grid;if(!i||i.cells.length!==1||!zl(i,e)||e.style?.rotateDeg)return null;const s=i.cells[0],a=[...s];for(let c=0;c<s.length;c++){const u=s[c];if(!u||!mn(u))return null;const f=o.get(e.table.columnKeys[c]);if(f){if(!Wl(u,f,i.colWidthsMm[c],i.paddingMm??.5))return null;a[c]={...u,value:f.value,text:f.value},r.add(f)}}return a.some((c,u)=>c!==s[u])?{...e,grid:{...i,cells:[a]}}:e}async function Hl(e,t,r){const n=_l(t);if(!n||!t.length)return null;const o=new Set,i=[];let s=0;for(const c of e.pages){const u=[];for(const f of c.components){if(r?.aborted)return null;const d=Vl(f,n,o);if(!d)return null;u.push(d),++s%128===0&&await new Promise(l=>setTimeout(l,0))}i.push(u.some((f,d)=>f!==c.components[d])?{...c,components:u}:c)}if(o.size!==t.length)return null;const a={...e,pages:i};return Re(a).ok?a:null}function Jl(e,t,r){let n=Bl(t,r),o=e,i;function s(c){if(o=c,i=void 0,!!n){if(!Kl(c)){n=!1;return}try{i=Cl(c)}catch{n=!1}}}s(e);async function a(c,u,f){if(!n||c!==o||!i?.())return null;const d=i,l=await Hl(c,u,f);return l&&d()?{plan:l,unchanged:d}:null}return{candidate:a,publish:s}}const Yn=new WeakMap;function je(e){if(e?.aborted){const t=new Error("报表重算已取消");throw t.name="AbortError",t}}function Wi(e,t){return e[t]===void 0?"":e[t]}function Ul(e,t){if(t.edits.length>1e4)throw new N("limit");const r=Fi(e),n=new Set,o=[],i=t.edits.map(s=>{const a=r(s.address);if(!a?.source)throw new N("missing");const c=Tt(s);if(n.has(c))throw new N("duplicate");if(n.add(c),Pl(a,s)||!Object.is(a.value,s.previousValue)||(a.cell.text??"")!==s.previousText)throw new N("conflict");return o.push(a),Ci(a,s.value)});return{batch:{requestId:t.requestId,edits:i},contexts:o}}function Gl(e,t){const r=ji(e);return t.flatMap(n=>{if(!n.source)throw new N("missing");return r(n.source).map(o=>{if(!Object.is(Wi(o.row,n.source.field),n.previousValue))throw new N("conflict");if(o.binding.rowKey===n.source.field)throw new N("readonly");return{row:o,field:n.source.field,value:n.value}})})}function ar(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:Ri(n,n.value)},n}function Yl(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?[Ce(o.source)]:[]));return Di(e,Nl(e,n,r))}function ql(e,t,r){const n=new Set(t.edits.map(o=>Ce(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 Xl(e,t,r){let n=t.parts;const o=t.rebuild,i=[...t.validationFormulas??[]],s=r?Jl(e,n,r):void 0;let a=Rl(n),c=e,u;const f=new Map,d=new Map;function l(g){if(g!==c)throw new N("conflict");if(u)return u;if(!a?.())throw new N("conflict");return jl(n)}async function m(g,y,w,p={}){je(p.signal),y={requestId:y.requestId,edits:y.edits.map(M=>({...M,address:{...M.address},source:M.source?{...M.source}:void 0,table:M.table?{...M.table}:void 0}))},w=w.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)),je(p.signal);const x=l(g),b=Di(x,Gl(x,y.edits)),S=await s?.candidate(g,y.edits,p.signal);je(p.signal);const C=Li(S?.plan??await o(b,p.signal),d);je(p.signal);let B=!1,v=[],k="allow",P=!1;function j(M){return P=!0,v=Object.freeze(cl(b,M,p.signal,i).map(O=>Object.freeze({...O}))),P=!1,k=M.warningPolicy??"allow",v}return p.validation&&j(p.validation),{plan:C,get validationIssues(){return v},validate:j,commit(M){if(je(p.signal),B||c!==g)throw new N("conflict");if(S&&!S.unchanged())throw new N("conflict");if(M?.conflicts?.length)throw new N("conflict");if(P)throw new Error("候选规则校验未完成,不能提交");al(v,k);const O=Yl(b,y,M),te=Ol(C,y,M);if(M){const re=ql(d,y,M);for(const[Te,me]of f)re.has(Ce(me.source))&&f.set(Te,ar(me,me.value,M))}return w.forEach((re,Te)=>f.set(Tt(re),ar(re,y.edits[Te].value,M))),B=!0,u=O,n=void 0,a=void 0,c=te,s?.publish(c),Yn.set(c,h),c}}}const h={get plan(){return c},async prepare(g,y,w){const p=Ul(g,y);return m(g,p.batch,p.contexts,w)},async prepareHistory(g,y,w,p,x){if(!p.trim()||y.length>1e4)throw new N("limit");const b=l(g),S=ji(b),C=Il(g),B=new Set,k=y.map(M=>{if(!M.source)throw new N("missing");const O=Tt(M);if(B.has(O))throw new N("duplicate");B.add(O);const te=C.get(O)??f.get(O);if(!te?.source)throw new N("missing");const re=S(te.source)[0];return ar(te,Wi(re.row,te.source.field))}).map((M,O)=>({context:M,edit:Ci(M,y[O][w])})).filter(({edit:M})=>!Object.is(M.previousValue,M.value)),P={requestId:p,edits:k.map(({edit:M})=>M)},j=k.map(({context:M})=>M);return{batch:P,contexts:j,prepared:await m(g,P,j,x)}}};return Yn.set(e,h),h}let Zl=0;function pt(){return`report-${Date.now()}-${++Zl}`}function Ee(e,t,r){if(!r?.aborted)try{const n=e?.({...t});n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{})}catch{}}function pe(e){const t=e.taskId??pt(),r=(n,o,i)=>{Ee(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){Ee(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 zi(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]=Vo(t[i]??[],{...s,maxRows:a},r.signal)}return o}function Ql(e,t,r={}){return Object.values(zi(e,t,r)).reduce((n,o)=>n+o.length,0)}function ed(e,t,r){const n=qs(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 hn(e,t){return JSON.stringify([e,t])}function Vi(e,t,r){return r===void 0?hn(e,t):JSON.stringify(["shared",r])}function Hi(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:Hi(a.children,t,r)}:{}}));return o||i?{...n,...o?{table:o}:{},...i?{grid:{...n.grid,cells:i}}:{}}:n})}function Ar(e){return Vt(e.maxChartComponents),{maxPages:e.maxPages,maxCells:e.maxCells,maxChartComponents:e.maxChartComponents??Jr,usedPages:0,usedCells:0,usedChartComponents:0}}function td(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 rd(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 kr(e,t){return e===void 0?void 0:e-t}function cr(e,t){return e===void 0?t:Math.max(1,Math.min(e,t??e))}function Ji(e,t,r,n,o){Vt(e?.maxChartComponents);const i=kr(t.maxPages,t.usedPages),s=t.maxChartComponents-t.usedChartComponents;if(i!==void 0&&i<1&&r.pages.length&&!td(r,n))throw new Pe(0,1);if(s<1&&r.pages.some(a=>a.components.some(c=>c.kind!=="list"&&c.chartBinding)))throw new Qe(s,1);return{...e,signal:o??e?.signal,maxPages:cr(i,e?.maxPages),maxCells:cr(kr(t.maxCells,t.usedCells),e?.maxCells),maxChartComponents:cr(s,e?.maxChartComponents)}}function Ui(e,t){const r=rd(t.plan),n=kr(e.maxCells,e.usedCells);if(n!==void 0&&r>n)throw new Ze(n,r);e.usedPages+=t.plan.pages.length,e.usedCells+=r,e.usedChartComponents+=t.chartComponents}function Gi(e,t){return e instanceof Pe&&t.maxPages!==void 0&&(e.limit===t.maxPages-t.usedPages||e.limit===0)?new Pe(t.maxPages,t.usedPages+e.actual):e instanceof Ze&&t.maxCells!==void 0?new Ze(t.maxCells,t.usedCells+e.actual):e instanceof Qe&&e.limit===t.maxChartComponents-t.usedChartComponents?new Qe(t.maxChartComponents,t.usedChartComponents+e.estimated):e}class $ extends Error{constructor(t,r,n){super(r),this.name="ReportSourceError",this.code=t,this.cause=n}}function qt(e){const t=new Error("报表加载已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function G(e){if(e?.aborted)throw qt(e)}function Pr(e,t){return t?new Promise((r,n)=>{const o=()=>t.removeEventListener("abort",i),i=()=>{o(),n(qt(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 nd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new $("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 $("validate",`报表 ${t} 的数据集 ${r} 应为对象数组`)}async function od(e,t,r){const{reportId:n,signal:o}=t;try{const i=await Pr(e(t),o);G(o);const s=el(i);if(!s.ok)throw new $("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?qt(o):i instanceof $?i:i instanceof Lf?new $("validate",`报表 ${n} 模板校验失败:${i.message}`,i):new $("fetch",`报表 ${n} 模板加载失败:${i instanceof Error?i.message:String(i)}`,i)}}async function id(e,t,r,n){const o=t.signal;let i;try{if(e.load)i=await Pr(e.load(t),o);else if(e.provider){const s=await Pr(e.provider.query(t),o);G(o),sd(s,r),i=s.datasets,n?.(r,s)}else i=e.datasets??{}}catch(s){throw o?.aborted?qt(o):s instanceof $?s:new $("fetch",`报表 ${r} 取数失败:${s instanceof Error?s.message:String(s)}`,s)}return G(o),i}function sd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new $("validate",`报表 ${t} Provider 应返回 datasets 结果对象`);for(const r of["revision","sourceToken"])if(e[r]!==void 0&&typeof e[r]!="string")throw new $("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 $("validate",`报表 ${t} Provider diagnostics 不符合结构化诊断契约`);if(e.diagnostics?.some(r=>!Fe(r)))throw new $("validate",`报表 ${t} Provider 数据说明缺少有效的字段身份或值状态`)}function ad(e,t,r,n,o){try{t=zi(n,t,{maxRows:e.dataValidation?.maxRows,signal:o})}catch(i){throw new $("validate",`报表 ${r} 树形数据无效:${i instanceof Error?i.message:String(i)}`,i)}for(const[i,s]of Object.entries(e.dataSchema??{})){let a;try{a=Gs(Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0,s,{...e.dataValidation,path:`$.datasets.${i}`})}catch(c){throw new $("config",`报表 ${r} 数据集 ${i} 字段契约配置无效`,c)}if(!a.ok)throw new $("validate",`报表 ${r} 数据集 ${i} 不符合字段契约:${a.issues[0]?.message}`,{issues:a.issues})}}async function cd(e,t,r,n,o){try{let i;try{i=Tl(e)}catch{}const s=i??e,a=Ji(t.pagination,n,s.template,s.datasets,o),c=i?await li(s.template,s.datasets,a):ju(s.template,s.datasets,a);return Ui(n,c),{result:c,part:s}}catch(i){G(o);const s=Gi(i,n);throw new $("validate",`报表 ${r} 排版失败:${s instanceof Error?s.message:String(s)}`,s)}}function Yi(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:hn(r,n)},components:Hi(a.components,o??Vi(r,n),s)})}async function ud(e,t,r,n,o){const i=[],s=Ar(n);for(const[u,f]of e.entries()){G(o);try{const d=await Dl(f.template,f.datasets,Ji(t[u]?.pagination,s,f.template,f.datasets,o));Ui(s,d),Yi(i,d.plan,u,r[u],f.sourceScope)}catch(d){throw Gi(d,s)}}const a={schemaVersion:nt,...e.some(u=>Zr(u.template))?{requiresRecalculation:!0}:{},pages:i},c=Re(a);if(!c.ok)throw new $("validate",`重算渲染计划校验失败:${c.errors[0]?.message}`);return a}function fd(e,t={}){if(t.maxPages!==void 0&&(!Number.isSafeInteger(t.maxPages)||t.maxPages<1))throw new $("config","maxPages 应为正安全整数");if(t.maxCells!==void 0&&(!Number.isSafeInteger(t.maxCells)||t.maxCells<1))throw new $("config","maxCells 应为正安全整数");try{Ar(t)}catch(o){throw new $("config","maxChartComponents 应为 1..1000000 的安全整数",o)}function r(o){const i=Object.prototype.hasOwnProperty.call(e,o)?e[o]:void 0;if(!i)throw new $("config",`未注册报表 ${o}`);if(i.sourceScope!==void 0&&(typeof i.sourceScope!="string"||!i.sourceScope.trim()||i.sourceScope.length>512))throw new $("config","sourceScope 应为不超过 512 字符的非空字符串");return i}return Object.assign(async({reportIds:o,params:i,signal:s,onWarning:a,onQueryResult:c,...u})=>{G(s);const f=pe({...u,signal:s}),d=[...o],l={...i};if(d.length===0)throw new $("config","缺少报表 ID");const m=d.map(r),h=f.runSync("validate",()=>m.map(v=>zn(v.params??(typeof v.template=="function"?[]:v.template.params)??[],l))),g=[],y=[],w=Ar(t),p=[];for(const[v,k]of m.entries()){G(s);const P=d[v],j={reportId:P,params:h[v],signal:s},M=typeof k.template=="function"?await f.run("query",()=>od(k.template,j,p),P):k.template;j.params=f.runSync("validate",()=>zn(k.params??M.params??[],j.params),P);const O=await f.run("query",()=>id(k,j,P,(me,$s)=>c?.(me,$s,v)),P);f.runSync("validate",()=>{nd(O,P),t.onDatasets?.(P,O,M),ad(k,O,P,M,s)},P),G(s);const te=Vi(v,P,k.sourceScope),{result:re,part:Te}=await f.run("layout",()=>cd({template:M,datasets:O,sourceScope:te},k,P,w,s),P);y.push(Te),Yi(g,re.plan,v,P,te),p.push(...re.warnings.map(me=>`${P}: ${me}`))}G(s);const x={schemaVersion:nt,...y.some(v=>Zr(v.template))?{requiresRecalculation:!0}:{},pages:g},b=f.runSync("validate",()=>{const v=Re(x);if(!v.ok)throw new $("validate",`渲染计划校验失败:${v.errors.slice(0,3).map(k=>`${k.path}: ${k.message}`).join("; ")}`);return v});p.push(...b.warnings.map(v=>`${v.path}: ${v.message}`));const S=m.map(v=>({...v,pagination:{...v.pagination}})),C={maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents};try{Xl(x,{parts:y,validationFormulas:S.map(v=>v.pagination?.formula),rebuild:(v,k)=>ud(v,S,d,C,k)},S.map(v=>v.pagination))}catch{p.push("来源数据无法建立本地重算口径;当前预览仅支持计划内编辑,请使用可序列化模板数据启用规则重算")}const B=a??t.onWarning??(v=>console.warn("[mach-report]",v));for(const v of p)G(s),B(v);return G(s),x},{getParamDefs:o=>Rt(e,o)})}const gn=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 F(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 T(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 qi(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 ze(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{F(n.signal);const c=new Promise((f,d)=>{a=()=>{try{F(n.signal)}catch(l){d(l)}},n.signal.addEventListener("abort",a,{once:!0})}),u=await Promise.race([r(n.signal),c]);if(F(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 Xi(e,t){ue.assertOutputActive(t.signal),ue.observeOutput(()=>t.onDiagnostic?.(e)),ue.assertOutputActive(t.signal)}class ld extends Error{constructor(t,r){super(`Output contains ${r?.total??t.length} known fidelity issue(s): ${t[0]?.code??Object.keys(r?.counts??{})[0]??"unknown"}`),this.diagnostics=t,this.diagnosticSummary=r,this.code="output-fidelity",this.name="OutputFidelityError"}}class Xt extends Error{constructor(t,r){super(r),this.code=t,this.name="ImageMediaError"}}const ur={maxImageBytes:16*1024*1024,maxTotalImageBytes:32*1024*1024,maxImages:1e3,maxImagePixels:16e6,maxTotalImagePixels:64e6,maxImageDimension:16384};function ne(e){throw new Xt("invalid-image-data",e)}function Ve(e){throw new Xt("image-budget-exceeded",e)}function dd(e){const t={...ur};for(const r of Object.keys(ur)){const n=e[r]??ur[r];if(!Number.isSafeInteger(n)||n<=0||n>2147483647)throw new RangeError(`${r} 图片预算须为1至2147483647的整数。`);t[r]=n}return t}function md(e){if(e.length<33||![137,80,78,71,13,10,26,10].every((r,n)=>e[n]===r))return ne("图片内容与 PNG/JPEG 类型不一致。");const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return t.getUint32(8)!==13||String.fromCharCode(...e.subarray(12,16))!=="IHDR"?ne("PNG must begin with an IHDR header."):[t.getUint32(16),t.getUint32(20)]}const hd=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function gd(e){if(e[0]!==255||e[1]!==216)return ne("图片内容与 PNG/JPEG 类型不一致。");let t=2;for(;t+3<e.length;){if(e[t++]!==255)return ne("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 ne("JPEG segment exceeds its data boundary.");if(hd.has(r))return n<8?ne("JPEG frame header is incomplete."):[e[t+5]*256+e[t+6],e[t+3]*256+e[t+4]];t+=n}return ne("JPEG has no supported dimension header.")}function pd(e,t){if(e.length>Math.ceil(t.maxImageBytes/3)*4+64)return Ve("单张图片超过字节预算。");const r=/^data:image\/(png|jpe?g);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(e);if(!r||r[2].length%4)return ne("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 Ve("单张图片超过字节预算。");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"?md(a):gd(a);return!c||!u?ne("Image dimensions must be positive."):c>t.maxImageDimension||u>t.maxImageDimension||c*u>t.maxImagePixels?Ve("Image exceeds its decoded dimension or pixel budget."):{dataUrl:`data:image/${i};base64,${n}`,bytes:a,extension:i,width:c,height:u}}function yd(e={}){const t=dd(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 Ve("唯一图片数量超过预算。");const c=pd(i,t);return n+c.bytes.length>t.maxTotalImageBytes||o+c.width*c.height>t.maxTotalImagePixels?Ve("图片总字节或总像素超过预算。"):(n+=c.bytes.length,o+=c.width*c.height,r.set(s,c),c)}}class pn extends Error{constructor(t,r){super(t.message),this.name="OutputAssetError",this.diagnostic=t,this.cause=r}}function Lt(e){if(e.aborted)throw e.reason??new DOMException("The operation was aborted.","AbortError")}function wd(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 bd(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 ct(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),Xi(i,{...e.options,signal:e.signal}),e.options.assetFailure!=="placeholder")throw new pn(i,o)}async function xd(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 ct(e,r,"asset-budget-exceeded","Output exceeded the asset count budget.");let o;try{if(e.active=r,o=await ue.waitForOutput(n({...r,signal:e.signal}),e.signal),Lt(e.signal),o.length>e.budget.maxImageBytes*4+1024)return ct(e,r,"asset-budget-exceeded","Output exceeded the image payload byte budget.");const i=bd(o);if(i>e.budget.maxImageBytes||e.bytes+i>e.budget.maxTotalImageBytes)return ct(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 pn||i instanceof Xt&&i.code==="image-budget-exceeded")throw i;return ct(e,r,"asset-render-failed",`Asset renderer failed for ${t.kind}; output was not silently omitted.`,i)}return o}function vd(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{Xi(n,{...e.options,signal:e.signal})}catch(o){t.abort(o);return}t.abort(new pn(n))}async function Md(e,t,r,n,o){if(!t?.children?.length)return t;const i=[];for(const[s,a]of t.children.entries())i.push(await Zi(e,a,{...r,component:a,componentPath:[...n,s]},o));return i.some((s,a)=>s!==t.children[a])?{...t,children:i}:t}async function Zi(e,t,r,n){if(Lt(e.signal),n.has(t))throw new TypeError("Cyclic grid children cannot be rendered.");let o=e.cache.get(t);o||(o=xd(e,t,r),e.cache.set(t,o));const i=await o;Lt(e.signal);let s=t.grid;if(s){const a=new Set(n).add(t),c=[];for(const[u,f]of s.cells.entries()){if(!f.some(l=>l?.children?.length)){c.push(f);continue}const d=[];for(const[l,m]of f.entries())d.push(m?.children?.length?await Md(e,m,r,[...r.componentPath,u,l],a):m);c.push(d.some((l,m)=>l!==f[m])?d:f)}c.some((u,f)=>u!==s.cells[f])&&(s={...s,cells:c})}return i!==t.imageData||s!==t.grid?{...t,imageData:i,grid:s}:t}function Sd(e,t,r){const n=new Set,o=i=>{if(ue.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 Xt)||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 $d(e){if(e.options.fidelity==="strict"&&e.diagnostics.total)throw new ld(e.diagnostics.entries,e.options.diagnosticLimit===void 0?void 0:e.diagnostics.snapshot())}function qn(e,t,r){return{plan:e,diagnostics:t.entries,...r===void 0?{}:{diagnosticSummary:t.snapshot()}}}async function Xn(e,t={}){ue.assertOutputActive(t.signal);const r=rt(t.diagnosticLimit);Ku(e);const n=wd(t),o=yd(t);if(Sd(e,o,t.signal),t.signal?.aborted)throw t.signal.reason??new DOMException("The operation was aborted.","AbortError");const i=new AbortController,s=()=>i.abort(t.signal?.reason);if(t.signal?.addEventListener("abort",s,{once:!0}),!t.assetRegistry&&(!t.assetRenderers||!Object.keys(t.assetRenderers).length))return t.signal?.removeEventListener("abort",s),qn(e,r,t.diagnosticLimit);const a={options:t,signal:i.signal,diagnostics:r,rendered:0,bytes:0,budget:n,cache:new WeakMap,inspectImage:o},c=setTimeout(()=>vd(a,i),n.maxDurationMs);try{const u=[];for(const[f,d]of e.pages.entries()){if(f<(t.start??0)||f>(t.end??e.pages.length-1)){u.push(d);continue}const l=[];for(const[m,h]of d.components.entries())l.push(await Zi(a,h,{component:h,pageIndex:f,componentIndex:m,componentPath:[]},new Set));u.push(l.some((m,h)=>m!==d.components[h])?{...d,components:l}:d)}return Lt(a.signal),$d(a),qn(u.some((f,d)=>f!==e.pages[d])?{...e,pages:u}:e,a.diagnostics,t.diagnosticLimit)}finally{clearTimeout(c),t.signal?.removeEventListener("abort",s)}}const Ed=new Set([8,9,10,12,13]);function Ad(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 kd(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+=Ed.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 Qi(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=kd(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 u(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 f(l,m)}function f(l,m){const{array:h,keys:g}=Ad(l,t.error);i.add(l),c(2);const y=h?[]:{};let w=0;for(const p of g){const x=Object.getOwnPropertyDescriptor(l,p);if(x.get||x.set||!x.enumerable||["__proto__","constructor","prototype"].includes(p))throw t.error("input","快照不允许访问器或危险键");if(x.value===void 0&&!h)continue;c((w++?1:0)+(h?0:a(p)+1));const b=u(x.value===void 0?null:x.value,m+1);p in y?Object.defineProperty(y,p,{value:b,enumerable:!0,configurable:!0,writable:!0}):y[p]=b}return i.delete(l),y}t.check?.();const d=u(e,0);return t.check?.(),d}const Pd=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 es(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 ts(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=Q(s,6)^Q(s,11)^Q(s,25),l=s&a^~s&c,m=u+d+l+Pd[f]+t[f]>>>0,h=Q(r,2)^Q(r,13)^Q(r,22),g=r&n^r&o^n&o,y=h+g>>>0;u=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]+u}function rs(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 ns=()=>new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),os=e=>Array.from(e,t=>t.toString(16).padStart(8,"0")).join("");function Zn(e){const t=rs(e),r=ns(),n=new Uint32Array(64);for(let o=0;o<t.length;o+=64)es(t,o,n),ts(r,n);return os(r)}async function Nd(e){const t=rs(e),r=ns(),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)),es(t,o,n),ts(r,n);return os(r)}function is(e){if(typeof e!="string"||!e.trim()||e.length>31||/[\\/*?:[\]]/.test(e)||/^'|'$/.test(e))throw new TypeError("工作表名称无效");return e}function Od(e){if(e!==void 0){if(!Array.isArray(e)||e.length>1e4)throw new RangeError("工作表名称列表最多 10000 项");return Array.from(e,is)}}function Id(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 Fd(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=is(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=Id(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 Nr(e){return e&&{...e,sheetNames:Od(e.sheetNames),additionalSheets:Fd(e.additionalSheets)}}function yn(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 He(e){if(!e)return;const t=r=>{if(!(r instanceof Uint8Array)&&!(r instanceof ArrayBuffer))throw new $("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 ss(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,Zn(i)]});return Zn(new TextEncoder().encode(JSON.stringify(r)))}const Or=new WeakMap;function Rd(e,t,r){const n=as(e,t,r);let o=!0;return{prepared:n,forward(){if(!o)throw new Error("报表快照只能交接一次");return o=!1,Or.set(n,t),n}}}function as(e,t,r){if(F(r),!Number.isSafeInteger(t)||t<=0)throw new L("budget","快照预算应为正安全整数","$.budget.maxPreparedBytes");const n=Or.get(e);if(Or.delete(e),n!==void 0&&n<=t)return e;const o=Qi(e,{maxBytes:t,maxNodes:t,check:()=>F(r),error:(i,s)=>i==="budget"?new L("budget",s,"$.budget.maxPreparedBytes"):new $("validate",s)});return us(o),o}function cs(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 us(e){if(!cs(e.sources))throw new $("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 $("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)||!Fe(t)||!Lr(t)))throw new $("validate","准备结果诊断无效");if(e.diagnosticSummary!==void 0&&!vo(e.diagnosticSummary,e.diagnostics))throw new $("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 $("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 $("validate","准备结果字体度量标识无效")}function Cd(e){if(e.layoutPolicy!==void 0&&!["verify","preserve"].includes(e.layoutPolicy))throw new $("validate","无效的 layoutPolicy");if(e.format!=="pdf")return;if(e.layoutPolicy==="preserve"&&!e.prepared.layout?.fontFingerprint){mr(e.prepared,[{code:"prepared-layout-preserved",severity:"info",message:"显式保持现有分页与几何;未验证排版字体身份,实际 PDF 输出仍遵循 fidelity 校验。"}]);return}const t=e.prepared.layout?.fontFingerprint,r=ss(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 $("validate",n);mr(e.prepared,[{code:"prepared-font-metrics",severity:"warning",message:n}])}function Td(e){let t=`$.pages.${e.pageIndex}`;if(e.componentIndex<0)return t;t+=`.components.${e.componentIndex}`;const r=e.componentPath??[];for(let n=0;n+1<r.length;n+=3)t+=`.grid.cells.${r[n]}.${r[n+1]}`,r[n+2]!==void 0&&(t+=`.children.${r[n+2]}`);return t}function Se(e=[]){return e.map(t=>({...t,path:Td(t)}))}function jd(e,t){const r=rt(t??(e.diagnosticSummary?Ye:void 0));return e.diagnosticSummary?r.merge(e.diagnosticSummary):e.diagnostics.forEach(n=>r.push(n)),r}function Qn(e,t){t.diagnosticSummary?e.merge({...t.diagnosticSummary,entries:Se(t.diagnosticSummary.entries)}):Se(t.diagnostics).forEach(r=>e.push(r))}function Dd(e){const t=e.prepared.diagnosticSummary?.counts,r=t?!!(t["asset-render-failed"]||t["asset-budget-exceeded"]):e.prepared.diagnostics.some(n=>n.code==="asset-render-failed"||n.code==="asset-budget-exceeded");if(e.fidelity==="strict"&&r)throw new $("validate","严格输出拒绝已有资产渲染降级,请修复组件后重新准备报表。")}async function eo(e,t,r=Date.now()){const n=e.prepared;yn(e,t),Dd(e);const o=jd(n,e.diagnosticLimit),i=e.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;F(e.signal);const s=e.pdf?.customFontFaces??(e.pdf?.customFontBytes?{regular:e.pdf.customFontBytes}:void 0),a=i&&s?i.createFontBytesMeasurer(s):void 0,c=pe(e),u=await c.run("encode",async()=>{let l;const m={fidelity:e.fidelity,diagnosticLimit:e.diagnosticLimit??(n.diagnosticSummary?Ye:void 0),signal:e.signal,onProgress:(h,g)=>c.progress("encode",h,g)};if(e.format==="pdf"){F(e.signal);const h=await i.renderPlanToPdf(n.plan,{...e.pdf,...a?{measurer:a}:{},...m});l=h.bytes,Qn(o,h),tr(o,"pdf-fidelity",h.fidelityWarnings,"warning",h.fidelityWarningCount),tr(o,"pdf-page",h.pageErrors,"error",h.pageErrorCount),h.unsupportedTextCount&&o.push({code:"pdf-font",message:`${h.unsupportedTextCount} 段文本包含当前字体不支持的字符`,severity:"warning"})}else{const{renderPlanToXlsx:h}=await import("@agile-team/mach-report/xlsx");F(e.signal);const g=await h(n.plan,{...e.xlsx,...m});l=new Uint8Array(g.buffer),Qn(o,g),tr(o,"xlsx-fidelity",g.warnings,"warning",g.warningCount),g.notes?.forEach(y=>o.push({code:"xlsx-snapshot",message:y,severity:"info"}))}return F(e.signal),l});T(t,"maxOutputBytes",u.byteLength);const{plan:f,...d}=n;return{...d,diagnostics:o.entries,...e.diagnosticLimit===void 0&&!n.diagnosticSummary?{}:{diagnosticSummary:o.snapshot()},bytes:u,format:e.format,contentType:e.format==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",stats:{...d.stats,durationMs:Date.now()-r,outputBytes:u.byteLength}}}function Ie(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ld(e){return Ie(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 Bd(e){return Array.isArray(e)&&e.every(t=>Ie(t)&&typeof t.code=="string"&&typeof t.message=="string"&&["info","warning","error"].includes(t.severity)&&Fe(t)&&Lr(t))}function _d(e){return Ie(e)&&Object.values(e).every(t=>Ie(t)&&(t.revision===void 0||typeof t.revision=="string")&&(t.sourceToken===void 0||typeof t.sourceToken=="string"))}function Kd(e){return e===void 0?!0:Ie(e)&&["heuristic","provided","font-bytes"].includes(e.textMetrics)&&(e.fontFingerprint===void 0||typeof e.fontFingerprint=="string"&&/^[a-f0-9]{64}$/.test(e.fontFingerprint))}function fs(e,t){if(!Ie(e)||!Ld(e.stats)||!Bd(e.diagnostics)||!_d(e.revisions)||!Kd(e.layout)||!cs(e.sources)||e.diagnosticSummary!==void 0&&!vo(e.diagnosticSummary,e.diagnostics))return!1;if(t==="prepare")return Re(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 to(e,t){if(!fs(e,"export")||!("format"in e)||e.format!==t)throw new $("validate","报表执行器返回的导出结果与请求格式不一致或元数据无效")}function ro(e){return{...e,reportIds:[...e.reportIds],...e.params?{params:{...e.params}}:{}}}function ls(e,t){if(t.length===0)throw new $("config","缺少报表 ID");return t.map(r=>{if(!Object.prototype.hasOwnProperty.call(e,r))throw new $("config",`未注册报表 ${r}`);return e[r]})}function Zt(e){return e.grid?.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+Zt(s),0)??0):0),0),0)??0}function Wd(e,t,r){return e.pages.reduce((n,o)=>n+o.components.reduce((i,s)=>s.kind!=="list"?i+Zt(s):i+Bu(s,t,r),0),0)}function zd(e,t=Object.keys(e)){return ls(e,t).map((r,n)=>{const o=t[n],i=Rt(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,ed(typeof r.template=="function"?void 0:r.template,s,a)])),capabilities:{save:!!r.provider?.save,export:!!r.provider?.export,templates:!!r.provider?.templates}}})}function ds(e,t){ls(e,t.reportIds);const r=Sr(Rt(e,t.reportIds),t.params),n=t.reportIds.flatMap(i=>Sr(Rt(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 Ir(e,t){const r=Re(e.plan);if(!r.ok)throw new $("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+Zt(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 no(e,t){const r=ds(e.reports,t);if(!r.ok)throw new Gt(r.issues)}function ms(e){const t={...gn,...e.budget};qi(t);const r=async(o,i)=>{const s=Date.now();let a=0,c=0;const u=rt(o.diagnosticLimit),f={},d=[],l=Object.fromEntries(Object.entries(e.reports).map(([b,S])=>[b,{...S,pagination:{...e.pagination,...S.pagination,...i?{measurer:i}:{}},dataValidation:{...S.dataValidation,maxRows:Math.min(t.maxRows??1e5,S.dataValidation?.maxRows??1/0),maxCells:Math.min(t.maxCells??2e6,S.dataValidation?.maxCells??1/0)}}])),h=await fd(l,{maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents,onDatasets:(b,S,C)=>{try{a+=Ql(C,S,{maxRows:t.maxRows,signal:o.signal})}catch(B){throw B instanceof jo?new L("budget",B.message,"$.budget.maxRows"):B}T(t,"maxRows",a),c+=Wd(C,S,l[b]?.pagination),T(t,"maxCells",c)}})({...o,params:o.params??{},onWarning:b=>u.push({code:"layout",message:b,severity:"warning"}),onQueryResult:(b,S,C=0)=>{const B=hn(C,b);Object.defineProperty(f,b,{value:{revision:S.revision,sourceToken:S.sourceToken},enumerable:!0,writable:!0}),d.push({reportId:b,reportIndex:C,reportScope:B,...S.revision===void 0?{}:{revision:S.revision},...S.sourceToken===void 0?{}:{sourceToken:S.sourceToken}}),(S.diagnostics??[]).forEach(v=>u.push({...v,...v.target?{target:{...v.target,reportScope:B,...v.target.tableId?{tableId:JSON.stringify([C,b,v.target.tableId])}:{}}}:{}}))}}).catch(b=>{throw b instanceof $&&b.cause instanceof Pe?new L("budget",b.cause.message,"$.budget.maxPages"):b instanceof $&&b.cause instanceof Ze?new L("budget",b.cause.message,"$.budget.maxCells"):b instanceof $&&b.cause instanceof Qe?new L("budget",b.cause.message,"$.budget.maxChartComponents"):b});F(o.signal);const g=e.assets?await pe(o).run("assets",()=>Xn(h,{...e.assets,diagnosticLimit:o.diagnosticLimit,signal:o.signal})):{plan:h,diagnostics:[]},y=g.plan;g.diagnosticSummary?u.merge({...g.diagnosticSummary,entries:Se(g.diagnosticSummary.entries)}):Se(g.diagnostics).forEach(b=>u.push(b));const w=y.pages.reduce((b,S)=>b+S.components.reduce((C,B)=>C+Zt(B),0),0);T(t,"maxPages",y.pages.length),T(t,"maxCells",w);const p=ss(o.pdf),x=e.pagination?.measurer||Object.values(e.reports).some(b=>b.pagination?.measurer);return{plan:y,diagnostics:u.entries,...o.diagnosticLimit===void 0?{}:{diagnosticSummary:u.snapshot()},revisions:f,sources:d,layout:{textMetrics:p?"font-bytes":x?"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 $("config","不支持的报表导出格式");const s=o.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;F(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 F(o.signal),eo({...o,prepared:u},t,i)};return{describe:o=>zd(e.reports,o),validate:o=>ds(e.reports,o),prepare:o=>ze(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=ro(o),u={...c,...c.pdf?{pdf:He(c.pdf)}:{},taskId:c.taskId??pt()},f=a?g=>Ee(a,g,i):void 0,d={...u,signal:i,onEvent:f};pe(d).runSync("validate",()=>no(e,u));let l;const m=u.pdf?.customFontFaces??(u.pdf?.customFontBytes?{regular:u.pdf.customFontBytes}:void 0);if(!e.executor&&m){const g=await import("@agile-team/mach-report/pdf");F(i),l=g.createFontBytesMeasurer(m)}const h=e.executor?await e.executor.prepare(u,i,f):await r(d,l);return Ir(h,t)}),exportPrepared:o=>ze(o.signal,t.maxDurationMs,async i=>{const s=Date.now(),{signal:a,onEvent:c,...u}=o,f=Ir(as(o.prepared,t.maxPreparedBytes??64e6,i),t),d={...u,xlsx:Nr(u.xlsx),prepared:f,...u.pdf?{pdf:He(u.pdf)}:{},taskId:u.taskId??pt()};if(d.format!=="pdf"&&d.format!=="xlsx")throw new $("config","不支持的报表导出格式");const l=c?h=>Ee(c,h,i):void 0;if(e.executor){if(!e.executor.exportPrepared)throw new $("config","执行器未实现 exportPrepared;请升级执行器或显式使用本地运行时");const h=await e.executor.exportPrepared(d,i,l);return to(h,d.format),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(pe(m).runSync("validate",()=>Cd(m)),e.assets){const h=await pe(m).run("assets",()=>Xn(f.plan,{...e.assets,diagnosticLimit:o.diagnosticLimit,signal:i}));f.plan=h.plan,mr(f,Se(h.diagnostics),h.diagnosticSummary?{...h.diagnosticSummary,entries:Se(h.diagnosticSummary.entries)}:void 0,o.diagnosticLimit)}return eo(m,t,s)}),export:o=>ze(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=ro(o),u={...c,xlsx:Nr(c.xlsx),...c.pdf?{pdf:He(c.pdf)}:{},taskId:c.taskId??pt()},f=a?m=>Ee(a,m,i):void 0,d={...u,signal:i,onEvent:f};if(pe(d).runSync("validate",()=>no(e,u)),u.format!=="pdf"&&u.format!=="xlsx")throw new $("config","不支持的报表导出格式");const l=e.executor?await e.executor.export(u,i,f):await n(d);return e.executor&&to(l,u.format),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 Vd={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 oe(e){return++e.visits>=1e5&&(e.capped=!0),!Je(e)}function Z(e){return typeof e=="string"?e.length*2:0}function oo(e,t){for(const r of e??[]){if(!oe(t))return;for(const n of r.segments){if(!oe(t))return;t.bytes+=Z(n.text)}}}function hs(e,t,r){if(r>32){t.capped=!0;return}if(oe(t)){t.bytes+=Z(e.text)+Z(e.rawText)+Z(e.imageData),oo(e.richParagraphs,t);for(const n of e.lines??[]){if(!oe(t))return;t.bytes+=Z(n)}for(const n of e.grid?.cells??[]){if(!oe(t))return;for(const o of n){if(!oe(t))return;if(o){t.cells++,t.bytes+=Z(o.text)+Z(o.rawText)+Z(o.value),oo(o.richParagraphs,t);for(const i of o.children??[]){if(Je(t))return;hs(i,t,r+1)}}}}}}function Hd(e,t){if(e.format==="xlsx")for(const r of e.xlsx?.additionalSheets??[]){if(!oe(t))return;t.bytes+=Z(r?.name);for(const n of r?.rows??[]){if(!oe(t))return;for(const o of n??[]){if(!oe(t))return;t.cells++,t.bytes+=Z(o)}}}}function Jd(e){const t={...Vd,...e.thresholds};for(const r of Object.values(t))if(!Number.isSafeInteger(r)||r<=0)throw new RangeError("导出隔离阈值应为正安全整数");return t}function Ud(e,t){const r=Jd(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;hs(c,o,0)}}Hd(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 de="mach-report-worker/1";class Fr 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,this.diagnosticSummary=t.diagnosticSummary,this.issueSummary=t.issueSummary}}function Ae(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Gd(e,t){return fs(e,t)}function gs(e){if(!e||typeof e!="object")return{message:String(e).slice(0,4096)};const t={};for(const r of["code","path","field","message"]){const n=e[r];typeof n=="string"&&(t[r]=n.slice(0,r==="code"?128:4096))}return t}function Yd(e){const t=gs(e);if(!Ae(e))return t;for(const r of["format","severity","kind","nid"])typeof e[r]=="string"&&(t[r]=e[r].slice(0,4096));for(const r of["pageIndex","componentIndex"])Number.isSafeInteger(e[r])&&e[r]>=0&&(t[r]=e[r]);if(Fe(e)&&e.valueState!==void 0&&Ae(e.target)){t.valueState=e.valueState;const r={};for(const n of["datasetId","field","rowKey","tableId","reportScope"])e.target[n]!==void 0&&(r[n]=e.target[n]);t.target=r}return Ae(e.extension)&&typeof e.extension.id=="string"&&typeof e.extension.version=="string"&&(t.extension={id:e.extension.id.slice(0,128),version:e.extension.version.slice(0,64)}),Array.isArray(e.componentPath)&&e.componentPath.length<=192&&e.componentPath.every(r=>Number.isSafeInteger(r)&&r>=0)&&(t.componentPath=e.componentPath),t}function io(e){return{code:Ae(e)&&typeof e.code=="string"?e.code:"unknown",value:e,...Ae(e)&&e.valueState!==void 0&&Fe(e)?{valueState:e.valueState}:{}}}function so(e,t,r){const n=rt(Ye);if(yo(r))n.merge({...r,entries:r.entries.slice(0,Ye).map(io)});else for(const i of e)n.push(io(i));const o=n.snapshot();return{...o,entries:o.entries.map(i=>t(i.value))}}function ps(e){if(!(e instanceof Error))return{name:"Error",message:String(e).slice(0,8192)};const t=e,r=Array.isArray(t.diagnostics)?so(t.diagnostics,Yd,t.diagnosticSummary):void 0,n=Array.isArray(t.issues)?so(t.issues,gs):void 0;return{name:e.name.slice(0,128),message:e.message.slice(0,8192),...typeof t.code=="string"?{code:t.code.slice(0,128)}:{},...typeof t.path=="string"?{path:t.path.slice(0,4096)}:{},...n?{issues:n.entries,...n.omitted?{issueSummary:n}:{}}:{},...r?{diagnostics:r.entries,...r.omitted||t.diagnosticSummary!==void 0?{diagnosticSummary:r}:{}}:{}}}function ys(e){if(!e||typeof e!="object")return!1;const t=e;return t.protocol===de&&typeof t.id=="string"&&(t.operation==="prepare"||t.operation==="export"||t.operation==="exportPrepared")&&!!t.input&&typeof t.input=="object"}async function ws(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:de,id:t.id,result:n}}catch(n){return{protocol:de,id:t.id,error:ps(n)}}}function bs(e){const t=e.result;return!t||!("bytes"in t)||!(t.bytes.buffer instanceof ArrayBuffer)?[]:[t.bytes.buffer]}function qd(e,t){if(!Ae(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 Rr extends Error{constructor(t){super("报表 Worker 无法启动"),this.cause=t,this.name="ReportWorkerStartError"}}let Xd=0;function ao(e){const t=new Error("报表 Worker 任务已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e}),t}function Zd(e,t){if(!e||typeof e!="object")return;const r=e;return r.protocol===de&&r.id===t?r:void 0}function Qd(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(ao(s.reason)):new Promise((c,u)=>{let f;try{f=e()}catch(p){u(new Rr(p));return}const d=`mach-report-${Date.now()}-${++Xd}`;let l=!1,m=()=>{},h;const g=(p,x)=>{if(l)return;l=!0,h&&clearTimeout(h);let b;try{m()}catch(S){b=S}s?.removeEventListener("abort",y),p??=b,Promise.resolve().then(()=>f.terminate()).then(()=>p===void 0?c(x):u(p),S=>u(p??S))},y=()=>g(ao(s?.reason)),w=p=>{const x=Zd(p,d);if(!(!x||l)){if("type"in x&&x.type==="event"){const b="event"in x?x.event:void 0;qd(b,i)?Ee(a,b,s):g(new Error("报表 Worker 返回无效阶段事件"));return}x.error&&typeof x.error.name=="string"&&typeof x.error.message=="string"?g(new Fr(x.error)):Gd(x.result,o)&&(o==="prepare"||"format"in x.result&&"format"in i&&x.result.format===i.format)?g(void 0,x.result):g(new Error("报表 Worker 返回无效响应"))}};try{if(m=f.subscribe(w,p=>g(p??new Error("报表 Worker 执行失败"))),l){m();return}if(s?.addEventListener("abort",y,{once:!0}),h=setTimeout(()=>g(new Fr({name:"ReportRuntimeError",code:"timeout",message:`报表 Worker 执行超过 ${r}ms`})),r),s?.aborted)y();else{const{onEvent:p,signal:x,...b}=i,S=em(b);f.postMessage({protocol:de,id:d,operation:o,input:b,...t.budget?{budget:t.budget}:{}},S)}}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 em(e){return e.pdf?(e.pdf=He(e.pdf),(e.pdf?.customFontFaces?Object.values(e.pdf.customFontFaces):[e.pdf?.customFontBytes]).filter(r=>r instanceof Uint8Array).map(r=>r.buffer)):[]}function tm(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("无效的导出回退策略");qi({...e.budget,maxDurationMs:e.timeoutMs??e.budget?.maxDurationMs??12e4})}function co(e,t){ue.observeOutput(()=>e.onDecision?.({...t,estimate:{...t.estimate}}))}function uo(e,t){return{...e,mode:"local",reason:t,hardCancellation:!1}}function fo(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),yn({...t,prepared:{...t.prepared,stats:e.stats}},r)}function rm(e,t){const r={...gn,...t.budget},n=Rd(e.prepared,r.maxPreparedBytes,e.signal),o={...e,prepared:n.prepared,pdf:He(e.pdf),xlsx:Nr(e.xlsx)};return{request:o,forward:()=>({...o,prepared:n.forward()})}}function nm(e,t){tm(e);const r={...e,thresholds:{...e.thresholds},budget:{...gn,...e.budget}},n=r.timeoutMs??r.budget.maxDurationMs??12e4,o=ms({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 w=n-(Date.now()-d);if(w<=0)throw new L("timeout",`报表执行超过 ${n}ms`);return w};let m=Ud(u,r);if(m.reason==="nonserializable-options"&&r.mode==="worker")throw new TypeError("Worker 模式不接受函数选项;请使用本地模式或可序列化配置");if(m.mode==="worker"&&!t){if(!a)throw new Rr(new Error("未配置 workerFactory"));m=uo(m,"worker-unavailable")}const h=rm(u,r),g=h.request;if(co(r,m),F(u.signal),m.mode==="worker")try{const w=t(l());if(!w.exportPrepared)throw new TypeError("隔离执行器缺少 exportPrepared");const{signal:p,onEvent:x,...b}=g,S=await w.exportPrepared(b,p,x);return F(p),fo(S,g,r.budget),{...S,execution:m}}catch(w){if(!(w instanceof Rr)||!a)throw w;F(u.signal),m=uo(m,"worker-start-failed"),co(r,m)}f&&(g.prepared=Ir(g.prepared,r.budget),yn(g,r.budget));const y=f?await ze(u.signal,l(),w=>f({...g,signal:w})):await ze(u.signal,l(),w=>o.exportPrepared({...h.forward(),signal:w}));return F(u.signal),fo(y,g,r.budget),{...y,execution:m}}return{async exportPrepared(u,f){if(s)throw new L("closed","导出执行器已释放");if(F(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 om(e,t){try{if(e.operation!=="exportPrepared")throw new TypeError("内置编码 Worker 仅接受 exportPrepared");return await ws(ms({reports:{},budget:e.budget}),e,t)}catch(r){return{protocol:de,id:e.id,error:ps(r)}}}class A extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportJobError"}}function Bt(e,t){if(typeof e!="string"||!e.trim()||e.length>256||typeof t!="string"||t!==t.trim()||!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(t))throw new A("input","任务范围应非空,ID应为1–128位安全标识")}function im(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 A("input","任务对象应为普通 JSON 对象");if(Object.getOwnPropertySymbols(e).length)throw new A("input","任务不能包含Symbol");if(Object.getOwnPropertyNames(e).filter(i=>!(t&&i==="length")).length!==n.length)throw new A("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 A("input","任务数组不能稀疏或包含额外属性");return n.sort()}function sm(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(["__proto__","prototype","constructor"].includes(t)||r.get||r.set)throw new A("input","任务不能包含危险键或访问器");return r.value}function ae(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 A("input","任务JSON预算无效");let o=0,i=0;const s=new Set;function a(u,f){if(++o>r||f>32)throw new A("input","任务数据超过节点或深度预算");if(typeof u=="string"){if(i+=u.length,i>n)throw new A("input","任务文本超过预算");return u}if(u===null||typeof u=="boolean"||typeof u=="number"&&Number.isFinite(u))return u;if(!u||typeof u!="object"||s.has(u))throw new A("input","任务只允许无循环的有限 JSON 值");const d=Array.isArray(u),l=im(u);s.add(u);const m=Object.create(null);for(const h of l){if(i+=h.length,i>n)throw new A("input","任务文本超过预算");m[h]=a(sm(u,h),f+1)}return s.delete(u),d?Array.from({length:u.length},(h,g)=>m[String(g)]):m}const c=JSON.stringify(a(e,0));if(c.length>n)throw new A("input","任务序列化数据超过字符预算");return c}function fr(e){return JSON.parse(JSON.stringify(e))}function xs(e,t,r,n){if(Bt(t,r),e.scope!==t||e.id!==r||e.revision!==(n??0)+1||!Number.isSafeInteger(e.revision))throw new A("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 A("input","任务状态无效");if(e.lease&&(!e.lease.owner||!Number.isSafeInteger(e.lease.expiresAt)))throw new A("input","任务租约无效");if(!e.request||typeof e.request.kind!="string"||!e.request.kind.trim()||e.request.kind.length>128)throw new A("input","任务类型无效");ae(e.request.payload,{maxNodes:19e3,maxCharacters:75e4}),ae(e)}function am(e,t){if(e&&(e.createdAt!==t.createdAt||ae(e.request)!==ae(t.request)))throw new A("input","任务创建时间与请求不可变更,请使用新任务ID")}function cm(e,t){return e.status==="queued"||e.status==="running"&&(e.lease?.expiresAt??0)<=t}function um(e={}){const t={maxRecords:e.maxRecords??1e4,maxBytes:e.maxBytes??67108864,maxResultBytes:e.maxResultBytes??262144,controlReserveBytes:e.controlReserveBytes??4096,maxTombstones:e.maxTombstones??1e4,maxTombstoneBytes:e.maxTombstoneBytes??16777216};if(!Object.values(t).every(r=>Number.isSafeInteger(r)&&r>0)||t.controlReserveBytes<4096)throw new A("input","任务容量应为正整数,控制状态预留至少4096字节");return t}function Ue(e){return new TextEncoder().encode(ae(e)).byteLength}function vs(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:Ue(e.result);if(o>t.maxResultBytes)throw new A("capacity","任务结果超过独立预算,请保存文件引用");return Math.max(Ue(r)+t.controlReserveBytes,Ue(n))+o}function Ms(e){return e.status!=="queued"&&e.status!=="running"}function fm(e){const t={...e,tombstoneRetentionMs:e.tombstoneRetentionMs??6048e5,limit:e.limit??100};if(![t.now,t.terminalBefore].every(r=>Number.isSafeInteger(r)&&r>=0)||t.terminalBefore>t.now)throw new A("input","终态清理时间应为不超过当前时间的非负整数");if(![t.tombstoneRetentionMs,t.limit].every(r=>Number.isSafeInteger(r)&&r>0)||!Number.isSafeInteger(t.now+t.tombstoneRetentionMs))throw new A("input","幂等保留期与清理批量应为正整数");return t}async function lm(e){const t=new TextEncoder().encode(ae(e)),r=globalThis.crypto?.subtle;if(!r)return Nd(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 dm(e,t){if(!Ms(e))throw new A("input","只能归档终态任务");return{scope:e.scope,id:e.id,revision:e.revision,status:e.status,createdAt:e.createdAt,updatedAt:e.updatedAt,attempt:e.attempt,requestHash:await lm(e.request),expiresAt:t}}function mm(e){if(!e||!["completed","failed","cancelled"].includes(e.status)||!/^[a-f0-9]{64}$/.test(e.requestHash))throw new A("input","任务幂等摘要无效");if(![e.revision,e.createdAt,e.updatedAt,e.attempt,e.expiresAt].every(t=>Number.isSafeInteger(t)&&t>=0)||e.revision<1)throw new A("input","任务幂等摘要时间或修订无效")}function st(e){return e?.code}function Ge(e,t){return be.createHash("sha256").update(JSON.stringify([e,t])).digest("hex")+".json"}async function Cr(e){try{return await E.promises.readFile(e,"utf8")}catch(t){if(st(t)==="ENOENT")return;throw t}}async function hm(e,t){const r=await Cr(e);if(r===void 0)return;let n;try{n=JSON.parse(r)}catch{throw new A("conflict","任务锁尚未完整写入或已损坏,拒绝自动移除")}if(!n||!Number.isSafeInteger(n.pid)||n.pid<1)throw new A("conflict","任务锁身份无效,拒绝自动移除");try{process.kill(n.pid,0)}catch(o){if(st(o)==="ESRCH"){await E.promises.unlink(e);return}throw o}throw new A("conflict","任务目录的写入进程仍在运行")}async function gm(e,t){if(!t)throw new A("conflict","任务目录已有写入进程;多实例请使用数据库CAS适配器");const r=e+".recovery";let n;try{n=await E.promises.open(r,"wx",384)}catch(o){throw st(o)==="EEXIST"?new A("conflict","任务目录恢复正在进行,请稍后重试"):o}try{return await n.writeFile(JSON.stringify({pid:process.pid})),await hm(e,!0),await E.promises.open(e,"wx",384)}finally{await n.close(),await E.promises.unlink(r)}}async function pm(e,t){const r=D.join(e,".writer-lock"),n=be.randomUUID();let o;try{o=await E.promises.open(r,"wx",384)}catch(i){if(st(i)!=="EEXIST")throw i;o=await gm(r,t)}try{await o.writeFile(JSON.stringify({pid:process.pid,token:n})),await o.sync()}catch(i){throw await o.close(),await E.promises.unlink(r).catch(()=>{}),i}return{file:r,token:n,handle:o}}function ym(e,t,r,n){if("tombstone"in r){const o=r.tombstone;if(mm(o),Bt(o.scope,o.id),Ge(o.scope,o.id)!==t)throw new A("input","持久任务摘要身份不匹配");const i=Ue(o);e.tombstoneBytes+=i,e.tombstones.set(t,{value:o,bytes:i})}else{if(xs(r,r.scope,r.id,r.revision-1),Ge(r.scope,r.id)!==t)throw new A("input","持久任务文件身份不匹配");const o=vs(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 A("capacity","持久任务及控制状态预留超过目录预算")}async function wm(e,t){const r=await E.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 E.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 A("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 E.promises.stat(s)).size>4e6)throw new A("capacity","持久任务文件超过单文件预算");ym(o,i,JSON.parse(await E.promises.readFile(s,"utf8")),t)}return o}async function bm(e,t,r){const n=D.join(e,`.pending-${be.randomUUID()}`);try{const o=await E.promises.open(n,"wx",384);try{await o.writeFile(r),await o.sync()}finally{await o.close()}await E.promises.rename(n,D.join(e,t));const i=await E.promises.open(e,"r");try{await i.sync()}finally{await i.close()}}finally{await E.promises.unlink(n).catch(o=>{if(st(o)!=="ENOENT")throw o})}}async function xm(e){const t=D.resolve(e.directory),r=um(e);await E.promises.mkdir(t,{recursive:!0,mode:448});const n=await pm(t,e.recoverDeadOwner??!1);let o;try{o=await wm(t,r)}catch(l){throw await n.handle.close(),await E.promises.unlink(n.file),l}let i=!1,s=Promise.resolve();const a=()=>{if(i)throw new A("closed","持久任务存储已关闭")},c=l=>{a();const m=s.then(async()=>{if(JSON.parse(await E.promises.readFile(n.file,"utf8")).token!==n.token)throw new A("closed","持久任务存储写入锁已失效");return l()});return s=m.then(()=>{},()=>{}),m},u=async(l,m,h)=>{try{await bm(t,l,m)}catch(g){throw await Cr(D.join(t,l))===m&&h(),g}h()};return{read:async(l,m)=>{a(),Bt(l,m),await s;const h=o.records.get(Ge(l,m));return h?fr(h.record):void 0},readTombstone:async(l,m)=>{a(),Bt(l,m),await s;const h=o.tombstones.get(Ge(l,m));return h?fr(h.value):void 0},candidates:async(l,m)=>(a(),await s,Array.from(o.records.values(),h=>h.record).filter(h=>cm(h,l)).sort((h,g)=>h.createdAt-g.createdAt).slice(0,m).map(fr)),compareAndSwap:async(l,m,h,g)=>{const y=JSON.parse(ae(g));return xs(y,l,m,h),c(async()=>{const w=Ge(l,m),p=o.records.get(w);if((p?.record.revision??null)!==h||o.tombstones.has(w))return!1;am(p?.record,y);const x=vs(y,r),b=o.bytes-(p?.bytes??0)+x;if(b>r.maxBytes||!p&&o.records.size>=r.maxRecords)throw new A("capacity","持久任务容量已满,请清理终态任务或扩大显式预算");return await u(w,ae(y),()=>{o.records.set(w,{record:y,bytes:x}),o.bytes=b}),!0})},prune:async l=>{const m=fm(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 E.promises.unlink(D.join(t,g)),o.tombstones.delete(g),o.tombstoneBytes-=y.bytes,h.expired++);for(const[g,y]of o.records){if(!Ms(y.record)||y.record.updatedAt>m.terminalBefore||h.archived+h.expired>=m.limit)continue;const w=await dm(y.record,m.now+m.tombstoneRetentionMs),p=Ue(w);if(o.tombstones.size>=r.maxTombstones||o.tombstoneBytes+p>r.maxTombstoneBytes)break;await u(g,ae({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 E.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 Cr(n.file);l&&JSON.parse(l).token===n.token&&await E.promises.unlink(n.file)}}}class I extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportDocumentError"}}function vm(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 I("input","文档预算应为正安全整数");return t}function he(e,t,r){if([e,t,...r===void 0?[]:[r]].some(n=>typeof n!="string"||!n.trim()||n.length>256))throw new I("input","文档 scope、id、version 应为 1–256 位非空字符串");return JSON.stringify([e,t])}function X(e,t,r){return Qi(e,{maxBytes:t,maxNodes:t,check:()=>F(r),error:(n,o)=>new I(n==="budget"?"capacity":"input",o)})}function $e(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}function lo(e){if(!e||e.schemaVersion!==nt||"pages"in e||e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean")throw new I("input","文档计划头应使用当前版本,且不得携带 pages")}function ut(e,t){e.bytes=0;for(let r=0;r<8;r++){const n=t+$e(e);if(n===e.bytes)return;e.bytes=n}throw new I("capacity","文档容量统计无效")}function Mm(e,t,r=[]){const n=new Map;let o=0,i=Promise.resolve();for(const f of r){const d=he(f.scope,f.id,f.version);if(lo(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 I("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 I("capacity","文档存储容量已满,请显式清理旧文档")}if(n.size>t.maxDocuments||o>t.maxBytes)throw new I("capacity","已存文档超过预算");const a=f=>{const d=i.then(f);return i=d.then(()=>{},()=>{}),d},c=(f,d,l,m)=>{const h=n.get(he(f,d,l));if(!h)throw new I("missing","文档不存在");if(h.version!==l||m!==void 0&&h.revision!==m)throw new I("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(he(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=he(l.scope,l.id,l.version);return lo(l.plan),a(async()=>{if(F(d),n.has(m))throw new I("conflict","文档已存在,不可覆盖");const h={...l,revision:0,state:"building",pageCount:0,bytes:0};return ut(h,0),u(h)})},append:(f,d,l,m,h,g)=>{const y=X(h,t.maxPageBytes,g),w=Re({pages:[y]});if(!w.ok)throw new I("input",w.errors[0].message);return a(async()=>{F(g);const p=c(f,d,l,m);if(p.state!=="building")throw new I("conflict","已完成文档不可追加");if(p.pageCount>=t.maxPages)throw new I("capacity","文档页数超过预算");const x={...p,revision:m+1,pageCount:p.pageCount+1};return ut(x,p.bytes-$e(p)+$e(y)),u(x,p,{index:p.pageCount,value:y})})},complete:(f,d,l,m,h,g)=>{const y=h===void 0?void 0:X(h,t.maxManifestBytes,g);return y&&us({...y}),a(async()=>{F(g);const w=c(f,d,l,m);if(w.state!=="building")throw new I("conflict","文档已完成");if(y&&y.stats.pages!==w.pageCount)throw new I("input","准备结果页数与文档页数不一致");const p={...w,revision:m+1,state:"complete",...y?{metadata:y}:{}};return ut(p,w.bytes-$e(w)),u(p,w)})},fail:(f,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 I("input","文档失败状态无效");return a(async()=>{const y=c(f,d,l,m);if(y.state!=="building")throw new I("conflict","终态文档不可变更");const w={...y,state:"failed",revision:m+1,failure:g};return ut(w,y.bytes-$e(y)),u(w,y)})},read:async(f,d,l)=>{F(l);const m=he(f,d);await i,F(l);const h=n.get(m);return h?X(h,t.maxManifestBytes):void 0},readPage:(f,d,l,m,h)=>a(async()=>{F(h);const g=c(f,d,l);if(!Number.isSafeInteger(m)||m<0)throw new I("input","页索引应为非负安全整数");if(m>=g.pageCount)return;const y=await e.readPage(f,d,m);if(F(h),!y)throw new I("missing","已提交的文档页缺失");return X(y,t.maxPageBytes,h)}),remove:(f,d,l,m)=>a(async()=>{F(m);const h=he(f,d,l),g=n.get(h);return g?(c(f,d,l),await e.remove(g),n.delete(h),o-=g.bytes,!0):!1})}}const Tr=e=>e?.code,yt=(e,t)=>be.createHash("sha256").update(he(e,t)).digest("hex");async function jr(e,t){const r=await E.promises.lstat(e);if(!r.isFile()||r.size>t)throw new I("capacity","文档文件类型或大小无效");return X(JSON.parse(await E.promises.readFile(e,"utf8")),t)}async function mo(e,t){const r=`${e}.pending-${be.randomUUID()}`;try{await E.promises.writeFile(r,JSON.stringify(t),{flag:"wx",mode:384}),await E.promises.rename(r,e)}finally{await E.promises.unlink(r).catch(n=>{if(Tr(n)!=="ENOENT")throw n})}}async function Sm(e,t){const r=(await E.promises.readdir(e)).filter(o=>/^[a-f0-9]{64}$/.test(o));if(r.length>t.maxDocuments)throw new I("capacity","文档数量超过目录预算");const n=[];for(const o of r){const i=D.join(e,o);if(!(await E.promises.lstat(i)).isDirectory())throw new I("input","文档目录不允许符号链接");const a=await jr(D.join(i,"manifest.json"),t.maxManifestBytes);if(yt(a.scope,a.id)!==o||!Number.isSafeInteger(a.pageCount)||a.pageCount<0||a.pageCount>t.maxPages)throw new I("input","文档清单身份或页数无效");let c=$e(a);for(let u=0;u<a.pageCount;u++){const f=await E.promises.lstat(D.join(i,`${u}.json`));if(!f.isFile()||f.size>t.maxPageBytes)throw new I("capacity","文档页文件类型或大小无效");c+=f.size}if(c!==a.bytes)throw new I("input","文档字节数与已提交页不一致");for(const u of await E.promises.readdir(i)){const f=/^(\d+)\.json$/.exec(u);(f&&Number(f[1])>=a.pageCount||/\.pending-[a-f0-9-]{36}$/.test(u))&&await E.promises.unlink(D.join(i,u))}n.push(a)}return n}async function $m(e){const t=vm(e),r=D.resolve(e.directory);await E.promises.mkdir(r,{recursive:!0,mode:448});const n=D.join(r,".document-writer-lock"),o=be.randomUUID();let i;try{i=await E.promises.open(n,"wx",384)}catch(l){throw Tr(l)==="EEXIST"?new I("conflict","文档目录已被占用;多实例请实现共享存储原子CAS"):l}try{await i.writeFile(JSON.stringify({pid:process.pid,token:o}))}catch(l){throw await i.close(),await E.promises.unlink(n),l}const s=async()=>{try{return(await jr(n,1024)).token===o}catch(l){if(Tr(l)==="ENOENT")return!1;throw l}},a=async()=>{if(!await s())throw new I("closed","文档存储写入锁已失效")};let c=Promise.resolve(),u=!1;const f=l=>{if(u)return Promise.reject(new I("closed","文档存储已关闭"));const m=l();return c=Promise.allSettled([c,m]).then(()=>{}),m};let d;try{const l=await Sm(r,t);d=Mm({write:async(m,h)=>{await a();const g=D.join(r,yt(m.scope,m.id));await E.promises.mkdir(g,{recursive:!0,mode:448}),h&&await mo(D.join(g,`${h.index}.json`),h.value);try{await mo(D.join(g,"manifest.json"),m)}catch(y){throw h?await E.promises.unlink(D.join(g,`${h.index}.json`)):m.revision===0&&await E.promises.rm(g,{recursive:!0}),y}},readPage:async(m,h,g)=>(await a(),jr(D.join(r,yt(m,h),`${g}.json`),t.maxPageBytes)),remove:async m=>{await a(),await E.promises.rm(D.join(r,yt(m.scope,m.id)),{recursive:!0})}},t,l)}catch(l){throw await i.close(),await E.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 E.promises.unlink(n))}}}function Ss(e){const t=e.filename??e.workerUrl;if(!t||e.filename&&e.workerUrl)throw new TypeError("请且仅请指定 filename 或 workerUrl");return Qd(()=>{const r=new Le.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 Em(e){const t=Le.parentPort;if(!t)throw new Error("serveNodeReportWorker 只能在 worker_threads 中调用");const r=n=>{ys(n)&&ws(e,n,o=>t.postMessage({protocol:de,id:n.id,type:"event",event:o})).then(o=>t.postMessage(o,bs(o)))};return t.on("message",r),()=>t.off("message",r)}function Am(e){return be.createHash("sha256").update(e).digest("hex")}function km(e={}){const t={timeoutMs:e.timeoutMs??e.budget?.maxDurationMs,budget:{...e.budget}};return nm(e,r=>Ss({filename:typeof __filename=="string"?__filename:new URL(typeof document>"u"?require("url").pathToFileURL(__filename).href:Qt&&Qt.tagName.toUpperCase()==="SCRIPT"&&Qt.src||new URL("server-node.cjs",document.baseURI).href),workerOptions:{workerData:{machReportEncoding:"prepared-v1"}},...t,timeoutMs:r}))}if(Le.parentPort&&Le.workerData?.machReportEncoding==="prepared-v1"){const e=Le.parentPort;e.on("message",t=>{ys(t)&&om(t,r=>e.postMessage({protocol:de,id:t.id,type:"event",event:r})).then(r=>e.postMessage(r,bs(r)))})}exports.ReportWorkerError=Fr;exports.createNodeAutoReportExporter=km;exports.createNodeReportExecutor=Ss;exports.openFileReportDocumentStore=$m;exports.openFileReportJobStore=xm;exports.reportArtifactSha256=Am;exports.serveNodeReportWorker=Em;
|