lantern-harness 0.1.45 → 0.2.3
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/CHANGELOG.md +242 -0
- package/README.md +25 -8
- package/builtin/case-backup-contract.mjs +27 -0
- package/builtin/case-workflow-contract.mjs +158 -0
- package/builtin/session/lh-fs.mjs +93 -4
- package/builtin/session/lh-nav-groups.mjs +36 -1
- package/builtin/session/mcp-client.mjs +7 -3
- package/builtin/session/session-runs.mjs +5 -1
- package/builtin/session/skill-validation.mjs +72 -0
- package/builtin/session/space-layout.mjs +8 -1
- package/builtin/session/space-skills.mjs +758 -0
- package/cli/data-root.mjs +21 -4
- package/cli/lantern.mjs +26 -1
- package/cli/mcp-server.mjs +3733 -0
- package/cli/server.mjs +10 -2
- package/config/app.defaults.json +4 -2
- package/dist/500.html +14 -6
- package/dist/_astro/Base.BQf1tZMl.css +1 -0
- package/dist/_astro/Base.astro_astro_type_script_index_0_lang.Dm3O_y-S.js +2 -0
- package/dist/_astro/BusinessMapBoard.CYxHcku_.js +5 -0
- package/dist/_astro/CaseExecBoard.CK9aGPmH.js +1 -0
- package/dist/_astro/CaseExecutionBoard.C94pmIMQ.js +5 -0
- package/dist/_astro/CaseGenerateApp.D5xlk9At.js +10 -0
- package/dist/_astro/CasesLibrary.BHQC955x.js +21 -0
- package/dist/_astro/ChatApp.CIt15w_1.js +1 -0
- package/dist/_astro/ChatApp.d4a9R3YS.js +262 -0
- package/dist/_astro/{ConfirmDialog.DrrPf1MB.js → ConfirmDialog.DQFd6g2r.js} +1 -1
- package/dist/_astro/DashboardBoard.qgc1s7pG.js +5 -0
- package/dist/_astro/{DatePicker.Bkl71M49.js → DatePicker.BRO_CjVQ.js} +1 -1
- package/dist/_astro/DefectSubmitEntry.JI85N1-i.js +2 -0
- package/dist/_astro/DocsFileBrowser.z5JZ74cy.js +1 -0
- package/dist/_astro/{DocsPager.Duf4I68E.js → DocsPager.Dg765uHW.js} +1 -1
- package/dist/_astro/{DrawerField.BH3p4Q4D.js → DrawerField.CLdvmHc6.js} +1 -1
- package/dist/_astro/KnowledgeLibrary.mkShtVun.js +1 -0
- package/dist/_astro/LifeKrTasksBoard.DpAwQffE.js +1 -0
- package/dist/_astro/LifeKrTodosBoard.BIjPiZ8H.js +1 -0
- package/dist/_astro/LifeObjectivesBoard.DYwLHPEG.js +1 -0
- package/dist/_astro/LifePlanTypeSelect.CYaziESp.js +1 -0
- package/dist/_astro/{LifeReviewsBoard.BPXeVpg1.js → LifeReviewsBoard.DIxoWBDA.js} +3 -3
- package/dist/_astro/{LifeShared.tnT7aQON.js → LifeShared.DuFQsMEx.js} +2 -2
- package/dist/_astro/LifeStagesBoard.DtOri9EW.js +1 -0
- package/dist/_astro/LifeYearCycleSelect.ByJ9-PGg.js +1 -0
- package/dist/_astro/LifeYearPlansBoard.BQN07wcv.js +1 -0
- package/dist/_astro/MultiSelectDropdown.D-rbpivp.js +1 -0
- package/dist/_astro/{NamePromptDialog.Csfnh5eM.js → NamePromptDialog.KPCeXmri.js} +1 -1
- package/dist/_astro/NavLibraries.BO4ezcUc.js +1 -0
- package/dist/_astro/PluginsPage.B1VeDtLx.js +18 -0
- package/dist/_astro/PmBugsBoard.Ddl3kqqt.js +1 -0
- package/dist/_astro/PmIterationsBoard.BJN7disI.js +1 -0
- package/dist/_astro/{PmProjectDetail.DneFVBpy.js → PmProjectDetail.D78gWhqk.js} +1 -1
- package/dist/_astro/PmProjectsBoard.Bf8VB3t6.js +1 -0
- package/dist/_astro/PmRequirementsBoard.CDyNHN2a.js +1 -0
- package/dist/_astro/PmRequirementsBoard.DarfGIrL.js +1 -0
- package/dist/_astro/PmShared.TOjBbtV8.js +1 -0
- package/dist/_astro/ReportsPage.BXGduuY3.js +1 -0
- package/dist/_astro/ReqAnalysisBoard.WLtIfBg8.js +39 -0
- package/dist/_astro/RequirementBreakdownLibrary.DMoeTeqX.js +2 -0
- package/dist/_astro/RequirementsLibrary.Iv7zOqWe.js +1 -0
- package/dist/_astro/SearchableSelect.DXclLMJI.js +1 -0
- package/dist/_astro/SelectDropdown.D7IeyHDI.js +1 -0
- package/dist/_astro/SettingsDialog.BvDU9EU6.js +1 -0
- package/dist/_astro/SlideOverDrawer.CvyB-quk.js +1 -0
- package/dist/_astro/SpaceSwitcher.D9bBNQBZ.js +7 -0
- package/dist/_astro/{TableFieldConfig.C7O-mL-p.js → TableFieldConfig.DHj25OKN.js} +1 -1
- package/dist/_astro/{TagSelect.UUXgkMqJ.js → TagSelect.B_r2p0fp.js} +1 -1
- package/dist/_astro/TasksBoard.CXmGdylV.js +1 -0
- package/dist/_astro/TemplatesLibrary.DsL2q-wp.js +1 -0
- package/dist/_astro/TestReportsLibrary.BBC1TYgP.js +1 -0
- package/dist/_astro/TestStatsBoard.VXjP4hu6.js +1 -0
- package/dist/_astro/Toast.BydY-X7T.js +1 -0
- package/dist/_astro/TodosBoard.-yKgp06M.js +1 -0
- package/dist/_astro/UiAutoBoard.BD5ZyLHj.js +3 -0
- package/dist/_astro/UiAutoEnvPanel.DrHUOlmH.js +10 -0
- package/dist/_astro/UiAutoGenerationDialog.gypq1zP9.js +12 -0
- package/dist/_astro/UiAutoProjectsPage.Dhzr09E9.js +3 -0
- package/dist/_astro/app-config.BSO5r82v.js +1 -0
- package/dist/_astro/app-version.CkDFkv4s.js +1 -0
- package/dist/_astro/{bash-tools.D9HCzC_7.js → bash-tools.C4DJiRJs.js} +1 -1
- package/dist/_astro/business-map.BiJ85oxm.js +1 -0
- package/dist/_astro/business-map.DKwdW1VL.css +1 -0
- package/dist/_astro/case-fields.C03NY3zC.js +148 -0
- package/dist/_astro/case-gen-run.C4p8uyU3.js +26 -0
- package/dist/_astro/case-prompt.ByLTgz4r.js +2 -0
- package/dist/_astro/{case-review.TdDs1WFM.js → case-review.BodP2jKm.js} +2 -2
- package/dist/_astro/{case-template.Cd2xNbgy.js → case-template.CC2eXegU.js} +2 -2
- package/dist/_astro/case-types.BjF1BivA.js +1 -0
- package/dist/_astro/case-workflow-contract.BBQ9bbKL.js +1 -0
- package/dist/_astro/defect-submit.Dc49lFjm.css +1 -0
- package/dist/_astro/defect-workbench.DBmohR-y.js +6 -0
- package/dist/_astro/dialog.XgRGNF_Q.js +1 -0
- package/dist/_astro/doc-roots.C-20VD0x.js +1 -0
- package/dist/_astro/{hydrate-cache.B15Nrpq0.js → hydrate-cache.CMMErx63.js} +1 -1
- package/dist/_astro/i18n.CEWjL5GX.js +7 -0
- package/dist/_astro/{llm.DN5S1KBK.js → llm.BCYNgppW.js} +1 -1
- package/dist/_astro/mcp-tools.Kf-lupGn.js +7 -0
- package/dist/_astro/{open-docs-in-session.CRiZT022.js → open-docs-in-session.BoyV6R2A.js} +1 -1
- package/dist/_astro/plugins.ChGmBEkF.js +1 -0
- package/dist/_astro/project-docs.BRgNjXhG.js +1 -0
- package/dist/_astro/prompts-meta.VAjE4OET.js +2 -0
- package/dist/_astro/report-prompt.CwHuOcRN.js +1 -0
- package/dist/_astro/req-analysis.BLvcktvQ.js +31 -0
- package/dist/_astro/requirement-breakdown-library.l0rPd7b3.js +1 -0
- package/dist/_astro/{settings.38J2uD5M.js → settings.BojKNwUC.js} +2 -2
- package/dist/_astro/space-skills.CPucW8zt.js +1 -0
- package/dist/_astro/{spaces-client.DV04tRyD.js → spaces-client.B28rzu8J.js} +1 -1
- package/dist/_astro/story-review.dEBWTeOW.js +7 -0
- package/dist/_astro/test-points.BuNgdNcU.js +8 -0
- package/dist/_astro/test-reports.0gr6-c_0.js +19 -0
- package/dist/_astro/ui-auto-prompt.BmO3ja2m.js +8 -0
- package/dist/_astro/ui-auto.LUcREUMe.js +1 -0
- package/dist/_astro/{view-prefs.DhdLZjGh.js → view-prefs.CWc5cQ2q.js} +1 -1
- package/dist/business-map/index.html +988 -0
- package/dist/case-exec/index.html +15 -7
- package/dist/{prompts → case-execution}/index.html +17 -9
- package/dist/cases/api/index.html +988 -0
- package/dist/cases/automation/index.html +988 -0
- package/dist/cases/functional/index.html +988 -0
- package/dist/cases/generate/index.html +14 -6
- package/dist/cases/index.html +1 -1
- package/dist/cases/library/index.html +1 -980
- package/dist/cases/other/index.html +988 -0
- package/dist/cases/performance/index.html +988 -0
- package/dist/dashboard/index.html +15 -7
- package/dist/defect-rules/index.html +695 -0
- package/dist/defect-submit/index.html +695 -0
- package/dist/defect-submit/templates/index.html +695 -0
- package/dist/docs/changelog/index.html +289 -52
- package/dist/docs/install/index.html +50 -12
- package/dist/docs/manual/index.html +230 -82
- package/dist/knowledge/index.html +15 -7
- package/dist/life/kr-tasks/index.html +15 -7
- package/dist/life/kr-todos/index.html +15 -7
- package/dist/life/objectives/index.html +15 -7
- package/dist/life/reviews/index.html +15 -7
- package/dist/life/stages/index.html +15 -7
- package/dist/life/year-plans/index.html +15 -7
- package/dist/plugins/index.html +15 -7
- package/dist/pm/bugs/index.html +15 -7
- package/dist/pm/iterations/index.html +15 -7
- package/dist/pm/projects/detail/index.html +15 -7
- package/dist/pm/projects/index.html +15 -7
- package/dist/pm/requirements/index.html +15 -7
- package/dist/reports/index.html +15 -7
- package/dist/requirement-analysis/index.html +15 -7
- package/dist/requirement-breakdowns/index.html +988 -0
- package/dist/requirements/index.html +15 -7
- package/dist/tasks/index.html +15 -7
- package/dist/templates/index.html +15 -7
- package/dist/test-automation/index.html +15 -7
- package/dist/test-automation/projects/index.html +15 -7
- package/dist/test-reports/index.html +15 -7
- package/dist/test-stats/index.html +15 -7
- package/dist/todos/index.html +15 -7
- package/dist/workbench/index.html +14 -6
- package/docs/Codex-MCP/351/233/206/346/210/220.md +340 -0
- package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/204/344/274/260.md +39 -0
- 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
- package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +28 -3
- package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +41 -1
- package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +65 -17
- 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
- package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +219 -74
- package/lh-plugins/business-map/assistant.mjs +958 -0
- package/lh-plugins/business-map/auth-paths.mjs +61 -0
- package/lh-plugins/business-map/jobs.mjs +749 -0
- package/lh-plugins/business-map/login.mjs +295 -0
- package/lh-plugins/business-map/sources.mjs +1014 -0
- package/lh-plugins/case-automation/service.mjs +921 -0
- package/lh-plugins/case-automation/store.mjs +231 -0
- package/lh-plugins/case-automation/tables.mjs +115 -0
- package/lh-plugins/case-automation-prompt.mjs +57 -0
- package/lh-plugins/case-execution/assets.mjs +180 -0
- package/lh-plugins/case-execution/files.mjs +829 -0
- package/lh-plugins/case-execution/plans.mjs +318 -0
- package/lh-plugins/case-execution/service.mjs +1026 -0
- package/lh-plugins/case-execution-prompt.mjs +36 -0
- package/lh-plugins/lh-business-map.mjs +2431 -0
- package/lh-plugins/lh-case-automation.mjs +169 -0
- package/lh-plugins/lh-case-design.mjs +456 -0
- package/lh-plugins/lh-case-execution.mjs +356 -0
- package/lh-plugins/lh-case-review.mjs +29 -11
- package/lh-plugins/lh-config.mjs +13 -0
- package/lh-plugins/lh-defect-submit.mjs +989 -0
- package/lh-plugins/lh-project-docs.mjs +55 -140
- package/lh-plugins/lh-reports.mjs +29 -57
- package/lh-plugins/lh-req-analysis.mjs +32 -3
- package/lh-plugins/lh-req-breakdown-library.mjs +1084 -0
- package/lh-plugins/lh-uiauto.mjs +625 -24
- package/lh-plugins/plugin-prompts.mjs +20 -15
- package/lh-plugins/req-analysis-revision.mjs +24 -0
- package/lh-plugins/test-points-prompt.mjs +2 -3
- package/lh-plugins/uiauto-adapters/playwright.mjs +44 -4
- package/lh-plugins/uiauto-adapters/shared.mjs +4 -0
- package/lh-plugins/uiauto-auth-setup.mjs +218 -0
- package/lh-plugins/uiauto-explorer/apps.mjs +13 -2
- package/lh-plugins/uiauto-explorer/emit-files.mjs +16 -2
- package/lh-plugins/uiauto-explorer/ir.mjs +3 -0
- package/lh-plugins/uiauto-explorer/merge.mjs +37 -1
- package/lh-plugins/uiauto-explorer/navigation-guard.mjs +255 -0
- package/lh-plugins/uiauto-explorer/runner.mjs +80 -5
- package/lh-plugins/uiauto-explorer/sessions.mjs +334 -18
- package/lh-plugins/uiauto-node.mjs +102 -11
- package/lh-plugins/uiauto-prompt.mjs +20 -15
- package/lh-plugins/uiauto-sso.mjs +407 -0
- package/package.json +5 -2
- package/skills/case-automation-bridge/SKILL.md +27 -0
- package/skills/case-execution/SKILL.md +41 -0
- package/skills/lantern-defect-submit/SKILL.md +15 -0
- package/skills/lantern-workflow/SKILL.md +95 -0
- package/skills/office/SKILL.md +26 -0
- package/dist/_astro/Base.Bkt1lrgu.css +0 -1
- package/dist/_astro/Base.astro_astro_type_script_index_0_lang.UKTVQqk7.js +0 -2
- package/dist/_astro/CaseExecBoard.DICluCbK.js +0 -1
- package/dist/_astro/CaseGenerateApp.Be3h5XPG.js +0 -10
- package/dist/_astro/CasesLibrary.Buys7Cy-.js +0 -21
- package/dist/_astro/ChatApp.D3BheKci.js +0 -227
- package/dist/_astro/DashboardBoard.Qvf8o4v1.js +0 -5
- package/dist/_astro/DocsFileBrowser.DwKBffbM.js +0 -1
- package/dist/_astro/KnowledgeLibrary.MDpMqeOd.js +0 -1
- package/dist/_astro/LifeKrTasksBoard.DsvW_S66.js +0 -1
- package/dist/_astro/LifeKrTodosBoard.D2KTqvg1.js +0 -1
- package/dist/_astro/LifeObjectivesBoard.B0cDK934.js +0 -1
- package/dist/_astro/LifePlanTypeSelect.BELDvMWU.js +0 -1
- package/dist/_astro/LifeStagesBoard.CZftLR9K.js +0 -1
- package/dist/_astro/LifeYearCycleSelect.Bw2eRbSm.js +0 -1
- package/dist/_astro/LifeYearPlansBoard.DB-RJFEl.js +0 -1
- package/dist/_astro/MultiSelectDropdown.CBC7aNOv.js +0 -1
- package/dist/_astro/NavLibraries.DdQYsZbe.js +0 -1
- package/dist/_astro/OverflowHint.CHZeFfUj.js +0 -1
- package/dist/_astro/PluginsPage.C1JnInH4.js +0 -17
- package/dist/_astro/PluginsPage.C3eEwy3K.js +0 -1
- package/dist/_astro/PmBugsBoard.CGpXUTPu.js +0 -1
- package/dist/_astro/PmIterationsBoard.BaKiFIam.js +0 -1
- package/dist/_astro/PmProjectsBoard.BxoMF9gK.js +0 -1
- package/dist/_astro/PmRequirementsBoard.-SI8VZXI.js +0 -1
- package/dist/_astro/PmRequirementsBoard.DsK6RF7Q.js +0 -1
- package/dist/_astro/PmShared.BK8kWRSV.js +0 -1
- package/dist/_astro/PromptMountDialog.mrTx3U5T.js +0 -1
- package/dist/_astro/PromptsLibrary.B_SUf47p.js +0 -1
- package/dist/_astro/ReportsPage.B9lGg1_s.js +0 -16
- package/dist/_astro/ReqAnalysisBoard.CIZKnCQH.js +0 -39
- package/dist/_astro/RequirementsLibrary.cJc-bnGQ.js +0 -1
- package/dist/_astro/SearchableSelect.SyLRS-Jj.js +0 -1
- package/dist/_astro/SelectDropdown.T3CKHaLt.js +0 -1
- package/dist/_astro/SettingsDialog.DYdtCvLc.js +0 -1
- package/dist/_astro/SpaceSwitcher.C47_S1g9.js +0 -7
- package/dist/_astro/TasksBoard.BUEg2BYk.js +0 -1
- package/dist/_astro/TemplatesLibrary.BLVIphXO.js +0 -1
- package/dist/_astro/TestReportsLibrary.DVq30Jae.js +0 -1
- package/dist/_astro/TestStatsBoard.-5BWQ6bI.js +0 -1
- package/dist/_astro/Toast.BO2NFckG.js +0 -1
- package/dist/_astro/TodosBoard.DI_lTp2e.js +0 -1
- package/dist/_astro/UiAutoBoard.ChFdgv7s.js +0 -2
- package/dist/_astro/UiAutoEnvPanel.B50q4kYb.js +0 -19
- package/dist/_astro/UiAutoGenerationDialog.CLkFAHrm.js +0 -1
- package/dist/_astro/UiAutoProjectsPage.DCsDeN5d.js +0 -3
- package/dist/_astro/app-config.DkyjuL-S.js +0 -1
- package/dist/_astro/app-version.Cy-5oZO2.js +0 -1
- package/dist/_astro/case-fields.CmePqYfh.js +0 -148
- package/dist/_astro/case-gen-run.BklG1H8k.js +0 -22
- package/dist/_astro/case-types.DlFkbZJN.js +0 -1
- package/dist/_astro/dialog.DZHZCe_T.js +0 -1
- package/dist/_astro/doc-roots.CO3IBiY6.js +0 -1
- package/dist/_astro/i18n.D_aOCHSN.js +0 -7
- package/dist/_astro/markdown-client.BS19nLL3.js +0 -62
- package/dist/_astro/plugins.BRvXWHLe.js +0 -1
- package/dist/_astro/project-docs.CCjtiFjB.js +0 -1
- package/dist/_astro/prompts-meta.BUGutlsk.js +0 -2
- package/dist/_astro/report-prompt.B9C4cv84.js +0 -1
- package/dist/_astro/req-analysis.B12_MGMQ.js +0 -31
- package/dist/_astro/story-review.D2W5tEOY.js +0 -14
- package/dist/_astro/test-reports.CuIjlEyK.js +0 -19
- package/dist/_astro/ui-auto-prompt.H9_yhau9.js +0 -9
- package/dist/_astro/ui-auto.DMv940x4.js +0 -1
|
@@ -0,0 +1,1014 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { resolveContentRoot } from '../../builtin/session/space-layout.mjs';
|
|
7
|
+
import {
|
|
8
|
+
businessLoginRequired,
|
|
9
|
+
businessLoginRoot,
|
|
10
|
+
hasLoginChallenge,
|
|
11
|
+
resolveBusinessLoginState,
|
|
12
|
+
} from './auth-paths.mjs';
|
|
13
|
+
|
|
14
|
+
const CODE_EXT = /\.(md|mdx|txt|json|ya?ml|ts|tsx|js|jsx|vue|svelte|java|kt|py|go|cs|sql|xml)$/i;
|
|
15
|
+
const DOC_EXT = /\.(md|markdown|txt|csv|docx|xlsx|xls)$/i;
|
|
16
|
+
const MATERIAL_TEXT_EXT = /\.(md|markdown|txt|csv|json|xml|html?|ya?ml)$/i;
|
|
17
|
+
const MATERIAL_SUPPORTED_EXT =
|
|
18
|
+
/\.(md|markdown|txt|csv|json|xml|html?|ya?ml|doc|docx|xls|xlsx|xmind|pptx)$/i;
|
|
19
|
+
export const BUSINESS_MATERIAL_MAX_BYTES = 25 * 1024 * 1024;
|
|
20
|
+
const SKIP_DIRS = new Set([
|
|
21
|
+
'.git',
|
|
22
|
+
'.lantern',
|
|
23
|
+
'node_modules',
|
|
24
|
+
'dist',
|
|
25
|
+
'build',
|
|
26
|
+
'coverage',
|
|
27
|
+
'.next',
|
|
28
|
+
'vendor',
|
|
29
|
+
'__pycache__',
|
|
30
|
+
]);
|
|
31
|
+
const SECRET =
|
|
32
|
+
/(^|[/.])(?:\.env(?:\..*)?|\.auth|credentials?|secrets?|id_rsa|id_ed25519)(?:[/.]|$)|\.(pem|key|p12|pfx)$|(?:storage[-_]?state|login[-_]?state|package-lock|pnpm-lock|yarn\.lock)/i;
|
|
33
|
+
export const hash = (value) => crypto.createHash('sha256').update(value).digest('hex');
|
|
34
|
+
export function within(root, abs) {
|
|
35
|
+
return abs === root || abs.startsWith(root + path.sep);
|
|
36
|
+
}
|
|
37
|
+
export function safeFile(root, rel) {
|
|
38
|
+
const base = fs.realpathSync(root);
|
|
39
|
+
const abs = fs.realpathSync(path.resolve(base, rel));
|
|
40
|
+
if (!within(base, abs) || !fs.statSync(abs).isFile()) throw new Error('文件不在选择的来源目录内');
|
|
41
|
+
return abs;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function decodeXml(value) {
|
|
45
|
+
return String(value)
|
|
46
|
+
.replace(/</g, '<')
|
|
47
|
+
.replace(/>/g, '>')
|
|
48
|
+
.replace(/"/g, '"')
|
|
49
|
+
.replace(/'|'/g, "'")
|
|
50
|
+
.replace(/&/g, '&');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function safeMaterialName(value) {
|
|
54
|
+
const name = path.basename(String(value || '').trim()).replace(/[\u0000-\u001f]/g, '');
|
|
55
|
+
if (!name || name === '.' || name === '..' || name.startsWith('.'))
|
|
56
|
+
throw new Error('资料文件名无效');
|
|
57
|
+
if (Buffer.byteLength(name) > 240) throw new Error('资料文件名过长');
|
|
58
|
+
return name;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function businessMaterialDir(root, systemId) {
|
|
62
|
+
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(systemId)) throw new Error('业务系统编号无效');
|
|
63
|
+
return path.join(resolveContentRoot(root, '业务地图').abs, '识别资料', systemId);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function businessMaterialCatalog(root, systemId) {
|
|
67
|
+
const dir = businessMaterialDir(root, systemId);
|
|
68
|
+
if (!fs.existsSync(dir)) return [];
|
|
69
|
+
return fs
|
|
70
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
71
|
+
.filter((entry) => entry.isFile())
|
|
72
|
+
.map((entry) => {
|
|
73
|
+
const abs = path.join(dir, entry.name);
|
|
74
|
+
const stat = fs.statSync(abs);
|
|
75
|
+
return {
|
|
76
|
+
id: entry.name,
|
|
77
|
+
name: entry.name,
|
|
78
|
+
path: entry.name,
|
|
79
|
+
size: stat.size,
|
|
80
|
+
updatedAt: stat.mtime.toISOString(),
|
|
81
|
+
supported: MATERIAL_SUPPORTED_EXT.test(entry.name),
|
|
82
|
+
};
|
|
83
|
+
})
|
|
84
|
+
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function saveBusinessMaterial(root, systemId, fileName, buffer) {
|
|
88
|
+
if (!buffer?.length) throw new Error('空文件');
|
|
89
|
+
if (buffer.length > BUSINESS_MATERIAL_MAX_BYTES)
|
|
90
|
+
throw new Error(`文件超过 ${BUSINESS_MATERIAL_MAX_BYTES / 1024 / 1024} MB`);
|
|
91
|
+
const name = safeMaterialName(fileName);
|
|
92
|
+
const dir = businessMaterialDir(root, systemId);
|
|
93
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
94
|
+
const dest = path.join(dir, name);
|
|
95
|
+
const tmp = `${dest}.${crypto.randomUUID()}.tmp`;
|
|
96
|
+
fs.writeFileSync(tmp, buffer);
|
|
97
|
+
fs.renameSync(tmp, dest);
|
|
98
|
+
return businessMaterialCatalog(root, systemId).find((item) => item.name === name);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function removeBusinessMaterial(root, systemId, fileName) {
|
|
102
|
+
const name = safeMaterialName(fileName);
|
|
103
|
+
fs.rmSync(path.join(businessMaterialDir(root, systemId), name), { force: true });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function walkFiles(root, predicate, limit = 600, exclusions = []) {
|
|
107
|
+
if (!fs.existsSync(root)) return [];
|
|
108
|
+
const base = fs.realpathSync(root);
|
|
109
|
+
const privateDir = businessLoginRoot();
|
|
110
|
+
const privateRoot = fs.existsSync(privateDir)
|
|
111
|
+
? fs.realpathSync(privateDir)
|
|
112
|
+
: path.resolve(privateDir);
|
|
113
|
+
const stack = [base],
|
|
114
|
+
output = [];
|
|
115
|
+
while (stack.length && output.length < limit) {
|
|
116
|
+
for (const entry of fs
|
|
117
|
+
.readdirSync(stack.pop(), { withFileTypes: true })
|
|
118
|
+
.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
119
|
+
const abs = path.join(entry.parentPath || entry.path, entry.name);
|
|
120
|
+
const rel = path.relative(base, abs).replaceAll('\\', '/');
|
|
121
|
+
if (
|
|
122
|
+
entry.isSymbolicLink() ||
|
|
123
|
+
within(privateRoot, abs) ||
|
|
124
|
+
SECRET.test(rel) ||
|
|
125
|
+
exclusions.some((item) => rel === item || rel.startsWith(item.replace(/\/$/, '') + '/'))
|
|
126
|
+
)
|
|
127
|
+
continue;
|
|
128
|
+
if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) stack.push(abs);
|
|
129
|
+
else if (entry.isFile() && predicate.test(entry.name)) output.push({ rel, abs });
|
|
130
|
+
if (output.length >= limit) break;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return output;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function documentCatalog(root) {
|
|
137
|
+
return ['需求文档库', '知识库管理'].flatMap((library) => {
|
|
138
|
+
const dir = resolveContentRoot(root, library).abs;
|
|
139
|
+
return walkFiles(dir, /\.(md|markdown|txt|csv|docx|xlsx|xls|pdf|doc|pptx?)$/i, 1000).map(
|
|
140
|
+
(file) => ({
|
|
141
|
+
id: `${library}/${file.rel}`,
|
|
142
|
+
library,
|
|
143
|
+
path: file.rel,
|
|
144
|
+
supported: DOC_EXT.test(file.rel),
|
|
145
|
+
}),
|
|
146
|
+
);
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
async function documentText(abs) {
|
|
150
|
+
if (/\.docx$/i.test(abs)) {
|
|
151
|
+
const mammoth = (await import('mammoth')).default;
|
|
152
|
+
return (await mammoth.extractRawText({ buffer: fs.readFileSync(abs) })).value;
|
|
153
|
+
}
|
|
154
|
+
if (/\.xlsx?$/i.test(abs)) {
|
|
155
|
+
const imported = await import('xlsx');
|
|
156
|
+
const xlsx = imported.default || imported;
|
|
157
|
+
const book = xlsx.read(fs.readFileSync(abs), { type: 'buffer' });
|
|
158
|
+
return book.SheetNames.map(
|
|
159
|
+
(name) => `# ${name}\n${xlsx.utils.sheet_to_csv(book.Sheets[name])}`,
|
|
160
|
+
).join('\n');
|
|
161
|
+
}
|
|
162
|
+
return fs.readFileSync(abs, 'utf8');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function materialText(abs, name) {
|
|
166
|
+
const lower = name.toLowerCase();
|
|
167
|
+
if (lower.endsWith('.xmind')) {
|
|
168
|
+
const JSZip = (await import('jszip')).default;
|
|
169
|
+
const zip = await JSZip.loadAsync(fs.readFileSync(abs));
|
|
170
|
+
const content = zip.file('content.json');
|
|
171
|
+
if (content) {
|
|
172
|
+
const sheets = JSON.parse(await content.async('string'));
|
|
173
|
+
const lines = [];
|
|
174
|
+
const walk = (topic, depth = 0) => {
|
|
175
|
+
if (!topic || typeof topic !== 'object') return;
|
|
176
|
+
const title = String(topic.title || '').trim();
|
|
177
|
+
if (title) lines.push(`${' '.repeat(depth)}- ${title}`);
|
|
178
|
+
const attached = topic.children?.attached;
|
|
179
|
+
if (Array.isArray(attached)) for (const child of attached) walk(child, depth + 1);
|
|
180
|
+
};
|
|
181
|
+
for (const sheet of Array.isArray(sheets) ? sheets : []) {
|
|
182
|
+
const rootTopic = sheet?.rootTopic || sheet?.topic;
|
|
183
|
+
if (rootTopic) walk(rootTopic);
|
|
184
|
+
}
|
|
185
|
+
if (lines.length) return lines.join('\n');
|
|
186
|
+
}
|
|
187
|
+
const legacy = zip.file('content.xml');
|
|
188
|
+
if (legacy) {
|
|
189
|
+
const xml = await legacy.async('string');
|
|
190
|
+
return [...xml.matchAll(/<title[^>]*>([\s\S]*?)<\/title>/gi)]
|
|
191
|
+
.map((match) => decodeXml(match[1]))
|
|
192
|
+
.filter(Boolean)
|
|
193
|
+
.join('\n');
|
|
194
|
+
}
|
|
195
|
+
throw new Error('XMind 文件里没有可读取的 content.json/content.xml');
|
|
196
|
+
}
|
|
197
|
+
if (lower.endsWith('.pptx')) {
|
|
198
|
+
const JSZip = (await import('jszip')).default;
|
|
199
|
+
const zip = await JSZip.loadAsync(fs.readFileSync(abs));
|
|
200
|
+
const slides = Object.keys(zip.files)
|
|
201
|
+
.filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))
|
|
202
|
+
.sort((a, b) => Number(a.match(/\d+/)?.[0]) - Number(b.match(/\d+/)?.[0]));
|
|
203
|
+
const output = [];
|
|
204
|
+
for (const [index, name] of slides.entries()) {
|
|
205
|
+
const xml = await zip.file(name).async('string');
|
|
206
|
+
const lines = [...xml.matchAll(/<a:t>([\s\S]*?)<\/a:t>/gi)]
|
|
207
|
+
.map((match) => decodeXml(match[1]).trim())
|
|
208
|
+
.filter(Boolean);
|
|
209
|
+
if (lines.length) output.push(`# 第 ${index + 1} 页\n${lines.join('\n')}`);
|
|
210
|
+
}
|
|
211
|
+
if (output.length) return output.join('\n\n');
|
|
212
|
+
throw new Error('PPTX 文件里没有可读取的文本');
|
|
213
|
+
}
|
|
214
|
+
if (/\.doc$/i.test(lower)) {
|
|
215
|
+
const imported = await import('word-extractor');
|
|
216
|
+
const WordExtractor = imported.default || imported;
|
|
217
|
+
const doc = await new WordExtractor().extract(fs.readFileSync(abs));
|
|
218
|
+
return String(doc.getBody?.() || '').trim();
|
|
219
|
+
}
|
|
220
|
+
if (/\.(docx|xlsx?)$/i.test(lower)) return documentText(abs);
|
|
221
|
+
if (MATERIAL_TEXT_EXT.test(lower)) return fs.readFileSync(abs, 'utf8');
|
|
222
|
+
const raw = fs.readFileSync(abs);
|
|
223
|
+
if (raw.includes(0)) throw new Error(`暂不支持解析 ${path.extname(name) || '该文件类型'}`);
|
|
224
|
+
return raw.toString('utf8');
|
|
225
|
+
}
|
|
226
|
+
export function makeEvidence(type, ref, content, title = ref) {
|
|
227
|
+
return {
|
|
228
|
+
id: `src_${hash(type + ':' + ref + ':' + content).slice(0, 24)}`,
|
|
229
|
+
type,
|
|
230
|
+
ref,
|
|
231
|
+
title,
|
|
232
|
+
content,
|
|
233
|
+
fingerprint: hash(content),
|
|
234
|
+
at: new Date().toISOString(),
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
export async function collectFiles(root, system, config, { signal, onProgress }) {
|
|
238
|
+
const evidence = [],
|
|
239
|
+
issues = [];
|
|
240
|
+
let collectedChars = 0;
|
|
241
|
+
const add = (type, ref, content, title) => {
|
|
242
|
+
const available = Math.max(0, 2000000 - collectedChars);
|
|
243
|
+
if (content.length > available && !issues.some((issue) => issue.includes('200万字符')))
|
|
244
|
+
issues.push('来源正文达到200万字符上限,结果为部分覆盖');
|
|
245
|
+
content = String(content).slice(0, available);
|
|
246
|
+
collectedChars += content.length;
|
|
247
|
+
let line = 1;
|
|
248
|
+
for (let offset = 0; offset < content.length; offset += 12000) {
|
|
249
|
+
const chunk = content.slice(offset, offset + 12000),
|
|
250
|
+
newlines = (chunk.match(/\n/g) || []).length;
|
|
251
|
+
const end = Math.max(line, line + newlines - (chunk.endsWith('\n') ? 1 : 0));
|
|
252
|
+
if (chunk.trim()) evidence.push(makeEvidence(type, `${ref}#L${line}-L${end}`, chunk, title));
|
|
253
|
+
line += newlines;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
if (config.sources.process?.enabled) {
|
|
257
|
+
const content = system.flows.length
|
|
258
|
+
? JSON.stringify(
|
|
259
|
+
system.flows.map((flow) => ({
|
|
260
|
+
id: flow.id,
|
|
261
|
+
name: flow.name,
|
|
262
|
+
result: flow.result,
|
|
263
|
+
status: flow.status,
|
|
264
|
+
steps: flow.steps.map((step) => ({
|
|
265
|
+
title: step.title,
|
|
266
|
+
role: step.role,
|
|
267
|
+
system: step.system,
|
|
268
|
+
functionId: step.functionId,
|
|
269
|
+
input: step.input,
|
|
270
|
+
output: step.output,
|
|
271
|
+
next: step.next,
|
|
272
|
+
branch: step.branch,
|
|
273
|
+
branchBroken: step.branchBroken,
|
|
274
|
+
manual: step.manual,
|
|
275
|
+
})),
|
|
276
|
+
})),
|
|
277
|
+
null,
|
|
278
|
+
2,
|
|
279
|
+
)
|
|
280
|
+
: '';
|
|
281
|
+
if (content) {
|
|
282
|
+
add('process', 'system://flows', `# 当前业务流程\n${content}`, '当前业务流程');
|
|
283
|
+
onProgress('processes', `${system.flows.length} 条流程`);
|
|
284
|
+
} else issues.push('业务流程来源:当前系统还没有已维护的流程');
|
|
285
|
+
}
|
|
286
|
+
if (config.sources.doc.enabled) {
|
|
287
|
+
const catalog = documentCatalog(root);
|
|
288
|
+
for (const id of config.documents) {
|
|
289
|
+
signal.throwIfAborted();
|
|
290
|
+
const item = catalog.find((item) => item.id === id);
|
|
291
|
+
if (!item || !item.supported) {
|
|
292
|
+
issues.push(`文档不可用或暂不支持:${id}`);
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
try {
|
|
296
|
+
const abs = safeFile(resolveContentRoot(root, item.library).abs, item.path);
|
|
297
|
+
if (fs.statSync(abs).size > 8 * 1024 * 1024) throw new Error('文件超过 8MB,请拆分后重试');
|
|
298
|
+
const content = await documentText(abs);
|
|
299
|
+
if (content.length > 300000) issues.push(`文档仅读取前 300000 字:${id}`);
|
|
300
|
+
add('doc', id, content.slice(0, 300000), item.path);
|
|
301
|
+
onProgress('documents', id);
|
|
302
|
+
} catch (error) {
|
|
303
|
+
issues.push(`文档 ${id}:${error.message}`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (config.sources.material?.enabled) {
|
|
308
|
+
const catalog = businessMaterialCatalog(root, system.id);
|
|
309
|
+
for (const name of config.materials || []) {
|
|
310
|
+
signal.throwIfAborted();
|
|
311
|
+
if (collectedChars >= 2000000) break;
|
|
312
|
+
const item = catalog.find((entry) => entry.name === name);
|
|
313
|
+
if (!item) {
|
|
314
|
+
issues.push(`本地资料不存在:${name}`);
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (!item.supported) {
|
|
318
|
+
issues.push(`本地资料暂不支持解析:${name}`);
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
try {
|
|
322
|
+
if (item.size > BUSINESS_MATERIAL_MAX_BYTES)
|
|
323
|
+
throw new Error(`文件超过 ${BUSINESS_MATERIAL_MAX_BYTES / 1024 / 1024} MB`);
|
|
324
|
+
const abs = path.join(businessMaterialDir(root, system.id), item.name);
|
|
325
|
+
const content = await materialText(abs, item.name);
|
|
326
|
+
if (content.length > 300000) issues.push(`本地资料仅读取前 300000 字:${name}`);
|
|
327
|
+
add('material', `本地资料/${item.name}`, content.slice(0, 300000), item.name);
|
|
328
|
+
onProgress('materials', item.name);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
issues.push(`本地资料 ${name}:${error.message}`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
if (config.sources.code.enabled) {
|
|
335
|
+
const dir = config.sourceDir || system.sourceDir;
|
|
336
|
+
try {
|
|
337
|
+
if (!dir || !fs.statSync(dir).isDirectory()) throw new Error('请配置可读取的源码目录');
|
|
338
|
+
const files = walkFiles(dir, CODE_EXT, 601, config.exclusions);
|
|
339
|
+
if (files.length > 600) issues.push('源码达到 600 文件上限,结果为部分覆盖');
|
|
340
|
+
for (const file of files.slice(0, 600)) {
|
|
341
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
342
|
+
signal.throwIfAborted();
|
|
343
|
+
if (collectedChars >= 2000000) break;
|
|
344
|
+
try {
|
|
345
|
+
if (fs.statSync(file.abs).size > 256000) {
|
|
346
|
+
issues.push(`跳过大文件:${file.rel}`);
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
const content = fs.readFileSync(file.abs, 'utf8');
|
|
350
|
+
if (content.includes('\0')) continue;
|
|
351
|
+
add('code', file.rel, content, file.rel);
|
|
352
|
+
onProgress('code', file.rel);
|
|
353
|
+
} catch (error) {
|
|
354
|
+
issues.push(`源码 ${file.rel}:${error.message}`);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
} catch (error) {
|
|
358
|
+
issues.push(`源码来源:${error.message}`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return { evidence, issues };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export async function collectOnlineDocuments(root, system, config, { signal, onProgress }) {
|
|
365
|
+
const evidence = [],
|
|
366
|
+
issues = [];
|
|
367
|
+
if (!config.sources.onlineDoc?.enabled) return { evidence, issues };
|
|
368
|
+
const urls = (config.onlineDocUrls || [])
|
|
369
|
+
.map((value) => {
|
|
370
|
+
try {
|
|
371
|
+
const url = new URL(value);
|
|
372
|
+
return ['http:', 'https:'].includes(url.protocol) ? url.href : '';
|
|
373
|
+
} catch {
|
|
374
|
+
return '';
|
|
375
|
+
}
|
|
376
|
+
})
|
|
377
|
+
.filter(Boolean);
|
|
378
|
+
if (!urls.length) return { evidence, issues: ['在线文档来源没有有效链接'] };
|
|
379
|
+
let collectedChars = 0;
|
|
380
|
+
const maxChars = config.maxChars ?? 2000000;
|
|
381
|
+
const runtime = loadBrowserRuntime([
|
|
382
|
+
config.runtimeDir,
|
|
383
|
+
config.sourceDir,
|
|
384
|
+
system.sourceDir,
|
|
385
|
+
fileURLToPath(new URL('../..', import.meta.url)),
|
|
386
|
+
process.cwd(),
|
|
387
|
+
]);
|
|
388
|
+
const browser = await runtime.chromium.launch({ headless: true });
|
|
389
|
+
const stop = () => void browser.close().catch(() => {});
|
|
390
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
391
|
+
try {
|
|
392
|
+
let storageState;
|
|
393
|
+
const loginStateFile = system.id ? resolveBusinessLoginState(root, system) : '';
|
|
394
|
+
if (loginStateFile && fs.existsSync(loginStateFile))
|
|
395
|
+
storageState = JSON.parse(fs.readFileSync(loginStateFile, 'utf8'));
|
|
396
|
+
const context = await browser.newContext({
|
|
397
|
+
storageState,
|
|
398
|
+
serviceWorkers: 'block',
|
|
399
|
+
acceptDownloads: false,
|
|
400
|
+
});
|
|
401
|
+
await context.route('**/*', async (route) => {
|
|
402
|
+
const request = route.request();
|
|
403
|
+
if (!['GET', 'HEAD', 'OPTIONS'].includes(request.method())) {
|
|
404
|
+
if (issues.length < 200)
|
|
405
|
+
issues.push(`在线文档只读拦截:${request.method()} ${new URL(request.url()).pathname}`);
|
|
406
|
+
return route.abort();
|
|
407
|
+
}
|
|
408
|
+
return route.continue();
|
|
409
|
+
});
|
|
410
|
+
await context.addInitScript(() => {
|
|
411
|
+
window.WebSocket = class {
|
|
412
|
+
constructor() {
|
|
413
|
+
throw new Error('业务地图只读采集不开放 WebSocket');
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
navigator.sendBeacon = () => false;
|
|
417
|
+
});
|
|
418
|
+
const page = await context.newPage();
|
|
419
|
+
for (const url of urls) {
|
|
420
|
+
signal.throwIfAborted();
|
|
421
|
+
if (collectedChars >= maxChars) break;
|
|
422
|
+
try {
|
|
423
|
+
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
|
|
424
|
+
await page.waitForTimeout(900);
|
|
425
|
+
if (await hasLoginChallenge(page)) {
|
|
426
|
+
issues.push(`在线文档需要登录或验证:${url}`);
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
const title = await page.title().catch(() => '');
|
|
430
|
+
const frameTexts = [];
|
|
431
|
+
for (const frame of page.frames()) {
|
|
432
|
+
const text = await frame
|
|
433
|
+
.evaluate(() => document.body?.innerText?.slice(0, 120000) || '')
|
|
434
|
+
.catch(() => '');
|
|
435
|
+
if (text.trim()) frameTexts.push(text);
|
|
436
|
+
}
|
|
437
|
+
const content = [...new Set(frameTexts)].join('\n\n');
|
|
438
|
+
const remaining = Math.max(0, maxChars - collectedChars);
|
|
439
|
+
if (content.length > remaining) issues.push('在线文档来源达到正文预算,结果为部分覆盖');
|
|
440
|
+
const sliced = content.slice(0, Math.min(remaining, 300000));
|
|
441
|
+
if (sliced.trim()) {
|
|
442
|
+
evidence.push(makeEvidence('online_doc', page.url(), sliced, title || url));
|
|
443
|
+
collectedChars += sliced.length;
|
|
444
|
+
} else issues.push(`在线文档没有可读取正文:${url}`);
|
|
445
|
+
onProgress('onlineDocs', title || url);
|
|
446
|
+
} catch (error) {
|
|
447
|
+
if (signal.aborted) throw error;
|
|
448
|
+
issues.push(`在线文档 ${url}:${String(error.message).split('\n')[0]}`);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return { evidence, issues };
|
|
452
|
+
} finally {
|
|
453
|
+
signal.removeEventListener('abort', stop);
|
|
454
|
+
await browser.close().catch(() => {});
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export function loadBrowserRuntime(dirs) {
|
|
459
|
+
for (const dir of dirs.filter(Boolean)) {
|
|
460
|
+
const require = createRequire(path.join(path.resolve(dir), 'package.json'));
|
|
461
|
+
for (const name of ['playwright', '@playwright/test']) {
|
|
462
|
+
try {
|
|
463
|
+
const runtime = require(name);
|
|
464
|
+
if (runtime.chromium) return runtime;
|
|
465
|
+
} catch {
|
|
466
|
+
/* next runtime */
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
throw new Error(
|
|
471
|
+
'缺少 Playwright 浏览器运行时:请在源码项目或 Lantern 安装目录准备 playwright 与 Chromium 后重试',
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
const UNSAFE =
|
|
475
|
+
/删除|保存|提交|审批|审核通过|发送|支付|退出|注销|启用|禁用|重置|导入|导出|新增|创建|remove|delete|submit|save|approve|send|pay|logout|signout|reset|create|export|import/i;
|
|
476
|
+
export function readableUrl(raw, base) {
|
|
477
|
+
try {
|
|
478
|
+
const url = new URL(raw, base);
|
|
479
|
+
if (
|
|
480
|
+
!['http:', 'https:'].includes(url.protocol) ||
|
|
481
|
+
url.origin !== new URL(base).origin ||
|
|
482
|
+
UNSAFE.test(decodeURIComponent(url.pathname + url.search))
|
|
483
|
+
)
|
|
484
|
+
return null;
|
|
485
|
+
url.searchParams.sort();
|
|
486
|
+
return url.href;
|
|
487
|
+
} catch {
|
|
488
|
+
return null;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* 门户型系统把子系统标识放在 localStorage 的 modulesConfigs 中。
|
|
493
|
+
* 直接打开子系统时如果缺少 moduleid,SPA 会请求
|
|
494
|
+
* `/menu/current/tree/undefined` 并显示内部错误;先经过门户根页把
|
|
495
|
+
* 目标模块的 moduleid 写回浏览器上下文,再进入实际系统页。
|
|
496
|
+
*/
|
|
497
|
+
async function hydratePortalModule(page, entry) {
|
|
498
|
+
let target;
|
|
499
|
+
try {
|
|
500
|
+
target = new URL(entry);
|
|
501
|
+
} catch {
|
|
502
|
+
return false;
|
|
503
|
+
}
|
|
504
|
+
if (target.pathname === '/' || target.pathname === '') return false;
|
|
505
|
+
const portalUrls = [new URL('/', target).href, new URL('/index', target).href];
|
|
506
|
+
for (const portalUrl of new Set(portalUrls)) {
|
|
507
|
+
try {
|
|
508
|
+
await page.goto(portalUrl, { waitUntil: 'domcontentloaded', timeout: 12000 });
|
|
509
|
+
await page.waitForTimeout(700);
|
|
510
|
+
const moduleId = await page.evaluate((pathname) => {
|
|
511
|
+
try {
|
|
512
|
+
const modules = JSON.parse(localStorage.getItem('modulesConfigs') || '[]');
|
|
513
|
+
if (!Array.isArray(modules)) return '';
|
|
514
|
+
const normalizedPath = String(pathname || '').replace(/\/+$/, '');
|
|
515
|
+
const module = modules.find((item) => {
|
|
516
|
+
const url = String(item?.url || '').replace(/\/+$/, '');
|
|
517
|
+
return url && (normalizedPath === url || normalizedPath.startsWith(`${url}/`));
|
|
518
|
+
});
|
|
519
|
+
if (!module?.id) return '';
|
|
520
|
+
localStorage.setItem('moduleid', String(module.id));
|
|
521
|
+
return String(module.id);
|
|
522
|
+
} catch {
|
|
523
|
+
return '';
|
|
524
|
+
}
|
|
525
|
+
}, target.pathname);
|
|
526
|
+
if (moduleId) return true;
|
|
527
|
+
} catch {
|
|
528
|
+
// 普通业务页面没有门户根页时继续使用原始入口。
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return false;
|
|
532
|
+
}
|
|
533
|
+
async function waitForSettledPage(page) {
|
|
534
|
+
await page.waitForTimeout(400);
|
|
535
|
+
const transient = await page
|
|
536
|
+
.evaluate(() => /正在前往|Network Error|系统内部错误/.test(document.body?.innerText || ''))
|
|
537
|
+
.catch(() => false);
|
|
538
|
+
if (!transient) return;
|
|
539
|
+
await page
|
|
540
|
+
.waitForFunction(
|
|
541
|
+
() => !/正在前往|Network Error|系统内部错误/.test(document.body?.innerText || ''),
|
|
542
|
+
null,
|
|
543
|
+
{ timeout: 5000 },
|
|
544
|
+
)
|
|
545
|
+
.catch(() => undefined);
|
|
546
|
+
await page.waitForTimeout(300);
|
|
547
|
+
}
|
|
548
|
+
export async function collectPages(root, system, config, { signal, onProgress }) {
|
|
549
|
+
const evidence = [],
|
|
550
|
+
issues = [],
|
|
551
|
+
navigation = [],
|
|
552
|
+
pageCatalog = new Map();
|
|
553
|
+
let collectedChars = 0;
|
|
554
|
+
const maxChars = config.maxChars ?? 2000000;
|
|
555
|
+
const maxPages = Math.max(1, Number(config.maxPages) || 100);
|
|
556
|
+
const pageId = (ref) => `pg_${hash(ref).slice(0, 12)}`;
|
|
557
|
+
const rememberPage = (ref, title, status, meta = {}) => {
|
|
558
|
+
const id = pageId(ref);
|
|
559
|
+
const previous = pageCatalog.get(id);
|
|
560
|
+
if (!previous && pageCatalog.size >= maxPages) return;
|
|
561
|
+
pageCatalog.set(id, {
|
|
562
|
+
id,
|
|
563
|
+
title: title || previous?.title || ref,
|
|
564
|
+
url: ref,
|
|
565
|
+
canonicalUrl: ref.replace(/#(?:tab|menu)=.*/, ''),
|
|
566
|
+
parentId: meta.parentRef ? pageId(meta.parentRef) : previous?.parentId || '',
|
|
567
|
+
depth: meta.depth ?? previous?.depth ?? 0,
|
|
568
|
+
source: meta.source || previous?.source || 'link',
|
|
569
|
+
menuPath: meta.menuPath ?? previous?.menuPath ?? [],
|
|
570
|
+
menuOrder: meta.menuOrder ?? previous?.menuOrder ?? 0,
|
|
571
|
+
actionable: meta.actionable ?? previous?.actionable ?? false,
|
|
572
|
+
status,
|
|
573
|
+
contentLength: meta.contentLength ?? previous?.contentLength ?? 0,
|
|
574
|
+
lastCapturedAt: new Date().toISOString(),
|
|
575
|
+
});
|
|
576
|
+
};
|
|
577
|
+
const addPage = (ref, content, title, meta = {}) => {
|
|
578
|
+
if (evidence.length >= maxPages) return;
|
|
579
|
+
const status = content.trim()
|
|
580
|
+
? /Network Error|系统内部错误/.test(content)
|
|
581
|
+
? 'error'
|
|
582
|
+
: 'success'
|
|
583
|
+
: 'empty';
|
|
584
|
+
rememberPage(ref, title, status, { ...meta, contentLength: content.length });
|
|
585
|
+
const remaining = Math.max(0, maxChars - collectedChars);
|
|
586
|
+
if (content.length > remaining && !issues.some((issue) => issue.includes('正文预算')))
|
|
587
|
+
issues.push('页面来源达到正文预算,结果为部分覆盖');
|
|
588
|
+
content = content.slice(0, remaining);
|
|
589
|
+
collectedChars += content.length;
|
|
590
|
+
if (content.trim()) evidence.push(makeEvidence('page', ref, content, title));
|
|
591
|
+
};
|
|
592
|
+
if (!config.sources.page.enabled) return { evidence, issues, pages: [], navigation: [] };
|
|
593
|
+
if (
|
|
594
|
+
system.id &&
|
|
595
|
+
businessLoginRequired(root, system.id) &&
|
|
596
|
+
!resolveBusinessLoginState(root, system)
|
|
597
|
+
)
|
|
598
|
+
return {
|
|
599
|
+
evidence,
|
|
600
|
+
issues: ['登录态失效:请先在系统登录配置完成登录并保存登录态'],
|
|
601
|
+
pages: [],
|
|
602
|
+
navigation: [],
|
|
603
|
+
};
|
|
604
|
+
const entry = config.entryUrl || system.entryUrl;
|
|
605
|
+
if (!readableUrl(entry, entry))
|
|
606
|
+
return {
|
|
607
|
+
evidence,
|
|
608
|
+
issues: ['系统入口不是可只读访问的 HTTP 地址'],
|
|
609
|
+
pages: [],
|
|
610
|
+
navigation: [],
|
|
611
|
+
};
|
|
612
|
+
const runtime = loadBrowserRuntime([
|
|
613
|
+
config.runtimeDir,
|
|
614
|
+
config.sourceDir,
|
|
615
|
+
system.sourceDir,
|
|
616
|
+
fileURLToPath(new URL('../..', import.meta.url)),
|
|
617
|
+
process.cwd(),
|
|
618
|
+
]);
|
|
619
|
+
const browser = await runtime.chromium.launch({ headless: true });
|
|
620
|
+
const stop = () => void browser.close().catch(() => {});
|
|
621
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
622
|
+
try {
|
|
623
|
+
let storageState;
|
|
624
|
+
const loginStateFile = system.id
|
|
625
|
+
? resolveBusinessLoginState(root, system)
|
|
626
|
+
: system.loginState
|
|
627
|
+
? path.resolve(system.sourceDir || root, system.loginState)
|
|
628
|
+
: '';
|
|
629
|
+
if (loginStateFile) {
|
|
630
|
+
const file = loginStateFile;
|
|
631
|
+
if (!fs.existsSync(file)) throw new Error('登录态文件不存在,请在系统设置更新');
|
|
632
|
+
storageState = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
633
|
+
}
|
|
634
|
+
const context = await browser.newContext({
|
|
635
|
+
storageState,
|
|
636
|
+
serviceWorkers: 'block',
|
|
637
|
+
acceptDownloads: false,
|
|
638
|
+
});
|
|
639
|
+
await context.route('**/*', async (route) => {
|
|
640
|
+
const request = route.request();
|
|
641
|
+
const url = request.url();
|
|
642
|
+
if (
|
|
643
|
+
!['GET', 'HEAD', 'OPTIONS'].includes(request.method()) ||
|
|
644
|
+
UNSAFE.test(new URL(url).pathname + new URL(url).search) ||
|
|
645
|
+
(request.isNavigationRequest() && !readableUrl(url, entry))
|
|
646
|
+
) {
|
|
647
|
+
if (issues.length < 200)
|
|
648
|
+
issues.push(`只读拦截:${request.method()} ${new URL(url).pathname}`);
|
|
649
|
+
return route.abort();
|
|
650
|
+
}
|
|
651
|
+
return route.continue();
|
|
652
|
+
});
|
|
653
|
+
await context.addInitScript(() => {
|
|
654
|
+
window.WebSocket = class {
|
|
655
|
+
constructor() {
|
|
656
|
+
throw new Error('业务地图只读采集不开放 WebSocket');
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
navigator.sendBeacon = () => false;
|
|
660
|
+
});
|
|
661
|
+
const page = await context.newPage();
|
|
662
|
+
await hydratePortalModule(page, entry);
|
|
663
|
+
const selectedPages = config.pageUrls.map((url) => ({
|
|
664
|
+
url,
|
|
665
|
+
depth: 0,
|
|
666
|
+
parentRef: '',
|
|
667
|
+
source: 'manual',
|
|
668
|
+
menuPath: [],
|
|
669
|
+
menuOrder: 0,
|
|
670
|
+
actionable: true,
|
|
671
|
+
}));
|
|
672
|
+
const queue = config.selectedPagesOnly
|
|
673
|
+
? selectedPages
|
|
674
|
+
: [
|
|
675
|
+
{
|
|
676
|
+
url: entry,
|
|
677
|
+
depth: 0,
|
|
678
|
+
parentRef: '',
|
|
679
|
+
source: 'entry',
|
|
680
|
+
menuPath: [],
|
|
681
|
+
menuOrder: 0,
|
|
682
|
+
actionable: false,
|
|
683
|
+
},
|
|
684
|
+
...selectedPages,
|
|
685
|
+
],
|
|
686
|
+
seen = new Set();
|
|
687
|
+
while (queue.length && seen.size < maxPages && collectedChars < maxChars) {
|
|
688
|
+
signal.throwIfAborted();
|
|
689
|
+
const next = queue.shift();
|
|
690
|
+
const url = readableUrl(next.url, entry);
|
|
691
|
+
if (!url || seen.has(url) || next.depth > config.maxDepth) continue;
|
|
692
|
+
seen.add(url);
|
|
693
|
+
try {
|
|
694
|
+
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 20000 });
|
|
695
|
+
await waitForSettledPage(page);
|
|
696
|
+
if (await hasLoginChallenge(page)) {
|
|
697
|
+
rememberPage(url, '登录页', 'login', {
|
|
698
|
+
depth: next.depth,
|
|
699
|
+
parentRef: next.parentRef,
|
|
700
|
+
source: next.source,
|
|
701
|
+
menuPath: next.menuPath,
|
|
702
|
+
menuOrder: next.menuOrder,
|
|
703
|
+
actionable: next.actionable,
|
|
704
|
+
});
|
|
705
|
+
issues.push('登录态失效:检测到登录页面,请更新登录态后重试');
|
|
706
|
+
break;
|
|
707
|
+
}
|
|
708
|
+
const snapshot = await page.evaluate(() => ({
|
|
709
|
+
title: document.title,
|
|
710
|
+
text: document.body.innerText.slice(0, 24000),
|
|
711
|
+
links: Array.from(document.querySelectorAll('a[href]'))
|
|
712
|
+
.map((e) => ({ url: e.href, title: e.innerText }))
|
|
713
|
+
.filter((item) => item.url && item.title),
|
|
714
|
+
controls: Array.from(
|
|
715
|
+
document.querySelectorAll('button,input,select,textarea,[role=button],[role=tab]'),
|
|
716
|
+
)
|
|
717
|
+
.slice(0, 150)
|
|
718
|
+
.map((e) => ({
|
|
719
|
+
role: e.getAttribute('role') || e.tagName,
|
|
720
|
+
label:
|
|
721
|
+
e.getAttribute('aria-label') ||
|
|
722
|
+
e.innerText ||
|
|
723
|
+
e.getAttribute('placeholder') ||
|
|
724
|
+
e.getAttribute('name'),
|
|
725
|
+
})),
|
|
726
|
+
menuItems: (() => {
|
|
727
|
+
const normalize = (value) =>
|
|
728
|
+
String(value || '')
|
|
729
|
+
.replace(/\s+/g, ' ')
|
|
730
|
+
.trim();
|
|
731
|
+
const visible = (element) => {
|
|
732
|
+
const rect = element.getBoundingClientRect();
|
|
733
|
+
const style = getComputedStyle(element);
|
|
734
|
+
return (
|
|
735
|
+
rect.width > 0 &&
|
|
736
|
+
rect.height > 0 &&
|
|
737
|
+
style.display !== 'none' &&
|
|
738
|
+
style.visibility !== 'hidden' &&
|
|
739
|
+
style.opacity !== '0'
|
|
740
|
+
);
|
|
741
|
+
};
|
|
742
|
+
const roots = [
|
|
743
|
+
...document.querySelectorAll(
|
|
744
|
+
'nav, aside, [role="navigation"], [class*="menu" i], [class*="nav" i], [class*="sidebar" i], [class*="sider" i]',
|
|
745
|
+
),
|
|
746
|
+
]
|
|
747
|
+
.filter(visible)
|
|
748
|
+
.map((root) => {
|
|
749
|
+
const rootRect = root.getBoundingClientRect();
|
|
750
|
+
if (
|
|
751
|
+
rootRect.width < 120 ||
|
|
752
|
+
rootRect.width > window.innerWidth * 0.55 ||
|
|
753
|
+
rootRect.height < 160 ||
|
|
754
|
+
rootRect.left > window.innerWidth * 0.55
|
|
755
|
+
)
|
|
756
|
+
return null;
|
|
757
|
+
const raw = [
|
|
758
|
+
...root.querySelectorAll(
|
|
759
|
+
'a, button, li, div, [role="menuitem"], [role="treeitem"], [tabindex], [onclick]',
|
|
760
|
+
),
|
|
761
|
+
]
|
|
762
|
+
.filter(visible)
|
|
763
|
+
.map((element) => {
|
|
764
|
+
const text = normalize(
|
|
765
|
+
element.getAttribute('aria-label') ||
|
|
766
|
+
element.innerText ||
|
|
767
|
+
element.textContent,
|
|
768
|
+
);
|
|
769
|
+
const rect = element.getBoundingClientRect();
|
|
770
|
+
const style = getComputedStyle(element);
|
|
771
|
+
const visualLeft =
|
|
772
|
+
rect.left +
|
|
773
|
+
(Number.parseFloat(style.paddingLeft) || 0) +
|
|
774
|
+
(Number.parseFloat(style.marginLeft) || 0);
|
|
775
|
+
const interactive =
|
|
776
|
+
element.matches(
|
|
777
|
+
'a, button, li, [role="menuitem"], [role="treeitem"], [tabindex], [onclick]',
|
|
778
|
+
) || style.cursor === 'pointer';
|
|
779
|
+
if (
|
|
780
|
+
!interactive ||
|
|
781
|
+
!text ||
|
|
782
|
+
text.length > 100 ||
|
|
783
|
+
rect.height < 20 ||
|
|
784
|
+
rect.height > 72 ||
|
|
785
|
+
rect.width < 60
|
|
786
|
+
)
|
|
787
|
+
return null;
|
|
788
|
+
return { element, text, rect, visualLeft };
|
|
789
|
+
})
|
|
790
|
+
.filter(Boolean);
|
|
791
|
+
const deduped = raw.filter(
|
|
792
|
+
(entry, index) =>
|
|
793
|
+
!raw.some(
|
|
794
|
+
(other, otherIndex) =>
|
|
795
|
+
otherIndex !== index &&
|
|
796
|
+
entry.element.contains(other.element) &&
|
|
797
|
+
entry.text === other.text &&
|
|
798
|
+
other.rect.height <= entry.rect.height + 1,
|
|
799
|
+
),
|
|
800
|
+
);
|
|
801
|
+
const entries = [];
|
|
802
|
+
const seen = new Set();
|
|
803
|
+
for (const entry of deduped) {
|
|
804
|
+
const key = `${entry.text}|${Math.round(entry.rect.left / 3)}|${Math.round(entry.rect.top / 3)}`;
|
|
805
|
+
if (seen.has(key)) continue;
|
|
806
|
+
seen.add(key);
|
|
807
|
+
entries.push(entry);
|
|
808
|
+
}
|
|
809
|
+
entries.sort(
|
|
810
|
+
(left, right) =>
|
|
811
|
+
left.rect.top - right.rect.top || left.rect.left - right.rect.left,
|
|
812
|
+
);
|
|
813
|
+
return { rootRect, entries };
|
|
814
|
+
})
|
|
815
|
+
.filter((item) => item && item.entries.length >= 3)
|
|
816
|
+
.sort(
|
|
817
|
+
(left, right) =>
|
|
818
|
+
right.entries.length - left.entries.length ||
|
|
819
|
+
left.rootRect.left - right.rootRect.left,
|
|
820
|
+
);
|
|
821
|
+
const best = roots[0];
|
|
822
|
+
if (!best) return [];
|
|
823
|
+
const baseLeft = Math.min(...best.entries.map((entry) => entry.visualLeft));
|
|
824
|
+
const ancestry = [];
|
|
825
|
+
return best.entries.slice(0, 300).map((entry, order) => {
|
|
826
|
+
const depth = Math.max(
|
|
827
|
+
0,
|
|
828
|
+
Math.min(6, Math.round((entry.visualLeft - baseLeft) / 18)),
|
|
829
|
+
);
|
|
830
|
+
ancestry.length = Math.min(ancestry.length, depth);
|
|
831
|
+
const path = [...ancestry, entry.text];
|
|
832
|
+
ancestry[depth] = entry.text;
|
|
833
|
+
return { label: entry.text, path, depth, order };
|
|
834
|
+
});
|
|
835
|
+
})(),
|
|
836
|
+
}));
|
|
837
|
+
addPage(
|
|
838
|
+
page.url(),
|
|
839
|
+
`${snapshot.title}\n${snapshot.text}\n页面动作(仅观察,未执行):${JSON.stringify(snapshot.controls)}`,
|
|
840
|
+
snapshot.title,
|
|
841
|
+
{
|
|
842
|
+
depth: next.depth,
|
|
843
|
+
parentRef: next.parentRef,
|
|
844
|
+
source: next.source,
|
|
845
|
+
menuPath: next.menuPath,
|
|
846
|
+
menuOrder: next.menuOrder,
|
|
847
|
+
actionable: next.actionable,
|
|
848
|
+
},
|
|
849
|
+
);
|
|
850
|
+
for (const item of snapshot.menuItems || []) {
|
|
851
|
+
const path = [...(next.menuPath || []), ...(item.path || [item.label])].filter(Boolean);
|
|
852
|
+
const navKey = `${path.join('\u001f')}\u001e${item.order}`;
|
|
853
|
+
if (
|
|
854
|
+
navigation.some(
|
|
855
|
+
(entry) => `${entry.path.join('\u001f')}\u001e${entry.order}` === navKey,
|
|
856
|
+
)
|
|
857
|
+
)
|
|
858
|
+
continue;
|
|
859
|
+
navigation.push({
|
|
860
|
+
id: `nav_${hash(navKey).slice(0, 12)}`,
|
|
861
|
+
label: item.label,
|
|
862
|
+
path,
|
|
863
|
+
depth: next.depth + Math.max(0, Number(item.depth) || 0),
|
|
864
|
+
order: Math.max(0, Number(item.order) || 0),
|
|
865
|
+
pageUrl: page.url(),
|
|
866
|
+
actionable: true,
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
onProgress('pages', page.url());
|
|
870
|
+
const terms =
|
|
871
|
+
config.scope?.targets
|
|
872
|
+
.flatMap((target) => [target.name, target.description])
|
|
873
|
+
.filter(Boolean) || [];
|
|
874
|
+
const relevant = (link) =>
|
|
875
|
+
config.scope?.mode === 'system' ||
|
|
876
|
+
!terms.length ||
|
|
877
|
+
next.depth === 0 ||
|
|
878
|
+
terms.some((term) => (link.title + link.url).includes(term));
|
|
879
|
+
for (const link of snapshot.links)
|
|
880
|
+
if (!UNSAFE.test(link.title) && relevant(link))
|
|
881
|
+
queue.push({
|
|
882
|
+
url: link.url,
|
|
883
|
+
depth: next.depth + 1,
|
|
884
|
+
parentRef: url,
|
|
885
|
+
source: 'link',
|
|
886
|
+
menuPath: [...(next.menuPath || []), link.title.trim()].filter(Boolean),
|
|
887
|
+
menuOrder: snapshot.links.findIndex((item) => item.url === link.url),
|
|
888
|
+
actionable: true,
|
|
889
|
+
});
|
|
890
|
+
// SPA 菜单通常没有 href;仅操作具有明确菜单/树节点语义的控件。
|
|
891
|
+
const menus = page.locator('[role=menuitem], [role=treeitem], button[aria-expanded=false]');
|
|
892
|
+
const menuCount = Math.min(await menus.count(), 20);
|
|
893
|
+
for (
|
|
894
|
+
let i = 0;
|
|
895
|
+
i < menuCount && collectedChars < maxChars && evidence.length < maxPages;
|
|
896
|
+
i++
|
|
897
|
+
) {
|
|
898
|
+
signal.throwIfAborted();
|
|
899
|
+
const menu = menus.nth(i),
|
|
900
|
+
name = await menu.innerText().catch(() => '');
|
|
901
|
+
if (!name || UNSAFE.test(name) || !relevant({ title: name, url: '' })) continue;
|
|
902
|
+
const menuMeta = await menu
|
|
903
|
+
.evaluate((element) => {
|
|
904
|
+
const path = [];
|
|
905
|
+
let current = element;
|
|
906
|
+
while (current && current !== document.body) {
|
|
907
|
+
const role = current.getAttribute?.('role');
|
|
908
|
+
if (role === 'menuitem' || role === 'treeitem') {
|
|
909
|
+
const label = String(
|
|
910
|
+
current.getAttribute('aria-label') ||
|
|
911
|
+
current.querySelector?.(':scope > span')?.textContent ||
|
|
912
|
+
current.textContent ||
|
|
913
|
+
'',
|
|
914
|
+
).trim();
|
|
915
|
+
if (label && !path.includes(label)) path.unshift(label);
|
|
916
|
+
}
|
|
917
|
+
current = current.parentElement;
|
|
918
|
+
}
|
|
919
|
+
return {
|
|
920
|
+
path: path.length ? path : [String(element.textContent || '').trim()],
|
|
921
|
+
level: Math.max(
|
|
922
|
+
0,
|
|
923
|
+
Number(element.getAttribute('aria-level') || path.length || 1) - 1,
|
|
924
|
+
),
|
|
925
|
+
};
|
|
926
|
+
})
|
|
927
|
+
.catch(() => ({ path: [name.trim()], level: 0 }));
|
|
928
|
+
const before = page.url();
|
|
929
|
+
await menu.click({ timeout: 2000 }).catch(() => {});
|
|
930
|
+
await page.waitForTimeout(150);
|
|
931
|
+
const result = await page.evaluate(() => ({
|
|
932
|
+
text: document.body.innerText.slice(0, 24000),
|
|
933
|
+
links: Array.from(document.querySelectorAll('a[href]')).map((e) => ({
|
|
934
|
+
url: e.href,
|
|
935
|
+
title: e.innerText,
|
|
936
|
+
})),
|
|
937
|
+
}));
|
|
938
|
+
addPage(
|
|
939
|
+
page.url() + '#menu=' + encodeURIComponent(name),
|
|
940
|
+
result.text,
|
|
941
|
+
snapshot.title + ' / ' + name,
|
|
942
|
+
{
|
|
943
|
+
depth: next.depth + 1,
|
|
944
|
+
parentRef: url,
|
|
945
|
+
source: 'menu',
|
|
946
|
+
menuPath: [...(next.menuPath || []), ...menuMeta.path].filter(Boolean),
|
|
947
|
+
menuOrder: i,
|
|
948
|
+
actionable: true,
|
|
949
|
+
},
|
|
950
|
+
);
|
|
951
|
+
for (const link of result.links)
|
|
952
|
+
if (!UNSAFE.test(link.title) && relevant(link))
|
|
953
|
+
queue.push({
|
|
954
|
+
url: link.url,
|
|
955
|
+
depth: next.depth + 1,
|
|
956
|
+
parentRef: page.url(),
|
|
957
|
+
source: 'menu',
|
|
958
|
+
menuPath: [...(next.menuPath || []), ...menuMeta.path, link.title.trim()].filter(
|
|
959
|
+
Boolean,
|
|
960
|
+
),
|
|
961
|
+
menuOrder: i,
|
|
962
|
+
actionable: true,
|
|
963
|
+
});
|
|
964
|
+
if (page.url() !== before)
|
|
965
|
+
await page.goto(before, { waitUntil: 'domcontentloaded', timeout: 15000 });
|
|
966
|
+
}
|
|
967
|
+
// 非导航控件仅展开明确的标签/菜单;不点击普通业务按钮。
|
|
968
|
+
const tabs = page.locator('[role=tab]');
|
|
969
|
+
const count = Math.min(await tabs.count(), 12);
|
|
970
|
+
for (let i = 0; i < count && collectedChars < maxChars && evidence.length < maxPages; i++) {
|
|
971
|
+
signal.throwIfAborted();
|
|
972
|
+
const tab = tabs.nth(i),
|
|
973
|
+
name = await tab.innerText();
|
|
974
|
+
if (UNSAFE.test(name)) continue;
|
|
975
|
+
await tab.click({ timeout: 3000 }).catch(() => {});
|
|
976
|
+
await page.waitForTimeout(150);
|
|
977
|
+
const body = await page.locator('body').innerText();
|
|
978
|
+
addPage(
|
|
979
|
+
`${page.url()}#tab=${encodeURIComponent(name)}`,
|
|
980
|
+
body.slice(0, 24000),
|
|
981
|
+
`${snapshot.title} / ${name}`,
|
|
982
|
+
{
|
|
983
|
+
depth: next.depth,
|
|
984
|
+
parentRef: url,
|
|
985
|
+
source: 'tab',
|
|
986
|
+
menuPath: [...(next.menuPath || []), name.trim()].filter(Boolean),
|
|
987
|
+
menuOrder: i,
|
|
988
|
+
actionable: false,
|
|
989
|
+
},
|
|
990
|
+
);
|
|
991
|
+
}
|
|
992
|
+
} catch (error) {
|
|
993
|
+
if (signal.aborted) throw error;
|
|
994
|
+
const previous = pageCatalog.get(pageId(url));
|
|
995
|
+
if (!previous || previous.status === 'error') {
|
|
996
|
+
rememberPage(url, previous?.title || url, 'error', {
|
|
997
|
+
depth: next.depth,
|
|
998
|
+
parentRef: next.parentRef,
|
|
999
|
+
source: next.source,
|
|
1000
|
+
menuPath: next.menuPath,
|
|
1001
|
+
menuOrder: next.menuOrder,
|
|
1002
|
+
actionable: next.actionable,
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
issues.push(`页面 ${url}:${error.message.split('\n')[0]}`);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
if (queue.length) issues.push('已达到页面数量或深度上限,未覆盖所有发现页面');
|
|
1009
|
+
return { evidence, issues, pages: [...pageCatalog.values()], navigation };
|
|
1010
|
+
} finally {
|
|
1011
|
+
signal.removeEventListener('abort', stop);
|
|
1012
|
+
await browser.close().catch(() => {});
|
|
1013
|
+
}
|
|
1014
|
+
}
|