@decocms/parity 0.33.63 → 0.33.64

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.
Files changed (2) hide show
  1. package/dist/cli.js +799 -456
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -37430,7 +37430,7 @@ order — never add, remove, merge, or split entries.
37430
37430
 
37431
37431
  // src/cli.ts
37432
37432
  import { DESCRIPTION, registerCommands } from "@decocms/vtex-cms";
37433
- import { Command } from "commander";
37433
+ import { Command, InvalidArgumentError as InvalidArgumentError2 } from "commander";
37434
37434
 
37435
37435
  // src/commands/studio.ts
37436
37436
  import { execFileSync as execFileSync2 } from "node:child_process";
@@ -39191,6 +39191,8 @@ async function newContext(browser, opts) {
39191
39191
  });
39192
39192
  }
39193
39193
  await ctx.addInitScript({ content: CAROUSEL_STABILIZER_INIT_SCRIPT });
39194
+ if (opts.cookies?.length)
39195
+ await ctx.addCookies(opts.cookies);
39194
39196
  if (opts.cohortCookieValue) {
39195
39197
  await ctx.addCookies([
39196
39198
  {
@@ -49050,8 +49052,8 @@ function baselineUnset(name) {
49050
49052
  }
49051
49053
 
49052
49054
  // src/commands/benchmark.ts
49053
- import { writeFileSync as writeFileSync11 } from "node:fs";
49054
- import { join as join14 } from "node:path";
49055
+ import { writeFileSync as writeFileSync12 } from "node:fs";
49056
+ import { join as join15 } from "node:path";
49055
49057
  import chalk6 from "chalk";
49056
49058
  import ora2 from "ora";
49057
49059
 
@@ -49059,8 +49061,138 @@ import ora2 from "ora";
49059
49061
  init_client();
49060
49062
 
49061
49063
  // src/migrate/assets.ts
49064
+ import { mkdirSync as mkdirSync6, writeFileSync as writeFileSync8 } from "node:fs";
49065
+ import { join as join10, relative as relative2 } from "node:path";
49066
+
49067
+ // src/migrate/vtex/content-assets.ts
49062
49068
  import { mkdirSync as mkdirSync5, writeFileSync as writeFileSync7 } from "node:fs";
49063
49069
  import { join as join9 } from "node:path";
49070
+ var MAX_IMAGES = 150;
49071
+ var IMG_EXT = /\.(jpe?g|png|webp|gif|svg|avif)(\?|#|$)/i;
49072
+ var VTEX_ASSET = /vtexassets\.com|vteximg\.com\.br|\/arquivos\/(ids|assets)\//i;
49073
+ function isImageUrl(s) {
49074
+ if (typeof s !== "string")
49075
+ return false;
49076
+ const v = s.trim();
49077
+ if (!/^(https?:)?\/\//i.test(v))
49078
+ return false;
49079
+ return IMG_EXT.test(v) || VTEX_ASSET.test(v);
49080
+ }
49081
+ function isImageRef(s) {
49082
+ if (typeof s !== "string")
49083
+ return false;
49084
+ const v = s.trim();
49085
+ if (isImageUrl(v))
49086
+ return true;
49087
+ return v.startsWith("/") && !v.startsWith("//") && (IMG_EXT.test(v) || VTEX_ASSET.test(v) || v.startsWith("/img/"));
49088
+ }
49089
+ function resolveRef(ref, baseUrl) {
49090
+ const v = ref.trim();
49091
+ try {
49092
+ if (v.startsWith("//"))
49093
+ return `https:${v}`;
49094
+ return new URL(v, baseUrl).toString();
49095
+ } catch {
49096
+ return null;
49097
+ }
49098
+ }
49099
+ function collectImageRefs(blocks, baseUrl) {
49100
+ const out = {};
49101
+ const walk = (v) => {
49102
+ if (typeof v === "string") {
49103
+ const s = v.trim();
49104
+ if (isImageRef(s) && !(s in out)) {
49105
+ const abs = resolveRef(s, baseUrl);
49106
+ if (abs)
49107
+ out[s] = abs;
49108
+ }
49109
+ } else if (Array.isArray(v)) {
49110
+ for (const x of v)
49111
+ walk(x);
49112
+ } else if (v && typeof v === "object") {
49113
+ for (const x of Object.values(v))
49114
+ walk(x);
49115
+ }
49116
+ };
49117
+ for (const b of blocks)
49118
+ if (b.props)
49119
+ walk(b.props);
49120
+ return out;
49121
+ }
49122
+ function countContentImages(blocks) {
49123
+ const urls = new Set;
49124
+ const walk = (v) => {
49125
+ if (typeof v === "string") {
49126
+ if (isImageUrl(v.trim()))
49127
+ urls.add(v.trim());
49128
+ } else if (Array.isArray(v)) {
49129
+ for (const x of v)
49130
+ walk(x);
49131
+ } else if (v && typeof v === "object") {
49132
+ for (const x of Object.values(v))
49133
+ walk(x);
49134
+ }
49135
+ };
49136
+ for (const b of blocks)
49137
+ if (b.props)
49138
+ walk(b.props);
49139
+ return urls.size;
49140
+ }
49141
+ function rewriteBlockUrls(blocks, urlToPath) {
49142
+ const replace = (v) => {
49143
+ if (typeof v === "string")
49144
+ return urlToPath[v.trim()] ?? v;
49145
+ if (Array.isArray(v))
49146
+ return v.map(replace);
49147
+ if (v && typeof v === "object") {
49148
+ const out = {};
49149
+ for (const [k, val] of Object.entries(v))
49150
+ out[k] = replace(val);
49151
+ return out;
49152
+ }
49153
+ return v;
49154
+ };
49155
+ return blocks.map((b) => ({
49156
+ ...b,
49157
+ props: b.props ? replace(b.props) : b.props
49158
+ }));
49159
+ }
49160
+ function contentImageName(url, index, used) {
49161
+ let base = "img";
49162
+ try {
49163
+ base = new URL(url, "https://x").pathname.split("/").filter(Boolean).pop() ?? "img";
49164
+ } catch {}
49165
+ base = base.split("?")[0].replace(/[^\w.-]/g, "_").slice(-60) || "img";
49166
+ if (!/\.(jpe?g|png|webp|gif|svg|avif)$/i.test(base))
49167
+ base += ".img";
49168
+ let name = base;
49169
+ if (used.has(name))
49170
+ name = `${index}-${base}`;
49171
+ used.add(name);
49172
+ return name;
49173
+ }
49174
+ async function downloadContentImages(urls, runDir, fetchBytes) {
49175
+ const map = {};
49176
+ if (urls.length === 0)
49177
+ return { map, downloaded: 0, skipped: 0 };
49178
+ const dir = join9(runDir, "assets", "content");
49179
+ mkdirSync5(dir, { recursive: true });
49180
+ const used = new Set;
49181
+ const take = urls.slice(0, MAX_IMAGES);
49182
+ let downloaded = 0;
49183
+ for (const [i, url] of take.entries()) {
49184
+ const got = await fetchBytes(url.startsWith("//") ? `https:${url}` : url);
49185
+ if (!got)
49186
+ continue;
49187
+ const name = contentImageName(url, i, used);
49188
+ writeFileSync7(join9(dir, name), got.buf);
49189
+ map[url] = `assets/content/${name}`;
49190
+ downloaded++;
49191
+ }
49192
+ return { map, downloaded, skipped: Math.max(0, urls.length - take.length) };
49193
+ }
49194
+
49195
+ // src/migrate/assets.ts
49064
49196
  function aggregateIcons(icons) {
49065
49197
  const byKey = new Map;
49066
49198
  for (const icon of icons) {
@@ -49200,7 +49332,7 @@ async function downloadTo(url, dir, name, fetchBytes) {
49200
49332
  return null;
49201
49333
  const ext = extFromUrlOrType(url, got.contentType);
49202
49334
  const file = `${name}${ext}`;
49203
- writeFileSync7(join9(dir, file), got.buf);
49335
+ writeFileSync8(join10(dir, file), got.buf);
49204
49336
  return `assets/${file}`;
49205
49337
  }
49206
49338
  function extFromUrlOrType(url, contentType) {
@@ -49222,15 +49354,15 @@ function extFromUrlOrType(url, contentType) {
49222
49354
  return "";
49223
49355
  }
49224
49356
  async function downloadSiteAssets(raw, runDir, fetchBytes) {
49225
- const dir = join9(runDir, "assets");
49226
- mkdirSync5(dir, { recursive: true });
49357
+ const dir = join10(runDir, "assets");
49358
+ mkdirSync6(dir, { recursive: true });
49227
49359
  let logo = null;
49228
49360
  let logoSource = null;
49229
49361
  if (raw.logo?.type === "img") {
49230
49362
  logoSource = raw.logo.url;
49231
49363
  logo = await downloadTo(raw.logo.url, dir, "logo", fetchBytes);
49232
49364
  } else if (raw.logo?.type === "svg") {
49233
- writeFileSync7(join9(dir, "logo.svg"), raw.logo.markup, "utf8");
49365
+ writeFileSync8(join10(dir, "logo.svg"), raw.logo.markup, "utf8");
49234
49366
  logo = "assets/logo.svg";
49235
49367
  logoSource = "inline-svg";
49236
49368
  }
@@ -49239,15 +49371,15 @@ async function downloadSiteAssets(raw, runDir, fetchBytes) {
49239
49371
  raw.appleTouchIcon ? downloadTo(raw.appleTouchIcon, dir, "apple-touch-icon", fetchBytes) : Promise.resolve(null),
49240
49372
  raw.ogImage ? downloadTo(raw.ogImage, dir, "og-image", fetchBytes) : Promise.resolve(null)
49241
49373
  ]);
49242
- const fontsDir = join9(dir, "fonts");
49243
- mkdirSync5(fontsDir, { recursive: true });
49374
+ const fontsDir = join10(dir, "fonts");
49375
+ mkdirSync6(fontsDir, { recursive: true });
49244
49376
  const fontFiles = [];
49245
49377
  for (const [i, url] of raw.fonts.entries()) {
49246
49378
  const got = await fetchBytes(url);
49247
49379
  if (!got)
49248
49380
  continue;
49249
49381
  const base = safeFontName(url, i);
49250
- writeFileSync7(join9(fontsDir, base), got.buf);
49382
+ writeFileSync8(join10(fontsDir, base), got.buf);
49251
49383
  fontFiles.push(`assets/fonts/${base}`);
49252
49384
  }
49253
49385
  return {
@@ -49274,6 +49406,77 @@ function safeFontName(url, i) {
49274
49406
  return `font-${i}.woff2`;
49275
49407
  }
49276
49408
  }
49409
+ function newComponentImageBudget(maxFiles = 200, maxBytes = 50 * 1024 * 1024) {
49410
+ return { maxFiles, maxBytes, files: 0, bytes: 0, capped: 0, byUrl: new Map };
49411
+ }
49412
+ function cssUrls(backgroundImage) {
49413
+ return [...backgroundImage.matchAll(/url\(\s*(['"]?)(.*?)\1\s*\)/g)].map((m) => m[2]).filter(Boolean);
49414
+ }
49415
+ var SMALLER_SRCSET_WIDTH = "smaller srcset width, not downloaded";
49416
+ function pickLargestImage(src, srcset) {
49417
+ const candidates = (srcset ?? "").split(",").map((part) => {
49418
+ const [url, desc = "1x"] = part.trim().split(/\s+/);
49419
+ const n = Number.parseFloat(desc) || 0;
49420
+ return { url: url ?? "", w: desc.endsWith("w") ? n : 0, x: desc.endsWith("x") ? n : 0 };
49421
+ }).filter((c) => c.url);
49422
+ if (!candidates.length)
49423
+ return { keep: src, smaller: [] };
49424
+ const best = candidates.reduce((a, b) => b.w > a.w || b.w === a.w && b.x > a.x ? b : a);
49425
+ const smaller = new Set([...candidates.map((c) => c.url), ...src ? [src] : []]);
49426
+ smaller.delete(best.url);
49427
+ return { keep: best.url, smaller: [...smaller] };
49428
+ }
49429
+ function absoluteUrls(raw, pageUrl) {
49430
+ const urls = new Set;
49431
+ for (const r of raw) {
49432
+ try {
49433
+ const abs = new URL(r, pageUrl);
49434
+ if (abs.protocol === "http:" || abs.protocol === "https:")
49435
+ urls.add(abs.href);
49436
+ } catch {}
49437
+ }
49438
+ return urls;
49439
+ }
49440
+ async function downloadComponentImages(rawUrls, pageUrl, componentDir, runDir, fetchBytes, budget, smallerUrls = []) {
49441
+ const urls = absoluteUrls(rawUrls, pageUrl);
49442
+ const dir = join10(componentDir, "images");
49443
+ const used = new Set;
49444
+ const out = [];
49445
+ for (const url of urls) {
49446
+ let entry = budget.byUrl.get(url);
49447
+ if (!entry) {
49448
+ if (budget.files >= budget.maxFiles || budget.bytes >= budget.maxBytes) {
49449
+ budget.capped++;
49450
+ const mb = Math.round(budget.maxBytes / 1024 / 1024);
49451
+ entry = {
49452
+ url,
49453
+ error: `not downloaded: per-run cap reached (${budget.maxFiles} files / ${mb} MB)`
49454
+ };
49455
+ } else {
49456
+ const got = await fetchBytes(url);
49457
+ if ("error" in got)
49458
+ entry = { url, error: got.error };
49459
+ else {
49460
+ mkdirSync6(dir, { recursive: true });
49461
+ const name = contentImageName(url, used.size, used);
49462
+ writeFileSync8(join10(dir, name), got.buf);
49463
+ budget.files++;
49464
+ budget.bytes += got.buf.length;
49465
+ entry = { url, path: relative2(runDir, join10(dir, name)) };
49466
+ }
49467
+ }
49468
+ budget.byUrl.set(url, entry);
49469
+ }
49470
+ out.push(entry);
49471
+ }
49472
+ for (const url of absoluteUrls(smallerUrls, pageUrl)) {
49473
+ if (urls.has(url))
49474
+ continue;
49475
+ const saved = budget.byUrl.get(url);
49476
+ out.push(saved?.path ? saved : { url, skipped: SMALLER_SRCSET_WIDTH });
49477
+ }
49478
+ return out;
49479
+ }
49277
49480
 
49278
49481
  // src/llm/recover-step.ts
49279
49482
  init_esm10();
@@ -49418,7 +49621,7 @@ ${compacted}
49418
49621
  // src/engine/interactive-selector-prompt.ts
49419
49622
  init_client();
49420
49623
  import { execSync } from "node:child_process";
49421
- import { existsSync as existsSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync8 } from "node:fs";
49624
+ import { existsSync as existsSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync9 } from "node:fs";
49422
49625
  import { resolve } from "node:path";
49423
49626
  import { createInterface } from "node:readline";
49424
49627
  var forceDisabled = false;
@@ -49508,7 +49711,7 @@ function writeSelectorOverride(rcPath, key, value) {
49508
49711
  }
49509
49712
  }
49510
49713
  current.selectors = { ...current.selectors ?? {}, [key]: value };
49511
- writeFileSync8(rcPath, `${JSON.stringify(current, null, 2)}
49714
+ writeFileSync9(rcPath, `${JSON.stringify(current, null, 2)}
49512
49715
  `, "utf8");
49513
49716
  }
49514
49717
  function tryOpenInEditor(rcPath) {
@@ -49628,7 +49831,7 @@ ${candidates.map((c, i) => `${i}. "${c.text}" → ${c.href}`).join(`
49628
49831
  }
49629
49832
 
49630
49833
  // src/learned/repo.ts
49631
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync9, renameSync, writeFileSync as writeFileSync9 } from "node:fs";
49834
+ import { existsSync as existsSync8, mkdirSync as mkdirSync7, readFileSync as readFileSync9, renameSync, writeFileSync as writeFileSync10 } from "node:fs";
49632
49835
  import { dirname as dirname3 } from "node:path";
49633
49836
  import { z as z2 } from "zod";
49634
49837
  var SelectorKey = z2.enum([
@@ -49714,9 +49917,9 @@ function loadLearned(path = DEFAULT_PATH) {
49714
49917
  function saveLearned(lib, path = DEFAULT_PATH) {
49715
49918
  const dir = dirname3(path);
49716
49919
  if (dir && dir !== "." && !existsSync8(dir))
49717
- mkdirSync6(dir, { recursive: true });
49920
+ mkdirSync7(dir, { recursive: true });
49718
49921
  const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
49719
- writeFileSync9(tmp, `${JSON.stringify(lib, null, 2)}
49922
+ writeFileSync10(tmp, `${JSON.stringify(lib, null, 2)}
49720
49923
  `, "utf8");
49721
49924
  renameSync(tmp, path);
49722
49925
  }
@@ -52701,8 +52904,8 @@ async function validateAddToCart(page, ctx, cartCountBefore, beforeUrl) {
52701
52904
 
52702
52905
  // src/engine/lighthouse.ts
52703
52906
  import { spawn } from "node:child_process";
52704
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync10 } from "node:fs";
52705
- import { join as join11, resolve as resolve2 } from "node:path";
52907
+ import { mkdirSync as mkdirSync8, readFileSync as readFileSync10 } from "node:fs";
52908
+ import { join as join12, resolve as resolve2 } from "node:path";
52706
52909
  var AGENT_A11Y_AUDIT_IDS = [
52707
52910
  "button-name",
52708
52911
  "link-name",
@@ -52789,10 +52992,10 @@ async function measureLighthouse(url, opts) {
52789
52992
  }
52790
52993
  async function measureLighthouseOnce(url, opts, attempt) {
52791
52994
  const formFactor = opts.formFactor ?? "mobile";
52792
- mkdirSync7(opts.outDir, { recursive: true });
52793
- const outPath = join11(opts.outDir, `${opts.id}-a${attempt}.json`);
52995
+ mkdirSync8(opts.outDir, { recursive: true });
52996
+ const outPath = join12(opts.outDir, `${opts.id}-a${attempt}.json`);
52794
52997
  const runTemp = resolve2(opts.outDir, `.tmp-${opts.id}-a${attempt}`);
52795
- mkdirSync7(runTemp, { recursive: true });
52998
+ mkdirSync8(runTemp, { recursive: true });
52796
52999
  const args = [
52797
53000
  "--yes",
52798
53001
  "lighthouse",
@@ -54229,9 +54432,9 @@ async function runSideBenchmarkContent(opts) {
54229
54432
 
54230
54433
  // src/ignore/parser.ts
54231
54434
  import { existsSync as existsSync9, readFileSync as readFileSync11 } from "node:fs";
54232
- import { join as join12 } from "node:path";
54435
+ import { join as join13 } from "node:path";
54233
54436
  function loadParityRc(cwd = process.cwd()) {
54234
- const path = join12(cwd, ".parityrc.json");
54437
+ const path = join13(cwd, ".parityrc.json");
54235
54438
  if (!existsSync9(path))
54236
54439
  return ParityRc.parse({});
54237
54440
  try {
@@ -54243,7 +54446,7 @@ function loadParityRc(cwd = process.cwd()) {
54243
54446
  }
54244
54447
  }
54245
54448
  function loadParityIgnore(cwd = process.cwd()) {
54246
- const path = join12(cwd, ".parityignore");
54449
+ const path = join13(cwd, ".parityignore");
54247
54450
  if (!existsSync9(path))
54248
54451
  return ParityIgnore.parse({});
54249
54452
  try {
@@ -54424,8 +54627,8 @@ init_client();
54424
54627
  init_client();
54425
54628
  init_html_compact();
54426
54629
  init_html_compact();
54427
- import { existsSync as existsSync10, mkdirSync as mkdirSync8, readFileSync as readFileSync12, unlinkSync as unlinkSync2, writeFileSync as writeFileSync10 } from "node:fs";
54428
- import { join as join13 } from "node:path";
54630
+ import { existsSync as existsSync10, mkdirSync as mkdirSync9, readFileSync as readFileSync12, unlinkSync as unlinkSync2, writeFileSync as writeFileSync11 } from "node:fs";
54631
+ import { join as join14 } from "node:path";
54429
54632
  import { z as z3 } from "zod";
54430
54633
  var CACHE_DIR = ".parity-cache";
54431
54634
  var CACHE_SCHEMA_VERSION = 1;
@@ -54692,7 +54895,7 @@ var PDP_MAX_CHARS = 9000;
54692
54895
  async function discoverSelectors(urls, html, opts = {}) {
54693
54896
  const host = safeHost2(urls.home);
54694
54897
  const cacheDir = opts.cacheDir ?? CACHE_DIR;
54695
- const cachePath = join13(cacheDir, `selectors-${host}.json`);
54898
+ const cachePath = join14(cacheDir, `selectors-${host}.json`);
54696
54899
  const fingerprint = computeHtmlFingerprint(html.home);
54697
54900
  if (!opts.noCache && existsSync10(cachePath)) {
54698
54901
  const cached = readCacheEntry(cachePath, fingerprint);
@@ -54744,14 +54947,14 @@ ${compactHtmlForSelectors(html.pdp, PDP_MAX_CHARS)}
54744
54947
  selectors.checkoutButton = undefined;
54745
54948
  }
54746
54949
  if (!existsSync10(cacheDir))
54747
- mkdirSync8(cacheDir, { recursive: true });
54950
+ mkdirSync9(cacheDir, { recursive: true });
54748
54951
  const entry = {
54749
54952
  schemaVersion: CACHE_SCHEMA_VERSION,
54750
54953
  createdAt: new Date().toISOString(),
54751
54954
  htmlFingerprint: fingerprint,
54752
54955
  selectors
54753
54956
  };
54754
- writeFileSync10(cachePath, `${JSON.stringify(entry, null, 2)}
54957
+ writeFileSync11(cachePath, `${JSON.stringify(entry, null, 2)}
54755
54958
  `, "utf8");
54756
54959
  return selectors;
54757
54960
  }
@@ -54791,7 +54994,7 @@ function readCacheEntry(cachePath, currentFingerprint) {
54791
54994
  }
54792
54995
  function persistSelectorValidation(homeUrl, validated, cacheDir = CACHE_DIR) {
54793
54996
  const host = safeHost2(homeUrl);
54794
- const cachePath = join13(cacheDir, `selectors-${host}.json`);
54997
+ const cachePath = join14(cacheDir, `selectors-${host}.json`);
54795
54998
  if (!existsSync10(cachePath))
54796
54999
  return;
54797
55000
  try {
@@ -54799,7 +55002,7 @@ function persistSelectorValidation(homeUrl, validated, cacheDir = CACHE_DIR) {
54799
55002
  if (!parsed.success)
54800
55003
  return;
54801
55004
  const entry = { ...parsed.data, validated };
54802
- writeFileSync10(cachePath, `${JSON.stringify(entry, null, 2)}
55005
+ writeFileSync11(cachePath, `${JSON.stringify(entry, null, 2)}
54803
55006
  `, "utf8");
54804
55007
  } catch {}
54805
55008
  }
@@ -55494,8 +55697,8 @@ async function benchmarkCommand(opts) {
55494
55697
  learned,
55495
55698
  platform,
55496
55699
  outDir: paths.screenshotsDir,
55497
- harPath: join14(paths.harDir, `user-navigation-benchmark-${viewport}-${side}.har`),
55498
- lighthouseDir: join14(paths.runDir, "lighthouse"),
55700
+ harPath: join15(paths.harDir, `user-navigation-benchmark-${viewport}-${side}.har`),
55701
+ lighthouseDir: join15(paths.runDir, "lighthouse"),
55499
55702
  warmupRuns,
55500
55703
  measuredRuns,
55501
55704
  paginations,
@@ -55576,10 +55779,10 @@ async function benchmarkCommand(opts) {
55576
55779
  logo,
55577
55780
  sides
55578
55781
  };
55579
- writeFileSync11(paths.reportJson, `${JSON.stringify(report, null, 2)}
55782
+ writeFileSync12(paths.reportJson, `${JSON.stringify(report, null, 2)}
55580
55783
  `, "utf8");
55581
55784
  const html = renderBenchmarkHtml(report, { lang });
55582
- writeFileSync11(paths.reportHtml, html, "utf8");
55785
+ writeFileSync12(paths.reportHtml, html, "utf8");
55583
55786
  printSummary2(report);
55584
55787
  console.log(chalk6.dim(` → ${paths.reportHtml}`));
55585
55788
  console.log(chalk6.dim(` → HAR: ${paths.harDir}/user-navigation-benchmark-*.har`));
@@ -55633,7 +55836,7 @@ function printSummary2(report) {
55633
55836
  }
55634
55837
 
55635
55838
  // src/commands/cache.ts
55636
- import { existsSync as existsSync11, readFileSync as readFileSync14, writeFileSync as writeFileSync12 } from "node:fs";
55839
+ import { existsSync as existsSync11, readFileSync as readFileSync14, writeFileSync as writeFileSync13 } from "node:fs";
55637
55840
 
55638
55841
  // src/util/concurrency.ts
55639
55842
  async function runWithConcurrency(items, workers, fn) {
@@ -55649,7 +55852,7 @@ async function runWithConcurrency(items, workers, fn) {
55649
55852
  }
55650
55853
 
55651
55854
  // src/commands/cache.ts
55652
- import { join as join15 } from "node:path";
55855
+ import { join as join16 } from "node:path";
55653
55856
  import chalk7 from "chalk";
55654
55857
  import ora3 from "ora";
55655
55858
 
@@ -55947,7 +56150,7 @@ function humanKey2(key) {
55947
56150
  }
55948
56151
 
55949
56152
  // src/report/visual-prompt-builder.ts
55950
- import { relative as relative2 } from "node:path";
56153
+ import { relative as relative3 } from "node:path";
55951
56154
  var SEVERITY_ORDER3 = {
55952
56155
  critical: 0,
55953
56156
  high: 1,
@@ -55964,7 +56167,7 @@ function relPath2(runDir, absPath) {
55964
56167
  if (!absPath)
55965
56168
  return "";
55966
56169
  try {
55967
- return relative2(runDir, absPath);
56170
+ return relative3(runDir, absPath);
55968
56171
  } catch {
55969
56172
  return absPath;
55970
56173
  }
@@ -57764,7 +57967,7 @@ async function cacheCommand(opts) {
57764
57967
  writeRunReportJson(paths.runDir, run);
57765
57968
  const html = renderHtmlReport(run, paths.runDir);
57766
57969
  writeRunReportHtml(paths.runDir, html);
57767
- writeFileSync12(join15(paths.runDir, "cache.json"), `${JSON.stringify({
57970
+ writeFileSync13(join16(paths.runDir, "cache.json"), `${JSON.stringify({
57768
57971
  schemaVersion: "0.1",
57769
57972
  prodUrl: opts.prod,
57770
57973
  candUrl: opts.cand,
@@ -57873,8 +58076,8 @@ function printSummary3(check) {
57873
58076
  }
57874
58077
 
57875
58078
  // src/commands/cache-gap.ts
57876
- import { existsSync as existsSync12, readFileSync as readFileSync15, writeFileSync as writeFileSync13 } from "node:fs";
57877
- import { join as join16 } from "node:path";
58079
+ import { existsSync as existsSync12, readFileSync as readFileSync15, writeFileSync as writeFileSync14 } from "node:fs";
58080
+ import { join as join17 } from "node:path";
57878
58081
  import chalk8 from "chalk";
57879
58082
  import ora4 from "ora";
57880
58083
 
@@ -58338,7 +58541,7 @@ async function cacheGapCommand(opts, probe = httpProbe) {
58338
58541
  segmentation,
58339
58542
  loaders: loadersOut
58340
58543
  };
58341
- writeFileSync13(join16(paths.runDir, "cache-probe.json"), `${JSON.stringify(artifact, null, 2)}
58544
+ writeFileSync14(join17(paths.runDir, "cache-probe.json"), `${JSON.stringify(artifact, null, 2)}
58342
58545
  `, "utf8");
58343
58546
  printSummary4(artifact);
58344
58547
  if (opts.json)
@@ -58469,7 +58672,7 @@ async function measureCell(urls, hit, concurrency, samples, settleMs) {
58469
58672
  function loadProbes(opts) {
58470
58673
  if (!opts.dir)
58471
58674
  return [];
58472
- const file = join16(opts.dir, ".deco", "blocks.gen.json");
58675
+ const file = join17(opts.dir, ".deco", "blocks.gen.json");
58473
58676
  if (!existsSync12(file)) {
58474
58677
  console.log(chalk8.yellow(` fase 3 pulada — ${file} não existe`));
58475
58678
  return [];
@@ -58615,7 +58818,7 @@ function printSummary4(a) {
58615
58818
  // src/commands/check.ts
58616
58819
  import { mkdtempSync } from "node:fs";
58617
58820
  import { tmpdir } from "node:os";
58618
- import { join as join17 } from "node:path";
58821
+ import { join as join18 } from "node:path";
58619
58822
  import chalk9 from "chalk";
58620
58823
  var SEVERITY_RANK4 = {
58621
58824
  critical: 0,
@@ -58672,7 +58875,7 @@ que o 'parity check' não roda.
58672
58875
  }
58673
58876
  const rc = loadParityRc();
58674
58877
  const ignore = loadParityIgnore();
58675
- const runDir = mkdtempSync(join17(tmpdir(), "parity-check-"));
58878
+ const runDir = mkdtempSync(join18(tmpdir(), "parity-check-"));
58676
58879
  const browser = await launchBrowser({ headless: true });
58677
58880
  const prodPages = [];
58678
58881
  const candPages = [];
@@ -58690,7 +58893,7 @@ que o 'parity check' não roda.
58690
58893
  url: fullUrl,
58691
58894
  side,
58692
58895
  viewport,
58693
- screenshotPath: join17(runDir, `${opts.name}-${viewport}-${side}.png`),
58896
+ screenshotPath: join18(runDir, `${opts.name}-${viewport}-${side}.png`),
58694
58897
  settleMs: 1200,
58695
58898
  timeoutMs: 25000,
58696
58899
  fast: true,
@@ -58793,7 +58996,7 @@ function printResult(result, meta) {
58793
58996
 
58794
58997
  // src/commands/css-modules.ts
58795
58998
  import { readFileSync as readFileSync16, readdirSync as readdirSync3 } from "node:fs";
58796
- import { basename as basename2, dirname as dirname4, join as join18, resolve as resolve3 } from "node:path";
58999
+ import { basename as basename2, dirname as dirname4, join as join19, resolve as resolve3 } from "node:path";
58797
59000
  import chalk10 from "chalk";
58798
59001
  var SKIP_DIRS = new Set(["node_modules", ".git", ".next", ".faststore", "dist", "build"]);
58799
59002
  var MODULE_RE = /\.module\.(scss|sass|css)$/;
@@ -58802,9 +59005,9 @@ function walk(dir, out = []) {
58802
59005
  for (const e of readdirSync3(dir, { withFileTypes: true })) {
58803
59006
  if (e.isDirectory()) {
58804
59007
  if (!SKIP_DIRS.has(e.name))
58805
- walk(join18(dir, e.name), out);
59008
+ walk(join19(dir, e.name), out);
58806
59009
  } else
58807
- out.push(join18(dir, e.name));
59010
+ out.push(join19(dir, e.name));
58808
59011
  }
58809
59012
  return out;
58810
59013
  }
@@ -59236,7 +59439,7 @@ async function cssTraceCommand(opts) {
59236
59439
  }
59237
59440
 
59238
59441
  // src/commands/e2e.ts
59239
- import { writeFileSync as writeFileSync15 } from "node:fs";
59442
+ import { writeFileSync as writeFileSync16 } from "node:fs";
59240
59443
  import { spawn as spawn2 } from "node:child_process";
59241
59444
  import chalk14 from "chalk";
59242
59445
  import ora6 from "ora";
@@ -60188,8 +60391,8 @@ async function flowLogin(ctx) {
60188
60391
 
60189
60392
  // src/llm/resolve-search-terms.ts
60190
60393
  init_client();
60191
- import { existsSync as existsSync13, mkdirSync as mkdirSync9, readFileSync as readFileSync17, writeFileSync as writeFileSync14 } from "node:fs";
60192
- import { join as join19 } from "node:path";
60394
+ import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync17, writeFileSync as writeFileSync15 } from "node:fs";
60395
+ import { join as join20 } from "node:path";
60193
60396
  var CACHE_DIR2 = ".parity-cache";
60194
60397
  var FALLBACK_TERMS = ["produto", "preto", "promocao"];
60195
60398
  function makeNoResults(runId) {
@@ -60269,7 +60472,7 @@ async function resolveSearchTerms(url, html, opts = {}) {
60269
60472
  }
60270
60473
  const host = safeHost3(url);
60271
60474
  const cacheDir = opts.cacheDir ?? CACHE_DIR2;
60272
- const cachePath = join19(cacheDir, `search-terms-${host}.json`);
60475
+ const cachePath = join20(cacheDir, `search-terms-${host}.json`);
60273
60476
  if (!opts.noCache && existsSync13(cachePath)) {
60274
60477
  try {
60275
60478
  const cached = JSON.parse(readFileSync17(cachePath, "utf8"));
@@ -60281,8 +60484,8 @@ async function resolveSearchTerms(url, html, opts = {}) {
60281
60484
  const suggested = await suggestTermViaLlm(url, html);
60282
60485
  if (suggested) {
60283
60486
  if (!existsSync13(cacheDir))
60284
- mkdirSync9(cacheDir, { recursive: true });
60285
- writeFileSync14(cachePath, `${JSON.stringify({ withResults: suggested, source: "llm" }, null, 2)}
60487
+ mkdirSync10(cacheDir, { recursive: true });
60488
+ writeFileSync15(cachePath, `${JSON.stringify({ withResults: suggested, source: "llm" }, null, 2)}
60286
60489
  `, "utf8");
60287
60490
  return { withResults: suggested, noResults };
60288
60491
  }
@@ -61537,7 +61740,7 @@ async function e2eCommand(opts) {
61537
61740
  generatedAt: new Date().toISOString(),
61538
61741
  durationMs
61539
61742
  });
61540
- writeFileSync15(paths.reportHtml, html, "utf8");
61743
+ writeFileSync16(paths.reportHtml, html, "utf8");
61541
61744
  writeRunReportJson(paths.runDir, {
61542
61745
  runId,
61543
61746
  mode: "e2e",
@@ -61742,7 +61945,7 @@ ${JSON.stringify(checks.map((c) => ({ name: c.name, status: c.status, summary: c
61742
61945
  }
61743
61946
 
61744
61947
  // src/commands/extract.ts
61745
- import { mkdirSync as mkdirSync13 } from "node:fs";
61948
+ import { mkdirSync as mkdirSync14 } from "node:fs";
61746
61949
  import { resolve as resolve5 } from "node:path";
61747
61950
  import chalk17 from "chalk";
61748
61951
 
@@ -62074,20 +62277,20 @@ function collectCandidatesInPage() {
62074
62277
  }
62075
62278
 
62076
62279
  // src/extract/exporters/json.ts
62077
- import { writeFileSync as writeFileSync16 } from "node:fs";
62078
- import { join as join20 } from "node:path";
62280
+ import { writeFileSync as writeFileSync17 } from "node:fs";
62281
+ import { join as join21 } from "node:path";
62079
62282
  var jsonExporter = {
62080
62283
  name: "json",
62081
62284
  async export(bundle, outDir) {
62082
- const path = join20(outDir, "manifest.json");
62083
- writeFileSync16(path, `${JSON.stringify(bundle, null, 2)}
62285
+ const path = join21(outDir, "manifest.json");
62286
+ writeFileSync17(path, `${JSON.stringify(bundle, null, 2)}
62084
62287
  `, "utf8");
62085
62288
  }
62086
62289
  };
62087
62290
 
62088
62291
  // src/extract/exporters/markdown.ts
62089
- import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync17 } from "node:fs";
62090
- import { join as join21 } from "node:path";
62292
+ import { mkdirSync as mkdirSync11, writeFileSync as writeFileSync18 } from "node:fs";
62293
+ import { join as join22 } from "node:path";
62091
62294
 
62092
62295
  // src/extract/naming.ts
62093
62296
  function componentDirName(role, index) {
@@ -62101,13 +62304,13 @@ var markdownExporter = {
62101
62304
  async export(bundle, outDir) {
62102
62305
  const dirNames = bundle.components.map((c, i) => componentDirName(c.role, i + 1));
62103
62306
  const indexMd = renderIndex(bundle, dirNames);
62104
- writeFileSync17(join21(outDir, "index.md"), indexMd, "utf8");
62307
+ writeFileSync18(join22(outDir, "index.md"), indexMd, "utf8");
62105
62308
  bundle.components.forEach((component, i) => {
62106
62309
  const dirName = dirNames[i];
62107
- const componentDir = join21(outDir, "components", dirName);
62108
- mkdirSync10(componentDir, { recursive: true });
62310
+ const componentDir = join22(outDir, "components", dirName);
62311
+ mkdirSync11(componentDir, { recursive: true });
62109
62312
  const readme = renderComponentReadme(bundle, component);
62110
- writeFileSync17(join21(componentDir, "README.md"), readme, "utf8");
62313
+ writeFileSync18(join22(componentDir, "README.md"), readme, "utf8");
62111
62314
  });
62112
62315
  }
62113
62316
  };
@@ -62214,7 +62417,7 @@ function truncateHtml(html, max) {
62214
62417
  }
62215
62418
 
62216
62419
  // src/extract/extract-component.ts
62217
- import { mkdirSync as mkdirSync11, writeFileSync as writeFileSync18 } from "node:fs";
62420
+ import { mkdirSync as mkdirSync12, writeFileSync as writeFileSync19 } from "node:fs";
62218
62421
 
62219
62422
  // src/engine/section-capture.ts
62220
62423
  init_esm10();
@@ -62478,7 +62681,7 @@ async function isDetachedFromScroll(loc) {
62478
62681
  // src/extract/extract-component.ts
62479
62682
  var LINK_CAP = 30;
62480
62683
  async function extractComponent(page, component, opts) {
62481
- mkdirSync11(opts.outDir, { recursive: true });
62684
+ mkdirSync12(opts.outDir, { recursive: true });
62482
62685
  const artifacts = await captureSectionArtifacts(page, {
62483
62686
  selector: component.selector,
62484
62687
  wantHtml: true,
@@ -62499,8 +62702,8 @@ async function extractComponent(page, component, opts) {
62499
62702
  links: capLinks(links, LINK_CAP),
62500
62703
  textContent
62501
62704
  };
62502
- writeFileSync18(`${opts.outDir}/component.html`, extracted.html, "utf8");
62503
- writeFileSync18(`${opts.outDir}/styles.json`, `${JSON.stringify(computedStyles ?? {}, null, 2)}
62705
+ writeFileSync19(`${opts.outDir}/component.html`, extracted.html, "utf8");
62706
+ writeFileSync19(`${opts.outDir}/styles.json`, `${JSON.stringify(computedStyles ?? {}, null, 2)}
62504
62707
  `, "utf8");
62505
62708
  return extracted;
62506
62709
  }
@@ -62926,7 +63129,7 @@ function viewportDeltas(primary, others) {
62926
63129
  }
62927
63130
 
62928
63131
  // src/commands/section.ts
62929
- import { mkdirSync as mkdirSync12 } from "node:fs";
63132
+ import { mkdirSync as mkdirSync13 } from "node:fs";
62930
63133
  import { resolve as resolve4 } from "node:path";
62931
63134
  import chalk16 from "chalk";
62932
63135
  import * as diff from "diff";
@@ -63051,8 +63254,8 @@ function analyzeHeatmapBuffer(data, width, height, opts = {}) {
63051
63254
  }
63052
63255
 
63053
63256
  // src/diff/section-bundle.ts
63054
- import { writeFileSync as writeFileSync19 } from "node:fs";
63055
- import { basename as basename3, dirname as dirname5, join as join22, relative as relative3 } from "node:path";
63257
+ import { writeFileSync as writeFileSync20 } from "node:fs";
63258
+ import { basename as basename3, dirname as dirname5, join as join23, relative as relative4 } from "node:path";
63056
63259
  function buildStyleDeltas(input) {
63057
63260
  const cs = input.computedStyles;
63058
63261
  if (!cs)
@@ -63096,12 +63299,12 @@ function assembleSectionDiffBundle(input) {
63096
63299
  boundingRects: styleResultsToRects(input.computedStyles),
63097
63300
  styleDeltas
63098
63301
  };
63099
- const jsonPath = join22(input.outDir, `${input.filePrefix}-bundle.json`);
63100
- writeFileSync19(jsonPath, `${JSON.stringify(json, mapReplacer, 2)}
63302
+ const jsonPath = join23(input.outDir, `${input.filePrefix}-bundle.json`);
63303
+ writeFileSync20(jsonPath, `${JSON.stringify(json, mapReplacer, 2)}
63101
63304
  `, "utf8");
63102
63305
  const markdown = renderMarkdownBundle(input, styleDeltas);
63103
- const markdownPath = join22(input.outDir, `${input.filePrefix}-prompt.md`);
63104
- writeFileSync19(markdownPath, markdown, "utf8");
63306
+ const markdownPath = join23(input.outDir, `${input.filePrefix}-prompt.md`);
63307
+ writeFileSync20(markdownPath, markdown, "utf8");
63105
63308
  const summary = oneLineSummary(input, styleDeltas);
63106
63309
  return { jsonPath, markdownPath, summary };
63107
63310
  }
@@ -63251,7 +63454,7 @@ function relativeOrAbs(outDir, absPath) {
63251
63454
  try {
63252
63455
  if (dirname5(absPath) === outDir)
63253
63456
  return basename3(absPath);
63254
- return relative3(outDir, absPath);
63457
+ return relative4(outDir, absPath);
63255
63458
  } catch {
63256
63459
  return absPath;
63257
63460
  }
@@ -63280,9 +63483,334 @@ function capDiff(diff, maxLines) {
63280
63483
  `);
63281
63484
  }
63282
63485
 
63486
+ // src/engine/ab-detect.ts
63487
+ import { createHash as createHash3 } from "node:crypto";
63488
+
63489
+ // src/engine/box-tree.ts
63490
+ var BOX_TREE_KEYS = [
63491
+ "display",
63492
+ "position",
63493
+ "visibility",
63494
+ "box-sizing",
63495
+ "margin-top",
63496
+ "margin-right",
63497
+ "margin-bottom",
63498
+ "margin-left",
63499
+ "padding-top",
63500
+ "padding-right",
63501
+ "padding-bottom",
63502
+ "padding-left",
63503
+ "border-top-width",
63504
+ "border-right-width",
63505
+ "border-bottom-width",
63506
+ "border-left-width",
63507
+ "border-top-left-radius",
63508
+ "border-top-right-radius",
63509
+ "border-bottom-right-radius",
63510
+ "border-bottom-left-radius",
63511
+ "flex-direction",
63512
+ "flex-wrap",
63513
+ "justify-content",
63514
+ "align-items",
63515
+ "align-self",
63516
+ "gap",
63517
+ "row-gap",
63518
+ "column-gap",
63519
+ "grid-template-columns",
63520
+ "grid-template-rows",
63521
+ "font-size",
63522
+ "font-weight",
63523
+ "line-height",
63524
+ "letter-spacing",
63525
+ "text-align",
63526
+ "text-transform",
63527
+ "white-space",
63528
+ "color",
63529
+ "background-color",
63530
+ "object-fit",
63531
+ "object-position",
63532
+ "overflow",
63533
+ "opacity",
63534
+ "z-index",
63535
+ "transform"
63536
+ ];
63537
+ var LABEL_ATTRS = ["data-section", "data-testid", "data-fs-section", "data-manifest-key", "id"];
63538
+ var GENERATED_ID = /^(?::[rR][0-9a-zA-Z]*:|_[rR]_[0-9a-zA-Z_]*_)$/;
63539
+ var NON_RENDERED = ["script", "style", "link", "meta", "template", "noscript", "title", "head"];
63540
+ async function readBoxTree(page, selector, opts = {}) {
63541
+ const maxDepth = opts.maxDepth ?? 12;
63542
+ const maxNodes = opts.maxNodes ?? 400;
63543
+ const skipZeroArea = opts.skipZeroArea ?? false;
63544
+ const keys = BOX_TREE_KEYS;
63545
+ let exists = false;
63546
+ try {
63547
+ exists = await page.locator(selector).count() > 0;
63548
+ } catch (err) {
63549
+ return { found: false, error: `seletor inválido: ${err.message}` };
63550
+ }
63551
+ if (!exists) {
63552
+ return { found: false, error: `seletor '${selector}' não casou nenhum elemento` };
63553
+ }
63554
+ let got;
63555
+ try {
63556
+ got = await page.evaluate(({ sel, keys, maxDepth, maxNodes, skipZeroArea, labelAttrs, skipTags, generatedIdPattern }) => {
63557
+ try {
63558
+ const root = document.querySelector(sel);
63559
+ if (!root || !(root instanceof HTMLElement)) {
63560
+ return { ok: false, reason: "querySelector retornou null ou non-HTMLElement" };
63561
+ }
63562
+ const origin = root.getBoundingClientRect();
63563
+ const nodes = [];
63564
+ let truncated = false;
63565
+ const generatedId = new RegExp(generatedIdPattern);
63566
+ const labelOf = (el) => {
63567
+ for (const a of labelAttrs) {
63568
+ const v = el.getAttribute(a);
63569
+ if (!v)
63570
+ continue;
63571
+ if (a === "id" && generatedId.test(v))
63572
+ continue;
63573
+ return v;
63574
+ }
63575
+ return null;
63576
+ };
63577
+ const skip = new Set(skipTags);
63578
+ const walk = (el, path, depth) => {
63579
+ if (nodes.length >= maxNodes) {
63580
+ truncated = true;
63581
+ return;
63582
+ }
63583
+ const r = el.getBoundingClientRect();
63584
+ const zero = r.width === 0 && r.height === 0;
63585
+ if (!(skipZeroArea && zero)) {
63586
+ const cs = window.getComputedStyle(el);
63587
+ const styles = {};
63588
+ for (const k of keys)
63589
+ styles[k] = cs.getPropertyValue(k) || "";
63590
+ const raw = (el.textContent ?? "").replace(/\s+/g, " ").trim();
63591
+ nodes.push({
63592
+ key: path,
63593
+ tag: el.tagName.toLowerCase(),
63594
+ depth,
63595
+ label: labelOf(el),
63596
+ rect: {
63597
+ x: Math.round((r.x - origin.x) * 100) / 100,
63598
+ y: Math.round((r.y - origin.y) * 100) / 100,
63599
+ width: Math.round(r.width * 100) / 100,
63600
+ height: Math.round(r.height * 100) / 100
63601
+ },
63602
+ styles,
63603
+ text: raw ? raw.slice(0, 40) : null
63604
+ });
63605
+ }
63606
+ if (depth >= maxDepth) {
63607
+ if (el.children.length > 0)
63608
+ truncated = true;
63609
+ return;
63610
+ }
63611
+ const perTag = {};
63612
+ for (const child of Array.from(el.children)) {
63613
+ const t = child.tagName.toLowerCase();
63614
+ if (skip.has(t))
63615
+ continue;
63616
+ const i = perTag[t] ?? 0;
63617
+ perTag[t] = i + 1;
63618
+ walk(child, `${path}>${t}[${i}]`, depth + 1);
63619
+ }
63620
+ };
63621
+ walk(root, root.tagName.toLowerCase(), 0);
63622
+ return { ok: true, nodes, truncated };
63623
+ } catch (err) {
63624
+ return {
63625
+ ok: false,
63626
+ reason: `walk falhou em '${sel}': ${err.message ?? "unknown"}`
63627
+ };
63628
+ }
63629
+ }, {
63630
+ sel: selector,
63631
+ keys,
63632
+ maxDepth,
63633
+ maxNodes,
63634
+ skipZeroArea,
63635
+ labelAttrs: LABEL_ATTRS,
63636
+ skipTags: NON_RENDERED,
63637
+ generatedIdPattern: GENERATED_ID.source
63638
+ });
63639
+ } catch (err) {
63640
+ return {
63641
+ found: false,
63642
+ error: `falha no page.evaluate de '${selector}': ${err.message ?? "unknown"}. Se o seletor usa sintaxe Playwright-only (text=..., :visible, xpath=...), use um seletor CSS puro.`
63643
+ };
63644
+ }
63645
+ if (!got.ok)
63646
+ return { found: false, error: got.reason };
63647
+ return { found: true, nodes: got.nodes, truncated: got.truncated };
63648
+ }
63649
+
63650
+ // src/engine/ab-detect.ts
63651
+ var EXPERIMENT_NAME = /(?:^|[^a-z])ab(?:[^a-z]|test|$)|split|optimi[sz]|experiment|variant|vwo|kameleoon/i;
63652
+ var AB_SDK_GLOBALS = [
63653
+ "optimizely",
63654
+ "VWO",
63655
+ "_vwo_code",
63656
+ "_vis_opt_queue",
63657
+ "google_optimize",
63658
+ "ABTasty",
63659
+ "Kameleoon"
63660
+ ];
63661
+ function isExperimentName(name) {
63662
+ return EXPERIMENT_NAME.test(name.replace(/([a-z])([A-Z])/g, "$1_$2"));
63663
+ }
63664
+ function extractSignals(raw) {
63665
+ const out = new Set;
63666
+ for (const c of raw.cookies)
63667
+ if (isExperimentName(c.name))
63668
+ out.add(`cookie:${c.name}=${c.value}`);
63669
+ for (const k of raw.storage)
63670
+ if (isExperimentName(k.name))
63671
+ out.add(`storage:${k.name}=${k.value.slice(0, 40)}`);
63672
+ for (const [h, v] of Object.entries(raw.headers))
63673
+ if (isExperimentName(h))
63674
+ out.add(`header:${h}=${v}`);
63675
+ for (const a of raw.attrs)
63676
+ out.add(`attr:${a}`);
63677
+ for (const g of raw.globals)
63678
+ out.add(`global:${g}`);
63679
+ return [...out].sort();
63680
+ }
63681
+ function boxTreeSignature(nodes) {
63682
+ const h = createHash3("sha256");
63683
+ for (const n of nodes) {
63684
+ const { transform: _t, opacity: _o, ...styles } = n.styles;
63685
+ h.update(`${n.key}|${n.tag}|${JSON.stringify(styles)}
63686
+ `);
63687
+ }
63688
+ return h.digest("hex").slice(0, 12);
63689
+ }
63690
+ function groupVariants(url, selector, sessions) {
63691
+ const loaded = sessions.filter((s) => s.signature !== null);
63692
+ const signals = [...new Set(loaded.flatMap((s) => s.signals))].sort();
63693
+ const target = selector ?? "the page";
63694
+ const base = { url, selector, loaded: loaded.length, sessions, signals };
63695
+ if (loaded.length < 2) {
63696
+ return {
63697
+ ...base,
63698
+ verdict: "inconclusive",
63699
+ variants: [],
63700
+ message: `inconclusive: only ${loaded.length} of ${sessions.length} sessions rendered ${target} — nothing to compare`
63701
+ };
63702
+ }
63703
+ const inAll = (sig) => loaded.every((s) => s.signals.includes(sig));
63704
+ const bySig = new Map;
63705
+ for (const s of loaded)
63706
+ bySig.set(s.signature, [...bySig.get(s.signature) ?? [], s]);
63707
+ const variants = [...bySig.entries()].map(([signature, group], i) => ({
63708
+ id: String.fromCharCode(65 + i),
63709
+ signature,
63710
+ sessions: group.map((s) => s.index),
63711
+ signals: (group[0]?.signals ?? []).filter((sig) => !inAll(sig) && group.every((s) => s.signals.includes(sig)))
63712
+ }));
63713
+ const signalNote = signals.length ? ` (signals: ${signals.join(", ")})` : "";
63714
+ if (variants.length === 1) {
63715
+ const differing = signals.filter((sig) => !inAll(sig));
63716
+ if (differing.length) {
63717
+ return {
63718
+ ...base,
63719
+ verdict: "possible",
63720
+ variants,
63721
+ message: `possible A/B on ${target}: structure matches across ${loaded.length} sessions but signals differ: ${differing.join(", ")} — the variants may differ only in behaviour (hover, transition); pin one with --prod-cookie and compare`
63722
+ };
63723
+ }
63724
+ return {
63725
+ ...base,
63726
+ verdict: "none",
63727
+ variants,
63728
+ message: `no A/B detected on ${target}: ${loaded.length} sessions rendered the same structure${signals.length ? ` with the same experiment signals${signalNote}` : ""}`
63729
+ };
63730
+ }
63731
+ const seen = variants.map((v) => `${v.id} (sessions ${v.sessions.join(",")}${v.signals.length ? `; ${v.signals.join(", ")}` : ""})`).join(", ");
63732
+ return {
63733
+ ...base,
63734
+ verdict: "ab-detected",
63735
+ variants,
63736
+ message: `prod is A/B-testing ${target}: variants seen = [${seen}]${signalNote}`
63737
+ };
63738
+ }
63739
+ function parseCookieFlags(values, pageUrl) {
63740
+ if (!values?.length)
63741
+ return [];
63742
+ const domain = new URL(pageUrl).hostname;
63743
+ return values.map((v) => {
63744
+ const eq = v.indexOf("=");
63745
+ if (eq <= 0)
63746
+ throw new Error(`--prod-cookie expects name=value, got "${v}"`);
63747
+ return { name: v.slice(0, eq).trim(), value: v.slice(eq + 1), domain, path: "/" };
63748
+ });
63749
+ }
63750
+ async function readAbSession(browser, index, opts) {
63751
+ const ctx = await newContext(browser, { viewport: opts.viewport, hideScrollbars: true });
63752
+ try {
63753
+ const page = await ctx.newPage();
63754
+ const resp = await page.goto(opts.url, { waitUntil: "domcontentloaded", timeout: 30000 });
63755
+ await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
63756
+ return;
63757
+ });
63758
+ await page.waitForTimeout(opts.waitMs);
63759
+ await stabilizeCarousels(page);
63760
+ const tree = await readBoxTree(page, opts.selector ?? "body");
63761
+ const inPage = await page.evaluate(({ sel, globals, pattern }) => {
63762
+ const re = new RegExp(pattern, "i");
63763
+ const named = (n) => re.test(n.replace(/([a-z])([A-Z])/g, "$1_$2"));
63764
+ const storage = [];
63765
+ for (const s of [localStorage, sessionStorage])
63766
+ for (let i = 0;i < s.length; i++) {
63767
+ const name = s.key(i) ?? "";
63768
+ storage.push({ name, value: s.getItem(name) ?? "" });
63769
+ }
63770
+ const attrs = new Set;
63771
+ const root = (sel ? document.querySelector(sel) : null) ?? document.body;
63772
+ for (const el of [root, ...Array.from(root.querySelectorAll("*"))]) {
63773
+ if (attrs.size >= 20)
63774
+ break;
63775
+ for (const a of Array.from(el.attributes)) {
63776
+ if (a.name === "class") {
63777
+ for (const t of a.value.split(/\s+/))
63778
+ if (t && named(t))
63779
+ attrs.add(`class~=${t}`);
63780
+ } else if (named(a.name.replace(/^data-/, "")))
63781
+ attrs.add(`${a.name}=${a.value.slice(0, 40)}`);
63782
+ }
63783
+ }
63784
+ const w = window;
63785
+ return {
63786
+ storage,
63787
+ attrs: [...attrs],
63788
+ globals: globals.filter((g) => w[g] !== undefined)
63789
+ };
63790
+ }, { sel: opts.selector, globals: AB_SDK_GLOBALS, pattern: EXPERIMENT_NAME.source });
63791
+ const raw = {
63792
+ cookies: await ctx.cookies(),
63793
+ headers: resp?.headers() ?? {},
63794
+ ...inPage
63795
+ };
63796
+ return {
63797
+ index,
63798
+ signature: tree.found ? boxTreeSignature(tree.nodes) : null,
63799
+ signals: extractSignals(raw),
63800
+ ...tree.found ? {} : { error: tree.error }
63801
+ };
63802
+ } catch (err) {
63803
+ return { index, signature: null, signals: [], error: err.message };
63804
+ } finally {
63805
+ await ctx.close().catch(() => {
63806
+ return;
63807
+ });
63808
+ }
63809
+ }
63810
+
63283
63811
  // src/migrate/plan.ts
63284
- import { existsSync as existsSync14, readFileSync as readFileSync20, writeFileSync as writeFileSync20 } from "node:fs";
63285
- import { join as join23 } from "node:path";
63812
+ import { existsSync as existsSync14, readFileSync as readFileSync20, writeFileSync as writeFileSync21 } from "node:fs";
63813
+ import { join as join24 } from "node:path";
63286
63814
  function dedupe(names) {
63287
63815
  return [...new Set(names)];
63288
63816
  }
@@ -63407,13 +63935,13 @@ function mergePlanDecisions(fresh, previous) {
63407
63935
  var PLAN_FILE = "migration-plan.json";
63408
63936
  var SETTLED = new Set(["done", "as-is", "upgrade", "skipped", "vanished"]);
63409
63937
  function loadPlan(dir) {
63410
- const p = join23(dir, PLAN_FILE);
63938
+ const p = join24(dir, PLAN_FILE);
63411
63939
  if (!existsSync14(p))
63412
63940
  return null;
63413
63941
  return JSON.parse(readFileSync20(p, "utf8"));
63414
63942
  }
63415
63943
  function savePlan(dir, plan) {
63416
- writeFileSync20(join23(dir, PLAN_FILE), `${JSON.stringify(plan, null, 2)}
63944
+ writeFileSync21(join24(dir, PLAN_FILE), `${JSON.stringify(plan, null, 2)}
63417
63945
  `, "utf8");
63418
63946
  }
63419
63947
  function setComponentStatus(plan, name, status, opts = {}) {
@@ -64201,167 +64729,6 @@ function formatBoxTreeDiff(diff, opts = {}) {
64201
64729
  `);
64202
64730
  }
64203
64731
 
64204
- // src/engine/box-tree.ts
64205
- var BOX_TREE_KEYS = [
64206
- "display",
64207
- "position",
64208
- "visibility",
64209
- "box-sizing",
64210
- "margin-top",
64211
- "margin-right",
64212
- "margin-bottom",
64213
- "margin-left",
64214
- "padding-top",
64215
- "padding-right",
64216
- "padding-bottom",
64217
- "padding-left",
64218
- "border-top-width",
64219
- "border-right-width",
64220
- "border-bottom-width",
64221
- "border-left-width",
64222
- "border-top-left-radius",
64223
- "border-top-right-radius",
64224
- "border-bottom-right-radius",
64225
- "border-bottom-left-radius",
64226
- "flex-direction",
64227
- "flex-wrap",
64228
- "justify-content",
64229
- "align-items",
64230
- "align-self",
64231
- "gap",
64232
- "row-gap",
64233
- "column-gap",
64234
- "grid-template-columns",
64235
- "grid-template-rows",
64236
- "font-size",
64237
- "font-weight",
64238
- "line-height",
64239
- "letter-spacing",
64240
- "text-align",
64241
- "text-transform",
64242
- "white-space",
64243
- "color",
64244
- "background-color",
64245
- "object-fit",
64246
- "object-position",
64247
- "overflow",
64248
- "opacity",
64249
- "z-index",
64250
- "transform"
64251
- ];
64252
- var LABEL_ATTRS = ["data-section", "data-testid", "data-fs-section", "data-manifest-key", "id"];
64253
- var GENERATED_ID = /^(?::[rR][0-9a-zA-Z]*:|_[rR]_[0-9a-zA-Z_]*_)$/;
64254
- var NON_RENDERED = ["script", "style", "link", "meta", "template", "noscript", "title", "head"];
64255
- async function readBoxTree(page, selector, opts = {}) {
64256
- const maxDepth = opts.maxDepth ?? 12;
64257
- const maxNodes = opts.maxNodes ?? 400;
64258
- const skipZeroArea = opts.skipZeroArea ?? false;
64259
- const keys = BOX_TREE_KEYS;
64260
- let exists = false;
64261
- try {
64262
- exists = await page.locator(selector).count() > 0;
64263
- } catch (err) {
64264
- return { found: false, error: `seletor inválido: ${err.message}` };
64265
- }
64266
- if (!exists) {
64267
- return { found: false, error: `seletor '${selector}' não casou nenhum elemento` };
64268
- }
64269
- let got;
64270
- try {
64271
- got = await page.evaluate(({ sel, keys, maxDepth, maxNodes, skipZeroArea, labelAttrs, skipTags, generatedIdPattern }) => {
64272
- try {
64273
- const root = document.querySelector(sel);
64274
- if (!root || !(root instanceof HTMLElement)) {
64275
- return { ok: false, reason: "querySelector retornou null ou non-HTMLElement" };
64276
- }
64277
- const origin = root.getBoundingClientRect();
64278
- const nodes = [];
64279
- let truncated = false;
64280
- const generatedId = new RegExp(generatedIdPattern);
64281
- const labelOf = (el) => {
64282
- for (const a of labelAttrs) {
64283
- const v = el.getAttribute(a);
64284
- if (!v)
64285
- continue;
64286
- if (a === "id" && generatedId.test(v))
64287
- continue;
64288
- return v;
64289
- }
64290
- return null;
64291
- };
64292
- const skip = new Set(skipTags);
64293
- const walk = (el, path, depth) => {
64294
- if (nodes.length >= maxNodes) {
64295
- truncated = true;
64296
- return;
64297
- }
64298
- const r = el.getBoundingClientRect();
64299
- const zero = r.width === 0 && r.height === 0;
64300
- if (!(skipZeroArea && zero)) {
64301
- const cs = window.getComputedStyle(el);
64302
- const styles = {};
64303
- for (const k of keys)
64304
- styles[k] = cs.getPropertyValue(k) || "";
64305
- const raw = (el.textContent ?? "").replace(/\s+/g, " ").trim();
64306
- nodes.push({
64307
- key: path,
64308
- tag: el.tagName.toLowerCase(),
64309
- depth,
64310
- label: labelOf(el),
64311
- rect: {
64312
- x: Math.round((r.x - origin.x) * 100) / 100,
64313
- y: Math.round((r.y - origin.y) * 100) / 100,
64314
- width: Math.round(r.width * 100) / 100,
64315
- height: Math.round(r.height * 100) / 100
64316
- },
64317
- styles,
64318
- text: raw ? raw.slice(0, 40) : null
64319
- });
64320
- }
64321
- if (depth >= maxDepth) {
64322
- if (el.children.length > 0)
64323
- truncated = true;
64324
- return;
64325
- }
64326
- const perTag = {};
64327
- for (const child of Array.from(el.children)) {
64328
- const t = child.tagName.toLowerCase();
64329
- if (skip.has(t))
64330
- continue;
64331
- const i = perTag[t] ?? 0;
64332
- perTag[t] = i + 1;
64333
- walk(child, `${path}>${t}[${i}]`, depth + 1);
64334
- }
64335
- };
64336
- walk(root, root.tagName.toLowerCase(), 0);
64337
- return { ok: true, nodes, truncated };
64338
- } catch (err) {
64339
- return {
64340
- ok: false,
64341
- reason: `walk falhou em '${sel}': ${err.message ?? "unknown"}`
64342
- };
64343
- }
64344
- }, {
64345
- sel: selector,
64346
- keys,
64347
- maxDepth,
64348
- maxNodes,
64349
- skipZeroArea,
64350
- labelAttrs: LABEL_ATTRS,
64351
- skipTags: NON_RENDERED,
64352
- generatedIdPattern: GENERATED_ID.source
64353
- });
64354
- } catch (err) {
64355
- return {
64356
- found: false,
64357
- error: `falha no page.evaluate de '${selector}': ${err.message ?? "unknown"}. Se o seletor usa sintaxe Playwright-only (text=..., :visible, xpath=...), use um seletor CSS puro.`
64358
- };
64359
- }
64360
- if (!got.ok)
64361
- return { found: false, error: got.reason };
64362
- return { found: true, nodes: got.nodes, truncated: got.truncated };
64363
- }
64364
-
64365
64732
  // src/commands/section.ts
64366
64733
  async function sectionCommand(opts) {
64367
64734
  const viewport = parseViewport3(opts.viewport);
@@ -64396,7 +64763,7 @@ async function sectionCommand(opts) {
64396
64763
  };
64397
64764
  if (want.heatmap)
64398
64765
  want.screenshot = true;
64399
- mkdirSync12(opts.outDir, { recursive: true });
64766
+ mkdirSync13(opts.outDir, { recursive: true });
64400
64767
  const hash = hashSelector(opts.selector);
64401
64768
  const filePrefix = `section-${hash}-${viewport}`;
64402
64769
  const screenshotPaths = {
@@ -64413,6 +64780,7 @@ async function sectionCommand(opts) {
64413
64780
  gatherSide(browser, {
64414
64781
  url: opts.prod,
64415
64782
  storageState: opts.prodStorageState,
64783
+ cookies: parseCookieFlags(opts.prodCookies, opts.prod),
64416
64784
  viewport,
64417
64785
  viewportSize: opts.viewportSize,
64418
64786
  waitMs,
@@ -64530,6 +64898,7 @@ async function gatherSide(browser, opts) {
64530
64898
  viewport: opts.viewport,
64531
64899
  ...opts.viewportSize ? { viewportSize: opts.viewportSize } : {},
64532
64900
  ...opts.storageState ? { storageState: opts.storageState } : {},
64901
+ cookies: opts.cookies,
64533
64902
  hideScrollbars: true
64534
64903
  });
64535
64904
  const page = await ctx.newPage();
@@ -64910,7 +65279,7 @@ async function extractCommand(opts) {
64910
65279
  const timestamp = new Date().toISOString();
64911
65280
  const runDirTimestamp = timestamp.replace(/[:.]/g, "-");
64912
65281
  const runDir = resolve5(opts.outDir, host, runDirTimestamp);
64913
- mkdirSync13(runDir, { recursive: true });
65282
+ mkdirSync14(runDir, { recursive: true });
64914
65283
  let pageTokens;
64915
65284
  try {
64916
65285
  pageTokens = parsePageList(opts.pages, { tokens: PLP_PDP_AUTO_TOKENS, fallback: ["/"] });
@@ -65368,8 +65737,8 @@ function formatPatch(patch) {
65368
65737
  }
65369
65738
 
65370
65739
  // src/commands/journey.ts
65371
- import { writeFileSync as writeFileSync21 } from "node:fs";
65372
- import { join as join24 } from "node:path";
65740
+ import { writeFileSync as writeFileSync22 } from "node:fs";
65741
+ import { join as join25 } from "node:path";
65373
65742
  import chalk19 from "chalk";
65374
65743
  import ora7 from "ora";
65375
65744
  init_client();
@@ -65439,7 +65808,7 @@ async function journeyCommand(opts) {
65439
65808
  };
65440
65809
  async function runOneSide(browserInstance, viewport, side) {
65441
65810
  const baseUrl = side === "prod" ? opts.prod : opts.cand;
65442
- const tracePath = join24(paths.tracesDir, `${viewport}-${side}.zip`);
65811
+ const tracePath = join25(paths.tracesDir, `${viewport}-${side}.zip`);
65443
65812
  const ctx = await newContext(browserInstance, {
65444
65813
  viewport,
65445
65814
  tracesDir: paths.tracesDir,
@@ -65531,7 +65900,7 @@ async function journeyCommand(opts) {
65531
65900
  if (opts.github)
65532
65901
  emitGithubAnnotations(failures);
65533
65902
  if (opts.junit) {
65534
- writeFileSync21(opts.junit, buildJUnit(rows, failures), "utf8");
65903
+ writeFileSync22(opts.junit, buildJUnit(rows, failures), "utf8");
65535
65904
  if (!opts.json)
65536
65905
  console.log(chalk19.dim(` → JUnit XML: ${opts.junit}`));
65537
65906
  }
@@ -66230,7 +66599,7 @@ function printSummary7(r) {
66230
66599
 
66231
66600
  // src/commands/migrate.ts
66232
66601
  import { existsSync as existsSync20, mkdirSync as mkdirSync16, readFileSync as readFileSync26, rmSync, writeFileSync as writeFileSync26 } from "node:fs";
66233
- import { relative as relative4, resolve as resolve7 } from "node:path";
66602
+ import { relative as relative5, resolve as resolve7 } from "node:path";
66234
66603
  import chalk23 from "chalk";
66235
66604
  import open from "open";
66236
66605
 
@@ -66298,12 +66667,12 @@ async function nodeFetchText(url) {
66298
66667
  }
66299
66668
 
66300
66669
  // src/migrate/exporters/json.ts
66301
- import { writeFileSync as writeFileSync22 } from "node:fs";
66302
- import { join as join25 } from "node:path";
66670
+ import { writeFileSync as writeFileSync23 } from "node:fs";
66671
+ import { join as join26 } from "node:path";
66303
66672
  var jsonExporter2 = {
66304
66673
  name: "json",
66305
66674
  async export(bundle, outDir) {
66306
- writeFileSync22(join25(outDir, "manifest.json"), `${JSON.stringify(bundle, null, 2)}
66675
+ writeFileSync23(join26(outDir, "manifest.json"), `${JSON.stringify(bundle, null, 2)}
66307
66676
  `, "utf8");
66308
66677
  }
66309
66678
  };
@@ -66311,136 +66680,6 @@ var jsonExporter2 = {
66311
66680
  // src/migrate/exporters/markdown.ts
66312
66681
  import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync24 } from "node:fs";
66313
66682
  import { join as join27 } from "node:path";
66314
-
66315
- // src/migrate/vtex/content-assets.ts
66316
- import { mkdirSync as mkdirSync14, writeFileSync as writeFileSync23 } from "node:fs";
66317
- import { join as join26 } from "node:path";
66318
- var MAX_IMAGES = 150;
66319
- var IMG_EXT = /\.(jpe?g|png|webp|gif|svg|avif)(\?|#|$)/i;
66320
- var VTEX_ASSET = /vtexassets\.com|vteximg\.com\.br|\/arquivos\/(ids|assets)\//i;
66321
- function isImageUrl(s) {
66322
- if (typeof s !== "string")
66323
- return false;
66324
- const v = s.trim();
66325
- if (!/^(https?:)?\/\//i.test(v))
66326
- return false;
66327
- return IMG_EXT.test(v) || VTEX_ASSET.test(v);
66328
- }
66329
- function isImageRef(s) {
66330
- if (typeof s !== "string")
66331
- return false;
66332
- const v = s.trim();
66333
- if (isImageUrl(v))
66334
- return true;
66335
- return v.startsWith("/") && !v.startsWith("//") && (IMG_EXT.test(v) || VTEX_ASSET.test(v) || v.startsWith("/img/"));
66336
- }
66337
- function resolveRef(ref, baseUrl) {
66338
- const v = ref.trim();
66339
- try {
66340
- if (v.startsWith("//"))
66341
- return `https:${v}`;
66342
- return new URL(v, baseUrl).toString();
66343
- } catch {
66344
- return null;
66345
- }
66346
- }
66347
- function collectImageRefs(blocks, baseUrl) {
66348
- const out = {};
66349
- const walk = (v) => {
66350
- if (typeof v === "string") {
66351
- const s = v.trim();
66352
- if (isImageRef(s) && !(s in out)) {
66353
- const abs = resolveRef(s, baseUrl);
66354
- if (abs)
66355
- out[s] = abs;
66356
- }
66357
- } else if (Array.isArray(v)) {
66358
- for (const x of v)
66359
- walk(x);
66360
- } else if (v && typeof v === "object") {
66361
- for (const x of Object.values(v))
66362
- walk(x);
66363
- }
66364
- };
66365
- for (const b of blocks)
66366
- if (b.props)
66367
- walk(b.props);
66368
- return out;
66369
- }
66370
- function countContentImages(blocks) {
66371
- const urls = new Set;
66372
- const walk = (v) => {
66373
- if (typeof v === "string") {
66374
- if (isImageUrl(v.trim()))
66375
- urls.add(v.trim());
66376
- } else if (Array.isArray(v)) {
66377
- for (const x of v)
66378
- walk(x);
66379
- } else if (v && typeof v === "object") {
66380
- for (const x of Object.values(v))
66381
- walk(x);
66382
- }
66383
- };
66384
- for (const b of blocks)
66385
- if (b.props)
66386
- walk(b.props);
66387
- return urls.size;
66388
- }
66389
- function rewriteBlockUrls(blocks, urlToPath) {
66390
- const replace = (v) => {
66391
- if (typeof v === "string")
66392
- return urlToPath[v.trim()] ?? v;
66393
- if (Array.isArray(v))
66394
- return v.map(replace);
66395
- if (v && typeof v === "object") {
66396
- const out = {};
66397
- for (const [k, val] of Object.entries(v))
66398
- out[k] = replace(val);
66399
- return out;
66400
- }
66401
- return v;
66402
- };
66403
- return blocks.map((b) => ({
66404
- ...b,
66405
- props: b.props ? replace(b.props) : b.props
66406
- }));
66407
- }
66408
- function contentImageName(url, index, used) {
66409
- let base = "img";
66410
- try {
66411
- base = new URL(url, "https://x").pathname.split("/").filter(Boolean).pop() ?? "img";
66412
- } catch {}
66413
- base = base.split("?")[0].replace(/[^\w.-]/g, "_").slice(-60) || "img";
66414
- if (!/\.(jpe?g|png|webp|gif|svg|avif)$/i.test(base))
66415
- base += ".img";
66416
- let name = base;
66417
- if (used.has(name))
66418
- name = `${index}-${base}`;
66419
- used.add(name);
66420
- return name;
66421
- }
66422
- async function downloadContentImages(urls, runDir, fetchBytes) {
66423
- const map = {};
66424
- if (urls.length === 0)
66425
- return { map, downloaded: 0, skipped: 0 };
66426
- const dir = join26(runDir, "assets", "content");
66427
- mkdirSync14(dir, { recursive: true });
66428
- const used = new Set;
66429
- const take = urls.slice(0, MAX_IMAGES);
66430
- let downloaded = 0;
66431
- for (const [i, url] of take.entries()) {
66432
- const got = await fetchBytes(url.startsWith("//") ? `https:${url}` : url);
66433
- if (!got)
66434
- continue;
66435
- const name = contentImageName(url, i, used);
66436
- writeFileSync23(join26(dir, name), got.buf);
66437
- map[url] = `assets/content/${name}`;
66438
- downloaded++;
66439
- }
66440
- return { map, downloaded, skipped: Math.max(0, urls.length - take.length) };
66441
- }
66442
-
66443
- // src/migrate/exporters/markdown.ts
66444
66683
  var markdownExporter2 = {
66445
66684
  name: "markdown",
66446
66685
  async export(bundle, outDir) {
@@ -66457,6 +66696,9 @@ var markdownExporter2 = {
66457
66696
  notes.push(`\`${dirName}\`: HTML truncated to fit the per-component token ceiling`);
66458
66697
  writeFileSync24(join27(componentDir, "README.md"), renderComponentReadme2(bundle.url, component, compact.html), "utf8");
66459
66698
  });
66699
+ const capped = new Set(bundle.components.flatMap((c) => (c.imageFiles ?? []).filter((f) => f.error?.includes("per-run cap")).map((f) => f.url)));
66700
+ if (capped.size)
66701
+ notes.push(`component images: per-run cap reached — ${capped.size} image URL(s) NOT saved locally (see each component's "Not saved" list)`);
66460
66702
  writeFileSync24(join27(outDir, "index.md"), renderIndex2(bundle, notes), "utf8");
66461
66703
  }
66462
66704
  };
@@ -66631,6 +66873,16 @@ ${c.tailwind.join(" ")}
66631
66873
  md("## Assets");
66632
66874
  md("");
66633
66875
  md(`- **Images** (${c.assets.images.length}): ${listOrNone2(c.assets.images)}`);
66876
+ if (c.imageFiles) {
66877
+ const saved = c.imageFiles.filter((f) => f.path);
66878
+ const missing = c.imageFiles.filter((f) => !f.path && !f.skipped);
66879
+ const smaller = c.imageFiles.filter((f) => f.skipped).length;
66880
+ md(`- **Local image copies**: ${saved.length} saved: ${listOrNone2(saved.map((f) => f.path))}`);
66881
+ if (smaller)
66882
+ md(`- **Smaller srcset widths** (${smaller}): listed in capture.json, not downloaded`);
66883
+ if (missing.length)
66884
+ md(`- **Not saved** (${missing.length}): ${listOrNone2(missing.map((f) => `${f.url} — ${f.error}`))}`);
66885
+ }
66634
66886
  md(`- **Fonts**: ${listOrNone2(c.assets.fonts)}`);
66635
66887
  md("");
66636
66888
  if (c.textContent.length) {
@@ -68452,7 +68704,8 @@ async function migrateCommand(opts) {
68452
68704
  baseUrl: opts.url,
68453
68705
  vtexScrape: opts.source ? source.kind === "vtex-io" : true,
68454
68706
  auth,
68455
- extraViewports: opts.componentViewports ? viewports.slice(1) : []
68707
+ extraViewports: opts.componentViewports ? viewports.slice(1) : [],
68708
+ downloadComponentAssets: opts.downloadComponentAssets ?? false
68456
68709
  }));
68457
68710
  writeFileSync26(capturePath, `${JSON.stringify({ pages, components, vtexBlocks, contentMap }, null, 2)}
68458
68711
  `, "utf8");
@@ -68560,9 +68813,25 @@ async function capturePages(browser, viewport, resolvedPages, theme, cfg) {
68560
68813
  const seenGlobalRoles = new Set;
68561
68814
  const blocksByPath = new Map;
68562
68815
  const contentMap = {};
68816
+ const imageBudget = cfg.downloadComponentAssets ? newComponentImageBudget() : null;
68817
+ let imageMs = 0;
68563
68818
  for (const target of resolvedPages) {
68564
68819
  const ctx = await newContext(browser, { viewport, keepMotion: true, ...cfg.auth });
68565
68820
  const page = await ctx.newPage();
68821
+ const fetchImage = async (url) => {
68822
+ const viaPage = await browserFetchBytes(page, url);
68823
+ if (viaPage)
68824
+ return viaPage;
68825
+ try {
68826
+ const res = await ctx.request.get(url, { timeout: 15000 });
68827
+ if (!res.ok())
68828
+ return { error: `HTTP ${res.status()}` };
68829
+ return { buf: await res.body(), contentType: res.headers()["content-type"] ?? null };
68830
+ } catch (e) {
68831
+ return { error: String(e.message ?? e).split(`
68832
+ `)[0] };
68833
+ }
68834
+ };
68566
68835
  const pageComponents = [];
68567
68836
  const capturedHere = [];
68568
68837
  try {
@@ -68595,6 +68864,20 @@ async function capturePages(browser, viewport, resolvedPages, theme, cfg) {
68595
68864
  });
68596
68865
  const interactions = await captureInteractions(page, component.selector);
68597
68866
  const migrated = toMigratedComponent(extracted, interactions, global ? "global" : "page", theme.tokens, repeated);
68867
+ if (imageBudget) {
68868
+ const t0 = Date.now();
68869
+ const imgs = await page.evaluate((sel) => {
68870
+ const root = document.querySelector(sel);
68871
+ return Array.from(root?.querySelectorAll("img") ?? []).map((img) => ({
68872
+ src: img.getAttribute("src"),
68873
+ srcset: img.getAttribute("srcset")
68874
+ }));
68875
+ }, component.selector).catch(() => null);
68876
+ const picks = imgs?.map((i) => pickLargestImage(i.src, i.srcset));
68877
+ const keep = picks ? picks.flatMap((p) => p.keep ? [p.keep] : []) : extracted.assets.images;
68878
+ migrated.imageFiles = await downloadComponentImages([...keep, ...extracted.assets.backgroundImages.flatMap(cssUrls)], page.url(), componentDir, cfg.runDir, fetchImage, imageBudget, picks?.flatMap((p) => p.smaller) ?? []);
68879
+ imageMs += Date.now() - t0;
68880
+ }
68598
68881
  components.push(migrated);
68599
68882
  capturedHere.push({ migrated, componentDir });
68600
68883
  if (!global)
@@ -68629,6 +68912,13 @@ async function capturePages(browser, viewport, resolvedPages, theme, cfg) {
68629
68912
  await captureViewportVariants(browser, target.url, cfg.extraViewports, capturedHere, cfg.runDir, cfg.auth);
68630
68913
  }
68631
68914
  }
68915
+ if (imageBudget) {
68916
+ const unsaved = [...imageBudget.byUrl.values()].filter((f) => !f.path).length;
68917
+ const failed = unsaved - imageBudget.capped;
68918
+ console.log(chalk23.dim(` phase 3 components: ${imageBudget.files} component image(s) saved (${(imageBudget.bytes / 1024 / 1024).toFixed(1)} MB, ${failed} failed) in ${(imageMs / 1000).toFixed(1)}s`));
68919
+ if (imageBudget.capped)
68920
+ console.log(chalk23.yellow(` ⚠ component images: per-run cap hit (${imageBudget.maxFiles} files / ${Math.round(imageBudget.maxBytes / 1024 / 1024)} MB) — ${imageBudget.capped} URL(s) NOT saved, listed per component in imageFiles[].error`));
68921
+ }
68632
68922
  return {
68633
68923
  pages,
68634
68924
  components,
@@ -68712,7 +69002,7 @@ async function captureViewportVariants(browser, url, extraViewports, captured, r
68712
69002
  ...d.absent ? { absent: true } : {},
68713
69003
  ...d.failed ? { failed: d.failed } : {},
68714
69004
  ...d.html !== undefined ? { html: d.html } : {},
68715
- ...d.keepScreenshot ? { screenshotPath: relative4(runDir, resolve7(dir, "screenshot.png")) } : {}
69005
+ ...d.keepScreenshot ? { screenshotPath: relative5(runDir, resolve7(dir, "screenshot.png")) } : {}
68716
69006
  });
68717
69007
  }
68718
69008
  if (variants.length)
@@ -76599,10 +76889,49 @@ async function mcpCommand(opts) {
76599
76889
  return 0;
76600
76890
  }
76601
76891
 
76892
+ // src/commands/ab-detect.ts
76893
+ import chalk36 from "chalk";
76894
+ async function abDetectCommand(opts) {
76895
+ const n = Math.max(2, Number.parseInt(opts.sessions, 10) || 3);
76896
+ const waitMs = Number.parseInt(opts.wait, 10) || 0;
76897
+ const selector = opts.selector ?? null;
76898
+ const browser = await launchBrowser({ headless: true });
76899
+ const sessions = [];
76900
+ try {
76901
+ for (let i = 1;i <= n; i++) {
76902
+ sessions.push(await readAbSession(browser, i, {
76903
+ url: opts.url,
76904
+ selector,
76905
+ viewport: opts.viewport,
76906
+ waitMs
76907
+ }));
76908
+ }
76909
+ } finally {
76910
+ await browser.close().catch(() => {
76911
+ return;
76912
+ });
76913
+ }
76914
+ const report = groupVariants(opts.url, selector, sessions);
76915
+ if (opts.json)
76916
+ console.log(JSON.stringify(report));
76917
+ else {
76918
+ const color = report.verdict === "ab-detected" || report.verdict === "possible" ? chalk36.yellow : report.verdict === "none" ? chalk36.green : chalk36.red;
76919
+ console.log(color(` ${report.message}`));
76920
+ for (const s of sessions) {
76921
+ if (s.signature === null)
76922
+ console.log(chalk36.dim(` session ${s.index}: not read — ${s.error ?? "unknown"}`));
76923
+ }
76924
+ if (report.verdict === "ab-detected" || report.verdict === "possible") {
76925
+ console.log(chalk36.dim(" Pin one variant with --prod-cookie name=value (or --prod-storage-state) on section/heatmap."));
76926
+ }
76927
+ }
76928
+ return report.verdict === "none" ? 0 : report.verdict === "inconclusive" ? 2 : 1;
76929
+ }
76930
+
76602
76931
  // src/commands/heatmap.ts
76603
76932
  import { mkdirSync as mkdirSync23 } from "node:fs";
76604
76933
  import { resolve as resolve19 } from "node:path";
76605
- import chalk36 from "chalk";
76934
+ import chalk37 from "chalk";
76606
76935
 
76607
76936
  // src/diff/hotspot-findings.ts
76608
76937
  var TYPOGRAPHY_PROPS = /^(font-family|font-weight|font-size|font-style|line-height|letter-spacing|text-transform)$/;
@@ -77016,16 +77345,16 @@ function exitCodeFor(verdict) {
77016
77345
  async function heatmapCommand(opts) {
77017
77346
  const specs = parseViewports2(opts.viewports);
77018
77347
  if (typeof specs === "string") {
77019
- console.error(chalk36.red(specs));
77348
+ console.error(chalk37.red(specs));
77020
77349
  return EXIT_INCONCLUSIVE;
77021
77350
  }
77022
77351
  const waitMs = Number.parseInt(opts.wait, 10);
77023
77352
  if (!Number.isFinite(waitMs) || waitMs < 0) {
77024
- console.error(chalk36.red(`--wait inválido: ${opts.wait}`));
77353
+ console.error(chalk37.red(`--wait inválido: ${opts.wait}`));
77025
77354
  return EXIT_INCONCLUSIVE;
77026
77355
  }
77027
77356
  if (!isValidUrl5(opts.prod) || !isValidUrl5(opts.cand)) {
77028
- console.error(chalk36.red("--prod ou --cand inválido"));
77357
+ console.error(chalk37.red("--prod ou --cand inválido"));
77029
77358
  return EXIT_INCONCLUSIVE;
77030
77359
  }
77031
77360
  const selector = opts.selector?.trim() || null;
@@ -77045,6 +77374,7 @@ async function heatmapCommand(opts) {
77045
77374
  candSelector,
77046
77375
  prodStorageState: opts.prodStorageState,
77047
77376
  candStorageState: opts.candStorageState,
77377
+ prodCookies: parseCookieFlags(opts.prodCookies, opts.prod),
77048
77378
  waitMs,
77049
77379
  outDir: opts.outDir,
77050
77380
  prefix
@@ -77066,7 +77396,7 @@ async function heatmapCommand(opts) {
77066
77396
  };
77067
77397
  if (opts.pr) {
77068
77398
  await postQaComment({ report, pr: opts.pr, repo: opts.repo }).catch((err) => {
77069
- console.error(chalk36.yellow(` aviso: não foi possível publicar no PR — ${err.message}`));
77399
+ console.error(chalk37.yellow(` aviso: não foi possível publicar no PR — ${err.message}`));
77070
77400
  });
77071
77401
  }
77072
77402
  if (opts.json)
@@ -77084,6 +77414,7 @@ async function compareViewport(browser, args) {
77084
77414
  url: args.prodUrl,
77085
77415
  selector: args.selector,
77086
77416
  storageState: args.prodStorageState,
77417
+ cookies: args.prodCookies,
77087
77418
  waitMs: args.waitMs,
77088
77419
  outPath: paths.prod,
77089
77420
  repeatPath: paths.prodRepeat
@@ -77406,7 +77737,8 @@ async function captureSide(browser, args) {
77406
77737
  viewportSize: args.spec.size ?? undefined,
77407
77738
  deviceScaleFactor: 1,
77408
77739
  hideScrollbars: true,
77409
- ...args.storageState ? { storageState: args.storageState } : {}
77740
+ ...args.storageState ? { storageState: args.storageState } : {},
77741
+ cookies: args.cookies
77410
77742
  });
77411
77743
  const page = await ctx.newPage();
77412
77744
  try {
@@ -77579,21 +77911,21 @@ function isValidUrl5(s) {
77579
77911
  }
77580
77912
  }
77581
77913
  var MARK = {
77582
- identical: chalk36.green("✓"),
77583
- differs: chalk36.red("✗"),
77584
- inconclusive: chalk36.yellow("?")
77914
+ identical: chalk37.green("✓"),
77915
+ differs: chalk37.red("✗"),
77916
+ inconclusive: chalk37.yellow("?")
77585
77917
  };
77586
77918
  function printReport(report) {
77587
77919
  console.log("");
77588
- console.log(chalk36.bold(` parity heatmap — ${report.mode}`));
77589
- console.log(chalk36.dim(` prod: ${report.prodUrl}`));
77590
- console.log(chalk36.dim(` cand: ${report.candUrl}`));
77920
+ console.log(chalk37.bold(` parity heatmap — ${report.mode}`));
77921
+ console.log(chalk37.dim(` prod: ${report.prodUrl}`));
77922
+ console.log(chalk37.dim(` cand: ${report.candUrl}`));
77591
77923
  console.log("");
77592
77924
  for (const v of report.viewports) {
77593
- const detail = v.verdict === "identical" ? chalk36.dim("0 pixels") : v.reason ?? chalk36.dim("no detail");
77925
+ const detail = v.verdict === "identical" ? chalk37.dim("0 pixels") : v.reason ?? chalk37.dim("no detail");
77594
77926
  console.log(` ${MARK[v.verdict]} ${v.label.padEnd(12)} ${detail}`);
77595
77927
  if (v.maskedCoverage != null && v.maskedCoverage > 0) {
77596
- console.log(chalk36.dim(` ${(v.maskedCoverage * 100).toFixed(1)}% of the frame excluded: prod does not reproduce those pixels`));
77928
+ console.log(chalk37.dim(` ${(v.maskedCoverage * 100).toFixed(1)}% of the frame excluded: prod does not reproduce those pixels`));
77597
77929
  }
77598
77930
  if (!v.findings.some((f) => f.type === "horizontal-overflow")) {
77599
77931
  for (const [name, s] of [
@@ -77602,23 +77934,23 @@ function printReport(report) {
77602
77934
  ]) {
77603
77935
  const o = s.horizontalOverflow;
77604
77936
  if (o) {
77605
- console.log(chalk36.yellow(` ${name} overflows sideways by ${o.px}px${o.widest ? ` (\`${o.widest.selector}\`)` : ""}`));
77937
+ console.log(chalk37.yellow(` ${name} overflows sideways by ${o.px}px${o.widest ? ` (\`${o.widest.selector}\`)` : ""}`));
77606
77938
  }
77607
77939
  }
77608
77940
  }
77609
77941
  for (const f of v.findings.slice(0, 5)) {
77610
- console.log(chalk36.dim(` [${f.type}] ${f.summary}`));
77942
+ console.log(chalk37.dim(` [${f.type}] ${f.summary}`));
77611
77943
  }
77612
77944
  if (v.heatmapPath && v.verdict === "differs") {
77613
- console.log(chalk36.dim(` ${v.heatmapPath}`));
77945
+ console.log(chalk37.dim(` ${v.heatmapPath}`));
77614
77946
  }
77615
77947
  const hosts = imageHostDelta(v.prod.imageHosts, v.cand.imageHosts);
77616
77948
  if (hosts.onlyProd.length > 0 || hosts.onlyCand.length > 0) {
77617
- console.log(chalk36.yellow(` image hosts diverge — ${formatHostDelta(hosts)}`));
77949
+ console.log(chalk37.yellow(` image hosts diverge — ${formatHostDelta(hosts)}`));
77618
77950
  }
77619
77951
  }
77620
77952
  console.log("");
77621
- console.log(` ${MARK[report.verdict]} ${chalk36.bold(report.verdict)}${report.reason ? ` — ${report.reason}` : ""}`);
77953
+ console.log(` ${MARK[report.verdict]} ${chalk37.bold(report.verdict)}${report.reason ? ` — ${report.reason}` : ""}`);
77622
77954
  console.log("");
77623
77955
  }
77624
77956
  function imageHostDelta(prod, cand) {
@@ -77639,7 +77971,7 @@ function formatHostDelta(d) {
77639
77971
  }
77640
77972
 
77641
77973
  // src/commands/overlay.ts
77642
- import chalk37 from "chalk";
77974
+ import chalk38 from "chalk";
77643
77975
  var SUBPIXEL_TOLERANCE = 0.5;
77644
77976
  var MIN_GUTTER_PX = 2;
77645
77977
  function judgeOverlay(rest, open, closed) {
@@ -77758,7 +78090,7 @@ async function measureTrigger(page, url, trigger, opts) {
77758
78090
  async function overlayCommand(opts) {
77759
78091
  const viewport = parseViewport3(opts.viewport);
77760
78092
  if (!viewport) {
77761
- console.error(chalk37.red(`invalid --viewport: ${opts.viewport}`));
78093
+ console.error(chalk38.red(`invalid --viewport: ${opts.viewport}`));
77762
78094
  return 2;
77763
78095
  }
77764
78096
  const waitMs = Math.max(0, Number.parseInt(opts.wait, 10) || 0);
@@ -77799,32 +78131,32 @@ async function overlayCommand(opts) {
77799
78131
  return code;
77800
78132
  }
77801
78133
  for (const { url, results } of pages) {
77802
- console.log(chalk37.bold(`
78134
+ console.log(chalk38.bold(`
77803
78135
  ${url}`));
77804
78136
  for (const r of results) {
77805
78137
  if (r.status === "clean") {
77806
78138
  const anchorNote = r.rest?.anchorX === null ? ` (anchor ${opts.anchor} not found — width only)` : "";
77807
78139
  console.log(` clean ${r.trigger}${anchorNote}`);
77808
78140
  } else if (r.status === "inconclusive") {
77809
- console.log(chalk37.yellow(` INCONCLUSIVE ${r.trigger} — ${r.reason}`));
78141
+ console.log(chalk38.yellow(` INCONCLUSIVE ${r.trigger} — ${r.reason}`));
77810
78142
  } else {
77811
- console.log(chalk37.red(` overlay-layout-shift ${r.trigger}`));
78143
+ console.log(chalk38.red(` overlay-layout-shift ${r.trigger}`));
77812
78144
  for (const s of r.shifts) {
77813
- console.log(chalk37.red(` ${s.phase.padEnd(6)} ${s.metric} ${s.from} → ${s.to} (${s.to - s.from > 0 ? "+" : ""}${Math.round((s.to - s.from) * 100) / 100}px)`));
78145
+ console.log(chalk38.red(` ${s.phase.padEnd(6)} ${s.metric} ${s.from} → ${s.to} (${s.to - s.from > 0 ? "+" : ""}${Math.round((s.to - s.from) * 100) / 100}px)`));
77814
78146
  }
77815
78147
  if (r.closed === null)
77816
- console.log(chalk37.dim(" (overlay did not close; close leg unmeasured)"));
78148
+ console.log(chalk38.dim(" (overlay did not close; close leg unmeasured)"));
77817
78149
  }
77818
78150
  }
77819
78151
  }
77820
78152
  if (code === 1) {
77821
- console.log(chalk37.dim("\n The scroll lock removes the scrollbar and the page widens. Fix: `html { scrollbar-gutter: stable }` once in global CSS, or pad the lock by the scrollbar width."));
78153
+ console.log(chalk38.dim("\n The scroll lock removes the scrollbar and the page widens. Fix: `html { scrollbar-gutter: stable }` once in global CSS, or pad the lock by the scrollbar width."));
77822
78154
  }
77823
78155
  return code;
77824
78156
  }
77825
78157
 
77826
78158
  // src/commands/states.ts
77827
- import chalk38 from "chalk";
78159
+ import chalk39 from "chalk";
77828
78160
  var ROOT_ATTR = "data-parity-states";
77829
78161
  var rootSelector = (i) => `[${ROOT_ATTR}="${i}"]`;
77830
78162
  function resolveStateRoots(args) {
@@ -78133,7 +78465,7 @@ function statesVerdict(counts) {
78133
78465
  async function statesCommand(opts) {
78134
78466
  const viewport = parseViewport3(opts.viewport);
78135
78467
  if (!viewport) {
78136
- console.error(chalk38.red(`--viewport inválido: ${opts.viewport}`));
78468
+ console.error(chalk39.red(`--viewport inválido: ${opts.viewport}`));
78137
78469
  return 2;
78138
78470
  }
78139
78471
  const waitMs = Number.parseInt(opts.wait, 10) || 0;
@@ -78143,12 +78475,12 @@ async function statesCommand(opts) {
78143
78475
  const prodSelector = opts.prodSelector?.trim() || opts.selector?.trim();
78144
78476
  const candSelector = opts.candSelector?.trim() || opts.selector?.trim();
78145
78477
  if (!prodSelector || !candSelector) {
78146
- console.error(chalk38.red(" informe --selector (ambos os lados) ou --prod-selector e --cand-selector"));
78478
+ console.error(chalk39.red(" informe --selector (ambos os lados) ou --prod-selector e --cand-selector"));
78147
78479
  return 2;
78148
78480
  }
78149
78481
  const { aliases, note: aliasNote } = resolveAliases(opts.planDir);
78150
78482
  if (aliasNote)
78151
- console.log(chalk38.dim(` ${aliasNote}`));
78483
+ console.log(chalk39.dim(` ${aliasNote}`));
78152
78484
  const browser = await launchBrowser({ headless: true });
78153
78485
  try {
78154
78486
  const [prodSide, candSide] = await Promise.all([
@@ -78173,7 +78505,7 @@ async function statesCommand(opts) {
78173
78505
  ]);
78174
78506
  if (prodSide.baseError || candSide.baseError) {
78175
78507
  const which = prodSide.baseError ? `prod: ${prodSide.baseError}` : `cand: ${candSide.baseError}`;
78176
- console.error(chalk38.red(` não foi possível ler o componente — ${which}`));
78508
+ console.error(chalk39.red(` não foi possível ler o componente — ${which}`));
78177
78509
  return 2;
78178
78510
  }
78179
78511
  for (const [name, side, sel] of [
@@ -78182,13 +78514,13 @@ async function statesCommand(opts) {
78182
78514
  ]) {
78183
78515
  const r = side.resolution;
78184
78516
  if (r?.kind === "ambiguous") {
78185
- console.error(chalk38.red(` ${name}: ${sel} matches ${r.total} visible elements and none looks like a product card (image + link + price). Narrow it to one:`));
78517
+ console.error(chalk39.red(` ${name}: ${sel} matches ${r.total} visible elements and none looks like a product card (image + link + price). Narrow it to one:`));
78186
78518
  for (const sample of r.samples)
78187
- console.error(chalk38.dim(` ${sample}`));
78519
+ console.error(chalk39.dim(` ${sample}`));
78188
78520
  return 2;
78189
78521
  }
78190
78522
  if (!r || r.kind === "none") {
78191
- console.error(chalk38.red(` ${name}: ${sel} matches no visible element${r?.error ? ` — ${r.error}` : ""}`));
78523
+ console.error(chalk39.red(` ${name}: ${sel} matches no visible element${r?.error ? ` — ${r.error}` : ""}`));
78192
78524
  return 2;
78193
78525
  }
78194
78526
  }
@@ -78270,21 +78602,21 @@ async function statesCommand(opts) {
78270
78602
  ]) {
78271
78603
  const caveat = data.settle && formatSettleCaveat(name, data.settle);
78272
78604
  if (caveat)
78273
- console.log(chalk38.yellow(` ${caveat}`));
78605
+ console.log(chalk39.yellow(` ${caveat}`));
78274
78606
  }
78275
78607
  if (cardMode) {
78276
78608
  console.log("");
78277
- console.log(chalk38.bold(` Product cards: ${pairing.pairs.length} pair(s) — ${pairing.pairs.map(([p, c]) => `prod #${p + 1} ↔ cand #${c + 1}`).join(", ") || "none"}`));
78609
+ console.log(chalk39.bold(` Product cards: ${pairing.pairs.length} pair(s) — ${pairing.pairs.map(([p, c]) => `prod #${p + 1} ↔ cand #${c + 1}`).join(", ") || "none"}`));
78278
78610
  for (const [name, side] of [
78279
78611
  ["prod", prodSide],
78280
78612
  ["cand", candSide]
78281
78613
  ]) {
78282
78614
  const r = side.resolution;
78283
78615
  if (r?.kind === "cards" && r.ignored > 0) {
78284
- console.log(chalk38.dim(` ${name}: ${r.ignored} matched element(s) are not product cards and were ignored`));
78616
+ console.log(chalk39.dim(` ${name}: ${r.ignored} matched element(s) are not product cards and were ignored`));
78285
78617
  }
78286
78618
  if (r?.kind === "single" && !r.isCard) {
78287
- console.log(chalk38.yellow(` ${name}: the selector names one element that is not a product card; it is never paired with a card`));
78619
+ console.log(chalk39.yellow(` ${name}: the selector names one element that is not a product card; it is never paired with a card`));
78288
78620
  }
78289
78621
  }
78290
78622
  const unpaired = [
@@ -78292,65 +78624,65 @@ async function statesCommand(opts) {
78292
78624
  ...pairing.unpairedCand.map((i) => `cand #${i + 1}`)
78293
78625
  ];
78294
78626
  if (unpaired.length)
78295
- console.log(chalk38.dim(` UNPAIRED cards: ${unpaired.join(", ")} — not compared`));
78627
+ console.log(chalk39.dim(` UNPAIRED cards: ${unpaired.join(", ")} — not compared`));
78296
78628
  if (pairing.pairs.length === 0) {
78297
- console.log(chalk38.yellow(" INCONCLUSIVE — no card paired, so nothing was compared."));
78629
+ console.log(chalk39.yellow(" INCONCLUSIVE — no card paired, so nothing was compared."));
78298
78630
  }
78299
78631
  }
78300
78632
  console.log("");
78301
- console.log(chalk38.bold(" Declared motion"));
78633
+ console.log(chalk39.bold(" Declared motion"));
78302
78634
  if (!motion) {
78303
78635
  const err = prodFlat.motionError ?? candFlat.motionError ?? "nothing paired";
78304
- console.log(chalk38.yellow(` não foi possível comparar — ${err}`));
78636
+ console.log(chalk39.yellow(` não foi possível comparar — ${err}`));
78305
78637
  } else {
78306
78638
  for (const line of formatMotionDiff(motion).split(`
78307
78639
  `))
78308
78640
  console.log(` ${line}`);
78309
78641
  }
78310
78642
  console.log("");
78311
- console.log(chalk38.bold(` Hover effects (${prodFlat.effects.length} prod / ${candFlat.effects.length} cand)`));
78643
+ console.log(chalk39.bold(` Hover effects (${prodFlat.effects.length} prod / ${candFlat.effects.length} cand)`));
78312
78644
  const nothing = effects.lost.length === 0 && effects.changed.length === 0 && effects.added.length === 0 && effects.unpaired.length === 0;
78313
78645
  if (nothing && !exercised) {
78314
- console.log(chalk38.yellow(" INCONCLUSIVE — no hover changed anything on either side, so nothing was exercised. Check the selector holds an interactive element."));
78646
+ console.log(chalk39.yellow(" INCONCLUSIVE — no hover changed anything on either side, so nothing was exercised. Check the selector holds an interactive element."));
78315
78647
  } else if (nothing) {
78316
78648
  console.log(" clean — every hover that changes something in prod changes the same in cand");
78317
78649
  }
78318
78650
  for (const e of effects.lost) {
78319
- console.log(chalk38.red(` LOST ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; cand's element was hovered and moved nothing`));
78651
+ console.log(chalk39.red(` LOST ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; cand's element was hovered and moved nothing`));
78320
78652
  }
78321
78653
  for (const { prod, extra, notComparable, onElement } of effects.changed) {
78322
78654
  console.log(` DIFFERS ${prod.target}${prod.label ? ` (${prod.label})` : ""}`);
78323
78655
  if (onElement.length) {
78324
- console.log(chalk38.yellow(` prod also moves [${onElement.join(", ")}] on the element itself`));
78656
+ console.log(chalk39.yellow(` prod also moves [${onElement.join(", ")}] on the element itself`));
78325
78657
  }
78326
78658
  if (extra.length)
78327
78659
  console.log(` cand also moves [${extra.join(", ")}]`);
78328
78660
  if (notComparable.length) {
78329
- console.log(chalk38.dim(` not comparable: [${notComparable.join(", ")}] — prod's hover renumbered ${prod.renumberedNodes} of the changed paths, so these were read on elements that are not the same ones before and after. Bench the component, or pick a selector whose subtree the hover does not restructure.`));
78661
+ console.log(chalk39.dim(` not comparable: [${notComparable.join(", ")}] — prod's hover renumbered ${prod.renumberedNodes} of the changed paths, so these were read on elements that are not the same ones before and after. Bench the component, or pick a selector whose subtree the hover does not restructure.`));
78330
78662
  }
78331
78663
  if (onElement.length === 0 && extra.length === 0) {
78332
- console.log(chalk38.dim(" nothing comparable differs."));
78664
+ console.log(chalk39.dim(" nothing comparable differs."));
78333
78665
  }
78334
78666
  }
78335
78667
  for (const e of effects.unpaired) {
78336
- console.log(chalk38.dim(` UNPAIRED ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; no matching element found on the cand side (not a defect — the port may have changed the element, or it is outside --selector)`));
78668
+ console.log(chalk39.dim(` UNPAIRED ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; no matching element found on the cand side (not a defect — the port may have changed the element, or it is outside --selector)`));
78337
78669
  }
78338
78670
  for (const e of effects.added) {
78339
78671
  console.log(` ADDED ${e.target} — cand moves [${e.properties.join(", ")}]; prod does not`);
78340
78672
  }
78341
78673
  if (effects.unpaired.length > 0 && effects.lost.length === 0 && effects.changed.length === 0) {
78342
78674
  console.log("");
78343
- console.log(chalk38.yellow(` ${effects.unpaired.length} prod effect(s) had no counterpart and NOTHING paired. That is a pairing failure, not a set of defects — check --selector contains the same component on both sides, and that ported roots carry data-section.`));
78675
+ console.log(chalk39.yellow(` ${effects.unpaired.length} prod effect(s) had no counterpart and NOTHING paired. That is a pairing failure, not a set of defects — check --selector contains the same component on both sides, and that ported roots carry data-section.`));
78344
78676
  }
78345
78677
  const prodAmbient = prodSide.roots.reduce((n, r) => n + r.ambient, 0);
78346
78678
  const candAmbient = candSide.roots.reduce((n, r) => n + r.ambient, 0);
78347
78679
  if (prodAmbient > 0 || candAmbient > 0) {
78348
- console.log(chalk38.dim(` ${prodAmbient} prod / ${candAmbient} cand node+property pair(s) were moving with no interaction (carousel, autoplaying video, anything on a timer) and were subtracted. A large count means --selector contains something animating on its own; narrow it.`));
78680
+ console.log(chalk39.dim(` ${prodAmbient} prod / ${candAmbient} cand node+property pair(s) were moving with no interaction (carousel, autoplaying video, anything on a timer) and were subtracted. A large count means --selector contains something animating on its own; narrow it.`));
78349
78681
  }
78350
78682
  for (const cap of caps)
78351
- console.log(chalk38.yellow(` CAPPED — ${cap}; absence of a finding is not proof`));
78683
+ console.log(chalk39.yellow(` CAPPED — ${cap}; absence of a finding is not proof`));
78352
78684
  if (truncated) {
78353
- console.log(chalk38.dim(" TRUNCATED — box-tree or motion node cap hit; absence of a finding is not proof"));
78685
+ console.log(chalk39.dim(" TRUNCATED — box-tree or motion node cap hit; absence of a finding is not proof"));
78354
78686
  }
78355
78687
  return inconclusive || effects.lost.length > 0 || (motion?.findings.length ?? 0) > 0 ? 1 : 0;
78356
78688
  } finally {
@@ -78361,7 +78693,7 @@ async function statesCommand(opts) {
78361
78693
  }
78362
78694
 
78363
78695
  // src/commands/variance.ts
78364
- import chalk39 from "chalk";
78696
+ import chalk40 from "chalk";
78365
78697
 
78366
78698
  // src/diff/variance.ts
78367
78699
  var uniq2 = (xs) => [...new Set(xs)];
@@ -78465,7 +78797,7 @@ function formatVariance(report, opts = {}) {
78465
78797
  // src/commands/variance.ts
78466
78798
  function varianceCommand(opts) {
78467
78799
  if (opts.runIds.length < 2) {
78468
- console.error(chalk39.red(" informe pelo menos 2 runs: parity variance <runIdA> <runIdB> [...]"));
78800
+ console.error(chalk40.red(" informe pelo menos 2 runs: parity variance <runIdA> <runIdB> [...]"));
78469
78801
  return 2;
78470
78802
  }
78471
78803
  const budget = Number.parseFloat(opts.scoreBudget ?? "1");
@@ -78474,7 +78806,7 @@ function varianceCommand(opts) {
78474
78806
  try {
78475
78807
  runs.push(loadRun(opts.output, id));
78476
78808
  } catch (err) {
78477
- console.error(chalk39.red(` ✖ ${err.message}`));
78809
+ console.error(chalk40.red(` ✖ ${err.message}`));
78478
78810
  return 2;
78479
78811
  }
78480
78812
  }
@@ -78483,7 +78815,7 @@ function varianceCommand(opts) {
78483
78815
  console.log(JSON.stringify({ ...report, stable: isStable(report, budget), scoreBudget: budget }));
78484
78816
  } else {
78485
78817
  console.log("");
78486
- console.log(chalk39.bold(" Score variance"));
78818
+ console.log(chalk40.bold(" Score variance"));
78487
78819
  for (const line of formatVariance(report, { scoreBudget: budget }).split(`
78488
78820
  `)) {
78489
78821
  console.log(` ${line}`);
@@ -78498,7 +78830,7 @@ function varianceCommand(opts) {
78498
78830
  import { existsSync as existsSync35, readFileSync as readFileSync43, writeFileSync as writeFileSync36 } from "node:fs";
78499
78831
  import { availableParallelism } from "node:os";
78500
78832
  import { join as join47 } from "node:path";
78501
- import chalk40 from "chalk";
78833
+ import chalk41 from "chalk";
78502
78834
  import ora9 from "ora";
78503
78835
 
78504
78836
  // src/checks/agentic-nav.ts
@@ -78796,10 +79128,10 @@ async function vitalsCommand(opts) {
78796
79128
  const runId = newRunId();
78797
79129
  const paths = createRunDir(opts.output, runId);
78798
79130
  const t0 = Date.now();
78799
- console.log(chalk40.bold(`
79131
+ console.log(chalk41.bold(`
78800
79132
  parity vitals ${runId}`));
78801
- console.log(chalk40.dim(` prod: ${opts.prod}`));
78802
- console.log(chalk40.dim(` cand: ${opts.cand}`));
79133
+ console.log(chalk41.dim(` prod: ${opts.prod}`));
79134
+ console.log(chalk41.dim(` cand: ${opts.cand}`));
78803
79135
  const discoverSpinner = ora9("Descobrindo páginas…").start();
78804
79136
  const pagePaths = await discoverPagePaths2(opts.prod, opts);
78805
79137
  if (pagePaths.length === 0) {
@@ -78831,7 +79163,7 @@ async function vitalsCommand(opts) {
78831
79163
  completed++;
78832
79164
  const elapsed = ((Date.now() - t0) / 1000).toFixed(0);
78833
79165
  const etaSec = completed > 0 ? Math.round((Date.now() - t0) / completed * (total - completed) / 1000) : 0;
78834
- progress.text = `${completed}/${total} · ${elapsed}s · ETA ${etaSec}s · ${task.side === "prod" ? chalk40.cyan("prod") : chalk40.magenta("cand")} ${task.path} (${task.viewport})`;
79166
+ progress.text = `${completed}/${total} · ${elapsed}s · ETA ${etaSec}s · ${task.side === "prod" ? chalk41.cyan("prod") : chalk41.magenta("cand")} ${task.path} (${task.viewport})`;
78835
79167
  }
78836
79168
  });
78837
79169
  progress.succeed(`${total} capture(s) em ${((Date.now() - t0) / 1000).toFixed(1)}s`);
@@ -78860,7 +79192,7 @@ async function vitalsCommand(opts) {
78860
79192
  }
78861
79193
  lhCompleted++;
78862
79194
  const elapsed = ((Date.now() - lhT0) / 1000).toFixed(0);
78863
- lhProgress.text = `Lighthouse ${lhCompleted}/${done.length} · ${elapsed}s · ${task.side === "prod" ? chalk40.cyan("prod") : chalk40.magenta("cand")} ${task.path} (${task.viewport})`;
79195
+ lhProgress.text = `Lighthouse ${lhCompleted}/${done.length} · ${elapsed}s · ${task.side === "prod" ? chalk41.cyan("prod") : chalk41.magenta("cand")} ${task.path} (${task.viewport})`;
78864
79196
  });
78865
79197
  lhProgress.succeed(`Lighthouse ${done.length} página(s) em ${((Date.now() - lhT0) / 1000).toFixed(1)}s`);
78866
79198
  }
@@ -78938,8 +79270,8 @@ async function vitalsCommand(opts) {
78938
79270
  `, "utf8");
78939
79271
  printSummary9(vitalsResult, cacheResult, scoresResult, oppsResult, agenticResult);
78940
79272
  console.log("");
78941
- console.log(chalk40.dim(` → ${paths.reportHtml}`));
78942
- console.log(chalk40.dim(` \uD83D\uDCA1 use 'parity serve ${runId}' pra preview iframe`));
79273
+ console.log(chalk41.dim(` → ${paths.reportHtml}`));
79274
+ console.log(chalk41.dim(` \uD83D\uDCA1 use 'parity serve ${runId}' pra preview iframe`));
78943
79275
  console.log("");
78944
79276
  if (opts.open) {
78945
79277
  const { default: open } = await import("open");
@@ -79039,7 +79371,7 @@ function parseUrlList(input) {
79039
79371
  }
79040
79372
  function printSummary9(vitals, cache, scores, opportunities, agentic) {
79041
79373
  console.log("");
79042
- console.log(chalk40.bold(" Summary:"));
79374
+ console.log(chalk41.bold(" Summary:"));
79043
79375
  console.log(` ${vitals.summary}`);
79044
79376
  console.log(` ${cache.summary}`);
79045
79377
  if (scores.status !== "skipped")
@@ -79305,7 +79637,15 @@ program.command("check").argument("<name>", "check name (kebab-case, e.g. consol
79305
79637
  json: opts.json
79306
79638
  }));
79307
79639
  });
79308
- program.command("heatmap").description("Is the candidate PIXEL-IDENTICAL to prod — yes, no, or 'nothing was compared'. Zero tolerance, no LLM, no flag to loosen it: one differing pixel fails. Sweeps mobile→2560px so a broken breakpoint cannot hide at the one size you checked, and captures prod twice first so a page that is not identical to itself reports its own noise floor instead of blaming the candidate. Use `parity section` to find out WHY something differs; use this to decide WHETHER it does.").requiredOption("--prod <url>", "Production URL (the reference)").requiredOption("--cand <url>", "Candidate URL").option("--selector <sel>", "Compare only this section instead of the whole page. Without it the comparison is full-page.").option("--cand-selector <sel>", "Selector on the CANDIDATE side, when the ported component no longer answers to --selector. Defaults to --selector.").option("--prod-storage-state <file>", "Playwright storageState (cookies + localStorage) for the production side, to compare pages behind a login. Without it an authenticated page measures the login redirect.").option("--cand-storage-state <file>", "Same, for the candidate side").option("--viewports <list>", "Comma-separated; each entry is a preset (mobile|tablet|desktop) or a literal <width>x<height>, and every entry must be clean for the run to pass. `all` expands to the full sweep (mobile→2560px) — worth it to close a page, too slow to put in a per-component loop, which is why it is not the default.", DEFAULT_VIEWPORTS).option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").option("--pr <number>", "Publish the verdict as a PR comment, with the diff images inline. Reporting only — a failure to publish never changes the verdict or the exit code.").option("--repo <owner/name>", "Repo for --pr. Defaults to whatever `gh` infers from the cwd.").option("--out-dir <dir>", "Where to write the screenshots and heatmaps", "./parity-output/heatmap").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
79640
+ function collectCookie(value, prev) {
79641
+ if (value.indexOf("=") <= 0)
79642
+ throw new InvalidArgumentError2("expected name=value");
79643
+ return [...prev, value];
79644
+ }
79645
+ program.command("ab-detect").description("Is prod A/B-testing this component? Opens N fresh sessions, hashes what --selector (or the page) rendered in each, and records experiment signals (cookies/storage keys, variant attributes, A/B SDK globals). Exit 0 = no A/B seen (same structure, no signal differs), 1 = A/B detected or possible (same structure but experiment signals differ between sessions — a behaviour-only test); either way it names the signals to pin with --prod-cookie, 2 = inconclusive.").requiredOption("--url <url>", "Production page URL").option("--sessions <n>", "Fresh sessions to open (min 2)", "3").option("--selector <sel>", "Component to compare across sessions. Without it, the whole page.").option("--viewport <viewport>", "mobile | desktop | tablet", "mobile").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
79646
+ process.exit(await abDetectCommand(opts));
79647
+ });
79648
+ program.command("heatmap").description("Is the candidate PIXEL-IDENTICAL to prod — yes, no, or 'nothing was compared'. Zero tolerance, no LLM, no flag to loosen it: one differing pixel fails. Sweeps mobile→2560px so a broken breakpoint cannot hide at the one size you checked, and captures prod twice first so a page that is not identical to itself reports its own noise floor instead of blaming the candidate. Use `parity section` to find out WHY something differs; use this to decide WHETHER it does.").requiredOption("--prod <url>", "Production URL (the reference)").requiredOption("--cand <url>", "Candidate URL").option("--selector <sel>", "Compare only this section instead of the whole page. Without it the comparison is full-page.").option("--cand-selector <sel>", "Selector on the CANDIDATE side, when the ported component no longer answers to --selector. Defaults to --selector.").option("--prod-storage-state <file>", "Playwright storageState (cookies + localStorage) for the production side, to compare pages behind a login. Without it an authenticated page measures the login redirect.").option("--cand-storage-state <file>", "Same, for the candidate side").option("--prod-cookie <name=value>", "Cookie set on the production side before navigation; repeatable. Pins prod to one A/B variant (see `parity ab-detect`) so the comparison stops depending on which bucket a fresh context drew.", collectCookie, []).option("--viewports <list>", "Comma-separated; each entry is a preset (mobile|tablet|desktop) or a literal <width>x<height>, and every entry must be clean for the run to pass. `all` expands to the full sweep (mobile→2560px) — worth it to close a page, too slow to put in a per-component loop, which is why it is not the default.", DEFAULT_VIEWPORTS).option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").option("--pr <number>", "Publish the verdict as a PR comment, with the diff images inline. Reporting only — a failure to publish never changes the verdict or the exit code.").option("--repo <owner/name>", "Repo for --pr. Defaults to whatever `gh` infers from the cwd.").option("--out-dir <dir>", "Where to write the screenshots and heatmaps", "./parity-output/heatmap").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
79309
79649
  process.exit(await heatmapCommand({
79310
79650
  prod: opts.prod,
79311
79651
  cand: opts.cand,
@@ -79313,6 +79653,7 @@ program.command("heatmap").description("Is the candidate PIXEL-IDENTICAL to prod
79313
79653
  candSelector: opts.candSelector,
79314
79654
  prodStorageState: opts.prodStorageState,
79315
79655
  candStorageState: opts.candStorageState,
79656
+ prodCookies: opts.prodCookie,
79316
79657
  viewports: opts.viewports,
79317
79658
  wait: opts.wait,
79318
79659
  pr: opts.pr,
@@ -79321,7 +79662,7 @@ program.command("heatmap").description("Is the candidate PIXEL-IDENTICAL to prod
79321
79662
  json: opts.json
79322
79663
  }));
79323
79664
  });
79324
- program.command("section").description("Focused prod×cand comparison of one section: HTML diff + screenshot + computed-styles diff, plus an opt-in numeric box-tree diff (--box-tree). No flags = all 3 facets. Designed for the 'in DOM but invisible' debug loop (issue #31).").option("--prod <url>", "Production URL (base, e.g. https://www.example.com). Required unless --task.").option("--cand <url>", "Candidate URL (base, e.g. https://example.deco-cx.workers.dev). Required unless --task; with --task, pass it to point at a local build.").option("--selector <sel>", "CSS selector for the section to compare. Required unless --task.").option("--task <dir>", "A cockpit task dir (.parity/tasks/<id>): takes the page, the prod/cand pair and the exact frame size the reviewer saw. Explicit flags override it.").option("--cand-selector <sel>", "CSS selector on the CANDIDATE side, when the ported component no longer matches --selector (VTEX IO class names → hashed CSS Modules, data-fs-* attributes, …). Defaults to --selector.").option("--output-html", "Include the HTML diff facet (default: on if no facet flag passed)", false).option("--screenshot", "Include the screenshot facet (locator screenshot per side)", false).option("--computed-styles", "Include the computed-styles diff facet", false).option("--heatmap", "Run pixelmatch on the two screenshots and analyze diff regions (bounding box + hotspots). Implies --screenshot.", false).option("--box-tree", "Walk the selector's whole subtree on both sides and report numeric box deltas, biggest first (`margin-top: 32px → 24px -8`). Deterministic, no LLM — this is the answer to 'everything is a little off', which a pixelmatch percentage and a vision paragraph cannot give.", false).option("--css-source", "For each divergent computed-style property, resolve which CSS rule (stylesheet + selector) produced it via CDP. Useful when the LLM needs to know which file to edit.", false).option("--prompt", "Emit an LLM-ready bundle: <prefix>-bundle.json (machine-readable) + <prefix>-prompt.md (opinionated Markdown with embedded images). Implies all signals.", false).option("--llm-summary", "After building the bundle, invoke Claude (needs ANTHROPIC_API_KEY) and print a 1-paragraph 'what I understood' summary. Does NOT generate a patch. Implies --prompt.", false).option("--all", "Turn on every diagnostic facet at once (html + screenshot + computed-styles + heatmap + css-source + prompt + llm-summary) — the pixel-perfect debug shortcut formerly known as `parity fix`. Issue #415.", false).option("--no-llm", "With --all, skip the LLM call (still writes the markdown bundle). Use when offline or to avoid API costs.").option("--prod-storage-state <file>", "Playwright storageState (cookies + localStorage) for the production side, to compare pages behind a login. Without it an authenticated page measures the login redirect.").option("--cand-storage-state <file>", "Same, for the candidate side").option("--viewport <viewport>", "mobile | desktop | tablet", "mobile").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").option("--out-dir <dir>", "Where to write the screenshots", "./parity-output/sections").option("--plan-dir <dir>", "Run dir holding migration-plan.json. Its component rows are the only place the prod-side spelling of a component (`site/sections/Hero/HeroBannerV2.tsx`) and the cand-side one (`HeroSlideshow`) are written down together, so reading it lets the label pass pair nodes whose markup does not agree. Without it, unlabelled nodes fall back to the structural path.").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts, cmd) => {
79665
+ program.command("section").description("Focused prod×cand comparison of one section: HTML diff + screenshot + computed-styles diff, plus an opt-in numeric box-tree diff (--box-tree). No flags = all 3 facets. Designed for the 'in DOM but invisible' debug loop (issue #31).").option("--prod <url>", "Production URL (base, e.g. https://www.example.com). Required unless --task.").option("--cand <url>", "Candidate URL (base, e.g. https://example.deco-cx.workers.dev). Required unless --task; with --task, pass it to point at a local build.").option("--selector <sel>", "CSS selector for the section to compare. Required unless --task.").option("--task <dir>", "A cockpit task dir (.parity/tasks/<id>): takes the page, the prod/cand pair and the exact frame size the reviewer saw. Explicit flags override it.").option("--cand-selector <sel>", "CSS selector on the CANDIDATE side, when the ported component no longer matches --selector (VTEX IO class names → hashed CSS Modules, data-fs-* attributes, …). Defaults to --selector.").option("--output-html", "Include the HTML diff facet (default: on if no facet flag passed)", false).option("--screenshot", "Include the screenshot facet (locator screenshot per side)", false).option("--computed-styles", "Include the computed-styles diff facet", false).option("--heatmap", "Run pixelmatch on the two screenshots and analyze diff regions (bounding box + hotspots). Implies --screenshot.", false).option("--box-tree", "Walk the selector's whole subtree on both sides and report numeric box deltas, biggest first (`margin-top: 32px → 24px -8`). Deterministic, no LLM — this is the answer to 'everything is a little off', which a pixelmatch percentage and a vision paragraph cannot give.", false).option("--css-source", "For each divergent computed-style property, resolve which CSS rule (stylesheet + selector) produced it via CDP. Useful when the LLM needs to know which file to edit.", false).option("--prompt", "Emit an LLM-ready bundle: <prefix>-bundle.json (machine-readable) + <prefix>-prompt.md (opinionated Markdown with embedded images). Implies all signals.", false).option("--llm-summary", "After building the bundle, invoke Claude (needs ANTHROPIC_API_KEY) and print a 1-paragraph 'what I understood' summary. Does NOT generate a patch. Implies --prompt.", false).option("--all", "Turn on every diagnostic facet at once (html + screenshot + computed-styles + heatmap + css-source + prompt + llm-summary) — the pixel-perfect debug shortcut formerly known as `parity fix`. Issue #415.", false).option("--no-llm", "With --all, skip the LLM call (still writes the markdown bundle). Use when offline or to avoid API costs.").option("--prod-storage-state <file>", "Playwright storageState (cookies + localStorage) for the production side, to compare pages behind a login. Without it an authenticated page measures the login redirect.").option("--cand-storage-state <file>", "Same, for the candidate side").option("--prod-cookie <name=value>", "Cookie set on the production side before navigation; repeatable. Pins prod to one A/B variant (see `parity ab-detect`) so the comparison stops depending on which bucket a fresh context drew.", collectCookie, []).option("--viewport <viewport>", "mobile | desktop | tablet", "mobile").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").option("--out-dir <dir>", "Where to write the screenshots", "./parity-output/sections").option("--plan-dir <dir>", "Run dir holding migration-plan.json. Its component rows are the only place the prod-side spelling of a component (`site/sections/Hero/HeroBannerV2.tsx`) and the cand-side one (`HeroSlideshow`) are written down together, so reading it lets the label pass pair nodes whose markup does not agree. Without it, unlabelled nodes fall back to the structural path.").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts, cmd) => {
79325
79666
  let fromTask = null;
79326
79667
  if (opts.task) {
79327
79668
  try {
@@ -79348,6 +79689,7 @@ program.command("section").description("Focused prod×cand comparison of one sec
79348
79689
  candSelector: pick(opts.candSelector, fromTask?.candSelector),
79349
79690
  prodStorageState: opts.prodStorageState,
79350
79691
  candStorageState: opts.candStorageState,
79692
+ prodCookies: opts.prodCookie,
79351
79693
  ...fromTask?.viewportSize && !viewportTyped ? { viewportSize: fromTask.viewportSize } : {},
79352
79694
  outputHtml: opts.all ? true : opts.outputHtml,
79353
79695
  screenshot: opts.all ? true : opts.screenshot,
@@ -79490,7 +79832,7 @@ program.command("extract").description("Single-site AI-ready component extractio
79490
79832
  }));
79491
79833
  });
79492
79834
  function buildCaptureCommand(name, deprecated) {
79493
- return new Command(name).description(`${deprecated ? "[deprecated: use `parity capture`] " : ""}Single-site, phased migration capture (theme → sitemap → components). No prod×cand comparison — produces a target-agnostic, token-lean bundle + prompt for a migration agent: site theme (colors/typography/spacing as Tailwind tokens), classified pages, and per-component detail (suggested Tailwind classes, interaction hints, e2e selectors). Works whether or not the source code exists. Pass --target faststore to append a target playbook. Resumable: re-runs skip a completed phase unless --refresh.`).requiredOption("--url <url>", "Site to capture from").option("--pages <list>", 'Comma-separated pages: literal paths/URLs, and/or "category-auto"/"pdp-auto". Default: "/,category-auto,pdp-auto" (home + a PLP + a PDP).').option("--components <list>", "Comma-separated role allowlist, e.g. header,footer,nav,shelf,minicart. Default: all detected.").option("--target <name>", "Target playbook to append to the prompt (e.g. faststore)").option("--viewport <viewport>", "Primary viewport for component capture: mobile | desktop | tablet", "mobile").option("--viewports <list>", "Comma-separated viewports for theme + site screenshots (e.g. mobile,desktop). Default: --viewport only.").option("--component-viewports", "Also capture every component at the non-primary --viewports. Keeps a per-viewport HTML only when it differs from the primary (normalised) and a screenshot only when its bytes differ. Costs one extra page load per viewport per page.", false).option("--sample <spec>", "Extra pages to sample from the sitemap by kind, e.g. 'plp=2,pdp=2,other=3,search=1' (other = institutional). Default samples a few of each incl. institutional pages.").option("--format <fmt>", "md | json | both", "both").option("--source <dir>", "Path to the source repo. When set, the component inventory is read from CODE (exhaustive, exact names) and the VTEX-IO runtime scrape is gated on the source actually being VTEX IO. Without it, everything comes from the live capture (original behaviour).").option("--source-kind <kind>", "Override source auto-detection: deco-fresh | vtex-io | live-only. Only needed when detection fails.").option("--no-source-hunt", "Skip the on-disk search for a source repo when --source is omitted. Without --source the command sweeps sibling directories for one.").option("--storage-state <file>", "Playwright storageState (cookies + localStorage) to capture pages behind a login (my account, checkout). Without it those pages capture the login redirect.").option("--out <dir>", "Output directory (stable per host, for resume)", "./parity-migrate").option("--refresh", "Re-run all phases even if cached artifacts exist", false).option("--open", "Open the generated index.html visual report in the browser", false).option("--no-llm", "Skip the optional LLM component-relabeling pass (heuristic detection always runs regardless).").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
79835
+ return new Command(name).description(`${deprecated ? "[deprecated: use `parity capture`] " : ""}Single-site, phased migration capture (theme → sitemap → components). No prod×cand comparison — produces a target-agnostic, token-lean bundle + prompt for a migration agent: site theme (colors/typography/spacing as Tailwind tokens), classified pages, and per-component detail (suggested Tailwind classes, interaction hints, e2e selectors). Works whether or not the source code exists. Pass --target faststore to append a target playbook. Resumable: re-runs skip a completed phase unless --refresh.`).requiredOption("--url <url>", "Site to capture from").option("--pages <list>", 'Comma-separated pages: literal paths/URLs, and/or "category-auto"/"pdp-auto". Default: "/,category-auto,pdp-auto" (home + a PLP + a PDP).').option("--components <list>", "Comma-separated role allowlist, e.g. header,footer,nav,shelf,minicart. Default: all detected.").option("--target <name>", "Target playbook to append to the prompt (e.g. faststore)").option("--viewport <viewport>", "Primary viewport for component capture: mobile | desktop | tablet", "mobile").option("--viewports <list>", "Comma-separated viewports for theme + site screenshots (e.g. mobile,desktop). Default: --viewport only.").option("--component-viewports", "Also capture every component at the non-primary --viewports. Keeps a per-viewport HTML only when it differs from the primary (normalised) and a screenshot only when its bytes differ. Costs one extra page load per viewport per page.", false).option("--download-component-assets", "Save every component's images into components/<dir>/images/ and record each local path (or why it failed) in imageFiles[], so a component that later vanishes from prod can still be rebuilt. One file per URL across the run, capped at 200 files / 50 MB.", false).option("--sample <spec>", "Extra pages to sample from the sitemap by kind, e.g. 'plp=2,pdp=2,other=3,search=1' (other = institutional). Default samples a few of each incl. institutional pages.").option("--format <fmt>", "md | json | both", "both").option("--source <dir>", "Path to the source repo. When set, the component inventory is read from CODE (exhaustive, exact names) and the VTEX-IO runtime scrape is gated on the source actually being VTEX IO. Without it, everything comes from the live capture (original behaviour).").option("--source-kind <kind>", "Override source auto-detection: deco-fresh | vtex-io | live-only. Only needed when detection fails.").option("--no-source-hunt", "Skip the on-disk search for a source repo when --source is omitted. Without --source the command sweeps sibling directories for one.").option("--storage-state <file>", "Playwright storageState (cookies + localStorage) to capture pages behind a login (my account, checkout). Without it those pages capture the login redirect.").option("--out <dir>", "Output directory (stable per host, for resume)", "./parity-migrate").option("--refresh", "Re-run all phases even if cached artifacts exist", false).option("--open", "Open the generated index.html visual report in the browser", false).option("--no-llm", "Skip the optional LLM component-relabeling pass (heuristic detection always runs regardless).").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
79494
79836
  if (deprecated)
79495
79837
  deprecatedNotice("migrate", "capture");
79496
79838
  process.exit(await migrateCommand({
@@ -79504,6 +79846,7 @@ function buildCaptureCommand(name, deprecated) {
79504
79846
  viewport: opts.viewport,
79505
79847
  viewports: opts.viewports,
79506
79848
  componentViewports: opts.componentViewports,
79849
+ downloadComponentAssets: opts.downloadComponentAssets,
79507
79850
  sample: opts.sample,
79508
79851
  storageState: opts.storageState,
79509
79852
  format: opts.format,