lazyscout 0.4.2 → 0.4.5

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
@@ -547,6 +547,37 @@ function collectPageData() {
547
547
  const value = el.getAttribute(name);
548
548
  return value && value.trim() ? value.trim() : void 0;
549
549
  }
550
+ function renderedText(el) {
551
+ let text = "";
552
+ const walk = (node) => {
553
+ if (node.nodeType === Node.TEXT_NODE) {
554
+ text += node.textContent ?? "";
555
+ return;
556
+ }
557
+ if (node.nodeType !== Node.ELEMENT_NODE)
558
+ return;
559
+ const element = node;
560
+ const style = window.getComputedStyle(element);
561
+ if (style.display === "none" || style.visibility === "hidden")
562
+ return;
563
+ if (element instanceof HTMLImageElement) {
564
+ const alt = element.getAttribute("alt");
565
+ if (alt)
566
+ text += ` ${alt} `;
567
+ return;
568
+ }
569
+ const inline = style.display === "inline" || style.display === "contents";
570
+ if (!inline)
571
+ text += " ";
572
+ for (const child of Array.from(element.childNodes))
573
+ walk(child);
574
+ if (!inline)
575
+ text += " ";
576
+ };
577
+ for (const child of Array.from(el.childNodes))
578
+ walk(child);
579
+ return text;
580
+ }
550
581
  function accessibleName(el) {
551
582
  const ariaLabel = cleanText(el.getAttribute("aria-label"));
552
583
  if (ariaLabel)
@@ -581,7 +612,7 @@ function collectPageData() {
581
612
  return cleanText(el.value);
582
613
  return cleanText(el.getAttribute("name"));
583
614
  }
584
- const ownText = cleanText(el.textContent);
615
+ const ownText = cleanText(renderedText(el));
585
616
  if (ownText)
586
617
  return ownText;
587
618
  const image = el.querySelector("img[alt]");
@@ -865,11 +896,12 @@ function collectPageData() {
865
896
  const kind = role === "tab" || dataTab ? "tab" : dataDrawer ? "drawer" : popup === "dialog" || toggle === "modal" || dataModal ? "dialog" : popup === "menu" || popup === "listbox" || toggle === "dropdown" ? "dropdown" : accordion ? "accordion" : element instanceof HTMLSelectElement ? "dropdown" : element.matches("[aria-expanded]") ? "accordion" : "dialog";
866
897
  const controls = element.getAttribute("aria-controls");
867
898
  const targetSelector = element.getAttribute("data-target") || element.getAttribute("data-bs-target") || element.getAttribute("data-modal") || element.getAttribute("data-drawer");
899
+ const clickable = element.tagName === "DETAILS" ? element.querySelector("summary") ?? element : element;
868
900
  return {
869
901
  kind,
870
902
  name: accessibleName(element),
871
903
  role,
872
- cssSelector: cssSelector(element),
904
+ cssSelector: cssSelector(clickable),
873
905
  expanded: expanded === null ? void 0 : expanded === "true",
874
906
  visible: true,
875
907
  controlsSelector: controls ? `#${CSS.escape(controls)}` : targetSelector || void 0,
@@ -1024,6 +1056,17 @@ async function launchBrowser(options = {}) {
1024
1056
  const failures = [];
1025
1057
  for (const candidate of CANDIDATES) {
1026
1058
  try {
1059
+ if (options.storageState) {
1060
+ const browser2 = await chromium.launch({
1061
+ headless: options.headless ?? true,
1062
+ ...candidate.channel ? { channel: candidate.channel } : {}
1063
+ });
1064
+ const context2 = await browser2.newContext({
1065
+ viewport: { width: 1366, height: 900 },
1066
+ storageState: options.storageState
1067
+ });
1068
+ return { context: context2, label: candidate.label, close: () => browser2.close() };
1069
+ }
1027
1070
  if (options.userDataDir) {
1028
1071
  const context2 = await chromium.launchPersistentContext(options.userDataDir, {
1029
1072
  headless: options.headless ?? true,
@@ -1046,6 +1089,32 @@ async function launchBrowser(options = {}) {
1046
1089
  throw new ExplorerError("browser-error", `unable to launch a browser (tried: ${failures.join(", ")})`, options.userDataDir ? "Close any other LazyScout browser for this Project \u2014 the login browser and a recording both hold its profile \u2014 and try again" : 'Please install Google Chrome or Microsoft Edge or run "npx playwright install chromium" and try again');
1047
1090
  }
1048
1091
 
1092
+ // ../../packages/explorer/dist/auth/browserStorage.js
1093
+ function readSessionStorage() {
1094
+ try {
1095
+ const items = [];
1096
+ for (let index = 0; index < window.sessionStorage.length; index++) {
1097
+ const name = window.sessionStorage.key(index);
1098
+ if (name === null)
1099
+ continue;
1100
+ items.push({ name, value: window.sessionStorage.getItem(name) ?? "" });
1101
+ }
1102
+ return items;
1103
+ } catch {
1104
+ return [];
1105
+ }
1106
+ }
1107
+ function writeSessionStorage(origins) {
1108
+ try {
1109
+ const match = origins.find((entry) => entry.origin === window.location.origin);
1110
+ if (!match)
1111
+ return;
1112
+ for (const item of match.items)
1113
+ window.sessionStorage.setItem(item.name, item.value);
1114
+ } catch {
1115
+ }
1116
+ }
1117
+
1049
1118
  // ../../packages/explorer/dist/scopedExplorer.js
1050
1119
  var DEFAULT_LIMITS = {
1051
1120
  maxPages: 20,
@@ -1159,20 +1228,53 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1159
1228
  function isSessionEnding(name, text) {
1160
1229
  return isSessionEndingLabel(name, text);
1161
1230
  }
1162
- async function discoverNavigationRegions(page) {
1231
+ async function discoverNavigationRegions(page, currentState) {
1163
1232
  const candidates = [];
1164
1233
  try {
1165
1234
  const navItems = await page.evaluate(() => {
1235
+ const renderedText = (element) => {
1236
+ let text = "";
1237
+ const walk = (node) => {
1238
+ if (node.nodeType === Node.TEXT_NODE) {
1239
+ text += node.textContent ?? "";
1240
+ return;
1241
+ }
1242
+ if (node.nodeType !== Node.ELEMENT_NODE)
1243
+ return;
1244
+ const child = node;
1245
+ const style = window.getComputedStyle(child);
1246
+ if (style.visibility === "hidden")
1247
+ return;
1248
+ if (child instanceof HTMLImageElement) {
1249
+ const alt = child.getAttribute("alt");
1250
+ if (alt)
1251
+ text += ` ${alt} `;
1252
+ return;
1253
+ }
1254
+ const inline = style.display === "inline" || style.display === "contents";
1255
+ if (!inline)
1256
+ text += " ";
1257
+ for (const grandChild of Array.from(child.childNodes))
1258
+ walk(grandChild);
1259
+ if (!inline)
1260
+ text += " ";
1261
+ };
1262
+ for (const child of Array.from(element.childNodes))
1263
+ walk(child);
1264
+ return text.replace(/\s+/g, " ").trim();
1265
+ };
1166
1266
  const results = [];
1167
1267
  const navRegions = document.querySelectorAll('nav a[href], aside a[href], [role="navigation"] a[href], [role="menu"] [role="menuitem"], [role="menubar"] [role="menuitem"]');
1168
1268
  navRegions.forEach((el) => {
1169
1269
  const anchor = el;
1170
- const name = el.getAttribute("aria-label") || el.textContent?.replace(/\s+/g, " ").trim() || "";
1171
- if (!name || name.length > 80)
1270
+ if (el.getClientRects().length === 0)
1271
+ return;
1272
+ const name = el.getAttribute("aria-label")?.trim() || renderedText(el);
1273
+ if (!name)
1172
1274
  return;
1173
- const cssSel = el.id ? `#${CSS.escape(el.id)}` : `${el.tagName.toLowerCase()}[href="${anchor.getAttribute("href") || ""}"]`;
1275
+ const cssSel = el.id ? `#${CSS.escape(el.id)}` : `${el.tagName.toLowerCase()}[href="${(anchor.getAttribute("href") || "").replace(/["\\]/g, "\\$&")}"]`;
1174
1276
  results.push({
1175
- name: name.slice(0, 80),
1277
+ name,
1176
1278
  role: el.getAttribute("role") || "link",
1177
1279
  href: anchor.href || null,
1178
1280
  cssSelector: cssSel
@@ -1184,7 +1286,9 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1184
1286
  if (!item.href)
1185
1287
  continue;
1186
1288
  const action = {
1187
- id: `nav|${item.cssSelector}`,
1289
+ // Scoped to the state, so failing here cannot blacklist the same link
1290
+ // in a state where it is reachable.
1291
+ id: `${currentState.id}|nav|${item.cssSelector}`,
1188
1292
  type: "navigate",
1189
1293
  description: `Navigate to \u201C${item.name}\u201D via sidebar`,
1190
1294
  target: item.name,
@@ -1203,7 +1307,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1203
1307
  candidates.push({
1204
1308
  priority: 2,
1205
1309
  action,
1206
- locator: { role: item.role, name: item.name },
1310
+ locator: { role: item.role, name: item.name, cssSelector: item.cssSelector },
1207
1311
  kind: "sidebar-nav",
1208
1312
  restoreStrategy: "goto"
1209
1313
  });
@@ -1228,7 +1332,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1228
1332
  safe: false,
1229
1333
  reason: "session-ending action"
1230
1334
  },
1231
- locator: { role: link.role, name: link.accessibleName },
1335
+ locator: { role: link.role, name: link.accessibleName, cssSelector: link.cssSelector },
1232
1336
  kind: "navigation-link",
1233
1337
  restoreStrategy: "goto"
1234
1338
  });
@@ -1247,13 +1351,13 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1247
1351
  safe: !blocked,
1248
1352
  reason: blocked ? "Action matched the Project click filter" : void 0
1249
1353
  },
1250
- locator: { role: link.role, name: link.accessibleName },
1354
+ locator: { role: link.role, name: link.accessibleName, cssSelector: link.cssSelector },
1251
1355
  kind: "navigation-link",
1252
1356
  restoreStrategy: "goto"
1253
1357
  });
1254
1358
  }
1255
1359
  try {
1256
- const navCandidates = await discoverNavigationRegions(page);
1360
+ const navCandidates = await discoverNavigationRegions(page, currentState);
1257
1361
  candidates.push(...navCandidates);
1258
1362
  } catch {
1259
1363
  }
@@ -1271,7 +1375,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1271
1375
  safe: !blocked,
1272
1376
  reason: blocked ? "Action matched the Project click filter" : void 0
1273
1377
  },
1274
- locator: { role: interaction.role, name: interaction.name },
1378
+ locator: { role: interaction.role, name: interaction.name, cssSelector: interaction.cssSelector },
1275
1379
  kind: "tab",
1276
1380
  restoreStrategy: "select-tab"
1277
1381
  });
@@ -1326,7 +1430,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1326
1430
  safe: !blocked,
1327
1431
  reason: blocked ? "Action matched the Project click filter" : void 0
1328
1432
  },
1329
- locator: { role: interaction.role, name: interaction.name },
1433
+ locator: { role: interaction.role, name: interaction.name, cssSelector: interaction.cssSelector },
1330
1434
  kind: "modal-opener",
1331
1435
  restoreStrategy: "close-dialog"
1332
1436
  });
@@ -1345,7 +1449,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1345
1449
  safe: !blocked,
1346
1450
  reason: blocked ? "Action matched the Project click filter" : void 0
1347
1451
  },
1348
- locator: { role: interaction.role, name: interaction.name },
1452
+ locator: { role: interaction.role, name: interaction.name, cssSelector: interaction.cssSelector },
1349
1453
  kind: "dropdown",
1350
1454
  restoreStrategy: "goto"
1351
1455
  });
@@ -1364,7 +1468,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1364
1468
  safe: !blocked,
1365
1469
  reason: blocked ? "Action matched the Project click filter" : void 0
1366
1470
  },
1367
- locator: { role: interaction.role, name: interaction.name },
1471
+ locator: { role: interaction.role, name: interaction.name, cssSelector: interaction.cssSelector },
1368
1472
  kind: "accordion",
1369
1473
  restoreStrategy: "goto"
1370
1474
  });
@@ -1439,15 +1543,37 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1439
1543
  candidates.sort((a, b) => a.priority - b.priority);
1440
1544
  return candidates;
1441
1545
  }
