@traqio/web 0.5.0 → 0.6.1

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.cjs CHANGED
@@ -236,6 +236,10 @@ var require_analytics = __commonJS({
236
236
  "use strict";
237
237
  Object.defineProperty(exports, "__esModule", { value: true });
238
238
  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;
239
+ exports.cleanUserId = cleanUserId2;
240
+ exports.isEntry = isEntry2;
241
+ exports.nextAnalyticsBatch = nextAnalyticsBatch;
242
+ exports.exposureProps = exposureProps2;
239
243
  exports.cleanGroupType = cleanGroupType2;
240
244
  exports.cleanGroupKey = cleanGroupKey2;
241
245
  exports.cleanGroups = cleanGroups2;
@@ -247,6 +251,49 @@ var require_analytics = __commonJS({
247
251
  exports.cleanProps = cleanProps;
248
252
  exports.touchSession = touchSession;
249
253
  exports.parseSession = parseSession;
254
+ function cleanUserId2(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 <= 256 ? t : null;
261
+ }
262
+ function isEntry2(kind) {
263
+ return kind === "identify" || kind === "group" || kind === "alias";
264
+ }
265
+ function nextAnalyticsBatch(queue, current, max) {
266
+ let userId;
267
+ let fixed = false;
268
+ const events = [];
269
+ for (const e of queue) {
270
+ if (events.length >= max)
271
+ break;
272
+ if (!isEntry2(e.kind)) {
273
+ const who = e.asUser !== void 0 ? e.asUser || void 0 : current;
274
+ if (!fixed) {
275
+ userId = who;
276
+ fixed = true;
277
+ } else if (who !== userId)
278
+ break;
279
+ }
280
+ const { asUser: _asUser, ...wire } = e;
281
+ events.push(wire);
282
+ }
283
+ return { events, userId: fixed ? userId : current, taken: events.length };
284
+ }
285
+ var MAX_EXPOSURE_TEXT = 200;
286
+ function exposureText2(v) {
287
+ const t = typeof v === "string" ? v.trim() : typeof v === "number" && Number.isFinite(v) || typeof v === "boolean" ? String(v) : "";
288
+ return t && t.length <= MAX_EXPOSURE_TEXT ? t : null;
289
+ }
290
+ function exposureProps2(experiment, variant, props) {
291
+ const e = exposureText2(experiment);
292
+ const v = exposureText2(variant);
293
+ if (!e || !v)
294
+ return null;
295
+ return { ...props && typeof props === "object" && !Array.isArray(props) ? props : {}, experiment: e, variant: v };
296
+ }
250
297
  var GROUP_TYPE2 = /^[a-z][a-z0-9_]{0,29}$/;
251
298
  exports.MAX_GROUP_TYPES = 5;
252
299
  var MAX_GROUP_KEY = 256;
@@ -768,6 +815,7 @@ var require_build = __commonJS({
768
815
  "use strict";
769
816
  Object.defineProperty(exports, "__esModule", { value: true });
770
817
  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;
818
+ exports.normalizeMetaInstallReferrers = normalizeMetaInstallReferrers;
771
819
  exports.normalizeAdvertisingId = normalizeAdvertisingId;
772
820
  exports.fromMaxAd = fromMaxAd;
773
821
  exports.detectDebug = detectDebug;
@@ -777,7 +825,7 @@ var require_build = __commonJS({
777
825
  var adservices_1 = require_adservices();
778
826
  var deeplink_1 = require_deeplink();
779
827
  var adRevenue_1 = require_adRevenue();
780
- exports.SDK_VERSION = "0.8.0";
828
+ exports.SDK_VERSION = "0.10.0";
781
829
  var skan_2 = require_skan();
782
830
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
783
831
  return skan_2.Skan;
@@ -868,6 +916,32 @@ var require_build = __commonJS({
868
916
  var FLUSH_DELAY_MS = 3e3;
869
917
  var MAX_INSTALL_ATTEMPTS = 3;
870
918
  var SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
919
+ var META_PROVIDERS = ["facebook", "instagram", "facebook_lite"];
920
+ function normalizeMetaInstallReferrers(raw) {
921
+ if (!Array.isArray(raw))
922
+ return [];
923
+ const out = [];
924
+ for (const item of raw) {
925
+ if (!item || typeof item !== "object")
926
+ continue;
927
+ const r = item;
928
+ if (typeof r.provider !== "string" || !META_PROVIDERS.includes(r.provider))
929
+ continue;
930
+ if (typeof r.installReferrer !== "string" || !r.installReferrer.trim())
931
+ continue;
932
+ const isCt = r.isCt === 1 || r.isCt === true ? 1 : r.isCt === 0 || r.isCt === false ? 0 : null;
933
+ if (isCt === null)
934
+ continue;
935
+ const ts = typeof r.actualTimestamp === "number" && Number.isFinite(r.actualTimestamp) && r.actualTimestamp > 0 ? r.actualTimestamp : void 0;
936
+ out.push({
937
+ provider: r.provider,
938
+ installReferrer: r.installReferrer,
939
+ isCt,
940
+ ...ts !== void 0 ? { actualTimestamp: ts } : {}
941
+ });
942
+ }
943
+ return out;
944
+ }
871
945
  var TRACKING_AUTHORIZATIONS = ["not_determined", "restricted", "denied", "authorized"];
872
946
  var MAX_PRECISION = {
873
947
  exact: "precise",
@@ -975,6 +1049,7 @@ var require_build = __commonJS({
975
1049
  this.currentScreen = null;
976
1050
  this.superProps = {};
977
1051
  this.groups = {};
1052
+ this.resetBeforeInit = false;
978
1053
  this.maxRevenuePaid = (adInfo) => {
979
1054
  try {
980
1055
  const max = (0, adRevenue_1.fromMaxAdInfo)(adInfo);
@@ -1023,7 +1098,10 @@ var require_build = __commonJS({
1023
1098
  this.wireDeepLinks();
1024
1099
  }
1025
1100
  }
1026
- await this.maybeStartSession(!this.isWeb);
1101
+ if (this.isWeb)
1102
+ void this.maybeStartSession(false);
1103
+ else
1104
+ await this.maybeStartSession(true);
1027
1105
  await this.initSkan();
1028
1106
  await this.initAppleAds();
1029
1107
  this.wireLifecycle();
@@ -1189,6 +1267,81 @@ var require_build = __commonJS({
1189
1267
  getGroups() {
1190
1268
  return { ...this.groups };
1191
1269
  }
1270
+ /**
1271
+ * Two ids, one person: the user known so far as `previousId` (a guest id, an id
1272
+ * from before sign-up, an older system's) IS the current user (`setUserId` /
1273
+ * `identify`). Their analytics history and properties are merged under the current
1274
+ * id — the current id's own properties win. From an app, only what THIS device sent
1275
+ * under `previousId` is merged; a backend (secret key) merges everything.
1276
+ *
1277
+ * Traqio.identify("u_123");
1278
+ * Traqio.alias("guest_8f2c");
1279
+ *
1280
+ * Ignored without a current user id, or when `previousId` is the current one.
1281
+ */
1282
+ alias(previousId) {
1283
+ try {
1284
+ const userId = this.opts ? this.opts.userId : this.earlyUserId;
1285
+ const prev = (0, analytics_1.cleanUserId)(previousId);
1286
+ if (!userId || !prev || prev === userId)
1287
+ return;
1288
+ this.queueAnalytics({ kind: "alias", ts: Date.now(), userId, previousId: prev });
1289
+ } catch {
1290
+ }
1291
+ }
1292
+ /**
1293
+ * Sign-out: forget who the user was on this device — the user id, the
1294
+ * super-properties (`register`), the accounts (`group`) — and end the analytics
1295
+ * session, so the next person's visit starts clean. Events already queued keep the
1296
+ * user they were captured under. The device id is KEPT: it is the install's
1297
+ * attribution identity, and a new one would read as a new install.
1298
+ */
1299
+ reset() {
1300
+ try {
1301
+ const userId = this.opts ? this.opts.userId : this.earlyUserId;
1302
+ if (userId) {
1303
+ for (const e of this.analyticsQueue)
1304
+ if (!(0, analytics_1.isEntry)(e.kind) && e.asUser === void 0)
1305
+ e.asUser = userId;
1306
+ for (const e of this.earlyAnalytics)
1307
+ if (!(0, analytics_1.isEntry)(e.kind) && e.asUser === void 0)
1308
+ e.asUser = userId;
1309
+ }
1310
+ if (this.opts)
1311
+ this.opts.userId = void 0;
1312
+ else {
1313
+ this.earlyUserId = void 0;
1314
+ this.resetBeforeInit = true;
1315
+ }
1316
+ this.superProps = {};
1317
+ this.groups = {};
1318
+ this.analyticsSession = null;
1319
+ this.currentScreen = null;
1320
+ if (this.opts && this.isWeb)
1321
+ return;
1322
+ void this.persistSuperProps();
1323
+ void this.persistGroups();
1324
+ void this.forgetAnalyticsSession();
1325
+ } catch {
1326
+ }
1327
+ }
1328
+ /**
1329
+ * An experiment exposure: the user SAW `variant` of `experiment` — what the console's
1330
+ * experiment analysis reads (uplift and significance per variant). Your app assigns
1331
+ * the variant (its own flags, a remote config, a hash); call this where the user
1332
+ * first meets it. Sends `$exposure { experiment, variant, ...props }`.
1333
+ *
1334
+ * Traqio.exposure("paywall_copy", "b");
1335
+ */
1336
+ exposure(experiment, variant, props) {
1337
+ var _a;
1338
+ try {
1339
+ const p = (0, analytics_1.exposureProps)(experiment, variant, props);
1340
+ if (p)
1341
+ this.capture(analytics_1.EXPOSURE_EVENT, (_a = (0, analytics_1.cleanProps)(p)) != null ? _a : { experiment: p.experiment, variant: p.variant });
1342
+ } catch {
1343
+ }
1344
+ }
1192
1345
  /**
1193
1346
  * A screen view — the app's page view, read under « Top pages » and usable as a
1194
1347
  * funnel step. Call it when a screen gets the focus, or let `trackScreens()` (React
@@ -1738,7 +1891,7 @@ var require_build = __commonJS({
1738
1891
  if (this.erased)
1739
1892
  return;
1740
1893
  let e = event;
1741
- if (event.kind !== "identify" && event.kind !== "group") {
1894
+ if (!(0, analytics_1.isEntry)(event.kind)) {
1742
1895
  const screen = (_b = (_a = event.screen) != null ? _a : this.currentScreen) != null ? _b : void 0;
1743
1896
  const props = (0, analytics_1.withSuperProps)(event.props, this.superProps);
1744
1897
  const groups = Object.keys(this.groups).length ? { ...this.groups } : void 0;
@@ -1754,12 +1907,12 @@ var require_build = __commonJS({
1754
1907
  this.pushAnalytics(e);
1755
1908
  }
1756
1909
  pushAnalytics(e, schedule = true) {
1757
- var _a, _b;
1758
- if (e.kind === "identify" || e.kind === "group")
1910
+ var _a, _b, _c;
1911
+ if ((0, analytics_1.isEntry)(e.kind))
1759
1912
  this.analyticsQueue.push({ ...e, sessionId: (_b = (_a = this.analyticsSession) == null ? void 0 : _a.id) != null ? _b : "" });
1760
1913
  else {
1761
1914
  this.analyticsSession = (0, analytics_1.touchSession)(this.analyticsSession, e.ts, uuid);
1762
- this.analyticsQueue.push({ ...e, sessionId: this.analyticsSession.id });
1915
+ this.analyticsQueue.push({ ...e, id: (_c = e.id) != null ? _c : uuid(), sessionId: this.analyticsSession.id });
1763
1916
  }
1764
1917
  if (this.analyticsQueue.length > MAX_ANALYTICS_QUEUE)
1765
1918
  this.analyticsQueue.splice(0, this.analyticsQueue.length - MAX_ANALYTICS_QUEUE);
@@ -1778,9 +1931,17 @@ var require_build = __commonJS({
1778
1931
  } catch {
1779
1932
  }
1780
1933
  try {
1781
- (_c = this.analyticsSession) != null ? _c : this.analyticsSession = (0, analytics_1.parseSession)(await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(ANALYTICS_SESSION_KEY)));
1934
+ if (!this.resetBeforeInit)
1935
+ (_c = this.analyticsSession) != null ? _c : this.analyticsSession = (0, analytics_1.parseSession)(await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(ANALYTICS_SESSION_KEY)));
1782
1936
  } catch {
1783
1937
  }
1938
+ if (this.resetBeforeInit) {
1939
+ this.resetBeforeInit = false;
1940
+ await this.persistSuperProps();
1941
+ await this.persistGroups();
1942
+ await this.forgetAnalyticsSession();
1943
+ return;
1944
+ }
1784
1945
  try {
1785
1946
  const raw = await ((_d = this.opts.storage) == null ? void 0 : _d.getItem(SUPER_PROPS_KEY2));
1786
1947
  const early = Object.keys(this.superProps).length > 0;
@@ -1800,6 +1961,16 @@ var require_build = __commonJS({
1800
1961
  } catch {
1801
1962
  }
1802
1963
  }
1964
+ async forgetAnalyticsSession() {
1965
+ var _a;
1966
+ if (!this.opts)
1967
+ return;
1968
+ try {
1969
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(ANALYTICS_SESSION_KEY, ""));
1970
+ await this.persistAnalyticsQueue();
1971
+ } catch {
1972
+ }
1973
+ }
1803
1974
  async persistGroups() {
1804
1975
  var _a;
1805
1976
  if (!this.opts)
@@ -1965,6 +2136,24 @@ var require_build = __commonJS({
1965
2136
  }
1966
2137
  return result;
1967
2138
  }
2139
+ /**
2140
+ * Meta's Install Referrer answers, Android only, read just before the install
2141
+ * leaves. Never throws: an old native build, a bridge teardown or no Meta app
2142
+ * installed all mean « no field ».
2143
+ */
2144
+ async readMetaInstallReferrers(platform) {
2145
+ var _a, _b;
2146
+ const read = (_a = this.opts.native) == null ? void 0 : _a.getMetaInstallReferrers;
2147
+ if (platform !== "android" || !read)
2148
+ return void 0;
2149
+ try {
2150
+ const appId = ((_b = this.opts.metaAppId) == null ? void 0 : _b.trim()) || void 0;
2151
+ const list = normalizeMetaInstallReferrers(await read.call(this.opts.native, appId));
2152
+ return list.length ? list : void 0;
2153
+ } catch {
2154
+ return void 0;
2155
+ }
2156
+ }
1968
2157
  /** Only with the host's opt-in; a zeroed or malformed id is never sent. */
1969
2158
  async readAdvertisingId() {
1970
2159
  var _a;
@@ -1997,10 +2186,12 @@ var require_build = __commonJS({
1997
2186
  }
1998
2187
  }
1999
2188
  const advertisingId = await this.readAdvertisingId();
2189
+ const metaInstallReferrers = await this.readMetaInstallReferrers(platform);
2000
2190
  const ok = await this.post({
2001
2191
  install: {
2002
2192
  platform,
2003
2193
  installReferrer: referrer.referrer,
2194
+ ...metaInstallReferrers ? { metaInstallReferrers } : {},
2004
2195
  appUserId: this.opts.userId,
2005
2196
  advertisingId,
2006
2197
  context: this.context
@@ -2106,18 +2297,18 @@ var require_build = __commonJS({
2106
2297
  this.retryMs = BASE_RETRY_MS;
2107
2298
  }
2108
2299
  while (this.analyticsQueue.length) {
2109
- const batch = this.analyticsQueue.slice(0, MAX_ANALYTICS_BATCH);
2300
+ const batch = (0, analytics_1.nextAnalyticsBatch)(this.analyticsQueue, this.opts.userId, MAX_ANALYTICS_BATCH);
2110
2301
  const outcome = await this.send({
2111
2302
  anonymousId: (_b = this.context.deviceId) != null ? _b : await this.getOrCreateDeviceId(),
2112
- userId: this.opts.userId,
2303
+ userId: batch.userId,
2113
2304
  platform: this.hostPlatform,
2114
- events: batch
2305
+ events: batch.events
2115
2306
  }, ANALYTICS_PATH);
2116
2307
  if (outcome === "retry")
2117
2308
  return this.backOff();
2118
2309
  if (outcome === "refused")
2119
- console.warn(`[traqio] the server refused ${batch.length} analytics event(s) as malformed \u2014 dropped, not retried`);
2120
- this.analyticsQueue.splice(0, batch.length);
2310
+ console.warn(`[traqio] the server refused ${batch.taken} analytics event(s) as malformed \u2014 dropped, not retried`);
2311
+ this.analyticsQueue.splice(0, batch.taken);
2121
2312
  await this.persistAnalyticsQueue();
2122
2313
  this.retryMs = BASE_RETRY_MS;
2123
2314
  }
@@ -2246,7 +2437,8 @@ var index_exports = {};
2246
2437
  __export(index_exports, {
2247
2438
  DEFAULT_ENDPOINT: () => DEFAULT_ENDPOINT,
2248
2439
  Traqio: () => Traqio,
2249
- TraqioWeb: () => TraqioWeb
2440
+ TraqioWeb: () => TraqioWeb,
2441
+ internalParam: () => internalParam
2250
2442
  });
2251
2443
  module.exports = __toCommonJS(index_exports);
2252
2444
  var import_core = __toESM(require_build(), 1);
@@ -2306,7 +2498,8 @@ function deleteCookie(name, domain) {
2306
2498
 
2307
2499
  // src/storage.ts
2308
2500
  var DEVICE_ID_KEY = "traq_device_id";
2309
- var MIRRORED = /* @__PURE__ */ new Set([DEVICE_ID_KEY]);
2501
+ var INTERNAL_KEY = "traq_internal";
2502
+ var MIRRORED = /* @__PURE__ */ new Set([DEVICE_ID_KEY, INTERNAL_KEY]);
2310
2503
  var MIRROR_MAX_AGE_SECONDS = 395 * 24 * 60 * 60;
2311
2504
  function local() {
2312
2505
  try {
@@ -2746,6 +2939,7 @@ function watchVitals(c) {
2746
2939
  }
2747
2940
 
2748
2941
  // src/analytics.ts
2942
+ var isEntry = (e) => e.kind === "identify" || e.kind === "group" || e.kind === "alias";
2749
2943
  var GROUP_TYPE = /^[a-z][a-z0-9_]{0,29}$/;
2750
2944
  var MAX_GROUP_TYPES = 5;
2751
2945
  function cleanGroupType(v) {
@@ -2805,11 +2999,46 @@ function withSuperProps(own, sup) {
2805
2999
  }
2806
3000
  }
2807
3001
  var SESSION_KEY = "traq_session";
3002
+ function cleanUserId(v) {
3003
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
3004
+ if (typeof v !== "string") return null;
3005
+ const t = v.trim();
3006
+ return t && t.length <= 256 ? t : null;
3007
+ }
3008
+ function exposureText(v) {
3009
+ const t = typeof v === "string" ? v.trim() : typeof v === "number" && Number.isFinite(v) || typeof v === "boolean" ? String(v) : "";
3010
+ return t && t.length <= 200 ? t : null;
3011
+ }
3012
+ function exposureProps(experiment, variant, props) {
3013
+ const e = exposureText(experiment);
3014
+ const v = exposureText(variant);
3015
+ if (!e || !v) return null;
3016
+ return { ...props && typeof props === "object" && !Array.isArray(props) ? props : {}, experiment: e, variant: v };
3017
+ }
3018
+ function takeBatch(queue, current, max) {
3019
+ let n = 0;
3020
+ let userId = current;
3021
+ let fixed = false;
3022
+ for (const e of queue) {
3023
+ if (n >= max) break;
3024
+ const entry = e.kind === "identify" || e.kind === "group" || e.kind === "alias";
3025
+ if (!entry) {
3026
+ const who = e.asUser !== void 0 ? e.asUser || void 0 : current;
3027
+ if (!fixed) {
3028
+ userId = who;
3029
+ fixed = true;
3030
+ } else if (who !== userId) break;
3031
+ }
3032
+ n++;
3033
+ }
3034
+ return { events: queue.splice(0, n), userId };
3035
+ }
2808
3036
  var SESSION_IDLE_MS = 30 * 60 * 1e3;
2809
3037
  var FLUSH_EVERY_MS = 5e3;
2810
3038
  var FLUSH_AT = 20;
2811
3039
  var MAX_QUEUE = 200;
2812
3040
  var MAX_ERRORS_PER_PAGE = 10;
3041
+ var LINK_SCANNER_ERROR = /^Object Not Found Matching Id:\d+, MethodName:\w+, ParamCount:\d+$/;
2813
3042
  var SCROLL_STEPS = [25, 50, 75, 100];
2814
3043
  var UTM = [
2815
3044
  ["utm_source", "utmSource"],
@@ -2886,6 +3115,8 @@ var AnalyticsTracker = class {
2886
3115
  this.scrollUrl = null;
2887
3116
  this.errorsThisPage = 0;
2888
3117
  this.stopped = false;
3118
+ /** This page is driven by a mail link scanner: every later batch says so (the server keeps it out of the figures). */
3119
+ this.scanner = false;
2889
3120
  this.rage = new RageClickDetector();
2890
3121
  this.vitals = null;
2891
3122
  this.vitalsUrl = null;
@@ -2946,6 +3177,26 @@ var AnalyticsTracker = class {
2946
3177
  if (this.queue.length > MAX_QUEUE) this.queue.shift();
2947
3178
  if (this.queue.length >= FLUSH_AT) this.flush(false);
2948
3179
  }
3180
+ /** Two ids, one person (`alias(previousId)`): one entry in the batch, under the current user. Not activity. */
3181
+ alias(userId, previousId) {
3182
+ if (this.stopped) return;
3183
+ this.queue.push({ kind: "alias", ts: Date.now(), userId, previousId });
3184
+ if (this.queue.length > MAX_QUEUE) this.queue.shift();
3185
+ if (this.queue.length >= FLUSH_AT) this.flush(false);
3186
+ }
3187
+ /**
3188
+ * Sign-out (`reset()`): what is queued keeps `userId`, the user it was captured
3189
+ * under, and the session ends — the next event opens a new one.
3190
+ */
3191
+ reset(userId) {
3192
+ if (userId) {
3193
+ for (const e of this.queue) if (!isEntry(e) && e.asUser === void 0) e.asUser = userId;
3194
+ }
3195
+ try {
3196
+ this.deps.store.removeSync(SESSION_KEY);
3197
+ } catch {
3198
+ }
3199
+ }
2949
3200
  /** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */
2950
3201
  pageview() {
2951
3202
  const url = bare2(location.href);
@@ -2961,6 +3212,7 @@ var AnalyticsTracker = class {
2961
3212
  }
2962
3213
  /** Sends what is queued. `leaving` = the page is going away: keepalive, so the request outlives it. */
2963
3214
  flush(leaving) {
3215
+ var _a, _b;
2964
3216
  if (!this.queue.length || this.stopped) return;
2965
3217
  if (this.deps.isForgotten()) {
2966
3218
  this.stop();
@@ -2968,13 +3220,17 @@ var AnalyticsTracker = class {
2968
3220
  }
2969
3221
  const anonymousId = this.deps.anonymousId();
2970
3222
  if (!anonymousId) return;
2971
- const events = this.queue.splice(0, 100);
3223
+ const taken = takeBatch(this.queue, this.deps.userId(), 100);
3224
+ const userId = taken.userId;
3225
+ const events = userId ? taken.events.map((e) => isEntry(e) || e.asUser !== void 0 ? e : { ...e, asUser: userId }) : taken.events;
2972
3226
  const body = JSON.stringify({
2973
3227
  sdkKey: this.deps.sdkKey,
2974
3228
  anonymousId,
2975
- userId: this.deps.userId(),
3229
+ userId,
2976
3230
  debug: this.deps.isDebug() || void 0,
2977
- events
3231
+ internal: ((_b = (_a = this.deps).isInternal) == null ? void 0 : _b.call(_a)) || void 0,
3232
+ scanner: this.scanner || void 0,
3233
+ events: events.map((e) => isEntry(e) ? e : { ...e, asUser: void 0 })
2978
3234
  });
2979
3235
  try {
2980
3236
  void fetch(`${this.deps.endpoint}/ingest/analytics`, {
@@ -3029,7 +3285,7 @@ var AnalyticsTracker = class {
3029
3285
  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 : {});
3030
3286
  const g = (_f = (_e = (_d = this.deps).groups) == null ? void 0 : _e.call(_d)) != null ? _f : {};
3031
3287
  const groups = Object.keys(g).length ? { ...g } : void 0;
3032
- 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 } : {} });
3288
+ this.queue.push({ ...e, ...props ? { props } : {}, ...groups ? { groups } : {}, id: newId(), ts: Date.now(), url: (_h = (_g = e.url) != null ? _g : bare2(location.href)) != null ? _h : "", title, sessionId: s.id, ...s.src ? { src: s.src } : {} });
3033
3289
  if (this.queue.length > MAX_QUEUE) this.queue.shift();
3034
3290
  if (this.queue.length >= FLUSH_AT) this.flush(false);
3035
3291
  }
@@ -3113,6 +3369,7 @@ var AnalyticsTracker = class {
3113
3369
  onError(e) {
3114
3370
  if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
3115
3371
  const message = (e.message || (e.error instanceof Error ? e.error.message : "") || "Script error").slice(0, 300);
3372
+ if (LINK_SCANNER_ERROR.test(message.replace(/^Uncaught (?:Error: )?/, ""))) this.scanner = true;
3116
3373
  this.errorsThisPage++;
3117
3374
  const stack = e.error instanceof Error && typeof e.error.stack === "string" ? e.error.stack.slice(0, 1500) : void 0;
3118
3375
  this.enqueue({ kind: "error", props: { message, ...stack ? { stack } : {}, ...e.filename ? { source: bare2(e.filename) } : {}, ...e.lineno ? { line: e.lineno } : {} } });
@@ -3121,6 +3378,7 @@ var AnalyticsTracker = class {
3121
3378
  if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
3122
3379
  const reason = e.reason;
3123
3380
  const message = (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection").slice(0, 300);
3381
+ if (LINK_SCANNER_ERROR.test(message)) this.scanner = true;
3124
3382
  this.errorsThisPage++;
3125
3383
  const stack = reason instanceof Error && typeof reason.stack === "string" ? reason.stack.slice(0, 1500) : void 0;
3126
3384
  this.enqueue({ kind: "error", props: { message, unhandledRejection: true, ...stack ? { stack } : {} } });
@@ -3143,6 +3401,15 @@ function randomId() {
3143
3401
  return null;
3144
3402
  }
3145
3403
  }
3404
+ function internalParam(href) {
3405
+ try {
3406
+ const v = new URL(href).searchParams.get("traqio_internal");
3407
+ if (v === "1" || v === "true") return true;
3408
+ if (v === "0" || v === "false") return false;
3409
+ } catch {
3410
+ }
3411
+ return null;
3412
+ }
3146
3413
  var TraqioWeb = class {
3147
3414
  constructor() {
3148
3415
  this.core = new import_core.Client();
@@ -3164,6 +3431,10 @@ var TraqioWeb = class {
3164
3431
  this.groups = {};
3165
3432
  /** Group entries made before `init()` — replayed once the tracker exists. */
3166
3433
  this.earlyGroups = [];
3434
+ /** `alias()` calls made before `init()`: [userId, previousId]. */
3435
+ this.earlyAliases = [];
3436
+ /** A `reset()` before `init()`: what earlier pages kept (super-properties, accounts) is dropped, not restored. */
3437
+ this.resetBeforeInit = false;
3167
3438
  }
3168
3439
  /**
3169
3440
  * Call once, as early as possible on every page (or once in a single-page app).
@@ -3187,11 +3458,17 @@ var TraqioWeb = class {
3187
3458
  this.trackIds.capture(location.href);
3188
3459
  this.sources = new SourceKeeper(this.store, keepMs, cookieDomain, cookies);
3189
3460
  this.sources.capture(location.href, document.referrer);
3461
+ const optOut = internalParam(location.href);
3462
+ if (optOut !== null) this.setInternal(optOut);
3190
3463
  if (!this.store.getSync(DEVICE_ID_KEY)) {
3191
3464
  const id = randomId();
3192
3465
  if (id) this.store.setSync(DEVICE_ID_KEY, id);
3193
3466
  }
3194
3467
  this.userId = (_c = opts.userId) != null ? _c : this.userId;
3468
+ if (this.resetBeforeInit) {
3469
+ this.store.removeSync(SUPER_PROPS_KEY);
3470
+ this.store.removeSync(GROUPS_KEY);
3471
+ }
3195
3472
  try {
3196
3473
  const raw = this.store.getSync(SUPER_PROPS_KEY);
3197
3474
  const early = Object.keys(this.superProps).length > 0;
@@ -3232,18 +3509,45 @@ var TraqioWeb = class {
3232
3509
  groups: () => this.groups,
3233
3510
  isDebug: () => this.core.isDebug,
3234
3511
  isForgotten: () => this.core.forgotten,
3512
+ isInternal: () => this.isInternal,
3235
3513
  options: opts.analytics === true ? {} : opts.analytics
3236
3514
  });
3237
3515
  this.analytics.start();
3238
3516
  for (const [id, set, once] of this.earlyIdentifies) this.analytics.identify(id, set, once);
3239
3517
  for (const [type, key, set, once] of this.earlyGroups) this.analytics.group(type, key, set, once);
3518
+ for (const [user, prev] of this.earlyAliases) this.analytics.alias(user, prev);
3240
3519
  for (const [name, props] of this.earlyCaptures) this.analytics.capture(name, props);
3241
3520
  }
3242
3521
  this.earlyCaptures = [];
3243
3522
  this.earlyIdentifies = [];
3244
3523
  this.earlyGroups = [];
3524
+ this.earlyAliases = [];
3245
3525
  this.ready = true;
3246
3526
  }
3527
+ /**
3528
+ * Mark this browser as the team's own (`true`) or as a visitor again (`false`) — what
3529
+ * opening the site with `?traqio_internal=1` / `=0` does. Its analytics events are
3530
+ * still sent, flagged: the console leaves them out of every figure by default and
3531
+ * shows them under « Internal traffic only ». Conversions (`track()`) are not
3532
+ * affected. Kept on the device, like the visitor id (and under the same consent).
3533
+ */
3534
+ setInternal(on) {
3535
+ if (!this.store) return;
3536
+ try {
3537
+ if (on) this.store.setSync(INTERNAL_KEY, "1");
3538
+ else this.store.removeSync(INTERNAL_KEY);
3539
+ } catch {
3540
+ }
3541
+ }
3542
+ /** True when this browser opted itself out as internal traffic — see `setInternal()`. */
3543
+ get isInternal() {
3544
+ var _a;
3545
+ try {
3546
+ return ((_a = this.store) == null ? void 0 : _a.getSync(INTERNAL_KEY)) === "1";
3547
+ } catch {
3548
+ return false;
3549
+ }
3550
+ }
3247
3551
  /** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
3248
3552
  get isDebug() {
3249
3553
  return this.core.isDebug;
@@ -3352,6 +3656,67 @@ var TraqioWeb = class {
3352
3656
  getGroups() {
3353
3657
  return { ...this.groups };
3354
3658
  }
3659
+ /**
3660
+ * Two ids, one person: the user known so far as `previousId` (a guest id, an id
3661
+ * from before sign-up) IS the current user (`setUserId` / `identify`). Their
3662
+ * analytics history and properties are merged under the current id — its own
3663
+ * properties win. From the browser only what THIS visitor sent under `previousId`
3664
+ * is merged; a backend (`@traqio/node`, secret key) merges everything.
3665
+ *
3666
+ * Traqio.identify("u_123");
3667
+ * Traqio.alias("guest_8f2c");
3668
+ *
3669
+ * Ignored without a current user id, or when `previousId` is the current one. Needs `analytics` at init.
3670
+ */
3671
+ alias(previousId) {
3672
+ const prev = cleanUserId(previousId);
3673
+ const user = this.userId;
3674
+ if (!user || !prev || prev === user) return;
3675
+ if (this.analytics) this.analytics.alias(user, prev);
3676
+ else if (!this.ready && this.earlyAliases.length < 10) this.earlyAliases.push([user, prev]);
3677
+ }
3678
+ /**
3679
+ * Sign-out: forget who the user was in this browser — the user id, the
3680
+ * super-properties, the accounts — and end the analytics session, so the next
3681
+ * person's visit starts clean. Events already queued keep the user they were
3682
+ * captured under. The visitor id is KEPT: it carries the visitor's attribution
3683
+ * (the click, the campaign) for the next sign-up.
3684
+ */
3685
+ reset() {
3686
+ var _a;
3687
+ const user = this.userId;
3688
+ (_a = this.analytics) == null ? void 0 : _a.reset(user);
3689
+ this.userId = void 0;
3690
+ this.core.reset();
3691
+ this.superProps = {};
3692
+ this.groups = {};
3693
+ this.earlyIdentifies = [];
3694
+ this.earlyGroups = [];
3695
+ this.earlyAliases = [];
3696
+ if (this.store) {
3697
+ this.persistSuperProps();
3698
+ this.persistGroups();
3699
+ } else this.resetBeforeInit = true;
3700
+ }
3701
+ /**
3702
+ * An experiment exposure: the visitor SAW `variant` of `experiment` — what the
3703
+ * console's experiment analysis reads (uplift, significance per variant). Your site
3704
+ * assigns the variant (its own flags, an edge split, a cookie); call this where the
3705
+ * visitor first meets it. Sends `$exposure { experiment, variant, ...props }`.
3706
+ *
3707
+ * Traqio.exposure("pricing_page", "annual_first");
3708
+ */
3709
+ exposure(experiment, variant, props) {
3710
+ const p = exposureProps(experiment, variant, props);
3711
+ if (!p) return;
3712
+ let fits = false;
3713
+ try {
3714
+ fits = JSON.stringify(p).length <= 4096;
3715
+ } catch {
3716
+ fits = false;
3717
+ }
3718
+ this.capture("$exposure", fits ? p : { experiment: p.experiment, variant: p.variant });
3719
+ }
3355
3720
  persistGroups() {
3356
3721
  try {
3357
3722
  if (!this.store) return;