@sentientui/core 0.16.0 → 0.16.2

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 (43) hide show
  1. package/LICENSE +21 -0
  2. package/dist/{chunk-KZHVBFG7.mjs → chunk-CD2A55US.mjs} +1 -0
  3. package/dist/chunk-CD2A55US.mjs.map +1 -0
  4. package/dist/chunk-I2QGVQI6.mjs +2 -0
  5. package/dist/chunk-I2QGVQI6.mjs.map +1 -0
  6. package/dist/{chunk-P5ZTJLZE.mjs → chunk-L5TA3FAB.mjs} +2 -1
  7. package/dist/chunk-L5TA3FAB.mjs.map +1 -0
  8. package/dist/{chunk-HGGX55FR.mjs → chunk-TMCGHANO.mjs} +1 -0
  9. package/dist/chunk-TMCGHANO.mjs.map +1 -0
  10. package/dist/index-C247KMBw.d.ts +394 -0
  11. package/dist/index-CZLjrtM4.d.cts +394 -0
  12. package/dist/index-engagement.js +2 -1
  13. package/dist/index-engagement.js.map +1 -0
  14. package/dist/index-engagement.mjs +2 -1
  15. package/dist/index-engagement.mjs.map +1 -0
  16. package/dist/index-graph.d.cts +38 -3
  17. package/dist/index-graph.d.ts +38 -3
  18. package/dist/index-graph.js +2 -1
  19. package/dist/index-graph.js.map +1 -0
  20. package/dist/index-graph.mjs +2 -1
  21. package/dist/index-graph.mjs.map +1 -0
  22. package/dist/index-local-stub.js +1 -0
  23. package/dist/index-local-stub.js.map +1 -0
  24. package/dist/index-local-stub.mjs +2 -1
  25. package/dist/index-local-stub.mjs.map +1 -0
  26. package/dist/index-local.d.cts +1 -1
  27. package/dist/index-local.d.ts +1 -1
  28. package/dist/index-local.js +1 -0
  29. package/dist/index-local.js.map +1 -0
  30. package/dist/index-local.mjs +2 -1
  31. package/dist/index-local.mjs.map +1 -0
  32. package/dist/index-server.js +1 -0
  33. package/dist/index-server.js.map +1 -0
  34. package/dist/index-server.mjs +2 -1
  35. package/dist/index-server.mjs.map +1 -0
  36. package/dist/index.d.cts +2 -430
  37. package/dist/index.d.ts +2 -430
  38. package/dist/index.js +2 -1
  39. package/dist/index.js.map +1 -0
  40. package/dist/index.mjs +2 -1
  41. package/dist/index.mjs.map +1 -0
  42. package/package.json +21 -2
  43. package/dist/chunk-CWUFS37B.mjs +0 -1
package/dist/index.d.ts CHANGED
@@ -1,431 +1,3 @@
1
- import { a as SlotDeclInput } from './session-meta-DU_3mY7U.js';
2
- export { b as agentUaList, c as armOfResult, d as baselineResultFor, e as baselineSlots, g as deriveSessionSegment, h as detectDeviceClass, i as detectTimeOfDay, j as detectTrafficSource, m as matchedAgentToken, r as referrerDomainFromReferer, t as toWireSlot, u as uaTokenMatch } from './session-meta-DU_3mY7U.js';
3
- import { SlotResult } from '@sentientui/policy';
1
+ export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, d as CompoundLocator, D as DecideInput, e as DecideOutcome, f as DecisionSnapshot, g as EventType, G as GoalDefinition, i as GraphConfig, j as GraphSnapshot, L as LOCAL_MODE_BANNER, M as MicroSignalEmitter, k as MicroSignalType, P as PROD_KEYLESS_ERROR, Q as QueueConfig, S as SNAPSHOT_STORAGE_KEY_PREFIX, m as SentientClient, n as SentientConfig, o as SentientEvent, p as SessionConfig, q as SessionManager, r as SlotConfigEntry, s as SlotOps, W as WeightEntry, t as attachMicroSignalDetectors, u as grantConsent, v as init, w as isDoNotTrackEnabled, x as readSnapshot, y as renderPrePaintScript, z as writeSnapshot } from './index-C247KMBw.js';
2
+ export { a as SlotDeclInput, b as agentUaList, c as armOfResult, d as baselineResultFor, e as baselineSlots, g as deriveSessionSegment, h as detectDeviceClass, i as detectTimeOfDay, j as detectTrafficSource, m as matchedAgentToken, r as referrerDomainFromReferer, t as toWireSlot, u as uaTokenMatch } from './session-meta-DU_3mY7U.js';
4
3
  export { SlotResult } from '@sentientui/policy';
5
-
6
- /** Manages anonymous session identity with cookie + localStorage layers. */
7
- type SessionConfig = {
8
- cookieName?: string;
9
- cookieTTLDays?: number;
10
- /**
11
- * Session ID generated during SSR (e.g. from `loadAdaptiveAssignments`).
12
- * Used as the fallback when no existing cookie or localStorage entry is found,
13
- * so the client adopts the same session the server used for variant assignment
14
- * on first visit rather than generating a new, orphaned ID.
15
- */
16
- ssrSessionId?: string;
17
- };
18
- type SessionManager = {
19
- getSessionId(): string | null;
20
- /** True when neither cookie nor localStorage could be written — id is in-memory only. */
21
- isEphemeral(): boolean;
22
- destroy(): void;
23
- };
24
-
25
- /** Batched event queue with reliable transport (fetch + keepalive, localStorage retry). */
26
- type EventType = 'variant_assigned' | 'goal_achieved' | 'scroll_depth' | 'dwell' | 'cursor_signal' | 'component_visible' | 'component_exited' | 'micro_signal';
27
- type SentientEvent = {
28
- id: string;
29
- sessionId: string;
30
- projectId: string;
31
- componentId: string;
32
- variantId?: string;
33
- eventType: EventType;
34
- goalType?: string;
35
- payload: Record<string, unknown>;
36
- timestamp: number;
37
- timeInSession: number;
38
- };
39
- type QueueConfig = {
40
- ingestUrl: string;
41
- apiKey: string;
42
- flushIntervalMs?: number;
43
- maxBatchSize?: number;
44
- maxRetrySize?: number;
45
- };
46
- type EventQueue = {
47
- push(event: SentientEvent): void;
48
- flush(): void;
49
- destroy(): void;
50
- };
51
-
52
- /** Synchronous variant assignment cache (memory + localStorage). */
53
- type Assignment = {
54
- variantId: string;
55
- assignedAt: number;
56
- segment: string;
57
- confidence: number;
58
- content?: string;
59
- };
60
- type AssignmentCache = {
61
- get(componentId: string, segment: string): Assignment | null;
62
- set(componentId: string, segment: string, assignment: Assignment): void;
63
- invalidate(componentId: string): void;
64
- clear(): void;
65
- };
66
-
67
- /** Reads the rendered DOM to build the page-side context graph. */
68
- type ScannedNode = {
69
- componentId: string;
70
- semanticType: string;
71
- ariaLabel?: string;
72
- headingText?: string;
73
- isAboveFold: boolean;
74
- prominenceScore: number;
75
- depth: number;
76
- reactComponentName?: string;
77
- dataAttributes: Record<string, string>;
78
- };
79
- type StructuralEdge$1 = {
80
- fromComponentId: string;
81
- toComponentId: string;
82
- /** 0.6 for direct parent → child, 0.3 for sibling (both directions emitted). */
83
- weight: number;
84
- };
85
- type ScanResult = {
86
- nodes: ScannedNode[];
87
- edges: StructuralEdge$1[];
88
- scannedAt: number;
89
- };
90
- type ContentAddedEvent = {
91
- nodes: ScannedNode[];
92
- edges: StructuralEdge$1[];
93
- addedAt: number;
94
- };
95
- type DOMScanner = {
96
- scan(): Promise<ScanResult>;
97
- observe(onContentAdded: (event: ContentAddedEvent) => void): void;
98
- getProminenceScore(element: Element): number;
99
- destroy(): void;
100
- };
101
-
102
- /** In-memory context graph with persistence and backend sync. */
103
- type PageNode = {
104
- id: string;
105
- componentId: string;
106
- semanticType: string;
107
- answers: string[];
108
- prominenceScore: number;
109
- depth: number;
110
- };
111
- type GraphSnapshot = {
112
- pageNodes: PageNode[];
113
- capturedAt: number;
114
- };
115
- type GraphConfig = {
116
- syncUrl?: string;
117
- apiKey?: string;
118
- projectId?: string;
119
- sessionId?: string;
120
- };
121
- type StructuralEdge = {
122
- fromComponentId: string;
123
- toComponentId: string;
124
- weight: number;
125
- };
126
- type GraphClient = {
127
- addPageNode(node: PageNode): void;
128
- /** Record a DOM-derived parent/child or sibling relationship between two components. */
129
- addStructuralEdge(edge: StructuralEdge): void;
130
- /** One-shot batch sync of all current page nodes to the backend. */
131
- syncOnce(): void;
132
- snapshot(): GraphSnapshot;
133
- serialize(): string;
134
- restore(data: string): void;
135
- destroy(): void;
136
- };
137
-
138
- /**
139
- * Decision snapshot: the SPA / return-visit pre-paint source. Written after
140
- * every successful decide; read by the inline pre-paint script (before any
141
- * framework code runs) and by init() to seed slot/persona state.
142
- */
143
-
144
- declare const SNAPSHOT_STORAGE_KEY_PREFIX = "_snt_snap:";
145
- /** Versioned compound locator: resolve id → dataAttr → selector, then verify
146
- * against fingerprint. Lets a slot survive DOM/markup drift. */
147
- type CompoundLocator = {
148
- v?: number;
149
- id?: string;
150
- dataAttr?: {
151
- name: string;
152
- value: string;
153
- };
154
- selector?: string;
155
- urlMatch?: string;
156
- fingerprint?: {
157
- tag?: string;
158
- text?: string;
159
- };
160
- semanticId?: string;
161
- };
162
- /** Bounded, declarative operations a registry arm may apply to its element.
163
- * The style set is a fixed whitelist (validated server-side); no arbitrary CSS,
164
- * HTML, or JS ever. `text` is applied via textContent; https-only URLs.
165
- * moveBefore/moveAfter (exactly one) reposition the element relative to a
166
- * uniquely-resolving sibling anchor — post-decide only, never pre-paint. */
167
- type SlotOps = {
168
- text?: string;
169
- style?: Record<string, string>;
170
- hidden?: boolean;
171
- href?: string;
172
- imageSrc?: string;
173
- imageAlt?: string;
174
- moveBefore?: CompoundLocator;
175
- moveAfter?: CompoundLocator;
176
- };
177
- /** Registry-mode apply info per slot: where to apply and what to set. Stored so
178
- * a returning visitor's pre-paint can reapply it. `target` is the Phase-2 bare
179
- * selector; `locator` (Phase 3) is the compound locator, preferred when present. */
180
- type SlotConfigEntry = {
181
- kind: 'tokens' | 'arms';
182
- target?: string;
183
- locator?: CompoundLocator;
184
- content?: string;
185
- ops?: SlotOps;
186
- };
187
- type DecisionSnapshot = {
188
- v: 1;
189
- persona: string;
190
- band: 'low' | 'medium' | 'high';
191
- slots: Record<string, SlotResult>;
192
- layoutOrder: string[] | null;
193
- savedAt: number;
194
- slotConfig?: Record<string, SlotConfigEntry>;
195
- };
196
- /** Returns null on missing, corrupt, or wrong-version data — never throws. */
197
- declare function readSnapshot(apiKey: string): DecisionSnapshot | null;
198
- /** Best-effort persist — storage failures are swallowed. */
199
- declare function writeSnapshot(apiKey: string, snap: DecisionSnapshot): void;
200
- /**
201
- * Inline pre-paint script (Rung 1a): reads the snapshot and sets
202
- * `data-sentient-persona` / `data-sentient-confidence` on <html> before
203
- * first paint. Single-writer: it never overwrites attributes already set.
204
- *
205
- * Safety properties (pinned by tests):
206
- * - apiKey goes through JSON.stringify, then '<' is escaped to <, so a
207
- * hostile key can neither break the JS string nor terminate the <script>.
208
- * - Built by string concatenation and contains no backticks, so the output
209
- * survives being embedded in template-literal-based renderers.
210
- */
211
- declare function renderPrePaintScript(apiKey: string): string;
212
-
213
- declare const PROD_KEYLESS_ERROR = "[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.";
214
- declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.";
215
-
216
- type MicroSignalEmitter = (signalType: 'rage_click' | 'text_copy' | 'scroll_hesitation' | 'tab_loss', extra?: Record<string, unknown>) => void;
217
- type MicroSignalType = Parameters<MicroSignalEmitter>[0];
218
- /**
219
- * Attaches passive behavioral detectors to `node`. Calls `emit` when a signal
220
- * fires. Each signal type fires at most once per call to this function.
221
- * Returns a cleanup function that removes all listeners.
222
- */
223
- declare function attachMicroSignalDetectors(emit: MicroSignalEmitter, node: Element, variantAssignedAt?: number): () => void;
224
-
225
- type SentientConfig = {
226
- apiKey: string;
227
- context: 'landing' | 'ecommerce' | 'saas' | 'marketplace';
228
- /** @internal — not exposed to users; defaults to the hosted SentientUI API. */
229
- ingestUrl?: string;
230
- debug?: boolean;
231
- /**
232
- * Pre-seeded assignments from `preloadAssignments()` (SSR).
233
- * Seeds the local cache so `assign()` returns without a network call for
234
- * listed code variants, guaranteeing server and client render the same
235
- * variant on first paint. Managed-text components (assign with no
236
- * variantIds) still fetch once when the seed carries no content.
237
- */
238
- initialAssignments?: Record<string, string>;
239
- /**
240
- * Segment used for SSR preload (`device:source`). When set with `initialAssignments`,
241
- * seeds the assignment cache under this key so hydration matches the server bandit row.
242
- */
243
- sessionSegment?: string;
244
- /**
245
- * Consent gate. When `false`, returns a no-op client and performs no tracking.
246
- * Defaults to `true`. Re-call `init()` (via `AdaptiveProvider` consent prop) when
247
- * the user grants or revokes consent mid-session.
248
- */
249
- consent?: boolean;
250
- /**
251
- * Behavior before consent is granted. `'statistical_winner'` fetches the
252
- * best-performing variant via `GET /v1/winner` — no session or tracking data
253
- * is stored. `'control'` (default) shows `variantIds[0]` with no API call.
254
- * Applies when tracking is gated off — either `consent: false` or an active
255
- * Do Not Track signal.
256
- */
257
- preConsentBehavior?: 'statistical_winner' | 'control';
258
- /**
259
- * Whether to honor the browser's Do Not Track (DNT) signal. Defaults to `true`.
260
- * When `true` and the visitor has DNT enabled, the SDK sets no cookies and
261
- * sends no tracking data — behaving exactly as `consent: false` (still serving
262
- * the read-only `preConsentBehavior` winner if configured), and `grantConsent()`
263
- * will not upgrade it. Set `false` to make your own consent gate authoritative.
264
- */
265
- respectDoNotTrack?: boolean;
266
- userId?: string;
267
- /**
268
- * Session ID generated server-side (from `loadAdaptiveAssignments` / `loadAdaptiveDecision`).
269
- * When provided, the client adopts this ID on first visit instead of generating a new one,
270
- * ensuring events and goals are attributed to the same session the server used for assignment.
271
- */
272
- ssrSessionId?: string;
273
- /**
274
- * ISO 3166-1 alpha-2 country code for the visitor. When provided (e.g. from
275
- * the `CF-IPCountry` header in a Next.js server component), it is included in
276
- * the session upsert so country-based segmentation works without client-side
277
- * geo lookup.
278
- */
279
- country?: string;
280
- /**
281
- * Pre-seeded slot results from `preloadDecisions()` / `loadAdaptiveDecision()`
282
- * (SSR). Seeds the local slot state so `getSlotResult()` agrees with the
283
- * server-rendered markup on first paint.
284
- */
285
- initialSlots?: Record<string, SlotResult>;
286
- /**
287
- * Persona decided during SSR. Takes priority over the html-attribute
288
- * adoption and the local snapshot.
289
- */
290
- initialPersona?: {
291
- persona: string;
292
- confidence: number;
293
- };
294
- /**
295
- * Keyless local mode. 'auto' (default) simulates decisions on-device when no
296
- * valid API key is configured — but only in development builds (the
297
- * `development` export condition); production bundles physically exclude the
298
- * engine. `true` forces the local engine regardless of key (escape hatch);
299
- * `false` restores the silent keyless no-op.
300
- */
301
- localMode?: 'auto' | boolean;
302
- };
303
- type AssignResult = {
304
- variantId: string;
305
- assignmentTtlMs: number;
306
- content?: string;
307
- };
308
-
309
- /** An editor-defined goal delivered with a registry-mode decision, for the
310
- * snippet to install delegated listeners from. */
311
- type GoalDefinition = {
312
- goalId: string;
313
- event: 'click' | 'form_submit' | 'url_reached';
314
- locator?: CompoundLocator;
315
- urlPattern?: string;
316
- slotId?: string;
317
- };
318
- type DecideOutcome = {
319
- layoutOrder: string[] | null;
320
- assignments: Record<string, string>;
321
- slots: Record<string, SlotResult>;
322
- persona: string;
323
- confidence: number;
324
- slotConfig?: Record<string, SlotConfigEntry>;
325
- goals?: GoalDefinition[];
326
- };
327
- type DecideInput = {
328
- sections?: string[];
329
- components?: Array<{
330
- id: string;
331
- variantIds?: string[];
332
- }>;
333
- slots?: SlotDeclInput[];
334
- slotsFrom?: 'request' | 'registry';
335
- /**
336
- * Caller's build version (e.g. the snippet's `__SNIPPET_VERSION__`), sent
337
- * as `v` on the wire. Additive/best-effort: the server persists it for
338
- * version-skew reporting (see apps/api decide route) and ignores it
339
- * entirely on older deployments. Omit if the caller has no version to report.
340
- */
341
- v?: string;
342
- };
343
- type WeightEntry = {
344
- variantId: string;
345
- pulls: number;
346
- avgReward: number | null;
347
- };
348
- type ComponentWeightEntry = {
349
- componentId: string;
350
- updatedAt: number;
351
- variants: WeightEntry[];
352
- };
353
- type ComponentGoalOptions = {
354
- /** Reward credited to the served variant (0–1). Defaults to 1. */
355
- reward?: number;
356
- /** Extra fields merged into the event payload. */
357
- metadata?: Record<string, unknown>;
358
- };
359
- type SentientClient = {
360
- track(event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>): void;
361
- goal(name: string, metadata?: Record<string, unknown>, weight?: number, stepIndex?: number): void;
362
- /**
363
- * Records a conversion attributed to the variant currently served for
364
- * `componentId`, so it feeds the per-variant CVR funnel. Resolves the served
365
- * variant from the local assignment cache — no need to pass variantId or
366
- * projectId. No-ops if the component has not been assigned yet (render its
367
- * `<Adaptive>`/call `assign()` first). Prefer this over bare `goal()` for
368
- * variant experiments; `goal()` is session-level only (no component attribution).
369
- */
370
- componentGoal(componentId: string, goalType: string, opts?: ComponentGoalOptions): void;
371
- identify(userId: string): void;
372
- getAssignment(componentId: string, segment: string): Assignment | null;
373
- /** Server-side variant assignment. Caches the result locally per (component, segment). */
374
- assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;
375
- /**
376
- * Single-roundtrip decision for layout sections, component variants, and
377
- * adaptive slots. Awaits the session upsert (like `assign`) so the server
378
- * never decides for a session row that doesn't exist yet. A response
379
- * without a `slots` field means the server predates slots — every declared
380
- * slot resolves to its baseline and no retry is made.
381
- */
382
- decide(input: DecideInput): Promise<DecideOutcome | null>;
383
- /** Slot result served this session (decide result, SSR seed, snapshot, or failure baseline). Null when unknown. */
384
- getSlotResult(slotId: string): SlotResult | null;
385
- /** Current persona estimate. Band is always `confidenceBand(confidence)`. Null when nothing is known yet. */
386
- getPersona(): {
387
- persona: string;
388
- confidence: number;
389
- band: 'low' | 'medium' | 'high';
390
- } | null;
391
- /** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */
392
- fetchWeights(): Promise<ComponentWeightEntry[]>;
393
- getGraph(): GraphSnapshot;
394
- /**
395
- * Routine teardown: stops timers/listeners and flushes pending events, but
396
- * KEEPS the visitor identity, decision snapshot, and retry bucket. Use for
397
- * component unmount / re-init (framework providers call this on cleanup).
398
- */
399
- dispose(): void;
400
- /**
401
- * Consent-revocation / forget-me teardown: everything `dispose()` does,
402
- * plus deletion of the visitor identity (`_snt_uid`), the decision
403
- * snapshot, and the persisted retry bucket. The next visit starts as a
404
- * brand-new visitor.
405
- */
406
- destroy(): void;
407
- /** True when this client is the keyless local-mode client (dev only). */
408
- readonly isLocal?: boolean;
409
- };
410
-
411
- /**
412
- * Detects whether the visitor has signalled a tracking opt-out. Honors Global
413
- * Privacy Control (`navigator.globalPrivacyControl`) — the legally-enforceable
414
- * CCPA/CPRA signal — as well as Do Not Track (`navigator.doNotTrack`, the legacy
415
- * `window.doNotTrack` on older Firefox, and `navigator.msDoNotTrack` on old
416
- * IE/Edge). GPC is a boolean; DNT is opt-out only when explicitly `'1'`/`'yes'`.
417
- */
418
- declare function isDoNotTrackEnabled(): boolean;
419
- /**
420
- * Upgrades a pre-consent client (created with `consent: false, preConsentBehavior: 'statistical_winner'`)
421
- * to a fully-tracking client. Call this from your consent management platform callback.
422
- * For React apps, prefer updating the `consent` prop on `<AdaptiveProvider>`.
423
- * Pass `apiKey` to target a specific project; omit to upgrade the most-recently-initialized client.
424
- */
425
- declare function grantConsent(apiKey?: string): void;
426
- /**
427
- * Initializes the Sentient client. Returns a no-op client during SSR.
428
- */
429
- declare function init(config: SentientConfig): SentientClient;
430
-
431
- export { type AssignResult, type Assignment, type AssignmentCache, type ComponentGoalOptions, type ComponentWeightEntry, type CompoundLocator, type ContentAddedEvent, type DOMScanner, type DecideInput, type DecideOutcome, type DecisionSnapshot, type EventQueue, type EventType, type GoalDefinition, type GraphClient, type GraphConfig, type GraphSnapshot, LOCAL_MODE_BANNER, type MicroSignalEmitter, type MicroSignalType, PROD_KEYLESS_ERROR, type PageNode, type QueueConfig, SNAPSHOT_STORAGE_KEY_PREFIX, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type SessionConfig, type SessionManager, type SlotConfigEntry, SlotDeclInput, type SlotOps, type WeightEntry, attachMicroSignalDetectors, grantConsent, init, isDoNotTrackEnabled, readSnapshot, renderPrePaintScript, writeSnapshot };
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
- "use strict";var ze=Object.create;var oe=Object.defineProperty,He=Object.defineProperties,Ve=Object.getOwnPropertyDescriptor,qe=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,Ze=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var Te=(e,t,n)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,h=(e,t)=>{for(var n in t||(t={}))Pe.call(t,n)&&Te(e,n,t[n]);if(Oe)for(var n of Oe(t))et.call(t,n)&&Te(e,n,t[n]);return e},F=(e,t)=>He(e,qe(t));var tt=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Le=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of Xe(t))!Pe.call(e,d)&&d!==n&&oe(e,d,{get:()=>t[d],enumerable:!(a=Ve(t,d))||a.enumerable});return e};var nt=(e,t,n)=>(n=e!=null?ze(Ze(e)):{},Le(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),ot=e=>Le(oe({},"__esModule",{value:!0}),e);var _t={};tt(_t,{LOCAL_MODE_BANNER:()=>Ie,PROD_KEYLESS_ERROR:()=>Se,SNAPSHOT_STORAGE_KEY_PREFIX:()=>W,agentUaList:()=>Ee,armOfResult:()=>fe,attachMicroSignalDetectors:()=>je,baselineResultFor:()=>Y,baselineSlots:()=>Ge,deriveSessionSegment:()=>Ke,detectDeviceClass:()=>se,detectTimeOfDay:()=>le,detectTrafficSource:()=>ie,grantConsent:()=>It,init:()=>Ye,isDoNotTrackEnabled:()=>Re,matchedAgentToken:()=>xe,readSnapshot:()=>pe,referrerDomainFromReferer:()=>ae,renderPrePaintScript:()=>Be,toWireSlot:()=>ce,uaTokenMatch:()=>re,writeSnapshot:()=>z});module.exports=ot(_t);var rt="_snt_uid";var J="_snt_uid";function st(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function it(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function at(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(a){}}function lt(e){try{return localStorage.getItem(e)}catch(t){return null}}function ct(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function dt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ut(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function gt(e){try{sessionStorage.removeItem(e)}catch(t){}}function ft(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function pt(e){try{localStorage.removeItem(e)}catch(t){}}function mt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var yt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ue(e){var c,g,p,v,E,S;if(typeof window=="undefined")return yt;let t=(c=e==null?void 0:e.cookieName)!=null?c:rt,a=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,d=(S=(E=(v=(p=it(t))!=null?p:lt(J))!=null?v:dt(J))!=null?E:e==null?void 0:e.ssrSessionId)!=null?S:st();at(t,d,a);let s=ct(J,d),l=ft(t),r=s?!1:ut(J,d),o=!s&&!l&&!r;return{getSessionId:()=>d,isEphemeral:()=>o,destroy:()=>{d=null,mt(t),pt(J),gt(J)}}}function ve(e){return`_snt_retry_${e.slice(0,12)}`}var St={push:()=>{},flush:()=>{},destroy:()=>{}};function ht(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let a=JSON.parse(n);return Array.isArray(a)?(localStorage.removeItem(t),a.slice(-e)):[]}catch(n){return[]}}function he(e,t,n){try{let d=[...(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let l=JSON.parse(s);return Array.isArray(l)?l:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(d))}catch(a){}}function Ne(e){var X,Z,ee;if(typeof window=="undefined")return St;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(Z=e.maxBatchSize)!=null?Z:20,a=(ee=e.maxRetrySize)!=null?ee:100,d=e.ingestUrl,s=e.apiKey,l=ve(s),r=[],o=new Set,c=[],g=f=>{for(let y of f)p.delete(y),!o.has(y)&&(o.add(y),c.push(y));for(;c.length>500;){let y=c.shift();y&&o.delete(y)}},p=new Set,v=f=>{o.has(f.id)||p.has(f.id)||(p.add(f.id),r.push(f))},E=ht(a,l);for(let f of E)v(f);let S=0,R=0,k=f=>{if(f.length===0)return;let y=JSON.stringify(f),I=f.map(i=>i.id),D;try{D=fetch(d,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(i){he(f,a,l);for(let u of I)p.delete(u);R++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6));return}let N=i=>{if(i.ok||i.status>=400&&i.status<500&&i.status!==429){g(I),R=0,S=0;return}he(f,a,l);for(let u of I)p.delete(u);R++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6))};D instanceof Promise?D.then(N).catch(()=>{he(f,a,l);for(let i of I)p.delete(i);R++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6))}):N(D)},w=typeof TextEncoder!="undefined"?new TextEncoder:null,de=f=>w?w.encode(f).length:f.length,K=f=>{let y=[],I=2;for(let D of f){let N=de(JSON.stringify(D))+1;if(y.length>0&&I+N>57344||y.length>=n)break;y.push(D),I+=N}return y},P=()=>{try{if(Date.now()<S)return;for(;r.length>0;){let f=r.filter(I=>!o.has(I.id));if(r.length=0,f.length===0)break;let y=K(f);if(y.length===0)break;y.length<f.length&&r.push(...f.slice(y.length)),k(y)}}catch(f){}},A=!0,G=null;G=setInterval(()=>{A&&P()},t);let V=()=>{document.visibilityState==="hidden"&&P()},q=()=>{P()};return document.addEventListener("visibilitychange",V),window.addEventListener("beforeunload",q),{push(f){v(f),r.length>=n&&P()},flush:P,destroy(){A=!1,G!==null&&(clearInterval(G),G=null),document.removeEventListener("visibilitychange",V),window.removeEventListener("beforeunload",q),P()}}}var be="_snt_asgn_";function ge(e,t){return`${e}:${t}`}function vt(e,t){return`${be}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Me(e){let t=e.slice(be.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(a){return null}}function we(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(be)&&e.push(n)}return e}catch(e){return[]}}function Ue(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of we())try{let s=localStorage.getItem(d);if(!s)continue;let l=JSON.parse(s);if(n(l)){localStorage.removeItem(d);continue}let r=Me(d);if(!r)continue;t.set(ge(r.componentId,r.segment),l)}catch(s){}})(),{get(d,s){let l=t.get(ge(d,s));return l?n(l)?(t.delete(ge(d,s)),null):l:null},set(d,s,l){let r=ge(d,s);t.set(r,l);try{localStorage.setItem(vt(d,s),JSON.stringify(l))}catch(o){}},invalidate(d){let s=`${d}:`;for(let l of[...t.keys()])l.startsWith(s)&&t.delete(l);for(let l of we()){let r=Me(l);if((r==null?void 0:r.componentId)===d)try{localStorage.removeItem(l)}catch(o){}}},clear(){t.clear();for(let d of we())try{localStorage.removeItem(d)}catch(s){}}}}var Ee=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function re(e){return xe(e)!==null}function xe(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ee.find(a=>t.includes(a.toLowerCase())))!=null?n:null}function se(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function ie(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(d){}let a=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(a)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(a)?"social":"referral"}catch(n){return"direct"}}function ae(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function le(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ke(e){let t=wt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function wt(e,t){var s,l,r,o,c,g,p;let n=(l=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?l:"",a=(o=(r=t==null?void 0:t.referer)==null?void 0:r.trim())!=null?o:"",d=(c=t==null?void 0:t.now)!=null?c:new Date;return{sessionId:e,ephemeral:!1,utmParams:(g=t==null?void 0:t.utmParams)!=null?g:{},deviceClass:n?se(n):"desktop",trafficSource:a?ie(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:ae(a),timeOfDay:le(d),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?p:"sun",automation:(t==null?void 0:t.webdriver)===!0||re(n)}}var Q=require("@sentientui/policy");function ce(e){return h(h(h({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function Y(e){let t=ce(e);return(0,Q.slotResultFor)(t,(0,Q.slotBaselineArm)(t))}function Ge(e){let t={};for(let n of e)t[n.id]=Y(n);return t}function fe(e){return typeof e=="string"?e:(0,Q.canonicalArm)(e)}var W="_snt_snap:",bt=["low","medium","high"];function pe(e){try{let t=localStorage.getItem(W+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!bt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function z(e,t){try{localStorage.setItem(W+e,JSON.stringify(t))}catch(n){}}function Be(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(W+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var _e=require("@sentientui/policy");var ye=require("@sentientui/policy");var Se="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ie="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",$e=!1,me=!1;function Et(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function We(e){var r;let t=ue({ssrSessionId:e.ssrSessionId}),n=(r=t.getSessionId())!=null?r:"local",a=Et(),d=import("@sentientui/core/local").then(o=>{let c=o;return c.LOCAL_ENGINE_AVAILABLE?($e||($e=!0,console.info(Ie)),c):(me||(me=!0,console.error(Se)),null)}).catch(()=>(me||(me=!0,console.error(Se)),null)),s=null;function l(o){let c=document.documentElement;c.dataset.sentientPersona===void 0&&(c.dataset.sentientPersona=o.persona,c.dataset.sentientConfidence=(0,ye.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var p,v,E;let c=await d;if(!c)return null;let g=c.createLocalEngine({sessionId:n,forcedPersona:a}).decide(o);return s=F(h({},g),{layoutOrder:(v=(p=g.layoutOrder)!=null?p:s==null?void 0:s.layoutOrder)!=null?v:null,slots:h(h({},(E=s==null?void 0:s.slots)!=null?E:{}),g.slots)}),z(e.apiKey||"local",{v:1,persona:s.persona,band:(0,ye.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),l(g),g},getSlotResult(o){var c,g,p;return(p=(g=s==null?void 0:s.slots[o])!=null?g:(c=e.initialSlots)==null?void 0:c[o])!=null?p:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,ye.confidenceBand)(s.confidence)}:null},async assign(o,c){var v;let g=await d;return!g||!c||c.length===0?c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null:{variantId:(v=g.createLocalEngine({sessionId:n,forcedPersona:a}).decide({components:[{id:o,variantIds:c}]}).assignments[o])!=null?v:c[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function je(e,t,n){var d;let a=[];{let r=!1,o=[],c=()=>{if(r)return;let g=Date.now();for(o.push(g);o.length>0&&g-o[0]>500;)o.shift();o.length>=3&&(r=!0,e("rage_click"))};t.addEventListener("click",c),a.push(()=>t.removeEventListener("click",c))}{let s=!1,l=r=>{if(s||!(r.target instanceof Node)||!t.contains(r.target)&&t!==r.target)return;s=!0;let o=typeof window!="undefined"?window.getSelection():null,c=o?o.toString().length:0;e("text_copy",{selectionLength:c})};document.addEventListener("copy",l),a.push(()=>document.removeEventListener("copy",l))}{let s=!1,l=!1,r=null,o=()=>{r!==null&&(clearTimeout(r),r=null)},c=()=>{s||!l||(o(),r=setTimeout(()=>{!s&&l&&(s=!0,e("scroll_hesitation"))},3e3))},g=()=>{o(),c()},p=E=>{for(let S of E)l=S.intersectionRatio>.3,l?c():o()};typeof process!="undefined"&&((d=process.env)==null?void 0:d.NODE_ENV)!=="production"&&(window.__lastIOCallback=p);let v=new IntersectionObserver(p,{threshold:[.3]});v.observe(t),window.addEventListener("scroll",g,{passive:!0}),a.push(()=>{v.disconnect(),window.removeEventListener("scroll",g),o()})}{let s=!1,l=n!=null?n:Date.now(),r=()=>{if(s||document.visibilityState!=="hidden")return;let o=Date.now()-l;o<15e3&&(s=!0,e("tab_loss",{timeOnPage:o}))};document.addEventListener("visibilitychange",r),a.push(()=>document.removeEventListener("visibilitychange",r))}return()=>{for(let s of a)s()}}var Fe="https://api.sentient-ui.com/v1/events",j=new Map,Je=null;function Ce(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var H={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function xt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,a]of t)n.startsWith("utm_")&&(e[n]=a);return e}catch(e){return{}}}function Qe(e){return e.replace(/\/events\/?$/,"")}function Re(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function It(e){if(typeof window=="undefined")return;let t=e!=null?e:Je;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=j.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:a,upgrade:d}=n;if(!d||a.respectDoNotTrack!==!1&&Re())return;let s=Ye(F(h({},a),{consent:!0}));d(s),j.set(t,{config:F(h({},a),{consent:!0}),upgrade:null})}function Ct(e){var l;let t=Qe((l=e.ingestUrl)!=null?l:Fe),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},a={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(r,o,c){try{let g=new URLSearchParams({componentId:r});for(let E of o!=null?o:[])g.append("variantIds[]",E);let p=await fetch(`${t}/winner?${g.toString()}`,{headers:n});return p.ok?{variantId:(await p.json()).variantId,assignmentTtlMs:0}:o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}catch(g){return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},d={track:r=>a.track(r),goal:(r,o,c,g)=>a.goal(r,o,c,g),componentGoal:(r,o,c)=>a.componentGoal(r,o,c),identify:r=>a.identify(r),getAssignment:(r,o)=>a.getAssignment(r,o),assign:(r,o,c,g)=>a.assign(r,o,c,g),decide:r=>a.decide(r),getSlotResult:r=>a.getSlotResult(r),getPersona:()=>a.getPersona(),fetchWeights:()=>a.fetchWeights(),getGraph:()=>a.getGraph(),dispose:()=>a.dispose(),destroy:()=>a.destroy()};function s(r){a=r}return{proxy:d,setInner:s}}function Ye(e){var q,X,Z,ee,f,y,I,D,N;if(typeof window=="undefined")return H;Je=e.apiKey;let t=e.respectDoNotTrack!==!1&&Re(),n=e.consent===!1||t,a=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!a&&e.localMode!==!1)return n?(j.set(e.apiKey||"local",{config:e,upgrade:null}),H):(j.set(e.apiKey||"local",{config:e,upgrade:null}),We(e));if(n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),H;let{proxy:i,setInner:u}=Ct(e);return j.set(e.apiKey,{config:e,upgrade:t?null:u}),i}return j.set(e.apiKey,{config:e,upgrade:null}),H}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),H;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),H;let d=(q=e.ingestUrl)!=null?q:Fe,s=Date.now(),l=ue({ssrSessionId:e.ssrSessionId}),r=Ue(),o=Ne({ingestUrl:d,apiKey:e.apiKey}),c=Qe(d),g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},p=se((X=navigator.userAgent)!=null?X:""),v=typeof window!="undefined"?window.location.origin:void 0,E=ie((Z=document.referrer)!=null?Z:"",v),S=(ee=e.sessionSegment)!=null?ee:`${p}:${E}`,R=new Map,k=new Map,w=null,de=i=>{for(let u of i)k.has(u.id)||k.set(u.id,Y(u))};if(e.initialSlots)for(let[i,u]of Object.entries(e.initialSlots))k.set(i,u);let K=pe(e.apiKey);if(K)for(let[i,u]of Object.entries(K.slots))k.has(i)||k.set(i,u);let P={low:.15,medium:.5,high:.85};if(e.initialPersona)w=h({},e.initialPersona);else{let i=document.documentElement.dataset;i.sentientPersona?w={persona:i.sentientPersona,confidence:(y=P[(f=i.sentientConfidence)!=null?f:"low"])!=null?y:.15}:K&&(w={persona:K.persona,confidence:(I=P[K.band])!=null?I:.15})}if(e.initialAssignments)for(let[i,u]of Object.entries(e.initialAssignments))r.set(i,S,{variantId:u,assignedAt:Date.now(),segment:S,confidence:1});let A=Promise.resolve(),G=l.getSessionId();if(G){let i=ae((D=document.referrer)!=null?D:""),u=h(h({sessionId:G,deviceClass:p,trafficSource:E,referrerDomain:i,utmParams:xt(),timeOfDay:le(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:l.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||re((N=navigator.userAgent)!=null?N:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{A=fetch(`${c}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:g}).then(m=>{m.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(m){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:o});let V={goal(i,u={},m=1,O=0){let x=l.getSessionId();if(!x)return;let C=Ce();A.then(()=>{fetch(`${c}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:x,name:i,metadata:u,weight:m,stepIndex:O,goalId:C}),headers:g}).catch(()=>{})})},componentGoal(i,u,m){var T,U,L;let O=l.getSessionId();if(!O)return;let x=r.get(i,S),C=x?null:(T=k.get(i))!=null?T:null;if(!x&&C===null){e.debug&&console.warn(`[sentient] componentGoal("${i}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let B=x?x.variantId:fe(C),M={id:Ce(),sessionId:O,projectId:e.apiKey,componentId:i,variantId:B,eventType:"goal_achieved",goalType:u,payload:h({reward:(U=m==null?void 0:m.reward)!=null?U:1},(L=m==null?void 0:m.metadata)!=null?L:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",M),A.then(()=>o.push(M))},identify(i){let u=l.getSessionId();u&&A.then(()=>{fetch(`${c}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:i,ephemeral:l.isEphemeral()}),headers:g}).catch(()=>{})})},track(i){let u=l.getSessionId();if(!u)return;let m=F(h({},i),{id:Ce(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",m),A.then(()=>o.push(m))},getAssignment(i,u){return r.get(i,u)},async assign(i,u,m,O){let x=l.getSessionId();if(!x)return null;let C=r.get(i,S);if(C&&(u!=null&&u.length||C.content!==void 0))return{variantId:C.variantId,assignmentTtlMs:0,content:C.content};let B=R.get(i);if(B)return B;let M=(async()=>{await A;try{let T={sessionId:x,componentId:i,variantIds:u};O!==void 0?T.agentDataByVariant=O:m!==void 0&&(T.agentData=m);let U=await fetch(`${c}/assign`,{method:"POST",body:JSON.stringify(T),headers:g});if(!U.ok)return null;let L=await U.json();return r.set(i,S,{variantId:L.variantId,assignedAt:Date.now(),segment:S,confidence:1,content:L.content}),L}catch(T){return null}finally{R.delete(i)}})();return R.set(i,M),M},async decide(i){var O,x,C,B,M,T,U,L,ke,Ae;let u=l.getSessionId();if(!u)return null;let m=(O=i.slots)!=null?O:[];await A;try{let $={sessionId:u};i.sections&&i.sections.length>0&&($.sections=i.sections.map(_=>({id:_}))),$.components=(x=i.components)!=null?x:[],m.length>0&&($.slots=m.map(ce)),i.slotsFrom==="registry"&&($.slotsFrom="registry"),i.v&&($.v=i.v);let De=await fetch(`${c}/decide`,{method:"POST",body:JSON.stringify($),headers:g});if(!De.ok)return de(m),null;let b=await De.json(),te={};for(let _ of m)te[_.id]=(B=(C=b.slots)==null?void 0:C[_.id])!=null?B:Y(_);if(b.slots)for(let[_,ne]of Object.entries(b.slots))_ in te||(te[_]=ne);for(let[_,ne]of Object.entries(te))k.set(_,ne);w={persona:(M=b.persona)!=null?M:"unknown",confidence:(T=b.confidence)!=null?T:0};for(let[_,ne]of Object.entries((U=b.assignments)!=null?U:{}))r.set(_,S,{variantId:ne,assignedAt:Date.now(),segment:S,confidence:1});return z(e.apiKey,h({v:1,persona:w.persona,band:(0,_e.confidenceBand)(w.confidence),slots:Object.fromEntries(k),layoutOrder:(L=b.layoutOrder)!=null?L:null,savedAt:Date.now()},b.slotConfig?{slotConfig:b.slotConfig}:{})),h(h({layoutOrder:(ke=b.layoutOrder)!=null?ke:null,assignments:(Ae=b.assignments)!=null?Ae:{},slots:te,persona:w.persona,confidence:w.confidence},b.slotConfig?{slotConfig:b.slotConfig}:{}),b.goals?{goals:b.goals}:{})}catch($){return de(m),null}},getSlotResult(i){var u;return(u=k.get(i))!=null?u:null},getPersona(){return w?{persona:w.persona,confidence:w.confidence,band:(0,_e.confidenceBand)(w.confidence)}:null},async fetchWeights(){var i;try{let u=await fetch(`${c}/weights`,{headers:g});return u.ok?(i=(await u.json()).components)!=null?i:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){o.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){o.destroy(),l.destroy();try{localStorage.removeItem(W+e.apiKey),localStorage.removeItem(ve(e.apiKey))}catch(i){}e.debug&&console.log("[sentient] destroyed")}};if(j.set(e.apiKey,{config:e,upgrade:null}),e.debug){let i=window;i.__sentient&&(i.__sentient.client=V)}return V}0&&(module.exports={LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
1
+ "use strict";var He=Object.create;var oe=Object.defineProperty,ze=Object.defineProperties,Ve=Object.getOwnPropertyDescriptor,qe=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,Ze=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var Te=(e,t,n)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,S=(e,t)=>{for(var n in t||(t={}))Pe.call(t,n)&&Te(e,n,t[n]);if(Oe)for(var n of Oe(t))et.call(t,n)&&Te(e,n,t[n]);return e},F=(e,t)=>ze(e,qe(t));var tt=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Le=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Xe(t))!Pe.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(c=Ve(t,i))||c.enumerable});return e};var nt=(e,t,n)=>(n=e!=null?He(Ze(e)):{},Le(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),ot=e=>Le(oe({},"__esModule",{value:!0}),e);var _t={};tt(_t,{LOCAL_MODE_BANNER:()=>Ie,PROD_KEYLESS_ERROR:()=>Se,SNAPSHOT_STORAGE_KEY_PREFIX:()=>W,agentUaList:()=>Ee,armOfResult:()=>fe,attachMicroSignalDetectors:()=>je,baselineResultFor:()=>Y,baselineSlots:()=>Ge,deriveSessionSegment:()=>Ke,detectDeviceClass:()=>se,detectTimeOfDay:()=>le,detectTrafficSource:()=>ie,grantConsent:()=>It,init:()=>Ye,isDoNotTrackEnabled:()=>Re,matchedAgentToken:()=>xe,readSnapshot:()=>pe,referrerDomainFromReferer:()=>ae,renderPrePaintScript:()=>Be,toWireSlot:()=>ce,uaTokenMatch:()=>re,writeSnapshot:()=>H});module.exports=ot(_t);var rt="_snt_uid";var J="_snt_uid";function st(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function it(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function at(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(c){}}function lt(e){try{return localStorage.getItem(e)}catch(t){return null}}function ct(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function dt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ut(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function gt(e){try{sessionStorage.removeItem(e)}catch(t){}}function ft(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function pt(e){try{localStorage.removeItem(e)}catch(t){}}function mt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var yt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ue(e){var d,g,p,v,E,h;if(typeof window=="undefined")return yt;let t=(d=e==null?void 0:e.cookieName)!=null?d:rt,c=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,i=(h=(E=(v=(p=it(t))!=null?p:lt(J))!=null?v:dt(J))!=null?E:e==null?void 0:e.ssrSessionId)!=null?h:st();at(t,i,c);let s=ct(J,i),a=ft(t),o=s?!1:ut(J,i),l=!s&&!a&&!o;return{getSessionId:()=>i,isEphemeral:()=>l,destroy:()=>{i=null,mt(t),pt(J),gt(J)}}}function ve(e){return`_snt_retry_${e.slice(0,12)}`}var St={push:()=>{},flush:()=>{},destroy:()=>{}};function ht(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?(localStorage.removeItem(t),c.slice(-e)):[]}catch(n){return[]}}function he(e,t,n){try{let i=[...(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let a=JSON.parse(s);return Array.isArray(a)?a:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(i))}catch(c){}}function Me(e){var X,Z,ee;if(typeof window=="undefined")return St;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(Z=e.maxBatchSize)!=null?Z:20,c=(ee=e.maxRetrySize)!=null?ee:100,i=e.ingestUrl,s=e.apiKey,a=ve(s),o=[],l=new Set,d=[],g=f=>{for(let y of f)p.delete(y),!l.has(y)&&(l.add(y),d.push(y));for(;d.length>500;){let y=d.shift();y&&l.delete(y)}},p=new Set,v=f=>{l.has(f.id)||p.has(f.id)||(p.add(f.id),o.push(f))},E=ht(c,a);for(let f of E)v(f);let h=0,R=0,k=f=>{if(f.length===0)return;let y=JSON.stringify(f),I=f.map(r=>r.id),D;try{D=fetch(i,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(r){he(f,c,a);for(let u of I)p.delete(u);R++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6));return}let M=r=>{if(r.ok||r.status>=400&&r.status<500&&r.status!==429){g(I),R=0,h=0;return}he(f,c,a);for(let u of I)p.delete(u);R++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6))};D instanceof Promise?D.then(M).catch(()=>{he(f,c,a);for(let r of I)p.delete(r);R++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6))}):M(D)},b=typeof TextEncoder!="undefined"?new TextEncoder:null,de=f=>b?b.encode(f).length:f.length,K=f=>{let y=[],I=2;for(let D of f){let M=de(JSON.stringify(D))+1;if(y.length>0&&I+M>57344||y.length>=n)break;y.push(D),I+=M}return y},P=()=>{try{if(Date.now()<h)return;for(;o.length>0;){let f=o.filter(I=>!l.has(I.id));if(o.length=0,f.length===0)break;let y=K(f);if(y.length===0)break;y.length<f.length&&o.push(...f.slice(y.length)),k(y)}}catch(f){}},A=!0,G=null;G=setInterval(()=>{A&&P()},t);let V=()=>{document.visibilityState==="hidden"&&P()},q=()=>{P()};return document.addEventListener("visibilitychange",V),window.addEventListener("pagehide",q),{push(f){v(f),o.length>=n&&P()},flush:P,destroy(){A=!1,G!==null&&(clearInterval(G),G=null),document.removeEventListener("visibilitychange",V),window.removeEventListener("pagehide",q),P()}}}var we="_snt_asgn_";function ge(e,t){return`${e}:${t}`}function vt(e,t){return`${we}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ne(e){let t=e.slice(we.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(c){return null}}function be(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(we)&&e.push(n)}return e}catch(e){return[]}}function Ue(e=18e5){let t=new Map,n=i=>i.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let i of be())try{let s=localStorage.getItem(i);if(!s)continue;let a=JSON.parse(s);if(n(a)){localStorage.removeItem(i);continue}let o=Ne(i);if(!o)continue;t.set(ge(o.componentId,o.segment),a)}catch(s){}})(),{get(i,s){let a=t.get(ge(i,s));return a?n(a)?(t.delete(ge(i,s)),null):a:null},set(i,s,a){let o=ge(i,s);t.set(o,a);try{localStorage.setItem(vt(i,s),JSON.stringify(a))}catch(l){}},invalidate(i){let s=`${i}:`;for(let a of[...t.keys()])a.startsWith(s)&&t.delete(a);for(let a of be()){let o=Ne(a);if((o==null?void 0:o.componentId)===i)try{localStorage.removeItem(a)}catch(l){}}},clear(){t.clear();for(let i of be())try{localStorage.removeItem(i)}catch(s){}}}}var Ee=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function re(e){return xe(e)!==null}function xe(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ee.find(c=>t.includes(c.toLowerCase())))!=null?n:null}function se(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function ie(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(i){}let c=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(c)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(c)?"social":"referral"}catch(n){return"direct"}}function ae(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function le(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ke(e){let t=bt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function bt(e,t){var s,a,o,l,d,g,p;let n=(a=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?a:"",c=(l=(o=t==null?void 0:t.referer)==null?void 0:o.trim())!=null?l:"",i=(d=t==null?void 0:t.now)!=null?d:new Date;return{sessionId:e,ephemeral:!1,utmParams:(g=t==null?void 0:t.utmParams)!=null?g:{},deviceClass:n?se(n):"desktop",trafficSource:c?ie(c,t==null?void 0:t.appOrigin):"direct",referrerDomain:ae(c),timeOfDay:le(i),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][i.getDay()])!=null?p:"sun",automation:(t==null?void 0:t.webdriver)===!0||re(n)}}var Q=require("@sentientui/policy");function ce(e){return S(S(S({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function Y(e){let t=ce(e);return(0,Q.slotResultFor)(t,(0,Q.slotBaselineArm)(t))}function Ge(e){let t={};for(let n of e)t[n.id]=Y(n);return t}function fe(e){return typeof e=="string"?e:(0,Q.canonicalArm)(e)}var W="_snt_snap:",wt=["low","medium","high"];function pe(e){try{let t=localStorage.getItem(W+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!wt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function H(e,t){try{localStorage.setItem(W+e,JSON.stringify(t))}catch(n){}}function Be(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(W+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var _e=require("@sentientui/policy");var ye=require("@sentientui/policy");var Se="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ie="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",$e=!1,me=!1;function Et(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function We(e){var o;let t=ue({ssrSessionId:e.ssrSessionId}),n=(o=t.getSessionId())!=null?o:"local",c=Et(),i=import("@sentientui/core/local").then(l=>{let d=l;return d.LOCAL_ENGINE_AVAILABLE?($e||($e=!0,console.info(Ie)),d):(me||(me=!0,console.error(Se)),null)}).catch(()=>(me||(me=!0,console.error(Se)),null)),s=null;function a(l){let d=document.documentElement;d.dataset.sentientPersona===void 0&&(d.dataset.sentientPersona=l.persona,d.dataset.sentientConfidence=(0,ye.confidenceBand)(l.confidence))}return{isLocal:!0,async decide(l){var p,v,E;let d=await i;if(!d)return null;let g=d.createLocalEngine({sessionId:n,forcedPersona:c}).decide(l);return s=F(S({},g),{layoutOrder:(v=(p=g.layoutOrder)!=null?p:s==null?void 0:s.layoutOrder)!=null?v:null,slots:S(S({},(E=s==null?void 0:s.slots)!=null?E:{}),g.slots)}),H(e.apiKey||"local",{v:1,persona:s.persona,band:(0,ye.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),a(g),g},getSlotResult(l){var d,g,p;return(p=(g=s==null?void 0:s.slots[l])!=null?g:(d=e.initialSlots)==null?void 0:d[l])!=null?p:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,ye.confidenceBand)(s.confidence)}:null},async assign(l,d){var v;let g=await i;return!g||!d||d.length===0?d!=null&&d[0]?{variantId:d[0],assignmentTtlMs:0}:null:{variantId:(v=g.createLocalEngine({sessionId:n,forcedPersona:c}).decide({components:[{id:l,variantIds:d}]}).assignments[l])!=null?v:d[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function je(e,t,n){let c=[];{let a=!1,o=[],l=()=>{if(a)return;let d=Date.now();for(o.push(d);o.length>0&&d-o[0]>500;)o.shift();o.length>=3&&(a=!0,e("rage_click"))};t.addEventListener("click",l),c.push(()=>t.removeEventListener("click",l))}{let i=!1,s=a=>{if(i||!(a.target instanceof Node)||!t.contains(a.target)&&t!==a.target)return;i=!0;let o=typeof window!="undefined"?window.getSelection():null,l=o?o.toString().length:0;e("text_copy",{selectionLength:l})};document.addEventListener("copy",s),c.push(()=>document.removeEventListener("copy",s))}{let i=!1,s=!1,a=null,o=()=>{a!==null&&(clearTimeout(a),a=null)},l=()=>{i||!s||(o(),a=setTimeout(()=>{!i&&s&&(i=!0,e("scroll_hesitation"))},3e3))},d=()=>{o(),l()},g=v=>{for(let E of v)s=E.intersectionRatio>.3,s?l():o()},p=new IntersectionObserver(g,{threshold:[.3]});p.observe(t),window.addEventListener("scroll",d,{passive:!0}),c.push(()=>{p.disconnect(),window.removeEventListener("scroll",d),o()})}{let i=!1,s=n!=null?n:Date.now(),a=()=>{if(i||document.visibilityState!=="hidden")return;let o=Date.now()-s;o<15e3&&(i=!0,e("tab_loss",{timeOnPage:o}))};document.addEventListener("visibilitychange",a),c.push(()=>document.removeEventListener("visibilitychange",a))}return()=>{for(let i of c)i()}}var Fe="https://api.sentient-ui.com/v1/events",j=new Map,Je=null;function Ce(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var z={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function xt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,c]of t)n.startsWith("utm_")&&(e[n]=c);return e}catch(e){return{}}}function Qe(e){return e.replace(/\/events\/?$/,"")}function Re(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function It(e){if(typeof window=="undefined")return;let t=e!=null?e:Je;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=j.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:c,upgrade:i}=n;if(!i||c.respectDoNotTrack!==!1&&Re())return;let s=Ye(F(S({},c),{consent:!0}));i(s),j.set(t,{config:F(S({},c),{consent:!0}),upgrade:null})}function Ct(e){var a;let t=Qe((a=e.ingestUrl)!=null?a:Fe),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},c={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,l,d){try{let g=new URLSearchParams({componentId:o});for(let E of l!=null?l:[])g.append("variantIds[]",E);let p=await fetch(`${t}/winner?${g.toString()}`,{headers:n});return p.ok?{variantId:(await p.json()).variantId,assignmentTtlMs:0}:l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null}catch(g){return l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},i={track:o=>c.track(o),goal:(o,l,d,g)=>c.goal(o,l,d,g),componentGoal:(o,l,d)=>c.componentGoal(o,l,d),identify:o=>c.identify(o),getAssignment:(o,l)=>c.getAssignment(o,l),assign:(o,l,d,g)=>c.assign(o,l,d,g),decide:o=>c.decide(o),getSlotResult:o=>c.getSlotResult(o),getPersona:()=>c.getPersona(),fetchWeights:()=>c.fetchWeights(),getGraph:()=>c.getGraph(),dispose:()=>c.dispose(),destroy:()=>c.destroy()};function s(o){c=o}return{proxy:i,setInner:s}}function Ye(e){var q,X,Z,ee,f,y,I,D,M;if(typeof window=="undefined")return z;Je=e.apiKey;let t=e.respectDoNotTrack!==!1&&Re(),n=e.consent===!1||t,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!c&&e.localMode!==!1)return n?(j.set(e.apiKey||"local",{config:e,upgrade:null}),z):(j.set(e.apiKey||"local",{config:e,upgrade:null}),We(e));if(n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),z;let{proxy:r,setInner:u}=Ct(e);return j.set(e.apiKey,{config:e,upgrade:t?null:u}),r}return j.set(e.apiKey,{config:e,upgrade:null}),z}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),z;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),z;let i=(q=e.ingestUrl)!=null?q:Fe,s=Date.now(),a=ue({ssrSessionId:e.ssrSessionId}),o=Ue(),l=Me({ingestUrl:i,apiKey:e.apiKey}),d=Qe(i),g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},p=se((X=navigator.userAgent)!=null?X:""),v=typeof window!="undefined"?window.location.origin:void 0,E=ie((Z=document.referrer)!=null?Z:"",v),h=(ee=e.sessionSegment)!=null?ee:`${p}:${E}`,R=new Map,k=new Map,b=null,de=r=>{for(let u of r)k.has(u.id)||k.set(u.id,Y(u))};if(e.initialSlots)for(let[r,u]of Object.entries(e.initialSlots))k.set(r,u);let K=pe(e.apiKey);if(K)for(let[r,u]of Object.entries(K.slots))k.has(r)||k.set(r,u);let P={low:.15,medium:.5,high:.85};if(e.initialPersona)b=S({},e.initialPersona);else{let r=document.documentElement.dataset;r.sentientPersona?b={persona:r.sentientPersona,confidence:(y=P[(f=r.sentientConfidence)!=null?f:"low"])!=null?y:.15}:K&&(b={persona:K.persona,confidence:(I=P[K.band])!=null?I:.15})}if(e.initialAssignments)for(let[r,u]of Object.entries(e.initialAssignments))o.set(r,h,{variantId:u,assignedAt:Date.now(),segment:h,confidence:1});let A=Promise.resolve(),G=a.getSessionId();if(G){let r=ae((D=document.referrer)!=null?D:""),u=S(S({sessionId:G,deviceClass:p,trafficSource:E,referrerDomain:r,utmParams:xt(),timeOfDay:le(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:a.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||re((M=navigator.userAgent)!=null?M:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{A=fetch(`${d}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:g}).then(m=>{m.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(m){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:l});let V={goal(r,u={},m=1,O=0){let x=a.getSessionId();if(!x)return;let C=Ce();A.then(()=>{fetch(`${d}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:x,name:r,metadata:u,weight:m,stepIndex:O,goalId:C}),headers:g}).catch(()=>{})})},componentGoal(r,u,m){var T,U,L;let O=a.getSessionId();if(!O)return;let x=o.get(r,h),C=x?null:(T=k.get(r))!=null?T:null;if(!x&&C===null){e.debug&&console.warn(`[sentient] componentGoal("${r}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let B=x?x.variantId:fe(C),N={id:Ce(),sessionId:O,projectId:e.apiKey,componentId:r,variantId:B,eventType:"goal_achieved",goalType:u,payload:S({reward:(U=m==null?void 0:m.reward)!=null?U:1},(L=m==null?void 0:m.metadata)!=null?L:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",N),A.then(()=>l.push(N))},identify(r){let u=a.getSessionId();u&&A.then(()=>{fetch(`${d}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:r,ephemeral:a.isEphemeral()}),headers:g}).catch(()=>{})})},track(r){let u=a.getSessionId();if(!u)return;let m=F(S({},r),{id:Ce(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",m),A.then(()=>l.push(m))},getAssignment(r,u){return o.get(r,u)},async assign(r,u,m,O){let x=a.getSessionId();if(!x)return null;let C=o.get(r,h);if(C&&(u!=null&&u.length||C.content!==void 0))return{variantId:C.variantId,assignmentTtlMs:0,content:C.content};let B=R.get(r);if(B)return B;let N=(async()=>{await A;try{let T={sessionId:x,componentId:r,variantIds:u};O!==void 0?T.agentDataByVariant=O:m!==void 0&&(T.agentData=m);let U=await fetch(`${d}/assign`,{method:"POST",body:JSON.stringify(T),headers:g});if(!U.ok)return null;let L=await U.json();return o.set(r,h,{variantId:L.variantId,assignedAt:Date.now(),segment:h,confidence:1,content:L.content}),L}catch(T){return null}finally{R.delete(r)}})();return R.set(r,N),N},async decide(r){var O,x,C,B,N,T,U,L,ke,Ae;let u=a.getSessionId();if(!u)return null;let m=(O=r.slots)!=null?O:[];await A;try{let $={sessionId:u};r.sections&&r.sections.length>0&&($.sections=r.sections.map(_=>({id:_}))),$.components=(x=r.components)!=null?x:[],m.length>0&&($.slots=m.map(ce)),r.slotsFrom==="registry"&&($.slotsFrom="registry"),r.v&&($.v=r.v);let De=await fetch(`${d}/decide`,{method:"POST",body:JSON.stringify($),headers:g});if(!De.ok)return de(m),null;let w=await De.json(),te={};for(let _ of m)te[_.id]=(B=(C=w.slots)==null?void 0:C[_.id])!=null?B:Y(_);if(w.slots)for(let[_,ne]of Object.entries(w.slots))_ in te||(te[_]=ne);for(let[_,ne]of Object.entries(te))k.set(_,ne);b={persona:(N=w.persona)!=null?N:"unknown",confidence:(T=w.confidence)!=null?T:0};for(let[_,ne]of Object.entries((U=w.assignments)!=null?U:{}))o.set(_,h,{variantId:ne,assignedAt:Date.now(),segment:h,confidence:1});return H(e.apiKey,S({v:1,persona:b.persona,band:(0,_e.confidenceBand)(b.confidence),slots:Object.fromEntries(k),layoutOrder:(L=w.layoutOrder)!=null?L:null,savedAt:Date.now()},w.slotConfig?{slotConfig:w.slotConfig}:{})),S(S({layoutOrder:(ke=w.layoutOrder)!=null?ke:null,assignments:(Ae=w.assignments)!=null?Ae:{},slots:te,persona:b.persona,confidence:b.confidence},w.slotConfig?{slotConfig:w.slotConfig}:{}),w.goals?{goals:w.goals}:{})}catch($){return de(m),null}},getSlotResult(r){var u;return(u=k.get(r))!=null?u:null},getPersona(){return b?{persona:b.persona,confidence:b.confidence,band:(0,_e.confidenceBand)(b.confidence)}:null},async fetchWeights(){var r;try{let u=await fetch(`${d}/weights`,{headers:g});return u.ok?(r=(await u.json()).components)!=null?r:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){l.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){l.destroy(),a.destroy();try{localStorage.removeItem(W+e.apiKey),localStorage.removeItem(ve(e.apiKey))}catch(r){}e.debug&&console.log("[sentient] destroyed")}};if(j.set(e.apiKey,{config:e,upgrade:null}),e.debug){let r=window;r.__sentient&&(r.__sentient.client=V)}return V}0&&(module.exports={LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
2
+ //# sourceMappingURL=index.js.map