1442
- async function restoreState(page, targetUrl, strategy, _entryFlow) {
1546
+ async function replayEntryFlow(page, entryFlow) {
1547
+ const inPageSteps = entryFlow.filter((step) => step.action.selector && step.action.type !== "navigate");
1548
+ if (inPageSteps.length === 0)
1549
+ return;
1550
+ for (const step of inPageSteps) {
1551
+ const selector = step.action.selector;
1552
+ if (!selector)
1553
+ continue;
1554
+ try {
1555
+ const target = page.locator(selector).first();
1556
+ if (await target.count() === 0)
1557
+ continue;
1558
+ if (!await target.isVisible())
1559
+ continue;
1560
+ await target.click({ timeout: legacyOptions.actionTimeoutMs });
1561
+ await page.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
1562
+ } catch {
1563
+ }
1564
+ }
1565
+ }
1566
+ async function restoreState(page, targetUrl, strategy, entryFlow) {
1443
1567
  switch (strategy) {
1444
1568
  case "goto":
1445
1569
  await page.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs }).catch(() => void 0);
1446
1570
  await page.waitForTimeout(legacyOptions.waitAfterNavigationMs);
1571
+ await replayEntryFlow(page, entryFlow);
1447
1572
  break;
1448
1573
  case "reload":
1449
1574
  await page.reload({ waitUntil: "domcontentloaded", timeout: legacyOptions.pageTimeoutMs }).catch(() => void 0);
1450
1575
  await page.waitForTimeout(legacyOptions.waitAfterNavigationMs);
1576
+ await replayEntryFlow(page, entryFlow);
1451
1577
  break;
1452
1578
  case "close-dialog":
1453
1579
  try {
@@ -1460,7 +1586,7 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1460
1586
  await page.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
1461
1587
  break;
1462
1588
  case "entry-replay":
1463
- for (const step of _entryFlow) {
1589
+ for (const step of entryFlow) {
1464
1590
  try {
1465
1591
  if (step.action.selector) {
1466
1592
  await page.locator(step.action.selector).click({ timeout: legacyOptions.actionTimeoutMs }).catch(() => void 0);
@@ -1484,20 +1610,34 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1484
1610
  }
1485
1611
  }
1486
1612
  async function executeWithRetry(page, candidate, currentUrl, entryFlow, maxRetries) {
1613
+ const locatorsFor = () => {
1614
+ const options = [];
1615
+ const { role, name, testId, cssSelector } = candidate.locator;
1616
+ if (testId)
1617
+ options.push(() => page.getByTestId(testId));
1618
+ if (role && name) {
1619
+ options.push(() => page.getByRole(role, { name, exact: true }).first());
1620
+ options.push(() => page.getByRole(role, { name }).first());
1621
+ }
1622
+ if (cssSelector)
1623
+ options.push(() => page.locator(cssSelector).first());
1624
+ return options;
1625
+ };
1487
1626
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
1488
1627
  try {
1489
- let locator3;
1490
- if (candidate.locator.cssSelector) {
1491
- locator3 = page.locator(candidate.locator.cssSelector).first();
1492
- } else if (candidate.locator.role && candidate.locator.name) {
1493
- locator3 = page.getByRole(candidate.locator.role, {
1494
- name: candidate.locator.name
1495
- });
1496
- } else if (candidate.locator.testId) {
1497
- locator3 = page.getByTestId(candidate.locator.testId);
1498
- } else {
1628
+ const options = locatorsFor();
1629
+ if (options.length === 0)
1499
1630
  return { success: false };
1631
+ let locator3;
1632
+ for (const build2 of options) {
1633
+ const next = build2();
1634
+ if (await next.count() > 0) {
1635
+ locator3 = next;
1636
+ break;
1637
+ }
1500
1638
  }
1639
+ if (!locator3)
1640
+ throw new Error("No locator candidate matched");
1501
1641
  await locator3.click({ timeout: legacyOptions.actionTimeoutMs });
1502
1642
  await page.waitForTimeout(legacyOptions.stateDiscoveryTimeoutMs);
1503
1643
  const newUrl = page.url();
@@ -1606,7 +1746,14 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1606
1746
  return { candidates: [] };
1607
1747
  }
1608
1748
  }
1609
- const launched = await launchBrowser(legacyOptions.browserProfileDir ? { userDataDir: legacyOptions.browserProfileDir } : {});
1749
+ const launched = await launchBrowser({
1750
+ headless: legacyOptions.headless ?? true,
1751
+ ...legacyOptions.authRestore?.storageState ? { storageState: legacyOptions.authRestore.storageState } : legacyOptions.browserProfileDir ? { userDataDir: legacyOptions.browserProfileDir } : {}
1752
+ });
1753
+ if (legacyOptions.authRestore?.sessionStorage) {
1754
+ debug("[Auth] Restoring authenticated state");
1755
+ await launched.context.addInitScript(writeSessionStorage, legacyOptions.authRestore.sessionStorage).catch(() => void 0);
1756
+ }
1610
1757
  const { context, label: browserLabel } = launched;
1611
1758
  let targetStartUrl = entryUrl;
1612
1759
  if (config2.startPath) {
@@ -1727,8 +1874,13 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1727
1874
  break;
1728
1875
  }
1729
1876
  }
1730
- const raw2 = await page.evaluate(collectPageData);
1731
- const currentModel = mapToPageModel(raw2, { url: item.url, finalUrl: page.url(), depth: item.depth, statusCode: 200 }, legacyOptions.blockedKeywords);
1877
+ const collect = async () => mapToPageModel(await page.evaluate(collectPageData), { url: item.url, finalUrl: page.url(), depth: item.depth, statusCode: 200 }, legacyOptions.blockedKeywords);
1878
+ let currentModel = await collect();
1879
+ const wantedState = item.stateId ? actionGraph.states.find((state) => state.id === item.stateId) : void 0;
1880
+ if (wantedState && currentModel.state && currentModel.state.fingerprint !== wantedState.fingerprint) {
1881
+ await replayEntryFlow(page, item.entryFlow);
1882
+ currentModel = await collect();
1883
+ }
1732
1884
  const currentState = currentModel.state;
1733
1885
  if (!currentState)
1734
1886
  continue;
@@ -2005,6 +2157,37 @@ function recorderInitScript() {
2005
2157
  const wrapping = element.closest("label");
2006
2158
  return clean(wrapping?.textContent) || void 0;
2007
2159
  };
2160
+ const renderedText = (el) => {
2161
+ let text = "";
2162
+ const walk = (node) => {
2163
+ if (node.nodeType === Node.TEXT_NODE) {
2164
+ text += node.textContent ?? "";
2165
+ return;
2166
+ }
2167
+ if (node.nodeType !== Node.ELEMENT_NODE)
2168
+ return;
2169
+ const child = node;
2170
+ const style = window.getComputedStyle(child);
2171
+ if (style.display === "none" || style.visibility === "hidden")
2172
+ return;
2173
+ if (child instanceof HTMLImageElement) {
2174
+ const alt = child.getAttribute("alt");
2175
+ if (alt)
2176
+ text += ` ${alt} `;
2177
+ return;
2178
+ }
2179
+ const inline = style.display === "inline" || style.display === "contents";
2180
+ if (!inline)
2181
+ text += " ";
2182
+ for (const grandChild of Array.from(child.childNodes))
2183
+ walk(grandChild);
2184
+ if (!inline)
2185
+ text += " ";
2186
+ };
2187
+ for (const child of Array.from(el.childNodes))
2188
+ walk(child);
2189
+ return text;
2190
+ };
2008
2191
  const accessibleName = (element) => {
2009
2192
  const aria = clean(element.getAttribute("aria-label"));
2010
2193
  if (aria)
@@ -2034,7 +2217,7 @@ function recorderInitScript() {
2034
2217
  }
2035
2218
  return void 0;
2036
2219
  }
2037
- return clean(element.textContent) || void 0;
2220
+ return clean(renderedText(element)) || void 0;
2038
2221
  };
2039
2222
  const TEST_ID_ATTRIBUTES = ["data-testid", "data-test-id", "data-test", "data-qa", "data-cy"];
2040
2223
  const testIdOf = (element) => {
@@ -3796,18 +3979,24 @@ Saved CSV: ${csvPath}`);
3796
3979
  }
3797
3980
 
3798
3981
  // src/commands/serve.ts
3799
- import { dirname as dirname4, join as join4 } from "node:path";
3982
+ import { dirname as dirname10, join as join6 } from "node:path";
3800
3983
  import { fileURLToPath } from "node:url";
3801
3984
 
3802
3985
  // ../server/dist/app.js
3803
3986
  import Fastify from "fastify";
3804
3987
  import fastifyStatic from "@fastify/static";
3805
3988
 
3989
+ // ../server/dist/routes/analyze.js
3990
+ import { dirname as dirname4 } from "node:path";
3991
+
3806
3992
  // ../server/dist/config.js
3993
+ var headedBrowser = /^(1|true|yes)$/i.test(process.env.LAZYSCOUT_HEADED ?? "");
3807
3994
  var config = {
3808
3995
  host: process.env.HOST ?? "127.0.0.1",
3809
3996
  port: Number(process.env.PORT ?? 4e3),
3810
3997
  urlPolicy: process.env.LAZYSCOUT_MODE === "public" ? PUBLIC_SAAS_POLICY : LOCAL_QA_POLICY,
3998
+ /** Shared by Open login browser, Recorder, Scout and the Test runner. */
3999
+ headless: !headedBrowser,
3811
4000
  limits: {
3812
4001
  maxPages: 20,
3813
4002
  maxDepth: 3
@@ -3819,6 +4008,223 @@ function clamp(value, min, max, fallback) {
3819
4008
  return Math.min(Math.max(Math.trunc(value), min), max);
3820
4009
  }
3821
4010
 
4011
+ // ../server/dist/auth/authLock.js
4012
+ import { mkdir, readFile, rm, writeFile as writeFile2 } from "node:fs/promises";
4013
+ import { dirname, join } from "node:path";
4014
+ var AuthProfileBusyError = class extends Error {
4015
+ current;
4016
+ code = "auth-profile-busy";
4017
+ constructor(current) {
4018
+ super(`The authenticated profile is in use by ${current.holder} (pid ${current.pid}). Running two of them against one saved session makes an application that rotates refresh tokens sign both out.`);
4019
+ this.current = current;
4020
+ this.name = "AuthProfileBusyError";
4021
+ }
4022
+ };
4023
+ var STALE_AFTER_MS = 15 * 60 * 1e3;
4024
+ function lockPath(projectDirectory2) {
4025
+ return join(projectDirectory2, "auth", "lock.json");
4026
+ }
4027
+ function isAlive(pid) {
4028
+ if (pid === process.pid)
4029
+ return true;
4030
+ try {
4031
+ process.kill(pid, 0);
4032
+ return true;
4033
+ } catch {
4034
+ return false;
4035
+ }
4036
+ }
4037
+ async function readRawLock(projectDirectory2) {
4038
+ try {
4039
+ const raw = JSON.parse(await readFile(lockPath(projectDirectory2), "utf8"));
4040
+ return raw?.pid && raw.since ? raw : void 0;
4041
+ } catch {
4042
+ return void 0;
4043
+ }
4044
+ }
4045
+ async function readLock(projectDirectory2) {
4046
+ const raw = await readRawLock(projectDirectory2);
4047
+ if (!raw)
4048
+ return void 0;
4049
+ const age = Date.now() - new Date(raw.since).getTime();
4050
+ if (age > STALE_AFTER_MS || !isAlive(raw.pid))
4051
+ return void 0;
4052
+ return raw;
4053
+ }
4054
+ async function acquireAuthLock(projectDirectory2, holder, options = {}) {
4055
+ const current = await readLock(projectDirectory2);
4056
+ if (current)
4057
+ throw new AuthProfileBusyError(current);
4058
+ const info = { holder, pid: process.pid, since: (/* @__PURE__ */ new Date()).toISOString() };
4059
+ const path = lockPath(projectDirectory2);
4060
+ await mkdir(dirname(path), { recursive: true });
4061
+ await writeFile2(path, `${JSON.stringify(info, null, 2)}
4062
+ `, { mode: 384 });
4063
+ options.log?.(`[Auth] Profile locked by ${holder}`);
4064
+ let released = false;
4065
+ return async () => {
4066
+ if (released)
4067
+ return;
4068
+ released = true;
4069
+ const held = await readRawLock(projectDirectory2);
4070
+ if (held && held.pid !== process.pid)
4071
+ return;
4072
+ await rm(path, { force: true }).catch(() => void 0);
4073
+ options.log?.(`[Auth] Profile released by ${holder}`);
4074
+ };
4075
+ }
4076
+ async function currentAuthLock(projectDirectory2) {
4077
+ return readLock(projectDirectory2);
4078
+ }
4079
+
4080
+ // ../server/dist/auth/authState.js
4081
+ import { mkdir as mkdir2, readFile as readFile2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
4082
+ import { dirname as dirname2, join as join2 } from "node:path";
4083
+ var EMPTY_META = { status: "not-configured" };
4084
+ function authDirectory(projectDirectory2) {
4085
+ return join2(projectDirectory2, "auth");
4086
+ }
4087
+ function authStatePath(projectDirectory2) {
4088
+ return join2(authDirectory(projectDirectory2), "storage-state.json");
4089
+ }
4090
+ function authMetaPath(projectDirectory2) {
4091
+ return join2(authDirectory(projectDirectory2), "meta.json");
4092
+ }
4093
+ async function writeJsonPrivate(path, value) {
4094
+ await mkdir2(dirname2(path), { recursive: true });
4095
+ await writeFile3(path, `${JSON.stringify(value, null, 2)}
4096
+ `, { mode: 384 });
4097
+ }
4098
+ async function readJson(path, fallback) {
4099
+ try {
4100
+ return JSON.parse(await readFile2(path, "utf8"));
4101
+ } catch {
4102
+ return fallback;
4103
+ }
4104
+ }
4105
+ async function waitForAuthSettle(context, page, options = {}) {
4106
+ const pollMs = options.pollMs ?? 250;
4107
+ const stableSamples = options.stableSamples ?? 3;
4108
+ const timeoutMs = options.timeoutMs ?? 1e4;
4109
+ const startedAt = Date.now();
4110
+ options.log?.("[Auth] Waiting for session stabilization");
4111
+ await page?.waitForLoadState("networkidle", { timeout: Math.min(5e3, timeoutMs) }).catch(() => void 0);
4112
+ let previous = "";
4113
+ let stable = 0;
4114
+ while (Date.now() - startedAt < timeoutMs) {
4115
+ const cookies = await context.cookies().catch(() => []);
4116
+ const signature = cookies.map((cookie) => `${cookie.domain}|${cookie.path}|${cookie.name}|${cookie.expires > 0 ? "p" : "s"}`).sort().join(",");
4117
+ if (signature === previous) {
4118
+ stable += 1;
4119
+ if (stable >= stableSamples)
4120
+ return;
4121
+ } else {
4122
+ previous = signature;
4123
+ stable = 0;
4124
+ }
4125
+ await new Promise((resolve3) => setTimeout(resolve3, pollMs));
4126
+ }
4127
+ }
4128
+ async function captureSessionStorage(context) {
4129
+ const snapshot = [];
4130
+ for (const page of context.pages()) {
4131
+ if (page.isClosed())
4132
+ continue;
4133
+ try {
4134
+ const origin = new URL(page.url()).origin;
4135
+ if (!origin.startsWith("http"))
4136
+ continue;
4137
+ if (snapshot.some((entry) => entry.origin === origin))
4138
+ continue;
4139
+ const items = await page.evaluate(readSessionStorage);
4140
+ if (items.length)
4141
+ snapshot.push({ origin, items });
4142
+ } catch {
4143
+ }
4144
+ }
4145
+ return snapshot;
4146
+ }
4147
+ async function captureAuthSnapshot(context, options = {}) {
4148
+ let indexedDb = true;
4149
+ let storageState;
4150
+ try {
4151
+ storageState = await context.storageState({ indexedDB: true });
4152
+ } catch {
4153
+ indexedDb = false;
4154
+ storageState = await context.storageState();
4155
+ }
4156
+ const sessionStorage = await captureSessionStorage(context);
4157
+ options.log?.("[Auth] Storage state captured");
4158
+ return { snapshot: { storageState, sessionStorage }, indexedDb };
4159
+ }
4160
+ function describe(snapshot, indexedDb, capturedHeadless) {
4161
+ const cookies = snapshot.storageState.cookies ?? [];
4162
+ return {
4163
+ status: "recorded",
4164
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
4165
+ cookieCount: cookies.length,
4166
+ // Expiry <= 0 means the cookie dies with the browser — exactly the kind a
4167
+ // profile directory loses and this snapshot preserves.
4168
+ sessionCookieCount: cookies.filter((cookie) => !(cookie.expires > 0)).length,
4169
+ originCount: (snapshot.storageState.origins ?? []).length,
4170
+ sessionStorageOriginCount: snapshot.sessionStorage.length,
4171
+ indexedDb,
4172
+ capturedHeadless
4173
+ };
4174
+ }
4175
+ async function saveAuthSnapshot(projectDirectory2, snapshot, options) {
4176
+ const meta = describe(snapshot, options.indexedDb, options.capturedHeadless);
4177
+ await writeJsonPrivate(authStatePath(projectDirectory2), snapshot);
4178
+ await writeJsonPrivate(authMetaPath(projectDirectory2), meta);
4179
+ options.log?.("[Auth] Auth snapshot saved");
4180
+ return meta;
4181
+ }
4182
+ async function loadAuthSnapshot(projectDirectory2) {
4183
+ const snapshot = await readJson(authStatePath(projectDirectory2), void 0);
4184
+ if (!snapshot?.storageState)
4185
+ return void 0;
4186
+ return { storageState: snapshot.storageState, sessionStorage: snapshot.sessionStorage ?? [] };
4187
+ }
4188
+ async function readAuthMeta(projectDirectory2) {
4189
+ return readJson(authMetaPath(projectDirectory2), EMPTY_META);
4190
+ }
4191
+ async function updateAuthMeta(projectDirectory2, patch) {
4192
+ const next = { ...await readAuthMeta(projectDirectory2), ...patch };
4193
+ await writeJsonPrivate(authMetaPath(projectDirectory2), next);
4194
+ return next;
4195
+ }
4196
+ async function clearAuthSnapshot(projectDirectory2) {
4197
+ await rm2(authDirectory(projectDirectory2), { recursive: true, force: true });
4198
+ }
4199
+ async function restoreSessionStorage(context, sessionStorage) {
4200
+ if (sessionStorage.length === 0)
4201
+ return;
4202
+ await context.addInitScript(writeSessionStorage, sessionStorage);
4203
+ }
4204
+ async function verifyAuthState(page, protectedUrl, options = {}) {
4205
+ options.log?.("[Auth] Verifying protected state");
4206
+ try {
4207
+ await page.goto(protectedUrl, { waitUntil: "domcontentloaded", timeout: options.timeoutMs ?? 2e4 });
4208
+ } catch (error) {
4209
+ return { ok: false, landedOn: page.url(), detail: error instanceof Error ? error.message : "navigation failed" };
4210
+ }
4211
+ const landedOn = page.url();
4212
+ if (looksLikeSignIn(landedOn, protectedUrl)) {
4213
+ return { ok: false, landedOn, detail: "redirected to a sign-in page" };
4214
+ }
4215
+ return { ok: true, landedOn };
4216
+ }
4217
+ function looksLikeSignIn(landedOn, requested) {
4218
+ try {
4219
+ const landedPath = new URL(landedOn).pathname.toLowerCase();
4220
+ const requestedPath = new URL(requested, landedOn).pathname.toLowerCase();
4221
+ const isSignIn = /\/(login|signin|sign-in|auth)(\/|$)/.test(landedPath);
4222
+ return isSignIn && !/\/(login|signin|sign-in|auth)(\/|$)/.test(requestedPath);
4223
+ } catch {
4224
+ return false;
4225
+ }
4226
+ }
4227
+
3822
4228
  // ../server/dist/toApiError.js
3823
4229
  function toApiError(error) {
3824
4230
  if (error instanceof ExplorerError) {
@@ -3850,25 +4256,25 @@ function toApiError(error) {
3850
4256
  import { execFile } from "node:child_process";
3851
4257
  import { randomUUID } from "node:crypto";
3852
4258
  import { homedir, platform } from "node:os";
3853
- import { basename, dirname, extname, isAbsolute, join, relative, resolve as resolve2 } from "node:path";
3854
- import { mkdir, readFile, readdir, rename, rm, stat, writeFile as writeFile2 } from "node:fs/promises";
4259
+ import { basename, dirname as dirname3, extname, isAbsolute, join as join3, relative, resolve as resolve2 } from "node:path";
4260
+ import { mkdir as mkdir3, readFile as readFile3, readdir, rename, rm as rm3, stat, writeFile as writeFile4 } from "node:fs/promises";
3855
4261
  import { promisify } from "node:util";
3856
4262
  var execFileAsync = promisify(execFile);
3857
4263
  var PROJECT_ID = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
3858
4264
  var FILE_NAME = /^[^\\/:*?"<>|]{1,160}$/;
3859
4265
  var mutationQueues = /* @__PURE__ */ new Map();
3860
4266
  function defaultWorkspaceRoot() {
3861
- return join(homedir(), "LazyScout");
4267
+ return join3(homedir(), "LazyScout");
3862
4268
  }
3863
4269
  function resolveWorkspaceRoot(value) {
3864
4270
  return resolve2(value?.trim() || process.env.LAZYSCOUT_WORKSPACE || defaultWorkspaceRoot());
3865
4271
  }
3866
4272
  async function ensureWorkspace(root) {
3867
4273
  await Promise.all([
3868
- mkdir(join(root, "projects"), { recursive: true }),
3869
- mkdir(join(root, "backups"), { recursive: true })
4274
+ mkdir3(join3(root, "projects"), { recursive: true }),
4275
+ mkdir3(join3(root, "backups"), { recursive: true })
3870
4276
  ]);
3871
- const settingsPath = join(root, "settings.json");
4277
+ const settingsPath = join3(root, "settings.json");
3872
4278
  try {
3873
4279
  await stat(settingsPath);
3874
4280
  } catch {
@@ -3877,7 +4283,7 @@ async function ensureWorkspace(root) {
3877
4283
  }
3878
4284
  async function listProjects(root) {
3879
4285
  await ensureWorkspace(root);
3880
- const entries = await readdir(join(root, "projects"), { withFileTypes: true });
4286
+ const entries = await readdir(join3(root, "projects"), { withFileTypes: true });
3881
4287
  const projects = await Promise.all(entries.filter((entry) => entry.isDirectory() && PROJECT_ID.test(entry.name)).map((entry) => readProject(root, entry.name)));
3882
4288
  return projects.filter((project) => Boolean(project)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
3883
4289
  }
@@ -3888,10 +4294,10 @@ async function saveProject(root, project) {
3888
4294
  const { testCases, ...result } = normalized;
3889
4295
  const testData = normalized.testData;
3890
4296
  await Promise.all([
3891
- writeJson(join(directory, "project.json"), { ...project, result }),
3892
- writeJson(join(directory, "test-cases.json"), testCases),
3893
- writeFileAtomic(join(directory, "test-cases.csv"), exportTestCasesToCsv(testCases, testData)),
3894
- writeFileAtomic(join(directory, "test-data.csv"), testDataCsv(testData))
4297
+ writeJson(join3(directory, "project.json"), { ...project, result }),
4298
+ writeJson(join3(directory, "test-cases.json"), testCases),
4299
+ writeFileAtomic(join3(directory, "test-cases.csv"), exportTestCasesToCsv(testCases, testData)),
4300
+ writeFileAtomic(join3(directory, "test-data.csv"), testDataCsv(testData))
3895
4301
  ]);
3896
4302
  });
3897
4303
  }
@@ -3905,16 +4311,16 @@ async function deleteProject(root, projectId) {
3905
4311
  }
3906
4312
  await ensureWorkspace(root);
3907
4313
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3908
- await rename(source, join(root, "backups", `${projectId}-${timestamp}`));
4314
+ await rename(source, join3(root, "backups", `${projectId}-${timestamp}`));
3909
4315
  });
3910
4316
  }
3911
4317
  async function readScreenshots(root, projectId) {
3912
4318
  const directory = await ensureProject(root, projectId);
3913
- return readJson(join(directory, "screenshots", "index.json"), []);
4319
+ return readJson2(join3(directory, "screenshots", "index.json"), []);
3914
4320
  }
3915
4321
  async function saveScreenshot(root, projectId, screenshot) {
3916
4322
  return enqueueMutation(`screenshots:${projectId}`, async () => {
3917
- const directory = join(await ensureProject(root, projectId), "screenshots");
4323
+ const directory = join3(await ensureProject(root, projectId), "screenshots");
3918
4324
  const match = screenshot.dataUrl.match(/^data:image\/(png|jpeg);base64,([a-zA-Z0-9+/=]+)$/);
3919
4325
  if (!match)
3920
4326
  throw new Error("Screenshot must be a PNG or JPEG data URL");
@@ -3924,44 +4330,44 @@ async function saveScreenshot(root, projectId, screenshot) {
3924
4330
  const extension = match[1] === "jpeg" ? ".jpg" : ".png";
3925
4331
  const requested = safeFileName(screenshot.name, `screenshot-${Date.now()}${extension}`);
3926
4332
  const name = extname(requested) ? `${basename(requested, extname(requested))}${extension}` : `${requested}${extension}`;
3927
- await writeFileAtomic(join(directory, name), image);
4333
+ await writeFileAtomic(join3(directory, name), image);
3928
4334
  const current = await readScreenshots(root, projectId);
3929
4335
  const stored = { ...screenshot, name, dataUrl: screenshotUrl(projectId, name) };
3930
4336
  const next = [stored, ...current.filter((item) => item.name !== name)].slice(0, 50);
3931
- await writeJson(join(directory, "index.json"), next);
4337
+ await writeJson(join3(directory, "index.json"), next);
3932
4338
  return stored;
3933
4339
  });
3934
4340
  }
3935
4341
  async function deleteScreenshot(root, projectId, name) {
3936
4342
  const safeName2 = assertFileName(name);
3937
- const directory = join(await ensureProject(root, projectId), "screenshots");
3938
- await rm(join(directory, safeName2), { force: true });
4343
+ const directory = join3(await ensureProject(root, projectId), "screenshots");
4344
+ await rm3(join3(directory, safeName2), { force: true });
3939
4345
  const current = await readScreenshots(root, projectId);
3940
- await writeJson(join(directory, "index.json"), current.filter((item) => item.name !== safeName2));
4346
+ await writeJson(join3(directory, "index.json"), current.filter((item) => item.name !== safeName2));
3941
4347
  }
3942
4348
  async function screenshotFile(root, projectId, name) {
3943
- return readFile(join(await ensureProject(root, projectId), "screenshots", assertFileName(name)));
4349
+ return readFile3(join3(await ensureProject(root, projectId), "screenshots", assertFileName(name)));
3944
4350
  }
3945
4351
  async function listBugReports(root, projectId) {
3946
- const directory = join(await ensureProject(root, projectId), "bugs");
4352
+ const directory = join3(await ensureProject(root, projectId), "bugs");
3947
4353
  const entries = await readdir(directory, { withFileTypes: true });
3948
- 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)));
4354
+ const reports = await Promise.all(entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json") && entry.name !== "index.json").map((entry) => readJson2(join3(directory, entry.name), null)));
3949
4355
  return reports.filter((report) => Boolean(report));
3950
4356
  }
3951
4357
  async function saveBugReport(root, projectId, report) {
3952
- const directory = join(await ensureProject(root, projectId), "bugs");
3953
- await writeJson(join(directory, `${safeFileName(report.id, `BUG-${Date.now()}`)}.json`), report);
4358
+ const directory = join3(await ensureProject(root, projectId), "bugs");
4359
+ await writeJson(join3(directory, `${safeFileName(report.id, `BUG-${Date.now()}`)}.json`), report);
3954
4360
  }
3955
4361
  async function deleteBugReport(root, projectId, bugId) {
3956
- const directory = join(await ensureProject(root, projectId), "bugs");
3957
- await rm(join(directory, `${safeFileName(bugId, "bug")}.json`), { force: true });
4362
+ const directory = join3(await ensureProject(root, projectId), "bugs");
4363
+ await rm3(join3(directory, `${safeFileName(bugId, "bug")}.json`), { force: true });
3958
4364
  }
3959
4365
  async function readAutomation(root, projectId) {
3960
- const directory = join(await ensureProject(root, projectId), "automation");
3961
- const index = await readJson(join(directory, "index.json"), {});
4366
+ const directory = join3(await ensureProject(root, projectId), "automation");
4367
+ const index = await readJson2(join3(directory, "index.json"), {});
3962
4368
  const entries = await Promise.all(Object.entries(index).map(async ([key, name]) => {
3963
4369
  try {
3964
- return [key, await readFile(join(directory, assertFileName(name)), "utf8")];
4370
+ return [key, await readFile3(join3(directory, assertFileName(name)), "utf8")];
3965
4371
  } catch {
3966
4372
  return void 0;
3967
4373
  }
@@ -3969,8 +4375,8 @@ async function readAutomation(root, projectId) {
3969
4375
  return Object.fromEntries(entries.filter((entry) => Boolean(entry)));
3970
4376
  }
3971
4377
  async function saveAutomation(root, projectId, overrides) {
3972
- const directory = join(await ensureProject(root, projectId), "automation");
3973
- const previous = await readJson(join(directory, "index.json"), {});
4378
+ const directory = join3(await ensureProject(root, projectId), "automation");
4379
+ const previous = await readJson2(join3(directory, "index.json"), {});
3974
4380
  const next = {};
3975
4381
  for (const [key, source] of Object.entries(overrides)) {
3976
4382
  if (typeof source !== "string" || source.length > 2e5)
@@ -3981,22 +4387,22 @@ async function saveAutomation(root, projectId, overrides) {
3981
4387
  const extension = framework === "playwright" ? ".spec.ts" : ".cy.ts";
3982
4388
  const name = `${framework}-${safeFileName(caseId, "test-case")}${extension}`;
3983
4389
  next[key] = name;
3984
- await writeFileAtomic(join(directory, name), source);
4390
+ await writeFileAtomic(join3(directory, name), source);
3985
4391
  }
3986
4392
  for (const name of Object.values(previous))
3987
4393
  if (!Object.values(next).includes(name))
3988
- await rm(join(directory, assertFileName(name)), { force: true });
3989
- await writeJson(join(directory, "index.json"), next);
4394
+ await rm3(join3(directory, assertFileName(name)), { force: true });
4395
+ await writeJson(join3(directory, "index.json"), next);
3990
4396
  }
3991
4397
  async function saveRunLog(root, projectId, testCaseId, status, logs) {
3992
- const directory = join(await ensureProject(root, projectId), "logs");
4398
+ const directory = join3(await ensureProject(root, projectId), "logs");
3993
4399
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3994
4400
  const name = `${timestamp}-${safeFileName(testCaseId, "test-case")}.json`;
3995
- await writeJson(join(directory, name), { testCaseId, status, createdAt: (/* @__PURE__ */ new Date()).toISOString(), logs });
4401
+ await writeJson(join3(directory, name), { testCaseId, status, createdAt: (/* @__PURE__ */ new Date()).toISOString(), logs });
3996
4402
  }
3997
4403
  async function readGuidedFlows(root, projectId) {
3998
4404
  const directory = await ensureProject(root, projectId);
3999
- return readJson(join(directory, "guided-flows.json"), []);
4405
+ return readJson2(join3(directory, "guided-flows.json"), []);
4000
4406
  }
4001
4407
  async function saveGuidedFlows(root, projectId, flows) {
4002
4408
  if (!Array.isArray(flows) || flows.length > 100)
@@ -4006,14 +4412,14 @@ async function saveGuidedFlows(root, projectId, flows) {
4006
4412
  throw new Error("Invalid Guided Flow");
4007
4413
  }
4008
4414
  const directory = await ensureProject(root, projectId);
4009
- await writeJson(join(directory, "guided-flows.json"), flows);
4415
+ await writeJson(join3(directory, "guided-flows.json"), flows);
4010
4416
  }
4011
4417
  async function saveReport(root, projectId, name, html) {
4012
4418
  if (typeof html !== "string" || html.length > 2e6)
4013
4419
  throw new Error("Report exceeds the 2 MB limit");
4014
- const directory = join(await ensureProject(root, projectId), "reports");
4420
+ const directory = join3(await ensureProject(root, projectId), "reports");
4015
4421
  const fileName = `${safeFileName(name, `quality-report-${Date.now()}.html`).replace(/\.[^.]+$/, "")}.html`;
4016
- await writeFileAtomic(join(directory, fileName), html);
4422
+ await writeFileAtomic(join3(directory, fileName), html);
4017
4423
  return fileName;
4018
4424
  }
4019
4425
  async function openWorkspace(root) {
@@ -4026,18 +4432,18 @@ async function openWorkspace(root) {
4026
4432
  await execFileAsync("xdg-open", [root]);
4027
4433
  }
4028
4434
  async function browserProfileDirectory(root, projectId) {
4029
- return join(await ensureProject(root, projectId), "browser-profile");
4435
+ return join3(await ensureProject(root, projectId), "browser-profile");
4030
4436
  }
4031
4437
  async function browserProfileStatus(root, projectId) {
4032
- const directory = join(projectDirectory(root, projectId), "browser-profile");
4438
+ const directory = join3(projectDirectory(root, projectId), "browser-profile");
4033
4439
  try {
4034
4440
  const entries = await readdir(directory);
4035
4441
  const candidates = [
4036
4442
  directory,
4037
- join(directory, "Local State"),
4038
- join(directory, "Default"),
4039
- join(directory, "Default", "Cookies"),
4040
- join(directory, "Default", "Local Storage")
4443
+ join3(directory, "Local State"),
4444
+ join3(directory, "Default"),
4445
+ join3(directory, "Default", "Cookies"),
4446
+ join3(directory, "Default", "Local Storage")
4041
4447
  ];
4042
4448
  const modifiedTimes = await Promise.all(candidates.map(async (candidate) => {
4043
4449
  try {
@@ -4057,16 +4463,16 @@ async function browserProfileStatus(root, projectId) {
4057
4463
  }
4058
4464
  }
4059
4465
  async function clearBrowserProfile(root, projectId) {
4060
- const directory = join(projectDirectory(root, projectId), "browser-profile");
4061
- await rm(directory, { recursive: true, force: true });
4466
+ const directory = join3(projectDirectory(root, projectId), "browser-profile");
4467
+ await rm3(directory, { recursive: true, force: true });
4062
4468
  }
4063
4469
  async function readProject(root, projectId) {
4064
4470
  try {
4065
4471
  const directory = projectDirectory(root, projectId);
4066
- const project = await readJson(join(directory, "project.json"), void 0);
4472
+ const project = await readJson2(join3(directory, "project.json"), void 0);
4067
4473
  if (!project)
4068
4474
  return void 0;
4069
- const testCases = await readJson(join(directory, "test-cases.json"), []);
4475
+ const testCases = await readJson2(join3(directory, "test-cases.json"), []);
4070
4476
  return { ...project, result: normalizeResult({ ...project.result, testCases }) };
4071
4477
  } catch {
4072
4478
  return void 0;
@@ -4075,13 +4481,13 @@ async function readProject(root, projectId) {
4075
4481
  async function ensureProject(root, projectId) {
4076
4482
  await ensureWorkspace(root);
4077
4483
  const directory = projectDirectory(root, projectId);
4078
- await Promise.all(["automation", "screenshots", "bugs", "reports", "logs", "browser-profile"].map((name) => mkdir(join(directory, name), { recursive: true })));
4484
+ await Promise.all(["automation", "screenshots", "bugs", "reports", "logs", "browser-profile"].map((name) => mkdir3(join3(directory, name), { recursive: true })));
4079
4485
  return directory;
4080
4486
  }
4081
4487
  function projectDirectory(root, projectId) {
4082
4488
  if (!PROJECT_ID.test(projectId))
4083
4489
  throw new Error("Invalid project ID");
4084
- return containedPath(join(root, "projects"), projectId);
4490
+ return containedPath(join3(root, "projects"), projectId);
4085
4491
  }
4086
4492
  function containedPath(root, value) {
4087
4493
  const target = resolve2(root, value);
@@ -4102,9 +4508,9 @@ function safeFileName(value, fallback) {
4102
4508
  function screenshotUrl(projectId, name) {
4103
4509
  return `/api/workspace/projects/${encodeURIComponent(projectId)}/screenshots/${encodeURIComponent(name)}`;
4104
4510
  }
4105
- async function readJson(path, fallback) {
4511
+ async function readJson2(path, fallback) {
4106
4512
  try {
4107
- return JSON.parse(await readFile(path, "utf8"));
4513
+ return JSON.parse(await readFile3(path, "utf8"));
4108
4514
  } catch {
4109
4515
  return fallback;
4110
4516
  }
@@ -4114,10 +4520,10 @@ async function writeJson(path, value) {
4114
4520
  `);
4115
4521
  }
4116
4522
  async function writeFileAtomic(path, value) {
4117
- await mkdir(dirname(path), { recursive: true });
4523
+ await mkdir3(dirname3(path), { recursive: true });
4118
4524
  const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
4119
- await writeFile2(temporary, value);
4120
- await rm(path, { force: true });
4525
+ await writeFile4(temporary, value);
4526
+ await rm3(path, { force: true });
4121
4527
  await rename(temporary, path);
4122
4528
  }
4123
4529
  function testDataCsv(rows) {
@@ -4186,6 +4592,20 @@ function registerAnalyzeRoute(app, workspaceRoot) {
4186
4592
  return reply.status(400).send({ error: { code: check.code, message: check.message } });
4187
4593
  }
4188
4594
  const browserProfileDir = body.projectId ? await browserProfileDirectory(workspaceRoot, body.projectId).catch(() => void 0) : void 0;
4595
+ const projectDirectory2 = browserProfileDir ? dirname4(browserProfileDir) : void 0;
4596
+ const authRestore = projectDirectory2 ? await loadAuthSnapshot(projectDirectory2).catch(() => void 0) : void 0;
4597
+ let releaseAuthLock;
4598
+ if (projectDirectory2 && authRestore) {
4599
+ try {
4600
+ releaseAuthLock = await acquireAuthLock(projectDirectory2, "scout", {
4601
+ log: (message) => request.log.info(message)
4602
+ });
4603
+ } catch (error) {
4604
+ if (error instanceof AuthProfileBusyError)
4605
+ return reply.status(409).send({ error: { code: error.code, message: error.message } });
4606
+ throw error;
4607
+ }
4608
+ }
4189
4609
  try {
4190
4610
  const abortController = new AbortController();
4191
4611
  let completed = false;
@@ -4211,7 +4631,8 @@ function registerAnalyzeRoute(app, workspaceRoot) {
4211
4631
  waitAfterNavigationMs: clamp(body.waitAfterNavigationMs, 0, 5e3, 750),
4212
4632
  blockedKeywords: normalizeBlockedKeywords(body.blockedKeywords),
4213
4633
  signal: abortController.signal,
4214
- ...browserProfileDir ? { browserProfileDir } : {}
4634
+ headless: config.headless,
4635
+ ...authRestore ? { authRestore: { storageState: authRestore.storageState, sessionStorage: authRestore.sessionStorage } } : browserProfileDir ? { browserProfileDir } : {}
4215
4636
  });
4216
4637
  if (result.pages.length === 0) {
4217
4638
  const firstIssue = result.issues[0];
@@ -4299,6 +4720,8 @@ function registerAnalyzeRoute(app, workspaceRoot) {
4299
4720
  request.log.error({ message: redactSensitiveText(error instanceof Error ? error.message : String(error)) }, "analyze failed");
4300
4721
  const { status, body: errorBody } = toApiError(error);
4301
4722
  return reply.status(status).send(errorBody);
4723
+ } finally {
4724
+ await releaseAuthLock?.().catch(() => void 0);
4302
4725
  }
4303
4726
  });
4304
4727
  }
@@ -4393,33 +4816,38 @@ function registerExportCsvRoute(app) {
4393
4816
  });
