@heyplaybook/hydrogen 0.3.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
2
- import { createContext, Component, useContext, useMemo, useCallback, useState, useEffect, useSyncExternalStore, useRef } from 'react';
2
+ import { memo, createContext, Component, useContext, useMemo, useCallback, useState, useEffect, useSyncExternalStore, useRef } from 'react';
3
3
 
4
4
  // src/growthbook.ts
5
5
  function hashFnv32a(str2) {
@@ -142,6 +142,10 @@ var SESSION_VISITOR_COOKIE = "_pb_session_vid";
142
142
  var LEGACY_VISITOR_COOKIE = "pb_vid";
143
143
  var NEW_SESSION_COOKIE = "pb_new";
144
144
  var VISITOR_REFRESHED_COOKIE = "_pb_vs";
145
+ var SERVER_VISITOR_MARKER_COOKIE = "_pb_vsrc";
146
+ function serverVisitorMarker(visitorId) {
147
+ return `s.${visitorId.slice(0, 8)}`;
148
+ }
145
149
  var PREVIEW_COOKIE = "pb_preview";
146
150
  var PREVIEW_PARAM = "pb_preview";
147
151
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -207,6 +211,7 @@ var consentAPIResolved = false;
207
211
  var resolvePromise = null;
208
212
  var listenerRegistered = false;
209
213
  var callbacks = /* @__PURE__ */ new Set();
214
+ var eventDecision = null;
210
215
  function declareConsentRequired() {
211
216
  consentRequiredOverride = true;
212
217
  }
@@ -297,13 +302,54 @@ function isAnalyticsConsentGranted() {
297
302
  const state = getConsentState();
298
303
  return state === "granted" || state === "absent";
299
304
  }
305
+ function consentDataLoading() {
306
+ try {
307
+ const status = shopify()?.customerPrivacy?.consentStatus;
308
+ return typeof status === "string" && status !== "loaded";
309
+ } catch {
310
+ return false;
311
+ }
312
+ }
313
+ var fromDecision = (granted) => granted ? "granted" : "denied";
300
314
  function getConsentState() {
301
- if (!consentAPIResolved && consentSystemLikelyPresent()) return "pending";
315
+ if (!consentAPIResolved && consentSystemLikelyPresent()) {
316
+ return eventDecision === null ? "pending" : fromDecision(eventDecision);
317
+ }
318
+ if (consentDataLoading()) {
319
+ return eventDecision === null ? "pending" : fromDecision(eventDecision);
320
+ }
302
321
  const result = readAnalyticsConsent();
303
322
  if (result === true) return "granted";
304
323
  if (result === false) return "denied";
324
+ if (eventDecision !== null) return fromDecision(eventDecision);
305
325
  return "absent";
306
326
  }
327
+ var CONSENT_LOADED_EVENTS = [
328
+ "consentTrackingApiLoaded",
329
+ "shopifyCustomerPrivacyApiLoaded"
330
+ ];
331
+ function onConsentLoaded(cb) {
332
+ if (typeof document === "undefined" || typeof window === "undefined") {
333
+ return () => {
334
+ };
335
+ }
336
+ const handler = () => {
337
+ try {
338
+ cb();
339
+ } catch {
340
+ }
341
+ };
342
+ for (const name of CONSENT_LOADED_EVENTS) {
343
+ document.addEventListener(name, handler);
344
+ window.addEventListener(name, handler);
345
+ }
346
+ return () => {
347
+ for (const name of CONSENT_LOADED_EVENTS) {
348
+ document.removeEventListener(name, handler);
349
+ window.removeEventListener(name, handler);
350
+ }
351
+ };
352
+ }
307
353
  function onConsentChange(cb) {
308
354
  callbacks.add(cb);
309
355
  if (!listenerRegistered && typeof document !== "undefined") {
@@ -311,6 +357,9 @@ function onConsentChange(cb) {
311
357
  document.addEventListener("visitorConsentCollected", (event) => {
312
358
  consentAPIResolved = true;
313
359
  const detail = event.detail;
360
+ if (detail && typeof detail.analyticsAllowed === "boolean") {
361
+ eventDecision = detail.analyticsAllowed;
362
+ }
314
363
  const granted = detail && typeof detail.analyticsAllowed === "boolean" ? detail.analyticsAllowed : isAnalyticsConsentGranted();
315
364
  for (const fn of callbacks) {
316
365
  try {
@@ -413,7 +462,8 @@ var STALE_MS = 3e5;
413
462
  var RENDER_BUDGET_MS = 300;
414
463
  var FAILURE_BACKOFF_MS = 3e4;
415
464
  var FETCH_TIMEOUT_MS = 5e3;
416
- var memory = /* @__PURE__ */ new Map();
465
+ var droppedWarned = /* @__PURE__ */ new Set();
466
+ var DROPPED_WARNED_MAX = 64;
417
467
  function rulesUrl(platformUrl, shopId) {
418
468
  const url = new URL("/api/storefront/tests/rules", platformUrl);
419
469
  url.searchParams.set("shop", shopId);
@@ -455,10 +505,13 @@ function sanitizeRuleset(value) {
455
505
  if (!isObj(value) || !Array.isArray(value.tests)) return null;
456
506
  if (typeof value.version !== "string") return null;
457
507
  const tests = value.tests.filter(isValidRule);
458
- if (tests.length !== value.tests.length) {
508
+ if (tests.length !== value.tests.length && !droppedWarned.has(value.version)) {
509
+ if (droppedWarned.size >= DROPPED_WARNED_MAX) droppedWarned.clear();
510
+ droppedWarned.add(value.version);
459
511
  console.warn(
460
512
  "[playbook] dropped invalid rules",
461
- value.tests.length - tests.length
513
+ value.tests.length - tests.length,
514
+ value.version
462
515
  );
463
516
  }
464
517
  return { ...value, tests };
@@ -466,80 +519,111 @@ function sanitizeRuleset(value) {
466
519
  function inBackoff(entry, now) {
467
520
  return entry.failedAt > 0 && now - entry.failedAt < FAILURE_BACKOFF_MS;
468
521
  }
469
- function refresh(key, url, entry, fetchImpl) {
470
- if (entry.inflight) return entry.inflight;
471
- const controller = new AbortController();
472
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
473
- entry.inflight = fetchImpl(url, {
474
- headers: { accept: "application/json" },
475
- signal: controller.signal
476
- }).then(async (res) => {
477
- if (!res.ok) throw new Error(`ruleset ${res.status}`);
478
- const json = sanitizeRuleset(await res.json());
479
- if (!json) throw new Error("ruleset malformed");
480
- entry.ruleset = json;
481
- entry.fetchedAt = Date.now();
482
- entry.failedAt = 0;
483
- return json;
484
- }).catch((error) => {
485
- entry.failedAt = Date.now();
486
- console.warn("[playbook] ruleset fetch failed", String(error));
487
- return entry.ruleset;
488
- }).finally(() => {
489
- clearTimeout(timer);
490
- entry.inflight = null;
491
- });
492
- memory.set(key, entry);
493
- return entry.inflight;
494
- }
495
522
  var COLD_RENDER_BUDGET_MS = 1500;
496
523
  var BUDGET_MISSED = /* @__PURE__ */ Symbol("budget-missed");
524
+ function createCachedJsonFetcher({
525
+ label,
526
+ sanitize
527
+ }) {
528
+ const memory = /* @__PURE__ */ new Map();
529
+ const failingKeys = /* @__PURE__ */ new Set();
530
+ function refresh(key, url, entry, fetchImpl) {
531
+ if (entry.inflight) return entry.inflight;
532
+ const controller = new AbortController();
533
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
534
+ entry.inflight = fetchImpl(url, {
535
+ headers: { accept: "application/json" },
536
+ signal: controller.signal
537
+ }).then(async (res) => {
538
+ if (!res.ok) throw new Error(`${label} ${res.status}`);
539
+ const json = sanitize(await res.json());
540
+ if (!json) throw new Error(`${label} malformed`);
541
+ entry.value = json;
542
+ entry.fetchedAt = Date.now();
543
+ entry.failedAt = 0;
544
+ failingKeys.delete(key);
545
+ return json;
546
+ }).catch((error) => {
547
+ entry.failedAt = Date.now();
548
+ if (!failingKeys.has(key)) {
549
+ failingKeys.add(key);
550
+ console.warn(`[playbook] ${label} fetch failed`, String(error));
551
+ }
552
+ return entry.value;
553
+ }).finally(() => {
554
+ clearTimeout(timer);
555
+ entry.inflight = null;
556
+ });
557
+ memory.set(key, entry);
558
+ return entry.inflight;
559
+ }
560
+ async function getWithSource({
561
+ url,
562
+ waitUntil,
563
+ fetchImpl = fetch
564
+ }) {
565
+ const key = url;
566
+ const entry = memory.get(key) ?? {
567
+ value: null,
568
+ fetchedAt: 0,
569
+ failedAt: 0,
570
+ inflight: null
571
+ };
572
+ const now = Date.now();
573
+ const age = now - entry.fetchedAt;
574
+ if (entry.value && age < FRESH_MS) {
575
+ return { value: entry.value, source: "memory" };
576
+ }
577
+ if (inBackoff(entry, now)) {
578
+ return { value: entry.value, source: "backoff" };
579
+ }
580
+ if (entry.value && age < FRESH_MS + STALE_MS) {
581
+ const p2 = refresh(key, url, entry, fetchImpl);
582
+ waitUntil?.(p2);
583
+ return { value: entry.value, source: "stale" };
584
+ }
585
+ const lastGood = entry.value;
586
+ const p = refresh(key, url, entry, fetchImpl);
587
+ waitUntil?.(p);
588
+ let timer;
589
+ const budget = new Promise((resolve) => {
590
+ timer = setTimeout(
591
+ () => resolve(BUDGET_MISSED),
592
+ lastGood ? RENDER_BUDGET_MS : COLD_RENDER_BUDGET_MS
593
+ );
594
+ });
595
+ const result = await Promise.race([p, budget]);
596
+ clearTimeout(timer);
597
+ if (result === BUDGET_MISSED) {
598
+ if (entry.inflight && entry.failedAt === 0) entry.failedAt = Date.now();
599
+ } else if (result && result !== lastGood) {
600
+ return { value: result, source: "fetched" };
601
+ }
602
+ if (lastGood) return { value: lastGood, source: "last-good" };
603
+ return { value: null, source: "cold-fallback" };
604
+ }
605
+ const reset = () => {
606
+ memory.clear();
607
+ failingKeys.clear();
608
+ };
609
+ return { getWithSource, reset };
610
+ }
611
+ var rulesetFetcher = createCachedJsonFetcher({
612
+ label: "ruleset",
613
+ sanitize: sanitizeRuleset
614
+ });
497
615
  async function getRulesetWithSource({
498
616
  platformUrl,
499
617
  shopId,
500
618
  waitUntil,
501
- fetchImpl = fetch
619
+ fetchImpl
502
620
  }) {
503
- const url = rulesUrl(platformUrl, shopId);
504
- const key = url;
505
- const entry = memory.get(key) ?? {
506
- ruleset: null,
507
- fetchedAt: 0,
508
- failedAt: 0,
509
- inflight: null
510
- };
511
- const now = Date.now();
512
- const age = now - entry.fetchedAt;
513
- if (entry.ruleset && age < FRESH_MS) {
514
- return { ruleset: entry.ruleset, source: "memory" };
515
- }
516
- if (inBackoff(entry, now)) {
517
- return { ruleset: entry.ruleset, source: "backoff" };
518
- }
519
- if (entry.ruleset && age < FRESH_MS + STALE_MS) {
520
- const p2 = refresh(key, url, entry, fetchImpl);
521
- waitUntil?.(p2);
522
- return { ruleset: entry.ruleset, source: "stale" };
523
- }
524
- const lastGood = entry.ruleset;
525
- const p = refresh(key, url, entry, fetchImpl);
526
- waitUntil?.(p);
527
- let timer;
528
- const budget = new Promise((resolve) => {
529
- timer = setTimeout(
530
- () => resolve(BUDGET_MISSED),
531
- lastGood ? RENDER_BUDGET_MS : COLD_RENDER_BUDGET_MS
532
- );
621
+ const { value, source } = await rulesetFetcher.getWithSource({
622
+ url: rulesUrl(platformUrl, shopId),
623
+ waitUntil,
624
+ fetchImpl
533
625
  });
534
- const result = await Promise.race([p, budget]);
535
- clearTimeout(timer);
536
- if (result === BUDGET_MISSED) {
537
- if (entry.inflight && entry.failedAt === 0) entry.failedAt = Date.now();
538
- } else if (result && result !== lastGood) {
539
- return { ruleset: result, source: "fetched" };
540
- }
541
- if (lastGood) return { ruleset: lastGood, source: "last-good" };
542
- return { ruleset: null, source: "cold-fallback" };
626
+ return { ruleset: value, source };
543
627
  }
544
628
  function prefetchRuleset(args) {
545
629
  const p = getRulesetWithSource(args).catch(() => null);
@@ -579,7 +663,6 @@ async function createPlaybook({
579
663
  request,
580
664
  waitUntil,
581
665
  fetchImpl,
582
- overrides,
583
666
  consentRequired = false,
584
667
  consent: consentAdapter
585
668
  }) {
@@ -640,6 +723,15 @@ async function createPlaybook({
640
723
  })
641
724
  );
642
725
  }
726
+ const marker = serverVisitorMarker(visitorId);
727
+ if (cookies[SERVER_VISITOR_MARKER_COOKIE] !== marker || !refreshed) {
728
+ setCookieHeaders.push(
729
+ serializeCookie(SERVER_VISITOR_MARKER_COOKIE, marker, {
730
+ maxAge: VISITOR_MAX_AGE,
731
+ secure
732
+ })
733
+ );
734
+ }
643
735
  if (!refreshed) {
644
736
  setCookieHeaders.push(
645
737
  serializeCookie(VISITOR_REFRESHED_COOKIE, "1", {
@@ -662,6 +754,11 @@ async function createPlaybook({
662
754
  serializeCookie(VISITOR_COOKIE, "", { maxAge: 0, secure })
663
755
  );
664
756
  }
757
+ if (consent === "denied" && cookies[SERVER_VISITOR_MARKER_COOKIE]) {
758
+ setCookieHeaders.push(
759
+ serializeCookie(SERVER_VISITOR_MARKER_COOKIE, "", { maxAge: 0, secure })
760
+ );
761
+ }
665
762
  }
666
763
  if (cookies[LEGACY_VISITOR_COOKIE]) {
667
764
  setCookieHeaders.push(
@@ -728,22 +825,6 @@ async function createPlaybook({
728
825
  });
729
826
  assignments[test.key] = isolated && preview?.testKey !== test.key ? { ...a, arm: controlArmOf(test), inTest: false, forced: false, reason: "preview-isolated" } : a;
730
827
  }
731
- for (const o of overrides ?? []) {
732
- if (isolated && preview?.testKey !== o.testKey) continue;
733
- if (preview?.testKey === o.testKey && !(previewSource === "session" && o.source === "request")) {
734
- continue;
735
- }
736
- const test = ruleset?.tests.find((t) => t.key === o.testKey);
737
- const a = assignments[o.testKey];
738
- if (!test || !a || !test.arms.some((arm) => arm.key === o.arm)) continue;
739
- assignments[o.testKey] = {
740
- ...a,
741
- arm: o.arm,
742
- inTest: false,
743
- forced: true,
744
- reason: "override"
745
- };
746
- }
747
828
  return {
748
829
  state: {
749
830
  enabled: true,
@@ -778,6 +859,14 @@ function cartHasPlaybookAttribute(attributes, visitorId) {
778
859
  (a) => a.key === CART_VISITOR_ATTRIBUTE && a.value === visitorId
779
860
  );
780
861
  }
862
+ function reconcilePlaybookCartAttribute(current, visitorId) {
863
+ const attributes = current ?? [];
864
+ const ours = attributes.filter((a) => a.key === CART_VISITOR_ATTRIBUTE);
865
+ const correct = visitorId ? ours.length === 1 && ours[0].value === visitorId : ours.length === 0;
866
+ if (correct) return null;
867
+ const kept = attributes.filter((a) => a.key !== CART_VISITOR_ATTRIBUTE).map((a) => ({ key: a.key, value: a.value ?? "" }));
868
+ return visitorId ? [...kept, { key: CART_VISITOR_ATTRIBUTE, value: visitorId }] : kept;
869
+ }
781
870
 
782
871
  // src/env.ts
783
872
  function hasPlaybookParams(url) {
@@ -798,12 +887,200 @@ function isPreviewHost(hostname) {
798
887
  return h === "localhost" || h === "127.0.0.1" || /\.myshopify\.(dev|com)$/.test(h) || /\.shopifypreview\.com$/.test(h) || /\.workers\.dev$/.test(h);
799
888
  }
800
889
 
890
+ // src/experience-attribution.ts
891
+ var EXPOSURE_COOKIE = "_pb_exp";
892
+ var EXPOSURE_CART_ATTRIBUTE = "pb_exp__";
893
+ var EXPERIENCE_VISITOR_CART_ATTRIBUTE = "pb_vid__";
894
+ var MAX_EXPOSURES = 8;
895
+ var EXPOSURE_TTL_DAYS = 30;
896
+ var EXPOSURE_ID_RE = /^[A-Za-z0-9-]{1,64}$/;
897
+ var VISITOR_ID_RE = /^[A-Za-z0-9._:-]{8,128}$/;
898
+ var ENTRY_SEP = "_";
899
+ var FIELD_SEP = ".";
900
+ function nowSeconds() {
901
+ return Math.floor(Date.now() / 1e3);
902
+ }
903
+ function maybeDecode(value) {
904
+ if (!value.includes("%")) return value;
905
+ try {
906
+ return decodeURIComponent(value);
907
+ } catch {
908
+ return value;
909
+ }
910
+ }
911
+ function normalize(list, now) {
912
+ const oldest = now - EXPOSURE_TTL_DAYS * 86400;
913
+ const sorted = list.filter(
914
+ (e) => EXPOSURE_ID_RE.test(e.experimentId) && EXPOSURE_ID_RE.test(e.armId) && EXPOSURE_ID_RE.test(e.impressionId) && Number.isFinite(e.seenAt) && e.seenAt >= oldest
915
+ ).sort((a, b) => b.seenAt - a.seenAt);
916
+ const seen = /* @__PURE__ */ new Set();
917
+ const out = [];
918
+ for (const e of sorted) {
919
+ if (seen.has(e.experimentId)) continue;
920
+ seen.add(e.experimentId);
921
+ out.push(e);
922
+ if (out.length >= MAX_EXPOSURES) break;
923
+ }
924
+ return out;
925
+ }
926
+ function normalizeExposureList(raw, now = nowSeconds()) {
927
+ if (typeof raw !== "string" || !raw) return null;
928
+ let value = maybeDecode(raw);
929
+ if (value.length > 4096) value = value.slice(0, 4096);
930
+ const parsed = [];
931
+ for (const part of value.split(ENTRY_SEP)) {
932
+ const fields = part.split(FIELD_SEP);
933
+ if (fields.length !== 4) continue;
934
+ const [experimentId, armId, impressionId, seen36] = fields;
935
+ const seenAt = parseInt(seen36, 36);
936
+ if (!Number.isFinite(seenAt)) continue;
937
+ parsed.push({ experimentId, armId, impressionId, seenAt });
938
+ }
939
+ const list = normalize(parsed, now);
940
+ if (!list.length) return null;
941
+ return list.map(
942
+ (e) => [
943
+ e.experimentId,
944
+ e.armId,
945
+ e.impressionId,
946
+ Math.max(0, Math.floor(e.seenAt)).toString(36)
947
+ ].join(FIELD_SEP)
948
+ ).join(ENTRY_SEP);
949
+ }
950
+ function validId(value) {
951
+ if (!value) return null;
952
+ const decoded = maybeDecode(value).trim();
953
+ return VISITOR_ID_RE.test(decoded) ? decoded : null;
954
+ }
955
+ function experienceVisitorIdFromCookies(cookies) {
956
+ return validId(cookies._y) ?? validId(cookies.shopify_client_id) ?? validId(cookies._shopify_y) ?? validId(cookies[VISITOR_COOKIE]);
957
+ }
958
+ function hasValue(attributes, key) {
959
+ return attributes.some((a) => a.key === key && !!a.value);
960
+ }
961
+ function reconcileExperienceCartAttributes(current, { consent, exposureCookie, visitorId, now }) {
962
+ const attributes = current ?? [];
963
+ const ours = /* @__PURE__ */ new Set([EXPOSURE_CART_ATTRIBUTE, EXPERIENCE_VISITOR_CART_ATTRIBUTE]);
964
+ const kept = () => attributes.map((a) => ({ key: a.key, value: a.value ?? "" }));
965
+ if (consent === "denied") {
966
+ if (!attributes.some((a) => ours.has(a.key))) return null;
967
+ return attributes.filter((a) => !ours.has(a.key)).map((a) => ({ key: a.key, value: a.value ?? "" }));
968
+ }
969
+ if (consent !== "allowed") return null;
970
+ const exposures = normalizeExposureList(exposureCookie, now);
971
+ if (!exposures) return null;
972
+ const additions = [];
973
+ if (!hasValue(attributes, EXPOSURE_CART_ATTRIBUTE)) {
974
+ additions.push({ key: EXPOSURE_CART_ATTRIBUTE, value: exposures });
975
+ }
976
+ const vid = visitorId && VISITOR_ID_RE.test(visitorId) ? visitorId : null;
977
+ if (vid && !hasValue(attributes, EXPERIENCE_VISITOR_CART_ATTRIBUTE)) {
978
+ additions.push({ key: EXPERIENCE_VISITOR_CART_ATTRIBUTE, value: vid });
979
+ }
980
+ if (!additions.length) return null;
981
+ const filling = new Set(additions.map((a) => a.key));
982
+ return [...kept().filter((a) => !filling.has(a.key)), ...additions];
983
+ }
984
+
985
+ // src/targeting.ts
986
+ function manifestUrl(platformUrl, shopDomain) {
987
+ const url = new URL("/api/storefront/targeting", platformUrl);
988
+ url.searchParams.set("shop", shopDomain);
989
+ return url.toString();
990
+ }
991
+ var MAX_PAGES = 500;
992
+ var MAX_KEY_LENGTH = 300;
993
+ function sanitizeManifestPages(value) {
994
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
995
+ const v = value;
996
+ if (typeof v.salt !== "string" || !Array.isArray(v.entries)) return null;
997
+ if (!Array.isArray(v.pages)) return [];
998
+ return v.pages.filter(
999
+ (p) => typeof p === "string" && p.length > 0 && p.length <= MAX_KEY_LENGTH
1000
+ ).slice(0, MAX_PAGES);
1001
+ }
1002
+ var manifestFetcher = createCachedJsonFetcher({
1003
+ label: "targeting manifest",
1004
+ sanitize: (json) => {
1005
+ const pages = sanitizeManifestPages(json);
1006
+ return pages ? { pages } : null;
1007
+ }
1008
+ });
1009
+ var HEALTHY = /* @__PURE__ */ new Set([
1010
+ "memory",
1011
+ "stale",
1012
+ "fetched"
1013
+ ]);
1014
+ async function getTargetedPages({
1015
+ platformUrl,
1016
+ shopDomain,
1017
+ waitUntil,
1018
+ fetchImpl
1019
+ }) {
1020
+ try {
1021
+ const { value, source } = await manifestFetcher.getWithSource({
1022
+ url: manifestUrl(platformUrl, shopDomain),
1023
+ waitUntil,
1024
+ fetchImpl
1025
+ });
1026
+ return { pages: value && HEALTHY.has(source) ? value.pages : null, source };
1027
+ } catch {
1028
+ return { pages: null, source: "cold-fallback" };
1029
+ }
1030
+ }
1031
+ var UNTARGETABLE_PATH_RE = /^\/(account|checkout|checkouts|orders|password|challenge|apps|tools|admin|services)(\/|$)/i;
1032
+ function targetPageKey(pathname) {
1033
+ let path = (pathname || "/").replace(/\/+$/, "") || "/";
1034
+ path = path.replace(/^\/[a-z]{2}(-[a-z]{2})?(?=\/|$)/i, "") || "/";
1035
+ if (path === "/") return "home:";
1036
+ if (UNTARGETABLE_PATH_RE.test(path)) return null;
1037
+ const decode = (raw) => {
1038
+ let h = raw;
1039
+ try {
1040
+ h = decodeURIComponent(h);
1041
+ } catch {
1042
+ }
1043
+ h = h.trim().toLowerCase();
1044
+ return h.length > 0 ? h : null;
1045
+ };
1046
+ const handle = (re) => {
1047
+ const m = re.exec(path);
1048
+ return m ? decode(m[1]) : null;
1049
+ };
1050
+ const product = handle(/\/products\/([^/?#]+)/);
1051
+ if (product) return `product:${product}`;
1052
+ const collection = handle(/^\/collections\/([^/?#]+)$/);
1053
+ if (collection) return `collection:${collection}`;
1054
+ const page = handle(/^\/pages\/([^/?#]+)$/);
1055
+ if (page) return `page:${page}`;
1056
+ const other = decode(path.replace(/^\//, ""));
1057
+ return other ? `page:${other}` : null;
1058
+ }
1059
+ function matchTargetedPage(pages, pathname) {
1060
+ if (!pages || pages.length === 0) return null;
1061
+ const key = targetPageKey(pathname);
1062
+ if (!key) return null;
1063
+ const hit = pages.some((p) => {
1064
+ if (typeof p !== "string") return false;
1065
+ const k = p.toLowerCase();
1066
+ return k.endsWith("*") ? key.startsWith(k.slice(0, -1)) : k === key;
1067
+ });
1068
+ return hit ? key : null;
1069
+ }
1070
+ var OWNED_PARAM_RE = /[?&](pbk|pb|_pv|_preview|pb_mode|pbThumb)=/;
1071
+ function hasOwnedPreviewParams(search) {
1072
+ return OWNED_PARAM_RE.test(search || "");
1073
+ }
1074
+
801
1075
  // src/request-context.ts
802
1076
  var FINALIZE_WAIT_MS = 2e3;
803
1077
  var FINALIZE_REDIRECT_WAIT_MS = 0;
804
1078
  function str(v) {
805
1079
  return typeof v === "string" && v ? v : void 0;
806
1080
  }
1081
+ function normalizeDomain(raw) {
1082
+ return raw.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/[/?#].*$/, "");
1083
+ }
807
1084
  function createPlaybookContext({
808
1085
  request,
809
1086
  env,
@@ -813,7 +1090,10 @@ function createPlaybookContext({
813
1090
  disabled: disabledOption,
814
1091
  consentRequired = false,
815
1092
  consent,
816
- overrides,
1093
+ experienceAttribution = true,
1094
+ cloak: cloakOption = true,
1095
+ shopDomain: shopDomainOption,
1096
+ apiBase: apiBaseOption,
817
1097
  fetchImpl
818
1098
  }) {
819
1099
  const e = env ?? {};
@@ -839,7 +1119,6 @@ function createPlaybookContext({
839
1119
  request,
840
1120
  waitUntil,
841
1121
  fetchImpl,
842
- overrides,
843
1122
  consentRequired,
844
1123
  consent
845
1124
  }).catch((error) => {
@@ -865,6 +1144,55 @@ function createPlaybookContext({
865
1144
  }
866
1145
  return (await promise)?.setCookieHeaders ?? [];
867
1146
  };
1147
+ const cartConsent = (cookies) => {
1148
+ const state = consent ? consent.fromRequest(request) : analyticsConsentFromCookie(cookies[TRACKING_CONSENT_COOKIE]);
1149
+ if (state === "granted" || state === "absent" && !consentRequired) {
1150
+ return "allowed";
1151
+ }
1152
+ return state === "denied" ? "denied" : "unknown";
1153
+ };
1154
+ const cartVisitorId = () => {
1155
+ if (!shopId) return null;
1156
+ try {
1157
+ const cookies = parseCookies(request.headers.get("cookie"));
1158
+ if (cartConsent(cookies) !== "allowed") return null;
1159
+ return [cookies[VISITOR_COOKIE], cookies[SESSION_VISITOR_COOKIE]].find(
1160
+ (v) => isValidVisitorId(v)
1161
+ ) ?? null;
1162
+ } catch {
1163
+ return null;
1164
+ }
1165
+ };
1166
+ let cloakPromise = null;
1167
+ const cloakFor = () => {
1168
+ if (!cloakPromise) {
1169
+ cloakPromise = (async () => {
1170
+ if (!shopId || !cloakOption || request.method !== "GET") return null;
1171
+ const url = new URL(request.url);
1172
+ if (url.pathname.endsWith(".data")) return null;
1173
+ if (hasOwnedPreviewParams(url.search)) return null;
1174
+ if (!targetPageKey(url.pathname)) return null;
1175
+ const shopDomain = normalizeDomain(
1176
+ shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? url.hostname
1177
+ );
1178
+ if (!shopDomain) return null;
1179
+ const { pages } = await getTargetedPages({
1180
+ platformUrl,
1181
+ shopDomain,
1182
+ waitUntil,
1183
+ fetchImpl
1184
+ });
1185
+ const targetedPage = matchTargetedPage(pages, url.pathname);
1186
+ if (!targetedPage) return null;
1187
+ return {
1188
+ targetedPage,
1189
+ shopDomain,
1190
+ apiBase: apiBaseOption || `${url.origin}/apps/playbook`
1191
+ };
1192
+ })().catch(() => null);
1193
+ }
1194
+ return cloakPromise;
1195
+ };
868
1196
  const append = (headers, cookies) => {
869
1197
  for (const cookie of cookies) headers.append("Set-Cookie", cookie);
870
1198
  };
@@ -874,24 +1202,43 @@ function createPlaybookContext({
874
1202
  disabled: disabled || !configuredShop,
875
1203
  get,
876
1204
  async loaderData() {
877
- const result = await get();
1205
+ const [result, cloak] = await Promise.all([get(), cloakFor()]);
878
1206
  return {
879
1207
  playbook: result?.state ?? null,
880
- hasPlaybookParams: hasPlaybookParams(request.url)
1208
+ hasPlaybookParams: hasPlaybookParams(request.url),
1209
+ targetedPage: cloak?.targetedPage ?? null,
1210
+ cloak
881
1211
  };
882
1212
  },
883
1213
  cartAttribute() {
1214
+ const id = cartVisitorId();
1215
+ return id ? { key: CART_VISITOR_ATTRIBUTE, value: id } : null;
1216
+ },
1217
+ cartVisitorId,
1218
+ reconcileCartAttributes(current) {
884
1219
  if (!shopId) return null;
1220
+ let storeEdit = null;
885
1221
  try {
886
- const cookies = parseCookies(request.headers.get("cookie"));
887
- const state = consent ? consent.fromRequest(request) : analyticsConsentFromCookie(cookies[TRACKING_CONSENT_COOKIE]);
888
- const allowed = state === "granted" || state === "absent" && !consentRequired;
889
- if (!allowed) return null;
890
- const id = [cookies[VISITOR_COOKIE], cookies[SESSION_VISITOR_COOKIE]].find((v) => isValidVisitorId(v));
891
- return id ? { key: CART_VISITOR_ATTRIBUTE, value: id } : null;
1222
+ storeEdit = reconcilePlaybookCartAttribute(current, cartVisitorId());
892
1223
  } catch {
893
1224
  return null;
894
1225
  }
1226
+ if (!experienceAttribution) return storeEdit;
1227
+ try {
1228
+ const cookies = parseCookies(request.headers.get("cookie"));
1229
+ const consentState = cartConsent(cookies);
1230
+ const experience = reconcileExperienceCartAttributes(
1231
+ storeEdit ?? current,
1232
+ {
1233
+ consent: consentState,
1234
+ exposureCookie: cookies[EXPOSURE_COOKIE],
1235
+ visitorId: consentState === "allowed" ? experienceVisitorIdFromCookies(cookies) : null
1236
+ }
1237
+ );
1238
+ return experience ?? storeEdit;
1239
+ } catch {
1240
+ return storeEdit;
1241
+ }
895
1242
  },
896
1243
  async appendCookies(headers) {
897
1244
  try {
@@ -1022,6 +1369,93 @@ function PlaybookHead({
1022
1369
  )
1023
1370
  ] });
1024
1371
  }
1372
+ var CLOAK_MAX_MS = 1500;
1373
+ var DEFAULT_EXPERIENCE_SDK_URL = "https://cdn.heyplaybook.com/experience-sdk.js";
1374
+ var CLOAK_STYLE_ID = "pb-cloak";
1375
+ var EXPERIENCE_SDK_SCRIPT_ID = "pb-experience-sdk";
1376
+ function jsLiteral(value) {
1377
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1378
+ }
1379
+ function safeSdkUrl(raw) {
1380
+ if (!raw) return DEFAULT_EXPERIENCE_SDK_URL;
1381
+ try {
1382
+ const u = new URL(raw);
1383
+ return u.protocol === "https:" && !u.username && !u.password ? u.toString() : DEFAULT_EXPERIENCE_SDK_URL;
1384
+ } catch {
1385
+ return DEFAULT_EXPERIENCE_SDK_URL;
1386
+ }
1387
+ }
1388
+ function clampHide(ms) {
1389
+ if (typeof ms !== "number" || !Number.isFinite(ms)) return CLOAK_MAX_MS;
1390
+ return Math.min(CLOAK_MAX_MS, Math.max(100, Math.round(ms)));
1391
+ }
1392
+ function buildHeadSnippet(cloak, options = {}) {
1393
+ if (!cloak || !cloak.targetedPage || !cloak.shopDomain || !cloak.apiBase) {
1394
+ return null;
1395
+ }
1396
+ const ms = clampHide(options.maxHideMs);
1397
+ const src = safeSdkUrl(options.sdkUrl);
1398
+ const css = `html:not(.pb-ready){opacity:0;animation:pb-uncloak 0s linear ${ms}ms forwards}@keyframes pb-uncloak{to{opacity:1}}`;
1399
+ const script = "(function(){var w=window,d=document;if(w.__pbCloak)return;var st=d.getElementById(" + jsLiteral(CLOAK_STYLE_ID) + ");function now(){try{return Math.round(performance.now())}catch(e){return 0}}var state={armedAt:now(),liftedAt:null,reason:null,rules:1,sdk:" + jsLiteral(src) + ",page:" + jsLiteral(cloak.targetedPage) + '};var timer=null;function lift(reason){if(state.liftedAt!==null)return;if(timer)clearTimeout(timer);state.liftedAt=now();state.reason=reason||"sdk";try{if(st){st.disabled=true;if(st.sheet)st.sheet.disabled=true}}catch(e){}try{performance.mark("pb:cloak:lift")}catch(e){}}state.lift=lift;w.__pbCloak=state;try{d.addEventListener("error",function(e){var t=e&&e.target;if(t&&t.id===' + jsLiteral(EXPERIENCE_SDK_SCRIPT_ID) + '){state.sdk=null;lift("sdk-error")}},true)}catch(e){}try{if(w.top!==w.self)return lift("iframe");if(/(\\.vercel\\.app|heyplaybook\\.com)$/.test(location.hostname))return lift("preview-host");if(/[?&](pbk|pb|_pv|_preview|pb_mode|pbThumb)=/.test(location.search))return lift("param")}catch(e){return lift("error")}timer=setTimeout(function(){lift("timeout")},' + ms + ");})();";
1400
+ const attrs = {
1401
+ "data-pb-api-base": cloak.apiBase,
1402
+ "data-pb-shop": cloak.shopDomain,
1403
+ "data-pb-targeted": "1"
1404
+ };
1405
+ if (options.consentRequired) attrs["data-pb-consent"] = "required";
1406
+ return { css, script, sdk: { src, attrs }, nonce: options.nonce };
1407
+ }
1408
+ var PlaybookCloakHead = memo(
1409
+ function PlaybookCloakHead2({
1410
+ cloak,
1411
+ ...options
1412
+ }) {
1413
+ const parts = buildHeadSnippet(cloak, options);
1414
+ if (!parts) return null;
1415
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1416
+ /* @__PURE__ */ jsx(
1417
+ "style",
1418
+ {
1419
+ id: CLOAK_STYLE_ID,
1420
+ nonce: parts.nonce,
1421
+ dangerouslySetInnerHTML: { __html: parts.css }
1422
+ }
1423
+ ),
1424
+ /* @__PURE__ */ jsx(
1425
+ "script",
1426
+ {
1427
+ nonce: parts.nonce,
1428
+ dangerouslySetInnerHTML: { __html: parts.script }
1429
+ }
1430
+ ),
1431
+ /* @__PURE__ */ jsx(
1432
+ "script",
1433
+ {
1434
+ id: EXPERIENCE_SDK_SCRIPT_ID,
1435
+ src: parts.sdk.src,
1436
+ nonce: parts.nonce,
1437
+ async: true,
1438
+ ...parts.sdk.attrs
1439
+ }
1440
+ )
1441
+ ] });
1442
+ },
1443
+ () => true
1444
+ );
1445
+ function playbookHeadSnippet(cloak, options = {}) {
1446
+ if (!buildHeadSnippet(cloak, options)) return null;
1447
+ return /* @__PURE__ */ jsx(PlaybookCloakHead, { cloak, ...options });
1448
+ }
1449
+ function escapeAttr(value) {
1450
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1451
+ }
1452
+ function playbookHeadSnippetHtml(cloak, options = {}) {
1453
+ const parts = buildHeadSnippet(cloak, options);
1454
+ if (!parts) return "";
1455
+ const nonce = parts.nonce ? ` nonce="${escapeAttr(parts.nonce)}"` : "";
1456
+ const attrs = Object.entries(parts.sdk.attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
1457
+ return `<style id="${CLOAK_STYLE_ID}"${nonce}>${parts.css}</style><script${nonce}>${parts.script}</script><script id="${EXPERIENCE_SDK_SCRIPT_ID}" src="${escapeAttr(parts.sdk.src)}"${nonce} async${attrs}></script>`;
1458
+ }
1025
1459
  var PlaybookBoundary = class extends Component {
1026
1460
  state = { failed: false };
1027
1461
  static getDerivedStateFromError() {
@@ -1258,7 +1692,7 @@ var config = {
1258
1692
  eventUrl: "/apps/playbook/api/storefront/tests/event",
1259
1693
  supportedEvents: new Set(DEFAULT_SUPPORTED_EVENTS),
1260
1694
  store: {},
1261
- dataLayer: {}
1695
+ dataLayer: false
1262
1696
  };
1263
1697
  var seenOnPage = /* @__PURE__ */ new Set();
1264
1698
  function configureTracker(next) {
@@ -1448,7 +1882,8 @@ function body(s2, testKey, arm, extra) {
1448
1882
  }
1449
1883
  function pushExposureToDataLayer(s2, testKey, arm) {
1450
1884
  const option = config.dataLayer;
1451
- if (option === false) return;
1885
+ if (!option) return;
1886
+ const eventName = option !== true && option.eventName || DEFAULT_DATALAYER_EVENT;
1452
1887
  try {
1453
1888
  const dl = window.dataLayer;
1454
1889
  if (!Array.isArray(dl) && typeof dl?.push !== "function") {
@@ -1459,7 +1894,7 @@ function pushExposureToDataLayer(s2, testKey, arm) {
1459
1894
  const cfg = assignment?.config ?? {};
1460
1895
  const str2 = (v) => typeof v === "string" && v ? v.slice(0, 100) : null;
1461
1896
  dl.push({
1462
- event: option.eventName || DEFAULT_DATALAYER_EVENT,
1897
+ event: eventName,
1463
1898
  experiment_id: testKey,
1464
1899
  // The ruleset carries no display names yet; an explicit
1465
1900
  // `config.experimentName` wins, else the key (never a variant's copy).
@@ -1572,7 +2007,8 @@ var PlaybookContext = createContext({
1572
2007
  pathname: "/",
1573
2008
  exposureUrl: DEFAULT_EXPOSURE_URL,
1574
2009
  eventUrl: DEFAULT_EVENT_URL,
1575
- consent: "pending"
2010
+ consent: "pending",
2011
+ previewIgnoresTargeting: false
1576
2012
  });
1577
2013
  function usePlaybookConsent() {
1578
2014
  return useContext(PlaybookContext).consent;
@@ -1591,10 +2027,13 @@ var CONTROL = {
1591
2027
  config: {}
1592
2028
  };
1593
2029
  function usePlaybookVariant(testKey, { eligible = true } = {}) {
1594
- const { state, pathname } = useContext(PlaybookContext);
2030
+ const { state, pathname, previewIgnoresTargeting } = useContext(PlaybookContext);
1595
2031
  const a = state?.enabled ? state.tests[testKey] : void 0;
1596
2032
  return useMemo(() => {
1597
2033
  if (!a) return CONTROL;
2034
+ if (a.forced && previewIgnoresTargeting) {
2035
+ return { arm: a.arm, inTest: false, forced: true, config: a.config };
2036
+ }
1598
2037
  if (!eligible || !matchesPathPrefix(pathname, a.pathPrefix)) {
1599
2038
  return { ...CONTROL, config: a.config };
1600
2039
  }
@@ -1602,7 +2041,7 @@ function usePlaybookVariant(testKey, { eligible = true } = {}) {
1602
2041
  return { arm: a.arm, inTest: false, forced: true, config: a.config };
1603
2042
  }
1604
2043
  return { arm: a.arm, inTest: a.inTest, forced: false, config: a.config };
1605
- }, [a, eligible, pathname]);
2044
+ }, [a, eligible, pathname, previewIgnoresTargeting]);
1606
2045
  }
1607
2046
  function usePlaybookInteraction(testKey, variant) {
1608
2047
  return useCallback(
@@ -1682,13 +2121,19 @@ var SERVER_REASONS = {
1682
2121
  coverage: "out of coverage",
1683
2122
  winner: "completed: winner served",
1684
2123
  preview: "forced: preview link",
1685
- "preview-isolated": "another test is being previewed",
1686
- override: "forced: override"
2124
+ "preview-isolated": "another test is being previewed"
1687
2125
  };
1688
- function whyNotInTest(key, a, pathname, implementedTests) {
2126
+ function whyNotInTest(key, a, pathname, implementedTests, explain) {
1689
2127
  if (implementedTests && !implementedTests.has(key)) {
1690
2128
  return "no code on this storefront";
1691
2129
  }
2130
+ if (explain) {
2131
+ try {
2132
+ const custom = explain(key, a, pathname);
2133
+ if (typeof custom === "string" && custom) return custom;
2134
+ } catch {
2135
+ }
2136
+ }
1692
2137
  if (a.forced) return SERVER_REASONS[a.reason] ?? "forced";
1693
2138
  if (!a.inTest) {
1694
2139
  if (a.reason === "not-running") return a.status;
@@ -1739,7 +2184,8 @@ function PlaybookDebugPanel({
1739
2184
  state,
1740
2185
  location,
1741
2186
  allowed,
1742
- implementedTests
2187
+ implementedTests,
2188
+ explain
1743
2189
  }) {
1744
2190
  const { pathname, search = "" } = location;
1745
2191
  const param = new URLSearchParams(search).get(FLAG);
@@ -1815,7 +2261,7 @@ function PlaybookDebugPanel({
1815
2261
  ] }),
1816
2262
  !tests.length && /* @__PURE__ */ jsx("p", { style: s.p, children: "No tests in the ruleset." }),
1817
2263
  /* @__PURE__ */ jsx("ul", { style: s.list, children: tests.map(([key, a]) => {
1818
- const why = whyNotInTest(key, a, pathname, implemented);
2264
+ const why = whyNotInTest(key, a, pathname, implemented, explain);
1819
2265
  const exposed = !!vid && hasSentExposure(vid, key);
1820
2266
  return /* @__PURE__ */ jsxs("li", { style: s.card, children: [
1821
2267
  /* @__PURE__ */ jsx("p", { style: { ...s.p, fontWeight: 600 }, children: key }),
@@ -1922,6 +2368,142 @@ function usePageEngagement(pathname, enabled) {
1922
2368
  };
1923
2369
  }, [pathname, enabled]);
1924
2370
  }
2371
+
2372
+ // src/consent-adapters.ts
2373
+ function consentFromAnalytics(value) {
2374
+ if (value === true || value === "granted" || value === "yes") {
2375
+ return "granted";
2376
+ }
2377
+ if (value === false || value === "denied" || value === "no") return "denied";
2378
+ return "pending";
2379
+ }
2380
+ var shopifyCustomerPrivacyConsent = {
2381
+ id: "shopify-customer-privacy",
2382
+ read() {
2383
+ if (typeof window === "undefined") return "pending";
2384
+ try {
2385
+ return getConsentState();
2386
+ } catch {
2387
+ return "pending";
2388
+ }
2389
+ },
2390
+ subscribe(onChange) {
2391
+ if (typeof window === "undefined") return () => {
2392
+ };
2393
+ let live = true;
2394
+ const notify = () => {
2395
+ if (live) onChange();
2396
+ };
2397
+ waitForConsentAPI().then(notify, notify);
2398
+ const offLoaded = onConsentLoaded(notify);
2399
+ const offChange = onConsentChange(notify);
2400
+ return () => {
2401
+ live = false;
2402
+ offLoaded();
2403
+ offChange();
2404
+ };
2405
+ }
2406
+ };
2407
+ var TRUEVAULT_CONSENT_COOKIE = "polaris_consent_settings";
2408
+ var TRUEVAULT_CONSENT_EVENT = "consentChanged";
2409
+ var POLL_INTERVAL_MS = 500;
2410
+ var POLL_CHECKS = 20;
2411
+ function trueVaultDecision(raw, gpc, { whenMissing = "pending", gpc: gpcMode = "follow-banner" } = {}) {
2412
+ if (gpc && gpcMode === "deny") return "denied";
2413
+ if (raw === null || raw === void 0 || raw === "") return whenMissing;
2414
+ let data = null;
2415
+ for (const candidate of [raw, safeDecode(raw)]) {
2416
+ if (candidate === null) continue;
2417
+ try {
2418
+ data = JSON.parse(candidate);
2419
+ break;
2420
+ } catch {
2421
+ }
2422
+ }
2423
+ const permitted = data?.analyticsPermitted;
2424
+ if (permitted === true) return "granted";
2425
+ if (permitted === false) return "denied";
2426
+ return "pending";
2427
+ }
2428
+ function safeDecode(raw) {
2429
+ try {
2430
+ return decodeURIComponent(raw);
2431
+ } catch {
2432
+ return null;
2433
+ }
2434
+ }
2435
+ function readDocumentCookie(name) {
2436
+ try {
2437
+ const match = document.cookie.match(
2438
+ new RegExp(`(?:^|; )${name}=([^;]*)`)
2439
+ );
2440
+ return match ? match[1] : null;
2441
+ } catch {
2442
+ return null;
2443
+ }
2444
+ }
2445
+ function clientGpc() {
2446
+ try {
2447
+ return navigator.globalPrivacyControl === true;
2448
+ } catch {
2449
+ return false;
2450
+ }
2451
+ }
2452
+ function createTrueVaultConsent(options = {}) {
2453
+ return {
2454
+ id: "truevault",
2455
+ fromRequest(request) {
2456
+ try {
2457
+ const cookies = parseCookies(request.headers.get("cookie"));
2458
+ const gpc = request.headers.get("sec-gpc") === "1";
2459
+ return trueVaultDecision(
2460
+ cookies[TRUEVAULT_CONSENT_COOKIE],
2461
+ gpc,
2462
+ options
2463
+ );
2464
+ } catch {
2465
+ return "pending";
2466
+ }
2467
+ },
2468
+ read() {
2469
+ if (typeof document === "undefined") return "pending";
2470
+ return trueVaultDecision(
2471
+ readDocumentCookie(TRUEVAULT_CONSENT_COOKIE),
2472
+ clientGpc(),
2473
+ options
2474
+ );
2475
+ },
2476
+ subscribe(onChange) {
2477
+ if (typeof window === "undefined") return () => {
2478
+ };
2479
+ const handler = () => setTimeout(onChange, 0);
2480
+ const onVisible = () => {
2481
+ if (document.visibilityState === "visible") onChange();
2482
+ };
2483
+ window.addEventListener(TRUEVAULT_CONSENT_EVENT, handler);
2484
+ document.addEventListener("visibilitychange", onVisible);
2485
+ let poll = null;
2486
+ if (readDocumentCookie(TRUEVAULT_CONSENT_COOKIE) === null) {
2487
+ let checks = 0;
2488
+ poll = setInterval(() => {
2489
+ checks += 1;
2490
+ const present = readDocumentCookie(TRUEVAULT_CONSENT_COOKIE) !== null;
2491
+ if (present || checks >= POLL_CHECKS) {
2492
+ if (poll) clearInterval(poll);
2493
+ poll = null;
2494
+ if (present) onChange();
2495
+ }
2496
+ }, POLL_INTERVAL_MS);
2497
+ }
2498
+ return () => {
2499
+ window.removeEventListener(TRUEVAULT_CONSENT_EVENT, handler);
2500
+ document.removeEventListener("visibilitychange", onVisible);
2501
+ if (poll) clearInterval(poll);
2502
+ };
2503
+ }
2504
+ };
2505
+ }
2506
+ var truevaultConsent = createTrueVaultConsent();
1925
2507
  function PlaybookProvider({
1926
2508
  state,
1927
2509
  pathname,
@@ -1930,33 +2512,31 @@ function PlaybookProvider({
1930
2512
  supportedEvents = DEFAULT_SUPPORTED_EVENTS,
1931
2513
  storeContext,
1932
2514
  consent: consentAdapter,
1933
- dataLayer = {},
2515
+ dataLayer = false,
2516
+ previewIgnoresTargeting = false,
1934
2517
  children
1935
2518
  }) {
1936
2519
  const [consent, setConsent] = useState("pending");
1937
2520
  const consentRequired = !!state?.consentRequired;
1938
2521
  useEffect(() => {
1939
2522
  let live = true;
1940
- if (consentAdapter) {
1941
- const update2 = () => {
1942
- if (!live) return;
1943
- try {
1944
- setConsent(consentAdapter.read());
1945
- } catch {
1946
- setConsent("pending");
1947
- }
1948
- };
1949
- update2();
1950
- const unsubscribe2 = consentAdapter.subscribe(update2);
1951
- return () => {
1952
- live = false;
1953
- unsubscribe2();
1954
- };
2523
+ const source = consentAdapter ?? shopifyCustomerPrivacyConsent;
2524
+ if (!consentAdapter && consentRequired) declareConsentRequired();
2525
+ const update = () => {
2526
+ if (!live) return;
2527
+ try {
2528
+ setConsent(source.read());
2529
+ } catch {
2530
+ setConsent("pending");
2531
+ }
2532
+ };
2533
+ update();
2534
+ let unsubscribe = () => {
2535
+ };
2536
+ try {
2537
+ unsubscribe = source.subscribe(update);
2538
+ } catch {
1955
2539
  }
1956
- if (consentRequired) declareConsentRequired();
1957
- const update = () => live && setConsent(getConsentState());
1958
- waitForConsentAPI().then(update);
1959
- const unsubscribe = onConsentChange(update);
1960
2540
  return () => {
1961
2541
  live = false;
1962
2542
  unsubscribe();
@@ -1982,8 +2562,15 @@ function PlaybookProvider({
1982
2562
  }
1983
2563
  }
1984
2564
  const value = useMemo(
1985
- () => ({ state: state ?? null, pathname, exposureUrl, eventUrl, consent }),
1986
- [state, pathname, exposureUrl, eventUrl, consent]
2565
+ () => ({
2566
+ state: state ?? null,
2567
+ pathname,
2568
+ exposureUrl,
2569
+ eventUrl,
2570
+ consent,
2571
+ previewIgnoresTargeting
2572
+ }),
2573
+ [state, pathname, exposureUrl, eventUrl, consent, previewIgnoresTargeting]
1987
2574
  );
1988
2575
  return /* @__PURE__ */ jsx(PlaybookContext.Provider, { value, children });
1989
2576
  }
@@ -2104,6 +2691,7 @@ function PlaybookRoot({
2104
2691
  aaSentinel = true,
2105
2692
  debug,
2106
2693
  dataLayer,
2694
+ previewIgnoresTargeting,
2107
2695
  onCartSyncEvent,
2108
2696
  exposureUrl,
2109
2697
  eventUrl,
@@ -2120,6 +2708,7 @@ function PlaybookRoot({
2120
2708
  storeContext,
2121
2709
  consent,
2122
2710
  dataLayer,
2711
+ previewIgnoresTargeting,
2123
2712
  exposureUrl,
2124
2713
  eventUrl,
2125
2714
  supportedEvents,
@@ -2143,7 +2732,8 @@ function PlaybookRoot({
2143
2732
  state,
2144
2733
  location,
2145
2734
  allowed: debug?.allowed,
2146
- implementedTests: debug?.implementedTests
2735
+ implementedTests: debug?.implementedTests,
2736
+ explain: debug?.explain
2147
2737
  }
2148
2738
  ) })
2149
2739
  ] })
@@ -2265,108 +2855,6 @@ function createPlaybookProxyHandler({
2265
2855
  return { loader: proxy, action: proxy };
2266
2856
  }
2267
2857
 
2268
- // src/consent-adapters.ts
2269
- var TRUEVAULT_CONSENT_COOKIE = "polaris_consent_settings";
2270
- var TRUEVAULT_CONSENT_EVENT = "consentChanged";
2271
- var POLL_INTERVAL_MS = 500;
2272
- var POLL_CHECKS = 20;
2273
- function trueVaultDecision(raw, gpc, { whenMissing = "pending", gpc: gpcMode = "follow-banner" } = {}) {
2274
- if (gpc && gpcMode === "deny") return "denied";
2275
- if (raw === null || raw === void 0 || raw === "") return whenMissing;
2276
- let data = null;
2277
- for (const candidate of [raw, safeDecode(raw)]) {
2278
- if (candidate === null) continue;
2279
- try {
2280
- data = JSON.parse(candidate);
2281
- break;
2282
- } catch {
2283
- }
2284
- }
2285
- const permitted = data?.analyticsPermitted;
2286
- if (permitted === true) return "granted";
2287
- if (permitted === false) return "denied";
2288
- return "pending";
2289
- }
2290
- function safeDecode(raw) {
2291
- try {
2292
- return decodeURIComponent(raw);
2293
- } catch {
2294
- return null;
2295
- }
2296
- }
2297
- function readDocumentCookie(name) {
2298
- try {
2299
- const match = document.cookie.match(
2300
- new RegExp(`(?:^|; )${name}=([^;]*)`)
2301
- );
2302
- return match ? match[1] : null;
2303
- } catch {
2304
- return null;
2305
- }
2306
- }
2307
- function clientGpc() {
2308
- try {
2309
- return navigator.globalPrivacyControl === true;
2310
- } catch {
2311
- return false;
2312
- }
2313
- }
2314
- function createTrueVaultConsent(options = {}) {
2315
- return {
2316
- id: "truevault",
2317
- fromRequest(request) {
2318
- try {
2319
- const cookies = parseCookies(request.headers.get("cookie"));
2320
- const gpc = request.headers.get("sec-gpc") === "1";
2321
- return trueVaultDecision(
2322
- cookies[TRUEVAULT_CONSENT_COOKIE],
2323
- gpc,
2324
- options
2325
- );
2326
- } catch {
2327
- return "pending";
2328
- }
2329
- },
2330
- read() {
2331
- if (typeof document === "undefined") return "pending";
2332
- return trueVaultDecision(
2333
- readDocumentCookie(TRUEVAULT_CONSENT_COOKIE),
2334
- clientGpc(),
2335
- options
2336
- );
2337
- },
2338
- subscribe(onChange) {
2339
- if (typeof window === "undefined") return () => {
2340
- };
2341
- const handler = () => setTimeout(onChange, 0);
2342
- const onVisible = () => {
2343
- if (document.visibilityState === "visible") onChange();
2344
- };
2345
- window.addEventListener(TRUEVAULT_CONSENT_EVENT, handler);
2346
- document.addEventListener("visibilitychange", onVisible);
2347
- let poll = null;
2348
- if (readDocumentCookie(TRUEVAULT_CONSENT_COOKIE) === null) {
2349
- let checks = 0;
2350
- poll = setInterval(() => {
2351
- checks += 1;
2352
- const present = readDocumentCookie(TRUEVAULT_CONSENT_COOKIE) !== null;
2353
- if (present || checks >= POLL_CHECKS) {
2354
- if (poll) clearInterval(poll);
2355
- poll = null;
2356
- if (present) onChange();
2357
- }
2358
- }, POLL_INTERVAL_MS);
2359
- }
2360
- return () => {
2361
- window.removeEventListener(TRUEVAULT_CONSENT_EVENT, handler);
2362
- document.removeEventListener("visibilitychange", onVisible);
2363
- if (poll) clearInterval(poll);
2364
- };
2365
- }
2366
- };
2367
- }
2368
- var truevaultConsent = createTrueVaultConsent();
2369
-
2370
2858
  // src/cart-events.ts
2371
2859
  var nextSource = null;
2372
2860
  function setNextAddSource(source) {
@@ -2438,4 +2926,4 @@ function trackAddToCartLines(lines, cartLines, source) {
2438
2926
  }
2439
2927
  }
2440
2928
 
2441
- export { AA_SITEWIDE_TEST, CART_SYNC_IDLE_MS, CART_VISITOR_ATTRIBUTE, CONTROL_ARM, DEFAULT_DATALAYER_EVENT, DEFAULT_EVENT_URL, DEFAULT_EXPOSURE_URL, DEFAULT_PLATFORM_URL, DEFAULT_PROXY_ENDPOINT, DEFAULT_SDK_URL, DEFAULT_SUPPORTED_EVENTS, LEGACY_VISITOR_COOKIE, MAX_WRITES_PER_CART, PlaybookAAExposure, PlaybookBoundary, PlaybookDebugPanel, PlaybookExposure, PlaybookHead, PlaybookProvider, PlaybookRoot, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, TRUEVAULT_CONSENT_COOKIE, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, assignTest, cartHasPlaybookAttribute, chooseVariation, createCartAttributeReader, createCartAttributeSync, createCartAttributeWriter, createPlaybook, createPlaybookContext, createPlaybookProxyHandler, createTrueVaultConsent, debugPanelAllowed, declareConsentRequired, detectDevice, detectGeo, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getTrackedLog, hasPlaybookParams, hasSentExposure, hash, inNamespace, isAnalyticsConsentGranted, isKillSwitchOn, isPreviewHost, matchesPathPrefix, mergeAttributes, onConsentChange, playbookBackendUrl, playbookCartAttribute, playbookTrack, prefetchRuleset, revealScript, sanitizeRuleset, setNextAddSource, subscribeTrackedLog, syncVisitorId, takeAddSource, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
2929
+ export { AA_SITEWIDE_TEST, CART_SYNC_IDLE_MS, CART_VISITOR_ATTRIBUTE, CLOAK_MAX_MS, CLOAK_STYLE_ID, CONSENT_LOADED_EVENTS, CONTROL_ARM, DEFAULT_DATALAYER_EVENT, DEFAULT_EVENT_URL, DEFAULT_EXPERIENCE_SDK_URL, DEFAULT_EXPOSURE_URL, DEFAULT_PLATFORM_URL, DEFAULT_PROXY_ENDPOINT, DEFAULT_SDK_URL, DEFAULT_SUPPORTED_EVENTS, EXPERIENCE_SDK_SCRIPT_ID, EXPERIENCE_VISITOR_CART_ATTRIBUTE, EXPOSURE_CART_ATTRIBUTE, EXPOSURE_COOKIE, LEGACY_VISITOR_COOKIE, MAX_WRITES_PER_CART, PlaybookAAExposure, PlaybookBoundary, PlaybookCloakHead, PlaybookDebugPanel, PlaybookExposure, PlaybookHead, PlaybookProvider, PlaybookRoot, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, TRUEVAULT_CONSENT_COOKIE, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, assignTest, buildHeadSnippet, cartHasPlaybookAttribute, chooseVariation, consentFromAnalytics, createCartAttributeReader, createCartAttributeSync, createCartAttributeWriter, createPlaybook, createPlaybookContext, createPlaybookProxyHandler, createTrueVaultConsent, debugPanelAllowed, declareConsentRequired, detectDevice, detectGeo, experienceVisitorIdFromCookies, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getTargetedPages, getTrackedLog, hasPlaybookParams, hasSentExposure, hash, inNamespace, isAnalyticsConsentGranted, isKillSwitchOn, isPreviewHost, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, revealScript, sanitizeManifestPages, sanitizeRuleset, setNextAddSource, shopifyCustomerPrivacyConsent, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };