@veolab/discoverylab 1.0.0 → 1.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.
@@ -0,0 +1,497 @@
1
+ import {
2
+ PROJECTS_DIR
3
+ } from "./chunk-VY3BLXBW.js";
4
+
5
+ // src/core/testing/playwright.ts
6
+ import { exec, spawn } from "child_process";
7
+ import { promisify } from "util";
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+ import { createRequire } from "module";
11
+ var execAsync = promisify(exec);
12
+ var requireFromHere = createRequire(import.meta.url);
13
+ function resolveInstalledPlaywrightVersion() {
14
+ try {
15
+ const pkgPath = requireFromHere.resolve("playwright/package.json");
16
+ const raw = fs.readFileSync(pkgPath, "utf-8");
17
+ const pkg = JSON.parse(raw);
18
+ return typeof pkg.version === "string" && pkg.version.trim() ? pkg.version.trim() : "installed";
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+ async function isPlaywrightInstalled() {
24
+ return !!resolveInstalledPlaywrightVersion();
25
+ }
26
+ async function getPlaywrightVersion() {
27
+ return resolveInstalledPlaywrightVersion();
28
+ }
29
+ async function installPlaywrightBrowsers() {
30
+ try {
31
+ await execAsync("npx playwright install");
32
+ return { success: true };
33
+ } catch (error) {
34
+ return {
35
+ success: false,
36
+ error: error instanceof Error ? error.message : String(error)
37
+ };
38
+ }
39
+ }
40
+ var BrowserDevices = {
41
+ "Desktop Chrome": {
42
+ name: "Desktop Chrome",
43
+ viewport: { width: 1280, height: 720 },
44
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
45
+ deviceScaleFactor: 1,
46
+ isMobile: false,
47
+ hasTouch: false
48
+ },
49
+ "Desktop Safari": {
50
+ name: "Desktop Safari",
51
+ viewport: { width: 1280, height: 720 },
52
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15",
53
+ deviceScaleFactor: 1,
54
+ isMobile: false,
55
+ hasTouch: false
56
+ },
57
+ "iPhone 15 Pro": {
58
+ name: "iPhone 15 Pro",
59
+ viewport: { width: 393, height: 852 },
60
+ userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",
61
+ deviceScaleFactor: 3,
62
+ isMobile: true,
63
+ hasTouch: true
64
+ },
65
+ "iPhone 14": {
66
+ name: "iPhone 14",
67
+ viewport: { width: 390, height: 844 },
68
+ userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1",
69
+ deviceScaleFactor: 3,
70
+ isMobile: true,
71
+ hasTouch: true
72
+ },
73
+ "Pixel 8": {
74
+ name: "Pixel 8",
75
+ viewport: { width: 412, height: 915 },
76
+ userAgent: "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36",
77
+ deviceScaleFactor: 2.625,
78
+ isMobile: true,
79
+ hasTouch: true
80
+ },
81
+ "iPad Pro 12.9": {
82
+ name: "iPad Pro 12.9",
83
+ viewport: { width: 1024, height: 1366 },
84
+ userAgent: "Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",
85
+ deviceScaleFactor: 2,
86
+ isMobile: true,
87
+ hasTouch: true
88
+ }
89
+ };
90
+ function listBrowserDevices() {
91
+ return Object.values(BrowserDevices);
92
+ }
93
+ function getBrowserDevice(name) {
94
+ return BrowserDevices[name] || null;
95
+ }
96
+ function generatePlaywrightScript(script) {
97
+ const { name, baseURL, viewport, actions } = script;
98
+ const lines = [
99
+ "import { test, expect } from '@playwright/test';",
100
+ ""
101
+ ];
102
+ lines.push(`test('${name || "Generated Test"}', async ({ page }) => {`);
103
+ if (viewport) {
104
+ lines.push(` await page.setViewportSize({ width: ${viewport.width}, height: ${viewport.height} });`);
105
+ }
106
+ if (baseURL) {
107
+ lines.push(` await page.goto('${baseURL}');`);
108
+ }
109
+ for (const action of actions) {
110
+ const code = generateActionCode(action);
111
+ if (code) {
112
+ lines.push(` ${code}`);
113
+ }
114
+ }
115
+ lines.push("});");
116
+ lines.push("");
117
+ return lines.join("\n");
118
+ }
119
+ function generateActionCode(action) {
120
+ const { type, selector, value, url, key, options } = action;
121
+ switch (type) {
122
+ case "goto":
123
+ return `await page.goto('${url || ""}');`;
124
+ case "click":
125
+ if (!selector) return null;
126
+ return `await page.click('${selector}');`;
127
+ case "fill":
128
+ if (!selector) return null;
129
+ return `await page.fill('${selector}', '${value || ""}');`;
130
+ case "type":
131
+ if (!selector) return null;
132
+ return `await page.type('${selector}', '${value || ""}');`;
133
+ case "press":
134
+ if (!selector) return null;
135
+ return `await page.press('${selector}', '${key || "Enter"}');`;
136
+ case "check":
137
+ if (!selector) return null;
138
+ return `await page.check('${selector}');`;
139
+ case "uncheck":
140
+ if (!selector) return null;
141
+ return `await page.uncheck('${selector}');`;
142
+ case "selectOption":
143
+ if (!selector) return null;
144
+ return `await page.selectOption('${selector}', '${value || ""}');`;
145
+ case "hover":
146
+ if (!selector) return null;
147
+ return `await page.hover('${selector}');`;
148
+ case "focus":
149
+ if (!selector) return null;
150
+ return `await page.focus('${selector}');`;
151
+ case "screenshot":
152
+ return `await page.screenshot({ path: '${value || "screenshot.png"}' });`;
153
+ case "wait":
154
+ return `await page.waitForTimeout(${value || 1e3});`;
155
+ case "waitForSelector":
156
+ if (!selector) return null;
157
+ return `await page.waitForSelector('${selector}');`;
158
+ case "waitForURL":
159
+ return `await page.waitForURL('${url || ""}');`;
160
+ case "expectVisible":
161
+ if (!selector) return null;
162
+ return `await expect(page.locator('${selector}')).toBeVisible();`;
163
+ case "expectHidden":
164
+ if (!selector) return null;
165
+ return `await expect(page.locator('${selector}')).toBeHidden();`;
166
+ case "expectText":
167
+ if (!selector) return null;
168
+ return `await expect(page.locator('${selector}')).toHaveText('${value || ""}');`;
169
+ case "expectURL":
170
+ return `await expect(page).toHaveURL('${url || ""}');`;
171
+ case "expectTitle":
172
+ return `await expect(page).toHaveTitle('${value || ""}');`;
173
+ case "scroll":
174
+ if (selector) {
175
+ return `await page.locator('${selector}').scrollIntoViewIfNeeded();`;
176
+ }
177
+ return `await page.evaluate(() => window.scrollBy(0, ${value || 500}));`;
178
+ case "evaluate":
179
+ return `await page.evaluate(() => { ${value || ""} });`;
180
+ default:
181
+ return null;
182
+ }
183
+ }
184
+ var PlaywrightActions = {
185
+ // Navigation
186
+ goto: (url) => ({ type: "goto", url }),
187
+ goBack: () => ({ type: "evaluate", value: "history.back()" }),
188
+ goForward: () => ({ type: "evaluate", value: "history.forward()" }),
189
+ reload: () => ({ type: "evaluate", value: "location.reload()" }),
190
+ // Interactions
191
+ click: (selector) => ({ type: "click", selector }),
192
+ fill: (selector, value) => ({ type: "fill", selector, value }),
193
+ type: (selector, value) => ({ type: "type", selector, value }),
194
+ press: (selector, key) => ({ type: "press", selector, key }),
195
+ check: (selector) => ({ type: "check", selector }),
196
+ uncheck: (selector) => ({ type: "uncheck", selector }),
197
+ selectOption: (selector, value) => ({ type: "selectOption", selector, value }),
198
+ hover: (selector) => ({ type: "hover", selector }),
199
+ focus: (selector) => ({ type: "focus", selector }),
200
+ // Waiting
201
+ wait: (ms) => ({ type: "wait", value: String(ms) }),
202
+ waitForSelector: (selector) => ({ type: "waitForSelector", selector }),
203
+ waitForURL: (url) => ({ type: "waitForURL", url }),
204
+ // Screenshots
205
+ screenshot: (path2) => ({ type: "screenshot", value: path2 }),
206
+ // Scrolling
207
+ scroll: (pixels) => ({ type: "scroll", value: String(pixels || 500) }),
208
+ scrollToElement: (selector) => ({ type: "scroll", selector }),
209
+ // Assertions
210
+ expectVisible: (selector) => ({ type: "expectVisible", selector }),
211
+ expectHidden: (selector) => ({ type: "expectHidden", selector }),
212
+ expectText: (selector, text) => ({ type: "expectText", selector, value: text }),
213
+ expectURL: (url) => ({ type: "expectURL", url }),
214
+ expectTitle: (title) => ({ type: "expectTitle", value: title }),
215
+ // Custom
216
+ evaluate: (code) => ({ type: "evaluate", value: code })
217
+ };
218
+ async function runPlaywrightTest(options) {
219
+ const installed = await isPlaywrightInstalled();
220
+ if (!installed) {
221
+ return {
222
+ success: false,
223
+ error: "Playwright is not installed. Install with: npm install -D @playwright/test && npx playwright install"
224
+ };
225
+ }
226
+ const {
227
+ testPath,
228
+ testPattern,
229
+ config = {},
230
+ outputDir = path.join(PROJECTS_DIR, "playwright-output", Date.now().toString()),
231
+ project,
232
+ workers = 1,
233
+ retries = 0,
234
+ reporter = "json"
235
+ } = options;
236
+ await fs.promises.mkdir(outputDir, { recursive: true });
237
+ const startTime = Date.now();
238
+ const args = ["playwright", "test"];
239
+ if (testPath) {
240
+ args.push(testPath);
241
+ }
242
+ if (testPattern) {
243
+ args.push("-g", testPattern);
244
+ }
245
+ if (project) {
246
+ args.push("--project", project);
247
+ }
248
+ args.push("--workers", workers.toString());
249
+ if (retries > 0) {
250
+ args.push("--retries", retries.toString());
251
+ }
252
+ args.push("--reporter", reporter);
253
+ args.push("--output", outputDir);
254
+ if (config.browser) {
255
+ args.push("--browser", config.browser);
256
+ }
257
+ if (config.headless === false) {
258
+ args.push("--headed");
259
+ }
260
+ try {
261
+ const { stdout, stderr } = await execAsync(`npx ${args.join(" ")}`, {
262
+ timeout: config.timeout || 3e5,
263
+ cwd: process.cwd()
264
+ });
265
+ const duration = Date.now() - startTime;
266
+ let passed = 0;
267
+ let failed = 0;
268
+ let skipped = 0;
269
+ const passedMatch = stdout.match(/(\d+) passed/);
270
+ const failedMatch = stdout.match(/(\d+) failed/);
271
+ const skippedMatch = stdout.match(/(\d+) skipped/);
272
+ if (passedMatch) passed = parseInt(passedMatch[1], 10);
273
+ if (failedMatch) failed = parseInt(failedMatch[1], 10);
274
+ if (skippedMatch) skipped = parseInt(skippedMatch[1], 10);
275
+ const videos = [];
276
+ const screenshots = [];
277
+ const traces = [];
278
+ if (fs.existsSync(outputDir)) {
279
+ const collectArtifacts = async (dir) => {
280
+ const files = await fs.promises.readdir(dir, { withFileTypes: true });
281
+ for (const file of files) {
282
+ const filePath = path.join(dir, file.name);
283
+ if (file.isDirectory()) {
284
+ await collectArtifacts(filePath);
285
+ } else if (file.name.endsWith(".webm") || file.name.endsWith(".mp4")) {
286
+ videos.push(filePath);
287
+ } else if (file.name.endsWith(".png")) {
288
+ screenshots.push(filePath);
289
+ } else if (file.name.endsWith(".zip") && file.name.includes("trace")) {
290
+ traces.push(filePath);
291
+ }
292
+ }
293
+ };
294
+ await collectArtifacts(outputDir);
295
+ }
296
+ return {
297
+ success: failed === 0,
298
+ duration,
299
+ passed,
300
+ failed,
301
+ skipped,
302
+ output: stdout + stderr,
303
+ reportPath: path.join(outputDir, "report.json"),
304
+ videos,
305
+ screenshots,
306
+ traces
307
+ };
308
+ } catch (error) {
309
+ const duration = Date.now() - startTime;
310
+ const message = error instanceof Error ? error.message : String(error);
311
+ let passed = 0;
312
+ let failed = 0;
313
+ let skipped = 0;
314
+ const passedMatch = message.match(/(\d+) passed/);
315
+ const failedMatch = message.match(/(\d+) failed/);
316
+ const skippedMatch = message.match(/(\d+) skipped/);
317
+ if (passedMatch) passed = parseInt(passedMatch[1], 10);
318
+ if (failedMatch) failed = parseInt(failedMatch[1], 10);
319
+ if (skippedMatch) skipped = parseInt(skippedMatch[1], 10);
320
+ return {
321
+ success: false,
322
+ error: message,
323
+ duration,
324
+ passed,
325
+ failed,
326
+ skipped,
327
+ output: message
328
+ };
329
+ }
330
+ }
331
+ async function runPlaywrightScript(script, options = {}) {
332
+ const outputDir = options.outputDir || path.join(PROJECTS_DIR, "playwright-output", Date.now().toString());
333
+ await fs.promises.mkdir(outputDir, { recursive: true });
334
+ const scriptContent = generatePlaywrightScript(script);
335
+ const scriptPath = path.join(outputDir, "test.spec.ts");
336
+ await fs.promises.writeFile(scriptPath, scriptContent);
337
+ const configContent = `
338
+ import { defineConfig } from '@playwright/test';
339
+
340
+ export default defineConfig({
341
+ testDir: '.',
342
+ timeout: ${options.config?.timeout || 3e4},
343
+ use: {
344
+ headless: ${options.config?.headless !== false},
345
+ video: '${options.config?.video || "off"}',
346
+ screenshot: '${options.config?.screenshot || "off"}',
347
+ trace: '${options.config?.trace || "off"}',
348
+ ${script.baseURL ? `baseURL: '${script.baseURL}',` : ""}
349
+ ${script.viewport ? `viewport: { width: ${script.viewport.width}, height: ${script.viewport.height} },` : ""}
350
+ },
351
+ reporter: [['json', { outputFile: 'report.json' }]],
352
+ outputDir: './results',
353
+ });
354
+ `;
355
+ const configPath = path.join(outputDir, "playwright.config.ts");
356
+ await fs.promises.writeFile(configPath, configContent);
357
+ return runPlaywrightTest({
358
+ ...options,
359
+ testPath: scriptPath,
360
+ outputDir
361
+ });
362
+ }
363
+ async function savePlaywrightScript(script, outputPath) {
364
+ const content = generatePlaywrightScript(script);
365
+ const filePath = outputPath || path.join(
366
+ PROJECTS_DIR,
367
+ "scripts",
368
+ `${script.name?.replace(/\s+/g, "_") || "test"}_${Date.now()}.spec.ts`
369
+ );
370
+ await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
371
+ await fs.promises.writeFile(filePath, content);
372
+ return filePath;
373
+ }
374
+ async function startPlaywrightCodegen(url, options = {}) {
375
+ const installed = await isPlaywrightInstalled();
376
+ if (!installed) {
377
+ return {
378
+ success: false,
379
+ error: "Playwright is not installed"
380
+ };
381
+ }
382
+ try {
383
+ const args = ["playwright", "codegen"];
384
+ if (options.browser) {
385
+ args.push("--browser", options.browser);
386
+ }
387
+ if (options.device) {
388
+ args.push("--device", `"${options.device}"`);
389
+ }
390
+ if (options.outputPath) {
391
+ args.push("-o", options.outputPath);
392
+ }
393
+ if (url) {
394
+ args.push(url);
395
+ }
396
+ spawn("npx", args, {
397
+ detached: true,
398
+ stdio: "ignore",
399
+ shell: true
400
+ }).unref();
401
+ return { success: true };
402
+ } catch (error) {
403
+ return {
404
+ success: false,
405
+ error: error instanceof Error ? error.message : String(error)
406
+ };
407
+ }
408
+ }
409
+ async function showPlaywrightReport(reportDir) {
410
+ const installed = await isPlaywrightInstalled();
411
+ if (!installed) {
412
+ return {
413
+ success: false,
414
+ error: "Playwright is not installed"
415
+ };
416
+ }
417
+ try {
418
+ const args = ["playwright", "show-report"];
419
+ if (reportDir) {
420
+ args.push(reportDir);
421
+ }
422
+ spawn("npx", args, {
423
+ detached: true,
424
+ stdio: "ignore",
425
+ shell: true
426
+ }).unref();
427
+ return { success: true };
428
+ } catch (error) {
429
+ return {
430
+ success: false,
431
+ error: error instanceof Error ? error.message : String(error)
432
+ };
433
+ }
434
+ }
435
+ function createLoginScript(baseURL, usernameSelector, passwordSelector, submitSelector, successURL) {
436
+ return {
437
+ name: "Login Test",
438
+ baseURL,
439
+ actions: [
440
+ PlaywrightActions.goto(baseURL),
441
+ PlaywrightActions.fill(usernameSelector, "${USERNAME}"),
442
+ PlaywrightActions.fill(passwordSelector, "${PASSWORD}"),
443
+ PlaywrightActions.click(submitSelector),
444
+ PlaywrightActions.waitForURL(successURL),
445
+ PlaywrightActions.expectURL(successURL),
446
+ PlaywrightActions.screenshot("login-success.png")
447
+ ]
448
+ };
449
+ }
450
+ function createNavigationScript(baseURL, links) {
451
+ const actions = [PlaywrightActions.goto(baseURL)];
452
+ for (const link of links) {
453
+ actions.push(PlaywrightActions.click(link.selector));
454
+ actions.push(PlaywrightActions.waitForURL(link.expectedURL));
455
+ actions.push(PlaywrightActions.screenshot(`${link.name}.png`));
456
+ actions.push(PlaywrightActions.goBack());
457
+ }
458
+ return {
459
+ name: "Navigation Test",
460
+ baseURL,
461
+ actions
462
+ };
463
+ }
464
+ function createFormSubmissionScript(baseURL, formFields, submitSelector, successIndicator) {
465
+ const actions = [PlaywrightActions.goto(baseURL)];
466
+ for (const field of formFields) {
467
+ actions.push(PlaywrightActions.fill(field.selector, field.value));
468
+ }
469
+ actions.push(PlaywrightActions.click(submitSelector));
470
+ actions.push(PlaywrightActions.waitForSelector(successIndicator));
471
+ actions.push(PlaywrightActions.expectVisible(successIndicator));
472
+ actions.push(PlaywrightActions.screenshot("form-success.png"));
473
+ return {
474
+ name: "Form Submission Test",
475
+ baseURL,
476
+ actions
477
+ };
478
+ }
479
+
480
+ export {
481
+ isPlaywrightInstalled,
482
+ getPlaywrightVersion,
483
+ installPlaywrightBrowsers,
484
+ BrowserDevices,
485
+ listBrowserDevices,
486
+ getBrowserDevice,
487
+ generatePlaywrightScript,
488
+ PlaywrightActions,
489
+ runPlaywrightTest,
490
+ runPlaywrightScript,
491
+ savePlaywrightScript,
492
+ startPlaywrightCodegen,
493
+ showPlaywrightReport,
494
+ createLoginScript,
495
+ createNavigationScript,
496
+ createFormSubmissionScript
497
+ };