@depsmith/depsmith-sdk 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ /* DepsmithSdk — Shopify custom pixel (DepSmith).
2
+ * 1. Edit DEPSMITH_SDK_CONFIG below. 2. Paste this entire file into
3
+ * Settings → Customer events → Add custom pixel → Permission: Analytics.
4
+ */
5
+ globalThis.DEPSMITH_SDK_CONFIG = {
6
+ apiKey: "REPLACE_WITH_YOUR_API_KEY",
7
+ endpoint: "https://collector.example.com",
8
+ debug: false
9
+ };
10
+ "use strict";(()=>{function loadAutocapture(){return Promise.resolve(null)}var SUPPRESSIONS=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screen","screen"],["timezone","timezone"],["userAgent","user_agent"]];var TRACKING_DEFAULTS=Object.fromEntries(SUPPRESSIONS.map(([option])=>[option,true]));function resolveTrackingOptions(options){const resolved={...TRACKING_DEFAULTS};if(!options)return resolved;for(const[option]of SUPPRESSIONS){if(options[option]===false)resolved[option]=false}return resolved}function applyTrackingOptions(context,options){const record=context;for(const[option,key,sub]of SUPPRESSIONS){if(options[option])continue;if(sub===void 0){delete record[key];continue}const block={...record[key]};delete block[sub];if(Object.keys(block).length>0)record[key]=block;else delete record[key]}return context}var AUTOCAPTURE_DEFAULTS={clicks:"interactive",forms:true,scrolls:true,pageviews:true,ignoredSelectors:[],selectorMaxDepth:5};function resolveClicks(clicks){if(clicks===void 0)return AUTOCAPTURE_DEFAULTS.clicks;if(clicks===true)return"interactive";return clicks}function resolveConfig(config){if(!config||typeof config.apiKey!=="string"||config.apiKey.length===0){throw new Error("depsmith-sdk: apiKey is required")}if(typeof config.endpoint!=="string"||!/^https?:\/\//.test(config.endpoint)){throw new Error("depsmith-sdk: endpoint must be an http(s) URL")}const autocapture=config.autocapture===true?AUTOCAPTURE_DEFAULTS:config.autocapture&&typeof config.autocapture==="object"?{...AUTOCAPTURE_DEFAULTS,...config.autocapture,clicks:resolveClicks(config.autocapture.clicks)}:false;return{apiKey:config.apiKey,endpoint:config.endpoint.replace(/\/+$/,""),batchSize:clamp(config.batchSize??20,1,500),batchIntervalMs:Math.max(config.batchIntervalMs??6e4,1e3),maxQueueSize:Math.max(config.maxQueueSize??1e3,1),maxQueueBytes:Math.max(config.maxQueueBytes??512*1024,4096),sessionTimeoutMs:Math.max(config.sessionTimeoutMs??18e5,6e4),sampleRate:Number.isFinite(config.sampleRate)?clamp(config.sampleRate,0,1):1,sessionEvents:config.sessionEvents==="derive"?"derive":"emit",consentMode:config.consentMode??"granted",respectDnt:config.respectDnt??true,maxRetries:clamp(config.maxRetries??5,0,10),debug:config.debug??false,defaultProperties:config.defaultProperties??{},autocapture,compression:config.compression??"gzip",childSafeMode:config.childSafeMode??false,anonymizeIp:(config.anonymizeIp??false)||(config.childSafeMode??false),deviceFingerprinting:config.deviceFingerprinting??true,geolocation:config.geolocation??false,trackingOptions:resolveTrackingOptions(config.trackingOptions),cookieDomain:config.cookieDomain??"",storage:config.storage??"localstorage"}}function clamp(n,min,max){return Math.min(Math.max(n,min),max)}function djb2(input){let hash=5381;for(let i=0;i<input.length;i++){hash=(hash<<5)+hash+input.charCodeAt(i)>>>0}return hash.toString(36)}function fnv1aInt(input){let hash=2166136261;for(let i=0;i<input.length;i++){hash^=input.charCodeAt(i);hash=Math.imul(hash,16777619)>>>0}return hash>>>0}function fnv1a(input){return fnv1aInt(input).toString(36)}function bucket(input){return fnv1aInt(input)/4294967296}function fingerprintHash(input){return djb2(input)+fnv1a(input)}var hints={};var hintsRequested=false;function primeClientHints(){if(hintsRequested)return;hintsRequested=true;try{const uaData=navigator?.userAgentData;if(typeof uaData?.getHighEntropyValues!=="function")return;void uaData.getHighEntropyValues(["model","platformVersion"]).then(values=>{hints=values}).catch(()=>{})}catch{}}function parseUserAgent(){const result={};if(typeof navigator==="undefined")return result;const ua=navigator.userAgent||"";const uaData=navigator.userAgentData;const browser2=parseBrowser(ua,uaData);if(browser2)result.browser=browser2;const os=parseOS(ua);if(os){const hinted=normalizeOsVersion(os.name,hints.platformVersion);result.os=hinted?{...os,version:hinted}:os}const deviceType=parseDeviceType(ua,uaData);if(deviceType)result.deviceType=deviceType;const device=parseDevice(ua,os);if(device)result.device=device;return result}function parseDevice(ua,os){const device={};if(os?.name==="iOS"||os?.name==="macOS")device.manufacturer="Apple";const hinted=hints.model?.trim();if(hinted)device.model=hinted;else if(/iPhone/.test(ua))device.model="iPhone";else if(/iPad/.test(ua))device.model="iPad";return device.manufacturer||device.model?device:void 0}function normalizeOsVersion(osName,platformVersion){const raw=platformVersion?.trim();if(!raw)return void 0;if(osName==="Windows"){const major=Number.parseInt(raw.split(".")[0]??"",10);if(!Number.isFinite(major))return void 0;if(major===0)return void 0;return major>=13?"11":"10"}return trimVersion(raw)}var BROWSER_RULES=[{pattern:/Edg(?:e|A|iOS)?\/([\d.]+)/,name:"Edge",engine:"Blink"},{pattern:/OPR\/([\d.]+)/,name:"Opera",engine:"Blink"},{pattern:/Firefox\/([\d.]+)/,name:"Firefox",engine:"Gecko"},{pattern:/Chrome\/([\d.]+)/,name:"Chrome",engine:"Blink"},{pattern:/Version\/([\d.]+)/,name:"Safari",engine:"WebKit",requires:/Safari/}];function parseBrowser(ua,uaData){for(const rule of BROWSER_RULES){if(rule.requires&&!rule.requires.test(ua))continue;const match=ua.match(rule.pattern);if(match)return{name:rule.name,version:match[1],engine:rule.engine}}const brand=uaData?.brands?.find(b=>!/not.?a.?brand/i.test(b.brand));if(brand)return{name:brand.brand,version:brand.version};return void 0}var OS_RULES=[{pattern:/Windows NT ([\d.]+)/,name:"Windows"},{pattern:/OS ([\d_]+)/,name:"iOS",requires:/iPhone|iPad|iPod/},{pattern:/Android ([\d.]+)/,name:"Android"},{pattern:/Mac OS X ([\d_]+)/,name:"macOS"}];function parseOS(ua){for(const rule of OS_RULES){if(rule.requires&&!rule.requires.test(ua))continue;const match=ua.match(rule.pattern);if(match)return{name:rule.name,version:trimVersion((match[1]??"").replace(/_/g,"."))}}if(/Linux/.test(ua))return{name:"Linux"};return void 0}function trimVersion(version){const trimmed=version.replace(/(\.0)+$/,"");return trimmed.length>0?trimmed:version}function parseDeviceType(ua,uaData){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(ua))return"tablet";if(uaData?.mobile===true)return"mobile";if(/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(ua))return"mobile";if(/Android/.test(ua))return"tablet";if(typeof navigator!=="undefined"&&ua)return"desktop";return void 0}var cachedVisitorId=null;var cachedComponents=null;function components(){if(cachedComponents!==null)return cachedComponents;cachedComponents=collectSignals();return cachedComponents}function computeVisitorId(){if(cachedVisitorId!==null)return cachedVisitorId;cachedVisitorId=fingerprintHash(components().map(c=>c.value).join("|"));return cachedVisitorId}function fingerprintComponents(){const out={};for(const component of components())out[`$fp_${component.name}`]=component.value;return out}function collectSignals(){const signals=[];try{if(typeof screen!=="undefined"){signals.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`})}if(typeof navigator!=="undefined"){const nav=navigator;signals.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`});signals.push({name:"dm",value:`dm:${nav.deviceMemory??""}`});signals.push({name:"plat",value:`plat:${navigator.platform??""}`});signals.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}signals.push({name:"canvas",value:`canvas:${canvasFingerprint()}`})}catch{}return signals}function canvasFingerprint(){try{if(typeof document==="undefined")return"";const canvas=document.createElement("canvas");canvas.width=240;canvas.height=60;const ctx=canvas.getContext("2d");if(!ctx)return"";ctx.textBaseline="top";ctx.font="14px 'Arial'";ctx.fillStyle="#f60";ctx.fillRect(10,10,100,30);ctx.fillStyle="#069";ctx.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15);ctx.strokeStyle="rgba(0,120,200,0.5)";ctx.arc(50,30,20,0,Math.PI*2);ctx.stroke();return fingerprintHash(canvas.toDataURL())}catch{return""}}function readNetwork(){try{if(typeof navigator==="undefined")return{};const conn=navigator.connection;if(!conn)return{};switch(conn.type){case"wifi":return{type:"wifi"};case"ethernet":return{type:"ethernet"};case"none":return{type:"none"}}switch(conn.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var MAX_FIX_AGE_MS=5*6e4;var FIX_TIMEOUT_MS=1e4;var fix=null;var fixAt=0;var primed=false;var inFlight=false;var permission=null;function primeGeolocation(){if(primed)return;primed=true;try{if(typeof navigator==="undefined"||!navigator.geolocation)return;const permissions=navigator.permissions;if(typeof permissions?.query!=="function")return;void permissions.query({name:"geolocation"}).then(status=>{permission=status;if(status.state==="granted")requestFix();status.onchange=()=>{if(status.state==="granted")requestFix();else fix=null}}).catch(()=>{})}catch{}}function requestFix(){if(inFlight)return;inFlight=true;try{navigator.geolocation.getCurrentPosition(position=>{inFlight=false;const{latitude,longitude,accuracy}=position.coords;if(!Number.isFinite(latitude)||!Number.isFinite(longitude))return;const next={latitude,longitude,source:"gps"};if(Number.isFinite(accuracy))next.accuracy=accuracy;fix=next;fixAt=Date.now()},()=>{inFlight=false},{enableHighAccuracy:false,maximumAge:MAX_FIX_AGE_MS,timeout:FIX_TIMEOUT_MS})}catch{inFlight=false}}function readGeolocation(){if(!fix)return void 0;if(Date.now()-fixAt>MAX_FIX_AGE_MS&&permission?.state==="granted")requestFix();return{...fix}}var LIBRARY_NAME="@depsmith/depsmith-sdk";var SDK_VERSION="0.6.0";var invariants=null;function readInvariants(){if(invariants)return invariants;const next={};try{next.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}if(typeof navigator!=="undefined"){next.locale=navigator.language;next.userAgent=navigator.userAgent}invariants=next;return next}function buildContext(opts={}){const context={library:{name:LIBRARY_NAME,version:SDK_VERSION}};attempt(()=>{if(typeof window!=="undefined"&&window.location){context.page={url:window.location.href,path:window.location.pathname,referrer:typeof document!=="undefined"?document.referrer:void 0,title:typeof document!=="undefined"?document.title:void 0}}});attempt(()=>{if(typeof window!=="undefined"&&window.screen){context.screen={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio}}});attempt(()=>{const cached=readInvariants();if(cached.locale!==void 0)context.locale=cached.locale;if(cached.userAgent!==void 0)context.user_agent=cached.userAgent;if(cached.timezone!==void 0)context.timezone=cached.timezone});attempt(()=>{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={};if(deviceType)device.type=deviceType;if(hinted?.manufacturer)device.manufacturer=hinted.manufacturer;if(hinted?.model)device.model=hinted.model;if(Object.keys(device).length>0)context.device=device;const network=readNetwork();if(network.type)context.network={...context.network,type:network.type}}function attempt(fn){try{fn()}catch{}}function dntEnabled(){try{if(typeof navigator==="undefined")return false;const nav=navigator;const win=typeof window!=="undefined"?window:{};const value=navigator.doNotTrack??win.doNotTrack??nav.msDoNotTrack;return value==="1"||value==="yes"}catch{return false}}var KEY_CONSENT="depsmith_consent";var ConsentManager=class{constructor(storage,initialMode,dntActive){this.storage=storage;this.dntActive=dntActive;const persisted=storage.get(KEY_CONSENT);this.state=persisted==="granted"||persisted==="denied"||persisted==="pending"?persisted:initialMode}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.effective()==="granted"}get current(){return this.effective()}optIn(){this.state="granted";this.storage.set(KEY_CONSENT,"granted")}optOut(){this.state="denied";this.storage.set(KEY_CONSENT,"denied")}};var IDLE_TIMEOUT_MS=250;var idleScheduler=fn=>{const idle=globalThis.requestIdleCallback;if(typeof idle==="function"){idle(fn,{timeout:IDLE_TIMEOUT_MS});return}setTimeout(fn,0)};var syncScheduler=fn=>fn();var KEY_QUEUE="depsmith_queue";var DEFAULT_MAX_CHARS=512*1024;var BRACKETS=2;var IDENTITY_EVENT_TYPES=new Set(["identify","alias","group"]);function isIdentityEvent(event){return IDENTITY_EVENT_TYPES.has(event?.event_type)}var EventQueue=class{constructor(storage,maxSize,logger,options={}){this.storage=storage;this.maxSize=maxSize;this.logger=logger;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=false;this.scheduled=false;this.maxChars=options.maxChars??DEFAULT_MAX_CHARS;this.schedule=options.schedule??idleScheduler;this.restore()}restore(){try{const raw=this.storage.get(KEY_QUEUE);if(!raw)return;const parsed=JSON.parse(raw);if(!Array.isArray(parsed))return;const kept=parsed.filter(e=>!!e&&typeof e==="object"&&typeof e.event_id==="string");this.reset(kept);if(kept.length!==parsed.length){this.logger.warn("discarded corrupt queued events on restore");this.markDirty()}if(this.trimToBudget())this.markDirty()}catch{this.logger.warn("queue storage corrupt; starting empty");this.reset([]);this.storage.remove(KEY_QUEUE)}}reset(events){this.events=events;this.sizes=events.map(e=>measure(e));this.sizeSum=this.sizes.reduce((a,b)=>a+b,0)}serializedLength(){if(this.events.length===0)return BRACKETS;return this.sizeSum+(this.events.length-1)+BRACKETS}trimToBudget(){let dropped=0;while(this.events.length>0&&this.serializedLength()>this.maxChars){this.evictAt(this.victimIndex());dropped++}if(dropped>0){this.logger.warn(`queue byte cap reached; dropped ${dropped} event(s)`)}return dropped>0}markDirty(){this.dirty=true;if(this.scheduled)return;this.scheduled=true;this.schedule(()=>{this.scheduled=false;this.persistNow()})}persistNow(){if(!this.dirty)return;this.dirty=false;this.storage.set(KEY_QUEUE,JSON.stringify(this.events))}prepend(events){const existing=new Set(this.events.map(e=>e.event_id));const fresh=events.filter(e=>!!e&&typeof e==="object"&&typeof e.event_id==="string"&&!existing.has(e.event_id));if(fresh.length===0)return;this.reset([...fresh,...this.events]);if(this.events.length>this.maxSize){this.dropOldest(this.events.length-this.maxSize)}this.trimToBudget();this.markDirty()}enqueue(event){const size=measure(event);if(size+BRACKETS>this.maxChars){this.logger.warn(`event ${event.event_id} exceeds the queue byte cap; dropped`);return}this.events.push(event);this.sizes.push(size);this.sizeSum+=size;if(this.events.length>this.maxSize){const dropped=this.events.length-this.maxSize;this.dropOldest(dropped);this.logger.warn(`queue cap reached; dropped ${dropped} event(s)`)}this.trimToBudget();this.markDirty()}victimIndex(){for(let i=0;i<this.events.length;i++){if(!isIdentityEvent(this.events[i]))return i}return 0}evictAt(index){this.events.splice(index,1);this.sizeSum-=this.sizes.splice(index,1)[0]??0}dropOldest(count){for(let n=0;n<count&&this.events.length>0;n++){this.evictAt(this.victimIndex())}}get size(){return this.events.length}peek(count){return this.events.slice(0,count)}remove(eventIds2){const ids=new Set(eventIds2);const events=[];const sizes=[];let sizeSum=0;for(let i=0;i<this.events.length;i++){const event=this.events[i];if(ids.has(event.event_id))continue;const size=this.sizes[i];events.push(event);sizes.push(size);sizeSum+=size}this.events=events;this.sizes=sizes;this.sizeSum=sizeSum;this.markDirty()}clear(){this.reset([]);this.dirty=false;this.storage.remove(KEY_QUEUE)}};function measure(event){return JSON.stringify(event).length}function uuidv7(now){const bytes=new Uint8Array(16);if(typeof crypto!=="undefined"&&crypto.getRandomValues){crypto.getRandomValues(bytes)}else{for(let i=0;i<16;i++)bytes[i]=Math.floor(Math.random()*256)}bytes[0]=now/2**40&255;bytes[1]=now/2**32&255;bytes[2]=now/2**24&255;bytes[3]=now/2**16&255;bytes[4]=now/2**8&255;bytes[5]=now&255;bytes[6]=bytes[6]&15|112;bytes[8]=bytes[8]&63|128;const hex=[];for(let i=0;i<16;i++)hex.push(bytes[i].toString(16).padStart(2,"0"));return`${hex[0]}${hex[1]}${hex[2]}${hex[3]}-${hex[4]}${hex[5]}-${hex[6]}${hex[7]}-${hex[8]}${hex[9]}-${hex[10]}${hex[11]}${hex[12]}${hex[13]}${hex[14]}${hex[15]}`}function uuidv7ToMs(id){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)){return null}const hex=id.slice(0,8)+id.slice(9,13);const ms=parseInt(hex,16);return Number.isFinite(ms)?ms:null}var DEPSMITH_SDK_STORAGE_KEYS=["depsmith_anonymous_id","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker"];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 LocalStorageAdapter=class{constructor(ls){this.ls=ls}get(key){try{return this.ls.getItem(key)}catch{return null}}set(key,value){try{this.ls.setItem(key,value)}catch{}}remove(key){try{this.ls.removeItem(key)}catch{}}};var CookieAdapter=class{constructor(domain){this.domain=domain}get(key){try{const prefix=`${encodeURIComponent(key)}=`;for(const part of document.cookie.split("; ")){if(part.startsWith(prefix))return decodeURIComponent(part.slice(prefix.length))}}catch{}return null}attributes(maxAge){const domain=this.domain?`; domain=${this.domain}`:"";const secure=typeof location!=="undefined"&&location.protocol==="https:"?"; Secure":"";return`${domain}; path=/; max-age=${maxAge}; SameSite=Lax${secure}`}set(key,value){try{const maxAge=60*60*24*400;document.cookie=`${encodeURIComponent(key)}=${encodeURIComponent(value)}${this.attributes(maxAge)}`}catch{}}remove(key){try{document.cookie=`${encodeURIComponent(key)}=${this.attributes(0)}`}catch{}}};var MIRRORED_IDENTITY_KEYS=new Set(["depsmith_anonymous_id"]);var RedundantAdapter=class{constructor(primary,secondary,mirrored=MIRRORED_IDENTITY_KEYS){this.primary=primary;this.secondary=secondary;this.mirrored=mirrored}get(key){const fromPrimary=this.primary.get(key);if(!this.mirrored.has(key))return fromPrimary;const fromSecondary=this.secondary.get(key);if(fromPrimary===fromSecondary)return fromPrimary;if(fromPrimary===null&&fromSecondary!==null){this.primary.set(key,fromSecondary);return fromSecondary}if(fromSecondary===null&&fromPrimary!==null){this.secondary.set(key,fromPrimary);return fromPrimary}const winner=olderUuidV7(fromPrimary,fromSecondary)??fromPrimary;this.primary.set(key,winner);this.secondary.set(key,winner);return winner}set(key,value){this.primary.set(key,value);if(this.mirrored.has(key))this.secondary.set(key,value)}remove(key){this.primary.remove(key);this.secondary.remove(key)}};function olderUuidV7(a,b){const aMs=uuidv7ToMs(a);const bMs=uuidv7ToMs(b);if(aMs===null||bMs===null)return null;return aMs<=bMs?a:b}var IndexedDBAdapter=class{constructor(dbName="depsmith-sdk"){this.mirror=new Map;this.snapshot=new Map;this.db=null;this.ready=this.open(dbName)}open(dbName){return new Promise(resolve=>{try{const request=indexedDB.open(dbName,1);request.onupgradeneeded=()=>request.result.createObjectStore("kv");request.onsuccess=()=>{this.db=request.result;const tx=this.db.transaction("kv","readonly").objectStore("kv");const keysReq=tx.getAllKeys();const valuesReq=tx.getAll();valuesReq.onsuccess=()=>{const keys=keysReq.result;valuesReq.result.forEach((value,i)=>{const key=keys[i];if(key===void 0)return;this.snapshot.set(key,value);if(!this.mirror.has(key))this.mirror.set(key,value)});resolve()};valuesReq.onerror=()=>resolve()};request.onerror=()=>resolve()}catch{resolve()}})}hydrate(){return this.ready.then(()=>this.snapshot)}get(key){return this.mirror.get(key)??null}set(key,value){this.mirror.set(key,value);void this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").put(value,key)}catch{}})}remove(key){this.mirror.delete(key);void this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").delete(key)}catch{}})}};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(){try{if(typeof window!=="undefined"&&window.localStorage){const probe="__depsmith_probe__";window.localStorage.setItem(probe,"1");window.localStorage.removeItem(probe);return new LocalStorageAdapter(window.localStorage)}}catch{}return new MemoryAdapter}var KEY_ANON="depsmith_anonymous_id";var KEY_USER="depsmith_user_id";var KEY_GROUP="depsmith_group_id";var KEY_PROPS="depsmith_user_props";var IdentityManager=class{constructor(storage,clock){this.storage=storage;this.clock=clock}get anonymousId(){let id=this.storage.get(KEY_ANON);if(!id){id=uuidv7(this.clock.now());this.storage.set(KEY_ANON,id)}return id}get userId(){return this.storage.get(KEY_USER)}get groupId(){return this.storage.get(KEY_GROUP)}identify(userId){this.storage.set(KEY_USER,userId)}setGroup(groupId){this.storage.set(KEY_GROUP,groupId)}getUserProps(){try{return JSON.parse(this.storage.get(KEY_PROPS)??"{}")}catch{return{}}}setUserProp(key,value){const props=this.getUserProps();props[key]=value;this.storage.set(KEY_PROPS,JSON.stringify(props))}hasUserProp(key){return key in this.getUserProps()}unsetUserProp(key){const props=this.getUserProps();delete props[key];this.storage.set(KEY_PROPS,JSON.stringify(props))}reset(){this.storage.remove(KEY_USER);this.storage.remove(KEY_GROUP);this.storage.remove(KEY_PROPS);const fresh=uuidv7(this.clock.now());this.storage.set(KEY_ANON,fresh);return fresh}};var KEY_SESSION="depsmith_session";var SessionManager=class{constructor(storage,clock,timeoutMs,schedule=idleScheduler){this.storage=storage;this.clock=clock;this.timeoutMs=timeoutMs;this.pending=null;this.scheduled=false;this.schedule=schedule}load(){const stored=this.readStored();const pending=this.pending;if(!pending)return stored;if(!stored||pending.lastActivityAt>=stored.lastActivityAt)return pending;this.pending=null;return stored}readStored(){try{const raw=this.storage.get(KEY_SESSION);if(!raw)return null;const parsed=JSON.parse(raw);if(typeof parsed.id!=="string"||typeof parsed.lastActivityAt!=="number")return null;if(typeof parsed.startedAt!=="number"){parsed.startedAt=uuidv7ToMs(parsed.id)??parsed.lastActivityAt}return parsed}catch{return null}}save(session){this.pending=session;if(this.scheduled)return;this.scheduled=true;this.schedule(()=>{this.scheduled=false;this.persistNow()})}persistNow(){const pending=this.pending;if(!pending)return;this.pending=null;this.storage.set(KEY_SESSION,JSON.stringify(pending))}mint(now){const fresh={id:uuidv7(now),lastActivityAt:now,startedAt:now};this.save(fresh);return fresh}touch(){const now=this.clock.now();const current=this.load();if(!current){const fresh=this.mint(now);return{sessionId:fresh.id,startedAt:now,startedSession:{id:fresh.id,startedAt:now}}}if(now-current.lastActivityAt>this.timeoutMs){const fresh=this.mint(now);return{sessionId:fresh.id,startedAt:now,endedSession:{id:current.id,lastActivityAt:current.lastActivityAt,startedAt:current.startedAt},startedSession:{id:fresh.id,startedAt:now}}}this.save({id:current.id,lastActivityAt:now,startedAt:current.startedAt});return{sessionId:current.id,startedAt:current.startedAt}}peek(){const current=this.load();if(current)return current.id;return this.mint(this.clock.now()).id}adopt(id,startedAt){const embedded=uuidv7ToMs(id);if(embedded===null)return false;this.save({id,lastActivityAt:this.clock.now(),startedAt:startedAt??embedded});return true}rotate(){return this.mint(this.clock.now()).id}};var MAX_TOP_LEVEL_KEYS=200;var MAX_ARRAY_ITEMS=100;var MAX_OBJECT_KEYS=50;function sanitizeProperties(input,logger){if(input===null||input===void 0)return{};if(typeof input!=="object"||Array.isArray(input)){logger.warn("properties must be an object; ignoring",input);return{}}const out={};let count=0;for(const[rawKey,rawValue]of Object.entries(input)){if(count>=MAX_TOP_LEVEL_KEYS){logger.warn(`properties exceed ${MAX_TOP_LEVEL_KEYS} keys; excess dropped`);break}const value=coerceValue(rawValue,logger);if(value===void 0){logger.debug(`property "${rawKey}" dropped (unsupported value)`);continue}out[String(rawKey)]=value;count++}return out}function coerceScalar(value){if(value===null)return null;const t=typeof value;if(t==="string"||t==="boolean")return value;if(t==="number")return Number.isFinite(value)?value:void 0;if(value instanceof Date)return isNaN(value.getTime())?void 0:value.toISOString();return void 0}function coerceValue(value,logger){const scalar=coerceScalar(value);if(scalar!==void 0)return scalar;if(value===void 0||typeof value==="function"||typeof value==="symbol")return void 0;if(Array.isArray(value)){const items=[];for(const item of value.slice(0,MAX_ARRAY_ITEMS)){const coerced=coerceScalar(item);items.push(coerced!==void 0?coerced:safeStringify(item))}return items}if(typeof value==="object"){const out={};let count=0;for(const[k,v]of Object.entries(value)){if(count>=MAX_OBJECT_KEYS){logger.debug(`nested object exceeds ${MAX_OBJECT_KEYS} keys; excess dropped`);break}const coerced=coerceScalar(v);out[String(k)]=coerced!==void 0?coerced:safeStringify(v);count++}return out}return void 0}function safeStringify(value){try{return JSON.stringify(value)??"null"}catch{return String(value)}}var TRAIT_OPERATORS=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"];var MAX_ADD_KEYS=50;var MAX_UNSET_KEYS=200;function normalizeUserPropertyOps(ops,logger){if(!ops||typeof ops!=="object")return void 0;if(ops.$clear_all===true){const others=Object.keys(ops).filter(k=>k!=="$clear_all");if(others.length>0){logger.warn(`$clear_all is exclusive; ignored ${others.join(", ")}`)}return{$clear_all:true}}const out={};const claimed=new Set;const claim=(key,operator)=>{if(claimed.has(key)){logger.debug(`"${key}" has an operator already; ${operator} dropped`);return false}claimed.add(key);return true};for(const operator of TRAIT_OPERATORS){const raw=ops[operator];if(!raw||typeof raw!=="object")continue;const clean=sanitizeProperties(raw,logger);const kept={};for(const[key,value]of Object.entries(clean)){if(!claim(key,operator))continue;kept[key]=value}if(Object.keys(kept).length>0)out[operator]=kept}if(ops.$add&&typeof ops.$add==="object"){const kept={};let count=0;for(const[key,value]of Object.entries(ops.$add)){if(count>=MAX_ADD_KEYS){logger.debug(`$add over ${MAX_ADD_KEYS} keys; excess dropped`);break}if(typeof value!=="number"||!Number.isFinite(value)){logger.debug(`$add "${key}" is not finite; dropped`);continue}if(!claim(key,"$add"))continue;kept[key]=value;count++}if(Object.keys(kept).length>0)out.$add=kept}if(Array.isArray(ops.$unset)){const kept=[];for(const key of ops.$unset){if(kept.length>=MAX_UNSET_KEYS){logger.debug(`$unset over ${MAX_UNSET_KEYS} keys; excess dropped`);break}if(typeof key!=="string"||key.length===0)continue;if(!claim(key,"$unset"))continue;kept.push(key)}if(kept.length>0)out.$unset=kept}return Object.keys(out).length>0?out:void 0}function sanitizedTraitOp(operator,clean){return Object.keys(clean).length>0?{[operator]:clean}:void 0}var systemClock={now:()=>Date.now()};function isoTimestamp(ms){return new Date(ms).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function isRetryable(status){return status===0||status===408||status===429||status>=500}var BASE_MS=1e3;var MAX_BACKOFF_MS=32e3;function backoffMs(attempt2,random=Math.random){const base=Math.min(BASE_MS*2**attempt2,MAX_BACKOFF_MS);return Math.round(random()*base)}async function gzip(text){const cs=new CompressionStream("gzip");const writer=cs.writable.getWriter();writer.write(new TextEncoder().encode(text)).catch(()=>{});writer.close().catch(()=>{});const reader=cs.readable.getReader();const chunks=[];for(;;){const{done,value}=await reader.read();if(done)break;chunks.push(value)}const total=chunks.reduce((n,c)=>n+c.length,0);const out=new Uint8Array(new ArrayBuffer(total));let offset=0;for(const chunk of chunks){out.set(chunk,offset);offset+=chunk.length}return out}function eventIds(batch){const ids=[];for(const event of batch)ids.push(event.event_id);return ids}var REQUEST_TIMEOUT_MS=3e4;var KEEPALIVE_MAX_BYTES=6e4;var MAX_UNLOAD_BATCHES=10;function bodyBytes(body){if(typeof body==="string")return new TextEncoder().encode(body).byteLength;if(body instanceof Uint8Array)return body.byteLength;return 0}var BatchUploader=class{constructor(queue,config,deps){this.queue=queue;this.config=config;this.deps=deps;this.inFlight=null}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){if(this.inFlight)return this.inFlight;this.inFlight=this.drain().catch(err=>this.deps.logger.error("flush failed",err)).finally(()=>{this.inFlight=null});return this.inFlight}async drain(){while(this.queue.size>0){if(!this.deps.isOnline()){this.deps.logger.debug("offline; deferring upload");return}if(this.deps.breaker?.open()){this.deps.logger.debug("collector unreachable; uploads paused");return}const batch=this.queue.peek(this.config.batchSize);this.queue.persistNow();const result=await this.uploadWithRetry(batch);if(result==="requeue")return;if(result==="dropped")this.deps.logger.warn(`dropped poison batch of ${batch.length}`);this.queue.remove(eventIds(batch))}}async uploadWithRetry(batch){const breaker=this.deps.breaker;let answered=false;for(let attempt2=0;attempt2<=this.config.maxRetries;attempt2++){const status=await this.post(batch);if(status!==0)answered=true;if(status>=200&&status<300){breaker?.ok();return"sent"}if(!isRetryable(status)){breaker?.ok();this.deps.logger.warn(`non-retryable ${status}; dropping batch`);return"dropped"}this.deps.logger.debug(`upload attempt ${attempt2+1} failed (${status})`);if(status===0&&!answered&&breaker?.suspect())break;if(attempt2<this.config.maxRetries)await this.deps.sleep(backoffMs(attempt2))}if(answered)breaker?.ok();else breaker?.fail();return"requeue"}buildPayload(batch){const payload={batch,api_key:this.config.apiKey,source:"sdk",sent_at:isoTimestamp(this.deps.clock.now())};if(this.config.anonymizeIp)payload.anonymize_ip=true;return payload}async post(batch){const json=JSON.stringify(this.buildPayload(batch));const controller=typeof AbortController!=="undefined"?new AbortController:null;let timer=null;try{let body=json;const headers={"Content-Type":"application/json"};if(this.config.compression!=="none"&&typeof CompressionStream!=="undefined"){try{body=await gzip(json);headers["Content-Encoding"]="gzip"}catch{body=json}}const keepalive=bodyBytes(body)<=KEEPALIVE_MAX_BYTES;if(!keepalive){this.deps.logger.debug("payload over keepalive cap; sending without keepalive")}const init2={method:"POST",headers,body,keepalive};if(controller){init2.signal=controller.signal;timer=setTimeout(()=>controller.abort(),this.timeoutMs())}const res=await this.deps.fetchFn(`${this.config.endpoint}/e/`,init2);return res.status}catch{return 0}finally{if(timer!==null)clearTimeout(timer)}}timeoutMs(){const configured=this.config.requestTimeoutMs;return typeof configured==="number"&&configured>0?configured:REQUEST_TIMEOUT_MS}sendBeaconAll(){try{if(typeof navigator==="undefined"||!navigator.sendBeacon)return;let batches=0;while(this.queue.size>0&&batches<MAX_UNLOAD_BATCHES){const batch=this.queue.peek(this.config.batchSize);const payload=this.buildPayload(batch);const accepted=navigator.sendBeacon(`${this.config.endpoint}/e/`,new Blob([JSON.stringify(payload)],{type:"text/plain"}));if(!accepted)return;this.queue.remove(eventIds(batch));batches++}}catch{}}};var KEY_NET_BREAKER="depsmith_net_breaker";var TRIP_AFTER_CYCLES=3;var BASE_COOLDOWN_MS=5*6e4;var MAX_COOLDOWN_MS=60*6e4;function createNetworkBreaker(storage,clock){let loaded=false;let failures=0;let openUntil=0;let cooldown=BASE_COOLDOWN_MS;const clamp2=(v,lo,hi)=>typeof v==="number"&&v===v?Math.min(Math.max(v,lo),hi):lo;const load=()=>{if(loaded)return;loaded=true;try{const s=JSON.parse(storage.get(KEY_NET_BREAKER)??"0");if(!Array.isArray(s))return;failures=clamp2(s[0],0,TRIP_AFTER_CYCLES);openUntil=clamp2(s[1],0,clock.now()+MAX_COOLDOWN_MS);cooldown=clamp2(s[2],BASE_COOLDOWN_MS,MAX_COOLDOWN_MS)}catch{}};const save=()=>{try{if(failures)storage.set(KEY_NET_BREAKER,JSON.stringify([failures,openUntil,cooldown]));else storage.remove(KEY_NET_BREAKER)}catch{}};return{open:()=>(load(),clock.now()<openUntil),suspect:()=>(load(),failures>0),fail:()=>{load();if(++failures>=TRIP_AFTER_CYCLES){openUntil=clock.now()+cooldown;cooldown=Math.min(cooldown*2,MAX_COOLDOWN_MS);failures=TRIP_AFTER_CYCLES}save()},ok:()=>{load();if(!failures)return;failures=openUntil=0;cooldown=BASE_COOLDOWN_MS;save()}}}var Logger=class{constructor(enabled){this.enabled=enabled}setEnabled(enabled){this.enabled=enabled}debug(...args){if(this.enabled)console.debug("[depsmith-sdk]",...args)}warn(...args){if(this.enabled)console.warn("[depsmith-sdk]",...args)}error(...args){if(this.enabled)console.error("[depsmith-sdk]",...args)}};var MAX_ENVELOPE_ID_LENGTH=255;var DepsmithSdkClient=class{constructor(config,overrides={}){this.flushTimer=null;this.drained=false;this.teardownFns=[];this.ready=Promise.resolve();this.config=resolveConfig(config);this.logger=new Logger(this.config.debug);this.clock=overrides.clock??systemClock;this.storage=overrides.storage??this.pickStorage();this.contextProvider=overrides.contextProvider;const identityStorage=this.config.childSafeMode?new MemoryAdapter:this.config.storage==="memory"?this.storage:new RedundantAdapter(this.storage,new CookieAdapter(this.config.cookieDomain||void 0));this.identity=new IdentityManager(identityStorage,this.clock);this.session=new SessionManager(this.storage,this.clock,this.config.sessionTimeoutMs,overrides.schedule);this.consent=new ConsentManager(this.storage,this.config.consentMode,this.config.respectDnt&&(overrides.dnt??dntEnabled()));this.queue=new EventQueue(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:overrides.schedule});this.detectConfigDrift();if(this.config.deviceFingerprinting&&!this.config.childSafeMode){primeClientHints()}if(this.config.geolocation&&!this.config.childSafeMode){primeGeolocation()}if(this.storage instanceof IndexedDBAdapter){this.ready=this.storage.hydrate().then(persisted=>{try{const raw=persisted.get("depsmith_queue");if(raw)this.queue.prepend(JSON.parse(raw))}catch{this.logger.warn("persisted queue corrupt; discarded")}})}this.uploader=new BatchUploader(this.queue,{endpoint:this.config.endpoint,apiKey:this.config.apiKey,batchSize:this.config.batchSize,maxRetries:this.config.maxRetries,compression:this.config.compression,anonymizeIp:this.config.anonymizeIp,requestTimeoutMs:overrides.requestTimeoutMs},{fetchFn:overrides.fetchFn??((...args)=>fetch(...args)),clock:this.clock,logger:this.logger,sleep:overrides.sleep??(ms=>new Promise(r=>setTimeout(r,ms))),isOnline:overrides.isOnline??(()=>typeof navigator==="undefined"?true:navigator.onLine!==false),breaker:createNetworkBreaker(this.storage,this.clock)});if(!overrides.manualLifecycle){this.startFlushTimer();this.attachLifecycle();this.startAutocapture()}this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(name,properties){this.guard(()=>{if(typeof name!=="string"||name.length===0){this.logger.warn("track: event name required");return}if(name.startsWith("$")){this.logger.warn(`track: "$"-prefixed names are reserved; dropped "${name}"`);return}if(this.tooLong(name,"track: event name"))return;this.capture(name,"track",properties)})}tooLong(value,label){if(value.length<=MAX_ENVELOPE_ID_LENGTH)return false;this.logger.warn(`${label} exceeds ${MAX_ENVELOPE_ID_LENGTH} characters (got ${value.length}); dropped`);return true}page(name,properties){this.guard(()=>{const pageName=name??(typeof document!=="undefined"?document.title:void 0)??"Unknown";this.capture("$page_view","page_view",{...properties,name:pageName})})}screen(name,properties){this.page(name,properties)}identify(userId,traits){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof userId!=="string"||userId.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(userId,"identify: userId"))return;this.identity.identify(userId);const clean=sanitizeProperties(traits,this.logger);this.capture("$identify","identify",void 0,clean,sanitizedTraitOp("$set",clean))})}alias(aliasId){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof aliasId!=="string"||aliasId.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:aliasId})})}reset(){this.guard(()=>{this.identity.reset();this.session.rotate();this.logger.debug("reset: identity and session rotated")})}group(groupId,traits){this.guard(()=>{if(typeof groupId!=="string"||groupId.length===0){this.logger.warn("group: groupId required");return}if(this.tooLong(groupId,"group: groupId"))return;this.identity.setGroup(groupId);this.capture("$group","group",void 0,sanitizeProperties(traits,this.logger))})}setGroupTraits(traits){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}this.capture("$group","group",void 0,sanitizeProperties(traits,this.logger))})}setProperty(key,value){this.guard(()=>{this.identity.setUserProp(key,value);const traits=sanitizeProperties({[key]:value},this.logger);this.capture("$identify","identify",void 0,traits,sanitizedTraitOp("$set",traits))})}setOnceProperty(key,value){this.guard(()=>{if(this.identity.hasUserProp(key)){this.logger.debug(`setOnceProperty: "${key}" already set`);return}this.identity.setUserProp(key,value);const traits=sanitizeProperties({[key]:value},this.logger);this.capture("$identify","identify",void 0,traits,sanitizedTraitOp("$set_once",traits))})}unsetProperty(key){this.guard(()=>{this.identity.unsetUserProp(key);this.capture("$identify","identify",void 0,{[key]:null},normalizeUserPropertyOps({$unset:[key]},this.logger))})}setUserProperties(ops){this.guard(()=>{const normalized=normalizeUserPropertyOps(ops,this.logger);if(!normalized)return;this.capture("$identify","identify",void 0,void 0,normalized)})}optIn(){this.guard(()=>{this.consent.optIn();this.logger.debug("consent granted");void this.flushUploads()})}optOut(){this.guard(()=>{this.consent.optOut();this.queue.clear();this.logger.debug("consent denied; queue cleared")})}async flush(){try{if(!this.consent.canUpload()){this.logger.debug("flush skipped: consent not granted");return}await this.flushUploads()}catch(err){this.logger.error("flush error",err)}}autocapture(properties){this.guard(()=>this.capture("$autocapture","autocapture",properties))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(sessionId,startedAt){this.guard(()=>{if(typeof sessionId!=="string"||!this.session.adopt(sessionId,startedAt)){this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(sessionId)}"`)}})}shutdown(){if(this.flushTimer!==null)clearInterval(this.flushTimer);this.flushTimer=null;for(const fn of this.teardownFns.splice(0))fn();this.persistNow()}persistNow(){try{this.queue.persistNow();this.session.persistNow()}catch{}}enqueueEvent(event){this.queue.enqueue(event);this.drained=false}flushUploads(){return this.ready.then(()=>this.uploader.flush())}contextOptions(){let overrides;try{overrides=this.contextProvider?.()}catch{}return{fingerprint:this.config.deviceFingerprinting&&!this.config.childSafeMode&&this.consent.current==="granted",geolocation:this.config.geolocation&&!this.config.childSafeMode&&this.consent.current==="granted",overrides,tracking:this.config.trackingOptions}}sessionInSample(sessionId){if(this.config.sampleRate>=1)return true;return bucket(`${this.config.apiKey}:${sessionId}`)<this.config.sampleRate}inSample(sessionId,type){if(type==="identify"||type==="alias"||type==="group")return true;return this.sessionInSample(sessionId)}capture(name,type,properties,traits,userProperties){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${name}`);return}const touch=this.session.touch();if(touch.endedSession&&this.sessionInSample(touch.endedSession.id)){this.enqueueSessionEnd(touch.endedSession)}if(touch.startedSession&&this.sessionInSample(touch.startedSession.id)){this.enqueueSessionStart(touch.startedSession)}if(!this.inSample(touch.sessionId,type)){this.logger.debug(`capture dropped (out of sample): ${name}`);return}const now=this.clock.now();const contextOptions=this.contextOptions();const event={event_id:uuidv7(now),event:name,event_type:type,timestamp:isoTimestamp(now),session_id:touch.sessionId,session_started_at:isoTimestamp(touch.startedAt),anonymous_id:this.identity.anonymousId,context:traits?{...buildContext(contextOptions),traits}:buildContext(contextOptions),platform:"web",sdk_version:SDK_VERSION};if(userProperties)event.user_properties=userProperties;const props={...this.config.defaultProperties,...sanitizeProperties(properties,this.logger)};if(Object.keys(props).length>0)event.properties=props;const userId=this.identity.userId;if(userId)event.user_id=userId;const groupId=this.identity.groupId;if(groupId)event.group_id=groupId;if(contextOptions.fingerprint)event.device_id=computeVisitorId();this.enqueueEvent(event);this.logger.debug(`captured ${name}`,event);if(this.queue.size>=this.config.batchSize&&this.consent.canUpload()){void this.flushUploads()}}detectConfigDrift(){const KEY="depsmith_config_fp";const fingerprint=djb2(this.config.apiKey);const stored=this.storage.get(KEY);if(stored!==null&&stored!==fingerprint){this.logger.warn("apiKey changed since last run; dropping queued events for the old project");this.queue.clear()}this.storage.set(KEY,fingerprint)}pickStorage(){if(this.config.storage==="memory")return new MemoryAdapter;if(this.config.storage==="indexeddb"&&typeof indexedDB!=="undefined"){return new IndexedDBAdapter}return defaultStorage()}enqueueSessionEnd(ended){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_end dropped (consent denied)");return}const contextOptions=this.contextOptions();const event={event_id:uuidv7(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:isoTimestamp(ended.lastActivityAt),session_id:ended.id,session_started_at:isoTimestamp(ended.startedAt),anonymous_id:this.identity.anonymousId,context:buildContext(contextOptions),platform:"web",sdk_version:SDK_VERSION};const userId=this.identity.userId;if(userId)event.user_id=userId;if(contextOptions.fingerprint)event.device_id=computeVisitorId();this.enqueueEvent(event)}enqueueSessionStart(started){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_start dropped (consent denied)");return}const contextOptions=this.contextOptions();const event={event_id:uuidv7(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:isoTimestamp(started.startedAt),session_id:started.id,session_started_at:isoTimestamp(started.startedAt),anonymous_id:this.identity.anonymousId,context:buildContext(contextOptions),platform:"web",sdk_version:SDK_VERSION};const userId=this.identity.userId;if(userId)event.user_id=userId;if(contextOptions.fingerprint)event.device_id=computeVisitorId();if(contextOptions.fingerprint){event.properties={...event.properties,...fingerprintComponents()}}this.enqueueEvent(event)}startFlushTimer(){this.flushTimer=setInterval(()=>{if(this.queue.size>0&&this.consent.canUpload())void this.flushUploads()},this.config.batchIntervalMs)}attachLifecycle(){if(typeof window==="undefined"||typeof document==="undefined")return;const onPageHide=()=>{if(this.drained)return;this.drained=true;if(this.consent.canUpload())this.uploader.sendBeaconAll();this.persistNow()};const onVisibility=()=>{if(document.visibilityState==="hidden"){onPageHide()}else{this.drained=false;const touch=this.session.touch();if(touch.endedSession)this.enqueueSessionEnd(touch.endedSession);if(touch.startedSession)this.enqueueSessionStart(touch.startedSession)}};const onPageShow=()=>{this.drained=false};const onOnline=()=>{this.uploader.resetNetworkBreaker();if(this.queue.size>0&&this.consent.canUpload())void this.flushUploads()};window.addEventListener("pagehide",onPageHide);window.addEventListener("pageshow",onPageShow);document.addEventListener("visibilitychange",onVisibility);window.addEventListener("online",onOnline);this.teardownFns.push(()=>{window.removeEventListener("pagehide",onPageHide);window.removeEventListener("pageshow",onPageShow);document.removeEventListener("visibilitychange",onVisibility);window.removeEventListener("online",onOnline)})}startAutocapture(){const autocaptureConfig=this.config.autocapture;if(!autocaptureConfig||typeof window==="undefined")return;void loadAutocapture().then(module=>{if(!module)return;this.teardownFns.push(module.startAutocapture(autocaptureConfig,{emit:properties=>this.autocapture(properties),page:()=>this.page()}))}).catch(err=>this.logger.debug("autocapture load failed",err))}guard(fn){try{fn()}catch(err){this.logger.error("internal error",err)}}};var client=null;var initApiKey=null;var DepsmithSdk={init(config,overrides){try{if(client&&initApiKey===config.apiKey){return client}client?.shutdown();client=new DepsmithSdkClient(config,overrides);initApiKey=config.apiKey;return client}catch(err){if(config?.debug)console.error("[depsmith-sdk] init failed:",err);return null}},track:(name,properties)=>client?.track(name,properties),page:(name,properties)=>client?.page(name,properties),screen:(name,properties)=>client?.screen(name,properties),identify:(userId,traits)=>client?.identify(userId,traits),alias:aliasId=>client?.alias(aliasId),reset:()=>client?.reset(),group:(groupId,traits)=>client?.group(groupId,traits),setGroupTraits:traits=>client?.setGroupTraits(traits),setProperty:(key,value)=>client?.setProperty(key,value),setOnceProperty:(key,value)=>client?.setOnceProperty(key,value),unsetProperty:key=>client?.unsetProperty(key),setUserProperties:ops=>client?.setUserProperties(ops),optIn:()=>client?.optIn(),optOut:()=>client?.optOut(),flush:()=>client?.flush()??Promise.resolve(),getAnonymousId:()=>client?.getAnonymousId(),getSessionId:()=>client?.getSessionId(),setSessionId:(sessionId,startedAt)=>client?.setSessionId(sessionId,startedAt),shutdown(){client?.shutdown();client=null;initApiKey=null}};var FLUSH_ON=new Set(["checkout_completed","payment_info_submitted","gokwik_purchase_event"]);function compact(input){const out={};for(const[key,value]of Object.entries(input)){if(value===void 0||value===null)continue;if(Array.isArray(value)&&value.length===0)continue;out[key]=value}return out}function amount(money){return typeof money?.amount==="number"?money.amount:void 0}function variantProps(variant){return{variant_id:variant?.id??void 0,variant_title:variant?.title??void 0,sku:variant?.sku??void 0,product_id:variant?.product?.id??void 0,title:variant?.product?.title??void 0,vendor:variant?.product?.vendor??void 0,product_type:variant?.product?.type??void 0,url:variant?.product?.url??void 0,price:amount(variant?.price),currency:variant?.price?.currencyCode??void 0}}function cartLineProps(line){return compact({...variantProps(line?.merchandise),quantity:line?.quantity??void 0,line_total:amount(line?.cost?.totalAmount)})}function isCheckoutPath(pathname){return typeof pathname==="string"&&(/^\/checkouts?\//.test(pathname)||/^\/orders\//.test(pathname))}function lineItemArrays(items){return compact({line_item_variant_ids:items.map(i=>i.variant?.id??""),line_item_product_ids:items.map(i=>i.variant?.product?.id??""),line_item_titles:items.map(i=>i.title??i.variant?.product?.title??""),line_item_quantities:items.map(i=>i.quantity??0),line_item_prices:items.map(i=>amount(i.finalLinePrice)??0)})}function checkoutProps(checkout){const items=checkout.lineItems??[];const discount=items.flatMap(item=>item.discountAllocations??[]).reduce((sum,allocation)=>sum+(amount(allocation.amount)??0),0);return compact({...lineItemArrays(items),order_id:checkout.order?.id??void 0,checkout_token:checkout.token??void 0,currency:checkout.currencyCode??checkout.totalPrice?.currencyCode??void 0,revenue:amount(checkout.totalPrice),subtotal:amount(checkout.subtotalPrice),tax:amount(checkout.totalTax),shipping:amount(checkout.shippingLine?.price),discount:discount>0?discount:void 0,item_count:items.reduce((sum,item)=>sum+(item.quantity??0),0),is_first_order:checkout.order?.customer?.isFirstOrder??void 0,customer_id:checkout.order?.customer?.id??void 0,discount_codes:(checkout.discountApplications??[]).map(application=>application.title??"").filter(Boolean)})}var GOKWIK_STEPS={Started_Checkout_GK:"checkout_started",Mobile_Added_GK:"checkout_contact_info_submitted",Address_Added_GK:"checkout_address_info_submitted",Address_Step_Reached_GK:null,Payment_Step_Reached_GK:"payment_step_reached"};function num(value){const n=typeof value==="string"?parseFloat(value):value;return typeof n==="number"&&Number.isFinite(n)?n:void 0}function str(value){if(typeof value==="number"&&Number.isFinite(value))return String(value);return typeof value==="string"&&value!==""?value:void 0}function pick(from,keys){for(const key of keys)if(from[key]!==void 0&&from[key]!==null)return from[key];return void 0}var GOKWIK_FIELDS=["event","price_breakup","total_price","totalValue","orderId","orderName","cart_token"];function hasGokwikFields(payload){return GOKWIK_FIELDS.some(key=>key in payload)}function gokwikPayload(event){let payload=event.customData??event.data??{};for(let depth=0;depth<2;depth++){if(hasGokwikFields(payload))break;const inner=payload.data;if(!inner||typeof inner!=="object"||Array.isArray(inner))break;payload=inner}return payload}function gokwikProps(p){const breakup=p.price_breakup??{};const analytics2=p.commonAnalyticsData??{};const items=Array.isArray(p.Products)?p.Products:Array.isArray(p.cart)?p.cart:[];const coupon=str(pick(breakup,["coupon_code"]))??str(pick(p,["Coupon Code","coupon"]))??str(analytics2.coupon);const total=num(pick(p,["totalValue","total_amount"]))||num(breakup.total_amount)||num(p.total_price);return compact({order_id:str(pick(p,["orderId","order_id","orderName","order_name","order_number"])),gokwik_order_id:str(pick(p,["gokwikOid","moid"])),checkout_token:str(p.cart_token),currency:str(pick(breakup,["currency"]))??str(p.currency),revenue:total,subtotal:num(breakup.total_product_price),discount:num(pick(p,["discountAmount"]))??(num(breakup.total_discount_applied)||void 0),shipping:num(pick(p,["shippingPrice"]))??num(breakup.shipping_price),tax:num(pick(p,["tax"]))??num(breakup.tax),cod_charges:num(breakup.cod_charges)??num(analytics2.codCharges),payment_method:str(pick(p,["paymentMethod","payment_method"])),discount_codes:coupon&&coupon!=="NA"?[coupon]:void 0,is_guest:typeof p.is_guest==="boolean"?p.is_guest:void 0,item_count:items.length?items.reduce((sum,i)=>sum+(num(pick(i,["Product Quantity","quantity"]))??0),0):void 0,line_item_variant_ids:items.map(i=>str(pick(i,["Product Variant Id","Product Variant ID","variant_id"]))??""),line_item_product_ids:items.map(i=>str(pick(i,["Product ID","product_id"]))??""),line_item_titles:items.map(i=>str(pick(i,["Product Name","title"]))??""),line_item_quantities:items.map(i=>num(pick(i,["Product Quantity","quantity"]))??0),line_item_prices:items.map(i=>num(pick(i,["Product Price","price"]))??0),gk_event_id:str(p.event_id),checkout_provider:"gokwik"})}function mapGokwikStep(event){const payload=gokwikPayload(event);const step=str(payload.event)??str((event.customData??{}).name);if(!step)return null;const name=Object.prototype.hasOwnProperty.call(GOKWIK_STEPS,step)?GOKWIK_STEPS[step]:"gokwik_checkout_step";if(!name)return null;const properties=gokwikProps(payload);if(name==="gokwik_checkout_step")properties.gk_event=step;return{kind:"track",name,properties}}function mapGokwikPurchase(event){const properties=gokwikProps(gokwikPayload(event));if(properties.revenue===void 0)return null;return{kind:"track",name:"order_completed",properties}}function mapPageViewed(event){const location2=event.context?.document?.location;if(!isCheckoutPath(location2?.pathname))return null;return{kind:"page",name:event.context?.document?.title||"Checkout",properties:compact({path:location2?.pathname,$checkout_step:true})}}function mapEvent(event){const data=event.data??{};switch(event.name){case"page_viewed":return mapPageViewed(event);case"product_viewed":return{kind:"track",name:"product_viewed",properties:compact(variantProps(data.productVariant))};case"collection_viewed":{const collection=data.collection;return{kind:"track",name:"collection_viewed",properties:compact({collection_id:collection?.id??void 0,title:collection?.title??void 0,products_count:collection?.productVariants?.length??void 0})}}case"search_submitted":{const result=data.searchResult;return{kind:"track",name:"products_searched",properties:compact({query:result?.query??void 0,results_count:result?.productVariants?.length??void 0})}}case"product_added_to_cart":return{kind:"track",name:"product_added_to_cart",properties:cartLineProps(data.cartLine)};case"product_removed_from_cart":return{kind:"track",name:"product_removed_from_cart",properties:cartLineProps(data.cartLine)};case"cart_viewed":{const cart=data.cart;return{kind:"track",name:"cart_viewed",properties:compact({cart_id:cart?.id??void 0,item_count:cart?.totalQuantity??void 0,total_price:amount(cart?.cost?.totalAmount),currency:cart?.cost?.totalAmount?.currencyCode??void 0})}}case"checkout_started":case"checkout_contact_info_submitted":case"checkout_address_info_submitted":case"checkout_shipping_info_submitted":case"payment_info_submitted":return{kind:"track",name:event.name,properties:checkoutProps(data.checkout??{})};case"checkout_completed":return{kind:"track",name:"order_completed",properties:checkoutProps(data.checkout??{})};case"alert_displayed":{const alert=data.alert;return{kind:"track",name:"checkout_alert_displayed",properties:compact({alert_type:alert?.type??void 0,message:alert?.message??void 0})}}case"gokwik_events":return mapGokwikStep(event);case"gokwik_purchase_event":return mapGokwikPurchase(event);default:return null}}var SUBSCRIBED_EVENTS=["page_viewed","product_viewed","collection_viewed","search_submitted","product_added_to_cart","product_removed_from_cart","cart_viewed","checkout_started","checkout_contact_info_submitted","checkout_address_info_submitted","checkout_shipping_info_submitted","payment_info_submitted","checkout_completed","alert_displayed","gokwik_events","gokwik_purchase_event"];function toDepsmithSdkContext(context){const out={};const location2=context?.document?.location;if(location2?.href||location2?.pathname){out.page=compact({url:location2?.href,path:location2?.pathname,referrer:context?.document?.referrer,title:context?.document?.title})}const screen2=context?.window?.screen;if(typeof screen2?.width==="number"||typeof screen2?.height==="number"){out.screen=compact({width:screen2?.width,height:screen2?.height})}if(context?.navigator?.language)out.locale=context.navigator.language;if(context?.navigator?.userAgent)out.user_agent=context.navigator.userAgent;return out}var ANON_KEY="depsmith_anonymous_id";var COOKIE_MAX_AGE_SECONDS=60*60*24*365;var FLUSH_INTERVAL_MS=15e3;function resolveSandbox(){try{const api=globalThis.api??{};const resolvedAnalytics=typeof analytics!=="undefined"?analytics:api.analytics;const resolvedBrowser=typeof browser!=="undefined"?browser:api.browser;const resolvedInit=(typeof init!=="undefined"?init:api.init)??{};if(!resolvedAnalytics?.subscribe||!resolvedBrowser?.localStorage)return null;return{analytics:resolvedAnalytics,browser:resolvedBrowser,init:resolvedInit}}catch{return null}}var UNFILLED_API_KEY=["REPLACE","WITH","YOUR","API","KEY"].join("_");function readConfig(){const config=globalThis.DEPSMITH_SDK_CONFIG;if(!config?.apiKey||!config.endpoint)return null;if(config.apiKey===UNFILLED_API_KEY)return null;return config}async function startShopifyPixel(){const sandbox=resolveSandbox();const config=readConfig();if(!sandbox||!config)return;const storage=new AsyncMirrorAdapter(sandbox.browser.localStorage,DEPSMITH_SDK_STORAGE_KEYS);await storage.hydrate();let anonymousId=null;try{anonymousId=await sandbox.browser.cookie.get(ANON_KEY)||null}catch{}if(anonymousId)storage.set(ANON_KEY,anonymousId);const shop=sandbox.init.data?.shop;let context=toDepsmithSdkContext(sandbox.init.context);const client2=DepsmithSdk.init({...config,autocapture:false,compression:"none",consentMode:"granted",defaultProperties:{...config.defaultProperties,$source:"shopify_pixel",...shop?.myshopifyDomain?{$shop:shop.myshopifyDomain}:{},...shop?.paymentSettings?.currencyCode??shop?.currencyCode?{$currency:shop?.paymentSettings?.currencyCode??shop?.currencyCode}:{}}},{storage,manualLifecycle:true,contextProvider:()=>context,schedule:syncScheduler});if(!client2)return;if(!anonymousId){try{await sandbox.browser.cookie.set(`${ANON_KEY}=${DepsmithSdk.getAnonymousId()??""}; path=/; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`)}catch{}}const customer=sandbox.init.data?.customer;if(customer?.id){DepsmithSdk.identify(String(customer.id),{...customer.email?{email:customer.email}:{},...customer.firstName?{first_name:customer.firstName}:{},...customer.lastName?{last_name:customer.lastName}:{},...typeof customer.ordersCount==="number"?{orders_count:customer.ordersCount}:{}})}const handlerFor=name=>event=>{try{context=toDepsmithSdkContext(event.context??sandbox.init.context);const mapped=mapEvent(event);if(!mapped)return;const properties={...mapped.properties};if(event.clientId)properties.$shopify_client_id=event.clientId;if(mapped.kind==="page")DepsmithSdk.page(mapped.name,properties);else DepsmithSdk.track(mapped.name,properties);if(FLUSH_ON.has(name))void DepsmithSdk.flush()}catch{}};for(const name of SUBSCRIBED_EVENTS){sandbox.analytics.subscribe(name,handlerFor(name))}setInterval(()=>void DepsmithSdk.flush(),FLUSH_INTERVAL_MS)}void startShopifyPixel().catch(()=>{});})();
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var j=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var ve=(r,e)=>()=>(r&&(e=r(r=0)),e);var ye=(r,e)=>{for(var t in e)j(r,t,{get:e[t],enumerable:!0})},ot=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nt(e))!it.call(r,i)&&i!==t&&j(r,i,{get:()=>e[i],enumerable:!(n=rt(e,i))||n.enumerable});return r};var st=r=>ot(j({},"__esModule",{value:!0}),r);function Y(r,e){let t=[],n=r;for(;n&&n!==document.documentElement&&t.length<e;){let i=n.tagName.toLowerCase();if(n.id){t.unshift(`${i}#${n.id}`);break}let o=Array.from(n.classList).slice(0,3);o.length&&(i+=`.${o.join(".")}`);let s=n.parentElement;if(s){let a=Array.from(s.children).filter(d=>d.tagName===n.tagName);a.length>1&&(i+=`:nth-of-type(${a.indexOf(n)+1})`)}t.unshift(i),n=s}return t.join(" > ")}function X(r,e){if(r.closest("[data-depsmith-sdk-no-capture]"))return!0;for(let t of e)try{if(r.closest(t))return!0}catch{}return!1}function Se(r){if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r.closest("[data-depsmith-sdk-mask]"))return;let e=r.textContent?.trim().replace(/\s+/g," ");return e?e.slice(0,255):void 0}function be(r){return r instanceof HTMLInputElement?at.has(r.type)||!!r.closest("[data-depsmith-sdk-mask]"):!1}var at,ke=ve(()=>{"use strict";at=new Set(["password","email","tel","hidden","number"])});var we={};ye(we,{startAutocapture:()=>ut});function ut(r,e){let t=[],n=[];if(r.clicks&&t.push(ct(r,e)),r.forms&&t.push(pt(r,e)),r.scrolls){let i=ft(e);t.push(i.stop),n.push(i.rearm)}return r.pageviews&&n.push(e.page),n.length>0&&t.push(mt(()=>{for(let i of n)i()})),()=>{for(let i of t.splice(0))i()}}function ct(r,e){let t=r.clicks!=="all",n=i=>{let o=i.target;if(!(o instanceof Element))return;let s=o.closest(dt);if(t&&!s)return;let a=s??o;if(X(a,r.ignoredSelectors))return;let d={$ac_kind:"click",$ac_selector:Y(a,r.selectorMaxDepth),$ac_tag:a.tagName.toLowerCase()},u=Se(a);u&&(d.$ac_text=u),a instanceof HTMLAnchorElement&&a.href&&(d.$ac_href=a.href),e.emit(d)};return document.documentElement.addEventListener("click",n,{capture:!0,passive:!0}),()=>document.documentElement.removeEventListener("click",n,{capture:!0})}function pt(r,e){let t=n=>{let i=n.target;if(!(i instanceof HTMLFormElement)||X(i,r.ignoredSelectors))return;let o=Array.from(i.elements).filter(s=>s instanceof HTMLInputElement&&!be(s)).map(s=>s.name||s.id).filter(Boolean).slice(0,50);e.emit({$ac_kind:"form_submit",$ac_selector:Y(i,r.selectorMaxDepth),$ac_form_id:i.id||null,$ac_form_fields:o})};return document.documentElement.addEventListener("submit",t,{capture:!0,passive:!0}),()=>document.documentElement.removeEventListener("submit",t,{capture:!0})}function ft(r){let e=0,t=-1,n=0,i=!1,o,s=()=>{t=o?o.scrollHeight-o.clientHeight:document.documentElement.scrollHeight-window.innerHeight},a=()=>Math.min(100,Math.round((o?o.scrollTop:window.scrollY)/t*100)),d=()=>{if(n=0,t<=0&&s(),t<=0||a()<E[e]||(s(),t<=0))return;let m=a();for(;e<E.length&&m>=E[e];)r.emit({$ac_kind:"scroll_depth",$ac_depth:E[e]}),e++;e>=E.length&&me()},u=m=>{if(o&&!o.isConnected&&(o=void 0),o===null&&t===0&&(o=void 0),o===void 0){let v=m.target;if(!(v instanceof Element)||v===document.documentElement||document.documentElement.scrollHeight>window.innerHeight)o=null;else{let H=v;if(H.scrollHeight-H.clientHeight<lt)return;o=H}t=-1,x()}else if(o&&m.target!==o)return;n===0&&(n=ht(d))},p=()=>{t=-1},l=null,x=()=>{if(!(typeof ResizeObserver>"u"))try{if(l?.disconnect(),l=new ResizeObserver(p),l.observe(o??document.documentElement),o){let m=o.children;for(let v=0;v<m.length;v++)l.observe(m[v])}}catch{l=null}},ge=()=>{i||(i=!0,window.addEventListener("scroll",u,{capture:!0,passive:!0}),window.addEventListener("resize",p,{passive:!0}),window.addEventListener("orientationchange",p,{passive:!0}),x())},me=()=>{i&&(i=!1,window.removeEventListener("scroll",u,{capture:!0}),window.removeEventListener("resize",p),window.removeEventListener("orientationchange",p),l?.disconnect(),l=null)};return ge(),{stop:()=>{n!==0&&gt(n),n=0,me()},rearm:()=>{e=0,t=-1,o=void 0,ge()}}}function ht(r){return typeof requestAnimationFrame=="function"?requestAnimationFrame(r):setTimeout(r,16)}function gt(r){typeof cancelAnimationFrame=="function"?cancelAnimationFrame(r):clearTimeout(r)}function mt(r){let e=location.href,t=()=>{location.href!==e&&(e=location.href,r())},n=history.pushState.bind(history),i=history.replaceState.bind(history);return history.pushState=(...o)=>{n(...o),t()},history.replaceState=(...o)=>{i(...o),t()},window.addEventListener("popstate",t),()=>{history.pushState=n,history.replaceState=i,window.removeEventListener("popstate",t)}}var dt,E,lt,xe=ve(()=>{"use strict";ke();dt='a, button, [role="button"], input[type="submit"], input[type="button"], [data-depsmith-sdk-capture]';E=[25,50,75,100],lt=240});var jt={};ye(jt,{AsyncMirrorAdapter:()=>U,DEPSMITH_SDK_STORAGE_KEYS:()=>ae,DepsmithSdk:()=>Ht,DepsmithSdkClient:()=>w,idleScheduler:()=>S,syncScheduler:()=>Ve});module.exports=st(jt);function Ee(){return Promise.resolve().then(()=>(xe(),we))}var G=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screen","screen"],["timezone","timezone"],["userAgent","user_agent"]],vt=Object.fromEntries(G.map(([r])=>[r,!0]));function _e(r){let e={...vt};if(!r)return e;for(let[t]of G)r[t]===!1&&(e[t]=!1);return e}function Ae(r,e){let t=r;for(let[n,i,o]of G){if(e[n])continue;if(o===void 0){delete t[i];continue}let s={...t[i]};delete s[o],Object.keys(s).length>0?t[i]=s:delete t[i]}return r}var J={clicks:"interactive",forms:!0,scrolls:!0,pageviews:!0,ignoredSelectors:[],selectorMaxDepth:5};function yt(r){return r===void 0?J.clicks:r===!0?"interactive":r}function Pe(r){if(!r||typeof r.apiKey!="string"||r.apiKey.length===0)throw new Error("depsmith-sdk: apiKey is required");if(typeof r.endpoint!="string"||!/^https?:\/\//.test(r.endpoint))throw new Error("depsmith-sdk: endpoint must be an http(s) URL");let e=r.autocapture===!0?J:r.autocapture&&typeof r.autocapture=="object"?{...J,...r.autocapture,clicks:yt(r.autocapture.clicks)}:!1;return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:W(r.batchSize??20,1,500),batchIntervalMs:Math.max(r.batchIntervalMs??6e4,1e3),maxQueueSize:Math.max(r.maxQueueSize??1e3,1),maxQueueBytes:Math.max(r.maxQueueBytes??512*1024,4096),sessionTimeoutMs:Math.max(r.sessionTimeoutMs??18e5,6e4),sampleRate:Number.isFinite(r.sampleRate)?W(r.sampleRate,0,1):1,sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:W(r.maxRetries??5,0,10),debug:r.debug??!1,defaultProperties:r.defaultProperties??{},autocapture:e,compression:r.compression??"gzip",childSafeMode:r.childSafeMode??!1,anonymizeIp:(r.anonymizeIp??!1)||(r.childSafeMode??!1),deviceFingerprinting:r.deviceFingerprinting??!0,geolocation:r.geolocation??!1,trackingOptions:_e(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage"}}function W(r,e,t){return Math.min(Math.max(r,e),t)}function Q(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)>>>0;return e.toString(36)}function Oe(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e>>>0}function St(r){return Oe(r).toString(36)}function Ce(r){return Oe(r)/4294967296}function Z(r){return Q(r)+St(r)}var ee={},Te=!1;function Ie(){if(!Te){Te=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{ee=e}).catch(()=>{})}catch{}}}function $e(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,n=xt(e,t);n&&(r.browser=n);let i=_t(e);if(i){let a=kt(i.name,ee.platformVersion);r.os=a?{...i,version:a}:i}let o=At(e,t);o&&(r.deviceType=o);let s=bt(e,i);return s&&(r.device=s),r}function bt(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let n=ee.model?.trim();return n?t.model=n:/iPhone/.test(r)?t.model="iPhone":/iPad/.test(r)&&(t.model="iPad"),t.manufacturer||t.model?t:void 0}function kt(r,e){let t=e?.trim();if(t){if(r==="Windows"){let n=Number.parseInt(t.split(".")[0]??"",10);return!Number.isFinite(n)||n===0?void 0:n>=13?"11":"10"}return Me(t)}}var wt=[{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 xt(r,e){for(let n of wt){if(n.requires&&!n.requires.test(r))continue;let i=r.match(n.pattern);if(i)return{name:n.name,version:i[1],engine:n.engine}}let t=e?.brands?.find(n=>!/not.?a.?brand/i.test(n.brand));if(t)return{name:t.brand,version:t.version}}var Et=[{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 _t(r){for(let e of Et){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:Me((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function Me(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function At(r,e){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(r))return"tablet";if(e?.mobile===!0||/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(r))return"mobile";if(/Android/.test(r))return"tablet";if(typeof navigator<"u"&&r)return"desktop"}var C=null,T=null;function Re(){return T!==null||(T=Pt()),T}function I(){return C!==null||(C=Z(Re().map(r=>r.value).join("|"))),C}function De(){let r={};for(let e of Re())r[`$fp_${e.name}`]=e.value;return r}function Pt(){let r=[];try{if(typeof screen<"u"&&r.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`}),typeof navigator<"u"){let e=navigator;r.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`}),r.push({name:"dm",value:`dm:${e.deviceMemory??""}`}),r.push({name:"plat",value:`plat:${navigator.platform??""}`}),r.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}r.push({name:"canvas",value:`canvas:${Ot()}`})}catch{}return r}function Ot(){try{if(typeof document>"u")return"";let r=document.createElement("canvas");r.width=240,r.height=60;let e=r.getContext("2d");return e?(e.textBaseline="top",e.font="14px 'Arial'",e.fillStyle="#f60",e.fillRect(10,10,100,30),e.fillStyle="#069",e.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15),e.strokeStyle="rgba(0,120,200,0.5)",e.arc(50,30,20,0,Math.PI*2),e.stroke(),Z(r.toDataURL())):""}catch{return""}}function Ne(){try{if(typeof navigator>"u")return{};let r=navigator.connection;if(!r)return{};switch(r.type){case"wifi":return{type:"wifi"};case"ethernet":return{type:"ethernet"};case"none":return{type:"none"}}switch(r.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var $=null,Ue=0,Le=!1,_=!1,qe=null;function ze(){if(!Le){Le=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let r=navigator.permissions;if(typeof r?.query!="function")return;r.query({name:"geolocation"}).then(e=>{qe=e,e.state==="granted"&&te(),e.onchange=()=>{e.state==="granted"?te():$=null}}).catch(()=>{})}catch{}}}function te(){if(!_){_=!0;try{navigator.geolocation.getCurrentPosition(r=>{_=!1;let{latitude:e,longitude:t,accuracy:n}=r.coords;if(!Number.isFinite(e)||!Number.isFinite(t))return;let i={latitude:e,longitude:t,source:"gps"};Number.isFinite(n)&&(i.accuracy=n),$=i,Ue=Date.now()},()=>{_=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{_=!1}}}function Ke(){if($)return Date.now()-Ue>3e5&&qe?.state==="granted"&&te(),{...$}}var ne="@depsmith/depsmith-sdk",y="0.6.0",re=null;function Ct(){if(re)return re;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),re=r,r}function P(r={}){let e={library:{name:ne,version:y}};A(()=>{typeof window<"u"&&window.location&&(e.page={url:window.location.href,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0})}),A(()=>{typeof window<"u"&&window.screen&&(e.screen={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),A(()=>{let t=Ct();t.locale!==void 0&&(e.locale=t.locale),t.userAgent!==void 0&&(e.user_agent=t.userAgent),t.timezone!==void 0&&(e.timezone=t.timezone)}),A(()=>{r.fingerprint&&Tt(e)}),A(()=>{if(r.geolocation){let t=Ke();t&&(e.location=t)}});try{if(r.overrides){for(let[t,n]of Object.entries(r.overrides))n!==void 0&&(e[t]=n);e.library={name:ne,version:y}}}catch{}return r.tracking&&Ae(e,r.tracking),e}function Tt(r){let{browser:e,os:t,deviceType:n,device:i}=$e();e&&(r.browser=e),t&&(r.os=t);let o={};n&&(o.type=n),i?.manufacturer&&(o.manufacturer=i.manufacturer),i?.model&&(o.model=i.model),Object.keys(o).length>0&&(r.device=o);let s=Ne();s.type&&(r.network={...r.network,type:s.type})}function A(r){try{r()}catch{}}function Fe(){try{if(typeof navigator>"u")return!1;let r=navigator,e=typeof window<"u"?window:{},t=navigator.doNotTrack??e.doNotTrack??r.msDoNotTrack;return t==="1"||t==="yes"}catch{return!1}}var ie="depsmith_consent",M=class{constructor(e,t,n){this.storage=e;this.dntActive=n;let i=e.get(ie);this.state=i==="granted"||i==="denied"||i==="pending"?i:t}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.effective()==="granted"}get current(){return this.effective()}optIn(){this.state="granted",this.storage.set(ie,"granted")}optOut(){this.state="denied",this.storage.set(ie,"denied")}};var S=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},Ve=r=>r();var R="depsmith_queue",It=512*1024,oe=2,$t=new Set(["identify","alias","group"]);function Mt(r){return $t.has(r?.event_type)}var D=class{constructor(e,t,n,i={}){this.storage=e;this.maxSize=t;this.logger=n;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=!1;this.scheduled=!1;this.maxChars=i.maxChars??It,this.schedule=i.schedule??S,this.restore()}restore(){try{let e=this.storage.get(R);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;let n=t.filter(i=>!!i&&typeof i=="object"&&typeof i.event_id=="string");this.reset(n),n.length!==t.length&&(this.logger.warn("discarded corrupt queued events on restore"),this.markDirty()),this.trimToBudget()&&this.markDirty()}catch{this.logger.warn("queue storage corrupt; starting empty"),this.reset([]),this.storage.remove(R)}}reset(e){this.events=e,this.sizes=e.map(t=>Be(t)),this.sizeSum=this.sizes.reduce((t,n)=>t+n,0)}serializedLength(){return this.events.length===0?oe:this.sizeSum+(this.events.length-1)+oe}trimToBudget(){let e=0;for(;this.events.length>0&&this.serializedLength()>this.maxChars;)this.evictAt(this.victimIndex()),e++;return e>0&&this.logger.warn(`queue byte cap reached; dropped ${e} event(s)`),e>0}markDirty(){this.dirty=!0,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){this.dirty&&(this.dirty=!1,this.storage.set(R,JSON.stringify(this.events)))}prepend(e){let t=new Set(this.events.map(i=>i.event_id)),n=e.filter(i=>!!i&&typeof i=="object"&&typeof i.event_id=="string"&&!t.has(i.event_id));n.length!==0&&(this.reset([...n,...this.events]),this.events.length>this.maxSize&&this.dropOldest(this.events.length-this.maxSize),this.trimToBudget(),this.markDirty())}enqueue(e){let t=Be(e);if(t+oe>this.maxChars){this.logger.warn(`event ${e.event_id} exceeds the queue byte cap; dropped`);return}if(this.events.push(e),this.sizes.push(t),this.sizeSum+=t,this.events.length>this.maxSize){let n=this.events.length-this.maxSize;this.dropOldest(n),this.logger.warn(`queue cap reached; dropped ${n} event(s)`)}this.trimToBudget(),this.markDirty()}victimIndex(){for(let e=0;e<this.events.length;e++)if(!Mt(this.events[e]))return e;return 0}evictAt(e){this.events.splice(e,1),this.sizeSum-=this.sizes.splice(e,1)[0]??0}dropOldest(e){for(let t=0;t<e&&this.events.length>0;t++)this.evictAt(this.victimIndex())}get size(){return this.events.length}peek(e){return this.events.slice(0,e)}remove(e){let t=new Set(e),n=[],i=[],o=0;for(let s=0;s<this.events.length;s++){let a=this.events[s];if(t.has(a.event_id))continue;let d=this.sizes[s];n.push(a),i.push(d),o+=d}this.events=n,this.sizes=i,this.sizeSum=o,this.markDirty()}clear(){this.reset([]),this.dirty=!1,this.storage.remove(R)}};function Be(r){return JSON.stringify(r).length}function f(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let n=0;n<16;n++)e[n]=Math.floor(Math.random()*256);e[0]=r/2**40&255,e[1]=r/2**32&255,e[2]=r/2**24&255,e[3]=r/2**16&255,e[4]=r/2**8&255,e[5]=r&255,e[6]=e[6]&15|112,e[8]=e[8]&63|128;let t=[];for(let n=0;n<16;n++)t.push(e[n].toString(16).padStart(2,"0"));return`${t[0]}${t[1]}${t[2]}${t[3]}-${t[4]}${t[5]}-${t[6]}${t[7]}-${t[8]}${t[9]}-${t[10]}${t[11]}${t[12]}${t[13]}${t[14]}${t[15]}`}function b(r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r))return null;let e=r.slice(0,8)+r.slice(9,13),t=parseInt(e,16);return Number.isFinite(t)?t:null}var ae=["depsmith_anonymous_id","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker"],k=class{constructor(){this.data=new Map}get(e){return this.data.get(e)??null}set(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}},se=class{constructor(e){this.ls=e}get(e){try{return this.ls.getItem(e)}catch{return null}}set(e,t){try{this.ls.setItem(e,t)}catch{}}remove(e){try{this.ls.removeItem(e)}catch{}}},N=class{constructor(e){this.domain=e}get(e){try{let t=`${encodeURIComponent(e)}=`;for(let n of document.cookie.split("; "))if(n.startsWith(t))return decodeURIComponent(n.slice(t.length))}catch{}return null}attributes(e){let t=this.domain?`; domain=${this.domain}`:"",n=typeof location<"u"&&location.protocol==="https:"?"; Secure":"";return`${t}; path=/; max-age=${e}; SameSite=Lax${n}`}set(e,t){try{document.cookie=`${encodeURIComponent(e)}=${encodeURIComponent(t)}${this.attributes(3456e4)}`}catch{}}remove(e){try{document.cookie=`${encodeURIComponent(e)}=${this.attributes(0)}`}catch{}}},Rt=new Set(["depsmith_anonymous_id"]),L=class{constructor(e,t,n=Rt){this.primary=e;this.secondary=t;this.mirrored=n}get(e){let t=this.primary.get(e);if(!this.mirrored.has(e))return t;let n=this.secondary.get(e);if(t===n)return t;if(t===null&&n!==null)return this.primary.set(e,n),n;if(n===null&&t!==null)return this.secondary.set(e,t),t;let i=Dt(t,n)??t;return this.primary.set(e,i),this.secondary.set(e,i),i}set(e,t){this.primary.set(e,t),this.mirrored.has(e)&&this.secondary.set(e,t)}remove(e){this.primary.remove(e),this.secondary.remove(e)}};function Dt(r,e){let t=b(r),n=b(e);return t===null||n===null?null:t<=n?r:e}var O=class{constructor(e="depsmith-sdk"){this.mirror=new Map;this.snapshot=new Map;this.db=null;this.ready=this.open(e)}open(e){return new Promise(t=>{try{let n=indexedDB.open(e,1);n.onupgradeneeded=()=>n.result.createObjectStore("kv"),n.onsuccess=()=>{this.db=n.result;let i=this.db.transaction("kv","readonly").objectStore("kv"),o=i.getAllKeys(),s=i.getAll();s.onsuccess=()=>{let a=o.result;s.result.forEach((d,u)=>{let p=a[u];p!==void 0&&(this.snapshot.set(p,d),this.mirror.has(p)||this.mirror.set(p,d))}),t()},s.onerror=()=>t()},n.onerror=()=>t()}catch{t()}})}hydrate(){return this.ready.then(()=>this.snapshot)}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").put(t,e)}catch{}})}remove(e){this.mirror.delete(e),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").delete(e)}catch{}})}},U=class{constructor(e,t=ae){this.backend=e;this.keys=t;this.mirror=new Map;this.hydrated=null}hydrate(){return this.hydrated??(this.hydrated=Promise.all(this.keys.map(async e=>{try{let t=await this.backend.getItem(e);typeof t=="string"&&!this.mirror.has(e)&&this.mirror.set(e,t)}catch{}})).then(()=>{})),this.hydrated}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),Promise.resolve(this.backend.setItem(e,t)).catch(()=>{})}remove(e){this.mirror.delete(e),Promise.resolve(this.backend.removeItem(e)).catch(()=>{})}};function He(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new se(window.localStorage)}}catch{}return new k}var de="depsmith_anonymous_id",ue="depsmith_user_id",ce="depsmith_group_id",q="depsmith_user_props",z=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(de);return e||(e=f(this.clock.now()),this.storage.set(de,e)),e}get userId(){return this.storage.get(ue)}get groupId(){return this.storage.get(ce)}identify(e){this.storage.set(ue,e)}setGroup(e){this.storage.set(ce,e)}getUserProps(){try{return JSON.parse(this.storage.get(q)??"{}")}catch{return{}}}setUserProp(e,t){let n=this.getUserProps();n[e]=t,this.storage.set(q,JSON.stringify(n))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(q,JSON.stringify(t))}reset(){this.storage.remove(ue),this.storage.remove(ce),this.storage.remove(q);let e=f(this.clock.now());return this.storage.set(de,e),e}};var je="depsmith_session",K=class{constructor(e,t,n,i=S){this.storage=e;this.clock=t;this.timeoutMs=n;this.pending=null;this.scheduled=!1;this.schedule=i}load(){let e=this.readStored(),t=this.pending;return t?!e||t.lastActivityAt>=e.lastActivityAt?t:(this.pending=null,e):e}readStored(){try{let e=this.storage.get(je);if(!e)return null;let t=JSON.parse(e);return typeof t.id!="string"||typeof t.lastActivityAt!="number"?null:(typeof t.startedAt!="number"&&(t.startedAt=b(t.id)??t.lastActivityAt),t)}catch{return null}}save(e){this.pending=e,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){let e=this.pending;e&&(this.pending=null,this.storage.set(je,JSON.stringify(e)))}mint(e){let t={id:f(e),lastActivityAt:e,startedAt:e};return this.save(t),t}touch(){let e=this.clock.now(),t=this.load();if(!t){let n=this.mint(e);return{sessionId:n.id,startedAt:e,startedSession:{id:n.id,startedAt:e}}}if(e-t.lastActivityAt>this.timeoutMs){let n=this.mint(e);return{sessionId:n.id,startedAt:e,endedSession:{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt},startedSession:{id:n.id,startedAt:e}}}return this.save({id:t.id,lastActivityAt:e,startedAt:t.startedAt}),{sessionId:t.id,startedAt:t.startedAt}}peek(){let e=this.load();return e?e.id:this.mint(this.clock.now()).id}adopt(e,t){let n=b(e);return n===null?!1:(this.save({id:e,lastActivityAt:this.clock.now(),startedAt:t??n}),!0)}rotate(){return this.mint(this.clock.now()).id}};function h(r,e){if(r==null)return{};if(typeof r!="object"||Array.isArray(r))return e.warn("properties must be an object; ignoring",r),{};let t={},n=0;for(let[i,o]of Object.entries(r)){if(n>=200){e.warn("properties exceed 200 keys; excess dropped");break}let s=Nt(o,e);if(s===void 0){e.debug(`property "${i}" dropped (unsupported value)`);continue}t[String(i)]=s,n++}return t}function pe(r){if(r===null)return null;let e=typeof r;if(e==="string"||e==="boolean")return r;if(e==="number")return Number.isFinite(r)?r:void 0;if(r instanceof Date)return isNaN(r.getTime())?void 0:r.toISOString()}function Nt(r,e){let t=pe(r);if(t!==void 0)return t;if(!(r===void 0||typeof r=="function"||typeof r=="symbol")){if(Array.isArray(r)){let n=[];for(let i of r.slice(0,100)){let o=pe(i);n.push(o!==void 0?o:Ye(i))}return n}if(typeof r=="object"){let n={},i=0;for(let[o,s]of Object.entries(r)){if(i>=50){e.debug("nested object exceeds 50 keys; excess dropped");break}let a=pe(s);n[String(o)]=a!==void 0?a:Ye(s),i++}return n}}}function Ye(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}var Lt=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],Xe=50,Ge=200;function le(r,e){if(!r||typeof r!="object")return;if(r.$clear_all===!0){let o=Object.keys(r).filter(s=>s!=="$clear_all");return o.length>0&&e.warn(`$clear_all is exclusive; ignored ${o.join(", ")}`),{$clear_all:!0}}let t={},n=new Set,i=(o,s)=>n.has(o)?(e.debug(`"${o}" has an operator already; ${s} dropped`),!1):(n.add(o),!0);for(let o of Lt){let s=r[o];if(!s||typeof s!="object")continue;let a=h(s,e),d={};for(let[u,p]of Object.entries(a))i(u,o)&&(d[u]=p);Object.keys(d).length>0&&(t[o]=d)}if(r.$add&&typeof r.$add=="object"){let o={},s=0;for(let[a,d]of Object.entries(r.$add)){if(s>=Xe){e.debug(`$add over ${Xe} keys; excess dropped`);break}if(typeof d!="number"||!Number.isFinite(d)){e.debug(`$add "${a}" is not finite; dropped`);continue}i(a,"$add")&&(o[a]=d,s++)}Object.keys(o).length>0&&(t.$add=o)}if(Array.isArray(r.$unset)){let o=[];for(let s of r.$unset){if(o.length>=Ge){e.debug(`$unset over ${Ge} keys; excess dropped`);break}typeof s!="string"||s.length===0||i(s,"$unset")&&o.push(s)}o.length>0&&(t.$unset=o)}return Object.keys(t).length>0?t:void 0}function F(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var We={now:()=>Date.now()};function g(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function Je(r){return r===0||r===408||r===429||r>=500}var Ut=1e3,qt=32e3;function Qe(r,e=Math.random){let t=Math.min(Ut*2**r,qt);return Math.round(e()*t)}async function zt(r){let e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new TextEncoder().encode(r)).catch(()=>{}),t.close().catch(()=>{});let n=e.readable.getReader(),i=[];for(;;){let{done:d,value:u}=await n.read();if(d)break;i.push(u)}let o=i.reduce((d,u)=>d+u.length,0),s=new Uint8Array(new ArrayBuffer(o)),a=0;for(let d of i)s.set(d,a),a+=d.length;return s}function Ze(r){let e=[];for(let t of r)e.push(t.event_id);return e}var Kt=3e4,Ft=6e4,Vt=10;function Bt(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var V=class{constructor(e,t,n){this.queue=e;this.config=t;this.deps=n;this.inFlight=null}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){return this.inFlight?this.inFlight:(this.inFlight=this.drain().catch(e=>this.deps.logger.error("flush failed",e)).finally(()=>{this.inFlight=null}),this.inFlight)}async drain(){for(;this.queue.size>0;){if(!this.deps.isOnline()){this.deps.logger.debug("offline; deferring upload");return}if(this.deps.breaker?.open()){this.deps.logger.debug("collector unreachable; uploads paused");return}let e=this.queue.peek(this.config.batchSize);this.queue.persistNow();let t=await this.uploadWithRetry(e);if(t==="requeue")return;t==="dropped"&&this.deps.logger.warn(`dropped poison batch of ${e.length}`),this.queue.remove(Ze(e))}}async uploadWithRetry(e){let t=this.deps.breaker,n=!1;for(let i=0;i<=this.config.maxRetries;i++){let o=await this.post(e);if(o!==0&&(n=!0),o>=200&&o<300)return t?.ok(),"sent";if(!Je(o))return t?.ok(),this.deps.logger.warn(`non-retryable ${o}; dropping batch`),"dropped";if(this.deps.logger.debug(`upload attempt ${i+1} failed (${o})`),o===0&&!n&&t?.suspect())break;i<this.config.maxRetries&&await this.deps.sleep(Qe(i))}return n?t?.ok():t?.fail(),"requeue"}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:g(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){let t=JSON.stringify(this.buildPayload(e)),n=typeof AbortController<"u"?new AbortController:null,i=null;try{let o=t,s={"Content-Type":"application/json"};if(this.config.compression!=="none"&&typeof CompressionStream<"u")try{o=await zt(t),s["Content-Encoding"]="gzip"}catch{o=t}let a=Bt(o)<=Ft;a||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let d={method:"POST",headers:s,body:o,keepalive:a};return n&&(d.signal=n.signal,i=setTimeout(()=>n.abort(),this.timeoutMs())),(await this.deps.fetchFn(`${this.config.endpoint}/e/`,d)).status}catch{return 0}finally{i!==null&&clearTimeout(i)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:Kt}sendBeaconAll(){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let e=0;for(;this.queue.size>0&&e<Vt;){let t=this.queue.peek(this.config.batchSize),n=this.buildPayload(t);if(!navigator.sendBeacon(`${this.config.endpoint}/e/`,new Blob([JSON.stringify(n)],{type:"text/plain"})))return;this.queue.remove(Ze(t)),e++}}catch{}}};var fe="depsmith_net_breaker";function et(r,e){let t=!1,n=0,i=0,o=3e5,s=(u,p,l)=>typeof u=="number"&&u===u?Math.min(Math.max(u,p),l):p,a=()=>{if(!t){t=!0;try{let u=JSON.parse(r.get(fe)??"0");if(!Array.isArray(u))return;n=s(u[0],0,3),i=s(u[1],0,e.now()+36e5),o=s(u[2],3e5,36e5)}catch{}}},d=()=>{try{n?r.set(fe,JSON.stringify([n,i,o])):r.remove(fe)}catch{}};return{open:()=>(a(),e.now()<i),suspect:()=>(a(),n>0),fail:()=>{a(),++n>=3&&(i=e.now()+o,o=Math.min(o*2,36e5),n=3),d()},ok:()=>{a(),n&&(n=i=0,o=3e5,d())}}}var B=class{constructor(e){this.enabled=e}setEnabled(e){this.enabled=e}debug(...e){this.enabled&&console.debug("[depsmith-sdk]",...e)}warn(...e){this.enabled&&console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var tt=255,w=class{constructor(e,t={}){this.flushTimer=null;this.drained=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=Pe(e),this.logger=new B(this.config.debug),this.clock=t.clock??We,this.storage=t.storage??this.pickStorage(),this.contextProvider=t.contextProvider;let n=this.config.childSafeMode?new k:this.config.storage==="memory"?this.storage:new L(this.storage,new N(this.config.cookieDomain||void 0));this.identity=new z(n,this.clock),this.session=new K(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new M(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??Fe())),this.queue=new D(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule}),this.detectConfigDrift(),this.config.deviceFingerprinting&&!this.config.childSafeMode&&Ie(),this.config.geolocation&&!this.config.childSafeMode&&ze(),this.storage instanceof O&&(this.ready=this.storage.hydrate().then(i=>{try{let o=i.get("depsmith_queue");o&&this.queue.prepend(JSON.parse(o))}catch{this.logger.warn("persisted queue corrupt; discarded")}})),this.uploader=new V(this.queue,{endpoint:this.config.endpoint,apiKey:this.config.apiKey,batchSize:this.config.batchSize,maxRetries:this.config.maxRetries,compression:this.config.compression,anonymizeIp:this.config.anonymizeIp,requestTimeoutMs:t.requestTimeoutMs},{fetchFn:t.fetchFn??((...i)=>fetch(...i)),clock:this.clock,logger:this.logger,sleep:t.sleep??(i=>new Promise(o=>setTimeout(o,i))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:et(this.storage,this.clock)}),t.manualLifecycle||(this.startFlushTimer(),this.attachLifecycle(),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}if(e.startsWith("$")){this.logger.warn(`track: "$"-prefixed names are reserved; dropped "${e}"`);return}this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}tooLong(e,t){return e.length<=tt?!1:(this.logger.warn(`${t} exceeds ${tt} characters (got ${e.length}); dropped`),!0)}page(e,t){this.guard(()=>{let n=e??(typeof document<"u"?document.title:void 0)??"Unknown";this.capture("$page_view","page_view",{...t,name:n})})}screen(e,t){this.page(e,t)}identify(e,t){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(e,"identify: userId"))return;this.identity.identify(e);let n=h(t,this.logger);this.capture("$identify","identify",void 0,n,F("$set",n))})}alias(e){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:e})})}reset(){this.guard(()=>{this.identity.reset(),this.session.rotate(),this.logger.debug("reset: identity and session rotated")})}group(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("group: groupId required");return}this.tooLong(e,"group: groupId")||(this.identity.setGroup(e),this.capture("$group","group",void 0,h(t,this.logger)))})}setGroupTraits(e){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}this.capture("$group","group",void 0,h(e,this.logger))})}setProperty(e,t){this.guard(()=>{this.identity.setUserProp(e,t);let n=h({[e]:t},this.logger);this.capture("$identify","identify",void 0,n,F("$set",n))})}setOnceProperty(e,t){this.guard(()=>{if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.identity.setUserProp(e,t);let n=h({[e]:t},this.logger);this.capture("$identify","identify",void 0,n,F("$set_once",n))})}unsetProperty(e){this.guard(()=>{this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},le({$unset:[e]},this.logger))})}setUserProperties(e){this.guard(()=>{let t=le(e,this.logger);t&&this.capture("$identify","identify",void 0,void 0,t)})}optIn(){this.guard(()=>{this.consent.optIn(),this.logger.debug("consent granted"),this.flushUploads()})}optOut(){this.guard(()=>{this.consent.optOut(),this.queue.clear(),this.logger.debug("consent denied; queue cleared")})}async flush(){try{if(!this.consent.canUpload()){this.logger.debug("flush skipped: consent not granted");return}await this.flushUploads()}catch(e){this.logger.error("flush error",e)}}autocapture(e){this.guard(()=>this.capture("$autocapture","autocapture",e))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(e,t){this.guard(()=>{(typeof e!="string"||!this.session.adopt(e,t))&&this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(e)}"`)})}shutdown(){this.flushTimer!==null&&clearInterval(this.flushTimer),this.flushTimer=null;for(let e of this.teardownFns.splice(0))e();this.persistNow()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}enqueueEvent(e){this.queue.enqueue(e),this.drained=!1}flushUploads(){return this.ready.then(()=>this.uploader.flush())}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}return{fingerprint:this.config.deviceFingerprinting&&!this.config.childSafeMode&&this.consent.current==="granted",geolocation:this.config.geolocation&&!this.config.childSafeMode&&this.consent.current==="granted",overrides:e,tracking:this.config.trackingOptions}}sessionInSample(e){return this.config.sampleRate>=1?!0:Ce(`${this.config.apiKey}:${e}`)<this.config.sampleRate}inSample(e,t){return t==="identify"||t==="alias"||t==="group"?!0:this.sessionInSample(e)}capture(e,t,n,i,o){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let s=this.session.touch();if(s.endedSession&&this.sessionInSample(s.endedSession.id)&&this.enqueueSessionEnd(s.endedSession),s.startedSession&&this.sessionInSample(s.startedSession.id)&&this.enqueueSessionStart(s.startedSession),!this.inSample(s.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let a=this.clock.now(),d=this.contextOptions(),u={event_id:f(a),event:e,event_type:t,timestamp:g(a),session_id:s.sessionId,session_started_at:g(s.startedAt),anonymous_id:this.identity.anonymousId,context:i?{...P(d),traits:i}:P(d),platform:"web",sdk_version:y};o&&(u.user_properties=o);let p={...this.config.defaultProperties,...h(n,this.logger)};Object.keys(p).length>0&&(u.properties=p);let l=this.identity.userId;l&&(u.user_id=l);let x=this.identity.groupId;x&&(u.group_id=x),d.fingerprint&&(u.device_id=I()),this.enqueueEvent(u),this.logger.debug(`captured ${e}`,u),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(){let e="depsmith_config_fp",t=Q(this.config.apiKey),n=this.storage.get(e);n!==null&&n!==t&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear()),this.storage.set(e,t)}pickStorage(){return this.config.storage==="memory"?new k:this.config.storage==="indexeddb"&&typeof indexedDB<"u"?new O:He()}enqueueSessionEnd(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_end dropped (consent denied)");return}let t=this.contextOptions(),n={event_id:f(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:g(e.lastActivityAt),session_id:e.id,session_started_at:g(e.startedAt),anonymous_id:this.identity.anonymousId,context:P(t),platform:"web",sdk_version:y},i=this.identity.userId;i&&(n.user_id=i),t.fingerprint&&(n.device_id=I()),this.enqueueEvent(n)}enqueueSessionStart(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_start dropped (consent denied)");return}let t=this.contextOptions(),n={event_id:f(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:g(e.startedAt),session_id:e.id,session_started_at:g(e.startedAt),anonymous_id:this.identity.anonymousId,context:P(t),platform:"web",sdk_version:y},i=this.identity.userId;i&&(n.user_id=i),t.fingerprint&&(n.device_id=I()),t.fingerprint&&(n.properties={...n.properties,...De()}),this.enqueueEvent(n)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()},this.config.batchIntervalMs)}attachLifecycle(){if(typeof window>"u"||typeof document>"u")return;let e=()=>{this.drained||(this.drained=!0,this.consent.canUpload()&&this.uploader.sendBeaconAll(),this.persistNow())},t=()=>{if(document.visibilityState==="hidden")e();else{this.drained=!1;let o=this.session.touch();o.endedSession&&this.enqueueSessionEnd(o.endedSession),o.startedSession&&this.enqueueSessionStart(o.startedSession)}},n=()=>{this.drained=!1},i=()=>{this.uploader.resetNetworkBreaker(),this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()};window.addEventListener("pagehide",e),window.addEventListener("pageshow",n),document.addEventListener("visibilitychange",t),window.addEventListener("online",i),this.teardownFns.push(()=>{window.removeEventListener("pagehide",e),window.removeEventListener("pageshow",n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",i)})}startAutocapture(){let e=this.config.autocapture;!e||typeof window>"u"||Ee().then(t=>{t&&this.teardownFns.push(t.startAutocapture(e,{emit:n=>this.autocapture(n),page:()=>this.page()}))}).catch(t=>this.logger.debug("autocapture load failed",t))}guard(e){try{e()}catch(t){this.logger.error("internal error",t)}}};var c=null,he=null,Ht={init(r,e){try{return c&&he===r.apiKey||(c?.shutdown(),c=new w(r,e),he=r.apiKey),c}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>c?.track(r,e),page:(r,e)=>c?.page(r,e),screen:(r,e)=>c?.screen(r,e),identify:(r,e)=>c?.identify(r,e),alias:r=>c?.alias(r),reset:()=>c?.reset(),group:(r,e)=>c?.group(r,e),setGroupTraits:r=>c?.setGroupTraits(r),setProperty:(r,e)=>c?.setProperty(r,e),setOnceProperty:(r,e)=>c?.setOnceProperty(r,e),unsetProperty:r=>c?.unsetProperty(r),setUserProperties:r=>c?.setUserProperties(r),optIn:()=>c?.optIn(),optOut:()=>c?.optOut(),flush:()=>c?.flush()??Promise.resolve(),getAnonymousId:()=>c?.getAnonymousId(),getSessionId:()=>c?.getSessionId(),setSessionId:(r,e)=>c?.setSessionId(r,e),shutdown(){c?.shutdown(),c=null,he=null}};0&&(module.exports={AsyncMirrorAdapter,DEPSMITH_SDK_STORAGE_KEYS,DepsmithSdk,DepsmithSdkClient,idleScheduler,syncScheduler});
2
+ //# sourceMappingURL=index.cjs.map