@traqio/web 0.4.0 → 0.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/build/index.js CHANGED
@@ -225,6 +225,141 @@ var require_skan = __commonJS({
225
225
  }
226
226
  });
227
227
 
228
+ // ../sdk-core/build/analytics.js
229
+ var require_analytics = __commonJS({
230
+ "../sdk-core/build/analytics.js"(exports) {
231
+ "use strict";
232
+ Object.defineProperty(exports, "__esModule", { value: true });
233
+ exports.EXPOSURE_EVENT = exports.MAX_PROPS_BYTES = exports.MAX_SCREEN_NAME = exports.MAX_EVENT_NAME = exports.ANALYTICS_SESSION_IDLE_MS = exports.MAX_TRAITS = exports.MAX_GROUP_TYPES = void 0;
234
+ exports.cleanGroupType = cleanGroupType2;
235
+ exports.cleanGroupKey = cleanGroupKey2;
236
+ exports.cleanGroups = cleanGroups2;
237
+ exports.withGroup = withGroup2;
238
+ exports.cleanTraits = cleanTraits2;
239
+ exports.withSuperProps = withSuperProps2;
240
+ exports.cleanEventName = cleanEventName;
241
+ exports.cleanScreenName = cleanScreenName;
242
+ exports.cleanProps = cleanProps;
243
+ exports.touchSession = touchSession;
244
+ exports.parseSession = parseSession;
245
+ var GROUP_TYPE2 = /^[a-z][a-z0-9_]{0,29}$/;
246
+ exports.MAX_GROUP_TYPES = 5;
247
+ var MAX_GROUP_KEY = 256;
248
+ function cleanGroupType2(v) {
249
+ if (typeof v !== "string")
250
+ return null;
251
+ const t = v.trim();
252
+ return GROUP_TYPE2.test(t) ? t : null;
253
+ }
254
+ function cleanGroupKey2(v) {
255
+ if (typeof v === "number" && Number.isFinite(v))
256
+ return String(v);
257
+ if (typeof v !== "string")
258
+ return null;
259
+ const t = v.trim();
260
+ return t && t.length <= MAX_GROUP_KEY ? t : null;
261
+ }
262
+ function cleanGroups2(v) {
263
+ const out = {};
264
+ if (typeof v !== "object" || v === null || Array.isArray(v))
265
+ return out;
266
+ for (const [t, k] of Object.entries(v)) {
267
+ if (Object.keys(out).length >= exports.MAX_GROUP_TYPES)
268
+ break;
269
+ const type = cleanGroupType2(t);
270
+ const key = cleanGroupKey2(k);
271
+ if (type && key)
272
+ out[type] = key;
273
+ }
274
+ return out;
275
+ }
276
+ function withGroup2(groups, type, key) {
277
+ const t = cleanGroupType2(type);
278
+ const k = cleanGroupKey2(key);
279
+ if (!t || !k)
280
+ return null;
281
+ if (!(t in groups) && Object.keys(groups).length >= exports.MAX_GROUP_TYPES)
282
+ return null;
283
+ return { groups: { ...groups, [t]: k }, type: t, key: k, changed: groups[t] !== k };
284
+ }
285
+ var TRAIT_KEY2 = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
286
+ exports.MAX_TRAITS = 50;
287
+ var MAX_TRAIT_TEXT = 200;
288
+ function cleanTraits2(v) {
289
+ const out = {};
290
+ if (typeof v !== "object" || v === null || Array.isArray(v))
291
+ return out;
292
+ for (const [k, raw] of Object.entries(v)) {
293
+ if (Object.keys(out).length >= exports.MAX_TRAITS)
294
+ break;
295
+ if (!TRAIT_KEY2.test(k))
296
+ continue;
297
+ if (typeof raw === "string") {
298
+ const t = raw.trim();
299
+ if (t)
300
+ out[k] = t.slice(0, MAX_TRAIT_TEXT);
301
+ } else if (typeof raw === "number" && Number.isFinite(raw) || typeof raw === "boolean") {
302
+ out[k] = raw;
303
+ }
304
+ }
305
+ return out;
306
+ }
307
+ function withSuperProps2(own, sup) {
308
+ var _a;
309
+ if (!Object.keys(sup).length)
310
+ return own;
311
+ return (_a = cleanProps({ ...sup, ...own != null ? own : {} })) != null ? _a : own;
312
+ }
313
+ exports.ANALYTICS_SESSION_IDLE_MS = 30 * 60 * 1e3;
314
+ exports.MAX_EVENT_NAME = 128;
315
+ exports.MAX_SCREEN_NAME = 512;
316
+ exports.MAX_PROPS_BYTES = 4096;
317
+ exports.EXPOSURE_EVENT = "$exposure";
318
+ function cleanEventName(name) {
319
+ if (typeof name !== "string")
320
+ return null;
321
+ const n = name.trim();
322
+ if (!n || n.length > exports.MAX_EVENT_NAME || n.startsWith("$") && n !== exports.EXPOSURE_EVENT)
323
+ return null;
324
+ return n;
325
+ }
326
+ function cleanScreenName(name) {
327
+ if (typeof name !== "string")
328
+ return null;
329
+ const n = name.trim();
330
+ return n ? n.slice(0, exports.MAX_SCREEN_NAME) : null;
331
+ }
332
+ function cleanProps(props) {
333
+ if (typeof props !== "object" || props === null || Array.isArray(props))
334
+ return void 0;
335
+ try {
336
+ const json = JSON.stringify(props);
337
+ if (!json || json === "{}" || json.length > exports.MAX_PROPS_BYTES)
338
+ return void 0;
339
+ return JSON.parse(json);
340
+ } catch {
341
+ return void 0;
342
+ }
343
+ }
344
+ function touchSession(current, now, newId2) {
345
+ if (current && typeof current.id === "string" && typeof current.last === "number" && now - current.last <= exports.ANALYTICS_SESSION_IDLE_MS && now >= current.last - 6e4) {
346
+ return { id: current.id, last: Math.max(now, current.last) };
347
+ }
348
+ return { id: newId2(), last: now };
349
+ }
350
+ function parseSession(raw) {
351
+ if (!raw)
352
+ return null;
353
+ try {
354
+ const s = JSON.parse(raw);
355
+ return typeof s.id === "string" && typeof s.last === "number" ? { id: s.id, last: s.last } : null;
356
+ } catch {
357
+ return null;
358
+ }
359
+ }
360
+ }
361
+ });
362
+
228
363
  // ../sdk-core/build/adservices.js
