@holdyapp/sdk 1.1.0 → 1.5.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.cjs CHANGED
@@ -34,6 +34,7 @@ var DEFAULT_FLUSH_AT = 20;
34
34
  var DEFAULT_FLUSH_INTERVAL_MS = 5e3;
35
35
  var MAX_QUEUE = 1e3;
36
36
  var BULK_LIMIT = 500;
37
+ var MAX_BACKOFF_MS = 6e4;
37
38
  var HoldyCore = class {
38
39
  apiKey;
39
40
  baseUrl;
@@ -43,6 +44,9 @@ var HoldyCore = class {
43
44
  queue = [];
44
45
  timer = null;
45
46
  flushing = null;
47
+ retryAt = 0;
48
+ failures = 0;
49
+ warned = /* @__PURE__ */ new Set();
46
50
  userId = null;
47
51
  anonymousId = null;
48
52
  accountKey = null;
@@ -76,13 +80,14 @@ var HoldyCore = class {
76
80
  event: name,
77
81
  occurred_at: occurredAt,
78
82
  source: this.source,
83
+ external_id: newEventId(),
79
84
  ...userId ? { user_id: userId } : {},
80
85
  ...this.anonymousId ? { anonymous_id: this.anonymousId } : {},
81
86
  properties: properties ?? {},
82
87
  ...Object.keys(context).length > 0 ? { context } : {}
83
88
  };
84
89
  this.queue.push(event);
85
- if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);
90
+ this.trimQueue();
86
91
  if (this.queue.length >= this.flushAt) void this.flush();
87
92
  }
