@traqio/web 0.6.1 → 0.7.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.d.ts CHANGED
@@ -1,8 +1,10 @@
1
+ import { type TraqioError } from "@traqio/core";
1
2
  import { type WebSource } from "./source";
2
3
  import { type AnalyticsOptions, type Groups, type Traits } from "./analytics";
3
4
  export type { WebSource } from "./source";
4
5
  export type { AnalyticsOptions, Groups, Traits, TraitValue } from "./analytics";
5
6
  export type { WebVitalsOptions } from "./vitals";
7
+ export type { TraqioError } from "@traqio/core";
6
8
  export declare const DEFAULT_ENDPOINT = "https://api.traqio.app";
7
9
  export interface WebInitOptions {
8
10
  /** The site's WEB key (`tq_web_…`), from the console. Public by design: it is held to the site's origins. */
@@ -48,6 +50,12 @@ export interface WebInitOptions {
48
50
  * analytics events have their own route and table, apart from conversions.
49
51
  */
50
52
  analytics?: boolean | AnalyticsOptions;
53
+ /**
54
+ * Called once when the API refuses `sdkKey` (`code: "invalid_sdk_key"`, HTTP 401 / 403).
55
+ * Events stay queued and are retried with backoff, so fixing the key in the console
56
+ * delivers them. A `console.warn` is logged either way.
57
+ */
58
+ onError?: (error: TraqioError) => void;
51
59
  }
52
60
  /** What `track()` accepts beside the event name. */
53
61
  export interface WebTrackProps {
package/build/index.js CHANGED
@@ -820,7 +820,7 @@ var require_build = __commonJS({
820
820
  var adservices_1 = require_adservices();
821
821
  var deeplink_1 = require_deeplink();
822
822
  var adRevenue_1 = require_adRevenue();
823
- exports.SDK_VERSION = "0.10.0";
823
+ exports.SDK_VERSION = "0.12.0";
824
824
  var skan_2 = require_skan();
825
825
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
826
826
  return skan_2.Skan;
@@ -883,6 +883,9 @@ var require_build = __commonJS({
883
883
  var AD_ID_SENT_KEY = "traq_ad_id_sent";
884
884
  var AD_ID_SENT_DEBUG_KEY = "traq_ad_id_sent_debug";
885
885
  var AD_ID_PATH = "/ingest/advertising-id";
886
+ var AD_ID_CONSENT_KEY = "traq_ad_id_consent";
887
+ var AD_ID_ANSWER_SENT_KEY = "traq_ad_id_answer_sent";
888
+ var AD_ID_ANSWER_SENT_DEBUG_KEY = "traq_ad_id_answer_sent_debug";
886
889
  var REFERRER_KEY = "traq_referrer";
887
890
  var QUEUE_KEY = "traq_queue";
888
891
  var AD_QUEUE_KEY = "traq_ad_queue";
@@ -903,6 +906,7 @@ var require_build = __commonJS({
903
906
  var MAX_EARLY_ANALYTICS = 100;
904
907
  var MAX_BATCH = 20;
905
908
  var NON_RETRYABLE_STATUS = /* @__PURE__ */ new Set([400, 413, 422]);
909
+ var KEY_REJECTED_STATUS = /* @__PURE__ */ new Set([401, 403]);
906
910
  var MAX_QUEUE2 = 500;
907
911
  var MAX_AD_BATCH = 100;
908
912
  var MAX_AD_QUEUE = 1e3;
@@ -1017,6 +1021,16 @@ var require_build = __commonJS({
1017
1021
  return void 0;
1018
1022
  }
1019
1023
  }
1024
+ function isServerRender() {
1025
+ var _a, _b;
1026
+ if (typeof window !== "undefined")
1027
+ return false;
1028
+ try {
1029
+ return ((_b = (_a = (init_empty(), __toCommonJS(empty_exports))) == null ? void 0 : _a.Platform) == null ? void 0 : _b.OS) === "web";
1030
+ } catch {
1031
+ return false;
1032
+ }
1033
+ }
1020
1034
  var Client2 = class {
1021
1035
  constructor() {
1022
1036
  this.queue = [];
@@ -1029,6 +1043,7 @@ var require_build = __commonJS({
1029
1043
  this.flushing = false;
1030
1044
  this.flushTimer = null;
1031
1045
  this.retryMs = BASE_RETRY_MS;
1046
+ this.keyRejected = null;
1032
1047
  this.skan = new skan_1.Skan();
1033
1048
  this.erased = false;
1034
1049
  this.deepLinkListeners = /* @__PURE__ */ new Set();
@@ -1036,8 +1051,10 @@ var require_build = __commonJS({
1036
1051
  this.deferred = null;
1037
1052
  this.consent = null;
1038
1053
  this.att = null;
1054
+ this.adIdConsent = null;
1039
1055
  this.adIdSync = null;
1040
1056
  this.debug = false;
1057
+ this.contextReady = false;
1041
1058
  this.analyticsQueue = [];
1042
1059
  this.analyticsSession = null;
1043
1060
  this.earlyAnalytics = [];
@@ -1063,6 +1080,8 @@ var require_build = __commonJS({
1063
1080
  var _a, _b;
1064
1081
  if (this.started)
1065
1082
  return;
1083
+ if (isServerRender())
1084
+ return;
1066
1085
  this.started = true;
1067
1086
  this.opts = { collectContext: true, ...opts, userId: (_a = opts.userId) != null ? _a : this.earlyUserId, storage: (_b = opts.storage) != null ? _b : defaultStorage() };
1068
1087
  if (!this.opts.storage) {
@@ -1070,10 +1089,12 @@ var require_build = __commonJS({
1070
1089
  }
1071
1090
  this.debug = await detectDebug(opts);
1072
1091
  await this.restoreConsent(opts.consent);
1092
+ await this.restoreAdvertisingIdConsent();
1073
1093
  await this.restoreQueue();
1074
1094
  await this.restoreAdQueue();
1075
1095
  await this.restoreAnalytics();
1076
1096
  await this.buildContext();
1097
+ this.contextReady = true;
1077
1098
  if (await this.restoreErased()) {
1078
1099
  this.earlyAnalytics = [];
1079
1100
  return;
@@ -1611,6 +1632,37 @@ var require_build = __commonJS({
1611
1632
  await this.deferred;
1612
1633
  }
1613
1634
  }
1635
+ /**
1636
+ * The user's answer to YOUR advertising-id consent (GDPR / ePrivacy CMP, ATT prompt)
1637
+ * — HQ todo cmx4z20d. Call it once the user has answered, at any launch; persisted.
1638
+ *
1639
+ * `true` turns IDFA / GAID collection on from now: the SDK reads the id (never
1640
+ * prompting) and sends it once. With `waitForAdvertisingIdConsent` at init, the
1641
+ * install's Meta / TikTok postback was held for it and now leaves with it. On iOS,
1642
+ * call it AFTER your ATT prompt: the IDFA exists only once ATT is authorized (a yes
1643
+ * before that releases the install without it; the IDFA follows at the next
1644
+ * foreground for later conversions).
1645
+ *
1646
+ * `false` stops collection, tells the server to forget an id it kept from an
1647
+ * earlier yes, and lets a held install leave without one. First-party measurement
1648
+ * is unchanged either way.
1649
+ *
1650
+ * Traqio.setAdvertisingIdConsent(cmp.hasConsentFor("ads"));
1651
+ *
1652
+ * Overrides `collectAdvertisingId` once called. Android still needs Google's
1653
+ * `play-services-ads-identifier` and the `AD_ID` permission in the app.
1654
+ */
1655
+ async setAdvertisingIdConsent(granted) {
1656
+ var _a, _b;
1657
+ this.adIdConsent = granted ? "granted" : "denied";
1658
+ if (!this.started || !this.opts)
1659
+ return;
1660
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(AD_ID_CONSENT_KEY, this.adIdConsent).catch(() => void 0));
1661
+ if (this.isWeb || this.erased)
1662
+ return;
1663
+ await ((_b = this.adIdSync) == null ? void 0 : _b.catch(() => void 0));
1664
+ await this.syncAdvertisingId();
1665
+ }
1614
1666
  /** True once `forgetMe()` has been honoured — this install sends nothing any more. */
1615
1667
  get forgotten() {
1616
1668
  return this.erased;
@@ -1809,6 +1861,31 @@ var require_build = __commonJS({
1809
1861
  get adIdSentKey() {
1810
1862
  return this.debug ? AD_ID_SENT_DEBUG_KEY : AD_ID_SENT_KEY;
1811
1863
  }
1864
+ get adIdAnswerSentKey() {
1865
+ return this.debug ? AD_ID_ANSWER_SENT_DEBUG_KEY : AD_ID_ANSWER_SENT_KEY;
1866
+ }
1867
+ /**
1868
+ * May the advertising id be read right now? The user's stored answer first; then,
1869
+ * for an app that said it would ask, no until it has; then the init opt-in.
1870
+ */
1871
+ get collectsAdvertisingId() {
1872
+ if (this.adIdConsent)
1873
+ return this.adIdConsent === "granted";
1874
+ if (this.opts.waitForAdvertisingIdConsent)
1875
+ return false;
1876
+ return this.opts.collectAdvertisingId === true;
1877
+ }
1878
+ /** A `setAdvertisingIdConsent()` made before `init()` wins over the stored answer. */
1879
+ async restoreAdvertisingIdConsent() {
1880
+ var _a, _b;
1881
+ if (this.adIdConsent) {
1882
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(AD_ID_CONSENT_KEY, this.adIdConsent).catch(() => void 0));
1883
+ return;
1884
+ }
1885
+ const stored = await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(AD_ID_CONSENT_KEY).catch(() => null));
1886
+ if (stored === "granted" || stored === "denied")
1887
+ this.adIdConsent = stored;
1888
+ }
1812
1889
  /** Spread into every body: present only in debug mode, so a release build's payload is unchanged. */
1813
1890
  debugField() {
1814
1891
  return this.debug ? { debug: true } : {};
@@ -2152,7 +2229,7 @@ var require_build = __commonJS({
2152
2229
  /** Only with the host's opt-in; a zeroed or malformed id is never sent. */
2153
2230
  async readAdvertisingId() {
2154
2231
  var _a;
2155
- if (!this.opts.collectAdvertisingId || !((_a = this.opts.native) == null ? void 0 : _a.getAdvertisingId))
2232
+ if (!this.collectsAdvertisingId || !((_a = this.opts.native) == null ? void 0 : _a.getAdvertisingId))
2156
2233
  return void 0;
2157
2234
  try {
2158
2235
  return normalizeAdvertisingId(await this.opts.native.getAdvertisingId());
@@ -2189,6 +2266,8 @@ var require_build = __commonJS({
2189
2266
  ...metaInstallReferrers ? { metaInstallReferrers } : {},
2190
2267
  appUserId: this.opts.userId,
2191
2268
  advertisingId,
2269
+ // The app has not asked yet: the server holds the install postback for the id.
2270
+ ...this.opts.waitForAdvertisingIdConsent && !this.adIdConsent ? { advertisingIdPending: true } : {},
2192
2271
  context: this.context
2193
2272
  }
2194
2273
  });
@@ -2218,17 +2297,40 @@ var require_build = __commonJS({
2218
2297
  async postAdvertisingIdIfChanged() {
2219
2298
  var _a;
2220
2299
  const store = this.opts.storage;
2221
- if (this.isWeb || this.erased || !store || !this.opts.collectAdvertisingId)
2300
+ if (this.isWeb || this.erased || !store)
2222
2301
  return;
2223
2302
  try {
2224
2303
  if (!await store.getItem(this.installSentKey))
2225
2304
  return;
2305
+ const answer = this.adIdConsent;
2306
+ const deviceId = (_a = this.context.deviceId) != null ? _a : await this.getOrCreateDeviceId();
2307
+ const who = { deviceId, appUserId: this.opts.userId };
2308
+ if (answer === "denied") {
2309
+ if (await store.getItem(this.adIdAnswerSentKey) === "denied")
2310
+ return;
2311
+ if (await this.post({ ...who, advertisingIdConsent: "denied" }, AD_ID_PATH)) {
2312
+ await store.setItem(this.adIdAnswerSentKey, "denied");
2313
+ await store.setItem(this.adIdSentKey, "");
2314
+ }
2315
+ return;
2316
+ }
2317
+ if (!this.collectsAdvertisingId)
2318
+ return;
2319
+ const consent = answer ? { advertisingIdConsent: answer } : {};
2226
2320
  const advertisingId = await this.readAdvertisingId();
2227
- if (!advertisingId || await store.getItem(this.adIdSentKey) === advertisingId)
2321
+ if (advertisingId) {
2322
+ if (await store.getItem(this.adIdSentKey) === advertisingId)
2323
+ return;
2324
+ if (await this.post({ ...who, advertisingId, ...consent }, AD_ID_PATH)) {
2325
+ await store.setItem(this.adIdSentKey, advertisingId);
2326
+ if (answer)
2327
+ await store.setItem(this.adIdAnswerSentKey, answer);
2328
+ }
2228
2329
  return;
2229
- const deviceId = (_a = this.context.deviceId) != null ? _a : await this.getOrCreateDeviceId();
2230
- if (await this.post({ deviceId, appUserId: this.opts.userId, advertisingId }, AD_ID_PATH)) {
2231
- await store.setItem(this.adIdSentKey, advertisingId);
2330
+ }
2331
+ if (answer === "granted" && await store.getItem(this.adIdAnswerSentKey) !== "granted") {
2332
+ if (await this.post({ ...who, advertisingIdConsent: "granted" }, AD_ID_PATH))
2333
+ await store.setItem(this.adIdAnswerSentKey, "granted");
2232
2334
  }
2233
2335
  } catch {
2234
2336
  }
@@ -2243,7 +2345,7 @@ var require_build = __commonJS({
2243
2345
  }
2244
2346
  async drain() {
2245
2347
  var _a, _b;
2246
- if (this.erased)
2348
+ if (this.erased || !this.contextReady)
2247
2349
  return;
2248
2350
  if (this.flushing || !this.queue.length && !this.adQueue.length && !this.analyticsQueue.length)
2249
2351
  return;
@@ -2325,11 +2427,33 @@ var require_build = __commonJS({
2325
2427
  body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...this.debugField() }),
2326
2428
  ...this.keepalive()
2327
2429
  });
2430
+ this.noteStatus(res.status, res.ok);
2328
2431
  return res.ok ? await res.json() : null;
2329
2432
  } catch {
2330
2433
  return null;
2331
2434
  }
2332
2435
  }
2436
+ /**
2437
+ * A refused key is the one failure the developer must hear about: the batch is kept
2438
+ * and replayed (a key fixed in the console makes it succeed), so without this the
2439
+ * SDK would retry in silence forever. Reported once per status; a success re-arms it.
2440
+ */
2441
+ noteStatus(status, ok) {
2442
+ var _a, _b;
2443
+ if (ok) {
2444
+ this.keyRejected = null;
2445
+ return;
2446
+ }
2447
+ if (!KEY_REJECTED_STATUS.has(status) || this.keyRejected === status)
2448
+ return;
2449
+ this.keyRejected = status;
2450
+ const message = `[traqio] the server rejected the sdkKey (HTTP ${status}) \u2014 check the key in the console. Events are kept and retried with backoff until it is accepted.`;
2451
+ console.warn(message);
2452
+ try {
2453
+ (_b = (_a = this.opts).onError) == null ? void 0 : _b.call(_a, { code: "invalid_sdk_key", status, message });
2454
+ } catch {
2455
+ }
2456
+ }
2333
2457
  /**
2334
2458
  * The init option wins over what is stored (it is the app's current answer); a
2335
2459
  * `setConsent()` made before `init()` survives too — it is only kept in memory
@@ -2374,7 +2498,8 @@ var require_build = __commonJS({
2374
2498
  * `post`, with the failure split in two: `refused` is a status the same body will
2375
2499
  * get again on every retry (400 malformed, 413 too large, 422 unprocessable);
2376
2500
  * `retry` is everything else — network down, 5xx, 429, and 401/403 too, since a
2377
- * key fixed in the console makes the same queued batch succeed.
2501
+ * key fixed in the console makes the same queued batch succeed (those two are
2502
+ * reported once through `noteStatus`: console.warn + `onError`).
2378
2503
  */
2379
2504
  async send(body, path = "/ingest") {
2380
2505
  const consent = this.consent && (path === "/ingest" || path === "/ingest/session" || path === AD_ID_PATH) ? { consent: this.consent } : {};
@@ -2392,6 +2517,7 @@ var require_build = __commonJS({
2392
2517
  }),
2393
2518
  ...this.keepalive()
2394
2519
  });
2520
+ this.noteStatus(res.status, res.ok);
2395
2521
  if (res.ok)
2396
2522
  return "ok";
2397
2523
  return NON_RETRYABLE_STATUS.has(res.status) ? "refused" : "retry";
@@ -3479,6 +3605,7 @@ var TraqioWeb = class {
3479
3605
  userId: this.userId,
3480
3606
  consent,
3481
3607
  debug: opts.debug,
3608
+ onError: opts.onError,
3482
3609
  lifecycle: ({ background, foreground }) => {
3483
3610
  document.addEventListener("visibilitychange", () => document.visibilityState === "hidden" ? background() : foreground());
3484
3611
  window.addEventListener("pagehide", background);