@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/README.md CHANGED
@@ -13,7 +13,7 @@ referring site, kept the same way in a `traq_src` cookie — so a sign-up from a
13
13
  Instagram bio or a newsletter is still reported under its source and campaign.
14
14
 
15
15
  It also records web events and visits, with consent handling and in-page erasure. No
16
- fingerprinting, no third-party cookie, no advertising id. ~7 KB gzipped, no dependency.
16
+ fingerprinting, no third-party cookie, no advertising id. ~20 KB gzipped, no dependency.
17
17
 
18
18
  ## Install
19
19
 
@@ -25,7 +25,7 @@ Or without a build step, with a `<script>` tag (it initialises itself from the
25
25
  `data-` attributes and exposes `window.Traqio`):
26
26
 
27
27
  ```html
28
- <script src="https://cdn.jsdelivr.net/npm/@traqio/web@0.1/build/traqio.min.js"
28
+ <script src="https://cdn.jsdelivr.net/npm/@traqio/web@0/build/traqio.min.js"
29
29
  data-sdk-key="YOUR_WEB_KEY" async></script>
30
30
  ```
31
31
 
@@ -101,6 +101,11 @@ because a browser and a signed-in user are not tied together yet.
101
101
  Events are batched, retried, kept across page loads, and flushed when the tab is
102
102
  hidden or the page is left.
103
103
 
104
+ **A wrong or revoked key is not silent.** When the API answers 401 / 403, the SDK logs
105
+ one `console.warn` and calls `onError({ code: "invalid_sdk_key", status, message })`
106
+ once — not on every retry. The events are kept and retried with backoff (up to 5 min),
107
+ so fixing the key in the console delivers them.
108
+
104
109
  ## Product analytics
105
110
 
106
111
  Page views, traffic sources, clicks, scroll depth, front-end errors, Core Web Vitals and your own
@@ -223,6 +228,7 @@ networks.
223
228
  | `cookies` | `true` | `false` = localStorage only, no sharing across subdomains |
224
229
  | `debug` | detected | Debug traffic, kept out of every report (see below) |
225
230
  | `analytics` | `false` | Product analytics: `true`, or `{ pageviews, clicks, rageClicks, scroll, errors, webVitals }` (`webVitals: { sampleRate }`, default 0.5) |
231
+ | `onError` | — | Called once if the API refuses `sdkKey` (401 / 403) — see below |
226
232
 
227
233
  **Debug traffic.** Omitted, `debug` is on for a page served from `localhost`, `127.0.0.1`, `*.localhost`, `*.local` or `file:`, and off everywhere else; `true` forces it (a staging site), `false` counts a local page. `traqio.isDebug` tells which mode is on. Debug traffic shows in the console's **Live events › Debug** view, but it is never counted in a report, attributed, sent to an ad network or a webhook, or billed.
228
234
 
