@heyplaybook/hydrogen 0.8.0 → 0.8.1

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.d.ts CHANGED
@@ -591,6 +591,26 @@ declare function getSsrPayload(args: {
591
591
  waitUntil?: (p: Promise<unknown>) => void;
592
592
  fetchImpl?: typeof fetch;
593
593
  }): Promise<SsrPayload | null>;
594
+ /**
595
+ * 0.8.1: the TOTAL budget for the uncached preview read, retry included. Only
596
+ * a `?pb=` preview (staff and the merchant looking at one test) ever waits on
597
+ * it; shopper reads keep `COLD_RENDER_BUDGET_MS` / `RENDER_BUDGET_MS`
598
+ * (./rules.ts). 0.7.1 had 1.5s, and a cold platform function missed it, so
599
+ * the first open of a preview link fell back to the browser's `?pb` path.
600
+ */
601
+ declare const PREVIEW_FETCH_BUDGET_MS = 5000;
602
+ /** 0.8.1: one attempt's share of the budget; a timed-out first attempt leaves room for the retry. */
603
+ declare const PREVIEW_ATTEMPT_BUDGET_MS = 3000;
604
+ /**
605
+ * 0.8.1: the cookie that carries a preview code across CLIENT-SIDE
606
+ * navigations. The browser strips `?pb=` from the address bar once it has
607
+ * resolved the code, so React Router's `.data` requests for later pages don't
608
+ * carry it. Session-only, HttpOnly, Lax. Set when a document request's code
609
+ * is valid; honoured ONLY on `.data` requests; cleared by any document
610
+ * request without `?pb=` (Exit reloads, a new tab, a typed URL), so it can't
611
+ * follow anyone out of the preview.
612
+ */
613
+ declare const PREVIEW_CODE_COOKIE = "_pb_preview_code";
594
614
  /**
595
615
  * The arm index for `seed` + `id` over `weights` (coverage 1), or -1. GrowthBook
596
616
  * v2: `fnv32a(fnv32a(seed + id) + "") % 10000 / 10000`; weights that don't sum
@@ -614,6 +634,13 @@ interface SsrDecision {
614
634
  code: string;
615
635
  testName: string;
616
636
  armLabel: string;
637
+ /**
638
+ * 0.8.1: decided on a `.data` request (a client-side navigation). It
639
+ * reaches the page through React, not the HTML, so `<PlaybookSlot>` and
640
+ * `<PlaybookSsrHead>` render it only in a tab previewing this code
641
+ * (`carriedPreviewAllowed`).
642
+ */
643
+ carried?: boolean;
617
644
  };
618
645
  /**
619
646
  * 0.8.0: which kind of declared slot serves the arm (`loaderData()` sets it):
@@ -892,6 +919,11 @@ declare function matchTargetedPage(pages: readonly string[] | null | undefined,
892
919
  * `window.__pbSsr` (so the SDK adopts the arm and reports it as shown) and the
893
920
  * arm's theme-section hides, before first paint. Renders nothing without a
894
921
  * decision.
922
+ *
923
+ * 0.8.1: a carried preview decision arrives with a client-side navigation, so
924
+ * an inline <script> would never run: `window.__pbSsr` is set from a layout
925
+ * effect instead, in the same commit that inserts the host, before the
926
+ * experience SDK looks at the new page.
895
927
  */