88
93
  identify(userId, traits) {
@@ -95,14 +100,9 @@ var HoldyCore = class {
95
100
  this.accountKey = accountKey;
96
101
  this.track("$group", traits ?? {});
97
102
  }
98
- /** Drena a fila. Nunca lança — falha re-enfileira e loga em debug. */
103
+ /** Drena a fila. Nunca lança — falha re-enfileira e espera antes de tentar de novo. */
99
104
  async flush() {
100
- if (this.flushing) return this.flushing;
101
- if (this.queue.length === 0) return;
102
- this.flushing = this.drain().finally(() => {
103
- this.flushing = null;
104
- });
105
- return this.flushing;
105
+ return this.startFlush(false);
106
106
  }
107
107
  /** Flush final + para o timer. Chamar em shutdown do server / unload do web. */
108
108
  async shutdown() {
@@ -110,18 +110,43 @@ var HoldyCore = class {
110
110
  clearInterval(this.timer);
111
111
  this.timer = null;
112
112
  }
113
- await this.flush();
113
+ await this.startFlush(true);
114
+ }
115
+ startFlush(force) {
116
+ if (this.flushing) return this.flushing;
117
+ if (this.queue.length === 0) return Promise.resolve();
118
+ if (!force && Date.now() < this.retryAt) return Promise.resolve();
119
+ this.flushing = this.drain().finally(() => {
120
+ this.flushing = null;
121
+ });
122
+ return this.flushing;
114
123
  }
115
124
  async drain() {
116
125
  while (this.queue.length > 0) {
117
126
  const batch = this.queue.splice(0, BULK_LIMIT);
118
- const ok = await this.send(batch);
119
- if (!ok) {
127
+ const outcome = await this.send(batch);
128
+ if (outcome.kind === "retry") {
120
129
  this.queue.unshift(...batch);
130
+ this.trimQueue();
131
+ this.scheduleRetry(outcome.afterMs);
121
132
  return;
122
133
  }
134
+ this.failures = 0;
135
+ this.retryAt = 0;
123
136
  }
124
137
  }
138
+ scheduleRetry(afterMs) {
139
+ this.failures += 1;
140
+ if (afterMs !== null) {
141
+ this.retryAt = Date.now() + afterMs;
142
+ return;
143
+ }
144
+ const backoff = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** (this.failures - 1));
145
+ this.retryAt = Date.now() + backoff + Math.floor(Math.random() * backoff * 0.2);
146
+ }
147
+ trimQueue() {
148
+ if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);
149
+ }
125
150
  async send(events) {
126
151
  try {
127
152
  const res = await fetch(`${this.baseUrl}/events/bulk`, {
@@ -133,23 +158,38 @@ var HoldyCore = class {
133
158
  body: JSON.stringify({ events }),
134
159
  ...this.source === "sdk_web" ? { keepalive: true } : {}
135
160
  });
136
- if (!res.ok) {
137
- if (res.status >= 400 && res.status < 500) {
138
- this.log(`bulk rejected ${res.status} \xB7 batch dropped`);
139
- return true;
140
- }
141
- this.log(`bulk failed ${res.status} \xB7 will retry`);
142
- return false;
161
+ if (res.ok) return { kind: "sent" };
162
+ if (res.status === 429) {
163
+ this.log("rate limited \xB7 will retry after Retry-After");
164
+ return { kind: "retry", afterMs: retryAfterMs(res) };
143
165
  }
144
- return true;
166
+ if (res.status >= 500) {
167
+ this.log(`bulk failed ${res.status} \xB7 will retry with backoff`);
168
+ return { kind: "retry", afterMs: null };
169
+ }
170
+ if (res.status === 401) {
171
+ this.warnOnce("401", "API key inv\xE1lida ou revogada \xB7 eventos descartados. Confira a chave em Configura\xE7\xF5es \u203A SDK.");
172
+ return { kind: "dropped" };
173
+ }
174
+ if (res.status === 403) {
175
+ this.warnOnce("403", "Origem n\xE3o permitida ou chave sem escopo events:write \xB7 eventos descartados.");
176
+ return { kind: "dropped" };
177
+ }
178
+ this.log(`bulk rejected ${res.status} \xB7 batch dropped`);
179
+ return { kind: "dropped" };
145
180
  } catch (err) {
146
- this.log(`bulk network error: ${err.message} \xB7 will retry`);
147
- return false;
181
+ this.log(`bulk network error: ${err.message} \xB7 will retry with backoff`);
182
+ return { kind: "retry", afterMs: null };
148
183
  }
149
184
  }
150
185
  log(msg) {
151
186
  if (this.debug) console.warn(`[holdy] ${msg}`);
152
187
  }
188
+ warnOnce(key, msg) {
189
+ if (this.warned.has(key)) return;
190
+ this.warned.add(key);
191
+ console.warn(`[holdy] ${msg}`);
192
+ }
153
193
  /**
154
194
  * Ambiente que o SDK observa sozinho (url, referrer, browser, utm…).
155
195
  * Vazio no core; `HoldyWeb` preenche. O server não infere ambiente — não
@@ -163,12 +203,72 @@ var HoldyCore = class {
163
203
  return this.queue.length;
164
204
  }
165
205
  };
206
+ function retryAfterMs(res) {
207
+ const raw = typeof res.headers?.get === "function" ? res.headers.get("Retry-After") : null;
208
+ if (!raw) return null;
209
+ const seconds = Number(raw);
210
+ if (!Number.isFinite(seconds) || seconds < 0) return null;
211
+ return Math.min(MAX_BACKOFF_MS, seconds * 1e3);
212
+ }
213
+ function newEventId() {
214
+ const c = globalThis.crypto;
215
+ if (typeof c?.randomUUID === "function") return c.randomUUID();
216
+ const rand = () => Math.random().toString(36).slice(2, 12);
217
+ return `${Date.now().toString(36)}-${rand()}-${rand()}`;
218
+ }
219
+
220
+ // src/run.ts
221
+ function newRunId() {
222
+ const c = globalThis.crypto;
223
+ if (typeof c?.randomUUID === "function") return c.randomUUID();
224
+ return `run_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
225
+ }
226
+ function runEventName(name, suffix) {
227
+ const base = name.trim().replace(/\.$/, "");
228
+ return `${base || "run"}.${suffix}`;
229
+ }
230
+ async function withRun(track, opts, fn) {
231
+ if (!opts || !opts.name) throw new Error("[holdy] run: name is required");
232
+ const id = opts.runId && opts.runId.length > 0 ? opts.runId : newRunId();
233
+ const base = { ...opts.properties ?? {}, ai_run_id: id };
234
+ const overrides = {
235
+ ...opts.accountKey ? { accountKey: opts.accountKey } : {},
236
+ ...opts.userId ? { userId: opts.userId } : {}
237
+ };
238
+ const emit = (event, properties) => track(event, { ...base, ...properties ?? {}, ai_run_id: id }, overrides);
239
+ const startedAt = Date.now();
240
+ emit(runEventName(opts.name, "started"));
241
+ try {
242
+ const result = await fn({ id, track: emit });
243
+ emit(runEventName(opts.name, "completed"), { duration_ms: Date.now() - startedAt });
244
+ return result;
245
+ } catch (err) {
246
+ emit(runEventName(opts.name, "failed"), {
247
+ duration_ms: Date.now() - startedAt,
248
+ error: err instanceof Error ? err.name : "Error"
249
+ });
250
+ throw err;
251
+ }
252
+ }
166
253
 
167
254
  // src/server.ts
168
255
  var Holdy = class extends HoldyCore {
169
256
  constructor(opts) {
170
257
  super("sdk_server", opts);
171
258
  }
259
+ /**
260
+ * Executa `fn` como UMA execução de agente: todo evento lá dentro carrega a
261
+ * mesma `ai_run_id`, e `<name>.started` / `.completed` / `.failed` saem
262
+ * sozinhos.
263
+ *
264
+ * await holdy.run({ name: 'support_agent', accountKey: 'acme' }, async (run) => {
265
+ * run.track('ticket_drafted', { ai_tokens: 1200, ai_cost_usd: 0.02 })
266
+ * return resolveTicket(ticket)
267
+ * })
268
+ */
269
+ run(opts, fn) {
270
+ return withRun((name, properties, overrides) => this.track(name, properties, overrides), opts, fn);
271
+ }
172
272
  };
173
273
 
174
274
  // src/auto-capture.ts
@@ -234,6 +334,302 @@ function currentPath() {
234
334
  return `${location.pathname}${location.search}${location.hash}`;
235
335
  }
236
336
 
337
+ // src/friction.ts
338
+ var INSTALLED_FLAG2 = "__holdy_friction__";
339
+ var INTERACTIVE_SELECTOR = 'button, a, input, select, textarea, summary, [role="button"], [role="link"], [role="menuitem"], [role="tab"]';
340
+ var INTERACTIVE_TAGS = /* @__PURE__ */ new Set(["button", "a", "input", "select", "textarea", "summary"]);
341
+ var FORM_CONTROL_TAGS = /* @__PURE__ */ new Set(["input", "select", "textarea"]);
342
+ var RageClickDetector = class {
343
+ constructor(threshold = 3, windowMs = 1e3, radiusPx = 30) {
344
+ this.threshold = threshold;
345
+ this.windowMs = windowMs;
346
+ this.radiusPx = radiusPx;
347
+ }
348
+ clicks = [];
349
+ push(x, y, t) {
350
+ this.clicks = this.clicks.filter(
351
+ (c) => t - c.t <= this.windowMs && Math.hypot(c.x - x, c.y - y) <= this.radiusPx
352
+ );
353
+ this.clicks.push({ x, y, t });
354
+ if (this.clicks.length >= this.threshold) {
355
+ this.clicks = [];
356
+ return true;
357
+ }
358
+ return false;
359
+ }
360
+ };
361
+ var NavLoopDetector = class {
362
+ constructor(windowMs = 6e4) {
363
+ this.windowMs = windowMs;
364
+ }
365
+ visits = [];
366
+ push(path, t) {
367
+ this.visits = [...this.visits, { path, t }].filter((v) => t - v.t <= this.windowMs).slice(-4);
368
+ if (this.visits.length < 4) return null;
369
+ const [a, b, c, d] = this.visits.map((v) => v.path);
370
+ if (a === c && b === d && a !== b) {
371
+ this.visits = [];
372
+ return { from: a, to: b };
373
+ }
374
+ return null;
375
+ }
376
+ };
377
+ function resolveInteractive(el) {
378
+ if (!el) return null;
379
+ const viaClosest = el.closest?.(INTERACTIVE_SELECTOR) ?? null;
380
+ if (viaClosest) return viaClosest;
381
+ const tag = el.tagName.toLowerCase();
382
+ if (INTERACTIVE_TAGS.has(tag)) return el;
383
+ const role = el.getAttribute("role");
384
+ if (role === "button" || role === "link" || role === "menuitem" || role === "tab") return el;
385
+ return null;
386
+ }
387
+ function isDeadClickTarget(el) {
388
+ const target = resolveInteractive(el);
389
+ if (!target) return false;
390
+ if (target.disabled === true) return true;
391
+ if (target.getAttribute("disabled") !== null) return true;
392
+ if (target.getAttribute("aria-disabled") === "true") return true;
393
+ const tag = target.tagName.toLowerCase();
394
+ if (tag === "a") {
395
+ const href = target.getAttribute("href");
396
+ if (!href || href === "#" || href.startsWith("javascript:")) return true;
397
+ }
398
+ return false;
399
+ }
400
+ function describeElement(el) {
401
+ const target = resolveInteractive(el) ?? el;
402
+ if (!target) return {};
403
+ const out = { element: target.tagName.toLowerCase() };
404
+ if (target.id) out.element_id = target.id;
405
+ const role = target.getAttribute("role");
406
+ if (role) out.element_role = role;
407
+ const label = target.getAttribute("aria-label") ?? target.textContent ?? "";
408
+ const text = label.replace(/\s+/g, " ").trim().slice(0, 60);
409
+ if (text) out.element_text = text;
410
+ const name = target.getAttribute("name") ?? target.getAttribute("data-testid");
411
+ if (name) out.element_name = name;
412
+ return out;
413
+ }
414
+ function stripRequestUrl(input, base) {
415
+ try {
416
+ const url = new URL(input, base);
417
+ return `${url.origin}${url.pathname}`;
418
+ } catch {
419
+ return input.split("?")[0].split("#")[0];
420
+ }
421
+ }
422
+ function errorMessage(reason) {
423
+ if (reason instanceof Error) return reason.message;
424
+ if (typeof reason === "string") return reason;
425
+ try {
426
+ return JSON.stringify(reason);
427
+ } catch {
428
+ return String(reason);
429
+ }
430
+ }
431
+ function isAbortError(err) {
432
+ return typeof err === "object" && err !== null && err.name === "AbortError";
433
+ }
434
+ function isIgnoredUrl(url, ignore) {
435
+ return ignore.some((prefix) => prefix.length > 0 && url.startsWith(prefix));
436
+ }
437
+ function registrableDomain(host) {
438
+ const labels = host.toLowerCase().split(".").filter(Boolean);
439
+ if (labels.length <= 2) return labels.join(".");
440
+ return labels.slice(-2).join(".");
441
+ }
442
+ function isFirstPartyRequest(url, pageUrl, extraOrigins = []) {
443
+ let target;
444
+ let page;
445
+ try {
446
+ target = new URL(url, pageUrl);
447
+ page = new URL(pageUrl);
448
+ } catch {
449
+ return true;
450
+ }
451
+ if (target.protocol !== "http:" && target.protocol !== "https:") return true;
452
+ if (target.host === page.host) return true;
453
+ if (extraOrigins.some((o) => o.length > 0 && target.origin === o)) return true;
454
+ const targetDomain = registrableDomain(target.hostname);
455
+ return targetDomain.length > 0 && targetDomain === registrableDomain(page.hostname);
456
+ }
457
+ function classifyRequest(outcome) {
458
+ if (outcome.aborted) return null;
459
+ if (!outcome.opaque && (outcome.status === null || outcome.status >= 400)) return "http_error";
460
+ return outcome.durationMs >= outcome.slowMs ? "slow_request" : null;
461
+ }
462
+ function documentStatus(perf) {
463
+ try {
464
+ const entry = perf?.getEntriesByType?.("navigation")?.[0];
465
+ const status = entry?.responseStatus;
466
+ return typeof status === "number" && status > 0 ? status : null;
467
+ } catch {
468
+ return null;
469
+ }
470
+ }
471
+ function formKey(form) {
472
+ return form.id || form.getAttribute("name") || form.getAttribute("data-testid") || stripRequestUrl(form.getAttribute("action") ?? "", location.href).replace(location.origin, "") || "form";
473
+ }
474
+ function currentPath2() {
475
+ return typeof location === "undefined" ? "/" : location.pathname || "/";
476
+ }
477
+ function installFrictionCapture(opts) {
478
+ const noop = { onNavigate: () => void 0, teardown: () => void 0 };
479
+ if (typeof window === "undefined" || typeof document === "undefined") return noop;
480
+ const w = window;
481
+ if (w[INSTALLED_FLAG2]) return noop;
482
+ w[INSTALLED_FLAG2] = true;
483
+ const emit = (kind, properties) => {
484
+ try {
485
+ opts.onFriction({ kind, properties: { path: currentPath2(), ...properties } });
486
+ } catch {
487
+ return;
488
+ }
489
+ };
490
+ const cleanups = [];
491
+ const rage = new RageClickDetector(opts.rageClicks, opts.rageWindowMs, opts.rageRadiusPx);
492
+ const navLoop = new NavLoopDetector(opts.navLoopWindowMs);
493
+ const slowMs = opts.slowRequestMs ?? 3e3;
494
+ const touched = /* @__PURE__ */ new Map();
495
+ const onClick = (ev) => {
496
+ const el = ev.target instanceof Element ? ev.target : null;
497
+ if (isDeadClickTarget(el)) emit("dead_click", describeElement(el));
498
+ if (rage.push(ev.clientX, ev.clientY, ev.timeStamp || Date.now())) {
499
+ emit("rage_click", describeElement(el));
500
+ }
501
+ };
502
+ document.addEventListener("click", onClick, true);
503
+ cleanups.push(() => document.removeEventListener("click", onClick, true));
504
+ const onError = (ev) => {
505
+ emit("js_error", {
506
+ message: String(ev.message ?? "").slice(0, 200),
507
+ ...ev.filename ? { source: stripRequestUrl(ev.filename, location.href) } : {},
508
+ ...ev.lineno ? { line: ev.lineno } : {}
509
+ });
510
+ };
511
+ window.addEventListener("error", onError);
512
+ cleanups.push(() => window.removeEventListener("error", onError));
513
+ const onRejection = (ev) => {
514
+ emit("js_error", { message: errorMessage(ev.reason).slice(0, 200), unhandled_rejection: true });
515
+ };
516
+ window.addEventListener("unhandledrejection", onRejection);
517
+ cleanups.push(() => window.removeEventListener("unhandledrejection", onRejection));
518
+ const ignore = (opts.ignoreUrls ?? []).map((url) => stripRequestUrl(url, location.href));
519
+ const apiOrigins = (opts.apiOrigins ?? []).map((o) => {
520
+ try {
521
+ return new URL(o, location.href).origin;
522
+ } catch {
523
+ return "";
524
+ }
525
+ });
526
+ const reportRequest = (url, method, started, status, flags = {}) => {
527
+ const target = stripRequestUrl(url, location.href);
528
+ if (isIgnoredUrl(target, ignore)) return;
529
+ if (!isFirstPartyRequest(target, location.href, apiOrigins)) return;
530
+ const durationMs = performance.now() - started;
531
+ const kind = classifyRequest({ status, durationMs, slowMs, ...flags });
532
+ if (!kind) return;
533
+ emit(kind, {
534
+ url: target,
535
+ method,
536
+ duration_ms: Math.round(durationMs),
537
+ ...flags.opaque ? {} : status !== null ? { status } : { failed: true }
538
+ });
539
+ };
540
+ const originalFetch = window.fetch;
541
+ if (typeof originalFetch === "function") {
542
+ const patched = async (input, init) => {
543
+ const started = performance.now();
544
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
545
+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
546
+ try {
547
+ const res = await originalFetch(input, init);
548
+ reportRequest(url, method, started, res.status, {
549
+ opaque: res.type === "opaque" || res.type === "opaqueredirect"
550
+ });
551
+ return res;
552
+ } catch (err) {
553
+ reportRequest(url, method, started, null, { aborted: isAbortError(err) });
554
+ throw err;
555
+ }
556
+ };
557
+ window.fetch = patched;
558
+ cleanups.push(() => {
559
+ window.fetch = originalFetch;
560
+ });
561
+ }
562
+ const xhrProto = typeof XMLHttpRequest === "function" ? XMLHttpRequest.prototype : null;
563
+ if (xhrProto) {
564
+ const originalOpen = xhrProto.open;
565
+ const originalSend = xhrProto.send;
566
+ const requests = /* @__PURE__ */ new WeakMap();
567
+ xhrProto.open = function(method, url, ...rest) {
568
+ requests.set(this, { method: String(method).toUpperCase(), url: String(url) });
569
+ return originalOpen.apply(this, [method, url, ...rest]);
570
+ };
571
+ xhrProto.send = function(body) {
572
+ const request = requests.get(this);
573
+ if (request) {
574
+ const started = performance.now();
575
+ let aborted = false;
576
+ this.addEventListener("abort", () => {
577
+ aborted = true;
578
+ });
579
+ this.addEventListener("loadend", () => {
580
+ reportRequest(request.url, request.method, started, this.status === 0 ? null : this.status, { aborted });
581
+ });
582
+ }
583
+ return originalSend.call(this, body);
584
+ };
585
+ cleanups.push(() => {
586
+ xhrProto.open = originalOpen;
587
+ xhrProto.send = originalSend;
588
+ });
589
+ }
590
+ const loadStatus = documentStatus(typeof performance === "undefined" ? void 0 : performance);
591
+ if (loadStatus !== null && loadStatus >= 400) {
592
+ emit("http_error", { document: true, status: loadStatus, url: stripRequestUrl(location.href) });
593
+ }
594
+ const onFocusIn = (ev) => {
595
+ const el = ev.target;
596
+ if (!el || !FORM_CONTROL_TAGS.has(el.tagName.toLowerCase())) return;
597
+ const form = el.form;
598
+ if (!form) return;
599
+ const entry = touched.get(form) ?? { form: formKey(form), fields: /* @__PURE__ */ new Set() };
600
+ const field = el.name || el.id || el.tagName.toLowerCase();
601
+ entry.fields.add(field);
602
+ touched.set(form, entry);
603
+ };
604
+ document.addEventListener("focusin", onFocusIn, true);
605
+ cleanups.push(() => document.removeEventListener("focusin", onFocusIn, true));
606
+ const onSubmit = (ev) => {
607
+ if (ev.target instanceof HTMLFormElement) touched.delete(ev.target);
608
+ };
609
+ document.addEventListener("submit", onSubmit, true);
610
+ cleanups.push(() => document.removeEventListener("submit", onSubmit, true));
611
+ const flushAbandons = () => {
612
+ for (const entry of touched.values()) {
613
+ emit("form_abandon", { form: entry.form, fields_touched: entry.fields.size });
614
+ }
615
+ touched.clear();
616
+ };
617
+ window.addEventListener("pagehide", flushAbandons);
618
+ cleanups.push(() => window.removeEventListener("pagehide", flushAbandons));
619
+ return {
620
+ onNavigate: (path) => {
621
+ flushAbandons();
622
+ const loop = navLoop.push(path, Date.now());
623
+ if (loop) emit("nav_loop", { from: loop.from, to: loop.to });
624
+ },
625
+ teardown: () => {
626
+ for (const cleanup of cleanups) cleanup();
627
+ touched.clear();
628
+ w[INSTALLED_FLAG2] = false;
629
+ }
630
+ };
631
+ }
632
+
237
633
  // src/web-context.ts
238
634
  var UTM_KEYS = [
239
635
  "utm_source",
@@ -276,17 +672,17 @@ function parseUserAgent(ua) {
276
672
  device
277
673
  };
278
674
  }
279
- function readStorage(storage, key) {
675
+ function readStorage(storage2, key) {
280
676
  try {
281
- const s = storage === "session" ? sessionStorage : localStorage;
677
+ const s = storage2 === "session" ? sessionStorage : localStorage;
282
678
  return s.getItem(key);
283
679
  } catch {
284
680
  return null;
285
681
  }
286
682
  }
287
- function writeStorage(storage, key, value) {
683
+ function writeStorage(storage2, key, value) {
288
684
  try {
289
- const s = storage === "session" ? sessionStorage : localStorage;
685
+ const s = storage2 === "session" ? sessionStorage : localStorage;
290
686
  s.setItem(key, value);
291
687
  } catch {
292
688
  }
@@ -351,10 +747,306 @@ function buildWebContext() {
351
747
  };
352
748
  }
353
749
 
750
+ // src/arm.ts
751
+ function fnv1a(input) {
752
+ let hash = 2166136261;
753
+ for (let i = 0; i < input.length; i++) {
754
+ hash ^= input.charCodeAt(i);
755
+ hash = Math.imul(hash, 16777619) >>> 0;
756
+ }
757
+ return hash >>> 0;
758
+ }
759
+ function changeBucket(changeId, accountKey) {
760
+ return fnv1a(`${changeId}:${accountKey}`) % 100;
761
+ }
762
+ function changeArm(changeId, accountKey, holdoutPct) {
763
+ return changeBucket(changeId, accountKey) < holdoutPct ? "holdout" : "change";
764
+ }
765
+ function matchesPathTemplate(template, path) {
766
+ const t = template.split(/[?#]/)[0].split("/").filter(Boolean);
767
+ const p = path.split(/[?#]/)[0].split("/").filter(Boolean);
768
+ if (t.length !== p.length) return false;
769
+ return t.every((segment, i) => segment.startsWith(":") || segment === p[i]);
770
+ }
771
+
772
+ // src/changes.ts
773
+ var REFRESH_MS = 5 * 60 * 1e3;
774
+ var NAV_REFRESH_MS = 60 * 1e3;
775
+ var SCAN_DEBOUNCE_MS = 250;
776
+ var SEEN_KEY = "holdy_changes_seen";
777
+ var DISMISSED_KEY = "holdy_changes_dismissed";
778
+ var TIP_GAP_PX = 8;
779
+ var TIP_CSS = `:host{all:initial}
780
+ .tip{position:fixed;box-sizing:border-box;max-width:280px;padding:10px 12px;border-radius:8px;background:#111;color:#fff;font:13px/1.45 system-ui,-apple-system,sans-serif;box-shadow:0 8px 24px rgba(0,0,0,.18);pointer-events:auto;display:flex;gap:10px;align-items:flex-start}
781
+ .tip p{margin:0;flex:1}
782
+ .tip button{all:unset;cursor:pointer;opacity:.7;font-size:15px;line-height:1}
783
+ .tip button:hover,.tip button:focus-visible{opacity:1}
784
+ @media (prefers-color-scheme:dark){.tip{background:#fff;color:#111}}`;
785
+ function normalizeText(text) {
786
+ return text.replace(/\s+/g, " ").trim();
787
+ }
788
+ function parseChanges(body) {
789
+ const list = body?.changes;
790
+ return Array.isArray(list) ? list.filter(isChange) : [];
791
+ }
792
+ function isAnchor(value) {
793
+ const a = value;
794
+ if (a?.kind === "page") return true;
795
+ return (a?.kind === "selector" || a?.kind === "text") && typeof a.value === "string" && a.value.length > 0;
796
+ }
797
+ function isChange(value) {
798
+ const c = value;
799
+ return typeof c?.id === "string" && (c.kind === "copy" || c.kind === "guidance") && typeof c.path === "string" && isAnchor(c.anchor) && typeof c.content?.text === "string" && typeof c.holdout_pct === "number";
800
+ }
801
+ function changesForPage(changes, path, accountKey) {
802
+ if (!accountKey) return [];
803
+ return changes.filter((c) => matchesPathTemplate(c.path, path)).map((change) => ({ change, arm: changeArm(change.id, accountKey, change.holdout_pct) }));
804
+ }
805
+ function storage(kind) {
806
+ try {
807
+ return kind === "local" ? window.localStorage : window.sessionStorage;
808
+ } catch {
809
+ return void 0;
810
+ }
811
+ }
812
+ function readSet(store, key) {
813
+ try {
814
+ return new Set(JSON.parse(store?.getItem(key) ?? "[]"));
815
+ } catch {
816
+ return /* @__PURE__ */ new Set();
817
+ }
818
+ }
819
+ function addToSet(store, key, value) {
820
+ try {
821
+ const set = readSet(store, key);
822
+ set.add(value);
823
+ store?.setItem(key, JSON.stringify([...set].slice(-200)));
824
+ } catch {
825
+ return;
826
+ }
827
+ }
828
+ function query(selector) {
829
+ try {
830
+ return document.querySelector(selector);
831
+ } catch {
832
+ return null;
833
+ }
834
+ }
835
+ var TEXT_ANCHOR_TAGS = 'button,a,[role="button"],label,summary,h1,h2,h3,h4,li,td,th,p,span,strong';
836
+ var TEXT_ANCHOR_SCAN_LIMIT = 3e3;
837
+ function findByText(value) {
838
+ const wanted = normalizeText(value);
839
+ let best = null;
840
+ let bestLength = Number.POSITIVE_INFINITY;
841
+ const nodes = document.querySelectorAll(TEXT_ANCHOR_TAGS);
842
+ const total = Math.min(nodes.length, TEXT_ANCHOR_SCAN_LIMIT);
843
+ for (let i = 0; i < total; i += 1) {
844
+ const el = nodes[i];
845
+ const raw = el.textContent ?? "";
846
+ if (raw.length >= bestLength || normalizeText(raw) !== wanted) continue;
847
+ best = el;
848
+ bestLength = raw.length;
849
+ }
850
+ return best;
851
+ }
852
+ function findAnchor(anchor) {
853
+ if (anchor.kind === "page") return null;
854
+ return anchor.kind === "selector" ? query(anchor.value) : findByText(anchor.value);
855
+ }
856
+ function findTextNode(el, match) {
857
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
858
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
859
+ if (match(normalizeText(node.textContent ?? ""))) return node;
860
+ }
861
+ return null;
862
+ }
863
+ function installProductChanges(opts) {
864
+ if (typeof window === "undefined" || typeof document === "undefined") {
865
+ return { onNavigate: () => void 0, refresh: async () => void 0, teardown: () => void 0 };
866
+ }
867
+ let changes = [];
868
+ let lastFetch = 0;
869
+ let timer = null;
870
+ let root = null;
871
+ let host = null;
872
+ const copies = /* @__PURE__ */ new Map();
873
+ const tips = /* @__PURE__ */ new Map();
874
+ const log = (message) => {
875
+ if (opts.debug) console.warn(`[holdy] ${message}`);
876
+ };
877
+ const expose = (change, arm) => {
878
+ const key = `${change.id}:${arm}`;
879
+ const session = storage("session");
880
+ if (readSet(session, SEEN_KEY).has(key)) return;
881
+ addToSet(session, SEEN_KEY, key);
882
+ opts.track("$change_exposure", { change_id: change.id, arm, kind: change.kind });
883
+ };
884
+ const eligibleCopyNode = (el, change) => {
885
+ const expected = change.expected_text ? normalizeText(change.expected_text) : null;
886
+ const next = normalizeText(change.content.text);
887
+ return findTextNode(el, (text) => text.length > 0 && (text === next || expected === null || text === expected));
888
+ };
889
+ const applyCopy = (el, change) => {
890
+ const next = normalizeText(change.content.text);
891
+ const current = copies.get(change.id);
892
+ if (current && current.node.isConnected && normalizeText(current.node.textContent ?? "") === next) return true;
893
+ const node = eligibleCopyNode(el, change);
894
+ if (!node) return false;
895
+ const text = node.textContent ?? "";
896
+ if (normalizeText(text) !== next) {
897
+ copies.set(change.id, { node, original: text, next: change.content.text });
898
+ node.textContent = text.replace(text.trim(), change.content.text);
899
+ }
900
+ return true;
901
+ };
902
+ const restoreCopy = (id) => {
903
+ const applied = copies.get(id);
904
+ if (!applied) return;
905
+ if (applied.node.isConnected && normalizeText(applied.node.textContent ?? "") === normalizeText(applied.next)) {
906
+ applied.node.textContent = applied.original;
907
+ }
908
+ copies.delete(id);
909
+ };
910
+ const ensureRoot = () => {
911
+ if (root) return root;
912
+ if (!document.body) return null;
913
+ host = document.createElement("holdy-changes");
914
+ host.setAttribute("data-holdy-root", "1");
915
+ host.style.cssText = "position:fixed;top:0;left:0;width:0;height:0;z-index:2147483647;pointer-events:none";
916
+ root = host.attachShadow({ mode: "closed" });
917
+ const style = document.createElement("style");
918
+ style.textContent = TIP_CSS;
919
+ root.appendChild(style);
920
+ document.body.appendChild(host);
921
+ return root;
922
+ };
923
+ const showTip = (anchor, change) => {
924
+ if (tips.has(change.id)) return true;
925
+ if (readSet(storage("local"), DISMISSED_KEY).has(change.id)) return true;
926
+ const shadow = ensureRoot();
927
+ if (!shadow) return false;
928
+ const card = document.createElement("div");
929
+ card.className = "tip";
930
+ card.setAttribute("role", "tooltip");
931
+ const text = document.createElement("p");
932
+ text.textContent = change.content.text;
933
+ const close = document.createElement("button");
934
+ close.type = "button";
935
+ close.setAttribute("aria-label", "Fechar");
936
+ close.textContent = "\xD7";
937
+ card.append(text, close);
938
+ card.style.top = "-9999px";
939
+ card.style.left = "-9999px";
940
+ shadow.appendChild(card);
941
+ const remove = () => {
942
+ card.remove();
943
+ window.removeEventListener("scroll", position, true);
944
+ window.removeEventListener("resize", position);
945
+ tips.delete(change.id);
946
+ };
947
+ function position() {
948
+ if (!anchor) {
949
+ const corner = card.getBoundingClientRect();
950
+ card.style.top = `${Math.max(8, window.innerHeight - corner.height - 16)}px`;
951
+ card.style.left = `${Math.max(8, window.innerWidth - corner.width - 16)}px`;
952
+ return;
953
+ }
954
+ if (!anchor.isConnected) {
955
+ remove();
956
+ return;
957
+ }
958
+ const a = anchor.getBoundingClientRect();
959
+ const c = card.getBoundingClientRect();
960
+ let top = a.bottom + TIP_GAP_PX;
961
+ if (top + c.height > window.innerHeight - 8) top = a.top - c.height - TIP_GAP_PX;
962
+ const left = Math.min(Math.max(8, a.left + a.width / 2 - c.width / 2), window.innerWidth - c.width - 8);
963
+ card.style.top = `${Math.max(8, top)}px`;
964
+ card.style.left = `${Math.max(8, left)}px`;
965
+ }
966
+ close.addEventListener("click", () => {
967
+ addToSet(storage("local"), DISMISSED_KEY, change.id);
968
+ opts.track("$change_dismissed", { change_id: change.id, kind: change.kind });
969
+ remove();
970
+ });
971
+ tips.set(change.id, remove);
972
+ requestAnimationFrame(position);
973
+ window.addEventListener("scroll", position, true);
974
+ window.addEventListener("resize", position);
975
+ return true;
976
+ };
977
+ const scan = () => {
978
+ timer = null;
979
+ const active = changesForPage(changes, location.pathname, opts.getAccountKey());
980
+ const activeIds = new Set(active.map((a) => a.change.id));
981
+ for (const id of [...copies.keys()]) if (!activeIds.has(id)) restoreCopy(id);
982
+ for (const [id, remove] of [...tips]) if (!activeIds.has(id)) remove();
983
+ for (const { change, arm } of active) {
984
+ const el = findAnchor(change.anchor);
985
+ if (!el && change.anchor.kind !== "page") continue;
986
+ if (change.kind === "copy") {
987
+ if (!el) continue;
988
+ const shown = arm === "change" ? applyCopy(el, change) : eligibleCopyNode(el, change) !== null;
989
+ if (shown) expose(change, arm);
990
+ } else if (arm === "holdout" || showTip(el, change)) {
991
+ expose(change, arm);
992
+ }
993
+ }
994
+ };
995
+ const schedule = () => {
996
+ if (timer === null) timer = setTimeout(scan, SCAN_DEBOUNCE_MS);
997
+ };
998
+ const refresh = async () => {
999
+ lastFetch = Date.now();
1000
+ try {
1001
+ const res = await fetch(`${opts.baseUrl}/runtime/changes`, {
1002
+ headers: { Authorization: `Bearer ${opts.apiKey}` }
1003
+ });
1004
+ if (!res.ok) {
1005
+ log(`changes ${res.status}`);
1006
+ return;
1007
+ }
1008
+ changes = parseChanges(await res.json());
1009
+ schedule();
1010
+ } catch (err) {
1011
+ log(`changes network error: ${err.message}`);
1012
+ }
1013
+ };
1014
+ const observer = typeof MutationObserver !== "undefined" ? new MutationObserver(() => {
1015
+ if (changes.length > 0 || copies.size > 0 || tips.size > 0) schedule();
1016
+ }) : null;
1017
+ const observe = () => {
1018
+ if (document.body) observer?.observe(document.body, { childList: true, subtree: true, characterData: true });
1019
+ };
1020
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", observe, { once: true });
1021
+ else observe();
1022
+ const interval = setInterval(() => void refresh(), REFRESH_MS);
1023
+ void refresh();
1024
+ return {
1025
+ onNavigate: () => {
1026
+ if (Date.now() - lastFetch > NAV_REFRESH_MS) void refresh();
1027
+ schedule();
1028
+ },
1029
+ refresh,
1030
+ teardown: () => {
1031
+ clearInterval(interval);
1032
+ if (timer !== null) clearTimeout(timer);
1033
+ observer?.disconnect();
1034
+ for (const id of [...copies.keys()]) restoreCopy(id);
1035
+ for (const remove of [...tips.values()]) remove();
1036
+ host?.remove();
1037
+ host = null;
1038
+ root = null;
1039
+ changes = [];
1040
+ }
1041
+ };
1042
+ }
1043
+
354
1044
  // src/web.ts
355
1045
  var ANON_STORAGE_KEY = "holdy_anon_id";
356
1046
  var HoldyWeb = class extends HoldyCore {
357
1047
  teardownAutoCapture = null;
1048
+ friction = null;
1049
+ changes = null;
358
1050
  constructor(opts) {
359
1051
  super("sdk_web", opts);
360
1052
  this.anonymousId = resolveAnonymousId();
@@ -364,9 +1056,30 @@ var HoldyWeb = class extends HoldyCore {
364
1056
  if (document.visibilityState === "hidden") void this.flush();
365
1057
  });
366
1058
  }
1059
+ if (opts.friction !== false) {
1060
+ const frictionOpts = typeof opts.friction === "object" ? opts.friction : {};
1061
+ this.friction = installFrictionCapture({
1062
+ ...frictionOpts,
1063
+ ignoreUrls: [...frictionOpts.ignoreUrls ?? [], this.baseUrl],
1064
+ onFriction: (signal) => this.track(`$${signal.kind}`, signal.properties)
1065
+ });
1066
+ }
367
1067
  if (opts.autoCapture !== false) {
368
1068
  this.teardownAutoCapture = installAutoCapture({
369
- onNavigate: (kind) => this.page(void 0, { navigation: kind })
1069
+ onNavigate: (kind) => {
1070
+ this.page(void 0, { navigation: kind });
1071
+ this.friction?.onNavigate(typeof location !== "undefined" ? location.pathname : "/");
1072
+ this.changes?.onNavigate();
1073
+ }
1074
+ });
1075
+ }
1076
+ if (opts.productChanges !== false && typeof window !== "undefined") {
1077
+ this.changes = installProductChanges({
1078
+ baseUrl: this.baseUrl,
1079
+ apiKey: this.apiKey,
1080
+ getAccountKey: () => this.accountKey,
1081
+ track: (name, properties) => this.track(name, properties),
1082
+ debug: opts.debug
370
1083
  });
371
1084
  }
372
1085
  }
@@ -384,6 +1097,10 @@ var HoldyWeb = class extends HoldyCore {
384
1097
  ...typeof document !== "undefined" && document.title ? { title: document.title } : {}
385
1098
  });
386
1099
  }
1100
+ group(accountKey, traits) {
1101
+ super.group(accountKey, traits);
1102
+ this.changes?.onNavigate();
1103
+ }
387
1104
  reset() {
388
1105
  this.userId = null;
389
1106
  this.accountKey = null;
@@ -392,11 +1109,16 @@ var HoldyWeb = class extends HoldyCore {
392
1109
  } catch {
393
1110
  }
394
1111
  this.anonymousId = resolveAnonymousId();
1112
+ this.changes?.onNavigate();
395
1113
  }
396
1114
  /** Flush final + desinstala o auto-capture (devolve `history` ao original). */
397
1115
  async shutdown() {
398
1116
  this.teardownAutoCapture?.();
399
1117
  this.teardownAutoCapture = null;
1118
+ this.friction?.teardown();
1119
+ this.friction = null;
1120
+ this.changes?.teardown();
1121
+ this.changes = null;
400
1122
  await super.shutdown();
401
1123
  }
402
1124
  environmentContext() {