lazyscout 0.1.0 → 0.2.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
 
@@ -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: "\u0E1E\u0E1A Cloudflare/browser challenge \u2014 \u0E2B\u0E22\u0E38\u0E14\u0E17\u0E35\u0E48\u0E2B\u0E19\u0E49\u0E32\u0E19\u0E35\u0E49\u0E41\u0E25\u0E30\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E2B\u0E49 Tester \u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E14\u0E49\u0E27\u0E22\u0E15\u0E19\u0E40\u0E2D\u0E07"
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(`\u0E01\u0E33\u0E25\u0E31\u0E07\u0E2A\u0E33\u0E23\u0E27\u0E08 ${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 } : {}
@@ -1111,7 +1363,7 @@ async function runScan(options) {
1111
1363
  }
1112
1364
 
1113
1365
  // src/commands/serve.ts
1114
- import { dirname, join } from "node:path";
1366
+ import { dirname as dirname2, join as join2 } 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,665 @@ function registerExportCsvRoute(app) {
1210
1539
  });
1211
1540
  }
1212
1541
 
1542
+ // ../server/dist/routes/automationRun.js
1543
+ var MAX_STEPS = 100;
1544
+ var MAX_LOGS = 250;
1545
+ var MAX_SOURCE_LENGTH = 2e5;
1546
+ var STEP_TIMEOUT_MS = 2e4;
1547
+ var activeRuns = /* @__PURE__ */ new Map();
1548
+ function registerAutomationRunRoute(app) {
1549
+ app.post("/api/automation/stop", async (request, reply) => {
1550
+ const runId = request.body?.runId;
1551
+ if (!runId)
1552
+ return reply.status(400).send({ error: { code: "invalid-run", message: "Run ID is required." } });
1553
+ const active = activeRuns.get(runId);
1554
+ if (!active)
1555
+ return reply.send({ stopped: false });
1556
+ active.stopped = true;
1557
+ await active.browser?.close().catch(() => void 0);
1558
+ return reply.send({ stopped: true });
1559
+ });
1560
+ app.post("/api/automation/run", async (request, reply) => {
1561
+ const body = request.body;
1562
+ const testCase = body.testCase;
1563
+ const secrets = body.secrets;
1564
+ const framework = body.framework ?? "playwright";
1565
+ const runId = body.runId || crypto.randomUUID();
1566
+ if (!testCase || !Array.isArray(testCase.steps))
1567
+ 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" } });
1568
+ if (testCase.steps.length > MAX_STEPS)
1569
+ 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 } });
1570
+ if (typeof body.code === "string" && body.code.length > MAX_SOURCE_LENGTH)
1571
+ 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" } });
1572
+ const logs = [];
1573
+ const secretValues = [
1574
+ secrets?.email,
1575
+ secrets?.username,
1576
+ secrets?.password,
1577
+ secrets?.apiToken,
1578
+ process.env.LAZYSCOUT_TEST_EMAIL,
1579
+ process.env.LAZYSCOUT_TEST_USERNAME,
1580
+ process.env.LAZYSCOUT_TEST_PASSWORD,
1581
+ process.env.LAZYSCOUT_API_TOKEN
1582
+ ].filter((value) => Boolean(value));
1583
+ const addLog = (level, message, durationMs) => {
1584
+ if (logs.length < MAX_LOGS)
1585
+ logs.push({
1586
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1587
+ level,
1588
+ message: redactSensitiveText(message, secretValues),
1589
+ ...durationMs === void 0 ? {} : { durationMs }
1590
+ });
1591
+ };
1592
+ const started = Date.now();
1593
+ addLog("info", "$ lazyscout test --case " + testCase.id);
1594
+ addLog("info", "Starting Playwright runner: " + testCase.title);
1595
+ addLog("info", "Test budget: " + MAX_STEPS + " steps \xB7 " + STEP_TIMEOUT_MS / 1e3 + "s per action \xB7 " + MAX_LOGS + " log lines");
1596
+ if (testCase.automationStatus === "manual") {
1597
+ addLog("warn", "Blocked: this case is marked manual and cannot be automated");
1598
+ return reply.send({ status: "blocked", framework, logs });
1599
+ }
1600
+ if (framework === "cypress") {
1601
+ addLog("warn", "Cypress code generation is available; local runner uses Playwright only.");
1602
+ return reply.send({ status: "unsupported", framework, logs });
1603
+ }
1604
+ const active = { stopped: false };
1605
+ activeRuns.set(runId, active);
1606
+ let browser;
1607
+ let page;
1608
+ try {
1609
+ const launched = await launchBrowser();
1610
+ browser = launched.browser;
1611
+ active.browser = browser;
1612
+ if (active.stopped)
1613
+ throw new Error("Run stopped by user");
1614
+ const context = await browser.newContext({ viewport: { width: 1366, height: 900 } });
1615
+ context.setDefaultTimeout(STEP_TIMEOUT_MS);
1616
+ page = await context.newPage();
1617
+ if (typeof body.code === "string" && body.code.trim()) {
1618
+ addLog("info", "Running edited automation source");
1619
+ await executeEditedCode(page, body.code, addLog, secrets);
1620
+ if (active.stopped)
1621
+ throw new Error("Run stopped by user");
1622
+ addLog("pass", "\u2713 edited source completed");
1623
+ } else
1624
+ for (const step of testCase.steps) {
1625
+ if (active.stopped)
1626
+ throw new Error("Run stopped by user");
1627
+ const stepStarted = Date.now();
1628
+ await executeStep(page, step, addLog, secrets);
1629
+ if (active.stopped)
1630
+ throw new Error("Run stopped by user");
1631
+ addLog("pass", `\u2713 ${step.type}`, Date.now() - stepStarted);
1632
+ }
1633
+ addLog("pass", `Completed ${testCase.id}`, Date.now() - started);
1634
+ return reply.send({
1635
+ status: "passed",
1636
+ framework,
1637
+ logs,
1638
+ screenshot: await captureScreenshot(page, testCase.id, "passed")
1639
+ });
1640
+ } catch (error) {
1641
+ const message = redactSensitiveText(error instanceof Error ? error.message : String(error), secretValues);
1642
+ if (active.stopped) {
1643
+ addLog("warn", "Run stopped by user", Date.now() - started);
1644
+ return reply.send({ status: "stopped", framework, logs });
1645
+ }
1646
+ addLog("fail", `\u2715 ${message}`, Date.now() - started);
1647
+ return reply.send({
1648
+ status: "failed",
1649
+ framework,
1650
+ logs,
1651
+ error: message,
1652
+ screenshot: await captureScreenshot(page, testCase.id, "failed")
1653
+ });
1654
+ } finally {
1655
+ activeRuns.delete(runId);
1656
+ await browser?.close().catch(() => void 0);
1657
+ }
1658
+ });
1659
+ }
1660
+ async function captureScreenshot(page, testCaseId, status) {
1661
+ if (!page)
1662
+ return void 0;
1663
+ try {
1664
+ const image = await page.screenshot({ type: "jpeg", quality: 65, fullPage: false });
1665
+ return {
1666
+ name: `${testCaseId}-${status}-${Date.now()}.jpg`,
1667
+ dataUrl: `data:image/jpeg;base64,${image.toString("base64")}`,
1668
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
1669
+ testCaseId,
1670
+ status
1671
+ };
1672
+ } catch {
1673
+ return void 0;
1674
+ }
1675
+ }
1676
+ async function executeEditedCode(page, source, addLog, projectSecrets) {
1677
+ const lines = source.split(/\r?\n/);
1678
+ let executed = 0;
1679
+ for (const rawLine of lines) {
1680
+ const line = rawLine.trim().replace(/;$/, "");
1681
+ if (!line || line.startsWith("import ") || line.startsWith("test(") || line === "})" || line === "});")
1682
+ continue;
1683
+ if (line.startsWith("//"))
1684
+ continue;
1685
+ if (++executed > MAX_STEPS)
1686
+ throw new Error(`Edited source exceeds the ${MAX_STEPS} action limit`);
1687
+ const gotoMatch = line.match(new RegExp(`^await page\\.goto\\((${STRING_LITERAL})\\)$`));
1688
+ if (gotoMatch) {
1689
+ const url = parseStringLiteral(gotoMatch[1]);
1690
+ const checked = checkTargetUrl(url, config.urlPolicy);
1691
+ if (!checked.ok)
1692
+ throw new Error(checked.message);
1693
+ addLog("info", `\u2192 Navigating to ${redactUrl(checked.url.toString())}`);
1694
+ await page.goto(checked.url.toString(), { waitUntil: "domcontentloaded", timeout: STEP_TIMEOUT_MS });
1695
+ continue;
1696
+ }
1697
+ const waitMatch = line.match(/^await page\.waitForTimeout\((\d{1,5})\)$/);
1698
+ if (waitMatch) {
1699
+ const waitMs = Math.min(Number(waitMatch[1]), 5e3);
1700
+ addLog("info", `\u2192 Waiting ${waitMs}ms`);
1701
+ await page.waitForTimeout(waitMs);
1702
+ continue;
1703
+ }
1704
+ const clickMatch = line.match(/^await (page\..+)\.click\(\)$/);
1705
+ if (clickMatch) {
1706
+ const target = parseEditedLocator(page, clickMatch[1]);
1707
+ await ensureSafeClick(target.locator, target.label);
1708
+ addLog("info", `\u2192 Clicking ${target.label}`);
1709
+ await target.locator.click();
1710
+ continue;
1711
+ }
1712
+ const fillMatch = line.match(new RegExp(`^await (page\\..+)\\.fill\\((${STRING_LITERAL})\\)$`));
1713
+ if (fillMatch) {
1714
+ const target = parseEditedLocator(page, fillMatch[1]);
1715
+ addLog("info", `\u2192 Filling ${target.label}`);
1716
+ await target.locator.fill(resolveSecret(parseStringLiteral(fillMatch[2]), projectSecrets));
1717
+ continue;
1718
+ }
1719
+ const selectMatch = line.match(new RegExp(`^await (page\\..+)\\.selectOption\\((${STRING_LITERAL})\\)$`));
1720
+ if (selectMatch) {
1721
+ const target = parseEditedLocator(page, selectMatch[1]);
1722
+ const option = parseStringLiteral(selectMatch[2]);
1723
+ addLog("info", `\u2192 Selecting an option in ${target.label}`);
1724
+ await target.locator.selectOption(option);
1725
+ continue;
1726
+ }
1727
+ const visibleMatch = line.match(/^await expect\((page\..+)\)\.toBeVisible\(\)$/);
1728
+ if (visibleMatch) {
1729
+ const target = parseEditedLocator(page, visibleMatch[1]);
1730
+ if (!await target.locator.isVisible())
1731
+ throw new Error(`Expected ${target.label} to be visible`);
1732
+ addLog("pass", `Element visible: ${target.label}`);
1733
+ continue;
1734
+ }
1735
+ const textMatch = line.match(new RegExp(`^await expect\\((page(?:\\..+)?)\\)\\.toContainText\\((${STRING_LITERAL})\\)$`));
1736
+ if (textMatch) {
1737
+ const expected = parseStringLiteral(textMatch[2]);
1738
+ const actual = textMatch[1] === "page" ? await page.locator("body").innerText() : await parseEditedLocator(page, textMatch[1]).locator.innerText();
1739
+ if (!actual.includes(expected))
1740
+ throw new Error(`Expected text was not found: ${expected}`);
1741
+ addLog("pass", "Text assertion passed");
1742
+ continue;
1743
+ }
1744
+ const urlMatch = line.match(new RegExp(`^await expect\\(page\\)\\.toHaveURL\\(new RegExp\\((${STRING_LITERAL})\\)\\)$`));
1745
+ if (urlMatch) {
1746
+ const expected = parseStringLiteral(urlMatch[1]);
1747
+ if (!page.url().includes(expected))
1748
+ throw new Error(`URL did not contain ${expected}`);
1749
+ addLog("pass", `URL assertion passed: ${redactUrl(page.url())}`);
1750
+ continue;
1751
+ }
1752
+ throw new Error(`Unsupported edited Playwright statement: ${line.slice(0, 120)}`);
1753
+ }
1754
+ if (executed === 0)
1755
+ throw new Error("Edited source does not contain a supported Playwright action");
1756
+ }
1757
+ var STRING_LITERAL = '"(?:\\\\.|[^"\\\\])*"';
1758
+ function parseStringLiteral(value) {
1759
+ const parsed = JSON.parse(value);
1760
+ if (typeof parsed !== "string")
1761
+ throw new Error("Edited Playwright arguments must be strings");
1762
+ return parsed;
1763
+ }
1764
+ function parseEditedLocator(page, expression) {
1765
+ const roleMatch = expression.match(new RegExp(`^page\\.getByRole\\((${STRING_LITERAL}),\\s*\\{\\s*name:\\s*(${STRING_LITERAL})\\s*\\}\\)$`));
1766
+ if (roleMatch) {
1767
+ const role = parseStringLiteral(roleMatch[1]);
1768
+ const name = parseStringLiteral(roleMatch[2]);
1769
+ return { locator: page.getByRole(role, { name }), label: name };
1770
+ }
1771
+ for (const [method, create] of [
1772
+ ["getByLabel", (value) => page.getByLabel(value)],
1773
+ ["getByPlaceholder", (value) => page.getByPlaceholder(value)],
1774
+ ["getByText", (value) => page.getByText(value)],
1775
+ ["locator", (value) => page.locator(value)]
1776
+ ]) {
1777
+ const match = expression.match(new RegExp(`^page\\.${method}\\((${STRING_LITERAL})\\)$`));
1778
+ if (match) {
1779
+ const value = parseStringLiteral(match[1]);
1780
+ return { locator: create(value), label: value };
1781
+ }
1782
+ }
1783
+ throw new Error(`Unsupported Playwright locator: ${expression.slice(0, 120)}`);
1784
+ }
1785
+ async function executeStep(page, step, addLog, secrets) {
1786
+ switch (step.type) {
1787
+ case "navigate":
1788
+ const checked = checkTargetUrl(step.url, config.urlPolicy);
1789
+ if (!checked.ok)
1790
+ throw new Error(checked.message);
1791
+ addLog("info", "Target URL found: " + redactUrl(checked.url.toString()));
1792
+ addLog("info", "\u2192 Navigating to " + redactUrl(checked.url.toString()));
1793
+ await page.goto(checked.url.toString(), { waitUntil: "domcontentloaded", timeout: STEP_TIMEOUT_MS });
1794
+ addLog("pass", "Page ready: " + (new URL(page.url()).pathname || "/"));
1795
+ addLog("info", "Continuing with the next test step");
1796
+ return;
1797
+ case "click": {
1798
+ const name = step.target.name ?? step.target.text ?? step.target.cssSelector ?? "target";
1799
+ const target = locator(page, step.target);
1800
+ await ensureSafeClick(target, name);
1801
+ addLog("info", "Control found: " + name);
1802
+ addLog("info", "\u2192 Clicking " + name);
1803
+ await target.click();
1804
+ addLog("pass", "Action completed: " + name);
1805
+ return;
1806
+ }
1807
+ case "fill": {
1808
+ const name = step.target.name ?? step.target.label ?? "field";
1809
+ const value = resolveSecret(step.value, secrets);
1810
+ addLog("info", "Input found: " + name);
1811
+ addLog("info", "\u2192 Filling " + name);
1812
+ await locator(page, step.target).fill(value);
1813
+ addLog("pass", "Input ready: " + name);
1814
+ return;
1815
+ }
1816
+ case "select":
1817
+ addLog("info", "Dropdown found: " + (step.target.name ?? step.target.label ?? "select"));
1818
+ await locator(page, step.target).selectOption(step.option);
1819
+ addLog("pass", "Selected option: " + step.option);
1820
+ return;
1821
+ case "assertVisible":
1822
+ await locator(page, step.target).isVisible().then((visible) => {
1823
+ if (!visible)
1824
+ throw new Error("Expected element is not visible");
1825
+ addLog("pass", "Element visible: " + (step.target.name ?? step.target.label ?? "target"));
1826
+ });
1827
+ return;
1828
+ case "assertText": {
1829
+ const bodyText = await page.locator("body").innerText();
1830
+ if (!bodyText.includes(step.text))
1831
+ throw new Error("Expected text was not found: " + step.text);
1832
+ addLog("pass", 'Assertion passed: page contains "' + step.text + '"');
1833
+ return;
1834
+ }
1835
+ case "assertUrl":
1836
+ if (!page.url().includes(step.urlContains))
1837
+ throw new Error("URL does not contain " + step.urlContains);
1838
+ addLog("pass", "URL assertion passed: " + redactUrl(page.url()));
1839
+ return;
1840
+ case "manual":
1841
+ throw new Error("Manual step requires Tester review");
1842
+ }
1843
+ }
1844
+ function resolveSecret(value, projectSecrets) {
1845
+ const secrets = {
1846
+ "{{TEST_EMAIL}}": projectSecrets?.email ?? process.env.LAZYSCOUT_TEST_EMAIL,
1847
+ "{{TEST_USERNAME}}": projectSecrets?.username ?? process.env.LAZYSCOUT_TEST_USERNAME,
1848
+ "{{TEST_PASSWORD}}": projectSecrets?.password ?? process.env.LAZYSCOUT_TEST_PASSWORD,
1849
+ "{{API_TOKEN}}": projectSecrets?.apiToken ?? process.env.LAZYSCOUT_API_TOKEN
1850
+ };
1851
+ const secret = secrets[value];
1852
+ if (secret === void 0 && value in secrets)
1853
+ throw new Error("Required secret is not configured for " + value);
1854
+ return secret ?? value;
1855
+ }
1856
+ function locator(page, target) {
1857
+ if (target.role && target.name)
1858
+ return page.getByRole(target.role, { name: target.name });
1859
+ if (target.label)
1860
+ return page.getByLabel(target.label);
1861
+ if (target.placeholder)
1862
+ return page.getByPlaceholder(target.placeholder);
1863
+ if (target.text)
1864
+ return page.getByText(target.text);
1865
+ return page.locator(target.cssSelector ?? "");
1866
+ }
1867
+ async function ensureSafeClick(target, fallbackLabel) {
1868
+ const labels = await Promise.all([
1869
+ target.getAttribute("aria-label").catch(() => null),
1870
+ target.getAttribute("title").catch(() => null),
1871
+ target.getAttribute("name").catch(() => null),
1872
+ target.getAttribute("id").catch(() => null),
1873
+ target.innerText().catch(() => "")
1874
+ ]);
1875
+ if (isDestructiveLabel(fallbackLabel, ...labels.map((value) => value ?? void 0))) {
1876
+ throw new Error(`Blocked destructive action: ${fallbackLabel}`);
1877
+ }
1878
+ }
1879
+
1880
+ // ../server/dist/routes/apiCheckRun.js
1881
+ var SAFE_API_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
1882
+ function registerApiCheckRunRoute(app) {
1883
+ app.post("/api/api-check/run", async (request, reply) => {
1884
+ const body = request.body;
1885
+ const check = body.apiCheck;
1886
+ if (!check?.url)
1887
+ return reply.status(400).send({ error: { code: "invalid-api-check", message: "\u0E44\u0E21\u0E48\u0E1E\u0E1A API Check" } });
1888
+ const target = checkTargetUrl(check.url, config.urlPolicy);
1889
+ if (!target.ok)
1890
+ return reply.status(400).send({ error: { code: target.code, message: target.message } });
1891
+ const method = check.method.toUpperCase();
1892
+ if (!SAFE_API_METHODS.has(method))
1893
+ return reply.status(400).send({
1894
+ error: {
1895
+ code: "unsafe-api-method",
1896
+ message: `${method} API checks are observation-only. LazyScout runs only GET, HEAD and OPTIONS automatically.`
1897
+ }
1898
+ });
1899
+ const token = body.secrets?.apiToken ?? process.env.LAZYSCOUT_API_TOKEN;
1900
+ if (check.status === "needs-auth" && !token)
1901
+ return reply.send({
1902
+ status: "needs-auth",
1903
+ durationMs: 0,
1904
+ 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"
1905
+ });
1906
+ const started = Date.now();
1907
+ try {
1908
+ const response = await fetch(target.url, {
1909
+ method,
1910
+ headers: token ? { Authorization: `Bearer ${token}` } : void 0,
1911
+ signal: AbortSignal.timeout(2e4)
1912
+ });
1913
+ const durationMs = Date.now() - started;
1914
+ const passed = check.expectedStatus === void 0 ? response.ok : response.status === check.expectedStatus;
1915
+ return reply.send({
1916
+ status: passed ? "passed" : "failed",
1917
+ statusCode: response.status,
1918
+ durationMs,
1919
+ message: passed ? `API ${check.method} returned expected HTTP ${response.status}` : `API ${check.method} returned HTTP ${response.status}`
1920
+ });
1921
+ } catch (error) {
1922
+ return reply.send({
1923
+ status: "failed",
1924
+ durationMs: Date.now() - started,
1925
+ message: redactSensitiveText(error instanceof Error ? error.message : String(error), token ? [token] : [])
1926
+ });
1927
+ }
1928
+ });
1929
+ }
1930
+
1931
+ // ../server/dist/routes/loadTest.js
1932
+ function registerLoadTestRoute(app) {
1933
+ app.post("/api/load-test/run", async (request, reply) => {
1934
+ const body = request.body;
1935
+ if (!body.confirmed)
1936
+ return reply.status(400).send({
1937
+ error: { code: "confirmation-required", message: "Confirm that you are authorized to load test this target." }
1938
+ });
1939
+ let url;
1940
+ try {
1941
+ url = new URL(body.url ?? "");
1942
+ } catch {
1943
+ return reply.status(400).send({ error: { code: "invalid-url", message: "A valid HTTP URL is required." } });
1944
+ }
1945
+ if (!["http:", "https:"].includes(url.protocol))
1946
+ return reply.status(400).send({ error: { code: "invalid-url", message: "Only HTTP and HTTPS URLs are supported." } });
1947
+ const virtualUsers = Math.max(1, Math.min(Number(body.virtualUsers) || 1, 20));
1948
+ const requestsPerUser = Math.max(1, Math.min(Number(body.requestsPerUser) || 1, 100));
1949
+ const intervalMs = Math.max(0, Math.min(Number(body.intervalMs) || 0, 1e4));
1950
+ const timings = [];
1951
+ const errors = [];
1952
+ const requests = [];
1953
+ let requestSequence = 0;
1954
+ const started = Date.now();
1955
+ async function worker(virtualUser) {
1956
+ for (let count = 0; count < requestsPerUser; count++) {
1957
+ const id = ++requestSequence;
1958
+ const requestStarted = Date.now();
1959
+ try {
1960
+ const response2 = await fetch(url, { signal: AbortSignal.timeout(15e3), redirect: "follow" });
1961
+ const durationMs = Date.now() - requestStarted;
1962
+ const responseBytes = Number(response2.headers.get("content-length")) || void 0;
1963
+ timings.push(durationMs);
1964
+ if (!response2.ok)
1965
+ errors.push(`HTTP ${response2.status} ${response2.statusText}`.trim());
1966
+ requests.push({
1967
+ id,
1968
+ virtualUser,
1969
+ iteration: count + 1,
1970
+ method: "GET",
1971
+ url: url.toString(),
1972
+ finalUrl: response2.url,
1973
+ statusCode: response2.status,
1974
+ statusText: response2.statusText,
1975
+ durationMs,
1976
+ passed: response2.ok,
1977
+ responseBytes
1978
+ });
1979
+ } catch (error) {
1980
+ const durationMs = Date.now() - requestStarted;
1981
+ const message = error instanceof Error ? error.message : String(error);
1982
+ timings.push(durationMs);
1983
+ errors.push(message);
1984
+ requests.push({
1985
+ id,
1986
+ virtualUser,
1987
+ iteration: count + 1,
1988
+ method: "GET",
1989
+ url: url.toString(),
1990
+ durationMs,
1991
+ passed: false,
1992
+ error: message
1993
+ });
1994
+ }
1995
+ if (intervalMs && count < requestsPerUser - 1)
1996
+ await new Promise((resolve2) => setTimeout(resolve2, intervalMs));
1997
+ }
1998
+ }
1999
+ await Promise.all(Array.from({ length: virtualUsers }, (_, index) => worker(index + 1)));
2000
+ const total = timings.length;
2001
+ const failed = errors.length;
2002
+ const duration = Math.max(Date.now() - started, 1);
2003
+ const response = {
2004
+ total,
2005
+ passed: total - failed,
2006
+ failed,
2007
+ averageMs: total ? Math.round(timings.reduce((sum, value) => sum + value, 0) / total) : 0,
2008
+ minMs: total ? Math.min(...timings) : 0,
2009
+ maxMs: total ? Math.max(...timings) : 0,
2010
+ requestsPerSecond: Number((total / (duration / 1e3)).toFixed(2)),
2011
+ errors: [...new Set(errors)].slice(0, 10),
2012
+ requests: requests.sort((left, right) => left.id - right.id)
2013
+ };
2014
+ return reply.send(response);
2015
+ });
2016
+ }
2017
+
2018
+ // ../server/dist/routes/versions.js
2019
+ import { spawn } from "node:child_process";
2020
+ import { access } from "node:fs/promises";
2021
+ import { dirname, join } from "node:path";
2022
+ var PACKAGE_NAME = "lazyscout";
2023
+ var REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}`;
2024
+ var VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
2025
+ var CACHE_TTL_MS = 6e4;
2026
+ var registryCache;
2027
+ var installInProgress = false;
2028
+ function compareVersions(left, right) {
2029
+ const [leftMain, leftPre] = left.split("-", 2);
2030
+ const [rightMain, rightPre] = right.split("-", 2);
2031
+ const leftParts = leftMain.split(".").map(Number);
2032
+ const rightParts = rightMain.split(".").map(Number);
2033
+ for (let index = 0; index < 3; index++) {
2034
+ const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
2035
+ if (difference !== 0)
2036
+ return difference;
2037
+ }
2038
+ if (!leftPre && rightPre)
2039
+ return 1;
2040
+ if (leftPre && !rightPre)
2041
+ return -1;
2042
+ return (leftPre ?? "").localeCompare(rightPre ?? "", void 0, { numeric: true });
2043
+ }
2044
+ async function fetchPublishedVersions(force = false) {
2045
+ if (!force && registryCache && registryCache.expiresAt > Date.now())
2046
+ return registryCache.value;
2047
+ const response = await fetch(REGISTRY_URL, {
2048
+ headers: { Accept: "application/vnd.npm.install-v1+json" },
2049
+ signal: AbortSignal.timeout(8e3)
2050
+ });
2051
+ if (!response.ok)
2052
+ throw new Error(`npm Registry returned HTTP ${response.status}.`);
2053
+ const body = await response.json();
2054
+ const tags = body["dist-tags"] ?? {};
2055
+ const versions = Object.keys(body.versions ?? {}).filter((version) => VERSION_PATTERN.test(version)).sort((left, right) => compareVersions(right, left)).slice(0, 20).map((version) => ({
2056
+ version,
2057
+ tags: Object.entries(tags).filter(([, taggedVersion]) => taggedVersion === version).map(([tag]) => tag),
2058
+ publishedAt: body.time?.[version]
2059
+ }));
2060
+ const value = { latestVersion: tags.latest, versions };
2061
+ registryCache = { expiresAt: Date.now() + CACHE_TTL_MS, value };
2062
+ return value;
2063
+ }
2064
+ async function findNpmCli() {
2065
+ const candidates = [
2066
+ process.env.npm_execpath,
2067
+ join(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js"),
2068
+ process.env.APPDATA ? join(process.env.APPDATA, "npm", "node_modules", "npm", "bin", "npm-cli.js") : void 0,
2069
+ "/usr/lib/node_modules/npm/bin/npm-cli.js",
2070
+ "/usr/local/lib/node_modules/npm/bin/npm-cli.js"
2071
+ ].filter((value) => Boolean(value?.endsWith(".js")));
2072
+ for (const candidate of candidates) {
2073
+ try {
2074
+ await access(candidate);
2075
+ return candidate;
2076
+ } catch {
2077
+ }
2078
+ }
2079
+ throw new Error("Could not locate npm-cli.js. Copy the install command and run it in a terminal instead.");
2080
+ }
2081
+ async function runNpmInstall(version) {
2082
+ const npmCli = await findNpmCli();
2083
+ return new Promise((resolve2, reject) => {
2084
+ const commandArgs = [npmCli, "install", "--global", `${PACKAGE_NAME}@${version}`, "--no-audit", "--no-fund"];
2085
+ const child = spawn(process.execPath, commandArgs, {
2086
+ windowsHide: true,
2087
+ stdio: ["ignore", "pipe", "pipe"]
2088
+ });
2089
+ let output = "";
2090
+ let settled = false;
2091
+ const append = (chunk) => {
2092
+ output = `${output}${chunk.toString()}`.slice(-12e3);
2093
+ };
2094
+ child.stdout.on("data", append);
2095
+ child.stderr.on("data", append);
2096
+ const timeout = setTimeout(() => {
2097
+ if (settled)
2098
+ return;
2099
+ settled = true;
2100
+ child.kill();
2101
+ reject(new Error("npm installation timed out after 5 minutes."));
2102
+ }, 3e5);
2103
+ child.once("error", (error) => {
2104
+ if (settled)
2105
+ return;
2106
+ settled = true;
2107
+ clearTimeout(timeout);
2108
+ reject(error);
2109
+ });
2110
+ child.once("close", (code) => {
2111
+ if (settled)
2112
+ return;
2113
+ settled = true;
2114
+ clearTimeout(timeout);
2115
+ if (code === 0)
2116
+ resolve2(output.trim());
2117
+ else
2118
+ reject(new Error(output.trim() || `npm exited with code ${code ?? "unknown"}.`));
2119
+ });
2120
+ });
2121
+ }
2122
+ function registerVersionRoutes(app, currentVersion) {
2123
+ app.get("/api/versions", async (_request, reply) => {
2124
+ try {
2125
+ const published = await fetchPublishedVersions();
2126
+ return reply.send({
2127
+ packageName: PACKAGE_NAME,
2128
+ currentVersion,
2129
+ latestVersion: published.latestVersion,
2130
+ updateAvailable: Boolean(published.latestVersion && compareVersions(published.latestVersion, currentVersion) > 0),
2131
+ registryAvailable: true,
2132
+ versions: published.versions
2133
+ });
2134
+ } catch (error) {
2135
+ return reply.send({
2136
+ packageName: PACKAGE_NAME,
2137
+ currentVersion,
2138
+ updateAvailable: false,
2139
+ registryAvailable: false,
2140
+ versions: VERSION_PATTERN.test(currentVersion) ? [{ version: currentVersion, tags: ["current"] }] : [],
2141
+ error: error instanceof Error ? error.message : String(error)
2142
+ });
2143
+ }
2144
+ });
2145
+ app.post("/api/versions/install", async (request, reply) => {
2146
+ const body = request.body ?? {};
2147
+ if (typeof body.version !== "string" || !VERSION_PATTERN.test(body.version)) {
2148
+ return reply.status(400).send({
2149
+ error: { code: "invalid-version", message: "Select a valid published LazyScout version." }
2150
+ });
2151
+ }
2152
+ if (installInProgress) {
2153
+ return reply.status(409).send({
2154
+ error: { code: "install-in-progress", message: "Another LazyScout installation is still running." }
2155
+ });
2156
+ }
2157
+ installInProgress = true;
2158
+ try {
2159
+ const published = await fetchPublishedVersions(true);
2160
+ if (!published.versions.some((item) => item.version === body.version)) {
2161
+ return reply.status(400).send({
2162
+ error: { code: "unknown-version", message: "That version is not available from npm Registry." }
2163
+ });
2164
+ }
2165
+ const output = await runNpmInstall(body.version);
2166
+ return reply.send({
2167
+ installedVersion: body.version,
2168
+ command: `npm install -g ${PACKAGE_NAME}@${body.version}`,
2169
+ output
2170
+ });
2171
+ } catch (error) {
2172
+ const message = error instanceof Error ? error.message : String(error);
2173
+ return reply.status(500).send({
2174
+ error: {
2175
+ code: "install-failed",
2176
+ message: `Could not install LazyScout v${body.version}.`,
2177
+ hint: message
2178
+ }
2179
+ });
2180
+ } finally {
2181
+ installInProgress = false;
2182
+ }
2183
+ });
2184
+ }
2185
+
1213
2186
  // ../server/dist/app.js
1214
2187
  function buildApp(options = {}) {
1215
2188
  const app = Fastify({
1216
2189
  logger: { level: options.logLevel ?? process.env.LOG_LEVEL ?? "info" },
1217
- // การ crawl ใช้เวลานาน จึงต้องยืด timeout ของ request ให้พอ
1218
2190
  connectionTimeout: 0,
1219
2191
  bodyLimit: 10 * 1024 * 1024
1220
2192
  });
1221
- app.get("/api/health", async () => ({ status: "ok" }));
2193
+ const appVersion = options.appVersion ?? process.env.npm_package_version ?? "0.0.0-dev";
2194
+ app.get("/api/health", async () => ({ status: "ok", version: appVersion }));
1222
2195
  registerAnalyzeRoute(app);
1223
2196
  registerExportCsvRoute(app);
2197
+ registerAutomationRunRoute(app);
2198
+ registerApiCheckRunRoute(app);
2199
+ registerLoadTestRoute(app);
2200
+ registerVersionRoutes(app, appVersion);
1224
2201
  if (options.staticDir) {
1225
2202
  app.register(fastifyStatic, { root: options.staticDir });
1226
2203
  app.setNotFoundHandler(async (request, reply) => {
@@ -1236,22 +2213,25 @@ function buildApp(options = {}) {
1236
2213
  }
1237
2214
 
1238
2215
  // src/openInBrowser.ts
1239
- import { spawn } from "node:child_process";
2216
+ import { spawn as spawn2 } from "node:child_process";
1240
2217
  async function openInBrowser(url) {
1241
2218
  const [command, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
1242
2219
  try {
1243
- const child = spawn(command, args, { stdio: "ignore", detached: true });
2220
+ const child = spawn2(command, args, { stdio: "ignore", detached: true });
1244
2221
  child.on("error", () => void 0);
1245
2222
  child.unref();
1246
2223
  } catch {
1247
2224
  }
1248
2225
  }
1249
2226
 
2227
+ // src/version.ts
2228
+ var VERSION = true ? "0.2.0" : "0.0.0-dev";
2229
+
1250
2230
  // src/commands/serve.ts
1251
2231
  var DEFAULT_PORT = 4321;
1252
- var WEB_DIR = join(dirname(fileURLToPath(import.meta.url)), "web");
2232
+ var WEB_DIR = join2(dirname2(fileURLToPath(import.meta.url)), "web");
1253
2233
  async function runServe(options) {
1254
- const app = buildApp({ staticDir: WEB_DIR, logLevel: "warn" });
2234
+ const app = buildApp({ staticDir: WEB_DIR, logLevel: "warn", appVersion: VERSION });
1255
2235
  const port = await listenOnFreePort(app, options.port ?? DEFAULT_PORT);
1256
2236
  const url = `http://localhost:${port}`;
1257
2237
  console.log(`
@@ -1272,9 +2252,6 @@ async function listenOnFreePort(app, startPort) {
1272
2252
  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}`);
1273
2253
  }
1274
2254
 
1275
- // src/version.ts
1276
- var VERSION = true ? "0.1.0" : "0.0.0-dev";
1277
-
1278
2255
  // src/index.ts
1279
2256
  var HELP = `
1280
2257
  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
@@ -1311,7 +2288,6 @@ async function main() {
1311
2288
  "max-pages": { type: "string" },
1312
2289
  "max-depth": { type: "string" },
1313
2290
  port: { type: "string" },
1314
- // parseArgs ของ Node ไม่แปลง --no-open ให้เอง ต้องประกาศเป็น option แยก
1315
2291
  "no-open": { type: "boolean", default: false }
1316
2292
  }
1317
2293
  });