896
928
  declare function PlaybookSsrHead({ ssr, nonce }: {
897
929
  ssr: SsrDecision | null | undefined;
@@ -1525,4 +1557,4 @@ declare function inNamespace(hashValue: string, namespace: [string, number, numb
1525
1557
  declare function chooseVariation(n: number, ranges: VariationRange[]): number;
1526
1558
  declare function getBucketRanges(numVariations: number, coverage: number | undefined, weights?: number[]): VariationRange[];
1527
1559
 
1528
- export { AA_SITEWIDE_TEST, type AddToCartSource, type AddedLineInput, CART_SYNC_IDLE_MS, CART_VISITOR_ATTRIBUTE, CLOAK_MAX_MS, CLOAK_STYLE_ID, CONSENT_LOADED_EVENTS, CONTROL_ARM, type CartAttribute, type CartAttributeReader, type CartAttributeWriter, type CartLineSnapshot, type CartSyncEvent, type CartSyncSnapshot, type CartWriteResult, type ConsentState, type CreatePlaybookContextOptions, type CreatePlaybookOptions, 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, type ExperienceAttributionConsent, type ExperienceAttributionInput, type HeadSnippetParts, LEGACY_VISITOR_COOKIE, MAX_WRITES_PER_CART, PlaybookAAExposure, type PlaybookArm, type PlaybookAssignReason, type PlaybookAssignment, PlaybookBoundary, type PlaybookCartAdapter, type PlaybookClientConsent, type PlaybookCloakConfig, PlaybookCloakHead, type PlaybookConsentAdapter, type PlaybookDataLayerOption, type PlaybookDebugExplain, type PlaybookDebugOptions, PlaybookDebugPanel, type PlaybookDevice, type PlaybookEnv, PlaybookExposure, PlaybookHead, type PlaybookHeadProps, type PlaybookHeadSnippetOptions, type PlaybookLoaderData, type PlaybookPreview, PlaybookProvider, type PlaybookProxyOptions, type PlaybookRequestContext, PlaybookRoot, type PlaybookRootProps, type PlaybookRuleset, PlaybookSections, type PlaybookServerConsent, type PlaybookServerResult, PlaybookSlot, type PlaybookSlotKey, type PlaybookSlotName, type PlaybookSlotProps, PlaybookSsrHead, type PlaybookState, type PlaybookStoreContext, type PlaybookTestRule, type PlaybookTestStatus, type PlaybookVariant, type PlaybookVisitorType, type RulesetSource, SECTION_SLOTS, SESSION_VISITOR_COOKIE, SLOT_REPORT_SAMPLE_RATE, SLOT_REPORT_URL, SSR_SLOT_ATTR, SSR_SLOT_NAMES, STANDARD_EVENTS, type SectionSlotKey, type SsrDecision, type SsrOutcome, type SsrPayload, type SsrSlotRef, type StandardEvent, TRUEVAULT_CONSENT_COOKIE, type TrackScope, type TrackedEntry, type TrueVaultConsentOptions, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, armSlot, 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, isSlotKey, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, renderedSlotKeys, reportPageSlots, revealScript, sanitizeManifestPages, sanitizeRuleset, sectionSlotKey, setNextAddSource, shopifyCustomerPrivacyConsent, slotFromSelector, slotMatches, slotSelector, ssrHostInnerHtml, ssrUrl, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
1560
+ export { AA_SITEWIDE_TEST, type AddToCartSource, type AddedLineInput, CART_SYNC_IDLE_MS, CART_VISITOR_ATTRIBUTE, CLOAK_MAX_MS, CLOAK_STYLE_ID, CONSENT_LOADED_EVENTS, CONTROL_ARM, type CartAttribute, type CartAttributeReader, type CartAttributeWriter, type CartLineSnapshot, type CartSyncEvent, type CartSyncSnapshot, type CartWriteResult, type ConsentState, type CreatePlaybookContextOptions, type CreatePlaybookOptions, 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, type ExperienceAttributionConsent, type ExperienceAttributionInput, type HeadSnippetParts, LEGACY_VISITOR_COOKIE, MAX_WRITES_PER_CART, PREVIEW_ATTEMPT_BUDGET_MS, PREVIEW_CODE_COOKIE, PREVIEW_FETCH_BUDGET_MS, PlaybookAAExposure, type PlaybookArm, type PlaybookAssignReason, type PlaybookAssignment, PlaybookBoundary, type PlaybookCartAdapter, type PlaybookClientConsent, type PlaybookCloakConfig, PlaybookCloakHead, type PlaybookConsentAdapter, type PlaybookDataLayerOption, type PlaybookDebugExplain, type PlaybookDebugOptions, PlaybookDebugPanel, type PlaybookDevice, type PlaybookEnv, PlaybookExposure, PlaybookHead, type PlaybookHeadProps, type PlaybookHeadSnippetOptions, type PlaybookLoaderData, type PlaybookPreview, PlaybookProvider, type PlaybookProxyOptions, type PlaybookRequestContext, PlaybookRoot, type PlaybookRootProps, type PlaybookRuleset, PlaybookSections, type PlaybookServerConsent, type PlaybookServerResult, PlaybookSlot, type PlaybookSlotKey, type PlaybookSlotName, type PlaybookSlotProps, PlaybookSsrHead, type PlaybookState, type PlaybookStoreContext, type PlaybookTestRule, type PlaybookTestStatus, type PlaybookVariant, type PlaybookVisitorType, type RulesetSource, SECTION_SLOTS, SESSION_VISITOR_COOKIE, SLOT_REPORT_SAMPLE_RATE, SLOT_REPORT_URL, SSR_SLOT_ATTR, SSR_SLOT_NAMES, STANDARD_EVENTS, type SectionSlotKey, type SsrDecision, type SsrOutcome, type SsrPayload, type SsrSlotRef, type StandardEvent, TRUEVAULT_CONSENT_COOKIE, type TrackScope, type TrackedEntry, type TrueVaultConsentOptions, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, armSlot, 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, isSlotKey, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, renderedSlotKeys, reportPageSlots, revealScript, sanitizeManifestPages, sanitizeRuleset, sectionSlotKey, setNextAddSource, shopifyCustomerPrivacyConsent, slotFromSelector, slotMatches, slotSelector, ssrHostInnerHtml, ssrUrl, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
2
- import { memo, createContext, isValidElement, Fragment as Fragment$1, Component, useContext, useMemo, useCallback, useState, useEffect, useSyncExternalStore, useRef } from 'react';
2
+ import { memo, createContext, isValidElement, Fragment as Fragment$1, Component, useContext, useMemo, useCallback, useState, useEffect, useSyncExternalStore, useLayoutEffect, useRef } from 'react';
3
3
 
4
4
  // src/growthbook.ts
5
5
  function hashFnv32a(str2) {
@@ -1144,31 +1144,77 @@ async function getSsrPayload(args) {
1144
1144
  }
1145
1145
  var PREVIEW_CODE_RE = /^[0-9A-HJKMNP-TV-Z]{4,8}$/;
1146
1146
  function previewCodeFromRequestUrl(url) {
1147
- const raw = url.searchParams.get("pb");
1148
- if (!raw) return null;
1149
- const code = raw.trim().toUpperCase();
1150
- return PREVIEW_CODE_RE.test(code) ? code : null;
1147
+ return normalizePreviewCode(url.searchParams.get("pb"));
1151
1148
  }
1152
- var PREVIEW_FETCH_BUDGET_MS = 1500;
1153
- async function getSsrPreviewPayload(args) {
1149
+ var PREVIEW_FETCH_BUDGET_MS = 5e3;
1150
+ var PREVIEW_ATTEMPT_BUDGET_MS = 3e3;
1151
+ var PREVIEW_RETRY_MIN_MS = 500;
1152
+ async function previewAttempt(url, timeoutMs, fetchImpl) {
1154
1153
  const controller = new AbortController();
1155
- const timer = setTimeout(() => controller.abort(), PREVIEW_FETCH_BUDGET_MS);
1154
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1155
+ try {
1156
+ const res = await fetchImpl(url, { headers: { accept: "application/json" }, signal: controller.signal });
1157
+ if (!res.ok) return { payload: null, retry: res.status >= 500 };
1158
+ return { payload: sanitizeSsrPayload(await res.json()), retry: false };
1159
+ } catch {
1160
+ return { payload: null, retry: true };
1161
+ } finally {
1162
+ clearTimeout(timer);
1163
+ }
1164
+ }
1165
+ async function getSsrPreviewPayload(args) {
1156
1166
  try {
1157
1167
  const url = new URL(ssrUrl(args.platformUrl, args.shopDomain));
1158
1168
  url.searchParams.set("pb", args.code);
1159
- const res = await (args.fetchImpl ?? fetch)(url.toString(), {
1160
- headers: { accept: "application/json" },
1161
- signal: controller.signal
1162
- });
1163
- if (!res.ok) return null;
1164
- return sanitizeSsrPayload(await res.json());
1169
+ const budget = args.budgetMs ?? PREVIEW_FETCH_BUDGET_MS;
1170
+ const perAttempt = Math.min(args.attemptBudgetMs ?? PREVIEW_ATTEMPT_BUDGET_MS, budget);
1171
+ const fetchImpl = args.fetchImpl ?? fetch;
1172
+ const started = Date.now();
1173
+ const first = await previewAttempt(url.toString(), perAttempt, fetchImpl);
1174
+ if (first.payload || !first.retry) return first.payload;
1175
+ const left = budget - (Date.now() - started);
1176
+ if (left < Math.min(PREVIEW_RETRY_MIN_MS, budget / 4)) return null;
1177
+ return (await previewAttempt(url.toString(), left, fetchImpl)).payload;
1165
1178
  } catch {
1166
1179
  return null;
1167
- } finally {
1168
- clearTimeout(timer);
1169
1180
  }
1170
1181
  }
1171
- function decidePreviewSsr(payload, pageKey, matchesPage) {
1182
+ var PREVIEW_CODE_COOKIE = "_pb_preview_code";
1183
+ function normalizePreviewCode(raw) {
1184
+ if (!raw) return null;
1185
+ const code = raw.trim().toUpperCase();
1186
+ return PREVIEW_CODE_RE.test(code) ? code : null;
1187
+ }
1188
+ function isDataRequest(url) {
1189
+ return url.pathname.endsWith(".data");
1190
+ }
1191
+ function dataRequestPagePath(pathname) {
1192
+ if (!pathname.endsWith(".data")) return pathname;
1193
+ if (pathname === "/_root.data") return "/";
1194
+ return pathname.slice(0, -".data".length) || "/";
1195
+ }
1196
+ var PREVIEW_SESSION_STORAGE_KEY = "_pb_preview";
1197
+ function carriedPreviewAllowed(d) {
1198
+ if (!d?.preview) return false;
1199
+ if (!d.preview.carried) return true;
1200
+ if (typeof window === "undefined") return false;
1201
+ const code = d.preview.code;
1202
+ try {
1203
+ const live = window.__pbSsr;
1204
+ if (live?.preview?.code === code) return true;
1205
+ } catch {
1206
+ }
1207
+ try {
1208
+ const raw = window.sessionStorage?.getItem(PREVIEW_SESSION_STORAGE_KEY);
1209
+ if (!raw) return false;
1210
+ const s2 = JSON.parse(raw);
1211
+ if (typeof s2?.code !== "string" || s2.code.toUpperCase() !== code) return false;
1212
+ return typeof s2.expiresAt !== "string" || Date.parse(s2.expiresAt) > Date.now();
1213
+ } catch {
1214
+ return false;
1215
+ }
1216
+ }
1217
+ function decidePreviewSsr(payload, pageKey, matchesPage, carried = false) {
1172
1218
  const p = payload.preview;
1173
1219
  if (!p) return { skip: "preview-unresolved" };
1174
1220
  if (p.why) return { skip: `preview-${p.why}` };
@@ -1186,7 +1232,7 @@ function decidePreviewSsr(payload, pageKey, matchesPage) {
1186
1232
  arm: p.arm,
1187
1233
  snapshot: p.snapshot,
1188
1234
  page: { t, h },
1189
- preview: { code: p.code, testName: p.testName, armLabel: p.armLabel }
1235
+ preview: { code: p.code, testName: p.testName, armLabel: p.armLabel, ...carried ? { carried: true } : {} }
1190
1236
  }
1191
1237
  };
1192
1238
  }
@@ -1291,7 +1337,10 @@ function ssrHostInnerHtml(snapshot, page) {
1291
1337
  return `<template shadowrootmode="open"><style data-pb-ssr-snapshot>${BASE}</style><div data-pb-experience-root data-pb-ssr-snapshot>${nodes}</div></template>`;
1292
1338
  }
1293
1339
  function ssrStateScript(d) {
1294
- const state = {
1340
+ return `window.__pbSsr=${JSON.stringify(ssrStateObject(d)).replace(/</g, "\\u003c")};`;
1341
+ }
1342
+ function ssrStateObject(d) {
1343
+ return {
1295
1344
  experimentId: d.experimentId,
1296
1345
  armId: d.armId,
1297
1346
  experienceId: d.experienceId,
@@ -1303,7 +1352,6 @@ function ssrStateScript(d) {
1303
1352
  // A preview render: the SDK keeps it without resolving or recording.
1304
1353
  ...d.preview ? { preview: d.preview } : {}
1305
1354
  };
1306
- return `window.__pbSsr=${JSON.stringify(state).replace(/</g, "\\u003c")};`;
1307
1355
  }
1308
1356
  function armSlot(a) {
1309
1357
  if (!a) return null;
@@ -1361,6 +1409,33 @@ function createPlaybookContext({
1361
1409
  const platformUrl = platformUrlOption || str(e.PLAYBOOK_PLATFORM_URL) || DEFAULT_PLATFORM_URL;
1362
1410
  let promise = null;
1363
1411
  let settled = false;
1412
+ const requestUrl = (() => {
1413
+ try {
1414
+ return new URL(request.url);
1415
+ } catch {
1416
+ return null;
1417
+ }
1418
+ })();
1419
+ const isGet = request.method === "GET";
1420
+ const isData = !!requestUrl && isDataRequest(requestUrl);
1421
+ const urlCode = requestUrl ? previewCodeFromRequestUrl(requestUrl) : null;
1422
+ const carryCookieRaw = isGet ? parseCookies(request.headers.get("cookie"))[PREVIEW_CODE_COOKIE] : void 0;
1423
+ const carryCode = normalizePreviewCode(carryCookieRaw);
1424
+ const previewCode = shopId && isGet && ssrSlots.length > 0 ? isData ? urlCode ?? carryCode : urlCode : null;
1425
+ const extraCookies = [];
1426
+ const secure = requestUrl?.protocol === "https:";
1427
+ const setCarry = (code) => extraCookies.push(serializeCookie(PREVIEW_CODE_COOKIE, code, { httpOnly: true, secure }));
1428
+ const clearCarry = () => extraCookies.push(serializeCookie(PREVIEW_CODE_COOKIE, "", { httpOnly: true, secure, maxAge: 0 }));
1429
+ if (shopId && isGet && !isData && !urlCode && carryCookieRaw !== void 0) clearCarry();
1430
+ let previewFetch = null;
1431
+ const previewPayload = () => {
1432
+ if (!previewFetch) {
1433
+ const shopDomain = requestUrl ? normalizeDomain(shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? requestUrl.hostname) : "";
1434
+ previewFetch = previewCode && shopDomain ? getSsrPreviewPayload({ platformUrl, shopDomain, code: previewCode, fetchImpl }).catch(() => null) : Promise.resolve(null);
1435
+ }
1436
+ return previewFetch;
1437
+ };
1438
+ if (previewCode) void previewPayload();
1364
1439
  if (shopId && request.method === "GET") {
1365
1440
  try {
1366
1441
  prefetchRuleset({ platformUrl, shopId, waitUntil, fetchImpl });
@@ -1452,21 +1527,24 @@ function createPlaybookContext({
1452
1527
  return cloakPromise;
1453
1528
  };
1454
1529
  let ssrRendered = false;
1530
+ const noStore = () => ssrRendered || !!previewCode;
1455
1531
  const slotRefs = ssrSlots.map(toSlotRef);
1456
1532
  let ssrPromise = null;
1457
1533
  const ssrFor = (cloak) => {
1458
1534
  if (!ssrPromise) {
1459
1535
  ssrPromise = (async () => {
1460
1536
  if (ssrSlots.length === 0) return { ssr: null, skip: null };
1461
- const url = new URL(request.url);
1462
- const code = request.method === "GET" && !url.pathname.endsWith(".data") ? previewCodeFromRequestUrl(url) : null;
1463
- if (code && shopId) {
1464
- const shopDomain = normalizeDomain(shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? url.hostname);
1465
- if (!shopDomain) return { ssr: null, skip: "preview-no-shop" };
1466
- const payload2 = await getSsrPreviewPayload({ platformUrl, shopDomain, code, fetchImpl });
1537
+ if (previewCode && requestUrl) {
1538
+ const payload2 = await previewPayload();
1467
1539
  if (!payload2) return { ssr: null, skip: "preview-unavailable" };
1468
- const pageKey = targetPageKey(url.pathname);
1469
- const out2 = decidePreviewSsr(payload2, pageKey, (pages) => matchTargetedPage(pages, url.pathname) !== null);
1540
+ if (!payload2.preview) {
1541
+ if (carryCookieRaw !== void 0 && (carryCode === previewCode || !carryCode)) clearCarry();
1542
+ } else if (!isData && carryCode !== previewCode) {
1543
+ setCarry(previewCode);
1544
+ }
1545
+ const pagePath = dataRequestPagePath(requestUrl.pathname);
1546
+ const pageKey = targetPageKey(pagePath);
1547
+ const out2 = decidePreviewSsr(payload2, pageKey, (pages) => matchTargetedPage(pages, pagePath) !== null, isData);
1470
1548
  if ("skip" in out2) return { ssr: null, skip: out2.skip };
1471
1549
  let d2 = out2.decision;
1472
1550
  if (d2.experienceId) {
@@ -1555,26 +1633,28 @@ function createPlaybookContext({
1555
1633
  },
1556
1634
  async appendCookies(headers) {
1557
1635
  try {
1558
- append(headers, await cookiesFor(FINALIZE_WAIT_MS));
1559
- if (ssrRendered) headers.set("Cache-Control", "private, no-store");
1636
+ append(headers, [...await cookiesFor(FINALIZE_WAIT_MS), ...extraCookies]);
1637
+ if (noStore()) headers.set("Cache-Control", "private, no-store");
1560
1638
  } catch {
1561
1639
  }
1562
1640
  },
1563
1641
  async finalize(response) {
1564
1642
  try {
1565
1643
  const isRedirect = response.status >= 300 && response.status < 400;
1566
- const cookies = await cookiesFor(
1567
- isRedirect ? FINALIZE_REDIRECT_WAIT_MS : FINALIZE_WAIT_MS
1568
- );
1569
- if (!cookies.length && !ssrRendered) return response;
1644
+ const cookies = [
1645
+ ...await cookiesFor(isRedirect ? FINALIZE_REDIRECT_WAIT_MS : FINALIZE_WAIT_MS),
1646
+ ...extraCookies
1647
+ ];
1648
+ const privateResponse = noStore();
1649
+ if (!cookies.length && !privateResponse) return response;
1570
1650
  try {
1571
1651
  append(response.headers, cookies);
1572
- if (ssrRendered) response.headers.set("Cache-Control", "private, no-store");
1652
+ if (privateResponse) response.headers.set("Cache-Control", "private, no-store");
1573
1653
  return response;
1574
1654
  } catch {
1575
1655
  const headers = new Headers(response.headers);
1576
1656
  append(headers, cookies);
1577
- if (ssrRendered) headers.set("Cache-Control", "private, no-store");
1657
+ if (privateResponse) headers.set("Cache-Control", "private, no-store");
1578
1658
  return new Response(response.body, {
1579
1659
  status: response.status,
1580
1660
  statusText: response.statusText,
@@ -1772,29 +1852,68 @@ function playbookHeadSnippetHtml(cloak, options = {}) {
1772
1852
  const attrs = Object.entries(parts.sdk.attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
1773
1853
  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>`;
1774
1854
  }
1775
- function PlaybookSsrHead({ ssr, nonce }) {
1855
+ var useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
1856
+ function renderable(ssr) {
1776
1857
  if (!ssr) return null;
1777
- const hide = ssr.experienceId ? (ssr.arm.hide || []).map((s2) => `${s2}{display:none!important}`).join("") : "";
1858
+ if (ssr.preview?.carried && !carriedPreviewAllowed(ssr)) return null;
1859
+ return ssr;
1860
+ }
1861
+ function PlaybookSsrHead({ ssr, nonce }) {
1862
+ const d = renderable(ssr);
1863
+ const carried = !!d?.preview?.carried;
1864
+ const stateKey = carried && d ? `${d.experimentId}:${d.armId}:${d.page.t}:${d.page.h}` : null;
1865
+ useIsoLayoutEffect(() => {
1866
+ if (!carried || !d) return;
1867
+ try {
1868
+ window.__pbSsr = ssrStateObject(d);
1869
+ } catch {
1870
+ }
1871
+ }, [stateKey]);
1872
+ if (!d) return null;
1873
+ const hide = d.experienceId ? (d.arm.hide || []).map((s2) => `${s2}{display:none!important}`).join("") : "";
1778
1874
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1779
- /* @__PURE__ */ jsx("script", { nonce, "data-pb-ssr-state": "", dangerouslySetInnerHTML: { __html: ssrStateScript(ssr) } }),
1875
+ carried ? null : /* @__PURE__ */ jsx("script", { nonce, "data-pb-ssr-state": "", dangerouslySetInnerHTML: { __html: ssrStateScript(d) } }),
1780
1876
  hide ? /* @__PURE__ */ jsx("style", { id: "pb-ssr-hide", nonce, dangerouslySetInnerHTML: { __html: escStyle(hide) } }) : null
1781
1877
  ] });
1782
1878
  }
1879
+ function attachDeclarativeShadow(host) {
1880
+ if (host.shadowRoot) return true;
1881
+ const tpl = Array.from(host.children).find(
1882
+ (c) => c.tagName === "TEMPLATE" && c.hasAttribute("shadowrootmode")
1883
+ );
1884
+ if (!tpl) return false;
1885
+ try {
1886
+ const root = host.attachShadow({ mode: "open" });
1887
+ root.appendChild(host.ownerDocument.importNode(tpl.content, true));
1888
+ tpl.remove();
1889
+ root.querySelectorAll("template[shadowrootmode]").forEach((t) => {
1890
+ if (t.parentElement) attachDeclarativeShadow(t.parentElement);
1891
+ });
1892
+ return true;
1893
+ } catch {
1894
+ return false;
1895
+ }
1896
+ }
1897
+ function ssrHostRef(el) {
1898
+ if (el) attachDeclarativeShadow(el);
1899
+ }
1783
1900
  function SsrHost({ ssr }) {
1784
1901
  return /* @__PURE__ */ jsx(
1785
1902
  "div",
1786
1903
  {
1904
+ ref: ssrHostRef,
1787
1905
  id: "pb-experience-root",
1788
1906
  "data-pb-experience-mount": "",
1789
1907
  "data-pb-ssr": ssr.experimentId,
1790
1908
  style: { display: "block", boxSizing: "border-box", maxWidth: "100%" },
1791
1909
  suppressHydrationWarning: true,
1792
1910
  dangerouslySetInnerHTML: { __html: ssrHostInnerHtml(ssr.snapshot, ssr.page) }
1793
- }
1911
+ },
1912
+ `${ssr.experimentId}:${ssr.armId}:${ssr.page.t}:${ssr.page.h}`
1794
1913
  );
1795
1914
  }
1796
1915
  function PlaybookSlot(props) {
1797
- const { ssr } = props;
1916
+ const ssr = renderable(props.ssr);
1798
1917
  if (typeof props.name === "string") {
1799
1918
  const key = props.name;
1800
1919
  if (!isSlotKey(key)) return null;
@@ -3417,4 +3536,4 @@ function trackAddToCartLines(lines, cartLines, source) {
3417
3536
  }
3418
3537
  }
3419
3538
 
3420
- 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, PlaybookSections, PlaybookSlot, PlaybookSsrHead, SECTION_SLOTS, SESSION_VISITOR_COOKIE, SLOT_REPORT_SAMPLE_RATE, SLOT_REPORT_URL, SSR_SLOT_ATTR, SSR_SLOT_NAMES, STANDARD_EVENTS, TRUEVAULT_CONSENT_COOKIE, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, armSlot, 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, isSlotKey, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, renderedSlotKeys, reportPageSlots, revealScript, sanitizeManifestPages, sanitizeRuleset, sectionSlotKey, setNextAddSource, shopifyCustomerPrivacyConsent, slotFromSelector, slotMatches, slotSelector, ssrHostInnerHtml, ssrUrl, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
3539
+ 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, PREVIEW_ATTEMPT_BUDGET_MS, PREVIEW_CODE_COOKIE, PREVIEW_FETCH_BUDGET_MS, PlaybookAAExposure, PlaybookBoundary, PlaybookCloakHead, PlaybookDebugPanel, PlaybookExposure, PlaybookHead, PlaybookProvider, PlaybookRoot, PlaybookSections, PlaybookSlot, PlaybookSsrHead, SECTION_SLOTS, SESSION_VISITOR_COOKIE, SLOT_REPORT_SAMPLE_RATE, SLOT_REPORT_URL, SSR_SLOT_ATTR, SSR_SLOT_NAMES, STANDARD_EVENTS, TRUEVAULT_CONSENT_COOKIE, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, armSlot, 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, isSlotKey, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, renderedSlotKeys, reportPageSlots, revealScript, sanitizeManifestPages, sanitizeRuleset, sectionSlotKey, setNextAddSource, shopifyCustomerPrivacyConsent, slotFromSelector, slotMatches, slotSelector, ssrHostInnerHtml, ssrUrl, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heyplaybook/hydrogen",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "Playbook store-edit tests for Shopify Hydrogen storefronts: server-side assignment, consent-gated visitor cookie, in-view exposures and cart attribution.",
5
5
  "license": "MIT",
6
6
  "author": "Pack Digital Inc.",