@decocms/parity 0.35.26 → 0.35.28

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 (3) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/cli.js +750 -264
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -76646,100 +76646,6 @@ function urlPageKey(url, viewport) {
76646
76646
  return `${path}::${viewport}`;
76647
76647
  }
76648
76648
 
76649
- // src/checks/analytics-beacon-parity.ts
76650
- var BEACON_PATTERNS = [
76651
- {
76652
- id: "gtm-container",
76653
- label: "Google Tag Manager (gtm.js)",
76654
- match: (u) => /googletagmanager\.com\/gtm\.js/.test(u)
76655
- },
76656
- {
76657
- id: "gtag-js",
76658
- label: "Google gtag.js / Google Ads",
76659
- match: (u) => /googletagmanager\.com\/gtag\/js/.test(u)
76660
- },
76661
- {
76662
- id: "ga4-collect",
76663
- label: "GA4 collect beacon",
76664
- match: (u) => /google-analytics\.com\/g\/collect|analytics\.google\.com\/g\/collect/.test(u)
76665
- },
76666
- {
76667
- id: "meta-pixel",
76668
- label: "Meta (Facebook) Pixel",
76669
- match: (u) => /connect\.facebook\.(net|com)\/.*\/fbevents\.js|facebook\.com\/tr\//.test(u)
76670
- },
76671
- {
76672
- id: "tiktok-pixel",
76673
- label: "TikTok Pixel",
76674
- match: (u) => /analytics\.tiktok\.com\/i18n\/pixel/.test(u)
76675
- },
76676
- {
76677
- id: "pinterest-tag",
76678
- label: "Pinterest Tag",
76679
- match: (u) => /ct\.pinterest\.com\/v3/.test(u)
76680
- }
76681
- ];
76682
- function analyticsBeaconParity(ctx) {
76683
- const start = Date.now();
76684
- if (ctx.prodPages.length === 0) {
76685
- return skip(start, "sem baseline prod — nada para comparar (single-site)");
76686
- }
76687
- const { pairs } = pairCaptures(ctx.prodPages, ctx.candPages);
76688
- const issues = [];
76689
- let pairsWithAnyBeacon = 0;
76690
- for (const pair of pairs) {
76691
- const prodHits = detectedBeacons(pair.prod);
76692
- const candHits = detectedBeacons(pair.cand);
76693
- if (prodHits.size === 0 && candHits.size === 0)
76694
- continue;
76695
- pairsWithAnyBeacon++;
76696
- for (const pattern of BEACON_PATTERNS) {
76697
- const inProd = prodHits.has(pattern.id);
76698
- const inCand = candHits.has(pattern.id);
76699
- if (inProd && !inCand) {
76700
- issues.push({
76701
- id: `analytics-beacon:missing:${pattern.id}:${pair.key}`,
76702
- severity: "high",
76703
- category: "network",
76704
- page: pair.key,
76705
- check: "analytics-beacon-parity",
76706
- summary: `${pattern.label} disparou em prod mas não no candidato em ${pair.key}`,
76707
- suggestedFix: "Confirme o container/pixel ID no candidato — tag manager ausente derruba TODO o rastreamento a jusante dele, não só este evento."
76708
- });
76709
- }
76710
- }
76711
- }
76712
- const hasHigh = issues.some((i) => i.severity === "high");
76713
- return {
76714
- name: "analytics-beacon-parity",
76715
- status: hasHigh ? "fail" : issues.length > 0 ? "warn" : "pass",
76716
- severity: "high",
76717
- durationMs: Date.now() - start,
76718
- summary: pairsWithAnyBeacon === 0 ? "Nenhum beacon de analytics conhecido observado em nenhum dos lados — nada a validar (ou o site usa uma ferramenta fora da lista de padrões)" : `${issues.length} beacon(s) de analytics perdido(s) em ${pairsWithAnyBeacon} página(s) com tráfego de analytics`,
76719
- issues
76720
- };
76721
- }
76722
- function detectedBeacons(page) {
76723
- const hits = new Set;
76724
- for (const entry of page.network) {
76725
- for (const pattern of BEACON_PATTERNS) {
76726
- if (pattern.match(entry.url))
76727
- hits.add(pattern.id);
76728
- }
76729
- }
76730
- return hits;
76731
- }
76732
- function skip(start, summary) {
76733
- return {
76734
- name: "analytics-beacon-parity",
76735
- status: "skipped",
76736
- severity: "high",
76737
- durationMs: Date.now() - start,
76738
- summary,
76739
- issues: []
76740
- };
76741
- }
76742
-
76743
76649
  // src/diff/dom.ts
76744
76650
  init_esm10();
76745
76651
 
@@ -77400,6 +77306,264 @@ function diffMeta(prod, cand) {
77400
77306
  return out;
77401
77307
  }
77402
77308
 
77309
+ // src/util/localhost.ts
77310
+ var LOCALHOST_HOSTS = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]"]);
77311
+ function isLocalhost(rawUrl) {
77312
+ try {
77313
+ const url = new URL(rawUrl);
77314
+ return LOCALHOST_HOSTS.has(url.hostname);
77315
+ } catch {
77316
+ return false;
77317
+ }
77318
+ }
77319
+
77320
+ // src/checks/lib/staging.ts
77321
+ function isCandOnStagingHost(prodPages, candPages, candIsProduction = false) {
77322
+ if (candIsProduction)
77323
+ return false;
77324
+ if (isCandOnLoopbackHost(prodPages, candPages, candIsProduction))
77325
+ return true;
77326
+ const prodSite = siteHost(prodPages);
77327
+ const candSite = siteHost(candPages);
77328
+ if (!prodSite || !candSite || prodSite === candSite)
77329
+ return false;
77330
+ const { pairs } = pairCaptures(prodPages, candPages);
77331
+ const judged = pairs.filter((p) => bareHost(finalOf(p.prod)) === prodSite && bareHost(finalOf(p.cand)) === candSite && !isNoindex(p.prod) && hasHead(p.cand));
77332
+ if (judged.length === 0)
77333
+ return false;
77334
+ const noindexed = judged.filter((p) => isNoindex(p.cand)).length;
77335
+ return noindexed * 2 > judged.length;
77336
+ }
77337
+ function isCandOnLoopbackHost(prodPages, candPages, candIsProduction = false) {
77338
+ if (candIsProduction)
77339
+ return false;
77340
+ const prodSite = siteHost(prodPages);
77341
+ const candSite = siteHost(candPages);
77342
+ if (!prodSite || !candSite)
77343
+ return false;
77344
+ return isLoopbackHost(candSite) && !isLoopbackHost(prodSite);
77345
+ }
77346
+ function isLoopbackHost(host) {
77347
+ return isLocalhost(`http://${host}/`) || host.endsWith(".localhost") || /^127\./.test(host);
77348
+ }
77349
+ var STAGING_NOTE = "cand está num host de staging (noindex no host inteiro com prod indexável, ou dev server local) — esperado ali; reconfira depois da troca de domínio, ou rode com --cand-is-production se cand já é o domínio final.";
77350
+ function hasHead(page) {
77351
+ const { meta } = snapshotDom(page.html ?? "");
77352
+ return meta.title != null || meta.robots != null || Boolean(page.xRobotsTag);
77353
+ }
77354
+ function isNoindex(page) {
77355
+ const meta = snapshotDom(page.html ?? "").meta.robots ?? "";
77356
+ return /\bnoindex\b/i.test(meta) || /\bnoindex\b/i.test(page.xRobotsTag ?? "");
77357
+ }
77358
+ function finalOf(page) {
77359
+ return page.finalUrl || page.url;
77360
+ }
77361
+ function siteHost(pages) {
77362
+ const counts = new Map;
77363
+ for (const page of pages) {
77364
+ const host = bareHost(finalOf(page));
77365
+ if (host)
77366
+ counts.set(host, (counts.get(host) ?? 0) + 1);
77367
+ }
77368
+ let best = null;
77369
+ for (const [host, n] of counts)
77370
+ if (!best || n > (counts.get(best) ?? 0))
77371
+ best = host;
77372
+ return best;
77373
+ }
77374
+ function bareHost(url) {
77375
+ try {
77376
+ return new URL(url).hostname.replace(/^www\./, "");
77377
+ } catch {
77378
+ return null;
77379
+ }
77380
+ }
77381
+ var SECOND_LEVEL = new Set(["com", "net", "org", "gov", "edu", "co", "ac", "ne", "or", "go"]);
77382
+ function registrableDomain(hostname) {
77383
+ const parts = hostname.split(".");
77384
+ if (parts.length <= 2)
77385
+ return hostname;
77386
+ const sld = parts[parts.length - 2];
77387
+ const tld = parts[parts.length - 1];
77388
+ const take = tld.length === 2 && SECOND_LEVEL.has(sld) ? 3 : 2;
77389
+ return parts.slice(-take).join(".");
77390
+ }
77391
+
77392
+ // src/checks/lib/tag-manager.ts
77393
+ var GTM_CONTAINER_URL = /googletagmanager\.com\/gtm\.js/;
77394
+ function loadsTagManager(page) {
77395
+ return page.network.some((e) => GTM_CONTAINER_URL.test(e.url));
77396
+ }
77397
+ function tagManagerAbsentOnCand(prod, cand) {
77398
+ return loadsTagManager(prod) && !loadsTagManager(cand);
77399
+ }
77400
+ function tagManagerContainerIds(page) {
77401
+ const ids = new Set;
77402
+ for (const e of page.network) {
77403
+ if (GTM_CONTAINER_URL.test(e.url))
77404
+ ids.add(new URL(e.url).searchParams.get("id") ?? "(sem id)");
77405
+ }
77406
+ return [...ids];
77407
+ }
77408
+ var VENDOR_DOMAINS = new Set([
77409
+ "googletagmanager.com",
77410
+ "google-analytics.com",
77411
+ "doubleclick.net",
77412
+ "googleadservices.com",
77413
+ "facebook.net",
77414
+ "facebook.com",
77415
+ "clarity.ms",
77416
+ "bing.com",
77417
+ "hotjar.com",
77418
+ "tiktok.com",
77419
+ "pinterest.com"
77420
+ ]);
77421
+ var GOOGLE_ADS_PATH = /^\/(pagead|ccm|rmkt|ads|g\/collect|j\/collect)(\/|$)/;
77422
+ function tagManagerVendorOrigins(prod) {
77423
+ const googlePaths = new Map;
77424
+ const out = new Set;
77425
+ for (const e of prod.network) {
77426
+ let u;
77427
+ try {
77428
+ u = new URL(e.url);
77429
+ } catch {
77430
+ continue;
77431
+ }
77432
+ const domain = registrableDomain(u.hostname);
77433
+ if (VENDOR_DOMAINS.has(domain))
77434
+ out.add(domain);
77435
+ else if (/^google\./.test(domain)) {
77436
+ googlePaths.set(domain, (googlePaths.get(domain) ?? true) && GOOGLE_ADS_PATH.test(u.pathname));
77437
+ }
77438
+ }
77439
+ for (const [domain, adsOnly] of googlePaths)
77440
+ if (adsOnly)
77441
+ out.add(domain);
77442
+ return out;
77443
+ }
77444
+
77445
+ // src/checks/analytics-beacon-parity.ts
77446
+ var BEACON_PATTERNS = [
77447
+ {
77448
+ id: "gtm-container",
77449
+ label: "Google Tag Manager (gtm.js)",
77450
+ match: (u) => GTM_CONTAINER_URL.test(u)
77451
+ },
77452
+ {
77453
+ id: "gtag-js",
77454
+ label: "Google gtag.js / Google Ads",
77455
+ match: (u) => /googletagmanager\.com\/gtag\/js/.test(u)
77456
+ },
77457
+ {
77458
+ id: "ga4-collect",
77459
+ label: "GA4 collect beacon",
77460
+ match: (u) => /google-analytics\.com\/g\/collect|analytics\.google\.com\/g\/collect/.test(u)
77461
+ },
77462
+ {
77463
+ id: "meta-pixel",
77464
+ label: "Meta (Facebook) Pixel",
77465
+ match: (u) => /connect\.facebook\.(net|com)\/.*\/fbevents\.js|facebook\.com\/tr\//.test(u)
77466
+ },
77467
+ {
77468
+ id: "tiktok-pixel",
77469
+ label: "TikTok Pixel",
77470
+ match: (u) => /analytics\.tiktok\.com\/i18n\/pixel/.test(u)
77471
+ },
77472
+ {
77473
+ id: "pinterest-tag",
77474
+ label: "Pinterest Tag",
77475
+ match: (u) => /ct\.pinterest\.com\/v3/.test(u)
77476
+ }
77477
+ ];
77478
+ function analyticsBeaconParity(ctx) {
77479
+ const start = Date.now();
77480
+ if (ctx.prodPages.length === 0) {
77481
+ return skip(start, "sem baseline prod — nada para comparar (single-site)");
77482
+ }
77483
+ const { pairs } = pairCaptures(ctx.prodPages, ctx.candPages);
77484
+ const issues = [];
77485
+ let pairsWithAnyBeacon = 0;
77486
+ const devServer = isCandOnLoopbackHost(ctx.prodPages, ctx.candPages, ctx.candIsProduction);
77487
+ for (const pair of pairs) {
77488
+ const prodHits = detectedBeacons(pair.prod);
77489
+ const candHits = detectedBeacons(pair.cand);
77490
+ if (prodHits.size === 0 && candHits.size === 0)
77491
+ continue;
77492
+ pairsWithAnyBeacon++;
77493
+ const containerAbsent = tagManagerAbsentOnCand(pair.prod, pair.cand);
77494
+ if (containerAbsent) {
77495
+ const dependents = BEACON_PATTERNS.filter((p) => p.id !== "gtm-container" && prodHits.has(p.id) && !candHits.has(p.id));
77496
+ const containers = tagManagerContainerIds(pair.prod);
77497
+ issues.push({
77498
+ id: `analytics-beacon:tag-manager-absent:${pair.key}`,
77499
+ severity: devServer ? "low" : "high",
77500
+ ...devServer ? { inconclusive: true } : {},
77501
+ category: "network",
77502
+ page: pair.key,
77503
+ check: "analytics-beacon-parity",
77504
+ summary: `Tag manager (${containers.join(", ")}) carregou em prod mas não no candidato em ${pair.key}${dependents.length > 0 ? ` — leva junto: ${dependents.map((d) => d.label).join(", ")}` : " — nenhuma outra tag conhecida de prod ficou de fora"}`,
77505
+ details: `${[
77506
+ `Container: ${containers.join(", ")} (gtm.js ausente no candidato).`,
77507
+ dependents.length > 0 ? `Tags de prod ausentes no candidato, atribuídas ao container:
77508
+ ${dependents.map((d) => ` - ${d.label}`).join(`
77509
+ `)}` : "",
77510
+ "Atribuição presumida, não observada: um snippet hard-coded em prod não se distingue de uma tag injetada pelo container. Corrija o ID do container no candidato e rode de novo antes de procurar cada tag.",
77511
+ devServer ? "cand é um dev server local, onde o rastreamento não é ligado de propósito: informativo. Reconfira num host de preview." : ""
77512
+ ].filter(Boolean).join(`
77513
+
77514
+ `)}`,
77515
+ suggestedFix: "Configure o container ID do tag manager no candidato — sem ele, todo o rastreamento a jusante some junto."
77516
+ });
77517
+ }
77518
+ for (const pattern of BEACON_PATTERNS) {
77519
+ const inProd = prodHits.has(pattern.id);
77520
+ const inCand = candHits.has(pattern.id);
77521
+ if (containerAbsent && inProd && !inCand)
77522
+ continue;
77523
+ if (inProd && !inCand) {
77524
+ issues.push({
77525
+ id: `analytics-beacon:missing:${pattern.id}:${pair.key}`,
77526
+ severity: "high",
77527
+ category: "network",
77528
+ page: pair.key,
77529
+ check: "analytics-beacon-parity",
77530
+ summary: `${pattern.label} disparou em prod mas não no candidato em ${pair.key}`,
77531
+ suggestedFix: "Confirme o container/pixel ID no candidato — tag manager ausente derruba TODO o rastreamento a jusante dele, não só este evento."
77532
+ });
77533
+ }
77534
+ }
77535
+ }
77536
+ const hasHigh = issues.some((i) => i.severity === "high");
77537
+ return {
77538
+ name: "analytics-beacon-parity",
77539
+ status: hasHigh ? "fail" : issues.length > 0 ? "warn" : "pass",
77540
+ severity: "high",
77541
+ durationMs: Date.now() - start,
77542
+ summary: pairsWithAnyBeacon === 0 ? "Nenhum beacon de analytics conhecido observado em nenhum dos lados — nada a validar (ou o site usa uma ferramenta fora da lista de padrões)" : `${issues.length} achado(s) de analytics em ${pairsWithAnyBeacon} página(s) com tráfego de analytics`,
77543
+ issues
77544
+ };
77545
+ }
77546
+ function detectedBeacons(page) {
77547
+ const hits = new Set;
77548
+ for (const entry of page.network) {
77549
+ for (const pattern of BEACON_PATTERNS) {
77550
+ if (pattern.match(entry.url))
77551
+ hits.add(pattern.id);
77552
+ }
77553
+ }
77554
+ return hits;
77555
+ }
77556
+ function skip(start, summary) {
77557
+ return {
77558
+ name: "analytics-beacon-parity",
77559
+ status: "skipped",
77560
+ severity: "high",
77561
+ durationMs: Date.now() - start,
77562
+ summary,
77563
+ issues: []
77564
+ };
77565
+ }
77566
+
77403
77567
  // src/checks/lib/counts.ts
77404
77568
  function unitCounts(args) {
77405
77569
  const judged = new Set(args.judged);
@@ -78255,64 +78419,6 @@ function diffConsole(prod, cand, opts = {}) {
78255
78419
  };
78256
78420
  }
78257
78421
 
78258
- // src/checks/lib/staging.ts
78259
- function isCandOnStagingHost(prodPages, candPages, candIsProduction = false) {
78260
- if (candIsProduction)
78261
- return false;
78262
- const prodSite = siteHost(prodPages);
78263
- const candSite = siteHost(candPages);
78264
- if (!prodSite || !candSite || prodSite === candSite)
78265
- return false;
78266
- const { pairs } = pairCaptures(prodPages, candPages);
78267
- const judged = pairs.filter((p) => bareHost(finalOf(p.prod)) === prodSite && bareHost(finalOf(p.cand)) === candSite && !isNoindex(p.prod) && hasHead(p.cand));
78268
- if (judged.length === 0)
78269
- return false;
78270
- const noindexed = judged.filter((p) => isNoindex(p.cand)).length;
78271
- return noindexed * 2 > judged.length;
78272
- }
78273
- var STAGING_NOTE = "cand está num host de staging (noindex no host inteiro, prod indexável) — esperado ali; reconfira depois da troca de domínio, ou rode com --cand-is-production se cand já é o domínio final.";
78274
- function hasHead(page) {
78275
- const { meta } = snapshotDom(page.html ?? "");
78276
- return meta.title != null || meta.robots != null || Boolean(page.xRobotsTag);
78277
- }
78278
- function isNoindex(page) {
78279
- const meta = snapshotDom(page.html ?? "").meta.robots ?? "";
78280
- return /\bnoindex\b/i.test(meta) || /\bnoindex\b/i.test(page.xRobotsTag ?? "");
78281
- }
78282
- function finalOf(page) {
78283
- return page.finalUrl || page.url;
78284
- }
78285
- function siteHost(pages) {
78286
- const counts = new Map;
78287
- for (const page of pages) {
78288
- const host = bareHost(finalOf(page));
78289
- if (host)
78290
- counts.set(host, (counts.get(host) ?? 0) + 1);
78291
- }
78292
- let best = null;
78293
- for (const [host, n] of counts)
78294
- if (!best || n > (counts.get(best) ?? 0))
78295
- best = host;
78296
- return best;
78297
- }
78298
- function bareHost(url) {
78299
- try {
78300
- return new URL(url).hostname.replace(/^www\./, "");
78301
- } catch {
78302
- return null;
78303
- }
78304
- }
78305
- var SECOND_LEVEL = new Set(["com", "net", "org", "gov", "edu", "co", "ac", "ne", "or", "go"]);
78306
- function registrableDomain(hostname) {
78307
- const parts = hostname.split(".");
78308
- if (parts.length <= 2)
78309
- return hostname;
78310
- const sld = parts[parts.length - 2];
78311
- const tld = parts[parts.length - 1];
78312
- const take = tld.length === 2 && SECOND_LEVEL.has(sld) ? 3 : 2;
78313
- return parts.slice(-take).join(".");
78314
- }
78315
-
78316
78422
  // src/checks/console-errors.ts
78317
78423
  var BENIGN = [/\bTransition was (?:skipped|aborted)\b/i];
78318
78424
  var DETERMINISTIC = new Set(["hydration", "section-crash"]);
