lantern-harness 0.1.44 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +224 -0
  2. package/README.md +25 -8
  3. package/builtin/session/lh-fs.mjs +93 -4
  4. package/builtin/session/lh-nav-groups.mjs +3 -0
  5. package/builtin/session/mcp-client.mjs +7 -3
  6. package/builtin/session/session-runs.mjs +5 -1
  7. package/builtin/session/skill-validation.mjs +72 -0
  8. package/builtin/session/space-skills.mjs +751 -0
  9. package/cli/data-root.mjs +21 -4
  10. package/cli/lantern.mjs +26 -1
  11. package/cli/mcp-server.mjs +2779 -0
  12. package/cli/server.mjs +8 -2
  13. package/config/app.defaults.json +4 -2
  14. package/dist/500.html +9 -6
  15. package/dist/_astro/Base.Du_-4L-4.css +1 -0
  16. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.XUV2H6ea.js +2 -0
  17. package/dist/_astro/BusinessMapBoard.mRxl2G3D.js +5 -0
  18. package/dist/_astro/CaseExecBoard.Cqkxuf5c.js +1 -0
  19. package/dist/_astro/CaseExecutionBoard.CjX4CoKd.js +5 -0
  20. package/dist/_astro/CaseGenerateApp.acgnxl79.js +10 -0
  21. package/dist/_astro/CasesLibrary.zmzOQwdn.js +21 -0
  22. package/dist/_astro/ChatApp.Ben9LFra.js +1 -0
  23. package/dist/_astro/ChatApp.DBi6q7Qv.js +262 -0
  24. package/dist/_astro/{ConfirmDialog.DrrPf1MB.js → ConfirmDialog.DQFd6g2r.js} +1 -1
  25. package/dist/_astro/DashboardBoard.CAJVE2G4.js +5 -0
  26. package/dist/_astro/{DatePicker.Bkl71M49.js → DatePicker.BRO_CjVQ.js} +1 -1
  27. package/dist/_astro/DefectSubmitEntry.BzKXJ-zq.js +2 -0
  28. package/dist/_astro/DocsFileBrowser.apKMbGVf.js +1 -0
  29. package/dist/_astro/{DocsPager.Duf4I68E.js → DocsPager.DMN9-Tjg.js} +1 -1
  30. package/dist/_astro/{DrawerField.BH3p4Q4D.js → DrawerField.CLdvmHc6.js} +1 -1
  31. package/dist/_astro/KnowledgeLibrary.BcoMQeUd.js +1 -0
  32. package/dist/_astro/LifeKrTasksBoard.DJU0-QI-.js +1 -0
  33. package/dist/_astro/LifeKrTodosBoard.GK7KRAO3.js +1 -0
  34. package/dist/_astro/LifeObjectivesBoard.DuKa6Q3k.js +1 -0
  35. package/dist/_astro/LifePlanTypeSelect.Cm2lUmnH.js +1 -0
  36. package/dist/_astro/{LifeReviewsBoard.BPXeVpg1.js → LifeReviewsBoard.BWOOVMtz.js} +3 -3
  37. package/dist/_astro/{LifeShared.tnT7aQON.js → LifeShared.bY2l01Ha.js} +2 -2
  38. package/dist/_astro/LifeStagesBoard.CIzxPOJB.js +1 -0
  39. package/dist/_astro/LifeYearCycleSelect.BlsyPmmI.js +1 -0
  40. package/dist/_astro/LifeYearPlansBoard.DaA9O08j.js +1 -0
  41. package/dist/_astro/MultiSelectDropdown.D-rbpivp.js +1 -0
  42. package/dist/_astro/{NamePromptDialog.Csfnh5eM.js → NamePromptDialog.KPCeXmri.js} +1 -1
  43. package/dist/_astro/NavLibraries.DVR5Ua-S.js +1 -0
  44. package/dist/_astro/PluginsPage.B063QIlQ.js +18 -0
  45. package/dist/_astro/PmBugsBoard.Cu-v0Gfd.js +1 -0
  46. package/dist/_astro/PmIterationsBoard.CgRzkP-j.js +1 -0
  47. package/dist/_astro/{PmProjectDetail.DneFVBpy.js → PmProjectDetail.DVCEh0Lm.js} +1 -1
  48. package/dist/_astro/PmProjectsBoard.z-bQa98r.js +1 -0
  49. package/dist/_astro/PmRequirementsBoard.B0W6bsW2.js +1 -0
  50. package/dist/_astro/PmRequirementsBoard.CyfBI0u_.js +1 -0
  51. package/dist/_astro/PmShared.BQVzwsiz.js +1 -0
  52. package/dist/_astro/ReportsPage.najSzJeT.js +1 -0
  53. package/dist/_astro/ReqAnalysisBoard.BQb8dHFD.js +39 -0
  54. package/dist/_astro/RequirementBreakdownLibrary.Cn6OV6xt.js +2 -0
  55. package/dist/_astro/RequirementsLibrary.CqKNFVsP.js +1 -0
  56. package/dist/_astro/SearchableSelect.DXclLMJI.js +1 -0
  57. package/dist/_astro/SelectDropdown.D7IeyHDI.js +1 -0
  58. package/dist/_astro/SettingsDialog.db3BpFw0.js +1 -0
  59. package/dist/_astro/SlideOverDrawer.BMg2tce6.js +1 -0
  60. package/dist/_astro/SpaceSwitcher.DSUVAPOi.js +7 -0
  61. package/dist/_astro/{TableFieldConfig.C7O-mL-p.js → TableFieldConfig.72AL-8p-.js} +1 -1
  62. package/dist/_astro/{TagSelect.UUXgkMqJ.js → TagSelect.B_r2p0fp.js} +1 -1
  63. package/dist/_astro/TasksBoard.CCDhCSR7.js +1 -0
  64. package/dist/_astro/TemplatesLibrary.peYzrHZ2.js +1 -0
  65. package/dist/_astro/TestReportsLibrary.fWiEyCRx.js +1 -0
  66. package/dist/_astro/TestStatsBoard.BSUBsWSu.js +1 -0
  67. package/dist/_astro/Toast.BydY-X7T.js +1 -0
  68. package/dist/_astro/TodosBoard.By5YdlUe.js +1 -0
  69. package/dist/_astro/UiAutoBoard.BGdlp5Sr.js +3 -0
  70. package/dist/_astro/UiAutoEnvPanel.BUASgPLB.js +10 -0
  71. package/dist/_astro/UiAutoGenerationDialog.D1PyCgrD.js +12 -0
  72. package/dist/_astro/UiAutoProjectsPage.B6A9NlVK.js +3 -0
  73. package/dist/_astro/app-config.Dvfzl5_N.js +1 -0
  74. package/dist/_astro/app-version.CNpnKIb9.js +1 -0
  75. package/dist/_astro/{bash-tools.D9HCzC_7.js → bash-tools.CS2w8LOb.js} +1 -1
  76. package/dist/_astro/business-map.BiJ85oxm.js +1 -0
  77. package/dist/_astro/business-map.DKwdW1VL.css +1 -0
  78. package/dist/_astro/case-gen-run.Cvvdv_kv.js +26 -0
  79. package/dist/_astro/case-prompt.CZ3vWUju.js +2 -0
  80. package/dist/_astro/{case-review.TdDs1WFM.js → case-review.DFWZkoR9.js} +1 -1
  81. package/dist/_astro/{case-template.Cd2xNbgy.js → case-template.Clb7HrDB.js} +1 -1
  82. package/dist/_astro/defect-submit.Dc49lFjm.css +1 -0
  83. package/dist/_astro/defect-workbench.CjTb4FDv.js +6 -0
  84. package/dist/_astro/dialog.XgRGNF_Q.js +1 -0
  85. package/dist/_astro/doc-roots.C-20VD0x.js +1 -0
  86. package/dist/_astro/{hydrate-cache.B15Nrpq0.js → hydrate-cache.O4CIma9y.js} +1 -1
  87. package/dist/_astro/i18n.Cp4so7KR.js +7 -0
  88. package/dist/_astro/{llm.DN5S1KBK.js → llm.BCYNgppW.js} +1 -1
  89. package/dist/_astro/mcp-tools.Kf-lupGn.js +7 -0
  90. package/dist/_astro/{open-docs-in-session.CRiZT022.js → open-docs-in-session.BpcAcBSI.js} +1 -1
  91. package/dist/_astro/plugins.Db9xoFZb.js +1 -0
  92. package/dist/_astro/project-docs.bB9lQ1Ki.js +1 -0
  93. package/dist/_astro/prompts-meta.VAjE4OET.js +2 -0
  94. package/dist/_astro/report-prompt.CwHuOcRN.js +1 -0
  95. package/dist/_astro/req-analysis.C_gARMrB.js +31 -0
  96. package/dist/_astro/requirement-breakdown-library.l0rPd7b3.js +1 -0
  97. package/dist/_astro/{settings.38J2uD5M.js → settings.D02wZj3w.js} +2 -2
  98. package/dist/_astro/space-skills.CPucW8zt.js +1 -0
  99. package/dist/_astro/{spaces-client.DV04tRyD.js → spaces-client.BAtG6PkW.js} +1 -1
  100. package/dist/_astro/story-review.DTN91Vl9.js +7 -0
  101. package/dist/_astro/test-points.C7ZgggQT.js +8 -0
  102. package/dist/_astro/test-reports.0gr6-c_0.js +19 -0
  103. package/dist/_astro/ui-auto-prompt.BmO3ja2m.js +8 -0
  104. package/dist/_astro/{view-prefs.DhdLZjGh.js → view-prefs.COAKEQtZ.js} +1 -1
  105. package/dist/business-map/index.html +983 -0
  106. package/dist/case-exec/index.html +10 -7
  107. package/dist/{prompts → case-execution}/index.html +12 -9
  108. package/dist/cases/generate/index.html +9 -6
  109. package/dist/cases/library/index.html +10 -7
  110. package/dist/dashboard/index.html +10 -7
  111. package/dist/defect-rules/index.html +690 -0
  112. package/dist/defect-submit/index.html +690 -0
  113. package/dist/defect-submit/templates/index.html +690 -0
  114. package/dist/docs/changelog/index.html +265 -51
  115. package/dist/docs/install/index.html +44 -12
  116. package/dist/docs/manual/index.html +213 -75
  117. package/dist/knowledge/index.html +10 -7
  118. package/dist/life/kr-tasks/index.html +10 -7
  119. package/dist/life/kr-todos/index.html +10 -7
  120. package/dist/life/objectives/index.html +10 -7
  121. package/dist/life/reviews/index.html +10 -7
  122. package/dist/life/stages/index.html +10 -7
  123. package/dist/life/year-plans/index.html +10 -7
  124. package/dist/plugins/index.html +10 -7
  125. package/dist/pm/bugs/index.html +10 -7
  126. package/dist/pm/iterations/index.html +10 -7
  127. package/dist/pm/projects/detail/index.html +10 -7
  128. package/dist/pm/projects/index.html +10 -7
  129. package/dist/pm/requirements/index.html +10 -7
  130. package/dist/reports/index.html +10 -7
  131. package/dist/requirement-analysis/index.html +10 -7
  132. package/dist/requirement-breakdowns/index.html +983 -0
  133. package/dist/requirements/index.html +10 -7
  134. package/dist/tasks/index.html +10 -7
  135. package/dist/templates/index.html +10 -7
  136. package/dist/test-automation/index.html +10 -7
  137. package/dist/test-automation/projects/index.html +10 -7
  138. package/dist/test-reports/index.html +10 -7
  139. package/dist/test-stats/index.html +10 -7
  140. package/dist/todos/index.html +10 -7
  141. package/dist/workbench/index.html +9 -6
  142. package/docs/Codex-MCP/351/233/206/346/210/220.md +296 -0
  143. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/204/344/274/260.md +39 -0
  144. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/206/345/210/253/351/207/215/346/236/204/346/226/271/346/241/210.md +88 -0
  145. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +22 -3
  146. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +41 -1
  147. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +63 -17
  148. package/docs//346/217/222/344/273/266/344/273/223/345/272/223/344/270/216/346/212/200/350/203/275/346/225/264/345/220/210/346/226/271/346/241/210.md +187 -0
  149. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +208 -69
  150. package/lh-plugins/business-map/assistant.mjs +958 -0
  151. package/lh-plugins/business-map/auth-paths.mjs +61 -0
  152. package/lh-plugins/business-map/jobs.mjs +749 -0
  153. package/lh-plugins/business-map/login.mjs +295 -0
  154. package/lh-plugins/business-map/sources.mjs +1014 -0
  155. package/lh-plugins/case-execution/files.mjs +777 -0
  156. package/lh-plugins/case-execution/service.mjs +959 -0
  157. package/lh-plugins/case-execution-prompt.mjs +33 -0
  158. package/lh-plugins/lh-business-map.mjs +2431 -0
  159. package/lh-plugins/lh-case-execution.mjs +304 -0
  160. package/lh-plugins/lh-config.mjs +13 -0
  161. package/lh-plugins/lh-defect-submit.mjs +989 -0
  162. package/lh-plugins/lh-project-docs.mjs +31 -140
  163. package/lh-plugins/lh-reports.mjs +29 -57
  164. package/lh-plugins/lh-req-analysis.mjs +32 -3
  165. package/lh-plugins/lh-req-breakdown-library.mjs +1084 -0
  166. package/lh-plugins/lh-uiauto.mjs +514 -22
  167. package/lh-plugins/plugin-prompts.mjs +19 -15
  168. package/lh-plugins/req-analysis-revision.mjs +24 -0
  169. package/lh-plugins/test-points-prompt.mjs +2 -3
  170. package/lh-plugins/uiauto-auth-setup.mjs +218 -0
  171. package/lh-plugins/uiauto-explorer/apps.mjs +13 -2
  172. package/lh-plugins/uiauto-explorer/runner.mjs +15 -2
  173. package/lh-plugins/uiauto-explorer/sessions.mjs +305 -17
  174. package/lh-plugins/uiauto-node.mjs +102 -11
  175. package/lh-plugins/uiauto-prompt.mjs +20 -15
  176. package/lh-plugins/uiauto-sso.mjs +407 -0
  177. package/package.json +5 -2
  178. package/skills/case-execution/SKILL.md +30 -0
  179. package/skills/lantern-defect-submit/SKILL.md +15 -0
  180. package/skills/lantern-workflow/SKILL.md +57 -0
  181. package/skills/office/SKILL.md +26 -0
  182. package/dist/_astro/Base.DIbzr8uT.css +0 -1
  183. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.CPR_CfsE.js +0 -2
  184. package/dist/_astro/CaseExecBoard.DICluCbK.js +0 -1
  185. package/dist/_astro/CaseGenerateApp.CcAtVSQJ.js +0 -10
  186. package/dist/_astro/CasesLibrary.Ci_0hYqL.js +0 -21
  187. package/dist/_astro/ChatApp.DFKZOkZy.js +0 -227
  188. package/dist/_astro/DashboardBoard.Qvf8o4v1.js +0 -5
  189. package/dist/_astro/DocsFileBrowser.DwKBffbM.js +0 -1
  190. package/dist/_astro/KnowledgeLibrary.MDpMqeOd.js +0 -1
  191. package/dist/_astro/LifeKrTasksBoard.DsvW_S66.js +0 -1
  192. package/dist/_astro/LifeKrTodosBoard.D2KTqvg1.js +0 -1
  193. package/dist/_astro/LifeObjectivesBoard.B0cDK934.js +0 -1
  194. package/dist/_astro/LifePlanTypeSelect.BELDvMWU.js +0 -1
  195. package/dist/_astro/LifeStagesBoard.CZftLR9K.js +0 -1
  196. package/dist/_astro/LifeYearCycleSelect.Bw2eRbSm.js +0 -1
  197. package/dist/_astro/LifeYearPlansBoard.DB-RJFEl.js +0 -1
  198. package/dist/_astro/MultiSelectDropdown.CBC7aNOv.js +0 -1
  199. package/dist/_astro/NavLibraries.DdQYsZbe.js +0 -1
  200. package/dist/_astro/OverflowHint.CHZeFfUj.js +0 -1
  201. package/dist/_astro/PluginsPage.BVrMtkLi.js +0 -17
  202. package/dist/_astro/PluginsPage.xdbDGigE.js +0 -1
  203. package/dist/_astro/PmBugsBoard.CGpXUTPu.js +0 -1
  204. package/dist/_astro/PmIterationsBoard.BaKiFIam.js +0 -1
  205. package/dist/_astro/PmProjectsBoard.BxoMF9gK.js +0 -1
  206. package/dist/_astro/PmRequirementsBoard.-SI8VZXI.js +0 -1
  207. package/dist/_astro/PmRequirementsBoard.DsK6RF7Q.js +0 -1
  208. package/dist/_astro/PmShared.BK8kWRSV.js +0 -1
  209. package/dist/_astro/PromptMountDialog.mrTx3U5T.js +0 -1
  210. package/dist/_astro/PromptsLibrary.B2LMGsrj.js +0 -1
  211. package/dist/_astro/ReportsPage.B9lGg1_s.js +0 -16
  212. package/dist/_astro/ReqAnalysisBoard.D-KmRwQM.js +0 -39
  213. package/dist/_astro/RequirementsLibrary.cJc-bnGQ.js +0 -1
  214. package/dist/_astro/SearchableSelect.SyLRS-Jj.js +0 -1
  215. package/dist/_astro/SelectDropdown.T3CKHaLt.js +0 -1
  216. package/dist/_astro/SettingsDialog.C62iJkMt.js +0 -1
  217. package/dist/_astro/SpaceSwitcher.C47_S1g9.js +0 -7
  218. package/dist/_astro/TasksBoard.BUEg2BYk.js +0 -1
  219. package/dist/_astro/TemplatesLibrary.BLVIphXO.js +0 -1
  220. package/dist/_astro/TestReportsLibrary.DVq30Jae.js +0 -1
  221. package/dist/_astro/TestStatsBoard.-5BWQ6bI.js +0 -1
  222. package/dist/_astro/Toast.BO2NFckG.js +0 -1
  223. package/dist/_astro/TodosBoard.DI_lTp2e.js +0 -1
  224. package/dist/_astro/UiAutoBoard.ChFdgv7s.js +0 -2
  225. package/dist/_astro/UiAutoEnvPanel.B50q4kYb.js +0 -19
  226. package/dist/_astro/UiAutoGenerationDialog.CLkFAHrm.js +0 -1
  227. package/dist/_astro/UiAutoProjectsPage.DCsDeN5d.js +0 -3
  228. package/dist/_astro/app-config.DkyjuL-S.js +0 -1
  229. package/dist/_astro/app-version.3eY3FSw1.js +0 -1
  230. package/dist/_astro/case-gen-run.BQeK-XUw.js +0 -22
  231. package/dist/_astro/case-types.DlFkbZJN.js +0 -1
  232. package/dist/_astro/dialog.DZHZCe_T.js +0 -1
  233. package/dist/_astro/doc-roots.CO3IBiY6.js +0 -1
  234. package/dist/_astro/i18n.D_aOCHSN.js +0 -7
  235. package/dist/_astro/markdown-client.BS19nLL3.js +0 -62
  236. package/dist/_astro/plugins.BRvXWHLe.js +0 -1
  237. package/dist/_astro/project-docs.CCjtiFjB.js +0 -1
  238. package/dist/_astro/prompts-meta.BUGutlsk.js +0 -2
  239. package/dist/_astro/report-prompt.B9C4cv84.js +0 -1
  240. package/dist/_astro/req-analysis.FrD6BfwK.js +0 -31
  241. package/dist/_astro/story-review.R8iWiFzl.js +0 -14
  242. package/dist/_astro/test-reports.CuIjlEyK.js +0 -19
  243. package/dist/_astro/ui-auto-prompt.H9_yhau9.js +0 -9
  244. package/dist/_astro/ui-auto.DMv940x4.js +0 -1
