@aiking/bridge-reportkit 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ 君瓴智能 · 桥梁规范族插件包 软件许可协议
2
+ ==========================================
3
+
4
+ Copyright (c) 2026 君瓴智能。保留所有权利。All rights reserved.
5
+
6
+ 一、权利归属
7
+ 1. 本软件(包括插件源代码、数据表、文档与报告模板)为君瓴智能的商业产品,
8
+ 著作权及相关权利归君瓴智能所有。
9
+ 2. 未经书面许可,不得复制、修改、再分发、反向工程、出租或用于对外商业服务。
10
+
11
+ 二、规范条文摘录
12
+ 1. 本软件部分数据表依据标准出版机构授权收录了规范条文与表格的必要摘录,
13
+ 该部分内容的著作权归原标准发布机构所有。
14
+ 2. 该部分内容的使用范围以君瓴智能与相应出版机构之间的授权协议为准;
15
+ 被授权方不得将摘录内容单独抽取、另行汇编或转授权。
16
+ 3. 软件中的算法实现、数据结构、校验规则与报告排版引擎为君瓴智能自有成果。
17
+
18
+ 三、免责与专业边界
19
+ 1. 本软件按“现状”提供,不附带任何明示或默示担保。
20
+ 2. 本软件输出为技术计算成果,不构成工程设计文件、检测评定结论或执业签署,
21
+ 不替代注册执业人员的专业判断与签字。
22
+ 3. 使用方应结合工程实际与规范原文复核后方可采用。
23
+
24
+ 如需商业授权,请联系权利人。
package/NOTICE ADDED
@@ -0,0 +1,31 @@
1
+ NOTICE — 第三方内容说明
2
+ ========================
3
+
4
+ 本插件包在数据表中收录了以下规范的必要条文与表格摘录。该部分内容的著作权
5
+ 归各标准发布机构所有,收录范围以君瓴智能取得的授权为准。
6
+
7
+ 1. JTG/T 5231—2026《公路桥梁耐久性检测评定规程》
8
+ 2. JTG/T H21—2011《公路桥梁技术状况评定标准》
9
+ 3. JTG/T 3310—2019《公路工程混凝土结构耐久性设计规范》
10
+ 4. JTG 5120—2021《公路桥涵养护规范》
11
+ 5. JTG/T 5122—2021《公路缆索结构体系桥梁养护技术规范》
12
+ 6. JTG/T 5124—2022《跨海桥梁养护技术规范》
13
+ 7. JTG 5220—2020《公路养护工程质量检验评定标准》
14
+ 8. JTG F80/1—2017《公路工程质量检验评定标准 第一册 土建工程》
15
+
16
+ 自有成果部分
17
+ ------------
18
+ · 全部 Algorithm 实现(评分、合格率、剩余耐久年限、等级判定等计算链)
19
+ · 数据结构与数据校验规则
20
+ · Word 报告排版引擎(docx 构造器、LaTeX→OMML 公式转换、排版校验)
21
+ · 跨规范口径纪律与提示词注入内容
22
+
23
+ 数据来源与校验
24
+ --------------
25
+ 数据由 PDF 原文逐表转录,页码偏移与验证记录见各插件 rules/ 目录。
26
+ 已发现的原文印刷瑕疵按“照录不改”原则保留并单独标注,见 docs/ERRATA.md。
27
+
28
+ 免责
29
+ ----
30
+ 本仓库内容为技术计算工具的数据基础,不替代规范原文。
31
+ 涉及具体工程时,必须以现行有效版规范原文为准。
package/README.md CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # @aiking/bridge-reportkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > 工程报告排版基础设施(v1.0.0)。把「一份能直接交出去的桥梁检测/评定报告」所需的排版能力,收敛成可复用的组件。
4
+
5
+ ## 一、它解决什么问题
6
+
7
+ 在 reportkit 之前,每写一个新插件的报告,都要重新解决一遍:中文字体怎么设、西文怎么走 Times New Roman、页眉页脚怎么放、表名怎么编号、公式怎么变成 Word 可编辑对象、目录页码怎么生成。这些是**同一件事**,不该在每个插件里重做一遍。
8
+
9
+ ## 二、能力清单
10
+
11
+ | 能力 | 实现 | 关键点 |
12
+ |---|---|---|
13
+ | DOCX 生成 | `lib/docx.js` | 零依赖,ZIP store 方式;**XML 合法 ≠ docx 合法**,中央目录字段偏移是 16/20/24 不是 14/18/22 |
14
+ | 字体方案 | `docx.js` 的 `rFonts` | 标题黑体、正文楷体、数字/英文/符号自动走 Times New Roman(ascii 通道) |
15
+ | 彩色主题 | `DEFAULT_THEME` | 主色 `#1F4E79`、辅色 `#2E75B6`、表头底 `#DEEBF7` |
16
+ | 页眉页脚 | `renderHeader` / `renderFooter` | 页脚「第 X 页 共 Y 页」用 PAGE/NUMPAGES 域;封面用 `titlePg` 独占 |
17
+ | 表名编号 | `renderTable` | 自动「表 章-序 + 名称」,加粗居中,表头加粗+底色+跨页重复 |
18
+ | 公式 | `lib/latex2omml.js` | **LaTeX → OMML**,Word 里可双击编辑;居中 + 右侧(章-序) |
19
+ | 封面 | `renderCover` | 标题/副标题/分隔线/信息条目/单位日期 |
20
+ | 目录 | `renderToc` | TOC 域 + 预置静态条目;`settings.xml` 的 `updateFields=true` 让 Word 打开即刷新页码 |
21
+ | 标准著录 | `kit.js` | 编制依据只列「《名称》(编号)」;参考文献为 GB/T 7714 全著录 |
22
+ | 排版校验 | `validateBlocks` / `assertBlocks` | 标题后必须有 ≥50 字说明段、文本块必须是字符串、公式必须有 latex |
23
+
24
+ ## 三、用法
25
+
26
+ ```js
27
+ import { coverBlock, tocBlock, chapter, validateBlocks, renderReport } from '@aiking/bridge-reportkit';
28
+
29
+ const blocks = [
30
+ coverBlock({ title: '桥梁技术状况评定报告', subtitle: '某桥', meta: [{ label: '工程名称', value: '某桥' }], org: '某单位', date: '2026-11-25' }),
31
+ tocBlock(),
32
+ chapter(1, '项目概况'),
33
+ { type: 'p', text: '这里是不少于 50 字的引题/机理说明……' },
34
+ { type: 'formula', latex: 'PCCI = \\overline{PMCI} - \\frac{100 - PMCI_{min}}{t}' },
35
+ { type: 'table', name: '各部件评分', rows: [['部件', '得分'], ['主拱圈', '33.75']], widths: [4000, 5026] },
36
+ ];
37
+
38
+ const issues = validateBlocks(blocks); // 先看有没有不合规
39
+ const buf = renderReport(blocks, { title: '评定报告', headerText: '某桥 评定报告' });
40
+ ```
41
+
42
+ 块类型一览:`cover` / `toc` / `h1` / `h2` / `h3` / `p` / `formula` / `table` / `page`。
43
+
44
+ ## 四、⚠ 模块解析限制与分发方式
45
+
46
+ **本插件环境里跨包 `import '@aiking/*'` 会 `ERR_MODULE_NOT_FOUND`**(已实测,见 `ARCHITECTURE.md` §2.1)。因此 `docx.js` 与 `latex2omml.js` 不能作为依赖被 import,只能复制到各插件的 `lib/core/` 下。
47
+
48
+ 为守住「只有一份源码」,采用:
49
+
50
+ ```
51
+ packages/aiking-bridge-reportkit/lib/ ← 唯一源码
52
+ │ scripts/sync-reportkit.ps1 同步
53
+ ├─→ dsh-bd-eval/lib/core/
54
+ └─→ packages/aiking-bridge-jtgh21/lib/core/
55
+ └─ .reportkit.json(版本戳:文件 sha256)
56
+ ```
57
+
58
+ **改代码的唯一正确姿势**:
59
+ 1. 改 `packages/aiking-bridge-reportkit/lib/*.js`
60
+ 2. 运行 `powershell -ExecutionPolicy Bypass -File scripts/sync-reportkit.ps1`
61
+ 3. 跑测试(两插件均含 `test/reportkit.test.mjs`,校验哈希戳)
62
+
63
+ 直接改插件里的副本会被漂移测试拦下。
64
+
65
+ > 本机 Windows PowerShell 5.1 会把无 BOM 的 UTF-8 脚本按 ANSI 解析导致中文乱码/语法错误 → `sync-reportkit.ps1` 必须以 **UTF-8 with BOM** 保存;脚本内块注释用 `<# #>`,不是 `/* */`。
66
+
67
+ ## 五、已知限制
68
+
69
+ 1. **目录页码**需在 Word 中更新域(文档已设 `updateFields`,打开即刷新;亦可按 F9)。LibreOffice 预览会显示 `—` 与域底纹,属预览差异,不影响打印。
70
+ 2. 公式为 OMML 子集转换,仅覆盖工程报告常用构造(上下标/分式/根式/求和/上划线/希腊字母/正负号等)。未知命令降级为文本并在返回值 `unknown` 中报告,不静默丢字符。
71
+ 3. 目录域只收录 h2/h3 两级(Word 大纲级别 1~2)。
72
+ 4. 暂无图片/图名能力(`caption` 块已备,尚未接图片)。
73
+
74
+ ## 六、测试
75
+
76
+ ```bash
77
+ cd packages/aiking-bridge-reportkit && node --test test/*.test.mjs
78
+ ```
package/lib/docx.js ADDED
@@ -0,0 +1,636 @@
1
+ /**
2
+ * 零依赖 DOCX 生成器 v2 —— 面向工程报告的正式排版。
3
+ * 相对 v1 的增强:
4
+ * - 样式表(styles.xml):docDefaults 设「楷体 + Times New Roman + 小四(12pt)」,
5
+ * 中文走 eastAsia 字体、数字/英文/符号走 ascii 字体,天然满足「数字英文用 Times New Roman」。
6
+ * - 彩色主题:主色深蓝、表头浅蓝底、边框淡蓝。
7
+ * - 标题层级:h1 黑体二号、h2 黑体四号(14pt)、h3 黑体小四加粗;正文楷体小四、首行缩进 2 字、1.5 倍行距。
8
+ * - 表格:表名加粗居中并自动编号「表 章-序」,表头加粗+浅蓝底+跨页重复,单元格内容水平垂直居中。
9
+ * - 公式:写成 LaTeX 源码,转成 **OMML 原生公式对象**(Word 里可双击编辑),
10
+ * 居中排版、右侧用右对齐制表位放「(章-序)」编号。
11
+ * - 页眉(分隔线 + 右对齐标题)、页脚(第 X 页 共 Y 页,PAGE/NUMPAGES 域)。
12
+ *
13
+ * 仍然零依赖:ZIP 用 store(不压缩)方式,报告体量小,最不易出错。
14
+ */
15
+
16
+ import { latexToOmml } from './latex2omml.js';
17
+
18
+ const CRC_TABLE = (() => {
19
+ const table = new Uint32Array(256);
20
+ for (let n = 0; n < 256; n += 1) {
21
+ let c = n;
22
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
23
+ table[n] = c >>> 0;
24
+ }
25
+ return table;
26
+ })();
27
+
28
+ function crc32(buf) {
29
+ let crc = 0xffffffff;
30
+ for (const byte of buf) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
31
+ return (crc ^ 0xffffffff) >>> 0;
32
+ }
33
+
34
+ /** 生成 store 方式(不压缩)的 zip。 */
35
+ export function buildZip(files) {
36
+ const locals = [];
37
+ const centrals = [];
38
+ let offset = 0;
39
+ for (const file of files) {
40
+ const name = Buffer.from(file.name, 'utf8');
41
+ const data = Buffer.isBuffer(file.data) ? file.data : Buffer.from(file.data, 'utf8');
42
+ const crc = crc32(data);
43
+
44
+ const local = Buffer.alloc(30);
45
+ local.writeUInt32LE(0x04034b50, 0);
46
+ local.writeUInt16LE(20, 4);
47
+ local.writeUInt16LE(0x0800, 6);
48
+ local.writeUInt16LE(0, 8);
49
+ local.writeUInt16LE(0, 10);
50
+ local.writeUInt16LE(0, 12);
51
+ local.writeUInt32LE(crc, 14);
52
+ local.writeUInt32LE(data.length, 18);
53
+ local.writeUInt32LE(data.length, 22);
54
+ local.writeUInt16LE(name.length, 26);
55
+ local.writeUInt16LE(0, 28);
56
+ locals.push(local, name, data);
57
+
58
+ // 中央目录字段偏移与本地头不同:crc=16、csize=20、usize=24(本地头是 14/18/22)
59
+ const central = Buffer.alloc(46);
60
+ central.writeUInt32LE(0x02014b50, 0);
61
+ central.writeUInt16LE(20, 4);
62
+ central.writeUInt16LE(20, 6);
63
+ central.writeUInt16LE(0x0800, 8);
64
+ central.writeUInt16LE(0, 10);
65
+ central.writeUInt16LE(0, 12);
66
+ central.writeUInt32LE(crc, 16);
67
+ central.writeUInt32LE(data.length, 20);
68
+ central.writeUInt32LE(data.length, 24);
69
+ central.writeUInt16LE(name.length, 28);
70
+ central.writeUInt32LE(offset, 42);
71
+ centrals.push(central, name);
72
+
73
+ offset += local.length + name.length + data.length;
74
+ }
75
+ const centralBuf = Buffer.concat(centrals);
76
+ const end = Buffer.alloc(22);
77
+ end.writeUInt32LE(0x06054b50, 0);
78
+ end.writeUInt16LE(files.length, 8);
79
+ end.writeUInt16LE(files.length, 10);
80
+ end.writeUInt32LE(centralBuf.length, 12);
81
+ end.writeUInt32LE(offset, 16);
82
+ return Buffer.concat([...locals, centralBuf, end]);
83
+ }
84
+
85
+ export function escapeXml(text) {
86
+ return String(text == null ? '' : text)
87
+ .replace(/&/g, '&amp;')
88
+ .replace(/</g, '&lt;')
89
+ .replace(/>/g, '&gt;')
90
+ .replace(/"/g, '&quot;')
91
+ .replace(/'/g, '&apos;');
92
+ }
93
+
94
+ // ---------------------------------------------------------------- 版式常量
95
+
96
+ /** A4 纵向:11906 × 16838 twips;左右边距 1440 → 正文宽 9026 */
97
+ const PAGE = { w: 11906, h: 16838, top: 1440, right: 1440, bottom: 1440, left: 1440, header: 851, footer: 992 };
98
+ const CONTENT_W = PAGE.w - PAGE.left - PAGE.right; // 9026
99
+ const TAB_CENTER = Math.round(CONTENT_W / 2); // 4513
100
+ const TAB_RIGHT = CONTENT_W; // 9026
101
+
102
+ /** 字号(半磅):二号44 三号32 四号28 小四24 五号21 小五18 */
103
+ const SZ = { er2: 44, san3: 32, si4: 28, xiao4: 24, wu5: 21, xiao5: 18 };
104
+
105
+ /** 彩色主题(可被 meta.theme 覆盖) */
106
+ const DEFAULT_THEME = {
107
+ primary: '1F4E79', // 深蓝:章标题
108
+ accent: '2E75B6', // 蓝:节标题
109
+ headerFill: 'DEEBF7', // 表头底色
110
+ border: 'B4C6E7', // 表格边框
111
+ rule: '8EAADB', // 页眉分隔线
112
+ };
113
+
114
+ const FONT = { kai: '楷体', hei: '黑体', tnr: 'Times New Roman' };
115
+
116
+ // ---------------------------------------------------------------- 片段构造
117
+
118
+ function rFonts(eastAsia, ascii = FONT.tnr) {
119
+ return `<w:rFonts w:ascii="${ascii}" w:hAnsi="${ascii}" w:eastAsia="${eastAsia}" w:cs="${ascii}"/>`;
120
+ }
121
+
122
+ /** 构造一个 run */
123
+ function run(text, opts = {}) {
124
+ const size = opts.size || SZ.xiao4;
125
+ const rPr = [
126
+ rFonts(opts.font || FONT.kai),
127
+ opts.bold ? '<w:b/><w:bCs/>' : '',
128
+ opts.italic ? '<w:i/>' : '',
129
+ `<w:color w:val="${opts.color || '000000'}"/>`,
130
+ `<w:sz w:val="${size}"/><w:szCs w:val="${size}"/>`,
131
+ ].join('');
132
+ return `<w:r><w:rPr>${rPr}</w:rPr><w:t xml:space="preserve">${escapeXml(text)}</w:t></w:r>`;
133
+ }
134
+
135
+ /** 段落 */
136
+ function para(runsXml, pPrExtra = '') {
137
+ return `<w:p><w:pPr>${pPrExtra}</w:pPr>${runsXml}</w:p>`;
138
+ }
139
+
140
+ /**
141
+ * 按 OOXML CT_PPr 的 schema 顺序拼装 pPr。
142
+ * ⚠ 顺序是强制的,乱序会让 LibreOffice / Word 直接拒绝打开文件。
143
+ * 顺序:keepNext → keepLines → pBdr → shd → tabs → spacing → ind → jc → outlineLvl
144
+ */
145
+ function pPr(o = {}) {
146
+ const parts = [];
147
+ if (o.keepNext) parts.push('<w:keepNext/>');
148
+ if (o.keepLines) parts.push('<w:keepLines/>');
149
+ if (o.pBdr) parts.push(o.pBdr);
150
+ if (o.shd) parts.push(o.shd);
151
+ if (o.tabs) parts.push(o.tabs);
152
+ if (o.spacing) parts.push(o.spacing);
153
+ if (o.ind) parts.push(o.ind);
154
+ if (o.jc) parts.push(o.jc);
155
+ if (o.outlineLvl !== undefined) parts.push(`<w:outlineLvl w:val="${o.outlineLvl}"/>`);
156
+ return parts.join('');
157
+ }
158
+
159
+ function jc(align) {
160
+ return `<w:jc w:val="${align}"/>`;
161
+ }
162
+
163
+ function spacing(before = 0, after = 0, line = 360) {
164
+ // line 360 = 1.5 倍行距(auto)
165
+ return `<w:spacing w:before="${before}" w:after="${after}" w:line="${line}" w:lineRule="auto"/>`;
166
+ }
167
+
168
+ function firstLineIndent(chars = 200, size = SZ.xiao4) {
169
+ const twips = Math.round((chars / 100) * size * 10);
170
+ return `<w:ind w:firstLineChars="${chars}" w:firstLine="${twips}"/>`;
171
+ }
172
+
173
+ // ---------------------------------------------------------------- 块渲染
174
+
175
+ function renderHeading(block, theme, level) {
176
+ const cfg = level === 1
177
+ ? { size: SZ.er2, color: theme.primary, align: 'center', before: 240, after: 360, outline: 0 }
178
+ : level === 2
179
+ ? { size: SZ.si4, color: theme.primary, align: 'left', before: 320, after: 160, outline: 0 }
180
+ : { size: SZ.xiao4, color: theme.accent, align: 'left', before: 200, after: 100, outline: 1 };
181
+ const pPrXml = pPr({
182
+ keepNext: true,
183
+ // 章标题不再加下边框(按评审人要求去掉标题下方横线)
184
+ spacing: spacing(cfg.before, cfg.after, cfg.size === SZ.er2 ? 400 : 340),
185
+ jc: jc(cfg.align),
186
+ outlineLvl: cfg.outline,
187
+ });
188
+ const rPr = [
189
+ rFonts(FONT.hei),
190
+ '<w:b/><w:bCs/>',
191
+ `<w:color w:val="${cfg.color}"/>`,
192
+ `<w:sz w:val="${cfg.size}"/><w:szCs w:val="${cfg.size}"/>`,
193
+ ].join('');
194
+ const text = escapeXml(block.text);
195
+ return `<w:p><w:pPr>${pPrXml}</w:pPr><w:r><w:rPr>${rPr}</w:rPr><w:t xml:space="preserve">${text}</w:t></w:r></w:p>`;
196
+ }
197
+
198
+ function renderPara(block) {
199
+ const pPrXml = pPr({
200
+ spacing: spacing(block.before || 0, block.after || 60, block.line || 360),
201
+ ind: block.indent === false ? '' : firstLineIndent(200, block.size || SZ.xiao4),
202
+ jc: jc(block.align || 'both'),
203
+ });
204
+ const text = block.text || '';
205
+ // 支持 **加粗** 行内标记
206
+ const parts = String(text).split(/(\*\*[^*]+\*\*)/g).filter((s) => s !== '');
207
+ const runs = parts.map((seg) => {
208
+ if (seg.startsWith('**') && seg.endsWith('**')) {
209
+ return run(seg.slice(2, -2), { bold: true, size: block.size, font: block.font, color: block.color });
210
+ }
211
+ return run(seg, { bold: block.bold, size: block.size, font: block.font, color: block.color });
212
+ }).join('') || run('', {});
213
+ return para(runs, pPrXml);
214
+ }
215
+
216
+ // ---------------------------------------------------------------- 封面与目录
217
+
218
+ /**
219
+ * 封面:大标题 + 副标题 + 分隔线 + 信息条目 + 编制单位与日期,末页分页。
220
+ * block = { title, subtitle, meta: [{label, value}], org, date }
221
+ */
222
+ function renderCover(block, theme) {
223
+ const out = [];
224
+ // 顶部留白
225
+ out.push(para(run(''), `${pPr({ spacing: spacing(0, 0, 240) })}`));
226
+ out.push(para(run(''), `${pPr({ spacing: spacing(0, 0, 240) })}`));
227
+
228
+ // 主标题
229
+ out.push(para(
230
+ run(block.title || '', { font: FONT.hei, bold: true, size: SZ.er2, color: theme.primary }),
231
+ pPr({ spacing: spacing(600, 240, 400), ind: '<w:ind w:firstLine="0"/>', jc: jc('center') }),
232
+ ));
233
+ // 副标题
234
+ if (block.subtitle) {
235
+ out.push(para(
236
+ run(block.subtitle, { font: FONT.hei, size: SZ.si4, color: theme.accent }),
237
+ pPr({ spacing: spacing(0, 240, 320), ind: '<w:ind w:firstLine="0"/>', jc: jc('center') }),
238
+ ));
239
+ }
240
+ // 分隔线
241
+ out.push(para(
242
+ run(''),
243
+ pPr({
244
+ pBdr: `<w:pBdr><w:bottom w:val="single" w:sz="12" w:space="1" w:color="${theme.accent}"/></w:pBdr>`,
245
+ spacing: spacing(0, 480, 240),
246
+ ind: '<w:ind w:firstLine="0"/>',
247
+ }),
248
+ ));
249
+
250
+ // 信息条目
251
+ for (const item of block.meta || []) {
252
+ out.push(para(
253
+ run(`${item.label}:${item.value}`, { font: FONT.kai, size: SZ.xiao4 }),
254
+ pPr({ spacing: spacing(0, 120, 360), ind: '<w:ind w:firstLine="0"/>', jc: jc('center') }),
255
+ ));
256
+ }
257
+
258
+ // 底部:编制单位与日期
259
+ if (block.org) {
260
+ out.push(para(run(''), `${pPr({ spacing: spacing(0, 0, 240) })}`));
261
+ out.push(para(run(''), `${pPr({ spacing: spacing(0, 0, 240) })}`));
262
+ out.push(para(
263
+ run(block.org, { font: FONT.hei, size: SZ.xiao4, color: theme.primary }),
264
+ pPr({ spacing: spacing(0, 120, 320), ind: '<w:ind w:firstLine="0"/>', jc: jc('center') }),
265
+ ));
266
+ }
267
+ if (block.date) {
268
+ out.push(para(
269
+ run(block.date, { font: FONT.tnr, size: SZ.xiao4 }),
270
+ pPr({ spacing: spacing(0, 0, 320), ind: '<w:ind w:firstLine="0"/>', jc: jc('center') }),
271
+ ));
272
+ }
273
+ out.push(`<w:p><w:r><w:br w:type="page"/></w:r></w:p>`);
274
+ return out.join('');
275
+ }
276
+
277
+ /**
278
+ * 目录:Word 原生 TOC 域(\o "1-2")。
279
+ * 域结果里预置静态条目,未更新域时也能看到章节目录;Word 打开后按 F9 / 自动更新即得页码。
280
+ */
281
+ function renderToc(block, outline, theme) {
282
+ const items = outline.filter((o) => o.level <= 2);
283
+ if (!items.length) return '';
284
+
285
+ const staticRuns = items.map((it) => {
286
+ const indentTwips = (it.level - 1) * 480;
287
+ const p = `<w:p><w:pPr>${pPr({
288
+ tabs: `<w:tabs><w:tab w:val="right" w:leader="dot" w:pos="${TAB_RIGHT}"/></w:tabs>`,
289
+ spacing: spacing(0, 80, 320),
290
+ ind: `<w:ind w:left="${indentTwips}" w:firstLine="0"/>`,
291
+ })}</w:pPr>`
292
+ + run(it.text, { font: FONT.kai, size: SZ.xiao4, bold: it.level === 1 })
293
+ + '<w:r><w:tab/></w:r>'
294
+ + run('—', { font: FONT.tnr, size: SZ.xiao4 })
295
+ + '</w:p>';
296
+ return p;
297
+ }).join('');
298
+
299
+ const head = para(
300
+ run(block.title || '目  录', { font: FONT.hei, bold: true, size: SZ.san3, color: theme.primary }),
301
+ pPr({ spacing: spacing(240, 320, 360), ind: '<w:ind w:firstLine="0"/>', jc: jc('center'), outlineLvl: undefined }),
302
+ );
303
+
304
+ const fieldStart = '<w:r><w:fldChar w:fldCharType="begin" w:dirty="true"/></w:r>'
305
+ + '<w:r><w:instrText xml:space="preserve"> TOC \\o "1-2" \\h \\z \\u </w:instrText></w:r>'
306
+ + '<w:r><w:fldChar w:fldCharType="separate"/></w:r>';
307
+ const fieldEnd = '<w:r><w:fldChar w:fldCharType="end"/></w:r>';
308
+
309
+ // 把静态条目包进域结果:域代码放在第一条之前
310
+ const tocBody = staticRuns.replace(/^<w:p>/, `<w:p>${fieldStart}`).replace(/<\/w:p>$/, `${fieldEnd}</w:p>`);
311
+
312
+ const tip = para(
313
+ run('(本目录为域结果,在 Word 中按 F9 或右键“更新域”可刷新页码)', { font: FONT.kai, size: SZ.xiao5, color: '808080' }),
314
+ pPr({ spacing: spacing(160, 0, 280), ind: '<w:ind w:firstLine="0"/>', jc: jc('center') }),
315
+ );
316
+
317
+ return head + tocBody + tip + `<w:p><w:r><w:br w:type="page"/></w:r></w:p>`;
318
+ }
319
+
320
+ /** 表名 / 图名:加粗居中 */function renderCaption(block) {
321
+ const pPrXml = pPr({
322
+ keepNext: true,
323
+ spacing: spacing(140, 60, 300),
324
+ ind: '<w:ind w:firstLine="0"/>',
325
+ jc: jc('center'),
326
+ });
327
+ const rPr = [
328
+ rFonts(block.font || FONT.hei),
329
+ '<w:b/><w:bCs/>',
330
+ `<w:sz w:val="${block.size || SZ.wu5}"/><w:szCs w:val="${block.size || SZ.wu5}"/>`,
331
+ ].join('');
332
+ return `<w:p><w:pPr>${pPrXml}</w:pPr><w:r><w:rPr>${rPr}</w:rPr><w:t xml:space="preserve">${escapeXml(block.text)}</w:t></w:r></w:p>`;
333
+ }
334
+
335
+ /** 公式:LaTeX → OMML 原生公式,居中;右侧编号 */
336
+ function renderFormula(block) {
337
+ const pPrXml = pPr({
338
+ tabs: `<w:tabs><w:tab w:val="center" w:pos="${TAB_CENTER}"/><w:tab w:val="right" w:pos="${TAB_RIGHT}"/></w:tabs>`,
339
+ spacing: spacing(80, 80, 320),
340
+ ind: '<w:ind w:firstLine="0"/>',
341
+ });
342
+
343
+ // 有 latex 就走 OMML(Word 原生可编辑公式);否则退回纯文本,保持向后兼容
344
+ let mathXml;
345
+ if (block.latex) {
346
+ const { omml } = latexToOmml(block.latex);
347
+ mathXml = omml;
348
+ } else {
349
+ mathXml = run(block.text || '', { font: FONT.tnr, size: block.size || SZ.xiao4 });
350
+ }
351
+
352
+ const body = [
353
+ '<w:r><w:tab/></w:r>',
354
+ mathXml,
355
+ '<w:r><w:tab/></w:r>',
356
+ run(block.number || '', { font: FONT.tnr, size: block.size || SZ.xiao4 }),
357
+ ].join('');
358
+ return `<w:p><w:pPr>${pPrXml}</w:pPr>${body}</w:p>`;
359
+ }
360
+
361
+ /** 表格:可带表名,表头加粗+底色,单元格居中 */
362
+ function renderTable(block, theme) {
363
+ const rows = (block.rows || []).filter((r) => Array.isArray(r));
364
+ if (!rows.length) return '';
365
+ const cols = Math.max(...rows.map((r) => r.length));
366
+ const widths = Array.isArray(block.widths) && block.widths.length === cols
367
+ ? block.widths
368
+ : new Array(cols).fill(Math.floor(CONTENT_W / cols));
369
+ const sum = widths.reduce((a, b) => a + b, 0);
370
+ const scaled = sum === CONTENT_W ? widths : widths.map((w) => Math.round((w / sum) * CONTENT_W));
371
+
372
+ const out = [];
373
+ if (block.caption) out.push(renderCaption({ text: block.caption }));
374
+
375
+ const border = (side) => `<w:${side} w:val="single" w:sz="4" w:space="0" w:color="${theme.border}"/>`;
376
+ out.push('<w:tbl><w:tblPr>'
377
+ + `<w:tblW w:w="${CONTENT_W}" w:type="dxa"/>`
378
+ + jc('center')
379
+ + `<w:tblBorders>${['top', 'left', 'bottom', 'right', 'insideH', 'insideV'].map(border).join('')}</w:tblBorders>`
380
+ + '<w:tblLayout w:type="fixed"/>'
381
+ + '<w:tblCellMar><w:top w:w="40" w:type="dxa"/><w:left w:w="80" w:type="dxa"/><w:bottom w:w="40" w:type="dxa"/><w:right w:w="80" w:type="dxa"/></w:tblCellMar>'
382
+ + '</w:tblPr>');
383
+ out.push(`<w:tblGrid>${scaled.map((w) => `<w:gridCol w:w="${w}"/>`).join('')}</w:tblGrid>`);
384
+
385
+ rows.forEach((row, ri) => {
386
+ const isHeader = block.header !== false && ri === 0;
387
+ out.push('<w:tr>' + (isHeader ? '<w:trPr><w:tblHeader/></w:trPr>' : ''));
388
+ for (let ci = 0; ci < cols; ci += 1) {
389
+ const cellText = row[ci] === undefined || row[ci] === null ? '' : String(row[ci]);
390
+ const cellPr = '<w:tcPr>'
391
+ + `<w:tcW w:w="${scaled[ci]}" w:type="dxa"/>`
392
+ + (isHeader ? `<w:shd w:val="clear" w:color="auto" w:fill="${theme.headerFill}"/>` : '')
393
+ + '<w:vAlign w:val="center"/>'
394
+ + '</w:tcPr>';
395
+ const cellPPr = pPr({
396
+ spacing: spacing(20, 20, 280),
397
+ ind: '<w:ind w:firstLine="0"/>',
398
+ jc: jc('center'),
399
+ });
400
+ // 单元格内支持 **加粗** 行内标记
401
+ const segs = cellText.split(/(\*\*[^*]+\*\*)/g).filter((s) => s !== '');
402
+ const runs = segs.map((seg) => {
403
+ const isBold = seg.startsWith('**') && seg.endsWith('**');
404
+ const txt = isBold ? seg.slice(2, -2) : seg;
405
+ return run(txt, { font: FONT.kai, size: block.cellSize || SZ.wu5, bold: isHeader || isBold });
406
+ }).join('') || run('', { size: SZ.wu5 });
407
+ out.push(`<w:tc>${cellPr}${para(runs, cellPPr)}</w:tc>`);
408
+ }
409
+ out.push('</w:tr>');
410
+ });
411
+ out.push('</w:tbl>');
412
+ // 表后留一点空隙,避免与后续段落贴死
413
+ out.push(para(run('', {}), spacing(0, 120, 240)));
414
+ return out.join('');
415
+ }
416
+
417
+ // ---------------------------------------------------------------- 页眉页脚
418
+
419
+ function renderHeader(meta, theme) {
420
+ const text = meta.headerText || meta.title || '';
421
+ const pPrXml = pPr({
422
+ pBdr: `<w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="${theme.rule}"/></w:pBdr>`,
423
+ spacing: spacing(0, 0, 240),
424
+ jc: jc('right'),
425
+ });
426
+ const rPr = [rFonts(FONT.hei), `<w:color w:val="${theme.primary}"/>`, `<w:sz w:val="${SZ.xiao5}"/><w:szCs w:val="${SZ.xiao5}"/>`].join('');
427
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
428
+ + '<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
429
+ + `<w:p><w:pPr>${pPrXml}</w:pPr><w:r><w:rPr>${rPr}</w:rPr><w:t xml:space="preserve">${escapeXml(text)}</w:t></w:r></w:p>`
430
+ + '</w:hdr>';
431
+ }
432
+
433
+ function fieldRun(instr, placeholder, opts) {
434
+ const rPr = [rFonts(FONT.tnr), `<w:sz w:val="${opts.size}"/><w:szCs w:val="${opts.size}"/>`].join('');
435
+ return '<w:r><w:fldChar w:fldCharType="begin"/></w:r>'
436
+ + `<w:r><w:instrText xml:space="preserve"> ${instr} </w:instrText></w:r>`
437
+ + '<w:r><w:fldChar w:fldCharType="separate"/></w:r>'
438
+ + `<w:r><w:rPr>${rPr}</w:rPr><w:t>${placeholder}</w:t></w:r>`
439
+ + '<w:r><w:fldChar w:fldCharType="end"/></w:r>';
440
+ }
441
+
442
+ function renderFooter() {
443
+ const opts = { size: SZ.xiao5 };
444
+ const pPrXml = pPr({ spacing: spacing(0, 0, 240), jc: jc('center') });
445
+ const body = [
446
+ run('第 ', { font: FONT.hei, size: SZ.xiao5 }),
447
+ fieldRun('PAGE', '1', opts),
448
+ run(' 页 共 ', { font: FONT.hei, size: SZ.xiao5 }),
449
+ fieldRun('NUMPAGES', '1', opts),
450
+ run(' 页', { font: FONT.hei, size: SZ.xiao5 }),
451
+ ].join('');
452
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
453
+ + '<w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
454
+ + `<w:p><w:pPr>${pPrXml}</w:pPr>${body}</w:p>`
455
+ + '</w:ftr>';
456
+ }
457
+
458
+ // ---------------------------------------------------------------- 样式表
459
+
460
+ function renderStyles() {
461
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
462
+ + '<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
463
+ + '<w:docDefaults><w:rPrDefault><w:rPr>'
464
+ + `<w:rFonts w:ascii="${FONT.tnr}" w:hAnsi="${FONT.tnr}" w:eastAsia="${FONT.kai}" w:cs="${FONT.tnr}"/>`
465
+ + `<w:sz w:val="${SZ.xiao4}"/><w:szCs w:val="${SZ.xiao4}"/>`
466
+ + '</w:rPr></w:rPrDefault>'
467
+ + '<w:pPrDefault><w:pPr>'
468
+ + `${spacing(0, 0, 360)}<w:jc w:val="both"/>`
469
+ + '</w:pPr></w:pPrDefault></w:docDefaults>'
470
+ + '<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>'
471
+ + '</w:styles>';
472
+ }
473
+
474
+ function renderSettings() {
475
+ // updateFields=true:Word 打开文档时自动刷新 TOC 域,得到真实页码
476
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
477
+ + '<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
478
+ + '<w:updateFields w:val="true"/>'
479
+ + '<w:defaultTabStop w:val="420"/>'
480
+ + '<w:characterSpacingControl w:val="compressPunctuation"/>'
481
+ + '</w:settings>';
482
+ }
483
+
484
+ // ---------------------------------------------------------------- 主入口
485
+
486
+ /**
487
+ * 生成 docx。
488
+ * @param {Array} blocks 块数组
489
+ * @param {object} meta { title, author, headerText, theme }
490
+ * @returns {Buffer}
491
+ */
492
+ export function buildDocx(blocks, meta = {}) {
493
+ const theme = { ...DEFAULT_THEME, ...(meta.theme || {}) };
494
+
495
+ // 编号:章号来自 h2 文本开头的数字;表/公式在章内顺序编号
496
+ let chapter = 0;
497
+ let tableNo = 0;
498
+ let formulaNo = 0;
499
+ const bodyXml = [];
500
+
501
+ // 先扫一遍标题,供目录使用(目录块出现在正文之前,必须预扫描)
502
+ const outline = [];
503
+ for (const b of blocks || []) {
504
+ if (!b) continue;
505
+ if (b.type === 'h1') outline.push({ level: 1, text: String(b.text || '') });
506
+ else if (b.type === 'h2') outline.push({ level: 1, text: String(b.text || '') });
507
+ else if (b.type === 'h3') outline.push({ level: 2, text: String(b.text || '') });
508
+ }
509
+
510
+ for (const block of blocks || []) {
511
+ if (!block || !block.type) continue;
512
+ switch (block.type) {
513
+ case 'h1':
514
+ bodyXml.push(renderHeading(block, theme, 1));
515
+ break;
516
+ case 'cover':
517
+ bodyXml.push(renderCover(block, theme));
518
+ break;
519
+ case 'toc':
520
+ bodyXml.push(renderToc(block, outline, theme));
521
+ break;
522
+ case 'h2': {
523
+ const m = /^\s*(\d+)/.exec(String(block.text || ''));
524
+ chapter = m ? Number(m[1]) : chapter + 1;
525
+ tableNo = 0;
526
+ formulaNo = 0;
527
+ bodyXml.push(renderHeading(block, theme, 2));
528
+ break;
529
+ }
530
+ case 'h3':
531
+ bodyXml.push(renderHeading(block, theme, 3));
532
+ break;
533
+ case 'p':
534
+ bodyXml.push(renderPara(block));
535
+ break;
536
+ case 'caption':
537
+ bodyXml.push(renderCaption(block, theme));
538
+ break;
539
+ case 'formula': {
540
+ formulaNo += 1;
541
+ const number = block.number || `(${chapter}-${formulaNo})`;
542
+ bodyXml.push(renderFormula({ ...block, number }));
543
+ break;
544
+ }
545
+ case 'table': {
546
+ tableNo += 1;
547
+ const caption = block.caption === false
548
+ ? null
549
+ : (block.caption || `表 ${chapter}-${tableNo}${block.name ? ` ${block.name}` : ''}`);
550
+ bodyXml.push(renderTable({ ...block, caption }, theme));
551
+ break;
552
+ }
553
+ case 'page':
554
+ bodyXml.push(`<w:p><w:r><w:br w:type="page"/></w:r></w:p>`);
555
+ break;
556
+ default:
557
+ break;
558
+ }
559
+ }
560
+
561
+ const documentXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
562
+ + '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" '
563
+ + 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" '
564
+ + 'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math">'
565
+ + '<w:body>'
566
+ + bodyXml.join('')
567
+ + '<w:sectPr>'
568
+ + '<w:headerReference w:type="default" r:id="rId2"/>'
569
+ + '<w:footerReference w:type="default" r:id="rId3"/>'
570
+ + '<w:titlePg/>'
571
+ + `<w:pgSz w:w="${PAGE.w}" w:h="${PAGE.h}"/>`
572
+ + `<w:pgMar w:top="${PAGE.top}" w:right="${PAGE.right}" w:bottom="${PAGE.bottom}" w:left="${PAGE.left}" w:header="${PAGE.header}" w:footer="${PAGE.footer}" w:gutter="0"/>`
573
+ + '<w:docGrid w:linePitch="312"/>'
574
+ + '</w:sectPr>'
575
+ + '</w:body></w:document>';
576
+
577
+ const contentTypes = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
578
+ + '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
579
+ + '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
580
+ + '<Default Extension="xml" ContentType="application/xml"/>'
581
+ + '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>'
582
+ + '<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>'
583
+ + '<Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/>'
584
+ + '<Override PartName="/word/header1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"/>'
585
+ + '<Override PartName="/word/footer1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"/>'
586
+ + '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>'
587
+ + '<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>'
588
+ + '</Types>';
589
+
590
+ const rootRels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
591
+ + '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
592
+ + '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>'
593
+ + '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>'
594
+ + '<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>'
595
+ + '</Relationships>';
596
+
597
+ const docRels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
598
+ + '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
599
+ + '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'
600
+ + '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>'
601
+ + '<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>'
602
+ + '<Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/>'
603
+ + '</Relationships>';
604
+
605
+ const now = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
606
+ const coreXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
607
+ + '<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" '
608
+ + 'xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" '
609
+ + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
610
+ + `<dc:title>${escapeXml(meta.title || '')}</dc:title>`
611
+ + `<dc:creator>${escapeXml(meta.author || '')}</dc:creator>`
612
+ + `<cp:lastModifiedBy>${escapeXml(meta.author || '')}</cp:lastModifiedBy>`
613
+ + `<dcterms:created xsi:type="dcterms:W3CDTF">${now}</dcterms:created>`
614
+ + `<dcterms:modified xsi:type="dcterms:W3CDTF">${now}</dcterms:modified>`
615
+ + '</cp:coreProperties>';
616
+
617
+ const appXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
618
+ + '<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">'
619
+ + '<Application>DSH Bridge Suite</Application>'
620
+ + '</Properties>';
621
+
622
+ return buildZip([
623
+ { name: '[Content_Types].xml', data: contentTypes },
624
+ { name: '_rels/.rels', data: rootRels },
625
+ { name: 'docProps/core.xml', data: coreXml },
626
+ { name: 'docProps/app.xml', data: appXml },
627
+ { name: 'word/document.xml', data: documentXml },
628
+ { name: 'word/styles.xml', data: renderStyles() },
629
+ { name: 'word/settings.xml', data: renderSettings() },
630
+ { name: 'word/header1.xml', data: renderHeader(meta, theme) },
631
+ { name: 'word/footer1.xml', data: renderFooter() },
632
+ { name: 'word/_rels/document.xml.rels', data: docRels },
633
+ ]);
634
+ }
635
+
636
+ export { PAGE, CONTENT_W, SZ, FONT, DEFAULT_THEME };
package/lib/kit.js ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * @aiking/bridge-reportkit —— 工程报告排版基础设施
3
+ *
4
+ * 把「一份能直接交出去的工程报告」所需的排版能力收敛为可复用组件:
5
+ * 1. DOCX 引擎(docx.js):字体、配色、页眉页脚、表名、公式、封面、目录
6
+ * 2. LaTeX → OMML 转换(latex2omml.js):Word 原生可编辑公式
7
+ * 3. 本文件(kit.js):标准著录、封面/目录块、章节构造、**排版规则校验**
8
+ *
9
+ * ⚠ 模块解析限制:本插件环境里跨包 `import '@aiking/*'` 会 ERR_MODULE_NOT_FOUND,
10
+ * 因此 docx.js / latex2omml.js 采用「单一源码 + 同步到各插件 lib/core」的方式分发,
11
+ * 由 scripts/sync-reportkit.ps1 同步并写入 .reportkit.json 版本戳;
12
+ * 各插件的测试会校验版本戳与文件哈希,防止手工改动造成漂移。
13
+ *
14
+ * @module @aiking/bridge-reportkit
15
+ */
16
+
17
+ export {
18
+ buildDocx, buildZip, escapeXml, PAGE, CONTENT_W, SZ, FONT, DEFAULT_THEME,
19
+ } from './docx.js';
20
+ export { latexToOmml } from './latex2omml.js';
21
+
22
+ import { buildDocx } from './docx.js';
23
+
24
+ /** 报告默认引用的标准(name/code 用于编制依据,full 用于参考文献) */
25
+ export const DEFAULT_STANDARDS = [
26
+ { name: '公路桥梁技术状况评定标准', code: 'JTG/T H21—2011', year: 2011 },
27
+ { name: '公路桥涵养护规范', code: 'JTG 5120—2021', year: 2021 },
28
+ { name: '公路桥梁耐久性检测评定规程', code: 'JTG/T 5231—2026', year: 2026 },
29
+ { name: '公路工程混凝土结构耐久性设计规范', code: 'JTG/T 3310—2019', year: 2019 },
30
+ ];
31
+
32
+ /** GB/T 7714 期刊/标准著录 */
33
+ export function fullCitation(s, idx) {
34
+ const year = s.year ? `,${s.year}` : '';
35
+ return `[${idx}] 中华人民共和国交通运输部. ${s.name}:${s.code}[S]. 北京:人民交通出版社${year}.`;
36
+ }
37
+
38
+ /**
39
+ * 把用户传入的引用项规整为 {name, code, year, full}。
40
+ * 支持三种写法:对象(含 name/code/year)、"《名称》(编号)"、完整著录字符串。
41
+ */
42
+ export function toStandard(item, idx = 1) {
43
+ if (item && typeof item === 'object') {
44
+ const name = String(item.name || '').trim();
45
+ const code = String(item.code || '').trim();
46
+ return { name, code, year: item.year, full: item.full || fullCitation({ name, code, year: item.year }, idx) };
47
+ }
48
+ const text = String(item || '').trim();
49
+ const paren = /《([^》]+)》\s*[((]\s*([^))]+)\s*[))]/.exec(text);
50
+ if (paren) return { name: paren[1].trim(), code: paren[2].trim(), year: undefined, full: fullCitation({ name: paren[1].trim(), code: paren[2].trim() }, idx) };
51
+ const codeMatch = /([A-Z][A-Z0-9/\s.]*?\s*[—\-–]\s*\d{4})/.exec(text);
52
+ const code = codeMatch ? codeMatch[1].trim() : '';
53
+ const nameMatch = /[.。]\s*([^::.。\[\]]+?)[::]\s*[A-Z]/.exec(text);
54
+ const name = nameMatch ? nameMatch[1].trim() : text;
55
+ return { name, code, year: undefined, full: code ? fullCitation({ name, code }, idx) : text };
56
+ }
57
+
58
+ /** 编制依据内容块:只列名称与编号 */
59
+ export function basisBlocks(standards) {
60
+ return standards.map((s, i) => ({
61
+ type: 'p',
62
+ indent: false,
63
+ size: 21,
64
+ text: `(${i + 1})《${s.name}》(${s.code})`,
65
+ }));
66
+ }
67
+
68
+ /** 参考文献内容块:完整著录 */
69
+ export function referenceBlocks(standards) {
70
+ return standards.map((s) => ({ type: 'p', indent: false, size: 21, text: s.full }));
71
+ }
72
+
73
+ /** 封面块 */
74
+ export function coverBlock({ title, subtitle, meta = [], org, date } = {}) {
75
+ return { type: 'cover', title, subtitle, meta, org, date };
76
+ }
77
+
78
+ /** 目录块 */
79
+ export function tocBlock(title = '目  录') {
80
+ return { type: 'toc', title };
81
+ }
82
+
83
+ /** 章标题(自动编号前缀由调用方给定) */
84
+ export function chapter(no, title) {
85
+ return { type: 'h2', text: `${no} ${title}` };
86
+ }
87
+
88
+ /** 节标题 */
89
+ export function section(chNo, no, title) {
90
+ return { type: 'h3', text: `${chNo}.${no} ${title}` };
91
+ }
92
+
93
+ /**
94
+ * 排版规则校验:在写文件前把「不合规的块序列」找出来。
95
+ * 规则(来自评审人意见,已固化):
96
+ * 1. 每个标题后必须是 ≥ minChars 字的说明段落,不得直接接表格或公式;
97
+ * 2. 正文文本块必须是字符串(防把对象当文本渲染成 [object Object]);
98
+ * 3. 封面必须是第一块,目录必须紧随其后;
99
+ * 4. 公式必须给 latex(走 OMML),不得只给 text。
100
+ * @returns {{level:'error'|'warn', message:string}[]}
101
+ */
102
+ export function validateBlocks(blocks = [], opts = {}) {
103
+ const minChars = opts.minChars ?? 50;
104
+ const issues = [];
105
+ const list = Array.isArray(blocks) ? blocks : [];
106
+
107
+ if (!list.length) {
108
+ issues.push({ level: 'error', message: '报告没有任何内容块' });
109
+ return issues;
110
+ }
111
+ if (list[0].type !== 'cover') issues.push({ level: 'error', message: '第一个块必须是封面(type=cover)' });
112
+ if (list[1] && list[1].type !== 'toc') issues.push({ level: 'warn', message: '目录(type=toc)应紧跟封面' });
113
+
114
+ list.forEach((b, i) => {
115
+ if (b.type === 'p' && typeof b.text !== 'string') {
116
+ issues.push({ level: 'error', message: `第 ${i + 1} 块正文不是字符串(会渲染成 [object Object])` });
117
+ }
118
+ if ((b.type === 'h2' || b.type === 'h3')) {
119
+ const nxt = list[i + 1];
120
+ if (!nxt || nxt.type === 'table' || nxt.type === 'formula') {
121
+ issues.push({ level: 'error', message: `标题「${b.text}」后直接接表格/公式,缺少说明段落` });
122
+ } else if (nxt.type === 'p' && String(nxt.text || '').length < minChars) {
123
+ issues.push({ level: 'warn', message: `标题「${b.text}」后首段仅 ${String(nxt.text || '').length} 字(建议 ≥${minChars})` });
124
+ }
125
+ }
126
+ if (b.type === 'formula' && !b.latex) {
127
+ issues.push({ level: 'error', message: `第 ${i + 1} 块公式缺少 latex 源码(无法转成 Word 原生公式)` });
128
+ }
129
+ if (b.type === 'table') {
130
+ const cols = Math.max(...(b.rows || []).map((r) => r.length), 0);
131
+ if (b.widths && b.widths.length !== cols) {
132
+ issues.push({ level: 'warn', message: `表格列数(${cols})与宽度数组长度(${b.widths.length})不一致` });
133
+ }
134
+ }
135
+ });
136
+ return issues;
137
+ }
138
+
139
+ /** 严格模式:有 error 直接抛错,供工具在写文件前拦截 */
140
+ export function assertBlocks(blocks, opts) {
141
+ const issues = validateBlocks(blocks, opts);
142
+ const errors = issues.filter((x) => x.level === 'error');
143
+ if (errors.length) {
144
+ throw new Error(`报告排版校验未通过:\n${errors.map((e) => ` - ${e.message}`).join('\n')}`);
145
+ }
146
+ return issues;
147
+ }
148
+
149
+ /** 一次性生成 docx Buffer(含校验) */
150
+ export function renderReport(blocks, meta = {}, opts = {}) {
151
+ if (opts.validate !== false) assertBlocks(blocks, opts);
152
+ return buildDocx(blocks, meta);
153
+ }
@@ -0,0 +1,296 @@
1
+ /**
2
+ * LaTeX → OMML(Office Math Markup Language)转换器。
3
+ *
4
+ * 只覆盖工程报告常用子集,目标是把公式变成 **Word 原生可编辑公式对象**,
5
+ * 而不是贴图或纯文本。支持的构造:
6
+ * - 上下标 x_i、x^2、x_i^2
7
+ * - 分式 \frac{a}{b}
8
+ * - 根式 \sqrt{x}、\sqrt[n]{x}
9
+ * - 求和 \sum_{i=1}^{n}(n 元运算符)
10
+ * - 上划线 \overline{X}、\bar{X}
11
+ * - 括号 \left( \right)、\{ \}
12
+ * - 希腊字母、常用运算符、\text{} 正体文字、\, \; \quad 间距
13
+ *
14
+ * 遇到不认识的命令时**降级为字面文本**并在返回值里报告,不静默丢字符。
15
+ */
16
+
17
+ const GREEK = {
18
+ alpha: 'α', beta: 'β', gamma: 'γ', delta: 'δ', epsilon: 'ε', varepsilon: 'ε',
19
+ zeta: 'ζ', eta: 'η', theta: 'θ', iota: 'ι', kappa: 'κ', lambda: 'λ', mu: 'μ',
20
+ nu: 'ν', xi: 'ξ', pi: 'π', rho: 'ρ', sigma: 'σ', tau: 'τ', upsilon: 'υ',
21
+ phi: 'φ', varphi: 'φ', chi: 'χ', psi: 'ψ', omega: 'ω',
22
+ Gamma: 'Γ', Delta: 'Δ', Theta: 'Θ', Lambda: 'Λ', Xi: 'Ξ', Pi: 'Π',
23
+ Sigma: 'Σ', Upsilon: 'Υ', Phi: 'Φ', Psi: 'Ψ', Omega: 'Ω',
24
+ };
25
+
26
+ const SYMBOL = {
27
+ cdot: '⋅', times: '×', div: '÷', pm: '±', mp: '∓',
28
+ le: '≤', leq: '≤', ge: '≥', geq: '≥', ne: '≠', neq: '≠', approx: '≈', equiv: '≡',
29
+ lt: '<', gt: '>', infty: '∞', partial: '∂', nabla: '∇', prime: '′',
30
+ ldots: '…', cdots: '⋯', to: '→', rightarrow: '→', leftarrow: '←',
31
+ sum: '∑', prod: '∏', int: '∫',
32
+ '%': '%', '&': '&', '#': '#', '_': '_', '{': '{', '}': '}',
33
+ };
34
+
35
+ /** 间距命令 → 对应数量的窄空格(Word 里用空格近似) */
36
+ const SPACE = { ',': '\u2009', ':': '\u2005', ';': '\u2004', '!': '', ' ': ' ', quad: '\u2003', qquad: '\u2003\u2003' };
37
+
38
+ function esc(s) {
39
+ return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
40
+ }
41
+
42
+ function rPr({ italic = true, size } = {}) {
43
+ const sz = size || 24;
44
+ return '<w:rPr>'
45
+ + '<w:rFonts w:ascii="Cambria Math" w:hAnsi="Cambria Math" w:eastAsia="楷体"/>'
46
+ + (italic ? '' : '<w:i w:val="0"/>')
47
+ + `<w:sz w:val="${sz}"/><w:szCs w:val="${sz}"/>`
48
+ + '</w:rPr>';
49
+ }
50
+
51
+ /** 数学 run */
52
+ function mr(text, opts = {}) {
53
+ return `<m:r>${rPr(opts)}<m:t xml:space="preserve">${esc(text)}</m:t></m:r>`;
54
+ }
55
+
56
+ function tokenize(src) {
57
+ const toks = [];
58
+ let i = 0;
59
+ while (i < src.length) {
60
+ const c = src[i];
61
+ if (c === '\\') {
62
+ const next = src[i + 1];
63
+ if (next === undefined) { i += 1; continue; }
64
+ if (!/[a-zA-Z]/.test(next)) {
65
+ toks.push({ t: 'cmd', v: next });
66
+ i += 2;
67
+ continue;
68
+ }
69
+ let j = i + 1;
70
+ while (j < src.length && /[a-zA-Z]/.test(src[j])) j += 1;
71
+ toks.push({ t: 'cmd', v: src.slice(i + 1, j) });
72
+ i = j;
73
+ continue;
74
+ }
75
+ if (c === '{' || c === '}' || c === '^' || c === '_') {
76
+ toks.push({ t: c });
77
+ i += 1;
78
+ continue;
79
+ }
80
+ if (/\s/.test(c)) { i += 1; continue; }
81
+ // 把连续的数字/小数点合成一个原子
82
+ if (/[0-9.]/.test(c)) {
83
+ let j = i;
84
+ while (j < src.length && /[0-9.]/.test(src[j])) j += 1;
85
+ toks.push({ t: 'chr', v: src.slice(i, j) });
86
+ i = j;
87
+ continue;
88
+ }
89
+ toks.push({ t: 'chr', v: c });
90
+ i += 1;
91
+ }
92
+ return toks;
93
+ }
94
+
95
+ /**
96
+ * 转换 LaTeX 子集 → OMML 片段(m:oMath 内部内容)。
97
+ * @returns {{ omml: string, unknown: string[] }}
98
+ */
99
+ export function latexToOmml(src) {
100
+ const toks = tokenize(String(src || ''));
101
+ const unknown = new Set();
102
+ let pos = 0;
103
+
104
+ const peek = () => toks[pos];
105
+ const next = () => toks[pos++];
106
+
107
+ function parseGroupOrAtom() {
108
+ if (peek() && peek().t === '{') {
109
+ next();
110
+ const inner = parseSeq(true);
111
+ if (peek() && peek().t === '}') next();
112
+ return inner;
113
+ }
114
+ return parseAtom();
115
+ }
116
+
117
+ function parseScripts(base) {
118
+ let sub = null;
119
+ let sup = null;
120
+ while (peek() && (peek().t === '_' || peek().t === '^')) {
121
+ const kind = next().t;
122
+ const val = parseGroupOrAtom();
123
+ if (kind === '_') sub = val; else sup = val;
124
+ }
125
+ if (sub !== null && sup !== null) {
126
+ return `<m:sSubSup><m:e>${base}</m:e><m:sub>${sub}</m:sub><m:sup>${sup}</m:sup></m:sSubSup>`;
127
+ }
128
+ if (sub !== null) return `<m:sSub><m:e>${base}</m:e><m:sub>${sub}</m:sub></m:sSub>`;
129
+ if (sup !== null) return `<m:sSup><m:e>${base}</m:e><m:sup>${sup}</m:sup></m:sSup>`;
130
+ return base;
131
+ }
132
+
133
+ function parseNary(baseChar) {
134
+ let sub = null;
135
+ let sup = null;
136
+ while (peek() && (peek().t === '_' || peek().t === '^')) {
137
+ const kind = next().t;
138
+ const val = parseGroupOrAtom();
139
+ if (kind === '_') sub = val; else sup = val;
140
+ }
141
+ const operand = (peek() && peek().t !== '}' && peek().t !== ']' && peek().t !== ')')
142
+ ? parseSeq(false, { single: true })
143
+ : '';
144
+ return '<m:nary>'
145
+ + '<m:naryPr><m:chr m:val="' + esc(baseChar) + '"/><m:limLoc m:val="undOvr"/>'
146
+ + (sub === null ? '<m:subHide m:val="1"/>' : '')
147
+ + (sup === null ? '<m:supHide m:val="1"/>' : '')
148
+ + '</m:naryPr>'
149
+ + `<m:sub>${sub || ''}</m:sub><m:sup>${sup || ''}</m:sup>`
150
+ + `<m:e>${operand}</m:e>`
151
+ + '</m:nary>';
152
+ }
153
+
154
+ function parseAtomRaw() {
155
+ const tok = next();
156
+ if (!tok) return { kind: 'xml', value: '' };
157
+
158
+ if (tok.t === 'cmd') {
159
+ const name = tok.v;
160
+
161
+ if (name === 'frac') {
162
+ const num = parseGroupOrAtom();
163
+ const den = parseGroupOrAtom();
164
+ return { kind: 'xml', value: `<m:f><m:num>${num}</m:num><m:den>${den}</m:den></m:f>` };
165
+ }
166
+ if (name === 'sqrt') {
167
+ let deg = null;
168
+ if (peek() && peek().t === 'chr' && peek().v === '[') {
169
+ next();
170
+ const parts = [];
171
+ while (peek() && !(peek().t === 'chr' && peek().v === ']')) parts.push(parseAtom());
172
+ if (peek()) next();
173
+ deg = parts.join('');
174
+ }
175
+ const body = parseGroupOrAtom();
176
+ return {
177
+ kind: 'xml',
178
+ value: '<m:rad>'
179
+ + `<m:radPr>${deg === null ? '<m:degHide m:val="1"/>' : ''}</m:radPr>`
180
+ + `<m:deg>${deg || ''}</m:deg><m:e>${body}</m:e>`
181
+ + '</m:rad>',
182
+ };
183
+ }
184
+ if (name === 'overline' || name === 'bar') {
185
+ const body = parseGroupOrAtom();
186
+ return {
187
+ kind: 'xml',
188
+ value: '<m:bar><m:barPr><m:pos m:val="top"/></m:barPr>'
189
+ + `<m:e>${body}</m:e></m:bar>`,
190
+ };
191
+ }
192
+ if (name === 'text' || name === 'mathrm' || name === 'operatorname') {
193
+ if (peek() && peek().t === '{') {
194
+ next();
195
+ const buf = [];
196
+ while (peek() && peek().t !== '}') {
197
+ const t = next();
198
+ buf.push(t.t === 'cmd' ? (t.v.length === 1 ? t.v : `\\${t.v}`) : (t.v || t.t));
199
+ }
200
+ if (peek()) next();
201
+ return { kind: 'upright', value: buf.join('') };
202
+ }
203
+ return { kind: 'xml', value: '' };
204
+ }
205
+ if (name === 'left' || name === 'right') {
206
+ const d = next();
207
+ if (!d) return { kind: 'xml', value: '' };
208
+ if (d.t === 'chr') return { kind: 'upright', value: d.v };
209
+ if (d.t === 'cmd') return { kind: 'upright', value: SYMBOL[d.v] || d.v };
210
+ return { kind: 'xml', value: '' };
211
+ }
212
+ if (name === 'sum' || name === 'prod' || name === 'int') {
213
+ return { kind: 'xml', value: parseNary(SYMBOL[name]) };
214
+ }
215
+ if (SPACE[name] !== undefined) return { kind: 'upright', value: SPACE[name] };
216
+ if (GREEK[name]) return { kind: 'upright', value: GREEK[name] };
217
+ if (SYMBOL[name] !== undefined) return { kind: 'upright', value: SYMBOL[name] };
218
+
219
+ unknown.add(name);
220
+ return { kind: 'upright', value: name };
221
+ }
222
+
223
+ if (tok.t === '{') {
224
+ const inner = parseSeq(true);
225
+ if (peek() && peek().t === '}') next();
226
+ return { kind: 'xml', value: inner };
227
+ }
228
+ if (tok.t === 'chr') {
229
+ return { kind: 'text', value: tok.v };
230
+ }
231
+ return { kind: 'xml', value: '' };
232
+ }
233
+
234
+ function parseAtom() {
235
+ const a = parseAtomRaw();
236
+ if (a.kind === 'xml') return a.value;
237
+ if (a.kind === 'upright') return mr(a.value, { italic: false });
238
+ return mr(a.value, { italic: /[a-zA-Z]/.test(a.value) });
239
+ }
240
+
241
+ /**
242
+ * 解析序列。
243
+ * @param {boolean} stopOnBrace 遇到 } 停止
244
+ * @param {{single?: boolean}} opts single=true 时只取一个原子(用于 n 元运算符的操作数)
245
+ */
246
+ function parseSeq(stopOnBrace, opts = {}) {
247
+ const out = [];
248
+ let pending = ''; // 连续普通字符合并成一个 run,减少碎片、便于 Word 编辑
249
+ const flush = () => {
250
+ if (pending) { out.push(mr(pending, { italic: /[a-zA-Z]/.test(pending) })); pending = ''; }
251
+ };
252
+
253
+ while (pos < toks.length) {
254
+ if (stopOnBrace && toks[pos].t === '}') break;
255
+
256
+ // 上下标必须挂到「前一个」基元上:若仍有待合并字符,先把它变成基元再解析脚本
257
+ if (toks[pos].t === '_' || toks[pos].t === '^') {
258
+ if (pending) {
259
+ const base = mr(pending, { italic: /[a-zA-Z]/.test(pending) });
260
+ pending = '';
261
+ out.push(parseScripts(base));
262
+ } else if (out.length) {
263
+ // 基元已单独成 run(如右括号、希腊字母),回填脚本
264
+ const last = out.pop();
265
+ out.push(parseScripts(last));
266
+ } else {
267
+ next(); // 无基元的孤立脚本标记,丢弃以免死循环
268
+ }
269
+ if (opts.single) break;
270
+ continue;
271
+ }
272
+
273
+ const a = parseAtomRaw();
274
+ if (a.kind === 'text' || a.kind === 'upright') {
275
+ // 正体字符(希腊、符号)不与普通字母混排,先冲掉待合并缓冲
276
+ if (a.kind === 'upright' && pending) flush();
277
+ pending += a.value;
278
+ if (opts.single) {
279
+ // 单原子模式:若后面紧跟脚本,需要把待合并字符作为基元
280
+ if (peek() && (peek().t === '_' || peek().t === '^')) continue;
281
+ flush();
282
+ break;
283
+ }
284
+ continue;
285
+ }
286
+ flush();
287
+ out.push(parseScripts(a.value));
288
+ if (opts.single) break;
289
+ }
290
+ flush();
291
+ return out.join('');
292
+ }
293
+
294
+ const body = parseSeq(false);
295
+ return { omml: `<m:oMath>${body}</m:oMath>`, unknown: [...unknown] };
296
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@aiking/bridge-reportkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "工程报告排版基础设施:DOCX 引擎(字体/配色/页眉页脚/表名/公式/封面/目录)+ LaTeX→OMML + 排版规则校验。供 @aiking/bridge-* 各规范插件复用。",
5
+ "type": "module",
6
+ "main": "lib/kit.js",
7
+ "exports": {
8
+ ".": "./lib/kit.js",
9
+ "./docx": "./lib/docx.js",
10
+ "./latex": "./lib/latex2omml.js"
11
+ },
12
+ "files": [
13
+ "lib",
14
+ "README.md",
15
+ "LICENSE",
16
+ "NOTICE"
17
+ ],
18
+ "scripts": {
19
+ "test": "node --test test/*.test.mjs"
20
+ },
21
+ "keywords": [
22
+ "bridge",
23
+ "report",
24
+ "docx",
25
+ "omml",
26
+ "latex",
27
+ "infrastructure"
28
+ ],
29
+ "license": "UNLICENSED",
30
+ "publishConfig": {
31
+ "access": "public"
32
+ }
33
+ }