@logludo/sdk 0.0.0-stage → 1.0.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,2 @@
1
+ /* @logludo/sdk v1.0.0 | Zero-Dependency JavaScript Game Analytics SDK | https://logludo.com */
2
+ "use strict";(()=>{function q(l){if(typeof l=="function")try{let s=l();if(s&&typeof s.toDataURL=="function")return s}catch{}else if(typeof l=="string"){if(typeof document=="undefined")return null;try{let s=document.querySelector(l);if(s&&s.tagName==="CANVAS")return s}catch{}}else if(l&&typeof l.toDataURL=="function")return l;if(typeof document=="undefined")return null;let e=Array.from(document.querySelectorAll("canvas"));if(e.length===0)return null;let i=null,t=-1;for(let s of e){let n=s.getBoundingClientRect(),r=(n.width||s.width||0)*(n.height||s.height||0);r>t&&(t=r,i=s)}return i||e[0]}function ee(l,e,i,t,s){if(e===0&&i===0&&t===l.width&&s===l.height){let o=l.toDataURL("image/png"),h=o.indexOf(",");return h!==-1?o.slice(h+1):o}let n=document.createElement("canvas");n.width=t,n.height=s;let r=n.getContext("2d");if(!r){let o=l.toDataURL("image/png"),h=o.indexOf(",");return h!==-1?o.slice(h+1):o}r.drawImage(l,e,i,t,s,0,0,t,s);let c=n.toDataURL("image/png"),a=c.indexOf(",");return a!==-1?c.slice(a+1):c}async function J(l){let{canvas:e,apiUrl:i,gameId:t,gameVersion:s,sceneName:n}=l,r=Math.max(256,l.tileSize||3e3),c=e.width||1,a=e.height||1,o=Math.max(1,Math.ceil(c/r)),h=Math.max(1,Math.ceil(a/r)),_=`${i.replace(/\/+$/,"")}/capture`;for(let m=0;m<h;m++)for(let u=0;u<o;u++){let g=u*r,k=m*r,v=Math.min(r,c-g),y=Math.min(r,a-k),x=ee(e,g,k,v,y);if(!(await fetch(_,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({game_id:t,game_version:s,room_name:n,image_base64:x,tile_x:u,tile_y:m})})).ok)return!1}return(await fetch(_,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({game_id:t,game_version:s,room_name:n,manifest:{width:c,height:a,tileSize:r,columns:o,rows:h}})})).ok}function N(l,e){var i;if(e==="run")return!0;if(e==="build")return!1;if(typeof l=="boolean")return l;try{if(typeof globalThis!="undefined"){let t=globalThis.location;if(t){let n=(t.hostname||"").toLowerCase();if(n==="localhost"||n==="127.0.0.1"||n==="[::1]"||n==="0.0.0.0"||n.endsWith(".local")||t.protocol==="file:"||typeof t.search=="string"&&/[?&]logludo_dev=(1|true)/i.test(t.search))return!0;if(n.length>0)return!1}let s=globalThis.process;if((i=s==null?void 0:s.env)!=null&&i.NODE_ENV&&s.env.NODE_ENV!=="production")return!0}}catch{}return!1}function te(l){let e=l.toLowerCase();return e.includes("electron")?"Electron":e.includes("edg/")||e.includes("edge/")?"Edge":e.includes("opr/")||e.includes("opera")?"Opera":e.includes("chrome/")||e.includes("crios/")?"Chrome":e.includes("firefox/")||e.includes("fxios/")?"Firefox":e.includes("safari/")?/iphone|ipad|ipod|mobile/i.test(l)?"Mobile Safari":"Safari":e.includes("msie")||e.includes("trident/")?"IE":"Unknown"}function ie(l,e){let i=`${e||""} ${l}`.toLowerCase();return/iphone|ipad|ipod|ios/.test(i)?"iOS":/android/.test(i)?"Android":/cros/.test(i)?"ChromeOS":/win/.test(i)?"Windows":/mac|darwin/.test(i)?"macOS":/linux|x11/.test(i)?"Linux":"Unknown"}function P(){var v,y,x,L;let l={platform:"Web",clientType:"Web",osInfo:"Unknown",deviceModel:"Unknown",domain:"",url:""};if(typeof globalThis=="undefined")return l;let e=globalThis,i=e.navigator,t=e.location,s=(i==null?void 0:i.userAgent)||"",n=((v=i==null?void 0:i.userAgentData)==null?void 0:v.platform)||(i==null?void 0:i.platform)||"",r=s.includes("Electron")||!!((x=(y=e.process)==null?void 0:y.versions)!=null&&x.electron),c=!!(e.__TAURI__||e.__TAURI_INTERNALS__),a=!!e.nw,o=e.Capacitor,h=!!(o!=null&&o.isNativePlatform&&o.isNativePlatform()),_=!!e.cordova,b=ie(s,n),p=s?te(s):"Node.js",m="Web",u="Web";if(r||c||a)m=b!=="Unknown"?b:"Desktop",u="Desktop",r?p="Electron":c&&(p="Tauri");else if(h||_){let T=(L=o==null?void 0:o.getPlatform)==null?void 0:L.call(o);T==="ios"||b==="iOS"?(m="iOS",u="Mobile"):T==="android"||b==="Android"?(m="Android",u="Mobile"):(m=b,u="Mobile")}else if(!t&&typeof e.process!="undefined"){m="Desktop",u="Desktop";let T=e.process;return T.platform==="darwin"?l.osInfo="macOS":T.platform==="win32"?l.osInfo="Windows":T.platform==="linux"&&(l.osInfo="Linux"),{...l,platform:l.osInfo!=="Unknown"?l.osInfo:"Desktop",clientType:"Desktop",deviceModel:"Node.js"}}let g="",k="";return t&&(t.hostname&&(g=t.hostname),t.href&&(t.protocol==="http:"||t.protocol==="https:")&&(k=t.href)),{platform:m,clientType:u,osInfo:b,deviceModel:p,domain:g,url:k}}function U(l){if(l&&l.trim())return l.trim();if(typeof globalThis=="undefined")return"Vanilla";let e=globalThis;return e.Phaser?"Phaser":e.PIXI?"PixiJS":e.THREE?"Three.js":e.BABYLON?"Babylon.js":e.kaplay||e.kaboom?"KAPLAY":e.ex&&typeof e.ex.Engine=="function"?"Excalibur":e.pc&&typeof e.pc.Application=="function"?"PlayCanvas":"Vanilla"}function K(l){let e=Math.round(l*10);if(e===0)return"0";let i=e<0,t=Math.abs(e),s=Math.floor(t/10),n=t%10,r=n===0?String(s):`${s}.${n}`;return i?`-${r}`:r}function W(l,e=0,i=0,t,s,n=0){if(!Array.isArray(l))return"";let r=l.length,c=n>0&&r>n?r-n:0,a=[],o=[],h=0,_=0;for(let u=c;u<r;u++){let g=l[u];if(!Array.isArray(g)||g.length<2)continue;let k=Number(g[0]),v=Number(g[1]);if(!Number.isFinite(k)||!Number.isFinite(v))continue;let y=k-e,x=v-i;(a.length===0||Math.abs(y-h)>=.75||Math.abs(x-_)>=.75)&&(a.push(y),o.push(x),h=y,_=x)}typeof t=="number"&&typeof s=="number"&&Number.isFinite(t)&&Number.isFinite(s)&&(a.length===0||Math.abs(t-h)>=.75||Math.abs(s-_)>=.75)&&(a.push(t),o.push(s));let b=a.length;if(b<2)return"";let p=new Array(b).fill(!1);if(p[0]=!0,p[b-1]=!0,b>2){let u=[[0,b-1]],g=2.25;for(;u.length>0;){let k=u.pop(),v=k[0],y=k[1];if(y-v<=1)continue;let x=a[v],L=o[v],T=a[y],$=o[y],D=T-x,O=$-L,f=D*D+O*O,d=-1,S=-1;for(let w=v+1;w<y;w++){let I=a[w],F=o[w],H;if(f<=1e-4){let M=I-x,R=F-L;H=M*M+R*R}else{let M=((I-x)*D+(F-L)*O)/f;M<0?M=0:M>1&&(M=1);let R=I-(x+M*D),V=F-(L+M*O);H=R*R+V*V}H>d&&(d=H,S=w)}d>g&&S!==-1&&(p[S]=!0,u.push([v,S]),u.push([S,y]))}}let m=[];for(let u=0;u<b;u++)p[u]&&m.push(`${K(a[u])},${K(o[u])}`);return m.join(";")}function Y(){let l=new Map,e=null;try{if(typeof globalThis!="undefined"&&"localStorage"in globalThis&&globalThis.localStorage){let i="__logludo_storage_probe__";globalThis.localStorage.setItem(i,"1"),globalThis.localStorage.removeItem(i),e=globalThis.localStorage}}catch{e=null}return{getItem(i){if(e)try{let t=e.getItem(i);if(t!==null)return t}catch{}return l.has(i)?l.get(i):null},setItem(i,t){if(l.set(i,t),e)try{e.setItem(i,t)}catch{}},removeItem(i){if(l.delete(i),e)try{e.removeItem(i)}catch{}}}}var j="js-1.0.0",z="https://api.logludo.com/v0",B="__LOGLUDO_INJECT_GAME_ID_HERE__",ne=new Set(["session_start","session_end","error","progression","monetization","gameplay","design","performance"]);function X(l){let e=new Date(l*1e3),i=e.getUTCFullYear(),t=e.getUTCMonth()+1,s=e.getUTCDate();return`${i}-${t}-${s}`}function E(l){if(typeof l!="string")return!1;let e=l.trim();return e.length>0&&!e.includes("INJECT_GAME_ID")}function G(l){if(!l||typeof l!="object")return{};let e={...l};return l.scenelytics&&typeof l.scenelytics=="object"&&(e.scenelytics={...l.scenelytics}),e}function Q(l){if(!l||typeof l=="string")return null;let e=l;return typeof e.x=="number"&&typeof e.y=="number"&&Number.isFinite(e.x)&&Number.isFinite(e.y)?{x:e.x,y:e.y}:e.position&&typeof e.position.x=="number"&&typeof e.position.y=="number"&&Number.isFinite(e.position.x)&&Number.isFinite(e.position.y)?{x:e.position.x,y:e.position.y}:null}var A=class{constructor(e){this.initialized=!1;this.sessionId="";this.deviceId="";this.bucket=1;this.daysSinceInstall=0;this.sessionCount=0;this.activeMask=0;this.firstOpenDate=0;this.installTime=0;this.isFirstSessionToday=!1;this.isDev=!1;this.framework="Vanilla";this._completedFunnelSteps=[];this._completedFunnelDropoffs=[];this._eventBuffer=[];this._bufferRaws=[];this._inFlightBatchCount=0;this._isFlushing=!1;this._flushQueued=!1;this._flushQueuedForce=!1;this._offlineDirty=!1;this._retryAfterTime=0;this._retryBackoffMs=0;this._recentEventHistory=[];this._dedupHistoryLimit=32;this._dedupWarnedAt=-99999;this._frame=0;this._spamTracker=new Map;this._pathCallTracker=new Map;this._rateWarnedAt=-99999;this._eventsThisSecond=0;this._lastEventSecond=0;this._lastFlushTime=0;this._gameIdWarned=!1;this._activeExperiments=[];this._experimentFlags={};this._experimentsLoaded=!1;this._experimentReadyCallbacks=[];this._experimentWarned=new Set;this._expTimeoutHandle=null;this._trackedPaths=new Map;this._targetKeyMap=new WeakMap;this._targetKeySeq=0;this._activeLinks=new Map;this._linkSeq=0;this._aggregates=new Map;this._sessionStartTimeMs=Date.now();this._currentSceneName="main";this._sceneEnterTimeMs=Date.now();this._scenePingSent=!1;this._lastScenePingMs=0;this._sessionEnded=!1;this._fpsSamples=[];this._lastRafTime=0;this._rafId=null;this._flushTimer=null;this._offlineSaveTimer=null;this._cleanupListeners=[];this._explicitFlushInterval=!1;this._storage=Y();let i=typeof window!="undefined"&&typeof document!="undefined";this._options={apiUrl:z,gameId:B,gameVersion:"1.0.0",logLevel:"info",captureCrashes:!0,autoPerformance:!0,performanceDelayMs:1e4,performanceIntervalMs:0,captureHotkeysEnabled:!0,captureRequireModifier:!0,autoFlush:!0,batchLimit:i?4:10,flushIntervalMs:5e3,dedupWindowMs:2e3,defaultExperimentPercentage:50,autoFlushOnSceneChange:!1,storagePrefix:"logludo",anchorX:0,anchorY:0},e&&this._applyOptions(e)}_logRank(e){switch(e){case"silent":return 0;case"errors":return 1;case"info":return 2;case"verbose":return 3;default:return 2}}_log(e,i,...t){!this.isDev&&e!=="errors"||this._logRank(this._options.logLevel)<this._logRank(e)||(e==="errors"?console.error(i,...t):console.log(i,...t))}_storageKey(e){let i=E(this._options.gameId)?this._options.gameId:"default";return`${this._options.storagePrefix}_${e}_${i}`}_applyOptions(e){var c,a,o,h,_;let i=(c=e.gameId)!=null?c:e.game_ID;typeof i=="string"&&i.trim()&&(this._options.gameId=i.trim());let t=(a=e.apiUrl)!=null?a:e.api_url;typeof t=="string"&&t.trim()&&(this._options.apiUrl=t.trim().replace(/\/+$/,""));let s=(o=e.gameVersion)!=null?o:e.appVersion;typeof s=="string"&&s.trim()&&(this._options.gameVersion=s.trim());let n=(h=e.logLevel)!=null?h:e.log_level;n&&(this._options.logLevel=n),typeof e.debug=="boolean"&&(this._options.explicitDebug=e.debug),e.buildType&&(this._options.explicitBuildType=e.buildType),typeof e.framework=="string"&&e.framework.trim()&&(this._options.explicitFramework=e.framework.trim());let r=(_=e.captureCrashes)!=null?_:e.capture_crashes;typeof r=="boolean"&&(this._options.captureCrashes=r),typeof e.autoPerformance=="boolean"&&(this._options.autoPerformance=e.autoPerformance),typeof e.performanceDelayMs=="number"&&(this._options.performanceDelayMs=Math.max(0,e.performanceDelayMs)),typeof e.performanceIntervalMs=="number"&&(this._options.performanceIntervalMs=Math.max(0,e.performanceIntervalMs)),typeof e.captureHotkeysEnabled=="boolean"&&(this._options.captureHotkeysEnabled=e.captureHotkeysEnabled),typeof e.captureRequireModifier=="boolean"&&(this._options.captureRequireModifier=e.captureRequireModifier),e.canvas!==void 0&&(this._options.canvas=e.canvas),typeof e.initialScene=="string"&&e.initialScene.trim()&&(this._currentSceneName=e.initialScene.trim()),typeof e.autoFlush=="boolean"&&(this._options.autoFlush=e.autoFlush),typeof e.batchLimit=="number"&&e.batchLimit>0&&(this._options.batchLimit=Math.floor(e.batchLimit)),typeof e.flushIntervalMs=="number"&&e.flushIntervalMs>=250&&(this._options.flushIntervalMs=Math.floor(e.flushIntervalMs),this._explicitFlushInterval=!0),typeof e.dedupWindowMs=="number"&&e.dedupWindowMs>=0&&(this._options.dedupWindowMs=Math.floor(e.dedupWindowMs)),typeof e.defaultExperimentPercentage=="number"&&(this._options.defaultExperimentPercentage=Math.max(0,Math.min(100,e.defaultExperimentPercentage))),typeof e.autoFlushOnSceneChange=="boolean"&&(this._options.autoFlushOnSceneChange=e.autoFlushOnSceneChange),e.sessionStartPayload&&typeof e.sessionStartPayload=="object"&&(this._options.sessionStartPayload={...e.sessionStartPayload}),typeof e.userId=="string"&&e.userId.trim()&&(this._options.userId=e.userId.trim()),typeof e.storagePrefix=="string"&&e.storagePrefix.trim()&&(this._options.storagePrefix=e.storagePrefix.trim()),typeof e.anchorX=="number"&&Number.isFinite(e.anchorX)&&(this._options.anchorX=e.anchorX),typeof e.anchorY=="number"&&Number.isFinite(e.anchorY)&&(this._options.anchorY=e.anchorY)}configure(e){let i=E(this._options.gameId);if(this._applyOptions(e),this.isDev=N(this._options.explicitDebug,this._options.explicitBuildType),this.framework=U(this._options.explicitFramework),this.initialized&&!i&&E(this._options.gameId)){this._gameIdWarned=!1,this._loadOrCreateDeviceData(Math.floor(Date.now()/1e3));for(let t of this._eventBuffer)E(t.game_id)||(t.game_id=this._options.gameId);this.saveDeviceData(),this.fetchExperiments(),this._eventBuffer.length>0&&this._options.autoFlush&&this.flush(!1)}return this}init(e){if(e&&this._applyOptions(e),this.initialized)return this;this.initialized=!0,this._sessionEnded=!1,this.isDev=N(this._options.explicitDebug,this._options.explicitBuildType),this.framework=U(this._options.explicitFramework),this._explicitFlushInterval||(this._options.flushIntervalMs=this.isDev?2e3:5e3);let i=Date.now(),t=Math.floor(i/1e3);this._sessionStartTimeMs=i,this._sceneEnterTimeMs=i,this._scenePingSent=!1,this._lastScenePingMs=0,this._lastFlushTime=i,this._recentEventHistory=[],this._bufferRaws=[],this._spamTracker.clear(),this._pathCallTracker.clear(),this._retryAfterTime=0,this._retryBackoffMs=0,!(e!=null&&e.initialScene)&&typeof document!="undefined"&&document.title&&(this._currentSceneName=document.title.trim()||"main");let s=Math.floor(Math.random()*1e6);this.sessionId=`sess_${t}_${i%1e5}_${s}`,this._loadOfflineBuffer(),this._loadOrCreateDeviceData(t),!E(this._options.gameId)&&!this._gameIdWarned&&(this._gameIdWarned=!0,this._log("errors",">> LOGLUDO WARNING: gameId is not configured. Pass { gameId: '...' } to LOGLUDO.init(). Telemetry uploads are paused until configured.")),this._loadCachedExperiments(),this.fetchExperiments(),this._flushPendingCrashFromStorage(),this._attachBrowserListeners(),this._startTimers(),this._ensureRafLoop();let n=P();return this.sendEvent("session_start",{app_version:this._options.gameVersion,sdk_version:j,sdk_engine:"JavaScript",framework:this.framework,platform:n.platform,client_type:n.clientType,os_info:n.osInfo,device_model:n.deviceModel,...n.domain?{domain:n.domain}:{},...n.url?{url:n.url}:{},days_since_install:this.daysSinceInstall,test_bucket:this.bucket,session_count:this.sessionCount,active_mask:this.activeMask,first_open_date:this.firstOpenDate,is_first_session_today:this.isFirstSessionToday,scene_name:this._currentSceneName,...this._options.sessionStartPayload||{}}),this}_loadOfflineBuffer(){let e=this._storage.getItem(this._storageKey("offline"));if(e)try{let i=JSON.parse(e);if(Array.isArray(i)){let t=i.length>400?i.slice(i.length-400):i;this._eventBuffer=t.filter(s=>!!(s&&typeof s=="object"&&typeof s.event_name=="string")),this._bufferRaws=new Array(this._eventBuffer.length).fill(""),this._offlineDirty=this._eventBuffer.length>0}}catch{}}_loadOrCreateDeviceData(e){let i=X(e),t=!1;this.installTime=e;let s=this._storage.getItem(this._storageKey("device"));if(s)try{let n=JSON.parse(s);E(this._options.gameId)&&n.game_id&&E(n.game_id)&&n.game_id!==this._options.gameId?t=!0:(typeof n.bucket=="number"&&(this.bucket=n.bucket),typeof n.device_id=="string"&&(this.deviceId=n.device_id),typeof n.install_time=="number"&&(this.installTime=n.install_time),typeof n.session_count=="number"&&(this.sessionCount=n.session_count),typeof n.active_mask=="number"&&(this.activeMask=n.active_mask),typeof n.first_open_date=="number"&&(this.firstOpenDate=n.first_open_date),this._completedFunnelSteps=Array.isArray(n.completed_funnel_steps)?n.completed_funnel_steps.map(String):[],this._completedFunnelDropoffs=Array.isArray(n.completed_funnel_dropoffs)?n.completed_funnel_dropoffs.map(String):[],(!Number.isFinite(this.firstOpenDate)||this.firstOpenDate<1e9)&&(this.firstOpenDate=e),this.isFirstSessionToday=n.last_session_date!==i)}catch{t=!0}else t=!0;t?(this.bucket=Math.floor(Math.random()*10)+1,this.firstOpenDate=e,this.deviceId=this._generateDeviceId(e),this.sessionCount=0,this.activeMask=0,this.installTime=e,this.isFirstSessionToday=!0,this._completedFunnelSteps=[],this._completedFunnelDropoffs=[]):this.deviceId||(this.deviceId=this._generateDeviceId(this.firstOpenDate||e)),this.sessionCount+=1,this.daysSinceInstall=Math.max(0,Math.floor((e-this.firstOpenDate)/86400)),this.daysSinceInstall<=30&&(this.activeMask=this.activeMask|1<<this.daysSinceInstall),this.saveDeviceData()}_generateDeviceId(e){let i=typeof globalThis!="undefined"?globalThis.crypto:void 0;if(i&&typeof i.randomUUID=="function")return`dev_${e}_${i.randomUUID().slice(0,12)}`;let t=Math.floor(1e5+Math.random()*9e5),s=Math.floor(Math.random()*1e6);return`dev_${e}_${t}_${s}`}saveDeviceData(){let e=X(Math.floor(Date.now()/1e3)),i={game_id:this._options.gameId,bucket:this.bucket,device_id:this.deviceId,install_time:this.installTime,session_count:this.sessionCount,active_mask:this.activeMask,first_open_date:this.firstOpenDate,last_session_date:e,completed_funnel_steps:this._completedFunnelSteps,completed_funnel_dropoffs:this._completedFunnelDropoffs};this._storage.setItem(this._storageKey("device"),JSON.stringify(i))}saveOffline(){this._offlineDirty&&(this._storage.setItem(this._storageKey("offline"),JSON.stringify(this._eventBuffer)),this._offlineDirty=!1)}_loadCachedExperiments(){let e=this._storage.getItem(this._storageKey("experiments"));if(e)try{let i=JSON.parse(e);i&&typeof i=="object"&&(Array.isArray(i.experiments)&&(this._activeExperiments=i.experiments.map(String)),i.flags&&typeof i.flags=="object"&&(this._experimentFlags={...i.flags}),this._experimentsLoaded=!0)}catch{}}_flushPendingCrashFromStorage(){let e=this._storage.getItem(this._storageKey("crash"));if(e){try{let i=JSON.parse(e);this.sendEvent("error",i)}catch{}this._storage.removeItem(this._storageKey("crash"))}}_attachBrowserListeners(){if(typeof window=="undefined"||typeof document=="undefined")return;this._detachListeners();let e=a=>{if(!this._options.captureCrashes)return;let o=a.error instanceof Error?a.error:void 0,h=a.message||(o==null?void 0:o.message)||"Uncaught error",_=(o==null?void 0:o.stack)||(a.filename?`at ${a.filename}:${a.lineno||0}:${a.colno||0}`:"");this.handleException({message:h,stack:_},{action:"fatal_crash",severity:"fatal_crash"})},i=a=>{if(!this._options.captureCrashes)return;let o=a.reason,h=o instanceof Error?o.message:typeof o=="string"?o:JSON.stringify(o||"Unhandled promise rejection"),_=o instanceof Error&&o.stack||"";this.handleException({message:h,stack:_},{action:"unhandled_exception",severity:"unhandled_exception"})},t=()=>{document.visibilityState==="hidden"&&(this.saveOffline(),this.flush(!1,!0))},s=()=>{this._endSession("page_hide")},n=()=>{this._endSession("normal_quit")},r=a=>{a.persisted&&this._sessionEnded&&(this._sessionEnded=!1,this._sessionStartTimeMs=Date.now(),this._sceneEnterTimeMs=Date.now())},c=a=>{!this.isDev||!this._options.captureHotkeysEnabled||a.key!=="F9"||!(!this._options.captureRequireModifier||(a.ctrlKey||a.metaKey)&&a.shiftKey)||(a.preventDefault(),this.captureScene())};window.addEventListener("error",e),window.addEventListener("unhandledrejection",i),document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",s),window.addEventListener("beforeunload",n),window.addEventListener("pageshow",r),window.addEventListener("keydown",c),this._cleanupListeners.push(()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",i),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",s),window.removeEventListener("beforeunload",n),window.removeEventListener("pageshow",r),window.removeEventListener("keydown",c)})}_detachListeners(){for(let e of this._cleanupListeners)try{e()}catch{}this._cleanupListeners=[]}_startTimers(){var e,i;this._stopTimers(),typeof setInterval!="undefined"&&(this._options.autoFlush&&(this._flushTimer=setInterval(()=>{Date.now()-this._lastFlushTime>=this._options.flushIntervalMs&&this._eventBuffer.length>0&&!this._isFlushing&&this.flush(!1)},Math.min(2e3,this._options.flushIntervalMs)),typeof((e=this._flushTimer)==null?void 0:e.unref)=="function"&&this._flushTimer.unref()),this._offlineSaveTimer=setInterval(()=>{this.saveOffline()},5e3),typeof((i=this._offlineSaveTimer)==null?void 0:i.unref)=="function"&&this._offlineSaveTimer.unref())}_stopTimers(){this._flushTimer!==null&&(clearInterval(this._flushTimer),this._flushTimer=null),this._offlineSaveTimer!==null&&(clearInterval(this._offlineSaveTimer),this._offlineSaveTimer=null),this._expTimeoutHandle!==null&&(clearTimeout(this._expTimeoutHandle),this._expTimeoutHandle=null)}_ensureRafLoop(){if(this._rafId!==null||typeof globalThis=="undefined"||typeof globalThis.requestAnimationFrame!="function"||!this._options.autoPerformance&&this._trackedPaths.size===0)return;this._lastRafTime=typeof performance!="undefined"?performance.now():Date.now();let e=i=>{if(!this.initialized){this._rafId=null;return}if(this._frame+=1,this._options.autoPerformance){let t=i-this._lastRafTime;if(this._lastRafTime=i,t>0&&t<1e3){let r=Math.min(240,1e3/t);this._fpsSamples.push(r),this._fpsSamples.length>300&&this._fpsSamples.shift()}let s=Date.now(),n=s-this._sceneEnterTimeMs;!this._scenePingSent&&n>=this._options.performanceDelayMs?(this._emitPerformancePing(s),this._scenePingSent=!0,this._lastScenePingMs=s):this._scenePingSent&&this._options.performanceIntervalMs>0&&s-this._lastScenePingMs>=this._options.performanceIntervalMs&&(this._emitPerformancePing(s),this._lastScenePingMs=s)}if(this._trackedPaths.size>0)for(let t of this._trackedPaths.values()){let s=Q(t.target);if(!s)continue;let n=Math.round(s.x*100)/100,r=Math.round(s.y*100)/100;(t.lastX===void 0||t.lastY===void 0||Math.abs(n-t.lastX)>=.75||Math.abs(r-t.lastY)>=.75)&&(t.lastX=n,t.lastY=r,t.path.push([n,r]),t.path.length>=t.maxLen*2&&t.path.splice(0,t.path.length-t.maxLen))}this._options.autoPerformance||this._trackedPaths.size>0?this._rafId=globalThis.requestAnimationFrame(e):this._rafId=null};this._rafId=globalThis.requestAnimationFrame(e)}_emitPerformancePing(e){var a;let i=this._fpsSamples,t=60,s=60,n=60;if(i.length>0){let o=0;s=1/0,n=-1/0;for(let h of i)o+=h,h<s&&(s=h),h>n&&(n=h);t=Math.round(o/i.length*10)/10,s=Math.round(s),n=Math.round(n),this._fpsSamples=[]}let r={action:"ping",average_fps:t,min_fps:s,max_fps:n,current_scene:this._currentSceneName,scene_name:this._currentSceneName},c=typeof performance!="undefined"?performance:void 0;(a=c==null?void 0:c.memory)!=null&&a.usedJSHeapSize&&(r.memory_mb=Math.round(c.memory.usedJSHeapSize/(1024*1024)*10)/10),this._lastFlushTime=Math.min(this._lastFlushTime,e),this.sendEvent("performance",r)}enterScene(e){this.initialized||this.init();let i=typeof e=="string"?e.trim():"";if(!i||i===this._currentSceneName)return this;let t=Date.now(),s=Math.max(0,Math.round((t-this._sceneEnterTimeMs)/100)/10);return this._currentSceneName&&s>=.2&&this.sendEvent("gameplay",{action:"scene_exit",room_name:this._currentSceneName,scene_name:this._currentSceneName,next_scene:i,duration_seconds:s,is_session_exit:!1}),this._currentSceneName=i,this._sceneEnterTimeMs=t,this._scenePingSent=!1,this._lastScenePingMs=0,this._activeLinks.clear(),this._options.autoFlushOnSceneChange&&this.flush(!1),this}enter_scene(e){return this.enterScene(e)}setScene(e){return this.enterScene(e)}set_scene(e){return this.enterScene(e)}identify(e,i){return this.initialized||this.init(),typeof e=="string"&&e.trim()&&(this._options.userId=e.trim()),i&&typeof i=="object"&&(this._userTraits={...this._userTraits||{},...i}),this}isExperimentsReady(){return this.initialized||this.init(),this._experimentsLoaded}is_experiments_ready(){return this.isExperimentsReady()}_hashExperimentBucket(e){let t=`${this.deviceId||String(this.firstOpenDate)}:${e}`,s=0;for(let n=0;n<t.length;n++)s=s*31+t.charCodeAt(n)|0;return Math.abs(s)%100}_flushExperimentCallbacks(){if(this._expTimeoutHandle!==null&&(clearTimeout(this._expTimeoutHandle),this._expTimeoutHandle=null),this._experimentReadyCallbacks.length===0)return;let e=this._experimentReadyCallbacks;this._experimentReadyCallbacks=[];for(let i of e)try{i()}catch(t){this._log("errors",">> LOGLUDO ERROR in whenExperimentsReady callback:",t)}}whenExperimentsReady(e,i=500){if(typeof e=="function"){if(this.initialized||this.init(),this._experimentsLoaded){e();return}this._experimentReadyCallbacks.push(e),i>0&&this._expTimeoutHandle===null&&(this._expTimeoutHandle=setTimeout(()=>{this._flushExperimentCallbacks()},Math.max(50,i)))}}when_experiments_ready(e,i=500){this.whenExperimentsReady(e,i)}experiment(e,i,t){if(this.initialized||this.init(),Object.prototype.hasOwnProperty.call(this._experimentFlags,e))return!!this._experimentFlags[e];if(this._activeExperiments.includes(e))return!0;let s=typeof i=="boolean"?i:!1,n;if(typeof t=="number"&&Number.isFinite(t)?n=Math.max(0,Math.min(100,t)):typeof i=="number"&&Number.isFinite(i)?n=Math.max(0,Math.min(100,i)):i===void 0&&(n=Math.max(0,Math.min(100,this._options.defaultExperimentPercentage))),!this._experimentsLoaded&&n!==void 0){let r=this._hashExperimentBucket(e),c=n>=100?!0:n<=0?!1:r<n;return this._experimentFlags[e]=c,c&&!this._activeExperiments.includes(e)&&this._activeExperiments.push(e),this.isDev&&!this._experimentWarned.has(e)&&(this._experimentWarned.add(e),this._log("info",`>> LOGLUDO: experiment("${e}") assigned locally at ${n}% default (${c?"experiment/true":"control/false"}) while awaiting server flags.`)),c}return!this._experimentsLoaded&&this.isDev&&!this._experimentWarned.has(e)&&(this._experimentWarned.add(e),this._log("info",`>> LOGLUDO WARNING: experiment("${e}") called before server experiments loaded; returning default (${s}).`)),s}async fetchExperiments(){if(!E(this._options.gameId)){this._experimentsLoaded=!0,this._flushExperimentCallbacks();return}let e=this.deviceId||String(this.firstOpenDate),i=`${this._options.apiUrl}/experiments?game_id=${encodeURIComponent(this._options.gameId)}&bucket=${encodeURIComponent(String(this.bucket))}&device_id=${encodeURIComponent(e)}`;try{if(typeof fetch!="function"){this._experimentsLoaded=!0,this._flushExperimentCallbacks();return}let t=await fetch(i,{method:"GET"});if(t.ok){let s=await t.text(),n=JSON.parse(s);n&&n.success&&(Array.isArray(n.experiments)&&(this._activeExperiments=n.experiments.map(String)),n.flags&&typeof n.flags=="object"&&(this._experimentFlags={...n.flags}),this._retroactivelyTagBufferedExperiments(),this._storage.setItem(this._storageKey("experiments"),s),this._log("info",`>> LOGLUDO: Experiments loaded (${this._activeExperiments.length} active)`))}}catch(t){this._log("info",">> LOGLUDO: Failed to fetch experiments:",t)}finally{this._experimentsLoaded=!0,this._flushExperimentCallbacks()}}_retroactivelyTagBufferedExperiments(){let e=this._activeExperiments.length>0,i=Object.keys(this._experimentFlags).length>0;if(!(!e&&!i))for(let t of this._eventBuffer)t.payload&&(e&&!("experiments"in t.payload)&&(t.payload.experiments=[...this._activeExperiments]),i&&!("experiment_flags"in t.payload)&&(t.payload.experiment_flags={...this._experimentFlags}))}_attachExperimentContext(e){this._activeExperiments.length>0&&!("experiments"in e)&&(e.experiments=[...this._activeExperiments]),Object.keys(this._experimentFlags).length>0&&!("experiment_flags"in e)&&(e.experiment_flags={...this._experimentFlags})}_resolveTrackKey(e){if(typeof e=="string")return`s:${e}`;if(e&&typeof e=="object"){if("id"in e&&e.id!==void 0&&e.id!==null)return`id:${String(e.id)}`;let i=this._targetKeyMap.get(e);return i||(this._targetKeySeq+=1,i=`obj_${this._targetKeySeq}`,this._targetKeyMap.set(e,i)),i}return"default"}trackPath(e,i=60){if(this.initialized||this.init(),!e)return this;let t=this._resolveTrackKey(e);if(this._trackedPaths.has(t)){let s=this._trackedPaths.get(t);s.maxLen=Math.max(2,i),s.target=e;let n=this._pathCallTracker.get(t);if(n){let r=this._frame-n.lastFrame;r>=1&&r<=2?n.consec+=1:r>2&&(n.consec=1),n.lastFrame=this._frame,n.consec>=4&&Date.now()-n.warnedAt>=1e4&&(n.warnedAt=Date.now(),this._log("errors",">> LOGLUDO WARNING: LOGLUDO.trackPath() is being called every frame (likely in update()). Call it once in create/init instead."))}else this._pathCallTracker.set(t,{lastFrame:this._frame,consec:1,warnedAt:-99999});return this}return this._trackedPaths.set(t,{key:t,target:e,path:[],maxLen:Math.max(2,i)}),this._ensureRafLoop(),this}track_path(e,i=60){return this.trackPath(e,i)}samplePath(e,i,t){if(this.initialized||this.init(),!Number.isFinite(i)||!Number.isFinite(t))return this;let s=this._resolveTrackKey(e),n=this._trackedPaths.get(s);n||(n={key:s,target:e,path:[],maxLen:60},this._trackedPaths.set(s,n));let r=Math.round(i*100)/100,c=Math.round(t*100)/100;return(n.lastX===void 0||n.lastY===void 0||Math.abs(r-n.lastX)>=.75||Math.abs(c-n.lastY)>=.75)&&(n.lastX=r,n.lastY=c,n.path.push([r,c]),n.path.length>=n.maxLen*2&&n.path.splice(0,n.path.length-n.maxLen)),this}sample_path(e,i,t){return this.samplePath(e,i,t)}stopTrackingPath(e){let i=this._resolveTrackKey(e);return this._trackedPaths.delete(i),this._pathCallTracker.delete(i),this}stop_tracking_path(e){return this.stopTrackingPath(e)}startLink(e="default"){this._linkSeq+=1;let i=String(e||"default"),s=`${i==="default"?"l":i}_${this._linkSeq}`;return this._activeLinks.set(i,s),s}start_link(e="default"){return this.startLink(e)}getLink(e="default"){return this._activeLinks.get(String(e||"default"))}get_link(e="default"){return this.getLink(e)}clearLink(e="default"){this._activeLinks.delete(String(e||"default"))}clear_link(e="default"){this.clearLink(e)}_formatAggregate(e){var i,t;if(e.type==="sum")return(i=e.value)!=null?i:0;if(e.type==="average")return e.count&&e.count>0?((t=e.sum)!=null?t:0)/e.count:0;if(e.type==="frequency"){let s=[];for(let[n,r]of(e.map||new Map).entries())s.push({item:n,count:r});return s.sort((n,r)=>r.count-n.count),s.slice(0,10)}}aggregateAdd(e,i,t="sum"){var n,r,c,a;let s=this._aggregates.get(e);if(s||(s={type:t},t==="sum"?s.value=0:t==="average"?(s.sum=0,s.count=0):t==="frequency"&&(s.map=new Map),this._aggregates.set(e,s)),s.type==="sum"){let o=Number(i);Number.isFinite(o)&&(s.value=((n=s.value)!=null?n:0)+o)}else if(s.type==="average"){let o=Number(i);Number.isFinite(o)&&(s.sum=((r=s.sum)!=null?r:0)+o,s.count=((c=s.count)!=null?c:0)+1)}else if(s.type==="frequency"){let o=String(i);s.map=s.map||new Map,s.map.set(o,((a=s.map.get(o))!=null?a:0)+1)}return this}aggregate_add(e,i,t="sum"){return this.aggregateAdd(e,i,t)}aggregatePop(e){let i=this._aggregates.get(e);if(!i)return;let t=this._formatAggregate(i);return this._aggregates.delete(e),t}aggregate_pop(e){return this.aggregatePop(e)}aggregateGetAll(e=!1){let i={};for(let[t,s]of this._aggregates.entries()){let n=this._formatAggregate(s);n!==void 0&&(i[t]=n)}return e&&this._aggregates.clear(),i}aggregate_get_all(e=!1){return this.aggregateGetAll(e)}funnelStep(e,i={}){if(this.initialized||this.init(),!e||typeof e!="string")return!1;let t=e.trim().toLowerCase();if(!t||this._completedFunnelSteps.includes(t))return!1;let s=[...this._completedFunnelSteps];this._completedFunnelSteps.push(t),this.saveDeviceData();let n=G(i);return n.action="funnel_step",n.step_id=e,n.step_name=e,n.funnel_once=!0,"prior_steps"in n||(n.prior_steps=s),this.sendEvent("progression",n)}funnel_step(e,i={}){return this.funnelStep(e,i)}funnelDropoff(e,i="abandoned",t={}){if(this.initialized||this.init(),!e||typeof e!="string")return!1;let s=e.trim().toLowerCase();if(!s||this._completedFunnelSteps.includes(s)||this._completedFunnelDropoffs.includes(s))return!1;this._completedFunnelDropoffs.push(s),this.saveDeviceData();let n=G(t);return n.action="dropoff",n.step_id=e,n.step_name=e,n.dropoff_reason=i,n.funnel_once=!0,this.sendEvent("progression",n)}funnel_dropoff(e,i="abandoned",t={}){return this.funnelDropoff(e,i,t)}_purgeUnflushedSpam(e,i){var s;let t=this._isFlushing?this._inFlightBatchCount:0;for(let n=this._eventBuffer.length-1;n>=t;n--){let r=this._eventBuffer[n];r.event_name===e&&(typeof((s=r.payload)==null?void 0:s.action)=="string"?r.payload.action:"")===i&&(this._eventBuffer.splice(n,1),n<this._bufferRaws.length&&this._bufferRaws.splice(n,1),this._offlineDirty=!0)}}_checkStepSpam(e,i,t){if(t)return!1;let s=Date.now();if(this._spamTracker.size>64)for(let[a,o]of this._spamTracker.entries())s-o.winStart>1e4&&s>=o.blockedUntil&&this._spamTracker.delete(a);let n=`${e}|${i}`,r=this._spamTracker.get(n);if(r){if(this._frame>0){let a=this._frame-r.lastFrame;a>=1&&a<=2?r.consecFrames+=1:a>2&&(r.consecFrames=1),r.lastFrame=this._frame}s-r.winStart>=1e3?(r.winStart=s,r.winCount=1):r.winCount+=1}else r={lastFrame:this._frame,consecFrames:1,winStart:s,winCount:1,warnedAt:-99999,blockedUntil:0},this._spamTracker.set(n,r);if(r.consecFrames>=4||r.winCount>12&&(this._frame===0||r.consecFrames>=3)||s<r.blockedUntil){if(r.blockedUntil=s+2e3,this._purgeUnflushedSpam(e,i),s-r.warnedAt>=1e4){r.warnedAt=s;let a=i?`${e} / ${i}`:e;this._log("errors",`>> LOGLUDO WARNING: Event '${a}' is being called repeatedly in a loop (likely inside update/requestAnimationFrame). Blocked to prevent spam. Move it out of the loop or use LOGLUDO.aggregateAdd().`)}return!0}return!1}sendEvent(e,i={}){var L,T,$,D,O;this.initialized||this.init(),ne.has(e)||this._log("errors",`>> LOGLUDO WARNING: Unknown event category "${e}". Allowed categories: session_start, session_end, error, progression, monetization, gameplay, design, performance.`);let t=G(i),s=typeof t.action=="string"?t.action:"",n=!!t.funnel_once,r=e==="session_start"||e==="session_end",c=r||e==="error"||e==="monetization"||n;if(this._checkStepSpam(e,s,r||n))return!1;let a=Date.now(),o=Math.floor(a/1e3);if(o!==this._lastEventSecond&&(this._lastEventSecond=o,this._eventsThisSecond=0),this._eventsThisSecond+=1,this._eventsThisSecond>20&&!c)return a-this._rateWarnedAt>=5e3&&(this._rateWarnedAt=a,this._log("errors",`>> LOGLUDO WARNING: Event rate limit (>20/sec) exceeded while logging '${e}'. Dropping excess events.`)),!1;if(this._eventBuffer.length>=(c?400:150))return!1;let h=t.scenelytics,_=($=(T=(L=t.track_id)!=null?L:t.trackId)!=null?T:h==null?void 0:h.track_id)!=null?$:h==null?void 0:h.trackId;("x"in t||"y"in t||"endX"in t||"endY"in t||_!==void 0)&&!t.scenelytics&&(t.scenelytics={});let p=this._options.anchorX,m=this._options.anchorY;if(t.scenelytics&&typeof t.scenelytics=="object"){let f=t.scenelytics;for(let d of["x","y","endX","endY"])d in t&&(f[d]=t[d],delete t[d]);if("link_id"in t||"linkId"in t?(f.link_id=(D=t.link_id)!=null?D:t.linkId,delete t.link_id,delete t.linkId):"linkId"in f&&!("link_id"in f)&&(f.link_id=f.linkId),delete f.linkId,"link_scope"in t||"linkScope"in t?("link_scope"in f||(f.link_scope=(O=t.link_scope)!=null?O:t.linkScope),delete t.link_scope,delete t.linkScope):"linkScope"in f&&!("link_scope"in f)&&(f.link_scope=f.linkScope),delete f.linkScope,typeof f.link_scope=="string"){let d=this.getLink(f.link_scope);d&&!f.link_id&&(f.link_id=d),delete f.link_scope}if("link_id"in f&&(f.link_id?f.link_id=String(f.link_id):delete f.link_id),_!==void 0){let d=Q(_);if(d)f.x===void 0&&(f.x=d.x),f.y===void 0&&(f.y=d.y);else{let S=this._resolveTrackKey(_),w=this._trackedPaths.get(S);if(w&&w.path.length>0){let I=w.path[w.path.length-1];f.x===void 0&&(f.x=I[0]),f.y===void 0&&(f.y=I[1])}}delete t.track_id,delete t.trackId,delete f.track_id,delete f.trackId}for(let d of["x","y","endX","endY"])if(typeof f[d]=="number"&&Number.isFinite(f[d])){let S=d==="x"||d==="endX"?p:m;f[d]=Math.round((f[d]-S)*100)/100}!("room_name"in t)&&!("scene_name"in t)?(t.room_name=this._currentSceneName,t.scene_name=this._currentSceneName):!("room_name"in t)&&typeof t.scene_name=="string"&&(t.room_name=t.scene_name)}t.build_type=this.isDev?"run":"build","sdk_version"in t||(t.sdk_version=j),"sdk_engine"in t||(t.sdk_engine="JavaScript"),this._options.userId&&!("user_id"in t)&&(t.user_id=this._options.userId,this._userTraits&&Object.assign(t,this._userTraits));let u=P();u.domain&&!("domain"in t)&&(t.domain=u.domain),u.url&&!("url"in t)&&(t.url=u.url),this._attachExperimentContext(t);let g=JSON.stringify(t),k=Math.max(0,Math.min(this._eventBuffer.length,this._bufferRaws.length)-20);for(let f=Math.min(this._eventBuffer.length,this._bufferRaws.length)-1;f>=k;f--)if(this._bufferRaws[f]===g&&this._eventBuffer[f].event_name===e)return!1;let v=`${e}|${g}`;for(let f=this._recentEventHistory.length-1;f>=0;f--){let d=this._recentEventHistory[f];if(a-d.time>=this._options.dedupWindowMs)this._recentEventHistory.splice(f,1);else if(d.key===v)return d.time=a,this.isDev&&a-this._dedupWarnedAt>=2e3&&(this._dedupWarnedAt=a,this._log("info",`>> LOGLUDO: Suppressed duplicate event '${e}' within ${this._options.dedupWindowMs}ms dedup window.`)),!1}if(this._recentEventHistory.push({key:v,time:a}),this._recentEventHistory.length>this._dedupHistoryLimit&&this._recentEventHistory.shift(),t.scenelytics&&typeof t.scenelytics=="object"&&_!==void 0){let f=t.scenelytics,d=this._resolveTrackKey(_),S=this._trackedPaths.get(d);if(S){let w=typeof f.x=="number"?f.x:void 0,I=typeof f.y=="number"?f.y:void 0,F=W(S.path,p,m,w,I,S.maxLen);F&&(f.recent_path=F)}}this._eventBuffer.push({game_id:this._options.gameId,game_version:this._options.gameVersion,session_id:this.sessionId,event_name:e,payload:t}),this._bufferRaws.push(g),this._offlineDirty=!0;let y=typeof window!="undefined";return this._options.autoFlush&&(this.isDev||y&&c||this._eventBuffer.length>=this._options.batchLimit)&&!this._isFlushing&&a>=this._retryAfterTime&&this.flush(!1),!0}send_event(e,i={}){return this.sendEvent(e,i)}async flush(e=!1,i=!1){if(this.initialized||this.init(),!E(this._options.gameId))return this._gameIdWarned||(this._gameIdWarned=!0,this._log("errors",">> LOGLUDO WARNING: Skipping flush because gameId is not configured.")),!1;if(this._eventBuffer.length===0)return!0;if(this._isFlushing)return this._flushQueued=!0,e&&(this._flushQueuedForce=!0),!1;let t=Date.now();if(!e&&t<this._retryAfterTime)return!1;this._flushQueued=!1,this._flushQueuedForce=!1,this._lastFlushTime=t;let s=Math.min(this._eventBuffer.length,50),n=this._eventBuffer.slice(0,s);this._inFlightBatchCount=s,this._isFlushing=!0;let r=JSON.stringify(n);this._log("verbose",">> LOGLUDO PACKET OUTBOUND:",r);try{if(typeof fetch!="function")return this._isFlushing=!1,this._inFlightBatchCount=0,!1;let c=await fetch(this._options.apiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:i});return c.ok?(this._log("info",`>> LOGLUDO: Batch Accepted! (${c.status})`),this._clearPending(s),!0):(this._log("errors",`>> LOGLUDO ERROR: ${c.status} ${c.statusText}`),c.status>=400&&c.status<500&&c.status!==429?(this._log("errors",`>> LOGLUDO: Permanent 4xx client error (${c.status}). Discarding rejected batch to prevent retry storm.`),this._clearPending(s),!1):(this._markFlushFailed(),!1))}catch(c){if(i&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{if(navigator.sendBeacon(this._options.apiUrl,new Blob([r],{type:"application/json"})))return this._clearPending(s),!0}catch{}return this._log("errors",">> LOGLUDO NETWORK ERROR:",c),this._markFlushFailed(),!1}}flushEvents(e=!1){return this.flush(e)}flush_events(e=!1){return this.flush(e)}_markFlushFailed(){this._isFlushing=!1,this._inFlightBatchCount=0,this._retryBackoffMs=this._retryBackoffMs<=0?2e3:Math.min(this._retryBackoffMs*2,3e4),this._retryAfterTime=Date.now()+this._retryBackoffMs,this.saveOffline()}_clearPending(e){let i=Math.min(e,this._eventBuffer.length);if(i>0&&(this._eventBuffer.splice(0,i),this._bufferRaws.splice(0,Math.min(i,this._bufferRaws.length)),this._offlineDirty=!0),this._inFlightBatchCount=0,this._isFlushing=!1,this._retryAfterTime=0,this._retryBackoffMs=0,this.saveOffline(),this._flushQueued||this._eventBuffer.length>=this._options.batchLimit){let t=this._flushQueuedForce;this._flushQueued=!1,this._flushQueuedForce=!1,this.flush(t)}}handleException(e,i={}){this.initialized||this.init();let t=(e instanceof Error,e),s=t&&typeof t.message=="string"&&t.message||(typeof e=="string"?e:"Unhandled exception"),n=t&&typeof t.stack=="string"&&t.stack||"",r=P(),c=i.currentScene||this._currentSceneName,a={action:i.action||"fatal_crash",severity:i.severity||"fatal_crash",message:s,error_message:s,stack_trace:n,current_scene:c,room_name:c,device_model:r.deviceModel,os_info:r.osInfo};this._options.captureCrashes&&this._storage.setItem(this._storageKey("crash"),JSON.stringify(a)),this.sendEvent("error",a),this._options.autoFlush&&this.flush(!0,!0)}handle_exception(e,i){this.handleException(e,i)}_endSession(e){if(!this.initialized||this._sessionEnded)return;this._sessionEnded=!0;let i=Date.now(),t=Math.max(0,Math.round((i-this._sceneEnterTimeMs)/100)/10);this._currentSceneName&&this.sendEvent("gameplay",{action:"scene_exit",room_name:this._currentSceneName,scene_name:this._currentSceneName,next_scene:"",duration_seconds:t,is_session_exit:!0,exit_state:e});let s={duration_seconds:Math.max(0,Math.round((i-this._sessionStartTimeMs)/1e3)),exit_state:e,last_scene:this._currentSceneName||"main"},n=this.aggregateGetAll(!0);for(let[r,c]of Object.entries(n))s[r]=c;if(this.sendEvent("session_end",s),this.saveOffline(),E(this._options.gameId)&&this._eventBuffer.length>0&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function"){let r=this._eventBuffer.slice(0,50);if(navigator.sendBeacon(this._options.apiUrl,new Blob([JSON.stringify(r)],{type:"application/json"}))){this._eventBuffer.splice(0,r.length),this._bufferRaws.splice(0,Math.min(r.length,this._bufferRaws.length)),this._offlineDirty=!0,this.saveOffline();return}}this.flush(!0,!0)}async captureScene(e,i){var c;if(this.initialized||this.init(),!E(this._options.gameId))return this._log("errors",">> LOGLUDO: Cannot capture scene before gameId is configured."),!1;let t=typeof e=="string"?{...i||{},sceneName:e}:e||i||{},s=(t.sceneName||this._currentSceneName||"main").trim(),n=q((c=t.canvas)!=null?c:this._options.canvas);if(!n)return this._log("errors",">> LOGLUDO: No <canvas> element found for SceneLytics capture."),!1;let r=async()=>{try{let a=await J({canvas:n,apiUrl:this._options.apiUrl,gameId:this._options.gameId,gameVersion:this._options.gameVersion,sceneName:s,tileSize:t.tileSize});return a&&this._log("info",`>> LOGLUDO: SceneLytics capture uploaded for '${s}'.`),a}catch(a){return this._log("errors",">> LOGLUDO ERROR (Capture):",a),!1}};return t.waitForRender!==!1&&typeof globalThis.requestAnimationFrame=="function"?new Promise(a=>{globalThis.requestAnimationFrame(()=>{r().then(a)})}):r()}capture_room(e,i){return this.captureScene(e,i)}attachPhaser(e,i={}){var _,b;if(!e||typeof e!="object")return()=>{};this.framework="Phaser",this._options.explicitFramework="Phaser";let t=i.gameVersion||((_=e.config)==null?void 0:_.gameVersion)||void 0;this.initialized?e.canvas&&!this._options.canvas&&(this._options.canvas=e.canvas):this.init({...t?{gameVersion:String(t)}:{},framework:"Phaser",...e.canvas?{canvas:e.canvas}:{}});let s=i.trackScenes!==!1,n=new Set,r=[],c=p=>{var g,k;if(!p||!p.sys||!p.sys.settings)return;let m=String(p.sys.settings.key||"main");if(!s||n.has(m))return;n.add(m);let u=p.sys.events;if(u&&typeof u.on=="function"){let v=()=>{this.enterScene(m)},y=()=>{this.enterScene(m)};u.on("start",v),u.on("wake",y),r.push(()=>{typeof u.off=="function"&&(u.off("start",v),u.off("wake",y))})}i.autoStartInitialScene!==!1&&((k=(g=p.sys).isActive)!=null&&k.call(g))&&this.enterScene(m)},a=e.scene;if(a&&Array.isArray(a.scenes))for(let p of a.scenes)c(p);let o=e.events;if(o&&typeof o.on=="function"){let p=()=>{if(a&&Array.isArray(a.scenes))for(let g of a.scenes)c(g)},m=()=>{e.canvas&&(this._options.canvas=e.canvas),p()},u=()=>{h()};o.on("ready",m),o.on("step",p),(b=o.once)==null||b.call(o,"destroy",u),r.push(()=>{typeof o.off=="function"&&(o.off("ready",m),o.off("step",p),o.off("destroy",u))})}let h=()=>{for(let p of r)try{p()}catch{}};return h}attach_phaser(e,i={}){return this.attachPhaser(e,i)}getQueuedEventCount(){return this._eventBuffer.length}getFlushIntervalMs(){return this._options.flushIntervalMs}destroy(){this.initialized&&this._endSession("normal_quit"),this._stopTimers(),this._detachListeners(),this._rafId!==null&&typeof globalThis!="undefined"&&typeof globalThis.cancelAnimationFrame=="function"&&(globalThis.cancelAnimationFrame(this._rafId),this._rafId=null),this.initialized=!1}},Z=new A;var C=Z;if(typeof globalThis!="undefined"){let l=globalThis;if(l.LOGLUDO=C,l.LogLudo=C,l.LogLudoClient=A,l.LogLudoSDK={LOGLUDO:C,LogLudoClient:A,SDK_VERSION:j,DEFAULT_API_URL:z,minifyPath:W,formatCoord:K,detectDevMode:N,detectEnvironment:P,detectFramework:U},typeof B=="string"&&B.length>0&&!B.includes("INJECT_GAME_ID")&&!l.LOGLUDO_MANUAL_INIT&&typeof document!="undefined"){let i=()=>{C.initialized||C.init()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",i,{once:!0}):i()}}var _e=C;})();
package/dist/path.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Formats a coordinate rounded to 1 decimal place without trailing `.0`.
3
+ */
4
+ export declare function formatCoord(val: number): string;
5
+ /**
6
+ * Offsets coordinates by anchor `(ax, ay)`, deduplicates stationary points (<0.75px),
7
+ * simplifies collinear segments using iterative Ramer-Douglas-Peucker (1.5px tolerance),
8
+ * and encodes into `"x0,y0;x1,y1;..."` compact format compatible with LogLudo SceneLytics.
9
+ */
10
+ export declare function minifyPath(rawPath: ReadonlyArray<readonly [number, number]>, ax?: number, ay?: number, curX?: number, curY?: number, maxPoints?: number): string;
@@ -0,0 +1,10 @@
1
+ export interface KeyValueStore {
2
+ getItem(key: string): string | null;
3
+ setItem(key: string, value: string): void;
4
+ removeItem(key: string): void;
5
+ }
6
+ /**
7
+ * Creates a resilient storage adapter backed by `window.localStorage` when available,
8
+ * transparently falling back to an isolated in-memory Map in Node/SSR/sandboxed environments.
9
+ */
10
+ export declare function createSafeStorage(): KeyValueStore;
@@ -0,0 +1,145 @@
1
+ export type LogLevel = "silent" | "errors" | "info" | "verbose";
2
+ export type EventCategory = "session_start" | "session_end" | "error" | "progression" | "monetization" | "gameplay" | "design" | "performance";
3
+ export type AggregateType = "sum" | "average" | "frequency";
4
+ export interface ScenelyticsPayload {
5
+ x?: number;
6
+ y?: number;
7
+ endX?: number;
8
+ endY?: number;
9
+ direction?: number;
10
+ angle?: number;
11
+ color?: string;
12
+ shape?: string;
13
+ type?: string;
14
+ pointType?: string;
15
+ track_id?: TrackTarget;
16
+ trackId?: TrackTarget;
17
+ link_id?: string;
18
+ linkId?: string;
19
+ link_scope?: string;
20
+ linkScope?: string;
21
+ recent_path?: string;
22
+ [key: string]: unknown;
23
+ }
24
+ export interface EventPayload {
25
+ action?: string;
26
+ room_name?: string;
27
+ scene_name?: string;
28
+ x?: number;
29
+ y?: number;
30
+ endX?: number;
31
+ endY?: number;
32
+ track_id?: TrackTarget;
33
+ trackId?: TrackTarget;
34
+ link_id?: string;
35
+ linkId?: string;
36
+ link_scope?: string;
37
+ linkScope?: string;
38
+ scenelytics?: ScenelyticsPayload;
39
+ [key: string]: unknown;
40
+ }
41
+ export interface SpatialObjectLike {
42
+ x?: number;
43
+ y?: number;
44
+ position?: {
45
+ x?: number;
46
+ y?: number;
47
+ };
48
+ id?: string | number;
49
+ name?: string;
50
+ }
51
+ export type TrackTarget = string | SpatialObjectLike;
52
+ export interface LogLudoOptions {
53
+ /** Your LogLudo Project Identifier (Game ID). */
54
+ gameId?: string;
55
+ /** Alias for `gameId`. */
56
+ game_ID?: string;
57
+ /** Ingestion API base URL. Defaults to `"https://api.logludo.com/v0"`. */
58
+ apiUrl?: string;
59
+ /** Alias for `apiUrl`. */
60
+ api_url?: string;
61
+ /** Your game's release version string (e.g. `"1.2.0"`). Defaults to `"1.0.0"`. */
62
+ gameVersion?: string;
63
+ /** Alias for `gameVersion`. */
64
+ appVersion?: string;
65
+ /** Optional explicit framework name (e.g. `"Phaser"`, `"PixiJS"`, `"Three.js"`). */
66
+ framework?: string;
67
+ /** Override dev/debug build detection (`true` -> `"run"`, `false` -> `"build"`). */
68
+ debug?: boolean;
69
+ /** Explicitly set `"run"` (dev) or `"build"` (release). */
70
+ buildType?: "run" | "build";
71
+ /** Console logging verbosity. Defaults to `"info"` in dev, `"errors"` in prod. */
72
+ logLevel?: LogLevel;
73
+ /** Alias for `logLevel`. */
74
+ log_level?: LogLevel;
75
+ /** Automatically attach global `error` and `unhandledrejection` handlers. Defaults to `true`. */
76
+ captureCrashes?: boolean;
77
+ /** Alias for `captureCrashes`. */
78
+ capture_crashes?: boolean;
79
+ /** Automatically sample FPS via `requestAnimationFrame` and emit `performance` pings. Defaults to `true`. */
80
+ autoPerformance?: boolean;
81
+ /** Delay in ms after entering a scene before sending a performance ping. Defaults to `10000`. */
82
+ performanceDelayMs?: number;
83
+ /** Optional repeating performance ping interval in ms (`0` = once per scene). Defaults to `0`. */
84
+ performanceIntervalMs?: number;
85
+ /** Enable SceneLytics dev capture hotkeys (`Ctrl+Shift+F9`). Defaults to `true`. */
86
+ captureHotkeysEnabled?: boolean;
87
+ /** Require `Ctrl+Shift` modifier with `F9` for SceneLytics capture. Defaults to `true`. */
88
+ captureRequireModifier?: boolean;
89
+ /** Optional canvas element, CSS selector, or resolver function used by `captureScene()`. */
90
+ canvas?: HTMLCanvasElement | string | (() => HTMLCanvasElement | null);
91
+ /** Initial scene/level name emitted on boot. */
92
+ initialScene?: string;
93
+ /** Automatically flush buffered events on interval, critical events, and unload. Defaults to `true`. */
94
+ autoFlush?: boolean;
95
+ /** Event buffer threshold before auto-flushing. Defaults to `4` in browser, `10` otherwise. */
96
+ batchLimit?: number;
97
+ /** Periodic flush interval in ms. Defaults to `2000` in dev, `5000` in production web. */
98
+ flushIntervalMs?: number;
99
+ /** Canonical duplicate suppression window in ms. Defaults to `2000`. */
100
+ dedupWindowMs?: number;
101
+ /** Local fallback percentage (0-100) for `experiment()` before server flags load. Defaults to `50`. */
102
+ defaultExperimentPercentage?: number;
103
+ /** Flush queued events automatically whenever `enterScene()` changes scenes. Defaults to `false`. */
104
+ autoFlushOnSceneChange?: boolean;
105
+ /** Optional extra fields merged into the automatic `session_start` event. */
106
+ sessionStartPayload?: Record<string, unknown>;
107
+ /** Optional authenticated/explicit player identifier. */
108
+ userId?: string;
109
+ /** Custom key prefix for localStorage persistence. Defaults to `"logludo"`. */
110
+ storagePrefix?: string;
111
+ /** Custom spatial origin anchor X offset. Defaults to `0`. */
112
+ anchorX?: number;
113
+ /** Custom spatial origin anchor Y offset. Defaults to `0`. */
114
+ anchorY?: number;
115
+ }
116
+ export interface CaptureSceneOptions {
117
+ sceneName?: string;
118
+ canvas?: HTMLCanvasElement | string;
119
+ tileSize?: number;
120
+ waitForRender?: boolean;
121
+ }
122
+ export interface PhaserAttachOptions {
123
+ gameVersion?: string;
124
+ trackScenes?: boolean;
125
+ autoStartInitialScene?: boolean;
126
+ }
127
+ export interface TelemetryEnvelope {
128
+ game_id: string;
129
+ game_version: string;
130
+ session_id: string;
131
+ event_name: string;
132
+ payload: Record<string, unknown>;
133
+ }
134
+ export interface ExperimentsResponse {
135
+ success: boolean;
136
+ game_id?: string;
137
+ experiments: string[];
138
+ flags: Record<string, boolean>;
139
+ error?: string;
140
+ }
141
+ export interface AggregateFrequencyItem {
142
+ item: string;
143
+ count: number;
144
+ }
145
+ export type AggregateValue = number | AggregateFrequencyItem[];
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@logludo/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Zero-dependency JavaScript and TypeScript telemetry SDK for HTML5, Canvas, WebGL, and web game frameworks (Phaser, PixiJS, Three.js, KAPLAY, Vanilla JS).",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.mjs",
8
+ "types": "./dist/index.d.ts",
9
+ "browser": "./dist/index.mjs",
10
+ "unpkg": "./dist/logludo.iife.js",
11
+ "jsdelivr": "./dist/logludo.iife.js",
12
+ "sideEffects": false,
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.mjs",
17
+ "require": "./dist/index.cjs"
18
+ },
19
+ "./esm": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/logludo.esm.js"
22
+ },
23
+ "./browser": "./dist/logludo.iife.js",
24
+ "./iife": "./dist/logludo.iife.js",
25
+ "./package.json": "./package.json"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "scripts": {
33
+ "build": "node scripts/build.mjs",
34
+ "typecheck": "node scripts/build.mjs --check",
35
+ "test": "node --test test/*.test.mjs",
36
+ "prepublishOnly": "npm run typecheck && npm run build && npm test"
37
+ },
38
+ "keywords": [
39
+ "logludo",
40
+ "analytics",
41
+ "telemetry",
42
+ "game-analytics",
43
+ "gamedev",
44
+ "html5",
45
+ "webgl",
46
+ "phaser",
47
+ "pixijs",
48
+ "threejs",
49
+ "kaplay"
50
+ ],
51
+ "author": "LogLudo LLC",
52
+ "license": "SEE LICENSE IN LICENSE",
53
+ "engines": {
54
+ "node": ">=16"
55
+ },
56
+ "repository": {
57
+ "type": "git",
58
+ "url": "git+https://github.com/Logludo/JavascriptSDK.git"
59
+ },
60
+ "homepage": "https://logludo.com",
61
+ "bugs": {
62
+ "url": "https://github.com/Logludo/JavascriptSDK/issues"
63
+ },
64
+ "publishConfig": {
65
+ "access": "public",
66
+ "registry": "https://registry.npmjs.org/"
67
+ }
68
+ }
69
+