@heyplaybook/hydrogen 0.6.0 → 0.7.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
@@ -479,6 +479,137 @@ declare function playbookHeadSnippet(cloak: PlaybookCloakConfig | null | undefin
479
479
  /** The same nodes as an HTML string, for a non-React head. '' when untargeted. */
480
480
  declare function playbookHeadSnippetHtml(cloak: PlaybookCloakConfig | null | undefined, options?: PlaybookHeadSnippetOptions): string;
481
481
 
482
+ interface SsrSnapshotNode {
483
+ id: string;
484
+ html: string;
485
+ css: string;
486
+ mt?: number;
487
+ mb?: number;
488
+ }
489
+ interface SsrSnapshot {
490
+ v: number;
491
+ nodes: SsrSnapshotNode[];
492
+ }
493
+ interface SsrArm {
494
+ id: string;
495
+ w: number;
496
+ c: 0 | 1;
497
+ x: string | null;
498
+ a: {
499
+ s: string;
500
+ p: 'before' | 'after' | 'prepend' | 'append';
501
+ f?: string;
502
+ } | null;
503
+ hide: string[];
504
+ }
505
+ interface SsrExperiment {
506
+ id: string;
507
+ ok: 0 | 1;
508
+ why?: string;
509
+ seed: string;
510
+ hv: number;
511
+ settled: string | null;
512
+ arms: SsrArm[];
513
+ aud?: unknown;
514
+ }
515
+ interface SsrDoc {
516
+ keys: Record<string, number[]>;
517
+ prefixes: Array<[string, number[]]>;
518
+ exps: SsrExperiment[];
519
+ }
520
+ interface SsrPayload {
521
+ doc: SsrDoc;
522
+ snapshots: Record<string, SsrSnapshot>;
523
+ /** 0.7.1: the arm a valid `?pb=` preview code names (only when one was sent). */
524
+ preview?: SsrPreview;
525
+ }
526
+ /** 0.7.1: a `?pb=` preview code's arm, as the platform resolved it (shop-scoped, unexpired). */
527
+ interface SsrPreview {
528
+ code: string;
529
+ experimentId: string;
530
+ armId: string;
531
+ experienceId: string | null;
532
+ testName: string;
533
+ armLabel: string;
534
+ pages: string[];
535
+ expiresAt: string;
536
+ arm: SsrArm;
537
+ snapshot: SsrSnapshot | null;
538
+ /** Non-null = the platform can't server-render this arm (the browser preview covers it). */
539
+ why: string | null;
540
+ }
541
+ declare function ssrUrl(platformUrl: string, shopDomain: string): string;
542
+ /** The shop's SSR doc, or null when the read isn't healthy (then: cloak only). Never throws. */
543
+ declare function getSsrPayload(args: {
544
+ platformUrl: string;
545
+ shopDomain: string;
546
+ waitUntil?: (p: Promise<unknown>) => void;
547
+ fetchImpl?: typeof fetch;
548
+ }): Promise<SsrPayload | null>;
549
+ /**
550
+ * The arm index for `seed` + `id` over `weights` (coverage 1), or -1. GrowthBook
551
+ * v2: `fnv32a(fnv32a(seed + id) + "") % 10000 / 10000`; weights that don't sum
552
+ * to ~1 are replaced by equal weights. Same as the embed's `pbBucket`.
553
+ */
554
+ declare function bucketIndex(seed: string, id: string, weights: readonly number[]): number;
555
+ interface SsrDecision {
556
+ experimentId: string;
557
+ armId: string;
558
+ experienceId: string | null;
559
+ /** How the arm was chosen. `preview` = a `?pb=` code named it (0.7.1). */
560
+ idSource: 'prior' | 'settled' | 'roll' | 'preview';
561
+ arm: SsrArm;
562
+ snapshot: SsrSnapshot | null;
563
+ page: {
564
+ t: string;
565
+ h: string;
566
+ };
567
+ /** 0.7.1: set for a preview-code render — nothing is assigned or recorded. */
568
+ preview?: {
569
+ code: string;
570
+ testName: string;
571
+ armLabel: string;
572
+ };
573
+ }
574
+ type SsrOutcome = {
575
+ decision: SsrDecision;
576
+ } | {
577
+ skip: string;
578
+ };
579
+ /**
580
+ * The server's arm for this page, or why it can't decide (→ cloak). Pure.
581
+ * `consent` = the request's analytics consent as the SDK would read it.
582
+ */
583
+ declare function decideSsr(input: {
584
+ payload: SsrPayload;
585
+ pageKey: string;
586
+ cookies: Record<string, string | undefined>;
587
+ consent: 'allowed' | 'denied' | 'unknown';
588
+ /**
589
+ * The id to roll on when the long-lived ids can't be used: the package's own
590
+ * visitor id for this request (`_pb_visitor_id`, or the session-scoped
591
+ * `_pb_session_vid` while consent isn't granted). Stable across page loads,
592
+ * so a visitor without consent keeps one arm, and no new cookie is written.
593
+ */
594
+ fallbackVisitorId?: string | null;
595
+ nowSec?: number;
596
+ }): SsrOutcome;
597
+ /**
598
+ * The host's inner HTML: a Declarative Shadow DOM tree identical in structure
599
+ * to the embed's `build()`, so `ssr-adopt.ts` finds and adopts it. The node
600
+ * markup was sanitized by the platform (ssr-doc.ts uses the import sanitizer);
601
+ * it is the trust boundary for this `innerHTML`, as for the embed's.
602
+ */
603
+ declare function ssrHostInnerHtml(snapshot: SsrSnapshot, page: {
604
+ t: string;
605
+ h: string;
606
+ }): string;
607
+ /** Does this slot serve the decision's anchor? Exact selector + position match. */
608
+ declare function slotMatches(d: SsrDecision, slot: {
609
+ anchor: string;
610
+ position?: string;
611
+ }): boolean;
612
+
482
613
  /** The env keys the kit reads (all optional). */
483
614
  interface PlaybookEnv {
484
615
  PUBLIC_PLAYBOOK_SHOP_ID?: string;
@@ -519,6 +650,18 @@ interface CreatePlaybookContextOptions {
519
650
  * targets (`loaderData().cloak`, `playbookHeadSnippet`). Default `true`.
520
651
  */
521
652
  cloak?: boolean;
653
+ /**
654
+ * 0.7.0: the `<PlaybookSlot>`s this store renders (anchor selector +
655
+ * position, exactly as the slot props). On a page an all-traffic test
656
+ * targets, `loaderData()` picks the visitor's arm on the server and returns
657
+ * it as `ssr` when one of these slots serves the arm's anchor (or the arm is
658
+ * the original page); the cloak then stays off for that page. Empty/absent =
659
+ * no server render, the 0.6.0 cloak only.
660
+ */
661
+ ssrSlots?: ReadonlyArray<{
662
+ anchor: string;
663
+ position?: 'before' | 'after' | 'prepend' | 'append';
664
+ }>;
522
665
  /**
523
666
  * 0.6.0: the storefront DOMAIN the targeting manifest is keyed by (its
524
667
  * `?shop=`; the Playbook UUID doesn't work there). Overrides
@@ -548,6 +691,13 @@ interface PlaybookLoaderData {
548
691
  targetedPage: string | null;
549
692
  /** 0.6.0: pass to `playbookHeadSnippet(cloak, {nonce})`. Null = no cloak. */
550
693
  cloak: PlaybookCloakConfig | null;
694
+ /**
695
+ * 0.7.0: the visitor's server-rendered arm for `<PlaybookSsrHead>` /
696
+ * `<PlaybookSlot>`, or null (no test here, or it falls back to the cloak).
697
+ */
698
+ ssr: SsrDecision | null;
699
+ /** 0.7.0: why there's no `ssr` on a targeted page (debugging), else null. */
700
+ ssrSkip: string | null;
551
701
  }
552
702
  interface PlaybookRequestContext {
553
703
  readonly shopId: string | null;
@@ -591,7 +741,7 @@ interface PlaybookRequestContext {
591
741
  */
592
742
  finalize(response: Response): Promise<Response>;
593
743
  }
594
- declare function createPlaybookContext({ request, env, waitUntil, shopId: shopIdOption, platformUrl: platformUrlOption, disabled: disabledOption, consentRequired, consent, experienceAttribution, cloak: cloakOption, shopDomain: shopDomainOption, apiBase: apiBaseOption, fetchImpl, }: CreatePlaybookContextOptions): PlaybookRequestContext;
744
+ declare function createPlaybookContext({ request, env, waitUntil, shopId: shopIdOption, platformUrl: platformUrlOption, disabled: disabledOption, consentRequired, consent, experienceAttribution, cloak: cloakOption, ssrSlots, shopDomain: shopDomainOption, apiBase: apiBaseOption, fetchImpl, }: CreatePlaybookContextOptions): PlaybookRequestContext;
595
745
  /**
596
746
  * Wrapper form: creates the context, runs the store's handler with it, then
597
747
  * finalizes whatever response the handler returns (incl. a redirect built
@@ -663,6 +813,27 @@ declare function targetPageKey(pathname: string): string | null;
663
813
  */
664
814
  declare function matchTargetedPage(pages: readonly string[] | null | undefined, pathname: string): string | null;
665
815
 
816
+ /**
817
+ * `window.__pbSsr` (so the SDK adopts the arm and reports it as shown) and the
818
+ * arm's theme-section hides, before first paint. Renders nothing without a
819
+ * decision.
820
+ */
821
+ declare function PlaybookSsrHead({ ssr, nonce }: {
822
+ ssr: SsrDecision | null | undefined;
823
+ nonce?: string;
824
+ }): react_jsx_runtime.JSX.Element | null;
825
+ /**
826
+ * The server-rendered arm, placed by the store where the test's anchor is.
827
+ * Renders only when the decision's arm targets exactly this anchor + position;
828
+ * otherwise nothing (and the SDK renders as usual).
829
+ */
830
+ declare function PlaybookSlot({ ssr, anchor, position, }: {
831
+ ssr: SsrDecision | null | undefined;
832
+ /** The CSS selector the test anchors to, exactly as Playbook stores it. */
833
+ anchor: string;
834
+ position?: 'before' | 'after' | 'prepend' | 'append';
835
+ }): react_jsx_runtime.JSX.Element | null;
836
+
666
837
  /**
667
838
  * Store-specific "why not in test" text for the QA panel. Return a string to
668
839
  * show it (it wins over the generic reason), or null to fall back to the
@@ -1203,4 +1374,4 @@ declare function inNamespace(hashValue: string, namespace: [string, number, numb
1203
1374
  declare function chooseVariation(n: number, ranges: VariationRange[]): number;
1204
1375
  declare function getBucketRanges(numVariations: number, coverage: number | undefined, weights?: number[]): VariationRange[];
1205
1376
 
1206
- 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, type PlaybookServerConsent, type PlaybookServerResult, type PlaybookState, type PlaybookStoreContext, type PlaybookTestRule, type PlaybookTestStatus, type PlaybookVariant, type PlaybookVisitorType, type RulesetSource, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, type StandardEvent, TRUEVAULT_CONSENT_COOKIE, type TrackScope, type TrackedEntry, type TrueVaultConsentOptions, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, assignTest, buildHeadSnippet, cartHasPlaybookAttribute, chooseVariation, consentFromAnalytics, createCartAttributeReader, createCartAttributeSync, createCartAttributeWriter, createPlaybook, createPlaybookContext, createPlaybookProxyHandler, createTrueVaultConsent, debugPanelAllowed, declareConsentRequired, detectDevice, detectGeo, experienceVisitorIdFromCookies, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getTargetedPages, getTrackedLog, hasPlaybookParams, hasSentExposure, hash, inNamespace, isAnalyticsConsentGranted, isKillSwitchOn, isPreviewHost, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, revealScript, sanitizeManifestPages, sanitizeRuleset, setNextAddSource, shopifyCustomerPrivacyConsent, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
1377
+ 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, type PlaybookServerConsent, type PlaybookServerResult, PlaybookSlot, PlaybookSsrHead, type PlaybookState, type PlaybookStoreContext, type PlaybookTestRule, type PlaybookTestStatus, type PlaybookVariant, type PlaybookVisitorType, type RulesetSource, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, type SsrDecision, type SsrOutcome, type SsrPayload, type StandardEvent, TRUEVAULT_CONSENT_COOKIE, type TrackScope, type TrackedEntry, type TrueVaultConsentOptions, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, assignTest, bucketIndex, buildHeadSnippet, cartHasPlaybookAttribute, chooseVariation, consentFromAnalytics, createCartAttributeReader, createCartAttributeSync, createCartAttributeWriter, createPlaybook, createPlaybookContext, createPlaybookProxyHandler, createTrueVaultConsent, debugPanelAllowed, decideSsr, declareConsentRequired, detectDevice, detectGeo, experienceVisitorIdFromCookies, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getSsrPayload, getTargetedPages, getTrackedLog, hasPlaybookParams, hasSentExposure, hash, inNamespace, isAnalyticsConsentGranted, isKillSwitchOn, isPreviewHost, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, revealScript, sanitizeManifestPages, sanitizeRuleset, setNextAddSource, shopifyCustomerPrivacyConsent, slotMatches, ssrHostInnerHtml, ssrUrl, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
package/dist/index.js CHANGED
@@ -1072,6 +1072,207 @@ function hasOwnedPreviewParams(search) {
1072
1072
  return OWNED_PARAM_RE.test(search || "");
1073
1073
  }
1074
1074
 
1075
+ // src/ssr.ts
1076
+ var SSR_SNAPSHOT_VERSION = 1;
1077
+ function ssrUrl(platformUrl, shopDomain) {
1078
+ const url = new URL("/api/storefront/ssr", platformUrl);
1079
+ url.searchParams.set("shop", shopDomain);
1080
+ return url.toString();
1081
+ }
1082
+ function sanitizeSsrPayload(json) {
1083
+ if (!json || typeof json !== "object") return null;
1084
+ const j = json;
1085
+ const doc = j.doc;
1086
+ if (!doc || typeof doc !== "object") return null;
1087
+ if (!doc.keys || typeof doc.keys !== "object" || !Array.isArray(doc.prefixes) || !Array.isArray(doc.exps)) return null;
1088
+ const snapshots = j.snapshots && typeof j.snapshots === "object" ? j.snapshots : {};
1089
+ const p = j.preview;
1090
+ const preview = p && typeof p === "object" && typeof p.experimentId === "string" && typeof p.armId === "string" && Array.isArray(p.pages) && p.arm ? p : void 0;
1091
+ return { doc, snapshots, ...preview ? { preview } : {} };
1092
+ }
1093
+ var ssrFetcher = createCachedJsonFetcher({ label: "ssr doc", sanitize: sanitizeSsrPayload });
1094
+ var HEALTHY2 = /* @__PURE__ */ new Set(["memory", "stale", "fetched"]);
1095
+ async function getSsrPayload(args) {
1096
+ try {
1097
+ const { value, source } = await ssrFetcher.getWithSource({
1098
+ url: ssrUrl(args.platformUrl, args.shopDomain),
1099
+ waitUntil: args.waitUntil,
1100
+ fetchImpl: args.fetchImpl
1101
+ });
1102
+ return value && HEALTHY2.has(source) ? value : null;
1103
+ } catch {
1104
+ return null;
1105
+ }
1106
+ }
1107
+ var PREVIEW_CODE_RE = /^[0-9A-HJKMNP-TV-Z]{4,8}$/;
1108
+ function previewCodeFromRequestUrl(url) {
1109
+ const raw = url.searchParams.get("pb");
1110
+ if (!raw) return null;
1111
+ const code = raw.trim().toUpperCase();
1112
+ return PREVIEW_CODE_RE.test(code) ? code : null;
1113
+ }
1114
+ var PREVIEW_FETCH_BUDGET_MS = 1500;
1115
+ async function getSsrPreviewPayload(args) {
1116
+ const controller = new AbortController();
1117
+ const timer = setTimeout(() => controller.abort(), PREVIEW_FETCH_BUDGET_MS);
1118
+ try {
1119
+ const url = new URL(ssrUrl(args.platformUrl, args.shopDomain));
1120
+ url.searchParams.set("pb", args.code);
1121
+ const res = await (args.fetchImpl ?? fetch)(url.toString(), {
1122
+ headers: { accept: "application/json" },
1123
+ signal: controller.signal
1124
+ });
1125
+ if (!res.ok) return null;
1126
+ return sanitizeSsrPayload(await res.json());
1127
+ } catch {
1128
+ return null;
1129
+ } finally {
1130
+ clearTimeout(timer);
1131
+ }
1132
+ }
1133
+ function decidePreviewSsr(payload, pageKey, matchesPage) {
1134
+ const p = payload.preview;
1135
+ if (!p) return { skip: "preview-unresolved" };
1136
+ if (p.why) return { skip: `preview-${p.why}` };
1137
+ if (!pageKey || !matchesPage(p.pages)) return { skip: "preview-not-this-page" };
1138
+ if (p.experienceId && (!p.snapshot || p.snapshot.v !== SSR_SNAPSHOT_VERSION || !p.snapshot.nodes?.length)) {
1139
+ return { skip: "preview-no-snapshot" };
1140
+ }
1141
+ const [t, h = ""] = pageKey.split(":");
1142
+ return {
1143
+ decision: {
1144
+ experimentId: p.experimentId,
1145
+ armId: p.armId,
1146
+ experienceId: p.experienceId,
1147
+ idSource: "preview",
1148
+ arm: p.arm,
1149
+ snapshot: p.snapshot,
1150
+ page: { t, h },
1151
+ preview: { code: p.code, testName: p.testName, armLabel: p.armLabel }
1152
+ }
1153
+ };
1154
+ }
1155
+ function fnv32a(s2) {
1156
+ let h = 2166136261;
1157
+ for (let i = 0; i < s2.length; i++) {
1158
+ h ^= s2.charCodeAt(i);
1159
+ h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);
1160
+ }
1161
+ return h >>> 0;
1162
+ }
1163
+ function bucketIndex(seed, id, weights) {
1164
+ const k = weights.length;
1165
+ if (!k) return -1;
1166
+ const n = fnv32a(String(fnv32a(seed + id))) % 1e4 / 1e4;
1167
+ const total = weights.reduce((a, b) => a + b, 0);
1168
+ const w = total < 0.99 || total > 1.01 ? weights.map(() => 1 / k) : weights;
1169
+ let cum = 0;
1170
+ for (let i = 0; i < k; i++) {
1171
+ const start = cum;
1172
+ cum += w[i];
1173
+ if (n >= start && n < start + w[i]) return i;
1174
+ }
1175
+ return -1;
1176
+ }
1177
+ function priorArmFromExposure(raw, experimentId, nowSec = Math.floor(Date.now() / 1e3)) {
1178
+ if (!raw) return null;
1179
+ let v = raw;
1180
+ if (v.includes("%")) {
1181
+ try {
1182
+ v = decodeURIComponent(v);
1183
+ } catch {
1184
+ }
1185
+ }
1186
+ v = v.slice(0, 4096);
1187
+ const RE = /^[A-Za-z0-9-]{1,64}$/;
1188
+ for (const part of v.split("_")) {
1189
+ const f = part.split(".");
1190
+ if (f.length !== 4 || f[0] !== experimentId || !RE.test(f[1])) continue;
1191
+ const s2 = parseInt(f[3], 36);
1192
+ if (Number.isFinite(s2) && nowSec - s2 <= EXPOSURE_TTL_DAYS * 86400) return f[1];
1193
+ }
1194
+ return null;
1195
+ }
1196
+ function experimentsForPage(doc, pageKey) {
1197
+ const out = new Set(doc.keys[pageKey] ?? []);
1198
+ for (const [prefix, idx] of doc.prefixes) if (pageKey.startsWith(prefix)) idx.forEach((i) => out.add(i));
1199
+ return [...out];
1200
+ }
1201
+ function decideSsr(input) {
1202
+ const { payload, pageKey, cookies, consent } = input;
1203
+ const idx = experimentsForPage(payload.doc, pageKey);
1204
+ if (idx.length === 0) return { skip: "no-test" };
1205
+ if (idx.length > 1) return { skip: "multi-test" };
1206
+ const exp = payload.doc.exps[idx[0]];
1207
+ if (!exp) return { skip: "no-test" };
1208
+ if (exp.ok !== 1) return { skip: `ineligible:${exp.why || "unknown"}` };
1209
+ if (exp.aud) return { skip: "audience" };
1210
+ if (!exp.settled && exp.hv !== 2 && exp.hv !== 3) return { skip: "hash-version" };
1211
+ const arms = exp.arms || [];
1212
+ let arm;
1213
+ let idSource = "roll";
1214
+ if (exp.settled) {
1215
+ arm = arms.find((a) => a.id === exp.settled);
1216
+ idSource = "settled";
1217
+ } else {
1218
+ const allowed = consent === "allowed";
1219
+ const prior = allowed ? priorArmFromExposure(cookies[EXPOSURE_COOKIE], exp.id, input.nowSec) : null;
1220
+ if (prior) {
1221
+ arm = arms.find((a) => a.id === prior && a.w > 0);
1222
+ if (arm) idSource = "prior";
1223
+ }
1224
+ if (!arm) {
1225
+ const vid = (allowed ? experienceVisitorIdFromCookies(cookies) : null) ?? input.fallbackVisitorId ?? null;
1226
+ if (!vid) return { skip: "no-visitor-id" };
1227
+ const i = bucketIndex(exp.seed, vid, arms.map((a) => a.w));
1228
+ arm = i >= 0 ? arms[i] : arms.find((a) => a.c === 1) ?? arms[0];
1229
+ }
1230
+ }
1231
+ if (!arm) return { skip: "no-arm" };
1232
+ const [t, h = ""] = pageKey.split(":");
1233
+ const snapshot = arm.x ? payload.snapshots[arm.x] ?? null : null;
1234
+ if (arm.x && (!snapshot || snapshot.v !== SSR_SNAPSHOT_VERSION || !snapshot.nodes?.length)) {
1235
+ return { skip: "no-snapshot" };
1236
+ }
1237
+ return { decision: { experimentId: exp.id, armId: arm.id, experienceId: arm.x, idSource, arm, snapshot, page: { t, h } } };
1238
+ }
1239
+ var BASE = ":host{all:initial}*,*::before,*::after{box-sizing:border-box}[data-pb-experience-root]{font-family:system-ui,-apple-system,sans-serif;color:#111827;display:flex;flex-direction:column}img,video{max-width:100%;display:block}";
1240
+ var HTML_BASE = ":host{display:block}*,*::before,*::after{box-sizing:border-box}";
1241
+ var escAttr = (s2) => s2.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1242
+ var escStyle = (s2) => s2.replace(/<\/(style)/gi, "<\\/$1");
1243
+ function ssrHostInnerHtml(snapshot, page) {
1244
+ const nodes = snapshot.nodes.map((nd) => {
1245
+ const style = [
1246
+ "display:block",
1247
+ "width:100%",
1248
+ typeof nd.mt === "number" ? `margin-top:${nd.mt}px` : "",
1249
+ typeof nd.mb === "number" ? `margin-bottom:${nd.mb}px` : ""
1250
+ ].filter(Boolean).join(";");
1251
+ return `<div data-proto-id="${escAttr(nd.id)}" data-proto-type="html" style="${style}"><template shadowrootmode="open"><style>${escStyle(HTML_BASE + "\n" + (nd.css || ""))}</style><div class="pb-html-root" data-pb-page-type="${escAttr(page.t === "home" ? "home" : page.t)}" data-pb-handle="${escAttr(page.h)}">${nd.html || ""}</div></template></div>`;
1252
+ }).join("");
1253
+ return `<template shadowrootmode="open"><style data-pb-ssr-snapshot>${BASE}</style><div data-pb-experience-root data-pb-ssr-snapshot>${nodes}</div></template>`;
1254
+ }
1255
+ function ssrStateScript(d) {
1256
+ const state = {
1257
+ experimentId: d.experimentId,
1258
+ armId: d.armId,
1259
+ experienceId: d.experienceId,
1260
+ placed: !!d.experienceId,
1261
+ reason: d.experienceId ? null : "control",
1262
+ idSource: d.idSource,
1263
+ placedAt: null,
1264
+ server: true,
1265
+ // A preview render: the SDK keeps it without resolving or recording.
1266
+ ...d.preview ? { preview: d.preview } : {}
1267
+ };
1268
+ return `window.__pbSsr=${JSON.stringify(state).replace(/</g, "\\u003c")};`;
1269
+ }
1270
+ function slotMatches(d, slot) {
1271
+ const a = d.arm.a;
1272
+ if (!a) return false;
1273
+ return a.s.trim() === slot.anchor.trim() && a.p === (slot.position ?? "after");
1274
+ }
1275
+
1075
1276
  // src/request-context.ts
1076
1277
  var FINALIZE_WAIT_MS = 2e3;
1077
1278
  var FINALIZE_REDIRECT_WAIT_MS = 0;
@@ -1092,6 +1293,7 @@ function createPlaybookContext({
1092
1293
  consent,
1093
1294
  experienceAttribution = true,
1094
1295
  cloak: cloakOption = true,
1296
+ ssrSlots = [],
1095
1297
  shopDomain: shopDomainOption,
1096
1298
  apiBase: apiBaseOption,
1097
1299
  fetchImpl
@@ -1193,6 +1395,48 @@ function createPlaybookContext({
1193
1395
  }
1194
1396
  return cloakPromise;
1195
1397
  };
1398
+ let ssrRendered = false;
1399
+ let ssrPromise = null;
1400
+ const ssrFor = (cloak) => {
1401
+ if (!ssrPromise) {
1402
+ ssrPromise = (async () => {
1403
+ if (ssrSlots.length === 0) return { ssr: null, skip: null };
1404
+ const url = new URL(request.url);
1405
+ const code = request.method === "GET" && !url.pathname.endsWith(".data") ? previewCodeFromRequestUrl(url) : null;
1406
+ if (code && shopId) {
1407
+ const shopDomain = normalizeDomain(shopDomainOption ?? str(e.PUBLIC_PLAYBOOK_SHOP_DOMAIN) ?? url.hostname);
1408
+ if (!shopDomain) return { ssr: null, skip: "preview-no-shop" };
1409
+ const payload2 = await getSsrPreviewPayload({ platformUrl, shopDomain, code, fetchImpl });
1410
+ if (!payload2) return { ssr: null, skip: "preview-unavailable" };
1411
+ const pageKey = targetPageKey(url.pathname);
1412
+ const out2 = decidePreviewSsr(payload2, pageKey, (pages) => matchTargetedPage(pages, url.pathname) !== null);
1413
+ if ("skip" in out2) return { ssr: null, skip: out2.skip };
1414
+ const d2 = out2.decision;
1415
+ if (d2.experienceId && !ssrSlots.some((s2) => slotMatches(d2, s2))) return { ssr: null, skip: "preview-no-slot" };
1416
+ ssrRendered = true;
1417
+ return { ssr: d2, skip: null };
1418
+ }
1419
+ if (!cloak) return { ssr: null, skip: null };
1420
+ const payload = await getSsrPayload({ platformUrl, shopDomain: cloak.shopDomain, waitUntil, fetchImpl });
1421
+ if (!payload) return { ssr: null, skip: "doc-unavailable" };
1422
+ const cookies = parseCookies(request.headers.get("cookie"));
1423
+ const own = (await get())?.state?.visitorId ?? null;
1424
+ const out = decideSsr({
1425
+ payload,
1426
+ pageKey: cloak.targetedPage,
1427
+ cookies,
1428
+ consent: cartConsent(cookies),
1429
+ fallbackVisitorId: own
1430
+ });
1431
+ if ("skip" in out) return { ssr: null, skip: out.skip };
1432
+ const d = out.decision;
1433
+ if (d.experienceId && !ssrSlots.some((s2) => slotMatches(d, s2))) return { ssr: null, skip: "no-slot" };
1434
+ ssrRendered = true;
1435
+ return { ssr: d, skip: null };
1436
+ })().catch(() => ({ ssr: null, skip: "error" }));
1437
+ }
1438
+ return ssrPromise;
1439
+ };
1196
1440
  const append = (headers, cookies) => {
1197
1441
  for (const cookie of cookies) headers.append("Set-Cookie", cookie);
1198
1442
  };
@@ -1203,11 +1447,15 @@ function createPlaybookContext({
1203
1447
  get,
1204
1448
  async loaderData() {
1205
1449
  const [result, cloak] = await Promise.all([get(), cloakFor()]);
1450
+ const { ssr, skip } = await ssrFor(cloak);
1206
1451
  return {
1207
1452
  playbook: result?.state ?? null,
1208
1453
  hasPlaybookParams: hasPlaybookParams(request.url),
1209
1454
  targetedPage: cloak?.targetedPage ?? null,
1210
- cloak
1455
+ // A server-rendered arm needs no hide: its design is already in the HTML.
1456
+ cloak: ssr ? null : cloak,
1457
+ ssr,
1458
+ ssrSkip: ssr ? null : skip
1211
1459
  };
1212
1460
  },
1213
1461
  cartAttribute() {
@@ -1243,6 +1491,7 @@ function createPlaybookContext({
1243
1491
  async appendCookies(headers) {
1244
1492
  try {
1245
1493
  append(headers, await cookiesFor(FINALIZE_WAIT_MS));
1494
+ if (ssrRendered) headers.set("Cache-Control", "private, no-store");
1246
1495
  } catch {
1247
1496
  }
1248
1497
  },
@@ -1252,13 +1501,15 @@ function createPlaybookContext({
1252
1501
  const cookies = await cookiesFor(
1253
1502
  isRedirect ? FINALIZE_REDIRECT_WAIT_MS : FINALIZE_WAIT_MS
1254
1503
  );
1255
- if (!cookies.length) return response;
1504
+ if (!cookies.length && !ssrRendered) return response;
1256
1505
  try {
1257
1506
  append(response.headers, cookies);
1507
+ if (ssrRendered) response.headers.set("Cache-Control", "private, no-store");
1258
1508
  return response;
1259
1509
  } catch {
1260
1510
  const headers = new Headers(response.headers);
1261
1511
  append(headers, cookies);
1512
+ if (ssrRendered) headers.set("Cache-Control", "private, no-store");
1262
1513
  return new Response(response.body, {
1263
1514
  status: response.status,
1264
1515
  statusText: response.statusText,
@@ -1456,6 +1707,32 @@ function playbookHeadSnippetHtml(cloak, options = {}) {
1456
1707
  const attrs = Object.entries(parts.sdk.attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
1457
1708
  return `<style id="${CLOAK_STYLE_ID}"${nonce}>${parts.css}</style><script${nonce}>${parts.script}</script><script id="${EXPERIENCE_SDK_SCRIPT_ID}" src="${escapeAttr(parts.sdk.src)}"${nonce} async${attrs}></script>`;
1458
1709
  }
1710
+ function PlaybookSsrHead({ ssr, nonce }) {
1711
+ if (!ssr) return null;
1712
+ const hide = ssr.experienceId ? (ssr.arm.hide || []).map((s2) => `${s2}{display:none!important}`).join("") : "";
1713
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1714
+ /* @__PURE__ */ jsx("script", { nonce, "data-pb-ssr-state": "", dangerouslySetInnerHTML: { __html: ssrStateScript(ssr) } }),
1715
+ hide ? /* @__PURE__ */ jsx("style", { id: "pb-ssr-hide", nonce, dangerouslySetInnerHTML: { __html: escStyle(hide) } }) : null
1716
+ ] });
1717
+ }
1718
+ function PlaybookSlot({
1719
+ ssr,
1720
+ anchor,
1721
+ position = "after"
1722
+ }) {
1723
+ if (!ssr || !ssr.experienceId || !ssr.snapshot || !slotMatches(ssr, { anchor, position })) return null;
1724
+ return /* @__PURE__ */ jsx(
1725
+ "div",
1726
+ {
1727
+ id: "pb-experience-root",
1728
+ "data-pb-experience-mount": "",
1729
+ "data-pb-ssr": ssr.experimentId,
1730
+ style: { display: "block", boxSizing: "border-box", maxWidth: "100%" },
1731
+ suppressHydrationWarning: true,
1732
+ dangerouslySetInnerHTML: { __html: ssrHostInnerHtml(ssr.snapshot, ssr.page) }
1733
+ }
1734
+ );
1735
+ }
1459
1736
  var PlaybookBoundary = class extends Component {
1460
1737
  state = { failed: false };
1461
1738
  static getDerivedStateFromError() {
@@ -2926,4 +3203,4 @@ function trackAddToCartLines(lines, cartLines, source) {
2926
3203
  }
2927
3204
  }
2928
3205
 
2929
- export { AA_SITEWIDE_TEST, CART_SYNC_IDLE_MS, CART_VISITOR_ATTRIBUTE, CLOAK_MAX_MS, CLOAK_STYLE_ID, CONSENT_LOADED_EVENTS, CONTROL_ARM, DEFAULT_DATALAYER_EVENT, DEFAULT_EVENT_URL, DEFAULT_EXPERIENCE_SDK_URL, DEFAULT_EXPOSURE_URL, DEFAULT_PLATFORM_URL, DEFAULT_PROXY_ENDPOINT, DEFAULT_SDK_URL, DEFAULT_SUPPORTED_EVENTS, EXPERIENCE_SDK_SCRIPT_ID, EXPERIENCE_VISITOR_CART_ATTRIBUTE, EXPOSURE_CART_ATTRIBUTE, EXPOSURE_COOKIE, LEGACY_VISITOR_COOKIE, MAX_WRITES_PER_CART, PlaybookAAExposure, PlaybookBoundary, PlaybookCloakHead, PlaybookDebugPanel, PlaybookExposure, PlaybookHead, PlaybookProvider, PlaybookRoot, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, TRUEVAULT_CONSENT_COOKIE, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, assignTest, buildHeadSnippet, cartHasPlaybookAttribute, chooseVariation, consentFromAnalytics, createCartAttributeReader, createCartAttributeSync, createCartAttributeWriter, createPlaybook, createPlaybookContext, createPlaybookProxyHandler, createTrueVaultConsent, debugPanelAllowed, declareConsentRequired, detectDevice, detectGeo, experienceVisitorIdFromCookies, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getTargetedPages, getTrackedLog, hasPlaybookParams, hasSentExposure, hash, inNamespace, isAnalyticsConsentGranted, isKillSwitchOn, isPreviewHost, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, revealScript, sanitizeManifestPages, sanitizeRuleset, setNextAddSource, shopifyCustomerPrivacyConsent, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
3206
+ export { AA_SITEWIDE_TEST, CART_SYNC_IDLE_MS, CART_VISITOR_ATTRIBUTE, CLOAK_MAX_MS, CLOAK_STYLE_ID, CONSENT_LOADED_EVENTS, CONTROL_ARM, DEFAULT_DATALAYER_EVENT, DEFAULT_EVENT_URL, DEFAULT_EXPERIENCE_SDK_URL, DEFAULT_EXPOSURE_URL, DEFAULT_PLATFORM_URL, DEFAULT_PROXY_ENDPOINT, DEFAULT_SDK_URL, DEFAULT_SUPPORTED_EVENTS, EXPERIENCE_SDK_SCRIPT_ID, EXPERIENCE_VISITOR_CART_ATTRIBUTE, EXPOSURE_CART_ATTRIBUTE, EXPOSURE_COOKIE, LEGACY_VISITOR_COOKIE, MAX_WRITES_PER_CART, PlaybookAAExposure, PlaybookBoundary, PlaybookCloakHead, PlaybookDebugPanel, PlaybookExposure, PlaybookHead, PlaybookProvider, PlaybookRoot, PlaybookSlot, PlaybookSsrHead, SESSION_VISITOR_COOKIE, STANDARD_EVENTS, TRUEVAULT_CONSENT_COOKIE, VISITOR_COOKIE, addedLinesFrom, analyticsConsentFromCookie, assignTest, bucketIndex, buildHeadSnippet, cartHasPlaybookAttribute, chooseVariation, consentFromAnalytics, createCartAttributeReader, createCartAttributeSync, createCartAttributeWriter, createPlaybook, createPlaybookContext, createPlaybookProxyHandler, createTrueVaultConsent, debugPanelAllowed, decideSsr, declareConsentRequired, detectDevice, detectGeo, experienceVisitorIdFromCookies, getBucketRanges, getConsentState, getEqualWeights, getServerTrackedLog, getSessionContext, getSsrPayload, getTargetedPages, getTrackedLog, hasPlaybookParams, hasSentExposure, hash, inNamespace, isAnalyticsConsentGranted, isKillSwitchOn, isPreviewHost, manifestUrl, matchTargetedPage, matchesPathPrefix, mergeAttributes, normalizeExposureList, onConsentChange, onConsentLoaded, playbookBackendUrl, playbookCartAttribute, playbookHeadSnippet, playbookHeadSnippetHtml, playbookTrack, prefetchRuleset, reconcileExperienceCartAttributes, reconcilePlaybookCartAttribute, revealScript, sanitizeManifestPages, sanitizeRuleset, setNextAddSource, shopifyCustomerPrivacyConsent, slotMatches, ssrHostInnerHtml, ssrUrl, subscribeTrackedLog, syncVisitorId, takeAddSource, targetPageKey, trackAddToCart, trackAddToCartLines, trueVaultDecision, truevaultConsent, useAnalyticsAllowed, usePageEngagement, usePlaybookConsent, usePlaybookExposure, usePlaybookInteraction, usePlaybookState, usePlaybookVariant, usePreviewParamRedirect, visitorInRunningTest, visitorSeedScript, waitForConsentAPI, withPlaybook, withPlaybookCartAttribute };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heyplaybook/hydrogen",
3
- "version": "0.6.0",
3
+ "version": "0.7.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.",