@fliwright/cli 0.0.0-stage → 0.1.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.
Files changed (81) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -2
  3. package/dist/ArtifactReferences.d.ts +7 -0
  4. package/dist/ArtifactReferences.js +82 -0
  5. package/dist/CommandRegistry.d.ts +40 -0
  6. package/dist/CommandRegistry.js +177 -0
  7. package/dist/InspectionOutput.d.ts +5 -0
  8. package/dist/InspectionOutput.js +11 -0
  9. package/dist/RecordingReplay.d.ts +24 -0
  10. package/dist/RecordingReplay.js +79 -0
  11. package/dist/WorkflowContext.d.ts +20 -0
  12. package/dist/WorkflowContext.js +1 -0
  13. package/dist/capabilities/form.d.ts +13 -0
  14. package/dist/capabilities/form.js +9 -0
  15. package/dist/capabilities/interaction.d.ts +226 -0
  16. package/dist/capabilities/interaction.js +447 -0
  17. package/dist/capabilities/session.d.ts +18 -0
  18. package/dist/capabilities/session.js +55 -0
  19. package/dist/catalog.d.ts +36 -0
  20. package/dist/catalog.js +69 -0
  21. package/dist/commands/app-inspect.d.ts +96 -0
  22. package/dist/commands/app-inspect.js +70 -0
  23. package/dist/commands/app.d.ts +53 -0
  24. package/dist/commands/app.js +104 -0
  25. package/dist/commands/artifact-query.d.ts +138 -0
  26. package/dist/commands/artifact-query.js +81 -0
  27. package/dist/commands/artifacts.d.ts +40 -0
  28. package/dist/commands/artifacts.js +311 -0
  29. package/dist/commands/doctor.d.ts +11 -0
  30. package/dist/commands/doctor.js +285 -0
  31. package/dist/commands/flow-runtime.d.ts +40 -0
  32. package/dist/commands/flow-runtime.js +37 -0
  33. package/dist/commands/flow.d.ts +122 -0
  34. package/dist/commands/flow.js +236 -0
  35. package/dist/commands/generate-test.d.ts +46 -0
  36. package/dist/commands/generate-test.js +233 -0
  37. package/dist/commands/init.d.ts +22 -0
  38. package/dist/commands/init.js +262 -0
  39. package/dist/commands/mock-management.d.ts +53 -0
  40. package/dist/commands/mock-management.js +65 -0
  41. package/dist/commands/mock.d.ts +8 -0
  42. package/dist/commands/mock.js +27 -0
  43. package/dist/commands/record.d.ts +55 -0
  44. package/dist/commands/record.js +216 -0
  45. package/dist/commands/run.d.ts +93 -0
  46. package/dist/commands/run.js +707 -0
  47. package/dist/commands/scenario.d.ts +26 -0
  48. package/dist/commands/scenario.js +39 -0
  49. package/dist/commands/tdd.d.ts +72 -0
  50. package/dist/commands/tdd.js +218 -0
  51. package/dist/config.d.ts +20 -0
  52. package/dist/config.js +40 -0
  53. package/dist/index.d.ts +10 -0
  54. package/dist/index.js +139 -0
  55. package/dist/registry/devices.d.ts +2 -0
  56. package/dist/registry/devices.js +12 -0
  57. package/dist/registry/finite.d.ts +38 -0
  58. package/dist/registry/finite.js +121 -0
  59. package/dist/registry/flow-schemas.d.ts +405 -0
  60. package/dist/registry/flow-schemas.js +98 -0
  61. package/dist/registry/flow.d.ts +3 -0
  62. package/dist/registry/flow.js +56 -0
  63. package/dist/registry/generation-schema.d.ts +112 -0
  64. package/dist/registry/generation-schema.js +36 -0
  65. package/dist/registry/session.d.ts +2 -0
  66. package/dist/registry/session.js +24 -0
  67. package/dist/registry/tdd.d.ts +3 -0
  68. package/dist/registry/tdd.js +118 -0
  69. package/dist/reporter.d.ts +95 -0
  70. package/dist/reporter.js +61 -0
  71. package/dist/run.d.ts +6 -0
  72. package/dist/run.js +5 -0
  73. package/dist/session/ConnectionHost.d.ts +43 -0
  74. package/dist/session/ConnectionHost.js +129 -0
  75. package/dist/session/client.d.ts +38 -0
  76. package/dist/session/client.js +120 -0
  77. package/dist/session/worker.d.ts +1 -0
  78. package/dist/session/worker.js +161 -0
  79. package/dist/vm-discovery.d.ts +14 -0
  80. package/dist/vm-discovery.js +85 -0
  81. package/package.json +78 -3
