feat(automation): implement dual-mode browser automation with DevTools adapter - Add explicit result types for all automation operations (NavigationResult, FormFillResult, ClickResult, WaitResult, ModalResult) - Implement BrowserDevToolsAdapter for real browser automation via Chrome DevTools Protocol - Create IRacingSelectorMap with CSS selectors for all 18 workflow steps - Add AutomationConfig for environment-based adapter selection (mock/dev/production) - Update DI container to support mode switching via AUTOMATION_MODE env var - Add 54 new tests (34 integration + 20 unit), total now 212 passing - Add npm scripts: companion:mock, companion:devtools, chrome:debug

This commit is contained in:
2025-11-21 19:54:37 +01:00
parent 33b6557eed
commit a980a288ea
18 changed files with 2446 additions and 94 deletions

View File

@@ -1,11 +1,42 @@
import { InMemorySessionRepository } from '../../../infrastructure/repositories/InMemorySessionRepository';
import { MockBrowserAutomationAdapter } from '../../../infrastructure/adapters/automation/MockBrowserAutomationAdapter';
import { BrowserDevToolsAdapter } from '../../../infrastructure/adapters/automation/BrowserDevToolsAdapter';
import { MockAutomationEngineAdapter } from '../../../infrastructure/adapters/automation/MockAutomationEngineAdapter';
import { StartAutomationSessionUseCase } from '../../../packages/application/use-cases/StartAutomationSessionUseCase';
import { loadAutomationConfig, AutomationMode } from '../../../infrastructure/config';
import type { ISessionRepository } from '../../../packages/application/ports/ISessionRepository';
import type { IBrowserAutomation } from '../../../packages/application/ports/IBrowserAutomation';
import type { IAutomationEngine } from '../../../packages/application/ports/IAutomationEngine';
/**
* Create browser automation adapter based on configuration mode.
*
* @param mode - The automation mode from configuration
* @returns IBrowserAutomation adapter instance
*/
function createBrowserAutomationAdapter(mode: AutomationMode): IBrowserAutomation {
const config = loadAutomationConfig();
switch (mode) {
case 'dev':
return new BrowserDevToolsAdapter({
debuggingPort: config.devTools?.debuggingPort,
browserWSEndpoint: config.devTools?.browserWSEndpoint,
defaultTimeout: config.defaultTimeout,
});
case 'production':
// Production mode will use nut.js adapter in the future
// For now, fall back to mock adapter with a warning
console.warn('Production mode (nut.js) not yet implemented, using mock adapter');
return new MockBrowserAutomationAdapter();
case 'mock':
default:
return new MockBrowserAutomationAdapter();
}
}
export class DIContainer {
private static instance: DIContainer;
@@ -13,10 +44,14 @@ export class DIContainer {
private browserAutomation: IBrowserAutomation;
private automationEngine: IAutomationEngine;
private startAutomationUseCase: StartAutomationSessionUseCase;
private automationMode: AutomationMode;
private constructor() {
const config = loadAutomationConfig();
this.automationMode = config.mode;
this.sessionRepository = new InMemorySessionRepository();
this.browserAutomation = new MockBrowserAutomationAdapter();
this.browserAutomation = createBrowserAutomationAdapter(config.mode);
this.automationEngine = new MockAutomationEngineAdapter(
this.browserAutomation,
this.sessionRepository
@@ -46,4 +81,19 @@ export class DIContainer {
public getAutomationEngine(): IAutomationEngine {
return this.automationEngine;
}
public getAutomationMode(): AutomationMode {
return this.automationMode;
}
public getBrowserAutomation(): IBrowserAutomation {
return this.browserAutomation;
}
/**
* Reset the singleton instance (useful for testing with different configurations).
*/
public static resetInstance(): void {
DIContainer.instance = undefined as unknown as DIContainer;
}
}

View File

@@ -1,4 +1,5 @@
import { ipcMain, BrowserWindow } from 'electron';
import { ipcMain } from 'electron';
import type { BrowserWindow, IpcMainInvokeEvent } from 'electron';
import { DIContainer } from './di-container';
import type { HostedSessionConfig } from '../../../packages/domain/entities/HostedSessionConfig';
import { StepId } from '../../../packages/domain/value-objects/StepId';
@@ -9,7 +10,7 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
const sessionRepository = container.getSessionRepository();
const automationEngine = container.getAutomationEngine();
ipcMain.handle('start-automation', async (_event, config: HostedSessionConfig) => {
ipcMain.handle('start-automation', async (_event: IpcMainInvokeEvent, config: HostedSessionConfig) => {
try {
const result = await startAutomationUseCase.execute(config);
const session = await sessionRepository.findById(result.sessionId);
@@ -55,7 +56,7 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
}
});
ipcMain.handle('get-session-status', async (_event, sessionId: string) => {
ipcMain.handle('get-session-status', async (_event: IpcMainInvokeEvent, sessionId: string) => {
const session = await sessionRepository.findById(sessionId);
if (!session) {
return { found: false };
@@ -71,11 +72,11 @@ export function setupIpcHandlers(mainWindow: BrowserWindow): void {
};
});
ipcMain.handle('pause-automation', async (_event, _sessionId: string) => {
ipcMain.handle('pause-automation', async (_event: IpcMainInvokeEvent, _sessionId: string) => {
return { success: false, error: 'Pause not implemented in POC' };
});
ipcMain.handle('resume-automation', async (_event, _sessionId: string) => {
ipcMain.handle('resume-automation', async (_event: IpcMainInvokeEvent, _sessionId: string) => {
return { success: false, error: 'Resume not implemented in POC' };
});
}

View File

@@ -0,0 +1,462 @@
import puppeteer, { Browser, Page, CDPSession } from 'puppeteer-core';
import { StepId } from '../../../packages/domain/value-objects/StepId';
import { IBrowserAutomation } from '../../../packages/application/ports/IBrowserAutomation';
import {
NavigationResult,
FormFillResult,
ClickResult,
WaitResult,
ModalResult,
} from '../../../packages/application/ports/AutomationResults';
import { IRacingSelectorMap, getStepSelectors, getStepName } from './selectors/IRacingSelectorMap';
/**
* Configuration for connecting to browser via Chrome DevTools Protocol
*/
export interface DevToolsConfig {
/** WebSocket endpoint URL (e.g., ws://127.0.0.1:9222/devtools/browser/...) */
browserWSEndpoint?: string;
/** Chrome debugging port (default: 9222) */
debuggingPort?: number;
/** Default timeout for operations in milliseconds (default: 30000) */
defaultTimeout?: number;
/** Human-like typing delay in milliseconds (default: 50) */
typingDelay?: number;
/** Whether to wait for network idle after navigation (default: true) */
waitForNetworkIdle?: boolean;
}
/**
* BrowserDevToolsAdapter - Real browser automation using Puppeteer-core.
*
* This adapter connects to an existing browser session via Chrome DevTools Protocol (CDP)
* and automates the iRacing hosted session creation workflow.
*
* Key features:
* - Connects to existing browser (doesn't launch new one)
* - Uses IRacingSelectorMap for element location
* - Human-like typing delays for form filling
* - Waits for network idle after navigation
* - Disconnects without closing browser
*
* Usage:
* 1. Start Chrome with remote debugging:
* `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --remote-debugging-port=9222`
* 2. Navigate to iRacing and log in manually
* 3. Create adapter and connect:
* ```
* const adapter = new BrowserDevToolsAdapter({ debuggingPort: 9222 });
* await adapter.connect();
* ```
*/
export class BrowserDevToolsAdapter implements IBrowserAutomation {
private browser: Browser | null = null;
private page: Page | null = null;
private config: Required<DevToolsConfig>;
private connected: boolean = false;
constructor(config: DevToolsConfig = {}) {
this.config = {
browserWSEndpoint: config.browserWSEndpoint ?? '',
debuggingPort: config.debuggingPort ?? 9222,
defaultTimeout: config.defaultTimeout ?? 30000,
typingDelay: config.typingDelay ?? 50,
waitForNetworkIdle: config.waitForNetworkIdle ?? true,
};
}
/**
* Connect to an existing browser via Chrome DevTools Protocol.
* The browser must be started with --remote-debugging-port flag.
*/
async connect(): Promise<void> {
if (this.connected) {
return;
}
try {
if (this.config.browserWSEndpoint) {
// Connect using explicit WebSocket endpoint
this.browser = await puppeteer.connect({
browserWSEndpoint: this.config.browserWSEndpoint,
});
} else {
// Connect using debugging port - need to fetch endpoint first
const response = await fetch(`http://127.0.0.1:${this.config.debuggingPort}/json/version`);
const data = await response.json();
const wsEndpoint = data.webSocketDebuggerUrl;
this.browser = await puppeteer.connect({
browserWSEndpoint: wsEndpoint,
});
}
// Find iRacing tab or use the first available tab
const pages = await this.browser.pages();
this.page = await this.findIRacingPage(pages) || pages[0];
if (!this.page) {
throw new Error('No pages found in browser');
}
// Set default timeout
this.page.setDefaultTimeout(this.config.defaultTimeout);
this.connected = true;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to connect to browser: ${errorMessage}`);
}
}
/**
* Disconnect from the browser without closing it.
* The user can continue using the browser after disconnection.
*/
async disconnect(): Promise<void> {
if (this.browser) {
// Disconnect without closing - user may still use the browser
this.browser.disconnect();
this.browser = null;
this.page = null;
}
this.connected = false;
}
/**
* Check if adapter is connected to browser.
*/
isConnected(): boolean {
return this.connected && this.browser !== null && this.page !== null;
}
/**
* Navigate to a URL and wait for the page to load.
*/
async navigateToPage(url: string): Promise<NavigationResult> {
this.ensureConnected();
const startTime = Date.now();
try {
const waitUntil = this.config.waitForNetworkIdle ? 'networkidle2' : 'domcontentloaded';
await this.page!.goto(url, { waitUntil });
const loadTime = Date.now() - startTime;
return {
success: true,
url,
loadTime,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
success: false,
url,
loadTime: Date.now() - startTime,
error: `Navigation failed: ${errorMessage}`,
};
}
}
/**
* Fill a form field with human-like typing delay.
*
* @param fieldName - Field identifier (will be looked up in selector map or used directly)
* @param value - Value to type into the field
*/
async fillFormField(fieldName: string, value: string): Promise<FormFillResult> {
this.ensureConnected();
try {
// Try to find the element
const element = await this.page!.$(fieldName);
if (!element) {
return {
success: false,
fieldName,
valueSet: '',
error: `Field not found: ${fieldName}`,
};
}
// Clear existing value and type new value with human-like delay
await element.click({ clickCount: 3 }); // Select all existing text
await element.type(value, { delay: this.config.typingDelay });
return {
success: true,
fieldName,
valueSet: value,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
success: false,
fieldName,
valueSet: '',
error: `Failed to fill field: ${errorMessage}`,
};
}
}
/**
* Click an element on the page.
*/
async clickElement(selector: string): Promise<ClickResult> {
this.ensureConnected();
try {
// Wait for element to be visible and clickable
await this.page!.waitForSelector(selector, {
visible: true,
timeout: this.config.defaultTimeout
});
await this.page!.click(selector);
return {
success: true,
target: selector,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
success: false,
target: selector,
error: `Click failed: ${errorMessage}`,
};
}
}
/**
* Wait for an element to appear on the page.
*/
async waitForElement(selector: string, maxWaitMs: number = 5000): Promise<WaitResult> {
this.ensureConnected();
const startTime = Date.now();
try {
await this.page!.waitForSelector(selector, {
timeout: maxWaitMs,
visible: true
});
return {
success: true,
target: selector,
waitedMs: Date.now() - startTime,
found: true,
};
} catch (error) {
return {
success: false,
target: selector,
waitedMs: Date.now() - startTime,
found: false,
error: `Element not found within ${maxWaitMs}ms`,
};
}
}
/**
* Handle modal operations for specific workflow steps.
* Modal steps are: 6 (SET_ADMINS), 9 (ADD_CAR), 12 (ADD_TRACK)
*/
async handleModal(stepId: StepId, action: string): Promise<ModalResult> {
this.ensureConnected();
if (!stepId.isModalStep()) {
return {
success: false,
stepId: stepId.value,
action,
error: `Step ${stepId.value} (${getStepName(stepId.value)}) is not a modal step`,
};
}
try {
const stepSelectors = getStepSelectors(stepId.value);
if (!stepSelectors?.modal) {
return {
success: false,
stepId: stepId.value,
action,
error: `No modal selectors defined for step ${stepId.value}`,
};
}
const modalSelectors = stepSelectors.modal;
switch (action) {
case 'open':
// Wait for and verify modal is open
await this.page!.waitForSelector(modalSelectors.container, {
visible: true,
timeout: this.config.defaultTimeout,
});
break;
case 'close':
// Click close button
await this.page!.click(modalSelectors.closeButton);
// Wait for modal to disappear
await this.page!.waitForSelector(modalSelectors.container, {
hidden: true,
timeout: this.config.defaultTimeout,
});
break;
case 'search':
// Focus search input if available
if (modalSelectors.searchInput) {
await this.page!.click(modalSelectors.searchInput);
}
break;
case 'select':
// Click select/confirm button
if (modalSelectors.selectButton) {
await this.page!.click(modalSelectors.selectButton);
}
break;
default:
return {
success: false,
stepId: stepId.value,
action,
error: `Unknown modal action: ${action}`,
};
}
return {
success: true,
stepId: stepId.value,
action,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
success: false,
stepId: stepId.value,
action,
error: `Modal operation failed: ${errorMessage}`,
};
}
}
// ============== Helper Methods ==============
/**
* Find the iRacing page among open browser tabs.
*/
private async findIRacingPage(pages: Page[]): Promise<Page | null> {
for (const page of pages) {
const url = page.url();
if (url.includes('iracing.com') || url.includes('members-ng.iracing.com')) {
return page;
}
}
return null;
}
/**
* Ensure adapter is connected before operations.
*/
private ensureConnected(): void {
if (!this.isConnected()) {
throw new Error('Not connected to browser. Call connect() first.');
}
}
// ============== Extended Methods for Workflow Automation ==============
/**
* Navigate to a specific step in the wizard using sidebar navigation.
*/
async navigateToStep(stepId: StepId): Promise<NavigationResult> {
this.ensureConnected();
const startTime = Date.now();
const stepSelectors = getStepSelectors(stepId.value);
if (!stepSelectors?.sidebarLink) {
return {
success: false,
url: '',
loadTime: 0,
error: `No sidebar link defined for step ${stepId.value} (${getStepName(stepId.value)})`,
};
}
try {
await this.page!.click(stepSelectors.sidebarLink);
// Wait for step container to be visible
if (stepSelectors.container) {
await this.page!.waitForSelector(stepSelectors.container, { visible: true });
}
return {
success: true,
url: this.page!.url(),
loadTime: Date.now() - startTime,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
success: false,
url: this.page!.url(),
loadTime: Date.now() - startTime,
error: `Failed to navigate to step: ${errorMessage}`,
};
}
}
/**
* Get the current page URL.
*/
getCurrentUrl(): string {
if (!this.page) {
return '';
}
return this.page.url();
}
/**
* Take a screenshot of the current page (useful for debugging).
*/
async takeScreenshot(path: string): Promise<void> {
this.ensureConnected();
await this.page!.screenshot({ path, fullPage: true });
}
/**
* Get the current page content (useful for debugging).
*/
async getPageContent(): Promise<string> {
this.ensureConnected();
return await this.page!.content();
}
/**
* Wait for network to be idle (no pending requests).
*/
async waitForNetworkIdle(timeout: number = 5000): Promise<void> {
this.ensureConnected();
await this.page!.waitForNetworkIdle({ timeout });
}
/**
* Execute JavaScript in the page context.
*/
async evaluate<T>(fn: () => T): Promise<T> {
this.ensureConnected();
return await this.page!.evaluate(fn);
}
}

View File

@@ -1,6 +1,13 @@
import { StepId } from '../../../packages/domain/value-objects/StepId';
import { HostedSessionConfig } from '../../../packages/domain/entities/HostedSessionConfig';
import { IBrowserAutomation } from '../../../packages/application/ports/IBrowserAutomation';
import {
NavigationResult,
FormFillResult,
ClickResult,
WaitResult,
ModalResult,
} from '../../../packages/application/ports/AutomationResults';
interface MockConfig {
simulateFailures?: boolean;
@@ -19,40 +26,9 @@ interface StepExecutionResult {
};
}
interface NavigationResult {
success: boolean;
url: string;
simulatedDelay: number;
}
interface FormFillResult {
success: boolean;
fieldName: string;
value: string;
simulatedDelay: number;
}
interface ClickResult {
success: boolean;
selector: string;
simulatedDelay: number;
}
interface WaitResult {
success: boolean;
selector: string;
simulatedDelay: number;
}
interface ModalResult {
success: boolean;
stepId: number;
action: string;
simulatedDelay: number;
}
export class MockBrowserAutomationAdapter implements IBrowserAutomation {
private config: MockConfig;
private connected: boolean = false;
constructor(config: MockConfig = {}) {
this.config = {
@@ -61,13 +37,25 @@ export class MockBrowserAutomationAdapter implements IBrowserAutomation {
};
}
async connect(): Promise<void> {
this.connected = true;
}
async disconnect(): Promise<void> {
this.connected = false;
}
isConnected(): boolean {
return this.connected;
}
async navigateToPage(url: string): Promise<NavigationResult> {
const delay = this.randomDelay(200, 800);
await this.sleep(delay);
return {
success: true,
url,
simulatedDelay: delay,
loadTime: delay,
};
}
@@ -77,8 +65,7 @@ export class MockBrowserAutomationAdapter implements IBrowserAutomation {
return {
success: true,
fieldName,
value,
simulatedDelay: delay,
valueSet: value,
};
}
@@ -87,8 +74,7 @@ export class MockBrowserAutomationAdapter implements IBrowserAutomation {
await this.sleep(delay);
return {
success: true,
selector,
simulatedDelay: delay,
target: selector,
};
}
@@ -99,8 +85,9 @@ export class MockBrowserAutomationAdapter implements IBrowserAutomation {
return {
success: true,
selector,
simulatedDelay: delay,
target: selector,
waitedMs: delay,
found: true,
};
}
@@ -115,7 +102,6 @@ export class MockBrowserAutomationAdapter implements IBrowserAutomation {
success: true,
stepId: stepId.value,
action,
simulatedDelay: delay,
};
}

View File

@@ -0,0 +1,22 @@
/**
* Automation adapters for browser automation.
*
* Exports:
* - MockBrowserAutomationAdapter: Mock adapter for testing
* - BrowserDevToolsAdapter: Real browser automation via Chrome DevTools Protocol
* - IRacingSelectorMap: CSS selectors for iRacing UI elements
*/
// Adapters
export { MockBrowserAutomationAdapter } from './MockBrowserAutomationAdapter';
export { BrowserDevToolsAdapter, DevToolsConfig } from './BrowserDevToolsAdapter';
// Selector map and utilities
export {
IRacingSelectorMap,
IRacingSelectorMapType,
StepSelectors,
getStepSelectors,
getStepName,
isModalStep,
} from './selectors/IRacingSelectorMap';

View File

@@ -0,0 +1,399 @@
/**
* CSS Selector map for iRacing hosted session workflow.
* Selectors are derived from HTML samples in resources/iracing-hosted-sessions/
*
* The iRacing UI uses Chakra UI/React with dynamic CSS classes.
* We prefer stable selectors: data-testid, id, aria-labels, role attributes.
*/
export interface StepSelectors {
/** Primary container/step identifier */
container?: string;
/** Wizard sidebar navigation link */
sidebarLink?: string;
/** Wizard top navigation link */
wizardNav?: string;
/** Form fields for this step */
fields?: Record<string, string>;
/** Buttons specific to this step */
buttons?: Record<string, string>;
/** Modal selectors if this is a modal step */
modal?: {
container: string;
closeButton: string;
confirmButton?: string;
searchInput?: string;
resultsList?: string;
selectButton?: string;
};
}
export interface IRacingSelectorMapType {
/** Common selectors used across multiple steps */
common: {
mainModal: string;
modalDialog: string;
modalContent: string;
modalTitle: string;
modalCloseButton: string;
checkoutButton: string;
backButton: string;
nextButton: string;
wizardContainer: string;
wizardSidebar: string;
searchInput: string;
loadingSpinner: string;
};
/** Step-specific selectors */
steps: Record<number, StepSelectors>;
/** iRacing-specific URLs */
urls: {
base: string;
hostedRacing: string;
login: string;
};
}
/**
* Complete selector map for iRacing hosted session creation workflow.
*
* Steps:
* 1. LOGIN - Login page (handled externally)
* 2. HOSTED_RACING - Navigate to hosted racing section
* 3. CREATE_RACE - Click create race button
* 4. RACE_INFORMATION - Fill session name, password, description
* 5. SERVER_DETAILS - Select server region, launch time
* 6. SET_ADMINS - Admin configuration (modal at step 6)
* 7. TIME_LIMITS - Configure time limits
* 8. SET_CARS - Car selection overview
* 9. ADD_CAR - Add a car (modal at step 9)
* 10. SET_CAR_CLASSES - Configure car classes
* 11. SET_TRACK - Track selection overview
* 12. ADD_TRACK - Add a track (modal at step 12)
* 13. TRACK_OPTIONS - Configure track options
* 14. TIME_OF_DAY - Configure time of day
* 15. WEATHER - Configure weather
* 16. RACE_OPTIONS - Configure race options
* 17. TEAM_DRIVING - Configure team driving
* 18. TRACK_CONDITIONS - Final review (safety checkpoint - no final submit)
*/
export const IRacingSelectorMap: IRacingSelectorMapType = {
common: {
mainModal: '#create-race-modal',
modalDialog: '#create-race-modal-modal-dialog',
modalContent: '#create-race-modal-modal-content',
modalTitle: '[data-testid="modal-title"]',
modalCloseButton: '.modal-header .close, [data-testid="button-close-modal"]',
checkoutButton: '.btn.btn-success',
backButton: '.btn.btn-secondary:has(.icon-caret-left)',
nextButton: '.btn.btn-secondary:has(.icon-caret-right)',
wizardContainer: '#create-race-wizard',
wizardSidebar: '.wizard-sidebar',
searchInput: '.wizard-sidebar input[type="text"][placeholder="Search"]',
loadingSpinner: '.loader-container .loader',
},
urls: {
base: 'https://members-ng.iracing.com',
hostedRacing: 'https://members-ng.iracing.com/web/racing/hosted',
login: 'https://members-ng.iracing.com/login',
},
steps: {
// Step 1: LOGIN - External, handled before automation
1: {
container: '#login-form, .login-container',
fields: {
email: 'input[name="email"], #email',
password: 'input[name="password"], #password',
},
buttons: {
submit: 'button[type="submit"], .login-button',
},
},
// Step 2: HOSTED_RACING - Navigate to hosted racing page
2: {
container: '#hosted-sessions, [data-page="hosted"]',
sidebarLink: 'a[href*="/racing/hosted"]',
buttons: {
createRace: '.btn:has-text("Create a Race"), [data-action="create-race"]',
},
},
// Step 3: CREATE_RACE - Click create race to open modal
3: {
container: '[data-modal-component="ModalCreateRace"]',
buttons: {
createRace: 'button:has-text("Create a Race"), .btn-primary:has-text("Create")',
},
},
// Step 4: RACE_INFORMATION - Fill session name, password, description
4: {
container: '#set-session-information',
sidebarLink: '#wizard-sidebar-link-set-session-information',
wizardNav: '[data-testid="wizard-nav-set-session-information"]',
fields: {
sessionName: '.form-group:has(label:has-text("Session Name")) input, input[name="sessionName"]',
password: '.form-group:has(label:has-text("Password")) input, input[name="password"]',
description: '.form-group:has(label:has-text("Description")) textarea, textarea[name="description"]',
},
buttons: {
next: '.wizard-footer .btn:has-text("Server Details")',
},
},
// Step 5: SERVER_DETAILS - Select server region and launch time
5: {
container: '#set-server-details',
sidebarLink: '#wizard-sidebar-link-set-server-details',
wizardNav: '[data-testid="wizard-nav-set-server-details"]',
fields: {
serverRegion: '.chakra-accordion__button[data-index="0"]',
launchTime: 'input[name="launchTime"], [id*="field-"]:has(+ [placeholder="Now"])',
startNow: '.switch:has(input[value="startNow"])',
},
buttons: {
next: '.wizard-footer .btn:has-text("Admins")',
back: '.wizard-footer .btn:has-text("Race Information")',
},
},
// Step 6: SET_ADMINS - Admin configuration (modal step)
6: {
container: '#set-admins',
sidebarLink: '#wizard-sidebar-link-set-admins',
wizardNav: '[data-testid="wizard-nav-set-admins"]',
buttons: {
addAdmin: '.btn:has-text("Add Admin"), .btn-primary:has(.icon-add)',
next: '.wizard-footer .btn:has-text("Time Limit")',
back: '.wizard-footer .btn:has-text("Server Details")',
},
modal: {
container: '#add-admin-modal, .modal:has([data-modal-component="AddAdmin"])',
closeButton: '.modal .close, [data-testid="button-close-modal"]',
searchInput: 'input[placeholder*="Search"], input[name="adminSearch"]',
resultsList: '.admin-list, .search-results',
selectButton: '.btn:has-text("Select"), .btn-primary:has-text("Add")',
},
},
// Step 7: TIME_LIMITS - Configure time limits
7: {
container: '#set-time-limit',
sidebarLink: '#wizard-sidebar-link-set-time-limit',
wizardNav: '[data-testid="wizard-nav-set-time-limit"]',
fields: {
practiceLength: 'input[name="practiceLength"]',
qualifyLength: 'input[name="qualifyLength"]',
raceLength: 'input[name="raceLength"]',
warmupLength: 'input[name="warmupLength"]',
},
buttons: {
next: '.wizard-footer .btn:has-text("Cars")',
back: '.wizard-footer .btn:has-text("Admins")',
},
},
// Step 8: SET_CARS - Car selection overview
8: {
container: '#set-cars',
sidebarLink: '#wizard-sidebar-link-set-cars',
wizardNav: '[data-testid="wizard-nav-set-cars"]',
buttons: {
addCar: '.btn:has-text("Add Car"), .btn-primary:has(.icon-add)',
next: '.wizard-footer .btn:has-text("Track")',
back: '.wizard-footer .btn:has-text("Time Limit")',
},
},
// Step 9: ADD_CAR - Add a car (modal step)
9: {
container: '#set-cars',
sidebarLink: '#wizard-sidebar-link-set-cars',
wizardNav: '[data-testid="wizard-nav-set-cars"]',
modal: {
container: '#add-car-modal, .modal:has(.car-list)',
closeButton: '.modal .close, [aria-label="Close"]',
searchInput: 'input[placeholder*="Search"], .car-search input',
resultsList: '.car-list table tbody, .car-grid',
selectButton: '.btn:has-text("Select"), .btn-primary.btn-xs:has-text("Select")',
},
},
// Step 10: SET_CAR_CLASSES - Configure car classes
10: {
container: '#set-car-classes, #set-cars',
sidebarLink: '#wizard-sidebar-link-set-cars',
wizardNav: '[data-testid="wizard-nav-set-cars"]',
fields: {
carClass: 'select[name="carClass"], .car-class-select',
},
buttons: {
next: '.wizard-footer .btn:has-text("Track")',
},
},
// Step 11: SET_TRACK - Track selection overview
11: {
container: '#set-track',
sidebarLink: '#wizard-sidebar-link-set-track',
wizardNav: '[data-testid="wizard-nav-set-track"]',
buttons: {
addTrack: '.btn:has-text("Add Track"), .btn-primary:has(.icon-add)',
next: '.wizard-footer .btn:has-text("Track Options")',
back: '.wizard-footer .btn:has-text("Cars")',
},
},
// Step 12: ADD_TRACK - Add a track (modal step)
12: {
container: '#set-track',
sidebarLink: '#wizard-sidebar-link-set-track',
wizardNav: '[data-testid="wizard-nav-set-track"]',
modal: {
container: '#add-track-modal, .modal:has(.track-list)',
closeButton: '.modal .close, [aria-label="Close"]',
searchInput: 'input[placeholder*="Search"], .track-search input',
resultsList: '.track-list table tbody, .track-grid',
selectButton: '.btn:has-text("Select"), .btn-primary.btn-xs:has-text("Select")',
},
},
// Step 13: TRACK_OPTIONS - Configure track options
13: {
container: '#set-track-options',
sidebarLink: '#wizard-sidebar-link-set-track-options',
wizardNav: '[data-testid="wizard-nav-set-track-options"]',
fields: {
trackConfig: 'select[name="trackConfig"]',
pitStalls: 'input[name="pitStalls"]',
},
buttons: {
next: '.wizard-footer .btn:has-text("Time of Day")',
back: '.wizard-footer .btn:has-text("Track")',
},
},
// Step 14: TIME_OF_DAY - Configure time of day
14: {
container: '#set-time-of-day',
sidebarLink: '#wizard-sidebar-link-set-time-of-day',
wizardNav: '[data-testid="wizard-nav-set-time-of-day"]',
fields: {
timeOfDay: 'input[name="timeOfDay"], .time-slider',
date: 'input[name="date"], .date-picker',
},
buttons: {
next: '.wizard-footer .btn:has-text("Weather")',
back: '.wizard-footer .btn:has-text("Track Options")',
},
},
// Step 15: WEATHER - Configure weather
15: {
container: '#set-weather',
sidebarLink: '#wizard-sidebar-link-set-weather',
wizardNav: '[data-testid="wizard-nav-set-weather"]',
fields: {
weatherType: 'select[name="weatherType"]',
temperature: 'input[name="temperature"]',
humidity: 'input[name="humidity"]',
windSpeed: 'input[name="windSpeed"]',
windDirection: 'input[name="windDirection"]',
},
buttons: {
next: '.wizard-footer .btn:has-text("Race Options")',
back: '.wizard-footer .btn:has-text("Time of Day")',
},
},
// Step 16: RACE_OPTIONS - Configure race options
16: {
container: '#set-race-options',
sidebarLink: '#wizard-sidebar-link-set-race-options',
wizardNav: '[data-testid="wizard-nav-set-race-options"]',
fields: {
maxDrivers: 'input[name="maxDrivers"]',
hardcoreIncidents: '.switch:has(input[name="hardcoreIncidents"])',
rollingStarts: '.switch:has(input[name="rollingStarts"])',
fullCourseCautions: '.switch:has(input[name="fullCourseCautions"])',
},
buttons: {
next: '.wizard-footer .btn:has-text("Track Conditions")',
back: '.wizard-footer .btn:has-text("Weather")',
},
},
// Step 17: TEAM_DRIVING - Configure team driving (if applicable)
17: {
container: '#set-team-driving',
fields: {
teamDriving: '.switch:has(input[name="teamDriving"])',
minDrivers: 'input[name="minDrivers"]',
maxDrivers: 'input[name="maxDrivers"]',
},
buttons: {
next: '.wizard-footer .btn:has-text("Track Conditions")',
back: '.wizard-footer .btn:has-text("Race Options")',
},
},
// Step 18: TRACK_CONDITIONS - Final review (safety checkpoint - NO final submit)
18: {
container: '#set-track-conditions',
sidebarLink: '#wizard-sidebar-link-set-track-conditions',
wizardNav: '[data-testid="wizard-nav-set-track-conditions"]',
fields: {
trackState: 'select[name="trackState"]',
marbles: '.switch:has(input[name="marbles"])',
rubberedTrack: '.switch:has(input[name="rubberedTrack"])',
},
buttons: {
// NOTE: Checkout button is intentionally NOT included for safety
// The automation should stop here and let the user review/confirm manually
back: '.wizard-footer .btn:has-text("Race Options")',
},
},
},
};
/**
* Get selectors for a specific step
*/
export function getStepSelectors(stepId: number): StepSelectors | undefined {
return IRacingSelectorMap.steps[stepId];
}
/**
* Check if a step is a modal step (requires opening a secondary dialog)
*/
export function isModalStep(stepId: number): boolean {
return stepId === 6 || stepId === 9 || stepId === 12;
}
/**
* Get the step name for logging/debugging
*/
export function getStepName(stepId: number): string {
const stepNames: Record<number, string> = {
1: 'LOGIN',
2: 'HOSTED_RACING',
3: 'CREATE_RACE',
4: 'RACE_INFORMATION',
5: 'SERVER_DETAILS',
6: 'SET_ADMINS',
7: 'TIME_LIMITS',
8: 'SET_CARS',
9: 'ADD_CAR',
10: 'SET_CAR_CLASSES',
11: 'SET_TRACK',
12: 'ADD_TRACK',
13: 'TRACK_OPTIONS',
14: 'TIME_OF_DAY',
15: 'WEATHER',
16: 'RACE_OPTIONS',
17: 'TEAM_DRIVING',
18: 'TRACK_CONDITIONS',
};
return stepNames[stepId] || `UNKNOWN_STEP_${stepId}`;
}

View File

@@ -0,0 +1,98 @@
/**
* Automation configuration module for environment-based adapter selection.
*
* This module provides configuration types and loaders for the automation system,
* allowing switching between different adapters based on environment variables.
*/
export type AutomationMode = 'dev' | 'production' | 'mock';
export interface AutomationEnvironmentConfig {
mode: AutomationMode;
/** Dev mode configuration (Browser DevTools) */
devTools?: {
browserWSEndpoint?: string;
debuggingPort?: number;
};
/** Production mode configuration (nut.js) - stub for future implementation */
nutJs?: {
windowTitle?: string;
templatePath?: string;
confidence?: number;
};
/** Default timeout for automation operations in milliseconds */
defaultTimeout?: number;
/** Number of retry attempts for failed operations */
retryAttempts?: number;
/** Whether to capture screenshots on error */
screenshotOnError?: boolean;
}
/**
* Load automation configuration from environment variables.
*
* Environment variables:
* - AUTOMATION_MODE: 'dev' | 'production' | 'mock' (default: 'mock')
* - CHROME_DEBUG_PORT: Chrome debugging port (default: 9222)
* - CHROME_WS_ENDPOINT: WebSocket endpoint for Chrome DevTools
* - IRACING_WINDOW_TITLE: Window title for nut.js (default: 'iRacing')
* - TEMPLATE_PATH: Path to template images (default: './resources/templates')
* - OCR_CONFIDENCE: OCR confidence threshold (default: 0.9)
* - AUTOMATION_TIMEOUT: Default timeout in ms (default: 30000)
* - RETRY_ATTEMPTS: Number of retry attempts (default: 3)
* - SCREENSHOT_ON_ERROR: Capture screenshots on error (default: true)
*
* @returns AutomationEnvironmentConfig with parsed environment values
*/
export function loadAutomationConfig(): AutomationEnvironmentConfig {
const modeEnv = process.env.AUTOMATION_MODE;
const mode: AutomationMode = isValidAutomationMode(modeEnv) ? modeEnv : 'mock';
return {
mode,
devTools: {
debuggingPort: parseIntSafe(process.env.CHROME_DEBUG_PORT, 9222),
browserWSEndpoint: process.env.CHROME_WS_ENDPOINT,
},
nutJs: {
windowTitle: process.env.IRACING_WINDOW_TITLE || 'iRacing',
templatePath: process.env.TEMPLATE_PATH || './resources/templates',
confidence: parseFloatSafe(process.env.OCR_CONFIDENCE, 0.9),
},
defaultTimeout: parseIntSafe(process.env.AUTOMATION_TIMEOUT, 30000),
retryAttempts: parseIntSafe(process.env.RETRY_ATTEMPTS, 3),
screenshotOnError: process.env.SCREENSHOT_ON_ERROR !== 'false',
};
}
/**
* Type guard to validate automation mode string.
*/
function isValidAutomationMode(value: string | undefined): value is AutomationMode {
return value === 'dev' || value === 'production' || value === 'mock';
}
/**
* Safely parse an integer with a default fallback.
*/
function parseIntSafe(value: string | undefined, defaultValue: number): number {
if (value === undefined || value === '') {
return defaultValue;
}
const parsed = parseInt(value, 10);
return isNaN(parsed) ? defaultValue : parsed;
}
/**
* Safely parse a float with a default fallback.
*/
function parseFloatSafe(value: string | undefined, defaultValue: number): number {
if (value === undefined || value === '') {
return defaultValue;
}
const parsed = parseFloat(value);
return isNaN(parsed) ? defaultValue : parsed;
}

View File

@@ -0,0 +1,9 @@
/**
* Configuration module exports for infrastructure layer.
*/
export {
AutomationMode,
AutomationEnvironmentConfig,
loadAutomationConfig,
} from './AutomationConfig';

View File

@@ -0,0 +1,30 @@
export interface AutomationResult {
success: boolean;
error?: string;
metadata?: Record<string, unknown>;
}
export interface NavigationResult extends AutomationResult {
url: string;
loadTime: number;
}
export interface FormFillResult extends AutomationResult {
fieldName: string;
valueSet: string;
}
export interface ClickResult extends AutomationResult {
target: string;
}
export interface WaitResult extends AutomationResult {
target: string;
waitedMs: number;
found: boolean;
}
export interface ModalResult extends AutomationResult {
stepId: number;
action: string;
}

View File

@@ -1,9 +1,20 @@
import { StepId } from '../../domain/value-objects/StepId';
import {
NavigationResult,
FormFillResult,
ClickResult,
WaitResult,
ModalResult,
} from './AutomationResults';
export interface IBrowserAutomation {
navigateToPage(url: string): Promise<any>;
fillFormField(fieldName: string, value: string): Promise<any>;
clickElement(selector: string): Promise<any>;
waitForElement(selector: string, maxWaitMs?: number): Promise<any>;
handleModal(stepId: StepId, action: string): Promise<any>;
navigateToPage(url: string): Promise<NavigationResult>;
fillFormField(fieldName: string, value: string): Promise<FormFillResult>;
clickElement(selector: string): Promise<ClickResult>;
waitForElement(selector: string, maxWaitMs?: number): Promise<WaitResult>;
handleModal(stepId: StepId, action: string): Promise<ModalResult>;
connect?(): Promise<void>;
disconnect?(): Promise<void>;
isConnected?(): boolean;
}