@sheeptrack/web 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -2
- package/dist/consent.js +23 -0
- package/dist/esm/consent.js +23 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/replay.js +53 -0
- package/dist/replay.js +53 -0
- package/dist/sheeptrack.js +2 -0
- package/dist/types/autocapture.d.ts +9 -0
- package/dist/types/consent.d.ts +3 -0
- package/dist/types/ctx.d.ts +29 -0
- package/dist/types/debug.d.ts +17 -0
- package/dist/types/flags.d.ts +21 -0
- package/dist/types/iife.d.ts +1 -0
- package/dist/types/index.d.ts +42 -0
- package/dist/types/replay.d.ts +2 -0
- package/dist/types/util.d.ts +15 -0
- package/package.json +37 -3
package/README.md
CHANGED
|
@@ -1,3 +1,62 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sheeptrack/web
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Browser SDK for SheepTrack. Core under 10 KB gzip (see `SIZES.md`); the consent banner (`consent.js`) and session replay (`replay.js`) load on demand.
|
|
4
|
+
|
|
5
|
+
## Snippet
|
|
6
|
+
|
|
7
|
+
```html
|
|
8
|
+
<script src="https://YOUR-HOST/sdk/sheeptrack.js" data-key="pk_xxx" data-host="https://YOUR-HOST" async></script>
|
|
9
|
+
<script>window.SheepTrack?.track('signup_clicked')</script>
|
|
10
|
+
```
|
|
11
|
+
Serve `sheeptrack.js`, `replay.js` and `consent.js` from the same folder. Without `data-key`, call `SheepTrack.init('pk_xxx', { host })` yourself.
|
|
12
|
+
|
|
13
|
+
## npm
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { init, track, identify, reset, optIn, optOut, consent, flags, replay } from '@sheeptrack/web';
|
|
17
|
+
|
|
18
|
+
init('pk_xxx', { host: 'https://YOUR-HOST', environment: 'prod', release: '1.4.2' });
|
|
19
|
+
track('plan_selected', { plan: 'pro' });
|
|
20
|
+
identify('user-42', { plan: 'pro' }); // needs the "personalization" consent
|
|
21
|
+
flags.isEnabled('new-checkout'); flags.getVariant('pricing'); flags.onChange(() => render());
|
|
22
|
+
consent.open(); // "Manage my cookies" link
|
|
23
|
+
```
|
|
24
|
+
Mark clickable elements with `data-pt-event="name"`. Mask text with `data-pt-mask`, block an element from replay with `data-pt-block`. Third-party scripts: `<script type="text/plain" data-pt-category="marketing" src="...">` run only after the matching consent.
|
|
25
|
+
|
|
26
|
+
Without consent nothing is written to storage (no cookie, localStorage or sessionStorage); the anonymous id lives in memory.
|
|
27
|
+
|
|
28
|
+
## Astro
|
|
29
|
+
|
|
30
|
+
```astro
|
|
31
|
+
---
|
|
32
|
+
// src/layouts/Base.astro
|
|
33
|
+
---
|
|
34
|
+
<script>
|
|
35
|
+
import { init } from '@sheeptrack/web';
|
|
36
|
+
init(import.meta.env.PUBLIC_ST_KEY, { host: import.meta.env.PUBLIC_ST_HOST });
|
|
37
|
+
</script>
|
|
38
|
+
```
|
|
39
|
+
Astro's `<ClientRouter />` navigations go through the History API, so pageviews are tracked.
|
|
40
|
+
|
|
41
|
+
## Angular
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
// main.ts: init in the browser only (SSR-safe: init is a no-op without window)
|
|
45
|
+
import { init } from '@sheeptrack/web';
|
|
46
|
+
init('pk_xxx', { host: 'https://YOUR-HOST' });
|
|
47
|
+
bootstrapApplication(AppComponent, appConfig);
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## React
|
|
51
|
+
|
|
52
|
+
```tsx
|
|
53
|
+
// src/main.tsx
|
|
54
|
+
import { init, track } from '@sheeptrack/web';
|
|
55
|
+
init(import.meta.env.VITE_ST_KEY, { host: import.meta.env.VITE_ST_HOST });
|
|
56
|
+
// in a component: <button onClick={() => track('cta_click')}>
|
|
57
|
+
// or declaratively: <button data-pt-event="cta_click">
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Commands
|
|
61
|
+
|
|
62
|
+
`pnpm test` (Vitest), `pnpm build`, `pnpm size` (writes `SIZES.md`, fails above 10 KB gzip for the core).
|
package/dist/consent.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
var T=`
|
|
2
|
+
:host{all:initial}
|
|
3
|
+
*{box-sizing:border-box}
|
|
4
|
+
.w{position:fixed;z-index:2147483647;left:0;right:0;bottom:0;display:flex;justify-content:center;padding:12px;pointer-events:none;
|
|
5
|
+
--bg:hsl(210 20% 98%);--fg:hsl(200 18% 20%);--p:#004D40;--pf:#fff;--bd:hsl(200 12% 80%);font-family:var(--f,system-ui,-apple-system,"Segoe UI",sans-serif)}
|
|
6
|
+
.w.d{--bg:hsl(200 18% 16%);--fg:hsl(210 20% 94%);--p:hsl(162 65% 42%);--pf:hsl(200 18% 10%);--bd:hsl(200 12% 30%)}
|
|
7
|
+
.w.bl{justify-content:flex-start}
|
|
8
|
+
.w.c{inset:0;align-items:center;background:rgb(0 0 0/.45);pointer-events:auto}
|
|
9
|
+
.b{pointer-events:auto;width:100%;max-width:720px;max-height:90vh;overflow:auto;background:var(--bg);color:var(--fg);border:1px solid var(--bd);border-radius:12px;padding:20px;box-shadow:0 8px 32px rgb(0 0 0/.2);font-size:15px;line-height:1.5}
|
|
10
|
+
.bl .b{max-width:380px}
|
|
11
|
+
h2{margin:0 0 8px;font-size:17px;font-weight:600}
|
|
12
|
+
p{margin:0 0 16px}
|
|
13
|
+
img{height:28px;margin-bottom:8px;display:block}
|
|
14
|
+
.r{display:flex;gap:8px;flex-wrap:wrap}
|
|
15
|
+
button{flex:1 1 140px;min-height:44px;padding:10px 16px;font:inherit;font-weight:600;cursor:pointer;color:var(--pf);background:var(--p);border:2px solid var(--p);border-radius:8px}
|
|
16
|
+
button:hover{filter:brightness(1.1)}
|
|
17
|
+
button:focus-visible,input:focus-visible,.b:focus-visible{outline:3px solid var(--fg);outline-offset:2px}
|
|
18
|
+
.l{margin:0 0 16px;padding:0;list-style:none;border-top:1px solid var(--bd)}
|
|
19
|
+
.l li{display:flex;gap:12px;align-items:flex-start;padding:10px 0;border-bottom:1px solid var(--bd)}
|
|
20
|
+
.l input{width:22px;height:22px;margin:2px 0 0;accent-color:var(--p);flex:none}
|
|
21
|
+
.l label{display:block;cursor:pointer}.l small{display:block;opacity:.85}
|
|
22
|
+
.l[hidden]{display:none}
|
|
23
|
+
`,j=a=>/^#[0-9a-f]{6}$/i.test(a||""),z=a=>[1,3,5].map(d=>{let p=parseInt(a.slice(d,d+2),16)/255;return p<=.03928?p/12.92:((p+.055)/1.055)**2.4}).reduce((d,p,g)=>d+p*[.2126,.7152,.0722][g],0);function H({cfg:a,current:d,onChoice:p,onClose:g}){let L=(navigator.language||"en").slice(0,2),r=a.texts[L]??a.texts.en??Object.values(a.texts)[0];if(!r)return()=>{};let n=a.style,f=n.position??"bottom",b=document.createElement("div");b.setAttribute("data-pt-consent","");let h=b.attachShadow({mode:"open"}),s=(e,o,t,u)=>{let m=document.createElement(e);return o&&(m.className=o),t!==void 0&&(m.textContent=t),u?.appendChild(m),m},l=s("div","w"+(f==="center"?" c":f==="bottom-left"?" bl":""));!n.primary&&!n.background&&!n.text&&matchMedia("(prefers-color-scheme: dark)").matches&&l.classList.add("d"),n.primary&&(l.style.setProperty("--p",n.primary),l.style.setProperty("--pf",j(n.primary)&&z(n.primary)>.4?"#000":"#fff")),n.background&&l.style.setProperty("--bg",n.background),n.text&&l.style.setProperty("--fg",n.text),n.font&&l.style.setProperty("--f",n.font);let i=s("div","b",void 0,l);if(i.setAttribute("role","dialog"),i.setAttribute("aria-modal",String(f==="center")),i.setAttribute("aria-labelledby","pt-t"),i.setAttribute("aria-describedby","pt-d"),i.tabIndex=-1,n.logo_url&&/^(https:|\/)/.test(n.logo_url)){let e=s("img","",void 0,i);e.src=n.logo_url,e.alt=""}s("h2","",r.title,i).id="pt-t",s("p","",r.body,i).id="pt-d";let w=[],c=s("ul","l",void 0,i);c.hidden=!d;for(let e of a.categories){let o=s("li","",void 0,c),t=s("input","",void 0,o);t.type="checkbox",t.id="pt-"+e.key,t.disabled=e.required||e.key==="necessary",t.checked=t.disabled||!!d?.[e.key];let u=s("label","",void 0,o);u.htmlFor=t.id,s("strong","",r.categories[e.key]?.label??e.key,u),s("small","",r.categories[e.key]?.description??"",u),w.push([e.key,t])}let M=s("div","r",void 0,i),x=(e,o)=>{let t=s("button","",e,M);return t.type="button",t.onclick=o,t},y=e=>k(Object.fromEntries(w.map(([o,t])=>[o,e===null?t.checked:e||t.disabled])));x(r.reject_all,()=>y(!1));let v=x(d?r.save:r.customize,()=>{if(!c.hidden)return y(null);c.hidden=!1,v.textContent=r.save,v.setAttribute("aria-expanded","true")});v.setAttribute("aria-expanded",String(!c.hidden)),x(r.accept_all,()=>y(!0));let S=document.activeElement,E=matchMedia("(prefers-reduced-motion: reduce)").matches,A=!1;function k(e){if(A)return;A=!0,e&&p(e);let o=()=>{b.remove(),S?.focus?.(),g()};if(E||!i.animate)return o();i.animate({opacity:[1,0]},{duration:150,easing:"ease-in"}).onfinish=o}i.addEventListener("keydown",e=>{if(e.key==="Escape")return k();if(e.key!=="Tab"||f!=="center")return;let o=[...h.querySelectorAll("input:not(:disabled),button")],t=o[(o.indexOf(h.activeElement)+(e.shiftKey?-1:1)+o.length)%o.length];e.preventDefault(),t.focus()}),h.append(s("style","",T),l);let C=()=>{document.body.appendChild(b),i.focus({preventScroll:!0}),!E&&i.animate&&i.animate({opacity:[0,1],transform:["translateY(16px)","translateY(0)"]},{duration:250,easing:"ease-out"})};return document.body?C():document.addEventListener("DOMContentLoaded",C,{once:!0}),()=>k()}export{H as show};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
var T=`
|
|
2
|
+
:host{all:initial}
|
|
3
|
+
*{box-sizing:border-box}
|
|
4
|
+
.w{position:fixed;z-index:2147483647;left:0;right:0;bottom:0;display:flex;justify-content:center;padding:12px;pointer-events:none;
|
|
5
|
+
--bg:hsl(210 20% 98%);--fg:hsl(200 18% 20%);--p:#004D40;--pf:#fff;--bd:hsl(200 12% 80%);font-family:var(--f,system-ui,-apple-system,"Segoe UI",sans-serif)}
|
|
6
|
+
.w.d{--bg:hsl(200 18% 16%);--fg:hsl(210 20% 94%);--p:hsl(162 65% 42%);--pf:hsl(200 18% 10%);--bd:hsl(200 12% 30%)}
|
|
7
|
+
.w.bl{justify-content:flex-start}
|
|
8
|
+
.w.c{inset:0;align-items:center;background:rgb(0 0 0/.45);pointer-events:auto}
|
|
9
|
+
.b{pointer-events:auto;width:100%;max-width:720px;max-height:90vh;overflow:auto;background:var(--bg);color:var(--fg);border:1px solid var(--bd);border-radius:12px;padding:20px;box-shadow:0 8px 32px rgb(0 0 0/.2);font-size:15px;line-height:1.5}
|
|
10
|
+
.bl .b{max-width:380px}
|
|
11
|
+
h2{margin:0 0 8px;font-size:17px;font-weight:600}
|
|
12
|
+
p{margin:0 0 16px}
|
|
13
|
+
img{height:28px;margin-bottom:8px;display:block}
|
|
14
|
+
.r{display:flex;gap:8px;flex-wrap:wrap}
|
|
15
|
+
button{flex:1 1 140px;min-height:44px;padding:10px 16px;font:inherit;font-weight:600;cursor:pointer;color:var(--pf);background:var(--p);border:2px solid var(--p);border-radius:8px}
|
|
16
|
+
button:hover{filter:brightness(1.1)}
|
|
17
|
+
button:focus-visible,input:focus-visible,.b:focus-visible{outline:3px solid var(--fg);outline-offset:2px}
|
|
18
|
+
.l{margin:0 0 16px;padding:0;list-style:none;border-top:1px solid var(--bd)}
|
|
19
|
+
.l li{display:flex;gap:12px;align-items:flex-start;padding:10px 0;border-bottom:1px solid var(--bd)}
|
|
20
|
+
.l input{width:22px;height:22px;margin:2px 0 0;accent-color:var(--p);flex:none}
|
|
21
|
+
.l label{display:block;cursor:pointer}.l small{display:block;opacity:.85}
|
|
22
|
+
.l[hidden]{display:none}
|
|
23
|
+
`,j=a=>/^#[0-9a-f]{6}$/i.test(a||""),z=a=>[1,3,5].map(d=>{let p=parseInt(a.slice(d,d+2),16)/255;return p<=.03928?p/12.92:((p+.055)/1.055)**2.4}).reduce((d,p,g)=>d+p*[.2126,.7152,.0722][g],0);function H({cfg:a,current:d,onChoice:p,onClose:g}){let L=(navigator.language||"en").slice(0,2),r=a.texts[L]??a.texts.en??Object.values(a.texts)[0];if(!r)return()=>{};let n=a.style,f=n.position??"bottom",b=document.createElement("div");b.setAttribute("data-pt-consent","");let h=b.attachShadow({mode:"open"}),s=(e,o,t,u)=>{let m=document.createElement(e);return o&&(m.className=o),t!==void 0&&(m.textContent=t),u?.appendChild(m),m},l=s("div","w"+(f==="center"?" c":f==="bottom-left"?" bl":""));!n.primary&&!n.background&&!n.text&&matchMedia("(prefers-color-scheme: dark)").matches&&l.classList.add("d"),n.primary&&(l.style.setProperty("--p",n.primary),l.style.setProperty("--pf",j(n.primary)&&z(n.primary)>.4?"#000":"#fff")),n.background&&l.style.setProperty("--bg",n.background),n.text&&l.style.setProperty("--fg",n.text),n.font&&l.style.setProperty("--f",n.font);let i=s("div","b",void 0,l);if(i.setAttribute("role","dialog"),i.setAttribute("aria-modal",String(f==="center")),i.setAttribute("aria-labelledby","pt-t"),i.setAttribute("aria-describedby","pt-d"),i.tabIndex=-1,n.logo_url&&/^(https:|\/)/.test(n.logo_url)){let e=s("img","",void 0,i);e.src=n.logo_url,e.alt=""}s("h2","",r.title,i).id="pt-t",s("p","",r.body,i).id="pt-d";let w=[],c=s("ul","l",void 0,i);c.hidden=!d;for(let e of a.categories){let o=s("li","",void 0,c),t=s("input","",void 0,o);t.type="checkbox",t.id="pt-"+e.key,t.disabled=e.required||e.key==="necessary",t.checked=t.disabled||!!d?.[e.key];let u=s("label","",void 0,o);u.htmlFor=t.id,s("strong","",r.categories[e.key]?.label??e.key,u),s("small","",r.categories[e.key]?.description??"",u),w.push([e.key,t])}let M=s("div","r",void 0,i),x=(e,o)=>{let t=s("button","",e,M);return t.type="button",t.onclick=o,t},y=e=>k(Object.fromEntries(w.map(([o,t])=>[o,e===null?t.checked:e||t.disabled])));x(r.reject_all,()=>y(!1));let v=x(d?r.save:r.customize,()=>{if(!c.hidden)return y(null);c.hidden=!1,v.textContent=r.save,v.setAttribute("aria-expanded","true")});v.setAttribute("aria-expanded",String(!c.hidden)),x(r.accept_all,()=>y(!0));let S=document.activeElement,E=matchMedia("(prefers-reduced-motion: reduce)").matches,A=!1;function k(e){if(A)return;A=!0,e&&p(e);let o=()=>{b.remove(),S?.focus?.(),g()};if(E||!i.animate)return o();i.animate({opacity:[1,0]},{duration:150,easing:"ease-in"}).onfinish=o}i.addEventListener("keydown",e=>{if(e.key==="Escape")return k();if(e.key!=="Tab"||f!=="center")return;let o=[...h.querySelectorAll("input:not(:disabled),button")],t=o[(o.indexOf(h.activeElement)+(e.shiftKey?-1:1)+o.length)%o.length];e.preventDefault(),t.focus()}),h.append(s("style","",T),l);let C=()=>{document.body.appendChild(b),i.focus({preventScroll:!0}),!E&&i.animate&&i.animate({opacity:[0,1],transform:["translateY(16px)","translateY(0)"]},{duration:250,easing:"ease-out"})};return document.body?C():document.addEventListener("DOMContentLoaded",C,{once:!0}),()=>k()}export{H as show};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var pe=["token","access_token","id_token","refresh_token","password","pwd","secret","key","api_key","apikey","auth","authorization","code","session","sid","email","mail","signature","sig","otp"];function M(){let e=crypto.getRandomValues(new Uint8Array(16)),n=Date.now();for(let r=5;r>=0;r--)e[r]=n%256,n=Math.floor(n/256);e[6]=e[6]&15|112,e[8]=e[8]&63|128;let t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var z=(e,n)=>String(e??"").slice(0,n);function x(e,n){try{let t=new URL(e,location.href);t.username=t.password="";for(let r of[...t.searchParams.keys()])n.includes(r.toLowerCase())&&t.searchParams.delete(r);return/^#\/[^?=&]*$/.test(t.hash)||(t.hash=""),t.href}catch{return""}}function ge(e){let n=[];for(let t=e,r=0;t&&t!==document.documentElement&&r<4;t=t.parentElement,r++){let o=t.tagName.toLowerCase();if(t.id&&/^[\w-]{1,40}$/.test(t.id)&&!/\d{3,}/.test(t.id)){n.unshift(`${o}#${t.id}`);break}let i=[...t.classList].find(a=>/^[a-zA-Z][\w-]{0,30}$/.test(a)&&!/\d{3,}/.test(a));i&&(o+=`.${i}`),n.unshift(o)}return n.join(" > ").slice(0,120)}async function G(e){if(typeof CompressionStream>"u")return new Blob([e],{type:"text/plain"});let n=await new Response(new Blob([e]).stream().pipeThrough(new CompressionStream("gzip"))).blob();return new Blob([n],{type:"text/plain"})}function me(){let e=navigator.userAgent,n=a=>e.match(a)?.[1],t=/Windows/.test(e)?"Windows":/Android/.test(e)?"Android":/iPhone|iPad|iPod/.test(e)?"iOS":/Mac OS X/.test(e)?"macOS":/CrOS/.test(e)?"ChromeOS":/Linux/.test(e)?"Linux":"Other",r=n(/(?:Windows NT|Android|OS|Mac OS X) ([\d._]+)/)?.replace(/_/g,"."),[o,i]=/Edg\//.test(e)?["Edge",/Edg\/([\d.]+)/]:/OPR\//.test(e)?["Opera",/OPR\/([\d.]+)/]:/Firefox\//.test(e)?["Firefox",/Firefox\/([\d.]+)/]:/Chrome\//.test(e)?["Chrome",/Chrome\/([\d.]+)/]:/Safari\//.test(e)?["Safari",/Version\/([\d.]+)/]:["Other",/$^/];return{os:t,os_version:r,browser:o,browser_version:n(i)}}var Xe="a[href],button,summary,[role=button],[data-pt-event]",We=1e3,Ve=500;function he(e,n,t){let r,o=0,i=[],a=!1;return n(()=>{a=!0}),addEventListener("pagehide",()=>{a=!0}),addEventListener("click",s=>{let c=s.target;if(!s.isTrusted||!(c instanceof Element)||o++>=Ve||c.closest("[data-pt-block]"))return;let l=ge(c),f=Math.round(s.clientX+scrollX),d=Math.round(s.clientY+scrollY),u=document.documentElement,_=c.closest("[data-pt-event]")?.getAttribute("data-pt-event"),b={selector:l,x:f,y:d,doc_w:u.scrollWidth,doc_h:u.scrollHeight};if(e("$autocapture",{...b,tag:c.tagName.toLowerCase(),pt_event:_||void 0}),_&&e(_.slice(0,100),{selector:l}),!t.frustration)return;let v=s.timeStamp||Date.now();r=b,setTimeout(()=>{r===b&&(r=void 0)},We),i=i.filter(Q=>v-Q.t<1e3&&Math.hypot(Q.x-f,Q.y-d)<30),i.push({t:v,x:f,y:d}),i.length>=3&&(e("$rageclick",{...b,count:i.length}),i=[]);let U=c.closest(Xe);if(!U||U.closest("a[target=_blank],a[download]")||/^(mailto|tel):/.test(U.getAttribute("href")||""))return;a=!1;let H=!1,B=new MutationObserver(()=>{H=!0});B.observe(u,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),setTimeout(()=>{B.disconnect(),!H&&!a&&e("$deadclick",b)},1e3)},{capture:!0,passive:!0}),s=>{r&&(e("$errorclick",{...r,...s}),r=void 0)}}function ve(e,n){let t=0,r=!1,o=0,i=()=>{let c=document.documentElement,l=Math.max(c.scrollHeight,1);return Math.min(100,Math.round((scrollY+c.clientHeight)/l*100))},a=()=>{o=0,t=Math.max(t,i())},s=()=>{if(r)return;r=!0;let c=document.documentElement;e("$scroll_depth",{max_pct:Math.max(t,i()),doc_h:c.scrollHeight,viewport_h:c.clientHeight})};addEventListener("scroll",()=>{o||(o=requestAnimationFrame(a))},{passive:!0}),addEventListener("pagehide",s),addEventListener("visibilitychange",()=>document.visibilityState==="hidden"&&s()),n(()=>{s(),r=!1,t=0})}function Z(e,n=0){let t=new TextEncoder().encode(e),r=n>>>0,o=3432918353,i=461845907,a=t.length&-4;for(let c=0;c<a;c+=4){let l=t[c]|t[c+1]<<8|t[c+2]<<16|t[c+3]<<24;l=Math.imul(l,o),l=l<<15|l>>>17,l=Math.imul(l,i),r^=l,r=r<<13|r>>>19,r=Math.imul(r,5)+3864292196|0}let s=0;switch(t.length&3){case 3:s^=t[a+2]<<16;case 2:s^=t[a+1]<<8;case 1:s^=t[a],s=Math.imul(s,o),s=s<<15|s>>>17,s=Math.imul(s,i),r^=s}return r^=t.length,r^=r>>>16,r=Math.imul(r,2246822507),r^=r>>>13,r=Math.imul(r,3266489909),r^=r>>>16,r>>>0}function ye(e,n,t=""){return Z(`${e}.${n}${t}`)/4294967296}function we(e,n){let t=e.split(/[.+-]/).map(o=>parseInt(o,10)||0),r=n.split(/[.+-]/).map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((t[o]??0)!==(r[o]??0))return(t[o]??0)-(r[o]??0);return 0}function Ke(e,n){let t=n[e.property];if(e.operator==="is_set")return t!=null;if(e.operator==="is_not_set")return t==null;if(t==null)return!1;let r=String(t),o=Array.isArray(e.value)?e.value.map(String):[String(e.value)];switch(e.operator){case"eq":return r===String(e.value);case"neq":return r!==String(e.value);case"in":return o.includes(r);case"nin":return!o.includes(r);case"contains":return r.toLowerCase().includes(String(e.value).toLowerCase());case"ncontains":return!r.toLowerCase().includes(String(e.value).toLowerCase());case"regex":if(r.length>1024)return!1;try{return new RegExp(String(e.value)).test(r)}catch{return!1}case"gt":return Number(t)>Number(e.value);case"gte":return Number(t)>=Number(e.value);case"lt":return Number(t)<Number(e.value);case"lte":return Number(t)<=Number(e.value);case"semver_gte":return we(r,String(e.value))>=0;case"semver_lt":return we(r,String(e.value))<0}}function Se(e,n,t={}){if(!e.active)return{enabled:!1};let o=(e.groups.length?e.groups:[{conditions:[]}]).find(s=>s.conditions.every(c=>Ke(c,t)));if(!o)return{enabled:!1};let i=o.rollout_percent??e.rollout_percent;if(ye(e.key,n)*100>=i)return{enabled:!1};if(!e.variants?.length)return be({enabled:!0},e.payloads?.true);let a=o.variant;if(!a){let s=ye(e.key,n,".variant")*100,c=0;a=e.variants[e.variants.length-1].key;for(let l of e.variants)if(c+=l.weight,s<c){a=l.key;break}}return be({enabled:!0,variant:a},e.payloads?.[a])}function be(e,n){return n===void 0?e:{...e,payload:n}}var Ye=/\/(\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?=[/?#]|$)/gi;function _e(e,n,t){if(n.errors){let r=0,o=(i,a,s="",c)=>{if(r++>=20)return;let l=s.split(`
|
|
2
|
+
`).slice(1,4).map(v=>v.replace(/[:\d]+\)?$/,"")).join("|"),f=Z([i,a.replace(/\d+/g,"N"),l].join("|")).toString(16),d=n.drop().map(v=>v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),u=v=>v.replace(/https?:\/\/[^\s)'"]+/gi,U=>{let[,H,B=""]=U.match(/^(.*?)(:\d+:\d+)?$/);return x(H,n.drop())+B}),_=v=>d?v.replace(new RegExp(`([?&;#]|%3[bf]|%26|%23)(${d})(=|%3d)(?:%(?!26|23|3b)[0-9a-f]{2}|(?!:\\d+:\\d+(?:$|[\\s)]))[^&\\s)'"#%])*`,"gi"),"$1$2$3[redacted]"):v,b=v=>_(u(_(v)));n.onError?.({fingerprint:f,type:i}),e("$error",{message:z(b(a),500),stack:z(b(s),4e3),type:i,fingerprint:f,release:n.release,filename:c&&x(c,n.drop())})};addEventListener("error",i=>o(i.error?.name||"Error",i.message,i.error?.stack,i.filename)),addEventListener("unhandledrejection",i=>{let a=i.reason;o(a?.name||"UnhandledRejection",a?.message??String(a),a?.stack)})}if(n.network){let r=0,o=(s,c,l,f)=>{if(r>=200||c.startsWith(n.host))return;r++;let d=x(c,n.drop()).replace(Ye,"/:id");e("$network",{method:s,url:d,status:l,duration_ms:Math.round(performance.now()-f)})},i=window.fetch;i&&(window.fetch=function(s,c){let l=performance.now(),f=(c?.method||(s instanceof Request?s.method:"GET")).toUpperCase(),d=typeof s=="string"?s:s instanceof URL?s.href:s.url;return i.call(this,s,c).then(u=>(o(f,d,u.status,l),u),u=>{throw o(f,d,0,l),u})});let a=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(s,c,...l){let f=performance.now();return this.addEventListener("loadend",()=>o(s.toUpperCase(),String(c),this.status,f)),a.call(this,s,c,...l)}}if(n.console){let r=0;for(let o of n.console){let i=console[o];console[o]=(...a)=>{i.apply(console,a),r++<100&&e("$console",{level:o,message:z(a.map(s=>typeof s=="string"?s:s instanceof Error?s.message:Qe(s)).join(" "),500)})}}}n.vitals&&typeof PerformanceObserver<"u"&&Ge(e,t)}var Qe=e=>{try{return JSON.stringify(e)}catch{return String(e)}};function Ge(e,n){let t,r=0,o=0,i=0,a=0,s=[],c=0,l=(u,_,b={})=>{try{new PerformanceObserver(v=>v.getEntries().forEach(_)).observe({type:u,buffered:!0,...b})}catch{}};l("largest-contentful-paint",u=>{t=u.startTime}),l("layout-shift",u=>{u.hadRecentInput||(o&&u.startTime-i<1e3&&u.startTime-a<5e3?o+=u.value:(o=u.value,a=u.startTime),i=u.startTime,r=Math.max(r,o))});let f=new Set;l("event",u=>{u.interactionId&&(f.has(u.interactionId)||(f.add(u.interactionId),c++),s=[...s,u.duration].sort((_,b)=>b-_).slice(0,10))},{durationThreshold:40});let d=()=>{let u={lcp:t&&Math.round(t),inp:s.length?s[Math.min(9,Math.floor(c/50))]:void 0,cls:r?+r.toFixed(4):void 0};(u.lcp!==void 0||u.inp!==void 0||u.cls!==void 0)&&e("$web_vitals",u),r=o=0,s=[],c=0,f.clear(),t=void 0};addEventListener("visibilitychange",()=>document.visibilityState==="hidden"&&d()),n(d)}function ke(e){let n=[],t={},r=0,o=new Set,i=new Set;try{let l=e.load();l&&(n=JSON.parse(l))}catch{}async function a(l=!0){let f=await e.json(`/i/v1/flags/definitions?key=${encodeURIComponent(e.key)}${e.env?`&env=${e.env}`:""}`);if(f?.flags&&(n=f.flags,e.save(JSON.stringify(n))),l&&e.canPost()){let d=await e.json("/i/v1/flags",{api_key:e.key,distinct_id:e.id(),environment:e.env,properties:e.props()});d?.flags&&(t=d.flags)}o.forEach(d=>d())}function s(){r||typeof setInterval>"u"||(a(),r=setInterval(()=>document.visibilityState!=="hidden"&&a(!1),e.pollMs))}function c(l){s();let f=n.find(u=>u.key===l),d=f?Se(f,e.id(),e.props()):t[l];return d?(i.has(l)||(i.add(l),e.capture("$feature_flag_called",{flag:l,enabled:d.enabled,variant:d.variant})),d):{enabled:!1}}return{isEnabled:l=>c(l).enabled,getVariant:l=>c(l).variant,getPayload:l=>c(l).payload,reload:()=>a(),onChange(l){return s(),o.add(l),()=>{o.delete(l)}},reset(){i.clear(),r&&a()}}}var Re=["necessary","analytics","replay","personalization","marketing"],$e=30*6e4,Ze=2e3,et=15e5,tt=100,m,L="",R="",se,X=!1,g=null,p=null,S="anon_"+M(),k=null,$={},T=null,w,h=[],N=[],ie=Promise.resolve(),ee=0,te=0,ne=!1,ce=!1,Ie,re,Me="",Pe={},ue=!1,y=null,oe=!1,W=!1,J=!1,C,ae=[],Oe,Le=new Promise(e=>{Oe=e}),O=e=>{try{return JSON.parse(localStorage.getItem(e)||"null")}catch{return null}},E=(e,n)=>{try{n==null?localStorage.removeItem(e):localStorage.setItem(e,JSON.stringify(n))}catch{}},V=(e,n)=>{I()==="full"&&E(e,n)},q=e=>!!e&&!!g&&Date.now()<e.t+(g.consent?.validity_days??180)*864e5&&(!g.consent||e.v===g.consent.version),A=e=>e==="necessary"||q(p)&&p.c[e]===!0,Te=()=>g?.consent?.respect_gpc!==!1&&(navigator.globalPrivacyControl===!0||navigator.doNotTrack==="1"),Ne=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone.startsWith("Europe/")}catch{return!0}};function I(){if(q(p))return p.c.analytics?"full":"off";if(!g)return"wait";let e=g.consent;return!e?.enabled||e.exempt_analytics||e.regions==="eu"&&!Ne()?"mem":Te()?"off":"wait"}function Ae(){let e=q(p)?p:null;return{id:e?.id,version:e?.v,categories:e?e.c:I()==="mem"?{analytics:!0}:{}}}var nt=e=>new Promise(n=>{let t=setTimeout(n,e);Ie=()=>{clearTimeout(t),n()}});async function Y(e,n,t=1/0){for(let r=0;;r++){let o=null;try{o=await fetch(e,{credentials:"omit",...n})}catch{}if(o&&o.status!==429&&o.status<500||r+1>=t)return o;await nt(Math.max((Number(o?.headers.get("retry-after"))||0)*1e3,Math.min(3e5,1e3*2**r)*(.5+Math.random()/2)))}}var qe=async(e,n,t)=>(await Y(R+e,{method:"POST",body:await G(n)},t))?.status??0,rt=async(e,n)=>{let t=await Y(R+e,n?{method:"POST",body:JSON.stringify(n),headers:{"content-type":"text/plain"}}:{},1).catch(()=>null);return t?.ok?t.json().catch(()=>null):null},F=()=>[...pe,...m?.sensitiveParams??[],...g?.replay.mask.ignore_url_params??[]].map(e=>e.toLowerCase());function Ue(){let e=document.documentElement;return{url:x(location.href,F()),referrer:Me,lang:navigator.language,viewport_w:e.clientWidth,viewport_h:e.clientHeight,platform:"web",...me(),app_version:m.release,...Pe}}function D(){let e=Date.now();return(!w||e-w.t>$e)&&(w={id:M(),t:e,u:Math.random(),v:Math.random(),n:0}),w.t=e,w.id}function P(e,n={},t={}){let r={id:M(),event:e,ts:new Date().toISOString(),distinct_id:k??S,session_id:D(),environment:se,props:{...Ue(),...n},...t};k&&(r.identified=!0),De(r),st(e)}function De(e){let n=I();if(n==="wait"||!g){N.push(e),N.length>tt&&N.shift();return}if(n==="off")return;let t=g.sampling;D(),!(w.u>=t.sessions||e.event!=="$identify"&&Math.random()>=t.events)&&(h.push(e),h.length>=m.batchSize?Ce():ee||(ee=setTimeout(()=>{ee=0,Ce()},m.batchInterval)),te||(te=setTimeout(()=>{te=0,j()},1e3)))}function j(){if(I()!=="full")return;let e=h.slice(-Ze);for(;e.length>1&&JSON.stringify(e).length>et;)e=e.slice(e.length>>1);E("pt_q",e.length?e:null),E("pt_s",w)}var Fe=e=>JSON.stringify({api_key:L,sent_at:new Date().toISOString(),consent:Ae(),batch:e}),K=()=>I()==="mem"||I()==="full";async function Ce(){if(!(ne||!h.length||!K())){ne=!0;try{for(await ie;h.length&&K();){let e=h.slice(0,100);await Y(R+"/i/v1/events",{method:"POST",body:await G(Fe(e))});let n=new Set(e);h=h.filter(t=>!n.has(t)),j()}}finally{ne=!1}}}function Ee(){for(j(),y?.beacon();h.length&&K();){let e=h.slice(0,25);if(!navigator.sendBeacon?.(R+"/i/v1/events",new Blob([Fe(e)],{type:"text/plain"})))break;let n=new Set(e);h=h.filter(t=>!n.has(t))}j()}function ot(){let e=S;S=O("pt_id")||S,E("pt_id",S);let n=O("pt_s");n&&Date.now()-n.t<$e&&(w=n);let t=O("pt_u");t&&A("personalization")&&(k=t.u,$=t.tr);let r=O("pt_q");Array.isArray(r)&&(h=[...r,...h]);for(let o of[...h,...N])o.distinct_id===e&&(o.distinct_id=S);ce=!0}function je(){for(let e of["pt_id","pt_s","pt_q","pt_u","pt_cfg","pt_flags"])E(e,null);h=[],N=[],k=null,$={},w=void 0,ce=!1,S="anon_"+M()}function He(){let e=I();e==="full"&&!ce&&ot(),e!=="wait"&&(N.splice(0).forEach(n=>e!=="off"&&De(n)),Be(),fe(),T&&A("personalization")&&(at(...T),T=null),j())}function de(e,n){let t=q(p)?p.c:null,r={...e,necessary:!0};p={id:p?.id||M(),v:g?.consent?.version??0,t:Date.now(),c:r},E("pt_consent",p),r.analytics?r.personalization||(k=null,$={},T=null,E("pt_u",null)):je(),r.replay||(y?.stop(),y=null);let o=n==="withdraw"||!!t&&Re.some(a=>t[a]&&!r[a]),i={api_key:L,consent_id:p.id,policy_version:p.v,choices:r,source:o?"withdraw":n};ie=ie.then(()=>qe("/i/v1/consent",JSON.stringify(i),6)),He(),C?.reset()}function Be(){!g||!ue||document.querySelectorAll('script[type="text/plain"][data-pt-category]').forEach(e=>{if(!A(e.dataset.ptCategory))return;let n=document.createElement("script");for(let t of Array.from(e.attributes))t.name!=="type"&&t.name!=="data-pt-category"&&n.setAttribute(t.name,t.value);n.text=e.text,e.replaceWith(n)})}async function ze(e){let n=g?.consent;if(!(!n||J)){J=!0;try{(await import("./consent.js")).show({cfg:n,current:e&&p?p.c:null,onChoice:r=>de(r,"banner"),onClose:()=>{J=!1}})}catch{J=!1}}}function xe(){He();let e=g?.consent;e?.enabled&&!q(p)&&!Te()&&(e.regions==="always"||Ne())&&ze(!1)}function fe(e=!1){let n=g?.replay;!ue||y||oe||W||!n?.enabled||!A("replay")||typeof document>"u"||(D(),!(w.u>=g.sampling.sessions||!(e||w.v<n.sample_rate))&&(oe=!0,import("./replay.js").then(t=>{if(y||!A("replay"))return;let r=(o,i)=>`/i/v1/replay/${o}/chunks?key=${encodeURIComponent(L)}&seq=${i}`;y=t.start({cfg:n,dropParams:F(),sessionId:D,distinctId:()=>k??S,consent:Ae,nextSeq:()=>(D(),w.n++),post:async(o,i,a)=>{let s=await qe(r(o,i),a,6);return s===403&&(y?.stop(),y=null,W=!0),s},beacon:(o,i,a)=>navigator.sendBeacon?.(R+r(o,i),new Blob([a],{type:"text/plain"}))})}).catch(()=>{}).finally(()=>{oe=!1})))}function st(e){let n=g?.replay.triggers;if(!n||y)return;let t=location.pathname+location.search,r=o=>new RegExp("^"+o.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$").test(t);(e==="$error"&&n.on_error||n.events?.includes(e)||e==="$pageview"&&n.url_patterns?.some(r))&&fe(!0)}function le(){let e=x(location.href,F());if(e===re)return;Me=re??x(document.referrer,F()),re=e;let n=new URL(location.href).searchParams;for(let[t,r]of n)t.startsWith("utm_")&&(Pe[t]=r.slice(0,200));P("$pageview")}function it(){for(let e of["pushState","replaceState"]){let n=history[e];history[e]=function(...t){ae.forEach(o=>o());let r=n.apply(this,t);return le(),r}}addEventListener("popstate",()=>{ae.forEach(e=>e()),le()})}function kt(e,n){if(X||typeof window>"u")return;X=!0,L=e,m={batchInterval:5e3,batchSize:20,...n},R=m.host.replace(/\/$/,""),se=m.environment,p=O("pt_consent"),C=ke({key:L,env:se,pollMs:m.flagsPollMs??3e4,capture:P,json:rt,id:()=>k??S,props:()=>({...Ue(),$platform:"web",...$}),load:()=>I()==="full"?localStorage.getItem("pt_flags"):null,save:i=>V("pt_flags",JSON.parse(i)),canPost:()=>K()});let t=p?.c.analytics?O("pt_cfg"):null;t&&t.consent?.version===p.v&&(g=t,xe()),(async()=>{let i=await Y(`${R}/i/v1/config?key=${encodeURIComponent(L)}`,{},5),a=i?.ok?await i.json().catch(()=>null):null;a&&(g=a,ue=!0,V("pt_cfg",a),q(p)||(y?.stop(),y=null),xe(),Oe())})();let r=i=>{ae.push(i)};m.autocapture!==!1&&ve(P,r),addEventListener("online",()=>Ie?.()),addEventListener("visibilitychange",()=>document.visibilityState==="hidden"&&Ee()),addEventListener("pagehide",Ee),m.pageviews!==!1&&(it(),le());let o=m.autocapture!==!1?he(P,r,{frustration:m.frustration!==!1}):void 0;_e(P,{errors:m.errors!==!1,network:m.network!==!1,vitals:m.vitals!==!1,console:m.console===void 0?["warn","error"]:m.console,drop:F,host:R,release:m.release,onError:o},r),document.addEventListener("DOMContentLoaded",Be)}function Ct(e,n){X&&P(e,n)}function at(e,n={}){if(!X)return;if(!A("personalization")){T=[e,n];return}let t=S;k=e,$={...$,...n},V("pt_u",{u:k,tr:$}),P("$identify",{},{anonymous_id:t,traits:n}),C?.reset()}function Et(){k=null,$={},T=null,w=void 0,S="anon_"+M(),E("pt_u",null),E("pt_s",null),V("pt_id",S),C?.reset()}var Je=e=>g?e():void Le.then(e),xt=e=>Je(()=>de(Object.fromEntries((e??Re).map(n=>[n,!0])),"api")),Rt=()=>{je(),Je(()=>de({},"withdraw"))},$t={open:()=>Le.then(()=>ze(!0))},It={pause(){W=!0,y?.pause()},resume(){W=!1,y?y.resume():fe()}},Mt={isEnabled:e=>C?.isEnabled(e)??!1,getVariant:e=>C?.getVariant(e),getPayload:e=>C?.getPayload(e),reload:()=>C?.reload(),onChange:e=>C?.onChange(e)??(()=>{})};export{$t as consent,Mt as flags,at as identify,kt as init,xt as optIn,Rt as optOut,It as replay,Et as reset,Ct as track};
|