@trycurious/js 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +104 -2
- package/dist/curious.iife.js +3 -0
- package/dist/curious.iife.js.map +1 -0
- package/dist/index.d.ts +127 -0
- package/dist/index.js +1086 -0
- package/dist/index.js.map +1 -0
- package/package.json +49 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1086 @@
|
|
|
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/events.ts
|
|
230
|
+
var DEFAULTS = {
|
|
231
|
+
flushIntervalMs: 5e3,
|
|
232
|
+
flushCount: 20,
|
|
233
|
+
queueLimit: 100,
|
|
234
|
+
keepaliveBodyBytes: 48 * 1024,
|
|
235
|
+
requestTimeoutMs: 1e4,
|
|
236
|
+
maxAttempts: 5,
|
|
237
|
+
itemCap: 200
|
|
238
|
+
};
|
|
239
|
+
var QUEUE_KEY = "curious:events";
|
|
240
|
+
var RESERVED_PREFIX = "$";
|
|
241
|
+
var EventQueue = class {
|
|
242
|
+
constructor(options) {
|
|
243
|
+
this.sequence = 0;
|
|
244
|
+
this.entries = [];
|
|
245
|
+
this.timer = null;
|
|
246
|
+
this.inFlight = null;
|
|
247
|
+
this.o = {
|
|
248
|
+
transport: options.transport,
|
|
249
|
+
userId: options.userId,
|
|
250
|
+
flushIntervalMs: options.flushIntervalMs ?? DEFAULTS.flushIntervalMs,
|
|
251
|
+
flushCount: options.flushCount ?? DEFAULTS.flushCount,
|
|
252
|
+
queueLimit: options.queueLimit ?? DEFAULTS.queueLimit,
|
|
253
|
+
keepaliveBodyBytes: options.keepaliveBodyBytes ?? DEFAULTS.keepaliveBodyBytes,
|
|
254
|
+
requestTimeoutMs: options.requestTimeoutMs ?? DEFAULTS.requestTimeoutMs,
|
|
255
|
+
maxAttempts: options.maxAttempts ?? DEFAULTS.maxAttempts,
|
|
256
|
+
onEventDrop: options.onEventDrop
|
|
257
|
+
};
|
|
258
|
+
this.store = options.storage === void 0 ? safeStorage("sessionStorage") : options.storage;
|
|
259
|
+
this.now = options.now ?? Date.now;
|
|
260
|
+
this.sessionId = Math.random().toString(36).slice(2, 10) + this.now().toString(36);
|
|
261
|
+
this.restore();
|
|
262
|
+
}
|
|
263
|
+
get size() {
|
|
264
|
+
return this.entries.length;
|
|
265
|
+
}
|
|
266
|
+
/** Customer events; `$` names are reserved for the SDK's own capture path. */
|
|
267
|
+
track(input) {
|
|
268
|
+
if (typeof input.name === "string" && input.name.startsWith(RESERVED_PREFIX)) {
|
|
269
|
+
throw new CuriousError(summary("invalid_input", "Event names starting with $ are reserved", { retryable: false }));
|
|
270
|
+
}
|
|
271
|
+
return this.enqueue(input);
|
|
272
|
+
}
|
|
273
|
+
/** The SDK's own autocapture events (`$pageview`, `$click`, `$form_submit`). */
|
|
274
|
+
system(input) {
|
|
275
|
+
return this.enqueue(input);
|
|
276
|
+
}
|
|
277
|
+
enqueue(input) {
|
|
278
|
+
if (typeof input.name !== "string" || input.name.trim().length === 0) {
|
|
279
|
+
throw new CuriousError(summary("invalid_input", "track: name is required", { retryable: false }));
|
|
280
|
+
}
|
|
281
|
+
const event = {
|
|
282
|
+
id: input.id ?? `browser:${this.sessionId}:${++this.sequence}:${Math.random().toString(36).slice(2, 8)}`,
|
|
283
|
+
user_id: this.o.userId(),
|
|
284
|
+
name: input.name
|
|
285
|
+
};
|
|
286
|
+
if (input.value !== void 0) event.value = input.value;
|
|
287
|
+
if (input.properties !== void 0) event.properties = input.properties;
|
|
288
|
+
if (input.context !== void 0) event.context = input.context;
|
|
289
|
+
if (input.timestamp !== void 0) {
|
|
290
|
+
event.timestamp = input.timestamp instanceof Date ? input.timestamp.toISOString() : input.timestamp;
|
|
291
|
+
}
|
|
292
|
+
if (this.entries.length >= this.o.queueLimit) {
|
|
293
|
+
this.o.onEventDrop(summary("queue_full", `Event queue is full (${this.o.queueLimit}); event not queued`, { retryable: true }));
|
|
294
|
+
return { id: event.id, queued: false };
|
|
295
|
+
}
|
|
296
|
+
this.entries.push({ event, attempts: 0 });
|
|
297
|
+
this.persist();
|
|
298
|
+
if (this.entries.length >= this.o.flushCount) {
|
|
299
|
+
void this.flush();
|
|
300
|
+
} else if (this.timer === null) {
|
|
301
|
+
this.timer = setTimeout(() => {
|
|
302
|
+
this.timer = null;
|
|
303
|
+
void this.flush();
|
|
304
|
+
}, this.o.flushIntervalMs);
|
|
305
|
+
}
|
|
306
|
+
return { id: event.id, queued: true };
|
|
307
|
+
}
|
|
308
|
+
/** Deliver what is queued. `keepalive` is for lifecycle flushes (hidden, pagehide, before identify/reset). */
|
|
309
|
+
flush(options = {}) {
|
|
310
|
+
if (this.inFlight === null) {
|
|
311
|
+
this.inFlight = this.run(options.keepalive === true).finally(() => {
|
|
312
|
+
this.inFlight = null;
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
return this.inFlight;
|
|
316
|
+
}
|
|
317
|
+
/** reset()/denyConsent(): forget everything queued. */
|
|
318
|
+
clear() {
|
|
319
|
+
this.entries = [];
|
|
320
|
+
this.persist();
|
|
321
|
+
}
|
|
322
|
+
async run(keepalive) {
|
|
323
|
+
if (this.timer !== null) {
|
|
324
|
+
clearTimeout(this.timer);
|
|
325
|
+
this.timer = null;
|
|
326
|
+
}
|
|
327
|
+
const totals = { sent: 0, duplicates: 0, failed: 0, pending: 0 };
|
|
328
|
+
while (this.entries.length > 0) {
|
|
329
|
+
const batch = this.takeBatch(keepalive);
|
|
330
|
+
if (batch.length === 0) break;
|
|
331
|
+
const retry = await this.deliver(batch, keepalive, totals);
|
|
332
|
+
if (retry.length > 0) {
|
|
333
|
+
this.entries.unshift(...retry);
|
|
334
|
+
this.persist();
|
|
335
|
+
break;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
totals.pending = this.entries.length;
|
|
339
|
+
this.persist();
|
|
340
|
+
return totals;
|
|
341
|
+
}
|
|
342
|
+
// Up to the API's item cap, and under the keepalive body budget when the
|
|
343
|
+
// flush rides keepalive.
|
|
344
|
+
takeBatch(keepalive) {
|
|
345
|
+
const batch = [];
|
|
346
|
+
let bytes = 2;
|
|
347
|
+
while (this.entries.length > 0 && batch.length < DEFAULTS.itemCap) {
|
|
348
|
+
const next = this.entries[0];
|
|
349
|
+
const size = JSON.stringify(next.event).length + 1;
|
|
350
|
+
if (keepalive && batch.length > 0 && bytes + size > this.o.keepaliveBodyBytes) break;
|
|
351
|
+
batch.push(this.entries.shift());
|
|
352
|
+
bytes += size;
|
|
353
|
+
}
|
|
354
|
+
return batch;
|
|
355
|
+
}
|
|
356
|
+
async deliver(batch, keepalive, totals) {
|
|
357
|
+
for (const item of batch) item.attempts += 1;
|
|
358
|
+
let response;
|
|
359
|
+
try {
|
|
360
|
+
response = await this.o.transport.post("/events", { events: batch.map((e) => e.event) }, {
|
|
361
|
+
timeoutMs: this.o.requestTimeoutMs,
|
|
362
|
+
keepalive
|
|
363
|
+
});
|
|
364
|
+
} catch (error) {
|
|
365
|
+
return this.retryOrDrop(batch, error.summary, totals);
|
|
366
|
+
}
|
|
367
|
+
if (response.status !== 200) {
|
|
368
|
+
const failure = summarizeHttpError(response.status, response.body, response.requestId);
|
|
369
|
+
if (!failure.retryable) {
|
|
370
|
+
for (const item of batch) {
|
|
371
|
+
totals.failed += 1;
|
|
372
|
+
this.o.onEventDrop(summary("event_rejected", failure.message, { ...failure, retryable: false }));
|
|
373
|
+
}
|
|
374
|
+
return [];
|
|
375
|
+
}
|
|
376
|
+
return this.retryOrDrop(batch, failure, totals);
|
|
377
|
+
}
|
|
378
|
+
const results = response.body?.results;
|
|
379
|
+
if (!Array.isArray(results)) {
|
|
380
|
+
return this.retryOrDrop(batch, summary("protocol_error", "Batch response carried no results", { retryable: true }), totals);
|
|
381
|
+
}
|
|
382
|
+
const retry = [];
|
|
383
|
+
batch.forEach((item, index) => {
|
|
384
|
+
const result = results[index];
|
|
385
|
+
if (result === void 0 || result === null || typeof result !== "object" || result.index !== index) {
|
|
386
|
+
retry.push(...this.retryOrDrop([item], summary("protocol_error", "Batch response had no result for this event", { retryable: true }), totals));
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
if (result.status === "ok") {
|
|
390
|
+
totals.sent += 1;
|
|
391
|
+
if (result.duplicate === true) totals.duplicates += 1;
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
const itemError = summarizeHttpError(result.error === "internal_error" ? 500 : 400, result, response.requestId);
|
|
395
|
+
if (itemError.retryable && item.attempts < this.o.maxAttempts) {
|
|
396
|
+
retry.push(item);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
totals.failed += 1;
|
|
400
|
+
this.o.onEventDrop(summary("event_rejected", itemError.message, { ...itemError, retryable: false }));
|
|
401
|
+
});
|
|
402
|
+
return retry;
|
|
403
|
+
}
|
|
404
|
+
retryOrDrop(batch, failure, totals) {
|
|
405
|
+
const retry = [];
|
|
406
|
+
for (const item of batch) {
|
|
407
|
+
if (item.attempts < this.o.maxAttempts) {
|
|
408
|
+
retry.push(item);
|
|
409
|
+
} else {
|
|
410
|
+
totals.failed += 1;
|
|
411
|
+
this.o.onEventDrop(summary("event_rejected", `Gave up after ${item.attempts} attempts: ${failure.message}`, {
|
|
412
|
+
...failure,
|
|
413
|
+
retryable: false
|
|
414
|
+
}));
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return retry;
|
|
418
|
+
}
|
|
419
|
+
persist() {
|
|
420
|
+
if (this.store === null) return;
|
|
421
|
+
safeSet(this.store, QUEUE_KEY, JSON.stringify(this.entries));
|
|
422
|
+
}
|
|
423
|
+
restore() {
|
|
424
|
+
if (this.store === null) return;
|
|
425
|
+
const raw = safeGet(this.store, QUEUE_KEY);
|
|
426
|
+
if (raw === null) return;
|
|
427
|
+
try {
|
|
428
|
+
const parsed = JSON.parse(raw);
|
|
429
|
+
if (Array.isArray(parsed)) this.entries = parsed.filter((e) => e && typeof e.event?.id === "string").slice(0, this.o.queueLimit);
|
|
430
|
+
} catch {
|
|
431
|
+
this.entries = [];
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
// src/tags.ts
|
|
437
|
+
var TAG_ATTRIBUTE = "data-curious";
|
|
438
|
+
var IGNORE_ATTRIBUTE = "data-curious-ignore";
|
|
439
|
+
var CRITICAL_ATTRIBUTE = "data-curious-critical";
|
|
440
|
+
var LOADING_CLASS = "curious-loading";
|
|
441
|
+
var DEFAULT_ROOT_MARGIN = "200% 0px";
|
|
442
|
+
var ELEMENT_NODE = 1;
|
|
443
|
+
var TEXT_NODE = 3;
|
|
444
|
+
var VOID_ELEMENTS = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "EMBED", "HR", "IMG", "INPUT", "LINK", "META", "SOURCE", "TRACK", "WBR"]);
|
|
445
|
+
function textSlot(node) {
|
|
446
|
+
if (VOID_ELEMENTS.has(node.tagName.toUpperCase())) return { unsupported: "void_element" };
|
|
447
|
+
let text = null;
|
|
448
|
+
for (const child of Array.from(node.childNodes)) {
|
|
449
|
+
if (child.nodeType === ELEMENT_NODE) return { unsupported: "child_elements" };
|
|
450
|
+
if (child.nodeType !== TEXT_NODE) continue;
|
|
451
|
+
if (text !== null) return { unsupported: "several_text_nodes" };
|
|
452
|
+
text = child;
|
|
453
|
+
}
|
|
454
|
+
return { text };
|
|
455
|
+
}
|
|
456
|
+
var TagRuntime = class {
|
|
457
|
+
constructor(options) {
|
|
458
|
+
this.nodes = /* @__PURE__ */ new Map();
|
|
459
|
+
this.byElement = /* @__PURE__ */ new Map();
|
|
460
|
+
this.pending = /* @__PURE__ */ new Set();
|
|
461
|
+
// Nodes whose text the page took back after a decision. Kept apart from
|
|
462
|
+
// `nodes` so the promise survives the node being removed and attached
|
|
463
|
+
// again, and weakly so a discarded node can be collected.
|
|
464
|
+
this.released = /* @__PURE__ */ new WeakSet();
|
|
465
|
+
this.intersection = null;
|
|
466
|
+
this.mutation = null;
|
|
467
|
+
this.frame = null;
|
|
468
|
+
this.o = options;
|
|
469
|
+
}
|
|
470
|
+
start() {
|
|
471
|
+
if (typeof IntersectionObserver === "function") {
|
|
472
|
+
this.intersection = new IntersectionObserver((entries) => {
|
|
473
|
+
for (const entry of entries) {
|
|
474
|
+
if (!entry.isIntersecting) continue;
|
|
475
|
+
const tagged = this.nodes.get(entry.target);
|
|
476
|
+
if (tagged === void 0 || tagged.state !== "idle") continue;
|
|
477
|
+
tagged.state = "pending";
|
|
478
|
+
this.pending.add(tagged.element);
|
|
479
|
+
this.intersection?.unobserve(entry.target);
|
|
480
|
+
}
|
|
481
|
+
this.schedule();
|
|
482
|
+
}, { rootMargin: this.o.rootMargin ?? DEFAULT_ROOT_MARGIN, threshold: 0 });
|
|
483
|
+
}
|
|
484
|
+
if (typeof MutationObserver === "function") {
|
|
485
|
+
this.mutation = new MutationObserver((records) => {
|
|
486
|
+
for (const record of records) {
|
|
487
|
+
if (record.type === "childList") {
|
|
488
|
+
for (const removed of record.removedNodes) {
|
|
489
|
+
if (removed instanceof Element) this.forgetRemoved(removed);
|
|
490
|
+
}
|
|
491
|
+
for (const added of record.addedNodes) {
|
|
492
|
+
if (added instanceof Element) this.scan(added);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
const target = record.target instanceof Element ? record.target : record.target.parentElement;
|
|
496
|
+
if (target !== null) this.detectDrift(target);
|
|
497
|
+
}
|
|
498
|
+
});
|
|
499
|
+
const root = this.o.root ?? document;
|
|
500
|
+
this.mutation.observe(root instanceof Document ? root.documentElement : root, {
|
|
501
|
+
childList: true,
|
|
502
|
+
subtree: true,
|
|
503
|
+
characterData: true
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
this.scan(this.o.root ?? document);
|
|
507
|
+
}
|
|
508
|
+
stop() {
|
|
509
|
+
this.intersection?.disconnect();
|
|
510
|
+
this.mutation?.disconnect();
|
|
511
|
+
this.intersection = null;
|
|
512
|
+
this.mutation = null;
|
|
513
|
+
if (this.frame !== null) clearTimeout(this.frame);
|
|
514
|
+
this.frame = null;
|
|
515
|
+
this.nodes.clear();
|
|
516
|
+
this.byElement.clear();
|
|
517
|
+
this.pending.clear();
|
|
518
|
+
this.released = /* @__PURE__ */ new WeakSet();
|
|
519
|
+
}
|
|
520
|
+
/** Register every tagged node under `root` (the whole document by default). Safe to call repeatedly. */
|
|
521
|
+
scan(root = this.o.root ?? document) {
|
|
522
|
+
const candidates = [];
|
|
523
|
+
if (root instanceof Element && root.hasAttribute(TAG_ATTRIBUTE)) candidates.push(root);
|
|
524
|
+
candidates.push(...Array.from(root.querySelectorAll(`[${TAG_ATTRIBUTE}]`)));
|
|
525
|
+
for (const node of candidates) {
|
|
526
|
+
if (this.nodes.has(node) || this.released.has(node) || node.closest(`[${IGNORE_ATTRIBUTE}]`) !== null) continue;
|
|
527
|
+
const element = (node.getAttribute(TAG_ATTRIBUTE) ?? "").trim();
|
|
528
|
+
if (element.length === 0) continue;
|
|
529
|
+
const tagged = { element, node, control: node.textContent ?? "", applied: null, state: "idle", drifted: false };
|
|
530
|
+
this.nodes.set(node, tagged);
|
|
531
|
+
const slot = textSlot(node);
|
|
532
|
+
if ("unsupported" in slot) {
|
|
533
|
+
this.refuse(tagged, slot.unsupported);
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
let set = this.byElement.get(element);
|
|
537
|
+
if (set === void 0) {
|
|
538
|
+
set = /* @__PURE__ */ new Set();
|
|
539
|
+
this.byElement.set(element, set);
|
|
540
|
+
}
|
|
541
|
+
set.add(tagged);
|
|
542
|
+
if (this.intersection !== null) this.intersection.observe(node);
|
|
543
|
+
else {
|
|
544
|
+
tagged.state = "pending";
|
|
545
|
+
this.pending.add(element);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
if (this.pending.size > 0) this.schedule();
|
|
549
|
+
}
|
|
550
|
+
/** Apply decided content to every node of an element that can take it. Non-string content leaves the control in place. */
|
|
551
|
+
apply(element, content) {
|
|
552
|
+
const set = this.byElement.get(element);
|
|
553
|
+
if (set === void 0) return "no_node";
|
|
554
|
+
if (typeof content !== "string") {
|
|
555
|
+
for (const tagged of set) {
|
|
556
|
+
if (!tagged.drifted) tagged.state = "fallback";
|
|
557
|
+
}
|
|
558
|
+
return "not_text";
|
|
559
|
+
}
|
|
560
|
+
let applied = false;
|
|
561
|
+
for (const tagged of Array.from(set)) {
|
|
562
|
+
if (!tagged.node.isConnected) {
|
|
563
|
+
this.forget(tagged);
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
if (tagged.drifted) continue;
|
|
567
|
+
const slot = textSlot(tagged.node);
|
|
568
|
+
if ("unsupported" in slot) {
|
|
569
|
+
this.refuse(tagged, slot.unsupported);
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
if (slot.text === null) tagged.node.appendChild(tagged.node.ownerDocument.createTextNode(content));
|
|
573
|
+
else if (slot.text.data !== content) slot.text.data = content;
|
|
574
|
+
tagged.applied = content;
|
|
575
|
+
tagged.state = "decided";
|
|
576
|
+
this.revealCritical(tagged.node);
|
|
577
|
+
applied = true;
|
|
578
|
+
}
|
|
579
|
+
return applied ? "applied" : "no_node";
|
|
580
|
+
}
|
|
581
|
+
/** Leave the control visible and mark the element as decided against. */
|
|
582
|
+
fallback(element) {
|
|
583
|
+
const set = this.byElement.get(element);
|
|
584
|
+
if (set === void 0) return;
|
|
585
|
+
for (const tagged of set) {
|
|
586
|
+
tagged.state = "fallback";
|
|
587
|
+
this.revealCritical(tagged.node);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
/** Forget decisions (identify/reset) so the nodes can be decided again for the new user. */
|
|
591
|
+
resetDecisions() {
|
|
592
|
+
for (const tagged of Array.from(this.nodes.values())) {
|
|
593
|
+
if (!tagged.node.isConnected) {
|
|
594
|
+
this.forget(tagged);
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
if ((tagged.state === "decided" || tagged.state === "fallback" || tagged.state === "pending") && !tagged.drifted) {
|
|
598
|
+
tagged.state = "idle";
|
|
599
|
+
tagged.applied = null;
|
|
600
|
+
this.intersection?.observe(tagged.node);
|
|
601
|
+
if (this.intersection === null) {
|
|
602
|
+
tagged.state = "pending";
|
|
603
|
+
this.pending.add(tagged.element);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
if (this.pending.size > 0) this.schedule();
|
|
608
|
+
}
|
|
609
|
+
elements() {
|
|
610
|
+
return Array.from(this.byElement.keys());
|
|
611
|
+
}
|
|
612
|
+
schedule() {
|
|
613
|
+
if (this.frame !== null || this.pending.size === 0) return;
|
|
614
|
+
this.frame = setTimeout(() => {
|
|
615
|
+
this.frame = null;
|
|
616
|
+
const batch = Array.from(this.pending).filter((element) => this.hasWritablePendingNode(element));
|
|
617
|
+
this.pending.clear();
|
|
618
|
+
if (batch.length > 0) this.o.onPending(batch);
|
|
619
|
+
}, 0);
|
|
620
|
+
}
|
|
621
|
+
// True when a node that neared the viewport (state `pending`) is still on
|
|
622
|
+
// the page and can still take text. A plain sibling that is still off
|
|
623
|
+
// screen does not count: it asks for the decision when it gets near. Nodes
|
|
624
|
+
// that can no longer take text are refused here, and removed ones
|
|
625
|
+
// forgotten, before a decision is requested on their account.
|
|
626
|
+
hasWritablePendingNode(element) {
|
|
627
|
+
const set = this.byElement.get(element);
|
|
628
|
+
if (set === void 0) return false;
|
|
629
|
+
let writable = false;
|
|
630
|
+
for (const tagged of Array.from(set)) {
|
|
631
|
+
if (tagged.state !== "pending") continue;
|
|
632
|
+
if (!tagged.node.isConnected) {
|
|
633
|
+
this.forget(tagged);
|
|
634
|
+
continue;
|
|
635
|
+
}
|
|
636
|
+
const slot = textSlot(tagged.node);
|
|
637
|
+
if ("unsupported" in slot) this.refuse(tagged, slot.unsupported);
|
|
638
|
+
else writable = true;
|
|
639
|
+
}
|
|
640
|
+
return writable;
|
|
641
|
+
}
|
|
642
|
+
forgetRemoved(removed) {
|
|
643
|
+
const candidates = [removed, ...Array.from(removed.querySelectorAll(`[${TAG_ATTRIBUTE}]`))];
|
|
644
|
+
for (const node of candidates) {
|
|
645
|
+
const tagged = this.nodes.get(node);
|
|
646
|
+
if (tagged !== void 0 && !node.isConnected) this.forget(tagged);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
// Drop a node the page has removed. If the same node is attached again, the
|
|
650
|
+
// MutationObserver scans it afresh.
|
|
651
|
+
forget(tagged) {
|
|
652
|
+
this.nodes.delete(tagged.node);
|
|
653
|
+
this.byElement.get(tagged.element)?.delete(tagged);
|
|
654
|
+
this.intersection?.unobserve(tagged.node);
|
|
655
|
+
}
|
|
656
|
+
// Take a node out of play for good: never observed, never decided, never
|
|
657
|
+
// written, reported once.
|
|
658
|
+
refuse(tagged, reason) {
|
|
659
|
+
tagged.state = "unsupported";
|
|
660
|
+
this.byElement.get(tagged.element)?.delete(tagged);
|
|
661
|
+
this.intersection?.unobserve(tagged.node);
|
|
662
|
+
this.revealCritical(tagged.node);
|
|
663
|
+
this.o.onUnsupported(tagged.element, reason);
|
|
664
|
+
}
|
|
665
|
+
detectDrift(target) {
|
|
666
|
+
const node = target.closest(`[${TAG_ATTRIBUTE}]`);
|
|
667
|
+
if (node === null) return;
|
|
668
|
+
const tagged = this.nodes.get(node);
|
|
669
|
+
if (tagged === void 0 || tagged.state !== "decided" || tagged.drifted) return;
|
|
670
|
+
if ((node.textContent ?? "") !== tagged.applied) {
|
|
671
|
+
tagged.drifted = true;
|
|
672
|
+
this.released.add(node);
|
|
673
|
+
this.o.onDrift(tagged.element);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
revealCritical(node) {
|
|
677
|
+
if (node.hasAttribute(CRITICAL_ATTRIBUTE)) {
|
|
678
|
+
document.documentElement.classList.remove(LOADING_CLASS);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
|
|
683
|
+
// src/version.ts
|
|
684
|
+
var SDK_VERSION = "0.1.0";
|
|
685
|
+
|
|
686
|
+
// src/transport.ts
|
|
687
|
+
var MAX_RESPONSE_BYTES = 1048576;
|
|
688
|
+
var Transport = class {
|
|
689
|
+
constructor(options) {
|
|
690
|
+
const fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch.bind(globalThis) : void 0);
|
|
691
|
+
if (fetchImpl === void 0) {
|
|
692
|
+
throw new CuriousError(summary("capability_unavailable", "fetch is not available", { retryable: false }));
|
|
693
|
+
}
|
|
694
|
+
this.fetchImpl = fetchImpl;
|
|
695
|
+
this.baseUrl = options.baseUrl.replace(/\/+$/, "");
|
|
696
|
+
this.headers = {
|
|
697
|
+
authorization: `Bearer ${options.publishableKey}`,
|
|
698
|
+
"content-type": "application/json",
|
|
699
|
+
"x-curious-client": `browser-js/${SDK_VERSION}`
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
// POST one JSON body within the deadline. Throws for a timeout, a network
|
|
703
|
+
// failure or an unreadable response; returns every HTTP status.
|
|
704
|
+
async post(path, body, options) {
|
|
705
|
+
const controller = new AbortController();
|
|
706
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs);
|
|
707
|
+
let response;
|
|
708
|
+
try {
|
|
709
|
+
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
710
|
+
method: "POST",
|
|
711
|
+
headers: this.headers,
|
|
712
|
+
body: JSON.stringify(body),
|
|
713
|
+
signal: controller.signal,
|
|
714
|
+
keepalive: options.keepalive === true,
|
|
715
|
+
credentials: "omit",
|
|
716
|
+
mode: "cors"
|
|
717
|
+
});
|
|
718
|
+
} catch (error) {
|
|
719
|
+
if (controller.signal.aborted) {
|
|
720
|
+
throw new CuriousError(summary("timeout", `No response within ${options.timeoutMs}ms`));
|
|
721
|
+
}
|
|
722
|
+
throw new CuriousError(summary("network_error", describe(error)));
|
|
723
|
+
} finally {
|
|
724
|
+
clearTimeout(timer);
|
|
725
|
+
}
|
|
726
|
+
const requestId = response.headers.get("x-request-id");
|
|
727
|
+
const retryAfterMs = parseRetryAfter(response.headers.get("retry-after"));
|
|
728
|
+
let text;
|
|
729
|
+
try {
|
|
730
|
+
text = await response.text();
|
|
731
|
+
} catch (error) {
|
|
732
|
+
throw new CuriousError(summary("network_error", describe(error), { status: response.status }));
|
|
733
|
+
}
|
|
734
|
+
if (text.length > MAX_RESPONSE_BYTES) {
|
|
735
|
+
throw new CuriousError(summary("protocol_error", "Response exceeds the size bound", { status: response.status, retryable: false }));
|
|
736
|
+
}
|
|
737
|
+
let parsed = null;
|
|
738
|
+
if (text.length > 0) {
|
|
739
|
+
try {
|
|
740
|
+
parsed = JSON.parse(text);
|
|
741
|
+
} catch {
|
|
742
|
+
throw new CuriousError(summary("protocol_error", `Response ${response.status} was not JSON`, {
|
|
743
|
+
status: response.status,
|
|
744
|
+
retryable: false
|
|
745
|
+
}));
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
return { status: response.status, requestId, retryAfterMs, body: parsed };
|
|
749
|
+
}
|
|
750
|
+
};
|
|
751
|
+
function describe(error) {
|
|
752
|
+
return error instanceof Error && error.message ? `Request failed: ${error.message}` : "Request failed";
|
|
753
|
+
}
|
|
754
|
+
function parseRetryAfter(value) {
|
|
755
|
+
if (value === null) return null;
|
|
756
|
+
const seconds = Number(value);
|
|
757
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1e3);
|
|
758
|
+
const at = Date.parse(value);
|
|
759
|
+
return Number.isNaN(at) ? null : Math.max(0, at - Date.now());
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// src/client.ts
|
|
763
|
+
var DEFAULTS2 = { baseUrl: "https://api.trycurious.ai/v1", decideTimeoutMs: 1e3 };
|
|
764
|
+
var PUBLISHABLE_PREFIX = "curious_pk_";
|
|
765
|
+
var DECIDE_BATCH_LIMIT = 50;
|
|
766
|
+
var BATCH_ITEM_STATUS = /* @__PURE__ */ new Map([
|
|
767
|
+
["internal_error", 500],
|
|
768
|
+
["decision_unavailable", 503],
|
|
769
|
+
["idempotency_error", 409],
|
|
770
|
+
["lock_timeout", 409],
|
|
771
|
+
["conflict", 409]
|
|
772
|
+
]);
|
|
773
|
+
var UNSUPPORTED_MESSAGE = {
|
|
774
|
+
child_elements: "The tagged element contains other elements; the SDK replaces plain text only. Tag the innermost element that holds only text",
|
|
775
|
+
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",
|
|
776
|
+
void_element: "The tagged element cannot hold text (an input, an image or another empty element); tag an element whose content is text"
|
|
777
|
+
};
|
|
778
|
+
function createCurious(options) {
|
|
779
|
+
if (typeof options.publishableKey !== "string" || options.publishableKey.length === 0) {
|
|
780
|
+
throw new CuriousError(summary("invalid_configuration", "publishableKey is required", { retryable: false }));
|
|
781
|
+
}
|
|
782
|
+
if (!options.publishableKey.startsWith(PUBLISHABLE_PREFIX)) {
|
|
783
|
+
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 }));
|
|
784
|
+
}
|
|
785
|
+
const timeoutMs = Math.min(options.decideTimeoutMs ?? DEFAULTS2.decideTimeoutMs, DEFAULTS2.decideTimeoutMs * 10);
|
|
786
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
787
|
+
throw new CuriousError(summary("invalid_configuration", "decideTimeoutMs must be a positive number", { retryable: false }));
|
|
788
|
+
}
|
|
789
|
+
const onFallback = guarded(options.onFallback);
|
|
790
|
+
const onDecision = guarded(options.onDecision);
|
|
791
|
+
const onEventDrop = guarded(options.onEventDrop);
|
|
792
|
+
const onIdentityChange = guarded(options.onIdentityChange);
|
|
793
|
+
const transport = new Transport({ publishableKey: options.publishableKey, baseUrl: options.baseUrl ?? DEFAULTS2.baseUrl, fetch: options.fetch });
|
|
794
|
+
const identity = new Identity({
|
|
795
|
+
...options.cookieMaxAgeSeconds === void 0 ? {} : { cookieMaxAgeSeconds: options.cookieMaxAgeSeconds },
|
|
796
|
+
document: options.document,
|
|
797
|
+
storage: options.storage
|
|
798
|
+
});
|
|
799
|
+
const cache = new AssignmentCache({ publishableKey: options.publishableKey, ...options.cacheTtlMs === void 0 ? {} : { ttlMs: options.cacheTtlMs }, ...options.storage === void 0 ? {} : { storage: options.storage } });
|
|
800
|
+
let consent = options.consent ?? "implicit";
|
|
801
|
+
let started = false;
|
|
802
|
+
let active = false;
|
|
803
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
804
|
+
let events = null;
|
|
805
|
+
const listeners = [];
|
|
806
|
+
const tags = new TagRuntime({
|
|
807
|
+
...options.rootMargin === void 0 ? {} : { rootMargin: options.rootMargin },
|
|
808
|
+
onPending: (elements) => void decideTagged(elements),
|
|
809
|
+
onDrift: (element) => onFallback(element, summary("mutation_drift", "Applied content was rewritten by the page; the SDK will not reapply it", { retryable: false })),
|
|
810
|
+
onUnsupported: (element, reason) => onFallback(element, summary("content_shape_mismatch", UNSUPPORTED_MESSAGE[reason], { retryable: false }))
|
|
811
|
+
});
|
|
812
|
+
function pageContext() {
|
|
813
|
+
const base = {};
|
|
814
|
+
if (typeof location !== "undefined") base.path = location.pathname;
|
|
815
|
+
if (typeof navigator !== "undefined" && navigator.language) base.locale = navigator.language;
|
|
816
|
+
return { ...base, ...options.context ?? {} };
|
|
817
|
+
}
|
|
818
|
+
function queue() {
|
|
819
|
+
if (events === null) {
|
|
820
|
+
const tuning = options.events ?? {};
|
|
821
|
+
events = new EventQueue({
|
|
822
|
+
transport,
|
|
823
|
+
userId: () => identity.activeUserId,
|
|
824
|
+
onEventDrop,
|
|
825
|
+
storage: options.storage,
|
|
826
|
+
...tuning.flushIntervalMs === void 0 ? {} : { flushIntervalMs: tuning.flushIntervalMs },
|
|
827
|
+
...tuning.flushCount === void 0 ? {} : { flushCount: tuning.flushCount },
|
|
828
|
+
...tuning.queueLimit === void 0 ? {} : { queueLimit: tuning.queueLimit }
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
return events;
|
|
832
|
+
}
|
|
833
|
+
async function decideTagged(elements) {
|
|
834
|
+
if (!active) return;
|
|
835
|
+
const userId = identity.activeUserId;
|
|
836
|
+
const toRequest = [];
|
|
837
|
+
for (const element of elements) {
|
|
838
|
+
const hit = cache.get(userId, element);
|
|
839
|
+
if (hit !== null) {
|
|
840
|
+
if (tags.apply(element, hit.content) === "applied") {
|
|
841
|
+
onDecision(element, { content: hit.content, served: "cache", armId: hit.armId, armType: hit.armType, experimentId: hit.experimentId, experimentStatus: hit.experimentStatus, requestId: null });
|
|
842
|
+
}
|
|
843
|
+
continue;
|
|
844
|
+
}
|
|
845
|
+
if (!inFlight.has(`${userId}:${element}`)) toRequest.push(element);
|
|
846
|
+
}
|
|
847
|
+
if (toRequest.length === 0) return;
|
|
848
|
+
const run = (async () => {
|
|
849
|
+
for (let i = 0; i < toRequest.length; i += DECIDE_BATCH_LIMIT) {
|
|
850
|
+
const slice = toRequest.slice(i, i + DECIDE_BATCH_LIMIT);
|
|
851
|
+
await decideBatch(userId, slice);
|
|
852
|
+
}
|
|
853
|
+
})();
|
|
854
|
+
for (const element of toRequest) inFlight.set(`${userId}:${element}`, run);
|
|
855
|
+
try {
|
|
856
|
+
await run;
|
|
857
|
+
} finally {
|
|
858
|
+
for (const element of toRequest) inFlight.delete(`${userId}:${element}`);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
async function decideBatch(userId, elements) {
|
|
862
|
+
const stale = () => !active || identity.activeUserId !== userId;
|
|
863
|
+
if (stale()) return;
|
|
864
|
+
let response;
|
|
865
|
+
try {
|
|
866
|
+
response = await transport.post("/decide", {
|
|
867
|
+
user_id: userId,
|
|
868
|
+
context: pageContext(),
|
|
869
|
+
elements: elements.map((element) => ({ element }))
|
|
870
|
+
}, { timeoutMs });
|
|
871
|
+
} catch (error) {
|
|
872
|
+
if (stale()) return;
|
|
873
|
+
for (const element of elements) fallbackTag(element, error.summary);
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
if (stale()) return;
|
|
877
|
+
if (response.status !== 200) {
|
|
878
|
+
const failure = summarizeHttpError(response.status, response.body, response.requestId);
|
|
879
|
+
for (const element of elements) fallbackTag(element, failure);
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
const results = response.body?.results;
|
|
883
|
+
elements.forEach((element, index) => {
|
|
884
|
+
if (stale()) return;
|
|
885
|
+
const item = Array.isArray(results) ? results[index] : void 0;
|
|
886
|
+
if (item === void 0 || item === null || typeof item !== "object" || item.index !== index) {
|
|
887
|
+
fallbackTag(element, summary("protocol_error", "Batch response had no result for this element", { retryable: false, status: 200 }));
|
|
888
|
+
return;
|
|
889
|
+
}
|
|
890
|
+
if (item.status === "error") {
|
|
891
|
+
fallbackTag(element, summarizeHttpError(BATCH_ITEM_STATUS.get(item.error) ?? 400, item, response.requestId));
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
const outcome = tags.apply(element, item.content);
|
|
895
|
+
if (stale()) return;
|
|
896
|
+
if (outcome === "not_text") {
|
|
897
|
+
fallbackTag(element, summary("content_shape_mismatch", "Served content is not text", { retryable: false, status: 200 }));
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
cache.set(userId, element, { content: item.content, armId: item.arm_id, armType: item.arm_type ?? null, experimentId: item.experiment_id, experimentStatus: item.experiment_status });
|
|
901
|
+
if (outcome === "applied") {
|
|
902
|
+
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 });
|
|
903
|
+
}
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
function fallbackTag(element, error) {
|
|
907
|
+
tags.fallback(element);
|
|
908
|
+
onFallback(element, error);
|
|
909
|
+
}
|
|
910
|
+
function attachLifecycle() {
|
|
911
|
+
if (typeof document === "undefined") return;
|
|
912
|
+
const onVisibility = () => {
|
|
913
|
+
if (document.visibilityState === "hidden" && events !== null) void events.flush({ keepalive: true });
|
|
914
|
+
};
|
|
915
|
+
const onPageHide = () => {
|
|
916
|
+
if (events !== null) void events.flush({ keepalive: true });
|
|
917
|
+
};
|
|
918
|
+
document.addEventListener("visibilitychange", onVisibility);
|
|
919
|
+
addEventListener("pagehide", onPageHide);
|
|
920
|
+
listeners.push(() => document.removeEventListener("visibilitychange", onVisibility));
|
|
921
|
+
listeners.push(() => removeEventListener("pagehide", onPageHide));
|
|
922
|
+
if (options.autocapture === false) return;
|
|
923
|
+
const capture = { pageviews: true, taggedClicks: true, taggedFormSubmits: true, ...options.autocapture };
|
|
924
|
+
if (capture.pageviews) {
|
|
925
|
+
queue().system({ name: "$pageview", properties: { path: location.pathname } });
|
|
926
|
+
}
|
|
927
|
+
if (capture.taggedClicks) {
|
|
928
|
+
const onClick = (event) => {
|
|
929
|
+
const target = event.target instanceof Element ? event.target.closest("[data-curious]") : null;
|
|
930
|
+
if (target === null || target.closest("[data-curious-ignore]") !== null) return;
|
|
931
|
+
const element = target.getAttribute("data-curious");
|
|
932
|
+
if (element) queue().system({ name: "$click", properties: { element_name: element } });
|
|
933
|
+
};
|
|
934
|
+
document.addEventListener("click", onClick, { capture: true, passive: true });
|
|
935
|
+
listeners.push(() => document.removeEventListener("click", onClick, { capture: true }));
|
|
936
|
+
}
|
|
937
|
+
if (capture.taggedFormSubmits) {
|
|
938
|
+
const onSubmit = (event) => {
|
|
939
|
+
const target = event.target instanceof Element ? event.target.closest("[data-curious]") : null;
|
|
940
|
+
if (target === null || target.closest("[data-curious-ignore]") !== null) return;
|
|
941
|
+
const element = target.getAttribute("data-curious");
|
|
942
|
+
if (element) queue().system({ name: "$form_submit", properties: { element_name: element } });
|
|
943
|
+
};
|
|
944
|
+
document.addEventListener("submit", onSubmit, { capture: true, passive: true });
|
|
945
|
+
listeners.push(() => document.removeEventListener("submit", onSubmit, { capture: true }));
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
function activate() {
|
|
949
|
+
if (active) return;
|
|
950
|
+
identity.enable();
|
|
951
|
+
active = true;
|
|
952
|
+
attachLifecycle();
|
|
953
|
+
tags.start();
|
|
954
|
+
}
|
|
955
|
+
const client = {
|
|
956
|
+
start() {
|
|
957
|
+
started = true;
|
|
958
|
+
if (consent === "implicit") activate();
|
|
959
|
+
else if (consent === "denied" && typeof document !== "undefined") {
|
|
960
|
+
document.documentElement.classList.remove("curious-loading");
|
|
961
|
+
}
|
|
962
|
+
},
|
|
963
|
+
stop() {
|
|
964
|
+
started = false;
|
|
965
|
+
active = false;
|
|
966
|
+
tags.stop();
|
|
967
|
+
for (const off of listeners.splice(0)) off();
|
|
968
|
+
},
|
|
969
|
+
scan(root) {
|
|
970
|
+
if (active) tags.scan(root);
|
|
971
|
+
},
|
|
972
|
+
async decide(input) {
|
|
973
|
+
const fallback = (error, requestId) => {
|
|
974
|
+
onFallback(input.element, error);
|
|
975
|
+
return { content: input.fallback, served: "fallback", armId: null, armType: null, experimentId: null, experimentStatus: null, error, requestId };
|
|
976
|
+
};
|
|
977
|
+
if (!active) return fallback(summary("capability_unavailable", "The SDK is not active (consent or start)", { retryable: false }), null);
|
|
978
|
+
const body = { element: input.element, user_id: identity.activeUserId, context: { ...pageContext(), ...input.context ?? {} } };
|
|
979
|
+
if (input.identifiers !== void 0) body.identifiers = input.identifiers;
|
|
980
|
+
if (input.attributes !== void 0) body.attributes = input.attributes;
|
|
981
|
+
let response;
|
|
982
|
+
try {
|
|
983
|
+
response = await transport.post("/decide", body, { timeoutMs });
|
|
984
|
+
} catch (error) {
|
|
985
|
+
return fallback(error.summary, null);
|
|
986
|
+
}
|
|
987
|
+
if (response.status !== 200) return fallback(summarizeHttpError(response.status, response.body, response.requestId), response.requestId);
|
|
988
|
+
const decision = response.body;
|
|
989
|
+
if (decision === null || typeof decision !== "object" || typeof decision.arm_id !== "string" || !("content" in decision)) {
|
|
990
|
+
return fallback(summary("protocol_error", "Decision response was missing required fields", { retryable: false, status: 200 }), response.requestId);
|
|
991
|
+
}
|
|
992
|
+
if (typeof decision.content !== typeof input.fallback) {
|
|
993
|
+
return fallback(summary("content_shape_mismatch", "Served content does not match the fallback's shape", { retryable: false, status: 200 }), response.requestId);
|
|
994
|
+
}
|
|
995
|
+
const result = { content: decision.content, served: "curious", armId: decision.arm_id, armType: decision.arm_type ?? null, experimentId: decision.experiment_id ?? null, experimentStatus: decision.experiment_status ?? null, requestId: response.requestId };
|
|
996
|
+
onDecision(input.element, result);
|
|
997
|
+
return result;
|
|
998
|
+
},
|
|
999
|
+
track(input) {
|
|
1000
|
+
if (!active) {
|
|
1001
|
+
onEventDrop(summary("capability_unavailable", "Events are not collected before consent", { retryable: false }));
|
|
1002
|
+
return { id: "", queued: false };
|
|
1003
|
+
}
|
|
1004
|
+
return queue().track(input);
|
|
1005
|
+
},
|
|
1006
|
+
flush(flushOptions) {
|
|
1007
|
+
if (events === null) return Promise.resolve({ sent: 0, duplicates: 0, failed: 0, pending: 0 });
|
|
1008
|
+
return events.flush(flushOptions);
|
|
1009
|
+
},
|
|
1010
|
+
page() {
|
|
1011
|
+
if (options.autocapture === false || options.autocapture?.pageviews === false) return { id: "", queued: false };
|
|
1012
|
+
if (!active) {
|
|
1013
|
+
onEventDrop(summary("capability_unavailable", "Events are not collected before consent", { retryable: false }));
|
|
1014
|
+
return { id: "", queued: false };
|
|
1015
|
+
}
|
|
1016
|
+
if (typeof location === "undefined") return { id: "", queued: false };
|
|
1017
|
+
return queue().system({ name: "$pageview", properties: { path: location.pathname } });
|
|
1018
|
+
},
|
|
1019
|
+
// After the customer's backend has linked the anonymous id with a secret
|
|
1020
|
+
// key: flush anonymous events, switch the active user, forget cached
|
|
1021
|
+
// assignments, decide tags again for the known user.
|
|
1022
|
+
async identify(userId) {
|
|
1023
|
+
if (typeof userId !== "string" || userId.trim().length === 0) {
|
|
1024
|
+
throw new CuriousError(summary("invalid_input", "identify: userId is required", { retryable: false }));
|
|
1025
|
+
}
|
|
1026
|
+
if (!active) throw new CuriousError(summary("capability_unavailable", "The SDK is not active (consent or start)", { retryable: false }));
|
|
1027
|
+
if (events !== null) await events.flush({ keepalive: true });
|
|
1028
|
+
identity.setKnown(userId);
|
|
1029
|
+
cache.clear();
|
|
1030
|
+
tags.resetDecisions();
|
|
1031
|
+
onIdentityChange(userId);
|
|
1032
|
+
return { userId };
|
|
1033
|
+
},
|
|
1034
|
+
// Logout: a bounded flush, then a fresh anonymous history. Never unlinks
|
|
1035
|
+
// anything server-side, and a failed flush never prevents the isolation.
|
|
1036
|
+
async reset() {
|
|
1037
|
+
if (events !== null) {
|
|
1038
|
+
try {
|
|
1039
|
+
await events.flush({ keepalive: true });
|
|
1040
|
+
} catch {
|
|
1041
|
+
}
|
|
1042
|
+
events.clear();
|
|
1043
|
+
}
|
|
1044
|
+
if (active) identity.reset();
|
|
1045
|
+
cache.clear();
|
|
1046
|
+
tags.resetDecisions();
|
|
1047
|
+
onIdentityChange(null);
|
|
1048
|
+
},
|
|
1049
|
+
grantConsent() {
|
|
1050
|
+
consent = "implicit";
|
|
1051
|
+
if (started) activate();
|
|
1052
|
+
},
|
|
1053
|
+
denyConsent() {
|
|
1054
|
+
consent = "denied";
|
|
1055
|
+
active = false;
|
|
1056
|
+
tags.stop();
|
|
1057
|
+
for (const off of listeners.splice(0)) off();
|
|
1058
|
+
events?.clear();
|
|
1059
|
+
cache.clear();
|
|
1060
|
+
identity.clear();
|
|
1061
|
+
onIdentityChange(null);
|
|
1062
|
+
},
|
|
1063
|
+
get anonymousId() {
|
|
1064
|
+
return identity.anonymousId;
|
|
1065
|
+
},
|
|
1066
|
+
get userId() {
|
|
1067
|
+
return identity.knownUserId;
|
|
1068
|
+
}
|
|
1069
|
+
};
|
|
1070
|
+
return client;
|
|
1071
|
+
}
|
|
1072
|
+
function guarded(hook) {
|
|
1073
|
+
return (...args) => {
|
|
1074
|
+
if (hook === void 0) return;
|
|
1075
|
+
try {
|
|
1076
|
+
hook(...args);
|
|
1077
|
+
} catch {
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
export {
|
|
1082
|
+
CuriousError,
|
|
1083
|
+
SDK_VERSION,
|
|
1084
|
+
createCurious
|
|
1085
|
+
};
|
|
1086
|
+
//# sourceMappingURL=index.js.map
|