@heyplaybook/hydrogen 0.2.1 → 0.3.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/README.md +172 -2
- package/dist/index.d.ts +475 -45
- package/dist/index.js +1212 -119
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
|
|
2
|
+
import { createContext, Component, useContext, useMemo, useCallback, useState, useEffect, useSyncExternalStore, useRef } from 'react';
|
|
3
3
|
|
|
4
4
|
// src/growthbook.ts
|
|
5
|
-
function hashFnv32a(
|
|
5
|
+
function hashFnv32a(str2) {
|
|
6
6
|
let hval = 2166136261;
|
|
7
|
-
const l =
|
|
7
|
+
const l = str2.length;
|
|
8
8
|
for (let i = 0; i < l; i++) {
|
|
9
|
-
hval ^=
|
|
9
|
+
hval ^= str2.charCodeAt(i);
|
|
10
10
|
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
|
|
11
11
|
}
|
|
12
12
|
return hval >>> 0;
|
|
@@ -419,12 +419,50 @@ function rulesUrl(platformUrl, shopId) {
|
|
|
419
419
|
url.searchParams.set("shop", shopId);
|
|
420
420
|
return url.toString();
|
|
421
421
|
}
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
422
|
+
var STATUSES = /* @__PURE__ */ new Set(["running", "paused", "completed"]);
|
|
423
|
+
var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
424
|
+
var isNum = (v) => typeof v === "number" && Number.isFinite(v);
|
|
425
|
+
var optional = (v, check) => v === void 0 || v === null || check(v);
|
|
426
|
+
function isValidRule(t) {
|
|
427
|
+
if (!isObj(t)) return false;
|
|
428
|
+
if (typeof t.key !== "string" || !t.key || t.key.length > 64) return false;
|
|
429
|
+
if (typeof t.status !== "string" || !STATUSES.has(t.status)) return false;
|
|
430
|
+
if (!Array.isArray(t.arms) || !t.arms.every(
|
|
431
|
+
(a) => isObj(a) && typeof a.key === "string" && !!a.key && isNum(a.weight) && a.weight >= 0
|
|
432
|
+
)) {
|
|
433
|
+
return false;
|
|
434
|
+
}
|
|
435
|
+
if (!optional(t.seed, (v) => typeof v === "string")) return false;
|
|
436
|
+
if (!optional(t.hashVersion, isNum)) return false;
|
|
437
|
+
if (!optional(t.coverage, (v) => isNum(v) && v >= 0 && v <= 1)) return false;
|
|
438
|
+
if (!optional(t.winner, (v) => typeof v === "string")) return false;
|
|
439
|
+
if (!optional(t.config, isObj)) return false;
|
|
440
|
+
if (!optional(
|
|
441
|
+
t.namespace,
|
|
442
|
+
(v) => isObj(v) && typeof v.id === "string" && Array.isArray(v.range) && v.range.length === 2 && v.range.every(isNum)
|
|
443
|
+
)) {
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
return optional(
|
|
447
|
+
t.targeting,
|
|
448
|
+
(v) => isObj(v) && optional(
|
|
449
|
+
v.pathPrefix,
|
|
450
|
+
(p) => Array.isArray(p) && p.every((s2) => typeof s2 === "string")
|
|
451
|
+
) && optional(v.device, (d) => d === "mobile" || d === "desktop") && optional(v.visitorType, (d) => d === "new" || d === "returning")
|
|
426
452
|
);
|
|
427
453
|
}
|
|
454
|
+
function sanitizeRuleset(value) {
|
|
455
|
+
if (!isObj(value) || !Array.isArray(value.tests)) return null;
|
|
456
|
+
if (typeof value.version !== "string") return null;
|
|
457
|
+
const tests = value.tests.filter(isValidRule);
|
|
458
|
+
if (tests.length !== value.tests.length) {
|
|
459
|
+
console.warn(
|
|
460
|
+
"[playbook] dropped invalid rules",
|
|
461
|
+
value.tests.length - tests.length
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
return { ...value, tests };
|
|
465
|
+
}
|
|
428
466
|
function inBackoff(entry, now) {
|
|
429
467
|
return entry.failedAt > 0 && now - entry.failedAt < FAILURE_BACKOFF_MS;
|
|
430
468
|
}
|
|
@@ -437,8 +475,8 @@ function refresh(key, url, entry, fetchImpl) {
|
|
|
437
475
|
signal: controller.signal
|
|
438
476
|
}).then(async (res) => {
|
|
439
477
|
if (!res.ok) throw new Error(`ruleset ${res.status}`);
|
|
440
|
-
const json = await res.json();
|
|
441
|
-
if (!
|
|
478
|
+
const json = sanitizeRuleset(await res.json());
|
|
479
|
+
if (!json) throw new Error("ruleset malformed");
|
|
442
480
|
entry.ruleset = json;
|
|
443
481
|
entry.fetchedAt = Date.now();
|
|
444
482
|
entry.failedAt = 0;
|
|
@@ -542,7 +580,8 @@ async function createPlaybook({
|
|
|
542
580
|
waitUntil,
|
|
543
581
|
fetchImpl,
|
|
544
582
|
overrides,
|
|
545
|
-
consentRequired = false
|
|
583
|
+
consentRequired = false,
|
|
584
|
+
consent: consentAdapter
|
|
546
585
|
}) {
|
|
547
586
|
const url = new URL(request.url);
|
|
548
587
|
const device = detectDevice(request.headers.get("user-agent"));
|
|
@@ -576,7 +615,7 @@ async function createPlaybook({
|
|
|
576
615
|
const domain = cookieDomainFor(url.hostname);
|
|
577
616
|
const secure = url.protocol === "https:";
|
|
578
617
|
const setCookieHeaders = [];
|
|
579
|
-
let consent = analyticsConsentFromCookie(cookies[TRACKING_CONSENT_COOKIE]);
|
|
618
|
+
let consent = consentAdapter ? consentAdapter.fromRequest(request) : analyticsConsentFromCookie(cookies[TRACKING_CONSENT_COOKIE]);
|
|
580
619
|
if (consent === "absent" && consentRequired) consent = "pending";
|
|
581
620
|
const persistentAllowed = consent === "granted" || consent === "absent";
|
|
582
621
|
const existing = [
|
|
@@ -618,7 +657,7 @@ async function createPlaybook({
|
|
|
618
657
|
})
|
|
619
658
|
);
|
|
620
659
|
}
|
|
621
|
-
if (cookies[VISITOR_COOKIE]) {
|
|
660
|
+
if (consent === "denied" && cookies[VISITOR_COOKIE]) {
|
|
622
661
|
setCookieHeaders.push(
|
|
623
662
|
serializeCookie(VISITOR_COOKIE, "", { maxAge: 0, secure })
|
|
624
663
|
);
|
|
@@ -729,6 +768,454 @@ async function createPlaybook({
|
|
|
729
768
|
};
|
|
730
769
|
}
|
|
731
770
|
|
|
771
|
+
// src/cart.ts
|
|
772
|
+
var CART_VISITOR_ATTRIBUTE = "_pb_vid";
|
|
773
|
+
function playbookCartAttribute(visitorId) {
|
|
774
|
+
return { key: CART_VISITOR_ATTRIBUTE, value: visitorId };
|
|
775
|
+
}
|
|
776
|
+
function cartHasPlaybookAttribute(attributes, visitorId) {
|
|
777
|
+
return !!attributes?.some(
|
|
778
|
+
(a) => a.key === CART_VISITOR_ATTRIBUTE && a.value === visitorId
|
|
779
|
+
);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// src/env.ts
|
|
783
|
+
function hasPlaybookParams(url) {
|
|
784
|
+
let search;
|
|
785
|
+
try {
|
|
786
|
+
search = (typeof url === "string" ? new URL(url) : url).search;
|
|
787
|
+
} catch {
|
|
788
|
+
return false;
|
|
789
|
+
}
|
|
790
|
+
return search.includes("_pv=") || search.includes("pbk=") || search.includes("pb_mode=brand_preview") || search.includes("_preview=true");
|
|
791
|
+
}
|
|
792
|
+
function isKillSwitchOn(value) {
|
|
793
|
+
const v = (value ?? "").trim().toLowerCase();
|
|
794
|
+
return v === "1" || v === "true" || v === "yes" || v === "on";
|
|
795
|
+
}
|
|
796
|
+
function isPreviewHost(hostname) {
|
|
797
|
+
const h = hostname.toLowerCase();
|
|
798
|
+
return h === "localhost" || h === "127.0.0.1" || /\.myshopify\.(dev|com)$/.test(h) || /\.shopifypreview\.com$/.test(h) || /\.workers\.dev$/.test(h);
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// src/request-context.ts
|
|
802
|
+
var FINALIZE_WAIT_MS = 2e3;
|
|
803
|
+
var FINALIZE_REDIRECT_WAIT_MS = 0;
|
|
804
|
+
function str(v) {
|
|
805
|
+
return typeof v === "string" && v ? v : void 0;
|
|
806
|
+
}
|
|
807
|
+
function createPlaybookContext({
|
|
808
|
+
request,
|
|
809
|
+
env,
|
|
810
|
+
waitUntil,
|
|
811
|
+
shopId: shopIdOption,
|
|
812
|
+
platformUrl: platformUrlOption,
|
|
813
|
+
disabled: disabledOption,
|
|
814
|
+
consentRequired = false,
|
|
815
|
+
consent,
|
|
816
|
+
overrides,
|
|
817
|
+
fetchImpl
|
|
818
|
+
}) {
|
|
819
|
+
const e = env ?? {};
|
|
820
|
+
const disabled = disabledOption ?? isKillSwitchOn(str(e.PLAYBOOK_TESTS_DISABLED));
|
|
821
|
+
const configuredShop = shopIdOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_ID) ?? null;
|
|
822
|
+
const shopId = disabled ? null : configuredShop;
|
|
823
|
+
const platformUrl = platformUrlOption || str(e.PLAYBOOK_PLATFORM_URL) || DEFAULT_PLATFORM_URL;
|
|
824
|
+
let promise = null;
|
|
825
|
+
let settled = false;
|
|
826
|
+
if (shopId && request.method === "GET") {
|
|
827
|
+
try {
|
|
828
|
+
prefetchRuleset({ platformUrl, shopId, waitUntil, fetchImpl });
|
|
829
|
+
} catch {
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
const get = () => {
|
|
833
|
+
if (!promise) {
|
|
834
|
+
promise = createPlaybook({
|
|
835
|
+
// Kill switch → shopId null → createPlaybook's disabled path:
|
|
836
|
+
// everyone control, no cookies, `enabled: false` on the client.
|
|
837
|
+
shopId,
|
|
838
|
+
platformUrl,
|
|
839
|
+
request,
|
|
840
|
+
waitUntil,
|
|
841
|
+
fetchImpl,
|
|
842
|
+
overrides,
|
|
843
|
+
consentRequired,
|
|
844
|
+
consent
|
|
845
|
+
}).catch((error) => {
|
|
846
|
+
console.error("[playbook] createPlaybook failed", String(error));
|
|
847
|
+
return null;
|
|
848
|
+
}).finally(() => {
|
|
849
|
+
settled = true;
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
return promise;
|
|
853
|
+
};
|
|
854
|
+
const cookiesFor = async (waitMs) => {
|
|
855
|
+
if (!promise) return [];
|
|
856
|
+
if (!settled) {
|
|
857
|
+
let timer;
|
|
858
|
+
const timeout = new Promise((resolve) => {
|
|
859
|
+
timer = setTimeout(() => resolve("timeout"), waitMs);
|
|
860
|
+
});
|
|
861
|
+
const winner = await Promise.race([promise, timeout]);
|
|
862
|
+
clearTimeout(timer);
|
|
863
|
+
if (winner === "timeout") return [];
|
|
864
|
+
return winner?.setCookieHeaders ?? [];
|
|
865
|
+
}
|
|
866
|
+
return (await promise)?.setCookieHeaders ?? [];
|
|
867
|
+
};
|
|
868
|
+
const append = (headers, cookies) => {
|
|
869
|
+
for (const cookie of cookies) headers.append("Set-Cookie", cookie);
|
|
870
|
+
};
|
|
871
|
+
return {
|
|
872
|
+
shopId,
|
|
873
|
+
platformUrl,
|
|
874
|
+
disabled: disabled || !configuredShop,
|
|
875
|
+
get,
|
|
876
|
+
async loaderData() {
|
|
877
|
+
const result = await get();
|
|
878
|
+
return {
|
|
879
|
+
playbook: result?.state ?? null,
|
|
880
|
+
hasPlaybookParams: hasPlaybookParams(request.url)
|
|
881
|
+
};
|
|
882
|
+
},
|
|
883
|
+
cartAttribute() {
|
|
884
|
+
if (!shopId) return null;
|
|
885
|
+
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;
|
|
892
|
+
} catch {
|
|
893
|
+
return null;
|
|
894
|
+
}
|
|
895
|
+
},
|
|
896
|
+
async appendCookies(headers) {
|
|
897
|
+
try {
|
|
898
|
+
append(headers, await cookiesFor(FINALIZE_WAIT_MS));
|
|
899
|
+
} catch {
|
|
900
|
+
}
|
|
901
|
+
},
|
|
902
|
+
async finalize(response) {
|
|
903
|
+
try {
|
|
904
|
+
const isRedirect = response.status >= 300 && response.status < 400;
|
|
905
|
+
const cookies = await cookiesFor(
|
|
906
|
+
isRedirect ? FINALIZE_REDIRECT_WAIT_MS : FINALIZE_WAIT_MS
|
|
907
|
+
);
|
|
908
|
+
if (!cookies.length) return response;
|
|
909
|
+
try {
|
|
910
|
+
append(response.headers, cookies);
|
|
911
|
+
return response;
|
|
912
|
+
} catch {
|
|
913
|
+
const headers = new Headers(response.headers);
|
|
914
|
+
append(headers, cookies);
|
|
915
|
+
return new Response(response.body, {
|
|
916
|
+
status: response.status,
|
|
917
|
+
statusText: response.statusText,
|
|
918
|
+
headers
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
} catch {
|
|
922
|
+
return response;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
async function withPlaybook(options, handler) {
|
|
928
|
+
const playbook = createPlaybookContext(options);
|
|
929
|
+
return playbook.finalize(await handler(playbook));
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
// src/visitor-sync.ts
|
|
933
|
+
function writeCookie(value, days) {
|
|
934
|
+
try {
|
|
935
|
+
const expires = new Date(Date.now() + days * 864e5).toUTCString();
|
|
936
|
+
const secure = window.location.protocol === "https:" ? ";Secure" : "";
|
|
937
|
+
document.cookie = `${VISITOR_COOKIE}=${value};expires=${expires};path=/;SameSite=Lax${secure}`;
|
|
938
|
+
} catch {
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
function readCookie() {
|
|
942
|
+
try {
|
|
943
|
+
const parts = `; ${document.cookie}`.split(`; ${VISITOR_COOKIE}=`);
|
|
944
|
+
return parts.length === 2 ? parts.pop()?.split(";").shift() ?? null : null;
|
|
945
|
+
} catch {
|
|
946
|
+
return null;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
function syncVisitorId(visitorId, consent) {
|
|
950
|
+
try {
|
|
951
|
+
window.sessionStorage.setItem(VISITOR_COOKIE, visitorId);
|
|
952
|
+
} catch {
|
|
953
|
+
}
|
|
954
|
+
if (consent === "granted" || consent === "absent") {
|
|
955
|
+
if (readCookie() !== visitorId) writeCookie(visitorId, 365);
|
|
956
|
+
} else if (consent === "denied" && readCookie() !== null) {
|
|
957
|
+
writeCookie("", -1);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
function visitorSeedScript(visitorId) {
|
|
961
|
+
if (!isValidVisitorId(visitorId ?? void 0)) return "";
|
|
962
|
+
return `try{sessionStorage.setItem(${JSON.stringify(VISITOR_COOKIE)},${JSON.stringify(visitorId)})}catch(e){}`;
|
|
963
|
+
}
|
|
964
|
+
var DEFAULT_SDK_URL = "https://cdn.heyplaybook.com/playbook.js";
|
|
965
|
+
var DEFAULT_PROXY_ENDPOINT = "/apps/playbook";
|
|
966
|
+
var ANTI_FLICKER_CSS = "html:not(.pb-ready){opacity:0!important}html.pb-ready{opacity:1!important;transition:opacity 0.3s ease-in!important}";
|
|
967
|
+
function revealScript(hasPlaybookParams2) {
|
|
968
|
+
return `
|
|
969
|
+
(function(){
|
|
970
|
+
function reveal() {
|
|
971
|
+
document.documentElement.classList.add('pb-ready');
|
|
972
|
+
if (window.__pbFlickerTimeout) {
|
|
973
|
+
clearTimeout(window.__pbFlickerTimeout);
|
|
974
|
+
window.__pbFlickerTimeout = null;
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
${hasPlaybookParams2 ? "window.__pbFlickerTimeout = setTimeout(reveal, 3000);" : ""}
|
|
979
|
+
|
|
980
|
+
window.Playbook = window.Playbook || {};
|
|
981
|
+
window.Playbook.pageReady = reveal;
|
|
982
|
+
})();
|
|
983
|
+
`;
|
|
984
|
+
}
|
|
985
|
+
function PlaybookHead({
|
|
986
|
+
shopId,
|
|
987
|
+
apiEndpoint = DEFAULT_PROXY_ENDPOINT,
|
|
988
|
+
sdkUrl = DEFAULT_SDK_URL,
|
|
989
|
+
hasPlaybookParams: hasPlaybookParams2 = false,
|
|
990
|
+
state,
|
|
991
|
+
visitorId,
|
|
992
|
+
nonce
|
|
993
|
+
}) {
|
|
994
|
+
if (!shopId) return null;
|
|
995
|
+
const id = visitorId !== void 0 ? visitorId : state?.enabled ? state.visitorId : null;
|
|
996
|
+
const seed = visitorSeedScript(id);
|
|
997
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
998
|
+
hasPlaybookParams2 && /* @__PURE__ */ jsx(
|
|
999
|
+
"style",
|
|
1000
|
+
{
|
|
1001
|
+
id: "pb-anti-flicker",
|
|
1002
|
+
nonce,
|
|
1003
|
+
dangerouslySetInnerHTML: { __html: ANTI_FLICKER_CSS }
|
|
1004
|
+
}
|
|
1005
|
+
),
|
|
1006
|
+
/* @__PURE__ */ jsx(
|
|
1007
|
+
"script",
|
|
1008
|
+
{
|
|
1009
|
+
nonce,
|
|
1010
|
+
dangerouslySetInnerHTML: { __html: revealScript(hasPlaybookParams2) }
|
|
1011
|
+
}
|
|
1012
|
+
),
|
|
1013
|
+
seed && /* @__PURE__ */ jsx("script", { nonce, dangerouslySetInnerHTML: { __html: seed } }),
|
|
1014
|
+
/* @__PURE__ */ jsx(
|
|
1015
|
+
"script",
|
|
1016
|
+
{
|
|
1017
|
+
src: sdkUrl,
|
|
1018
|
+
nonce,
|
|
1019
|
+
"data-pb-config": JSON.stringify({ shopId, apiEndpoint }),
|
|
1020
|
+
async: true
|
|
1021
|
+
}
|
|
1022
|
+
)
|
|
1023
|
+
] });
|
|
1024
|
+
}
|
|
1025
|
+
var PlaybookBoundary = class extends Component {
|
|
1026
|
+
state = { failed: false };
|
|
1027
|
+
static getDerivedStateFromError() {
|
|
1028
|
+
return { failed: true };
|
|
1029
|
+
}
|
|
1030
|
+
componentDidCatch(error) {
|
|
1031
|
+
try {
|
|
1032
|
+
console.warn(`[playbook] ${this.props.name} disabled`, String(error));
|
|
1033
|
+
} catch {
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
render() {
|
|
1037
|
+
return this.state.failed ? null : this.props.children ?? null;
|
|
1038
|
+
}
|
|
1039
|
+
};
|
|
1040
|
+
|
|
1041
|
+
// src/cart-sync.ts
|
|
1042
|
+
function mergeAttributes(current, add) {
|
|
1043
|
+
const map = /* @__PURE__ */ new Map();
|
|
1044
|
+
for (const a of current ?? []) {
|
|
1045
|
+
if (a?.key) map.set(a.key, a.value ?? "");
|
|
1046
|
+
}
|
|
1047
|
+
for (const a of add) {
|
|
1048
|
+
if (!a.value) map.delete(a.key);
|
|
1049
|
+
else map.set(a.key, a.value);
|
|
1050
|
+
}
|
|
1051
|
+
return [...map].map(([key, value]) => ({ key, value }));
|
|
1052
|
+
}
|
|
1053
|
+
var WRITE_TIMEOUT_MS = 8e3;
|
|
1054
|
+
async function withTimeout(fetchImpl, url, init) {
|
|
1055
|
+
const controller = new AbortController();
|
|
1056
|
+
const timer = setTimeout(() => controller.abort(), WRITE_TIMEOUT_MS);
|
|
1057
|
+
try {
|
|
1058
|
+
return await fetchImpl(url, { ...init, signal: controller.signal });
|
|
1059
|
+
} finally {
|
|
1060
|
+
clearTimeout(timer);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
function attributesFrom(data) {
|
|
1064
|
+
const attrs = data?.cart?.attributes;
|
|
1065
|
+
return Array.isArray(attrs) ? attrs : null;
|
|
1066
|
+
}
|
|
1067
|
+
function createCartAttributeWriter({
|
|
1068
|
+
endpoint = "/api/cart",
|
|
1069
|
+
serverMerges = false,
|
|
1070
|
+
fetchImpl
|
|
1071
|
+
} = {}) {
|
|
1072
|
+
return async (add, current) => {
|
|
1073
|
+
try {
|
|
1074
|
+
const list = serverMerges ? add.map((a) => ({ key: a.key, value: a.value ?? "" })) : mergeAttributes(current, add);
|
|
1075
|
+
const form = new FormData();
|
|
1076
|
+
form.append("action", "AttributesUpdateInput");
|
|
1077
|
+
form.append("attributes", JSON.stringify(list));
|
|
1078
|
+
form.append(
|
|
1079
|
+
"cartFormInput",
|
|
1080
|
+
JSON.stringify({
|
|
1081
|
+
action: "AttributesUpdateInput",
|
|
1082
|
+
inputs: { attributes: list }
|
|
1083
|
+
})
|
|
1084
|
+
);
|
|
1085
|
+
const res = await withTimeout(fetchImpl ?? fetch, endpoint, {
|
|
1086
|
+
method: "POST",
|
|
1087
|
+
body: form,
|
|
1088
|
+
headers: { accept: "application/json" }
|
|
1089
|
+
});
|
|
1090
|
+
if (!res.ok) return { ok: false };
|
|
1091
|
+
let data = null;
|
|
1092
|
+
try {
|
|
1093
|
+
data = await res.json();
|
|
1094
|
+
} catch {
|
|
1095
|
+
return { ok: true, attributes: null };
|
|
1096
|
+
}
|
|
1097
|
+
const d = data;
|
|
1098
|
+
const failed = !!(d?.userErrors?.length || d?.errors?.length);
|
|
1099
|
+
return { ok: !failed, attributes: attributesFrom(data) };
|
|
1100
|
+
} catch {
|
|
1101
|
+
return { ok: false };
|
|
1102
|
+
}
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
function createCartAttributeReader({
|
|
1106
|
+
endpoint = "/api/cart",
|
|
1107
|
+
fetchImpl
|
|
1108
|
+
} = {}) {
|
|
1109
|
+
return async () => {
|
|
1110
|
+
try {
|
|
1111
|
+
const res = await withTimeout(fetchImpl ?? fetch, endpoint, {
|
|
1112
|
+
headers: { accept: "application/json" }
|
|
1113
|
+
});
|
|
1114
|
+
if (!res.ok) return null;
|
|
1115
|
+
return attributesFrom(await res.json());
|
|
1116
|
+
} catch {
|
|
1117
|
+
return null;
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
var CART_SYNC_IDLE_MS = 3e3;
|
|
1122
|
+
var MAX_WRITES_PER_CART = 3;
|
|
1123
|
+
function createCartAttributeSync({
|
|
1124
|
+
write,
|
|
1125
|
+
read,
|
|
1126
|
+
maxWritesPerCart = MAX_WRITES_PER_CART,
|
|
1127
|
+
idleMs = CART_SYNC_IDLE_MS,
|
|
1128
|
+
protectedKeyPrefixes = ["_ig"],
|
|
1129
|
+
onEvent
|
|
1130
|
+
}) {
|
|
1131
|
+
let counted = {
|
|
1132
|
+
cartId: null,
|
|
1133
|
+
count: 0
|
|
1134
|
+
};
|
|
1135
|
+
let inFlight = false;
|
|
1136
|
+
let timer = null;
|
|
1137
|
+
let disposed = false;
|
|
1138
|
+
const emit = (e) => {
|
|
1139
|
+
try {
|
|
1140
|
+
onEvent?.(e);
|
|
1141
|
+
} catch {
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
const isProtected = (key) => protectedKeyPrefixes.some((p) => key.startsWith(p));
|
|
1145
|
+
const cancel = () => {
|
|
1146
|
+
if (timer) clearTimeout(timer);
|
|
1147
|
+
timer = null;
|
|
1148
|
+
};
|
|
1149
|
+
async function run(s2) {
|
|
1150
|
+
if (disposed || inFlight) return;
|
|
1151
|
+
if (counted.cartId !== s2.cartId) counted = { cartId: s2.cartId, count: 0 };
|
|
1152
|
+
if (counted.count >= maxWritesPerCart) {
|
|
1153
|
+
emit({ type: "capped", cartId: s2.cartId });
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
counted.count += 1;
|
|
1157
|
+
inFlight = true;
|
|
1158
|
+
try {
|
|
1159
|
+
const before = (s2.attributes ?? []).filter(
|
|
1160
|
+
(a) => a?.key && isProtected(a.key) && a.value
|
|
1161
|
+
);
|
|
1162
|
+
const attribute = { key: CART_VISITOR_ATTRIBUTE, value: s2.visitorId };
|
|
1163
|
+
const result = await write([attribute], s2.attributes);
|
|
1164
|
+
emit({ type: "written", cartId: s2.cartId, ok: result.ok });
|
|
1165
|
+
if (!before.length) return;
|
|
1166
|
+
const after = result.attributes ?? (read ? await read() : null) ?? null;
|
|
1167
|
+
if (!after) return;
|
|
1168
|
+
const present = new Set(after.map((a) => a.key));
|
|
1169
|
+
const lost = before.filter((a) => !present.has(a.key));
|
|
1170
|
+
if (!lost.length) return;
|
|
1171
|
+
const restored = await write(lost, after);
|
|
1172
|
+
emit({
|
|
1173
|
+
type: "restored",
|
|
1174
|
+
cartId: s2.cartId,
|
|
1175
|
+
keys: lost.map((a) => a.key),
|
|
1176
|
+
ok: restored.ok
|
|
1177
|
+
});
|
|
1178
|
+
} catch {
|
|
1179
|
+
} finally {
|
|
1180
|
+
inFlight = false;
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
return {
|
|
1184
|
+
update(s2) {
|
|
1185
|
+
cancel();
|
|
1186
|
+
if (disposed || !s2.eligible || !s2.cartId || !s2.visitorId) return;
|
|
1187
|
+
if (s2.status && s2.status !== "idle") return;
|
|
1188
|
+
if (cartHasPlaybookAttribute(s2.attributes, s2.visitorId)) return;
|
|
1189
|
+
if (inFlight) return;
|
|
1190
|
+
if (counted.cartId === s2.cartId && counted.count >= maxWritesPerCart) {
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
const ready = { ...s2, cartId: s2.cartId, visitorId: s2.visitorId };
|
|
1194
|
+
emit({ type: "scheduled", cartId: s2.cartId });
|
|
1195
|
+
timer = setTimeout(() => {
|
|
1196
|
+
timer = null;
|
|
1197
|
+
void run(ready);
|
|
1198
|
+
}, idleMs);
|
|
1199
|
+
},
|
|
1200
|
+
dispose() {
|
|
1201
|
+
disposed = true;
|
|
1202
|
+
cancel();
|
|
1203
|
+
},
|
|
1204
|
+
/** Test/debug: writes made for the current cart. */
|
|
1205
|
+
writesForCart(cartId) {
|
|
1206
|
+
return counted.cartId === cartId ? counted.count : 0;
|
|
1207
|
+
}
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
function withPlaybookCartAttribute(input, attribute) {
|
|
1211
|
+
const base = input ?? {};
|
|
1212
|
+
if (!attribute?.value) return base;
|
|
1213
|
+
return {
|
|
1214
|
+
...base,
|
|
1215
|
+
attributes: mergeAttributes(base.attributes, [attribute])
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
|
|
732
1219
|
// src/tracker.ts
|
|
733
1220
|
var ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
734
1221
|
var KEY_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
@@ -762,6 +1249,7 @@ function cleanProps(props) {
|
|
|
762
1249
|
}
|
|
763
1250
|
return out;
|
|
764
1251
|
}
|
|
1252
|
+
var DEFAULT_DATALAYER_EVENT = "view_experiment";
|
|
765
1253
|
var config = {
|
|
766
1254
|
state: null,
|
|
767
1255
|
consent: "pending",
|
|
@@ -769,7 +1257,8 @@ var config = {
|
|
|
769
1257
|
exposureUrl: "/apps/playbook/api/storefront/tests/exposure",
|
|
770
1258
|
eventUrl: "/apps/playbook/api/storefront/tests/event",
|
|
771
1259
|
supportedEvents: new Set(DEFAULT_SUPPORTED_EVENTS),
|
|
772
|
-
store: {}
|
|
1260
|
+
store: {},
|
|
1261
|
+
dataLayer: {}
|
|
773
1262
|
};
|
|
774
1263
|
var seenOnPage = /* @__PURE__ */ new Set();
|
|
775
1264
|
function configureTracker(next) {
|
|
@@ -877,12 +1366,12 @@ function viewportBucket(width) {
|
|
|
877
1366
|
return "xl";
|
|
878
1367
|
}
|
|
879
1368
|
function exposureContext() {
|
|
880
|
-
const
|
|
1369
|
+
const s2 = config.state;
|
|
881
1370
|
const session = getSessionContext();
|
|
882
1371
|
const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
|
|
883
1372
|
return {
|
|
884
|
-
country:
|
|
885
|
-
region:
|
|
1373
|
+
country: s2?.geo?.country ?? null,
|
|
1374
|
+
region: s2?.geo?.region ?? null,
|
|
886
1375
|
market: config.store.market ?? null,
|
|
887
1376
|
locale: config.store.locale ?? null,
|
|
888
1377
|
utm: session?.utm ?? {},
|
|
@@ -938,16 +1427,16 @@ function post(url, body2, { beacon = false } = {}) {
|
|
|
938
1427
|
});
|
|
939
1428
|
}
|
|
940
1429
|
function baseValid(testKey, arm) {
|
|
941
|
-
const
|
|
942
|
-
if (!
|
|
943
|
-
if (!ID_RE.test(
|
|
1430
|
+
const s2 = config.state;
|
|
1431
|
+
if (!s2?.enabled || !s2.visitorId || !s2.shopId) return null;
|
|
1432
|
+
if (!ID_RE.test(s2.shopId) || !ID_RE.test(s2.visitorId)) return null;
|
|
944
1433
|
if (!KEY_RE.test(testKey) || !KEY_RE.test(arm)) return null;
|
|
945
|
-
return
|
|
1434
|
+
return s2;
|
|
946
1435
|
}
|
|
947
|
-
function body(
|
|
1436
|
+
function body(s2, testKey, arm, extra) {
|
|
948
1437
|
const json = JSON.stringify({
|
|
949
|
-
shopId:
|
|
950
|
-
visitorId:
|
|
1438
|
+
shopId: s2.shopId,
|
|
1439
|
+
visitorId: s2.visitorId,
|
|
951
1440
|
testKey,
|
|
952
1441
|
arm,
|
|
953
1442
|
...extra,
|
|
@@ -957,13 +1446,40 @@ function body(s, testKey, arm, extra) {
|
|
|
957
1446
|
});
|
|
958
1447
|
return json.length <= MAX_BODY_BYTES ? json : null;
|
|
959
1448
|
}
|
|
1449
|
+
function pushExposureToDataLayer(s2, testKey, arm) {
|
|
1450
|
+
const option = config.dataLayer;
|
|
1451
|
+
if (option === false) return;
|
|
1452
|
+
try {
|
|
1453
|
+
const dl = window.dataLayer;
|
|
1454
|
+
if (!Array.isArray(dl) && typeof dl?.push !== "function") {
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
const assignment = s2.tests[testKey];
|
|
1458
|
+
if (!assignment?.inTest || assignment.forced) return;
|
|
1459
|
+
const cfg = assignment?.config ?? {};
|
|
1460
|
+
const str2 = (v) => typeof v === "string" && v ? v.slice(0, 100) : null;
|
|
1461
|
+
dl.push({
|
|
1462
|
+
event: option.eventName || DEFAULT_DATALAYER_EVENT,
|
|
1463
|
+
experiment_id: testKey,
|
|
1464
|
+
// The ruleset carries no display names yet; an explicit
|
|
1465
|
+
// `config.experimentName` wins, else the key (never a variant's copy).
|
|
1466
|
+
experiment_name: str2(cfg.experimentName) ?? testKey,
|
|
1467
|
+
variant_id: arm,
|
|
1468
|
+
variant_name: arm,
|
|
1469
|
+
experiment_variant: arm,
|
|
1470
|
+
pb_vid: s2.visitorId
|
|
1471
|
+
});
|
|
1472
|
+
} catch {
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
960
1475
|
function sendExposure(testKey, arm) {
|
|
961
|
-
const
|
|
962
|
-
if (!
|
|
963
|
-
if (!claimOnce(exposureKey(
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
1476
|
+
const s2 = baseValid(testKey, arm);
|
|
1477
|
+
if (!s2 || !analyticsAllowed()) return;
|
|
1478
|
+
if (!claimOnce(exposureKey(s2.visitorId, testKey), arm)) return;
|
|
1479
|
+
pushExposureToDataLayer(s2, testKey, arm);
|
|
1480
|
+
const json = body(s2, testKey, arm, {
|
|
1481
|
+
device: s2.device,
|
|
1482
|
+
visitorType: s2.visitorType,
|
|
967
1483
|
context: exposureContext()
|
|
968
1484
|
});
|
|
969
1485
|
if (json) post(config.exposureUrl, json);
|
|
@@ -977,15 +1493,15 @@ function sendExposure(testKey, arm) {
|
|
|
977
1493
|
});
|
|
978
1494
|
}
|
|
979
1495
|
function testsFor(scope) {
|
|
980
|
-
const
|
|
981
|
-
if (!
|
|
1496
|
+
const s2 = config.state;
|
|
1497
|
+
if (!s2?.enabled || !s2.visitorId) return [];
|
|
982
1498
|
const out = [];
|
|
983
|
-
for (const [key, a] of Object.entries(
|
|
1499
|
+
for (const [key, a] of Object.entries(s2.tests)) {
|
|
984
1500
|
if (!a.inTest || a.forced) continue;
|
|
985
1501
|
if (typeof scope === "object") {
|
|
986
1502
|
if (scope.testKeys.includes(key)) out.push([key, a.arm]);
|
|
987
1503
|
} else if (scope === "visitor") {
|
|
988
|
-
if (hasSentExposure(
|
|
1504
|
+
if (hasSentExposure(s2.visitorId, key)) out.push([key, a.arm]);
|
|
989
1505
|
} else if (
|
|
990
1506
|
// Tested page type only: the test targets a pathPrefix that matches
|
|
991
1507
|
// this page, and its slot was on screen during this page view.
|
|
@@ -1006,8 +1522,8 @@ function playbookTrack(event, rawProps = {}, scope = "visitor", { oncePerSession
|
|
|
1006
1522
|
if (!targets.length) return 0;
|
|
1007
1523
|
const allowed = analyticsAllowed();
|
|
1008
1524
|
for (const [testKey, arm] of targets) {
|
|
1009
|
-
const
|
|
1010
|
-
if (!
|
|
1525
|
+
const s2 = baseValid(testKey, arm);
|
|
1526
|
+
if (!s2) continue;
|
|
1011
1527
|
const entry = {
|
|
1012
1528
|
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1013
1529
|
kind: "event",
|
|
@@ -1021,7 +1537,7 @@ function playbookTrack(event, rawProps = {}, scope = "visitor", { oncePerSession
|
|
|
1021
1537
|
record(entry);
|
|
1022
1538
|
continue;
|
|
1023
1539
|
}
|
|
1024
|
-
if (oncePerSession && !claimOnce(`pb_evt:${
|
|
1540
|
+
if (oncePerSession && !claimOnce(`pb_evt:${s2.visitorId}:${testKey}:${oncePerSession}`, arm)) {
|
|
1025
1541
|
continue;
|
|
1026
1542
|
}
|
|
1027
1543
|
let wire = {
|
|
@@ -1037,7 +1553,7 @@ function playbookTrack(event, rawProps = {}, scope = "visitor", { oncePerSession
|
|
|
1037
1553
|
continue;
|
|
1038
1554
|
}
|
|
1039
1555
|
const json = body(
|
|
1040
|
-
|
|
1556
|
+
s2,
|
|
1041
1557
|
testKey,
|
|
1042
1558
|
arm,
|
|
1043
1559
|
Object.keys(wire.props).length ? wire : { event: wire.event }
|
|
@@ -1142,89 +1658,200 @@ function usePreviewParamRedirect(location) {
|
|
|
1142
1658
|
params.set("pb_preview", token);
|
|
1143
1659
|
return `${location.pathname}?${params.toString()}${location.hash}`;
|
|
1144
1660
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
function writeCookie(value, days) {
|
|
1661
|
+
var FLAG = "pb_debug";
|
|
1662
|
+
function readFlag() {
|
|
1148
1663
|
try {
|
|
1149
|
-
|
|
1150
|
-
const secure = window.location.protocol === "https:" ? ";Secure" : "";
|
|
1151
|
-
document.cookie = `${VISITOR_COOKIE}=${value};expires=${expires};path=/;SameSite=Lax${secure}`;
|
|
1664
|
+
return window.sessionStorage.getItem(FLAG) === "1";
|
|
1152
1665
|
} catch {
|
|
1666
|
+
return false;
|
|
1153
1667
|
}
|
|
1154
1668
|
}
|
|
1155
|
-
function
|
|
1669
|
+
function writeFlag(on) {
|
|
1156
1670
|
try {
|
|
1157
|
-
|
|
1158
|
-
return parts.length === 2 ? parts.pop()?.split(";").shift() ?? null : null;
|
|
1671
|
+
window.sessionStorage.setItem(FLAG, on ? "1" : "0");
|
|
1159
1672
|
} catch {
|
|
1160
|
-
return null;
|
|
1161
1673
|
}
|
|
1162
1674
|
}
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1675
|
+
var SERVER_REASONS = {
|
|
1676
|
+
"not-running": "not running",
|
|
1677
|
+
"no-visitor": "no visitor id",
|
|
1678
|
+
"targeting-device": "targeting: device",
|
|
1679
|
+
"targeting-visitor-type": "targeting: new vs returning",
|
|
1680
|
+
namespace: "out of namespace",
|
|
1681
|
+
"hash-error": "hash error",
|
|
1682
|
+
coverage: "out of coverage",
|
|
1683
|
+
winner: "completed: winner served",
|
|
1684
|
+
preview: "forced: preview link",
|
|
1685
|
+
"preview-isolated": "another test is being previewed",
|
|
1686
|
+
override: "forced: override"
|
|
1687
|
+
};
|
|
1688
|
+
function whyNotInTest(key, a, pathname, implementedTests) {
|
|
1689
|
+
if (implementedTests && !implementedTests.has(key)) {
|
|
1690
|
+
return "no code on this storefront";
|
|
1167
1691
|
}
|
|
1168
|
-
if (
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1692
|
+
if (a.forced) return SERVER_REASONS[a.reason] ?? "forced";
|
|
1693
|
+
if (!a.inTest) {
|
|
1694
|
+
if (a.reason === "not-running") return a.status;
|
|
1695
|
+
return SERVER_REASONS[a.reason] ?? a.reason;
|
|
1172
1696
|
}
|
|
1697
|
+
if (!matchesPathPrefix(pathname, a.pathPrefix)) return "targeting: path";
|
|
1698
|
+
return null;
|
|
1173
1699
|
}
|
|
1174
|
-
function
|
|
1175
|
-
|
|
1700
|
+
function debugPanelAllowed(state, hostname, allowed) {
|
|
1701
|
+
if (allowed !== void 0) return allowed;
|
|
1702
|
+
return isPreviewHost(hostname) || !!state?.previewToken;
|
|
1703
|
+
}
|
|
1704
|
+
var s = {
|
|
1705
|
+
panel: {
|
|
1706
|
+
position: "fixed",
|
|
1707
|
+
bottom: 16,
|
|
1708
|
+
left: 16,
|
|
1709
|
+
zIndex: 2147483e3,
|
|
1710
|
+
maxHeight: "70vh",
|
|
1711
|
+
width: "min(380px, calc(100vw - 2rem))",
|
|
1712
|
+
overflowY: "auto",
|
|
1713
|
+
borderRadius: 12,
|
|
1714
|
+
background: "#fff",
|
|
1715
|
+
color: "#111",
|
|
1716
|
+
padding: 12,
|
|
1717
|
+
font: "12px/1.45 ui-sans-serif, system-ui, -apple-system, sans-serif",
|
|
1718
|
+
boxShadow: "0 8px 30px rgba(0,0,0,0.18)"
|
|
1719
|
+
},
|
|
1720
|
+
row: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 8 },
|
|
1721
|
+
title: { fontWeight: 600, margin: 0 },
|
|
1722
|
+
close: { width: 24, height: 24, border: 0, borderRadius: 999, background: "#f2f2f2", cursor: "pointer", fontSize: 14, lineHeight: 1 },
|
|
1723
|
+
card: { background: "#f6f6f6", borderRadius: 8, padding: 8, marginBottom: 8 },
|
|
1724
|
+
muted: { color: "#666", margin: 0 },
|
|
1725
|
+
p: { margin: 0 },
|
|
1726
|
+
grid: { display: "grid", gridTemplateColumns: "auto 1fr", columnGap: 12, rowGap: 4, margin: 0 },
|
|
1727
|
+
dd: { margin: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
|
|
1728
|
+
btn: { border: 0, borderRadius: 4, background: "#fff", padding: "2px 6px", cursor: "pointer", fontWeight: 500 },
|
|
1729
|
+
list: { listStyle: "none", margin: 0, padding: 0 }
|
|
1730
|
+
};
|
|
1731
|
+
function copyText(text) {
|
|
1732
|
+
if (navigator.clipboard?.writeText) {
|
|
1733
|
+
navigator.clipboard.writeText(text).catch(() => window.prompt("", text));
|
|
1734
|
+
} else {
|
|
1735
|
+
window.prompt("", text);
|
|
1736
|
+
}
|
|
1176
1737
|
}
|
|
1177
|
-
function
|
|
1738
|
+
function PlaybookDebugPanel({
|
|
1178
1739
|
state,
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
supportedEvents = DEFAULT_SUPPORTED_EVENTS,
|
|
1183
|
-
storeContext,
|
|
1184
|
-
children
|
|
1740
|
+
location,
|
|
1741
|
+
allowed,
|
|
1742
|
+
implementedTests
|
|
1185
1743
|
}) {
|
|
1186
|
-
const
|
|
1187
|
-
const
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
live = false;
|
|
1196
|
-
unsubscribe();
|
|
1197
|
-
};
|
|
1198
|
-
}, [consentRequired]);
|
|
1199
|
-
const visitorId = state?.enabled ? state.visitorId : null;
|
|
1200
|
-
useEffect(() => {
|
|
1201
|
-
if (visitorId) syncVisitorId(visitorId, consent);
|
|
1202
|
-
}, [visitorId, consent]);
|
|
1203
|
-
if (typeof window !== "undefined") {
|
|
1204
|
-
configureTracker({
|
|
1205
|
-
state: state ?? null,
|
|
1206
|
-
consent,
|
|
1207
|
-
pathname,
|
|
1208
|
-
exposureUrl,
|
|
1209
|
-
eventUrl,
|
|
1210
|
-
supportedEvents: new Set(supportedEvents),
|
|
1211
|
-
store: storeContext ?? {}
|
|
1212
|
-
});
|
|
1213
|
-
}
|
|
1214
|
-
const value = useMemo(
|
|
1215
|
-
() => ({ state: state ?? null, pathname, exposureUrl, eventUrl, consent }),
|
|
1216
|
-
[state, pathname, exposureUrl, eventUrl, consent]
|
|
1744
|
+
const { pathname, search = "" } = location;
|
|
1745
|
+
const param = new URLSearchParams(search).get(FLAG);
|
|
1746
|
+
const [stored, setStored] = useState(readFlag);
|
|
1747
|
+
const [copied, setCopied] = useState(false);
|
|
1748
|
+
const consent = usePlaybookConsent();
|
|
1749
|
+
const tracked = useSyncExternalStore(
|
|
1750
|
+
subscribeTrackedLog,
|
|
1751
|
+
getTrackedLog,
|
|
1752
|
+
getServerTrackedLog
|
|
1217
1753
|
);
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1754
|
+
const permitted = debugPanelAllowed(state, window.location.hostname, allowed);
|
|
1755
|
+
const open = permitted && (param === "1" ? true : param === "0" ? false : stored);
|
|
1756
|
+
useEffect(() => {
|
|
1757
|
+
if (permitted && (param === "1" || param === "0")) writeFlag(param === "1");
|
|
1758
|
+
}, [param, permitted]);
|
|
1759
|
+
if (!open) return null;
|
|
1760
|
+
const close = () => {
|
|
1761
|
+
writeFlag(false);
|
|
1762
|
+
setStored(false);
|
|
1763
|
+
if (param === "1") {
|
|
1764
|
+
try {
|
|
1765
|
+
const url = new URL(window.location.href);
|
|
1766
|
+
url.searchParams.set(FLAG, "0");
|
|
1767
|
+
window.history.replaceState(window.history.state, "", url);
|
|
1768
|
+
} catch {
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
};
|
|
1772
|
+
const implemented = implementedTests ? new Set(implementedTests) : void 0;
|
|
1773
|
+
const tests = Object.entries(state?.tests ?? {});
|
|
1774
|
+
const vid = state?.visitorId;
|
|
1775
|
+
return /* @__PURE__ */ jsxs("aside", { "aria-label": "Playbook tests debug", style: s.panel, children: [
|
|
1776
|
+
/* @__PURE__ */ jsxs("div", { style: s.row, children: [
|
|
1777
|
+
/* @__PURE__ */ jsx("p", { style: s.title, children: "Playbook tests" }),
|
|
1778
|
+
/* @__PURE__ */ jsx("button", { type: "button", "aria-label": "Close debug panel", style: s.close, onClick: close, children: "\xD7" })
|
|
1779
|
+
] }),
|
|
1780
|
+
!state?.enabled ? /* @__PURE__ */ jsx("p", { style: s.p, children: "Disabled: no shop id, or PLAYBOOK_TESTS_DISABLED is on." }) : /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
1781
|
+
/* @__PURE__ */ jsxs("dl", { style: { ...s.grid, ...s.card }, children: [
|
|
1782
|
+
/* @__PURE__ */ jsx("dt", { style: s.muted, children: "Visitor" }),
|
|
1783
|
+
/* @__PURE__ */ jsxs("dd", { style: { ...s.dd, display: "flex", gap: 8, alignItems: "center" }, children: [
|
|
1784
|
+
/* @__PURE__ */ jsx("code", { style: { overflow: "hidden", textOverflow: "ellipsis" }, children: vid ?? "none (preview)" }),
|
|
1785
|
+
vid && /* @__PURE__ */ jsx(
|
|
1786
|
+
"button",
|
|
1787
|
+
{
|
|
1788
|
+
type: "button",
|
|
1789
|
+
style: s.btn,
|
|
1790
|
+
onClick: () => {
|
|
1791
|
+
copyText(vid);
|
|
1792
|
+
setCopied(true);
|
|
1793
|
+
setTimeout(() => setCopied(false), 1500);
|
|
1794
|
+
},
|
|
1795
|
+
children: copied ? "Copied" : "Copy"
|
|
1796
|
+
}
|
|
1797
|
+
)
|
|
1798
|
+
] }),
|
|
1799
|
+
/* @__PURE__ */ jsx("dt", { style: s.muted, children: "Type" }),
|
|
1800
|
+
/* @__PURE__ */ jsxs("dd", { style: s.dd, children: [
|
|
1801
|
+
state.visitorType,
|
|
1802
|
+
" \xB7 ",
|
|
1803
|
+
state.device
|
|
1804
|
+
] }),
|
|
1805
|
+
/* @__PURE__ */ jsx("dt", { style: s.muted, children: "Analytics" }),
|
|
1806
|
+
/* @__PURE__ */ jsxs("dd", { style: s.dd, children: [
|
|
1807
|
+
consent === "absent" ? "API absent" : consent,
|
|
1808
|
+
" (server: ",
|
|
1809
|
+
state.serverConsent,
|
|
1810
|
+
")",
|
|
1811
|
+
consent === "denied" || consent === "pending" ? " \xB7 no beacons" : ""
|
|
1812
|
+
] }),
|
|
1813
|
+
/* @__PURE__ */ jsx("dt", { style: s.muted, children: "Ruleset" }),
|
|
1814
|
+
/* @__PURE__ */ jsx("dd", { style: s.dd, children: state.rulesetSource === "cold-fallback" ? "cold fallback (everyone gets control)" : `${state.rulesetVersion ?? "none"} \xB7 ${state.rulesetSource}` })
|
|
1815
|
+
] }),
|
|
1816
|
+
!tests.length && /* @__PURE__ */ jsx("p", { style: s.p, children: "No tests in the ruleset." }),
|
|
1817
|
+
/* @__PURE__ */ jsx("ul", { style: s.list, children: tests.map(([key, a]) => {
|
|
1818
|
+
const why = whyNotInTest(key, a, pathname, implemented);
|
|
1819
|
+
const exposed = !!vid && hasSentExposure(vid, key);
|
|
1820
|
+
return /* @__PURE__ */ jsxs("li", { style: s.card, children: [
|
|
1821
|
+
/* @__PURE__ */ jsx("p", { style: { ...s.p, fontWeight: 600 }, children: key }),
|
|
1822
|
+
/* @__PURE__ */ jsxs("p", { style: s.p, children: [
|
|
1823
|
+
a.status,
|
|
1824
|
+
" \xB7 arm ",
|
|
1825
|
+
/* @__PURE__ */ jsx("strong", { children: a.arm }),
|
|
1826
|
+
" \xB7 inTest ",
|
|
1827
|
+
String(a.inTest && !why),
|
|
1828
|
+
" \xB7 forced",
|
|
1829
|
+
" ",
|
|
1830
|
+
String(a.forced)
|
|
1831
|
+
] }),
|
|
1832
|
+
why && /* @__PURE__ */ jsxs("p", { style: s.muted, children: [
|
|
1833
|
+
"Why: ",
|
|
1834
|
+
why
|
|
1835
|
+
] }),
|
|
1836
|
+
/* @__PURE__ */ jsxs("p", { style: s.muted, children: [
|
|
1837
|
+
"Exposure this session: ",
|
|
1838
|
+
exposed ? "sent" : "not sent"
|
|
1839
|
+
] })
|
|
1840
|
+
] }, key);
|
|
1841
|
+
}) }),
|
|
1842
|
+
/* @__PURE__ */ jsx("p", { style: { ...s.p, fontWeight: 600, marginTop: 4 }, children: "Last beacons" }),
|
|
1843
|
+
tracked.length ? /* @__PURE__ */ jsx("ol", { style: s.list, children: tracked.slice(0, 8).map((t) => /* @__PURE__ */ jsxs("li", { style: { ...s.dd, display: "flex", gap: 8 }, children: [
|
|
1844
|
+
/* @__PURE__ */ jsx("span", { style: t.status === "sent" ? void 0 : s.muted, children: t.status }),
|
|
1845
|
+
/* @__PURE__ */ jsx("span", { style: { fontWeight: 500 }, children: t.name }),
|
|
1846
|
+
/* @__PURE__ */ jsxs("span", { style: { ...s.muted, overflow: "hidden", textOverflow: "ellipsis" }, children: [
|
|
1847
|
+
t.testKey,
|
|
1848
|
+
":",
|
|
1849
|
+
t.arm,
|
|
1850
|
+
t.props && Object.keys(t.props).length ? ` ${JSON.stringify(t.props)}` : ""
|
|
1851
|
+
] })
|
|
1852
|
+
] }, `${t.at}-${t.name}-${t.testKey}`)) }) : /* @__PURE__ */ jsx("p", { style: s.muted, children: "None yet this page." })
|
|
1853
|
+
] })
|
|
1854
|
+
] });
|
|
1228
1855
|
}
|
|
1229
1856
|
var MILESTONES = [25, 50, 75, 100];
|
|
1230
1857
|
var IDLE_MS = 5e3;
|
|
@@ -1295,6 +1922,450 @@ function usePageEngagement(pathname, enabled) {
|
|
|
1295
1922
|
};
|
|
1296
1923
|
}, [pathname, enabled]);
|
|
1297
1924
|
}
|
|
1925
|
+
function PlaybookProvider({
|
|
1926
|
+
state,
|
|
1927
|
+
pathname,
|
|
1928
|
+
exposureUrl = DEFAULT_EXPOSURE_URL,
|
|
1929
|
+
eventUrl = DEFAULT_EVENT_URL,
|
|
1930
|
+
supportedEvents = DEFAULT_SUPPORTED_EVENTS,
|
|
1931
|
+
storeContext,
|
|
1932
|
+
consent: consentAdapter,
|
|
1933
|
+
dataLayer = {},
|
|
1934
|
+
children
|
|
1935
|
+
}) {
|
|
1936
|
+
const [consent, setConsent] = useState("pending");
|
|
1937
|
+
const consentRequired = !!state?.consentRequired;
|
|
1938
|
+
useEffect(() => {
|
|
1939
|
+
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
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
if (consentRequired) declareConsentRequired();
|
|
1957
|
+
const update = () => live && setConsent(getConsentState());
|
|
1958
|
+
waitForConsentAPI().then(update);
|
|
1959
|
+
const unsubscribe = onConsentChange(update);
|
|
1960
|
+
return () => {
|
|
1961
|
+
live = false;
|
|
1962
|
+
unsubscribe();
|
|
1963
|
+
};
|
|
1964
|
+
}, [consentRequired, consentAdapter]);
|
|
1965
|
+
const visitorId = state?.enabled ? state.visitorId : null;
|
|
1966
|
+
useEffect(() => {
|
|
1967
|
+
if (visitorId) syncVisitorId(visitorId, consent);
|
|
1968
|
+
}, [visitorId, consent]);
|
|
1969
|
+
if (typeof window !== "undefined") {
|
|
1970
|
+
try {
|
|
1971
|
+
configureTracker({
|
|
1972
|
+
state: state ?? null,
|
|
1973
|
+
consent,
|
|
1974
|
+
pathname,
|
|
1975
|
+
exposureUrl,
|
|
1976
|
+
eventUrl,
|
|
1977
|
+
supportedEvents: new Set(supportedEvents),
|
|
1978
|
+
store: storeContext ?? {},
|
|
1979
|
+
dataLayer
|
|
1980
|
+
});
|
|
1981
|
+
} catch {
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
const value = useMemo(
|
|
1985
|
+
() => ({ state: state ?? null, pathname, exposureUrl, eventUrl, consent }),
|
|
1986
|
+
[state, pathname, exposureUrl, eventUrl, consent]
|
|
1987
|
+
);
|
|
1988
|
+
return /* @__PURE__ */ jsx(PlaybookContext.Provider, { value, children });
|
|
1989
|
+
}
|
|
1990
|
+
function PlaybookExposure({
|
|
1991
|
+
testKey,
|
|
1992
|
+
variant,
|
|
1993
|
+
enabled,
|
|
1994
|
+
children
|
|
1995
|
+
}) {
|
|
1996
|
+
const ref = usePlaybookExposure(testKey, variant, { enabled });
|
|
1997
|
+
return /* @__PURE__ */ jsx(Fragment, { children: children(ref) });
|
|
1998
|
+
}
|
|
1999
|
+
var AA_SITEWIDE_TEST = "aa-sitewide";
|
|
2000
|
+
var noopSubscribe = () => () => {
|
|
2001
|
+
};
|
|
2002
|
+
function useHydrated() {
|
|
2003
|
+
return useSyncExternalStore(
|
|
2004
|
+
noopSubscribe,
|
|
2005
|
+
() => true,
|
|
2006
|
+
() => false
|
|
2007
|
+
);
|
|
2008
|
+
}
|
|
2009
|
+
function visitorInRunningTest(state) {
|
|
2010
|
+
if (!state?.enabled || !state.visitorId) return false;
|
|
2011
|
+
return Object.values(state.tests).some(
|
|
2012
|
+
(a) => a.inTest && !a.forced && a.status === "running"
|
|
2013
|
+
);
|
|
2014
|
+
}
|
|
2015
|
+
function CartAttributeSync({
|
|
2016
|
+
state,
|
|
2017
|
+
cart,
|
|
2018
|
+
onEvent
|
|
2019
|
+
}) {
|
|
2020
|
+
const allowed = useAnalyticsAllowed();
|
|
2021
|
+
const cartRef = useRef(cart);
|
|
2022
|
+
cartRef.current = cart;
|
|
2023
|
+
const onEventRef = useRef(onEvent);
|
|
2024
|
+
onEventRef.current = onEvent;
|
|
2025
|
+
const sync = useMemo(
|
|
2026
|
+
() => createCartAttributeSync({
|
|
2027
|
+
write: (add, current) => {
|
|
2028
|
+
const c = cartRef.current;
|
|
2029
|
+
const writer = c.write ?? createCartAttributeWriter({
|
|
2030
|
+
endpoint: c.endpoint,
|
|
2031
|
+
serverMerges: c.serverMerges
|
|
2032
|
+
});
|
|
2033
|
+
return writer(add, current);
|
|
2034
|
+
},
|
|
2035
|
+
read: () => {
|
|
2036
|
+
const c = cartRef.current;
|
|
2037
|
+
return (c.read ?? createCartAttributeReader({ endpoint: c.endpoint }))();
|
|
2038
|
+
},
|
|
2039
|
+
onEvent: (e) => onEventRef.current?.(e)
|
|
2040
|
+
}),
|
|
2041
|
+
[]
|
|
2042
|
+
);
|
|
2043
|
+
useEffect(() => () => sync.dispose(), [sync]);
|
|
2044
|
+
const eligible = allowed && visitorInRunningTest(state);
|
|
2045
|
+
let attrSignature = "";
|
|
2046
|
+
try {
|
|
2047
|
+
attrSignature = JSON.stringify(cart.attributes ?? []);
|
|
2048
|
+
} catch {
|
|
2049
|
+
attrSignature = String(cart.attributes?.length ?? 0);
|
|
2050
|
+
}
|
|
2051
|
+
useEffect(() => {
|
|
2052
|
+
sync.update({
|
|
2053
|
+
cartId: cartRef.current.cartId,
|
|
2054
|
+
attributes: cartRef.current.attributes,
|
|
2055
|
+
status: cartRef.current.status,
|
|
2056
|
+
visitorId: state.visitorId,
|
|
2057
|
+
eligible
|
|
2058
|
+
});
|
|
2059
|
+
}, [sync, cart.cartId, attrSignature, cart.status, state.visitorId, eligible]);
|
|
2060
|
+
return null;
|
|
2061
|
+
}
|
|
2062
|
+
function PreviewParam({
|
|
2063
|
+
location,
|
|
2064
|
+
navigate
|
|
2065
|
+
}) {
|
|
2066
|
+
const target = usePreviewParamRedirect({
|
|
2067
|
+
pathname: location.pathname,
|
|
2068
|
+
search: location.search ?? "",
|
|
2069
|
+
hash: location.hash ?? ""
|
|
2070
|
+
});
|
|
2071
|
+
useEffect(() => {
|
|
2072
|
+
if (!target) return;
|
|
2073
|
+
if (navigate) navigate(target, { replace: true, preventScrollReset: true });
|
|
2074
|
+
else window.location.replace(target);
|
|
2075
|
+
}, [target]);
|
|
2076
|
+
return null;
|
|
2077
|
+
}
|
|
2078
|
+
var SENTINEL_STYLE = {
|
|
2079
|
+
position: "fixed",
|
|
2080
|
+
top: 0,
|
|
2081
|
+
left: 0,
|
|
2082
|
+
width: 1,
|
|
2083
|
+
height: 1,
|
|
2084
|
+
opacity: 0,
|
|
2085
|
+
pointerEvents: "none"
|
|
2086
|
+
};
|
|
2087
|
+
function PlaybookAAExposure({ testKey = AA_SITEWIDE_TEST }) {
|
|
2088
|
+
const variant = usePlaybookVariant(testKey);
|
|
2089
|
+
const ref = usePlaybookExposure(testKey, variant);
|
|
2090
|
+
return /* @__PURE__ */ jsx("span", { ref, "aria-hidden": "true", style: SENTINEL_STYLE });
|
|
2091
|
+
}
|
|
2092
|
+
function Engagement({ pathname, enabled }) {
|
|
2093
|
+
usePageEngagement(pathname, enabled);
|
|
2094
|
+
return null;
|
|
2095
|
+
}
|
|
2096
|
+
function PlaybookRoot({
|
|
2097
|
+
state,
|
|
2098
|
+
location,
|
|
2099
|
+
navigate,
|
|
2100
|
+
cart,
|
|
2101
|
+
consent,
|
|
2102
|
+
storeContext,
|
|
2103
|
+
editorPreview = false,
|
|
2104
|
+
aaSentinel = true,
|
|
2105
|
+
debug,
|
|
2106
|
+
dataLayer,
|
|
2107
|
+
onCartSyncEvent,
|
|
2108
|
+
exposureUrl,
|
|
2109
|
+
eventUrl,
|
|
2110
|
+
supportedEvents,
|
|
2111
|
+
children
|
|
2112
|
+
}) {
|
|
2113
|
+
const hydrated = useHydrated();
|
|
2114
|
+
const enabled = !!state?.enabled;
|
|
2115
|
+
return /* @__PURE__ */ jsxs(
|
|
2116
|
+
PlaybookProvider,
|
|
2117
|
+
{
|
|
2118
|
+
state,
|
|
2119
|
+
pathname: location.pathname,
|
|
2120
|
+
storeContext,
|
|
2121
|
+
consent,
|
|
2122
|
+
dataLayer,
|
|
2123
|
+
exposureUrl,
|
|
2124
|
+
eventUrl,
|
|
2125
|
+
supportedEvents,
|
|
2126
|
+
children: [
|
|
2127
|
+
children,
|
|
2128
|
+
hydrated && /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
2129
|
+
/* @__PURE__ */ jsx(PlaybookBoundary, { name: "engagement", children: /* @__PURE__ */ jsx(Engagement, { pathname: location.pathname, enabled }) }),
|
|
2130
|
+
enabled && state?.visitorId && cart && !editorPreview && /* @__PURE__ */ jsx(PlaybookBoundary, { name: "cart attribute", children: /* @__PURE__ */ jsx(
|
|
2131
|
+
CartAttributeSync,
|
|
2132
|
+
{
|
|
2133
|
+
state,
|
|
2134
|
+
cart,
|
|
2135
|
+
onEvent: onCartSyncEvent
|
|
2136
|
+
}
|
|
2137
|
+
) }),
|
|
2138
|
+
state?.previewToken && /* @__PURE__ */ jsx(PlaybookBoundary, { name: "preview param", children: /* @__PURE__ */ jsx(PreviewParam, { location, navigate }) }),
|
|
2139
|
+
enabled && aaSentinel && !editorPreview && /* @__PURE__ */ jsx(PlaybookBoundary, { name: "aa sentinel", children: /* @__PURE__ */ jsx(PlaybookAAExposure, {}) }),
|
|
2140
|
+
/* @__PURE__ */ jsx(PlaybookBoundary, { name: "debug panel", children: /* @__PURE__ */ jsx(
|
|
2141
|
+
PlaybookDebugPanel,
|
|
2142
|
+
{
|
|
2143
|
+
state,
|
|
2144
|
+
location,
|
|
2145
|
+
allowed: debug?.allowed,
|
|
2146
|
+
implementedTests: debug?.implementedTests
|
|
2147
|
+
}
|
|
2148
|
+
) })
|
|
2149
|
+
] })
|
|
2150
|
+
]
|
|
2151
|
+
}
|
|
2152
|
+
);
|
|
2153
|
+
}
|
|
2154
|
+
|
|
2155
|
+
// src/proxy.ts
|
|
2156
|
+
var FORWARDED_REQUEST_HEADERS = [
|
|
2157
|
+
"accept",
|
|
2158
|
+
"accept-language",
|
|
2159
|
+
"content-type",
|
|
2160
|
+
"referer",
|
|
2161
|
+
"user-agent",
|
|
2162
|
+
"x-forwarded-for"
|
|
2163
|
+
];
|
|
2164
|
+
var FORWARDED_RESPONSE_HEADERS = ["content-type", "cache-control", "etag"];
|
|
2165
|
+
var CORS_HEADERS = {
|
|
2166
|
+
"access-control-allow-origin": "*",
|
|
2167
|
+
"access-control-allow-methods": "GET, POST, OPTIONS",
|
|
2168
|
+
"access-control-allow-headers": "Content-Type"
|
|
2169
|
+
};
|
|
2170
|
+
var ALLOWED_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "POST", "OPTIONS"]);
|
|
2171
|
+
var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([101, 204, 205, 304]);
|
|
2172
|
+
var PROXY_PREFIX = "/apps/playbook/";
|
|
2173
|
+
var PROXY_TIMEOUT_MS = 5e3;
|
|
2174
|
+
var PROXY_MAX_BODY_BYTES = 64 * 1024;
|
|
2175
|
+
function playbookBackendUrl(requestUrl, platformUrl) {
|
|
2176
|
+
const url = new URL(requestUrl);
|
|
2177
|
+
const idx = url.pathname.indexOf(PROXY_PREFIX);
|
|
2178
|
+
const subPath = idx !== -1 ? url.pathname.slice(idx + PROXY_PREFIX.length) : "";
|
|
2179
|
+
const backendPath = subPath.startsWith("api/") ? `/${subPath}` : `/api/${subPath}`;
|
|
2180
|
+
const backend = new URL(backendPath, platformUrl);
|
|
2181
|
+
backend.search = url.search;
|
|
2182
|
+
return backend.toString();
|
|
2183
|
+
}
|
|
2184
|
+
function plain(status, text) {
|
|
2185
|
+
return new Response(text, {
|
|
2186
|
+
status,
|
|
2187
|
+
headers: {
|
|
2188
|
+
...CORS_HEADERS,
|
|
2189
|
+
"content-type": "text/plain; charset=utf-8",
|
|
2190
|
+
"cache-control": "no-store"
|
|
2191
|
+
}
|
|
2192
|
+
});
|
|
2193
|
+
}
|
|
2194
|
+
function resolvePlatformUrl(option, args) {
|
|
2195
|
+
const fromOption = typeof option === "function" ? option(args) : option;
|
|
2196
|
+
if (fromOption) return fromOption;
|
|
2197
|
+
const env = args.context?.env;
|
|
2198
|
+
const fromEnv = env?.PLAYBOOK_PLATFORM_URL;
|
|
2199
|
+
return typeof fromEnv === "string" && fromEnv ? fromEnv : DEFAULT_PLATFORM_URL;
|
|
2200
|
+
}
|
|
2201
|
+
async function readCappedBody(request, max) {
|
|
2202
|
+
const declared = Number(request.headers.get("content-length"));
|
|
2203
|
+
if (Number.isFinite(declared) && declared > max) return null;
|
|
2204
|
+
const text = await request.text();
|
|
2205
|
+
return new TextEncoder().encode(text).length > max ? null : text;
|
|
2206
|
+
}
|
|
2207
|
+
function createPlaybookProxyHandler({
|
|
2208
|
+
platformUrl,
|
|
2209
|
+
timeoutMs = PROXY_TIMEOUT_MS,
|
|
2210
|
+
maxBodyBytes = PROXY_MAX_BODY_BYTES,
|
|
2211
|
+
fetchImpl
|
|
2212
|
+
} = {}) {
|
|
2213
|
+
const proxy = async (args) => {
|
|
2214
|
+
const { request } = args;
|
|
2215
|
+
const method = request.method.toUpperCase();
|
|
2216
|
+
if (method === "OPTIONS") {
|
|
2217
|
+
return new Response(null, {
|
|
2218
|
+
status: 204,
|
|
2219
|
+
headers: { ...CORS_HEADERS, "access-control-max-age": "86400" }
|
|
2220
|
+
});
|
|
2221
|
+
}
|
|
2222
|
+
if (!ALLOWED_METHODS.has(method)) return plain(405, "Method Not Allowed");
|
|
2223
|
+
const controller = new AbortController();
|
|
2224
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
2225
|
+
try {
|
|
2226
|
+
const backendUrl = playbookBackendUrl(
|
|
2227
|
+
request.url,
|
|
2228
|
+
resolvePlatformUrl(platformUrl, args)
|
|
2229
|
+
);
|
|
2230
|
+
const headers = new Headers();
|
|
2231
|
+
for (const name of FORWARDED_REQUEST_HEADERS) {
|
|
2232
|
+
const value = request.headers.get(name);
|
|
2233
|
+
if (value) headers.set(name, value);
|
|
2234
|
+
}
|
|
2235
|
+
headers.set("x-forwarded-host", new URL(request.url).host);
|
|
2236
|
+
const init = { method, headers, signal: controller.signal };
|
|
2237
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
2238
|
+
const body3 = await readCappedBody(request, maxBodyBytes);
|
|
2239
|
+
if (body3 === null) return plain(413, "Payload Too Large");
|
|
2240
|
+
init.body = body3;
|
|
2241
|
+
}
|
|
2242
|
+
const upstream = await (fetchImpl ?? fetch)(backendUrl, init);
|
|
2243
|
+
const responseHeaders = new Headers();
|
|
2244
|
+
for (const name of FORWARDED_RESPONSE_HEADERS) {
|
|
2245
|
+
const value = upstream.headers.get(name);
|
|
2246
|
+
if (value) responseHeaders.set(name, value);
|
|
2247
|
+
}
|
|
2248
|
+
for (const [k, v] of Object.entries(CORS_HEADERS)) responseHeaders.set(k, v);
|
|
2249
|
+
responseHeaders.set("cache-control", "no-store");
|
|
2250
|
+
const nullBody = NULL_BODY_STATUSES.has(upstream.status) || method === "HEAD";
|
|
2251
|
+
const body2 = nullBody ? null : await upstream.arrayBuffer();
|
|
2252
|
+
return new Response(body2, { status: upstream.status, headers: responseHeaders });
|
|
2253
|
+
} catch (error) {
|
|
2254
|
+
const timedOut = controller.signal.aborted;
|
|
2255
|
+
console.warn(
|
|
2256
|
+
"[playbook] proxy",
|
|
2257
|
+
timedOut ? "upstream timeout" : "upstream failed",
|
|
2258
|
+
String(error)
|
|
2259
|
+
);
|
|
2260
|
+
return timedOut ? plain(504, "Gateway Timeout") : plain(502, "Bad Gateway");
|
|
2261
|
+
} finally {
|
|
2262
|
+
clearTimeout(timer);
|
|
2263
|
+
}
|
|
2264
|
+
};
|
|
2265
|
+
return { loader: proxy, action: proxy };
|
|
2266
|
+
}
|
|
2267
|
+
|
|
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();
|
|
1298
2369
|
|
|
1299
2370
|
// src/cart-events.ts
|
|
1300
2371
|
var nextSource = null;
|
|
@@ -1310,6 +2381,39 @@ function numericId(gid) {
|
|
|
1310
2381
|
const id = gid?.split("/").pop();
|
|
1311
2382
|
return id && /^\d{1,30}$/.test(id) ? id : null;
|
|
1312
2383
|
}
|
|
2384
|
+
function parseJson(value) {
|
|
2385
|
+
if (typeof value !== "string" || !value) return null;
|
|
2386
|
+
try {
|
|
2387
|
+
return JSON.parse(value);
|
|
2388
|
+
} catch {
|
|
2389
|
+
return null;
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
2392
|
+
function addedLinesFrom(input) {
|
|
2393
|
+
if (!input) return [];
|
|
2394
|
+
if (Array.isArray(input)) return input;
|
|
2395
|
+
if (typeof FormData === "undefined" || !(input instanceof FormData)) return [];
|
|
2396
|
+
const formInput = parseJson(input.get("cartFormInput"));
|
|
2397
|
+
if (formInput?.inputs?.lines) return formInput.inputs.lines;
|
|
2398
|
+
const action = input.get("action");
|
|
2399
|
+
const raw = action === "Create" ? parseJson(input.get("cart"))?.lines : parseJson(input.get("lines"));
|
|
2400
|
+
return Array.isArray(raw) ? raw : [];
|
|
2401
|
+
}
|
|
2402
|
+
function trackAddToCart(source, {
|
|
2403
|
+
lines,
|
|
2404
|
+
cart
|
|
2405
|
+
}) {
|
|
2406
|
+
try {
|
|
2407
|
+
const conn = cart?.lines;
|
|
2408
|
+
const snapshots = Array.isArray(conn) ? conn : conn?.nodes ?? conn?.edges?.map((e) => e.node) ?? [];
|
|
2409
|
+
trackAddToCartLines(
|
|
2410
|
+
addedLinesFrom(lines),
|
|
2411
|
+
snapshots,
|
|
2412
|
+
source ?? takeAddSource()
|
|
2413
|
+
);
|
|
2414
|
+
} catch {
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
1313
2417
|
function trackAddToCartLines(lines, cartLines, source) {
|
|
1314
2418
|
try {
|
|
1315
2419
|
for (const line of lines) {
|
|
@@ -1334,15 +2438,4 @@ function trackAddToCartLines(lines, cartLines, source) {
|
|
|
1334
2438
|
}
|
|
1335
2439
|
}
|
|
1336
2440
|
|
|
1337
|
-
|
|
1338
|
-
var CART_VISITOR_ATTRIBUTE = "_pb_vid";
|
|
1339
|
-
function playbookCartAttribute(visitorId) {
|
|
1340
|
-
return { key: CART_VISITOR_ATTRIBUTE, value: visitorId };
|
|
1341
|
-
}
|
|
1342
|
-
function cartHasPlaybookAttribute(attributes, visitorId) {
|
|
1343
|
-
return !!attributes?.some(
|
|
1344
|
-
(a) => a.key === CART_VISITOR_ATTRIBUTE && a.value === visitorId
|
|
1345
|
-
);
|
|
1346
|
-
}
|
|
1347
|
-
|
|
1348
|
-
export { CART_VISITOR_ATTRIBUTE, CONTROL_ARM, DEFAULT_EVENT_URL, DEFAULT_EXPOSURE_URL, DEFAULT_PLATFORM_URL, DEFAULT_SUPPORTED_EVENTS, LEGACY_VISITOR_COOKIE, PlaybookExposure, PlaybookProvider, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, VISITOR_COOKIE, analyticsConsentFromCookie, assignTest, cartHasPlaybookAttribute, chooseVariation, createPlaybook, declareConsentRequired, detectDevice, detectGeo, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getTrackedLog, hasSentExposure, hash, inNamespace, isAnalyticsConsentGranted, matchesPathPrefix, onConsentChange, playbookCartAttribute, playbookTrack, prefetchRuleset, setNextAddSource, subscribeTrackedLog, syncVisitorId, takeAddSource, trackAddToCartLines, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorSeedScript, waitForConsentAPI };
|
|
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 };
|