blastproof 0.29.1 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -574,13 +574,13 @@ async function resolveTarget(page, target, resolveTimeoutMs = 2e3) {
574
574
  if (!target.ref) throw new ActionError(`Element not found: ${describeTarget(target)} has no ref`);
575
575
  const ref = bareRef(target.ref);
576
576
  const locator = page.locator(`aria-ref=${ref}`);
577
- let count;
577
+ let count2;
578
578
  try {
579
- count = await locator.count();
579
+ count2 = await locator.count();
580
580
  } catch {
581
- count = 0;
581
+ count2 = 0;
582
582
  }
583
- if (count === 0) {
583
+ if (count2 === 0) {
584
584
  throw new ActionError(
585
585
  `Element not found: ${describeTarget(target)} (ref ${ref}) is no longer on the page; it changed since the snapshot. Choose the element again from the fresh snapshot.`
586
586
  );
@@ -1269,6 +1269,141 @@ function deviceOptions(name) {
1269
1269
  return options;
1270
1270
  }
1271
1271
 
1272
+ // src/session-capture.ts
1273
+ var SESSION_SEEDED_MARKER = "blastproof:session-seeded";
1274
+ async function readFalsyRecords() {
1275
+ const g = globalThis;
1276
+ const done = (request) => new Promise((resolve2, reject) => {
1277
+ request.onsuccess = () => resolve2(request.result);
1278
+ request.onerror = () => reject(request.error);
1279
+ });
1280
+ const encode = (value) => {
1281
+ if (value === null) return { v: "null" };
1282
+ if (typeof value === "number" && Number.isNaN(value)) return { v: "NaN" };
1283
+ if (Object.is(value, -0)) return { v: "-0" };
1284
+ if (value === 0 || value === "" || value === false) return { plain: value };
1285
+ return void 0;
1286
+ };
1287
+ const databases = [];
1288
+ for (const info of await g.indexedDB.databases()) {
1289
+ if (!info.name) continue;
1290
+ const db = await done(g.indexedDB.open(info.name));
1291
+ try {
1292
+ if (db.objectStoreNames.length === 0) {
1293
+ databases.push({ name: info.name, stores: [] });
1294
+ continue;
1295
+ }
1296
+ const transaction = db.transaction(db.objectStoreNames, "readonly");
1297
+ const reads = [...db.objectStoreNames].map((name) => {
1298
+ const store = transaction.objectStore(name);
1299
+ return Promise.all([done(store.getAllKeys()), done(store.getAll())]).then(([keys, values]) => ({
1300
+ name,
1301
+ count: keys.length,
1302
+ keys: keys.flatMap((key, i) => key === 0 || key === "" ? [[i, key]] : []),
1303
+ values: values.flatMap((value, i) => {
1304
+ const encoded = encode(value);
1305
+ return encoded ? [[i, encoded]] : [];
1306
+ })
1307
+ }));
1308
+ });
1309
+ databases.push({ name: info.name, stores: await Promise.all(reads) });
1310
+ } finally {
1311
+ db.close();
1312
+ }
1313
+ }
1314
+ return { origin: g.location.origin, databases };
1315
+ }
1316
+ function readSessionStorage() {
1317
+ const g = globalThis;
1318
+ const items = [];
1319
+ for (let i = 0; i < g.sessionStorage.length; i++) {
1320
+ const name = g.sessionStorage.key(i);
1321
+ if (name !== null) items.push({ name, value: g.sessionStorage.getItem(name) ?? "" });
1322
+ }
1323
+ return { origin: g.location.origin, items };
1324
+ }
1325
+ function seedSessionStorage(seed) {
1326
+ const g = globalThis;
1327
+ if (g.location.origin !== seed.origin) return;
1328
+ try {
1329
+ if (g.sessionStorage.getItem(seed.marker) !== null) return;
1330
+ for (const { name, value } of seed.items) g.sessionStorage.setItem(name, value);
1331
+ g.sessionStorage.setItem(seed.marker, "1");
1332
+ } catch {
1333
+ }
1334
+ }
1335
+ var isMissing = (record, field) => !(field in record) && !(`${field}Encoded` in record);
1336
+ var isOutOfLine = (store) => store.keyPath === void 0 && store.keyPathArray === void 0;
1337
+ function repairIndexedDB(state, found) {
1338
+ const origins = structuredClone(state.origins);
1339
+ for (const origin of origins) {
1340
+ const databases = origin.indexedDB ?? [];
1341
+ if (origin.origin !== found.origin) {
1342
+ const broken = databases.some(
1343
+ (db) => db.stores.some(
1344
+ (store) => store.records.some((r) => isOutOfLine(store) && isMissing(r, "key") || isMissing(r, "value"))
1345
+ )
1346
+ );
1347
+ if (broken) delete origin.indexedDB;
1348
+ continue;
1349
+ }
1350
+ for (const db of databases) {
1351
+ for (const store of db.stores) {
1352
+ const read = found.databases.find((d) => d.name === db.name)?.stores.find((s) => s.name === store.name);
1353
+ if (!read || read.count !== store.records.length) return void 0;
1354
+ const keys = new Map(read.keys);
1355
+ const values = new Map(read.values);
1356
+ for (const [i, record] of store.records.entries()) {
1357
+ if (isOutOfLine(store)) {
1358
+ const key = keys.get(i);
1359
+ if (isMissing(record, "key")) {
1360
+ if (key === void 0) return void 0;
1361
+ record.key = key;
1362
+ } else if (key !== void 0 && record.key !== key) {
1363
+ return void 0;
1364
+ }
1365
+ }
1366
+ const value = values.get(i);
1367
+ if (isMissing(record, "value")) {
1368
+ if (value === void 0) return void 0;
1369
+ if ("plain" in value) record.value = value.plain;
1370
+ else record.valueEncoded = value;
1371
+ } else if (value !== void 0 && "value" in record && record.value) {
1372
+ return void 0;
1373
+ }
1374
+ }
1375
+ }
1376
+ }
1377
+ }
1378
+ return { ...state, origins };
1379
+ }
1380
+ var CAPTURE_ATTEMPTS = 3;
1381
+ async function captureSession(context, page) {
1382
+ for (let attempt = 1; ; attempt++) {
1383
+ const state = await context.storageState({ indexedDB: true });
1384
+ const found = await page.evaluate(readFalsyRecords);
1385
+ const repaired = repairIndexedDB(state, found);
1386
+ if (repaired) {
1387
+ const sessionStorage = await page.evaluate(readSessionStorage);
1388
+ return {
1389
+ storageState: repaired,
1390
+ ...sessionStorage.items.length > 0 && sessionStorage.origin !== "null" ? { sessionStorage } : {}
1391
+ };
1392
+ }
1393
+ if (attempt === CAPTURE_ATTEMPTS) {
1394
+ throw new Error(`the app kept writing to its IndexedDB while the session was read (${CAPTURE_ATTEMPTS} attempts)`);
1395
+ }
1396
+ }
1397
+ }
1398
+ async function seedSessionStorageInto(context, seed) {
1399
+ await context.addInitScript(seedSessionStorage, { ...seed, marker: SESSION_SEEDED_MARKER });
1400
+ }
1401
+ function isSessionStorageSeed(value) {
1402
+ return typeof value === "object" && value !== null && typeof value.origin === "string" && Array.isArray(value.items) && value.items.every(
1403
+ (item) => typeof item?.name === "string" && typeof item?.value === "string"
1404
+ );
1405
+ }
1406
+
1272
1407
  // src/auth.ts
1273
1408
  var AUTH_STATE_RELATIVE_PATH = path3.join(".blastproof", ".auth-state.json");
1274
1409
  var AuthError = class extends Error {
@@ -1300,7 +1435,8 @@ async function fromStorageState(file) {
1300
1435
  `Invalid storage state at ${file}: expected an object with "cookies" and "origins" arrays.`
1301
1436
  );
1302
1437
  }
1303
- return { storageState: parsed };
1438
+ const { sessionStorage, ...storageState } = parsed;
1439
+ return { storageState, ...isSessionStorageSeed(sessionStorage) ? { sessionStorage } : {} };
1304
1440
  }
1305
1441
  function fromStatic(auth, mask) {
1306
1442
  const session = {};
@@ -1392,7 +1528,55 @@ async function fromSteps(options) {
1392
1528
  throw new AuthError(`Authentication could not be verified: ${mask.mask(judgment.reason)}`);
1393
1529
  }
1394
1530
  }
1395
- return { storageState: await context.storageState() };
1531
+ let session;
1532
+ try {
1533
+ session = await captureSession(context, page);
1534
+ } catch (error) {
1535
+ throw new AuthError(
1536
+ `Signed in, but the session could not be captured: ${error instanceof Error ? error.message : String(error)}`
1537
+ );
1538
+ }
1539
+ await checkWhereUsed(options, session, page, takeSnapshot);
1540
+ return session;
1541
+ } finally {
1542
+ await context.close();
1543
+ }
1544
+ }
1545
+ async function checkWhereUsed(options, session, loginPage, takeSnapshot) {
1546
+ const { browser, brain, mask, maxRetries, timeoutMs } = options;
1547
+ const verify = options.auth.verify;
1548
+ if (!verify) return;
1549
+ let context;
1550
+ try {
1551
+ context = await browser.newContext(contextOptions(session, options.device));
1552
+ } catch (error) {
1553
+ throw new AuthError(
1554
+ "Signed in, but the captured session cannot be restored into a new browser context: " + (error instanceof Error ? error.message : String(error))
1555
+ );
1556
+ }
1557
+ try {
1558
+ await seedContext(context, session);
1559
+ const page = await context.newPage();
1560
+ try {
1561
+ await page.goto(loginPage.url(), { timeout: timeoutMs });
1562
+ } catch (error) {
1563
+ throw new AuthError(
1564
+ "Signed in, but the page the login ended on did not open in a new browser context seeded with the session: " + (error instanceof Error ? error.message : String(error))
1565
+ );
1566
+ }
1567
+ await waitForSettled(page);
1568
+ const judgment = await verifyJudgment(
1569
+ brain,
1570
+ verify,
1571
+ async () => withoutRefs(mask.mask(await takeSnapshot(page))),
1572
+ (text) => mask.mask(text),
1573
+ maxRetries
1574
+ );
1575
+ if (!judgment.pass) {
1576
+ throw new AuthError(
1577
+ `Signed in, but the captured session does not keep the sign-in: a new browser context seeded with it is not signed in (${mask.mask(judgment.reason)}). The app may keep its session where a storage state cannot hold it, such as memory or a service worker. Tests would start signed out, so none were run.`
1578
+ );
1579
+ }
1396
1580
  } finally {
1397
1581
  await context.close();
1398
1582
  }
@@ -1408,7 +1592,8 @@ async function writeCached(cwd, session) {
1408
1592
  if (!session.storageState) return;
1409
1593
  const file = path3.join(cwd, AUTH_STATE_RELATIVE_PATH);
1410
1594
  await mkdir3(path3.dirname(file), { recursive: true });
1411
- await writeFile2(file, JSON.stringify(session.storageState), "utf8");
1595
+ const cached = session.sessionStorage ? { ...session.storageState, sessionStorage: session.sessionStorage } : session.storageState;
1596
+ await writeFile2(file, JSON.stringify(cached), "utf8");
1412
1597
  }
1413
1598
  async function authenticate(options) {
1414
1599
  const { auth, cwd } = options;
@@ -1434,6 +1619,9 @@ function contextOptions(session, device) {
1434
1619
  ...session.extraHTTPHeaders ? { extraHTTPHeaders: session.extraHTTPHeaders } : {}
1435
1620
  };
1436
1621
  }
1622
+ async function seedContext(context, session) {
1623
+ if (session?.sessionStorage) await seedSessionStorageInto(context, session.sessionStorage);
1624
+ }
1437
1625
 
1438
1626
  // src/config.ts
1439
1627
  import { readFile as readFile2 } from "fs/promises";
@@ -3206,6 +3394,7 @@ async function runOne(browser, test, config, sessionDir, session, runMask, budge
3206
3394
  const device = test.device ?? config.browser.device;
3207
3395
  const context = await browser.newContext(contextOptions(test.auth ? session : void 0, device));
3208
3396
  try {
3397
+ await seedContext(context, test.auth ? session : void 0);
3209
3398
  const page = await context.newPage();
3210
3399
  page.setDefaultTimeout(config.browser.timeout_ms);
3211
3400
  const result = await executeTest(page, resolved, {
@@ -3225,28 +3414,42 @@ async function runOne(browser, test, config, sessionDir, session, runMask, budge
3225
3414
  await context.close();
3226
3415
  }
3227
3416
  }
3228
- function printImpactReport(impact, selection, cwd) {
3229
- console.log("\n--- Impact -----------------------------------------------------");
3230
- console.log(
3231
- impact.affectedRoutes.length > 0 ? "Affected routes:" : "Affected routes: none"
3232
- );
3233
- for (const route of impact.affectedRoutes) console.log(` ${route}`);
3234
- if (impact.unmappedFiles.length > 0) {
3235
- console.log("Unclassified files (matched by no routes: or ignore: glob):");
3236
- for (const file of impact.unmappedFiles) console.log(` ${file}`);
3237
- }
3417
+ function count(n, singular, plural) {
3418
+ return `${n} ${n === 1 ? singular : plural}`;
3419
+ }
3420
+ var IGNORED_NAMED = 3;
3421
+ function printImpactReport(impact, selection, changedCount, base, cwd) {
3422
+ const uncovered = new Set(selection.uncoveredRoutes);
3423
+ const unrouted = selection.unroutedSkipped;
3424
+ const gaps = [
3425
+ impact.unmappedFiles.length > 0 && count(impact.unmappedFiles.length, "unclassified file", "unclassified files"),
3426
+ uncovered.size > 0 && count(uncovered.size, "route no selected test covers", "routes no selected test covers"),
3427
+ unrouted.length > 0 && count(unrouted.length, "test with no routes:", "tests with no routes:")
3428
+ ].filter((gap) => gap !== false);
3429
+ console.log(`
3430
+ ${`--- Impact against ${base} `.padEnd(64, "-")}`);
3431
+ console.log(`Not covered: ${gaps.length > 0 ? gaps.join(" \xB7 ") : "nothing"}`);
3432
+ console.log(`
3433
+ Changed files: ${changedCount}`);
3434
+ const reaching = changedCount - impact.ignoredFiles.length - impact.unmappedFiles.length;
3435
+ if (reaching > 0) console.log(` ${reaching} reach a route`);
3238
3436
  if (impact.ignoredFiles.length > 0) {
3239
- console.log(`Ignored files: ${impact.ignoredFiles.length}`);
3437
+ const named = impact.ignoredFiles.slice(0, IGNORED_NAMED).join(", ");
3438
+ const more = impact.ignoredFiles.length - IGNORED_NAMED;
3439
+ console.log(` ${impact.ignoredFiles.length} ignored by an ignore: glob: ${named}${more > 0 ? ` and ${more} more` : ""}`);
3240
3440
  }
3241
- if (selection.unroutedSkipped.length > 0) {
3242
- console.log("Unrouted tests (skipped):");
3243
- for (const test of selection.unroutedSkipped) {
3244
- console.log(` ${test.summary} (${path10.relative(cwd, test.path)})`);
3245
- }
3441
+ if (impact.unmappedFiles.length > 0) {
3442
+ console.log(` ${impact.unmappedFiles.length} unclassified, matched by no routes: or ignore: glob:`);
3443
+ for (const file of impact.unmappedFiles) console.log(` ${file}`);
3444
+ }
3445
+ console.log(`Routes the diff reaches: ${impact.affectedRoutes.length > 0 ? impact.affectedRoutes.length : "none"}`);
3446
+ for (const route of impact.affectedRoutes) {
3447
+ console.log(` ${route}${uncovered.has(route) ? " (no selected test covers it)" : ""}`);
3246
3448
  }
3247
- if (selection.uncoveredRoutes.length > 0) {
3248
- console.log("Affected but uncovered routes:");
3249
- for (const route of selection.uncoveredRoutes) console.log(` ${route}`);
3449
+ console.log(`Tests: ${selection.selected.length} selected`);
3450
+ if (unrouted.length > 0) {
3451
+ console.log(` ${unrouted.length} ${unrouted.length === 1 ? "declares" : "declare"} no routes:, so --impacted cannot select ${unrouted.length === 1 ? "it" : "them"}:`);
3452
+ for (const test of unrouted) console.log(` ${test.summary} (${path10.relative(cwd, test.path)})`);
3250
3453
  }
3251
3454
  console.log("---------------------------------------------------------------");
3252
3455
  }
@@ -3402,6 +3605,7 @@ async function runCommand(options) {
3402
3605
  return EXIT_USAGE;
3403
3606
  }
3404
3607
  let impact;
3608
+ let changedCount = 0;
3405
3609
  if (impacted) {
3406
3610
  let changedFiles;
3407
3611
  try {
@@ -3414,6 +3618,7 @@ async function runCommand(options) {
3414
3618
  throw error;
3415
3619
  }
3416
3620
  impact = mapImpact(changedFiles, config.routes ?? {}, config.ignore ?? []);
3621
+ changedCount = changedFiles.length;
3417
3622
  printUncommitted(await getUncommittedFiles(options.cwd), changedFiles, config, base, warnings);
3418
3623
  }
3419
3624
  const testsDir = path10.join(options.cwd, TESTS_RELATIVE_DIR);
@@ -3463,7 +3668,7 @@ async function runCommand(options) {
3463
3668
  };
3464
3669
  const selected = selection.selected;
3465
3670
  if (impact) {
3466
- printImpactReport(impact, selection, options.cwd);
3671
+ printImpactReport(impact, selection, changedCount, base, options.cwd);
3467
3672
  }
3468
3673
  if (options.dryRun) {
3469
3674
  printDryRun(selected, config, options.cwd);
@@ -3782,6 +3987,7 @@ async function planCommand(options) {
3782
3987
  let draft;
3783
3988
  const context = await browser.newContext(contextOptions(session, config.browser.device));
3784
3989
  try {
3990
+ await seedContext(context, session);
3785
3991
  const page = await context.newPage();
3786
3992
  page.setDefaultTimeout(config.browser.timeout_ms);
3787
3993
  draft = await generateForRoute(page, {
@@ -3942,7 +4148,7 @@ function parsePositiveNumber(flag) {
3942
4148
  };
3943
4149
  }
3944
4150
  var program = new Command();
3945
- program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.29.1");
4151
+ program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.30.0");
3946
4152
  program.command("init").description("Scaffold .blastproof/ (config, tests, sample tests) in the current directory").action(async () => {
3947
4153
  try {
3948
4154
  const result = await initProject(process.cwd());