lazyscout 0.3.7 → 0.3.9
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.
package/dist/index.js
CHANGED
|
@@ -303,6 +303,10 @@ function describeStep(step) {
|
|
|
303
303
|
return `Enter "${step.value}" in ${describeTarget(step.target)}`;
|
|
304
304
|
case "select":
|
|
305
305
|
return `Select "${step.option}" from ${describeTarget(step.target)}`;
|
|
306
|
+
case "check":
|
|
307
|
+
return `${step.checked ? "Check" : "Uncheck"} ${describeTarget(step.target)}`;
|
|
308
|
+
case "wait":
|
|
309
|
+
return `Wait for ${step.mode}: ${step.value}`;
|
|
306
310
|
case "assertVisible":
|
|
307
311
|
return `Verify that ${describeTarget(step.target)} is visible`;
|
|
308
312
|
case "assertText":
|
|
@@ -438,6 +442,13 @@ function collectPageData() {
|
|
|
438
442
|
}
|
|
439
443
|
const disabled = el.disabled === true || el.getAttribute("aria-disabled") === "true";
|
|
440
444
|
const required = el.required === true || el.getAttribute("aria-required") === "true";
|
|
445
|
+
const context = el.closest('form, fieldset, tr, [role="row"], li, section, article, aside, main, nav, dialog, [role="dialog"], [role="region"], .card, [class*="card" i]');
|
|
446
|
+
const contextAriaLabel = context?.getAttribute("aria-label");
|
|
447
|
+
const contextHeading = context?.querySelector("h1, h2, h3");
|
|
448
|
+
const rowLabel = context?.matches('tr, [role="row"]') ? context.querySelector('th, td, [role="cell"], [role="gridcell"]') : void 0;
|
|
449
|
+
const namedContainer = context?.querySelector("[data-title], [data-name], [data-label]");
|
|
450
|
+
const contextText = cleanText(contextAriaLabel || contextHeading?.textContent || namedContainer?.getAttribute("data-title") || namedContainer?.getAttribute("data-name") || namedContainer?.getAttribute("data-label") || rowLabel?.textContent);
|
|
451
|
+
const contextTestId = context?.getAttribute("data-testid")?.trim() || void 0;
|
|
441
452
|
return {
|
|
442
453
|
kind,
|
|
443
454
|
role,
|
|
@@ -447,14 +458,52 @@ function collectPageData() {
|
|
|
447
458
|
inputType,
|
|
448
459
|
placeholder: attr(el, "placeholder"),
|
|
449
460
|
name: attr(el, "name"),
|
|
461
|
+
testId: attr(el, "data-testid"),
|
|
450
462
|
id: el.id || void 0,
|
|
451
463
|
href: el instanceof HTMLAnchorElement ? el.href : void 0,
|
|
452
464
|
options,
|
|
453
465
|
required,
|
|
454
466
|
disabled,
|
|
455
|
-
cssSelector: cssSelector(el)
|
|
467
|
+
cssSelector: cssSelector(el),
|
|
468
|
+
contextText: contextText || void 0,
|
|
469
|
+
contextSelector: context ? cssSelector(context) : void 0,
|
|
470
|
+
contextTestId
|
|
456
471
|
};
|
|
457
472
|
}
|
|
473
|
+
function annotateMatches(elements) {
|
|
474
|
+
const groups = /* @__PURE__ */ new Map();
|
|
475
|
+
for (const element of elements) {
|
|
476
|
+
if (!element.accessibleName)
|
|
477
|
+
continue;
|
|
478
|
+
const key = `${element.role}|${element.accessibleName}`;
|
|
479
|
+
const group = groups.get(key) ?? [];
|
|
480
|
+
group.push(element);
|
|
481
|
+
groups.set(key, group);
|
|
482
|
+
}
|
|
483
|
+
for (const group of groups.values()) {
|
|
484
|
+
if (group.length < 2)
|
|
485
|
+
continue;
|
|
486
|
+
group.forEach((element, index) => {
|
|
487
|
+
element.matchIndex = index;
|
|
488
|
+
element.matchCount = group.length;
|
|
489
|
+
});
|
|
490
|
+
const scopedGroups = /* @__PURE__ */ new Map();
|
|
491
|
+
for (const element of group) {
|
|
492
|
+
if (!element.contextSelector)
|
|
493
|
+
continue;
|
|
494
|
+
const scopedKey = element.contextSelector;
|
|
495
|
+
const scoped = scopedGroups.get(scopedKey) ?? [];
|
|
496
|
+
scoped.push(element);
|
|
497
|
+
scopedGroups.set(scopedKey, scoped);
|
|
498
|
+
}
|
|
499
|
+
for (const scoped of scopedGroups.values()) {
|
|
500
|
+
scoped.forEach((element, index) => {
|
|
501
|
+
element.scopeIndex = index;
|
|
502
|
+
element.scopeMatchCount = scoped.length;
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
}
|
|
458
507
|
function isCollectable(el) {
|
|
459
508
|
if (el.closest('[aria-hidden="true"]'))
|
|
460
509
|
return false;
|
|
@@ -491,7 +540,7 @@ function collectPageData() {
|
|
|
491
540
|
submitButtons
|
|
492
541
|
};
|
|
493
542
|
});
|
|
494
|
-
|
|
543
|
+
const result = {
|
|
495
544
|
title: document.title,
|
|
496
545
|
headings: Array.from(document.querySelectorAll("h1, h2, h3")).map((el) => cleanText(el.textContent)).filter(Boolean).slice(0, 30),
|
|
497
546
|
links: collect("a[href]", "link", "link"),
|
|
@@ -523,6 +572,9 @@ function collectPageData() {
|
|
|
523
572
|
stateContent: Array.from(document.querySelectorAll('[aria-live], [data-state], [data-testid*="state" i]')).filter(isCollectable).map((element) => cleanText(element.textContent)).filter(Boolean).slice(0, 30),
|
|
524
573
|
validationMessages: Array.from(document.querySelectorAll('[role="alert"], [aria-invalid="true"], .error, .errors, .invalid-feedback')).filter(isCollectable).map((element) => cleanText(element.textContent)).filter(Boolean).slice(0, 20)
|
|
525
574
|
};
|
|
575
|
+
annotateMatches([...result.links, ...result.buttons, ...result.inputs, ...result.textareas, ...result.selects]);
|
|
576
|
+
annotateMatches(result.forms.flatMap((form) => [...form.fields, ...form.submitButtons]));
|
|
577
|
+
return result;
|
|
526
578
|
}
|
|
527
579
|
|
|
528
580
|
// ../../packages/explorer/dist/mapToPageModel.js
|
|
@@ -1092,19 +1144,19 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
|
|
|
1092
1144
|
async function executeWithRetry(page, candidate, currentUrl, entryFlow, maxRetries) {
|
|
1093
1145
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
1094
1146
|
try {
|
|
1095
|
-
let
|
|
1147
|
+
let locator3;
|
|
1096
1148
|
if (candidate.locator.cssSelector) {
|
|
1097
|
-
|
|
1149
|
+
locator3 = page.locator(candidate.locator.cssSelector).first();
|
|
1098
1150
|
} else if (candidate.locator.role && candidate.locator.name) {
|
|
1099
|
-
|
|
1151
|
+
locator3 = page.getByRole(candidate.locator.role, {
|
|
1100
1152
|
name: candidate.locator.name
|
|
1101
1153
|
});
|
|
1102
1154
|
} else if (candidate.locator.testId) {
|
|
1103
|
-
|
|
1155
|
+
locator3 = page.getByTestId(candidate.locator.testId);
|
|
1104
1156
|
} else {
|
|
1105
1157
|
return { success: false };
|
|
1106
1158
|
}
|
|
1107
|
-
await
|
|
1159
|
+
await locator3.click({ timeout: legacyOptions.actionTimeoutMs });
|
|
1108
1160
|
await page.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
|
|
1109
1161
|
const newUrl = page.url();
|
|
1110
1162
|
return { success: true, newUrl };
|
|
@@ -1817,13 +1869,23 @@ function assignModules(pages) {
|
|
|
1817
1869
|
|
|
1818
1870
|
// ../../packages/generators/dist/testcases/targets.js
|
|
1819
1871
|
function toTargetRef(element) {
|
|
1872
|
+
const needsDisambiguation = element.matchCount !== void 0 && element.matchCount > 1;
|
|
1873
|
+
const disambiguation = needsDisambiguation ? {
|
|
1874
|
+
nth: element.scopeMatchCount && element.scopeMatchCount > 1 ? element.scopeIndex : element.contextSelector || element.contextText ? void 0 : element.matchIndex,
|
|
1875
|
+
matchCount: element.matchCount,
|
|
1876
|
+
contextText: element.contextText,
|
|
1877
|
+
contextSelector: element.contextSelector,
|
|
1878
|
+
contextTestId: element.contextTestId
|
|
1879
|
+
} : void 0;
|
|
1820
1880
|
if (element.accessibleName) {
|
|
1821
|
-
return { role: element.role, name: element.accessibleName };
|
|
1881
|
+
return { role: element.role, name: element.accessibleName, cssSelector: element.cssSelector, ...disambiguation };
|
|
1822
1882
|
}
|
|
1823
1883
|
if (element.placeholder) {
|
|
1824
|
-
return { role: element.role, placeholder: element.placeholder };
|
|
1884
|
+
return { role: element.role, placeholder: element.placeholder, cssSelector: element.cssSelector, ...disambiguation };
|
|
1825
1885
|
}
|
|
1826
|
-
|
|
1886
|
+
if (element.testId)
|
|
1887
|
+
return { testId: element.testId, ...disambiguation };
|
|
1888
|
+
return { role: element.role, cssSelector: element.cssSelector, ...disambiguation };
|
|
1827
1889
|
}
|
|
1828
1890
|
function labelOf(element) {
|
|
1829
1891
|
return element.accessibleName || element.placeholder || element.name || element.id || element.tagName;
|
|
@@ -2156,6 +2218,10 @@ function translateStep(step) {
|
|
|
2156
2218
|
return `\u0E01\u0E23\u0E2D\u0E01\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E43\u0E19 ${step.target.name ?? step.target.label ?? step.target.placeholder ?? "\u0E0A\u0E48\u0E2D\u0E07\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25"}`;
|
|
2157
2219
|
case "select":
|
|
2158
2220
|
return `\u0E40\u0E25\u0E37\u0E2D\u0E01 ${step.option} \u0E08\u0E32\u0E01 ${step.target.name ?? step.target.label ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
|
|
2221
|
+
case "check":
|
|
2222
|
+
return `${step.checked ? "Check" : "Uncheck"} ${step.target.name ?? step.target.label ?? "element"}`;
|
|
2223
|
+
case "wait":
|
|
2224
|
+
return `Wait for ${step.mode}: ${step.value}`;
|
|
2159
2225
|
case "assertVisible":
|
|
2160
2226
|
return `\u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E27\u0E48\u0E32 ${step.target.name ?? step.target.label ?? "element"} \u0E41\u0E2A\u0E14\u0E07\u0E2D\u0E22\u0E39\u0E48`;
|
|
2161
2227
|
case "assertText":
|
|
@@ -2326,6 +2392,167 @@ function exportTestCasesToCsv(testCases, testData = []) {
|
|
|
2326
2392
|
return UTF8_BOM + lines.join("\r\n") + "\r\n";
|
|
2327
2393
|
}
|
|
2328
2394
|
|
|
2395
|
+
// ../../packages/generators/dist/playwright/generatePlaywrightTest.js
|
|
2396
|
+
function generatePlaywrightTest(testCase) {
|
|
2397
|
+
const lines = [
|
|
2398
|
+
`import { test, expect } from '@playwright/test'`,
|
|
2399
|
+
"",
|
|
2400
|
+
`test('${quote(testCase.title)}', async ({ page }) => {`
|
|
2401
|
+
];
|
|
2402
|
+
for (const step of testCase.steps)
|
|
2403
|
+
lines.push(` ${playwrightStep(step)}`);
|
|
2404
|
+
lines.push("})", "");
|
|
2405
|
+
return lines.join("\n");
|
|
2406
|
+
}
|
|
2407
|
+
function locator(target) {
|
|
2408
|
+
const base = target.role && target.name ? `page.getByRole(${quote(target.role)}, { name: ${quote(target.name)} })` : target.label ? `page.getByLabel(${quote(target.label)}, { exact: true })` : target.testId ? `page.getByTestId(${quote(target.testId)})` : target.placeholder ? `page.getByPlaceholder(${quote(target.placeholder)})` : target.text ? `page.getByText(${quote(target.text)})` : `page.locator(${quote(target.cssSelector ?? "")})`;
|
|
2409
|
+
const context = target.contextTestId ? `page.getByTestId(${quote(target.contextTestId)})` : target.contextSelector ? `page.locator(${quote(target.contextSelector)})` : void 0;
|
|
2410
|
+
const scoped = context ? target.contextText ? `${context}.filter({ hasText: ${quote(target.contextText)} }).${base.slice(5)}` : `${context}.${base.slice(5)}` : base;
|
|
2411
|
+
return target.nth === void 0 ? scoped : `${scoped}.nth(${target.nth})`;
|
|
2412
|
+
}
|
|
2413
|
+
function playwrightStep(step) {
|
|
2414
|
+
switch (step.type) {
|
|
2415
|
+
case "navigate":
|
|
2416
|
+
return `await page.goto(${quote(step.url)})`;
|
|
2417
|
+
case "click":
|
|
2418
|
+
return `await ${locator(step.target)}.click()`;
|
|
2419
|
+
case "fill":
|
|
2420
|
+
return `await ${locator(step.target)}.fill(${quote(runtimeValue(step))})`;
|
|
2421
|
+
case "select":
|
|
2422
|
+
return `await ${locator(step.target)}.selectOption(${quote(step.option)})`;
|
|
2423
|
+
case "check":
|
|
2424
|
+
return `await ${locator(step.target)}.${step.checked ? "check" : "uncheck"}()`;
|
|
2425
|
+
case "wait":
|
|
2426
|
+
if (step.mode === "timeout")
|
|
2427
|
+
return `await page.waitForTimeout(${Math.min(5e3, Math.max(0, Number(step.value) || 0))})`;
|
|
2428
|
+
if (step.mode === "url")
|
|
2429
|
+
return `await expect(page).toHaveURL(new RegExp(${quote(step.value)}))`;
|
|
2430
|
+
if (step.mode === "text")
|
|
2431
|
+
return `await expect(page).toContainText(${quote(step.value)})`;
|
|
2432
|
+
return `await expect(${locator(step.target)}).toBeVisible()`;
|
|
2433
|
+
case "assertVisible":
|
|
2434
|
+
return `await expect(${locator(step.target)}).toBeVisible()`;
|
|
2435
|
+
case "assertText":
|
|
2436
|
+
return step.target ? `await expect(${locator(step.target)}).toContainText(${quote(step.text)})` : `await expect(page).toContainText(${quote(step.text)})`;
|
|
2437
|
+
case "assertUrl":
|
|
2438
|
+
return `await expect(page).toHaveURL(new RegExp(${quote(step.urlContains)}))`;
|
|
2439
|
+
case "manual":
|
|
2440
|
+
return `// TODO: ${step.description}`;
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
function runtimeValue(step) {
|
|
2444
|
+
const hint = `${step.target.name ?? ""} ${step.target.label ?? ""} ${step.target.placeholder ?? ""}`.toLowerCase();
|
|
2445
|
+
if (hint.includes("password") || hint.includes("\u0E23\u0E2B\u0E31\u0E2A\u0E1C\u0E48\u0E32\u0E19"))
|
|
2446
|
+
return "{{TEST_PASSWORD}}";
|
|
2447
|
+
if (hint.includes("email") || hint.includes("\u0E2D\u0E35\u0E40\u0E21\u0E25"))
|
|
2448
|
+
return "{{TEST_EMAIL}}";
|
|
2449
|
+
if (hint.includes("username") || hint.includes("user name") || hint.includes("\u0E0A\u0E37\u0E48\u0E2D\u0E1C\u0E39\u0E49\u0E43\u0E0A\u0E49"))
|
|
2450
|
+
return "{{TEST_USERNAME}}";
|
|
2451
|
+
return step.value;
|
|
2452
|
+
}
|
|
2453
|
+
var quote = (value) => JSON.stringify(value);
|
|
2454
|
+
|
|
2455
|
+
// ../../packages/generators/dist/guidedflow/flowToTestCase.js
|
|
2456
|
+
function flowToTestCase(flow) {
|
|
2457
|
+
const steps = flow.steps.map((step) => flowStepToTestStep(flow, step));
|
|
2458
|
+
const assertion = flow.steps.find((step) => step.type === "assert");
|
|
2459
|
+
const expectedResult = assertion?.type === "assert" && assertion.assertion.type === "text" ? `The page shows "${assertion.assertion.value}".` : assertion?.type === "assert" && assertion.assertion.type === "url" ? `The URL contains "${assertion.assertion.value}".` : assertion?.type === "assert" ? "The expected element is visible." : "Needs Review";
|
|
2460
|
+
return {
|
|
2461
|
+
id: `TC-FLOW-${flow.id.slice(-8).toUpperCase()}`,
|
|
2462
|
+
module: "FLOW",
|
|
2463
|
+
title: flow.name,
|
|
2464
|
+
preconditions: flow.description ? [flow.description] : [],
|
|
2465
|
+
steps,
|
|
2466
|
+
expectedResult,
|
|
2467
|
+
type: "positive",
|
|
2468
|
+
priority: "medium",
|
|
2469
|
+
automationStatus: steps.length ? "ready" : "needs-review",
|
|
2470
|
+
status: "pending",
|
|
2471
|
+
sourceUrl: flow.baseUrl,
|
|
2472
|
+
notes: assertion ? void 0 : "Guided Flow has no assertion \u2014 expected result needs review."
|
|
2473
|
+
};
|
|
2474
|
+
}
|
|
2475
|
+
function flowStepToTestStep(flow, step) {
|
|
2476
|
+
switch (step.type) {
|
|
2477
|
+
case "navigate":
|
|
2478
|
+
return { type: "navigate", url: new URL(step.path, flow.baseUrl).toString() };
|
|
2479
|
+
case "click":
|
|
2480
|
+
return { type: "click", target: step.target };
|
|
2481
|
+
case "fill":
|
|
2482
|
+
return {
|
|
2483
|
+
type: "fill",
|
|
2484
|
+
target: step.target,
|
|
2485
|
+
value: step.valueRef ? `{{${step.valueRef}}}` : step.value ?? ""
|
|
2486
|
+
};
|
|
2487
|
+
case "select":
|
|
2488
|
+
return { type: "select", target: step.target, option: step.option };
|
|
2489
|
+
case "check":
|
|
2490
|
+
return { type: "check", target: step.target, checked: step.checked };
|
|
2491
|
+
case "wait":
|
|
2492
|
+
return { type: "wait", mode: step.mode, value: step.value, target: step.target };
|
|
2493
|
+
case "assert":
|
|
2494
|
+
if (step.assertion.type === "visible")
|
|
2495
|
+
return { type: "assertVisible", target: step.assertion.target };
|
|
2496
|
+
if (step.assertion.type === "text")
|
|
2497
|
+
return { type: "assertText", text: step.assertion.value };
|
|
2498
|
+
return { type: "assertUrl", urlContains: step.assertion.value };
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2502
|
+
// ../../packages/generators/dist/guidedflow/generatePlaywrightFromFlow.js
|
|
2503
|
+
function generatePlaywrightFromFlow(flow) {
|
|
2504
|
+
const lines = [
|
|
2505
|
+
`import { test, expect } from '@playwright/test'`,
|
|
2506
|
+
"",
|
|
2507
|
+
`test(${JSON.stringify(flow.name)}, async ({ page }) => {`
|
|
2508
|
+
];
|
|
2509
|
+
for (const step of flow.steps)
|
|
2510
|
+
lines.push(` ${playwrightFlowStep(flow, step)}`);
|
|
2511
|
+
lines.push("})", "");
|
|
2512
|
+
return lines.join("\n");
|
|
2513
|
+
}
|
|
2514
|
+
function playwrightFlowStep(flow, step) {
|
|
2515
|
+
switch (step.type) {
|
|
2516
|
+
case "navigate":
|
|
2517
|
+
return `await page.goto(${JSON.stringify(new URL(step.path, flow.baseUrl).toString())})`;
|
|
2518
|
+
case "click":
|
|
2519
|
+
return `await ${locator2(step.target)}.click()`;
|
|
2520
|
+
case "fill":
|
|
2521
|
+
return `await ${locator2(step.target)}.fill(${JSON.stringify(step.valueRef ? `{{${step.valueRef}}}` : step.value ?? "")})`;
|
|
2522
|
+
case "select":
|
|
2523
|
+
return `await ${locator2(step.target)}.selectOption(${JSON.stringify(step.option)})`;
|
|
2524
|
+
case "check":
|
|
2525
|
+
return `await ${locator2(step.target)}.${step.checked ? "check" : "uncheck"}()`;
|
|
2526
|
+
case "wait":
|
|
2527
|
+
if (step.mode === "timeout")
|
|
2528
|
+
return `await page.waitForTimeout(${Math.min(5e3, Math.max(0, Number(step.value) || 0))})`;
|
|
2529
|
+
if (step.mode === "url")
|
|
2530
|
+
return `await expect(page).toHaveURL(new RegExp(${JSON.stringify(step.value)}))`;
|
|
2531
|
+
if (step.mode === "text")
|
|
2532
|
+
return `await expect(page).toContainText(${JSON.stringify(step.value)})`;
|
|
2533
|
+
return `await expect(${locator2(step.target)}).toBeVisible()`;
|
|
2534
|
+
case "assert":
|
|
2535
|
+
if (step.assertion.type === "visible")
|
|
2536
|
+
return `await expect(${locator2(step.assertion.target)}).toBeVisible()`;
|
|
2537
|
+
if (step.assertion.type === "text")
|
|
2538
|
+
return `await expect(page.getByText(${JSON.stringify(step.assertion.value)})).toBeVisible()`;
|
|
2539
|
+
return `await expect(page).toHaveURL(new RegExp(${JSON.stringify(step.assertion.value)}))`;
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
function locator2(target) {
|
|
2543
|
+
if (target.strategy === "role" || target.role && target.name)
|
|
2544
|
+
return `page.getByRole(${JSON.stringify(target.role ?? "generic")}, { name: ${JSON.stringify(target.name ?? target.value ?? "")}${target.exact ? ", exact: true" : ""} })`;
|
|
2545
|
+
if (target.strategy === "label" || target.label)
|
|
2546
|
+
return `page.getByLabel(${JSON.stringify(target.label ?? target.value ?? "")}, { exact: true })`;
|
|
2547
|
+
if (target.strategy === "placeholder" || target.placeholder)
|
|
2548
|
+
return `page.getByPlaceholder(${JSON.stringify(target.placeholder ?? target.value ?? "")})`;
|
|
2549
|
+
if (target.strategy === "testid" || target.testId)
|
|
2550
|
+
return `page.getByTestId(${JSON.stringify(target.testId ?? target.value ?? "")})`;
|
|
2551
|
+
if (target.strategy === "text" || target.text)
|
|
2552
|
+
return `page.getByText(${JSON.stringify(target.text ?? target.value ?? "")})`;
|
|
2553
|
+
return `page.locator(${JSON.stringify(target.cssSelector ?? target.value ?? "")})`;
|
|
2554
|
+
}
|
|
2555
|
+
|
|
2329
2556
|
// src/commands/scan.ts
|
|
2330
2557
|
async function runScan(options) {
|
|
2331
2558
|
console.log(`checking scan ${redactUrl(options.url)} ...`);
|
|
@@ -2394,7 +2621,7 @@ Saved CSV: ${csvPath}`);
|
|
|
2394
2621
|
}
|
|
2395
2622
|
|
|
2396
2623
|
// src/commands/serve.ts
|
|
2397
|
-
import { dirname as
|
|
2624
|
+
import { dirname as dirname4, join as join4 } from "node:path";
|
|
2398
2625
|
import { fileURLToPath } from "node:url";
|
|
2399
2626
|
|
|
2400
2627
|
// ../server/dist/app.js
|
|
@@ -2531,11 +2758,11 @@ async function saveScreenshot(root, projectId, screenshot) {
|
|
|
2531
2758
|
});
|
|
2532
2759
|
}
|
|
2533
2760
|
async function deleteScreenshot(root, projectId, name) {
|
|
2534
|
-
const
|
|
2761
|
+
const safeName2 = assertFileName(name);
|
|
2535
2762
|
const directory = join(await ensureProject(root, projectId), "screenshots");
|
|
2536
|
-
await rm(join(directory,
|
|
2763
|
+
await rm(join(directory, safeName2), { force: true });
|
|
2537
2764
|
const current = await readScreenshots(root, projectId);
|
|
2538
|
-
await writeJson(join(directory, "index.json"), current.filter((item) => item.name !==
|
|
2765
|
+
await writeJson(join(directory, "index.json"), current.filter((item) => item.name !== safeName2));
|
|
2539
2766
|
}
|
|
2540
2767
|
async function screenshotFile(root, projectId, name) {
|
|
2541
2768
|
return readFile(join(await ensureProject(root, projectId), "screenshots", assertFileName(name)));
|
|
@@ -2592,6 +2819,20 @@ async function saveRunLog(root, projectId, testCaseId, status, logs) {
|
|
|
2592
2819
|
const name = `${timestamp}-${safeFileName(testCaseId, "test-case")}.json`;
|
|
2593
2820
|
await writeJson(join(directory, name), { testCaseId, status, createdAt: (/* @__PURE__ */ new Date()).toISOString(), logs });
|
|
2594
2821
|
}
|
|
2822
|
+
async function readGuidedFlows(root, projectId) {
|
|
2823
|
+
const directory = await ensureProject(root, projectId);
|
|
2824
|
+
return readJson(join(directory, "guided-flows.json"), []);
|
|
2825
|
+
}
|
|
2826
|
+
async function saveGuidedFlows(root, projectId, flows) {
|
|
2827
|
+
if (!Array.isArray(flows) || flows.length > 100)
|
|
2828
|
+
throw new Error("Guided Flow limit exceeded");
|
|
2829
|
+
for (const flow of flows) {
|
|
2830
|
+
if (!flow?.id || !flow.name || !flow.baseUrl || !Array.isArray(flow.steps) || flow.steps.length > 200)
|
|
2831
|
+
throw new Error("Invalid Guided Flow");
|
|
2832
|
+
}
|
|
2833
|
+
const directory = await ensureProject(root, projectId);
|
|
2834
|
+
await writeJson(join(directory, "guided-flows.json"), flows);
|
|
2835
|
+
}
|
|
2595
2836
|
async function saveReport(root, projectId, name, html) {
|
|
2596
2837
|
if (typeof html !== "string" || html.length > 2e6)
|
|
2597
2838
|
throw new Error("Report exceeds the 2 MB limit");
|
|
@@ -2612,6 +2853,38 @@ async function openWorkspace(root) {
|
|
|
2612
2853
|
async function browserProfileDirectory(root, projectId) {
|
|
2613
2854
|
return join(await ensureProject(root, projectId), "browser-profile");
|
|
2614
2855
|
}
|
|
2856
|
+
async function browserProfileStatus(root, projectId) {
|
|
2857
|
+
const directory = join(projectDirectory(root, projectId), "browser-profile");
|
|
2858
|
+
try {
|
|
2859
|
+
const entries = await readdir(directory);
|
|
2860
|
+
const candidates = [
|
|
2861
|
+
directory,
|
|
2862
|
+
join(directory, "Local State"),
|
|
2863
|
+
join(directory, "Default"),
|
|
2864
|
+
join(directory, "Default", "Cookies"),
|
|
2865
|
+
join(directory, "Default", "Local Storage")
|
|
2866
|
+
];
|
|
2867
|
+
const modifiedTimes = await Promise.all(candidates.map(async (candidate) => {
|
|
2868
|
+
try {
|
|
2869
|
+
return (await stat(candidate)).mtimeMs;
|
|
2870
|
+
} catch {
|
|
2871
|
+
return 0;
|
|
2872
|
+
}
|
|
2873
|
+
}));
|
|
2874
|
+
return {
|
|
2875
|
+
profileExists: true,
|
|
2876
|
+
browserDataDetected: entries.includes("Default") || entries.includes("Local State"),
|
|
2877
|
+
cookieStoreDetected: modifiedTimes[3] > 0 || modifiedTimes[4] > 0,
|
|
2878
|
+
lastModifiedAt: new Date(Math.max(...modifiedTimes)).toISOString()
|
|
2879
|
+
};
|
|
2880
|
+
} catch {
|
|
2881
|
+
return { profileExists: false, browserDataDetected: false, cookieStoreDetected: false };
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
async function clearBrowserProfile(root, projectId) {
|
|
2885
|
+
const directory = join(projectDirectory(root, projectId), "browser-profile");
|
|
2886
|
+
await rm(directory, { recursive: true, force: true });
|
|
2887
|
+
}
|
|
2615
2888
|
async function readProject(root, projectId) {
|
|
2616
2889
|
try {
|
|
2617
2890
|
const directory = projectDirectory(root, projectId);
|
|
@@ -2940,6 +3213,205 @@ function registerExportCsvRoute(app) {
|
|
|
2940
3213
|
});
|
|
2941
3214
|
}
|
|
2942
3215
|
|
|
3216
|
+
// ../server/dist/routes/playwrightCliRunner.js
|
|
3217
|
+
import { createRequire } from "node:module";
|
|
3218
|
+
import { spawn } from "node:child_process";
|
|
3219
|
+
import { mkdtemp, readdir as readdir2, readFile as readFile2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
|
|
3220
|
+
import { dirname as dirname2, join as join2 } from "node:path";
|
|
3221
|
+
var require2 = createRequire(import.meta.url);
|
|
3222
|
+
var CLI_ENTRY = require2.resolve("@playwright/test/cli");
|
|
3223
|
+
var MAX_SCREENSHOTS = 10;
|
|
3224
|
+
async function runPlaywrightCli(input) {
|
|
3225
|
+
const started = Date.now();
|
|
3226
|
+
const runDirectory = await mkdtemp(join2(dirname2(CLI_ENTRY), ".lazyscout-run-"));
|
|
3227
|
+
const source = resolveSource(input.source, input.testCase, input.secrets, Boolean(input.profileDirectory));
|
|
3228
|
+
validateLiteralNavigationUrls(source);
|
|
3229
|
+
const specPath = join2(runDirectory, `${safeName(input.testCaseId)}.spec.ts`);
|
|
3230
|
+
const configPath = join2(runDirectory, "playwright.config.mjs");
|
|
3231
|
+
await writeFile3(specPath, source, "utf8");
|
|
3232
|
+
if (input.profileDirectory) {
|
|
3233
|
+
const fixture = createProfileFixture();
|
|
3234
|
+
await writeFile3(join2(runDirectory, "lazyscout-fixture.mjs"), fixture, "utf8");
|
|
3235
|
+
}
|
|
3236
|
+
await writeFile3(configPath, createConfig(), "utf8");
|
|
3237
|
+
const child = spawn(process.execPath, [CLI_ENTRY, "test", "--config", configPath], {
|
|
3238
|
+
cwd: runDirectory,
|
|
3239
|
+
env: {
|
|
3240
|
+
...process.env,
|
|
3241
|
+
FORCE_COLOR: "0",
|
|
3242
|
+
...input.profileDirectory ? { LAZYSCOUT_PROFILE_DIR: input.profileDirectory } : {}
|
|
3243
|
+
},
|
|
3244
|
+
windowsHide: true,
|
|
3245
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
3246
|
+
});
|
|
3247
|
+
input.onProcess?.(child);
|
|
3248
|
+
let stopped = false;
|
|
3249
|
+
let output = "";
|
|
3250
|
+
const appendOutput = (level, chunk) => {
|
|
3251
|
+
output += String(chunk);
|
|
3252
|
+
const lines = output.split(/\r?\n/);
|
|
3253
|
+
output = lines.pop() ?? "";
|
|
3254
|
+
for (const line of lines) {
|
|
3255
|
+
const clean = stripAnsi(line).trim();
|
|
3256
|
+
if (clean)
|
|
3257
|
+
input.addLog(level, clean);
|
|
3258
|
+
}
|
|
3259
|
+
};
|
|
3260
|
+
child.stdout?.on("data", (chunk) => appendOutput("info", chunk));
|
|
3261
|
+
child.stderr?.on("data", (chunk) => appendOutput("warn", chunk));
|
|
3262
|
+
const close = async () => {
|
|
3263
|
+
if (child.exitCode !== null || child.killed)
|
|
3264
|
+
return;
|
|
3265
|
+
stopped = true;
|
|
3266
|
+
if (process.platform === "win32" && child.pid) {
|
|
3267
|
+
spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
|
|
3268
|
+
} else
|
|
3269
|
+
child.kill("SIGTERM");
|
|
3270
|
+
};
|
|
3271
|
+
const exit = await new Promise((resolve3) => {
|
|
3272
|
+
child.once("close", (code, signal) => resolve3({ code, signal }));
|
|
3273
|
+
child.once("error", () => resolve3({ code: 1, signal: null }));
|
|
3274
|
+
});
|
|
3275
|
+
if (output.trim())
|
|
3276
|
+
appendOutput(exit.code === 0 ? "info" : "warn", "\n" + output);
|
|
3277
|
+
const screenshots = await readScreenshots2(runDirectory, input.testCaseId);
|
|
3278
|
+
const passed = exit.code === 0 && !stopped;
|
|
3279
|
+
const status = stopped ? "stopped" : passed ? "passed" : "failed";
|
|
3280
|
+
if (status === "passed")
|
|
3281
|
+
input.addLog("pass", `Playwright Test completed: ${input.testCaseId}`, Date.now() - started);
|
|
3282
|
+
if (status === "stopped")
|
|
3283
|
+
input.addLog("warn", "Playwright Test stopped by user", Date.now() - started);
|
|
3284
|
+
if (status === "failed")
|
|
3285
|
+
input.addLog("fail", `Playwright Test failed (exit code ${exit.code ?? "unknown"})`, Date.now() - started);
|
|
3286
|
+
let error;
|
|
3287
|
+
if (status === "failed") {
|
|
3288
|
+
const result = await readFile2(join2(runDirectory, "results.json"), "utf8").catch(() => "");
|
|
3289
|
+
error = summarizeFailure(result) ?? "Playwright Test failed. See the CLI output for details.";
|
|
3290
|
+
input.addLog("fail", error);
|
|
3291
|
+
}
|
|
3292
|
+
await rm2(runDirectory, { recursive: true, force: true }).catch(() => void 0);
|
|
3293
|
+
return {
|
|
3294
|
+
status,
|
|
3295
|
+
error,
|
|
3296
|
+
screenshots: screenshots.map((item) => ({ ...item, status: status === "passed" ? "passed" : "failed" })),
|
|
3297
|
+
close
|
|
3298
|
+
};
|
|
3299
|
+
}
|
|
3300
|
+
function resolveSource(source, testCase, secrets, useProfile = false) {
|
|
3301
|
+
const generated = source?.trim() || generatePlaywrightTest(testCase);
|
|
3302
|
+
const resolved = replaceSecrets(generated, secrets);
|
|
3303
|
+
const fullSource = /\btest\s*\(/.test(resolved) && /@playwright\/test/.test(resolved) ? resolved : [
|
|
3304
|
+
`import { test, expect } from '@playwright/test'`,
|
|
3305
|
+
"",
|
|
3306
|
+
`test(${JSON.stringify(testCase.title)}, async ({ page }) => {`,
|
|
3307
|
+
resolved,
|
|
3308
|
+
"})",
|
|
3309
|
+
""
|
|
3310
|
+
].join("\n");
|
|
3311
|
+
return useProfile ? fullSource.replace(/from\s+(['"])@playwright\/test\1/g, "from './lazyscout-fixture.mjs'") : fullSource;
|
|
3312
|
+
}
|
|
3313
|
+
function createProfileFixture() {
|
|
3314
|
+
return `import { test as base, expect } from '@playwright/test'
|
|
3315
|
+
import { chromium } from 'playwright-core'
|
|
3316
|
+
|
|
3317
|
+
export const test = base.extend({
|
|
3318
|
+
context: async ({}, use) => {
|
|
3319
|
+
const context = await chromium.launchPersistentContext(process.env.LAZYSCOUT_PROFILE_DIR, { headless: true })
|
|
3320
|
+
await use(context)
|
|
3321
|
+
await context.close()
|
|
3322
|
+
}
|
|
3323
|
+
})
|
|
3324
|
+
|
|
3325
|
+
export { expect }
|
|
3326
|
+
`;
|
|
3327
|
+
}
|
|
3328
|
+
function replaceSecrets(source, secrets) {
|
|
3329
|
+
const values = {
|
|
3330
|
+
TEST_EMAIL: secrets?.email ?? process.env.LAZYSCOUT_TEST_EMAIL,
|
|
3331
|
+
TEST_USERNAME: secrets?.username ?? process.env.LAZYSCOUT_TEST_USERNAME,
|
|
3332
|
+
TEST_PASSWORD: secrets?.password ?? process.env.LAZYSCOUT_TEST_PASSWORD,
|
|
3333
|
+
API_TOKEN: secrets?.apiToken ?? process.env.LAZYSCOUT_API_TOKEN,
|
|
3334
|
+
...secrets?.variables ?? {}
|
|
3335
|
+
};
|
|
3336
|
+
return source.replace(/\{\{([A-Z][A-Z0-9_]*)\}\}/g, (_, key) => {
|
|
3337
|
+
const value = values[key];
|
|
3338
|
+
if (value === void 0)
|
|
3339
|
+
throw new Error(`Required test variable is not configured for {{${key}}}`);
|
|
3340
|
+
return escapeStringContent(value);
|
|
3341
|
+
});
|
|
3342
|
+
}
|
|
3343
|
+
function escapeStringContent(value) {
|
|
3344
|
+
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r/g, "\\r").replace(/\n/g, "\\n");
|
|
3345
|
+
}
|
|
3346
|
+
function validateLiteralNavigationUrls(source) {
|
|
3347
|
+
const pattern = /page\.goto\(\s*(['"])(.*?)\1/g;
|
|
3348
|
+
for (const match of source.matchAll(pattern)) {
|
|
3349
|
+
const checked = checkTargetUrl(match[2], config.urlPolicy);
|
|
3350
|
+
if (!checked.ok)
|
|
3351
|
+
throw new Error(checked.message);
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
3354
|
+
function createConfig() {
|
|
3355
|
+
return `import { defineConfig } from '@playwright/test'
|
|
3356
|
+
export default defineConfig({
|
|
3357
|
+
testDir: '.',
|
|
3358
|
+
timeout: 20000,
|
|
3359
|
+
expect: { timeout: 20000 },
|
|
3360
|
+
workers: 1,
|
|
3361
|
+
fullyParallel: false,
|
|
3362
|
+
reporter: [['line'], ['json', { outputFile: 'results.json' }]],
|
|
3363
|
+
use: { headless: true, actionTimeout: 20000, navigationTimeout: 20000, screenshot: 'off' }
|
|
3364
|
+
})
|
|
3365
|
+
`;
|
|
3366
|
+
}
|
|
3367
|
+
async function readScreenshots2(directory, testCaseId) {
|
|
3368
|
+
const files = await collectImages(directory);
|
|
3369
|
+
const screenshots = [];
|
|
3370
|
+
for (const file of files.slice(0, MAX_SCREENSHOTS)) {
|
|
3371
|
+
const extension = file.toLowerCase().endsWith(".jpg") || file.toLowerCase().endsWith(".jpeg") ? "jpeg" : "png";
|
|
3372
|
+
const data = await readFile2(file);
|
|
3373
|
+
screenshots.push({
|
|
3374
|
+
name: file.slice(directory.length + 1).replaceAll("\\", "/"),
|
|
3375
|
+
dataUrl: `data:image/${extension};base64,${data.toString("base64")}`,
|
|
3376
|
+
capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3377
|
+
testCaseId,
|
|
3378
|
+
status: "failed"
|
|
3379
|
+
});
|
|
3380
|
+
}
|
|
3381
|
+
return screenshots;
|
|
3382
|
+
}
|
|
3383
|
+
async function collectImages(directory) {
|
|
3384
|
+
const entries = await readdir2(directory, { withFileTypes: true });
|
|
3385
|
+
const files = [];
|
|
3386
|
+
for (const entry of entries) {
|
|
3387
|
+
const path = join2(directory, entry.name);
|
|
3388
|
+
if (entry.isDirectory())
|
|
3389
|
+
files.push(...await collectImages(path));
|
|
3390
|
+
else if (/\.(png|jpe?g)$/i.test(entry.name))
|
|
3391
|
+
files.push(path);
|
|
3392
|
+
}
|
|
3393
|
+
return files;
|
|
3394
|
+
}
|
|
3395
|
+
function summarizeFailure(result) {
|
|
3396
|
+
if (!result)
|
|
3397
|
+
return void 0;
|
|
3398
|
+
try {
|
|
3399
|
+
const parsed = JSON.parse(result);
|
|
3400
|
+
return parsed.suites?.flatMap((suite) => suite.specs ?? []).flatMap((spec) => spec.tests ?? []).flatMap((test) => test.errors ?? [])[0]?.message;
|
|
3401
|
+
} catch {
|
|
3402
|
+
return void 0;
|
|
3403
|
+
}
|
|
3404
|
+
}
|
|
3405
|
+
function safeName(value) {
|
|
3406
|
+
return value.replace(/[^a-zA-Z0-9._-]/g, "-").slice(0, 80) || "test-case";
|
|
3407
|
+
}
|
|
3408
|
+
function stripAnsi(value) {
|
|
3409
|
+
return value.replace(/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g, "");
|
|
3410
|
+
}
|
|
3411
|
+
function redactCliError(error, secretValues) {
|
|
3412
|
+
return redactSensitiveText(error instanceof Error ? error.message : String(error), secretValues);
|
|
3413
|
+
}
|
|
3414
|
+
|
|
2943
3415
|
// ../server/dist/routes/automationRun.js
|
|
2944
3416
|
var MAX_STEPS = 100;
|
|
2945
3417
|
var MAX_LOGS = 250;
|
|
@@ -2962,497 +3434,112 @@ function registerAutomationRunRoute(app, workspaceRoot) {
|
|
|
2962
3434
|
const body = request.body;
|
|
2963
3435
|
const testCase = body.testCase;
|
|
2964
3436
|
const secrets = body.secrets;
|
|
2965
|
-
const blockedKeywords = normalizeBlockedKeywords(body.blockedKeywords);
|
|
2966
3437
|
const framework = body.framework ?? "playwright";
|
|
2967
3438
|
const runId = body.runId || crypto.randomUUID();
|
|
3439
|
+
const blockedKeywords = normalizeBlockedKeywords(body.blockedKeywords);
|
|
2968
3440
|
if (!testCase || !Array.isArray(testCase.steps))
|
|
2969
3441
|
return reply.status(400).send({ error: { code: "invalid-test-case", message: "The requested Test Case was not found." } });
|
|
2970
3442
|
if (testCase.steps.length > MAX_STEPS)
|
|
2971
|
-
return reply.status(400).send({ error: { code: "run-limit", message:
|
|
3443
|
+
return reply.status(400).send({ error: { code: "run-limit", message: `Step count exceeds the limit of ${MAX_STEPS}` } });
|
|
2972
3444
|
if (typeof body.code === "string" && body.code.length > MAX_SOURCE_LENGTH)
|
|
2973
3445
|
return reply.status(400).send({ error: { code: "source-limit", message: "Generated source exceeds the size limit." } });
|
|
2974
3446
|
const logs = [];
|
|
2975
3447
|
const secretValues = [
|
|
2976
|
-
secrets?.email,
|
|
2977
|
-
secrets?.username,
|
|
2978
|
-
secrets?.password,
|
|
2979
|
-
secrets?.apiToken,
|
|
3448
|
+
body.secrets?.email,
|
|
3449
|
+
body.secrets?.username,
|
|
3450
|
+
body.secrets?.password,
|
|
3451
|
+
body.secrets?.apiToken,
|
|
2980
3452
|
process.env.LAZYSCOUT_TEST_EMAIL,
|
|
2981
3453
|
process.env.LAZYSCOUT_TEST_USERNAME,
|
|
2982
3454
|
process.env.LAZYSCOUT_TEST_PASSWORD,
|
|
2983
|
-
process.env.LAZYSCOUT_API_TOKEN
|
|
3455
|
+
process.env.LAZYSCOUT_API_TOKEN,
|
|
3456
|
+
...secrets?.variables ? Object.values(secrets.variables) : []
|
|
2984
3457
|
].filter((value) => Boolean(value));
|
|
2985
3458
|
const addLog = (level, message, durationMs) => {
|
|
2986
|
-
if (logs.length
|
|
2987
|
-
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
}
|
|
3459
|
+
if (logs.length >= MAX_LOGS)
|
|
3460
|
+
return;
|
|
3461
|
+
logs.push({
|
|
3462
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3463
|
+
level,
|
|
3464
|
+
message: redactSensitiveText(message, secretValues),
|
|
3465
|
+
...durationMs === void 0 ? {} : { durationMs }
|
|
3466
|
+
});
|
|
2993
3467
|
};
|
|
2994
|
-
const persistLog = async (
|
|
3468
|
+
const persistLog = async (status) => {
|
|
2995
3469
|
if (!body.projectId)
|
|
2996
3470
|
return;
|
|
2997
|
-
await saveRunLog(workspaceRoot, body.projectId, testCase.id,
|
|
3471
|
+
await saveRunLog(workspaceRoot, body.projectId, testCase.id, status, logs).catch((error) => addLog("warn", `Could not save run log: ${error instanceof Error ? error.message : String(error)}`));
|
|
2998
3472
|
};
|
|
2999
|
-
|
|
3000
|
-
addLog("info",
|
|
3001
|
-
addLog("info",
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
addLog("warn", "Blocked: this case is marked manual and cannot be automated");
|
|
3473
|
+
addLog("info", `$ lazyscout test --case ${testCase.id}`);
|
|
3474
|
+
addLog("info", `Starting Playwright Test CLI: ${testCase.title}`);
|
|
3475
|
+
addLog("info", `Test budget: ${MAX_STEPS} steps \xB7 ${STEP_TIMEOUT_MS / 1e3}s per action \xB7 ${MAX_LOGS} log lines`);
|
|
3476
|
+
if (!body.code?.trim() && testCase.steps.length === 0) {
|
|
3477
|
+
addLog("warn", "This Test Case has no Steps or Playwright code to run");
|
|
3005
3478
|
await persistLog("blocked");
|
|
3006
3479
|
return reply.send({ status: "blocked", framework, logs });
|
|
3007
3480
|
}
|
|
3481
|
+
if (testCase.automationStatus === "manual") {
|
|
3482
|
+
addLog("info", "Manual Test Case accepted: running the provided Playwright source or Steps");
|
|
3483
|
+
}
|
|
3008
3484
|
if (framework === "cypress") {
|
|
3009
3485
|
addLog("warn", "Cypress code generation is available; local runner uses Playwright only.");
|
|
3010
3486
|
await persistLog("unsupported");
|
|
3011
3487
|
return reply.send({ status: "unsupported", framework, logs });
|
|
3012
3488
|
}
|
|
3489
|
+
const sourceForSafety = body.code?.trim() || "";
|
|
3490
|
+
const unsafeLine = sourceForSafety.split(/\r?\n/).find((line) => /\.click\s*\(\s*\)/.test(line) && (isUnsafeAutoClick(line) || isBlockedLabel(blockedKeywords, line)));
|
|
3491
|
+
if (unsafeLine) {
|
|
3492
|
+
addLog("warn", "Blocked by the LazyScout click safety policy");
|
|
3493
|
+
await persistLog("blocked");
|
|
3494
|
+
return reply.send({ status: "blocked", framework, logs });
|
|
3495
|
+
}
|
|
3013
3496
|
const active = { stopped: false };
|
|
3014
3497
|
activeRuns.set(runId, active);
|
|
3015
|
-
let close;
|
|
3016
|
-
let page;
|
|
3017
|
-
const capturedScreenshots = [];
|
|
3018
3498
|
try {
|
|
3019
|
-
const
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
const stepStarted = Date.now();
|
|
3039
|
-
await executeStep(page, step, addLog, blockedKeywords, secrets);
|
|
3040
|
-
if (active.stopped)
|
|
3041
|
-
throw new Error("Run stopped by user");
|
|
3042
|
-
addLog("pass", `\u2713 ${step.type}`, Date.now() - stepStarted);
|
|
3499
|
+
const result = await runPlaywrightCli({
|
|
3500
|
+
source: body.code,
|
|
3501
|
+
testCase,
|
|
3502
|
+
testCaseId: testCase.id,
|
|
3503
|
+
secrets: body.secrets,
|
|
3504
|
+
secretValues,
|
|
3505
|
+
profileDirectory: body.projectId ? await browserProfileDirectory(workspaceRoot, body.projectId) : void 0,
|
|
3506
|
+
addLog,
|
|
3507
|
+
onProcess: (child) => {
|
|
3508
|
+
active.close = async () => {
|
|
3509
|
+
if (process.platform === "win32" && child.pid) {
|
|
3510
|
+
const killer = (await import("node:child_process")).spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
3511
|
+
windowsHide: true,
|
|
3512
|
+
stdio: "ignore"
|
|
3513
|
+
});
|
|
3514
|
+
await new Promise((resolve3) => killer.once("close", () => resolve3()));
|
|
3515
|
+
} else
|
|
3516
|
+
child.kill("SIGTERM");
|
|
3517
|
+
};
|
|
3043
3518
|
}
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
await persistLog("passed");
|
|
3519
|
+
});
|
|
3520
|
+
await persistLog(result.status);
|
|
3047
3521
|
return reply.send({
|
|
3048
|
-
status:
|
|
3522
|
+
status: result.status,
|
|
3049
3523
|
framework,
|
|
3050
3524
|
logs,
|
|
3051
|
-
|
|
3052
|
-
|
|
3525
|
+
...result.error ? { error: redactCliError(result.error, secretValues) } : {},
|
|
3526
|
+
screenshots: result.screenshots,
|
|
3527
|
+
screenshot: result.screenshots.at(-1)
|
|
3053
3528
|
});
|
|
3054
3529
|
} catch (error) {
|
|
3055
|
-
const message =
|
|
3056
|
-
debugLocator("StepFailed", { testCaseId: testCase.id, url: page?.url(), error: message });
|
|
3530
|
+
const message = redactCliError(error, secretValues);
|
|
3057
3531
|
if (active.stopped) {
|
|
3058
|
-
addLog("warn", "Run stopped by user"
|
|
3532
|
+
addLog("warn", "Run stopped by user");
|
|
3059
3533
|
await persistLog("stopped");
|
|
3060
3534
|
return reply.send({ status: "stopped", framework, logs });
|
|
3061
3535
|
}
|
|
3062
|
-
addLog("fail",
|
|
3063
|
-
const screenshots = withScreenshotStatus(capturedScreenshots, "failed");
|
|
3536
|
+
addLog("fail", message);
|
|
3064
3537
|
await persistLog("failed");
|
|
3065
|
-
return reply.send({
|
|
3066
|
-
status: "failed",
|
|
3067
|
-
framework,
|
|
3068
|
-
logs,
|
|
3069
|
-
error: message,
|
|
3070
|
-
screenshots,
|
|
3071
|
-
screenshot: screenshots.at(-1)
|
|
3072
|
-
});
|
|
3538
|
+
return reply.send({ status: "failed", framework, logs, error: message });
|
|
3073
3539
|
} finally {
|
|
3074
3540
|
activeRuns.delete(runId);
|
|
3075
|
-
await close?.().catch(() => void 0);
|
|
3076
|
-
}
|
|
3077
|
-
});
|
|
3078
|
-
}
|
|
3079
|
-
function withScreenshotStatus(screenshots, status) {
|
|
3080
|
-
return screenshots.map((screenshot) => ({ ...screenshot, status }));
|
|
3081
|
-
}
|
|
3082
|
-
async function executeEditedCode(page, source, testCaseId, capturedScreenshots, addLog, blockedKeywords, projectSecrets) {
|
|
3083
|
-
const lines = source.split(/\r?\n/);
|
|
3084
|
-
let executed = 0;
|
|
3085
|
-
for (const rawLine of lines) {
|
|
3086
|
-
const line = rawLine.trim().replace(/;$/, "");
|
|
3087
|
-
if (!line || line.startsWith("import ") || line.startsWith("test(") || line === "})" || line === "});")
|
|
3088
|
-
continue;
|
|
3089
|
-
if (line.startsWith("//"))
|
|
3090
|
-
continue;
|
|
3091
|
-
if (++executed > MAX_STEPS)
|
|
3092
|
-
throw new Error(`Edited source exceeds the ${MAX_STEPS} action limit`);
|
|
3093
|
-
const gotoMatch = line.match(new RegExp(`^await page\\.goto\\((${STRING_LITERAL})\\)$`));
|
|
3094
|
-
if (gotoMatch) {
|
|
3095
|
-
const url = parseStringLiteral(gotoMatch[1]);
|
|
3096
|
-
const checked = checkTargetUrl(url, config.urlPolicy);
|
|
3097
|
-
if (!checked.ok)
|
|
3098
|
-
throw new Error(checked.message);
|
|
3099
|
-
addLog("info", `\u2192 Navigating to ${redactUrl(checked.url.toString())}`);
|
|
3100
|
-
await page.goto(checked.url.toString(), { waitUntil: "domcontentloaded", timeout: STEP_TIMEOUT_MS });
|
|
3101
|
-
continue;
|
|
3102
|
-
}
|
|
3103
|
-
const waitMatch = line.match(/^await page\.waitForTimeout\((\d{1,5})\)$/);
|
|
3104
|
-
if (waitMatch) {
|
|
3105
|
-
const waitMs = Math.min(Number(waitMatch[1]), 5e3);
|
|
3106
|
-
addLog("info", `\u2192 Waiting ${waitMs}ms`);
|
|
3107
|
-
await page.waitForTimeout(waitMs);
|
|
3108
|
-
continue;
|
|
3109
|
-
}
|
|
3110
|
-
const screenshotMatch = line.match(/^await page\.screenshot\((.*)\)$/);
|
|
3111
|
-
if (screenshotMatch) {
|
|
3112
|
-
const screenshot = await captureRequestedScreenshot(page, screenshotMatch[1], testCaseId);
|
|
3113
|
-
capturedScreenshots.push(screenshot);
|
|
3114
|
-
addLog("pass", `Screenshot captured: ${screenshot.name}`);
|
|
3115
|
-
continue;
|
|
3116
|
-
}
|
|
3117
|
-
const clickMatch = line.match(/^await (page\..+)\.click\(\)$/);
|
|
3118
|
-
if (clickMatch) {
|
|
3119
|
-
const target = parseEditedLocator(page, clickMatch[1]);
|
|
3120
|
-
await ensureSafeClick(target.locator, target.label, blockedKeywords);
|
|
3121
|
-
addLog("info", `\u2192 Clicking ${target.label}`);
|
|
3122
|
-
await target.locator.click();
|
|
3123
|
-
continue;
|
|
3124
|
-
}
|
|
3125
|
-
const fillMatch = line.match(new RegExp(`^await (page\\..+)\\.fill\\((${STRING_LITERAL})\\)$`));
|
|
3126
|
-
if (fillMatch) {
|
|
3127
|
-
const target = parseEditedLocator(page, fillMatch[1]);
|
|
3128
|
-
addLog("info", `\u2192 Filling ${target.label}`);
|
|
3129
|
-
await target.locator.fill(resolveSecret(parseStringLiteral(fillMatch[2]), projectSecrets));
|
|
3130
|
-
continue;
|
|
3131
|
-
}
|
|
3132
|
-
const selectMatch = line.match(new RegExp(`^await (page\\..+)\\.selectOption\\((${STRING_LITERAL})\\)$`));
|
|
3133
|
-
if (selectMatch) {
|
|
3134
|
-
const target = parseEditedLocator(page, selectMatch[1]);
|
|
3135
|
-
const option = parseStringLiteral(selectMatch[2]);
|
|
3136
|
-
addLog("info", `\u2192 Selecting an option in ${target.label}`);
|
|
3137
|
-
await target.locator.selectOption(option);
|
|
3138
|
-
continue;
|
|
3139
|
-
}
|
|
3140
|
-
const visibleMatch = line.match(/^await expect\((page\..+)\)\.toBeVisible\(\)$/);
|
|
3141
|
-
if (visibleMatch) {
|
|
3142
|
-
const target = parseEditedLocator(page, visibleMatch[1]);
|
|
3143
|
-
if (!await target.locator.isVisible())
|
|
3144
|
-
throw new Error(`Expected ${target.label} to be visible`);
|
|
3145
|
-
addLog("pass", `Element visible: ${target.label}`);
|
|
3146
|
-
continue;
|
|
3147
|
-
}
|
|
3148
|
-
const textMatch = line.match(new RegExp(`^await expect\\((page(?:\\..+)?)\\)\\.toContainText\\((${STRING_LITERAL})\\)$`));
|
|
3149
|
-
if (textMatch) {
|
|
3150
|
-
const expected = parseStringLiteral(textMatch[2]);
|
|
3151
|
-
const actual = textMatch[1] === "page" ? await page.locator("body").innerText() : await parseEditedLocator(page, textMatch[1]).locator.innerText();
|
|
3152
|
-
if (!actual.includes(expected))
|
|
3153
|
-
throw new Error(`Expected text was not found: ${expected}`);
|
|
3154
|
-
addLog("pass", "Text assertion passed");
|
|
3155
|
-
continue;
|
|
3156
|
-
}
|
|
3157
|
-
const urlMatch = line.match(new RegExp(`^await expect\\(page\\)\\.toHaveURL\\(new RegExp\\((${STRING_LITERAL})\\)\\)$`));
|
|
3158
|
-
if (urlMatch) {
|
|
3159
|
-
const expected = parseStringLiteral(urlMatch[1]);
|
|
3160
|
-
if (!page.url().includes(expected))
|
|
3161
|
-
throw new Error(`URL did not contain ${expected}`);
|
|
3162
|
-
addLog("pass", `URL assertion passed: ${redactUrl(page.url())}`);
|
|
3163
|
-
continue;
|
|
3164
|
-
}
|
|
3165
|
-
throw new Error(`Unsupported edited Playwright statement: ${line.slice(0, 120)}`);
|
|
3166
|
-
}
|
|
3167
|
-
if (executed === 0)
|
|
3168
|
-
throw new Error("Edited source does not contain a supported Playwright action");
|
|
3169
|
-
}
|
|
3170
|
-
function parseScreenshotOptions(source) {
|
|
3171
|
-
const value = source.trim();
|
|
3172
|
-
if (!value)
|
|
3173
|
-
return { fullPage: false, type: "png" };
|
|
3174
|
-
const objectMatch = value.match(/^\{([\s\S]*)\}$/);
|
|
3175
|
-
if (!objectMatch)
|
|
3176
|
-
throw new Error("page.screenshot() accepts an options object only");
|
|
3177
|
-
let path;
|
|
3178
|
-
let fullPage = false;
|
|
3179
|
-
let type;
|
|
3180
|
-
let quality;
|
|
3181
|
-
for (const entry of splitOptionList(objectMatch[1])) {
|
|
3182
|
-
const separator = entry.indexOf(":");
|
|
3183
|
-
if (separator < 1)
|
|
3184
|
-
throw new Error(`Unsupported screenshot option: ${entry.slice(0, 80)}`);
|
|
3185
|
-
const key = entry.slice(0, separator).trim();
|
|
3186
|
-
const raw = entry.slice(separator + 1).trim();
|
|
3187
|
-
if (key === "path")
|
|
3188
|
-
path = parseSourceString(raw);
|
|
3189
|
-
else if (key === "fullPage" && /^(true|false)$/.test(raw))
|
|
3190
|
-
fullPage = raw === "true";
|
|
3191
|
-
else if (key === "type") {
|
|
3192
|
-
const parsedType = parseSourceString(raw);
|
|
3193
|
-
if (parsedType !== "png" && parsedType !== "jpeg")
|
|
3194
|
-
throw new Error("Screenshot type must be png or jpeg");
|
|
3195
|
-
type = parsedType;
|
|
3196
|
-
} else if (key === "quality" && /^\d{1,3}$/.test(raw))
|
|
3197
|
-
quality = Math.min(100, Math.max(1, Number(raw)));
|
|
3198
|
-
else
|
|
3199
|
-
throw new Error(`Unsupported screenshot option: ${key.slice(0, 40)}`);
|
|
3200
|
-
}
|
|
3201
|
-
const inferredType = path && /\.jpe?g$/i.test(path) ? "jpeg" : "png";
|
|
3202
|
-
return { path, fullPage, type: type ?? inferredType, quality };
|
|
3203
|
-
}
|
|
3204
|
-
function splitOptionList(value) {
|
|
3205
|
-
const entries = [];
|
|
3206
|
-
let current = "";
|
|
3207
|
-
let quote = "";
|
|
3208
|
-
let escaped = false;
|
|
3209
|
-
for (const character of value) {
|
|
3210
|
-
if (escaped) {
|
|
3211
|
-
current += character;
|
|
3212
|
-
escaped = false;
|
|
3213
|
-
continue;
|
|
3214
|
-
}
|
|
3215
|
-
if (character === "\\") {
|
|
3216
|
-
current += character;
|
|
3217
|
-
escaped = true;
|
|
3218
|
-
continue;
|
|
3219
|
-
}
|
|
3220
|
-
if (quote) {
|
|
3221
|
-
current += character;
|
|
3222
|
-
if (character === quote)
|
|
3223
|
-
quote = "";
|
|
3224
|
-
continue;
|
|
3225
|
-
}
|
|
3226
|
-
if (character === '"' || character === "'") {
|
|
3227
|
-
quote = character;
|
|
3228
|
-
current += character;
|
|
3229
|
-
continue;
|
|
3230
|
-
}
|
|
3231
|
-
if (character === ",") {
|
|
3232
|
-
if (current.trim())
|
|
3233
|
-
entries.push(current.trim());
|
|
3234
|
-
current = "";
|
|
3235
|
-
continue;
|
|
3236
|
-
}
|
|
3237
|
-
current += character;
|
|
3238
|
-
}
|
|
3239
|
-
if (quote || escaped)
|
|
3240
|
-
throw new Error("Screenshot options contain an incomplete string");
|
|
3241
|
-
if (current.trim())
|
|
3242
|
-
entries.push(current.trim());
|
|
3243
|
-
return entries;
|
|
3244
|
-
}
|
|
3245
|
-
function parseSourceString(value) {
|
|
3246
|
-
if (value.startsWith('"'))
|
|
3247
|
-
return parseStringLiteral(value);
|
|
3248
|
-
if (!value.startsWith("'") || !value.endsWith("'"))
|
|
3249
|
-
throw new Error("Screenshot strings must use quotes");
|
|
3250
|
-
const inner = value.slice(1, -1);
|
|
3251
|
-
let parsed = "";
|
|
3252
|
-
for (let index = 0; index < inner.length; index++) {
|
|
3253
|
-
const character = inner[index];
|
|
3254
|
-
if (character !== "\\") {
|
|
3255
|
-
parsed += character;
|
|
3256
|
-
continue;
|
|
3257
|
-
}
|
|
3258
|
-
const next = inner[++index];
|
|
3259
|
-
if (next === void 0)
|
|
3260
|
-
throw new Error("Screenshot string contains an incomplete escape");
|
|
3261
|
-
parsed += next === "n" ? "\n" : next === "r" ? "\r" : next === "t" ? " " : next;
|
|
3262
|
-
}
|
|
3263
|
-
return parsed;
|
|
3264
|
-
}
|
|
3265
|
-
async function captureRequestedScreenshot(page, source, testCaseId) {
|
|
3266
|
-
const options = parseScreenshotOptions(source);
|
|
3267
|
-
const image = await page.screenshot({
|
|
3268
|
-
type: options.type,
|
|
3269
|
-
fullPage: options.fullPage,
|
|
3270
|
-
...options.type === "jpeg" && options.quality ? { quality: options.quality } : {}
|
|
3271
|
-
});
|
|
3272
|
-
const extension = options.type === "jpeg" ? "jpg" : "png";
|
|
3273
|
-
const requestedName = options.path?.split(/[\\/]/).pop()?.replace(/\.[^.]+$/, "");
|
|
3274
|
-
const safeName = (requestedName || `${testCaseId}-${Date.now()}`).replace(/[^\p{L}\p{N}._-]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 100);
|
|
3275
|
-
return {
|
|
3276
|
-
name: `${safeName || `screenshot-${Date.now()}`}.${extension}`,
|
|
3277
|
-
dataUrl: `data:image/${options.type};base64,${image.toString("base64")}`,
|
|
3278
|
-
capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3279
|
-
testCaseId,
|
|
3280
|
-
status: "passed"
|
|
3281
|
-
};
|
|
3282
|
-
}
|
|
3283
|
-
var STRING_LITERAL = `(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*')`;
|
|
3284
|
-
function parseStringLiteral(value) {
|
|
3285
|
-
const quote = value[0];
|
|
3286
|
-
if (quote !== '"' && quote !== "'")
|
|
3287
|
-
throw new Error("Edited Playwright arguments must be quoted strings");
|
|
3288
|
-
const asJson = quote === '"' ? value : `"${value.slice(1, -1).replace(/\\'/g, "'").replace(/"/g, '\\"')}"`;
|
|
3289
|
-
let parsed;
|
|
3290
|
-
try {
|
|
3291
|
-
parsed = JSON.parse(asJson);
|
|
3292
|
-
} catch {
|
|
3293
|
-
throw new Error("Edited Playwright arguments must be quoted strings");
|
|
3294
|
-
}
|
|
3295
|
-
if (typeof parsed !== "string")
|
|
3296
|
-
throw new Error("Edited Playwright arguments must be strings");
|
|
3297
|
-
return parsed;
|
|
3298
|
-
}
|
|
3299
|
-
var INDEX_SUFFIX = /\.(first|last|nth)\((\d{0,4})\)$/;
|
|
3300
|
-
function applyIndexSuffix(expression) {
|
|
3301
|
-
const match = expression.match(INDEX_SUFFIX);
|
|
3302
|
-
if (!match)
|
|
3303
|
-
return { base: expression };
|
|
3304
|
-
const base = expression.slice(0, match.index);
|
|
3305
|
-
if (match[1] === "first")
|
|
3306
|
-
return { base, pick: (target) => target.first() };
|
|
3307
|
-
if (match[1] === "last")
|
|
3308
|
-
return { base, pick: (target) => target.last() };
|
|
3309
|
-
if (!match[2])
|
|
3310
|
-
return { base: expression };
|
|
3311
|
-
const index = Number(match[2]);
|
|
3312
|
-
return { base, pick: (target) => target.nth(index) };
|
|
3313
|
-
}
|
|
3314
|
-
function parseEditedLocator(page, expression) {
|
|
3315
|
-
debugLocator("EditedSource", { expression });
|
|
3316
|
-
const { base, pick } = applyIndexSuffix(expression);
|
|
3317
|
-
const resolved = resolveLocatorExpression(page, base);
|
|
3318
|
-
return pick ? { locator: pick(resolved.locator), label: resolved.label } : resolved;
|
|
3319
|
-
}
|
|
3320
|
-
function resolveLocatorExpression(page, expression) {
|
|
3321
|
-
const roleMatch = expression.match(new RegExp(`^page\\.getByRole\\((${STRING_LITERAL}),\\s*\\{\\s*name:\\s*(${STRING_LITERAL})\\s*\\}\\)$`));
|
|
3322
|
-
if (roleMatch) {
|
|
3323
|
-
const role = parseStringLiteral(roleMatch[1]);
|
|
3324
|
-
const name = parseStringLiteral(roleMatch[2]);
|
|
3325
|
-
return { locator: page.getByRole(role, { name }), label: name };
|
|
3326
|
-
}
|
|
3327
|
-
const roleOnlyMatch = expression.match(new RegExp(`^page\\.getByRole\\((${STRING_LITERAL})\\)$`));
|
|
3328
|
-
if (roleOnlyMatch) {
|
|
3329
|
-
const role = parseStringLiteral(roleOnlyMatch[1]);
|
|
3330
|
-
return { locator: page.getByRole(role), label: role };
|
|
3331
|
-
}
|
|
3332
|
-
for (const [method, create] of [
|
|
3333
|
-
["getByLabel", (value) => page.getByLabel(value)],
|
|
3334
|
-
["getByPlaceholder", (value) => page.getByPlaceholder(value)],
|
|
3335
|
-
["getByText", (value) => page.getByText(value)],
|
|
3336
|
-
["getByTestId", (value) => page.getByTestId(value)],
|
|
3337
|
-
["locator", (value) => page.locator(value)]
|
|
3338
|
-
]) {
|
|
3339
|
-
const match = expression.match(new RegExp(`^page\\.${method}\\((${STRING_LITERAL})\\)$`));
|
|
3340
|
-
if (match) {
|
|
3341
|
-
const value = parseStringLiteral(match[1]);
|
|
3342
|
-
return { locator: create(value), label: value };
|
|
3343
|
-
}
|
|
3344
|
-
}
|
|
3345
|
-
throw new Error(`Unsupported locator: ${expression.slice(0, 120)}
|
|
3346
|
-
Expected page.getByRole("button", { name: "Login" }), page.getByLabel/getByPlaceholder/getByText/getByTestId("\u2026") or page.locator("css"), optionally followed by .first(), .last() or .nth(n).`);
|
|
3347
|
-
}
|
|
3348
|
-
async function executeStep(page, step, addLog, blockedKeywords, secrets) {
|
|
3349
|
-
switch (step.type) {
|
|
3350
|
-
case "navigate":
|
|
3351
|
-
const checked = checkTargetUrl(step.url, config.urlPolicy);
|
|
3352
|
-
if (!checked.ok)
|
|
3353
|
-
throw new Error(checked.message);
|
|
3354
|
-
addLog("info", "Target URL found: " + redactUrl(checked.url.toString()));
|
|
3355
|
-
addLog("info", "\u2192 Navigating to " + redactUrl(checked.url.toString()));
|
|
3356
|
-
await page.goto(checked.url.toString(), { waitUntil: "domcontentloaded", timeout: STEP_TIMEOUT_MS });
|
|
3357
|
-
addLog("pass", "Page ready: " + (new URL(page.url()).pathname || "/"));
|
|
3358
|
-
addLog("info", "Continuing with the next test step");
|
|
3359
|
-
return;
|
|
3360
|
-
case "click": {
|
|
3361
|
-
const name = step.target.name ?? step.target.text ?? step.target.cssSelector ?? "target";
|
|
3362
|
-
const target = locator(page, step.target);
|
|
3363
|
-
await ensureSafeClick(target, name, blockedKeywords);
|
|
3364
|
-
addLog("info", "Control found: " + name);
|
|
3365
|
-
addLog("info", "\u2192 Clicking " + name);
|
|
3366
|
-
await target.click();
|
|
3367
|
-
addLog("pass", "Action completed: " + name);
|
|
3368
|
-
return;
|
|
3369
|
-
}
|
|
3370
|
-
case "fill": {
|
|
3371
|
-
const name = step.target.name ?? step.target.label ?? "field";
|
|
3372
|
-
const value = resolveSecret(step.value, secrets);
|
|
3373
|
-
addLog("info", "Input found: " + name);
|
|
3374
|
-
addLog("info", "\u2192 Filling " + name);
|
|
3375
|
-
await locator(page, step.target).fill(value);
|
|
3376
|
-
addLog("pass", "Input ready: " + name);
|
|
3377
|
-
return;
|
|
3378
|
-
}
|
|
3379
|
-
case "select":
|
|
3380
|
-
addLog("info", "Dropdown found: " + (step.target.name ?? step.target.label ?? "select"));
|
|
3381
|
-
await locator(page, step.target).selectOption(step.option);
|
|
3382
|
-
addLog("pass", "Selected option: " + step.option);
|
|
3383
|
-
return;
|
|
3384
|
-
case "assertVisible":
|
|
3385
|
-
await locator(page, step.target).isVisible().then((visible) => {
|
|
3386
|
-
if (!visible)
|
|
3387
|
-
throw new Error("Expected element is not visible");
|
|
3388
|
-
addLog("pass", "Element visible: " + (step.target.name ?? step.target.label ?? "target"));
|
|
3389
|
-
});
|
|
3390
|
-
return;
|
|
3391
|
-
case "assertText": {
|
|
3392
|
-
const bodyText = await page.locator("body").innerText();
|
|
3393
|
-
if (!bodyText.includes(step.text))
|
|
3394
|
-
throw new Error("Expected text was not found: " + step.text);
|
|
3395
|
-
addLog("pass", 'Assertion passed: page contains "' + step.text + '"');
|
|
3396
|
-
return;
|
|
3397
3541
|
}
|
|
3398
|
-
case "assertUrl":
|
|
3399
|
-
if (!page.url().includes(step.urlContains))
|
|
3400
|
-
throw new Error("URL does not contain " + step.urlContains);
|
|
3401
|
-
addLog("pass", "URL assertion passed: " + redactUrl(page.url()));
|
|
3402
|
-
return;
|
|
3403
|
-
case "manual":
|
|
3404
|
-
throw new Error("Manual step requires Tester review");
|
|
3405
|
-
}
|
|
3406
|
-
}
|
|
3407
|
-
function resolveSecret(value, projectSecrets) {
|
|
3408
|
-
const secrets = {
|
|
3409
|
-
"{{TEST_EMAIL}}": projectSecrets?.email ?? process.env.LAZYSCOUT_TEST_EMAIL,
|
|
3410
|
-
"{{TEST_USERNAME}}": projectSecrets?.username ?? process.env.LAZYSCOUT_TEST_USERNAME,
|
|
3411
|
-
"{{TEST_PASSWORD}}": projectSecrets?.password ?? process.env.LAZYSCOUT_TEST_PASSWORD,
|
|
3412
|
-
"{{API_TOKEN}}": projectSecrets?.apiToken ?? process.env.LAZYSCOUT_API_TOKEN
|
|
3413
|
-
};
|
|
3414
|
-
const secret = secrets[value];
|
|
3415
|
-
if (secret === void 0 && value in secrets)
|
|
3416
|
-
throw new Error("Required secret is not configured for " + value);
|
|
3417
|
-
return secret ?? value;
|
|
3418
|
-
}
|
|
3419
|
-
function locator(page, target) {
|
|
3420
|
-
debugLocator("Resolver", {
|
|
3421
|
-
strategy: target.role && target.name ? "role" : target.label ? "label" : target.placeholder ? "placeholder" : target.text ? "text" : "css",
|
|
3422
|
-
role: target.role,
|
|
3423
|
-
name: target.name,
|
|
3424
|
-
cssSelector: target.cssSelector
|
|
3425
3542
|
});
|
|
3426
|
-
if (target.role && target.name)
|
|
3427
|
-
return page.getByRole(target.role, { name: target.name });
|
|
3428
|
-
if (target.label)
|
|
3429
|
-
return page.getByLabel(target.label);
|
|
3430
|
-
if (target.placeholder)
|
|
3431
|
-
return page.getByPlaceholder(target.placeholder);
|
|
3432
|
-
if (target.text)
|
|
3433
|
-
return page.getByText(target.text);
|
|
3434
|
-
return page.locator(target.cssSelector ?? "");
|
|
3435
|
-
}
|
|
3436
|
-
function debugLocator(stage, detail) {
|
|
3437
|
-
if (!process.env.LAZYSCOUT_DEBUG_LOCATOR)
|
|
3438
|
-
return;
|
|
3439
|
-
const safe = Object.fromEntries(Object.entries(detail).filter(([, value]) => value !== void 0).map(([key, value]) => [key, typeof value === "string" ? redactSensitiveText(value) : value]));
|
|
3440
|
-
console.log(`[LazyScout:${stage}]`, safe);
|
|
3441
|
-
}
|
|
3442
|
-
async function ensureSafeClick(target, fallbackLabel, blockedKeywords) {
|
|
3443
|
-
const labels = await Promise.all([
|
|
3444
|
-
target.getAttribute("aria-label").catch(() => null),
|
|
3445
|
-
target.getAttribute("title").catch(() => null),
|
|
3446
|
-
target.getAttribute("name").catch(() => null),
|
|
3447
|
-
target.getAttribute("id").catch(() => null),
|
|
3448
|
-
target.innerText().catch(() => "")
|
|
3449
|
-
]);
|
|
3450
|
-
const values = [fallbackLabel, ...labels.map((value) => value ?? void 0)];
|
|
3451
|
-
if (isUnsafeAutoClick(...values))
|
|
3452
|
-
throw new Error(`Blocked by mandatory safety policy: ${fallbackLabel}`);
|
|
3453
|
-
if (isBlockedLabel(blockedKeywords, ...values)) {
|
|
3454
|
-
throw new Error(`Blocked by the Project click filter: ${fallbackLabel}`);
|
|
3455
|
-
}
|
|
3456
3543
|
}
|
|
3457
3544
|
|
|
3458
3545
|
// ../server/dist/routes/apiCheckRun.js
|
|
@@ -3594,9 +3681,9 @@ function registerLoadTestRoute(app) {
|
|
|
3594
3681
|
}
|
|
3595
3682
|
|
|
3596
3683
|
// ../server/dist/routes/versions.js
|
|
3597
|
-
import { spawn } from "node:child_process";
|
|
3684
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
3598
3685
|
import { access } from "node:fs/promises";
|
|
3599
|
-
import { dirname as
|
|
3686
|
+
import { dirname as dirname3, join as join3 } from "node:path";
|
|
3600
3687
|
var PACKAGE_NAME = "lazyscout";
|
|
3601
3688
|
var REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}`;
|
|
3602
3689
|
var VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
@@ -3642,8 +3729,8 @@ async function fetchPublishedVersions(force = false) {
|
|
|
3642
3729
|
async function findNpmCli() {
|
|
3643
3730
|
const candidates = [
|
|
3644
3731
|
process.env.npm_execpath,
|
|
3645
|
-
|
|
3646
|
-
process.env.APPDATA ?
|
|
3732
|
+
join3(dirname3(process.execPath), "node_modules", "npm", "bin", "npm-cli.js"),
|
|
3733
|
+
process.env.APPDATA ? join3(process.env.APPDATA, "npm", "node_modules", "npm", "bin", "npm-cli.js") : void 0,
|
|
3647
3734
|
"/usr/lib/node_modules/npm/bin/npm-cli.js",
|
|
3648
3735
|
"/usr/local/lib/node_modules/npm/bin/npm-cli.js"
|
|
3649
3736
|
].filter((value) => Boolean(value?.endsWith(".js")));
|
|
@@ -3660,7 +3747,7 @@ async function runNpmInstall(version) {
|
|
|
3660
3747
|
const npmCli = await findNpmCli();
|
|
3661
3748
|
return new Promise((resolve3, reject) => {
|
|
3662
3749
|
const commandArgs = [npmCli, "install", "--global", `${PACKAGE_NAME}@${version}`, "--no-audit", "--no-fund"];
|
|
3663
|
-
const child =
|
|
3750
|
+
const child = spawn2(process.execPath, commandArgs, {
|
|
3664
3751
|
windowsHide: true,
|
|
3665
3752
|
stdio: ["ignore", "pipe", "pipe"]
|
|
3666
3753
|
});
|
|
@@ -3789,6 +3876,11 @@ function registerWorkspaceRoutes(app, root) {
|
|
|
3789
3876
|
await page.goto(body.url, { waitUntil: "domcontentloaded" });
|
|
3790
3877
|
return reply.send({ opened: true });
|
|
3791
3878
|
});
|
|
3879
|
+
app.get("/api/workspace/projects/:projectId/auth-session/status", async (request) => browserProfileStatus(root, request.params.projectId));
|
|
3880
|
+
app.delete("/api/workspace/projects/:projectId/auth-session", async (request, reply) => {
|
|
3881
|
+
await clearBrowserProfile(root, request.params.projectId);
|
|
3882
|
+
return reply.send({ cleared: true });
|
|
3883
|
+
});
|
|
3792
3884
|
app.get("/api/workspace/projects/:projectId/screenshots", async (request) => readScreenshots(root, request.params.projectId));
|
|
3793
3885
|
app.post("/api/workspace/projects/:projectId/screenshots", async (request) => saveScreenshot(root, request.params.projectId, request.body));
|
|
3794
3886
|
app.get("/api/workspace/projects/:projectId/screenshots/:name", async (request, reply) => {
|
|
@@ -3813,6 +3905,14 @@ function registerWorkspaceRoutes(app, root) {
|
|
|
3813
3905
|
return reply.send({ deleted: true });
|
|
3814
3906
|
});
|
|
3815
3907
|
app.get("/api/workspace/projects/:projectId/automation", async (request) => readAutomation(root, request.params.projectId));
|
|
3908
|
+
app.get("/api/workspace/projects/:projectId/guided-flows", async (request) => readGuidedFlows(root, request.params.projectId));
|
|
3909
|
+
app.put("/api/workspace/projects/:projectId/guided-flows", async (request, reply) => {
|
|
3910
|
+
const body = request.body;
|
|
3911
|
+
if (!Array.isArray(body?.flows))
|
|
3912
|
+
return reply.status(400).send({ error: { code: "invalid-guided-flows", message: "Guided Flow list is required." } });
|
|
3913
|
+
await saveGuidedFlows(root, request.params.projectId, body.flows);
|
|
3914
|
+
return reply.send({ saved: true });
|
|
3915
|
+
});
|
|
3816
3916
|
app.put("/api/workspace/projects/:projectId/automation", async (request, reply) => {
|
|
3817
3917
|
await saveAutomation(root, request.params.projectId, request.body);
|
|
3818
3918
|
return reply.send({ saved: true });
|
|
@@ -3947,6 +4047,105 @@ function registerRecorderRoutes(app, workspaceRoot, options = {}) {
|
|
|
3947
4047
|
});
|
|
3948
4048
|
}
|
|
3949
4049
|
|
|
4050
|
+
// ../server/dist/routes/guidedFlowRun.js
|
|
4051
|
+
var activeRuns2 = /* @__PURE__ */ new Map();
|
|
4052
|
+
function registerGuidedFlowRunRoute(app, workspaceRoot) {
|
|
4053
|
+
app.post("/api/guided-flows/stop", async (request, reply) => {
|
|
4054
|
+
const runId = request.body?.runId;
|
|
4055
|
+
const active = runId ? activeRuns2.get(runId) : void 0;
|
|
4056
|
+
if (!active)
|
|
4057
|
+
return reply.send({ stopped: false });
|
|
4058
|
+
active.stopped = true;
|
|
4059
|
+
await active.close?.().catch(() => void 0);
|
|
4060
|
+
return reply.send({ stopped: true });
|
|
4061
|
+
});
|
|
4062
|
+
app.post("/api/guided-flows/run", async (request, reply) => {
|
|
4063
|
+
const body = request.body;
|
|
4064
|
+
if (!body?.flow?.id || !body.flow.baseUrl || !Array.isArray(body.flow.steps) || body.flow.steps.length === 0)
|
|
4065
|
+
return reply.status(400).send({ error: { code: "invalid-guided-flow", message: "A Guided Flow with steps is required." } });
|
|
4066
|
+
const testCase = flowToTestCase(body.flow);
|
|
4067
|
+
const runId = body.runId || crypto.randomUUID();
|
|
4068
|
+
const logs = [];
|
|
4069
|
+
const secretValues = [
|
|
4070
|
+
body.secrets?.email,
|
|
4071
|
+
body.secrets?.username,
|
|
4072
|
+
body.secrets?.password,
|
|
4073
|
+
body.secrets?.apiToken,
|
|
4074
|
+
...body.secrets?.variables ? Object.values(body.secrets.variables) : []
|
|
4075
|
+
].filter((value) => Boolean(value));
|
|
4076
|
+
const addLog = (level, message, durationMs) => {
|
|
4077
|
+
logs.push({
|
|
4078
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4079
|
+
level,
|
|
4080
|
+
message: redactSensitiveText(message, secretValues),
|
|
4081
|
+
...durationMs === void 0 ? {} : { durationMs }
|
|
4082
|
+
});
|
|
4083
|
+
};
|
|
4084
|
+
const active = { stopped: false };
|
|
4085
|
+
activeRuns2.set(runId, active);
|
|
4086
|
+
addLog("info", `[Flow] Start: ${body.flow.name}`);
|
|
4087
|
+
body.flow.steps.forEach((step, index) => addLog("info", `[${index + 1}/${body.flow.steps.length}] ${describeStep(stepToTestStep(body.flow, step))}`));
|
|
4088
|
+
const unsafeStep = body.flow.steps.find((step) => step.type === "click" && isUnsafeAutoClick(step.target.name, step.target.label, step.target.text));
|
|
4089
|
+
if (unsafeStep) {
|
|
4090
|
+
addLog("warn", "Blocked by the LazyScout safety policy");
|
|
4091
|
+
const response = {
|
|
4092
|
+
status: "blocked",
|
|
4093
|
+
framework: "playwright",
|
|
4094
|
+
runId,
|
|
4095
|
+
logs,
|
|
4096
|
+
stepStatuses: body.flow.steps.map((step) => ({ id: step.id, status: "pending" }))
|
|
4097
|
+
};
|
|
4098
|
+
activeRuns2.delete(runId);
|
|
4099
|
+
return reply.send(response);
|
|
4100
|
+
}
|
|
4101
|
+
try {
|
|
4102
|
+
const result = await runPlaywrightCli({
|
|
4103
|
+
testCase,
|
|
4104
|
+
testCaseId: testCase.id,
|
|
4105
|
+
source: generatePlaywrightFromFlow(body.flow),
|
|
4106
|
+
secrets: body.secrets,
|
|
4107
|
+
secretValues,
|
|
4108
|
+
profileDirectory: body.projectId ? await browserProfileDirectory(workspaceRoot, body.projectId) : void 0,
|
|
4109
|
+
addLog,
|
|
4110
|
+
onProcess: (child) => {
|
|
4111
|
+
active.close = async () => {
|
|
4112
|
+
if (child.pid && process.platform === "win32") {
|
|
4113
|
+
const killer = (await import("node:child_process")).spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
4114
|
+
windowsHide: true,
|
|
4115
|
+
stdio: "ignore"
|
|
4116
|
+
});
|
|
4117
|
+
await new Promise((resolve3) => killer.once("close", () => resolve3()));
|
|
4118
|
+
} else
|
|
4119
|
+
child.kill("SIGTERM");
|
|
4120
|
+
};
|
|
4121
|
+
}
|
|
4122
|
+
});
|
|
4123
|
+
const stepStatuses = body.flow.steps.map((_, index) => ({
|
|
4124
|
+
id: body.flow.steps[index].id,
|
|
4125
|
+
status: result.status === "passed" ? "passed" : index === body.flow.steps.length - 1 ? "failed" : "pending"
|
|
4126
|
+
}));
|
|
4127
|
+
if (body.projectId)
|
|
4128
|
+
await saveRunLog(workspaceRoot, body.projectId, testCase.id, result.status, logs).catch(() => void 0);
|
|
4129
|
+
return reply.send({ ...result, logs, runId, stepStatuses });
|
|
4130
|
+
} catch (error) {
|
|
4131
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4132
|
+
addLog("fail", message);
|
|
4133
|
+
return reply.status(400).send({
|
|
4134
|
+
error: {
|
|
4135
|
+
code: message.includes("Required test variable") ? "missing-test-variable" : "guided-flow-run-failed",
|
|
4136
|
+
message,
|
|
4137
|
+
hint: message.includes("Required test variable") ? "Open Project settings and configure the referenced test variable before running this Flow." : "Review the Guided Flow steps and CLI log, then run it again."
|
|
4138
|
+
}
|
|
4139
|
+
});
|
|
4140
|
+
} finally {
|
|
4141
|
+
activeRuns2.delete(runId);
|
|
4142
|
+
}
|
|
4143
|
+
});
|
|
4144
|
+
}
|
|
4145
|
+
function stepToTestStep(flow, step) {
|
|
4146
|
+
return flowToTestCase({ ...flow, steps: [step] }).steps[0];
|
|
4147
|
+
}
|
|
4148
|
+
|
|
3950
4149
|
// ../server/dist/app.js
|
|
3951
4150
|
function buildApp(options = {}) {
|
|
3952
4151
|
const app = Fastify({
|
|
@@ -3965,6 +4164,7 @@ function buildApp(options = {}) {
|
|
|
3965
4164
|
registerVersionRoutes(app, appVersion);
|
|
3966
4165
|
registerWorkspaceRoutes(app, workspaceRoot);
|
|
3967
4166
|
registerRecorderRoutes(app, workspaceRoot);
|
|
4167
|
+
registerGuidedFlowRunRoute(app, workspaceRoot);
|
|
3968
4168
|
if (options.staticDir) {
|
|
3969
4169
|
app.register(fastifyStatic, { root: options.staticDir });
|
|
3970
4170
|
app.setNotFoundHandler(async (request, reply) => {
|
|
@@ -3980,11 +4180,11 @@ function buildApp(options = {}) {
|
|
|
3980
4180
|
}
|
|
3981
4181
|
|
|
3982
4182
|
// src/openInBrowser.ts
|
|
3983
|
-
import { spawn as
|
|
4183
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
3984
4184
|
async function openInBrowser(url) {
|
|
3985
4185
|
const [command, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
|
|
3986
4186
|
try {
|
|
3987
|
-
const child =
|
|
4187
|
+
const child = spawn3(command, args, { stdio: "ignore", detached: true });
|
|
3988
4188
|
child.on("error", () => void 0);
|
|
3989
4189
|
child.unref();
|
|
3990
4190
|
} catch {
|
|
@@ -3992,11 +4192,11 @@ async function openInBrowser(url) {
|
|
|
3992
4192
|
}
|
|
3993
4193
|
|
|
3994
4194
|
// src/version.ts
|
|
3995
|
-
var VERSION = true ? "0.3.
|
|
4195
|
+
var VERSION = true ? "0.3.9" : "0.0.0-dev";
|
|
3996
4196
|
|
|
3997
4197
|
// src/commands/serve.ts
|
|
3998
4198
|
var DEFAULT_PORT = 4321;
|
|
3999
|
-
var WEB_DIR =
|
|
4199
|
+
var WEB_DIR = join4(dirname4(fileURLToPath(import.meta.url)), "web");
|
|
4000
4200
|
async function runServe(options) {
|
|
4001
4201
|
const workspaceRoot = resolveWorkspaceRoot(options.workspace);
|
|
4002
4202
|
await ensureWorkspace(workspaceRoot);
|