lazyscout 0.3.8 → 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":
@@ -1140,19 +1144,19 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1140
1144
  async function executeWithRetry(page, candidate, currentUrl, entryFlow, maxRetries) {
1141
1145
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
1142
1146
  try {
1143
- let locator2;
1147
+ let locator3;
1144
1148
  if (candidate.locator.cssSelector) {
1145
- locator2 = page.locator(candidate.locator.cssSelector).first();
1149
+ locator3 = page.locator(candidate.locator.cssSelector).first();
1146
1150
  } else if (candidate.locator.role && candidate.locator.name) {
1147
- locator2 = page.getByRole(candidate.locator.role, {
1151
+ locator3 = page.getByRole(candidate.locator.role, {
1148
1152
  name: candidate.locator.name
1149
1153
  });
1150
1154
  } else if (candidate.locator.testId) {
1151
- locator2 = page.getByTestId(candidate.locator.testId);
1155
+ locator3 = page.getByTestId(candidate.locator.testId);
1152
1156
  } else {
1153
1157
  return { success: false };
1154
1158
  }
1155
- await locator2.click({ timeout: legacyOptions.actionTimeoutMs });
1159
+ await locator3.click({ timeout: legacyOptions.actionTimeoutMs });
1156
1160
  await page.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
1157
1161
  const newUrl = page.url();
1158
1162
  return { success: true, newUrl };
@@ -1874,10 +1878,10 @@ function toTargetRef(element) {
1874
1878
  contextTestId: element.contextTestId
1875
1879
  } : void 0;
1876
1880
  if (element.accessibleName) {
1877
- return { role: element.role, name: element.accessibleName, ...disambiguation };
1881
+ return { role: element.role, name: element.accessibleName, cssSelector: element.cssSelector, ...disambiguation };
1878
1882
  }
1879
1883
  if (element.placeholder) {
1880
- return { role: element.role, placeholder: element.placeholder, ...disambiguation };
1884
+ return { role: element.role, placeholder: element.placeholder, cssSelector: element.cssSelector, ...disambiguation };
1881
1885
  }
1882
1886
  if (element.testId)
1883
1887
  return { testId: element.testId, ...disambiguation };
@@ -2214,6 +2218,10 @@ function translateStep(step) {
2214
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"}`;
2215
2219
  case "select":
2216
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}`;
2217
2225
  case "assertVisible":
2218
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`;
2219
2227
  case "assertText":
@@ -2384,6 +2392,167 @@ function exportTestCasesToCsv(testCases, testData = []) {
2384
2392
  return UTF8_BOM + lines.join("\r\n") + "\r\n";
2385
2393
  }
2386
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
+
2387
2556
  // src/commands/scan.ts
2388
2557
  async function runScan(options) {
2389
2558
  console.log(`checking scan ${redactUrl(options.url)} ...`);
@@ -2452,7 +2621,7 @@ Saved CSV: ${csvPath}`);
2452
2621
  }
2453
2622
 
2454
2623
  // src/commands/serve.ts
2455
- import { dirname as dirname3, join as join3 } from "node:path";
2624
+ import { dirname as dirname4, join as join4 } from "node:path";
2456
2625
  import { fileURLToPath } from "node:url";
2457
2626
 
2458
2627
  // ../server/dist/app.js
@@ -2589,11 +2758,11 @@ async function saveScreenshot(root, projectId, screenshot) {
2589
2758
  });
2590
2759
  }
2591
2760
  async function deleteScreenshot(root, projectId, name) {
2592
- const safeName = assertFileName(name);
2761
+ const safeName2 = assertFileName(name);
2593
2762
  const directory = join(await ensureProject(root, projectId), "screenshots");
2594
- await rm(join(directory, safeName), { force: true });
2763
+ await rm(join(directory, safeName2), { force: true });
2595
2764
  const current = await readScreenshots(root, projectId);
2596
- await writeJson(join(directory, "index.json"), current.filter((item) => item.name !== safeName));
2765
+ await writeJson(join(directory, "index.json"), current.filter((item) => item.name !== safeName2));
2597
2766
  }
2598
2767
  async function screenshotFile(root, projectId, name) {
2599
2768
  return readFile(join(await ensureProject(root, projectId), "screenshots", assertFileName(name)));
@@ -2650,6 +2819,20 @@ async function saveRunLog(root, projectId, testCaseId, status, logs) {
2650
2819
  const name = `${timestamp}-${safeFileName(testCaseId, "test-case")}.json`;
2651
2820
  await writeJson(join(directory, name), { testCaseId, status, createdAt: (/* @__PURE__ */ new Date()).toISOString(), logs });
2652
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
+ }
2653
2836
  async function saveReport(root, projectId, name, html) {
2654
2837
  if (typeof html !== "string" || html.length > 2e6)
2655
2838
  throw new Error("Report exceeds the 2 MB limit");
@@ -3030,6 +3213,205 @@ function registerExportCsvRoute(app) {
3030
3213
  });
3031
3214
  }
3032
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
+
3033
3415
  // ../server/dist/routes/automationRun.js
3034
3416
  var MAX_STEPS = 100;
3035
3417
  var MAX_LOGS = 250;
@@ -3052,497 +3434,112 @@ function registerAutomationRunRoute(app, workspaceRoot) {
3052
3434
  const body = request.body;
3053
3435
  const testCase = body.testCase;
3054
3436
  const secrets = body.secrets;
3055
- const blockedKeywords = normalizeBlockedKeywords(body.blockedKeywords);
3056
3437
  const framework = body.framework ?? "playwright";
3057
3438
  const runId = body.runId || crypto.randomUUID();
3439
+ const blockedKeywords = normalizeBlockedKeywords(body.blockedKeywords);
3058
3440
  if (!testCase || !Array.isArray(testCase.steps))
3059
3441
  return reply.status(400).send({ error: { code: "invalid-test-case", message: "The requested Test Case was not found." } });
3060
3442
  if (testCase.steps.length > MAX_STEPS)
3061
- return reply.status(400).send({ error: { code: "run-limit", message: "Step count exceeds the limit of " + MAX_STEPS } });
3443
+ return reply.status(400).send({ error: { code: "run-limit", message: `Step count exceeds the limit of ${MAX_STEPS}` } });
3062
3444
  if (typeof body.code === "string" && body.code.length > MAX_SOURCE_LENGTH)
3063
3445
  return reply.status(400).send({ error: { code: "source-limit", message: "Generated source exceeds the size limit." } });
3064
3446
  const logs = [];
3065
3447
  const secretValues = [
3066
- secrets?.email,
3067
- secrets?.username,
3068
- secrets?.password,
3069
- secrets?.apiToken,
3448
+ body.secrets?.email,
3449
+ body.secrets?.username,
3450
+ body.secrets?.password,
3451
+ body.secrets?.apiToken,
3070
3452
  process.env.LAZYSCOUT_TEST_EMAIL,
3071
3453
  process.env.LAZYSCOUT_TEST_USERNAME,
3072
3454
  process.env.LAZYSCOUT_TEST_PASSWORD,
3073
- process.env.LAZYSCOUT_API_TOKEN
3455
+ process.env.LAZYSCOUT_API_TOKEN,
3456
+ ...secrets?.variables ? Object.values(secrets.variables) : []
3074
3457
  ].filter((value) => Boolean(value));
3075
3458
  const addLog = (level, message, durationMs) => {
3076
- if (logs.length < MAX_LOGS)
3077
- logs.push({
3078
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3079
- level,
3080
- message: redactSensitiveText(message, secretValues),
3081
- ...durationMs === void 0 ? {} : { durationMs }
3082
- });
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
+ });
3083
3467
  };
3084
- const persistLog = async (runStatus) => {
3468
+ const persistLog = async (status) => {
3085
3469
  if (!body.projectId)
3086
3470
  return;
3087
- await saveRunLog(workspaceRoot, body.projectId, testCase.id, runStatus, logs).catch((error) => addLog("warn", `Could not save run log: ${error instanceof Error ? error.message : String(error)}`));
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)}`));
3088
3472
  };
3089
- const started = Date.now();
3090
- addLog("info", "$ lazyscout test --case " + testCase.id);
3091
- addLog("info", "Starting Playwright runner: " + testCase.title);
3092
- addLog("info", "Test budget: " + MAX_STEPS + " steps \xB7 " + STEP_TIMEOUT_MS / 1e3 + "s per action \xB7 " + MAX_LOGS + " log lines");
3093
- if (testCase.automationStatus === "manual") {
3094
- 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");
3095
3478
  await persistLog("blocked");
3096
3479
  return reply.send({ status: "blocked", framework, logs });
3097
3480
  }
3481
+ if (testCase.automationStatus === "manual") {
3482
+ addLog("info", "Manual Test Case accepted: running the provided Playwright source or Steps");
3483
+ }
3098
3484
  if (framework === "cypress") {
3099
3485
  addLog("warn", "Cypress code generation is available; local runner uses Playwright only.");
3100
3486
  await persistLog("unsupported");
3101
3487
  return reply.send({ status: "unsupported", framework, logs });
3102
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
+ }
3103
3496
  const active = { stopped: false };
3104
3497
  activeRuns.set(runId, active);
3105
- let close;
3106
- let page;
3107
- const capturedScreenshots = [];
3108
3498
  try {
3109
- const profile = body.projectId ? await browserProfileDirectory(workspaceRoot, body.projectId) : void 0;
3110
- const launched = await launchBrowser({ userDataDir: profile });
3111
- close = launched.close;
3112
- active.close = close;
3113
- if (active.stopped)
3114
- throw new Error("Run stopped by user");
3115
- const { context } = launched;
3116
- context.setDefaultTimeout(STEP_TIMEOUT_MS);
3117
- page = await context.newPage();
3118
- if (typeof body.code === "string" && body.code.trim()) {
3119
- addLog("info", "Running edited automation source");
3120
- await executeEditedCode(page, body.code, testCase.id, capturedScreenshots, addLog, blockedKeywords, secrets);
3121
- if (active.stopped)
3122
- throw new Error("Run stopped by user");
3123
- addLog("pass", "\u2713 edited source completed");
3124
- } else
3125
- for (const step of testCase.steps) {
3126
- if (active.stopped)
3127
- throw new Error("Run stopped by user");
3128
- const stepStarted = Date.now();
3129
- await executeStep(page, step, addLog, blockedKeywords, secrets);
3130
- if (active.stopped)
3131
- throw new Error("Run stopped by user");
3132
- 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
+ };
3133
3518
  }
3134
- addLog("pass", `Completed ${testCase.id}`, Date.now() - started);
3135
- const screenshots = withScreenshotStatus(capturedScreenshots, "passed");
3136
- await persistLog("passed");
3519
+ });
3520
+ await persistLog(result.status);
3137
3521
  return reply.send({
3138
- status: "passed",
3522
+ status: result.status,
3139
3523
  framework,
3140
3524
  logs,
3141
- screenshots,
3142
- screenshot: screenshots.at(-1)
3525
+ ...result.error ? { error: redactCliError(result.error, secretValues) } : {},
3526
+ screenshots: result.screenshots,
3527
+ screenshot: result.screenshots.at(-1)
3143
3528
  });
