@traqio/web 0.1.2 → 0.2.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
@@ -25,6 +25,14 @@ export interface WebInitOptions {
25
25
  trackIdDays?: number;
26
26
  /** `false` = never write a cookie, localStorage only (no sharing across subdomains). Default `true`. */
27
27
  cookies?: boolean;
28
+ /**
29
+ * Debug mode. Omitted = on when the page is served from your machine (`localhost`,
30
+ * `127.0.0.1`, `*.localhost`, `*.local`, `file:`), off everywhere else. Debug
31
+ * traffic shows in the console's Live events › Debug view and is never counted,
32
+ * attributed, sent to an ad network or a webhook, or billed. `true` for a staging
33
+ * site, `false` to count a local page.
34
+ */
35
+ debug?: boolean;
28
36
  }
29
37
  /** What `track()` accepts beside the event name. */
30
38
  export interface WebTrackProps {
@@ -51,6 +59,8 @@ export declare class TraqioWeb {
51
59
  * does nothing there.
52
60
  */
53
61
  init(opts: WebInitOptions): Promise<void>;
62
+ /** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
63
+ get isDebug(): boolean;
54
64
  /** Record an event — `signup`, `purchase`, `add_to_cart`… Batched, retried, kept across page loads. */
55
65
  track(name: string, props?: WebTrackProps): void;
56
66
  /** Set the user id once known (after sign-in). */
package/build/index.js CHANGED
@@ -264,7 +264,8 @@ var require_adservices = __commonJS({
264
264
  sdkKey: opts.sdkKey,
265
265
  token: token.trim(),
266
266
  deviceId: opts.deviceId,
267
- appUserId: opts.userId
267
+ appUserId: opts.userId,
268
+ ...opts.debug ? { debug: true } : {}
268
269
  })
269
270
  });
270
271
  if (!res.ok)
