@depsmith/depsmith-sdk 0.9.4 → 0.9.5
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/CHANGELOG.md +6 -0
- package/README.md +47 -0
- package/dist/depsmith-sdk.global.js +1 -1
- package/dist/depsmith-sdk.global.js.map +1 -1
- package/dist/depsmith-sdk.pixel.global.js +1 -1
- package/dist/depsmith-sdk.replay.global.js +3 -0
- package/dist/depsmith-sdk.replay.global.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/replay.cjs +3 -0
- package/dist/replay.cjs.map +1 -0
- package/dist/replay.d.cts +56 -0
- package/dist/replay.d.ts +56 -0
- package/dist/replay.js +3 -0
- package/dist/replay.js.map +1 -0
- package/package.json +27 -5
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var ne=class{constructor(){this.counter=0}recordPage(e,t){return e===this.currentUrl?!1:(this.currentUrl===void 0?t?(this.previousUrl=t,this.previousType=Ie(t,e)?"internal":"external"):this.previousType="direct":(this.previousUrl=this.currentUrl,this.previousType=Ie(this.currentUrl,e)?"internal":"external"),this.currentUrl=e,this.counter+=1,!0)}tracking(){let e={};return this.previousUrl!==void 0&&(e.previous_url=this.previousUrl),this.previousType!==void 0&&(e.previous_type=this.previousType),this.counter>0&&(e.counter=this.counter),e}get pageCount(){return this.counter}get current(){return this.currentUrl}resetForNewSession(){this.counter=this.currentUrl===void 0?0:1}},D=class{constructor(e,t={autocapture:!1}){this.sink=e;this.pages=new ne;this.enteredAt=0;this.left=!1;this.rules=Tt(t.pageNames),this.byHref=!!t.autocapture&&t.autocapture.pageviews==="all"}start(e,t){this.pages.recordPage(e,t),this.enteredAt=this.sink.now()}get pageCount(){return this.pages.pageCount}recordExplicit(){this.record(),this.lastViewed=this.pageKey(),this.autoViewed=void 0}manual(e,t,i){let n=this.pending;if(n&&this.keyOf(n.location)===this.pageKey())this.discardPending();else{this.flushPending();let s=this.autoViewed;if(this.autoViewed=void 0,s&&s.url===Re()&&this.sink.now()-s.at<=Ct)return}this.recordExplicit(),this.sink.capture("$page_view","page_view",{...t,...$e({source:"manual",name:e,type:i},this.rules),$page_counter:this.pages.pageCount})}autoPageView(e){this.flushPending(),this.record();let t=this.pageKey();if(t!==void 0&&t===this.lastViewed)return;this.lastViewed=t;let i=this.pages.pageCount;if(!e){this.emitView(location,i);return}let n=location.href,s={at:this.sink.now(),counter:i,location:new URL(n),page:{url:n,path:location.pathname,referrer:document.referrer,domain:P(n),url_base:U(n),...this.pages.tracking()},cancel:()=>{}};this.pending=s,s.cancel=e(document.title,()=>this.flushPending())}flushPending(){let e=this.pending;e&&(this.pending=void 0,e.cancel(),this.emitView(e.location,e.counter,e))}discardPending(){this.pending?.cancel(),this.pending=void 0}emitView(e,t,i){let n=document.title;this.autoViewed={url:e.href,at:this.sink.now()},this.sink.capture("$page_view","page_view",{...$e({source:"auto",location:e,title:n},this.rules),$page_counter:t},i?.at,i&&{...i.page,title:n})}leave(e){this.flushPending();let t=this.pages.current;if(t===void 0||this.left)return;this.left=!0;let i={$page_duration_ms:Math.max(0,this.sink.now()-this.enteredAt)};e!==void 0&&(i.$page_max_scroll=e),this.leaving=t;try{this.sink.capture("$page_leave","page_leave",i)}finally{this.leaving=void 0}}restored(e){e&&(this.left=!1,this.enteredAt=this.sink.now())}newSession(){this.pages.resetForNewSession()}tracking(){let e=this.pages.tracking();return this.leaving===void 0?e:{...e,url:this.leaving,path:Rt(this.leaving),domain:P(this.leaving),url_base:U(this.leaving)}}pageKey(){let e=globalThis.location;return e&&this.keyOf(e)}keyOf(e){return this.byHref?e.href:e.pathname}record(){let e=Re();if(e===void 0)return;this.pages.recordPage(e,typeof document<"u"?document.referrer:"")&&(this.enteredAt=this.sink.now(),this.left=!1)}},Ct=2e3;function $e({source:r,name:e,type:t,location:i=globalThis.location,title:n=globalThis.document?.title},s){let o=i&&s?.(i),d=t?.trim()||o?.type;return{$page_name:e?.trim()||o?.name.trim()||n?.trim()||i?.pathname||"Unknown",...d?{$page_type:d}:{},$page_source:r}}function Tt(r){if(typeof r=="function")return t=>{try{let i=r(t);return typeof i=="string"?{name:i}:void 0}catch{return}};if(!r||typeof r!="object")return;let e=(Array.isArray(r)?r:Object.entries(r)).map(([t,i])=>[typeof t=="string"&&typeof i=="string"&&$t(t),i]);return t=>{let i=Ne(t.pathname);for(let[n,s]of e)if(n&&n.test(i))return{name:s,type:s}}}function $t(r){let e=Ne(r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\/\*\*|\*\*?/g,t=>t==="*"?"[^/]+":t==="**"?".*":"(?:/.*)?");return new RegExp(`^${e}$`)}function Ne(r){return r.replace(/(.)\/$/,"$1")}function Re(){if(!(typeof window>"u"||!window.location))return window.location.href}function Ie(r,e){try{return new URL(r).host===new URL(e).host}catch{return!1}}function Rt(r){try{return new URL(r).pathname||void 0}catch{return}}function P(r){try{return new URL(r).host||void 0}catch{return}}function U(r){try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return}}var It=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]],se="depsmith_campaign",oe="depsmith_referrer",L=class{constructor(e){this.storage=e;this.campaign={};this.referrer={};this.campaign=this.read(se)??{},this.referrer=this.read(oe)??{}}read(e){try{let t=this.storage.get(e);if(!t)return null;let i=JSON.parse(t);return i&&typeof i=="object"?i:null}catch{return null}}write(e,t){try{this.storage.set(e,JSON.stringify(t))}catch{}}recordLanding(e,t){let i,n;try{let u=new URL(e);i=u.searchParams,n=u.host}catch{return}let s={};for(let[u,c]of It){let p=i.get(u);p&&(s[c]=p)}Object.keys(s).length>0&&(this.campaign=s,this.write(se,s));let o=t?P(t):void 0,d=!!o&&o!==n,a=!1;d&&(this.referrer.url=t,this.referrer.domain=o,a=!0),this.referrer.initial_domain===void 0&&(this.referrer.initial_domain=d?o:"$direct",d&&(this.referrer.initial_url=t),a=!0),a&&this.write(oe,this.referrer)}campaignBlock(){return Object.keys(this.campaign).length>0?{...this.campaign}:void 0}referrerBlock(){return Object.keys(this.referrer).length>0?{...this.referrer}:void 0}clear(){this.campaign={},this.referrer={};try{this.storage.remove(se),this.storage.remove(oe)}catch{}}};function Me(r){if(typeof window>"u"||typeof document>"u")return;let e=setInterval(()=>r.flushIfQueued(),r.intervalMs);e.unref?.();let t=!1,i,n=()=>{let a=i;clearTimeout(a),i=void 0,r.guard(()=>r.vitals()),r.guard(()=>r.leave()),!(t&&!a)&&(t=!0,r.beacon(),r.persistNow())},s=()=>{if(document.visibilityState==="hidden"){if(t)return;r.guard(()=>r.vitals()),t=!0,r.persistNow(),i=setTimeout(()=>{i=void 0,r.flushIfQueued()},0)}else clearTimeout(i),t=!1,r.resume()},o=a=>{t=!1,r.restored(a.persisted)},d=()=>r.online();return window.addEventListener("pagehide",n),window.addEventListener("pageshow",o),document.addEventListener("visibilitychange",s),window.addEventListener("online",d),{rearm:()=>{t=!1},stop:()=>{clearInterval(e),window.removeEventListener("pagehide",n),window.removeEventListener("pageshow",o),document.removeEventListener("visibilitychange",s),window.removeEventListener("online",d),clearTimeout(i)}}}function De(){return import("./autocapture.js")}var ae=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["idfv","device","idfv"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screenSize","screen_size"],["timezone","timezone"],["userAgent","user_agent"]],Nt=Object.fromEntries(ae.map(([r])=>[r,!0]));function Ue(r){let e={...Nt};if(!r)return e;for(let[t]of ae)r[t]===!1&&(e[t]=!1);return e}function Le(r,e){let t=r;for(let[i,n,s]of ae){if(e[i])continue;if(s===void 0){delete t[n];continue}let o={...t[n]};delete o[s],Object.keys(o).length>0?t[n]=o:delete t[n]}return r}var Ke={clicks:"interactive",forms:!0,scrolls:!1,pageviews:"path",ignoredSelectors:[],selectorMaxDepth:5,selectorIgnore:[],attributes:[]};function Ve(r){if(r===!0)return Ke;if(!r||typeof r!="object")return!1;let e={...Ke};for(let[n,s]of Object.entries(r))s!==void 0&&(e[n]=s);let{clicks:t,pageviews:i}=e;return e.clicks=t==="all"?"all":t?"interactive":!1,e.pageviews=i==="all"?"all":i?"path":!1,e}function Be(r){if(!r||typeof r.apiKey!="string"||r.apiKey.length===0)throw new Error("depsmith-sdk: apiKey is required");if(typeof r.endpoint!="string"||!/^https?:\/\//.test(r.endpoint))throw new Error("depsmith-sdk: endpoint must be an http(s) URL");let e=Ve(r.autocapture);return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:x(r.batchSize,20,1,500),batchIntervalMs:x(r.batchIntervalMs,6e4,1e3,2**31-1),maxQueueSize:x(r.maxQueueSize,1e3,1),maxQueueBytes:x(r.maxQueueBytes,512*1024,4096),sessionTimeoutMs:x(r.sessionTimeoutMs,18e5,6e4),sampleRate:qe(r.sampleRate,1,0,1),sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:x(r.maxRetries,5,0,10),debug:r.debug??!1,defaultProperties:r.defaultProperties??{},autocapture:e,compression:r.compression??"gzip",childSafeMode:r.childSafeMode??!1,anonymizeIp:(r.anonymizeIp??!1)||(r.childSafeMode??!1),deviceFingerprinting:r.deviceFingerprinting??!0,geolocation:r.geolocation??!1,scrubUrls:r.scrubUrls??!1,trackingOptions:Ue(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage",pageNames:r.pageNames}}function qe(r,e,t,i=1/0){return Math.min(Math.max(Number.isFinite(r)?r:e,t),i)}function x(r,e,t,i){return Math.floor(qe(r,e,t,i))}function de(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)>>>0;return e.toString(36)}function ze(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e}function Mt(r){return ze(r).toString(36)}function Fe(r){return ze(r)/4294967296}function ue(r){return de(r)+Mt(r)}var ce={},je=!1;function We(){if(!je){je=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{ce=e}).catch(()=>{})}catch{}}}function pe(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,i=Kt(e,t);i&&(r.browser=i);let n=Bt(e);if(n){let d=Ut(n.name,ce.platformVersion);r.os=d?{...n,version:d}:n}let s=qt(e,t);s&&(r.deviceType=s);let o=Dt(e,n);return o&&(r.device=o),r}function Dt(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let i=ce.model?.trim();return i?t.model=i:/iPhone/.test(r)?t.model="iPhone":/iPad/.test(r)&&(t.model="iPad"),t.manufacturer||t.model?t:void 0}function Ut(r,e){let t=e?.trim();if(t){if(r==="Windows"){let i=Number.parseInt(t.split(".")[0]??"",10);return!Number.isFinite(i)||i===0?void 0:i>=13?"11":"10"}return Xe(t)}}var Lt=[{pattern:/Edg(?:e|A|iOS)?\/([\d.]+)/,name:"Edge",engine:"Blink"},{pattern:/OPR\/([\d.]+)/,name:"Opera",engine:"Blink"},{pattern:/Firefox\/([\d.]+)/,name:"Firefox",engine:"Gecko"},{pattern:/Chrome\/([\d.]+)/,name:"Chrome",engine:"Blink"},{pattern:/Version\/([\d.]+)/,name:"Safari",engine:"WebKit",requires:/Safari/}];function Kt(r,e){for(let i of Lt){if(i.requires&&!i.requires.test(r))continue;let n=r.match(i.pattern);if(n)return{name:i.name,version:n[1],engine:i.engine}}let t=e?.brands?.find(i=>!/not.?a.?brand/i.test(i.brand));if(t)return{name:t.brand,version:t.version}}var Vt=[{pattern:/Windows NT ([\d.]+)/,name:"Windows"},{pattern:/OS ([\d_]+)/,name:"iOS",requires:/iPhone|iPad|iPod/},{pattern:/Android ([\d.]+)/,name:"Android"},{pattern:/Mac OS X ([\d_]+)/,name:"macOS"}];function Bt(r){for(let e of Vt){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:Xe((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function Xe(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function qt(r,e){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(r))return"tablet";if(e?.mobile===!0||/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(r))return"mobile";if(/Android/.test(r))return"tablet";if(typeof navigator<"u"&&r)return"desktop"}var Ye=new Map,K=null;function He(){return K!==null||(K=zt()),K}function le(r=""){let e=Ye.get(r);if(e!==void 0)return e;let t=He().map(n=>n.value).join("|"),i=ue(r?`project=${r}|${t}`:t);return Ye.set(r,i),i}function Qe(){let r={};for(let e of He())r[`$fp_${e.name}`]=e.value;return r}function zt(){let r=[];try{if(typeof screen<"u"&&r.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`}),typeof navigator<"u"){let e=navigator;r.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`}),r.push({name:"dm",value:`dm:${e.deviceMemory??""}`}),r.push({name:"plat",value:`plat:${navigator.platform??""}`}),r.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}r.push({name:"canvas",value:`canvas:${Ft()}`})}catch{}return r}function Ft(){try{if(typeof document>"u")return"";let r=document.createElement("canvas");r.width=240,r.height=60;let e=r.getContext("2d");return e?(e.textBaseline="top",e.font="14px 'Arial'",e.fillStyle="#f60",e.fillRect(10,10,100,30),e.fillStyle="#069",e.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15),e.strokeStyle="rgba(0,120,200,0.5)",e.arc(50,30,20,0,Math.PI*2),e.stroke(),ue(r.toDataURL())):""}catch{return""}}function Ge(){try{if(typeof navigator>"u")return{};let r=navigator.connection;if(!r)return{};let e=r.type;if(e==="wifi"||e==="ethernet"||e==="none")return{type:e};switch(r.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var C=null,Ze=0,Je=!1,O=!1,et=null,V=()=>!0;function tt(r=V){if(V=r,!Je){Je=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let e=navigator.permissions;if(typeof e?.query!="function")return;e.query({name:"geolocation"}).then(t=>{et=t,t.state==="granted"&&fe(),t.onchange=()=>{t.state==="granted"?fe():C=null}}).catch(()=>{})}catch{}}}function fe(){if(!(O||!V())){O=!0;try{navigator.geolocation.getCurrentPosition(r=>{O=!1;let{latitude:e,longitude:t,accuracy:i}=r.coords;if(!Number.isFinite(e)||!Number.isFinite(t))return;let n={latitude:e,longitude:t,source:"gps"};Number.isFinite(i)&&(n.accuracy=i),C=n,Ze=Date.now()},()=>{O=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{O=!1}}}function rt(){if(V()||(C=null),!!C)return Date.now()-Ze>3e5&&et?.state==="granted"&&fe(),{...C}}var he="@depsmith/depsmith-sdk",T="0.9.4",ge=null;function jt(){if(ge)return ge;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),ge=r,r}function B(r={}){let e={library:{name:he,version:T}};S(()=>{if(typeof window<"u"&&window.location){let t=window.location.href;e.page={url:t,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0,domain:P(t),url_base:U(t),...r.page??{}}}}),S(()=>{typeof window<"u"&&window.screen&&(e.screen_size={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),S(()=>{let t=jt();t.locale!==void 0&&(e.locale=t.locale),t.userAgent!==void 0&&(e.user_agent=t.userAgent),t.timezone!==void 0&&(e.timezone=t.timezone)}),S(()=>{let{deviceType:t}=pe();t&&(e.device={...e.device,type:t})}),S(()=>{if(r.attribution){let t=r.attribution.campaignBlock();t&&(e.campaign=t);let i=r.attribution.referrerBlock();i&&(e.referrer=i)}}),S(()=>{r.fingerprint&&Yt(e)}),S(()=>{if(r.geolocation){let t=rt();t&&(e.location=t)}});try{if(r.overrides){for(let[t,i]of Object.entries(r.overrides))i!==void 0&&(e[t]=i);e.library={name:he,version:T}}}catch{}return r.tracking&&Le(e,r.tracking),e}function Yt(r){let{browser:e,os:t,deviceType:i,device:n}=pe();e&&(r.browser=e),t&&(r.os=t);let s={...r.device};i&&(s.type=i),n?.manufacturer&&(s.manufacturer=n.manufacturer),n?.model&&(s.model=n.model),Object.keys(s).length>0&&(r.device=s);let o=Ge();o.type&&(r.network={...r.network,type:o.type})}function S(r){try{r()}catch{}}function it(){try{if(typeof navigator>"u")return!1;let r=navigator,e=typeof window<"u"?window:{},t=navigator.doNotTrack??e.doNotTrack??r.msDoNotTrack;return t==="1"||t==="yes"}catch{return!1}}var E="depsmith_consent";function Wt(r){return r==="granted"||r==="denied"||r==="pending"}var q=class{constructor(e,t,i){this.storage=e;this.dntActive=i;let n=e.get(E);this.state=n==="granted"||n==="denied"||n==="pending"?n:t}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.reload(),this.effective()==="granted"}reload(){let e=this.storage.get(E);return!Wt(e)||e===this.state?!1:(this.state=e,!0)}get current(){return this.effective()}optIn(){this.state="granted",this.storage.set(E,"granted")}optOut(){this.state="denied",this.storage.set(E,"denied")}};var $=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},Xt=r=>r();var v="depsmith_queue",Ht=512*1024,me=2,Qt=new Set(["identify","alias","group"]);function Gt(r){return Qt.has(r?.event_type)}var z=class{constructor(e,t,i,n={}){this.storage=e;this.maxSize=t;this.logger=i;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=!1;this.scheduled=!1;this.maxChars=n.maxChars??Ht,this.schedule=n.schedule??$,this.restore()}restore(){try{let e=this.storage.get(v);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;let i=t.filter(n=>!!n&&typeof n=="object"&&typeof n.event_id=="string");this.reset(i),i.length!==t.length&&(this.logger.warn("discarded corrupt queued events on restore"),this.markDirty()),this.trimToBudget()&&this.markDirty()}catch{this.logger.warn("queue storage corrupt; starting empty"),this.reset([]),this.storage.remove(v)}}reset(e){this.events=e,this.sizes=e.map(t=>nt(t)),this.sizeSum=this.sizes.reduce((t,i)=>t+i,0)}serializedLength(){return this.events.length===0?me:this.sizeSum+(this.events.length-1)+me}trimToBudget(){let e=0;for(;this.events.length>0&&this.serializedLength()>this.maxChars;)this.evictAt(this.victimIndex()),e++;return e>0&&this.logger.warn(`queue byte cap reached; dropped ${e} event(s)`),e>0}markDirty(){this.dirty=!0,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){this.dirty&&(this.dirty=!1,this.storage.set(v,JSON.stringify(this.events)))}prepend(e){let t=new Set(this.events.map(n=>n.event_id)),i=e.filter(n=>!!n&&typeof n=="object"&&typeof n.event_id=="string"&&!t.has(n.event_id));i.length!==0&&(this.reset([...i,...this.events]),this.events.length>this.maxSize&&this.dropOldest(this.events.length-this.maxSize),this.trimToBudget(),this.markDirty())}enqueue(e){let t=nt(e);if(t+me>this.maxChars){this.logger.warn(`event ${e.event_id} exceeds the queue byte cap; dropped`);return}if(this.events.push(e),this.sizes.push(t),this.sizeSum+=t,this.events.length>this.maxSize){let i=this.events.length-this.maxSize;this.dropOldest(i),this.logger.warn(`queue cap reached; dropped ${i} event(s)`)}this.trimToBudget(),this.markDirty()}victimIndex(){for(let e=0;e<this.events.length;e++)if(!Gt(this.events[e]))return e;return 0}evictAt(e){this.events.splice(e,1),this.sizeSum-=this.sizes.splice(e,1)[0]??0}dropOldest(e){for(let t=0;t<e&&this.events.length>0;t++)this.evictAt(this.victimIndex())}get size(){return this.events.length}peek(e,t=1/0,i=0){let n=i;for(let s=0;n<this.events.length&&n-i<e&&(s+=this.sizes[n]+1,!(n>i&&s>t));n++);return this.events.slice(i,n)}remove(e){let t=new Set(e),i=[],n=[],s=0;for(let o=0;o<this.events.length;o++){let d=this.events[o];if(t.has(d.event_id))continue;let a=this.sizes[o];i.push(d),n.push(a),s+=a}this.events=i,this.sizes=n,this.sizeSum=s,this.markDirty()}close(){}clear(){this.reset([]),this.dirty=!1,this.storage.remove(v)}};function nt(r){return JSON.stringify(r).length}var ve=-1,ye=0,Jt=67108863;function y(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let n=0;n<16;n++)e[n]=Math.floor(Math.random()*256);e[0]=r/2**40&255,e[1]=r/2**32&255,e[2]=r/2**24&255,e[3]=r/2**16&255,e[4]=r/2**8&255,e[5]=r&255;let t=(e[6]&7)<<22|e[7]<<14|(e[8]&63)<<8|e[9];r===ve?t=ye=ye+1&Jt:r>ve&&(ve=r,ye=t),e[6]=112|t>>>22,e[7]=t>>>14&255,e[8]=128|t>>>8&63,e[9]=t&255;let i="";for(let n=0;n<16;n++)i+=(e[n]+256).toString(16).slice(1);return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function A(r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r))return null;let e=r.slice(0,8)+r.slice(9,13),t=parseInt(e,16);return Number.isFinite(t)?t:null}var st=["depsmith_anonymous_id","depsmith_anon_reset_at","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker","depsmith_campaign","depsmith_referrer","depsmith_super_props"],w=class{constructor(){this.data=new Map}get(e){return this.data.get(e)??null}set(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}},F=class{constructor(e){this.domain=e}get(e){try{let t=`${encodeURIComponent(e)}=`;for(let i of document.cookie.split("; "))if(i.startsWith(t))return decodeURIComponent(i.slice(t.length))}catch{}return null}attributes(e){let t=this.domain?`; domain=${this.domain}`:"",i=typeof location<"u"&&location.protocol==="https:"?"; Secure":"";return`${t}; path=/; max-age=${e}; SameSite=Lax${i}`}set(e,t){try{document.cookie=`${encodeURIComponent(e)}=${encodeURIComponent(t)}${this.attributes(3456e4)}`}catch{}}remove(e){try{document.cookie=`${encodeURIComponent(e)}=${this.attributes(0)}`}catch{}}},R="depsmith_anon_reset_at",Zt=new Set(["depsmith_anonymous_id",R]),j=class{constructor(e,t,i=Zt){this.primary=e;this.secondary=t;this.mirrored=i}get(e){let t=this.primary.get(e);if(!this.mirrored.has(e))return t;let i=this.secondary.get(e);if(t===i)return t;if(t===null&&i!==null)return this.primary.set(e,i),i;if(i===null&&t!==null)return this.secondary.set(e,t),t;let n=this.pick(t,i);return this.primary.set(e,n),this.secondary.set(e,n),n}pick(e,t){let i=A(e),n=A(t);if(i===null||n===null)return e;let s=[this.primary,this.secondary],o=Math.max(...s.map(a=>Number(a.get(R))||0));o&&s.forEach(a=>a.set(R,`${o}`));let d=i>=o;return d!==n>=o?d?e:t:i<=n?e:t}set(e,t){this.primary.set(e,t),this.mirrored.has(e)&&this.secondary.set(e,t)}remove(e){this.primary.remove(e),this.secondary.remove(e)}},be=class{constructor(e,t=st){this.backend=e;this.keys=t;this.mirror=new Map;this.hydrated=null}hydrate(){return this.hydrated??(this.hydrated=Promise.all(this.keys.map(async e=>{try{let t=await this.backend.getItem(e);typeof t=="string"&&!this.mirror.has(e)&&this.mirror.set(e,t)}catch{}})).then(()=>{})),this.hydrated}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),Promise.resolve(this.backend.setItem(e,t)).catch(()=>{})}remove(e){this.mirror.delete(e),Promise.resolve(this.backend.removeItem(e)).catch(()=>{})}};var I=class{constructor(e){this.ls=e}get(e){try{return this.ls.getItem(e)}catch{return null}}set(e,t){try{this.ls.setItem(e,t)}catch{}}remove(e){try{this.ls.removeItem(e)}catch{}}},Y=class{constructor(e="depsmith-sdk"){this.mirror=new Map;this.snapshot=new Map;this.db=null;this.ready=this.open(e)}open(e){return new Promise(t=>{try{let i=indexedDB.open(e,1);i.onupgradeneeded=()=>i.result.createObjectStore("kv"),i.onsuccess=()=>{this.db=i.result;let n=this.db.transaction("kv","readonly").objectStore("kv"),s=n.getAllKeys(),o=n.getAll();o.onsuccess=()=>{let d=s.result;o.result.forEach((a,u)=>{let c=d[u];c!==void 0&&(this.snapshot.set(c,a),this.mirror.has(c)||this.mirror.set(c,a))}),t()},o.onerror=()=>t()},i.onerror=()=>t()}catch{t()}})}hydrate(){return this.ready.then(()=>this.snapshot)}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").put(t,e)}catch{}})}remove(e){this.mirror.delete(e),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").delete(e)}catch{}})}};function ot(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new I(window.localStorage)}}catch{}return new w}function at(r,e){return r==="indexeddb"&&typeof indexedDB<"u"?new Y:e}function dt(r,e,t,i,n,s){return r instanceof Y?r.hydrate().then(o=>{try{let d="depsmith_consent";if(o.get(d)==="denied"&&!e.get(d)&&t.optOut(),n||!t.canCapture()){i.clear();return}let a=o.get("depsmith_queue");a&&i.prepend(JSON.parse(a))}catch{s.warn("persisted queue corrupt; discarded")}}):Promise.resolve()}function ut(r){try{let e=JSON.parse(r||"[]");return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.event_id=="string"):null}catch{return null}}var W=class extends z{constructor(...t){super(...t);this.known=new Set(this.ids());this.removed=new Set;this.area=null;this.onStorage=t=>{if(t.key!==v||t.storageArea!==this.area)return;let i=ut(t.newValue);if(!i)return;let n=new Set;for(let o of i)n.add(o.event_id);let s=[];if(this.known.forEach(o=>{n.has(o)||s.push(o)}),s.length!==0){for(let o of s)this.known.delete(o),this.removed.add(o);this.remove(s)}};let i=this.storage instanceof I?this.storage.ls:this.storage.ls;if(!(!i||typeof i.getItem!="function")){this.area=i;try{typeof window<"u"&&window.addEventListener("storage",this.onStorage)}catch{}}}ids(){return this.events.map(t=>t.event_id)}persistNow(){if(!this.dirty)return;this.dirty=!1;let t=new Set(this.ids());this.known.forEach(o=>{t.has(o)||this.removed.add(o)});let i=[],n=new Set;for(let o of ut(this.storage.get(v))??[])n.add(o.event_id),!t.has(o.event_id)&&!this.removed.has(o.event_id)&&i.push(o);let s=JSON.stringify(this.bounded(i).concat(this.events));if(this.storage.set(v,s),this.storage.get(v)!==s){this.known=new Set([...t].filter(o=>n.has(o))),this.dirty=!0;return}this.known=t,this.removed.forEach(o=>{n.has(o)||this.removed.delete(o)})}bounded(t){if(t.length===0)return t;let i=this.maxSize-this.events.length,n=this.maxChars-this.serializedLength(),s=[];for(let o=t.length-1;o>=0&&i>0;o--){let d=JSON.stringify(t[o]).length+1;if(d>n)break;n-=d,i--,s.push(t[o])}return s.reverse()}clear(){super.clear(),this.known.clear(),this.removed.clear()}close(){try{typeof window<"u"&&window.removeEventListener("storage",this.onStorage)}catch{}}};var Se="depsmith_anonymous_id",we="depsmith_user_id",ke="depsmith_group_id",X="depsmith_user_props",H=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(Se);return e||(e=y(this.clock.now()),this.storage.set(Se,e)),e}get userId(){return this.storage.get(we)}get groupId(){return this.storage.get(ke)}identify(e){this.storage.set(we,e)}setGroup(e){this.storage.set(ke,e)}getUserProps(){try{return JSON.parse(this.storage.get(X)??"{}")}catch{return{}}}setUserProp(e,t){let i=this.getUserProps();i[e]=t,this.storage.set(X,JSON.stringify(i))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(X,JSON.stringify(t))}reset(){this.storage.remove(we),this.storage.remove(ke),this.storage.remove(X);let e=this.clock.now();this.storage.set(R,`${e}`);let t=y(e);return this.storage.set(Se,t),t}};var ct="depsmith_session",Q=class{constructor(e,t,i,n=$){this.storage=e;this.clock=t;this.timeoutMs=i;this.pending=null;this.scheduled=!1;this.schedule=n}load(){let e=this.readStored(),t=this.pending;return t?!e||t.lastActivityAt>=e.lastActivityAt?t:(this.pending=null,e):e}readStored(){try{let e=this.storage.get(ct);if(!e)return null;let t=JSON.parse(e);return typeof t.id!="string"||typeof t.lastActivityAt!="number"?null:(typeof t.startedAt!="number"&&(t.startedAt=A(t.id)??t.lastActivityAt),t)}catch{return null}}save(e){this.pending=e,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){let e=this.pending;e&&(this.pending=null,this.storage.set(ct,JSON.stringify(e)))}mint(e){let t={id:y(e),lastActivityAt:e,startedAt:e};return this.save(t),t}touch(){let e=this.clock.now(),t=this.load();if(!t){let i=this.mint(e);return{sessionId:i.id,startedAt:e,startedSession:{id:i.id,startedAt:e}}}if(e-t.lastActivityAt>this.timeoutMs){let i=this.mint(e);return{sessionId:i.id,startedAt:e,endedSession:{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt},startedSession:{id:i.id,startedAt:e}}}return this.save({id:t.id,lastActivityAt:e,startedAt:t.startedAt}),{sessionId:t.id,startedAt:t.startedAt}}peek(){let e=this.load();return e?e.id:this.mint(this.clock.now()).id}adopt(e,t){let i=A(e);return i===null?!1:(this.save({id:e,lastActivityAt:this.clock.now(),startedAt:t??i}),!0)}rotate(){return this.mint(this.clock.now()).id}};function k(r,e){if(r==null)return{};if(typeof r!="object"||Array.isArray(r))return e.warn("properties must be an object; ignoring",r),{};let t={},i=0;for(let[n,s]of Object.entries(r)){if(i>=200){e.warn("properties exceed 200 keys; excess dropped");break}let o=er(s,e);if(o===void 0){e.debug(`property "${n}" dropped (unsupported value)`);continue}t[String(n)]=o,i++}return t}function _e(r){if(r===null)return null;let e=typeof r;if(e==="string"||e==="boolean")return r;if(e==="number")return Number.isFinite(r)?r:void 0;if(r instanceof Date)return isNaN(r.getTime())?void 0:r.toISOString()}function er(r,e){let t=_e(r);if(t!==void 0)return t;if(!(r===void 0||typeof r=="function"||typeof r=="symbol")){if(Array.isArray(r)){let i=[];for(let n of r.slice(0,100)){let s=_e(n);i.push(s!==void 0?s:pt(n))}return i}if(typeof r=="object"){let i={},n=0;for(let[s,o]of Object.entries(r)){if(n>=50){e.debug("nested object exceeds 50 keys; excess dropped");break}let d=_e(o);i[String(s)]=d!==void 0?d:pt(o),n++}return i}}}function pt(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}function G(r,e,t){let i={...r},n;for(let s in i)m(s,e,t)&&(n=delete i[s]);return n?i:r}function m(r,e,t){return r?.[0]!=="$"?!1:(t.warn(`${e}: "$"-prefixed keys are reserved; ignored "${r}"`),!0)}function tr(r,e){let t=r?.name;return t==="AbortError"||t!=="TimeoutError"&&!!e?.aborted}function rr(r){let e=r?.message;return typeof e=="string"&&e?e.slice(0,255):"network error"}function ir(r){return r>=500}function lt(r){let e={};try{let t=new URL(r,typeof location<"u"?location.href:void 0);e.$net_url=`${t.origin}${t.pathname}`,t.search.length>1&&(e.$net_query=t.search.slice(1)),t.hash.length>1&&(e.$net_fragment=t.hash.slice(1))}catch{e.$net_url=r.slice(0,255)}return e}function nr(r){try{let e=r?.get("content-length");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}catch{return}}function sr(r,e){let t=Object.prototype.toString.call(r)==="[object Request]"?r:void 0;return{raw:String(t?t.url:r),method:String(e?.method??t?.method??"GET").toUpperCase(),signal:e?.signal??t?.signal}}function ft(r,e){if(r.autocapture&&r.autocapture.networkErrors===!1||typeof fetch!="function")return{stop:()=>{}};let i=fetch,n=r.endpoint.replace(/\/+$/,""),s=!1,o=0,d=new Set,a=p=>{let f=Date.now();return f-o>=6e4&&(o=f,d=new Set),d.size>=10||d.has(p)?!1:(d.add(p),!0)},u=(p,f)=>{try{let g=f();a(`${String(g.$net_method)} ${String(g.$net_url)} ${p}`)&&e(g)}catch{}},c=function(...p){let f=Date.now(),g=i.apply(this,p);if(s||typeof g?.then!="function")return g;let b,ie,Te;try{if({raw:b,method:ie,signal:Te}=sr(p[0],p[1]),b.startsWith(n))return g}catch{return g}let Ot=p[1];return g.then(h=>(ir(h.status)&&u(h.status,()=>({...lt(b),$net_method:ie,$net_status:h.status,$net_start:f,$net_end:Date.now(),$net_duration_ms:Date.now()-f,...or(Ot,h)})),h),h=>{throw typeof navigator<"u"&&navigator.onLine===!1||tr(h,Te)||u("error",()=>({...lt(b),$net_method:ie,$net_error_message:rr(h),$net_start:f,$net_end:Date.now(),$net_duration_ms:Date.now()-f})),h})};return globalThis.fetch=c,{stop:()=>{s=!0,globalThis.fetch===c&&(globalThis.fetch=i)}}}function or(r,e){let t={},i=typeof r?.body=="string"?r.body.length:void 0;i!==void 0&&(t.$net_req_bytes=i);let n=nr(e.headers);return n!==void 0&&(t.$net_res_bytes=n),t}function J(r){return Math.round(r)}function gt(){let r,e,t,i=0,n=!1,s,o=[],d=(a,u)=>{try{let c=new PerformanceObserver(p=>u(p.getEntries()));c.observe({type:a,buffered:!0}),o.push(c)}catch{}};d("largest-contentful-paint",a=>{let u=a[a.length-1];u&&(r=J(u.startTime))}),d("paint",a=>{for(let u of a)u.name==="first-contentful-paint"&&(e=J(u.startTime))}),d("layout-shift",a=>{for(let u of a)u.hadRecentInput||(i+=u.value??0,n=!0)}),d("event",a=>{for(let u of a){let c=J(u.duration);(t===void 0||c>t)&&(t=c)}});try{let[a]=performance.getEntriesByType("navigation"),u=a;u?.responseStart!==void 0&&u.responseStart>0&&(s=J(u.responseStart))}catch{}return{snapshot(){let a={};return r!==void 0&&(a.$wv_lcp=r),e!==void 0&&(a.$wv_fcp=e),t!==void 0&&(a.$wv_inp=t),n&&(a.$wv_cls=Math.round(i*1e3)/1e3),s!==void 0&&(a.$wv_ttfb=s),a},hasAny(){return r!==void 0||e!==void 0||t!==void 0||n||s!==void 0},stop(){for(let a of o.splice(0))try{a.disconnect()}catch{}}}}var Pe="depsmith_super_props";function ht(r,e){return r.length===0?(e.warn("register: empty property key ignored"),!1):!m(r,"register",e)}var Z=class{constructor(e,t){this.storage=e;this.logger=t;this.properties={};try{let i=this.storage.get(Pe);if(i){let n=JSON.parse(i);n&&typeof n=="object"&&!Array.isArray(n)&&(this.properties=n)}}catch{}}register(e){let t=!1;for(let[i,n]of Object.entries(e))ht(i,this.logger)&&(this.properties[i]=n,t=!0);t&&this.persist()}registerOnce(e){let t=!1;for(let[i,n]of Object.entries(e))ht(i,this.logger)&&(Object.prototype.hasOwnProperty.call(this.properties,i)||(this.properties[i]=n,t=!0));t&&this.persist()}unregister(e){Object.prototype.hasOwnProperty.call(this.properties,e)&&(delete this.properties[e],this.persist())}clear(){if(Object.keys(this.properties).length!==0){this.properties={};try{this.storage.remove(Pe)}catch{}}}current(){return{...this.properties}}persist(){try{this.storage.set(Pe,JSON.stringify(this.properties))}catch{this.logger.debug("register: could not persist super properties")}}};var ar=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],mt=50,vt=200;function xe(r,e){if(!r||typeof r!="object")return;if(r.$clear_all===!0){let s=Object.keys(r).filter(o=>o!=="$clear_all");return s.length>0&&e.warn(`$clear_all is exclusive; ignored ${s.join(", ")}`),{$clear_all:!0}}let t={},i=new Set,n=(s,o)=>m(s,o,e)?!1:i.has(s)?(e.debug(`"${s}" has an operator already; ${o} dropped`),!1):(i.add(s),!0);for(let s of ar){let o=r[s];if(!o||typeof o!="object")continue;let d=k(o,e),a={};for(let[u,c]of Object.entries(d))n(u,s)&&(a[u]=c);Object.keys(a).length>0&&(t[s]=a)}if(r.$add&&typeof r.$add=="object"){let s={},o=0;for(let[d,a]of Object.entries(r.$add)){if(o>=mt){e.debug(`$add over ${mt} keys; excess dropped`);break}if(typeof a!="number"||!Number.isFinite(a)){e.debug(`$add "${d}" is not finite; dropped`);continue}n(d,"$add")&&(s[d]=a,o++)}Object.keys(s).length>0&&(t.$add=s)}if(Array.isArray(r.$unset)){let s=[];for(let o of r.$unset){if(s.length>=vt){e.debug(`$unset over ${vt} keys; excess dropped`);break}typeof o!="string"||o.length===0||n(o,"$unset")&&s.push(o)}s.length>0&&(t.$unset=s)}return Object.keys(t).length>0?t:void 0}function Ee(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var yt={now:()=>Date.now()};function _(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function ee(r){return r===0||r===408||r===429||r>=500}var dr=1e3,ur=32e3;function bt(r,e=Math.random){let t=Math.min(dr*2**r,ur);return Math.round(e()*t)}function St(r,e){if(!r)return 0;let t=Number(r),i=t===t?t*1e3:Date.parse(r)-e;return i>0?i:0}async function cr(r){let e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new TextEncoder().encode(r)).catch(()=>{}),t.close().catch(()=>{});let i=e.readable.getReader(),n=[];for(;;){let{done:a,value:u}=await i.read();if(a)break;n.push(u)}let s=n.reduce((a,u)=>a+u.length,0),o=new Uint8Array(new ArrayBuffer(s)),d=0;for(let a of n)o.set(a,d),d+=a.length;return o}async function wt(r,e){if(e==="none"||typeof CompressionStream>"u")return null;try{return await cr(r)}catch{return null}}function kt(r,e,t,i,n){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let s=t.breaker;if(!t.isOnline()||s?.open()||s?.suspect())return;let o=i;for(let d=0;d<10;d++){let a=r.peek(e.batchSize,48e3,o);if(!a.length)return;let u=n(a);if(navigator.sendBeacon(`${e.endpoint}/e/`,new Blob([JSON.stringify(u)],{type:"text/plain"})))r.remove(a.map(p=>p.event_id));else{if(a.length>1)return;o++}}}catch{}}function pr(r){return r.map(e=>e.event_id)}var lr=3e4,fr=6e4,gr=256e3;function hr(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var mr=399;function Ae(r){return r>299&&r<400||r===401||r===403}var vr=3e4,yr=60*6e4,te=class{constructor(e,t,i){this.queue=e;this.config=t;this.deps=i;this.inFlight=null;this.uploading=0;this.limit=0;this.strikes=0;this.wait=0}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){return this.inFlight?this.inFlight:(this.inFlight=this.drain().catch(e=>this.deps.logger.error("flush failed",e)).finally(()=>{this.inFlight=null}),this.inFlight)}async drain(){for(this.limit=0;this.queue.size>0;){if(!this.deps.isOnline()){this.deps.logger.debug("offline; deferring upload");return}if(this.deps.breaker?.open()){this.deps.logger.debug("uploads paused");return}let e=this.config.batchSize,t=this.queue.peek(this.limit||e,gr);this.queue.persistNow(),this.uploading=t.length;let i=await this.uploadWithRetry(t);if(this.uploading=0,Ae(i)||ee(i))return;if(i===400||i===413){if(t.length>1){this.limit=t.length>>1;continue}this.limit=0}if(i>299&&this.deps.logger.notice(`collector answered ${i}; dropped ${t.length} event(s)`),this.queue.remove(pr(t)),i===400)return}}async uploadWithRetry(e){let t=this.deps.breaker,i=!1,n=0;for(let s=0;s<=this.config.maxRetries&&!(s&&(this.deps.canUpload?.()===!1||this.queue.peek(1)[0]?.event_id!==e[0].event_id)||(n=await this.post(e),n&&(i=!0),!ee(n)||this.wait)||(this.deps.logger.debug(`upload attempt ${s+1} failed (${n})`),!i&&t?.suspect()));s++)s<this.config.maxRetries&&await this.deps.sleep(bt(s));return i?(t?.ok(),n>199&&n<300?this.strikes=0:(Ae(n)||ee(n))&&(Ae(n)&&this.deps.logger.notice(`collector refused uploads (${n}); paused`),t?.hold(this.wait||Math.min(vr*2**this.strikes++,yr)))):t?.fail(),n}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:_(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){this.wait=0;let t=JSON.stringify(this.buildPayload(e)),i=typeof AbortController<"u"?new AbortController:null,n=null;try{let s={"Content-Type":"application/json"},o=await wt(t,this.config.compression);o&&(s["Content-Encoding"]="gzip");let d=o??t,a=hr(d)<=fr;a||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let u={method:"POST",headers:s,body:d,keepalive:a};i&&(u.signal=i.signal,n=setTimeout(()=>i.abort(),this.timeoutMs()));let c=await this.deps.fetchFn(`${this.config.endpoint}/e/`,u);return c.redirected?mr:(this.wait=St(c.headers?.get("Retry-After"),this.deps.clock.now()),c.status)}catch{return 0}finally{n!==null&&clearTimeout(n)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:lr}sendBeaconAll(){kt(this.queue,this.config,this.deps,this.uploading,e=>this.buildPayload(e))}};var N="depsmith_net_breaker";function _t(r,e){let t=!1,i=0,n=0,s=3e5,o=(u,c,p)=>typeof u=="number"&&u===u?Math.min(Math.max(u,c),p):c,d=()=>{if(!t){t=!0;try{let u=JSON.parse(r.get(N)??"0");if(!Array.isArray(u))return;i=o(u[0],0,3),n=o(u[1],0,e.now()+36e5),s=o(u[2],3e5,36e5)}catch{}}},a=()=>{try{i||n>e.now()?r.set(N,JSON.stringify([i,n,s])):r.remove(N)}catch{}};return{open:()=>(d(),e.now()<(n=Math.min(n,e.now()+36e5))),suspect:()=>(d(),i>0),fail:()=>{d(),++i>=3&&(n=e.now()+s,s=Math.min(s*2,36e5),i=3),a()},ok:()=>{d(),i&&(i=n=0,s=3e5,a())},hold:u=>{d(),n=Math.max(n,e.now()+Math.min(u,36e5)),a()}}}var re=class{constructor(e){this.enabled=e}setEnabled(e){this.enabled=e}debug(...e){this.enabled&&console.debug("[depsmith-sdk]",...e)}warn(...e){this.enabled&&console.warn("[depsmith-sdk]",...e)}notice(...e){console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var Pt=["url","referrer","previous_url","initial_url"],br=["$ac_href","$ac_form_action","$net_url","$fr_error_file"];function xt(r,e){let t=r.split("#")[0],i=t.indexOf("?");if(i<0)return t;let n=t.slice(i+1).split("&").filter(s=>e.has(Sr(s)));return t.slice(0,i)+(n.length?`?${n.join("&")}`:"")}function Sr(r){let e=r.split("=")[0].replace(/\+/g," ");try{return decodeURIComponent(e)}catch{return e}}function Et(r,e){if(e)try{let t=e.keepParams,i=new Set(Array.isArray(t)?t:[]),n=[[r.context.page,Pt],[r.context.referrer,Pt],[r.properties,br]];for(let[o,d]of n)for(let a of d){let u=o?.[a];typeof u=="string"&&(o[a]=xt(u,i))}let s=r.properties;if(!s)return;if(delete s.$net_fragment,typeof s.$net_query=="string"){let o=xt(`?${s.$net_query}`,i).slice(1);o?s.$net_query=o:delete s.$net_query}}catch{}}var Oe="depsmith_config_fp",At=255,M=class{constructor(e,t={}){this.vitalsReported=!1;this.stopped=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=Be(e),this.logger=new re(this.config.debug),this.clock=t.clock??yt,this.storage=t.storage??this.pickStorage();let i=t.storage?this.storage:at(this.config.storage,this.storage);this.contextProvider=t.contextProvider,this.pageLife=new D({now:()=>this.clock.now(),capture:(a,u,c,p,f)=>this.capture(a,u,c,void 0,void 0,p,f)},this.config);let n=this.config.childSafeMode?new w:this.config.storage==="memory"?this.storage:new j(this.storage,new F(this.config.cookieDomain||void 0));if(this.identity=new H(n,this.clock),this.session=new Q(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new q(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??it())),typeof window<"u"&&typeof window.addEventListener=="function"){let a=u=>{u.key===E&&this.followConsentElsewhere()};try{window.addEventListener("storage",a),this.teardownFns.push(()=>window.removeEventListener("storage",a))}catch{}}this.attribution=new L(n),this.superProperties=new Z(this.storage,this.logger),!this.contextProvider&&typeof window<"u"&&window.location&&(this.attribution.recordLanding(window.location.href,typeof document<"u"?document.referrer:""),this.pageLife.start(window.location.href,typeof document<"u"?document.referrer:""));let s=de(this.config.apiKey),o={ls:i.ls,get:a=>i.get(a),set:(a,u)=>{this.storage.get(Oe)===s&&i.set(a,u)},remove:a=>i.remove(a)};this.queue=new W(o,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule});let d=this.detectConfigDrift(s);this.primeDeviceSignals(),this.ready=dt(i,this.storage,this.consent,this.queue,d,this.logger),this.uploader=new te(this.queue,{endpoint:this.config.endpoint,apiKey:this.config.apiKey,batchSize:this.config.batchSize,maxRetries:this.config.maxRetries,compression:this.config.compression,anonymizeIp:this.config.anonymizeIp,requestTimeoutMs:t.requestTimeoutMs},{fetchFn:t.fetchFn??((...a)=>fetch(...a)),clock:this.clock,logger:this.logger,sleep:t.sleep??(a=>new Promise(u=>setTimeout(u,a))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:_t(this.storage,this.clock),canUpload:()=>this.consent.canUpload()}),t.manualLifecycle||(this.lifecycle=Me({intervalMs:this.config.batchIntervalMs,guard:a=>this.guard(a),vitals:()=>this.emitWebVitals(),leave:()=>this.leaveOnUnload?.(),restored:a=>this.pageLife.restored(a),resume:()=>this.resumeSession(),flushIfQueued:()=>this.flushIfQueued(),persistNow:()=>this.persistNow(),beacon:()=>{this.consent.canUpload()&&this.uploader.sendBeaconAll()},online:()=>{this.uploader.resetNetworkBreaker(),this.flushIfQueued()}}),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.trackInternal(e,G(t,"track",this.logger))}trackInternal(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}m(e,"track",this.logger)||this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}traits(e,t){return k(G(e,t,this.logger),this.logger)}tooLong(e,t){return e.length<=At?!1:(this.logger.warn(`${t} exceeds ${At} characters (got ${e.length}); dropped`),!0)}page(e,t,i){this.pageInternal(e,G(t,"page",this.logger),i)}pageInternal(e,t,i){this.guard(()=>this.pageLife.manual(e,t,i?.type))}emitWebVitals(){this.vitalsReported||!this.vitals?.hasAny()||(this.vitalsReported=!0,this.capture("$web_vitals","track",this.vitals.snapshot()))}screen(e,t,i){this.page(e,t,i)}identify(e,t){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(e,"identify: userId"))return;this.identity.identify(e);let i=this.traits(t,"identify");this.capture("$identify","identify",void 0,i,Ee("$set",i))})}alias(e){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:e})})}reset(){this.guard(()=>{this.pageLife.flushPending(),this.identity.reset(),this.session.rotate(),this.attribution.clear(),this.superProperties.clear(),this.logger.debug("reset: identity, session and attribution cleared")})}group(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("group: groupId required");return}if(this.tooLong(e,"group: groupId"))return;this.identity.setGroup(e);let i=this.traits(t,"group");this.capture("$group","group",void 0,i)})}setGroupTraits(e){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}let t=this.traits(e,"setGroupTraits");this.capture("$group","group",void 0,t)})}setProperty(e,t){this.guard(()=>{m(e,"setProperty",this.logger)||this.setUserProp(e,t,"$set")})}setUserProp(e,t,i){this.identity.setUserProp(e,t);let n=k({[e]:t},this.logger);this.capture("$identify","identify",void 0,n,Ee(i,n))}setOnceProperty(e,t){this.guard(()=>{if(!m(e,"setOnceProperty",this.logger)){if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.setUserProp(e,t,"$set_once")}})}unsetProperty(e){this.guard(()=>{m(e,"unsetProperty",this.logger)||(this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},xe({$unset:[e]},this.logger)))})}register(e){this.guard(()=>this.superProperties.register(e))}registerOnce(e){this.guard(()=>this.superProperties.registerOnce(e))}unregister(e){this.guard(()=>this.superProperties.unregister(e))}setUserProperties(e){this.guard(()=>{let t=xe(e,this.logger);t&&this.capture("$identify","identify",void 0,void 0,t)})}optIn(){this.guard(()=>{this.consent.optIn(),this.logger.debug("consent granted"),this.primeDeviceSignals(),this.flushUploads()})}followConsentElsewhere(){this.guard(()=>{let e=this.consent.current;this.consent.reload()&&(this.consent.current==="denied"&&e!=="denied"?(this.pageLife.discardPending(),this.queue.clear(),this.logger.debug("consent denied in another tab; queue cleared")):this.consent.canUpload()&&this.flushUploads())})}optOut(){this.guard(()=>{this.pageLife.discardPending(),this.consent.optOut(),this.queue.clear(),this.logger.debug("consent denied; queue cleared")})}async flush(){try{if(!this.consent.canUpload()){this.logger.debug("flush skipped: consent not granted");return}await this.flushUploads()}catch(e){this.logger.error("flush error",e)}}autocapture(e){this.guard(()=>this.capture("$autocapture","autocapture",e))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(e,t){this.guard(()=>{(typeof e!="string"||!this.session.adopt(e,t))&&this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(e)}"`)})}shutdown(){this.guard(()=>this.pageLife.flushPending()),this.stopped=!0,this.lifecycle?.stop();for(let e of this.teardownFns.splice(0))e();this.persistNow(),this.queue.close()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}deviceSignals(){return!this.config.childSafeMode&&this.consent.canUpload()}primeDeviceSignals(){this.deviceSignals()&&(this.config.deviceFingerprinting&&We(),this.config.geolocation&&tt(()=>this.deviceSignals()))}enqueueEvent(e){Et(e,this.config.scrubUrls),this.queue.enqueue(e),this.lifecycle?.rearm()}flushUploads(){return this.ready.then(()=>this.uploader.flush())}flushIfQueued(){this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}let t=this.deviceSignals();return{fingerprint:this.config.deviceFingerprinting&&t,geolocation:this.config.geolocation&&t,overrides:e,tracking:this.config.trackingOptions,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(e){return this.config.sampleRate>=1?!0:Fe(`${this.config.apiKey}:${e}`)<this.config.sampleRate}inSample(e,t){return t==="identify"||t==="alias"||t==="group"?!0:this.sessionInSample(e)}capture(e,t,i,n,s,o,d){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let a=this.touchSession();if(!this.inSample(a.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let u=o??this.clock.now(),c=this.contextOptions();d&&(c.page=d);let p={event_id:y(u),event:e,event_type:t,timestamp:_(u),session_id:a.sessionId,session_started_at:_(a.startedAt),anonymous_id:this.identity.anonymousId,context:n?{...B(c),traits:n}:B(c),platform:"Web",sdk_version:T};s&&(p.user_properties=s);let f=k({...this.config.defaultProperties,...this.superProperties.current(),...k(i,this.logger)},this.logger);Object.keys(f).length>0&&(p.properties=f);let g=this.identity.userId;g&&(p.user_id=g);let b=this.identity.groupId;b&&(p.group_id=b),c.fingerprint&&(p.device_id=le(this.config.apiKey)),this.enqueueEvent(p),this.logger.debug(`captured ${e}`,p),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(e){let t=this.storage.get(Oe),i=t!==null&&t!==e;return i&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear(),this.storage.remove(N)),this.storage.set(Oe,e),i}pickStorage(){return this.config.storage==="memory"?new w:ot()}enqueueSessionBoundary(e,t,i,n){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug(`session_${e} dropped (consent denied)`);return}let s=this.contextOptions(),o={event_id:y(this.clock.now()),event:`$session_${e}`,event_type:`session_${e}`,timestamp:_(i),session_id:t,session_started_at:_(n),anonymous_id:this.identity.anonymousId,context:B(s),platform:"Web",sdk_version:T},d=this.identity.userId;d&&(o.user_id=d),s.fingerprint&&(o.device_id=le(this.config.apiKey),e==="start"&&(o.properties=Qe())),this.enqueueEvent(o)}touchSession(){let e=this.session.touch();if(e.startedSession&&this.pageLife.newSession(),e.endedSession&&this.sessionInSample(e.endedSession.id)){let t=e.endedSession;this.enqueueSessionBoundary("end",t.id,t.lastActivityAt,t.startedAt)}if(e.startedSession&&this.sessionInSample(e.startedSession.id)){let t=e.startedSession;this.enqueueSessionBoundary("start",t.id,t.startedAt,t.startedAt)}return e}resumeSession(){this.consent.canCapture()&&this.touchSession()}startAutocapture(){let e=this.config.autocapture;if(!e||typeof window>"u")return;typeof PerformanceObserver<"u"&&(this.vitals=gt(),this.teardownFns.push(()=>this.vitals?.stop()));let t=ft(this.config,i=>this.guard(()=>this.capture("$network_request","track",i)));this.teardownFns.push(()=>t.stop()),De().then(i=>{i&&(this.stopped||(this.teardownFns.push(i.startAutocapture(e,{emit:n=>this.autocapture(n),page:n=>this.guard(()=>this.pageLife.autoPageView(n)),pageLeave:n=>this.guard(()=>this.pageLife.leave(n)),warn:n=>this.logger.warn(n),armUnloadLeave:n=>{this.leaveOnUnload=n}})),this.teardownFns.push(()=>{this.leaveOnUnload=void 0})))}).catch(i=>this.logger.debug("autocapture load failed",i))}guard(e){try{e()}catch(t){this.logger.error("internal error",t)}}};var l=null,Ce=null,tn={init(r,e){try{return l&&Ce===r.apiKey?l:typeof window>"u"&&r.storage!=="memory"&&!e?.storage?(r.debug&&console.warn("[depsmith-sdk] init skipped: no window"),null):(l?.shutdown(),l=new M(r,e),Ce=r.apiKey,l)}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>l?.track(r,e),page:(r,e,t)=>l?.page(r,e,t),screen:(r,e,t)=>l?.screen(r,e,t),identify:(r,e)=>l?.identify(r,e),alias:r=>l?.alias(r),reset:()=>l?.reset(),group:(r,e)=>l?.group(r,e),setGroupTraits:r=>l?.setGroupTraits(r),setProperty:(r,e)=>l?.setProperty(r,e),setOnceProperty:(r,e)=>l?.setOnceProperty(r,e),unsetProperty:r=>l?.unsetProperty(r),setUserProperties:r=>l?.setUserProperties(r),register:r=>l?.register(r),registerOnce:r=>l?.registerOnce(r),unregister:r=>l?.unregister(r),optIn:()=>l?.optIn(),optOut:()=>l?.optOut(),flush:()=>l?.flush()??Promise.resolve(),getAnonymousId:()=>l?.getAnonymousId(),getSessionId:()=>l?.getSessionId(),setSessionId:(r,e)=>l?.setSessionId(r,e),shutdown(){l?.shutdown(),l=null,Ce=null}};export{be as AsyncMirrorAdapter,st as DEPSMITH_SDK_STORAGE_KEYS,tn as DepsmithSdk,M as DepsmithSdkClient,$ as idleScheduler,Xt as syncScheduler};
|
|
1
|
+
var ie=class{constructor(){this.counter=0}recordPage(e,t){return e===this.currentUrl?!1:(this.currentUrl===void 0?t?(this.previousUrl=t,this.previousType=Me(t,e)?"internal":"external"):this.previousType="direct":(this.previousUrl=this.currentUrl,this.previousType=Me(this.currentUrl,e)?"internal":"external"),this.currentUrl=e,this.counter+=1,!0)}tracking(){let e={};return this.previousUrl!==void 0&&(e.previous_url=this.previousUrl),this.previousType!==void 0&&(e.previous_type=this.previousType),this.counter>0&&(e.counter=this.counter),e}get pageCount(){return this.counter}get current(){return this.currentUrl}resetForNewSession(){this.counter=this.currentUrl===void 0?0:1}},D=class{constructor(e,t={autocapture:!1}){this.sink=e;this.pages=new ie;this.enteredAt=0;this.left=!1;this.rules=Nt(t.pageNames),this.byHref=!!t.autocapture&&t.autocapture.pageviews==="all"}start(e,t){this.pages.recordPage(e,t),this.enteredAt=this.sink.now()}get pageCount(){return this.pages.pageCount}recordExplicit(){this.record(),this.lastViewed=this.pageKey(),this.autoViewed=void 0}manual(e,t,n){let i=this.pending;if(i&&this.keyOf(i.location)===this.pageKey())this.discardPending();else{this.flushPending();let s=this.autoViewed;if(this.autoViewed=void 0,s&&s.url===Ne()&&this.sink.now()-s.at<=It)return}this.recordExplicit(),this.sink.capture("$page_view","page_view",{...t,...Ie({source:"manual",name:e,type:n},this.rules),$page_counter:this.pages.pageCount})}autoPageView(e){this.flushPending(),this.record();let t=this.pageKey();if(t!==void 0&&t===this.lastViewed)return;this.lastViewed=t;let n=this.pages.pageCount;if(!e){this.emitView(location,n);return}let i=location.href,s={at:this.sink.now(),counter:n,location:new URL(i),page:{url:i,path:location.pathname,referrer:document.referrer,domain:P(i),url_base:U(i),...this.pages.tracking()},cancel:()=>{}};this.pending=s,s.cancel=e(document.title,()=>this.flushPending())}flushPending(){let e=this.pending;e&&(this.pending=void 0,e.cancel(),this.emitView(e.location,e.counter,e))}discardPending(){this.pending?.cancel(),this.pending=void 0}emitView(e,t,n){let i=document.title;this.autoViewed={url:e.href,at:this.sink.now()},this.sink.capture("$page_view","page_view",{...Ie({source:"auto",location:e,title:i},this.rules),$page_counter:t},n?.at,n&&{...n.page,title:i})}leave(e){this.flushPending();let t=this.pages.current;if(t===void 0||this.left)return;this.left=!0;let n={$page_duration_ms:Math.max(0,this.sink.now()-this.enteredAt)};e!==void 0&&(n.$page_max_scroll=e),this.leaving=t;try{this.sink.capture("$page_leave","page_leave",n)}finally{this.leaving=void 0}}restored(e){e&&(this.left=!1,this.enteredAt=this.sink.now())}newSession(){this.pages.resetForNewSession()}tracking(){let e=this.pages.tracking();return this.leaving===void 0?e:{...e,url:this.leaving,path:Dt(this.leaving),domain:P(this.leaving),url_base:U(this.leaving)}}pageKey(){let e=globalThis.location;return e&&this.keyOf(e)}keyOf(e){return this.byHref?e.href:e.pathname}record(){let e=Ne();if(e===void 0)return;this.pages.recordPage(e,typeof document<"u"?document.referrer:"")&&(this.enteredAt=this.sink.now(),this.left=!1)}},It=2e3;function Ie({source:r,name:e,type:t,location:n=globalThis.location,title:i=globalThis.document?.title},s){let o=n&&s?.(n),d=t?.trim()||o?.type;return{$page_name:e?.trim()||o?.name.trim()||i?.trim()||n?.pathname||"Unknown",...d?{$page_type:d}:{},$page_source:r}}function Nt(r){if(typeof r=="function")return t=>{try{let n=r(t);return typeof n=="string"?{name:n}:void 0}catch{return}};if(!r||typeof r!="object")return;let e=(Array.isArray(r)?r:Object.entries(r)).map(([t,n])=>[typeof t=="string"&&typeof n=="string"&&Mt(t),n]);return t=>{let n=De(t.pathname);for(let[i,s]of e)if(i&&i.test(n))return{name:s,type:s}}}function Mt(r){let e=De(r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\/\*\*|\*\*?/g,t=>t==="*"?"[^/]+":t==="**"?".*":"(?:/.*)?");return new RegExp(`^${e}$`)}function De(r){return r.replace(/(.)\/$/,"$1")}function Ne(){if(!(typeof window>"u"||!window.location))return window.location.href}function Me(r,e){try{return new URL(r).host===new URL(e).host}catch{return!1}}function Dt(r){try{return new URL(r).pathname||void 0}catch{return}}function P(r){try{return new URL(r).host||void 0}catch{return}}function U(r){try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return}}var Ut=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]],se="depsmith_campaign",oe="depsmith_referrer",L=class{constructor(e){this.storage=e;this.campaign={};this.referrer={};this.campaign=this.read(se)??{},this.referrer=this.read(oe)??{}}read(e){try{let t=this.storage.get(e);if(!t)return null;let n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}write(e,t){try{this.storage.set(e,JSON.stringify(t))}catch{}}recordLanding(e,t){let n,i;try{let u=new URL(e);n=u.searchParams,i=u.host}catch{return}let s={};for(let[u,c]of Ut){let l=n.get(u);l&&(s[c]=l)}Object.keys(s).length>0&&(this.campaign=s,this.write(se,s));let o=t?P(t):void 0,d=!!o&&o!==i,a=!1;d&&(this.referrer.url=t,this.referrer.domain=o,a=!0),this.referrer.initial_domain===void 0&&(this.referrer.initial_domain=d?o:"$direct",d&&(this.referrer.initial_url=t),a=!0),a&&this.write(oe,this.referrer)}campaignBlock(){return Object.keys(this.campaign).length>0?{...this.campaign}:void 0}referrerBlock(){return Object.keys(this.referrer).length>0?{...this.referrer}:void 0}clear(){this.campaign={},this.referrer={};try{this.storage.remove(se),this.storage.remove(oe)}catch{}}};function Ue(r){if(typeof window>"u"||typeof document>"u")return;let e=setInterval(()=>r.flushIfQueued(),r.intervalMs);e.unref?.();let t=!1,n,i=()=>{let a=n;clearTimeout(a),n=void 0,r.guard(()=>r.vitals()),r.guard(()=>r.leave()),!(t&&!a)&&(t=!0,r.beacon(),r.persistNow())},s=()=>{if(document.visibilityState==="hidden"){if(t)return;r.guard(()=>r.vitals()),t=!0,r.persistNow(),n=setTimeout(()=>{n=void 0,r.flushIfQueued()},0)}else clearTimeout(n),t=!1,r.resume()},o=a=>{t=!1,r.restored(a.persisted)},d=()=>r.online();return window.addEventListener("pagehide",i),window.addEventListener("pageshow",o),document.addEventListener("visibilitychange",s),window.addEventListener("online",d),{rearm:()=>{t=!1},stop:()=>{clearInterval(e),window.removeEventListener("pagehide",i),window.removeEventListener("pageshow",o),document.removeEventListener("visibilitychange",s),window.removeEventListener("online",d),clearTimeout(n)}}}function Le(){return import("./autocapture.js")}var ae=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["idfv","device","idfv"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screenSize","screen_size"],["timezone","timezone"],["userAgent","user_agent"]],Lt=Object.fromEntries(ae.map(([r])=>[r,!0]));function Ke(r){let e={...Lt};if(!r)return e;for(let[t]of ae)r[t]===!1&&(e[t]=!1);return e}function Ve(r,e){let t=r;for(let[n,i,s]of ae){if(e[n])continue;if(s===void 0){delete t[i];continue}let o={...t[i]};delete o[s],Object.keys(o).length>0?t[i]=o:delete t[i]}return r}var Be={clicks:"interactive",forms:!0,scrolls:!1,pageviews:"path",ignoredSelectors:[],selectorMaxDepth:5,selectorIgnore:[],attributes:[]};function qe(r){if(r===!0)return Be;if(!r||typeof r!="object")return!1;let e={...Be};for(let[i,s]of Object.entries(r))s!==void 0&&(e[i]=s);let{clicks:t,pageviews:n}=e;return e.clicks=t==="all"?"all":t?"interactive":!1,e.pageviews=n==="all"?"all":n?"path":!1,e}function ze(r){if(!r||typeof r.apiKey!="string"||r.apiKey.length===0)throw new Error("depsmith-sdk: apiKey is required");if(typeof r.endpoint!="string"||!/^https?:\/\//.test(r.endpoint))throw new Error("depsmith-sdk: endpoint must be an http(s) URL");let e=qe(r.autocapture);return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:x(r.batchSize,20,1,500),batchIntervalMs:x(r.batchIntervalMs,6e4,1e3,2**31-1),maxQueueSize:x(r.maxQueueSize,1e3,1),maxQueueBytes:x(r.maxQueueBytes,512*1024,4096),sessionTimeoutMs:x(r.sessionTimeoutMs,18e5,6e4),sampleRate:Fe(r.sampleRate,1,0,1),sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:x(r.maxRetries,5,0,10),debug:r.debug??!1,defaultProperties:r.defaultProperties??{},autocapture:e,compression:r.compression??"gzip",childSafeMode:r.childSafeMode??!1,anonymizeIp:(r.anonymizeIp??!1)||(r.childSafeMode??!1),deviceFingerprinting:r.deviceFingerprinting??!0,geolocation:r.geolocation??!1,scrubUrls:r.scrubUrls??!1,trackingOptions:Ke(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage",pageNames:r.pageNames}}function Fe(r,e,t,n=1/0){return Math.min(Math.max(Number.isFinite(r)?r:e,t),n)}function x(r,e,t,n){return Math.floor(Fe(r,e,t,n))}function de(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)>>>0;return e.toString(36)}function je(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e}function Kt(r){return je(r).toString(36)}function He(r){return je(r)/4294967296}function ue(r){return de(r)+Kt(r)}var ce={},Ye=!1;function Xe(){if(!Ye){Ye=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{ce=e}).catch(()=>{})}catch{}}}function pe(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,n=zt(e,t);n&&(r.browser=n);let i=jt(e);if(i){let d=Bt(i.name,ce.platformVersion);r.os=d?{...i,version:d}:i}let s=Ht(e,t);s&&(r.deviceType=s);let o=Vt(e,i);return o&&(r.device=o),r}function Vt(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let n=ce.model?.trim();return n?t.model=n:/iPhone/.test(r)?t.model="iPhone":/iPad/.test(r)&&(t.model="iPad"),t.manufacturer||t.model?t:void 0}function Bt(r,e){let t=e?.trim();if(t){if(r==="Windows"){let n=Number.parseInt(t.split(".")[0]??"",10);return!Number.isFinite(n)||n===0?void 0:n>=13?"11":"10"}return Qe(t)}}var qt=[{pattern:/Edg(?:e|A|iOS)?\/([\d.]+)/,name:"Edge",engine:"Blink"},{pattern:/OPR\/([\d.]+)/,name:"Opera",engine:"Blink"},{pattern:/Firefox\/([\d.]+)/,name:"Firefox",engine:"Gecko"},{pattern:/Chrome\/([\d.]+)/,name:"Chrome",engine:"Blink"},{pattern:/Version\/([\d.]+)/,name:"Safari",engine:"WebKit",requires:/Safari/}];function zt(r,e){for(let n of qt){if(n.requires&&!n.requires.test(r))continue;let i=r.match(n.pattern);if(i)return{name:n.name,version:i[1],engine:n.engine}}let t=e?.brands?.find(n=>!/not.?a.?brand/i.test(n.brand));if(t)return{name:t.brand,version:t.version}}var Ft=[{pattern:/Windows NT ([\d.]+)/,name:"Windows"},{pattern:/OS ([\d_]+)/,name:"iOS",requires:/iPhone|iPad|iPod/},{pattern:/Android ([\d.]+)/,name:"Android"},{pattern:/Mac OS X ([\d_]+)/,name:"macOS"}];function jt(r){for(let e of Ft){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:Qe((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function Qe(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function Ht(r,e){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(r))return"tablet";if(e?.mobile===!0||/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(r))return"mobile";if(/Android/.test(r))return"tablet";if(typeof navigator<"u"&&r)return"desktop"}var We=new Map,K=null;function Ge(){return K!==null||(K=Yt()),K}function le(r=""){let e=We.get(r);if(e!==void 0)return e;let t=Ge().map(i=>i.value).join("|"),n=ue(r?`project=${r}|${t}`:t);return We.set(r,n),n}function Je(){let r={};for(let e of Ge())r[`$fp_${e.name}`]=e.value;return r}function Yt(){let r=[];try{if(typeof screen<"u"&&r.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`}),typeof navigator<"u"){let e=navigator;r.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`}),r.push({name:"dm",value:`dm:${e.deviceMemory??""}`}),r.push({name:"plat",value:`plat:${navigator.platform??""}`}),r.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}r.push({name:"canvas",value:`canvas:${Wt()}`})}catch{}return r}function Wt(){try{if(typeof document>"u")return"";let r=document.createElement("canvas");r.width=240,r.height=60;let e=r.getContext("2d");return e?(e.textBaseline="top",e.font="14px 'Arial'",e.fillStyle="#f60",e.fillRect(10,10,100,30),e.fillStyle="#069",e.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15),e.strokeStyle="rgba(0,120,200,0.5)",e.arc(50,30,20,0,Math.PI*2),e.stroke(),ue(r.toDataURL())):""}catch{return""}}function Ze(){try{if(typeof navigator>"u")return{};let r=navigator.connection;if(!r)return{};let e=r.type;if(e==="wifi"||e==="ethernet"||e==="none")return{type:e};switch(r.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var C=null,tt=0,et=!1,O=!1,rt=null,V=()=>!0;function nt(r=V){if(V=r,!et){et=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let e=navigator.permissions;if(typeof e?.query!="function")return;e.query({name:"geolocation"}).then(t=>{rt=t,t.state==="granted"&&ge(),t.onchange=()=>{t.state==="granted"?ge():C=null}}).catch(()=>{})}catch{}}}function ge(){if(!(O||!V())){O=!0;try{navigator.geolocation.getCurrentPosition(r=>{O=!1;let{latitude:e,longitude:t,accuracy:n}=r.coords;if(!Number.isFinite(e)||!Number.isFinite(t))return;let i={latitude:e,longitude:t,source:"gps"};Number.isFinite(n)&&(i.accuracy=n),C=i,tt=Date.now()},()=>{O=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{O=!1}}}function it(){if(V()||(C=null),!!C)return Date.now()-tt>3e5&&rt?.state==="granted"&&ge(),{...C}}var he="@depsmith/depsmith-sdk",R="0.9.5",fe=null;function Xt(){if(fe)return fe;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),fe=r,r}function B(r={}){let e={library:{name:he,version:R}};S(()=>{if(typeof window<"u"&&window.location){let t=window.location.href;e.page={url:t,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0,domain:P(t),url_base:U(t),...r.page??{}}}}),S(()=>{typeof window<"u"&&window.screen&&(e.screen_size={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),S(()=>{let t=Xt();t.locale!==void 0&&(e.locale=t.locale),t.userAgent!==void 0&&(e.user_agent=t.userAgent),t.timezone!==void 0&&(e.timezone=t.timezone)}),S(()=>{let{deviceType:t}=pe();t&&(e.device={...e.device,type:t})}),S(()=>{if(r.attribution){let t=r.attribution.campaignBlock();t&&(e.campaign=t);let n=r.attribution.referrerBlock();n&&(e.referrer=n)}}),S(()=>{r.fingerprint&&Qt(e)}),S(()=>{if(r.geolocation){let t=it();t&&(e.location=t)}});try{if(r.overrides){for(let[t,n]of Object.entries(r.overrides))n!==void 0&&(e[t]=n);e.library={name:he,version:R}}}catch{}return r.tracking&&Ve(e,r.tracking),e}function Qt(r){let{browser:e,os:t,deviceType:n,device:i}=pe();e&&(r.browser=e),t&&(r.os=t);let s={...r.device};n&&(s.type=n),i?.manufacturer&&(s.manufacturer=i.manufacturer),i?.model&&(s.model=i.model),Object.keys(s).length>0&&(r.device=s);let o=Ze();o.type&&(r.network={...r.network,type:o.type})}function S(r){try{r()}catch{}}function st(){try{if(typeof navigator>"u")return!1;let r=navigator,e=typeof window<"u"?window:{},t=navigator.doNotTrack??e.doNotTrack??r.msDoNotTrack;return t==="1"||t==="yes"}catch{return!1}}var E="depsmith_consent";function Gt(r){return r==="granted"||r==="denied"||r==="pending"}var q=class{constructor(e,t,n){this.storage=e;this.dntActive=n;let i=e.get(E);this.state=i==="granted"||i==="denied"||i==="pending"?i:t}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.reload(),this.effective()==="granted"}reload(){let e=this.storage.get(E);return!Gt(e)||e===this.state?!1:(this.state=e,!0)}get current(){return this.effective()}optIn(){this.state="granted",this.storage.set(E,"granted")}optOut(){this.state="denied",this.storage.set(E,"denied")}};var T=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},Jt=r=>r();var v="depsmith_queue",Zt=512*1024,me=2,er=new Set(["identify","alias","group"]);function tr(r){return er.has(r?.event_type)}var z=class{constructor(e,t,n,i={}){this.storage=e;this.maxSize=t;this.logger=n;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=!1;this.scheduled=!1;this.maxChars=i.maxChars??Zt,this.schedule=i.schedule??T,this.restore()}restore(){try{let e=this.storage.get(v);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;let n=t.filter(i=>!!i&&typeof i=="object"&&typeof i.event_id=="string");this.reset(n),n.length!==t.length&&(this.logger.warn("discarded corrupt queued events on restore"),this.markDirty()),this.trimToBudget()&&this.markDirty()}catch{this.logger.warn("queue storage corrupt; starting empty"),this.reset([]),this.storage.remove(v)}}reset(e){this.events=e,this.sizes=e.map(t=>ot(t)),this.sizeSum=this.sizes.reduce((t,n)=>t+n,0)}serializedLength(){return this.events.length===0?me:this.sizeSum+(this.events.length-1)+me}trimToBudget(){let e=0;for(;this.events.length>0&&this.serializedLength()>this.maxChars;)this.evictAt(this.victimIndex()),e++;return e>0&&this.logger.warn(`queue byte cap reached; dropped ${e} event(s)`),e>0}markDirty(){this.dirty=!0,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){this.dirty&&(this.dirty=!1,this.storage.set(v,JSON.stringify(this.events)))}prepend(e){let t=new Set(this.events.map(i=>i.event_id)),n=e.filter(i=>!!i&&typeof i=="object"&&typeof i.event_id=="string"&&!t.has(i.event_id));n.length!==0&&(this.reset([...n,...this.events]),this.events.length>this.maxSize&&this.dropOldest(this.events.length-this.maxSize),this.trimToBudget(),this.markDirty())}enqueue(e){let t=ot(e);if(t+me>this.maxChars){this.logger.warn(`event ${e.event_id} exceeds the queue byte cap; dropped`);return}if(this.events.push(e),this.sizes.push(t),this.sizeSum+=t,this.events.length>this.maxSize){let n=this.events.length-this.maxSize;this.dropOldest(n),this.logger.warn(`queue cap reached; dropped ${n} event(s)`)}this.trimToBudget(),this.markDirty()}victimIndex(){for(let e=0;e<this.events.length;e++)if(!tr(this.events[e]))return e;return 0}evictAt(e){this.events.splice(e,1),this.sizeSum-=this.sizes.splice(e,1)[0]??0}dropOldest(e){for(let t=0;t<e&&this.events.length>0;t++)this.evictAt(this.victimIndex())}get size(){return this.events.length}peek(e,t=1/0,n=0){let i=n;for(let s=0;i<this.events.length&&i-n<e&&(s+=this.sizes[i]+1,!(i>n&&s>t));i++);return this.events.slice(n,i)}remove(e){let t=new Set(e),n=[],i=[],s=0;for(let o=0;o<this.events.length;o++){let d=this.events[o];if(t.has(d.event_id))continue;let a=this.sizes[o];n.push(d),i.push(a),s+=a}this.events=n,this.sizes=i,this.sizeSum=s,this.markDirty()}close(){}clear(){this.reset([]),this.dirty=!1,this.storage.remove(v)}};function ot(r){return JSON.stringify(r).length}var ve=-1,ye=0,rr=67108863;function y(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let i=0;i<16;i++)e[i]=Math.floor(Math.random()*256);e[0]=r/2**40&255,e[1]=r/2**32&255,e[2]=r/2**24&255,e[3]=r/2**16&255,e[4]=r/2**8&255,e[5]=r&255;let t=(e[6]&7)<<22|e[7]<<14|(e[8]&63)<<8|e[9];r===ve?t=ye=ye+1&rr:r>ve&&(ve=r,ye=t),e[6]=112|t>>>22,e[7]=t>>>14&255,e[8]=128|t>>>8&63,e[9]=t&255;let n="";for(let i=0;i<16;i++)n+=(e[i]+256).toString(16).slice(1);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function A(r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r))return null;let e=r.slice(0,8)+r.slice(9,13),t=parseInt(e,16);return Number.isFinite(t)?t:null}var at=["depsmith_anonymous_id","depsmith_anon_reset_at","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker","depsmith_campaign","depsmith_referrer","depsmith_super_props"],w=class{constructor(){this.data=new Map}get(e){return this.data.get(e)??null}set(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}},F=class{constructor(e){this.domain=e}get(e){try{let t=`${encodeURIComponent(e)}=`;for(let n of document.cookie.split("; "))if(n.startsWith(t))return decodeURIComponent(n.slice(t.length))}catch{}return null}attributes(e){let t=this.domain?`; domain=${this.domain}`:"",n=typeof location<"u"&&location.protocol==="https:"?"; Secure":"";return`${t}; path=/; max-age=${e}; SameSite=Lax${n}`}set(e,t){try{document.cookie=`${encodeURIComponent(e)}=${encodeURIComponent(t)}${this.attributes(3456e4)}`}catch{}}remove(e){try{document.cookie=`${encodeURIComponent(e)}=${this.attributes(0)}`}catch{}}},$="depsmith_anon_reset_at",nr=new Set(["depsmith_anonymous_id",$]),j=class{constructor(e,t,n=nr){this.primary=e;this.secondary=t;this.mirrored=n}get(e){let t=this.primary.get(e);if(!this.mirrored.has(e))return t;let n=this.secondary.get(e);if(t===n)return t;if(t===null&&n!==null)return this.primary.set(e,n),n;if(n===null&&t!==null)return this.secondary.set(e,t),t;let i=this.pick(t,n);return this.primary.set(e,i),this.secondary.set(e,i),i}pick(e,t){let n=A(e),i=A(t);if(n===null||i===null)return e;let s=[this.primary,this.secondary],o=Math.max(...s.map(a=>Number(a.get($))||0));o&&s.forEach(a=>a.set($,`${o}`));let d=n>=o;return d!==i>=o?d?e:t:n<=i?e:t}set(e,t){this.primary.set(e,t),this.mirrored.has(e)&&this.secondary.set(e,t)}remove(e){this.primary.remove(e),this.secondary.remove(e)}},be=class{constructor(e,t=at){this.backend=e;this.keys=t;this.mirror=new Map;this.hydrated=null}hydrate(){return this.hydrated??(this.hydrated=Promise.all(this.keys.map(async e=>{try{let t=await this.backend.getItem(e);typeof t=="string"&&!this.mirror.has(e)&&this.mirror.set(e,t)}catch{}})).then(()=>{})),this.hydrated}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),Promise.resolve(this.backend.setItem(e,t)).catch(()=>{})}remove(e){this.mirror.delete(e),Promise.resolve(this.backend.removeItem(e)).catch(()=>{})}};var I=class{constructor(e){this.ls=e}get(e){try{return this.ls.getItem(e)}catch{return null}}set(e,t){try{this.ls.setItem(e,t)}catch{}}remove(e){try{this.ls.removeItem(e)}catch{}}},H=class{constructor(e="depsmith-sdk"){this.mirror=new Map;this.snapshot=new Map;this.db=null;this.ready=this.open(e)}open(e){return new Promise(t=>{try{let n=indexedDB.open(e,1);n.onupgradeneeded=()=>n.result.createObjectStore("kv"),n.onsuccess=()=>{this.db=n.result;let i=this.db.transaction("kv","readonly").objectStore("kv"),s=i.getAllKeys(),o=i.getAll();o.onsuccess=()=>{let d=s.result;o.result.forEach((a,u)=>{let c=d[u];c!==void 0&&(this.snapshot.set(c,a),this.mirror.has(c)||this.mirror.set(c,a))}),t()},o.onerror=()=>t()},n.onerror=()=>t()}catch{t()}})}hydrate(){return this.ready.then(()=>this.snapshot)}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").put(t,e)}catch{}})}remove(e){this.mirror.delete(e),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").delete(e)}catch{}})}};function dt(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new I(window.localStorage)}}catch{}return new w}function ut(r,e){return r==="indexeddb"&&typeof indexedDB<"u"?new H:e}function ct(r,e,t,n,i,s){return r instanceof H?r.hydrate().then(o=>{try{let d="depsmith_consent";if(o.get(d)==="denied"&&!e.get(d)&&t.optOut(),i||!t.canCapture()){n.clear();return}let a=o.get("depsmith_queue");a&&n.prepend(JSON.parse(a))}catch{s.warn("persisted queue corrupt; discarded")}}):Promise.resolve()}function pt(r){try{let e=JSON.parse(r||"[]");return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.event_id=="string"):null}catch{return null}}var Y=class extends z{constructor(...t){super(...t);this.known=new Set(this.ids());this.removed=new Set;this.area=null;this.onStorage=t=>{if(t.key!==v||t.storageArea!==this.area)return;let n=pt(t.newValue);if(!n)return;let i=new Set;for(let o of n)i.add(o.event_id);let s=[];if(this.known.forEach(o=>{i.has(o)||s.push(o)}),s.length!==0){for(let o of s)this.known.delete(o),this.removed.add(o);this.remove(s)}};let n=this.storage instanceof I?this.storage.ls:this.storage.ls;if(!(!n||typeof n.getItem!="function")){this.area=n;try{typeof window<"u"&&window.addEventListener("storage",this.onStorage)}catch{}}}ids(){return this.events.map(t=>t.event_id)}persistNow(){if(!this.dirty)return;this.dirty=!1;let t=new Set(this.ids());this.known.forEach(o=>{t.has(o)||this.removed.add(o)});let n=[],i=new Set;for(let o of pt(this.storage.get(v))??[])i.add(o.event_id),!t.has(o.event_id)&&!this.removed.has(o.event_id)&&n.push(o);let s=JSON.stringify(this.bounded(n).concat(this.events));if(this.storage.set(v,s),this.storage.get(v)!==s){this.known=new Set([...t].filter(o=>i.has(o))),this.dirty=!0;return}this.known=t,this.removed.forEach(o=>{i.has(o)||this.removed.delete(o)})}bounded(t){if(t.length===0)return t;let n=this.maxSize-this.events.length,i=this.maxChars-this.serializedLength(),s=[];for(let o=t.length-1;o>=0&&n>0;o--){let d=JSON.stringify(t[o]).length+1;if(d>i)break;i-=d,n--,s.push(t[o])}return s.reverse()}clear(){super.clear(),this.known.clear(),this.removed.clear()}close(){try{typeof window<"u"&&window.removeEventListener("storage",this.onStorage)}catch{}}};var Se="depsmith_anonymous_id",we="depsmith_user_id",ke="depsmith_group_id",W="depsmith_user_props",X=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(Se);return e||(e=y(this.clock.now()),this.storage.set(Se,e)),e}get userId(){return this.storage.get(we)}get groupId(){return this.storage.get(ke)}identify(e){this.storage.set(we,e)}setGroup(e){this.storage.set(ke,e)}getUserProps(){try{return JSON.parse(this.storage.get(W)??"{}")}catch{return{}}}setUserProp(e,t){let n=this.getUserProps();n[e]=t,this.storage.set(W,JSON.stringify(n))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(W,JSON.stringify(t))}reset(){this.storage.remove(we),this.storage.remove(ke),this.storage.remove(W);let e=this.clock.now();this.storage.set($,`${e}`);let t=y(e);return this.storage.set(Se,t),t}};var lt="depsmith_session",Q=class{constructor(e,t,n,i=T){this.storage=e;this.clock=t;this.timeoutMs=n;this.pending=null;this.scheduled=!1;this.schedule=i}load(){let e=this.readStored(),t=this.pending;return t?!e||t.lastActivityAt>=e.lastActivityAt?t:(this.pending=null,e):e}readStored(){try{let e=this.storage.get(lt);if(!e)return null;let t=JSON.parse(e);return typeof t.id!="string"||typeof t.lastActivityAt!="number"?null:(typeof t.startedAt!="number"&&(t.startedAt=A(t.id)??t.lastActivityAt),t)}catch{return null}}save(e){this.pending=e,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){let e=this.pending;e&&(this.pending=null,this.storage.set(lt,JSON.stringify(e)))}mint(e){let t={id:y(e),lastActivityAt:e,startedAt:e};return this.save(t),t}touch(){let e=this.clock.now(),t=this.load();if(!t){let n=this.mint(e);return{sessionId:n.id,startedAt:e,startedSession:{id:n.id,startedAt:e}}}if(e-t.lastActivityAt>this.timeoutMs){let n=this.mint(e);return{sessionId:n.id,startedAt:e,endedSession:{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt},startedSession:{id:n.id,startedAt:e}}}return this.save({id:t.id,lastActivityAt:e,startedAt:t.startedAt}),{sessionId:t.id,startedAt:t.startedAt}}peek(){let e=this.load();return e?e.id:this.mint(this.clock.now()).id}adopt(e,t){let n=A(e);return n===null?!1:(this.save({id:e,lastActivityAt:this.clock.now(),startedAt:t??n}),!0)}rotate(){return this.mint(this.clock.now()).id}};function k(r,e){if(r==null)return{};if(typeof r!="object"||Array.isArray(r))return e.warn("properties must be an object; ignoring",r),{};let t={},n=0;for(let[i,s]of Object.entries(r)){if(n>=200){e.warn("properties exceed 200 keys; excess dropped");break}let o=ir(s,e);if(o===void 0){e.debug(`property "${i}" dropped (unsupported value)`);continue}t[String(i)]=o,n++}return t}function _e(r){if(r===null)return null;let e=typeof r;if(e==="string"||e==="boolean")return r;if(e==="number")return Number.isFinite(r)?r:void 0;if(r instanceof Date)return isNaN(r.getTime())?void 0:r.toISOString()}function ir(r,e){let t=_e(r);if(t!==void 0)return t;if(!(r===void 0||typeof r=="function"||typeof r=="symbol")){if(Array.isArray(r)){let n=[];for(let i of r.slice(0,100)){let s=_e(i);n.push(s!==void 0?s:gt(i))}return n}if(typeof r=="object"){let n={},i=0;for(let[s,o]of Object.entries(r)){if(i>=50){e.debug("nested object exceeds 50 keys; excess dropped");break}let d=_e(o);n[String(s)]=d!==void 0?d:gt(o),i++}return n}}}function gt(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}function G(r,e,t){let n={...r},i;for(let s in n)m(s,e,t)&&(i=delete n[s]);return i?n:r}function m(r,e,t){return r?.[0]!=="$"?!1:(t.warn(`${e}: "$"-prefixed keys are reserved; ignored "${r}"`),!0)}function sr(r,e){let t=r?.name;return t==="AbortError"||t!=="TimeoutError"&&!!e?.aborted}function or(r){let e=r?.message;return typeof e=="string"&&e?e.slice(0,255):"network error"}function ar(r){return r>=500}function ft(r){let e={};try{let t=new URL(r,typeof location<"u"?location.href:void 0);e.$net_url=`${t.origin}${t.pathname}`,t.search.length>1&&(e.$net_query=t.search.slice(1)),t.hash.length>1&&(e.$net_fragment=t.hash.slice(1))}catch{e.$net_url=r.slice(0,255)}return e}function dr(r){try{let e=r?.get("content-length");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}catch{return}}function ur(r,e){let t=Object.prototype.toString.call(r)==="[object Request]"?r:void 0;return{raw:String(t?t.url:r),method:String(e?.method??t?.method??"GET").toUpperCase(),signal:e?.signal??t?.signal}}function ht(r,e){if(r.autocapture&&r.autocapture.networkErrors===!1||typeof fetch!="function")return{stop:()=>{}};let n=fetch,i=r.endpoint.replace(/\/+$/,""),s=!1,o=0,d=new Set,a=l=>{let g=Date.now();return g-o>=6e4&&(o=g,d=new Set),d.size>=10||d.has(l)?!1:(d.add(l),!0)},u=(l,g)=>{try{let f=g();a(`${String(f.$net_method)} ${String(f.$net_url)} ${l}`)&&e(f)}catch{}},c=function(...l){let g=Date.now(),f=n.apply(this,l);if(s||typeof f?.then!="function")return f;let b,ne,$e;try{if({raw:b,method:ne,signal:$e}=ur(l[0],l[1]),b.startsWith(i))return f}catch{return f}let $t=l[1];return f.then(h=>(ar(h.status)&&u(h.status,()=>({...ft(b),$net_method:ne,$net_status:h.status,$net_start:g,$net_end:Date.now(),$net_duration_ms:Date.now()-g,...cr($t,h)})),h),h=>{throw typeof navigator<"u"&&navigator.onLine===!1||sr(h,$e)||u("error",()=>({...ft(b),$net_method:ne,$net_error_message:or(h),$net_start:g,$net_end:Date.now(),$net_duration_ms:Date.now()-g})),h})};return globalThis.fetch=c,{stop:()=>{s=!0,globalThis.fetch===c&&(globalThis.fetch=n)}}}function cr(r,e){let t={},n=typeof r?.body=="string"?r.body.length:void 0;n!==void 0&&(t.$net_req_bytes=n);let i=dr(e.headers);return i!==void 0&&(t.$net_res_bytes=i),t}function J(r){return Math.round(r)}function mt(){let r,e,t,n=0,i=!1,s,o=[],d=(a,u)=>{try{let c=new PerformanceObserver(l=>u(l.getEntries()));c.observe({type:a,buffered:!0}),o.push(c)}catch{}};d("largest-contentful-paint",a=>{let u=a[a.length-1];u&&(r=J(u.startTime))}),d("paint",a=>{for(let u of a)u.name==="first-contentful-paint"&&(e=J(u.startTime))}),d("layout-shift",a=>{for(let u of a)u.hadRecentInput||(n+=u.value??0,i=!0)}),d("event",a=>{for(let u of a){let c=J(u.duration);(t===void 0||c>t)&&(t=c)}});try{let[a]=performance.getEntriesByType("navigation"),u=a;u?.responseStart!==void 0&&u.responseStart>0&&(s=J(u.responseStart))}catch{}return{snapshot(){let a={};return r!==void 0&&(a.$wv_lcp=r),e!==void 0&&(a.$wv_fcp=e),t!==void 0&&(a.$wv_inp=t),i&&(a.$wv_cls=Math.round(n*1e3)/1e3),s!==void 0&&(a.$wv_ttfb=s),a},hasAny(){return r!==void 0||e!==void 0||t!==void 0||i||s!==void 0},stop(){for(let a of o.splice(0))try{a.disconnect()}catch{}}}}var Pe="depsmith_super_props";function vt(r,e){return r.length===0?(e.warn("register: empty property key ignored"),!1):!m(r,"register",e)}var Z=class{constructor(e,t){this.storage=e;this.logger=t;this.properties={};try{let n=this.storage.get(Pe);if(n){let i=JSON.parse(n);i&&typeof i=="object"&&!Array.isArray(i)&&(this.properties=i)}}catch{}}register(e){let t=!1;for(let[n,i]of Object.entries(e))vt(n,this.logger)&&(this.properties[n]=i,t=!0);t&&this.persist()}registerOnce(e){let t=!1;for(let[n,i]of Object.entries(e))vt(n,this.logger)&&(Object.prototype.hasOwnProperty.call(this.properties,n)||(this.properties[n]=i,t=!0));t&&this.persist()}unregister(e){Object.prototype.hasOwnProperty.call(this.properties,e)&&(delete this.properties[e],this.persist())}clear(){if(Object.keys(this.properties).length!==0){this.properties={};try{this.storage.remove(Pe)}catch{}}}current(){return{...this.properties}}persist(){try{this.storage.set(Pe,JSON.stringify(this.properties))}catch{this.logger.debug("register: could not persist super properties")}}};var pr=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],yt=50,bt=200;function xe(r,e){if(!r||typeof r!="object")return;if(r.$clear_all===!0){let s=Object.keys(r).filter(o=>o!=="$clear_all");return s.length>0&&e.warn(`$clear_all is exclusive; ignored ${s.join(", ")}`),{$clear_all:!0}}let t={},n=new Set,i=(s,o)=>m(s,o,e)?!1:n.has(s)?(e.debug(`"${s}" has an operator already; ${o} dropped`),!1):(n.add(s),!0);for(let s of pr){let o=r[s];if(!o||typeof o!="object")continue;let d=k(o,e),a={};for(let[u,c]of Object.entries(d))i(u,s)&&(a[u]=c);Object.keys(a).length>0&&(t[s]=a)}if(r.$add&&typeof r.$add=="object"){let s={},o=0;for(let[d,a]of Object.entries(r.$add)){if(o>=yt){e.debug(`$add over ${yt} keys; excess dropped`);break}if(typeof a!="number"||!Number.isFinite(a)){e.debug(`$add "${d}" is not finite; dropped`);continue}i(d,"$add")&&(s[d]=a,o++)}Object.keys(s).length>0&&(t.$add=s)}if(Array.isArray(r.$unset)){let s=[];for(let o of r.$unset){if(s.length>=bt){e.debug(`$unset over ${bt} keys; excess dropped`);break}typeof o!="string"||o.length===0||i(o,"$unset")&&s.push(o)}s.length>0&&(t.$unset=s)}return Object.keys(t).length>0?t:void 0}function Ee(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var St={now:()=>Date.now()};function _(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function ee(r){return r===0||r===408||r===429||r>=500}var lr=1e3,gr=32e3;function wt(r,e=Math.random){let t=Math.min(lr*2**r,gr);return Math.round(e()*t)}function kt(r,e){if(!r)return 0;let t=Number(r),n=t===t?t*1e3:Date.parse(r)-e;return n>0?n:0}async function fr(r){let e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new TextEncoder().encode(r)).catch(()=>{}),t.close().catch(()=>{});let n=e.readable.getReader(),i=[];for(;;){let{done:a,value:u}=await n.read();if(a)break;i.push(u)}let s=i.reduce((a,u)=>a+u.length,0),o=new Uint8Array(new ArrayBuffer(s)),d=0;for(let a of i)o.set(a,d),d+=a.length;return o}async function _t(r,e){if(e==="none"||typeof CompressionStream>"u")return null;try{return await fr(r)}catch{return null}}function Pt(r,e,t,n,i){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let s=t.breaker;if(!t.isOnline()||s?.open()||s?.suspect())return;let o=n;for(let d=0;d<10;d++){let a=r.peek(e.batchSize,48e3,o);if(!a.length)return;let u=i(a);if(navigator.sendBeacon(`${e.endpoint}/e/`,new Blob([JSON.stringify(u)],{type:"text/plain"})))r.remove(a.map(l=>l.event_id));else{if(a.length>1)return;o++}}}catch{}}function hr(r){return r.map(e=>e.event_id)}var mr=3e4,vr=6e4,yr=256e3;function br(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var Sr=399;function Ae(r){return r>299&&r<400||r===401||r===403}var wr=3e4,kr=60*6e4,te=class{constructor(e,t,n){this.queue=e;this.config=t;this.deps=n;this.inFlight=null;this.uploading=0;this.limit=0;this.strikes=0;this.wait=0}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){return this.inFlight?this.inFlight:(this.inFlight=this.drain().catch(e=>this.deps.logger.error("flush failed",e)).finally(()=>{this.inFlight=null}),this.inFlight)}async drain(){for(this.limit=0;this.queue.size>0;){if(!this.deps.isOnline()){this.deps.logger.debug("offline; deferring upload");return}if(this.deps.breaker?.open()){this.deps.logger.debug("uploads paused");return}let e=this.config.batchSize,t=this.queue.peek(this.limit||e,yr);this.queue.persistNow(),this.uploading=t.length;let n=await this.uploadWithRetry(t);if(this.uploading=0,Ae(n)||ee(n))return;if(n===400||n===413){if(t.length>1){this.limit=t.length>>1;continue}this.limit=0}if(n>299&&this.deps.logger.notice(`collector answered ${n}; dropped ${t.length} event(s)`),this.queue.remove(hr(t)),n===400)return}}async uploadWithRetry(e){let t=this.deps.breaker,n=!1,i=0;for(let s=0;s<=this.config.maxRetries&&!(s&&(this.deps.canUpload?.()===!1||this.queue.peek(1)[0]?.event_id!==e[0].event_id)||(i=await this.post(e),i&&(n=!0),!ee(i)||this.wait)||(this.deps.logger.debug(`upload attempt ${s+1} failed (${i})`),!n&&t?.suspect()));s++)s<this.config.maxRetries&&await this.deps.sleep(wt(s));return n?(t?.ok(),i>199&&i<300?this.strikes=0:(Ae(i)||ee(i))&&(Ae(i)&&this.deps.logger.notice(`collector refused uploads (${i}); paused`),t?.hold(this.wait||Math.min(wr*2**this.strikes++,kr)))):t?.fail(),i}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:_(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){this.wait=0;let t=JSON.stringify(this.buildPayload(e)),n=typeof AbortController<"u"?new AbortController:null,i=null;try{let s={"Content-Type":"application/json"},o=await _t(t,this.config.compression);o&&(s["Content-Encoding"]="gzip");let d=o??t,a=br(d)<=vr;a||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let u={method:"POST",headers:s,body:d,keepalive:a};n&&(u.signal=n.signal,i=setTimeout(()=>n.abort(),this.timeoutMs()));let c=await this.deps.fetchFn(`${this.config.endpoint}/e/`,u);return c.redirected?Sr:(this.wait=kt(c.headers?.get("Retry-After"),this.deps.clock.now()),c.status)}catch{return 0}finally{i!==null&&clearTimeout(i)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:mr}sendBeaconAll(){Pt(this.queue,this.config,this.deps,this.uploading,e=>this.buildPayload(e))}};var N="depsmith_net_breaker";function xt(r,e){let t=!1,n=0,i=0,s=3e5,o=(u,c,l)=>typeof u=="number"&&u===u?Math.min(Math.max(u,c),l):c,d=()=>{if(!t){t=!0;try{let u=JSON.parse(r.get(N)??"0");if(!Array.isArray(u))return;n=o(u[0],0,3),i=o(u[1],0,e.now()+36e5),s=o(u[2],3e5,36e5)}catch{}}},a=()=>{try{n||i>e.now()?r.set(N,JSON.stringify([n,i,s])):r.remove(N)}catch{}};return{open:()=>(d(),e.now()<(i=Math.min(i,e.now()+36e5))),suspect:()=>(d(),n>0),fail:()=>{d(),++n>=3&&(i=e.now()+s,s=Math.min(s*2,36e5),n=3),a()},ok:()=>{d(),n&&(n=i=0,s=3e5,a())},hold:u=>{d(),i=Math.max(i,e.now()+Math.min(u,36e5)),a()}}}var re=class{constructor(e){this.enabled=e}setEnabled(e){this.enabled=e}debug(...e){this.enabled&&console.debug("[depsmith-sdk]",...e)}warn(...e){this.enabled&&console.warn("[depsmith-sdk]",...e)}notice(...e){console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var Et=["url","referrer","previous_url","initial_url"],_r=["$ac_href","$ac_form_action","$net_url","$fr_error_file"];function At(r,e){let t=r.split("#")[0],n=t.indexOf("?");if(n<0)return t;let i=t.slice(n+1).split("&").filter(s=>e.has(Pr(s)));return t.slice(0,n)+(i.length?`?${i.join("&")}`:"")}function Pr(r){let e=r.split("=")[0].replace(/\+/g," ");try{return decodeURIComponent(e)}catch{return e}}function Ot(r,e){if(e)try{let t=e.keepParams,n=new Set(Array.isArray(t)?t:[]),i=[[r.context.page,Et],[r.context.referrer,Et],[r.properties,_r]];for(let[o,d]of i)for(let a of d){let u=o?.[a];typeof u=="string"&&(o[a]=At(u,n))}let s=r.properties;if(!s)return;if(delete s.$net_fragment,typeof s.$net_query=="string"){let o=At(`?${s.$net_query}`,n).slice(1);o?s.$net_query=o:delete s.$net_query}}catch{}}var Oe="depsmith_config_fp",Ct=255,M=class{constructor(e,t={}){this.vitalsReported=!1;this.stopped=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=ze(e),this.logger=new re(this.config.debug),this.clock=t.clock??St,this.storage=t.storage??this.pickStorage();let n=t.storage?this.storage:ut(this.config.storage,this.storage);this.contextProvider=t.contextProvider,this.pageLife=new D({now:()=>this.clock.now(),capture:(a,u,c,l,g)=>this.capture(a,u,c,void 0,void 0,l,g)},this.config);let i=this.config.childSafeMode?new w:this.config.storage==="memory"?this.storage:new j(this.storage,new F(this.config.cookieDomain||void 0));if(this.identity=new X(i,this.clock),this.session=new Q(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new q(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??st())),typeof window<"u"&&typeof window.addEventListener=="function"){let a=u=>{u.key===E&&this.followConsentElsewhere()};try{window.addEventListener("storage",a),this.teardownFns.push(()=>window.removeEventListener("storage",a))}catch{}}this.attribution=new L(i),this.superProperties=new Z(this.storage,this.logger),!this.contextProvider&&typeof window<"u"&&window.location&&(this.attribution.recordLanding(window.location.href,typeof document<"u"?document.referrer:""),this.pageLife.start(window.location.href,typeof document<"u"?document.referrer:""));let s=de(this.config.apiKey),o={ls:n.ls,get:a=>n.get(a),set:(a,u)=>{this.storage.get(Oe)===s&&n.set(a,u)},remove:a=>n.remove(a)};this.queue=new Y(o,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule});let d=this.detectConfigDrift(s);this.primeDeviceSignals(),this.ready=ct(n,this.storage,this.consent,this.queue,d,this.logger),this.uploader=new te(this.queue,{endpoint:this.config.endpoint,apiKey:this.config.apiKey,batchSize:this.config.batchSize,maxRetries:this.config.maxRetries,compression:this.config.compression,anonymizeIp:this.config.anonymizeIp,requestTimeoutMs:t.requestTimeoutMs},{fetchFn:t.fetchFn??((...a)=>fetch(...a)),clock:this.clock,logger:this.logger,sleep:t.sleep??(a=>new Promise(u=>setTimeout(u,a))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:xt(this.storage,this.clock),canUpload:()=>this.consent.canUpload()}),t.manualLifecycle||(this.lifecycle=Ue({intervalMs:this.config.batchIntervalMs,guard:a=>this.guard(a),vitals:()=>this.emitWebVitals(),leave:()=>this.leaveOnUnload?.(),restored:a=>this.pageLife.restored(a),resume:()=>this.resumeSession(),flushIfQueued:()=>this.flushIfQueued(),persistNow:()=>this.persistNow(),beacon:()=>{this.consent.canUpload()&&this.uploader.sendBeaconAll()},online:()=>{this.uploader.resetNetworkBreaker(),this.flushIfQueued()}}),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.trackInternal(e,G(t,"track",this.logger))}trackInternal(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}m(e,"track",this.logger)||this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}traits(e,t){return k(G(e,t,this.logger),this.logger)}tooLong(e,t){return e.length<=Ct?!1:(this.logger.warn(`${t} exceeds ${Ct} characters (got ${e.length}); dropped`),!0)}page(e,t,n){this.pageInternal(e,G(t,"page",this.logger),n)}pageInternal(e,t,n){this.guard(()=>this.pageLife.manual(e,t,n?.type))}emitWebVitals(){this.vitalsReported||!this.vitals?.hasAny()||(this.vitalsReported=!0,this.capture("$web_vitals","track",this.vitals.snapshot()))}screen(e,t,n){this.page(e,t,n)}identify(e,t){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(e,"identify: userId"))return;this.identity.identify(e);let n=this.traits(t,"identify");this.capture("$identify","identify",void 0,n,Ee("$set",n))})}alias(e){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:e})})}reset(){this.guard(()=>{this.pageLife.flushPending(),this.identity.reset(),this.session.rotate(),this.attribution.clear(),this.superProperties.clear(),this.logger.debug("reset: identity, session and attribution cleared")})}group(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("group: groupId required");return}if(this.tooLong(e,"group: groupId"))return;this.identity.setGroup(e);let n=this.traits(t,"group");this.capture("$group","group",void 0,n)})}setGroupTraits(e){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}let t=this.traits(e,"setGroupTraits");this.capture("$group","group",void 0,t)})}setProperty(e,t){this.guard(()=>{m(e,"setProperty",this.logger)||this.setUserProp(e,t,"$set")})}setUserProp(e,t,n){this.identity.setUserProp(e,t);let i=k({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,Ee(n,i))}setOnceProperty(e,t){this.guard(()=>{if(!m(e,"setOnceProperty",this.logger)){if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.setUserProp(e,t,"$set_once")}})}unsetProperty(e){this.guard(()=>{m(e,"unsetProperty",this.logger)||(this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},xe({$unset:[e]},this.logger)))})}register(e){this.guard(()=>this.superProperties.register(e))}registerOnce(e){this.guard(()=>this.superProperties.registerOnce(e))}unregister(e){this.guard(()=>this.superProperties.unregister(e))}setUserProperties(e){this.guard(()=>{let t=xe(e,this.logger);t&&this.capture("$identify","identify",void 0,void 0,t)})}optIn(){this.guard(()=>{this.consent.optIn(),this.logger.debug("consent granted"),this.primeDeviceSignals(),this.flushUploads()})}followConsentElsewhere(){this.guard(()=>{let e=this.consent.current;this.consent.reload()&&(this.consent.current==="denied"&&e!=="denied"?(this.pageLife.discardPending(),this.queue.clear(),this.logger.debug("consent denied in another tab; queue cleared")):this.consent.canUpload()&&this.flushUploads())})}optOut(){this.guard(()=>{this.pageLife.discardPending(),this.consent.optOut(),this.queue.clear(),this.logger.debug("consent denied; queue cleared")})}async flush(){try{if(!this.consent.canUpload()){this.logger.debug("flush skipped: consent not granted");return}await this.flushUploads()}catch(e){this.logger.error("flush error",e)}}autocapture(e){this.guard(()=>this.capture("$autocapture","autocapture",e))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(e,t){this.guard(()=>{(typeof e!="string"||!this.session.adopt(e,t))&&this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(e)}"`)})}shutdown(){this.guard(()=>this.pageLife.flushPending()),this.stopped=!0,this.lifecycle?.stop();for(let e of this.teardownFns.splice(0))e();this.persistNow(),this.queue.close()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}deviceSignals(){return!this.config.childSafeMode&&this.consent.canUpload()}primeDeviceSignals(){this.deviceSignals()&&(this.config.deviceFingerprinting&&Xe(),this.config.geolocation&&nt(()=>this.deviceSignals()))}enqueueEvent(e){Ot(e,this.config.scrubUrls),this.queue.enqueue(e),this.lifecycle?.rearm()}flushUploads(){return this.ready.then(()=>this.uploader.flush())}flushIfQueued(){this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}let t=this.deviceSignals();return{fingerprint:this.config.deviceFingerprinting&&t,geolocation:this.config.geolocation&&t,overrides:e,tracking:this.config.trackingOptions,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(e){return this.config.sampleRate>=1?!0:He(`${this.config.apiKey}:${e}`)<this.config.sampleRate}inSample(e,t){return t==="identify"||t==="alias"||t==="group"?!0:this.sessionInSample(e)}capture(e,t,n,i,s,o,d){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let a=this.touchSession();if(!this.inSample(a.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let u=o??this.clock.now(),c=this.contextOptions();d&&(c.page=d);let l={event_id:y(u),event:e,event_type:t,timestamp:_(u),session_id:a.sessionId,session_started_at:_(a.startedAt),anonymous_id:this.identity.anonymousId,context:i?{...B(c),traits:i}:B(c),platform:"Web",sdk_version:R};s&&(l.user_properties=s);let g=k({...this.config.defaultProperties,...this.superProperties.current(),...k(n,this.logger)},this.logger);Object.keys(g).length>0&&(l.properties=g);let f=this.identity.userId;f&&(l.user_id=f);let b=this.identity.groupId;b&&(l.group_id=b),c.fingerprint&&(l.device_id=le(this.config.apiKey)),this.enqueueEvent(l),this.logger.debug(`captured ${e}`,l),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(e){let t=this.storage.get(Oe),n=t!==null&&t!==e;return n&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear(),this.storage.remove(N)),this.storage.set(Oe,e),n}pickStorage(){return this.config.storage==="memory"?new w:dt()}enqueueSessionBoundary(e,t,n,i){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug(`session_${e} dropped (consent denied)`);return}let s=this.contextOptions(),o={event_id:y(this.clock.now()),event:`$session_${e}`,event_type:`session_${e}`,timestamp:_(n),session_id:t,session_started_at:_(i),anonymous_id:this.identity.anonymousId,context:B(s),platform:"Web",sdk_version:R},d=this.identity.userId;d&&(o.user_id=d),s.fingerprint&&(o.device_id=le(this.config.apiKey),e==="start"&&(o.properties=Je())),this.enqueueEvent(o)}touchSession(){let e=this.session.touch();if(e.startedSession&&this.pageLife.newSession(),e.endedSession&&this.sessionInSample(e.endedSession.id)){let t=e.endedSession;this.enqueueSessionBoundary("end",t.id,t.lastActivityAt,t.startedAt)}if(e.startedSession&&this.sessionInSample(e.startedSession.id)){let t=e.startedSession;this.enqueueSessionBoundary("start",t.id,t.startedAt,t.startedAt)}return e}resumeSession(){this.consent.canCapture()&&this.touchSession()}startAutocapture(){let e=this.config.autocapture;if(!e||typeof window>"u")return;typeof PerformanceObserver<"u"&&(this.vitals=mt(),this.teardownFns.push(()=>this.vitals?.stop()));let t=ht(this.config,n=>this.guard(()=>this.capture("$network_request","track",n)));this.teardownFns.push(()=>t.stop()),Le().then(n=>{n&&(this.stopped||(this.teardownFns.push(n.startAutocapture(e,{emit:i=>this.autocapture(i),page:i=>this.guard(()=>this.pageLife.autoPageView(i)),pageLeave:i=>this.guard(()=>this.pageLife.leave(i)),warn:i=>this.logger.warn(i),armUnloadLeave:i=>{this.leaveOnUnload=i}})),this.teardownFns.push(()=>{this.leaveOnUnload=void 0})))}).catch(n=>this.logger.debug("autocapture load failed",n))}guard(e){try{e()}catch(t){this.logger.error("internal error",t)}}};var Ce=Symbol.for("depsmith.sdk.replay.registry"),Rt=()=>globalThis[Ce]??(globalThis[Ce]={});function Tt(r){let e=Rt();e.current=r;try{e.integration?.clientCreated(r)}catch{}}function Re(r,e){let t=Rt();if(t.current===r){t.current=void 0;try{t.integration?.clientGone(r,e)}catch{}}}var p=null,Te=null,di={init(r,e){try{if(p&&Te===r.apiKey)return p;if(typeof window>"u"&&r.storage!=="memory"&&!e?.storage)return r.debug&&console.warn("[depsmith-sdk] init skipped: no window"),null;let t=p;return t&&(Re(t,!0),t.shutdown()),p=new M(r,e),Te=r.apiKey,Tt(p),p}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>p?.track(r,e),page:(r,e,t)=>p?.page(r,e,t),screen:(r,e,t)=>p?.screen(r,e,t),identify:(r,e)=>p?.identify(r,e),alias:r=>p?.alias(r),reset:()=>p?.reset(),group:(r,e)=>p?.group(r,e),setGroupTraits:r=>p?.setGroupTraits(r),setProperty:(r,e)=>p?.setProperty(r,e),setOnceProperty:(r,e)=>p?.setOnceProperty(r,e),unsetProperty:r=>p?.unsetProperty(r),setUserProperties:r=>p?.setUserProperties(r),register:r=>p?.register(r),registerOnce:r=>p?.registerOnce(r),unregister:r=>p?.unregister(r),optIn:()=>p?.optIn(),optOut:()=>p?.optOut(),flush:()=>p?.flush()??Promise.resolve(),getAnonymousId:()=>p?.getAnonymousId(),getSessionId:()=>p?.getSessionId(),setSessionId:(r,e)=>p?.setSessionId(r,e),shutdown(){p&&(p.shutdown(),Re(p,!1)),p=null,Te=null}};export{be as AsyncMirrorAdapter,at as DEPSMITH_SDK_STORAGE_KEYS,di as DepsmithSdk,M as DepsmithSdkClient,T as idleScheduler,Jt as syncScheduler};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|