@heyplaybook/hydrogen 0.2.1 → 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/README.md CHANGED
@@ -14,6 +14,15 @@ tested element scrolls into view, and tags the cart so orders join the test.
14
14
  and tested against GrowthBook's published vectors. It matches Playbook's platform core
15
15
  exactly, so readouts re-derive the same arms.
16
16
 
17
+ > **Upgrading from 0.3.0?** 0.5.0 has breaking changes: the GA4 `view_experiment`
18
+ > dataLayer push is now **off by default**, and QA `overrides` are gone. See
19
+ > [`MIGRATION.md`](./MIGRATION.md). (There is no 0.4.0: that number was used by an
20
+ > unpublished build.)
21
+ >
22
+ > **Running Pack (or any other) A/B tests on the same store?** Leave the dataLayer push
23
+ > off (the 0.5.0 default; or pass `dataLayer={false}` explicitly). If both tools push
24
+ > `view_experiment`, GTM forwards both into GA4 and their experiments mix in one report.
25
+
17
26
  ## Install
18
27
 
19
28
  ```bash
@@ -21,7 +30,323 @@ npm install @heyplaybook/hydrogen
21
30
  # or: pnpm add @heyplaybook/hydrogen
22
31
  ```
23
32
 
24
- ## Integrate (six steps)
33
+ ## Quickstart: three touchpoints (0.3.0+)
34
+
35
+ The kit moves all of the store wiring into the package. A store adds three things, plus a
36
+ two-line proxy route. Set `PUBLIC_PLAYBOOK_SHOP_ID` first (see [Environment](#1-environment)).
37
+
38
+ ### 1. `server.ts`: one context, finalized on the way out
39
+
40
+ ```ts
41
+ import {createPlaybookContext} from '@heyplaybook/hydrogen';
42
+
43
+ const playbook = createPlaybookContext({request, env, waitUntil});
44
+ // …getLoadContext: () => ({…, playbook})
45
+
46
+ if (session.isPending) response.headers.set('Set-Cookie', await session.commit());
47
+ if (response.status === 404) {
48
+ return playbook.finalize(await storefrontRedirect({request, response, storefront}));
49
+ }
50
+ return playbook.finalize(response);
51
+ ```
52
+
53
+ `finalize` appends (never sets) the visitor cookies, after your session cookie, and also on
54
+ a 404 that `storefrontRedirect` turned into a redirect. A redirect never waits on a
55
+ still-running rules fetch. Prefer one call? `withPlaybook(options, async (playbook) => …)`
56
+ wraps the handler and finalizes whatever it returns.
57
+
58
+ ### 2. Root: `<PlaybookHead>` and `<PlaybookRoot>`
59
+
60
+ ```tsx
61
+ // root loader
62
+ return data({...(await context.playbook.loaderData()) /* playbook, hasPlaybookParams */});
63
+
64
+ // <head>
65
+ <PlaybookHead
66
+ shopId={ENV.PUBLIC_PLAYBOOK_SHOP_ID}
67
+ hasPlaybookParams={hasPlaybookParams}
68
+ state={playbook}
69
+ />
70
+
71
+ // around the app (inside your cart provider)
72
+ const {id, attributes, status} = useCart();
73
+ <PlaybookRoot
74
+ state={playbook}
75
+ location={useLocation()}
76
+ navigate={useNavigate()}
77
+ cart={{cartId: id, attributes, status}}
78
+ >
79
+ <App />
80
+ </PlaybookRoot>
81
+ ```
82
+
83
+ - `PlaybookHead` renders the anti-flicker style (only with Playbook URL params), the reveal
84
+ hook, the visitor-id seed (UUIDs only) and the **legacy `playbook.js` loader**, which runs
85
+ Playbook landing experiences. Pass `nonce` if your store sets a CSP.
86
+ - `PlaybookRoot` renders your children untouched. Everything it adds is invisible and in its
87
+ own error boundary: consent, page engagement, the `_pb_vid` cart attribute, the preview
88
+ redirect, the `aa-sitewide` A/A sentinel, and the QA panel.
89
+ - `cart` is **read only**. The kit writes `_pb_vid` on its own request to your cart endpoint
90
+ (default `/api/cart`; `serverMerges: true` if that endpoint merges attributes itself). It
91
+ never changes your cart status, so it can't block an add to cart.
92
+
93
+ ### 3. The add-to-cart path
94
+
95
+ ```ts
96
+ import {trackAddToCart} from '@heyplaybook/hydrogen';
97
+
98
+ // after a successful add (no user errors)
99
+ trackAddToCart('pdp', {lines: formData /* or the lines array */, cart: data.cart});
100
+ ```
101
+
102
+ Sources: `pdp`, `quick_add`, `cart_upsell`, `cross_sell`, `other`. A shared cart hook that
103
+ can't know the source calls `setNextAddSource(source)` in the UI and passes `undefined`.
104
+
105
+ ### Proxy route
106
+
107
+ ```ts
108
+ // app/routes/apps.playbook.$.tsx
109
+ import {createPlaybookProxyHandler} from '@heyplaybook/hydrogen';
110
+ export const {loader, action} = createPlaybookProxyHandler();
111
+ ```
112
+
113
+ Reads `PLAYBOOK_PLATFORM_URL` from the load context. A slow platform gets a 504 after 5
114
+ seconds instead of holding your worker.
115
+
116
+ ### Server-owned `_pb_vid` (0.5.0, recommended when your cart action can do it)
117
+
118
+ The most robust option: let the cart action own `_pb_vid`, and turn the client sync off
119
+ with `<PlaybookRoot cart={null}>`. After **every** cart action, reconcile against the
120
+ cart as it now stands:
121
+
122
+ ```ts
123
+ // app/routes/($locale).api.cart.tsx, after the action ran
124
+ const next = context.playbook.reconcileCartAttributes(result.cart?.attributes);
125
+ if (result.cart?.id && next) {
126
+ try {
127
+ const updated = await cart.updateAttributes(next, {cartId: result.cart.id});
128
+ if (!updated.userErrors?.length && updated.cart) result = {...result, cart: updated.cart};
129
+ } catch {
130
+ // never fail the cart action that already succeeded
131
+ }
132
+ }
133
+ ```
134
+
135
+ - It **adds** `_pb_vid` when missing, **corrects** a stale one (e.g. a gift-note editor
136
+ writing back an old attribute snapshot), and **removes** it when analytics consent is
137
+ withdrawn. Every other attribute is kept.
138
+ - It returns `null` when the cart is already right (no mutation; normally one write per
139
+ cart), when there's no visitor id (it never mints one), and when Playbook is disabled.
140
+ - `context.playbook.cartVisitorId()` is the consent-gated id on its own, and
141
+ `reconcilePlaybookCartAttribute(attributes, visitorId)` is the pure function underneath.
142
+ - Known gap: the server only runs on a cart action. A shopper who grants consent after their
143
+ last add and goes straight to checkout reaches it without `_pb_vid`.
144
+
145
+ ### Experience tests on the same cart (unreleased, planned 0.6.0)
146
+
147
+ Playbook experience tests (designs rendered by `experience-sdk.js`) join orders
148
+ through two other cart attributes, `pb_exp__` (every test the shopper saw) and
149
+ `pb_vid__` (the visitor id their impressions use). The browser SDK writes them; on
150
+ Hydrogen another script can wipe them. The same `reconcileCartAttributes` call above
151
+ puts them back:
152
+
153
+ - only for a visitor with an experience exposure (a valid `_pb_exp` cookie), so a
154
+ store with no experience test sees no new write;
155
+ - only when a key is missing or empty (the browser's value always wins);
156
+ - removed on an explicit analytics denial, untouched while consent is pending.
157
+
158
+ `createPlaybookContext({experienceAttribution: false})` turns it off.
159
+
160
+ ### Anti-flicker for all-traffic experience tests (unreleased, planned 0.6.0)
161
+
162
+ Without this, a shopper on a page with an all-traffic experience test sees the
163
+ original page first, then the design: `playbook.js` loads, fetches the targeting
164
+ manifest, then injects `experience-sdk.js`. The package can do the manifest check on
165
+ the server and start the SDK from the head instead.
166
+
167
+ `loaderData()` now returns `targetedPage` (this path's page key, e.g.
168
+ `product:ring-1`, or `null`) and `cloak` (the config for the head). Render the
169
+ snippet early in `<head>`, before your stylesheets and before `playbook.js`:
170
+
171
+ ```tsx
172
+ import {playbookHeadSnippet} from '@heyplaybook/hydrogen';
173
+
174
+ // in the root/Document head, with the loader's `cloak` and your CSP nonce
175
+ {playbookHeadSnippet(data.cloak, {nonce, consentRequired: true})}
176
+ ```
177
+
178
+ On a targeted page it renders three nodes: a style that hides the page, a small
179
+ inline script (the `window.__pbCloak` contract the Liquid app embed uses), and
180
+ `experience-sdk.js` with `data-pb-targeted="1"`. Everywhere else it renders nothing.
181
+
182
+ - **Hide only on a manifest page hit.** Never on utm or other params alone. A
183
+ manifest error, a timeout or the 30-second backoff means no hide.
184
+ - **1.5 s maximum.** A timer in the inline script lifts it, plus a CSS-only
185
+ failsafe if no script runs. The SDK lifts it sooner, once it has painted the test
186
+ or decided there's nothing to paint. A failed SDK download lifts it at once.
187
+ - **No double load.** The inline script sets `window.__pbCloak.sdk`; `playbook.js`
188
+ then skips its own inject. The bundle's singleton guard is the backstop.
189
+ - **Skipped** on `pbk` / `_pv` / `_preview` / `pb_mode` / `pbThumb` visits, in an
190
+ iframe and on Playbook preview hosts.
191
+ - **CSP:** pass your nonce; it goes on all three nodes. Your `script-src` must
192
+ allow `https://cdn.heyplaybook.com` (or use `'strict-dynamic'` with the nonce).
193
+ - **Consent:** not gated, by design. Rendering is functional; the SDK gates its own
194
+ impression, cookies and cart attributes. Pass `consentRequired: true` when your
195
+ consent banner loads after first paint, so the SDK waits for it.
196
+
197
+ Manifest settings on `createPlaybookContext`:
198
+
199
+ | Option | Env | Default |
200
+ |---|---|---|
201
+ | `shopDomain` | `PUBLIC_PLAYBOOK_SHOP_DOMAIN` | the request hostname. The manifest is keyed by storefront domain, not the shop UUID |
202
+ | `apiBase` | | `<request origin>/apps/playbook` |
203
+ | `cloak: false` | | on. Turns the manifest read off |
204
+
205
+ The manifest is cached per isolate exactly like the ruleset: 60 s fresh, 300 s
206
+ stale, a 300 ms / 1.5 s render budget, a 30 s backoff after a failure. The kill
207
+ switch and a missing shop id turn it off with everything else.
208
+
209
+ ### Cart attribute at creation
210
+
211
+ Writing `_pb_vid` after the fact can race other attribute writers (Intelligems writes when
212
+ the cart id first appears). Attach it when the cart is created, in your cart action:
213
+
214
+ ```ts
215
+ import {withPlaybookCartAttribute} from '@heyplaybook/hydrogen';
216
+
217
+ case 'Create':
218
+ result = await cart.create(withPlaybookCartAttribute(input, context.playbook.cartAttribute()));
219
+ case 'LinesAdd': // the first add creates the cart
220
+ const attr = context.playbook.cartAttribute();
221
+ result = attr && !cart.getCartId()
222
+ ? await cart.create(withPlaybookCartAttribute({lines}, attr))
223
+ : await cart.addLines(lines);
224
+ ```
225
+
226
+ `cartAttribute()` reads cookies and consent only (no rules fetch on the cart path) and is
227
+ `null` without analytics consent. For a cart that already exists, the client writes once,
228
+ only after the cart has been idle for 3 seconds, only for a visitor in a running test, at
229
+ most 3 times per cart, and it puts back any `_ig*` key the write lost.
230
+
231
+ ### Consent adapters
232
+
233
+ Without one, consent comes from Shopify's Customer Privacy API (client,
234
+ `shopifyCustomerPrivacyConsent`) and the `_tracking_consent` cookie (server).
235
+
236
+ The built-in client source (0.5.0):
237
+
238
+ - is **pending** until the API reports `consentStatus === 'loaded'` (before that, Shopify's
239
+ API answers with a fallback that allows everything),
240
+ - re-reads on `consentTrackingApiLoaded` and `shopifyCustomerPrivacyApiLoaded`,
241
+ - takes the `visitorConsentCollected` decision from `event.detail`,
242
+ - fails **open** only when there is no consent system at all; it stays closed while the API
243
+ is resolving or when it denies.
244
+
245
+ If your consent banner does **not** feed that API, pass an adapter to **both**
246
+ `createPlaybookContext({consent})` and `<PlaybookRoot consent>`, so the server and client
247
+ make the same decision:
248
+
249
+ ```ts
250
+ import {truevaultConsent} from '@heyplaybook/hydrogen'; // TrueVault Polaris
251
+ ```
252
+
253
+ **Different sources on each side (0.5.0).** The two halves are separate types. A store
254
+ whose server knows consent from one system (e.g. a CMS session) and whose browser knows it
255
+ from another passes each half on its own:
256
+
257
+ ```ts
258
+ import {consentFromAnalytics} from '@heyplaybook/hydrogen';
259
+ import type {PlaybookClientConsent, PlaybookServerConsent} from '@heyplaybook/hydrogen';
260
+
261
+ export const serverConsent = (session: MySession): PlaybookServerConsent => ({
262
+ id: 'my-session',
263
+ fromRequest: () => consentFromAnalytics(session.analytics), // 'granted' | 'denied' | other → pending
264
+ });
265
+ export const clientConsent: PlaybookClientConsent = {
266
+ id: 'my-banner',
267
+ read: () => consentFromAnalytics(myBanner.analytics()),
268
+ subscribe: (onChange) => myBanner.onChange(onChange),
269
+ };
270
+
271
+ createPlaybookContext({request, env, waitUntil, consent: serverConsent(session)});
272
+ <PlaybookRoot consent={clientConsent} … />
273
+ ```
274
+
275
+ `consentFromAnalytics` maps `true`/`'granted'`/`'yes'` → granted, `false`/`'denied'`/`'no'` →
276
+ denied, and anything else → pending (closed, never open). Keep both halves closed on the
277
+ same "unknown" states; they can still disagree briefly while one side catches up.
278
+
279
+ `truevaultConsent` reads `polaris_consent_settings.analyticsPermitted`. With no cookie yet it
280
+ is `pending` (closed: nothing is tracked until the shopper's banner decision is recorded);
281
+ `createTrueVaultConsent({whenMissing: 'granted'})` changes that.
282
+
283
+ Global Privacy Control (`Sec-GPC: 1` / `navigator.globalPrivacyControl`) **follows the
284
+ banner** by default. GPC is an opt-out of sale and sharing, and Playbook doesn't sell data, so
285
+ GPC alone doesn't switch analytics off; the banner's `analyticsPermitted` decides (Polaris
286
+ handles GPC the same way). A store that wants GPC to deny analytics too passes
287
+ `createTrueVaultConsent({gpc: 'deny'})`.
288
+ Pending never writes or expires the persistent `_pb_visitor_id`; only a denial expires it.
289
+
290
+ ### GA4: `view_experiment` on the dataLayer (opt-in since 0.5.0)
291
+
292
+ With `<PlaybookRoot dataLayer>` (or `dataLayer={{eventName: '…'}}`), each exposure is also
293
+ pushed to `window.dataLayer`, once per visitor per test per session, under the same consent
294
+ decision as the exposure, and never for a forced or preview arm. It is **off by default**:
295
+ a store that also runs another tool's tests (Pack tests, for example) would otherwise send
296
+ two tools' `view_experiment` events into the same GA4 report.
297
+
298
+ ```js
299
+ {event: 'view_experiment', experiment_id: 'aa-sitewide', experiment_name: 'aa-sitewide',
300
+ variant_id: 'b', variant_name: 'b', experiment_variant: 'b', pb_vid: '<visitor id>'}
301
+ ```
302
+
303
+ - `experiment_variant` matches the legacy `playbook.js` `playbook_experiment` push, so one
304
+ GTM variable reads both. `experiment_name` is the test key unless the test's config sets
305
+ `experimentName`.
306
+ - `dataLayer` / `dataLayer={true}` turns it on; `dataLayer={{eventName: '…'}}` turns it on
307
+ under another name; omitted or `false` keeps it off.
308
+ - No `window.dataLayer` → nothing happens. The kit never creates one.
309
+ - **Getting it into GA4 is the store's setup:** its GTM container (or Fueled / Elevar) needs a
310
+ trigger on `view_experiment` and a GA4 event tag that forwards these fields. **BigQuery**
311
+ needs the store's GA4 → BigQuery export turned on.
312
+
313
+ ### Kill switch and rollback
314
+
315
+ | Setting | Effect |
316
+ | --- | --- |
317
+ | `PLAYBOOK_TESTS_DISABLED=1` | Store tests off: everyone sees control, no visitor cookies, no cart attribute, no exposures or events. `playbook.js` keeps running. |
318
+ | Unset `PUBLIC_PLAYBOOK_SHOP_ID` | Everything off, including `playbook.js`. |
319
+
320
+ Change the variable in the storefront's environment and redeploy (Oxygen reads env at
321
+ deploy). No code revert is needed.
322
+
323
+ ### QA panel
324
+
325
+ `?pb_debug=1` opens the panel only on a preview host (`*.myshopify.dev`, Shopify previews,
326
+ localhost) or on a request with a verified `pb_preview` link. On the production domain a
327
+ public `?pb_debug=1` shows nothing. Pass `debug={{implementedTests: ['…']}}` to label tests
328
+ the storefront has no code for, and `debug={{explain}}` to add your own "why not in test"
329
+ text (0.5.0):
330
+
331
+ ```tsx
332
+ <PlaybookRoot
333
+ debug={{
334
+ explain: (testKey, assignment, pathname) =>
335
+ testKey === 'towel-badge' && !isTowelPage(pathname) ? 'not a towel product' : null,
336
+ }}
337
+ />
338
+ ```
339
+
340
+ Return a string to show it (it replaces the generic reason), or `null` for the generic one.
341
+
342
+ `<PlaybookRoot previewIgnoresTargeting>` (0.5.0, default off) makes a verified preview show
343
+ its arm even where the test doesn't apply (`eligible: false` or an off-target path). By
344
+ default a previewed arm respects targeting, so it doesn't follow the reviewer onto pages
345
+ the test doesn't cover.
346
+
347
+ ## Manual integration (the building blocks)
348
+
349
+ The kit is built from these exports; use them directly if the kit doesn't fit.
25
350
 
26
351
  ### 1. Environment
27
352
 
@@ -29,8 +354,9 @@ npm install @heyplaybook/hydrogen
29
354
  | --- | --- | --- |
30
355
  | `PUBLIC_PLAYBOOK_SHOP_ID` | Yes | Your Playbook shop ID |
31
356
  | `PLAYBOOK_PLATFORM_URL` | No | Defaults to `https://www.heyplaybook.com`. Set it only for a non-production Playbook |
357
+ | `PLAYBOOK_TESTS_DISABLED` | No | `1` turns off store tests only (the kit's kill switch) |
32
358
 
33
- No secrets reach the client. Without a shop ID the package is inert: everyone sees
359
+ The kit (`createPlaybookContext`) reads these from `env` itself. No secrets reach the client. Without a shop ID the package is inert: everyone sees
34
360
  control and no cookies are set.
35
361
 
36
362
  ### 2. Server: resolve once per document request
@@ -150,6 +476,9 @@ banner that feeds it works with no extra code.
150
476
  | Exposures and events | Sent | Not sent |
151
477
  | `_pb_vid` cart attribute | Written | Not written |
152
478
 
479
+ While consent is **pending**, an existing `_pb_visitor_id` from an earlier grant is left as
480
+ it is (not refreshed, not expired). Only a denial expires it.
481
+
153
482
  - **One visitor ID**, shared with Playbook's storefront script.
154
483
  - **Server-set, so Safari keeps it.** Safari caps cookies written by browser scripts at 7
155
484
  days. The server re-sends `_pb_visitor_id` once per browser session (a `_pb_vs` session
@@ -169,12 +498,13 @@ banner that feeds it works with no extra code.
169
498
  (`Sec-Fetch-Dest: iframe`); a normal top-level visit clears it, so a reviewer never
170
499
  carries a preview out of Playbook.
171
500
  - A preview is **isolated** (0.2.0+): only the previewed test renders, every other test
172
- serves its control (`reason: 'preview-isolated'`), overrides for other tests are ignored,
173
- and the visit writes no visitor cookies and has no visitor id (`visitorId: null`), so it
174
- sends no exposures or events and leaves no assignment behind.
175
- - `createPlaybook({overrides})`: force arms for QA from your own code, for example on
176
- preview hosts only. Forced arms ignore status and traffic split, still respect page
177
- targeting, and never send exposures.
501
+ serves its control (`reason: 'preview-isolated'`), and the visit writes no visitor
502
+ cookies and has no visitor id (`visitorId: null`), so it sends no exposures or events and
503
+ leaves no assignment behind.
504
+ - A previewed arm ignores status and traffic split, respects page targeting (unless
505
+ `previewIgnoresTargeting`), and never sends exposures. The signed `pb_preview` link is
506
+ the only way to force an arm: QA `overrides` (and `pb_force`-style params built on them)
507
+ were removed in 0.5.0.
178
508
  - `usePreviewParamRedirect(location)` returns the URL that re-adds the preview param after
179
509
  an in-app navigation, for frames where third-party cookies are blocked.
180
510
  - Preview requests must not send `X-Frame-Options` or a `frame-ancestors` policy that