@depsmith/depsmith-sdk 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,4 +7,4 @@ globalThis.DEPSMITH_SDK_CONFIG = {
7
7
  endpoint: "https://collector.example.com",
8
8
  debug: false
9
9
  };
10
- "use strict";(()=>{var UTM_PARAMS=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]];var KEY_CAMPAIGN="depsmith_campaign";var KEY_REFERRER="depsmith_referrer";function hostOf(url){try{return new URL(url).host||void 0}catch{return void 0}}var Attribution=class{constructor(storage){this.storage=storage;this.campaign={};this.referrer={};this.campaign=this.read(KEY_CAMPAIGN)??{};this.referrer=this.read(KEY_REFERRER)??{}}read(key){try{const raw=this.storage.get(key);if(!raw)return null;const parsed=JSON.parse(raw);return parsed&&typeof parsed==="object"?parsed:null}catch{return null}}write(key,value){try{this.storage.set(key,JSON.stringify(value))}catch{}}recordLanding(url,documentReferrer){let params;let currentHost;try{const parsed=new URL(url);params=parsed.searchParams;currentHost=parsed.host}catch{return}const incoming={};for(const[param,key]of UTM_PARAMS){const value=params.get(param);if(value)incoming[key]=value}if(Object.keys(incoming).length>0){this.campaign=incoming;this.write(KEY_CAMPAIGN,incoming)}const refHost=documentReferrer?hostOf(documentReferrer):void 0;const isExternal=Boolean(refHost)&&refHost!==currentHost;let changed=false;if(isExternal){this.referrer.url=documentReferrer;this.referrer.domain=refHost;changed=true}if(this.referrer.initial_domain===void 0){this.referrer.initial_domain=isExternal?refHost:"$direct";if(isExternal)this.referrer.initial_url=documentReferrer;changed=true}if(changed)this.write(KEY_REFERRER,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(KEY_CAMPAIGN);this.storage.remove(KEY_REFERRER)}catch{}}};var PageLifecycle=class{constructor(_sink){this.counter=0}get pageCount(){return this.counter}start(_url,_documentReferrer){this.counter=1}recordExplicit(){this.counter+=1}autoPageView(){}leave(_maxScroll){}restored(_persisted){}newSession(){this.counter=Math.min(this.counter,1)}tracking(){return{}}};function domainOf(_url){return void 0}function urlBase(_url){return void 0}function loadAutocapture(){return Promise.resolve(null)}var SUPPRESSIONS=[["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"],["screen","screen"],["timezone","timezone"],["userAgent","user_agent"]];var TRACKING_DEFAULTS=Object.fromEntries(SUPPRESSIONS.map(([option])=>[option,true]));function resolveTrackingOptions(options){const resolved={...TRACKING_DEFAULTS};if(!options)return resolved;for(const[option]of SUPPRESSIONS){if(options[option]===false)resolved[option]=false}return resolved}function applyTrackingOptions(context,options){const record=context;for(const[option,key,sub]of SUPPRESSIONS){if(options[option])continue;if(sub===void 0){delete record[key];continue}const block={...record[key]};delete block[sub];if(Object.keys(block).length>0)record[key]=block;else delete record[key]}return context}var AUTOCAPTURE_DEFAULTS={clicks:"interactive",forms:true,scrolls:true,pageviews:true,ignoredSelectors:[],selectorMaxDepth:5,attributes:[]};function resolveClicks(clicks){if(clicks===void 0)return AUTOCAPTURE_DEFAULTS.clicks;if(clicks===true)return"interactive";return clicks}function resolveConfig(config){if(!config||typeof config.apiKey!=="string"||config.apiKey.length===0){throw new Error("depsmith-sdk: apiKey is required")}if(typeof config.endpoint!=="string"||!/^https?:\/\//.test(config.endpoint)){throw new Error("depsmith-sdk: endpoint must be an http(s) URL")}const autocapture=config.autocapture===true?AUTOCAPTURE_DEFAULTS:config.autocapture&&typeof config.autocapture==="object"?{...AUTOCAPTURE_DEFAULTS,...config.autocapture,clicks:resolveClicks(config.autocapture.clicks)}:false;return{apiKey:config.apiKey,endpoint:config.endpoint.replace(/\/+$/,""),batchSize:clamp(config.batchSize??20,1,500),batchIntervalMs:Math.max(config.batchIntervalMs??6e4,1e3),maxQueueSize:Math.max(config.maxQueueSize??1e3,1),maxQueueBytes:Math.max(config.maxQueueBytes??512*1024,4096),sessionTimeoutMs:Math.max(config.sessionTimeoutMs??18e5,6e4),sampleRate:Number.isFinite(config.sampleRate)?clamp(config.sampleRate,0,1):1,sessionEvents:config.sessionEvents==="derive"?"derive":"emit",consentMode:config.consentMode??"granted",respectDnt:config.respectDnt??true,maxRetries:clamp(config.maxRetries??5,0,10),debug:config.debug??false,defaultProperties:config.defaultProperties??{},autocapture,compression:config.compression??"gzip",childSafeMode:config.childSafeMode??false,anonymizeIp:(config.anonymizeIp??false)||(config.childSafeMode??false),deviceFingerprinting:config.deviceFingerprinting??true,geolocation:config.geolocation??false,trackingOptions:resolveTrackingOptions(config.trackingOptions),cookieDomain:config.cookieDomain??"",storage:config.storage??"localstorage"}}function clamp(n,min,max){return Math.min(Math.max(n,min),max)}function djb2(input){let hash=5381;for(let i=0;i<input.length;i++){hash=(hash<<5)+hash+input.charCodeAt(i)>>>0}return hash.toString(36)}function fnv1aInt(input){let hash=2166136261;for(let i=0;i<input.length;i++){hash^=input.charCodeAt(i);hash=Math.imul(hash,16777619)>>>0}return hash>>>0}function fnv1a(input){return fnv1aInt(input).toString(36)}function bucket(input){return fnv1aInt(input)/4294967296}function fingerprintHash(input){return djb2(input)+fnv1a(input)}var hints={};var hintsRequested=false;function primeClientHints(){if(hintsRequested)return;hintsRequested=true;try{const uaData=navigator?.userAgentData;if(typeof uaData?.getHighEntropyValues!=="function")return;void uaData.getHighEntropyValues(["model","platformVersion"]).then(values=>{hints=values}).catch(()=>{})}catch{}}function parseUserAgent(){const result={};if(typeof navigator==="undefined")return result;const ua=navigator.userAgent||"";const uaData=navigator.userAgentData;const browser2=parseBrowser(ua,uaData);if(browser2)result.browser=browser2;const os=parseOS(ua);if(os){const hinted=normalizeOsVersion(os.name,hints.platformVersion);result.os=hinted?{...os,version:hinted}:os}const deviceType=parseDeviceType(ua,uaData);if(deviceType)result.deviceType=deviceType;const device=parseDevice(ua,os);if(device)result.device=device;return result}function parseDevice(ua,os){const device={};if(os?.name==="iOS"||os?.name==="macOS")device.manufacturer="Apple";const hinted=hints.model?.trim();if(hinted)device.model=hinted;else if(/iPhone/.test(ua))device.model="iPhone";else if(/iPad/.test(ua))device.model="iPad";return device.manufacturer||device.model?device:void 0}function normalizeOsVersion(osName,platformVersion){const raw=platformVersion?.trim();if(!raw)return void 0;if(osName==="Windows"){const major=Number.parseInt(raw.split(".")[0]??"",10);if(!Number.isFinite(major))return void 0;if(major===0)return void 0;return major>=13?"11":"10"}return trimVersion(raw)}var BROWSER_RULES=[{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 parseBrowser(ua,uaData){for(const rule of BROWSER_RULES){if(rule.requires&&!rule.requires.test(ua))continue;const match=ua.match(rule.pattern);if(match)return{name:rule.name,version:match[1],engine:rule.engine}}const brand=uaData?.brands?.find(b=>!/not.?a.?brand/i.test(b.brand));if(brand)return{name:brand.brand,version:brand.version};return void 0}var OS_RULES=[{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 parseOS(ua){for(const rule of OS_RULES){if(rule.requires&&!rule.requires.test(ua))continue;const match=ua.match(rule.pattern);if(match)return{name:rule.name,version:trimVersion((match[1]??"").replace(/_/g,"."))}}if(/Linux/.test(ua))return{name:"Linux"};return void 0}function trimVersion(version){const trimmed=version.replace(/(\.0)+$/,"");return trimmed.length>0?trimmed:version}function parseDeviceType(ua,uaData){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(ua))return"tablet";if(uaData?.mobile===true)return"mobile";if(/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(ua))return"mobile";if(/Android/.test(ua))return"tablet";if(typeof navigator!=="undefined"&&ua)return"desktop";return void 0}var cachedVisitorId=null;var cachedComponents=null;function components(){if(cachedComponents!==null)return cachedComponents;cachedComponents=collectSignals();return cachedComponents}function computeVisitorId(){if(cachedVisitorId!==null)return cachedVisitorId;cachedVisitorId=fingerprintHash(components().map(c=>c.value).join("|"));return cachedVisitorId}function fingerprintComponents(){const out={};for(const component of components())out[`$fp_${component.name}`]=component.value;return out}function collectSignals(){const signals=[];try{if(typeof screen!=="undefined"){signals.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`})}if(typeof navigator!=="undefined"){const nav=navigator;signals.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`});signals.push({name:"dm",value:`dm:${nav.deviceMemory??""}`});signals.push({name:"plat",value:`plat:${navigator.platform??""}`});signals.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}signals.push({name:"canvas",value:`canvas:${canvasFingerprint()}`})}catch{}return signals}function canvasFingerprint(){try{if(typeof document==="undefined")return"";const canvas=document.createElement("canvas");canvas.width=240;canvas.height=60;const ctx=canvas.getContext("2d");if(!ctx)return"";ctx.textBaseline="top";ctx.font="14px 'Arial'";ctx.fillStyle="#f60";ctx.fillRect(10,10,100,30);ctx.fillStyle="#069";ctx.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15);ctx.strokeStyle="rgba(0,120,200,0.5)";ctx.arc(50,30,20,0,Math.PI*2);ctx.stroke();return fingerprintHash(canvas.toDataURL())}catch{return""}}function readNetwork(){try{if(typeof navigator==="undefined")return{};const conn=navigator.connection;if(!conn)return{};switch(conn.type){case"wifi":return{type:"wifi"};case"ethernet":return{type:"ethernet"};case"none":return{type:"none"}}switch(conn.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var MAX_FIX_AGE_MS=5*6e4;var FIX_TIMEOUT_MS=1e4;var fix=null;var fixAt=0;var primed=false;var inFlight=false;var permission=null;function primeGeolocation(){if(primed)return;primed=true;try{if(typeof navigator==="undefined"||!navigator.geolocation)return;const permissions=navigator.permissions;if(typeof permissions?.query!=="function")return;void permissions.query({name:"geolocation"}).then(status=>{permission=status;if(status.state==="granted")requestFix();status.onchange=()=>{if(status.state==="granted")requestFix();else fix=null}}).catch(()=>{})}catch{}}function requestFix(){if(inFlight)return;inFlight=true;try{navigator.geolocation.getCurrentPosition(position=>{inFlight=false;const{latitude,longitude,accuracy}=position.coords;if(!Number.isFinite(latitude)||!Number.isFinite(longitude))return;const next={latitude,longitude,source:"gps"};if(Number.isFinite(accuracy))next.accuracy=accuracy;fix=next;fixAt=Date.now()},()=>{inFlight=false},{enableHighAccuracy:false,maximumAge:MAX_FIX_AGE_MS,timeout:FIX_TIMEOUT_MS})}catch{inFlight=false}}function readGeolocation(){if(!fix)return void 0;if(Date.now()-fixAt>MAX_FIX_AGE_MS&&permission?.state==="granted")requestFix();return{...fix}}var LIBRARY_NAME="@depsmith/depsmith-sdk";var SDK_VERSION="0.7.0";var invariants=null;function readInvariants(){if(invariants)return invariants;const next={};try{next.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}if(typeof navigator!=="undefined"){next.locale=navigator.language;next.userAgent=navigator.userAgent}invariants=next;return next}function buildContext(opts={}){const context={library:{name:LIBRARY_NAME,version:SDK_VERSION}};attempt(()=>{if(typeof window!=="undefined"&&window.location){const href=window.location.href;context.page={url:href,path:window.location.pathname,referrer:typeof document!=="undefined"?document.referrer:void 0,title:typeof document!=="undefined"?document.title:void 0,domain:domainOf(href),url_base:urlBase(href),...opts.page??{}}}});attempt(()=>{if(typeof window!=="undefined"&&window.screen){context.screen={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio}}});attempt(()=>{const cached=readInvariants();if(cached.locale!==void 0)context.locale=cached.locale;if(cached.userAgent!==void 0)context.user_agent=cached.userAgent;if(cached.timezone!==void 0)context.timezone=cached.timezone});attempt(()=>{const{deviceType}=parseUserAgent();if(deviceType)context.device={...context.device,type:deviceType}});attempt(()=>{if(opts.attribution){const campaign=opts.attribution.campaignBlock();if(campaign)context.campaign=campaign;const referrer=opts.attribution.referrerBlock();if(referrer)context.referrer=referrer}});attempt(()=>{if(opts.fingerprint)enrichFingerprint(context)});attempt(()=>{if(opts.geolocation){const fix2=readGeolocation();if(fix2)context.location=fix2}});try{if(opts.overrides){for(const[key,value]of Object.entries(opts.overrides)){if(value!==void 0)context[key]=value}context.library={name:LIBRARY_NAME,version:SDK_VERSION}}}catch{}if(opts.tracking)applyTrackingOptions(context,opts.tracking);return context}function enrichFingerprint(context){const{browser:browser2,os,deviceType,device:hinted}=parseUserAgent();if(browser2)context.browser=browser2;if(os)context.os=os;const device={...context.device};if(deviceType)device.type=deviceType;if(hinted?.manufacturer)device.manufacturer=hinted.manufacturer;if(hinted?.model)device.model=hinted.model;if(Object.keys(device).length>0)context.device=device;const network=readNetwork();if(network.type)context.network={...context.network,type:network.type}}function attempt(fn){try{fn()}catch{}}function dntEnabled(){try{if(typeof navigator==="undefined")return false;const nav=navigator;const win=typeof window!=="undefined"?window:{};const value=navigator.doNotTrack??win.doNotTrack??nav.msDoNotTrack;return value==="1"||value==="yes"}catch{return false}}var KEY_CONSENT="depsmith_consent";var ConsentManager=class{constructor(storage,initialMode,dntActive){this.storage=storage;this.dntActive=dntActive;const persisted=storage.get(KEY_CONSENT);this.state=persisted==="granted"||persisted==="denied"||persisted==="pending"?persisted:initialMode}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.effective()==="granted"}get current(){return this.effective()}optIn(){this.state="granted";this.storage.set(KEY_CONSENT,"granted")}optOut(){this.state="denied";this.storage.set(KEY_CONSENT,"denied")}};var IDLE_TIMEOUT_MS=250;var idleScheduler=fn=>{const idle=globalThis.requestIdleCallback;if(typeof idle==="function"){idle(fn,{timeout:IDLE_TIMEOUT_MS});return}setTimeout(fn,0)};var syncScheduler=fn=>fn();var KEY_QUEUE="depsmith_queue";var DEFAULT_MAX_CHARS=512*1024;var BRACKETS=2;var IDENTITY_EVENT_TYPES=new Set(["identify","alias","group"]);function isIdentityEvent(event){return IDENTITY_EVENT_TYPES.has(event?.event_type)}var EventQueue=class{constructor(storage,maxSize,logger,options={}){this.storage=storage;this.maxSize=maxSize;this.logger=logger;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=false;this.scheduled=false;this.maxChars=options.maxChars??DEFAULT_MAX_CHARS;this.schedule=options.schedule??idleScheduler;this.restore()}restore(){try{const raw=this.storage.get(KEY_QUEUE);if(!raw)return;const parsed=JSON.parse(raw);if(!Array.isArray(parsed))return;const kept=parsed.filter(e=>!!e&&typeof e==="object"&&typeof e.event_id==="string");this.reset(kept);if(kept.length!==parsed.length){this.logger.warn("discarded corrupt queued events on restore");this.markDirty()}if(this.trimToBudget())this.markDirty()}catch{this.logger.warn("queue storage corrupt; starting empty");this.reset([]);this.storage.remove(KEY_QUEUE)}}reset(events){this.events=events;this.sizes=events.map(e=>measure(e));this.sizeSum=this.sizes.reduce((a,b)=>a+b,0)}serializedLength(){if(this.events.length===0)return BRACKETS;return this.sizeSum+(this.events.length-1)+BRACKETS}trimToBudget(){let dropped=0;while(this.events.length>0&&this.serializedLength()>this.maxChars){this.evictAt(this.victimIndex());dropped++}if(dropped>0){this.logger.warn(`queue byte cap reached; dropped ${dropped} event(s)`)}return dropped>0}markDirty(){this.dirty=true;if(this.scheduled)return;this.scheduled=true;this.schedule(()=>{this.scheduled=false;this.persistNow()})}persistNow(){if(!this.dirty)return;this.dirty=false;this.storage.set(KEY_QUEUE,JSON.stringify(this.events))}prepend(events){const existing=new Set(this.events.map(e=>e.event_id));const fresh=events.filter(e=>!!e&&typeof e==="object"&&typeof e.event_id==="string"&&!existing.has(e.event_id));if(fresh.length===0)return;this.reset([...fresh,...this.events]);if(this.events.length>this.maxSize){this.dropOldest(this.events.length-this.maxSize)}this.trimToBudget();this.markDirty()}enqueue(event){const size=measure(event);if(size+BRACKETS>this.maxChars){this.logger.warn(`event ${event.event_id} exceeds the queue byte cap; dropped`);return}this.events.push(event);this.sizes.push(size);this.sizeSum+=size;if(this.events.length>this.maxSize){const dropped=this.events.length-this.maxSize;this.dropOldest(dropped);this.logger.warn(`queue cap reached; dropped ${dropped} event(s)`)}this.trimToBudget();this.markDirty()}victimIndex(){for(let i=0;i<this.events.length;i++){if(!isIdentityEvent(this.events[i]))return i}return 0}evictAt(index){this.events.splice(index,1);this.sizeSum-=this.sizes.splice(index,1)[0]??0}dropOldest(count){for(let n=0;n<count&&this.events.length>0;n++){this.evictAt(this.victimIndex())}}get size(){return this.events.length}peek(count){return this.events.slice(0,count)}remove(eventIds2){const ids=new Set(eventIds2);const events=[];const sizes=[];let sizeSum=0;for(let i=0;i<this.events.length;i++){const event=this.events[i];if(ids.has(event.event_id))continue;const size=this.sizes[i];events.push(event);sizes.push(size);sizeSum+=size}this.events=events;this.sizes=sizes;this.sizeSum=sizeSum;this.markDirty()}clear(){this.reset([]);this.dirty=false;this.storage.remove(KEY_QUEUE)}};function measure(event){return JSON.stringify(event).length}function uuidv7(now){const bytes=new Uint8Array(16);if(typeof crypto!=="undefined"&&crypto.getRandomValues){crypto.getRandomValues(bytes)}else{for(let i=0;i<16;i++)bytes[i]=Math.floor(Math.random()*256)}bytes[0]=now/2**40&255;bytes[1]=now/2**32&255;bytes[2]=now/2**24&255;bytes[3]=now/2**16&255;bytes[4]=now/2**8&255;bytes[5]=now&255;bytes[6]=bytes[6]&15|112;bytes[8]=bytes[8]&63|128;const hex=[];for(let i=0;i<16;i++)hex.push(bytes[i].toString(16).padStart(2,"0"));return`${hex[0]}${hex[1]}${hex[2]}${hex[3]}-${hex[4]}${hex[5]}-${hex[6]}${hex[7]}-${hex[8]}${hex[9]}-${hex[10]}${hex[11]}${hex[12]}${hex[13]}${hex[14]}${hex[15]}`}function uuidv7ToMs(id){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)){return null}const hex=id.slice(0,8)+id.slice(9,13);const ms=parseInt(hex,16);return Number.isFinite(ms)?ms:null}var DEPSMITH_SDK_STORAGE_KEYS=["depsmith_anonymous_id","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"];var MemoryAdapter=class{constructor(){this.data=new Map}get(key){return this.data.get(key)??null}set(key,value){this.data.set(key,value)}remove(key){this.data.delete(key)}};var CookieAdapter=class{constructor(domain){this.domain=domain}get(key){try{const prefix=`${encodeURIComponent(key)}=`;for(const part of document.cookie.split("; ")){if(part.startsWith(prefix))return decodeURIComponent(part.slice(prefix.length))}}catch{}return null}attributes(maxAge){const domain=this.domain?`; domain=${this.domain}`:"";const secure=typeof location!=="undefined"&&location.protocol==="https:"?"; Secure":"";return`${domain}; path=/; max-age=${maxAge}; SameSite=Lax${secure}`}set(key,value){try{const maxAge=60*60*24*400;document.cookie=`${encodeURIComponent(key)}=${encodeURIComponent(value)}${this.attributes(maxAge)}`}catch{}}remove(key){try{document.cookie=`${encodeURIComponent(key)}=${this.attributes(0)}`}catch{}}};var MIRRORED_IDENTITY_KEYS=new Set(["depsmith_anonymous_id"]);var RedundantAdapter=class{constructor(primary,secondary,mirrored=MIRRORED_IDENTITY_KEYS){this.primary=primary;this.secondary=secondary;this.mirrored=mirrored}get(key){const fromPrimary=this.primary.get(key);if(!this.mirrored.has(key))return fromPrimary;const fromSecondary=this.secondary.get(key);if(fromPrimary===fromSecondary)return fromPrimary;if(fromPrimary===null&&fromSecondary!==null){this.primary.set(key,fromSecondary);return fromSecondary}if(fromSecondary===null&&fromPrimary!==null){this.secondary.set(key,fromPrimary);return fromPrimary}const winner=olderUuidV7(fromPrimary,fromSecondary)??fromPrimary;this.primary.set(key,winner);this.secondary.set(key,winner);return winner}set(key,value){this.primary.set(key,value);if(this.mirrored.has(key))this.secondary.set(key,value)}remove(key){this.primary.remove(key);this.secondary.remove(key)}};function olderUuidV7(a,b){const aMs=uuidv7ToMs(a);const bMs=uuidv7ToMs(b);if(aMs===null||bMs===null)return null;return aMs<=bMs?a:b}var AsyncMirrorAdapter=class{constructor(backend,keys=DEPSMITH_SDK_STORAGE_KEYS){this.backend=backend;this.keys=keys;this.mirror=new Map;this.hydrated=null}hydrate(){this.hydrated??(this.hydrated=Promise.all(this.keys.map(async key=>{try{const value=await this.backend.getItem(key);if(typeof value==="string"&&!this.mirror.has(key))this.mirror.set(key,value)}catch{}})).then(()=>void 0));return this.hydrated}get(key){return this.mirror.get(key)??null}set(key,value){this.mirror.set(key,value);void Promise.resolve(this.backend.setItem(key,value)).catch(()=>{})}remove(key){this.mirror.delete(key);void Promise.resolve(this.backend.removeItem(key)).catch(()=>{})}};var IndexedDBAdapter=class extends MemoryAdapter{hydrate(){return Promise.resolve(new Map)}};function defaultStorage(){return new MemoryAdapter}var KEY_ANON="depsmith_anonymous_id";var KEY_USER="depsmith_user_id";var KEY_GROUP="depsmith_group_id";var KEY_PROPS="depsmith_user_props";var IdentityManager=class{constructor(storage,clock){this.storage=storage;this.clock=clock}get anonymousId(){let id=this.storage.get(KEY_ANON);if(!id){id=uuidv7(this.clock.now());this.storage.set(KEY_ANON,id)}return id}get userId(){return this.storage.get(KEY_USER)}get groupId(){return this.storage.get(KEY_GROUP)}identify(userId){this.storage.set(KEY_USER,userId)}setGroup(groupId){this.storage.set(KEY_GROUP,groupId)}getUserProps(){try{return JSON.parse(this.storage.get(KEY_PROPS)??"{}")}catch{return{}}}setUserProp(key,value){const props=this.getUserProps();props[key]=value;this.storage.set(KEY_PROPS,JSON.stringify(props))}hasUserProp(key){return key in this.getUserProps()}unsetUserProp(key){const props=this.getUserProps();delete props[key];this.storage.set(KEY_PROPS,JSON.stringify(props))}reset(){this.storage.remove(KEY_USER);this.storage.remove(KEY_GROUP);this.storage.remove(KEY_PROPS);const fresh=uuidv7(this.clock.now());this.storage.set(KEY_ANON,fresh);return fresh}};var KEY_SESSION="depsmith_session";var SessionManager=class{constructor(storage,clock,timeoutMs,schedule=idleScheduler){this.storage=storage;this.clock=clock;this.timeoutMs=timeoutMs;this.pending=null;this.scheduled=false;this.schedule=schedule}load(){const stored=this.readStored();const pending=this.pending;if(!pending)return stored;if(!stored||pending.lastActivityAt>=stored.lastActivityAt)return pending;this.pending=null;return stored}readStored(){try{const raw=this.storage.get(KEY_SESSION);if(!raw)return null;const parsed=JSON.parse(raw);if(typeof parsed.id!=="string"||typeof parsed.lastActivityAt!=="number")return null;if(typeof parsed.startedAt!=="number"){parsed.startedAt=uuidv7ToMs(parsed.id)??parsed.lastActivityAt}return parsed}catch{return null}}save(session){this.pending=session;if(this.scheduled)return;this.scheduled=true;this.schedule(()=>{this.scheduled=false;this.persistNow()})}persistNow(){const pending=this.pending;if(!pending)return;this.pending=null;this.storage.set(KEY_SESSION,JSON.stringify(pending))}mint(now){const fresh={id:uuidv7(now),lastActivityAt:now,startedAt:now};this.save(fresh);return fresh}touch(){const now=this.clock.now();const current=this.load();if(!current){const fresh=this.mint(now);return{sessionId:fresh.id,startedAt:now,startedSession:{id:fresh.id,startedAt:now}}}if(now-current.lastActivityAt>this.timeoutMs){const fresh=this.mint(now);return{sessionId:fresh.id,startedAt:now,endedSession:{id:current.id,lastActivityAt:current.lastActivityAt,startedAt:current.startedAt},startedSession:{id:fresh.id,startedAt:now}}}this.save({id:current.id,lastActivityAt:now,startedAt:current.startedAt});return{sessionId:current.id,startedAt:current.startedAt}}peek(){const current=this.load();if(current)return current.id;return this.mint(this.clock.now()).id}adopt(id,startedAt){const embedded=uuidv7ToMs(id);if(embedded===null)return false;this.save({id,lastActivityAt:this.clock.now(),startedAt:startedAt??embedded});return true}rotate(){return this.mint(this.clock.now()).id}};var MAX_TOP_LEVEL_KEYS=200;var MAX_ARRAY_ITEMS=100;var MAX_OBJECT_KEYS=50;function sanitizeProperties(input,logger){if(input===null||input===void 0)return{};if(typeof input!=="object"||Array.isArray(input)){logger.warn("properties must be an object; ignoring",input);return{}}const out={};let count=0;for(const[rawKey,rawValue]of Object.entries(input)){if(count>=MAX_TOP_LEVEL_KEYS){logger.warn(`properties exceed ${MAX_TOP_LEVEL_KEYS} keys; excess dropped`);break}const value=coerceValue(rawValue,logger);if(value===void 0){logger.debug(`property "${rawKey}" dropped (unsupported value)`);continue}out[String(rawKey)]=value;count++}return out}function coerceScalar(value){if(value===null)return null;const t=typeof value;if(t==="string"||t==="boolean")return value;if(t==="number")return Number.isFinite(value)?value:void 0;if(value instanceof Date)return isNaN(value.getTime())?void 0:value.toISOString();return void 0}function coerceValue(value,logger){const scalar=coerceScalar(value);if(scalar!==void 0)return scalar;if(value===void 0||typeof value==="function"||typeof value==="symbol")return void 0;if(Array.isArray(value)){const items=[];for(const item of value.slice(0,MAX_ARRAY_ITEMS)){const coerced=coerceScalar(item);items.push(coerced!==void 0?coerced:safeStringify(item))}return items}if(typeof value==="object"){const out={};let count=0;for(const[k,v]of Object.entries(value)){if(count>=MAX_OBJECT_KEYS){logger.debug(`nested object exceeds ${MAX_OBJECT_KEYS} keys; excess dropped`);break}const coerced=coerceScalar(v);out[String(k)]=coerced!==void 0?coerced:safeStringify(v);count++}return out}return void 0}function safeStringify(value){try{return JSON.stringify(value)??"null"}catch{return String(value)}}function observeNetworkErrors(_endpoint,_emit){return{stop:()=>{}}}function observeVitals(){return{snapshot:()=>({}),hasAny:()=>false,stop:()=>{}}}var SuperProperties=class{constructor(_storage,_logger){}register(_properties){}registerOnce(_properties){}unregister(_key){}clear(){}current(){return{}}};var TRAIT_OPERATORS=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"];var MAX_ADD_KEYS=50;var MAX_UNSET_KEYS=200;function normalizeUserPropertyOps(ops,logger){if(!ops||typeof ops!=="object")return void 0;if(ops.$clear_all===true){const others=Object.keys(ops).filter(k=>k!=="$clear_all");if(others.length>0){logger.warn(`$clear_all is exclusive; ignored ${others.join(", ")}`)}return{$clear_all:true}}const out={};const claimed=new Set;const claim=(key,operator)=>{if(claimed.has(key)){logger.debug(`"${key}" has an operator already; ${operator} dropped`);return false}claimed.add(key);return true};for(const operator of TRAIT_OPERATORS){const raw=ops[operator];if(!raw||typeof raw!=="object")continue;const clean=sanitizeProperties(raw,logger);const kept={};for(const[key,value]of Object.entries(clean)){if(!claim(key,operator))continue;kept[key]=value}if(Object.keys(kept).length>0)out[operator]=kept}if(ops.$add&&typeof ops.$add==="object"){const kept={};let count=0;for(const[key,value]of Object.entries(ops.$add)){if(count>=MAX_ADD_KEYS){logger.debug(`$add over ${MAX_ADD_KEYS} keys; excess dropped`);break}if(typeof value!=="number"||!Number.isFinite(value)){logger.debug(`$add "${key}" is not finite; dropped`);continue}if(!claim(key,"$add"))continue;kept[key]=value;count++}if(Object.keys(kept).length>0)out.$add=kept}if(Array.isArray(ops.$unset)){const kept=[];for(const key of ops.$unset){if(kept.length>=MAX_UNSET_KEYS){logger.debug(`$unset over ${MAX_UNSET_KEYS} keys; excess dropped`);break}if(typeof key!=="string"||key.length===0)continue;if(!claim(key,"$unset"))continue;kept.push(key)}if(kept.length>0)out.$unset=kept}return Object.keys(out).length>0?out:void 0}function sanitizedTraitOp(operator,clean){return Object.keys(clean).length>0?{[operator]:clean}:void 0}var systemClock={now:()=>Date.now()};function isoTimestamp(ms){return new Date(ms).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function isRetryable(status){return status===0||status===408||status===429||status>=500}var BASE_MS=1e3;var MAX_BACKOFF_MS=32e3;function backoffMs(attempt2,random=Math.random){const base=Math.min(BASE_MS*2**attempt2,MAX_BACKOFF_MS);return Math.round(random()*base)}async function gzip(text){const cs=new CompressionStream("gzip");const writer=cs.writable.getWriter();writer.write(new TextEncoder().encode(text)).catch(()=>{});writer.close().catch(()=>{});const reader=cs.readable.getReader();const chunks=[];for(;;){const{done,value}=await reader.read();if(done)break;chunks.push(value)}const total=chunks.reduce((n,c)=>n+c.length,0);const out=new Uint8Array(new ArrayBuffer(total));let offset=0;for(const chunk of chunks){out.set(chunk,offset);offset+=chunk.length}return out}function eventIds(batch){const ids=[];for(const event of batch)ids.push(event.event_id);return ids}var REQUEST_TIMEOUT_MS=3e4;var KEEPALIVE_MAX_BYTES=6e4;var MAX_UNLOAD_BATCHES=10;function bodyBytes(body){if(typeof body==="string")return new TextEncoder().encode(body).byteLength;if(body instanceof Uint8Array)return body.byteLength;return 0}var BatchUploader=class{constructor(queue,config,deps){this.queue=queue;this.config=config;this.deps=deps;this.inFlight=null}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){if(this.inFlight)return this.inFlight;this.inFlight=this.drain().catch(err=>this.deps.logger.error("flush failed",err)).finally(()=>{this.inFlight=null});return this.inFlight}async drain(){while(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("collector unreachable; uploads paused");return}const batch=this.queue.peek(this.config.batchSize);this.queue.persistNow();const result=await this.uploadWithRetry(batch);if(result==="requeue")return;if(result==="dropped")this.deps.logger.warn(`dropped poison batch of ${batch.length}`);this.queue.remove(eventIds(batch))}}async uploadWithRetry(batch){const breaker=this.deps.breaker;let answered=false;for(let attempt2=0;attempt2<=this.config.maxRetries;attempt2++){const status=await this.post(batch);if(status!==0)answered=true;if(status>=200&&status<300){breaker?.ok();return"sent"}if(!isRetryable(status)){breaker?.ok();this.deps.logger.warn(`non-retryable ${status}; dropping batch`);return"dropped"}this.deps.logger.debug(`upload attempt ${attempt2+1} failed (${status})`);if(status===0&&!answered&&breaker?.suspect())break;if(attempt2<this.config.maxRetries)await this.deps.sleep(backoffMs(attempt2))}if(answered)breaker?.ok();else breaker?.fail();return"requeue"}buildPayload(batch){const payload={batch,api_key:this.config.apiKey,source:"sdk",sent_at:isoTimestamp(this.deps.clock.now())};if(this.config.anonymizeIp)payload.anonymize_ip=true;return payload}async post(batch){const json=JSON.stringify(this.buildPayload(batch));const controller=typeof AbortController!=="undefined"?new AbortController:null;let timer=null;try{let body=json;const headers={"Content-Type":"application/json"};if(this.config.compression!=="none"&&typeof CompressionStream!=="undefined"){try{body=await gzip(json);headers["Content-Encoding"]="gzip"}catch{body=json}}const keepalive=bodyBytes(body)<=KEEPALIVE_MAX_BYTES;if(!keepalive){this.deps.logger.debug("payload over keepalive cap; sending without keepalive")}const init2={method:"POST",headers,body,keepalive};if(controller){init2.signal=controller.signal;timer=setTimeout(()=>controller.abort(),this.timeoutMs())}const res=await this.deps.fetchFn(`${this.config.endpoint}/e/`,init2);return res.status}catch{return 0}finally{if(timer!==null)clearTimeout(timer)}}timeoutMs(){const configured=this.config.requestTimeoutMs;return typeof configured==="number"&&configured>0?configured:REQUEST_TIMEOUT_MS}sendBeaconAll(){try{if(typeof navigator==="undefined"||!navigator.sendBeacon)return;let batches=0;while(this.queue.size>0&&batches<MAX_UNLOAD_BATCHES){const batch=this.queue.peek(this.config.batchSize);const payload=this.buildPayload(batch);const accepted=navigator.sendBeacon(`${this.config.endpoint}/e/`,new Blob([JSON.stringify(payload)],{type:"text/plain"}));if(!accepted)return;this.queue.remove(eventIds(batch));batches++}}catch{}}};var KEY_NET_BREAKER="depsmith_net_breaker";var TRIP_AFTER_CYCLES=3;var BASE_COOLDOWN_MS=5*6e4;var MAX_COOLDOWN_MS=60*6e4;function createNetworkBreaker(storage,clock){let loaded=false;let failures=0;let openUntil=0;let cooldown=BASE_COOLDOWN_MS;const clamp2=(v,lo,hi)=>typeof v==="number"&&v===v?Math.min(Math.max(v,lo),hi):lo;const load=()=>{if(loaded)return;loaded=true;try{const s=JSON.parse(storage.get(KEY_NET_BREAKER)??"0");if(!Array.isArray(s))return;failures=clamp2(s[0],0,TRIP_AFTER_CYCLES);openUntil=clamp2(s[1],0,clock.now()+MAX_COOLDOWN_MS);cooldown=clamp2(s[2],BASE_COOLDOWN_MS,MAX_COOLDOWN_MS)}catch{}};const save=()=>{try{if(failures)storage.set(KEY_NET_BREAKER,JSON.stringify([failures,openUntil,cooldown]));else storage.remove(KEY_NET_BREAKER)}catch{}};return{open:()=>(load(),clock.now()<openUntil),suspect:()=>(load(),failures>0),fail:()=>{load();if(++failures>=TRIP_AFTER_CYCLES){openUntil=clock.now()+cooldown;cooldown=Math.min(cooldown*2,MAX_COOLDOWN_MS);failures=TRIP_AFTER_CYCLES}save()},ok:()=>{load();if(!failures)return;failures=openUntil=0;cooldown=BASE_COOLDOWN_MS;save()}}}var Logger=class{constructor(enabled){this.enabled=enabled}setEnabled(enabled){this.enabled=enabled}debug(...args){if(this.enabled)console.debug("[depsmith-sdk]",...args)}warn(...args){if(this.enabled)console.warn("[depsmith-sdk]",...args)}error(...args){if(this.enabled)console.error("[depsmith-sdk]",...args)}};var MAX_ENVELOPE_ID_LENGTH=255;var DepsmithSdkClient=class{constructor(config,overrides={}){this.pageLife=new PageLifecycle({now:()=>this.clock.now(),capture:(name,type,properties)=>this.capture(name,type,properties)});this.vitalsReported=false;this.flushTimer=null;this.drained=false;this.teardownFns=[];this.ready=Promise.resolve();this.config=resolveConfig(config);this.logger=new Logger(this.config.debug);this.clock=overrides.clock??systemClock;this.storage=overrides.storage??this.pickStorage();this.contextProvider=overrides.contextProvider;const identityStorage=this.config.childSafeMode?new MemoryAdapter:this.config.storage==="memory"?this.storage:new RedundantAdapter(this.storage,new CookieAdapter(this.config.cookieDomain||void 0));this.identity=new IdentityManager(identityStorage,this.clock);this.session=new SessionManager(this.storage,this.clock,this.config.sessionTimeoutMs,overrides.schedule);this.consent=new ConsentManager(this.storage,this.config.consentMode,this.config.respectDnt&&(overrides.dnt??dntEnabled()));this.attribution=new Attribution(identityStorage);this.superProperties=new SuperProperties(this.storage,this.logger);if(!this.contextProvider&&typeof window!=="undefined"&&window.location){this.attribution.recordLanding(window.location.href,typeof document!=="undefined"?document.referrer:"");this.pageLife.start(window.location.href,typeof document!=="undefined"?document.referrer:"")}this.queue=new EventQueue(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:overrides.schedule});this.detectConfigDrift();if(this.config.deviceFingerprinting&&!this.config.childSafeMode){primeClientHints()}if(this.config.geolocation&&!this.config.childSafeMode){primeGeolocation()}if(this.storage instanceof IndexedDBAdapter){this.ready=this.storage.hydrate().then(persisted=>{try{const raw=persisted.get("depsmith_queue");if(raw)this.queue.prepend(JSON.parse(raw))}catch{this.logger.warn("persisted queue corrupt; discarded")}})}this.uploader=new BatchUploader(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:overrides.requestTimeoutMs},{fetchFn:overrides.fetchFn??((...args)=>fetch(...args)),clock:this.clock,logger:this.logger,sleep:overrides.sleep??(ms=>new Promise(r=>setTimeout(r,ms))),isOnline:overrides.isOnline??(()=>typeof navigator==="undefined"?true:navigator.onLine!==false),breaker:createNetworkBreaker(this.storage,this.clock)});if(!overrides.manualLifecycle){this.startFlushTimer();this.attachLifecycle();this.startAutocapture()}this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(name,properties){this.guard(()=>{if(typeof name!=="string"||name.length===0){this.logger.warn("track: event name required");return}if(name.startsWith("$")){this.logger.warn(`track: "$"-prefixed names are reserved; dropped "${name}"`);return}if(this.tooLong(name,"track: event name"))return;this.capture(name,"track",properties)})}tooLong(value,label){if(value.length<=MAX_ENVELOPE_ID_LENGTH)return false;this.logger.warn(`${label} exceeds ${MAX_ENVELOPE_ID_LENGTH} characters (got ${value.length}); dropped`);return true}page(name,properties){this.guard(()=>{this.pageLife.recordExplicit();const pageName=name??(typeof document!=="undefined"?document.title:void 0)??"Unknown";this.capture("$page_view","page_view",{...properties,name:pageName,$page_counter:this.pageLife.pageCount})})}emitWebVitals(){if(this.vitalsReported||!this.vitals?.hasAny())return;this.vitalsReported=true;this.capture("$web_vitals","track",this.vitals.snapshot())}screen(name,properties){this.page(name,properties)}identify(userId,traits){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof userId!=="string"||userId.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(userId,"identify: userId"))return;this.identity.identify(userId);const clean=sanitizeProperties(traits,this.logger);this.capture("$identify","identify",void 0,clean,sanitizedTraitOp("$set",clean))})}alias(aliasId){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof aliasId!=="string"||aliasId.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:aliasId})})}reset(){this.guard(()=>{this.identity.reset();this.session.rotate();this.attribution.clear();this.superProperties.clear();this.logger.debug("reset: identity, session and attribution cleared")})}group(groupId,traits){this.guard(()=>{if(typeof groupId!=="string"||groupId.length===0){this.logger.warn("group: groupId required");return}if(this.tooLong(groupId,"group: groupId"))return;this.identity.setGroup(groupId);this.capture("$group","group",void 0,sanitizeProperties(traits,this.logger))})}setGroupTraits(traits){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}this.capture("$group","group",void 0,sanitizeProperties(traits,this.logger))})}setProperty(key,value){this.guard(()=>{this.identity.setUserProp(key,value);const traits=sanitizeProperties({[key]:value},this.logger);this.capture("$identify","identify",void 0,traits,sanitizedTraitOp("$set",traits))})}setOnceProperty(key,value){this.guard(()=>{if(this.identity.hasUserProp(key)){this.logger.debug(`setOnceProperty: "${key}" already set`);return}this.identity.setUserProp(key,value);const traits=sanitizeProperties({[key]:value},this.logger);this.capture("$identify","identify",void 0,traits,sanitizedTraitOp("$set_once",traits))})}unsetProperty(key){this.guard(()=>{this.identity.unsetUserProp(key);this.capture("$identify","identify",void 0,{[key]:null},normalizeUserPropertyOps({$unset:[key]},this.logger))})}register(properties){this.guard(()=>this.superProperties.register(properties))}registerOnce(properties){this.guard(()=>this.superProperties.registerOnce(properties))}unregister(key){this.guard(()=>this.superProperties.unregister(key))}setUserProperties(ops){this.guard(()=>{const normalized=normalizeUserPropertyOps(ops,this.logger);if(!normalized)return;this.capture("$identify","identify",void 0,void 0,normalized)})}optIn(){this.guard(()=>{this.consent.optIn();this.logger.debug("consent granted");void this.flushUploads()})}optOut(){this.guard(()=>{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(err){this.logger.error("flush error",err)}}autocapture(properties){this.guard(()=>this.capture("$autocapture","autocapture",properties))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(sessionId,startedAt){this.guard(()=>{if(typeof sessionId!=="string"||!this.session.adopt(sessionId,startedAt)){this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(sessionId)}"`)}})}shutdown(){if(this.flushTimer!==null)clearInterval(this.flushTimer);this.flushTimer=null;for(const fn of this.teardownFns.splice(0))fn();this.persistNow()}persistNow(){try{this.queue.persistNow();this.session.persistNow()}catch{}}enqueueEvent(event){this.queue.enqueue(event);this.drained=false}flushUploads(){return this.ready.then(()=>this.uploader.flush())}contextOptions(){let overrides;try{overrides=this.contextProvider?.()}catch{}return{fingerprint:this.config.deviceFingerprinting&&!this.config.childSafeMode&&this.consent.current==="granted",geolocation:this.config.geolocation&&!this.config.childSafeMode&&this.consent.current==="granted",overrides,tracking:this.config.trackingOptions,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(sessionId){if(this.config.sampleRate>=1)return true;return bucket(`${this.config.apiKey}:${sessionId}`)<this.config.sampleRate}inSample(sessionId,type){if(type==="identify"||type==="alias"||type==="group")return true;return this.sessionInSample(sessionId)}capture(name,type,properties,traits,userProperties){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${name}`);return}const touch=this.session.touch();if(touch.startedSession)this.pageLife.newSession();if(touch.endedSession&&this.sessionInSample(touch.endedSession.id)){this.enqueueSessionEnd(touch.endedSession)}if(touch.startedSession&&this.sessionInSample(touch.startedSession.id)){this.enqueueSessionStart(touch.startedSession)}if(!this.inSample(touch.sessionId,type)){this.logger.debug(`capture dropped (out of sample): ${name}`);return}const now=this.clock.now();const contextOptions=this.contextOptions();const event={event_id:uuidv7(now),event:name,event_type:type,timestamp:isoTimestamp(now),session_id:touch.sessionId,session_started_at:isoTimestamp(touch.startedAt),anonymous_id:this.identity.anonymousId,context:traits?{...buildContext(contextOptions),traits}:buildContext(contextOptions),platform:"web",sdk_version:SDK_VERSION};if(userProperties)event.user_properties=userProperties;const props={...this.config.defaultProperties,...this.superProperties.current(),...sanitizeProperties(properties,this.logger)};if(Object.keys(props).length>0)event.properties=props;const userId=this.identity.userId;if(userId)event.user_id=userId;const groupId=this.identity.groupId;if(groupId)event.group_id=groupId;if(contextOptions.fingerprint)event.device_id=computeVisitorId();this.enqueueEvent(event);this.logger.debug(`captured ${name}`,event);if(this.queue.size>=this.config.batchSize&&this.consent.canUpload()){void this.flushUploads()}}detectConfigDrift(){const KEY="depsmith_config_fp";const fingerprint=djb2(this.config.apiKey);const stored=this.storage.get(KEY);if(stored!==null&&stored!==fingerprint){this.logger.warn("apiKey changed since last run; dropping queued events for the old project");this.queue.clear()}this.storage.set(KEY,fingerprint)}pickStorage(){if(this.config.storage==="memory")return new MemoryAdapter;if(this.config.storage==="indexeddb"&&typeof indexedDB!=="undefined"){return new IndexedDBAdapter}return defaultStorage()}enqueueSessionEnd(ended){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_end dropped (consent denied)");return}const contextOptions=this.contextOptions();const event={event_id:uuidv7(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:isoTimestamp(ended.lastActivityAt),session_id:ended.id,session_started_at:isoTimestamp(ended.startedAt),anonymous_id:this.identity.anonymousId,context:buildContext(contextOptions),platform:"web",sdk_version:SDK_VERSION};const userId=this.identity.userId;if(userId)event.user_id=userId;if(contextOptions.fingerprint)event.device_id=computeVisitorId();this.enqueueEvent(event)}enqueueSessionStart(started){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_start dropped (consent denied)");return}const contextOptions=this.contextOptions();const event={event_id:uuidv7(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:isoTimestamp(started.startedAt),session_id:started.id,session_started_at:isoTimestamp(started.startedAt),anonymous_id:this.identity.anonymousId,context:buildContext(contextOptions),platform:"web",sdk_version:SDK_VERSION};const userId=this.identity.userId;if(userId)event.user_id=userId;if(contextOptions.fingerprint)event.device_id=computeVisitorId();if(contextOptions.fingerprint){event.properties={...event.properties,...fingerprintComponents()}}this.enqueueEvent(event)}startFlushTimer(){this.flushTimer=setInterval(()=>{if(this.queue.size>0&&this.consent.canUpload())void this.flushUploads()},this.config.batchIntervalMs)}attachLifecycle(){if(typeof window==="undefined"||typeof document==="undefined")return;const onPageHide=()=>{if(this.drained)return;this.guard(()=>this.emitWebVitals());this.guard(()=>this.leaveOnUnload?.());this.drained=true;if(this.consent.canUpload())this.uploader.sendBeaconAll();this.persistNow()};const onVisibility=()=>{if(document.visibilityState==="hidden"){onPageHide()}else{this.drained=false;const touch=this.session.touch();if(touch.endedSession)this.enqueueSessionEnd(touch.endedSession);if(touch.startedSession){this.pageLife.newSession();this.enqueueSessionStart(touch.startedSession)}}};const onPageShow=event=>{this.drained=false;this.pageLife.restored(event.persisted)};const onOnline=()=>{this.uploader.resetNetworkBreaker();if(this.queue.size>0&&this.consent.canUpload())void this.flushUploads()};window.addEventListener("pagehide",onPageHide);window.addEventListener("pageshow",onPageShow);document.addEventListener("visibilitychange",onVisibility);window.addEventListener("online",onOnline);this.teardownFns.push(()=>{window.removeEventListener("pagehide",onPageHide);window.removeEventListener("pageshow",onPageShow);document.removeEventListener("visibilitychange",onVisibility);window.removeEventListener("online",onOnline)})}startAutocapture(){const autocaptureConfig=this.config.autocapture;if(!autocaptureConfig||typeof window==="undefined")return;if(typeof PerformanceObserver!=="undefined"){this.vitals=observeVitals();this.teardownFns.push(()=>this.vitals?.stop())}const network=observeNetworkErrors(this.config.endpoint,properties=>this.guard(()=>this.capture("$network_request","track",properties)));this.teardownFns.push(()=>network.stop());void loadAutocapture().then(module=>{if(!module)return;this.teardownFns.push(module.startAutocapture(autocaptureConfig,{emit:properties=>this.autocapture(properties),page:()=>this.guard(()=>this.pageLife.autoPageView()),pageLeave:maxScroll=>this.guard(()=>this.pageLife.leave(maxScroll)),armUnloadLeave:leave=>{this.leaveOnUnload=leave}}));this.teardownFns.push(()=>{this.leaveOnUnload=void 0})}).catch(err=>this.logger.debug("autocapture load failed",err))}guard(fn){try{fn()}catch(err){this.logger.error("internal error",err)}}};var client=null;var initApiKey=null;var DepsmithSdk={init(config,overrides){try{if(client&&initApiKey===config.apiKey){return client}client?.shutdown();client=new DepsmithSdkClient(config,overrides);initApiKey=config.apiKey;return client}catch(err){if(config?.debug)console.error("[depsmith-sdk] init failed:",err);return null}},track:(name,properties)=>client?.track(name,properties),page:(name,properties)=>client?.page(name,properties),screen:(name,properties)=>client?.screen(name,properties),identify:(userId,traits)=>client?.identify(userId,traits),alias:aliasId=>client?.alias(aliasId),reset:()=>client?.reset(),group:(groupId,traits)=>client?.group(groupId,traits),setGroupTraits:traits=>client?.setGroupTraits(traits),setProperty:(key,value)=>client?.setProperty(key,value),setOnceProperty:(key,value)=>client?.setOnceProperty(key,value),unsetProperty:key=>client?.unsetProperty(key),setUserProperties:ops=>client?.setUserProperties(ops),register:properties=>client?.register(properties),registerOnce:properties=>client?.registerOnce(properties),unregister:key=>client?.unregister(key),optIn:()=>client?.optIn(),optOut:()=>client?.optOut(),flush:()=>client?.flush()??Promise.resolve(),getAnonymousId:()=>client?.getAnonymousId(),getSessionId:()=>client?.getSessionId(),setSessionId:(sessionId,startedAt)=>client?.setSessionId(sessionId,startedAt),shutdown(){client?.shutdown();client=null;initApiKey=null}};var FLUSH_ON=new Set(["checkout_completed","payment_info_submitted","gokwik_purchase_event"]);function compact(input){const out={};for(const[key,value]of Object.entries(input)){if(value===void 0||value===null)continue;if(Array.isArray(value)&&value.length===0)continue;out[key]=value}return out}function amount(money){return typeof money?.amount==="number"?money.amount:void 0}function variantProps(variant){return{variant_id:variant?.id??void 0,variant_title:variant?.title??void 0,sku:variant?.sku??void 0,product_id:variant?.product?.id??void 0,title:variant?.product?.title??void 0,vendor:variant?.product?.vendor??void 0,product_type:variant?.product?.type??void 0,url:variant?.product?.url??void 0,price:amount(variant?.price),currency:variant?.price?.currencyCode??void 0}}function cartLineProps(line){return compact({...variantProps(line?.merchandise),quantity:line?.quantity??void 0,line_total:amount(line?.cost?.totalAmount)})}function isCheckoutPath(pathname){return typeof pathname==="string"&&(/^\/checkouts?\//.test(pathname)||/^\/orders\//.test(pathname))}function lineItemArrays(items){return compact({line_item_variant_ids:items.map(i=>i.variant?.id??""),line_item_product_ids:items.map(i=>i.variant?.product?.id??""),line_item_titles:items.map(i=>i.title??i.variant?.product?.title??""),line_item_quantities:items.map(i=>i.quantity??0),line_item_prices:items.map(i=>amount(i.finalLinePrice)??0)})}function checkoutProps(checkout){const items=checkout.lineItems??[];const discount=items.flatMap(item=>item.discountAllocations??[]).reduce((sum,allocation)=>sum+(amount(allocation.amount)??0),0);return compact({...lineItemArrays(items),order_id:checkout.order?.id??void 0,checkout_token:checkout.token??void 0,currency:checkout.currencyCode??checkout.totalPrice?.currencyCode??void 0,revenue:amount(checkout.totalPrice),subtotal:amount(checkout.subtotalPrice),tax:amount(checkout.totalTax),shipping:amount(checkout.shippingLine?.price),discount:discount>0?discount:void 0,item_count:items.reduce((sum,item)=>sum+(item.quantity??0),0),is_first_order:checkout.order?.customer?.isFirstOrder??void 0,customer_id:checkout.order?.customer?.id??void 0,discount_codes:(checkout.discountApplications??[]).map(application=>application.title??"").filter(Boolean)})}var GOKWIK_STEPS={Started_Checkout_GK:"checkout_started",Mobile_Added_GK:"checkout_contact_info_submitted",Address_Added_GK:"checkout_address_info_submitted",Address_Step_Reached_GK:null,Payment_Step_Reached_GK:"payment_step_reached"};function num(value){const n=typeof value==="string"?parseFloat(value):value;return typeof n==="number"&&Number.isFinite(n)?n:void 0}function str(value){if(typeof value==="number"&&Number.isFinite(value))return String(value);return typeof value==="string"&&value!==""?value:void 0}function pick(from,keys){for(const key of keys)if(from[key]!==void 0&&from[key]!==null)return from[key];return void 0}var GOKWIK_FIELDS=["event","price_breakup","total_price","totalValue","orderId","orderName","cart_token"];function hasGokwikFields(payload){return GOKWIK_FIELDS.some(key=>key in payload)}function gokwikPayload(event){let payload=event.customData??event.data??{};for(let depth=0;depth<2;depth++){if(hasGokwikFields(payload))break;const inner=payload.data;if(!inner||typeof inner!=="object"||Array.isArray(inner))break;payload=inner}return payload}function gokwikProps(p){const breakup=p.price_breakup??{};const analytics2=p.commonAnalyticsData??{};const items=Array.isArray(p.Products)?p.Products:Array.isArray(p.cart)?p.cart:[];const coupon=str(pick(breakup,["coupon_code"]))??str(pick(p,["Coupon Code","coupon"]))??str(analytics2.coupon);const total=num(pick(p,["totalValue","total_amount"]))||num(breakup.total_amount)||num(p.total_price);return compact({order_id:str(pick(p,["orderId","order_id","orderName","order_name","order_number"])),gokwik_order_id:str(pick(p,["gokwikOid","moid"])),checkout_token:str(p.cart_token),currency:str(pick(breakup,["currency"]))??str(p.currency),revenue:total,subtotal:num(breakup.total_product_price),discount:num(pick(p,["discountAmount"]))??(num(breakup.total_discount_applied)||void 0),shipping:num(pick(p,["shippingPrice"]))??num(breakup.shipping_price),tax:num(pick(p,["tax"]))??num(breakup.tax),cod_charges:num(breakup.cod_charges)??num(analytics2.codCharges),payment_method:str(pick(p,["paymentMethod","payment_method"])),discount_codes:coupon&&coupon!=="NA"?[coupon]:void 0,is_guest:typeof p.is_guest==="boolean"?p.is_guest:void 0,item_count:items.length?items.reduce((sum,i)=>sum+(num(pick(i,["Product Quantity","quantity"]))??0),0):void 0,line_item_variant_ids:items.map(i=>str(pick(i,["Product Variant Id","Product Variant ID","variant_id"]))??""),line_item_product_ids:items.map(i=>str(pick(i,["Product ID","product_id"]))??""),line_item_titles:items.map(i=>str(pick(i,["Product Name","title"]))??""),line_item_quantities:items.map(i=>num(pick(i,["Product Quantity","quantity"]))??0),line_item_prices:items.map(i=>num(pick(i,["Product Price","price"]))??0),gk_event_id:str(p.event_id),checkout_provider:"gokwik"})}function mapGokwikStep(event){const payload=gokwikPayload(event);const step=str(payload.event)??str((event.customData??{}).name);if(!step)return null;const name=Object.prototype.hasOwnProperty.call(GOKWIK_STEPS,step)?GOKWIK_STEPS[step]:"gokwik_checkout_step";if(!name)return null;const properties=gokwikProps(payload);if(name==="gokwik_checkout_step")properties.gk_event=step;return{kind:"track",name,properties}}function mapGokwikPurchase(event){const properties=gokwikProps(gokwikPayload(event));if(properties.revenue===void 0)return null;return{kind:"track",name:"order_completed",properties}}function mapPageViewed(event){const location2=event.context?.document?.location;if(!isCheckoutPath(location2?.pathname))return null;return{kind:"page",name:event.context?.document?.title||"Checkout",properties:compact({path:location2?.pathname,$checkout_step:true})}}function mapEvent(event){const data=event.data??{};switch(event.name){case"page_viewed":return mapPageViewed(event);case"product_viewed":return{kind:"track",name:"product_viewed",properties:compact(variantProps(data.productVariant))};case"collection_viewed":{const collection=data.collection;return{kind:"track",name:"collection_viewed",properties:compact({collection_id:collection?.id??void 0,title:collection?.title??void 0,products_count:collection?.productVariants?.length??void 0})}}case"search_submitted":{const result=data.searchResult;return{kind:"track",name:"products_searched",properties:compact({query:result?.query??void 0,results_count:result?.productVariants?.length??void 0})}}case"product_added_to_cart":return{kind:"track",name:"product_added_to_cart",properties:cartLineProps(data.cartLine)};case"product_removed_from_cart":return{kind:"track",name:"product_removed_from_cart",properties:cartLineProps(data.cartLine)};case"cart_viewed":{const cart=data.cart;return{kind:"track",name:"cart_viewed",properties:compact({cart_id:cart?.id??void 0,item_count:cart?.totalQuantity??void 0,total_price:amount(cart?.cost?.totalAmount),currency:cart?.cost?.totalAmount?.currencyCode??void 0})}}case"checkout_started":case"checkout_contact_info_submitted":case"checkout_address_info_submitted":case"checkout_shipping_info_submitted":case"payment_info_submitted":return{kind:"track",name:event.name,properties:checkoutProps(data.checkout??{})};case"checkout_completed":return{kind:"track",name:"order_completed",properties:checkoutProps(data.checkout??{})};case"alert_displayed":{const alert=data.alert;return{kind:"track",name:"checkout_alert_displayed",properties:compact({alert_type:alert?.type??void 0,message:alert?.message??void 0})}}case"gokwik_events":return mapGokwikStep(event);case"gokwik_purchase_event":return mapGokwikPurchase(event);default:return null}}var SUBSCRIBED_EVENTS=["page_viewed","product_viewed","collection_viewed","search_submitted","product_added_to_cart","product_removed_from_cart","cart_viewed","checkout_started","checkout_contact_info_submitted","checkout_address_info_submitted","checkout_shipping_info_submitted","payment_info_submitted","checkout_completed","alert_displayed","gokwik_events","gokwik_purchase_event"];function toDepsmithSdkContext(context){const out={};const location2=context?.document?.location;if(location2?.href||location2?.pathname){out.page=compact({url:location2?.href,path:location2?.pathname,referrer:context?.document?.referrer,title:context?.document?.title})}const screen2=context?.window?.screen;if(typeof screen2?.width==="number"||typeof screen2?.height==="number"){out.screen=compact({width:screen2?.width,height:screen2?.height})}if(context?.navigator?.language)out.locale=context.navigator.language;if(context?.navigator?.userAgent)out.user_agent=context.navigator.userAgent;return out}var ANON_KEY="depsmith_anonymous_id";var COOKIE_MAX_AGE_SECONDS=60*60*24*365;var FLUSH_INTERVAL_MS=15e3;function resolveSandbox(){try{const api=globalThis.api??{};const resolvedAnalytics=typeof analytics!=="undefined"?analytics:api.analytics;const resolvedBrowser=typeof browser!=="undefined"?browser:api.browser;const resolvedInit=(typeof init!=="undefined"?init:api.init)??{};if(!resolvedAnalytics?.subscribe||!resolvedBrowser?.localStorage)return null;return{analytics:resolvedAnalytics,browser:resolvedBrowser,init:resolvedInit}}catch{return null}}var UNFILLED_API_KEY=["REPLACE","WITH","YOUR","API","KEY"].join("_");function readConfig(){const config=globalThis.DEPSMITH_SDK_CONFIG;if(!config?.apiKey||!config.endpoint)return null;if(config.apiKey===UNFILLED_API_KEY)return null;return config}async function startShopifyPixel(){const sandbox=resolveSandbox();const config=readConfig();if(!sandbox||!config)return;const storage=new AsyncMirrorAdapter(sandbox.browser.localStorage,DEPSMITH_SDK_STORAGE_KEYS);await storage.hydrate();let anonymousId=null;try{anonymousId=await sandbox.browser.cookie.get(ANON_KEY)||null}catch{}if(anonymousId)storage.set(ANON_KEY,anonymousId);const shop=sandbox.init.data?.shop;let context=toDepsmithSdkContext(sandbox.init.context);const client2=DepsmithSdk.init({...config,autocapture:false,compression:"none",consentMode:"granted",defaultProperties:{...config.defaultProperties,$source:"shopify_pixel",...shop?.myshopifyDomain?{$shop:shop.myshopifyDomain}:{},...shop?.paymentSettings?.currencyCode??shop?.currencyCode?{$currency:shop?.paymentSettings?.currencyCode??shop?.currencyCode}:{}}},{storage,manualLifecycle:true,contextProvider:()=>context,schedule:syncScheduler});if(!client2)return;if(!anonymousId){try{await sandbox.browser.cookie.set(`${ANON_KEY}=${DepsmithSdk.getAnonymousId()??""}; path=/; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`)}catch{}}const customer=sandbox.init.data?.customer;if(customer?.id){DepsmithSdk.identify(String(customer.id),{...customer.email?{email:customer.email}:{},...customer.firstName?{first_name:customer.firstName}:{},...customer.lastName?{last_name:customer.lastName}:{},...typeof customer.ordersCount==="number"?{orders_count:customer.ordersCount}:{}})}const handlerFor=name=>event=>{try{context=toDepsmithSdkContext(event.context??sandbox.init.context);const mapped=mapEvent(event);if(!mapped)return;const properties={...mapped.properties};if(event.clientId)properties.$shopify_client_id=event.clientId;if(mapped.kind==="page")DepsmithSdk.page(mapped.name,properties);else DepsmithSdk.track(mapped.name,properties);if(FLUSH_ON.has(name))void DepsmithSdk.flush()}catch{}};for(const name of SUBSCRIBED_EVENTS){sandbox.analytics.subscribe(name,handlerFor(name))}setInterval(()=>void DepsmithSdk.flush(),FLUSH_INTERVAL_MS)}void startShopifyPixel().catch(()=>{});})();
10
+ "use strict";(()=>{var UTM_PARAMS=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]];var KEY_CAMPAIGN="depsmith_campaign";var KEY_REFERRER="depsmith_referrer";function hostOf(url){try{return new URL(url).host||void 0}catch{return void 0}}var Attribution=class{constructor(storage){this.storage=storage;this.campaign={};this.referrer={};this.campaign=this.read(KEY_CAMPAIGN)??{};this.referrer=this.read(KEY_REFERRER)??{}}read(key){try{const raw=this.storage.get(key);if(!raw)return null;const parsed=JSON.parse(raw);return parsed&&typeof parsed==="object"?parsed:null}catch{return null}}write(key,value){try{this.storage.set(key,JSON.stringify(value))}catch{}}recordLanding(url,documentReferrer){let params;let currentHost;try{const parsed=new URL(url);params=parsed.searchParams;currentHost=parsed.host}catch{return}const incoming={};for(const[param,key]of UTM_PARAMS){const value=params.get(param);if(value)incoming[key]=value}if(Object.keys(incoming).length>0){this.campaign=incoming;this.write(KEY_CAMPAIGN,incoming)}const refHost=documentReferrer?hostOf(documentReferrer):void 0;const isExternal=Boolean(refHost)&&refHost!==currentHost;let changed=false;if(isExternal){this.referrer.url=documentReferrer;this.referrer.domain=refHost;changed=true}if(this.referrer.initial_domain===void 0){this.referrer.initial_domain=isExternal?refHost:"$direct";if(isExternal)this.referrer.initial_url=documentReferrer;changed=true}if(changed)this.write(KEY_REFERRER,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(KEY_CAMPAIGN);this.storage.remove(KEY_REFERRER)}catch{}}};var PageLifecycle=class{constructor(sink,_config){this.sink=sink;this.counter=0}get pageCount(){return this.counter}start(_url,_documentReferrer){this.counter=1}recordExplicit(){this.counter+=1}manual(name,properties,_type){this.counter+=1;this.sink.capture("$page_view","page_view",{...properties,$page_name:name?.trim()||"Unknown",$page_source:"manual",$page_counter:this.counter})}autoPageView(_watchTitle){}flushPending(){}discardPending(){}leave(_maxScroll){}restored(_persisted){}newSession(){this.counter=Math.min(this.counter,1)}tracking(){return{}}};function domainOf(_url){return void 0}function urlBase(_url){return void 0}function loadAutocapture(){return Promise.resolve(null)}var SUPPRESSIONS=[["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"]];var TRACKING_DEFAULTS=Object.fromEntries(SUPPRESSIONS.map(([option])=>[option,true]));function resolveTrackingOptions(options){const resolved={...TRACKING_DEFAULTS};if(!options)return resolved;for(const[option]of SUPPRESSIONS){if(options[option]===false)resolved[option]=false}return resolved}function applyTrackingOptions(context,options){const record=context;for(const[option,key,sub]of SUPPRESSIONS){if(options[option])continue;if(sub===void 0){delete record[key];continue}const block={...record[key]};delete block[sub];if(Object.keys(block).length>0)record[key]=block;else delete record[key]}return context}function resolveAutocapture(_autocapture){return false}function resolveConfig(config){if(!config||typeof config.apiKey!=="string"||config.apiKey.length===0){throw new Error("depsmith-sdk: apiKey is required")}if(typeof config.endpoint!=="string"||!/^https?:\/\//.test(config.endpoint)){throw new Error("depsmith-sdk: endpoint must be an http(s) URL")}const autocapture=resolveAutocapture(config.autocapture);return{apiKey:config.apiKey,endpoint:config.endpoint.replace(/\/+$/,""),batchSize:clamp(config.batchSize??20,1,500),batchIntervalMs:Math.max(config.batchIntervalMs??6e4,1e3),maxQueueSize:Math.max(config.maxQueueSize??1e3,1),maxQueueBytes:Math.max(config.maxQueueBytes??512*1024,4096),sessionTimeoutMs:Math.max(config.sessionTimeoutMs??18e5,6e4),sampleRate:Number.isFinite(config.sampleRate)?clamp(config.sampleRate,0,1):1,sessionEvents:config.sessionEvents==="derive"?"derive":"emit",consentMode:config.consentMode??"granted",respectDnt:config.respectDnt??true,maxRetries:clamp(config.maxRetries??5,0,10),debug:config.debug??false,defaultProperties:config.defaultProperties??{},autocapture,compression:config.compression??"gzip",childSafeMode:config.childSafeMode??false,anonymizeIp:(config.anonymizeIp??false)||(config.childSafeMode??false),deviceFingerprinting:config.deviceFingerprinting??true,geolocation:config.geolocation??false,trackingOptions:resolveTrackingOptions(config.trackingOptions),cookieDomain:config.cookieDomain??"",storage:config.storage??"localstorage",pageNames:config.pageNames}}function clamp(n,min,max){return Math.min(Math.max(n,min),max)}function djb2(input){let hash=5381;for(let i=0;i<input.length;i++){hash=(hash<<5)+hash+input.charCodeAt(i)>>>0}return hash.toString(36)}function fnv1aInt(input){let hash=2166136261;for(let i=0;i<input.length;i++){hash^=input.charCodeAt(i);hash=Math.imul(hash,16777619)>>>0}return hash>>>0}function fnv1a(input){return fnv1aInt(input).toString(36)}function bucket(input){return fnv1aInt(input)/4294967296}function fingerprintHash(input){return djb2(input)+fnv1a(input)}var hints={};var hintsRequested=false;function primeClientHints(){if(hintsRequested)return;hintsRequested=true;try{const uaData=navigator?.userAgentData;if(typeof uaData?.getHighEntropyValues!=="function")return;void uaData.getHighEntropyValues(["model","platformVersion"]).then(values=>{hints=values}).catch(()=>{})}catch{}}function parseUserAgent(){const result={};if(typeof navigator==="undefined")return result;const ua=navigator.userAgent||"";const uaData=navigator.userAgentData;const browser2=parseBrowser(ua,uaData);if(browser2)result.browser=browser2;const os=parseOS(ua);if(os){const hinted=normalizeOsVersion(os.name,hints.platformVersion);result.os=hinted?{...os,version:hinted}:os}const deviceType=parseDeviceType(ua,uaData);if(deviceType)result.deviceType=deviceType;const device=parseDevice(ua,os);if(device)result.device=device;return result}function parseDevice(ua,os){const device={};if(os?.name==="iOS"||os?.name==="macOS")device.manufacturer="Apple";const hinted=hints.model?.trim();if(hinted)device.model=hinted;else if(/iPhone/.test(ua))device.model="iPhone";else if(/iPad/.test(ua))device.model="iPad";return device.manufacturer||device.model?device:void 0}function normalizeOsVersion(osName,platformVersion){const raw=platformVersion?.trim();if(!raw)return void 0;if(osName==="Windows"){const major=Number.parseInt(raw.split(".")[0]??"",10);if(!Number.isFinite(major))return void 0;if(major===0)return void 0;return major>=13?"11":"10"}return trimVersion(raw)}var BROWSER_RULES=[{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 parseBrowser(ua,uaData){for(const rule of BROWSER_RULES){if(rule.requires&&!rule.requires.test(ua))continue;const match=ua.match(rule.pattern);if(match)return{name:rule.name,version:match[1],engine:rule.engine}}const brand=uaData?.brands?.find(b=>!/not.?a.?brand/i.test(b.brand));if(brand)return{name:brand.brand,version:brand.version};return void 0}var OS_RULES=[{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 parseOS(ua){for(const rule of OS_RULES){if(rule.requires&&!rule.requires.test(ua))continue;const match=ua.match(rule.pattern);if(match)return{name:rule.name,version:trimVersion((match[1]??"").replace(/_/g,"."))}}if(/Linux/.test(ua))return{name:"Linux"};return void 0}function trimVersion(version){const trimmed=version.replace(/(\.0)+$/,"");return trimmed.length>0?trimmed:version}function parseDeviceType(ua,uaData){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(ua))return"tablet";if(uaData?.mobile===true)return"mobile";if(/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(ua))return"mobile";if(/Android/.test(ua))return"tablet";if(typeof navigator!=="undefined"&&ua)return"desktop";return void 0}var cachedVisitorId=null;var cachedComponents=null;function components(){if(cachedComponents!==null)return cachedComponents;cachedComponents=collectSignals();return cachedComponents}function computeVisitorId(){if(cachedVisitorId!==null)return cachedVisitorId;cachedVisitorId=fingerprintHash(components().map(c=>c.value).join("|"));return cachedVisitorId}function fingerprintComponents(){const out={};for(const component of components())out[`$fp_${component.name}`]=component.value;return out}function collectSignals(){const signals=[];try{if(typeof screen!=="undefined"){signals.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`})}if(typeof navigator!=="undefined"){const nav=navigator;signals.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`});signals.push({name:"dm",value:`dm:${nav.deviceMemory??""}`});signals.push({name:"plat",value:`plat:${navigator.platform??""}`});signals.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}signals.push({name:"canvas",value:`canvas:${canvasFingerprint()}`})}catch{}return signals}function canvasFingerprint(){try{if(typeof document==="undefined")return"";const canvas=document.createElement("canvas");canvas.width=240;canvas.height=60;const ctx=canvas.getContext("2d");if(!ctx)return"";ctx.textBaseline="top";ctx.font="14px 'Arial'";ctx.fillStyle="#f60";ctx.fillRect(10,10,100,30);ctx.fillStyle="#069";ctx.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15);ctx.strokeStyle="rgba(0,120,200,0.5)";ctx.arc(50,30,20,0,Math.PI*2);ctx.stroke();return fingerprintHash(canvas.toDataURL())}catch{return""}}function readNetwork(){try{if(typeof navigator==="undefined")return{};const conn=navigator.connection;if(!conn)return{};switch(conn.type){case"wifi":return{type:"wifi"};case"ethernet":return{type:"ethernet"};case"none":return{type:"none"}}switch(conn.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var MAX_FIX_AGE_MS=5*6e4;var FIX_TIMEOUT_MS=1e4;var fix=null;var fixAt=0;var primed=false;var inFlight=false;var permission=null;function primeGeolocation(){if(primed)return;primed=true;try{if(typeof navigator==="undefined"||!navigator.geolocation)return;const permissions=navigator.permissions;if(typeof permissions?.query!=="function")return;void permissions.query({name:"geolocation"}).then(status=>{permission=status;if(status.state==="granted")requestFix();status.onchange=()=>{if(status.state==="granted")requestFix();else fix=null}}).catch(()=>{})}catch{}}function requestFix(){if(inFlight)return;inFlight=true;try{navigator.geolocation.getCurrentPosition(position=>{inFlight=false;const{latitude,longitude,accuracy}=position.coords;if(!Number.isFinite(latitude)||!Number.isFinite(longitude))return;const next={latitude,longitude,source:"gps"};if(Number.isFinite(accuracy))next.accuracy=accuracy;fix=next;fixAt=Date.now()},()=>{inFlight=false},{enableHighAccuracy:false,maximumAge:MAX_FIX_AGE_MS,timeout:FIX_TIMEOUT_MS})}catch{inFlight=false}}function readGeolocation(){if(!fix)return void 0;if(Date.now()-fixAt>MAX_FIX_AGE_MS&&permission?.state==="granted")requestFix();return{...fix}}var LIBRARY_NAME="@depsmith/depsmith-sdk";var SDK_VERSION="0.8.0";var invariants=null;function readInvariants(){if(invariants)return invariants;const next={};try{next.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}if(typeof navigator!=="undefined"){next.locale=navigator.language;next.userAgent=navigator.userAgent}invariants=next;return next}function buildContext(opts={}){const context={library:{name:LIBRARY_NAME,version:SDK_VERSION}};attempt(()=>{if(typeof window!=="undefined"&&window.location){const href=window.location.href;context.page={url:href,path:window.location.pathname,referrer:typeof document!=="undefined"?document.referrer:void 0,title:typeof document!=="undefined"?document.title:void 0,domain:domainOf(href),url_base:urlBase(href),...opts.page??{}}}});attempt(()=>{if(typeof window!=="undefined"&&window.screen){context.screen_size={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio}}});attempt(()=>{const cached=readInvariants();if(cached.locale!==void 0)context.locale=cached.locale;if(cached.userAgent!==void 0)context.user_agent=cached.userAgent;if(cached.timezone!==void 0)context.timezone=cached.timezone});attempt(()=>{const{deviceType}=parseUserAgent();if(deviceType)context.device={...context.device,type:deviceType}});attempt(()=>{if(opts.attribution){const campaign=opts.attribution.campaignBlock();if(campaign)context.campaign=campaign;const referrer=opts.attribution.referrerBlock();if(referrer)context.referrer=referrer}});attempt(()=>{if(opts.fingerprint)enrichFingerprint(context)});attempt(()=>{if(opts.geolocation){const fix2=readGeolocation();if(fix2)context.location=fix2}});try{if(opts.overrides){for(const[key,value]of Object.entries(opts.overrides)){if(value!==void 0)context[key]=value}context.library={name:LIBRARY_NAME,version:SDK_VERSION}}}catch{}if(opts.tracking)applyTrackingOptions(context,opts.tracking);return context}function enrichFingerprint(context){const{browser:browser2,os,deviceType,device:hinted}=parseUserAgent();if(browser2)context.browser=browser2;if(os)context.os=os;const device={...context.device};if(deviceType)device.type=deviceType;if(hinted?.manufacturer)device.manufacturer=hinted.manufacturer;if(hinted?.model)device.model=hinted.model;if(Object.keys(device).length>0)context.device=device;const network=readNetwork();if(network.type)context.network={...context.network,type:network.type}}function attempt(fn){try{fn()}catch{}}function dntEnabled(){try{if(typeof navigator==="undefined")return false;const nav=navigator;const win=typeof window!=="undefined"?window:{};const value=navigator.doNotTrack??win.doNotTrack??nav.msDoNotTrack;return value==="1"||value==="yes"}catch{return false}}var KEY_CONSENT="depsmith_consent";var ConsentManager=class{constructor(storage,initialMode,dntActive){this.storage=storage;this.dntActive=dntActive;const persisted=storage.get(KEY_CONSENT);this.state=persisted==="granted"||persisted==="denied"||persisted==="pending"?persisted:initialMode}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.effective()==="granted"}get current(){return this.effective()}optIn(){this.state="granted";this.storage.set(KEY_CONSENT,"granted")}optOut(){this.state="denied";this.storage.set(KEY_CONSENT,"denied")}};var IDLE_TIMEOUT_MS=250;var idleScheduler=fn=>{const idle=globalThis.requestIdleCallback;if(typeof idle==="function"){idle(fn,{timeout:IDLE_TIMEOUT_MS});return}setTimeout(fn,0)};var syncScheduler=fn=>fn();var KEY_QUEUE="depsmith_queue";var DEFAULT_MAX_CHARS=512*1024;var BRACKETS=2;var IDENTITY_EVENT_TYPES=new Set(["identify","alias","group"]);function isIdentityEvent(event){return IDENTITY_EVENT_TYPES.has(event?.event_type)}var EventQueue=class{constructor(storage,maxSize,logger,options={}){this.storage=storage;this.maxSize=maxSize;this.logger=logger;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=false;this.scheduled=false;this.maxChars=options.maxChars??DEFAULT_MAX_CHARS;this.schedule=options.schedule??idleScheduler;this.restore()}restore(){try{const raw=this.storage.get(KEY_QUEUE);if(!raw)return;const parsed=JSON.parse(raw);if(!Array.isArray(parsed))return;const kept=parsed.filter(e=>!!e&&typeof e==="object"&&typeof e.event_id==="string");this.reset(kept);if(kept.length!==parsed.length){this.logger.warn("discarded corrupt queued events on restore");this.markDirty()}if(this.trimToBudget())this.markDirty()}catch{this.logger.warn("queue storage corrupt; starting empty");this.reset([]);this.storage.remove(KEY_QUEUE)}}reset(events){this.events=events;this.sizes=events.map(e=>measure(e));this.sizeSum=this.sizes.reduce((a,b)=>a+b,0)}serializedLength(){if(this.events.length===0)return BRACKETS;return this.sizeSum+(this.events.length-1)+BRACKETS}trimToBudget(){let dropped=0;while(this.events.length>0&&this.serializedLength()>this.maxChars){this.evictAt(this.victimIndex());dropped++}if(dropped>0){this.logger.warn(`queue byte cap reached; dropped ${dropped} event(s)`)}return dropped>0}markDirty(){this.dirty=true;if(this.scheduled)return;this.scheduled=true;this.schedule(()=>{this.scheduled=false;this.persistNow()})}persistNow(){if(!this.dirty)return;this.dirty=false;this.storage.set(KEY_QUEUE,JSON.stringify(this.events))}prepend(events){const existing=new Set(this.events.map(e=>e.event_id));const fresh=events.filter(e=>!!e&&typeof e==="object"&&typeof e.event_id==="string"&&!existing.has(e.event_id));if(fresh.length===0)return;this.reset([...fresh,...this.events]);if(this.events.length>this.maxSize){this.dropOldest(this.events.length-this.maxSize)}this.trimToBudget();this.markDirty()}enqueue(event){const size=measure(event);if(size+BRACKETS>this.maxChars){this.logger.warn(`event ${event.event_id} exceeds the queue byte cap; dropped`);return}this.events.push(event);this.sizes.push(size);this.sizeSum+=size;if(this.events.length>this.maxSize){const dropped=this.events.length-this.maxSize;this.dropOldest(dropped);this.logger.warn(`queue cap reached; dropped ${dropped} event(s)`)}this.trimToBudget();this.markDirty()}victimIndex(){for(let i=0;i<this.events.length;i++){if(!isIdentityEvent(this.events[i]))return i}return 0}evictAt(index){this.events.splice(index,1);this.sizeSum-=this.sizes.splice(index,1)[0]??0}dropOldest(count){for(let n=0;n<count&&this.events.length>0;n++){this.evictAt(this.victimIndex())}}get size(){return this.events.length}peek(count){return this.events.slice(0,count)}remove(eventIds2){const ids=new Set(eventIds2);const events=[];const sizes=[];let sizeSum=0;for(let i=0;i<this.events.length;i++){const event=this.events[i];if(ids.has(event.event_id))continue;const size=this.sizes[i];events.push(event);sizes.push(size);sizeSum+=size}this.events=events;this.sizes=sizes;this.sizeSum=sizeSum;this.markDirty()}clear(){this.reset([]);this.dirty=false;this.storage.remove(KEY_QUEUE)}};function measure(event){return JSON.stringify(event).length}function uuidv7(now){const bytes=new Uint8Array(16);if(typeof crypto!=="undefined"&&crypto.getRandomValues){crypto.getRandomValues(bytes)}else{for(let i=0;i<16;i++)bytes[i]=Math.floor(Math.random()*256)}bytes[0]=now/2**40&255;bytes[1]=now/2**32&255;bytes[2]=now/2**24&255;bytes[3]=now/2**16&255;bytes[4]=now/2**8&255;bytes[5]=now&255;bytes[6]=bytes[6]&15|112;bytes[8]=bytes[8]&63|128;const hex=[];for(let i=0;i<16;i++)hex.push(bytes[i].toString(16).padStart(2,"0"));return`${hex[0]}${hex[1]}${hex[2]}${hex[3]}-${hex[4]}${hex[5]}-${hex[6]}${hex[7]}-${hex[8]}${hex[9]}-${hex[10]}${hex[11]}${hex[12]}${hex[13]}${hex[14]}${hex[15]}`}function uuidv7ToMs(id){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)){return null}const hex=id.slice(0,8)+id.slice(9,13);const ms=parseInt(hex,16);return Number.isFinite(ms)?ms:null}var DEPSMITH_SDK_STORAGE_KEYS=["depsmith_anonymous_id","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"];var MemoryAdapter=class{constructor(){this.data=new Map}get(key){return this.data.get(key)??null}set(key,value){this.data.set(key,value)}remove(key){this.data.delete(key)}};var CookieAdapter=class{constructor(domain){this.domain=domain}get(key){try{const prefix=`${encodeURIComponent(key)}=`;for(const part of document.cookie.split("; ")){if(part.startsWith(prefix))return decodeURIComponent(part.slice(prefix.length))}}catch{}return null}attributes(maxAge){const domain=this.domain?`; domain=${this.domain}`:"";const secure=typeof location!=="undefined"&&location.protocol==="https:"?"; Secure":"";return`${domain}; path=/; max-age=${maxAge}; SameSite=Lax${secure}`}set(key,value){try{const maxAge=60*60*24*400;document.cookie=`${encodeURIComponent(key)}=${encodeURIComponent(value)}${this.attributes(maxAge)}`}catch{}}remove(key){try{document.cookie=`${encodeURIComponent(key)}=${this.attributes(0)}`}catch{}}};var MIRRORED_IDENTITY_KEYS=new Set(["depsmith_anonymous_id"]);var RedundantAdapter=class{constructor(primary,secondary,mirrored=MIRRORED_IDENTITY_KEYS){this.primary=primary;this.secondary=secondary;this.mirrored=mirrored}get(key){const fromPrimary=this.primary.get(key);if(!this.mirrored.has(key))return fromPrimary;const fromSecondary=this.secondary.get(key);if(fromPrimary===fromSecondary)return fromPrimary;if(fromPrimary===null&&fromSecondary!==null){this.primary.set(key,fromSecondary);return fromSecondary}if(fromSecondary===null&&fromPrimary!==null){this.secondary.set(key,fromPrimary);return fromPrimary}const winner=olderUuidV7(fromPrimary,fromSecondary)??fromPrimary;this.primary.set(key,winner);this.secondary.set(key,winner);return winner}set(key,value){this.primary.set(key,value);if(this.mirrored.has(key))this.secondary.set(key,value)}remove(key){this.primary.remove(key);this.secondary.remove(key)}};function olderUuidV7(a,b){const aMs=uuidv7ToMs(a);const bMs=uuidv7ToMs(b);if(aMs===null||bMs===null)return null;return aMs<=bMs?a:b}var AsyncMirrorAdapter=class{constructor(backend,keys=DEPSMITH_SDK_STORAGE_KEYS){this.backend=backend;this.keys=keys;this.mirror=new Map;this.hydrated=null}hydrate(){this.hydrated??(this.hydrated=Promise.all(this.keys.map(async key=>{try{const value=await this.backend.getItem(key);if(typeof value==="string"&&!this.mirror.has(key))this.mirror.set(key,value)}catch{}})).then(()=>void 0));return this.hydrated}get(key){return this.mirror.get(key)??null}set(key,value){this.mirror.set(key,value);void Promise.resolve(this.backend.setItem(key,value)).catch(()=>{})}remove(key){this.mirror.delete(key);void Promise.resolve(this.backend.removeItem(key)).catch(()=>{})}};var IndexedDBAdapter=class extends MemoryAdapter{hydrate(){return Promise.resolve(new Map)}};function defaultStorage(){return new MemoryAdapter}var KEY_ANON="depsmith_anonymous_id";var KEY_USER="depsmith_user_id";var KEY_GROUP="depsmith_group_id";var KEY_PROPS="depsmith_user_props";var IdentityManager=class{constructor(storage,clock){this.storage=storage;this.clock=clock}get anonymousId(){let id=this.storage.get(KEY_ANON);if(!id){id=uuidv7(this.clock.now());this.storage.set(KEY_ANON,id)}return id}get userId(){return this.storage.get(KEY_USER)}get groupId(){return this.storage.get(KEY_GROUP)}identify(userId){this.storage.set(KEY_USER,userId)}setGroup(groupId){this.storage.set(KEY_GROUP,groupId)}getUserProps(){try{return JSON.parse(this.storage.get(KEY_PROPS)??"{}")}catch{return{}}}setUserProp(key,value){const props=this.getUserProps();props[key]=value;this.storage.set(KEY_PROPS,JSON.stringify(props))}hasUserProp(key){return key in this.getUserProps()}unsetUserProp(key){const props=this.getUserProps();delete props[key];this.storage.set(KEY_PROPS,JSON.stringify(props))}reset(){this.storage.remove(KEY_USER);this.storage.remove(KEY_GROUP);this.storage.remove(KEY_PROPS);const fresh=uuidv7(this.clock.now());this.storage.set(KEY_ANON,fresh);return fresh}};var KEY_SESSION="depsmith_session";var SessionManager=class{constructor(storage,clock,timeoutMs,schedule=idleScheduler){this.storage=storage;this.clock=clock;this.timeoutMs=timeoutMs;this.pending=null;this.scheduled=false;this.schedule=schedule}load(){const stored=this.readStored();const pending=this.pending;if(!pending)return stored;if(!stored||pending.lastActivityAt>=stored.lastActivityAt)return pending;this.pending=null;return stored}readStored(){try{const raw=this.storage.get(KEY_SESSION);if(!raw)return null;const parsed=JSON.parse(raw);if(typeof parsed.id!=="string"||typeof parsed.lastActivityAt!=="number")return null;if(typeof parsed.startedAt!=="number"){parsed.startedAt=uuidv7ToMs(parsed.id)??parsed.lastActivityAt}return parsed}catch{return null}}save(session){this.pending=session;if(this.scheduled)return;this.scheduled=true;this.schedule(()=>{this.scheduled=false;this.persistNow()})}persistNow(){const pending=this.pending;if(!pending)return;this.pending=null;this.storage.set(KEY_SESSION,JSON.stringify(pending))}mint(now){const fresh={id:uuidv7(now),lastActivityAt:now,startedAt:now};this.save(fresh);return fresh}touch(){const now=this.clock.now();const current=this.load();if(!current){const fresh=this.mint(now);return{sessionId:fresh.id,startedAt:now,startedSession:{id:fresh.id,startedAt:now}}}if(now-current.lastActivityAt>this.timeoutMs){const fresh=this.mint(now);return{sessionId:fresh.id,startedAt:now,endedSession:{id:current.id,lastActivityAt:current.lastActivityAt,startedAt:current.startedAt},startedSession:{id:fresh.id,startedAt:now}}}this.save({id:current.id,lastActivityAt:now,startedAt:current.startedAt});return{sessionId:current.id,startedAt:current.startedAt}}peek(){const current=this.load();if(current)return current.id;return this.mint(this.clock.now()).id}adopt(id,startedAt){const embedded=uuidv7ToMs(id);if(embedded===null)return false;this.save({id,lastActivityAt:this.clock.now(),startedAt:startedAt??embedded});return true}rotate(){return this.mint(this.clock.now()).id}};var MAX_TOP_LEVEL_KEYS=200;var MAX_ARRAY_ITEMS=100;var MAX_OBJECT_KEYS=50;function sanitizeProperties(input,logger){if(input===null||input===void 0)return{};if(typeof input!=="object"||Array.isArray(input)){logger.warn("properties must be an object; ignoring",input);return{}}const out={};let count=0;for(const[rawKey,rawValue]of Object.entries(input)){if(count>=MAX_TOP_LEVEL_KEYS){logger.warn(`properties exceed ${MAX_TOP_LEVEL_KEYS} keys; excess dropped`);break}const value=coerceValue(rawValue,logger);if(value===void 0){logger.debug(`property "${rawKey}" dropped (unsupported value)`);continue}out[String(rawKey)]=value;count++}return out}function coerceScalar(value){if(value===null)return null;const t=typeof value;if(t==="string"||t==="boolean")return value;if(t==="number")return Number.isFinite(value)?value:void 0;if(value instanceof Date)return isNaN(value.getTime())?void 0:value.toISOString();return void 0}function coerceValue(value,logger){const scalar=coerceScalar(value);if(scalar!==void 0)return scalar;if(value===void 0||typeof value==="function"||typeof value==="symbol")return void 0;if(Array.isArray(value)){const items=[];for(const item of value.slice(0,MAX_ARRAY_ITEMS)){const coerced=coerceScalar(item);items.push(coerced!==void 0?coerced:safeStringify(item))}return items}if(typeof value==="object"){const out={};let count=0;for(const[k,v]of Object.entries(value)){if(count>=MAX_OBJECT_KEYS){logger.debug(`nested object exceeds ${MAX_OBJECT_KEYS} keys; excess dropped`);break}const coerced=coerceScalar(v);out[String(k)]=coerced!==void 0?coerced:safeStringify(v);count++}return out}return void 0}function safeStringify(value){try{return JSON.stringify(value)??"null"}catch{return String(value)}}function stripReserved(input){return input}function isReserved(_key){return false}function observeNetworkErrors(_endpoint,_emit){return{stop:()=>{}}}function observeVitals(){return{snapshot:()=>({}),hasAny:()=>false,stop:()=>{}}}var SuperProperties=class{constructor(_storage,_logger){}register(_properties){}registerOnce(_properties){}unregister(_key){}clear(){}current(){return{}}};var TRAIT_OPERATORS=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"];var MAX_ADD_KEYS=50;var MAX_UNSET_KEYS=200;function normalizeUserPropertyOps(ops,logger){if(!ops||typeof ops!=="object")return void 0;if(ops.$clear_all===true){const others=Object.keys(ops).filter(k=>k!=="$clear_all");if(others.length>0){logger.warn(`$clear_all is exclusive; ignored ${others.join(", ")}`)}return{$clear_all:true}}const out={};const claimed=new Set;const claim=(key,operator)=>{if(isReserved(key,operator,logger))return false;if(claimed.has(key)){logger.debug(`"${key}" has an operator already; ${operator} dropped`);return false}claimed.add(key);return true};for(const operator of TRAIT_OPERATORS){const raw=ops[operator];if(!raw||typeof raw!=="object")continue;const clean=sanitizeProperties(raw,logger);const kept={};for(const[key,value]of Object.entries(clean)){if(!claim(key,operator))continue;kept[key]=value}if(Object.keys(kept).length>0)out[operator]=kept}if(ops.$add&&typeof ops.$add==="object"){const kept={};let count=0;for(const[key,value]of Object.entries(ops.$add)){if(count>=MAX_ADD_KEYS){logger.debug(`$add over ${MAX_ADD_KEYS} keys; excess dropped`);break}if(typeof value!=="number"||!Number.isFinite(value)){logger.debug(`$add "${key}" is not finite; dropped`);continue}if(!claim(key,"$add"))continue;kept[key]=value;count++}if(Object.keys(kept).length>0)out.$add=kept}if(Array.isArray(ops.$unset)){const kept=[];for(const key of ops.$unset){if(kept.length>=MAX_UNSET_KEYS){logger.debug(`$unset over ${MAX_UNSET_KEYS} keys; excess dropped`);break}if(typeof key!=="string"||key.length===0)continue;if(!claim(key,"$unset"))continue;kept.push(key)}if(kept.length>0)out.$unset=kept}return Object.keys(out).length>0?out:void 0}function sanitizedTraitOp(operator,clean){return Object.keys(clean).length>0?{[operator]:clean}:void 0}var systemClock={now:()=>Date.now()};function isoTimestamp(ms){return new Date(ms).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function isRetryable(status){return status===0||status===408||status===429||status>=500}var BASE_MS=1e3;var MAX_BACKOFF_MS=32e3;function backoffMs(attempt2,random=Math.random){const base=Math.min(BASE_MS*2**attempt2,MAX_BACKOFF_MS);return Math.round(random()*base)}async function gzip(text){const cs=new CompressionStream("gzip");const writer=cs.writable.getWriter();writer.write(new TextEncoder().encode(text)).catch(()=>{});writer.close().catch(()=>{});const reader=cs.readable.getReader();const chunks=[];for(;;){const{done,value}=await reader.read();if(done)break;chunks.push(value)}const total=chunks.reduce((n,c)=>n+c.length,0);const out=new Uint8Array(new ArrayBuffer(total));let offset=0;for(const chunk of chunks){out.set(chunk,offset);offset+=chunk.length}return out}function eventIds(batch){const ids=[];for(const event of batch)ids.push(event.event_id);return ids}var REQUEST_TIMEOUT_MS=3e4;var KEEPALIVE_MAX_BYTES=6e4;var MAX_UNLOAD_BATCHES=10;function bodyBytes(body){if(typeof body==="string")return new TextEncoder().encode(body).byteLength;if(body instanceof Uint8Array)return body.byteLength;return 0}var BatchUploader=class{constructor(queue,config,deps){this.queue=queue;this.config=config;this.deps=deps;this.inFlight=null}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){if(this.inFlight)return this.inFlight;this.inFlight=this.drain().catch(err=>this.deps.logger.error("flush failed",err)).finally(()=>{this.inFlight=null});return this.inFlight}async drain(){while(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("collector unreachable; uploads paused");return}const batch=this.queue.peek(this.config.batchSize);this.queue.persistNow();const result=await this.uploadWithRetry(batch);if(result==="requeue")return;if(result==="dropped")this.deps.logger.warn(`dropped poison batch of ${batch.length}`);this.queue.remove(eventIds(batch))}}async uploadWithRetry(batch){const breaker=this.deps.breaker;let answered=false;for(let attempt2=0;attempt2<=this.config.maxRetries;attempt2++){const status=await this.post(batch);if(status!==0)answered=true;if(status>=200&&status<300){breaker?.ok();return"sent"}if(!isRetryable(status)){breaker?.ok();this.deps.logger.warn(`non-retryable ${status}; dropping batch`);return"dropped"}this.deps.logger.debug(`upload attempt ${attempt2+1} failed (${status})`);if(status===0&&!answered&&breaker?.suspect())break;if(attempt2<this.config.maxRetries)await this.deps.sleep(backoffMs(attempt2))}if(answered)breaker?.ok();else breaker?.fail();return"requeue"}buildPayload(batch){const payload={batch,api_key:this.config.apiKey,source:"sdk",sent_at:isoTimestamp(this.deps.clock.now())};if(this.config.anonymizeIp)payload.anonymize_ip=true;return payload}async post(batch){const json=JSON.stringify(this.buildPayload(batch));const controller=typeof AbortController!=="undefined"?new AbortController:null;let timer=null;try{let body=json;const headers={"Content-Type":"application/json"};if(this.config.compression!=="none"&&typeof CompressionStream!=="undefined"){try{body=await gzip(json);headers["Content-Encoding"]="gzip"}catch{body=json}}const keepalive=bodyBytes(body)<=KEEPALIVE_MAX_BYTES;if(!keepalive){this.deps.logger.debug("payload over keepalive cap; sending without keepalive")}const init2={method:"POST",headers,body,keepalive};if(controller){init2.signal=controller.signal;timer=setTimeout(()=>controller.abort(),this.timeoutMs())}const res=await this.deps.fetchFn(`${this.config.endpoint}/e/`,init2);return res.status}catch{return 0}finally{if(timer!==null)clearTimeout(timer)}}timeoutMs(){const configured=this.config.requestTimeoutMs;return typeof configured==="number"&&configured>0?configured:REQUEST_TIMEOUT_MS}sendBeaconAll(){try{if(typeof navigator==="undefined"||!navigator.sendBeacon)return;let batches=0;while(this.queue.size>0&&batches<MAX_UNLOAD_BATCHES){const batch=this.queue.peek(this.config.batchSize);const payload=this.buildPayload(batch);const accepted=navigator.sendBeacon(`${this.config.endpoint}/e/`,new Blob([JSON.stringify(payload)],{type:"text/plain"}));if(!accepted)return;this.queue.remove(eventIds(batch));batches++}}catch{}}};var KEY_NET_BREAKER="depsmith_net_breaker";var TRIP_AFTER_CYCLES=3;var BASE_COOLDOWN_MS=5*6e4;var MAX_COOLDOWN_MS=60*6e4;function createNetworkBreaker(storage,clock){let loaded=false;let failures=0;let openUntil=0;let cooldown=BASE_COOLDOWN_MS;const clamp2=(v,lo,hi)=>typeof v==="number"&&v===v?Math.min(Math.max(v,lo),hi):lo;const load=()=>{if(loaded)return;loaded=true;try{const s=JSON.parse(storage.get(KEY_NET_BREAKER)??"0");if(!Array.isArray(s))return;failures=clamp2(s[0],0,TRIP_AFTER_CYCLES);openUntil=clamp2(s[1],0,clock.now()+MAX_COOLDOWN_MS);cooldown=clamp2(s[2],BASE_COOLDOWN_MS,MAX_COOLDOWN_MS)}catch{}};const save=()=>{try{if(failures)storage.set(KEY_NET_BREAKER,JSON.stringify([failures,openUntil,cooldown]));else storage.remove(KEY_NET_BREAKER)}catch{}};return{open:()=>(load(),clock.now()<openUntil),suspect:()=>(load(),failures>0),fail:()=>{load();if(++failures>=TRIP_AFTER_CYCLES){openUntil=clock.now()+cooldown;cooldown=Math.min(cooldown*2,MAX_COOLDOWN_MS);failures=TRIP_AFTER_CYCLES}save()},ok:()=>{load();if(!failures)return;failures=openUntil=0;cooldown=BASE_COOLDOWN_MS;save()}}}var Logger=class{constructor(enabled){this.enabled=enabled}setEnabled(enabled){this.enabled=enabled}debug(...args){if(this.enabled)console.debug("[depsmith-sdk]",...args)}warn(...args){if(this.enabled)console.warn("[depsmith-sdk]",...args)}error(...args){if(this.enabled)console.error("[depsmith-sdk]",...args)}};var MAX_ENVELOPE_ID_LENGTH=255;var DepsmithSdkClient=class{constructor(config,overrides={}){this.vitalsReported=false;this.flushTimer=null;this.drained=false;this.teardownFns=[];this.ready=Promise.resolve();this.config=resolveConfig(config);this.logger=new Logger(this.config.debug);this.clock=overrides.clock??systemClock;this.storage=overrides.storage??this.pickStorage();this.contextProvider=overrides.contextProvider;this.pageLife=new PageLifecycle({now:()=>this.clock.now(),capture:(name,type,properties,at,page)=>this.capture(name,type,properties,void 0,void 0,at,page)},this.config);const identityStorage=this.config.childSafeMode?new MemoryAdapter:this.config.storage==="memory"?this.storage:new RedundantAdapter(this.storage,new CookieAdapter(this.config.cookieDomain||void 0));this.identity=new IdentityManager(identityStorage,this.clock);this.session=new SessionManager(this.storage,this.clock,this.config.sessionTimeoutMs,overrides.schedule);this.consent=new ConsentManager(this.storage,this.config.consentMode,this.config.respectDnt&&(overrides.dnt??dntEnabled()));this.attribution=new Attribution(identityStorage);this.superProperties=new SuperProperties(this.storage,this.logger);if(!this.contextProvider&&typeof window!=="undefined"&&window.location){this.attribution.recordLanding(window.location.href,typeof document!=="undefined"?document.referrer:"");this.pageLife.start(window.location.href,typeof document!=="undefined"?document.referrer:"")}this.queue=new EventQueue(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:overrides.schedule});this.detectConfigDrift();if(this.config.deviceFingerprinting&&!this.config.childSafeMode){primeClientHints()}if(this.config.geolocation&&!this.config.childSafeMode){primeGeolocation()}if(this.storage instanceof IndexedDBAdapter){this.ready=this.storage.hydrate().then(persisted=>{try{const raw=persisted.get("depsmith_queue");if(raw)this.queue.prepend(JSON.parse(raw))}catch{this.logger.warn("persisted queue corrupt; discarded")}})}this.uploader=new BatchUploader(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:overrides.requestTimeoutMs},{fetchFn:overrides.fetchFn??((...args)=>fetch(...args)),clock:this.clock,logger:this.logger,sleep:overrides.sleep??(ms=>new Promise(r=>setTimeout(r,ms))),isOnline:overrides.isOnline??(()=>typeof navigator==="undefined"?true:navigator.onLine!==false),breaker:createNetworkBreaker(this.storage,this.clock)});if(!overrides.manualLifecycle){this.startFlushTimer();this.attachLifecycle();this.startAutocapture()}this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(name,properties){this.trackInternal(name,stripReserved(properties,"track",this.logger))}trackInternal(name,properties){this.guard(()=>{if(typeof name!=="string"||name.length===0){this.logger.warn("track: event name required");return}if(isReserved(name,"track",this.logger))return;if(this.tooLong(name,"track: event name"))return;this.capture(name,"track",properties)})}traits(traits,method){return sanitizeProperties(stripReserved(traits,method,this.logger),this.logger)}tooLong(value,label){if(value.length<=MAX_ENVELOPE_ID_LENGTH)return false;this.logger.warn(`${label} exceeds ${MAX_ENVELOPE_ID_LENGTH} characters (got ${value.length}); dropped`);return true}page(name,properties,options){this.pageInternal(name,stripReserved(properties,"page",this.logger),options)}pageInternal(name,properties,options){this.guard(()=>this.pageLife.manual(name,properties,options?.type))}emitWebVitals(){if(this.vitalsReported||!this.vitals?.hasAny())return;this.vitalsReported=true;this.capture("$web_vitals","track",this.vitals.snapshot())}screen(name,properties,options){this.page(name,properties,options)}identify(userId,traits){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof userId!=="string"||userId.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(userId,"identify: userId"))return;this.identity.identify(userId);const clean=this.traits(traits,"identify");this.capture("$identify","identify",void 0,clean,sanitizedTraitOp("$set",clean))})}alias(aliasId){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof aliasId!=="string"||aliasId.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:aliasId})})}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(groupId,traits){this.guard(()=>{if(typeof groupId!=="string"||groupId.length===0){this.logger.warn("group: groupId required");return}if(this.tooLong(groupId,"group: groupId"))return;this.identity.setGroup(groupId);const clean=this.traits(traits,"group");this.capture("$group","group",void 0,clean)})}setGroupTraits(traits){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}const clean=this.traits(traits,"setGroupTraits");this.capture("$group","group",void 0,clean)})}setProperty(key,value){this.guard(()=>{if(isReserved(key,"setProperty",this.logger))return;this.identity.setUserProp(key,value);const traits=sanitizeProperties({[key]:value},this.logger);this.capture("$identify","identify",void 0,traits,sanitizedTraitOp("$set",traits))})}setOnceProperty(key,value){this.guard(()=>{if(isReserved(key,"setOnceProperty",this.logger))return;if(this.identity.hasUserProp(key)){this.logger.debug(`setOnceProperty: "${key}" already set`);return}this.identity.setUserProp(key,value);const traits=sanitizeProperties({[key]:value},this.logger);this.capture("$identify","identify",void 0,traits,sanitizedTraitOp("$set_once",traits))})}unsetProperty(key){this.guard(()=>{if(isReserved(key,"unsetProperty",this.logger))return;this.identity.unsetUserProp(key);this.capture("$identify","identify",void 0,{[key]:null},normalizeUserPropertyOps({$unset:[key]},this.logger))})}register(properties){this.guard(()=>this.superProperties.register(properties))}registerOnce(properties){this.guard(()=>this.superProperties.registerOnce(properties))}unregister(key){this.guard(()=>this.superProperties.unregister(key))}setUserProperties(ops){this.guard(()=>{const normalized=normalizeUserPropertyOps(ops,this.logger);if(!normalized)return;this.capture("$identify","identify",void 0,void 0,normalized)})}optIn(){this.guard(()=>{this.consent.optIn();this.logger.debug("consent granted");void 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(err){this.logger.error("flush error",err)}}autocapture(properties){this.guard(()=>this.capture("$autocapture","autocapture",properties))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(sessionId,startedAt){this.guard(()=>{if(typeof sessionId!=="string"||!this.session.adopt(sessionId,startedAt)){this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(sessionId)}"`)}})}shutdown(){this.guard(()=>this.pageLife.flushPending());if(this.flushTimer!==null)clearInterval(this.flushTimer);this.flushTimer=null;for(const fn of this.teardownFns.splice(0))fn();this.persistNow()}persistNow(){try{this.queue.persistNow();this.session.persistNow()}catch{}}enqueueEvent(event){this.queue.enqueue(event);this.drained=false}flushUploads(){return this.ready.then(()=>this.uploader.flush())}contextOptions(){let overrides;try{overrides=this.contextProvider?.()}catch{}return{fingerprint:this.config.deviceFingerprinting&&!this.config.childSafeMode&&this.consent.current==="granted",geolocation:this.config.geolocation&&!this.config.childSafeMode&&this.consent.current==="granted",overrides,tracking:this.config.trackingOptions,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(sessionId){if(this.config.sampleRate>=1)return true;return bucket(`${this.config.apiKey}:${sessionId}`)<this.config.sampleRate}inSample(sessionId,type){if(type==="identify"||type==="alias"||type==="group")return true;return this.sessionInSample(sessionId)}capture(name,type,properties,traits,userProperties,at,page){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${name}`);return}const touch=this.session.touch();if(touch.startedSession)this.pageLife.newSession();if(touch.endedSession&&this.sessionInSample(touch.endedSession.id)){this.enqueueSessionEnd(touch.endedSession)}if(touch.startedSession&&this.sessionInSample(touch.startedSession.id)){this.enqueueSessionStart(touch.startedSession)}if(!this.inSample(touch.sessionId,type)){this.logger.debug(`capture dropped (out of sample): ${name}`);return}const now=at??this.clock.now();const contextOptions=this.contextOptions();if(page)contextOptions.page=page;const event={event_id:uuidv7(now),event:name,event_type:type,timestamp:isoTimestamp(now),session_id:touch.sessionId,session_started_at:isoTimestamp(touch.startedAt),anonymous_id:this.identity.anonymousId,context:traits?{...buildContext(contextOptions),traits}:buildContext(contextOptions),platform:"web",sdk_version:SDK_VERSION};if(userProperties)event.user_properties=userProperties;const props={...this.config.defaultProperties,...this.superProperties.current(),...sanitizeProperties(properties,this.logger)};if(Object.keys(props).length>0)event.properties=props;const userId=this.identity.userId;if(userId)event.user_id=userId;const groupId=this.identity.groupId;if(groupId)event.group_id=groupId;if(contextOptions.fingerprint)event.device_id=computeVisitorId();this.enqueueEvent(event);this.logger.debug(`captured ${name}`,event);if(this.queue.size>=this.config.batchSize&&this.consent.canUpload()){void this.flushUploads()}}detectConfigDrift(){const KEY="depsmith_config_fp";const fingerprint=djb2(this.config.apiKey);const stored=this.storage.get(KEY);if(stored!==null&&stored!==fingerprint){this.logger.warn("apiKey changed since last run; dropping queued events for the old project");this.queue.clear()}this.storage.set(KEY,fingerprint)}pickStorage(){if(this.config.storage==="memory")return new MemoryAdapter;if(this.config.storage==="indexeddb"&&typeof indexedDB!=="undefined"){return new IndexedDBAdapter}return defaultStorage()}enqueueSessionEnd(ended){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_end dropped (consent denied)");return}const contextOptions=this.contextOptions();const event={event_id:uuidv7(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:isoTimestamp(ended.lastActivityAt),session_id:ended.id,session_started_at:isoTimestamp(ended.startedAt),anonymous_id:this.identity.anonymousId,context:buildContext(contextOptions),platform:"web",sdk_version:SDK_VERSION};const userId=this.identity.userId;if(userId)event.user_id=userId;if(contextOptions.fingerprint)event.device_id=computeVisitorId();this.enqueueEvent(event)}enqueueSessionStart(started){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_start dropped (consent denied)");return}const contextOptions=this.contextOptions();const event={event_id:uuidv7(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:isoTimestamp(started.startedAt),session_id:started.id,session_started_at:isoTimestamp(started.startedAt),anonymous_id:this.identity.anonymousId,context:buildContext(contextOptions),platform:"web",sdk_version:SDK_VERSION};const userId=this.identity.userId;if(userId)event.user_id=userId;if(contextOptions.fingerprint)event.device_id=computeVisitorId();if(contextOptions.fingerprint){event.properties={...event.properties,...fingerprintComponents()}}this.enqueueEvent(event)}startFlushTimer(){this.flushTimer=setInterval(()=>{if(this.queue.size>0&&this.consent.canUpload())void this.flushUploads()},this.config.batchIntervalMs)}attachLifecycle(){if(typeof window==="undefined"||typeof document==="undefined")return;const onPageHide=()=>{if(this.drained)return;this.guard(()=>this.emitWebVitals());this.guard(()=>this.leaveOnUnload?.());this.drained=true;if(this.consent.canUpload())this.uploader.sendBeaconAll();this.persistNow()};const onVisibility=()=>{if(document.visibilityState==="hidden"){onPageHide()}else{this.drained=false;const touch=this.session.touch();if(touch.endedSession)this.enqueueSessionEnd(touch.endedSession);if(touch.startedSession){this.pageLife.newSession();this.enqueueSessionStart(touch.startedSession)}}};const onPageShow=event=>{this.drained=false;this.pageLife.restored(event.persisted)};const onOnline=()=>{this.uploader.resetNetworkBreaker();if(this.queue.size>0&&this.consent.canUpload())void this.flushUploads()};window.addEventListener("pagehide",onPageHide);window.addEventListener("pageshow",onPageShow);document.addEventListener("visibilitychange",onVisibility);window.addEventListener("online",onOnline);this.teardownFns.push(()=>{window.removeEventListener("pagehide",onPageHide);window.removeEventListener("pageshow",onPageShow);document.removeEventListener("visibilitychange",onVisibility);window.removeEventListener("online",onOnline)})}startAutocapture(){const autocaptureConfig=this.config.autocapture;if(!autocaptureConfig||typeof window==="undefined")return;if(typeof PerformanceObserver!=="undefined"){this.vitals=observeVitals();this.teardownFns.push(()=>this.vitals?.stop())}const network=observeNetworkErrors(this.config.endpoint,properties=>this.guard(()=>this.capture("$network_request","track",properties)));this.teardownFns.push(()=>network.stop());void loadAutocapture().then(module=>{if(!module)return;this.teardownFns.push(module.startAutocapture(autocaptureConfig,{emit:properties=>this.autocapture(properties),page:watchTitle=>this.guard(()=>this.pageLife.autoPageView(watchTitle)),pageLeave:maxScroll=>this.guard(()=>this.pageLife.leave(maxScroll)),warn:message=>this.logger.warn(message),armUnloadLeave:leave=>{this.leaveOnUnload=leave}}));this.teardownFns.push(()=>{this.leaveOnUnload=void 0})}).catch(err=>this.logger.debug("autocapture load failed",err))}guard(fn){try{fn()}catch(err){this.logger.error("internal error",err)}}};var client=null;var initApiKey=null;var DepsmithSdk={init(config,overrides){try{if(client&&initApiKey===config.apiKey){return client}client?.shutdown();client=new DepsmithSdkClient(config,overrides);initApiKey=config.apiKey;return client}catch(err){if(config?.debug)console.error("[depsmith-sdk] init failed:",err);return null}},track:(name,properties)=>client?.track(name,properties),page:(name,properties,options)=>client?.page(name,properties,options),screen:(name,properties,options)=>client?.screen(name,properties,options),identify:(userId,traits)=>client?.identify(userId,traits),alias:aliasId=>client?.alias(aliasId),reset:()=>client?.reset(),group:(groupId,traits)=>client?.group(groupId,traits),setGroupTraits:traits=>client?.setGroupTraits(traits),setProperty:(key,value)=>client?.setProperty(key,value),setOnceProperty:(key,value)=>client?.setOnceProperty(key,value),unsetProperty:key=>client?.unsetProperty(key),setUserProperties:ops=>client?.setUserProperties(ops),register:properties=>client?.register(properties),registerOnce:properties=>client?.registerOnce(properties),unregister:key=>client?.unregister(key),optIn:()=>client?.optIn(),optOut:()=>client?.optOut(),flush:()=>client?.flush()??Promise.resolve(),getAnonymousId:()=>client?.getAnonymousId(),getSessionId:()=>client?.getSessionId(),setSessionId:(sessionId,startedAt)=>client?.setSessionId(sessionId,startedAt),shutdown(){client?.shutdown();client=null;initApiKey=null}};var FLUSH_ON=new Set(["checkout_completed","payment_info_submitted","gokwik_purchase_event"]);function compact(input){const out={};for(const[key,value]of Object.entries(input)){if(value===void 0||value===null)continue;if(Array.isArray(value)&&value.length===0)continue;out[key]=value}return out}function amount(money){return typeof money?.amount==="number"?money.amount:void 0}function variantProps(variant){return{variant_id:variant?.id??void 0,variant_title:variant?.title??void 0,sku:variant?.sku??void 0,product_id:variant?.product?.id??void 0,title:variant?.product?.title??void 0,vendor:variant?.product?.vendor??void 0,product_type:variant?.product?.type??void 0,url:variant?.product?.url??void 0,price:amount(variant?.price),currency:variant?.price?.currencyCode??void 0}}function cartLineProps(line){return compact({...variantProps(line?.merchandise),quantity:line?.quantity??void 0,line_total:amount(line?.cost?.totalAmount)})}function isCheckoutPath(pathname){return typeof pathname==="string"&&(/^\/checkouts?\//.test(pathname)||/^\/orders\//.test(pathname))}function lineItemArrays(items){return compact({line_item_variant_ids:items.map(i=>i.variant?.id??""),line_item_product_ids:items.map(i=>i.variant?.product?.id??""),line_item_titles:items.map(i=>i.title??i.variant?.product?.title??""),line_item_quantities:items.map(i=>i.quantity??0),line_item_prices:items.map(i=>amount(i.finalLinePrice)??0)})}function checkoutProps(checkout){const items=checkout.lineItems??[];const discount=items.flatMap(item=>item.discountAllocations??[]).reduce((sum,allocation)=>sum+(amount(allocation.amount)??0),0);return compact({...lineItemArrays(items),order_id:checkout.order?.id??void 0,checkout_token:checkout.token??void 0,currency:checkout.currencyCode??checkout.totalPrice?.currencyCode??void 0,revenue:amount(checkout.totalPrice),subtotal:amount(checkout.subtotalPrice),tax:amount(checkout.totalTax),shipping:amount(checkout.shippingLine?.price),discount:discount>0?discount:void 0,item_count:items.reduce((sum,item)=>sum+(item.quantity??0),0),is_first_order:checkout.order?.customer?.isFirstOrder??void 0,customer_id:checkout.order?.customer?.id??void 0,discount_codes:(checkout.discountApplications??[]).map(application=>application.title??"").filter(Boolean)})}var GOKWIK_STEPS={Started_Checkout_GK:"checkout_started",Mobile_Added_GK:"checkout_contact_info_submitted",Address_Added_GK:"checkout_address_info_submitted",Address_Step_Reached_GK:null,Payment_Step_Reached_GK:"payment_step_reached"};function num(value){const n=typeof value==="string"?parseFloat(value):value;return typeof n==="number"&&Number.isFinite(n)?n:void 0}function str(value){if(typeof value==="number"&&Number.isFinite(value))return String(value);return typeof value==="string"&&value!==""?value:void 0}function pick(from,keys){for(const key of keys)if(from[key]!==void 0&&from[key]!==null)return from[key];return void 0}var GOKWIK_FIELDS=["event","price_breakup","total_price","totalValue","orderId","orderName","cart_token"];function hasGokwikFields(payload){return GOKWIK_FIELDS.some(key=>key in payload)}function gokwikPayload(event){let payload=event.customData??event.data??{};for(let depth=0;depth<2;depth++){if(hasGokwikFields(payload))break;const inner=payload.data;if(!inner||typeof inner!=="object"||Array.isArray(inner))break;payload=inner}return payload}function gokwikProps(p){const breakup=p.price_breakup??{};const analytics2=p.commonAnalyticsData??{};const items=Array.isArray(p.Products)?p.Products:Array.isArray(p.cart)?p.cart:[];const coupon=str(pick(breakup,["coupon_code"]))??str(pick(p,["Coupon Code","coupon"]))??str(analytics2.coupon);const total=num(pick(p,["totalValue","total_amount"]))||num(breakup.total_amount)||num(p.total_price);return compact({order_id:str(pick(p,["orderId","order_id","orderName","order_name","order_number"])),gokwik_order_id:str(pick(p,["gokwikOid","moid"])),checkout_token:str(p.cart_token),currency:str(pick(breakup,["currency"]))??str(p.currency),revenue:total,subtotal:num(breakup.total_product_price),discount:num(pick(p,["discountAmount"]))??(num(breakup.total_discount_applied)||void 0),shipping:num(pick(p,["shippingPrice"]))??num(breakup.shipping_price),tax:num(pick(p,["tax"]))??num(breakup.tax),cod_charges:num(breakup.cod_charges)??num(analytics2.codCharges),payment_method:str(pick(p,["paymentMethod","payment_method"])),discount_codes:coupon&&coupon!=="NA"?[coupon]:void 0,is_guest:typeof p.is_guest==="boolean"?p.is_guest:void 0,item_count:items.length?items.reduce((sum,i)=>sum+(num(pick(i,["Product Quantity","quantity"]))??0),0):void 0,line_item_variant_ids:items.map(i=>str(pick(i,["Product Variant Id","Product Variant ID","variant_id"]))??""),line_item_product_ids:items.map(i=>str(pick(i,["Product ID","product_id"]))??""),line_item_titles:items.map(i=>str(pick(i,["Product Name","title"]))??""),line_item_quantities:items.map(i=>num(pick(i,["Product Quantity","quantity"]))??0),line_item_prices:items.map(i=>num(pick(i,["Product Price","price"]))??0),gk_event_id:str(p.event_id),checkout_provider:"gokwik"})}function mapGokwikStep(event){const payload=gokwikPayload(event);const step=str(payload.event)??str((event.customData??{}).name);if(!step)return null;const name=Object.prototype.hasOwnProperty.call(GOKWIK_STEPS,step)?GOKWIK_STEPS[step]:"gokwik_checkout_step";if(!name)return null;const properties=gokwikProps(payload);if(name==="gokwik_checkout_step")properties.gk_event=step;return{kind:"track",name,properties}}function mapGokwikPurchase(event){const properties=gokwikProps(gokwikPayload(event));if(properties.revenue===void 0)return null;return{kind:"track",name:"order_completed",properties}}function mapPageViewed(event){const location2=event.context?.document?.location;if(!isCheckoutPath(location2?.pathname))return null;return{kind:"page",name:event.context?.document?.title||"Checkout",properties:compact({path:location2?.pathname,$checkout_step:true})}}function mapEvent(event){const data=event.data??{};switch(event.name){case"page_viewed":return mapPageViewed(event);case"product_viewed":return{kind:"track",name:"product_viewed",properties:compact(variantProps(data.productVariant))};case"collection_viewed":{const collection=data.collection;return{kind:"track",name:"collection_viewed",properties:compact({collection_id:collection?.id??void 0,title:collection?.title??void 0,products_count:collection?.productVariants?.length??void 0})}}case"search_submitted":{const result=data.searchResult;return{kind:"track",name:"products_searched",properties:compact({query:result?.query??void 0,results_count:result?.productVariants?.length??void 0})}}case"product_added_to_cart":return{kind:"track",name:"product_added_to_cart",properties:cartLineProps(data.cartLine)};case"product_removed_from_cart":return{kind:"track",name:"product_removed_from_cart",properties:cartLineProps(data.cartLine)};case"cart_viewed":{const cart=data.cart;return{kind:"track",name:"cart_viewed",properties:compact({cart_id:cart?.id??void 0,item_count:cart?.totalQuantity??void 0,total_price:amount(cart?.cost?.totalAmount),currency:cart?.cost?.totalAmount?.currencyCode??void 0})}}case"checkout_started":case"checkout_contact_info_submitted":case"checkout_address_info_submitted":case"checkout_shipping_info_submitted":case"payment_info_submitted":return{kind:"track",name:event.name,properties:checkoutProps(data.checkout??{})};case"checkout_completed":return{kind:"track",name:"order_completed",properties:checkoutProps(data.checkout??{})};case"alert_displayed":{const alert=data.alert;return{kind:"track",name:"checkout_alert_displayed",properties:compact({alert_type:alert?.type??void 0,message:alert?.message??void 0})}}case"gokwik_events":return mapGokwikStep(event);case"gokwik_purchase_event":return mapGokwikPurchase(event);default:return null}}var SUBSCRIBED_EVENTS=["page_viewed","product_viewed","collection_viewed","search_submitted","product_added_to_cart","product_removed_from_cart","cart_viewed","checkout_started","checkout_contact_info_submitted","checkout_address_info_submitted","checkout_shipping_info_submitted","payment_info_submitted","checkout_completed","alert_displayed","gokwik_events","gokwik_purchase_event"];function toDepsmithSdkContext(context){const out={};const location2=context?.document?.location;if(location2?.href||location2?.pathname){out.page=compact({url:location2?.href,path:location2?.pathname,referrer:context?.document?.referrer,title:context?.document?.title})}const screen2=context?.window?.screen;if(typeof screen2?.width==="number"||typeof screen2?.height==="number"){out.screen_size=compact({width:screen2?.width,height:screen2?.height})}if(context?.navigator?.language)out.locale=context.navigator.language;if(context?.navigator?.userAgent)out.user_agent=context.navigator.userAgent;return out}var ANON_KEY="depsmith_anonymous_id";var COOKIE_MAX_AGE_SECONDS=60*60*24*365;var FLUSH_INTERVAL_MS=15e3;function resolveSandbox(){try{const api=globalThis.api??{};const resolvedAnalytics=typeof analytics!=="undefined"?analytics:api.analytics;const resolvedBrowser=typeof browser!=="undefined"?browser:api.browser;const resolvedInit=(typeof init!=="undefined"?init:api.init)??{};if(!resolvedAnalytics?.subscribe||!resolvedBrowser?.localStorage)return null;return{analytics:resolvedAnalytics,browser:resolvedBrowser,init:resolvedInit}}catch{return null}}var UNFILLED_API_KEY=["REPLACE","WITH","YOUR","API","KEY"].join("_");function readConfig(){const config=globalThis.DEPSMITH_SDK_CONFIG;if(!config?.apiKey||!config.endpoint)return null;if(config.apiKey===UNFILLED_API_KEY)return null;return config}async function startShopifyPixel(){const sandbox=resolveSandbox();const config=readConfig();if(!sandbox||!config)return;const storage=new AsyncMirrorAdapter(sandbox.browser.localStorage,DEPSMITH_SDK_STORAGE_KEYS);await storage.hydrate();let anonymousId=null;try{anonymousId=await sandbox.browser.cookie.get(ANON_KEY)||null}catch{}if(anonymousId)storage.set(ANON_KEY,anonymousId);const shop=sandbox.init.data?.shop;let context=toDepsmithSdkContext(sandbox.init.context);const client2=DepsmithSdk.init({...config,autocapture:false,compression:"none",consentMode:"granted",defaultProperties:{...config.defaultProperties,$source:"shopify_pixel",...shop?.myshopifyDomain?{$shop:shop.myshopifyDomain}:{},...shop?.paymentSettings?.currencyCode??shop?.currencyCode?{$currency:shop?.paymentSettings?.currencyCode??shop?.currencyCode}:{}}},{storage,manualLifecycle:true,contextProvider:()=>context,schedule:syncScheduler});if(!client2)return;if(!anonymousId){try{await sandbox.browser.cookie.set(`${ANON_KEY}=${DepsmithSdk.getAnonymousId()??""}; path=/; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`)}catch{}}const customer=sandbox.init.data?.customer;if(customer?.id){DepsmithSdk.identify(String(customer.id),{...customer.email?{email:customer.email}:{},...customer.firstName?{first_name:customer.firstName}:{},...customer.lastName?{last_name:customer.lastName}:{},...typeof customer.ordersCount==="number"?{orders_count:customer.ordersCount}:{}})}const handlerFor=name=>event=>{try{context=toDepsmithSdkContext(event.context??sandbox.init.context);const mapped=mapEvent(event);if(!mapped)return;const properties={...mapped.properties};if(event.clientId)properties.$shopify_client_id=event.clientId;if(mapped.kind==="page")client2.pageInternal(mapped.name,properties);else client2.trackInternal(mapped.name,properties);if(FLUSH_ON.has(name))void DepsmithSdk.flush()}catch{}};for(const name of SUBSCRIBED_EVENTS){sandbox.analytics.subscribe(name,handlerFor(name))}setInterval(()=>void DepsmithSdk.flush(),FLUSH_INTERVAL_MS)}void startShopifyPixel().catch(()=>{});})();