@traqio/web 0.2.1 → 0.3.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
@@ -7,6 +7,11 @@ arrives from a Traqio tracking link, the landing URL carries the ad click id as
7
7
  plus a cookie on your own domain) and hands it back when the visitor converts — so the
8
8
  conversion is tied to its click **deterministically**, not by guesswork.
9
9
 
10
+ A visitor who arrives **without** a Traqio link keeps their origin too: the landing's
11
+ `utm_*` parameters, the ad networks' click ids (`gclid`, `fbclid`, `ttclid`) and the
12
+ referring site, kept the same way in a `traq_src` cookie — so a sign-up from an
13
+ Instagram bio or a newsletter is still reported under its source and campaign.
14
+
10
15
  It also records web events and visits, with consent handling and in-page erasure. No
11
16
  fingerprinting, no third-party cookie, no advertising id. ~7 KB gzipped, no dependency.
12
17
 
@@ -55,6 +60,25 @@ const trackId = Traqio.getTrackId(); // null when the visitor did not come from
55
60
  form.querySelector<HTMLInputElement>('input[name="traq_click"]')!.value = trackId ?? "";
56
61
  ```
57
62
 
63
+ ### The visit's source, when there was no Traqio link
64
+
65
+ On landing, the SDK also keeps where the visitor came from — `utm_source`,
66
+ `utm_medium`, `utm_campaign`, `utm_content`, `utm_term`, `gclid`, `fbclid`, `ttclid`,
67
+ and the referring site's host (never its path) — in a `traq_src` cookie, a plain query
68
+ string. `@traqio/node` reads it with `sourceFromRequest(req)`; elsewhere, send
69
+ `Traqio.getSource()` with the form. Traqio then reports the sign-up under that source
70
+ and campaign. Rules:
71
+
72
+ - a new `utm_*` or click id replaces the kept source (last campaign wins, like the
73
+ trackID); a referrer alone only fills an empty slot, so the return from a payment
74
+ page never overwrites the campaign;
75
+ - when the visitor also came through a Traqio link, the link click wins;
76
+ - same lifetime (`trackIdDays`), same consent rules and same erasure as the trackID.
77
+
78
+ ```ts
79
+ const source = Traqio.getSource(); // { utmSource: "instagram", utmCampaign: "launch", referrer: "l.instagram.com", … } or null
80
+ ```
81
+
58
82
  The browser SDK never sends the trackID itself: a key that anyone can read in your page
59
83
  must not be able to credit a campaign. Your backend sends the conversion with its
60
84
  trackID using a **secret** server key.
@@ -92,7 +116,7 @@ hidden or the page is left.
92
116
  ```ts
93
117
  Traqio.init({ sdkKey: "YOUR_WEB_KEY", waitForConsent: true });
94
118
  // … when your banner gets an answer:
95
- Traqio.setConsent(true); // stores what the page kept in memory, trackID included
119
+ Traqio.setConsent(true); // stores what the page kept in memory, trackID and source included
96
120
  Traqio.setConsent(false); // removes everything the SDK stored on the device
