@xenia-martech/sdk-js 1.0.0-dev.26 → 1.0.0-dev.27

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.
Files changed (36) hide show
  1. package/README.md +21 -1
  2. package/dist/{actions-DFLoSXO_.d.cts → actions-CkiSdvSa.d.cts} +65 -5
  3. package/dist/{actions-DFLoSXO_.d.ts → actions-CkiSdvSa.d.ts} +65 -5
  4. package/dist/{chunk-D37RD3UC.js → chunk-7D2HJMW6.js} +31 -3
  5. package/dist/chunk-7D2HJMW6.js.map +1 -0
  6. package/dist/{chunk-3KYKKIIG.cjs → chunk-UOW3GK4I.cjs} +32 -2
  7. package/dist/chunk-UOW3GK4I.cjs.map +1 -0
  8. package/dist/client/index.cjs +73 -8
  9. package/dist/client/index.cjs.map +1 -1
  10. package/dist/client/index.d.cts +2 -2
  11. package/dist/client/index.d.ts +2 -2
  12. package/dist/client/index.js +73 -8
  13. package/dist/client/index.js.map +1 -1
  14. package/dist/client/react/index.cjs +73 -8
  15. package/dist/client/react/index.cjs.map +1 -1
  16. package/dist/client/react/index.d.cts +2 -2
  17. package/dist/client/react/index.d.ts +2 -2
  18. package/dist/client/react/index.js +73 -8
  19. package/dist/client/react/index.js.map +1 -1
  20. package/dist/{cookie-names-LgNDAreS.d.cts → cookie-names-C3LKDhsg.d.cts} +34 -0
  21. package/dist/{cookie-names-LgNDAreS.d.ts → cookie-names-C3LKDhsg.d.ts} +34 -0
  22. package/dist/index.cjs +23 -19
  23. package/dist/index.d.cts +23 -3
  24. package/dist/index.d.ts +23 -3
  25. package/dist/index.js +1 -1
  26. package/dist/server/index.cjs +53 -22
  27. package/dist/server/index.cjs.map +1 -1
  28. package/dist/server/index.d.cts +31 -11
  29. package/dist/server/index.d.ts +31 -11
  30. package/dist/server/index.js +43 -12
  31. package/dist/server/index.js.map +1 -1
  32. package/dist/xenia-sdk.iife.js +3 -3
  33. package/dist/xenia-sdk.iife.js.map +1 -1
  34. package/package.json +1 -1
  35. package/dist/chunk-3KYKKIIG.cjs.map +0 -1
  36. package/dist/chunk-D37RD3UC.js.map +0 -1
@@ -1,12 +1,14 @@
1
- import { s as CallerIdentity, A as AnalyticsContext, J as JsonValue, d as ConsentState, e as EventIdentity, E as EventContext, n as XeniaApi, o as XeniaConfig, a as AnalyticsEventName, c as AnalyticsIngestResponse, W as WebhookResponse, I as IdentifyRequest, f as IdentifyResponse, l as ResolveOptions, m as ResolveResult, j as ResolveBatchItem, k as ResolveBatchResult } from '../cookie-names-LgNDAreS.cjs';
2
- export { b as AnalyticsIdentity, C as CONSENT_COOKIE, P as PersonalizationSwap, V as VISITOR_COOKIE, p as XeniaEvent, q as consentCookieName, r as parseActions, v as visitorCookieName } from '../cookie-names-LgNDAreS.cjs';
1
+ import { s as CallerIdentity, A as AnalyticsContext, J as JsonValue, d as ConsentState, e as EventIdentity, E as EventContext, n as XeniaApi, o as XeniaConfig, a as AnalyticsEventName, c as AnalyticsIngestResponse, W as WebhookResponse, I as IdentifyRequest, f as IdentifyResponse, l as ResolveOptions, m as ResolveResult, j as ResolveBatchItem, k as ResolveBatchResult } from '../cookie-names-C3LKDhsg.cjs';
2
+ export { b as AnalyticsIdentity, C as CONSENT_COOKIE, P as PersonalizationSwap, V as VISITOR_COOKIE, p as XeniaEvent, q as consentCookieName, r as parseActions, v as visitorCookieName } from '../cookie-names-C3LKDhsg.cjs';
3
3
 
4
4
  /**
5
- * Extra per-call identity/context for server-side webhook calls. There's no
6
- * ambient `window` on the server to auto-collect `path`/`query`/`url`/UTM
7
- * params the way the browser client does — pass whatever's known at the call
8
- * site (e.g. the current request's pathname from Next.js `headers()`/route
9
- * params) via `context`, and `deviceId`/`visitorId`/etc. via `identity`.
5
+ * Extra per-call identity/context for server-side webhook calls — an override on top of whatever the
6
+ * client already carries.
7
+ *
8
+ * There's no ambient `window` on the server to auto-collect `path`/`query`/`url`/UTM params the way
9
+ * the browser client does, so bind them ONCE per request via {@link XeniaConfig.context} (see
10
+ * `contextFromUrl`) and every call attaches them automatically. These per-call fields are for the
11
+ * remainder: values known only at this call site, or a deliberate override of the ambient ones.
10
12
  */
