@heyplaybook/hydrogen 0.3.0 → 0.7.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,349 @@ 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
+
1075
+ // src/ssr.ts
1076
+ var SSR_SNAPSHOT_VERSION = 1;
1077
+ function ssrUrl(platformUrl, shopDomain) {
1078
+ const url = new URL("/api/storefront/ssr", platformUrl);
1079
+ url.searchParams.set("shop", shopDomain);
1080
+ return url.toString();
1081
+ }
1082
+ function sanitizeSsrPayload(json) {
1083
+ if (!json || typeof json !== "object") return null;
1084
+ const j = json;
1085
+ const doc = j.doc;
1086
+ if (!doc || typeof doc !== "object") return null;
1087
+ if (!doc.keys || typeof doc.keys !== "object" || !Array.isArray(doc.prefixes) || !Array.isArray(doc.exps)) return null;
1088
+ const snapshots = j.snapshots && typeof j.snapshots === "object" ? j.snapshots : {};
1089
+ return { doc, snapshots };
1090
+ }
1091
+ var ssrFetcher = createCachedJsonFetcher({ label: "ssr doc", sanitize: sanitizeSsrPayload });
1092
+ var HEALTHY2 = /* @__PURE__ */ new Set(["memory", "stale", "fetched"]);
1093
+ async function getSsrPayload(args) {
1094
+ try {
1095
+ const { value, source } = await ssrFetcher.getWithSource({
1096
+ url: ssrUrl(args.platformUrl, args.shopDomain),
1097
+ waitUntil: args.waitUntil,
1098
+ fetchImpl: args.fetchImpl
1099
+ });
1100
+ return value && HEALTHY2.has(source) ? value : null;
1101
+ } catch {
1102
+ return null;
1103
+ }
1104
+ }
1105
+ function fnv32a(s2) {
1106
+ let h = 2166136261;
1107
+ for (let i = 0; i < s2.length; i++) {
1108
+ h ^= s2.charCodeAt(i);
1109
+ h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);
1110
+ }
1111
+ return h >>> 0;
1112
+ }
1113
+ function bucketIndex(seed, id, weights) {
1114
+ const k = weights.length;
1115
+ if (!k) return -1;
1116
+ const n = fnv32a(String(fnv32a(seed + id))) % 1e4 / 1e4;
1117
+ const total = weights.reduce((a, b) => a + b, 0);
1118
+ const w = total < 0.99 || total > 1.01 ? weights.map(() => 1 / k) : weights;
1119
+ let cum = 0;
1120
+ for (let i = 0; i < k; i++) {
1121
+ const start = cum;
1122
+ cum += w[i];
1123
+ if (n >= start && n < start + w[i]) return i;
1124
+ }
1125
+ return -1;
1126
+ }
1127
+ function priorArmFromExposure(raw, experimentId, nowSec = Math.floor(Date.now() / 1e3)) {
1128
+ if (!raw) return null;
1129
+ let v = raw;
1130
+ if (v.includes("%")) {
1131
+ try {
1132
+ v = decodeURIComponent(v);
1133
+ } catch {
1134
+ }
1135
+ }
1136
+ v = v.slice(0, 4096);
1137
+ const RE = /^[A-Za-z0-9-]{1,64}$/;
1138
+ for (const part of v.split("_")) {
1139
+ const f = part.split(".");
1140
+ if (f.length !== 4 || f[0] !== experimentId || !RE.test(f[1])) continue;
1141
+ const s2 = parseInt(f[3], 36);
1142
+ if (Number.isFinite(s2) && nowSec - s2 <= EXPOSURE_TTL_DAYS * 86400) return f[1];
1143
+ }
1144
+ return null;
1145
+ }
1146
+ function experimentsForPage(doc, pageKey) {
1147
+ const out = new Set(doc.keys[pageKey] ?? []);
1148
+ for (const [prefix, idx] of doc.prefixes) if (pageKey.startsWith(prefix)) idx.forEach((i) => out.add(i));
1149
+ return [...out];
1150
+ }
1151
+ function decideSsr(input) {
1152
+ const { payload, pageKey, cookies, consent } = input;
1153
+ const idx = experimentsForPage(payload.doc, pageKey);
1154
+ if (idx.length === 0) return { skip: "no-test" };
1155
+ if (idx.length > 1) return { skip: "multi-test" };
1156
+ const exp = payload.doc.exps[idx[0]];
1157
+ if (!exp) return { skip: "no-test" };
1158
+ if (exp.ok !== 1) return { skip: `ineligible:${exp.why || "unknown"}` };
1159
+ if (exp.aud) return { skip: "audience" };
1160
+ if (!exp.settled && exp.hv !== 2 && exp.hv !== 3) return { skip: "hash-version" };
1161
+ const arms = exp.arms || [];
1162
+ let arm;
1163
+ let idSource = "roll";
1164
+ if (exp.settled) {
1165
+ arm = arms.find((a) => a.id === exp.settled);
1166
+ idSource = "settled";
1167
+ } else {
1168
+ const allowed = consent === "allowed";
1169
+ const prior = allowed ? priorArmFromExposure(cookies[EXPOSURE_COOKIE], exp.id, input.nowSec) : null;
1170
+ if (prior) {
1171
+ arm = arms.find((a) => a.id === prior && a.w > 0);
1172
+ if (arm) idSource = "prior";
1173
+ }
1174
+ if (!arm) {
1175
+ const vid = (allowed ? experienceVisitorIdFromCookies(cookies) : null) ?? input.fallbackVisitorId ?? null;
1176
+ if (!vid) return { skip: "no-visitor-id" };
1177
+ const i = bucketIndex(exp.seed, vid, arms.map((a) => a.w));
1178
+ arm = i >= 0 ? arms[i] : arms.find((a) => a.c === 1) ?? arms[0];
1179
+ }
1180
+ }
1181
+ if (!arm) return { skip: "no-arm" };
1182
+ const [t, h = ""] = pageKey.split(":");
1183
+ const snapshot = arm.x ? payload.snapshots[arm.x] ?? null : null;
1184
+ if (arm.x && (!snapshot || snapshot.v !== SSR_SNAPSHOT_VERSION || !snapshot.nodes?.length)) {
1185
+ return { skip: "no-snapshot" };
1186
+ }
1187
+ return { decision: { experimentId: exp.id, armId: arm.id, experienceId: arm.x, idSource, arm, snapshot, page: { t, h } } };
1188
+ }
1189
+ var BASE = ":host{all:initial}*,*::before,*::after{box-sizing:border-box}[data-pb-experience-root]{font-family:system-ui,-apple-system,sans-serif;color:#111827;display:flex;flex-direction:column}img,video{max-width:100%;display:block}";
1190
+ var HTML_BASE = ":host{display:block}*,*::before,*::after{box-sizing:border-box}";
1191
+ var escAttr = (s2) => s2.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1192
+ var escStyle = (s2) => s2.replace(/<\/(style)/gi, "<\\/$1");
1193
+ function ssrHostInnerHtml(snapshot, page) {
1194
+ const nodes = snapshot.nodes.map((nd) => {
1195
+ const style = [
1196
+ "display:block",
1197
+ "width:100%",
1198
+ typeof nd.mt === "number" ? `margin-top:${nd.mt}px` : "",
1199
+ typeof nd.mb === "number" ? `margin-bottom:${nd.mb}px` : ""
1200
+ ].filter(Boolean).join(";");
1201
+ return `<div data-proto-id="${escAttr(nd.id)}" data-proto-type="html" style="${style}"><template shadowrootmode="open"><style>${escStyle(HTML_BASE + "\n" + (nd.css || ""))}</style><div class="pb-html-root" data-pb-page-type="${escAttr(page.t === "home" ? "home" : page.t)}" data-pb-handle="${escAttr(page.h)}">${nd.html || ""}</div></template></div>`;
1202
+ }).join("");
1203
+ return `<template shadowrootmode="open"><style data-pb-ssr-snapshot>${BASE}</style><div data-pb-experience-root data-pb-ssr-snapshot>${nodes}</div></template>`;
1204
+ }
1205
+ function ssrStateScript(d) {
1206
+ const state = {
1207
+ experimentId: d.experimentId,
1208
+ armId: d.armId,
1209
+ experienceId: d.experienceId,
1210
+ placed: !!d.experienceId,
1211
+ reason: d.experienceId ? null : "control",
1212
+ idSource: d.idSource,
1213
+ placedAt: null,
1214
+ server: true
1215
+ };
1216
+ return `window.__pbSsr=${JSON.stringify(state).replace(/</g, "\\u003c")};`;
1217
+ }
1218
+ function slotMatches(d, slot) {
1219
+ const a = d.arm.a;
1220
+ if (!a) return false;
1221
+ return a.s.trim() === slot.anchor.trim() && a.p === (slot.position ?? "after");
1222
+ }
1223
+
801
1224
  // src/request-context.ts
