@xenia-martech/sdk-js 1.0.0-dev.26 → 1.0.0-dev.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CSS_VARIABLES.md +7 -0
- package/README.md +71 -2
- package/dist/{actions-DFLoSXO_.d.cts → actions-CcBYV--3.d.cts} +242 -6
- package/dist/{actions-DFLoSXO_.d.ts → actions-CcBYV--3.d.ts} +242 -6
- package/dist/{chunk-3KYKKIIG.cjs → chunk-WYM4CQVG.cjs} +126 -4
- package/dist/chunk-WYM4CQVG.cjs.map +1 -0
- package/dist/{chunk-D37RD3UC.js → chunk-XXNDHYAS.js} +125 -5
- package/dist/chunk-XXNDHYAS.js.map +1 -0
- package/dist/client/index.cjs +613 -35
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.d.cts +112 -3
- package/dist/client/index.d.ts +112 -3
- package/dist/client/index.js +610 -36
- package/dist/client/index.js.map +1 -1
- package/dist/client/react/index.cjs +609 -35
- package/dist/client/react/index.cjs.map +1 -1
- package/dist/client/react/index.d.cts +2 -2
- package/dist/client/react/index.d.ts +2 -2
- package/dist/client/react/index.js +609 -35
- package/dist/client/react/index.js.map +1 -1
- package/dist/{cookie-names-LgNDAreS.d.cts → cookie-names-B3b0XNc2.d.cts} +187 -1
- package/dist/{cookie-names-LgNDAreS.d.ts → cookie-names-B3b0XNc2.d.ts} +187 -1
- package/dist/index.cjs +23 -19
- package/dist/index.d.cts +23 -3
- package/dist/index.d.ts +23 -3
- package/dist/index.js +1 -1
- package/dist/server/index.cjs +53 -22
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +31 -11
- package/dist/server/index.d.ts +31 -11
- package/dist/server/index.js +43 -12
- package/dist/server/index.js.map +1 -1
- package/dist/xenia-sdk.iife.js +37 -3
- package/dist/xenia-sdk.iife.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-3KYKKIIG.cjs.map +0 -1
- package/dist/chunk-D37RD3UC.js.map +0 -1
|
@@ -80,6 +80,23 @@ interface XeniaConfig {
|
|
|
80
80
|
* cookie read via `getVisitorId()`.
|
|
81
81
|
*/
|
|
82
82
|
visitorId?: string;
|
|
83
|
+
/**
|
|
84
|
+
* The ambient request context for a **server** client — the SDK-provided page/campaign fields
|
|
85
|
+
* (`path`, `query`, `url`, `referrer`, `utmSource`/`utmMedium`/`utmCampaign`/`utmContent`/`utmId`)
|
|
86
|
+
* that get attached to EVERY `resolve()`/`resolveBatch()`/`webhook()` made with this client, so
|
|
87
|
+
* journey rules can gate on `query.<name>` or `path` without any per-call wiring.
|
|
88
|
+
*
|
|
89
|
+
* The browser client needs nothing here — it reads these off `window.location` itself. A server
|
|
90
|
+
* runtime has no ambient request, so bind it once when constructing the per-request client:
|
|
91
|
+
*
|
|
92
|
+
* ```ts
|
|
93
|
+
* createXeniaServer({ …, context: contextFromUrl(currentUrl, referrer) })
|
|
94
|
+
* ```
|
|
95
|
+
*
|
|
96
|
+
* Lowest precedence: a per-call `context`/`identity` overrides it, and the SDK-owned `visitorId`
|
|
97
|
+
* still wins over everything.
|
|
98
|
+
*/
|
|
99
|
+
context?: EventContext;
|
|
83
100
|
/**
|
|
84
101
|
* Persist the SDK visitor id to a first-party `xenia_vid` cookie so your
|
|
85
102
|
* **same-origin** server can read it (`getVisitorId(cookieHeader)`) and bind
|
|
@@ -115,6 +132,13 @@ interface VisitorCookieOptions {
|
|
|
115
132
|
/** Cookie lifetime in days. Default 365. */
|
|
116
133
|
maxAgeDays?: number;
|
|
117
134
|
}
|
|
135
|
+
/** Well-known event fields understood by the backend event-trigger node. */
|
|
136
|
+
interface EventIdentity {
|
|
137
|
+
deviceId?: string;
|
|
138
|
+
visitorId?: string;
|
|
139
|
+
customerId?: string;
|
|
140
|
+
email?: string;
|
|
141
|
+
}
|
|
118
142
|
/** UTM + page context captured automatically by the client. */
|
|
119
143
|
interface EventContext {
|
|
120
144
|
utmSource?: string;
|
|
@@ -291,6 +315,23 @@ interface ResolveOptions {
|
|
|
291
315
|
locale?: string;
|
|
292
316
|
/** When true, ask the server to splice and return `content`. */
|
|
293
317
|
merge?: boolean;
|
|
318
|
+
/**
|
|
319
|
+
* Caller-supplied identity fields (`deviceId`/`visitorId`/`customerId`/
|
|
320
|
+
* `email`), merged into `data` the same way `ServerWebhookOptions.identity`
|
|
321
|
+
* is merged for `webhook()`. Only relevant server-side — the browser client
|
|
322
|
+
* collects these ambiently instead and ignores this field. The SDK-owned
|
|
323
|
+
* `visitorId` (from `config.visitorId`) still wins over a value supplied
|
|
324
|
+
* here, same precedence as `webhook()`.
|
|
325
|
+
*/
|
|
326
|
+
identity?: EventIdentity;
|
|
327
|
+
/**
|
|
328
|
+
* Caller-supplied page context (`path`/`query`/`url`/`referrer`/`utm*`),
|
|
329
|
+
* merged into `data` the same way `ServerWebhookOptions.context` is merged
|
|
330
|
+
* for `webhook()`. There's no ambient `window`/`document` server-side, so a
|
|
331
|
+
* server caller who wants these SDK-provided fields on a resolve() call
|
|
332
|
+
* must pass them explicitly (e.g. from the current request's headers).
|
|
333
|
+
*/
|
|
334
|
+
context?: EventContext;
|
|
294
335
|
}
|
|
295
336
|
/** Body posted to `POST /api/events/v1/identify` — binds visitor to a known user. */
|
|
296
337
|
interface IdentifyRequest {
|
|
@@ -334,6 +375,109 @@ interface MessageCta {
|
|
|
334
375
|
/** Optional event fired when the CTA is clicked. */
|
|
335
376
|
event?: string;
|
|
336
377
|
}
|
|
378
|
+
/**
|
|
379
|
+
* Widget-specific rendering/interaction behavior for a message-placement action —
|
|
380
|
+
* ORTHOGONAL to `type` (the existing `banner|popup|modal|inline` placement enum, which
|
|
381
|
+
* stays exactly as-is). `type` says WHERE it renders; `widgetType` says WHAT it is.
|
|
382
|
+
* Keeping these separate is what lets `core/actions.ts`'s `MESSAGE_TYPES` allowlist AND
|
|
383
|
+
* the PHP SDK's `XeniaActions::KNOWN_TYPES` allowlist (same value set) stay completely
|
|
384
|
+
* unchanged — the PHP SDK needs zero code changes for widget support.
|
|
385
|
+
*
|
|
386
|
+
* `"standard"` (or omitted) is a plain message/popup — the existing card path, unmodified.
|
|
387
|
+
* A future 3rd widget type is one new literal here + one new dispatch-table entry in
|
|
388
|
+
* `client/widgets/index.ts`, not a rewrite.
|
|
389
|
+
*/
|
|
390
|
+
type WidgetType = "standard" | "spin-wheel";
|
|
391
|
+
/**
|
|
392
|
+
* A prize/outcome segment shown to the visitor for a spin-wheel widget — label/color ONLY.
|
|
393
|
+
* Real weight/prize-code are marketer-authored server-side config (`config.widgetSubmissions`)
|
|
394
|
+
* and never leave the backend; they never appear here.
|
|
395
|
+
*/
|
|
396
|
+
interface WidgetSegment {
|
|
397
|
+
id: string;
|
|
398
|
+
label: string;
|
|
399
|
+
colorHex?: string;
|
|
400
|
+
/** Marks this segment as a non-winning outcome (e.g. "Try Again") — drives which of the
|
|
401
|
+
* win/loss reveal screens (see WidgetStyle) the widget shows once this segment resolves. */
|
|
402
|
+
isLoss?: boolean;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* The SAFE runtime envelope describing how a widget's captured form submission is
|
|
406
|
+
* dispatched — never a credential, never a prize weight/code (see the cross-repo
|
|
407
|
+
* contract). The SDK does not branch on `mode`'s value itself; it only follows whichever
|
|
408
|
+
* ref field is present (`flowRef` vs `bindingRef`) to pick an endpoint — `mode`/`ref` are
|
|
409
|
+
* otherwise relayed to the backend verbatim, uninterpreted.
|
|
410
|
+
*/
|
|
411
|
+
interface WidgetFormSubmit {
|
|
412
|
+
/** `true` for spin-wheel (server must resolve an outcome before anything renders). */
|
|
413
|
+
requiresResolve: boolean;
|
|
414
|
+
/** `"journey"` or `"endpoint"` — informational only; the SDK never branches on this value. */
|
|
415
|
+
mode: "journey" | "endpoint" | (string & {});
|
|
416
|
+
/** Present only when `mode === "journey" && !requiresResolve` — the direct `/flow` fast path, no secret. */
|
|
417
|
+
flowRef?: string;
|
|
418
|
+
/** Present whenever `requiresResolve || mode === "endpoint"`. */
|
|
419
|
+
bindingRef?: string;
|
|
420
|
+
/**
|
|
421
|
+
* Minimum time (ms) to keep the success state visible after a submit resolves, before the
|
|
422
|
+
* card dismisses itself — configured marketer-side on the webhook-response node's
|
|
423
|
+
* Form-submission panel. The real dispatch typically responds in well under 100ms, which
|
|
424
|
+
* would otherwise make the card vanish before a visitor registers it succeeded at all.
|
|
425
|
+
* Defaults to 900 when absent (an older/unconfigured binding).
|
|
426
|
+
*/
|
|
427
|
+
successDisplayMs?: number;
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Per-action visual overrides for a widget's own window chrome (spin-wheel).
|
|
431
|
+
* Deliberately narrow — everything about the widget's actual CONTENT (spinner/win/loss screens)
|
|
432
|
+
* is full marketer/AI-authored HTML (`spinnerHtml`/`winHtml`/`lossHtml` on `XeniaAction`, same
|
|
433
|
+
* pattern as a popup's `body`), not a field here. This only covers the two things that live
|
|
434
|
+
* OUTSIDE that HTML, in the SDK's own generated chrome around it.
|
|
435
|
+
*/
|
|
436
|
+
interface WidgetStyle {
|
|
437
|
+
/**
|
|
438
|
+
* Hides the built-in close (×) button. No spin-wheel renderer draws one of its own anymore
|
|
439
|
+
* (see `spin-wheel.ts`'s `html()`) — every screen's own `spinnerHtml`/`winHtml`/`lossHtml`
|
|
440
|
+
* carries its own close affordance, matched by the same heuristic every custom-HTML surface
|
|
441
|
+
* honors (`wireCloseAffordances`). Currently vestigial: not exposed in Content Studio's AI
|
|
442
|
+
* schema, and not read by any widget renderer's `html()`.
|
|
443
|
+
*/
|
|
444
|
+
hideCloseButton?: boolean;
|
|
445
|
+
/** Hides the dimmed backdrop behind the modal/popup/banner. Defaults to shown. */
|
|
446
|
+
hideOverlay?: boolean;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Server-resolved outcome for a spin-wheel submission
|
|
450
|
+
* (`XeniaClient.submitWidgetForm`'s response). Absent for a plain form submit.
|
|
451
|
+
* `segmentId` matches an `id` in the action's `segments` list. Never the whole prize
|
|
452
|
+
* config (weight/internal code) — only what the backend decides is safe to reveal.
|
|
453
|
+
*/
|
|
454
|
+
interface WidgetPrize {
|
|
455
|
+
segmentId?: string;
|
|
456
|
+
label?: string;
|
|
457
|
+
colorHex?: string;
|
|
458
|
+
[key: string]: JsonValue | undefined;
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Response from a widget form submission (`XeniaClient.submitWidgetForm`) — whichever
|
|
462
|
+
* endpoint was actually hit (the `/flow` fast path or `/widget-submissions`), normalized
|
|
463
|
+
* to one shape. `actions` flows through the existing `parseActions()`/`ActionRenderer.apply()`
|
|
464
|
+
* pipeline unchanged; `prize` is read directly by the spin-wheel widget module to drive
|
|
465
|
+
* its reveal.
|
|
466
|
+
*/
|
|
467
|
+
interface WidgetSubmitResponse {
|
|
468
|
+
status: number;
|
|
469
|
+
body: JsonValue;
|
|
470
|
+
actions: XeniaAction[];
|
|
471
|
+
prize?: WidgetPrize;
|
|
472
|
+
/** True when this visitor already played and the stored result is being replayed, not re-rolled. */
|
|
473
|
+
alreadyPlayed?: boolean;
|
|
474
|
+
/** Whether the configured dispatch (journey invoke / outbound endpoint call) actually fired. */
|
|
475
|
+
dispatched?: boolean;
|
|
476
|
+
/** Present when `dispatched` is false and the server attempted but failed the configured dispatch. */
|
|
477
|
+
dispatchError?: string;
|
|
478
|
+
widgetType?: WidgetType;
|
|
479
|
+
receivedAt: number;
|
|
480
|
+
}
|
|
337
481
|
/**
|
|
338
482
|
* A render directive the SDK executes in the browser. Marketers emit these in
|
|
339
483
|
* a `webhook-response` node body under the `xeniaActions` key.
|
|
@@ -369,6 +513,43 @@ type XeniaAction = {
|
|
|
369
513
|
/** Anchor within the placement (see {@link MessagePosition}). Defaults to the
|
|
370
514
|
* SDK's built-in default per type (popup: bottom-right; banner: bottom). */
|
|
371
515
|
position?: MessagePosition;
|
|
516
|
+
/** Orthogonal widget-behavior driver — see {@link WidgetType}. Omitted/`"standard"` renders
|
|
517
|
+
* exactly like today. */
|
|
518
|
+
widgetType?: WidgetType;
|
|
519
|
+
/** Label/color-only outcome segments for `spin-wheel` widgets. */
|
|
520
|
+
segments?: WidgetSegment[];
|
|
521
|
+
/** Safe form-submission envelope — see {@link WidgetFormSubmit}. Absent when the action has
|
|
522
|
+
* no capturable outcome. */
|
|
523
|
+
formSubmit?: WidgetFormSubmit;
|
|
524
|
+
/** Per-action visual overrides for the widget's own window — see {@link WidgetStyle}. */
|
|
525
|
+
style?: WidgetStyle;
|
|
526
|
+
/**
|
|
527
|
+
* Full marketer/AI-authored HTML for `spin-wheel`'s pre-spin face (title/subtitle/spin
|
|
528
|
+
* button/background — the whole visual design) — independent of the generic `html` field
|
|
529
|
+
* above, which spin-wheel never reads. The primary, ordinary way this screen
|
|
530
|
+
* is authored (same role `body` plays for a popup) — there is no separate generated
|
|
531
|
+
* template to fall back to. To keep the wheel and spin button working, include an element
|
|
532
|
+
* carrying `data-xenia-wheel-slot` (the SDK mounts the generated SVG wheel + pointer
|
|
533
|
+
* there) and one carrying `data-xenia-spin` (the SDK wires the spin click there) —
|
|
534
|
+
* omitting either simply drops that capability, same as any other custom-HTML widget.
|
|
535
|
+
*/
|
|
536
|
+
spinnerHtml?: string;
|
|
537
|
+
/**
|
|
538
|
+
* Full marketer/AI-authored HTML for the win-reveal screen (`spin-wheel`), shown once a
|
|
539
|
+
* spin resolves to a non-`isLoss` segment — the primary way this screen is authored,
|
|
540
|
+
* same role as {@link spinnerHtml}. Include `data-xenia-wheel-prize` on any element to
|
|
541
|
+
* receive the resolved prize label, and `data-xenia-wheel-cta` on a button to wire its
|
|
542
|
+
* click to dismiss (same close-affordance heuristics as any other custom-HTML widget also
|
|
543
|
+
* apply here — see `wireCloseAffordances`).
|
|
544
|
+
*/
|
|
545
|
+
winHtml?: string;
|
|
546
|
+
/**
|
|
547
|
+
* Full marketer/AI-authored HTML for the loss/"try again" screen, shown once a
|
|
548
|
+
* spin resolves to a segment with {@link WidgetSegment.isLoss} set. Same hooks and
|
|
549
|
+
* same primary-authoring role as {@link winHtml} (a losing outcome still has a `label`,
|
|
550
|
+
* e.g. "Try Again", so `data-xenia-wheel-prize` is still honored here).
|
|
551
|
+
*/
|
|
552
|
+
lossHtml?: string;
|
|
372
553
|
} | {
|
|
373
554
|
type: "redirect";
|
|
374
555
|
url: string;
|
|
@@ -455,6 +636,18 @@ declare class XeniaApi {
|
|
|
455
636
|
* duplicate the journey run.
|
|
456
637
|
*/
|
|
457
638
|
webhook(triggerId: string, data?: JsonValue, method?: "GET" | "POST"): Promise<WebhookResponse>;
|
|
639
|
+
/**
|
|
640
|
+
* Widget form submission — `POST /widget-submissions?ref={bindingRef}`. Used whenever the
|
|
641
|
+
* action's `formSubmit.requiresResolve` is true (spin-wheel, which must have a
|
|
642
|
+
* server-resolved outcome before anything renders) or `mode === "endpoint"` — the common
|
|
643
|
+
* plain-popup case (`mode === "journey" && !requiresResolve`) bypasses this entirely and calls
|
|
644
|
+
* {@link webhook} against `flowRef` instead (see `XeniaClient.submitWidgetForm`'s endpoint
|
|
645
|
+
* selection).
|
|
646
|
+
*
|
|
647
|
+
* Not retried (`noRetry: true`), styled like {@link webhook} — a retried POST must never
|
|
648
|
+
* double-fire a journey or double-resolve a prize server-side.
|
|
649
|
+
*/
|
|
650
|
+
submitWidget(ref: string, body?: JsonValue): Promise<WidgetSubmitResponse>;
|
|
458
651
|
/**
|
|
459
652
|
* Unified event batch (max 100/request per the backend) — `POST /api/events/v1`.
|
|
460
653
|
* Records analytics for every event and matches/advances a journey for any
|
|
@@ -543,6 +736,10 @@ declare class Identity {
|
|
|
543
736
|
/** Persist a visitor id so it rides on every future event. */
|
|
544
737
|
identify(visitorId: string): void;
|
|
545
738
|
getVisitorId(): string | null;
|
|
739
|
+
setCustomerId(customerId: string | null): void;
|
|
740
|
+
getCustomerId(): string | null;
|
|
741
|
+
setEmail(email: string | null): void;
|
|
742
|
+
getEmail(): string | null;
|
|
546
743
|
/**
|
|
547
744
|
* Resolve the current session id: reused while activity continues within
|
|
548
745
|
* {@link SESSION_TIMEOUT_MS}, otherwise a new one is minted. Persisted in
|
|
@@ -628,8 +825,15 @@ declare class XeniaClient {
|
|
|
628
825
|
* Persist a visitor id, attached to every subsequent event, and bind it to
|
|
629
826
|
* a known user server-side (`POST /api/events/v1/identify`, fire-and-
|
|
630
827
|
* forget — resolves to an `"identify"` client event carrying `personId`).
|
|
828
|
+
*
|
|
829
|
+
* `extra.customerId`/`extra.email`, when supplied, are also persisted
|
|
830
|
+
* ambiently (like the visitor id) so they ride on every later `resolve()`
|
|
831
|
+
* call automatically — part of the SDK-provided-fields parity list.
|
|
631
832
|
*/
|
|
632
|
-
identify(visitorId: string
|
|
833
|
+
identify(visitorId: string, extra?: {
|
|
834
|
+
customerId?: string;
|
|
835
|
+
email?: string;
|
|
836
|
+
}): void;
|
|
633
837
|
/** Override the customer-journey UUID (else derived from utm_id). */
|
|
634
838
|
setJourneyId(id: string | null): void;
|
|
635
839
|
/**
|
|
@@ -675,10 +879,18 @@ declare class XeniaClient {
|
|
|
675
879
|
/** The SDK-owned visitor anchor: the `identify()`/`config.visitorId` id, else the device id. */
|
|
676
880
|
private resolveVisitorId;
|
|
677
881
|
/**
|
|
678
|
-
* Stamp the SDK-
|
|
679
|
-
* `
|
|
680
|
-
*
|
|
681
|
-
*
|
|
882
|
+
* Stamp the full set of SDK-provided fields into the resolve `data` —
|
|
883
|
+
* `path`, `query`, `deviceId`, `visitorId`, `customerId`, `email`, `url`,
|
|
884
|
+
* `referrer`, and the five `utm*` fields — the same field-name/type parity
|
|
885
|
+
* the webhook trigger's "SDK-provided fields" already promises, now native
|
|
886
|
+
* (always attached, no marketer toggle) for the Personalization Resolve
|
|
887
|
+
* trigger too. Plus the reserved `_xenia_vid` key the backend reads for
|
|
888
|
+
* holdout/exposure bucketing. All of these are spread LAST (after the
|
|
889
|
+
* caller's own `data`) so none can be overridden per call — the same
|
|
890
|
+
* override-protection guarantee `_xenia_vid` alone used to have, now
|
|
891
|
+
* widened to the full set. A no-op (returns `opts` unchanged) when nothing
|
|
892
|
+
* is resolvable yet (e.g. called before `init()` on a fresh visit with no
|
|
893
|
+
* page context available).
|
|
682
894
|
*/
|
|
683
895
|
private withVisitor;
|
|
684
896
|
private dntBlocked;
|
|
@@ -694,6 +906,30 @@ declare class XeniaClient {
|
|
|
694
906
|
}): Promise<WebhookResponse>;
|
|
695
907
|
/** Read the last saved webhook response for a key (triggerId/eventId). */
|
|
696
908
|
getResponse(key: string): WebhookResponse | undefined;
|
|
909
|
+
/**
|
|
910
|
+
* Submit a widget's captured form values (standard/custom popup submit, or a spin-wheel/
|
|
911
|
+
* spin-wheel's resolve request) and apply any returned `xeniaActions`, exactly like
|
|
912
|
+
* {@link request}.
|
|
913
|
+
*
|
|
914
|
+
* **Endpoint selection is config-driven, not SDK-decided** (per the cross-repo contract): a
|
|
915
|
+
* `flowRef` (present only when `mode === "journey" && !requiresResolve` — the common
|
|
916
|
+
* plain-popup case) bypasses the resolve endpoint entirely and POSTs straight to the existing
|
|
917
|
+
* public `/flow` fast path; otherwise this POSTs to `/widget-submissions` via `bindingRef`. The
|
|
918
|
+
* SDK is agnostic to *why* — it just follows whichever ref field the backend populated.
|
|
919
|
+
*
|
|
920
|
+
* The full ambient-context parity list {@link request}/`withVisitor()` already build
|
|
921
|
+
* (visitorId, deviceId, url, referrer, path, query, `utm*`) rides on every call, plus `fields`
|
|
922
|
+
* and `submit.mode`/the resolved ref, relayed verbatim/uninterpreted — the SDK never branches
|
|
923
|
+
* on `mode`'s value itself, that's server-side.
|
|
924
|
+
*
|
|
925
|
+
* `opts.idempotencyKey` defaults to a freshly generated ULID; pass the SAME key back in on a
|
|
926
|
+
* retried submit of the same interaction so a network retry can't double-fire a journey or
|
|
927
|
+
* double-resolve a prize server-side.
|
|
928
|
+
*/
|
|
929
|
+
submitWidgetForm(submit: WidgetFormSubmit, fields: Record<string, string>, opts?: {
|
|
930
|
+
idempotencyKey?: string;
|
|
931
|
+
apply?: boolean;
|
|
932
|
+
}): Promise<WidgetSubmitResponse>;
|
|
697
933
|
swapContent(target: string, content: {
|
|
698
934
|
html?: string;
|
|
699
935
|
text?: string;
|
|
@@ -748,4 +984,4 @@ declare function extractContentSwaps(body: JsonValue): ContentSwap[] | undefined
|
|
|
748
984
|
*/
|
|
749
985
|
declare function parseActions(body: JsonValue): XeniaAction[];
|
|
750
986
|
|
|
751
|
-
export { type AnalyticsContext as A, type ClientEvent as C, type InteractionType as I, type JsonValue as J, type MessageCta as M, type PersonalizationSwap as P, type ResolveBatchItem as R, type TrackOptions as T, type
|
|
987
|
+
export { type AnalyticsContext as A, extractContentSwaps as B, type ClientEvent as C, parseActions as D, spliceSlots as E, type InteractionType as I, type JsonValue as J, type MessageCta as M, type PersonalizationSwap as P, type ResolveBatchItem as R, type TrackOptions as T, type WidgetFormSubmit as W, type XeniaConfig as X, type XeniaEvent as a, type MessageTemplateFn as b, type MessageComponentRenderer as c, type WidgetSubmitResponse as d, type XeniaAction as e, type MessagePlacement as f, type AnalyticsEventName as g, type AnalyticsIdentity as h, type AnalyticsIngestResponse as i, type ConsentState as j, type ContentSwap as k, type IdentifyRequest as l, type IdentifyResponse as m, Identity as n, type MessageMountContext as o, type MessageRenderContext as p, type ResolveBatchResult as q, type ResolveOptions as r, type ResolveResult as s, type WebhookResponse as t, type WidgetPrize as u, type WidgetSegment as v, type WidgetType as w, XeniaClient as x, type XeniaClientOptions as y, createXeniaClient as z };
|
|
@@ -15,6 +15,7 @@ var MESSAGE_POSITIONS = /* @__PURE__ */ new Set([
|
|
|
15
15
|
"top",
|
|
16
16
|
"bottom"
|
|
17
17
|
]);
|
|
18
|
+
var WIDGET_TYPES = /* @__PURE__ */ new Set(["standard", "spin-wheel"]);
|
|
18
19
|
var ALL_TYPES = /* @__PURE__ */ new Set([
|
|
19
20
|
"swap",
|
|
20
21
|
"hide",
|
|
@@ -61,15 +62,67 @@ function toAction(raw) {
|
|
|
61
62
|
message: asString(raw.message),
|
|
62
63
|
imageUrl: asString(raw.imageUrl),
|
|
63
64
|
html: asString(raw.html),
|
|
64
|
-
|
|
65
|
+
// A link-only CTA (empty label, e.g. a spin-wheel's data-xenia-wheel-cta —
|
|
66
|
+
// label is meaningless there, the winHtml/lossHtml design supplies its own button text)
|
|
67
|
+
// must still parse through — gating on `cta.label` alone silently dropped it.
|
|
68
|
+
cta: cta && (cta.label || cta.url) ? cta : void 0,
|
|
65
69
|
dismissAfterMs: asNumber(raw.dismissAfterMs),
|
|
66
|
-
position: asMessagePosition(raw.position)
|
|
70
|
+
position: asMessagePosition(raw.position),
|
|
71
|
+
widgetType: asWidgetType(raw.widgetType),
|
|
72
|
+
segments: asSegments(raw.segments),
|
|
73
|
+
formSubmit: asFormSubmit(raw.formSubmit),
|
|
74
|
+
style: asWidgetStyle(raw.style),
|
|
75
|
+
spinnerHtml: asString(raw.spinnerHtml),
|
|
76
|
+
winHtml: asString(raw.winHtml),
|
|
77
|
+
lossHtml: asString(raw.lossHtml)
|
|
67
78
|
};
|
|
68
79
|
}
|
|
69
80
|
function asMessagePosition(v) {
|
|
70
81
|
const s = asString(v);
|
|
71
82
|
return s && MESSAGE_POSITIONS.has(s) ? s : void 0;
|
|
72
83
|
}
|
|
84
|
+
function asWidgetType(v) {
|
|
85
|
+
const s = asString(v);
|
|
86
|
+
return s && WIDGET_TYPES.has(s) ? s : void 0;
|
|
87
|
+
}
|
|
88
|
+
function asSegments(v) {
|
|
89
|
+
if (!Array.isArray(v)) return void 0;
|
|
90
|
+
const segments = [];
|
|
91
|
+
for (const entry of v) {
|
|
92
|
+
if (!isObject(entry)) continue;
|
|
93
|
+
const id = asString(entry.id);
|
|
94
|
+
const label = asString(entry.label);
|
|
95
|
+
if (!id || !label) continue;
|
|
96
|
+
segments.push({
|
|
97
|
+
id,
|
|
98
|
+
label,
|
|
99
|
+
colorHex: asString(entry.colorHex),
|
|
100
|
+
isLoss: entry.isLoss === true
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
return segments.length ? segments : void 0;
|
|
104
|
+
}
|
|
105
|
+
function asFormSubmit(v) {
|
|
106
|
+
if (!isObject(v)) return void 0;
|
|
107
|
+
const mode = asString(v.mode);
|
|
108
|
+
if (!mode) return void 0;
|
|
109
|
+
return {
|
|
110
|
+
requiresResolve: v.requiresResolve === true,
|
|
111
|
+
mode,
|
|
112
|
+
flowRef: asString(v.flowRef),
|
|
113
|
+
bindingRef: asString(v.bindingRef),
|
|
114
|
+
successDisplayMs: asNumber(v.successDisplayMs)
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function asWidgetStyle(v) {
|
|
118
|
+
if (!isObject(v)) return void 0;
|
|
119
|
+
const style = {
|
|
120
|
+
hideCloseButton: v.hideCloseButton === true,
|
|
121
|
+
hideOverlay: v.hideOverlay === true
|
|
122
|
+
};
|
|
123
|
+
const hasAny = style.hideCloseButton || style.hideOverlay;
|
|
124
|
+
return hasAny ? style : void 0;
|
|
125
|
+
}
|
|
73
126
|
function parseActions(body) {
|
|
74
127
|
let list;
|
|
75
128
|
if (Array.isArray(body)) {
|
|
@@ -252,6 +305,12 @@ var TokenProvider = class {
|
|
|
252
305
|
};
|
|
253
306
|
|
|
254
307
|
// src/core/api.ts
|
|
308
|
+
function isJsonObject(v) {
|
|
309
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
310
|
+
}
|
|
311
|
+
function asWidgetPrize(v) {
|
|
312
|
+
return v !== void 0 && isJsonObject(v) ? v : void 0;
|
|
313
|
+
}
|
|
255
314
|
function compact(obj) {
|
|
256
315
|
const out = {};
|
|
257
316
|
for (const [k, v] of Object.entries(obj)) {
|
|
@@ -321,6 +380,39 @@ var XeniaApi = class {
|
|
|
321
380
|
receivedAt: Date.now()
|
|
322
381
|
};
|
|
323
382
|
}
|
|
383
|
+
/**
|
|
384
|
+
* Widget form submission — `POST /widget-submissions?ref={bindingRef}`. Used whenever the
|
|
385
|
+
* action's `formSubmit.requiresResolve` is true (spin-wheel, which must have a
|
|
386
|
+
* server-resolved outcome before anything renders) or `mode === "endpoint"` — the common
|
|
387
|
+
* plain-popup case (`mode === "journey" && !requiresResolve`) bypasses this entirely and calls
|
|
388
|
+
* {@link webhook} against `flowRef` instead (see `XeniaClient.submitWidgetForm`'s endpoint
|
|
389
|
+
* selection).
|
|
390
|
+
*
|
|
391
|
+
* Not retried (`noRetry: true`), styled like {@link webhook} — a retried POST must never
|
|
392
|
+
* double-fire a journey or double-resolve a prize server-side.
|
|
393
|
+
*/
|
|
394
|
+
async submitWidget(ref, body) {
|
|
395
|
+
const { response, data: rawBody } = await this.http.request({
|
|
396
|
+
method: "POST",
|
|
397
|
+
path: "/widget-submissions",
|
|
398
|
+
query: { ref },
|
|
399
|
+
headers: await this.authHeaders(),
|
|
400
|
+
body: body ?? {},
|
|
401
|
+
noRetry: true
|
|
402
|
+
});
|
|
403
|
+
const obj = isJsonObject(rawBody) ? rawBody : {};
|
|
404
|
+
return {
|
|
405
|
+
status: response.status,
|
|
406
|
+
body: rawBody,
|
|
407
|
+
actions: parseActions(rawBody),
|
|
408
|
+
prize: asWidgetPrize(obj.prize),
|
|
409
|
+
alreadyPlayed: obj.alreadyPlayed === true,
|
|
410
|
+
dispatched: obj.dispatched === true,
|
|
411
|
+
dispatchError: typeof obj.dispatchError === "string" ? obj.dispatchError : void 0,
|
|
412
|
+
widgetType: typeof obj.widgetType === "string" ? obj.widgetType : void 0,
|
|
413
|
+
receivedAt: Date.now()
|
|
414
|
+
};
|
|
415
|
+
}
|
|
324
416
|
/**
|
|
325
417
|
* Unified event batch (max 100/request per the backend) — `POST /api/events/v1`.
|
|
326
418
|
* Records analytics for every event and matches/advances a journey for any
|
|
@@ -518,6 +610,34 @@ function extractContentSwaps(body) {
|
|
|
518
610
|
return Array.isArray(swaps) ? swaps : void 0;
|
|
519
611
|
}
|
|
520
612
|
|
|
613
|
+
// src/core/request-context.ts
|
|
614
|
+
function contextFromUrl(url, referrer) {
|
|
615
|
+
const ctx = {};
|
|
616
|
+
if (referrer) ctx.referrer = referrer;
|
|
617
|
+
if (!url) return ctx;
|
|
618
|
+
let parsed;
|
|
619
|
+
try {
|
|
620
|
+
parsed = new URL(url);
|
|
621
|
+
} catch {
|
|
622
|
+
return ctx;
|
|
623
|
+
}
|
|
624
|
+
ctx.url = parsed.href;
|
|
625
|
+
ctx.path = parsed.pathname;
|
|
626
|
+
ctx.query = Object.fromEntries(parsed.searchParams);
|
|
627
|
+
const utm = (name) => parsed.searchParams.get(name) || void 0;
|
|
628
|
+
const utmSource = utm("utm_source");
|
|
629
|
+
const utmMedium = utm("utm_medium");
|
|
630
|
+
const utmCampaign = utm("utm_campaign");
|
|
631
|
+
const utmContent = utm("utm_content");
|
|
632
|
+
const utmId = utm("utm_id");
|
|
633
|
+
if (utmSource) ctx.utmSource = utmSource;
|
|
634
|
+
if (utmMedium) ctx.utmMedium = utmMedium;
|
|
635
|
+
if (utmCampaign) ctx.utmCampaign = utmCampaign;
|
|
636
|
+
if (utmContent) ctx.utmContent = utmContent;
|
|
637
|
+
if (utmId) ctx.utmId = utmId;
|
|
638
|
+
return ctx;
|
|
639
|
+
}
|
|
640
|
+
|
|
521
641
|
// src/core/response-store.ts
|
|
522
642
|
var MemoryResponseStore = class {
|
|
523
643
|
map = /* @__PURE__ */ new Map();
|
|
@@ -582,7 +702,9 @@ exports.MemoryResponseStore = MemoryResponseStore;
|
|
|
582
702
|
exports.VISITOR_COOKIE = VISITOR_COOKIE;
|
|
583
703
|
exports.XeniaApi = XeniaApi;
|
|
584
704
|
exports.buildUrl = buildUrl;
|
|
705
|
+
exports.compact = compact;
|
|
585
706
|
exports.consentCookieName = consentCookieName;
|
|
707
|
+
exports.contextFromUrl = contextFromUrl;
|
|
586
708
|
exports.extractContentSwaps = extractContentSwaps;
|
|
587
709
|
exports.generateUlid = generateUlid;
|
|
588
710
|
exports.isBrowser = isBrowser;
|
|
@@ -590,5 +712,5 @@ exports.parseActions = parseActions;
|
|
|
590
712
|
exports.spliceSlots = spliceSlots;
|
|
591
713
|
exports.toEventId = toEventId;
|
|
592
714
|
exports.visitorCookieName = visitorCookieName;
|
|
593
|
-
//# sourceMappingURL=chunk-
|
|
594
|
-
//# sourceMappingURL=chunk-
|
|
715
|
+
//# sourceMappingURL=chunk-WYM4CQVG.cjs.map
|
|
716
|
+
//# sourceMappingURL=chunk-WYM4CQVG.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/actions.ts","../src/core/http-client.ts","../src/core/token-provider.ts","../src/core/api.ts","../src/core/id.ts","../src/core/cookie-names.ts","../src/core/content-splice.ts","../src/core/request-context.ts","../src/core/response-store.ts"],"names":[],"mappings":";;;AAWA,IAAM,aAAA,uBAAyC,GAAA,CAAsB;AAAA,EACnE,QAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAC,CAAA;AAED,IAAM,iBAAA,uBAA6C,GAAA,CAAqB;AAAA,EACtE,UAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,cAAA;AAAA,EACA,KAAA;AAAA,EACA;AACF,CAAC,CAAA;AAMD,IAAM,+BAAoC,IAAI,GAAA,CAAgB,CAAC,UAAA,EAAY,YAAY,CAAC,CAAA;AAExF,IAAM,SAAA,uBAAqC,GAAA,CAAY;AAAA,EACrD,MAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,YAAA;AAAA,EACA,UAAA;AAAA,EACA,GAAG;AACL,CAAC,CAAA;AAGD,SAAS,SAAS,CAAA,EAA2D;AAC3E,EAAA,OAAO,OAAO,MAAM,QAAA,IAAY,CAAA,KAAM,QAAQ,CAAC,KAAA,CAAM,QAAQ,CAAC,CAAA;AAChE;AAEA,SAAS,SAAS,CAAA,EAA8C;AAC9D,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AACrC;AAEA,SAAS,SAAS,CAAA,EAA8C;AAC9D,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AACrC;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\n JsonValue,\n MessagePlacement,\n MessagePosition,\n WidgetFormSubmit,\n WidgetSegment,\n WidgetStyle,\n WidgetType,\n XeniaAction,\n} from \"./types\";\n\nconst MESSAGE_TYPES: ReadonlySet<string> = new Set<MessagePlacement>([\n \"banner\",\n \"popup\",\n \"modal\",\n \"inline\",\n]);\n\nconst MESSAGE_POSITIONS: ReadonlySet<string> = new Set<MessagePosition>([\n \"top-left\",\n \"top-right\",\n \"bottom-left\",\n \"bottom-right\",\n \"top\",\n \"bottom\",\n]);\n\n// NOTE: `widgetType` is deliberately NOT added to `ALL_TYPES`/`MESSAGE_TYPES` below — it is an\n// orthogonal field on message-placement actions, not a new `type` value. Keeping `type`'s\n// allowlist untouched is exactly what keeps the PHP SDK's `XeniaActions::KNOWN_TYPES` (same value\n// set) valid with zero PHP changes.\nconst WIDGET_TYPES: ReadonlySet<string> = new Set<WidgetType>([\"standard\", \"spin-wheel\"]);\n\nconst ALL_TYPES: ReadonlySet<string> = new Set<string>([\n \"swap\",\n \"hide\",\n \"show\",\n \"setContent\",\n \"redirect\",\n ...MESSAGE_TYPES,\n]);\n\n/** Type guard for a plain JSON object. */\nfunction isObject(v: JsonValue | undefined): v is { [k: string]: JsonValue } {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction asString(v: JsonValue | undefined): string | undefined {\n return typeof v === \"string\" ? v : undefined;\n}\n\nfunction asNumber(v: JsonValue | undefined): number | undefined {\n return typeof v === \"number\" ? v : undefined;\n}\n\n/**\n * Validate and narrow a single raw entry into a {@link XeniaAction}.\n * Returns null for anything malformed so a bad entry can't crash the renderer.\n */\nfunction toAction(raw: JsonValue): XeniaAction | null {\n if (!isObject(raw)) return null;\n const type = asString(raw.type);\n if (!type || !ALL_TYPES.has(type)) return null;\n\n if (type === \"redirect\") {\n const url = asString(raw.url);\n return url ? { type, url } : null;\n }\n\n if (type === \"hide\" || type === \"show\") {\n const target = asString(raw.target);\n return target ? { type, target } : null;\n }\n\n if (type === \"swap\" || type === \"setContent\") {\n const target = asString(raw.target);\n if (!target) return null;\n return { type, target, html: asString(raw.html), text: asString(raw.text) };\n }\n\n // Message placement actions (banner/popup/modal/inline).\n const cta = isObject(raw.cta)\n ? {\n label: asString(raw.cta.label) ?? \"\",\n url: asString(raw.cta.url),\n event: asString(raw.cta.event),\n }\n : undefined;\n\n return {\n type: type as MessagePlacement,\n target: asString(raw.target),\n title: asString(raw.title),\n message: asString(raw.message),\n imageUrl: asString(raw.imageUrl),\n html: asString(raw.html),\n // A link-only CTA (empty label, e.g. a spin-wheel's data-xenia-wheel-cta —\n // label is meaningless there, the winHtml/lossHtml design supplies its own button text)\n // must still parse through — gating on `cta.label` alone silently dropped it.\n cta: cta && (cta.label || cta.url) ? cta : undefined,\n dismissAfterMs: asNumber(raw.dismissAfterMs),\n position: asMessagePosition(raw.position),\n widgetType: asWidgetType(raw.widgetType),\n segments: asSegments(raw.segments),\n formSubmit: asFormSubmit(raw.formSubmit),\n style: asWidgetStyle(raw.style),\n spinnerHtml: asString(raw.spinnerHtml),\n winHtml: asString(raw.winHtml),\n lossHtml: asString(raw.lossHtml),\n };\n}\n\nfunction asMessagePosition(v: JsonValue | undefined): MessagePosition | undefined {\n const s = asString(v);\n return s && MESSAGE_POSITIONS.has(s) ? (s as MessagePosition) : undefined;\n}\n\nfunction asWidgetType(v: JsonValue | undefined): WidgetType | undefined {\n const s = asString(v);\n return s && WIDGET_TYPES.has(s) ? (s as WidgetType) : undefined;\n}\n\n/** Narrow a raw `segments` array to label/color/isLoss-only entries — drops anything malformed. */\nfunction asSegments(v: JsonValue | undefined): WidgetSegment[] | undefined {\n if (!Array.isArray(v)) return undefined;\n const segments: WidgetSegment[] = [];\n for (const entry of v) {\n if (!isObject(entry)) continue;\n const id = asString(entry.id);\n const label = asString(entry.label);\n if (!id || !label) continue;\n segments.push({\n id,\n label,\n colorHex: asString(entry.colorHex),\n isLoss: entry.isLoss === true,\n });\n }\n return segments.length ? segments : undefined;\n}\n\n/**\n * Narrow a raw `formSubmit` envelope. Defensive by design (same as the rest of this\n * module) — a malformed envelope (missing `mode`) is dropped entirely rather than\n * passed through half-formed, since the SDK's endpoint-selection logic depends on it.\n */\nfunction asFormSubmit(v: JsonValue | undefined): WidgetFormSubmit | undefined {\n if (!isObject(v)) return undefined;\n const mode = asString(v.mode);\n if (!mode) return undefined;\n return {\n requiresResolve: v.requiresResolve === true,\n mode,\n flowRef: asString(v.flowRef),\n bindingRef: asString(v.bindingRef),\n successDisplayMs: asNumber(v.successDisplayMs),\n };\n}\n\n/**\n * Narrow a raw `style` override. Every field is independently optional/defensive (same\n * philosophy as the rest of this module) — a malformed value for one field just drops that\n * field, it never discards the whole `style` object.\n */\nfunction asWidgetStyle(v: JsonValue | undefined): WidgetStyle | undefined {\n if (!isObject(v)) return undefined;\n const style: WidgetStyle = {\n hideCloseButton: v.hideCloseButton === true,\n hideOverlay: v.hideOverlay === true,\n };\n const hasAny = style.hideCloseButton || style.hideOverlay;\n return hasAny ? style : undefined;\n}\n\n/**\n * Parse render actions out of a webhook-response body.\n *\n * The convention: marketers return `{ \"xeniaActions\": [ ... ] }` (or a bare\n * array) from the `webhook-response` node. Any body without a recognizable\n * `xeniaActions` array yields an empty list — a safe no-op.\n */\nexport function parseActions(body: JsonValue): XeniaAction[] {\n let list: JsonValue | undefined;\n if (Array.isArray(body)) {\n list = body;\n } else if (isObject(body) && Array.isArray(body.xeniaActions)) {\n list = body.xeniaActions;\n }\n if (!Array.isArray(list)) return [];\n\n const actions: XeniaAction[] = [];\n for (const entry of list) {\n const action = toAction(entry);\n if (action) actions.push(action);\n }\n return actions;\n}\n","import type { HttpMethod, JsonValue, RetryConfig } from \"./types\";\n\n/**\n * Default Xenia backend base URL, used whenever `baseUrl` is omitted from\n * config. Points at the hosted engine — override only for a self-hosted or\n * non-default environment.\n */\nexport const DEFAULT_BASE_URL = \"https://engine.xeniamartech.com/xenia\";\n\n/** Returns true when running in a browser environment (SSR-safe). */\nexport function isBrowser(): boolean {\n return typeof window !== \"undefined\" && typeof document !== \"undefined\";\n}\n\n/** Appends query parameters to a URL. Returns the URL unchanged when empty. */\nexport function buildUrl(url: string, queryParams?: Record<string, string>): string {\n if (!queryParams || Object.keys(queryParams).length === 0) return url;\n const params = new URLSearchParams(queryParams);\n const sep = url.includes(\"?\") ? \"&\" : \"?\";\n return `${url}${sep}${params.toString()}`;\n}\n\n/** Sleep helper used by the retry backoff. */\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Options for a single request. */\nexport interface RequestOptions {\n method?: HttpMethod;\n /** Path appended to `baseUrl` (should start with `/`). */\n path: string;\n headers?: Record<string, string>;\n query?: Record<string, string>;\n body?: JsonValue;\n /** Per-request timeout override in ms. */\n timeout?: number;\n /** Disable retry for this request (e.g. long-polling webhook). */\n noRetry?: boolean;\n /** Per-request retry override. */\n retry?: RetryConfig;\n /**\n * Keep the request alive past page unload (`fetch`'s `keepalive` flag).\n * Used for best-effort flushes on `pagehide`, where `sendBeacon` can't be\n * used instead because it doesn't support custom headers (tenant scope).\n */\n keepalive?: boolean;\n}\n\n/** Result of a request: the raw Response plus the parsed JSON (or null). */\nexport interface HttpResult {\n response: Response;\n data: JsonValue;\n}\n\n/** Error thrown for non-2xx responses (after retries are exhausted). */\nexport class HttpError extends Error {\n constructor(\n public readonly status: number,\n public readonly data: JsonValue,\n message?: string,\n ) {\n super(message ?? `Request failed with status ${status}`);\n this.name = \"HttpError\";\n }\n}\n\nexport interface HttpClientOptions {\n /** Defaults to {@link DEFAULT_BASE_URL} when omitted. */\n baseUrl?: string;\n defaultHeaders?: Record<string, string>;\n timeout?: number;\n retry?: RetryConfig;\n debug?: boolean;\n}\n\n/**\n * Minimal fetch wrapper shared by all runtimes.\n *\n * - Injects default headers (tenant scope, content-type).\n * - Applies an `AbortController` timeout.\n * - Retries transient failures (network error, `429`, `5xx`) with exponential\n * backoff, honoring a `Retry-After` header when present.\n * - Parses JSON, falling back to `null` on empty/invalid bodies.\n */\nexport class HttpClient {\n private readonly baseUrl: string;\n private readonly defaultHeaders: Record<string, string>;\n private readonly timeout: number;\n private readonly retry: Required<RetryConfig>;\n private readonly debug: boolean;\n\n constructor(opts: HttpClientOptions) {\n this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.defaultHeaders = opts.defaultHeaders ?? {};\n this.timeout = opts.timeout ?? 8000;\n this.retry = {\n attempts: opts.retry?.attempts ?? 2,\n baseDelayMs: opts.retry?.baseDelayMs ?? 300,\n };\n this.debug = opts.debug ?? false;\n }\n\n async request(opts: RequestOptions): Promise<HttpResult> {\n const url = buildUrl(this.baseUrl + opts.path, opts.query);\n const method = opts.method ?? \"GET\";\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...this.defaultHeaders,\n ...opts.headers,\n };\n const body = opts.body !== undefined ? JSON.stringify(opts.body) : undefined;\n const timeout = opts.timeout ?? this.timeout;\n const maxAttempts = opts.noRetry ? 1 : (opts.retry?.attempts ?? this.retry.attempts) + 1;\n const baseDelay = opts.retry?.baseDelayMs ?? this.retry.baseDelayMs;\n\n let lastError: unknown;\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n try {\n const response = await this.fetchWithTimeout(\n url,\n { method, headers, body, ...(opts.keepalive ? { keepalive: true } : {}) },\n timeout,\n );\n const data = await this.parseBody(response);\n\n if (response.ok) {\n return { response, data };\n }\n\n // Retry on 429/5xx if attempts remain; otherwise throw.\n if (this.isRetryableStatus(response.status) && attempt < maxAttempts - 1) {\n const wait = this.retryAfterMs(response, baseDelay, attempt);\n this.log(`retrying ${opts.path} after ${wait}ms (status ${response.status})`);\n await delay(wait);\n continue;\n }\n throw new HttpError(response.status, data);\n } catch (err) {\n lastError = err;\n // Non-retryable HttpError → rethrow immediately.\n if (err instanceof HttpError) throw err;\n // Network/timeout error → retry if attempts remain.\n if (attempt < maxAttempts - 1) {\n const wait = baseDelay * 2 ** attempt;\n this.log(`retrying ${opts.path} after ${wait}ms (network error)`);\n await delay(wait);\n continue;\n }\n }\n }\n throw lastError instanceof Error ? lastError : new Error(\"Request failed\");\n }\n\n private async fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeout: number,\n ): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new Error(`Request timeout after ${timeout}ms`, { cause: err });\n }\n throw err;\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async parseBody(response: Response): Promise<JsonValue> {\n const text = await response.text().catch(() => \"\");\n if (!text) return null;\n try {\n return JSON.parse(text) as JsonValue;\n } catch {\n return text;\n }\n }\n\n private isRetryableStatus(status: number): boolean {\n return status === 429 || (status >= 500 && status <= 599);\n }\n\n private retryAfterMs(response: Response, baseDelay: number, attempt: number): number {\n const header = response.headers.get(\"Retry-After\");\n if (header) {\n const seconds = Number(header);\n if (!Number.isNaN(seconds)) return seconds * 1000;\n }\n return baseDelay * 2 ** attempt;\n }\n\n private log(msg: string): void {\n if (this.debug) console.warn(`[xenia] ${msg}`);\n }\n}\n","import type { XeniaConfig } from \"./types\";\n\ninterface Cached {\n token: string;\n /** Epoch ms when the token should be considered stale. */\n expiresAt: number;\n}\n\n/** JWT `exp` (seconds) if decodable, else undefined. Best-effort, no verify. */\nfunction decodeExp(token: string): number | undefined {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return undefined;\n const json = JSON.parse(atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\")));\n return typeof json.exp === \"number\" ? json.exp * 1000 : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolves the Bearer token `XeniaApi` attaches to every request, caching a\n * short-lived token from `config.getToken` until ~30s before expiry. A static\n * `config.token` is returned as-is. Isomorphic (browser + Node ≥18, both have\n * global `atob`).\n */\nexport class TokenProvider {\n private readonly config: XeniaConfig;\n private cached: Cached | null = null;\n private inflight: Promise<string> | null = null;\n\n constructor(config: XeniaConfig) {\n this.config = config;\n }\n\n /** Whether a token source is configured at all — lets callers skip resolution entirely. */\n hasSource(): boolean {\n return Boolean(this.config.token || this.config.getToken);\n }\n\n readonly getToken = async (): Promise<string> => {\n if (this.config.token && !this.config.getToken) return this.config.token;\n\n const now = Date.now();\n if (this.cached && this.cached.expiresAt > now) return this.cached.token;\n if (this.inflight) return this.inflight;\n\n if (!this.config.getToken) {\n throw new Error(\"No token source: set config.token or config.getToken.\");\n }\n\n this.inflight = Promise.resolve(this.config.getToken())\n .then((token) => {\n const exp = decodeExp(token);\n // Refresh 30s before real expiry; default 5 min if the token is opaque.\n const expiresAt = exp ? exp - 30_000 : now + 5 * 60_000;\n this.cached = { token, expiresAt };\n return token;\n })\n .finally(() => {\n this.inflight = null;\n });\n\n return this.inflight;\n };\n}\n","import { parseActions } from \"./actions\";\nimport { HttpClient } from \"./http-client\";\nimport { TokenProvider } from \"./token-provider\";\nimport type {\n AnalyticsIngestResponse,\n ConsentState,\n IdentifyRequest,\n IdentifyResponse,\n JsonObject,\n JsonValue,\n ResolveBatchItem,\n ResolveBatchResult,\n ResolveOptions,\n ResolveResult,\n WebhookResponse,\n WidgetPrize,\n WidgetSubmitResponse,\n WidgetType,\n XeniaConfig,\n XeniaEvent,\n} from \"./types\";\n\n/** Type guard for a plain JSON object (as opposed to an array/primitive/null). */\nfunction isJsonObject(v: JsonValue): v is JsonObject {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** Narrow a raw `prize` field off a `/widget-submissions` response body. */\nfunction asWidgetPrize(v: JsonValue | undefined): WidgetPrize | undefined {\n return v !== undefined && isJsonObject(v) ? (v as WidgetPrize) : undefined;\n}\n\n/** Drop `undefined` values so the JSON body stays clean. */\nexport function compact(obj: Record<string, JsonValue | undefined>): JsonObject {\n const out: JsonObject = {};\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) out[k] = v;\n }\n return out;\n}\n\n/**\n * Low-level, isomorphic Xenia API client. Wraps the raw endpoints; identity,\n * UTM capture, and action rendering are layered on top by the client runtime.\n * All paths are relative to `baseUrl`, which defaults to the hosted engine\n * (`https://engine.xeniamartech.com/xenia`) when omitted from config.\n */\nexport class XeniaApi {\n private readonly http: HttpClient;\n private readonly tenantId: string;\n private readonly environmentKey: string;\n private readonly tokenProvider: TokenProvider;\n\n constructor(config: XeniaConfig) {\n this.tenantId = config.tenantId;\n this.environmentKey = config.environmentKey;\n this.tokenProvider = new TokenProvider(config);\n this.http = new HttpClient({\n baseUrl: config.baseUrl,\n defaultHeaders: config.headers,\n timeout: config.timeout,\n retry: config.retry,\n debug: config.debug,\n });\n }\n\n /** Tenant-scope headers required by header-scoped endpoints. */\n private tenantHeaders(): Record<string, string> {\n return {\n \"X-Tenant-Id\": this.tenantId,\n \"X-Environment\": this.environmentKey,\n };\n }\n\n /**\n * Tenant headers plus a resolved `Authorization: Bearer` header when\n * `config.token`/`config.getToken` is set — e.g. required by a webhook\n * trigger node configured with its own auth token. No-op (tenant headers\n * only) when no token source is configured, so this is safe to call\n * unconditionally on every request.\n */\n private async authHeaders(): Promise<Record<string, string>> {\n const headers = this.tenantHeaders();\n if (!this.tokenProvider.hasSource()) return headers;\n const token = await this.tokenProvider.getToken();\n if (token) headers.Authorization = `Bearer ${token}`;\n return headers;\n }\n\n /**\n * Webhook request/response — `GET|POST /flow?id={triggerId}`. Held open by the\n * backend until a `webhook-response` node resolves. Returns the normalized\n * response, including any `xeniaActions` parsed from the body.\n *\n * Not retried by default: the backend long-polls this call, so a retry would\n * duplicate the journey run.\n */\n async webhook(\n triggerId: string,\n data?: JsonValue,\n method: \"GET\" | \"POST\" = \"POST\",\n ): Promise<WebhookResponse> {\n const { response, data: rawBody } = await this.http.request({\n method,\n path: \"/flow\",\n query: { id: triggerId },\n headers: await this.authHeaders(),\n body: method === \"POST\" ? (data ?? {}) : undefined,\n noRetry: true,\n });\n return {\n status: response.status,\n body: rawBody,\n actions: parseActions(rawBody),\n receivedAt: Date.now(),\n };\n }\n\n /**\n * Widget form submission — `POST /widget-submissions?ref={bindingRef}`. Used whenever the\n * action's `formSubmit.requiresResolve` is true (spin-wheel, which must have a\n * server-resolved outcome before anything renders) or `mode === \"endpoint\"` — the common\n * plain-popup case (`mode === \"journey\" && !requiresResolve`) bypasses this entirely and calls\n * {@link webhook} against `flowRef` instead (see `XeniaClient.submitWidgetForm`'s endpoint\n * selection).\n *\n * Not retried (`noRetry: true`), styled like {@link webhook} — a retried POST must never\n * double-fire a journey or double-resolve a prize server-side.\n */\n async submitWidget(ref: string, body?: JsonValue): Promise<WidgetSubmitResponse> {\n const { response, data: rawBody } = await this.http.request({\n method: \"POST\",\n path: \"/widget-submissions\",\n query: { ref },\n headers: await this.authHeaders(),\n body: body ?? {},\n noRetry: true,\n });\n const obj = isJsonObject(rawBody) ? rawBody : {};\n return {\n status: response.status,\n body: rawBody,\n actions: parseActions(rawBody),\n prize: asWidgetPrize(obj.prize),\n alreadyPlayed: obj.alreadyPlayed === true,\n dispatched: obj.dispatched === true,\n dispatchError: typeof obj.dispatchError === \"string\" ? obj.dispatchError : undefined,\n widgetType: typeof obj.widgetType === \"string\" ? (obj.widgetType as WidgetType) : undefined,\n receivedAt: Date.now(),\n };\n }\n\n /**\n * Unified event batch (max 100/request per the backend) — `POST /api/events/v1`.\n * Records analytics for every event and matches/advances a journey for any\n * event with `trigger: true`. Replaces the old `sendEvent()` (journey trigger)\n * and `sendAnalytics()` (CDP) calls.\n */\n async sendEvents(\n events: XeniaEvent[],\n opts?: { keepalive?: boolean },\n ): Promise<AnalyticsIngestResponse> {\n const { data } = await this.http.request({\n method: \"POST\",\n path: \"/api/events/v1\",\n headers: await this.authHeaders(),\n body: { events } as unknown as JsonObject,\n keepalive: opts?.keepalive,\n });\n return data as unknown as AnalyticsIngestResponse;\n }\n\n /** Bind visitor→user — `POST /api/events/v1/identify`. */\n async identify(body: IdentifyRequest): Promise<IdentifyResponse> {\n const { data } = await this.http.request({\n method: \"POST\",\n path: \"/api/events/v1/identify\",\n headers: await this.authHeaders(),\n body: body as unknown as JsonObject,\n });\n return data as unknown as IdentifyResponse;\n }\n\n /**\n * Update consent — `POST /api/events/v1/consent`.\n *\n * The three scope flags are required (non-null) by the backend, so an omitted\n * one is sent as an explicit `false` rather than left out: a partial body like\n * `consent({ analytics: true })` — the shape most callers actually write — is\n * otherwise rejected with a 400 and the consent record is never stored.\n */\n async consent(xeniaVisitorId: string, consent: ConsentState): Promise<JsonValue> {\n const { data } = await this.http.request({\n method: \"POST\",\n path: \"/api/events/v1/consent\",\n headers: await this.authHeaders(),\n body: compact({\n xeniaVisitorId,\n analytics: consent.analytics === true,\n marketing: consent.marketing === true,\n personalization: consent.personalization === true,\n consentSource: consent.consentSource,\n consentVersion: consent.consentVersion,\n }),\n });\n return data;\n }\n\n /**\n * Resolve in-entry content personalization for one content key —\n * `POST /api/personalization/resolve?merge=<bool>`. Requires the SDK Bearer\n * token (same credential as events; resolve is auth-required). `merge=true`\n * returns server-spliced `content`; otherwise splice `swaps` client-side.\n */\n async resolve(contentKey: string, opts: ResolveOptions = {}): Promise<ResolveResult> {\n const { data } = await this.http.request({\n method: \"POST\",\n path: \"/api/personalization/resolve\",\n query: opts.merge !== undefined ? { merge: String(opts.merge) } : undefined,\n headers: await this.authHeaders(),\n body: compact({\n contentKey,\n data: opts.data as JsonValue,\n locale: opts.locale,\n }),\n });\n return data as unknown as ResolveResult;\n }\n\n /**\n * Resolve several content keys in one round-trip (≤50) —\n * `POST /api/personalization/resolve-batch?merge=<bool>`. Same auth/merge\n * semantics as {@link resolve}.\n */\n async resolveBatch(\n items: ResolveBatchItem[],\n opts: ResolveOptions = {},\n ): Promise<ResolveBatchResult[]> {\n const { data } = await this.http.request({\n method: \"POST\",\n path: \"/api/personalization/resolve-batch\",\n query: opts.merge !== undefined ? { merge: String(opts.merge) } : undefined,\n headers: await this.authHeaders(),\n body: compact({\n items: items as unknown as JsonValue,\n data: opts.data as JsonValue,\n locale: opts.locale,\n }),\n });\n return data as unknown as ResolveBatchResult[];\n }\n}\n","/** Crockford base32 alphabet (no I/L/O/U, avoids visual ambiguity) — used by ULID. */\nconst ENCODING = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nfunction randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n if (typeof crypto !== \"undefined\" && crypto.getRandomValues) {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < length; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n return bytes;\n}\n\n/**\n * Generate a ULID (Universally Unique Lexicographically Sortable Identifier):\n * a 48-bit timestamp (10 Crockford-base32 chars) + 80 bits of randomness (16\n * chars), 26 chars total — matches the backend's `eventId` field (`≤26`\n * chars). No dependency; implemented inline to keep the SDK lean.\n */\nexport function generateUlid(time: number = Date.now()): string {\n let timePart = \"\";\n let t = time;\n for (let i = 9; i >= 0; i--) {\n timePart = ENCODING[t % 32] + timePart;\n t = Math.floor(t / 32);\n }\n\n const random = randomBytes(16);\n let randomPart = \"\";\n for (let i = 0; i < 16; i++) {\n randomPart += ENCODING[random[i] % 32];\n }\n\n return timePart + randomPart;\n}\n\n/** Backend cap on `eventId` (`@Size(max = 26)`), which a ULID exactly fills. */\nexport const MAX_EVENT_ID_LENGTH = 26;\n\n/**\n * Coerce a caller-supplied dedup key into something the backend will accept.\n *\n * `eventId` is capped at 26 characters server-side, and an over-length value\n * rejects the ENTIRE batch it rides in — not just its own event. That is easy to\n * hit: `\"ord-\" + <uuid>` is 40. Rather than drop the caller's idempotency key or\n * let the batch 400, fold anything longer into a deterministic 26-char digest.\n * Deterministic is the point — the same order id always yields the same event id,\n * so re-firing it still de-dupes to one conversion, which is what the key is for.\n *\n * Truncation is deliberately not used: `\"ord-<uuid>\"` values share a long common\n * prefix, so cutting to 26 chars can map two different orders onto one id.\n */\nexport function toEventId(raw: string): string {\n if (raw.length <= MAX_EVENT_ID_LENGTH) return raw;\n\n // Two independently-seeded FNV-1a passes → 128 bits, encoded Crockford base32.\n let out = \"\";\n for (const seed of [0x811c9dc5, 0x01000193]) {\n let hash = seed >>> 0;\n for (let i = 0; i < raw.length; i++) {\n hash ^= raw.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n out += ENCODING[hash % 32];\n }\n }\n // Fold the accumulated stream down to exactly the cap, order-dependently.\n let digest = \"\";\n for (let i = 0; i < MAX_EVENT_ID_LENGTH; i++) {\n let acc = i + 1;\n for (let j = i; j < out.length; j += MAX_EVENT_ID_LENGTH) {\n acc = (acc * 31 + ENCODING.indexOf(out[j])) >>> 0;\n }\n digest += ENCODING[acc % 32];\n }\n return digest;\n}\n","/**\n * Cookie names shared by the browser and server halves of the SDK.\n *\n * The visitor cookie is the one channel where two runtimes must agree on a literal string: the\n * browser writes it, a same-origin server reads it back, and that match is what lets a server-side\n * conversion attribute to a browser-entered journey. `config.prefix` namespaces it — so two Xenia\n * apps on one domain keep separate visitors — which means **both halves must derive the name the\n * same way**. Deriving it on one side and hardcoding it on the other silently breaks the link for\n * anyone using a custom prefix: the server just finds no cookie and falls back to no visitor.\n *\n * Always build the name with these helpers rather than interpolating it by hand.\n */\n\n/** Default storage/cookie prefix, matching `XeniaConfig.prefix`. */\nexport const DEFAULT_PREFIX = \"xenia\";\n\n/** Name of the first-party cookie carrying the SDK-owned visitor id, for a given prefix. */\nexport function visitorCookieName(prefix: string = DEFAULT_PREFIX): string {\n return `${prefix || DEFAULT_PREFIX}_vid`;\n}\n\n/** Name of the first-party cookie carrying consent scopes, for a given prefix. */\nexport function consentCookieName(prefix: string = DEFAULT_PREFIX): string {\n return `${prefix || DEFAULT_PREFIX}_consent`;\n}\n\n/**\n * The visitor cookie name for the DEFAULT prefix (`\"xenia_vid\"`).\n *\n * Correct for the common case, and kept so existing code (e.g. reading the cookie straight out of a\n * framework's cookie jar) keeps working. If you set `config.prefix`, use {@link visitorCookieName}\n * instead — this constant will not match what the browser wrote.\n */\nexport const VISITOR_COOKIE = visitorCookieName();\n\n/**\n * The consent cookie name for the DEFAULT prefix (`\"xenia_consent\"`). Same custom-prefix caveat as\n * {@link VISITOR_COOKIE}.\n */\nexport const CONSENT_COOKIE = consentCookieName();\n","import type { JsonValue } from \"./types\";\n\n/**\n * A single content swap, as emitted in a webhook-response body's\n * `xeniaContentSwaps` array (the multi-slot personalization analogue of\n * `xeniaActions`). `identifier` is `\"<slotKey>\"` (whole-slot replace) or\n * `\"<slotKey>.<dotted.path>\"` addressing a node inside that slot's JSON\n * (object keys or array indices).\n *\n * NOTE: this field name/shape is a proposed contract, not yet emitted by any\n * journey node — confirm with the Journey Orchestrator (FE/BE) team before\n * relying on it in production.\n */\nexport interface ContentSwap {\n identifier: string;\n replacement: JsonValue;\n /** `\"replace\"` (default) swaps the whole matched node; `\"merge\"` shallow-merges when both sides are objects. */\n mode?: \"replace\" | \"merge\";\n}\n\nfunction isPlainObject(v: JsonValue): v is { [key: string]: JsonValue } {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction cloneJson<T extends JsonValue>(value: T): T {\n return value === null || typeof value !== \"object\" ? value : (JSON.parse(JSON.stringify(value)) as T);\n}\n\nfunction setAtPath(node: JsonValue, path: string[], value: JsonValue, mode: \"replace\" | \"merge\"): JsonValue {\n if (path.length === 0) {\n if (mode === \"merge\" && isPlainObject(node) && isPlainObject(value)) {\n return { ...node, ...value };\n }\n return value;\n }\n\n const [key, ...rest] = path;\n if (Array.isArray(node)) {\n const index = Number(key);\n if (!Number.isInteger(index) || index < 0 || index >= node.length) return node;\n const next = node.slice();\n next[index] = setAtPath(next[index], rest, value, mode);\n return next;\n }\n if (isPlainObject(node)) {\n if (!(key in node)) return node;\n return { ...node, [key]: setAtPath(node[key], rest, value, mode) };\n }\n return node;\n}\n\n/**\n * Splice `swaps` into a base map of named content slots, recursively at any\n * nesting depth. Defensive by design (mirrors the PHP SDK's personalization\n * client): a swap whose `identifier` doesn't resolve to an existing slot/path\n * is silently ignored rather than thrown — this never fails, it degrades to\n * the base slot value. Slots are deep-cloned; inputs are never mutated.\n */\nexport function spliceSlots(\n slots: Record<string, JsonValue>,\n swaps: ContentSwap[] | undefined,\n): Record<string, JsonValue> {\n const result: Record<string, JsonValue> = {};\n for (const [key, value] of Object.entries(slots)) {\n result[key] = cloneJson(value);\n }\n if (!swaps) return result;\n\n for (const swap of swaps) {\n const [slotKey, ...pathParts] = swap.identifier.split(\".\");\n if (!(slotKey in result)) continue;\n result[slotKey] = setAtPath(result[slotKey], pathParts, swap.replacement, swap.mode ?? \"replace\");\n }\n return result;\n}\n\n/** Extract `xeniaContentSwaps` from a webhook-response body, if present and well-formed. */\nexport function extractContentSwaps(body: JsonValue): ContentSwap[] | undefined {\n if (!isPlainObject(body)) return undefined;\n const swaps = body.xeniaContentSwaps;\n return Array.isArray(swaps) ? (swaps as unknown as ContentSwap[]) : undefined;\n}\n","import type { EventContext } from \"./types\";\n\n/**\n * Derive the SDK-provided page/campaign fields from a URL — the server-side counterpart to the\n * browser client's `Identity.collectContext()`, which reads the same fields off `window.location`.\n *\n * Exists because a server runtime has no ambient `window`: a Node client is constructed per request,\n * so the one thing it needs handed over is the URL being served. Everything a journey rule can\n * reference — `path`, `query.<name>`, `url`, `referrer`, `utmSource`/`utmMedium`/`utmCampaign`/\n * `utmContent`/`utmId` — is derived here rather than by each app, so a server-rendered page gets the\n * same field set a browser page does without hand-rolling UTM parsing at every call site.\n *\n * Field names and semantics deliberately mirror `collectContext()` exactly: `query` is the flattened\n * search params, UTMs come from the standard `utm_*` params, and absent values are omitted rather\n * than set to `\"\"` (a blank string is a value a condition could accidentally match).\n *\n * @param url Absolute URL of the request being served (e.g. `https://shop.example/product/x?ref=a`).\n * A relative or unparseable value yields an empty context rather than throwing.\n * @param referrer Optional referring URL, typically the request's `Referer` header.\n */\nexport function contextFromUrl(url: string | null | undefined, referrer?: string | null): EventContext {\n const ctx: EventContext = {};\n if (referrer) ctx.referrer = referrer;\n if (!url) return ctx;\n\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return ctx; // not an absolute URL — nothing safely derivable\n }\n\n ctx.url = parsed.href;\n ctx.path = parsed.pathname;\n ctx.query = Object.fromEntries(parsed.searchParams);\n\n const utm = (name: string) => parsed.searchParams.get(name) || undefined;\n const utmSource = utm(\"utm_source\");\n const utmMedium = utm(\"utm_medium\");\n const utmCampaign = utm(\"utm_campaign\");\n const utmContent = utm(\"utm_content\");\n const utmId = utm(\"utm_id\");\n if (utmSource) ctx.utmSource = utmSource;\n if (utmMedium) ctx.utmMedium = utmMedium;\n if (utmCampaign) ctx.utmCampaign = utmCampaign;\n if (utmContent) ctx.utmContent = utmContent;\n if (utmId) ctx.utmId = utmId;\n\n return ctx;\n}\n","import type { WebhookResponse } from \"./types\";\n\n/**\n * Persists webhook responses the SDK receives, keyed by an arbitrary string\n * (typically the eventId, triggerId, or journeyId). Lets the app read back the\n * last server response for a given interaction without re-firing it.\n */\nexport interface ResponseStore {\n set(key: string, value: WebhookResponse): void;\n get(key: string): WebhookResponse | undefined;\n keys(): string[];\n clear(): void;\n}\n\n/** In-memory store. Default; lost on reload. */\nexport class MemoryResponseStore implements ResponseStore {\n private readonly map = new Map<string, WebhookResponse>();\n\n set(key: string, value: WebhookResponse): void {\n this.map.set(key, value);\n }\n get(key: string): WebhookResponse | undefined {\n return this.map.get(key);\n }\n keys(): string[] {\n return [...this.map.keys()];\n }\n clear(): void {\n this.map.clear();\n }\n}\n\n/**\n * localStorage-backed store — survives reloads. Falls back to memory semantics\n * (silent no-op reads/writes) when localStorage is unavailable or throws.\n */\nexport class LocalStorageResponseStore implements ResponseStore {\n private readonly nsKey: string;\n\n constructor(prefix = \"xenia\") {\n this.nsKey = `${prefix}_responses`;\n }\n\n private read(): Record<string, WebhookResponse> {\n try {\n const raw = localStorage.getItem(this.nsKey);\n return raw ? (JSON.parse(raw) as Record<string, WebhookResponse>) : {};\n } catch {\n return {};\n }\n }\n\n private write(data: Record<string, WebhookResponse>): void {\n try {\n localStorage.setItem(this.nsKey, JSON.stringify(data));\n } catch {\n /* storage full / unavailable — ignore */\n }\n }\n\n set(key: string, value: WebhookResponse): void {\n const data = this.read();\n data[key] = value;\n this.write(data);\n }\n get(key: string): WebhookResponse | undefined {\n return this.read()[key];\n }\n keys(): string[] {\n return Object.keys(this.read());\n }\n clear(): void {\n try {\n localStorage.removeItem(this.nsKey);\n } catch {\n /* ignore */\n }\n }\n}\n"]}
|