@@ -79040,6 +79146,7 @@ function htmlStructuralDiff(ctx) {
79040
79146
  const issues = [];
79041
79147
  const staging = isCandOnStagingHost(ctx.prodPages, ctx.candPages, ctx.candIsProduction);
79042
79148
  const vendorDeltas = [];
79149
+ const tagManagerDeltas = [];
79043
79150
  for (const pair of pairs) {
79044
79151
  const prodSnap = snapshotDom(pair.prod.html ?? "");
79045
79152
  const candSnap = snapshotDom(pair.cand.html ?? "");
@@ -79061,6 +79168,31 @@ function htmlStructuralDiff(ctx) {
79061
79168
  }
79062
79169
  if (lines.length > 0)
79063
79170
  vendorDeltas.push({ page: pair.key, lines });
79171
+ } else if (tagManagerAbsentOnCand(pair.prod, pair.cand)) {
79172
+ const vendors = tagManagerVendorOrigins(pair.prod);
79173
+ const site = new Set([pair.prod, pair.cand].map((p) => hostDomain(p.finalUrl || p.url)).filter(Boolean));
79174
+ const prod = embeds(pair.prod.html ?? "", "scripts", site);
79175
+ const cand = embeds(pair.cand.html ?? "", "scripts", site);
79176
+ const lines = [];
79177
+ let lost = 0;
79178
+ for (const [origin, n] of prod.vendor) {
79179
+ const gone = Math.max(0, n - (cand.vendor.get(origin) ?? 0));
79180
+ if (!vendors.has(origin) || gone === 0)
79181
+ continue;
79182
+ lost += gone;
79183
+ lines.push(`${origin} ×${n}→${cand.vendor.get(origin) ?? 0}`);
79184
+ }
79185
+ const tag = "scripts";
79186
+ const scripts = diff.countsDelta[tag];
79187
+ if (lost > 0 && scripts) {
79188
+ const delta = scripts.delta + lost;
79189
+ if (Math.abs(delta) > COUNT_TOLERANCE) {
79190
+ diff.countsDelta[tag] = { prod: scripts.prod - lost, cand: scripts.cand, delta };
79191
+ } else {
79192
+ delete diff.countsDelta[tag];
79193
+ }
79194
+ tagManagerDeltas.push({ page: pair.key, lines });
79195
+ }
79064
79196
  }
79065
79197
  const NOISY = new Set(["imgs"]);
79066
79198
  const structural = Object.entries(diff.countsDelta).filter(([k]) => !NOISY.has(k));
@@ -79126,6 +79258,23 @@ function htmlStructuralDiff(ctx) {
79126
79258
  ${STAGING_NOTE}`
79127
79259
  });
79128
79260
  }
79261
+ if (tagManagerDeltas.length > 0) {
79262
+ issues.push({
79263
+ id: "html-structural:tag-manager-scripts",
79264
+ severity: "low",
79265
+ inconclusive: true,
79266
+ category: "functional",
79267
+ page: tagManagerDeltas[0].page,
79268
+ check: "html-structural-diff",
79269
+ summary: `Scripts de vendors do tag manager ausentes em ${tagManagerDeltas.length} página(s) — descontados da contagem (tag manager ausente no candidato)`,
79270
+ details: `${tagManagerDeltas.map((v) => `${v.page}
79271
+ ${v.lines.join(`
79272
+ `)}`).join(`
79273
+ `)}
79274
+
79275
+ Mesma causa de analytics-beacon:tag-manager-absent: o container não carregou no candidato, então as tags que ele injetaria não existem. Scripts inline escritos pelo container não são atribuídos e continuam na contagem.`
79276
+ });
79277
+ }
79129
79278
  const hasBlocking = issues.some((i) => i.severity === "high" && !i.inconclusive);
79130
79279
  return {
79131
79280
  name: "html-structural-diff",
@@ -82934,19 +83083,6 @@ function hydrationDuringNavIssue(viewport, side, count, step) {
82934
83083
 
82935
83084
  // src/checks/ssr-no-js.ts
82936
83085
  init_esm10();
82937
-
82938
- // src/util/localhost.ts
82939
- var LOCALHOST_HOSTS = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]"]);
82940
- function isLocalhost(rawUrl) {
82941
- try {
82942
- const url = new URL(rawUrl);
82943
- return LOCALHOST_HOSTS.has(url.hostname);
82944
- } catch {
82945
- return false;
82946
- }
82947
- }
82948
-
82949
- // src/checks/ssr-no-js.ts
82950
83086
  async function ssrNoJs(ctx) {
82951
83087
  const start = Date.now();
82952
83088
  const issues = [];
@@ -85818,19 +85954,30 @@ function thirdPartyScriptsParity(ctx) {
85818
85954
  const missing = [...prodOrigins].filter((o) => !candOrigins.has(o)).sort();
85819
85955
  const added = [...candOrigins].filter((o) => !prodOrigins.has(o)).sort();
85820
85956
  if (missing.length > 0) {
85957
+ const viaTagManager = tagManagerAbsentOnCand(pair.prod, pair.cand) ? tagManagerVendorOrigins(pair.prod) : new Set;
85958
+ const explained = missing.filter((o) => viaTagManager.has(o));
85959
+ const unexplained = missing.filter((o) => !viaTagManager.has(o));
85960
+ const lenient = staging || unexplained.length === 0;
85961
+ const body = [
85962
+ unexplained.join(`
85963
+ `),
85964
+ explained.length > 0 ? `Explicadas pela ausência do tag manager no candidato (ver analytics-beacon:tag-manager-absent:${pair.key}), não contam como severidade alta:
85965
+ ${explained.join(`
85966
+ `)}` : ""
85967
+ ].filter(Boolean).join(`
85968
+
85969
+ `);
85821
85970
  issues.push({
85822
85971
  id: `3p-scripts:missing:${pair.key}`,
85823
- severity: staging ? "low" : "high",
85824
- ...staging ? { inconclusive: true } : {},
85972
+ severity: lenient ? "low" : "high",
85973
+ ...lenient ? { inconclusive: true } : {},
85825
85974
  category: "network",
85826
85975
  page: pair.key,
85827
85976
  check: "third-party-scripts-parity",
85828
- summary: `${missing.length} origem(ns) de terceiro presente(s) em prod mas ausente(s) no candidato em ${pair.key}`,
85829
- details: staging ? `${missing.join(`
85830
- `)}
85977
+ summary: `${missing.length} origem(ns) de terceiro presente(s) em prod mas ausente(s) no candidato em ${pair.key}${explained.length > 0 ? ` (${explained.length} explicada(s) pelo tag manager ausente)` : ""}`,
85978
+ details: staging ? `${body}
85831
85979
 
85832
- ${STAGING_NOTE}` : missing.join(`
85833
- `),
85980
+ ${STAGING_NOTE}` : body,
85834
85981
  suggestedFix: "Confirme se o script foi migrado deliberadamente ou se a tag (GTM, pixel, chat, avaliações, etc.) foi perdida na porta."
85835
85982
  });
85836
85983
  }
@@ -90497,6 +90644,7 @@ var PageCapture = z2.object({
90497
90644
  tracePath: z2.string().optional(),
90498
90645
  xRobotsTag: z2.string().nullable().optional(),
90499
90646
  pairKey: z2.string().optional(),
90647
+ pass: z2.enum(["extra", "visual"]).optional(),
90500
90648
  variant: VariantFingerprint.optional()
90501
90649
  });
90502
90650
  var StepCapture = z2.object({
@@ -90855,6 +91003,12 @@ var Run = z2.object({
90855
91003
  cand: z2.object({ cookies: z2.array(z2.string()), headers: z2.array(z2.string()) })
90856
91004
  }).optional(),
90857
91005
  pagePairs: z2.array(PagePairMeasurement).optional(),
91006
+ golden: z2.object({
91007
+ dir: z2.string(),
91008
+ recordedAt: z2.string(),
91009
+ parityVersion: z2.string().optional(),
91010
+ staleRequests: z2.array(z2.string()).optional()
91011
+ }).optional(),
90858
91012
  timings: z2.object({
90859
91013
  totalMs: z2.number(),
90860
91014
  phases: z2.array(z2.object({ phase: z2.string(), durationMs: z2.number() }))
@@ -117487,13 +117641,13 @@ function planTouchCommand(dir, page, opts) {
117487
117641
  }
117488
117642
 
117489
117643
  // src/commands/pr.ts
117490
- import { existsSync as existsSync31, readFileSync as readFileSync40, writeFileSync as writeFileSync33 } from "node:fs";
117491
- import { join as join46 } from "node:path";
117644
+ import { existsSync as existsSync32, readFileSync as readFileSync40, writeFileSync as writeFileSync33 } from "node:fs";
117645
+ import { join as join47 } from "node:path";
117492
117646
  import chalk35 from "chalk";
117493
117647
 
117494
117648
  // src/commands/run.ts
117495
- import { existsSync as existsSync30, readFileSync as readFileSync39, rmSync as rmSync5 } from "node:fs";
117496
- import { join as join45 } from "node:path";
117649
+ import { existsSync as existsSync31, readFileSync as readFileSync39, rmSync as rmSync5 } from "node:fs";
117650
+ import { join as join46, resolve as resolve21 } from "node:path";
117497
117651
  import chalk34 from "chalk";
117498
117652
  import ora8 from "ora";
117499
117653
 
@@ -117564,6 +117718,7 @@ var RecordedContext = z4.object({
117564
117718
  viewports: z4.array(Viewport),
117565
117719
  candIsProduction: z4.boolean().optional(),
117566
117720
  checkNames: z4.array(z4.string()).optional(),
117721
+ platform: z4.string().optional(),
117567
117722
  visualProbes: z4.array(z4.tuple([z4.string(), CaptureResultSchema])).optional(),
117568
117723
  missingFiles: z4.array(MissingFile),
117569
117724
  omittedArtifacts: z4.object({ har: z4.number(), trace: z4.number(), video: z4.number() })
@@ -117585,7 +117740,7 @@ function saveCheckContext(dir, ctx, meta) {
117585
117740
  const missing = [];
117586
117741
  const omitted = { har: 0, trace: 0, video: 0 };
117587
117742
  let n = 0;
117588
- const rel = (p) => {
117743
+ const rel = (p, expectedAbsent = false) => {
117589
117744
  if (p === "")
117590
117745
  return "";
117591
117746
  const hit = copied.get(p);
@@ -117594,7 +117749,7 @@ function saveCheckContext(dir, ctx, meta) {
117594
117749
  const dest = `files/${String(++n).padStart(4, "0")}-${basename5(p)}`;
117595
117750
  if (existsSync29(p))
117596
117751
  copyFileSync(p, join44(dir, dest));
117597
- else
117752
+ else if (!expectedAbsent)
117598
117753
  missing.push({ path: dest, original: p });
117599
117754
  copied.set(p, dest);
117600
117755
  return dest;
@@ -117606,7 +117761,7 @@ function saveCheckContext(dir, ctx, meta) {
117606
117761
  omitted.har++;
117607
117762
  if (tracePath)
117608
117763
  omitted.trace++;
117609
- return { ...rest, screenshotPath: rel(c.screenshotPath) };
117764
+ return { ...rest, screenshotPath: rel(c.screenshotPath, c.pass === "extra") };
117610
117765
  };
117611
117766
  const step = (s) => {
117612
117767
  const { tracePath, screenshotBeforePath, ...rest } = s;
@@ -117631,6 +117786,7 @@ function saveCheckContext(dir, ctx, meta) {
117631
117786
  prodUrl: meta.prodUrl,
117632
117787
  candUrl: meta.candUrl,
117633
117788
  ...meta.checkNames ? { checkNames: meta.checkNames } : {},
117789
+ ...meta.platform ? { platform: meta.platform } : {},
117634
117790
  prodPages: ctx.prodPages.map(page),
117635
117791
  candPages: ctx.candPages.map(page),
117636
117792
  prodFlows: ctx.prodFlows.map(flow),
@@ -117707,6 +117863,7 @@ function loadCheckContext(dir) {
117707
117863
  candUrl: r.candUrl,
117708
117864
  recordedAt: r.recordedAt,
117709
117865
  ...r.checkNames ? { checkNames: r.checkNames } : {},
117866
+ ...r.platform ? { platform: r.platform } : {},
117710
117867
  ...r.parityVersion ? { parityVersion: r.parityVersion } : {}
117711
117868
  },
117712
117869
  fetchLog,
@@ -118140,6 +118297,253 @@ function checkToJsonl(runId, check) {
118140
118297
  };
118141
118298
  }
118142
118299
 
118300
+ // src/engine/golden.ts
118301
+ import { copyFileSync as copyFileSync2, existsSync as existsSync30, mkdirSync as mkdirSync24 } from "node:fs";
118302
+ import { basename as basename6, join as join45 } from "node:path";
118303
+ var GOLDEN_STALE_AFTER_DAYS = 7;
118304
+ var isVisualPage = (p) => p.pass === "visual";
118305
+ var isExtraPage = (p) => p.pass === "extra";
118306
+ function pathname(url) {
118307
+ try {
118308
+ return new URL(url).pathname || "/";
118309
+ } catch {
118310
+ return url;
118311
+ }
118312
+ }
118313
+ function pathAndQuery(url) {
118314
+ try {
118315
+ const u = new URL(url);
118316
+ return (u.pathname || "/") + u.search;
118317
+ } catch {
118318
+ return url;
118319
+ }
118320
+ }
118321
+ var pairKeyOf = (p) => p.pairKey ?? pathAndQuery(p.url);
118322
+ function originOf2(url) {
118323
+ try {
118324
+ return new URL(url).origin;
118325
+ } catch {
118326
+ return null;
118327
+ }
118328
+ }
118329
+ function loadGolden(dir) {
118330
+ try {
118331
+ return { rec: loadCheckContext(dir) };
118332
+ } catch (err) {
118333
+ return { error: `--golden ${dir}: ${err.message}` };
118334
+ }
118335
+ }
118336
+ function planGoldenRun(rec, input) {
118337
+ const errors = [];
118338
+ const warnings = [];
118339
+ const plan = {
118340
+ errors,
118341
+ warnings,
118342
+ visualPaths: [],
118343
+ visualKeys: new Set,
118344
+ extraPaths: [],
118345
+ viewports: new Set(input.viewports),
118346
+ flows: new Set(input.flows)
118347
+ };
118348
+ const { prodPages, candPages, prodFlows, viewports: goldenViewports } = rec.ctx;
118349
+ if (input.prod !== undefined) {
118350
+ const asked = originOf2(input.prod);
118351
+ const held = originOf2(rec.meta.prodUrl);
118352
+ if (asked !== held) {
118353
+ errors.push(`--prod ${input.prod} is not the golden's prod (${rec.meta.prodUrl}): the recording is a capture of a different site. Drop --prod, or record a golden of that site.`);
118354
+ }
118355
+ }
118356
+ const missingViewports = input.viewports.filter((v) => !goldenViewports.includes(v));
118357
+ if (missingViewports.length > 0) {
118358
+ errors.push(`the golden holds viewport(s) ${goldenViewports.join(", ") || "(none)"} but this run asks for ${missingViewports.join(", ")}`);
118359
+ }
118360
+ if (rec.meta.checkNames) {
118361
+ const recorded = new Set(rec.meta.checkNames);
118362
+ const wanted = input.checkNames ?? new Set(Object.keys(ALL_CHECKS_BY_NAME));
118363
+ const uncovered = [...wanted].filter((n) => !recorded.has(n)).sort();
118364
+ if (uncovered.length > 0) {
118365
+ errors.push(`the golden was recorded with a check selection that does not cover ${uncovered.length} check(s) this run executes (${uncovered.join(", ")}); narrow --only/--skip or record a new golden`);
118366
+ }
118367
+ }
118368
+ if (prodPages.length === 0 && prodFlows.length === 0) {
118369
+ errors.push("the golden holds no prod pages and no prod flows: there is nothing to compare against");
118370
+ return plan;
118371
+ }
118372
+ const inFlow = new Set(prodFlows.flatMap((f) => f.pages.map((p) => `${p.viewport} ${p.url} ${p.screenshotPath}`)));
118373
+ const outsideFlows = prodPages.filter((p) => !inFlow.has(`${p.viewport} ${p.url} ${p.screenshotPath}`));
118374
+ if (outsideFlows.length > 0 && !prodPages.some((p) => p.pass !== undefined)) {
118375
+ errors.push("the golden was recorded before the capture pass was stored on each page; record it again");
118376
+ return plan;
118377
+ }
118378
+ const inRun = (p) => plan.viewports.has(p.viewport);
118379
+ if (input.visualPagesLimit > 0) {
118380
+ const goldenVisual = prodPages.filter((p) => isVisualPage(p) && inRun(p));
118381
+ const candPathByKey = new Map;
118382
+ for (const c of candPages) {
118383
+ if (isVisualPage(c) && !candPathByKey.has(pairKeyOf(c))) {
118384
+ candPathByKey.set(pairKeyOf(c), pathAndQuery(c.url));
118385
+ }
118386
+ }
118387
+ const keys = [...new Set(goldenVisual.map(pairKeyOf))];
118388
+ if (input.explicitPages) {
118389
+ const held = new Set(keys);
118390
+ const missing = input.explicitPages.filter((e) => !held.has(e.prod)).map((e) => e.prod);
118391
+ if (missing.length > 0) {
118392
+ errors.push(`the golden holds no prod capture for --pages path(s): ${missing.join(", ")} (it holds: ${keys.join(", ") || "none"}). Record a new golden that includes them.`);
118393
+ } else {
118394
+ plan.visualPaths = input.explicitPages;
118395
+ }
118396
+ } else {
118397
+ plan.visualPaths = keys.slice(0, input.visualPagesLimit).map((k) => ({ prod: k, cand: candPathByKey.get(k) ?? k }));
118398
+ }
118399
+ plan.visualKeys = new Set(plan.visualPaths.map((p) => p.prod));
118400
+ if (plan.visualKeys.size === 0 && errors.length === 0) {
118401
+ warnings.push("the golden holds no visual-pass pages (recorded with --no-visual-diff?): the visual check will be inconclusive");
118402
+ }
118403
+ }
118404
+ if (input.vitalsPagesLimit > 0) {
118405
+ const paths = prodPages.filter((p) => isExtraPage(p) && inRun(p)).map((p) => pathname(p.url));
118406
+ plan.extraPaths = [...new Set(paths)].slice(0, input.vitalsPagesLimit);
118407
+ }
118408
+ const heldFlows = new Set(prodFlows.map((f) => f.flow));
118409
+ const noProdFlow = input.flows.filter((f) => !heldFlows.has(f));
118410
+ if (noProdFlow.length > 0) {
118411
+ warnings.push(`the golden has no prod capture of flow(s) ${noProdFlow.join(", ")}: the cand side of each is reported as unpaired`);
118412
+ }
118413
+ return plan;
118414
+ }
118415
+ function makeRelocator(destDir) {
118416
+ const done = new Map;
118417
+ const taken = new Set;
118418
+ return (p) => {
118419
+ if (p === "")
118420
+ return p;
118421
+ const hit = done.get(p);
118422
+ if (hit !== undefined)
118423
+ return hit;
118424
+ let out = p;
118425
+ if (existsSync30(p)) {
118426
+ mkdirSync24(destDir, { recursive: true });
118427
+ const name = basename6(p).replace(/^\d{4}-/, "");
118428
+ const dot = name.lastIndexOf(".");
118429
+ const stem = dot > 0 ? name.slice(0, dot) : name;
118430
+ const ext = dot > 0 ? name.slice(dot) : "";
118431
+ let candidate = name;
118432
+ for (let n = 2;taken.has(candidate); n++)
118433
+ candidate = `${stem}-${n}${ext}`;
118434
+ taken.add(candidate);
118435
+ out = join45(destDir, candidate);
118436
+ copyFileSync2(p, out);
118437
+ }
118438
+ done.set(p, out);
118439
+ return out;
118440
+ };
118441
+ }
118442
+ function mergeGoldenContext(rec, plan, live, relocate) {
118443
+ const extraKept = (p) => plan.extraPaths.includes(pathname(p.url));
118444
+ const keepPage = (p) => {
118445
+ if (!plan.viewports.has(p.viewport))
118446
+ return false;
118447
+ if (isExtraPage(p))
118448
+ return extraKept(p);
118449
+ if (isVisualPage(p))
118450
+ return plan.visualKeys.has(pairKeyOf(p));
118451
+ return true;
118452
+ };
118453
+ const page = (p) => ({
118454
+ ...p,
118455
+ screenshotPath: relocate(p.screenshotPath)
118456
+ });
118457
+ const step = (s) => ({
118458
+ ...s,
118459
+ screenshotPath: relocate(s.screenshotPath),
118460
+ ...s.screenshotBeforePath !== undefined ? { screenshotBeforePath: relocate(s.screenshotBeforePath) } : {}
118461
+ });
118462
+ const keepFlow = (f) => {
118463
+ if (!plan.viewports.has(f.viewport))
118464
+ return false;
118465
+ const only = f.pages.length === 1 ? f.pages[0] : undefined;
118466
+ if (only && isExtraPage(only))
118467
+ return extraKept(only);
118468
+ return plan.flows.has(f.flow);
118469
+ };
118470
+ const keptPages = rec.ctx.prodPages.filter(keepPage);
118471
+ const pages = [...keptPages.map(page), ...live.pages];
118472
+ const flows = [
118473
+ ...rec.ctx.prodFlows.filter(keepFlow).map((f) => ({
118474
+ ...f,
118475
+ pages: f.pages.map(page),
118476
+ ...f.steps ? { steps: f.steps.map(step) } : {}
118477
+ })),
118478
+ ...live.flows
118479
+ ];
118480
+ let visualProbes;
118481
+ if (live.visualProbes) {
118482
+ visualProbes = new Map;
118483
+ const keptShots = new Set(keptPages.filter(isVisualPage).map((p) => p.screenshotPath));
118484
+ for (const [k, v] of rec.ctx.visualProbes ?? []) {
118485
+ if (!keptShots.has(k))
118486
+ continue;
118487
+ visualProbes.set(relocate(k), {
118488
+ ...v,
118489
+ side: { ...v.side, screenshot: v.side.screenshot ? relocate(v.side.screenshot) : null },
118490
+ repeatScreenshot: v.repeatScreenshot ? relocate(v.repeatScreenshot) : null
118491
+ });
118492
+ }
118493
+ for (const [k, v] of live.visualProbes)
118494
+ visualProbes.set(k, v);
118495
+ }
118496
+ return { pages, flows, visualProbes };
118497
+ }
118498
+ function goldenPlatform(rec) {
118499
+ if (rec.meta.platform)
118500
+ return rec.meta.platform;
118501
+ const home = rec.ctx.prodPages.find((p) => p.html && pathname(p.url) === "/");
118502
+ return home?.html ? detectPlatform({ url: rec.meta.prodUrl, html: home.html }) : "custom";
118503
+ }
118504
+ function installGoldenFetch(log, prodOrigin) {
118505
+ const orig = globalThis.fetch;
118506
+ const replay = createReplayFetch(log);
118507
+ const stale = new Set;
118508
+ const mine = async (input, init) => {
118509
+ const raw = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
118510
+ if (originOf2(raw) !== prodOrigin)
118511
+ return orig(input, init);
118512
+ try {
118513
+ return await replay(input, init);
118514
+ } catch (err) {
118515
+ if (err instanceof UnrecordedFetchError) {
118516
+ stale.add(err.message.replace(/^replay: /, "").replace(/ was not made during the recorded run$/, ""));
118517
+ }
118518
+ throw err;
118519
+ }
118520
+ };
118521
+ globalThis.fetch = mine;
118522
+ return {
118523
+ stale: () => [...stale].sort(),
118524
+ restore: () => {
118525
+ if (globalThis.fetch === mine)
118526
+ globalThis.fetch = orig;
118527
+ }
118528
+ };
118529
+ }
118530
+ function goldenAge(recordedAt, now = Date.now()) {
118531
+ const ms = now - Date.parse(recordedAt);
118532
+ if (!Number.isFinite(ms))
118533
+ return { text: "age unknown", warn: true };
118534
+ const hours = Math.max(0, ms) / 3600000;
118535
+ const text = hours < 48 ? `${Math.round(hours)}h old` : `${Math.round(hours / 24)} days old`;
118536
+ return { text, warn: hours / 24 > GOLDEN_STALE_AFTER_DAYS };
118537
+ }
118538
+ function goldenReportField(dir, meta, stale) {
118539
+ return {
118540
+ dir,
118541
+ recordedAt: meta.recordedAt,
118542
+ ...meta.parityVersion ? { parityVersion: meta.parityVersion } : {},
118543
+ ...stale.length > 0 ? { staleRequests: stale } : {}
118544
+ };
118545
+ }
118546
+
118143
118547
  // src/util/heartbeat.ts
