@mizchi/vlmkit-generate 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.d.mts +26 -0
- package/dist/cli.mjs +181 -0
- package/dist/generate.d.mts +14 -0
- package/dist/generate.mjs +335 -0
- package/dist/index.d.mts +4 -0
- package/dist/index.mjs +3 -0
- package/{src/types.ts → dist/types.d.mts} +10 -12
- package/dist/types.mjs +1 -0
- package/dist/write.d.mts +46 -0
- package/dist/write.mjs +121 -0
- package/package.json +23 -8
- package/src/cli.ts +0 -213
- package/src/generate.ts +0 -424
- package/src/index.ts +0 -21
- package/src/write.ts +0 -177
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { GateCommand } from "./write.mjs";
|
|
2
|
+
import { GenerateDeps, GeneratorModelOptions } from "./types.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/cli.d.ts
|
|
5
|
+
interface GenerateCliArgs {
|
|
6
|
+
plan: string;
|
|
7
|
+
out: string;
|
|
8
|
+
rules?: string;
|
|
9
|
+
helperImportPath?: string;
|
|
10
|
+
seedTestPath?: string;
|
|
11
|
+
locatorInventory?: string;
|
|
12
|
+
requireScreenshots: boolean;
|
|
13
|
+
provider?: GeneratorModelOptions["provider"];
|
|
14
|
+
model?: string;
|
|
15
|
+
maxTokens?: number;
|
|
16
|
+
maxAttempts?: number;
|
|
17
|
+
overwrite: boolean;
|
|
18
|
+
runtimeGate?: boolean;
|
|
19
|
+
playwrightConfig?: string;
|
|
20
|
+
runtimeGateRuns?: number;
|
|
21
|
+
gateCommands: GateCommand[];
|
|
22
|
+
}
|
|
23
|
+
declare function parseGenerateCliArgs(argv: string[]): GenerateCliArgs;
|
|
24
|
+
declare function runGenerateCli(argv: string[], deps?: Partial<GenerateDeps>): Promise<number>;
|
|
25
|
+
//#endregion
|
|
26
|
+
export { GenerateCliArgs, parseGenerateCliArgs, runGenerateCli };
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { generatePlaywrightTestWithRetry } from "./generate.mjs";
|
|
3
|
+
import { GeneratedTestGateError, GeneratedTestWriteError, buildPlaywrightRuntimeGate, writeGeneratedTestFile } from "./write.mjs";
|
|
4
|
+
import { realpathSync } from "node:fs";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
//#region src/cli.ts
|
|
8
|
+
function parseGenerateCliArgs(argv) {
|
|
9
|
+
const args = {
|
|
10
|
+
requireScreenshots: true,
|
|
11
|
+
overwrite: false,
|
|
12
|
+
gateCommands: []
|
|
13
|
+
};
|
|
14
|
+
for (let i = 0; i < argv.length; i++) {
|
|
15
|
+
const arg = argv[i];
|
|
16
|
+
const next = () => {
|
|
17
|
+
const value = argv[++i];
|
|
18
|
+
if (!value) throw new Error(`Missing value for ${arg}`);
|
|
19
|
+
return value;
|
|
20
|
+
};
|
|
21
|
+
switch (arg) {
|
|
22
|
+
case "--plan":
|
|
23
|
+
args.plan = next();
|
|
24
|
+
break;
|
|
25
|
+
case "--out":
|
|
26
|
+
args.out = next();
|
|
27
|
+
break;
|
|
28
|
+
case "--rules":
|
|
29
|
+
args.rules = next();
|
|
30
|
+
break;
|
|
31
|
+
case "--helper-import":
|
|
32
|
+
args.helperImportPath = next();
|
|
33
|
+
break;
|
|
34
|
+
case "--seed":
|
|
35
|
+
args.seedTestPath = next();
|
|
36
|
+
break;
|
|
37
|
+
case "--locator-inventory":
|
|
38
|
+
args.locatorInventory = next();
|
|
39
|
+
break;
|
|
40
|
+
case "--no-screenshots":
|
|
41
|
+
args.requireScreenshots = false;
|
|
42
|
+
break;
|
|
43
|
+
case "--provider":
|
|
44
|
+
args.provider = parseProvider(next());
|
|
45
|
+
break;
|
|
46
|
+
case "--model":
|
|
47
|
+
args.model = next();
|
|
48
|
+
break;
|
|
49
|
+
case "--max-tokens":
|
|
50
|
+
args.maxTokens = parsePositiveInt(next(), arg);
|
|
51
|
+
break;
|
|
52
|
+
case "--max-attempts":
|
|
53
|
+
args.maxAttempts = parsePositiveInt(next(), arg);
|
|
54
|
+
break;
|
|
55
|
+
case "--overwrite":
|
|
56
|
+
args.overwrite = true;
|
|
57
|
+
break;
|
|
58
|
+
case "--runtime-gate":
|
|
59
|
+
args.runtimeGate = true;
|
|
60
|
+
break;
|
|
61
|
+
case "--playwright-config":
|
|
62
|
+
args.playwrightConfig = next();
|
|
63
|
+
break;
|
|
64
|
+
case "--runtime-gate-runs":
|
|
65
|
+
args.runtimeGateRuns = parsePositiveInt(next(), arg);
|
|
66
|
+
break;
|
|
67
|
+
case "--gate-command":
|
|
68
|
+
args.gateCommands.push({ command: next() });
|
|
69
|
+
break;
|
|
70
|
+
case "--help":
|
|
71
|
+
case "-h": throw new Error(GENERATE_USAGE);
|
|
72
|
+
default: throw new Error(`Unknown argument: ${arg}\n\n${GENERATE_USAGE}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (!args.plan) throw new Error(`--plan is required\n\n${GENERATE_USAGE}`);
|
|
76
|
+
if (!args.out) throw new Error(`--out is required\n\n${GENERATE_USAGE}`);
|
|
77
|
+
if (args.runtimeGate) args.gateCommands.push(buildPlaywrightRuntimeGate(args.playwrightConfig, args.runtimeGateRuns));
|
|
78
|
+
return args;
|
|
79
|
+
}
|
|
80
|
+
async function runGenerateCli(argv, deps) {
|
|
81
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
82
|
+
console.log(GENERATE_USAGE);
|
|
83
|
+
return 0;
|
|
84
|
+
}
|
|
85
|
+
let args;
|
|
86
|
+
try {
|
|
87
|
+
args = parseGenerateCliArgs(argv);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
console.error(error instanceof Error ? error.message : error);
|
|
90
|
+
return 1;
|
|
91
|
+
}
|
|
92
|
+
const result = await generatePlaywrightTestWithRetry(await buildGenerateInput(args), {
|
|
93
|
+
provider: args.provider,
|
|
94
|
+
model: args.model,
|
|
95
|
+
maxTokens: args.maxTokens
|
|
96
|
+
}, deps, { maxAttempts: args.maxAttempts });
|
|
97
|
+
if (result.diagnostics.length) {
|
|
98
|
+
console.error(`Invalid generated test after ${result.attempts} attempt(s):`);
|
|
99
|
+
for (const diagnostic of result.diagnostics) console.error(`- ${diagnostic}`);
|
|
100
|
+
return 2;
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
await writeGeneratedTestFile({
|
|
104
|
+
filePath: args.out,
|
|
105
|
+
source: result.source,
|
|
106
|
+
overwrite: args.overwrite,
|
|
107
|
+
gates: args.gateCommands
|
|
108
|
+
});
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error instanceof GeneratedTestWriteError) {
|
|
111
|
+
console.error(error.message);
|
|
112
|
+
return 1;
|
|
113
|
+
}
|
|
114
|
+
if (error instanceof GeneratedTestGateError) {
|
|
115
|
+
console.error(`Generated test gate failed: ${error.result.name}`);
|
|
116
|
+
if (error.result.stdout) console.error(error.result.stdout.trimEnd());
|
|
117
|
+
if (error.result.stderr) console.error(error.result.stderr.trimEnd());
|
|
118
|
+
return 2;
|
|
119
|
+
}
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
return 0;
|
|
123
|
+
}
|
|
124
|
+
async function buildGenerateInput(args) {
|
|
125
|
+
return {
|
|
126
|
+
planMarkdown: await readFile(args.plan, "utf8"),
|
|
127
|
+
rulesMarkdown: args.rules ? await readFile(args.rules, "utf8") : void 0,
|
|
128
|
+
testFilePath: args.out,
|
|
129
|
+
helperImportPath: args.helperImportPath,
|
|
130
|
+
seedTestPath: args.seedTestPath,
|
|
131
|
+
requireScreenshots: args.requireScreenshots,
|
|
132
|
+
locatorInventory: args.locatorInventory ? parseLocatorInventory(await readFile(args.locatorInventory, "utf8")) : void 0
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
function parseLocatorInventory(raw) {
|
|
136
|
+
return JSON.parse(raw);
|
|
137
|
+
}
|
|
138
|
+
function parseProvider(value) {
|
|
139
|
+
if (value === "anthropic" || value === "gemini" || value === "openrouter") return value;
|
|
140
|
+
throw new Error(`Invalid --provider: ${value}`);
|
|
141
|
+
}
|
|
142
|
+
function parsePositiveInt(value, flag) {
|
|
143
|
+
const parsed = Number(value);
|
|
144
|
+
if (!Number.isInteger(parsed) || parsed < 1) throw new Error(`${flag} must be a positive integer`);
|
|
145
|
+
return parsed;
|
|
146
|
+
}
|
|
147
|
+
const GENERATE_USAGE = `Usage: vlmkit-generate --plan <path> --out <path>
|
|
148
|
+
|
|
149
|
+
Options:
|
|
150
|
+
--rules <path> Additional generation rules markdown
|
|
151
|
+
--helper-import <path> Module path for gotoApp import (default: ./_helpers)
|
|
152
|
+
--seed <path> Seed test reference path
|
|
153
|
+
--locator-inventory <path>
|
|
154
|
+
JSON file with roles/labels/testIds/texts
|
|
155
|
+
--no-screenshots Do not require toHaveScreenshot assertions
|
|
156
|
+
--provider <name> anthropic | gemini | openrouter
|
|
157
|
+
--model <id> Provider model id
|
|
158
|
+
--max-tokens <n> LLM output token budget
|
|
159
|
+
--max-attempts <n> Retry attempts when diagnostics remain
|
|
160
|
+
--overwrite Allow replacing an existing output file
|
|
161
|
+
--runtime-gate Run the generated test after writing it
|
|
162
|
+
--playwright-config <path>
|
|
163
|
+
Playwright config path for --runtime-gate
|
|
164
|
+
--runtime-gate-runs <n> Run the Playwright runtime gate n times (default: 1)
|
|
165
|
+
--gate-command <cmd> Repeatable post-write gate; use {testFile} placeholder`;
|
|
166
|
+
if (isDirectRun()) runGenerateCli(process.argv.slice(2)).then((code) => {
|
|
167
|
+
process.exitCode = code;
|
|
168
|
+
}).catch((error) => {
|
|
169
|
+
console.error(error instanceof Error ? error.stack : error);
|
|
170
|
+
process.exitCode = 1;
|
|
171
|
+
});
|
|
172
|
+
function isDirectRun() {
|
|
173
|
+
if (!process.argv[1]) return false;
|
|
174
|
+
try {
|
|
175
|
+
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
|
176
|
+
} catch {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
//#endregion
|
|
181
|
+
export { parseGenerateCliArgs, runGenerateCli };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { GenerateDeps, GenerateInput, GenerateResult, GenerateRetryOptions, GeneratorModelOptions } from "./types.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/generate.d.ts
|
|
4
|
+
type ResolvedGeneratorModelOptions = GeneratorModelOptions & {
|
|
5
|
+
provider: NonNullable<GeneratorModelOptions["provider"]>;
|
|
6
|
+
};
|
|
7
|
+
declare function buildGeneratePrompt(input: GenerateInput): string;
|
|
8
|
+
declare function extractTypescriptSource(raw: string): string;
|
|
9
|
+
declare function validateGeneratedTestSource(source: string, input?: Pick<GenerateInput, "helperImportPath" | "requireScreenshots" | "locatorInventory">): string[];
|
|
10
|
+
declare function generatePlaywrightTest(input: GenerateInput, opts?: GeneratorModelOptions, deps?: Partial<GenerateDeps>): Promise<GenerateResult>;
|
|
11
|
+
declare function generatePlaywrightTestWithRetry(input: GenerateInput, opts?: GeneratorModelOptions, deps?: Partial<GenerateDeps>, retry?: GenerateRetryOptions): Promise<GenerateResult>;
|
|
12
|
+
declare function resolveGeneratorModelOptions(opts?: GeneratorModelOptions, env?: Record<string, string | undefined>): ResolvedGeneratorModelOptions;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { buildGeneratePrompt, extractTypescriptSource, generatePlaywrightTest, generatePlaywrightTestWithRetry, resolveGeneratorModelOptions, validateGeneratedTestSource };
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
import { createUnifiedLLMClient } from "@mizchi/vlmkit-ai";
|
|
2
|
+
import * as ts from "typescript";
|
|
3
|
+
//#region src/generate.ts
|
|
4
|
+
function buildGeneratePrompt(input) {
|
|
5
|
+
const helperImportPath = input.helperImportPath ?? "./_helpers";
|
|
6
|
+
const requireScreenshots = input.requireScreenshots ?? true;
|
|
7
|
+
return [
|
|
8
|
+
"You are a Playwright Test generator.",
|
|
9
|
+
"Write exactly one complete TypeScript Playwright spec file.",
|
|
10
|
+
"Output only the full file inside one ```ts code block.",
|
|
11
|
+
"",
|
|
12
|
+
`Target file: ${input.testFilePath}`,
|
|
13
|
+
input.seedTestPath ? `Seed test reference: ${input.seedTestPath}` : void 0,
|
|
14
|
+
"",
|
|
15
|
+
"Mandatory rules:",
|
|
16
|
+
"- Import `test` and `expect` from `@playwright/test`.",
|
|
17
|
+
`- Import and use \`gotoApp\` from \`${helperImportPath}\`; do not call \`page.goto\` directly.`,
|
|
18
|
+
"- Prefer role, label, and test id locators. Avoid CSS and XPath unless no semantic locator exists.",
|
|
19
|
+
"- For live-region roles such as `status`, `alert`, and `log`, use `getByRole(\"status\")` and assert text separately; do not pass a `name` filter.",
|
|
20
|
+
"- Keep comments sparse. Do not narrate obvious Playwright actions; comment only non-obvious locator or determinism constraints.",
|
|
21
|
+
"- Every visual assertion must also have semantic assertions.",
|
|
22
|
+
requireScreenshots ? "- Include deterministic `toHaveScreenshot()` checks for the start and goal states." : void 0,
|
|
23
|
+
input.locatorInventory ? formatLocatorInventory(input.locatorInventory) : void 0,
|
|
24
|
+
"",
|
|
25
|
+
input.rulesMarkdown?.trim() ? `Additional generation rules:\n${input.rulesMarkdown.trim()}` : void 0,
|
|
26
|
+
"",
|
|
27
|
+
`Plan:\n${input.planMarkdown.trim()}`
|
|
28
|
+
].filter((p) => Boolean(p)).join("\n");
|
|
29
|
+
}
|
|
30
|
+
function extractTypescriptSource(raw) {
|
|
31
|
+
let text = raw.trim();
|
|
32
|
+
for (let i = 0; i < 3; i++) {
|
|
33
|
+
const outer = stripOuterCodeFence(text);
|
|
34
|
+
if (outer !== null) {
|
|
35
|
+
text = outer;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
const fenced = text.match(/```(?:ts|typescript)?\r?\n([\s\S]*?)\r?\n```/i);
|
|
39
|
+
if (!fenced) break;
|
|
40
|
+
text = fenced[1].trim();
|
|
41
|
+
}
|
|
42
|
+
return text.trimEnd() + "\n";
|
|
43
|
+
}
|
|
44
|
+
function validateGeneratedTestSource(source, input = {}) {
|
|
45
|
+
const diagnostics = [];
|
|
46
|
+
if (/```/.test(source)) diagnostics.push("source contains markdown code fences");
|
|
47
|
+
if (countStandaloneCommentLines(source) >= 3) diagnostics.push("generated source has excessive comments; keep only non-obvious comments");
|
|
48
|
+
const sourceFile = ts.createSourceFile("generated.spec.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
49
|
+
const parseDiagnostics = sourceFile.parseDiagnostics ?? [];
|
|
50
|
+
for (const parseDiagnostic of parseDiagnostics) {
|
|
51
|
+
const message = ts.flattenDiagnosticMessageText(parseDiagnostic.messageText, " ");
|
|
52
|
+
diagnostics.push(`typescript syntax error: ${message}`);
|
|
53
|
+
}
|
|
54
|
+
const astInfo = collectGeneratedTestAstInfo(sourceFile, input.helperImportPath ?? "./_helpers");
|
|
55
|
+
if (!astInfo.hasPlaywrightImport) diagnostics.push("missing @playwright/test import");
|
|
56
|
+
else {
|
|
57
|
+
if (!astInfo.hasTestImport) diagnostics.push("missing test import from @playwright/test");
|
|
58
|
+
if (!astInfo.hasExpectImport) diagnostics.push("missing expect import from @playwright/test");
|
|
59
|
+
}
|
|
60
|
+
if (!astInfo.usesGotoApp) diagnostics.push("missing gotoApp usage");
|
|
61
|
+
if (!astInfo.usesExpect) diagnostics.push("missing expect assertions");
|
|
62
|
+
if (astInfo.usesPageGoto) diagnostics.push("direct page.goto is not allowed; use gotoApp(page)");
|
|
63
|
+
if ((input.requireScreenshots ?? true) && !astInfo.usesToHaveScreenshot) diagnostics.push("missing toHaveScreenshot assertions");
|
|
64
|
+
if (!astInfo.hasGotoAppImport) diagnostics.push(`missing gotoApp import from ${astInfo.helperImportPath}`);
|
|
65
|
+
diagnostics.push(...validateRoleLocatorUsage(astInfo.locators));
|
|
66
|
+
if (input.locatorInventory) diagnostics.push(...validateLocatorInventory(astInfo.locators, input.locatorInventory));
|
|
67
|
+
return diagnostics;
|
|
68
|
+
}
|
|
69
|
+
async function generatePlaywrightTest(input, opts, deps) {
|
|
70
|
+
const prompt = buildGeneratePrompt(input);
|
|
71
|
+
const res = await (deps?.complete ?? defaultComplete(opts))(prompt);
|
|
72
|
+
const source = extractTypescriptSource(res.content);
|
|
73
|
+
return {
|
|
74
|
+
source,
|
|
75
|
+
diagnostics: validateGeneratedTestSource(source, input),
|
|
76
|
+
attempts: 1,
|
|
77
|
+
costUsd: res.costUsd ?? 0,
|
|
78
|
+
provider: res.provider,
|
|
79
|
+
model: res.model
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
async function generatePlaywrightTestWithRetry(input, opts, deps, retry) {
|
|
83
|
+
const maxAttempts = normalizeMaxAttempts(retry?.maxAttempts);
|
|
84
|
+
const basePrompt = buildGeneratePrompt(input);
|
|
85
|
+
const complete = deps?.complete ?? defaultComplete(opts);
|
|
86
|
+
let prompt = basePrompt;
|
|
87
|
+
let totalCostUsd = 0;
|
|
88
|
+
let last;
|
|
89
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
90
|
+
const res = await complete(prompt);
|
|
91
|
+
totalCostUsd += res.costUsd ?? 0;
|
|
92
|
+
const source = extractTypescriptSource(res.content);
|
|
93
|
+
last = {
|
|
94
|
+
source,
|
|
95
|
+
diagnostics: validateGeneratedTestSource(source, input),
|
|
96
|
+
attempts: attempt,
|
|
97
|
+
costUsd: totalCostUsd,
|
|
98
|
+
provider: res.provider,
|
|
99
|
+
model: res.model
|
|
100
|
+
};
|
|
101
|
+
if (last.diagnostics.length === 0) return last;
|
|
102
|
+
prompt = buildGenerateRepairPrompt(basePrompt, source, last.diagnostics);
|
|
103
|
+
}
|
|
104
|
+
return last;
|
|
105
|
+
}
|
|
106
|
+
function resolveGeneratorModelOptions(opts, env = process.env) {
|
|
107
|
+
const provider = opts?.provider ?? resolveDefaultProvider(env);
|
|
108
|
+
const model = opts?.model ?? (provider === "openrouter" ? "openai/gpt-5-codex" : void 0);
|
|
109
|
+
const maxTokens = opts?.maxTokens ?? 4096;
|
|
110
|
+
return model ? {
|
|
111
|
+
provider,
|
|
112
|
+
model,
|
|
113
|
+
maxTokens
|
|
114
|
+
} : {
|
|
115
|
+
provider,
|
|
116
|
+
maxTokens
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function defaultComplete(opts) {
|
|
120
|
+
const modelOptions = resolveGeneratorModelOptions(opts);
|
|
121
|
+
return async (prompt) => {
|
|
122
|
+
const client = createUnifiedLLMClient({
|
|
123
|
+
provider: modelOptions.provider,
|
|
124
|
+
model: modelOptions.model,
|
|
125
|
+
vision: false
|
|
126
|
+
});
|
|
127
|
+
if (!client) throw new Error("No LLM provider configured for vlmkit-generate");
|
|
128
|
+
return client.completeWithImages(prompt, { maxTokens: modelOptions.maxTokens });
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function stripOuterCodeFence(source) {
|
|
132
|
+
const lines = source.trim().split(/\r?\n/);
|
|
133
|
+
if (!/^```(?:ts|typescript)?\s*$/i.test(lines[0] ?? "")) return null;
|
|
134
|
+
let end = lines.length - 1;
|
|
135
|
+
while (end > 0 && lines[end].trim() === "") end--;
|
|
136
|
+
if (lines[end].trim() !== "```") return null;
|
|
137
|
+
return lines.slice(1, end).join("\n").trim();
|
|
138
|
+
}
|
|
139
|
+
function countStandaloneCommentLines(source) {
|
|
140
|
+
return source.split(/\r?\n/).filter((line) => {
|
|
141
|
+
const trimmed = line.trim();
|
|
142
|
+
return trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*");
|
|
143
|
+
}).length;
|
|
144
|
+
}
|
|
145
|
+
function collectGeneratedTestAstInfo(sourceFile, helperImportPath) {
|
|
146
|
+
const info = {
|
|
147
|
+
helperImportPath,
|
|
148
|
+
hasPlaywrightImport: false,
|
|
149
|
+
hasTestImport: false,
|
|
150
|
+
hasExpectImport: false,
|
|
151
|
+
hasGotoAppImport: false,
|
|
152
|
+
usesGotoApp: false,
|
|
153
|
+
usesExpect: false,
|
|
154
|
+
usesPageGoto: false,
|
|
155
|
+
usesToHaveScreenshot: false,
|
|
156
|
+
locators: []
|
|
157
|
+
};
|
|
158
|
+
function visit(node) {
|
|
159
|
+
if (ts.isImportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) {
|
|
160
|
+
const moduleName = node.moduleSpecifier.text;
|
|
161
|
+
const imported = getNamedImportMap(node);
|
|
162
|
+
if (moduleName === "@playwright/test") {
|
|
163
|
+
info.hasPlaywrightImport = true;
|
|
164
|
+
info.hasTestImport ||= imported.has("test");
|
|
165
|
+
info.hasExpectImport ||= imported.has("expect");
|
|
166
|
+
}
|
|
167
|
+
if (moduleName === helperImportPath) info.hasGotoAppImport ||= imported.get("gotoApp") === "gotoApp";
|
|
168
|
+
}
|
|
169
|
+
if (ts.isCallExpression(node)) {
|
|
170
|
+
if (ts.isIdentifier(node.expression)) {
|
|
171
|
+
if (node.expression.text === "gotoApp") info.usesGotoApp = true;
|
|
172
|
+
if (node.expression.text === "expect") info.usesExpect = true;
|
|
173
|
+
} else if (ts.isPropertyAccessExpression(node.expression)) {
|
|
174
|
+
const property = node.expression.name.text;
|
|
175
|
+
if (property === "goto" && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "page") info.usesPageGoto = true;
|
|
176
|
+
if (property === "soft" && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "expect") info.usesExpect = true;
|
|
177
|
+
if (property === "toHaveScreenshot") info.usesToHaveScreenshot = true;
|
|
178
|
+
const locator = extractUsedLocator(node, property);
|
|
179
|
+
if (locator) info.locators.push(locator);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
ts.forEachChild(node, visit);
|
|
183
|
+
}
|
|
184
|
+
visit(sourceFile);
|
|
185
|
+
return info;
|
|
186
|
+
}
|
|
187
|
+
function getNamedImportMap(node) {
|
|
188
|
+
const imports = /* @__PURE__ */ new Map();
|
|
189
|
+
const bindings = node.importClause?.namedBindings;
|
|
190
|
+
if (!bindings || !ts.isNamedImports(bindings)) return imports;
|
|
191
|
+
for (const element of bindings.elements) {
|
|
192
|
+
const importedName = element.propertyName?.text ?? element.name.text;
|
|
193
|
+
imports.set(importedName, element.name.text);
|
|
194
|
+
}
|
|
195
|
+
return imports;
|
|
196
|
+
}
|
|
197
|
+
function extractUsedLocator(node, property) {
|
|
198
|
+
if (property === "getByRole") {
|
|
199
|
+
const role = getStringArg(node, 0);
|
|
200
|
+
if (!role) return null;
|
|
201
|
+
return {
|
|
202
|
+
kind: "role",
|
|
203
|
+
role,
|
|
204
|
+
name: getObjectStringProperty(node.arguments[1], "name")
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
if (property === "getByLabel") {
|
|
208
|
+
const value = getStringArg(node, 0);
|
|
209
|
+
return value ? {
|
|
210
|
+
kind: "label",
|
|
211
|
+
value
|
|
212
|
+
} : null;
|
|
213
|
+
}
|
|
214
|
+
if (property === "getByTestId") {
|
|
215
|
+
const value = getStringArg(node, 0);
|
|
216
|
+
return value ? {
|
|
217
|
+
kind: "testId",
|
|
218
|
+
value
|
|
219
|
+
} : null;
|
|
220
|
+
}
|
|
221
|
+
if (property === "getByText") {
|
|
222
|
+
const value = getStringArg(node, 0);
|
|
223
|
+
return value ? {
|
|
224
|
+
kind: "text",
|
|
225
|
+
value
|
|
226
|
+
} : null;
|
|
227
|
+
}
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
function getStringArg(node, index) {
|
|
231
|
+
const arg = node.arguments[index];
|
|
232
|
+
return arg && ts.isStringLiteralLike(arg) ? arg.text : null;
|
|
233
|
+
}
|
|
234
|
+
function getObjectStringProperty(node, propertyName) {
|
|
235
|
+
if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
|
|
236
|
+
for (const property of node.properties) {
|
|
237
|
+
if (!ts.isPropertyAssignment(property)) continue;
|
|
238
|
+
const name = property.name;
|
|
239
|
+
if ((ts.isIdentifier(name) || ts.isStringLiteralLike(name) ? name.text : void 0) !== propertyName) continue;
|
|
240
|
+
return ts.isStringLiteralLike(property.initializer) ? property.initializer.text : void 0;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function validateLocatorInventory(usedLocators, inventory) {
|
|
244
|
+
const diagnostics = [];
|
|
245
|
+
const allowed = normalizeLocatorInventory(inventory);
|
|
246
|
+
for (const locator of usedLocators) {
|
|
247
|
+
if (locator.kind === "role" && allowed.roles.size) {
|
|
248
|
+
if (![roleKey(locator.role, locator.name), roleKey(locator.role, void 0)].some((key) => allowed.roles.has(key)) && !isAllowedNamelessObservedRole(locator, allowed)) diagnostics.push(`unknown role locator: ${locator.role}${locator.name ? ` "${locator.name}"` : ""}`);
|
|
249
|
+
}
|
|
250
|
+
if (locator.kind === "label" && allowed.labels.size && !allowed.labels.has(locator.value)) diagnostics.push(`unknown label locator: "${locator.value}"`);
|
|
251
|
+
if (locator.kind === "testId" && allowed.testIds.size && !allowed.testIds.has(locator.value)) diagnostics.push(`unknown test id locator: "${locator.value}"`);
|
|
252
|
+
if (locator.kind === "text" && allowed.texts.size && !allowed.texts.has(locator.value)) diagnostics.push(`unknown text locator: "${locator.value}"`);
|
|
253
|
+
}
|
|
254
|
+
return diagnostics;
|
|
255
|
+
}
|
|
256
|
+
function validateRoleLocatorUsage(usedLocators) {
|
|
257
|
+
const diagnostics = [];
|
|
258
|
+
for (const locator of usedLocators) if (locator.kind === "role" && locator.name && namelessObservedRoleNames.has(locator.role)) diagnostics.push(`role "${locator.role}" should not use a name filter; assert text separately`);
|
|
259
|
+
return diagnostics;
|
|
260
|
+
}
|
|
261
|
+
function normalizeLocatorInventory(inventory) {
|
|
262
|
+
const roleEntries = (inventory.roles ?? []).map(parseRoleInventoryEntry);
|
|
263
|
+
return {
|
|
264
|
+
roles: new Set(roleEntries.map((entry) => roleKey(entry.role, entry.name))),
|
|
265
|
+
observedRoleKinds: new Set(roleEntries.map((entry) => entry.role)),
|
|
266
|
+
labels: new Set(inventory.labels ?? []),
|
|
267
|
+
testIds: new Set(inventory.testIds ?? []),
|
|
268
|
+
texts: new Set(inventory.texts ?? [])
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
function isAllowedNamelessObservedRole(locator, allowed) {
|
|
272
|
+
return locator.kind === "role" && !locator.name && namelessObservedRoleNames.has(locator.role) && allowed.observedRoleKinds.has(locator.role);
|
|
273
|
+
}
|
|
274
|
+
const namelessObservedRoleNames = new Set([
|
|
275
|
+
"status",
|
|
276
|
+
"alert",
|
|
277
|
+
"log"
|
|
278
|
+
]);
|
|
279
|
+
function parseRoleInventoryEntry(entry) {
|
|
280
|
+
const quoted = entry.match(/^([^"']+?)\s*["'](.+)["']$/);
|
|
281
|
+
if (quoted) return {
|
|
282
|
+
role: quoted[1].trim().replace(/:$/, ""),
|
|
283
|
+
name: quoted[2].trim()
|
|
284
|
+
};
|
|
285
|
+
const colon = entry.match(/^([^:]+):\s*(.+)$/);
|
|
286
|
+
if (colon) return {
|
|
287
|
+
role: colon[1].trim(),
|
|
288
|
+
name: colon[2].trim()
|
|
289
|
+
};
|
|
290
|
+
return { role: entry.trim() };
|
|
291
|
+
}
|
|
292
|
+
function roleKey(role, name) {
|
|
293
|
+
return name ? `${role}\u0000${name}` : role;
|
|
294
|
+
}
|
|
295
|
+
function formatLocatorInventory(inventory) {
|
|
296
|
+
const lines = ["", "Allowed observed locators:"];
|
|
297
|
+
if (inventory.roles?.length) lines.push(`- Roles: ${inventory.roles.join(", ")}`);
|
|
298
|
+
if (inventory.labels?.length) lines.push(`- Labels: ${inventory.labels.join(", ")}`);
|
|
299
|
+
if (inventory.testIds?.length) lines.push(`- Test IDs: ${inventory.testIds.join(", ")}`);
|
|
300
|
+
if (inventory.texts?.length) lines.push(`- Text: ${inventory.texts.join(", ")}`);
|
|
301
|
+
lines.push("- Do not invent locators outside this observed set unless the plan explicitly says to discover them first.");
|
|
302
|
+
return lines.join("\n");
|
|
303
|
+
}
|
|
304
|
+
function buildGenerateRepairPrompt(basePrompt, source, diagnostics) {
|
|
305
|
+
return [
|
|
306
|
+
basePrompt,
|
|
307
|
+
"",
|
|
308
|
+
"Previous generator diagnostics:",
|
|
309
|
+
...diagnostics.map((d) => `- ${d}`),
|
|
310
|
+
"",
|
|
311
|
+
"Previous generated source:",
|
|
312
|
+
"```ts",
|
|
313
|
+
source.trim(),
|
|
314
|
+
"```",
|
|
315
|
+
"",
|
|
316
|
+
"Regenerate the full TypeScript Playwright spec. Fix every diagnostic. Output only one ```ts code block."
|
|
317
|
+
].join("\n");
|
|
318
|
+
}
|
|
319
|
+
function normalizeMaxAttempts(value) {
|
|
320
|
+
if (!Number.isFinite(value)) return 2;
|
|
321
|
+
return Math.max(1, Math.floor(value));
|
|
322
|
+
}
|
|
323
|
+
function resolveDefaultProvider(env) {
|
|
324
|
+
const fromEnv = env.VRT_LLM_PROVIDER;
|
|
325
|
+
if (fromEnv) {
|
|
326
|
+
if (fromEnv === "anthropic" || fromEnv === "gemini" || fromEnv === "openrouter") return fromEnv;
|
|
327
|
+
throw new Error(`Invalid VRT_LLM_PROVIDER: ${fromEnv}`);
|
|
328
|
+
}
|
|
329
|
+
if (env.ANTHROPIC_API_KEY) return "anthropic";
|
|
330
|
+
if (env.OPENROUTER_API_KEY) return "openrouter";
|
|
331
|
+
if (env.GEMINI_API_KEY || env.GOOGLE_AI_API_KEY) return "gemini";
|
|
332
|
+
return "openrouter";
|
|
333
|
+
}
|
|
334
|
+
//#endregion
|
|
335
|
+
export { buildGeneratePrompt, extractTypescriptSource, generatePlaywrightTest, generatePlaywrightTestWithRetry, resolveGeneratorModelOptions, validateGeneratedTestSource };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { GateCommand, GateResult, GeneratedTestGateError, GeneratedTestWriteError, WriteGeneratedTestOptions, WriteGeneratedTestResult, buildPlaywrightListGate, buildPlaywrightRuntimeGate, buildTypecheckGate, writeGeneratedTestFile } from "./write.mjs";
|
|
2
|
+
import { GenerateDeps, GenerateInput, GenerateResult, GenerateRetryOptions, GeneratorModelOptions, LocatorInventory } from "./types.mjs";
|
|
3
|
+
import { buildGeneratePrompt, extractTypescriptSource, generatePlaywrightTest, generatePlaywrightTestWithRetry, resolveGeneratorModelOptions, validateGeneratedTestSource } from "./generate.mjs";
|
|
4
|
+
export { type GateCommand, type GateResult, GenerateDeps, GenerateInput, GenerateResult, GenerateRetryOptions, GeneratedTestGateError, GeneratedTestWriteError, GeneratorModelOptions, LocatorInventory, type WriteGeneratedTestOptions, type WriteGeneratedTestResult, buildGeneratePrompt, buildPlaywrightListGate, buildPlaywrightRuntimeGate, buildTypecheckGate, extractTypescriptSource, generatePlaywrightTest, generatePlaywrightTestWithRetry, resolveGeneratorModelOptions, validateGeneratedTestSource, writeGeneratedTestFile };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { buildGeneratePrompt, extractTypescriptSource, generatePlaywrightTest, generatePlaywrightTestWithRetry, resolveGeneratorModelOptions, validateGeneratedTestSource } from "./generate.mjs";
|
|
2
|
+
import { GeneratedTestGateError, GeneratedTestWriteError, buildPlaywrightListGate, buildPlaywrightRuntimeGate, buildTypecheckGate, writeGeneratedTestFile } from "./write.mjs";
|
|
3
|
+
export { GeneratedTestGateError, GeneratedTestWriteError, buildGeneratePrompt, buildPlaywrightListGate, buildPlaywrightRuntimeGate, buildTypecheckGate, extractTypescriptSource, generatePlaywrightTest, generatePlaywrightTestWithRetry, resolveGeneratorModelOptions, validateGeneratedTestSource, writeGeneratedTestFile };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { LLMResponse } from "@mizchi/vlmkit-ai";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
//#region src/types.d.ts
|
|
4
|
+
interface GenerateInput {
|
|
4
5
|
planMarkdown: string;
|
|
5
6
|
testFilePath: string;
|
|
6
7
|
rulesMarkdown?: string;
|
|
@@ -9,25 +10,21 @@ export interface GenerateInput {
|
|
|
9
10
|
requireScreenshots?: boolean;
|
|
10
11
|
locatorInventory?: LocatorInventory;
|
|
11
12
|
}
|
|
12
|
-
|
|
13
|
-
export interface LocatorInventory {
|
|
13
|
+
interface LocatorInventory {
|
|
14
14
|
roles?: string[];
|
|
15
15
|
labels?: string[];
|
|
16
16
|
testIds?: string[];
|
|
17
17
|
texts?: string[];
|
|
18
18
|
}
|
|
19
|
-
|
|
20
|
-
export interface GeneratorModelOptions {
|
|
19
|
+
interface GeneratorModelOptions {
|
|
21
20
|
provider?: "anthropic" | "gemini" | "openrouter";
|
|
22
21
|
model?: string;
|
|
23
22
|
maxTokens?: number;
|
|
24
23
|
}
|
|
25
|
-
|
|
26
|
-
export interface GenerateRetryOptions {
|
|
24
|
+
interface GenerateRetryOptions {
|
|
27
25
|
maxAttempts?: number;
|
|
28
26
|
}
|
|
29
|
-
|
|
30
|
-
export interface GenerateResult {
|
|
27
|
+
interface GenerateResult {
|
|
31
28
|
source: string;
|
|
32
29
|
diagnostics: string[];
|
|
33
30
|
attempts: number;
|
|
@@ -35,8 +32,9 @@ export interface GenerateResult {
|
|
|
35
32
|
provider?: string;
|
|
36
33
|
model?: string;
|
|
37
34
|
}
|
|
38
|
-
|
|
39
|
-
export interface GenerateDeps {
|
|
35
|
+
interface GenerateDeps {
|
|
40
36
|
/** Only `content` is required — cost/provider/model metadata is best-effort (fakes and some providers omit it). */
|
|
41
37
|
complete: (prompt: string) => Promise<Pick<LLMResponse, "content"> & Partial<Pick<LLMResponse, "costUsd" | "provider" | "model">>>;
|
|
42
38
|
}
|
|
39
|
+
//#endregion
|
|
40
|
+
export { GenerateDeps, GenerateInput, GenerateResult, GenerateRetryOptions, GeneratorModelOptions, LocatorInventory };
|
package/dist/types.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/write.d.mts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
//#region src/write.d.ts
|
|
2
|
+
interface GateCommand {
|
|
3
|
+
name?: string;
|
|
4
|
+
command: string;
|
|
5
|
+
cwd?: string;
|
|
6
|
+
env?: Record<string, string | undefined>;
|
|
7
|
+
runs?: number;
|
|
8
|
+
}
|
|
9
|
+
interface GateResult {
|
|
10
|
+
name: string;
|
|
11
|
+
command: string;
|
|
12
|
+
ok: boolean;
|
|
13
|
+
exitCode: number;
|
|
14
|
+
stdout: string;
|
|
15
|
+
stderr: string;
|
|
16
|
+
}
|
|
17
|
+
interface WriteGeneratedTestOptions {
|
|
18
|
+
filePath: string;
|
|
19
|
+
source: string;
|
|
20
|
+
overwrite?: boolean;
|
|
21
|
+
dryRun?: boolean;
|
|
22
|
+
gates?: GateCommand[];
|
|
23
|
+
cwd?: string;
|
|
24
|
+
}
|
|
25
|
+
interface WriteGeneratedTestResult {
|
|
26
|
+
filePath: string;
|
|
27
|
+
written: boolean;
|
|
28
|
+
gates: GateResult[];
|
|
29
|
+
}
|
|
30
|
+
interface WriteGeneratedTestDeps {
|
|
31
|
+
runCommand?: (gate: GateCommand) => Promise<GateResult>;
|
|
32
|
+
}
|
|
33
|
+
declare class GeneratedTestWriteError extends Error {
|
|
34
|
+
readonly code: "EEXIST";
|
|
35
|
+
constructor(code: "EEXIST", message: string);
|
|
36
|
+
}
|
|
37
|
+
declare class GeneratedTestGateError extends Error {
|
|
38
|
+
readonly result: GateResult;
|
|
39
|
+
constructor(result: GateResult);
|
|
40
|
+
}
|
|
41
|
+
declare function writeGeneratedTestFile(options: WriteGeneratedTestOptions, deps?: WriteGeneratedTestDeps): Promise<WriteGeneratedTestResult>;
|
|
42
|
+
declare function buildPlaywrightListGate(): GateCommand;
|
|
43
|
+
declare function buildPlaywrightRuntimeGate(config?: string, runs?: number): GateCommand;
|
|
44
|
+
declare function buildTypecheckGate(tsconfig?: string): GateCommand;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { GateCommand, GateResult, GeneratedTestGateError, GeneratedTestWriteError, WriteGeneratedTestDeps, WriteGeneratedTestOptions, WriteGeneratedTestResult, buildPlaywrightListGate, buildPlaywrightRuntimeGate, buildTypecheckGate, writeGeneratedTestFile };
|