lazyscout 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7,6 +7,42 @@ import { parseArgs } from "node:util";
7
7
  import { writeFile } from "node:fs/promises";
8
8
  import { resolve } from "node:path";
9
9
 
10
+ // ../../packages/core/dist/state/fingerprint.js
11
+ function fingerprintState(input) {
12
+ const canonical = JSON.stringify({
13
+ url: input.url,
14
+ title: input.title,
15
+ visibleDialogs: [...input.visibleDialogs].sort(),
16
+ headings: [...input.headings].sort(),
17
+ controls: input.controls.map(({ kind, role, accessibleName, text, inputType, placeholder, disabled }) => ({
18
+ kind,
19
+ role,
20
+ name: accessibleName,
21
+ text,
22
+ inputType,
23
+ placeholder,
24
+ disabled
25
+ })),
26
+ interactions: input.interactions.map(({ kind, name, role, expanded, visible }) => ({
27
+ kind,
28
+ name,
29
+ role,
30
+ expanded,
31
+ visible
32
+ })),
33
+ stateContent: [...input.stateContent].sort()
34
+ });
35
+ let hash = 2166136261;
36
+ for (let index = 0; index < canonical.length; index += 1) {
37
+ hash ^= canonical.charCodeAt(index);
38
+ hash = Math.imul(hash, 16777619);
39
+ }
40
+ return `state-${(hash >>> 0).toString(16).padStart(8, "0")}`;
41
+ }
42
+ function stateId(url, fingerprint) {
43
+ return `${url}#${fingerprint}`;
44
+ }
45
+
10
46
  // ../../packages/core/dist/url/policy.js
