@shware/analytics 13.0.2 → 13.0.3

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
@@ -236,6 +236,12 @@ Mode effect replay also queues another view, so its predecessor is the first vie
236
236
  page preserves that navigation referrer and `page_load_id`. Unrelated renders and uncommitted
237
237
  navigation do not advance the reporter's view history.
238
238
 
239
+ `page_location` and `page_referrer` (and a native deep link's `page_location`) are reported
240
+ without their credential-bearing query parameters, stripped on the client before anything is
241
+ sent: `code`, `state`, `token`, `access_token`, `id_token`, `refresh_token`, `session_id`,
242
+ `api_key`, `apikey`, `secret`, `password` and `otp`, matched case-insensitively, in the query and
243
+ in a hash shaped like one (an implicit flow's `#access_token=…`). Every other parameter is kept.
244
+
239
245
  ## Backend API
240
246
 
241
247
  - /analytics/tracks: track events
@@ -14,7 +14,7 @@ function sendFirstVisit(pathname) {
14
14
  page_path: pathname,
15
15
  page_title: document.title,
16
16
  page_referrer: require_web_index.getPageReferrer(),
17
- page_location: window.location.href
17
+ page_location: require_web_index.getPageLocation()
18
18
  });
19
19
  require_setup_index.config.storage.setItem(require_constants_storage.keys.first_visit_time, (/* @__PURE__ */ new Date()).toISOString());
20
20
  }
@@ -112,7 +112,7 @@ function useWebAnalytics(pathname, search) {
112
112
  page_path: pathname,
113
113
  page_title: document.title,
114
114
  page_referrer: require_web_index.getPageReferrer(),
115
- page_location: window.location.href,
115
+ page_location: require_web_index.getPageLocation(),
116
116
  previous_page_path: prevPathname,
117
117
  engagement_time_msec: prevPathname === void 0 ? void 0 : require_setup_session.getSession().flush()
118
118
  });
@@ -1 +1 @@
1
- {"version":3,"file":"use-web-analytics.cjs","names":["config","keys","getPageReferrer","getSession","getPageKey","useRef","throttle"],"sources":["../../src/hooks/use-web-analytics.ts"],"sourcesContent":["import { throttle } from '@shware/utils';\nimport { useEffect, useRef } from 'react';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { sendBeacon, sendPendingEvents, track } from '../track/index';\nimport { getPageReferrer } from '../web/index';\nimport { getPageKey } from '../web/page-key';\n\nfunction sendFirstVisit(pathname: string) {\n if (config.storage.getItem(keys.first_visit_time)) return;\n track('first_visit', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: getPageReferrer(),\n page_location: window.location.href,\n });\n config.storage.setItem(keys.first_visit_time, new Date().toISOString());\n}\n\nfunction sendUserEngagement(trigger: 'pagehide' | 'visibilitychange') {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return;\n sendBeacon('user_engagement', { engagement_time_msec, trigger });\n}\n\n/** Whether the event was actually sent — a zero-engagement crossing reports nothing. */\nfunction sendScroll(): boolean {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return false;\n track('scroll', { engagement_time_msec });\n return true;\n}\n\nfunction getScrollPercent() {\n const scrollTop = window.scrollY || document.documentElement.scrollTop;\n const windowHeight = window.innerHeight;\n const docHeight = document.documentElement.scrollHeight;\n if (docHeight === 0) return 0;\n return ((scrollTop + windowHeight) * 100) / docHeight;\n}\n\n// The queue goes first: a new session's `session_start` is in it, ahead of the engagement that\n// reports for that session. On `hidden` as well as on `pagehide`, as GA4 does: a mobile browser\n// often discards a hidden page without firing `pagehide`.\nfunction onPageHide() {\n getSession().pagehide();\n sendPendingEvents();\n sendUserEngagement('pagehide');\n}\n\nfunction onVisibilityChange() {\n getSession().visibilitychange(document.visibilityState);\n if (document.visibilityState === 'hidden') {\n sendPendingEvents();\n sendUserEngagement('visibilitychange');\n }\n}\n\n/**\n * 1. send session_start event when the page is loaded\n * 2. send scroll event when the user scrolls more than 90% of the page\n * 3. send user_engagement event when the page is hidden or the user is not focused\n * 4. send page_view when the page changes — path or query, see `getPageKey`; `search` is the\n * router's query string (`?a=1`, or `''`), required so no caller forgets that the query is\n * part of what makes a page\n */\nexport function useWebAnalytics(pathname: string, search: string) {\n const page = getPageKey(pathname, search);\n const lastViewPath = useRef<string | undefined>(undefined);\n\n // reset state when the page changes and send scroll when the user navigates to a new page\n const hasSendScroll = useRef(false);\n useEffect(() => {\n hasSendScroll.current = false;\n }, [page]);\n\n useEffect(() => {\n // One lookup for the whole effect: `addEventListener` and its matching\n // `removeEventListener` have to be handed the very same function.\n const session = getSession();\n\n sendFirstVisit(pathname);\n\n const onScroll = throttle(() => {\n session.updateAccumulator();\n if (hasSendScroll.current) return;\n // only send scroll when the user has scrolled more than 90% of the page\n if (getScrollPercent() < 90) return;\n // A crossing with no engaged time (a restored scroll position in an unfocused window) must\n // not consume the page's one shot: the flag is set only once the event is actually sent.\n hasSendScroll.current = sendScroll();\n }, 500);\n\n const checkpointEvents = ['mousedown', 'keydown', 'touchstart'];\n const checkpoint = throttle(session.updateAccumulator, 1000);\n\n window.addEventListener('focus', session.focus);\n window.addEventListener('blur', session.blur);\n window.addEventListener('scroll', onScroll, { passive: true });\n window.addEventListener('pageshow', session.pageshow);\n window.addEventListener('pagehide', onPageHide);\n document.addEventListener('visibilitychange', onVisibilityChange);\n\n // save checkpoint\n checkpointEvents.forEach((e) => {\n window.addEventListener(e, checkpoint, { passive: true, capture: true });\n });\n\n return () => {\n window.removeEventListener('focus', session.focus);\n window.removeEventListener('blur', session.blur);\n window.removeEventListener('scroll', onScroll);\n window.removeEventListener('pageshow', session.pageshow);\n window.removeEventListener('pagehide', onPageHide);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n checkpointEvents.forEach((e) => window.removeEventListener(e, checkpoint, { capture: true }));\n\n onScroll.cancel();\n checkpoint.cancel();\n };\n }, []);\n\n useEffect(() => {\n // `page_path` stays the path — the query is in `page_location` — and the previous page is\n // named by its path too, so a query-only change reports the same path as its predecessor.\n const prevPathname = lastViewPath.current;\n track('page_view', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: getPageReferrer(),\n page_location: window.location.href,\n previous_page_path: prevPathname,\n engagement_time_msec: prevPathname === undefined ? undefined : getSession().flush(),\n });\n // Advance only after this view is queued; effect restoration also em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S,MAAM,OAAO,oBAAoB,GAAG,YAAY,EAAE,SAAS,KAAK,CAAC,CAAC;GAE5F,SAAS,OAAO;GAChB,WAAW,OAAO;EACpB;CACF,GAAG,CAAC,CAAC;CAEL,CAAA,GAAA,MAAA,UAAA,OAAgB;EAGd,MAAM,eAAe,aAAa;EAClC,oBAAA,MAAM,aAAa;GACjB,WAAW;GACX,YAAY,SAAS;GACrB,eAAeJ,kBAAAA,gBAAgB;GAC/B,eAAe,OAAO,SAAS;GAC/B,oBAAoB;GACpB,sBAAsB,iBAAiB,KAAA,IAAY,KAAA,IAAYC,sBAAAA,WAAW,CAAC,CAAC,MAAM;EACpF,CAAC;EAED,aAAa,UAAU;CACzB,GAAG,CAAC,IAAI,CAAC;AACX"}
1
+ {"version":3,"file":"use-web-analytics.cjs","names":["config","keys","getPageReferrer","getPageLocation","getSession","getPageKey","useRef","throttle"],"sources":["../../src/hooks/use-web-analytics.ts"],"sourcesContent":["import { throttle } from '@shware/utils';\nimport { useEffect, useRef } from 'react';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { sendBeacon, sendPendingEvents, track } from '../track/index';\nimport { getPageLocation, getPageReferrer } from '../web/index';\nimport { getPageKey } from '../web/page-key';\n\nfunction sendFirstVisit(pathname: string) {\n if (config.storage.getItem(keys.first_visit_time)) return;\n track('first_visit', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: getPageReferrer(),\n page_location: getPageLocation(),\n });\n config.storage.setItem(keys.first_visit_time, new Date().toISOString());\n}\n\nfunction sendUserEngagement(trigger: 'pagehide' | 'visibilitychange') {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return;\n sendBeacon('user_engagement', { engagement_time_msec, trigger });\n}\n\n/** Whether the event was actually sent — a zero-engagement crossing reports nothing. */\nfunction sendScroll(): boolean {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return false;\n track('scroll', { engagement_time_msec });\n return true;\n}\n\nfunction getScrollPercent() {\n const scrollTop = window.scrollY || document.documentElement.scrollTop;\n const windowHeight = window.innerHeight;\n const docHeight = document.documentElement.scrollHeight;\n if (docHeight === 0) return 0;\n return ((scrollTop + windowHeight) * 100) / docHeight;\n}\n\n// The queue goes first: a new session's `session_start` is in it, ahead of the engagement that\n// reports for that session. On `hidden` as well as on `pagehide`, as GA4 does: a mobile browser\n// often discards a hidden page without firing `pagehide`.\nfunction onPageHide() {\n getSession().pagehide();\n sendPendingEvents();\n sendUserEngagement('pagehide');\n}\n\nfunction onVisibilityChange() {\n getSession().visibilitychange(document.visibilityState);\n if (document.visibilityState === 'hidden') {\n sendPendingEvents();\n sendUserEngagement('visibilitychange');\n }\n}\n\n/**\n * 1. send session_start event when the page is loaded\n * 2. send scroll event when the user scrolls more than 90% of the page\n * 3. send user_engagement event when the page is hidden or the user is not focused\n * 4. send page_view when the page changes — path or query, see `getPageKey`; `search` is the\n * router's query string (`?a=1`, or `''`), required so no caller forgets that the query is\n * part of what makes a page\n */\nexport function useWebAnalytics(pathname: string, search: string) {\n const page = getPageKey(pathname, search);\n const lastViewPath = useRef<string | undefined>(undefined);\n\n // reset state when the page changes and send scroll when the user navigates to a new page\n const hasSendScroll = useRef(false);\n useEffect(() => {\n hasSendScroll.current = false;\n }, [page]);\n\n useEffect(() => {\n // One lookup for the whole effect: `addEventListener` and its matching\n // `removeEventListener` have to be handed the very same function.\n const session = getSession();\n\n sendFirstVisit(pathname);\n\n const onScroll = throttle(() => {\n session.updateAccumulator();\n if (hasSendScroll.current) return;\n // only send scroll when the user has scrolled more than 90% of the page\n if (getScrollPercent() < 90) return;\n // A crossing with no engaged time (a restored scroll position in an unfocused window) must\n // not consume the page's one shot: the flag is set only once the event is actually sent.\n hasSendScroll.current = sendScroll();\n }, 500);\n\n const checkpointEvents = ['mousedown', 'keydown', 'touchstart'];\n const checkpoint = throttle(session.updateAccumulator, 1000);\n\n window.addEventListener('focus', session.focus);\n window.addEventListener('blur', session.blur);\n window.addEventListener('scroll', onScroll, { passive: true });\n window.addEventListener('pageshow', session.pageshow);\n window.addEventListener('pagehide', onPageHide);\n document.addEventListener('visibilitychange', onVisibilityChange);\n\n // save checkpoint\n checkpointEvents.forEach((e) => {\n window.addEventListener(e, checkpoint, { passive: true, capture: true });\n });\n\n return () => {\n window.removeEventListener('focus', session.focus);\n window.removeEventListener('blur', session.blur);\n window.removeEventListener('scroll', onScroll);\n window.removeEventListener('pageshow', session.pageshow);\n window.removeEventListener('pagehide', onPageHide);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n checkpointEvents.forEach((e) => window.removeEventListener(e, checkpoint, { capture: true }));\n\n onScroll.cancel();\n checkpoint.cancel();\n };\n }, []);\n\n useEffect(() => {\n // `page_path` stays the path — the query is in `page_location` — and the previous page is\n // named by its path too, so a query-only change reports the same path as its predecessor.\n const prevPathname = lastViewPath.current;\n track('page_view', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: getPageReferrer(),\n page_location: getPageLocation(),\n previous_page_path: prevPathname,\n engagement_time_msec: prevPathname === undefined ? undefined : getSession().flush(),\n });\n // Advance only after this view is queued; effect restoration also emits a new view.\n lastViewPath.current = pathname;\n }, [page]);\n}\n"],"mappings":";;;;;;;;;;AASA,SAAS,eAAe,UAAkB;CACxC,IAAIA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,gBAAgB,GAAG;CACnD,oBAAA,MAAM,eAAe;EACnB,WAAW;EACX,YAAY,SAAS;EACrB,eAAeC,kBAAAA,gBAAgB;EAC/B,eAAeC,kBAAAA,gBAAgB;CACjC,CAAC;CACD,oBAAA,OAAO,QAAQ,QAAQF,0BAAAA,KAAK,mCAAkB,IAAI,KAAK,EAAA,CAAE,YAAY,CAAC;AACxE;AAEA,SAAS,mBAAmB,SAA0C;CACpE,MAAM,uBAAuBG,sBAAAA,WAAW,CAAC,CAAC,MAAM;CAChD,IAAI,wBAAwB,GAAG;CAC/B,oBAAA,WAAW,mBAAmB;EAAE;EAAsB;CAAQ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setup/session.mjs";
4
4
  import { sendBeacon, sendPendingEvents, track } from "../track/index.mjs";
5
5
  import { getPageKey } from "../web/page-key.mjs";
6
- import { getPageReferrer } from "../web/index.mjs";
6
+ import { getPageLocation, getPageReferrer } from "../web/index.mjs";
7
7
  import { throttle } from "@shware/utils";
8
8
  import { useEffect, useRef } from "react";
9
9
  //#region src/hooks/use-web-analytics.ts
@@ -13,7 +13,7 @@ function sendFirstVisit(pathname) {
13
13
  page_path: pathname,
14
14
  page_title: document.title,
15
15
  page_referrer: getPageReferrer(),
16
- page_location: window.location.href
16
+ page_location: getPageLocation()
17
17
  });
18
18
  config.storage.setItem(keys.first_visit_time, (/* @__PURE__ */ new Date()).toISOString());
19
19
  }