118144
118548
  function startHeartbeat(opts) {
118145
118549
  const intervalMs = opts.intervalMs ?? 30000;
@@ -118213,7 +118617,7 @@ function detectRunCaveats(input) {
118213
118617
  id: "cand-staging-host",
118214
118618
  level: "warn",
118215
118619
  summary: "Candidato num host de staging — noindex e terceiros não julgados",
118216
- detail: "cand está noutro host e marca noindex em todas as páginas que prod indexa: é o comportamento de um host de staging (deco marca noindex fora do domínio de produção). noindex/nofollow, terceiros ausentes e requests a terceiros que falham só em cand ficaram inconclusivos. Reconfira depois da troca de domínio, ou rode com --cand-is-production se cand já é o domínio final."
118620
+ detail: "cand está noutro host e marca noindex em todas as páginas que prod indexa (é o comportamento de um host de staging: deco marca noindex fora do domínio de produção), ou é um dev server local, onde rastreamento e vendors não são ligados. noindex/nofollow, terceiros ausentes e requests a terceiros que falham só em cand ficaram inconclusivos. Reconfira depois da troca de domínio, ou rode com --cand-is-production se cand já é o domínio final."
118217
118621
  });
118218
118622
  }
118219
118623
  for (const side of ["prod", "cand"]) {
@@ -118590,7 +118994,14 @@ function readRunChecks(reportPath) {
118590
118994
  }
118591
118995
  }
