lantern-harness 0.1.9 → 0.1.11

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 (181) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +6 -6
  3. package/builtin/session/lh-fs.mjs +32 -14
  4. package/dist/500.html +258 -22
  5. package/dist/_astro/Base.Bgxs1QQl.css +1 -0
  6. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.CvbRi7Tl.js +1 -0
  7. package/dist/_astro/CaseExecBoard.Dttqp0wg.js +1 -0
  8. package/dist/_astro/CaseGenerateApp.DqW_nWMc.js +9 -0
  9. package/dist/_astro/CasesLibrary.8aMUUGp_.js +1 -0
  10. package/dist/_astro/ChatApp.BLxf0h1d.js +219 -0
  11. package/dist/_astro/ColumnResize.BEkEW7qw.js +1 -0
  12. package/dist/_astro/{ConfirmDialog.CBVsDJ8f.js → ConfirmDialog.BZzZWDci.js} +1 -1
  13. package/dist/_astro/{DashboardBoard.DCtfrrJz.js → DashboardBoard.CkSbhEDI.js} +3 -3
  14. package/dist/_astro/DatePicker.Bkl71M49.js +1 -0
  15. package/dist/_astro/DocsFileBrowser.MKVCfZrE.js +1 -0
  16. package/dist/_astro/DocsPager.DJY4foYL.js +1 -0
  17. package/dist/_astro/{DrawerField.CWMLhcPX.js → DrawerField.CHRg77LG.js} +1 -1
  18. package/dist/_astro/{ExcelFieldTags.B_XMwNNx.js → ExcelFieldTags.DXMeaDa5.js} +4 -4
  19. package/dist/_astro/KnowledgeLibrary.B-p1aoQN.js +1 -0
  20. package/dist/_astro/NamePromptDialog.Wa9O530a.js +1 -0
  21. package/dist/_astro/NavLibraries.C6LImMO_.js +1 -0
  22. package/dist/_astro/OverflowHint.D6v4Uj2N.js +1 -0
  23. package/dist/_astro/PluginsPage.-97n3x2U.js +39 -0
  24. package/dist/_astro/PluginsPage.DkmRPfbU.js +1 -0
  25. package/dist/_astro/PmBugsBoard.CMT4-eoB.js +1 -0
  26. package/dist/_astro/PmIterationsBoard.BQM_dzdZ.js +1 -0
  27. package/dist/_astro/PmProjectDetail.CzU80pat.js +1 -0
  28. package/dist/_astro/PmProjectsBoard.Cxsa7SYQ.js +1 -0
  29. package/dist/_astro/PmRequirementsBoard.4_JMDDN0.js +1 -0
  30. package/dist/_astro/PmRequirementsBoard.B8HL07cw.js +1 -0
  31. package/dist/_astro/PmShared.Ca2Ao7v_.js +1 -0
  32. package/dist/_astro/PromptsLibrary.C9BcIxKK.js +1 -0
  33. package/dist/_astro/ReportsPage.Fh5DRKLT.js +1 -0
  34. package/dist/_astro/RequirementsLibrary.CBkuWE8X.js +1 -0
  35. package/dist/_astro/SearchableSelect.DnjoSslK.js +1 -0
  36. package/dist/_astro/SelectDropdown.CuuDHa8s.js +1 -0
  37. package/dist/_astro/SettingsDialog.CVB5Gtk4.js +1 -0
  38. package/dist/_astro/SlideOverDrawer.B7B5Wu8I.js +1 -0
  39. package/dist/_astro/{SpaceSwitcher.CI3KDBOA.js → SpaceSwitcher.BVQLt_tL.js} +2 -2
  40. package/dist/_astro/TagSelect.CuN5RdF4.js +1 -0
  41. package/dist/_astro/TasksBoard.Bu-fpIZ7.js +1 -0
  42. package/dist/_astro/TemplatesLibrary.DSylQGlN.js +1 -0
  43. package/dist/_astro/TestStatsBoard.CPyKW4wc.js +1 -0
  44. package/dist/_astro/Toast.R8_2OWRX.js +1 -0
  45. package/dist/_astro/TodosBoard.8kvRTEW-.js +1 -0
  46. package/dist/_astro/UiAutoBoard.DFTiDqCp.js +9 -0
  47. package/dist/_astro/active-element-history.CED-m1Zp.js +1 -0
  48. package/dist/_astro/app-config.BUPzGl9f.js +1 -0
  49. package/dist/_astro/{client.Be_SakrB.js → client.BHNTqLjv.js} +3 -3
  50. package/dist/_astro/dialog.BAPTk9a_.js +1 -0
  51. package/dist/_astro/hydrate-cache.BXX604Bw.js +1 -0
  52. package/dist/_astro/{i18n.B52gLzii.js → i18n.BGPnP1Bg.js} +1 -1
  53. package/dist/_astro/index.astro_astro_type_script_index_0_lang.LPL9mPQY.js +1 -0
  54. package/dist/_astro/jsx-runtime.DUg_B_vD.js +1 -0
  55. package/dist/_astro/{lib.DJNDi_Ht.js → lib.CgXLzMMd.js} +15 -15
  56. package/dist/_astro/listbox.C96OCanh.js +1 -0
  57. package/dist/_astro/markdown-client.DRva7DS9.js +58 -0
  58. package/dist/_astro/menu.IPWdRoNM.js +1 -0
  59. package/dist/_astro/{open-docs-in-session.Xg3OSOfc.js → open-docs-in-session.CyFNgh1I.js} +1 -1
  60. package/dist/_astro/{plugins.BDZqJNOy.js → plugins.C2BMfzv1.js} +1 -1
  61. package/dist/_astro/{pm.Bl3hz9fF.js → pm.CagBA-ht.js} +2 -2
  62. package/dist/_astro/{portal.Cm9XlIPf.js → portal.C0hAhXDF.js} +2 -2
  63. package/dist/_astro/prompts-meta.Bua-j14I.js +2 -0
  64. package/dist/_astro/react-dom.DLW9pGCF.js +1 -0
  65. package/dist/_astro/{react-dom.CqAxpHMt.js → react.Blvh0GOs.js} +1 -1
  66. package/dist/_astro/report-prompt.CAfZ6RIo.js +1 -0
  67. package/dist/_astro/{settings.C6NWuiFO.js → settings.Ceefeil5.js} +2 -2
  68. package/dist/_astro/{spaces-client.k_ciWMai.js → spaces-client.BocUabwy.js} +1 -1
  69. package/dist/_astro/ui-auto-prompt.CX8fju7r.js +3 -0
  70. package/dist/_astro/ui-auto.BmC9JJ_X.js +1 -0
  71. package/dist/_astro/update.CtF8vsag.js +1 -0
  72. package/dist/_astro/use-text-value.DBQvHeNl.js +1 -0
  73. package/dist/_astro/use-tree-walker.DFU2AaAP.js +1 -0
  74. package/dist/_astro/useListAnim.BoerpmsB.js +1 -0
  75. package/dist/_astro/{view-prefs.Dyu_lmN2.js → view-prefs.BEAZRcxF.js} +1 -1
  76. package/dist/case-exec/index.html +458 -22
  77. package/dist/cases/generate/index.html +258 -22
  78. package/dist/cases/library/index.html +458 -22
  79. package/dist/dashboard/index.html +458 -22
  80. package/dist/docs/changelog/index.html +373 -23
  81. package/dist/docs/install/index.html +258 -22
  82. package/dist/docs/manual/index.html +314 -35
  83. package/dist/index.html +2 -281
  84. package/dist/knowledge/index.html +458 -22
  85. package/dist/knowledge//345/212/237/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/347/274/226/345/206/231/350/247/204/350/214/203/index.html +258 -22
  86. package/dist/plugins/index.html +258 -22
  87. package/dist/pm/bugs/index.html +458 -22
  88. package/dist/pm/iterations/index.html +458 -22
  89. package/dist/pm/projects/detail/index.html +458 -22
  90. package/dist/pm/projects/index.html +458 -22
  91. package/dist/pm/requirements/index.html +458 -22
  92. package/dist/prompts/index.html +458 -22
  93. package/dist/reports/index.html +458 -22
  94. package/dist/requirements/index.html +458 -22
  95. package/dist/tasks/index.html +458 -22
  96. package/dist/templates/index.html +458 -22
  97. package/dist/templates//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +258 -22
  98. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +258 -22
  99. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +258 -22
  100. package/dist/templates//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +258 -22
  101. package/dist/templates//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +258 -22
  102. package/dist/test-automation/index.html +717 -0
  103. package/dist/test-stats/index.html +458 -22
  104. package/dist/todos/index.html +458 -22
  105. package/dist/workbench/index.html +517 -0
  106. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +80 -43
  107. package/lh-plugins/lh-project-docs.mjs +14 -0
  108. package/lh-plugins/lh-uiauto.mjs +1445 -386
  109. package/lh-plugins/plugin-prompts.mjs +200 -0
  110. package/lh-plugins/storage-domain.mjs +6 -0
  111. package/lh-plugins/uiauto-adapters/index.mjs +57 -0
  112. package/lh-plugins/uiauto-adapters/playwright.mjs +215 -0
  113. package/lh-plugins/uiauto-adapters/pytest.mjs +151 -0
  114. package/lh-plugins/uiauto-adapters/selenium.mjs +163 -0
  115. package/lh-plugins/uiauto-adapters/shared.mjs +371 -0
  116. package/lh-plugins/uiauto-adapters/tasks.mjs +369 -0
  117. package/lh-plugins/uiauto-explorer/apps.mjs +332 -0
  118. package/lh-plugins/uiauto-explorer/diff.mjs +159 -0
  119. package/lh-plugins/uiauto-explorer/emit-files.mjs +506 -0
  120. package/lh-plugins/uiauto-explorer/emit-python.mjs +160 -0
  121. package/lh-plugins/uiauto-explorer/emit-ts.mjs +118 -0
  122. package/lh-plugins/uiauto-explorer/emit.mjs +15 -0
  123. package/lh-plugins/uiauto-explorer/ir.mjs +114 -0
  124. package/lh-plugins/uiauto-explorer/locators.mjs +267 -0
  125. package/lh-plugins/uiauto-explorer/merge.mjs +235 -0
  126. package/lh-plugins/uiauto-explorer/plan.mjs +165 -0
  127. package/lh-plugins/uiauto-explorer/runner.mjs +370 -0
  128. package/lh-plugins/uiauto-explorer/sessions.mjs +1373 -0
  129. package/lh-plugins/uiauto-explorer/snapshot.mjs +492 -0
  130. package/lh-plugins/uiauto-prompt.mjs +122 -0
  131. package/lh-plugins/uiauto-report.mjs +111 -0
  132. package/package.json +1 -1
  133. package/dist/_astro/Base.4X_wsSoR.css +0 -1
  134. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.Dy7fJoxu.js +0 -1
  135. package/dist/_astro/CaseExecBoard.DKdfW5fM.js +0 -1
  136. package/dist/_astro/CaseGenerateApp.Bm8AyH9s.js +0 -9
  137. package/dist/_astro/CasesLibrary.CvVJZ74h.js +0 -1
  138. package/dist/_astro/ChatApp.BS-wLBRa.js +0 -276
  139. package/dist/_astro/ColumnResize.Bs6GL3DJ.js +0 -1
  140. package/dist/_astro/DatePicker.CMfX7F6z.js +0 -1
  141. package/dist/_astro/DocsFileBrowser.BtRoZ787.js +0 -1
  142. package/dist/_astro/DocsPager.C20ue_JZ.js +0 -1
  143. package/dist/_astro/KnowledgeLibrary.CV4DyStj.js +0 -1
  144. package/dist/_astro/NamePromptDialog.Dl5kSnQI.js +0 -1
  145. package/dist/_astro/NavLibraries.DmD2lZBZ.js +0 -1
  146. package/dist/_astro/OverflowHint.lzmplP5j.js +0 -1
  147. package/dist/_astro/PluginsPage.B59AMDrB.js +0 -1
  148. package/dist/_astro/PluginsPage.BEAPymNL.js +0 -39
  149. package/dist/_astro/PmBugsBoard.CPEyBp0l.js +0 -1
  150. package/dist/_astro/PmIterationsBoard.zCeLpcBo.js +0 -1
  151. package/dist/_astro/PmProjectDetail.ejIam5sD.js +0 -1
  152. package/dist/_astro/PmProjectsBoard.DbXzir8o.js +0 -1
  153. package/dist/_astro/PmRequirementsBoard.CynewRfv.js +0 -1
  154. package/dist/_astro/PmRequirementsBoard.D9eUMJWI.js +0 -1
  155. package/dist/_astro/PmShared.BxTHKdjY.js +0 -1
  156. package/dist/_astro/PromptsLibrary.Bkruu80b.js +0 -1
  157. package/dist/_astro/ReportsPage.BoBQshMQ.js +0 -1
  158. package/dist/_astro/RequirementsLibrary.BC0A8qdk.js +0 -1
  159. package/dist/_astro/SearchableSelect.CXa1hiDd.js +0 -1
  160. package/dist/_astro/SelectDropdown.Buv7rQJ_.js +0 -1
  161. package/dist/_astro/SettingsDialog.Dc-9QNJI.js +0 -1
  162. package/dist/_astro/SlideOverDrawer.TPbGEoWn.js +0 -1
  163. package/dist/_astro/TagSelect.u8DTop7v.js +0 -1
  164. package/dist/_astro/TasksBoard.Bb--oVV8.js +0 -1
  165. package/dist/_astro/TemplatesLibrary.D1wZq94E.js +0 -1
  166. package/dist/_astro/TestStatsBoard.DlVezlXl.js +0 -1
  167. package/dist/_astro/TodosBoard.S84wqcWY.js +0 -1
  168. package/dist/_astro/UiAutoBoard.BKp9ifxg.js +0 -1
  169. package/dist/_astro/active-element-history.CeefGkFQ.js +0 -1
  170. package/dist/_astro/app-config.DUyozIL9.js +0 -1
  171. package/dist/_astro/dialog.DXHznyjD.js +0 -1
  172. package/dist/_astro/jsx-runtime.BUXbF_vF.js +0 -1
  173. package/dist/_astro/listbox.Di-t5U37.js +0 -1
  174. package/dist/_astro/menu.Bkluqxic.js +0 -1
  175. package/dist/_astro/prompts-meta.F4wwkjUA.js +0 -2
  176. package/dist/_astro/report-prompt.Cmw4XzfY.js +0 -1
  177. package/dist/_astro/update.Bl_HfSe6.js +0 -1
  178. package/dist/_astro/use-text-value.BuY0Cm1z.js +0 -1
  179. package/dist/_astro/use-tree-walker.CfTHFX43.js +0 -1
  180. package/dist/_astro/useListAnim.CpGB1cft.js +0 -1
  181. package/dist/ui-automation/index.html +0 -281
