@depsmith/depsmith-sdk 0.9.2 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 KEY_CAMPAIGN="depsmith_campaign";var KEY_REFERRER="depsmith_referrer";var Attribution=class{constructor(storage){this.storage=storage;this.campaign=this.read(KEY_CAMPAIGN);this.referrer=this.read(KEY_REFERRER)}read(key){try{const parsed=JSON.parse(this.storage.get(key)||"null");return parsed&&typeof parsed==="object"?parsed:{}}catch{return{}}}recordLanding(_url,_documentReferrer){}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 startLifecycle(_host){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:int(config.batchSize,20,1,500),batchIntervalMs:int(config.batchIntervalMs,6e4,1e3,2**31-1),maxQueueSize:int(config.maxQueueSize,1e3,1),maxQueueBytes:int(config.maxQueueBytes,512*1024,4096),sessionTimeoutMs:int(config.sessionTimeoutMs,18e5,6e4),sampleRate:num(config.sampleRate,1,0,1),sessionEvents:config.sessionEvents==="derive"?"derive":"emit",consentMode:config.consentMode??"granted",respectDnt:config.respectDnt??true,maxRetries:int(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,scrubUrls:config.scrubUrls??false,trackingOptions:resolveTrackingOptions(config.trackingOptions),cookieDomain:config.cookieDomain??"",storage:config.storage??"localstorage",pageNames:config.pageNames}}function num(value,fallback,min,max=Infinity){return Math.min(Math.max(Number.isFinite(value)?value:fallback,min),max)}function int(value,fallback,min,max){return Math.floor(num(value,fallback,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}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{};const type=conn.type;if(type==="wifi"||type==="ethernet"||type==="none")return{type};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;var allowed=()=>true;function primeGeolocation(gate=allowed){allowed=gate;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||!allowed())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(!allowed())fix=null;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.9.2";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,maxChars=Infinity,from=0){let end=from;for(let total=0;end<this.events.length&&end-from<count;end++){total+=this.sizes[end]+1;if(end>from&&total>maxChars)break}return this.events.slice(from,end)}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()}close(){}clear(){this.reset([]);this.dirty=false;this.storage.remove(KEY_QUEUE)}};function measure(event){return JSON.stringify(event).length}var lastMs=-1;var lastSeq=0;var SEQ_MASK=67108863;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;let seq=(bytes[6]&7)<<22|bytes[7]<<14|(bytes[8]&63)<<8|bytes[9];if(now===lastMs){seq=lastSeq=lastSeq+1&SEQ_MASK}else if(now>lastMs){lastMs=now;lastSeq=seq}bytes[6]=112|seq>>>22;bytes[7]=seq>>>14&255;bytes[8]=128|seq>>>8&63;bytes[9]=seq&255;let hex="";for(let i=0;i<16;i++)hex+=(bytes[i]+256).toString(16).slice(1);return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}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_anon_reset_at","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker","depsmith_campaign","depsmith_referrer","depsmith_super_props"];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 KEY_ANON_RESET="depsmith_anon_reset_at";var MIRRORED_IDENTITY_KEYS=new Set(["depsmith_anonymous_id",KEY_ANON_RESET]);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=this.pick(fromPrimary,fromSecondary);this.primary.set(key,winner);this.secondary.set(key,winner);return winner}pick(a,b){const aMs=uuidv7ToMs(a);const bMs=uuidv7ToMs(b);if(aMs===null||bMs===null)return a;const stores=[this.primary,this.secondary];const at=Math.max(...stores.map(s=>Number(s.get(KEY_ANON_RESET))||0));if(at)stores.forEach(s=>s.set(KEY_ANON_RESET,`${at}`));const live=aMs>=at;if(live!==bMs>=at)return live?a:b;return aMs<=bMs?a:b}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)}};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(()=>{})}};function defaultStorage(){return new MemoryAdapter}function pickQueueStorage(_mode,fallback){return fallback}function hydrateQueue(){return Promise.resolve()}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 now=this.clock.now();this.storage.set(KEY_ANON_RESET,`${now}`);const fresh=uuidv7(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(_config,_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)}function retryAfterMs(value,now){if(!value)return 0;const seconds=Number(value);const ms=seconds===seconds?seconds*1e3:Date.parse(value)-now;return ms>0?ms:0}function compress(_text,_mode){return Promise.resolve(null)}function sendBeacons(){}function eventIds(batch){return batch.map(event=>event.event_id)}var REQUEST_TIMEOUT_MS=3e4;var KEEPALIVE_MAX_BYTES=6e4;var MAX_BATCH_CHARS=256e3;function bodyBytes(body){if(typeof body==="string")return new TextEncoder().encode(body).byteLength;if(body instanceof Uint8Array)return body.byteLength;return 0}var REDIRECTED=399;function refused(status){return status>299&&status<400||status===401||status===403}var HOLD_BASE_MS=3e4;var HOLD_MAX_MS=60*6e4;var BatchUploader=class{constructor(queue,config,deps){this.queue=queue;this.config=config;this.deps=deps;this.inFlight=null;this.uploading=0;this.limit=0;this.strikes=0;this.wait=0}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){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(){this.limit=0;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("uploads paused");return}const max=this.config.batchSize;const batch=this.queue.peek(this.limit||max,MAX_BATCH_CHARS);this.queue.persistNow();this.uploading=batch.length;const status=await this.uploadWithRetry(batch);this.uploading=0;if(refused(status)||isRetryable(status))return;if(status===400||status===413){if(batch.length>1){this.limit=batch.length>>1;continue}this.limit=0}if(status>299)this.deps.logger.notice(`collector answered ${status}; dropped ${batch.length} event(s)`);this.queue.remove(eventIds(batch));if(status===400)return}}async uploadWithRetry(batch){const breaker=this.deps.breaker;let answered=false;let status=0;for(let attempt2=0;attempt2<=this.config.maxRetries;attempt2++){if(attempt2&&(this.deps.canUpload?.()===false||this.queue.peek(1)[0]?.event_id!==batch[0].event_id)){break}status=await this.post(batch);if(status)answered=true;if(!isRetryable(status)||this.wait)break;this.deps.logger.debug(`upload attempt ${attempt2+1} failed (${status})`);if(!answered&&breaker?.suspect())break;if(attempt2<this.config.maxRetries)await this.deps.sleep(backoffMs(attempt2))}if(!answered){breaker?.fail()}else{breaker?.ok();if(status>199&&status<300)this.strikes=0;else if(refused(status)||isRetryable(status)){if(refused(status))this.deps.logger.notice(`collector refused uploads (${status}); paused`);breaker?.hold(this.wait||Math.min(HOLD_BASE_MS*2**this.strikes++,HOLD_MAX_MS))}}return status}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){this.wait=0;const json=JSON.stringify(this.buildPayload(batch));const controller=typeof AbortController!=="undefined"?new AbortController:null;let timer=null;try{const headers={"Content-Type":"application/json"};const zipped=await compress(json,this.config.compression);if(zipped)headers["Content-Encoding"]="gzip";const body=zipped??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);if(res.redirected)return REDIRECTED;this.wait=retryAfterMs(res.headers?.get("Retry-After"),this.deps.clock.now());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(){sendBeacons(this.queue,this.config,this.deps,this.uploading,batch=>this.buildPayload(batch))}};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 clamp=(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=clamp(s[0],0,TRIP_AFTER_CYCLES);openUntil=clamp(s[1],0,clock.now()+MAX_COOLDOWN_MS);cooldown=clamp(s[2],BASE_COOLDOWN_MS,MAX_COOLDOWN_MS)}catch{}};const save=()=>{try{if(failures||openUntil>clock.now())storage.set(KEY_NET_BREAKER,JSON.stringify([failures,openUntil,cooldown]));else storage.remove(KEY_NET_BREAKER)}catch{}};return{open:()=>(load(),clock.now()<(openUntil=Math.min(openUntil,clock.now()+MAX_COOLDOWN_MS))),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()},hold:ms=>{load();openUntil=Math.max(openUntil,clock.now()+Math.min(ms,MAX_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)}notice(...args){console.warn("[depsmith-sdk]",...args)}error(...args){if(this.enabled)console.error("[depsmith-sdk]",...args)}};var CONTEXT_KEYS=["url","referrer","previous_url","initial_url"];var URL_PROPERTIES=["$ac_href","$ac_form_action","$net_url","$fr_error_file"];function scrubUrl(url,keep){const bare=url.split("#")[0];const q=bare.indexOf("?");if(q<0)return bare;const kept=bare.slice(q+1).split("&").filter(pair=>keep.has(paramName(pair)));return bare.slice(0,q)+(kept.length?`?${kept.join("&")}`:"")}function paramName(pair){const name=pair.split("=")[0].replace(/\+/g," ");try{return decodeURIComponent(name)}catch{return name}}function scrubEventUrls(event,option){if(!option)return;try{const params=option.keepParams;const keep=new Set(Array.isArray(params)?params:[]);const targets=[[event.context.page,CONTEXT_KEYS],[event.context.referrer,CONTEXT_KEYS],[event.properties,URL_PROPERTIES]];for(const[target,keys]of targets){for(const key of keys){const value=target?.[key];if(typeof value==="string")target[key]=scrubUrl(value,keep)}}const props=event.properties;if(!props)return;delete props.$net_fragment;if(typeof props.$net_query==="string"){const query=scrubUrl(`?${props.$net_query}`,keep).slice(1);if(query)props.$net_query=query;else delete props.$net_query}}catch{}}var KEY_CONFIG_FP="depsmith_config_fp";var MAX_ENVELOPE_ID_LENGTH=255;var DepsmithSdkClient=class{constructor(config,overrides={}){this.vitalsReported=false;this.stopped=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();const queueStorage=overrides.storage?this.storage:pickQueueStorage(this.config.storage,this.storage);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:"")}const fp=djb2(this.config.apiKey);const owned={get:key=>queueStorage.get(key),set:(key,value)=>{if(this.storage.get(KEY_CONFIG_FP)===fp)queueStorage.set(key,value)},remove:key=>queueStorage.remove(key)};this.queue=new EventQueue(owned,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:overrides.schedule});const drifted=this.detectConfigDrift(fp);this.primeDeviceSignals();this.ready=hydrateQueue(queueStorage,this.storage,this.consent,this.queue,drifted,this.logger);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),canUpload:()=>this.consent.canUpload()});if(!overrides.manualLifecycle){this.lifecycle=startLifecycle({intervalMs:this.config.batchIntervalMs,guard:fn=>this.guard(fn),vitals:()=>this.emitWebVitals(),leave:()=>this.leaveOnUnload?.(),restored:persisted=>this.pageLife.restored(persisted),resume:()=>this.resumeSession(),flushIfQueued:()=>this.flushIfQueued(),persistNow:()=>this.persistNow(),beacon:()=>{if(this.consent.canUpload())this.uploader.sendBeaconAll()},online:()=>{this.uploader.resetNetworkBreaker();this.flushIfQueued()}});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.setUserProp(key,value,"$set")})}setUserProp(key,value,op){this.identity.setUserProp(key,value);const traits=sanitizeProperties({[key]:value},this.logger);this.capture("$identify","identify",void 0,traits,sanitizedTraitOp(op,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.setUserProp(key,value,"$set_once")})}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");this.primeDeviceSignals();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());this.stopped=true;this.lifecycle?.stop();for(const fn of this.teardownFns.splice(0))fn();this.persistNow();this.queue.close()}persistNow(){try{this.queue.persistNow();this.session.persistNow()}catch{}}deviceSignals(){return!this.config.childSafeMode&&this.consent.canUpload()}primeDeviceSignals(){if(!this.deviceSignals())return;if(this.config.deviceFingerprinting)primeClientHints();if(this.config.geolocation)primeGeolocation(()=>this.deviceSignals())}enqueueEvent(event){scrubEventUrls(event,this.config.scrubUrls);this.queue.enqueue(event);this.lifecycle?.rearm()}flushUploads(){return this.ready.then(()=>this.uploader.flush())}flushIfQueued(){if(this.queue.size>0&&this.consent.canUpload())void this.flushUploads()}contextOptions(){let overrides;try{overrides=this.contextProvider?.()}catch{}const signals=this.deviceSignals();return{fingerprint:this.config.deviceFingerprinting&&signals,geolocation:this.config.geolocation&&signals,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.touchSession();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=sanitizeProperties({...this.config.defaultProperties,...this.superProperties.current(),...sanitizeProperties(properties,this.logger)},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(fingerprint){const stored=this.storage.get(KEY_CONFIG_FP);const drifted=stored!==null&&stored!==fingerprint;if(drifted){this.logger.warn("apiKey changed since last run; dropping queued events for the old project");this.queue.clear();this.storage.remove(KEY_NET_BREAKER)}this.storage.set(KEY_CONFIG_FP,fingerprint);return drifted}pickStorage(){return this.config.storage==="memory"?new MemoryAdapter:defaultStorage()}enqueueSessionBoundary(kind,id,at,startedAt){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug(`session_${kind} dropped (consent denied)`);return}const contextOptions=this.contextOptions();const event={event_id:uuidv7(this.clock.now()),event:`$session_${kind}`,event_type:`session_${kind}`,timestamp:isoTimestamp(at),session_id:id,session_started_at:isoTimestamp(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(kind==="start")event.properties=fingerprintComponents()}this.enqueueEvent(event)}touchSession(){const touch=this.session.touch();if(touch.startedSession)this.pageLife.newSession();if(touch.endedSession&&this.sessionInSample(touch.endedSession.id)){const ended=touch.endedSession;this.enqueueSessionBoundary("end",ended.id,ended.lastActivityAt,ended.startedAt)}if(touch.startedSession&&this.sessionInSample(touch.startedSession.id)){const started=touch.startedSession;this.enqueueSessionBoundary("start",started.id,started.startedAt,started.startedAt)}return touch}resumeSession(){if(this.consent.canCapture())this.touchSession()}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,properties=>this.guard(()=>this.capture("$network_request","track",properties)));this.teardownFns.push(()=>network.stop());void loadAutocapture().then(module=>{if(!module)return;if(this.stopped)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 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,variant_title:variant?.title,sku:variant?.sku,product_id:variant?.product?.id,title:variant?.product?.title,vendor:variant?.product?.vendor,product_type:variant?.product?.type,url:variant?.product?.url,price:amount(variant?.price),currency:variant?.price?.currencyCode}}function cartLineProps(line){return compact({...variantProps(line?.merchandise),quantity:line?.quantity,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,checkout_token:checkout.token,currency:checkout.currencyCode??checkout.totalPrice?.currencyCode,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,customer_id:checkout.order?.customer?.id,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 num2(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=num2(pick(p,["totalValue","total_amount"]))||num2(breakup.total_amount)||num2(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:num2(breakup.total_product_price),discount:num2(pick(p,["discountAmount"]))??(num2(breakup.total_discount_applied)||void 0),shipping:num2(pick(p,["shippingPrice"]))??num2(breakup.shipping_price),tax:num2(pick(p,["tax"]))??num2(breakup.tax),cod_charges:num2(breakup.cod_charges)??num2(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+(num2(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=>num2(pick(i,["Product Quantity","quantity"]))??0),line_item_prices:items.map(i=>num2(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,title:collection?.title,products_count:collection?.productVariants?.length})}}case"search_submitted":{const result=data.searchResult;return{kind:"track",name:"products_searched",properties:compact({query:result?.query,results_count:result?.productVariants?.length})}}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,item_count:cart?.totalQuantity,total_price:amount(cart?.cost?.totalAmount),currency:cart?.cost?.totalAmount?.currencyCode})}}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,message:alert?.message})}}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;var PIXEL_OWN_KEYS=["depsmith_queue","depsmith_config_fp","depsmith_net_breaker"];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;let deliver;const early=[];const handlerFor=name=>event=>{if(deliver)deliver(name,event);else if(early.length<100)early.push([name,event])};for(const name of SUBSCRIBED_EVENTS){sandbox.analytics.subscribe(name,handlerFor(name))}const kv=sandbox.browser.localStorage;const own=key=>PIXEL_OWN_KEYS.includes(key)?key.replace("depsmith_","depsmith_pixel_"):key;const storage=new AsyncMirrorAdapter({getItem:key=>kv.getItem(own(key)),setItem:(key,value)=>kv.setItem(own(key),value),removeItem:key=>kv.removeItem(own(key))},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;const currency=shop?.paymentSettings?.currencyCode??shop?.currencyCode;let context=toDepsmithSdkContext(sandbox.init.context);let client;try{client=new DepsmithSdkClient({...config,autocapture:false,compression:"none",consentMode:"granted",defaultProperties:{...config.defaultProperties,$source:"shopify_pixel",...shop?.myshopifyDomain?{$shop:shop.myshopifyDomain}:{},...currency?{$currency:currency}:{}}},{storage,manualLifecycle:true,contextProvider:()=>context,schedule:syncScheduler})}catch{deliver=()=>{};return}const customer=sandbox.init.data?.customer;if(customer?.id){client.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}:{}})}deliver=(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")client.pageInternal(mapped.name,properties);else client.trackInternal(mapped.name,properties);if(FLUSH_ON.has(name))void client.flush()}catch{}};for(const[name,event]of early.splice(0))deliver(name,event);setInterval(()=>void client.flush(),FLUSH_INTERVAL_MS);if(!anonymousId){try{await sandbox.browser.cookie.set(`${ANON_KEY}=${client.getAnonymousId()??""}; path=/; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`)}catch{}}}void startShopifyPixel().catch(()=>{});})();
10
+ "use strict";(()=>{var KEY_CAMPAIGN="depsmith_campaign";var KEY_REFERRER="depsmith_referrer";var Attribution=class{constructor(storage){this.storage=storage;this.campaign=this.read(KEY_CAMPAIGN);this.referrer=this.read(KEY_REFERRER)}read(key){try{const parsed=JSON.parse(this.storage.get(key)||"null");return parsed&&typeof parsed==="object"?parsed:{}}catch{return{}}}recordLanding(_url,_documentReferrer){}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 startLifecycle(_host){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:int(config.batchSize,20,1,500),batchIntervalMs:int(config.batchIntervalMs,6e4,1e3,2**31-1),maxQueueSize:int(config.maxQueueSize,1e3,1),maxQueueBytes:int(config.maxQueueBytes,512*1024,4096),sessionTimeoutMs:int(config.sessionTimeoutMs,18e5,6e4),sampleRate:num(config.sampleRate,1,0,1),sessionEvents:config.sessionEvents==="derive"?"derive":"emit",consentMode:config.consentMode??"granted",respectDnt:config.respectDnt??true,maxRetries:int(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,scrubUrls:config.scrubUrls??false,trackingOptions:resolveTrackingOptions(config.trackingOptions),cookieDomain:config.cookieDomain??"",storage:config.storage??"localstorage",pageNames:config.pageNames}}function num(value,fallback,min,max=Infinity){return Math.min(Math.max(Number.isFinite(value)?value:fallback,min),max)}function int(value,fallback,min,max){return Math.floor(num(value,fallback,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}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{};const type=conn.type;if(type==="wifi"||type==="ethernet"||type==="none")return{type};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;var allowed=()=>true;function primeGeolocation(gate=allowed){allowed=gate;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||!allowed())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(!allowed())fix=null;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.9.3";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,maxChars=Infinity,from=0){let end=from;for(let total=0;end<this.events.length&&end-from<count;end++){total+=this.sizes[end]+1;if(end>from&&total>maxChars)break}return this.events.slice(from,end)}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()}close(){}clear(){this.reset([]);this.dirty=false;this.storage.remove(KEY_QUEUE)}};function measure(event){return JSON.stringify(event).length}var lastMs=-1;var lastSeq=0;var SEQ_MASK=67108863;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;let seq=(bytes[6]&7)<<22|bytes[7]<<14|(bytes[8]&63)<<8|bytes[9];if(now===lastMs){seq=lastSeq=lastSeq+1&SEQ_MASK}else if(now>lastMs){lastMs=now;lastSeq=seq}bytes[6]=112|seq>>>22;bytes[7]=seq>>>14&255;bytes[8]=128|seq>>>8&63;bytes[9]=seq&255;let hex="";for(let i=0;i<16;i++)hex+=(bytes[i]+256).toString(16).slice(1);return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}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_anon_reset_at","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker","depsmith_campaign","depsmith_referrer","depsmith_super_props"];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 KEY_ANON_RESET="depsmith_anon_reset_at";var MIRRORED_IDENTITY_KEYS=new Set(["depsmith_anonymous_id",KEY_ANON_RESET]);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=this.pick(fromPrimary,fromSecondary);this.primary.set(key,winner);this.secondary.set(key,winner);return winner}pick(a,b){const aMs=uuidv7ToMs(a);const bMs=uuidv7ToMs(b);if(aMs===null||bMs===null)return a;const stores=[this.primary,this.secondary];const at=Math.max(...stores.map(s=>Number(s.get(KEY_ANON_RESET))||0));if(at)stores.forEach(s=>s.set(KEY_ANON_RESET,`${at}`));const live=aMs>=at;if(live!==bMs>=at)return live?a:b;return aMs<=bMs?a:b}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)}};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(()=>{})}};function defaultStorage(){return new MemoryAdapter}function pickQueueStorage(_mode,fallback){return fallback}function hydrateQueue(){return Promise.resolve()}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 now=this.clock.now();this.storage.set(KEY_ANON_RESET,`${now}`);const fresh=uuidv7(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(_config,_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)}function retryAfterMs(value,now){if(!value)return 0;const seconds=Number(value);const ms=seconds===seconds?seconds*1e3:Date.parse(value)-now;return ms>0?ms:0}function compress(_text,_mode){return Promise.resolve(null)}function sendBeacons(){}function eventIds(batch){return batch.map(event=>event.event_id)}var REQUEST_TIMEOUT_MS=3e4;var KEEPALIVE_MAX_BYTES=6e4;var MAX_BATCH_CHARS=256e3;function bodyBytes(body){if(typeof body==="string")return new TextEncoder().encode(body).byteLength;if(body instanceof Uint8Array)return body.byteLength;return 0}var REDIRECTED=399;function refused(status){return status>299&&status<400||status===401||status===403}var HOLD_BASE_MS=3e4;var HOLD_MAX_MS=60*6e4;var BatchUploader=class{constructor(queue,config,deps){this.queue=queue;this.config=config;this.deps=deps;this.inFlight=null;this.uploading=0;this.limit=0;this.strikes=0;this.wait=0}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){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(){this.limit=0;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("uploads paused");return}const max=this.config.batchSize;const batch=this.queue.peek(this.limit||max,MAX_BATCH_CHARS);this.queue.persistNow();this.uploading=batch.length;const status=await this.uploadWithRetry(batch);this.uploading=0;if(refused(status)||isRetryable(status))return;if(status===400||status===413){if(batch.length>1){this.limit=batch.length>>1;continue}this.limit=0}if(status>299)this.deps.logger.notice(`collector answered ${status}; dropped ${batch.length} event(s)`);this.queue.remove(eventIds(batch));if(status===400)return}}async uploadWithRetry(batch){const breaker=this.deps.breaker;let answered=false;let status=0;for(let attempt2=0;attempt2<=this.config.maxRetries;attempt2++){if(attempt2&&(this.deps.canUpload?.()===false||this.queue.peek(1)[0]?.event_id!==batch[0].event_id)){break}status=await this.post(batch);if(status)answered=true;if(!isRetryable(status)||this.wait)break;this.deps.logger.debug(`upload attempt ${attempt2+1} failed (${status})`);if(!answered&&breaker?.suspect())break;if(attempt2<this.config.maxRetries)await this.deps.sleep(backoffMs(attempt2))}if(!answered){breaker?.fail()}else{breaker?.ok();if(status>199&&status<300)this.strikes=0;else if(refused(status)||isRetryable(status)){if(refused(status))this.deps.logger.notice(`collector refused uploads (${status}); paused`);breaker?.hold(this.wait||Math.min(HOLD_BASE_MS*2**this.strikes++,HOLD_MAX_MS))}}return status}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){this.wait=0;const json=JSON.stringify(this.buildPayload(batch));const controller=typeof AbortController!=="undefined"?new AbortController:null;let timer=null;try{const headers={"Content-Type":"application/json"};const zipped=await compress(json,this.config.compression);if(zipped)headers["Content-Encoding"]="gzip";const body=zipped??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);if(res.redirected)return REDIRECTED;this.wait=retryAfterMs(res.headers?.get("Retry-After"),this.deps.clock.now());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(){sendBeacons(this.queue,this.config,this.deps,this.uploading,batch=>this.buildPayload(batch))}};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 clamp=(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=clamp(s[0],0,TRIP_AFTER_CYCLES);openUntil=clamp(s[1],0,clock.now()+MAX_COOLDOWN_MS);cooldown=clamp(s[2],BASE_COOLDOWN_MS,MAX_COOLDOWN_MS)}catch{}};const save=()=>{try{if(failures||openUntil>clock.now())storage.set(KEY_NET_BREAKER,JSON.stringify([failures,openUntil,cooldown]));else storage.remove(KEY_NET_BREAKER)}catch{}};return{open:()=>(load(),clock.now()<(openUntil=Math.min(openUntil,clock.now()+MAX_COOLDOWN_MS))),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()},hold:ms=>{load();openUntil=Math.max(openUntil,clock.now()+Math.min(ms,MAX_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)}notice(...args){console.warn("[depsmith-sdk]",...args)}error(...args){if(this.enabled)console.error("[depsmith-sdk]",...args)}};var CONTEXT_KEYS=["url","referrer","previous_url","initial_url"];var URL_PROPERTIES=["$ac_href","$ac_form_action","$net_url","$fr_error_file"];function scrubUrl(url,keep){const bare=url.split("#")[0];const q=bare.indexOf("?");if(q<0)return bare;const kept=bare.slice(q+1).split("&").filter(pair=>keep.has(paramName(pair)));return bare.slice(0,q)+(kept.length?`?${kept.join("&")}`:"")}function paramName(pair){const name=pair.split("=")[0].replace(/\+/g," ");try{return decodeURIComponent(name)}catch{return name}}function scrubEventUrls(event,option){if(!option)return;try{const params=option.keepParams;const keep=new Set(Array.isArray(params)?params:[]);const targets=[[event.context.page,CONTEXT_KEYS],[event.context.referrer,CONTEXT_KEYS],[event.properties,URL_PROPERTIES]];for(const[target,keys]of targets){for(const key of keys){const value=target?.[key];if(typeof value==="string")target[key]=scrubUrl(value,keep)}}const props=event.properties;if(!props)return;delete props.$net_fragment;if(typeof props.$net_query==="string"){const query=scrubUrl(`?${props.$net_query}`,keep).slice(1);if(query)props.$net_query=query;else delete props.$net_query}}catch{}}var KEY_CONFIG_FP="depsmith_config_fp";var MAX_ENVELOPE_ID_LENGTH=255;var DepsmithSdkClient=class{constructor(config,overrides={}){this.vitalsReported=false;this.stopped=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();const queueStorage=overrides.storage?this.storage:pickQueueStorage(this.config.storage,this.storage);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:"")}const fp=djb2(this.config.apiKey);const owned={get:key=>queueStorage.get(key),set:(key,value)=>{if(this.storage.get(KEY_CONFIG_FP)===fp)queueStorage.set(key,value)},remove:key=>queueStorage.remove(key)};this.queue=new EventQueue(owned,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:overrides.schedule});const drifted=this.detectConfigDrift(fp);this.primeDeviceSignals();this.ready=hydrateQueue(queueStorage,this.storage,this.consent,this.queue,drifted,this.logger);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),canUpload:()=>this.consent.canUpload()});if(!overrides.manualLifecycle){this.lifecycle=startLifecycle({intervalMs:this.config.batchIntervalMs,guard:fn=>this.guard(fn),vitals:()=>this.emitWebVitals(),leave:()=>this.leaveOnUnload?.(),restored:persisted=>this.pageLife.restored(persisted),resume:()=>this.resumeSession(),flushIfQueued:()=>this.flushIfQueued(),persistNow:()=>this.persistNow(),beacon:()=>{if(this.consent.canUpload())this.uploader.sendBeaconAll()},online:()=>{this.uploader.resetNetworkBreaker();this.flushIfQueued()}});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.setUserProp(key,value,"$set")})}setUserProp(key,value,op){this.identity.setUserProp(key,value);const traits=sanitizeProperties({[key]:value},this.logger);this.capture("$identify","identify",void 0,traits,sanitizedTraitOp(op,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.setUserProp(key,value,"$set_once")})}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");this.primeDeviceSignals();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());this.stopped=true;this.lifecycle?.stop();for(const fn of this.teardownFns.splice(0))fn();this.persistNow();this.queue.close()}persistNow(){try{this.queue.persistNow();this.session.persistNow()}catch{}}deviceSignals(){return!this.config.childSafeMode&&this.consent.canUpload()}primeDeviceSignals(){if(!this.deviceSignals())return;if(this.config.deviceFingerprinting)primeClientHints();if(this.config.geolocation)primeGeolocation(()=>this.deviceSignals())}enqueueEvent(event){scrubEventUrls(event,this.config.scrubUrls);this.queue.enqueue(event);this.lifecycle?.rearm()}flushUploads(){return this.ready.then(()=>this.uploader.flush())}flushIfQueued(){if(this.queue.size>0&&this.consent.canUpload())void this.flushUploads()}contextOptions(){let overrides;try{overrides=this.contextProvider?.()}catch{}const signals=this.deviceSignals();return{fingerprint:this.config.deviceFingerprinting&&signals,geolocation:this.config.geolocation&&signals,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.touchSession();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=sanitizeProperties({...this.config.defaultProperties,...this.superProperties.current(),...sanitizeProperties(properties,this.logger)},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(fingerprint){const stored=this.storage.get(KEY_CONFIG_FP);const drifted=stored!==null&&stored!==fingerprint;if(drifted){this.logger.warn("apiKey changed since last run; dropping queued events for the old project");this.queue.clear();this.storage.remove(KEY_NET_BREAKER)}this.storage.set(KEY_CONFIG_FP,fingerprint);return drifted}pickStorage(){return this.config.storage==="memory"?new MemoryAdapter:defaultStorage()}enqueueSessionBoundary(kind,id,at,startedAt){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug(`session_${kind} dropped (consent denied)`);return}const contextOptions=this.contextOptions();const event={event_id:uuidv7(this.clock.now()),event:`$session_${kind}`,event_type:`session_${kind}`,timestamp:isoTimestamp(at),session_id:id,session_started_at:isoTimestamp(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(kind==="start")event.properties=fingerprintComponents()}this.enqueueEvent(event)}touchSession(){const touch=this.session.touch();if(touch.startedSession)this.pageLife.newSession();if(touch.endedSession&&this.sessionInSample(touch.endedSession.id)){const ended=touch.endedSession;this.enqueueSessionBoundary("end",ended.id,ended.lastActivityAt,ended.startedAt)}if(touch.startedSession&&this.sessionInSample(touch.startedSession.id)){const started=touch.startedSession;this.enqueueSessionBoundary("start",started.id,started.startedAt,started.startedAt)}return touch}resumeSession(){if(this.consent.canCapture())this.touchSession()}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,properties=>this.guard(()=>this.capture("$network_request","track",properties)));this.teardownFns.push(()=>network.stop());void loadAutocapture().then(module=>{if(!module)return;if(this.stopped)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 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,variant_title:variant?.title,sku:variant?.sku,product_id:variant?.product?.id,title:variant?.product?.title,vendor:variant?.product?.vendor,product_type:variant?.product?.type,url:variant?.product?.url,price:amount(variant?.price),currency:variant?.price?.currencyCode}}function cartLineProps(line){return compact({...variantProps(line?.merchandise),quantity:line?.quantity,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,checkout_token:checkout.token,currency:checkout.currencyCode??checkout.totalPrice?.currencyCode,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,customer_id:checkout.order?.customer?.id,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 num2(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=num2(pick(p,["totalValue","total_amount"]))||num2(breakup.total_amount)||num2(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:num2(breakup.total_product_price),discount:num2(pick(p,["discountAmount"]))??(num2(breakup.total_discount_applied)||void 0),shipping:num2(pick(p,["shippingPrice"]))??num2(breakup.shipping_price),tax:num2(pick(p,["tax"]))??num2(breakup.tax),cod_charges:num2(breakup.cod_charges)??num2(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+(num2(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=>num2(pick(i,["Product Quantity","quantity"]))??0),line_item_prices:items.map(i=>num2(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,title:collection?.title,products_count:collection?.productVariants?.length})}}case"search_submitted":{const result=data.searchResult;return{kind:"track",name:"products_searched",properties:compact({query:result?.query,results_count:result?.productVariants?.length})}}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,item_count:cart?.totalQuantity,total_price:amount(cart?.cost?.totalAmount),currency:cart?.cost?.totalAmount?.currencyCode})}}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,message:alert?.message})}}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;var PIXEL_OWN_KEYS=["depsmith_queue","depsmith_config_fp","depsmith_net_breaker"];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;let deliver;const early=[];const handlerFor=name=>event=>{if(deliver)deliver(name,event);else if(early.length<100)early.push([name,event])};for(const name of SUBSCRIBED_EVENTS){sandbox.analytics.subscribe(name,handlerFor(name))}const kv=sandbox.browser.localStorage;const own=key=>PIXEL_OWN_KEYS.includes(key)?key.replace("depsmith_","depsmith_pixel_"):key;const storage=new AsyncMirrorAdapter({getItem:key=>kv.getItem(own(key)),setItem:(key,value)=>kv.setItem(own(key),value),removeItem:key=>kv.removeItem(own(key))},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;const currency=shop?.paymentSettings?.currencyCode??shop?.currencyCode;let context=toDepsmithSdkContext(sandbox.init.context);let client;try{client=new DepsmithSdkClient({...config,autocapture:false,compression:"none",consentMode:"granted",defaultProperties:{...config.defaultProperties,$source:"shopify_pixel",...shop?.myshopifyDomain?{$shop:shop.myshopifyDomain}:{},...currency?{$currency:currency}:{}}},{storage,manualLifecycle:true,contextProvider:()=>context,schedule:syncScheduler})}catch{deliver=()=>{};return}const customer=sandbox.init.data?.customer;if(customer?.id){client.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}:{}})}deliver=(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")client.pageInternal(mapped.name,properties);else client.trackInternal(mapped.name,properties);if(FLUSH_ON.has(name))void client.flush()}catch{}};for(const[name,event]of early.splice(0))deliver(name,event);setInterval(()=>void client.flush(),FLUSH_INTERVAL_MS);if(!anonymousId){try{await sandbox.browser.cookie.set(`${ANON_KEY}=${client.getAnonymousId()??""}; path=/; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`)}catch{}}}void startShopifyPixel().catch(()=>{});})();