229
364
  var require_adservices = __commonJS({
230
365
  "../sdk-core/build/adservices.js"(exports) {
@@ -627,16 +762,17 @@ var require_build = __commonJS({
627
762
  "../sdk-core/build/index.js"(exports) {
628
763
  "use strict";
629
764
  Object.defineProperty(exports, "__esModule", { value: true });
630
- exports.Traqio = exports.Client = exports.AdRevenueGate = exports.watchReactNativeAds = exports.fromMaxAdInfo = exports.fromGoogleMobileAdsPaid = exports.fromGoogleMobileAdsNativeAd = exports.fromGoogleMobileAdsChannel = exports.fromCapacitorAdMob = exports.MAX_RN_REVENUE_EVENTS = exports.MAX_RN_MIN_VERSION = exports.GMA_MIN_VERSION = exports.GMA_FULLSCREEN_CHANNELS = exports.CAPACITOR_ADMOB_PAID_EVENTS = exports.isTrackingUrl = exports.isOpenUrl = exports.reportAdServicesToken = exports.Skan = exports.SDK_VERSION = void 0;
765
+ exports.Traqio = exports.Client = exports.AdRevenueGate = exports.watchReactNativeAds = exports.fromMaxAdInfo = exports.fromGoogleMobileAdsPaid = exports.fromGoogleMobileAdsNativeAd = exports.fromGoogleMobileAdsChannel = exports.fromCapacitorAdMob = exports.MAX_RN_REVENUE_EVENTS = exports.MAX_RN_MIN_VERSION = exports.GMA_MIN_VERSION = exports.GMA_FULLSCREEN_CHANNELS = exports.CAPACITOR_ADMOB_PAID_EVENTS = exports.isTrackingUrl = exports.isOpenUrl = exports.ANALYTICS_SESSION_IDLE_MS = exports.reportAdServicesToken = exports.Skan = exports.SDK_VERSION = void 0;
631
766
  exports.normalizeAdvertisingId = normalizeAdvertisingId;
632
767
  exports.fromMaxAd = fromMaxAd;
633
768
  exports.detectDebug = detectDebug;
634
769
  exports.isLocalPage = isLocalPage;
635
770
  var skan_1 = require_skan();
771
+ var analytics_1 = require_analytics();
636
772
  var adservices_1 = require_adservices();
637
773
  var deeplink_1 = require_deeplink();
638
774
  var adRevenue_1 = require_adRevenue();
639
- exports.SDK_VERSION = "0.6.0";
775
+ exports.SDK_VERSION = "0.8.0";
640
776
  var skan_2 = require_skan();
641
777
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
642
778
  return skan_2.Skan;
@@ -645,6 +781,10 @@ var require_build = __commonJS({
645
781
  Object.defineProperty(exports, "reportAdServicesToken", { enumerable: true, get: function() {
646
782
  return adservices_2.reportAdServicesToken;
647
783
  } });
784
+ var analytics_2 = require_analytics();
785
+ Object.defineProperty(exports, "ANALYTICS_SESSION_IDLE_MS", { enumerable: true, get: function() {
786
+ return analytics_2.ANALYTICS_SESSION_IDLE_MS;
787
+ } });
648
788
  var deeplink_2 = require_deeplink();
649
789
  Object.defineProperty(exports, "isOpenUrl", { enumerable: true, get: function() {
650
790
  return deeplink_2.isOpenUrl;
@@ -705,6 +845,14 @@ var require_build = __commonJS({
705
845
  var DEFERRED_RETRY_KEY = "traq_deferred_consent_retry_until";
706
846
  var DEFERRED_RETRY_WINDOW_MS = 60 * 6e4;
707
847
  var CONSENT_KEY = "traq_consent";
848
+ var ANALYTICS_QUEUE_KEY = "traq_analytics_queue";
849
+ var ANALYTICS_SESSION_KEY = "traq_analytics_session";
850
+ var SUPER_PROPS_KEY2 = "traq_super_props";
851
+ var GROUPS_KEY2 = "traq_groups";
852
+ var ANALYTICS_PATH = "/ingest/analytics";
853
+ var MAX_ANALYTICS_BATCH = 50;
854
+ var MAX_ANALYTICS_QUEUE = 1e3;
855
+ var MAX_EARLY_ANALYTICS = 100;
708
856
  var MAX_BATCH = 20;
709
857
  var NON_RETRYABLE_STATUS = /* @__PURE__ */ new Set([400, 413, 422]);
710
858
  var MAX_QUEUE2 = 500;
@@ -816,6 +964,12 @@ var require_build = __commonJS({
816
964
  this.att = null;
817
965
  this.adIdSync = null;
818
966
  this.debug = false;
967
+ this.analyticsQueue = [];
968
+ this.analyticsSession = null;
969
+ this.earlyAnalytics = [];
970
+ this.currentScreen = null;
971
+ this.superProps = {};
972
+ this.groups = {};
819
973
  this.maxRevenuePaid = (adInfo) => {
820
974
  try {
821
975
  const max = (0, adRevenue_1.fromMaxAdInfo)(adInfo);
@@ -831,11 +985,11 @@ var require_build = __commonJS({
831
985
  return this.debug;
832
986
  }
833
987
  async init(opts) {
834
- var _a;
988
+ var _a, _b;
835
989
  if (this.started)
836
990
  return;
837
991
  this.started = true;
838
- this.opts = { collectContext: true, ...opts, storage: (_a = opts.storage) != null ? _a : defaultStorage() };
992
+ this.opts = { collectContext: true, ...opts, userId: (_a = opts.userId) != null ? _a : this.earlyUserId, storage: (_b = opts.storage) != null ? _b : defaultStorage() };
839
993
  if (!this.opts.storage) {
840
994
  console.warn("[traqio] no storage available \u2014 pass `storage` to init() or install @react-native-async-storage/async-storage, otherwise the install is re-sent at every launch.");
841
995
  }
@@ -843,9 +997,18 @@ var require_build = __commonJS({
843
997
  await this.restoreConsent(opts.consent);
844
998
  await this.restoreQueue();
845
999
  await this.restoreAdQueue();
1000
+ await this.restoreAnalytics();
846
1001
  await this.buildContext();
847
- if (await this.restoreErased())
1002
+ if (await this.restoreErased()) {
1003
+ this.earlyAnalytics = [];
848
1004
  return;
1005
+ }
1006
+ if (this.isWeb) {
1007
+ this.earlyAnalytics = [];
1008
+ } else {
1009
+ for (const e of this.earlyAnalytics.splice(0))
1010
+ this.pushAnalytics(e, false);
1011
+ }
849
1012
  if (!this.isWeb) {
850
1013
  const freshInstall = Boolean(this.opts.storage) && !await this.opts.storage.getItem(this.installSentKey).catch(() => "1");
851
1014
  await this.sendInstallOnce();
@@ -860,7 +1023,7 @@ var require_build = __commonJS({
860
1023
  await this.initAppleAds();
861
1024
  this.wireLifecycle();
862
1025
  this.wireAdRevenue();
863
- if (this.queue.length || this.adQueue.length)
1026
+ if (this.queue.length || this.adQueue.length || this.analyticsQueue.length)
864
1027
  this.scheduleFlush(0);
865
1028
  }
866
1029
  // `InitOptions.adRevenue`: hand the ad SDKs' own paid events to the trackers.
@@ -902,6 +1065,179 @@ var require_build = __commonJS({
902
1065
  if (props == null ? void 0 : props.value)
903
1066
  this.skan.addRevenue(props.value);
904
1067
  }
1068
+ /**
1069
+ * A product-analytics event — `paywall_viewed`, `deck_built`, `search_performed`…
1070
+ * — read in the console's Analytics section (events, funnels, property splits).
1071
+ * NOT a conversion: never billed, never sent to an ad network (that is `track()`).
1072
+ *
1073
+ * Batched, persisted while offline and retried like every other call; it never
1074
+ * throws. Names starting with `$` are reserved (but `$exposure { experiment, variant }`, an experiment exposure); properties must survive JSON and
1075
+ * stay under 4 KB, else they are dropped (the event is kept). Callable before
1076
+ * `init()`: the first 100 calls wait for it.
1077
+ *
1078
+ * Traqio.capture("lead_captured", { magnet: "starter-deck" });
1079
+ */
1080
+ capture(name, props) {
1081
+ try {
1082
+ const n = (0, analytics_1.cleanEventName)(name);
1083
+ if (!n)
1084
+ return;
1085
+ const p = (0, analytics_1.cleanProps)(props);
1086
+ this.queueAnalytics({ kind: "custom", name: n, ts: Date.now(), ...p ? { props: p } : {} });
1087
+ } catch {
1088
+ }
1089
+ }
1090
+ /**
1091
+ * Who the user is, and what they are: sets the user id (like `setUserId`) and, with
1092
+ * traits, the user's PROPERTIES — `plan`, `role`, `company_size` — read in the
1093
+ * console as a breakdown, a report dimension and a cohort condition.
1094
+ *
1095
+ * Traqio.identify("u_123", { plan: "pro", seats: 12 }, { signup_platform: "ios" });
1096
+ *
1097
+ * `traits` overwrite what was set before; `traitsOnce` are written only where the
1098
+ * user has no value yet (a first plan, a sign-up source). Values are text, numbers
1099
+ * or booleans — never an email or a name: the docs say why. At most 50 keys.
1100
+ */
1101
+ identify(userId, traits, traitsOnce) {
1102
+ try {
1103
+ const id = typeof userId === "string" ? userId.trim() : "";
1104
+ if (!id)
1105
+ return;
1106
+ if (this.opts)
1107
+ this.setUserId(id);
1108
+ else
1109
+ this.earlyUserId = id;
1110
+ const set = (0, analytics_1.cleanTraits)(traits);
1111
+ const setOnce = (0, analytics_1.cleanTraits)(traitsOnce);
1112
+ if (!Object.keys(set).length && !Object.keys(setOnce).length)
1113
+ return;
1114
+ this.queueAnalytics({ kind: "identify", ts: Date.now(), userId: id, ...Object.keys(set).length ? { set } : {}, ...Object.keys(setOnce).length ? { setOnce } : {} });
1115
+ } catch {
1116
+ }
1117
+ }
1118
+ /**
1119
+ * Super-properties: added to EVERY analytics event from now on (and across
1120
+ * launches) — an app version flavour, an A/B arm, a theme. An event's own property
1121
+ * of the same name wins. `unregister(key)` removes one.
1122
+ *
1123
+ * Traqio.register({ app_flavor: "beta", theme: "dark" });
1124
+ */
1125
+ register(props) {
1126
+ try {
1127
+ this.superProps = (0, analytics_1.cleanTraits)({ ...this.superProps, ...(0, analytics_1.cleanTraits)(props) });
1128
+ void this.persistSuperProps();
1129
+ } catch {
1130
+ }
1131
+ }
1132
+ /** Stop adding one super-property to the events. */
1133
+ unregister(key) {
1134
+ if (typeof key !== "string" || !(key in this.superProps))
1135
+ return;
1136
+ const rest = { ...this.superProps };
1137
+ delete rest[key];
1138
+ this.superProps = rest;
1139
+ void this.persistSuperProps();
1140
+ }
1141
+ /** The super-properties `register()` set — a copy. */
1142
+ getSuperProperties() {
1143
+ return { ...this.superProps };
1144
+ }
1145
+ /**
1146
+ * The B2B ACCOUNT the user works in (group analytics): every analytics event from now
1147
+ * on (and across launches) counts for it, so the console can count accounts — unique
1148
+ * accounts, funnels, retention and cohorts « by company » — and list them with their
1149
+ * traits. Call it after sign-in, and again when the user switches account.
1150
+ *
1151
+ * Traqio.group("company", "acc_42", { plan: "enterprise", seats: 40 });
1152
+ *
1153
+ * `groupType` is lowercase (`company`, `workspace`, `team`; 5 types at most),
1154
+ * `groupKey` your own account id — never an email. Traits follow identify's rules.
1155
+ */
1156
+ group(groupType, groupKey, traits, traitsOnce) {
1157
+ try {
1158
+ const next = (0, analytics_1.withGroup)(this.groups, groupType, groupKey);
1159
+ if (!next)
1160
+ return;
1161
+ this.groups = next.groups;
1162
+ void this.persistGroups();
1163
+ const set = (0, analytics_1.cleanTraits)(traits);
1164
+ const setOnce = (0, analytics_1.cleanTraits)(traitsOnce);
1165
+ if (!next.changed && !Object.keys(set).length && !Object.keys(setOnce).length)
1166
+ return;
1167
+ this.queueAnalytics({
1168
+ kind: "group",
1169
+ ts: Date.now(),
1170
+ groupType: next.type,
1171
+ groupKey: next.key,
1172
+ ...Object.keys(set).length ? { set } : {},
1173
+ ...Object.keys(setOnce).length ? { setOnce } : {}
1174
+ });
1175
+ } catch {
1176
+ }
1177
+ }
1178
+ /** Stop stamping the events with any account — call it on sign-out. */
1179
+ resetGroups() {
1180
+ this.groups = {};
1181
+ void this.persistGroups();
1182
+ }
1183
+ /** The accounts `group()` set, by type — a copy. */
1184
+ getGroups() {
1185
+ return { ...this.groups };
1186
+ }
1187
+ /**
1188
+ * A screen view — the app's page view, read under « Top pages » and usable as a
1189
+ * funnel step. Call it when a screen gets the focus, or let `trackScreens()` (React
1190
+ * Navigation) or Expo Router's `usePathname()` do it (docs: /docs/sdks/react-native).
1191
+ * The same screen reported twice in a row inside a session counts once (re-renders).
1192
+ * Custom events captured afterwards carry this screen as their page.
1193
+ */
1194
+ screen(name, props) {
1195
+ try {
1196
+ const s = (0, analytics_1.cleanScreenName)(name);
1197
+ if (!s)
1198
+ return;
1199
+ const now = Date.now();
1200
+ const sameVisit = this.analyticsSession !== null && now - this.analyticsSession.last <= analytics_1.ANALYTICS_SESSION_IDLE_MS;
1201
+ if (s === this.currentScreen && sameVisit)
1202
+ return;
1203
+ this.currentScreen = s;
1204
+ const p = (0, analytics_1.cleanProps)(props);
1205
+ this.queueAnalytics({ kind: "pageview", ts: now, screen: s, ...p ? { props: p } : {} });
1206
+ } catch {
1207
+ }
1208
+ }
1209
+ /**
1210
+ * Screen views from a React Navigation container, by themselves:
1211
+ *
1212
+ * const navigationRef = useNavigationContainerRef();
1213
+ * useEffect(() => Traqio.trackScreens(navigationRef), [navigationRef]);
1214
+ *
1215
+ * Returns the unsubscribe. Typed by shape: no navigation library is a dependency.
1216
+ */
1217
+ trackScreens(navigation) {
1218
+ const report = () => {
1219
+ try {
1220
+ const route = navigation.getCurrentRoute();
1221
+ if (route == null ? void 0 : route.name)
1222
+ this.screen(route.name);
1223
+ } catch {
1224
+ }
1225
+ };
1226
+ let off;
1227
+ try {
1228
+ off = navigation.addListener("state", report);
1229
+ } catch {
1230
+ off = void 0;
1231
+ }
1232
+ report();
1233
+ return () => {
1234
+ try {
1235
+ if (typeof off === "function")
1236
+ off();
1237
+ } catch {
1238
+ }
1239
+ };
1240
+ }
905
1241
  /**
906
1242
  * The store this app runs on: the native bridge's word, else React Native's
907
1243
  * `Platform.OS`, else UNKNOWN. Never a guess — until 2026-11 a missing bridge meant
@@ -1370,8 +1706,15 @@ var require_build = __commonJS({
1370
1706
  this.queue = [];
1371
1707
  this.adQueue = [];
1372
1708
  this.adBatchId = null;
1709
+ this.analyticsQueue = [];
1710
+ this.earlyAnalytics = [];
1711
+ this.superProps = {};
1712
+ this.groups = {};
1713
+ await this.persistSuperProps();
1714
+ await this.persistGroups();
1373
1715
  await this.persistQueue();
1374
1716
  await this.persistAdQueue();
1717
+ await this.persistAnalyticsQueue();
1375
1718
  try {
1376
1719
  await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(ERASED_KEY, "1"));
1377
1720
  } catch {
@@ -1384,6 +1727,101 @@ var require_build = __commonJS({
1384
1727
  void this.persistQueue();
1385
1728
  this.scheduleFlush();
1386
1729
  }
1730
+ /** Before `init()` the call waits in memory; after it, it is stamped and queued. */
1731
+ queueAnalytics(event) {
1732
+ var _a, _b;
1733
+ if (this.erased)
1734
+ return;
1735
+ let e = event;
1736
+ if (event.kind !== "identify" && event.kind !== "group") {
1737
+ const screen = (_b = (_a = event.screen) != null ? _a : this.currentScreen) != null ? _b : void 0;
1738
+ const props = (0, analytics_1.withSuperProps)(event.props, this.superProps);
1739
+ const groups = Object.keys(this.groups).length ? { ...this.groups } : void 0;
1740
+ e = { ...event, ...screen ? { screen } : {}, ...props ? { props } : {}, ...groups ? { groups } : {} };
1741
+ }
1742
+ if (!this.started) {
1743
+ if (this.earlyAnalytics.length < MAX_EARLY_ANALYTICS)
1744
+ this.earlyAnalytics.push(e);
1745
+ return;
1746
+ }
1747
+ if (this.isWeb)
1748
+ return;
1749
+ this.pushAnalytics(e);
1750
+ }
1751
+ pushAnalytics(e, schedule = true) {
1752
+ var _a, _b;
1753
+ if (e.kind === "identify" || e.kind === "group")
1754
+ this.analyticsQueue.push({ ...e, sessionId: (_b = (_a = this.analyticsSession) == null ? void 0 : _a.id) != null ? _b : "" });
1755
+ else {
1756
+ this.analyticsSession = (0, analytics_1.touchSession)(this.analyticsSession, e.ts, uuid);
1757
+ this.analyticsQueue.push({ ...e, sessionId: this.analyticsSession.id });
1758
+ }
1759
+ if (this.analyticsQueue.length > MAX_ANALYTICS_QUEUE)
1760
+ this.analyticsQueue.splice(0, this.analyticsQueue.length - MAX_ANALYTICS_QUEUE);
1761
+ void this.persistAnalyticsQueue();
1762
+ if (schedule)
1763
+ this.scheduleFlush();
1764
+ }
1765
+ /** The persisted queue first (older), then whatever was captured while it was being read. */
1766
+ async restoreAnalytics() {
1767
+ var _a, _b, _c, _d, _e;
1768
+ try {
1769
+ const raw = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(ANALYTICS_QUEUE_KEY));
1770
+ const stored = raw ? JSON.parse(raw) : null;
1771
+ if (Array.isArray(stored))
1772
+ this.analyticsQueue = [...stored, ...this.analyticsQueue].slice(-MAX_ANALYTICS_QUEUE);
1773
+ } catch {
1774
+ }
1775
+ try {
1776
+ (_c = this.analyticsSession) != null ? _c : this.analyticsSession = (0, analytics_1.parseSession)(await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(ANALYTICS_SESSION_KEY)));
1777
+ } catch {
1778
+ }
1779
+ try {
1780
+ const raw = await ((_d = this.opts.storage) == null ? void 0 : _d.getItem(SUPER_PROPS_KEY2));
1781
+ const early = Object.keys(this.superProps).length > 0;
1782
+ if (raw)
1783
+ this.superProps = (0, analytics_1.cleanTraits)({ ...(0, analytics_1.cleanTraits)(JSON.parse(raw)), ...this.superProps });
1784
+ if (early)
1785
+ await this.persistSuperProps();
1786
+ } catch {
1787
+ }
1788
+ try {
1789
+ const raw = await ((_e = this.opts.storage) == null ? void 0 : _e.getItem(GROUPS_KEY2));
1790
+ const early = Object.keys(this.groups).length > 0;
1791
+ if (raw)
1792
+ this.groups = (0, analytics_1.cleanGroups)({ ...(0, analytics_1.cleanGroups)(JSON.parse(raw)), ...this.groups });
1793
+ if (early)
1794
+ await this.persistGroups();
1795
+ } catch {
1796
+ }
1797
+ }
1798
+ async persistGroups() {
1799
+ var _a;
1800
+ if (!this.opts)
1801
+ return;
1802
+ try {
1803
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(GROUPS_KEY2, JSON.stringify(this.groups)));
1804
+ } catch {
1805
+ }
1806
+ }
1807
+ async persistSuperProps() {
1808
+ var _a;
1809
+ if (!this.opts)
1810
+ return;
1811
+ try {
1812
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(SUPER_PROPS_KEY2, JSON.stringify(this.superProps)));
1813
+ } catch {
1814
+ }
1815
+ }
1816
+ async persistAnalyticsQueue() {
1817
+ var _a, _b;
1818
+ try {
1819
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(ANALYTICS_QUEUE_KEY, JSON.stringify(this.analyticsQueue)));
1820
+ if (this.analyticsSession)
1821
+ await ((_b = this.opts.storage) == null ? void 0 : _b.setItem(ANALYTICS_SESSION_KEY, JSON.stringify(this.analyticsSession)));
1822
+ } catch {
1823
+ }
1824
+ }
1387
1825
  async restoreQueue() {
1388
1826
  var _a;
1389
1827
  try {
@@ -1613,10 +2051,10 @@ var require_build = __commonJS({
1613
2051
  }, delay);
1614
2052
  }
1615
2053
  async drain() {
1616
- var _a;
2054
+ var _a, _b;
1617
2055
  if (this.erased)
1618
2056
  return;
1619
- if (this.flushing || !this.queue.length && !this.adQueue.length)
2057
+ if (this.flushing || !this.queue.length && !this.adQueue.length && !this.analyticsQueue.length)
1620
2058
  return;
1621
2059
  this.flushing = true;
1622
2060
  try {
@@ -1662,6 +2100,22 @@ var require_build = __commonJS({
1662
2100
  await this.persistAdQueue();
1663
2101
  this.retryMs = BASE_RETRY_MS;
1664
2102
  }
2103
+ while (this.analyticsQueue.length) {
2104
+ const batch = this.analyticsQueue.slice(0, MAX_ANALYTICS_BATCH);
2105
+ const outcome = await this.send({
2106
+ anonymousId: (_b = this.context.deviceId) != null ? _b : await this.getOrCreateDeviceId(),
2107
+ userId: this.opts.userId,
2108
+ platform: this.hostPlatform,
2109
+ events: batch
2110
+ }, ANALYTICS_PATH);
2111
+ if (outcome === "retry")
2112
+ return this.backOff();
2113
+ if (outcome === "refused")
2114
+ console.warn(`[traqio] the server refused ${batch.length} analytics event(s) as malformed \u2014 dropped, not retried`);
2115
+ this.analyticsQueue.splice(0, batch.length);
2116
+ await this.persistAnalyticsQueue();
2117
+ this.retryMs = BASE_RETRY_MS;
2118
+ }
1665
2119
  } finally {
1666
2120
  this.flushing = false;
1667
2121
  }
@@ -2134,7 +2588,210 @@ var TrackIdKeeper = class {
2134
2588
  }
2135
2589
  };
2136
2590
 
2591
+ // src/vitals.ts
2592
+ var DEFAULT_VITALS_SAMPLE_RATE = 0.5;
2593
+ function sampled(rate, random = Math.random) {
2594
+ const r = typeof rate === "number" && Number.isFinite(rate) && rate >= 0 && rate <= 1 ? rate : DEFAULT_VITALS_SAMPLE_RATE;
2595
+ if (r <= 0) return false;
2596
+ return r >= 1 || random() < r;
2597
+ }
2598
+ var CLS_GAP_MS = 1e3;
2599
+ var CLS_WINDOW_MS = 5e3;
2600
+ var INP_KEEP = 10;
2601
+ var VitalsCollector = class {
2602
+ constructor() {
2603
+ this.clsMax = 0;
2604
+ this.clsSeen = false;
2605
+ this.clsWindow = { value: 0, first: 0, last: 0 };
2606
+ /** The longest interactions, by interactionId: their longest entry. */
2607
+ this.longest = /* @__PURE__ */ new Map();
2608
+ this.interactions = /* @__PURE__ */ new Set();
2609
+ this.inpSeen = false;
2610
+ }
2611
+ /** A `largest-contentful-paint` entry: the latest one is the LCP. */
2612
+ addLcp(startTime) {
2613
+ if (Number.isFinite(startTime) && startTime >= 0) this.lcp = startTime;
2614
+ }
2615
+ /** The `first-contentful-paint` paint entry. */
2616
+ addFcp(startTime) {
2617
+ if (this.fcp === void 0 && Number.isFinite(startTime) && startTime >= 0) this.fcp = startTime;
2618
+ }
2619
+ /** The navigation entry's `responseStart` (minus `activationStart` for a prerendered page). */
2620
+ setTtfb(ms) {
2621
+ if (Number.isFinite(ms) && ms >= 0) this.ttfb = ms;
2622
+ }
2623
+ /**
2624
+ * A `layout-shift` entry. Shifts right after an input are expected and skipped; the
2625
+ * rest are grouped in session windows and CLS is the largest window's sum.
2626
+ */
2627
+ addShift(value, startTime, hadRecentInput) {
2628
+ this.clsSeen = true;
2629
+ if (hadRecentInput || !Number.isFinite(value) || value < 0) return;
2630
+ const w = this.clsWindow;
2631
+ if (w.value > 0 && startTime - w.last < CLS_GAP_MS && startTime - w.first < CLS_WINDOW_MS) {
2632
+ w.value += value;
2633
+ w.last = startTime;
2634
+ } else {
2635
+ this.clsWindow = { value, first: startTime, last: startTime };
2636
+ }
2637
+ this.clsMax = Math.max(this.clsMax, this.clsWindow.value);
2638
+ }
2639
+ /** The browser supports layout shifts: a page that never moved has a CLS of 0, not none. */
2640
+ clsObserved() {
2641
+ this.clsSeen = true;
2642
+ }
2643
+ /** An `event` (or `first-input`) entry with an interactionId: one interaction's latency. */
2644
+ addInteraction(interactionId, duration) {
2645
+ if (!interactionId || !Number.isFinite(duration) || duration < 0) return;
2646
+ this.inpSeen = true;
2647
+ this.interactions.add(interactionId);
2648
+ const prev = this.longest.get(interactionId);
2649
+ if (prev !== void 0 && prev >= duration) return;
2650
+ this.longest.set(interactionId, duration);
2651
+ if (this.longest.size > INP_KEEP) {
2652
+ let minId = 0;
2653
+ let min = Infinity;
2654
+ for (const [id, d] of this.longest) {
2655
+ if (d < min) {
2656
+ min = d;
2657
+ minId = id;
2658
+ }
2659
+ }
2660
+ this.longest.delete(minId);
2661
+ }
2662
+ }
2663
+ /**
2664
+ * INP: the longest interaction, ignoring one per 50 — the 98th percentile for a busy
2665
+ * page, the worst one for an ordinary visit.
2666
+ */
2667
+ inp() {
2668
+ if (!this.inpSeen || !this.longest.size) return void 0;
2669
+ const sorted = [...this.longest.values()].sort((a, b) => b - a);
2670
+ return sorted[Math.min(sorted.length - 1, Math.floor(this.interactions.size / 50))];
2671
+ }
2672
+ /** What was measured, rounded: ms for the timings, 4 decimals for CLS. Null when nothing was. */
2673
+ snapshot() {
2674
+ const out = {};
2675
+ if (this.lcp !== void 0) out.lcp = Math.round(this.lcp);
2676
+ const inp = this.inp();
2677
+ if (inp !== void 0) out.inp = Math.round(inp);
2678
+ if (this.clsSeen) out.cls = Math.round(this.clsMax * 1e4) / 1e4;
2679
+ if (this.fcp !== void 0) out.fcp = Math.round(this.fcp);
2680
+ if (this.ttfb !== void 0) out.ttfb = Math.round(this.ttfb);
2681
+ return Object.keys(out).length ? out : null;
2682
+ }
2683
+ };
2684
+ function observe(type, onEntries, extra = {}) {
2685
+ var _a;
2686
+ try {
2687
+ const PO = globalThis.PerformanceObserver;
2688
+ if (!PO || !((_a = PO.supportedEntryTypes) == null ? void 0 : _a.includes(type))) return false;
2689
+ const po = new PO((list) => onEntries(list.getEntries()));
2690
+ po.observe({ type, buffered: true, ...extra });
2691
+ return true;
2692
+ } catch {
2693
+ return false;
2694
+ }
2695
+ }
2696
+ function watchVitals(c) {
2697
+ var _a;
2698
+ const startedVisible = typeof document === "undefined" || document.visibilityState !== "hidden";
2699
+ let activation = 0;
2700
+ try {
2701
+ const nav = performance.getEntriesByType("navigation")[0];
2702
+ if (nav) {
2703
+ activation = Math.max(0, (_a = nav.activationStart) != null ? _a : 0);
2704
+ if (typeof nav.responseStart === "number" && nav.responseStart > 0) c.setTtfb(Math.max(0, nav.responseStart - activation));
2705
+ }
2706
+ } catch {
2707
+ }
2708
+ if (startedVisible) {
2709
+ let lcpFinal = false;
2710
+ const finalize = () => {
2711
+ lcpFinal = true;
2712
+ };
2713
+ for (const type of ["keydown", "click", "pointerdown"]) window.addEventListener(type, finalize, { once: true, capture: true });
2714
+ observe("largest-contentful-paint", (es) => {
2715
+ if (lcpFinal) return;
2716
+ for (const e of es) c.addLcp(Math.max(0, e.startTime - activation));
2717
+ });
2718
+ observe("paint", (es) => {
2719
+ for (const e of es) if (e.name === "first-contentful-paint") c.addFcp(Math.max(0, e.startTime - activation));
2720
+ });
2721
+ }
2722
+ if (observe("layout-shift", (es) => es.forEach((e) => {
2723
+ var _a2;
2724
+ return c.addShift((_a2 = e.value) != null ? _a2 : 0, e.startTime, !!e.hadRecentInput);
2725
+ }))) c.clsObserved();
2726
+ observe("event", (es) => es.forEach((e) => {
2727
+ var _a2;
2728
+ return c.addInteraction((_a2 = e.interactionId) != null ? _a2 : 0, e.duration);
2729
+ }), { durationThreshold: 40 });
2730
+ observe("first-input", (es) => es.forEach((e) => {
2731
+ var _a2;
2732
+ return c.addInteraction((_a2 = e.interactionId) != null ? _a2 : 0, e.duration);
2733
+ }));
2734
+ }
2735
+
2137
2736
  // src/analytics.ts
2737
+ var GROUP_TYPE = /^[a-z][a-z0-9_]{0,29}$/;
2738
+ var MAX_GROUP_TYPES = 5;
2739
+ function cleanGroupType(v) {
2740
+ if (typeof v !== "string") return null;
2741
+ const t = v.trim();
2742
+ return GROUP_TYPE.test(t) ? t : null;
2743
+ }
2744
+ function cleanGroupKey(v) {
2745
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
2746
+ if (typeof v !== "string") return null;
2747
+ const t = v.trim();
2748
+ return t && t.length <= 256 ? t : null;
2749
+ }
2750
+ function cleanGroups(v) {
2751
+ const out = {};
2752
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return out;
2753
+ for (const [t, k] of Object.entries(v)) {
2754
+ if (Object.keys(out).length >= MAX_GROUP_TYPES) break;
2755
+ const type = cleanGroupType(t);
2756
+ const key = cleanGroupKey(k);
2757
+ if (type && key) out[type] = key;
2758
+ }
2759
+ return out;
2760
+ }
2761
+ function withGroup(groups, type, key) {
2762
+ const t = cleanGroupType(type);
2763
+ const k = cleanGroupKey(key);
2764
+ if (!t || !k) return null;
2765
+ if (!(t in groups) && Object.keys(groups).length >= MAX_GROUP_TYPES) return null;
2766
+ return { groups: { ...groups, [t]: k }, type: t, key: k, changed: groups[t] !== k };
2767
+ }
2768
+ var TRAIT_KEY = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
2769
+ var MAX_TRAITS = 50;
2770
+ var MAX_PROPS_BYTES = 4096;
2771
+ function cleanTraits(v) {
2772
+ const out = {};
2773
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return out;
2774
+ for (const [k, raw] of Object.entries(v)) {
2775
+ if (Object.keys(out).length >= MAX_TRAITS) break;
2776
+ if (!TRAIT_KEY.test(k)) continue;
2777
+ if (typeof raw === "string") {
2778
+ const t = raw.trim();
2779
+ if (t) out[k] = t.slice(0, 200);
2780
+ } else if (typeof raw === "number" && Number.isFinite(raw) || typeof raw === "boolean") {
2781
+ out[k] = raw;
2782
+ }
2783
+ }
2784
+ return out;
2785
+ }
2786
+ function withSuperProps(own, sup) {
2787
+ if (!Object.keys(sup).length) return own;
2788
+ const merged = { ...sup, ...own != null ? own : {} };
2789
+ try {
2790
+ return JSON.stringify(merged).length <= MAX_PROPS_BYTES ? merged : own;
2791
+ } catch {
2792
+ return own;
2793
+ }
2794
+ }
2138
2795
  var SESSION_KEY = "traq_session";
2139
2796
  var SESSION_IDLE_MS = 30 * 60 * 1e3;
2140
2797
  var FLUSH_EVERY_MS = 5e3;
@@ -2186,6 +2843,27 @@ function bare2(href) {
2186
2843
  return void 0;
2187
2844
  }
2188
2845
  }
2846
+ var RAGE_WINDOW_MS = 1e3;
2847
+ var RAGE_RADIUS_PX = 30;
2848
+ var RAGE_THRESHOLD = 3;
2849
+ var RageClickDetector = class {
2850
+ constructor() {
2851
+ this.burst = null;
2852
+ }
2853
+ hit(x, y, t) {
2854
+ const b = this.burst;
2855
+ const near = b !== null && t - b.last <= RAGE_WINDOW_MS && Math.hypot(x - b.x, y - b.y) <= RAGE_RADIUS_PX;
2856
+ if (!near || !b.reported && t - b.first > RAGE_WINDOW_MS) {
2857
+ this.burst = { x, y, first: t, last: t, count: 1, reported: false };
2858
+ return false;
2859
+ }
2860
+ b.count++;
2861
+ b.last = t;
2862
+ if (b.reported || b.count < RAGE_THRESHOLD) return false;
2863
+ b.reported = true;
2864
+ return true;
2865
+ }
2866
+ };
2189
2867
  var AnalyticsTracker = class {
2190
2868
  constructor(deps) {
2191
2869
  this.deps = deps;
@@ -2196,9 +2874,13 @@ var AnalyticsTracker = class {
2196
2874
  this.scrollUrl = null;
2197
2875
  this.errorsThisPage = 0;
2198
2876
  this.stopped = false;
2877
+ this.rage = new RageClickDetector();
2878
+ this.vitals = null;
2879
+ this.vitalsUrl = null;
2199
2880
  }
2200
2881
  /** Wires the listeners the options ask for and records the first page view. */
2201
2882
  start() {
2883
+ var _a;
2202
2884
  const o = this.deps.options;
2203
2885
  this.timer = setInterval(() => this.flush(false), FLUSH_EVERY_MS);
2204
2886
  document.addEventListener("visibilitychange", () => {
@@ -2210,17 +2892,48 @@ var AnalyticsTracker = class {
2210
2892
  this.watchRoutes();
2211
2893
  }
2212
2894
  if (o.clicks !== false) document.addEventListener("click", (e) => this.onClick(e), true);
2895
+ if (o.rageClicks !== false) document.addEventListener("click", (e) => this.onRageClick(e), true);
2213
2896
  if (o.scroll !== false) window.addEventListener("scroll", () => this.onScroll(), { passive: true });
2214
2897
  if (o.errors !== false) {
2215
2898
  window.addEventListener("error", (e) => this.onError(e));
2216
2899
  window.addEventListener("unhandledrejection", (e) => this.onRejection(e));
2217
2900
  }
2901
+ if (o.webVitals !== false) {
2902
+ const rate = typeof o.webVitals === "object" ? o.webVitals.sampleRate : DEFAULT_VITALS_SAMPLE_RATE;
2903
+ if (sampled(rate)) {
2904
+ this.vitals = new VitalsCollector();
2905
+ this.vitalsUrl = (_a = bare2(location.href)) != null ? _a : null;
2906
+ watchVitals(this.vitals);
2907
+ }
2908
+ }
2218
2909
  }
2219
2910
  /** A custom analytics event — never a conversion (that is `track()`). */
2220
2911
  capture(name, props) {
2221
- if (typeof name !== "string" || !name.trim() || name.startsWith("$")) return;
2912
+ if (typeof name !== "string" || !name.trim() || name.startsWith("$") && name.trim() !== "$exposure") return;
2222
2913
  this.enqueue({ kind: "custom", name: name.trim(), props });
2223
2914
  }
2915
+ /**
2916
+ * The user's properties (`identify(userId, traits, traitsOnce)`): one entry in the
2917
+ * batch, under its own user id. Not activity — it neither opens nor prolongs a session.
2918
+ */
2919
+ identify(userId, set, setOnce) {
2920
+ if (this.stopped || !userId) return;
2921
+ const hasSet = Object.keys(set).length > 0;
2922
+ const hasOnce = Object.keys(setOnce).length > 0;
2923
+ if (!hasSet && !hasOnce) return;
2924
+ this.queue.push({ kind: "identify", ts: Date.now(), userId, ...hasSet ? { set } : {}, ...hasOnce ? { setOnce } : {} });
2925
+ if (this.queue.length > MAX_QUEUE) this.queue.shift();
2926
+ if (this.queue.length >= FLUSH_AT) this.flush(false);
2927
+ }
2928
+ /** An account's properties (`group(type, key, traits)`): one entry in the batch. Not activity either. */
2929
+ group(groupType, groupKey, set, setOnce) {
2930
+ if (this.stopped) return;
2931
+ const hasSet = Object.keys(set).length > 0;
2932
+ const hasOnce = Object.keys(setOnce).length > 0;
2933
+ this.queue.push({ kind: "group", ts: Date.now(), groupType, groupKey, ...hasSet ? { set } : {}, ...hasOnce ? { setOnce } : {} });
2934
+ if (this.queue.length > MAX_QUEUE) this.queue.shift();
2935
+ if (this.queue.length >= FLUSH_AT) this.flush(false);
2936
+ }
2224
2937
  /** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */
2225
2938
  pageview() {
2226
2939
  const url = bare2(location.href);
@@ -2297,18 +3010,30 @@ var AnalyticsTracker = class {
2297
3010
  return s;
2298
3011
  }
2299
3012
  enqueue(e) {
2300
- var _a, _b;
3013
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2301
3014
  if (this.stopped) return;
2302
3015
  const s = this.session();
2303
3016
  const title = typeof document.title === "string" && document.title ? document.title.slice(0, 200) : void 0;
2304
- this.queue.push({ ...e, ts: Date.now(), url: (_b = (_a = e.url) != null ? _a : bare2(location.href)) != null ? _b : "", title, sessionId: s.id, ...s.src ? { src: s.src } : {} });
3017
+ const props = e.kind === "scroll" || e.kind === "vitals" ? e.props : withSuperProps(e.props, (_c = (_b = (_a = this.deps).superProps) == null ? void 0 : _b.call(_a)) != null ? _c : {});
3018
+ const g = (_f = (_e = (_d = this.deps).groups) == null ? void 0 : _e.call(_d)) != null ? _f : {};
3019
+ const groups = Object.keys(g).length ? { ...g } : void 0;
3020
+ this.queue.push({ ...e, ...props ? { props } : {}, ...groups ? { groups } : {}, ts: Date.now(), url: (_h = (_g = e.url) != null ? _g : bare2(location.href)) != null ? _h : "", title, sessionId: s.id, ...s.src ? { src: s.src } : {} });
2305
3021
  if (this.queue.length > MAX_QUEUE) this.queue.shift();
2306
3022
  if (this.queue.length >= FLUSH_AT) this.flush(false);
2307
3023
  }
2308
3024
  leave() {
2309
3025
  this.sendScroll();
3026
+ this.sendVitals();
2310
3027
  this.flush(true);
2311
3028
  }
3029
+ /** Once per load, at the first hide: LCP is final then, and CLS and INP have seen the visit. */
3030
+ sendVitals() {
3031
+ const c = this.vitals;
3032
+ if (!c || !this.vitalsUrl) return;
3033
+ this.vitals = null;
3034
+ const props = c.snapshot();
3035
+ if (props) this.enqueue({ kind: "vitals", url: this.vitalsUrl, props: { ...props } });
3036
+ }
2312
3037
  /** Single-page apps change the URL through the history API: wrap it, and listen for back/forward. */
2313
3038
  watchRoutes() {
2314
3039
  if (typeof history === "undefined") return;
@@ -2356,6 +3081,23 @@ var AnalyticsTracker = class {
2356
3081
  if (el.id) props.id = el.id.slice(0, 100);
2357
3082
  this.enqueue({ kind: "click", props });
2358
3083
  }
3084
+ /** Any element: frustration is most telling where nothing was clickable. */
3085
+ onRageClick(e) {
3086
+ var _a;
3087
+ const x = typeof e.clientX === "number" ? e.clientX : 0;
3088
+ const y = typeof e.clientY === "number" ? e.clientY : 0;
3089
+ if (!this.rage.hit(x, y, Date.now())) return;
3090
+ const target = e.target;
3091
+ if (!target || typeof target.closest !== "function" || target.closest("[data-traqio-ignore]")) return;
3092
+ const el = (_a = target.closest("a, button, [role='button'], input[type='submit'], input[type='button']")) != null ? _a : target;
3093
+ const text = (el.tagName === "INPUT" ? el.value : el.innerText || el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 100);
3094
+ const props = { tag: el.tagName.toLowerCase(), count: RAGE_THRESHOLD };
3095
+ if (text) props.text = text;
3096
+ const href = el.tagName === "A" ? bare2(el.getAttribute("href")) : void 0;
3097
+ if (href) props.href = href;
3098
+ if (el.id) props.id = el.id.slice(0, 100);
3099
+ this.enqueue({ kind: "rageclick", props });
3100
+ }
2359
3101
  onError(e) {
2360
3102
  if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
2361
3103
  const message = (e.message || (e.error instanceof Error ? e.error.message : "") || "Script error").slice(0, 300);
@@ -2375,6 +3117,8 @@ var AnalyticsTracker = class {
2375
3117
 
2376
3118
  // src/index.ts
2377
3119
  var DEFAULT_ENDPOINT = "https://api.traqio.app";
3120
+ var SUPER_PROPS_KEY = "traq_super";
3121
+ var GROUPS_KEY = "traq_groups";
2378
3122
  var DEFAULT_TRACK_ID_DAYS = 30;
2379
3123
  var DAY_MS = 24 * 60 * 60 * 1e3;
2380
3124
  function inBrowser() {
@@ -2400,6 +3144,14 @@ var TraqioWeb = class {
2400
3144
  this.earlyCaptures = [];
2401
3145
  /** `init()` has finished (or will never run here): early captures are no longer kept. */
2402
3146
  this.ready = false;
3147
+ /** `register()`: properties added to every analytics event, kept in `traq_super`. */
3148
+ this.superProps = {};
3149
+ /** `identify()` calls with traits made before `init()` — replayed once the tracker exists. */
3150
+ this.earlyIdentifies = [];
3151
+ /** `group()`: the accounts every analytics event is stamped with, kept in `traq_groups`. */
3152
+ this.groups = {};
3153
+ /** Group entries made before `init()` — replayed once the tracker exists. */
3154
+ this.earlyGroups = [];
2403
3155
  }
2404
3156
  /**
2405
3157
  * Call once, as early as possible on every page (or once in a single-page app).
@@ -2408,7 +3160,7 @@ var TraqioWeb = class {
2408
3160
  * does nothing there.
2409
3161
  */
2410
3162
  async init(opts) {
2411
- var _a, _b, _c;
3163
+ var _a, _b, _c, _d;
2412
3164
  if (this.started || !inBrowser()) return;
2413
3165
  this.started = true;
2414
3166
  this.waitForConsent = opts.waitForConsent === true;
@@ -2427,14 +3179,28 @@ var TraqioWeb = class {
2427
3179
  const id = randomId();
2428
3180
  if (id) this.store.setSync(DEVICE_ID_KEY, id);
2429
3181
  }
2430
- this.userId = opts.userId;
2431
- const endpoint = ((_c = opts.endpoint) != null ? _c : DEFAULT_ENDPOINT).replace(/\/+$/, "");
3182
+ this.userId = (_c = opts.userId) != null ? _c : this.userId;
3183
+ try {
3184
+ const raw = this.store.getSync(SUPER_PROPS_KEY);
3185
+ const early = Object.keys(this.superProps).length > 0;
3186
+ if (raw) this.superProps = cleanTraits({ ...cleanTraits(JSON.parse(raw)), ...this.superProps });
3187
+ if (early) this.store.setSync(SUPER_PROPS_KEY, JSON.stringify(this.superProps));
3188
+ } catch {
3189
+ }
3190
+ try {
3191
+ const raw = this.store.getSync(GROUPS_KEY);
3192
+ const early = Object.keys(this.groups).length > 0;
3193
+ if (raw) this.groups = cleanGroups({ ...cleanGroups(JSON.parse(raw)), ...this.groups });
3194
+ if (early) this.store.setSync(GROUPS_KEY, JSON.stringify(this.groups));
3195
+ } catch {
3196
+ }
3197
+ const endpoint = ((_d = opts.endpoint) != null ? _d : DEFAULT_ENDPOINT).replace(/\/+$/, "");
2432
3198
  await this.core.init({
2433
3199
  sdkKey: opts.sdkKey,
2434
3200
  endpoint,
2435
3201
  storage: this.store,
2436
3202
  platform: "web",
2437
- userId: opts.userId,
3203
+ userId: this.userId,
2438
3204
  consent,
2439
3205
  debug: opts.debug,
2440
3206
  lifecycle: ({ background, foreground }) => {
@@ -2450,14 +3216,20 @@ var TraqioWeb = class {
2450
3216
  sdkKey: opts.sdkKey,
2451
3217
  anonymousId: () => store.getSync(DEVICE_ID_KEY),
2452
3218
  userId: () => this.userId,
3219
+ superProps: () => this.superProps,
3220
+ groups: () => this.groups,
2453
3221
  isDebug: () => this.core.isDebug,
2454
3222
  isForgotten: () => this.core.forgotten,
2455
3223
  options: opts.analytics === true ? {} : opts.analytics
2456
3224
  });
2457
3225
  this.analytics.start();
3226
+ for (const [id, set, once] of this.earlyIdentifies) this.analytics.identify(id, set, once);
3227
+ for (const [type, key, set, once] of this.earlyGroups) this.analytics.group(type, key, set, once);
2458
3228
  for (const [name, props] of this.earlyCaptures) this.analytics.capture(name, props);
2459
3229
  }
2460
3230
  this.earlyCaptures = [];
3231
+ this.earlyIdentifies = [];
3232
+ this.earlyGroups = [];
2461
3233
  this.ready = true;
2462
3234
  }
2463
3235
  /** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
@@ -2472,7 +3244,8 @@ var TraqioWeb = class {
2472
3244
  * A product-analytics event — `search_performed`, `pricing_toggled`… — read in the
2473
3245
  * console's Analytics section (events, funnels). NOT a conversion: it is never
2474
3246
  * billed nor sent to an ad network. A conversion (sign-up, purchase) is `track()`.
2475
- * Needs `analytics` at init; names starting with `$` are reserved.
3247
+ * Needs `analytics` at init; names starting with `$` are reserved, but for an
3248
+ * experiment exposure: `capture("$exposure", { experiment, variant })`.
2476
3249
  */
2477
3250
  capture(name, props) {
2478
3251
  if (this.analytics) this.analytics.capture(name, props);
@@ -2491,6 +3264,98 @@ var TraqioWeb = class {
2491
3264
  this.userId = id;
2492
3265
  this.core.setUserId(id);
2493
3266
  }
3267
+ /**
3268
+ * Who the user is, and what they are: sets the user id (like `setUserId`) and, with
3269
+ * traits, the user's PROPERTIES — `plan`, `role`, `company_size` — read in the
3270
+ * console as a breakdown, a report dimension and a cohort condition. Needs
3271
+ * `analytics` at init for the traits.
3272
+ *
3273
+ * Traqio.identify("u_123", { plan: "pro", seats: 12 }, { signup_source: "webinar" });
3274
+ *
3275
+ * `traits` overwrite what was set before; `traitsOnce` are written only where the
3276
+ * user has no value yet. Text, numbers, booleans — never an email or a name. At most 50 keys.
3277
+ */
3278
+ identify(userId, traits, traitsOnce) {
3279
+ const id = typeof userId === "string" ? userId.trim() : "";
3280
+ if (!id) return;
3281
+ this.setUserId(id);
3282
+ const set = cleanTraits(traits);
3283
+ const once = cleanTraits(traitsOnce);
3284
+ if (!Object.keys(set).length && !Object.keys(once).length) return;
3285
+ if (this.analytics) this.analytics.identify(id, set, once);
3286
+ else if (!this.ready && this.earlyIdentifies.length < 10) this.earlyIdentifies.push([id, set, once]);
3287
+ }
3288
+ /**
3289
+ * Super-properties: added to EVERY analytics event from now on, on this page and the
3290
+ * next ones — an A/B arm, a pricing variant, a theme. An event's own property of the
3291
+ * same name wins. Kept with the visitor id (same consent rules). `unregister(key)` removes one.
3292
+ *
3293
+ * Traqio.register({ pricing_variant: "b" });
3294
+ */
3295
+ register(props) {
3296
+ this.superProps = cleanTraits({ ...this.superProps, ...cleanTraits(props) });
3297
+ this.persistSuperProps();
3298
+ }
3299
+ /** Stop adding one super-property to the events. */
3300
+ unregister(key) {
3301
+ if (typeof key !== "string" || !(key in this.superProps)) return;
3302
+ const rest = { ...this.superProps };
3303
+ delete rest[key];
3304
+ this.superProps = rest;
3305
+ this.persistSuperProps();
3306
+ }
3307
+ /** The super-properties `register()` set — a copy. */
3308
+ getSuperProperties() {
3309
+ return { ...this.superProps };
3310
+ }
3311
+ /**
3312
+ * The B2B ACCOUNT the visitor works in (group analytics): every analytics event from
3313
+ * now on — on this page and the next ones — counts for it, so the console can count
3314
+ * accounts (unique accounts, funnels, retention, cohorts « by company ») and list them
3315
+ * with their traits. Call it after sign-in, and again on an account switch. Needs
3316
+ * `analytics` at init.
3317
+ *
3318
+ * Traqio.group("company", "acc_42", { plan: "enterprise", seats: 40 });
3319
+ *
3320
+ * `groupType` is lowercase (`company`, `workspace`; 5 types at most), `groupKey` your
3321
+ * own account id — never an email. Traits follow identify's rules.
3322
+ */
3323
+ group(groupType, groupKey, traits, traitsOnce) {
3324
+ const next = withGroup(this.groups, groupType, groupKey);
3325
+ if (!next) return;
3326
+ this.groups = next.groups;
3327
+ this.persistGroups();
3328
+ const set = cleanTraits(traits);
3329
+ const once = cleanTraits(traitsOnce);
3330
+ if (!next.changed && !Object.keys(set).length && !Object.keys(once).length) return;
3331
+ if (this.analytics) this.analytics.group(next.type, next.key, set, once);
3332
+ else if (!this.ready && this.earlyGroups.length < 10) this.earlyGroups.push([next.type, next.key, set, once]);
3333
+ }
3334
+ /** Stop stamping the events with any account — call it on sign-out. */
3335
+ resetGroups() {
3336
+ this.groups = {};
3337
+ this.persistGroups();
3338
+ }
3339
+ /** The accounts `group()` set, by type — a copy. */
3340
+ getGroups() {
3341
+ return { ...this.groups };
3342
+ }
3343
+ persistGroups() {
3344
+ try {
3345
+ if (!this.store) return;
3346
+ if (Object.keys(this.groups).length) this.store.setSync(GROUPS_KEY, JSON.stringify(this.groups));
3347
+ else this.store.removeSync(GROUPS_KEY);
3348
+ } catch {
3349
+ }
3350
+ }
3351
+ persistSuperProps() {
3352
+ try {
3353
+ if (!this.store) return;
3354
+ if (Object.keys(this.superProps).length) this.store.setSync(SUPER_PROPS_KEY, JSON.stringify(this.superProps));
3355
+ else this.store.removeSync(SUPER_PROPS_KEY);
3356
+ } catch {
3357
+ }
3358
+ }
2494
3359
  /**
2495
3360
  * The visitor's consent answer. Governs sharing with ad networks, and — with
2496
3361
  * `waitForConsent` — whether anything may be stored: `true` writes out what the
@@ -2543,6 +3408,10 @@ var TraqioWeb = class {
2543
3408
  (_a = this.trackIds) == null ? void 0 : _a.clear();
2544
3409
  (_b = this.sources) == null ? void 0 : _b.clear();
2545
3410
  (_c = this.analytics) == null ? void 0 : _c.stop();
3411
+ this.superProps = {};
3412
+ this.persistSuperProps();
3413
+ this.groups = {};
3414
+ this.persistGroups();
2546
3415
  }
2547
3416
  return ok;
2548
3417
  }