@@ -0,0 +1,236 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { resolveProjectConfig } from '../config.js';
3
+ import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { dirname, join } from 'node:path';
5
+ import { AiRuntime, FLIWRIGHT_FLOWS_DIR, buildFlowAgentSpec, buildFlowReviewBundle, buildFlowReviewReport, buildFlowReviewPlan, buildFlowVisualComparisons, captureFigmaReviewScreenshots, cleanFlowWithAi, FigmaRestScreenshotProvider, figmaBindingFromUrl, flowFilePath, generateFlowTestSkeleton, resolveAiConfig, sanitizeFlowFileId, validateFlow, } from '@fliwright/core';
6
+ export async function flowListCommand(options = {}) {
7
+ const cwd = options.cwd ?? process.cwd();
8
+ const flowsDir = join(cwd, FLIWRIGHT_FLOWS_DIR);
9
+ let entries;
10
+ try {
11
+ entries = await readdir(flowsDir);
12
+ }
13
+ catch {
14
+ return { flows: [] };
15
+ }
16
+ const flows = [];
17
+ for (const entry of entries.filter((name) => name.endsWith('.flow.json'))) {
18
+ const path = join(flowsDir, entry);
19
+ try {
20
+ const flow = await readFlowAtPath(path);
21
+ flows.push({
22
+ id: flow.id,
23
+ ...(flow.title ? { title: flow.title } : {}),
24
+ updatedAt: flow.updatedAt,
25
+ ...(flow.source ? { source: flow.source } : {}),
26
+ path,
27
+ nodeCount: flow.nodes.length,
28
+ edgeCount: flow.edges.length,
29
+ });
30
+ }
31
+ catch {
32
+ // Ignore malformed draft files so a single bad flow does not hide the rest.
33
+ }
34
+ }
35
+ flows.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
36
+ return { flows };
37
+ }
38
+ export async function flowGetCommand(options) {
39
+ const path = resolveFlowPath(options);
40
+ return {
41
+ path,
42
+ flow: await readFlowAtPath(path),
43
+ };
44
+ }
45
+ export async function flowBindFigmaCommand(options) {
46
+ const path = resolveFlowPath(options);
47
+ const flow = await readFlowAtPath(path);
48
+ const nodeIndex = flow.nodes.findIndex((node) => node.id === options.flowNodeId);
49
+ if (nodeIndex === -1) {
50
+ throw new Error(`Flow node not found: ${options.flowNodeId}`);
51
+ }
52
+ const currentNode = flow.nodes[nodeIndex];
53
+ const binding = resolveFigmaBinding(options, currentNode.figma);
54
+ if (!binding.fileKey) {
55
+ throw new Error('Pass --figma-url or --file-key.');
56
+ }
57
+ const node = {
58
+ ...currentNode,
59
+ figma: binding,
60
+ };
61
+ const nextFlow = {
62
+ ...flow,
63
+ updatedAt: new Date().toISOString(),
64
+ nodes: flow.nodes.map((candidate, index) => index === nodeIndex ? node : candidate),
65
+ };
66
+ await writeFlowAtPath(path, nextFlow);
67
+ return { path, flow: nextFlow, node };
68
+ }
69
+ export async function flowAgentSpecCommand(options) {
70
+ const { path, flow } = await flowGetCommand(options);
71
+ return {
72
+ path,
73
+ spec: buildFlowAgentSpec(flow),
74
+ };
75
+ }
76
+ export async function flowCleanCommand(options) {
77
+ const { path, flow } = await flowGetCommand(options);
78
+ const config = options.aiRuntime ? undefined : await resolveProjectConfig(options.cwd ?? process.cwd());
79
+ const aiRuntime = options.aiRuntime ?? new AiRuntime(resolveAiConfig({
80
+ artifactsDir: join(config.cacheRoot, 'inspect', randomUUID(), 'ai'),
81
+ provider: options.aiProvider,
82
+ timeoutMs: options.aiTimeoutMs,
83
+ }));
84
+ const result = await cleanFlowWithAi(flow, {
85
+ ai: aiRuntime,
86
+ timeoutMs: options.aiTimeoutMs,
87
+ protectedNodeIds: options.protectedNodeIds,
88
+ instructions: options.instructions,
89
+ });
90
+ const outputPath = options.outputPath ?? path;
91
+ if (!options.dryRun) {
92
+ await writeFlowAtPath(outputPath, result.flow);
93
+ }
94
+ return {
95
+ path,
96
+ outputPath,
97
+ flow: result.flow,
98
+ plan: result.plan,
99
+ dryRun: Boolean(options.dryRun),
100
+ };
101
+ }
102
+ export async function flowReviewPlanCommand(options) {
103
+ const { path, flow } = await flowGetCommand(options);
104
+ return {
105
+ path,
106
+ reviewPlan: buildFlowReviewPlan(flow, {
107
+ pixelDiffTolerance: options.pixelDiffTolerance,
108
+ layoutPxTolerance: options.layoutPxTolerance,
109
+ }),
110
+ };
111
+ }
112
+ export async function flowReviewBundleCommand(options) {
113
+ const { path, flow } = await flowGetCommand(options);
114
+ const cwd = options.cwd ?? process.cwd();
115
+ const outputDir = options.outputDir ?? join(cwd, '.fliwright', 'reviews', sanitizeFlowFileId(flow.id));
116
+ const bundle = buildFlowReviewBundle(flow, {
117
+ flowPath: path,
118
+ outputDir,
119
+ pixelDiffTolerance: options.pixelDiffTolerance,
120
+ layoutPxTolerance: options.layoutPxTolerance,
121
+ });
122
+ const outputPath = options.outputPath ?? join(outputDir, `${sanitizeFlowFileId(flow.id)}-review-bundle.json`);
123
+ await mkdir(dirname(outputPath), { recursive: true });
124
+ await writeFile(outputPath, `${JSON.stringify(bundle, null, 2)}\n`, 'utf8');
125
+ return { path, outputPath, bundle };
126
+ }
127
+ export async function flowReviewCaptureFigmaCommand(options) {
128
+ const { path, flow } = await flowGetCommand(options);
129
+ const cwd = options.cwd ?? process.cwd();
130
+ const outputDir = options.outputDir ?? join(cwd, '.fliwright', 'reviews', sanitizeFlowFileId(flow.id), 'figma');
131
+ const bundle = buildFlowReviewBundle(flow, {
132
+ flowPath: path,
133
+ outputDir: dirname(outputDir),
134
+ pixelDiffTolerance: options.pixelDiffTolerance,
135
+ layoutPxTolerance: options.layoutPxTolerance,
136
+ });
137
+ const provider = options.figmaProvider ?? new FigmaRestScreenshotProvider({
138
+ accessToken: options.accessToken,
139
+ scale: options.scale,
140
+ });
141
+ const captures = await captureFigmaReviewScreenshots(bundle.figmaMcp.tasks.map((task) => ({
142
+ ...task,
143
+ screenshotPath: join(outputDir, `${task.screenshotPath.split('/').pop()}`),
144
+ metadataPath: join(outputDir, `${task.metadataPath.split('/').pop()}`),
145
+ })), provider);
146
+ const capturesFile = options.capturesFile ?? join(outputDir, 'figma-captures.json');
147
+ await mkdir(dirname(capturesFile), { recursive: true });
148
+ await writeFile(capturesFile, `${JSON.stringify(captures, null, 2)}\n`, 'utf8');
149
+ return { path, outputDir, capturesFile, captures };
150
+ }
151
+ export async function flowReviewReportCommand(options) {
152
+ const { path, reviewPlan } = await flowReviewPlanCommand(options);
153
+ const autoComparisons = (options.autoCompare ?? true)
154
+ ? await buildFlowVisualComparisons({
155
+ runtimeCaptures: options.runtimeCaptures,
156
+ figmaCaptures: options.figmaCaptures,
157
+ pixelThreshold: options.pixelThreshold,
158
+ })
159
+ : [];
160
+ const report = buildFlowReviewReport({
161
+ reviewPlan,
162
+ runtimeCaptures: options.runtimeCaptures,
163
+ figmaCaptures: options.figmaCaptures,
164
+ comparisons: [
165
+ ...autoComparisons,
166
+ ...(options.comparisons ?? []),
167
+ ],
168
+ });
169
+ const cwd = options.cwd ?? process.cwd();
170
+ const reportPath = options.outputPath ?? join(cwd, '.fliwright', 'reviews', `${sanitizeFlowFileId(report.flowId)}-report.json`);
171
+ await mkdir(dirname(reportPath), { recursive: true });
172
+ await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`, 'utf8');
173
+ return { path, reportPath, report };
174
+ }
175
+ export async function flowGenerateTestCommand(options) {
176
+ const { path, flow } = await flowGetCommand(options);
177
+ const code = generateFlowTestSkeleton(flow, {
178
+ testName: options.testName,
179
+ resetToHomeBeforeEach: options.resetToHomeBeforeEach,
180
+ homeRoute: options.homeRoute,
181
+ useFlowSteps: options.useFlowSteps,
182
+ });
183
+ if (options.outputFile) {
184
+ await mkdir(dirname(options.outputFile), { recursive: true });
185
+ await writeFile(options.outputFile, `${code}\n`, 'utf8');
186
+ }
187
+ return {
188
+ path,
189
+ code,
190
+ ...(options.outputFile ? { outputFile: options.outputFile } : {}),
191
+ };
192
+ }
193
+ export async function flowValidateCommand(options) {
194
+ const { path, flow } = await flowGetCommand(options);
195
+ return {
196
+ path,
197
+ validation: validateFlow(flow, {
198
+ requireCodeTargetForFigmaNodes: options.requireCodeTargetForFigmaNodes,
199
+ requireReviewRuntimeEntryForFigmaNodes: options.requireReviewRuntimeEntryForFigmaNodes,
200
+ }),
201
+ };
202
+ }
203
+ function resolveFlowPath(options) {
204
+ const cwd = options.cwd ?? process.cwd();
205
+ const path = options.path ?? (options.id ? flowFilePath(cwd, options.id) : undefined);
206
+ if (!path) {
207
+ throw new Error('Pass a flow id or --path <file>.');
208
+ }
209
+ return path;
210
+ }
211
+ async function readFlowAtPath(path) {
212
+ return JSON.parse(await readFile(path, 'utf8'));
213
+ }
214
+ async function writeFlowAtPath(path, flow) {
215
+ await mkdir(dirname(path), { recursive: true });
216
+ await writeFile(path, `${JSON.stringify(flow, null, 2)}\n`, 'utf8');
217
+ }
218
+ function resolveFigmaBinding(options, existing) {
219
+ const fromUrl = options.figmaUrl ? figmaBindingFromUrl(options.figmaUrl, existing) : null;
220
+ return {
221
+ ...(existing ?? {}),
222
+ ...(fromUrl ?? {}),
223
+ fileKey: options.fileKey ?? fromUrl?.fileKey ?? existing?.fileKey ?? '',
224
+ nodeId: normalizeFigmaNodeId(options.figmaNodeId) ?? fromUrl?.nodeId ?? existing?.nodeId ?? '',
225
+ ...(options.figmaUrl ? { url: options.figmaUrl } : {}),
226
+ ...(options.name ? { name: options.name } : {}),
227
+ ...(options.codeConnectId ? { codeConnectId: options.codeConnectId } : {}),
228
+ ...(options.componentName ? { componentName: options.componentName } : {}),
229
+ };
230
+ }
231
+ function normalizeFigmaNodeId(nodeId) {
232
+ return nodeId?.replace(/-/g, ':');
233
+ }
234
+ export function flowIdFromPath(path) {
235
+ return sanitizeFlowFileId(path.replace(/\.flow\.json$/u, ''));
236
+ }
@@ -0,0 +1,46 @@
1
+ import type { InteractionSpec } from '@fliwright/tdd';
2
+ import type { TddWorkflowContext } from '../WorkflowContext.js';
3
+ interface GenerationContext {
4
+ setTddWorkflowContext(context: TddWorkflowContext): void;
5
+ }
6
+ import type { GenerateTestResult } from '../WorkflowContext.js';
7
+ export interface SnapshotRefInput {
8
+ role: string;
9
+ label: string;
10
+ key?: string;
11
+ type?: string;
12
+ selector?: string;
13
+ textField?: boolean;
14
+ }
15
+ export interface RedFirstGenerateTestParams {
16
+ mode?: 'red-first';
17
+ spec: InteractionSpec;
18
+ flowId?: string;
19
+ allFlows?: boolean;
20
+ flowIds?: string[];
21
+ testNamePrefix?: string;
22
+ snapshot?: string;
23
+ refs?: SnapshotRefInput[];
24
+ testName?: string;
25
+ resetToHomeBeforeEach?: boolean;
26
+ homeRoute?: string;
27
+ outputFile?: string;
28
+ }
29
+ export declare function generateTestCommand(params: {
30
+ mode?: 'default' | 'red-first';
31
+ spec?: InteractionSpec;
32
+ flowId?: string;
33
+ allFlows?: boolean;
34
+ flowIds?: string[];
35
+ testNamePrefix?: string;
36
+ source?: string;
37
+ snapshot?: string;
38
+ refs?: SnapshotRefInput[];
39
+ description?: string;
40
+ testName?: string;
41
+ resetToHomeBeforeEach?: boolean;
42
+ homeRoute?: string;
43
+ outputFile?: string;
44
+ }, state?: GenerationContext): Promise<GenerateTestResult>;
45
+ export declare function prepareRedFirstGeneratedTest(params: RedFirstGenerateTestParams, state?: GenerationContext): Promise<GenerateTestResult>;
46
+ export {};
@@ -0,0 +1,233 @@
1
+ import { mkdir, writeFile } from 'node:fs/promises';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { analyzeInteractionSpecCoverage, generateRedFirstTestSuite, prepareRedFirstWorkflow } from '@fliwright/tdd';
4
+ function parseFlutterSource(source) {
5
+ const widgets = [];
6
+ // Extract AppBar title
7
+ const appBarRegex = /AppBar\([^)]*title:\s*Text\(['"]([^'"]+)['"]\)/;
8
+ const appBarMatch = appBarRegex.exec(source);
9
+ if (appBarMatch) {
10
+ widgets.push({ type: 'appBar', text: appBarMatch[1] });
11
+ }
12
+ // Extract TextField with hintText
13
+ const hintRegex = /TextField\([^)]*hintText:\s*['"]([^'"]+)['"]/g;
14
+ let match;
15
+ while ((match = hintRegex.exec(source)) !== null) {
16
+ widgets.push({ type: 'textField', text: match[1], hintText: match[1] });
17
+ }
18
+ // Extract TextFormField with hintText or labelText
19
+ const formFieldRegex = /TextFormField\([^)]*(?:hintText|labelText):\s*['"]([^'"]+)['"]/g;
20
+ while ((match = formFieldRegex.exec(source)) !== null) {
21
+ widgets.push({ type: 'textField', text: match[1], hintText: match[1] });
22
+ }
23
+ // Extract ElevatedButton/TextButton child Text
24
+ // Use [\s\S]*? instead of [^)]* to handle nested parens like onPressed: () {}
25
+ const buttonRegex = /(?:ElevatedButton|TextButton|OutlinedButton)\([\s\S]*?child:\s*Text\(['"]([^'"]+)['"]\)/g;
26
+ while ((match = buttonRegex.exec(source)) !== null) {
27
+ widgets.push({ type: 'button', text: match[1] });
28
+ }
29
+ // Extract Text('...') widgets (general)
30
+ const textRegex = /Text\(['"]([^'"]+)['"]\)/g;
31
+ while ((match = textRegex.exec(source)) !== null) {
32
+ widgets.push({ type: 'text', text: match[1] });
33
+ }
34
+ return widgets;
35
+ }
36
+ function stringLiteral(value) {
37
+ return JSON.stringify(value);
38
+ }
39
+ function normalizeSnapshotRefs(refs, snapshot) {
40
+ if (refs?.length) {
41
+ return refs.filter((ref) => ref.label?.trim());
42
+ }
43
+ if (!snapshot)
44
+ return [];
45
+ const parsed = [];
46
+ const lineRegex = /-\s+([a-zA-Z][\w-]*)\s+"([^"]+)"\s+\[ref=[^\]]+\]/g;
47
+ let match;
48
+ while ((match = lineRegex.exec(snapshot)) !== null) {
49
+ parsed.push({ role: match[1], label: unescapeSnapshotLabel(match[2]) });
50
+ }
51
+ return parsed;
52
+ }
53
+ function unescapeSnapshotLabel(value) {
54
+ return value.replace(/\\"/g, '"').replace(/\\\\/g, '\\');
55
+ }
56
+ function appendSnapshotBasedSteps(lines, refs) {
57
+ const textFields = refs.filter((ref) => ref.textField || ref.role === 'textbox');
58
+ const buttons = refs.filter((ref) => ref.role === 'button' || ref.role === 'link');
59
+ const visibleText = refs.filter((ref) => ref.role === 'heading' || ref.role === 'text');
60
+ for (const field of textFields.slice(0, 3)) {
61
+ const variable = uniqueVarName('field', field.label, lines);
62
+ lines.push(` const ${variable} = await page.findRef(${findQueryFor(field)});`);
63
+ lines.push(` await ${variable}.fill(${stringLiteral('test_input')});`);
64
+ }
65
+ for (const button of buttons.slice(0, 2)) {
66
+ const variable = uniqueVarName('button', button.label, lines);
67
+ lines.push(` const ${variable} = await page.findRef(${findQueryFor(button)});`);
68
+ lines.push(` await ${variable}.click();`);
69
+ }
70
+ const assertionTarget = visibleText.at(-1) ?? buttons.at(-1) ?? textFields.at(-1);
71
+ if (assertionTarget) {
72
+ lines.push(` await expect(page.locator({ text: ${stringLiteral(assertionTarget.label)} })).toBeVisible();`);
73
+ }
74
+ }
75
+ function appendSourceBasedSteps(lines, widgets) {
76
+ const textWidgets = widgets.filter(w => w.type === 'text');
77
+ const buttonWidgets = widgets.filter(w => w.type === 'button');
78
+ const textFieldWidgets = widgets.filter(w => w.type === 'textField');
79
+ for (const field of textFieldWidgets) {
80
+ const selector = `{ text: ${stringLiteral(field.hintText ?? field.text)} }`;
81
+ lines.push(` await page.locator(${selector}).click();`);
82
+ lines.push(` await page.locator(${selector}).type(${stringLiteral('test_input')});`);
83
+ }
84
+ for (const btn of buttonWidgets) {
85
+ lines.push(` await page.locator({ text: ${stringLiteral(btn.text)} }).click();`);
86
+ }
87
+ if (textWidgets.length > 0) {
88
+ const lastText = textWidgets[textWidgets.length - 1];
89
+ lines.push(` await expect(page.locator({ text: ${stringLiteral(lastText.text)} })).toBeVisible();`);
90
+ }
91
+ }
92
+ function findQueryFor(ref) {
93
+ if (ref.key)
94
+ return `{ key: ${stringLiteral(ref.key)} }`;
95
+ const parts = [`role: ${stringLiteral(ref.role)}`, `text: ${stringLiteral(ref.label)}`];
96
+ if (ref.type)
97
+ parts.push(`type: ${stringLiteral(ref.type)}`);
98
+ return `{ ${parts.join(', ')} }`;
99
+ }
100
+ function uniqueVarName(prefix, label, existingLines) {
101
+ const base = `${prefix}${toPascal(label)}`.slice(0, 40) || prefix;
102
+ let candidate = base;
103
+ let suffix = 2;
104
+ while (existingLines.some((line) => line.includes(`const ${candidate} `))) {
105
+ candidate = `${base}${suffix++}`;
106
+ }
107
+ return candidate;
108
+ }
109
+ function toPascal(value) {
110
+ const ascii = value
111
+ .normalize('NFKD')
112
+ .replace(/[^a-zA-Z0-9]+/g, ' ')
113
+ .trim()
114
+ .split(/\s+/)
115
+ .filter(Boolean)
116
+ .map((part) => part[0].toUpperCase() + part.slice(1))
117
+ .join('');
118
+ return ascii || 'Target';
119
+ }
120
+ export async function generateTestCommand(params, state) {
121
+ if (params.mode === 'red-first') {
122
+ if (!params.spec)
123
+ throw new Error("mode 'red-first' requires an InteractionSpec in params.spec.");
124
+ return await prepareRedFirstGeneratedTest(params, state);
125
+ }
126
+ const testName = params.testName ?? 'generated test';
127
+ const resetToHomeBeforeEach = params.resetToHomeBeforeEach ?? true;
128
+ const homeRoute = params.homeRoute ?? '/';
129
+ const refs = normalizeSnapshotRefs(params.refs, params.snapshot);
130
+ const widgets = refs.length > 0 ? [] : parseFlutterSource(params.source ?? '');
131
+ const lines = [];
132
+ const imports = resetToHomeBeforeEach ? 'test, expect, beforeEach' : 'test, expect';
133
+ lines.push(`import { ${imports} } from '@fliwright/vitest';`);
134
+ lines.push('');
135
+ if (resetToHomeBeforeEach) {
136
+ lines.push('beforeEach(async ({ page }) => {');
137
+ lines.push(` await page.resetToHome({ homeRoute: ${stringLiteral(homeRoute)} });`);
138
+ lines.push('});');
139
+ lines.push('');
140
+ }
141
+ lines.push(`test(${stringLiteral(testName)}, async ({ page }) => {`);
142
+ if (refs.length > 0) {
143
+ appendSnapshotBasedSteps(lines, refs);
144
+ }
145
+ else {
146
+ appendSourceBasedSteps(lines, widgets);
147
+ }
148
+ lines.push('});');
149
+ const output = {
150
+ testCode: lines.join('\n'),
151
+ testName,
152
+ };
153
+ return await persistGeneratedTest(output, params.outputFile);
154
+ }
155
+ export async function prepareRedFirstGeneratedTest(params, state) {
156
+ const outputFile = params.outputFile ? resolve(params.outputFile) : undefined;
157
+ const refs = normalizeSnapshotRefs(params.refs, params.snapshot);
158
+ if (params.allFlows) {
159
+ const coverage = analyzeInteractionSpecCoverage(params.spec);
160
+ const result = generateRedFirstTestSuite(params.spec, {
161
+ flowIds: params.flowIds,
162
+ testNamePrefix: params.testNamePrefix,
163
+ homeRoute: params.homeRoute,
164
+ resetToHomeBeforeEach: params.resetToHomeBeforeEach,
165
+ widgets: snapshotRefsToWidgetCandidates(refs),
166
+ });
167
+ const output = {
168
+ testCode: result.testCode,
169
+ testName: params.testName ?? params.testNamePrefix ?? 'red-first suite',
170
+ testFile: outputFile,
171
+ warnings: result.warnings,
172
+ selectorDiagnostics: result.selectorDiagnostics,
173
+ tests: result.tests,
174
+ coverage,
175
+ };
176
+ const persisted = await persistGeneratedTest(output, outputFile);
177
+ state?.setTddWorkflowContext({
178
+ testFile: persisted.testFile,
179
+ selectorDiagnostics: result.selectorDiagnostics,
180
+ tests: result.tests,
181
+ coverage,
182
+ });
183
+ return persisted;
184
+ }
185
+ const result = prepareRedFirstWorkflow(params.spec, {
186
+ flowId: params.flowId,
187
+ testName: params.testName,
188
+ homeRoute: params.homeRoute,
189
+ resetToHomeBeforeEach: params.resetToHomeBeforeEach,
190
+ widgets: snapshotRefsToWidgetCandidates(refs),
191
+ testFile: outputFile,
192
+ });
193
+ const output = {
194
+ testCode: result.testCode,
195
+ testName: result.testName,
196
+ testFile: outputFile,
197
+ warnings: result.warnings,
198
+ selectorDiagnostics: result.selectorDiagnostics,
199
+ workflow: result.workflow,
200
+ coverage: result.workflow.coverage,
201
+ };
202
+ const persisted = await persistGeneratedTest(output, outputFile);
203
+ state?.setTddWorkflowContext({
204
+ testName: result.testName,
205
+ flowId: result.flowId,
206
+ testFile: persisted.testFile,
207
+ selectorDiagnostics: result.selectorDiagnostics,
208
+ coverage: result.workflow.coverage,
209
+ workflow: result.workflow,
210
+ });
211
+ return persisted;
212
+ }
213
+ function snapshotRefsToWidgetCandidates(refs) {
214
+ return refs.map((ref) => ({
215
+ key: ref.key,
216
+ text: ref.label,
217
+ type: ref.type,
218
+ role: ref.role,
219
+ }));
220
+ }
221
+ async function persistGeneratedTest(result, outputFile) {
222
+ if (!outputFile)
223
+ return result;
224
+ const absolutePath = resolve(outputFile);
225
+ await mkdir(dirname(absolutePath), { recursive: true });
226
+ await writeFile(absolutePath, result.testCode, 'utf8');
227
+ const { testCode: _testCode, ...metadata } = result;
228
+ await writeFile(`${absolutePath}.workflow.json`, JSON.stringify({ schemaVersion: 1, ...metadata, testFile: absolutePath }, null, 2) + '\n', 'utf8');
229
+ return {
230
+ ...result,
231
+ testFile: absolutePath,
232
+ };
233
+ }
@@ -0,0 +1,22 @@
1
+ export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';
2
+ export interface InitOptions {
3
+ install?: boolean;
4
+ node?: boolean;
5
+ flutter?: boolean;
6
+ packageManager?: PackageManager;
7
+ }
8
+ export interface InitResult {
9
+ created: string[];
10
+ updated: string[];
11
+ skipped: string[];
12
+ commands: Array<{
13
+ command: string;
14
+ args: string[];
15
+ cwd: string;
16
+ }>;
17
+ }
18
+ export interface InitDeps {
19
+ log?: (message: string) => void;
20
+ runCommand?: (command: string, args: string[], cwd: string) => Promise<void>;
21
+ }
22
+ export declare function initCommand(projectDir: string, options?: InitOptions, deps?: InitDeps): Promise<InitResult>;