@@ -111,7 +111,7 @@ function useWebAnalytics(pathname, search) {
111
111
  page_path: pathname,
112
112
  page_title: document.title,
113
113
  page_referrer: getPageReferrer(),
114
- page_location: window.location.href,
114
+ page_location: getPageLocation(),
115
115
  previous_page_path: prevPathname,
116
116
  engagement_time_msec: prevPathname === void 0 ? void 0 : getSession().flush()
117
117
  });
@@ -1 +1 @@
1
- {"version":3,"file":"use-web-analytics.mjs","names":[],"sources":["../../src/hooks/use-web-analytics.ts"],"sourcesContent":["import { throttle } from '@shware/utils';\nimport { useEffect, useRef } from 'react';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { sendBeacon, sendPendingEvents, track } from '../track/index';\nimport { getPageReferrer } from '../web/index';\nimport { getPageKey } from '../web/page-key';\n\nfunction sendFirstVisit(pathname: string) {\n if (config.storage.getItem(keys.first_visit_time)) return;\n track('first_visit', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: getPageReferrer(),\n page_location: window.location.href,\n });\n config.storage.setItem(keys.first_visit_time, new Date().toISOString());\n}\n\nfunction sendUserEngagement(trigger: 'pagehide' | 'visibilitychange') {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return;\n sendBeacon('user_engagement', { engagement_time_msec, trigger });\n}\n\n/** Whether the event was actually sent — a zero-engagement crossing reports nothing. */\nfunction sendScroll(): boolean {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return false;\n track('scroll', { engagement_time_msec });\n return true;\n}\n\nfunction getScrollPercent() {\n const scrollTop = window.scrollY || document.documentElement.scrollTop;\n const windowHeight = window.innerHeight;\n const docHeight = document.documentElement.scrollHeight;\n if (docHeight === 0) return 0;\n return ((scrollTop + windowHeight) * 100) / docHeight;\n}\n\n// The queue goes first: a new session's `session_start` is in it, ahead of the engagement that\n// reports for that session. On `hidden` as well as on `pagehide`, as GA4 does: a mobile browser\n// often discards a hidden page without firing `pagehide`.\nfunction onPageHide() {\n getSession().pagehide();\n sendPendingEvents();\n sendUserEngagement('pagehide');\n}\n\nfunction onVisibilityChange() {\n getSession().visibilitychange(document.visibilityState);\n if (document.visibilityState === 'hidden') {\n sendPendingEvents();\n sendUserEngagement('visibilitychange');\n }\n}\n\n/**\n * 1. send session_start event when the page is loaded\n * 2. send scroll event when the user scrolls more than 90% of the page\n * 3. send user_engagement event when the page is hidden or the user is not focused\n * 4. send page_view when the page changes — path or query, see `getPageKey`; `search` is the\n * router's query string (`?a=1`, or `''`), required so no caller forgets that the query is\n * part of what makes a page\n */\nexport function useWebAnalytics(pathname: string, search: string) {\n const page = getPageKey(pathname, search);\n const lastViewPath = useRef<string | undefined>(undefined);\n\n // reset state when the page changes and send scroll when the user navigates to a new page\n const hasSendScroll = useRef(false);\n useEffect(() => {\n hasSendScroll.current = false;\n }, [page]);\n\n useEffect(() => {\n // One lookup for the whole effect: `addEventListener` and its matching\n // `removeEventListener` have to be handed the very same function.\n const session = getSession();\n\n sendFirstVisit(pathname);\n\n const onScroll = throttle(() => {\n session.updateAccumulator();\n if (hasSendScroll.current) return;\n // only send scroll when the user has scrolled more than 90% of the page\n if (getScrollPercent() < 90) return;\n // A crossing with no engaged time (a restored scroll position in an unfocused window) must\n // not consume the page's one shot: the flag is set only once the event is actually sent.\n hasSendScroll.current = sendScroll();\n }, 500);\n\n const checkpointEvents = ['mousedown', 'keydown', 'touchstart'];\n const checkpoint = throttle(session.updateAccumulator, 1000);\n\n window.addEventListener('focus', session.focus);\n window.addEventListener('blur', session.blur);\n window.addEventListener('scroll', onScroll, { passive: true });\n window.addEventListener('pageshow', session.pageshow);\n window.addEventListener('pagehide', onPageHide);\n document.addEventListener('visibilitychange', onVisibilityChange);\n\n // save checkpoint\n checkpointEvents.forEach((e) => {\n window.addEventListener(e, checkpoint, { passive: true, capture: true });\n });\n\n return () => {\n window.removeEventListener('focus', session.focus);\n window.removeEventListener('blur', session.blur);\n window.removeEventListener('scroll', onScroll);\n window.removeEventListener('pageshow', session.pageshow);\n window.removeEventListener('pagehide', onPageHide);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n checkpointEvents.forEach((e) => window.removeEventListener(e, checkpoint, { capture: true }));\n\n onScroll.cancel();\n checkpoint.cancel();\n };\n }, []);\n\n useEffect(() => {\n // `page_path` stays the path — the query is in `page_location` — and the previous page is\n // named by its path too, so a query-only change reports the same path as its predecessor.\n const prevPathname = lastViewPath.current;\n track('page_view', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: getPageReferrer(),\n page_location: window.location.href,\n previous_page_path: prevPathname,\n engagement_time_msec: prevPathname === undefined ? undefined : getSession().flush(),\n });\n // Advance only after this view is queued; effect restoration also emits a new view.\n lastViewPath.current = pathname;\n }, [page]);\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,eAAe,UAAkB;CACxC,IAAI,OAAO,QAAQ,QAAQ,KAAK,gBAAgB,GAAG;CACnD,MAAM,eAAe;EACnB,WAAW;EACX,YAAY,SAAS;EACrB,eAAe,gBAAgB;EAC/B,eAAe,OAAO,SAAS;CACjC,CAAC;CACD,OAAO,QAAQ,QAAQ,KAAK,mCAAkB,IAAI,KAAK,EAAA,CAAE,YAAY,CAAC;AACxE;AAEA,SAAS,mBAAmB,SAA0C;CACpE,MAAM,uBAAuB,WAAW,CAAC,CAA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;EAC9C,OAAO,iBAAiB,QAAQ,QAAQ,IAAI;EAC5C,OAAO,iBAAiB,UAAU,UAAU,EAAE,SAAS,KAAK,CAAC;EAC7D,OAAO,iBAAiB,YAAY,QAAQ,QAAQ;EACpD,OAAO,iBAAiB,YAAY,UAAU;EAC9C,SAAS,iBAAiB,oBAAoB,kBAAkB;EAGhE,iBAAiB,SAAS,MAAM;GAC9B,OAAO,iBAAiB,GAAG,YAAY;IAAE,SAAS;IAAM,SAAS;GAAK,CAAC;EACzE,CAAC;EAED,aAAa;GACX,OAAO,oBAAoB,SAAS,QAAQ,KAAK;GACjD,OAAO,oBAAoB,QAAQ,QAAQ,IAAI;GAC/C,OAAO,oBAAoB,UAAU,QAAQ;GAC7C,OAAO,oBAAoB,YAAY,QAAQ,QAAQ;GACvD,OAAO,oBAAoB,YAAY,UAAU;GACjD,SAAS,oBAAoB,oBAAoB,kBAAkB;GACnE,iBAAiB,SAAS,MAAM,OAAO,oBAAoB,GAAG,YAAY,EAAE,SAAS,KAAK,CAAC,CAAC;GAE5F,SAAS,OAAO;GAChB,WAAW,OAAO;EACpB;CACF,GAAG,CAAC,CAAC;CAEL,gBAAgB;EAGd,MAAM,eAAe,aAAa;EAClC,MAAM,aAAa;GACjB,WAAW;GACX,YAAY,SAAS;GACrB,eAAe,gBAAgB;GAC/B,eAAe,OAAO,SAAS;GAC/B,oBAAoB;GACpB,sBAAsB,iBAAiB,KAAA,IAAY,KAAA,IAAY,WAAW,CAAC,CAAC,MAAM;EACpF,CAAC;EAED,aAAa,UAAU;CACzB,GAAG,CAAC,IAAI,CAAC;AACX"}
1
+ {"version":3,"file":"use-web-analytics.mjs","names":[],"sources":["../../src/hooks/use-web-analytics.ts"],"sourcesContent":["import { throttle } from '@shware/utils';\nimport { useEffect, useRef } from 'react';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { sendBeacon, sendPendingEvents, track } from '../track/index';\nimport { getPageLocation, getPageReferrer } from '../web/index';\nimport { getPageKey } from '../web/page-key';\n\nfunction sendFirstVisit(pathname: string) {\n if (config.storage.getItem(keys.first_visit_time)) return;\n track('first_visit', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: getPageReferrer(),\n page_location: getPageLocation(),\n });\n config.storage.setItem(keys.first_visit_time, new Date().toISOString());\n}\n\nfunction sendUserEngagement(trigger: 'pagehide' | 'visibilitychange') {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return;\n sendBeacon('user_engagement', { engagement_time_msec, trigger });\n}\n\n/** Whether the event was actually sent — a zero-engagement crossing reports nothing. */\nfunction sendScroll(): boolean {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return false;\n track('scroll', { engagement_time_msec });\n return true;\n}\n\nfunction getScrollPercent() {\n const scrollTop = window.scrollY || document.documentElement.scrollTop;\n const windowHeight = window.innerHeight;\n const docHeight = document.documentElement.scrollHeight;\n if (docHeight === 0) return 0;\n return ((scrollTop + windowHeight) * 100) / docHeight;\n}\n\n// The queue goes first: a new session's `session_start` is in it, ahead of the engagement that\n// reports for that session. On `hidden` as well as on `pagehide`, as GA4 does: a mobile browser\n// often discards a hidden page without firing `pagehide`.\nfunction onPageHide() {\n getSession().pagehide();\n sendPendingEvents();\n sendUserEngagement('pagehide');\n}\n\nfunction onVisibilityChange() {\n getSession().visibilitychange(document.visibilityState);\n if (document.visibilityState === 'hidden') {\n sendPendingEvents();\n sendUserEngagement('visibilitychange');\n }\n}\n\n/**\n * 1. send session_start event when the page is loaded\n * 2. send scroll event when the user scrolls more than 90% of the page\n * 3. send user_engagement event when the page is hidden or the user is not focused\n * 4. send page_view when the page changes — path or query, see `getPageKey`; `search` is the\n * router's query string (`?a=1`, or `''`), required so no caller forgets that the query is\n * part of what makes a page\n */\nexport function useWebAnalytics(pathname: string, search: string) {\n const page = getPageKey(pathname, search);\n const lastViewPath = useRef<string | undefined>(undefined);\n\n // reset state when the page changes and send scroll when the user navigates to a new page\n const hasSendScroll = useRef(false);\n useEffect(() => {\n hasSendScroll.current = false;\n }, [page]);\n\n useEffect(() => {\n // One lookup for the whole effect: `addEventListener` and its matching\n // `removeEventListener` have to be handed the very same function.\n const session = getSession();\n\n sendFirstVisit(pathname);\n\n const onScroll = throttle(() => {\n session.updateAccumulator();\n if (hasSendScroll.current) return;\n // only send scroll when the user has scrolled more than 90% of the page\n if (getScrollPercent() < 90) return;\n // A crossing with no engaged time (a restored scroll position in an unfocused window) must\n // not consume the page's one shot: the flag is set only once the event is actually sent.\n hasSendScroll.current = sendScroll();\n }, 500);\n\n const checkpointEvents = ['mousedown', 'keydown', 'touchstart'];\n const checkpoint = throttle(session.updateAccumulator, 1000);\n\n window.addEventListener('focus', session.focus);\n window.addEventListener('blur', session.blur);\n window.addEventListener('scroll', onScroll, { passive: true });\n window.addEventListener('pageshow', session.pageshow);\n window.addEventListener('pagehide', onPageHide);\n document.addEventListener('visibilitychange', onVisibilityChange);\n\n // save checkpoint\n checkpointEvents.forEach((e) => {\n window.addEventListener(e, checkpoint, { passive: true, capture: true });\n });\n\n return () => {\n window.removeEventListener('focus', session.focus);\n window.removeEventListener('blur', session.blur);\n window.removeEventListener('scroll', onScroll);\n window.removeEventListener('pageshow', session.pageshow);\n window.removeEventListener('pagehide', onPageHide);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n checkpointEvents.forEach((e) => window.removeEventListener(e, checkpoint, { capture: true }));\n\n onScroll.cancel();\n checkpoint.cancel();\n };\n }, []);\n\n useEffect(() => {\n // `page_path` stays the path — the query is in `page_location` — and the previous page is\n // named by its path too, so a query-only change reports the same path as its predecessor.\n const prevPathname = lastViewPath.current;\n track('page_view', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: getPageReferrer(),\n page_location: getPageLocation(),\n previous_page_path: prevPathname,\n engagement_time_msec: prevPathname === undefined ? undefined : getSession().flush(),\n });\n // Advance only after this view is queued; effect restoration also emits a new view.\n lastViewPath.current = pathname;\n }, [page]);\n}\n"],"mappings":";;;;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AW,CAAC,CAAC,MAAM;EACpF,CAAC;EAED,aAAa,UAAU;CACzB,GAAG,CAAC,IAAI,CAAC;AACX"}
@@ -1,4 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_utils_redact_url = require("../utils/redact-url.cjs");
2
3
  let react_native = require("react-native");
3
4
  //#region src/native/deep-link.ts
4
5
  /**
@@ -57,7 +58,7 @@ const deepLink = {
57
58
  if (!openUrl) return {};
58
59
  const at = openUrl.indexOf("?");
59
60
  const params = new URLSearchParams(at === -1 ? "" : openUrl.slice(at + 1).split("#")[0]);
60
- const tags = { page_location: openUrl };
61
+ const tags = { page_location: require_utils_redact_url.redactUrl(openUrl) };
61
62
  for (const key of UTM_KEYS) {
62
63
  const value = params.get(key);
63
64
  if (value !== null) tags[key] = value;
@@ -1 +1 @@
1
- {"version":3,"file":"deep-link.cjs","names":["Linking"],"sources":["../../src/native/deep-link.ts"],"sourcesContent":["import { AppState, Linking } from 'react-native';\nimport type { DeepLink } from '../setup/index';\nimport type { TrackTags, UTMParams } from '../track/types';\n\n/**\n * The link that opened the app for this visit, the app's landing page: `getTags` merges its URL\n * (as `page_location`) and utm into every event's tags, so the session it starts is\n * classified as a web page's URL would be. A universal link or an app link from an email or an ad\n * opens the app rather than the site, and without this every one of those sessions was direct.\n *\n * The visit lasts from the open to the app going to the background, so every event in between\n * carries the link, as every event of a web page carries that page's query; the next open, with a\n * link or without, starts from nothing. Only the event that starts a session gets it classified:\n * a link tapped while the session is still running joins it, as GA4 keeps one session across a\n * change of campaign.\n *\n * Read from React Native's `Linking`: the URL that launched the process, and each one that brings\n * the running app to the front. Pass it to `setupAnalytics({ deepLink })`, which starts the\n * listening; nothing happens at import.\n */\nlet openUrl: string | undefined;\n\n/**\n * The parameters a deep link carries: the utm its sender tagged it with. An ad platform's click id\n * rides on the web landing page, not on a link into the app.\n */\nconst UTM_KEYS = [\n 'utm_source',\n 'utm_medium',\n 'utm_campaign',\n 'utm_term',\n 'utm_content',\n 'utm_id',\n 'utm_source_platform',\n 'utm_creative_format',\n 'utm_marketing_tactic',\n] as const satisfies readonly (keyof UTMParams)[];\nlet initialUrlPromise: Promise<void> | undefined;\nlet listening = false;\n\n/** The URL that launched the process, read once; a link that arrived since has the last word. */\nfunction resolveInitialUrl(): Promise<void> {\n initialUrlPromise ??= Linking.getInitialURL().then(\n (url) => {\n if (url && openUrl === undefined) openUrl = url;\n },\n () => undefined\n );\n return initialUrlPromise;\n}\n\nexport const deepLink: DeepLink & {\n /** The link this visit opened with, for an entry `Linking` does not see, such as a push notification. */\n open: (url: string | null | undefined) => void;\n} = {\n listen() {\n if (listening) return;\n listening = true;\n Linking.addEventListener('url', ({ url }) => deepLink.open(url));\n // `background`, not `inactive`: iOS goes inactive for a system sheet or the control center,\n // with the visit still on.\n AppState.addEventListener('change', (state) => {\n if (state === 'background') openUrl = undefined;\n });\n },\n /** Waits for the launch URL, so the first event of a launch has it. */\n async getTags(): Promise<TrackTags> {\n await resolveInitialUrl();\n if (!openUrl) return {};\n const at = openUrl.indexOf('?');\n const params = new URLSearchParams(at === -1 ? '' : openUrl.slice(at + 1).split('#')[0]);\n const tags: TrackTags = { page_location: openUrl };\n for (const key of UTM_KEYS) {\n const value = params.get(key);\n if (value !== null) tags[key] = value;\n }\n return tags;\n },\n open(url) {\n openUrl = url || undefined;\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,IAAI;;;;;AAMJ,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,IAAI;AACJ,IAAI,YAAY;;AAGhB,SAAS,oBAAmC;CAC1C,sBAAsBA,aAAAA,QAAQ,cAAc,CAAC,CAAC,MAC3C,QAAQ;EACP,IAAI,OAAO,YAAY,KAAA,GAAW,UAAU;CAC9C,SACM,KAAA,CACR;CACA,OAAO;AACT;AAEA,MAAa,WAGT;CACF,SAAS;EACP,IAAI,WAAW;EACf,YAAY;EACZ,aAAA,QAAQ,iBAAiB,QAAQ,EAAE,UAAU,SAAS,KAAK,GAAG,CAAC;EAG/D,aAAA,SAAS,iBAAiB,WAAW,UAAU;GAC7C,IAAI,UAAU,cAAc,UAAU,KAAA;EACxC,CAAC;CACH;;CAEA,MAAM,UAA8B;EAClC,MAAM,kBAAkB;EACxB,IAAI,CAAC,SAAS,OAAO,CAAC;EACtB,MAAM,KAAK,QAAQ,QAAQ,GAAG;EAC9B,MAAM,SAAS,IAAI,gBAAgB,OAAO,KAAK,KAAK,QAAQ,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE;EACvF,MAAM,OAAkB,EAAE,eAAe,QAAQ;EACjD,KAAK,MAAM,OAAO,UAAU;GAC1B,MAAM,QAAQ,OAAO,IAAI,GAAG;GAC5B,IAAI,UAAU,MAAM,KAAK,OAAO;EAClC;EACA,OAAO;CACT;CACA,KAAK,KAAK;EACR,UAAU,OAAO,KAAA;CACnB;AACF"}
1
+ {"version":3,"file":"deep-link.cjs","names":["Linking","redactUrl"],"sources":["../../src/native/deep-link.ts"],"sourcesContent":["import { AppState, Linking } from 'react-native';\nimport type { DeepLink } from '../setup/index';\nimport type { TrackTags, UTMParams } from '../track/types';\nimport { redactUrl } from '../utils/redact-url';\n\n/**\n * The link that opened the app for this visit, the app's landing page: `getTags` merges its URL\n * (as `page_location`) and utm into every event's tags, so the session it starts is\n * classified as a web page's URL would be. A universal link or an app link from an email or an ad\n * opens the app rather than the site, and without this every one of those sessions was direct.\n *\n * The visit lasts from the open to the app going to the background, so every event in between\n * carries the link, as every event of a web page carries that page's query; the next open, with a\n * link or without, starts from nothing. Only the event that starts a session gets it classified:\n * a link tapped while the session is still running joins it, as GA4 keeps one session across a\n * change of campaign.\n *\n * Read from React Native's `Linking`: the URL that launched the process, and each one that brings\n * the running app to the front. Pass it to `setupAnalytics({ deepLink })`, which starts the\n * listening; nothing happens at import.\n */\nlet openUrl: string | undefined;\n\n/**\n * The parameters a deep link carries: the utm its sender tagged it with. An ad platform's click id\n * rides on the web landing page, not on a link into the app.\n */\nconst UTM_KEYS = [\n 'utm_source',\n 'utm_medium',\n 'utm_campaign',\n 'utm_term',\n 'utm_content',\n 'utm_id',\n 'utm_source_platform',\n 'utm_creative_format',\n 'utm_marketing_tactic',\n] as const satisfies readonly (keyof UTMParams)[];\nlet initialUrlPromise: Promise<void> | undefined;\nlet listening = false;\n\n/** The URL that launched the process, read once; a link that arrived since has the last word. */\nfunction resolveInitialUrl(): Promise<void> {\n initialUrlPromise ??= Linking.getInitialURL().then(\n (url) => {\n if (url && openUrl === undefined) openUrl = url;\n },\n () => undefined\n );\n return initialUrlPromise;\n}\n\nexport const deepLink: DeepLink & {\n /** The link this visit opened with, for an entry `Linking` does not see, such as a push notification. */\n open: (url: string | null | undefined) => void;\n} = {\n listen() {\n if (listening) return;\n listening = true;\n Linking.addEventListener('url', ({ url }) => deepLink.open(url));\n // `background`, not `inactive`: iOS goes inactive for a system sheet or the control center,\n // with the visit still on.\n AppState.addEventListener('change', (state) => {\n if (state === 'background') openUrl = undefined;\n });\n },\n /** Waits for the launch URL, so the first event of a launch has it. */\n async getTags(): Promise<TrackTags> {\n await resolveInitialUrl();\n if (!openUrl) return {};\n const at = openUrl.indexOf('?');\n const params = new URLSearchParams(at === -1 ? '' : openUrl.slice(at + 1).split('#')[0]);\n const tags: TrackTags = { page_location: redactUrl(openUrl) };\n for (const key of UTM_KEYS) {\n const value = params.get(key);\n if (value !== null) tags[key] = value;\n }\n return tags;\n },\n open(url) {\n openUrl = url || undefined;\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,IAAI;;;;;AAMJ,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,IAAI;AACJ,IAAI,YAAY;;AAGhB,SAAS,oBAAmC;CAC1C,sBAAsBA,aAAAA,QAAQ,cAAc,CAAC,CAAC,MAC3C,QAAQ;EACP,IAAI,OAAO,YAAY,KAAA,GAAW,UAAU;CAC9C,SACM,KAAA,CACR;CACA,OAAO;AACT;AAEA,MAAa,WAGT;CACF,SAAS;EACP,IAAI,WAAW;EACf,YAAY;EACZ,aAAA,QAAQ,iBAAiB,QAAQ,EAAE,UAAU,SAAS,KAAK,GAAG,CAAC;EAG/D,aAAA,SAAS,iBAAiB,WAAW,UAAU;GAC7C,IAAI,UAAU,cAAc,UAAU,KAAA;EACxC,CAAC;CACH;;CAEA,MAAM,UAA8B;EAClC,MAAM,kBAAkB;EACxB,IAAI,CAAC,SAAS,OAAO,CAAC;EACtB,MAAM,KAAK,QAAQ,QAAQ,GAAG;EAC9B,MAAM,SAAS,IAAI,gBAAgB,OAAO,KAAK,KAAK,QAAQ,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE;EACvF,MAAM,OAAkB,EAAE,eAAeC,yBAAAA,UAAU,OAAO,EAAE;EAC5D,KAAK,MAAM,OAAO,UAAU;GAC1B,MAAM,QAAQ,OAAO,IAAI,GAAG;GAC5B,IAAI,UAAU,MAAM,KAAK,OAAO;EAClC;EACA,OAAO;CACT;CACA,KAAK,KAAK;EACR,UAAU,OAAO,KAAA;CACnB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"deep-link.d.cts","names":[],"sources":["../../src/native/deep-link.ts"],"mappings":";;qBAmDa,UAAU;;EAErB,OAAO"}
1
+ {"version":3,"file":"deep-link.d.cts","names":[],"sources":["../../src/native/deep-link.ts"],"mappings":";;qBAoDa,UAAU;;EAErB,OAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"deep-link.d.mts","names":[],"sources":["../../src/native/deep-link.ts"],"mappings":";;qBAmDa,UAAU;;EAErB,OAAO"}
1
+ {"version":3,"file":"deep-link.d.mts","names":[],"sources":["../../src/native/deep-link.ts"],"mappings":";;qBAoDa,UAAU;;EAErB,OAAO"}
@@ -1,3 +1,4 @@
1
+ import { redactUrl } from "../utils/redact-url.mjs";
1
2
  import { AppState, Linking } from "react-native";
2
3
  //#region src/native/deep-link.ts
3
4
  /**
@@ -56,7 +57,7 @@ const deepLink = {
56
57
  if (!openUrl) return {};
57
58
  const at = openUrl.indexOf("?");
58
59
  const params = new URLSearchParams(at === -1 ? "" : openUrl.slice(at + 1).split("#")[0]);
59
- const tags = { page_location: openUrl };
60
+ const tags = { page_location: redactUrl(openUrl) };
60
61
  for (const key of UTM_KEYS) {
61
62
  const value = params.get(key);
62
63
  if (value !== null) tags[key] = value;
@@ -1 +1 @@
1
- {"version":3,"file":"deep-link.mjs","names":[],"sources":["../../src/native/deep-link.ts"],"sourcesContent":["import { AppState, Linking } from 'react-native';\nimport type { DeepLink } from '../setup/index';\nimport type { TrackTags, UTMParams } from '../track/types';\n\n/**\n * The link that opened the app for this visit, the app's landing page: `getTags` merges its URL\n * (as `page_location`) and utm into every event's tags, so the session it starts is\n * classified as a web page's URL would be. A universal link or an app link from an email or an ad\n * opens the app rather than the site, and without this every one of those sessions was direct.\n *\n * The visit lasts from the open to the app going to the background, so every event in between\n * carries the link, as every event of a web page carries that page's query; the next open, with a\n * link or without, starts from nothing. Only the event that starts a session gets it classified:\n * a link tapped while the session is still running joins it, as GA4 keeps one session across a\n * change of campaign.\n *\n * Read from React Native's `Linking`: the URL that launched the process, and each one that brings\n * the running app to the front. Pass it to `setupAnalytics({ deepLink })`, which starts the\n * listening; nothing happens at import.\n */\nlet openUrl: string | undefined;\n\n/**\n * The parameters a deep link carries: the utm its sender tagged it with. An ad platform's click id\n * rides on the web landing page, not on a link into the app.\n */\nconst UTM_KEYS = [\n 'utm_source',\n 'utm_medium',\n 'utm_campaign',\n 'utm_term',\n 'utm_content',\n 'utm_id',\n 'utm_source_platform',\n 'utm_creative_format',\n 'utm_marketing_tactic',\n] as const satisfies readonly (keyof UTMParams)[];\nlet initialUrlPromise: Promise<void> | undefined;\nlet listening = false;\n\n/** The URL that launched the process, read once; a link that arrived since has the last word. */\nfunction resolveInitialUrl(): Promise<void> {\n initialUrlPromise ??= Linking.getInitialURL().then(\n (url) => {\n if (url && openUrl === undefined) openUrl = url;\n },\n () => undefined\n );\n return initialUrlPromise;\n}\n\nexport const deepLink: DeepLink & {\n /** The link this visit opened with, for an entry `Linking` does not see, such as a push notification. */\n open: (url: string | null | undefined) => void;\n} = {\n listen() {\n if (listening) return;\n listening = true;\n Linking.addEventListener('url', ({ url }) => deepLink.open(url));\n // `background`, not `inactive`: iOS goes inactive for a system sheet or the control center,\n // with the visit still on.\n AppState.addEventListener('change', (state) => {\n if (state === 'background') openUrl = undefined;\n });\n },\n /** Waits for the launch URL, so the first event of a launch has it. */\n async getTags(): Promise<TrackTags> {\n await resolveInitialUrl();\n if (!openUrl) return {};\n const at = openUrl.indexOf('?');\n const params = new URLSearchParams(at === -1 ? '' : openUrl.slice(at + 1).split('#')[0]);\n const tags: TrackTags = { page_location: openUrl };\n for (const key of UTM_KEYS) {\n const value = params.get(key);\n if (value !== null) tags[key] = value;\n }\n return tags;\n },\n open(url) {\n openUrl = url || undefined;\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,IAAI;;;;;AAMJ,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,IAAI;AACJ,IAAI,YAAY;;AAGhB,SAAS,oBAAmC;CAC1C,sBAAsB,QAAQ,cAAc,CAAC,CAAC,MAC3C,QAAQ;EACP,IAAI,OAAO,YAAY,KAAA,GAAW,UAAU;CAC9C,SACM,KAAA,CACR;CACA,OAAO;AACT;AAEA,MAAa,WAGT;CACF,SAAS;EACP,IAAI,WAAW;EACf,YAAY;EACZ,QAAQ,iBAAiB,QAAQ,EAAE,UAAU,SAAS,KAAK,GAAG,CAAC;EAG/D,SAAS,iBAAiB,WAAW,UAAU;GAC7C,IAAI,UAAU,cAAc,UAAU,KAAA;EACxC,CAAC;CACH;;CAEA,MAAM,UAA8B;EAClC,MAAM,kBAAkB;EACxB,IAAI,CAAC,SAAS,OAAO,CAAC;EACtB,MAAM,KAAK,QAAQ,QAAQ,GAAG;EAC9B,MAAM,SAAS,IAAI,gBAAgB,OAAO,KAAK,KAAK,QAAQ,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE;EACvF,MAAM,OAAkB,EAAE,eAAe,QAAQ;EACjD,KAAK,MAAM,OAAO,UAAU;GAC1B,MAAM,QAAQ,OAAO,IAAI,GAAG;GAC5B,IAAI,UAAU,MAAM,KAAK,OAAO;EAClC;EACA,OAAO;CACT;CACA,KAAK,KAAK;EACR,UAAU,OAAO,KAAA;CACnB;AACF"}
1
+ {"version":3,"file":"deep-link.mjs","names":[],"sources":["../../src/native/deep-link.ts"],"sourcesContent":["import { AppState, Linking } from 'react-native';\nimport type { DeepLink } from '../setup/index';\nimport type { TrackTags, UTMParams } from '../track/types';\nimport { redactUrl } from '../utils/redact-url';\n\n/**\n * The link that opened the app for this visit, the app's landing page: `getTags` merges its URL\n * (as `page_location`) and utm into every event's tags, so the session it starts is\n * classified as a web page's URL would be. A universal link or an app link from an email or an ad\n * opens the app rather than the site, and without this every one of those sessions was direct.\n *\n * The visit lasts from the open to the app going to the background, so every event in between\n * carries the link, as every event of a web page carries that page's query; the next open, with a\n * link or without, starts from nothing. Only the event that starts a session gets it classified:\n * a link tapped while the session is still running joins it, as GA4 keeps one session across a\n * change of campaign.\n *\n * Read from React Native's `Linking`: the URL that launched the process, and each one that brings\n * the running app to the front. Pass it to `setupAnalytics({ deepLink })`, which starts the\n * listening; nothing happens at import.\n */\nlet openUrl: string | undefined;\n\n/**\n * The parameters a deep link carries: the utm its sender tagged it with. An ad platform's click id\n * rides on the web landing page, not on a link into the app.\n */\nconst UTM_KEYS = [\n 'utm_source',\n 'utm_medium',\n 'utm_campaign',\n 'utm_term',\n 'utm_content',\n 'utm_id',\n 'utm_source_platform',\n 'utm_creative_format',\n 'utm_marketing_tactic',\n] as const satisfies readonly (keyof UTMParams)[];\nlet initialUrlPromise: Promise<void> | undefined;\nlet listening = false;\n\n/** The URL that launched the process, read once; a link that arrived since has the last word. */\nfunction resolveInitialUrl(): Promise<void> {\n initialUrlPromise ??= Linking.getInitialURL().then(\n (url) => {\n if (url && openUrl === undefined) openUrl = url;\n },\n () => undefined\n );\n return initialUrlPromise;\n}\n\nexport const deepLink: DeepLink & {\n /** The link this visit opened with, for an entry `Linking` does not see, such as a push notification. */\n open: (url: string | null | undefined) => void;\n} = {\n listen() {\n if (listening) return;\n listening = true;\n Linking.addEventListener('url', ({ url }) => deepLink.open(url));\n // `background`, not `inactive`: iOS goes inactive for a system sheet or the control center,\n // with the visit still on.\n AppState.addEventListener('change', (state) => {\n if (state === 'background') openUrl = undefined;\n });\n },\n /** Waits for the launch URL, so the first event of a launch has it. */\n async getTags(): Promise<TrackTags> {\n await resolveInitialUrl();\n if (!openUrl) return {};\n const at = openUrl.indexOf('?');\n const params = new URLSearchParams(at === -1 ? '' : openUrl.slice(at + 1).split('#')[0]);\n const tags: TrackTags = { page_location: redactUrl(openUrl) };\n for (const key of UTM_KEYS) {\n const value = params.get(key);\n if (value !== null) tags[key] = value;\n }\n return tags;\n },\n open(url) {\n openUrl = url || undefined;\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,IAAI;;;;;AAMJ,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,IAAI;AACJ,IAAI,YAAY;;AAGhB,SAAS,oBAAmC;CAC1C,sBAAsB,QAAQ,cAAc,CAAC,CAAC,MAC3C,QAAQ;EACP,IAAI,OAAO,YAAY,KAAA,GAAW,UAAU;CAC9C,SACM,KAAA,CACR;CACA,OAAO;AACT;AAEA,MAAa,WAGT;CACF,SAAS;EACP,IAAI,WAAW;EACf,YAAY;EACZ,QAAQ,iBAAiB,QAAQ,EAAE,UAAU,SAAS,KAAK,GAAG,CAAC;EAG/D,SAAS,iBAAiB,WAAW,UAAU;GAC7C,IAAI,UAAU,cAAc,UAAU,KAAA;EACxC,CAAC;CACH;;CAEA,MAAM,UAA8B;EAClC,MAAM,kBAAkB;EACxB,IAAI,CAAC,SAAS,OAAO,CAAC;EACtB,MAAM,KAAK,QAAQ,QAAQ,GAAG;EAC9B,MAAM,SAAS,IAAI,gBAAgB,OAAO,KAAK,KAAK,QAAQ,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE;EACvF,MAAM,OAAkB,EAAE,eAAe,UAAU,OAAO,EAAE;EAC5D,KAAK,MAAM,OAAO,UAAU;GAC1B,MAAM,QAAQ,OAAO,IAAI,GAAG;GAC5B,IAAI,UAAU,MAAM,KAAK,OAAO;EAClC;EACA,OAAO;CACT;CACA,KAAK,KAAK;EACR,UAAU,OAAO,KAAA;CACnB;AACF"}
@@ -0,0 +1,48 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/utils/redact-url.ts
3
+ /**
4
+ * Query parameter names that carry a one-time credential or a secret: OAuth's `code`/`state` and
5
+ * tokens, a Stripe Checkout `session_id`, API keys, one-time passwords. Compared lower-cased.
6
+ */
7
+ const REDACTED_URL_PARAMS = [
8
+ "code",
9
+ "state",
10
+ "token",
11
+ "access_token",
12
+ "id_token",
13
+ "refresh_token",
14
+ "session_id",
15
+ "api_key",
16
+ "apikey",
17
+ "secret",
18
+ "password",
19
+ "otp"
20
+ ];
21
+ const redacted = new Set(REDACTED_URL_PARAMS);
22
+ /** `part` from its `sep` on is a query string: drop the redacted names, keep the rest. */
23
+ function redactAfter(part, sep) {
24
+ const at = part.indexOf(sep);
25
+ if (at === -1 || !part.includes("=")) return part;
26
+ const params = new URLSearchParams(part.slice(at + 1));
27
+ for (const key of Array.from(params.keys())) if (redacted.has(key.toLowerCase())) params.delete(key);
28
+ const rest = params.toString();
29
+ return rest ? `${part.slice(0, at + 1)}${rest}` : part.slice(0, at);
30
+ }
31
+ /**
32
+ * The URL without the credential-bearing query parameters in `REDACTED_URL_PARAMS`, from its query
33
+ * and from a hash shaped like one (an implicit flow's `#access_token=…`, a hash router's
34
+ * `#/callback?code=…`), so an OAuth or payment redirect's one-time values never reach the
35
+ * analytics tables as `page_location` or `page_referrer`. Kept parameters come back in
36
+ * `URLSearchParams` form (`a b` as `a+b`); a string with no query and no hash is returned as is.
37
+ */
38
+ function redactUrl(url) {
39
+ const hashAt = url.indexOf("#");
40
+ const head = hashAt === -1 ? url : url.slice(0, hashAt);
41
+ const hash = hashAt === -1 ? "" : url.slice(hashAt);
42
+ return redactAfter(head, "?") + redactAfter(hash, hash.includes("?") ? "?" : "#");
43
+ }
44
+ //#endregion
45
+ exports.REDACTED_URL_PARAMS = REDACTED_URL_PARAMS;
46
+ exports.redactUrl = redactUrl;
47
+
48
+ //# sourceMappingURL=redact-url.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact-url.cjs","names":[],"sources":["../../src/utils/redact-url.ts"],"sourcesContent":["/**\n * Query parameter names that carry a one-time credential or a secret: OAuth's `code`/`state` and\n * tokens, a Stripe Checkout `session_id`, API keys, one-time passwords. Compared lower-cased.\n */\nexport const REDACTED_URL_PARAMS: readonly string[] = [\n 'code',\n 'state',\n 'token',\n 'access_token',\n 'id_token',\n 'refresh_token',\n 'session_id',\n 'api_key',\n 'apikey',\n 'secret',\n 'password',\n 'otp',\n];\n\nconst redacted = new Set(REDACTED_URL_PARAMS);\n\n/** `part` from its `sep` on is a query string: drop the redacted names, keep the rest. */\nfunction redactAfter(part: string, sep: string): string {\n const at = part.indexOf(sep);\n if (at === -1 || !part.includes('=')) return part;\n const params = new URLSearchParams(part.slice(at + 1));\n // A copy of the keys: deleting while iterating the live iterator would skip entries.\n for (const key of Array.from(params.keys())) {\n if (redacted.has(key.toLowerCase())) params.delete(key);\n }\n const rest = params.toString();\n return rest ? `${part.slice(0, at + 1)}${rest}` : part.slice(0, at);\n}\n\n/**\n * The URL without the credential-bearing query parameters in `REDACTED_URL_PARAMS`, from its query\n * and from a hash shaped like one (an implicit flow's `#access_token=…`, a hash router's\n * `#/callback?code=…`), so an OAuth or payment redirect's one-time values never reach the\n * analytics tables as `page_location` or `page_referrer`. Kept parameters come back in\n * `URLSearchParams` form (`a b` as `a+b`); a string with no query and no hash is returned as is.\n */\nexport function redactUrl(url: string): string {\n const hashAt = url.indexOf('#');\n const head = hashAt === -1 ? url : url.slice(0, hashAt);\n const hash = hashAt === -1 ? '' : url.slice(hashAt);\n return redactAfter(head, '?') + redactAfter(hash, hash.includes('?') ? '?' : '#');\n}\n"],"mappings":";;;;;;AAIA,MAAa,sBAAyC;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,WAAW,IAAI,IAAI,mBAAmB;;AAG5C,SAAS,YAAY,MAAc,KAAqB;CACtD,MAAM,KAAK,KAAK,QAAQ,GAAG;CAC3B,IAAI,OAAO,MAAM,CAAC,KAAK,SAAS,GAAG,GAAG,OAAO;CAC7C,MAAM,SAAS,IAAI,gBAAgB,KAAK,MAAM,KAAK,CAAC,CAAC;CAErD,KAAK,MAAM,OAAO,MAAM,KAAK,OAAO,KAAK,CAAC,GACxC,IAAI,SAAS,IAAI,IAAI,YAAY,CAAC,GAAG,OAAO,OAAO,GAAG;CAExD,MAAM,OAAO,OAAO,SAAS;CAC7B,OAAO,OAAO,GAAG,KAAK,MAAM,GAAG,KAAK,CAAC,IAAI,SAAS,KAAK,MAAM,GAAG,EAAE;AACpE;;;;;;;;AASA,SAAgB,UAAU,KAAqB;CAC7C,MAAM,SAAS,IAAI,QAAQ,GAAG;CAC9B,MAAM,OAAO,WAAW,KAAK,MAAM,IAAI,MAAM,GAAG,MAAM;CACtD,MAAM,OAAO,WAAW,KAAK,KAAK,IAAI,MAAM,MAAM;CAClD,OAAO,YAAY,MAAM,GAAG,IAAI,YAAY,MAAM,KAAK,SAAS,GAAG,IAAI,MAAM,GAAG;AAClF"}
@@ -0,0 +1,16 @@
1
+ //#region src/utils/redact-url.d.ts
2
+ /**
3
+ * Query parameter names that carry a one-time credential or a secret: OAuth's `code`/`state` and
4
+ * tokens, a Stripe Checkout `session_id`, API keys, one-time passwords. Compared lower-cased.
5
+ */
6
+ export declare const REDACTED_URL_PARAMS: readonly string[];
7
+ /**
8
+ * The URL without the credential-bearing query parameters in `REDACTED_URL_PARAMS`, from its query
9
+ * and from a hash shaped like one (an implicit flow's `#access_token=…`, a hash router's
10
+ * `#/callback?code=…`), so an OAuth or payment redirect's one-time values never reach the
11
+ * analytics tables as `page_location` or `page_referrer`. Kept parameters come back in
12
+ * `URLSearchParams` form (`a b` as `a+b`); a string with no query and no hash is returned as is.
13
+ */
14
+ export declare function redactUrl(url: string): string;
15
+ //#endregion
16
+ //# sourceMappingURL=redact-url.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact-url.d.cts","names":[],"sources":["../../src/utils/redact-url.ts"],"mappings":";;;;;qBAIa;;;;;;;;wBAqCG,UAAU"}
@@ -0,0 +1,16 @@
1
+ //#region src/utils/redact-url.d.ts
2
+ /**
3
+ * Query parameter names that carry a one-time credential or a secret: OAuth's `code`/`state` and
4
+ * tokens, a Stripe Checkout `session_id`, API keys, one-time passwords. Compared lower-cased.
5
+ */
6
+ export declare const REDACTED_URL_PARAMS: readonly string[];
7
+ /**
8
+ * The URL without the credential-bearing query parameters in `REDACTED_URL_PARAMS`, from its query
9
+ * and from a hash shaped like one (an implicit flow's `#access_token=…`, a hash router's
10
+ * `#/callback?code=…`), so an OAuth or payment redirect's one-time values never reach the
11
+ * analytics tables as `page_location` or `page_referrer`. Kept parameters come back in
12
+ * `URLSearchParams` form (`a b` as `a+b`); a string with no query and no hash is returned as is.
13
+ */
14
+ export declare function redactUrl(url: string): string;
15
+ //#endregion
16
+ //# sourceMappingURL=redact-url.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact-url.d.mts","names":[],"sources":["../../src/utils/redact-url.ts"],"mappings":";;;;;qBAIa;;;;;;;;wBAqCG,UAAU"}
@@ -0,0 +1,46 @@
1
+ //#region src/utils/redact-url.ts
2
+ /**
3
+ * Query parameter names that carry a one-time credential or a secret: OAuth's `code`/`state` and
4
+ * tokens, a Stripe Checkout `session_id`, API keys, one-time passwords. Compared lower-cased.
5
+ */
6
+ const REDACTED_URL_PARAMS = [
7
+ "code",
8
+ "state",
9
+ "token",
10
+ "access_token",
11
+ "id_token",
12
+ "refresh_token",
13
+ "session_id",
14
+ "api_key",
15
+ "apikey",
16
+ "secret",
17
+ "password",
18
+ "otp"
19
+ ];
20
+ const redacted = new Set(REDACTED_URL_PARAMS);
21
+ /** `part` from its `sep` on is a query string: drop the redacted names, keep the rest. */
22
+ function redactAfter(part, sep) {
23
+ const at = part.indexOf(sep);
24
+ if (at === -1 || !part.includes("=")) return part;
25
+ const params = new URLSearchParams(part.slice(at + 1));
26
+ for (const key of Array.from(params.keys())) if (redacted.has(key.toLowerCase())) params.delete(key);
27
+ const rest = params.toString();
28
+ return rest ? `${part.slice(0, at + 1)}${rest}` : part.slice(0, at);
29
+ }
30
+ /**
31
+ * The URL without the credential-bearing query parameters in `REDACTED_URL_PARAMS`, from its query
32
+ * and from a hash shaped like one (an implicit flow's `#access_token=…`, a hash router's
33
+ * `#/callback?code=…`), so an OAuth or payment redirect's one-time values never reach the
34
+ * analytics tables as `page_location` or `page_referrer`. Kept parameters come back in
35
+ * `URLSearchParams` form (`a b` as `a+b`); a string with no query and no hash is returned as is.
36
+ */
37
+ function redactUrl(url) {
38
+ const hashAt = url.indexOf("#");
39
+ const head = hashAt === -1 ? url : url.slice(0, hashAt);
40
+ const hash = hashAt === -1 ? "" : url.slice(hashAt);
41
+ return redactAfter(head, "?") + redactAfter(hash, hash.includes("?") ? "?" : "#");
42
+ }
43
+ //#endregion
44
+ export { REDACTED_URL_PARAMS, redactUrl };
45
+
46
+ //# sourceMappingURL=redact-url.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact-url.mjs","names":[],"sources":["../../src/utils/redact-url.ts"],"sourcesContent":["/**\n * Query parameter names that carry a one-time credential or a secret: OAuth's `code`/`state` and\n * tokens, a Stripe Checkout `session_id`, API keys, one-time passwords. Compared lower-cased.\n */\nexport const REDACTED_URL_PARAMS: readonly string[] = [\n 'code',\n 'state',\n 'token',\n 'access_token',\n 'id_token',\n 'refresh_token',\n 'session_id',\n 'api_key',\n 'apikey',\n 'secret',\n 'password',\n 'otp',\n];\n\nconst redacted = new Set(REDACTED_URL_PARAMS);\n\n/** `part` from its `sep` on is a query string: drop the redacted names, keep the rest. */\nfunction redactAfter(part: string, sep: string): string {\n const at = part.indexOf(sep);\n if (at === -1 || !part.includes('=')) return part;\n const params = new URLSearchParams(part.slice(at + 1));\n // A copy of the keys: deleting while iterating the live iterator would skip entries.\n for (const key of Array.from(params.keys())) {\n if (redacted.has(key.toLowerCase())) params.delete(key);\n }\n const rest = params.toString();\n return rest ? `${part.slice(0, at + 1)}${rest}` : part.slice(0, at);\n}\n\n/**\n * The URL without the credential-bearing query parameters in `REDACTED_URL_PARAMS`, from its query\n * and from a hash shaped like one (an implicit flow's `#access_token=…`, a hash router's\n * `#/callback?code=…`), so an OAuth or payment redirect's one-time values never reach the\n * analytics tables as `page_location` or `page_referrer`. Kept parameters come back in\n * `URLSearchParams` form (`a b` as `a+b`); a string with no query and no hash is returned as is.\n */\nexport function redactUrl(url: string): string {\n const hashAt = url.indexOf('#');\n const head = hashAt === -1 ? url : url.slice(0, hashAt);\n const hash = hashAt === -1 ? '' : url.slice(hashAt);\n return redactAfter(head, '?') + redactAfter(hash, hash.includes('?') ? '?' : '#');\n}\n"],"mappings":";;;;;AAIA,MAAa,sBAAyC;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,WAAW,IAAI,IAAI,mBAAmB;;AAG5C,SAAS,YAAY,MAAc,KAAqB;CACtD,MAAM,KAAK,KAAK,QAAQ,GAAG;CAC3B,IAAI,OAAO,MAAM,CAAC,KAAK,SAAS,GAAG,GAAG,OAAO;CAC7C,MAAM,SAAS,IAAI,gBAAgB,KAAK,MAAM,KAAK,CAAC,CAAC;CAErD,KAAK,MAAM,OAAO,MAAM,KAAK,OAAO,KAAK,CAAC,GACxC,IAAI,SAAS,IAAI,IAAI,YAAY,CAAC,GAAG,OAAO,OAAO,GAAG;CAExD,MAAM,OAAO,OAAO,SAAS;CAC7B,OAAO,OAAO,GAAG,KAAK,MAAM,GAAG,KAAK,CAAC,IAAI,SAAS,KAAK,MAAM,GAAG,EAAE;AACpE;;;;;;;;AASA,SAAgB,UAAU,KAAqB;CAC7C,MAAM,SAAS,IAAI,QAAQ,GAAG;CAC9B,MAAM,OAAO,WAAW,KAAK,MAAM,IAAI,MAAM,GAAG,MAAM;CACtD,MAAM,OAAO,WAAW,KAAK,KAAK,IAAI,MAAM,MAAM;CAClD,OAAO,YAAY,MAAM,GAAG,IAAI,YAAY,MAAM,KAAK,SAAS,GAAG,IAAI,MAAM,GAAG;AAClF"}
@@ -4,6 +4,7 @@ const require_setup_index = require("../setup/index.cjs");
4
4
  const require_constants_storage = require("../constants/storage.cjs");
5
5
  const require_link_index = require("../link/index.cjs");
6
6
  const require_es5$1 = require("../node_modules/.pnpm/bowser@2.14.1/node_modules/bowser/es5.cjs");
7
+ const require_utils_redact_url = require("../utils/redact-url.cjs");
7
8
  const require_web_page_key = require("./page-key.cjs");
8
9
  let uuid = require("uuid");
9
10
  let cookie = require("cookie");
@@ -39,13 +40,13 @@ function getDeviceId() {
39
40
  */
40
41
  let pageLoad;
41
42
  function currentPage() {
42
- const href = window.location.href;
43
+ const href = require_utils_redact_url.redactUrl(window.location.href);
43
44
  const page = require_web_page_key.getPageKey(window.location.pathname, window.location.search);
44
45
  if (pageLoad?.page === page) {
45
46
  pageLoad.href = href;
46
47
  return pageLoad;
47
48
  }
48
- const referrer = pageLoad ? pageLoad.href : document.referrer || void 0;
49
+ const referrer = pageLoad ? pageLoad.href : require_utils_redact_url.redactUrl(document.referrer) || void 0;
49
50
  pageLoad = {
50
51
  page,
51
52
  id: randomUUID(),
@@ -54,7 +55,14 @@ function currentPage() {
54
55
  };
55
56
  return pageLoad;
56
57
  }
57
- /** The current page's referrer: see `pageLoad`. */
58
+ /**
59
+ * The current page's URL as reported, without its credential parameters (`redactUrl`), so
60
+ * `page_location` never carries an OAuth code or a checkout session id.
61
+ */
62
+ function getPageLocation() {
63
+ return require_utils_redact_url.redactUrl(window.location.href);
64
+ }
65
+ /** The current page's referrer, without its credential parameters: see `pageLoad`. */
58
66
  function getPageReferrer() {
59
67
  return currentPage().referrer;
60
68
  }
@@ -77,7 +85,7 @@ function getCachedLink(id) {
77
85
  /** The user agent cannot change while the page is open, so it is parsed once. */
78
86
  let parser;
79
87
  async function getTags() {
80
- const page_location = window.location.href;
88
+ const page_location = require_utils_redact_url.redactUrl(window.location.href);
81
89
  const { id: page_load_id, referrer: page_referrer } = currentPage();
82
90
  const page_title = document.title;
83
91
  parser ??= import_es5.default.getParser(window.navigator.userAgent);
@@ -182,6 +190,7 @@ const storage = {
182
190
  };
183
191
  //#endregion
184
192
  exports.getDeviceId = getDeviceId;
193
+ exports.getPageLocation = getPageLocation;
185
194
  exports.getPageReferrer = getPageReferrer;
186
195
  exports.getTags = getTags;
187
196
  exports.storage = storage;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["uuidv4","config","keys","getPageKey","getLink","Bowser","parseCookie"],"sources":["../../src/web/index.ts"],"sourcesContent":["import Bowser from 'bowser';\nimport { parseCookie } from 'cookie';\nimport { v4 as uuidv4 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { type Link, getLink } from '../link/index';\nimport { type Storage, cache, config } from '../setup/index';\nimport type { TrackTags } from '../track/types';\nimport { getPageKey } from './page-key';\n\n// lib.dom types `crypto.randomUUID` as always present, but it is missing in insecure contexts\n// and older browsers, so probe it before use.\nfunction randomUUID(): string {\n return (crypto as Partial<Crypto>).randomUUID ? crypto.randomUUID() : uuidv4();\n}\n\nexport function getDeviceId() {\n const cached = config.storage.getItem(keys.device_id);\n if (cached) return cached;\n const id = randomUUID();\n config.storage.setItem(keys.device_id, id);\n return id;\n}\n\n/**\n * The current page load, keyed by the page it was loaded at. A module variable and nothing more\n * persistent: the id must die with the page (a reload is a new page load, and storage would\n * carry it over — or, shared across tabs, let two pages overwrite each other's).\n *\n * Keyed by `getPageKey` because that is what the SDK's own `page_view` fires on (see\n * `useWebAnalytics`): the id exists to link an event to the `page_view` of the page it happened\n * on, so it must rotate exactly when a `page_view` is sent — path or query change, yes; hash\n * change or tracking-parameter cleanup, no.\n *\n * `referrer` is the page's referrer as GA4 reports it in a single page app: `document.referrer`\n * for the document's first page, and the previous page's URL after an in-app navigation. The\n * browser never updates `document.referrer` on a `pushState`, so read alone it would name the\n * site the visit came from on every later page — and a session opened there, after 30 minutes\n * idle, would count that site as a second visit from it. With the previous page as its referrer,\n * that session's referrer is the product's own host: no touch, a direct session, which the\n * attribution view then credits to the touch before it.\n */\nlet pageLoad: { page: string; id: string; href: string; referrer: string | undefined } | undefined;\n\nfunction currentPage() {\n const href = window.location.href;\n const page = getPageKey(window.location.pathname, window.location.search);\n if (pageLoad?.page === page) {\n // The same page, its URL maybe cleaned of tracking parameters since: the next page's\n // referrer is the URL as it last was, as the browser's own would be.\n pageLoad.href = href;\n return pageLoad;\n }\n const referrer = pageLoad ? pageLoad.href : document.referrer || undefined;\n pageLoad = { page, id: randomUUID(), href, referrer };\n return pageLoad;\n}\n\n/** The current page's referrer: see `pageLoad`. */\nexport function getPageReferrer(): string | undefined {\n return currentPage().referrer;\n}\n\nconst links = new Map<string, Promise<Link | null>>();\n\n/**\n * `getTags` runs once per event now, and the link a `?s=` id points at cannot change while the\n * page is open, so an uncached lookup would put an identical request on the wire for every\n * event the page sends.\n */\nfunction getCachedLink(id: string) {\n const cached = links.get(id);\n if (cached) return cached;\n const link = getLink(id).then((result) => {\n // A lookup that came back empty must not stick for the lifetime of the page. `getLink`\n // answers null for a network failure as well as for a link that does not exist, and losing\n // the link's utm params for every later event costs more than repeating a rare request.\n if (!result) links.delete(id);\n return result;\n });\n links.set(id, link);\n return link;\n}\n\n/** The user agent cannot change while the page is open, so it is parsed once. */\nlet parser: ReturnType<typeof Bowser.getParser> | undefined;\n\nexport async function getTags() {\n // Read the page before the first await: `getTags` runs when the event happens, and a single\n // page app can navigate while the link lookup below is still in flight.\n const page_location = window.location.href;\n const { id: page_load_id, referrer: page_referrer } = currentPage();\n const page_title = document.title;\n\n parser ??= Bowser.getParser(window.navigator.userAgent);\n const params = new URLSearchParams(window.location.search);\n const os = parser.getOS();\n const browser = parser.getBrowser();\n const platform = parser.getPlatform();\n const parsed = parseCookie(document.cookie);\n\n const linkId = params.get('s');\n const link = linkId ? await getCachedLink(linkId) : null;\n\n const tags: TrackTags = {\n os: `${os.name} ${os.version}`,\n os_name: os.name,\n os_version: os.version,\n browser: `${browser.name} ${browser.version}`,\n browser_name: browser.name,\n browser_version: browser.version,\n device: platform.model,\n device_id: getDeviceId(),\n device_type: platform.type,\n device_vendor: platform.vendor,\n device_pixel_ratio: window.devicePixelRatio,\n screen_width: window.screen.width,\n screen_height: window.screen.height,\n screen_resolution: `${window.screen.width}x${window.screen.height}`,\n webdriver: navigator.webdriver || undefined,\n release: config.release,\n language: navigator.language,\n time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n page_location,\n page_referrer,\n page_title,\n page_load_id,\n // Ad click ids from the URL, each under its parameter's name: this page's click, which\n // names the visit's channel (`CLICK_ID_CHANNELS`). Never filled from a cookie — a cookie\n // outlives the click; the cookies go below under their own names.\n fbclid: params.get('fbclid') ?? undefined,\n ad_id: params.get('ad_id') ?? undefined,\n ad_name: params.get('ad_name') ?? undefined,\n adset_id: params.get('adset_id') ?? undefined,\n adset_name: params.get('adset_name') ?? undefined,\n campaign_id: params.get('campaign_id') ?? undefined,\n campaign_name: params.get('campaign_name') ?? undefined,\n placement: params.get('placement') ?? undefined,\n gclid: params.get('gclid') ?? undefined,\n gclsrc: params.get('gclsrc') ?? undefined,\n gad_source: params.get('gad_source') ?? undefined,\n gad_campaignid: params.get('gad_campaignid') ?? undefined,\n network: params.get('network') ?? undefined,\n match_type: params.get('match_type') ?? undefined,\n wbraid: params.get('wbraid') ?? undefined,\n gbraid: params.get('gbraid') ?? undefined,\n dclid: params.get('dclid') ?? undefined,\n msclkid: params.get('msclkid') ?? undefined,\n rdt_cid: params.get('rdt_cid') ?? undefined,\n li_fat_id: params.get('li_fat_id') ?? undefined,\n oppref: params.get('oppref') ?? undefined,\n ko_click_id: params.get('ko_click_id') ?? undefined,\n // Snapchat appends `ScCid`, and URL parameters are case-sensitive.\n ScCid: params.get('ScCid') ?? undefined,\n ttclid: params.get('ttclid') ?? undefined,\n twclid: params.get('twclid') ?? undefined,\n yclid: params.get('yclid') ?? undefined,\n epik: params.get('epik') ?? undefined,\n // The ad platforms' first-party cookies, raw and under the cookie's own name, for the\n // conversion senders only: they carry the click to the later pages and visits where the\n // URL no longer does. `_fbc`, `_rdt_cid`, `_gcl_*` and `_uetmsclkid` are kept alive\n // server-side (see @shware/analytics/server resolveClickIdCookies); the rest are the pixels'.\n _fbc: parsed._fbc || undefined,\n _fbp: parsed._fbp || undefined,\n _gcl_aw: parsed._gcl_aw || undefined,\n _gcl_gb: parsed._gcl_gb || undefined,\n _uetmsclkid: parsed._uetmsclkid || undefined,\n _rdt_cid: parsed._rdt_cid || undefined,\n _rdt_uuid: parsed._rdt_uuid || undefined,\n // The Insight Tag's cookie is itself named `li_fat_id`; renamed so it cannot pass for the\n // URL parameter.\n _li_fat_id: parsed.li_fat_id || undefined,\n __oppref: parsed.__oppref || undefined,\n __obref: parsed.__obref || undefined,\n // utm params\n utm_source: link?.utm_source ?? params.get('utm_source') ?? undefined,\n utm_medium: link?.utm_medium ?? params.get('utm_medium') ?? undefined,\n utm_campaign: link?.utm_campaign ?? params.get('utm_campaign') ?? undefined,\n utm_term: link?.utm_term ?? params.get('utm_term') ?? undefined,\n utm_content: link?.utm_content ?? params.get('utm_content') ?? undefined,\n utm_id: link?.utm_id ?? params.get('utm_id') ?? undefined,\n utm_source_platform:\n link?.utm_source_platform ?? params.get('utm_source_platform') ?? undefined,\n utm_creative_format:\n link?.utm_creative_format ?? params.get('utm_creative_format') ?? undefined,\n utm_marketing_tactic:\n link?.utm_marketing_tactic ?? params.get('utm_marketing_tactic') ?? undefined,\n };\n\n cache.tags = tags;\n return tags;\n}\n\nconst map = new Map<string, string>();\n\nexport const storage: Storage = {\n getItem: (key) => {\n try {\n return localStorage.getItem(key);\n } catch {\n console.error('localStorage is not available');\n return map.get(key) ?? null;\n }\n },\n setItem: (key, value) => {\n try {\n localStorage.setItem(key, value);\n } catch {\n console.error('localStorage is not available');\n map.set(key, value);\n }\n },\n};\n"],"mappings":";;;;;;;;;;;AAWA,SAAS,aAAqB;CAC5B,OAAQ,OAA2B,aAAa,OAAO,WAAW,KAAA,GAAIA,KAAAA,GAAAA,CAAO;AAC/E;AAEA,SAAgB,cAAc;CAC5B,MAAM,SAASC,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,SAAS;CACpD,IAAI,QAAQ,OAAO;CACnB,MAAM,KAAK,WAAW;CACtB,oBAAA,OAAO,QAAQ,QAAQA,0BAAAA,KAAK,WAAW,EAAE;CACzC,OAAO;AACT;;;;;;;;;;;;;;;;;;;AAoBA,IAAI;AAEJ,SAAS,cAAc;CACrB,MAAM,OAAO,OAAO,SAAS;CAC7B,MAAM,OAAOC,qBAAAA,WAAW,OAAO,SAAS,UAAU,OAAO,SAAS,MAAM;CACxE,IAAI,UAAU,SAAS,MAAM;EAG3B,SAAS,OAAO;EAChB,OAAO;CACT;CACA,MAAM,WAAW,WAAW,SAAS,OAAO,SAAS,YAAY,KAAA;CACjE,WAAW;EAAE;EAAM,IAAI,WAAW;EAAG;EAAM;CAAS;CACpD,OAAO;AACT;;AAGA,SAAgB,kBAAsC;CACpD,OAAO,YAAY,CAAC,CAAC;AACvB;AAEA,MAAM,wBAAQ,IAAI,IAAkC;;;;;;AAOpD,SAAS,cAAc,IAAY;CACjC,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ageKey","getLink","Bowser","parseCookie"],"sources":["../../src/web/index.ts"],"sourcesContent":["import Bowser from 'bowser';\nimport { parseCookie } from 'cookie';\nimport { v4 as uuidv4 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { type Link, getLink } from '../link/index';\nimport { type Storage, cache, config } from '../setup/index';\nimport type { TrackTags } from '../track/types';\nimport { redactUrl } from '../utils/redact-url';\nimport { getPageKey } from './page-key';\n\n// lib.dom types `crypto.randomUUID` as always present, but it is missing in insecure contexts\n// and older browsers, so probe it before use.\nfunction randomUUID(): string {\n return (crypto as Partial<Crypto>).randomUUID ? crypto.randomUUID() : uuidv4();\n}\n\nexport function getDeviceId() {\n const cached = config.storage.getItem(keys.device_id);\n if (cached) return cached;\n const id = randomUUID();\n config.storage.setItem(keys.device_id, id);\n return id;\n}\n\n/**\n * The current page load, keyed by the page it was loaded at. A module variable and nothing more\n * persistent: the id must die with the page (a reload is a new page load, and storage would\n * carry it over — or, shared across tabs, let two pages overwrite each other's).\n *\n * Keyed by `getPageKey` because that is what the SDK's own `page_view` fires on (see\n * `useWebAnalytics`): the id exists to link an event to the `page_view` of the page it happened\n * on, so it must rotate exactly when a `page_view` is sent — path or query change, yes; hash\n * change or tracking-parameter cleanup, no.\n *\n * `referrer` is the page's referrer as GA4 reports it in a single page app: `document.referrer`\n * for the document's first page, and the previous page's URL after an in-app navigation. The\n * browser never updates `document.referrer` on a `pushState`, so read alone it would name the\n * site the visit came from on every later page — and a session opened there, after 30 minutes\n * idle, would count that site as a second visit from it. With the previous page as its referrer,\n * that session's referrer is the product's own host: no touch, a direct session, which the\n * attribution view then credits to the touch before it.\n */\nlet pageLoad: { page: string; id: string; href: string; referrer: string | undefined } | undefined;\n\nfunction currentPage() {\n const href = redactUrl(window.location.href);\n const page = getPageKey(window.location.pathname, window.location.search);\n if (pageLoad?.page === page) {\n // The same page, its URL maybe cleaned of tracking parameters since: the next page's\n // referrer is the URL as it last was, as the browser's own would be.\n pageLoad.href = href;\n return pageLoad;\n }\n const referrer = pageLoad ? pageLoad.href : redactUrl(document.referrer) || undefined;\n pageLoad = { page, id: randomUUID(), href, referrer };\n return pageLoad;\n}\n\n/**\n * The current page's URL as reported, without its credential parameters (`redactUrl`), so\n * `page_location` never carries an OAuth code or a checkout session id.\n */\nexport function getPageLocation(): string {\n return redactUrl(window.location.href);\n}\n\n/** The current page's referrer, without its credential parameters: see `pageLoad`. */\nexport function getPageReferrer(): string | undefined {\n return currentPage().referrer;\n}\n\nconst links = new Map<string, Promise<Link | null>>();\n\n/**\n * `getTags` runs once per event now, and the link a `?s=` id points at cannot change while the\n * page is open, so an uncached lookup would put an identical request on the wire for every\n * event the page sends.\n */\nfunction getCachedLink(id: string) {\n const cached = links.get(id);\n if (cached) return cached;\n const link = getLink(id).then((result) => {\n // A lookup that came back empty must not stick for the lifetime of the page. `getLink`\n // answers null for a network failure as well as for a link that does not exist, and losing\n // the link's utm params for every later event costs more than repeating a rare request.\n if (!result) links.delete(id);\n return result;\n });\n links.set(id, link);\n return link;\n}\n\n/** The user agent cannot change while the page is open, so it is parsed once. */\nlet parser: ReturnType<typeof Bowser.getParser> | undefined;\n\nexport async function getTags() {\n // Read the page before the first await: `getTags` runs when the event happens, and a single\n // page app can navigate while the link lookup below is still in flight.\n const page_location = redactUrl(window.location.href);\n const { id: page_load_id, referrer: page_referrer } = currentPage();\n const page_title = document.title;\n\n parser ??= Bowser.getParser(window.navigator.userAgent);\n const params = new URLSearchParams(window.location.search);\n const os = parser.getOS();\n const browser = parser.getBrowser();\n const platform = parser.getPlatform();\n const parsed = parseCookie(document.cookie);\n\n const linkId = params.get('s');\n const link = linkId ? await getCachedLink(linkId) : null;\n\n const tags: TrackTags = {\n os: `${os.name} ${os.version}`,\n os_name: os.name,\n os_version: os.version,\n browser: `${browser.name} ${browser.version}`,\n browser_name: browser.name,\n browser_version: browser.version,\n device: platform.model,\n device_id: getDeviceId(),\n device_type: platform.type,\n device_vendor: platform.vendor,\n device_pixel_ratio: window.devicePixelRatio,\n screen_width: window.screen.width,\n screen_height: window.screen.height,\n screen_resolution: `${window.screen.width}x${window.screen.height}`,\n webdriver: navigator.webdriver || undefined,\n release: config.release,\n language: navigator.language,\n time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n page_location,\n page_referrer,\n page_title,\n page_load_id,\n // Ad click ids from the URL, each under its parameter's name: this page's click, which\n // names the visit's channel (`CLICK_ID_CHANNELS`). Never filled from a cookie — a cookie\n // outlives the click; the cookies go below under their own names.\n fbclid: params.get('fbclid') ?? undefined,\n ad_id: params.get('ad_id') ?? undefined,\n ad_name: params.get('ad_name') ?? undefined,\n adset_id: params.get('adset_id') ?? undefined,\n adset_name: params.get('adset_name') ?? undefined,\n campaign_id: params.get('campaign_id') ?? undefined,\n campaign_name: params.get('campaign_name') ?? undefined,\n placement: params.get('placement') ?? undefined,\n gclid: params.get('gclid') ?? undefined,\n gclsrc: params.get('gclsrc') ?? undefined,\n gad_source: params.get('gad_source') ?? undefined,\n gad_campaignid: params.get('gad_campaignid') ?? undefined,\n network: params.get('network') ?? undefined,\n match_type: params.get('match_type') ?? undefined,\n wbraid: params.get('wbraid') ?? undefined,\n gbraid: params.get('gbraid') ?? undefined,\n dclid: params.get('dclid') ?? undefined,\n msclkid: params.get('msclkid') ?? undefined,\n rdt_cid: params.get('rdt_cid') ?? undefined,\n li_fat_id: params.get('li_fat_id') ?? undefined,\n oppref: params.get('oppref') ?? undefined,\n ko_click_id: params.get('ko_click_id') ?? undefined,\n // Snapchat appends `ScCid`, and URL parameters are case-sensitive.\n ScCid: params.get('ScCid') ?? undefined,\n ttclid: params.get('ttclid') ?? undefined,\n twclid: params.get('twclid') ?? undefined,\n yclid: params.get('yclid') ?? undefined,\n epik: params.get('epik') ?? undefined,\n // The ad platforms' first-party cookies, raw and under the cookie's own name, for the\n // conversion senders only: they carry the click to the later pages and visits where the\n // URL no longer does. `_fbc`, `_rdt_cid`, `_gcl_*` and `_uetmsclkid` are kept alive\n // server-side (see @shware/analytics/server resolveClickIdCookies); the rest are the pixels'.\n _fbc: parsed._fbc || undefined,\n _fbp: parsed._fbp || undefined,\n _gcl_aw: parsed._gcl_aw || undefined,\n _gcl_gb: parsed._gcl_gb || undefined,\n _uetmsclkid: parsed._uetmsclkid || undefined,\n _rdt_cid: parsed._rdt_cid || undefined,\n _rdt_uuid: parsed._rdt_uuid || undefined,\n // The Insight Tag's cookie is itself named `li_fat_id`; renamed so it cannot pass for the\n // URL parameter.\n _li_fat_id: parsed.li_fat_id || undefined,\n __oppref: parsed.__oppref || undefined,\n __obref: parsed.__obref || undefined,\n // utm params\n utm_source: link?.utm_source ?? params.get('utm_source') ?? undefined,\n utm_medium: link?.utm_medium ?? params.get('utm_medium') ?? undefined,\n utm_campaign: link?.utm_campaign ?? params.get('utm_campaign') ?? undefined,\n utm_term: link?.utm_term ?? params.get('utm_term') ?? undefined,\n utm_content: link?.utm_content ?? params.get('utm_content') ?? undefined,\n utm_id: link?.utm_id ?? params.get('utm_id') ?? undefined,\n utm_source_platform:\n link?.utm_source_platform ?? params.get('utm_source_platform') ?? undefined,\n utm_creative_format:\n link?.utm_creative_format ?? params.get('utm_creative_format') ?? undefined,\n utm_marketing_tactic:\n link?.utm_marketing_tactic ?? params.get('utm_marketing_tactic') ?? undefined,\n };\n\n cache.tags = tags;\n return tags;\n}\n\nconst map = new Map<string, string>();\n\nexport const storage: Storage = {\n getItem: (key) => {\n try {\n return localStorage.getItem(key);\n } catch {\n console.error('localStorage is not available');\n return map.get(key) ?? null;\n }\n },\n setItem: (key, value) => {\n try {\n localStorage.setItem(key, value);\n } catch {\n console.error('localStorage is not available');\n map.set(key, value);\n }\n },\n};\n"],"mappings":";;;;;;;;;;;;AAYA,SAAS,aAAqB;CAC5B,OAAQ,OAA2B,aAAa,OAAO,WAAW,KAAA,GAAIA,KAAAA,GAAAA,CAAO;AAC/E;AAEA,SAAgB,cAAc;CAC5B,MAAM,SAASC,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,SAAS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AAA;EACtD,aAAa,MAAM,eAAe,OAAO,IAAI,aAAa,KAAK,KAAA;EAC/D,QAAQ,MAAM,UAAU,OAAO,IAAI,QAAQ,KAAK,KAAA;EAChD,qBACE,MAAM,uBAAuB,OAAO,IAAI,qBAAqB,KAAK,KAAA;EACpE,qBACE,MAAM,uBAAuB,OAAO,IAAI,qBAAqB,KAAK,KAAA;EACpE,sBACE,MAAM,wBAAwB,OAAO,IAAI,sBAAsB,KAAK,KAAA;CACxE;CAEA,oBAAA,MAAM,OAAO;CACb,OAAO;AACT;AAEA,MAAM,sBAAM,IAAI,IAAoB;AAEpC,MAAa,UAAmB;CAC9B,UAAU,QAAQ;EAChB,IAAI;GACF,OAAO,aAAa,QAAQ,GAAG;EACjC,QAAQ;GACN,QAAQ,MAAM,+BAA+B;GAC7C,OAAO,IAAI,IAAI,GAAG,KAAK;EACzB;CACF;CACA,UAAU,KAAK,UAAU;EACvB,IAAI;GACF,aAAa,QAAQ,KAAK,KAAK;EACjC,QAAQ;GACN,QAAQ,MAAM,+BAA+B;GAC7C,IAAI,IAAI,KAAK,KAAK;EACpB;CACF;AACF"}
@@ -2,7 +2,12 @@ import { TrackTags } from "../track/types.cjs";
2
2
  import { Storage } from "../setup/index.cjs";
3
3
  //#region src/web/index.d.ts
4
4
  export declare function getDeviceId(): string;
5
- /** The current page's referrer: see `pageLoad`. */
5
+ /**
6
+ * The current page's URL as reported, without its credential parameters (`redactUrl`), so
7
+ * `page_location` never carries an OAuth code or a checkout session id.
8
+ */
9
+ export declare function getPageLocation(): string;
10
+ /** The current page's referrer, without its credential parameters: see `pageLoad`. */
6
11
  export declare function getPageReferrer(): string | undefined;
7
12
  export declare function getTags(): Promise<TrackTags>;
8
13
  export declare const storage: Storage;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/web/index.ts"],"mappings":";;;wBAegB;;wBA2CA;wBA4BM,WAAO,QAAA;qBA4GhB,SAAS"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/web/index.ts"],"mappings":";;;wBAgBgB;;;;;wBA8CA;;wBAKA;wBA4BM,WAAO,QAAA;qBA4GhB,SAAS"}
@@ -2,7 +2,12 @@ import { TrackTags } from "../track/types.mjs";
2
2
  import { Storage } from "../setup/index.mjs";
3
3
  //#region src/web/index.d.ts
4
4
  export declare function getDeviceId(): string;
5
- /** The current page's referrer: see `pageLoad`. */
5
+ /**
6
+ * The current page's URL as reported, without its credential parameters (`redactUrl`), so
7
+ * `page_location` never carries an OAuth code or a checkout session id.
8
+ */
9
+ export declare function getPageLocation(): string;
10
+ /** The current page's referrer, without its credential parameters: see `pageLoad`. */
6
11
  export declare function getPageReferrer(): string | undefined;
7
12
  export declare function getTags(): Promise<TrackTags>;
8
13
  export declare const storage: Storage;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/web/index.ts"],"mappings":";;;wBAegB;;wBA2CA;wBA4BM,WAAO,QAAA;qBA4GhB,SAAS"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/web/index.ts"],"mappings":";;;wBAgBgB;;;;;wBA8CA;;wBAKA;wBA4BM,WAAO,QAAA;qBA4GhB,SAAS"}
@@ -3,6 +3,7 @@ import { cache, config } from "../setup/index.mjs";
3
3
  import { keys } from "../constants/storage.mjs";
4
4
  import { getLink } from "../link/index.mjs";
5
5
  import { require_es5 } from "../node_modules/.pnpm/bowser@2.14.1/node_modules/bowser/es5.mjs";
6
+ import { redactUrl } from "../utils/redact-url.mjs";
6
7
  import { getPageKey } from "./page-key.mjs";
7
8
  import { v4 } from "uuid";
8
9
  import { parseCookie } from "cookie";
@@ -38,13 +39,13 @@ function getDeviceId() {
38
39
  */
39
40
  let pageLoad;
40
41
  function currentPage() {
41
- const href = window.location.href;
42
+ const href = redactUrl(window.location.href);
42
43
  const page = getPageKey(window.location.pathname, window.location.search);
43
44
  if (pageLoad?.page === page) {
44
45
  pageLoad.href = href;
45
46
  return pageLoad;
46
47
  }
47
- const referrer = pageLoad ? pageLoad.href : document.referrer || void 0;
48
+ const referrer = pageLoad ? pageLoad.href : redactUrl(document.referrer) || void 0;
48
49
  pageLoad = {
49
50
  page,
50
51
  id: randomUUID(),
@@ -53,7 +54,14 @@ function currentPage() {
53
54
  };
54
55
  return pageLoad;
55
56
  }
56
- /** The current page's referrer: see `pageLoad`. */
57
+ /**
58
+ * The current page's URL as reported, without its credential parameters (`redactUrl`), so
59
+ * `page_location` never carries an OAuth code or a checkout session id.
60
+ */
61
+ function getPageLocation() {
62
+ return redactUrl(window.location.href);
63
+ }
64
+ /** The current page's referrer, without its credential parameters: see `pageLoad`. */
57
65
  function getPageReferrer() {
58
66
  return currentPage().referrer;
59
67
  }
@@ -76,7 +84,7 @@ function getCachedLink(id) {
76
84
  /** The user agent cannot change while the page is open, so it is parsed once. */
77
85
  let parser;
78
86
  async function getTags() {
79
- const page_location = window.location.href;
87
+ const page_location = redactUrl(window.location.href);
80
88
  const { id: page_load_id, referrer: page_referrer } = currentPage();
81
89
  const page_title = document.title;
82
90
  parser ??= import_es5.default.getParser(window.navigator.userAgent);
@@ -180,6 +188,6 @@ const storage = {
180
188
  }
181
189
  };
182
190
  //#endregion
183
- export { getDeviceId, getPageReferrer, getTags, storage };
191
+ export { getDeviceId, getPageLocation, getPageReferrer, getTags, storage };
184
192
 
185
193
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["uuidv4","Bowser"],"sources":["../../src/web/index.ts"],"sourcesContent":["import Bowser from 'bowser';\nimport { parseCookie } from 'cookie';\nimport { v4 as uuidv4 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { type Link, getLink } from '../link/index';\nimport { type Storage, cache, config } from '../setup/index';\nimport type { TrackTags } from '../track/types';\nimport { getPageKey } from './page-key';\n\n// lib.dom types `crypto.randomUUID` as always present, but it is missing in insecure contexts\n// and older browsers, so probe it before use.\nfunction randomUUID(): string {\n return (crypto as Partial<Crypto>).randomUUID ? crypto.randomUUID() : uuidv4();\n}\n\nexport function getDeviceId() {\n const cached = config.storage.getItem(keys.device_id);\n if (cached) return cached;\n const id = randomUUID();\n config.storage.setItem(keys.device_id, id);\n return id;\n}\n\n/**\n * The current page load, keyed by the page it was loaded at. A module variable and nothing more\n * persistent: the id must die with the page (a reload is a new page load, and storage would\n * carry it over — or, shared across tabs, let two pages overwrite each other's).\n *\n * Keyed by `getPageKey` because that is what the SDK's own `page_view` fires on (see\n * `useWebAnalytics`): the id exists to link an event to the `page_view` of the page it happened\n * on, so it must rotate exactly when a `page_view` is sent — path or query change, yes; hash\n * change or tracking-parameter cleanup, no.\n *\n * `referrer` is the page's referrer as GA4 reports it in a single page app: `document.referrer`\n * for the document's first page, and the previous page's URL after an in-app navigation. The\n * browser never updates `document.referrer` on a `pushState`, so read alone it would name the\n * site the visit came from on every later page — and a session opened there, after 30 minutes\n * idle, would count that site as a second visit from it. With the previous page as its referrer,\n * that session's referrer is the product's own host: no touch, a direct session, which the\n * attribution view then credits to the touch before it.\n */\nlet pageLoad: { page: string; id: string; href: string; referrer: string | undefined } | undefined;\n\nfunction currentPage() {\n const href = window.location.href;\n const page = getPageKey(window.location.pathname, window.location.search);\n if (pageLoad?.page === page) {\n // The same page, its URL maybe cleaned of tracking parameters since: the next page's\n // referrer is the URL as it last was, as the browser's own would be.\n pageLoad.href = href;\n return pageLoad;\n }\n const referrer = pageLoad ? pageLoad.href : document.referrer || undefined;\n pageLoad = { page, id: randomUUID(), href, referrer };\n return pageLoad;\n}\n\n/** The current page's referrer: see `pageLoad`. */\nexport function getPageReferrer(): string | undefined {\n return currentPage().referrer;\n}\n\nconst links = new Map<string, Promise<Link | null>>();\n\n/**\n * `getTags` runs once per event now, and the link a `?s=` id points at cannot change while the\n * page is open, so an uncached lookup would put an identical request on the wire for every\n * event the page sends.\n */\nfunction getCachedLink(id: string) {\n const cached = links.get(id);\n if (cached) return cached;\n const link = getLink(id).then((result) => {\n // A lookup that came back empty must not stick for the lifetime of the page. `getLink`\n // answers null for a network failure as well as for a link that does not exist, and losing\n // the link's utm params for every later event costs more than repeating a rare request.\n if (!result) links.delete(id);\n return result;\n });\n links.set(id, link);\n return link;\n}\n\n/** The user agent cannot change while the page is open, so it is parsed once. */\nlet parser: ReturnType<typeof Bowser.getParser> | undefined;\n\nexport async function getTags() {\n // Read the page before the first await: `getTags` runs when the event happens, and a single\n // page app can navigate while the link lookup below is still in flight.\n const page_location = window.location.href;\n const { id: page_load_id, referrer: page_referrer } = currentPage();\n const page_title = document.title;\n\n parser ??= Bowser.getParser(window.navigator.userAgent);\n const params = new URLSearchParams(window.location.search);\n const os = parser.getOS();\n const browser = parser.getBrowser();\n const platform = parser.getPlatform();\n const parsed = parseCookie(document.cookie);\n\n const linkId = params.get('s');\n const link = linkId ? await getCachedLink(linkId) : null;\n\n const tags: TrackTags = {\n os: `${os.name} ${os.version}`,\n os_name: os.name,\n os_version: os.version,\n browser: `${browser.name} ${browser.version}`,\n browser_name: browser.name,\n browser_version: browser.version,\n device: platform.model,\n device_id: getDeviceId(),\n device_type: platform.type,\n device_vendor: platform.vendor,\n device_pixel_ratio: window.devicePixelRatio,\n screen_width: window.screen.width,\n screen_height: window.screen.height,\n screen_resolution: `${window.screen.width}x${window.screen.height}`,\n webdriver: navigator.webdriver || undefined,\n release: config.release,\n language: navigator.language,\n time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n page_location,\n page_referrer,\n page_title,\n page_load_id,\n // Ad click ids from the URL, each under its parameter's name: this page's click, which\n // names the visit's channel (`CLICK_ID_CHANNELS`). Never filled from a cookie — a cookie\n // outlives the click; the cookies go below under their own names.\n fbclid: params.get('fbclid') ?? undefined,\n ad_id: params.get('ad_id') ?? undefined,\n ad_name: params.get('ad_name') ?? undefined,\n adset_id: params.get('adset_id') ?? undefined,\n adset_name: params.get('adset_name') ?? undefined,\n campaign_id: params.get('campaign_id') ?? undefined,\n campaign_name: params.get('campaign_name') ?? undefined,\n placement: params.get('placement') ?? undefined,\n gclid: params.get('gclid') ?? undefined,\n gclsrc: params.get('gclsrc') ?? undefined,\n gad_source: params.get('gad_source') ?? undefined,\n gad_campaignid: params.get('gad_campaignid') ?? undefined,\n network: params.get('network') ?? undefined,\n match_type: params.get('match_type') ?? undefined,\n wbraid: params.get('wbraid') ?? undefined,\n gbraid: params.get('gbraid') ?? undefined,\n dclid: params.get('dclid') ?? undefined,\n msclkid: params.get('msclkid') ?? undefined,\n rdt_cid: params.get('rdt_cid') ?? undefined,\n li_fat_id: params.get('li_fat_id') ?? undefined,\n oppref: params.get('oppref') ?? undefined,\n ko_click_id: params.get('ko_click_id') ?? undefined,\n // Snapchat appends `ScCid`, and URL parameters are case-sensitive.\n ScCid: params.get('ScCid') ?? undefined,\n ttclid: params.get('ttclid') ?? undefined,\n twclid: params.get('twclid') ?? undefined,\n yclid: params.get('yclid') ?? undefined,\n epik: params.get('epik') ?? undefined,\n // The ad platforms' first-party cookies, raw and under the cookie's own name, for the\n // conversion senders only: they carry the click to the later pages and visits where the\n // URL no longer does. `_fbc`, `_rdt_cid`, `_gcl_*` and `_uetmsclkid` are kept alive\n // server-side (see @shware/analytics/server resolveClickIdCookies); the rest are the pixels'.\n _fbc: parsed._fbc || undefined,\n _fbp: parsed._fbp || undefined,\n _gcl_aw: parsed._gcl_aw || undefined,\n _gcl_gb: parsed._gcl_gb || undefined,\n _uetmsclkid: parsed._uetmsclkid || undefined,\n _rdt_cid: parsed._rdt_cid || undefined,\n _rdt_uuid: parsed._rdt_uuid || undefined,\n // The Insight Tag's cookie is itself named `li_fat_id`; renamed so it cannot pass for the\n // URL parameter.\n _li_fat_id: parsed.li_fat_id || undefined,\n __oppref: parsed.__oppref || undefined,\n __obref: parsed.__obref || undefined,\n // utm params\n utm_source: link?.utm_source ?? params.get('utm_source') ?? undefined,\n utm_medium: link?.utm_medium ?? params.get('utm_medium') ?? undefined,\n utm_campaign: link?.utm_campaign ?? params.get('utm_campaign') ?? undefined,\n utm_term: link?.utm_term ?? params.get('utm_term') ?? undefined,\n utm_content: link?.utm_content ?? params.get('utm_content') ?? undefined,\n utm_id: link?.utm_id ?? params.get('utm_id') ?? undefined,\n utm_source_platform:\n link?.utm_source_platform ?? params.get('utm_source_platform') ?? undefined,\n utm_creative_format:\n link?.utm_creative_format ?? params.get('utm_creative_format') ?? undefined,\n utm_marketing_tactic:\n link?.utm_marketing_tactic ?? params.get('utm_marketing_tactic') ?? undefined,\n };\n\n cache.tags = tags;\n return tags;\n}\n\nconst map = new Map<string, string>();\n\nexport const storage: Storage = {\n getItem: (key) => {\n try {\n return localStorage.getItem(key);\n } catch {\n console.error('localStorage is not available');\n return map.get(key) ?? null;\n }\n },\n setItem: (key, value) => {\n try {\n localStorage.setItem(key, value);\n } catch {\n console.error('localStorage is not available');\n map.set(key, value);\n }\n },\n};\n"],"mappings":";;;;;;;;;;AAWA,SAAS,aAAqB;CAC5B,OAAQ,OAA2B,aAAa,OAAO,WAAW,IAAIA,GAAO;AAC/E;AAEA,SAAgB,cAAc;CAC5B,MAAM,SAAS,OAAO,QAAQ,QAAQ,KAAK,SAAS;CACpD,IAAI,QAAQ,OAAO;CACnB,MAAM,KAAK,WAAW;CACtB,OAAO,QAAQ,QAAQ,KAAK,WAAW,EAAE;CACzC,OAAO;AACT;;;;;;;;;;;;;;;;;;;AAoBA,IAAI;AAEJ,SAAS,cAAc;CACrB,MAAM,OAAO,OAAO,SAAS;CAC7B,MAAM,OAAO,WAAW,OAAO,SAAS,UAAU,OAAO,SAAS,MAAM;CACxE,IAAI,UAAU,SAAS,MAAM;EAG3B,SAAS,OAAO;EAChB,OAAO;CACT;CACA,MAAM,WAAW,WAAW,SAAS,OAAO,SAAS,YAAY,KAAA;CACjE,WAAW;EAAE;EAAM,IAAI,WAAW;EAAG;EAAM;CAAS;CACpD,OAAO;AACT;;AAGA,SAAgB,kBAAsC;CACpD,OAAO,YAAY,CAAC,CAAC;AACvB;AAEA,MAAM,wBAAQ,IAAI,IAAkC;;;;;;AAOpD,SAAS,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ser from 'bowser';\nimport { parseCookie } from 'cookie';\nimport { v4 as uuidv4 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { type Link, getLink } from '../link/index';\nimport { type Storage, cache, config } from '../setup/index';\nimport type { TrackTags } from '../track/types';\nimport { redactUrl } from '../utils/redact-url';\nimport { getPageKey } from './page-key';\n\n// lib.dom types `crypto.randomUUID` as always present, but it is missing in insecure contexts\n// and older browsers, so probe it before use.\nfunction randomUUID(): string {\n return (crypto as Partial<Crypto>).randomUUID ? crypto.randomUUID() : uuidv4();\n}\n\nexport function getDeviceId() {\n const cached = config.storage.getItem(keys.device_id);\n if (cached) return cached;\n const id = randomUUID();\n config.storage.setItem(keys.device_id, id);\n return id;\n}\n\n/**\n * The current page load, keyed by the page it was loaded at. A module variable and nothing more\n * persistent: the id must die with the page (a reload is a new page load, and storage would\n * carry it over — or, shared across tabs, let two pages overwrite each other's).\n *\n * Keyed by `getPageKey` because that is what the SDK's own `page_view` fires on (see\n * `useWebAnalytics`): the id exists to link an event to the `page_view` of the page it happened\n * on, so it must rotate exactly when a `page_view` is sent — path or query change, yes; hash\n * change or tracking-parameter cleanup, no.\n *\n * `referrer` is the page's referrer as GA4 reports it in a single page app: `document.referrer`\n * for the document's first page, and the previous page's URL after an in-app navigation. The\n * browser never updates `document.referrer` on a `pushState`, so read alone it would name the\n * site the visit came from on every later page — and a session opened there, after 30 minutes\n * idle, would count that site as a second visit from it. With the previous page as its referrer,\n * that session's referrer is the product's own host: no touch, a direct session, which the\n * attribution view then credits to the touch before it.\n */\nlet pageLoad: { page: string; id: string; href: string; referrer: string | undefined } | undefined;\n\nfunction currentPage() {\n const href = redactUrl(window.location.href);\n const page = getPageKey(window.location.pathname, window.location.search);\n if (pageLoad?.page === page) {\n // The same page, its URL maybe cleaned of tracking parameters since: the next page's\n // referrer is the URL as it last was, as the browser's own would be.\n pageLoad.href = href;\n return pageLoad;\n }\n const referrer = pageLoad ? pageLoad.href : redactUrl(document.referrer) || undefined;\n pageLoad = { page, id: randomUUID(), href, referrer };\n return pageLoad;\n}\n\n/**\n * The current page's URL as reported, without its credential parameters (`redactUrl`), so\n * `page_location` never carries an OAuth code or a checkout session id.\n */\nexport function getPageLocation(): string {\n return redactUrl(window.location.href);\n}\n\n/** The current page's referrer, without its credential parameters: see `pageLoad`. */\nexport function getPageReferrer(): string | undefined {\n return currentPage().referrer;\n}\n\nconst links = new Map<string, Promise<Link | null>>();\n\n/**\n * `getTags` runs once per event now, and the link a `?s=` id points at cannot change while the\n * page is open, so an uncached lookup would put an identical request on the wire for every\n * event the page sends.\n */\nfunction getCachedLink(id: string) {\n const cached = links.get(id);\n if (cached) return cached;\n const link = getLink(id).then((result) => {\n // A lookup that came back empty must not stick for the lifetime of the page. `getLink`\n // answers null for a network failure as well as for a link that does not exist, and losing\n // the link's utm params for every later event costs more than repeating a rare request.\n if (!result) links.delete(id);\n return result;\n });\n links.set(id, link);\n return link;\n}\n\n/** The user agent cannot change while the page is open, so it is parsed once. */\nlet parser: ReturnType<typeof Bowser.getParser> | undefined;\n\nexport async function getTags() {\n // Read the page before the first await: `getTags` runs when the event happens, and a single\n // page app can navigate while the link lookup below is still in flight.\n const page_location = redactUrl(window.location.href);\n const { id: page_load_id, referrer: page_referrer } = currentPage();\n const page_title = document.title;\n\n parser ??= Bowser.getParser(window.navigator.userAgent);\n const params = new URLSearchParams(window.location.search);\n const os = parser.getOS();\n const browser = parser.getBrowser();\n const platform = parser.getPlatform();\n const parsed = parseCookie(document.cookie);\n\n const linkId = params.get('s');\n const link = linkId ? await getCachedLink(linkId) : null;\n\n const tags: TrackTags = {\n os: `${os.name} ${os.version}`,\n os_name: os.name,\n os_version: os.version,\n browser: `${browser.name} ${browser.version}`,\n browser_name: browser.name,\n browser_version: browser.version,\n device: platform.model,\n device_id: getDeviceId(),\n device_type: platform.type,\n device_vendor: platform.vendor,\n device_pixel_ratio: window.devicePixelRatio,\n screen_width: window.screen.width,\n screen_height: window.screen.height,\n screen_resolution: `${window.screen.width}x${window.screen.height}`,\n webdriver: navigator.webdriver || undefined,\n release: config.release,\n language: navigator.language,\n time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n page_location,\n page_referrer,\n page_title,\n page_load_id,\n // Ad click ids from the URL, each under its parameter's name: this page's click, which\n // names the visit's channel (`CLICK_ID_CHANNELS`). Never filled from a cookie — a cookie\n // outlives the click; the cookies go below under their own names.\n fbclid: params.get('fbclid') ?? undefined,\n ad_id: params.get('ad_id') ?? undefined,\n ad_name: params.get('ad_name') ?? undefined,\n adset_id: params.get('adset_id') ?? undefined,\n adset_name: params.get('adset_name') ?? undefined,\n campaign_id: params.get('campaign_id') ?? undefined,\n campaign_name: params.get('campaign_name') ?? undefined,\n placement: params.get('placement') ?? undefined,\n gclid: params.get('gclid') ?? undefined,\n gclsrc: params.get('gclsrc') ?? undefined,\n gad_source: params.get('gad_source') ?? undefined,\n gad_campaignid: params.get('gad_campaignid') ?? undefined,\n network: params.get('network') ?? undefined,\n match_type: params.get('match_type') ?? undefined,\n wbraid: params.get('wbraid') ?? undefined,\n gbraid: params.get('gbraid') ?? undefined,\n dclid: params.get('dclid') ?? undefined,\n msclkid: params.get('msclkid') ?? undefined,\n rdt_cid: params.get('rdt_cid') ?? undefined,\n li_fat_id: params.get('li_fat_id') ?? undefined,\n oppref: params.get('oppref') ?? undefined,\n ko_click_id: params.get('ko_click_id') ?? undefined,\n // Snapchat appends `ScCid`, and URL parameters are case-sensitive.\n ScCid: params.get('ScCid') ?? undefined,\n ttclid: params.get('ttclid') ?? undefined,\n twclid: params.get('twclid') ?? undefined,\n yclid: params.get('yclid') ?? undefined,\n epik: params.get('epik') ?? undefined,\n // The ad platforms' first-party cookies, raw and under the cookie's own name, for the\n // conversion senders only: they carry the click to the later pages and visits where the\n // URL no longer does. `_fbc`, `_rdt_cid`, `_gcl_*` and `_uetmsclkid` are kept alive\n // server-side (see @shware/analytics/server resolveClickIdCookies); the rest are the pixels'.\n _fbc: parsed._fbc || undefined,\n _fbp: parsed._fbp || undefined,\n _gcl_aw: parsed._gcl_aw || undefined,\n _gcl_gb: parsed._gcl_gb || undefined,\n _uetmsclkid: parsed._uetmsclkid || undefined,\n _rdt_cid: parsed._rdt_cid || undefined,\n _rdt_uuid: parsed._rdt_uuid || undefined,\n // The Insight Tag's cookie is itself named `li_fat_id`; renamed so it cannot pass for the\n // URL parameter.\n _li_fat_id: parsed.li_fat_id || undefined,\n __oppref: parsed.__oppref || undefined,\n __obref: parsed.__obref || undefined,\n // utm params\n utm_source: link?.utm_source ?? params.get('utm_source') ?? undefined,\n utm_medium: link?.utm_medium ?? params.get('utm_medium') ?? undefined,\n utm_campaign: link?.utm_campaign ?? params.get('utm_campaign') ?? undefined,\n utm_term: link?.utm_term ?? params.get('utm_term') ?? undefined,\n utm_content: link?.utm_content ?? params.get('utm_content') ?? undefined,\n utm_id: link?.utm_id ?? params.get('utm_id') ?? undefined,\n utm_source_platform:\n link?.utm_source_platform ?? params.get('utm_source_platform') ?? undefined,\n utm_creative_format:\n link?.utm_creative_format ?? params.get('utm_creative_format') ?? undefined,\n utm_marketing_tactic:\n link?.utm_marketing_tactic ?? params.get('utm_marketing_tactic') ?? undefined,\n };\n\n cache.tags = tags;\n return tags;\n}\n\nconst map = new Map<string, string>();\n\nexport const storage: Storage = {\n getItem: (key) => {\n try {\n return localStorage.getItem(key);\n } catch {\n console.error('localStorage is not available');\n return map.get(key) ?? null;\n }\n },\n setItem: (key, value) => {\n try {\n localStorage.setItem(key, value);\n } catch {\n console.error('localStorage is not available');\n map.set(key, value);\n }\n },\n};\n"],"mappings":";;;;;;;;;;;AAYA,SAAS,aAAqB;CAC5B,OAAQ,OAA2B,aAAa,OAAO,WAAW,IAAIA,GAAO;AAC/E;AAEA,SAAgB,cAAc;CAC5B,MAAM,SAAS,OAAO,QAAQ,QAAQ,KAAK,SAAS;CACpD,IAAI,QAAQ,OAAO;CACnB,MAAM,KAAK,WAAW;CACtB,OAAO,QAAQ,QAAQ,KAAK,WAAW,EAAE;CACz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,OAAO,IAAI,qBAAqB,KAAK,KAAA;EACpE,sBACE,MAAM,wBAAwB,OAAO,IAAI,sBAAsB,KAAK,KAAA;CACxE;CAEA,MAAM,OAAO;CACb,OAAO;AACT;AAEA,MAAM,sBAAM,IAAI,IAAoB;AAEpC,MAAa,UAAmB;CAC9B,UAAU,QAAQ;EAChB,IAAI;GACF,OAAO,aAAa,QAAQ,GAAG;EACjC,QAAQ;GACN,QAAQ,MAAM,+BAA+B;GAC7C,OAAO,IAAI,IAAI,GAAG,KAAK;EACzB;CACF;CACA,UAAU,KAAK,UAAU;EACvB,IAAI;GACF,aAAa,QAAQ,KAAK,KAAK;EACjC,QAAQ;GACN,QAAQ,MAAM,+BAA+B;GAC7C,IAAI,IAAI,KAAK,KAAK;EACpB;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shware/analytics",
3
- "version": "13.0.2",
3
+ "version": "13.0.3",
4
4
  "private": false,
5
5
  "repository": {
6
6
  "type": "git",