@trycurious/js 0.0.0-stage → 0.2.0

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/dist/index.js ADDED
@@ -0,0 +1,1206 @@
1
+ // src/errors.ts
2
+ var CuriousError = class extends Error {
3
+ constructor(summary2) {
4
+ super(summary2.message);
5
+ this.name = "CuriousError";
6
+ this.summary = summary2;
7
+ }
8
+ get code() {
9
+ return this.summary.code;
10
+ }
11
+ };
12
+ var LIMIT = 300;
13
+ function summary(code, message, extra = {}) {
14
+ const retryable = extra.retryable ?? (code === "timeout" || code === "network_error" || code === "rate_limited" || code === "server_error");
15
+ const out = {
16
+ code,
17
+ retryable,
18
+ message: message.length > LIMIT ? `${message.slice(0, LIMIT)}\u2026` : message
19
+ };
20
+ if (extra.status !== void 0) out.status = extra.status;
21
+ if (extra.requestId !== void 0) out.requestId = extra.requestId;
22
+ if (extra.serverCode !== void 0) out.serverCode = extra.serverCode;
23
+ return out;
24
+ }
25
+ function envelope(body) {
26
+ if (typeof body === "object" && body !== null && typeof body.error === "string" && typeof body.message === "string") return body;
27
+ return null;
28
+ }
29
+ function summarizeHttpError(status, body, requestId) {
30
+ const env = envelope(body);
31
+ const message = env?.message ?? `HTTP ${status}`;
32
+ const extra = { status };
33
+ if (requestId !== null) extra.requestId = requestId;
34
+ if (env !== null) extra.serverCode = env.error;
35
+ if (status === 401) return summary("authentication_error", message, extra);
36
+ if (status === 403) return summary(/origin/i.test(message) ? "origin_not_allowed" : "authentication_error", message, extra);
37
+ if (status === 408) return summary("timeout", message, extra);
38
+ if (status === 429) return summary("rate_limited", message, extra);
39
+ if (status === 409) {
40
+ if (env?.error === "idempotency_error") return summary("mutation_drift", message, extra);
41
+ if (env?.error === "lock_timeout") return summary("lock_timeout", message, { ...extra, retryable: true });
42
+ if (/no live experiment/i.test(message)) return summary("undeclared_element", message, extra);
43
+ return summary("invalid_input", message, { ...extra, retryable: /retry/i.test(message) });
44
+ }
45
+ if (status >= 500) return summary("server_error", message, extra);
46
+ if (status === 400 || status === 413 || status === 422) return summary("invalid_input", message, extra);
47
+ return summary("protocol_error", message, { ...extra, retryable: false });
48
+ }
49
+
50
+ // src/identity.ts
51
+ var COOKIE_NAME = "curious_anon";
52
+ var STORAGE_KEY = "curious:anon";
53
+ var KNOWN_KEY = "curious:user";
54
+ var DEFAULT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;
55
+ var Identity = class {
56
+ constructor(options = {}) {
57
+ this.anonymous = null;
58
+ this.known = null;
59
+ this.enabled = false;
60
+ this.maxAge = options.cookieMaxAgeSeconds ?? DEFAULT_COOKIE_MAX_AGE_SECONDS;
61
+ this.doc = options.document ?? (typeof document === "undefined" ? null : document);
62
+ this.local = options.storage === void 0 ? safeStorage("localStorage") : options.storage;
63
+ this.session = safeStorage("sessionStorage");
64
+ }
65
+ /** Called when consent allows identity: reads or mints the anonymous id. */
66
+ enable() {
67
+ this.enabled = true;
68
+ this.known = this.session === null ? null : safeGet(this.session, KNOWN_KEY);
69
+ this.anonymous = this.readCookie() ?? (this.local === null ? null : safeGet(this.local, STORAGE_KEY));
70
+ if (this.anonymous === null) this.anonymous = newAnonymousId();
71
+ this.persistAnonymous();
72
+ }
73
+ /** The id decisions and events are made for: the known user when set, else the anonymous one. */
74
+ get activeUserId() {
75
+ if (!this.enabled) {
76
+ throw new CuriousError(summary("capability_unavailable", "Identity is unavailable before consent", { retryable: false }));
77
+ }
78
+ return this.known ?? this.anonymous;
79
+ }
80
+ get anonymousId() {
81
+ return this.anonymous;
82
+ }
83
+ get knownUserId() {
84
+ return this.known;
85
+ }
86
+ /** After the customer's backend linked the anonymous id, switch the active user. The anonymous id is retained as link evidence. */
87
+ setKnown(userId) {
88
+ this.known = userId;
89
+ if (this.session !== null) safeSet(this.session, KNOWN_KEY, userId);
90
+ }
91
+ /** Logout: drop the known id and start a fresh anonymous history. Never unlinks server-side. */
92
+ reset() {
93
+ this.known = null;
94
+ if (this.session !== null) safeRemove(this.session, KNOWN_KEY);
95
+ this.anonymous = newAnonymousId();
96
+ this.persistAnonymous();
97
+ }
98
+ /** denyConsent(): remove everything the SDK stored about this browser. */
99
+ clear() {
100
+ this.enabled = false;
101
+ this.known = null;
102
+ this.anonymous = null;
103
+ if (this.session !== null) safeRemove(this.session, KNOWN_KEY);
104
+ if (this.local !== null) safeRemove(this.local, STORAGE_KEY);
105
+ this.writeCookie("", 0);
106
+ }
107
+ persistAnonymous() {
108
+ if (this.anonymous === null) return;
109
+ this.writeCookie(this.anonymous, this.maxAge);
110
+ if (this.local !== null) safeSet(this.local, STORAGE_KEY, this.anonymous);
111
+ }
112
+ readCookie() {
113
+ if (this.doc === null) return null;
114
+ const match = this.doc.cookie.split("; ").find((part) => part.startsWith(`${COOKIE_NAME}=`));
115
+ if (match === void 0) return null;
116
+ const value = decodeURIComponent(match.slice(COOKIE_NAME.length + 1));
117
+ return /^anon_[0-9a-f-]{36}$/.test(value) ? value : null;
118
+ }
119
+ writeCookie(value, maxAge) {
120
+ if (this.doc === null) return;
121
+ const secure = this.doc.location?.protocol === "https:" ? "; Secure" : "";
122
+ try {
123
+ this.doc.cookie = `${COOKIE_NAME}=${encodeURIComponent(value)}; Max-Age=${maxAge}; Path=/; SameSite=Lax${secure}`;
124
+ } catch {
125
+ }
126
+ }
127
+ };
128
+ function newAnonymousId() {
129
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
130
+ return `anon_${crypto.randomUUID()}`;
131
+ }
132
+ const bytes = new Uint8Array(16);
133
+ crypto.getRandomValues(bytes);
134
+ bytes[6] = bytes[6] & 15 | 64;
135
+ bytes[8] = bytes[8] & 63 | 128;
136
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
137
+ return `anon_${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
138
+ }
139
+ function safeStorage(kind) {
140
+ try {
141
+ const store = globalThis[kind];
142
+ const probe = "__curious_probe__";
143
+ store.setItem(probe, "1");
144
+ store.removeItem(probe);
145
+ return store;
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+ function safeGet(store, key) {
151
+ try {
152
+ return store.getItem(key);
153
+ } catch {
154
+ return null;
155
+ }
156
+ }
157
+ function safeSet(store, key, value) {
158
+ try {
159
+ store.setItem(key, value);
160
+ } catch {
161
+ }
162
+ }
163
+ function safeRemove(store, key) {
164
+ try {
165
+ store.removeItem(key);
166
+ } catch {
167
+ }
168
+ }
169
+
170
+ // src/cache.ts
171
+ var CACHE_SCHEMA = 1;
172
+ var DEFAULT_CACHE_TTL_MS = 6e4;
173
+ var PREFIX = "curious:assign:";
174
+ var AssignmentCache = class {
175
+ constructor(options) {
176
+ this.memory = /* @__PURE__ */ new Map();
177
+ this.store = options.storage === void 0 ? safeStorage("sessionStorage") : options.storage;
178
+ this.ttlMs = options.ttlMs ?? DEFAULT_CACHE_TTL_MS;
179
+ this.fingerprint = options.publishableKey.slice(-8);
180
+ }
181
+ key(userId, element) {
182
+ const origin = typeof location === "undefined" ? "" : location.origin;
183
+ return `${PREFIX}${this.fingerprint}:${origin}:${userId}:${element}`;
184
+ }
185
+ get(userId, element, now = Date.now()) {
186
+ const key = this.key(userId, element);
187
+ const raw = this.store === null ? this.memory.get(key) ?? null : safeGet(this.store, key);
188
+ if (raw === null) return null;
189
+ try {
190
+ const parsed = JSON.parse(raw);
191
+ if (parsed.schema !== CACHE_SCHEMA || parsed.expiresAt <= now) {
192
+ this.remove(userId, element);
193
+ return null;
194
+ }
195
+ return parsed;
196
+ } catch {
197
+ this.remove(userId, element);
198
+ return null;
199
+ }
200
+ }
201
+ set(userId, element, value, now = Date.now()) {
202
+ const entry = { ...value, storedAt: now, expiresAt: now + this.ttlMs, schema: CACHE_SCHEMA };
203
+ const key = this.key(userId, element);
204
+ const raw = JSON.stringify(entry);
205
+ if (this.store === null) this.memory.set(key, raw);
206
+ else safeSet(this.store, key, raw);
207
+ }
208
+ remove(userId, element) {
209
+ const key = this.key(userId, element);
210
+ this.memory.delete(key);
211
+ if (this.store !== null) safeRemove(this.store, key);
212
+ }
213
+ /** identify(), reset(), denyConsent(): everything this SDK cached. */
214
+ clear() {
215
+ this.memory.clear();
216
+ if (this.store === null) return;
217
+ try {
218
+ const doomed = [];
219
+ for (let i = 0; i < this.store.length; i += 1) {
220
+ const k = this.store.key(i);
221
+ if (k !== null && k.startsWith(PREFIX)) doomed.push(k);
222
+ }
223
+ for (const k of doomed) this.store.removeItem(k);
224
+ } catch {
225
+ }
226
+ }
227
+ };
228
+
229
+ // src/history.ts
230
+ var subscribers = /* @__PURE__ */ new WeakMap();
231
+ function notify(listeners) {
232
+ for (const listener of Array.from(listeners)) {
233
+ try {
234
+ listener();
235
+ } catch {
236
+ }
237
+ }
238
+ }
239
+ function install(target) {
240
+ const existing = subscribers.get(target);
241
+ if (existing !== void 0) return existing;
242
+ const listeners = /* @__PURE__ */ new Set();
243
+ subscribers.set(target, listeners);
244
+ for (const method of ["pushState", "replaceState"]) {
245
+ const original = target[method];
246
+ if (typeof original !== "function") continue;
247
+ try {
248
+ target[method] = function(...args) {
249
+ const result = original.apply(this, args);
250
+ notify(listeners);
251
+ return result;
252
+ };
253
+ } catch {
254
+ }
255
+ }
256
+ addEventListener("popstate", () => notify(listeners));
257
+ return listeners;
258
+ }
259
+ function onHistoryChange(listener) {
260
+ if (typeof history === "undefined" || typeof addEventListener === "undefined") return () => {
261
+ };
262
+ const listeners = install(history);
263
+ listeners.add(listener);
264
+ return () => {
265
+ listeners.delete(listener);
266
+ };
267
+ }
268
+
269
+ // src/events.ts
270
+ var DEFAULTS = {
271
+ flushIntervalMs: 5e3,
272
+ flushCount: 20,
273
+ queueLimit: 100,
274
+ keepaliveBodyBytes: 48 * 1024,
275
+ requestTimeoutMs: 1e4,
276
+ maxAttempts: 5,
277
+ itemCap: 200
278
+ };
279
+ var QUEUE_KEY = "curious:events";
280
+ var RESERVED_PREFIX = "$";
281
+ var EventQueue = class {
282
+ constructor(options) {
283
+ this.sequence = 0;
284
+ this.entries = [];
285
+ this.timer = null;
286
+ this.inFlight = null;
287
+ this.o = {
288
+ transport: options.transport,
289
+ userId: options.userId,
290
+ flushIntervalMs: options.flushIntervalMs ?? DEFAULTS.flushIntervalMs,
291
+ flushCount: options.flushCount ?? DEFAULTS.flushCount,
292
+ queueLimit: options.queueLimit ?? DEFAULTS.queueLimit,
293
+ keepaliveBodyBytes: options.keepaliveBodyBytes ?? DEFAULTS.keepaliveBodyBytes,
294
+ requestTimeoutMs: options.requestTimeoutMs ?? DEFAULTS.requestTimeoutMs,
295
+ maxAttempts: options.maxAttempts ?? DEFAULTS.maxAttempts,
296
+ onEventDrop: options.onEventDrop
297
+ };
298
+ this.store = options.storage === void 0 ? safeStorage("sessionStorage") : options.storage;
299
+ this.now = options.now ?? Date.now;
300
+ this.sessionId = Math.random().toString(36).slice(2, 10) + this.now().toString(36);
301
+ this.restore();
302
+ }
303
+ get size() {
304
+ return this.entries.length;
305
+ }
306
+ /** Customer events; `$` names are reserved for the SDK's own capture path. */
307
+ track(input) {
308
+ if (typeof input.name === "string" && input.name.startsWith(RESERVED_PREFIX)) {
309
+ throw new CuriousError(summary("invalid_input", "Event names starting with $ are reserved", { retryable: false }));
310
+ }
311
+ return this.enqueue(input);
312
+ }
313
+ /** The SDK's own autocapture events (`$pageview`, `$click`, `$form_submit`). */
314
+ system(input) {
315
+ return this.enqueue(input);
316
+ }
317
+ enqueue(input) {
318
+ if (typeof input.name !== "string" || input.name.trim().length === 0) {
319
+ throw new CuriousError(summary("invalid_input", "track: name is required", { retryable: false }));
320
+ }
321
+ const event = {
322
+ id: input.id ?? `browser:${this.sessionId}:${++this.sequence}:${Math.random().toString(36).slice(2, 8)}`,
323
+ user_id: this.o.userId(),
324
+ name: input.name
325
+ };
326
+ if (input.value !== void 0) event.value = input.value;
327
+ if (input.properties !== void 0) event.properties = input.properties;
328
+ if (input.context !== void 0) event.context = input.context;
329
+ if (input.timestamp !== void 0) {
330
+ event.timestamp = input.timestamp instanceof Date ? input.timestamp.toISOString() : input.timestamp;
331
+ }
332
+ if (this.entries.length >= this.o.queueLimit) {
333
+ this.o.onEventDrop(summary("queue_full", `Event queue is full (${this.o.queueLimit}); event not queued`, { retryable: true }));
334
+ return { id: event.id, queued: false };
335
+ }
336
+ this.entries.push({ event, attempts: 0 });
337
+ this.persist();
338
+ if (this.entries.length >= this.o.flushCount) {
339
+ void this.flush();
340
+ } else if (this.timer === null) {
341
+ this.timer = setTimeout(() => {
342
+ this.timer = null;
343
+ void this.flush();
344
+ }, this.o.flushIntervalMs);
345
+ }
346
+ return { id: event.id, queued: true };
347
+ }
348
+ /** Deliver what is queued. `keepalive` is for lifecycle flushes (hidden, pagehide, before identify/reset). */
349
+ flush(options = {}) {
350
+ if (this.inFlight === null) {
351
+ this.inFlight = this.run(options.keepalive === true).finally(() => {
352
+ this.inFlight = null;
353
+ });
354
+ }
355
+ return this.inFlight;
356
+ }
357
+ /** reset()/denyConsent(): forget everything queued. */
358
+ clear() {
359
+ this.entries = [];
360
+ this.persist();
361
+ }
362
+ async run(keepalive) {
363
+ if (this.timer !== null) {
364
+ clearTimeout(this.timer);
365
+ this.timer = null;
366
+ }
367
+ const totals = { sent: 0, duplicates: 0, failed: 0, pending: 0 };
368
+ while (this.entries.length > 0) {
369
+ const batch = this.takeBatch(keepalive);
370
+ if (batch.length === 0) break;
371
+ const retry = await this.deliver(batch, keepalive, totals);
372
+ if (retry.length > 0) {
373
+ this.entries.unshift(...retry);
374
+ this.persist();
375
+ break;
376
+ }
377
+ }
378
+ totals.pending = this.entries.length;
379
+ this.persist();
380
+ return totals;
381
+ }
382
+ // Up to the API's item cap, and under the keepalive body budget when the
383
+ // flush rides keepalive.
384
+ takeBatch(keepalive) {
385
+ const batch = [];
386
+ let bytes = 2;
387
+ while (this.entries.length > 0 && batch.length < DEFAULTS.itemCap) {
388
+ const next = this.entries[0];
389
+ const size = JSON.stringify(next.event).length + 1;
390
+ if (keepalive && batch.length > 0 && bytes + size > this.o.keepaliveBodyBytes) break;
391
+ batch.push(this.entries.shift());
392
+ bytes += size;
393
+ }
394
+ return batch;
395
+ }
396
+ async deliver(batch, keepalive, totals) {
397
+ for (const item of batch) item.attempts += 1;
398
+ let response;
399
+ try {
400
+ response = await this.o.transport.post("/events", { events: batch.map((e) => e.event) }, {
401
+ timeoutMs: this.o.requestTimeoutMs,
402
+ keepalive
403
+ });
404
+ } catch (error) {
405
+ return this.retryOrDrop(batch, error.summary, totals);
406
+ }
407
+ if (response.status !== 200) {
408
+ const failure = summarizeHttpError(response.status, response.body, response.requestId);
409
+ if (!failure.retryable) {
410
+ for (const item of batch) {
411
+ totals.failed += 1;
412
+ this.o.onEventDrop(summary("event_rejected", failure.message, { ...failure, retryable: false }));
413
+ }
414
+ return [];
415
+ }
416
+ return this.retryOrDrop(batch, failure, totals);
417
+ }
418
+ const results = response.body?.results;
419
+ if (!Array.isArray(results)) {
420
+ return this.retryOrDrop(batch, summary("protocol_error", "Batch response carried no results", { retryable: true }), totals);
421
+ }
422
+ const retry = [];
423
+ batch.forEach((item, index) => {
424
+ const result = results[index];
425
+ if (result === void 0 || result === null || typeof result !== "object" || result.index !== index) {
426
+ retry.push(...this.retryOrDrop([item], summary("protocol_error", "Batch response had no result for this event", { retryable: true }), totals));
427
+ return;
428
+ }
429
+ if (result.status === "ok") {
430
+ totals.sent += 1;
431
+ if (result.duplicate === true) totals.duplicates += 1;
432
+ return;
433
+ }
434
+ const itemError = summarizeHttpError(result.error === "internal_error" ? 500 : 400, result, response.requestId);
435
+ if (itemError.retryable && item.attempts < this.o.maxAttempts) {
436
+ retry.push(item);
437
+ return;
438
+ }
439
+ totals.failed += 1;
440
+ this.o.onEventDrop(summary("event_rejected", itemError.message, { ...itemError, retryable: false }));
441
+ });
442
+ return retry;
443
+ }
444
+ retryOrDrop(batch, failure, totals) {
445
+ const retry = [];
446
+ for (const item of batch) {
447
+ if (item.attempts < this.o.maxAttempts) {
448
+ retry.push(item);
449
+ } else {
450
+ totals.failed += 1;
451
+ this.o.onEventDrop(summary("event_rejected", `Gave up after ${item.attempts} attempts: ${failure.message}`, {
452
+ ...failure,
453
+ retryable: false
454
+ }));
455
+ }
456
+ }
457
+ return retry;
458
+ }
459
+ persist() {
460
+ if (this.store === null) return;
461
+ safeSet(this.store, QUEUE_KEY, JSON.stringify(this.entries));
462
+ }
463
+ restore() {
464
+ if (this.store === null) return;
465
+ const raw = safeGet(this.store, QUEUE_KEY);
466
+ if (raw === null) return;
467
+ try {
468
+ const parsed = JSON.parse(raw);
469
+ if (Array.isArray(parsed)) this.entries = parsed.filter((e) => e && typeof e.event?.id === "string").slice(0, this.o.queueLimit);
470
+ } catch {
471
+ this.entries = [];
472
+ }
473
+ }
474
+ };
475
+
476
+ // src/tags.ts
477
+ var TAG_ATTRIBUTE = "data-curious";
478
+ var IGNORE_ATTRIBUTE = "data-curious-ignore";
479
+ var CRITICAL_ATTRIBUTE = "data-curious-critical";
480
+ var LOADING_CLASS = "curious-loading";
481
+ var DEFAULT_ROOT_MARGIN = "200% 0px";
482
+ var ELEMENT_NODE = 1;
483
+ var TEXT_NODE = 3;
484
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "EMBED", "HR", "IMG", "INPUT", "LINK", "META", "SOURCE", "TRACK", "WBR"]);
485
+ function textSlot(node) {
486
+ if (VOID_ELEMENTS.has(node.tagName.toUpperCase())) return { unsupported: "void_element" };
487
+ let text = null;
488
+ for (const child of Array.from(node.childNodes)) {
489
+ if (child.nodeType === ELEMENT_NODE) return { unsupported: "child_elements" };
490
+ if (child.nodeType !== TEXT_NODE) continue;
491
+ if (text !== null) return { unsupported: "several_text_nodes" };
492
+ text = child;
493
+ }
494
+ return { text };
495
+ }
496
+ var TagRuntime = class {
497
+ constructor(options) {
498
+ this.nodes = /* @__PURE__ */ new Map();
499
+ this.byElement = /* @__PURE__ */ new Map();
500
+ this.pending = /* @__PURE__ */ new Set();
501
+ // Nodes whose text the page took back after a decision. Kept apart from
502
+ // `nodes` so the promise survives the node being removed and attached
503
+ // again, and weakly so a discarded node can be collected.
504
+ this.released = /* @__PURE__ */ new WeakSet();
505
+ this.intersection = null;
506
+ this.mutation = null;
507
+ this.frame = null;
508
+ this.o = options;
509
+ }
510
+ start() {
511
+ if (typeof IntersectionObserver === "function") {
512
+ this.intersection = new IntersectionObserver((entries) => {
513
+ for (const entry of entries) {
514
+ if (!entry.isIntersecting) continue;
515
+ const tagged = this.nodes.get(entry.target);
516
+ if (tagged === void 0 || tagged.state !== "idle") continue;
517
+ tagged.state = "pending";
518
+ this.pending.add(tagged.element);
519
+ this.intersection?.unobserve(entry.target);
520
+ }
521
+ this.schedule();
522
+ }, { rootMargin: this.o.rootMargin ?? DEFAULT_ROOT_MARGIN, threshold: 0 });
523
+ }
524
+ if (typeof MutationObserver === "function") {
525
+ this.mutation = new MutationObserver((records) => {
526
+ for (const record of records) {
527
+ if (record.type === "childList") {
528
+ for (const removed of record.removedNodes) {
529
+ if (removed instanceof Element) this.forgetRemoved(removed);
530
+ }
531
+ for (const added of record.addedNodes) {
532
+ if (added instanceof Element) this.scan(added);
533
+ }
534
+ }
535
+ const target = record.target instanceof Element ? record.target : record.target.parentElement;
536
+ if (target !== null) this.detectDrift(target);
537
+ }
538
+ });
539
+ const root = this.o.root ?? document;
540
+ this.mutation.observe(root instanceof Document ? root.documentElement : root, {
541
+ childList: true,
542
+ subtree: true,
543
+ characterData: true
544
+ });
545
+ }
546
+ this.scan(this.o.root ?? document);
547
+ }
548
+ stop() {
549
+ this.intersection?.disconnect();
550
+ this.mutation?.disconnect();
551
+ this.intersection = null;
552
+ this.mutation = null;
553
+ if (this.frame !== null) clearTimeout(this.frame);
554
+ this.frame = null;
555
+ this.nodes.clear();
556
+ this.byElement.clear();
557
+ this.pending.clear();
558
+ this.released = /* @__PURE__ */ new WeakSet();
559
+ }
560
+ /** Register every tagged node under `root` (the whole document by default). Safe to call repeatedly. */
561
+ scan(root = this.o.root ?? document) {
562
+ const candidates = [];
563
+ if (root instanceof Element && root.hasAttribute(TAG_ATTRIBUTE)) candidates.push(root);
564
+ candidates.push(...Array.from(root.querySelectorAll(`[${TAG_ATTRIBUTE}]`)));
565
+ for (const node of candidates) {
566
+ if (this.nodes.has(node) || this.released.has(node) || node.closest(`[${IGNORE_ATTRIBUTE}]`) !== null) continue;
567
+ const element = (node.getAttribute(TAG_ATTRIBUTE) ?? "").trim();
568
+ if (element.length === 0) continue;
569
+ const tagged = { element, node, control: node.textContent ?? "", applied: null, state: "idle", drifted: false };
570
+ this.nodes.set(node, tagged);
571
+ const slot = textSlot(node);
572
+ if ("unsupported" in slot) {
573
+ this.refuse(tagged, slot.unsupported);
574
+ continue;
575
+ }
576
+ let set = this.byElement.get(element);
577
+ if (set === void 0) {
578
+ set = /* @__PURE__ */ new Set();
579
+ this.byElement.set(element, set);
580
+ }
581
+ set.add(tagged);
582
+ if (this.intersection !== null) this.intersection.observe(node);
583
+ else {
584
+ tagged.state = "pending";
585
+ this.pending.add(element);
586
+ }
587
+ }
588
+ if (this.pending.size > 0) this.schedule();
589
+ }
590
+ /** Apply decided content to every node of an element that can take it. Non-string content leaves the control in place. */
591
+ apply(element, content) {
592
+ const set = this.byElement.get(element);
593
+ if (set === void 0) return "no_node";
594
+ if (typeof content !== "string") {
595
+ for (const tagged of set) {
596
+ if (!tagged.drifted) tagged.state = "fallback";
597
+ }
598
+ return "not_text";
599
+ }
600
+ let applied = false;
601
+ for (const tagged of Array.from(set)) {
602
+ if (!tagged.node.isConnected) {
603
+ this.forget(tagged);
604
+ continue;
605
+ }
606
+ if (tagged.drifted) continue;
607
+ const slot = textSlot(tagged.node);
608
+ if ("unsupported" in slot) {
609
+ this.refuse(tagged, slot.unsupported);
610
+ continue;
611
+ }
612
+ if (slot.text === null) tagged.node.appendChild(tagged.node.ownerDocument.createTextNode(content));
613
+ else if (slot.text.data !== content) slot.text.data = content;
614
+ tagged.applied = content;
615
+ tagged.state = "decided";
616
+ this.revealCritical(tagged.node);
617
+ applied = true;
618
+ }
619
+ return applied ? "applied" : "no_node";
620
+ }
621
+ /** Leave the control visible and mark the element as decided against. */
622
+ fallback(element) {
623
+ const set = this.byElement.get(element);
624
+ if (set === void 0) return;
625
+ for (const tagged of set) {
626
+ tagged.state = "fallback";
627
+ this.revealCritical(tagged.node);
628
+ }
629
+ }
630
+ /** Forget decisions (identify/reset) so the nodes can be decided again for the new user. */
631
+ resetDecisions() {
632
+ for (const tagged of Array.from(this.nodes.values())) {
633
+ if (!tagged.node.isConnected) {
634
+ this.forget(tagged);
635
+ continue;
636
+ }
637
+ if ((tagged.state === "decided" || tagged.state === "fallback" || tagged.state === "pending") && !tagged.drifted) {
638
+ tagged.state = "idle";
639
+ tagged.applied = null;
640
+ this.intersection?.observe(tagged.node);
641
+ if (this.intersection === null) {
642
+ tagged.state = "pending";
643
+ this.pending.add(tagged.element);
644
+ }
645
+ }
646
+ }
647
+ if (this.pending.size > 0) this.schedule();
648
+ }
649
+ elements() {
650
+ return Array.from(this.byElement.keys());
651
+ }
652
+ schedule() {
653
+ if (this.frame !== null || this.pending.size === 0) return;
654
+ this.frame = setTimeout(() => {
655
+ this.frame = null;
656
+ const batch = Array.from(this.pending).filter((element) => this.hasWritablePendingNode(element));
657
+ this.pending.clear();
658
+ if (batch.length > 0) this.o.onPending(batch);
659
+ }, 0);
660
+ }
661
+ // True when a node that neared the viewport (state `pending`) is still on
662
+ // the page and can still take text. A plain sibling that is still off
663
+ // screen does not count: it asks for the decision when it gets near. Nodes
664
+ // that can no longer take text are refused here, and removed ones
665
+ // forgotten, before a decision is requested on their account.
666
+ hasWritablePendingNode(element) {
667
+ const set = this.byElement.get(element);
668
+ if (set === void 0) return false;
669
+ let writable = false;
670
+ for (const tagged of Array.from(set)) {
671
+ if (tagged.state !== "pending") continue;
672
+ if (!tagged.node.isConnected) {
673
+ this.forget(tagged);
674
+ continue;
675
+ }
676
+ const slot = textSlot(tagged.node);
677
+ if ("unsupported" in slot) this.refuse(tagged, slot.unsupported);
678
+ else writable = true;
679
+ }
680
+ return writable;
681
+ }
682
+ forgetRemoved(removed) {
683
+ const candidates = [removed, ...Array.from(removed.querySelectorAll(`[${TAG_ATTRIBUTE}]`))];
684
+ for (const node of candidates) {
685
+ const tagged = this.nodes.get(node);
686
+ if (tagged !== void 0 && !node.isConnected) this.forget(tagged);
687
+ }
688
+ }
689
+ // Drop a node the page has removed. If the same node is attached again, the
690
+ // MutationObserver scans it afresh.
691
+ forget(tagged) {
692
+ this.nodes.delete(tagged.node);
693
+ this.byElement.get(tagged.element)?.delete(tagged);
694
+ this.intersection?.unobserve(tagged.node);
695
+ }
696
+ // Take a node out of play for good: never observed, never decided, never
697
+ // written, reported once.
698
+ refuse(tagged, reason) {
699
+ tagged.state = "unsupported";
700
+ this.byElement.get(tagged.element)?.delete(tagged);
701
+ this.intersection?.unobserve(tagged.node);
702
+ this.revealCritical(tagged.node);
703
+ this.o.onUnsupported(tagged.element, reason);
704
+ }
705
+ detectDrift(target) {
706
+ const node = target.closest(`[${TAG_ATTRIBUTE}]`);
707
+ if (node === null) return;
708
+ const tagged = this.nodes.get(node);
709
+ if (tagged === void 0 || tagged.state !== "decided" || tagged.drifted) return;
710
+ if ((node.textContent ?? "") !== tagged.applied) {
711
+ tagged.drifted = true;
712
+ this.released.add(node);
713
+ this.o.onDrift(tagged.element);
714
+ }
715
+ }
716
+ revealCritical(node) {
717
+ if (node.hasAttribute(CRITICAL_ATTRIBUTE)) {
718
+ document.documentElement.classList.remove(LOADING_CLASS);
719
+ }
720
+ }
721
+ };
722
+
723
+ // src/version.ts
724
+ var SDK_VERSION = "0.2.0";
725
+
726
+ // src/transport.ts
727
+ var MAX_RESPONSE_BYTES = 1048576;
728
+ var Transport = class {
729
+ constructor(options) {
730
+ const fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch.bind(globalThis) : void 0);
731
+ if (fetchImpl === void 0) {
732
+ throw new CuriousError(summary("capability_unavailable", "fetch is not available", { retryable: false }));
733
+ }
734
+ this.fetchImpl = fetchImpl;
735
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
736
+ this.headers = {
737
+ authorization: `Bearer ${options.publishableKey}`,
738
+ "content-type": "application/json",
739
+ "x-curious-client": `browser-js/${SDK_VERSION}`
740
+ };
741
+ }
742
+ // POST one JSON body within the deadline. Throws for a timeout, a network
743
+ // failure or an unreadable response; returns every HTTP status.
744
+ async post(path, body, options) {
745
+ const controller = new AbortController();
746
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
747
+ let response;
748
+ try {
749
+ response = await this.fetchImpl(`${this.baseUrl}${path}`, {
750
+ method: "POST",
751
+ headers: this.headers,
752
+ body: JSON.stringify(body),
753
+ signal: controller.signal,
754
+ keepalive: options.keepalive === true,
755
+ credentials: "omit",
756
+ mode: "cors"
757
+ });
758
+ } catch (error) {
759
+ if (controller.signal.aborted) {
760
+ throw new CuriousError(summary("timeout", `No response within ${options.timeoutMs}ms`));
761
+ }
762
+ throw new CuriousError(summary("network_error", describe(error)));
763
+ } finally {
764
+ clearTimeout(timer);
765
+ }
766
+ const requestId = response.headers.get("x-request-id");
767
+ const retryAfterMs = parseRetryAfter(response.headers.get("retry-after"));
768
+ let text;
769
+ try {
770
+ text = await response.text();
771
+ } catch (error) {
772
+ throw new CuriousError(summary("network_error", describe(error), { status: response.status }));
773
+ }
774
+ if (text.length > MAX_RESPONSE_BYTES) {
775
+ throw new CuriousError(summary("protocol_error", "Response exceeds the size bound", { status: response.status, retryable: false }));
776
+ }
777
+ let parsed = null;
778
+ if (text.length > 0) {
779
+ try {
780
+ parsed = JSON.parse(text);
781
+ } catch {
782
+ throw new CuriousError(summary("protocol_error", `Response ${response.status} was not JSON`, {
783
+ status: response.status,
784
+ retryable: false
785
+ }));
786
+ }
787
+ }
788
+ return { status: response.status, requestId, retryAfterMs, body: parsed };
789
+ }
790
+ };
791
+ function describe(error) {
792
+ return error instanceof Error && error.message ? `Request failed: ${error.message}` : "Request failed";
793
+ }
794
+ function parseRetryAfter(value) {
795
+ if (value === null) return null;
796
+ const seconds = Number(value);
797
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1e3);
798
+ const at = Date.parse(value);
799
+ return Number.isNaN(at) ? null : Math.max(0, at - Date.now());
800
+ }
801
+
802
+ // src/client.ts
803
+ var DEFAULTS2 = { baseUrl: "https://api.trycurious.ai/v1", decideTimeoutMs: 1e3 };
804
+ var PUBLISHABLE_PREFIX = "curious_pk_";
805
+ var DECIDE_BATCH_LIMIT = 50;
806
+ var BATCH_ITEM_STATUS = /* @__PURE__ */ new Map([
807
+ ["internal_error", 500],
808
+ ["decision_unavailable", 503],
809
+ ["idempotency_error", 409],
810
+ ["lock_timeout", 409],
811
+ ["conflict", 409]
812
+ ]);
813
+ var UNSUPPORTED_MESSAGE = {
814
+ child_elements: "The tagged element contains other elements; the SDK replaces plain text only. Tag the innermost element that holds only text",
815
+ several_text_nodes: "The tagged element's text is made of several pieces (a template with expressions); the SDK replaces one run of plain text only",
816
+ void_element: "The tagged element cannot hold text (an input, an image or another empty element); tag an element whose content is text"
817
+ };
818
+ function createCurious(options) {
819
+ if (typeof options.publishableKey !== "string" || options.publishableKey.length === 0) {
820
+ throw new CuriousError(summary("invalid_configuration", "publishableKey is required", { retryable: false }));
821
+ }
822
+ if (!options.publishableKey.startsWith(PUBLISHABLE_PREFIX)) {
823
+ throw new CuriousError(summary("invalid_key_type", "The browser SDK takes a publishable key (curious_pk_...). Never ship a secret key to a browser", { retryable: false }));
824
+ }
825
+ const timeoutMs = Math.min(options.decideTimeoutMs ?? DEFAULTS2.decideTimeoutMs, DEFAULTS2.decideTimeoutMs * 10);
826
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
827
+ throw new CuriousError(summary("invalid_configuration", "decideTimeoutMs must be a positive number", { retryable: false }));
828
+ }
829
+ const onFallback = guarded(options.onFallback);
830
+ const onDecision = guarded(options.onDecision);
831
+ const onEventDrop = guarded(options.onEventDrop);
832
+ const onIdentityChange = guarded(options.onIdentityChange);
833
+ const transport = new Transport({ publishableKey: options.publishableKey, baseUrl: options.baseUrl ?? DEFAULTS2.baseUrl, fetch: options.fetch });
834
+ const identity = new Identity({
835
+ ...options.cookieMaxAgeSeconds === void 0 ? {} : { cookieMaxAgeSeconds: options.cookieMaxAgeSeconds },
836
+ document: options.document,
837
+ storage: options.storage
838
+ });
839
+ const cache = new AssignmentCache({ publishableKey: options.publishableKey, ...options.cacheTtlMs === void 0 ? {} : { ttlMs: options.cacheTtlMs }, ...options.storage === void 0 ? {} : { storage: options.storage } });
840
+ let consent = options.consent ?? "implicit";
841
+ let started = false;
842
+ let active = false;
843
+ const inFlight = /* @__PURE__ */ new Map();
844
+ const directInFlight = /* @__PURE__ */ new Map();
845
+ let events = null;
846
+ const listeners = [];
847
+ const pageviewSetting = options.autocapture === false ? false : options.autocapture?.pageviews ?? true;
848
+ const pageviews = pageviewSetting !== false;
849
+ const historyChanges = pageviews && (pageviewSetting === true || pageviewSetting.historyChanges !== false);
850
+ let visitPath = null;
851
+ let visitRecorded = false;
852
+ const tags = new TagRuntime({
853
+ ...options.rootMargin === void 0 ? {} : { rootMargin: options.rootMargin },
854
+ onPending: (elements) => void decideTagged(elements),
855
+ onDrift: (element) => onFallback(element, summary("mutation_drift", "Applied content was rewritten by the page; the SDK will not reapply it", { retryable: false })),
856
+ onUnsupported: (element, reason) => onFallback(element, summary("content_shape_mismatch", UNSUPPORTED_MESSAGE[reason], { retryable: false }))
857
+ });
858
+ function pageContext() {
859
+ const base = {};
860
+ if (typeof location !== "undefined") base.path = location.pathname;
861
+ if (typeof navigator !== "undefined" && navigator.language) base.locale = navigator.language;
862
+ return { ...base, ...options.context ?? {} };
863
+ }
864
+ function recordPageview() {
865
+ visitPath = location.pathname;
866
+ const recorded = queue().system({ name: "$pageview", properties: { path: visitPath } });
867
+ visitRecorded = recorded.queued;
868
+ return recorded;
869
+ }
870
+ function pageviewRecorded() {
871
+ return visitRecorded && location.pathname === visitPath;
872
+ }
873
+ function queue() {
874
+ if (events === null) {
875
+ const tuning = options.events ?? {};
876
+ events = new EventQueue({
877
+ transport,
878
+ userId: () => identity.activeUserId,
879
+ onEventDrop,
880
+ storage: options.storage,
881
+ ...tuning.flushIntervalMs === void 0 ? {} : { flushIntervalMs: tuning.flushIntervalMs },
882
+ ...tuning.flushCount === void 0 ? {} : { flushCount: tuning.flushCount },
883
+ ...tuning.queueLimit === void 0 ? {} : { queueLimit: tuning.queueLimit }
884
+ });
885
+ }
886
+ return events;
887
+ }
888
+ async function decideTagged(elements) {
889
+ if (!active) return;
890
+ const userId = identity.activeUserId;
891
+ const toRequest = [];
892
+ for (const element of elements) {
893
+ const hit = cache.get(userId, element);
894
+ if (hit !== null) {
895
+ if (typeof hit.content !== "string") {
896
+ fallbackTag(element, summary("content_shape_mismatch", "Served content is not text", { retryable: false, status: 200 }));
897
+ continue;
898
+ }
899
+ if (tags.apply(element, hit.content) === "applied") {
900
+ onDecision(element, { content: hit.content, served: "cache", armId: hit.armId, armType: hit.armType, experimentId: hit.experimentId, experimentStatus: hit.experimentStatus, requestId: null });
901
+ }
902
+ continue;
903
+ }
904
+ if (!inFlight.has(`${userId}:${element}`)) toRequest.push(element);
905
+ }
906
+ if (toRequest.length === 0) return;
907
+ const run = (async () => {
908
+ for (let i = 0; i < toRequest.length; i += DECIDE_BATCH_LIMIT) {
909
+ const slice = toRequest.slice(i, i + DECIDE_BATCH_LIMIT);
910
+ await decideBatch(userId, slice);
911
+ }
912
+ })();
913
+ for (const element of toRequest) inFlight.set(`${userId}:${element}`, run);
914
+ try {
915
+ await run;
916
+ } finally {
917
+ for (const element of toRequest) inFlight.delete(`${userId}:${element}`);
918
+ }
919
+ }
920
+ async function decideBatch(userId, elements) {
921
+ const stale = () => !active || identity.activeUserId !== userId;
922
+ if (stale()) return;
923
+ let response;
924
+ try {
925
+ response = await transport.post("/decide", {
926
+ user_id: userId,
927
+ context: pageContext(),
928
+ elements: elements.map((element) => ({ element }))
929
+ }, { timeoutMs });
930
+ } catch (error) {
931
+ if (stale()) return;
932
+ for (const element of elements) fallbackTag(element, error.summary);
933
+ return;
934
+ }
935
+ if (stale()) return;
936
+ if (response.status !== 200) {
937
+ const failure = summarizeHttpError(response.status, response.body, response.requestId);
938
+ for (const element of elements) fallbackTag(element, failure);
939
+ return;
940
+ }
941
+ const results = response.body?.results;
942
+ elements.forEach((element, index) => {
943
+ if (stale()) return;
944
+ const item = Array.isArray(results) ? results[index] : void 0;
945
+ if (item === void 0 || item === null || typeof item !== "object" || item.index !== index) {
946
+ fallbackTag(element, summary("protocol_error", "Batch response had no result for this element", { retryable: false, status: 200 }));
947
+ return;
948
+ }
949
+ if (item.status === "error") {
950
+ fallbackTag(element, summarizeHttpError(BATCH_ITEM_STATUS.get(item.error) ?? 400, item, response.requestId));
951
+ return;
952
+ }
953
+ const outcome = tags.apply(element, item.content);
954
+ if (stale()) return;
955
+ if (outcome === "not_text") {
956
+ fallbackTag(element, summary("content_shape_mismatch", "Served content is not text", { retryable: false, status: 200 }));
957
+ return;
958
+ }
959
+ cache.set(userId, element, { content: item.content, armId: item.arm_id, armType: item.arm_type ?? null, experimentId: item.experiment_id, experimentStatus: item.experiment_status });
960
+ if (outcome === "applied") {
961
+ onDecision(element, { content: item.content, served: "curious", armId: item.arm_id, armType: item.arm_type ?? null, experimentId: item.experiment_id, experimentStatus: item.experiment_status, requestId: response.requestId });
962
+ }
963
+ });
964
+ }
965
+ async function requestDecision(userId, input) {
966
+ const body = { element: input.element, user_id: userId, context: { ...pageContext(), ...input.context ?? {} } };
967
+ if (input.identifiers !== void 0) body.identifiers = input.identifiers;
968
+ if (input.attributes !== void 0) body.attributes = input.attributes;
969
+ let response;
970
+ try {
971
+ response = await transport.post("/decide", body, { timeoutMs });
972
+ } catch (error) {
973
+ return { ok: false, error: error.summary, requestId: null };
974
+ }
975
+ if (response.status !== 200) return { ok: false, error: summarizeHttpError(response.status, response.body, response.requestId), requestId: response.requestId };
976
+ const decision = response.body;
977
+ if (decision === null || typeof decision !== "object" || typeof decision.arm_id !== "string" || !("content" in decision)) {
978
+ return { ok: false, error: summary("protocol_error", "Decision response was missing required fields", { retryable: false, status: 200 }), requestId: response.requestId };
979
+ }
980
+ return {
981
+ ok: true,
982
+ content: decision.content,
983
+ armId: decision.arm_id,
984
+ armType: decision.arm_type ?? null,
985
+ experimentId: typeof decision.experiment_id === "string" ? decision.experiment_id : null,
986
+ experimentStatus: typeof decision.experiment_status === "string" ? decision.experiment_status : null,
987
+ requestId: response.requestId
988
+ };
989
+ }
990
+ function fallbackTag(element, error) {
991
+ tags.fallback(element);
992
+ onFallback(element, error);
993
+ }
994
+ function attachLifecycle() {
995
+ if (typeof document === "undefined") return;
996
+ const onVisibility = () => {
997
+ if (document.visibilityState === "hidden" && events !== null) void events.flush({ keepalive: true });
998
+ };
999
+ const onPageHide = () => {
1000
+ if (events !== null) void events.flush({ keepalive: true });
1001
+ };
1002
+ document.addEventListener("visibilitychange", onVisibility);
1003
+ addEventListener("pagehide", onPageHide);
1004
+ listeners.push(() => document.removeEventListener("visibilitychange", onVisibility));
1005
+ listeners.push(() => removeEventListener("pagehide", onPageHide));
1006
+ if (options.autocapture === false) return;
1007
+ const capture = { taggedClicks: true, taggedFormSubmits: true, ...options.autocapture };
1008
+ if (pageviews && !pageviewRecorded()) recordPageview();
1009
+ if (historyChanges) {
1010
+ listeners.push(
1011
+ onHistoryChange(() => {
1012
+ if (active && !pageviewRecorded()) recordPageview();
1013
+ })
1014
+ );
1015
+ }
1016
+ if (capture.taggedClicks) {
1017
+ const onClick = (event) => {
1018
+ const target = event.target instanceof Element ? event.target.closest("[data-curious]") : null;
1019
+ if (target === null || target.closest("[data-curious-ignore]") !== null) return;
1020
+ const element = target.getAttribute("data-curious");
1021
+ if (element) queue().system({ name: "$click", properties: { element_name: element } });
1022
+ };
1023
+ document.addEventListener("click", onClick, { capture: true, passive: true });
1024
+ listeners.push(() => document.removeEventListener("click", onClick, { capture: true }));
1025
+ }
1026
+ if (capture.taggedFormSubmits) {
1027
+ const onSubmit = (event) => {
1028
+ const target = event.target instanceof Element ? event.target.closest("[data-curious]") : null;
1029
+ if (target === null || target.closest("[data-curious-ignore]") !== null) return;
1030
+ const element = target.getAttribute("data-curious");
1031
+ if (element) queue().system({ name: "$form_submit", properties: { element_name: element } });
1032
+ };
1033
+ document.addEventListener("submit", onSubmit, { capture: true, passive: true });
1034
+ listeners.push(() => document.removeEventListener("submit", onSubmit, { capture: true }));
1035
+ }
1036
+ }
1037
+ function activate() {
1038
+ if (active) return;
1039
+ identity.enable();
1040
+ active = true;
1041
+ attachLifecycle();
1042
+ tags.start();
1043
+ }
1044
+ const client = {
1045
+ start() {
1046
+ started = true;
1047
+ if (consent === "implicit") activate();
1048
+ else if (consent === "denied" && typeof document !== "undefined") {
1049
+ document.documentElement.classList.remove("curious-loading");
1050
+ }
1051
+ },
1052
+ stop() {
1053
+ started = false;
1054
+ active = false;
1055
+ tags.stop();
1056
+ for (const off of listeners.splice(0)) off();
1057
+ },
1058
+ scan(root) {
1059
+ if (active) tags.scan(root);
1060
+ },
1061
+ async decide(input) {
1062
+ const fallback = (error, requestId) => {
1063
+ onFallback(input.element, error);
1064
+ return { content: input.fallback, served: "fallback", armId: null, armType: null, experimentId: null, experimentStatus: null, error, requestId };
1065
+ };
1066
+ if (!active) return fallback(summary("capability_unavailable", "The SDK is not active (consent or start)", { retryable: false }), null);
1067
+ const userId = identity.activeUserId;
1068
+ const plain = input.identifiers === void 0 && input.attributes === void 0 && input.context === void 0;
1069
+ const hit = plain ? cache.get(userId, input.element) : null;
1070
+ if (hit !== null && sameShape(hit.content, input.fallback)) {
1071
+ const cached = { content: hit.content, served: "cache", armId: hit.armId, armType: hit.armType, experimentId: hit.experimentId, experimentStatus: hit.experimentStatus, requestId: null };
1072
+ onDecision(input.element, cached);
1073
+ return cached;
1074
+ }
1075
+ const key = `${userId}:${input.element}`;
1076
+ const out = plain ? directInFlight.get(key) : void 0;
1077
+ const pending = out ?? requestDecision(userId, input);
1078
+ if (plain && out === void 0) {
1079
+ directInFlight.set(key, pending);
1080
+ void pending.then(() => {
1081
+ if (directInFlight.get(key) === pending) directInFlight.delete(key);
1082
+ });
1083
+ }
1084
+ const outcome = await pending;
1085
+ if (!active || identity.activeUserId !== userId) {
1086
+ return fallback(summary("capability_unavailable", "The SDK was stopped, or the visitor changed, while the decision was in flight", { retryable: false }), outcome.requestId);
1087
+ }
1088
+ if (!outcome.ok) return fallback(outcome.error, outcome.requestId);
1089
+ if (!sameShape(outcome.content, input.fallback)) {
1090
+ return fallback(summary("content_shape_mismatch", "Served content does not match the fallback's shape", { retryable: false, status: 200 }), outcome.requestId);
1091
+ }
1092
+ const result = { content: outcome.content, served: out === void 0 ? "curious" : "cache", armId: outcome.armId, armType: outcome.armType, experimentId: outcome.experimentId, experimentStatus: outcome.experimentStatus, requestId: outcome.requestId };
1093
+ if (plain && outcome.experimentId !== null && outcome.experimentStatus !== null) {
1094
+ cache.set(userId, input.element, { content: outcome.content, armId: outcome.armId, armType: outcome.armType, experimentId: outcome.experimentId, experimentStatus: outcome.experimentStatus });
1095
+ } else if (input.identifiers !== void 0 || input.attributes !== void 0) {
1096
+ cache.remove(userId, input.element);
1097
+ }
1098
+ onDecision(input.element, result);
1099
+ return result;
1100
+ },
1101
+ track(input) {
1102
+ if (!active) {
1103
+ onEventDrop(summary("capability_unavailable", "Events are not collected before consent", { retryable: false }));
1104
+ return { id: "", queued: false };
1105
+ }
1106
+ return queue().track(input);
1107
+ },
1108
+ flush(flushOptions) {
1109
+ if (events === null) return Promise.resolve({ sent: 0, duplicates: 0, failed: 0, pending: 0 });
1110
+ return events.flush(flushOptions);
1111
+ },
1112
+ page() {
1113
+ if (!pageviews) return { id: "", queued: false };
1114
+ if (!active) {
1115
+ onEventDrop(summary("capability_unavailable", "Events are not collected before consent", { retryable: false }));
1116
+ return { id: "", queued: false };
1117
+ }
1118
+ if (typeof location === "undefined") return { id: "", queued: false };
1119
+ if (historyChanges && pageviewRecorded()) return { id: "", queued: false };
1120
+ return recordPageview();
1121
+ },
1122
+ // After the customer's backend has linked the anonymous id with a secret
1123
+ // key: flush anonymous events, switch the active user, forget cached
1124
+ // assignments, decide tags again for the known user.
1125
+ async identify(userId) {
1126
+ if (typeof userId !== "string" || userId.trim().length === 0) {
1127
+ throw new CuriousError(summary("invalid_input", "identify: userId is required", { retryable: false }));
1128
+ }
1129
+ if (!active) throw new CuriousError(summary("capability_unavailable", "The SDK is not active (consent or start)", { retryable: false }));
1130
+ if (events !== null) await events.flush({ keepalive: true });
1131
+ identity.setKnown(userId);
1132
+ cache.clear();
1133
+ tags.resetDecisions();
1134
+ onIdentityChange(userId);
1135
+ return { userId };
1136
+ },
1137
+ // Logout: a bounded flush, then a fresh anonymous history. Never unlinks
1138
+ // anything server-side, and a failed flush never prevents the isolation.
1139
+ async reset() {
1140
+ if (events !== null) {
1141
+ try {
1142
+ await events.flush({ keepalive: true });
1143
+ } catch {
1144
+ }
1145
+ events.clear();
1146
+ }
1147
+ if (active) identity.reset();
1148
+ cache.clear();
1149
+ tags.resetDecisions();
1150
+ visitRecorded = false;
1151
+ onIdentityChange(null);
1152
+ },
1153
+ grantConsent() {
1154
+ consent = "implicit";
1155
+ if (started) activate();
1156
+ },
1157
+ denyConsent() {
1158
+ consent = "denied";
1159
+ active = false;
1160
+ tags.stop();
1161
+ for (const off of listeners.splice(0)) off();
1162
+ events?.clear();
1163
+ cache.clear();
1164
+ identity.clear();
1165
+ visitRecorded = false;
1166
+ onIdentityChange(null);
1167
+ },
1168
+ get anonymousId() {
1169
+ return identity.anonymousId;
1170
+ },
1171
+ get userId() {
1172
+ return identity.knownUserId;
1173
+ }
1174
+ };
1175
+ return client;
1176
+ }
1177
+ function sameShape(content, fallback) {
1178
+ if (fallback === null || fallback === void 0) return true;
1179
+ if (content === null || content === void 0) return false;
1180
+ if (Array.isArray(fallback) || Array.isArray(content)) {
1181
+ if (!Array.isArray(fallback) || !Array.isArray(content)) return false;
1182
+ return fallback.length === 0 || content.every((item) => sameShape(item, fallback[0]));
1183
+ }
1184
+ if (typeof fallback !== "object") return typeof content === typeof fallback;
1185
+ if (typeof content !== "object") return false;
1186
+ for (const [key, want] of Object.entries(fallback)) {
1187
+ if (!Object.prototype.hasOwnProperty.call(content, key)) return false;
1188
+ if (!sameShape(content[key], want)) return false;
1189
+ }
1190
+ return true;
1191
+ }
1192
+ function guarded(hook) {
1193
+ return (...args) => {
1194
+ if (hook === void 0) return;
1195
+ try {
1196
+ hook(...args);
1197
+ } catch {
1198
+ }
1199
+ };
1200
+ }
1201
+ export {
1202
+ CuriousError,
1203
+ SDK_VERSION,
1204
+ createCurious
1205
+ };
1206
+ //# sourceMappingURL=index.js.map