1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
|
// playwright-helpers.js
// Reusable utility functions for Playwright automation
const { chromium, firefox, webkit } = require('playwright');
/**
* Parse extra HTTP headers from environment variables.
* Supports two formats:
* - PW_HEADER_NAME + PW_HEADER_VALUE: Single header (simple, common case)
* - PW_EXTRA_HEADERS: JSON object for multiple headers (advanced)
* Single header format takes precedence if both are set.
* @returns {Object|null} Headers object or null if none configured
*/
function getExtraHeadersFromEnv() {
const headerName = process.env.PW_HEADER_NAME;
const headerValue = process.env.PW_HEADER_VALUE;
if (headerName && headerValue) {
return { [headerName]: headerValue };
}
const headersJson = process.env.PW_EXTRA_HEADERS;
if (headersJson) {
try {
const parsed = JSON.parse(headersJson);
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
return parsed;
}
console.warn('PW_EXTRA_HEADERS must be a JSON object, ignoring...');
} catch (e) {
console.warn('Failed to parse PW_EXTRA_HEADERS as JSON:', e.message);
}
}
return null;
}
/**
* Launch browser with standard configuration
* @param {string} browserType - 'chromium', 'firefox', or 'webkit'
* @param {Object} options - Additional launch options
*/
async function launchBrowser(browserType = 'chromium', options = {}) {
const defaultOptions = {
headless: process.env.HEADLESS !== 'false',
slowMo: process.env.SLOW_MO ? parseInt(process.env.SLOW_MO) : 0,
args: ['--no-sandbox', '--disable-setuid-sandbox']
};
const browsers = { chromium, firefox, webkit };
const browser = browsers[browserType];
if (!browser) {
throw new Error(`Invalid browser type: ${browserType}`);
}
return await browser.launch({ ...defaultOptions, ...options });
}
/**
* Create a new page with viewport and user agent
* @param {Object} context - Browser context
* @param {Object} options - Page options
*/
async function createPage(context, options = {}) {
const page = await context.newPage();
if (options.viewport) {
await page.setViewportSize(options.viewport);
}
if (options.userAgent) {
await page.setExtraHTTPHeaders({
'User-Agent': options.userAgent
});
}
// Set default timeout
page.setDefaultTimeout(options.timeout || 30000);
return page;
}
/**
* Smart wait for page to be ready
* @param {Object} page - Playwright page
* @param {Object} options - Wait options
*/
async function waitForPageReady(page, options = {}) {
const waitOptions = {
waitUntil: options.waitUntil || 'networkidle',
timeout: options.timeout || 30000
};
try {
await page.waitForLoadState(waitOptions.waitUntil, {
timeout: waitOptions.timeout
});
} catch (e) {
console.warn('Page load timeout, continuing...');
}
// Additional wait for dynamic content if selector provided
if (options.waitForSelector) {
await page.waitForSelector(options.waitForSelector, {
timeout: options.timeout
});
}
}
/**
* Safe click with retry logic
* @param {Object} page - Playwright page
* @param {string} selector - Element selector
* @param {Object} options - Click options
*/
async function safeClick(page, selector, options = {}) {
const maxRetries = options.retries || 3;
const retryDelay = options.retryDelay || 1000;
for (let i = 0; i < maxRetries; i++) {
try {
await page.waitForSelector(selector, {
state: 'visible',
timeout: options.timeout || 5000
});
await page.click(selector, {
force: options.force || false,
timeout: options.timeout || 5000
});
return true;
} catch (e) {
if (i === maxRetries - 1) {
console.error(`Failed to click ${selector} after ${maxRetries} attempts`);
throw e;
}
console.log(`Retry ${i + 1}/${maxRetries} for clicking ${selector}`);
await page.waitForTimeout(retryDelay);
}
}
}
/**
* Safe text input with clear before type
* @param {Object} page - Playwright page
* @param {string} selector - Input selector
* @param {string} text - Text to type
* @param {Object} options - Type options
*/
async function safeType(page, selector, text, options = {}) {
await page.waitForSelector(selector, {
state: 'visible',
timeout: options.timeout || 10000
});
if (options.clear !== false) {
await page.fill(selector, '');
}
if (options.slow) {
await page.type(selector, text, { delay: options.delay || 100 });
} else {
await page.fill(selector, text);
}
}
/**
* Extract text from multiple elements
* @param {Object} page - Playwright page
* @param {string} selector - Elements selector
*/
async function extractTexts(page, selector) {
await page.waitForSelector(selector, { timeout: 10000 });
return await page.$$eval(selector, elements =>
elements.map(el => el.textContent?.trim()).filter(Boolean)
);
}
/**
* Take screenshot with timestamp
* @param {Object} page - Playwright page
* @param {string} name - Screenshot name
* @param {Object} options - Screenshot options
*/
async function takeScreenshot(page, name, options = {}) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `${name}-${timestamp}.png`;
await page.screenshot({
path: filename,
fullPage: options.fullPage !== false,
...options
});
console.log(`Screenshot saved: ${filename}`);
return filename;
}
/**
* Handle authentication
* @param {Object} page - Playwright page
* @param {Object} credentials - Username and password
* @param {Object} selectors - Login form selectors
*/
async function authenticate(page, credentials, selectors = {}) {
const defaultSelectors = {
username: 'input[name="username"], input[name="email"], #username, #email',
password: 'input[name="password"], #password',
submit: 'button[type="submit"], input[type="submit"], button:has-text("Login"), button:has-text("Sign in")'
};
const finalSelectors = { ...defaultSelectors, ...selectors };
await safeType(page, finalSelectors.username, credentials.username);
await safeType(page, finalSelectors.password, credentials.password);
await safeClick(page, finalSelectors.submit);
// Wait for navigation or success indicator
await Promise.race([
page.waitForNavigation({ waitUntil: 'networkidle' }),
page.waitForSelector(selectors.successIndicator || '.dashboard, .user-menu, .logout', { timeout: 10000 })
]).catch(() => {
console.log('Login might have completed without navigation');
});
}
/**
* Scroll page
* @param {Object} page - Playwright page
* @param {string} direction - 'down', 'up', 'top', 'bottom'
* @param {number} distance - Pixels to scroll (for up/down)
*/
async function scrollPage(page, direction = 'down', distance = 500) {
switch (direction) {
case 'down':
await page.evaluate(d => window.scrollBy(0, d), distance);
break;
case 'up':
await page.evaluate(d => window.scrollBy(0, -d), distance);
break;
case 'top':
await page.evaluate(() => window.scrollTo(0, 0));
break;
case 'bottom':
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
break;
}
await page.waitForTimeout(500); // Wait for scroll animation
}
/**
* Extract table data
* @param {Object} page - Playwright page
* @param {string} tableSelector - Table selector
*/
async function extractTableData(page, tableSelector) {
await page.waitForSelector(tableSelector);
return await page.evaluate((selector) => {
const table = document.querySelector(selector);
if (!table) return null;
const headers = Array.from(table.querySelectorAll('thead th')).map(th =>
th.textContent?.trim()
);
const rows = Array.from(table.querySelectorAll('tbody tr')).map(tr => {
const cells = Array.from(tr.querySelectorAll('td'));
if (headers.length > 0) {
return cells.reduce((obj, cell, index) => {
obj[headers[index] || `column_${index}`] = cell.textContent?.trim();
return obj;
}, {});
} else {
return cells.map(cell => cell.textContent?.trim());
}
});
return { headers, rows };
}, tableSelector);
}
/**
* Wait for and dismiss cookie banners
* @param {Object} page - Playwright page
* @param {number} timeout - Max time to wait
*/
async function handleCookieBanner(page, timeout = 3000) {
const commonSelectors = [
'button:has-text("Accept")',
'button:has-text("Accept all")',
'button:has-text("OK")',
'button:has-text("Got it")',
'button:has-text("I agree")',
'.cookie-accept',
'#cookie-accept',
'[data-testid="cookie-accept"]'
];
for (const selector of commonSelectors) {
try {
const element = await page.waitForSelector(selector, {
timeout: timeout / commonSelectors.length,
state: 'visible'
});
if (element) {
await element.click();
console.log('Cookie banner dismissed');
return true;
}
} catch (e) {
// Continue to next selector
}
}
return false;
}
/**
* Retry a function with exponential backoff
* @param {Function} fn - Function to retry
* @param {number} maxRetries - Maximum retry attempts
* @param {number} initialDelay - Initial delay in ms
*/
async function retryWithBackoff(fn, maxRetries = 3, initialDelay = 1000) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
lastError = error;
const delay = initialDelay * Math.pow(2, i);
console.log(`Attempt ${i + 1} failed, retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw lastError;
}
/**
* Create browser context with common settings
* @param {Object} browser - Browser instance
* @param {Object} options - Context options
*/
async function createContext(browser, options = {}) {
const envHeaders = getExtraHeadersFromEnv();
// Merge environment headers with any passed in options
const mergedHeaders = {
...envHeaders,
...options.extraHTTPHeaders
};
const defaultOptions = {
viewport: { width: 1280, height: 720 },
userAgent: options.mobile
? 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1'
: undefined,
permissions: options.permissions || [],
geolocation: options.geolocation,
locale: options.locale || 'en-US',
timezoneId: options.timezoneId || 'America/New_York',
// Only include extraHTTPHeaders if we have any
...(Object.keys(mergedHeaders).length > 0 && { extraHTTPHeaders: mergedHeaders })
};
return await browser.newContext({ ...defaultOptions, ...options });
}
/**
* Detect running dev servers on common ports
* @param {Array<number>} customPorts - Additional ports to check
* @returns {Promise<Array>} Array of detected server URLs
*/
async function detectDevServers(customPorts = []) {
const http = require('http');
// Common dev server ports
const commonPorts = [3000, 3001, 3002, 5173, 8080, 8000, 4200, 5000, 9000, 1234];
const allPorts = [...new Set([...commonPorts, ...customPorts])];
const detectedServers = [];
console.log('🔍 Checking for running dev servers...');
for (const port of allPorts) {
try {
await new Promise((resolve, reject) => {
const req = http.request({
hostname: 'localhost',
port: port,
path: '/',
method: 'HEAD',
timeout: 500
}, (res) => {
if (res.statusCode < 500) {
detectedServers.push(`http://localhost:${port}`);
console.log(` ✅ Found server on port ${port}`);
}
resolve();
});
req.on('error', () => resolve());
req.on('timeout', () => {
req.destroy();
resolve();
});
req.end();
});
} catch (e) {
// Port not available, continue
}
}
if (detectedServers.length === 0) {
console.log(' ❌ No dev servers detected');
}
return detectedServers;
}
module.exports = {
launchBrowser,
createPage,
waitForPageReady,
safeClick,
safeType,
extractTexts,
takeScreenshot,
authenticate,
scrollPage,
extractTableData,
handleCookieBanner,
retryWithBackoff,
createContext,
detectDevServers,
getExtraHeadersFromEnv
};
|