@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,26 @@
1
+ import { type AppSessionDeps, type AppSessionOptions } from '../capabilities/session.js';
2
+ export declare function scenarioListCommand(options?: {
3
+ cwd?: string;
4
+ }): Promise<{
5
+ scenarios: {
6
+ name: string;
7
+ startupIsolation: import("@fliwright/core").ScenarioStartupIsolation;
8
+ layers: ("navigation" | "storage" | "mocks" | "auth" | "state" | "app")[];
9
+ }[];
10
+ }>;
11
+ export declare function scenarioApplyCommand(options: AppSessionOptions & {
12
+ name: string;
13
+ mode?: 'managed-start' | 'attach';
14
+ }, deps?: AppSessionDeps): Promise<import("@fliwright/core").ScenarioApplicationReport>;
15
+ export declare function scenarioResetCommand(options: AppSessionOptions & {
16
+ homeRoute?: string;
17
+ }, deps?: AppSessionDeps): Promise<{
18
+ reset: boolean;
19
+ homeRoute: string;
20
+ storage: "ok" | "unsupported";
21
+ mocks: string;
22
+ }>;
23
+ export declare function scenarioResolveCommand(options: {
24
+ cwd?: string;
25
+ name: string;
26
+ }): Promise<import("@fliwright/core").ResolvedScenario>;
@@ -0,0 +1,39 @@
1
+ import { ScenarioCoordinator, ScenarioResolver } from '@fliwright/core';
2
+ import { loadConfig } from '../config.js';
3
+ import { withAppSession } from '../capabilities/session.js';
4
+ export async function scenarioListCommand(options = {}) {
5
+ const config = await loadConfig(options.cwd ?? process.cwd());
6
+ return {
7
+ scenarios: Object.keys(config.scenarios ?? {}).sort().map((name) => ({
8
+ name,
9
+ startupIsolation: config.scenarios?.[name]?.startupIsolation ?? 'optional',
10
+ layers: config.scenarios?.[name]?.layers.map((layer) => layer.kind) ?? [],
11
+ })),
12
+ };
13
+ }
14
+ export async function scenarioApplyCommand(options, deps = {}) {
15
+ const config = await loadConfig(options.cwd ?? process.cwd());
16
+ const scenario = new ScenarioResolver(config.scenarios ?? {}).resolve(options.name);
17
+ return withAppSession(options, ({ driver }) => new ScenarioCoordinator(driver).apply(scenario, {
18
+ mode: options.mode ?? config.scenarioMode ?? 'attach',
19
+ }), deps);
20
+ }
21
+ export async function scenarioResetCommand(options, deps = {}) {
22
+ return withAppSession(options, async ({ driver }) => {
23
+ await driver.mock.clearFlutterRoutes();
24
+ await driver.mock.clearCalls();
25
+ await driver.mock.setPassthrough(true);
26
+ const storage = await driver.storage.reset({});
27
+ await driver.page.resetToHome({ homeRoute: options.homeRoute ?? '/' });
28
+ return {
29
+ reset: true,
30
+ homeRoute: options.homeRoute ?? '/',
31
+ storage: storage.status,
32
+ mocks: 'cleared',
33
+ };
34
+ }, deps);
35
+ }
36
+ export async function scenarioResolveCommand(options) {
37
+ const config = await loadConfig(options.cwd ?? process.cwd());
38
+ return new ScenarioResolver(config.scenarios ?? {}).resolve(options.name);
39
+ }
@@ -0,0 +1,72 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { TddRuntime } from '@fliwright/tdd';
3
+ import type { CycleOpts, RuntimeSnapshot, TddCycleResult } from '@fliwright/tdd';
4
+ type TddCliResetCategory = 'navigation' | 'riverpod' | 'mock' | 'storage' | 'secureStorage' | 'authTokens' | 'webview' | 'localDb' | 'timers' | 'isolates' | 'permissions';
5
+ export interface TddCycleCommandOptions {
6
+ configRoot: string;
7
+ vmUrl?: string;
8
+ deviceId?: string;
9
+ projectId?: string;
10
+ target?: string;
11
+ flutterArgs?: string[];
12
+ mode?: 'run' | 'drive';
13
+ file: string;
14
+ testName?: string;
15
+ sync?: CycleOpts['sync'];
16
+ changes?: string[];
17
+ fullReset?: boolean;
18
+ autoEscalate?: boolean;
19
+ timeoutMs?: number;
20
+ homeRoute?: string;
21
+ resetCategories?: TddCliResetCategory[];
22
+ riverpodOverrideJson?: string[];
23
+ mockProfile?: string;
24
+ mockDir?: string;
25
+ storageSeedJson?: string;
26
+ statusFile?: string;
27
+ keepAppAlive?: boolean;
28
+ json?: boolean;
29
+ print?: boolean;
30
+ }
31
+ export interface TddStatusCommandOptions {
32
+ configRoot: string;
33
+ statusFile?: string;
34
+ json?: boolean;
35
+ print?: boolean;
36
+ }
37
+ type TddSyncMode = 'none' | 'reload' | 'restart';
38
+ export interface TddSyncCommandOptions {
39
+ configRoot: string;
40
+ vmUrl?: string;
41
+ deviceId?: string;
42
+ projectId?: string;
43
+ target?: string;
44
+ flutterArgs?: string[];
45
+ mode?: 'run' | 'drive';
46
+ sync: TddSyncMode;
47
+ statusFile?: string;
48
+ keepAppAlive?: boolean;
49
+ json?: boolean;
50
+ print?: boolean;
51
+ signal?: AbortSignal;
52
+ }
53
+ export interface TddCommandDeps {
54
+ createRuntime?: () => TddRuntime;
55
+ readFile?: typeof readFile;
56
+ log?: (message: string) => void;
57
+ }
58
+ export interface TddCycleCommandResult {
59
+ snapshot: RuntimeSnapshot;
60
+ result: TddCycleResult;
61
+ stopped: RuntimeSnapshot;
62
+ }
63
+ export interface TddSyncCommandResult {
64
+ snapshot: RuntimeSnapshot;
65
+ lastSync: TddSyncMode;
66
+ synced: RuntimeSnapshot;
67
+ stopped: RuntimeSnapshot;
68
+ }
69
+ export declare function tddCycleCommand(options: TddCycleCommandOptions, deps?: TddCommandDeps): Promise<TddCycleCommandResult>;
70
+ export declare function tddSyncCommand(options: TddSyncCommandOptions, deps?: TddCommandDeps): Promise<TddSyncCommandResult>;
71
+ export declare function tddStatusCommand(options: TddStatusCommandOptions, deps?: TddCommandDeps): Promise<RuntimeSnapshot | null>;
72
+ export {};
@@ -0,0 +1,218 @@
1
+ import { resolveProjectConfig } from '../config.js';
2
+ import { dirname, extname } from 'node:path';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { defaultStatusFilePath, TddRuntime } from '@fliwright/tdd';
5
+ export async function tddCycleCommand(options, deps = {}) {
6
+ if (!options.vmUrl && !options.deviceId) {
7
+ throw new Error('fliwright tdd cycle requires either --vm-url or --device-id.');
8
+ }
9
+ const runtime = deps.createRuntime?.() ?? new TddRuntime();
10
+ const scenario = {
11
+ homeRoute: options.homeRoute ?? '/',
12
+ resetCategories: options.resetCategories ?? ['navigation', 'mock'],
13
+ riverpodOverrides: parseRiverpodOverrideJson(options.riverpodOverrideJson),
14
+ mockProfile: options.mockProfile,
15
+ mockDir: options.mockDir,
16
+ storageSeed: parseStorageSeedJson(options.storageSeedJson),
17
+ };
18
+ const statusFilePath = options.statusFile ?? defaultStatusFilePath(options.configRoot);
19
+ const print = options.print ?? true;
20
+ const snapshot = await runtime.start({
21
+ configRoot: options.configRoot,
22
+ sharedConfig: await resolveProjectConfig(extname(options.configRoot) ? dirname(options.configRoot) : options.configRoot),
23
+ vmServiceUrl: options.vmUrl,
24
+ app: options.deviceId
25
+ ? {
26
+ deviceId: options.deviceId,
27
+ projectId: options.projectId,
28
+ target: options.target,
29
+ flutterArgs: options.flutterArgs,
30
+ mode: options.mode,
31
+ }
32
+ : undefined,
33
+ launchMode: options.vmUrl ? 'attach' : 'start',
34
+ scenario: scenario,
35
+ statusFilePath,
36
+ });
37
+ let result;
38
+ let stopped;
39
+ try {
40
+ await runtime.focus(options.file, options.testName);
41
+ result = await runtime.cycle(options.testName, {
42
+ sync: options.sync ?? 'none',
43
+ changes: options.changes,
44
+ fullReset: options.fullReset,
45
+ autoEscalate: options.autoEscalate ?? true,
46
+ timeoutMs: options.timeoutMs,
47
+ });
48
+ }
49
+ finally {
50
+ await runtime.stop({ keepAppAlive: options.keepAppAlive ?? Boolean(options.vmUrl) });
51
+ stopped = runtime.snapshot();
52
+ }
53
+ if (print) {
54
+ const output = options.json
55
+ ? JSON.stringify({ snapshot, result, stopped }, null, 2)
56
+ : formatCycleResult(result, stopped);
57
+ (deps.log ?? console.log)(output);
58
+ }
59
+ return { snapshot, result, stopped };
60
+ }
61
+ export async function tddSyncCommand(options, deps = {}) {
62
+ if (!options.vmUrl && !options.deviceId) {
63
+ throw new Error('fliwright tdd sync requires either --vm-url or --device-id.');
64
+ }
65
+ if (!['none', 'reload', 'restart'].includes(options.sync)) {
66
+ throw new Error('fliwright tdd sync mode must be one of: none, reload, restart.');
67
+ }
68
+ const runtime = deps.createRuntime?.() ?? new TddRuntime();
69
+ const statusFilePath = options.statusFile ?? defaultStatusFilePath(options.configRoot);
70
+ const print = options.print ?? true;
71
+ let snapshot;
72
+ let synced;
73
+ let stopped;
74
+ const abort = () => { void runtime.cancel(); };
75
+ options.signal?.addEventListener('abort', abort, { once: true });
76
+ try {
77
+ options.signal?.throwIfAborted();
78
+ snapshot = await runtime.start({
79
+ configRoot: options.configRoot,
80
+ sharedConfig: await resolveProjectConfig(extname(options.configRoot) ? dirname(options.configRoot) : options.configRoot),
81
+ vmServiceUrl: options.vmUrl,
82
+ app: options.deviceId
83
+ ? {
84
+ deviceId: options.deviceId,
85
+ projectId: options.projectId,
86
+ target: options.target,
87
+ flutterArgs: options.flutterArgs,
88
+ mode: options.mode,
89
+ }
90
+ : undefined,
91
+ launchMode: options.vmUrl ? 'attach' : 'start',
92
+ statusFilePath,
93
+ });
94
+ options.signal?.throwIfAborted();
95
+ synced = await runtime.syncApp(options.sync);
96
+ options.signal?.throwIfAborted();
97
+ }
98
+ finally {
99
+ options.signal?.removeEventListener('abort', abort);
100
+ await runtime.stop({ keepAppAlive: options.keepAppAlive ?? Boolean(options.vmUrl) });
101
+ stopped = runtime.snapshot();
102
+ }
103
+ if (print) {
104
+ const output = options.json
105
+ ? JSON.stringify({ snapshot, lastSync: synced.lastSync, synced: synced.snapshot, stopped }, null, 2)
106
+ : formatSyncResult(synced.lastSync, synced.snapshot, stopped);
107
+ (deps.log ?? console.log)(output);
108
+ }
109
+ return {
110
+ snapshot,
111
+ lastSync: synced.lastSync,
112
+ synced: synced.snapshot,
113
+ stopped,
114
+ };
115
+ }
116
+ export async function tddStatusCommand(options, deps = {}) {
117
+ const statusFilePath = options.statusFile ?? defaultStatusFilePath(options.configRoot);
118
+ const print = options.print ?? true;
119
+ const read = deps.readFile ?? readFile;
120
+ let snapshot = null;
121
+ try {
122
+ snapshot = JSON.parse(await read(statusFilePath, 'utf8'));
123
+ }
124
+ catch {
125
+ snapshot = null;
126
+ }
127
+ if (print) {
128
+ const output = options.json
129
+ ? JSON.stringify(snapshot, null, 2)
130
+ : snapshot
131
+ ? formatSnapshot(snapshot)
132
+ : `No TDD runtime status found at ${statusFilePath}`;
133
+ (deps.log ?? console.log)(output);
134
+ }
135
+ return snapshot;
136
+ }
137
+ function formatCycleResult(result, stopped) {
138
+ const lines = [
139
+ `TDD ${result.status.toUpperCase()}: ${result.testName ?? '(focused test)'}`,
140
+ `file: ${result.file}`,
141
+ `duration: ${result.durationMs}ms`,
142
+ `sync: ${result.lastSync}`,
143
+ `baseline: ${result.baselineVersion}`,
144
+ ];
145
+ if (result.failure?.message)
146
+ lines.push(`failure: ${result.failure.message}`);
147
+ if (result.unsupportedState?.length)
148
+ lines.push(`unsupported state: ${result.unsupportedState.join(', ')}`);
149
+ lines.push(`runtime: ${stopped.connected ? 'running' : 'stopped'}`);
150
+ return lines.join('\n');
151
+ }
152
+ function formatSyncResult(lastSync, synced, stopped) {
153
+ const lines = [
154
+ `TDD sync: ${lastSync}`,
155
+ `runtime: ${stopped.connected ? 'running' : 'stopped'}`,
156
+ `launch mode: ${synced.launchMode}`,
157
+ `restart capable: ${synced.restartCapable ? 'yes' : 'no'}`,
158
+ `baseline: ${synced.baselineVersion}`,
159
+ ];
160
+ return lines.join('\n');
161
+ }
162
+ function formatSnapshot(snapshot) {
163
+ const lines = [
164
+ `TDD runtime: ${snapshot.connected ? 'connected' : 'stopped'}`,
165
+ `daemon: ${snapshot.daemonStatus}`,
166
+ `launch mode: ${snapshot.launchMode}`,
167
+ `restart capable: ${snapshot.restartCapable ? 'yes' : 'no'}`,
168
+ `baseline: ${snapshot.baselineVersion}`,
169
+ ];
170
+ if (snapshot.focusedTest) {
171
+ lines.push(`focused: ${snapshot.focusedTest.testName ? `${snapshot.focusedTest.testName} ` : ''}${snapshot.focusedTest.file}`);
172
+ }
173
+ if (snapshot.lastResult) {
174
+ lines.push(`last result: ${snapshot.lastResult.status} (${snapshot.lastResult.durationMs}ms)`);
175
+ }
176
+ if (snapshot.unsupportedState?.length)
177
+ lines.push(`unsupported state: ${snapshot.unsupportedState.join(', ')}`);
178
+ return lines.join('\n');
179
+ }
180
+ function parseStorageSeedJson(input) {
181
+ if (input === undefined)
182
+ return undefined;
183
+ let parsed;
184
+ try {
185
+ parsed = JSON.parse(input);
186
+ }
187
+ catch (error) {
188
+ const detail = error instanceof Error ? error.message : String(error);
189
+ throw new Error(`--storage-seed-json must be valid JSON: ${detail}`);
190
+ }
191
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
192
+ throw new Error('--storage-seed-json must be a JSON object.');
193
+ }
194
+ return parsed;
195
+ }
196
+ function parseRiverpodOverrideJson(inputs) {
197
+ if (!inputs?.length)
198
+ return undefined;
199
+ return inputs.map((input, index) => {
200
+ let parsed;
201
+ try {
202
+ parsed = JSON.parse(input);
203
+ }
204
+ catch (error) {
205
+ const detail = error instanceof Error ? error.message : String(error);
206
+ throw new Error(`--riverpod-override-json[${index}] must be valid JSON: ${detail}`);
207
+ }
208
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
209
+ throw new Error(`--riverpod-override-json[${index}] must be a JSON object.`);
210
+ }
211
+ const record = parsed;
212
+ const hasKey = typeof record.provider === 'string' || typeof record.key === 'string';
213
+ if (!hasKey || !Object.prototype.hasOwnProperty.call(record, 'value')) {
214
+ throw new Error(`--riverpod-override-json[${index}] must include { provider | key, value }.`);
215
+ }
216
+ return record;
217
+ });
218
+ }
@@ -0,0 +1,20 @@
1
+ import type { FliwrightPathsConfig, FliwrightProjectConfig, FliwrightRecordingConfig, ResolvedFliwrightConfig, ScenarioExecutionMode, TestScenario } from '@fliwright/core';
2
+ export interface FliwrightCliConfig {
3
+ suites?: Record<string, string>;
4
+ vmServiceUrl?: string;
5
+ timeout: number;
6
+ screenshot: 'file' | 'base64' | 'off';
7
+ testDir: string;
8
+ reporter: 'pretty' | 'json' | 'junit';
9
+ runsRoot?: string;
10
+ cacheRoot?: string;
11
+ recording?: Partial<FliwrightRecordingConfig>;
12
+ paths?: Partial<FliwrightPathsConfig>;
13
+ scenarios?: Record<string, TestScenario>;
14
+ scenarioMode?: ScenarioExecutionMode;
15
+ defaultScenario?: string;
16
+ }
17
+ export declare function defineConfig(overrides?: Partial<FliwrightCliConfig>): FliwrightCliConfig;
18
+ export declare function loadConfig(projectDir: string): Promise<FliwrightCliConfig>;
19
+ /** Resolve serializable settings consistently for commands and external integrations. */
20
+ export declare function resolveProjectConfig(projectDir: string, explicit?: Partial<FliwrightProjectConfig>, environment?: Record<string, string | undefined>): Promise<FliwrightCliConfig & ResolvedFliwrightConfig>;
package/dist/config.js ADDED
@@ -0,0 +1,40 @@
1
+ import { join } from 'node:path';
2
+ import { stat } from 'node:fs/promises';
3
+ import { createJiti } from 'jiti';
4
+ import { mergeFliwrightConfig, readFliwrightEnvironment, resolveFliwrightProjectRoot, resolveFliwrightRunsRoot, resolveFliwrightCacheRoot } from '@fliwright/core';
5
+ const DEFAULTS = {
6
+ timeout: 30000,
7
+ screenshot: 'file',
8
+ testDir: '.fliwright/tests',
9
+ reporter: 'pretty',
10
+ recording: { mode: 'standard' },
11
+ };
12
+ export function defineConfig(overrides = {}) {
13
+ const shared = mergeFliwrightConfig({ project: { ...overrides,
14
+ paths: { ...overrides.paths, ...(overrides.testDir ? { tests: overrides.testDir } : {}) },
15
+ } });
16
+ return { ...DEFAULTS, ...overrides, ...shared, testDir: shared.paths.tests };
17
+ }
18
+ export async function loadConfig(projectDir) {
19
+ const configPath = join(resolveFliwrightProjectRoot(projectDir), 'fliwright.config.ts');
20
+ try {
21
+ await stat(configPath);
22
+ }
23
+ catch {
24
+ return defineConfig();
25
+ }
26
+ const jiti = createJiti(import.meta.url, { moduleCache: false, fsCache: false });
27
+ const raw = await jiti.import(configPath);
28
+ const loaded = (raw.default ?? raw);
29
+ return defineConfig(loaded);
30
+ }
31
+ /** Resolve serializable settings consistently for commands and external integrations. */
32
+ export async function resolveProjectConfig(projectDir, explicit = {}, environment = process.env) {
33
+ const project = await loadConfig(projectDir);
34
+ const shared = mergeFliwrightConfig({ project, environment: readFliwrightEnvironment(environment), explicit });
35
+ const projectRoot = resolveFliwrightProjectRoot(projectDir);
36
+ return { ...project, ...shared, testDir: shared.paths.tests,
37
+ runsRoot: resolveFliwrightRunsRoot({ projectRoot, runsRoot: shared.runsRoot, env: {} }),
38
+ cacheRoot: resolveFliwrightCacheRoot({ projectRoot, cacheRoot: shared.cacheRoot }),
39
+ };
40
+ }
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { CommandRegistry } from './CommandRegistry.js';
3
+ export declare function createRegistry(): CommandRegistry;
4
+ export declare function createProgram(): import("commander").Command;
5
+ /** Execute the same registry used by --help/schema without exiting the embedding process. */
6
+ export declare function executeCli(argv: string[], registry?: CommandRegistry): Promise<{
7
+ stdout: string;
8
+ stderr: string;
9
+ exitCode: number;
10
+ }>;
package/dist/index.js ADDED
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env node
2
+ import { fileURLToPath } from 'node:url';
3
+ import { realpathSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ import { formatJunit, formatPretty } from './reporter.js';
6
+ import { CommandRegistry, CliError, classifyError, requestId } from './CommandRegistry.js';
7
+ import { registerSessions } from './registry/session.js';
8
+ import { sessionRequest } from './session/client.js';
9
+ import { registerTdd } from './registry/tdd.js';
10
+ import { registerFlow } from './registry/flow.js';
11
+ import { registerFinite } from './registry/finite.js';
12
+ import { registerDevices } from './registry/devices.js';
13
+ export function createRegistry() {
14
+ const registry = new CommandRegistry();
15
+ registerFinite(registry);
16
+ registerDevices(registry);
17
+ registerFlow(registry);
18
+ registerTdd(registry);
19
+ registerSessions(registry);
20
+ return registry;
21
+ }
22
+ export function createProgram() {
23
+ return createRegistry().program(async (definition, input, common) => {
24
+ await definition.execute(input, { cwd: resolve(String(common.cwd ?? process.cwd())), requestId: requestId(), signal: new AbortController().signal });
25
+ });
26
+ }
27
+ /** Execute the same registry used by --help/schema without exiting the embedding process. */
28
+ export async function executeCli(argv, registry = createRegistry()) {
29
+ let stdout = '';
30
+ let stderr = '';
31
+ let exitCode = 0;
32
+ let command = argv.filter((entry) => !entry.startsWith('-')).slice(0, 2).join('.');
33
+ let data;
34
+ let sessionOperation = false;
35
+ const id = requestId();
36
+ const json = argv.includes('--json');
37
+ const controller = new AbortController();
38
+ let gracefulInterrupt;
39
+ const interrupt = () => {
40
+ if (gracefulInterrupt) {
41
+ const stop = gracefulInterrupt;
42
+ gracefulInterrupt = undefined;
43
+ stop();
44
+ }
45
+ else
46
+ controller.abort(new DOMException('Command cancelled.', 'AbortError'));
47
+ };
48
+ const waitForInterrupt = (signal) => new Promise((resolveStop) => {
49
+ const cleanup = () => { if (gracefulInterrupt === stop)
50
+ gracefulInterrupt = undefined; signal.removeEventListener('abort', stop); };
51
+ const stop = () => { cleanup(); resolveStop(); };
52
+ if (signal.aborted) {
53
+ resolveStop();
54
+ return;
55
+ }
56
+ gracefulInterrupt = stop;
57
+ signal.addEventListener('abort', stop, { once: true });
58
+ });
59
+ const terminate = () => controller.abort(new DOMException('Command terminated.', 'AbortError'));
60
+ let deadlineTimer;
61
+ let failure;
62
+ let selectedReporter;
63
+ const program = registry.program(async (definition, input, common) => {
64
+ command = definition.path;
65
+ const cwd = resolve(String(common.cwd ?? process.cwd()));
66
+ if (common.deadline !== undefined) {
67
+ const deadline = Number(common.deadline);
68
+ if (!Number.isSafeInteger(deadline) || deadline <= 0)
69
+ throw new CliError('INVALID_INPUT', 'deadline must be a positive integer in milliseconds.', 2);
70
+ deadlineTimer = setTimeout(() => controller.abort(new DOMException('Command deadline exceeded.', 'TimeoutError')), deadline);
71
+ }
72
+ if (json && input.reporter && input.reporter !== 'json')
73
+ throw new CliError('INVALID_INPUT', '--json conflicts with an explicit non-JSON reporter.', 2);
74
+ selectedReporter = input.reporter;
75
+ const session = common.session ?? process.env.FLIWRIGHT_SESSION;
76
+ const routedToSession = Boolean(session && (definition.needsSession || (definition.needsApp && !['run', 'script', 'record'].includes(definition.path)) || ['generate-test', 'tdd.cycle', 'tdd.sync', 'tdd.status'].includes(definition.path)));
77
+ if (routedToSession && (input.vmUrl || input.deviceId))
78
+ throw new CliError('INVALID_INPUT', '--session cannot change its endpoint or device.', 2);
79
+ if (routedToSession && session) {
80
+ sessionOperation = true;
81
+ const onAbort = () => { void sessionRequest(cwd, session, { type: 'cancel', operationId: id }, AbortSignal.timeout(2000)).catch(() => { }); };
82
+ controller.signal.addEventListener('abort', onAbort, { once: true });
83
+ try {
84
+ data = await sessionRequest(cwd, session, { type: 'execute', operationId: id, command: definition.path, input }, controller.signal);
85
+ }
86
+ finally {
87
+ controller.signal.removeEventListener('abort', onAbort);
88
+ }
89
+ }
90
+ else
91
+ data = await definition.execute(input, { cwd, signal: controller.signal, requestId: id, session, waitForInterrupt });
92
+ controller.signal.throwIfAborted();
93
+ });
94
+ program.configureOutput({ writeOut: (message) => { stdout += message; }, writeErr: (message) => { stderr += message; } });
95
+ process.on('SIGINT', interrupt);
96
+ process.once('SIGTERM', terminate);
97
+ try {
98
+ await program.parseAsync(argv, { from: 'user' });
99
+ }
100
+ catch (error) {
101
+ if (error && typeof error === 'object' && 'code' in error && ['commander.helpDisplayed', 'commander.version'].includes(String(error.code))) {
102
+ return { stdout, stderr, exitCode: 0 };
103
+ }
104
+ failure = classifyError(controller.signal.aborted ? controller.signal.reason : error);
105
+ if (failure.data !== undefined)
106
+ data = failure.data;
107
+ exitCode = failure.exitCode;
108
+ }
109
+ finally {
110
+ if (deadlineTimer)
111
+ clearTimeout(deadlineTimer);
112
+ process.removeListener('SIGINT', interrupt);
113
+ process.removeListener('SIGTERM', terminate);
114
+ }
115
+ if (json) {
116
+ stdout = JSON.stringify({ schemaVersion: 1, command, requestId: id, ...(sessionOperation ? { operationId: id } : {}), ok: !failure,
117
+ ...(data !== undefined ? { data } : {}),
118
+ ...(failure ? { error: { code: failure.code, message: failure.message, retryable: false } } : {}),
119
+ }) + '\n';
120
+ // Commander usage errors belong to the envelope; progress stays on stderr.
121
+ if (failure?.code === 'INVALID_INPUT')
122
+ stderr = '';
123
+ }
124
+ else if (data !== undefined) {
125
+ stdout += (['run', 'script'].includes(command) && selectedReporter === 'junit' ? formatJunit(data)
126
+ : ['run', 'script'].includes(command) && !selectedReporter ? formatPretty(data)
127
+ : JSON.stringify(data, null, 2)) + '\n';
128
+ }
129
+ if (failure && !json)
130
+ stderr += `${failure.code}: ${failure.message}\n`;
131
+ return { stdout, stderr, exitCode };
132
+ }
133
+ if (process.argv[1] && fileURLToPath(import.meta.url) === realpathSync(resolve(process.argv[1]))) {
134
+ executeCli(process.argv.slice(2)).then((result) => {
135
+ process.stdout.write(result.stdout);
136
+ process.stderr.write(result.stderr);
137
+ process.exitCode = result.exitCode;
138
+ }).catch((error) => { console.error(error); process.exitCode = 3; });
139
+ }
@@ -0,0 +1,2 @@
1
+ import type { CommandRegistry } from '../CommandRegistry.js';
2
+ export declare function registerDevices(registry: CommandRegistry): void;
@@ -0,0 +1,12 @@
1
+ import { DeviceDiscovery } from '@fliwright/devices';
2
+ import { z } from 'zod';
3
+ export function registerDevices(registry) {
4
+ registry.add({
5
+ path: 'devices.list',
6
+ description: 'Discover local iOS and Android devices and simulators',
7
+ input: z.object({ platform: z.enum(['ios', 'android']).optional() }),
8
+ effects: ['environment-probe'],
9
+ output: 'DeviceInventory',
10
+ execute: (input, context) => new DeviceDiscovery().scan({ platforms: input.platform ? [input.platform] : undefined, signal: context.signal }),
11
+ });
12
+ }
@@ -0,0 +1,38 @@
1
+ import { z } from 'zod';
2
+ import { CommandRegistry } from '../CommandRegistry.js';
3
+ import type { AppSessionDeps } from '../capabilities/session.js';
4
+ export declare const str: z.ZodOptional<z.ZodString>;
5
+ export declare const bool: z.ZodOptional<z.ZodBoolean>;
6
+ export declare const positive: z.ZodOptional<z.ZodNumber>;
7
+ export declare const number: z.ZodOptional<z.ZodNumber>;
8
+ export declare const target: {
9
+ ref: z.ZodOptional<z.ZodString>;
10
+ key: z.ZodOptional<z.ZodString>;
11
+ text: z.ZodOptional<z.ZodString>;
12
+ type: z.ZodOptional<z.ZodString>;
13
+ };
14
+ export declare const snapshot: {
15
+ depth: z.ZodOptional<z.ZodNumber>;
16
+ includeRects: z.ZodOptional<z.ZodBoolean>;
17
+ includeProperties: z.ZodOptional<z.ZodBoolean>;
18
+ };
19
+ export declare const diagnostics: {
20
+ listen: z.ZodOptional<z.ZodBoolean>;
21
+ clear: z.ZodOptional<z.ZodBoolean>;
22
+ limit: z.ZodOptional<z.ZodNumber>;
23
+ kinds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
24
+ streams: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
25
+ };
26
+ export declare const connection: {
27
+ vmUrl: z.ZodOptional<z.ZodString>;
28
+ };
29
+ export declare const artifact: {
30
+ runId: z.ZodOptional<z.ZodString>;
31
+ runsRoot: z.ZodOptional<z.ZodString>;
32
+ allowPartial: z.ZodOptional<z.ZodBoolean>;
33
+ };
34
+ export declare const actionNames: readonly ["doubleClick", "tripleClick", "rightClick", "hover", "focus", "blur", "clear", "pressKey", "setCheckbox", "selectOption", "drag", "dismissModal", "dismissKeyboard", "waitForNetworkIdle"];
35
+ export interface FiniteDeps {
36
+ app?: AppSessionDeps;
37
+ }
38
+ export declare function registerFinite(registry: CommandRegistry, deps?: FiniteDeps): void;