tagreeve 0.6.1 → 0.6.2

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/README.md +3 -1
  2. package/dist/cli.js +659 -518
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -108,6 +108,7 @@ function pageTimeToEpoch(pageTime, offset) {
108
108
 
109
109
  // packages/core/src/records.ts
110
110
  var RECORD_SCHEMA_VERSION = 5;
111
+ var GTM_TAG_STATUSES = ["success", "failure", "exception", "timeout"];
111
112
 
112
113
  // packages/core/src/store.ts
113
114
  import { createReadStream } from "node:fs";
@@ -516,6 +517,9 @@ function* variants(text2, depth = 0, seen = /* @__PURE__ */ new Set()) {
516
517
  if (depth >= MAX_DEPTH) return;
517
518
  for (const decoded of base64Decodes(text2)) yield* variants(decoded, depth + 1, seen);
518
519
  }
520
+ function readings(text2) {
521
+ return [...variants(text2)];
522
+ }
519
523
  function fieldHashes(...values) {
520
524
  const hashes = /* @__PURE__ */ new Set();
521
525
  for (const value of values) {
@@ -909,17 +913,18 @@ var GCD_LETTERS = {
909
913
  v: { notSet: false, default: "granted", update: "granted" },
910
914
  l: { notSet: true }
911
915
  };
916
+ var gcdLetterAt = (gcd, i) => gcd[2 + 2 * i];
912
917
  function gcdSignals(gcd) {
913
918
  if (!gcd || gcd.length < 9) return void 0;
914
919
  const out = {};
915
920
  GCD_SIGNALS.forEach((name, i) => {
916
- out[name] = GCD_LETTERS[gcd[2 + 2 * i]] ?? { notSet: false, default: "unknown", update: "unknown" };
921
+ out[name] = GCD_LETTERS[gcdLetterAt(gcd, i)] ?? { notSet: false, default: "unknown", update: "unknown" };
917
922
  });
918
923
  return out;
919
924
  }
920
925
  function gcdLetters(gcd) {
921
926
  if (!gcdSignals(gcd)) return void 0;
922
- return GCD_SIGNALS.map((_, i) => gcd[2 + 2 * i] in GCD_LETTERS ? gcd[2 + 2 * i] : "?");
927
+ return GCD_SIGNALS.map((_, i) => gcdLetterAt(gcd, i) in GCD_LETTERS ? gcdLetterAt(gcd, i) : "?");
923
928
  }
924
929
  function gcdValue(signal) {
925
930
  if (signal.notSet) return "unknown";
@@ -1861,7 +1866,6 @@ var VENDOR_KEYS = /* @__PURE__ */ new Set(["vendor", "event", "page", "transport
1861
1866
  var GROUP_KEYS = ["consent", "ids", "params", "identity", "body"];
1862
1867
  var COOKIE_RULE_KEYS = ["cookie", "before", "in", "after", "from"];
1863
1868
  var TAG_RULE_KEYS = ["tag", "count", "after", "from"];
1864
- var TAG_STATUSES = ["success", "failure", "exception", "timeout"];
1865
1869
  var TAG_SELECTOR_KEYS = ["id", "name", "container", "event", "status", "side"];
1866
1870
  var MAX_TAG_TEXT = 200;
1867
1871
  var BODY_KEYS = ["has", "only", "ignore"];
@@ -1876,6 +1880,9 @@ var OPTION_KEYS = ["network", "seed", "consentTimeout", "graceWindow", "optional
1876
1880
  var MAX_DATALAYER_NAMES = 8;
1877
1881
  var DATALAYER_NAME_PATTERN = /^[A-Za-z_$][\w$]{0,63}$/;
1878
1882
  var NEVER_TRAPPED_NAMES = ["location", "Shopify", "__proto__", "constructor", "prototype"];
1883
+ function isDataLayerName(name) {
1884
+ return typeof name === "string" && DATALAYER_NAME_PATTERN.test(name) && !NEVER_TRAPPED_NAMES.includes(name);
1885
+ }
1879
1886
  var HOST_HINT = ", each a host such as cdn.example.com or a wildcard such as *.example.com";
1880
1887
  function isRegExp(source) {
1881
1888
  try {
@@ -1899,6 +1906,11 @@ function parseDuration(value) {
1899
1906
  const unit = m[2] ?? "ms";
1900
1907
  return Number(m[1]) * (unit === "m" ? 6e4 : unit === "s" ? 1e3 : 1);
1901
1908
  }
1909
+ function durationAt(value, path, fail) {
1910
+ const ms = parseDuration(value);
1911
+ if (ms === void 0) fail(path, "must be a duration such as 4s, 500ms or 2m");
1912
+ return ms;
1913
+ }
1902
1914
  function parseCount(value) {
1903
1915
  const text2 = String(value).trim();
1904
1916
  const m = /^(>=|<=|>|<|=)?\s*(\d+)$/.exec(text2);
@@ -1951,7 +1963,7 @@ function parseOptions(raw, path, fail, { keys = OPTION_KEYS, echo = true } = {})
1951
1963
  } else if (k === "dataLayerNames") {
1952
1964
  const names = Array.isArray(v) ? v : [];
1953
1965
  if (!Array.isArray(v) || v.length === 0 || v.length > MAX_DATALAYER_NAMES) fail(p, `must be a list of 1 to ${MAX_DATALAYER_NAMES} global names such as myLayer`);
1954
- else if (!names.every((x) => typeof x === "string" && DATALAYER_NAME_PATTERN.test(x) && !NEVER_TRAPPED_NAMES.includes(x))) {
1966
+ else if (!names.every(isDataLayerName)) {
1955
1967
  fail(p, `each name must be a plain identifier of at most 64 characters (letters, digits, _ and $), and not ${NEVER_TRAPPED_NAMES.join(", ")}`);
1956
1968
  } else options.dataLayerNames = [...new Set(v)];
1957
1969
  } else if (k === "serverHosts") {
@@ -1985,9 +1997,9 @@ function parseOptions(raw, path, fail, { keys = OPTION_KEYS, echo = true } = {})
1985
1997
  if (isHostList(v)) options.firstPartyHosts = v;
1986
1998
  else fail(p, `must be a list of hosts${HOST_HINT}`);
1987
1999
  } else {
1988
- const ms = parseDuration(v);
1989
- if (ms === void 0) fail(p, "must be a duration such as 4s or 500ms");
1990
- else if (k === "consentTimeout") options.consentTimeout = ms;
2000
+ const ms = durationAt(v, p, fail);
2001
+ if (ms === void 0) continue;
2002
+ if (k === "consentTimeout") options.consentTimeout = ms;
1991
2003
  else if (k === "optionalTimeout") {
1992
2004
  if (ms < 100 || ms > 3e4) fail(p, "must be from 100ms to 30s");
1993
2005
  else options.optionalTimeout = ms;
@@ -2188,9 +2200,7 @@ function parseScenario(text2, extraVendorKeys = []) {
2188
2200
  const until = value.until === void 0 ? void 0 : condition(value.until, [...at, "until"]);
2189
2201
  const duration = (key) => {
2190
2202
  if (value[key] === void 0) return void 0;
2191
- const ms = parseDuration(value[key]);
2192
- if (ms === void 0) fail([...at, key], "must be a duration such as 4s, 500ms or 10m");
2193
- return ms;
2203
+ return durationAt(value[key], [...at, key], fail);
2194
2204
  };
2195
2205
  const settle = duration("settle");
2196
2206
  const timeout = duration("timeout");
@@ -2285,8 +2295,7 @@ function parseScenario(text2, extraVendorKeys = []) {
2285
2295
  const url = urlMatcher(value.url, [...path, kind, "url"]);
2286
2296
  let timeout;
2287
2297
  if ("timeout" in value) {
2288
- timeout = parseDuration(value.timeout);
2289
- if (timeout === void 0) fail([...path, kind, "timeout"], "must be a duration such as 90s or 2m");
2298
+ timeout = durationAt(value.timeout, [...path, kind, "timeout"], fail);
2290
2299
  }
2291
2300
  if (url && (!("timeout" in value) || timeout !== void 0)) add2({ kind, value: timeout === void 0 ? { url } : { url, timeout } });
2292
2301
  }
@@ -2342,7 +2351,7 @@ function parseScenario(text2, extraVendorKeys = []) {
2342
2351
  } else if (key === "status") {
2343
2352
  const items = Array.isArray(raw2) ? raw2 : [raw2];
2344
2353
  if (items.length === 0 || !items.every((x) => typeof x === "string" && x && x.length <= MAX_FIELD_NAME)) fail(p, "must be a status or a list of statuses");
2345
- else if (!items.every((x) => TAG_STATUSES.includes(x))) fail(p, `must be one of ${TAG_STATUSES.join(", ")}`);
2354
+ else if (!items.every((x) => GTM_TAG_STATUSES.includes(x))) fail(p, `must be one of ${GTM_TAG_STATUSES.join(", ")}`);
2346
2355
  else tag.status = items;
2347
2356
  } else if (key === "side") {
2348
2357
  if (raw2 === "web" || raw2 === "server") tag.side = raw2;
@@ -2636,8 +2645,15 @@ function nameOf(report, tag, expected) {
2636
2645
  return named ? { name: named, from: "expectedTags" } : void 0;
2637
2646
  }
2638
2647
  var tagLabel = (id, name) => name ? `${maskTagId(id)} ${maskTagName(name)}` : maskTagId(id);
2648
+ function expectedTagsOf(run) {
2649
+ const override = run?.gtmOverride;
2650
+ return override ? { container: override.container, tags: override.expectedTags } : void 0;
2651
+ }
2652
+ function listWithMore(items, max) {
2653
+ return items.length > max ? `${items.slice(0, max).join(", ")} and ${items.length - max} more` : items.join(", ");
2654
+ }
2639
2655
  function listLabels(labels) {
2640
- return labels.length > MAX_LISTED2 ? `${labels.slice(0, MAX_LISTED2).join(", ")} and ${labels.length - MAX_LISTED2} more` : labels.join(", ");
2656
+ return listWithMore(labels, MAX_LISTED2);
2641
2657
  }
2642
2658
  function evaluateTagRule(rule, input) {
2643
2659
  const selector = rule.tag;
@@ -2726,7 +2742,6 @@ function summarizeTags(reports, expected) {
2726
2742
  var DEFAULT_GRACE_MS = 50;
2727
2743
  var MAX_LISTED3 = 5;
2728
2744
  var MAX_NAMES = 12;
2729
- var GOOGLE_VENDORS2 = /* @__PURE__ */ new Set(["ga4", "google-ads"]);
2730
2745
  function evaluate(records, scenario, options = {}) {
2731
2746
  const runRecord = records.find((r) => r.type === "run");
2732
2747
  const runId = runRecord?.id ?? records.find((r) => "runId" in r)?.runId ?? newId("run");
@@ -2743,7 +2758,7 @@ function evaluate(records, scenario, options = {}) {
2743
2758
  responses: records.filter((r) => r.type === "response"),
2744
2759
  checkpoints: records.filter((r) => r.type === "checkpoint"),
2745
2760
  tagReports: records.filter((r) => r.type === "tagReport"),
2746
- ...runRecord?.gtmOverride && { expectedTags: { container: runRecord.gtmOverride.container, tags: runRecord.gtmOverride.expectedTags } },
2761
+ expectedTags: expectedTagsOf(runRecord),
2747
2762
  networkMode: runRecord?.networkMode,
2748
2763
  grace: options.graceWindowMs ?? scenario.options.graceWindow ?? DEFAULT_GRACE_MS,
2749
2764
  identity: options.identity ?? identityOf(runRecord)
@@ -2769,8 +2784,11 @@ function evaluate(records, scenario, options = {}) {
2769
2784
  const { pass, evidence, message } = outcome;
2770
2785
  const passes = (c) => evaluateRuleHits(rule, c).pass;
2771
2786
  const scoped = !rule.tag && isScoped(rule);
2772
- const note = outcome.note ?? (pass && scoped && passRestsOnProbableLink(ctx, passes) ? "serverSendProbableLink" : void 0);
2773
- add2(`${kind}: ${rule.description}`, pass, evidence, message, void 0, note, scoped && (pass || failureRestsOnProbableLink(ctx, passes)));
2787
+ const failureRests = scoped && !pass && failureRestsOnProbableLink(ctx, passes, rule);
2788
+ const ownNote = outcome.note === "nestedNameOnly" ? void 0 : outcome.note;
2789
+ const note = ownNote ?? (pass && scoped && passRestsOnProbableLink(ctx, passes, rule) ? "serverSendProbableLink" : outcome.note);
2790
+ const countRests = kind === "must" && failureRests && !ownNote;
2791
+ add2(`${kind}: ${rule.description}`, pass, evidence, message, countRests ? "warn" : void 0, countRests ? "serverSendProbableLink" : note, scoped && (pass || failureRests));
2774
2792
  }
2775
2793
  builtInChecks(records, scenario, ctx, add2);
2776
2794
  return results;
@@ -2786,6 +2804,37 @@ function ruleWindowStart(rule, ctx) {
2786
2804
  }
2787
2805
  return rule.from ? { at: step.startedAt, text: `from ${label}` } : { at: step.endedAt ?? step.startedAt, text: `after ${label}` };
2788
2806
  }
2807
+ var MAX_SEARCHED_HITS = 10;
2808
+ var dependsOnWhichHits = (rule) => rule.count?.op === "=" || Boolean(rule.body || rule.hashesMatch);
2809
+ var isPlainExactCount = (rule) => rule.count?.op === "=" && !rule.body && !rule.hashesMatch;
2810
+ function placementsChange(ctx, rule, unlinked, probable, base2) {
2811
+ const byLink = scopedIds(rule, ctx);
2812
+ const byOwnTime = new Set(probable.filter((h) => scopedIds(rule, asBrowserHits(ctx, [h])).has(h.id)).map((h) => h.id));
2813
+ const reach = probable.filter((h) => byLink.has(h.id) || byOwnTime.has(h.id));
2814
+ if (unlinked.length + reach.length === 0) return false;
2815
+ const reachIds = new Set(reach.map((h) => h.id));
2816
+ const run = (placed, selected) => {
2817
+ const chosen = new Set(selected.map((h) => h.id));
2818
+ const moved = asBrowserHits(ctx, selected.filter((h) => !byLink.has(h.id)));
2819
+ const placedCtx = { ...moved, hits: moved.hits.filter((h) => chosen.has(h.id) || !reachIds.has(h.id)), anywhere: new Set(placed.map((h) => h.id)) };
2820
+ return evaluateRuleHits(rule, placedCtx).pass !== base2;
2821
+ };
2822
+ if (!dependsOnWhichHits(rule)) return run(unlinked, reach) || run([], []);
2823
+ const prefixes = isPlainExactCount(rule);
2824
+ if (!prefixes && unlinked.length + reach.length > MAX_SEARCHED_HITS) return true;
2825
+ if (prefixes) {
2826
+ for (let k = 0; k <= unlinked.length + reach.length; k++) {
2827
+ const u = Math.min(k, unlinked.length);
2828
+ if (run(unlinked.slice(0, u), reach.slice(0, k - u))) return true;
2829
+ }
2830
+ return false;
2831
+ }
2832
+ for (let u = 0; u < 2 ** unlinked.length; u++) {
2833
+ const placed = unlinked.filter((_, i) => u & 2 ** i);
2834
+ for (let code = 0; code < 2 ** reach.length; code++) if (run(placed, reach.filter((_, i) => code & 2 ** i))) return true;
2835
+ }
2836
+ return false;
2837
+ }
2789
2838
  function evaluateRule(rule, ctx) {
2790
2839
  const outcome = evaluateRuleHits(rule, ctx);
2791
2840
  if (rule.cookie || rule.tag || !isScoped(rule)) return outcome;
@@ -2794,9 +2843,11 @@ function evaluateRule(rule, ctx) {
2794
2843
  if (rule.kind === "mustNot") {
2795
2844
  if (!outcome.pass) return outcome;
2796
2845
  } else {
2797
- const exact = rule.count?.op === "=";
2798
- const sizes = exact ? Array.from({ length: unjudged.length }, (_, i) => i + 1) : [unjudged.length];
2799
- const changes = sizes.some((k) => evaluateRuleHits(rule, { ...ctx, anywhere: new Set(unjudged.slice(0, k).map((h) => h.id)) }).pass !== outcome.pass);
2846
+ let changes = placementsChange(ctx, rule, unjudged, [], outcome.pass);
2847
+ if (!changes) {
2848
+ const probable = probableHits(ctx, rule);
2849
+ changes = probable.length > 0 && !placementsChange(ctx, rule, [], probable, outcome.pass) && placementsChange(ctx, rule, unjudged, probable, outcome.pass);
2850
+ }
2800
2851
  if (!changes) return outcome;
2801
2852
  }
2802
2853
  return {
@@ -2817,23 +2868,25 @@ function asBrowserHits(ctx, hits) {
2817
2868
  }
2818
2869
  return { ...ctx, requests, index: judgeIndex(ctx.hits, requests) };
2819
2870
  }
2820
- function passRestsOnProbableLink(ctx, passes) {
2871
+ function probableHits(ctx, rule) {
2821
2872
  const probable = ctx.hits.filter((h) => h.via?.confidence === "probable" && viaHitOf(h, ctx.index) !== void 0);
2822
- return probable.length > 0 && !passes(asBrowserHits(ctx, probable));
2873
+ return rule ? probable.filter((h) => matchesFilter(h, { ...rule.filter, consent: {} }, ctx)) : probable;
2823
2874
  }
2824
- function failureRestsOnProbableLink(ctx, passes) {
2825
- const probable = ctx.hits.filter((h) => h.via?.confidence === "probable" && viaHitOf(h, ctx.index) !== void 0);
2875
+ function passRestsOnProbableLink(ctx, passes, rule) {
2876
+ const probable = probableHits(ctx, rule);
2877
+ if (probable.length === 0) return false;
2878
+ if (!rule) return !passes(asBrowserHits(ctx, probable));
2879
+ return placementsChange(ctx, rule, [], probable, true);
2880
+ }
2881
+ function failureRestsOnProbableLink(ctx, passes, rule) {
2882
+ const probable = probableHits(ctx, rule);
2826
2883
  if (probable.length === 0) return false;
2827
2884
  const ids = new Set(probable.map((h) => h.id));
2828
- return passes(asBrowserHits(ctx, probable)) || passes({ ...ctx, hits: ctx.hits.filter((h) => !ids.has(h.id)) });
2885
+ const leftOut = () => passes({ ...ctx, hits: ctx.hits.filter((h) => !ids.has(h.id)) });
2886
+ if (!rule) return passes(asBrowserHits(ctx, probable)) || leftOut();
2887
+ return placementsChange(ctx, rule, [], probable, false);
2829
2888
  }
2830
- function evaluateRuleHits(rule, ctx) {
2831
- if (rule.tag) {
2832
- const window2 = ruleWindowStart(rule, ctx);
2833
- if (window2 && "message" in window2) return window2;
2834
- return evaluateTagRule(rule, { reports: ctx.tagReports, expected: ctx.expectedTags, window: window2 });
2835
- }
2836
- if (rule.cookie) return evaluateCookieRule(rule, rule.cookie, ctx);
2889
+ function scopedHits(rule, ctx) {
2837
2890
  const anywhere = (h) => ctx.anywhere?.has(h.id) ?? false;
2838
2891
  let hits = ctx.hits.filter((h) => matchesFilter(h, anywhere(h) ? { ...rule.filter, consent: {} } : rule.filter, ctx));
2839
2892
  const total2 = hits.length;
@@ -2858,6 +2911,22 @@ function evaluateRuleHits(rule, ctx) {
2858
2911
  });
2859
2912
  narrowed.push(text2);
2860
2913
  }
2914
+ return { hits, total: total2, narrowed };
2915
+ }
2916
+ var scopedIds = (rule, ctx) => {
2917
+ const scope = scopedHits(rule, ctx);
2918
+ return new Set("hits" in scope ? scope.hits.map((h) => h.id) : []);
2919
+ };
2920
+ function evaluateRuleHits(rule, ctx) {
2921
+ if (rule.tag) {
2922
+ const window2 = ruleWindowStart(rule, ctx);
2923
+ if (window2 && "message" in window2) return window2;
2924
+ return evaluateTagRule(rule, { reports: ctx.tagReports, expected: ctx.expectedTags, window: window2 });
2925
+ }
2926
+ if (rule.cookie) return evaluateCookieRule(rule, rule.cookie, ctx);
2927
+ const scope = scopedHits(rule, ctx);
2928
+ if ("message" in scope) return scope;
2929
+ const { hits, total: total2, narrowed } = scope;
2861
2930
  const where2 = narrowed.length ? ` ${narrowed.join(", ")}` : "";
2862
2931
  const vacuous = rule.before ? vacuousBeforeConsent(rule, ctx) : void 0;
2863
2932
  if (rule.body) return evaluateBodyRule(rule, rule.body, hits, where2, total2, vacuous);
@@ -3109,7 +3178,7 @@ function describeSelector(filter) {
3109
3178
  }
3110
3179
  function vacuousBeforeConsent(rule, ctx) {
3111
3180
  const vendors = rule.filter.vendor;
3112
- if (!vendors || vendors.some((v) => GOOGLE_VENDORS2.has(v))) return void 0;
3181
+ if (!vendors || vendors.some((v) => GOOGLE_VENDORS.has(v))) return void 0;
3113
3182
  const first = ctx.epochs[0];
3114
3183
  const state = first?.label === "undecided" ? first.state : void 0;
3115
3184
  const blocked = consentFields.filter((f) => {
@@ -3238,7 +3307,7 @@ function effectiveConsentAt(hit, epochs, graceMs, index) {
3238
3307
  if (t === void 0) return { analytics: "unknown", ads: "unknown", adUserData: "unknown", adPersonalization: "unknown" };
3239
3308
  const source = index && viaHitOf(hit, index) || hit;
3240
3309
  const base2 = epochForHit(epochs, t, graceMs)?.state;
3241
- const own = GOOGLE_VENDORS2.has(source.vendor) && consentFields.some((f) => source.consent[f] !== "unknown");
3310
+ const own = GOOGLE_VENDORS.has(source.vendor) && consentFields.some((f) => source.consent[f] !== "unknown");
3242
3311
  const pick2 = (f) => {
3243
3312
  if (own) return source.consent[f];
3244
3313
  return base2 ? base2[f] : "unknown";
@@ -3273,7 +3342,7 @@ function inEpoch(hit, selector, ctx) {
3273
3342
  if (isUnlinkedServerHit(hit, ctx.index)) return false;
3274
3343
  if (selector === "undecided") return inUndecidedEpoch(hit, ctx);
3275
3344
  if (selector.startsWith("label=")) return epochOf(hit, ctx)?.label === selector.slice("label=".length);
3276
- if ((selector === "granted" || selector === "denied") && !GOOGLE_VENDORS2.has(hit.vendor)) {
3345
+ if ((selector === "granted" || selector === "denied") && !GOOGLE_VENDORS.has(hit.vendor)) {
3277
3346
  const epoch = epochOf(hit, ctx);
3278
3347
  return (epoch?.outcome ?? epoch?.label) === selector;
3279
3348
  }
@@ -3307,6 +3376,8 @@ function joinLabels(labels) {
3307
3376
  }
3308
3377
  var PLAIN_ADDRESS_PARAMS = /* @__PURE__ */ new Set(["user_data.city", "user_data.postal_code", "user_data.country"]);
3309
3378
  var PLAIN_ADDRESS_VENDORS = /* @__PURE__ */ new Set(["sgtm"]);
3379
+ var HASH_REQUIRED_VENDORS = /* @__PURE__ */ new Set(["meta-capi"]);
3380
+ var HASH_MESSAGE_VENDOR_LABELS = { "meta-capi": "the Conversions API" };
3310
3381
  var DIGEST_SHAPE = /^(?:[0-9a-f]{64}|[A-Za-z0-9+/_-]{43}=?)$/i;
3311
3382
  function allForms(h) {
3312
3383
  return [h.hex, h.base64, h.base64url];
@@ -3330,7 +3401,7 @@ function hashJudge(identity) {
3330
3401
  if (known.has(value)) return "match";
3331
3402
  const typed = value.trim().toLowerCase();
3332
3403
  if (plain.has(typed) || accepted.some((v) => v.trim().toLowerCase() === typed)) return "unhashed";
3333
- return PLAIN_ADDRESS_PARAMS.has(name) && vendor === "meta-capi" && !DIGEST_SHAPE.test(value) ? "plain" : "wrong";
3404
+ return PLAIN_ADDRESS_PARAMS.has(name) && HASH_REQUIRED_VENDORS.has(vendor) && !DIGEST_SHAPE.test(value) ? "plainRequired" : "wrong";
3334
3405
  };
3335
3406
  }
3336
3407
  function capiMatchesIdentity(hit, field, identity) {
@@ -3354,12 +3425,13 @@ function checkHashes(hits, ctx) {
3354
3425
  const withHash = [];
3355
3426
  const wrong = [];
3356
3427
  const unhashed = [];
3357
- const plainCapi = [];
3428
+ const plainRequired = [];
3358
3429
  const wrongFields = /* @__PURE__ */ new Set();
3359
3430
  const wrongParams = /* @__PURE__ */ new Set();
3360
3431
  const matchedFields = /* @__PURE__ */ new Set();
3361
3432
  const unhashedFields = /* @__PURE__ */ new Set();
3362
- const plainCapiFields = /* @__PURE__ */ new Set();
3433
+ const plainRequiredFields = /* @__PURE__ */ new Set();
3434
+ const plainRequiredVendors = /* @__PURE__ */ new Set();
3363
3435
  const plainAddressFields = /* @__PURE__ */ new Set();
3364
3436
  const uncheckedFields = /* @__PURE__ */ new Set();
3365
3437
  for (const hit of hits) {
@@ -3375,10 +3447,12 @@ function checkHashes(hits, ctx) {
3375
3447
  if (!verdict) continue;
3376
3448
  const label = fieldLabel(identityParamName(hit.vendor, name));
3377
3449
  if (verdict === "plain") {
3378
- if (hit.vendor === "meta-capi") {
3379
- plainCapiFields.add(label);
3380
- plainHit = true;
3381
- } else plainAddressFields.add(label);
3450
+ plainAddressFields.add(label);
3451
+ continue;
3452
+ }
3453
+ if (verdict === "plainRequired") {
3454
+ plainRequiredFields.add(label);
3455
+ plainHit = true;
3382
3456
  continue;
3383
3457
  }
3384
3458
  seen = true;
@@ -3398,7 +3472,10 @@ function checkHashes(hits, ctx) {
3398
3472
  if (seen) withHash.push(hit.id);
3399
3473
  if (bad2) wrong.push(hit.id);
3400
3474
  if (raw) unhashed.push(hit.id);
3401
- if (plainHit) plainCapi.push(hit.id);
3475
+ if (plainHit) {
3476
+ plainRequired.push(hit.id);
3477
+ plainRequiredVendors.add(HASH_MESSAGE_VENDOR_LABELS[hit.vendor] ?? hit.vendor);
3478
+ }
3402
3479
  }
3403
3480
  const several = hits.length > 1;
3404
3481
  const they = several ? "they" : "it";
@@ -3411,12 +3488,13 @@ function checkHashes(hits, ctx) {
3411
3488
  const message = `the hashed ${joinLabels(wrongFields)} values ${they} carried do not match the run identity${of(wrong.length)}. Not matching: ${[...wrongParams].join(", ")}.` + (matching.size ? ` Matching: ${joinLabels(matching)}.` : "");
3412
3489
  return { pass: false, evidence: wrong, headline: UNMATCHED_HEADLINE, message };
3413
3490
  }
3414
- if (plainCapi.length) {
3491
+ if (plainRequired.length) {
3492
+ const who = joinLabels(plainRequiredVendors).replace(/^the /, "The ");
3415
3493
  return {
3416
3494
  pass: false,
3417
- evidence: plainCapi,
3495
+ evidence: plainRequired,
3418
3496
  headline: UNMATCHED_HEADLINE,
3419
- message: `${they} carried a plain ${joinLabels(plainCapiFields)}, not a hash${of(plainCapi.length)}. The Conversions API takes these hashed.`
3497
+ message: `${they} carried a plain ${joinLabels(plainRequiredFields)}, not a hash${of(plainRequired.length)}. ${who} ${plainRequiredVendors.size > 1 ? "take" : "takes"} these hashed.`
3420
3498
  };
3421
3499
  }
3422
3500
  if (!withHash.length && uncheckedFields.size) {
@@ -3841,62 +3919,59 @@ function bodyTexts(headers, body) {
3841
3919
  }
3842
3920
  return isBinaryText(body) ? [] : [{ text: body, where: "the body" }, ...leafTexts(body)];
3843
3921
  }
3922
+ var JSON_ESCAPES = { n: "\n", r: "\r", t: " ", b: "\b", f: "\f", '"': '"', "\\": "\\", "/": "/" };
3923
+ function jsonUnescaped(text2) {
3924
+ return text2.replace(/\\(?:u([0-9a-f]{4})|(.))/gi, (m, hex, ch) => hex ? String.fromCharCode(parseInt(hex, 16)) : JSON_ESCAPES[ch] ?? m);
3925
+ }
3926
+ function percentLayers(text2) {
3927
+ const layers = [text2];
3928
+ for (let i = 0; i < 4; i++) {
3929
+ const next = text2.replace(/(?:%[0-9a-f]{2})+/gi, (run) => {
3930
+ try {
3931
+ return decodeURIComponent(run);
3932
+ } catch {
3933
+ return run;
3934
+ }
3935
+ });
3936
+ if (next === text2) break;
3937
+ layers.push(text2 = next);
3938
+ }
3939
+ return layers;
3940
+ }
3941
+ function bodyForms(raw) {
3942
+ const stripped = raw.replace(/\[\]|%5B%5D/gi, "");
3943
+ const textForms = new Set(percentLayers(stripped).flatMap((layer) => [layer, jsonUnescaped(layer)]));
3944
+ const decoded = [...textForms].flatMap((form) => readings(form)).filter((form) => !textForms.has(form));
3945
+ return { textForms, decoded };
3946
+ }
3844
3947
  function isEdgeShift(a, b, bodies) {
3845
3948
  const [short, long] = a.length <= b.length ? [a, b] : [b, a];
3846
3949
  if (!long.includes(short)) return false;
3847
3950
  let sawLong = false;
3848
- const ok = bodies.every(
3849
- (raw) => readingForms(raw.replace(/\[\]|%5B%5D/gi, "")).every((text2) => {
3850
- if (!text2.includes(long)) return true;
3851
- sawLong = true;
3951
+ const ok = bodies.every(({ textForms, decoded }) => {
3952
+ return [...textForms, ...decoded].every((text2) => {
3953
+ if (text2.includes(long)) {
3954
+ if (textForms.has(text2)) sawLong = true;
3955
+ } else if (textForms.has(text2)) return true;
3852
3956
  const covered = [];
3853
3957
  for (let i = text2.indexOf(long); i >= 0; i = text2.indexOf(long, i + 1)) covered.push([i, i + long.length]);
3854
3958
  for (let i = text2.indexOf(short); i >= 0; i = text2.indexOf(short, i + 1)) {
3855
3959
  if (!covered.some(([from, to]) => i >= from && i + short.length <= to)) return false;
3856
3960
  }
3857
3961
  return true;
3858
- })
3859
- );
3860
- return ok && sawLong;
3861
- }
3862
- var JSON_ESCAPES = { n: "\n", r: "\r", t: " ", b: "\b", f: "\f", '"': '"', "\\": "\\", "/": "/" };
3863
- function percentDecoded(text2) {
3864
- return text2.replace(/(?:%[0-9a-f]{2})+/gi, (run) => {
3865
- try {
3866
- return decodeURIComponent(run);
3867
- } catch {
3868
- return run;
3869
- }
3870
- });
3871
- }
3872
- function base64InPlace(text2) {
3873
- return text2.replace(/[A-Za-z0-9+/_-]{12,}={0,2}/g, (token) => {
3874
- const decoded = Buffer.from(token, "base64").toString("utf8");
3875
- return decoded.includes("\uFFFD") ? token : decoded;
3962
+ });
3876
3963
  });
3877
- }
3878
- function readingForms(text2) {
3879
- const forms = /* @__PURE__ */ new Set([text2]);
3880
- let layer = text2;
3881
- for (let i = 0; i < 4; i++) {
3882
- const next = percentDecoded(layer);
3883
- if (next === layer) break;
3884
- forms.add(layer = next);
3885
- }
3886
- for (const form of [...forms]) {
3887
- forms.add(form.replace(/\\(?:u([0-9a-f]{4})|(.))/gi, (m, hex, ch) => hex ? String.fromCharCode(parseInt(hex, 16)) : JSON_ESCAPES[ch] ?? m));
3888
- }
3889
- for (const form of [...forms]) forms.add(base64InPlace(form));
3890
- return [...forms];
3964
+ return ok && sawLong;
3891
3965
  }
3892
3966
  function mergeEdgeReadings(found, bodies) {
3893
3967
  const best = (f) => Math.min(...f.where.values());
3894
3968
  const valueOf3 = (key, kind) => key.slice(kind.length + 1);
3895
3969
  const fields2 = [...found].filter(([, f]) => best(f) < 2);
3970
+ let forms;
3896
3971
  for (const [key, f] of [...found]) {
3897
3972
  if (best(f) < 2 || [...f.where.keys()].some((w) => w !== "the body")) continue;
3898
3973
  const value = valueOf3(key, f.kind);
3899
- const twin = fields2.find(([k, other]) => other.kind === f.kind && isEdgeShift(valueOf3(k, other.kind), value, bodies));
3974
+ const twin = fields2.find(([k, other]) => other.kind === f.kind && isEdgeShift(valueOf3(k, other.kind), value, forms ??= bodies.map(bodyForms)));
3900
3975
  if (!twin) continue;
3901
3976
  for (const [w, tier] of f.where) twin[1].where.set(w, Math.min(tier, twin[1].where.get(w) ?? tier));
3902
3977
  found.delete(key);
@@ -3956,7 +4031,7 @@ function findForeignData(requests, hits, identity, dataLayerEvents = []) {
3956
4031
  const best = Math.min(...where2.values());
3957
4032
  for (const [w, tier] of where2) if (tier === best) places.add(w);
3958
4033
  }
3959
- const shown2 = [...places].sort();
4034
+ const shown2 = [...places].map((w) => entry.push && w === "the body" ? "the push" : w).sort();
3960
4035
  const in_ = shown2.length > 5 ? `${shown2.slice(0, 5).join(", ")} and ${shown2.length - 5} more` : shown2.join(", ");
3961
4036
  const step = entry.stepId ? ` in step ${entry.stepId}` : "";
3962
4037
  out.push({
@@ -3969,6 +4044,118 @@ function findForeignData(requests, hits, identity, dataLayerEvents = []) {
3969
4044
  return out;
3970
4045
  }
3971
4046
 
4047
+ // packages/expect/src/push-shape.ts
4048
+ var PUSH_FRAME_KINDS = ["main", "embedded", "unknown"];
4049
+ var NO_EVENT = "(no event)";
4050
+ var NO_STEP = "(no step)";
4051
+ var EVENT_CHARS = /^[A-Za-z0-9_.:-]+$/;
4052
+ var MAX_DEPTH2 = 8;
4053
+ var MAX_PATHS = 200;
4054
+ var GTAG_COMMANDS = /* @__PURE__ */ new Set(["config", "consent", "event", "get", "js", "set"]);
4055
+ var GTAG_OTHER = "gtag (other)";
4056
+ var MAX_ARGUMENTS = 16;
4057
+ function safeName(name) {
4058
+ return EVENT_CHARS.test(name) && !isValueSegment(name) && guardFieldName(name) === name ? name : OTHER_NAME;
4059
+ }
4060
+ function safeKey(key) {
4061
+ return guardFieldName(key) === key && !isValueSegment(key) ? key : OTHER_NAME;
4062
+ }
4063
+ function typeOf(value) {
4064
+ if (value === null || value === void 0) return "null";
4065
+ return Array.isArray(value) ? "array" : typeof value;
4066
+ }
4067
+ function walk(value, path, depth, out) {
4068
+ const children = typeof value !== "object" || value === null ? [] : Array.isArray(value) ? value.map((v) => ["[*]", v]) : Object.entries(value);
4069
+ if (children.length === 0 || depth >= MAX_DEPTH2) {
4070
+ if (path === "" || !out.has(path) && out.size >= MAX_PATHS) return;
4071
+ (out.get(path) ?? out.set(path, /* @__PURE__ */ new Set()).get(path)).add(typeOf(value));
4072
+ return;
4073
+ }
4074
+ for (const [key, child] of children) {
4075
+ walk(child, key === "[*]" ? `${path}[*]` : path === "" ? safeKey(key) : `${path}.${safeKey(key)}`, depth + 1, out);
4076
+ }
4077
+ }
4078
+ function startsWithString(args) {
4079
+ return typeof args[0] === "string";
4080
+ }
4081
+ function argumentsLike(args) {
4082
+ const [item] = args;
4083
+ if (args.length !== 1 || typeof item !== "object" || item === null || Array.isArray(item)) return void 0;
4084
+ const keys = Object.keys(item);
4085
+ if (keys.length < 1 || keys.length > MAX_ARGUMENTS || !keys.every((k, i) => Object.hasOwn(item, String(i)) && k === String(i))) return void 0;
4086
+ const list3 = keys.map((_, i) => item[String(i)]);
4087
+ return typeof list3[0] === "string" ? list3 : void 0;
4088
+ }
4089
+ function commandOf(e) {
4090
+ if (startsWithString(e.args)) return { list: e.args, fromObject: false };
4091
+ const list3 = argumentsLike(e.args);
4092
+ return list3 !== void 0 && startsWithString(list3) ? { list: list3, fromObject: true } : void 0;
4093
+ }
4094
+ var CONSENT_COMMANDS = /* @__PURE__ */ new Set(["default", "update"]);
4095
+ function isObjectConsent(command) {
4096
+ return command?.fromObject === true && command.list[0] === "consent" && typeof command.list[1] === "string" && CONSENT_COMMANDS.has(command.list[1]);
4097
+ }
4098
+ function commandLabel(command) {
4099
+ const [name, second] = command.list;
4100
+ if (command.fromObject && typeof second === "string") {
4101
+ if (isObjectConsent(command)) return `consent ${second}`;
4102
+ if (name === "event") return safeName(second);
4103
+ }
4104
+ return GTAG_COMMANDS.has(name) ? `gtag ${name}` : GTAG_OTHER;
4105
+ }
4106
+ function eventLabel(e, command) {
4107
+ if (e.isConsentCommand) return `consent ${String(e.args[1])}`;
4108
+ if (e.event !== null) return safeName(e.event);
4109
+ return command === void 0 ? NO_EVENT : commandLabel(command);
4110
+ }
4111
+ function labelKind(label) {
4112
+ return label.startsWith("consent ") ? "consent" : label.startsWith("gtag ") ? "gtag" : "event";
4113
+ }
4114
+ function frameKind(e) {
4115
+ return e.frame === void 0 ? "unknown" : e.frame.main ? "main" : "embedded";
4116
+ }
4117
+ function collectPaths(e, command, into) {
4118
+ if (e.event?.startsWith("gtm.")) return;
4119
+ if (command?.fromObject && command.list[0] === "event" && typeof command.list[1] === "string" && command.list[1].startsWith("gtm.")) return;
4120
+ if (e.isConsentCommand || isObjectConsent(command)) {
4121
+ const signals = (command?.fromObject ? command.list : e.args)[2];
4122
+ if (typeof signals === "object" && signals !== null) for (const [name, value] of Object.entries(signals)) walk(value, safeKey(name), 0, into);
4123
+ return;
4124
+ }
4125
+ if (command !== void 0) {
4126
+ for (const arg of command.list.slice(command.list[0] === "set" ? 1 : 2)) walk(arg, "", 0, into);
4127
+ return;
4128
+ }
4129
+ for (const arg of e.args) walk(arg, "", 0, into);
4130
+ }
4131
+ function pushShapes(records) {
4132
+ const labels = new Map((records.steps ?? []).map((s) => [s.id, s.label]));
4133
+ const steps = /* @__PURE__ */ new Map();
4134
+ for (const e of records.dataLayerEvents) {
4135
+ const step = e.stepId === null ? NO_STEP : labels.get(e.stepId) ?? NO_STEP;
4136
+ const command = commandOf(e);
4137
+ const event = eventLabel(e, command);
4138
+ const kind = command === void 0 ? "object" : "gtag";
4139
+ const frame = frameKind(e);
4140
+ const groups = steps.get(step) ?? steps.set(step, /* @__PURE__ */ new Map()).get(step);
4141
+ const key = JSON.stringify([event, kind, frame]);
4142
+ const group = groups.get(key) ?? groups.set(key, { shape: { event, kind, frame, count: 0, paths: [], ids: [] }, types: /* @__PURE__ */ new Map() }).get(key);
4143
+ group.shape.count += 1;
4144
+ group.shape.ids.push(e.id);
4145
+ collectPaths(e, command, group.types);
4146
+ }
4147
+ return {
4148
+ pushes: records.dataLayerEvents.length,
4149
+ steps: [...steps].map(([step, groups]) => ({
4150
+ step,
4151
+ events: [...groups.values()].map(({ shape, types }) => ({
4152
+ ...shape,
4153
+ paths: [...types].map(([path, set]) => ({ path, types: [...set].sort() }))
4154
+ }))
4155
+ }))
4156
+ };
4157
+ }
4158
+
3972
4159
  // packages/expect/src/event-map.ts
3973
4160
  var EVENT_NAME = /^[A-Za-z0-9_.: -]{1,200}$/;
3974
4161
  var PATH_NAME = /^[A-Za-z0-9_.()[\]*-]{1,200}$/;
@@ -4076,7 +4263,7 @@ function parseEventMap(text2, file) {
4076
4263
  return map;
4077
4264
  }
4078
4265
  function builtInEventName(event) {
4079
- return /^(consent|gtag) /.test(event) ? event : ga4EventName(event);
4266
+ return labelKind(event) === "event" ? ga4EventName(event) : event;
4080
4267
  }
4081
4268
  function renamePath(path, renames) {
4082
4269
  const bySpecificity = Object.entries(renames).sort(([x], [y]) => y.length - x.length);
@@ -4089,11 +4276,11 @@ function renamePath(path, renames) {
4089
4276
  }
4090
4277
  return path;
4091
4278
  }
4092
- function mapPushGroups(groups, rename2, paths = {}, pathKeys = (recorded, final) => [final, recorded]) {
4279
+ function mapPushGroups(groups, rename2, paths, pathKeys) {
4093
4280
  return groups.map((g) => {
4094
4281
  const event = rename2(g.event);
4095
- const key = pathKeys(g.event, event).find((k) => Object.hasOwn(paths, k));
4096
- const renames = key === void 0 ? void 0 : paths[key];
4282
+ const key = pathKeys(g.event, event).find((k) => paths !== void 0 && Object.hasOwn(paths, k));
4283
+ const renames = key === void 0 ? void 0 : paths?.[key];
4097
4284
  if (!renames) return { ...g, event };
4098
4285
  const under = Object.hasOwn(renames, ROOT) ? renames[ROOT] : void 0;
4099
4286
  if (under !== void 0) {
@@ -4117,167 +4304,76 @@ function userEventName(event, user) {
4117
4304
  const named = builtInEventName(event);
4118
4305
  return user !== void 0 && Object.hasOwn(user, event) ? user[event] : user !== void 0 && Object.hasOwn(user, named) ? user[named] : named;
4119
4306
  }
4307
+ function pathKeysFor(userMap, own, fallback) {
4308
+ const targets = new Set(Object.values(userMap?.events ?? {}));
4309
+ return (recorded, final) => [...own(recorded, final), ...fallback(recorded).filter((k) => !targets.has(k))];
4310
+ }
4120
4311
  function normalizePushGroups(groups, userMap) {
4121
4312
  const user = userMap?.events;
4122
- const rename2 = (event) => mappedEventName(event, userMap);
4123
- const targets = new Set(user === void 0 ? [] : Object.values(user));
4124
- const pathKeys = (recorded, final) => [final, userEventName(recorded, user), recorded].filter((k, i) => i < 2 || !targets.has(k));
4125
- return mapPushGroups(groups, rename2, userMap?.paths, pathKeys);
4126
- }
4127
-
4128
- // packages/expect/src/push-shape.ts
4129
- var NO_EVENT = "(no event)";
4130
- var NO_STEP = "(no step)";
4131
- var EVENT_CHARS = /^[A-Za-z0-9_.:-]+$/;
4132
- var MAX_DEPTH2 = 8;
4133
- var MAX_PATHS = 200;
4134
- var GTAG_COMMANDS = /* @__PURE__ */ new Set(["config", "consent", "event", "get", "js", "set"]);
4135
- var GTAG_OTHER = "gtag (other)";
4136
- var MAX_ARGUMENTS = 16;
4137
- function safeName(name) {
4138
- return EVENT_CHARS.test(name) && !isValueSegment(name) && guardFieldName(name) === name ? name : OTHER_NAME;
4139
- }
4140
- function safeKey(key) {
4141
- return guardFieldName(key) === key && !isValueSegment(key) ? key : OTHER_NAME;
4313
+ const pathKeys = pathKeysFor(userMap, (recorded, final) => [final, userEventName(recorded, user)], (recorded) => [recorded]);
4314
+ return mapPushGroups(groups, (event) => mappedEventName(event, userMap), userMap?.paths, pathKeys);
4142
4315
  }
4143
- function typeOf(value) {
4144
- if (value === null || value === void 0) return "null";
4145
- return Array.isArray(value) ? "array" : typeof value;
4316
+ function keepPushGroups(groups, userMap) {
4317
+ const pathKeys = pathKeysFor(userMap, (recorded) => [recorded], (recorded) => [builtInEventName(recorded)]);
4318
+ return mapPushGroups(groups, (event) => event, userMap?.paths, pathKeys);
4146
4319
  }
4147
- function walk(value, path, depth, out) {
4148
- const children = typeof value !== "object" || value === null ? [] : Array.isArray(value) ? value.map((v) => ["[*]", v]) : Object.entries(value);
4149
- if (children.length === 0 || depth >= MAX_DEPTH2) {
4150
- if (path === "" || !out.has(path) && out.size >= MAX_PATHS) return;
4151
- (out.get(path) ?? out.set(path, /* @__PURE__ */ new Set()).get(path)).add(typeOf(value));
4152
- return;
4320
+
4321
+ // packages/expect/src/diff.ts
4322
+ var NO_EPOCH = "none";
4323
+ var SERVER_UNLINKED = "server";
4324
+ function diffRuns(a, b, options = {}) {
4325
+ const result = { warnings: [], added: [], removed: [], changed: [], countMismatches: [], flags: [] };
4326
+ const versionA = a.run.recordSchemaVersion ?? 0;
4327
+ const versionB = b.run.recordSchemaVersion ?? 0;
4328
+ if (versionA !== versionB) {
4329
+ result.warnings.push(
4330
+ `The runs have different record schema versions (${versionA} and ${versionB}). The diff may show changes that are only differences in the record shape.`
4331
+ );
4153
4332
  }
4154
- for (const [key, child] of children) {
4155
- walk(child, key === "[*]" ? `${path}[*]` : path === "" ? safeKey(key) : `${path}.${safeKey(key)}`, depth + 1, out);
4333
+ const stepsA = stepLabels(a);
4334
+ const stepsB = stepLabels(b);
4335
+ const groupsA = groupHits(a, options);
4336
+ const groupsB = groupHits(b, options);
4337
+ const ids = [.../* @__PURE__ */ new Set([...groupsA.keys(), ...groupsB.keys()])].sort();
4338
+ for (const id of ids) {
4339
+ const ga = groupsA.get(id);
4340
+ const gb = groupsB.get(id);
4341
+ const key = (ga ?? gb).key;
4342
+ const hitsA = ga?.hits ?? [];
4343
+ const hitsB = gb?.hits ?? [];
4344
+ if (hitsA.length !== hitsB.length) result.countMismatches.push({ key, a: hitsA.length, b: hitsB.length });
4345
+ const paired = Math.min(hitsA.length, hitsB.length);
4346
+ for (let i = 0; i < paired; i++) {
4347
+ const ha = hitsA[i];
4348
+ const hb = hitsB[i];
4349
+ const consent = consentChanges(ha, hb);
4350
+ const idChanges = idPresenceChanges(ha.ids, hb.ids);
4351
+ if (consent.length || idChanges.length) {
4352
+ result.changed.push({ key, a: ref(ha, stepsA), b: ref(hb, stepsB), consent, ids: idChanges });
4353
+ }
4354
+ }
4355
+ for (const h of hitsA.slice(paired)) result.removed.push({ key, ...ref(h, stepsA) });
4356
+ for (const h of hitsB.slice(paired)) result.added.push({ key, ...ref(h, stepsB) });
4357
+ }
4358
+ result.flags = flagChanges(a, b);
4359
+ const pushesA = pushGroups(a);
4360
+ const pushesB = pushGroups(b);
4361
+ if (pushesA.length > 0 || pushesB.length > 0) {
4362
+ result.dataLayer = diffPushes(pushesA, pushesB, { acrossFrames: options.acrossFrames, epochOrder: epochOrder(b), eventMap: options.eventMap });
4363
+ result.warnings.push(...result.dataLayer.kindChanged.map(kindChangeWarning));
4156
4364
  }
4365
+ return result;
4157
4366
  }
4158
- function isGtagCommand(args) {
4159
- return typeof args[0] === "string";
4367
+ function kindChangeWarning(k) {
4368
+ return `push kind changed: ${k.event}${k.renamedFrom === void 0 ? "" : ` (renamed from ${k.renamedFrom})`}`;
4160
4369
  }
4161
- function argumentsLike(args) {
4162
- const [item] = args;
4163
- if (args.length !== 1 || typeof item !== "object" || item === null || Array.isArray(item)) return void 0;
4164
- const keys = Object.keys(item);
4165
- if (keys.length < 1 || keys.length > MAX_ARGUMENTS || !keys.every((k, i) => Object.hasOwn(item, String(i)) && k === String(i))) return void 0;
4166
- const list3 = keys.map((_, i) => item[String(i)]);
4167
- return typeof list3[0] === "string" ? list3 : void 0;
4370
+ function kindsMerged(a, b) {
4371
+ return [...a, ...b].some((g) => g.kind === void 0);
4168
4372
  }
4169
- function commandOf(e) {
4170
- if (isGtagCommand(e.args)) return { list: e.args, fromObject: false };
4171
- const list3 = argumentsLike(e.args);
4172
- return list3 !== void 0 && isGtagCommand(list3) ? { list: list3, fromObject: true } : void 0;
4173
- }
4174
- var CONSENT_COMMANDS = /* @__PURE__ */ new Set(["default", "update"]);
4175
- function isObjectConsent(command) {
4176
- return command?.fromObject === true && command.list[0] === "consent" && typeof command.list[1] === "string" && CONSENT_COMMANDS.has(command.list[1]);
4177
- }
4178
- function commandLabel(command) {
4179
- const [name, second] = command.list;
4180
- if (command.fromObject && typeof second === "string") {
4181
- if (isObjectConsent(command)) return `consent ${second}`;
4182
- if (name === "event") return safeName(second);
4183
- }
4184
- return GTAG_COMMANDS.has(name) ? `gtag ${name}` : GTAG_OTHER;
4185
- }
4186
- function eventLabel(e, command) {
4187
- if (e.isConsentCommand) return `consent ${String(e.args[1])}`;
4188
- if (e.event !== null) return safeName(e.event);
4189
- return command === void 0 ? NO_EVENT : commandLabel(command);
4190
- }
4191
- function frameKind(e) {
4192
- return e.frame === void 0 ? "unknown" : e.frame.main ? "main" : "embedded";
4193
- }
4194
- function collectPaths(e, command, into) {
4195
- if (e.event?.startsWith("gtm.")) return;
4196
- if (command?.fromObject && command.list[0] === "event" && typeof command.list[1] === "string" && command.list[1].startsWith("gtm.")) return;
4197
- if (e.isConsentCommand || isObjectConsent(command)) {
4198
- const signals = (command?.fromObject ? command.list : e.args)[2];
4199
- if (typeof signals === "object" && signals !== null) for (const [name, value] of Object.entries(signals)) walk(value, safeKey(name), 0, into);
4200
- return;
4201
- }
4202
- if (command !== void 0) {
4203
- for (const arg of command.list.slice(command.list[0] === "set" ? 1 : 2)) walk(arg, "", 0, into);
4204
- return;
4205
- }
4206
- for (const arg of e.args) walk(arg, "", 0, into);
4207
- }
4208
- function pushShapes(records) {
4209
- const labels = new Map((records.steps ?? []).map((s) => [s.id, s.label]));
4210
- const steps = /* @__PURE__ */ new Map();
4211
- for (const e of records.dataLayerEvents) {
4212
- const step = e.stepId === null ? NO_STEP : labels.get(e.stepId) ?? NO_STEP;
4213
- const command = commandOf(e);
4214
- const event = eventLabel(e, command);
4215
- const kind = command === void 0 ? "object" : "gtag";
4216
- const frame = frameKind(e);
4217
- const groups = steps.get(step) ?? steps.set(step, /* @__PURE__ */ new Map()).get(step);
4218
- const key = JSON.stringify([event, kind, frame]);
4219
- const group = groups.get(key) ?? groups.set(key, { shape: { event, kind, frame, count: 0, paths: [], ids: [] }, types: /* @__PURE__ */ new Map() }).get(key);
4220
- group.shape.count += 1;
4221
- group.shape.ids.push(e.id);
4222
- collectPaths(e, command, group.types);
4223
- }
4224
- return {
4225
- pushes: records.dataLayerEvents.length,
4226
- steps: [...steps].map(([step, groups]) => ({
4227
- step,
4228
- events: [...groups.values()].map(({ shape, types }) => ({
4229
- ...shape,
4230
- paths: [...types].map(([path, set]) => ({ path, types: [...set].sort() }))
4231
- }))
4232
- }))
4233
- };
4234
- }
4235
-
4236
- // packages/expect/src/diff.ts
4237
- var NO_EPOCH = "none";
4238
- var SERVER_UNLINKED = "server";
4239
- function diffRuns(a, b, options = {}) {
4240
- const result = { warnings: [], added: [], removed: [], changed: [], countMismatches: [], flags: [] };
4241
- const versionA = a.run.recordSchemaVersion ?? 0;
4242
- const versionB = b.run.recordSchemaVersion ?? 0;
4243
- if (versionA !== versionB) {
4244
- result.warnings.push(
4245
- `The runs have different record schema versions (${versionA} and ${versionB}). The diff may show changes that are only differences in the record shape.`
4246
- );
4247
- }
4248
- const stepsA = stepLabels(a);
4249
- const stepsB = stepLabels(b);
4250
- const groupsA = groupHits(a, options);
4251
- const groupsB = groupHits(b, options);
4252
- const ids = [.../* @__PURE__ */ new Set([...groupsA.keys(), ...groupsB.keys()])].sort();
4253
- for (const id of ids) {
4254
- const ga = groupsA.get(id);
4255
- const gb = groupsB.get(id);
4256
- const key = (ga ?? gb).key;
4257
- const hitsA = ga?.hits ?? [];
4258
- const hitsB = gb?.hits ?? [];
4259
- if (hitsA.length !== hitsB.length) result.countMismatches.push({ key, a: hitsA.length, b: hitsB.length });
4260
- const paired = Math.min(hitsA.length, hitsB.length);
4261
- for (let i = 0; i < paired; i++) {
4262
- const ha = hitsA[i];
4263
- const hb = hitsB[i];
4264
- const consent = consentChanges(ha, hb);
4265
- const idChanges = idPresenceChanges(ha.ids, hb.ids);
4266
- if (consent.length || idChanges.length) {
4267
- result.changed.push({ key, a: ref(ha, stepsA), b: ref(hb, stepsB), consent, ids: idChanges });
4268
- }
4269
- }
4270
- for (const h of hitsA.slice(paired)) result.removed.push({ key, ...ref(h, stepsA) });
4271
- for (const h of hitsB.slice(paired)) result.added.push({ key, ...ref(h, stepsB) });
4272
- }
4273
- result.flags = flagChanges(a, b);
4274
- const pushesA = pushGroups(a);
4275
- const pushesB = pushGroups(b);
4276
- if (pushesA.length > 0 || pushesB.length > 0) {
4277
- result.dataLayer = diffPushes(pushesA, pushesB, { acrossFrames: options.acrossFrames, epochOrder: epochOrder(b), eventMap: options.eventMap });
4278
- result.warnings.push(...result.dataLayer.kindChanged.map((k) => `push kind changed: ${k.event}`));
4279
- }
4280
- return result;
4373
+ function neighbourEpochs(order, from, to) {
4374
+ const i = order.indexOf(from);
4375
+ const j = order.indexOf(to);
4376
+ return i >= 0 && j >= 0 && Math.abs(i - j) === 1 && order.filter((l) => l === from || l === to).length === 2;
4281
4377
  }
4282
4378
  function epochOrder(run) {
4283
4379
  return [...run.consentEpochs].sort((x, y) => x.startT - y.startT).map((e) => e.label);
@@ -4329,13 +4425,18 @@ var nodeRef = (n, renamedFrom = n.renamedFrom) => ({
4329
4425
  });
4330
4426
  var epochEventId = (g) => JSON.stringify([g.epoch, g.event]);
4331
4427
  var byEventThenEpoch = (x, y) => x.event < y.event ? -1 : x.event > y.event ? 1 : x.epoch < y.epoch ? -1 : x.epoch > y.epoch ? 1 : 0;
4332
- function pairNames(a, b, userMap) {
4428
+ function pairNames(a, b, userMap, context = {}) {
4333
4429
  const inA = new Set(a.map(epochEventId));
4334
4430
  const inB = new Set(b.map(epochEventId));
4335
4431
  const unique = (groups) => [...new Map(groups.map((g) => [epochEventId(g), g])).values()];
4336
4432
  const onlyA = unique(a.filter((g) => !inB.has(epochEventId(g)))).sort(byEventThenEpoch);
4337
4433
  const onlyB = unique(b.filter((g) => !inA.has(epochEventId(g)))).sort(byEventThenEpoch);
4338
4434
  const movedNames = new Set(onlyA.map((g) => g.event).filter((n) => onlyB.some((g) => g.event === n)));
4435
+ const normalized = normalizePushGroups(a, userMap);
4436
+ const shapeOf = (groups, from, epoch, event) => JSON.stringify(
4437
+ [...pushNodes(groups.filter((_, i) => from[i].epoch === epoch && from[i].event === event), context.acrossFrames ?? false, context.mergeKinds ?? false).values()].map((n) => JSON.stringify([n.kind ?? null, n.frame, typesId(n)])).sort()
4438
+ );
4439
+ const canMove = (from, to) => neighbourEpochs(context.epochOrder ?? [], from.epoch, to.epoch) && shapeOf(normalized, a, from.epoch, from.event) === shapeOf(b, b, to.epoch, to.event);
4339
4440
  const taken = new Set(inA);
4340
4441
  const claimed = /* @__PURE__ */ new Set();
4341
4442
  const joined = /* @__PURE__ */ new Map();
@@ -4344,7 +4445,7 @@ function pairNames(a, b, userMap) {
4344
4445
  if (joined.has(epochEventId(from)) || !sameEpoch && movedNames.has(from.event)) continue;
4345
4446
  const want = mappedEventName(from.event, userMap);
4346
4447
  const to = onlyB.find(
4347
- (g) => !claimed.has(epochEventId(g)) && builtInEventName(g.event) === want && !taken.has(JSON.stringify([from.epoch, g.event])) && (sameEpoch ? g.epoch === from.epoch : !movedNames.has(g.event))
4448
+ (g) => !claimed.has(epochEventId(g)) && builtInEventName(g.event) === want && !taken.has(JSON.stringify([from.epoch, g.event])) && (sameEpoch ? g.epoch === from.epoch : !movedNames.has(g.event) && canMove(from, g))
4348
4449
  );
4349
4450
  if (to === void 0) continue;
4350
4451
  claimed.add(epochEventId(to));
@@ -4354,19 +4455,27 @@ function pairNames(a, b, userMap) {
4354
4455
  };
4355
4456
  pair(true);
4356
4457
  pair(false);
4357
- const targets = new Set(Object.values(userMap?.events ?? {}));
4358
- const kept = mapPushGroups(a, (e) => e, userMap?.paths, (r) => [r, builtInEventName(r)].filter((k, i) => i === 0 || !targets.has(k)));
4359
- return normalizePushGroups(a, userMap).map((g, i) => {
4458
+ const kept = keepPushGroups(a, userMap);
4459
+ return normalized.map((g, i) => {
4360
4460
  const recorded = a[i];
4361
4461
  const to = joined.get(epochEventId(recorded));
4362
4462
  return to === void 0 ? kept[i] : { ...g, event: to, renamedFrom: recorded.event };
4363
4463
  });
4364
4464
  }
4365
- var typesId = (n) => JSON.stringify([...n.types].sort(([x], [y]) => x < y ? -1 : x > y ? 1 : 0));
4465
+ function typesId(n) {
4466
+ return JSON.stringify([...n.types].sort(([x], [y]) => x < y ? -1 : x > y ? 1 : 0));
4467
+ }
4468
+ function withoutEventName(n, other) {
4469
+ if (n.kind !== "object" || !n.types.has("event") || other.types.has("event")) return n;
4470
+ const types = new Map(n.types);
4471
+ types.delete("event");
4472
+ return { ...n, types };
4473
+ }
4366
4474
  function diffPushes(a, b, options = {}) {
4367
4475
  const result = { eventsAdded: [], eventsRemoved: [], pathsAdded: [], pathsRemoved: [], typeChanges: [], moved: [], kindChanged: [], changed: false };
4368
- const mergeKinds = [...a, ...b].some((g) => g.kind === void 0);
4369
- const na = pushNodes(pairNames(a, b, options.eventMap), options.acrossFrames ?? false, mergeKinds);
4476
+ const mergeKinds = kindsMerged(a, b);
4477
+ const order = options.epochOrder ?? [];
4478
+ const na = pushNodes(pairNames(a, b, options.eventMap, { epochOrder: order, acrossFrames: options.acrossFrames, mergeKinds }), options.acrossFrames ?? false, mergeKinds);
4370
4479
  const nb = pushNodes(b, options.acrossFrames ?? false, mergeKinds);
4371
4480
  const gone = [];
4372
4481
  const fresh = [];
@@ -4378,7 +4487,7 @@ function diffPushes(a, b, options = {}) {
4378
4487
  }
4379
4488
  for (const [path, types] of x.types) if (!y.types.has(path)) result.pathsRemoved.push({ ...nodeRef(x), path, types });
4380
4489
  if (x.frames.slice().sort().join() !== y.frames.slice().sort().join()) {
4381
- result.moved.push({ event: y.event, kind: "frame", epoch: y.epoch, from: x.frames.slice().sort().join("+"), to: y.frames.slice().sort().join("+") });
4490
+ result.moved.push({ event: y.event, ...x.renamedFrom === void 0 ? {} : { renamedFrom: x.renamedFrom }, kind: "frame", ...y.kind === void 0 ? {} : { pushKind: y.kind }, epoch: y.epoch, from: x.frames.slice().sort().join("+"), to: y.frames.slice().sort().join("+") });
4382
4491
  }
4383
4492
  };
4384
4493
  for (const id of [.../* @__PURE__ */ new Set([...na.keys(), ...nb.keys()])].sort()) {
@@ -4394,24 +4503,20 @@ function diffPushes(a, b, options = {}) {
4394
4503
  if (!f) continue;
4395
4504
  gone.splice(gone.indexOf(g), 1);
4396
4505
  fresh.splice(fresh.indexOf(f), 1);
4397
- result.kindChanged.push({ epoch: g.epoch, event: g.event, frame: g.frame, from: g.kind, to: f.kind });
4398
- compare(g, f);
4506
+ result.kindChanged.push({ epoch: g.epoch, event: g.event, frame: g.frame, from: g.kind, to: f.kind, ...g.renamedFrom === void 0 ? {} : { renamedFrom: g.renamedFrom } });
4507
+ compare(withoutEventName(g, f), withoutEventName(f, g));
4399
4508
  }
4400
- const order = options.epochOrder ?? [];
4401
4509
  const taken = /* @__PURE__ */ new Set();
4402
4510
  for (const g of gone) {
4403
- const i = order.indexOf(g.epoch);
4404
- const match = fresh.find((f) => {
4405
- if (taken.has(f) || f.event !== g.event || f.kind !== g.kind || f.frame !== g.frame || typesId(f) !== typesId(g)) return false;
4406
- const j = order.indexOf(f.epoch);
4407
- return i >= 0 && j >= 0 && Math.abs(i - j) === 1 && order.filter((l) => l === g.epoch || l === f.epoch).length === 2;
4408
- });
4511
+ const match = fresh.find(
4512
+ (f) => !taken.has(f) && f.event === g.event && f.kind === g.kind && f.frame === g.frame && typesId(f) === typesId(g) && neighbourEpochs(order, g.epoch, f.epoch)
4513
+ );
4409
4514
  if (!match) {
4410
4515
  result.eventsRemoved.push({ ...nodeRef({ ...g, renamedFrom: void 0 }), event: g.renamedFrom ?? g.event });
4411
4516
  continue;
4412
4517
  }
4413
4518
  taken.add(match);
4414
- result.moved.push({ event: g.event, kind: "epoch", frame: g.frame, from: g.epoch, to: match.epoch });
4519
+ result.moved.push({ event: g.event, ...g.renamedFrom === void 0 ? {} : { renamedFrom: g.renamedFrom }, kind: "epoch", ...g.kind === void 0 ? {} : { pushKind: g.kind }, frame: g.frame, from: g.epoch, to: match.epoch });
4415
4520
  }
4416
4521
  for (const f of fresh) if (!taken.has(f)) result.eventsAdded.push(nodeRef(f));
4417
4522
  result.changed = result.eventsAdded.length + result.eventsRemoved.length + result.pathsAdded.length + result.pathsRemoved.length + result.typeChanges.length + result.kindChanged.length > 0;
@@ -4476,10 +4581,7 @@ function findMove(epochs, order) {
4476
4581
  const d1 = total(v1.b) - total(v1.a);
4477
4582
  if (d1 + total(v2.b) - total(v2.a) !== 0) return void 0;
4478
4583
  const [from, to] = d1 < 0 ? [[e1, v1], [e2, v2]] : [[e2, v2], [e1, v1]];
4479
- const i = order.indexOf(from[0]);
4480
- const j = order.indexOf(to[0]);
4481
- if (i < 0 || j < 0 || Math.abs(i - j) !== 1) return void 0;
4482
- if (order.filter((l) => l === from[0] || l === to[0]).length !== 2) return void 0;
4584
+ if (!neighbourEpochs(order, from[0], to[0])) return void 0;
4483
4585
  if (!contains(tupleCounts(from[1].a), tupleCounts(from[1].b))) return void 0;
4484
4586
  if (!contains(tupleCounts(to[1].b), tupleCounts(to[1].a))) return void 0;
4485
4587
  if (!sameCounts(surplusByIds(from[1].a, from[1].b), surplusByIds(to[1].b, to[1].a))) return void 0;
@@ -5155,9 +5257,6 @@ function dataLayerInitScript(names = []) {
5155
5257
  });
5156
5258
  })();`;
5157
5259
  }
5158
- function isDataLayerName(name) {
5159
- return typeof name === "string" && DATALAYER_NAME_PATTERN.test(name) && !NEVER_TRAPPED_NAMES.includes(name);
5160
- }
5161
5260
  function isConsentCommand(args) {
5162
5261
  return args[0] === "consent" && (args[1] === "default" || args[1] === "update");
5163
5262
  }
@@ -5523,8 +5622,8 @@ function handoffOverlayScript(nonce) {
5523
5622
  setText(button, 'Done');
5524
5623
  appendChild(pill, label, button);
5525
5624
  appendToRoot(root, pill);
5526
- apply(pill, { display: 'flex', 'align-items': 'flex-start', gap: '10px', padding: '6px 6px 6px 12px', background: '#1d2530', color: '#fff', font: '13px/1.3 system-ui, sans-serif', 'border-radius': '999px', 'box-sizing': 'border-box', 'max-width': '100%', 'box-shadow': '0 2px 10px rgba(0,0,0,.35)', cursor: 'grab', 'user-select': 'none', 'touch-action': 'none' });
5527
- apply(label, { display: '-webkit-box', '-webkit-box-orient': 'vertical', '-webkit-line-clamp': '4', overflow: 'hidden', 'overflow-wrap': 'anywhere', 'max-width': '300px', 'min-width': '0' });
5625
+ apply(pill, { display: 'flex', 'align-items': 'flex-start', gap: '10px', padding: '6px 6px 6px 12px', background: '#1d2530', color: '#fff', font: '13px/1.3 system-ui, sans-serif', 'border-radius': '14px', 'box-sizing': 'border-box', 'max-width': '100%', 'box-shadow': '0 2px 10px rgba(0,0,0,.35)', cursor: 'grab', 'user-select': 'none', 'touch-action': 'none' });
5626
+ apply(label, { display: '-webkit-box', '-webkit-box-orient': 'vertical', '-webkit-line-clamp': '4', overflow: 'hidden', 'overflow-wrap': 'anywhere', 'min-width': '0' });
5528
5627
  apply(button, { all: 'unset', 'box-sizing': 'border-box', background: '#2f7d4f', color: '#fff', padding: '4px 14px', 'align-self': 'stretch', display: 'flex', 'align-items': 'center', 'border-radius': '999px', 'font-weight': '600', cursor: 'pointer', 'flex-shrink': '0' });
5529
5628
  addListener(button, 'click', (event) => {
5530
5629
  if (!trusted(event)) return;
@@ -6297,6 +6396,15 @@ function gtmFailureMessage(override, applied, fetchError, hint = "") {
6297
6396
 
6298
6397
  // packages/recorder/src/datalayer-names.ts
6299
6398
  var GOOGLE_TAG_ID = /^(GTM|G|GT|AW|DC)-[A-Z0-9]+$/;
6399
+ var LOADER_PATH = /\/(gtm\.js|gtag\/js)$/;
6400
+ function isGoogleHostLoaderUrl(url) {
6401
+ try {
6402
+ const parsed = new URL(url);
6403
+ return parsed.hostname === "www.googletagmanager.com" && LOADER_PATH.test(parsed.pathname);
6404
+ } catch {
6405
+ return false;
6406
+ }
6407
+ }
6300
6408
  function loaderName(url, googleOnly) {
6301
6409
  let parsed;
6302
6410
  try {
@@ -6304,7 +6412,7 @@ function loaderName(url, googleOnly) {
6304
6412
  } catch {
6305
6413
  return void 0;
6306
6414
  }
6307
- if (!/\/(gtm\.js|gtag\/js)$/.test(parsed.pathname)) return void 0;
6415
+ if (!LOADER_PATH.test(parsed.pathname)) return void 0;
6308
6416
  if (googleOnly && !GOOGLE_HOST.test(parsed.hostname) && !GOOGLE_TAG_ID.test(parsed.searchParams.get("id") ?? "")) return void 0;
6309
6417
  const name = parsed.searchParams.get("l");
6310
6418
  return name === null || name === "" ? void 0 : name;
@@ -6336,6 +6444,17 @@ function buildDataLayerNotHookedFlag(input) {
6336
6444
  detail: plural2 ? `Google loaders name the data layers ${shown2}, which are not hooked, so pushes to them are not recorded. ${advice}` : `A Google loader names the data layer ${shown2}, which is not hooked, so pushes to it are not recorded. ${advice.replace("them", "it")}`
6337
6445
  };
6338
6446
  }
6447
+ function buildDataLayerReassignedFlags(input) {
6448
+ const frames = new Set(input.reassigns.filter((r) => input.loaders.some((l) => l.doc === r.doc && l.t <= r.t)).map((r) => r.n));
6449
+ return [...frames].sort((a, b) => a - b).map((n) => ({
6450
+ type: "flag",
6451
+ id: newId("flag"),
6452
+ runId: input.runId,
6453
+ kind: "dataLayerReassigned",
6454
+ recordIds: [],
6455
+ detail: `Frame ${n} replaced window.dataLayer with a new array after a Google loader request. Pushes to the new array are still recorded.`
6456
+ }));
6457
+ }
6339
6458
 
6340
6459
  // packages/recorder/src/tag-report.ts
6341
6460
  var TAG_REPORT_BINDING = "tagreeveTagReport";
@@ -7478,11 +7597,11 @@ ${lines.join("\n")}` : "";
7478
7597
  throw new ServerContainerError("notReady", `${PROBE_HOST} could not be resolved here, so the egress check cannot run. The container was not started.`);
7479
7598
  }
7480
7599
  if (!net.isIPv4(probeAddress)) throw new ServerContainerError("notReady", `${PROBE_HOST} did not resolve to an IPv4 address. The container was not started.`);
7481
- const probe = await docker(["run", "--rm", "--name", names.probe, "--network", names.network, ...labels, "--entrypoint", NODE_BIN, options.image, "-e", PROBE_SCRIPT, probeAddress], {}, 6e4);
7600
+ const probe2 = await docker(["run", "--rm", "--name", names.probe, "--network", names.network, ...labels, "--entrypoint", NODE_BIN, options.image, "-e", PROBE_SCRIPT, probeAddress], {}, 6e4);
7482
7601
  checkAborted();
7483
7602
  let outcome;
7484
7603
  try {
7485
- outcome = JSON.parse(probe.stdout.trim().split("\n").pop() ?? "");
7604
+ outcome = JSON.parse(probe2.stdout.trim().split("\n").pop() ?? "");
7486
7605
  } catch {
7487
7606
  outcome = void 0;
7488
7607
  }
@@ -7793,7 +7912,7 @@ function linkServerHits({ hits, requests, serverHosts, identity, inFlight }) {
7793
7912
  });
7794
7913
  const hitRequestIds = new Set(hits.map((h) => h.requestId));
7795
7914
  const hasConcurrentRequest = (only, from, to, callClientIds) => requests.some((r) => {
7796
- if (r.captured === "serverContainer" || r.id === only.hit.requestId || !isServerContainerRequest(r, serverHosts)) return false;
7915
+ if (r.captured === "serverContainer" || r.id === only.hit.requestId || r.initiator === "unload" || !isServerContainerRequest(r, serverHosts)) return false;
7797
7916
  const sentAt = inFlight?.get(r.id)?.sentAt ?? r.t;
7798
7917
  if (sentAt < from || sentAt > to) return false;
7799
7918
  if (!hitRequestIds.has(r.id)) return true;
@@ -8769,19 +8888,8 @@ var Recorder = class _Recorder {
8769
8888
  return buildTallyFlags(this.runId, tallies, this.payloadCounts);
8770
8889
  }
8771
8890
  dataLayerReassignedFlags(requests) {
8772
- const loaders = requests.filter((r) => isGoogleLoaderUrl(r.url));
8773
- if (loaders.length === 0) return [];
8774
- const frames = new Set(
8775
- this.dataLayerReassigns.filter((r) => loaders.some((l) => this.requestFrameIds.get(l.id) === r.doc && l.t <= r.t)).map((r) => r.n)
8776
- );
8777
- return [...frames].sort((a, b) => a - b).map((n) => ({
8778
- type: "flag",
8779
- id: newId("flag"),
8780
- runId: this.runId,
8781
- kind: "dataLayerReassigned",
8782
- recordIds: [],
8783
- detail: `Frame ${n} replaced window.dataLayer with a new array after a Google loader request. Pushes to the new array are still recorded.`
8784
- }));
8891
+ const loaders = requests.filter((r) => isGoogleHostLoaderUrl(r.url)).map((r) => ({ t: r.t, doc: this.requestFrameIds.get(r.id) }));
8892
+ return buildDataLayerReassignedFlags({ runId: this.runId, reassigns: this.dataLayerReassigns, loaders });
8785
8893
  }
8786
8894
  noteContainerExit() {
8787
8895
  if (this.session?.containerExited() && !this.containerFailure) {
@@ -8908,14 +9016,6 @@ function abortCode(error) {
8908
9016
  return "failed";
8909
9017
  }
8910
9018
  var BODY_HEADERS = /* @__PURE__ */ new Set(["content-type", "content-length", "content-encoding", "content-language", "content-location", "origin"]);
8911
- function isGoogleLoaderUrl(url) {
8912
- try {
8913
- const u = new URL(url);
8914
- return u.hostname === "www.googletagmanager.com" && (u.pathname === "/gtm.js" || u.pathname === "/gtag/js");
8915
- } catch {
8916
- return false;
8917
- }
8918
- }
8919
9019
  function withoutMethodChangeHeaders(headers) {
8920
9020
  return Object.fromEntries(Object.entries(headers).filter(([name]) => !BODY_HEADERS.has(name.toLowerCase())));
8921
9021
  }
@@ -9070,7 +9170,8 @@ var BLOCK_REASONS = ["required, not ticked", "invalid", "aria-invalid"];
9070
9170
  var INPUT_TYPES = ["checkbox", "color", "date", "datetime-local", "email", "file", "month", "number", "password", "radio", "range", "search", "tel", "text", "time", "url", "week"];
9071
9171
  var WIDGET_ROLES = ["checkbox", "combobox", "listbox", "radio", "radiogroup", "searchbox", "slider", "spinbutton", "switch", "textbox"];
9072
9172
  var KINDS = [...INPUT_TYPES, ...WIDGET_ROLES, "select", "textarea"];
9073
- function readBlockingControls({ max, form }) {
9173
+ function readBlockingControls({ max, form: remembered }) {
9174
+ const form = remembered?.isConnected && remembered.ownerDocument === document ? remembered : null;
9074
9175
  const found = [];
9075
9176
  const nameOf2 = (el) => el.getAttribute("aria-label")?.trim() || el.getAttribute("name") || el.id;
9076
9177
  for (const el of document.querySelectorAll('input, select, textarea, [aria-invalid="true"]')) {
@@ -9099,9 +9200,11 @@ function withDeadline(work, ms) {
9099
9200
  }
9100
9201
  async function blockingControls(context, form = null) {
9101
9202
  const listed = [];
9203
+ const live = form ? await withDeadline(form.evaluate((f) => f.isConnected), DIAGNOSTIC_DEADLINE_MS).catch(() => false) : false;
9204
+ const scope = live ? form : null;
9102
9205
  for (const page2 of context.pages()) {
9103
9206
  try {
9104
- const controls = await withDeadline(page2.evaluate(readBlockingControls, { max: MAX_LISTED4, form }), DIAGNOSTIC_DEADLINE_MS);
9207
+ const controls = await withDeadline(page2.evaluate(readBlockingControls, { max: MAX_LISTED4, form: scope }), DIAGNOSTIC_DEADLINE_MS);
9105
9208
  for (const c of controls) {
9106
9209
  if (!BLOCK_REASONS.includes(c.reason)) continue;
9107
9210
  const kind = KINDS.includes(c.kind) ? c.kind : "control";
@@ -9164,6 +9267,19 @@ function pathOf2(url) {
9164
9267
  return "";
9165
9268
  }
9166
9269
  }
9270
+ var FILL_TRY_MS = 500;
9271
+ var UNREADABLE_FRAME = "the card frame could not be read";
9272
+ var DEADLINE_GRACE_MS = 500;
9273
+ var Unresponsive = class extends Error {
9274
+ };
9275
+ function withinDeadline(work, deadline) {
9276
+ let timer;
9277
+ const late = new Promise((_, reject) => {
9278
+ timer = setTimeout(() => reject(new Unresponsive()), Math.max(1, deadline + DEADLINE_GRACE_MS - Date.now()));
9279
+ });
9280
+ work.catch(() => void 0);
9281
+ return Promise.race([work, late]).finally(() => clearTimeout(timer));
9282
+ }
9167
9283
  async function cardFrameServed(page2, field, cardHost, deadline) {
9168
9284
  let reason = "not found";
9169
9285
  for (; ; ) {
@@ -9171,39 +9287,44 @@ async function cardFrameServed(page2, field, cardHost, deadline) {
9171
9287
  let hidden = false;
9172
9288
  let elsewhere = false;
9173
9289
  let otherPath;
9174
- for (const element of await page2.locator(field.frame).elementHandles()) {
9175
- const frame = await element.contentFrame();
9290
+ for (const element of await withinDeadline(page2.locator(field.frame).elementHandles(), deadline)) {
9291
+ const frame = await withinDeadline(element.contentFrame(), deadline);
9176
9292
  if (!frame) continue;
9177
9293
  if (hostOf3(frame.url()) !== cardHost) {
9178
9294
  elsewhere = true;
9179
9295
  } else if (!field.path.test(pathOf2(frame.url()))) {
9180
9296
  otherPath = pathOf2(frame.url());
9181
- } else if (await element.isVisible()) {
9297
+ } else if (await withinDeadline(element.isVisible(), deadline)) {
9182
9298
  return { element, frame };
9183
9299
  } else {
9184
9300
  hidden = true;
9185
9301
  }
9186
9302
  }
9187
9303
  reason = hidden ? "not visible" : otherPath !== void 0 ? `served from another path: ${otherPath}` : elsewhere ? "served from another host" : "not found";
9188
- } catch {
9304
+ } catch (error) {
9305
+ if (error instanceof Unresponsive) throw error;
9189
9306
  return reason;
9190
9307
  }
9191
9308
  if (Date.now() >= deadline) return reason;
9192
9309
  await new Promise((resolve5) => setTimeout(resolve5, 100));
9193
9310
  }
9194
9311
  }
9195
- async function markerInCardContainer(frames, marker, timeout) {
9312
+ async function markerInCardContainer(frames, marker, deadline) {
9196
9313
  try {
9197
- const container = await frames[0].evaluateHandle((first, all) => {
9198
- let node = first.parentElement;
9199
- while (node && !all.every((f) => node.contains(f))) node = node.parentElement;
9200
- return node;
9201
- }, frames);
9314
+ const container = await withinDeadline(
9315
+ frames[0].evaluateHandle((first, all) => {
9316
+ let node = first.parentElement;
9317
+ while (node && !all.every((f) => node.contains(f))) node = node.parentElement;
9318
+ return node;
9319
+ }, frames),
9320
+ deadline
9321
+ );
9202
9322
  const element = container.asElement();
9203
9323
  if (!element) return false;
9204
- await element.waitForSelector(marker, { state: "visible", timeout });
9324
+ await element.waitForSelector(marker, { state: "visible", timeout: Math.max(1, deadline + DEADLINE_GRACE_MS - Date.now()) });
9205
9325
  return true;
9206
- } catch {
9326
+ } catch (error) {
9327
+ if (error instanceof Unresponsive) throw error;
9207
9328
  return false;
9208
9329
  }
9209
9330
  }
@@ -9227,19 +9348,27 @@ async function runPayment(page2, recorder, value, identity, testPayment, record,
9227
9348
  }
9228
9349
  const declared = testPayment.declaredProviders?.includes(provider.id) === true;
9229
9350
  const wait = Math.min(timeout, MARKER_TIMEOUT_MS);
9351
+ const stepDeadline = Date.now() + timeout;
9230
9352
  const deadline = Date.now() + wait;
9231
9353
  const found = [];
9232
9354
  for (const field of runtime.fields) {
9233
- const result = await cardFrameServed(page2, field, runtime.cardHost, deadline);
9355
+ const result = await cardFrameServed(page2, field, runtime.cardHost, deadline).catch((error) => {
9356
+ throw error instanceof Unresponsive ? new Error(`card field ${field.kind} could not be filled: ${UNREADABLE_FRAME}`) : error;
9357
+ });
9234
9358
  if (typeof result === "string") throw new Error(`card frame not found (${field.kind}): ${result}`);
9235
9359
  found.push(result);
9236
9360
  }
9237
- if (!declared && !await markerInCardContainer(found.map((f) => f.element), runtime.marker, wait)) throw new Error("test mode not detected");
9361
+ if (!declared) {
9362
+ const marked = await markerInCardContainer(found.map((f) => f.element), runtime.marker, deadline).catch((error) => {
9363
+ throw error instanceof Unresponsive ? new Error(`test mode could not be checked: ${UNREADABLE_FRAME}`) : error;
9364
+ });
9365
+ if (!marked) throw new Error("test mode not detected");
9366
+ }
9238
9367
  recorder.holdRedaction();
9239
9368
  const typed = typedValues(provider, card, identity);
9240
9369
  for (const [index, field] of runtime.fields.entries()) {
9241
9370
  try {
9242
- await fillVerified(found[index].element, field, runtime.cardHost, valueOf2(field.kind, provider, card, identity), timeout, typed);
9371
+ await fillVerified(found[index].element, field, runtime.cardHost, valueOf2(field.kind, provider, card, identity), stepDeadline, typed);
9243
9372
  } catch (error) {
9244
9373
  throw new Error(`card field ${field.kind} could not be filled: ${reasonOf(error, typed)}`);
9245
9374
  }
@@ -9254,21 +9383,7 @@ async function frameStillServed(element, cardHost, field) {
9254
9383
  }
9255
9384
  return frame;
9256
9385
  }
9257
- var FILL_TRY_MS = 500;
9258
- var UNREADABLE_FRAME = "the card frame could not be read";
9259
- var DEADLINE_GRACE_MS = 500;
9260
- var Unresponsive = class extends Error {
9261
- };
9262
- function withinDeadline(work, deadline) {
9263
- let timer;
9264
- const late = new Promise((_, reject) => {
9265
- timer = setTimeout(() => reject(new Unresponsive()), Math.max(1, deadline - Date.now()) + DEADLINE_GRACE_MS);
9266
- });
9267
- work.catch(() => void 0);
9268
- return Promise.race([work, late]).finally(() => clearTimeout(timer));
9269
- }
9270
- async function fillVerified(element, field, cardHost, value, timeout, typed) {
9271
- const deadline = Date.now() + timeout;
9386
+ async function fillVerified(element, field, cardHost, value, deadline, typed) {
9272
9387
  const tryMs = () => Math.max(1, Math.min(FILL_TRY_MS, deadline - Date.now()));
9273
9388
  const readable = (work) => withinDeadline(work, deadline).catch((error) => {
9274
9389
  throw error instanceof Unresponsive ? new OwnReason(UNREADABLE_FRAME) : error;
@@ -9593,7 +9708,7 @@ async function rememberClickedForm(recorder, target) {
9593
9708
  try {
9594
9709
  const work = target.evaluateHandle(
9595
9710
  (el) => {
9596
- const control = el;
9711
+ const control = el.closest("button, input[type=submit], input[type=image]");
9597
9712
  const submits = control instanceof HTMLButtonElement && control.type === "submit" || control instanceof HTMLInputElement && (control.type === "submit" || control.type === "image");
9598
9713
  return submits ? control.form : null;
9599
9714
  },
@@ -9795,13 +9910,106 @@ async function recordScenario(options) {
9795
9910
  return result;
9796
9911
  }
9797
9912
 
9913
+ // packages/recorder/src/gtm-templates/tpl.ts
9914
+ import { readFileSync as readFileSync4 } from "node:fs";
9915
+ var PACKAGE_TEMPLATE_FILE = "tagreeve-tag-reporter.tpl";
9916
+ function readWebTagReporterTemplate() {
9917
+ const places = [
9918
+ new URL(`./templates/${PACKAGE_TEMPLATE_FILE}`, import.meta.url),
9919
+ new URL("./web-tag-reporter.tpl", import.meta.url)
9920
+ ];
9921
+ for (const place of places) {
9922
+ try {
9923
+ return readFileSync4(place, "utf8");
9924
+ } catch (error) {
9925
+ if (error.code !== "ENOENT") throw error;
9926
+ }
9927
+ }
9928
+ throw new Error("The web tag reporter template is missing from this install.");
9929
+ }
9930
+
9798
9931
  // packages/cli/src/args.ts
9799
9932
  import { parseArgs } from "node:util";
9800
9933
 
9801
9934
  // packages/cli/src/out-dir.ts
9802
- import { readdir } from "node:fs/promises";
9935
+ import { readdir as readdir2 } from "node:fs/promises";
9803
9936
  import { join as join6 } from "node:path";
9804
- function resolveOutDir({ out, now, label, base: base2 = "tagreeve/runs" }) {
9937
+
9938
+ // packages/cli/src/defaults.ts
9939
+ import { readdir, stat } from "node:fs/promises";
9940
+ var DEFAULT_CONFIG = "tagreeve/config.yml";
9941
+ var DEFAULT_RUNS = "tagreeve/runs";
9942
+ var DEFAULT_SCENARIOS = "tagreeve/scenarios";
9943
+ var DEFAULT_TRACKER_LIST = "tagreeve/trackers.json";
9944
+ var DEFAULT_AUTOCONSENT_DIR = "tagreeve/autoconsent";
9945
+ var DEFAULT_STORES = "tagreeve/stores.json";
9946
+ var DEFAULT_BASELINES = "tagreeve/baselines";
9947
+ var SETTING_TEXT = {
9948
+ config: "project config",
9949
+ scenarios: "scenario folder",
9950
+ trackerList: "tracker list",
9951
+ autoconsentRules: "autoconsent rules",
9952
+ stores: "stores",
9953
+ baseline: "baseline"
9954
+ };
9955
+ function isAbsent(error) {
9956
+ const code = error.code;
9957
+ return code === "ENOENT" || code === "ENOTDIR";
9958
+ }
9959
+ function unreadable(path, error) {
9960
+ const code = error.code;
9961
+ return new Error(`Cannot read ${path}${typeof code === "string" ? ` (${code})` : ""}. Fix its permissions or remove it.`);
9962
+ }
9963
+ async function isKind(path, kind) {
9964
+ try {
9965
+ const info = await stat(path);
9966
+ return kind === "file" ? info.isFile() : info.isDirectory();
9967
+ } catch (error) {
9968
+ if (isAbsent(error)) return false;
9969
+ throw unreadable(path, error);
9970
+ }
9971
+ }
9972
+ async function defaultScenarioDir(used) {
9973
+ if (!await isKind(DEFAULT_SCENARIOS, "directory")) return void 0;
9974
+ used.push({ setting: "scenarios", path: DEFAULT_SCENARIOS });
9975
+ return DEFAULT_SCENARIOS;
9976
+ }
9977
+ async function resolveTrackerList(flag2, used) {
9978
+ if (flag2 !== void 0) return flag2;
9979
+ if (!await isKind(DEFAULT_TRACKER_LIST, "file")) return void 0;
9980
+ used.push({ setting: "trackerList", path: DEFAULT_TRACKER_LIST });
9981
+ return DEFAULT_TRACKER_LIST;
9982
+ }
9983
+ async function resolveAutoconsentRules(flags2, used) {
9984
+ if (flags2?.length) return flags2;
9985
+ let names;
9986
+ try {
9987
+ names = (await readdir(DEFAULT_AUTOCONSENT_DIR)).filter((name) => name.endsWith(".json")).sort();
9988
+ } catch (error) {
9989
+ if (isAbsent(error)) return [];
9990
+ throw unreadable(DEFAULT_AUTOCONSENT_DIR, error);
9991
+ }
9992
+ const paths = [];
9993
+ for (const name of names) {
9994
+ const path = `${DEFAULT_AUTOCONSENT_DIR}/${name}`;
9995
+ if (await isKind(path, "file")) paths.push(path);
9996
+ }
9997
+ for (const path of paths) used.push({ setting: "autoconsentRules", path });
9998
+ return paths;
9999
+ }
10000
+ async function defaultStores(used) {
10001
+ if (!await isKind(DEFAULT_STORES, "file")) return void 0;
10002
+ used.push({ setting: "stores", path: DEFAULT_STORES });
10003
+ return DEFAULT_STORES;
10004
+ }
10005
+ function formatDefaultsLine(defaults) {
10006
+ if (!defaults?.length) return void 0;
10007
+ const ordered = [...defaults.filter((d) => d.setting === "config"), ...defaults.filter((d) => d.setting !== "config")];
10008
+ return `Defaults: ${ordered.map((d) => `${d.path} (${SETTING_TEXT[d.setting]})`).join(", ")}`;
10009
+ }
10010
+
10011
+ // packages/cli/src/out-dir.ts
10012
+ function resolveOutDir({ out, now, label, base: base2 = DEFAULT_RUNS }) {
9805
10013
  if (out !== void 0) return out;
9806
10014
  const pad = (n) => String(n).padStart(2, "0");
9807
10015
  const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
@@ -9815,12 +10023,18 @@ function oldRunsNoticeText(folder) {
9815
10023
  async function oldRunsNotice(cwd, folder) {
9816
10024
  let names;
9817
10025
  try {
9818
- names = await readdir(join6(cwd, "runs"));
10026
+ names = await readdir2(join6(cwd, "runs"));
9819
10027
  } catch {
9820
10028
  return void 0;
9821
10029
  }
9822
10030
  return names.some((n) => /^run_.*\.jsonl$/.test(n) || n.startsWith("suite_")) ? oldRunsNoticeText(folder) : void 0;
9823
10031
  }
10032
+ async function resolveRunFolder(input, cwd = process.cwd()) {
10033
+ const folder = resolveOutDir(input);
10034
+ const isDefault = input.out === void 0 && input.base === void 0;
10035
+ const notice = isDefault ? await oldRunsNotice(cwd, folder) : void 0;
10036
+ return { folder, isDefault, ...notice && { notice } };
10037
+ }
9824
10038
 
9825
10039
  // packages/cli/src/args.ts
9826
10040
  var UsageError = class extends Error {
@@ -10275,7 +10489,7 @@ function describePushDiff(d) {
10275
10489
  ...d.pathsAdded.map((p) => `new path ${p.path} (${p.types.join("|")}) in ${named(p)} ${at(p)}`),
10276
10490
  ...d.typeChanges.map((p) => `type change ${p.path}: ${p.a.join("|")} -> ${p.b.join("|")} in ${named(p)} ${at(p)}`),
10277
10491
  ...d.moved.map(
10278
- (m) => m.kind === "frame" ? `moved event ${m.event} from frame ${m.from} to ${m.to} [epoch ${m.epoch}]` : `moved event ${m.event} from epoch ${m.from} to ${m.to} [frame ${m.frame}]`
10492
+ (m) => m.kind === "frame" ? `moved event ${named(m)} from frame ${m.from} to ${m.to} [epoch ${m.epoch}]` : `moved event ${named(m)} from epoch ${m.from} to ${m.to} [frame ${m.frame}]`
10279
10493
  )
10280
10494
  ];
10281
10495
  }
@@ -10345,75 +10559,6 @@ async function diffCommand(args, io) {
10345
10559
  return 0;
10346
10560
  }
10347
10561
 
10348
- // packages/cli/src/defaults.ts
10349
- import { readdir as readdir2, stat } from "node:fs/promises";
10350
- var DEFAULT_SCENARIOS = "tagreeve/scenarios";
10351
- var DEFAULT_TRACKER_LIST = "tagreeve/trackers.json";
10352
- var DEFAULT_AUTOCONSENT_DIR = "tagreeve/autoconsent";
10353
- var DEFAULT_STORES = "tagreeve/stores.json";
10354
- var DEFAULT_BASELINES = "tagreeve/baselines";
10355
- var SETTING_TEXT = {
10356
- scenarios: "scenario folder",
10357
- trackerList: "tracker list",
10358
- autoconsentRules: "autoconsent rules",
10359
- stores: "stores",
10360
- baseline: "baseline"
10361
- };
10362
- function isAbsent(error) {
10363
- const code = error.code;
10364
- return code === "ENOENT" || code === "ENOTDIR";
10365
- }
10366
- function unreadable(path, error) {
10367
- const code = error.code;
10368
- return new Error(`Cannot read ${path}${typeof code === "string" ? ` (${code})` : ""}. Fix its permissions or remove it.`);
10369
- }
10370
- async function isKind(path, kind) {
10371
- try {
10372
- const info = await stat(path);
10373
- return kind === "file" ? info.isFile() : info.isDirectory();
10374
- } catch (error) {
10375
- if (isAbsent(error)) return false;
10376
- throw unreadable(path, error);
10377
- }
10378
- }
10379
- async function defaultScenarioDir(used) {
10380
- if (!await isKind(DEFAULT_SCENARIOS, "directory")) return void 0;
10381
- used.push({ setting: "scenarios", path: DEFAULT_SCENARIOS });
10382
- return DEFAULT_SCENARIOS;
10383
- }
10384
- async function resolveTrackerList(flag2, used) {
10385
- if (flag2 !== void 0) return flag2;
10386
- if (!await isKind(DEFAULT_TRACKER_LIST, "file")) return void 0;
10387
- used.push({ setting: "trackerList", path: DEFAULT_TRACKER_LIST });
10388
- return DEFAULT_TRACKER_LIST;
10389
- }
10390
- async function resolveAutoconsentRules(flags2, used) {
10391
- if (flags2?.length) return flags2;
10392
- let names;
10393
- try {
10394
- names = (await readdir2(DEFAULT_AUTOCONSENT_DIR)).filter((name) => name.endsWith(".json")).sort();
10395
- } catch (error) {
10396
- if (isAbsent(error)) return [];
10397
- throw unreadable(DEFAULT_AUTOCONSENT_DIR, error);
10398
- }
10399
- const paths = [];
10400
- for (const name of names) {
10401
- const path = `${DEFAULT_AUTOCONSENT_DIR}/${name}`;
10402
- if (await isKind(path, "file")) paths.push(path);
10403
- }
10404
- for (const path of paths) used.push({ setting: "autoconsentRules", path });
10405
- return paths;
10406
- }
10407
- async function defaultStores(used) {
10408
- if (!await isKind(DEFAULT_STORES, "file")) return void 0;
10409
- used.push({ setting: "stores", path: DEFAULT_STORES });
10410
- return DEFAULT_STORES;
10411
- }
10412
- function formatDefaultsLine(defaults) {
10413
- if (!defaults?.length) return void 0;
10414
- return `Defaults: ${defaults.map((d) => `${d.path} (${SETTING_TEXT[d.setting]})`).join(", ")}`;
10415
- }
10416
-
10417
10562
  // packages/cli/src/stores.ts
10418
10563
  import { constants } from "node:fs";
10419
10564
  import { access, readFile as readFile3, stat as stat2 } from "node:fs/promises";
@@ -10532,9 +10677,8 @@ function validKey(k) {
10532
10677
  (t) => isRecord2(t) && isRecord2(t.consent) && Object.values(t.consent).every((v) => typeof v === "string") && isStringArray(t.ids) && Number.isInteger(t.count) && t.count >= 1
10533
10678
  );
10534
10679
  }
10535
- var FRAME_KINDS = /* @__PURE__ */ new Set(["main", "embedded", "unknown"]);
10536
10680
  function validPushGroup(g) {
10537
- return isRecord2(g) && typeof g.epoch === "string" && typeof g.event === "string" && (g.kind === void 0 || g.kind === "gtag" || g.kind === "object") && typeof g.frame === "string" && FRAME_KINDS.has(g.frame) && Array.isArray(g.paths) && g.paths.every((p) => isRecord2(p) && typeof p.path === "string" && isStringArray(p.types));
10681
+ return isRecord2(g) && typeof g.epoch === "string" && typeof g.event === "string" && (g.kind === void 0 || g.kind === "gtag" || g.kind === "object") && typeof g.frame === "string" && PUSH_FRAME_KINDS.includes(g.frame) && Array.isArray(g.paths) && g.paths.every((p) => isRecord2(p) && typeof p.path === "string" && isStringArray(p.types));
10538
10682
  }
10539
10683
  function uniformKinds(groups) {
10540
10684
  return groups.every((g) => g.kind === void 0 === (groups[0].kind === void 0));
@@ -10559,13 +10703,14 @@ function parseBaseline(text2, label) {
10559
10703
  }
10560
10704
  return json;
10561
10705
  }
10706
+ var errnoCode = (error) => error.code ?? "unknown error";
10562
10707
  async function readBaseline(path) {
10563
10708
  let text2;
10564
10709
  try {
10565
10710
  text2 = await readFile4(path, "utf8");
10566
10711
  } catch (error) {
10567
- const code = error.code;
10568
- throw new BaselineError(`Cannot read ${path}: ${code ?? "unknown error"}`, code === "ENOENT" ? "missing" : "unreadable");
10712
+ const code = errnoCode(error);
10713
+ throw new BaselineError(`Cannot read ${path}: ${code}`, code === "ENOENT" ? "missing" : "unreadable");
10569
10714
  }
10570
10715
  return parseBaseline(text2, path);
10571
10716
  }
@@ -10600,11 +10745,10 @@ function defaultBaselineName(run) {
10600
10745
  }
10601
10746
  const unsafe = (part) => /[/\\\0]/.test(part) || part.includes("..") || part.startsWith(".");
10602
10747
  const name = scenarioName(run.scenario);
10603
- const bad2 = !name || unsafe(name) ? "scenario" : unsafe(run.store ?? "") || run.store !== void 0 && !STORE_NAME.test(run.store) ? "store" : unsafe(run.variant ?? "") || run.variant !== void 0 && !VARIANT_NAME2.test(run.variant) ? "variant" : void 0;
10748
+ const bad2 = !name || unsafe(name) ? "scenario" : unsafe(run.store ?? "") || run.store !== void 0 && !STORE_NAME.test(run.store) ? "store" : unsafe(run.variant ?? "") || run.variant !== void 0 && !VARIANT_NAME.test(run.variant) ? "variant" : void 0;
10604
10749
  if (bad2) throw new BaselineError(`The ${bad2} in this record cannot name a baseline file. Give the baseline path.`, "usage");
10605
10750
  return baselineFileName(run.scenario, run.store, run.variant);
10606
10751
  }
10607
- var VARIANT_NAME2 = /^[a-z0-9][a-z0-9_-]*$/;
10608
10752
  function insideBaselines(path) {
10609
10753
  const rel = relative(resolve2(DEFAULT_BASELINES), resolve2(path));
10610
10754
  return rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel);
@@ -10622,10 +10766,11 @@ function compareBaseline(baseline, records) {
10622
10766
  if (baseline.dataLayer === void 0) {
10623
10767
  warnings.push("dataLayer pushes not compared: the baseline has no push shapes (saved before 0.6.0-rc.2). Save it again to compare them.");
10624
10768
  } else {
10625
- const pushes = diffPushes(baseline.dataLayer, pushGroups(records), { epochOrder: epochOrder2 });
10769
+ const current = pushGroups(records);
10770
+ const pushes = diffPushes(baseline.dataLayer, current, { epochOrder: epochOrder2 });
10626
10771
  warnings.push(...describePushDiff(pushes).map((line) => `dataLayer ${line}`));
10627
- warnings.push(...pushes.kindChanged.map((k) => `dataLayer push kind changed: ${k.event}`));
10628
- if (baseline.dataLayer.some((g) => g.kind === void 0)) {
10772
+ warnings.push(...pushes.kindChanged.map((k) => `dataLayer ${kindChangeWarning(k)}`));
10773
+ if (kindsMerged(baseline.dataLayer, current)) {
10629
10774
  warnings.push("dataLayer push kinds not compared: the baseline was saved by 0.6.0-rc.2. Save it again to compare them.");
10630
10775
  }
10631
10776
  }
@@ -10638,7 +10783,6 @@ function compareBaseline(baseline, records) {
10638
10783
  changes: describeDiff(diff)
10639
10784
  };
10640
10785
  }
10641
- var errnoCode = (error) => error.code ?? "unknown error";
10642
10786
  async function baselineCommand(args, io) {
10643
10787
  let records;
10644
10788
  try {
@@ -10681,8 +10825,8 @@ async function baselineCommand(args, io) {
10681
10825
  }
10682
10826
 
10683
10827
  // packages/cli/src/init.ts
10684
- import { appendFile, mkdir as mkdir3, readFile as readFile5, stat as stat4, writeFile as writeFile3 } from "node:fs/promises";
10685
- import { join as join9 } from "node:path";
10828
+ import { appendFile, lstat, mkdir as mkdir3, readFile as readFile5, stat as stat4, writeFile as writeFile3 } from "node:fs/promises";
10829
+ import { dirname as dirname5, join as join9 } from "node:path";
10686
10830
 
10687
10831
  // packages/cli/src/git-ignore.ts
10688
10832
  import { execFile as execFile2 } from "node:child_process";
@@ -10729,15 +10873,24 @@ async function warnIfNotIgnored(folder, stderr) {
10729
10873
  }
10730
10874
 
10731
10875
  // packages/cli/src/init.ts
10732
- var IGNORE_LINE = "/tagreeve/runs/";
10733
- var FOLDERS = ["tagreeve/scenarios", "tagreeve/baselines"];
10734
- var CONFIG = "tagreeve/config.yml";
10876
+ var IGNORE_LINE = `/${DEFAULT_RUNS}/`;
10877
+ var FOLDERS = [DEFAULT_SCENARIOS, DEFAULT_BASELINES];
10735
10878
  var STARTER_CONFIG = `configSchemaVersion: 1
10736
10879
  # Allowed keys: site, out, options. See docs/cli.md, "Project config".
10737
10880
  # site:
10738
10881
  # out:
10739
10882
  # options:
10740
10883
  `;
10884
+ var NotAFolder = class extends Error {
10885
+ constructor() {
10886
+ super("not a folder");
10887
+ }
10888
+ };
10889
+ var NotAFile = class extends Error {
10890
+ constructor() {
10891
+ super("not a file");
10892
+ }
10893
+ };
10741
10894
  async function ensureIgnoreLine(cwd) {
10742
10895
  const file = join9(cwd, ".gitignore");
10743
10896
  let current;
@@ -10747,7 +10900,7 @@ async function ensureIgnoreLine(cwd) {
10747
10900
  current = void 0;
10748
10901
  }
10749
10902
  if (current?.split(/\r?\n/).some((line) => line.trim() === IGNORE_LINE)) return { path: ".gitignore", action: "skipped", text: `Skipped .gitignore: it already has ${IGNORE_LINE}` };
10750
- if (await gitIgnoreStatus(join9(cwd, "tagreeve/runs"), { probe: "folder" }) === "ignored") return { path: ".gitignore", action: "skipped", text: "Skipped .gitignore: git already ignores tagreeve/runs/" };
10903
+ if (await gitIgnoreStatus(join9(cwd, DEFAULT_RUNS), { probe: "folder" }) === "ignored") return { path: ".gitignore", action: "skipped", text: `Skipped .gitignore: git already ignores ${DEFAULT_RUNS}/` };
10751
10904
  const prefix = current === void 0 || current === "" || current.endsWith("\n") ? "" : "\n";
10752
10905
  await appendFile(file, `${prefix}${IGNORE_LINE}
10753
10906
  `);
@@ -10755,24 +10908,42 @@ async function ensureIgnoreLine(cwd) {
10755
10908
  }
10756
10909
  async function ensureFolder(cwd, folder) {
10757
10910
  const found = await stat4(join9(cwd, folder)).catch(() => void 0);
10758
- if (found && !found.isDirectory()) throw Object.assign(new Error("not a folder"), { code: "NOTFOLDER" });
10911
+ if (found && !found.isDirectory()) throw new NotAFolder();
10759
10912
  if (found) return { path: `${folder}/`, action: "skipped", text: `Skipped ${folder}/: it exists` };
10760
10913
  await mkdir3(join9(cwd, folder), { recursive: true });
10761
10914
  return { path: `${folder}/`, action: "created", text: `Created ${folder}/` };
10762
10915
  }
10763
10916
  async function ensureConfig(cwd) {
10764
- const found = await stat4(join9(cwd, CONFIG)).catch(() => void 0);
10765
- if (found && !found.isFile()) throw Object.assign(new Error("not a file"), { code: "NOTFILE" });
10766
- if (found) return { path: CONFIG, action: "skipped", text: `Skipped ${CONFIG}: it exists` };
10767
- await mkdir3(join9(cwd, "tagreeve"), { recursive: true });
10768
- await writeFile3(join9(cwd, CONFIG), STARTER_CONFIG, { flag: "wx" });
10769
- return { path: CONFIG, action: "created", text: `Created ${CONFIG}` };
10917
+ const found = await stat4(join9(cwd, DEFAULT_CONFIG)).catch(() => void 0);
10918
+ if (found && !found.isFile()) throw new NotAFile();
10919
+ if (found) return { path: DEFAULT_CONFIG, action: "skipped", text: `Skipped ${DEFAULT_CONFIG}: it exists` };
10920
+ await mkdir3(dirname5(join9(cwd, DEFAULT_CONFIG)), { recursive: true });
10921
+ await writeFile3(join9(cwd, DEFAULT_CONFIG), STARTER_CONFIG, { flag: "wx" });
10922
+ return { path: DEFAULT_CONFIG, action: "created", text: `Created ${DEFAULT_CONFIG}` };
10923
+ }
10924
+ async function probe(path) {
10925
+ try {
10926
+ return await stat4(path);
10927
+ } catch {
10928
+ return await lstat(path).then(() => true, () => false) ? "unresolvable" : "absent";
10929
+ }
10930
+ }
10931
+ async function checkTargets(cwd) {
10932
+ for (const folder of FOLDERS) {
10933
+ const found = await probe(join9(cwd, folder));
10934
+ if (found === "unresolvable" || found !== "absent" && !found.isDirectory()) return [`${folder}/`, new NotAFolder()];
10935
+ }
10936
+ const config = await probe(join9(cwd, DEFAULT_CONFIG));
10937
+ if (config === "unresolvable" || config !== "absent" && !config.isFile()) return [DEFAULT_CONFIG, new NotAFile()];
10938
+ const ignore = await probe(join9(cwd, ".gitignore"));
10939
+ if (ignore === "unresolvable" || ignore !== "absent" && !ignore.isFile()) return [".gitignore", Object.assign(new Error("in the way"), { code: "EISDIR" })];
10940
+ return void 0;
10770
10941
  }
10771
10942
  function failureText(path, error) {
10772
10943
  const code = error?.code;
10773
- if (code === "NOTFOLDER") return `${path.replace(/\/$/, "")} is not a folder
10944
+ if (error instanceof NotAFolder) return `${path.replace(/\/$/, "")} is not a folder
10774
10945
  `;
10775
- if (code === "NOTFILE") return `${path} is not a file
10946
+ if (error instanceof NotAFile) return `${path} is not a file
10776
10947
  `;
10777
10948
  const reason = code === "EACCES" || code === "EPERM" ? "permission denied" : code === "EEXIST" ? "it exists" : code === "ENOTDIR" || code === "EISDIR" ? "a file or folder is in the way" : "the write failed";
10778
10949
  return `Could not write ${path}: ${reason}
@@ -10781,10 +10952,17 @@ function failureText(path, error) {
10781
10952
  async function initCommand(io, json = false, cwd = process.cwd()) {
10782
10953
  const steps = [
10783
10954
  ...FOLDERS.map((folder) => [`${folder}/`, () => ensureFolder(cwd, folder)]),
10784
- [CONFIG, () => ensureConfig(cwd)],
10955
+ [DEFAULT_CONFIG, () => ensureConfig(cwd)],
10785
10956
  [".gitignore", () => ensureIgnoreLine(cwd)]
10786
10957
  ];
10787
10958
  const items = [];
10959
+ const blocked = await checkTargets(cwd);
10960
+ if (blocked) {
10961
+ if (json) io.stdout(`${JSON.stringify({ items })}
10962
+ `);
10963
+ io.stderr(failureText(blocked[0], blocked[1]));
10964
+ return 2;
10965
+ }
10788
10966
  for (const [path, step] of steps) {
10789
10967
  try {
10790
10968
  const item = await step();
@@ -10804,22 +10982,6 @@ async function initCommand(io, json = false, cwd = process.cwd()) {
10804
10982
  }
10805
10983
 
10806
10984
  // packages/cli/src/template.ts
10807
- import { readFileSync as readFileSync4 } from "node:fs";
10808
- var WEB_TEMPLATE_FILE_NAME = "tagreeve-tag-reporter.tpl";
10809
- var WEB_TEMPLATE_PATHS = [
10810
- new URL(`./templates/${WEB_TEMPLATE_FILE_NAME}`, import.meta.url),
10811
- new URL("../../recorder/src/gtm-templates/web-tag-reporter.tpl", import.meta.url)
10812
- ];
10813
- function readWebTemplate() {
10814
- for (const path of WEB_TEMPLATE_PATHS) {
10815
- try {
10816
- return readFileSync4(path, "utf8");
10817
- } catch {
10818
- continue;
10819
- }
10820
- }
10821
- throw new Error("The web tag reporter template is missing from this install.");
10822
- }
10823
10985
  var WEB_STEPS = [
10824
10986
  'In a GTM workspace, import the text in "template" as a custom tag template.',
10825
10987
  'Add one tag of that type with the trigger in "setup.trigger" (a custom event trigger on the event name ".*" with regex matching on) and the consent setting in "setup.consent".',
@@ -10833,8 +10995,8 @@ function webTemplateJson() {
10833
10995
  return {
10834
10996
  templateVersion: 1,
10835
10997
  name: "web",
10836
- fileName: WEB_TEMPLATE_FILE_NAME,
10837
- template: readWebTemplate(),
10998
+ fileName: PACKAGE_TEMPLATE_FILE,
10999
+ template: readWebTagReporterTemplate(),
10838
11000
  setup: {
10839
11001
  trigger: { type: "customEvent", eventName: ".*", regex: true },
10840
11002
  consent: "noAdditionalConsentRequired",
@@ -10846,16 +11008,16 @@ function webTemplateJson() {
10846
11008
  }
10847
11009
  function templateCommand(io, json) {
10848
11010
  io.stdout(json ? `${JSON.stringify(webTemplateJson(), null, 2)}
10849
- ` : readWebTemplate());
11011
+ ` : readWebTagReporterTemplate());
10850
11012
  return 0;
10851
11013
  }
10852
11014
 
10853
11015
  // packages/cli/src/install-browser.ts
10854
11016
  import { spawn as spawn2 } from "node:child_process";
10855
11017
  import { createRequire as createRequire2 } from "node:module";
10856
- import { dirname as dirname5, join as join10 } from "node:path";
11018
+ import { dirname as dirname6, join as join10 } from "node:path";
10857
11019
  function installBrowser() {
10858
- const cli = join10(dirname5(createRequire2(import.meta.url).resolve("playwright/package.json")), "cli.js");
11020
+ const cli = join10(dirname6(createRequire2(import.meta.url).resolve("playwright/package.json")), "cli.js");
10859
11021
  return new Promise((resolve5, reject) => {
10860
11022
  const child = spawn2(process.execPath, [cli, "install", "chromium"], { stdio: "inherit" });
10861
11023
  child.on("error", reject);
@@ -10865,7 +11027,7 @@ function installBrowser() {
10865
11027
 
10866
11028
  // packages/cli/src/report/index.ts
10867
11029
  import { mkdir as mkdir5, stat as stat6, writeFile as writeFile6 } from "node:fs/promises";
10868
- import { dirname as dirname6, join as join15, resolve as resolve4 } from "node:path";
11030
+ import { dirname as dirname7, join as join15, resolve as resolve4 } from "node:path";
10869
11031
 
10870
11032
  // packages/cli/src/report/model.ts
10871
11033
  var NOTE_TEXT = {
@@ -11407,44 +11569,8 @@ import { basename as basename3, join as join14 } from "node:path";
11407
11569
  import { mkdir as mkdir4, readdir as readdir3, readFile as readFile9, writeFile as writeFile5 } from "node:fs/promises";
11408
11570
  import { basename as basename2, extname, join as join13 } from "node:path";
11409
11571
 
11410
- // packages/cli/src/project-config.ts
11411
- import { readFile as readFile6 } from "node:fs/promises";
11412
- var DEFAULT_CONFIG = "tagreeve/config.yml";
11413
- var ProjectConfigLoadError = class extends Error {
11414
- };
11415
- async function loadProjectConfig(flag2) {
11416
- const path = flag2 ?? DEFAULT_CONFIG;
11417
- let text2;
11418
- try {
11419
- text2 = await readFile6(path, "utf8");
11420
- } catch (error) {
11421
- const code = error instanceof Error ? error.code : void 0;
11422
- if (flag2 === void 0 && code === "ENOENT") return void 0;
11423
- throw new ProjectConfigLoadError(`Cannot read ${path}: ${code ?? "unknown error"}`);
11424
- }
11425
- try {
11426
- const config = parseProjectConfig(text2, path);
11427
- return { path, config, ...flag2 === void 0 && { defaultUsed: { setting: "config", path: DEFAULT_CONFIG } } };
11428
- } catch (error) {
11429
- if (!(error instanceof ProjectConfigError)) throw error;
11430
- throw new ProjectConfigLoadError(`${path} is not a valid project config:
11431
- ${error.issues.map((i) => ` ${i}`).join("\n")}`);
11432
- }
11433
- }
11434
- function formatDefaults(defaults) {
11435
- if (!defaults?.length) return void 0;
11436
- const config = defaults.filter((d) => d.setting === "config");
11437
- const rest = formatDefaultsLine(defaults.filter((d) => d.setting !== "config"))?.slice("Defaults: ".length);
11438
- const parts = [...config.map((d) => `${d.path} (project config)`), ...rest ? [rest] : []];
11439
- return `Defaults: ${parts.join(", ")}`;
11440
- }
11441
- function siteMissingMessage(config) {
11442
- return config ? `--site is required. Give --site or set site in ${config.path}.` : "--site is required";
11443
- }
11444
- var ALLOW_TEST_PAYMENT_NEEDS_SITE = "--allow-test-payment needs --site on the command line. A site from the project config never supplies the host a test payment runs on.";
11445
-
11446
11572
  // packages/cli/src/test-payment-hosts.ts
11447
- import { readFile as readFile7, stat as stat5 } from "node:fs/promises";
11573
+ import { readFile as readFile6, stat as stat5 } from "node:fs/promises";
11448
11574
  import { homedir } from "node:os";
11449
11575
  import { isAbsolute as isAbsolute3, join as join11 } from "node:path";
11450
11576
  var FILE_NAME = "test-payment-hosts.json";
@@ -11488,7 +11614,7 @@ async function readTestPaymentHosts(path, loopbackHosted = loopbackIsHostedForTe
11488
11614
  }
11489
11615
  let json;
11490
11616
  try {
11491
- json = JSON.parse(await readFile7(path, "utf8"));
11617
+ json = JSON.parse(await readFile6(path, "utf8"));
11492
11618
  } catch {
11493
11619
  throw new Error(`${path} is not valid JSON.`);
11494
11620
  }
@@ -11527,6 +11653,34 @@ async function checkTestPaymentGates(parsed, site, allow, env = process.env) {
11527
11653
  import { appendFile as appendFile2, readFile as readFile8, rename, writeFile as writeFile4 } from "node:fs/promises";
11528
11654
  import { basename, join as join12 } from "node:path";
11529
11655
 
11656
+ // packages/cli/src/project-config.ts
11657
+ import { readFile as readFile7 } from "node:fs/promises";
11658
+ var ProjectConfigLoadError = class extends Error {
11659
+ };
11660
+ async function loadProjectConfig(flag2) {
11661
+ const path = flag2 ?? DEFAULT_CONFIG;
11662
+ let text2;
11663
+ try {
11664
+ text2 = await readFile7(path, "utf8");
11665
+ } catch (error) {
11666
+ const code = error instanceof Error ? error.code : void 0;
11667
+ if (flag2 === void 0 && code === "ENOENT") return void 0;
11668
+ throw new ProjectConfigLoadError(`Cannot read ${path}: ${code ?? "unknown error"}`);
11669
+ }
11670
+ try {
11671
+ const config = parseProjectConfig(text2, path);
11672
+ return { path, config, ...flag2 === void 0 && { defaultUsed: { setting: "config", path: DEFAULT_CONFIG } } };
11673
+ } catch (error) {
11674
+ if (!(error instanceof ProjectConfigError)) throw error;
11675
+ throw new ProjectConfigLoadError(`${path} is not a valid project config:
11676
+ ${error.issues.map((i) => ` ${i}`).join("\n")}`);
11677
+ }
11678
+ }
11679
+ function siteMissingMessage(config) {
11680
+ return config ? `--site is required. Give --site or set site in ${config.path}.` : "--site is required";
11681
+ }
11682
+ var ALLOW_TEST_PAYMENT_NEEDS_SITE = "--allow-test-payment needs --site on the command line. A site from the project config never supplies the host a test payment runs on.";
11683
+
11530
11684
  // packages/cli/src/summary.ts
11531
11685
  var EVIDENCE_CAP = 5;
11532
11686
  var PATH_EXAMPLES = 3;
@@ -11584,8 +11738,7 @@ function buildSummary(records, results, path) {
11584
11738
  const testPayment = testPaymentOf(records);
11585
11739
  const serverContainer = serverContainerOf(records);
11586
11740
  const dataLayer = pushShapes({ steps: records.steps, dataLayerEvents: records.dataLayerEvents ?? [] });
11587
- const override = records.run.gtmOverride;
11588
- const tags = summarizeTags(records.tagReports ?? [], override ? { container: override.container, tags: override.expectedTags } : void 0);
11741
+ const tags = summarizeTags(records.tagReports ?? [], expectedTagsOf(records.run));
11589
11742
  return {
11590
11743
  runId: records.run.id,
11591
11744
  ...records.run.label !== void 0 && { label: records.run.label },
@@ -11709,20 +11862,25 @@ function serverContainerLines(summary) {
11709
11862
  return [`Server container: ${head}${error}; ${calls}; ${c.forwarded} request${c.forwarded === 1 ? "" : "s"} forwarded to Google`, SERVER_CONTAINER_LIMITS];
11710
11863
  }
11711
11864
  var DATALAYER_EVENTS_SHOWN = 3;
11712
- function dataLayerLabelRank(label) {
11713
- if (label.startsWith("consent ")) return 1;
11714
- if (label.startsWith("gtag ")) return 2;
11715
- return label.startsWith("gtm.") ? 3 : 0;
11865
+ function dataLayerLabelRank({ event, kind }) {
11866
+ const label = kind === "gtag" ? labelKind(event) : "event";
11867
+ if (label === "consent") return 1;
11868
+ if (label === "gtag") return 2;
11869
+ return event.startsWith("gtm.") ? 3 : 0;
11716
11870
  }
11717
11871
  function dataLayerLine({ pushes, steps }) {
11718
- const events = [...new Set(steps.flatMap((s) => s.events.map((e) => e.event)))].filter((e) => e !== NO_EVENT).sort((a, b) => dataLayerLabelRank(a) - dataLayerLabelRank(b) || (a < b ? -1 : a > b ? 1 : 0));
11872
+ const ranks = /* @__PURE__ */ new Map();
11873
+ for (const shape of steps.flatMap((s) => s.events)) {
11874
+ if (shape.event !== NO_EVENT) ranks.set(shape.event, Math.min(ranks.get(shape.event) ?? Infinity, dataLayerLabelRank(shape)));
11875
+ }
11876
+ const events = [...ranks.keys()].sort((a, b) => ranks.get(a) - ranks.get(b) || (a < b ? -1 : a > b ? 1 : 0));
11719
11877
  const shown2 = events.slice(0, DATALAYER_EVENTS_SHOWN).join(", ");
11720
11878
  const list3 = events.length > 0 ? ` (${shown2}${events.length > DATALAYER_EVENTS_SHOWN ? ", \u2026" : ""})` : "";
11721
11879
  return `dataLayer: ${pushes} push${pushes === 1 ? "" : "es"}, ${events.length} event${events.length === 1 ? "" : "s"}${list3}; shapes in --json`;
11722
11880
  }
11723
11881
  var TAGS_SHOWN = 5;
11724
11882
  function tagList(items) {
11725
- return items.length > TAGS_SHOWN ? `${items.slice(0, TAGS_SHOWN).join(", ")} and ${items.length - TAGS_SHOWN} more` : items.join(", ");
11883
+ return listWithMore(items, TAGS_SHOWN);
11726
11884
  }
11727
11885
  function tagsLine(container, entry) {
11728
11886
  if (!("fired" in entry)) return `Tags: no reports from ${container}. Install the reporter: ${entry.hint}`;
@@ -11738,7 +11896,7 @@ function tagsLine(container, entry) {
11738
11896
  function formatSummary(summary) {
11739
11897
  const lines = [];
11740
11898
  if (summary.label !== void 0) lines.push(`Label: ${summary.label}`);
11741
- const defaultsLine = formatDefaults(summary.defaults);
11899
+ const defaultsLine = formatDefaultsLine(summary.defaults);
11742
11900
  if (defaultsLine) lines.push(defaultsLine);
11743
11901
  if (summary.testPayment) {
11744
11902
  const { provider, host, testMode } = summary.testPayment;
@@ -12126,11 +12284,8 @@ ${error.issues.map((i) => ` ${i}`).join("\n")}
12126
12284
  }
12127
12285
  warnTestGtmOrigin(io);
12128
12286
  warnTestLoopbackHosted(io);
12129
- const out = resolveOutDir({ out: args.out, now: /* @__PURE__ */ new Date(), label: args.label, base: loaded?.config.out });
12130
- if (args.out === void 0 && loaded?.config.out === void 0) {
12131
- const notice = await oldRunsNotice(process.cwd(), out);
12132
- if (notice) io.stderr(notice);
12133
- }
12287
+ const { folder: out, notice } = await resolveRunFolder({ out: args.out, now: /* @__PURE__ */ new Date(), label: args.label, base: loaded?.config.out });
12288
+ if (notice) io.stderr(notice);
12134
12289
  await warnIfNotIgnored(out, io.stderr);
12135
12290
  const outcome = await executeRun(
12136
12291
  {
@@ -12228,7 +12383,7 @@ function formatSuiteTable(manifest, dir) {
12228
12383
  const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
12229
12384
  const line = (cols) => cols.map((c, i) => i === cols.length - 1 ? c : c.padEnd(widths[i] + 3)).join("").trimEnd();
12230
12385
  const out = [line(header), ...rows.map(line)];
12231
- const defaultsLine = formatDefaults(manifest.defaults);
12386
+ const defaultsLine = formatDefaultsLine(manifest.defaults);
12232
12387
  if (defaultsLine) out.push("", defaultsLine);
12233
12388
  const records = manifest.cells.filter((c) => c.record);
12234
12389
  if (records.length) out.push("", "Records", ...records.map((c) => ` ${cellName(c)}: ${join13(dir, c.record)}`));
@@ -12356,17 +12511,6 @@ async function loadStores(path, io) {
12356
12511
  }
12357
12512
  }
12358
12513
  async function suiteCommand(args, io, deps = { run: executeRun }) {
12359
- try {
12360
- return await runSuite(args, io, deps);
12361
- } catch (error) {
12362
- if (!(error instanceof UsageError)) throw error;
12363
- io.stderr(`${error.message}
12364
- ${usageHint(error.command)}
12365
- `);
12366
- return 2;
12367
- }
12368
- }
12369
- async function runSuite(args, io, deps) {
12370
12514
  if (args.allowTestPayment !== void 0 && args.site === void 0 && args.stores === void 0) {
12371
12515
  throw new UsageError("--allow-test-payment needs --site or --stores on the command line. A default file never supplies the host a test payment runs on.", "suite");
12372
12516
  }
@@ -12499,11 +12643,8 @@ ${hints.join(" ")}
12499
12643
  }
12500
12644
  }
12501
12645
  const id = `suite_${ulid()}`;
12502
- const outFolder = resolveOutDir({ out: args.out, now: /* @__PURE__ */ new Date(), label: args.label, base: loaded?.config.out });
12503
- if (args.out === void 0 && loaded?.config.out === void 0) {
12504
- const notice = await oldRunsNotice(process.cwd(), outFolder);
12505
- if (notice) io.stderr(notice);
12506
- }
12646
+ const { folder: outFolder, notice } = await resolveRunFolder({ out: args.out, now: /* @__PURE__ */ new Date(), label: args.label, base: loaded?.config.out });
12647
+ if (notice) io.stderr(notice);
12507
12648
  await warnIfNotIgnored(outFolder, io.stderr);
12508
12649
  const dir = join13(outFolder, id);
12509
12650
  await mkdir4(dir, { recursive: true });
@@ -12836,7 +12977,7 @@ async function refuseOverwrite(html, inputs) {
12836
12977
  for (const input of inputs) if (await isSameFile(input, html)) throw new Error(`--html must not be ${input}`);
12837
12978
  }
12838
12979
  async function write(args, html, io) {
12839
- await mkdir5(dirname6(args.html), { recursive: true });
12980
+ await mkdir5(dirname7(args.html), { recursive: true });
12840
12981
  await writeFile6(args.html, html);
12841
12982
  io.stdout(`Wrote ${args.html}
12842
12983
  `);