@wwkit/harness 1.0.45 → 1.0.46
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/package.json +1 -1
- package/skills/convert-files/scripts/convert.js +1 -1
- package/skills/pea/SKILL.md +6 -1
- package/skills/pea/references/tpl-prd/epic.md +10 -0
- package/skills/pea/references/tpl-prd/us.md +4 -4
- package/skills/peago/SKILL.md +113 -0
- package/skills/peago/references/extract/baseline.md +17 -0
- package/skills/peago/references/extract/spec.md +117 -0
- package/skills/peago/references/res2kb/spec.md +113 -0
- package/skills/peago/references/spec-format.md +123 -0
- package/skills/peago/references/translate/baseline.md +26 -0
- package/skills/peago/references/translate/spec.md +132 -0
- package/skills/shared/references/template/pea/spec-agile.md +15 -6
- package/skills/shared/references/template/pea/spec-common.md +12 -2
- package/skills/shared/scripts/format.md +1 -1
- package/skills/extract/SKILL.md +0 -251
- package/skills/extract/references/detail_schema.json5 +0 -49
- package/skills/extract/references/detail_workflow.md +0 -55
- package/skills/extract/references/list_rule_gen.md +0 -109
- package/skills/extract/references/list_schema.json5 +0 -34
- package/skills/extract/references/list_workflow.md +0 -135
- package/skills/extract/references/navi_schema.json5 +0 -23
- package/skills/extract/references/navi_workflow.md +0 -45
- package/skills/extract/references/planning_template.md +0 -206
- package/skills/extract/references/text_schema.json5 +0 -22
- package/skills/extract/references/text_workflow.md +0 -41
- package/skills/extract/scripts/build_xpath.js +0 -31
- package/skills/extract/scripts/clean_html.js +0 -91
- package/skills/extract/scripts/extract_detail.js +0 -72
- package/skills/extract/scripts/extract_regex.js +0 -82
- package/skills/extract/scripts/extract_sample.js +0 -49
- package/skills/extract/scripts/to_text.js +0 -21
- package/skills/extract/scripts/validate_schema.js +0 -40
- package/skills/revise/SKILL.md +0 -66
- package/skills/revise/references/article.md +0 -37
- package/skills/revise/references/article.schema.json5 +0 -40
- package/skills/revise/references/gallery.md +0 -35
- package/skills/revise/references/gallery.schema.json5 +0 -40
- package/skills/revise/references/question.md +0 -33
- package/skills/revise/references/question.schema.json5 +0 -31
- package/skills/revise/references/sprint_for_revise.md +0 -46
- package/skills/revise/references/status.md +0 -32
- package/skills/revise/references/status.schema.json5 +0 -27
- package/skills/revise/scripts/check_input_vars.js +0 -127
- package/skills/revise/scripts/init.js +0 -84
- package/skills/revise/scripts/resolve_run_vars.js +0 -71
- package/skills/revise/scripts/validate-schema.js +0 -94
- package/skills/translate/SKILL.md +0 -398
- package/skills/translate/app.json5 +0 -70
- package/skills/translate/package.json +0 -11
- package/skills/translate/references/failure-diagnosis.md +0 -43
- package/skills/translate/references/format-prompt.md +0 -62
- package/skills/translate/references/format-rules.md +0 -39
- package/skills/translate/references/global-review-rules.md +0 -23
- package/skills/translate/references/glossary-prompt.md +0 -86
- package/skills/translate/references/glossary-rules.md +0 -44
- package/skills/translate/references/prepare-prompt.md +0 -110
- package/skills/translate/references/prepare-rules.md +0 -20
- package/skills/translate/references/resume-detection.md +0 -51
- package/skills/translate/references/rulings.md +0 -15
- package/skills/translate/references/translation-prompt.md +0 -73
- package/skills/translate/references/translation-rules.md +0 -51
- package/skills/translate/scripts/check-boundaries.js +0 -169
- package/skills/translate/scripts/check-paragraphs.js +0 -71
- package/skills/translate/scripts/chunk-bilingual.js +0 -123
- package/skills/translate/scripts/chunk-text.js +0 -145
- package/skills/translate/scripts/clean-text.js +0 -121
- package/skills/translate/scripts/count-terms.js +0 -54
- package/skills/translate/scripts/extract-pdf.js +0 -94
- package/skills/translate/scripts/generate-review.js +0 -179
- package/skills/translate/scripts/init-progress.js +0 -144
- package/skills/translate/scripts/md-to-docx.js +0 -381
- package/skills/translate/scripts/merge-format.js +0 -110
- package/skills/translate/scripts/merge-result.js +0 -113
- package/skills/translate/scripts/verify-chunk.js +0 -185
- package/skills/translate/todos.md +0 -38
- package/skills/translate-file/SKILL.md +0 -45
- package/skills/translate-file/package.json +0 -10
- package/skills/translate-file/references/sprint_for_preprocess.md +0 -14
- package/skills/translate-file/references/sprint_for_teardown.md +0 -15
- package/skills/translate-file/references/sprint_for_translate.md +0 -74
- package/skills/translate-file/references/translation_prompt.md +0 -43
- package/skills/translate-file/scripts/check_input_vars.js +0 -53
- package/skills/translate-file/scripts/chunk_text.js +0 -167
- package/skills/translate-file/scripts/clean_text.js +0 -121
- package/skills/translate-file/scripts/extract.js +0 -98
- package/skills/translate-file/scripts/generate_review.js +0 -155
- package/skills/translate-file/scripts/init.js +0 -86
- package/skills/translate-file/scripts/merge_results.js +0 -112
- package/skills/translate-file/scripts/resolve_run_vars.js +0 -123
- package/skills/translate-file/scripts/verify_chunk.js +0 -144
- package/skills/translate-format/SKILL.md +0 -45
- package/skills/translate-format/references/format-prompt.md +0 -80
- package/skills/translate-format/references/format-rules.md +0 -39
- package/skills/translate-format/references/sprint_for_format.md +0 -208
- package/skills/translate-format/scripts/check-paragraphs.js +0 -81
- package/skills/translate-format/scripts/check_input_vars.js +0 -51
- package/skills/translate-format/scripts/chunk-bilingual.js +0 -135
- package/skills/translate-format/scripts/count-words.js +0 -38
- package/skills/translate-format/scripts/diagnose-failure.js +0 -54
- package/skills/translate-format/scripts/init.js +0 -71
- package/skills/translate-format/scripts/md-to-docx.js +0 -398
- package/skills/translate-format/scripts/merge-format.js +0 -118
- package/skills/translate-format/scripts/resolve_run_vars.js +0 -78
|
@@ -1,398 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* md-to-docx.js — Markdown 转 docx 脚本(ESM)
|
|
4
|
-
*
|
|
5
|
-
* 将 Markdown 内容/文件转换为 Microsoft Word (.docx)。
|
|
6
|
-
* 被 translate-format(Item 6 docx 生成)引用。
|
|
7
|
-
*
|
|
8
|
-
* 三道转换前/后修正(缺一不可,都针对 Word 打开 docx 报错):
|
|
9
|
-
* 1. sanitizeMarkdownUrls(转换前):把"裸 URL + 全角标点/CJK 紧贴"的畸形转成
|
|
10
|
-
* 标准 Markdown 链接,防止 marked 的 GFM autolink 把全角标点/中文吞入 href
|
|
11
|
-
* 生成非法 URI(Word 打开报超链接错误)。
|
|
12
|
-
* 2. normalizeFootnoteLabels(转换前):translate/translate-format 产物中每章脚注重新编号
|
|
13
|
-
* ([^1]..[^N]),全书 label 大量复用。markdown-docx 用 label 作 key,后章
|
|
14
|
-
* 定义覆盖前章定义,生成大量"孤儿定义 + 重复引用",Word 报成百上千个脚注
|
|
15
|
-
* 错误。本函数按"正文引用 → 之后最近的同 label 定义"配对,把 label 重写为
|
|
16
|
-
* 全局唯一 [^f1]..[^fN];同时给紧贴正文段落的定义行前补空行(否则 marked
|
|
17
|
-
* 的 paragraph tokenizer 会吞掉定义行,footnote 扩展匹配不到)。
|
|
18
|
-
* 3. rebuildFootnotes(转换后兜底):把 document.xml 每个脚注/尾注引用按出现
|
|
19
|
-
* 顺序分配唯一 id(同一旧 id 的重复引用拆分为独立定义,内容复制),重建
|
|
20
|
-
* footnotes.xml/endnotes.xml(保留 Word 规范的 separator id=-1 与
|
|
21
|
-
* continuationSeparator id=0,并保留 XML 声明与完整 xmlns——两者缺失都会让
|
|
22
|
-
* Word 报 xml parsing error),删除无引用的孤儿定义。
|
|
23
|
-
*
|
|
24
|
-
* 用法:node md-to-docx.js <input_dir|input.md> [--ignore-image]
|
|
25
|
-
* node md-to-docx.js --check # 仅检查 markdown-docx 依赖可用性
|
|
26
|
-
* - 目录模式:扫描 <input_dir>/*-fmt.md,逐个转同名 .docx
|
|
27
|
-
* - 文件模式:<input.md> → 同名 .docx
|
|
28
|
-
* 短路:输出 docx 已存在且非空 → 打印 skipped(避免重复创建)
|
|
29
|
-
* stdout: docx: <input> → <output> (bytes=N)
|
|
30
|
-
* 退出码:0 成功/短路 / 2 参数或输入错误 / 3 依赖缺失 / 4 转换或写入失败
|
|
31
|
-
*/
|
|
32
|
-
|
|
33
|
-
import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync, readdirSync } from 'fs';
|
|
34
|
-
import { dirname, join, basename } from 'path';
|
|
35
|
-
import { createRequire } from 'module';
|
|
36
|
-
import JSZip from 'jszip';
|
|
37
|
-
|
|
38
|
-
const require = createRequire(import.meta.url);
|
|
39
|
-
|
|
40
|
-
// markdown-docx 默认选项:启用 GFM(脚注/表格/删除线等扩展语法依赖)
|
|
41
|
-
const DEFAULTS = { gfm: true };
|
|
42
|
-
|
|
43
|
-
const OK_DOCX = 'OK: docx 已生成'
|
|
44
|
-
const OK_SKIPPED = 'OK: docx 已跳过(输出已存在)'
|
|
45
|
-
const OK_DEPS = 'OK: markdown-docx 依赖可用'
|
|
46
|
-
const INVALID_USAGE = 'INVALID: 用法 node md-to-docx.js <input_dir|input.md> [--ignore-image]'
|
|
47
|
-
const INVALID_INPUT = 'INVALID: 输入必须是 .md 文件或目录'
|
|
48
|
-
const INVALID_NOT_FOUND = 'INVALID: 输入文件不存在'
|
|
49
|
-
const INVALID_NO_MD = 'INVALID: 目录中无 *-fmt.md 文件'
|
|
50
|
-
const ERROR_DEPS = 'ERROR: markdown-docx 不可用,请在 skills/translate-format 下 npm install'
|
|
51
|
-
const ERROR_CONVERT = 'ERROR: 转换失败'
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* 惰性加载 markdown-docx(依赖检查用)。
|
|
55
|
-
* @returns {{ default: Function, Packer: object }} markdown-docx 模块
|
|
56
|
-
* @throws {Error} markdown-docx 不可用时抛出,附带安装提示
|
|
57
|
-
*/
|
|
58
|
-
function loadMarkdownDocx() {
|
|
59
|
-
try {
|
|
60
|
-
const mod = require('markdown-docx');
|
|
61
|
-
return { default: mod.default || mod, Packer: mod.Packer };
|
|
62
|
-
} catch {
|
|
63
|
-
throw new Error('ERROR: markdown-docx not available. Run: npm install (in skills/translate-format)');
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* 将跨章节复用的脚注 label 归一化为全局唯一(转换前预处理)。
|
|
69
|
-
*
|
|
70
|
-
* 背景:translate-format 产物中每章脚注重新编号([^1]..[^N]),全书 label 大量
|
|
71
|
-
* 复用(实测 141 个定义行只有 14 个唯一 label)。markdown-docx 的 label→id Map
|
|
72
|
-
* 被后章定义覆盖,导致前章脚注内容丢失、生成大量孤儿定义与重复引用,Word 打开
|
|
73
|
-
* 报"成百上千个脚注错误"。
|
|
74
|
-
*
|
|
75
|
-
* 配对规则:正文引用 [^x] 对应其"之后最近"的同 label 定义(translate-format 产物中
|
|
76
|
-
* 脚注定义位于各章末尾,正文引用在前)。定义在前、引用在后的罕见场景回退到
|
|
77
|
-
* "之前最近"的同 label 定义。无法配对的引用保留原样(不报错,按普通文本处理)。
|
|
78
|
-
*
|
|
79
|
-
* @param {string} markdown - 原始 Markdown 文本
|
|
80
|
-
* @returns {string} 归一化后的 Markdown(label 全部形如 [^f1]..[^fN])
|
|
81
|
-
*/
|
|
82
|
-
export function normalizeFootnoteLabels(markdown) {
|
|
83
|
-
const lines = markdown.split('\n');
|
|
84
|
-
const defs = new Map(); // label -> [行号]
|
|
85
|
-
const defLines = new Set(); // 定义行号
|
|
86
|
-
let inCode = false;
|
|
87
|
-
lines.forEach((l, i) => {
|
|
88
|
-
if (/^\s*```/.test(l)) {
|
|
89
|
-
inCode = !inCode;
|
|
90
|
-
return;
|
|
91
|
-
}
|
|
92
|
-
if (inCode) return;
|
|
93
|
-
const m = l.match(/^\[\^([^\]\n]+)\]:/);
|
|
94
|
-
if (m) {
|
|
95
|
-
const label = m[1];
|
|
96
|
-
if (!defs.has(label)) defs.set(label, []);
|
|
97
|
-
defs.get(label).push(i);
|
|
98
|
-
defLines.add(i);
|
|
99
|
-
}
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
// 引用位置(跳过定义行与 ``` 代码块)
|
|
103
|
-
const refs = new Map(); // label -> [行号]
|
|
104
|
-
inCode = false;
|
|
105
|
-
lines.forEach((l, i) => {
|
|
106
|
-
if (/^\s*```/.test(l)) {
|
|
107
|
-
inCode = !inCode;
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
if (inCode || defLines.has(i)) return;
|
|
111
|
-
for (const m of l.matchAll(/\[\^([^\]\n]+)\]/g)) {
|
|
112
|
-
const label = m[1];
|
|
113
|
-
if (!refs.has(label)) refs.set(label, []);
|
|
114
|
-
refs.get(label).push(i);
|
|
115
|
-
}
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
// 定义按文档顺序编号(1..N)
|
|
119
|
-
const defOrder = [];
|
|
120
|
-
for (const [label, positions] of defs) for (const li of positions) defOrder.push({ label, li });
|
|
121
|
-
defOrder.sort((a, b) => a.li - b.li);
|
|
122
|
-
const idxOf = new Map(); // `${label}#${行号}` -> 全局序号
|
|
123
|
-
defOrder.forEach((d, i) => idxOf.set(`${d.label}#${d.li}`, i + 1));
|
|
124
|
-
|
|
125
|
-
// 引用 → 定义映射(之后最近优先,回退之前最近)
|
|
126
|
-
const refIdx = new Map(); // `${label}#${行号}` -> 定义序号 | -1(无法配对)
|
|
127
|
-
for (const [label, rlines] of refs) {
|
|
128
|
-
const dlines = defs.get(label) || [];
|
|
129
|
-
for (const li of rlines) {
|
|
130
|
-
const later = dlines.find((d) => d > li);
|
|
131
|
-
if (later !== undefined) {
|
|
132
|
-
refIdx.set(`${label}#${li}`, idxOf.get(`${label}#${later}`));
|
|
133
|
-
} else {
|
|
134
|
-
const earlier = [...dlines].reverse().find((d) => d < li);
|
|
135
|
-
refIdx.set(`${label}#${li}`, earlier !== undefined ? idxOf.get(`${label}#${earlier}`) : -1);
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
return lines
|
|
141
|
-
.map((l, i) => {
|
|
142
|
-
if (defLines.has(i)) {
|
|
143
|
-
const rewritten = l.replace(/^\[\^([^\]\n]+)\]:/, (m, label) => `[^f${idxOf.get(`${label}#${i}`)}]:`);
|
|
144
|
-
// 定义行前补空行(若前一行非空且非文档开头):marked 的 paragraph tokenizer
|
|
145
|
-
// 会把紧贴正文段落(无空行分隔)的定义行吞进段落,footnote 扩展永远匹配不到。
|
|
146
|
-
return (i > 0 && lines[i - 1].trim() !== '' ? '\n' : '') + rewritten;
|
|
147
|
-
}
|
|
148
|
-
return l.replace(/\[\^([^\]\n]+)\]/g, (m, label) => {
|
|
149
|
-
const idx = refIdx.get(`${label}#${i}`);
|
|
150
|
-
return idx && idx > 0 ? `[^f${idx}]` : m;
|
|
151
|
-
});
|
|
152
|
-
})
|
|
153
|
-
.join('\n');
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* 解析 footnotes.xml / endnotes.xml,供 rebuildFootnotes 重建时复用。
|
|
158
|
-
*
|
|
159
|
-
* 返回对象字段:
|
|
160
|
-
* - decl:XML 声明(`<?xml ...?>`),重建时必须原样保留
|
|
161
|
-
* - rootOpen:根开标签(含全部 xmlns 声明),重建时必须原样保留
|
|
162
|
-
* - sep / contSep:separator / continuationSeparator 定义(Word 规范 id=-1 / 0)
|
|
163
|
-
* - defs:普通脚注定义 id → 内部 XML 的映射
|
|
164
|
-
* - tag / plural:元素名('footnote'/'footnotes' 或 'endnote'/'endnotes')
|
|
165
|
-
*
|
|
166
|
-
* @param {string} xml - footnotes.xml 或 endnotes.xml 文本
|
|
167
|
-
* @param {string} tag - 'footnote' | 'endnote'
|
|
168
|
-
*/
|
|
169
|
-
function parseNotesXml(xml, tag) {
|
|
170
|
-
const plural = `${tag}s`;
|
|
171
|
-
// 必须保留 XML 声明(<?xml ...?>)与根开标签的完整 xmlns 声明:
|
|
172
|
-
// 若丢失,w: 前缀未绑定命名空间,Word 报 "xml parsing error"(行0,列0)。
|
|
173
|
-
const decl = xml.match(/^<\?xml[^>]*\?>/)?.[0] || '';
|
|
174
|
-
const rootOpen = xml.match(new RegExp(`<w:${plural}[^>]*>`))?.[0] || `<w:${plural}>`;
|
|
175
|
-
const sep = xml.match(new RegExp(`<w:${tag} w:type="separator"[^>]*>.*?</w:${tag}>`, 's'))?.[0] || '';
|
|
176
|
-
const contSep = xml.match(
|
|
177
|
-
new RegExp(`<w:${tag} w:type="continuationSeparator"[^>]*>.*?</w:${tag}>`, 's')
|
|
178
|
-
)?.[0] || '';
|
|
179
|
-
const defs = new Map();
|
|
180
|
-
const re = new RegExp(`<w:${tag} w:id="(\\d+)">(.*?)</w:${tag}>`, 'gs');
|
|
181
|
-
let m;
|
|
182
|
-
while ((m = re.exec(xml))) defs.set(parseInt(m[1], 10), m[2]);
|
|
183
|
-
return { decl, rootOpen, sep, contSep, defs, tag, plural };
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/**
|
|
187
|
-
* 重建 docx 中的脚注/尾注结构(转换后兜底)。
|
|
188
|
-
*
|
|
189
|
-
* 保证每个引用在 document.xml 中有唯一定义且定义全部被引用,彻底消除
|
|
190
|
-
* "重复引用 + 孤儿定义"(Word 严格校验的报错来源);保留 Word 规范的
|
|
191
|
-
* separator(id=-1) / continuationSeparator(id=0) 以及 XML 声明与完整 xmlns
|
|
192
|
-
* 命名空间(缺失则 Word 报 xml parsing error 行0列0);普通脚注按引用出现
|
|
193
|
-
* 顺序分配连续 id(1..M)。同一旧 id 的重复引用拆分为独立定义(内容复制)。
|
|
194
|
-
*
|
|
195
|
-
* @param {Buffer} docxBuffer - 原始 docx buffer
|
|
196
|
-
* @returns {Promise<Buffer>} 重建后的 docx buffer
|
|
197
|
-
*/
|
|
198
|
-
export async function rebuildFootnotes(docxBuffer) {
|
|
199
|
-
const zip = await JSZip.loadAsync(docxBuffer);
|
|
200
|
-
const docXml = await zip.file('word/document.xml').async('string');
|
|
201
|
-
|
|
202
|
-
// 引用按在 document.xml 中的出现顺序重编号为 1..M(每个引用一个唯一 id)
|
|
203
|
-
let fnCounter = 0;
|
|
204
|
-
let enCounter = 0;
|
|
205
|
-
const fnUses = []; // { oldId, newId }:脚注引用记录
|
|
206
|
-
const enUses = []; // { oldId, newId }:尾注引用记录
|
|
207
|
-
const newDocXml = docXml
|
|
208
|
-
.replace(/w:footnoteReference w:id="(-?\d+)"/g, (m, id) => {
|
|
209
|
-
fnCounter += 1;
|
|
210
|
-
fnUses.push({ oldId: parseInt(id, 10), newId: fnCounter });
|
|
211
|
-
return `w:footnoteReference w:id="${fnCounter}"`;
|
|
212
|
-
})
|
|
213
|
-
.replace(/w:endnoteReference w:id="(-?\d+)"/g, (m, id) => {
|
|
214
|
-
enCounter += 1;
|
|
215
|
-
enUses.push({ oldId: parseInt(id, 10), newId: enCounter });
|
|
216
|
-
return `w:endnoteReference w:id="${enCounter}"`;
|
|
217
|
-
});
|
|
218
|
-
|
|
219
|
-
// 按引用记录重建 notes XML:声明 + 根开标签 + 两个特殊定义 + 普通定义
|
|
220
|
-
const buildNotes = (notes, uses) => {
|
|
221
|
-
const { decl, rootOpen, sep, contSep, defs, tag, plural } = notes;
|
|
222
|
-
let body = '';
|
|
223
|
-
for (const { oldId, newId } of uses) {
|
|
224
|
-
// 引用无对应定义时用空段落占位(正常流程不会发生,仅为结构兜底)
|
|
225
|
-
const inner = defs.get(oldId) || '<w:p><w:r><w:t xml:space="preserve"> </w:t></w:r></w:p>';
|
|
226
|
-
body += `<w:${tag} w:id="${newId}">${inner}</w:${tag}>`;
|
|
227
|
-
}
|
|
228
|
-
return `${decl}${rootOpen}${sep}${contSep}${body}</w:${plural}>`;
|
|
229
|
-
};
|
|
230
|
-
|
|
231
|
-
if (zip.file('word/footnotes.xml')) {
|
|
232
|
-
const fnXml = await zip.file('word/footnotes.xml').async('string');
|
|
233
|
-
zip.file('word/footnotes.xml', buildNotes(parseNotesXml(fnXml, 'footnote'), fnUses));
|
|
234
|
-
}
|
|
235
|
-
if (zip.file('word/endnotes.xml')) {
|
|
236
|
-
const enXml = await zip.file('word/endnotes.xml').async('string');
|
|
237
|
-
zip.file('word/endnotes.xml', buildNotes(parseNotesXml(enXml, 'endnote'), enUses));
|
|
238
|
-
}
|
|
239
|
-
zip.file('word/document.xml', newDocXml);
|
|
240
|
-
return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* 裸 URL 匹配:https?:// 或 www. 开头,到空白/尖括号/全角标点/CJK 为止。
|
|
245
|
-
* 前缀排除半角 ( 和 ] —— 已是标准链接目标 `[text](url)` 的 URL 不被处理。
|
|
246
|
-
*/
|
|
247
|
-
const BARE_URL_RE = /(^|[^(\]])((?:https?:\/\/|www\.)[^\s<()《》“”‘’!?,。;:、\u4e00-\u9fff]+)/g;
|
|
248
|
-
|
|
249
|
-
/** URL 尾部回退的半角标点(与 marked _backpedal 一致)。 */
|
|
250
|
-
const TRAILING_ASCII_PUNCT = /[?!.,:;*_'"~)]+$/;
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* 清洗 Markdown 中的畸形裸 URL。
|
|
254
|
-
*
|
|
255
|
-
* 背景:marked 的 GFM autolink 对裸 URL 只回退半角尾部标点,
|
|
256
|
-
* 全角标点()、。,等)与 CJK 字符会被吞入 href,生成的 docx 超链接
|
|
257
|
-
* URI 非法,Word 打开时报错。本函数在转换前把畸形裸 URL 转为标准
|
|
258
|
-
* Markdown 链接 [url](url),URL 后的全角标点/中文保持在链接外。
|
|
259
|
-
*
|
|
260
|
-
* @param {string} markdown - 原始 Markdown 文本
|
|
261
|
-
* @returns {string} 清洗后的 Markdown 文本
|
|
262
|
-
*/
|
|
263
|
-
export function sanitizeMarkdownUrls(markdown) {
|
|
264
|
-
return markdown.replace(BARE_URL_RE, (match, prefix, url) => {
|
|
265
|
-
// 回退 URL 尾部半角标点(如 `pdf.` → url=`pdf`,`.` 放回链接外)
|
|
266
|
-
const cleaned = url.replace(TRAILING_ASCII_PUNCT, '');
|
|
267
|
-
if (cleaned.length === 0) return match;
|
|
268
|
-
const rest = url.slice(cleaned.length);
|
|
269
|
-
return `${prefix}[${cleaned}](${cleaned})${rest}`;
|
|
270
|
-
});
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
* 将 Markdown 内容转换为 docx Buffer。
|
|
275
|
-
* 流程:sanitizeMarkdownUrls(畸形 URL 清洗)→ normalizeFootnoteLabels(脚注
|
|
276
|
-
* label 全局唯一化)→ markdown-docx 转换 → rebuildFootnotes(脚注结构兜底重建)。
|
|
277
|
-
* @param {string} markdown - Markdown 文本内容
|
|
278
|
-
* @param {object} [options] - markdown-docx 转换选项
|
|
279
|
-
* @returns {Promise<Buffer>} docx 文件 buffer
|
|
280
|
-
*/
|
|
281
|
-
export async function mdToDocxBuffer(markdown, options = {}) {
|
|
282
|
-
const { default: markdownDocx, Packer } = loadMarkdownDocx();
|
|
283
|
-
const cleaned = normalizeFootnoteLabels(sanitizeMarkdownUrls(markdown));
|
|
284
|
-
const doc = await markdownDocx(cleaned, { ...DEFAULTS, ...options });
|
|
285
|
-
const rawBuf = await Packer.toBuffer(doc);
|
|
286
|
-
return rebuildFootnotes(rawBuf);
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
/**
|
|
290
|
-
* 将 Markdown 文件转换为 docx 文件。
|
|
291
|
-
* @param {string} inputPath - 输入 .md 文件路径
|
|
292
|
-
* @param {string} outputPath - 输出 .docx 文件路径(父目录不存在时自动创建)
|
|
293
|
-
* @param {object} [options] - markdown-docx 转换选项
|
|
294
|
-
* @returns {Promise<{ inputPath: string, outputPath: string, bytes: number }>}
|
|
295
|
-
* @throws {Error} 参数缺失 / 输入文件不存在 / 转换或写入失败
|
|
296
|
-
*/
|
|
297
|
-
export async function mdToDocx(inputPath, outputPath, options = {}) {
|
|
298
|
-
if (!inputPath || !outputPath) {
|
|
299
|
-
throw new Error('Usage: node md-to-docx.js <input.md> <output.docx>');
|
|
300
|
-
}
|
|
301
|
-
if (!existsSync(inputPath)) {
|
|
302
|
-
throw new Error(`ERROR: input file not found: ${inputPath}`);
|
|
303
|
-
}
|
|
304
|
-
const markdown = readFileSync(inputPath, 'utf-8');
|
|
305
|
-
const buf = await mdToDocxBuffer(markdown, options);
|
|
306
|
-
mkdirSync(dirname(outputPath), { recursive: true });
|
|
307
|
-
writeFileSync(outputPath, buf);
|
|
308
|
-
return { inputPath, outputPath, bytes: buf.length };
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
// --- CLI entry point (only when run directly, not when imported) ---
|
|
312
|
-
|
|
313
|
-
const isMain = import.meta.url === `file://${process.argv[1]}`;
|
|
314
|
-
|
|
315
|
-
if (isMain) {
|
|
316
|
-
const args = process.argv.slice(2);
|
|
317
|
-
|
|
318
|
-
// --check 模式:仅检查 markdown-docx 依赖可用性
|
|
319
|
-
if (args[0] === '--check') {
|
|
320
|
-
try {
|
|
321
|
-
loadMarkdownDocx();
|
|
322
|
-
console.log(OK_DEPS);
|
|
323
|
-
process.exit(0);
|
|
324
|
-
} catch {
|
|
325
|
-
console.error(ERROR_DEPS);
|
|
326
|
-
process.exit(3);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
const target = args[0];
|
|
331
|
-
const options = args.includes('--ignore-image') ? { ignoreImage: true } : {};
|
|
332
|
-
|
|
333
|
-
if (!target) {
|
|
334
|
-
console.error(INVALID_USAGE);
|
|
335
|
-
process.exit(2);
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
// 目录模式:扫描 <target>/*-fmt.md 批量转换
|
|
339
|
-
if (!target.endsWith('.md')) {
|
|
340
|
-
if (!existsSync(target) || !statSync(target).isDirectory()) {
|
|
341
|
-
console.error(`${INVALID_INPUT}: ${target}`);
|
|
342
|
-
process.exit(2);
|
|
343
|
-
}
|
|
344
|
-
const mdFiles = readdirSync(target)
|
|
345
|
-
.filter((f) => f.endsWith('-fmt.md'))
|
|
346
|
-
.sort();
|
|
347
|
-
if (mdFiles.length === 0) {
|
|
348
|
-
console.error(`${INVALID_NO_MD}: ${target}`);
|
|
349
|
-
process.exit(2);
|
|
350
|
-
}
|
|
351
|
-
for (const f of mdFiles) {
|
|
352
|
-
const inputPath = join(target, f);
|
|
353
|
-
const outputPath = inputPath.replace(/\.md$/, '.docx');
|
|
354
|
-
if (existsSync(outputPath) && statSync(outputPath).size > 0) {
|
|
355
|
-
console.log(`${OK_SKIPPED}: ${outputPath}`);
|
|
356
|
-
console.log(`| bytes |`)
|
|
357
|
-
console.log(`| ${statSync(outputPath).size} |`)
|
|
358
|
-
continue;
|
|
359
|
-
}
|
|
360
|
-
try {
|
|
361
|
-
const result = await mdToDocx(inputPath, outputPath, options);
|
|
362
|
-
console.log(`${OK_DOCX}: ${result.inputPath} → ${result.outputPath}`);
|
|
363
|
-
console.log(`| bytes |`)
|
|
364
|
-
console.log(`| ${result.bytes} |`)
|
|
365
|
-
} catch (e) {
|
|
366
|
-
console.error(`${ERROR_CONVERT}: ${e.message}`);
|
|
367
|
-
process.exit(4);
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
process.exit(0);
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
// 单文件模式:输出 = 输入同名 .docx
|
|
374
|
-
const inputPath = target;
|
|
375
|
-
const outputPath = inputPath.replace(/\.md$/, '.docx');
|
|
376
|
-
if (!existsSync(inputPath)) {
|
|
377
|
-
console.error(`${INVALID_NOT_FOUND}: ${inputPath}`);
|
|
378
|
-
process.exit(2);
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
// 短路:输出 docx 已存在且非空 → 跳过(避免重复创建)
|
|
382
|
-
if (existsSync(outputPath) && statSync(outputPath).size > 0) {
|
|
383
|
-
console.log(`${OK_SKIPPED}: ${outputPath}`);
|
|
384
|
-
console.log(`| bytes |`)
|
|
385
|
-
console.log(`| ${statSync(outputPath).size} |`)
|
|
386
|
-
process.exit(0);
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
try {
|
|
390
|
-
const result = await mdToDocx(inputPath, outputPath, options);
|
|
391
|
-
console.log(`${OK_DOCX}: ${result.inputPath} → ${result.outputPath}`);
|
|
392
|
-
console.log(`| bytes |`)
|
|
393
|
-
console.log(`| ${result.bytes} |`)
|
|
394
|
-
} catch (e) {
|
|
395
|
-
console.error(`${ERROR_CONVERT}: ${e.message}`);
|
|
396
|
-
process.exit(4);
|
|
397
|
-
}
|
|
398
|
-
}
|
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* merge-format.js — 合并 subagent 格式化结果到主产物(ESM)
|
|
4
|
-
*
|
|
5
|
-
* 用法:node merge-format.js <result-file>
|
|
6
|
-
* workDir = result 文件所在目录,chunkId = 文件名解析(result-pNNN.md → pNNN)
|
|
7
|
-
*
|
|
8
|
-
* 功能(全部在脚本内完成,主 Agent 上下文只获得一行输出):
|
|
9
|
-
* 1. 解析 result-pNNN.md:格式化内容 / status
|
|
10
|
-
* 2. VALID → 追加格式化内容到 <work-dir>/formatted.md
|
|
11
|
-
* 3. 更新 <work-dir>/progress.md(VALID→done,FAILED→failed+retry+1)
|
|
12
|
-
* 4. 删除 result 文件
|
|
13
|
-
* 5. stdout:`OK: pNNN VALID` 或 `OK: pNNN FAILED`
|
|
14
|
-
*
|
|
15
|
-
* 主 Agent 上下文只获得一行 status 输出,完整格式化内容不进入上下文。
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
import { readFileSync, writeFileSync, unlinkSync, existsSync } from 'fs'
|
|
19
|
-
import { join, dirname, basename } from 'path'
|
|
20
|
-
|
|
21
|
-
const OK_VALID = 'OK: ${chunkId} VALID'
|
|
22
|
-
const OK_FAILED = 'OK: ${chunkId} FAILED'
|
|
23
|
-
const INVALID_USAGE = 'INVALID: 用法 node merge-format.js <result-file>'
|
|
24
|
-
const INVALID_NOT_FOUND = 'INVALID: result 文件不存在'
|
|
25
|
-
const INVALID_FILENAME = 'INVALID: 文件名格式错误(期望 result-pNNN.md)'
|
|
26
|
-
const INVALID_NO_STATUS = 'INVALID: result 文件缺少 ## status 标记'
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* 合并单个 result 文件到主产物。
|
|
30
|
-
* @param {string} resultFile - result-pNNN.md 路径(workDir 和 chunkId 自动推导)
|
|
31
|
-
* @returns {{ chunkId: string, status: string }} 合并结果
|
|
32
|
-
* @throws {Error} 参数缺失 / 文件不存在 / 格式错误
|
|
33
|
-
*/
|
|
34
|
-
export function mergeFormat(resultFile) {
|
|
35
|
-
if (!resultFile) {
|
|
36
|
-
throw new Error(INVALID_USAGE)
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
if (!existsSync(resultFile)) {
|
|
40
|
-
throw new Error(`${INVALID_NOT_FOUND}: ${resultFile}`)
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const workDir = dirname(resultFile)
|
|
44
|
-
const chunkMatch = basename(resultFile).match(/^result-(p\d+)\.md$/)
|
|
45
|
-
if (!chunkMatch) {
|
|
46
|
-
throw new Error(`${INVALID_FILENAME}: ${basename(resultFile)}`)
|
|
47
|
-
}
|
|
48
|
-
const chunkId = chunkMatch[1]
|
|
49
|
-
|
|
50
|
-
const content = readFileSync(resultFile, 'utf-8')
|
|
51
|
-
|
|
52
|
-
// --- Parse result file ---
|
|
53
|
-
|
|
54
|
-
// Status: first VALID or FAILED after ## status
|
|
55
|
-
const statusMatch = content.match(/^## status\s*\n\s*(VALID|FAILED)/m)
|
|
56
|
-
if (!statusMatch) {
|
|
57
|
-
throw new Error(`${INVALID_NO_STATUS}: ${resultFile}`)
|
|
58
|
-
}
|
|
59
|
-
const status = statusMatch[1]
|
|
60
|
-
const statusPos = content.indexOf('## status')
|
|
61
|
-
|
|
62
|
-
// Formatted content = everything before ## status
|
|
63
|
-
const formattedContent = content.substring(0, statusPos).trim()
|
|
64
|
-
|
|
65
|
-
// --- 1. Append formatted content (VALID only) ---
|
|
66
|
-
|
|
67
|
-
if (status === 'VALID' && formattedContent) {
|
|
68
|
-
const formattedPath = join(workDir, 'formatted.md')
|
|
69
|
-
if (existsSync(formattedPath)) {
|
|
70
|
-
const existing = readFileSync(formattedPath, 'utf-8')
|
|
71
|
-
const sep = existing.endsWith('\n') ? '' : '\n'
|
|
72
|
-
writeFileSync(formattedPath, existing + sep + formattedContent + '\n')
|
|
73
|
-
} else {
|
|
74
|
-
writeFileSync(formattedPath, formattedContent + '\n')
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// --- 2. Update progress.md ---
|
|
79
|
-
|
|
80
|
-
const progressPath = join(workDir, 'progress.md')
|
|
81
|
-
const progress = readFileSync(progressPath, 'utf-8')
|
|
82
|
-
const lines = progress.split('\n')
|
|
83
|
-
const updatedLines = lines.map(line => {
|
|
84
|
-
const match = line.match(/^\| (p\d+) \| (\w+) \| (\d+) \|$/)
|
|
85
|
-
if (match && match[1] === chunkId) {
|
|
86
|
-
if (status === 'VALID') {
|
|
87
|
-
return `| ${chunkId} | done | ${match[3]} |`
|
|
88
|
-
} else {
|
|
89
|
-
return `| ${chunkId} | failed | ${parseInt(match[3], 10) + 1} |`
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return line
|
|
93
|
-
})
|
|
94
|
-
writeFileSync(progressPath, updatedLines.join('\n'))
|
|
95
|
-
|
|
96
|
-
// --- 3. Delete result file ---
|
|
97
|
-
|
|
98
|
-
unlinkSync(resultFile)
|
|
99
|
-
|
|
100
|
-
// --- 4. Return result ---
|
|
101
|
-
|
|
102
|
-
return { chunkId, status }
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// --- CLI entry point (only when run directly, not when imported) ---
|
|
106
|
-
|
|
107
|
-
const isMain = import.meta.url === `file://${process.argv[1]}`
|
|
108
|
-
if (isMain) {
|
|
109
|
-
const resultFile = process.argv[2]
|
|
110
|
-
try {
|
|
111
|
-
const result = mergeFormat(resultFile)
|
|
112
|
-
const template = result.status === 'VALID' ? OK_VALID : OK_FAILED
|
|
113
|
-
console.log(template.replace('${chunkId}', result.chunkId))
|
|
114
|
-
} catch (e) {
|
|
115
|
-
console.error(e.message)
|
|
116
|
-
process.exit(2)
|
|
117
|
-
}
|
|
118
|
-
}
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* resolve_run_vars.js — 输出 Run 变量表(接收 skill_data_dir + input,计算 run 变量)
|
|
3
|
-
*
|
|
4
|
-
* 输入:argv[2] = skill_data_dir(系统变量),argv[3] = input(.txt 文件路径)
|
|
5
|
-
* 计算:input_dir / file_name / tmp / chunk_words
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { existsSync, statSync } from 'fs'
|
|
9
|
-
import { dirname, basename, join } from 'path'
|
|
10
|
-
import { render } from '../../shared/scripts/utils.js'
|
|
11
|
-
|
|
12
|
-
const RUN_VARS_TEMPLATE = `OK: Run 变量已解析
|
|
13
|
-
|
|
14
|
-
## Run 变量表
|
|
15
|
-
|
|
16
|
-
| 变量 | 值 | 说明 |
|
|
17
|
-
|---|---|---|
|
|
18
|
-
| \`input_dir\` | \${input_dir} | input 文件所在目录 |
|
|
19
|
-
| \`file_name\` | \${file_name} | input 文件名去掉 .txt 扩展名 |
|
|
20
|
-
| \`tmp\` | \${tmp} | 格式重建临时工作目录 |
|
|
21
|
-
| \`chunk_words\` | \${chunk_words} | 每块最大词数(默认 4000) |`
|
|
22
|
-
|
|
23
|
-
const INVALID_TEMPLATE = 'INVALID: ${error}'
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* 计算 run 变量(纯函数,可测试)。
|
|
27
|
-
* @param {string} skillDataDir — skill 数据目录绝对路径
|
|
28
|
-
* @param {string} inputPath — 源 .txt 文件路径
|
|
29
|
-
* @param {number} [chunkWords=4000] — 每块最大词数
|
|
30
|
-
* @returns {{input_dir: string, file_name: string, tmp: string, chunk_words: number} | {error: string}}
|
|
31
|
-
*/
|
|
32
|
-
export function resolveRunVars(skillDataDir, inputPath, chunkWords = 4000) {
|
|
33
|
-
if (!skillDataDir) {
|
|
34
|
-
return { error: '系统变量 skill_data_dir 未提供,请立即按短路规则处理' }
|
|
35
|
-
}
|
|
36
|
-
if (!existsSync(skillDataDir) || !statSync(skillDataDir).isDirectory()) {
|
|
37
|
-
return { error: `系统变量 skill_data_dir 非法:${skillDataDir},请立即按短路规则处理` }
|
|
38
|
-
}
|
|
39
|
-
if (!inputPath) {
|
|
40
|
-
return { error: 'input 未提供,请立即按短路规则处理' }
|
|
41
|
-
}
|
|
42
|
-
if (!existsSync(inputPath) || !statSync(inputPath).isFile()) {
|
|
43
|
-
return { error: `input 不存在或不是文件:${inputPath},请立即按短路规则处理` }
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
const inputDir = dirname(inputPath)
|
|
47
|
-
const fileName = basename(inputPath, '.txt')
|
|
48
|
-
const tmp = join(inputDir, '.tsl', fileName, 'fmt')
|
|
49
|
-
|
|
50
|
-
return {
|
|
51
|
-
input_dir: inputDir,
|
|
52
|
-
file_name: fileName,
|
|
53
|
-
tmp,
|
|
54
|
-
chunk_words: chunkWords,
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* 渲染 Run 变量表为 Markdown 字符串。
|
|
60
|
-
*/
|
|
61
|
-
export function formatRunVars(vars) {
|
|
62
|
-
return render(RUN_VARS_TEMPLATE, vars)
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const isMain = import.meta.url === `file://${process.argv[1]}`
|
|
66
|
-
if (isMain) {
|
|
67
|
-
const skillDataDir = process.argv[2]
|
|
68
|
-
const inputPath = process.argv[3]
|
|
69
|
-
|
|
70
|
-
const result = resolveRunVars(skillDataDir, inputPath)
|
|
71
|
-
|
|
72
|
-
if (result.error) {
|
|
73
|
-
console.log(render(INVALID_TEMPLATE, { error: result.error }))
|
|
74
|
-
process.exit(0)
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
console.log(render(RUN_VARS_TEMPLATE, result))
|
|
78
|
-
}
|