@decocms/parity 0.33.61 → 0.33.62

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 +385 -76
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -46671,6 +46671,66 @@ async function waitReady(page, cap = READY_CAP_MS) {
46671
46671
  await page.waitForTimeout(400);
46672
46672
  return loaded && idled;
46673
46673
  }
46674
+ function isContentReady(s, before) {
46675
+ if (!s.mainVisible || s.busy)
46676
+ return false;
46677
+ if (before !== undefined && s.signature === before)
46678
+ return false;
46679
+ if (s.heroImage === null)
46680
+ return s.textChars >= 20;
46681
+ return s.heroImage.loaded;
46682
+ }
46683
+ async function readContentSnapshot(page) {
46684
+ return page.evaluate(() => {
46685
+ const vh = window.innerHeight;
46686
+ const shown = (el) => {
46687
+ const r = el.getBoundingClientRect();
46688
+ if (r.width <= 0 || r.height <= 0 || r.bottom <= 0 || r.top >= vh)
46689
+ return false;
46690
+ const cs = getComputedStyle(el);
46691
+ return cs.visibility !== "hidden" && cs.display !== "none" && cs.opacity !== "0";
46692
+ };
46693
+ const root = Array.from(document.querySelectorAll("main, [role='main']")).find(shown) ?? document.body;
46694
+ const text = root.innerText ?? "";
46695
+ let hash = 5381;
46696
+ for (let i = 0;i < text.length; i++)
46697
+ hash = (hash << 5) + hash + text.charCodeAt(i) | 0;
46698
+ let hero = null;
46699
+ let heroArea = 0;
46700
+ for (const im of Array.from(root.querySelectorAll("img"))) {
46701
+ const r = im.getBoundingClientRect();
46702
+ if (r.width < 120 || r.height < 120 || !shown(im))
46703
+ continue;
46704
+ if (r.width * r.height > heroArea) {
46705
+ hero = im;
46706
+ heroArea = r.width * r.height;
46707
+ }
46708
+ }
46709
+ const busy = Array.from(document.querySelectorAll("[aria-busy='true'], [role='progressbar']:not([aria-valuenow]), [class*='spinner' i], [class*='skeleton' i]")).some(shown);
46710
+ return {
46711
+ mainVisible: !!root && shown(root),
46712
+ textChars: text.trim().length,
46713
+ heroImage: hero ? { loaded: hero.complete && hero.naturalWidth > 0 } : null,
46714
+ busy,
46715
+ signature: `${text.length}:${hash}`
46716
+ };
46717
+ });
46718
+ }
46719
+ async function contentSignature(page) {
46720
+ return readContentSnapshot(page).then((s) => s.signature).catch(() => {
46721
+ return;
46722
+ });
46723
+ }
46724
+ async function waitContentReady(page, before, cap = READY_CAP_MS) {
46725
+ const deadline = Date.now() + cap;
46726
+ while (Date.now() < deadline) {
46727
+ const s = await readContentSnapshot(page).catch(() => null);
46728
+ if (s && isContentReady(s, before))
46729
+ return true;
46730
+ await page.waitForTimeout(50);
46731
+ }
46732
+ return false;
46733
+ }
46674
46734
  async function waitForProductImage(page, capMs = 8000) {
46675
46735
  return page.waitForFunction(() => {
46676
46736
  for (const el of Array.from(document.querySelectorAll("img"))) {
@@ -46696,7 +46756,7 @@ async function waitForCardGrowth(page, before, capMs) {
46696
46756
  }
46697
46757
  return cur;
46698
46758
  }
46699
- async function navigateWithHover(page, targetUrl, productImage = false) {
46759
+ async function navigateWithHover(page, targetUrl, ready = "load") {
46700
46760
  const targetPath = new URL(targetUrl).pathname;
46701
46761
  const sel = `a[href="${cssAttrEscape(targetUrl)}"], a[href="${cssAttrEscape(targetPath)}"], a[href^="${cssAttrEscape(`${targetPath}?`)}"]`;
46702
46762
  const anchor = page.locator(sel).first();
@@ -46704,6 +46764,7 @@ async function navigateWithHover(page, targetUrl, productImage = false) {
46704
46764
  return;
46705
46765
  });
46706
46766
  const visible = await anchor.isVisible({ timeout: 1500 }).catch(() => false);
46767
+ const before = ready === "content" ? await contentSignature(page) : undefined;
46707
46768
  let t;
46708
46769
  let viaFallback = false;
46709
46770
  let prefetched;
@@ -46747,9 +46808,11 @@ async function navigateWithHover(page, targetUrl, productImage = false) {
46747
46808
  });
46748
46809
  }
46749
46810
  let ok;
46750
- if (productImage) {
46811
+ if (ready === "product") {
46751
46812
  await withCap(page.waitForLoadState("domcontentloaded"), 5000, undefined);
46752
46813
  ok = await waitForProductImage(page);
46814
+ } else if (ready === "content") {
46815
+ ok = await waitContentReady(page, before);
46753
46816
  } else {
46754
46817
  ok = await waitReady(page);
46755
46818
  }
@@ -46981,7 +47044,7 @@ async function clickShelfProduct(page, ctx) {
46981
47044
  });
46982
47045
  if (!target)
46983
47046
  return null;
46984
- const nav = await navigateWithHover(page, target.href, true);
47047
+ const nav = await navigateWithHover(page, target.href, "product");
46985
47048
  const now = (() => {
46986
47049
  try {
46987
47050
  return new URL(page.url()).pathname;
@@ -47087,10 +47150,10 @@ async function onePass(page, ctx, targets, paginations, measure, paginationCapMs
47087
47150
  await scrollToTop(page);
47088
47151
  const productPath = new URL(targets.product).pathname;
47089
47152
  const reachedPdp = () => page.url().includes(productPath);
47090
- let pdpNav = await navigateWithHover(page, targets.product, true);
47153
+ let pdpNav = await navigateWithHover(page, targets.product, "product");
47091
47154
  if (!reachedPdp() || !pdpNav.ok) {
47092
47155
  await page.waitForTimeout(500);
47093
- pdpNav = await navigateWithHover(page, targets.product, true);
47156
+ pdpNav = await navigateWithHover(page, targets.product, "product");
47094
47157
  }
47095
47158
  await dismissAll(page, ctx);
47096
47159
  const pdpBroken = await pageLooksBroken(page);
@@ -47765,7 +47828,7 @@ async function resolveContentPaths(opts) {
47765
47828
  await dismissAll(page, flow);
47766
47829
  const brand = await captureBrand(page);
47767
47830
  const hrefs = await page.evaluate(() => Array.from(document.querySelectorAll("header a[href], nav a[href], a[href]")).filter((a) => !a.parentElement?.querySelector(":scope > ul, :scope > [class*='dropdown']:not(a), :scope > [class*='submenu']:not(a)")).map((a) => a.getAttribute("href")).filter((h) => !!h)).catch(() => []);
47768
- const candidates = filterContentPaths(hrefs, opts.prodBase);
47831
+ const candidates = filterContentPaths(opts.pages?.length ? opts.pages : hrefs, opts.prodBase);
47769
47832
  const ok = [];
47770
47833
  for (const path of candidates) {
47771
47834
  if (ok.length >= 2)
@@ -47832,14 +47895,14 @@ async function onePassContent(page, ctx, paths, measure) {
47832
47895
  await page.goto(ctx.baseUrl, { waitUntil: "domcontentloaded", timeout: 30000 }).catch(() => {
47833
47896
  return;
47834
47897
  });
47835
- const ready = await waitReady(page, 12000);
47898
+ const ready = await waitContentReady(page, undefined, 12000);
47836
47899
  const broken = await pageLooksBroken(page);
47837
47900
  const home = {
47838
47901
  step: "home-load",
47839
47902
  ms: Date.now() - t,
47840
47903
  url: page.url(),
47841
47904
  ok: ready && !broken,
47842
- note: !ready ? "atingiu o cap de espera sem sinal de prontidão (load/networkidle)" : undefined
47905
+ note: !ready ? "atingiu o cap de espera sem conteúdo pronto" : undefined
47843
47906
  };
47844
47907
  await dismissAll(page, ctx);
47845
47908
  await scrollPageInChunks(page).catch(() => {
@@ -47851,7 +47914,7 @@ async function onePassContent(page, ctx, paths, measure) {
47851
47914
  await revealLink(page, ctx.baseUrl, path).catch(() => {
47852
47915
  return;
47853
47916
  });
47854
- const nav = await navigateWithHover(page, new URL(path, ctx.baseUrl).toString(), false);
47917
+ const nav = await navigateWithHover(page, new URL(path, ctx.baseUrl).toString(), "content");
47855
47918
  const broken = await pageLooksBroken(page);
47856
47919
  return {
47857
47920
  step,
@@ -47859,7 +47922,7 @@ async function onePassContent(page, ctx, paths, measure) {
47859
47922
  url: page.url(),
47860
47923
  ok: nav.ok && !broken,
47861
47924
  ...nav.prefetched !== undefined ? { prefetched: nav.prefetched } : {},
47862
- note: labelGotoFallback(!nav.landed ? `${path} — navegação não trocou de página` : !nav.ok ? `atingiu o cap de espera sem sinal de prontidão (${path})` : broken ? "página não encontrada / erro" : path, nav.viaFallback)
47925
+ note: labelGotoFallback(!nav.landed ? `${path} — navegação não trocou de página` : !nav.ok ? `atingiu o cap de espera sem conteúdo pronto (${path})` : broken ? "página não encontrada / erro" : path, nav.viaFallback)
47863
47926
  };
47864
47927
  };
47865
47928
  const nav1 = await hop("nav-to-page-1", paths.pageA);
@@ -49204,8 +49267,10 @@ async function benchmarkCommand(opts) {
49204
49267
  }
49205
49268
  }
49206
49269
  } catch {}
49207
- const journey = opts.journey === "content" || opts.journey === "commerce" ? opts.journey : detectSiteProfile({ url: opts.prod, html: prodHomeHtml }) === "content" ? "content" : "commerce";
49208
- console.log(chalk5.dim(` journey: ${journey}${opts.journey ? "" : " (auto)"}`));
49270
+ const pinnedPages = opts.pages?.split(",").map((p) => p.trim()).filter(Boolean);
49271
+ const journey = opts.journey === "content" || opts.journey === "commerce" ? opts.journey : pinnedPages?.length || detectSiteProfile({ url: opts.prod, html: prodHomeHtml }) === "content" ? "content" : "commerce";
49272
+ const journeyWhy = opts.journey ? "" : pinnedPages?.length ? " (--pages)" : " (auto)";
49273
+ console.log(chalk5.dim(` journey: ${journey}${journeyWhy}`));
49209
49274
  const spinner = ora2("Lançando browser…").start();
49210
49275
  const sides = [];
49211
49276
  let favicon = null;
@@ -49247,7 +49312,8 @@ async function benchmarkCommand(opts) {
49247
49312
  learned,
49248
49313
  platform,
49249
49314
  outDir: paths.screenshotsDir,
49250
- onEvent
49315
+ onEvent,
49316
+ pages: pinnedPages
49251
49317
  });
49252
49318
  if (!contentPaths) {
49253
49319
  console.error(chalk5.red(`
@@ -63414,6 +63480,32 @@ function planBoard(plan, candUrl) {
63414
63480
  }
63415
63481
  return { url: plan.url, columns, shell, unassigned, sampled: plan.pages.length };
63416
63482
  }
63483
+ function mergeScopedBoards(scoped, candUrl) {
63484
+ const merged = {
63485
+ url: [...new Set(scoped.map((s) => s.plan.url))].join(", "),
63486
+ columns: { triage: [], backlog: [], building: [], review: [], done: [], skipped: [] },
63487
+ shell: [],
63488
+ unassigned: [],
63489
+ sampled: 0
63490
+ };
63491
+ const rows = new Map;
63492
+ for (const { scope, plan } of scoped) {
63493
+ const board = planBoard(plan, candUrl);
63494
+ for (const column of Object.keys(board.columns)) {
63495
+ merged.columns[column].push(...board.columns[column].map((card) => ({ ...card, scope })));
63496
+ }
63497
+ merged.shell.push(...board.shell.map((name) => `${scope}: ${name}`));
63498
+ merged.unassigned.push(...board.unassigned.map((name) => `${scope}: ${name}`));
63499
+ merged.sampled += board.sampled;
63500
+ for (const c of plan.components) {
63501
+ const entry = rows.get(key(c.name)) ?? { component: c.name, rows: [] };
63502
+ entry.rows.push({ scope, status: c.status, disposition: disposition(c) });
63503
+ rows.set(key(c.name), entry);
63504
+ }
63505
+ }
63506
+ const conflicts = [...rows.values()].filter((e) => new Set(e.rows.map((r) => `${r.status}/${r.disposition}`)).size > 1);
63507
+ return { ...merged, conflicts };
63508
+ }
63417
63509
  function setComponentVerified(plan, name, verdict, at, note) {
63418
63510
  const k = key(name);
63419
63511
  const component = plan.components.find((c) => key(c.name) === k);
@@ -67996,6 +68088,7 @@ async function migrateCommand(opts) {
67996
68088
  const host = safeHost6(opts.url);
67997
68089
  const runDir = resolve7(opts.outDir, host);
67998
68090
  mkdirSync16(runDir, { recursive: true });
68091
+ const auth = opts.storageState ? { storageState: opts.storageState } : {};
67999
68092
  const browser = await launchBrowser({ headless: true });
68000
68093
  try {
68001
68094
  const themePath = resolve7(runDir, "theme.json");
@@ -68024,7 +68117,7 @@ async function migrateCommand(opts) {
68024
68117
  let platformSeen = null;
68025
68118
  let assetsResolved = null;
68026
68119
  for (const vp of viewports) {
68027
- const ctx = await newContext(browser, { viewport: vp, keepMotion: true });
68120
+ const ctx = await newContext(browser, { viewport: vp, keepMotion: true, ...auth });
68028
68121
  const page = await ctx.newPage();
68029
68122
  try {
68030
68123
  await page.goto(opts.url, { waitUntil: "domcontentloaded", timeout: 30000 });
@@ -68083,7 +68176,7 @@ async function migrateCommand(opts) {
68083
68176
  console.log(chalk22.dim(` phase 2 sitemap: cached (${resolvedPages.length} page(s))`));
68084
68177
  } else {
68085
68178
  console.log(chalk22.dim(" phase 2 sitemap: resolving pages…"));
68086
- const ctx = await newContext(browser, { viewport: primaryViewport });
68179
+ const ctx = await newContext(browser, { viewport: primaryViewport, ...auth });
68087
68180
  const page = await ctx.newPage();
68088
68181
  let sitemapUrls = [];
68089
68182
  try {
@@ -68137,6 +68230,7 @@ async function migrateCommand(opts) {
68137
68230
  runDir,
68138
68231
  baseUrl: opts.url,
68139
68232
  vtexScrape: opts.source ? source.kind === "vtex-io" : true,
68233
+ auth,
68140
68234
  extraViewports: opts.componentViewports ? viewports.slice(1) : []
68141
68235
  }));
68142
68236
  writeFileSync25(capturePath, `${JSON.stringify({ pages, components, vtexBlocks, contentMap }, null, 2)}
@@ -68246,7 +68340,7 @@ async function capturePages(browser, viewport, resolvedPages, theme, cfg) {
68246
68340
  const blocksByPath = new Map;
68247
68341
  const contentMap = {};
68248
68342
  for (const target of resolvedPages) {
68249
- const ctx = await newContext(browser, { viewport, keepMotion: true });
68343
+ const ctx = await newContext(browser, { viewport, keepMotion: true, ...cfg.auth });
68250
68344
  const page = await ctx.newPage();
68251
68345
  const pageComponents = [];
68252
68346
  const capturedHere = [];
@@ -68311,7 +68405,7 @@ async function capturePages(browser, viewport, resolvedPages, theme, cfg) {
68311
68405
  });
68312
68406
  }
68313
68407
  if (cfg.extraViewports.length && capturedHere.length) {
68314
- await captureViewportVariants(browser, target.url, cfg.extraViewports, capturedHere, cfg.runDir);
68408
+ await captureViewportVariants(browser, target.url, cfg.extraViewports, capturedHere, cfg.runDir, cfg.auth);
68315
68409
  }
68316
68410
  }
68317
68411
  return {
@@ -68321,14 +68415,14 @@ async function capturePages(browser, viewport, resolvedPages, theme, cfg) {
68321
68415
  contentMap
68322
68416
  };
68323
68417
  }
68324
- async function captureViewportVariants(browser, url, extraViewports, captured, runDir) {
68418
+ async function captureViewportVariants(browser, url, extraViewports, captured, runDir, auth = {}) {
68325
68419
  const perComponent = captured.map(() => []);
68326
68420
  for (const vp of extraViewports) {
68327
68421
  let ctx;
68328
68422
  let page;
68329
68423
  let done = 0;
68330
68424
  try {
68331
- ctx = await newContext(browser, { viewport: vp });
68425
+ ctx = await newContext(browser, { viewport: vp, ...auth });
68332
68426
  page = await ctx.newPage();
68333
68427
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 });
68334
68428
  await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
@@ -68848,14 +68942,21 @@ var COLUMN_STYLE = {
68848
68942
  done: chalk23.green,
68849
68943
  skipped: chalk23.gray
68850
68944
  };
68851
- async function planBoardCommand(dir, opts) {
68852
- const plan = loadPlan(dir);
68853
- if (!plan) {
68854
- console.error(chalk23.red(`No migration-plan.json found in ${dir}`));
68855
- console.error(chalk23.yellow("Run `parity migrate --url <prod>` first — no plan, no board."));
68856
- return 1;
68945
+ async function planBoardCommand(dirs, opts) {
68946
+ const list = typeof dirs === "string" ? [dirs] : dirs;
68947
+ const scoped = [];
68948
+ for (const scope of list) {
68949
+ const plan = loadPlan(scope);
68950
+ if (!plan) {
68951
+ console.error(chalk23.red(`No migration-plan.json found in ${scope}`));
68952
+ console.error(chalk23.yellow("Run `parity migrate --url <prod>` first — no plan, no board."));
68953
+ return 1;
68954
+ }
68955
+ scoped.push({ scope, plan });
68857
68956
  }
68858
- const board = planBoard(plan, opts.cand);
68957
+ const dir = list[0];
68958
+ const plan = scoped[0].plan;
68959
+ const board = scoped.length > 1 ? mergeScopedBoards(scoped, opts.cand) : planBoard(plan, opts.cand);
68859
68960
  if (opts.json) {
68860
68961
  console.log(JSON.stringify(board, null, 2));
68861
68962
  return 0;
@@ -68874,7 +68975,8 @@ ${chalk23.bold("shell")} ${chalk23.gray("(global — blocks every page)")}: ${ch
68874
68975
  console.log(`
68875
68976
  ${COLUMN_STYLE[column](chalk23.bold(column))} (${cards.length})`);
68876
68977
  for (const card of cards) {
68877
- console.log(` ${card.path} ${chalk23.gray(`(${card.kind})`)}`);
68978
+ const scope = card.scope ? chalk23.cyan(`[${card.scope}] `) : "";
68979
+ console.log(` ${scope}${card.path} ${chalk23.gray(`(${card.kind})`)}`);
68878
68980
  if (card.blockers.length) {
68879
68981
  console.log(chalk23.gray(` blocked by: ${card.blockers.join(", ")}`));
68880
68982
  }
@@ -68883,7 +68985,14 @@ ${COLUMN_STYLE[column](chalk23.bold(column))} (${cards.length})`);
68883
68985
  const skipped = board.columns.skipped;
68884
68986
  if (skipped.length) {
68885
68987
  console.log(`
68886
- ${chalk23.gray(`skipped (${skipped.length}): ${skipped.map((c) => c.path).join(", ")}`)}`);
68988
+ ${chalk23.gray(`skipped (${skipped.length}): ${skipped.map((c) => c.scope ? `[${c.scope}] ${c.path}` : c.path).join(", ")}`)}`);
68989
+ }
68990
+ if (board.conflicts?.length) {
68991
+ console.log(`
68992
+ ${chalk23.red.bold("conflicts")} ${chalk23.gray("(same component, different state per scope — settle by hand)")}`);
68993
+ for (const c of board.conflicts) {
68994
+ console.log(` ${c.component}: ${c.rows.map((r) => `[${r.scope}] ${r.status} (${r.disposition})`).join(" vs ")}`);
68995
+ }
68887
68996
  }
68888
68997
  if (board.unassigned.length) {
68889
68998
  console.log(`
@@ -68891,6 +69000,11 @@ ${chalk23.bold("no page")} ${chalk23.gray("(in the code, not seen on any sampled
68891
69000
  ${chalk23.gray(board.unassigned.join(", "))}`);
68892
69001
  }
68893
69002
  console.log("");
69003
+ if (opts.board === "studio" && scoped.length > 1) {
69004
+ console.log(chalk23.yellow(`Studio board skipped — push one --dir at a time.
69005
+ `));
69006
+ return 0;
69007
+ }
68894
69008
  if (opts.board === "studio") {
68895
69009
  const cfg = studioConfigFromEnv();
68896
69010
  if (!cfg) {
@@ -76600,6 +76714,8 @@ async function heatmapCommand(opts) {
76600
76714
  candUrl: opts.cand,
76601
76715
  selector,
76602
76716
  candSelector,
76717
+ prodStorageState: opts.prodStorageState,
76718
+ candStorageState: opts.candStorageState,
76603
76719
  waitMs,
76604
76720
  outDir: opts.outDir,
76605
76721
  prefix
@@ -76638,6 +76754,7 @@ async function compareViewport(browser, args) {
76638
76754
  spec,
76639
76755
  url: args.prodUrl,
76640
76756
  selector: args.selector,
76757
+ storageState: args.prodStorageState,
76641
76758
  waitMs: args.waitMs,
76642
76759
  outPath: paths.prod,
76643
76760
  repeatPath: paths.prodRepeat
@@ -76646,6 +76763,7 @@ async function compareViewport(browser, args) {
76646
76763
  spec,
76647
76764
  url: args.candUrl,
76648
76765
  selector: args.candSelector,
76766
+ storageState: args.candStorageState,
76649
76767
  waitMs: args.waitMs,
76650
76768
  outPath: paths.cand,
76651
76769
  repeatPath: null
@@ -76958,7 +77076,8 @@ async function captureSide(browser, args) {
76958
77076
  viewport: args.spec.viewport,
76959
77077
  viewportSize: args.spec.size ?? undefined,
76960
77078
  deviceScaleFactor: 1,
76961
- hideScrollbars: true
77079
+ hideScrollbars: true,
77080
+ ...args.storageState ? { storageState: args.storageState } : {}
76962
77081
  });
76963
77082
  const page = await ctx.newPage();
76964
77083
  try {
@@ -77377,6 +77496,99 @@ async function overlayCommand(opts) {
77377
77496
 
77378
77497
  // src/commands/states.ts
77379
77498
  import chalk37 from "chalk";
77499
+ var ROOT_ATTR = "data-parity-states";
77500
+ var rootSelector = (i) => `[${ROOT_ATTR}="${i}"]`;
77501
+ function resolveStateRoots(args) {
77502
+ const PRICE = /(?:R\$|US\$|\$|€|£|¥)\s?\d|\d[.,]\d{2}\s?(?:€|zł|kr)/;
77503
+ const linkOf = (el) => el.closest("a[href]") ?? el.querySelector("a[href]");
77504
+ const isCard = (el) => !!el.querySelector("img") && !!linkOf(el) && PRICE.test(el.textContent ?? "");
77505
+ const visible = (el) => {
77506
+ const check = el.checkVisibility;
77507
+ return typeof check === "function" ? check.call(el) : true;
77508
+ };
77509
+ const text = (el) => (el.textContent ?? "").replace(/\s+/g, " ").trim();
77510
+ let all;
77511
+ try {
77512
+ all = Array.from(document.querySelectorAll(args.selector));
77513
+ } catch (err) {
77514
+ return { kind: "none", error: String(err) };
77515
+ }
77516
+ const shown = all.filter(visible);
77517
+ if (shown.length === 0)
77518
+ return { kind: "none" };
77519
+ const first = shown[0];
77520
+ if (shown.length === 1) {
77521
+ first.setAttribute(args.attr, "0");
77522
+ return { kind: "single", isCard: isCard(first) };
77523
+ }
77524
+ const cards = shown.filter(isCard);
77525
+ const inner = cards.filter((c) => !cards.some((o) => o !== c && c.contains(o)));
77526
+ if (inner.length === 0) {
77527
+ return {
77528
+ kind: "ambiguous",
77529
+ total: shown.length,
77530
+ samples: shown.slice(0, 5).map((el) => `${el.tagName.toLowerCase()} "${text(el).slice(0, 40)}"`)
77531
+ };
77532
+ }
77533
+ const take = inner.slice(0, args.max);
77534
+ take.forEach((el, i) => el.setAttribute(args.attr, String(i)));
77535
+ return {
77536
+ kind: "cards",
77537
+ total: inner.length,
77538
+ ignored: shown.length - inner.length,
77539
+ labels: take.map((el) => {
77540
+ const name = el.querySelector("img[alt]")?.getAttribute("alt") ?? linkOf(el)?.getAttribute("aria-label") ?? linkOf(el)?.getAttribute("title") ?? "";
77541
+ return name.replace(/\s+/g, " ").trim().toLowerCase() || null;
77542
+ })
77543
+ };
77544
+ }
77545
+ function pairRoots(prod, cand) {
77546
+ const unique = (labels) => {
77547
+ const seen = new Map;
77548
+ labels.forEach((l, i) => {
77549
+ if (l)
77550
+ seen.set(l, seen.has(l) ? null : i);
77551
+ });
77552
+ return seen;
77553
+ };
77554
+ const p = unique(prod);
77555
+ const c = unique(cand);
77556
+ const pairs = [];
77557
+ const usedP = new Set;
77558
+ const usedC = new Set;
77559
+ for (const [label, pi] of p) {
77560
+ const ci = c.get(label);
77561
+ if (pi === null || ci === null || ci === undefined)
77562
+ continue;
77563
+ pairs.push([pi, ci]);
77564
+ usedP.add(pi);
77565
+ usedC.add(ci);
77566
+ }
77567
+ const restP = prod.map((_, i) => i).filter((i) => !usedP.has(i));
77568
+ const restC = cand.map((_, i) => i).filter((i) => !usedC.has(i));
77569
+ const n = Math.min(restP.length, restC.length);
77570
+ for (let k = 0;k < n; k++)
77571
+ pairs.push([restP[k], restC[k]]);
77572
+ pairs.sort((a, b) => a[0] - b[0]);
77573
+ return { pairs, unpairedProd: restP.slice(n), unpairedCand: restC.slice(n) };
77574
+ }
77575
+ function pairSides(prod, cand) {
77576
+ const asList = (r, other) => {
77577
+ if (r.kind === "cards")
77578
+ return r.labels;
77579
+ if (r.kind === "single" && (r.isCard || other.kind === "single"))
77580
+ return [null];
77581
+ return [];
77582
+ };
77583
+ const p = asList(prod, cand);
77584
+ const c = asList(cand, prod);
77585
+ const out = pairRoots(p, c);
77586
+ if (prod.kind === "single" && p.length === 0)
77587
+ out.unpairedProd.push(0);
77588
+ if (cand.kind === "single" && c.length === 0)
77589
+ out.unpairedCand.push(0);
77590
+ return out;
77591
+ }
77380
77592
  var HOVERABLE = "a,button,summary,[role='button'],[role='menuitem'],label";
77381
77593
  var SETTLE_RETRY_FACTOR = 4;
77382
77594
  async function readStateEffects(page, opts) {
@@ -77458,7 +77670,7 @@ async function readStateEffects(page, opts) {
77458
77670
  renumberedNodes: delta.renumbered
77459
77671
  });
77460
77672
  }
77461
- return { effects, truncated: total > take, ambient: ambient.size };
77673
+ return { effects, hoverables: total, ambient: ambient.size };
77462
77674
  }
77463
77675
  var fingerprint = (n) => `${n.tag}\x00${n.label ?? ""}\x00${n.text ?? ""}`;
77464
77676
  async function readDelta(page, selector, base) {
@@ -77486,13 +77698,7 @@ async function gatherStates(browser, opts) {
77486
77698
  keepMotion: true
77487
77699
  });
77488
77700
  const page = await ctx.newPage();
77489
- const out = {
77490
- motion: { found: false, error: "not read" },
77491
- base: null,
77492
- effects: [],
77493
- truncated: false,
77494
- ambient: 0
77495
- };
77701
+ const out = { roots: [] };
77496
77702
  try {
77497
77703
  const res = await page.goto(opts.url, { waitUntil: "domcontentloaded", timeout: 30000 }).catch((err) => err);
77498
77704
  if (res instanceof Error) {
@@ -77508,22 +77714,29 @@ async function gatherStates(browser, opts) {
77508
77714
  return;
77509
77715
  });
77510
77716
  out.settle = (await settlePage(page, { waitMs: opts.waitMs, scroll: false })).settle;
77511
- out.motion = await readMotion(page, opts.selector);
77512
- const base = await readBoxTree(page, opts.selector);
77513
- if (!base.found) {
77514
- out.baseError = base.error;
77515
- return out;
77516
- }
77517
- out.base = base.nodes;
77518
- const { effects, truncated, ambient } = await readStateEffects(page, {
77717
+ const resolution = await page.evaluate(resolveStateRoots, {
77519
77718
  selector: opts.selector,
77520
- base: base.nodes,
77521
- max: opts.maxStates,
77522
- settleMs: opts.settleMs
77719
+ max: opts.maxCards,
77720
+ attr: ROOT_ATTR
77523
77721
  });
77524
- out.effects = effects;
77525
- out.ambient = ambient;
77526
- out.truncated = truncated || base.truncated;
77722
+ out.resolution = resolution;
77723
+ const count = resolution.kind === "single" ? 1 : resolution.kind === "cards" ? resolution.labels.length : 0;
77724
+ for (let i = 0;i < count; i++) {
77725
+ const selector = rootSelector(i);
77726
+ const motion = await readMotion(page, selector);
77727
+ const base = await readBoxTree(page, selector);
77728
+ if (!base.found) {
77729
+ out.baseError = base.error;
77730
+ return out;
77731
+ }
77732
+ const { effects, hoverables, ambient } = await readStateEffects(page, {
77733
+ selector,
77734
+ base: base.nodes,
77735
+ max: opts.maxStates,
77736
+ settleMs: opts.settleMs
77737
+ });
77738
+ out.roots.push({ motion, effects, hoverables, ambient, boxTruncated: base.truncated });
77739
+ }
77527
77740
  } finally {
77528
77741
  await page.close().catch(() => {
77529
77742
  return;
@@ -77597,6 +77810,7 @@ async function statesCommand(opts) {
77597
77810
  const waitMs = Number.parseInt(opts.wait, 10) || 0;
77598
77811
  const maxStates = Math.max(1, Number.parseInt(opts.maxStates ?? "12", 10) || 12);
77599
77812
  const settleMs = Math.max(0, Number.parseInt(opts.hoverSettle ?? "250", 10) || 250);
77813
+ const maxCards = Math.max(1, Number.parseInt(opts.maxCards ?? "4", 10) || 4);
77600
77814
  const prodSelector = opts.prodSelector?.trim() || opts.selector?.trim();
77601
77815
  const candSelector = opts.candSelector?.trim() || opts.selector?.trim();
77602
77816
  if (!prodSelector || !candSelector) {
@@ -77615,6 +77829,7 @@ async function statesCommand(opts) {
77615
77829
  viewport,
77616
77830
  waitMs,
77617
77831
  maxStates,
77832
+ maxCards,
77618
77833
  settleMs
77619
77834
  }),
77620
77835
  gatherStates(browser, {
@@ -77623,6 +77838,7 @@ async function statesCommand(opts) {
77623
77838
  viewport,
77624
77839
  waitMs,
77625
77840
  maxStates,
77841
+ maxCards,
77626
77842
  settleMs
77627
77843
  })
77628
77844
  ]);
@@ -77631,16 +77847,73 @@ async function statesCommand(opts) {
77631
77847
  console.error(chalk37.red(` não foi possível ler o componente — ${which}`));
77632
77848
  return 2;
77633
77849
  }
77634
- const motion = prodSide.motion.found && candSide.motion.found ? diffMotion(prodSide.motion, candSide.motion, {
77635
- truncated: prodSide.truncated || candSide.truncated,
77636
- aliases
77637
- }) : null;
77638
- const effects = diffEffects(prodSide.effects, candSide.effects);
77639
- const { exercised, inconclusive } = statesVerdict({
77640
- prodEffects: prodSide.effects.length,
77641
- candEffects: candSide.effects.length,
77850
+ for (const [name, side, sel] of [
77851
+ ["prod", prodSide, prodSelector],
77852
+ ["cand", candSide, candSelector]
77853
+ ]) {
77854
+ const r = side.resolution;
77855
+ if (r?.kind === "ambiguous") {
77856
+ console.error(chalk37.red(` ${name}: ${sel} matches ${r.total} visible elements and none looks like a product card (image + link + price). Narrow it to one:`));
77857
+ for (const sample of r.samples)
77858
+ console.error(chalk37.dim(` ${sample}`));
77859
+ return 2;
77860
+ }
77861
+ if (!r || r.kind === "none") {
77862
+ console.error(chalk37.red(` ${name}: ${sel} matches no visible element${r?.error ? ` — ${r.error}` : ""}`));
77863
+ return 2;
77864
+ }
77865
+ }
77866
+ const pairing = pairSides(prodSide.resolution, candSide.resolution);
77867
+ const cardMode = prodSide.resolution?.kind === "cards" || candSide.resolution?.kind === "cards";
77868
+ const flatten = (side, pick) => {
77869
+ const effects = [];
77870
+ const nodes = [];
77871
+ let motionError;
77872
+ let truncated = false;
77873
+ pairing.pairs.forEach((pair, k) => {
77874
+ const root = side.roots[pair[pick]];
77875
+ const tag = (s) => cardMode ? `card#${k + 1} ${s}` : s;
77876
+ const tagLabel = (l) => cardMode && l ? tag(l) : l;
77877
+ for (const e of root.effects)
77878
+ effects.push({ ...e, target: tag(e.target), label: tagLabel(e.label) });
77879
+ if (root.motion.found) {
77880
+ truncated ||= root.motion.truncated;
77881
+ for (const n of root.motion.nodes)
77882
+ nodes.push({ ...n, key: tag(n.key), label: tagLabel(n.label) });
77883
+ } else
77884
+ motionError ??= root.motion.error;
77885
+ truncated ||= root.boxTruncated;
77886
+ });
77887
+ const motion = motionError ? null : { found: true, nodes, truncated };
77888
+ return { effects, motion, motionError, truncated };
77889
+ };
77890
+ const prodFlat = flatten(prodSide, 0);
77891
+ const candFlat = flatten(candSide, 1);
77892
+ const truncated = prodFlat.truncated || candFlat.truncated;
77893
+ const motion = prodFlat.motion && candFlat.motion ? diffMotion(prodFlat.motion, candFlat.motion, { truncated, aliases }) : null;
77894
+ const effects = diffEffects(prodFlat.effects, candFlat.effects);
77895
+ const verdict = statesVerdict({
77896
+ prodEffects: prodFlat.effects.length,
77897
+ candEffects: candFlat.effects.length,
77642
77898
  motionMatched: motion?.matched ?? 0
77643
77899
  });
77900
+ const { exercised } = verdict;
77901
+ const inconclusive = verdict.inconclusive || pairing.pairs.length === 0;
77902
+ const caps = [];
77903
+ for (const [name, side] of [
77904
+ ["prod", prodSide],
77905
+ ["cand", candSide]
77906
+ ]) {
77907
+ const r = side.resolution;
77908
+ if (r?.kind === "cards" && r.total > r.labels.length) {
77909
+ caps.push(`${name}: compared ${r.labels.length} of ${r.total} product cards; raise with --max-cards N`);
77910
+ }
77911
+ const hoverables = side.roots.reduce((n, root) => n + root.hoverables, 0);
77912
+ const hovered = side.roots.reduce((n, root) => n + Math.min(root.hoverables, maxStates), 0);
77913
+ if (hoverables > hovered) {
77914
+ caps.push(`${name}: hovered ${hovered} of ${hoverables} interactive elements; raise with --max-states N (per ${cardMode ? "card" : "component"})`);
77915
+ }
77916
+ }
77644
77917
  if (opts.json) {
77645
77918
  console.log(JSON.stringify({
77646
77919
  prod: opts.prod,
@@ -77650,11 +77923,14 @@ async function statesCommand(opts) {
77650
77923
  candSelector,
77651
77924
  viewport,
77652
77925
  motion,
77653
- motionError: prodSide.motion.found ? undefined : prodSide.motion.error,
77926
+ motionError: prodFlat.motionError ?? candFlat.motionError,
77654
77927
  effects,
77655
- prodEffects: prodSide.effects,
77656
- candEffects: candSide.effects,
77657
- truncated: prodSide.truncated || candSide.truncated,
77928
+ prodEffects: prodFlat.effects,
77929
+ candEffects: candFlat.effects,
77930
+ truncated: truncated || caps.length > 0,
77931
+ roots: { prod: prodSide.resolution, cand: candSide.resolution },
77932
+ pairing,
77933
+ caps,
77658
77934
  settle: { prod: prodSide.settle, cand: candSide.settle }
77659
77935
  }));
77660
77936
  return inconclusive || effects.lost.length > 0 || (motion?.findings.length ?? 0) > 0 ? 1 : 0;
@@ -77667,18 +77943,43 @@ async function statesCommand(opts) {
77667
77943
  if (caveat)
77668
77944
  console.log(chalk37.yellow(` ${caveat}`));
77669
77945
  }
77946
+ if (cardMode) {
77947
+ console.log("");
77948
+ console.log(chalk37.bold(` Product cards: ${pairing.pairs.length} pair(s) — ${pairing.pairs.map(([p, c]) => `prod #${p + 1} ↔ cand #${c + 1}`).join(", ") || "none"}`));
77949
+ for (const [name, side] of [
77950
+ ["prod", prodSide],
77951
+ ["cand", candSide]
77952
+ ]) {
77953
+ const r = side.resolution;
77954
+ if (r?.kind === "cards" && r.ignored > 0) {
77955
+ console.log(chalk37.dim(` ${name}: ${r.ignored} matched element(s) are not product cards and were ignored`));
77956
+ }
77957
+ if (r?.kind === "single" && !r.isCard) {
77958
+ console.log(chalk37.yellow(` ${name}: the selector names one element that is not a product card; it is never paired with a card`));
77959
+ }
77960
+ }
77961
+ const unpaired = [
77962
+ ...pairing.unpairedProd.map((i) => `prod #${i + 1}`),
77963
+ ...pairing.unpairedCand.map((i) => `cand #${i + 1}`)
77964
+ ];
77965
+ if (unpaired.length)
77966
+ console.log(chalk37.dim(` UNPAIRED cards: ${unpaired.join(", ")} — not compared`));
77967
+ if (pairing.pairs.length === 0) {
77968
+ console.log(chalk37.yellow(" INCONCLUSIVE — no card paired, so nothing was compared."));
77969
+ }
77970
+ }
77670
77971
  console.log("");
77671
77972
  console.log(chalk37.bold(" Declared motion"));
77672
77973
  if (!motion) {
77673
- const err = prodSide.motion.found ? candSide.motion : prodSide.motion;
77674
- console.log(chalk37.yellow(` não foi possível comparar — ${"error" in err ? err.error : "?"}`));
77974
+ const err = prodFlat.motionError ?? candFlat.motionError ?? "nothing paired";
77975
+ console.log(chalk37.yellow(` não foi possível comparar — ${err}`));
77675
77976
  } else {
77676
77977
  for (const line of formatMotionDiff(motion).split(`
77677
77978
  `))
77678
77979
  console.log(` ${line}`);
77679
77980
  }
77680
77981
  console.log("");
77681
- console.log(chalk37.bold(` Hover effects (${prodSide.effects.length} prod / ${candSide.effects.length} cand)`));
77982
+ console.log(chalk37.bold(` Hover effects (${prodFlat.effects.length} prod / ${candFlat.effects.length} cand)`));
77682
77983
  const nothing = effects.lost.length === 0 && effects.changed.length === 0 && effects.added.length === 0 && effects.unpaired.length === 0;
77683
77984
  if (nothing && !exercised) {
77684
77985
  console.log(chalk37.yellow(" INCONCLUSIVE — no hover changed anything on either side, so nothing was exercised. Check the selector holds an interactive element."));
@@ -77712,11 +78013,15 @@ async function statesCommand(opts) {
77712
78013
  console.log("");
77713
78014
  console.log(chalk37.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.`));
77714
78015
  }
77715
- if (prodSide.ambient > 0 || candSide.ambient > 0) {
77716
- console.log(chalk37.dim(` ${prodSide.ambient} prod / ${candSide.ambient} 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.`));
78016
+ const prodAmbient = prodSide.roots.reduce((n, r) => n + r.ambient, 0);
78017
+ const candAmbient = candSide.roots.reduce((n, r) => n + r.ambient, 0);
78018
+ if (prodAmbient > 0 || candAmbient > 0) {
78019
+ console.log(chalk37.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.`));
77717
78020
  }
77718
- if (prodSide.truncated || candSide.truncated) {
77719
- console.log(chalk37.dim(" TRUNCATED — element cap hit; absence of a finding is not proof"));
78021
+ for (const cap of caps)
78022
+ console.log(chalk37.yellow(` CAPPED — ${cap}; absence of a finding is not proof`));
78023
+ if (truncated) {
78024
+ console.log(chalk37.dim(" TRUNCATED — box-tree or motion node cap hit; absence of a finding is not proof"));
77720
78025
  }
77721
78026
  return inconclusive || effects.lost.length > 0 || (motion?.findings.length ?? 0) > 0 ? 1 : 0;
77722
78027
  } finally {
@@ -78481,8 +78786,8 @@ program.command("plan").description("Inspect/update the migration-plan.json comp
78481
78786
  process.exit(planStatusCommand(opts.dir, Boolean(opts.json)));
78482
78787
  })).addCommand(new Command("page").description("Per-page worksheet: every component the capture saw on this page, what to do about it (build | validate | upgrade | as-is | settled), and a runnable `parity section` command for the checkable ones. The unit of work a migration closes is a page, not a global queue.").argument("<path>", "Page path, e.g. / or /refrigeracion").option("--dir <path>", "Directory holding migration-plan.json (default: the target repo's .parity/)", ".parity").option("--cand <url>", "Candidate base URL — required for runnable validation commands").option("--json", "Emit structured JSON instead of human-readable text", false).action((path, opts) => {
78483
78788
  process.exit(planPageCommand(opts.dir, path, { cand: opts.cand, json: Boolean(opts.json) }));
78484
- })).addCommand(new Command("board").description("Per-page kanban: every sampled page in a derived lane (triage | backlog | building | review | done) with what blocks it. Lanes come from each page's components, so a page cannot read as done while a component it needs is missing.").option("--dir <path>", "Directory holding migration-plan.json (default: the target repo's .parity/)", ".parity").option("--cand <url>", "Candidate base URL — enriches cards with validation state").option("--board <where>", "terminal (default) | studio — push one card per page to the deco Studio task board (uses the `bunx decocms auth login` session, or PARITY_STUDIO_URL + PARITY_STUDIO_TOKEN; falls back to terminal when unset or unreachable)", "terminal").option("--repo <owner/name>", "Repository stored on each card, so the board knows where the work lives").option("--fixes <path>", "JSON file of client-legible fixes to mirror as cards: [{title, body?, prUrl?, state: open|in_review|closed}]").option("--json", "Emit structured JSON instead of human-readable text", false).action(async (opts) => {
78485
- process.exit(await planBoardCommand(opts.dir, {
78789
+ })).addCommand(new Command("board").description("Per-page kanban: every sampled page in a derived lane (triage | backlog | building | review | done) with what blocks it. Lanes come from each page's components, so a page cannot read as done while a component it needs is missing.").option("--dir <path>", "Directory holding migration-plan.json (default: the target repo's .parity/). Repeat it to merge scoped plans into one board; a component the scopes record differently is listed as a conflict.", (value, previous) => [...previous ?? [], value]).option("--cand <url>", "Candidate base URL — enriches cards with validation state").option("--board <where>", "terminal (default) | studio — push one card per page to the deco Studio task board (uses the `bunx decocms auth login` session, or PARITY_STUDIO_URL + PARITY_STUDIO_TOKEN; falls back to terminal when unset or unreachable)", "terminal").option("--repo <owner/name>", "Repository stored on each card, so the board knows where the work lives").option("--fixes <path>", "JSON file of client-legible fixes to mirror as cards: [{title, body?, prUrl?, state: open|in_review|closed}]").option("--json", "Emit structured JSON instead of human-readable text", false).action(async (opts) => {
78790
+ process.exit(await planBoardCommand(opts.dir ?? [".parity"], {
78486
78791
  cand: opts.cand,
78487
78792
  json: Boolean(opts.json),
78488
78793
  board: opts.board,
@@ -78609,7 +78914,7 @@ program.command("benchmark").description([
78609
78914
  "a HAR, measures Web Vitals with Lighthouse, and emits ONE self-contained HTML report",
78610
78915
  "(PT/EN toggle) you can share with a client."
78611
78916
  ].join(`
78612
- `)).requiredOption("--prod <url>", "Production URL (Fresh — the 'before')").requiredOption("--cand <url>", "Candidate URL (TanStack — the 'after')").option("--viewports <list>", "mobile,desktop (pick one or both)", "mobile,desktop").option("--warmup-runs <n>", "Journey passes to warm caches before measuring", "2").option("--measured-runs <n>", "Measured passes per side (median, kills variance)", "3").option("--paginations <n>", "How many times to scroll/paginate the PLP", "3").option("--pagination-cap-ms <n>", "How long one scroll waits for new cards; slower loads are truncated to this (#274)", "5000").option("--plp <path>", "Pin the PLP path (skip auto-discovery), e.g. /roupas — useful to force a clothing category with real color variants").option("--journey <type>", "Journey shape: commerce (home→PLP→PDP→variant) | content (home→page A→page B, for blog/custom sites with no PLP/PDP). Auto-detected from the platform when omitted. Issue #251.").option("--cep <cep>", "CEP (kept for overlay/region dismissal parity)", "01310-100").option("--output <dir>", "Output directory for runs/<id>/", "./parity-output").option("--no-vitals", "Skip the Lighthouse web-vitals pass (faster iteration)").option("--no-auto-selectors", "Skip LLM-based selector discovery").option("--lang <pt|en>", "Default report language (toggle switches live)", "pt").option("--open", "Open the HTML report when done", false).option("--pt", "Tell the LLM to respond in Brazilian Portuguese. Issue #67.").action(async (opts) => {
78917
+ `)).requiredOption("--prod <url>", "Production URL (Fresh — the 'before')").requiredOption("--cand <url>", "Candidate URL (TanStack — the 'after')").option("--viewports <list>", "mobile,desktop (pick one or both)", "mobile,desktop").option("--warmup-runs <n>", "Journey passes to warm caches before measuring", "2").option("--measured-runs <n>", "Measured passes per side (median, kills variance)", "3").option("--paginations <n>", "How many times to scroll/paginate the PLP", "3").option("--pagination-cap-ms <n>", "How long one scroll waits for new cards; slower loads are truncated to this (#274)", "5000").option("--plp <path>", "Pin the PLP path (skip auto-discovery), e.g. /roupas — useful to force a clothing category with real color variants").option("--journey <type>", "Journey shape: commerce (home→PLP→PDP→variant) | content (home→page A→page B, for blog/custom sites with no PLP/PDP). Auto-detected from the platform when omitted. Issue #251.").option("--pages <paths>", "Content journey: candidate content pages, comma-separated (e.g. /blog,/sobre). The first two that load on BOTH sites are measured, instead of scraping the home nav. Implies --journey content when --journey is omitted").option("--cep <cep>", "CEP (kept for overlay/region dismissal parity)", "01310-100").option("--output <dir>", "Output directory for runs/<id>/", "./parity-output").option("--no-vitals", "Skip the Lighthouse web-vitals pass (faster iteration)").option("--no-auto-selectors", "Skip LLM-based selector discovery").option("--lang <pt|en>", "Default report language (toggle switches live)", "pt").option("--open", "Open the HTML report when done", false).option("--pt", "Tell the LLM to respond in Brazilian Portuguese. Issue #67.").action(async (opts) => {
78613
78918
  if (opts.pt) {
78614
78919
  await Promise.resolve().then(() => init_client());
78615
78920
  setLlmLanguage("pt");
@@ -78662,12 +78967,14 @@ program.command("check").argument("<name>", "check name (kebab-case, e.g. consol
78662
78967
  json: opts.json
78663
78968
  }));
78664
78969
  });
78665
- 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("--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) => {
78970
+ 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) => {
78666
78971
  process.exit(await heatmapCommand({
78667
78972
  prod: opts.prod,
78668
78973
  cand: opts.cand,
78669
78974
  selector: opts.selector,
78670
78975
  candSelector: opts.candSelector,
78976
+ prodStorageState: opts.prodStorageState,
78977
+ candStorageState: opts.candStorageState,
78671
78978
  viewports: opts.viewports,
78672
78979
  wait: opts.wait,
78673
78980
  pr: opts.pr,
@@ -78785,7 +79092,7 @@ program.command("bench").description("Compare ONE component in ISOLATION. Both s
78785
79092
  json: opts.json
78786
79093
  }));
78787
79094
  });
78788
- program.command("states").description("Compare a component's INTERACTIVE states, not just its resting frame. Two deterministic signals: declared motion (transitions, animations and the @keyframes bodies they point at, per interactive element) and hover effects (hover each element in turn, re-read the box tree, and report which effects prod has that cand lost). This is the instrument behind 'the hover effects are not the same' — no LLM, no screenshots to eyeball.").requiredOption("--prod <url>", "Production URL (source of truth)").requiredOption("--cand <url>", "Candidate URL (migrated)").option("--selector <sel>", "CSS selector for the component, on both sides. Shorthand for passing --prod-selector and --cand-selector the same value.").option("--prod-selector <sel>", "CSS selector on the PRODUCTION side. On a legacy-to-modern migration the two sides frequently share no selector at all — a prod PDP with no <main>, a header nine levels deeper than the port's — and widening to `body` to find one string that resolves on both is the worst place to run this. Give each side its own.").option("--cand-selector <sel>", "CSS selector on the CANDIDATE side. Defaults to --selector.").option("--max-states <n>", "How many interactive elements to hover per side. A mega-nav has hundreds of links sharing one hover rule; N distinct effects is the signal.", "12").option("--hover-settle <ms>", "Wait after hovering before re-reading. A pure CSS transition needs none — its end state is already in the computed style on the first frame — but anything gated on a JS timer (hover intent, a debounce) needs the whole timer, and 'moves nothing' measured too early reads exactly like a broken hover. When the first read finds nothing, a second is taken at 4x this before concluding, so a site without hover-intent never pays for one.", "250").option("--viewport <viewport>", "mobile | desktop | tablet", "desktop").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").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) => {
79095
+ program.command("states").description("Compare a component's INTERACTIVE states, not just its resting frame. Two deterministic signals: declared motion (transitions, animations and the @keyframes bodies they point at, per interactive element) and hover effects (hover each element in turn, re-read the box tree, and report which effects prod has that cand lost). This is the instrument behind 'the hover effects are not the same' — no LLM, no screenshots to eyeball.").requiredOption("--prod <url>", "Production URL (source of truth)").requiredOption("--cand <url>", "Candidate URL (migrated)").option("--selector <sel>", "CSS selector for the component, on both sides. Shorthand for passing --prod-selector and --cand-selector the same value.").option("--prod-selector <sel>", "CSS selector on the PRODUCTION side. On a legacy-to-modern migration the two sides frequently share no selector at all — a prod PDP with no <main>, a header nine levels deeper than the port's — and widening to `body` to find one string that resolves on both is the worst place to run this. Give each side its own.").option("--cand-selector <sel>", "CSS selector on the CANDIDATE side. Defaults to --selector.").option("--max-states <n>", "How many interactive elements to hover per component (per card when the selector matches product cards). A mega-nav has hundreds of links sharing one hover rule; N distinct effects is the signal. The output says when the cap cut anything.", "12").option("--max-cards <n>", "When a selector matches several visible elements, the ones that look like a product card (image + link + price) are measured one by one and paired by product name, then by position. This caps how many per side.", "4").option("--hover-settle <ms>", "Wait after hovering before re-reading. A pure CSS transition needs none — its end state is already in the computed style on the first frame — but anything gated on a JS timer (hover intent, a debounce) needs the whole timer, and 'moves nothing' measured too early reads exactly like a broken hover. When the first read finds nothing, a second is taken at 4x this before concluding, so a site without hover-intent never pays for one.", "250").option("--viewport <viewport>", "mobile | desktop | tablet", "desktop").option("--wait <ms>", "Extra ms after networkidle so hydration settles", "2000").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) => {
78789
79096
  process.exit(await statesCommand({
78790
79097
  planDir: opts.planDir,
78791
79098
  prod: opts.prod,
@@ -78794,6 +79101,7 @@ program.command("states").description("Compare a component's INTERACTIVE states,
78794
79101
  prodSelector: opts.prodSelector,
78795
79102
  candSelector: opts.candSelector,
78796
79103
  maxStates: opts.maxStates,
79104
+ maxCards: opts.maxCards,
78797
79105
  hoverSettle: opts.hoverSettle,
78798
79106
  viewport: opts.viewport,
78799
79107
  wait: opts.wait,
@@ -78844,7 +79152,7 @@ program.command("extract").description("Single-site AI-ready component extractio
78844
79152
  }));
78845
79153
  });
78846
79154
  function buildCaptureCommand(name, deprecated) {
78847
- 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("--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) => {
79155
+ 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) => {
78848
79156
  if (deprecated)
78849
79157
  deprecatedNotice("migrate", "capture");
78850
79158
  process.exit(await migrateCommand({
@@ -78859,6 +79167,7 @@ function buildCaptureCommand(name, deprecated) {
78859
79167
  viewports: opts.viewports,
78860
79168
  componentViewports: opts.componentViewports,
78861
79169
  sample: opts.sample,
79170
+ storageState: opts.storageState,
78862
79171
  format: opts.format,
78863
79172
  outDir: opts.out,
78864
79173
  refresh: opts.refresh,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/parity",
3
- "version": "0.33.61",
3
+ "version": "0.33.62",
4
4
  "description": "E2E parity validator for site migrations. Compares prod vs cand and reports UI, functional, SEO, visual, and Web Vitals deltas with an LLM-ranked HTML report.",
5
5
  "type": "module",
6
6
  "license": "MIT",