@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/src/generate.ts DELETED
@@ -1,424 +0,0 @@
1
- import { createUnifiedLLMClient } from "@mizchi/vlmkit-ai";
2
- import * as ts from "typescript";
3
- import type { GenerateDeps, GenerateInput, GenerateResult, GenerateRetryOptions, GeneratorModelOptions, LocatorInventory } from "./types.ts";
4
-
5
- type ResolvedGeneratorModelOptions = GeneratorModelOptions & {
6
- provider: NonNullable<GeneratorModelOptions["provider"]>;
7
- };
8
-
9
- export function buildGeneratePrompt(input: GenerateInput): string {
10
- const helperImportPath = input.helperImportPath ?? "./_helpers";
11
- const requireScreenshots = input.requireScreenshots ?? true;
12
- return [
13
- "You are a Playwright Test generator.",
14
- "Write exactly one complete TypeScript Playwright spec file.",
15
- "Output only the full file inside one ```ts code block.",
16
- "",
17
- `Target file: ${input.testFilePath}`,
18
- input.seedTestPath ? `Seed test reference: ${input.seedTestPath}` : undefined,
19
- "",
20
- "Mandatory rules:",
21
- "- Import `test` and `expect` from `@playwright/test`.",
22
- `- Import and use \`gotoApp\` from \`${helperImportPath}\`; do not call \`page.goto\` directly.`,
23
- "- Prefer role, label, and test id locators. Avoid CSS and XPath unless no semantic locator exists.",
24
- "- For live-region roles such as `status`, `alert`, and `log`, use `getByRole(\"status\")` and assert text separately; do not pass a `name` filter.",
25
- "- Keep comments sparse. Do not narrate obvious Playwright actions; comment only non-obvious locator or determinism constraints.",
26
- "- Every visual assertion must also have semantic assertions.",
27
- requireScreenshots ? "- Include deterministic `toHaveScreenshot()` checks for the start and goal states." : undefined,
28
- input.locatorInventory ? formatLocatorInventory(input.locatorInventory) : undefined,
29
- "",
30
- input.rulesMarkdown?.trim() ? `Additional generation rules:\n${input.rulesMarkdown.trim()}` : undefined,
31
- "",
32
- `Plan:\n${input.planMarkdown.trim()}`,
33
- ].filter((p): p is string => Boolean(p)).join("\n");
34
- }
35
-
36
- export function extractTypescriptSource(raw: string): string {
37
- let text = raw.trim();
38
- for (let i = 0; i < 3; i++) {
39
- const outer = stripOuterCodeFence(text);
40
- if (outer !== null) {
41
- text = outer;
42
- continue;
43
- }
44
- const fenced = text.match(/```(?:ts|typescript)?\r?\n([\s\S]*?)\r?\n```/i);
45
- if (!fenced) break;
46
- text = fenced[1]!.trim();
47
- }
48
- return text.trimEnd() + "\n";
49
- }
50
-
51
- export function validateGeneratedTestSource(
52
- source: string,
53
- input: Pick<GenerateInput, "helperImportPath" | "requireScreenshots" | "locatorInventory"> = {},
54
- ): string[] {
55
- const diagnostics: string[] = [];
56
- if (/```/.test(source)) {
57
- diagnostics.push("source contains markdown code fences");
58
- }
59
- if (countStandaloneCommentLines(source) >= 3) {
60
- diagnostics.push("generated source has excessive comments; keep only non-obvious comments");
61
- }
62
- const sourceFile = ts.createSourceFile("generated.spec.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
63
- // parseDiagnostics is a TypeScript-internal field not in the public SourceFile type.
64
- const parseDiagnostics = (sourceFile as ts.SourceFile & { parseDiagnostics?: ts.DiagnosticWithLocation[] }).parseDiagnostics ?? [];
65
- for (const parseDiagnostic of parseDiagnostics) {
66
- const message = ts.flattenDiagnosticMessageText(parseDiagnostic.messageText, " ");
67
- diagnostics.push(`typescript syntax error: ${message}`);
68
- }
69
-
70
- const astInfo = collectGeneratedTestAstInfo(sourceFile, input.helperImportPath ?? "./_helpers");
71
- if (!astInfo.hasPlaywrightImport) {
72
- diagnostics.push("missing @playwright/test import");
73
- } else {
74
- if (!astInfo.hasTestImport) diagnostics.push("missing test import from @playwright/test");
75
- if (!astInfo.hasExpectImport) diagnostics.push("missing expect import from @playwright/test");
76
- }
77
- if (!astInfo.usesGotoApp) {
78
- diagnostics.push("missing gotoApp usage");
79
- }
80
- if (!astInfo.usesExpect) {
81
- diagnostics.push("missing expect assertions");
82
- }
83
- if (astInfo.usesPageGoto) {
84
- diagnostics.push("direct page.goto is not allowed; use gotoApp(page)");
85
- }
86
- if ((input.requireScreenshots ?? true) && !astInfo.usesToHaveScreenshot) {
87
- diagnostics.push("missing toHaveScreenshot assertions");
88
- }
89
-
90
- if (!astInfo.hasGotoAppImport) {
91
- diagnostics.push(`missing gotoApp import from ${astInfo.helperImportPath}`);
92
- }
93
- diagnostics.push(...validateRoleLocatorUsage(astInfo.locators));
94
- if (input.locatorInventory) {
95
- diagnostics.push(...validateLocatorInventory(astInfo.locators, input.locatorInventory));
96
- }
97
- return diagnostics;
98
- }
99
-
100
- export async function generatePlaywrightTest(
101
- input: GenerateInput,
102
- opts?: GeneratorModelOptions,
103
- deps?: Partial<GenerateDeps>,
104
- ): Promise<GenerateResult> {
105
- const prompt = buildGeneratePrompt(input);
106
- const complete = deps?.complete ?? defaultComplete(opts);
107
- const res = await complete(prompt);
108
- const source = extractTypescriptSource(res.content);
109
- return {
110
- source,
111
- diagnostics: validateGeneratedTestSource(source, input),
112
- attempts: 1,
113
- costUsd: res.costUsd ?? 0,
114
- provider: res.provider,
115
- model: res.model,
116
- };
117
- }
118
-
119
- export async function generatePlaywrightTestWithRetry(
120
- input: GenerateInput,
121
- opts?: GeneratorModelOptions,
122
- deps?: Partial<GenerateDeps>,
123
- retry?: GenerateRetryOptions,
124
- ): Promise<GenerateResult> {
125
- const maxAttempts = normalizeMaxAttempts(retry?.maxAttempts);
126
- const basePrompt = buildGeneratePrompt(input);
127
- const complete = deps?.complete ?? defaultComplete(opts);
128
- let prompt = basePrompt;
129
- let totalCostUsd = 0;
130
- let last: GenerateResult | undefined;
131
-
132
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
133
- const res = await complete(prompt);
134
- totalCostUsd += res.costUsd ?? 0;
135
- const source = extractTypescriptSource(res.content);
136
- last = {
137
- source,
138
- diagnostics: validateGeneratedTestSource(source, input),
139
- attempts: attempt,
140
- costUsd: totalCostUsd,
141
- provider: res.provider,
142
- model: res.model,
143
- };
144
- if (last.diagnostics.length === 0) return last;
145
- prompt = buildGenerateRepairPrompt(basePrompt, source, last.diagnostics);
146
- }
147
-
148
- return last!;
149
- }
150
-
151
- export function resolveGeneratorModelOptions(
152
- opts?: GeneratorModelOptions,
153
- env: Record<string, string | undefined> = process.env,
154
- ): ResolvedGeneratorModelOptions {
155
- const provider = opts?.provider ?? resolveDefaultProvider(env);
156
- const model = opts?.model ?? (provider === "openrouter" ? "openai/gpt-5-codex" : undefined);
157
- const maxTokens = opts?.maxTokens ?? 4096;
158
- return model ? { provider, model, maxTokens } : { provider, maxTokens };
159
- }
160
-
161
- function defaultComplete(opts?: GeneratorModelOptions): GenerateDeps["complete"] {
162
- const modelOptions = resolveGeneratorModelOptions(opts);
163
- return async (prompt) => {
164
- const client = createUnifiedLLMClient({
165
- provider: modelOptions.provider,
166
- model: modelOptions.model,
167
- vision: false,
168
- });
169
- if (!client) throw new Error("No LLM provider configured for vlmkit-generate");
170
- return client.completeWithImages(prompt, { maxTokens: modelOptions.maxTokens });
171
- };
172
- }
173
-
174
- function stripOuterCodeFence(source: string): string | null {
175
- const lines = source.trim().split(/\r?\n/);
176
- if (!/^```(?:ts|typescript)?\s*$/i.test(lines[0] ?? "")) return null;
177
- let end = lines.length - 1;
178
- while (end > 0 && lines[end]!.trim() === "") end--;
179
- if (lines[end]!.trim() !== "```") return null;
180
- return lines.slice(1, end).join("\n").trim();
181
- }
182
-
183
- function countStandaloneCommentLines(source: string): number {
184
- return source.split(/\r?\n/).filter((line) => {
185
- const trimmed = line.trim();
186
- return trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*");
187
- }).length;
188
- }
189
-
190
- interface GeneratedTestAstInfo {
191
- helperImportPath: string;
192
- hasPlaywrightImport: boolean;
193
- hasTestImport: boolean;
194
- hasExpectImport: boolean;
195
- hasGotoAppImport: boolean;
196
- usesGotoApp: boolean;
197
- usesExpect: boolean;
198
- usesPageGoto: boolean;
199
- usesToHaveScreenshot: boolean;
200
- locators: UsedLocator[];
201
- }
202
-
203
- type UsedLocator =
204
- | { kind: "role"; role: string; name?: string }
205
- | { kind: "label"; value: string }
206
- | { kind: "testId"; value: string }
207
- | { kind: "text"; value: string };
208
-
209
- function collectGeneratedTestAstInfo(sourceFile: ts.SourceFile, helperImportPath: string): GeneratedTestAstInfo {
210
- const info: GeneratedTestAstInfo = {
211
- helperImportPath,
212
- hasPlaywrightImport: false,
213
- hasTestImport: false,
214
- hasExpectImport: false,
215
- hasGotoAppImport: false,
216
- usesGotoApp: false,
217
- usesExpect: false,
218
- usesPageGoto: false,
219
- usesToHaveScreenshot: false,
220
- locators: [],
221
- };
222
-
223
- function visit(node: ts.Node) {
224
- if (ts.isImportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) {
225
- const moduleName = node.moduleSpecifier.text;
226
- const imported = getNamedImportMap(node);
227
- if (moduleName === "@playwright/test") {
228
- info.hasPlaywrightImport = true;
229
- info.hasTestImport ||= imported.has("test");
230
- info.hasExpectImport ||= imported.has("expect");
231
- }
232
- if (moduleName === helperImportPath) {
233
- info.hasGotoAppImport ||= imported.get("gotoApp") === "gotoApp";
234
- }
235
- }
236
-
237
- if (ts.isCallExpression(node)) {
238
- if (ts.isIdentifier(node.expression)) {
239
- if (node.expression.text === "gotoApp") info.usesGotoApp = true;
240
- if (node.expression.text === "expect") info.usesExpect = true;
241
- } else if (ts.isPropertyAccessExpression(node.expression)) {
242
- const property = node.expression.name.text;
243
- if (property === "goto" && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "page") {
244
- info.usesPageGoto = true;
245
- }
246
- if (property === "soft" && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "expect") {
247
- info.usesExpect = true;
248
- }
249
- if (property === "toHaveScreenshot") {
250
- info.usesToHaveScreenshot = true;
251
- }
252
- const locator = extractUsedLocator(node, property);
253
- if (locator) info.locators.push(locator);
254
- }
255
- }
256
-
257
- ts.forEachChild(node, visit);
258
- }
259
-
260
- visit(sourceFile);
261
- return info;
262
- }
263
-
264
- function getNamedImportMap(node: ts.ImportDeclaration): Map<string, string> {
265
- const imports = new Map<string, string>();
266
- const clause = node.importClause;
267
- const bindings = clause?.namedBindings;
268
- if (!bindings || !ts.isNamedImports(bindings)) return imports;
269
- for (const element of bindings.elements) {
270
- const importedName = element.propertyName?.text ?? element.name.text;
271
- imports.set(importedName, element.name.text);
272
- }
273
- return imports;
274
- }
275
-
276
- function extractUsedLocator(node: ts.CallExpression, property: string): UsedLocator | null {
277
- if (property === "getByRole") {
278
- const role = getStringArg(node, 0);
279
- if (!role) return null;
280
- const name = getObjectStringProperty(node.arguments[1], "name");
281
- return { kind: "role", role, name };
282
- }
283
- if (property === "getByLabel") {
284
- const value = getStringArg(node, 0);
285
- return value ? { kind: "label", value } : null;
286
- }
287
- if (property === "getByTestId") {
288
- const value = getStringArg(node, 0);
289
- return value ? { kind: "testId", value } : null;
290
- }
291
- if (property === "getByText") {
292
- const value = getStringArg(node, 0);
293
- return value ? { kind: "text", value } : null;
294
- }
295
- return null;
296
- }
297
-
298
- function getStringArg(node: ts.CallExpression, index: number): string | null {
299
- const arg = node.arguments[index];
300
- return arg && ts.isStringLiteralLike(arg) ? arg.text : null;
301
- }
302
-
303
- function getObjectStringProperty(node: ts.Expression | undefined, propertyName: string): string | undefined {
304
- if (!node || !ts.isObjectLiteralExpression(node)) return undefined;
305
- for (const property of node.properties) {
306
- if (!ts.isPropertyAssignment(property)) continue;
307
- const name = property.name;
308
- const key = ts.isIdentifier(name) || ts.isStringLiteralLike(name) ? name.text : undefined;
309
- if (key !== propertyName) continue;
310
- return ts.isStringLiteralLike(property.initializer) ? property.initializer.text : undefined;
311
- }
312
- return undefined;
313
- }
314
-
315
- function validateLocatorInventory(usedLocators: UsedLocator[], inventory: LocatorInventory): string[] {
316
- const diagnostics: string[] = [];
317
- const allowed = normalizeLocatorInventory(inventory);
318
- for (const locator of usedLocators) {
319
- if (locator.kind === "role" && allowed.roles.size) {
320
- const keys = [roleKey(locator.role, locator.name), roleKey(locator.role, undefined)];
321
- if (!keys.some((key) => allowed.roles.has(key)) && !isAllowedNamelessObservedRole(locator, allowed)) {
322
- diagnostics.push(`unknown role locator: ${locator.role}${locator.name ? ` "${locator.name}"` : ""}`);
323
- }
324
- }
325
- if (locator.kind === "label" && allowed.labels.size && !allowed.labels.has(locator.value)) {
326
- diagnostics.push(`unknown label locator: "${locator.value}"`);
327
- }
328
- if (locator.kind === "testId" && allowed.testIds.size && !allowed.testIds.has(locator.value)) {
329
- diagnostics.push(`unknown test id locator: "${locator.value}"`);
330
- }
331
- if (locator.kind === "text" && allowed.texts.size && !allowed.texts.has(locator.value)) {
332
- diagnostics.push(`unknown text locator: "${locator.value}"`);
333
- }
334
- }
335
- return diagnostics;
336
- }
337
-
338
- function validateRoleLocatorUsage(usedLocators: UsedLocator[]): string[] {
339
- const diagnostics: string[] = [];
340
- for (const locator of usedLocators) {
341
- if (locator.kind === "role" && locator.name && namelessObservedRoleNames.has(locator.role)) {
342
- diagnostics.push(`role "${locator.role}" should not use a name filter; assert text separately`);
343
- }
344
- }
345
- return diagnostics;
346
- }
347
-
348
- function normalizeLocatorInventory(inventory: LocatorInventory) {
349
- const roleEntries = (inventory.roles ?? []).map(parseRoleInventoryEntry);
350
- return {
351
- roles: new Set(roleEntries.map((entry) => roleKey(entry.role, entry.name))),
352
- observedRoleKinds: new Set(roleEntries.map((entry) => entry.role)),
353
- labels: new Set(inventory.labels ?? []),
354
- testIds: new Set(inventory.testIds ?? []),
355
- texts: new Set(inventory.texts ?? []),
356
- };
357
- }
358
-
359
- function isAllowedNamelessObservedRole(
360
- locator: UsedLocator,
361
- allowed: ReturnType<typeof normalizeLocatorInventory>,
362
- ): boolean {
363
- return locator.kind === "role"
364
- && !locator.name
365
- && namelessObservedRoleNames.has(locator.role)
366
- && allowed.observedRoleKinds.has(locator.role);
367
- }
368
-
369
- const namelessObservedRoleNames = new Set(["status", "alert", "log"]);
370
-
371
- function parseRoleInventoryEntry(entry: string): { role: string; name?: string } {
372
- const quoted = entry.match(/^([^"']+?)\s*["'](.+)["']$/);
373
- if (quoted) return { role: quoted[1]!.trim().replace(/:$/, ""), name: quoted[2]!.trim() };
374
- const colon = entry.match(/^([^:]+):\s*(.+)$/);
375
- if (colon) return { role: colon[1]!.trim(), name: colon[2]!.trim() };
376
- return { role: entry.trim() };
377
- }
378
-
379
- function roleKey(role: string, name: string | undefined): string {
380
- return name ? `${role}\u0000${name}` : role;
381
- }
382
-
383
- function formatLocatorInventory(inventory: LocatorInventory): string {
384
- const lines = ["", "Allowed observed locators:"];
385
- if (inventory.roles?.length) lines.push(`- Roles: ${inventory.roles.join(", ")}`);
386
- if (inventory.labels?.length) lines.push(`- Labels: ${inventory.labels.join(", ")}`);
387
- if (inventory.testIds?.length) lines.push(`- Test IDs: ${inventory.testIds.join(", ")}`);
388
- if (inventory.texts?.length) lines.push(`- Text: ${inventory.texts.join(", ")}`);
389
- lines.push("- Do not invent locators outside this observed set unless the plan explicitly says to discover them first.");
390
- return lines.join("\n");
391
- }
392
-
393
- function buildGenerateRepairPrompt(basePrompt: string, source: string, diagnostics: string[]): string {
394
- return [
395
- basePrompt,
396
- "",
397
- "Previous generator diagnostics:",
398
- ...diagnostics.map((d) => `- ${d}`),
399
- "",
400
- "Previous generated source:",
401
- "```ts",
402
- source.trim(),
403
- "```",
404
- "",
405
- "Regenerate the full TypeScript Playwright spec. Fix every diagnostic. Output only one ```ts code block.",
406
- ].join("\n");
407
- }
408
-
409
- function normalizeMaxAttempts(value: number | undefined): number {
410
- if (!Number.isFinite(value)) return 2;
411
- return Math.max(1, Math.floor(value!));
412
- }
413
-
414
- function resolveDefaultProvider(env: Record<string, string | undefined>): NonNullable<GeneratorModelOptions["provider"]> {
415
- const fromEnv = env.VRT_LLM_PROVIDER;
416
- if (fromEnv) {
417
- if (fromEnv === "anthropic" || fromEnv === "gemini" || fromEnv === "openrouter") return fromEnv;
418
- throw new Error(`Invalid VRT_LLM_PROVIDER: ${fromEnv}`);
419
- }
420
- if (env.ANTHROPIC_API_KEY) return "anthropic";
421
- if (env.OPENROUTER_API_KEY) return "openrouter";
422
- if (env.GEMINI_API_KEY || env.GOOGLE_AI_API_KEY) return "gemini";
423
- return "openrouter";
424
- }
package/src/index.ts DELETED
@@ -1,21 +0,0 @@
1
- export * from "./types.ts";
2
- export {
3
- buildGeneratePrompt,
4
- extractTypescriptSource,
5
- generatePlaywrightTest,
6
- generatePlaywrightTestWithRetry,
7
- resolveGeneratorModelOptions,
8
- validateGeneratedTestSource,
9
- } from "./generate.ts";
10
- export {
11
- buildPlaywrightListGate,
12
- buildPlaywrightRuntimeGate,
13
- buildTypecheckGate,
14
- GeneratedTestGateError,
15
- GeneratedTestWriteError,
16
- writeGeneratedTestFile,
17
- type GateCommand,
18
- type GateResult,
19
- type WriteGeneratedTestOptions,
20
- type WriteGeneratedTestResult,
21
- } from "./write.ts";
package/src/write.ts DELETED
@@ -1,177 +0,0 @@
1
- import { exec } from "node:child_process";
2
- import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
- import { dirname, resolve } from "node:path";
4
-
5
- export interface GateCommand {
6
- name?: string;
7
- command: string;
8
- cwd?: string;
9
- env?: Record<string, string | undefined>;
10
- runs?: number;
11
- }
12
-
13
- export interface GateResult {
14
- name: string;
15
- command: string;
16
- ok: boolean;
17
- exitCode: number;
18
- stdout: string;
19
- stderr: string;
20
- }
21
-
22
- export interface WriteGeneratedTestOptions {
23
- filePath: string;
24
- source: string;
25
- overwrite?: boolean;
26
- dryRun?: boolean;
27
- gates?: GateCommand[];
28
- cwd?: string;
29
- }
30
-
31
- export interface WriteGeneratedTestResult {
32
- filePath: string;
33
- written: boolean;
34
- gates: GateResult[];
35
- }
36
-
37
- export interface WriteGeneratedTestDeps {
38
- runCommand?: (gate: GateCommand) => Promise<GateResult>;
39
- }
40
-
41
- export class GeneratedTestWriteError extends Error {
42
- readonly code: "EEXIST";
43
-
44
- constructor(
45
- code: "EEXIST",
46
- message: string,
47
- ) {
48
- super(message);
49
- this.name = "GeneratedTestWriteError";
50
- this.code = code;
51
- }
52
- }
53
-
54
- export class GeneratedTestGateError extends Error {
55
- readonly result: GateResult;
56
-
57
- constructor(result: GateResult) {
58
- super(`Generated test gate failed: ${result.name}`);
59
- this.name = "GeneratedTestGateError";
60
- this.result = result;
61
- }
62
- }
63
-
64
- export async function writeGeneratedTestFile(
65
- options: WriteGeneratedTestOptions,
66
- deps: WriteGeneratedTestDeps = {},
67
- ): Promise<WriteGeneratedTestResult> {
68
- const cwd = options.cwd ?? process.cwd();
69
- const filePath = resolve(cwd, options.filePath);
70
- const gates = options.gates ?? [];
71
- const runCommand = deps.runCommand ?? runShellGate;
72
- const previous = await readOptional(filePath);
73
-
74
- if (previous !== undefined && !options.overwrite) {
75
- throw new GeneratedTestWriteError("EEXIST", `Refusing to overwrite existing file: ${filePath}`);
76
- }
77
- if (options.dryRun) {
78
- return { filePath, written: false, gates: [] };
79
- }
80
-
81
- await mkdir(dirname(filePath), { recursive: true });
82
- await writeFile(filePath, options.source, "utf8");
83
-
84
- const results: GateResult[] = [];
85
- try {
86
- for (const gate of gates) {
87
- const runs = normalizeGateRuns(gate.runs);
88
- for (let i = 0; i < runs; i++) {
89
- const result = await runCommand({
90
- ...gate,
91
- cwd: gate.cwd ?? cwd,
92
- command: formatGateCommand(gate.command, filePath),
93
- });
94
- results.push(result);
95
- if (!result.ok) throw new GeneratedTestGateError(result);
96
- }
97
- }
98
- } catch (error) {
99
- if (previous !== undefined) {
100
- await writeFile(filePath, previous, "utf8");
101
- } else {
102
- await rm(filePath, { force: true });
103
- }
104
- throw error;
105
- }
106
-
107
- return { filePath, written: true, gates: results };
108
- }
109
-
110
- export function buildPlaywrightListGate(): GateCommand {
111
- return {
112
- name: "playwright-list",
113
- command: "pnpm exec playwright test --list {testFile}",
114
- };
115
- }
116
-
117
- export function buildPlaywrightRuntimeGate(config?: string, runs?: number): GateCommand {
118
- const normalizedRuns = normalizeGateRuns(runs);
119
- return {
120
- name: "playwright-runtime",
121
- command: config
122
- ? `pnpm exec playwright test --config ${config} {testFile}`
123
- : "pnpm exec playwright test {testFile}",
124
- ...(normalizedRuns > 1 ? { runs: normalizedRuns } : {}),
125
- };
126
- }
127
-
128
- export function buildTypecheckGate(tsconfig?: string): GateCommand {
129
- return {
130
- name: "typecheck",
131
- command: tsconfig ? `pnpm exec tsc --noEmit -p ${tsconfig}` : "pnpm exec tsc --noEmit",
132
- };
133
- }
134
-
135
- async function readOptional(path: string): Promise<string | undefined> {
136
- try {
137
- return await readFile(path, "utf8");
138
- } catch (error) {
139
- if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return undefined;
140
- throw error;
141
- }
142
- }
143
-
144
- function formatGateCommand(command: string, filePath: string): string {
145
- return command.replaceAll("{testFile}", shellQuote(filePath));
146
- }
147
-
148
- function normalizeGateRuns(runs: number | undefined): number {
149
- if (runs === undefined) return 1;
150
- if (!Number.isInteger(runs) || runs < 1) throw new Error("gate runs must be a positive integer");
151
- return runs;
152
- }
153
-
154
- function shellQuote(value: string): string {
155
- return `'${value.replaceAll("'", "'\\''")}'`;
156
- }
157
-
158
- function runShellGate(gate: GateCommand): Promise<GateResult> {
159
- return new Promise((resolveResult) => {
160
- exec(gate.command, {
161
- cwd: gate.cwd,
162
- env: { ...process.env, ...gate.env },
163
- }, (error, stdout, stderr) => {
164
- const exitCode = typeof (error as { code?: unknown } | null)?.code === "number"
165
- ? (error as { code: number }).code
166
- : error ? 1 : 0;
167
- resolveResult({
168
- name: gate.name ?? gate.command,
169
- command: gate.command,
170
- ok: !error,
171
- exitCode,
172
- stdout,
173
- stderr,
174
- });
175
- });
176
- });
177
- }