package/build/index.cjs CHANGED
@@ -825,7 +825,7 @@ var require_build = __commonJS({
825
825
  var adservices_1 = require_adservices();
826
826
  var deeplink_1 = require_deeplink();
827
827
  var adRevenue_1 = require_adRevenue();
828
- exports.SDK_VERSION = "0.10.0";
828
+ exports.SDK_VERSION = "0.12.0";
829
829
  var skan_2 = require_skan();
830
830
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
831
831
  return skan_2.Skan;
@@ -888,6 +888,9 @@ var require_build = __commonJS({
888
888
  var AD_ID_SENT_KEY = "traq_ad_id_sent";
889
889
  var AD_ID_SENT_DEBUG_KEY = "traq_ad_id_sent_debug";
890
890
  var AD_ID_PATH = "/ingest/advertising-id";
891
+ var AD_ID_CONSENT_KEY = "traq_ad_id_consent";
892
+ var AD_ID_ANSWER_SENT_KEY = "traq_ad_id_answer_sent";
893
+ var AD_ID_ANSWER_SENT_DEBUG_KEY = "traq_ad_id_answer_sent_debug";
891
894
  var REFERRER_KEY = "traq_referrer";
892
895
  var QUEUE_KEY = "traq_queue";
893
896
  var AD_QUEUE_KEY = "traq_ad_queue";
@@ -908,6 +911,7 @@ var require_build = __commonJS({
908
911
  var MAX_EARLY_ANALYTICS = 100;
909
912
  var MAX_BATCH = 20;
910
913
  var NON_RETRYABLE_STATUS = /* @__PURE__ */ new Set([400, 413, 422]);
914
+ var KEY_REJECTED_STATUS = /* @__PURE__ */ new Set([401, 403]);
911
915
  var MAX_QUEUE2 = 500;
912
916
  var MAX_AD_BATCH = 100;
913
917
  var MAX_AD_QUEUE = 1e3;
@@ -1022,6 +1026,16 @@ var require_build = __commonJS({
1022
1026
  return void 0;
1023
1027
  }
1024
1028
  }
1029
+ function isServerRender() {
1030
+ var _a, _b;
1031
+ if (typeof window !== "undefined")
1032
+ return false;
1033
+ try {
1034
+ return ((_b = (_a = (init_empty(), __toCommonJS(empty_exports))) == null ? void 0 : _a.Platform) == null ? void 0 : _b.OS) === "web";
1035
+ } catch {
1036
+ return false;
1037
+ }
1038
+ }
1025
1039
  var Client2 = class {
1026
1040
  constructor() {
1027
1041
  this.queue = [];
@@ -1034,6 +1048,7 @@ var require_build = __commonJS({
1034
1048
  this.flushing = false;
1035
1049
  this.flushTimer = null;
1036
1050
  this.retryMs = BASE_RETRY_MS;
1051
+ this.keyRejected = null;
1037
1052
  this.skan = new skan_1.Skan();
1038
1053
  this.erased = false;
1039
1054
  this.deepLinkListeners = /* @__PURE__ */ new Set();
@@ -1041,8 +1056,10 @@ var require_build = __commonJS({
1041
1056
  this.deferred = null;
1042
1057
  this.consent = null;
1043
1058
  this.att = null;
1059
+ this.adIdConsent = null;
1044
1060
  this.adIdSync = null;
1045
1061
  this.debug = false;
1062
+ this.contextReady = false;
1046
1063
  this.analyticsQueue = [];
1047
1064
  this.analyticsSession = null;
1048
1065
  this.earlyAnalytics = [];
@@ -1068,6 +1085,8 @@ var require_build = __commonJS({
1068
1085
  var _a, _b;
1069
1086
  if (this.started)
1070
1087
  return;
1088
+ if (isServerRender())
1089
+ return;
1071
1090
  this.started = true;
1072
1091
  this.opts = { collectContext: true, ...opts, userId: (_a = opts.userId) != null ? _a : this.earlyUserId, storage: (_b = opts.storage) != null ? _b : defaultStorage() };
1073
1092
  if (!this.opts.storage) {
@@ -1075,10 +1094,12 @@ var require_build = __commonJS({
1075
1094
  }
1076
1095
  this.debug = await detectDebug(opts);
1077
1096
  await this.restoreConsent(opts.consent);
1097
+ await this.restoreAdvertisingIdConsent();
1078
1098
  await this.restoreQueue();
1079
1099
  await this.restoreAdQueue();
1080
1100
  await this.restoreAnalytics();
1081
1101
  await this.buildContext();
1102
+ this.contextReady = true;
1082
1103
  if (await this.restoreErased()) {
1083
1104
  this.earlyAnalytics = [];
1084
1105
  return;
@@ -1616,6 +1637,37 @@ var require_build = __commonJS({
1616
1637
  await this.deferred;
1617
1638
  }
1618
1639
  }
1640
+ /**
1641
+ * The user's answer to YOUR advertising-id consent (GDPR / ePrivacy CMP, ATT prompt)
1642
+ * — HQ todo cmx4z20d. Call it once the user has answered, at any launch; persisted.
1643
+ *
1644
+ * `true` turns IDFA / GAID collection on from now: the SDK reads the id (never
1645
+ * prompting) and sends it once. With `waitForAdvertisingIdConsent` at init, the
1646
+ * install's Meta / TikTok postback was held for it and now leaves with it. On iOS,
1647
+ * call it AFTER your ATT prompt: the IDFA exists only once ATT is authorized (a yes
1648
+ * before that releases the install without it; the IDFA follows at the next
1649
+ * foreground for later conversions).
1650
+ *
1651
+ * `false` stops collection, tells the server to forget an id it kept from an
1652
+ * earlier yes, and lets a held install leave without one. First-party measurement
1653
+ * is unchanged either way.
1654
+ *
1655
+ * Traqio.setAdvertisingIdConsent(cmp.hasConsentFor("ads"));
1656
+ *
1657
+ * Overrides `collectAdvertisingId` once called. Android still needs Google's
1658
+ * `play-services-ads-identifier` and the `AD_ID` permission in the app.
1659
+ */
1660
+ async setAdvertisingIdConsent(granted) {
1661
+ var _a, _b;
1662
+ this.adIdConsent = granted ? "granted" : "denied";
1663
+ if (!this.started || !this.opts)
1664
+ return;
1665
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(AD_ID_CONSENT_KEY, this.adIdConsent).catch(() => void 0));
1666
+ if (this.isWeb || this.erased)
1667
+ return;
1668
+ await ((_b = this.adIdSync) == null ? void 0 : _b.catch(() => void 0));
1669
+ await this.syncAdvertisingId();
1670
+ }
1619
1671
  /** True once `forgetMe()` has been honoured — this install sends nothing any more. */
1620
1672
  get forgotten() {
1621
1673
  return this.erased;
@@ -1814,6 +1866,31 @@ var require_build = __commonJS({
1814
1866
  get adIdSentKey() {
1815
1867
  return this.debug ? AD_ID_SENT_DEBUG_KEY : AD_ID_SENT_KEY;
1816
1868
  }
1869
+ get adIdAnswerSentKey() {
1870
+ return this.debug ? AD_ID_ANSWER_SENT_DEBUG_KEY : AD_ID_ANSWER_SENT_KEY;
1871
+ }
1872
+ /**
1873
+ * May the advertising id be read right now? The user's stored answer first; then,
1874
+ * for an app that said it would ask, no until it has; then the init opt-in.
1875
+ */
1876
+ get collectsAdvertisingId() {
1877
+ if (this.adIdConsent)
1878
+ return this.adIdConsent === "granted";
1879
+ if (this.opts.waitForAdvertisingIdConsent)
1880
+ return false;
1881
+ return this.opts.collectAdvertisingId === true;
1882
+ }
1883
+ /** A `setAdvertisingIdConsent()` made before `init()` wins over the stored answer. */
1884
+ async restoreAdvertisingIdConsent() {
1885
+ var _a, _b;
1886
+ if (this.adIdConsent) {
1887
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(AD_ID_CONSENT_KEY, this.adIdConsent).catch(() => void 0));
1888
+ return;
1889
+ }
1890
+ const stored = await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(AD_ID_CONSENT_KEY).catch(() => null));
1891
+ if (stored === "granted" || stored === "denied")
1892
+ this.adIdConsent = stored;
1893
+ }
1817
1894
  /** Spread into every body: present only in debug mode, so a release build's payload is unchanged. */
1818
1895
  debugField() {
1819
1896
  return this.debug ? { debug: true } : {};
@@ -2157,7 +2234,7 @@ var require_build = __commonJS({
2157
2234
  /** Only with the host's opt-in; a zeroed or malformed id is never sent. */
2158
2235
  async readAdvertisingId() {
2159
2236
  var _a;
2160
- if (!this.opts.collectAdvertisingId || !((_a = this.opts.native) == null ? void 0 : _a.getAdvertisingId))
2237
+ if (!this.collectsAdvertisingId || !((_a = this.opts.native) == null ? void 0 : _a.getAdvertisingId))
2161
2238
  return void 0;
2162
2239
  try {
2163
2240
  return normalizeAdvertisingId(await this.opts.native.getAdvertisingId());
@@ -2194,6 +2271,8 @@ var require_build = __commonJS({
2194
2271
  ...metaInstallReferrers ? { metaInstallReferrers } : {},
2195
2272
  appUserId: this.opts.userId,
2196
2273
  advertisingId,
2274
+ // The app has not asked yet: the server holds the install postback for the id.
2275
+ ...this.opts.waitForAdvertisingIdConsent && !this.adIdConsent ? { advertisingIdPending: true } : {},
2197
2276
  context: this.context
2198
2277
  }
2199
2278
  });
@@ -2223,17 +2302,40 @@ var require_build = __commonJS({
2223
2302
  async postAdvertisingIdIfChanged() {
2224
2303
  var _a;
2225
2304
  const store = this.opts.storage;
2226
- if (this.isWeb || this.erased || !store || !this.opts.collectAdvertisingId)
2305
+ if (this.isWeb || this.erased || !store)
2227
2306
  return;
2228
2307
  try {
2229
2308
  if (!await store.getItem(this.installSentKey))
2230
2309
  return;
2310
+ const answer = this.adIdConsent;
2311
+ const deviceId = (_a = this.context.deviceId) != null ? _a : await this.getOrCreateDeviceId();
2312
+ const who = { deviceId, appUserId: this.opts.userId };
2313
+ if (answer === "denied") {
2314
+ if (await store.getItem(this.adIdAnswerSentKey) === "denied")
2315
+ return;
2316
+ if (await this.post({ ...who, advertisingIdConsent: "denied" }, AD_ID_PATH)) {
2317
+ await store.setItem(this.adIdAnswerSentKey, "denied");
2318
+ await store.setItem(this.adIdSentKey, "");
2319
+ }
2320
+ return;
2321
+ }
2322
+ if (!this.collectsAdvertisingId)
2323
+ return;
2324
+ const consent = answer ? { advertisingIdConsent: answer } : {};
2231
2325
  const advertisingId = await this.readAdvertisingId();
2232
- if (!advertisingId || await store.getItem(this.adIdSentKey) === advertisingId)
2326
+ if (advertisingId) {
2327
+ if (await store.getItem(this.adIdSentKey) === advertisingId)
2328
+ return;
2329
+ if (await this.post({ ...who, advertisingId, ...consent }, AD_ID_PATH)) {
2330
+ await store.setItem(this.adIdSentKey, advertisingId);
2331
+ if (answer)
2332
+ await store.setItem(this.adIdAnswerSentKey, answer);
2333
+ }
2233
2334
  return;
2234
- const deviceId = (_a = this.context.deviceId) != null ? _a : await this.getOrCreateDeviceId();
2235
- if (await this.post({ deviceId, appUserId: this.opts.userId, advertisingId }, AD_ID_PATH)) {
2236
- await store.setItem(this.adIdSentKey, advertisingId);
2335
+ }
2336
+ if (answer === "granted" && await store.getItem(this.adIdAnswerSentKey) !== "granted") {
2337
+ if (await this.post({ ...who, advertisingIdConsent: "granted" }, AD_ID_PATH))
2338
+ await store.setItem(this.adIdAnswerSentKey, "granted");
2237
2339
  }
2238
2340
  } catch {
2239
2341
  }
@@ -2248,7 +2350,7 @@ var require_build = __commonJS({
2248
2350
  }
2249
2351
  async drain() {
2250
2352
  var _a, _b;
2251
- if (this.erased)
2353
+ if (this.erased || !this.contextReady)
2252
2354
  return;
2253
2355
  if (this.flushing || !this.queue.length && !this.adQueue.length && !this.analyticsQueue.length)
2254
2356
  return;
@@ -2330,11 +2432,33 @@ var require_build = __commonJS({
2330
2432
  body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...this.debugField() }),
2331
2433
  ...this.keepalive()
2332
2434
  });
2435
+ this.noteStatus(res.status, res.ok);
2333
2436
  return res.ok ? await res.json() : null;
2334
2437
  } catch {
2335
2438
  return null;
2336
2439
  }
2337
2440
  }
2441
+ /**
2442
+ * A refused key is the one failure the developer must hear about: the batch is kept
2443
+ * and replayed (a key fixed in the console makes it succeed), so without this the
2444
+ * SDK would retry in silence forever. Reported once per status; a success re-arms it.
2445
+ */
2446
+ noteStatus(status, ok) {
2447
+ var _a, _b;
2448
+ if (ok) {
2449
+ this.keyRejected = null;
2450
+ return;
2451
+ }
2452
+ if (!KEY_REJECTED_STATUS.has(status) || this.keyRejected === status)
2453
+ return;
2454
+ this.keyRejected = status;
2455
+ 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.`;
2456
+ console.warn(message);
2457
+ try {
2458
+ (_b = (_a = this.opts).onError) == null ? void 0 : _b.call(_a, { code: "invalid_sdk_key", status, message });
2459
+ } catch {
2460
+ }
2461
+ }
2338
2462
  /**
2339
2463
  * The init option wins over what is stored (it is the app's current answer); a
2340
2464
  * `setConsent()` made before `init()` survives too — it is only kept in memory
@@ -2379,7 +2503,8 @@ var require_build = __commonJS({
2379
2503
  * `post`, with the failure split in two: `refused` is a status the same body will
2380
2504
  * get again on every retry (400 malformed, 413 too large, 422 unprocessable);
2381
2505
  * `retry` is everything else — network down, 5xx, 429, and 401/403 too, since a
2382
- * key fixed in the console makes the same queued batch succeed.
2506
+ * key fixed in the console makes the same queued batch succeed (those two are
2507
+ * reported once through `noteStatus`: console.warn + `onError`).
2383
2508
  */
2384
2509
  async send(body, path = "/ingest") {
2385
2510
  const consent = this.consent && (path === "/ingest" || path === "/ingest/session" || path === AD_ID_PATH) ? { consent: this.consent } : {};
@@ -2397,6 +2522,7 @@ var require_build = __commonJS({
2397
2522
  }),
2398
2523
  ...this.keepalive()
2399
2524
  });
2525
+ this.noteStatus(res.status, res.ok);
2400
2526
  if (res.ok)
2401
2527
  return "ok";
2402
2528
  return NON_RETRYABLE_STATUS.has(res.status) ? "refused" : "retry";
@@ -3492,6 +3618,7 @@ var TraqioWeb = class {
3492
3618
  userId: this.userId,
3493
3619
  consent,
3494
3620
  debug: opts.debug,
3621
+ onError: opts.onError,
3495
3622
  lifecycle: ({ background, foreground }) => {
3496
3623
  document.addEventListener("visibilitychange", () => document.visibilityState === "hidden" ? background() : foreground());
3497
3624
  window.addEventListener("pagehide", background);