@@ -0,0 +1,777 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ import { resolveContentRoot } from '../../builtin/session/space-layout.mjs';
6
+
7
+ const CASE_DIR_NAME = '用例管理';
8
+ const BACKUP_DIR_NAME = '备份列表';
9
+ const DEFECT_URL_HEADER = '缺陷地址';
10
+ const EXECUTION_STATUSES = ['待验证', '通过', '不通过', '阻塞', '跳过'];
11
+
12
+ const ALIASES = {
13
+ no: ['用例编号', '测试用例编号', '案例编号', '用例号', '编号', 'caseid'],
14
+ title: ['用例标题', '用例名称', '测试分项目', '测试项目', '测试点', '标题'],
15
+ precondition: ['前置条件', '预置条件', '前提条件', '准备条件'],
16
+ steps: ['测试步骤', '操作步骤', '执行步骤', '用例步骤', '测试过程'],
17
+ expected: ['预期结果', '期望结果', '预期内容', '期望内容标准', '验收标准'],
18
+ priority: ['优先级', '重要级别', '重要程度'],
19
+ module: ['所属模块', '模块', '测试模块', '功能模块', '测试项目'],
20
+ submodule: ['子模块', '小模块', '功能点'],
21
+ status: ['用例状态', '执行状态', '执行结果', '测试结果'],
22
+ actual: ['实际结果', '实测结果', '执行实际结果'],
23
+ executor: ['执行人', '测试人'],
24
+ executedAt: ['执行时间', '测试时间'],
25
+ evidence: ['执行证据', '截图日志', '证据'],
26
+ defectNo: ['缺陷编号', '缺陷ID', 'BUG编号', 'bug编号'],
27
+ defectUrl: ['缺陷地址', '缺陷链接', '缺陷URL', 'BUG地址', 'bug地址', 'bug链接'],
28
+ };
29
+
30
+ function text(value, max = 4000) {
31
+ return typeof value === 'string' ? value.trim().slice(0, max) : '';
32
+ }
33
+
34
+ function hashBuffer(buffer) {
35
+ return crypto.createHash('sha256').update(buffer).digest('hex');
36
+ }
37
+
38
+ function normalizeHeader(value) {
39
+ return String(value || '')
40
+ .replace(/[((][^))]*[))]/g, '')
41
+ .replace(/[\s**・·::]/g, '')
42
+ .toLowerCase();
43
+ }
44
+
45
+ function fieldMap(headers) {
46
+ const pairs = headers
47
+ .map((header) => ({ raw: String(header || ''), norm: normalizeHeader(header) }))
48
+ .filter((item) => item.raw && item.norm);
49
+ const mapped = {};
50
+ const used = new Set();
51
+ for (const [field, aliases] of Object.entries(ALIASES)) {
52
+ for (const alias of aliases.map(normalizeHeader)) {
53
+ const hit = pairs.find((item) => !used.has(item.raw) && item.norm === alias);
54
+ if (!hit) continue;
55
+ mapped[field] = hit.raw;
56
+ used.add(hit.raw);
57
+ break;
58
+ }
59
+ }
60
+ return mapped;
61
+ }
62
+
63
+ function rowValue(row, map, field) {
64
+ const header = map[field];
65
+ return header ? String(row[header] ?? '') : '';
66
+ }
67
+
68
+ function caseRoot(root) {
69
+ return resolveContentRoot(root, CASE_DIR_NAME).abs;
70
+ }
71
+
72
+ function safeCasePath(root, relativePath) {
73
+ const base = path.resolve(caseRoot(root));
74
+ const abs = path.resolve(base, text(relativePath, 1000));
75
+ if (abs === base || !abs.startsWith(base + path.sep)) {
76
+ throw Object.assign(new Error('用例文件路径越界'), { statusCode: 400 });
77
+ }
78
+ return abs;
79
+ }
80
+
81
+ function ignored(name) {
82
+ return (
83
+ name === '.DS_Store' ||
84
+ name === '.gitkeep' ||
85
+ name.startsWith('~$') ||
86
+ name.startsWith('.~lock.') ||
87
+ /\.bak(?:[-_.].*)?$/i.test(name) ||
88
+ name.endsWith('~')
89
+ );
90
+ }
91
+
92
+ function walkCaseFiles(root, dir = caseRoot(root), relative = '') {
93
+ if (!fs.existsSync(dir)) return [];
94
+ const files = [];
95
+ for (const item of fs.readdirSync(dir, { withFileTypes: true })) {
96
+ if (ignored(item.name)) continue;
97
+ const rel = relative ? `${relative}/${item.name}` : item.name;
98
+ if (item.isDirectory()) {
99
+ if (item.name === BACKUP_DIR_NAME) continue;
100
+ files.push(...walkCaseFiles(root, path.join(dir, item.name), rel));
101
+ continue;
102
+ }
103
+ if (!item.isFile() || !/\.(xlsx|xls|csv|md)$/i.test(item.name)) continue;
104
+ const abs = path.join(dir, item.name);
105
+ const stat = fs.statSync(abs);
106
+ files.push({
107
+ path: rel,
108
+ name: item.name,
109
+ ext: path.extname(item.name).toLowerCase(),
110
+ size: stat.size,
111
+ mtime: stat.mtime.toISOString(),
112
+ });
113
+ }
114
+ return files.sort(
115
+ (left, right) =>
116
+ right.mtime.localeCompare(left.mtime) || left.path.localeCompare(right.path, 'zh'),
117
+ );
118
+ }
119
+
120
+ function decodeCell(value) {
121
+ return String(value ?? '')
122
+ .replace(/<br\s*\/?>/gi, '\n')
123
+ .replace(/&lt;/g, '<')
124
+ .replace(/&gt;/g, '>')
125
+ .replace(/&amp;/g, '&')
126
+ .trim();
127
+ }
128
+
129
+ function splitMarkdownRow(line) {
130
+ return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(decodeCell);
131
+ }
132
+
133
+ function isMarkdownSeparator(line) {
134
+ return /^\s*\|?[\s:|-]+\|?\s*$/.test(line) && /-+/.test(line);
135
+ }
136
+
137
+ function parseMarkdown(raw) {
138
+ const lines = raw.replace(/\r\n/g, '\n').split('\n');
139
+ let headerIndex = -1;
140
+ let headers = [];
141
+ for (let index = 0; index < lines.length; index += 1) {
142
+ if (!lines[index].includes('|')) continue;
143
+ const cells = splitMarkdownRow(lines[index]);
144
+ if (!cells.some((cell) => /用例|测试/.test(cell)) || cells.length < 2) continue;
145
+ headerIndex = index;
146
+ headers = cells;
147
+ break;
148
+ }
149
+ if (headerIndex < 0) {
150
+ throw Object.assign(new Error('没有找到 Markdown 用例表头'), { statusCode: 422 });
151
+ }
152
+ const rows = [];
153
+ let dataStart = headerIndex + (isMarkdownSeparator(lines[headerIndex + 1] || '') ? 2 : 1);
154
+ for (let index = dataStart; index < lines.length; index += 1) {
155
+ const line = lines[index];
156
+ if (!line.includes('|')) break;
157
+ if (isMarkdownSeparator(line)) continue;
158
+ const cells = splitMarkdownRow(line);
159
+ if (!cells.some(Boolean)) continue;
160
+ const row = {};
161
+ headers.forEach((header, column) => {
162
+ if (header) row[header] = cells[column] ?? '';
163
+ });
164
+ rows.push({ row, lineIndex: index });
165
+ }
166
+ return { kind: 'md', lines, headers, rows, headerIndex };
167
+ }
168
+
169
+ function parseCsvRecords(raw) {
170
+ const source = raw.replace(/^\uFEFF/, '');
171
+ const records = [];
172
+ let field = '';
173
+ let record = [];
174
+ let quoted = false;
175
+ for (let index = 0; index < source.length; index += 1) {
176
+ const char = source[index];
177
+ if (quoted) {
178
+ if (char === '"' && source[index + 1] === '"') {
179
+ field += '"';
180
+ index += 1;
181
+ } else if (char === '"') {
182
+ quoted = false;
183
+ } else {
184
+ field += char;
185
+ }
186
+ continue;
187
+ }
188
+ if (char === '"') {
189
+ quoted = true;
190
+ } else if (char === ',') {
191
+ record.push(field);
192
+ field = '';
193
+ } else if (char === '\n' || char === '\r') {
194
+ if (char === '\r' && source[index + 1] === '\n') index += 1;
195
+ record.push(field);
196
+ field = '';
197
+ if (record.some((cell) => cell.trim())) records.push(record);
198
+ record = [];
199
+ } else {
200
+ field += char;
201
+ }
202
+ }
203
+ record.push(field);
204
+ if (record.some((cell) => cell.trim())) records.push(record);
205
+ return records;
206
+ }
207
+
208
+ function parseCsv(raw) {
209
+ const records = parseCsvRecords(raw);
210
+ if (!records.length) throw Object.assign(new Error('CSV 没有表头'), { statusCode: 422 });
211
+ const headers = records[0].map((cell) => String(cell || '').trim());
212
+ const rows = records.slice(1).map((cells, index) => {
213
+ const row = {};
214
+ headers.forEach((header, column) => {
215
+ if (header) row[header] = String(cells[column] ?? '').trim();
216
+ });
217
+ return { row, lineIndex: index + 1 };
218
+ });
219
+ return { kind: 'csv', headers, rows };
220
+ }
221
+
222
+ function headerScore(cells) {
223
+ const headers = cells.map((cell) => String(cell || '').trim()).filter(Boolean);
224
+ const map = fieldMap(headers);
225
+ if (!map.title || !map.steps) return 0;
226
+ return Object.keys(map).length * 10 + (map.expected ? 8 : 0) + (map.no ? 4 : 0);
227
+ }
228
+
229
+ async function parseXlsx(buffer) {
230
+ const mod = await import('xlsx');
231
+ const xlsx = mod.default ?? mod;
232
+ const book = xlsx.read(buffer, { type: 'buffer', cellDates: true });
233
+ let best = null;
234
+ for (const sheetName of book.SheetNames) {
235
+ const sheet = book.Sheets[sheetName];
236
+ if (!sheet) continue;
237
+ const range = sheet['!ref'] ? xlsx.utils.decode_range(sheet['!ref']) : { s: { r: 0 } };
238
+ const table = xlsx.utils.sheet_to_json(sheet, {
239
+ header: 1,
240
+ defval: '',
241
+ raw: false,
242
+ blankrows: true,
243
+ });
244
+ const bonus = /用例|测试/.test(sheetName) ? 20 : 0;
245
+ for (let index = 0; index < Math.min(30, table.length); index += 1) {
246
+ const score = headerScore(table[index] || []) + bonus - index;
247
+ if (score <= 0) continue;
248
+ if (!best || score > best.score) {
249
+ best = {
250
+ score,
251
+ sheetName,
252
+ headerRowIndex: index,
253
+ headers: (table[index] || []).map((cell) => String(cell ?? '').trim()),
254
+ table,
255
+ sheetStartRow: range.s.r,
256
+ };
257
+ }
258
+ }
259
+ }
260
+ if (!best) throw Object.assign(new Error('没有找到 Excel 用例表头'), { statusCode: 422 });
261
+ const rows = [];
262
+ for (let index = best.headerRowIndex + 1; index < best.table.length; index += 1) {
263
+ const cells = best.table[index] || [];
264
+ if (!cells.some((cell) => String(cell ?? '').trim())) continue;
265
+ const row = {};
266
+ best.headers.forEach((header, column) => {
267
+ if (header) row[header] = String(cells[column] ?? '').trim();
268
+ });
269
+ rows.push({
270
+ row,
271
+ dataIndex: index - best.headerRowIndex - 1,
272
+ physicalRow: best.sheetStartRow + index + 1,
273
+ });
274
+ }
275
+ return {
276
+ kind: 'xlsx',
277
+ headers: best.headers.filter(Boolean),
278
+ rawHeaders: best.headers,
279
+ rows,
280
+ sheetName: best.sheetName,
281
+ headerRowIndex: best.headerRowIndex,
282
+ headerRowNumber: best.sheetStartRow + best.headerRowIndex + 1,
283
+ };
284
+ }
285
+
286
+ function rowId(row, map, index) {
287
+ const no = rowValue(row, map, 'no');
288
+ const title = rowValue(row, map, 'title');
289
+ return `${no || index + 1}\0${title}`;
290
+ }
291
+
292
+ function publicRow(parsed, item, index) {
293
+ const map = fieldMap(parsed.headers);
294
+ const row = item.row;
295
+ const status = rowValue(row, map, 'status');
296
+ const actual = rowValue(row, map, 'actual');
297
+ return {
298
+ rowIndex: index,
299
+ id: crypto
300
+ .createHash('sha1')
301
+ .update(rowId(row, map, index))
302
+ .digest('hex')
303
+ .slice(0, 16),
304
+ no: rowValue(row, map, 'no'),
305
+ title: rowValue(row, map, 'title'),
306
+ module: [rowValue(row, map, 'module'), rowValue(row, map, 'submodule')]
307
+ .filter(Boolean)
308
+ .join(' / '),
309
+ priority: rowValue(row, map, 'priority'),
310
+ precondition: rowValue(row, map, 'precondition'),
311
+ steps: rowValue(row, map, 'steps'),
312
+ expected: rowValue(row, map, 'expected'),
313
+ status,
314
+ actual,
315
+ executor: rowValue(row, map, 'executor'),
316
+ executedAt: rowValue(row, map, 'executedAt'),
317
+ evidence: rowValue(row, map, 'evidence'),
318
+ defectNo: rowValue(row, map, 'defectNo'),
319
+ defectUrl: rowValue(row, map, 'defectUrl'),
320
+ fields: parsed.headers
321
+ .filter(Boolean)
322
+ .map((header) => ({ name: String(header), value: String(row[header] ?? '') })),
323
+ };
324
+ }
325
+
326
+ export async function loadCaseDocument(root, relativePath) {
327
+ const abs = safeCasePath(root, relativePath);
328
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
329
+ throw Object.assign(new Error('用例文件不存在'), { statusCode: 404 });
330
+ }
331
+ const buffer = fs.readFileSync(abs);
332
+ const fileHash = hashBuffer(buffer);
333
+ const ext = path.extname(abs).toLowerCase();
334
+ let parsed;
335
+ if (ext === '.xlsx' || ext === '.xls') parsed = await parseXlsx(buffer);
336
+ else if (ext === '.csv') parsed = parseCsv(buffer.toString('utf8'));
337
+ else if (ext === '.md') parsed = parseMarkdown(buffer.toString('utf8'));
338
+ else throw Object.assign(new Error(`不支持 ${ext} 用例文件`), { statusCode: 415 });
339
+ const map = fieldMap(parsed.headers);
340
+ const cases = parsed.rows.map((item, index) => publicRow(parsed, item, index));
341
+ const missingColumns = [!map.status ? '用例状态' : '', !map.actual ? '实际结果' : ''].filter(
342
+ Boolean,
343
+ );
344
+ const executionIssue =
345
+ ext === '.xls'
346
+ ? '旧版 .xls 暂不支持安全写回,请先另存为 .xlsx'
347
+ : missingColumns.length
348
+ ? `缺少执行列:${missingColumns.join('、')}`
349
+ : '';
350
+ return {
351
+ path: relativePath.replaceAll('\\', '/'),
352
+ abs,
353
+ ext,
354
+ fileHash,
355
+ headers: parsed.headers,
356
+ rawHeaders: parsed.rawHeaders || parsed.headers,
357
+ sheetName: parsed.sheetName || '',
358
+ headerRowIndex: parsed.headerRowIndex ?? 0,
359
+ cases,
360
+ columns: {
361
+ expected: map.expected || '',
362
+ priority: map.priority || '',
363
+ status: map.status || '',
364
+ actual: map.actual || '',
365
+ executor: map.executor || '',
366
+ executedAt: map.executedAt || '',
367
+ evidence: map.evidence || '',
368
+ defectNo: map.defectNo || '',
369
+ defectUrl: map.defectUrl || '',
370
+ },
371
+ executable: !executionIssue,
372
+ missingColumns,
373
+ executionIssue,
374
+ statuses: EXECUTION_STATUSES,
375
+ _parsed: parsed,
376
+ _map: map,
377
+ };
378
+ }
379
+
380
+ export async function listCaseDocuments(root) {
381
+ const files = walkCaseFiles(root);
382
+ const documents = [];
383
+ for (const file of files) {
384
+ try {
385
+ const document = await loadCaseDocument(root, file.path);
386
+ documents.push({
387
+ ...file,
388
+ caseCount: document.cases.length,
389
+ executable: document.executable,
390
+ missingColumns: document.missingColumns,
391
+ executionIssue: document.executionIssue,
392
+ });
393
+ } catch (error) {
394
+ documents.push({
395
+ ...file,
396
+ caseCount: 0,
397
+ executable: false,
398
+ missingColumns: [],
399
+ executionIssue: '用例文件解析失败',
400
+ error: error instanceof Error ? error.message : String(error),
401
+ });
402
+ }
403
+ }
404
+ return documents;
405
+ }
406
+
407
+ function stamp(date = new Date()) {
408
+ const pad = (value) => String(value).padStart(2, '0');
409
+ return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
410
+ }
411
+
412
+ export function backupCaseDocument(root, relativePath) {
413
+ const abs = safeCasePath(root, relativePath);
414
+ const backupDir = path.join(caseRoot(root), BACKUP_DIR_NAME);
415
+ fs.mkdirSync(backupDir, { recursive: true });
416
+ const ext = path.extname(abs);
417
+ const base = path.basename(abs, ext);
418
+ let target = path.join(backupDir, `${base}_bak_${stamp()}${ext}`);
419
+ let index = 2;
420
+ while (fs.existsSync(target)) {
421
+ target = path.join(backupDir, `${base}_bak_${stamp()}_${index}${ext}`);
422
+ index += 1;
423
+ }
424
+ fs.copyFileSync(abs, target);
425
+ return path.relative(caseRoot(root), target).replaceAll('\\', '/');
426
+ }
427
+
428
+ function xmlEscape(value) {
429
+ return String(value ?? '')
430
+ .replace(/&/g, '&amp;')
431
+ .replace(/</g, '&lt;')
432
+ .replace(/>/g, '&gt;')
433
+ .replace(/"/g, '&quot;');
434
+ }
435
+
436
+ function columnIndex(ref) {
437
+ const letters = /^[A-Z]+/i.exec(ref)?.[0]?.toUpperCase() || 'A';
438
+ let value = 0;
439
+ for (const char of letters) value = value * 26 + char.charCodeAt(0) - 64;
440
+ return value;
441
+ }
442
+
443
+ function columnName(index) {
444
+ let value = index;
445
+ let out = '';
446
+ while (value > 0) {
447
+ value -= 1;
448
+ out = String.fromCharCode(65 + (value % 26)) + out;
449
+ value = Math.floor(value / 26);
450
+ }
451
+ return out;
452
+ }
453
+
454
+ function replaceCell(rowXml, cellRef, value, styleHint = '') {
455
+ const cellRe = /<c\b[^>]*\/>|<c\b[^>]*>[\s\S]*?<\/c>/g;
456
+ const cells = [...rowXml.matchAll(cellRe)].map((match) => match[0]);
457
+ const wanted = columnIndex(cellRef);
458
+ const existing = cells.find((cell) => {
459
+ const ref = /\br="([A-Z]+\d+)"/i.exec(cell)?.[1] || '';
460
+ return ref.toUpperCase() === cellRef.toUpperCase();
461
+ });
462
+ const style = existing ? /\bs="(\d+)"/.exec(existing)?.[1] : styleHint;
463
+ const nextCell = `<c r="${cellRef}"${style ? ` s="${style}"` : ''} t="inlineStr"><is><t xml:space="preserve">${xmlEscape(value)}</t></is></c>`;
464
+ const without = cells.filter((cell) => cell !== existing);
465
+ without.push(nextCell);
466
+ without.sort((left, right) => {
467
+ const leftRef = /\br="([A-Z]+\d+)"/i.exec(left)?.[1] || 'A1';
468
+ const rightRef = /\br="([A-Z]+\d+)"/i.exec(right)?.[1] || 'A1';
469
+ return columnIndex(leftRef) - columnIndex(rightRef);
470
+ });
471
+ const outer = rowXml.replace(cellRe, '').replace(/<\/row>$/i, '');
472
+ return `${outer}${without.join('')}</row>`;
473
+ }
474
+
475
+ async function patchXlsx(abs, parsed, rowIndex, updates) {
476
+ const { default: JSZip } = await import('jszip');
477
+ const zip = await JSZip.loadAsync(fs.readFileSync(abs));
478
+ const workbook = await zip.file('xl/workbook.xml')?.async('string');
479
+ const rels = await zip.file('xl/_rels/workbook.xml.rels')?.async('string');
480
+ if (!workbook || !rels) throw new Error('Excel 工作簿结构不完整');
481
+ const safeName = parsed.sheetName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
482
+ const sheetTag = new RegExp(`<sheet\\b[^>]*name="${safeName}"[^>]*>`, 'i').exec(workbook)?.[0];
483
+ const relationId = sheetTag ? /\br:id="([^"]+)"/i.exec(sheetTag)?.[1] : '';
484
+ const relationTag = relationId
485
+ ? new RegExp(`<Relationship\\b[^>]*Id="${relationId}"[^>]*>`, 'i').exec(rels)?.[0]
486
+ : '';
487
+ const target = relationTag ? /\bTarget="([^"]+)"/i.exec(relationTag)?.[1] || '' : '';
488
+ if (!target) throw new Error(`找不到工作表 ${parsed.sheetName}`);
489
+ const sheetPath = target.startsWith('/')
490
+ ? target.slice(1)
491
+ : path.posix.normalize(`xl/${target.replace(/^\.\//, '')}`);
492
+ const file = zip.file(sheetPath);
493
+ if (!file) throw new Error('找不到工作表 XML');
494
+ let xml = await file.async('string');
495
+ const physicalRow = parsed.rows[rowIndex]?.physicalRow;
496
+ if (!Number.isInteger(physicalRow) || physicalRow < 1) {
497
+ throw new Error('找不到要写回的 Excel 用例行');
498
+ }
499
+ const rowRe = new RegExp(`<row\\b[^>]*\\br="${physicalRow}"[^>]*>[\\s\\S]*?<\\/row>`, 'i');
500
+ let rowXml = rowRe.exec(xml)?.[0] || '';
501
+ if (!rowXml) throw new Error(`找不到第 ${physicalRow} 行`);
502
+ for (const update of updates) {
503
+ const rawHeaders = parsed.rawHeaders || parsed.headers;
504
+ const column = rawHeaders.indexOf(update.header) + 1;
505
+ if (column <= 0) continue;
506
+ rowXml = replaceCell(rowXml, `${columnName(column)}${physicalRow}`, update.value);
507
+ }
508
+ xml = xml.replace(rowRe, rowXml);
509
+ zip.file(sheetPath, xml);
510
+ const output = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
511
+ const temp = `${abs}.${process.pid}.${Date.now()}.tmp`;
512
+ fs.writeFileSync(temp, output);
513
+ fs.renameSync(temp, abs);
514
+ }
515
+
516
+ function markdownCell(value) {
517
+ return String(value ?? '')
518
+ .replace(/\|/g, '\\|')
519
+ .replace(/\n/g, '<br>');
520
+ }
521
+
522
+ function csvCell(value) {
523
+ const raw = String(value ?? '');
524
+ return /[",\n\r]/.test(raw) ? `"${raw.replace(/"/g, '""')}"` : raw;
525
+ }
526
+
527
+ function writeTextAtomic(abs, value) {
528
+ const temp = `${abs}.${process.pid}.${Date.now()}.tmp`;
529
+ fs.writeFileSync(temp, value, 'utf8');
530
+ fs.renameSync(temp, abs);
531
+ }
532
+
533
+ function patchText(abs, ext, parsed, rowIndex, updates) {
534
+ const raw = fs.readFileSync(abs, 'utf8');
535
+ if (ext === '.csv') {
536
+ const records = parseCsvRecords(raw);
537
+ const header = records[0] || [];
538
+ const row = records[rowIndex + 1] || [];
539
+ for (const update of updates) {
540
+ const column = header.indexOf(update.header);
541
+ if (column < 0) continue;
542
+ while (row.length <= column) row.push('');
543
+ row[column] = update.value;
544
+ }
545
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
546
+ const body = records.map((cells) => cells.map(csvCell).join(',')).join(eol);
547
+ writeTextAtomic(abs, `${raw.startsWith('\uFEFF') ? '\uFEFF' : ''}${body}${eol}`);
548
+ return;
549
+ }
550
+ const lines = raw.replace(/\r\n/g, '\n').split('\n');
551
+ const target = parsed.rows[rowIndex]?.lineIndex;
552
+ if (!Number.isInteger(target) || target < 0 || target >= lines.length) {
553
+ throw new Error('找不到要写回的 Markdown 用例行');
554
+ }
555
+ const cells = splitMarkdownRow(lines[target]);
556
+ for (const update of updates) {
557
+ const column = parsed.headers.indexOf(update.header);
558
+ if (column < 0) continue;
559
+ while (cells.length <= column) cells.push('');
560
+ cells[column] = update.value;
561
+ }
562
+ lines[target] = `| ${cells.map(markdownCell).join(' | ')} |`;
563
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
564
+ writeTextAtomic(abs, lines.join(eol));
565
+ }
566
+
567
+ async function appendXlsxHeader(abs, parsed, header) {
568
+ const { default: JSZip } = await import('jszip');
569
+ const zip = await JSZip.loadAsync(fs.readFileSync(abs));
570
+ const workbook = await zip.file('xl/workbook.xml')?.async('string');
571
+ const rels = await zip.file('xl/_rels/workbook.xml.rels')?.async('string');
572
+ if (!workbook || !rels) throw new Error('Excel 工作簿结构不完整');
573
+ const safeName = parsed.sheetName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
574
+ const sheetTag = new RegExp(`<sheet\\b[^>]*name="${safeName}"[^>]*>`, 'i').exec(workbook)?.[0];
575
+ const relationId = sheetTag ? /\br:id="([^"]+)"/i.exec(sheetTag)?.[1] : '';
576
+ const relationTag = relationId
577
+ ? new RegExp(`<Relationship\\b[^>]*Id="${relationId}"[^>]*>`, 'i').exec(rels)?.[0]
578
+ : '';
579
+ const target = relationTag ? /\bTarget="([^"]+)"/i.exec(relationTag)?.[1] || '' : '';
580
+ if (!target) throw new Error(`找不到工作表 ${parsed.sheetName}`);
581
+ const sheetPath = target.startsWith('/')
582
+ ? target.slice(1)
583
+ : path.posix.normalize(`xl/${target.replace(/^\.\//, '')}`);
584
+ const file = zip.file(sheetPath);
585
+ if (!file) throw new Error('找不到工作表 XML');
586
+ let xml = await file.async('string');
587
+ const physicalRow = parsed.headerRowNumber;
588
+ const rowRe = new RegExp(`<row\\b[^>]*\\br="${physicalRow}"[^>]*>[\\s\\S]*?<\\/row>`, 'i');
589
+ let rowXml = rowRe.exec(xml)?.[0] || '';
590
+ if (!rowXml) throw new Error(`找不到第 ${physicalRow} 行表头`);
591
+ const cells = [...rowXml.matchAll(/<c\b[^>]*\/>|<c\b[^>]*>[\s\S]*?<\/c>/g)].map(
592
+ (match) => match[0],
593
+ );
594
+ const styleHint = cells
595
+ .map((cell) => /\bs="(\d+)"/.exec(cell)?.[1] || '')
596
+ .filter(Boolean)
597
+ .at(-1);
598
+ const column = parsed.rawHeaders.length + 1;
599
+ rowXml = replaceCell(rowXml, `${columnName(column)}${physicalRow}`, header, styleHint || '');
600
+ xml = xml.replace(rowRe, rowXml);
601
+ xml = xml.replace(/<dimension\b[^>]*\bref="([^"]+)"[^>]*\/>/i, (tag, ref) => {
602
+ const start = ref.split(':')[0] || 'A1';
603
+ const endRow = /(\d+)$/.exec(ref)?.[1] || String(physicalRow);
604
+ return tag.replace(ref, `${start}:${columnName(column)}${endRow}`);
605
+ });
606
+ zip.file(sheetPath, xml);
607
+ const output = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
608
+ const temp = `${abs}.${process.pid}.${Date.now()}.tmp`;
609
+ fs.writeFileSync(temp, output);
610
+ fs.renameSync(temp, abs);
611
+ parsed.headers.push(header);
612
+ parsed.rawHeaders.push(header);
613
+ }
614
+
615
+ function appendTextHeader(abs, ext, parsed, header) {
616
+ const raw = fs.readFileSync(abs, 'utf8');
617
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
618
+ if (ext === '.csv') {
619
+ const records = parseCsvRecords(raw);
620
+ if (!records.length) throw new Error('CSV 没有表头');
621
+ records[0].push(header);
622
+ for (const row of records.slice(1)) row.push('');
623
+ const body = records.map((cells) => cells.map(csvCell).join(',')).join(eol);
624
+ writeTextAtomic(abs, `${raw.startsWith('\uFEFF') ? '\uFEFF' : ''}${body}${eol}`);
625
+ } else {
626
+ const lines = raw.replace(/\r\n/g, '\n').split('\n');
627
+ const headerIndex = parsed.headerIndex;
628
+ if (!Number.isInteger(headerIndex) || headerIndex < 0) throw new Error('找不到 Markdown 表头');
629
+ const appendToMarkdownLine = (lineIndex, value) => {
630
+ const cells = splitMarkdownRow(lines[lineIndex]);
631
+ cells.push(value);
632
+ lines[lineIndex] = `| ${cells.map(markdownCell).join(' | ')} |`;
633
+ };
634
+ appendToMarkdownLine(headerIndex, header);
635
+ if (isMarkdownSeparator(lines[headerIndex + 1] || '')) {
636
+ appendToMarkdownLine(headerIndex + 1, '---');
637
+ }
638
+ for (const row of parsed.rows) appendToMarkdownLine(row.lineIndex, '');
639
+ writeTextAtomic(abs, lines.join(eol));
640
+ }
641
+ parsed.headers.push(header);
642
+ }
643
+
644
+ async function appendCaseHeader(document, header) {
645
+ if (document.ext === '.xlsx') {
646
+ await appendXlsxHeader(document.abs, document._parsed, header);
647
+ } else if (document.ext === '.csv' || document.ext === '.md') {
648
+ appendTextHeader(document.abs, document.ext, document._parsed, header);
649
+ } else {
650
+ throw Object.assign(new Error('当前文件格式无法新增字段'), { statusCode: 415 });
651
+ }
652
+ }
653
+
654
+ export async function applyCaseExecutionResult(
655
+ root,
656
+ {
657
+ path: relativePath,
658
+ expectedFileHash,
659
+ rowIndex,
660
+ status,
661
+ actualResult,
662
+ executor = '',
663
+ executedAt = '',
664
+ evidence = '',
665
+ defectNo = '',
666
+ },
667
+ ) {
668
+ let document = await loadCaseDocument(root, relativePath);
669
+ if (document.ext === '.xls') {
670
+ throw Object.assign(new Error(document.executionIssue), { statusCode: 415 });
671
+ }
672
+ if (!document.executable) {
673
+ throw Object.assign(new Error(document.executionIssue), {
674
+ statusCode: 422,
675
+ });
676
+ }
677
+ if (expectedFileHash !== document.fileHash) {
678
+ throw Object.assign(new Error('用例文件已被外部修改,请重新执行后再写回'), {
679
+ statusCode: 409,
680
+ currentHash: document.fileHash,
681
+ });
682
+ }
683
+ const selectedStatus = text(status, 20);
684
+ if (!EXECUTION_STATUSES.includes(selectedStatus)) {
685
+ throw Object.assign(new Error('用例状态无效'), { statusCode: 400 });
686
+ }
687
+ if (!Number.isInteger(rowIndex) || rowIndex < 0 || rowIndex >= document.cases.length) {
688
+ throw Object.assign(new Error('用例行不存在'), { statusCode: 404 });
689
+ }
690
+ const map = document._map;
691
+ const updates = [
692
+ { header: map.status, value: selectedStatus },
693
+ { header: map.actual, value: text(actualResult, 30000) },
694
+ ...(map.executor ? [{ header: map.executor, value: text(executor, 200) }] : []),
695
+ ...(map.executedAt ? [{ header: map.executedAt, value: text(executedAt, 80) }] : []),
696
+ ...(map.evidence ? [{ header: map.evidence, value: text(evidence, 4000) }] : []),
697
+ ...(map.defectNo ? [{ header: map.defectNo, value: text(defectNo, 200) }] : []),
698
+ ].filter((item) => item.header);
699
+ const backup = backupCaseDocument(root, relativePath);
700
+ if (document.ext === '.xlsx') {
701
+ await patchXlsx(document.abs, document._parsed, rowIndex, updates);
702
+ } else if (document.ext === '.csv' || document.ext === '.md') {
703
+ patchText(document.abs, document.ext, document._parsed, rowIndex, updates);
704
+ } else {
705
+ throw Object.assign(new Error('旧版 .xls 暂不支持写回,请先另存为 .xlsx'), {
706
+ statusCode: 415,
707
+ });
708
+ }
709
+ return {
710
+ ok: true,
711
+ path: relativePath,
712
+ rowIndex,
713
+ status: selectedStatus,
714
+ backup,
715
+ fileHash: hashBuffer(fs.readFileSync(document.abs)),
716
+ };
717
+ }
718
+
719
+ export async function applyCaseFieldUpdates(
720
+ root,
721
+ { path: relativePath, expectedFileHash, rowIndex, updates },
722
+ ) {
723
+ let document = await loadCaseDocument(root, relativePath);
724
+ if (document.ext === '.xls') {
725
+ throw Object.assign(new Error(document.executionIssue), { statusCode: 415 });
726
+ }
727
+ if (expectedFileHash !== document.fileHash) {
728
+ throw Object.assign(new Error('用例文件已被外部修改,请重新读取后再保存'), {
729
+ statusCode: 409,
730
+ currentHash: document.fileHash,
731
+ });
732
+ }
733
+ if (!Number.isInteger(rowIndex) || rowIndex < 0 || rowIndex >= document.cases.length) {
734
+ throw Object.assign(new Error('用例行不存在'), { statusCode: 404 });
735
+ }
736
+ const normalized = (Array.isArray(updates) ? updates : [])
737
+ .slice(0, 100)
738
+ .map((update) => ({
739
+ header: text(update?.header, 500),
740
+ value: String(update?.value ?? '').slice(0, 30000),
741
+ }))
742
+ .filter((update) => update.header);
743
+ if (!normalized.length) {
744
+ throw Object.assign(new Error('没有需要保存的字段'), { statusCode: 400 });
745
+ }
746
+ let allowed = new Set(document.headers.map((header) => String(header)));
747
+ const unknown = normalized.filter((update) => !allowed.has(update.header));
748
+ if (unknown.some((update) => update.header !== DEFECT_URL_HEADER)) {
749
+ const first = unknown.find((update) => update.header !== DEFECT_URL_HEADER);
750
+ throw Object.assign(new Error(`用例文件不存在字段:${first?.header || ''}`), {
751
+ statusCode: 400,
752
+ });
753
+ }
754
+ const backup = backupCaseDocument(root, relativePath);
755
+ if (unknown.length) {
756
+ await appendCaseHeader(document, DEFECT_URL_HEADER);
757
+ document = await loadCaseDocument(root, relativePath);
758
+ allowed = new Set(document.headers.map((header) => String(header)));
759
+ if (!allowed.has(DEFECT_URL_HEADER)) {
760
+ throw new Error('缺陷地址字段追加失败');
761
+ }
762
+ }
763
+ if (document.ext === '.xlsx') {
764
+ await patchXlsx(document.abs, document._parsed, rowIndex, normalized);
765
+ } else {
766
+ patchText(document.abs, document.ext, document._parsed, rowIndex, normalized);
767
+ }
768
+ return {
769
+ ok: true,
770
+ path: relativePath,
771
+ rowIndex,
772
+ backup,
773
+ fileHash: hashBuffer(fs.readFileSync(document.abs)),
774
+ };
775
+ }
776
+
777
+ export { EXECUTION_STATUSES };