@coframe/sdk 1.1.47 → 1.1.49

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
@@ -140,6 +140,178 @@ const projectData = serverData?.project
140
140
 
141
141
  Pass `projectData` into `<CoframeProvider>` to avoid the extra client-side project fetch and personalize on first paint.
142
142
 
143
+ ### Server-side assignment
144
+
145
+ Use `getExperimentAssignment()` when the server must know one experiment's
146
+ variant before rendering or calling an upstream service. Edge performs the full
147
+ assignment; the package never falls back to local bucketing.
148
+
149
+ ```ts
150
+ import {
151
+ generateUserToken,
152
+ getExperimentAssignment,
153
+ } from '@coframe/sdk/server'
154
+
155
+ // Next.js `request.cookies.get()` returns `{ name, value }`; other runtimes
156
+ // return the string. Either way `userToken` must be the string value.
157
+ const existingToken = request.cookies.get('coframe.user.token')?.value
158
+ const userToken = existingToken ?? generateUserToken()
159
+
160
+ if (!existingToken) {
161
+ // Do not set `httpOnly`: the browser SDK reads this cookie to reuse the
162
+ // same identity. An HttpOnly token makes the browser generate a new one and
163
+ // bucket differently, with no error.
164
+ response.cookies.set('coframe.user.token', userToken, {
165
+ path: '/',
166
+ secure: true,
167
+ sameSite: 'lax',
168
+ maxAge: 400 * 24 * 60 * 60,
169
+ })
170
+ }
171
+
172
+ const assignment = await getExperimentAssignment({
173
+ projectId: 'your-project-id',
174
+ experimentId: 'your-experiment-id',
175
+ userToken,
176
+ currentUrl: request.url,
177
+ headers: request.headers,
178
+ })
179
+
180
+ const upstreamVersion =
181
+ assignment?.variant?.slug === 'variant-2' ? 'v2' : 'v1'
182
+ ```
183
+
184
+ The package derives visitor context from an allowlist of request headers.
185
+ Explicit `userAgent`, `languages`, `browserPlatform`, `country`, `region`,
186
+ `city`, `device`, `botScore`, `verifiedBotCategory`, `clientIp`,
187
+ `userVisitCount`, and `userContext` options override the derived values. Only
188
+ the lane cookie is forwarded to Edge; authorization and application cookies are
189
+ not forwarded. `clientIp` is used only for existing blocklist targeting.
190
+
191
+ Geography, device, bot score, and client IP are read from `cf-*` request
192
+ headers. Cloudflare adds `cf-ipcountry` and `cf-connecting-ip` to every
193
+ request that reaches your origin; `cf-region-code` and `cf-ipcity` need the
194
+ "Add visitor location headers" Managed Transform, `cf-device-type` needs
195
+ "cache by device type", and `cf-bot-score` needs Bot Management plus a
196
+ Transform Rule. If your server is not behind Cloudflare, or a header is not
197
+ enabled, that value is missing: the country becomes `unknown`, country
198
+ audiences never match, and the device falls back to the user agent. Pass
199
+ `country`, `region`, `city`, and `device` explicitly in that case, from
200
+ whatever geo source your stack already has. Values are forwarded verbatim and
201
+ audiences compare them exactly, so use Cloudflare's spelling: `country` is the
202
+ uppercase ISO 3166-1 alpha-2 code (`US`, not `us`), `region` the ISO 3166-2
203
+ subdivision code (`CA`), and `device` one of `desktop`, `mobile`, `tablet`.
204
+
205
+ When a result is available, pass its project snapshot to the provider. The
206
+ browser reads the same standard token cookie and runs its existing assignment
207
+ flow without fetching project data again.
208
+
209
+ ```tsx
210
+ <CoframeProvider
211
+ projectConfig={{ projectId: 'your-project-id' }}
212
+ projectData={assignment?.projectData}
213
+ >
214
+ {children}
215
+ </CoframeProvider>
216
+ ```
217
+
218
+ `assignment` is `undefined` when the call failed (see below), so read
219
+ `projectData` with optional chaining and decide there whether the browser may
220
+ initialize on its own.
221
+
222
+ `generateUserToken()` uses Web Crypto when available and falls back to a
223
+ non-cryptographic UUID generator in server runtimes without Web Crypto. The
224
+ token is assignment identity, not an authentication credential. It remains
225
+ stable until its cookie is removed, expires, or is replaced.
226
+ The separate visit count uses the SDK's existing two-hour visit boundary. The
227
+ package only reads the visit cookies the browser SDK writes (`coframe.cvc`,
228
+ `coframe.lastVisitTime`) and never sets them, so without the browser SDK running
229
+ after consent the count stays at 1 and `returning` audiences never match.
230
+
231
+ The result contains either one `variant` or `variant: null` with a structured
232
+ reason (`experiment_not_found`; `not_assigned`, which also covers a visitor
233
+ held out of this experiment or of the whole project by a holdout and renders
234
+ the default experience in the browser too; `unsupported_experiment_type` for
235
+ CMAB targets; `preview_active` for URL previews; a newer Edge may add reasons,
236
+ so treat any reason you do not know as "no variant"). Both forms include the exact `projectData` snapshot used by Edge, so the
237
+ browser can initialize from that snapshot. The snapshot also carries the
238
+ normalized language, platform, and visit-count values used by Edge. The browser
239
+ uses those values only for its initial assignment and returns to its normal
240
+ browser-derived context for later SPA navigations. In every case without a
241
+ variant, use the default upstream experience.
242
+
243
+ The function returns `undefined` for transport, timeout (`timeoutMs`,
244
+ default 1500 ms), Edge, or response validation failures, and when
245
+ `currentUrl` carries `cf_disable`. Handle that state explicitly. Invalid options are a
246
+ programming error and throw instead: an empty `projectId`, `experimentId` or
247
+ `userToken`, a `currentUrl` that is not an absolute URL (Express and Fastify
248
+ `req.url` is a path, build the full URL first), out-of-range `languages`,
249
+ `device`, `botScore`, `timeoutMs` and `userVisitCount` values, any string
250
+ option longer than its limit (4096 characters for URLs, 2048 for the user
251
+ agent, 200 for `projectId`, 512 for `experimentId` and `userToken`), or a
252
+ `userContext` that serializes to more than 4096 bytes (`userContext is too large`). Values derived from
253
+ request headers are clamped instead. To preserve server/browser
254
+ consistency for the response, do not let the browser independently fetch project
255
+ data and assign an experiment after the server has fallen back to its default.
256
+ Applications that accept that possible mismatch may instead initialize the
257
+ browser normally as their fail-open policy.
258
+
259
+ #### What Edge cannot evaluate
260
+
261
+ Server assignment runs the same deterministic logic as the browser, with the
262
+ same token, the same project snapshot, and the same visitor context. The
263
+ browser then reaches the same bucket because every input is the same. Five
264
+ kinds of input only exist in the page, so Edge cannot evaluate them:
265
+
266
+ - **JavaScript targeting.** A `js_function` condition (custom JavaScript that
267
+ reads a page value, a cookie, `localStorage`, or the `dataLayer`) runs only
268
+ in the browser, whether it sits on an audience or on a frame's activation
269
+ condition. Edge treats it as not matched.
270
+ - If the target experiment itself uses a JavaScript audience, the result is
271
+ `variant: null` with reason `not_assigned`. Do not use JavaScript audiences
272
+ on experiments you resolve on the server.
273
+ - Experiments in the same frame are evaluated in order and the first match
274
+ wins. If a JavaScript-targeted experiment sits **ahead of the target in
275
+ the same frame**, Edge skips it and assigns the target, while the browser
276
+ can match it and skip the target. Keep JavaScript-targeted experiments out
277
+ of the target experiment's frame, or place them after the target.
278
+ - The same applies to a JavaScript-targeted experiment that shares a
279
+ **lane** with the target, wherever it sits: lane winners are drawn from
280
+ the experiments the visitor can reach, and Edge cannot tell whether that
281
+ one is reachable. Keep JavaScript-targeted experiments out of the target's
282
+ lane.
283
+ - **CMAB experiments.** A target CMAB experiment returns `variant: null` with
284
+ reason `unsupported_experiment_type`.
285
+ - **URL fragments.** A server never sees the `#fragment` of the page URL, and
286
+ the browser re-evaluates the snapshot with its full `location.href`. Frames
287
+ that use `base_url_matches` ignore query and fragment and are safe; an exact
288
+ `url` condition compares both, and a `url_regex` runs against the full
289
+ `location.href` in the browser, so pass the same URL the browser will have,
290
+ without a fragment, and avoid regexes anchored on the end of the URL.
291
+ - **Previews.** Previews are browser-only. A `coframe_variant_id` URL
292
+ parameter reaches Edge, but the published preview payloads do not name the
293
+ experiment a variant belongs to, so the server answers `variant: null` with
294
+ reason `preview_active` and the browser renders the preview from the
295
+ returned snapshot. A preview kept across navigation by the Preview Session
296
+ tool lives in the browser's `sessionStorage` and never reaches Edge; the
297
+ browser discards the snapshot and fetches its own project. Both affect
298
+ preview users only; render the default upstream experience.
299
+ - **Lane state.** Edge reads lane claims from the `coframe.lanes` cookie only.
300
+ Before cookie consent the browser keeps claims in `localStorage`, which the
301
+ server cannot see, and the server does not persist the claims Edge commits.
302
+ Laned experiments therefore agree once the browser has written the cookie,
303
+ not for a visitor without cookie consent.
304
+
305
+ Audience conditions based on URL (`base_url_matches`), country, device,
306
+ language, platform, visit type, search, time, allocation, or `userContext`
307
+ evaluate identically on both sides, as does bot cloaking. For platform, Edge derives the same
308
+ `navigator.platform` family the browser reports (a `Linux …` string on Android,
309
+ for example `Linux armv8l`), or takes an explicit `browserPlatform` option.
310
+
311
+ If the application uses a custom identity cookie, call `setUserToken()` before
312
+ browser initialization with `waitForUserToken: true`. That integration must also
313
+ keep visit and lane state aligned between the server and browser.
314
+
143
315
  ## Feature flags and remote config
144
316
 
145
317
  Browser Feature Flags use the existing public `projectId` and receive only
@@ -453,6 +625,8 @@ Modern resolution modes handle package subpath exports more reliably.
453
625
  ### `@coframe/sdk/server`
454
626
 
455
627
  - `getProjectData(options)`
628
+ - `getExperimentAssignment(options)`
629
+ - `generateUserToken()`
456
630
  - `evaluateFlags(options)`
457
631
  - `getFeatureFlag(key, options)` / `isFeatureEnabled(key, options)`
458
632
  - `getFeatureFlagPayload(key, options)` / `getRemoteConfig(key, options)`
@@ -302,9 +302,11 @@ const generateUUID = () => {
302
302
  const cryptoObject = (_a = getGlobalScope()) === null || _a === void 0 ? void 0 : _a.crypto;
303
303
  if (cryptoObject === null || cryptoObject === void 0 ? void 0 : cryptoObject.randomUUID)
304
304
  return cryptoObject.randomUUID();
305
+ const randomByte = (cryptoObject === null || cryptoObject === void 0 ? void 0 : cryptoObject.getRandomValues)
306
+ ? () => cryptoObject.getRandomValues(new Uint8Array(1))[0]
307
+ : () => Math.floor(Math.random() * 256);
305
308
  return `${1e7}${ -1e3}${ -4e3}${ -8e3}${ -1e11}`.replace(/[018]/g, (c) => {
306
- var _a, _b;
307
- const randomValue = (_b = (_a = cryptoObject === null || cryptoObject === void 0 ? void 0 : cryptoObject.getRandomValues) === null || _a === void 0 ? void 0 : _a.call(cryptoObject, new Uint8Array(1))[0]) !== null && _b !== void 0 ? _b : 0;
309
+ const randomValue = randomByte();
308
310
  return (c ^
309
311
  (randomValue & (15 >> (c / 4)))).toString(16);
310
312
  });
@@ -371,16 +373,30 @@ const getOrGenerateUserToken = () => {
371
373
  const setUserTokenCookie = (uuid, logger) => {
372
374
  setCookie(USER_TOKEN_COOKIE_KEY, uuid, logger);
373
375
  };
376
+ const VISIT_BOUNDARY_MS = 2 * 60 * 60 * 1000;
377
+ function startsNewVisit(lastVisitTime, now) {
378
+ return !lastVisitTime || now - lastVisitTime > VISIT_BOUNDARY_MS;
379
+ }
380
+ function nextVisitCount(existing, lastVisitTime, now) {
381
+ return startsNewVisit(lastVisitTime, now) ? existing + 1 : existing;
382
+ }
383
+ function parseNonNegativeInt(raw) {
384
+ if (!raw || !/^\d+$/.test(raw))
385
+ return undefined;
386
+ const parsed = Number(raw);
387
+ return parsed <= 9007199254740991 ? parsed : undefined;
388
+ }
389
+ function parseVisitCount(raw) {
390
+ var _a;
391
+ return (_a = parseNonNegativeInt(raw)) !== null && _a !== void 0 ? _a : 0;
392
+ }
374
393
  const trackVisitCookie = (logger) => {
375
- const visitCountString = getCookie(VISIT_COUNT_COOKIE_KEY);
376
- const lastVisitTime = Number.parseInt(getCookie(LAST_VISIT_TIME_KEY), 10);
394
+ const existing = parseVisitCount(getCookie(VISIT_COUNT_COOKIE_KEY));
395
+ const lastVisitTime = parseVisitCount(getCookie(LAST_VISIT_TIME_KEY));
377
396
  const currentTime = Date.now();
378
- const twoHours = 2 * 60 * 60 * 1000;
379
- if (!lastVisitTime || currentTime - lastVisitTime > twoHours) {
380
- const visitCount = visitCountString
381
- ? Number.parseInt(visitCountString, 10) + 1
382
- : 1;
383
- setCookie(VISIT_COUNT_COOKIE_KEY, visitCount.toString(), logger);
397
+ const next = nextVisitCount(existing, lastVisitTime, currentTime);
398
+ if (next !== existing) {
399
+ setCookie(VISIT_COUNT_COOKIE_KEY, next.toString(), logger);
384
400
  setCookie(LAST_VISIT_TIME_KEY, currentTime.toString(), logger);
385
401
  }
386
402
  };
@@ -2107,7 +2123,13 @@ const applyVariantChanges = (variantElements, currentUrl, logger, nonce, lifecyc
2107
2123
  });
2108
2124
  }
2109
2125
  else if (selectedElement instanceof HTMLElement) {
2110
- selectedElement.setAttribute('coframe-exp-id', variant.experiment_id);
2126
+ const listAttribute = 'coframe-experiment-ids';
2127
+ const listed = selectedElement.getAttribute(listAttribute);
2128
+ const experimentIds = listed ? listed.split(',') : [];
2129
+ if (experimentIds.indexOf(variant.experiment_id) === -1) {
2130
+ experimentIds.push(variant.experiment_id);
2131
+ selectedElement.setAttribute(listAttribute, experimentIds.join(','));
2132
+ }
2111
2133
  }
2112
2134
  }
2113
2135
  return true;
@@ -2293,6 +2315,16 @@ function murmurHash3_x86_32(key, seed) {
2293
2315
  return h1 >>> 0;
2294
2316
  }
2295
2317
 
2318
+ function parseLaneCookie(raw) {
2319
+ if (!raw)
2320
+ return {};
2321
+ try {
2322
+ return parseClaims(decodeURIComponent(raw));
2323
+ }
2324
+ catch (_a) {
2325
+ return parseClaims(raw);
2326
+ }
2327
+ }
2296
2328
  function parseClaims(raw) {
2297
2329
  if (!raw)
2298
2330
  return {};
@@ -2726,7 +2758,7 @@ function checkAllAudiences(metadata, ctx) {
2726
2758
  const audience = ctx.project.audiences[audienceId];
2727
2759
  if (!audience)
2728
2760
  continue;
2729
- const activated = checkActivationCondition(audience.selector, ctx.personalizationHeaders, ctx.currentPageUrl, ctx.languages, ctx.browserPlatform, ctx.userToken, ctx.userVisitCount, (js, args) => executeJs(js, args, { isExpression: true, nonce: ctx.nonce }), ctx.logger);
2761
+ const activated = checkActivationCondition(audience.selector, ctx.personalizationHeaders, ctx.currentPageUrl, ctx.languages, ctx.browserPlatform, ctx.userToken, ctx.userVisitCount, ctx.runJsFunction, ctx.logger);
2730
2762
  if (activated === false)
2731
2763
  return false;
2732
2764
  if (activated !== true)
@@ -2734,8 +2766,12 @@ function checkAllAudiences(metadata, ctx) {
2734
2766
  }
2735
2767
  return result;
2736
2768
  }
2737
- async function getVariantsAndElements(personalizationHeaders, project, previewVariantId, userToken, currentPageUrl, languages, browserPlatform, logger, nonce, laneClaims = {}, silentFallback = false, chooseCmabVariants) {
2738
- var _a;
2769
+ function audiencesPass(metadata, ctx) {
2770
+ const result = checkAllAudiences(metadata, ctx);
2771
+ return ctx.unknownIsInactive ? result === true : result !== false;
2772
+ }
2773
+ async function getVariantsAndElements(personalizationHeaders, project, previewVariantId, userToken, currentPageUrl, languages, browserPlatform, logger, nonce, laneClaims = {}, silentFallback = false, chooseCmabVariants, userVisitCountOverride, runtime = {}) {
2774
+ var _a, _b;
2739
2775
  const experimentsInfo = [];
2740
2776
  const cloakBot = !!((_a = project.settings) === null || _a === void 0 ? void 0 : _a.bot_cloaking_enabled) &&
2741
2777
  personalizationHeaders['x-is-bot'] === 'true';
@@ -2747,7 +2783,11 @@ async function getVariantsAndElements(personalizationHeaders, project, previewVa
2747
2783
  laneClaims: meClaims,
2748
2784
  };
2749
2785
  };
2750
- const userVisitCount = Number.parseInt(getCookie(VISIT_COUNT_COOKIE_KEY) || '0', 10);
2786
+ const userVisitCount = userVisitCountOverride !== null && userVisitCountOverride !== void 0 ? userVisitCountOverride : parseVisitCount(getCookie(VISIT_COUNT_COOKIE_KEY));
2787
+ const evaluateJsFunctions = (_b = runtime.evaluateJsFunctions) !== null && _b !== void 0 ? _b : true;
2788
+ const runJsFunction = evaluateJsFunctions
2789
+ ? (js, args) => executeJs(js, args, { isExpression: true, nonce })
2790
+ : undefined;
2751
2791
  const ctx = {
2752
2792
  project,
2753
2793
  personalizationHeaders,
@@ -2756,8 +2796,9 @@ async function getVariantsAndElements(personalizationHeaders, project, previewVa
2756
2796
  languages,
2757
2797
  browserPlatform,
2758
2798
  userVisitCount,
2759
- nonce,
2760
2799
  logger,
2800
+ runJsFunction,
2801
+ unknownIsInactive: !evaluateJsFunctions,
2761
2802
  };
2762
2803
  const validatedClaims = validateClaims(laneClaims, project.lanes);
2763
2804
  const previewVariantIds = splitPreviewVariantIds(previewVariantId);
@@ -2812,27 +2853,24 @@ function activateFrames(ctx) {
2812
2853
  return ctx.project.frames.filter((frame) => {
2813
2854
  if (!frame.experiments)
2814
2855
  return false;
2815
- const frameActivated = checkActivationCondition(frame.activation_condition, ctx.personalizationHeaders, ctx.currentPageUrl, ctx.languages, ctx.browserPlatform, ctx.userToken, ctx.userVisitCount, (js, args) => executeJs(js, args, { isExpression: true, nonce: ctx.nonce }), ctx.logger);
2816
- if (!frameActivated)
2817
- return false;
2818
- return true;
2856
+ const frameActivated = checkActivationCondition(frame.activation_condition, ctx.personalizationHeaders, ctx.currentPageUrl, ctx.languages, ctx.browserPlatform, ctx.userToken, ctx.userVisitCount, ctx.runJsFunction, ctx.logger);
2857
+ return ctx.unknownIsInactive ? frameActivated === true : !!frameActivated;
2819
2858
  });
2820
2859
  }
2821
2860
  async function assignFrames(activeFrames, validatedClaims, ctx, chooseCmabVariants) {
2822
- var _a;
2861
+ var _a, _b, _c;
2823
2862
  const { project, userToken, logger } = ctx;
2824
2863
  const experimentsInfo = [];
2825
2864
  const variantsAndElements = [];
2826
- const evalAudiences = (metadata) => checkAllAudiences(metadata, ctx) !== false;
2827
2865
  const audiencePass = new Map();
2828
2866
  const reachableByLane = {};
2829
2867
  for (const frame of activeFrames) {
2830
- for (const experiment of frame.experiments) {
2868
+ for (const experiment of (_a = frame.experiments) !== null && _a !== void 0 ? _a : []) {
2831
2869
  const metadata = experiment.metadata;
2832
2870
  const laneIds = experimentLaneIds(metadata);
2833
2871
  if (laneIds.length === 0)
2834
2872
  continue;
2835
- const passes = evalAudiences(metadata);
2873
+ const passes = audiencesPass(metadata, ctx);
2836
2874
  audiencePass.set(metadata.experiment_id, passes);
2837
2875
  if (passes) {
2838
2876
  for (const laneId of laneIds) {
@@ -2849,7 +2887,7 @@ async function assignFrames(activeFrames, validatedClaims, ctx, chooseCmabVarian
2849
2887
  let hasActivatedFrames = false;
2850
2888
  for (const frame of activeFrames) {
2851
2889
  let atLeastOneExperimentWasActivated = false;
2852
- for (const experiment of frame.experiments) {
2890
+ for (const experiment of (_b = frame.experiments) !== null && _b !== void 0 ? _b : []) {
2853
2891
  if (atLeastOneExperimentWasActivated)
2854
2892
  break;
2855
2893
  const metadata = experiment.metadata;
@@ -2859,7 +2897,7 @@ async function assignFrames(activeFrames, validatedClaims, ctx, chooseCmabVarian
2859
2897
  continue;
2860
2898
  let activated = audiencePass.get(metadata.experiment_id);
2861
2899
  if (activated === undefined) {
2862
- activated = evalAudiences(metadata);
2900
+ activated = audiencesPass(metadata, ctx);
2863
2901
  }
2864
2902
  if (!activated)
2865
2903
  continue;
@@ -2915,7 +2953,7 @@ async function assignFrames(activeFrames, validatedClaims, ctx, chooseCmabVarian
2915
2953
  try {
2916
2954
  mlVariantIds = await chooseCmabVariants(Array.from(cmabMetadataById.values()), userToken);
2917
2955
  }
2918
- catch (_b) {
2956
+ catch (_d) {
2919
2957
  mlVariantIds = new Map();
2920
2958
  }
2921
2959
  }
@@ -2926,7 +2964,7 @@ async function assignFrames(activeFrames, validatedClaims, ctx, chooseCmabVarian
2926
2964
  }
2927
2965
  const { metadata, variants, elements } = entry;
2928
2966
  let mlVariantId = metadata.type === 'CMAB'
2929
- ? ((_a = mlVariantIds.get(metadata.experiment_id)) !== null && _a !== void 0 ? _a : null)
2967
+ ? ((_c = mlVariantIds.get(metadata.experiment_id)) !== null && _c !== void 0 ? _c : null)
2930
2968
  : null;
2931
2969
  if (mlVariantId && !variants.some((v) => v.id === mlVariantId)) {
2932
2970
  logger.warn(`CMAB variant ${mlVariantId} not in experiment ${metadata.experiment_id}`, 'cmab_variant_not_found', { experiment_id: metadata.experiment_id });
@@ -2979,9 +3017,12 @@ async function previewVariants(previewVariantIds, validatedClaims, ctx, silentFa
2979
3017
  return uniqueByVariantId([...rolledOutVariants, ...requestedVariants]);
2980
3018
  }
2981
3019
  function findVariants(frames, variantIds) {
2982
- return frames.flatMap((frame) => frame.experiments.flatMap((experiment) => experiment.variants
2983
- .filter((variant) => variantIds.includes(variant.id))
2984
- .map((variant) => ({ variant, elements: frame.elements }))));
3020
+ return frames.flatMap((frame) => {
3021
+ var _a;
3022
+ return ((_a = frame.experiments) !== null && _a !== void 0 ? _a : []).flatMap((experiment) => experiment.variants
3023
+ .filter((variant) => variantIds.includes(variant.id))
3024
+ .map((variant) => ({ variant, elements: frame.elements })));
3025
+ });
2985
3026
  }
2986
3027
  function uniqueByVariantId(items) {
2987
3028
  const seen = {};
@@ -2993,10 +3034,13 @@ function uniqueByVariantId(items) {
2993
3034
  });
2994
3035
  }
2995
3036
  function keepRolledOutExperiments(frames) {
2996
- return frames.map((frame) => ({
2997
- ...frame,
2998
- experiments: frame.experiments.filter((experiment) => experiment.metadata.serving_mode === 'winner'),
2999
- }));
3037
+ return frames.map((frame) => {
3038
+ var _a;
3039
+ return ({
3040
+ ...frame,
3041
+ experiments: ((_a = frame.experiments) !== null && _a !== void 0 ? _a : []).filter((experiment) => experiment.metadata.serving_mode === 'winner'),
3042
+ });
3043
+ });
3000
3044
  }
3001
3045
 
3002
3046
  function buildSessionContext(isInitialApply) {
@@ -3667,6 +3711,7 @@ async function resolveProject(Coframe, previewVariantId, isSessionVariant, confi
3667
3711
  const queuedHeaders = getQueuedPersonalizationHeaders();
3668
3712
  let personalizationHeaders = queuedHeaders;
3669
3713
  let project = isSessionVariant ? undefined : projectData === null || projectData === void 0 ? void 0 : projectData.project;
3714
+ const assignmentContext = project ? projectData === null || projectData === void 0 ? void 0 : projectData.assignmentContext : undefined;
3670
3715
  if (!project) {
3671
3716
  const edgeResult = await fetchProject(config.projectUrl, Coframe.projectId, config.currentUrl || getCurrentPageUrl(), undefined, config.userContext, previewVariantId || undefined, undefined, (_b = config.referrer) !== null && _b !== void 0 ? _b : getBrowserReferrer());
3672
3717
  personalizationHeaders = mergeClientHeaders(queuedHeaders, edgeResult === null || edgeResult === void 0 ? void 0 : edgeResult.personalizationHeaders);
@@ -3683,6 +3728,7 @@ async function resolveProject(Coframe, previewVariantId, isSessionVariant, confi
3683
3728
  return {
3684
3729
  project,
3685
3730
  personalizationHeaders: personalizationHeaders,
3731
+ ...(assignmentContext ? { assignmentContext } : {}),
3686
3732
  };
3687
3733
  }
3688
3734
 
@@ -4160,8 +4206,11 @@ function setupListeners(Coframe, executionStartTime) {
4160
4206
  for (const variantElement of Coframe.variantsAndElements || []) {
4161
4207
  const variant = variantElement.variant;
4162
4208
  if (!experiencedCoframeIds.has(variant.id)) {
4163
- const elements = document.querySelectorAll(`[coframe-exp-id="${variant.experiment_id}"]`);
4209
+ const elements = document.querySelectorAll('[coframe-experiment-ids]');
4164
4210
  for (const el of Array.from(elements)) {
4211
+ const experimentIds = (el.getAttribute('coframe-experiment-ids') || '').split(',');
4212
+ if (experimentIds.indexOf(variant.experiment_id) === -1)
4213
+ continue;
4165
4214
  if (isElementVisible(el)) {
4166
4215
  el.setAttribute('coframe-experienced', 'true');
4167
4216
  experiencedCoframeIds.add(variant.id);
@@ -4454,18 +4503,12 @@ function setupSPANavigation(Coframe, project, config, previewVariantId, isSessio
4454
4503
  }
4455
4504
  function readLaneClaims() {
4456
4505
  const cookie = getCookie(LANE_COOKIE_KEY);
4457
- if (cookie) {
4458
- try {
4459
- return parseClaims(decodeURIComponent(cookie));
4460
- }
4461
- catch (_a) {
4462
- return parseClaims(cookie);
4463
- }
4464
- }
4506
+ if (cookie)
4507
+ return parseLaneCookie(cookie);
4465
4508
  try {
4466
4509
  return parseClaims(localStorage.getItem(LANE_COOKIE_KEY));
4467
4510
  }
4468
- catch (_b) {
4511
+ catch (_a) {
4469
4512
  return {};
4470
4513
  }
4471
4514
  }
@@ -4480,14 +4523,17 @@ function persistLaneClaims(claims, logger) {
4480
4523
  setCookie(LANE_COOKIE_KEY, encodeURIComponent(serialized), logger);
4481
4524
  }
4482
4525
  }
4483
- function createApplyVariants(Coframe, config, previewVariantId, isSessionVariant, executionStartTime, analytics, laneStore, runtime) {
4526
+ function createApplyVariants(Coframe, config, previewVariantId, isSessionVariant, executionStartTime, analytics, laneStore, runtime, initialAssignmentContext) {
4484
4527
  let isFirstApply = true;
4528
+ let snapshotContext = initialAssignmentContext;
4485
4529
  let applicationId = 0;
4486
4530
  const apply = async (pageUrl, pageProject, personalizationHeaders, signal, deadline) => {
4487
- var _a, _b;
4531
+ var _a, _b, _c, _d;
4488
4532
  const currentApplication = ++applicationId;
4489
4533
  if (signal === null || signal === void 0 ? void 0 : signal.aborted)
4490
4534
  return 'skipped';
4535
+ const assignmentContext = snapshotContext;
4536
+ snapshotContext = undefined;
4491
4537
  const preview = resolvePreview(pageUrl, previewVariantId, isSessionVariant);
4492
4538
  const chooseCmabVariants = createCmabVariantBatchChooser({
4493
4539
  projectId: Coframe.projectId,
@@ -4498,7 +4544,7 @@ function createApplyVariants(Coframe, config, previewVariantId, isSessionVariant
4498
4544
  disableRemoteAssignment: Boolean(config.projectUrl || config.ingestUrl),
4499
4545
  userContext: config.userContext,
4500
4546
  });
4501
- const { variantsAndElements, experimentsInfo, hasActivatedFrames, laneClaims, } = await getVariantsAndElements(personalizationHeaders, pageProject, preview.previewVariantId, Coframe.userToken, pageUrl, getBrowserLanguages(), getBrowserPlatform(), Coframe.logger, config.nonce, laneStore.claims, preview.isSessionVariant, chooseCmabVariants);
4547
+ const { variantsAndElements, experimentsInfo, hasActivatedFrames, laneClaims, } = await getVariantsAndElements(personalizationHeaders, pageProject, preview.previewVariantId, Coframe.userToken, pageUrl, (_b = assignmentContext === null || assignmentContext === void 0 ? void 0 : assignmentContext.languages) !== null && _b !== void 0 ? _b : getBrowserLanguages(), (_c = assignmentContext === null || assignmentContext === void 0 ? void 0 : assignmentContext.browserPlatform) !== null && _c !== void 0 ? _c : getBrowserPlatform(), Coframe.logger, config.nonce, laneStore.claims, preview.isSessionVariant, chooseCmabVariants, assignmentContext === null || assignmentContext === void 0 ? void 0 : assignmentContext.userVisitCount);
4502
4548
  if ((signal === null || signal === void 0 ? void 0 : signal.aborted) ||
4503
4549
  currentApplication !== applicationId ||
4504
4550
  (runtime === null || runtime === void 0 ? void 0 : runtime.isDestroyed()) ||
@@ -4506,7 +4552,7 @@ function createApplyVariants(Coframe, config, previewVariantId, isSessionVariant
4506
4552
  return 'skipped';
4507
4553
  if (!signal &&
4508
4554
  runtime &&
4509
- ((_b = pageProject === null || pageProject === void 0 ? void 0 : pageProject.settings) === null || _b === void 0 ? void 0 : _b.mutation_observer_active) &&
4555
+ ((_d = pageProject === null || pageProject === void 0 ? void 0 : pageProject.settings) === null || _d === void 0 ? void 0 : _d.mutation_observer_active) &&
4510
4556
  !urlsMatch(pageUrl, getCurrentPageUrl(), true))
4511
4557
  return 'stale-route';
4512
4558
  if (!signal && runtime) {
@@ -4552,7 +4598,7 @@ function createApplyVariants(Coframe, config, previewVariantId, isSessionVariant
4552
4598
  async function modifyPage(Coframe, configResult, projectResult, analytics, lifecycle) {
4553
4599
  var _a;
4554
4600
  const { config, timeoutMs, previewVariantId, isSessionVariant, integrationStartTime, executionStartTime, } = configResult;
4555
- const { project: cdnProject, personalizationHeaders } = projectResult;
4601
+ const { project: cdnProject, personalizationHeaders, assignmentContext, } = projectResult;
4556
4602
  const revealCoordinator = (_a = lifecycle === null || lifecycle === void 0 ? void 0 : lifecycle.revealCoordinator) !== null && _a !== void 0 ? _a : createRevealCoordinator(revealPage, logRevealListenerError(() => Coframe.logger));
4557
4603
  const runtime = lifecycle === null || lifecycle === void 0 ? void 0 : lifecycle.runtime;
4558
4604
  if (runtime && config.waitForHydration) {
@@ -4578,7 +4624,7 @@ async function modifyPage(Coframe, configResult, projectResult, analytics, lifec
4578
4624
  if (!(await ensureBody(Coframe, cdnProject, timeoutMs, config.nonce, revealCoordinator, () => !(runtime === null || runtime === void 0 ? void 0 : runtime.isDestroyed()))))
4579
4625
  return;
4580
4626
  const laneStore = { claims: readLaneClaims() };
4581
- const applier = createApplyVariants(Coframe, config, previewVariantId, isSessionVariant, executionStartTime, analytics, laneStore, runtime);
4627
+ const applier = createApplyVariants(Coframe, config, previewVariantId, isSessionVariant, executionStartTime, analytics, laneStore, runtime, assignmentContext);
4582
4628
  const initialUrl = getCurrentPageUrl();
4583
4629
  if (runtime) {
4584
4630
  const runtimeUrl = runtime.getState().currentUrl;
@@ -5181,6 +5227,9 @@ function injectOptions(options) {
5181
5227
  projectData: {
5182
5228
  project: options.projectData.project,
5183
5229
  personalizationHeaders: (_a = options.projectData.personalizationHeaders) !== null && _a !== void 0 ? _a : {},
5230
+ ...(options.projectData.assignmentContext
5231
+ ? { assignmentContext: options.projectData.assignmentContext }
5232
+ : {}),
5184
5233
  },
5185
5234
  });
5186
5235
  }