4394
4817
  }
4395
4818
 
4819
+ // ../server/dist/routes/automationRun.js
4820
+ import { dirname as dirname6 } from "node:path";
4821
+
4396
4822
  // ../server/dist/routes/playwrightCliRunner.js
4397
4823
  import { createRequire } from "node:module";
4398
4824
  import { spawn } from "node:child_process";
4399
- import { mkdtemp, readdir as readdir2, readFile as readFile2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
4400
- import { dirname as dirname2, join as join2 } from "node:path";
4825
+ import { mkdtemp, readdir as readdir2, readFile as readFile4, rm as rm4, writeFile as writeFile5 } from "node:fs/promises";
4826
+ import { dirname as dirname5, join as join4 } from "node:path";
4401
4827
  var require2 = createRequire(import.meta.url);
4402
4828
  var CLI_ENTRY = require2.resolve("@playwright/test/cli");
4403
4829
  var MAX_SCREENSHOTS = 10;
4404
4830
  async function runPlaywrightCli(input) {
4405
4831
  const started = Date.now();
4406
- const runDirectory = await mkdtemp(join2(dirname2(CLI_ENTRY), ".lazyscout-run-"));
4407
- const source = resolveSource(input.source, input.testCase, input.secrets, Boolean(input.profileDirectory));
4832
+ const runDirectory = await mkdtemp(join4(dirname5(CLI_ENTRY), ".lazyscout-run-"));
4833
+ const useContextFixture = Boolean(input.authStatePath || input.profileDirectory);
4834
+ const source = resolveSource(input.source, input.testCase, input.secrets, useContextFixture);
4408
4835
  validateLiteralNavigationUrls(source);
4409
- const specPath = join2(runDirectory, `${safeName(input.testCaseId)}.spec.ts`);
4410
- const configPath = join2(runDirectory, "playwright.config.mjs");
4411
- await writeFile3(specPath, source, "utf8");
4412
- if (input.profileDirectory) {
4413
- const fixture = createProfileFixture();
4414
- await writeFile3(join2(runDirectory, "lazyscout-fixture.mjs"), fixture, "utf8");
4415
- }
4416
- await writeFile3(configPath, createConfig(), "utf8");
4836
+ const specPath = join4(runDirectory, `${safeName(input.testCaseId)}.spec.ts`);
4837
+ const configPath = join4(runDirectory, "playwright.config.mjs");
4838
+ await writeFile5(specPath, source, "utf8");
4839
+ if (useContextFixture) {
4840
+ const fixture = createProfileFixture(input.headless ?? true);
4841
+ await writeFile5(join4(runDirectory, "lazyscout-fixture.mjs"), fixture, "utf8");
4842
+ }
4843
+ await writeFile5(configPath, createConfig(input.headless ?? true), "utf8");
4417
4844
  const child = spawn(process.execPath, [CLI_ENTRY, "test", "--config", configPath], {
4418
4845
  cwd: runDirectory,
4419
4846
  env: {
4420
4847
  ...process.env,
4421
4848
  FORCE_COLOR: "0",
4422
- ...input.profileDirectory ? { LAZYSCOUT_PROFILE_DIR: input.profileDirectory } : {}
4849
+ ...input.profileDirectory ? { LAZYSCOUT_PROFILE_DIR: input.profileDirectory } : {},
4850
+ ...input.authStatePath ? { LAZYSCOUT_AUTH_STATE: input.authStatePath } : {}
4423
4851
  },
4424
4852
  windowsHide: true,
4425
4853
  stdio: ["ignore", "pipe", "pipe"]
@@ -4465,11 +4893,11 @@ async function runPlaywrightCli(input) {
4465
4893
  input.addLog("fail", `Playwright Test failed (exit code ${exit.code ?? "unknown"})`, Date.now() - started);
4466
4894
  let error;
4467
4895
  if (status === "failed") {
4468
- const result = await readFile2(join2(runDirectory, "results.json"), "utf8").catch(() => "");
4896
+ const result = await readFile4(join4(runDirectory, "results.json"), "utf8").catch(() => "");
4469
4897
  error = summarizeFailure(result) ?? "Playwright Test failed. See the CLI output for details.";
4470
4898
  input.addLog("fail", error);
4471
4899
  }
4472
- await rm2(runDirectory, { recursive: true, force: true }).catch(() => void 0);
4900
+ await rm4(runDirectory, { recursive: true, force: true }).catch(() => void 0);
4473
4901
  return {
4474
4902
  status,
4475
4903
  error,
@@ -4490,13 +4918,37 @@ function resolveSource(source, testCase, secrets, useProfile = false) {
4490
4918
  ].join("\n");
4491
4919
  return useProfile ? fullSource.replace(/from\s+(['"])@playwright\/test\1/g, "from './lazyscout-fixture.mjs'") : fullSource;
4492
4920
  }
4493
- function createProfileFixture() {
4921
+ function createProfileFixture(headless) {
4494
4922
  return `import { test as base, expect } from '@playwright/test'
4495
4923
  import { chromium } from 'playwright-core'
4924
+ import { readFileSync } from 'node:fs'
4925
+
4926
+ const headless = ${headless ? "true" : "false"}
4927
+ const snapshotPath = process.env.LAZYSCOUT_AUTH_STATE
4928
+ const profileDir = process.env.LAZYSCOUT_PROFILE_DIR
4496
4929
 
4497
4930
  export const test = base.extend({
4498
4931
  context: async ({}, use) => {
4499
- const context = await chromium.launchPersistentContext(process.env.LAZYSCOUT_PROFILE_DIR, { headless: true })
4932
+ if (snapshotPath) {
4933
+ const snapshot = JSON.parse(readFileSync(snapshotPath, 'utf8'))
4934
+ const browser = await chromium.launch({ headless })
4935
+ const context = await browser.newContext({ storageState: snapshot.storageState })
4936
+ const sessionStorage = snapshot.sessionStorage ?? []
4937
+ if (sessionStorage.length) {
4938
+ await context.addInitScript((origins) => {
4939
+ try {
4940
+ const match = origins.find((entry) => entry.origin === window.location.origin)
4941
+ if (!match) return
4942
+ for (const item of match.items) window.sessionStorage.setItem(item.name, item.value)
4943
+ } catch {}
4944
+ }, sessionStorage)
4945
+ }
4946
+ await use(context)
4947
+ await context.close()
4948
+ await browser.close()
4949
+ return
4950
+ }
4951
+ const context = await chromium.launchPersistentContext(profileDir, { headless })
4500
4952
  await use(context)
4501
4953
  await context.close()
4502
4954
  }
@@ -4531,7 +4983,7 @@ function validateLiteralNavigationUrls(source) {
4531
4983
  throw new Error(checked.message);
4532
4984
  }
4533
4985
  }
4534
- function createConfig() {
4986
+ function createConfig(headless) {
4535
4987
  return `import { defineConfig } from '@playwright/test'
4536
4988
  export default defineConfig({
4537
4989
  testDir: '.',
@@ -4540,7 +4992,7 @@ export default defineConfig({
4540
4992
  workers: 1,
4541
4993
  fullyParallel: false,
4542
4994
  reporter: [['line'], ['json', { outputFile: 'results.json' }]],
4543
- use: { headless: true, actionTimeout: 20000, navigationTimeout: 20000, screenshot: 'off' }
4995
+ use: { headless: ${headless ? "true" : "false"}, actionTimeout: 20000, navigationTimeout: 20000, screenshot: 'off' }
4544
4996
  })
4545
4997
  `;
4546
4998
  }
@@ -4549,7 +5001,7 @@ async function readScreenshots2(directory, testCaseId) {
4549
5001
  const screenshots = [];
4550
5002
  for (const file of files.slice(0, MAX_SCREENSHOTS)) {
4551
5003
  const extension = file.toLowerCase().endsWith(".jpg") || file.toLowerCase().endsWith(".jpeg") ? "jpeg" : "png";
4552
- const data = await readFile2(file);
5004
+ const data = await readFile4(file);
4553
5005
  screenshots.push({
4554
5006
  name: file.slice(directory.length + 1).replaceAll("\\", "/"),
4555
5007
  dataUrl: `data:image/${extension};base64,${data.toString("base64")}`,
@@ -4564,7 +5016,7 @@ async function collectImages(directory) {
4564
5016
  const entries = await readdir2(directory, { withFileTypes: true });
4565
5017
  const files = [];
4566
5018
  for (const entry of entries) {
4567
- const path = join2(directory, entry.name);
5019
+ const path = join4(directory, entry.name);
4568
5020
  if (entry.isDirectory())
4569
5021
  files.push(...await collectImages(path));
4570
5022
  else if (/\.(png|jpe?g)$/i.test(entry.name))
@@ -4675,14 +5127,37 @@ function registerAutomationRunRoute(app, workspaceRoot) {
4675
5127
  }
4676
5128
  const active = { stopped: false };
4677
5129
  activeRuns.set(runId, active);
5130
+ const profileDirectory = body.projectId ? await browserProfileDirectory(workspaceRoot, body.projectId) : void 0;
5131
+ const projectDirectory2 = profileDirectory ? dirname6(profileDirectory) : void 0;
5132
+ const snapshot = projectDirectory2 ? await loadAuthSnapshot(projectDirectory2).catch(() => void 0) : void 0;
5133
+ let releaseAuthLock;
5134
+ if (projectDirectory2 && snapshot) {
5135
+ try {
5136
+ releaseAuthLock = await acquireAuthLock(projectDirectory2, "runner", {
5137
+ log: (message) => addLog("info", message)
5138
+ });
5139
+ } catch (error) {
5140
+ activeRuns.delete(runId);
5141
+ if (error instanceof AuthProfileBusyError) {
5142
+ addLog("warn", error.message);
5143
+ await persistLog("blocked");
5144
+ return reply.status(409).send({ error: { code: error.code, message: error.message } });
5145
+ }
5146
+ throw error;
5147
+ }
5148
+ }
4678
5149
  try {
5150
+ if (snapshot)
5151
+ addLog("info", "[Auth] Restoring authenticated state");
4679
5152
  const result = await runPlaywrightCli({
4680
5153
  source: body.code,
4681
5154
  testCase,
4682
5155
  testCaseId: testCase.id,
4683
5156
  secrets: body.secrets,
4684
5157
  secretValues,
4685
- profileDirectory: body.projectId ? await browserProfileDirectory(workspaceRoot, body.projectId) : void 0,
5158
+ headless: config.headless,
5159
+ ...snapshot && projectDirectory2 ? { authStatePath: authStatePath(projectDirectory2) } : {},
5160
+ profileDirectory,
4686
5161
  addLog,
4687
5162
  onProcess: (child) => {
4688
5163
  active.close = async () => {
@@ -4718,6 +5193,7 @@ function registerAutomationRunRoute(app, workspaceRoot) {
4718
5193
  return reply.send({ status: "failed", framework, logs, error: message });
4719
5194
  } finally {
4720
5195
  activeRuns.delete(runId);
5196
+ await releaseAuthLock?.().catch(() => void 0);
4721
5197
  }
4722
5198
  });
4723
5199
  }
@@ -4863,7 +5339,7 @@ function registerLoadTestRoute(app) {
4863
5339
  // ../server/dist/routes/versions.js
4864
5340
  import { spawn as spawn2 } from "node:child_process";
4865
5341
  import { access } from "node:fs/promises";
4866
- import { dirname as dirname3, join as join3 } from "node:path";
5342
+ import { dirname as dirname7, join as join5 } from "node:path";
4867
5343
  var PACKAGE_NAME = "lazyscout";
4868
5344
  var REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}`;
4869
5345
  var VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
@@ -4909,8 +5385,8 @@ async function fetchPublishedVersions(force = false) {
4909
5385
  async function findNpmCli() {
4910
5386
  const candidates = [
4911
5387
  process.env.npm_execpath,
4912
- join3(dirname3(process.execPath), "node_modules", "npm", "bin", "npm-cli.js"),
4913
- process.env.APPDATA ? join3(process.env.APPDATA, "npm", "node_modules", "npm", "bin", "npm-cli.js") : void 0,
5388
+ join5(dirname7(process.execPath), "node_modules", "npm", "bin", "npm-cli.js"),
5389
+ process.env.APPDATA ? join5(process.env.APPDATA, "npm", "node_modules", "npm", "bin", "npm-cli.js") : void 0,
4914
5390
  "/usr/lib/node_modules/npm/bin/npm-cli.js",
4915
5391
  "/usr/local/lib/node_modules/npm/bin/npm-cli.js"
4916
5392
  ].filter((value) => Boolean(value?.endsWith(".js")));
@@ -5029,6 +5505,11 @@ function registerVersionRoutes(app, currentVersion) {
5029
5505
  }
5030
5506
 
5031
5507
  // ../server/dist/routes/workspace.js
5508
+ import { dirname as dirname8 } from "node:path";
5509
+ var authSessions = /* @__PURE__ */ new Map();
5510
+ async function projectPath(root, projectId) {
5511
+ return dirname8(await browserProfileDirectory(root, projectId));
5512
+ }
5032
5513
  function registerWorkspaceRoutes(app, root) {
5033
5514
  app.get("/api/workspace", async () => ({ root, projects: await listProjects(root) }));
5034
5515
  app.post("/api/workspace/open", async (_request, reply) => {
@@ -5050,15 +5531,121 @@ function registerWorkspaceRoutes(app, root) {
5050
5531
  const body = request.body;
5051
5532
  if (!body?.url)
5052
5533
  return reply.status(400).send({ error: { code: "invalid-url", message: "A login URL is required." } });
5053
- const profile = await browserProfileDirectory(root, request.params.projectId);
5054
- const launched = await launchBrowser({ userDataDir: profile, headless: false });
5534
+ const check = checkTargetUrl(body.url, config.urlPolicy);
5535
+ if (!check.ok)
5536
+ return reply.status(400).send({ error: { code: check.code, message: check.message } });
5537
+ const { projectId } = request.params;
5538
+ const projectDirectory2 = await projectPath(root, projectId);
5539
+ const log = (message) => request.log.info(message);
5540
+ let release;
5541
+ try {
5542
+ release = await acquireAuthLock(projectDirectory2, "login-browser", { log });
5543
+ } catch (error) {
5544
+ if (error instanceof AuthProfileBusyError)
5545
+ return reply.status(409).send({
5546
+ error: { code: error.code, message: error.message, hint: "Close the other LazyScout browser and try again." }
5547
+ });
5548
+ throw error;
5549
+ }
5550
+ const headless = config.headless;
5551
+ const launched = await launchBrowser({ userDataDir: await browserProfileDirectory(root, projectId), headless });
5055
5552
  const page = launched.context.pages()[0] ?? await launched.context.newPage();
5056
- await page.goto(body.url, { waitUntil: "domcontentloaded" });
5057
- return reply.send({ opened: true });
5553
+ await page.goto(check.url.toString(), { waitUntil: "domcontentloaded" });
5554
+ await updateAuthMeta(projectDirectory2, { status: "verifying", detail: "Waiting for the sign-in window to close" });
5555
+ authSessions.set(projectId, { launched, release, headless, projectDirectory: projectDirectory2 });
5556
+ log("[Auth] Login browser opened");
5557
+ return reply.send({ opened: true, headless });
5558
+ });
5559
+ app.post("/api/workspace/projects/:projectId/auth-session/capture", async (request, reply) => {
5560
+ const { projectId } = request.params;
5561
+ const active = authSessions.get(projectId);
5562
+ if (!active)
5563
+ return reply.status(409).send({
5564
+ error: { code: "no-login-browser", message: "Open the login browser before capturing a session." }
5565
+ });
5566
+ const log = (message) => request.log.info(message);
5567
+ try {
5568
+ log("[Auth] Recorded login completed");
5569
+ const page = active.launched.context.pages().find((candidate) => !candidate.isClosed());
5570
+ await waitForAuthSettle(active.launched.context, page, { log });
5571
+ const { snapshot, indexedDb } = await captureAuthSnapshot(active.launched.context, { log });
5572
+ const meta = await saveAuthSnapshot(active.projectDirectory, snapshot, {
5573
+ indexedDb,
5574
+ capturedHeadless: active.headless,
5575
+ log
5576
+ });
5577
+ return reply.send(meta);
5578
+ } finally {
5579
+ authSessions.delete(projectId);
5580
+ await active.launched.close().catch(() => void 0);
5581
+ await active.release().catch(() => void 0);
5582
+ }
5583
+ });
5584
+ app.get("/api/workspace/projects/:projectId/auth-session/status", async (request) => {
5585
+ const { projectId } = request.params;
5586
+ const projectDirectory2 = await projectPath(root, projectId);
5587
+ const meta = await readAuthMeta(projectDirectory2);
5588
+ const lock = await currentAuthLock(projectDirectory2);
5589
+ return {
5590
+ ...meta,
5591
+ // Kept so existing callers keep working; it describes the directory only
5592
+ // and never means the login still works.
5593
+ profile: await browserProfileStatus(root, projectId),
5594
+ lockedBy: lock?.holder,
5595
+ executionHeadless: config.headless,
5596
+ // A snapshot taken in a different browser mode can be rejected by an app
5597
+ // that binds a session to the browser it was issued to.
5598
+ browserModeMismatch: meta.capturedHeadless !== void 0 && meta.capturedHeadless !== config.headless
5599
+ };
5600
+ });
5601
+ app.post("/api/workspace/projects/:projectId/auth-session/verify", async (request, reply) => {
5602
+ const { projectId } = request.params;
5603
+ const body = request.body ?? {};
5604
+ if (!body.url)
5605
+ return reply.status(400).send({ error: { code: "invalid-url", message: "A protected URL is required." } });
5606
+ const check = checkTargetUrl(body.url, config.urlPolicy);
5607
+ if (!check.ok)
5608
+ return reply.status(400).send({ error: { code: check.code, message: check.message } });
5609
+ const projectDirectory2 = await projectPath(root, projectId);
5610
+ const snapshot = await loadAuthSnapshot(projectDirectory2);
5611
+ if (!snapshot)
5612
+ return reply.status(409).send({
5613
+ error: { code: "no-auth-snapshot", message: "Record a login before verifying it." }
5614
+ });
5615
+ const log = (message) => request.log.info(message);
5616
+ let release;
5617
+ try {
5618
+ release = await acquireAuthLock(projectDirectory2, "scout", { log });
5619
+ } catch (error) {
5620
+ if (error instanceof AuthProfileBusyError)
5621
+ return reply.status(409).send({ error: { code: error.code, message: error.message } });
5622
+ throw error;
5623
+ }
5624
+ await updateAuthMeta(projectDirectory2, { status: "verifying" });
5625
+ const launched = await launchBrowser({ storageState: snapshot.storageState, headless: config.headless });
5626
+ try {
5627
+ await restoreSessionStorage(launched.context, snapshot.sessionStorage);
5628
+ log("[Auth] Restoring authenticated state");
5629
+ const page = launched.context.pages()[0] ?? await launched.context.newPage();
5630
+ const result = await verifyAuthState(page, check.url.toString(), { log });
5631
+ const meta = await updateAuthMeta(projectDirectory2, {
5632
+ status: result.ok ? "ready" : "expired",
5633
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
5634
+ verifiedPath: new URL(check.url.toString()).pathname,
5635
+ detail: result.detail
5636
+ });
5637
+ if (result.ok)
5638
+ log("[Auth] READY");
5639
+ return reply.send(meta);
5640
+ } finally {
5641
+ await launched.close().catch(() => void 0);
5642
+ await release().catch(() => void 0);
5643
+ }
5058
5644
  });
5059
- app.get("/api/workspace/projects/:projectId/auth-session/status", async (request) => browserProfileStatus(root, request.params.projectId));
5060
5645
  app.delete("/api/workspace/projects/:projectId/auth-session", async (request, reply) => {
5061
- await clearBrowserProfile(root, request.params.projectId);
5646
+ const { projectId } = request.params;
5647
+ await clearBrowserProfile(root, projectId);
5648
+ await clearAuthSnapshot(await projectPath(root, projectId));
5062
5649
  return reply.send({ cleared: true });
5063
5650
  });
5064
5651
  app.get("/api/workspace/projects/:projectId/screenshots", async (request) => readScreenshots(root, request.params.projectId));
@@ -5106,6 +5693,9 @@ function registerWorkspaceRoutes(app, root) {
5106
5693
  });
5107
5694
  }
5108
5695
 
5696
+ // ../server/dist/routes/recorder.js
5697
+ import { dirname as dirname9 } from "node:path";
5698
+
5109
5699
  // ../server/dist/recorderSessions.js
5110
5700
  function idleRecorderState(projectId) {
5111
5701
  return { projectId, status: "idle", startUrl: "", startedAt: "", steps: [] };
@@ -5288,7 +5878,14 @@ function safeDisplayUrl(value) {
5288
5878
 
5289
5879
  // ../server/dist/routes/recorder.js
5290
5880
  function registerRecorderRoutes(app, workspaceRoot, options = {}) {
5291
- const launch = options.launch ?? (async (projectId) => launchBrowser({ userDataDir: await browserProfileDirectory(workspaceRoot, projectId), headless: true }));
5881
+ const launch = options.launch ?? (async (projectId) => {
5882
+ const profile = await browserProfileDirectory(workspaceRoot, projectId);
5883
+ const snapshot = await loadAuthSnapshot(dirname9(profile)).catch(() => void 0);
5884
+ const launched = await launchBrowser(snapshot ? { storageState: snapshot.storageState, headless: config.headless } : { userDataDir: profile, headless: config.headless });
5885
+ if (snapshot)
5886
+ await restoreSessionStorage(launched.context, snapshot.sessionStorage).catch(() => void 0);
5887
+ return launched;
5888
+ });
5292
5889
  const sessions = new RecorderSessions(launch);
5293
5890
  app.post("/api/recorder/:projectId/start", async (request, reply) => {
5294
5891
  const { projectId } = request.params;
@@ -5519,11 +6116,11 @@ async function openInBrowser(url) {
5519
6116
  }
5520
6117
 
5521
6118
  // src/version.ts
5522
- var VERSION = true ? "0.4.2" : "0.0.0-dev";
6119
+ var VERSION = true ? "0.4.5" : "0.0.0-dev";
5523
6120
 
5524
6121
  // src/commands/serve.ts
5525
6122
  var DEFAULT_PORT = 4321;
5526
- var WEB_DIR = join4(dirname4(fileURLToPath(import.meta.url)), "web");
6123
+ var WEB_DIR = join6(dirname10(fileURLToPath(import.meta.url)), "web");
5527
6124
  async function runServe(options) {
5528
6125
  const workspaceRoot = resolveWorkspaceRoot(options.workspace);
5529
6126
  await ensureWorkspace(workspaceRoot);