118592
118996
  async function runCommand(rawOpts) {
118593
- if (!rawOpts.prod) {
118997
+ const goldenLoaded = rawOpts.golden ? loadGolden(rawOpts.golden) : undefined;
118998
+ if (goldenLoaded && "error" in goldenLoaded) {
118999
+ console.error(chalk34.red(` ${goldenLoaded.error}`));
119000
+ return 2;
119001
+ }
119002
+ const goldenRec = goldenLoaded?.rec;
119003
+ const userProd = rawOpts.prod;
119004
+ if (!rawOpts.prod && !goldenRec) {
118594
119005
  const target = rawOpts.cand ?? "<url>";
118595
119006
  console.error(`${chalk34.yellow("Single-site run?")} \`parity run\` compares two URLs (prod↔cand).
118596
119007
  For one site, use: ${chalk34.cyan(`parity e2e --url ${target}`)}
@@ -118598,6 +119009,8 @@ async function runCommand(rawOpts) {
118598
119009
  return 2;
118599
119010
  }
118600
119011
  const opts = applyPreset(rawOpts);
119012
+ if (goldenRec)
119013
+ opts.prod = goldenRec.meta.prodUrl;
118601
119014
  if (opts.record) {
118602
119015
  try {
118603
119016
  assertRecordDirFree(opts.record);
@@ -118649,6 +119062,8 @@ async function runCommand(rawOpts) {
118649
119062
  let profile;
118650
119063
  if (opts.profile === "commerce" || opts.profile === "content") {
118651
119064
  profile = opts.profile;
119065
+ } else if (goldenRec) {
119066
+ profile = goldenRec.ctx.rc.profile ?? "commerce";
118652
119067
  } else {
118653
119068
  const pv = opts.viewports.split(",")[0]?.trim() || "mobile";
118654
119069
  earlyProdHtml = await fetchHomeHtml(opts.prod, pv, pinFetchHeaders(pins.prod));
@@ -118708,7 +119123,41 @@ async function runCommand(rawOpts) {
118708
119123
  }
118709
119124
  const viewports = opts.viewports.split(",").map((s) => s.trim());
118710
119125
  const failOn = opts.failOn.split(",").map((s) => s.trim()).filter(Boolean);
118711
- const rc = loadParityRc();
119126
+ let explicitForGolden = null;
119127
+ if (goldenRec) {
119128
+ try {
119129
+ explicitForGolden = resolveExplicitPages(opts.pagesFile, opts.pages);
119130
+ } catch (err) {
119131
+ console.error(chalk34.red(` ${err.message}`));
119132
+ return 2;
119133
+ }
119134
+ }
119135
+ const goldenPlan = goldenRec ? planGoldenRun(goldenRec, {
119136
+ prod: userProd,
119137
+ viewports,
119138
+ checkNames: hasSelection ? selection.checkNames : undefined,
119139
+ flows,
119140
+ explicitPages: explicitForGolden,
119141
+ visualPagesLimit: resolveVisualPagesLimit(opts, explicitForGolden?.length ?? null),
119142
+ vitalsPagesLimit: opts.vitalsPages ?? (isLocalhost(opts.cand) ? 3 : 10)
119143
+ }) : undefined;
119144
+ if (goldenRec && goldenPlan) {
119145
+ if (goldenPlan.errors.length > 0) {
119146
+ console.error(chalk34.red(` --golden ${opts.golden}: cannot use this recording:`));
119147
+ for (const e of goldenPlan.errors)
119148
+ console.error(chalk34.red(` - ${e}`));
119149
+ return 2;
119150
+ }
119151
+ const age = goldenAge(goldenRec.meta.recordedAt);
119152
+ const line = ` prod: from golden ${opts.golden} (recorded ${goldenRec.meta.recordedAt}, ${age.text}) — prod is not captured by this run`;
119153
+ console.log(age.warn ? chalk34.yellow(`${line}; older than a week, prod may have moved`) : chalk34.dim(line));
119154
+ for (const w of goldenPlan.warnings)
119155
+ console.log(chalk34.yellow(` ! ${w}`));
119156
+ if (goldenRec.missingFiles.length > 0) {
119157
+ console.log(chalk34.yellow(` ! ${goldenRec.missingFiles.length} file(s) the golden references were missing when it was saved`));
119158
+ }
119159
+ }
119160
+ const rc = goldenRec ? structuredClone(goldenRec.ctx.rc) : loadParityRc();
118712
119161
  rc.profile = profile;
118713
119162
  rc.cep = isContentProfile ? "" : opts.cep || rc.cep;
118714
119163
  if (typeof opts.addToCartTimeout === "number" && Number.isFinite(opts.addToCartTimeout)) {
@@ -118724,7 +119173,7 @@ async function runCommand(rawOpts) {
118724
119173
  console.log(chalk34.dim(" interactive: enabled — TTY + no LLM. Missing selectors will pause to prompt (disable with --no-interactive). Issue #72."));
118725
119174
  }
118726
119175
  const primaryViewport = viewports[0] ?? "mobile";
118727
- const preflight = await preflightCheck(opts.prod, opts.cand, primaryViewport, pins);
119176
+ const preflight = await preflightCheck(opts.prod, opts.cand, primaryViewport, pins, Boolean(goldenRec));
118728
119177
  if (!preflight.ok) {
118729
119178
  console.error(chalk34.red(`
118730
119179
  ✖ pre-flight falhou:`));
@@ -118737,7 +119186,9 @@ async function runCommand(rawOpts) {
118737
119186
  const learned = loadLearned();
118738
119187
  const learnedBefore = JSON.stringify(learned);
118739
119188
  let platform = "custom";
118740
- const prodHomeHtml = earlyProdHtml ?? await fetchHomeHtml(opts.prod, primaryViewport, pinFetchHeaders(pins.prod));
119189
+ const prodHomeHtml = goldenRec ? null : earlyProdHtml ?? await fetchHomeHtml(opts.prod, primaryViewport, pinFetchHeaders(pins.prod));
119190
+ if (goldenRec)
119191
+ platform = goldenPlatform(goldenRec);
118741
119192
  if (prodHomeHtml) {
118742
119193
  platform = detectPlatform({ url: opts.prod, html: prodHomeHtml });
118743
119194
  if (platform !== "custom") {
@@ -118747,7 +119198,7 @@ async function runCommand(rawOpts) {
118747
119198
  const prodHost = hostOf4(opts.prod);
118748
119199
  let promotedCount = 0;
118749
119200
  let deprecatedCount = 0;
118750
- const wantsAutoSelectors = opts.autoSelectors !== false && isLlmAvailable();
119201
+ const wantsAutoSelectors = opts.autoSelectors !== false && isLlmAvailable() && !goldenRec;
118751
119202
  let discoveryBrowser = null;
118752
119203
  if (wantsAutoSelectors) {
118753
119204
  discoveryBrowser = await runSelectorDiscoveryPass({
@@ -118810,6 +119261,7 @@ async function runCommand(rawOpts) {
118810
119261
  let currentPhase = "launch";
118811
119262
  let shuttingDown = false;
118812
119263
  const partialChecks = [];
119264
+ let goldenFetch;
118813
119265
  const forceCloseBrowser = async (b, capMs) => {
118814
119266
  if (!b)
118815
119267
  return;
@@ -118885,8 +119337,8 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
118885
119337
  if (opts.warmup) {
118886
119338
  const warmupSpinner = ora8("Warmup: bustando cache em prod + cand…").start();
118887
119339
  const result = await warmupTargets({
118888
- urls: [opts.prod, opts.cand],
118889
- headersFor: [pinFetchHeaders(pins.prod), pinFetchHeaders(pins.cand)],
119340
+ urls: goldenRec ? [opts.cand] : [opts.prod, opts.cand],
119341
+ headersFor: goldenRec ? [pinFetchHeaders(pins.cand)] : [pinFetchHeaders(pins.prod), pinFetchHeaders(pins.cand)],
118890
119342
  viewports,
118891
119343
  bypassCache: opts.bypassCache !== false
118892
119344
  });
@@ -118901,11 +119353,12 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
118901
119353
  }
118902
119354
  }
118903
119355
  const traceEnabled = process.env.PARITY_TRACE === "1";
119356
+ const liveSides = goldenRec ? ["cand"] : ["prod", "cand"];
118904
119357
  const runOneSide = async (viewport, side) => {
118905
119358
  const baseUrl = side === "prod" ? opts.prod : opts.cand;
118906
119359
  const harEnabled = process.env.PARITY_HAR === "1";
118907
- const harPath = harEnabled ? join45(paths.harDir, `${viewport}-${side}.har`) : undefined;
118908
- const tracePath = traceEnabled ? join45(paths.tracesDir, `${viewport}-${side}.zip`) : null;
119360
+ const harPath = harEnabled ? join46(paths.harDir, `${viewport}-${side}.har`) : undefined;
119361
+ const tracePath = traceEnabled ? join46(paths.tracesDir, `${viewport}-${side}.zip`) : null;
118909
119362
  const ctx = await newContext(browser, {
118910
119363
  viewport,
118911
119364
  harPath,
@@ -118982,7 +119435,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
118982
119435
  };
118983
119436
  const runOneViewport = async (viewport) => {
118984
119437
  const [prodResult, candResult] = await Promise.all([
118985
- runOneSide(viewport, "prod"),
119438
+ goldenRec ? { captures: [], pages: [] } : runOneSide(viewport, "prod"),
118986
119439
  runOneSide(viewport, "cand")
118987
119440
  ]);
118988
119441
  for (const r of [prodResult, candResult]) {
@@ -119031,7 +119484,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119031
119484
  baseText: "Coletando vitals em páginas extras…"
119032
119485
  });
119033
119486
  try {
119034
- const allUrls = await resolveSitemapUrls(opts.prod);
119487
+ const allUrls = goldenRec ? [] : await resolveSitemapUrls(opts.prod);
119035
119488
  const visitedPaths = new Set;
119036
119489
  for (const p of allPageCaptures) {
119037
119490
  try {
@@ -119053,7 +119506,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119053
119506
  arr.push(p);
119054
119507
  buckets.set(seg, arr);
119055
119508
  }
119056
- const extraPaths = [];
119509
+ const extraPaths = goldenPlan ? [...goldenPlan.extraPaths] : [];
119057
119510
  const keys = [...buckets.keys()];
119058
119511
  let idx = 0;
119059
119512
  while (extraPaths.length < vitalsPagesLimit && keys.some((k) => (buckets.get(k)?.length ?? 0) > 0)) {
@@ -119069,7 +119522,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119069
119522
  const tasks = [];
119070
119523
  for (const viewport of mobileOnly) {
119071
119524
  for (const path of extraPaths) {
119072
- for (const side of ["prod", "cand"]) {
119525
+ for (const side of liveSides) {
119073
119526
  tasks.push({ path, viewport, side });
119074
119527
  }
119075
119528
  }
@@ -119118,6 +119571,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119118
119571
  if (!cap) {
119119
119572
  return;
119120
119573
  }
119574
+ cap.pass = "extra";
119121
119575
  allPageCaptures.push(cap);
119122
119576
  allFlowCaptures.push({
119123
119577
  flow: "homepage",
@@ -119164,11 +119618,11 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119164
119618
  baseText: visualSpinnerBaseText
119165
119619
  });
119166
119620
  try {
119167
- const visualPaths = explicitPaths ?? (await discoverPagesFromSitemap(opts.prod, { sampleSize: visualPagesLimit })).all.map((p) => ({ prod: p.path, cand: p.path }));
119621
+ const visualPaths = explicitPaths ?? (goldenPlan ? goldenPlan.visualPaths : (await discoverPagesFromSitemap(opts.prod, { sampleSize: visualPagesLimit })).all.map((p) => ({ prod: p.path, cand: p.path })));
119168
119622
  const tasks = [];
119169
119623
  for (const viewport of viewports) {
119170
119624
  for (const pair of visualPaths) {
119171
- for (const side of ["prod", "cand"]) {
119625
+ for (const side of liveSides) {
119172
119626
  tasks.push({
119173
119627
  path: side === "prod" ? pair.prod : pair.cand,
119174
119628
  pairKey: pair.prod,
@@ -119212,8 +119666,9 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119212
119666
  scrollToLoad: true,
119213
119667
  pairKey: task.pairKey
119214
119668
  });
119669
+ cap.pass = "visual";
119215
119670
  allPageCaptures.push(cap);
119216
- if (existsSync30(screenshotPath)) {
119671
+ if (existsSync31(screenshotPath)) {
119217
119672
  visualProbes.set(screenshotPath, await probeFullPage(page, screenshotPath, task.side === "prod" ? screenshotPath.replace(/\.png$/, "-repeat.png") : null));
119218
119673
  }
119219
119674
  } finally {
@@ -119244,6 +119699,18 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119244
119699
  const w = vitalsWarm.stats;
119245
119700
  console.log(chalk34.dim(` vitals warm-up: ${w.pages} page(s), ${w.loads} load(s)${w.failed ? `, ${w.failed} failed` : ""}, +${(w.totalMs / 1000).toFixed(1)}s summed across captures`));
119246
119701
  }
119702
+ if (goldenRec && goldenPlan) {
119703
+ const merged = mergeGoldenContext(goldenRec, goldenPlan, {
119704
+ pages: allPageCaptures,
119705
+ flows: allFlowCaptures,
119706
+ visualProbes: visualPagesLimit > 0 ? visualProbes : undefined
119707
+ }, makeRelocator(paths.screenshotsDir));
119708
+ allPageCaptures.splice(0, allPageCaptures.length, ...merged.pages);
119709
+ allFlowCaptures.splice(0, allFlowCaptures.length, ...merged.flows);
119710
+ visualProbes.clear();
119711
+ for (const [k, v] of merged.visualProbes ?? [])
119712
+ visualProbes.set(k, v);
119713
+ }
119247
119714
  currentPhase = "checks";
119248
119715
  setSpinnerLabel("Rodando checks…");
119249
119716
  spinner.start();
@@ -119261,13 +119728,15 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119261
119728
  candIsProduction: opts.candIsProduction
119262
119729
  };
119263
119730
  let recordedOk = false;
119731
+ let goldenStale = [];
119264
119732
  if (opts.record) {
119265
119733
  try {
119266
119734
  saveCheckContext(opts.record, checkCtx, {
119267
119735
  prodUrl: opts.prod,
119268
119736
  candUrl: opts.cand,
119269
119737
  parityVersion: getPackageVersion(),
119270
- checkNames: hasSelection ? [...selection.checkNames] : undefined
119738
+ checkNames: hasSelection ? [...selection.checkNames] : undefined,
119739
+ platform
119271
119740
  });
119272
119741
  recordedOk = true;
119273
119742
  } catch (err) {
@@ -119275,6 +119744,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119275
119744
  }
119276
119745
  }
119277
119746
  const runChecks = () => runAllChecks(checkCtx, partialChecks, hasSelection ? selection.checkNames : undefined);
119747
+ goldenFetch = goldenRec ? installGoldenFetch(goldenRec.fetchLog, new URL(opts.prod).origin) : undefined;
119278
119748
  let checks;
119279
119749
  if (recordedOk && opts.record) {
119280
119750
  const { result, log } = await recordFetch(runChecks);
@@ -119288,6 +119758,10 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119288
119758
  } else {
119289
119759
  checks = await runChecks();
119290
119760
  }
119761
+ if (goldenFetch) {
119762
+ goldenStale = goldenFetch.stale();
119763
+ goldenFetch.restore();
119764
+ }
119291
119765
  checksHb.stop();
119292
119766
  stampPhase("checks");
119293
119767
  spinner.succeed(`Checks concluídos (${checks.length})`);
@@ -119399,7 +119873,8 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119399
119873
  prodPinned: !isEmptyPin(pins.prod)
119400
119874
  })),
119401
119875
  pinned: isEmptyPin(pins.prod) && isEmptyPin(pins.cand) ? undefined : { prod: pinNames(pins.prod), cand: pinNames(pins.cand) },
119402
- pagePairs
119876
+ pagePairs,
119877
+ golden: goldenRec ? goldenReportField(resolve21(opts.golden), goldenRec.meta, goldenStale) : undefined
119403
119878
  };
119404
119879
  const reportStart = performance.now();
119405
119880
  const reportWhere = writeRunReport(paths, run, Boolean(opts.html || opts.open));
@@ -119417,6 +119892,11 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
119417
119892
  verdict: { status: verdict.status, score: verdict.score, scoreVersion: SCORE_VERSION }
119418
119893
  });
119419
119894
  printSummary8(run, reportWhere, { promotedCount, deprecatedCount, platform });
119895
+ if (run.golden) {
119896
+ const age = goldenAge(run.golden.recordedAt);
119897
+ const say = age.warn ? chalk34.yellow : chalk34.dim;
119898
+ console.log(say(` prod from golden ${run.golden.dir} (${age.text}); prod was not recaptured`));
119899
+ }
119420
119900
  console.log(`
119421
119901
  ${formatTimingsSummary(runTimings, buildFlowBreakdown(allFlowCaptures))}`);
119422
119902
  if (pagePairs) {
@@ -119435,6 +119915,11 @@ ${formatPagePairTable(pagePairs)}`);
119435
119915
  console.log(chalk34.red(failOnGate.message));
119436
119916
  return 1;
119437
119917
  }
119918
+ if (goldenStale.length > 0) {
119919
+ console.log(chalk34.red(`
119920
+ ✖ golden is stale for: ${goldenStale.join(", ")} — a check asked prod for something the recording never saw, so its result rests on no data; record a new golden (report.json golden.staleRequests)`));
119921
+ return 2;
119922
+ }
119438
119923
  if (opts.open) {
119439
119924
  const { default: open } = await import("open");
119440
119925
  await open(paths.reportHtml).catch(() => {
@@ -119457,6 +119942,7 @@ ${formatPagePairTable(pagePairs)}`);
119457
119942
  clearTimeout(globalTimeoutTimer);
119458
119943
  process.removeListener("SIGINT", onSignal);
119459
119944
  process.removeListener("SIGTERM", onSignal);
119945
+ goldenFetch?.restore();
119460
119946
  if (browser)
119461
119947
  await browser.close().catch(() => {
119462
119948
  return;
@@ -119523,7 +120009,7 @@ function parsePagePair(entry) {
119523
120009
  }
119524
120010
  function resolveExplicitPages(pagesFile, pagesList) {
119525
120011
  if (pagesFile) {
119526
- if (!existsSync30(pagesFile)) {
120012
+ if (!existsSync31(pagesFile)) {
119527
120013
  throw new Error(`--pages-file não encontrado: ${pagesFile}`);
119528
120014
  }
119529
120015
  const raw = readFileSync39(pagesFile, "utf-8");
@@ -119618,7 +120104,7 @@ async function runWithConcurrency2(items, workers, fn) {
119618
120104
  }
119619
120105
  }));
119620
120106
  }
119621
- async function preflightCheck(prodUrl, candUrl, viewport, pins) {
120107
+ async function preflightCheck(prodUrl, candUrl, viewport, pins, skipProd = false) {
119622
120108
  const spinner = ora8("Pre-flight: verificando URLs…").start();
119623
120109
  const errors = [];
119624
120110
  const ua = userAgentFor(viewport);
@@ -119683,7 +120169,7 @@ async function preflightCheck(prodUrl, candUrl, viewport, pins) {
119683
120169
  await probeWithFetch(label, url);
119684
120170
  }
119685
120171
  }
119686
- await Promise.all([probe("prod", prodUrl), probe("cand", candUrl)]);
120172
+ await Promise.all([skipProd ? undefined : probe("prod", prodUrl), probe("cand", candUrl)]);
119687
120173
  await browser?.close().catch(() => {});
119688
120174
  if (errors.length > 0) {
119689
120175
  spinner.fail("Pre-flight falhou");
@@ -119859,8 +120345,8 @@ async function prCommand(opts) {
119859
120345
  return runCode || 1;
119860
120346
  }
119861
120347
  const latest = runs[0];
119862
- const reportJsonPath = join46(opts.output, "runs", latest.id, "report.json");
119863
- if (!existsSync31(reportJsonPath)) {
120348
+ const reportJsonPath = join47(opts.output, "runs", latest.id, "report.json");
120349
+ if (!existsSync32(reportJsonPath)) {
119864
120350
  console.error(chalk35.red(`report.json not found at ${reportJsonPath}`));
119865
120351
  return runCode || 1;
119866
120352
  }
@@ -119944,7 +120430,7 @@ function moduleTableLines(run) {
119944
120430
  }
119945
120431
 
119946
120432
  // src/commands/prompt.ts
119947
- import { existsSync as existsSync32, writeFileSync as writeFileSync34 } from "node:fs";
120433
+ import { existsSync as existsSync33, writeFileSync as writeFileSync34 } from "node:fs";
119948
120434
  import chalk36 from "chalk";
119949
120435
 
119950
120436
  // src/report/prompt-builder.ts
@@ -120072,7 +120558,7 @@ function promptCommand(runId, opts) {
120072
120558
  if (opts.out) {
120073
120559
  writeFileSync34(opts.out, md, "utf8");
120074
120560
  console.log(chalk36.green(`✔ prompt salvo em ${opts.out}`));
120075
- if (existsSync32(opts.out)) {
120561
+ if (existsSync33(opts.out)) {
120076
120562
  const sizeKb = (md.length / 1024).toFixed(1);
120077
120563
  console.log(chalk36.dim(` ${md.length} chars (${sizeKb} KB)`));
120078
120564
  }
@@ -120083,12 +120569,12 @@ function promptCommand(runId, opts) {
120083
120569
  }
120084
120570
 
120085
120571
  // src/commands/qa.ts
120086
- import { existsSync as existsSync36, readFileSync as readFileSync43 } from "node:fs";
120087
- import { basename as basename6, dirname as dirname10, join as join50 } from "node:path";
120572
+ import { existsSync as existsSync37, readFileSync as readFileSync43 } from "node:fs";
120573
+ import { basename as basename7, dirname as dirname10, join as join51 } from "node:path";
120088
120574
  import chalk38 from "chalk";
120089
120575
 
120090
120576
  // src/board/sweep-cards.ts
120091
- import { existsSync as existsSync33, readFileSync as readFileSync41 } from "node:fs";
120577
+ import { existsSync as existsSync34, readFileSync as readFileSync41 } from "node:fs";
120092
120578
  var QA_PREFIX = "[QA]";
120093
120579
  var CARD_BODY_MAX = 1200;
120094
120580
  var CLOSED = new Set(["done", "archived", "merged"]);
@@ -120415,7 +120901,7 @@ function readSpecs(entries) {
120415
120901
  const out = {};
120416
120902
  for (const e of entries)
120417
120903
  for (const ev of e.issue?.evidence ?? [])
120418
- if (ev.kind === "spec" && existsSync33(ev.path))
120904
+ if (ev.kind === "spec" && existsSync34(ev.path))
120419
120905
  out[ev.path] = readFileSync41(ev.path, "utf8");
120420
120906
  return out;
120421
120907
  }
@@ -120440,7 +120926,7 @@ function plannedEvidenceUrls(entries, run, cfg) {
120440
120926
  return {};
120441
120927
  const out = {};
120442
120928
  for (const p of cardEvidencePaths(entries))
120443
- if (existsSync33(p))
120929
+ if (existsSync34(p))
120444
120930
  out[p] = `${base}/fs/org/read?path=${encodeURIComponent(evidenceLibraryPath(p, run))}`;
120445
120931
  return out;
120446
120932
  }
@@ -120448,7 +120934,7 @@ async function uploadEvidence(entries, run, cfg, call, opts) {
120448
120934
  const upload = opts.upload ?? ((local, lib) => uploadToLibrary(cfg, local, lib, call));
120449
120935
  const out = {};
120450
120936
  for (const p of cardEvidencePaths(entries)) {
120451
- if (!existsSync33(p))
120937
+ if (!existsSync34(p))
120452
120938
  continue;
120453
120939
  const url = await upload(p, evidenceLibraryPath(p, run));
120454
120940
  if (url)
@@ -120464,8 +120950,8 @@ function truncate6(s, n) {
120464
120950
  }
120465
120951
 
120466
120952
  // src/commands/sweep.ts
120467
- import { existsSync as existsSync35, readFileSync as readFileSync42, writeFileSync as writeFileSync35 } from "node:fs";
120468
- import { join as join49 } from "node:path";
120953
+ import { existsSync as existsSync36, readFileSync as readFileSync42, writeFileSync as writeFileSync35 } from "node:fs";
120954
+ import { join as join50 } from "node:path";
120469
120955
  import chalk37 from "chalk";
120470
120956
  import { z as z5 } from "zod";
120471
120957
 
@@ -120813,7 +121299,7 @@ function a11yIssues(results) {
120813
121299
  }
120814
121300
 
120815
121301
  // src/engine/menu-audit.ts
120816
- import { join as join47 } from "node:path";
121302
+ import { join as join48 } from "node:path";
120817
121303
  var MAX_LINKS = 40;
120818
121304
  async function collectLinks(page, origin, scope) {
120819
121305
  const raw = await page.evaluate((sel) => {
@@ -120942,7 +121428,7 @@ async function probeMenuLinks(url, opts = {}) {
120942
121428
  try {
120943
121429
  for (const link of [...links.values()].slice(0, MAX_LINKS)) {
120944
121430
  const slug = new URL(link.href).pathname.replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, "");
120945
- const shot = opts.screenshotsDir ? join47(opts.screenshotsDir, `menu-${slug || "root"}.jpg`) : undefined;
121431
+ const shot = opts.screenshotsDir ? join48(opts.screenshotsDir, `menu-${slug || "root"}.jpg`) : undefined;
120946
121432
  out.push(await visit(page, link, shot));
120947
121433
  }
120948
121434
  } finally {
@@ -121029,21 +121515,21 @@ function menuLinkIssues(visits) {
121029
121515
 
121030
121516
  // src/engine/regression-specs.ts
121031
121517
  import { spawnSync as spawnSync2 } from "node:child_process";
121032
- import { existsSync as existsSync34 } from "node:fs";
121033
- import { join as join48, resolve as resolve21 } from "node:path";
121518
+ import { existsSync as existsSync35 } from "node:fs";
121519
+ import { join as join49, resolve as resolve22 } from "node:path";
121034
121520
  import { stripVTControlCharacters } from "node:util";
121035
121521
  function runRegressionSpecs(repoDirArg, baseUrl) {
121036
- const repoDir = resolve21(repoDirArg);
121037
- const dir = join48(repoDir, "tests", "qa");
121038
- if (!existsSync34(dir))
121522
+ const repoDir = resolve22(repoDirArg);
121523
+ const dir = join49(repoDir, "tests", "qa");
121524
+ if (!existsSync35(dir))
121039
121525
  return null;
121040
121526
  spawnSync2("npx", ["playwright", "install", "chromium"], {
121041
121527
  cwd: repoDir,
121042
121528
  encoding: "utf8",
121043
121529
  timeout: 10 * 60000
121044
121530
  });
121045
- const config = join48(dir, "playwright.config.ts");
121046
- const args = existsSync34(config) ? ["playwright", "test", "-c", config, "--reporter=json"] : ["playwright", "test", "tests/qa", "--reporter=json"];
121531
+ const config = join49(dir, "playwright.config.ts");
121532
+ const args = existsSync35(config) ? ["playwright", "test", "-c", config, "--reporter=json"] : ["playwright", "test", "tests/qa", "--reporter=json"];
121047
121533
  const res = spawnSync2("npx", args, {
121048
121534
  cwd: repoDir,
121049
121535
  env: { ...process.env, BASE_URL: baseUrl, CI: "1" },
@@ -121281,8 +121767,8 @@ async function addProbeFindings(url, runDir, reportJson, rc, json, specsRepo) {
121281
121767
  { label: "busca", selectors: selectorsFor("searchTrigger", { rc }) },
121282
121768
  { label: "menu", selectors: HAMBURGER_SELECTORS }
121283
121769
  ]).catch(() => []);
121284
- const menu = await probeMenuLinks(url, { screenshotsDir: join49(runDir, "screenshots") }).catch(() => []);
121285
- writeFileSync35(join49(runDir, "menu-links.json"), `${JSON.stringify(menu, null, 2)}
121770
+ const menu = await probeMenuLinks(url, { screenshotsDir: join50(runDir, "screenshots") }).catch(() => []);
121771
+ writeFileSync35(join50(runDir, "menu-links.json"), `${JSON.stringify(menu, null, 2)}
121286
121772
  `, "utf8");
121287
121773
  const listing = menu.find((v) => v.listingUi && v.products > 0);
121288
121774
  const a11y = await probeA11y(url, listing ? new URL(listing.link.href).pathname : undefined).catch(() => []);
@@ -121340,8 +121826,8 @@ function readUnverified(reportJson) {
121340
121826
  var SEVERITIES = ["critical", "high", "medium", "low"];
121341
121827
  var SWEEPER_ISSUES_FILE = "sweeper-issues.json";
121342
121828
  function readSweeperIssues(runDir) {
121343
- const path = join49(runDir, SWEEPER_ISSUES_FILE);
121344
- if (!existsSync35(path))
121829
+ const path = join50(runDir, SWEEPER_ISSUES_FILE);
121830
+ if (!existsSync36(path))
121345
121831
  return { issues: [], dropped: new Set };
121346
121832
  const parsed = z5.object({
121347
121833
  issues: agentIssues,
@@ -121368,8 +121854,8 @@ function normalizeAgentIssue(raw) {
121368
121854
  }
121369
121855
  var agentIssues = z5.preprocess((v) => Array.isArray(v) ? v.map(normalizeAgentIssue) : v, z5.array(Issue).default([]));
121370
121856
  function readCardReview(runDir) {
121371
- const path = join49(runDir, CARD_REVIEW_FILE);
121372
- if (!existsSync35(path))
121857
+ const path = join50(runDir, CARD_REVIEW_FILE);
121858
+ if (!existsSync36(path))
121373
121859
  return { issues: [], hold: new Map };
121374
121860
  const parsed = z5.object({
121375
121861
  issues: agentIssues,
@@ -121431,12 +121917,12 @@ async function sweepFileCommand(opts) {
121431
121917
  for (const i of agent.issues)
121432
121918
  for (const e of i.evidence ?? [])
121433
121919
  if (!e.path.startsWith("/"))
121434
- e.path = join49(paths.runDir, e.path);
121920
+ e.path = join50(paths.runDir, e.path);
121435
121921
  const review = readCardReview(paths.runDir);
121436
121922
  for (const i of review.issues)
121437
121923
  for (const e of i.evidence ?? [])
121438
121924
  if (!e.path.startsWith("/"))
121439
- e.path = join49(paths.runDir, e.path);
121925
+ e.path = join50(paths.runDir, e.path);
121440
121926
  const { issues, held } = applyCardReview(mergeIssues(report.allIssues ?? [], agent.issues, agent.dropped), review);
121441
121927
  const info = {
121442
121928
  runId,
@@ -121575,7 +122061,7 @@ async function qaFileCommand(opts) {
121575
122061
  console.error(chalk38.red(`--min-severity ${opts.minSeverity}: use ${SEVERITIES2.join("|")}`));
121576
122062
  return 2;
121577
122063
  }
121578
- if (!existsSync36(opts.issues)) {
122064
+ if (!existsSync37(opts.issues)) {
121579
122065
  console.error(chalk38.red(`${opts.issues}: not found`));
121580
122066
  return 2;
121581
122067
  }
@@ -121590,7 +122076,7 @@ async function qaFileCommand(opts) {
121590
122076
  for (const i of [...parsed.data, ...review.issues])
121591
122077
  for (const e of i.evidence ?? [])
121592
122078
  if (!e.path.startsWith("/"))
121593
- e.path = join50(dir, e.path);
122079
+ e.path = join51(dir, e.path);
121594
122080
  const { issues, held } = applyCardReview(parsed.data, review);
121595
122081
  const cfg = studioConfigFromEnv();
121596
122082
  if (!cfg) {
@@ -121598,7 +122084,7 @@ async function qaFileCommand(opts) {
121598
122084
  return 2;
121599
122085
  }
121600
122086
  const info = {
121601
- runId: basename6(opts.issues).replace(/\.json$/, ""),
122087
+ runId: basename7(opts.issues).replace(/\.json$/, ""),
121602
122088
  source: "parity qa",
121603
122089
  url: opts.url,
121604
122090
  timestamp: new Date().toISOString(),
@@ -121645,8 +122131,8 @@ async function qaFileCommand(opts) {
121645
122131
  }
121646
122132
 
121647
122133
  // src/commands/report.ts
121648
- import { existsSync as existsSync37, readFileSync as readFileSync44, writeFileSync as writeFileSync36 } from "node:fs";
121649
- import { join as join51, resolve as resolve22 } from "node:path";
122134
+ import { existsSync as existsSync38, readFileSync as readFileSync44, writeFileSync as writeFileSync36 } from "node:fs";
122135
+ import { join as join52, resolve as resolve23 } from "node:path";
121650
122136
  import chalk39 from "chalk";
121651
122137
  import open3 from "open";
121652
122138
 
@@ -122297,12 +122783,12 @@ var REMOVED_SECTIONS = {
122297
122783
  prompt: "use `parity prompt <runId>` for the LLM-ready Markdown."
122298
122784
  };
122299
122785
  function resolveRunPaths(output, runIdOrDir) {
122300
- if (existsSync37(join51(runIdOrDir, "report.json")))
122301
- return runPathsFor(resolve22(runIdOrDir));
122786
+ if (existsSync38(join52(runIdOrDir, "report.json")))
122787
+ return runPathsFor(resolve23(runIdOrDir));
122302
122788
  return getRunPaths(output, runIdOrDir);
122303
122789
  }
122304
122790
  function ensureReportHtml(paths) {
122305
- if (existsSync37(paths.reportHtml))
122791
+ if (existsSync38(paths.reportHtml))
122306
122792
  return { path: paths.reportHtml, rendered: false };
122307
122793
  const run = loadRunDir(paths.runDir);
122308
122794
  writeRunReportHtml(paths.runDir, renderHtmlReport(run, paths.runDir));
@@ -122332,7 +122818,7 @@ async function reportCommand(runId, opts) {
122332
122818
  }
122333
122819
  }
122334
122820
  const html = renderDeckHtml(buildDeckModel(run, plan), opts.lang ?? "en");
122335
- const dest = opts.out ?? join51(paths.runDir, "deck.html");
122821
+ const dest = opts.out ?? join52(paths.runDir, "deck.html");
122336
122822
  writeFileSync36(dest, html, "utf8");
122337
122823
  console.log(`${chalk39.green("✓")} deck → ${dest}`);
122338
122824
  if (opts.open) {
@@ -122675,8 +123161,8 @@ async function rerenderCommand(opts) {
122675
123161
  import chalk41 from "chalk";
122676
123162
 
122677
123163
  // src/replay/outcome.ts
122678
- import { existsSync as existsSync38, readFileSync as readFileSync45, writeFileSync as writeFileSync38 } from "node:fs";
122679
- import { join as join52 } from "node:path";
123164
+ import { existsSync as existsSync39, readFileSync as readFileSync45, writeFileSync as writeFileSync38 } from "node:fs";
123165
+ import { join as join53 } from "node:path";
122680
123166
  import { z as z6 } from "zod";
122681
123167
  var EXPECTED_FILE = "expected.json";
122682
123168
  var ReplayOutcome = z6.object({
@@ -122700,14 +123186,14 @@ function buildOutcome(checks, issues, verdict, parityVersion) {
122700
123186
  };
122701
123187
  }
122702
123188
  function readExpected(dir) {
122703
- const file = join52(dir, EXPECTED_FILE);
122704
- if (!existsSync38(file))
123189
+ const file = join53(dir, EXPECTED_FILE);
123190
+ if (!existsSync39(file))
122705
123191
  throw new Error(`${file} not found (record the expectation with --update-expected)`);
122706
123192
  return ReplayOutcome.parse(JSON.parse(readFileSync45(file, "utf8")));
122707
123193
  }
122708
123194
  function writeExpected(dir, outcome) {
122709
- const file = join52(dir, EXPECTED_FILE);
122710
- const notes = existsSync38(file) ? readExpected(dir).notes : undefined;
123195
+ const file = join53(dir, EXPECTED_FILE);
123196
+ const notes = existsSync39(file) ? readExpected(dir).notes : undefined;
122711
123197
  const { notes: _drop, ...rest } = outcome;
122712
123198
  writeFileSync38(file, `${JSON.stringify({ ...rest, ...notes !== undefined ? { notes } : {} }, null, 2)}
122713
123199
  `, "utf8");
@@ -122745,9 +123231,9 @@ function formatDiff(d) {
122745
123231
  }
122746
123232
 
122747
123233
  // src/replay/replay.ts
122748
- import { mkdirSync as mkdirSync24, mkdtempSync as mkdtempSync2, rmSync as rmSync6 } from "node:fs";
123234
+ import { mkdirSync as mkdirSync25, mkdtempSync as mkdtempSync2, rmSync as rmSync6 } from "node:fs";
122749
123235
  import { tmpdir as tmpdir3 } from "node:os";
122750
- import { join as join53 } from "node:path";
123236
+ import { join as join54 } from "node:path";
122751
123237
  class NothingToJudgeError extends Error {
122752
123238
  name = "NothingToJudgeError";
122753
123239
  }
@@ -122759,8 +123245,8 @@ async function replayRecording(dir, opts = {}) {
122759
123245
  throw new NothingToJudgeError(`nothing was compared: ${dir} holds no page pairs and no flows`);
122760
123246
  }
122761
123247
  const ownsOutDir = opts.outDir === undefined;
122762
- const outDir = opts.outDir ?? mkdtempSync2(join53(tmpdir3(), "parity-replay-"));
122763
- mkdirSync24(outDir, { recursive: true });
123248
+ const outDir = opts.outDir ?? mkdtempSync2(join54(tmpdir3(), "parity-replay-"));
123249
+ mkdirSync25(outDir, { recursive: true });
122764
123250
  const ctx = { ...rec.ctx, outDir };
122765
123251
  const unrecorded = new Set;
122766
123252
  const restore = replayFetch(rec.fetchLog);
@@ -122877,7 +123363,7 @@ async function replayCommand(dir, opts) {
122877
123363
  }
122878
123364
 
122879
123365
  // src/commands/serve.ts
122880
- import { existsSync as existsSync39 } from "node:fs";
123366
+ import { existsSync as existsSync40 } from "node:fs";
122881
123367
  import chalk42 from "chalk";
122882
123368
  async function serveRunAndBlock(runDir, opts = {}) {
122883
123369
  let handle;
@@ -122925,7 +123411,7 @@ async function serveRunAndBlock(runDir, opts = {}) {
122925
123411
  }
122926
123412
  async function serveCommand(runId, opts) {
122927
123413
  const paths = getRunPaths(opts.output, runId);
122928
- if (!existsSync39(paths.runDir)) {
123414
+ if (!existsSync40(paths.runDir)) {
122929
123415
  console.error(chalk42.red(`✖ Run não encontrado: ${runId} (em ${opts.output})`));
122930
123416
  return 1;
122931
123417
  }
@@ -123798,8 +124284,8 @@ async function studioCommentCommand(opts, call = callTool2) {
123798
124284
 
123799
124285
  // src/commands/drift.ts
123800
124286
  import { spawnSync as spawnSync3 } from "node:child_process";
123801
- import { existsSync as existsSync40, readFileSync as readFileSync46 } from "node:fs";
123802
- import { resolve as resolve23 } from "node:path";
124287
+ import { existsSync as existsSync41, readFileSync as readFileSync46 } from "node:fs";
124288
+ import { resolve as resolve24 } from "node:path";
123803
124289
  import chalk46 from "chalk";
123804
124290
  var DRIFT_EXCLUDES = [":!.deco"];
123805
124291
  var SHA_RE = /^[0-9a-f]{7,64}$/i;
@@ -123918,7 +124404,7 @@ function computeDrift(inputs, opts) {
123918
124404
  const fail = (code, message) => ({ error: { code, message } });
123919
124405
  if (headRef.startsWith("-"))
123920
124406
  return fail("bad_head", `head "${headRef}" looks like a flag`);
123921
- if (!existsSync40(source))
124407
+ if (!existsSync41(source))
123922
124408
  return fail("not_a_repo", `${source} does not exist`);
123923
124409
  const inside = git(source, ["rev-parse", "--is-inside-work-tree"]);
123924
124410
  if (!inside.ok || inside.stdout.trim() !== "true") {
@@ -123986,7 +124472,7 @@ function computeDrift(inputs, opts) {
123986
124472
  };
123987
124473
  }
123988
124474
  function loadState(path) {
123989
- if (!existsSync40(path))
124475
+ if (!existsSync41(path))
123990
124476
  return null;
123991
124477
  try {
123992
124478
  return JSON.parse(readFileSync46(path, "utf8"));
@@ -123997,7 +124483,7 @@ function loadState(path) {
123997
124483
  function runDrift(flags) {
123998
124484
  let state = null;
123999
124485
  if (!(flags.source && flags.base)) {
124000
- const loaded = loadState(resolve23(flags.state ?? ".parity/migration.json"));
124486
+ const loaded = loadState(resolve24(flags.state ?? ".parity/migration.json"));
124001
124487
  if (loaded && "error" in loaded)
124002
124488
  return loaded;
124003
124489
  state = loaded;
@@ -124166,9 +124652,9 @@ function varianceCommand(opts) {
124166
124652
  }
124167
124653
 
124168
124654
  // src/commands/vitals.ts
124169
- import { existsSync as existsSync41, readFileSync as readFileSync47, writeFileSync as writeFileSync39 } from "node:fs";
124655
+ import { existsSync as existsSync42, readFileSync as readFileSync47, writeFileSync as writeFileSync39 } from "node:fs";
124170
124656
  import { availableParallelism } from "node:os";
124171
- import { join as join54 } from "node:path";
124657
+ import { join as join55 } from "node:path";
124172
124658
  import chalk48 from "chalk";
124173
124659
  import ora9 from "ora";
124174
124660
 
@@ -124217,7 +124703,7 @@ async function agenticNav(ctx) {
124217
124703
  note: "no Lighthouse data (run without --no-lighthouse)"
124218
124704
  });
124219
124705
  }
124220
- const candOrigin = originOf2(ctx.candPages);
124706
+ const candOrigin = originOf3(ctx.candPages);
124221
124707
  const llms = candOrigin ? await fetchLlmsTxtQuality(candOrigin) : null;
124222
124708
  const llmsOk = !!llms?.wellFormed;
124223
124709
  pillars.push({
@@ -124249,7 +124735,7 @@ async function agenticNav(ctx) {
124249
124735
  data: { agentic: { passed, total: applicable.length, pillars } }
124250
124736
  };
124251
124737
  }
124252
- function originOf2(pages) {
124738
+ function originOf3(pages) {
124253
124739
  for (const p of pages) {
124254
124740
  try {
124255
124741
  return new URL(p.url).origin;
@@ -124513,7 +124999,7 @@ async function vitalsCommand(opts) {
124513
124999
  });
124514
125000
  progress.succeed(`${total} capture(s) em ${((Date.now() - t0) / 1000).toFixed(1)}s`);
124515
125001
  if (opts.lighthouse !== false) {
124516
- const lhDir = join54(paths.runDir, "lighthouse");
125002
+ const lhDir = join55(paths.runDir, "lighthouse");
124517
125003
  const lhCap = opts.lighthouseConcurrency ?? Math.max(1, Math.min(2, Math.floor(availableParallelism() / 2)));
124518
125004
  const done = tasks.filter((t) => !!t.capture);
124519
125005
  const lhT0 = Date.now();
@@ -124602,7 +125088,7 @@ async function vitalsCommand(opts) {
124602
125088
  writeRunReportJson(paths.runDir, run);
124603
125089
  const html = renderHtmlReport(run, paths.runDir);
124604
125090
  writeRunReportHtml(paths.runDir, html);
124605
- writeFileSync39(join54(paths.runDir, "vitals.json"), `${JSON.stringify({
125091
+ writeFileSync39(join55(paths.runDir, "vitals.json"), `${JSON.stringify({
124606
125092
  schemaVersion: "0.1",
124607
125093
  prodUrl: opts.prod,
124608
125094
  candUrl: opts.cand,
@@ -124708,7 +125194,7 @@ async function discoverPagePaths2(prodUrl, opts) {
124708
125194
  function parseUrlList(input) {
124709
125195
  if (input.startsWith("file:") || input.endsWith(".txt") || input.endsWith(".list")) {
124710
125196
  const path = input.replace(/^file:\/\//, "");
124711
- if (existsSync41(path)) {
125197
+ if (existsSync42(path)) {
124712
125198
  return readFileSync47(path, "utf8").split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith("#")).map((s) => s.startsWith("/") ? s : `/${s}`);
124713
125199
  }
124714
125200
  }
@@ -124745,7 +125231,7 @@ program.command("run").description([
124745
125231
  " visual-pages=5, auto-selectors=ON (if LLM), learn=ON, visual-diff=ON,",
124746
125232
  " warmup=OFF, vitals warm=ON, bypass-cache=OFF, fail-on=critical (exit 1 if hit)."
124747
125233
  ].join(`
124748
- `)).option("--prod <url>", "Production URL (source of truth, e.g. Fresh site). Omit for a single site — the run will point you to `parity e2e` (issue #141).").requiredOption("--cand <url>", "Candidate URL (migrated site, e.g. TanStack)").option("--preset <name>", "Bundle of defaults: smoke (fast, ~30s, no LLM) | full (deep audit) | ci (CI-tuned)").option("--flows <list>", "Comma-separated flows: homepage,plp,pdp,purchase-journey", "purchase-journey").option("--viewports <list>", "Comma-separated viewports: mobile,desktop", "mobile,desktop").option("--cep <cep>", "CEP for shipping calculation", "01310-100").option("--prod-cookie <name=value>", "Cookie set on every prod browser context and plain request; repeatable. Pins prod to one A/B variant (e.g. a Fresh-vs-TanStack bucket cookie) so the run does not compare whichever build each fresh context drew. Values are redacted in logs and report.json.", collectCookie, []).option("--cand-cookie <name=value>", "Same as --prod-cookie, for the candidate side", collectCookie, []).option("--prod-header <Name: value>", "Request header sent on every prod request (all origins — no credentials); repeatable. The header twin of --prod-cookie. Values are redacted in logs and report.json.", collectHeader, []).option("--cand-header <Name: value>", "Same as --prod-header, for the candidate side", collectHeader, []).option("--add-to-cart-timeout <ms>", "How long (ms) the add-to-cart step polls for a success signal before failing. Default 3000. Raise/lower to match your site's success-toast lifetime (issue #143).", (v) => Number(v)).option("--runs <n>", "Repeat each measurement N times (median)", "1").option("--baseline <name>", "Compare against a saved baseline").option("--output <dir>", "Output directory", "./parity-output").option("--fail-on <severities>", "Comma-separated severities that cause exit 1 (default: critical)", "critical").option("--html", "Also write report.html (off by default: render it later with `parity report <runId>`)", false).option("--open", "Write report.html and open it after the run completes (implies --html)", false).option("--no-auto-selectors", "Disable LLM-based selector discovery (uses defaults instead)").option("--refresh-selectors", "Bypass selector cache and re-run discovery", false).option("--no-learn", "Don't write to learned-selectors.json (read-only mode)").option("--vitals-pages <n>", "Extra pages from sitemap to crawl for Vitals coverage, beyond what --flows/--pages already cover (default 10). These are auto-sampled and can add significant unrelated noise to findings — pass 0 to scope the run to only the pages you explicitly requested.", (v) => Number(v), 10).option("--max-viewport-concurrency <n>", "How many viewports run concurrently during collect (default 2: mobile+desktop together). Set to 1 if you hit OOM with many viewports.", (v) => Number(v), 2).option("--visual-pages <n>", "Pages to compare visually with the heatmap engine — pixel diff + box-tree diff, no LLM (home + sampled PLPs/PDPs from sitemap, default 5)", (v) => Number(v), 5).option("--pages <list>", 'Comma-separated paths to compare visually (overrides sitemap discovery). E.g. "/,/account,/p/some-product". Use "prod->cand" for a page that lives at DIFFERENT paths on each side (partial migration), e.g. "/encimera-gc60/p->/ar-condicionado-12k/p". Use this when you want deterministic coverage instead of sampled. Scopes the visual-diff + vitals-extra-pages passes ONLY — the flows crawl (--flows, default purchase-journey) discovers its own target pages independently and ignores this flag. To scope which page(s) a flow visits, use --flows to pick a lighter flow and/or set the matching *UrlHint (e.g. plpUrlHint) in .parityrc.json. Issue #178.').option("--pages-file <path>", `Read paths to compare visually from a text file (one entry per line). Lines starting with # are ignored. Accepts the same "prod->cand" pair syntax as --pages. Overrides --pages when both are present. Same visual-diff/vitals-only scope as --pages — see that flag's help. Issue #178.`).option("--no-visual-diff", "Skip the visual diff capture pass entirely").option("--no-cache", "Deprecated, no effect (the visual verdict cache is gone).").option("--clear-cache", "Deprecated, no effect (the visual verdict cache is gone).", false).option("--bypass-cache", "Bypass CDN/edge caches AND the browser's own HTTP cache (CDP cache-disable), forcing a cold-visit fetch. Use right after a deploy to avoid false failures from stale CF edge content, or to approximate Lighthouse/CrUX-comparable TTFB/FCP/LCP numbers — without this flag, parity's vitals are a warm-connection/cache-enabled ('repeat visit') measurement, not a cold first-visit one, so they aren't directly comparable 1:1 to Lighthouse.", false).option("--warmup", "Before measurement, hit each target URL once (per viewport) with a cache-buster so the Worker serves a fresh response. Recommended after deploys.", false).option("--no-warm", "Don't warm each side's URL before measuring vitals. By default every vitals-measured page is loaded once on BOTH sides first, in a throwaway page (same device + cookies), so a cold edge/loader cache on whichever side hit the route first isn't reported as a Web Vitals or CLS regression. Ignored under --bypass-cache, which measures cold on purpose. Distinct from --warmup (a cache-busted homepage hit after a deploy).").option("--accept-prod-quirks", "Demote prod-side cart-empty journey failures (VTEX session quirk) from failed to skipped. The cart-reveal-mode-divergence check still emits critical if prod/cand markup intents differ, so this flag never masks a real regression. See issue #12.", false).option("--cand-is-production", "Cand is the final production domain, not a staging host. Disables staging detection (cand on another host with noindex everywhere), so noindex/nofollow on cand is critical and third-party origins missing on cand are high again.", false).option("--record <dir>", "Save the exact input the checks ran on (captures with full page HTML, resolved config, visual probes, screenshots, and the fetches the checks made) into <dir>, which must be new or empty. Contains full HTML and screenshots of both sites: do not commit it.").option("--llm-timeout <seconds>", "Deprecated, no effect: topIssues is ranked deterministically now, there is no LLM aggregation call to time out.").option("--keep-runs <n>", "After the run, delete all but the n newest runs of this prod/cand host pair under --output (other host pairs, runs without a readable report.json and baseline-referenced runs are never touched). 0 keeps everything. Default: 10.", (v) => Number(v), 10).option("--timeout <minutes>", "Hard wall-clock cap for the whole run (minutes). On expiry, parity writes a partial report and exits 130. Default: 30. Issue #56.", (v) => Number(v), 30).option("--flow <name>", "Alias for --flows when running a single flow (e.g. --flow cart). Issue #53.").option("--json <path|->", "Emit JSON-Lines (one line per check) to the given file path, or '-' for stdout. Schema versioned via leading metadata line. Issue #53.").option("--pt", "Tell the LLM to respond in Brazilian Portuguese. Only affects LLM-generated content (issues, explain, prompts) — the static HTML report stays in English. Issue #67.").option("--llm <provider>", "Force LLM provider: anthropic | openrouter | claude-code | none. Default: auto-detect (anthropic key → openrouter key → local claude CLI → none). Issue #66.").option("--llm-model <overrides>", "Per-feature model override, e.g. visual-diff=claude-opus-5,explain=claude-opus-5. Features: selector-discovery, step-recovery, search-terms, plp-matching, pdp-matching, section-understanding, visual-diff, explain, component-detection. Issue #66.").option("--llm-tier-default <tier>", "Override the default tier (haiku | sonnet | opus) for every feature that doesn't have a per-feature override. Issue #66.").option("--llm-model-default <model>", "Force every LLM call to use this exact model ID, ignoring per-feature defaults. Issue #66.").option("--llm-premium", "Bump the reasoning-heavy features (explain/visual-diff) to opus. Defaults are sonnet-first for cost/latency (opus blew the 60s timeout on most runs); opt into opus for hard fixes. Issue #256.").option("--no-interactive", "Disable the interactive selector prompt that auto-fires in a TTY without an LLM provider. Use in scripts and CI where stdin is technically a TTY but you don't want to pause. Issue #72.").option("--only <modules>", "Scope the run to these modules and/or single checks (comma-separated). Module names: e2e, seo, visual, vitals, cache, console, html, network. Single-check granularity via `check:<name>`, e.g. `--only e2e,check:cache-coverage`. Run `parity list modules` for the full check/flow mapping. Default: all modules. M3 module selection.").option("--skip <modules>", "Subtract these modules and/or single checks (comma-separated, same syntax as --only) from whatever base set was chosen (all modules, or --only's set if both are given). M3 module selection.").option("--why <text>", "Free-text reason for this run's scope, stored in report.json as `selectionReason`. Purely informational. M3 module selection.").option("--profile <type>", "Site profile: commerce | content. Scopes modules/flows/CEP. `content` (blog/custom site with no storefront) drops the e2e purchase journey, scopes flows to the homepage, and skips CEP. Auto-detected from the platform when omitted. Issues #254/#255.").action(async (opts) => {
125234
+ `)).option("--prod <url>", "Production URL (source of truth, e.g. Fresh site). Omit for a single site — the run will point you to `parity e2e` (issue #141).").requiredOption("--cand <url>", "Candidate URL (migrated site, e.g. TanStack)").option("--preset <name>", "Bundle of defaults: smoke (fast, ~30s, no LLM) | full (deep audit) | ci (CI-tuned)").option("--flows <list>", "Comma-separated flows: homepage,plp,pdp,purchase-journey", "purchase-journey").option("--viewports <list>", "Comma-separated viewports: mobile,desktop", "mobile,desktop").option("--cep <cep>", "CEP for shipping calculation", "01310-100").option("--prod-cookie <name=value>", "Cookie set on every prod browser context and plain request; repeatable. Pins prod to one A/B variant (e.g. a Fresh-vs-TanStack bucket cookie) so the run does not compare whichever build each fresh context drew. Values are redacted in logs and report.json.", collectCookie, []).option("--cand-cookie <name=value>", "Same as --prod-cookie, for the candidate side", collectCookie, []).option("--prod-header <Name: value>", "Request header sent on every prod request (all origins — no credentials); repeatable. The header twin of --prod-cookie. Values are redacted in logs and report.json.", collectHeader, []).option("--cand-header <Name: value>", "Same as --prod-header, for the candidate side", collectHeader, []).option("--add-to-cart-timeout <ms>", "How long (ms) the add-to-cart step polls for a success signal before failing. Default 3000. Raise/lower to match your site's success-toast lifetime (issue #143).", (v) => Number(v)).option("--runs <n>", "Repeat each measurement N times (median)", "1").option("--baseline <name>", "Compare against a saved baseline").option("--output <dir>", "Output directory", "./parity-output").option("--fail-on <severities>", "Comma-separated severities that cause exit 1 (default: critical)", "critical").option("--html", "Also write report.html (off by default: render it later with `parity report <runId>`)", false).option("--open", "Write report.html and open it after the run completes (implies --html)", false).option("--no-auto-selectors", "Disable LLM-based selector discovery (uses defaults instead)").option("--refresh-selectors", "Bypass selector cache and re-run discovery", false).option("--no-learn", "Don't write to learned-selectors.json (read-only mode)").option("--vitals-pages <n>", "Extra pages from sitemap to crawl for Vitals coverage, beyond what --flows/--pages already cover (default 10). These are auto-sampled and can add significant unrelated noise to findings — pass 0 to scope the run to only the pages you explicitly requested.", (v) => Number(v), 10).option("--max-viewport-concurrency <n>", "How many viewports run concurrently during collect (default 2: mobile+desktop together). Set to 1 if you hit OOM with many viewports.", (v) => Number(v), 2).option("--visual-pages <n>", "Pages to compare visually with the heatmap engine — pixel diff + box-tree diff, no LLM (home + sampled PLPs/PDPs from sitemap, default 5)", (v) => Number(v), 5).option("--pages <list>", 'Comma-separated paths to compare visually (overrides sitemap discovery). E.g. "/,/account,/p/some-product". Use "prod->cand" for a page that lives at DIFFERENT paths on each side (partial migration), e.g. "/encimera-gc60/p->/ar-condicionado-12k/p". Use this when you want deterministic coverage instead of sampled. Scopes the visual-diff + vitals-extra-pages passes ONLY — the flows crawl (--flows, default purchase-journey) discovers its own target pages independently and ignores this flag. To scope which page(s) a flow visits, use --flows to pick a lighter flow and/or set the matching *UrlHint (e.g. plpUrlHint) in .parityrc.json. Issue #178.').option("--pages-file <path>", `Read paths to compare visually from a text file (one entry per line). Lines starting with # are ignored. Accepts the same "prod->cand" pair syntax as --pages. Overrides --pages when both are present. Same visual-diff/vitals-only scope as --pages — see that flag's help. Issue #178.`).option("--no-visual-diff", "Skip the visual diff capture pass entirely").option("--no-cache", "Deprecated, no effect (the visual verdict cache is gone).").option("--clear-cache", "Deprecated, no effect (the visual verdict cache is gone).", false).option("--bypass-cache", "Bypass CDN/edge caches AND the browser's own HTTP cache (CDP cache-disable), forcing a cold-visit fetch. Use right after a deploy to avoid false failures from stale CF edge content, or to approximate Lighthouse/CrUX-comparable TTFB/FCP/LCP numbers — without this flag, parity's vitals are a warm-connection/cache-enabled ('repeat visit') measurement, not a cold first-visit one, so they aren't directly comparable 1:1 to Lighthouse.", false).option("--warmup", "Before measurement, hit each target URL once (per viewport) with a cache-buster so the Worker serves a fresh response. Recommended after deploys.", false).option("--no-warm", "Don't warm each side's URL before measuring vitals. By default every vitals-measured page is loaded once on BOTH sides first, in a throwaway page (same device + cookies), so a cold edge/loader cache on whichever side hit the route first isn't reported as a Web Vitals or CLS regression. Ignored under --bypass-cache, which measures cold on purpose. Distinct from --warmup (a cache-busted homepage hit after a deploy).").option("--accept-prod-quirks", "Demote prod-side cart-empty journey failures (VTEX session quirk) from failed to skipped. The cart-reveal-mode-divergence check still emits critical if prod/cand markup intents differ, so this flag never masks a real regression. See issue #12.", false).option("--cand-is-production", "Cand is the final production domain, not a staging host. Disables staging detection (cand on another host with noindex everywhere), so noindex/nofollow on cand is critical and third-party origins missing on cand are high again.", false).option("--record <dir>", "Save the exact input the checks ran on (captures with full page HTML, resolved config, visual probes, screenshots, and the fetches the checks made) into <dir>, which must be new or empty. Contains full HTML and screenshots of both sites: do not commit it.").option("--golden <dir>", "Use the PROD half of a `--record` recording as the reference and capture only cand (--prod becomes optional). Pages come from the recording, prod-origin fetches by the checks are served from it, and a prod request it never saw is reported as stale (exit 2). Never written to. See docs/cli.md.").option("--llm-timeout <seconds>", "Deprecated, no effect: topIssues is ranked deterministically now, there is no LLM aggregation call to time out.").option("--keep-runs <n>", "After the run, delete all but the n newest runs of this prod/cand host pair under --output (other host pairs, runs without a readable report.json and baseline-referenced runs are never touched). 0 keeps everything. Default: 10.", (v) => Number(v), 10).option("--timeout <minutes>", "Hard wall-clock cap for the whole run (minutes). On expiry, parity writes a partial report and exits 130. Default: 30. Issue #56.", (v) => Number(v), 30).option("--flow <name>", "Alias for --flows when running a single flow (e.g. --flow cart). Issue #53.").option("--json <path|->", "Emit JSON-Lines (one line per check) to the given file path, or '-' for stdout. Schema versioned via leading metadata line. Issue #53.").option("--pt", "Tell the LLM to respond in Brazilian Portuguese. Only affects LLM-generated content (issues, explain, prompts) — the static HTML report stays in English. Issue #67.").option("--llm <provider>", "Force LLM provider: anthropic | openrouter | claude-code | none. Default: auto-detect (anthropic key → openrouter key → local claude CLI → none). Issue #66.").option("--llm-model <overrides>", "Per-feature model override, e.g. visual-diff=claude-opus-5,explain=claude-opus-5. Features: selector-discovery, step-recovery, search-terms, plp-matching, pdp-matching, section-understanding, visual-diff, explain, component-detection. Issue #66.").option("--llm-tier-default <tier>", "Override the default tier (haiku | sonnet | opus) for every feature that doesn't have a per-feature override. Issue #66.").option("--llm-model-default <model>", "Force every LLM call to use this exact model ID, ignoring per-feature defaults. Issue #66.").option("--llm-premium", "Bump the reasoning-heavy features (explain/visual-diff) to opus. Defaults are sonnet-first for cost/latency (opus blew the 60s timeout on most runs); opt into opus for hard fixes. Issue #256.").option("--no-interactive", "Disable the interactive selector prompt that auto-fires in a TTY without an LLM provider. Use in scripts and CI where stdin is technically a TTY but you don't want to pause. Issue #72.").option("--only <modules>", "Scope the run to these modules and/or single checks (comma-separated). Module names: e2e, seo, visual, vitals, cache, console, html, network. Single-check granularity via `check:<name>`, e.g. `--only e2e,check:cache-coverage`. Run `parity list modules` for the full check/flow mapping. Default: all modules. M3 module selection.").option("--skip <modules>", "Subtract these modules and/or single checks (comma-separated, same syntax as --only) from whatever base set was chosen (all modules, or --only's set if both are given). M3 module selection.").option("--why <text>", "Free-text reason for this run's scope, stored in report.json as `selectionReason`. Purely informational. M3 module selection.").option("--profile <type>", "Site profile: commerce | content. Scopes modules/flows/CEP. `content` (blog/custom site with no storefront) drops the e2e purchase journey, scopes flows to the homepage, and skips CEP. Auto-detected from the platform when omitted. Issues #254/#255.").action(async (opts) => {
124749
125235
  if (opts.flow) {
124750
125236
  opts.flows = opts.flow;
124751
125237
  }