11
13
  interface ServerWebhookOptions {
12
14
  method?: "GET" | "POST";
@@ -45,6 +47,8 @@ declare class XeniaServer {
45
47
  readonly api: XeniaApi;
46
48
  /** SDK-owned visitor anchor for this (per-request) client — see {@link XeniaConfig.visitorId}. */
47
49
  private readonly visitorId?;
50
+ /** Ambient request context attached to every call — see {@link XeniaConfig.context}. */
51
+ private readonly context?;
48
52
  constructor(config: XeniaConfig);
49
53
  /**
50
54
  * Send a unified event server-side (`POST /api/events/v1`) and return the
@@ -67,15 +71,31 @@ declare class XeniaServer {
67
71
  * (`POST /api/personalization/resolve`). Requires a configured SDK token
68
72
  * (`token`/`getToken`) — resolve is auth-required. With `merge: true` the
69
73
  * returned `content` is server-spliced.
74
+ *
75
+ * Pass `opts.identity`/`opts.context` to attach the same SDK-provided
76
+ * fields (`deviceId`, `customerId`, `email`, `path`, `url`, `referrer`,
77
+ * `utm*`, …) the browser client collects ambiently — there's no ambient
78
+ * `window`/`document` server-side, so a server caller must supply whatever
79
+ * it knows (e.g. from the current request) explicitly. See
80
+ * {@link ResolveOptions}.
70
81
  */
71
82
  resolve(contentKey: string, opts?: ResolveOptions): Promise<ResolveResult>;
72
83
  /** Resolve several content keys in one round-trip (`POST /api/personalization/resolve-batch`). */
73
84
  resolveBatch(items: ResolveBatchItem[], opts?: ResolveOptions): Promise<ResolveBatchResult[]>;
74
85
  /**
75
- * Stamp the SDK-owned visitor id (`config.visitorId`) into the resolve `data`
76
- * under the reserved `_xenia_vid` key so the backend can bucket holdout
77
- * experiments and record exposure per visitor. Set last so a caller can't
78
- * override it; a no-op when no `visitorId` was bound on this client.
86
+ * Merge the ambient `config.context` and `opts.identity`/`opts.context` into
87
+ * the resolve `data`, then stamp the SDK-owned visitor id
88
+ * (`config.visitorId`) under both the reserved `_xenia_vid` key (read by the
89
+ * backend for holdout/exposure bucketing) and the flat `visitorId` field —
90
+ * mirrors `webhook()`'s merge order/precedence exactly: caller `data` <
91
+ * ambient `config.context` < caller `context`/`identity` < SDK-owned
92
+ * `visitorId`/`_xenia_vid`, set LAST so neither can be overridden per call.
93
+ *
94
+ * `config.context` is what makes the SDK-provided fields automatic on the
95
+ * server: bound once per request, every `resolve()` carries `path`/`query`/
96
+ * `url`/`referrer`/UTMs with no per-call wiring, matching what the browser
97
+ * client collects from `window` on its own. A no-op when nothing is bound and
98
+ * nothing was passed — preserving today's behavior for callers using neither.
79
99
  */
80
100
  private withVisitor;
81
101
  }
@@ -1,12 +1,14 @@
1
- import { s as CallerIdentity, A as AnalyticsContext, J as JsonValue, d as ConsentState, e as EventIdentity, E as EventContext, n as XeniaApi, o as XeniaConfig, a as AnalyticsEventName, c as AnalyticsIngestResponse, W as WebhookResponse, I as IdentifyRequest, f as IdentifyResponse, l as ResolveOptions, m as ResolveResult, j as ResolveBatchItem, k as ResolveBatchResult } from '../cookie-names-LgNDAreS.js';
2
- export { b as AnalyticsIdentity, C as CONSENT_COOKIE, P as PersonalizationSwap, V as VISITOR_COOKIE, p as XeniaEvent, q as consentCookieName, r as parseActions, v as visitorCookieName } from '../cookie-names-LgNDAreS.js';
1
+ import { s as CallerIdentity, A as AnalyticsContext, J as JsonValue, d as ConsentState, e as EventIdentity, E as EventContext, n as XeniaApi, o as XeniaConfig, a as AnalyticsEventName, c as AnalyticsIngestResponse, W as WebhookResponse, I as IdentifyRequest, f as IdentifyResponse, l as ResolveOptions, m as ResolveResult, j as ResolveBatchItem, k as ResolveBatchResult } from '../cookie-names-C3LKDhsg.js';
2
+ export { b as AnalyticsIdentity, C as CONSENT_COOKIE, P as PersonalizationSwap, V as VISITOR_COOKIE, p as XeniaEvent, q as consentCookieName, r as parseActions, v as visitorCookieName } from '../cookie-names-C3LKDhsg.js';
3
3
 
4
4
  /**
5
- * Extra per-call identity/context for server-side webhook calls. There's no
6
- * ambient `window` on the server to auto-collect `path`/`query`/`url`/UTM
7
- * params the way the browser client does — pass whatever's known at the call
8
- * site (e.g. the current request's pathname from Next.js `headers()`/route
9
- * params) via `context`, and `deviceId`/`visitorId`/etc. via `identity`.
5
+ * Extra per-call identity/context for server-side webhook calls — an override on top of whatever the
6
+ * client already carries.
7
+ *
8
+ * There's no ambient `window` on the server to auto-collect `path`/`query`/`url`/UTM params the way
9
+ * the browser client does, so bind them ONCE per request via {@link XeniaConfig.context} (see
10
+ * `contextFromUrl`) and every call attaches them automatically. These per-call fields are for the
11
+ * remainder: values known only at this call site, or a deliberate override of the ambient ones.
10
12
  */
11
13
  interface ServerWebhookOptions {
12
14
  method?: "GET" | "POST";
@@ -45,6 +47,8 @@ declare class XeniaServer {
45
47
  readonly api: XeniaApi;
46
48
  /** SDK-owned visitor anchor for this (per-request) client — see {@link XeniaConfig.visitorId}. */
47
49
  private readonly visitorId?;
50
+ /** Ambient request context attached to every call — see {@link XeniaConfig.context}. */
51
+ private readonly context?;
48
52
  constructor(config: XeniaConfig);
49
53
  /**
50
54
  * Send a unified event server-side (`POST /api/events/v1`) and return the
@@ -67,15 +71,31 @@ declare class XeniaServer {
67
71
  * (`POST /api/personalization/resolve`). Requires a configured SDK token
68
72
  * (`token`/`getToken`) — resolve is auth-required. With `merge: true` the
69
73
  * returned `content` is server-spliced.
74
+ *
75
+ * Pass `opts.identity`/`opts.context` to attach the same SDK-provided
76
+ * fields (`deviceId`, `customerId`, `email`, `path`, `url`, `referrer`,
77
+ * `utm*`, …) the browser client collects ambiently — there's no ambient
78
+ * `window`/`document` server-side, so a server caller must supply whatever
79
+ * it knows (e.g. from the current request) explicitly. See
80
+ * {@link ResolveOptions}.
70
81
  */
71
82
  resolve(contentKey: string, opts?: ResolveOptions): Promise<ResolveResult>;
72
83
  /** Resolve several content keys in one round-trip (`POST /api/personalization/resolve-batch`). */
73
84
  resolveBatch(items: ResolveBatchItem[], opts?: ResolveOptions): Promise<ResolveBatchResult[]>;
74
85
  /**
75
- * Stamp the SDK-owned visitor id (`config.visitorId`) into the resolve `data`
76
- * under the reserved `_xenia_vid` key so the backend can bucket holdout
77
- * experiments and record exposure per visitor. Set last so a caller can't
78
- * override it; a no-op when no `visitorId` was bound on this client.
86
+ * Merge the ambient `config.context` and `opts.identity`/`opts.context` into
87
+ * the resolve `data`, then stamp the SDK-owned visitor id
88
+ * (`config.visitorId`) under both the reserved `_xenia_vid` key (read by the
89
+ * backend for holdout/exposure bucketing) and the flat `visitorId` field —
90
+ * mirrors `webhook()`'s merge order/precedence exactly: caller `data` <
91
+ * ambient `config.context` < caller `context`/`identity` < SDK-owned
92
+ * `visitorId`/`_xenia_vid`, set LAST so neither can be overridden per call.
93
+ *
94
+ * `config.context` is what makes the SDK-provided fields automatic on the
95
+ * server: bound once per request, every `resolve()` carries `path`/`query`/
96
+ * `url`/`referrer`/UTMs with no per-call wiring, matching what the browser
97
+ * client collects from `window` on its own. A no-op when nothing is bound and
98
+ * nothing was passed — preserving today's behavior for callers using neither.
79
99
  */
80
100
  private withVisitor;
81
101
  }
@@ -1,5 +1,5 @@
1
- import { XeniaApi, toEventId, generateUlid, HttpClient, visitorCookieName, consentCookieName } from '../chunk-D37RD3UC.js';
2
- export { CONSENT_COOKIE, VISITOR_COOKIE, XeniaApi, consentCookieName, parseActions, visitorCookieName } from '../chunk-D37RD3UC.js';
1
+ import { XeniaApi, toEventId, generateUlid, compact, HttpClient, visitorCookieName, consentCookieName } from '../chunk-7D2HJMW6.js';
2
+ export { CONSENT_COOKIE, VISITOR_COOKIE, XeniaApi, consentCookieName, parseActions, visitorCookieName } from '../chunk-7D2HJMW6.js';
3
3
 
4
4
  // src/core/event-payload.ts
5
5
  var RESERVED = /* @__PURE__ */ new Set([
@@ -20,7 +20,7 @@ var RESERVED = /* @__PURE__ */ new Set([
20
20
  "path",
21
21
  "query"
22
22
  ]);
23
- function compact(obj) {
23
+ function compact2(obj) {
24
24
  const out = {};
25
25
  for (const [k, v] of Object.entries(obj)) {
26
26
  if (v !== void 0) out[k] = v;
@@ -44,8 +44,8 @@ function buildEventPayload(input) {
44
44
  // what they reliably know (real page url, visitor/device id), so a stray prop
45
45
  // can't override the true page context — see merge order below.
46
46
  ...reserved,
47
- ...compact(input.context ?? {}),
48
- ...compact(input.identity ?? {}),
47
+ ...compact2(input.context ?? {}),
48
+ ...compact2(input.identity ?? {}),
49
49
  eventId: input.eventId,
50
50
  ...input.eventType ? { eventType: input.eventType } : {},
51
51
  ...input.journeyId ? { journeyId: input.journeyId } : {}
@@ -58,9 +58,12 @@ var XeniaServer = class {
58
58
  api;
59
59
  /** SDK-owned visitor anchor for this (per-request) client — see {@link XeniaConfig.visitorId}. */
60
60
  visitorId;
61
+ /** Ambient request context attached to every call — see {@link XeniaConfig.context}. */
62
+ context;
61
63
  constructor(config) {
62
64
  this.api = new XeniaApi(config);
63
65
  this.visitorId = config.visitorId;
66
+ this.context = config.context;
64
67
  }
65
68
  /**
66
69
  * Send a unified event server-side (`POST /api/events/v1`) and return the
@@ -102,7 +105,9 @@ var XeniaServer = class {
102
105
  // cookie per request) is attached automatically. Falls back to a
103
106
  // per-call visitorId only when none is bound.
104
107
  identity: { ...opts.identity, visitorId: this.visitorId ?? opts.identity?.visitorId },
105
- context: opts.context,
108
+ // Ambient request context (config.context, bound once per request) under a per-call
109
+ // override — same precedence resolve() uses, so both surfaces carry the same fields.
110
+ context: { ...this.context, ...opts.context },
106
111
  props: data
107
112
  });
108
113
  return this.api.webhook(triggerId, payload, opts.method ?? "POST");
@@ -116,6 +121,13 @@ var XeniaServer = class {
116
121
  * (`POST /api/personalization/resolve`). Requires a configured SDK token
117
122
  * (`token`/`getToken`) — resolve is auth-required. With `merge: true` the
118
123
  * returned `content` is server-spliced.
124
+ *
125
+ * Pass `opts.identity`/`opts.context` to attach the same SDK-provided
126
+ * fields (`deviceId`, `customerId`, `email`, `path`, `url`, `referrer`,
127
+ * `utm*`, …) the browser client collects ambiently — there's no ambient
128
+ * `window`/`document` server-side, so a server caller must supply whatever
129
+ * it knows (e.g. from the current request) explicitly. See
130
+ * {@link ResolveOptions}.
119
131
  */
120
132
  async resolve(contentKey, opts) {
121
133
  return this.api.resolve(contentKey, this.withVisitor(opts));
@@ -125,14 +137,33 @@ var XeniaServer = class {
125
137
  return this.api.resolveBatch(items, this.withVisitor(opts));
126
138
  }
127
139
  /**
128
- * Stamp the SDK-owned visitor id (`config.visitorId`) into the resolve `data`
129
- * under the reserved `_xenia_vid` key so the backend can bucket holdout
130
- * experiments and record exposure per visitor. Set last so a caller can't
131
- * override it; a no-op when no `visitorId` was bound on this client.
140
+ * Merge the ambient `config.context` and `opts.identity`/`opts.context` into
141
+ * the resolve `data`, then stamp the SDK-owned visitor id
142
+ * (`config.visitorId`) under both the reserved `_xenia_vid` key (read by the
143
+ * backend for holdout/exposure bucketing) and the flat `visitorId` field —
144
+ * mirrors `webhook()`'s merge order/precedence exactly: caller `data` <
145
+ * ambient `config.context` < caller `context`/`identity` < SDK-owned
146
+ * `visitorId`/`_xenia_vid`, set LAST so neither can be overridden per call.
147
+ *
148
+ * `config.context` is what makes the SDK-provided fields automatic on the
149
+ * server: bound once per request, every `resolve()` carries `path`/`query`/
150
+ * `url`/`referrer`/UTMs with no per-call wiring, matching what the browser
151
+ * client collects from `window` on its own. A no-op when nothing is bound and
152
+ * nothing was passed — preserving today's behavior for callers using neither.
132
153
  */
133
154
  withVisitor(opts) {
134
- if (!this.visitorId) return opts;
135
- return { ...opts, data: { ...opts?.data ?? {}, _xenia_vid: this.visitorId } };
155
+ const identity = compact({
156
+ ...opts?.identity,
157
+ visitorId: this.visitorId ?? opts?.identity?.visitorId
158
+ });
159
+ const merged = {
160
+ ...compact(this.context ?? {}),
161
+ ...compact(opts?.context ?? {}),
162
+ ...identity
163
+ };
164
+ if (Object.keys(merged).length === 0 && !this.visitorId) return opts;
165
+ if (this.visitorId) merged._xenia_vid = this.visitorId;
166
+ return { ...opts, data: { ...opts?.data ?? {}, ...merged } };
136
167
  }
137
168
  };
138
169
  function createXeniaServer(config) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/event-payload.ts","../../src/server/xenia-server.ts","../../src/server/token.ts","../../src/server/cookies.ts"],"names":[],"mappings":";;;;AAGA,IAAM,QAAA,uBAAe,GAAA,CAAI;AAAA,EACvB,SAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,YAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF,CAAC,CAAA;AAaD,SAAS,QAAQ,GAAA,EAAuE;AACtF,EAAA,MAAM,MAAiC,EAAC;AACxC,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,EAAG;AACxC,IAAA,IAAI,CAAA,KAAM,MAAA,EAAW,GAAA,CAAI,CAAC,CAAA,GAAI,CAAA;AAAA,EAChC;AACA,EAAA,OAAO,GAAA;AACT;AAWO,SAAS,kBAAkB,KAAA,EAAsC;AACtE,EAAA,MAAM,cAAyC,EAAC;AAChD,EAAA,MAAM,WAAsC,EAAC;AAC7C,EAAA,IAAI,MAAM,KAAA,EAAO;AACf,IAAA,KAAA,MAAW,CAAC,GAAG,CAAC,CAAA,IAAK,OAAO,OAAA,CAAQ,KAAA,CAAM,KAAK,CAAA,EAAG;AAChD,MAAA,IAAI,MAAM,MAAA,EAAW;AAKrB,MAAA,IAAI,SAAS,GAAA,CAAI,CAAC,CAAA,EAAG,QAAA,CAAS,CAAC,CAAA,GAAI,CAAA;AAAA,WAC9B,WAAA,CAAY,CAAC,CAAA,GAAI,CAAA;AAAA,IACxB;AAAA,EACF;AAEA,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,GAAG,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKH,GAAG,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AAS,UAAA,CACd,cACA,MAAA,EACc;AACd,EAAA,MAAM,MAAM,YAAA,CAAa,YAAY,CAAA,CAAE,iBAAA,CAAkB,MAAM,CAAC,CAAA;AAChE,EAAA,IAAI,CAAC,KAAK,OAAO,EAAE,WAAW,KAAA,EAAO,SAAA,EAAW,KAAA,EAAO,eAAA,EAAiB,KAAA,EAAM;AAC9E,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC7B,IAAA,OAAO,MAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,GAAA,CAAI,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,EAAM,CAAC,CAAA;AAC1D,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,MAAA,CAAO,GAAA,CAAI,WAAW,CAAA;AAAA,MACjC,SAAA,EAAW,MAAA,CAAO,GAAA,CAAI,WAAW,CAAA;AAAA,MACjC,eAAA,EAAiB,MAAA,CAAO,GAAA,CAAI,iBAAiB;AAAA,KAC/C;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { EventContext, EventIdentity, EventPayload, JsonValue } from \"./types\";\n\n/** Reserved keys that map to first-class fields (not passthrough data). */\nconst RESERVED = new Set([\n \"eventId\",\n \"eventType\",\n \"journeyId\",\n \"deviceId\",\n \"visitorId\",\n \"customerId\",\n \"email\",\n \"utmSource\",\n \"utmMedium\",\n \"utmCampaign\",\n \"utmContent\",\n \"utmId\",\n \"url\",\n \"referrer\",\n \"path\",\n \"query\",\n]);\n\nexport interface BuildEventInput {\n eventId: string;\n eventType?: string;\n journeyId?: string;\n identity?: EventIdentity;\n context?: EventContext;\n /** Arbitrary extra properties merged as passthrough data. */\n props?: Record<string, JsonValue | undefined>;\n}\n\n/** Drop `undefined` values so the JSON body stays clean. */\nfunction compact(obj: Record<string, JsonValue | undefined>): Record<string, JsonValue> {\n const out: Record<string, JsonValue> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) out[k] = v;\n }\n return out;\n}\n\n/**\n * Build the request body for the webhook `/flow` call (`XeniaApi.webhook`).\n *\n * Merge order (later wins): passthrough props < context < identity < core.\n * Field names match the backend `EventTriggerRequest` DTO exactly.\n *\n * @internal Used only by the webhook request/response path — the unified event\n * surface (`track()` → `POST /api/events/v1`) builds {@link XeniaEvent} instead.\n */\nexport function buildEventPayload(input: BuildEventInput): EventPayload {\n const passthrough: Record<string, JsonValue> = {};\n const reserved: Record<string, JsonValue> = {};\n if (input.props) {\n for (const [k, v] of Object.entries(input.props)) {\n if (v === undefined) continue;\n // A prop whose key matches a reserved field (e.g. `email`, `customerId`,\n // `utmSource`) is promoted to that first-class field; everything else is\n // custom passthrough data. Previously reserved-named props were dropped\n // outright — so `track(\"sign_up\", { email })` never sent `email` at all.\n if (RESERVED.has(k)) reserved[k] = v;\n else passthrough[k] = v;\n }\n }\n\n const payload = {\n ...passthrough,\n // Reserved-named props fill first-class fields (e.g. `email`, `customerId`)\n // the SDK didn't auto-collect. Auto-collected context/identity still win for\n // what they reliably know (real page url, visitor/device id), so a stray prop\n // can't override the true page context — see merge order below.\n ...reserved,\n ...compact((input.context ?? {}) as Record<string, JsonValue | undefined>),\n ...compact((input.identity ?? {}) as Record<string, JsonValue | undefined>),\n eventId: input.eventId,\n ...(input.eventType ? { eventType: input.eventType } : {}),\n ...(input.journeyId ? { journeyId: input.journeyId } : {}),\n };\n\n return payload as EventPayload;\n}\n","import { XeniaApi } from \"../core/api\";\nimport { buildEventPayload } from \"../core/event-payload\";\nimport { generateUlid, toEventId } from \"../core/id\";\nimport type {\n AnalyticsContext,\n AnalyticsEventName,\n CallerIdentity,\n AnalyticsIngestResponse,\n ConsentState,\n EventContext,\n EventIdentity,\n IdentifyRequest,\n IdentifyResponse,\n JsonValue,\n ResolveBatchItem,\n ResolveBatchResult,\n ResolveOptions,\n ResolveResult,\n WebhookResponse,\n XeniaConfig,\n XeniaEvent,\n} from \"../core/types\";\n\n/**\n * Extra per-call identity/context for server-side webhook calls. There's no\n * ambient `window` on the server to auto-collect `path`/`query`/`url`/UTM\n * params the way the browser client does — pass whatever's known at the call\n * site (e.g. the current request's pathname from Next.js `headers()`/route\n * params) via `context`, and `deviceId`/`visitorId`/etc. via `identity`.\n */\nexport interface ServerWebhookOptions {\n method?: \"GET\" | \"POST\";\n journeyId?: string;\n identity?: EventIdentity;\n context?: EventContext;\n}\n\n/**\n * Options for a server-side unified event (`POST /api/events/v1`). There's no\n * ambient request context on the server — pass whatever's known at the call\n * site (e.g. pathname/user-agent from the current request, session id from a\n * cookie) via `identity`/`context`.\n */\nexport interface ServerTrackOptions {\n /** When true, also match/advance a journey (never sampled/shed). Default false. */\n trigger?: boolean;\n /** Stable dedup key (e.g. `\"ord-1001\"`) for idempotent conversions. */\n eventId?: string;\n eventVersion?: number;\n occurredAtMs?: number;\n /** Origin tag. Default `\"xenia-server-sdk\"`. */\n source?: string;\n /** Identity fields for this event (except the SDK-owned `xeniaVisitorId`,\n * which comes from `config.visitorId` and can't be set per call). */\n identity?: CallerIdentity;\n context?: AnalyticsContext;\n properties?: Record<string, JsonValue | undefined>;\n consent?: ConsentState;\n}\n\n/**\n * Server-native Xenia client. Same method names as the browser client, but\n * every call is stateless: identity and context are passed explicitly rather\n * than read from the DOM/localStorage. Uses global `fetch` (Node ≥18).\n */\nexport class XeniaServer {\n readonly api: XeniaApi;\n /** SDK-owned visitor anchor for this (per-request) client — see {@link XeniaConfig.visitorId}. */\n private readonly visitorId?: string;\n\n constructor(config: XeniaConfig) {\n this.api = new XeniaApi(config);\n this.visitorId = config.visitorId;\n }\n\n /**\n * Send a unified event server-side (`POST /api/events/v1`) and return the\n * ingest response (including per-result `triggered`). `opts.trigger: true`\n * also matches/advances a journey; pass `opts.eventId` (e.g. `\"ord-1001\"`)\n * as a stable dedup key for idempotent conversions.\n */\n async track(\n eventName: AnalyticsEventName,\n opts: ServerTrackOptions = {},\n ): Promise<AnalyticsIngestResponse> {\n const event: XeniaEvent = {\n eventName,\n eventId: opts.eventId ? toEventId(opts.eventId) : generateUlid(),\n eventVersion: opts.eventVersion ?? 1,\n occurredAtMs: opts.occurredAtMs ?? Date.now(),\n source: opts.source ?? \"xenia-server-sdk\",\n identity: {\n ...opts.identity,\n // SDK-owned, set LAST so it can't be overridden per call. Comes from\n // `config.visitorId` (bind it per request from the `xenia_vid` cookie).\n xeniaVisitorId: this.visitorId,\n },\n context: opts.context,\n properties: opts.properties,\n consent: opts.consent,\n trigger: opts.trigger === true ? true : undefined,\n };\n return this.api.sendEvents([event]);\n }\n\n /**\n * Send a webhook request and await the synchronous response. Merges\n * `opts.identity`/`opts.context` into the payload the same way the browser\n * client's auto-attached fields do (`path`, `query`, `url`, `referrer`,\n * `deviceId`, `visitorId`, etc.) — see `ServerWebhookOptions`.\n */\n async webhook(\n triggerId: string,\n data?: Record<string, JsonValue | undefined>,\n opts: ServerWebhookOptions = {},\n ): Promise<WebhookResponse> {\n const payload = buildEventPayload({\n eventId: triggerId,\n journeyId: opts.journeyId,\n // SDK-owned visitor anchor wins: config.visitorId (bind the `xenia_vid`\n // cookie per request) is attached automatically. Falls back to a\n // per-call visitorId only when none is bound.\n identity: { ...opts.identity, visitorId: this.visitorId ?? opts.identity?.visitorId },\n context: opts.context,\n props: data,\n });\n return this.api.webhook(triggerId, payload as JsonValue, opts.method ?? \"POST\");\n }\n\n /** Bind visitor→user server-side — `POST /api/events/v1/identify`. */\n async identify(body: IdentifyRequest): Promise<IdentifyResponse> {\n return this.api.identify(body);\n }\n\n /**\n * Resolve in-entry content personalization for one content key\n * (`POST /api/personalization/resolve`). Requires a configured SDK token\n * (`token`/`getToken`) — resolve is auth-required. With `merge: true` the\n * returned `content` is server-spliced.\n */\n async resolve(contentKey: string, opts?: ResolveOptions): Promise<ResolveResult> {\n return this.api.resolve(contentKey, this.withVisitor(opts));\n }\n\n /** Resolve several content keys in one round-trip (`POST /api/personalization/resolve-batch`). */\n async resolveBatch(\n items: ResolveBatchItem[],\n opts?: ResolveOptions,\n ): Promise<ResolveBatchResult[]> {\n return this.api.resolveBatch(items, this.withVisitor(opts));\n }\n\n /**\n * Stamp the SDK-owned visitor id (`config.visitorId`) into the resolve `data`\n * under the reserved `_xenia_vid` key so the backend can bucket holdout\n * experiments and record exposure per visitor. Set last so a caller can't\n * override it; a no-op when no `visitorId` was bound on this client.\n */\n private withVisitor(opts?: ResolveOptions): ResolveOptions | undefined {\n if (!this.visitorId) return opts;\n return { ...opts, data: { ...(opts?.data ?? {}), _xenia_vid: this.visitorId } };\n }\n}\n\n/** Create a server-native client. */\nexport function createXeniaServer(config: XeniaConfig): XeniaServer {\n return new XeniaServer(config);\n}\n","import { HttpClient } from \"../core/http-client\";\nimport type { JsonObject } from \"../core/types\";\n\nexport interface RefreshTokenOptions {\n /**\n * Xenia base URL. Defaults to the hosted engine,\n * `https://engine.xeniamartech.com/xenia` — omit unless self-hosting.\n */\n baseUrl?: string;\n /**\n * The personalization SDK token created once in the dashboard (API Tokens →\n * Create token). Stays server-side; the browser never sees it — only the\n * short-lived token this exchanges it for does.\n */\n sdkToken: string;\n /** Lifetime of the returned token, in minutes. Default 15, capped server-side at 60. */\n ttlMinutes?: number;\n timeout?: number;\n}\n\nexport interface RefreshedToken {\n token: string;\n expiresAt?: string;\n}\n\n/**\n * Exchange the long-lived personalization SDK token for a short-lived one with\n * the same tenant/env scope, via `POST /api/personalization/token/refresh`.\n * Self-service — no dashboard credential needed, just the SDK token you\n * already have. Call this from your backend and hand the result to the\n * browser (e.g. from a token route the client SDK calls via `getToken`).\n */\nexport async function refreshSdkToken(opts: RefreshTokenOptions): Promise<RefreshedToken> {\n const http = new HttpClient({ baseUrl: opts.baseUrl, timeout: opts.timeout });\n const { data } = await http.request({\n method: \"POST\",\n path: \"/api/personalization/token/refresh\",\n headers: { Authorization: `Bearer ${opts.sdkToken}` },\n body: { ttlMinutes: opts.ttlMinutes ?? null },\n });\n const obj = (data ?? {}) as JsonObject;\n return {\n token: String(obj.token ?? \"\"),\n expiresAt: typeof obj.expiresAt === \"string\" ? obj.expiresAt : undefined,\n };\n}\n\n/**\n * Build a framework-agnostic request handler that hands the browser SDK a\n * personalization token — mount it at the endpoint `getToken` calls. Needs\n * only the SDK token you already created in the dashboard; mints a fresh\n * short-lived token per request so the long-lived one never reaches the\n * browser.\n *\n * @example\n * ```ts\n * export const GET = createTokenRoute({\n * sdkToken: process.env.XENIA_SDK_TOKEN!,\n * // baseUrl: process.env.XENIA_URL, // only to override the default hosted engine\n * });\n * ```\n */\nexport function createTokenRoute(config: RefreshTokenOptions): (request: Request) => Promise<Response> {\n return async (): Promise<Response> => {\n try {\n const refreshed = await refreshSdkToken(config);\n return new Response(JSON.stringify(refreshed), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\" },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : \"token refresh failed\";\n return new Response(JSON.stringify({ error: message }), {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n };\n}\n","import {\n CONSENT_COOKIE,\n VISITOR_COOKIE,\n consentCookieName,\n visitorCookieName,\n} from \"../core/cookie-names\";\nimport type { ConsentState } from \"../core/types\";\n\n/**\n * Cookie names the SDK reads server-side (set by the browser SDK / your app).\n *\n * The constants are the DEFAULT-prefix names; the functions build the name for any prefix. If you\n * pass `config.prefix` to the browser client, pass the same prefix here — the browser namespaces\n * the cookie by it, so the default name won't be there to find.\n */\nexport { CONSENT_COOKIE, VISITOR_COOKIE, consentCookieName, visitorCookieName };\n\n/**\n * Parse a raw `Cookie` header into a map. Framework-agnostic so it works with\n * `Request.headers.get(\"cookie\")`, Node `req.headers.cookie`, etc.\n */\nexport function parseCookies(header: string | null | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!header) return out;\n for (const part of header.split(\";\")) {\n const idx = part.indexOf(\"=\");\n if (idx === -1) continue;\n const key = part.slice(0, idx).trim();\n const value = part.slice(idx + 1).trim();\n if (key) out[key] = decodeURIComponent(value);\n }\n return out;\n}\n\n/**\n * Read the visitor id the browser SDK wrote, so a server-side event can be bound to the same\n * visitor (`createXeniaServer({ visitorId })`) and attribute to a browser-entered journey.\n *\n * @param prefix Must match the browser client's `config.prefix`. The cookie is namespaced by it, so\n * a mismatch finds nothing and quietly leaves the server with no visitor.\n */\nexport function getVisitorId(\n cookieHeader: string | null | undefined,\n prefix?: string,\n): string | null {\n return parseCookies(cookieHeader)[visitorCookieName(prefix)] ?? null;\n}\n\n/**\n * Read consent from a cookie header. Accepts a JSON blob or a comma-list of\n * granted scopes (e.g. `analytics,personalization`). Absent → all denied.\n *\n * @param prefix Must match the browser client's `config.prefix` — see {@link getVisitorId}.\n */\nexport function getConsent(\n cookieHeader: string | null | undefined,\n prefix?: string,\n): ConsentState {\n const raw = parseCookies(cookieHeader)[consentCookieName(prefix)];\n if (!raw) return { analytics: false, marketing: false, personalization: false };\n try {\n const parsed = JSON.parse(raw) as ConsentState;\n return parsed;\n } catch {\n const scopes = new Set(raw.split(\",\").map((s) => s.trim()));\n return {\n analytics: scopes.has(\"analytics\"),\n marketing: scopes.has(\"marketing\"),\n personalization: scopes.has(\"personalization\"),\n };\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/core/event-payload.ts","../../src/server/xenia-server.ts","../../src/server/token.ts","../../src/server/cookies.ts"],"names":["compact"],"mappings":";;;;AAGA,IAAM,QAAA,uBAAe,GAAA,CAAI;AAAA,EACvB,SAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,YAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF,CAAC,CAAA;AAaD,SAASA,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AE,IAAA,EAAK;AACvC,IAAA,IAAI,GAAA,EAAK,GAAA,CAAI,GAAG,CAAA,GAAI,mBAAmB,KAAK,CAAA;AAAA,EAC9C;AACA,EAAA,OAAO,GAAA;AACT;AASO,SAAS,YAAA,CACd,cACA,MAAA,EACe;AACf,EAAA,OAAO,aAAa,YAAY,CAAA,CAAE,iBAAA,CAAkB,MAAM,CAAC,CAAA,IAAK,IAAA;AAClE;AAQO,SAAS,UAAA,CACd,cACA,MAAA,EACc;AACd,EAAA,MAAM,MAAM,YAAA,CAAa,YAAY,CAAA,CAAE,iBAAA,CAAkB,MAAM,CAAC,CAAA;AAChE,EAAA,IAAI,CAAC,KAAK,OAAO,EAAE,WAAW,KAAA,EAAO,SAAA,EAAW,KAAA,EAAO,eAAA,EAAiB,KAAA,EAAM;AAC9E,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC7B,IAAA,OAAO,MAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,GAAA,CAAI,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,EAAM,CAAC,CAAA;AAC1D,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,MAAA,CAAO,GAAA,CAAI,WAAW,CAAA;AAAA,MACjC,SAAA,EAAW,MAAA,CAAO,GAAA,CAAI,WAAW,CAAA;AAAA,MACjC,eAAA,EAAiB,MAAA,CAAO,GAAA,CAAI,iBAAiB;AAAA,KAC/C;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { EventContext, EventIdentity, EventPayload, JsonValue } from \"./types\";\n\n/** Reserved keys that map to first-class fields (not passthrough data). */\nconst RESERVED = new Set([\n \"eventId\",\n \"eventType\",\n \"journeyId\",\n \"deviceId\",\n \"visitorId\",\n \"customerId\",\n \"email\",\n \"utmSource\",\n \"utmMedium\",\n \"utmCampaign\",\n \"utmContent\",\n \"utmId\",\n \"url\",\n \"referrer\",\n \"path\",\n \"query\",\n]);\n\nexport interface BuildEventInput {\n eventId: string;\n eventType?: string;\n journeyId?: string;\n identity?: EventIdentity;\n context?: EventContext;\n /** Arbitrary extra properties merged as passthrough data. */\n props?: Record<string, JsonValue | undefined>;\n}\n\n/** Drop `undefined` values so the JSON body stays clean. */\nfunction compact(obj: Record<string, JsonValue | undefined>): Record<string, JsonValue> {\n const out: Record<string, JsonValue> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) out[k] = v;\n }\n return out;\n}\n\n/**\n * Build the request body for the webhook `/flow` call (`XeniaApi.webhook`).\n *\n * Merge order (later wins): passthrough props < context < identity < core.\n * Field names match the backend `EventTriggerRequest` DTO exactly.\n *\n * @internal Used only by the webhook request/response path — the unified event\n * surface (`track()` → `POST /api/events/v1`) builds {@link XeniaEvent} instead.\n */\nexport function buildEventPayload(input: BuildEventInput): EventPayload {\n const passthrough: Record<string, JsonValue> = {};\n const reserved: Record<string, JsonValue> = {};\n if (input.props) {\n for (const [k, v] of Object.entries(input.props)) {\n if (v === undefined) continue;\n // A prop whose key matches a reserved field (e.g. `email`, `customerId`,\n // `utmSource`) is promoted to that first-class field; everything else is\n // custom passthrough data. Previously reserved-named props were dropped\n // outright — so `track(\"sign_up\", { email })` never sent `email` at all.\n if (RESERVED.has(k)) reserved[k] = v;\n else passthrough[k] = v;\n }\n }\n\n const payload = {\n ...passthrough,\n // Reserved-named props fill first-class fields (e.g. `email`, `customerId`)\n // the SDK didn't auto-collect. Auto-collected context/identity still win for\n // what they reliably know (real page url, visitor/device id), so a stray prop\n // can't override the true page context — see merge order below.\n ...reserved,\n ...compact((input.context ?? {}) as Record<string, JsonValue | undefined>),\n ...compact((input.identity ?? {}) as Record<string, JsonValue | undefined>),\n eventId: input.eventId,\n ...(input.eventType ? { eventType: input.eventType } : {}),\n ...(input.journeyId ? { journeyId: input.journeyId } : {}),\n };\n\n return payload as EventPayload;\n}\n","import { compact, XeniaApi } from \"../core/api\";\nimport { buildEventPayload } from \"../core/event-payload\";\nimport { generateUlid, toEventId } from \"../core/id\";\nimport type {\n AnalyticsContext,\n AnalyticsEventName,\n CallerIdentity,\n AnalyticsIngestResponse,\n ConsentState,\n EventContext,\n EventIdentity,\n IdentifyRequest,\n IdentifyResponse,\n JsonValue,\n ResolveBatchItem,\n ResolveBatchResult,\n ResolveOptions,\n ResolveResult,\n WebhookResponse,\n XeniaConfig,\n XeniaEvent,\n} from \"../core/types\";\n\n/**\n * Extra per-call identity/context for server-side webhook calls — an override on top of whatever the\n * client already carries.\n *\n * There's no ambient `window` on the server to auto-collect `path`/`query`/`url`/UTM params the way\n * the browser client does, so bind them ONCE per request via {@link XeniaConfig.context} (see\n * `contextFromUrl`) and every call attaches them automatically. These per-call fields are for the\n * remainder: values known only at this call site, or a deliberate override of the ambient ones.\n */\nexport interface ServerWebhookOptions {\n method?: \"GET\" | \"POST\";\n journeyId?: string;\n identity?: EventIdentity;\n context?: EventContext;\n}\n\n/**\n * Options for a server-side unified event (`POST /api/events/v1`). There's no\n * ambient request context on the server — pass whatever's known at the call\n * site (e.g. pathname/user-agent from the current request, session id from a\n * cookie) via `identity`/`context`.\n */\nexport interface ServerTrackOptions {\n /** When true, also match/advance a journey (never sampled/shed). Default false. */\n trigger?: boolean;\n /** Stable dedup key (e.g. `\"ord-1001\"`) for idempotent conversions. */\n eventId?: string;\n eventVersion?: number;\n occurredAtMs?: number;\n /** Origin tag. Default `\"xenia-server-sdk\"`. */\n source?: string;\n /** Identity fields for this event (except the SDK-owned `xeniaVisitorId`,\n * which comes from `config.visitorId` and can't be set per call). */\n identity?: CallerIdentity;\n context?: AnalyticsContext;\n properties?: Record<string, JsonValue | undefined>;\n consent?: ConsentState;\n}\n\n/**\n * Server-native Xenia client. Same method names as the browser client, but\n * every call is stateless: identity and context are passed explicitly rather\n * than read from the DOM/localStorage. Uses global `fetch` (Node ≥18).\n */\nexport class XeniaServer {\n readonly api: XeniaApi;\n /** SDK-owned visitor anchor for this (per-request) client — see {@link XeniaConfig.visitorId}. */\n private readonly visitorId?: string;\n /** Ambient request context attached to every call — see {@link XeniaConfig.context}. */\n private readonly context?: EventContext;\n\n constructor(config: XeniaConfig) {\n this.api = new XeniaApi(config);\n this.visitorId = config.visitorId;\n this.context = config.context;\n }\n\n /**\n * Send a unified event server-side (`POST /api/events/v1`) and return the\n * ingest response (including per-result `triggered`). `opts.trigger: true`\n * also matches/advances a journey; pass `opts.eventId` (e.g. `\"ord-1001\"`)\n * as a stable dedup key for idempotent conversions.\n */\n async track(\n eventName: AnalyticsEventName,\n opts: ServerTrackOptions = {},\n ): Promise<AnalyticsIngestResponse> {\n const event: XeniaEvent = {\n eventName,\n eventId: opts.eventId ? toEventId(opts.eventId) : generateUlid(),\n eventVersion: opts.eventVersion ?? 1,\n occurredAtMs: opts.occurredAtMs ?? Date.now(),\n source: opts.source ?? \"xenia-server-sdk\",\n identity: {\n ...opts.identity,\n // SDK-owned, set LAST so it can't be overridden per call. Comes from\n // `config.visitorId` (bind it per request from the `xenia_vid` cookie).\n xeniaVisitorId: this.visitorId,\n },\n context: opts.context,\n properties: opts.properties,\n consent: opts.consent,\n trigger: opts.trigger === true ? true : undefined,\n };\n return this.api.sendEvents([event]);\n }\n\n /**\n * Send a webhook request and await the synchronous response. Merges\n * `opts.identity`/`opts.context` into the payload the same way the browser\n * client's auto-attached fields do (`path`, `query`, `url`, `referrer`,\n * `deviceId`, `visitorId`, etc.) — see `ServerWebhookOptions`.\n */\n async webhook(\n triggerId: string,\n data?: Record<string, JsonValue | undefined>,\n opts: ServerWebhookOptions = {},\n ): Promise<WebhookResponse> {\n const payload = buildEventPayload({\n eventId: triggerId,\n journeyId: opts.journeyId,\n // SDK-owned visitor anchor wins: config.visitorId (bind the `xenia_vid`\n // cookie per request) is attached automatically. Falls back to a\n // per-call visitorId only when none is bound.\n identity: { ...opts.identity, visitorId: this.visitorId ?? opts.identity?.visitorId },\n // Ambient request context (config.context, bound once per request) under a per-call\n // override — same precedence resolve() uses, so both surfaces carry the same fields.\n context: { ...this.context, ...opts.context },\n props: data,\n });\n return this.api.webhook(triggerId, payload as JsonValue, opts.method ?? \"POST\");\n }\n\n /** Bind visitor→user server-side — `POST /api/events/v1/identify`. */\n async identify(body: IdentifyRequest): Promise<IdentifyResponse> {\n return this.api.identify(body);\n }\n\n /**\n * Resolve in-entry content personalization for one content key\n * (`POST /api/personalization/resolve`). Requires a configured SDK token\n * (`token`/`getToken`) — resolve is auth-required. With `merge: true` the\n * returned `content` is server-spliced.\n *\n * Pass `opts.identity`/`opts.context` to attach the same SDK-provided\n * fields (`deviceId`, `customerId`, `email`, `path`, `url`, `referrer`,\n * `utm*`, …) the browser client collects ambiently — there's no ambient\n * `window`/`document` server-side, so a server caller must supply whatever\n * it knows (e.g. from the current request) explicitly. See\n * {@link ResolveOptions}.\n */\n async resolve(contentKey: string, opts?: ResolveOptions): Promise<ResolveResult> {\n return this.api.resolve(contentKey, this.withVisitor(opts));\n }\n\n /** Resolve several content keys in one round-trip (`POST /api/personalization/resolve-batch`). */\n async resolveBatch(\n items: ResolveBatchItem[],\n opts?: ResolveOptions,\n ): Promise<ResolveBatchResult[]> {\n return this.api.resolveBatch(items, this.withVisitor(opts));\n }\n\n /**\n * Merge the ambient `config.context` and `opts.identity`/`opts.context` into\n * the resolve `data`, then stamp the SDK-owned visitor id\n * (`config.visitorId`) under both the reserved `_xenia_vid` key (read by the\n * backend for holdout/exposure bucketing) and the flat `visitorId` field —\n * mirrors `webhook()`'s merge order/precedence exactly: caller `data` <\n * ambient `config.context` < caller `context`/`identity` < SDK-owned\n * `visitorId`/`_xenia_vid`, set LAST so neither can be overridden per call.\n *\n * `config.context` is what makes the SDK-provided fields automatic on the\n * server: bound once per request, every `resolve()` carries `path`/`query`/\n * `url`/`referrer`/UTMs with no per-call wiring, matching what the browser\n * client collects from `window` on its own. A no-op when nothing is bound and\n * nothing was passed — preserving today's behavior for callers using neither.\n */\n private withVisitor(opts?: ResolveOptions): ResolveOptions | undefined {\n const identity = compact({\n ...opts?.identity,\n visitorId: this.visitorId ?? opts?.identity?.visitorId,\n });\n const merged = {\n ...compact((this.context ?? {}) as Record<string, JsonValue | undefined>),\n ...compact((opts?.context ?? {}) as Record<string, JsonValue | undefined>),\n ...identity,\n };\n if (Object.keys(merged).length === 0 && !this.visitorId) return opts;\n if (this.visitorId) merged._xenia_vid = this.visitorId;\n return { ...opts, data: { ...(opts?.data ?? {}), ...merged } };\n }\n}\n\n/** Create a server-native client. */\nexport function createXeniaServer(config: XeniaConfig): XeniaServer {\n return new XeniaServer(config);\n}\n","import { HttpClient } from \"../core/http-client\";\nimport type { JsonObject } from \"../core/types\";\n\nexport interface RefreshTokenOptions {\n /**\n * Xenia base URL. Defaults to the hosted engine,\n * `https://engine.xeniamartech.com/xenia` — omit unless self-hosting.\n */\n baseUrl?: string;\n /**\n * The personalization SDK token created once in the dashboard (API Tokens →\n * Create token). Stays server-side; the browser never sees it — only the\n * short-lived token this exchanges it for does.\n */\n sdkToken: string;\n /** Lifetime of the returned token, in minutes. Default 15, capped server-side at 60. */\n ttlMinutes?: number;\n timeout?: number;\n}\n\nexport interface RefreshedToken {\n token: string;\n expiresAt?: string;\n}\n\n/**\n * Exchange the long-lived personalization SDK token for a short-lived one with\n * the same tenant/env scope, via `POST /api/personalization/token/refresh`.\n * Self-service — no dashboard credential needed, just the SDK token you\n * already have. Call this from your backend and hand the result to the\n * browser (e.g. from a token route the client SDK calls via `getToken`).\n */\nexport async function refreshSdkToken(opts: RefreshTokenOptions): Promise<RefreshedToken> {\n const http = new HttpClient({ baseUrl: opts.baseUrl, timeout: opts.timeout });\n const { data } = await http.request({\n method: \"POST\",\n path: \"/api/personalization/token/refresh\",\n headers: { Authorization: `Bearer ${opts.sdkToken}` },\n body: { ttlMinutes: opts.ttlMinutes ?? null },\n });\n const obj = (data ?? {}) as JsonObject;\n return {\n token: String(obj.token ?? \"\"),\n expiresAt: typeof obj.expiresAt === \"string\" ? obj.expiresAt : undefined,\n };\n}\n\n/**\n * Build a framework-agnostic request handler that hands the browser SDK a\n * personalization token — mount it at the endpoint `getToken` calls. Needs\n * only the SDK token you already created in the dashboard; mints a fresh\n * short-lived token per request so the long-lived one never reaches the\n * browser.\n *\n * @example\n * ```ts\n * export const GET = createTokenRoute({\n * sdkToken: process.env.XENIA_SDK_TOKEN!,\n * // baseUrl: process.env.XENIA_URL, // only to override the default hosted engine\n * });\n * ```\n */\nexport function createTokenRoute(config: RefreshTokenOptions): (request: Request) => Promise<Response> {\n return async (): Promise<Response> => {\n try {\n const refreshed = await refreshSdkToken(config);\n return new Response(JSON.stringify(refreshed), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\" },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : \"token refresh failed\";\n return new Response(JSON.stringify({ error: message }), {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n };\n}\n","import {\n CONSENT_COOKIE,\n VISITOR_COOKIE,\n consentCookieName,\n visitorCookieName,\n} from \"../core/cookie-names\";\nimport type { ConsentState } from \"../core/types\";\n\n/**\n * Cookie names the SDK reads server-side (set by the browser SDK / your app).\n *\n * The constants are the DEFAULT-prefix names; the functions build the name for any prefix. If you\n * pass `config.prefix` to the browser client, pass the same prefix here — the browser namespaces\n * the cookie by it, so the default name won't be there to find.\n */\nexport { CONSENT_COOKIE, VISITOR_COOKIE, consentCookieName, visitorCookieName };\n\n/**\n * Parse a raw `Cookie` header into a map. Framework-agnostic so it works with\n * `Request.headers.get(\"cookie\")`, Node `req.headers.cookie`, etc.\n */\nexport function parseCookies(header: string | null | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!header) return out;\n for (const part of header.split(\";\")) {\n const idx = part.indexOf(\"=\");\n if (idx === -1) continue;\n const key = part.slice(0, idx).trim();\n const value = part.slice(idx + 1).trim();\n if (key) out[key] = decodeURIComponent(value);\n }\n return out;\n}\n\n/**\n * Read the visitor id the browser SDK wrote, so a server-side event can be bound to the same\n * visitor (`createXeniaServer({ visitorId })`) and attribute to a browser-entered journey.\n *\n * @param prefix Must match the browser client's `config.prefix`. The cookie is namespaced by it, so\n * a mismatch finds nothing and quietly leaves the server with no visitor.\n */\nexport function getVisitorId(\n cookieHeader: string | null | undefined,\n prefix?: string,\n): string | null {\n return parseCookies(cookieHeader)[visitorCookieName(prefix)] ?? null;\n}\n\n/**\n * Read consent from a cookie header. Accepts a JSON blob or a comma-list of\n * granted scopes (e.g. `analytics,personalization`). Absent → all denied.\n *\n * @param prefix Must match the browser client's `config.prefix` — see {@link getVisitorId}.\n */\nexport function getConsent(\n cookieHeader: string | null | undefined,\n prefix?: string,\n): ConsentState {\n const raw = parseCookies(cookieHeader)[consentCookieName(prefix)];\n if (!raw) return { analytics: false, marketing: false, personalization: false };\n try {\n const parsed = JSON.parse(raw) as ConsentState;\n return parsed;\n } catch {\n const scopes = new Set(raw.split(\",\").map((s) => s.trim()));\n return {\n analytics: scopes.has(\"analytics\"),\n marketing: scopes.has(\"marketing\"),\n personalization: scopes.has(\"personalization\"),\n };\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
- var Xenia=(function(exports){'use strict';var G=new Set(["banner","popup","modal","inline"]),Y=new Set(["top-left","top-right","bottom-left","bottom-right","top","bottom"]),Z=new Set(["swap","hide","show","setContent","redirect",...G]);function V(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function d(n){return typeof n=="string"?n:void 0}function ee(n){return typeof n=="number"?n:void 0}function te(n){if(!V(n))return null;let e=d(n.type);if(!e||!Z.has(e))return null;if(e==="redirect"){let i=d(n.url);return i?{type:e,url:i}:null}if(e==="hide"||e==="show"){let i=d(n.target);return i?{type:e,target:i}:null}if(e==="swap"||e==="setContent"){let i=d(n.target);return i?{type:e,target:i,html:d(n.html),text:d(n.text)}:null}let t=V(n.cta)?{label:d(n.cta.label)??"",url:d(n.cta.url),event:d(n.cta.event)}:void 0;return {type:e,target:d(n.target),title:d(n.title),message:d(n.message),imageUrl:d(n.imageUrl),html:d(n.html),cta:t&&t.label?t:void 0,dismissAfterMs:ee(n.dismissAfterMs),position:ne(n.position)}}function ne(n){let e=d(n);return e&&Y.has(e)?e:void 0}function _(n){let e;if(Array.isArray(n)?e=n:V(n)&&Array.isArray(n.xeniaActions)&&(e=n.xeniaActions),!Array.isArray(e))return [];let t=[];for(let i of e){let s=te(i);s&&t.push(s);}return t}var ie="https://engine.xeniamartech.com/xenia";function x(){return typeof window<"u"&&typeof document<"u"}function se(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 z(n){return new Promise(e=>setTimeout(e,n))}var m=class extends Error{constructor(t,i,s){super(s??`Request failed with status ${t}`);this.status=t;this.data=i;this.name="HttpError";}status;data},b=class{baseUrl;defaultHeaders;timeout;retry;debug;constructor(e){this.baseUrl=(e.baseUrl??ie).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;}async request(e){let t=se(this.baseUrl+e.path,e.query),i=e.method??"GET",s={"Content-Type":"application/json",...this.defaultHeaders,...e.headers},r=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,l=e.retry?.baseDelayMs??this.retry.baseDelayMs,P;for(let h=0;h<a;h++)try{let u=await this.fetchWithTimeout(t,{method:i,headers:s,body:r,...e.keepalive?{keepalive:!0}:{}},o),f=await this.parseBody(u);if(u.ok)return {response:u,data:f};if(this.isRetryableStatus(u.status)&&h<a-1){let D=this.retryAfterMs(u,l,h);this.log(`retrying ${e.path} after ${D}ms (status ${u.status})`),await z(D);continue}throw new m(u.status,f)}catch(u){if(P=u,u instanceof m)throw u;if(h<a-1){let f=l*2**h;this.log(`retrying ${e.path} after ${f}ms (network error)`),await z(f);continue}}throw P instanceof Error?P:new Error("Request failed")}async fetchWithTimeout(e,t,i){let s=new AbortController,r=setTimeout(()=>s.abort(),i);try{return await fetch(e,{...t,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`Request timeout after ${i}ms`,{cause:o}):o}finally{clearTimeout(r);}}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 s=e.headers.get("Retry-After");if(s){let r=Number(s);if(!Number.isNaN(r))return r*1e3}return t*2**i}log(e){this.debug&&console.warn(`[xenia] ${e}`);}};function re(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 w=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=re(t),s=i?i-3e4:e+5*6e4;return this.cached={token:t,expiresAt:s},t}).finally(()=>{this.inflight=null;}),this.inflight}};function J(n){let e={};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);return e}var k=class{http;tenantId;environmentKey;tokenProvider;constructor(e){this.tenantId=e.tenantId,this.environmentKey=e.environmentKey,this.tokenProvider=new w(e),this.http=new b({baseUrl:e.baseUrl,defaultHeaders:e.headers,timeout:e.timeout,retry:e.retry,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:s,data:r}=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:s.status,body:r,actions:_(r),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:J({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:J({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:J({items:e,data:t.data,locale:t.locale})});return i}};var oe=new Set(["eventId","eventType","journeyId","deviceId","visitorId","customerId","email","utmSource","utmMedium","utmCampaign","utmContent","utmId","url","referrer","path","query"]);function L(n){let e={};for(let[t,i]of Object.entries(n))i!==void 0&&(e[t]=i);return e}function j(n){let e={},t={};if(n.props)for(let[s,r]of Object.entries(n.props))r!==void 0&&(oe.has(s)?t[s]=r:e[s]=r);return {...e,...t,...L(n.context??{}),...L(n.identity??{}),eventId:n.eventId,...n.eventType?{eventType:n.eventType}:{},...n.journeyId?{journeyId:n.journeyId}:{}}}var g="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ae(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 v(n=Date.now()){let e="",t=n;for(let r=9;r>=0;r--)e=g[t%32]+e,t=Math.floor(t/32);let i=ae(16),s="";for(let r=0;r<16;r++)s+=g[i[r]%32];return e+s}var H=26;function B(n){if(n.length<=H)return n;let e="";for(let i of [2166136261,16777619]){let s=i>>>0;for(let r=0;r<n.length;r++)s^=n.charCodeAt(r),s=Math.imul(s,16777619)>>>0,e+=g[s%32];}let t="";for(let i=0;i<H;i++){let s=i+1;for(let r=i;r<e.length;r+=H)s=s*31+g.indexOf(e[r])>>>0;t+=g[s%32];}return t}var I=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();}},S=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 C=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 m&&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 le=new Set(["click","view-port","page-load"]);function U(n){let e=n.indexOf("&");if(e===-1)return null;let t=n.slice(0,e),i=n.slice(e+1);return !t||!le.has(i)?null:{eventId:t,interactionType:i}}function Q(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"),s=n.getAttribute("data-xenia-personalized");return {contentKey:e,contentEntryId:t??void 0,baseEntryId:i??void 0,personalized:s==null?void 0:s==="true"}}var E=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 s=i.closest(`[${e}]`);if(s){let r=s.getAttribute(e),o=r?U(r):null;o&&o.interactionType==="click"&&!this.throttled(s)&&this.opts.fire(o.eventId,"click");}if(this.opts.fireSlot){let r=i.closest("[data-xenia-slot]");if(r){let o=Q(r);o&&!this.throttled(r)&&this.opts.fireSlot("click",o);}}},document.addEventListener("click",this.clickHandler);}observeSlot(e){if(!this.opts.fireSlot||this.slotObservers.has(e))return;let t=Q(e);if(!t)return;let i=this.opts.fireSlot,{threshold:s,rootMargin:r}=this.opts.viewport,o=new IntersectionObserver(a=>{for(let l of a)l.isIntersecting&&(this.slotImpressed.has(e)||(this.slotImpressed.add(e),i("impression",t),o.disconnect(),this.slotObservers.delete(e)));},{threshold:s,rootMargin:r});o.observe(e),this.slotObservers.set(e,o);}observeViewport(e,t){if(this.observers.has(e))return;let{threshold:i,rootMargin:s,triggerOnce:r}=this.opts.viewport,o=new IntersectionObserver(a=>{for(let l of a)l.isIntersecting&&(r&&this.triggered.has(e)||this.throttled(e)||(this.opts.fire(t,"view-port"),r&&(this.triggered.add(e),o.disconnect(),this.observers.delete(e))));},{threshold:i,rootMargin:s});o.observe(e),this.observers.set(e,o);}handleElement(e){let t=e.getAttribute(this.attr());if(!t)return;let i=U(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 s=i;this.handleElement(s),this.opts.fireSlot&&s.matches("[data-xenia-slot]")&&this.observeSlot(s),this.scan(s);}}),this.mutationObserver.observe(document.body,{childList:true,subtree:true});}};var R="xenia";function q(n=R){return `${n||R}_vid`}var ue=1800*1e3,M=class{prefix;cookie;deviceId=null;journeyId=null;sessionId=null;constructor(e="xenia",t=true){this.prefix=e,this.cookie=ce(t);}key(e){return `${this.prefix}_${e}`}cookieName(){return q(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{}}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=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}}getSessionId(){let e=this.key("session_id"),t=this.key("session_last_activity"),i=Date.now();try{let s=sessionStorage.getItem(e),r=Number(sessionStorage.getItem(t)),a=s&&Number.isFinite(r)&&i-r<ue?s:v(i);return sessionStorage.setItem(e,a),sessionStorage.setItem(t,String(i)),this.sessionId=a,a}catch{return this.sessionId||(this.sessionId=v(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"),s=this.utmParam("utm_campaign"),r=this.utmParam("utm_content"),o=this.utmParam("utm_id");t&&(e.utmSource=t),i&&(e.utmMedium=i),s&&(e.utmCampaign=s),r&&(e.utmContent=r),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 ce(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 O(n,e=document){if(!n)return null;let t=e.querySelector(`[data-xenia-slot="${pe(n)}"]`);if(t)return t;try{return e.querySelector(n)}catch{return null}}function pe(n){let e=window;return e.CSS?.escape?e.CSS.escape(n):n.replace(/["\\]/g,"\\$&")}function A(n,e){let t=O(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 X(n){let e=O(n);return !e||!(e instanceof HTMLElement)?false:(e.dataset.xeniaHidden="1",e.style.setProperty("display","none","important"),true)}function $(n){let e=O(n);return !e||!(e instanceof HTMLElement)?false:(delete e.dataset.xeniaHidden,e.style.removeProperty("display"),true)}var he=new Set(["banner","popup","modal","inline"]);function me(n){return he.has(n)}var T=class{host=null;shadow=null;onCta;messageTemplate;messageStyles;messageComponent;mounted=new Map;constructor(e,t){this.onCta=e,this.messageTemplate=t?.messageTemplate,this.messageStyles=t?.messageStyles,this.messageComponent=t?.messageComponent;}apply(e){let t=0;for(let i of e)this.applyOne(i)&&t++;return t}applyOne(e){switch(e.type){case "swap":return A(e.target,{html:e.html,text:e.text});case "setContent":return A(e.target,{html:e.html,text:e.text});case "hide":return X(e.target);case "show":return $(e.target);case "redirect":try{return window.location.assign(e.url),!0}catch{return false}default:return me(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?`${K}
2
- ${this.messageStyles}`:K,e}renderMessage(e){let t=e.html===void 0&&!!this.messageComponent;if(e.type==="inline"){if(!e.target)return false;let l=O(e.target);return l?(this.unmount(l),t?(l.innerHTML="",this.mountComponent(l,e,"inline",()=>this.unmount(l))):(l.innerHTML=this.cardHtml(e,"inline"),this.wireCard(l,e)),true):false}let i=this.ensureShadow(),s=document.createElement("div"),r=this.positionClass(e.type,e.position),o=e.html!==void 0?" xenia-custom-bg":"";s.className=`xenia-msg xenia-${e.type}${r?` ${r}`:""}${o}`,i.appendChild(s);let a=()=>{this.unmount(s),s.remove();};return t?this.mountComponent(s,e,e.type,a):(s.innerHTML=this.cardHtml(e,e.type),this.wireCard(s,e,a)),e.dismissAfterMs&&e.dismissAfterMs>0&&setTimeout(a,e.dismissAfterMs),true}mountComponent(e,t,i,s){if(!this.messageComponent)return;let r={action:t,variant:i,close:s,fireCta:()=>{t.cta?.event&&this.onCta?.(t.cta.event,t.cta),t.cta?.url&&window.location.assign(t.cta.url),s();}},o=this.messageComponent(e,r);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){if(e.html!==void 0)return fe(e.html,t);if(this.messageTemplate){let l={action:e,variant:t,escapeHtml:y,escapeAttr:W};return this.messageTemplate(l)}let i=e.imageUrl?`<img class="xenia-img" src="${W(e.imageUrl)}" alt="" />`:"",s=e.title?`<div class="xenia-title">${y(e.title)}</div>`:"",r=e.message?`<div class="xenia-body">${y(e.message)}</div>`:"",o=e.cta?`<button class="xenia-cta" type="button">${y(e.cta.label)}</button>`:"";return `<div class="xenia-card">${t==="inline"?"":'<button class="xenia-close" type="button" aria-label="Close">\xD7</button>'}${i}<div class="xenia-content">${s}${r}${o}</div></div>`}wireCard(e,t,i){i&&e.querySelectorAll(".xenia-close, [data-xenia-close], [class*='close' i], [id*='close' i], [class*='backdrop' i], [id*='backdrop' i]").forEach(o=>{o.removeAttribute("onclick"),o.addEventListener("click",i);}),e.querySelectorAll("[class*='backdrop' i], [id*='backdrop' i]").forEach(r=>{r instanceof HTMLElement&&r.children.length===0&&!r.textContent?.trim()&&(r.style.opacity="0.5");});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?.();});}};function fe(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 y(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function W(n){return y(n).replace(/"/g,"&quot;")}var K=`
1
+ var Xenia=(function(exports){'use strict';var G=new Set(["banner","popup","modal","inline"]),Y=new Set(["top-left","top-right","bottom-left","bottom-right","top","bottom"]),Z=new Set(["swap","hide","show","setContent","redirect",...G]);function J(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function d(i){return typeof i=="string"?i:void 0}function ee(i){return typeof i=="number"?i:void 0}function te(i){if(!J(i))return null;let e=d(i.type);if(!e||!Z.has(e))return null;if(e==="redirect"){let n=d(i.url);return n?{type:e,url:n}:null}if(e==="hide"||e==="show"){let n=d(i.target);return n?{type:e,target:n}:null}if(e==="swap"||e==="setContent"){let n=d(i.target);return n?{type:e,target:n,html:d(i.html),text:d(i.text)}:null}let t=J(i.cta)?{label:d(i.cta.label)??"",url:d(i.cta.url),event:d(i.cta.event)}:void 0;return {type:e,target:d(i.target),title:d(i.title),message:d(i.message),imageUrl:d(i.imageUrl),html:d(i.html),cta:t&&t.label?t:void 0,dismissAfterMs:ee(i.dismissAfterMs),position:ne(i.position)}}function ne(i){let e=d(i);return e&&Y.has(e)?e:void 0}function D(i){let e;if(Array.isArray(i)?e=i:J(i)&&Array.isArray(i.xeniaActions)&&(e=i.xeniaActions),!Array.isArray(e))return [];let t=[];for(let n of e){let s=te(n);s&&t.push(s);}return t}var ie="https://engine.xeniamartech.com/xenia";function w(){return typeof window<"u"&&typeof document<"u"}function se(i,e){if(!e||Object.keys(e).length===0)return i;let t=new URLSearchParams(e),n=i.includes("?")?"&":"?";return `${i}${n}${t.toString()}`}function z(i){return new Promise(e=>setTimeout(e,i))}var m=class extends Error{constructor(t,n,s){super(s??`Request failed with status ${t}`);this.status=t;this.data=n;this.name="HttpError";}status;data},x=class{baseUrl;defaultHeaders;timeout;retry;debug;constructor(e){this.baseUrl=(e.baseUrl??ie).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;}async request(e){let t=se(this.baseUrl+e.path,e.query),n=e.method??"GET",s={"Content-Type":"application/json",...this.defaultHeaders,...e.headers},r=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,l=e.retry?.baseDelayMs??this.retry.baseDelayMs,V;for(let p=0;p<a;p++)try{let u=await this.fetchWithTimeout(t,{method:n,headers:s,body:r,...e.keepalive?{keepalive:!0}:{}},o),f=await this.parseBody(u);if(u.ok)return {response:u,data:f};if(this.isRetryableStatus(u.status)&&p<a-1){let _=this.retryAfterMs(u,l,p);this.log(`retrying ${e.path} after ${_}ms (status ${u.status})`),await z(_);continue}throw new m(u.status,f)}catch(u){if(V=u,u instanceof m)throw u;if(p<a-1){let f=l*2**p;this.log(`retrying ${e.path} after ${f}ms (network error)`),await z(f);continue}}throw V instanceof Error?V:new Error("Request failed")}async fetchWithTimeout(e,t,n){let s=new AbortController,r=setTimeout(()=>s.abort(),n);try{return await fetch(e,{...t,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`Request timeout after ${n}ms`,{cause:o}):o}finally{clearTimeout(r);}}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,n){let s=e.headers.get("Retry-After");if(s){let r=Number(s);if(!Number.isNaN(r))return r*1e3}return t*2**n}log(e){this.debug&&console.warn(`[xenia] ${e}`);}};function re(i){try{let e=i.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 I=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 n=re(t),s=n?n-3e4:e+5*6e4;return this.cached={token:t,expiresAt:s},t}).finally(()=>{this.inflight=null;}),this.inflight}};function g(i){let e={};for(let[t,n]of Object.entries(i))n!==void 0&&(e[t]=n);return e}var k=class{http;tenantId;environmentKey;tokenProvider;constructor(e){this.tenantId=e.tenantId,this.environmentKey=e.environmentKey,this.tokenProvider=new I(e),this.http=new x({baseUrl:e.baseUrl,defaultHeaders:e.headers,timeout:e.timeout,retry:e.retry,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,n="POST"){let{response:s,data:r}=await this.http.request({method:n,path:"/flow",query:{id:e},headers:await this.authHeaders(),body:n==="POST"?t??{}:void 0,noRetry:true});return {status:s.status,body:r,actions:D(r),receivedAt:Date.now()}}async sendEvents(e,t){let{data:n}=await this.http.request({method:"POST",path:"/api/events/v1",headers:await this.authHeaders(),body:{events:e},keepalive:t?.keepalive});return n}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:n}=await this.http.request({method:"POST",path:"/api/events/v1/consent",headers:await this.authHeaders(),body:g({xeniaVisitorId:e,analytics:t.analytics===true,marketing:t.marketing===true,personalization:t.personalization===true,consentSource:t.consentSource,consentVersion:t.consentVersion})});return n}async resolve(e,t={}){let{data:n}=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:g({contentKey:e,data:t.data,locale:t.locale})});return n}async resolveBatch(e,t={}){let{data:n}=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:g({items:e,data:t.data,locale:t.locale})});return n}};var oe=new Set(["eventId","eventType","journeyId","deviceId","visitorId","customerId","email","utmSource","utmMedium","utmCampaign","utmContent","utmId","url","referrer","path","query"]);function L(i){let e={};for(let[t,n]of Object.entries(i))n!==void 0&&(e[t]=n);return e}function j(i){let e={},t={};if(i.props)for(let[s,r]of Object.entries(i.props))r!==void 0&&(oe.has(s)?t[s]=r:e[s]=r);return {...e,...t,...L(i.context??{}),...L(i.identity??{}),eventId:i.eventId,...i.eventType?{eventType:i.eventType}:{},...i.journeyId?{journeyId:i.journeyId}:{}}}var v="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ae(i){let e=new Uint8Array(i);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<i;t++)e[t]=Math.floor(Math.random()*256);return e}function y(i=Date.now()){let e="",t=i;for(let r=9;r>=0;r--)e=v[t%32]+e,t=Math.floor(t/32);let n=ae(16),s="";for(let r=0;r<16;r++)s+=v[n[r]%32];return e+s}var H=26;function B(i){if(i.length<=H)return i;let e="";for(let n of [2166136261,16777619]){let s=n>>>0;for(let r=0;r<i.length;r++)s^=i.charCodeAt(r),s=Math.imul(s,16777619)>>>0,e+=v[s%32];}let t="";for(let n=0;n<H;n++){let s=n+1;for(let r=n;r<e.length;r+=H)s=s*31+v.indexOf(e[r])>>>0;t+=v[s%32];}return t}var S=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();}},C=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 n=this.read();n[e]=t,this.write(n);}get(e){return this.read()[e]}keys(){return Object.keys(this.read())}clear(){try{localStorage.removeItem(this.nsKey);}catch{}}};var E=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 m&&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 le=new Set(["click","view-port","page-load"]);function U(i){let e=i.indexOf("&");if(e===-1)return null;let t=i.slice(0,e),n=i.slice(e+1);return !t||!le.has(n)?null:{eventId:t,interactionType:n}}function Q(i){let e=i.getAttribute("data-xenia-content-key");if(!e)return null;let t=i.getAttribute("data-xenia-content-entry-id"),n=i.getAttribute("data-xenia-base-entry-id"),s=i.getAttribute("data-xenia-personalized");return {contentKey:e,contentEntryId:t??void 0,baseEntryId:n??void 0,personalized:s==null?void 0:s==="true"}}var R=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(),n=this.throttleTimers.get(e)??0;return t-n>=this.opts.throttleMs?(this.throttleTimers.set(e,t),false):true}setupClicks(){let e=this.attr();this.clickHandler=t=>{let n=t.target;if(!n)return;let s=n.closest(`[${e}]`);if(s){let r=s.getAttribute(e),o=r?U(r):null;o&&o.interactionType==="click"&&!this.throttled(s)&&this.opts.fire(o.eventId,"click");}if(this.opts.fireSlot){let r=n.closest("[data-xenia-slot]");if(r){let o=Q(r);o&&!this.throttled(r)&&this.opts.fireSlot("click",o);}}},document.addEventListener("click",this.clickHandler);}observeSlot(e){if(!this.opts.fireSlot||this.slotObservers.has(e))return;let t=Q(e);if(!t)return;let n=this.opts.fireSlot,{threshold:s,rootMargin:r}=this.opts.viewport,o=new IntersectionObserver(a=>{for(let l of a)l.isIntersecting&&(this.slotImpressed.has(e)||(this.slotImpressed.add(e),n("impression",t),o.disconnect(),this.slotObservers.delete(e)));},{threshold:s,rootMargin:r});o.observe(e),this.slotObservers.set(e,o);}observeViewport(e,t){if(this.observers.has(e))return;let{threshold:n,rootMargin:s,triggerOnce:r}=this.opts.viewport,o=new IntersectionObserver(a=>{for(let l of a)l.isIntersecting&&(r&&this.triggered.has(e)||this.throttled(e)||(this.opts.fire(t,"view-port"),r&&(this.triggered.add(e),o.disconnect(),this.observers.delete(e))));},{threshold:n,rootMargin:s});o.observe(e),this.observers.set(e,o);}handleElement(e){let t=e.getAttribute(this.attr());if(!t)return;let n=U(t);n&&(n.interactionType==="view-port"?this.observeViewport(e,n.eventId):n.interactionType==="page-load"&&this.opts.fire(n.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 n of t.addedNodes){if(n.nodeType!==Node.ELEMENT_NODE)continue;let s=n;this.handleElement(s),this.opts.fireSlot&&s.matches("[data-xenia-slot]")&&this.observeSlot(s),this.scan(s);}}),this.mutationObserver.observe(document.body,{childList:true,subtree:true});}};var M="xenia";function q(i=M){return `${i||M}_vid`}var ue=1800*1e3,A=class{prefix;cookie;deviceId=null;journeyId=null;sessionId=null;constructor(e="xenia",t=true){this.prefix=e,this.cookie=ce(t);}key(e){return `${this.prefix}_${e}`}cookieName(){return q(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{}}async resolveDeviceId(){if(this.deviceId)return this.writeVisitorCookie(this.getVisitorId()??this.deviceId),this.deviceId;let e=this.key("device_id");try{let n=localStorage.getItem(e);if(n)return this.deviceId=n,this.writeVisitorCookie(this.getVisitorId()??n),n}catch{}let 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(n=>n.kind==="videoinput"&&n.deviceId)||e.find(n=>n.kind==="audioinput"&&n.deviceId)||e.find(n=>n.kind==="audiooutput"&&n.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(n=>n.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"),n=Date.now();try{let s=sessionStorage.getItem(e),r=Number(sessionStorage.getItem(t)),a=s&&Number.isFinite(r)&&n-r<ue?s:y(n);return sessionStorage.setItem(e,a),sessionStorage.setItem(t,String(n)),this.sessionId=a,a}catch{return this.sessionId||(this.sessionId=y(n)),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"),n=this.utmParam("utm_medium"),s=this.utmParam("utm_campaign"),r=this.utmParam("utm_content"),o=this.utmParam("utm_id");t&&(e.utmSource=t),n&&(e.utmMedium=n),s&&(e.utmCampaign=s),r&&(e.utmContent=r),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 ce(i){if(i===false)return null;let e=i===true?{}:i,t=e.sameSite??"Lax",n=t==="None"?true:e.secure??false;return {sameSite:t,secure:n,maxAgeDays:e.maxAgeDays??365,domain:e.domain}}function P(i,e=document){if(!i)return null;let t=e.querySelector(`[data-xenia-slot="${he(i)}"]`);if(t)return t;try{return e.querySelector(i)}catch{return null}}function he(i){let e=window;return e.CSS?.escape?e.CSS.escape(i):i.replace(/["\\]/g,"\\$&")}function T(i,e){let t=P(i);return t?(e.html!==void 0?t.innerHTML=e.html:e.text!==void 0&&(t.textContent=e.text),t.removeAttribute("hidden"),true):false}function X(i){let e=P(i);return !e||!(e instanceof HTMLElement)?false:(e.dataset.xeniaHidden="1",e.style.setProperty("display","none","important"),true)}function $(i){let e=P(i);return !e||!(e instanceof HTMLElement)?false:(delete e.dataset.xeniaHidden,e.style.removeProperty("display"),true)}var pe=new Set(["banner","popup","modal","inline"]);function me(i){return pe.has(i)}var O=class{host=null;shadow=null;onCta;messageTemplate;messageStyles;messageComponent;mounted=new Map;constructor(e,t){this.onCta=e,this.messageTemplate=t?.messageTemplate,this.messageStyles=t?.messageStyles,this.messageComponent=t?.messageComponent;}apply(e){let t=0;for(let n of e)this.applyOne(n)&&t++;return t}applyOne(e){switch(e.type){case "swap":return T(e.target,{html:e.html,text:e.text});case "setContent":return T(e.target,{html:e.html,text:e.text});case "hide":return X(e.target);case "show":return $(e.target);case "redirect":try{return window.location.assign(e.url),!0}catch{return false}default:return me(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?`${K}
2
+ ${this.messageStyles}`:K,e}renderMessage(e){let t=e.html===void 0&&!!this.messageComponent;if(e.type==="inline"){if(!e.target)return false;let l=P(e.target);return l?(this.unmount(l),t?(l.innerHTML="",this.mountComponent(l,e,"inline",()=>this.unmount(l))):(l.innerHTML=this.cardHtml(e,"inline"),this.wireCard(l,e)),true):false}let n=this.ensureShadow(),s=document.createElement("div"),r=this.positionClass(e.type,e.position),o=e.html!==void 0?" xenia-custom-bg":"";s.className=`xenia-msg xenia-${e.type}${r?` ${r}`:""}${o}`,n.appendChild(s);let a=()=>{this.unmount(s),s.remove();};return t?this.mountComponent(s,e,e.type,a):(s.innerHTML=this.cardHtml(e,e.type),this.wireCard(s,e,a)),e.dismissAfterMs&&e.dismissAfterMs>0&&setTimeout(a,e.dismissAfterMs),true}mountComponent(e,t,n,s){if(!this.messageComponent)return;let r={action:t,variant:n,close:s,fireCta:()=>{t.cta?.event&&this.onCta?.(t.cta.event,t.cta),t.cta?.url&&window.location.assign(t.cta.url),s();}},o=this.messageComponent(e,r);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){if(e.html!==void 0)return fe(e.html,t);if(this.messageTemplate){let l={action:e,variant:t,escapeHtml:b,escapeAttr:W};return this.messageTemplate(l)}let n=e.imageUrl?`<img class="xenia-img" src="${W(e.imageUrl)}" alt="" />`:"",s=e.title?`<div class="xenia-title">${b(e.title)}</div>`:"",r=e.message?`<div class="xenia-body">${b(e.message)}</div>`:"",o=e.cta?`<button class="xenia-cta" type="button">${b(e.cta.label)}</button>`:"";return `<div class="xenia-card">${t==="inline"?"":'<button class="xenia-close" type="button" aria-label="Close">\xD7</button>'}${n}<div class="xenia-content">${s}${r}${o}</div></div>`}wireCard(e,t,n){n&&e.querySelectorAll(".xenia-close, [data-xenia-close], [class*='close' i], [id*='close' i], [class*='backdrop' i], [id*='backdrop' i]").forEach(o=>{o.removeAttribute("onclick"),o.addEventListener("click",n);}),e.querySelectorAll("[class*='backdrop' i], [id*='backdrop' i]").forEach(r=>{r instanceof HTMLElement&&r.children.length===0&&!r.textContent?.trim()&&(r.style.opacity="0.5");});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),n?.();});}};function fe(i,e){return e==="modal"?`<div class="xenia-custom-html">${i}</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>${i}</div>`}function b(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function W(i){return b(i).replace(/"/g,"&quot;")}var K=`
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); }
@@ -31,6 +31,6 @@ ${this.messageStyles}`:K,e}renderMessage(e){let t=e.html===void 0&&!!this.messag
31
31
  font-size: var(--xenia-cta-size, 14px); cursor: pointer; }
32
32
  .xenia-close { position: absolute; top: 6px; right: 8px; background: none; border: 0;
33
33
  font-size: var(--xenia-close-size, 20px); line-height: 1; cursor: pointer; color: var(--xenia-close-color, #999); }
34
- `;var N=class{api;identity;responses;options;renderer;analyticsQueue;tracker=null;ready=false;consentState;listeners=new Map;constructor(e){this.options=e;let t=e.prefix??"xenia";this.identity=new M(t,e.visitorCookie??true),e.visitorId&&this.identity.identify(e.visitorId),this.api=new k(e),this.responses=e.persistResponses===false||!x()?new I:new S(t),this.renderer=new T((i,s)=>this.onCtaEvent(i,s),{messageTemplate:e.messageTemplate,messageStyles:e.messageStyles,messageComponent:e.messageComponent}),this.consentState={...e.consent},this.analyticsQueue=new C({debug:e.debug,send:(i,s)=>this.api.sendEvents(i.map(r=>({...r,consent:this.consentState})),s)});}async init(){this.ready||!x()||(await this.identity.resolveDeviceId(),this.ready=true,this.analyticsAllowed()&&this.analyticsQueue.start(),this.options.autoTrack!==false&&(this.tracker=new E({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},fire:(e,t)=>this.track(e,{interactionType:t},{trigger:true}),fireSlot:(e,t)=>{this.track("customEvent",{customEventName:e==="impression"?"personalization_impression":"personalization_click",contentKey:t.contentKey,contentEntryId:t.contentEntryId??null,baseEntryId:t.baseEntryId??null},{trigger:false});}}),this.tracker.start()));}destroy(){this.tracker?.stop(),this.tracker=null,this.renderer.destroy(),this.analyticsQueue.stop(),this.ready=false;}identify(e){this.identity.identify(e),this.api.identify({xeniaVisitorId:e}).then(t=>this.emit("identify",t)).catch(t=>this.emitError(t));}setJourneyId(e){this.identity.setJourneyId(e);}track(e,t,i={}){if(!x())return;let s=i.trigger===true;if(!s&&this.dntBlocked())return;let r=this.buildEvent(e,t,i);this.emit("event",{eventName:e,event:r}),s?this.analyticsQueue.sendImmediate(r).catch(o=>this.emitError(o)):(this.analyticsQueue.enqueue(r),this.analyticsAllowed()&&this.analyticsQueue.start());}buildEvent(e,t,i){let s=this.identity.collectContext(),r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch{}return {eventName:e,eventId:i.eventId?B(i.eventId):v(),eventVersion:1,occurredAtMs:Date.now(),source:"xenia-js-sdk",identity:{sessionId:this.identity.getSessionId(),...i.identity,xeniaVisitorId:s.visitorId??this.identity.getDeviceId()??void 0},context:{pagePath:s.path,referrer:s.referrer,userAgent:navigator.userAgent,locale:navigator.language,timezone:r,journeyId:this.identity.getJourneyId()??void 0,utmSource:s.utmSource,utmMedium:s.utmMedium,utmCampaign:s.utmCampaign,utmContent:s.utmContent,...i.context},properties:this.withUtmId(t,s.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))}resolveVisitorId(){return this.identity.getVisitorId()??this.identity.getDeviceId()??void 0}withVisitor(e){let t=this.resolveVisitorId();return t?{...e,data:{...e?.data??{},_xenia_vid:t}}:e}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 s=this.identity.collectContext(),r=j({eventId:e,journeyId:this.identity.getJourneyId()??void 0,identity:{deviceId:this.identity.getDeviceId()??void 0,visitorId:this.resolveVisitorId()},context:s,props:t}),o=await this.api.webhook(e,r,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)}swapContent(e,t){return A(e,t)}hideContent(e){return X(e)}showContent(e){return $(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();this.consentState={...this.consentState,...e},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(s){this.emitError(s);}}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 F(n){return new N(n)}var p=null;function c(n){if(!p)throw console.warn(`[xenia] ${n}() called before init().`),new Error("Xenia not initialized");return p}var Qe={init(n){p&&p.destroy(),p=F(n),p.init();},destroy(){p?.destroy(),p=null;},track(n,e,t){c("track").track(n,e,t);},identify(n){c("identify").identify(n);},consent(n){return c("consent").consent(n)},resolve(n,e){return c("resolve").resolve(n,e)},resolveBatch(n,e){return c("resolveBatch").resolveBatch(n,e)},setJourneyId(n){c("setJourneyId").setJourneyId(n);},request(n,e){return c("request").request(n,e)},getResponse(n){return c("getResponse").getResponse(n)},swapContent(n,e){return c("swapContent").swapContent(n,e)},hideContent(n){return c("hideContent").hideContent(n)},showContent(n){return c("showContent").showContent(n)}};exports.Xenia=Qe;return exports;})({});
34
+ `;var N=class{api;identity;responses;options;renderer;analyticsQueue;tracker=null;ready=false;consentState;listeners=new Map;constructor(e){this.options=e;let t=e.prefix??"xenia";this.identity=new A(t,e.visitorCookie??true),e.visitorId&&this.identity.identify(e.visitorId),this.api=new k(e),this.responses=e.persistResponses===false||!w()?new S:new C(t),this.renderer=new O((n,s)=>this.onCtaEvent(n,s),{messageTemplate:e.messageTemplate,messageStyles:e.messageStyles,messageComponent:e.messageComponent}),this.consentState={...e.consent},this.analyticsQueue=new E({debug:e.debug,send:(n,s)=>this.api.sendEvents(n.map(r=>({...r,consent:this.consentState})),s)});}async init(){this.ready||!w()||(await this.identity.resolveDeviceId(),this.ready=true,this.analyticsAllowed()&&this.analyticsQueue.start(),this.options.autoTrack!==false&&(this.tracker=new R({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},fire:(e,t)=>this.track(e,{interactionType:t},{trigger:true}),fireSlot:(e,t)=>{this.track("customEvent",{customEventName:e==="impression"?"personalization_impression":"personalization_click",contentKey:t.contentKey,contentEntryId:t.contentEntryId??null,baseEntryId:t.baseEntryId??null},{trigger:false});}}),this.tracker.start()));}destroy(){this.tracker?.stop(),this.tracker=null,this.renderer.destroy(),this.analyticsQueue.stop(),this.ready=false;}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(n=>this.emit("identify",n)).catch(n=>this.emitError(n));}setJourneyId(e){this.identity.setJourneyId(e);}track(e,t,n={}){if(!w())return;let s=n.trigger===true;if(!s&&this.dntBlocked())return;let r=this.buildEvent(e,t,n);this.emit("event",{eventName:e,event:r}),s?this.analyticsQueue.sendImmediate(r).catch(o=>this.emitError(o)):(this.analyticsQueue.enqueue(r),this.analyticsAllowed()&&this.analyticsQueue.start());}buildEvent(e,t,n){let s=this.identity.collectContext(),r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch{}return {eventName:e,eventId:n.eventId?B(n.eventId):y(),eventVersion:1,occurredAtMs:Date.now(),source:"xenia-js-sdk",identity:{sessionId:this.identity.getSessionId(),...n.identity,xeniaVisitorId:s.visitorId??this.identity.getDeviceId()??void 0},context:{pagePath:s.path,referrer:s.referrer,userAgent:navigator.userAgent,locale:navigator.language,timezone:r,journeyId:this.identity.getJourneyId()??void 0,utmSource:s.utmSource,utmMedium:s.utmMedium,utmCampaign:s.utmCampaign,utmContent:s.utmContent,...n.context},properties:this.withUtmId(t,s.utmId),trigger:n.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))}resolveVisitorId(){return this.identity.getVisitorId()??this.identity.getDeviceId()??void 0}withVisitor(e){let t=this.identity.collectContext(),n=this.resolveVisitorId(),s=g({path:t.path,query:t.query,deviceId:this.identity.getDeviceId()??void 0,visitorId:n,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 n&&(s._xenia_vid=n),Object.keys(s).length===0?e:{...e,data:{...e?.data??{},...s}}}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,n){let s=this.identity.collectContext(),r=j({eventId:e,journeyId:this.identity.getJourneyId()??void 0,identity:{deviceId:this.identity.getDeviceId()??void 0,visitorId:this.resolveVisitorId()},context:s,props:t}),o=await this.api.webhook(e,r,n?.method??"POST");return this.responses.set(e,o),this.emit("response",{triggerId:e,response:o}),(n?.apply??this.options.autoApplyActions!==false)&&o.actions.length&&this.applyActions(o.actions),o}getResponse(e){return this.responses.get(e)}swapContent(e,t){return T(e,t)}hideContent(e){return X(e)}showContent(e){return $(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();this.consentState={...this.consentState,...e},this.analyticsAllowed()&&!t?(this.analyticsQueue.start(),this.analyticsQueue.flush()):!this.analyticsAllowed()&&t&&this.analyticsQueue.stop();let n=this.identity.getVisitorId()??this.identity.getDeviceId();if(n)try{await this.api.consent(n,e);}catch(s){this.emitError(s);}}on(e,t){let n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>n.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>{try{n(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 F(i){return new N(i)}var h=null;function c(i){if(!h)throw console.warn(`[xenia] ${i}() called before init().`),new Error("Xenia not initialized");return h}var Qe={init(i){h&&h.destroy(),h=F(i),h.init();},destroy(){h?.destroy(),h=null;},track(i,e,t){c("track").track(i,e,t);},identify(i){c("identify").identify(i);},consent(i){return c("consent").consent(i)},resolve(i,e){return c("resolve").resolve(i,e)},resolveBatch(i,e){return c("resolveBatch").resolveBatch(i,e)},setJourneyId(i){c("setJourneyId").setJourneyId(i);},request(i,e){return c("request").request(i,e)},getResponse(i){return c("getResponse").getResponse(i)},swapContent(i,e){return c("swapContent").swapContent(i,e)},hideContent(i){return c("hideContent").hideContent(i)},showContent(i){return c("showContent").showContent(i)}};exports.Xenia=Qe;return exports;})({});
35
35
  Xenia=Xenia&&(Xenia.Xenia||Xenia.default)||Xenia;if(typeof window!=='undefined'){window.Xenia=Xenia;}
36
36
  //# sourceMappingURL=xenia-sdk.iife.js.map