@heyplaybook/hydrogen 0.3.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -21,6 +21,14 @@ import { ReactNode, Component } from 'react';
21
21
  * Client: `window`/`document` touched at CALL time only (safe to import on the
22
22
  * server). Server: `analyticsConsentFromCookie` reads Shopify's own
23
23
  * `_tracking_consent` cookie, the same signal the checkout pixel trusts.
24
+ *
25
+ * 0.5.0: a present API whose `consentStatus` is a string other than
26
+ * `'loaded'` is still resolving (pending). Before it loads, the API answers
27
+ * with a no-data fallback (every `*Allowed()` true, no banner owed) that
28
+ * would otherwise read as granted in a region that requires a banner. An
29
+ * API with no `consentStatus` field at all (older script versions) is read
30
+ * as before. The decision carried by `visitorConsentCollected`'s
31
+ * `event.detail` is remembered and used until the API itself has loaded.
24
32
  */
25
33
  type ConsentState = 'granted' | 'denied' | 'pending' | 'absent';
26
34
  /**
@@ -34,6 +42,15 @@ declare function waitForConsentAPI(): Promise<void>;
34
42
  /** Granted right now? Closed while resolving a known-present API; open if absent. */
35
43
  declare function isAnalyticsConsentGranted(): boolean;
36
44
  declare function getConsentState(): ConsentState;
45
+ /**
46
+ * Events after which a present API may have finished loading the visitor's
47
+ * consent (`consentStatus` → 'loaded'): Shopify's consent data loaded, or
48
+ * Hydrogen loaded the Customer Privacy script. `visitorConsentCollected` is
49
+ * handled by `onConsentChange` (decision read from `event.detail`).
50
+ */
51
+ declare const CONSENT_LOADED_EVENTS: readonly ["consentTrackingApiLoaded", "shopifyCustomerPrivacyApiLoaded"];
52
+ /** Call `cb` after each "consent loaded" event (document and window). */
53
+ declare function onConsentLoaded(cb: () => void): () => void;
37
54
  /** Subscribe to `visitorConsentCollected` (decision read from event.detail). */
38
55
  declare function onConsentChange(cb: (granted: boolean) => void): () => void;
39
56
  /**
@@ -45,34 +62,50 @@ declare function onConsentChange(cb: (granted: boolean) => void): () => void;
45
62
  */
46
63
  declare function analyticsConsentFromCookie(raw: string | undefined): ConsentState;
47
64
 
48
- /**
49
- * Pluggable analytics-consent sources. ONE decision function per adapter is
50
- * used on BOTH sides — the server reads it from the request (cookie + GPC
51
- * header), the client from `document.cookie` + `navigator` — so the server's
52
- * `serverConsent` and the client's live consent can never disagree on the same
53
- * inputs (0.2.1 resolved a TrueVault store to `pending` on the server and to
54
- * `absent`/open on the client).
55
- *
56
- * Without an adapter the package keeps 0.2.1 behaviour: Shopify's Customer
57
- * Privacy API on the client and its `_tracking_consent` cookie on the server.
58
- * Use an adapter when the store's CMP does NOT feed that API (TrueVault
59
- * Polaris on Sand Cloud never sets `window.Shopify.customerPrivacy` or
60
- * `_tracking_consent`).
61
- *
62
- * Pass the SAME adapter to `createPlaybookContext({consent})` and
63
- * `<PlaybookRoot consent>`.
64
- */
65
-
66
- interface PlaybookConsentAdapter {
65
+ /** SERVER half: the decision for one request. */
66
+ interface PlaybookServerConsent {
67
67
  /** Stable name, for debug output. */
68
68
  readonly id: string;
69
69
  /** SERVER: the decision for this request. Never throws. */
70
70
  fromRequest(request: Request): ConsentState;
71
+ }
72
+ /** CLIENT half: the live decision in the browser. */
73
+ interface PlaybookClientConsent {
74
+ /** Stable name, for debug output. */
75
+ readonly id: string;
71
76
  /** CLIENT: the decision right now. `window`/`document` read at call time. */
72
77
  read(): ConsentState;
73
78
  /** CLIENT: call `onChange` whenever the decision may have changed. */
74
79
  subscribe(onChange: () => void): () => void;
75
80
  }
81
+ /** Both halves from one decision function (unchanged since 0.3.0). */
82
+ interface PlaybookConsentAdapter extends PlaybookServerConsent, PlaybookClientConsent {
83
+ }
84
+ /**
85
+ * Map a store's own analytics answer to a `ConsentState`, so a store adapter
86
+ * doesn't hand-roll tri-state logic:
87
+ * `true` / `'granted'` / `'yes'` → granted, `false` / `'denied'` / `'no'` →
88
+ * denied, anything else (null, undefined, `'unknown'`, `''`) → pending
89
+ * (closed). Never `absent`: a store that wires an adapter has a consent
90
+ * system, so "no answer" must not fail open.
91
+ */
92
+ declare function consentFromAnalytics(value: boolean | string | null | undefined): ConsentState;
93
+ /**
94
+ * The built-in browser source: Shopify's Customer Privacy API (what
95
+ * `<PlaybookRoot>` uses when no client consent is passed).
96
+ *
97
+ * - Pending while the API is resolving, and while it reports a
98
+ * `consentStatus` other than `'loaded'` (its pre-load fallback answers
99
+ * "everything allowed").
100
+ * - Re-read when the consent data or the privacy script loads
101
+ * (`consentTrackingApiLoaded`, `shopifyCustomerPrivacyApiLoaded`).
102
+ * - On `visitorConsentCollected`, the decision comes from `event.detail`
103
+ * (the API's methods may not exist yet when it fires).
104
+ * - Fails OPEN (`absent`) only when no consent system is present at all.
105
+ *
106
+ * Module-level state (one listener, one wait) is shared by every subscriber.
107
+ */
108
+ declare const shopifyCustomerPrivacyConsent: PlaybookClientConsent;
76
109
  /** TrueVault Polaris's banner cookie (the one Sand Cloud's Blotout/analytics read). */
77
110
  declare const TRUEVAULT_CONSENT_COOKIE = "polaris_consent_settings";
78
111
  interface TrueVaultConsentOptions {
@@ -141,14 +174,14 @@ interface PlaybookRuleset {
141
174
  /** Why a visitor got this arm (debug/QA; mirrors the platform core's AssignReason). */
142
175
  type PlaybookAssignReason = 'preview'
143
176
  /** Another test is being previewed on this request: this one serves control. */
144
- | 'preview-isolated' | 'override' | 'winner' | 'not-running' | 'no-visitor' | 'targeting-device' | 'targeting-visitor-type' | 'namespace' | 'hash-error' | 'coverage' | 'assigned' | 'unknown-test';
177
+ | 'preview-isolated' | 'winner' | 'not-running' | 'no-visitor' | 'targeting-device' | 'targeting-visitor-type' | 'namespace' | 'hash-error' | 'coverage' | 'assigned' | 'unknown-test';
145
178
  interface PlaybookAssignment {
146
179
  arm: string;
147
180
  status: PlaybookTestStatus;
148
181
  reason: PlaybookAssignReason;
149
182
  /** True only when the visitor was bucketed into a RUNNING test. */
150
183
  inTest: boolean;
151
- /** True when the arm comes from a verified `pb_preview` token or a QA override. */
184
+ /** True when the arm comes from a verified `pb_preview` token. */
152
185
  forced: boolean;
153
186
  config: Record<string, unknown>;
154
187
  /** Evaluated on the client against the current route (SPA navigation). */
@@ -162,8 +195,9 @@ interface PlaybookState {
162
195
  visitorType: PlaybookVisitorType;
163
196
  device: PlaybookDevice;
164
197
  /**
165
- * Analytics consent as the server saw it (`_tracking_consent` cookie). The
166
- * client re-reads the live Customer Privacy API before any beacon.
198
+ * Analytics consent as the server saw it (the server consent source, default
199
+ * `_tracking_consent`). The client re-reads its own live source before any
200
+ * beacon.
167
201
  */
168
202
  serverConsent: 'granted' | 'denied' | 'pending' | 'absent';
169
203
  /** The store declared a late-loading CMP (closed until it answers). */
@@ -200,16 +234,6 @@ interface CreatePlaybookOptions {
200
234
  /** Keeps a background ruleset refresh alive after the response (Workers). */
201
235
  waitUntil?: (p: Promise<unknown>) => void;
202
236
  fetchImpl?: typeof fetch;
203
- /**
204
- * Arms to force regardless of status/targeting (QA). Forced views never
205
- * expose. The CALLER decides when overrides are trusted (e.g. preview hosts
206
- * only) — this module applies whatever it is given.
207
- *
208
- * Precedence per test: a `pb_preview` token on THIS request > an override
209
- * from this request (`source: 'request'`) > a `pb_preview` carried by the
210
- * session cookie > a session override > natural assignment.
211
- */
212
- overrides?: PlaybookOverride[];
213
237
  /**
214
238
  * The store's CMP may load after first paint (headless, e.g. TrueVault
215
239
  * Polaris): with no `_tracking_consent` cookie yet, treat consent as pending
@@ -218,15 +242,11 @@ interface CreatePlaybookOptions {
218
242
  */
219
243
  consentRequired?: boolean;
220
244
  /**
221
- * Consent source when the store's CMP doesn't feed Shopify's Customer Privacy
222
- * API (e.g. `truevaultConsent`). Replaces the `_tracking_consent` read; pass
223
- * the SAME adapter to the client (`PlaybookRoot consent`).
245
+ * Server consent source when the store's CMP doesn't feed Shopify's
246
+ * `_tracking_consent` cookie (e.g. `truevaultConsent`, or a store's own
247
+ * `PlaybookServerConsent`). Replaces the `_tracking_consent` read.
224
248
  */
225
- consent?: PlaybookConsentAdapter;
226
- }
227
- interface PlaybookOverride extends PlaybookPreview {
228
- /** `request`: set by this request's URL; `session`: replayed from a cookie. */
229
- source?: 'request' | 'session';
249
+ consent?: PlaybookServerConsent;
230
250
  }
231
251
  interface PlaybookServerResult {
232
252
  /** Serializable; pass to the client through loader data. */
@@ -249,7 +269,7 @@ declare function detectGeo(headers: Headers): {
249
269
  region: string | null;
250
270
  };
251
271
  declare function detectDevice(userAgent: string | null): PlaybookDevice;
252
- declare function createPlaybook({ shopId, platformUrl, request, waitUntil, fetchImpl, overrides, consentRequired, consent: consentAdapter, }: CreatePlaybookOptions): Promise<PlaybookServerResult>;
272
+ declare function createPlaybook({ shopId, platformUrl, request, waitUntil, fetchImpl, consentRequired, consent: consentAdapter, }: CreatePlaybookOptions): Promise<PlaybookServerResult>;
253
273
 
254
274
  /**
255
275
  * Ruleset fetch with an in-memory (per-isolate) cache.
@@ -265,6 +285,11 @@ declare function createPlaybook({ shopId, platformUrl, request, waitUntil, fetch
265
285
  * shop. Inside it no render touches the network or waits: each one gets the
266
286
  * last good copy, or control. The first render after the window retries.
267
287
  * This keeps a hanging platform from costing every page request its budget.
288
+ *
289
+ * 0.6.0: the cache itself is `createCachedJsonFetcher`, generic over the
290
+ * payload, so the targeting manifest (`./targeting`) shares the exact same
291
+ * fresh / stale / budget / backoff / warn-once behaviour. The ruleset is its
292
+ * first user; nothing about the ruleset path changed.
268
293
  */
269
294
 
270
295
  /**
@@ -395,11 +420,72 @@ declare function withPlaybookCartAttribute<T extends object>(input: T | null | u
395
420
  }[];
396
421
  };
397
422
 
423
+ /** Hard ceiling on the hide, in ms. The cloak can be shorter, never longer. */
424
+ declare const CLOAK_MAX_MS = 1500;
425
+ /** The bundle `playbook.js` injects on Hydrogen (CDN sibling of the loader). */
426
+ declare const DEFAULT_EXPERIENCE_SDK_URL = "https://cdn.heyplaybook.com/experience-sdk.js";
427
+ declare const CLOAK_STYLE_ID = "pb-cloak";
428
+ declare const EXPERIENCE_SDK_SCRIPT_ID = "pb-experience-sdk";
429
+ /** What the server decided for this request (`loaderData().cloak`). */
430
+ interface PlaybookCloakConfig {
431
+ /** This path's manifest page key (`product:<handle>`, `home:`, …). */
432
+ targetedPage: string;
433
+ /** `data-pb-shop`: the storefront domain the manifest was read for. */
434
+ shopDomain: string;
435
+ /** `data-pb-api-base`: where the SDK calls the resolver (app proxy). */
436
+ apiBase: string;
437
+ }
438
+ interface PlaybookHeadSnippetOptions {
439
+ /** The store's CSP nonce, put on all three nodes. */
440
+ nonce?: string;
441
+ /** Override the bundle URL (absolute https). Default: the CDN. */
442
+ sdkUrl?: string;
443
+ /** Adds `data-pb-consent="required"` (see the module comment). */
444
+ consentRequired?: boolean;
445
+ /** Shorter hide than 1.5s. Clamped to 100…`CLOAK_MAX_MS`. */
446
+ maxHideMs?: number;
447
+ }
448
+ interface HeadSnippetParts {
449
+ css: string;
450
+ script: string;
451
+ sdk: {
452
+ src: string;
453
+ attrs: Record<string, string>;
454
+ };
455
+ nonce?: string;
456
+ }
457
+ /**
458
+ * Pure: the snippet's parts, or null when nothing should render (no targeted
459
+ * page, or a config missing its shop / api base).
460
+ */
461
+ declare function buildHeadSnippet(cloak: PlaybookCloakConfig | null | undefined, options?: PlaybookHeadSnippetOptions): HeadSnippetParts | null;
462
+ /**
463
+ * The head nodes as React elements. Renders ONCE: later prop changes (a
464
+ * client-side navigation revalidating the root loader) are ignored, so the
465
+ * hydrated nodes stay exactly as the server sent them.
466
+ */
467
+ declare const PlaybookCloakHead: react.NamedExoticComponent<PlaybookHeadSnippetOptions & {
468
+ cloak: PlaybookCloakConfig | null | undefined;
469
+ }>;
470
+ /**
471
+ * The cloak + early inject for `<head>`. Place it EARLY in <head> (before the
472
+ * stylesheets and before any `playbook.js` tag):
473
+ *
474
+ * {playbookHeadSnippet(data.cloak, {nonce})}
475
+ *
476
+ * Returns null when the page isn't targeted.
477
+ */
478
+ declare function playbookHeadSnippet(cloak: PlaybookCloakConfig | null | undefined, options?: PlaybookHeadSnippetOptions): react_jsx_runtime.JSX.Element | null;
479
+ /** The same nodes as an HTML string, for a non-React head. '' when untargeted. */
480
+ declare function playbookHeadSnippetHtml(cloak: PlaybookCloakConfig | null | undefined, options?: PlaybookHeadSnippetOptions): string;
481
+
398
482
  /** The env keys the kit reads (all optional). */
399
483
  interface PlaybookEnv {
400
484
  PUBLIC_PLAYBOOK_SHOP_ID?: string;
401
485
  PLAYBOOK_PLATFORM_URL?: string;
402
486
  PLAYBOOK_TESTS_DISABLED?: string;
487
+ /** 0.6.0: storefront domain for the targeting manifest (see `shopDomain`). */
488
+ PUBLIC_PLAYBOOK_SHOP_DOMAIN?: string;
403
489
  }
404
490
  interface CreatePlaybookContextOptions {
405
491
  request: Request;
@@ -414,9 +500,38 @@ interface CreatePlaybookContextOptions {
414
500
  disabled?: boolean;
415
501
  /** See `createPlaybook({consentRequired})` (Shopify consent path only). */
416
502
  consentRequired?: boolean;
417
- /** Consent adapter (e.g. `truevaultConsent`); same one as the client. */
418
- consent?: PlaybookConsentAdapter;
419
- overrides?: PlaybookOverride[];
503
+ /**
504
+ * Server consent source: a `PlaybookServerConsent` (e.g. a store's CMS
505
+ * session record) or a full adapter (e.g. `truevaultConsent`, then pass the
506
+ * same one to the client). Default: Shopify's `_tracking_consent` cookie.
507
+ */
508
+ consent?: PlaybookServerConsent;
509
+ /**
510
+ * 0.6.0: `reconcileCartAttributes` also puts back the EXPERIENCE-test cart
511
+ * attributes (`pb_exp__`, `pb_vid__`) when another script wiped them, for a
512
+ * visitor the browser SDK has shown an experience test. Fill-only; see
513
+ * `./experience-attribution`. Default `true`; `false` restores 0.5.0.
514
+ */
515
+ experienceAttribution?: boolean;
516
+ /**
517
+ * 0.6.0: read the platform's targeting manifest in `loaderData()` so the
518
+ * head can cloak + early-inject on a page an all-traffic experience test
519
+ * targets (`loaderData().cloak`, `playbookHeadSnippet`). Default `true`.
520
+ */
521
+ cloak?: boolean;
522
+ /**
523
+ * 0.6.0: the storefront DOMAIN the targeting manifest is keyed by (its
524
+ * `?shop=`; the Playbook UUID doesn't work there). Overrides
525
+ * `env.PUBLIC_PLAYBOOK_SHOP_DOMAIN`; default the request's hostname, the
526
+ * same fallback `playbook.js` uses on a headless store.
527
+ */
528
+ shopDomain?: string | null;
529
+ /**
530
+ * 0.6.0: the experience SDK's `data-pb-api-base`. Default
531
+ * `<request origin>/apps/playbook` (the store's app-proxy route), which is
532
+ * what `playbook.js` passes when it's loaded from `/apps/playbook/sdk`.
533
+ */
534
+ apiBase?: string | null;
420
535
  fetchImpl?: typeof fetch;
421
536
  }
422
537
  interface PlaybookLoaderData {
@@ -424,6 +539,15 @@ interface PlaybookLoaderData {
424
539
  playbook: PlaybookState | null;
425
540
  /** For `<PlaybookHead hasPlaybookParams>` (anti-flicker). */
426
541
  hasPlaybookParams: boolean;
542
+ /**
543
+ * 0.6.0: this path's manifest page key (`product:<handle>`, `home:`, …)
544
+ * when an all-traffic experience test targets it, else null. Null on any
545
+ * manifest failure or timeout, on `pbk`/`_pv`/preview visits, and never
546
+ * set by utm params alone.
547
+ */
548
+ targetedPage: string | null;
549
+ /** 0.6.0: pass to `playbookHeadSnippet(cloak, {nonce})`. Null = no cloak. */
550
+ cloak: PlaybookCloakConfig | null;
427
551
  }
428
552
  interface PlaybookRequestContext {
429
553
  readonly shopId: string | null;
@@ -433,6 +557,30 @@ interface PlaybookRequestContext {
433
557
  get(): Promise<PlaybookServerResult | null>;
434
558
  loaderData(): Promise<PlaybookLoaderData>;
435
559
  cartAttribute(): CartAttribute | null;
560
+ /**
561
+ * The visitor id this request may stamp on the cart as `_pb_vid`: analytics
562
+ * consent granted (or no consent system and `consentRequired` off), read
563
+ * from `_pb_visitor_id` then `_pb_session_vid`. Never minted; null when
564
+ * disabled, without consent, or without an id. No ruleset fetch.
565
+ */
566
+ cartVisitorId(): string | null;
567
+ /**
568
+ * The cart's full attribute list with `_pb_vid` added, corrected or removed
569
+ * (consent withdrawn / no id), every other attribute kept; `null` when the
570
+ * cart is already right, or when Playbook is disabled (the cart is left
571
+ * untouched). Call after EVERY cart action with the cart as it now stands.
572
+ *
573
+ * 0.6.0: also fills a missing `pb_exp__` / `pb_vid__` (experience tests) for
574
+ * a visitor with an experience exposure, and removes them on an explicit
575
+ * denial. Still one list, so still at most one write.
576
+ */
577
+ reconcileCartAttributes(current: ReadonlyArray<{
578
+ key: string;
579
+ value?: string | null;
580
+ }> | null | undefined): {
581
+ key: string;
582
+ value: string;
583
+ }[] | null;
436
584
  /** APPEND this request's Playbook cookies to `headers`. Never throws. */
437
585
  appendCookies(headers: Headers): Promise<void>;
438
586
  /**
@@ -443,7 +591,7 @@ interface PlaybookRequestContext {
443
591
  */
444
592
  finalize(response: Response): Promise<Response>;
445
593
  }
446
- declare function createPlaybookContext({ request, env, waitUntil, shopId: shopIdOption, platformUrl: platformUrlOption, disabled: disabledOption, consentRequired, consent, overrides, fetchImpl, }: CreatePlaybookContextOptions): PlaybookRequestContext;
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;
447
595
  /**
448
596
  * Wrapper form: creates the context, runs the store's handler with it, then
449
597
  * finalizes whatever response the handler returns (incl. a redirect built
@@ -476,6 +624,70 @@ interface PlaybookHeadProps {
476
624
  }
477
625
  declare function PlaybookHead({ shopId, apiEndpoint, sdkUrl, hasPlaybookParams, state, visitorId, nonce, }: PlaybookHeadProps): react_jsx_runtime.JSX.Element | null;
478
626
 
627
+ declare function manifestUrl(platformUrl: string, shopDomain: string): string;
628
+ /**
629
+ * The manifest's `pages` as clean strings, or null when the envelope is not
630
+ * a manifest. A manifest without `pages` (an older platform) is `[]` — valid,
631
+ * nothing targeted. Non-string entries are dropped.
632
+ */
633
+ declare function sanitizeManifestPages(value: unknown): string[] | null;
634
+ /**
635
+ * The shop's all-traffic page keys, or `null` when the read is not healthy
636
+ * (failure, timeout, backoff, last-good during an outage) — the caller must
637
+ * then NOT hide. Never throws.
638
+ */
639
+ declare function getTargetedPages({ platformUrl, shopDomain, waitUntil, fetchImpl, }: {
640
+ platformUrl: string;
641
+ shopDomain: string;
642
+ waitUntil?: (p: Promise<unknown>) => void;
643
+ fetchImpl?: typeof fetch;
644
+ }): Promise<{
645
+ pages: string[] | null;
646
+ source: RulesetSource;
647
+ }>;
648
+ /**
649
+ * The manifest page key for a storefront path — a byte-for-byte port of
650
+ * `targetPageKey` in shared/src/targeting/index.ts (the same function the
651
+ * `playbook.js` loader and the experience SDK use):
652
+ * `product:<handle>` (also under `/collections/<c>/products/<p>`),
653
+ * `collection:<handle>`, `home:`, `page:<handle>` for `/pages/<handle>`,
654
+ * `page:cart`, `page:<path>` for any other storefront path; null for an
655
+ * untargetable path. A leading locale segment (`/en-us`, `/fr`) and a
656
+ * trailing slash are stripped; handles are URI-decoded and lowercased.
657
+ */
658
+ declare function targetPageKey(pathname: string): string | null;
659
+ /**
660
+ * This path's page key when the manifest serves it to all traffic, else null.
661
+ * Same matching as `manifestMatchesPage` (shared): exact key, or a key ending
662
+ * in `*` by prefix (`"*"`, `"product:*"`, `"product:the-weekender-in-*"`).
663
+ */
664
+ declare function matchTargetedPage(pages: readonly string[] | null | undefined, pathname: string): string | null;
665
+
666
+ /**
667
+ * Store-specific "why not in test" text for the QA panel. Return a string to
668
+ * show it (it wins over the generic reason), or null to fall back to the
669
+ * generic reason. Runs in the browser; must not throw (errors are ignored).
670
+ */
671
+ type PlaybookDebugExplain = (testKey: string, assignment: PlaybookAssignment, pathname: string) => string | null | undefined;
672
+ /** `<PlaybookRoot debug>` options. */
673
+ interface PlaybookDebugOptions {
674
+ /** Force allow/deny; default: preview hosts or a verified preview token. */
675
+ allowed?: boolean;
676
+ /** Test keys this storefront has code for (others are labelled as such). */
677
+ implementedTests?: string[];
678
+ /** Store-specific eligibility text (e.g. "not a towel product"). */
679
+ explain?: PlaybookDebugExplain;
680
+ }
681
+ /** May the panel open on this page? */
682
+ declare function debugPanelAllowed(state: PlaybookState | null | undefined, hostname: string, allowed?: boolean): boolean;
683
+ declare function PlaybookDebugPanel({ state, location, allowed, implementedTests, explain, }: {
684
+ state: PlaybookState | null | undefined;
685
+ location: {
686
+ pathname: string;
687
+ search?: string;
688
+ };
689
+ } & PlaybookDebugOptions): react_jsx_runtime.JSX.Element | null;
690
+
479
691
  /**
480
692
  * The standard events — ONE taxonomy for every store (GROWTH-TESTS.md "The
481
693
  * standard events"). Store-specific interactions are `variant_interaction`
@@ -491,10 +703,13 @@ interface PlaybookStoreContext {
491
703
  isLoggedIn?: boolean | null;
492
704
  }
493
705
  /**
494
- * GA4 / GTM forwarding of exposures. `false` turns it off; `eventName`
495
- * renames the event (default `view_experiment`).
706
+ * GA4 / GTM forwarding of exposures. OFF by default since 0.5.0 (a store that
707
+ * also runs another testing tool's `view_experiment` — e.g. Pack tests — would
708
+ * get two tools' experiments mixed in GA4). `true` or `{}` turns it on;
709
+ * `{eventName}` turns it on under another event name (default
710
+ * `view_experiment`); `false` keeps it off.
496
711
  */
497
- type PlaybookDataLayerOption = false | {
712
+ type PlaybookDataLayerOption = boolean | {
498
713
  eventName?: string;
499
714
  };
500
715
  declare const DEFAULT_DATALAYER_EVENT = "view_experiment";
@@ -572,8 +787,16 @@ interface PlaybookRootProps {
572
787
  replace: true;
573
788
  preventScrollReset: true;
574
789
  }) => void;
790
+ /**
791
+ * Client `_pb_vid` sync. `null` turns it off — do that when the server owns
792
+ * `_pb_vid` (`context.playbook.reconcileCartAttributes` in the cart action).
793
+ */
575
794
  cart?: PlaybookCartAdapter | null;
576
- consent?: PlaybookConsentAdapter;
795
+ /**
796
+ * Browser consent: a `PlaybookClientConsent` or a full adapter. Default:
797
+ * Shopify's Customer Privacy API (`shopifyCustomerPrivacyConsent`).
798
+ */
799
+ consent?: PlaybookClientConsent;
577
800
  storeContext?: PlaybookStoreContext;
578
801
  /**
579
802
  * The store's own CMS/editor preview (e.g. Pack customizer): no cart write,
@@ -582,13 +805,18 @@ interface PlaybookRootProps {
582
805
  editorPreview?: boolean;
583
806
  /** Render the `aa-sitewide` sentinel (default true; inert without that test). */
584
807
  aaSentinel?: boolean;
585
- /** QA panel: force allow/deny, and the test keys this store has code for. */
586
- debug?: {
587
- allowed?: boolean;
588
- implementedTests?: string[];
589
- };
590
- /** GA4 `view_experiment` dataLayer push per exposure (default on). */
808
+ /**
809
+ * QA panel: force allow/deny, the test keys this store has code for, and
810
+ * `explain` for store-specific "why not in test" text.
811
+ */
812
+ debug?: PlaybookDebugOptions;
813
+ /**
814
+ * GA4 `view_experiment` dataLayer push per exposure. OFF by default since
815
+ * 0.5.0; `true` / `{eventName}` turns it on.
816
+ */
591
817
  dataLayer?: PlaybookDataLayerOption;
818
+ /** A verified preview shows its arm even off-target (default false). */
819
+ previewIgnoresTargeting?: boolean;
592
820
  /** Observe cart-sync decisions (debug/logging). */
593
821
  onCartSyncEvent?: (event: CartSyncEvent) => void;
594
822
  exposureUrl?: string;
@@ -606,21 +834,7 @@ declare function visitorInRunningTest(state: PlaybookState | null | undefined):
606
834
  declare function PlaybookAAExposure({ testKey }: {
607
835
  testKey?: string;
608
836
  }): react_jsx_runtime.JSX.Element;
609
- declare function PlaybookRoot({ state, location, navigate, cart, consent, storeContext, editorPreview, aaSentinel, debug, dataLayer, onCartSyncEvent, exposureUrl, eventUrl, supportedEvents, children, }: PlaybookRootProps): react_jsx_runtime.JSX.Element;
610
-
611
- /** May the panel open on this page? */
612
- declare function debugPanelAllowed(state: PlaybookState | null | undefined, hostname: string, allowed?: boolean): boolean;
613
- declare function PlaybookDebugPanel({ state, location, allowed, implementedTests, }: {
614
- state: PlaybookState | null | undefined;
615
- location: {
616
- pathname: string;
617
- search?: string;
618
- };
619
- /** Force allow/deny; default: preview hosts or a verified preview token. */
620
- allowed?: boolean;
621
- /** Test keys this storefront has code for (others are labelled as such). */
622
- implementedTests?: string[];
623
- }): react_jsx_runtime.JSX.Element | null;
837
+ declare function PlaybookRoot({ state, location, navigate, cart, consent, storeContext, editorPreview, aaSentinel, debug, dataLayer, previewIgnoresTargeting, onCartSyncEvent, exposureUrl, eventUrl, supportedEvents, children, }: PlaybookRootProps): react_jsx_runtime.JSX.Element;
624
838
 
625
839
  interface Props {
626
840
  /** For the console warning only. */
@@ -700,9 +914,10 @@ interface PlaybookVariant {
700
914
  * state, so SSR and hydration render the same arm (no flicker).
701
915
  *
702
916
  * `eligible: false` (e.g. "not a towel product") → control, not in test.
703
- * A forced arm (QA `pb_force` or a `pb_preview` link) skips status and traffic
704
- * split but still respects targeting: a towel arm forced on a towel page must
705
- * not follow the session onto a bedding page.
917
+ * A forced arm (a verified `pb_preview` link) skips status and traffic split
918
+ * but still respects targeting: a towel arm forced on a towel page must not
919
+ * follow the session onto a bedding page. A store that wants previews to show
920
+ * the arm everywhere passes `<PlaybookRoot previewIgnoresTargeting>`.
706
921
  */
707
922
  declare function usePlaybookVariant(testKey: string, { eligible }?: {
708
923
  eligible?: boolean;
@@ -737,7 +952,7 @@ declare function usePreviewParamRedirect(location: {
737
952
  hash: string;
738
953
  }): string | null;
739
954
 
740
- declare function PlaybookProvider({ state, pathname, exposureUrl, eventUrl, supportedEvents, storeContext, consent: consentAdapter, dataLayer, children, }: {
955
+ declare function PlaybookProvider({ state, pathname, exposureUrl, eventUrl, supportedEvents, storeContext, consent: consentAdapter, dataLayer, previewIgnoresTargeting, children, }: {
741
956
  state: PlaybookState | null | undefined;
742
957
  /** Current route pathname (re-render on navigation so path targeting updates). */
743
958
  pathname: string;
@@ -748,15 +963,24 @@ declare function PlaybookProvider({ state, pathname, exposureUrl, eventUrl, supp
748
963
  /** Market / locale / login state, for the exposure context. */
749
964
  storeContext?: PlaybookStoreContext;
750
965
  /**
751
- * Consent source for stores whose CMP doesn't feed Shopify's Customer
752
- * Privacy API. Must be the SAME adapter the server used.
966
+ * Browser consent source (a `PlaybookClientConsent`, or a full adapter).
967
+ * Default: Shopify's Customer Privacy API (`shopifyCustomerPrivacyConsent`).
968
+ * Keep it closed on the same "unknown" states as the server source.
753
969
  */
754
- consent?: PlaybookConsentAdapter;
970
+ consent?: PlaybookClientConsent;
755
971
  /**
756
- * Forward each exposure to `window.dataLayer` as GA4 `view_experiment`
757
- * (default on). `false` disables; `{eventName}` renames.
972
+ * Forward each exposure to `window.dataLayer` as GA4 `view_experiment`.
973
+ * OFF by default since 0.5.0; `true` / `{}` turns it on, `{eventName}`
974
+ * renames it.
758
975
  */
759
976
  dataLayer?: PlaybookDataLayerOption;
977
+ /**
978
+ * A verified preview (`pb_preview`) shows the forced arm even where the
979
+ * test doesn't apply (`eligible: false` or an off-target path). Default
980
+ * false: the forced arm respects targeting, so an arm previewed on a towel
981
+ * page doesn't follow the reviewer onto a bedding page.
982
+ */
983
+ previewIgnoresTargeting?: boolean;
760
984
  children: ReactNode;
761
985
  }): react_jsx_runtime.JSX.Element;
762
986
  /** Component form of `usePlaybookExposure` for wrapping an existing element. */
@@ -870,6 +1094,74 @@ declare function cartHasPlaybookAttribute(attributes: ReadonlyArray<{
870
1094
  key: string;
871
1095
  value?: string | null;
872
1096
  }> | null | undefined, visitorId: string): boolean;
1097
+ /**
1098
+ * The cart's FULL attribute list with `_pb_vid` reconciled to `visitorId`:
1099
+ * added when missing, corrected when stale (or duplicated), removed when
1100
+ * `visitorId` is null (no id, or consent withdrawn). Every other attribute is
1101
+ * kept as-is, in order. Returns `null` when the cart is already right, so the
1102
+ * caller skips the mutation.
1103
+ *
1104
+ * Pure: it never mints an id. Pass the result to a REPLACE-style write
1105
+ * (Hydrogen's `cart.updateAttributes`), which is why the whole list comes
1106
+ * back rather than just `_pb_vid`. A null/empty value on another key is
1107
+ * written back as `''`.
1108
+ */
1109
+ declare function reconcilePlaybookCartAttribute(current: ReadonlyArray<{
1110
+ key: string;
1111
+ value?: string | null;
1112
+ }> | null | undefined, visitorId: string | null | undefined): {
1113
+ key: string;
1114
+ value: string;
1115
+ }[] | null;
1116
+
1117
+ /** The SDK's exposure-list cookie (30 days). */
1118
+ declare const EXPOSURE_COOKIE = "_pb_exp";
1119
+ /** Cart attribute the `orders/paid` webhook decodes as the exposure list. */
1120
+ declare const EXPOSURE_CART_ATTRIBUTE = "pb_exp__";
1121
+ /** Cart attribute carrying the long-lived visitor id the impressions use. */
1122
+ declare const EXPERIENCE_VISITOR_CART_ATTRIBUTE = "pb_vid__";
1123
+ /**
1124
+ * The exposure list from a raw cookie value, re-encoded in the platform's wire
1125
+ * format (malformed and expired entries dropped), or `null` when nothing valid
1126
+ * is left. Pure; `now` is epoch SECONDS.
1127
+ */
1128
+ declare function normalizeExposureList(raw: string | null | undefined, now?: number): string | null;
1129
+ /**
1130
+ * The long-lived visitor id the browser SDK records impressions under, read
1131
+ * from the request's cookies in the SDK's own order (`readBucketingId`):
1132
+ * Shopify's `_y` (the SDK reads it from Server-Timing; the server sees the
1133
+ * cookie itself), then a Shopify client-id cookie (`shopify_client_id`, then
1134
+ * the legacy `_shopify_y`), then Playbook's `_pb_visitor_id`. `null` when none
1135
+ * is present. Call it only with analytics consent.
1136
+ *
1137
+ * Never the session-only `_pb_session_vid`: the SDK can't read it (HttpOnly),
1138
+ * so no impression is ever recorded under it.
1139
+ */
1140
+ declare function experienceVisitorIdFromCookies(cookies: Record<string, string | undefined>): string | null;
1141
+ type ExperienceAttributionConsent = 'allowed' | 'denied' | 'unknown';
1142
+ interface ExperienceAttributionInput {
1143
+ consent: ExperienceAttributionConsent;
1144
+ /** The request's `_pb_exp` cookie, raw. */
1145
+ exposureCookie: string | null | undefined;
1146
+ /** From `experienceVisitorIdFromCookies`. */
1147
+ visitorId: string | null | undefined;
1148
+ /** Epoch seconds (tests). */
1149
+ now?: number;
1150
+ }
1151
+ type Attr = {
1152
+ key: string;
1153
+ value?: string | null;
1154
+ };
1155
+ /**
1156
+ * The cart's FULL attribute list with `pb_exp__` / `pb_vid__` filled in or
1157
+ * removed per the policy above; `null` when the cart should be left as it is.
1158
+ * Every other attribute is kept, in order (a null value becomes `''`, as in
1159
+ * `reconcilePlaybookCartAttribute`). Pure.
1160
+ */
1161
+ declare function reconcileExperienceCartAttributes(current: readonly Attr[] | null | undefined, { consent, exposureCookie, visitorId, now }: ExperienceAttributionInput): {
1162
+ key: string;
1163
+ value: string;
1164
+ }[] | null;
873
1165
 
874
1166
  declare const CONTROL_ARM = "control";
875
1167
  interface AssignInput {
@@ -911,4 +1203,4 @@ declare function inNamespace(hashValue: string, namespace: [string, number, numb
911
1203
  declare function chooseVariation(n: number, ranges: VariationRange[]): number;
912
1204
  declare function getBucketRanges(numVariations: number, coverage: number | undefined, weights?: number[]): VariationRange[];
913
1205
 
914
- export { AA_SITEWIDE_TEST, type AddToCartSource, type AddedLineInput, CART_SYNC_IDLE_MS, CART_VISITOR_ATTRIBUTE, 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_EXPOSURE_URL, DEFAULT_PLATFORM_URL, DEFAULT_PROXY_ENDPOINT, DEFAULT_SDK_URL, DEFAULT_SUPPORTED_EVENTS, LEGACY_VISITOR_COOKIE, MAX_WRITES_PER_CART, PlaybookAAExposure, type PlaybookArm, type PlaybookAssignReason, type PlaybookAssignment, PlaybookBoundary, type PlaybookCartAdapter, type PlaybookConsentAdapter, type PlaybookDataLayerOption, PlaybookDebugPanel, type PlaybookDevice, type PlaybookEnv, PlaybookExposure, PlaybookHead, type PlaybookHeadProps, type PlaybookLoaderData, type PlaybookOverride, type PlaybookPreview, PlaybookProvider, type PlaybookProxyOptions, type PlaybookRequestContext, PlaybookRoot, type PlaybookRootProps, type PlaybookRuleset, 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, 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 };
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 };