11
47
  var LOCAL_QA_POLICY = {
12
48
  allowedProtocols: ["http:", "https:"],
@@ -64,7 +100,7 @@ function checkTargetUrl(rawUrl, policy = LOCAL_QA_POLICY) {
64
100
  try {
65
101
  url = new URL(withProtocol);
66
102
  } catch {
67
- return { ok: false, code: "invalid-url", message: `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A URL \u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${rawUrl}` };
103
+ return { ok: false, code: "invalid-url", message: "\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A URL \u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07" };
68
104
  }
69
105
  if (!policy.allowedProtocols.includes(url.protocol)) {
70
106
  return {
@@ -76,6 +112,9 @@ function checkTargetUrl(rawUrl, policy = LOCAL_QA_POLICY) {
76
112
  if (!url.hostname) {
77
113
  return { ok: false, code: "invalid-url", message: "URL \u0E44\u0E21\u0E48\u0E21\u0E35\u0E0A\u0E37\u0E48\u0E2D\u0E42\u0E2E\u0E2A\u0E15\u0E4C" };
78
114
  }
115
+ if (url.username || url.password) {
116
+ return { ok: false, code: "blocked-url", message: "\u0E44\u0E21\u0E48\u0E2D\u0E19\u0E38\u0E0D\u0E32\u0E15\u0E43\u0E2B\u0E49\u0E43\u0E2A\u0E48 credentials \u0E44\u0E27\u0E49\u0E43\u0E19 URL" };
117
+ }
79
118
  if (!policy.allowCloudMetadata && isCloudMetadataHostname(url.hostname)) {
80
119
  return { ok: false, code: "blocked-url", message: "\u0E44\u0E21\u0E48\u0E2D\u0E19\u0E38\u0E0D\u0E32\u0E15\u0E43\u0E2B\u0E49\u0E40\u0E02\u0E49\u0E32\u0E16\u0E36\u0E07 cloud metadata endpoint" };
81
120
  }
@@ -154,6 +193,55 @@ function moduleNameFromUrl(rawUrl) {
154
193
  }
155
194
  }
156
195
 
196
+ // ../../packages/core/dist/security/redact.js
197
+ var SENSITIVE_NAMES = [
198
+ "password",
199
+ "passwd",
200
+ "token",
201
+ "access_token",
202
+ "refresh_token",
203
+ "api_key",
204
+ "apikey",
205
+ "authorization",
206
+ "cookie",
207
+ "set-cookie",
208
+ "secret",
209
+ "client_secret",
210
+ "session",
211
+ "sessionid"
212
+ ];
213
+ var SENSITIVE_NAME_PATTERN = SENSITIVE_NAMES.map((name) => name.replace("-", "[-_]?").replace("_", "[-_]?")).join("|");
214
+ var ASSIGNMENT_NAME_PATTERN = SENSITIVE_NAMES.filter((name) => name !== "authorization").map((name) => name.replace("-", "[-_]?").replace("_", "[-_]?")).join("|");
215
+ function escapeRegExp(value) {
216
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
217
+ }
218
+ function redactSensitiveText(value, knownSecrets = []) {
219
+ let redacted = value.replace(/(authorization\s*[:=]\s*bearer\s+)[^\s,;]+/gi, "$1***").replace(/(bearer\s+)[A-Za-z0-9._~+/-]{8,}/gi, "$1***").replace(new RegExp(`((?:${ASSIGNMENT_NAME_PATTERN})["']?\\s*[:=]\\s*["']?)[^"'\\s,;}]+`, "gi"), "$1***").replace(new RegExp(`([?&](?:${SENSITIVE_NAME_PATTERN})=)[^&#\\s]*`, "gi"), "$1***");
220
+ for (const secret of knownSecrets) {
221
+ if (secret.length < 3)
222
+ continue;
223
+ redacted = redacted.replace(new RegExp(escapeRegExp(secret), "g"), "***");
224
+ }
225
+ return redacted;
226
+ }
227
+ function redactUrl(value) {
228
+ try {
229
+ const url = new URL(value);
230
+ if (url.username)
231
+ url.username = "***";
232
+ if (url.password)
233
+ url.password = "***";
234
+ for (const key of [...url.searchParams.keys()]) {
235
+ const normalized = key.toLowerCase().replace(/-/g, "_");
236
+ if (SENSITIVE_NAMES.some((name) => normalized.includes(name.replace(/-/g, "_"))))
237
+ url.searchParams.set(key, "***");
238
+ }
239
+ return url.toString();
240
+ } catch {
241
+ return redactSensitiveText(value);
242
+ }
243
+ }
244
+
157
245
  // ../../packages/core/dist/testcase/describeStep.js
158
246
  function describeTarget(target) {
159
247
  const name = target.name || target.label || target.text || target.placeholder;
@@ -353,7 +441,6 @@ function collectPageData() {
353
441
  name: attr(form, "name"),
354
442
  action: form.getAttribute("action") || void 0,
355
443
  method: (form.getAttribute("method") || "get").toLowerCase(),
356
- // ใช้ aria-label / name / id เท่านั้น เพราะ textContent ของ form คือทั้งฟอร์ม
357
444
  accessibleName: attr(form, "aria-label") || attr(form, "name") || form.id || void 0,
358
445
  fields,
359
446
  submitButtons
@@ -367,13 +454,27 @@ function collectPageData() {
367
454
  inputs: collect(INPUT_SELECTOR, "input", "textbox"),
368
455
  textareas: collect("textarea", "textarea", "textbox"),
369
456
  selects: collect("select", "select", "combobox"),
370
- forms
457
+ forms,
458
+ visibleDialogs: Array.from(document.querySelectorAll('[role="dialog"], dialog[open], [aria-modal="true"]')).filter(isCollectable).map((element) => accessibleName(element) || cleanText(element.textContent).slice(0, 120)).filter(Boolean).slice(0, 20),
459
+ interactions: Array.from(document.querySelectorAll('[role="tab"], [role="tablist"] [aria-controls], [aria-expanded], select')).filter(isCollectable).map((element) => {
460
+ const role = attr(element, "role") || (element instanceof HTMLSelectElement ? "combobox" : "button");
461
+ const expanded = element.getAttribute("aria-expanded");
462
+ const kind = role === "tab" ? "tab" : element instanceof HTMLSelectElement ? "dropdown" : element.matches("[aria-expanded]") ? "accordion" : "dialog";
463
+ return {
464
+ kind,
465
+ name: accessibleName(element),
466
+ role,
467
+ cssSelector: cssSelector(element),
468
+ expanded: expanded === null ? void 0 : expanded === "true",
469
+ visible: true
470
+ };
471
+ }).filter((item) => item.name).slice(0, 40),
472
+ 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)
371
473
  };
372
474
  }
373
475
 
374
476
  // ../../packages/explorer/dist/safety.js
375
477
  var DESTRUCTIVE_KEYWORDS = [
376
- // English
377
478
  "delete",
378
479
  "remove",
379
480
  "destroy",
@@ -407,7 +508,6 @@ var DESTRUCTIVE_KEYWORDS = [
407
508
  "publish",
408
509
  "approve",
409
510
  "reject",
410
- // ไทย
411
511
  "\u0E25\u0E1A",
412
512
  "\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01",
413
513
  "\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19",
@@ -453,6 +553,22 @@ function toFormInfo(raw) {
453
553
  };
454
554
  }
455
555
  function mapToPageModel(raw, meta) {
556
+ const links = raw.links.map(toUIElement);
557
+ const buttons = raw.buttons.map(toUIElement);
558
+ const inputs = raw.inputs.map(toUIElement);
559
+ const textareas = raw.textareas.map(toUIElement);
560
+ const selects = raw.selects.map(toUIElement);
561
+ const controls = [...links, ...buttons, ...inputs, ...textareas, ...selects];
562
+ const stateInput = {
563
+ url: meta.finalUrl,
564
+ title: raw.title,
565
+ visibleDialogs: raw.visibleDialogs,
566
+ headings: raw.headings,
567
+ controls,
568
+ interactions: raw.interactions,
569
+ stateContent: raw.stateContent
570
+ };
571
+ const fingerprint = fingerprintState(stateInput);
456
572
  return {
457
573
  url: meta.url,
458
574
  finalUrl: meta.finalUrl,
@@ -460,12 +576,14 @@ function mapToPageModel(raw, meta) {
460
576
  depth: meta.depth,
461
577
  statusCode: meta.statusCode,
462
578
  headings: raw.headings,
463
- links: raw.links.map(toUIElement),
464
- buttons: raw.buttons.map(toUIElement),
465
- inputs: raw.inputs.map(toUIElement),
466
- textareas: raw.textareas.map(toUIElement),
467
- selects: raw.selects.map(toUIElement),
468
- forms: raw.forms.map(toFormInfo)
579
+ links,
580
+ buttons,
581
+ inputs,
582
+ textareas,
583
+ selects,
584
+ forms: raw.forms.map(toFormInfo),
585
+ apiRequests: meta.apiRequests ?? [],
586
+ state: { id: stateId(meta.finalUrl, fingerprint), ...stateInput, fingerprint }
469
587
  };
470
588
  }
471
589
 
@@ -474,31 +592,31 @@ function toExploreIssue(url, error) {
474
592
  const raw = error instanceof Error ? error.message : String(error);
475
593
  const text = raw.toLowerCase();
476
594
  let code = "navigation-failed";
477
- let message = "\u0E40\u0E1B\u0E34\u0E14\u0E2B\u0E19\u0E49\u0E32\u0E19\u0E35\u0E49\u0E44\u0E21\u0E48\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08";
595
+ let message = "could not open the page \u2014 navigation failed";
478
596
  if (text.includes("err_connection_refused") || text.includes("econnrefused")) {
479
597
  code = "connection-refused";
480
- message = "\u0E40\u0E0A\u0E37\u0E48\u0E2D\u0E21\u0E15\u0E48\u0E2D\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49 (connection refused) \u2014 \u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E27\u0E48\u0E32\u0E40\u0E27\u0E47\u0E1A\u0E44\u0E0B\u0E15\u0E4C\u0E40\u0E1B\u0E34\u0E14\u0E2D\u0E22\u0E39\u0E48\u0E41\u0E25\u0E30\u0E1E\u0E2D\u0E23\u0E4C\u0E15\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07";
598
+ message = "could not connect \u2014 connection refused";
481
599
  } else if (text.includes("err_name_not_resolved") || text.includes("enotfound")) {
482
600
  code = "dns-error";
483
- message = "\u0E2B\u0E32\u0E0A\u0E37\u0E48\u0E2D\u0E42\u0E14\u0E40\u0E21\u0E19\u0E19\u0E35\u0E49\u0E44\u0E21\u0E48\u0E1E\u0E1A (DNS) \u2014 \u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E15\u0E31\u0E27\u0E2A\u0E30\u0E01\u0E14\u0E02\u0E2D\u0E07 URL";
601
+ message = "could not resolve domain name \u2014 check the URL";
484
602
  } else if (text.includes("err_cert") || text.includes("ssl") || text.includes("err_bad_ssl")) {
485
603
  code = "ssl-error";
486
- message = "\u0E43\u0E1A\u0E23\u0E31\u0E1A\u0E23\u0E2D\u0E07 SSL \u0E02\u0E2D\u0E07\u0E40\u0E27\u0E47\u0E1A\u0E44\u0E0B\u0E15\u0E4C\u0E21\u0E35\u0E1B\u0E31\u0E0D\u0E2B\u0E32";
604
+ message = "the SSL certificate of the website is invalid";
487
605
  } else if (text.includes("timeout") || text.includes("timed out")) {
488
606
  code = "timeout";
489
- message = "\u0E40\u0E1B\u0E34\u0E14\u0E2B\u0E19\u0E49\u0E32\u0E44\u0E21\u0E48\u0E17\u0E31\u0E19\u0E40\u0E27\u0E25\u0E32\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 (timeout)";
607
+ message = "could not open the page \u2014 timeout";
490
608
  } else if (text.includes("crash")) {
491
609
  code = "page-crash";
492
- message = "\u0E2B\u0E19\u0E49\u0E32\u0E40\u0E27\u0E47\u0E1A\u0E17\u0E33\u0E43\u0E2B\u0E49 browser \u0E2B\u0E22\u0E38\u0E14\u0E17\u0E33\u0E07\u0E32\u0E19 (page crash)";
610
+ message = "could not open the page \u2014 page crash";
493
611
  } else if (text.includes("err_connection_timed_out")) {
494
612
  code = "timeout";
495
- message = "\u0E40\u0E0A\u0E37\u0E48\u0E2D\u0E21\u0E15\u0E48\u0E2D\u0E44\u0E21\u0E48\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08\u0E20\u0E32\u0E22\u0E43\u0E19\u0E40\u0E27\u0E25\u0E32\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14";
613
+ message = "could not connect \u2014 connection timeout";
496
614
  } else if (text.includes("err_aborted")) {
497
615
  code = "navigation-failed";
498
- message = "\u0E01\u0E32\u0E23\u0E40\u0E1B\u0E34\u0E14\u0E2B\u0E19\u0E49\u0E32\u0E16\u0E39\u0E01\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01\u0E01\u0E25\u0E32\u0E07\u0E17\u0E32\u0E07";
616
+ message = "could not open the page \u2014 navigation aborted";
499
617
  } else if (text.includes("executable doesn") || text.includes("browsertype.launch")) {
500
618
  code = "browser-error";
501
- message = '\u0E40\u0E1B\u0E34\u0E14 browser \u0E44\u0E21\u0E48\u0E44\u0E14\u0E49 \u2014 \u0E43\u0E2B\u0E49\u0E23\u0E31\u0E19 "npx playwright install chromium" \u0E01\u0E48\u0E2D\u0E19';
619
+ message = 'could not open the browser \u2014 run "npx playwright install chromium" first';
502
620
  }
503
621
  return { url, code, message };
504
622
  }
@@ -534,7 +652,7 @@ async function launchBrowser() {
534
652
  void error;
535
653
  }
536
654
  }
537
- throw new ExplorerError("browser-error", `\u0E40\u0E1B\u0E34\u0E14\u0E40\u0E1A\u0E23\u0E32\u0E27\u0E4C\u0E40\u0E0B\u0E2D\u0E23\u0E4C\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49 (\u0E25\u0E2D\u0E07\u0E41\u0E25\u0E49\u0E27: ${failures.join(", ")})`, '\u0E15\u0E34\u0E14\u0E15\u0E31\u0E49\u0E07 Google Chrome \u0E2B\u0E23\u0E37\u0E2D Microsoft Edge \u0E2B\u0E23\u0E37\u0E2D\u0E23\u0E31\u0E19 "npx playwright install chromium" \u0E41\u0E25\u0E49\u0E27\u0E25\u0E2D\u0E07\u0E43\u0E2B\u0E21\u0E48');
655
+ throw new ExplorerError("browser-error", `unable to launch a browser (tried: ${failures.join(", ")})`, 'Please install Google Chrome or Microsoft Edge or run "npx playwright install chromium" and try again');
538
656
  }
539
657
 
540
658
  // ../../packages/explorer/dist/exploreWebsite.js
@@ -542,7 +660,8 @@ var DEFAULT_EXPLORE_OPTIONS = {
542
660
  maxPages: 20,
543
661
  maxDepth: 3,
544
662
  pageTimeoutMs: 2e4,
545
- totalTimeoutMs: 12e4
663
+ totalTimeoutMs: 12e4,
664
+ waitAfterNavigationMs: 750
546
665
  };
547
666
  async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY) {
548
667
  const config2 = { ...DEFAULT_EXPLORE_OPTIONS, ...options };
@@ -622,11 +741,89 @@ async function exploreWebsite(startUrl, options = {}, policy = LOCAL_QA_POLICY)
622
741
  urlsSkipped,
623
742
  durationMs: Date.now() - startedAt,
624
743
  limitReached
744
+ },
745
+ actionGraph: buildActionGraph(pages)
746
+ };
747
+ }
748
+ function buildActionGraph(pages) {
749
+ const states = pages.flatMap((page) => page.state ? [page.state] : []);
750
+ const edges = [];
751
+ const visitedActionKeys = [];
752
+ const failedActionKeys = [];
753
+ const blockedActionKeys = [];
754
+ for (const page of pages) {
755
+ const state = page.state;
756
+ if (!state)
757
+ continue;
758
+ const fromStateId = state.id;
759
+ for (const link of page.links) {
760
+ if (!link.href || !link.accessibleName)
761
+ continue;
762
+ const targetPage = pages.find((candidate) => candidate.url === link.href || candidate.finalUrl === link.href);
763
+ const action = {
764
+ type: "navigate",
765
+ target: link.accessibleName,
766
+ selector: link.cssSelector,
767
+ safe: canFollowLink(link.href, link.accessibleName)
768
+ };
769
+ const key = `${fromStateId}|navigate|${link.cssSelector}`;
770
+ const status = action.safe ? targetPage ? "visited" : "discovered" : "blocked";
771
+ edges.push({ fromStateId, toStateId: targetPage?.state?.id, action, status });
772
+ if (status === "visited")
773
+ visitedActionKeys.push(key);
774
+ if (status === "blocked")
775
+ blockedActionKeys.push(key);
776
+ }
777
+ for (const interaction of state.interactions) {
778
+ const destructive = isDestructiveLabel(interaction.name);
779
+ const type = interaction.kind === "tab" ? "selectTab" : interaction.kind === "accordion" ? "expandAccordion" : interaction.kind === "dropdown" ? "openDropdown" : interaction.expanded ? "closeDialog" : "openModal";
780
+ const key = `${fromStateId}|${type}|${interaction.cssSelector}`;
781
+ const action = {
782
+ type,
783
+ target: interaction.name,
784
+ selector: interaction.cssSelector,
785
+ safe: !destructive,
786
+ reason: destructive ? "Destructive action was discovered but not executed" : void 0
787
+ };
788
+ edges.push({ fromStateId, action, status: destructive ? "blocked" : "discovered" });
789
+ if (destructive)
790
+ blockedActionKeys.push(key);
625
791
  }
792
+ }
793
+ return {
794
+ states,
795
+ edges,
796
+ visitedStateIds: states.map((state) => state.id),
797
+ visitedActionKeys,
798
+ failedActionKeys,
799
+ blockedActionKeys
626
800
  };
627
801
  }
628
802
  async function visitPage(page, item, config2) {
629
803
  try {
804
+ const apiRequests = [];
805
+ const requestStarted = /* @__PURE__ */ new Map();
806
+ const onRequest = (request) => {
807
+ if (request.resourceType() === "xhr" || request.resourceType() === "fetch")
808
+ requestStarted.set(request.url(), Date.now());
809
+ };
810
+ const onResponse = (response2) => {
811
+ const request = response2.request();
812
+ if (request.resourceType() !== "xhr" && request.resourceType() !== "fetch")
813
+ return;
814
+ apiRequests.push({
815
+ id: `api-${apiRequests.length + 1}`,
816
+ method: request.method(),
817
+ url: redactUrl(request.url()),
818
+ status: response2.status(),
819
+ durationMs: Date.now() - (requestStarted.get(request.url()) ?? Date.now()),
820
+ resourceType: request.resourceType(),
821
+ sourceUrl: redactUrl(item.url),
822
+ contentType: response2.headers()["content-type"]
823
+ });
824
+ };
825
+ page.on("request", onRequest);
826
+ page.on("response", onResponse);
630
827
  const response = await page.goto(item.url, {
631
828
  waitUntil: "domcontentloaded",
632
829
  timeout: config2.pageTimeoutMs
@@ -638,16 +835,31 @@ async function visitPage(page, item, config2) {
638
835
  issue: { url: item.url, code: "http-error", message: `\u0E40\u0E0B\u0E34\u0E23\u0E4C\u0E1F\u0E40\u0E27\u0E2D\u0E23\u0E4C\u0E15\u0E2D\u0E1A\u0E01\u0E25\u0E31\u0E1A HTTP ${status}` }
639
836
  };
640
837
  }
641
- await page.waitForLoadState("networkidle", { timeout: 3e3 }).catch(() => void 0);
838
+ await page.waitForLoadState("networkidle", { timeout: Math.min(config2.pageTimeoutMs, 5e3) }).catch(() => void 0);
839
+ await page.waitForTimeout(config2.waitAfterNavigationMs);
840
+ const challengeText = `${await page.title()} ${await page.locator("body").innerText().catch(() => "")}`.toLowerCase();
841
+ if (challengeText.includes("cloudflare") || challengeText.includes("checking your browser") || challengeText.includes("verify you are human") || challengeText.includes("just a moment")) {
842
+ return {
843
+ kind: "issue",
844
+ issue: {
845
+ url: item.url,
846
+ code: "cloudflare",
847
+ message: "Cloudflare/browser challenge \u2014 self check the website in a browser and try again"
848
+ }
849
+ };
850
+ }
642
851
  const finalUrl = page.url();
643
852
  const raw = await page.evaluate(collectPageData);
853
+ page.off("request", onRequest);
854
+ page.off("response", onResponse);
644
855
  return {
645
856
  kind: "page",
646
857
  page: mapToPageModel(raw, {
647
858
  url: item.url,
648
859
  finalUrl,
649
860
  depth: item.depth,
650
- statusCode: status
861
+ statusCode: status,
862
+ apiRequests
651
863
  })
652
864
  };
653
865
  } catch (error) {
@@ -898,7 +1110,8 @@ function destructiveActionRule(ctx) {
898
1110
 
899
1111
  // ../../packages/generators/dist/testcases/generateTestCases.js
900
1112
  var DEFAULT_GENERATE_OPTIONS = {
901
- maxTestCasesPerPage: 15
1113
+ maxTestCasesPerPage: 15,
1114
+ language: "en"
902
1115
  };
903
1116
  function generateTestCases(pages, options = {}) {
904
1117
  const config2 = { ...DEFAULT_GENERATE_OPTIONS, ...options };
@@ -926,7 +1139,40 @@ function generateTestCases(pages, options = {}) {
926
1139
  testCases.push({ id: makeTestCaseId(module, sequence), ...generated });
927
1140
  }
928
1141
  }
929
- return testCases;
1142
+ return config2.language === "en" ? testCases : localizeThai(testCases);
1143
+ }
1144
+ function localizeThai(testCases) {
1145
+ return testCases.map((testCase) => ({
1146
+ ...testCase,
1147
+ title: translate(testCase.title),
1148
+ preconditions: testCase.preconditions.map(translate),
1149
+ steps: testCase.steps.map((step) => step.type === "manual" ? { ...step, description: translate(step.description) } : { ...step, description: translateStep(step) }),
1150
+ expectedResult: translate(testCase.expectedResult),
1151
+ notes: testCase.notes ? translate(testCase.notes) : void 0
1152
+ }));
1153
+ }
1154
+ function translateStep(step) {
1155
+ switch (step.type) {
1156
+ case "navigate":
1157
+ return `\u0E44\u0E1B\u0E22\u0E31\u0E07\u0E2B\u0E19\u0E49\u0E32 ${step.url}`;
1158
+ case "click":
1159
+ return `\u0E01\u0E14 ${step.target.name ?? step.target.label ?? step.target.text ?? "element"}`;
1160
+ case "fill":
1161
+ 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"}`;
1162
+ case "select":
1163
+ return `\u0E40\u0E25\u0E37\u0E2D\u0E01 ${step.option} \u0E08\u0E32\u0E01 ${step.target.name ?? step.target.label ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
1164
+ case "assertVisible":
1165
+ 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`;
1166
+ case "assertText":
1167
+ return step.target ? `\u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E27\u0E48\u0E32 ${step.target.name ?? step.target.label ?? "element"} \u0E41\u0E2A\u0E14\u0E07\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21 "${step.text}"` : `\u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E27\u0E48\u0E32\u0E2B\u0E19\u0E49\u0E32\u0E40\u0E27\u0E47\u0E1A\u0E41\u0E2A\u0E14\u0E07\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21 "${step.text}"`;
1168
+ case "assertUrl":
1169
+ return `\u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E27\u0E48\u0E32 URL \u0E21\u0E35\u0E04\u0E33\u0E27\u0E48\u0E32 "${step.urlContains}"`;
1170
+ case "manual":
1171
+ return step.description;
1172
+ }
1173
+ }
1174
+ function translate(value) {
1175
+ return value.replace(/^(.+) page displays required controls$/, "$1 \u0E41\u0E2A\u0E14\u0E07 controls \u0E17\u0E35\u0E48\u0E08\u0E33\u0E40\u0E1B\u0E47\u0E19").replace(/^(.+) is required$/, "$1 \u0E40\u0E1B\u0E47\u0E19\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E08\u0E33\u0E40\u0E1B\u0E47\u0E19").replace(/^Submit (.+) with valid data$/, "\u0E2A\u0E48\u0E07 $1 \u0E14\u0E49\u0E27\u0E22\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07").replace(/^Navigate to (.+)$/, "\u0E44\u0E1B\u0E22\u0E31\u0E07 $1").replace(/^Verify "(.+)" action \(manual\)$/, '\u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A action "$1" \u0E14\u0E49\u0E27\u0E22\u0E15\u0E19\u0E40\u0E2D\u0E07').replace(/^Open (.+)$/, "\u0E40\u0E1B\u0E34\u0E14 $1").replace(/^The page is reachable and rendered$/, "\u0E2B\u0E19\u0E49\u0E32\u0E40\u0E27\u0E47\u0E1A\u0E2A\u0E32\u0E21\u0E32\u0E23\u0E16\u0E40\u0E1B\u0E34\u0E14\u0E41\u0E25\u0E30\u0E41\u0E2A\u0E14\u0E07\u0E1C\u0E25\u0E44\u0E14\u0E49").replace(/^Expected behavior is not known from static exploration; review manually\.$/, "\u0E44\u0E21\u0E48\u0E17\u0E23\u0E32\u0E1A behavior \u0E08\u0E32\u0E01\u0E01\u0E32\u0E23\u0E2A\u0E33\u0E23\u0E27\u0E08\u0E41\u0E1A\u0E1A static \u0E01\u0E23\u0E38\u0E13\u0E32\u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E14\u0E49\u0E27\u0E22\u0E15\u0E19\u0E40\u0E2D\u0E07");
930
1176
  }
931
1177
  function safeNormalize(url) {
932
1178
  try {
@@ -1015,6 +1261,9 @@ var UTF8_BOM = "\uFEFF";
1015
1261
  var CSV_COLUMNS = [
1016
1262
  "TC_ID",
1017
1263
  "Module",
1264
+ "Folder",
1265
+ "Tags",
1266
+ "Requirements",
1018
1267
  "Title",
1019
1268
  "Preconditions",
1020
1269
  "Test_Steps",
@@ -1045,6 +1294,9 @@ function testCaseRow(testCase) {
1045
1294
  return toRow([
1046
1295
  testCase.id,
1047
1296
  testCase.module,
1297
+ testCase.folder ?? "",
1298
+ (testCase.tags ?? []).join(", "),
1299
+ (testCase.requirements ?? []).join(", "),
1048
1300
  testCase.title,
1049
1301
  testCase.preconditions.join("\n"),
1050
1302
  describeSteps(testCase.steps),
@@ -1078,7 +1330,7 @@ function exportTestCasesToCsv(testCases, testData = []) {
1078
1330
 
1079
1331
  // src/commands/scan.ts
1080
1332
  async function runScan(options) {
1081
- console.log(`\u0E01\u0E33\u0E25\u0E31\u0E07\u0E2A\u0E33\u0E23\u0E27\u0E08 ${options.url} ...`);
1333
+ console.log(`checking scan ${redactUrl(options.url)} ...`);
1082
1334
  const result = await exploreWebsite(options.url, {
1083
1335
  ...options.maxPages !== void 0 ? { maxPages: options.maxPages } : {},
1084
1336
  ...options.maxDepth !== void 0 ? { maxDepth: options.maxDepth } : {}
@@ -1093,25 +1345,25 @@ async function runScan(options) {
1093
1345
  }
1094
1346
  console.log(
1095
1347
  `
1096
- \u0E2A\u0E23\u0E38\u0E1B: ${result.pages.length} \u0E2B\u0E19\u0E49\u0E32 \xB7 ${testCases.length} test case \xB7 ${testData.length} test data \xB7 ${(result.stats.durationMs / 1e3).toFixed(1)} \u0E27\u0E34\u0E19\u0E32\u0E17\u0E35 \xB7 \u0E43\u0E0A\u0E49 ${result.stats.browser}`
1348
+ Summary: ${result.pages.length} pages \xB7 ${testCases.length} test cases \xB7 ${testData.length} test data \xB7 ${(result.stats.durationMs / 1e3).toFixed(1)} seconds \xB7 Using ${result.stats.browser}`
1097
1349
  );
1098
1350
  if (result.pages.length === 0) {
1099
- console.error("\u0E40\u0E1B\u0E34\u0E14\u0E40\u0E27\u0E47\u0E1A\u0E44\u0E0B\u0E15\u0E4C\u0E44\u0E21\u0E48\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08 \u0E08\u0E36\u0E07\u0E44\u0E21\u0E48\u0E21\u0E35\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E43\u0E2B\u0E49\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01");
1351
+ console.error("Failed to open the website, no data to save");
1100
1352
  process.exitCode = 1;
1101
1353
  return;
1102
1354
  }
1103
1355
  const csvPath = resolve(options.csvPath ?? "lazyscout-testcases.csv");
1104
1356
  await writeFile(csvPath, exportTestCasesToCsv(testCases, testData), "utf8");
1105
- console.log(`\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01 CSV: ${csvPath}`);
1357
+ console.log(`Saved CSV: ${csvPath}`);
1106
1358
  if (options.jsonPath) {
1107
1359
  const jsonPath = resolve(options.jsonPath);
1108
1360
  await writeFile(jsonPath, JSON.stringify({ ...result, testCases, testData }, null, 2), "utf8");
1109
- console.log(`\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01 JSON: ${jsonPath}`);
1361
+ console.log(`Saved JSON: ${jsonPath}`);
1110
1362
  }
1111
1363
  }
1112
1364
 
1113
1365
  // src/commands/serve.ts
1114
- import { dirname, join } from "node:path";
1366
+ import { dirname as dirname3, join as join3 } from "node:path";
1115
1367
  import { fileURLToPath } from "node:url";
1116
1368
 
1117
1369
  // ../server/dist/app.js
@@ -1140,7 +1392,13 @@ function toApiError(error) {
1140
1392
  const status = error.code === "invalid-url" || error.code === "blocked-url" ? 400 : 502;
1141
1393
  return {
1142
1394
  status,
1143
- body: { error: { code: error.code, message: error.message, hint: error.hint } }
1395
+ body: {
1396
+ error: {
1397
+ code: error.code,
1398
+ message: redactSensitiveText(error.message),
1399
+ hint: error.hint ? redactSensitiveText(error.hint) : void 0
1400
+ }
1401
+ }
1144
1402
  };
1145
1403
  }
1146
1404
  return {
@@ -1171,29 +1429,100 @@ function registerAnalyzeRoute(app) {
1171
1429
  try {
1172
1430
  const result = await exploreWebsite(check.url.toString(), {
1173
1431
  maxPages: clamp(body.maxPages, 1, config.limits.maxPages, config.limits.maxPages),
1174
- maxDepth: clamp(body.maxDepth, 0, config.limits.maxDepth, config.limits.maxDepth)
1432
+ maxDepth: clamp(body.maxDepth, 0, config.limits.maxDepth, config.limits.maxDepth),
1433
+ waitAfterNavigationMs: clamp(body.waitAfterNavigationMs, 0, 5e3, 750)
1175
1434
  }, config.urlPolicy);
1176
1435
  if (result.pages.length === 0) {
1177
1436
  const firstIssue = result.issues[0];
1178
1437
  throw new ExplorerError(firstIssue?.code ?? "navigation-failed", firstIssue?.message ?? "\u0E40\u0E1B\u0E34\u0E14\u0E40\u0E27\u0E47\u0E1A\u0E44\u0E0B\u0E15\u0E4C\u0E44\u0E21\u0E48\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08", "\u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E27\u0E48\u0E32 URL \u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E41\u0E25\u0E30\u0E40\u0E27\u0E47\u0E1A\u0E44\u0E0B\u0E15\u0E4C\u0E01\u0E33\u0E25\u0E31\u0E07\u0E17\u0E33\u0E07\u0E32\u0E19\u0E2D\u0E22\u0E39\u0E48");
1179
1438
  }
1439
+ const testCases = generateTestCases(result.pages, { language: body.language ?? "en" });
1440
+ const runEvents = [
1441
+ {
1442
+ timestamp: new Date(Date.now() - result.stats.durationMs).toISOString(),
1443
+ eventType: "run-started",
1444
+ result: "running",
1445
+ message: "Explorer run started"
1446
+ },
1447
+ ...result.pages.flatMap((page) => [
1448
+ {
1449
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1450
+ eventType: "page-discovered",
1451
+ currentUrl: page.finalUrl,
1452
+ currentStateId: page.state?.id,
1453
+ result: "passed",
1454
+ message: `Page discovered: ${page.title || page.finalUrl}`
1455
+ },
1456
+ ...(page.state?.interactions ?? []).map((interaction) => ({
1457
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1458
+ eventType: result.actionGraph.blockedActionKeys.some((key) => key.endsWith(`|${interaction.cssSelector}`)) ? "action-blocked" : "action-discovered",
1459
+ currentUrl: page.finalUrl,
1460
+ currentStateId: page.state?.id,
1461
+ result: result.actionGraph.blockedActionKeys.some((key) => key.endsWith(`|${interaction.cssSelector}`)) ? "blocked" : "warning",
1462
+ message: `${interaction.kind}: ${interaction.name}`
1463
+ }))
1464
+ ]),
1465
+ ...result.issues.map((issue) => ({
1466
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1467
+ eventType: "error",
1468
+ currentUrl: issue.url,
1469
+ result: "failed",
1470
+ error: issue.message,
1471
+ message: issue.message
1472
+ })),
1473
+ {
1474
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1475
+ eventType: "run-completed",
1476
+ result: result.issues.length ? "warning" : "passed",
1477
+ durationMs: result.stats.durationMs,
1478
+ message: "Analysis completed"
1479
+ }
1480
+ ];
1180
1481
  const response = {
1181
1482
  startUrl: result.startUrl,
1182
1483
  origin: result.origin,
1183
1484
  pages: result.pages,
1184
- testCases: generateTestCases(result.pages),
1485
+ testCases,
1185
1486
  testData: generateTestData(result.pages),
1186
1487
  issues: result.issues,
1187
- stats: result.stats
1488
+ stats: result.stats,
1489
+ actionGraph: result.actionGraph,
1490
+ runEvents,
1491
+ apiChecks: body.includeApiChecks ? buildApiChecks(result.pages) : []
1188
1492
  };
1189
1493
  return reply.send(response);
1190
1494
  } catch (error) {
1191
- request.log.error({ err: error }, "analyze failed");
1495
+ request.log.error({ message: redactSensitiveText(error instanceof Error ? error.message : String(error)) }, "analyze failed");
1192
1496
  const { status, body: errorBody } = toApiError(error);
1193
1497
  return reply.status(status).send(errorBody);
1194
1498
  }
1195
1499
  });
1196
1500
  }
1501
+ function buildApiChecks(pages) {
1502
+ const seen = /* @__PURE__ */ new Set();
1503
+ const checks = [];
1504
+ for (const page of pages)
1505
+ for (const request of page.apiRequests) {
1506
+ const key = `${request.method}:${request.url}`;
1507
+ if (seen.has(key))
1508
+ continue;
1509
+ seen.add(key);
1510
+ const authRequired = request.status === 401 || request.status === 403;
1511
+ const safeMethod = ["GET", "HEAD", "OPTIONS"].includes(request.method.toUpperCase());
1512
+ checks.push({
1513
+ id: `API-${String(checks.length + 1).padStart(3, "0")}`,
1514
+ method: request.method,
1515
+ url: request.url,
1516
+ observedStatus: request.status,
1517
+ expectedStatus: authRequired ? void 0 : request.status && request.status < 400 ? 200 : void 0,
1518
+ sourceUrl: request.sourceUrl,
1519
+ durationMs: request.durationMs,
1520
+ status: !safeMethod ? "needs-review" : authRequired ? "needs-auth" : request.status && request.status >= 400 ? "needs-review" : "observed",
1521
+ note: !safeMethod ? "Observation only. LazyScout does not replay state-changing API methods automatically." : authRequired ? "Requires auth profile or token before execution." : void 0
1522
+ });
1523
+ }
1524
+ return checks;
1525
+ }
1197
1526
 
1198
1527
  // ../server/dist/routes/exportCsv.js
1199
1528
  function registerExportCsvRoute(app) {
@@ -1210,17 +1539,1118 @@ function registerExportCsvRoute(app) {
1210
1539
  });
1211
1540
  }
1212
1541
 
1542
+ // ../server/dist/workspace.js
1543
+ import { execFile } from "node:child_process";
1544
+ import { randomUUID } from "node:crypto";
1545
+ import { homedir, platform } from "node:os";
1546
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve as resolve2 } from "node:path";
1547
+ import { mkdir, readFile, readdir, rename, rm, stat, writeFile as writeFile2 } from "node:fs/promises";
1548
+ import { promisify } from "node:util";
1549
+ var execFileAsync = promisify(execFile);
1550
+ var PROJECT_ID = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
1551
+ var FILE_NAME = /^[^\\/:*?"<>|]{1,160}$/;
1552
+ var mutationQueues = /* @__PURE__ */ new Map();
1553
+ function defaultWorkspaceRoot() {
1554
+ return join(homedir(), "LazyScout");
1555
+ }
1556
+ function resolveWorkspaceRoot(value) {
1557
+ return resolve2(value?.trim() || process.env.LAZYSCOUT_WORKSPACE || defaultWorkspaceRoot());
1558
+ }
1559
+ async function ensureWorkspace(root) {
1560
+ await Promise.all([
1561
+ mkdir(join(root, "projects"), { recursive: true }),
1562
+ mkdir(join(root, "backups"), { recursive: true })
1563
+ ]);
1564
+ const settingsPath = join(root, "settings.json");
1565
+ try {
1566
+ await stat(settingsPath);
1567
+ } catch {
1568
+ await writeJson(settingsPath, { version: 1, workspaceRoot: root, createdAt: (/* @__PURE__ */ new Date()).toISOString() });
1569
+ }
1570
+ }
1571
+ async function listProjects(root) {
1572
+ await ensureWorkspace(root);
1573
+ const entries = await readdir(join(root, "projects"), { withFileTypes: true });
1574
+ const projects = await Promise.all(entries.filter((entry) => entry.isDirectory() && PROJECT_ID.test(entry.name)).map((entry) => readProject(root, entry.name)));
1575
+ return projects.filter((project) => Boolean(project)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
1576
+ }
1577
+ async function saveProject(root, project) {
1578
+ return enqueueMutation(`project:${project.id}`, async () => {
1579
+ const directory = await ensureProject(root, project.id);
1580
+ const normalized = normalizeResult(project.result);
1581
+ const { testCases, ...result } = normalized;
1582
+ const testData = normalized.testData;
1583
+ await Promise.all([
1584
+ writeJson(join(directory, "project.json"), { ...project, result }),
1585
+ writeJson(join(directory, "test-cases.json"), testCases),
1586
+ writeFileAtomic(join(directory, "test-cases.csv"), exportTestCasesToCsv(testCases, testData)),
1587
+ writeFileAtomic(join(directory, "test-data.csv"), testDataCsv(testData))
1588
+ ]);
1589
+ });
1590
+ }
1591
+ async function deleteProject(root, projectId) {
1592
+ return enqueueMutation(`project:${projectId}`, async () => {
1593
+ const source = projectDirectory(root, projectId);
1594
+ try {
1595
+ await stat(source);
1596
+ } catch {
1597
+ return;
1598
+ }
1599
+ await ensureWorkspace(root);
1600
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1601
+ await rename(source, join(root, "backups", `${projectId}-${timestamp}`));
1602
+ });
1603
+ }
1604
+ async function readScreenshots(root, projectId) {
1605
+ const directory = await ensureProject(root, projectId);
1606
+ return readJson(join(directory, "screenshots", "index.json"), []);
1607
+ }
1608
+ async function saveScreenshot(root, projectId, screenshot) {
1609
+ return enqueueMutation(`screenshots:${projectId}`, async () => {
1610
+ const directory = join(await ensureProject(root, projectId), "screenshots");
1611
+ const match = screenshot.dataUrl.match(/^data:image\/(png|jpeg);base64,([a-zA-Z0-9+/=]+)$/);
1612
+ if (!match)
1613
+ throw new Error("Screenshot must be a PNG or JPEG data URL");
1614
+ const image = Buffer.from(match[2], "base64");
1615
+ if (image.byteLength > 6 * 1024 * 1024)
1616
+ throw new Error("Screenshot exceeds the 6 MB limit");
1617
+ const extension = match[1] === "jpeg" ? ".jpg" : ".png";
1618
+ const requested = safeFileName(screenshot.name, `screenshot-${Date.now()}${extension}`);
1619
+ const name = extname(requested) ? `${basename(requested, extname(requested))}${extension}` : `${requested}${extension}`;
1620
+ await writeFileAtomic(join(directory, name), image);
1621
+ const current = await readScreenshots(root, projectId);
1622
+ const stored = { ...screenshot, name, dataUrl: screenshotUrl(projectId, name) };
1623
+ const next = [stored, ...current.filter((item) => item.name !== name)].slice(0, 50);
1624
+ await writeJson(join(directory, "index.json"), next);
1625
+ return stored;
1626
+ });
1627
+ }
1628
+ async function deleteScreenshot(root, projectId, name) {
1629
+ const safeName = assertFileName(name);
1630
+ const directory = join(await ensureProject(root, projectId), "screenshots");
1631
+ await rm(join(directory, safeName), { force: true });
1632
+ const current = await readScreenshots(root, projectId);
1633
+ await writeJson(join(directory, "index.json"), current.filter((item) => item.name !== safeName));
1634
+ }
1635
+ async function screenshotFile(root, projectId, name) {
1636
+ return readFile(join(await ensureProject(root, projectId), "screenshots", assertFileName(name)));
1637
+ }
1638
+ async function listBugReports(root, projectId) {
1639
+ const directory = join(await ensureProject(root, projectId), "bugs");
1640
+ const entries = await readdir(directory, { withFileTypes: true });
1641
+ const reports = await Promise.all(entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json") && entry.name !== "index.json").map((entry) => readJson(join(directory, entry.name), null)));
1642
+ return reports.filter((report) => Boolean(report));
1643
+ }
1644
+ async function saveBugReport(root, projectId, report) {
1645
+ const directory = join(await ensureProject(root, projectId), "bugs");
1646
+ await writeJson(join(directory, `${safeFileName(report.id, `BUG-${Date.now()}`)}.json`), report);
1647
+ }
1648
+ async function deleteBugReport(root, projectId, bugId) {
1649
+ const directory = join(await ensureProject(root, projectId), "bugs");
1650
+ await rm(join(directory, `${safeFileName(bugId, "bug")}.json`), { force: true });
1651
+ }
1652
+ async function readAutomation(root, projectId) {
1653
+ const directory = join(await ensureProject(root, projectId), "automation");
1654
+ const index = await readJson(join(directory, "index.json"), {});
1655
+ const entries = await Promise.all(Object.entries(index).map(async ([key, name]) => {
1656
+ try {
1657
+ return [key, await readFile(join(directory, assertFileName(name)), "utf8")];
1658
+ } catch {
1659
+ return void 0;
1660
+ }
1661
+ }));
1662
+ return Object.fromEntries(entries.filter((entry) => Boolean(entry)));
1663
+ }
1664
+ async function saveAutomation(root, projectId, overrides) {
1665
+ const directory = join(await ensureProject(root, projectId), "automation");
1666
+ const previous = await readJson(join(directory, "index.json"), {});
1667
+ const next = {};
1668
+ for (const [key, source] of Object.entries(overrides)) {
1669
+ if (typeof source !== "string" || source.length > 2e5)
1670
+ throw new Error("Automation source exceeds the limit");
1671
+ const [framework, caseId] = key.split(":", 2);
1672
+ if (framework !== "playwright" && framework !== "cypress" || !caseId)
1673
+ continue;
1674
+ const extension = framework === "playwright" ? ".spec.ts" : ".cy.ts";
1675
+ const name = `${framework}-${safeFileName(caseId, "test-case")}${extension}`;
1676
+ next[key] = name;
1677
+ await writeFileAtomic(join(directory, name), source);
1678
+ }
1679
+ for (const name of Object.values(previous))
1680
+ if (!Object.values(next).includes(name))
1681
+ await rm(join(directory, assertFileName(name)), { force: true });
1682
+ await writeJson(join(directory, "index.json"), next);
1683
+ }
1684
+ async function saveRunLog(root, projectId, testCaseId, status, logs) {
1685
+ const directory = join(await ensureProject(root, projectId), "logs");
1686
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1687
+ const name = `${timestamp}-${safeFileName(testCaseId, "test-case")}.json`;
1688
+ await writeJson(join(directory, name), { testCaseId, status, createdAt: (/* @__PURE__ */ new Date()).toISOString(), logs });
1689
+ }
1690
+ async function saveReport(root, projectId, name, html) {
1691
+ if (typeof html !== "string" || html.length > 2e6)
1692
+ throw new Error("Report exceeds the 2 MB limit");
1693
+ const directory = join(await ensureProject(root, projectId), "reports");
1694
+ const fileName = `${safeFileName(name, `quality-report-${Date.now()}.html`).replace(/\.[^.]+$/, "")}.html`;
1695
+ await writeFileAtomic(join(directory, fileName), html);
1696
+ return fileName;
1697
+ }
1698
+ async function openWorkspace(root) {
1699
+ await ensureWorkspace(root);
1700
+ if (platform() === "win32")
1701
+ await execFileAsync("explorer.exe", [root], { windowsHide: true });
1702
+ else if (platform() === "darwin")
1703
+ await execFileAsync("open", [root]);
1704
+ else
1705
+ await execFileAsync("xdg-open", [root]);
1706
+ }
1707
+ async function readProject(root, projectId) {
1708
+ try {
1709
+ const directory = projectDirectory(root, projectId);
1710
+ const project = await readJson(join(directory, "project.json"), void 0);
1711
+ if (!project)
1712
+ return void 0;
1713
+ const testCases = await readJson(join(directory, "test-cases.json"), []);
1714
+ return { ...project, result: normalizeResult({ ...project.result, testCases }) };
1715
+ } catch {
1716
+ return void 0;
1717
+ }
1718
+ }
1719
+ async function ensureProject(root, projectId) {
1720
+ await ensureWorkspace(root);
1721
+ const directory = projectDirectory(root, projectId);
1722
+ await Promise.all(["automation", "screenshots", "bugs", "reports", "logs"].map((name) => mkdir(join(directory, name), { recursive: true })));
1723
+ return directory;
1724
+ }
1725
+ function projectDirectory(root, projectId) {
1726
+ if (!PROJECT_ID.test(projectId))
1727
+ throw new Error("Invalid project ID");
1728
+ return containedPath(join(root, "projects"), projectId);
1729
+ }
1730
+ function containedPath(root, value) {
1731
+ const target = resolve2(root, value);
1732
+ const relation = relative(resolve2(root), target);
1733
+ if (!relation || relation.startsWith("..") || isAbsolute(relation))
1734
+ throw new Error("Path is outside the workspace");
1735
+ return target;
1736
+ }
1737
+ function assertFileName(value) {
1738
+ if (!FILE_NAME.test(value) || value === "." || value === "..")
1739
+ throw new Error("Invalid file name");
1740
+ return value;
1741
+ }
1742
+ function safeFileName(value, fallback) {
1743
+ const safe = basename(value).replace(/[^\p{L}\p{N}._-]+/gu, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 120);
1744
+ return safe || fallback;
1745
+ }
1746
+ function screenshotUrl(projectId, name) {
1747
+ return `/api/workspace/projects/${encodeURIComponent(projectId)}/screenshots/${encodeURIComponent(name)}`;
1748
+ }
1749
+ async function readJson(path, fallback) {
1750
+ try {
1751
+ return JSON.parse(await readFile(path, "utf8"));
1752
+ } catch {
1753
+ return fallback;
1754
+ }
1755
+ }
1756
+ async function writeJson(path, value) {
1757
+ await writeFileAtomic(path, `${JSON.stringify(value, null, 2)}
1758
+ `);
1759
+ }
1760
+ async function writeFileAtomic(path, value) {
1761
+ await mkdir(dirname(path), { recursive: true });
1762
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
1763
+ await writeFile2(temporary, value);
1764
+ await rm(path, { force: true });
1765
+ await rename(temporary, path);
1766
+ }
1767
+ function testDataCsv(rows) {
1768
+ const toRow2 = (values) => values.map(escapeCsvValue).join(",");
1769
+ return UTF8_BOM + [
1770
+ toRow2([...TEST_DATA_CSV_COLUMNS]),
1771
+ ...rows.map((row) => toRow2([
1772
+ row.id,
1773
+ row.module,
1774
+ row.field,
1775
+ row.inputType,
1776
+ row.required ? "yes" : "no",
1777
+ row.validValue,
1778
+ row.invalidValue,
1779
+ row.note ?? "",
1780
+ row.sourceUrl
1781
+ ]))
1782
+ ].join("\r\n") + "\r\n";
1783
+ }
1784
+ function normalizeResult(value) {
1785
+ const actionGraph = value?.actionGraph;
1786
+ return {
1787
+ startUrl: value?.startUrl ?? "",
1788
+ origin: value?.origin ?? "Manual test suite",
1789
+ pages: Array.isArray(value?.pages) ? value.pages : [],
1790
+ testCases: Array.isArray(value?.testCases) ? value.testCases : [],
1791
+ testData: Array.isArray(value?.testData) ? value.testData : [],
1792
+ issues: Array.isArray(value?.issues) ? value.issues : [],
1793
+ stats: value?.stats ?? { pagesVisited: 0, urlsSkipped: 0, durationMs: 0, limitReached: "none" },
1794
+ actionGraph: {
1795
+ states: Array.isArray(actionGraph?.states) ? actionGraph.states : [],
1796
+ edges: Array.isArray(actionGraph?.edges) ? actionGraph.edges : [],
1797
+ visitedStateIds: Array.isArray(actionGraph?.visitedStateIds) ? actionGraph.visitedStateIds : [],
1798
+ visitedActionKeys: Array.isArray(actionGraph?.visitedActionKeys) ? actionGraph.visitedActionKeys : [],
1799
+ failedActionKeys: Array.isArray(actionGraph?.failedActionKeys) ? actionGraph.failedActionKeys : [],
1800
+ blockedActionKeys: Array.isArray(actionGraph?.blockedActionKeys) ? actionGraph.blockedActionKeys : []
1801
+ },
1802
+ runEvents: Array.isArray(value?.runEvents) ? value.runEvents : [],
1803
+ apiChecks: Array.isArray(value?.apiChecks) ? value.apiChecks : []
1804
+ };
1805
+ }
1806
+ function enqueueMutation(key, action) {
1807
+ const previous = mutationQueues.get(key) ?? Promise.resolve();
1808
+ const next = previous.catch(() => void 0).then(action);
1809
+ mutationQueues.set(key, next);
1810
+ return next.finally(() => {
1811
+ if (mutationQueues.get(key) === next)
1812
+ mutationQueues.delete(key);
1813
+ });
1814
+ }
1815
+
1816
+ // ../server/dist/routes/automationRun.js
1817
+ var MAX_STEPS = 100;
1818
+ var MAX_LOGS = 250;
1819
+ var MAX_SOURCE_LENGTH = 2e5;
1820
+ var STEP_TIMEOUT_MS = 2e4;
1821
+ var activeRuns = /* @__PURE__ */ new Map();
1822
+ function registerAutomationRunRoute(app, workspaceRoot) {
1823
+ app.post("/api/automation/stop", async (request, reply) => {
1824
+ const runId = request.body?.runId;
1825
+ if (!runId)
1826
+ return reply.status(400).send({ error: { code: "invalid-run", message: "Run ID is required." } });
1827
+ const active = activeRuns.get(runId);
1828
+ if (!active)
1829
+ return reply.send({ stopped: false });
1830
+ active.stopped = true;
1831
+ await active.browser?.close().catch(() => void 0);
1832
+ return reply.send({ stopped: true });
1833
+ });
1834
+ app.post("/api/automation/run", async (request, reply) => {
1835
+ const body = request.body;
1836
+ const testCase = body.testCase;
1837
+ const secrets = body.secrets;
1838
+ const framework = body.framework ?? "playwright";
1839
+ const runId = body.runId || crypto.randomUUID();
1840
+ if (!testCase || !Array.isArray(testCase.steps))
1841
+ return reply.status(400).send({ error: { code: "invalid-test-case", message: "\u0E44\u0E21\u0E48\u0E1E\u0E1A Test Case \u0E17\u0E35\u0E48\u0E15\u0E49\u0E2D\u0E07\u0E01\u0E32\u0E23\u0E23\u0E31\u0E19" } });
1842
+ if (testCase.steps.length > MAX_STEPS)
1843
+ return reply.status(400).send({ error: { code: "run-limit", message: "\u0E08\u0E33\u0E19\u0E27\u0E19 steps \u0E40\u0E01\u0E34\u0E19\u0E02\u0E35\u0E14\u0E08\u0E33\u0E01\u0E31\u0E14 " + MAX_STEPS } });
1844
+ if (typeof body.code === "string" && body.code.length > MAX_SOURCE_LENGTH)
1845
+ return reply.status(400).send({ error: { code: "source-limit", message: "Generated source \u0E21\u0E35\u0E02\u0E19\u0E32\u0E14\u0E43\u0E2B\u0E0D\u0E48\u0E40\u0E01\u0E34\u0E19\u0E44\u0E1B" } });
1846
+ const logs = [];
1847
+ const secretValues = [
1848
+ secrets?.email,
1849
+ secrets?.username,
1850
+ secrets?.password,
1851
+ secrets?.apiToken,
1852
+ process.env.LAZYSCOUT_TEST_EMAIL,
1853
+ process.env.LAZYSCOUT_TEST_USERNAME,
1854
+ process.env.LAZYSCOUT_TEST_PASSWORD,
1855
+ process.env.LAZYSCOUT_API_TOKEN
1856
+ ].filter((value) => Boolean(value));
1857
+ const addLog = (level, message, durationMs) => {
1858
+ if (logs.length < MAX_LOGS)
1859
+ logs.push({
1860
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1861
+ level,
1862
+ message: redactSensitiveText(message, secretValues),
1863
+ ...durationMs === void 0 ? {} : { durationMs }
1864
+ });
1865
+ };
1866
+ const persistLog = async (runStatus) => {
1867
+ if (!body.projectId)
1868
+ return;
1869
+ 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)}`));
1870
+ };
1871
+ const started = Date.now();
1872
+ addLog("info", "$ lazyscout test --case " + testCase.id);
1873
+ addLog("info", "Starting Playwright runner: " + testCase.title);
1874
+ addLog("info", "Test budget: " + MAX_STEPS + " steps \xB7 " + STEP_TIMEOUT_MS / 1e3 + "s per action \xB7 " + MAX_LOGS + " log lines");
1875
+ if (testCase.automationStatus === "manual") {
1876
+ addLog("warn", "Blocked: this case is marked manual and cannot be automated");
1877
+ await persistLog("blocked");
1878
+ return reply.send({ status: "blocked", framework, logs });
1879
+ }
1880
+ if (framework === "cypress") {
1881
+ addLog("warn", "Cypress code generation is available; local runner uses Playwright only.");
1882
+ await persistLog("unsupported");
1883
+ return reply.send({ status: "unsupported", framework, logs });
1884
+ }
1885
+ const active = { stopped: false };
1886
+ activeRuns.set(runId, active);
1887
+ let browser;
1888
+ let page;
1889
+ const capturedScreenshots = [];
1890
+ try {
1891
+ const launched = await launchBrowser();
1892
+ browser = launched.browser;
1893
+ active.browser = browser;
1894
+ if (active.stopped)
1895
+ throw new Error("Run stopped by user");
1896
+ const context = await browser.newContext({ viewport: { width: 1366, height: 900 } });
1897
+ context.setDefaultTimeout(STEP_TIMEOUT_MS);
1898
+ page = await context.newPage();
1899
+ if (typeof body.code === "string" && body.code.trim()) {
1900
+ addLog("info", "Running edited automation source");
1901
+ await executeEditedCode(page, body.code, testCase.id, capturedScreenshots, addLog, secrets);
1902
+ if (active.stopped)
1903
+ throw new Error("Run stopped by user");
1904
+ addLog("pass", "\u2713 edited source completed");
1905
+ } else
1906
+ for (const step of testCase.steps) {
1907
+ if (active.stopped)
1908
+ throw new Error("Run stopped by user");
1909
+ const stepStarted = Date.now();
1910
+ await executeStep(page, step, addLog, secrets);
1911
+ if (active.stopped)
1912
+ throw new Error("Run stopped by user");
1913
+ addLog("pass", `\u2713 ${step.type}`, Date.now() - stepStarted);
1914
+ }
1915
+ addLog("pass", `Completed ${testCase.id}`, Date.now() - started);
1916
+ const screenshots = withScreenshotStatus(capturedScreenshots, "passed");
1917
+ await persistLog("passed");
1918
+ return reply.send({
1919
+ status: "passed",
1920
+ framework,
1921
+ logs,
1922
+ screenshots,
1923
+ screenshot: screenshots.at(-1)
1924
+ });
1925
+ } catch (error) {
1926
+ const message = redactSensitiveText(error instanceof Error ? error.message : String(error), secretValues);
1927
+ if (active.stopped) {
1928
+ addLog("warn", "Run stopped by user", Date.now() - started);
1929
+ await persistLog("stopped");
1930
+ return reply.send({ status: "stopped", framework, logs });
1931
+ }
1932
+ addLog("fail", `\u2715 ${message}`, Date.now() - started);
1933
+ const screenshots = withScreenshotStatus(capturedScreenshots, "failed");
1934
+ await persistLog("failed");
1935
+ return reply.send({
1936
+ status: "failed",
1937
+ framework,
1938
+ logs,
1939
+ error: message,
1940
+ screenshots,
1941
+ screenshot: screenshots.at(-1)
1942
+ });
1943
+ } finally {
1944
+ activeRuns.delete(runId);
1945
+ await browser?.close().catch(() => void 0);
1946
+ }
1947
+ });
1948
+ }
1949
+ function withScreenshotStatus(screenshots, status) {
1950
+ return screenshots.map((screenshot) => ({ ...screenshot, status }));
1951
+ }
1952
+ async function executeEditedCode(page, source, testCaseId, capturedScreenshots, addLog, projectSecrets) {
1953
+ const lines = source.split(/\r?\n/);
1954
+ let executed = 0;
1955
+ for (const rawLine of lines) {
1956
+ const line = rawLine.trim().replace(/;$/, "");
1957
+ if (!line || line.startsWith("import ") || line.startsWith("test(") || line === "})" || line === "});")
1958
+ continue;
1959
+ if (line.startsWith("//"))
1960
+ continue;
1961
+ if (++executed > MAX_STEPS)
1962
+ throw new Error(`Edited source exceeds the ${MAX_STEPS} action limit`);
1963
+ const gotoMatch = line.match(new RegExp(`^await page\\.goto\\((${STRING_LITERAL})\\)$`));
1964
+ if (gotoMatch) {
1965
+ const url = parseStringLiteral(gotoMatch[1]);
1966
+ const checked = checkTargetUrl(url, config.urlPolicy);
1967
+ if (!checked.ok)
1968
+ throw new Error(checked.message);
1969
+ addLog("info", `\u2192 Navigating to ${redactUrl(checked.url.toString())}`);
1970
+ await page.goto(checked.url.toString(), { waitUntil: "domcontentloaded", timeout: STEP_TIMEOUT_MS });
1971
+ continue;
1972
+ }
1973
+ const waitMatch = line.match(/^await page\.waitForTimeout\((\d{1,5})\)$/);
1974
+ if (waitMatch) {
1975
+ const waitMs = Math.min(Number(waitMatch[1]), 5e3);
1976
+ addLog("info", `\u2192 Waiting ${waitMs}ms`);
1977
+ await page.waitForTimeout(waitMs);
1978
+ continue;
1979
+ }
1980
+ const screenshotMatch = line.match(/^await page\.screenshot\((.*)\)$/);
1981
+ if (screenshotMatch) {
1982
+ const screenshot = await captureRequestedScreenshot(page, screenshotMatch[1], testCaseId);
1983
+ capturedScreenshots.push(screenshot);
1984
+ addLog("pass", `Screenshot captured: ${screenshot.name}`);
1985
+ continue;
1986
+ }
1987
+ const clickMatch = line.match(/^await (page\..+)\.click\(\)$/);
1988
+ if (clickMatch) {
1989
+ const target = parseEditedLocator(page, clickMatch[1]);
1990
+ await ensureSafeClick(target.locator, target.label);
1991
+ addLog("info", `\u2192 Clicking ${target.label}`);
1992
+ await target.locator.click();
1993
+ continue;
1994
+ }
1995
+ const fillMatch = line.match(new RegExp(`^await (page\\..+)\\.fill\\((${STRING_LITERAL})\\)$`));
1996
+ if (fillMatch) {
1997
+ const target = parseEditedLocator(page, fillMatch[1]);
1998
+ addLog("info", `\u2192 Filling ${target.label}`);
1999
+ await target.locator.fill(resolveSecret(parseStringLiteral(fillMatch[2]), projectSecrets));
2000
+ continue;
2001
+ }
2002
+ const selectMatch = line.match(new RegExp(`^await (page\\..+)\\.selectOption\\((${STRING_LITERAL})\\)$`));
2003
+ if (selectMatch) {
2004
+ const target = parseEditedLocator(page, selectMatch[1]);
2005
+ const option = parseStringLiteral(selectMatch[2]);
2006
+ addLog("info", `\u2192 Selecting an option in ${target.label}`);
2007
+ await target.locator.selectOption(option);
2008
+ continue;
2009
+ }
2010
+ const visibleMatch = line.match(/^await expect\((page\..+)\)\.toBeVisible\(\)$/);
2011
+ if (visibleMatch) {
2012
+ const target = parseEditedLocator(page, visibleMatch[1]);
2013
+ if (!await target.locator.isVisible())
2014
+ throw new Error(`Expected ${target.label} to be visible`);
2015
+ addLog("pass", `Element visible: ${target.label}`);
2016
+ continue;
2017
+ }
2018
+ const textMatch = line.match(new RegExp(`^await expect\\((page(?:\\..+)?)\\)\\.toContainText\\((${STRING_LITERAL})\\)$`));
2019
+ if (textMatch) {
2020
+ const expected = parseStringLiteral(textMatch[2]);
2021
+ const actual = textMatch[1] === "page" ? await page.locator("body").innerText() : await parseEditedLocator(page, textMatch[1]).locator.innerText();
2022
+ if (!actual.includes(expected))
2023
+ throw new Error(`Expected text was not found: ${expected}`);
2024
+ addLog("pass", "Text assertion passed");
2025
+ continue;
2026
+ }
2027
+ const urlMatch = line.match(new RegExp(`^await expect\\(page\\)\\.toHaveURL\\(new RegExp\\((${STRING_LITERAL})\\)\\)$`));
2028
+ if (urlMatch) {
2029
+ const expected = parseStringLiteral(urlMatch[1]);
2030
+ if (!page.url().includes(expected))
2031
+ throw new Error(`URL did not contain ${expected}`);
2032
+ addLog("pass", `URL assertion passed: ${redactUrl(page.url())}`);
2033
+ continue;
2034
+ }
2035
+ throw new Error(`Unsupported edited Playwright statement: ${line.slice(0, 120)}`);
2036
+ }
2037
+ if (executed === 0)
2038
+ throw new Error("Edited source does not contain a supported Playwright action");
2039
+ }
2040
+ function parseScreenshotOptions(source) {
2041
+ const value = source.trim();
2042
+ if (!value)
2043
+ return { fullPage: false, type: "png" };
2044
+ const objectMatch = value.match(/^\{([\s\S]*)\}$/);
2045
+ if (!objectMatch)
2046
+ throw new Error("page.screenshot() accepts an options object only");
2047
+ let path;
2048
+ let fullPage = false;
2049
+ let type;
2050
+ let quality;
2051
+ for (const entry of splitOptionList(objectMatch[1])) {
2052
+ const separator = entry.indexOf(":");
2053
+ if (separator < 1)
2054
+ throw new Error(`Unsupported screenshot option: ${entry.slice(0, 80)}`);
2055
+ const key = entry.slice(0, separator).trim();
2056
+ const raw = entry.slice(separator + 1).trim();
2057
+ if (key === "path")
2058
+ path = parseSourceString(raw);
2059
+ else if (key === "fullPage" && /^(true|false)$/.test(raw))
2060
+ fullPage = raw === "true";
2061
+ else if (key === "type") {
2062
+ const parsedType = parseSourceString(raw);
2063
+ if (parsedType !== "png" && parsedType !== "jpeg")
2064
+ throw new Error("Screenshot type must be png or jpeg");
2065
+ type = parsedType;
2066
+ } else if (key === "quality" && /^\d{1,3}$/.test(raw))
2067
+ quality = Math.min(100, Math.max(1, Number(raw)));
2068
+ else
2069
+ throw new Error(`Unsupported screenshot option: ${key.slice(0, 40)}`);
2070
+ }
2071
+ const inferredType = path && /\.jpe?g$/i.test(path) ? "jpeg" : "png";
2072
+ return { path, fullPage, type: type ?? inferredType, quality };
2073
+ }
2074
+ function splitOptionList(value) {
2075
+ const entries = [];
2076
+ let current = "";
2077
+ let quote = "";
2078
+ let escaped = false;
2079
+ for (const character of value) {
2080
+ if (escaped) {
2081
+ current += character;
2082
+ escaped = false;
2083
+ continue;
2084
+ }
2085
+ if (character === "\\") {
2086
+ current += character;
2087
+ escaped = true;
2088
+ continue;
2089
+ }
2090
+ if (quote) {
2091
+ current += character;
2092
+ if (character === quote)
2093
+ quote = "";
2094
+ continue;
2095
+ }
2096
+ if (character === '"' || character === "'") {
2097
+ quote = character;
2098
+ current += character;
2099
+ continue;
2100
+ }
2101
+ if (character === ",") {
2102
+ if (current.trim())
2103
+ entries.push(current.trim());
2104
+ current = "";
2105
+ continue;
2106
+ }
2107
+ current += character;
2108
+ }
2109
+ if (quote || escaped)
2110
+ throw new Error("Screenshot options contain an incomplete string");
2111
+ if (current.trim())
2112
+ entries.push(current.trim());
2113
+ return entries;
2114
+ }
2115
+ function parseSourceString(value) {
2116
+ if (value.startsWith('"'))
2117
+ return parseStringLiteral(value);
2118
+ if (!value.startsWith("'") || !value.endsWith("'"))
2119
+ throw new Error("Screenshot strings must use quotes");
2120
+ const inner = value.slice(1, -1);
2121
+ let parsed = "";
2122
+ for (let index = 0; index < inner.length; index++) {
2123
+ const character = inner[index];
2124
+ if (character !== "\\") {
2125
+ parsed += character;
2126
+ continue;
2127
+ }
2128
+ const next = inner[++index];
2129
+ if (next === void 0)
2130
+ throw new Error("Screenshot string contains an incomplete escape");
2131
+ parsed += next === "n" ? "\n" : next === "r" ? "\r" : next === "t" ? " " : next;
2132
+ }
2133
+ return parsed;
2134
+ }
2135
+ async function captureRequestedScreenshot(page, source, testCaseId) {
2136
+ const options = parseScreenshotOptions(source);
2137
+ const image = await page.screenshot({
2138
+ type: options.type,
2139
+ fullPage: options.fullPage,
2140
+ ...options.type === "jpeg" && options.quality ? { quality: options.quality } : {}
2141
+ });
2142
+ const extension = options.type === "jpeg" ? "jpg" : "png";
2143
+ const requestedName = options.path?.split(/[\\/]/).pop()?.replace(/\.[^.]+$/, "");
2144
+ const safeName = (requestedName || `${testCaseId}-${Date.now()}`).replace(/[^\p{L}\p{N}._-]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 100);
2145
+ return {
2146
+ name: `${safeName || `screenshot-${Date.now()}`}.${extension}`,
2147
+ dataUrl: `data:image/${options.type};base64,${image.toString("base64")}`,
2148
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
2149
+ testCaseId,
2150
+ status: "passed"
2151
+ };
2152
+ }
2153
+ var STRING_LITERAL = '"(?:\\\\.|[^"\\\\])*"';
2154
+ function parseStringLiteral(value) {
2155
+ const parsed = JSON.parse(value);
2156
+ if (typeof parsed !== "string")
2157
+ throw new Error("Edited Playwright arguments must be strings");
2158
+ return parsed;
2159
+ }
2160
+ function parseEditedLocator(page, expression) {
2161
+ const roleMatch = expression.match(new RegExp(`^page\\.getByRole\\((${STRING_LITERAL}),\\s*\\{\\s*name:\\s*(${STRING_LITERAL})\\s*\\}\\)$`));
2162
+ if (roleMatch) {
2163
+ const role = parseStringLiteral(roleMatch[1]);
2164
+ const name = parseStringLiteral(roleMatch[2]);
2165
+ return { locator: page.getByRole(role, { name }), label: name };
2166
+ }
2167
+ for (const [method, create] of [
2168
+ ["getByLabel", (value) => page.getByLabel(value)],
2169
+ ["getByPlaceholder", (value) => page.getByPlaceholder(value)],
2170
+ ["getByText", (value) => page.getByText(value)],
2171
+ ["locator", (value) => page.locator(value)]
2172
+ ]) {
2173
+ const match = expression.match(new RegExp(`^page\\.${method}\\((${STRING_LITERAL})\\)$`));
2174
+ if (match) {
2175
+ const value = parseStringLiteral(match[1]);
2176
+ return { locator: create(value), label: value };
2177
+ }
2178
+ }
2179
+ throw new Error(`Unsupported Playwright locator: ${expression.slice(0, 120)}`);
2180
+ }
2181
+ async function executeStep(page, step, addLog, secrets) {
2182
+ switch (step.type) {
2183
+ case "navigate":
2184
+ const checked = checkTargetUrl(step.url, config.urlPolicy);
2185
+ if (!checked.ok)
2186
+ throw new Error(checked.message);
2187
+ addLog("info", "Target URL found: " + redactUrl(checked.url.toString()));
2188
+ addLog("info", "\u2192 Navigating to " + redactUrl(checked.url.toString()));
2189
+ await page.goto(checked.url.toString(), { waitUntil: "domcontentloaded", timeout: STEP_TIMEOUT_MS });
2190
+ addLog("pass", "Page ready: " + (new URL(page.url()).pathname || "/"));
2191
+ addLog("info", "Continuing with the next test step");
2192
+ return;
2193
+ case "click": {
2194
+ const name = step.target.name ?? step.target.text ?? step.target.cssSelector ?? "target";
2195
+ const target = locator(page, step.target);
2196
+ await ensureSafeClick(target, name);
2197
+ addLog("info", "Control found: " + name);
2198
+ addLog("info", "\u2192 Clicking " + name);
2199
+ await target.click();
2200
+ addLog("pass", "Action completed: " + name);
2201
+ return;
2202
+ }
2203
+ case "fill": {
2204
+ const name = step.target.name ?? step.target.label ?? "field";
2205
+ const value = resolveSecret(step.value, secrets);
2206
+ addLog("info", "Input found: " + name);
2207
+ addLog("info", "\u2192 Filling " + name);
2208
+ await locator(page, step.target).fill(value);
2209
+ addLog("pass", "Input ready: " + name);
2210
+ return;
2211
+ }
2212
+ case "select":
2213
+ addLog("info", "Dropdown found: " + (step.target.name ?? step.target.label ?? "select"));
2214
+ await locator(page, step.target).selectOption(step.option);
2215
+ addLog("pass", "Selected option: " + step.option);
2216
+ return;
2217
+ case "assertVisible":
2218
+ await locator(page, step.target).isVisible().then((visible) => {
2219
+ if (!visible)
2220
+ throw new Error("Expected element is not visible");
2221
+ addLog("pass", "Element visible: " + (step.target.name ?? step.target.label ?? "target"));
2222
+ });
2223
+ return;
2224
+ case "assertText": {
2225
+ const bodyText = await page.locator("body").innerText();
2226
+ if (!bodyText.includes(step.text))
2227
+ throw new Error("Expected text was not found: " + step.text);
2228
+ addLog("pass", 'Assertion passed: page contains "' + step.text + '"');
2229
+ return;
2230
+ }
2231
+ case "assertUrl":
2232
+ if (!page.url().includes(step.urlContains))
2233
+ throw new Error("URL does not contain " + step.urlContains);
2234
+ addLog("pass", "URL assertion passed: " + redactUrl(page.url()));
2235
+ return;
2236
+ case "manual":
2237
+ throw new Error("Manual step requires Tester review");
2238
+ }
2239
+ }
2240
+ function resolveSecret(value, projectSecrets) {
2241
+ const secrets = {
2242
+ "{{TEST_EMAIL}}": projectSecrets?.email ?? process.env.LAZYSCOUT_TEST_EMAIL,
2243
+ "{{TEST_USERNAME}}": projectSecrets?.username ?? process.env.LAZYSCOUT_TEST_USERNAME,
2244
+ "{{TEST_PASSWORD}}": projectSecrets?.password ?? process.env.LAZYSCOUT_TEST_PASSWORD,
2245
+ "{{API_TOKEN}}": projectSecrets?.apiToken ?? process.env.LAZYSCOUT_API_TOKEN
2246
+ };
2247
+ const secret = secrets[value];
2248
+ if (secret === void 0 && value in secrets)
2249
+ throw new Error("Required secret is not configured for " + value);
2250
+ return secret ?? value;
2251
+ }
2252
+ function locator(page, target) {
2253
+ if (target.role && target.name)
2254
+ return page.getByRole(target.role, { name: target.name });
2255
+ if (target.label)
2256
+ return page.getByLabel(target.label);
2257
+ if (target.placeholder)
2258
+ return page.getByPlaceholder(target.placeholder);
2259
+ if (target.text)
2260
+ return page.getByText(target.text);
2261
+ return page.locator(target.cssSelector ?? "");
2262
+ }
2263
+ async function ensureSafeClick(target, fallbackLabel) {
2264
+ const labels = await Promise.all([
2265
+ target.getAttribute("aria-label").catch(() => null),
2266
+ target.getAttribute("title").catch(() => null),
2267
+ target.getAttribute("name").catch(() => null),
2268
+ target.getAttribute("id").catch(() => null),
2269
+ target.innerText().catch(() => "")
2270
+ ]);
2271
+ if (isDestructiveLabel(fallbackLabel, ...labels.map((value) => value ?? void 0))) {
2272
+ throw new Error(`Blocked destructive action: ${fallbackLabel}`);
2273
+ }
2274
+ }
2275
+
2276
+ // ../server/dist/routes/apiCheckRun.js
2277
+ var SAFE_API_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
2278
+ function registerApiCheckRunRoute(app) {
2279
+ app.post("/api/api-check/run", async (request, reply) => {
2280
+ const body = request.body;
2281
+ const check = body.apiCheck;
2282
+ if (!check?.url)
2283
+ return reply.status(400).send({ error: { code: "invalid-api-check", message: "\u0E44\u0E21\u0E48\u0E1E\u0E1A API Check" } });
2284
+ const target = checkTargetUrl(check.url, config.urlPolicy);
2285
+ if (!target.ok)
2286
+ return reply.status(400).send({ error: { code: target.code, message: target.message } });
2287
+ const method = check.method.toUpperCase();
2288
+ if (!SAFE_API_METHODS.has(method))
2289
+ return reply.status(400).send({
2290
+ error: {
2291
+ code: "unsafe-api-method",
2292
+ message: `${method} API checks are observation-only. LazyScout runs only GET, HEAD and OPTIONS automatically.`
2293
+ }
2294
+ });
2295
+ const token = body.secrets?.apiToken ?? process.env.LAZYSCOUT_API_TOKEN;
2296
+ if (check.status === "needs-auth" && !token)
2297
+ return reply.send({
2298
+ status: "needs-auth",
2299
+ durationMs: 0,
2300
+ message: "API \u0E19\u0E35\u0E49\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E0A\u0E49 token \u0E15\u0E31\u0E49\u0E07\u0E04\u0E48\u0E32 LAZYSCOUT_API_TOKEN \u0E01\u0E48\u0E2D\u0E19\u0E23\u0E31\u0E19"
2301
+ });
2302
+ const started = Date.now();
2303
+ try {
2304
+ const response = await fetch(target.url, {
2305
+ method,
2306
+ headers: token ? { Authorization: `Bearer ${token}` } : void 0,
2307
+ signal: AbortSignal.timeout(2e4)
2308
+ });
2309
+ const durationMs = Date.now() - started;
2310
+ const passed = check.expectedStatus === void 0 ? response.ok : response.status === check.expectedStatus;
2311
+ return reply.send({
2312
+ status: passed ? "passed" : "failed",
2313
+ statusCode: response.status,
2314
+ durationMs,
2315
+ message: passed ? `API ${check.method} returned expected HTTP ${response.status}` : `API ${check.method} returned HTTP ${response.status}`
2316
+ });
2317
+ } catch (error) {
2318
+ return reply.send({
2319
+ status: "failed",
2320
+ durationMs: Date.now() - started,
2321
+ message: redactSensitiveText(error instanceof Error ? error.message : String(error), token ? [token] : [])
2322
+ });
2323
+ }
2324
+ });
2325
+ }
2326
+
2327
+ // ../server/dist/routes/loadTest.js
2328
+ function registerLoadTestRoute(app) {
2329
+ app.post("/api/load-test/run", async (request, reply) => {
2330
+ const body = request.body;
2331
+ if (!body.confirmed)
2332
+ return reply.status(400).send({
2333
+ error: { code: "confirmation-required", message: "Confirm that you are authorized to load test this target." }
2334
+ });
2335
+ let url;
2336
+ try {
2337
+ url = new URL(body.url ?? "");
2338
+ } catch {
2339
+ return reply.status(400).send({ error: { code: "invalid-url", message: "A valid HTTP URL is required." } });
2340
+ }
2341
+ if (!["http:", "https:"].includes(url.protocol))
2342
+ return reply.status(400).send({ error: { code: "invalid-url", message: "Only HTTP and HTTPS URLs are supported." } });
2343
+ const virtualUsers = Math.max(1, Math.min(Number(body.virtualUsers) || 1, 20));
2344
+ const requestsPerUser = Math.max(1, Math.min(Number(body.requestsPerUser) || 1, 100));
2345
+ const intervalMs = Math.max(0, Math.min(Number(body.intervalMs) || 0, 1e4));
2346
+ const timings = [];
2347
+ const errors = [];
2348
+ const requests = [];
2349
+ let requestSequence = 0;
2350
+ const started = Date.now();
2351
+ async function worker(virtualUser) {
2352
+ for (let count = 0; count < requestsPerUser; count++) {
2353
+ const id = ++requestSequence;
2354
+ const requestStarted = Date.now();
2355
+ try {
2356
+ const response2 = await fetch(url, { signal: AbortSignal.timeout(15e3), redirect: "follow" });
2357
+ const durationMs = Date.now() - requestStarted;
2358
+ const responseBytes = Number(response2.headers.get("content-length")) || void 0;
2359
+ timings.push(durationMs);
2360
+ if (!response2.ok)
2361
+ errors.push(`HTTP ${response2.status} ${response2.statusText}`.trim());
2362
+ requests.push({
2363
+ id,
2364
+ virtualUser,
2365
+ iteration: count + 1,
2366
+ method: "GET",
2367
+ url: url.toString(),
2368
+ finalUrl: response2.url,
2369
+ statusCode: response2.status,
2370
+ statusText: response2.statusText,
2371
+ durationMs,
2372
+ passed: response2.ok,
2373
+ responseBytes
2374
+ });
2375
+ } catch (error) {
2376
+ const durationMs = Date.now() - requestStarted;
2377
+ const message = error instanceof Error ? error.message : String(error);
2378
+ timings.push(durationMs);
2379
+ errors.push(message);
2380
+ requests.push({
2381
+ id,
2382
+ virtualUser,
2383
+ iteration: count + 1,
2384
+ method: "GET",
2385
+ url: url.toString(),
2386
+ durationMs,
2387
+ passed: false,
2388
+ error: message
2389
+ });
2390
+ }
2391
+ if (intervalMs && count < requestsPerUser - 1)
2392
+ await new Promise((resolve3) => setTimeout(resolve3, intervalMs));
2393
+ }
2394
+ }
2395
+ await Promise.all(Array.from({ length: virtualUsers }, (_, index) => worker(index + 1)));
2396
+ const total = timings.length;
2397
+ const failed = errors.length;
2398
+ const duration = Math.max(Date.now() - started, 1);
2399
+ const response = {
2400
+ total,
2401
+ passed: total - failed,
2402
+ failed,
2403
+ averageMs: total ? Math.round(timings.reduce((sum, value) => sum + value, 0) / total) : 0,
2404
+ minMs: total ? Math.min(...timings) : 0,
2405
+ maxMs: total ? Math.max(...timings) : 0,
2406
+ requestsPerSecond: Number((total / (duration / 1e3)).toFixed(2)),
2407
+ errors: [...new Set(errors)].slice(0, 10),
2408
+ requests: requests.sort((left, right) => left.id - right.id)
2409
+ };
2410
+ return reply.send(response);
2411
+ });
2412
+ }
2413
+
2414
+ // ../server/dist/routes/versions.js
2415
+ import { spawn } from "node:child_process";
2416
+ import { access } from "node:fs/promises";
2417
+ import { dirname as dirname2, join as join2 } from "node:path";
2418
+ var PACKAGE_NAME = "lazyscout";
2419
+ var REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}`;
2420
+ var VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
2421
+ var CACHE_TTL_MS = 6e4;
2422
+ var registryCache;
2423
+ var installInProgress = false;
2424
+ function compareVersions(left, right) {
2425
+ const [leftMain, leftPre] = left.split("-", 2);
2426
+ const [rightMain, rightPre] = right.split("-", 2);
2427
+ const leftParts = leftMain.split(".").map(Number);
2428
+ const rightParts = rightMain.split(".").map(Number);
2429
+ for (let index = 0; index < 3; index++) {
2430
+ const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
2431
+ if (difference !== 0)
2432
+ return difference;
2433
+ }
2434
+ if (!leftPre && rightPre)
2435
+ return 1;
2436
+ if (leftPre && !rightPre)
2437
+ return -1;
2438
+ return (leftPre ?? "").localeCompare(rightPre ?? "", void 0, { numeric: true });
2439
+ }
2440
+ async function fetchPublishedVersions(force = false) {
2441
+ if (!force && registryCache && registryCache.expiresAt > Date.now())
2442
+ return registryCache.value;
2443
+ const response = await fetch(REGISTRY_URL, {
2444
+ headers: { Accept: "application/vnd.npm.install-v1+json" },
2445
+ signal: AbortSignal.timeout(8e3)
2446
+ });
2447
+ if (!response.ok)
2448
+ throw new Error(`npm Registry returned HTTP ${response.status}.`);
2449
+ const body = await response.json();
2450
+ const tags = body["dist-tags"] ?? {};
2451
+ const versions = Object.keys(body.versions ?? {}).filter((version) => VERSION_PATTERN.test(version)).sort((left, right) => compareVersions(right, left)).slice(0, 20).map((version) => ({
2452
+ version,
2453
+ tags: Object.entries(tags).filter(([, taggedVersion]) => taggedVersion === version).map(([tag]) => tag),
2454
+ publishedAt: body.time?.[version]
2455
+ }));
2456
+ const value = { latestVersion: tags.latest, versions };
2457
+ registryCache = { expiresAt: Date.now() + CACHE_TTL_MS, value };
2458
+ return value;
2459
+ }
2460
+ async function findNpmCli() {
2461
+ const candidates = [
2462
+ process.env.npm_execpath,
2463
+ join2(dirname2(process.execPath), "node_modules", "npm", "bin", "npm-cli.js"),
2464
+ process.env.APPDATA ? join2(process.env.APPDATA, "npm", "node_modules", "npm", "bin", "npm-cli.js") : void 0,
2465
+ "/usr/lib/node_modules/npm/bin/npm-cli.js",
2466
+ "/usr/local/lib/node_modules/npm/bin/npm-cli.js"
2467
+ ].filter((value) => Boolean(value?.endsWith(".js")));
2468
+ for (const candidate of candidates) {
2469
+ try {
2470
+ await access(candidate);
2471
+ return candidate;
2472
+ } catch {
2473
+ }
2474
+ }
2475
+ throw new Error("Could not locate npm-cli.js. Copy the install command and run it in a terminal instead.");
2476
+ }
2477
+ async function runNpmInstall(version) {
2478
+ const npmCli = await findNpmCli();
2479
+ return new Promise((resolve3, reject) => {
2480
+ const commandArgs = [npmCli, "install", "--global", `${PACKAGE_NAME}@${version}`, "--no-audit", "--no-fund"];
2481
+ const child = spawn(process.execPath, commandArgs, {
2482
+ windowsHide: true,
2483
+ stdio: ["ignore", "pipe", "pipe"]
2484
+ });
2485
+ let output = "";
2486
+ let settled = false;
2487
+ const append = (chunk) => {
2488
+ output = `${output}${chunk.toString()}`.slice(-12e3);
2489
+ };
2490
+ child.stdout.on("data", append);
2491
+ child.stderr.on("data", append);
2492
+ const timeout = setTimeout(() => {
2493
+ if (settled)
2494
+ return;
2495
+ settled = true;
2496
+ child.kill();
2497
+ reject(new Error("npm installation timed out after 5 minutes."));
2498
+ }, 3e5);
2499
+ child.once("error", (error) => {
2500
+ if (settled)
2501
+ return;
2502
+ settled = true;
2503
+ clearTimeout(timeout);
2504
+ reject(error);
2505
+ });
2506
+ child.once("close", (code) => {
2507
+ if (settled)
2508
+ return;
2509
+ settled = true;
2510
+ clearTimeout(timeout);
2511
+ if (code === 0)
2512
+ resolve3(output.trim());
2513
+ else
2514
+ reject(new Error(output.trim() || `npm exited with code ${code ?? "unknown"}.`));
2515
+ });
2516
+ });
2517
+ }
2518
+ function registerVersionRoutes(app, currentVersion) {
2519
+ app.get("/api/versions", async (_request, reply) => {
2520
+ try {
2521
+ const published = await fetchPublishedVersions();
2522
+ return reply.send({
2523
+ packageName: PACKAGE_NAME,
2524
+ currentVersion,
2525
+ latestVersion: published.latestVersion,
2526
+ updateAvailable: Boolean(published.latestVersion && compareVersions(published.latestVersion, currentVersion) > 0),
2527
+ registryAvailable: true,
2528
+ versions: published.versions
2529
+ });
2530
+ } catch (error) {
2531
+ return reply.send({
2532
+ packageName: PACKAGE_NAME,
2533
+ currentVersion,
2534
+ updateAvailable: false,
2535
+ registryAvailable: false,
2536
+ versions: VERSION_PATTERN.test(currentVersion) ? [{ version: currentVersion, tags: ["current"] }] : [],
2537
+ error: error instanceof Error ? error.message : String(error)
2538
+ });
2539
+ }
2540
+ });
2541
+ app.post("/api/versions/install", async (request, reply) => {
2542
+ const body = request.body ?? {};
2543
+ if (typeof body.version !== "string" || !VERSION_PATTERN.test(body.version)) {
2544
+ return reply.status(400).send({
2545
+ error: { code: "invalid-version", message: "Select a valid published LazyScout version." }
2546
+ });
2547
+ }
2548
+ if (installInProgress) {
2549
+ return reply.status(409).send({
2550
+ error: { code: "install-in-progress", message: "Another LazyScout installation is still running." }
2551
+ });
2552
+ }
2553
+ installInProgress = true;
2554
+ try {
2555
+ const published = await fetchPublishedVersions(true);
2556
+ if (!published.versions.some((item) => item.version === body.version)) {
2557
+ return reply.status(400).send({
2558
+ error: { code: "unknown-version", message: "That version is not available from npm Registry." }
2559
+ });
2560
+ }
2561
+ const output = await runNpmInstall(body.version);
2562
+ return reply.send({
2563
+ installedVersion: body.version,
2564
+ command: `npm install -g ${PACKAGE_NAME}@${body.version}`,
2565
+ output
2566
+ });
2567
+ } catch (error) {
2568
+ const message = error instanceof Error ? error.message : String(error);
2569
+ return reply.status(500).send({
2570
+ error: {
2571
+ code: "install-failed",
2572
+ message: `Could not install LazyScout v${body.version}.`,
2573
+ hint: message
2574
+ }
2575
+ });
2576
+ } finally {
2577
+ installInProgress = false;
2578
+ }
2579
+ });
2580
+ }
2581
+
2582
+ // ../server/dist/routes/workspace.js
2583
+ function registerWorkspaceRoutes(app, root) {
2584
+ app.get("/api/workspace", async () => ({ root, projects: await listProjects(root) }));
2585
+ app.post("/api/workspace/open", async (_request, reply) => {
2586
+ await openWorkspace(root);
2587
+ return reply.send({ opened: true, root });
2588
+ });
2589
+ app.put("/api/workspace/projects/:projectId", async (request, reply) => {
2590
+ const project = request.body;
2591
+ if (!project || project.id !== request.params.projectId)
2592
+ return reply.status(400).send({ error: { code: "invalid-project", message: "Project ID does not match." } });
2593
+ await saveProject(root, project);
2594
+ return reply.send({ saved: true });
2595
+ });
2596
+ app.delete("/api/workspace/projects/:projectId", async (request, reply) => {
2597
+ await deleteProject(root, request.params.projectId);
2598
+ return reply.send({ deleted: true });
2599
+ });
2600
+ app.get("/api/workspace/projects/:projectId/screenshots", async (request) => readScreenshots(root, request.params.projectId));
2601
+ app.post("/api/workspace/projects/:projectId/screenshots", async (request) => saveScreenshot(root, request.params.projectId, request.body));
2602
+ app.get("/api/workspace/projects/:projectId/screenshots/:name", async (request, reply) => {
2603
+ const image = await screenshotFile(root, request.params.projectId, request.params.name);
2604
+ const contentType = request.params.name.toLowerCase().endsWith(".png") ? "image/png" : "image/jpeg";
2605
+ return reply.header("Content-Type", contentType).header("Cache-Control", "no-store").send(image);
2606
+ });
2607
+ app.delete("/api/workspace/projects/:projectId/screenshots/:name", async (request, reply) => {
2608
+ await deleteScreenshot(root, request.params.projectId, request.params.name);
2609
+ return reply.send({ deleted: true });
2610
+ });
2611
+ app.get("/api/workspace/projects/:projectId/bugs", async (request) => listBugReports(root, request.params.projectId));
2612
+ app.put("/api/workspace/projects/:projectId/bugs/:bugId", async (request, reply) => {
2613
+ const report = request.body;
2614
+ if (!report || report.id !== request.params.bugId)
2615
+ return reply.status(400).send({ error: { code: "invalid-bug", message: "Bug ID does not match." } });
2616
+ await saveBugReport(root, request.params.projectId, report);
2617
+ return reply.send({ saved: true });
2618
+ });
2619
+ app.delete("/api/workspace/projects/:projectId/bugs/:bugId", async (request, reply) => {
2620
+ await deleteBugReport(root, request.params.projectId, request.params.bugId);
2621
+ return reply.send({ deleted: true });
2622
+ });
2623
+ app.get("/api/workspace/projects/:projectId/automation", async (request) => readAutomation(root, request.params.projectId));
2624
+ app.put("/api/workspace/projects/:projectId/automation", async (request, reply) => {
2625
+ await saveAutomation(root, request.params.projectId, request.body);
2626
+ return reply.send({ saved: true });
2627
+ });
2628
+ app.post("/api/workspace/projects/:projectId/reports", async (request, reply) => {
2629
+ const body = request.body;
2630
+ if (!body?.html)
2631
+ return reply.status(400).send({ error: { code: "invalid-report", message: "Report HTML is required." } });
2632
+ const name = await saveReport(root, request.params.projectId, body.name ?? "quality-report.html", body.html);
2633
+ return reply.send({ saved: true, name });
2634
+ });
2635
+ }
2636
+
1213
2637
  // ../server/dist/app.js
1214
2638
  function buildApp(options = {}) {
1215
2639
  const app = Fastify({
1216
2640
  logger: { level: options.logLevel ?? process.env.LOG_LEVEL ?? "info" },
1217
- // การ crawl ใช้เวลานาน จึงต้องยืด timeout ของ request ให้พอ
1218
2641
  connectionTimeout: 0,
1219
2642
  bodyLimit: 10 * 1024 * 1024
1220
2643
  });
1221
- app.get("/api/health", async () => ({ status: "ok" }));
2644
+ const appVersion = options.appVersion ?? process.env.npm_package_version ?? "0.0.0-dev";
2645
+ const workspaceRoot = resolveWorkspaceRoot(options.workspaceRoot);
2646
+ app.get("/api/health", async () => ({ status: "ok", version: appVersion, workspaceRoot }));
1222
2647
  registerAnalyzeRoute(app);
1223
2648
  registerExportCsvRoute(app);
2649
+ registerAutomationRunRoute(app, workspaceRoot);
2650
+ registerApiCheckRunRoute(app);
2651
+ registerLoadTestRoute(app);
2652
+ registerVersionRoutes(app, appVersion);
2653
+ registerWorkspaceRoutes(app, workspaceRoot);
1224
2654
  if (options.staticDir) {
1225
2655
  app.register(fastifyStatic, { root: options.staticDir });
1226
2656
  app.setNotFoundHandler(async (request, reply) => {
@@ -1236,27 +2666,33 @@ function buildApp(options = {}) {
1236
2666
  }
1237
2667
 
1238
2668
  // src/openInBrowser.ts
1239
- import { spawn } from "node:child_process";
2669
+ import { spawn as spawn2 } from "node:child_process";
1240
2670
  async function openInBrowser(url) {
1241
2671
  const [command, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
1242
2672
  try {
1243
- const child = spawn(command, args, { stdio: "ignore", detached: true });
2673
+ const child = spawn2(command, args, { stdio: "ignore", detached: true });
1244
2674
  child.on("error", () => void 0);
1245
2675
  child.unref();
1246
2676
  } catch {
1247
2677
  }
1248
2678
  }
1249
2679
 
2680
+ // src/version.ts
2681
+ var VERSION = true ? "0.3.0" : "0.0.0-dev";
2682
+
1250
2683
  // src/commands/serve.ts
1251
2684
  var DEFAULT_PORT = 4321;
1252
- var WEB_DIR = join(dirname(fileURLToPath(import.meta.url)), "web");
2685
+ var WEB_DIR = join3(dirname3(fileURLToPath(import.meta.url)), "web");
1253
2686
  async function runServe(options) {
1254
- const app = buildApp({ staticDir: WEB_DIR, logLevel: "warn" });
2687
+ const workspaceRoot = resolveWorkspaceRoot(options.workspace);
2688
+ await ensureWorkspace(workspaceRoot);
2689
+ const app = buildApp({ staticDir: WEB_DIR, logLevel: "warn", appVersion: VERSION, workspaceRoot });
1255
2690
  const port = await listenOnFreePort(app, options.port ?? DEFAULT_PORT);
1256
2691
  const url = `http://localhost:${port}`;
1257
2692
  console.log(`
1258
- LazyScout \u0E1E\u0E23\u0E49\u0E2D\u0E21\u0E43\u0E0A\u0E49\u0E07\u0E32\u0E19\u0E41\u0E25\u0E49\u0E27\u0E17\u0E35\u0E48 ${url}`);
1259
- console.log(" \u0E01\u0E14 Ctrl+C \u0E40\u0E1E\u0E37\u0E48\u0E2D\u0E1B\u0E34\u0E14\n");
2693
+ \u{1F680} LazyScout is now available. ${url}`);
2694
+ console.log(` \u{1F4C1} Workspace: ${workspaceRoot}`);
2695
+ console.log(" Press Ctrl+C to exit \n");
1260
2696
  if (options.open) await openInBrowser(url);
1261
2697
  }
1262
2698
  async function listenOnFreePort(app, startPort) {
@@ -1269,36 +2705,53 @@ async function listenOnFreePort(app, startPort) {
1269
2705
  if (code !== "EADDRINUSE") throw error;
1270
2706
  }
1271
2707
  }
1272
- throw new Error(`\u0E2B\u0E32\u0E1E\u0E2D\u0E23\u0E4C\u0E15\u0E27\u0E48\u0E32\u0E07\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 ${startPort}-${startPort + 19}`);
2708
+ throw new Error(`No free port found in the specified range ${startPort}-${startPort + 19}`);
1273
2709
  }
1274
2710
 
1275
- // src/version.ts
1276
- var VERSION = true ? "0.1.0" : "0.0.0-dev";
1277
-
1278
2711
  // src/index.ts
1279
2712
  var HELP = `
1280
- LazyScout ${VERSION} \u2014 \u0E27\u0E34\u0E40\u0E04\u0E23\u0E32\u0E30\u0E2B\u0E4C\u0E40\u0E27\u0E47\u0E1A\u0E44\u0E0B\u0E15\u0E4C\u0E41\u0E25\u0E49\u0E27\u0E2A\u0E23\u0E49\u0E32\u0E07 Draft Test Case \u0E43\u0E2B\u0E49 Software Tester
2713
+ LazyScout ${VERSION} \u2014 Analyze websites and generate draft test cases for software testers.
2714
+
2715
+ Usage
2716
+ npx lazyscout
2717
+ Open the LazyScout web interface. Recommended.
1281
2718
 
1282
- \u0E01\u0E32\u0E23\u0E43\u0E0A\u0E49\u0E07\u0E32\u0E19
1283
- npx lazyscout \u0E40\u0E1B\u0E34\u0E14\u0E2B\u0E19\u0E49\u0E32\u0E40\u0E27\u0E47\u0E1A\u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E43\u0E0A\u0E49\u0E07\u0E32\u0E19 (\u0E41\u0E19\u0E30\u0E19\u0E33)
1284
- npx lazyscout scan <url> \u0E2A\u0E41\u0E01\u0E19\u0E41\u0E25\u0E49\u0E27\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E1C\u0E25\u0E40\u0E1B\u0E47\u0E19\u0E44\u0E1F\u0E25\u0E4C \u0E44\u0E21\u0E48\u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E34\u0E14\u0E40\u0E1A\u0E23\u0E32\u0E27\u0E4C\u0E40\u0E0B\u0E2D\u0E23\u0E4C
2719
+ npx lazyscout scan <url>
2720
+ Scan a website and save the results to files without opening the LazyScout interface.
1285
2721
 
1286
- \u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E02\u0E2D\u0E07 scan
1287
- --csv <\u0E44\u0E1F\u0E25\u0E4C> \u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01 test case + test data \u0E40\u0E1B\u0E47\u0E19 CSV (\u0E04\u0E48\u0E32\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19: lazyscout-testcases.csv)
1288
- --json <\u0E44\u0E1F\u0E25\u0E4C> \u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E1C\u0E25\u0E14\u0E34\u0E1A\u0E17\u0E31\u0E49\u0E07\u0E2B\u0E21\u0E14\u0E40\u0E1B\u0E47\u0E19 JSON
1289
- --max-pages <n> \u0E08\u0E33\u0E19\u0E27\u0E19\u0E2B\u0E19\u0E49\u0E32\u0E2A\u0E39\u0E07\u0E2A\u0E38\u0E14 (\u0E04\u0E48\u0E32\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19 20)
1290
- --max-depth <n> \u0E04\u0E27\u0E32\u0E21\u0E25\u0E36\u0E01\u0E2A\u0E39\u0E07\u0E2A\u0E38\u0E14 (\u0E04\u0E48\u0E32\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19 3)
2722
+ Scan Options
2723
+ --csv <file> Save test cases and test data as CSV.
2724
+ Default: lazyscout-testcases.csv
1291
2725
 
1292
- \u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E02\u0E2D\u0E07\u0E01\u0E32\u0E23\u0E40\u0E1B\u0E34\u0E14\u0E2B\u0E19\u0E49\u0E32\u0E40\u0E27\u0E47\u0E1A
1293
- --port <n> \u0E1E\u0E2D\u0E23\u0E4C\u0E15\u0E17\u0E35\u0E48\u0E15\u0E49\u0E2D\u0E07\u0E01\u0E32\u0E23 (\u0E04\u0E48\u0E32\u0E40\u0E23\u0E34\u0E48\u0E21\u0E15\u0E49\u0E19 4321)
1294
- --no-open \u0E44\u0E21\u0E48\u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E34\u0E14\u0E40\u0E1A\u0E23\u0E32\u0E27\u0E4C\u0E40\u0E0B\u0E2D\u0E23\u0E4C\u0E43\u0E2B\u0E49\u0E2D\u0E31\u0E15\u0E42\u0E19\u0E21\u0E31\u0E15\u0E34
2726
+ --json <file> Save all raw scan results as JSON.
1295
2727
 
1296
- \u0E15\u0E31\u0E27\u0E2D\u0E22\u0E48\u0E32\u0E07
1297
- npx lazyscout
1298
- npx lazyscout scan http://localhost:5173
1299
- npx lazyscout scan https://example.com --max-pages 10 --csv report.csv
2728
+ --max-pages <n> Maximum number of pages to scan.
2729
+ Default: 20
1300
2730
 
1301
- Explorer \u0E2A\u0E33\u0E23\u0E27\u0E08\u0E40\u0E09\u0E1E\u0E32\u0E30 origin \u0E40\u0E14\u0E35\u0E22\u0E27\u0E01\u0E31\u0E19 \u0E40\u0E14\u0E34\u0E19\u0E14\u0E49\u0E27\u0E22\u0E25\u0E34\u0E07\u0E01\u0E4C\u0E40\u0E17\u0E48\u0E32\u0E19\u0E31\u0E49\u0E19 \u0E44\u0E21\u0E48\u0E04\u0E25\u0E34\u0E01\u0E1B\u0E38\u0E48\u0E21\u0E41\u0E25\u0E30\u0E44\u0E21\u0E48 submit form
2731
+ --max-depth <n> Maximum crawl depth.
2732
+ Default: 3
2733
+
2734
+ Web Interface Options
2735
+ --port <port> Port used by the LazyScout web interface.
2736
+ Default: 4321
2737
+
2738
+ --workspace <path> Workspace used for projects and evidence.
2739
+ Default: ~/LazyScout
2740
+
2741
+ --no-open Do not open the browser automatically.
2742
+
2743
+ Examples
2744
+ npx lazyscout
2745
+
2746
+ npx lazyscout --workspace D:\\QA\\LazyScout
2747
+
2748
+ npx lazyscout scan http://localhost:5173
2749
+
2750
+ npx lazyscout scan https://example.com --max-pages 10 --csv report.csv
2751
+
2752
+ Explorer Behavior
2753
+ LazyScout only explores URLs within the same origin.
2754
+ It currently follows links only and does not click buttons or submit forms.
1302
2755
  `;
1303
2756
  async function main() {
1304
2757
  const { values, positionals } = parseArgs({
@@ -1311,7 +2764,7 @@ async function main() {
1311
2764
  "max-pages": { type: "string" },
1312
2765
  "max-depth": { type: "string" },
1313
2766
  port: { type: "string" },
1314
- // parseArgs ของ Node ไม่แปลง --no-open ให้เอง ต้องประกาศเป็น option แยก
2767
+ workspace: { type: "string" },
1315
2768
  "no-open": { type: "boolean", default: false }
1316
2769
  }
1317
2770
  });
@@ -1327,7 +2780,11 @@ async function main() {
1327
2780
  switch (command) {
1328
2781
  case void 0:
1329
2782
  case "serve":
1330
- await runServe({ port: values.port ? Number(values.port) : void 0, open: !values["no-open"] });
2783
+ await runServe({
2784
+ port: values.port ? Number(values.port) : void 0,
2785
+ open: !values["no-open"],
2786
+ workspace: values.workspace
2787
+ });
1331
2788
  return;
1332
2789
  case "scan": {
1333
2790
  const url = positionals[1];