3144
3529
  } catch (error) {
3145
- const message = redactSensitiveText(error instanceof Error ? error.message : String(error), secretValues);
3146
- debugLocator("StepFailed", { testCaseId: testCase.id, url: page?.url(), error: message });
3530
+ const message = redactCliError(error, secretValues);
3147
3531
  if (active.stopped) {
3148
- addLog("warn", "Run stopped by user", Date.now() - started);
3532
+ addLog("warn", "Run stopped by user");
3149
3533
  await persistLog("stopped");
3150
3534
  return reply.send({ status: "stopped", framework, logs });
3151
3535
  }
3152
- addLog("fail", `\u2715 ${message}`, Date.now() - started);
3153
- const screenshots = withScreenshotStatus(capturedScreenshots, "failed");
3536
+ addLog("fail", message);
3154
3537
  await persistLog("failed");
3155
- return reply.send({
3156
- status: "failed",
3157
- framework,
3158
- logs,
3159
- error: message,
3160
- screenshots,
3161
- screenshot: screenshots.at(-1)
3162
- });
3538
+ return reply.send({ status: "failed", framework, logs, error: message });
3163
3539
  } finally {
3164
3540
  activeRuns.delete(runId);
3165
- await close?.().catch(() => void 0);
3166
- }
3167
- });
3168
- }
3169
- function withScreenshotStatus(screenshots, status) {
3170
- return screenshots.map((screenshot) => ({ ...screenshot, status }));
3171
- }
3172
- async function executeEditedCode(page, source, testCaseId, capturedScreenshots, addLog, blockedKeywords, projectSecrets) {
3173
- const lines = source.split(/\r?\n/);
3174
- let executed = 0;
3175
- for (const rawLine of lines) {
3176
- const line = rawLine.trim().replace(/;$/, "");
3177
- if (!line || line.startsWith("import ") || line.startsWith("test(") || line === "})" || line === "});")
3178
- continue;
3179
- if (line.startsWith("//"))
3180
- continue;
3181
- if (++executed > MAX_STEPS)
3182
- throw new Error(`Edited source exceeds the ${MAX_STEPS} action limit`);
3183
- const gotoMatch = line.match(new RegExp(`^await page\\.goto\\((${STRING_LITERAL})\\)$`));
3184
- if (gotoMatch) {
3185
- const url = parseStringLiteral(gotoMatch[1]);
3186
- const checked = checkTargetUrl(url, config.urlPolicy);
3187
- if (!checked.ok)
3188
- throw new Error(checked.message);
3189
- addLog("info", `\u2192 Navigating to ${redactUrl(checked.url.toString())}`);
3190
- await page.goto(checked.url.toString(), { waitUntil: "domcontentloaded", timeout: STEP_TIMEOUT_MS });
3191
- continue;
3192
- }
3193
- const waitMatch = line.match(/^await page\.waitForTimeout\((\d{1,5})\)$/);
3194
- if (waitMatch) {
3195
- const waitMs = Math.min(Number(waitMatch[1]), 5e3);
3196
- addLog("info", `\u2192 Waiting ${waitMs}ms`);
3197
- await page.waitForTimeout(waitMs);
3198
- continue;
3199
- }
3200
- const screenshotMatch = line.match(/^await page\.screenshot\((.*)\)$/);
3201
- if (screenshotMatch) {
3202
- const screenshot = await captureRequestedScreenshot(page, screenshotMatch[1], testCaseId);
3203
- capturedScreenshots.push(screenshot);
3204
- addLog("pass", `Screenshot captured: ${screenshot.name}`);
3205
- continue;
3206
- }
3207
- const clickMatch = line.match(/^await (page\..+)\.click\(\)$/);
3208
- if (clickMatch) {
3209
- const target = parseEditedLocator(page, clickMatch[1]);
3210
- await ensureSafeClick(target.locator, target.label, blockedKeywords);
3211
- addLog("info", `\u2192 Clicking ${target.label}`);
3212
- await target.locator.click();
3213
- continue;
3214
- }
3215
- const fillMatch = line.match(new RegExp(`^await (page\\..+)\\.fill\\((${STRING_LITERAL})\\)$`));
3216
- if (fillMatch) {
3217
- const target = parseEditedLocator(page, fillMatch[1]);
3218
- addLog("info", `\u2192 Filling ${target.label}`);
3219
- await target.locator.fill(resolveSecret(parseStringLiteral(fillMatch[2]), projectSecrets));
3220
- continue;
3221
- }
3222
- const selectMatch = line.match(new RegExp(`^await (page\\..+)\\.selectOption\\((${STRING_LITERAL})\\)$`));
3223
- if (selectMatch) {
3224
- const target = parseEditedLocator(page, selectMatch[1]);
3225
- const option = parseStringLiteral(selectMatch[2]);
3226
- addLog("info", `\u2192 Selecting an option in ${target.label}`);
3227
- await target.locator.selectOption(option);
3228
- continue;
3229
- }
3230
- const visibleMatch = line.match(/^await expect\((page\..+)\)\.toBeVisible\(\)$/);
3231
- if (visibleMatch) {
3232
- const target = parseEditedLocator(page, visibleMatch[1]);
3233
- if (!await target.locator.isVisible())
3234
- throw new Error(`Expected ${target.label} to be visible`);
3235
- addLog("pass", `Element visible: ${target.label}`);
3236
- continue;
3237
- }
3238
- const textMatch = line.match(new RegExp(`^await expect\\((page(?:\\..+)?)\\)\\.toContainText\\((${STRING_LITERAL})\\)$`));
3239
- if (textMatch) {
3240
- const expected = parseStringLiteral(textMatch[2]);
3241
- const actual = textMatch[1] === "page" ? await page.locator("body").innerText() : await parseEditedLocator(page, textMatch[1]).locator.innerText();
3242
- if (!actual.includes(expected))
3243
- throw new Error(`Expected text was not found: ${expected}`);
3244
- addLog("pass", "Text assertion passed");
3245
- continue;
3246
- }
3247
- const urlMatch = line.match(new RegExp(`^await expect\\(page\\)\\.toHaveURL\\(new RegExp\\((${STRING_LITERAL})\\)\\)$`));
3248
- if (urlMatch) {
3249
- const expected = parseStringLiteral(urlMatch[1]);
3250
- if (!page.url().includes(expected))
3251
- throw new Error(`URL did not contain ${expected}`);
3252
- addLog("pass", `URL assertion passed: ${redactUrl(page.url())}`);
3253
- continue;
3254
- }
3255
- throw new Error(`Unsupported edited Playwright statement: ${line.slice(0, 120)}`);
3256
- }
3257
- if (executed === 0)
3258
- throw new Error("Edited source does not contain a supported Playwright action");
3259
- }
3260
- function parseScreenshotOptions(source) {
3261
- const value = source.trim();
3262
- if (!value)
3263
- return { fullPage: false, type: "png" };
3264
- const objectMatch = value.match(/^\{([\s\S]*)\}$/);
3265
- if (!objectMatch)
3266
- throw new Error("page.screenshot() accepts an options object only");
3267
- let path;
3268
- let fullPage = false;
3269
- let type;
3270
- let quality;
3271
- for (const entry of splitOptionList(objectMatch[1])) {
3272
- const separator = entry.indexOf(":");
3273
- if (separator < 1)
3274
- throw new Error(`Unsupported screenshot option: ${entry.slice(0, 80)}`);
3275
- const key = entry.slice(0, separator).trim();
3276
- const raw = entry.slice(separator + 1).trim();
3277
- if (key === "path")
3278
- path = parseSourceString(raw);
3279
- else if (key === "fullPage" && /^(true|false)$/.test(raw))
3280
- fullPage = raw === "true";
3281
- else if (key === "type") {
3282
- const parsedType = parseSourceString(raw);
3283
- if (parsedType !== "png" && parsedType !== "jpeg")
3284
- throw new Error("Screenshot type must be png or jpeg");
3285
- type = parsedType;
3286
- } else if (key === "quality" && /^\d{1,3}$/.test(raw))
3287
- quality = Math.min(100, Math.max(1, Number(raw)));
3288
- else
3289
- throw new Error(`Unsupported screenshot option: ${key.slice(0, 40)}`);
3290
- }
3291
- const inferredType = path && /\.jpe?g$/i.test(path) ? "jpeg" : "png";
3292
- return { path, fullPage, type: type ?? inferredType, quality };
3293
- }
3294
- function splitOptionList(value) {
3295
- const entries = [];
3296
- let current = "";
3297
- let quote = "";
3298
- let escaped = false;
3299
- for (const character of value) {
3300
- if (escaped) {
3301
- current += character;
3302
- escaped = false;
3303
- continue;
3304
- }
3305
- if (character === "\\") {
3306
- current += character;
3307
- escaped = true;
3308
- continue;
3309
- }
3310
- if (quote) {
3311
- current += character;
3312
- if (character === quote)
3313
- quote = "";
3314
- continue;
3315
- }
3316
- if (character === '"' || character === "'") {
3317
- quote = character;
3318
- current += character;
3319
- continue;
3320
- }
3321
- if (character === ",") {
3322
- if (current.trim())
3323
- entries.push(current.trim());
3324
- current = "";
3325
- continue;
3326
- }
3327
- current += character;
3328
- }
3329
- if (quote || escaped)
3330
- throw new Error("Screenshot options contain an incomplete string");
3331
- if (current.trim())
3332
- entries.push(current.trim());
3333
- return entries;
3334
- }
3335
- function parseSourceString(value) {
3336
- if (value.startsWith('"'))
3337
- return parseStringLiteral(value);
3338
- if (!value.startsWith("'") || !value.endsWith("'"))
3339
- throw new Error("Screenshot strings must use quotes");
3340
- const inner = value.slice(1, -1);
3341
- let parsed = "";
3342
- for (let index = 0; index < inner.length; index++) {
3343
- const character = inner[index];
3344
- if (character !== "\\") {
3345
- parsed += character;
3346
- continue;
3347
- }
3348
- const next = inner[++index];
3349
- if (next === void 0)
3350
- throw new Error("Screenshot string contains an incomplete escape");
3351
- parsed += next === "n" ? "\n" : next === "r" ? "\r" : next === "t" ? " " : next;
3352
- }
3353
- return parsed;
3354
- }
3355
- async function captureRequestedScreenshot(page, source, testCaseId) {
3356
- const options = parseScreenshotOptions(source);
3357
- const image = await page.screenshot({
3358
- type: options.type,
3359
- fullPage: options.fullPage,
3360
- ...options.type === "jpeg" && options.quality ? { quality: options.quality } : {}
3361
- });
3362
- const extension = options.type === "jpeg" ? "jpg" : "png";
3363
- const requestedName = options.path?.split(/[\\/]/).pop()?.replace(/\.[^.]+$/, "");
3364
- const safeName = (requestedName || `${testCaseId}-${Date.now()}`).replace(/[^\p{L}\p{N}._-]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 100);
3365
- return {
3366
- name: `${safeName || `screenshot-${Date.now()}`}.${extension}`,
3367
- dataUrl: `data:image/${options.type};base64,${image.toString("base64")}`,
3368
- capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
3369
- testCaseId,
3370
- status: "passed"
3371
- };
3372
- }
3373
- var STRING_LITERAL = `(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*')`;
3374
- function parseStringLiteral(value) {
3375
- const quote = value[0];
3376
- if (quote !== '"' && quote !== "'")
3377
- throw new Error("Edited Playwright arguments must be quoted strings");
3378
- const asJson = quote === '"' ? value : `"${value.slice(1, -1).replace(/\\'/g, "'").replace(/"/g, '\\"')}"`;
3379
- let parsed;
3380
- try {
3381
- parsed = JSON.parse(asJson);
3382
- } catch {
3383
- throw new Error("Edited Playwright arguments must be quoted strings");
3384
- }
3385
- if (typeof parsed !== "string")
3386
- throw new Error("Edited Playwright arguments must be strings");
3387
- return parsed;
3388
- }
3389
- var INDEX_SUFFIX = /\.(first|last|nth)\((\d{0,4})\)$/;
3390
- function applyIndexSuffix(expression) {
3391
- const match = expression.match(INDEX_SUFFIX);
3392
- if (!match)
3393
- return { base: expression };
3394
- const base = expression.slice(0, match.index);
3395
- if (match[1] === "first")
3396
- return { base, pick: (target) => target.first() };
3397
- if (match[1] === "last")
3398
- return { base, pick: (target) => target.last() };
3399
- if (!match[2])
3400
- return { base: expression };
3401
- const index = Number(match[2]);
3402
- return { base, pick: (target) => target.nth(index) };
3403
- }
3404
- function parseEditedLocator(page, expression) {
3405
- debugLocator("EditedSource", { expression });
3406
- const { base, pick } = applyIndexSuffix(expression);
3407
- const resolved = resolveLocatorExpression(page, base);
3408
- return pick ? { locator: pick(resolved.locator), label: resolved.label } : resolved;
3409
- }
3410
- function resolveLocatorExpression(page, expression) {
3411
- const roleMatch = expression.match(new RegExp(`^page\\.getByRole\\((${STRING_LITERAL}),\\s*\\{\\s*name:\\s*(${STRING_LITERAL})\\s*\\}\\)$`));
3412
- if (roleMatch) {
3413
- const role = parseStringLiteral(roleMatch[1]);
3414
- const name = parseStringLiteral(roleMatch[2]);
3415
- return { locator: page.getByRole(role, { name }), label: name };
3416
- }
3417
- const roleOnlyMatch = expression.match(new RegExp(`^page\\.getByRole\\((${STRING_LITERAL})\\)$`));
3418
- if (roleOnlyMatch) {
3419
- const role = parseStringLiteral(roleOnlyMatch[1]);
3420
- return { locator: page.getByRole(role), label: role };
3421
- }
3422
- for (const [method, create] of [
3423
- ["getByLabel", (value) => page.getByLabel(value)],
3424
- ["getByPlaceholder", (value) => page.getByPlaceholder(value)],
3425
- ["getByText", (value) => page.getByText(value)],
3426
- ["getByTestId", (value) => page.getByTestId(value)],
3427
- ["locator", (value) => page.locator(value)]
3428
- ]) {
3429
- const match = expression.match(new RegExp(`^page\\.${method}\\((${STRING_LITERAL})\\)$`));
3430
- if (match) {
3431
- const value = parseStringLiteral(match[1]);
3432
- return { locator: create(value), label: value };
3433
- }
3434
- }
3435
- throw new Error(`Unsupported locator: ${expression.slice(0, 120)}
3436
- Expected page.getByRole("button", { name: "Login" }), page.getByLabel/getByPlaceholder/getByText/getByTestId("\u2026") or page.locator("css"), optionally followed by .first(), .last() or .nth(n).`);
3437
- }
3438
- async function executeStep(page, step, addLog, blockedKeywords, secrets) {
3439
- switch (step.type) {
3440
- case "navigate":
3441
- const checked = checkTargetUrl(step.url, config.urlPolicy);
3442
- if (!checked.ok)
3443
- throw new Error(checked.message);
3444
- addLog("info", "Target URL found: " + redactUrl(checked.url.toString()));
3445
- addLog("info", "\u2192 Navigating to " + redactUrl(checked.url.toString()));
3446
- await page.goto(checked.url.toString(), { waitUntil: "domcontentloaded", timeout: STEP_TIMEOUT_MS });
3447
- addLog("pass", "Page ready: " + (new URL(page.url()).pathname || "/"));
3448
- addLog("info", "Continuing with the next test step");
3449
- return;
3450
- case "click": {
3451
- const name = step.target.name ?? step.target.text ?? step.target.cssSelector ?? "target";
3452
- const target = locator(page, step.target);
3453
- await ensureSafeClick(target, name, blockedKeywords);
3454
- addLog("info", "Control found: " + name);
3455
- addLog("info", "\u2192 Clicking " + name);
3456
- await target.click();
3457
- addLog("pass", "Action completed: " + name);
3458
- return;
3459
- }
3460
- case "fill": {
3461
- const name = step.target.name ?? step.target.label ?? "field";
3462
- const value = resolveSecret(step.value, secrets);
3463
- addLog("info", "Input found: " + name);
3464
- addLog("info", "\u2192 Filling " + name);
3465
- await locator(page, step.target).fill(value);
3466
- addLog("pass", "Input ready: " + name);
3467
- return;
3468
- }
3469
- case "select":
3470
- addLog("info", "Dropdown found: " + (step.target.name ?? step.target.label ?? "select"));
3471
- await locator(page, step.target).selectOption(step.option);
3472
- addLog("pass", "Selected option: " + step.option);
3473
- return;
3474
- case "assertVisible":
3475
- await locator(page, step.target).isVisible().then((visible) => {
3476
- if (!visible)
3477
- throw new Error("Expected element is not visible");
3478
- addLog("pass", "Element visible: " + (step.target.name ?? step.target.label ?? "target"));
3479
- });
3480
- return;
3481
- case "assertText": {
3482
- const bodyText = await page.locator("body").innerText();
3483
- if (!bodyText.includes(step.text))
3484
- throw new Error("Expected text was not found: " + step.text);
3485
- addLog("pass", 'Assertion passed: page contains "' + step.text + '"');
3486
- return;
3487
3541
  }
3488
- case "assertUrl":
3489
- if (!page.url().includes(step.urlContains))
3490
- throw new Error("URL does not contain " + step.urlContains);
3491
- addLog("pass", "URL assertion passed: " + redactUrl(page.url()));
3492
- return;
3493
- case "manual":
3494
- throw new Error("Manual step requires Tester review");
3495
- }
3496
- }
3497
- function resolveSecret(value, projectSecrets) {
3498
- const secrets = {
3499
- "{{TEST_EMAIL}}": projectSecrets?.email ?? process.env.LAZYSCOUT_TEST_EMAIL,
3500
- "{{TEST_USERNAME}}": projectSecrets?.username ?? process.env.LAZYSCOUT_TEST_USERNAME,
3501
- "{{TEST_PASSWORD}}": projectSecrets?.password ?? process.env.LAZYSCOUT_TEST_PASSWORD,
3502
- "{{API_TOKEN}}": projectSecrets?.apiToken ?? process.env.LAZYSCOUT_API_TOKEN
3503
- };
3504
- const secret = secrets[value];
3505
- if (secret === void 0 && value in secrets)
3506
- throw new Error("Required secret is not configured for " + value);
3507
- return secret ?? value;
3508
- }
3509
- function locator(page, target) {
3510
- debugLocator("Resolver", {
3511
- strategy: target.role && target.name ? "role" : target.label ? "label" : target.placeholder ? "placeholder" : target.text ? "text" : "css",
3512
- role: target.role,
3513
- name: target.name,
3514
- cssSelector: target.cssSelector
3515
3542
  });
3516
- if (target.role && target.name)
3517
- return page.getByRole(target.role, { name: target.name });
3518
- if (target.label)
3519
- return page.getByLabel(target.label);
3520
- if (target.placeholder)
3521
- return page.getByPlaceholder(target.placeholder);
3522
- if (target.text)
3523
- return page.getByText(target.text);
3524
- return page.locator(target.cssSelector ?? "");
3525
- }
3526
- function debugLocator(stage, detail) {
3527
- if (!process.env.LAZYSCOUT_DEBUG_LOCATOR)
3528
- return;
3529
- const safe = Object.fromEntries(Object.entries(detail).filter(([, value]) => value !== void 0).map(([key, value]) => [key, typeof value === "string" ? redactSensitiveText(value) : value]));
3530
- console.log(`[LazyScout:${stage}]`, safe);
3531
- }
3532
- async function ensureSafeClick(target, fallbackLabel, blockedKeywords) {
3533
- const labels = await Promise.all([
3534
- target.getAttribute("aria-label").catch(() => null),
3535
- target.getAttribute("title").catch(() => null),
3536
- target.getAttribute("name").catch(() => null),
3537
- target.getAttribute("id").catch(() => null),
3538
- target.innerText().catch(() => "")
3539
- ]);
3540
- const values = [fallbackLabel, ...labels.map((value) => value ?? void 0)];
3541
- if (isUnsafeAutoClick(...values))
3542
- throw new Error(`Blocked by mandatory safety policy: ${fallbackLabel}`);
3543
- if (isBlockedLabel(blockedKeywords, ...values)) {
3544
- throw new Error(`Blocked by the Project click filter: ${fallbackLabel}`);
3545
- }
3546
3543
  }
3547
3544
 
3548
3545
  // ../server/dist/routes/apiCheckRun.js
@@ -3684,9 +3681,9 @@ function registerLoadTestRoute(app) {
3684
3681
  }
3685
3682
 
3686
3683
  // ../server/dist/routes/versions.js
3687
- import { spawn } from "node:child_process";
3684
+ import { spawn as spawn2 } from "node:child_process";
3688
3685
  import { access } from "node:fs/promises";
3689
- import { dirname as dirname2, join as join2 } from "node:path";
3686
+ import { dirname as dirname3, join as join3 } from "node:path";
3690
3687
  var PACKAGE_NAME = "lazyscout";
3691
3688
  var REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}`;
3692
3689
  var VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
@@ -3732,8 +3729,8 @@ async function fetchPublishedVersions(force = false) {
3732
3729
  async function findNpmCli() {
3733
3730
  const candidates = [
3734
3731
  process.env.npm_execpath,
3735
- join2(dirname2(process.execPath), "node_modules", "npm", "bin", "npm-cli.js"),
3736
- process.env.APPDATA ? join2(process.env.APPDATA, "npm", "node_modules", "npm", "bin", "npm-cli.js") : void 0,
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,
3737
3734
  "/usr/lib/node_modules/npm/bin/npm-cli.js",
3738
3735
  "/usr/local/lib/node_modules/npm/bin/npm-cli.js"
3739
3736
  ].filter((value) => Boolean(value?.endsWith(".js")));
@@ -3750,7 +3747,7 @@ async function runNpmInstall(version) {
3750
3747
  const npmCli = await findNpmCli();
3751
3748
  return new Promise((resolve3, reject) => {
3752
3749
  const commandArgs = [npmCli, "install", "--global", `${PACKAGE_NAME}@${version}`, "--no-audit", "--no-fund"];
3753
- const child = spawn(process.execPath, commandArgs, {
3750
+ const child = spawn2(process.execPath, commandArgs, {
3754
3751
  windowsHide: true,
3755
3752
  stdio: ["ignore", "pipe", "pipe"]
3756
3753
  });
@@ -3908,6 +3905,14 @@ function registerWorkspaceRoutes(app, root) {
3908
3905
  return reply.send({ deleted: true });
3909
3906
  });
3910
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
+ });
3911
3916
  app.put("/api/workspace/projects/:projectId/automation", async (request, reply) => {
3912
3917
  await saveAutomation(root, request.params.projectId, request.body);
3913
3918
  return reply.send({ saved: true });
@@ -4042,6 +4047,105 @@ function registerRecorderRoutes(app, workspaceRoot, options = {}) {
4042
4047
  });
4043
4048
  }
4044
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
+
4045
4149
  // ../server/dist/app.js
4046
4150
  function buildApp(options = {}) {
4047
4151
  const app = Fastify({
@@ -4060,6 +4164,7 @@ function buildApp(options = {}) {
4060
4164
  registerVersionRoutes(app, appVersion);
4061
4165
  registerWorkspaceRoutes(app, workspaceRoot);
4062
4166
  registerRecorderRoutes(app, workspaceRoot);
4167
+ registerGuidedFlowRunRoute(app, workspaceRoot);
4063
4168
  if (options.staticDir) {
4064
4169
  app.register(fastifyStatic, { root: options.staticDir });
4065
4170
  app.setNotFoundHandler(async (request, reply) => {
@@ -4075,11 +4180,11 @@ function buildApp(options = {}) {
4075
4180
  }
4076
4181
 
4077
4182
  // src/openInBrowser.ts
4078
- import { spawn as spawn2 } from "node:child_process";
4183
+ import { spawn as spawn3 } from "node:child_process";
4079
4184
  async function openInBrowser(url) {
4080
4185
  const [command, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
4081
4186
  try {
4082
- const child = spawn2(command, args, { stdio: "ignore", detached: true });
4187
+ const child = spawn3(command, args, { stdio: "ignore", detached: true });
4083
4188
  child.on("error", () => void 0);
4084
4189
  child.unref();
4085
4190
  } catch {
@@ -4087,11 +4192,11 @@ async function openInBrowser(url) {
4087
4192
  }
4088
4193
 
4089
4194
  // src/version.ts
4090
- var VERSION = true ? "0.3.8" : "0.0.0-dev";
4195
+ var VERSION = true ? "0.3.9" : "0.0.0-dev";
4091
4196
 
4092
4197
  // src/commands/serve.ts
4093
4198
  var DEFAULT_PORT = 4321;
4094
- var WEB_DIR = join3(dirname3(fileURLToPath(import.meta.url)), "web");
4199
+ var WEB_DIR = join4(dirname4(fileURLToPath(import.meta.url)), "web");
4095
4200
  async function runServe(options) {
4096
4201
  const workspaceRoot = resolveWorkspaceRoot(options.workspace);
4097
4202
  await ensureWorkspace(workspaceRoot);