lazyscout 0.4.4 → 0.4.6

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
@@ -1056,6 +1056,17 @@ async function launchBrowser(options = {}) {
1056
1056
  const failures = [];
1057
1057
  for (const candidate of CANDIDATES) {
1058
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
+ }
1059
1070
  if (options.userDataDir) {
1060
1071
  const context2 = await chromium.launchPersistentContext(options.userDataDir, {
1061
1072
  headless: options.headless ?? true,
@@ -1078,6 +1089,32 @@ async function launchBrowser(options = {}) {
1078
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');
1079
1090
  }
1080
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
+
1081
1118
  // ../../packages/explorer/dist/scopedExplorer.js
1082
1119
  var DEFAULT_LIMITS = {
1083
1120
  maxPages: 20,
@@ -1709,7 +1746,14 @@ async function exploreWithScope(startUrl, explorationConfig = {}, exploreOptions
1709
1746
  return { candidates: [] };
1710
1747
  }
1711
1748
  }
1712
- 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
+ }
1713
1757
  const { context, label: browserLabel } = launched;
1714
1758
  let targetStartUrl = entryUrl;
1715
1759
  if (config2.startPath) {
@@ -3935,18 +3979,24 @@ Saved CSV: ${csvPath}`);
3935
3979
  }
3936
3980
 
3937
3981
  // src/commands/serve.ts
3938
- import { dirname as dirname4, join as join4 } from "node:path";
3982
+ import { dirname as dirname10, join as join6 } from "node:path";
3939
3983
  import { fileURLToPath } from "node:url";
3940
3984
 
3941
3985
  // ../server/dist/app.js
3942
3986
  import Fastify from "fastify";
3943
3987
  import fastifyStatic from "@fastify/static";
3944
3988
 
3989
+ // ../server/dist/routes/analyze.js
3990
+ import { dirname as dirname4 } from "node:path";
3991
+
3945
3992
  // ../server/dist/config.js
3993
+ var headedBrowser = /^(1|true|yes)$/i.test(process.env.LAZYSCOUT_HEADED ?? "");
3946
3994
  var config = {
3947
3995
  host: process.env.HOST ?? "127.0.0.1",
3948
3996
  port: Number(process.env.PORT ?? 4e3),
3949
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,
3950
4000
  limits: {
3951
4001
  maxPages: 20,
3952
4002
  maxDepth: 3
@@ -3958,6 +4008,223 @@ function clamp(value, min, max, fallback) {
3958
4008
  return Math.min(Math.max(Math.trunc(value), min), max);
3959
4009
  }
3960
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
+
3961
4228
  // ../server/dist/toApiError.js
3962
4229
  function toApiError(error) {
3963
4230
  if (error instanceof ExplorerError) {
@@ -3989,25 +4256,25 @@ function toApiError(error) {
3989
4256
  import { execFile } from "node:child_process";
3990
4257
  import { randomUUID } from "node:crypto";
3991
4258
  import { homedir, platform } from "node:os";
3992
- import { basename, dirname, extname, isAbsolute, join, relative, resolve as resolve2 } from "node:path";
3993
- 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";
3994
4261
  import { promisify } from "node:util";
3995
4262
  var execFileAsync = promisify(execFile);
3996
4263
  var PROJECT_ID = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
3997
4264
  var FILE_NAME = /^[^\\/:*?"<>|]{1,160}$/;
3998
4265
  var mutationQueues = /* @__PURE__ */ new Map();
3999
4266
  function defaultWorkspaceRoot() {
4000
- return join(homedir(), "LazyScout");
4267
+ return join3(homedir(), "LazyScout");
4001
4268
  }
4002
4269
  function resolveWorkspaceRoot(value) {
4003
4270
  return resolve2(value?.trim() || process.env.LAZYSCOUT_WORKSPACE || defaultWorkspaceRoot());
4004
4271
  }
4005
4272
  async function ensureWorkspace(root) {
4006
4273
  await Promise.all([
4007
- mkdir(join(root, "projects"), { recursive: true }),
4008
- mkdir(join(root, "backups"), { recursive: true })
4274
+ mkdir3(join3(root, "projects"), { recursive: true }),
4275
+ mkdir3(join3(root, "backups"), { recursive: true })
4009
4276
  ]);
4010
- const settingsPath = join(root, "settings.json");
4277
+ const settingsPath = join3(root, "settings.json");
4011
4278
  try {
4012
4279
  await stat(settingsPath);
4013
4280
  } catch {
@@ -4016,7 +4283,7 @@ async function ensureWorkspace(root) {
4016
4283
  }
4017
4284
  async function listProjects(root) {
4018
4285
  await ensureWorkspace(root);
4019
- const entries = await readdir(join(root, "projects"), { withFileTypes: true });
4286
+ const entries = await readdir(join3(root, "projects"), { withFileTypes: true });
4020
4287
  const projects = await Promise.all(entries.filter((entry) => entry.isDirectory() && PROJECT_ID.test(entry.name)).map((entry) => readProject(root, entry.name)));
4021
4288
  return projects.filter((project) => Boolean(project)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
4022
4289
  }
@@ -4027,10 +4294,10 @@ async function saveProject(root, project) {
4027
4294
  const { testCases, ...result } = normalized;
4028
4295
  const testData = normalized.testData;
4029
4296
  await Promise.all([
4030
- writeJson(join(directory, "project.json"), { ...project, result }),
4031
- writeJson(join(directory, "test-cases.json"), testCases),
4032
- writeFileAtomic(join(directory, "test-cases.csv"), exportTestCasesToCsv(testCases, testData)),
4033
- 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))
4034
4301
  ]);
4035
4302
  });
4036
4303
  }
@@ -4044,16 +4311,16 @@ async function deleteProject(root, projectId) {
4044
4311
  }
4045
4312
  await ensureWorkspace(root);
4046
4313
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
4047
- await rename(source, join(root, "backups", `${projectId}-${timestamp}`));
4314
+ await rename(source, join3(root, "backups", `${projectId}-${timestamp}`));
4048
4315
  });
4049
4316
  }
4050
4317
  async function readScreenshots(root, projectId) {
4051
4318
  const directory = await ensureProject(root, projectId);
4052
- return readJson(join(directory, "screenshots", "index.json"), []);
4319
+ return readJson2(join3(directory, "screenshots", "index.json"), []);
4053
4320
  }
4054
4321
  async function saveScreenshot(root, projectId, screenshot) {
4055
4322
  return enqueueMutation(`screenshots:${projectId}`, async () => {
4056
- const directory = join(await ensureProject(root, projectId), "screenshots");
4323
+ const directory = join3(await ensureProject(root, projectId), "screenshots");
4057
4324
  const match = screenshot.dataUrl.match(/^data:image\/(png|jpeg);base64,([a-zA-Z0-9+/=]+)$/);
4058
4325
  if (!match)
4059
4326
  throw new Error("Screenshot must be a PNG or JPEG data URL");
@@ -4063,44 +4330,44 @@ async function saveScreenshot(root, projectId, screenshot) {
4063
4330
  const extension = match[1] === "jpeg" ? ".jpg" : ".png";
4064
4331
  const requested = safeFileName(screenshot.name, `screenshot-${Date.now()}${extension}`);
4065
4332
  const name = extname(requested) ? `${basename(requested, extname(requested))}${extension}` : `${requested}${extension}`;
4066
- await writeFileAtomic(join(directory, name), image);
4333
+ await writeFileAtomic(join3(directory, name), image);
4067
4334
  const current = await readScreenshots(root, projectId);
4068
4335
  const stored = { ...screenshot, name, dataUrl: screenshotUrl(projectId, name) };
4069
4336
  const next = [stored, ...current.filter((item) => item.name !== name)].slice(0, 50);
4070
- await writeJson(join(directory, "index.json"), next);
4337
+ await writeJson(join3(directory, "index.json"), next);
4071
4338
  return stored;
4072
4339
  });
4073
4340
  }
4074
4341
  async function deleteScreenshot(root, projectId, name) {
4075
4342
  const safeName2 = assertFileName(name);
4076
- const directory = join(await ensureProject(root, projectId), "screenshots");
4077
- await rm(join(directory, safeName2), { force: true });
4343
+ const directory = join3(await ensureProject(root, projectId), "screenshots");
4344
+ await rm3(join3(directory, safeName2), { force: true });
4078
4345
  const current = await readScreenshots(root, projectId);
4079
- 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));
4080
4347
  }
4081
4348
  async function screenshotFile(root, projectId, name) {
4082
- return readFile(join(await ensureProject(root, projectId), "screenshots", assertFileName(name)));
4349
+ return readFile3(join3(await ensureProject(root, projectId), "screenshots", assertFileName(name)));
4083
4350
  }
4084
4351
  async function listBugReports(root, projectId) {
4085
- const directory = join(await ensureProject(root, projectId), "bugs");
4352
+ const directory = join3(await ensureProject(root, projectId), "bugs");
4086
4353
  const entries = await readdir(directory, { withFileTypes: true });
4087
- 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)));
4088
4355
  return reports.filter((report) => Boolean(report));
4089
4356
  }
4090
4357
  async function saveBugReport(root, projectId, report) {
4091
- const directory = join(await ensureProject(root, projectId), "bugs");
4092
- 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);
4093
4360
  }
4094
4361
  async function deleteBugReport(root, projectId, bugId) {
4095
- const directory = join(await ensureProject(root, projectId), "bugs");
4096
- 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 });
4097
4364
  }
4098
4365
  async function readAutomation(root, projectId) {
4099
- const directory = join(await ensureProject(root, projectId), "automation");
4100
- 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"), {});
4101
4368
  const entries = await Promise.all(Object.entries(index).map(async ([key, name]) => {
4102
4369
  try {
4103
- return [key, await readFile(join(directory, assertFileName(name)), "utf8")];
4370
+ return [key, await readFile3(join3(directory, assertFileName(name)), "utf8")];
4104
4371
  } catch {
4105
4372
  return void 0;
4106
4373
  }
@@ -4108,8 +4375,8 @@ async function readAutomation(root, projectId) {
4108
4375
  return Object.fromEntries(entries.filter((entry) => Boolean(entry)));
4109
4376
  }
4110
4377
  async function saveAutomation(root, projectId, overrides) {
4111
- const directory = join(await ensureProject(root, projectId), "automation");
4112
- 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"), {});
4113
4380
  const next = {};
4114
4381
  for (const [key, source] of Object.entries(overrides)) {
4115
4382
  if (typeof source !== "string" || source.length > 2e5)
@@ -4120,22 +4387,22 @@ async function saveAutomation(root, projectId, overrides) {
4120
4387
  const extension = framework === "playwright" ? ".spec.ts" : ".cy.ts";
4121
4388
  const name = `${framework}-${safeFileName(caseId, "test-case")}${extension}`;
4122
4389
  next[key] = name;
4123
- await writeFileAtomic(join(directory, name), source);
4390
+ await writeFileAtomic(join3(directory, name), source);
4124
4391
  }
4125
4392
  for (const name of Object.values(previous))
4126
4393
  if (!Object.values(next).includes(name))
4127
- await rm(join(directory, assertFileName(name)), { force: true });
4128
- await writeJson(join(directory, "index.json"), next);
4394
+ await rm3(join3(directory, assertFileName(name)), { force: true });
4395
+ await writeJson(join3(directory, "index.json"), next);
4129
4396
  }
4130
4397
  async function saveRunLog(root, projectId, testCaseId, status, logs) {
4131
- const directory = join(await ensureProject(root, projectId), "logs");
4398
+ const directory = join3(await ensureProject(root, projectId), "logs");
4132
4399
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
4133
4400
  const name = `${timestamp}-${safeFileName(testCaseId, "test-case")}.json`;
4134
- 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 });
4135
4402
  }
4136
4403
  async function readGuidedFlows(root, projectId) {
4137
4404
  const directory = await ensureProject(root, projectId);
4138
- return readJson(join(directory, "guided-flows.json"), []);
4405
+ return readJson2(join3(directory, "guided-flows.json"), []);
4139
4406
  }
4140
4407
  async function saveGuidedFlows(root, projectId, flows) {
4141
4408
  if (!Array.isArray(flows) || flows.length > 100)
@@ -4145,14 +4412,14 @@ async function saveGuidedFlows(root, projectId, flows) {
4145
4412
  throw new Error("Invalid Guided Flow");
4146
4413
  }
4147
4414
  const directory = await ensureProject(root, projectId);
4148
- await writeJson(join(directory, "guided-flows.json"), flows);
4415
+ await writeJson(join3(directory, "guided-flows.json"), flows);
4149
4416
  }
4150
4417
  async function saveReport(root, projectId, name, html) {
4151
4418
  if (typeof html !== "string" || html.length > 2e6)
4152
4419
  throw new Error("Report exceeds the 2 MB limit");
4153
- const directory = join(await ensureProject(root, projectId), "reports");
4420
+ const directory = join3(await ensureProject(root, projectId), "reports");
4154
4421
  const fileName = `${safeFileName(name, `quality-report-${Date.now()}.html`).replace(/\.[^.]+$/, "")}.html`;
4155
- await writeFileAtomic(join(directory, fileName), html);
4422
+ await writeFileAtomic(join3(directory, fileName), html);
4156
4423
  return fileName;
4157
4424
  }
4158
4425
  async function openWorkspace(root) {
@@ -4165,18 +4432,18 @@ async function openWorkspace(root) {
4165
4432
  await execFileAsync("xdg-open", [root]);
4166
4433
  }
4167
4434
  async function browserProfileDirectory(root, projectId) {
4168
- return join(await ensureProject(root, projectId), "browser-profile");
4435
+ return join3(await ensureProject(root, projectId), "browser-profile");
4169
4436
  }
4170
4437
  async function browserProfileStatus(root, projectId) {
4171
- const directory = join(projectDirectory(root, projectId), "browser-profile");
4438
+ const directory = join3(projectDirectory(root, projectId), "browser-profile");
4172
4439
  try {
4173
4440
  const entries = await readdir(directory);
4174
4441
  const candidates = [
4175
4442
  directory,
4176
- join(directory, "Local State"),
4177
- join(directory, "Default"),
4178
- join(directory, "Default", "Cookies"),
4179
- 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")
4180
4447
  ];
4181
4448
  const modifiedTimes = await Promise.all(candidates.map(async (candidate) => {
4182
4449
  try {
@@ -4196,16 +4463,16 @@ async function browserProfileStatus(root, projectId) {
4196
4463
  }
4197
4464
  }
4198
4465
  async function clearBrowserProfile(root, projectId) {
4199
- const directory = join(projectDirectory(root, projectId), "browser-profile");
4200
- await rm(directory, { recursive: true, force: true });
4466
+ const directory = join3(projectDirectory(root, projectId), "browser-profile");
4467
+ await rm3(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 150 });
4201
4468
  }
4202
4469
  async function readProject(root, projectId) {
4203
4470
  try {
4204
4471
  const directory = projectDirectory(root, projectId);
4205
- const project = await readJson(join(directory, "project.json"), void 0);
4472
+ const project = await readJson2(join3(directory, "project.json"), void 0);
4206
4473
  if (!project)
4207
4474
  return void 0;
4208
- const testCases = await readJson(join(directory, "test-cases.json"), []);
4475
+ const testCases = await readJson2(join3(directory, "test-cases.json"), []);
4209
4476
  return { ...project, result: normalizeResult({ ...project.result, testCases }) };
4210
4477
  } catch {
4211
4478
  return void 0;
@@ -4214,13 +4481,13 @@ async function readProject(root, projectId) {
4214
4481
  async function ensureProject(root, projectId) {
4215
4482
  await ensureWorkspace(root);
4216
4483
  const directory = projectDirectory(root, projectId);
4217
- 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 })));
4218
4485
  return directory;
4219
4486
  }
4220
4487
  function projectDirectory(root, projectId) {
4221
4488
  if (!PROJECT_ID.test(projectId))
4222
4489
  throw new Error("Invalid project ID");
4223
- return containedPath(join(root, "projects"), projectId);
4490
+ return containedPath(join3(root, "projects"), projectId);
4224
4491
  }
4225
4492
  function containedPath(root, value) {
4226
4493
  const target = resolve2(root, value);
@@ -4241,9 +4508,9 @@ function safeFileName(value, fallback) {
4241
4508
  function screenshotUrl(projectId, name) {
4242
4509
  return `/api/workspace/projects/${encodeURIComponent(projectId)}/screenshots/${encodeURIComponent(name)}`;
4243
4510
  }
4244
- async function readJson(path, fallback) {
4511
+ async function readJson2(path, fallback) {
4245
4512
  try {
4246
- return JSON.parse(await readFile(path, "utf8"));
4513
+ return JSON.parse(await readFile3(path, "utf8"));
4247
4514
  } catch {
4248
4515
  return fallback;
4249
4516
  }
@@ -4253,10 +4520,10 @@ async function writeJson(path, value) {
4253
4520
  `);
4254
4521
  }
4255
4522
  async function writeFileAtomic(path, value) {
4256
- await mkdir(dirname(path), { recursive: true });
4523
+ await mkdir3(dirname3(path), { recursive: true });
4257
4524
  const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
4258
- await writeFile2(temporary, value);
4259
- await rm(path, { force: true });
4525
+ await writeFile4(temporary, value);
4526
+ await rm3(path, { force: true });
4260
4527
  await rename(temporary, path);
4261
4528
  }
4262
4529
  function testDataCsv(rows) {
@@ -4325,6 +4592,20 @@ function registerAnalyzeRoute(app, workspaceRoot) {
4325
4592
  return reply.status(400).send({ error: { code: check.code, message: check.message } });
4326
4593
  }
4327
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
+ }
4328
4609
  try {
4329
4610
  const abortController = new AbortController();
4330
4611
  let completed = false;
@@ -4350,7 +4631,8 @@ function registerAnalyzeRoute(app, workspaceRoot) {
4350
4631
  waitAfterNavigationMs: clamp(body.waitAfterNavigationMs, 0, 5e3, 750),
4351
4632
  blockedKeywords: normalizeBlockedKeywords(body.blockedKeywords),
4352
4633
  signal: abortController.signal,
4353
- ...browserProfileDir ? { browserProfileDir } : {}
4634
+ headless: config.headless,
4635
+ ...authRestore ? { authRestore: { storageState: authRestore.storageState, sessionStorage: authRestore.sessionStorage } } : browserProfileDir ? { browserProfileDir } : {}
4354
4636
  });
4355
4637
  if (result.pages.length === 0) {
4356
4638
  const firstIssue = result.issues[0];
@@ -4438,6 +4720,8 @@ function registerAnalyzeRoute(app, workspaceRoot) {
4438
4720
  request.log.error({ message: redactSensitiveText(error instanceof Error ? error.message : String(error)) }, "analyze failed");
4439
4721
  const { status, body: errorBody } = toApiError(error);
4440
4722
  return reply.status(status).send(errorBody);
4723
+ } finally {
4724
+ await releaseAuthLock?.().catch(() => void 0);
4441
4725
  }
4442
4726
  });
4443
4727
  }