97
121
  ```
98
122
 
@@ -110,7 +134,7 @@ networks.
110
134
  | `userId` | — | Your user id, once known |
111
135
  | `consent` | not collected | The visitor's consent, if already known |
112
136
  | `waitForConsent` | `false` | Store nothing until `setConsent(true)` |
113
- | `trackIdDays` | `30` | How long the trackID is kept after the click |
137
+ | `trackIdDays` | `30` | How long the trackID and the visit's source are kept |
114
138
  | `cookies` | `true` | `false` = localStorage only, no sharing across subdomains |
115
139
  | `debug` | detected | Debug traffic, kept out of every report (see below) |
116
140
 
package/build/index.cjs CHANGED
@@ -367,13 +367,72 @@ var require_adRevenue = __commonJS({
367
367
  "../sdk-core/build/adRevenue.js"(exports) {
368
368
  "use strict";
369
369
  Object.defineProperty(exports, "__esModule", { value: true });
370
- exports.CAPACITOR_ADMOB_PAID_EVENTS = exports.MAX_RN_MIN_VERSION = exports.MAX_RN_REVENUE_EVENTS = exports.GMA_MIN_VERSION = exports.GMA_FULLSCREEN_CHANNELS = void 0;
370
+ exports.CAPACITOR_ADMOB_PAID_EVENTS = exports.MAX_RN_MIN_VERSION = exports.MAX_RN_REVENUE_EVENTS = exports.GMA_MIN_VERSION = exports.GMA_FULLSCREEN_CHANNELS = exports.AdRevenueGate = void 0;
371
371
  exports.fromGoogleMobileAdsPaid = fromGoogleMobileAdsPaid;
372
372
  exports.fromGoogleMobileAdsChannel = fromGoogleMobileAdsChannel;
373
373
  exports.fromGoogleMobileAdsNativeAd = fromGoogleMobileAdsNativeAd;
374
374
  exports.fromMaxAdInfo = fromMaxAdInfo;
375
375
  exports.fromCapacitorAdMob = fromCapacitorAdMob;
376
376
  exports.watchReactNativeAds = watchReactNativeAds;
377
+ function covers(c) {
378
+ return Array.isArray(c) ? c.length > 0 : c === true;
379
+ }
380
+ var AdRevenueGate = class {
381
+ constructor(warn = (m) => console.warn(m)) {
382
+ this.warn = warn;
383
+ this.coverage = {};
384
+ this.warned = /* @__PURE__ */ new Set();
385
+ this.seen = /* @__PURE__ */ new WeakSet();
386
+ }
387
+ arm(coverage) {
388
+ this.coverage = { ...coverage };
389
+ }
390
+ /** Does the automatic capture own this network (any format)? */
391
+ captures(network) {
392
+ return covers(this.coverage[network]);
393
+ }
394
+ /** Does the automatic capture own this format of the network? */
395
+ capturesFormat(network, format) {
396
+ const c = this.coverage[network];
397
+ if (c === true)
398
+ return true;
399
+ return Array.isArray(c) && format !== void 0 && c.includes(format);
400
+ }
401
+ /** A public manual tracker: allowed only for a network nothing captures. */
402
+ manual(network, call) {
403
+ if (!this.captures(network))
404
+ return true;
405
+ this.warnOnce(`manual:${network}`, `[traqio] adRevenue.${network} is on: manual ${call}() ignored \u2014 Traqio already captures this network, remove the call.`);
406
+ return false;
407
+ }
408
+ /** A one-line helper: allowed for the formats the watcher does not capture, once per event. */
409
+ helper(network, format, raw, call) {
410
+ if (this.capturesFormat(network, format)) {
411
+ this.warnOnce(`helper:${network}:${format}`, `[traqio] adRevenue.${network} already captures ${format} ads: ${call} ignored for them, keep it on the formats it is documented for.`);
412
+ return false;
413
+ }
414
+ return this.first(raw);
415
+ }
416
+ /** True the first time this event object is seen (non-objects always pass). */
417
+ first(raw) {
418
+ if (!raw || typeof raw !== "object")
419
+ return true;
420
+ if (this.seen.has(raw))
421
+ return false;
422
+ this.seen.add(raw);
423
+ return true;
424
+ }
425
+ warnOnce(key, message) {
426
+ if (this.warned.has(key))
427
+ return;
428
+ this.warned.add(key);
429
+ try {
430
+ this.warn(message);
431
+ } catch {
432
+ }
433
+ }
434
+ };
435
+ exports.AdRevenueGate = AdRevenueGate;
377
436
  var PRECISION_BY_INDEX = ["unknown", "estimated", "publisher_provided", "precise"];
378
437
  function precisionOf(raw) {
379
438
  var _a;
@@ -486,38 +545,49 @@ var require_adRevenue = __commonJS({
486
545
  return (_e = rn.NativeModules) == null ? void 0 : _e[name];
487
546
  }
488
547
  }
548
+ var MAX_RN_FULLSCREEN_FORMATS = ["interstitial", "rewarded", "rewarded_interstitial", "app_open"];
489
549
  function watchReactNativeAds(want, sink, rn) {
490
550
  var _a, _b, _c, _d;
491
551
  if (!rn) {
492
552
  try {
493
553
  rn = (init_empty(), __toCommonJS(empty_exports));
494
554
  } catch {
495
- return () => void 0;
555
+ return { coverage: {}, stop: () => void 0 };
496
556
  }
497
557
  }
498
558
  const subs = [];
499
- const guard = (parse, deliver) => (e) => {
559
+ const coverage = {};
560
+ const guard = (parse, deliver, rawOf = (e) => e) => (e) => {
500
561
  try {
501
562
  const v = parse(e);
502
563
  if (v)
503
- deliver(v);
564
+ deliver(v, rawOf(e));
504
565
  } catch {
505
566
  }
506
567
  };
568
+ const paidData = (e) => {
569
+ var _a2, _b2;
570
+ return (_b2 = record((_a2 = record(e)) == null ? void 0 : _a2.body)) == null ? void 0 : _b2.data;
571
+ };
507
572
  if (want.admob) {
508
- for (const channel of Object.keys(exports.GMA_FULLSCREEN_CHANNELS)) {
509
- const sub = (_a = rn.DeviceEventEmitter) == null ? void 0 : _a.addListener(channel, guard((e) => fromGoogleMobileAdsChannel(channel, e), sink.admob));
510
- if (sub)
573
+ coverage.admob = [];
574
+ for (const [channel, format] of Object.entries(exports.GMA_FULLSCREEN_CHANNELS)) {
575
+ const sub = (_a = rn.DeviceEventEmitter) == null ? void 0 : _a.addListener(channel, guard((e) => fromGoogleMobileAdsChannel(channel, e), sink.admob, paidData));
576
+ if (sub) {
511
577
  subs.push(sub);
578
+ coverage.admob.push(format);
579
+ }
512
580
  }
513
581
  const nativeAds = nativeModule(rn, "RNGoogleMobileAdsNativeModule");
514
582
  const onNative = guard(fromGoogleMobileAdsNativeAd, sink.admob);
515
583
  try {
516
584
  if (nativeAds && typeof nativeAds.onAdEvent === "function") {
517
585
  subs.push(nativeAds.onAdEvent(onNative));
586
+ coverage.admob.push("native");
518
587
  } else if (nativeAds && rn.NativeEventEmitter) {
519
588
  const emitter = new rn.NativeEventEmitter(((_b = rn.Platform) == null ? void 0 : _b.OS) === "ios" ? nativeAds : void 0);
520
589
  subs.push(emitter.addListener("RNGMANativeAdEvent", onNative));
590
+ coverage.admob.push("native");
521
591
  }
522
592
  } catch {
523
593
  }
@@ -537,15 +607,19 @@ var require_adRevenue = __commonJS({
537
607
  const emitter = new rn.NativeEventEmitter(max);
538
608
  for (const name of names)
539
609
  subs.push(emitter.addListener(name, guard(fromMaxAdInfo, sink.applovinMax)));
610
+ coverage.applovinMax = [...MAX_RN_FULLSCREEN_FORMATS];
540
611
  } catch {
541
612
  }
542
613
  }
543
614
  }
544
- return () => {
545
- for (const s of subs.splice(0)) {
546
- try {
547
- s.remove();
548
- } catch {
615
+ return {
616
+ coverage,
617
+ stop: () => {
618
+ for (const s of subs.splice(0)) {
619
+ try {
620
+ s.remove();
621
+ } catch {
622
+ }
549
623
  }
550
624
  }
551
625
  };
@@ -558,7 +632,7 @@ var require_build = __commonJS({
558
632
  "../sdk-core/build/index.js"(exports) {
559
633
  "use strict";
560
634
  Object.defineProperty(exports, "__esModule", { value: true });
561
- exports.Traqio = exports.Client = 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;
635
+ 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;
562
636
  exports.normalizeAdvertisingId = normalizeAdvertisingId;
563
637
  exports.fromMaxAd = fromMaxAd;
564
638
  exports.detectDebug = detectDebug;
@@ -567,7 +641,7 @@ var require_build = __commonJS({
567
641
  var adservices_1 = require_adservices();
568
642
  var deeplink_1 = require_deeplink();
569
643
  var adRevenue_1 = require_adRevenue();
570
- exports.SDK_VERSION = "0.4.0";
644
+ exports.SDK_VERSION = "0.5.0";
571
645
  var skan_2 = require_skan();
572
646
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
573
647
  return skan_2.Skan;
@@ -617,6 +691,9 @@ var require_build = __commonJS({
617
691
  Object.defineProperty(exports, "watchReactNativeAds", { enumerable: true, get: function() {
618
692
  return adRevenue_2.watchReactNativeAds;
619
693
  } });
694
+ Object.defineProperty(exports, "AdRevenueGate", { enumerable: true, get: function() {
695
+ return adRevenue_2.AdRevenueGate;
696
+ } });
620
697
  var INSTALL_SENT_KEY = "traq_install_sent";
621
698
  var INSTALL_SENT_DEBUG_KEY = "traq_install_sent_debug";
622
699
  var INSTALL_ATTEMPTS_KEY = "traq_install_attempts";
@@ -714,6 +791,7 @@ var require_build = __commonJS({
714
791
  constructor() {
715
792
  this.queue = [];
716
793
  this.adQueue = [];
794
+ this.adGate = new adRevenue_1.AdRevenueGate();
717
795
  this.adBatchId = null;
718
796
  this.context = { sdkVersion: exports.SDK_VERSION };
719
797
  this.referrer = null;
@@ -730,9 +808,10 @@ var require_build = __commonJS({
730
808
  this.debug = false;
731
809
  this.maxRevenuePaid = (adInfo) => {
732
810
  try {
733
- const ad = (0, adRevenue_1.fromMaxAdInfo)(adInfo);
734
- if (ad)
735
- this.trackMaxAdRevenue(ad);
811
+ const max = (0, adRevenue_1.fromMaxAdInfo)(adInfo);
812
+ const ad = max && fromMaxAd(max);
813
+ if (ad && this.adGate.helper("applovinMax", ad.adFormat, adInfo, "Traqio.maxRevenuePaid"))
814
+ this.queueAdRevenue(ad, "applovin_max", "auto");
736
815
  } catch {
737
816
  }
738
817
  };
@@ -775,19 +854,24 @@ var require_build = __commonJS({
775
854
  }
776
855
  // `InitOptions.adRevenue`: hand the ad SDKs' own paid events to the trackers.
777
856
  wireAdRevenue() {
778
- var _a;
857
+ var _a, _b;
779
858
  const want = this.opts.adRevenue;
780
859
  if (!want || this.isWeb || !(want.admob || want.applovinMax))
781
860
  return;
782
861
  const sink = {
783
- admob: (ad) => this.trackAdRevenue(ad),
784
- applovinMax: (ad) => this.trackMaxAdRevenue(ad)
862
+ admob: (ad, raw) => {
863
+ if (this.adGate.first(raw))
864
+ this.queueAdRevenue(ad, "admob", "auto");
865
+ },
866
+ applovinMax: (ad, raw) => {
867
+ const converted = fromMaxAd(ad);
868
+ if (converted && this.adGate.first(raw))
869
+ this.queueAdRevenue(converted, "applovin_max", "auto");
870
+ }
785
871
  };
786
872
  try {
787
- if ((_a = this.opts.native) == null ? void 0 : _a.watchAdRevenue)
788
- this.opts.native.watchAdRevenue(want, sink);
789
- else
790
- (0, adRevenue_1.watchReactNativeAds)(want, sink);
873
+ const coverage = ((_a = this.opts.native) == null ? void 0 : _a.watchAdRevenue) ? (_b = this.opts.native.watchAdRevenue(want, sink)) != null ? _b : want : (0, adRevenue_1.watchReactNativeAds)(want, sink).coverage;
874
+ this.adGate.arm(coverage);
791
875
  } catch {
792
876
  }
793
877
  }
@@ -822,9 +906,14 @@ var require_build = __commonJS({
822
906
  *
823
907
  * Impressions are batched and sent to /ingest/ad-revenue, where they are matched
824
908
  * to this install and become the ad half of ROAS.
909
+ *
910
+ * Ignored (one warning) once `adRevenue: { admob: true }` captures AdMob: the
911
+ * impression is already counted.
825
912
  */
826
913
  trackAdRevenue(ad) {
827
- this.queueAdRevenue(ad, "admob");
914
+ if (!this.adGate.manual("admob", "trackAdRevenue"))
915
+ return;
916
+ this.queueAdRevenue(ad, "admob", "manual");
828
917
  }
829
918
  /**
830
919
  * Report one AppLovin MAX impression's revenue. Call it from MAX's callback:
@@ -836,12 +925,15 @@ var require_build = __commonJS({
836
925
  * }); }
837
926
  *
838
927
  * Same batching, same endpoint and same ROAS numerator as AdMob, filed under
839
- * the `applovin_max` source.
928
+ * the `applovin_max` source. Ignored (one warning) once
929
+ * `adRevenue: { applovinMax: true }` captures MAX.
840
930
  */
841
931
  trackMaxAdRevenue(ad) {
932
+ if (!this.adGate.manual("applovinMax", "trackMaxAdRevenue"))
933
+ return;
842
934
  const converted = fromMaxAd(ad);
843
935
  if (converted)
844
- this.queueAdRevenue(converted, "applovin_max");
936
+ this.queueAdRevenue(converted, "applovin_max", "manual");
845
937
  }
846
938
  /**
847
939
  * The one line for an ad that reports through its own callback — a
@@ -852,25 +944,27 @@ var require_build = __commonJS({
852
944
  * ad.addAdEventListener(AdEventType.PAID, Traqio.admobPaid(AD_UNIT_ID, "rewarded"))
853
945
  *
854
946
  * Reads the library's PAID payload (`value` in currency units, or v17's exact
855
- * `valueMicros`) and reports it as AdMob revenue.
947
+ * `valueMicros`) and reports it as AdMob revenue. With `adRevenue: { admob: true }`
948
+ * it only counts the formats the capture does not reach (banners): on a
949
+ * full-screen or native ad it is ignored, so the impression is never doubled.
856
950
  */
857
951
  admobPaid(adUnitId, adFormat = "banner") {
858
952
  return (event) => {
859
953
  try {
860
954
  const ad = (0, adRevenue_1.fromGoogleMobileAdsPaid)(event, { adUnitId, adFormat });
861
- if (ad)
862
- this.trackAdRevenue(ad);
955
+ if (ad && this.adGate.helper("admob", adFormat, event, "Traqio.admobPaid()"))
956
+ this.queueAdRevenue(ad, "admob", "auto");
863
957
  } catch {
864
958
  }
865
959
  };
866
960
  }
867
- queueAdRevenue(ad, source) {
961
+ queueAdRevenue(ad, source, origin) {
868
962
  var _a;
869
963
  if (!this.started || this.erased)
870
964
  return;
871
965
  if (!(ad.valueMicros >= 0) || !ad.currency)
872
966
  return;
873
- this.adQueue.push({ ...ad, source, impressionId: uuid(), ts: (_a = ad.ts) != null ? _a : Math.floor(Date.now() / 1e3) });
967
+ this.adQueue.push({ ...ad, source, origin, impressionId: uuid(), ts: (_a = ad.ts) != null ? _a : Math.floor(Date.now() / 1e3) });
874
968
  this.skan.addRevenue(ad.valueMicros / 1e6);
875
969
  if (this.adQueue.length > MAX_AD_QUEUE)
876
970
  this.adQueue.splice(0, this.adQueue.length - MAX_AD_QUEUE);
@@ -1765,6 +1859,156 @@ var BrowserStore = class {
1765
1859
  }
1766
1860
  };
1767
1861
 
1862
+ // src/kept.ts
1863
+ var KeptValue = class {
1864
+ constructor(store, key, cookieDomain, cookies, valid) {
1865
+ this.store = store;
1866
+ this.key = key;
1867
+ this.cookieDomain = cookieDomain;
1868
+ this.cookies = cookies;
1869
+ this.valid = valid;
1870
+ }
1871
+ /** The kept value, or null once it has expired or was never there. */
1872
+ get(now = Date.now()) {
1873
+ const raw = this.store.getSync(this.key);
1874
+ if (raw) {
1875
+ try {
1876
+ const parsed = JSON.parse(raw);
1877
+ if (parsed && typeof parsed.id === "string" && parsed.exp > now) return parsed.id;
1878
+ } catch {
1879
+ }
1880
+ }
1881
+ if (this.cookies && this.store.isPersistent) {
1882
+ const fromCookie = readCookie(this.key);
1883
+ if (fromCookie && this.valid(fromCookie)) return fromCookie;
1884
+ }
1885
+ return null;
1886
+ }
1887
+ set(value, maxAgeMs, now = Date.now()) {
1888
+ const record = { id: value, exp: now + maxAgeMs };
1889
+ this.store.setSync(this.key, JSON.stringify(record));
1890
+ if (this.cookies && this.store.isPersistent) writeCookie(this.key, value, maxAgeMs / 1e3, this.cookieDomain());
1891
+ }
1892
+ /** Removes it everywhere — `forgetMe()`. */
1893
+ clear() {
1894
+ this.store.removeSync(this.key);
1895
+ if (this.cookies) deleteCookie(this.key, this.cookieDomain());
1896
+ }
1897
+ /** Writes the cookie half once storage becomes allowed (the localStorage half moves with the store). */
1898
+ persistCookie(now = Date.now()) {
1899
+ const raw = this.store.getSync(this.key);
1900
+ if (!raw || !this.cookies || !this.store.isPersistent) return;
1901
+ try {
1902
+ const parsed = JSON.parse(raw);
1903
+ if (parsed.exp > now) writeCookie(this.key, parsed.id, (parsed.exp - now) / 1e3, this.cookieDomain());
1904
+ } catch {
1905
+ }
1906
+ }
1907
+ };
1908
+
1909
+ // src/source.ts
1910
+ var SOURCE_KEY = "traq_src";
1911
+ var SOURCE_PARAMS = ["utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term", "gclid", "fbclid", "ttclid"];
1912
+ var MAX_VALUE_LENGTH = 200;
1913
+ var FIELD = {
1914
+ utm_source: "utmSource",
1915
+ utm_medium: "utmMedium",
1916
+ utm_campaign: "utmCampaign",
1917
+ utm_content: "utmContent",
1918
+ utm_term: "utmTerm",
1919
+ gclid: "gclid",
1920
+ fbclid: "fbclid",
1921
+ ttclid: "ttclid",
1922
+ referrer: "referrer"
1923
+ };
1924
+ var clean = (v) => {
1925
+ const t = v == null ? void 0 : v.trim();
1926
+ return t ? t.slice(0, MAX_VALUE_LENGTH) : null;
1927
+ };
1928
+ var bare = (host) => host.toLowerCase().replace(/^www\./, "");
1929
+ function sameSite(host, other) {
1930
+ const a = bare(host);
1931
+ const b = bare(other);
1932
+ return a === b || a.endsWith(`.${b}`) || b.endsWith(`.${a}`);
1933
+ }
1934
+ function referrerHost(referrer, pageHref) {
1935
+ if (!referrer) return null;
1936
+ try {
1937
+ const ref = new URL(referrer);
1938
+ if (ref.protocol !== "http:" && ref.protocol !== "https:") return null;
1939
+ if (sameSite(new URL(pageHref).hostname, ref.hostname)) return null;
1940
+ return clean(bare(ref.hostname));
1941
+ } catch {
1942
+ return null;
1943
+ }
1944
+ }
1945
+ function sourceFromLanding(href, referrer, now) {
1946
+ const out = new URLSearchParams();
1947
+ try {
1948
+ const params = new URL(href).searchParams;
1949
+ for (const key of SOURCE_PARAMS) {
1950
+ const v = clean(params.get(key));
1951
+ if (v) out.set(key, v);
1952
+ }
1953
+ } catch {
1954
+ return null;
1955
+ }
1956
+ const fromUrl = out.toString() !== "";
1957
+ const ref = referrerHost(referrer, href);
1958
+ if (ref) out.set("referrer", ref);
1959
+ if (out.toString() === "") return null;
1960
+ out.set("ts", String(now));
1961
+ return { query: out.toString(), fromUrl };
1962
+ }
1963
+ function parseSource(query) {
1964
+ let params;
1965
+ try {
1966
+ params = new URLSearchParams(query);
1967
+ } catch {
1968
+ return null;
1969
+ }
1970
+ const source = {};
1971
+ for (const [param, field] of Object.entries(FIELD)) {
1972
+ const v = clean(params.get(param));
1973
+ if (v) source[field] = v;
1974
+ }
1975
+ if (!Object.keys(source).length) return null;
1976
+ const ts = Number(params.get("ts"));
1977
+ if (Number.isFinite(ts) && ts > 0) source.landedAt = ts;
1978
+ return source;
1979
+ }
1980
+ var SourceKeeper = class {
1981
+ constructor(store, maxAgeMs, cookieDomain, cookies) {
1982
+ this.maxAgeMs = maxAgeMs;
1983
+ this.kept = new KeptValue(store, SOURCE_KEY, cookieDomain, cookies, (v) => parseSource(v) !== null);
1984
+ }
1985
+ /**
1986
+ * Reads the landing. URL parameters (`utm_*`, a click id) REPLACE what is kept:
1987
+ * the last campaign that brought the visitor is the one that counts, as for the
1988
+ * trackID. A referrer alone only fills an empty slot — the return from a payment
1989
+ * page or a webmail must not overwrite the campaign the visitor came from. A
1990
+ * landing with neither (a typed URL, an internal navigation) changes nothing.
1991
+ */
1992
+ capture(href, referrer, now = Date.now()) {
1993
+ const landing = sourceFromLanding(href, referrer, now);
1994
+ if (!landing) return null;
1995
+ if (!landing.fromUrl && this.kept.get(now) !== null) return null;
1996
+ this.kept.set(landing.query, this.maxAgeMs, now);
1997
+ return parseSource(landing.query);
1998
+ }
1999
+ /** The kept source, or null (none, or expired). */
2000
+ get(now = Date.now()) {
2001
+ const query = this.kept.get(now);
2002
+ return query === null ? null : parseSource(query);
2003
+ }
2004
+ clear() {
2005
+ this.kept.clear();
2006
+ }
2007
+ persistCookie(now = Date.now()) {
2008
+ this.kept.persistCookie(now);
2009
+ }
2010
+ };
2011
+
1768
2012
  // src/trackId.ts
1769
2013
  var CLICK_PARAM = "traq_click";
1770
2014
  var STORE_KEY = "traq_click";
@@ -1779,10 +2023,8 @@ function clickIdFromUrl(href) {
1779
2023
  }
1780
2024
  var TrackIdKeeper = class {
1781
2025
  constructor(store, maxAgeMs, cookieDomain, cookies) {
1782
- this.store = store;
1783
2026
  this.maxAgeMs = maxAgeMs;
1784
- this.cookieDomain = cookieDomain;
1785
- this.cookies = cookies;
2027
+ this.kept = new KeptValue(store, STORE_KEY, cookieDomain, cookies, (v) => CLICK_ID.test(v));
1786
2028
  }
1787
2029
  /**
1788
2030
  * Reads the landing URL. A new click REPLACES the kept one: the last ad clicked is
@@ -1791,44 +2033,20 @@ var TrackIdKeeper = class {
1791
2033
  */
1792
2034
  capture(href, now = Date.now()) {
1793
2035
  const id = clickIdFromUrl(href);
1794
- if (id) this.write(id, now);
2036
+ if (id) this.kept.set(id, this.maxAgeMs, now);
1795
2037
  return id;
1796
2038
  }
1797
2039
  /** The kept click id, or null once it has expired or was never there. */
1798
2040
  get(now = Date.now()) {
1799
- const raw = this.store.getSync(STORE_KEY);
1800
- if (raw) {
1801
- try {
1802
- const parsed = JSON.parse(raw);
1803
- if (parsed && typeof parsed.id === "string" && parsed.exp > now) return parsed.id;
1804
- } catch {
1805
- }
1806
- }
1807
- if (this.cookies && this.store.isPersistent) {
1808
- const fromCookie = readCookie(STORE_KEY);
1809
- if (fromCookie && CLICK_ID.test(fromCookie)) return fromCookie;
1810
- }
1811
- return null;
2041
+ return this.kept.get(now);
1812
2042
  }
1813
2043
  /** Removes it everywhere — `forgetMe()`. */
1814
2044
  clear() {
1815
- this.store.removeSync(STORE_KEY);
1816
- if (this.cookies) deleteCookie(STORE_KEY, this.cookieDomain());
2045
+ this.kept.clear();
1817
2046
  }
1818
2047
  /** Writes the cookie half once storage becomes allowed (the localStorage half moves with the store). */
1819
2048
  persistCookie(now = Date.now()) {
1820
- const raw = this.store.getSync(STORE_KEY);
1821
- if (!raw || !this.cookies || !this.store.isPersistent) return;
1822
- try {
1823
- const parsed = JSON.parse(raw);
1824
- if (parsed.exp > now) writeCookie(STORE_KEY, parsed.id, (parsed.exp - now) / 1e3, this.cookieDomain());
1825
- } catch {
1826
- }
1827
- }
1828
- write(id, now) {
1829
- const record = { id, exp: now + this.maxAgeMs };
1830
- this.store.setSync(STORE_KEY, JSON.stringify(record));
1831
- if (this.cookies && this.store.isPersistent) writeCookie(STORE_KEY, id, this.maxAgeMs / 1e3, this.cookieDomain());
2049
+ this.kept.persistCookie(now);
1832
2050
  }
1833
2051
  };
1834
2052
 
@@ -1851,6 +2069,7 @@ var TraqioWeb = class {
1851
2069
  this.core = new import_core.Client();
1852
2070
  this.store = null;
1853
2071
  this.trackIds = null;
2072
+ this.sources = null;
1854
2073
  this.waitForConsent = false;
1855
2074
  this.started = false;
1856
2075
  }
@@ -1871,8 +2090,11 @@ var TraqioWeb = class {
1871
2090
  const consent = (_a = opts.consent) != null ? _a : this.earlyConsent;
1872
2091
  const persistent = !this.waitForConsent || consent === true;
1873
2092
  this.store = new BrowserStore(persistent, cookieDomain, cookies);
1874
- this.trackIds = new TrackIdKeeper(this.store, ((_b = opts.trackIdDays) != null ? _b : DEFAULT_TRACK_ID_DAYS) * DAY_MS, cookieDomain, cookies);
2093
+ const keepMs = ((_b = opts.trackIdDays) != null ? _b : DEFAULT_TRACK_ID_DAYS) * DAY_MS;
2094
+ this.trackIds = new TrackIdKeeper(this.store, keepMs, cookieDomain, cookies);
1875
2095
  this.trackIds.capture(location.href);
2096
+ this.sources = new SourceKeeper(this.store, keepMs, cookieDomain, cookies);
2097
+ this.sources.capture(location.href, document.referrer);
1876
2098
  if (!this.store.getSync(DEVICE_ID_KEY)) {
1877
2099
  const id = randomId();
1878
2100
  if (id) this.store.setSync(DEVICE_ID_KEY, id);
@@ -1910,12 +2132,13 @@ var TraqioWeb = class {
1910
2132
  * stored on the device.
1911
2133
  */
1912
2134
  async setConsent(granted) {
1913
- var _a;
2135
+ var _a, _b;
1914
2136
  if (!this.started) this.earlyConsent = granted;
1915
2137
  if (this.store && this.waitForConsent) {
1916
2138
  if (granted) {
1917
2139
  this.store.enable();
1918
2140
  (_a = this.trackIds) == null ? void 0 : _a.persistCookie();
2141
+ (_b = this.sources) == null ? void 0 : _b.persistCookie();
1919
2142
  } else {
1920
2143
  this.store.disable();
1921
2144
  }
@@ -1931,15 +2154,29 @@ var TraqioWeb = class {
1931
2154
  var _a, _b;
1932
2155
  return (_b = (_a = this.trackIds) == null ? void 0 : _a.get()) != null ? _b : null;
1933
2156
  }
2157
+ /**
2158
+ * Where the visitor came from when no Traqio link brought them — the landing's
2159
+ * `utm_*`, an ad network's click id (`gclid`, `fbclid`, `ttclid`), the referring
2160
+ * site — or null. Kept in the `traq_src` cookie your backend reads with the
2161
+ * sign-up (`@traqio/node`: `sourceFromRequest(req)`); pass this to it instead
2162
+ * when your backend is on another domain. A Traqio link click wins over it.
2163
+ */
2164
+ getSource() {
2165
+ var _a, _b;
2166
+ return (_b = (_a = this.sources) == null ? void 0 : _a.get()) != null ? _b : null;
2167
+ }
1934
2168
  /**
1935
2169
  * GDPR erasure from the page: the server deletes what it holds about this browser
1936
2170
  * and user, and this SDK stops sending and forgets the trackID. Irreversible.
1937
2171
  * Resolves false when the request did not reach the server — then nothing changed.
1938
2172
  */
1939
2173
  async forgetMe() {
1940
- var _a;
2174
+ var _a, _b;
1941
2175
  const ok = await this.core.forgetMe();
1942
- if (ok) (_a = this.trackIds) == null ? void 0 : _a.clear();
2176
+ if (ok) {
2177
+ (_a = this.trackIds) == null ? void 0 : _a.clear();
2178
+ (_b = this.sources) == null ? void 0 : _b.clear();
2179
+ }
1943
2180
  return ok;
1944
2181
  }
1945
2182
  /** Send what is queued now. Already wired to tab hide and page exit. */