@@ -299,17 +300,51 @@ var require_deeplink = __commonJS({
299
300
  "use strict";
300
301
  Object.defineProperty(exports, "__esModule", { value: true });
301
302
  exports.isTrackingUrl = isTrackingUrl;
303
+ exports.isOpenUrl = isOpenUrl;
302
304
  exports.toDeepLink = toDeepLink;
305
+ exports.upgradeStoredDeepLink = upgradeStoredDeepLink;
303
306
  var TRACKING_PATH = /^\/c\/[A-Za-z0-9_-]{1,50}\/?$/;
304
- function isTrackingUrl(url) {
307
+ var OPEN_PATH = /^\/o\/[0-9a-fA-F-]{36}\/?$/;
308
+ function pathOf(url) {
305
309
  var _a;
306
310
  const m = /^https?:\/\/[^/?#]+(\/[^?#]*)?/i.exec(url);
307
- return Boolean(m && TRACKING_PATH.test((_a = m[1]) != null ? _a : ""));
311
+ return m ? (_a = m[1]) != null ? _a : "" : null;
312
+ }
313
+ function isTrackingUrl(url) {
314
+ const path = pathOf(url);
315
+ return path !== null && (TRACKING_PATH.test(path) || OPEN_PATH.test(path));
316
+ }
317
+ function isOpenUrl(url) {
318
+ const path = pathOf(url);
319
+ return path !== null && OPEN_PATH.test(path);
308
320
  }
309
321
  function toDeepLink(answer, deferred, url) {
322
+ var _a, _b, _c;
310
323
  if (!(answer == null ? void 0 : answer.matched) || !answer.via)
311
324
  return null;
312
- return { deepLink: answer.deepLink, code: answer.code, deferred, via: answer.via, ...url ? { url } : {} };
325
+ const matchType = (_a = answer.matchType) != null ? _a : answer.via === "ip_match" ? "probabilistic" : answer.via;
326
+ const payload = (_b = answer.payload) != null ? _b : { deepLink: answer.deepLink, value: null, params: {} };
327
+ return {
328
+ payload,
329
+ matchType,
330
+ confidence: matchType === "probabilistic" ? (_c = answer.confidence) != null ? _c : "low" : null,
331
+ deferred,
332
+ code: answer.code,
333
+ deepLink: payload.deepLink,
334
+ via: answer.via,
335
+ ...url ? { url } : {}
336
+ };
337
+ }
338
+ function upgradeStoredDeepLink(stored) {
339
+ var _a, _b, _c;
340
+ if (!stored || typeof stored !== "object")
341
+ return null;
342
+ const link = stored;
343
+ if (link.payload && link.matchType)
344
+ return link;
345
+ if (!link.via)
346
+ return null;
347
+ return toDeepLink({ matched: true, via: link.via, code: (_a = link.code) != null ? _a : null, deepLink: (_b = link.deepLink) != null ? _b : null }, (_c = link.deferred) != null ? _c : true, link.url);
313
348
  }
314
349
  }
315
350
  });
@@ -327,13 +362,15 @@ var require_build = __commonJS({
327
362
  "../sdk-core/build/index.js"(exports) {
328
363
  "use strict";
329
364
  Object.defineProperty(exports, "__esModule", { value: true });
330
- exports.Traqio = exports.Client = exports.isTrackingUrl = exports.reportAdServicesToken = exports.Skan = exports.SDK_VERSION = void 0;
365
+ exports.Traqio = exports.Client = exports.isTrackingUrl = exports.isOpenUrl = exports.reportAdServicesToken = exports.Skan = exports.SDK_VERSION = void 0;
331
366
  exports.normalizeAdvertisingId = normalizeAdvertisingId;
332
367
  exports.fromMaxAd = fromMaxAd;
368
+ exports.detectDebug = detectDebug;
369
+ exports.isLocalPage = isLocalPage;
333
370
  var skan_1 = require_skan();
334
371
  var adservices_1 = require_adservices();
335
372
  var deeplink_1 = require_deeplink();
336
- exports.SDK_VERSION = "0.1.2";
373
+ exports.SDK_VERSION = "0.3.0";
337
374
  var skan_2 = require_skan();
338
375
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
339
376
  return skan_2.Skan;
@@ -343,10 +380,14 @@ var require_build = __commonJS({
343
380
  return adservices_2.reportAdServicesToken;
344
381
  } });
345
382
  var deeplink_2 = require_deeplink();
383
+ Object.defineProperty(exports, "isOpenUrl", { enumerable: true, get: function() {
384
+ return deeplink_2.isOpenUrl;
385
+ } });
346
386
  Object.defineProperty(exports, "isTrackingUrl", { enumerable: true, get: function() {
347
387
  return deeplink_2.isTrackingUrl;
348
388
  } });
349
389
  var INSTALL_SENT_KEY = "traq_install_sent";
390
+ var INSTALL_SENT_DEBUG_KEY = "traq_install_sent_debug";
350
391
  var INSTALL_ATTEMPTS_KEY = "traq_install_attempts";
351
392
  var REFERRER_KEY = "traq_referrer";
352
393
  var QUEUE_KEY = "traq_queue";
@@ -355,6 +396,8 @@ var require_build = __commonJS({
355
396
  var LAST_SESSION_KEY = "traq_last_session";
356
397
  var ERASED_KEY = "traq_erased";
357
398
  var DEFERRED_KEY = "traq_deferred_link";
399
+ var DEFERRED_RETRY_KEY = "traq_deferred_consent_retry_until";
400
+ var DEFERRED_RETRY_WINDOW_MS = 60 * 6e4;
358
401
  var CONSENT_KEY = "traq_consent";
359
402
  var MAX_BATCH = 20;
360
403
  var NON_RETRYABLE_STATUS = /* @__PURE__ */ new Set([400, 413, 422]);
@@ -453,6 +496,11 @@ var require_build = __commonJS({
453
496
  this.undelivered = [];
454
497
  this.deferred = null;
455
498
  this.consent = null;
499
+ this.debug = false;
500
+ }
501
+ /** Whether this run is in debug mode — see `InitOptions.debug`. Settled by `init()`. */
502
+ get isDebug() {
503
+ return this.debug;
456
504
  }
457
505
  async init(opts) {
458
506
  var _a;
@@ -463,6 +511,7 @@ var require_build = __commonJS({
463
511
  if (!this.opts.storage) {
464
512
  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.");
465
513
  }
514
+ this.debug = await detectDebug(opts);
466
515
  await this.restoreConsent(opts.consent);
467
516
  await this.restoreQueue();
468
517
  await this.restoreAdQueue();
@@ -470,10 +519,10 @@ var require_build = __commonJS({
470
519
  if (await this.restoreErased())
471
520
  return;
472
521
  if (!this.isWeb) {
473
- const freshInstall = Boolean(this.opts.storage) && !await this.opts.storage.getItem(INSTALL_SENT_KEY).catch(() => "1");
522
+ const freshInstall = Boolean(this.opts.storage) && !await this.opts.storage.getItem(this.installSentKey).catch(() => "1");
474
523
  await this.sendInstallOnce();
475
524
  if (this.opts.deepLinking !== false) {
476
- this.deferred = this.resolveDeferredOnce(freshInstall);
525
+ this.deferred = this.resolveDeferredOnce(freshInstall).then((link) => link != null ? link : this.retryDeferredWithConsent());
477
526
  this.wireDeepLinks();
478
527
  }
479
528
  }
@@ -591,20 +640,47 @@ var require_build = __commonJS({
591
640
  if (!this.started || this.erased || this.opts.deepLinking === false || !(0, deeplink_1.isTrackingUrl)(url))
592
641
  return null;
593
642
  const answer = await this.postJson({ url }, "/deeplink/open");
594
- const link = (0, deeplink_1.toDeepLink)(answer, false, url);
643
+ const deferred = (0, deeplink_1.isOpenUrl)(url);
644
+ const link = (0, deeplink_1.toDeepLink)(answer, deferred, url);
645
+ if (link && deferred)
646
+ await this.keepDeferred(link);
595
647
  if (link)
596
648
  this.emitDeepLink(link);
597
649
  return link;
598
650
  }
599
651
  /**
600
- * The deferred deep link of this install, if it came from one — resolved once,
601
- * on the first launch, and remembered. Null on every install that did not
602
- * come from a link (and on iOS unless the IP match is on for this app).
652
+ * The deferred deep link of this install, if it came from one — resolved on the
653
+ * first launch and remembered. Null on every install that did not come from a
654
+ * link. `matchType` says how it was found; read `payload.value` for the token the
655
+ * shared URL carried (`deep_link_value`).
656
+ *
657
+ * iOS has no install referrer: the deterministic carriers there are the landing
658
+ * page's « Open in app » link (delivered through `handleUrl` / `onDeepLink`) and
659
+ * its code (`redeemDeepLinkCode`). The probabilistic fallback runs only when the
660
+ * user consented — `setConsent(true)` or `consent: true` at init — and the app
661
+ * turned the IP match on in the console.
603
662
  */
604
663
  getDeferredDeepLink() {
605
664
  var _a;
606
665
  return (_a = this.deferred) != null ? _a : Promise.resolve(null);
607
666
  }
667
+ /**
668
+ * The code the iOS landing page showed (« ABCD-EFGH »), typed by the user in the
669
+ * app — the manual fallback when neither the store nor a link carried the click.
670
+ * Case, spaces and the dash are forgiven. Resolves to the link (`matchType:
671
+ * "code"`), delivered to `onDeepLink` too, or null for an unknown / expired code.
672
+ */
673
+ async redeemDeepLinkCode(code) {
674
+ if (!this.started || this.erased || this.opts.deepLinking === false || !code.trim())
675
+ return null;
676
+ const answer = await this.postJson({ code }, "/deeplink/code");
677
+ const link = (0, deeplink_1.toDeepLink)(answer, true);
678
+ if (!link)
679
+ return null;
680
+ await this.keepDeferred(link);
681
+ this.emitDeepLink(link);
682
+ return link;
683
+ }
608
684
  /**
609
685
  * GDPR Art. 17, from inside the app: delete everything the server holds about this
610
686
  * device and this user, and stop sending.
@@ -648,6 +724,10 @@ var require_build = __commonJS({
648
724
  var _a, _b;
649
725
  this.consent = granted ? "granted" : "denied";
650
726
  await ((_b = (_a = this.opts) == null ? void 0 : _a.storage) == null ? void 0 : _b.setItem(CONSENT_KEY, this.consent).catch(() => void 0));
727
+ if (granted && this.deferred && !this.erased) {
728
+ this.deferred = this.deferred.then((link) => link != null ? link : this.retryDeferredWithConsent());
729
+ await this.deferred;
730
+ }
651
731
  }
652
732
  /** True once `forgetMe()` has been honoured — this install sends nothing any more. */
653
733
  get forgotten() {
@@ -702,7 +782,8 @@ var require_build = __commonJS({
702
782
  deviceId: this.context.deviceId,
703
783
  userId: this.opts.userId,
704
784
  storage: this.opts.storage,
705
- native: { getAttributionToken: () => native.getAttributionToken() }
785
+ native: { getAttributionToken: () => native.getAttributionToken() },
786
+ debug: this.debug
706
787
  });
707
788
  }
708
789
  async initSkan() {
@@ -734,7 +815,7 @@ var require_build = __commonJS({
734
815
  try {
735
816
  const cached = await (store == null ? void 0 : store.getItem(DEFERRED_KEY));
736
817
  if (cached)
737
- return JSON.parse(cached);
818
+ return (0, deeplink_1.upgradeStoredDeepLink)(JSON.parse(cached));
738
819
  } catch {
739
820
  }
740
821
  if (!freshInstall && !await (store == null ? void 0 : store.getItem(`${DEFERRED_KEY}_pending`).catch(() => null)))
@@ -742,18 +823,78 @@ var require_build = __commonJS({
742
823
  const platform = (_b = (_a = this.opts.native) == null ? void 0 : _a.platform) != null ? _b : "android";
743
824
  const referrer = platform === "android" ? await this.readReferrer() : null;
744
825
  await (store == null ? void 0 : store.setItem(`${DEFERRED_KEY}_pending`, "1").catch(() => void 0));
745
- const answer = await this.postJson({ platform, installReferrer: referrer == null ? void 0 : referrer.referrer }, "/deeplink/deferred");
826
+ const answer = await this.askDeferred(platform, referrer == null ? void 0 : referrer.referrer);
746
827
  if (!answer)
747
828
  return null;
748
829
  const link = (0, deeplink_1.toDeepLink)(answer, true);
830
+ const kept = await this.storedDeferred();
831
+ if (kept)
832
+ return kept;
749
833
  try {
750
834
  await (store == null ? void 0 : store.setItem(DEFERRED_KEY, JSON.stringify(link)));
835
+ if (!link && this.consent !== "granted") {
836
+ await (store == null ? void 0 : store.setItem(DEFERRED_RETRY_KEY, String(Date.now() + DEFERRED_RETRY_WINDOW_MS)));
837
+ }
751
838
  } catch {
752
839
  }
753
840
  if (link)
754
841
  this.emitDeepLink(link);
755
842
  return link;
756
843
  }
844
+ /** The deferred ask: the referrer (Android), the consent, and what the tap is compared with. */
845
+ askDeferred(platform, installReferrer) {
846
+ return this.postJson({
847
+ platform,
848
+ installReferrer,
849
+ ...this.consent ? { consent: this.consent } : {},
850
+ ...this.context.osVersion ? { osVersion: this.context.osVersion } : {},
851
+ ...this.context.deviceModel ? { deviceModel: this.context.deviceModel } : {}
852
+ }, "/deeplink/deferred");
853
+ }
854
+ /**
855
+ * The user consented AFTER the first launch asked without consent and found
856
+ * nothing: ask once more, inside the hour, so the probabilistic layer can run.
857
+ * Never when a link is already known, never twice.
858
+ */
859
+ async retryDeferredWithConsent() {
860
+ var _a, _b, _c, _d;
861
+ const store = (_a = this.opts) == null ? void 0 : _a.storage;
862
+ if (!store || this.consent !== "granted" || this.opts.deepLinking === false || this.isWeb)
863
+ return null;
864
+ const until = Number(await store.getItem(DEFERRED_RETRY_KEY).catch(() => null));
865
+ if (!until)
866
+ return null;
867
+ await store.setItem(DEFERRED_RETRY_KEY, "").catch(() => void 0);
868
+ if (Date.now() > until)
869
+ return null;
870
+ const known = await this.storedDeferred();
871
+ if (known)
872
+ return known;
873
+ const link = (0, deeplink_1.toDeepLink)(await this.askDeferred((_c = (_b = this.opts.native) == null ? void 0 : _b.platform) != null ? _c : "ios", void 0), true);
874
+ if (!link)
875
+ return null;
876
+ await ((_d = this.opts.storage) == null ? void 0 : _d.setItem(DEFERRED_KEY, JSON.stringify(link)).catch(() => void 0));
877
+ this.emitDeepLink(link);
878
+ return link;
879
+ }
880
+ /** The deferred link already stored for this install, if any. */
881
+ async storedDeferred() {
882
+ var _a;
883
+ try {
884
+ const raw = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(DEFERRED_KEY));
885
+ return raw ? (0, deeplink_1.upgradeStoredDeepLink)(JSON.parse(raw)) : null;
886
+ } catch {
887
+ return null;
888
+ }
889
+ }
890
+ /** Remember `link` as this install's deferred link, unless one is already known. */
891
+ async keepDeferred(link) {
892
+ var _a;
893
+ if (await this.storedDeferred())
894
+ return;
895
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(DEFERRED_KEY, JSON.stringify(link)).catch(() => void 0));
896
+ this.deferred = Promise.resolve(link);
897
+ }
757
898
  emitDeepLink(link) {
758
899
  if (!this.deepLinkListeners.size) {
759
900
  this.undelivered.push(link);
@@ -780,6 +921,13 @@ var require_build = __commonJS({
780
921
  var _a;
781
922
  return ((_a = this.opts) == null ? void 0 : _a.platform) === "web";
782
923
  }
924
+ get installSentKey() {
925
+ return this.debug ? INSTALL_SENT_DEBUG_KEY : INSTALL_SENT_KEY;
926
+ }
927
+ /** Spread into every body: present only in debug mode, so a release build's payload is unchanged. */
928
+ debugField() {
929
+ return this.debug ? { debug: true } : {};
930
+ }
783
931
  wireLifecycle() {
784
932
  const events = {
785
933
  background: () => this.flush(),
@@ -991,7 +1139,7 @@ var require_build = __commonJS({
991
1139
  async sendInstallOnce() {
992
1140
  var _a, _b;
993
1141
  const store = this.opts.storage;
994
- if (store && await store.getItem(INSTALL_SENT_KEY))
1142
+ if (store && await store.getItem(this.installSentKey))
995
1143
  return;
996
1144
  const platform = (_b = (_a = this.opts.native) == null ? void 0 : _a.platform) != null ? _b : "android";
997
1145
  const referrer = await this.readReferrer();
@@ -1012,7 +1160,7 @@ var require_build = __commonJS({
1012
1160
  }
1013
1161
  });
1014
1162
  if (ok)
1015
- await (store == null ? void 0 : store.setItem(INSTALL_SENT_KEY, "1"));
1163
+ await (store == null ? void 0 : store.setItem(this.installSentKey, "1"));
1016
1164
  }
1017
1165
  scheduleFlush(delay = FLUSH_DELAY_MS) {
1018
1166
  if (this.flushTimer)
@@ -1087,7 +1235,7 @@ var require_build = __commonJS({
1087
1235
  const res = await fetch(`${this.opts.endpoint}${path}`, {
1088
1236
  method: "POST",
1089
1237
  headers: { "Content-Type": "application/json" },
1090
- body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body }),
1238
+ body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...this.debugField() }),
1091
1239
  ...this.keepalive()
1092
1240
  });
1093
1241
  return res.ok ? await res.json() : null;
@@ -1132,7 +1280,7 @@ var require_build = __commonJS({
1132
1280
  const res = await fetch(`${this.opts.endpoint}${path}`, {
1133
1281
  method: "POST",
1134
1282
  headers: { "Content-Type": "application/json" },
1135
- body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...consent }),
1283
+ body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...consent, ...this.debugField() }),
1136
1284
  ...this.keepalive()
1137
1285
  });
1138
1286
  if (res.ok)
@@ -1144,6 +1292,28 @@ var require_build = __commonJS({
1144
1292
  }
1145
1293
  };
1146
1294
  exports.Client = Client2;
1295
+ async function detectDebug(opts) {
1296
+ var _a, _b;
1297
+ if (opts.debug !== void 0)
1298
+ return opts.debug;
1299
+ if (opts.platform === "web")
1300
+ return isLocalPage();
1301
+ if (globalThis.__DEV__ === true)
1302
+ return true;
1303
+ try {
1304
+ return await ((_b = (_a = opts.native) == null ? void 0 : _a.isDebugBuild) == null ? void 0 : _b.call(_a)) === true;
1305
+ } catch {
1306
+ return false;
1307
+ }
1308
+ }
1309
+ function isLocalPage(loc = globalThis.location) {
1310
+ if (!loc)
1311
+ return false;
1312
+ if (loc.protocol === "file:")
1313
+ return true;
1314
+ const host = loc.hostname.toLowerCase().replace(/^\[|\]$/g, "");
1315
+ return host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host === "::1" || host === "0.0.0.0" || /^127\.\d+\.\d+\.\d+$/.test(host);
1316
+ }
1147
1317
  exports.Traqio = new Client2();
1148
1318
  }
1149
1319
  });
@@ -1428,12 +1598,17 @@ var TraqioWeb = class {
1428
1598
  platform: "web",
1429
1599
  userId: opts.userId,
1430
1600
  consent,
1601
+ debug: opts.debug,
1431
1602
  lifecycle: ({ background, foreground }) => {
1432
1603
  document.addEventListener("visibilitychange", () => document.visibilityState === "hidden" ? background() : foreground());
1433
1604
  window.addEventListener("pagehide", background);
1434
1605
  }
1435
1606
  });
1436
1607
  }
1608
+ /** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
1609
+ get isDebug() {
1610
+ return this.core.isDebug;
1611
+ }
1437
1612
  /** Record an event — `signup`, `purchase`, `add_to_cart`… Batched, retried, kept across page loads. */
1438
1613
  track(name, props) {
1439
1614
  this.core.track(name, props);