@@ -0,0 +1,160 @@
1
+ /**
2
+ * IR → pytest + playwright.sync_api
3
+ *
4
+ * 依赖项目自己的 pytest-playwright(提供 `page` fixture)。
5
+ * 浏览器二进制可以直接复用 Playwright 的全局缓存,不必重新下载。
6
+ */
7
+ import { pythonFunctionName, slugify, splitEnvValue } from './ir.mjs';
8
+
9
+ const q = (value) => JSON.stringify(String(value ?? ''));
10
+
11
+ const PY_KEYWORDS = new Set([
12
+ 'False',
13
+ 'None',
14
+ 'True',
15
+ 'and',
16
+ 'as',
17
+ 'assert',
18
+ 'async',
19
+ 'await',
20
+ 'break',
21
+ 'class',
22
+ 'continue',
23
+ 'def',
24
+ 'del',
25
+ 'elif',
26
+ 'else',
27
+ 'except',
28
+ 'finally',
29
+ 'for',
30
+ 'from',
31
+ 'global',
32
+ 'if',
33
+ 'import',
34
+ 'in',
35
+ 'is',
36
+ 'lambda',
37
+ 'nonlocal',
38
+ 'not',
39
+ 'or',
40
+ 'pass',
41
+ 'raise',
42
+ 'return',
43
+ 'try',
44
+ 'while',
45
+ 'with',
46
+ 'yield',
47
+ ]);
48
+
49
+ function locatorCode(spec, owner = 'page') {
50
+ const base = (() => {
51
+ if (spec.kind === 'testid') return `${owner}.get_by_test_id(${q(spec.value)})`;
52
+ if (spec.kind === 'role') {
53
+ if (!spec.name) return `${owner}.get_by_role(${q(spec.role)})`;
54
+ const exact = spec.exact ? ', exact=True' : '';
55
+ return `${owner}.get_by_role(${q(spec.role)}, name=${q(spec.name)}${exact})`;
56
+ }
57
+ if (spec.kind === 'label') {
58
+ return `${owner}.get_by_label(${q(spec.value)}${spec.exact ? ', exact=True' : ''})`;
59
+ }
60
+ if (spec.kind === 'placeholder') {
61
+ return `${owner}.get_by_placeholder(${q(spec.value)}${spec.exact ? ', exact=True' : ''})`;
62
+ }
63
+ if (spec.kind === 'text') {
64
+ return `${owner}.get_by_text(${q(spec.value)}${spec.exact ? ', exact=True' : ''})`;
65
+ }
66
+ if (spec.kind === 'attr') {
67
+ const body = `[${spec.attr}="${String(spec.value).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"]`;
68
+ return `${owner}.locator(${q(body)})`;
69
+ }
70
+ return `${owner}.locator(${q(spec.value)})`;
71
+ })();
72
+ if (spec.nth == null) return base;
73
+ return spec.nth === 0 ? `${base}.first` : `${base}.nth(${spec.nth})`;
74
+ }
75
+
76
+ function valueCode(value) {
77
+ const env = splitEnvValue(value);
78
+ if (env) return `os.environ.get(${q(env)}, "")`;
79
+ return q(value ?? '');
80
+ }
81
+
82
+ function stepCode(step, index, ir) {
83
+ const target = step.locator ? locatorCode(step.locator) : '';
84
+ const url = (value) =>
85
+ ir.baseURL && String(value ?? '/').startsWith('/')
86
+ ? `BASE_URL + ${q(value ?? '/')}`
87
+ : q(value ?? '/');
88
+ switch (step.action) {
89
+ case 'goto':
90
+ return ` page.goto(${url(step.url)})`;
91
+ case 'click':
92
+ return ` ${target}.click()`;
93
+ case 'fill':
94
+ return ` ${target}.fill(${valueCode(step.value)})`;
95
+ case 'select':
96
+ return ` ${target}.select_option(${valueCode(step.value)})`;
97
+ case 'press':
98
+ return step.locator
99
+ ? ` ${target}.press(${q(step.key ?? 'Enter')})`
100
+ : ` page.keyboard.press(${q(step.key ?? 'Enter')})`;
101
+ case 'hover':
102
+ return ` ${target}.hover()`;
103
+ case 'expect': {
104
+ if (step.text) return ` expect(${target}).to_contain_text(${valueCode(step.text)})`;
105
+ if (step.state === 'hidden') return ` expect(${target}).to_be_hidden()`;
106
+ return ` expect(${target}).to_be_visible()`;
107
+ }
108
+ case 'expectUrl':
109
+ return ` expect(page).to_have_url(${url(step.url)})`;
110
+ case 'wait':
111
+ return ` page.wait_for_timeout(${Number(step.ms) || 500})`;
112
+ case 'screenshot': {
113
+ const name = String(step.value ?? `step-${index + 1}`)
114
+ .replace(/[^\w.-]+/g, '-')
115
+ .replace(/^-+|-+$/g, '');
116
+ return ` page.screenshot(path=${q(`reports/ai/${name || `step-${index + 1}`}.png`)}, full_page=True)`;
117
+ }
118
+ default:
119
+ return '';
120
+ }
121
+ }
122
+
123
+ /** 生成 Python 脚本;`ir` 需先过 normalizeIr */
124
+ export function renderPython(ir) {
125
+ const title = ir.title || 'AI 生成用例';
126
+ const funcName = PY_KEYWORDS.has(pythonFunctionName(title))
127
+ ? 'test_ai_generated'
128
+ : pythonFunctionName(title);
129
+ const lines = [];
130
+ lines.push('"""');
131
+ lines.push(title);
132
+ if (ir.source) {
133
+ for (const line of String(ir.source).split(/\r?\n/).slice(0, 8)) {
134
+ lines.push(line.trim());
135
+ }
136
+ }
137
+ lines.push('"""');
138
+ lines.push('import os');
139
+ lines.push('');
140
+ lines.push('from playwright.sync_api import Page, expect');
141
+ if (ir.baseURL) {
142
+ lines.push('');
143
+ // 相对路径靠这里拼成完整地址:不依赖项目的 pytest-playwright --base-url 配置
144
+ lines.push(`BASE_URL = os.environ.get("BASE_URL", ${q(ir.baseURL)})`);
145
+ }
146
+ lines.push('');
147
+ lines.push('');
148
+ lines.push(`def ${funcName}(page: Page) -> None:`);
149
+ for (let index = 0; index < ir.steps.length; index += 1) {
150
+ const step = ir.steps[index];
151
+ if (step.note) lines.push(` # ${step.note.replace(/\s+/g, ' ').slice(0, 160)}`);
152
+ const code = stepCode(step, index, ir);
153
+ if (code) lines.push(code);
154
+ }
155
+ if (!ir.steps.length) lines.push(' pass');
156
+ lines.push('');
157
+ return { code: lines.join('\n'), filename: `${funcName}.py`, language: 'python' };
158
+ }
159
+
160
+ export { slugify, locatorCode, valueCode };
@@ -0,0 +1,118 @@
1
+ /**
2
+ * IR → Playwright Test(TypeScript)
3
+ */
4
+ import { pythonFunctionName, slugify, splitEnvValue } from './ir.mjs';
5
+
6
+ const q = (value) => JSON.stringify(String(value ?? ''));
7
+
8
+ function locatorCode(spec, owner = 'page') {
9
+ const base = (() => {
10
+ if (spec.kind === 'testid') return `${owner}.getByTestId(${q(spec.value)})`;
11
+ if (spec.kind === 'role') {
12
+ if (!spec.name) return `${owner}.getByRole(${q(spec.role)})`;
13
+ const exact = spec.exact ? ', exact: true' : '';
14
+ return `${owner}.getByRole(${q(spec.role)}, { name: ${q(spec.name)}${exact} })`;
15
+ }
16
+ if (spec.kind === 'label') {
17
+ return `${owner}.getByLabel(${q(spec.value)}${spec.exact ? ', { exact: true }' : ''})`;
18
+ }
19
+ if (spec.kind === 'placeholder') {
20
+ return `${owner}.getByPlaceholder(${q(spec.value)}${spec.exact ? ', { exact: true }' : ''})`;
21
+ }
22
+ if (spec.kind === 'text') {
23
+ return `${owner}.getByText(${q(spec.value)}${spec.exact ? ', { exact: true }' : ''})`;
24
+ }
25
+ if (spec.kind === 'attr') {
26
+ const body = `[${spec.attr}="${String(spec.value).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"]`;
27
+ return `${owner}.locator(${q(body)})`;
28
+ }
29
+ return `${owner}.locator(${q(spec.value)})`;
30
+ })();
31
+ if (spec.nth == null) return base;
32
+ return spec.nth === 0 ? `${base}.first()` : `${base}.nth(${spec.nth})`;
33
+ }
34
+
35
+ function valueCode(value) {
36
+ const env = splitEnvValue(value);
37
+ if (env) return `process.env.${env} ?? ''`;
38
+ return q(value ?? '');
39
+ }
40
+
41
+ function stepCode(step, index) {
42
+ const target = step.locator ? locatorCode(step.locator) : '';
43
+ switch (step.action) {
44
+ case 'goto':
45
+ return ` await page.goto(${q(step.url ?? '/')});`;
46
+ case 'click':
47
+ return ` await ${target}.click();`;
48
+ case 'fill':
49
+ return ` await ${target}.fill(${valueCode(step.value)});`;
50
+ case 'select':
51
+ return ` await ${target}.selectOption(${valueCode(step.value)});`;
52
+ case 'press':
53
+ return step.locator
54
+ ? ` await ${target}.press(${q(step.key ?? 'Enter')});`
55
+ : ` await page.keyboard.press(${q(step.key ?? 'Enter')});`;
56
+ case 'hover':
57
+ return ` await ${target}.hover();`;
58
+ case 'expect': {
59
+ if (step.text) return ` await expect(${target}).toContainText(${valueCode(step.text)});`;
60
+ if (step.state === 'hidden') return ` await expect(${target}).toBeHidden();`;
61
+ return ` await expect(${target}).toBeVisible();`;
62
+ }
63
+ case 'expectUrl':
64
+ return ` await expect(page).toHaveURL(${valueCode(step.url ?? '/')});`;
65
+ case 'wait':
66
+ return ` await page.waitForTimeout(${Number(step.ms) || 500});`;
67
+ case 'screenshot': {
68
+ const name = String(step.value ?? `step-${index + 1}`)
69
+ .replace(/[^\w.-]+/g, '-')
70
+ .replace(/^-+|-+$/g, '');
71
+ return ` await page.screenshot({ path: ${q(
72
+ `reports/ai/${name || `step-${index + 1}`}.png`,
73
+ )}, fullPage: true });`;
74
+ }
75
+ default:
76
+ return '';
77
+ }
78
+ }
79
+
80
+ /** 生成 TS 脚本;`ir` 需先过 normalizeIr */
81
+ export function renderTs(ir) {
82
+ const title = ir.title || 'AI 生成用例';
83
+ const lines = [];
84
+ lines.push('/**');
85
+ lines.push(` * ${title}`);
86
+ if (ir.source) {
87
+ for (const line of String(ir.source).split(/\r?\n/).slice(0, 8)) {
88
+ lines.push(` * ${line.trim()}`);
89
+ }
90
+ }
91
+ lines.push(' */');
92
+ lines.push("import { test, expect } from '@playwright/test';");
93
+ lines.push('');
94
+ const useOptions = [];
95
+ if (ir.baseURL) useOptions.push(`baseURL: ${q(ir.baseURL)}`);
96
+ // 探索时复用了登录态,生成的脚本也要带上,否则写回项目后第一步就卡登录
97
+ if (ir.storageState) useOptions.push(`storageState: ${q(ir.storageState)}`);
98
+ if (useOptions.length) {
99
+ // 不依赖项目 config 有没有配:写死到本文件,换环境改这一行即可
100
+ lines.push(`test.use({ ${useOptions.join(', ')} });`);
101
+ lines.push('');
102
+ }
103
+ lines.push(`test.describe(${q(title)}, () => {`);
104
+ lines.push(` test(${q(title)}, async ({ page }) => {`);
105
+ if (ir.baseURL) lines.push(` // baseURL: ${ir.baseURL}`);
106
+ for (let index = 0; index < ir.steps.length; index += 1) {
107
+ const step = ir.steps[index];
108
+ if (step.note) lines.push(` // ${step.note.replace(/\s+/g, ' ').slice(0, 160)}`);
109
+ const code = stepCode(step, index);
110
+ if (code) lines.push(code);
111
+ }
112
+ lines.push(' });');
113
+ lines.push('});');
114
+ lines.push('');
115
+ return { code: lines.join('\n'), filename: `${slugify(title)}.spec.ts`, language: 'ts' };
116
+ }
117
+
118
+ export { pythonFunctionName, locatorCode, valueCode };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * 出码调度:同一份 IR 按目标语言渲染。
3
+ */
4
+ import { normalizeIr } from './ir.mjs';
5
+ import { renderTs } from './emit-ts.mjs';
6
+ import { renderPython } from './emit-python.mjs';
7
+
8
+ export function emitCode(rawIr, target) {
9
+ const ir = normalizeIr(rawIr, { target });
10
+ const language = target === 'python' || ir.target === 'python' ? 'python' : 'ts';
11
+ const rendered = language === 'python' ? renderPython(ir) : renderTs(ir);
12
+ return { ...rendered, ir: { ...ir, target: language } };
13
+ }
14
+
15
+ export { normalizeIr };
@@ -0,0 +1,114 @@
1
+ /**
2
+ * 步骤 IR:AI 只产出「做什么 + 定位谁」,代码由模板渲染。
3
+ *
4
+ * 为什么不让模型直接写脚本:
5
+ * - 同一份 IR 可以同时出 TS 与 Python,换语言不用重跑模型
6
+ * - 试跑失败后模型只需要改一个字段(定位器 / 等待),改代码容易牵一发动全身
7
+ * - 代码风格、转义、环境变量读取都由模板保证,不受模型心情影响
8
+ */
9
+
10
+ /** 允许的步骤动作 */
11
+ export const STEP_ACTIONS = [
12
+ 'goto',
13
+ 'click',
14
+ 'fill',
15
+ 'select',
16
+ 'press',
17
+ 'hover',
18
+ 'expect',
19
+ 'expectUrl',
20
+ 'wait',
21
+ 'screenshot',
22
+ ];
23
+
24
+ const LOCATOR_ACTIONS = new Set(['click', 'fill', 'select', 'press', 'hover', 'expect']);
25
+
26
+ /** 需要定位器的动作里,没给 locator 的直接丢掉,避免生成必崩的脚本 */
27
+ export function normalizeIr(raw, fallback = {}) {
28
+ const source = raw && typeof raw === 'object' ? raw : {};
29
+ const steps = Array.isArray(source.steps) ? source.steps : [];
30
+ const normalized = [];
31
+ for (const step of steps) {
32
+ if (!step || typeof step !== 'object') continue;
33
+ const action = String(step.action ?? '').trim();
34
+ if (!STEP_ACTIONS.includes(action)) continue;
35
+ const locator = normalizeLocator(step.locator);
36
+ if (LOCATOR_ACTIONS.has(action) && !locator) continue;
37
+ normalized.push({
38
+ action,
39
+ locator: locator || undefined,
40
+ url: typeof step.url === 'string' ? step.url : undefined,
41
+ value: step.value == null ? undefined : String(step.value),
42
+ key: typeof step.key === 'string' ? step.key : undefined,
43
+ text: typeof step.text === 'string' ? step.text : undefined,
44
+ state: step.state === 'hidden' ? 'hidden' : step.state === 'visible' ? 'visible' : undefined,
45
+ ms: Number.isFinite(Number(step.ms)) ? Math.max(0, Number(step.ms)) : undefined,
46
+ note: typeof step.note === 'string' ? step.note.slice(0, 200) : undefined,
47
+ // 只用于把 IR 与左侧计划对齐,出码时忽略
48
+ planStepId: typeof step.planStepId === 'string' ? step.planStepId.slice(0, 40) : undefined,
49
+ });
50
+ }
51
+ return {
52
+ title: String(source.title ?? fallback.title ?? '未命名流程').slice(0, 120),
53
+ target: (source.target ?? fallback.target) === 'python' ? 'python' : 'ts',
54
+ baseURL: String(source.baseURL ?? fallback.baseURL ?? ''),
55
+ storageState: String(source.storageState ?? fallback.storageState ?? ''),
56
+ source: String(source.source ?? fallback.source ?? '').slice(0, 2000),
57
+ steps: normalized,
58
+ };
59
+ }
60
+
61
+ export function normalizeLocator(raw) {
62
+ if (!raw || typeof raw !== 'object') return null;
63
+ const kind = String(raw.kind ?? '').trim();
64
+ if (!['testid', 'role', 'label', 'placeholder', 'text', 'attr', 'css'].includes(kind))
65
+ return null;
66
+ const spec = { kind };
67
+ if (kind === 'role') {
68
+ const role = String(raw.role ?? '').trim();
69
+ if (!role) return null;
70
+ spec.role = role;
71
+ if (raw.name != null && String(raw.name).trim()) {
72
+ spec.name = String(raw.name).trim();
73
+ spec.exact = raw.exact !== false;
74
+ }
75
+ } else if (kind === 'attr') {
76
+ const attr = String(raw.attr ?? '').trim();
77
+ const value = String(raw.value ?? '').trim();
78
+ if (!attr || !value) return null;
79
+ spec.attr = attr;
80
+ spec.value = value;
81
+ } else {
82
+ const value = String(raw.value ?? '').trim();
83
+ if (!value) return null;
84
+ spec.value = value;
85
+ if (kind === 'label' || kind === 'placeholder' || kind === 'text') {
86
+ spec.exact = raw.exact !== false;
87
+ }
88
+ }
89
+ if (Number.isInteger(raw.nth) && Number(raw.nth) >= 0) spec.nth = Number(raw.nth);
90
+ return spec;
91
+ }
92
+
93
+ /** `${NAME}` 这类占位符 → 环境变量读取,避免把账号写死进脚本 */
94
+ export function splitEnvValue(value) {
95
+ const text = String(value ?? '');
96
+ const match = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(text.trim());
97
+ return match ? match[1] : '';
98
+ }
99
+
100
+ /** 标题 → 文件名(ASCII,避免不同系统对中文文件名的处理差异) */
101
+ export function slugify(title) {
102
+ const ascii = String(title ?? '')
103
+ .toLowerCase()
104
+ .replace(/[^a-z0-9]+/g, '-')
105
+ .replace(/^-+|-+$/g, '')
106
+ .slice(0, 48);
107
+ if (ascii) return ascii;
108
+ return 'ai-generated';
109
+ }
110
+
111
+ export function pythonFunctionName(title) {
112
+ const slug = slugify(title).replace(/-/g, '_');
113
+ return `test_${slug || 'ai_generated'}`;
114
+ }
@@ -0,0 +1,267 @@
1
+ /**
2
+ * 定位器候选:把探索期的临时 ref 转成「能写进脚本」的 Playwright locator。
3
+ *
4
+ * 顺序遵循官方建议:testid → role+name → label → placeholder → text → 稳定属性 → 短 CSS。
5
+ * 每个候选都要过两道校验:
6
+ * 1. count() === 1 —— 唯一,脚本里不会点错元素
7
+ * 2. 命中的元素就是刚才 ref 指的那个 —— 语义对得上,不是碰巧同名
8
+ * 校验不通过的候选只保留信息,不会被推荐。
9
+ */
10
+
11
+ /** 候选类型的默认权重,越大越稳 */
12
+ const KIND_SCORE = {
13
+ testid: 100,
14
+ role: 90,
15
+ label: 80,
16
+ placeholder: 70,
17
+ text: 60,
18
+ attr: 40,
19
+ css: 20,
20
+ };
21
+
22
+ const ROLE_NAME_REQUIRED = new Set(['button', 'link', 'tab', 'menuitem', 'option', 'treeitem']);
23
+
24
+ function clean(value) {
25
+ return String(value ?? '')
26
+ .replace(/\s+/g, ' ')
27
+ .trim();
28
+ }
29
+
30
+ /** 纯函数:根据元素信息生成候选(不碰浏览器,方便单测) */
31
+ export function buildCandidateLocators(info) {
32
+ const list = [];
33
+ const push = (spec, source, score) => {
34
+ if (!spec) return;
35
+ const key = locatorKey(spec);
36
+ if (list.some((item) => locatorKey(item.locator) === key)) return;
37
+ list.push({ locator: spec, source, score });
38
+ };
39
+
40
+ const testId = clean(info.testId);
41
+ if (testId) push({ kind: 'testid', value: testId }, 'data-testid', KIND_SCORE.testid);
42
+
43
+ const role = clean(info.role);
44
+ const name = clean(info.name);
45
+ if (role && (!ROLE_NAME_REQUIRED.has(role) || name)) {
46
+ if (name) {
47
+ push({ kind: 'role', role, name, exact: true }, 'role + 精确名称', KIND_SCORE.role);
48
+ push({ kind: 'role', role, name, exact: false }, 'role + 模糊名称', KIND_SCORE.role - 10);
49
+ } else {
50
+ push({ kind: 'role', role }, `role=${role}`, KIND_SCORE.role - 30);
51
+ }
52
+ }
53
+
54
+ const label = clean(info.labelText);
55
+ if (label) {
56
+ push({ kind: 'label', value: label, exact: true }, 'label 精确', KIND_SCORE.label);
57
+ push({ kind: 'label', value: label, exact: false }, 'label 模糊', KIND_SCORE.label - 10);
58
+ }
59
+
60
+ const placeholder = clean(info.placeholder);
61
+ if (placeholder && placeholder !== name) {
62
+ push(
63
+ { kind: 'placeholder', value: placeholder, exact: true },
64
+ 'placeholder 精确',
65
+ KIND_SCORE.placeholder,
66
+ );
67
+ }
68
+
69
+ const text = clean(info.text);
70
+ const textInput = role === 'textbox' || role === 'combobox' || role === 'searchbox';
71
+ if (text && text.length <= 40 && !textInput) {
72
+ push({ kind: 'text', value: text, exact: true }, 'text 精确', KIND_SCORE.text);
73
+ }
74
+
75
+ const nameAttr = clean(info.nameAttr);
76
+ if (nameAttr && info.tag !== 'a') {
77
+ push({ kind: 'attr', attr: 'name', value: nameAttr }, 'name 属性', KIND_SCORE.attr);
78
+ }
79
+
80
+ const href = clean(info.href);
81
+ if (href && !href.startsWith('#') && href.length <= 80) {
82
+ push({ kind: 'attr', attr: 'href', value: href }, 'href 属性', KIND_SCORE.attr - 5);
83
+ }
84
+
85
+ const ariaLabel = clean(info.ariaLabel);
86
+ if (ariaLabel && ariaLabel !== name) {
87
+ push(
88
+ { kind: 'attr', attr: 'aria-label', value: ariaLabel },
89
+ 'aria-label 属性',
90
+ KIND_SCORE.attr,
91
+ );
92
+ }
93
+
94
+ const cssPath = clean(info.cssPath);
95
+ if (cssPath) {
96
+ push({ kind: 'css', value: cssPath }, '短 CSS 路径', KIND_SCORE.css);
97
+ }
98
+
99
+ return list.sort((a, b) => b.score - a.score);
100
+ }
101
+
102
+ /** 结构化 locator → 稳定字符串(去重 / 展示用) */
103
+ export function locatorKey(spec) {
104
+ if (!spec || typeof spec !== 'object') return '';
105
+ const parts = [spec.kind];
106
+ if (spec.role) parts.push(spec.role);
107
+ if (spec.name != null) parts.push(`name=${spec.name}`, spec.exact ? 'exact' : 'loose');
108
+ if (spec.value != null) parts.push(`value=${spec.value}`, spec.exact ? 'exact' : 'loose');
109
+ if (spec.attr) parts.push(`${spec.attr}=${spec.value}`);
110
+ if (spec.nth != null) parts.push(`nth=${spec.nth}`);
111
+ return parts.join('|');
112
+ }
113
+
114
+ /** 结构化 locator → Playwright Locator(Node 侧) */
115
+ export function buildLocator(page, spec) {
116
+ if (!spec || !spec.kind) throw new Error('定位器缺少 kind');
117
+ if (spec.kind === 'testid') return page.getByTestId(spec.value);
118
+ if (spec.kind === 'role') {
119
+ const options = {};
120
+ if (spec.name != null && spec.name !== '') {
121
+ options.name = spec.name;
122
+ options.exact = Boolean(spec.exact);
123
+ }
124
+ return page.getByRole(spec.role, options);
125
+ }
126
+ if (spec.kind === 'label') return page.getByLabel(spec.value, { exact: Boolean(spec.exact) });
127
+ if (spec.kind === 'placeholder') {
128
+ return page.getByPlaceholder(spec.value, { exact: Boolean(spec.exact) });
129
+ }
130
+ if (spec.kind === 'text') return page.getByText(spec.value, { exact: Boolean(spec.exact) });
131
+ if (spec.kind === 'attr') {
132
+ const value = String(spec.value ?? '')
133
+ .replace(/\\/g, '\\\\')
134
+ .replace(/"/g, '\\"');
135
+ return page.locator(`[${spec.attr}="${value}"]`);
136
+ }
137
+ if (spec.kind === 'css') return page.locator(spec.value);
138
+ throw new Error(`不支持的定位器类型:${spec.kind}`);
139
+ }
140
+
141
+ /** 长 CSS / 多层 nth-of-type 换一次渲染就可能失效,不能当 high confidence */
142
+ export function isFragileLocator(spec) {
143
+ if (!spec) return false;
144
+ if (spec.kind !== 'css') return false;
145
+ const value = String(spec.value ?? '');
146
+ const nth = (value.match(/nth-of-type/g) || []).length;
147
+ const segments = value.split('>').length;
148
+ return nth >= 2 || segments >= 4;
149
+ }
150
+
151
+ /**
152
+ * 逐个校验候选。
153
+ * @param {import('playwright').Page} page
154
+ * @param {import('playwright').ElementHandle} element 目标元素(ref 解出来的)
155
+ * @param {{locator: Record<string, unknown>, source: string, score: number}[]} candidates
156
+ */
157
+ export async function verifyCandidates(page, element, candidates) {
158
+ const results = [];
159
+ for (const candidate of candidates) {
160
+ let count = 0;
161
+ let same = false;
162
+ let error = '';
163
+ try {
164
+ const locator = buildLocator(page, candidate.locator);
165
+ count = await locator.count();
166
+ if (count > 0) {
167
+ same = await locator.evaluateAll((nodes, target) => nodes.includes(target), element);
168
+ }
169
+ } catch (err) {
170
+ error = err instanceof Error ? err.message : String(err);
171
+ }
172
+ const unique = count === 1;
173
+ results.push({
174
+ locator: candidate.locator,
175
+ source: candidate.source,
176
+ count,
177
+ unique,
178
+ same,
179
+ error,
180
+ score: candidate.score,
181
+ });
182
+
183
+ // 同一元素在页面上有多个同名按钮时(列表行操作),用 nth 收窄:
184
+ // 这就是 Playwright codegen 的 `.first()` / `.nth(2)`,比长 CSS 稳定得多。
185
+ if (same && count > 1 && count <= 50) {
186
+ let index = -1;
187
+ try {
188
+ const locator = buildLocator(page, candidate.locator);
189
+ index = await locator.evaluateAll((nodes, target) => nodes.indexOf(target), element);
190
+ } catch {
191
+ index = -1;
192
+ }
193
+ if (index >= 0) {
194
+ results.push({
195
+ locator: { ...candidate.locator, nth: index },
196
+ source: `${candidate.source} · 第 ${index + 1} 个`,
197
+ count,
198
+ unique: true,
199
+ same: true,
200
+ error: '',
201
+ score: candidate.score - 25,
202
+ });
203
+ }
204
+ }
205
+ }
206
+
207
+ // 先按「唯一 + 指向同一元素」排,再按权重
208
+ results.sort((a, b) => {
209
+ const rank = (item) => (item.same && item.unique ? 2 : item.same ? 1 : 0);
210
+ if (rank(a) !== rank(b)) return rank(b) - rank(a);
211
+ return b.score - a.score;
212
+ });
213
+
214
+ const best = results.find((item) => item.same && item.unique) ?? null;
215
+ const fragile = best ? isFragileLocator(best.locator) : false;
216
+ const ordered = best?.locator?.nth != null;
217
+
218
+ return {
219
+ candidates: results,
220
+ recommended: best ? best.locator : null,
221
+ confidence: !best
222
+ ? results.some((item) => item.same)
223
+ ? 'medium'
224
+ : 'low'
225
+ : fragile
226
+ ? 'low'
227
+ : ordered
228
+ ? 'medium'
229
+ : 'high',
230
+ fragile: fragile || ordered,
231
+ warning: fragile
232
+ ? '只能靠长 CSS 定位(多层 nth-of-type),页面结构一变就失效;建议给元素加 data-testid'
233
+ : ordered
234
+ ? '同名元素有多个,靠页面顺序取第 N 个;列表顺序变动会失效'
235
+ : '',
236
+ };
237
+ }
238
+
239
+ /**
240
+ * 探测一个 ref 可用的定位器。
241
+ * @param {import('playwright').Page} page
242
+ * @param {{ describeElement: Function }} helpers
243
+ * @param {string} ref
244
+ */
245
+ export async function probeLocators(page, helpers, ref) {
246
+ const handle = await page.evaluateHandle((key) => {
247
+ const store = window.__lanternRefs;
248
+ return store ? (store.get(key) ?? null) : null;
249
+ }, ref);
250
+ const element = handle.asElement();
251
+ if (!element) {
252
+ await handle.dispose().catch(() => undefined);
253
+ throw new Error(`ref ${ref} 已失效(元素不在页面上),请重新获取快照`);
254
+ }
255
+ try {
256
+ const info = await helpers.describeElement(page, element);
257
+ const candidates = buildCandidateLocators(info);
258
+ const verified = await verifyCandidates(page, element, candidates);
259
+ return {
260
+ ref,
261
+ element: info,
262
+ ...verified,
263
+ };
264
+ } finally {
265
+ await element.dispose().catch(() => undefined);
266
+ }
267
+ }