802
1225
  var FINALIZE_WAIT_MS = 2e3;
803
1226
  var FINALIZE_REDIRECT_WAIT_MS = 0;
804
1227
  function str(v) {
805
1228
  return typeof v === "string" && v ? v : void 0;
806
1229
  }
1230
+ function normalizeDomain(raw) {
1231
+ return raw.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/[/?#].*$/, "");
1232
+ }
807
1233
  function createPlaybookContext({
808
1234
  request,
809
1235
  env,
@@ -813,7 +1239,11 @@ function createPlaybookContext({
813
1239
  disabled: disabledOption,
814
1240
  consentRequired = false,
815
1241
  consent,
816
- overrides,
1242
+ experienceAttribution = true,
1243
+ cloak: cloakOption = true,
1244
+ ssrSlots = [],
1245
+ shopDomain: shopDomainOption,
1246
+ apiBase: apiBaseOption,
817
1247
  fetchImpl
818
1248
  }) {
819
1249
  const e = env ?? {};
@@ -839,7 +1269,6 @@ function createPlaybookContext({
839
1269
  request,
840
1270
  waitUntil,
841
1271
  fetchImpl,
842
- overrides,
843
1272
  consentRequired,
844
1273
  consent
845
1274
  }).catch((error) => {
@@ -865,6 +1294,81 @@ function createPlaybookContext({
865
1294
  }
866
1295
  return (await promise)?.setCookieHeaders ?? [];
867
1296
  };
1297
+ const cartConsent = (cookies) => {
1298
+ const state = consent ? consent.fromRequest(request) : analyticsConsentFromCookie(cookies[TRACKING_CONSENT_COOKIE]);
1299
+ if (state === "granted" || state === "absent" && !consentRequired) {
1300
+ return "allowed";
1301
+ }
1302
+ return state === "denied" ? "denied" : "unknown";
1303
+ };
1304
+ const cartVisitorId = () => {
1305
+ if (!shopId) return null;
1306
+ try {
1307
+ const cookies = parseCookies(request.headers.get("cookie"));
1308
+ if (cartConsent(cookies) !== "allowed") return null;
1309
+ return [cookies[VISITOR_COOKIE], cookies[SESSION_VISITOR_COOKIE]].find(
1310
+ (v) => isValidVisitorId(v)
1311
+ ) ?? null;
1312
+ } catch {
1313
+ return null;
1314
+ }
1315
+ };
1316
+ let cloakPromise = null;
1317
+ const cloakFor = () => {
1318
+ if (!cloakPromise) {
1319
+ cloakPromise = (async () => {
1320
+ if (!shopId || !cloakOption || request.method !== "GET") return null;
1321
+ const url = new URL(request.url);
1322
+ if (url.pathname.endsWith(".data")) return null;
1323
+ if (hasOwnedPreviewParams(url.search)) return null;
1324
+ if (!targetPageKey(url.pathname)) return null;
1325
+ const shopDomain = normalizeDomain(
1326
+ shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? url.hostname
1327
+ );
1328
+ if (!shopDomain) return null;
1329
+ const { pages } = await getTargetedPages({
1330
+ platformUrl,
1331
+ shopDomain,
1332
+ waitUntil,
1333
+ fetchImpl
1334
+ });
1335
+ const targetedPage = matchTargetedPage(pages, url.pathname);
1336
+ if (!targetedPage) return null;
1337
+ return {
1338
+ targetedPage,
1339
+ shopDomain,
1340
+ apiBase: apiBaseOption || `${url.origin}/apps/playbook`
1341
+ };
1342
+ })().catch(() => null);
1343
+ }
1344
+ return cloakPromise;
1345
+ };
1346
+ let ssrRendered = false;
1347
+ let ssrPromise = null;
1348
+ const ssrFor = (cloak) => {
1349
+ if (!ssrPromise) {
1350
+ ssrPromise = (async () => {
1351
+ if (!cloak || ssrSlots.length === 0) return { ssr: null, skip: null };
1352
+ const payload = await getSsrPayload({ platformUrl, shopDomain: cloak.shopDomain, waitUntil, fetchImpl });
1353
+ if (!payload) return { ssr: null, skip: "doc-unavailable" };
1354
+ const cookies = parseCookies(request.headers.get("cookie"));
1355
+ const own = (await get())?.state?.visitorId ?? null;
1356
+ const out = decideSsr({
1357
+ payload,
1358
+ pageKey: cloak.targetedPage,
1359
+ cookies,
1360
+ consent: cartConsent(cookies),
1361
+ fallbackVisitorId: own
1362
+ });
1363
+ if ("skip" in out) return { ssr: null, skip: out.skip };
1364
+ const d = out.decision;
1365
+ if (d.experienceId && !ssrSlots.some((s2) => slotMatches(d, s2))) return { ssr: null, skip: "no-slot" };
1366
+ ssrRendered = true;
1367
+ return { ssr: d, skip: null };
1368
+ })().catch(() => ({ ssr: null, skip: "error" }));
1369
+ }
1370
+ return ssrPromise;
1371
+ };
868
1372
  const append = (headers, cookies) => {
869
1373
  for (const cookie of cookies) headers.append("Set-Cookie", cookie);
870
1374
  };
@@ -874,28 +1378,52 @@ function createPlaybookContext({
874
1378
  disabled: disabled || !configuredShop,
875
1379
  get,
876
1380
  async loaderData() {
877
- const result = await get();
1381
+ const [result, cloak] = await Promise.all([get(), cloakFor()]);
1382
+ const { ssr, skip } = await ssrFor(cloak);
878
1383
  return {
879
1384
  playbook: result?.state ?? null,
880
- hasPlaybookParams: hasPlaybookParams(request.url)
1385
+ hasPlaybookParams: hasPlaybookParams(request.url),
1386
+ targetedPage: cloak?.targetedPage ?? null,
1387
+ // A server-rendered arm needs no hide: its design is already in the HTML.
1388
+ cloak: ssr ? null : cloak,
1389
+ ssr,
1390
+ ssrSkip: ssr ? null : skip
881
1391
  };
882
1392
  },
883
1393
  cartAttribute() {
1394
+ const id = cartVisitorId();
1395
+ return id ? { key: CART_VISITOR_ATTRIBUTE, value: id } : null;
1396
+ },
1397
+ cartVisitorId,
1398
+ reconcileCartAttributes(current) {
884
1399
  if (!shopId) return null;
1400
+ let storeEdit = null;
885
1401
  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;
1402
+ storeEdit = reconcilePlaybookCartAttribute(current, cartVisitorId());
892
1403
  } catch {
893
1404
  return null;
894
1405
  }
1406
+ if (!experienceAttribution) return storeEdit;
1407
+ try {
1408
+ const cookies = parseCookies(request.headers.get("cookie"));
1409
+ const consentState = cartConsent(cookies);
1410
+ const experience = reconcileExperienceCartAttributes(
1411
+ storeEdit ?? current,
1412
+ {
1413
+ consent: consentState,
1414
+ exposureCookie: cookies[EXPOSURE_COOKIE],
1415
+ visitorId: consentState === "allowed" ? experienceVisitorIdFromCookies(cookies) : null
1416
+ }
1417
+ );
1418
+ return experience ?? storeEdit;
1419
+ } catch {
1420
+ return storeEdit;
1421
+ }
895
1422
  },
896
1423
  async appendCookies(headers) {
897
1424
  try {
898
1425
  append(headers, await cookiesFor(FINALIZE_WAIT_MS));
1426
+ if (ssrRendered) headers.set("Cache-Control", "private, no-store");
899
1427
  } catch {
900
1428
  }
901
1429
  },
@@ -905,13 +1433,15 @@ function createPlaybookContext({
905
1433
  const cookies = await cookiesFor(
906
1434
  isRedirect ? FINALIZE_REDIRECT_WAIT_MS : FINALIZE_WAIT_MS
907
1435
  );
908
- if (!cookies.length) return response;
1436
+ if (!cookies.length && !ssrRendered) return response;
909
1437
  try {
910
1438
  append(response.headers, cookies);
1439
+ if (ssrRendered) response.headers.set("Cache-Control", "private, no-store");
911
1440
  return response;
912
1441
  } catch {
913
1442
  const headers = new Headers(response.headers);
914
1443
  append(headers, cookies);
1444
+ if (ssrRendered) headers.set("Cache-Control", "private, no-store");
915
1445
  return new Response(response.body, {
916
1446
  status: response.status,
917
1447
  statusText: response.statusText,
@@ -1022,6 +1552,119 @@ function PlaybookHead({
1022
1552
  )
1023
1553
  ] });
1024
1554
  }
1555
+ var CLOAK_MAX_MS = 1500;
1556
+ var DEFAULT_EXPERIENCE_SDK_URL = "https://cdn.heyplaybook.com/experience-sdk.js";
1557
+ var CLOAK_STYLE_ID = "pb-cloak";
1558
+ var EXPERIENCE_SDK_SCRIPT_ID = "pb-experience-sdk";
1559
+ function jsLiteral(value) {
1560
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1561
+ }
1562
+ function safeSdkUrl(raw) {
1563
+ if (!raw) return DEFAULT_EXPERIENCE_SDK_URL;
1564
+ try {
1565
+ const u = new URL(raw);
1566
+ return u.protocol === "https:" && !u.username && !u.password ? u.toString() : DEFAULT_EXPERIENCE_SDK_URL;
1567
+ } catch {
1568
+ return DEFAULT_EXPERIENCE_SDK_URL;
1569
+ }
1570
+ }
1571
+ function clampHide(ms) {
1572
+ if (typeof ms !== "number" || !Number.isFinite(ms)) return CLOAK_MAX_MS;
1573
+ return Math.min(CLOAK_MAX_MS, Math.max(100, Math.round(ms)));
1574
+ }
1575
+ function buildHeadSnippet(cloak, options = {}) {
1576
+ if (!cloak || !cloak.targetedPage || !cloak.shopDomain || !cloak.apiBase) {
1577
+ return null;
1578
+ }
1579
+ const ms = clampHide(options.maxHideMs);
1580
+ const src = safeSdkUrl(options.sdkUrl);
1581
+ const css = `html:not(.pb-ready){opacity:0;animation:pb-uncloak 0s linear ${ms}ms forwards}@keyframes pb-uncloak{to{opacity:1}}`;
1582
+ 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 + ");})();";
1583
+ const attrs = {
1584
+ "data-pb-api-base": cloak.apiBase,
1585
+ "data-pb-shop": cloak.shopDomain,
1586
+ "data-pb-targeted": "1"
1587
+ };
1588
+ if (options.consentRequired) attrs["data-pb-consent"] = "required";
1589
+ return { css, script, sdk: { src, attrs }, nonce: options.nonce };
1590
+ }
1591
+ var PlaybookCloakHead = memo(
1592
+ function PlaybookCloakHead2({
1593
+ cloak,
1594
+ ...options
1595
+ }) {
1596
+ const parts = buildHeadSnippet(cloak, options);
1597
+ if (!parts) return null;
1598
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1599
+ /* @__PURE__ */ jsx(
1600
+ "style",
1601
+ {
1602
+ id: CLOAK_STYLE_ID,
1603
+ nonce: parts.nonce,
1604
+ dangerouslySetInnerHTML: { __html: parts.css }
1605
+ }
1606
+ ),
1607
+ /* @__PURE__ */ jsx(
1608
+ "script",
1609
+ {
1610
+ nonce: parts.nonce,
1611
+ dangerouslySetInnerHTML: { __html: parts.script }
1612
+ }
1613
+ ),
1614
+ /* @__PURE__ */ jsx(
1615
+ "script",
1616
+ {
1617
+ id: EXPERIENCE_SDK_SCRIPT_ID,
1618
+ src: parts.sdk.src,
1619
+ nonce: parts.nonce,
1620
+ async: true,
1621
+ ...parts.sdk.attrs
1622
+ }
1623
+ )
1624
+ ] });
1625
+ },
1626
+ () => true
1627
+ );
1628
+ function playbookHeadSnippet(cloak, options = {}) {
1629
+ if (!buildHeadSnippet(cloak, options)) return null;
1630
+ return /* @__PURE__ */ jsx(PlaybookCloakHead, { cloak, ...options });
1631
+ }
1632
+ function escapeAttr(value) {
1633
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1634
+ }
1635
+ function playbookHeadSnippetHtml(cloak, options = {}) {
1636
+ const parts = buildHeadSnippet(cloak, options);
1637
+ if (!parts) return "";
1638
+ const nonce = parts.nonce ? ` nonce="${escapeAttr(parts.nonce)}"` : "";
1639
+ const attrs = Object.entries(parts.sdk.attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
1640
+ 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>`;
1641
+ }
1642
+ function PlaybookSsrHead({ ssr, nonce }) {
1643
+ if (!ssr) return null;
1644
+ const hide = ssr.experienceId ? (ssr.arm.hide || []).map((s2) => `${s2}{display:none!important}`).join("") : "";
1645
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1646
+ /* @__PURE__ */ jsx("script", { nonce, "data-pb-ssr-state": "", dangerouslySetInnerHTML: { __html: ssrStateScript(ssr) } }),
1647
+ hide ? /* @__PURE__ */ jsx("style", { id: "pb-ssr-hide", nonce, dangerouslySetInnerHTML: { __html: escStyle(hide) } }) : null
1648
+ ] });
1649
+ }
1650
+ function PlaybookSlot({
1651
+ ssr,
1652
+ anchor,
1653
+ position = "after"
1654
+ }) {
1655
+ if (!ssr || !ssr.experienceId || !ssr.snapshot || !slotMatches(ssr, { anchor, position })) return null;
1656
+ return /* @__PURE__ */ jsx(
1657
+ "div",
1658
+ {
1659
+ id: "pb-experience-root",
1660
+ "data-pb-experience-mount": "",
1661
+ "data-pb-ssr": ssr.experimentId,
1662
+ style: { display: "block", boxSizing: "border-box", maxWidth: "100%" },
1663
+ suppressHydrationWarning: true,
1664
+ dangerouslySetInnerHTML: { __html: ssrHostInnerHtml(ssr.snapshot, ssr.page) }
1665
+ }
1666
+ );
1667
+ }
1025
1668
  var PlaybookBoundary = class extends Component {
1026
1669
  state = { failed: false };
1027
1670
  static getDerivedStateFromError() {
@@ -1258,7 +1901,7 @@ var config = {
1258
1901
  eventUrl: "/apps/playbook/api/storefront/tests/event",
1259
1902
  supportedEvents: new Set(DEFAULT_SUPPORTED_EVENTS),
1260
1903
  store: {},
1261
- dataLayer: {}
1904
+ dataLayer: false
1262
1905
  };
1263
1906
  var seenOnPage = /* @__PURE__ */ new Set();
1264
1907
  function configureTracker(next) {
@@ -1448,7 +2091,8 @@ function body(s2, testKey, arm, extra) {
1448
2091
  }
1449
2092
  function pushExposureToDataLayer(s2, testKey, arm) {
1450
2093
  const option = config.dataLayer;
1451
- if (option === false) return;
2094
+ if (!option) return;
2095
+ const eventName = option !== true && option.eventName || DEFAULT_DATALAYER_EVENT;
1452
2096
  try {
1453
2097
  const dl = window.dataLayer;
1454
2098
  if (!Array.isArray(dl) && typeof dl?.push !== "function") {
@@ -1459,7 +2103,7 @@ function pushExposureToDataLayer(s2, testKey, arm) {
1459
2103
  const cfg = assignment?.config ?? {};
1460
2104
  const str2 = (v) => typeof v === "string" && v ? v.slice(0, 100) : null;
1461
2105
  dl.push({
1462
- event: option.eventName || DEFAULT_DATALAYER_EVENT,
2106
+ event: eventName,
1463
2107
  experiment_id: testKey,
1464
2108
  // The ruleset carries no display names yet; an explicit
1465
2109
  // `config.experimentName` wins, else the key (never a variant's copy).
@@ -1572,7 +2216,8 @@ var PlaybookContext = createContext({
1572
2216
  pathname: "/",
1573
2217
  exposureUrl: DEFAULT_EXPOSURE_URL,
1574
2218
  eventUrl: DEFAULT_EVENT_URL,
1575
- consent: "pending"
2219
+ consent: "pending",
2220
+ previewIgnoresTargeting: false
1576
2221
  });
1577
2222
  function usePlaybookConsent() {
1578
2223
  return useContext(PlaybookContext).consent;
@@ -1591,10 +2236,13 @@ var CONTROL = {
1591
2236
  config: {}
1592
2237
  };
1593
2238
  function usePlaybookVariant(testKey, { eligible = true } = {}) {
1594
- const { state, pathname } = useContext(PlaybookContext);
2239
+ const { state, pathname, previewIgnoresTargeting } = useContext(PlaybookContext);
1595
2240
  const a = state?.enabled ? state.tests[testKey] : void 0;
1596
2241
  return useMemo(() => {
1597
2242
  if (!a) return CONTROL;
2243
+ if (a.forced && previewIgnoresTargeting) {
2244
+ return { arm: a.arm, inTest: false, forced: true, config: a.config };
2245
+ }
1598
2246
  if (!eligible || !matchesPathPrefix(pathname, a.pathPrefix)) {
1599
2247
  return { ...CONTROL, config: a.config };
1600
2248
  }
@@ -1602,7 +2250,7 @@ function usePlaybookVariant(testKey, { eligible = true } = {}) {
1602
2250
  return { arm: a.arm, inTest: false, forced: true, config: a.config };
1603
2251
  }
1604
2252
  return { arm: a.arm, inTest: a.inTest, forced: false, config: a.config };
1605
- }, [a, eligible, pathname]);
2253
+ }, [a, eligible, pathname, previewIgnoresTargeting]);
1606
2254
  }
1607
2255
  function usePlaybookInteraction(testKey, variant) {
1608
2256
  return useCallback(
@@ -1682,13 +2330,19 @@ var SERVER_REASONS = {
1682
2330
  coverage: "out of coverage",
1683
2331
  winner: "completed: winner served",
1684
2332
  preview: "forced: preview link",
1685
- "preview-isolated": "another test is being previewed",
1686
- override: "forced: override"
2333
+ "preview-isolated": "another test is being previewed"
1687
2334
  };
1688
- function whyNotInTest(key, a, pathname, implementedTests) {
2335
+ function whyNotInTest(key, a, pathname, implementedTests, explain) {
1689
2336
  if (implementedTests && !implementedTests.has(key)) {
1690
2337
  return "no code on this storefront";
1691
2338
  }
2339
+ if (explain) {
2340
+ try {
2341
+ const custom = explain(key, a, pathname);
2342
+ if (typeof custom === "string" && custom) return custom;
2343
+ } catch {
2344
+ }
2345
+ }
1692
2346
  if (a.forced) return SERVER_REASONS[a.reason] ?? "forced";
1693
2347
  if (!a.inTest) {
1694
2348
  if (a.reason === "not-running") return a.status;
@@ -1739,7 +2393,8 @@ function PlaybookDebugPanel({
1739
2393
  state,
1740
2394
  location,
1741
2395
  allowed,
1742
- implementedTests
2396
+ implementedTests,
2397
+ explain
1743
2398
  }) {
1744
2399
  const { pathname, search = "" } = location;
1745
2400
  const param = new URLSearchParams(search).get(FLAG);
@@ -1815,7 +2470,7 @@ function PlaybookDebugPanel({
1815
2470
  ] }),
1816
2471
  !tests.length && /* @__PURE__ */ jsx("p", { style: s.p, children: "No tests in the ruleset." }),
1817
2472
  /* @__PURE__ */ jsx("ul", { style: s.list, children: tests.map(([key, a]) => {
1818
- const why = whyNotInTest(key, a, pathname, implemented);
2473
+ const why = whyNotInTest(key, a, pathname, implemented, explain);
1819
2474
  const exposed = !!vid && hasSentExposure(vid, key);
1820
2475
  return /* @__PURE__ */ jsxs("li", { style: s.card, children: [
1821
2476
  /* @__PURE__ */ jsx("p", { style: { ...s.p, fontWeight: 600 }, children: key }),
@@ -1922,6 +2577,142 @@ function usePageEngagement(pathname, enabled) {
1922
2577
  };
1923
2578
  }, [pathname, enabled]);
1924
2579
  }
2580
+
2581
+ // src/consent-adapters.ts
2582
+ function consentFromAnalytics(value) {
2583
+ if (value === true || value === "granted" || value === "yes") {
2584
+ return "granted";
2585
+ }
2586
+ if (value === false || value === "denied" || value === "no") return "denied";
2587
+ return "pending";
2588
+ }
2589
+ var shopifyCustomerPrivacyConsent = {
2590
+ id: "shopify-customer-privacy",
2591
+ read() {
2592
+ if (typeof window === "undefined") return "pending";
2593
+ try {
2594
+ return getConsentState();
2595
+ } catch {
2596
+ return "pending";
2597
+ }
2598
+ },
2599
+ subscribe(onChange) {
2600
+ if (typeof window === "undefined") return () => {
2601
+ };
2602
+ let live = true;
2603
+ const notify = () => {
2604
+ if (live) onChange();
2605
+ };
2606
+ waitForConsentAPI().then(notify, notify);
2607
+ const offLoaded = onConsentLoaded(notify);
2608
+ const offChange = onConsentChange(notify);
2609
+ return () => {
2610
+ live = false;
2611
+ offLoaded();
2612
+ offChange();
2613
+ };
2614
+ }
2615
+ };
2616
+ var TRUEVAULT_CONSENT_COOKIE = "polaris_consent_settings";
2617
+ var TRUEVAULT_CONSENT_EVENT = "consentChanged";
2618
+ var POLL_INTERVAL_MS = 500;
2619
+ var POLL_CHECKS = 20;
2620
+ function trueVaultDecision(raw, gpc, { whenMissing = "pending", gpc: gpcMode = "follow-banner" } = {}) {
2621
+ if (gpc && gpcMode === "deny") return "denied";
2622
+ if (raw === null || raw === void 0 || raw === "") return whenMissing;
2623
+ let data = null;
2624
+ for (const candidate of [raw, safeDecode(raw)]) {
2625
+ if (candidate === null) continue;
2626
+ try {
2627
+ data = JSON.parse(candidate);
2628
+ break;
2629
+ } catch {
2630
+ }
2631
+ }
2632
+ const permitted = data?.analyticsPermitted;
2633
+ if (permitted === true) return "granted";
2634
+ if (permitted === false) return "denied";
2635
+ return "pending";
2636
+ }
2637
+ function safeDecode(raw) {
2638
+ try {
2639
+ return decodeURIComponent(raw);
2640
+ } catch {
2641
+ return null;
2642
+ }
2643
+ }
2644
+ function readDocumentCookie(name) {
2645
+ try {
2646
+ const match = document.cookie.match(
2647
+ new RegExp(`(?:^|; )${name}=([^;]*)`)
2648
+ );
2649
+ return match ? match[1] : null;
2650
+ } catch {
2651
+ return null;
2652
+ }
2653
+ }
2654
+ function clientGpc() {
2655
+ try {
2656
+ return navigator.globalPrivacyControl === true;
2657
+ } catch {
2658
+ return false;
2659
+ }
2660
+ }
2661
+ function createTrueVaultConsent(options = {}) {
2662
+ return {
2663
+ id: "truevault",
2664
+ fromRequest(request) {
2665
+ try {
2666
+ const cookies = parseCookies(request.headers.get("cookie"));
2667
+ const gpc = request.headers.get("sec-gpc") === "1";
2668
+ return trueVaultDecision(
2669
+ cookies[TRUEVAULT_CONSENT_COOKIE],
2670
+ gpc,
2671
+ options
2672
+ );
2673
+ } catch {
2674
+ return "pending";
2675
+ }
2676
+ },
2677
+ read() {
2678
+ if (typeof document === "undefined") return "pending";
2679
+ return trueVaultDecision(
2680
+ readDocumentCookie(TRUEVAULT_CONSENT_COOKIE),
2681
+ clientGpc(),
2682
+ options
2683
+ );
2684
+ },
2685
+ subscribe(onChange) {
2686
+ if (typeof window === "undefined") return () => {
2687
+ };
2688
+ const handler = () => setTimeout(onChange, 0);
2689
+ const onVisible = () => {
2690
+ if (document.visibilityState === "visible") onChange();
2691
+ };
2692
+ window.addEventListener(TRUEVAULT_CONSENT_EVENT, handler);
2693
+ document.addEventListener("visibilitychange", onVisible);
2694
+ let poll = null;
2695
+ if (readDocumentCookie(TRUEVAULT_CONSENT_COOKIE) === null) {
2696
+ let checks = 0;
2697
+ poll = setInterval(() => {
2698
+ checks += 1;
2699
+ const present = readDocumentCookie(TRUEVAULT_CONSENT_COOKIE) !== null;
2700
+ if (present || checks >= POLL_CHECKS) {
2701
+ if (poll) clearInterval(poll);
2702
+ poll = null;
2703
+ if (present) onChange();
2704
+ }
2705
+ }, POLL_INTERVAL_MS);
2706
+ }
2707
+ return () => {
2708
+ window.removeEventListener(TRUEVAULT_CONSENT_EVENT, handler);
2709
+ document.removeEventListener("visibilitychange", onVisible);
2710
+ if (poll) clearInterval(poll);
2711
+ };
2712
+ }
2713
+ };
2714
+ }
2715
+ var truevaultConsent = createTrueVaultConsent();
1925
2716
  function PlaybookProvider({
1926
2717
  state,
1927
2718
  pathname,
@@ -1930,33 +2721,31 @@ function PlaybookProvider({
1930
2721
  supportedEvents = DEFAULT_SUPPORTED_EVENTS,
1931
2722
  storeContext,
1932
2723
  consent: consentAdapter,
1933
- dataLayer = {},
2724
+ dataLayer = false,
2725
+ previewIgnoresTargeting = false,
1934
2726
  children
1935
2727
  }) {
1936
2728
  const [consent, setConsent] = useState("pending");
1937
2729
  const consentRequired = !!state?.consentRequired;
1938
2730
  useEffect(() => {
1939
2731
  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
- };
2732
+ const source = consentAdapter ?? shopifyCustomerPrivacyConsent;
2733
+ if (!consentAdapter && consentRequired) declareConsentRequired();
2734
+ const update = () => {
2735
+ if (!live) return;
2736
+ try {
2737
+ setConsent(source.read());
2738
+ } catch {
2739
+ setConsent("pending");
2740
+ }
2741
+ };
2742
+ update();
2743
+ let unsubscribe = () => {
2744
+ };
2745
+ try {
2746
+ unsubscribe = source.subscribe(update);
2747
+ } catch {
1955
2748
  }
1956
- if (consentRequired) declareConsentRequired();
1957
- const update = () => live && setConsent(getConsentState());
1958
- waitForConsentAPI().then(update);
1959
- const unsubscribe = onConsentChange(update);
1960
2749
  return () => {
1961
2750
  live = false;
1962
2751
  unsubscribe();
@@ -1982,8 +2771,15 @@ function PlaybookProvider({
1982
2771
  }
1983
2772
  }
1984
2773
  const value = useMemo(
1985
- () => ({ state: state ?? null, pathname, exposureUrl, eventUrl, consent }),
1986
- [state, pathname, exposureUrl, eventUrl, consent]
2774
+ () => ({
2775
+ state: state ?? null,
2776
+ pathname,
2777
+ exposureUrl,
2778
+ eventUrl,
2779
+ consent,
2780
+ previewIgnoresTargeting
2781
+ }),
2782
+ [state, pathname, exposureUrl, eventUrl, consent, previewIgnoresTargeting]
1987
2783
  );
1988
2784
  return /* @__PURE__ */ jsx(PlaybookContext.Provider, { value, children });
1989
2785
  }
@@ -2104,6 +2900,7 @@ function PlaybookRoot({
2104
2900
  aaSentinel = true,
2105
2901
  debug,
2106
2902
  dataLayer,
2903
+ previewIgnoresTargeting,
2107
2904
  onCartSyncEvent,
2108
2905
  exposureUrl,
2109
2906
  eventUrl,
@@ -2120,6 +2917,7 @@ function PlaybookRoot({
2120
2917
  storeContext,
2121
2918
  consent,
2122
2919
  dataLayer,
2920
+ previewIgnoresTargeting,
2123
2921
  exposureUrl,
2124
2922
  eventUrl,
2125
2923
  supportedEvents,
@@ -2143,7 +2941,8 @@ function PlaybookRoot({
2143
2941
  state,
2144
2942
  location,
2145
2943
  allowed: debug?.allowed,
2146
- implementedTests: debug?.implementedTests
2944
+ implementedTests: debug?.implementedTests,
2945
+ explain: debug?.explain
2147
2946
  }
2148
2947
  ) })
2149
2948
  ] })
@@ -2265,108 +3064,6 @@ function createPlaybookProxyHandler({
2265
3064
  return { loader: proxy, action: proxy };
2266
3065
  }
2267
3066
 
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
3067
  // src/cart-events.ts
2371
3068
  var nextSource = null;
2372
3069
  function setNextAddSource(source) {
@@ -2438,4 +3135,4 @@ function trackAddToCartLines(lines, cartLines, source) {
2438
3135
  }
2439
3136
  }
2440
3137
 
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 };
3138
+ 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, PlaybookSlot, PlaybookSsrHead, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, TRUEVAULT_CONSENT_COOKIE, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, assignTest, bucketIndex, buildHeadSnippet, cartHasPlaybookAttribute, chooseVariation, consentFromAnalytics, createCartAttributeReader, createCartAttributeSync, createCartAttributeWriter, createPlaybook, createPlaybookContext, createPlaybookProxyHandler, createTrueVaultConsent, debugPanelAllowed, decideSsr, declareConsentRequired, detectDevice, detectGeo, experienceVisitorIdFromCookies, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getSsrPayload, 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, slotMatches, ssrHostInnerHtml, ssrUrl, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };