@xenia-martech/sdk-js 1.2.0-dev.3 → 1.2.0-dev.5
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 +106 -2
- package/dist/{actions-Bhji05Pe.d.cts → actions-C18Kv-4w.d.cts} +35 -0
- package/dist/{actions-Bhji05Pe.d.ts → actions-C18Kv-4w.d.ts} +35 -0
- package/dist/{api-ByoECRhR.d.ts → api-0IycTYJR.d.cts} +1 -1
- package/dist/{api-BqSvWgBZ.d.cts → api-COXWLL5L.d.ts} +1 -1
- package/dist/{chunk-TRRMMPBH.cjs → chunk-2DR5AVPX.cjs} +10 -45
- package/dist/chunk-2DR5AVPX.cjs.map +1 -0
- package/dist/chunk-BQ5PJCZ7.js +179 -0
- package/dist/chunk-BQ5PJCZ7.js.map +1 -0
- package/dist/{chunk-INM2SPH4.js → chunk-GWRDZIVA.js} +4 -36
- package/dist/chunk-GWRDZIVA.js.map +1 -0
- package/dist/{chunk-TGG5Y4QD.js → chunk-LW5AEJ6K.js} +5 -179
- package/dist/chunk-LW5AEJ6K.js.map +1 -0
- package/dist/chunk-N5M4PI7C.cjs +192 -0
- package/dist/chunk-N5M4PI7C.cjs.map +1 -0
- package/dist/chunk-OMMIRSPK.js +336 -0
- package/dist/chunk-OMMIRSPK.js.map +1 -0
- package/dist/chunk-QEYONKWY.js +42 -0
- package/dist/chunk-QEYONKWY.js.map +1 -0
- package/dist/{chunk-YZG6JR4E.cjs → chunk-RWE2OCQL.cjs} +5 -190
- package/dist/chunk-RWE2OCQL.cjs.map +1 -0
- package/dist/chunk-WHGK55JP.cjs +46 -0
- package/dist/chunk-WHGK55JP.cjs.map +1 -0
- package/dist/chunk-YLMMTKQL.cjs +358 -0
- package/dist/chunk-YLMMTKQL.cjs.map +1 -0
- package/dist/client/index.cjs +304 -26
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.d.cts +15 -4
- package/dist/client/index.d.ts +15 -4
- package/dist/client/index.js +304 -26
- package/dist/client/index.js.map +1 -1
- package/dist/client/react/index.cjs +714 -26
- package/dist/client/react/index.cjs.map +1 -1
- package/dist/client/react/index.d.cts +32 -3
- package/dist/client/react/index.d.ts +32 -3
- package/dist/client/react/index.js +715 -29
- package/dist/client/react/index.js.map +1 -1
- package/dist/cms/contentful.d.cts +2 -1
- package/dist/cms/contentful.d.ts +2 -1
- package/dist/consent-Cemn91j3.d.ts +248 -0
- package/dist/consent-DgWdjsSy.d.cts +248 -0
- package/dist/{cookie-names-Bxd-VNyJ.d.ts → cookie-names-BvUaW3uo.d.ts} +1 -1
- package/dist/{cookie-names-RXVfGYPE.d.cts → cookie-names-CnL65Oly.d.cts} +1 -1
- package/dist/edge/index.cjs +280 -0
- package/dist/edge/index.cjs.map +1 -0
- package/dist/edge/index.d.cts +61 -0
- package/dist/edge/index.d.ts +61 -0
- package/dist/edge/index.js +191 -0
- package/dist/edge/index.js.map +1 -0
- package/dist/index.cjs +41 -40
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +2 -1
- package/dist/next/index.cjs +331 -15
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +180 -6
- package/dist/next/index.d.ts +180 -6
- package/dist/next/index.js +320 -9
- package/dist/next/index.js.map +1 -1
- package/dist/personalize-content-c2DDAV6g.d.ts +140 -0
- package/dist/personalize-content-ghZPKlf1.d.cts +140 -0
- package/dist/server/index.cjs +34 -32
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +6 -5
- package/dist/server/index.d.ts +6 -5
- package/dist/server/index.js +5 -3
- package/dist/server/index.js.map +1 -1
- package/dist/{personalize-content-Bf6YZdkZ.d.cts → types-DgVHS4Qw.d.cts} +7 -138
- package/dist/{personalize-content-Bf6YZdkZ.d.ts → types-DgVHS4Qw.d.ts} +7 -138
- package/dist/xenia-sdk.iife.js +3 -3
- package/dist/xenia-sdk.iife.js.map +1 -1
- package/dist/{xenia-server-MlI3Khya.d.cts → xenia-server-C3O-cWQT.d.cts} +3 -2
- package/dist/{xenia-server-CcjQenru.d.ts → xenia-server-DV8Sjmoo.d.ts} +3 -2
- package/package.json +14 -1
- package/dist/chunk-INM2SPH4.js.map +0 -1
- package/dist/chunk-TGG5Y4QD.js.map +0 -1
- package/dist/chunk-TRRMMPBH.cjs.map +0 -1
- package/dist/chunk-YZG6JR4E.cjs.map +0 -1
|
@@ -155,6 +155,12 @@ interface VisitorCookieOptions {
|
|
|
155
155
|
secure?: boolean;
|
|
156
156
|
/** Cookie lifetime in days. Default 365. */
|
|
157
157
|
maxAgeDays?: number;
|
|
158
|
+
/**
|
|
159
|
+
* The cookie wins over the id stored in this browser: when a server (e.g. an edge proxy) changes
|
|
160
|
+
* the visitor — a profile switch, a QA persona — the browser follows instead of writing its old id
|
|
161
|
+
* back. Default false: the stored id wins and the cookie only seeds a first visit.
|
|
162
|
+
*/
|
|
163
|
+
authoritative?: boolean;
|
|
158
164
|
}
|
|
159
165
|
/** Well-known event fields understood by the backend event-trigger node. */
|
|
160
166
|
interface EventIdentity {
|
|
@@ -614,141 +620,4 @@ type XeniaAction = {
|
|
|
614
620
|
url: string;
|
|
615
621
|
};
|
|
616
622
|
|
|
617
|
-
|
|
618
|
-
* CMS page personalization — walk a fetched CMS page breadth-first, swap the
|
|
619
|
-
* entries Xenia marked as personalized, and do it in as few round trips as
|
|
620
|
-
* the page's nesting allows.
|
|
621
|
-
*
|
|
622
|
-
* Rules (see the "Rounds" section of the feature plan):
|
|
623
|
-
* - **Static** targets carry their replacement in the payload (`xeniaVariants`)
|
|
624
|
-
* and are swapped inline — no network at all.
|
|
625
|
-
* - **Runtime** targets are a barrier: their id is collected, their subtree is
|
|
626
|
-
* NOT walked (it may be replaced). One `resolve-entries` call decides every
|
|
627
|
-
* target found in a round, one parallel CMS fetch loads every replacement,
|
|
628
|
-
* and the next round walks whatever now sits at each position.
|
|
629
|
-
* - Never throws: on error or when `timeoutMs` runs out, whatever is not yet
|
|
630
|
-
* decided keeps its base content.
|
|
631
|
-
*
|
|
632
|
-
* CMS specifics live behind {@link CmsAdapter}; built-in adapters ship as
|
|
633
|
-
* `@xenia-martech/sdk-js/cms/contentful` (and later `/cms/contentstack`). Any
|
|
634
|
-
* other CMS works by implementing the interface.
|
|
635
|
-
*/
|
|
636
|
-
|
|
637
|
-
/** Any value inside a CMS payload — the walker is shape-agnostic; adapters give it meaning. */
|
|
638
|
-
type Node = any;
|
|
639
|
-
/** The parsed `xenia` marker field of a personalized entry. */
|
|
640
|
-
interface XeniaMarker {
|
|
641
|
-
kind: "static" | "runtime";
|
|
642
|
-
op?: EntrySwapOp;
|
|
643
|
-
/** Array field replaced by `op: "items"`. */
|
|
644
|
-
field?: string;
|
|
645
|
-
limit?: number;
|
|
646
|
-
/**
|
|
647
|
-
* The content keys (Personalization Resolve identifiers) that personalize this entry. A page only
|
|
648
|
-
* acts on markers that list its `contentKey`; a marker without keys is ignored.
|
|
649
|
-
*/
|
|
650
|
-
keys?: string[];
|
|
651
|
-
}
|
|
652
|
-
/** What the page resolver needs to know about a CMS's entries. `N` is the entry shape. */
|
|
653
|
-
interface CmsAdapter<N extends object = Node> {
|
|
654
|
-
/** The entry id when `value` is a CMS entry (not a link stub, asset or plain object). */
|
|
655
|
-
entryId(value: unknown): string | undefined;
|
|
656
|
-
/** The entry's Xenia marker, or null when it is not personalized. */
|
|
657
|
-
marker(entry: N): XeniaMarker | null;
|
|
658
|
-
/** Static replacements pinned on the entry (its resolved `xeniaVariants`). */
|
|
659
|
-
staticVariants(entry: N): N[];
|
|
660
|
-
getField(entry: N, field: string): unknown;
|
|
661
|
-
setField(entry: N, field: string, value: unknown): void;
|
|
662
|
-
/** Legacy `items` without a field: copy the replacement's array fields onto the entry. */
|
|
663
|
-
mergeItems?(entry: N, replacement: N): void;
|
|
664
|
-
/**
|
|
665
|
-
* Remove the marker from an entry that has been dealt with (kept base, or had its items replaced),
|
|
666
|
-
* so personalizing the output again — e.g. the browser continuing a server render — never decides
|
|
667
|
-
* it twice. Optional; without it a re-run re-asks Xenia about those entries.
|
|
668
|
-
*/
|
|
669
|
-
clearMarker?(entry: N): void;
|
|
670
|
-
/** Normalize a fetched payload before walking (e.g. resolve links). Defaults to identity. */
|
|
671
|
-
prepare?(payload: unknown): unknown;
|
|
672
|
-
/** Load entries by id in ONE call; order does not matter. */
|
|
673
|
-
fetchEntries(ids: string[], locale?: string): Promise<N[]>;
|
|
674
|
-
/** Run a content-type query in ONE call, in the query's order. */
|
|
675
|
-
queryEntries(query: EntryQuery, locale?: string): Promise<N[]>;
|
|
676
|
-
/**
|
|
677
|
-
* Load one page with its whole tree (links resolved), or null when there is none. Optional; it
|
|
678
|
-
* is what lets `personalizePage(ref)` do the fetch, so apps never fetch the page themselves.
|
|
679
|
-
*/
|
|
680
|
-
fetchPage?(ref: PageRef, locale?: string): Promise<N | null>;
|
|
681
|
-
}
|
|
682
|
-
/** Identifies a page in the CMS: its entry id, or a content type plus exact field values (a slug). */
|
|
683
|
-
type PageRef = string | {
|
|
684
|
-
contentType: string;
|
|
685
|
-
fields: Record<string, string | number | boolean>;
|
|
686
|
-
};
|
|
687
|
-
/** Resolves a round's runtime targets — `XeniaApi.resolveEntries` bound to the visitor. */
|
|
688
|
-
type EntryResolver = (entryIds: string[]) => Promise<EntryDecision[]>;
|
|
689
|
-
/** Reported for every swap actually applied (for impressions / analytics). */
|
|
690
|
-
interface AppliedSwap {
|
|
691
|
-
target: string;
|
|
692
|
-
kind: "static" | "runtime";
|
|
693
|
-
op: EntrySwapOp;
|
|
694
|
-
/** Ids of the entries now at the target's position (or in its field). */
|
|
695
|
-
entryIds: string[];
|
|
696
|
-
contentKey?: string;
|
|
697
|
-
bucket?: string;
|
|
698
|
-
round: number;
|
|
699
|
-
}
|
|
700
|
-
interface PersonalizeContentOptions {
|
|
701
|
-
cms: CmsAdapter;
|
|
702
|
-
/** Decides runtime targets. Omit to apply static swaps only (zero network). */
|
|
703
|
-
resolve?: EntryResolver;
|
|
704
|
-
locale?: string;
|
|
705
|
-
/**
|
|
706
|
-
* The page's Personalization Resolve identifier (required). Only that journey personalizes the
|
|
707
|
-
* page: a marker that doesn't list this key is plain content, and the backend decides for this key
|
|
708
|
-
* alone — another journey targeting the same section is neither consulted nor run.
|
|
709
|
-
*/
|
|
710
|
-
contentKey: string;
|
|
711
|
-
/** Max network rounds (nesting depth of runtime targets). Default 3. */
|
|
712
|
-
maxRounds?: number;
|
|
713
|
-
/** Total budget for all rounds, in ms. Undecided targets keep their base. Default 300. */
|
|
714
|
-
timeoutMs?: number;
|
|
715
|
-
/** Mutate the payload in place instead of personalizing a copy. Default false. */
|
|
716
|
-
inPlace?: boolean;
|
|
717
|
-
onApplied?(swap: AppliedSwap): void;
|
|
718
|
-
/**
|
|
719
|
-
* Called when a round starts waiting on the network (`pending` = targets being decided) and when
|
|
720
|
-
* it has been applied (`pending` empty). `content` is the live, partially personalized tree —
|
|
721
|
-
* lets a UI render level by level instead of waiting for every round.
|
|
722
|
-
*/
|
|
723
|
-
onProgress?(progress: {
|
|
724
|
-
content: unknown;
|
|
725
|
-
round: number;
|
|
726
|
-
pending: string[];
|
|
727
|
-
}): void;
|
|
728
|
-
}
|
|
729
|
-
/** `personalizeContent` options as taken by `XeniaClient` / `XeniaServer`, which supply `resolve`. */
|
|
730
|
-
type PagePersonalizeOptions = Omit<PersonalizeContentOptions, "resolve"> & Pick<ResolveOptions, "data" | "identity" | "context">;
|
|
731
|
-
interface PersonalizeContentResult<T> {
|
|
732
|
-
content: T;
|
|
733
|
-
applied: AppliedSwap[];
|
|
734
|
-
/** False when the budget ran out, a call failed, or `maxRounds` was hit with targets left. */
|
|
735
|
-
complete: boolean;
|
|
736
|
-
error?: unknown;
|
|
737
|
-
}
|
|
738
|
-
declare function personalizeContent<T>(payload: T, options: PersonalizeContentOptions): Promise<PersonalizeContentResult<T>>;
|
|
739
|
-
/**
|
|
740
|
-
* The entries Xenia still has to decide on this page — runtime targets reachable without crossing
|
|
741
|
-
* another undecided one. Synchronous and network-free (it reads the `xenia` markers), so a page can
|
|
742
|
-
* render a skeleton in exactly those places from the first frame instead of flashing base content.
|
|
743
|
-
* Nested targets inside a pending one are found once it is decided.
|
|
744
|
-
*/
|
|
745
|
-
declare function pendingTargets(payload: unknown, adapter: CmsAdapter, contentKey: string): string[];
|
|
746
|
-
/**
|
|
747
|
-
* Fetch a page through `options.cms` and personalize it — {@link personalizeContent} without the
|
|
748
|
-
* fetch in app code. Never throws: a failed fetch comes back as `content: null` with `error`; a page
|
|
749
|
-
* that does not exist as `content: null`, `complete: true`. The page fetch is not counted against
|
|
750
|
-
* `timeoutMs` — that budget is for personalization only.
|
|
751
|
-
*/
|
|
752
|
-
declare function personalizePage<T>(ref: PageRef, options: PersonalizeContentOptions): Promise<PersonalizeContentResult<T | null>>;
|
|
753
|
-
|
|
754
|
-
export { type AnalyticsContext as A, type WidgetPrize as B, type CmsAdapter as C, type WidgetSegment as D, type EventContext as E, type WidgetSubmitResponse as F, type WidgetType as G, type HttpMethod as H, type IdentifyRequest as I, type JsonValue as J, type XeniaAction as K, type XeniaConfig as L, type MessageCta as M, type XeniaEvent as N, pendingTargets as O, type PagePersonalizeOptions as P, personalizeContent as Q, type ResolveBatchItem as R, personalizePage as S, type TrackOptions as T, type CallerIdentity as U, type VisitorCookieOptions as V, type WebhookResponse as W, type XeniaMarker as X, type AnalyticsEventName as a, type AnalyticsIdentity as b, type AnalyticsIngestResponse as c, type AppliedSwap as d, type CircuitBreakerConfig as e, type ConsentState as f, type EntryDecision as g, type EntryFilter as h, type EntryQuery as i, type EntryResolver as j, type EntrySwapOp as k, type EventIdentity as l, type IdentifyResponse as m, type InteractionType as n, type JsonObject as o, type MessagePlacement as p, type PageRef as q, type PersonalizationSwap as r, type PersonalizeContentOptions as s, type PersonalizeContentResult as t, type ResolveBatchResult as u, type ResolveEntriesResult as v, type ResolveOptions as w, type ResolveResult as x, type RetryConfig as y, type WidgetFormSubmit as z };
|
|
623
|
+
export type { AnalyticsContext as A, CircuitBreakerConfig as C, EventContext as E, HttpMethod as H, IdentifyRequest as I, JsonValue as J, MessageCta as M, PersonalizationSwap as P, ResolveBatchItem as R, TrackOptions as T, VisitorCookieOptions as V, WebhookResponse as W, XeniaAction as X, AnalyticsEventName as a, AnalyticsIdentity as b, AnalyticsIngestResponse as c, ConsentState as d, EntryDecision as e, EntryFilter as f, EntryQuery as g, EntrySwapOp as h, EventIdentity as i, IdentifyResponse as j, InteractionType as k, JsonObject as l, MessagePlacement as m, ResolveBatchResult as n, ResolveEntriesResult as o, ResolveOptions as p, ResolveResult as q, RetryConfig as r, WidgetFormSubmit as s, WidgetPrize as t, WidgetSegment as u, WidgetSubmitResponse as v, WidgetType as w, XeniaConfig as x, XeniaEvent as y, CallerIdentity as z };
|
|
@@ -155,6 +155,12 @@ interface VisitorCookieOptions {
|
|
|
155
155
|
secure?: boolean;
|
|
156
156
|
/** Cookie lifetime in days. Default 365. */
|
|
157
157
|
maxAgeDays?: number;
|
|
158
|
+
/**
|
|
159
|
+
* The cookie wins over the id stored in this browser: when a server (e.g. an edge proxy) changes
|
|
160
|
+
* the visitor — a profile switch, a QA persona — the browser follows instead of writing its old id
|
|
161
|
+
* back. Default false: the stored id wins and the cookie only seeds a first visit.
|
|
162
|
+
*/
|
|
163
|
+
authoritative?: boolean;
|
|
158
164
|
}
|
|
159
165
|
/** Well-known event fields understood by the backend event-trigger node. */
|
|
160
166
|
interface EventIdentity {
|
|
@@ -614,141 +620,4 @@ type XeniaAction = {
|
|
|
614
620
|
url: string;
|
|
615
621
|
};
|
|
616
622
|
|
|
617
|
-
|
|
618
|
-
* CMS page personalization — walk a fetched CMS page breadth-first, swap the
|
|
619
|
-
* entries Xenia marked as personalized, and do it in as few round trips as
|
|
620
|
-
* the page's nesting allows.
|
|
621
|
-
*
|
|
622
|
-
* Rules (see the "Rounds" section of the feature plan):
|
|
623
|
-
* - **Static** targets carry their replacement in the payload (`xeniaVariants`)
|
|
624
|
-
* and are swapped inline — no network at all.
|
|
625
|
-
* - **Runtime** targets are a barrier: their id is collected, their subtree is
|
|
626
|
-
* NOT walked (it may be replaced). One `resolve-entries` call decides every
|
|
627
|
-
* target found in a round, one parallel CMS fetch loads every replacement,
|
|
628
|
-
* and the next round walks whatever now sits at each position.
|
|
629
|
-
* - Never throws: on error or when `timeoutMs` runs out, whatever is not yet
|
|
630
|
-
* decided keeps its base content.
|
|
631
|
-
*
|
|
632
|
-
* CMS specifics live behind {@link CmsAdapter}; built-in adapters ship as
|
|
633
|
-
* `@xenia-martech/sdk-js/cms/contentful` (and later `/cms/contentstack`). Any
|
|
634
|
-
* other CMS works by implementing the interface.
|
|
635
|
-
*/
|
|
636
|
-
|
|
637
|
-
/** Any value inside a CMS payload — the walker is shape-agnostic; adapters give it meaning. */
|
|
638
|
-
type Node = any;
|
|
639
|
-
/** The parsed `xenia` marker field of a personalized entry. */
|
|
640
|
-
interface XeniaMarker {
|
|
641
|
-
kind: "static" | "runtime";
|
|
642
|
-
op?: EntrySwapOp;
|
|
643
|
-
/** Array field replaced by `op: "items"`. */
|
|
644
|
-
field?: string;
|
|
645
|
-
limit?: number;
|
|
646
|
-
/**
|
|
647
|
-
* The content keys (Personalization Resolve identifiers) that personalize this entry. A page only
|
|
648
|
-
* acts on markers that list its `contentKey`; a marker without keys is ignored.
|
|
649
|
-
*/
|
|
650
|
-
keys?: string[];
|
|
651
|
-
}
|
|
652
|
-
/** What the page resolver needs to know about a CMS's entries. `N` is the entry shape. */
|
|
653
|
-
interface CmsAdapter<N extends object = Node> {
|
|
654
|
-
/** The entry id when `value` is a CMS entry (not a link stub, asset or plain object). */
|
|
655
|
-
entryId(value: unknown): string | undefined;
|
|
656
|
-
/** The entry's Xenia marker, or null when it is not personalized. */
|
|
657
|
-
marker(entry: N): XeniaMarker | null;
|
|
658
|
-
/** Static replacements pinned on the entry (its resolved `xeniaVariants`). */
|
|
659
|
-
staticVariants(entry: N): N[];
|
|
660
|
-
getField(entry: N, field: string): unknown;
|
|
661
|
-
setField(entry: N, field: string, value: unknown): void;
|
|
662
|
-
/** Legacy `items` without a field: copy the replacement's array fields onto the entry. */
|
|
663
|
-
mergeItems?(entry: N, replacement: N): void;
|
|
664
|
-
/**
|
|
665
|
-
* Remove the marker from an entry that has been dealt with (kept base, or had its items replaced),
|
|
666
|
-
* so personalizing the output again — e.g. the browser continuing a server render — never decides
|
|
667
|
-
* it twice. Optional; without it a re-run re-asks Xenia about those entries.
|
|
668
|
-
*/
|
|
669
|
-
clearMarker?(entry: N): void;
|
|
670
|
-
/** Normalize a fetched payload before walking (e.g. resolve links). Defaults to identity. */
|
|
671
|
-
prepare?(payload: unknown): unknown;
|
|
672
|
-
/** Load entries by id in ONE call; order does not matter. */
|
|
673
|
-
fetchEntries(ids: string[], locale?: string): Promise<N[]>;
|
|
674
|
-
/** Run a content-type query in ONE call, in the query's order. */
|
|
675
|
-
queryEntries(query: EntryQuery, locale?: string): Promise<N[]>;
|
|
676
|
-
/**
|
|
677
|
-
* Load one page with its whole tree (links resolved), or null when there is none. Optional; it
|
|
678
|
-
* is what lets `personalizePage(ref)` do the fetch, so apps never fetch the page themselves.
|
|
679
|
-
*/
|
|
680
|
-
fetchPage?(ref: PageRef, locale?: string): Promise<N | null>;
|
|
681
|
-
}
|
|
682
|
-
/** Identifies a page in the CMS: its entry id, or a content type plus exact field values (a slug). */
|
|
683
|
-
type PageRef = string | {
|
|
684
|
-
contentType: string;
|
|
685
|
-
fields: Record<string, string | number | boolean>;
|
|
686
|
-
};
|
|
687
|
-
/** Resolves a round's runtime targets — `XeniaApi.resolveEntries` bound to the visitor. */
|
|
688
|
-
type EntryResolver = (entryIds: string[]) => Promise<EntryDecision[]>;
|
|
689
|
-
/** Reported for every swap actually applied (for impressions / analytics). */
|
|
690
|
-
interface AppliedSwap {
|
|
691
|
-
target: string;
|
|
692
|
-
kind: "static" | "runtime";
|
|
693
|
-
op: EntrySwapOp;
|
|
694
|
-
/** Ids of the entries now at the target's position (or in its field). */
|
|
695
|
-
entryIds: string[];
|
|
696
|
-
contentKey?: string;
|
|
697
|
-
bucket?: string;
|
|
698
|
-
round: number;
|
|
699
|
-
}
|
|
700
|
-
interface PersonalizeContentOptions {
|
|
701
|
-
cms: CmsAdapter;
|
|
702
|
-
/** Decides runtime targets. Omit to apply static swaps only (zero network). */
|
|
703
|
-
resolve?: EntryResolver;
|
|
704
|
-
locale?: string;
|
|
705
|
-
/**
|
|
706
|
-
* The page's Personalization Resolve identifier (required). Only that journey personalizes the
|
|
707
|
-
* page: a marker that doesn't list this key is plain content, and the backend decides for this key
|
|
708
|
-
* alone — another journey targeting the same section is neither consulted nor run.
|
|
709
|
-
*/
|
|
710
|
-
contentKey: string;
|
|
711
|
-
/** Max network rounds (nesting depth of runtime targets). Default 3. */
|
|
712
|
-
maxRounds?: number;
|
|
713
|
-
/** Total budget for all rounds, in ms. Undecided targets keep their base. Default 300. */
|
|
714
|
-
timeoutMs?: number;
|
|
715
|
-
/** Mutate the payload in place instead of personalizing a copy. Default false. */
|
|
716
|
-
inPlace?: boolean;
|
|
717
|
-
onApplied?(swap: AppliedSwap): void;
|
|
718
|
-
/**
|
|
719
|
-
* Called when a round starts waiting on the network (`pending` = targets being decided) and when
|
|
720
|
-
* it has been applied (`pending` empty). `content` is the live, partially personalized tree —
|
|
721
|
-
* lets a UI render level by level instead of waiting for every round.
|
|
722
|
-
*/
|
|
723
|
-
onProgress?(progress: {
|
|
724
|
-
content: unknown;
|
|
725
|
-
round: number;
|
|
726
|
-
pending: string[];
|
|
727
|
-
}): void;
|
|
728
|
-
}
|
|
729
|
-
/** `personalizeContent` options as taken by `XeniaClient` / `XeniaServer`, which supply `resolve`. */
|
|
730
|
-
type PagePersonalizeOptions = Omit<PersonalizeContentOptions, "resolve"> & Pick<ResolveOptions, "data" | "identity" | "context">;
|
|
731
|
-
interface PersonalizeContentResult<T> {
|
|
732
|
-
content: T;
|
|
733
|
-
applied: AppliedSwap[];
|
|
734
|
-
/** False when the budget ran out, a call failed, or `maxRounds` was hit with targets left. */
|
|
735
|
-
complete: boolean;
|
|
736
|
-
error?: unknown;
|
|
737
|
-
}
|
|
738
|
-
declare function personalizeContent<T>(payload: T, options: PersonalizeContentOptions): Promise<PersonalizeContentResult<T>>;
|
|
739
|
-
/**
|
|
740
|
-
* The entries Xenia still has to decide on this page — runtime targets reachable without crossing
|
|
741
|
-
* another undecided one. Synchronous and network-free (it reads the `xenia` markers), so a page can
|
|
742
|
-
* render a skeleton in exactly those places from the first frame instead of flashing base content.
|
|
743
|
-
* Nested targets inside a pending one are found once it is decided.
|
|
744
|
-
*/
|
|
745
|
-
declare function pendingTargets(payload: unknown, adapter: CmsAdapter, contentKey: string): string[];
|
|
746
|
-
/**
|
|
747
|
-
* Fetch a page through `options.cms` and personalize it — {@link personalizeContent} without the
|
|
748
|
-
* fetch in app code. Never throws: a failed fetch comes back as `content: null` with `error`; a page
|
|
749
|
-
* that does not exist as `content: null`, `complete: true`. The page fetch is not counted against
|
|
750
|
-
* `timeoutMs` — that budget is for personalization only.
|
|
751
|
-
*/
|
|
752
|
-
declare function personalizePage<T>(ref: PageRef, options: PersonalizeContentOptions): Promise<PersonalizeContentResult<T | null>>;
|
|
753
|
-
|
|
754
|
-
export { type AnalyticsContext as A, type WidgetPrize as B, type CmsAdapter as C, type WidgetSegment as D, type EventContext as E, type WidgetSubmitResponse as F, type WidgetType as G, type HttpMethod as H, type IdentifyRequest as I, type JsonValue as J, type XeniaAction as K, type XeniaConfig as L, type MessageCta as M, type XeniaEvent as N, pendingTargets as O, type PagePersonalizeOptions as P, personalizeContent as Q, type ResolveBatchItem as R, personalizePage as S, type TrackOptions as T, type CallerIdentity as U, type VisitorCookieOptions as V, type WebhookResponse as W, type XeniaMarker as X, type AnalyticsEventName as a, type AnalyticsIdentity as b, type AnalyticsIngestResponse as c, type AppliedSwap as d, type CircuitBreakerConfig as e, type ConsentState as f, type EntryDecision as g, type EntryFilter as h, type EntryQuery as i, type EntryResolver as j, type EntrySwapOp as k, type EventIdentity as l, type IdentifyResponse as m, type InteractionType as n, type JsonObject as o, type MessagePlacement as p, type PageRef as q, type PersonalizationSwap as r, type PersonalizeContentOptions as s, type PersonalizeContentResult as t, type ResolveBatchResult as u, type ResolveEntriesResult as v, type ResolveOptions as w, type ResolveResult as x, type RetryConfig as y, type WidgetFormSubmit as z };
|
|
623
|
+
export type { AnalyticsContext as A, CircuitBreakerConfig as C, EventContext as E, HttpMethod as H, IdentifyRequest as I, JsonValue as J, MessageCta as M, PersonalizationSwap as P, ResolveBatchItem as R, TrackOptions as T, VisitorCookieOptions as V, WebhookResponse as W, XeniaAction as X, AnalyticsEventName as a, AnalyticsIdentity as b, AnalyticsIngestResponse as c, ConsentState as d, EntryDecision as e, EntryFilter as f, EntryQuery as g, EntrySwapOp as h, EventIdentity as i, IdentifyResponse as j, InteractionType as k, JsonObject as l, MessagePlacement as m, ResolveBatchResult as n, ResolveEntriesResult as o, ResolveOptions as p, ResolveResult as q, RetryConfig as r, WidgetFormSubmit as s, WidgetPrize as t, WidgetSegment as u, WidgetSubmitResponse as v, WidgetType as w, XeniaConfig as x, XeniaEvent as y, CallerIdentity as z };
|
package/dist/xenia-sdk.iife.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var Xenia=(function(exports){'use strict';var je=new Set(["banner","popup","modal","inline"]),Be=new Set(["top-left","top-right","bottom-left","bottom-right","top","bottom"]),Ue=new Set(["standard","spin-wheel"]),Ke=new Set(["swap","hide","show","setContent","redirect",...je]);function I(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function f(n){return typeof n=="string"?n:void 0}function fe(n){return typeof n=="number"?n:void 0}function Qe(n){if(!I(n))return null;let e=f(n.type);if(!e||!Ke.has(e))return null;if(e==="redirect"){let i=f(n.url);return i?{type:e,url:i}:null}if(e==="hide"||e==="show"){let i=f(n.target);return i?{type:e,target:i}:null}if(e==="swap"||e==="setContent"){let i=f(n.target);return i?{type:e,target:i,html:f(n.html),text:f(n.text)}:null}let t=I(n.cta)?{label:f(n.cta.label)??"",url:f(n.cta.url),event:f(n.cta.event)}:void 0;return {type:e,target:f(n.target),title:f(n.title),message:f(n.message),imageUrl:f(n.imageUrl),html:f(n.html),cta:t&&(t.label||t.url)?t:void 0,dismissAfterMs:fe(n.dismissAfterMs),position:Ge(n.position),widgetType:Ye(n.widgetType),segments:Ze(n.segments),formSubmit:et(n.formSubmit),style:tt(n.style),spinnerHtml:f(n.spinnerHtml),winHtml:f(n.winHtml),lossHtml:f(n.lossHtml)}}function Ge(n){let e=f(n);return e&&Be.has(e)?e:void 0}function Ye(n){let e=f(n);return e&&Ue.has(e)?e:void 0}function Ze(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!I(t))continue;let i=f(t.id),r=f(t.label);!i||!r||e.push({id:i,label:r,colorHex:f(t.colorHex),isLoss:t.isLoss===true});}return e.length?e:void 0}function et(n){if(!I(n))return;let e=f(n.mode);if(e)return {requiresResolve:n.requiresResolve===true,mode:e,flowRef:f(n.flowRef),bindingRef:f(n.bindingRef),successDisplayMs:fe(n.successDisplayMs)}}function tt(n){if(!I(n))return;let e={hideCloseButton:n.hideCloseButton===true,hideOverlay:n.hideOverlay===true};return e.hideCloseButton||e.hideOverlay?e:void 0}function Y(n){let e;if(Array.isArray(n)?e=n:I(n)&&Array.isArray(n.xeniaActions)&&(e=n.xeniaActions),!Array.isArray(e))return [];let t=[];for(let i of e){let r=Qe(i);r&&t.push(r);}return t}var nt="https://engine.xeniamartech.com/xenia";function O(){return typeof window<"u"&&typeof document<"u"}function ge(n,e){if(!e||Object.keys(e).length===0)return n;let t=new URLSearchParams(e),i=n.includes("?")?"&":"?";return `${n}${i}${t.toString()}`}function ye(n){return new Promise(e=>setTimeout(e,n))}var R=class extends Error{constructor(t,i,r){super(r??`Request failed with status ${t}`);this.status=t;this.data=i;this.name="HttpError";}status;data},Z=class extends Error{constructor(t){super(`Circuit open for ${t}: failing fast until the cooldown passes`);this.endpoint=t;this.name="CircuitOpenError";}endpoint},L=new Map,q=class{baseUrl;defaultHeaders;timeout;retry;debug;breaker;constructor(e){this.baseUrl=(e.baseUrl??nt).replace(/\/+$/,""),this.defaultHeaders=e.defaultHeaders??{},this.timeout=e.timeout??8e3,this.retry={attempts:e.retry?.attempts??2,baseDelayMs:e.retry?.baseDelayMs??300},this.debug=e.debug??false;let t=e.circuitBreaker===true?{}:e.circuitBreaker||null;this.breaker=t&&{failureThreshold:t.failureThreshold??3,cooldownMs:t.cooldownMs??3e4};}async request(e){if(!this.breaker)return this.send(e);let t=ge(this.baseUrl+e.path,e.query),i=L.get(t)??{failures:0,openedAt:0};if(i.openedAt){if(Date.now()-i.openedAt<this.breaker.cooldownMs)throw new Z(t);i.openedAt=0,i.failures=this.breaker.failureThreshold-1;}try{let r=await this.send(e);return L.delete(t),r}catch(r){throw r instanceof R&&!this.isRetryableStatus(r.status)?(L.delete(t),r):(i.failures+=1,i.failures>=this.breaker.failureThreshold&&(i.openedAt=Date.now(),this.log(`circuit opened for ${e.path} after ${i.failures} failures`)),L.set(t,i),r)}}async send(e){let t=ge(this.baseUrl+e.path,e.query),i=e.method??"GET",r={"Content-Type":"application/json",...this.defaultHeaders,...e.headers},s=e.body!==void 0?JSON.stringify(e.body):void 0,o=e.timeout??this.timeout,a=e.noRetry?1:(e.retry?.attempts??this.retry.attempts)+1,d=e.retry?.baseDelayMs??this.retry.baseDelayMs,l;for(let c=0;c<a;c++)try{let p=await this.fetchWithTimeout(t,{method:i,headers:r,body:s,...e.keepalive?{keepalive:!0}:{}},o),y=await this.parseBody(p);if(p.ok)return {response:p,data:y};if(this.isRetryableStatus(p.status)&&c<a-1){let u=this.retryAfterMs(p,d,c);this.log(`retrying ${e.path} after ${u}ms (status ${p.status})`),await ye(u);continue}throw new R(p.status,y)}catch(p){if(l=p,p instanceof R)throw p;if(c<a-1){let y=d*2**c;this.log(`retrying ${e.path} after ${y}ms (network error)`),await ye(y);continue}}throw l instanceof Error?l:new Error("Request failed")}async fetchWithTimeout(e,t,i){let r=new AbortController,s=setTimeout(()=>r.abort(),i);try{return await fetch(e,{...t,signal:r.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`Request timeout after ${i}ms`,{cause:o}):o}finally{clearTimeout(s);}}async parseBody(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}isRetryableStatus(e){return e===429||e>=500&&e<=599}retryAfterMs(e,t,i){let r=e.headers.get("Retry-After");if(r){let s=Number(r);if(!Number.isNaN(s))return s*1e3}return t*2**i}log(e){this.debug&&console.warn(`[xenia] ${e}`);}};function it(n){try{let e=n.split(".")[1];if(!e)return;let t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:void 0}catch{return}}var N=class{config;cached=null;inflight=null;constructor(e){this.config=e;}hasSource(){return !!(this.config.token||this.config.getToken)}getToken=async()=>{if(this.config.token&&!this.config.getToken)return this.config.token;let e=Date.now();if(this.cached&&this.cached.expiresAt>e)return this.cached.token;if(this.inflight)return this.inflight;if(!this.config.getToken)throw new Error("No token source: set config.token or config.getToken.");return this.inflight=Promise.resolve(this.config.getToken()).then(t=>{let i=it(t),r=i?i-3e4:e+5*6e4;return this.cached={token:t,expiresAt:r},t}).finally(()=>{this.inflight=null;}),this.inflight}};function ve(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function rt(n){return n!==void 0&&ve(n)?n:void 0}function E(n){let e={};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);return e}var z=class{http;tenantId;environmentKey;tokenProvider;constructor(e){this.tenantId=e.tenantId,this.environmentKey=e.environmentKey,this.tokenProvider=new N(e),this.http=new q({baseUrl:e.baseUrl,defaultHeaders:e.headers,timeout:e.timeout,retry:e.retry,circuitBreaker:e.circuitBreaker,debug:e.debug});}tenantHeaders(){return {"X-Tenant-Id":this.tenantId,"X-Environment":this.environmentKey}}async authHeaders(){let e=this.tenantHeaders();if(!this.tokenProvider.hasSource())return e;let t=await this.tokenProvider.getToken();return t&&(e.Authorization=`Bearer ${t}`),e}async webhook(e,t,i="POST"){let{response:r,data:s}=await this.http.request({method:i,path:"/flow",query:{id:e},headers:await this.authHeaders(),body:i==="POST"?t??{}:void 0,noRetry:true});return {status:r.status,body:s,actions:Y(s),receivedAt:Date.now()}}async submitWidget(e,t){let{response:i,data:r}=await this.http.request({method:"POST",path:"/widget-submissions",query:{ref:e},headers:await this.authHeaders(),body:t??{},noRetry:true}),s=ve(r)?r:{};return {status:i.status,body:r,actions:Y(r),prize:rt(s.prize),alreadyPlayed:s.alreadyPlayed===true,dispatched:s.dispatched===true,dispatchError:typeof s.dispatchError=="string"?s.dispatchError:void 0,widgetType:typeof s.widgetType=="string"?s.widgetType:void 0,receivedAt:Date.now()}}async sendEvents(e,t){let{data:i}=await this.http.request({method:"POST",path:"/api/events/v1",headers:await this.authHeaders(),body:{events:e},keepalive:t?.keepalive});return i}async identify(e){let{data:t}=await this.http.request({method:"POST",path:"/api/events/v1/identify",headers:await this.authHeaders(),body:e});return t}async consent(e,t){let{data:i}=await this.http.request({method:"POST",path:"/api/events/v1/consent",headers:await this.authHeaders(),body:E({xeniaVisitorId:e,analytics:t.analytics===true,marketing:t.marketing===true,personalization:t.personalization===true,consentSource:t.consentSource,consentVersion:t.consentVersion})});return i}async resolve(e,t={}){let{data:i}=await this.http.request({method:"POST",path:"/api/personalization/resolve",query:t.merge!==void 0?{merge:String(t.merge)}:void 0,headers:await this.authHeaders(),body:E({contentKey:e,data:t.data,locale:t.locale})});return i}async resolveBatch(e,t={}){let{data:i}=await this.http.request({method:"POST",path:"/api/personalization/resolve-batch",query:t.merge!==void 0?{merge:String(t.merge)}:void 0,headers:await this.authHeaders(),body:E({items:e,data:t.data,locale:t.locale})});return i}async resolveEntries(e,t){let{data:i}=await this.http.request({method:"POST",path:"/api/personalization/resolve-entries",headers:await this.authHeaders(),body:E({entryIds:e,data:t.data,locale:t.locale,contentKey:t.contentKey})});return i}};var $="xenia";function ee(n=$){return `${n||$}_vid`}function be(n=$){return `${n||$}_consent`}function xe(n,e,t=365){return `${be(e)}=${encodeURIComponent(JSON.stringify(n))}; path=/; max-age=${Math.floor(t*86400)}; SameSite=Lax`}var st=new Set(["eventId","eventType","journeyId","deviceId","visitorId","customerId","email","utmSource","utmMedium","utmCampaign","utmContent","utmId","url","referrer","path","query"]);function we(n){let e={};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);return e}function Se(n){let e={},t={};if(n.props)for(let[r,s]of Object.entries(n.props))s!==void 0&&(st.has(r)?t[r]=s:e[r]=s);return {...e,...t,...we(n.context??{}),...we(n.identity??{}),eventId:n.eventId,...n.eventType?{eventType:n.eventType}:{},...n.journeyId?{journeyId:n.journeyId}:{}}}var W="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ot(n){let e=new Uint8Array(n);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<n;t++)e[t]=Math.floor(Math.random()*256);return e}function k(n=Date.now()){let e="",t=n;for(let s=9;s>=0;s--)e=W[t%32]+e,t=Math.floor(t/32);let i=ot(16),r="";for(let s=0;s<16;s++)r+=W[i[s]%32];return e+r}var te=26;function Ee(n){if(n.length<=te)return n;let e="";for(let i of [2166136261,16777619]){let r=i>>>0;for(let s=0;s<n.length;s++)r^=n.charCodeAt(s),r=Math.imul(r,16777619)>>>0,e+=W[r%32];}let t="";for(let i=0;i<te;i++){let r=i+1;for(let s=i;s<e.length;s+=te)r=r*31+W.indexOf(e[s])>>>0;t+=W[r%32];}return t}var at=n=>n&&typeof n=="object"&&typeof structuredClone=="function"?structuredClone(n):n;async function ie(n,e){let t=ut(e.cms,e.contentKey),i=e.maxRounds??3,r=Date.now()+(e.timeoutMs??300),s=[],o=u=>{s.push(u);try{e.onApplied?.(u);}catch{}},a=n;try{!e.inPlace&&typeof structuredClone=="function"&&(a=structuredClone(a)),a=t.prepare?t.prepare(a):a;}catch(u){return {content:n,applied:s,complete:false,error:u}}let d={root:a},l=new WeakSet,c=new Map,p=[{parent:d,key:"root",value:d.root}],y=(u,m,g)=>{l.add(u.entry),t.clearMarker?.(u.entry);let v=m.items.map(at);if(!m.decision||v.length===0)return dt(u,t);for(let h of v)h&&typeof h=="object"&&l.add(h);let b=m.decision.op??u.marker.op??"replace",S=Ie(u,b,m.decision.field??u.marker.field,v,t);return o({target:u.id,kind:"runtime",op:b,entryIds:v.map(h=>t.entryId(h)).filter(h=>!!h),contentKey:m.decision.contentKey,bucket:m.decision.bucket,round:g}),S};for(let u=0;;u++){let m=lt(p,t,l,u,o,h=>{let w=c.get(h.id);return w?y(h,w,u):void 0});if(m.size===0)return {content:d.root,applied:s,complete:true};if(!e.resolve||u>=i)return {content:d.root,applied:s,complete:!e.resolve};ke(e,{content:d.root,round:u,pending:[...m.keys()]});let g,v,b;try{g=await Re(e.resolve([...m.keys()]),r),{entriesById:v,queried:b}=await Re(ct(g,t,e.locale),r);}catch(h){return {content:d.root,applied:s,complete:false,error:h===ne?void 0:h}}let S=new Map(g.map(h=>[h.target,h]));p=[];for(let h of m.values()){let w=S.get(h.id),G=w?w.ids?w.ids.map(P=>v.get(P)).filter(P=>P!==void 0):b.get(w)??[]:[],M={decision:w,items:G};c.set(h.id,M),p.push(...y(h,M,u));}ke(e,{content:d.root,round:u,pending:[]});}}function ke(n,e){try{n.onProgress?.(e);}catch{}}function lt(n,e,t,i,r,s){let o=new Map,a=new WeakSet,d=new WeakSet,l=[...n];for(;l.length>0;){let c=l.shift(),p=c.value;if(!p||typeof p!="object"||d.has(p))continue;let y=t.has(p)?void 0:e.entryId(p),u=y?e.marker(p):null;if(y&&u?.kind==="runtime"){let m=s({id:y,marker:u,entry:p,slots:[c]});if(m){l.push(...m);continue}let g=o.get(y);if(g)g.slots.push(c);else if(o.set(y,{id:y,marker:u,entry:p,slots:[c]}),u.op==="items"&&u.field){let v=e.getField(p,u.field);v&&typeof v=="object"&&d.add(v),l.push(...Ce(p));}continue}if(y&&u?.kind==="static"){let m=e.staticVariants(p).filter(g=>g&&typeof g=="object");if(t.add(p),e.clearMarker?.(p),m.length>0){for(let b of m)t.add(b);let g=u.op??"replace",v={entry:p,slots:[c]};l.push(...Ie(v,g,u.field,m,e)),r({target:y,kind:"static",op:g,entryIds:m.map(b=>e.entryId(b)).filter(b=>!!b),round:i});continue}}a.has(p)||(a.add(p),l.push(...Ce(p)));}return o}function Ie(n,e,t,i,r){if(e==="items"){if(t)return r.setField(n.entry,t,i),[{parent:n.entry,key:t,value:r.getField(n.entry,t)}];if(r.mergeItems)return r.mergeItems(n.entry,i[0]),n.slots.map(o=>({...o,value:n.entry}));e="replace";}let s=[];for(let o of n.slots){let a=e==="expand"&&Array.isArray(o.parent)?i:[i[0]];if(Array.isArray(o.parent)){let d=o.parent.indexOf(n.entry);if(d<0)continue;o.parent.splice(d,1,...a);}else o.parent[o.key]=a[0];for(let d of a)s.push({parent:o.parent,key:o.key,value:d});}return s}function dt(n,e){return n.marker.op==="items"&&n.marker.field?[{parent:n.entry,key:n.marker.field,value:e.getField(n.entry,n.marker.field)}]:n.slots.map(t=>({...t,value:n.entry}))}function Ce(n){return Array.isArray(n)?n.map((e,t)=>({parent:n,key:t,value:e})):Object.keys(n).map(e=>({parent:n,key:e,value:n[e]}))}async function ct(n,e,t){let i=[...new Set(n.flatMap(l=>l.ids??[]))],r=n.filter(l=>!l.ids&&l.query),[s,...o]=await Promise.all([i.length>0?e.fetchEntries(i,t):Promise.resolve([]),...r.map(l=>e.queryEntries(l.query,t).catch(()=>[]))]),a=new Map;for(let l of s){let c=e.entryId(l);c&&a.set(c,l);}let d=new Map;return r.forEach((l,c)=>d.set(l,o[c])),{entriesById:a,queried:d}}var ne=Symbol("timeout");function Re(n,e){let t=e-Date.now();if(t<=0)return Promise.reject(ne);let i;return Promise.race([n,new Promise((r,s)=>{i=setTimeout(()=>s(ne),t);})]).finally(()=>clearTimeout(i))}function ut(n,e){return {...n,marker(t){let i=n.marker(t);return i&&e&&i.keys?.includes(e)?i:null}}}async function Te(n,e){let t;try{if(!e.cms.fetchPage)throw new Error("This CMS adapter cannot fetch pages; use personalizeContent(page)");t=await e.cms.fetchPage(n,e.locale);}catch(i){return {content:null,applied:[],complete:false,error:i}}return t==null?{content:null,applied:[],complete:true}:ie(t,e)}var D=class{map=new Map;set(e,t){this.map.set(e,t);}get(e){return this.map.get(e)}keys(){return [...this.map.keys()]}clear(){this.map.clear();}},J=class{nsKey;constructor(e="xenia"){this.nsKey=`${e}_responses`;}read(){try{let e=localStorage.getItem(this.nsKey);return e?JSON.parse(e):{}}catch{return {}}}write(e){try{localStorage.setItem(this.nsKey,JSON.stringify(e));}catch{}}set(e,t){let i=this.read();i[e]=t,this.write(i);}get(e){return this.read()[e]}keys(){return Object.keys(this.read())}clear(){try{localStorage.removeItem(this.nsKey);}catch{}}};var _=class{queue=[];send;batchSize;flushIntervalMs;maxQueueSize;debug;timer=null;flushing=false;listenersAttached=false;allowed=false;onPageHide=()=>this.flushOnUnload();onVisibilityChange=()=>{document.visibilityState==="hidden"&&this.flushOnUnload();};constructor(e){this.send=e.send,this.batchSize=e.batchSize??20,this.flushIntervalMs=e.flushIntervalMs??3e3,this.maxQueueSize=e.maxQueueSize??200,this.debug=e.debug??false;}start(){this.allowed=true,!(this.timer||typeof window>"u")&&(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibilityChange),this.listenersAttached=true);}stop(){this.allowed=false,this.timer&&clearInterval(this.timer),this.timer=null,this.listenersAttached&&(window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibilityChange),this.listenersAttached=false);}enqueue(e){this.queue.length>=this.maxQueueSize&&this.queue.shift(),this.queue.push(e),this.allowed&&this.queue.length>=this.batchSize&&this.flush();}async sendImmediate(e){try{await this.send([e],{keepalive:!0});}catch(t){this.isPermanentFailure(t)||this.requeue([e]),this.debug&&console.warn("[xenia] immediate send failed",t);}}async flush(){if(!this.allowed||this.flushing||this.queue.length===0)return;this.flushing=true;let e=this.queue.splice(0,this.batchSize);try{await this.send(e);}catch(t){this.isPermanentFailure(t)||this.requeue(e),this.debug&&console.warn("[xenia] analytics flush failed",t);}finally{this.flushing=false;}}isPermanentFailure(e){return e instanceof R&&e.status>=400&&e.status<500}flushOnUnload(){if(!this.allowed||this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length);this.send(e,{keepalive:true}).catch(()=>{});}requeue(e){let t=this.maxQueueSize-this.queue.length;t<=0||this.queue.unshift(...e.slice(0,t));}};var pt=new Set(["click","view-port","page-load"]);function Ae(n){let e=n.indexOf("&");if(e===-1)return null;let t=n.slice(0,e),i=n.slice(e+1);return !t||!pt.has(i)?null:{eventId:t,interactionType:i}}function Me(n){let e=n.getAttribute("data-xenia-content-key");if(!e)return null;let t=n.getAttribute("data-xenia-content-entry-id"),i=n.getAttribute("data-xenia-base-entry-id"),r=n.getAttribute("data-xenia-personalized");return {contentKey:e,contentEntryId:t??void 0,baseEntryId:i??void 0,personalized:r==null?void 0:r==="true"}}var F=class{opts;throttleTimers=new Map;observers=new Map;slotObservers=new Map;triggered=new Set;slotImpressed=new Set;clickHandler=null;mutationObserver=null;constructor(e){this.opts=e;}start(){this.setupClicks(),this.scan(document),this.setupMutations();}stop(){this.clickHandler&&document.removeEventListener("click",this.clickHandler),this.clickHandler=null,this.mutationObserver?.disconnect(),this.mutationObserver=null,this.observers.forEach(e=>e.disconnect()),this.observers.clear(),this.slotObservers.forEach(e=>e.disconnect()),this.slotObservers.clear(),this.throttleTimers.clear(),this.triggered.clear(),this.slotImpressed.clear();}attr(){return `data-${this.opts.prefix}`}throttled(e){if(this.opts.throttleMs<=0)return false;let t=Date.now(),i=this.throttleTimers.get(e)??0;return t-i>=this.opts.throttleMs?(this.throttleTimers.set(e,t),false):true}setupClicks(){let e=this.attr();this.clickHandler=t=>{let i=t.target;if(!i)return;let r=i.closest(`[${e}]`);if(r){let s=r.getAttribute(e),o=s?Ae(s):null;o&&o.interactionType==="click"&&!this.throttled(r)&&this.opts.fire(o.eventId,"click");}if(this.opts.fireSlot){let s=i.closest("[data-xenia-slot]");if(s){let o=Me(s);o&&!this.throttled(s)&&this.opts.fireSlot("click",o);}}},document.addEventListener("click",this.clickHandler);}observeSlot(e){if(!this.opts.fireSlot||this.slotObservers.has(e))return;let t=Me(e);if(!t)return;let i=this.opts.fireSlot,{threshold:r,rootMargin:s}=this.opts.viewport,o=new IntersectionObserver(a=>{for(let d of a)d.isIntersecting&&(this.slotImpressed.has(e)||(this.slotImpressed.add(e),i("impression",t),o.disconnect(),this.slotObservers.delete(e)));},{threshold:r,rootMargin:s});o.observe(e),this.slotObservers.set(e,o);}observeViewport(e,t){if(this.observers.has(e))return;let{threshold:i,rootMargin:r,triggerOnce:s}=this.opts.viewport,o=new IntersectionObserver(a=>{for(let d of a)d.isIntersecting&&(s&&this.triggered.has(e)||this.throttled(e)||(this.opts.fire(t,"view-port"),s&&(this.triggered.add(e),o.disconnect(),this.observers.delete(e))));},{threshold:i,rootMargin:r});o.observe(e),this.observers.set(e,o);}handleElement(e){let t=e.getAttribute(this.attr());if(!t)return;let i=Ae(t);i&&(i.interactionType==="view-port"?this.observeViewport(e,i.eventId):i.interactionType==="page-load"&&this.opts.fire(i.eventId,"page-load"));}scan(e){e.querySelectorAll(`[${this.attr()}]`).forEach(t=>this.handleElement(t)),this.opts.fireSlot&&e.querySelectorAll("[data-xenia-slot]").forEach(t=>this.observeSlot(t));}setupMutations(){this.mutationObserver=new MutationObserver(e=>{for(let t of e)for(let i of t.addedNodes){if(i.nodeType!==Node.ELEMENT_NODE)continue;let r=i;this.handleElement(r),this.opts.fireSlot&&r.matches("[data-xenia-slot]")&&this.observeSlot(r),this.scan(r);}}),this.mutationObserver.observe(document.body,{childList:true,subtree:true});}};function Pe(n){let e={};if(!n)return e;for(let t of n.split(";")){let i=t.indexOf("=");if(i===-1)continue;let r=t.slice(0,i).trim(),s=t.slice(i+1).trim();r&&(e[r]=decodeURIComponent(s));}return e}var mt=1800*1e3,X=class{prefix;cookie;deviceId=null;journeyId=null;sessionId=null;constructor(e="xenia",t=true){this.prefix=e,this.cookie=ht(t);}key(e){return `${this.prefix}_${e}`}cookieName(){return ee(this.prefix)}writeVisitorCookie(e){if(!(!this.cookie||!e))try{if(typeof document>"u")return;let t=[`${this.cookieName()}=${encodeURIComponent(e)}`,"path=/",`max-age=${Math.floor(this.cookie.maxAgeDays*86400)}`,`SameSite=${this.cookie.sameSite}`];this.cookie.domain&&t.push(`domain=${this.cookie.domain}`),this.cookie.secure&&t.push("Secure"),document.cookie=t.join("; ");}catch{}}readVisitorCookie(){if(!this.cookie||typeof document>"u")return null;try{return Pe(document.cookie)[this.cookieName()]||null}catch{return null}}async resolveDeviceId(){if(this.deviceId)return this.writeVisitorCookie(this.getVisitorId()??this.deviceId),this.deviceId;let e=this.key("device_id");try{let i=localStorage.getItem(e);if(i)return this.deviceId=i,this.writeVisitorCookie(this.getVisitorId()??i),i}catch{}let t=this.readVisitorCookie();t||(t=await this.mediaDeviceId()),t||(t=await this.fingerprint()),this.deviceId=t;try{localStorage.setItem(e,t);}catch{}return this.writeVisitorCookie(this.getVisitorId()??t),t}getDeviceId(){return this.deviceId}async mediaDeviceId(){try{if(!navigator.mediaDevices?.enumerateDevices)return null;let e=await navigator.mediaDevices.enumerateDevices();return (e.find(i=>i.kind==="videoinput"&&i.deviceId)||e.find(i=>i.kind==="audioinput"&&i.deviceId)||e.find(i=>i.kind==="audiooutput"&&i.deviceId))?.deviceId||null}catch{return null}}async fingerprint(){let e=[navigator.userAgent,navigator.language,screen.width,screen.height,screen.colorDepth,new Date().getTimezoneOffset()].join("|"),t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}identify(e){if(e){try{localStorage.setItem(this.key("visitor_id"),e);}catch{}this.writeVisitorCookie(e);}}getVisitorId(){try{return localStorage.getItem(this.key("visitor_id"))}catch{return null}}setCustomerId(e){try{e?localStorage.setItem(this.key("customer_id"),e):localStorage.removeItem(this.key("customer_id"));}catch{}}getCustomerId(){try{return localStorage.getItem(this.key("customer_id"))}catch{return null}}setEmail(e){try{e?localStorage.setItem(this.key("email"),e):localStorage.removeItem(this.key("email"));}catch{}}getEmail(){try{return localStorage.getItem(this.key("email"))}catch{return null}}getSessionId(){let e=this.key("session_id"),t=this.key("session_last_activity"),i=Date.now();try{let r=sessionStorage.getItem(e),s=Number(sessionStorage.getItem(t)),a=r&&Number.isFinite(s)&&i-s<mt?r:k(i);return sessionStorage.setItem(e,a),sessionStorage.setItem(t,String(i)),this.sessionId=a,a}catch{return this.sessionId||(this.sessionId=k(i)),this.sessionId}}setJourneyId(e){this.journeyId=e&&e.trim()?e.trim():null;}getJourneyId(){return this.journeyId||this.utmParam("utm_id")||null}utmParam(e){try{let t=new URLSearchParams(window.location.search).get(e);if(t){try{sessionStorage.setItem(this.key(e),t);}catch{}return t}try{return sessionStorage.getItem(this.key(e))}catch{}}catch{}return null}collectContext(){let e={},t=this.utmParam("utm_source"),i=this.utmParam("utm_medium"),r=this.utmParam("utm_campaign"),s=this.utmParam("utm_content"),o=this.utmParam("utm_id");t&&(e.utmSource=t),i&&(e.utmMedium=i),r&&(e.utmCampaign=r),s&&(e.utmContent=s),o&&(e.utmId=o);try{e.url=window.location.href,e.path=window.location.pathname,e.query=Object.fromEntries(new URLSearchParams(window.location.search)),document.referrer&&(e.referrer=document.referrer);}catch{}let a=this.getVisitorId();return a&&(e.visitorId=a),e}};function ht(n){if(n===false)return null;let e=n===true?{}:n,t=e.sameSite??"Lax",i=t==="None"?true:e.secure??false;return {sameSite:t,secure:i,maxAgeDays:e.maxAgeDays??365,domain:e.domain}}function j(n){let e={};return n.querySelectorAll("[data-xenia-field]").forEach(t=>{let i=t.getAttribute("data-xenia-field");i&&(e[i]=ft(t));}),e}function ft(n){return n instanceof HTMLInputElement?n.type==="checkbox"?n.checked?n.value||"on":"":n.type==="radio"?n.checked?n.value:"":n.value:n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement?n.value:n.textContent?.trim()??""}function Oe(n,e){n&&(n instanceof HTMLButtonElement||n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement||n instanceof HTMLFieldSetElement?n.disabled=e:e?n.setAttribute("aria-disabled","true"):n.removeAttribute("aria-disabled"));}function re(n,e){let t=n.querySelector("[data-xenia-error]");t&&(t.textContent=e);}var We="xenia-form-submit-style";function gt(n){if(n.querySelector(`#${We}`))return;let e=document.createElement("style");e.id=We,e.textContent="@keyframes xenia-submit-spin{to{transform:rotate(360deg)}}[data-xenia-submitting]::after{content:'';display:inline-block;width:0.85em;height:0.85em;margin-left:0.5em;vertical-align:-0.15em;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:xenia-submit-spin 0.6s linear infinite}",n.prepend(e);}function se(n,e){n&&(e?n.setAttribute("data-xenia-submitting",""):n.removeAttribute("data-xenia-submitting"));}function yt(n,e){if(!e)return;let t=n instanceof ShadowRoot?n.host:n;t instanceof HTMLElement?(t.style.transition="opacity 220ms ease, transform 220ms ease",t.style.opacity="0",t.style.transform="scale(0.96)",window.setTimeout(e,220)):e();}var vt=900;function bt(n,e){let t=n.querySelector("[data-xenia-success]");return t?(t instanceof HTMLElement?t.hidden=false:t.removeAttribute("hidden"),e?e.hidden=true:n.querySelectorAll("[data-xenia-field], [data-xenia-submit]").forEach(i=>{i.hidden=true;}),true):false}function He(n,e,t){let i=n.querySelector("form"),r=false;gt(n);let s=(o,a)=>{if(r)return;if(!e.formSubmit){re(n,"This form isn't connected yet.");return}r=true,re(n,""),Oe(o,true),se(o,true);let d=Date.now(),l=e.formSubmit.successDisplayMs??vt;t.submitWidgetForm(a).then(()=>{se(o,false),bt(n,i);let c=Math.max(0,l-(Date.now()-d));window.setTimeout(()=>yt(n,t.dismiss),c);}).catch(()=>{se(o,false),Oe(o,false),re(n,"Something went wrong. Please try again.");}).finally(()=>{r=false;});};i&&i.addEventListener("submit",o=>{o.preventDefault();let a={};new FormData(i).forEach((l,c)=>{typeof l=="string"&&(a[c]=l);});let d=o.submitter??i.querySelector('[type="submit"], button:not([type])');s(d,{...j(n),...a});}),n.querySelectorAll("[data-xenia-submit]").forEach(o=>{i?.contains(o)||o.addEventListener("click",()=>s(o,j(n)));});}function oe(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Ve(n){return oe(n).replace(/"/g,""")}function B(n,e){e&&n.querySelectorAll(".xenia-close, [data-xenia-close], [class*='close' i], [id*='close' i], [class*='backdrop' i], [id*='backdrop' i]").forEach(i=>{i.removeAttribute("onclick"),i.addEventListener("click",e);}),n.querySelectorAll("[class*='backdrop' i], [id*='backdrop' i]").forEach(t=>{t instanceof HTMLElement&&t.children.length===0&&!t.textContent?.trim()&&(t.style.opacity="0.5");});}var T=260,H=T/2,A=T/2,Le=["#7c3aed","#2563eb","#059669","#d97706","#dc2626","#0891b2"],xt="transform 3.2s cubic-bezier(0.15, 0.85, 0.25, 1)",wt='<div class="xenia-wheel-pointer" aria-hidden="true"></div>',le=320,qe=`opacity ${le}ms ease, transform ${le}ms ease`,St=900,ae=(n,e)=>`perspective(${St}px) translateZ(${e}px) scale(${n})`;function de(n,e){let t=n*Math.PI/180;return {x:A+e*Math.sin(t),y:A-e*Math.cos(t)}}function Et(n,e){let t=de(n,H),i=de(e,H),r=e-n>180?1:0;return `M ${A},${A} L ${t.x},${t.y} A ${H},${H} 0 ${r} 1 ${i.x},${i.y} Z`}function kt(n,e,t=0){if(e<=0)return 0;let i=360/e,s=(360-(n*i+i/2))%360;return t*360+s}function ze(n,e){let t=n?Array.from(n.children):[],i=e?Array.from(e.children):[];e&&(e.hidden=false),i.forEach(r=>{r instanceof HTMLElement&&(r.style.transition="none",r.style.opacity="0",r.style.transform=ae(.94,-60));}),i.forEach(r=>{r instanceof HTMLElement&&r.offsetHeight;}),$e(()=>{t.forEach(r=>{r instanceof HTMLElement&&(r.style.transition=qe,r.style.opacity="0",r.style.transform=ae(.94,-60));}),i.forEach(r=>{r instanceof HTMLElement&&(r.style.transition=qe,r.style.opacity="1",r.style.transform=ae(1,0));});}),n&&setTimeout(()=>{n.hidden=true;},le);}function $e(n){typeof requestAnimationFrame=="function"?requestAnimationFrame(n):setTimeout(n,0);}function Ct(n){let t=360/(n.length||1),i=n.map((r,s)=>{let o=s*t,a=o+t,d=r.colorHex||Le[s%Le.length],l=o+t/2,c=de(l,H*.62);return `<path d="${Et(o,a)}" fill="${Ve(d)}" stroke="#fff" stroke-width="1"></path><text x="${c.x}" y="${c.y}" fill="#fff" font-size="12" text-anchor="middle" transform="rotate(${l} ${c.x} ${c.y})">${oe(r.label)}</text>`}).join("");return `<svg class="xenia-wheel-svg" viewBox="0 0 ${T} ${T}" width="${T}" height="${T}"><g class="xenia-wheel-dial">${i}</g><circle class="xenia-wheel-hub" cx="${A}" cy="${A}" r="6"></circle></svg>`}var De={html(n){return `<div class="xenia-spin-wheel"><div data-xenia-wheel-face>${n.spinnerHtml??""}</div><div class="xenia-widget-result" data-xenia-wheel-result hidden>${n.winHtml??""}</div><div class="xenia-widget-result" data-xenia-wheel-loss hidden>${n.lossHtml??""}</div></div>`},wire(n,e,t){B(n,t.dismiss);let i=e.segments??[],r=n.querySelector("[data-xenia-wheel-face]"),s=n.querySelector("[data-xenia-spin]"),o=n.querySelector("[data-xenia-wheel-result]"),a=n.querySelector("[data-xenia-wheel-loss]"),d=n.querySelector("[data-xenia-error]"),l=n.querySelector("[data-xenia-wheel-slot]");l&&l.insertAdjacentHTML("afterbegin",Ct(i)+wt);let c=n.querySelector(".xenia-wheel-dial");if(!s||!e.formSubmit)return;n.querySelectorAll("[data-xenia-wheel-cta]").forEach(m=>{m.addEventListener("click",()=>t.fireCta());});let p=(m,g,v)=>{n.querySelectorAll("[data-xenia-wheel-prize]").forEach(h=>{h.textContent=m;});let b=g?a:o,S=g?o:a;S&&(S.hidden=true),ze(r,b),v||(u=true,n.querySelectorAll("[data-xenia-spin-again]").forEach(h=>{h.hidden=true;}));},y=false,u=false;n.querySelectorAll("[data-xenia-spin-again]").forEach(m=>{m.addEventListener("click",()=>{if(u)return;let g=o&&!o.hidden?o:a&&!a.hidden?a:null;g&&(y=false,s.disabled=false,d&&(d.textContent=""),ze(g,r));});}),s.addEventListener("click",()=>{if(y)return;y=true,s.disabled=true,d&&(d.textContent="");let m=j(n);t.submitWidgetForm(m).then(g=>{let v=i.findIndex(Xe=>Xe.id===g.prize?.segmentId),b=g.prize?.label??i[v]?.label??"",S=v>=0&&!!i[v]?.isLoss,h=g.alreadyPlayed!==true;if(v<0||!c){p(b,S,h);return}let w=3+Math.floor(Math.random()*3),G=kt(v,i.length||1,w),M=/rotate\(([-\d.]+)deg\)/.exec(c.style.transform),P=M?parseFloat(M[1]):0;c.style.transition="none",c.style.transform=`rotate(${P%360}deg)`,c.getBoundingClientRect(),c.style.transition=xt;let he=()=>{c.removeEventListener("transitionend",he),p(b,S,h);};c.addEventListener("transitionend",he),$e(()=>{c.style.transform=`rotate(${G}deg)`;});}).catch(()=>{y=false,s.disabled=false,d&&(d.textContent="Something went wrong. Please try again.");});});}};var ce={"spin-wheel":De};function Q(n,e=document){if(!n)return null;let t=e.querySelector(`[data-xenia-slot="${Rt(n)}"]`);if(t)return t;try{return e.querySelector(n)}catch{return null}}function Rt(n){let e=window;return e.CSS?.escape?e.CSS.escape(n):n.replace(/["\\]/g,"\\$&")}function U(n,e){let t=Q(n);return t?(e.html!==void 0?t.innerHTML=e.html:e.text!==void 0&&(t.textContent=e.text),t.removeAttribute("hidden"),true):false}function ue(n){let e=Q(n);return !e||!(e instanceof HTMLElement)?false:(e.dataset.xeniaHidden="1",e.style.setProperty("display","none","important"),true)}function pe(n){let e=Q(n);return !e||!(e instanceof HTMLElement)?false:(delete e.dataset.xeniaHidden,e.style.removeProperty("display"),true)}var It=new Set(["banner","popup","modal","inline"]);function Tt(n){return It.has(n)}var K=class{host=null;shadow=null;onCta;messageTemplate;messageStyles;messageComponent;submitWidgetFormFn;mounted=new Map;constructor(e,t){this.onCta=e,this.messageTemplate=t?.messageTemplate,this.messageStyles=t?.messageStyles,this.messageComponent=t?.messageComponent,this.submitWidgetFormFn=t?.submitWidgetForm;}apply(e){let t=0;for(let i of e)this.applyOne(i)&&t++;return t}applyOne(e){switch(e.type){case "swap":return U(e.target,{html:e.html,text:e.text});case "setContent":return U(e.target,{html:e.html,text:e.text});case "hide":return ue(e.target);case "show":return pe(e.target);case "redirect":try{return window.location.assign(e.url),!0}catch{return false}default:return Tt(e.type)?this.renderMessage(e):false}}destroy(){this.mounted.forEach(e=>e()),this.mounted.clear(),this.host?.remove(),this.host=null,this.shadow=null;}ensureShadow(){if(this.shadow)return this.shadow;let e=document.createElement("div");e.setAttribute("data-xenia-ui",""),document.body.appendChild(e);let t=e.attachShadow({mode:"open"});return t.appendChild(this.styleEl()),this.host=e,this.shadow=t,t}styleEl(){let e=document.createElement("style");return e.textContent=this.messageStyles?`${_e}
|
|
2
|
-
${this.messageStyles}`:
|
|
1
|
+
var Xenia=(function(exports){'use strict';var lt=new Set(["banner","popup","modal","inline"]),ct=new Set(["top-left","top-right","bottom-left","bottom-right","top","bottom"]),dt=new Set(["standard","spin-wheel"]),ut=new Set(["swap","hide","show","setContent","redirect",...lt]);function A(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function b(n){return typeof n=="string"?n:void 0}function ke(n){return typeof n=="number"?n:void 0}function pt(n){if(!A(n))return null;let e=b(n.type);if(!e||!ut.has(e))return null;if(e==="redirect"){let i=b(n.url);return i?{type:e,url:i}:null}if(e==="hide"||e==="show"){let i=b(n.target);return i?{type:e,target:i}:null}if(e==="swap"||e==="setContent"){let i=b(n.target);return i?{type:e,target:i,html:b(n.html),text:b(n.text)}:null}let t=A(n.cta)?{label:b(n.cta.label)??"",url:b(n.cta.url),event:b(n.cta.event)}:void 0;return {type:e,target:b(n.target),title:b(n.title),message:b(n.message),imageUrl:b(n.imageUrl),html:b(n.html),cta:t&&(t.label||t.url)?t:void 0,dismissAfterMs:ke(n.dismissAfterMs),position:mt(n.position),widgetType:ft(n.widgetType),segments:ht(n.segments),formSubmit:gt(n.formSubmit),style:yt(n.style),spinnerHtml:b(n.spinnerHtml),winHtml:b(n.winHtml),lossHtml:b(n.lossHtml)}}function mt(n){let e=b(n);return e&&ct.has(e)?e:void 0}function ft(n){let e=b(n);return e&&dt.has(e)?e:void 0}function ht(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!A(t))continue;let i=b(t.id),r=b(t.label);!i||!r||e.push({id:i,label:r,colorHex:b(t.colorHex),isLoss:t.isLoss===true});}return e.length?e:void 0}function gt(n){if(!A(n))return;let e=b(n.mode);if(e)return {requiresResolve:n.requiresResolve===true,mode:e,flowRef:b(n.flowRef),bindingRef:b(n.bindingRef),successDisplayMs:ke(n.successDisplayMs)}}function yt(n){if(!A(n))return;let e={hideCloseButton:n.hideCloseButton===true,hideOverlay:n.hideOverlay===true};return e.hideCloseButton||e.hideOverlay?e:void 0}function ee(n){let e;if(Array.isArray(n)?e=n:A(n)&&Array.isArray(n.xeniaActions)&&(e=n.xeniaActions),!Array.isArray(e))return [];let t=[];for(let i of e){let r=pt(i);r&&t.push(r);}return t}var vt="https://engine.xeniamartech.com/xenia";function V(){return typeof window<"u"&&typeof document<"u"}function Ee(n,e){if(!e||Object.keys(e).length===0)return n;let t=new URLSearchParams(e),i=n.includes("?")?"&":"?";return `${n}${i}${t.toString()}`}function Ce(n){return new Promise(e=>setTimeout(e,n))}var T=class extends Error{constructor(t,i,r){super(r??`Request failed with status ${t}`);this.status=t;this.data=i;this.name="HttpError";}status;data},te=class extends Error{constructor(t){super(`Circuit open for ${t}: failing fast until the cooldown passes`);this.endpoint=t;this.name="CircuitOpenError";}endpoint},_=new Map,D=class{baseUrl;defaultHeaders;timeout;retry;debug;breaker;constructor(e){this.baseUrl=(e.baseUrl??vt).replace(/\/+$/,""),this.defaultHeaders=e.defaultHeaders??{},this.timeout=e.timeout??8e3,this.retry={attempts:e.retry?.attempts??2,baseDelayMs:e.retry?.baseDelayMs??300},this.debug=e.debug??false;let t=e.circuitBreaker===true?{}:e.circuitBreaker||null;this.breaker=t&&{failureThreshold:t.failureThreshold??3,cooldownMs:t.cooldownMs??3e4};}async request(e){if(!this.breaker)return this.send(e);let t=Ee(this.baseUrl+e.path,e.query),i=_.get(t)??{failures:0,openedAt:0};if(i.openedAt){if(Date.now()-i.openedAt<this.breaker.cooldownMs)throw new te(t);i.openedAt=0,i.failures=this.breaker.failureThreshold-1;}try{let r=await this.send(e);return _.delete(t),r}catch(r){throw r instanceof T&&!this.isRetryableStatus(r.status)?(_.delete(t),r):(i.failures+=1,i.failures>=this.breaker.failureThreshold&&(i.openedAt=Date.now(),this.log(`circuit opened for ${e.path} after ${i.failures} failures`)),_.set(t,i),r)}}async send(e){let t=Ee(this.baseUrl+e.path,e.query),i=e.method??"GET",r={"Content-Type":"application/json",...this.defaultHeaders,...e.headers},s=e.body!==void 0?JSON.stringify(e.body):void 0,o=e.timeout??this.timeout,l=e.noRetry?1:(e.retry?.attempts??this.retry.attempts)+1,a=e.retry?.baseDelayMs??this.retry.baseDelayMs,c;for(let d=0;d<l;d++)try{let m=await this.fetchWithTimeout(t,{method:i,headers:r,body:s,...e.keepalive?{keepalive:!0}:{}},o),y=await this.parseBody(m);if(m.ok)return {response:m,data:y};if(this.isRetryableStatus(m.status)&&d<l-1){let u=this.retryAfterMs(m,a,d);this.log(`retrying ${e.path} after ${u}ms (status ${m.status})`),await Ce(u);continue}throw new T(m.status,y)}catch(m){if(c=m,m instanceof T)throw m;if(d<l-1){let y=a*2**d;this.log(`retrying ${e.path} after ${y}ms (network error)`),await Ce(y);continue}}throw c instanceof Error?c:new Error("Request failed")}async fetchWithTimeout(e,t,i){let r=new AbortController,s=setTimeout(()=>r.abort(),i);try{return await fetch(e,{...t,signal:r.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`Request timeout after ${i}ms`,{cause:o}):o}finally{clearTimeout(s);}}async parseBody(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}isRetryableStatus(e){return e===429||e>=500&&e<=599}retryAfterMs(e,t,i){let r=e.headers.get("Retry-After");if(r){let s=Number(r);if(!Number.isNaN(s))return s*1e3}return t*2**i}log(e){this.debug&&console.warn(`[xenia] ${e}`);}};function bt(n){try{let e=n.split(".")[1];if(!e)return;let t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:void 0}catch{return}}var $=class{config;cached=null;inflight=null;constructor(e){this.config=e;}hasSource(){return !!(this.config.token||this.config.getToken)}getToken=async()=>{if(this.config.token&&!this.config.getToken)return this.config.token;let e=Date.now();if(this.cached&&this.cached.expiresAt>e)return this.cached.token;if(this.inflight)return this.inflight;if(!this.config.getToken)throw new Error("No token source: set config.token or config.getToken.");return this.inflight=Promise.resolve(this.config.getToken()).then(t=>{let i=bt(t),r=i?i-3e4:e+5*6e4;return this.cached={token:t,expiresAt:r},t}).finally(()=>{this.inflight=null;}),this.inflight}};function Re(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function xt(n){return n!==void 0&&Re(n)?n:void 0}function E(n){let e={};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);return e}var q=class{http;tenantId;environmentKey;tokenProvider;constructor(e){this.tenantId=e.tenantId,this.environmentKey=e.environmentKey,this.tokenProvider=new $(e),this.http=new D({baseUrl:e.baseUrl,defaultHeaders:e.headers,timeout:e.timeout,retry:e.retry,circuitBreaker:e.circuitBreaker,debug:e.debug});}tenantHeaders(){return {"X-Tenant-Id":this.tenantId,"X-Environment":this.environmentKey}}async authHeaders(){let e=this.tenantHeaders();if(!this.tokenProvider.hasSource())return e;let t=await this.tokenProvider.getToken();return t&&(e.Authorization=`Bearer ${t}`),e}async webhook(e,t,i="POST"){let{response:r,data:s}=await this.http.request({method:i,path:"/flow",query:{id:e},headers:await this.authHeaders(),body:i==="POST"?t??{}:void 0,noRetry:true});return {status:r.status,body:s,actions:ee(s),receivedAt:Date.now()}}async submitWidget(e,t){let{response:i,data:r}=await this.http.request({method:"POST",path:"/widget-submissions",query:{ref:e},headers:await this.authHeaders(),body:t??{},noRetry:true}),s=Re(r)?r:{};return {status:i.status,body:r,actions:ee(r),prize:xt(s.prize),alreadyPlayed:s.alreadyPlayed===true,dispatched:s.dispatched===true,dispatchError:typeof s.dispatchError=="string"?s.dispatchError:void 0,widgetType:typeof s.widgetType=="string"?s.widgetType:void 0,receivedAt:Date.now()}}async sendEvents(e,t){let{data:i}=await this.http.request({method:"POST",path:"/api/events/v1",headers:await this.authHeaders(),body:{events:e},keepalive:t?.keepalive});return i}async identify(e){let{data:t}=await this.http.request({method:"POST",path:"/api/events/v1/identify",headers:await this.authHeaders(),body:e});return t}async consent(e,t){let{data:i}=await this.http.request({method:"POST",path:"/api/events/v1/consent",headers:await this.authHeaders(),body:E({xeniaVisitorId:e,analytics:t.analytics===true,marketing:t.marketing===true,personalization:t.personalization===true,consentSource:t.consentSource,consentVersion:t.consentVersion})});return i}async resolve(e,t={}){let{data:i}=await this.http.request({method:"POST",path:"/api/personalization/resolve",query:t.merge!==void 0?{merge:String(t.merge)}:void 0,headers:await this.authHeaders(),body:E({contentKey:e,data:t.data,locale:t.locale})});return i}async resolveBatch(e,t={}){let{data:i}=await this.http.request({method:"POST",path:"/api/personalization/resolve-batch",query:t.merge!==void 0?{merge:String(t.merge)}:void 0,headers:await this.authHeaders(),body:E({items:e,data:t.data,locale:t.locale})});return i}async resolveEntries(e,t){let{data:i}=await this.http.request({method:"POST",path:"/api/personalization/resolve-entries",headers:await this.authHeaders(),body:E({entryIds:e,data:t.data,locale:t.locale,contentKey:t.contentKey})});return i}};var M="xenia";function ne(n=M){return `${n||M}_vid`}function Te(n=M){return `${n||M}_consent`}function Ie(n,e,t=365){return `${Te(e)}=${encodeURIComponent(JSON.stringify(n))}; path=/; max-age=${Math.floor(t*86400)}; SameSite=Lax`}var wt=new Set(["eventId","eventType","journeyId","deviceId","visitorId","customerId","email","utmSource","utmMedium","utmCampaign","utmContent","utmId","url","referrer","path","query"]);function Ae(n){let e={};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);return e}function Me(n){let e={},t={};if(n.props)for(let[r,s]of Object.entries(n.props))s!==void 0&&(wt.has(r)?t[r]=s:e[r]=s);return {...e,...t,...Ae(n.context??{}),...Ae(n.identity??{}),eventId:n.eventId,...n.eventType?{eventType:n.eventType}:{},...n.journeyId?{journeyId:n.journeyId}:{}}}var H="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function St(n){let e=new Uint8Array(n);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<n;t++)e[t]=Math.floor(Math.random()*256);return e}function C(n=Date.now()){let e="",t=n;for(let s=9;s>=0;s--)e=H[t%32]+e,t=Math.floor(t/32);let i=St(16),r="";for(let s=0;s<16;s++)r+=H[i[s]%32];return e+r}var ie=26;function Pe(n){if(n.length<=ie)return n;let e="";for(let i of [2166136261,16777619]){let r=i>>>0;for(let s=0;s<n.length;s++)r^=n.charCodeAt(s),r=Math.imul(r,16777619)>>>0,e+=H[r%32];}let t="";for(let i=0;i<ie;i++){let r=i+1;for(let s=i;s<e.length;s+=ie)r=r*31+H.indexOf(e[s])>>>0;t+=H[r%32];}return t}var kt=n=>n&&typeof n=="object"&&typeof structuredClone=="function"?structuredClone(n):n;async function se(n,e){let t=Tt(e.cms,e.contentKey),i=e.maxRounds??3,r=Date.now()+(e.timeoutMs??300),s=[],o=u=>{s.push(u);try{e.onApplied?.(u);}catch{}},l=n;try{!e.inPlace&&typeof structuredClone=="function"&&(l=structuredClone(l)),l=t.prepare?t.prepare(l):l;}catch(u){return {content:n,applied:s,complete:false,error:u}}let a={root:l},c=new WeakSet,d=new Map,m=[{parent:a,key:"root",value:a.root}],y=(u,h,f)=>{c.add(u.entry),t.clearMarker?.(u.entry);let p=h.items.map(kt);if(!h.decision||p.length===0)return Ct(u,t);for(let g of p)g&&typeof g=="object"&&c.add(g);let v=h.decision.op??u.marker.op??"replace",x=He(u,v,h.decision.field??u.marker.field,p,t);return o({target:u.id,kind:"runtime",op:v,entryIds:p.map(g=>t.entryId(g)).filter(g=>!!g),contentKey:h.decision.contentKey,bucket:h.decision.bucket,round:f}),x};for(let u=0;;u++){let h=Et(m,t,c,u,o,g=>{let w=d.get(g.id);return w?y(g,w,u):void 0});if(h.size===0)return {content:a.root,applied:s,complete:true};if(!e.resolve||u>=i)return {content:a.root,applied:s,complete:!e.resolve};Oe(e,{content:a.root,round:u,pending:[...h.keys()]});let f,p,v;try{f=await Ve(e.resolve([...h.keys()]),r),{entriesById:p,queried:v}=await Ve(Rt(f,t,e.locale),r);}catch(g){return {content:a.root,applied:s,complete:false,error:g===re?void 0:g}}let x=new Map(f.map(g=>[g.target,g]));m=[];for(let g of h.values()){let w=x.get(g.id),I=w?w.ids?w.ids.map(L=>p.get(L)).filter(L=>L!==void 0):v.get(w)??[]:[],k={decision:w,items:I};d.set(g.id,k),m.push(...y(g,k,u));}Oe(e,{content:a.root,round:u,pending:[]});}}function Oe(n,e){try{n.onProgress?.(e);}catch{}}function Et(n,e,t,i,r,s){let o=new Map,l=new WeakSet,a=new WeakSet,c=[...n];for(;c.length>0;){let d=c.shift(),m=d.value;if(!m||typeof m!="object"||a.has(m))continue;let y=t.has(m)?void 0:e.entryId(m),u=y?e.marker(m):null;if(y&&u?.kind==="runtime"){let h=s({id:y,marker:u,entry:m,slots:[d]});if(h){c.push(...h);continue}let f=o.get(y);if(f)f.slots.push(d);else if(o.set(y,{id:y,marker:u,entry:m,slots:[d]}),u.op==="items"&&u.field){let p=e.getField(m,u.field);p&&typeof p=="object"&&a.add(p),c.push(...Le(m));}continue}if(y&&u?.kind==="static"){let h=e.staticVariants(m).filter(f=>f&&typeof f=="object");if(t.add(m),e.clearMarker?.(m),h.length>0){for(let v of h)t.add(v);let f=u.op??"replace",p={entry:m,slots:[d]};c.push(...He(p,f,u.field,h,e)),r({target:y,kind:"static",op:f,entryIds:h.map(v=>e.entryId(v)).filter(v=>!!v),round:i});continue}}l.has(m)||(l.add(m),c.push(...Le(m)));}return o}function He(n,e,t,i,r){if(e==="items"){if(t)return r.setField(n.entry,t,i),[{parent:n.entry,key:t,value:r.getField(n.entry,t)}];if(r.mergeItems)return r.mergeItems(n.entry,i[0]),n.slots.map(o=>({...o,value:n.entry}));e="replace";}let s=[];for(let o of n.slots){let l=e==="expand"&&Array.isArray(o.parent)?i:[i[0]];if(Array.isArray(o.parent)){let a=o.parent.indexOf(n.entry);if(a<0)continue;o.parent.splice(a,1,...l);}else o.parent[o.key]=l[0];for(let a of l)s.push({parent:o.parent,key:o.key,value:a});}return s}function Ct(n,e){return n.marker.op==="items"&&n.marker.field?[{parent:n.entry,key:n.marker.field,value:e.getField(n.entry,n.marker.field)}]:n.slots.map(t=>({...t,value:n.entry}))}function Le(n){return Array.isArray(n)?n.map((e,t)=>({parent:n,key:t,value:e})):Object.keys(n).map(e=>({parent:n,key:e,value:n[e]}))}async function Rt(n,e,t){let i=[...new Set(n.flatMap(c=>c.ids??[]))],r=n.filter(c=>!c.ids&&c.query),[s,...o]=await Promise.all([i.length>0?e.fetchEntries(i,t):Promise.resolve([]),...r.map(c=>e.queryEntries(c.query,t).catch(()=>[]))]),l=new Map;for(let c of s){let d=e.entryId(c);d&&l.set(d,c);}let a=new Map;return r.forEach((c,d)=>a.set(c,o[d])),{entriesById:l,queried:a}}var re=Symbol("timeout");function Ve(n,e){let t=e-Date.now();if(t<=0)return Promise.reject(re);let i;return Promise.race([n,new Promise((r,s)=>{i=setTimeout(()=>s(re),t);})]).finally(()=>clearTimeout(i))}function Tt(n,e){return {...n,marker(t){let i=n.marker(t);return i&&e&&i.keys?.includes(e)?i:null}}}async function We(n,e){let t;try{if(!e.cms.fetchPage)throw new Error("This CMS adapter cannot fetch pages; use personalizeContent(page)");t=await e.cms.fetchPage(n,e.locale);}catch(i){return {content:null,applied:[],complete:false,error:i}}return t==null?{content:null,applied:[],complete:true}:se(t,e)}var z=class{map=new Map;set(e,t){this.map.set(e,t);}get(e){return this.map.get(e)}keys(){return [...this.map.keys()]}clear(){this.map.clear();}},J=class{nsKey;constructor(e="xenia"){this.nsKey=`${e}_responses`;}read(){try{let e=localStorage.getItem(this.nsKey);return e?JSON.parse(e):{}}catch{return {}}}write(e){try{localStorage.setItem(this.nsKey,JSON.stringify(e));}catch{}}set(e,t){let i=this.read();i[e]=t,this.write(i);}get(e){return this.read()[e]}keys(){return Object.keys(this.read())}clear(){try{localStorage.removeItem(this.nsKey);}catch{}}};var F=class{queue=[];send;batchSize;flushIntervalMs;maxQueueSize;debug;timer=null;flushing=false;listenersAttached=false;allowed=false;onPageHide=()=>this.flushOnUnload();onVisibilityChange=()=>{document.visibilityState==="hidden"&&this.flushOnUnload();};constructor(e){this.send=e.send,this.batchSize=e.batchSize??20,this.flushIntervalMs=e.flushIntervalMs??3e3,this.maxQueueSize=e.maxQueueSize??200,this.debug=e.debug??false;}start(){this.allowed=true,!(this.timer||typeof window>"u")&&(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibilityChange),this.listenersAttached=true);}stop(){this.allowed=false,this.timer&&clearInterval(this.timer),this.timer=null,this.listenersAttached&&(window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibilityChange),this.listenersAttached=false);}enqueue(e){this.queue.length>=this.maxQueueSize&&this.queue.shift(),this.queue.push(e),this.allowed&&this.queue.length>=this.batchSize&&this.flush();}async sendImmediate(e){try{await this.send([e],{keepalive:!0});}catch(t){this.isPermanentFailure(t)||this.requeue([e]),this.debug&&console.warn("[xenia] immediate send failed",t);}}async flush(){if(!this.allowed||this.flushing||this.queue.length===0)return;this.flushing=true;let e=this.queue.splice(0,this.batchSize);try{await this.send(e);}catch(t){this.isPermanentFailure(t)||this.requeue(e),this.debug&&console.warn("[xenia] analytics flush failed",t);}finally{this.flushing=false;}}isPermanentFailure(e){return e instanceof T&&e.status>=400&&e.status<500}flushOnUnload(){if(!this.allowed||this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length);this.send(e,{keepalive:true}).catch(()=>{});}requeue(e){let t=this.maxQueueSize-this.queue.length;t<=0||this.queue.unshift(...e.slice(0,t));}};var It=new Set(["click","view-port","page-load"]);function Ne(n){let e=n.indexOf("&");if(e===-1)return null;let t=n.slice(0,e),i=n.slice(e+1);return !t||!It.has(i)?null:{eventId:t,interactionType:i}}function _e(n){let e=c=>n.getAttribute(`data-xenia-${c}`)??void 0,t=e("content-key"),i=e("content-entry-id");if(!t&&!i)return null;let r=e("personalized"),s={},o=e("slot");o&&(s.slot=o),t&&(s.contentKey=t),i&&(s.contentEntryId=i);let l=e("base-entry-id");l&&(s.baseEntryId=l),r!=null&&(s.personalized=r==="true");let a=e("bucket");return a&&(s.bucket=a),s}var X=class{opts;throttleTimers=new Map;observers=new Map;slotObservers=new Map;triggered=new Set;slotImpressed=new Set;clickHandler=null;mutationObserver=null;constructor(e){this.opts=e;}start(){this.setupClicks(),this.scan(document),this.setupMutations();}stop(){this.clickHandler&&document.removeEventListener("click",this.clickHandler),this.clickHandler=null,this.mutationObserver?.disconnect(),this.mutationObserver=null,this.observers.forEach(e=>e.disconnect()),this.observers.clear(),this.slotObservers.forEach(e=>e.disconnect()),this.slotObservers.clear(),this.throttleTimers.clear(),this.triggered.clear(),this.slotImpressed.clear();}attr(){return `data-${this.opts.prefix}`}throttled(e){if(this.opts.throttleMs<=0)return false;let t=Date.now(),i=this.throttleTimers.get(e)??0;return t-i>=this.opts.throttleMs?(this.throttleTimers.set(e,t),false):true}setupClicks(){let e=this.attr();this.clickHandler=t=>{let i=t.target;if(!i)return;let r=i.closest(`[${e}]`);if(r){let s=r.getAttribute(e),o=s?Ne(s):null;o&&o.interactionType==="click"&&!this.throttled(r)&&this.opts.fire(o.eventId,"click");}if(this.opts.fireSlot){let s=i.closest("[data-xenia-slot]");if(s){let o=_e(s),l=i.closest("a, button"),a=l&&s.contains(l)?l:null;if(!a&&this.opts.slotClicks==="controls")return;let c=a?(a.textContent??"").trim().slice(0,60):"";o&&!this.throttled(s)&&this.opts.fireSlot("click",c?{...o,label:c}:o);}}},document.addEventListener("click",this.clickHandler);}observeSlot(e){if(!this.opts.fireSlot||this.slotObservers.has(e))return;let t=_e(e);if(!t)return;let i=this.opts.fireSlot,{threshold:r,rootMargin:s}=this.opts.viewport,o=new IntersectionObserver(l=>{for(let a of l)!(a.isIntersecting&&(a.intersectionRatio>=r||a.intersectionRect.height>=window.innerHeight/2))||this.slotImpressed.has(e)||(this.slotImpressed.add(e),i("impression",t),o.disconnect(),this.slotObservers.delete(e));},{threshold:[...new Set([.1,.25,r])].sort(),rootMargin:s});o.observe(At(e)),this.slotObservers.set(e,o);}observeViewport(e,t){if(this.observers.has(e))return;let{threshold:i,rootMargin:r,triggerOnce:s}=this.opts.viewport,o=new IntersectionObserver(l=>{for(let a of l)a.isIntersecting&&(s&&this.triggered.has(e)||this.throttled(e)||(this.opts.fire(t,"view-port"),s&&(this.triggered.add(e),o.disconnect(),this.observers.delete(e))));},{threshold:i,rootMargin:r});o.observe(e),this.observers.set(e,o);}handleElement(e){let t=e.getAttribute(this.attr());if(!t)return;let i=Ne(t);i&&(i.interactionType==="view-port"?this.observeViewport(e,i.eventId):i.interactionType==="page-load"&&this.opts.fire(i.eventId,"page-load"));}scan(e){e.querySelectorAll(`[${this.attr()}]`).forEach(t=>this.handleElement(t)),this.opts.fireSlot&&e.querySelectorAll("[data-xenia-slot]").forEach(t=>this.observeSlot(t));}setupMutations(){this.mutationObserver=new MutationObserver(e=>{for(let t of e)for(let i of t.addedNodes){if(i.nodeType!==Node.ELEMENT_NODE)continue;let r=i;this.handleElement(r),this.opts.fireSlot&&r.matches("[data-xenia-slot]")&&this.observeSlot(r),this.scan(r);}}),this.mutationObserver.observe(document.body,{childList:true,subtree:true});}};function At(n){return typeof getComputedStyle!="function"?n:getComputedStyle(n).display==="contents"?n.firstElementChild??n:n}var oe=8,De=1800;function $e(n=M){return `${n}_trail`}var Mt=n=>{try{return decodeURIComponent(n)}catch{return n}};function ae(n){if(!n)return [];try{let e=JSON.parse(Mt(n));return Array.isArray(e)?e.filter(t=>Array.isArray(t)&&typeof t[0]=="string"&&typeof t[1]=="number").slice(0,oe).map(([t,i,r])=>typeof r=="number"&&r>=0&&r<=86400?{path:t,at:i,seconds:r}:{path:t,at:i}):[]}catch{return []}}function qe(n,e,t=Date.now()){if(n[0]?.path===e)return n;let i=n.find(r=>r.path===e);return [{path:e,at:i?.at??t},...n.filter(r=>r.path!==e)].slice(0,oe)}function le(n){return JSON.stringify(n.slice(0,oe).map(e=>e.seconds===void 0?[e.path,e.at]:[e.path,e.at,e.seconds]))}var j=new Set,B=null;function ce(n){if(j.add(n),!B){let{pushState:e,replaceState:t}=history,i=()=>j.forEach(o=>{try{o();}catch{}}),r=function(...o){e.apply(this,o),i();},s=function(...o){t.apply(this,o),i();};history.pushState=r,history.replaceState=s,window.addEventListener("popstate",i),B=()=>history.pushState!==r||history.replaceState!==s?false:(history.pushState=e,history.replaceState=t,window.removeEventListener("popstate",i),true);}return ()=>{j.delete(n),!j.size&&B?.()&&(B=null);}}var ze=n=>document.querySelector(`meta[name="${n}"]`)?.content||void 0;function Je(n,e){let t=location.pathname,i=null,r,s={path:t,since:o(),sent:false};function o(){return document.visibilityState==="visible"?Date.now():null}function l(){clearTimeout(r);let y=Date.now(),u=()=>{if(!(document.title!==""&&document.title!==i)&&Date.now()-y<3e3){r=setTimeout(u,50);return}let f=new URLSearchParams(location.search),p=(f.get("utm_term")??f.get("q")??"").slice(0,120),v=ze("xenia-category");i=document.title,n.track("pageView",{title:(ze("xenia-title")??document.title).slice(0,160),...p?{searchTerm:p}:{},...v?{category:v}:{}});};r=setTimeout(u,0);}function a(){s.sent||s.since===null||Date.now()-s.since<250||(s.sent=true,n.track("page_leave",{path:s.path,durationMs:Date.now()-s.since}));}let c=()=>{location.pathname!==t&&(e.pageLeave&&a(),t=location.pathname,s={path:t,since:o(),sent:false},e.pageViews&&l());},d=()=>{document.visibilityState==="hidden"?a():s.since===null&&(s.since=Date.now());},m=ce(c);return e.pageLeave&&document.addEventListener("visibilitychange",d),e.pageViews&&l(),()=>{clearTimeout(r),m(),document.removeEventListener("visibilitychange",d);}}var Fe=(n,e)=>typeof n=="object"&&n.root||e;function de(n){return document.cookie.match(new RegExp(`(?:^|;\\s*)${n}=([^;]*)`))?.[1]}function ue(n,e){try{document.cookie=`${n}=${encodeURIComponent(e)}; path=/; max-age=${De}; samesite=lax`;}catch{}}function Xe(n){if(!(!n||n.origin!==location.origin))return n.pathname.split("/").filter(Boolean)[0]}function Pt(n,e){let t=n;for(let i=0;t&&i<5&&t!==e;i++,t=t.parentElement){let r=[...t.querySelectorAll("img")].filter(s=>s.alt.trim());if(r.length)return new Set(r.map(s=>s.alt.trim())).size===1?r[0]:null}return null}function je(n,e){let t=$e(e.prefix),i=`${e.prefix}_clicks`,r=()=>document.visibilityState==="visible"?Date.now():null,s={path:location.pathname,since:r(),stamped:false},o=()=>{if(s.stamped||!e.trail||!e.analyticsAllowed()||s.since===null)return;s.stamped=true;let f=Math.round((Date.now()-s.since)/100)/10,p=ae(de(t)),v=p.findIndex(x=>x.path===s.path);v<0||(p[v]={...p[v],seconds:f},ue(t,le(p)));},l=()=>{if(location.pathname===s.path||(o(),s={path:location.pathname,since:r(),stamped:false},!e.trail||!e.analyticsAllowed()))return;let f=ae(de(t)),p=qe(f,s.path);p!==f&&ue(t,le(p));},a=()=>{document.visibilityState==="visible"&&s.since===null&&(s.since=Date.now());},c=f=>{let p=f.target?.closest?.("a[href]");p&&p.origin===location.origin&&p.pathname!==location.pathname&&o();},d=()=>{e.analyticsAllowed()&&ue(i,String((Number(de(i))||0)+1));},m=Fe(e.navClicks,"header"),y=Fe(e.contentClicks,"main"),u=f=>{let p=f.target;if(!p?.closest)return;let v=e.navClicks?p.closest(`${m} a[href]`):null;if(v){let k=Xe(v);if(!k)return;n.track("nav_click",{category:k,label:(v.textContent??"").trim().slice(0,60)}),d();return}let x=e.contentClicks?p.closest(y):null;if(!x)return;let w=((p.closest("img")??Pt(p,x))?.alt??"").trim().slice(0,160);if(!w)return;let I=Xe(p.closest("a[href]"));n.track("content_click",I?{label:w,category:I}:{label:w}),d();},h=ce(l);return window.addEventListener("click",c,{capture:true}),document.addEventListener("visibilitychange",a),(e.contentClicks||e.navClicks)&&document.addEventListener("click",u,{capture:true}),()=>{h(),window.removeEventListener("click",c,{capture:true}),document.removeEventListener("visibilitychange",a),document.removeEventListener("click",u,{capture:true});}}function Be(n){let e={};if(!n)return e;for(let t of n.split(";")){let i=t.indexOf("=");if(i===-1)continue;let r=t.slice(0,i).trim(),s=t.slice(i+1).trim();if(r)try{e[r]=decodeURIComponent(s);}catch{e[r]=s;}}return e}var Ot=1800*1e3,U=class{prefix;cookie;deviceId=null;journeyId=null;sessionId=null;constructor(e="xenia",t=true){this.prefix=e,this.cookie=Lt(t);}key(e){return `${this.prefix}_${e}`}cookieName(){return ne(this.prefix)}writeVisitorCookie(e){if(!(!this.cookie||!e))try{if(typeof document>"u")return;let t=[`${this.cookieName()}=${encodeURIComponent(e)}`,"path=/",`max-age=${Math.floor(this.cookie.maxAgeDays*86400)}`,`SameSite=${this.cookie.sameSite}`];this.cookie.domain&&t.push(`domain=${this.cookie.domain}`),this.cookie.secure&&t.push("Secure"),document.cookie=t.join("; ");}catch{}}readVisitorCookie(){if(!this.cookie||typeof document>"u")return null;try{return Be(document.cookie)[this.cookieName()]||null}catch{return null}}async resolveDeviceId(){if(this.deviceId)return this.writeVisitorCookie(this.getVisitorId()??this.deviceId),this.deviceId;let e=this.key("device_id");try{let i=localStorage.getItem(e),r=this.cookie?.authoritative?this.readVisitorCookie():null,s=localStorage.getItem(this.key("visitor_id"))??i;if(i&&r&&r!==s)return this.deviceId=r,localStorage.setItem(e,r),localStorage.getItem(this.key("visitor_id"))&&localStorage.setItem(this.key("visitor_id"),r),r;if(i)return this.deviceId=i,this.writeVisitorCookie(this.getVisitorId()??i),i}catch{}let t=this.readVisitorCookie();t||(t=await this.mediaDeviceId()),t||(t=await this.fingerprint()),this.deviceId=t;try{localStorage.setItem(e,t);}catch{}return this.writeVisitorCookie(this.getVisitorId()??t),t}getDeviceId(){return this.deviceId}async mediaDeviceId(){try{if(!navigator.mediaDevices?.enumerateDevices)return null;let e=await navigator.mediaDevices.enumerateDevices();return (e.find(i=>i.kind==="videoinput"&&i.deviceId)||e.find(i=>i.kind==="audioinput"&&i.deviceId)||e.find(i=>i.kind==="audiooutput"&&i.deviceId))?.deviceId||null}catch{return null}}async fingerprint(){let e=[navigator.userAgent,navigator.language,screen.width,screen.height,screen.colorDepth,new Date().getTimezoneOffset()].join("|"),t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}identify(e){if(e){try{localStorage.setItem(this.key("visitor_id"),e);}catch{}this.writeVisitorCookie(e);}}getVisitorId(){try{return localStorage.getItem(this.key("visitor_id"))}catch{return null}}setCustomerId(e){try{e?localStorage.setItem(this.key("customer_id"),e):localStorage.removeItem(this.key("customer_id"));}catch{}}getCustomerId(){try{return localStorage.getItem(this.key("customer_id"))}catch{return null}}setEmail(e){try{e?localStorage.setItem(this.key("email"),e):localStorage.removeItem(this.key("email"));}catch{}}getEmail(){try{return localStorage.getItem(this.key("email"))}catch{return null}}getSessionId(){let e=this.key("session_id"),t=this.key("session_last_activity"),i=Date.now();try{let r=sessionStorage.getItem(e),s=Number(sessionStorage.getItem(t)),l=r&&Number.isFinite(s)&&i-s<Ot?r:C(i);return sessionStorage.setItem(e,l),sessionStorage.setItem(t,String(i)),this.sessionId=l,l}catch{return this.sessionId||(this.sessionId=C(i)),this.sessionId}}setJourneyId(e){this.journeyId=e&&e.trim()?e.trim():null;}getJourneyId(){return this.journeyId||this.utmParam("utm_id")||null}utmParam(e){try{let t=new URLSearchParams(window.location.search).get(e);if(t){try{sessionStorage.setItem(this.key(e),t);}catch{}return t}try{return sessionStorage.getItem(this.key(e))}catch{}}catch{}return null}collectContext(){let e={},t=this.utmParam("utm_source"),i=this.utmParam("utm_medium"),r=this.utmParam("utm_campaign"),s=this.utmParam("utm_content"),o=this.utmParam("utm_id");t&&(e.utmSource=t),i&&(e.utmMedium=i),r&&(e.utmCampaign=r),s&&(e.utmContent=s),o&&(e.utmId=o);try{e.url=window.location.href,e.path=window.location.pathname,e.query=Object.fromEntries(new URLSearchParams(window.location.search)),document.referrer&&(e.referrer=document.referrer);}catch{}let l=this.getVisitorId();return l&&(e.visitorId=l),e}};function Lt(n){if(n===false)return null;let e=n===true?{}:n,t=e.sameSite??"Lax",i=t==="None"?true:e.secure??false;return {sameSite:t,secure:i,maxAgeDays:e.maxAgeDays??365,domain:e.domain,authoritative:e.authoritative??false}}function K(n){let e={};return n.querySelectorAll("[data-xenia-field]").forEach(t=>{let i=t.getAttribute("data-xenia-field");i&&(e[i]=Vt(t));}),e}function Vt(n){return n instanceof HTMLInputElement?n.type==="checkbox"?n.checked?n.value||"on":"":n.type==="radio"?n.checked?n.value:"":n.value:n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement?n.value:n.textContent?.trim()??""}function Ue(n,e){n&&(n instanceof HTMLButtonElement||n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement||n instanceof HTMLFieldSetElement?n.disabled=e:e?n.setAttribute("aria-disabled","true"):n.removeAttribute("aria-disabled"));}function pe(n,e){let t=n.querySelector("[data-xenia-error]");t&&(t.textContent=e);}var Ke="xenia-form-submit-style";function Ht(n){if(n.querySelector(`#${Ke}`))return;let e=document.createElement("style");e.id=Ke,e.textContent="@keyframes xenia-submit-spin{to{transform:rotate(360deg)}}[data-xenia-submitting]::after{content:'';display:inline-block;width:0.85em;height:0.85em;margin-left:0.5em;vertical-align:-0.15em;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:xenia-submit-spin 0.6s linear infinite}",n.prepend(e);}function me(n,e){n&&(e?n.setAttribute("data-xenia-submitting",""):n.removeAttribute("data-xenia-submitting"));}function Wt(n,e){if(!e)return;let t=n instanceof ShadowRoot?n.host:n;t instanceof HTMLElement?(t.style.transition="opacity 220ms ease, transform 220ms ease",t.style.opacity="0",t.style.transform="scale(0.96)",window.setTimeout(e,220)):e();}var Nt=900;function _t(n,e){let t=n.querySelector("[data-xenia-success]");return t?(t instanceof HTMLElement?t.hidden=false:t.removeAttribute("hidden"),e?e.hidden=true:n.querySelectorAll("[data-xenia-field], [data-xenia-submit]").forEach(i=>{i.hidden=true;}),true):false}function Qe(n,e,t){let i=n.querySelector("form"),r=false;Ht(n);let s=(o,l)=>{if(r)return;if(!e.formSubmit){pe(n,"This form isn't connected yet.");return}r=true,pe(n,""),Ue(o,true),me(o,true);let a=Date.now(),c=e.formSubmit.successDisplayMs??Nt;t.submitWidgetForm(l).then(()=>{me(o,false),_t(n,i);let d=Math.max(0,c-(Date.now()-a));window.setTimeout(()=>Wt(n,t.dismiss),d);}).catch(()=>{me(o,false),Ue(o,false),pe(n,"Something went wrong. Please try again.");}).finally(()=>{r=false;});};i&&i.addEventListener("submit",o=>{o.preventDefault();let l={};new FormData(i).forEach((c,d)=>{typeof c=="string"&&(l[d]=c);});let a=o.submitter??i.querySelector('[type="submit"], button:not([type])');s(a,{...K(n),...l});}),n.querySelectorAll("[data-xenia-submit]").forEach(o=>{i?.contains(o)||o.addEventListener("click",()=>s(o,K(n)));});}function fe(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Ge(n){return fe(n).replace(/"/g,""")}function Q(n,e){e&&n.querySelectorAll(".xenia-close, [data-xenia-close], [class*='close' i], [id*='close' i], [class*='backdrop' i], [id*='backdrop' i]").forEach(i=>{i.removeAttribute("onclick"),i.addEventListener("click",e);}),n.querySelectorAll("[class*='backdrop' i], [id*='backdrop' i]").forEach(t=>{t instanceof HTMLElement&&t.children.length===0&&!t.textContent?.trim()&&(t.style.opacity="0.5");});}var P=260,W=P/2,O=P/2,Ye=["#7c3aed","#2563eb","#059669","#d97706","#dc2626","#0891b2"],Dt="transform 3.2s cubic-bezier(0.15, 0.85, 0.25, 1)",$t='<div class="xenia-wheel-pointer" aria-hidden="true"></div>',ge=320,Ze=`opacity ${ge}ms ease, transform ${ge}ms ease`,qt=900,he=(n,e)=>`perspective(${qt}px) translateZ(${e}px) scale(${n})`;function ye(n,e){let t=n*Math.PI/180;return {x:O+e*Math.sin(t),y:O-e*Math.cos(t)}}function zt(n,e){let t=ye(n,W),i=ye(e,W),r=e-n>180?1:0;return `M ${O},${O} L ${t.x},${t.y} A ${W},${W} 0 ${r} 1 ${i.x},${i.y} Z`}function Jt(n,e,t=0){if(e<=0)return 0;let i=360/e,s=(360-(n*i+i/2))%360;return t*360+s}function tt(n,e){let t=n?Array.from(n.children):[],i=e?Array.from(e.children):[];e&&(e.hidden=false),i.forEach(r=>{r instanceof HTMLElement&&(r.style.transition="none",r.style.opacity="0",r.style.transform=he(.94,-60));}),i.forEach(r=>{r instanceof HTMLElement&&r.offsetHeight;}),nt(()=>{t.forEach(r=>{r instanceof HTMLElement&&(r.style.transition=Ze,r.style.opacity="0",r.style.transform=he(.94,-60));}),i.forEach(r=>{r instanceof HTMLElement&&(r.style.transition=Ze,r.style.opacity="1",r.style.transform=he(1,0));});}),n&&setTimeout(()=>{n.hidden=true;},ge);}function nt(n){typeof requestAnimationFrame=="function"?requestAnimationFrame(n):setTimeout(n,0);}function Ft(n){let t=360/(n.length||1),i=n.map((r,s)=>{let o=s*t,l=o+t,a=r.colorHex||Ye[s%Ye.length],c=o+t/2,d=ye(c,W*.62);return `<path d="${zt(o,l)}" fill="${Ge(a)}" stroke="#fff" stroke-width="1"></path><text x="${d.x}" y="${d.y}" fill="#fff" font-size="12" text-anchor="middle" transform="rotate(${c} ${d.x} ${d.y})">${fe(r.label)}</text>`}).join("");return `<svg class="xenia-wheel-svg" viewBox="0 0 ${P} ${P}" width="${P}" height="${P}"><g class="xenia-wheel-dial">${i}</g><circle class="xenia-wheel-hub" cx="${O}" cy="${O}" r="6"></circle></svg>`}var it={html(n){return `<div class="xenia-spin-wheel"><div data-xenia-wheel-face>${n.spinnerHtml??""}</div><div class="xenia-widget-result" data-xenia-wheel-result hidden>${n.winHtml??""}</div><div class="xenia-widget-result" data-xenia-wheel-loss hidden>${n.lossHtml??""}</div></div>`},wire(n,e,t){Q(n,t.dismiss);let i=e.segments??[],r=n.querySelector("[data-xenia-wheel-face]"),s=n.querySelector("[data-xenia-spin]"),o=n.querySelector("[data-xenia-wheel-result]"),l=n.querySelector("[data-xenia-wheel-loss]"),a=n.querySelector("[data-xenia-error]"),c=n.querySelector("[data-xenia-wheel-slot]");c&&c.insertAdjacentHTML("afterbegin",Ft(i)+$t);let d=n.querySelector(".xenia-wheel-dial");if(!s||!e.formSubmit)return;n.querySelectorAll("[data-xenia-wheel-cta]").forEach(h=>{h.addEventListener("click",()=>t.fireCta());});let m=(h,f,p)=>{n.querySelectorAll("[data-xenia-wheel-prize]").forEach(g=>{g.textContent=h;});let v=f?l:o,x=f?o:l;x&&(x.hidden=true),tt(r,v),p||(u=true,n.querySelectorAll("[data-xenia-spin-again]").forEach(g=>{g.hidden=true;}));},y=false,u=false;n.querySelectorAll("[data-xenia-spin-again]").forEach(h=>{h.addEventListener("click",()=>{if(u)return;let f=o&&!o.hidden?o:l&&!l.hidden?l:null;f&&(y=false,s.disabled=false,a&&(a.textContent=""),tt(f,r));});}),s.addEventListener("click",()=>{if(y)return;y=true,s.disabled=true,a&&(a.textContent="");let h=K(n);t.submitWidgetForm(h).then(f=>{let p=i.findIndex(at=>at.id===f.prize?.segmentId),v=f.prize?.label??i[p]?.label??"",x=p>=0&&!!i[p]?.isLoss,g=f.alreadyPlayed!==true;if(p<0||!d){m(v,x,g);return}let w=3+Math.floor(Math.random()*3),I=Jt(p,i.length||1,w),k=/rotate\(([-\d.]+)deg\)/.exec(d.style.transform),L=k?parseFloat(k[1]):0;d.style.transition="none",d.style.transform=`rotate(${L%360}deg)`,d.getBoundingClientRect(),d.style.transition=Dt;let Se=()=>{d.removeEventListener("transitionend",Se),m(v,x,g);};d.addEventListener("transitionend",Se),nt(()=>{d.style.transform=`rotate(${I}deg)`;});}).catch(()=>{y=false,s.disabled=false,a&&(a.textContent="Something went wrong. Please try again.");});});}};var ve={"spin-wheel":it};function Z(n,e=document){if(!n)return null;let t=e.querySelector(`[data-xenia-slot="${Xt(n)}"]`);if(t)return t;try{return e.querySelector(n)}catch{return null}}function Xt(n){let e=window;return e.CSS?.escape?e.CSS.escape(n):n.replace(/["\\]/g,"\\$&")}function G(n,e){let t=Z(n);return t?(e.html!==void 0?t.innerHTML=e.html:e.text!==void 0&&(t.textContent=e.text),t.removeAttribute("hidden"),true):false}function be(n){let e=Z(n);return !e||!(e instanceof HTMLElement)?false:(e.dataset.xeniaHidden="1",e.style.setProperty("display","none","important"),true)}function xe(n){let e=Z(n);return !e||!(e instanceof HTMLElement)?false:(delete e.dataset.xeniaHidden,e.style.removeProperty("display"),true)}var jt=new Set(["banner","popup","modal","inline"]);function Bt(n){return jt.has(n)}var Y=class{host=null;shadow=null;onCta;messageTemplate;messageStyles;messageComponent;submitWidgetFormFn;mounted=new Map;constructor(e,t){this.onCta=e,this.messageTemplate=t?.messageTemplate,this.messageStyles=t?.messageStyles,this.messageComponent=t?.messageComponent,this.submitWidgetFormFn=t?.submitWidgetForm;}apply(e){let t=0;for(let i of e)this.applyOne(i)&&t++;return t}applyOne(e){switch(e.type){case "swap":return G(e.target,{html:e.html,text:e.text});case "setContent":return G(e.target,{html:e.html,text:e.text});case "hide":return be(e.target);case "show":return xe(e.target);case "redirect":try{return window.location.assign(e.url),!0}catch{return false}default:return Bt(e.type)?this.renderMessage(e):false}}destroy(){this.mounted.forEach(e=>e()),this.mounted.clear(),this.host?.remove(),this.host=null,this.shadow=null;}ensureShadow(){if(this.shadow)return this.shadow;let e=document.createElement("div");e.setAttribute("data-xenia-ui",""),document.body.appendChild(e);let t=e.attachShadow({mode:"open"});return t.appendChild(this.styleEl()),this.host=e,this.shadow=t,t}styleEl(){let e=document.createElement("style");return e.textContent=this.messageStyles?`${st}
|
|
2
|
+
${this.messageStyles}`:st,e}renderMessage(e){let t=e.html===void 0&&!!this.messageComponent;if(e.type==="inline"){if(!e.target)return false;let c=Z(e.target);return c?(this.unmount(c),t?(c.innerHTML="",this.mountComponent(c,e,"inline",()=>this.unmount(c))):(c.innerHTML=this.cardHtml(e,"inline"),this.wireCard(c,e)),true):false}let i=this.ensureShadow(),r=document.createElement("div"),s=this.positionClass(e.type,e.position),o=e.html!==void 0?" xenia-custom-bg":"",l=e.style?.hideOverlay?" xenia-no-overlay":"";r.className=`xenia-msg xenia-${e.type}${s?` ${s}`:""}${o}${l}`,i.appendChild(r);let a=()=>{this.unmount(r),r.remove();};if(t?this.mountComponent(r,e,e.type,a):(r.innerHTML=this.cardHtml(e,e.type),this.wireCard(r,e,a)),e.dismissAfterMs&&e.dismissAfterMs>0){let c=setTimeout(a,e.dismissAfterMs),d=()=>clearTimeout(c);r.addEventListener("click",d,{once:true}),r.addEventListener("focusin",d,{once:true});}return true}mountComponent(e,t,i,r){if(!this.messageComponent)return;let s={action:t,variant:i,close:r,fireCta:()=>{t.cta?.event&&this.onCta?.(t.cta.event,t.cta),t.cta?.url&&window.location.assign(t.cta.url),r();}},o=this.messageComponent(e,s);o&&this.mounted.set(e,o);}unmount(e){let t=this.mounted.get(e);t&&(t(),this.mounted.delete(e));}positionClass(e,t){return e==="popup"?`xenia-pos-${t==="top-left"||t==="top-right"||t==="bottom-left"?t:"bottom-right"}`:e==="banner"?`xenia-pos-${t==="top"?"top":"bottom"}`:""}cardHtml(e,t){let i=e.widgetType?ve[e.widgetType]:void 0;if(i)return i.html(e,t);if(e.html!==void 0)return Ut(e.html,t);if(this.messageTemplate){let c={action:e,variant:t,escapeHtml:N,escapeAttr:rt};return this.messageTemplate(c)}let r=e.imageUrl?`<img class="xenia-img" src="${rt(e.imageUrl)}" alt="" />`:"",s=e.title?`<div class="xenia-title">${N(e.title)}</div>`:"",o=e.message?`<div class="xenia-body">${N(e.message)}</div>`:"",l=e.cta?`<button class="xenia-cta" type="button">${N(e.cta.label)}</button>`:"";return `<div class="xenia-card">${t==="inline"?"":'<button class="xenia-close" type="button" aria-label="Close">\xD7</button>'}${r}<div class="xenia-content">${s}${o}${l}</div></div>`}wireCard(e,t,i){let r=t.widgetType?ve[t.widgetType]:void 0;if(r){r.wire(e,t,this.buildWidgetCtx(t,i));return}Q(e,i);let s=e.querySelector(".xenia-cta, [data-xenia-cta]");s&&t.cta&&s.addEventListener("click",()=>{t.cta?.event&&this.onCta?.(t.cta.event,t.cta),t.cta?.url&&window.location.assign(t.cta.url),i?.();}),Qe(e,t,this.buildWidgetCtx(t,i));}buildWidgetCtx(e,t){let i=C();return {dismiss:t,fireCta:()=>{e.cta?.event&&this.onCta?.(e.cta.event,e.cta),e.cta?.url&&window.location.assign(e.cta.url),t?.();},submitWidgetForm:r=>!e.formSubmit||!this.submitWidgetFormFn?Promise.reject(new Error("xenia: this action has no formSubmit config, or no submitWidgetForm handler is wired (construct the ActionRenderer via XeniaClient to get one)")):this.submitWidgetFormFn(e.formSubmit,r,{idempotencyKey:i})}}};function Ut(n,e){return e==="modal"?`<div class="xenia-custom-html">${n}</div>`:`<div class="xenia-custom-html"><style>.xenia-custom-html{position:relative}.xenia-custom-html>*{position:static!important;inset:auto!important;top:auto!important;right:auto!important;bottom:auto!important;left:auto!important}</style>${n}</div>`}function N(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function rt(n){return N(n).replace(/"/g,""")}var st=`
|
|
3
3
|
:host { all: initial; }
|
|
4
4
|
.xenia-msg { position: fixed; z-index: var(--xenia-z-index, 2147483000);
|
|
5
5
|
font-family: var(--xenia-font-family, system-ui, sans-serif); }
|
|
@@ -76,6 +76,6 @@ ${this.messageStyles}`:_e,e}renderMessage(e){let t=e.html===void 0&&!!this.messa
|
|
|
76
76
|
.xenia-widget-result-cta { margin-top: 8px; background: var(--xenia-cta-bg, #111); color: var(--xenia-cta-color, #fff);
|
|
77
77
|
border: 0; border-radius: var(--xenia-cta-radius, 8px); padding: var(--xenia-cta-padding, 8px 14px);
|
|
78
78
|
font-size: var(--xenia-cta-size, 14px); font-family: inherit; cursor: pointer; }
|
|
79
|
-
`;var
|
|
79
|
+
`;var we=class{api;identity;responses;options;renderer;analyticsQueue;tracker=null;stopPageTracking=null;stopEngagement=null;booting=null;generation=0;consentState;listeners=new Map;constructor(e){this.options=e;let t=e.prefix??"xenia";this.identity=new U(t,e.visitorCookie??true),e.visitorId&&this.identity.identify(e.visitorId),this.api=new q(e),this.responses=e.persistResponses===false||!V()?new z:new J(t),this.renderer=new Y((i,r)=>this.onCtaEvent(i,r),{messageTemplate:e.messageTemplate,messageStyles:e.messageStyles,messageComponent:e.messageComponent,submitWidgetForm:(i,r,s)=>this.submitWidgetForm(i,r,s)}),this.consentState={...e.consent},this.analyticsQueue=new F({debug:e.debug,send:(i,r)=>this.api.sendEvents(i.map(s=>({...s,consent:this.consentState})),r)});}init(){return V()?this.booting??=this.boot():Promise.resolve()}async boot(){let e=this.generation;if(await this.identity.resolveDeviceId(),e!==this.generation)return;this.analyticsAllowed()&&this.analyticsQueue.start(),this.options.autoTrack!==false&&(this.tracker=new X({prefix:this.options.prefix??"xenia",throttleMs:this.options.throttleMs??1e3,viewport:{threshold:this.options.viewport?.threshold??.5,rootMargin:this.options.viewport?.rootMargin,triggerOnce:this.options.viewport?.triggerOnce??true},slotClicks:this.options.slotClicks,fire:(l,a)=>this.track(l,{interactionType:a},{trigger:true}),fireSlot:(l,a)=>{this.track("customEvent",{customEventName:l==="impression"?"personalization_impression":"personalization_click",...a.contentKey?{contentKey:a.contentKey}:{},contentEntryId:a.contentEntryId??null,baseEntryId:a.baseEntryId??null,...a.bucket?{bucket:a.bucket}:{},...a.slot?{slot:a.slot}:{},...a.label?{label:a.label}:{}},{trigger:false});}}),this.tracker.start());let{pageViews:t=false,pageLeave:i=false}=this.options;(t||i)&&(this.stopPageTracking=Je({track:(l,a)=>this.track(l,a)},{pageViews:t,pageLeave:i}));let{trail:r=false,contentClicks:s=false,navClicks:o=false}=this.options;(r||s||o)&&(this.stopEngagement=je({track:(l,a)=>this.track(l,a)},{trail:r,contentClicks:s,navClicks:o,prefix:this.options.prefix??"xenia",analyticsAllowed:()=>this.analyticsAllowed()&&!this.dntBlocked()}));}destroy(){this.tracker?.stop(),this.tracker=null,this.stopPageTracking?.(),this.stopPageTracking=null,this.stopEngagement?.(),this.stopEngagement=null,this.renderer.destroy(),this.analyticsQueue.stop(),this.booting=null,this.generation++;}identify(e,t){this.identity.identify(e),t?.customerId!==void 0&&this.identity.setCustomerId(t.customerId),t?.email!==void 0&&this.identity.setEmail(t.email),this.api.identify({xeniaVisitorId:e,userId:t?.customerId,email:t?.email}).then(i=>this.emit("identify",i)).catch(i=>this.emitError(i));}setJourneyId(e){this.identity.setJourneyId(e);}track(e,t,i={}){if(!V())return;let r=i.trigger===true;if(!r&&this.dntBlocked())return;let s=this.buildEvent(e,t,i);this.emit("event",{eventName:e,event:s}),r?this.analyticsQueue.sendImmediate(s).catch(o=>this.emitError(o)):(this.analyticsQueue.enqueue(s),this.analyticsAllowed()&&this.analyticsQueue.start());}buildEvent(e,t,i){let r=this.identity.collectContext(),s;try{s=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch{}return {eventName:e,eventId:i.eventId?Pe(i.eventId):C(),eventVersion:1,occurredAtMs:Date.now(),source:"xenia-js-sdk",identity:{sessionId:this.identity.getSessionId(),...i.identity,xeniaVisitorId:r.visitorId??this.identity.getDeviceId()??void 0},context:{pagePath:r.path,referrer:r.referrer,userAgent:navigator.userAgent,locale:navigator.language,timezone:s,journeyId:this.identity.getJourneyId()??void 0,utmSource:r.utmSource,utmMedium:r.utmMedium,utmCampaign:r.utmCampaign,utmContent:r.utmContent,...i.context},properties:this.withUtmId(t,r.utmId),trigger:i.trigger===true?true:void 0}}withUtmId(e,t){return !t||e&&(e.utm_id!==void 0||e.utmId!==void 0)?e:{...e,utm_id:t}}async resolve(e,t){return this.api.resolve(e,this.withVisitor(t))}async resolveBatch(e,t){return this.api.resolveBatch(e,this.withVisitor(t))}async personalizeContent(e,t){return se(e,{...t,resolve:this.entryResolver(t)})}async personalizePage(e,t){return We(e,{...t,resolve:this.entryResolver(t)})}entryResolver(e){let t={...this.withVisitor({data:e.data,locale:e.locale}),contentKey:e.contentKey};return async i=>(await this.api.resolveEntries(i,t)).decisions??[]}resolveVisitorId(){return this.identity.getVisitorId()??this.identity.getDeviceId()??void 0}withVisitor(e){let t=this.identity.collectContext(),i=this.resolveVisitorId(),r=E({path:t.path,query:t.query,deviceId:this.identity.getDeviceId()??void 0,visitorId:i,customerId:this.identity.getCustomerId()??void 0,email:this.identity.getEmail()??void 0,url:t.url,referrer:t.referrer,utmSource:t.utmSource,utmMedium:t.utmMedium,utmCampaign:t.utmCampaign,utmContent:t.utmContent,utmId:t.utmId});return i&&(r._xenia_vid=i),Object.keys(r).length===0?e:{...e,data:{...e?.data??{},...r}}}dntBlocked(){if(this.options.respectDnt===false)return false;try{let e=navigator,t=navigator.doNotTrack??window.doNotTrack;if(t==="1"||t==="yes"||e.globalPrivacyControl===!0)return !0}catch{}return false}analyticsAllowed(){return this.consentState.analytics===true}async request(e,t,i){let r=this.identity.collectContext(),s=Me({eventId:e,journeyId:this.identity.getJourneyId()??void 0,identity:{deviceId:this.identity.getDeviceId()??void 0,visitorId:this.resolveVisitorId()},context:r,props:t}),o=await this.api.webhook(e,s,i?.method??"POST");return this.responses.set(e,o),this.emit("response",{triggerId:e,response:o}),(i?.apply??this.options.autoApplyActions!==false)&&o.actions.length&&this.applyActions(o.actions),o}getResponse(e){return this.responses.get(e)}async submitWidgetForm(e,t,i){let r=this.identity.collectContext(),s=i?.idempotencyKey??C(),o=e.flowRef??e.bindingRef,l={visitorId:this.resolveVisitorId(),deviceId:this.identity.getDeviceId()??void 0,idempotencyKey:s,mode:e.mode,ref:o,url:r.url,referrer:r.referrer,path:r.path,query:r.query,utmSource:r.utmSource,utmMedium:r.utmMedium,utmCampaign:r.utmCampaign,utmContent:r.utmContent,utmId:r.utmId},a=e.flowRef?await this.api.webhook(e.flowRef,E({...l,...t}),"POST"):await this.api.submitWidget(e.bindingRef??"",E({...l,fields:t}));return this.emit("response",{triggerId:o,response:a}),(i?.apply??this.options.autoApplyActions!==false)&&a.actions.length&&this.applyActions(a.actions),a}swapContent(e,t){return G(e,t)}hideContent(e){return be(e)}showContent(e){return xe(e)}applyActions(e){let t=this.renderer.apply(e);return this.emit("actions",{actions:e,applied:t}),t}async consent(e){let t=this.analyticsAllowed();if(this.consentState={...this.consentState,...e},V())try{document.cookie=Ie(this.consentState,this.options.prefix);}catch{}this.analyticsAllowed()&&!t?(this.analyticsQueue.start(),this.analyticsQueue.flush()):!this.analyticsAllowed()&&t&&this.analyticsQueue.stop();let i=this.identity.getVisitorId()??this.identity.getDeviceId();if(i)try{await this.api.consent(i,e);}catch(r){this.emitError(r);}}on(e,t){let i=this.listeners.get(e)??new Set;return i.add(t),this.listeners.set(e,i),()=>i.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(i=>{try{i(t);}catch{}});}emitError(e){let t=e instanceof Error?e:new Error(String(e));this.options.debug&&console.error("[xenia]",t),this.emit("error",t);}onCtaEvent(e,t){this.track(e,{ctaLabel:t.label,ctaUrl:t.url??null},{trigger:true});}};function ot(n){return new we(n)}var R=null;function S(n){if(!R)throw console.warn(`[xenia] ${n}() called before init().`),new Error("Xenia not initialized");return R}var Gn={init(n){R&&R.destroy(),R=ot(n),R.init();},destroy(){R?.destroy(),R=null;},track(n,e,t){S("track").track(n,e,t);},identify(n){S("identify").identify(n);},consent(n){return S("consent").consent(n)},resolve(n,e){return S("resolve").resolve(n,e)},resolveBatch(n,e){return S("resolveBatch").resolveBatch(n,e)},setJourneyId(n){S("setJourneyId").setJourneyId(n);},request(n,e){return S("request").request(n,e)},getResponse(n){return S("getResponse").getResponse(n)},swapContent(n,e){return S("swapContent").swapContent(n,e)},hideContent(n){return S("hideContent").hideContent(n)},showContent(n){return S("showContent").showContent(n)}};exports.Xenia=Gn;return exports;})({});
|
|
80
80
|
Xenia=Xenia&&(Xenia.Xenia||Xenia.default)||Xenia;if(typeof window!=='undefined'){window.Xenia=Xenia;}
|
|
81
81
|
//# sourceMappingURL=xenia-sdk.iife.js.map
|