@inferevents/sdk 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var h=false;function E(e){h=e;}function a(e,...t){h&&console.log(`[infer] ${e}`,...t);}function g(e,...t){h&&console.warn(`[infer] ${e}`,...t);}function w(e,...t){h&&console.error(`[infer] ${e}`,...t);}var I="infer_event_queue",p=1e3,i=[];function _(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function T(e){i.length>=p&&(g("Queue full, dropping oldest event"),i.shift()),i.push(e),a(`Queued event: ${e.event_name} (${i.length} in queue)`);}function S(e){return i.splice(0,e)}function m(){return i.length}function l(e){i=[...e,...i],i.length>p&&(i=i.slice(i.length-p));}function d(){let e=_();if(!(!e||i.length===0))try{e.setItem(I,JSON.stringify(i)),a("Persisted queue to localStorage:",i.length);}catch{}}function C(){let e=_();if(e)try{let t=e.getItem(I);if(t){let n=JSON.parse(t);Array.isArray(n)&&(i=[...n,...i],i.length>p&&(i=i.slice(i.length-p)),a("Restored queue from localStorage:",n.length)),e.removeItem(I);}}catch{}}var Q="0.1.0";function $(){return typeof window<"u"&&typeof document<"u"}function A(){let e={platform:"web",sdk_version:Q};if(!$())return e;typeof navigator<"u"&&(e.browser=navigator.userAgent,e.locale=navigator.language),typeof screen<"u"&&(e.screen_width=screen.width,e.screen_height=screen.height);try{e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch{}return e.page_url=window.location.href,e.pathname=window.location.pathname,e.page_title=document.title,e.referrer=document.referrer||void 0,e.os=q(navigator.userAgent),e.device_type=D(navigator.userAgent),e}function q(e){return /Windows/.test(e)?"Windows":/Mac OS X/.test(e)?"macOS":/Android/.test(e)?"Android":/iPhone|iPad|iPod/.test(e)?"iOS":/Linux/.test(e)?"Linux":/CrOS/.test(e)?"ChromeOS":"Unknown"}function D(e){return /Mobi|Android.*Mobile|iPhone|iPod/.test(e)?"Mobile":/iPad|Android(?!.*Mobile)|Tablet/.test(e)?"Tablet":"Desktop"}var k="infer_anonymous_id",u=null,y=null,v={};function x(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function R(){if(u)return u;let e=x();if(e){let t=e.getItem(k);if(t)return u=t,u}if(u=crypto.randomUUID(),a("Generated anonymous_id:",u),e)try{e.setItem(k,u);}catch{}return u}function L(){return y}function N(e,t){y=e,t&&(v={...v,...t}),a("Identity set:",y,v);}function z(){y=null,v={},u=null;let e=x();if(e)try{e.removeItem(k);}catch{}}var O="infer_session_last_active";var U={pageView:true,session:true,click:true,formSubmit:true,error:true};function j(e){return e===false?null:e===true?{...U}:{...U,...e}}function M(e,t){if(typeof window>"u")return ()=>{};let n=[];return t.session&&B(e),t.pageView&&n.push(F(e)),t.click&&n.push(Y(e)),t.formSubmit&&n.push(V(e)),t.error&&n.push(H(e)),()=>{for(let r of n)r();}}function B(e){try{let t=Date.now(),n=sessionStorage.getItem(O);(!n||t-Number(n)>18e5)&&e.trackInternal("session_start",{}),sessionStorage.setItem(O,String(t));}catch{}}function F(e){e.trackInternal("page_view",{url:window.location.href,path:window.location.pathname,title:document.title});let t=history.pushState.bind(history),n=history.replaceState.bind(history),r=()=>{e.trackInternal("page_view",{url:window.location.href,path:window.location.pathname,title:document.title});};return history.pushState=function(...o){t(...o),r();},history.replaceState=function(...o){n(...o),r();},window.addEventListener("popstate",r),()=>{history.pushState=t,history.replaceState=n,window.removeEventListener("popstate",r);}}function Y(e){let t=n=>{let r=n.target;if(!r)return;let o=r.closest("a, button, [role='button'], input[type='submit']");if(!o)return;let c={tag:o.tagName.toLowerCase()};o.id&&(c.element_id=o.id),o.className&&typeof o.className=="string"&&(c.element_class=o.className),o.tagName==="A"&&(c.href=o.href),e.trackInternal("click",c);};return document.addEventListener("click",t,{capture:true}),()=>document.removeEventListener("click",t,{capture:true})}function V(e){let t=n=>{let r=n.target;if(!r)return;let o={};r.id&&(o.form_id=r.id),r.action&&(o.form_action=r.action),r.method&&(o.form_method=r.method.toUpperCase()),e.trackInternal("form_submit",o);};return document.addEventListener("submit",t,{capture:true}),()=>document.removeEventListener("submit",t,{capture:true})}function H(e){let t=r=>{e.trackInternal("error",{message:r.message||"Unknown error",filename:r.filename||null,lineno:r.lineno||null,colno:r.colno||null});},n=r=>{let o=r.reason instanceof Error?r.reason.message:typeof r.reason=="string"?r.reason:"Unhandled promise rejection";e.trackInternal("error",{message:o,type:"unhandledrejection"});};return window.addEventListener("error",t),window.addEventListener("unhandledrejection",n),()=>{window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",n);}}var J="https://api.infer.events",K=20,X=1e4,Z=3e4,W=1e3,P=5,b=class{config;flushTimer=null;teardownAutoTrack=null;flushing=false;retryCount=0;disabled=false;constructor(t){if(!t.projectId||typeof t.projectId!="string")throw new Error("[infer] projectId is required");if(E(t.debug??false),this.config={projectId:t.projectId,endpoint:t.endpoint??J,batchSize:t.batchSize??K,flushInterval:t.flushInterval??X},a("Initialized with config:",this.config),C(),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),typeof window<"u"){let r=()=>{d(),this.sendBeacon();};window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();}),window.addEventListener("pagehide",r);}let n=j(t.autoTrack??false);n&&(this.teardownAutoTrack=M(this,n));}track(t,n){this.enqueueEvent("track",t,n??{});}identify(t,n){N(t,n),this.enqueueEvent("identify","identify",n??{});}page(t){let n={};t&&(n.name=t),typeof window<"u"&&(n.url=window.location.href,n.path=window.location.pathname,n.title=document.title),this.enqueueEvent("page","page_view",n);}screen(t){this.enqueueEvent("screen","screen_view",{name:t});}trackInternal(t,n){this.enqueueEvent("track",t,n);}async flush(){if(this.disabled||this.flushing||m()===0)return;this.flushing=true;let t=S(this.config.batchSize);a(`Flushing ${t.length} events`);try{let n=await fetch(`${this.config.endpoint}/v1/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.projectId}`},body:JSON.stringify({events:t})});n.ok?(this.retryCount=0,a(`Flushed ${t.length} events successfully`)):n.status>=500?(g(`Server error ${n.status}, will retry`),l(t),this.scheduleRetry()):w(`Client error ${n.status}, dropping batch`);}catch(n){if(this.retryCount>=P){w(`Cannot connect to ${this.config.endpoint} after ${P} attempts. If your site uses a Content Security Policy, add ${this.config.endpoint} to connect-src. Events will be dropped until the page is reloaded.`),this.disabled=true;return}g("Network error, will retry:",n),l(t),this.scheduleRetry();}finally{this.flushing=false;}m()>0&&this.flush();}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.teardownAutoTrack&&(this.teardownAutoTrack(),this.teardownAutoTrack=null),d();}enqueueEvent(t,n,r){let o={event_id:crypto.randomUUID(),project_id:this.config.projectId,anonymous_id:R(),event_name:n,event_type:t,properties:r,context:A(),timestamp:new Date().toISOString()},c=L();c&&(o.user_id=c),T(o),m()>=this.config.batchSize&&this.flush();}sendBeacon(){let t=S(this.config.batchSize);if(t.length!==0)try{fetch(`${this.config.endpoint}/v1/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.projectId}`},body:JSON.stringify({events:t}),keepalive:!0}).then(n=>{n.ok?a(`Beacon sent ${t.length} events`):(l(t),d());}).catch(()=>{l(t),d();});}catch{l(t),d();}}scheduleRetry(){this.retryCount++;let t=Math.min(W*Math.pow(2,this.retryCount-1)+Math.random()*1e3,Z);a(`Retry #${this.retryCount} in ${Math.round(t)}ms`),setTimeout(()=>{this.flush();},t);}};var s=null,f=[];function ge(e){s&&s.destroy(),s=new b(e);for(let t of f)switch(t.type){case "track":s.track(...t.args);break;case "identify":s.identify(...t.args);break;case "page":s.page(...t.args);break;case "screen":s.screen(...t.args);break}return f=[],s}function pe(e,t){if(!s){f.push({type:"track",args:[e,t]});return}s.track(e,t);}function he(e,t){if(!s){f.push({type:"identify",args:[e,t]});return}s.identify(e,t);}function me(e){if(!s){f.push({type:"page",args:[e]});return}s.page(e);}function ve(e){if(!s){f.push({type:"screen",args:[e]});return}s.screen(e);}async function ye(){s&&await s.flush();}function be(){s&&(s.destroy(),s=null);}
2
- exports.destroy=be;exports.flush=ye;exports.identify=he;exports.init=ge;exports.page=me;exports.reset=z;exports.screen=ve;exports.track=pe;
1
+ 'use strict';var v=false;function T(e){v=e;}function a(e,...t){v&&console.log(`[infer] ${e}`,...t);}function g(e,...t){v&&console.warn(`[infer] ${e}`,...t);}function S(e,...t){v&&console.error(`[infer] ${e}`,...t);}var _="infer_event_queue",p=1e3,i=[];function C(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function A(e){i.length>=p&&(g("Queue full, dropping oldest event"),i.shift()),i.push(e),a(`Queued event: ${e.event_name} (${i.length} in queue)`);}function k(e){return i.splice(0,e)}function y(){return i.length}function l(e){i=[...e,...i],i.length>p&&(i=i.slice(i.length-p));}function d(){let e=C();if(!(!e||i.length===0))try{e.setItem(_,JSON.stringify(i)),a("Persisted queue to localStorage:",i.length);}catch{}}function x(){let e=C();if(e)try{let t=e.getItem(_);if(t){let n=JSON.parse(t);Array.isArray(n)&&(i=[...n,...i],i.length>p&&(i=i.slice(i.length-p)),a("Restored queue from localStorage:",n.length)),e.removeItem(_);}}catch{}}var E="infer_anonymous_id",c=null,w=null,b={};function L(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function N(){if(c)return c;let e=L();if(e){let t=e.getItem(E);if(t)return c=t,c}if(c=crypto.randomUUID(),a("Generated anonymous_id:",c),e)try{e.setItem(E,c);}catch{}return c}function U(){return w}function D(e,t){w=e,t&&(b={...b,...t}),a("Identity set:",w,b);}var R="infer_tab_id";function M(){try{if(typeof sessionStorage>"u")return null;let e=sessionStorage.getItem(R);return e||(e=crypto.randomUUID(),sessionStorage.setItem(R,e)),e}catch{return null}}function F(){w=null,b={},c=null;let e=L();if(e)try{e.removeItem(E);}catch{}}var Y="0.1.0";function K(){return typeof window<"u"&&typeof document<"u"}function O(){let e={platform:"web",sdk_version:Y};if(!K())return e;typeof navigator<"u"&&(e.browser=navigator.userAgent,e.locale=navigator.language),typeof screen<"u"&&(e.screen_width=screen.width,e.screen_height=screen.height);try{e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch{}e.page_url=window.location.href,e.pathname=window.location.pathname,e.page_title=document.title,e.referrer=document.referrer||void 0,e.os=V(navigator.userAgent),e.device_type=H(navigator.userAgent);let t=M();return t&&(e.tab_id=t),e}function V(e){return /Windows/.test(e)?"Windows":/Mac OS X/.test(e)?"macOS":/Android/.test(e)?"Android":/iPhone|iPad|iPod/.test(e)?"iOS":/Linux/.test(e)?"Linux":/CrOS/.test(e)?"ChromeOS":"Unknown"}function H(e){return /Mobi|Android.*Mobile|iPhone|iPod/.test(e)?"Mobile":/iPad|Android(?!.*Mobile)|Tablet/.test(e)?"Tablet":"Desktop"}var P="infer_session_last_active";var $={pageView:true,session:true,click:true,formSubmit:true,error:true};function Q(e){return e===false?null:e===true?{...$}:{...$,...e}}var h=new Map,j=500;function q(e){let t=Date.now(),n=h.get(e);if(n&&t-n<j)return true;if(h.set(e,t),h.size>50)for(let[r,o]of h)t-o>j&&h.delete(r);return false}function z(e,t){if(typeof window>"u")return ()=>{};let n=[];return t.session&&J(e),t.pageView&&n.push(X(e)),t.click&&n.push(Z(e)),t.formSubmit&&n.push(W(e)),t.error&&n.push(G(e)),()=>{for(let r of n)r();}}function J(e){try{let t=Date.now(),n=sessionStorage.getItem(P);(!n||t-Number(n)>18e5)&&e.trackInternal("session_start",{}),sessionStorage.setItem(P,String(t));}catch{}}function X(e){e.trackInternal("page_view",{url:window.location.href,path:window.location.pathname,title:document.title});let t=history.pushState.bind(history),n=history.replaceState.bind(history),r=()=>{e.trackInternal("page_view",{url:window.location.href,path:window.location.pathname,title:document.title});};return history.pushState=function(...o){t(...o),r();},history.replaceState=function(...o){n(...o),r();},window.addEventListener("popstate",r),()=>{history.pushState=t,history.replaceState=n,window.removeEventListener("popstate",r);}}function Z(e){let t=n=>{let r=n.target;if(!r)return;let o=r.closest("a, button, [role='button'], input[type='submit']");if(!o)return;let u=`click:${o.id||o.className||o.tagName}`;if(q(u))return;let m={tag:o.tagName.toLowerCase()};o.id&&(m.element_id=o.id),o.className&&typeof o.className=="string"&&(m.element_class=o.className),o.tagName==="A"&&(m.href=o.href),e.trackInternal("click",m);};return document.addEventListener("click",t,{capture:true}),()=>document.removeEventListener("click",t,{capture:true})}function W(e){let t=n=>{let r=n.target;r&&queueMicrotask(()=>{let o=`form_submit:${r.id||r.action||""}`;if(q(o))return;let u={};r.id&&(u.form_id=r.id),r.action&&(u.form_action=r.action),r.method&&(u.form_method=r.method.toUpperCase()),n.defaultPrevented&&(u.prevented=true),e.trackInternal("form_submit",u);});};return document.addEventListener("submit",t,{capture:true}),()=>document.removeEventListener("submit",t,{capture:true})}function G(e){let t=r=>{e.trackInternal("error",{message:r.message||"Unknown error",filename:r.filename||null,lineno:r.lineno||null,colno:r.colno||null});},n=r=>{let o=r.reason instanceof Error?r.reason.message:typeof r.reason=="string"?r.reason:"Unhandled promise rejection";e.trackInternal("error",{message:o,type:"unhandledrejection"});};return window.addEventListener("error",t),window.addEventListener("unhandledrejection",n),()=>{window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",n);}}var ee="https://api.infer.events",te=20,ne=1e4,re=3e4,oe=1e3,B=5,I=class{config;flushTimer=null;teardownAutoTrack=null;flushing=false;retryCount=0;disabled=false;constructor(t){if(!t.projectId||typeof t.projectId!="string")throw new Error("[infer] projectId is required");if(T(t.debug??false),this.config={projectId:t.projectId,endpoint:t.endpoint??ee,batchSize:t.batchSize??te,flushInterval:t.flushInterval??ne},a("Initialized with config:",this.config),x(),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),typeof window<"u"){let r=()=>{d(),this.sendBeacon();};window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();}),window.addEventListener("pagehide",r);}let n=Q(t.autoTrack??false);n&&(this.teardownAutoTrack=z(this,n));}track(t,n){this.enqueueEvent("track",t,n??{});}identify(t,n){D(t,n),this.enqueueEvent("identify","identify",n??{});}page(t){let n={};t&&(n.name=t),typeof window<"u"&&(n.url=window.location.href,n.path=window.location.pathname,n.title=document.title),this.enqueueEvent("page","page_view",n);}screen(t){this.enqueueEvent("screen","screen_view",{name:t});}trackInternal(t,n){this.enqueueEvent("track",t,n);}async flush(){if(this.disabled||this.flushing||y()===0)return;this.flushing=true;let t=k(this.config.batchSize);a(`Flushing ${t.length} events`);try{let n=await fetch(`${this.config.endpoint}/v1/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.projectId}`},body:JSON.stringify({events:t})});n.ok?(this.retryCount=0,a(`Flushed ${t.length} events successfully`)):n.status>=500?(g(`Server error ${n.status}, will retry`),l(t),this.scheduleRetry()):S(`Client error ${n.status}, dropping batch`);}catch(n){if(this.retryCount>=B){S(`Cannot connect to ${this.config.endpoint} after ${B} attempts. If your site uses a Content Security Policy, add ${this.config.endpoint} to connect-src. Events will be dropped until the page is reloaded.`),this.disabled=true;return}g("Network error, will retry:",n),l(t),this.scheduleRetry();}finally{this.flushing=false;}y()>0&&this.flush();}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.teardownAutoTrack&&(this.teardownAutoTrack(),this.teardownAutoTrack=null),d();}enqueueEvent(t,n,r){let o={event_id:crypto.randomUUID(),project_id:this.config.projectId,anonymous_id:N(),event_name:n,event_type:t,properties:r,context:O(),timestamp:new Date().toISOString()},u=U();u&&(o.user_id=u),A(o),y()>=this.config.batchSize&&this.flush();}sendBeacon(){let t=k(this.config.batchSize);if(t.length!==0)try{fetch(`${this.config.endpoint}/v1/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.projectId}`},body:JSON.stringify({events:t}),keepalive:!0}).then(n=>{n.ok?a(`Beacon sent ${t.length} events`):(l(t),d());}).catch(()=>{l(t),d();});}catch{l(t),d();}}scheduleRetry(){this.retryCount++;let t=Math.min(oe*Math.pow(2,this.retryCount-1)+Math.random()*1e3,re);a(`Retry #${this.retryCount} in ${Math.round(t)}ms`),setTimeout(()=>{this.flush();},t);}};var s=null,f=[];function we(e){s&&s.destroy(),s=new I(e);for(let t of f)switch(t.type){case "track":s.track(...t.args);break;case "identify":s.identify(...t.args);break;case "page":s.page(...t.args);break;case "screen":s.screen(...t.args);break}return f=[],s}function Ie(e,t){if(!s){f.push({type:"track",args:[e,t]});return}s.track(e,t);}function Se(e,t){if(!s){f.push({type:"identify",args:[e,t]});return}s.identify(e,t);}function _e(e){if(!s){f.push({type:"page",args:[e]});return}s.page(e);}function ke(e){if(!s){f.push({type:"screen",args:[e]});return}s.screen(e);}async function Ee(){s&&await s.flush();}function Te(){s&&(s.destroy(),s=null);}
2
+ exports.destroy=Te;exports.flush=Ee;exports.identify=Se;exports.init=we;exports.page=_e;exports.reset=F;exports.screen=ke;exports.track=Ie;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var h=false;function E(e){h=e;}function a(e,...t){h&&console.log(`[infer] ${e}`,...t);}function g(e,...t){h&&console.warn(`[infer] ${e}`,...t);}function w(e,...t){h&&console.error(`[infer] ${e}`,...t);}var I="infer_event_queue",p=1e3,i=[];function _(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function T(e){i.length>=p&&(g("Queue full, dropping oldest event"),i.shift()),i.push(e),a(`Queued event: ${e.event_name} (${i.length} in queue)`);}function S(e){return i.splice(0,e)}function m(){return i.length}function l(e){i=[...e,...i],i.length>p&&(i=i.slice(i.length-p));}function d(){let e=_();if(!(!e||i.length===0))try{e.setItem(I,JSON.stringify(i)),a("Persisted queue to localStorage:",i.length);}catch{}}function C(){let e=_();if(e)try{let t=e.getItem(I);if(t){let n=JSON.parse(t);Array.isArray(n)&&(i=[...n,...i],i.length>p&&(i=i.slice(i.length-p)),a("Restored queue from localStorage:",n.length)),e.removeItem(I);}}catch{}}var Q="0.1.0";function $(){return typeof window<"u"&&typeof document<"u"}function A(){let e={platform:"web",sdk_version:Q};if(!$())return e;typeof navigator<"u"&&(e.browser=navigator.userAgent,e.locale=navigator.language),typeof screen<"u"&&(e.screen_width=screen.width,e.screen_height=screen.height);try{e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch{}return e.page_url=window.location.href,e.pathname=window.location.pathname,e.page_title=document.title,e.referrer=document.referrer||void 0,e.os=q(navigator.userAgent),e.device_type=D(navigator.userAgent),e}function q(e){return /Windows/.test(e)?"Windows":/Mac OS X/.test(e)?"macOS":/Android/.test(e)?"Android":/iPhone|iPad|iPod/.test(e)?"iOS":/Linux/.test(e)?"Linux":/CrOS/.test(e)?"ChromeOS":"Unknown"}function D(e){return /Mobi|Android.*Mobile|iPhone|iPod/.test(e)?"Mobile":/iPad|Android(?!.*Mobile)|Tablet/.test(e)?"Tablet":"Desktop"}var k="infer_anonymous_id",u=null,y=null,v={};function x(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function R(){if(u)return u;let e=x();if(e){let t=e.getItem(k);if(t)return u=t,u}if(u=crypto.randomUUID(),a("Generated anonymous_id:",u),e)try{e.setItem(k,u);}catch{}return u}function L(){return y}function N(e,t){y=e,t&&(v={...v,...t}),a("Identity set:",y,v);}function z(){y=null,v={},u=null;let e=x();if(e)try{e.removeItem(k);}catch{}}var O="infer_session_last_active";var U={pageView:true,session:true,click:true,formSubmit:true,error:true};function j(e){return e===false?null:e===true?{...U}:{...U,...e}}function M(e,t){if(typeof window>"u")return ()=>{};let n=[];return t.session&&B(e),t.pageView&&n.push(F(e)),t.click&&n.push(Y(e)),t.formSubmit&&n.push(V(e)),t.error&&n.push(H(e)),()=>{for(let r of n)r();}}function B(e){try{let t=Date.now(),n=sessionStorage.getItem(O);(!n||t-Number(n)>18e5)&&e.trackInternal("session_start",{}),sessionStorage.setItem(O,String(t));}catch{}}function F(e){e.trackInternal("page_view",{url:window.location.href,path:window.location.pathname,title:document.title});let t=history.pushState.bind(history),n=history.replaceState.bind(history),r=()=>{e.trackInternal("page_view",{url:window.location.href,path:window.location.pathname,title:document.title});};return history.pushState=function(...o){t(...o),r();},history.replaceState=function(...o){n(...o),r();},window.addEventListener("popstate",r),()=>{history.pushState=t,history.replaceState=n,window.removeEventListener("popstate",r);}}function Y(e){let t=n=>{let r=n.target;if(!r)return;let o=r.closest("a, button, [role='button'], input[type='submit']");if(!o)return;let c={tag:o.tagName.toLowerCase()};o.id&&(c.element_id=o.id),o.className&&typeof o.className=="string"&&(c.element_class=o.className),o.tagName==="A"&&(c.href=o.href),e.trackInternal("click",c);};return document.addEventListener("click",t,{capture:true}),()=>document.removeEventListener("click",t,{capture:true})}function V(e){let t=n=>{let r=n.target;if(!r)return;let o={};r.id&&(o.form_id=r.id),r.action&&(o.form_action=r.action),r.method&&(o.form_method=r.method.toUpperCase()),e.trackInternal("form_submit",o);};return document.addEventListener("submit",t,{capture:true}),()=>document.removeEventListener("submit",t,{capture:true})}function H(e){let t=r=>{e.trackInternal("error",{message:r.message||"Unknown error",filename:r.filename||null,lineno:r.lineno||null,colno:r.colno||null});},n=r=>{let o=r.reason instanceof Error?r.reason.message:typeof r.reason=="string"?r.reason:"Unhandled promise rejection";e.trackInternal("error",{message:o,type:"unhandledrejection"});};return window.addEventListener("error",t),window.addEventListener("unhandledrejection",n),()=>{window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",n);}}var J="https://api.infer.events",K=20,X=1e4,Z=3e4,W=1e3,P=5,b=class{config;flushTimer=null;teardownAutoTrack=null;flushing=false;retryCount=0;disabled=false;constructor(t){if(!t.projectId||typeof t.projectId!="string")throw new Error("[infer] projectId is required");if(E(t.debug??false),this.config={projectId:t.projectId,endpoint:t.endpoint??J,batchSize:t.batchSize??K,flushInterval:t.flushInterval??X},a("Initialized with config:",this.config),C(),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),typeof window<"u"){let r=()=>{d(),this.sendBeacon();};window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();}),window.addEventListener("pagehide",r);}let n=j(t.autoTrack??false);n&&(this.teardownAutoTrack=M(this,n));}track(t,n){this.enqueueEvent("track",t,n??{});}identify(t,n){N(t,n),this.enqueueEvent("identify","identify",n??{});}page(t){let n={};t&&(n.name=t),typeof window<"u"&&(n.url=window.location.href,n.path=window.location.pathname,n.title=document.title),this.enqueueEvent("page","page_view",n);}screen(t){this.enqueueEvent("screen","screen_view",{name:t});}trackInternal(t,n){this.enqueueEvent("track",t,n);}async flush(){if(this.disabled||this.flushing||m()===0)return;this.flushing=true;let t=S(this.config.batchSize);a(`Flushing ${t.length} events`);try{let n=await fetch(`${this.config.endpoint}/v1/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.projectId}`},body:JSON.stringify({events:t})});n.ok?(this.retryCount=0,a(`Flushed ${t.length} events successfully`)):n.status>=500?(g(`Server error ${n.status}, will retry`),l(t),this.scheduleRetry()):w(`Client error ${n.status}, dropping batch`);}catch(n){if(this.retryCount>=P){w(`Cannot connect to ${this.config.endpoint} after ${P} attempts. If your site uses a Content Security Policy, add ${this.config.endpoint} to connect-src. Events will be dropped until the page is reloaded.`),this.disabled=true;return}g("Network error, will retry:",n),l(t),this.scheduleRetry();}finally{this.flushing=false;}m()>0&&this.flush();}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.teardownAutoTrack&&(this.teardownAutoTrack(),this.teardownAutoTrack=null),d();}enqueueEvent(t,n,r){let o={event_id:crypto.randomUUID(),project_id:this.config.projectId,anonymous_id:R(),event_name:n,event_type:t,properties:r,context:A(),timestamp:new Date().toISOString()},c=L();c&&(o.user_id=c),T(o),m()>=this.config.batchSize&&this.flush();}sendBeacon(){let t=S(this.config.batchSize);if(t.length!==0)try{fetch(`${this.config.endpoint}/v1/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.projectId}`},body:JSON.stringify({events:t}),keepalive:!0}).then(n=>{n.ok?a(`Beacon sent ${t.length} events`):(l(t),d());}).catch(()=>{l(t),d();});}catch{l(t),d();}}scheduleRetry(){this.retryCount++;let t=Math.min(W*Math.pow(2,this.retryCount-1)+Math.random()*1e3,Z);a(`Retry #${this.retryCount} in ${Math.round(t)}ms`),setTimeout(()=>{this.flush();},t);}};var s=null,f=[];function ge(e){s&&s.destroy(),s=new b(e);for(let t of f)switch(t.type){case "track":s.track(...t.args);break;case "identify":s.identify(...t.args);break;case "page":s.page(...t.args);break;case "screen":s.screen(...t.args);break}return f=[],s}function pe(e,t){if(!s){f.push({type:"track",args:[e,t]});return}s.track(e,t);}function he(e,t){if(!s){f.push({type:"identify",args:[e,t]});return}s.identify(e,t);}function me(e){if(!s){f.push({type:"page",args:[e]});return}s.page(e);}function ve(e){if(!s){f.push({type:"screen",args:[e]});return}s.screen(e);}async function ye(){s&&await s.flush();}function be(){s&&(s.destroy(),s=null);}
2
- export{be as destroy,ye as flush,he as identify,ge as init,me as page,z as reset,ve as screen,pe as track};
1
+ var v=false;function T(e){v=e;}function a(e,...t){v&&console.log(`[infer] ${e}`,...t);}function g(e,...t){v&&console.warn(`[infer] ${e}`,...t);}function S(e,...t){v&&console.error(`[infer] ${e}`,...t);}var _="infer_event_queue",p=1e3,i=[];function C(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function A(e){i.length>=p&&(g("Queue full, dropping oldest event"),i.shift()),i.push(e),a(`Queued event: ${e.event_name} (${i.length} in queue)`);}function k(e){return i.splice(0,e)}function y(){return i.length}function l(e){i=[...e,...i],i.length>p&&(i=i.slice(i.length-p));}function d(){let e=C();if(!(!e||i.length===0))try{e.setItem(_,JSON.stringify(i)),a("Persisted queue to localStorage:",i.length);}catch{}}function x(){let e=C();if(e)try{let t=e.getItem(_);if(t){let n=JSON.parse(t);Array.isArray(n)&&(i=[...n,...i],i.length>p&&(i=i.slice(i.length-p)),a("Restored queue from localStorage:",n.length)),e.removeItem(_);}}catch{}}var E="infer_anonymous_id",c=null,w=null,b={};function L(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function N(){if(c)return c;let e=L();if(e){let t=e.getItem(E);if(t)return c=t,c}if(c=crypto.randomUUID(),a("Generated anonymous_id:",c),e)try{e.setItem(E,c);}catch{}return c}function U(){return w}function D(e,t){w=e,t&&(b={...b,...t}),a("Identity set:",w,b);}var R="infer_tab_id";function M(){try{if(typeof sessionStorage>"u")return null;let e=sessionStorage.getItem(R);return e||(e=crypto.randomUUID(),sessionStorage.setItem(R,e)),e}catch{return null}}function F(){w=null,b={},c=null;let e=L();if(e)try{e.removeItem(E);}catch{}}var Y="0.1.0";function K(){return typeof window<"u"&&typeof document<"u"}function O(){let e={platform:"web",sdk_version:Y};if(!K())return e;typeof navigator<"u"&&(e.browser=navigator.userAgent,e.locale=navigator.language),typeof screen<"u"&&(e.screen_width=screen.width,e.screen_height=screen.height);try{e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch{}e.page_url=window.location.href,e.pathname=window.location.pathname,e.page_title=document.title,e.referrer=document.referrer||void 0,e.os=V(navigator.userAgent),e.device_type=H(navigator.userAgent);let t=M();return t&&(e.tab_id=t),e}function V(e){return /Windows/.test(e)?"Windows":/Mac OS X/.test(e)?"macOS":/Android/.test(e)?"Android":/iPhone|iPad|iPod/.test(e)?"iOS":/Linux/.test(e)?"Linux":/CrOS/.test(e)?"ChromeOS":"Unknown"}function H(e){return /Mobi|Android.*Mobile|iPhone|iPod/.test(e)?"Mobile":/iPad|Android(?!.*Mobile)|Tablet/.test(e)?"Tablet":"Desktop"}var P="infer_session_last_active";var $={pageView:true,session:true,click:true,formSubmit:true,error:true};function Q(e){return e===false?null:e===true?{...$}:{...$,...e}}var h=new Map,j=500;function q(e){let t=Date.now(),n=h.get(e);if(n&&t-n<j)return true;if(h.set(e,t),h.size>50)for(let[r,o]of h)t-o>j&&h.delete(r);return false}function z(e,t){if(typeof window>"u")return ()=>{};let n=[];return t.session&&J(e),t.pageView&&n.push(X(e)),t.click&&n.push(Z(e)),t.formSubmit&&n.push(W(e)),t.error&&n.push(G(e)),()=>{for(let r of n)r();}}function J(e){try{let t=Date.now(),n=sessionStorage.getItem(P);(!n||t-Number(n)>18e5)&&e.trackInternal("session_start",{}),sessionStorage.setItem(P,String(t));}catch{}}function X(e){e.trackInternal("page_view",{url:window.location.href,path:window.location.pathname,title:document.title});let t=history.pushState.bind(history),n=history.replaceState.bind(history),r=()=>{e.trackInternal("page_view",{url:window.location.href,path:window.location.pathname,title:document.title});};return history.pushState=function(...o){t(...o),r();},history.replaceState=function(...o){n(...o),r();},window.addEventListener("popstate",r),()=>{history.pushState=t,history.replaceState=n,window.removeEventListener("popstate",r);}}function Z(e){let t=n=>{let r=n.target;if(!r)return;let o=r.closest("a, button, [role='button'], input[type='submit']");if(!o)return;let u=`click:${o.id||o.className||o.tagName}`;if(q(u))return;let m={tag:o.tagName.toLowerCase()};o.id&&(m.element_id=o.id),o.className&&typeof o.className=="string"&&(m.element_class=o.className),o.tagName==="A"&&(m.href=o.href),e.trackInternal("click",m);};return document.addEventListener("click",t,{capture:true}),()=>document.removeEventListener("click",t,{capture:true})}function W(e){let t=n=>{let r=n.target;r&&queueMicrotask(()=>{let o=`form_submit:${r.id||r.action||""}`;if(q(o))return;let u={};r.id&&(u.form_id=r.id),r.action&&(u.form_action=r.action),r.method&&(u.form_method=r.method.toUpperCase()),n.defaultPrevented&&(u.prevented=true),e.trackInternal("form_submit",u);});};return document.addEventListener("submit",t,{capture:true}),()=>document.removeEventListener("submit",t,{capture:true})}function G(e){let t=r=>{e.trackInternal("error",{message:r.message||"Unknown error",filename:r.filename||null,lineno:r.lineno||null,colno:r.colno||null});},n=r=>{let o=r.reason instanceof Error?r.reason.message:typeof r.reason=="string"?r.reason:"Unhandled promise rejection";e.trackInternal("error",{message:o,type:"unhandledrejection"});};return window.addEventListener("error",t),window.addEventListener("unhandledrejection",n),()=>{window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",n);}}var ee="https://api.infer.events",te=20,ne=1e4,re=3e4,oe=1e3,B=5,I=class{config;flushTimer=null;teardownAutoTrack=null;flushing=false;retryCount=0;disabled=false;constructor(t){if(!t.projectId||typeof t.projectId!="string")throw new Error("[infer] projectId is required");if(T(t.debug??false),this.config={projectId:t.projectId,endpoint:t.endpoint??ee,batchSize:t.batchSize??te,flushInterval:t.flushInterval??ne},a("Initialized with config:",this.config),x(),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),typeof window<"u"){let r=()=>{d(),this.sendBeacon();};window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();}),window.addEventListener("pagehide",r);}let n=Q(t.autoTrack??false);n&&(this.teardownAutoTrack=z(this,n));}track(t,n){this.enqueueEvent("track",t,n??{});}identify(t,n){D(t,n),this.enqueueEvent("identify","identify",n??{});}page(t){let n={};t&&(n.name=t),typeof window<"u"&&(n.url=window.location.href,n.path=window.location.pathname,n.title=document.title),this.enqueueEvent("page","page_view",n);}screen(t){this.enqueueEvent("screen","screen_view",{name:t});}trackInternal(t,n){this.enqueueEvent("track",t,n);}async flush(){if(this.disabled||this.flushing||y()===0)return;this.flushing=true;let t=k(this.config.batchSize);a(`Flushing ${t.length} events`);try{let n=await fetch(`${this.config.endpoint}/v1/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.projectId}`},body:JSON.stringify({events:t})});n.ok?(this.retryCount=0,a(`Flushed ${t.length} events successfully`)):n.status>=500?(g(`Server error ${n.status}, will retry`),l(t),this.scheduleRetry()):S(`Client error ${n.status}, dropping batch`);}catch(n){if(this.retryCount>=B){S(`Cannot connect to ${this.config.endpoint} after ${B} attempts. If your site uses a Content Security Policy, add ${this.config.endpoint} to connect-src. Events will be dropped until the page is reloaded.`),this.disabled=true;return}g("Network error, will retry:",n),l(t),this.scheduleRetry();}finally{this.flushing=false;}y()>0&&this.flush();}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.teardownAutoTrack&&(this.teardownAutoTrack(),this.teardownAutoTrack=null),d();}enqueueEvent(t,n,r){let o={event_id:crypto.randomUUID(),project_id:this.config.projectId,anonymous_id:N(),event_name:n,event_type:t,properties:r,context:O(),timestamp:new Date().toISOString()},u=U();u&&(o.user_id=u),A(o),y()>=this.config.batchSize&&this.flush();}sendBeacon(){let t=k(this.config.batchSize);if(t.length!==0)try{fetch(`${this.config.endpoint}/v1/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.projectId}`},body:JSON.stringify({events:t}),keepalive:!0}).then(n=>{n.ok?a(`Beacon sent ${t.length} events`):(l(t),d());}).catch(()=>{l(t),d();});}catch{l(t),d();}}scheduleRetry(){this.retryCount++;let t=Math.min(oe*Math.pow(2,this.retryCount-1)+Math.random()*1e3,re);a(`Retry #${this.retryCount} in ${Math.round(t)}ms`),setTimeout(()=>{this.flush();},t);}};var s=null,f=[];function we(e){s&&s.destroy(),s=new I(e);for(let t of f)switch(t.type){case "track":s.track(...t.args);break;case "identify":s.identify(...t.args);break;case "page":s.page(...t.args);break;case "screen":s.screen(...t.args);break}return f=[],s}function Ie(e,t){if(!s){f.push({type:"track",args:[e,t]});return}s.track(e,t);}function Se(e,t){if(!s){f.push({type:"identify",args:[e,t]});return}s.identify(e,t);}function _e(e){if(!s){f.push({type:"page",args:[e]});return}s.page(e);}function ke(e){if(!s){f.push({type:"screen",args:[e]});return}s.screen(e);}async function Ee(){s&&await s.flush();}function Te(){s&&(s.destroy(),s=null);}
2
+ export{Te as destroy,Ee as flush,Se as identify,we as init,_e as page,F as reset,ke as screen,Ie as track};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferevents/sdk",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Event collection SDK for Infer — analytics designed for AI agents, not dashboards",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",