@@ -4532,33 +4816,38 @@ function registerExportCsvRoute(app) {
4532
4816
  });
4533
4817
  }
4534
4818
 
4819
+ // ../server/dist/routes/automationRun.js
4820
+ import { dirname as dirname6 } from "node:path";
4821
+
4535
4822
  // ../server/dist/routes/playwrightCliRunner.js
4536
4823
  import { createRequire } from "node:module";
4537
4824
  import { spawn } from "node:child_process";
4538
- import { mkdtemp, readdir as readdir2, readFile as readFile2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
4539
- 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";
4540
4827
  var require2 = createRequire(import.meta.url);
4541
4828
  var CLI_ENTRY = require2.resolve("@playwright/test/cli");
4542
4829
  var MAX_SCREENSHOTS = 10;
4543
4830
  async function runPlaywrightCli(input) {
4544
4831
  const started = Date.now();
4545
- const runDirectory = await mkdtemp(join2(dirname2(CLI_ENTRY), ".lazyscout-run-"));
4546
- 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);
4547
4835
  validateLiteralNavigationUrls(source);
4548
- const specPath = join2(runDirectory, `${safeName(input.testCaseId)}.spec.ts`);
4549
- const configPath = join2(runDirectory, "playwright.config.mjs");
4550
- await writeFile3(specPath, source, "utf8");
4551
- if (input.profileDirectory) {
4552
- const fixture = createProfileFixture();
4553
- await writeFile3(join2(runDirectory, "lazyscout-fixture.mjs"), fixture, "utf8");
4554
- }
4555
- 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");
4556
4844
  const child = spawn(process.execPath, [CLI_ENTRY, "test", "--config", configPath], {
4557
4845
  cwd: runDirectory,
4558
4846
  env: {
4559
4847
  ...process.env,
4560
4848
  FORCE_COLOR: "0",
4561
- ...input.profileDirectory ? { LAZYSCOUT_PROFILE_DIR: input.profileDirectory } : {}
4849
+ ...input.profileDirectory ? { LAZYSCOUT_PROFILE_DIR: input.profileDirectory } : {},
4850
+ ...input.authStatePath ? { LAZYSCOUT_AUTH_STATE: input.authStatePath } : {}
4562
4851
  },
4563
4852
  windowsHide: true,
4564
4853
  stdio: ["ignore", "pipe", "pipe"]
@@ -4604,11 +4893,11 @@ async function runPlaywrightCli(input) {
4604
4893
  input.addLog("fail", `Playwright Test failed (exit code ${exit.code ?? "unknown"})`, Date.now() - started);
4605
4894
  let error;
4606
4895
  if (status === "failed") {
4607
- const result = await readFile2(join2(runDirectory, "results.json"), "utf8").catch(() => "");
4896
+ const result = await readFile4(join4(runDirectory, "results.json"), "utf8").catch(() => "");
4608
4897
  error = summarizeFailure(result) ?? "Playwright Test failed. See the CLI output for details.";
4609
4898
  input.addLog("fail", error);
4610
4899
  }
4611
- await rm2(runDirectory, { recursive: true, force: true }).catch(() => void 0);
4900
+ await rm4(runDirectory, { recursive: true, force: true }).catch(() => void 0);
4612
4901
  return {
4613
4902
  status,
4614
4903
  error,
@@ -4629,13 +4918,37 @@ function resolveSource(source, testCase, secrets, useProfile = false) {
4629
4918
  ].join("\n");
4630
4919
  return useProfile ? fullSource.replace(/from\s+(['"])@playwright\/test\1/g, "from './lazyscout-fixture.mjs'") : fullSource;
4631
4920
  }
4632
- function createProfileFixture() {
4921
+ function createProfileFixture(headless) {
4633
4922
  return `import { test as base, expect } from '@playwright/test'
4634
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
4635
4929
 
4636
4930
  export const test = base.extend({
4637
4931
  context: async ({}, use) => {
4638
- 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 })
4639
4952
  await use(context)
4640
4953
  await context.close()
4641
4954
  }
@@ -4670,7 +4983,7 @@ function validateLiteralNavigationUrls(source) {
4670
4983
  throw new Error(checked.message);
4671
4984
  }
4672
4985
  }
4673
- function createConfig() {
4986
+ function createConfig(headless) {
4674
4987
  return `import { defineConfig } from '@playwright/test'
4675
4988
  export default defineConfig({
4676
4989
  testDir: '.',
@@ -4679,7 +4992,7 @@ export default defineConfig({
4679
4992
  workers: 1,
4680
4993
  fullyParallel: false,
4681
4994
  reporter: [['line'], ['json', { outputFile: 'results.json' }]],
4682
- use: { headless: true, actionTimeout: 20000, navigationTimeout: 20000, screenshot: 'off' }
4995
+ use: { headless: ${headless ? "true" : "false"}, actionTimeout: 20000, navigationTimeout: 20000, screenshot: 'off' }
4683
4996
  })
4684
4997
  `;
4685
4998
  }
@@ -4688,7 +5001,7 @@ async function readScreenshots2(directory, testCaseId) {
4688
5001
  const screenshots = [];
4689
5002
  for (const file of files.slice(0, MAX_SCREENSHOTS)) {
4690
5003
  const extension = file.toLowerCase().endsWith(".jpg") || file.toLowerCase().endsWith(".jpeg") ? "jpeg" : "png";
4691
- const data = await readFile2(file);
5004
+ const data = await readFile4(file);
4692
5005
  screenshots.push({
4693
5006
  name: file.slice(directory.length + 1).replaceAll("\\", "/"),
4694
5007
  dataUrl: `data:image/${extension};base64,${data.toString("base64")}`,
@@ -4703,7 +5016,7 @@ async function collectImages(directory) {
4703
5016
  const entries = await readdir2(directory, { withFileTypes: true });
4704
5017
  const files = [];
4705
5018
  for (const entry of entries) {
4706
- const path = join2(directory, entry.name);
5019
+ const path = join4(directory, entry.name);
4707
5020
  if (entry.isDirectory())
4708
5021
  files.push(...await collectImages(path));
4709
5022
  else if (/\.(png|jpe?g)$/i.test(entry.name))
@@ -4814,14 +5127,37 @@ function registerAutomationRunRoute(app, workspaceRoot) {
4814
5127
  }
4815
5128
  const active = { stopped: false };
4816
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
+ }
4817
5149
  try {
5150
+ if (snapshot)
5151
+ addLog("info", "[Auth] Restoring authenticated state");
4818
5152
  const result = await runPlaywrightCli({
4819
5153
  source: body.code,
4820
5154
  testCase,
4821
5155
  testCaseId: testCase.id,
4822
5156
  secrets: body.secrets,
4823
5157
  secretValues,
4824
- profileDirectory: body.projectId ? await browserProfileDirectory(workspaceRoot, body.projectId) : void 0,
5158
+ headless: config.headless,
5159
+ ...snapshot && projectDirectory2 ? { authStatePath: authStatePath(projectDirectory2) } : {},
5160
+ profileDirectory,
4825
5161
  addLog,
4826
5162
  onProcess: (child) => {
4827
5163
  active.close = async () => {
@@ -4857,6 +5193,7 @@ function registerAutomationRunRoute(app, workspaceRoot) {
4857
5193
  return reply.send({ status: "failed", framework, logs, error: message });
4858
5194
  } finally {
4859
5195
  activeRuns.delete(runId);
5196
+ await releaseAuthLock?.().catch(() => void 0);
4860
5197
  }
4861
5198
  });
4862
5199
  }
@@ -5002,7 +5339,7 @@ function registerLoadTestRoute(app) {
5002
5339
  // ../server/dist/routes/versions.js
5003
5340
  import { spawn as spawn2 } from "node:child_process";
5004
5341
  import { access } from "node:fs/promises";
5005
- import { dirname as dirname3, join as join3 } from "node:path";
5342
+ import { dirname as dirname7, join as join5 } from "node:path";
5006
5343
  var PACKAGE_NAME = "lazyscout";
5007
5344
  var REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}`;
5008
5345
  var VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
@@ -5048,8 +5385,8 @@ async function fetchPublishedVersions(force = false) {
5048
5385
  async function findNpmCli() {
5049
5386
  const candidates = [
5050
5387
  process.env.npm_execpath,
5051
- join3(dirname3(process.execPath), "node_modules", "npm", "bin", "npm-cli.js"),
5052
- 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,
5053
5390
  "/usr/lib/node_modules/npm/bin/npm-cli.js",
5054
5391
  "/usr/local/lib/node_modules/npm/bin/npm-cli.js"
5055
5392
  ].filter((value) => Boolean(value?.endsWith(".js")));
@@ -5168,6 +5505,21 @@ function registerVersionRoutes(app, currentVersion) {
5168
5505
  }
5169
5506
 
5170
5507
  // ../server/dist/routes/workspace.js
5508
+ import { dirname as dirname8 } from "node:path";
5509
+ var authSessions = /* @__PURE__ */ new Map();
5510
+ async function abandonLoginSession(projectId, log) {
5511
+ const active = authSessions.get(projectId);
5512
+ if (!active)
5513
+ return false;
5514
+ authSessions.delete(projectId);
5515
+ await active.launched.close().catch(() => void 0);
5516
+ await active.release().catch(() => void 0);
5517
+ log?.("[Auth] Sign-in window abandoned, profile released");
5518
+ return true;
5519
+ }
5520
+ async function projectPath(root, projectId) {
5521
+ return dirname8(await browserProfileDirectory(root, projectId));
5522
+ }
5171
5523
  function registerWorkspaceRoutes(app, root) {
5172
5524
  app.get("/api/workspace", async () => ({ root, projects: await listProjects(root) }));
5173
5525
  app.post("/api/workspace/open", async (_request, reply) => {
@@ -5189,16 +5541,151 @@ function registerWorkspaceRoutes(app, root) {
5189
5541
  const body = request.body;
5190
5542
  if (!body?.url)
5191
5543
  return reply.status(400).send({ error: { code: "invalid-url", message: "A login URL is required." } });
5192
- const profile = await browserProfileDirectory(root, request.params.projectId);
5193
- const launched = await launchBrowser({ userDataDir: profile, headless: false });
5544
+ const check = checkTargetUrl(body.url, config.urlPolicy);
5545
+ if (!check.ok)
5546
+ return reply.status(400).send({ error: { code: check.code, message: check.message } });
5547
+ const { projectId } = request.params;
5548
+ const projectDirectory2 = await projectPath(root, projectId);
5549
+ const log = (message) => request.log.info(message);
5550
+ await abandonLoginSession(projectId, log);
5551
+ let release;
5552
+ try {
5553
+ release = await acquireAuthLock(projectDirectory2, "login-browser", { log });
5554
+ } catch (error) {
5555
+ if (error instanceof AuthProfileBusyError)
5556
+ return reply.status(409).send({
5557
+ error: {
5558
+ code: error.code,
5559
+ message: error.message,
5560
+ hint: "Wait for it to finish, or press Cancel sign-in to release it."
5561
+ }
5562
+ });
5563
+ throw error;
5564
+ }
5565
+ const headless = false;
5566
+ const launched = await launchBrowser({ userDataDir: await browserProfileDirectory(root, projectId), headless });
5194
5567
  const page = launched.context.pages()[0] ?? await launched.context.newPage();
5195
- await page.goto(body.url, { waitUntil: "domcontentloaded" });
5196
- return reply.send({ opened: true });
5568
+ await page.goto(check.url.toString(), { waitUntil: "domcontentloaded" });
5569
+ await updateAuthMeta(projectDirectory2, { status: "verifying", detail: "Waiting for the sign-in window to close" });
5570
+ authSessions.set(projectId, { launched, release, headless, projectDirectory: projectDirectory2 });
5571
+ launched.context.once("close", () => {
5572
+ void abandonLoginSession(projectId, log);
5573
+ });
5574
+ log("[Auth] Login browser opened");
5575
+ return reply.send({ opened: true, headless });
5576
+ });
5577
+ app.delete("/api/workspace/projects/:projectId/auth-session/login-browser", async (request, reply) => {
5578
+ const released = await abandonLoginSession(request.params.projectId, (message) => request.log.info(message));
5579
+ return reply.send({ released });
5580
+ });
5581
+ app.post("/api/workspace/projects/:projectId/auth-session/capture", async (request, reply) => {
5582
+ const { projectId } = request.params;
5583
+ const active = authSessions.get(projectId);
5584
+ if (!active)
5585
+ return reply.status(409).send({
5586
+ error: { code: "no-login-browser", message: "Open the login browser before capturing a session." }
5587
+ });
5588
+ const log = (message) => request.log.info(message);
5589
+ let meta;
5590
+ let failure;
5591
+ try {
5592
+ log("[Auth] Recorded login completed");
5593
+ const page = active.launched.context.pages().find((candidate) => !candidate.isClosed());
5594
+ await waitForAuthSettle(active.launched.context, page, { log });
5595
+ const { snapshot, indexedDb } = await captureAuthSnapshot(active.launched.context, { log });
5596
+ meta = await saveAuthSnapshot(active.projectDirectory, snapshot, {
5597
+ indexedDb,
5598
+ capturedHeadless: active.headless,
5599
+ log
5600
+ });
5601
+ } catch (error) {
5602
+ failure = error;
5603
+ }
5604
+ authSessions.delete(projectId);
5605
+ await active.launched.close().catch(() => void 0);
5606
+ await active.release().catch(() => void 0);
5607
+ if (failure)
5608
+ throw failure;
5609
+ return reply.send(meta);
5610
+ });
5611
+ app.get("/api/workspace/projects/:projectId/auth-session/status", async (request) => {
5612
+ const { projectId } = request.params;
5613
+ const projectDirectory2 = await projectPath(root, projectId);
5614
+ const meta = await readAuthMeta(projectDirectory2);
5615
+ const lock = await currentAuthLock(projectDirectory2);
5616
+ return {
5617
+ ...meta,
5618
+ // Kept so existing callers keep working; it describes the directory only
5619
+ // and never means the login still works.
5620
+ profile: await browserProfileStatus(root, projectId),
5621
+ lockedBy: lock?.holder,
5622
+ // Whether a sign-in window is still open and waiting to be captured.
5623
+ // Held on the server so closing and reopening the dialog does not lose it.
5624
+ loginBrowserOpen: authSessions.has(projectId),
5625
+ executionHeadless: config.headless,
5626
+ // A snapshot taken in a different browser mode can be rejected by an app
5627
+ // that binds a session to the browser it was issued to.
5628
+ browserModeMismatch: meta.capturedHeadless !== void 0 && meta.capturedHeadless !== config.headless
5629
+ };
5630
+ });
5631
+ app.post("/api/workspace/projects/:projectId/auth-session/verify", async (request, reply) => {
5632
+ const { projectId } = request.params;
5633
+ const body = request.body ?? {};
5634
+ if (!body.url)
5635
+ return reply.status(400).send({ error: { code: "invalid-url", message: "A protected URL is required." } });
5636
+ const check = checkTargetUrl(body.url, config.urlPolicy);
5637
+ if (!check.ok)
5638
+ return reply.status(400).send({ error: { code: check.code, message: check.message } });
5639
+ const projectDirectory2 = await projectPath(root, projectId);
5640
+ const snapshot = await loadAuthSnapshot(projectDirectory2);
5641
+ if (!snapshot)
5642
+ return reply.status(409).send({
5643
+ error: { code: "no-auth-snapshot", message: "Record a login before verifying it." }
5644
+ });
5645
+ const log = (message) => request.log.info(message);
5646
+ let release;
5647
+ try {
5648
+ release = await acquireAuthLock(projectDirectory2, "scout", { log });
5649
+ } catch (error) {
5650
+ if (error instanceof AuthProfileBusyError)
5651
+ return reply.status(409).send({ error: { code: error.code, message: error.message } });
5652
+ throw error;
5653
+ }
5654
+ await updateAuthMeta(projectDirectory2, { status: "verifying" });
5655
+ const launched = await launchBrowser({ storageState: snapshot.storageState, headless: config.headless });
5656
+ try {
5657
+ await restoreSessionStorage(launched.context, snapshot.sessionStorage);
5658
+ log("[Auth] Restoring authenticated state");
5659
+ const page = launched.context.pages()[0] ?? await launched.context.newPage();
5660
+ const result = await verifyAuthState(page, check.url.toString(), { log });
5661
+ const meta = await updateAuthMeta(projectDirectory2, {
5662
+ status: result.ok ? "ready" : "expired",
5663
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
5664
+ verifiedPath: new URL(check.url.toString()).pathname,
5665
+ detail: result.detail
5666
+ });
5667
+ if (result.ok)
5668
+ log("[Auth] READY");
5669
+ return reply.send(meta);
5670
+ } finally {
5671
+ await launched.close().catch(() => void 0);
5672
+ await release().catch(() => void 0);
5673
+ }
5197
5674
  });
5198
- app.get("/api/workspace/projects/:projectId/auth-session/status", async (request) => browserProfileStatus(root, request.params.projectId));
5199
5675
  app.delete("/api/workspace/projects/:projectId/auth-session", async (request, reply) => {
5200
- await clearBrowserProfile(root, request.params.projectId);
5201
- return reply.send({ cleared: true });
5676
+ const { projectId } = request.params;
5677
+ const log = (message) => request.log.info(message);
5678
+ await abandonLoginSession(projectId, log);
5679
+ await clearAuthSnapshot(await projectPath(root, projectId));
5680
+ const profileRemoved = await clearBrowserProfile(root, projectId).then(() => true).catch(() => false);
5681
+ log("[Auth] Session cleared");
5682
+ return reply.send({
5683
+ cleared: true,
5684
+ profileRemoved,
5685
+ ...profileRemoved ? {} : {
5686
+ detail: "The saved session was removed. Some browser profile files were still in use and were left behind; they are replaced on the next sign-in."
5687
+ }
5688
+ });
5202
5689
  });
5203
5690
  app.get("/api/workspace/projects/:projectId/screenshots", async (request) => readScreenshots(root, request.params.projectId));
5204
5691
  app.post("/api/workspace/projects/:projectId/screenshots", async (request) => saveScreenshot(root, request.params.projectId, request.body));
@@ -5245,6 +5732,9 @@ function registerWorkspaceRoutes(app, root) {
5245
5732
  });
5246
5733
  }
5247
5734
 
5735
+ // ../server/dist/routes/recorder.js
5736
+ import { dirname as dirname9 } from "node:path";
5737
+
5248
5738
  // ../server/dist/recorderSessions.js
5249
5739
  function idleRecorderState(projectId) {
5250
5740
  return { projectId, status: "idle", startUrl: "", startedAt: "", steps: [] };
@@ -5427,7 +5917,14 @@ function safeDisplayUrl(value) {
5427
5917
 
5428
5918
  // ../server/dist/routes/recorder.js
5429
5919
  function registerRecorderRoutes(app, workspaceRoot, options = {}) {
5430
- const launch = options.launch ?? (async (projectId) => launchBrowser({ userDataDir: await browserProfileDirectory(workspaceRoot, projectId), headless: true }));
5920
+ const launch = options.launch ?? (async (projectId) => {
5921
+ const profile = await browserProfileDirectory(workspaceRoot, projectId);
5922
+ const snapshot = await loadAuthSnapshot(dirname9(profile)).catch(() => void 0);
5923
+ const launched = await launchBrowser(snapshot ? { storageState: snapshot.storageState, headless: config.headless } : { userDataDir: profile, headless: config.headless });
5924
+ if (snapshot)
5925
+ await restoreSessionStorage(launched.context, snapshot.sessionStorage).catch(() => void 0);
5926
+ return launched;
5927
+ });
5431
5928
  const sessions = new RecorderSessions(launch);
5432
5929
  app.post("/api/recorder/:projectId/start", async (request, reply) => {
5433
5930
  const { projectId } = request.params;
@@ -5658,11 +6155,11 @@ async function openInBrowser(url) {
5658
6155
  }
5659
6156
 
5660
6157
  // src/version.ts
5661
- var VERSION = true ? "0.4.4" : "0.0.0-dev";
6158
+ var VERSION = true ? "0.4.6" : "0.0.0-dev";
5662
6159
 
5663
6160
  // src/commands/serve.ts
5664
6161
  var DEFAULT_PORT = 4321;
5665
- var WEB_DIR = join4(dirname4(fileURLToPath(import.meta.url)), "web");
6162
+ var WEB_DIR = join6(dirname10(fileURLToPath(import.meta.url)), "web");
5666
6163
  async function runServe(options) {
5667
6164
  const workspaceRoot = resolveWorkspaceRoot(options.workspace);
5668
6165
  await ensureWorkspace(workspaceRoot);