@agentstats/sdk 0.5.0 → 0.5.1

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.
@@ -1 +1 @@
1
- var AgentStatsSDK=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=[10,40,100,250],n=[1,2,6,21],r=(e,t)=>{let n=0;for(;n<t.length&&e>=t[n];)n++;return n},i=e=>!!e&&(e.isContentEditable||e.tagName===`TEXTAREA`||e.tagName===`INPUT`&&/^(text|search|email|url|tel|password|number|)$/.test(e.type)),a=e=>!!e&&(e.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(e.tagName)),o=e=>{try{return e.matches(`:autofill`)}catch{return!1}};function s(){let e={take:()=>null,stop(){}};if(typeof document>`u`||typeof performance>`u`)return e;let s=()=>performance.now(),c=()=>document.visibilityState===`hidden`||!document.hasFocus(),l=[],u=0,d=0,f=-1e9,p=-1e9,m=-1e9,h=-1e9,g=new Map,_=()=>{l=Array.from({length:29},()=>0),l[0]=1,u=s(),d=0};_();let v=e=>{l[2]||(l[2]=Math.max(1,Math.round(e-u)))},y=new AbortController,b=(e,t)=>document.addEventListener(e,t,{capture:!0,passive:!0,signal:y.signal});b(`pointermove`,e=>{e.isTrusted&&(l[3]++,d++)}),b(`pointerdown`,e=>{e.isTrusted&&(m=s(),v(m))}),b(`click`,e=>{if(!e.isTrusted)return void l[26]++;v(s()),c()&&l[27]++,e.detail===0?l[10]++:e.pointerType===`touch`||e.pointerType===`pen`?l[9]++:e.detail===1&&l[4+r(d,n)]++,d=0}),b(`keydown`,e=>{if(!e.isTrusted)return void l[26]++;let n=s();v(n),m=p=n,c()&&l[27]++,!(e.repeat||e.target?.type===`password`)&&(n-f<2e3&&l[16+r(n-f,t)]++,f=n,g.set(e.code||e.key,n))}),b(`keyup`,e=>{let n=g.get(e.code||e.key);e.isTrusted&&n!==void 0&&(g.delete(e.code||e.key),l[11+r(s()-n,t)]++)});for(let e of[`paste`,`drop`,`compositionend`])b(e,()=>{p=s()});for(let e of[`wheel`,`touchstart`])b(e,()=>{m=s()});return b(`change`,e=>{!e.isTrusted&&a(e.target)&&l[28]++}),b(`input`,e=>{if(!e.isTrusted)return void(a(e.target)&&l[28]++);if(!i(e.target)||o(e.target))return;let t=s();v(t),c()&&l[27]++;let n=t-p;l[n<100?21:n<1e3?22:23]++}),b(`scroll`,()=>{let e=s();e-h>150&&(l[24]++,e-m>500&&l[25]++),h=e}),{take(){let e=l.slice(3).some(Boolean)?l:null;return e&&(e[1]=Math.min(2**31,Math.round(s()-u))),_(),e},stop:()=>y.abort()}}let c=`agentstats:locationchange`,l=Symbol.for(`agentstats.patched`),u=`pdf.xlsx.docx.txt.rtf.csv.exe.key.pps.ppt.pptx.7z.pkg.rar.gz.zip.avi.mov.mp4.mpeg.wmv.midi.mp3.wav.wma.dmg.iso.msi`.split(`.`);function d(e){try{return document.cookie.match(RegExp(`(?:^|; )${e}=([\\w-]{8,64})`))?.[1]}catch{return}}function f(){if(typeof document>`u`||typeof navigator>`u`)return null;if(document.querySelector?.(`#claude-agent-stop-container`))return{name:`claude-in-chrome`,via:`dom`};let e=String(navigator.userAgent??``);return/\bClaude\/\d/.test(e)?{name:`claude-browser`,via:`user-agent`}:d(`_al_v`)?{name:`verified-visit`,via:`visit`}:navigator.webdriver===!0||/HeadlessChrome/.test(e)?{name:`automation`,via:`webdriver`}:null}function p(){if(!(typeof history>`u`))for(let e of[`pushState`,`replaceState`]){let t=history[e];if(typeof t!=`function`||t[l])continue;let n=function(...e){let n=t.apply(this,e);return window.dispatchEvent(new Event(c)),n};Object.defineProperty(n,l,{value:!0}),history[e]=n}}function m(e){let t={pageview(){},track(){},stop(){}};if(typeof window>`u`||typeof document>`u`)return t;let n=(...t)=>e.debug&&console.debug(`[agentstats]`,...t),r=/^localhost$|^127(\.\d+){3}$|^\[::1?\]$|\.local$|^$/.test(location.hostname)||location.protocol===`file:`,i=!1;try{i=localStorage.getItem(`agentstats_ignore`)===`true`}catch{}let a=(t,a)=>{if(i)return n(`ignored: agentstats_ignore is set`);if(r&&!e.allowLocalhost)return n(`ignored on localhost:`,t);let o=JSON.stringify({k:e.key,...a,a:f()?.name});n(`send`,t);try{if(navigator.sendBeacon?.(e.endpoint,o))return}catch{}fetch(e.endpoint,{method:`POST`,body:o,keepalive:!0,headers:{"Content-Type":`text/plain`}}).catch(()=>{})},o=(t,n)=>a(t,{n:t,u:location.href,r:document.referrer||null,w:window.innerWidth,p:n,h:e.hashRouting?1:void 0}),l=e.agentSignals===!1?null:s(),d=location.href,m=()=>{let e=l?.take();e&&a(`signals`,{t:`s`,u:d,s:e})},h=new AbortController,g={signal:h.signal},_=``,v=()=>{if(h.signal.aborted)return;let t=location.pathname+(e.hashRouting?location.hash:``);t!==_&&(_&&m(),_=t,d=location.href,o(`pageview`))};(()=>{if(document.visibilityState!==`prerender`)return v();document.addEventListener(`visibilitychange`,function e(){document.visibilityState!==`prerender`&&(document.removeEventListener(`visibilitychange`,e),v())},g)})(),p();let y=()=>setTimeout(v,0);if(window.addEventListener(c,y,g),window.addEventListener(`popstate`,y,g),e.hashRouting&&window.addEventListener(`hashchange`,y,g),e.outboundLinks||e.fileDownloads){let t=Array.isArray(e.fileDownloads)?e.fileDownloads:e.fileDownloads?u:[],n=n=>{if(n.type===`auxclick`&&n.button!==1)return;let r=n.target?.closest?.(`a[href]`);if(!r)return;let i;try{i=new URL(r.href,location.href)}catch{return}let a=i.pathname.split(`.`).pop()?.toLowerCase()??``;t.includes(a)?o(`File Download`,{url:i.href.split(`?`)[0]}):e.outboundLinks&&/^https?:$/.test(i.protocol)&&i.host!==location.host&&o(`Outbound Link: Click`,{url:i.href.split(`?`)[0]})};document.addEventListener(`click`,n,{capture:!0,signal:h.signal}),document.addEventListener(`auxclick`,n,{capture:!0,signal:h.signal})}return l&&(window.addEventListener(`pagehide`,m,g),document.addEventListener(`visibilitychange`,()=>document.visibilityState===`hidden`&&m(),g)),{pageview:v,track:(e,t)=>o(String(e),t),stop:()=>{h.signal.aborted||(m(),l?.stop(),h.abort())}}}let h=`0.5.0`;function g(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}function _(){return Date.now()}function v(){return typeof performance<`u`&&performance.now?performance.now():Date.now()}function y(e){return!!e&&typeof e==`object`&&e.name===`AbortError`}function b(e,t,n=0){if(n>6)return`[depth]`;if(Array.isArray(e))return e.slice(0,100).map(e=>b(e,t,n+1));if(e&&typeof e==`object`){let r={};for(let[i,a]of Object.entries(e)){let e=i.toLowerCase();r[i]=t.some(t=>e.includes(t))?`[redacted]`:b(a,t,n+1)}return r}return typeof e==`string`&&e.length>1e3?e.slice(0,1e3)+`…`:e}function x(e,t){let n;try{n=typeof e==`string`?e:JSON.stringify(e)}catch{n=String(e)}return n===void 0&&(n=``),n.length>t?n.slice(0,t)+`…`:n}function S(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}function C(e){let t={name:String(e.name??``)};return e.title&&(t.title=String(e.title)),e.description&&(t.description=String(e.description)),e.inputSchema!==void 0&&(t.inputSchema=e.inputSchema),e.annotations&&(t.annotations={...e.annotations}),e.origin&&(t.origin=String(e.origin)),t}function w(){if(typeof document<`u`){let e=document.currentScript;if(e?.src)try{return new URL(`/api/ingest`,e.src).toString()}catch{}}return`https://agentstats.io/api/ingest`}let T=/(^|\.)(chatgpt\.com|chat\.openai\.com|perplexity\.ai|claude\.ai|gemini\.google\.com|bard\.google\.com|copilot\.microsoft\.com|copilot\.cloud\.microsoft|copilot\.com|meta\.ai|deepseek\.com|grok\.com|chat\.mistral\.ai|you\.com|phind\.com|poe\.com|duck\.ai|chat\.qwen\.ai|kimi\.com|kimi\.ai|doubao\.com)$/i,E=/[?&]utm_source=(chatgpt(\.com)?|openai|perplexity(\.ai)?|claude(\.ai)?|gemini|copilot(\.com)?|meta\.?ai|deepseek|grok|mistral|le-?chat)(&|$)/i,D=Symbol.for(`agentstats.patched`),O=Symbol.for(`agentstats.wrapped`);var k=class{constructor(e){if(this.queue=[],this.timer=null,this.snapshotTimer=null,this.pollTimer=null,this.sessionId=``,this.lastActivity=0,this.lastSnapshotHash=``,this.inflight=Promise.resolve(),this.web=null,this.agentPage=``,this.controlStarted=0,!e||!e.key)throw Error("[agentstats] `key` is required");if(this.options={endpoint:w(),captureArgs:!0,captureResults:!1,captureErrors:!0,redactKeys:[],sessionTimeoutMs:18e5,flushIntervalMs:2e3,maxBatchSize:25,autoInstrument:!0,trackAgentBrowsers:!0,trackPageviews:!0,debug:!1,disabled:!1,...Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))},this._fetch=e.fetch??(typeof fetch<`u`?fetch.bind(globalThis):(()=>Promise.reject(Error(`no fetch`)))),this.sessionId=this.loadSession(),!this.options.disabled&&(this.options.autoInstrument&&this.instrument(),this.bindLifecycle(),this.reportReferral(),this.options.trackAgentBrowsers&&this.watchAgentBrowsers(),this.options.trackPageviews)){let e=this.options;this.web=m({key:e.key,endpoint:`${e.endpoint.replace(/\/+$/,``)}/web`,hashRouting:e.hashRouting,outboundLinks:e.outboundLinks,fileDownloads:e.fileDownloads,allowLocalhost:e.allowLocalhost,agentSignals:e.agentSignals,debug:e.debug})}this.log(`initialised`,{endpoint:this.options.endpoint,session:this.sessionId})}wrap(e){if(!e||typeof e.execute!=`function`||e[O])return e;let t=e.execute,n=String(e.name),r=this,i=async function(e,i){let a=v(),o=i?.signal;try{let s=await t.call(this,e,i);return r.recordCall(n,`success`,v()-a,e,s,void 0,o),s}catch(t){let i=o?.aborted||y(t);throw r.recordCall(n,i?`cancelled`:`error`,v()-a,e,void 0,t,o),t}};Object.defineProperty(i,O,{value:!0});let a=Object.assign({},e,{execute:i});return Object.defineProperty(a,O,{value:!0}),a}track(e,t){let n=t?b(t,this.redactKeys()):void 0;this.enqueue({type:`custom`,id:g(),ts:_(),name:e,props:n,url:this.url()}),this.web?.track(e,n)}pageview(){this.web?.pageview()}async snapshot(){let e=this.modelContext();if(!e?.getTools)return[];let t=[];try{t=(await e.getTools()??[]).map(e=>C(e))}catch(e){return this.log(`getTools failed`,e),[]}let n=x(t.map(e=>[e.name,e.description,e.inputSchema,e.annotations]),1e7);return n!==this.lastSnapshotHash&&(this.lastSnapshotHash=n,this.enqueue({type:`tools_snapshot`,id:g(),ts:_(),tools:t,url:this.url()})),t}flush(e=!1){if(this.timer&&=(clearTimeout(this.timer),null),!this.queue.length)return this.inflight;let t=this.queue.splice(0,this.queue.length),n={key:this.options.key,sdk:`js/${h}`,session_id:this.sessionId,sent_at:_(),metadata:this.options.metadata,visit:typeof document<`u`?d(`_al_v`):void 0,client:this.clientHints(),events:t},r=JSON.stringify(n);if(this.log(`flush`,t.length,`events`),e&&typeof navigator<`u`&&navigator.sendBeacon)try{if(navigator.sendBeacon(this.options.endpoint,new Blob([r],{type:`text/plain`})))return Promise.resolve()}catch{}let i=this._fetch(this.options.endpoint,{method:`POST`,body:r,keepalive:!0,headers:{"Content-Type":`text/plain`}}).then(async e=>{e.ok||this.log(`ingest responded`,e.status)}).catch(e=>{this.log(`ingest failed`,e)});return this.inflight=i,i}destroy(){this.timer&&clearTimeout(this.timer),this.snapshotTimer&&clearTimeout(this.snapshotTimer),this.pollTimer&&clearInterval(this.pollTimer),this.timer=this.snapshotTimer=this.pollTimer=null,this.web?.stop(),this.web=null}get session(){return this.sessionId}log(...e){this.options.debug&&console.debug(`[agentstats]`,...e)}url(){return typeof location<`u`?location.href:void 0}redactKeys(){return(this.options.redactKeys??[]).map(e=>e.toLowerCase()).filter(Boolean)}modelContext(){let e=globalThis;return e.document?.modelContext??e.navigator?.modelContext}captureArgs(e,t){let n=this.options.captureArgs;if(n===!1)return;let r=typeof n==`function`?this.callOption(`captureArgs`,()=>n(e,t)):b(t,this.redactKeys());return r!==void 0&&S(r)>8192&&(r={_truncated:!0,preview:x(r,1e3)}),r}captureResult(e,t){let n=this.options.captureResults;if(!n||t===void 0)return;let r=typeof n==`function`?this.callOption(`captureResults`,()=>n(e,t)):t;return r===void 0?void 0:x(r,2048)}captureError(e,t){let n=this.options.captureErrors;if(n===!1)return;let r=t,i=typeof r?.message==`string`?r.message:x(t,1e3);if(typeof n!=`function`)return x(i,1e3);let a=typeof r?.code==`string`||typeof r?.code==`number`?r.code:null,o=this.callOption(`captureErrors`,()=>n({tool:e,message:i,name:typeof r?.name==`string`?r.name:null,code:a,error:t}));return typeof o==`string`&&o?x(o,1e3):void 0}callOption(e,t){try{return t()}catch(t){this.log(`${e} threw`,t);return}}recordCall(e,t,n,r,i,a,o){let s={type:`tool_call`,id:g(),ts:_(),tool:e,status:t,duration_ms:Math.round(n*100)/100,url:this.url()},c=this.captureArgs(e,r);c!==void 0&&(s.args=c);let l=this.captureResult(e,i);if(l!==void 0&&(s.result=l),a!==void 0){let t=this.captureError(e,a);t!==void 0&&(s.error=t);let n=a?.name;n&&(s.error_name=String(n).slice(0,100))}this.enqueue(s)}enqueue(e){this.options.disabled||(this.touchSession(),this.queue.push(e),this.log(`event`,e.type,e.tool??e.name??``),this.queue.length>=this.options.maxBatchSize?this.flush():this.timer||=setTimeout(()=>void this.flush(),this.options.flushIntervalMs))}scheduleSnapshot(e=250){this.snapshotTimer&&clearTimeout(this.snapshotTimer),this.snapshotTimer=setTimeout(()=>{this.snapshotTimer=null,this.snapshot()},e)}instrument(){let e=()=>{let e=this.modelContext();return e?(this.patch(e),!0):!1};if(e())return;let t=0;this.pollTimer=setInterval(()=>{t++,(e()||t>40)&&(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null)},250)}patch(e){if(e[D]){this.log(`modelContext already patched`),this.scheduleSnapshot(0);return}Object.defineProperty(e,D,{value:!0});let t=this;if(typeof e.registerTool==`function`){let n=e.registerTool;e.registerTool=function(e,r){let i=t.wrap(e);return t.enqueue({type:`tool_registered`,id:g(),ts:_(),tool:String(e?.name),descriptor:C(e),url:t.url()}),t.scheduleSnapshot(),n.call(this,i,r)}}if(typeof e.provideContext==`function`){let n=e.provideContext;e.provideContext=function(e){let r=(e?.tools??[]).map(e=>(t.enqueue({type:`tool_registered`,id:g(),ts:_(),tool:String(e?.name),descriptor:C(e),url:t.url()}),t.wrap(e)));return t.scheduleSnapshot(),n.call(this,{...e,tools:r})}}if(typeof e.unregisterTool==`function`){let n=e.unregisterTool;e.unregisterTool=function(e){return t.enqueue({type:`tool_unregistered`,id:g(),ts:_(),tool:String(e),url:t.url()}),t.scheduleSnapshot(),n.call(this,e)}}if(typeof e.clearContext==`function`){let n=e.clearContext;e.clearContext=function(){return t.scheduleSnapshot(),n.call(this)}}if(typeof e.addEventListener==`function`)try{e.addEventListener(`toolchange`,()=>t.scheduleSnapshot())}catch{}this.log(`modelContext patched`),this.scheduleSnapshot(0)}bindLifecycle(){if(typeof window>`u`||typeof window.addEventListener!=`function`)return;let e=()=>void this.flush(!0);window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&e()})}clientHints(){if(typeof navigator>`u`)return;let e=String(navigator.userAgent??``).slice(0,1e3),t=navigator.webdriver===!0;return e||t?{ua:e||void 0,webdriver:t||void 0}:void 0}detectAgentBrowser(){return f()}watchAgentBrowsers(){if(typeof document>`u`||typeof window>`u`)return;let e=()=>{let e=this.detectAgentBrowser(),t=this.url();e&&t!==this.agentPage&&(this.agentPage=t??``,this.enqueue({type:`agent_pageview`,id:g(),ts:_(),name:e.name,props:{via:e.via},url:t}))},t=()=>{e(),!(typeof MutationObserver>`u`||!document.body)&&new MutationObserver(()=>{let t=!!document.querySelector(`#claude-agent-stop-container`);if(t&&!this.controlStarted)this.controlStarted=v(),this.enqueue({type:`agent_control`,id:g(),ts:_(),name:`claude-in-chrome`,props:{via:`dom`,phase:`start`},url:this.url()}),e();else if(!t&&this.controlStarted){let e=Math.round(v()-this.controlStarted);this.controlStarted=0,this.enqueue({type:`agent_control`,id:g(),ts:_(),name:`claude-in-chrome`,props:{via:`dom`,phase:`stop`,duration_ms:e},url:this.url()})}}).observe(document.body,{childList:!0})};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,t,{once:!0}):t();let n=()=>setTimeout(e,0);window.addEventListener(`popstate`,n),window.addEventListener(c,n),p()}reportReferral(){if(typeof document>`u`||typeof location>`u`)return;let e=``;try{e=document.referrer?new URL(document.referrer).hostname.replace(/^www\./,``):``}catch{}if(!(e&&T.test(e))&&!E.test(location.search))return;let t=`__agentstats_ref_${this.sessionId}`;try{if(sessionStorage.getItem(t))return;sessionStorage.setItem(t,`1`)}catch{}this.enqueue({type:`referral`,id:g(),ts:_(),url:this.url()??location.href,referrer:e?`https://${e}/`:null})}loadSession(){try{let e=sessionStorage.getItem(`__agentstats_session`);if(e){let t=JSON.parse(e);if(t?.id&&_()-t.last<this.options.sessionTimeoutMs)return this.lastActivity=t.last,t.id}}catch{}return g()}touchSession(){let e=_();this.lastActivity&&e-this.lastActivity>this.options.sessionTimeoutMs&&(this.sessionId=g(),this.lastSnapshotHash=``,this.log(`new session`,this.sessionId)),this.lastActivity=e;try{sessionStorage.setItem(`__agentstats_session`,JSON.stringify({id:this.sessionId,last:e}))}catch{}}};let A=null;function j(e){return A&&A.destroy(),A=new k(e),A}function M(){return A}function N(e,t){A?.track(e,t)}function P(e){return A?A.wrap(e):e}function F(){return A?.flush()??Promise.resolve()}function I(){return A?.snapshot()??Promise.resolve([])}function L(){A?.pageview()}let R={init:j,track:N,pageview:L,wrap:P,flush:F,snapshot:I,getClient:M,version:h};window.AgentStats=R;let z=document.currentScript,B=z?.dataset.key,V=e=>e!==void 0&&e!==`false`,H=z?.dataset.fileDownloads;return B&&R.init({key:B,endpoint:z?.dataset.endpoint,debug:z?.dataset.debug===`true`,captureArgs:z?.dataset.captureArgs!==`false`,captureErrors:z?.dataset.captureErrors!==`false`,captureResults:z?.dataset.captureResults===`true`,redactKeys:z?.dataset.redactKeys?.split(`,`).map(e=>e.trim()).filter(Boolean),trackPageviews:z?.dataset.pageviews!==`false`,hashRouting:V(z?.dataset.hashRouting),outboundLinks:V(z?.dataset.outboundLinks),fileDownloads:H&&![``,`true`,`false`].includes(H)?H.split(`,`).map(e=>e.trim()):V(H),allowLocalhost:V(z?.dataset.allowLocalhost),agentSignals:z?.dataset.agentSignals!==`false`}),e.AgentStats=R,e})({});
1
+ var AgentStatsSDK=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=[10,40,100,250],n=[1,2,6,21],r=(e,t)=>{let n=0;for(;n<t.length&&e>=t[n];)n++;return n},i=e=>!!e&&(e.isContentEditable||e.tagName===`TEXTAREA`||e.tagName===`INPUT`&&/^(text|search|email|url|tel|password|number|)$/.test(e.type)),a=e=>!!e&&(e.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(e.tagName)),o=e=>{try{return e.matches(`:autofill`)}catch{return!1}};function s(){let e={take:()=>null,stop(){}};if(typeof document>`u`||typeof performance>`u`)return e;let s=()=>performance.now(),c=()=>document.visibilityState===`hidden`||!document.hasFocus(),l=[],u=0,d=0,f=-1e9,p=-1e9,m=-1e9,h=-1e9,g=/* @__PURE__ */ new Map,_=()=>{l=Array.from({length:29},()=>0),l[0]=1,u=s(),d=0};_();let v=e=>{l[2]||(l[2]=Math.max(1,Math.round(e-u)))},y=new AbortController,b=(e,t)=>document.addEventListener(e,t,{capture:!0,passive:!0,signal:y.signal});b(`pointermove`,e=>{e.isTrusted&&(l[3]++,d++)}),b(`pointerdown`,e=>{e.isTrusted&&(m=s(),v(m))}),b(`click`,e=>{if(!e.isTrusted)return void l[26]++;v(s()),c()&&l[27]++,e.detail===0?l[10]++:e.pointerType===`touch`||e.pointerType===`pen`?l[9]++:e.detail===1&&l[4+r(d,n)]++,d=0}),b(`keydown`,e=>{if(!e.isTrusted)return void l[26]++;let n=s();v(n),m=p=n,c()&&l[27]++,e.repeat||e.target?.type===`password`||(n-f<2e3&&l[16+r(n-f,t)]++,f=n,g.set(e.code||e.key,n))}),b(`keyup`,e=>{let n=g.get(e.code||e.key);e.isTrusted&&n!==void 0&&(g.delete(e.code||e.key),l[11+r(s()-n,t)]++)});for(let e of[`paste`,`drop`,`compositionend`])b(e,()=>{p=s()});for(let e of[`wheel`,`touchstart`])b(e,()=>{m=s()});return b(`change`,e=>{!e.isTrusted&&a(e.target)&&l[28]++}),b(`input`,e=>{if(!e.isTrusted)return void(a(e.target)&&l[28]++);if(!i(e.target)||o(e.target))return;let t=s();v(t),c()&&l[27]++;let n=t-p;l[n<100?21:n<1e3?22:23]++}),b(`scroll`,()=>{let e=s();e-h>150&&(l[24]++,e-m>500&&l[25]++),h=e}),{take(){let e=l.slice(3).some(Boolean)?l:null;return e&&(e[1]=Math.min(2**31,Math.round(s()-u))),_(),e},stop:()=>y.abort()}}let c=`agentstats:locationchange`,l=Symbol.for(`agentstats.patched`),u=/* @__PURE__ */ `pdf.xlsx.docx.txt.rtf.csv.exe.key.pps.ppt.pptx.7z.pkg.rar.gz.zip.avi.mov.mp4.mpeg.wmv.midi.mp3.wav.wma.dmg.iso.msi`.split(`.`);function d(e){try{return document.cookie.match(RegExp(`(?:^|; )${e}=([\\w-]{8,64})`))?.[1]}catch{return}}function f(){if(typeof document>`u`||typeof navigator>`u`)return null;if(document.querySelector?.(`#claude-agent-stop-container`))return{name:`claude-in-chrome`,via:`dom`};let e=String(navigator.userAgent??``);return/\bClaude\/\d/.test(e)?{name:`claude-browser`,via:`user-agent`}:d(`_al_v`)?{name:`verified-visit`,via:`visit`}:navigator.webdriver===!0||/HeadlessChrome/.test(e)?{name:`automation`,via:`webdriver`}:null}function p(){if(typeof history<`u`)for(let e of[`pushState`,`replaceState`]){let t=history[e];if(typeof t!=`function`||t[l])continue;let n=function(...e){let n=t.apply(this,e);return window.dispatchEvent(new Event(c)),n};Object.defineProperty(n,l,{value:!0}),history[e]=n}}function m(e){let t={pageview(){},track(){},stop(){}};if(typeof window>`u`||typeof document>`u`)return t;let n=(...t)=>e.debug&&console.debug(`[agentstats]`,...t),r=/^localhost$|^127(\.\d+){3}$|^\[::1?\]$|\.local$|^$/.test(location.hostname)||location.protocol===`file:`,i=!1;try{i=localStorage.getItem(`agentstats_ignore`)===`true`}catch{}let a=(t,a)=>{if(i)return n(`ignored: agentstats_ignore is set`);if(r&&!e.allowLocalhost)return n(`ignored on localhost:`,t);let o=JSON.stringify({k:e.key,...a,a:f()?.name});n(`send`,t);try{if(navigator.sendBeacon?.(e.endpoint,o))return}catch{}fetch(e.endpoint,{method:`POST`,body:o,keepalive:!0,headers:{"Content-Type":`text/plain`}}).catch(()=>{})},o=(t,n)=>a(t,{n:t,u:location.href,r:document.referrer||null,w:window.innerWidth,p:n,h:e.hashRouting?1:void 0}),l=e.agentSignals===!1?null:s(),d=location.href,m=()=>{let e=l?.take();e&&a(`signals`,{t:`s`,u:d,s:e})},h=new AbortController,g={signal:h.signal},_=``,v=()=>{if(h.signal.aborted)return;let t=location.pathname+(e.hashRouting?location.hash:``);t!==_&&(_&&m(),_=t,d=location.href,o(`pageview`))};(()=>{if(document.visibilityState!==`prerender`)return v();document.addEventListener(`visibilitychange`,function e(){document.visibilityState!==`prerender`&&(document.removeEventListener(`visibilitychange`,e),v())},g)})(),p();let y=()=>setTimeout(v,0);if(window.addEventListener(c,y,g),window.addEventListener(`popstate`,y,g),e.hashRouting&&window.addEventListener(`hashchange`,y,g),e.outboundLinks||e.fileDownloads){let t=Array.isArray(e.fileDownloads)?e.fileDownloads:e.fileDownloads?u:[],n=n=>{if(n.type===`auxclick`&&n.button!==1)return;let r=n.target?.closest?.(`a[href]`);if(!r)return;let i;try{i=new URL(r.href,location.href)}catch{return}let a=i.pathname.split(`.`).pop()?.toLowerCase()??``;t.includes(a)?o(`File Download`,{url:i.href.split(`?`)[0]}):e.outboundLinks&&/^https?:$/.test(i.protocol)&&i.host!==location.host&&o(`Outbound Link: Click`,{url:i.href.split(`?`)[0]})};document.addEventListener(`click`,n,{capture:!0,signal:h.signal}),document.addEventListener(`auxclick`,n,{capture:!0,signal:h.signal})}return l&&(window.addEventListener(`pagehide`,m,g),document.addEventListener(`visibilitychange`,()=>document.visibilityState===`hidden`&&m(),g)),{pageview:v,track:(e,t)=>o(String(e),t),stop:()=>{h.signal.aborted||(m(),l?.stop(),h.abort())}}}let h=`0.5.1`;function g(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}function _(){return Date.now()}function v(){return typeof performance<`u`&&performance.now?performance.now():Date.now()}function y(e){return!!e&&typeof e==`object`&&e.name===`AbortError`}function b(e,t,n=0){if(n>6)return`[depth]`;if(Array.isArray(e))return e.slice(0,100).map(e=>b(e,t,n+1));if(e&&typeof e==`object`){let r={};for(let[i,a]of Object.entries(e)){let e=i.toLowerCase();r[i]=t.some(t=>e.includes(t))?`[redacted]`:b(a,t,n+1)}return r}return typeof e==`string`&&e.length>1e3?e.slice(0,1e3)+`…`:e}function x(e,t){let n;try{n=typeof e==`string`?e:JSON.stringify(e)}catch{n=String(e)}return n===void 0&&(n=``),n.length>t?n.slice(0,t)+`…`:n}function S(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}function C(e){let t={name:String(e.name??``)};return e.title&&(t.title=String(e.title)),e.description&&(t.description=String(e.description)),e.inputSchema!==void 0&&(t.inputSchema=e.inputSchema),e.annotations&&(t.annotations={...e.annotations}),e.origin&&(t.origin=String(e.origin)),t}function w(){if(typeof document<`u`){let e=document.currentScript;if(e?.src)try{return new URL(`/api/ingest`,e.src).toString()}catch{}}return`https://agentstats.io/api/ingest`}let T=/(^|\.)(chatgpt\.com|chat\.openai\.com|perplexity\.ai|claude\.ai|gemini\.google\.com|bard\.google\.com|copilot\.microsoft\.com|copilot\.cloud\.microsoft|copilot\.com|meta\.ai|deepseek\.com|grok\.com|chat\.mistral\.ai|you\.com|phind\.com|poe\.com|duck\.ai|chat\.qwen\.ai|kimi\.com|kimi\.ai|doubao\.com)$/i,E=/[?&]utm_source=(chatgpt(\.com)?|openai|perplexity(\.ai)?|claude(\.ai)?|gemini|copilot(\.com)?|meta\.?ai|deepseek|grok|mistral|le-?chat)(&|$)/i,D=Symbol.for(`agentstats.patched`),O=Symbol.for(`agentstats.wrapped`);var k=class{constructor(e){if(this.queue=[],this.timer=null,this.snapshotTimer=null,this.pollTimer=null,this.sessionId=``,this.lastActivity=0,this.lastSnapshotHash=``,this.inflight=Promise.resolve(),this.web=null,this.agentPage=``,this.controlStarted=0,!e||!e.key)throw Error("[agentstats] `key` is required");if(this.options={endpoint:w(),captureArgs:!0,captureResults:!1,captureErrors:!0,redactKeys:[],sessionTimeoutMs:18e5,flushIntervalMs:2e3,maxBatchSize:25,autoInstrument:!0,trackAgentBrowsers:!0,trackPageviews:!0,debug:!1,disabled:!1,...Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))},this._fetch=e.fetch??(typeof fetch<`u`?fetch.bind(globalThis):(()=>Promise.reject(/* @__PURE__ */ Error(`no fetch`)))),this.sessionId=this.loadSession(),!this.options.disabled&&(this.options.autoInstrument&&this.instrument(),this.bindLifecycle(),this.reportReferral(),this.options.trackAgentBrowsers&&this.watchAgentBrowsers(),this.options.trackPageviews)){let e=this.options;this.web=m({key:e.key,endpoint:`${e.endpoint.replace(/\/+$/,``)}/web`,hashRouting:e.hashRouting,outboundLinks:e.outboundLinks,fileDownloads:e.fileDownloads,allowLocalhost:e.allowLocalhost,agentSignals:e.agentSignals,debug:e.debug})}this.log(`initialised`,{endpoint:this.options.endpoint,session:this.sessionId})}wrap(e){if(!e||typeof e.execute!=`function`||e[O])return e;let t=e.execute,n=String(e.name),r=this,i=async function(e,i){let a=v(),o=i?.signal;try{let s=await t.call(this,e,i);return r.recordCall(n,`success`,v()-a,e,s,void 0,o),s}catch(t){let i=o?.aborted||y(t);throw r.recordCall(n,i?`cancelled`:`error`,v()-a,e,void 0,t,o),t}};Object.defineProperty(i,O,{value:!0});let a=Object.assign({},e,{execute:i});return Object.defineProperty(a,O,{value:!0}),a}track(e,t){let n=t?b(t,this.redactKeys()):void 0;this.enqueue({type:`custom`,id:g(),ts:_(),name:e,props:n,url:this.url()}),this.web?.track(e,n)}pageview(){this.web?.pageview()}async snapshot(){let e=this.modelContext();if(!e?.getTools)return[];let t=[];try{t=(await e.getTools()??[]).map(e=>C(e))}catch(e){return this.log(`getTools failed`,e),[]}let n=x(t.map(e=>[e.name,e.description,e.inputSchema,e.annotations]),1e7);return n!==this.lastSnapshotHash&&(this.lastSnapshotHash=n,this.enqueue({type:`tools_snapshot`,id:g(),ts:_(),tools:t,url:this.url()})),t}flush(e=!1){if(this.timer&&=(clearTimeout(this.timer),null),!this.queue.length)return this.inflight;let t=this.queue.splice(0,this.queue.length),n={key:this.options.key,sdk:`js/${h}`,session_id:this.sessionId,sent_at:_(),metadata:this.options.metadata,visit:typeof document<`u`?d(`_al_v`):void 0,client:this.clientHints(),events:t},r=JSON.stringify(n);if(this.log(`flush`,t.length,`events`),e&&typeof navigator<`u`&&navigator.sendBeacon)try{if(navigator.sendBeacon(this.options.endpoint,new Blob([r],{type:`text/plain`})))return Promise.resolve()}catch{}let i=this._fetch(this.options.endpoint,{method:`POST`,body:r,keepalive:!0,headers:{"Content-Type":`text/plain`}}).then(async e=>{e.ok||this.log(`ingest responded`,e.status)}).catch(e=>{this.log(`ingest failed`,e)});return this.inflight=i,i}destroy(){this.timer&&clearTimeout(this.timer),this.snapshotTimer&&clearTimeout(this.snapshotTimer),this.pollTimer&&clearInterval(this.pollTimer),this.timer=this.snapshotTimer=this.pollTimer=null,this.web?.stop(),this.web=null}get session(){return this.sessionId}log(...e){this.options.debug&&console.debug(`[agentstats]`,...e)}url(){return typeof location<`u`?location.href:void 0}redactKeys(){return(this.options.redactKeys??[]).map(e=>e.toLowerCase()).filter(Boolean)}modelContext(){let e=globalThis;return e.document?.modelContext??e.navigator?.modelContext}captureArgs(e,t){let n=this.options.captureArgs;if(n===!1)return;let r=typeof n==`function`?this.callOption(`captureArgs`,()=>n(e,t)):b(t,this.redactKeys());return r!==void 0&&S(r)>8192&&(r={_truncated:!0,preview:x(r,1e3)}),r}captureResult(e,t){let n=this.options.captureResults;if(!n||t===void 0)return;let r=typeof n==`function`?this.callOption(`captureResults`,()=>n(e,t)):t;return r===void 0?void 0:x(r,2048)}captureError(e,t){let n=this.options.captureErrors;if(n===!1)return;let r=t,i=typeof r?.message==`string`?r.message:x(t,1e3);if(typeof n!=`function`)return x(i,1e3);let a=typeof r?.code==`string`||typeof r?.code==`number`?r.code:null,o=this.callOption(`captureErrors`,()=>n({tool:e,message:i,name:typeof r?.name==`string`?r.name:null,code:a,error:t}));return typeof o==`string`&&o?x(o,1e3):void 0}callOption(e,t){try{return t()}catch(t){this.log(`${e} threw`,t);return}}recordCall(e,t,n,r,i,a,o){let s={type:`tool_call`,id:g(),ts:_(),tool:e,status:t,duration_ms:Math.round(n*100)/100,url:this.url()},c=this.captureArgs(e,r);c!==void 0&&(s.args=c);let l=this.captureResult(e,i);if(l!==void 0&&(s.result=l),a!==void 0){let t=this.captureError(e,a);t!==void 0&&(s.error=t);let n=a?.name;n&&(s.error_name=String(n).slice(0,100))}this.enqueue(s)}enqueue(e){this.options.disabled||(this.touchSession(),this.queue.push(e),this.log(`event`,e.type,e.tool??e.name??``),this.queue.length>=this.options.maxBatchSize?this.flush():this.timer||=setTimeout(()=>void this.flush(),this.options.flushIntervalMs))}scheduleSnapshot(e=250){this.snapshotTimer&&clearTimeout(this.snapshotTimer),this.snapshotTimer=setTimeout(()=>{this.snapshotTimer=null,this.snapshot()},e)}instrument(){let e=()=>{let e=this.modelContext();return e?(this.patch(e),!0):!1};if(e())return;let t=0;this.pollTimer=setInterval(()=>{t++,(e()||t>40)&&(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null)},250)}patch(e){if(e[D]){this.log(`modelContext already patched`),this.scheduleSnapshot(0);return}Object.defineProperty(e,D,{value:!0});let t=this;if(typeof e.registerTool==`function`){let n=e.registerTool;e.registerTool=function(e,r){let i=t.wrap(e);return t.enqueue({type:`tool_registered`,id:g(),ts:_(),tool:String(e?.name),descriptor:C(e),url:t.url()}),t.scheduleSnapshot(),n.call(this,i,r)}}if(typeof e.provideContext==`function`){let n=e.provideContext;e.provideContext=function(e){let r=(e?.tools??[]).map(e=>(t.enqueue({type:`tool_registered`,id:g(),ts:_(),tool:String(e?.name),descriptor:C(e),url:t.url()}),t.wrap(e)));return t.scheduleSnapshot(),n.call(this,{...e,tools:r})}}if(typeof e.unregisterTool==`function`){let n=e.unregisterTool;e.unregisterTool=function(e){return t.enqueue({type:`tool_unregistered`,id:g(),ts:_(),tool:String(e),url:t.url()}),t.scheduleSnapshot(),n.call(this,e)}}if(typeof e.clearContext==`function`){let n=e.clearContext;e.clearContext=function(){return t.scheduleSnapshot(),n.call(this)}}if(typeof e.addEventListener==`function`)try{e.addEventListener(`toolchange`,()=>t.scheduleSnapshot())}catch{}this.log(`modelContext patched`),this.scheduleSnapshot(0)}bindLifecycle(){if(typeof window>`u`||typeof window.addEventListener!=`function`)return;let e=()=>void this.flush(!0);window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&e()})}clientHints(){if(typeof navigator>`u`)return;let e=String(navigator.userAgent??``).slice(0,1e3),t=navigator.webdriver===!0;return e||t?{ua:e||void 0,webdriver:t||void 0}:void 0}detectAgentBrowser(){return f()}watchAgentBrowsers(){if(typeof document>`u`||typeof window>`u`)return;let e=()=>{let e=this.detectAgentBrowser(),t=this.url();e&&t!==this.agentPage&&(this.agentPage=t??``,this.enqueue({type:`agent_pageview`,id:g(),ts:_(),name:e.name,props:{via:e.via},url:t}))},t=()=>{e(),typeof MutationObserver<`u`&&document.body&&new MutationObserver(()=>{let t=!!document.querySelector(`#claude-agent-stop-container`);if(t&&!this.controlStarted)this.controlStarted=v(),this.enqueue({type:`agent_control`,id:g(),ts:_(),name:`claude-in-chrome`,props:{via:`dom`,phase:`start`},url:this.url()}),e();else if(!t&&this.controlStarted){let e=Math.round(v()-this.controlStarted);this.controlStarted=0,this.enqueue({type:`agent_control`,id:g(),ts:_(),name:`claude-in-chrome`,props:{via:`dom`,phase:`stop`,duration_ms:e},url:this.url()})}}).observe(document.body,{childList:!0})};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,t,{once:!0}):t();let n=()=>setTimeout(e,0);window.addEventListener(`popstate`,n),window.addEventListener(c,n),p()}reportReferral(){if(typeof document>`u`||typeof location>`u`)return;let e=``;try{e=document.referrer?new URL(document.referrer).hostname.replace(/^www\./,``):``}catch{}if(!(e&&T.test(e))&&!E.test(location.search))return;let t=`__agentstats_ref_${this.sessionId}`;try{if(sessionStorage.getItem(t))return;sessionStorage.setItem(t,`1`)}catch{}this.enqueue({type:`referral`,id:g(),ts:_(),url:this.url()??location.href,referrer:e?`https://${e}/`:null})}loadSession(){try{let e=sessionStorage.getItem(`__agentstats_session`);if(e){let t=JSON.parse(e);if(t?.id&&_()-t.last<this.options.sessionTimeoutMs)return this.lastActivity=t.last,t.id}}catch{}return g()}touchSession(){let e=_();this.lastActivity&&e-this.lastActivity>this.options.sessionTimeoutMs&&(this.sessionId=g(),this.lastSnapshotHash=``,this.log(`new session`,this.sessionId)),this.lastActivity=e;try{sessionStorage.setItem(`__agentstats_session`,JSON.stringify({id:this.sessionId,last:e}))}catch{}}};let A=null;function j(e){return A&&A.destroy(),A=new k(e),A}function M(){return A}function N(e,t){A?.track(e,t)}function P(e){return A?A.wrap(e):e}function F(){return A?.flush()??Promise.resolve()}function I(){return A?.snapshot()??Promise.resolve([])}function L(){A?.pageview()}let R={init:j,track:N,pageview:L,wrap:P,flush:F,snapshot:I,getClient:M,version:h};window.AgentStats=R;let z=document.currentScript,B=z?.dataset.key,V=e=>e!==void 0&&e!==`false`,H=z?.dataset.fileDownloads;return B&&R.init({key:B,endpoint:z?.dataset.endpoint,debug:z?.dataset.debug===`true`,captureArgs:z?.dataset.captureArgs!==`false`,captureErrors:z?.dataset.captureErrors!==`false`,captureResults:z?.dataset.captureResults===`true`,redactKeys:z?.dataset.redactKeys?.split(`,`).map(e=>e.trim()).filter(Boolean),trackPageviews:z?.dataset.pageviews!==`false`,hashRouting:V(z?.dataset.hashRouting),outboundLinks:V(z?.dataset.outboundLinks),fileDownloads:H&&![``,`true`,`false`].includes(H)?H.split(`,`).map(e=>e.trim()):V(H),allowLocalhost:V(z?.dataset.allowLocalhost),agentSignals:z?.dataset.agentSignals!==`false`}),e.AgentStats=R,e})({});
package/dist/index.cjs CHANGED
@@ -137,8 +137,7 @@ function watchSignals() {
137
137
  stop: () => ctl.abort()
138
138
  };
139
139
  }
140
- //#endregion
141
- //#region src/web.ts
140
+ // src/web.ts
142
141
  /**
143
142
  * Visitors: privacy-friendly web analytics for people. One small request per pageview or custom
144
143
  * event, no cookies, nothing stored in the browser. The server counts unique visitors from a
@@ -343,8 +342,7 @@ function webAnalytics(o) {
343
342
  }
344
343
  };
345
344
  }
346
- //#endregion
347
- //#region src/index.ts
345
+ // src/index.ts
348
346
  /**
349
347
  * AgentStats SDK — analytics for WebMCP tool calls, and for the people visiting the site.
350
348
  *
@@ -356,7 +354,7 @@ function webAnalytics(o) {
356
354
  * It also records pageviews (Visitors, see ./web.ts): no cookies, no personal data. Turn that
357
355
  * off with `trackPageviews: false`.
358
356
  */
359
- const SDK_VERSION = "0.5.0";
357
+ const SDK_VERSION = "0.5.1";
360
358
  const MAX_ARG_BYTES = 8192;
361
359
  const MAX_RESULT_CHARS = 2048;
362
360
  function uuid() {
@@ -955,7 +953,6 @@ const AgentStats = {
955
953
  getClient,
956
954
  version: SDK_VERSION
957
955
  };
958
- //#endregion
959
956
  exports.AgentStats = AgentStats;
960
957
  exports.default = AgentStats;
961
958
  exports.AgentStatsClient = AgentStatsClient;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/web.d.ts
2
1
  /**
3
2
  * Visitors: privacy-friendly web analytics for people. One small request per pageview or custom
4
3
  * event, no cookies, nothing stored in the browser. The server counts unique visitors from a
@@ -8,9 +7,7 @@
8
7
  * the lite script (`/sdk/lite.js`) for sites without WebMCP tools.
9
8
  */
10
9
  type EventProps = Record<string, string | number | boolean>;
11
- //#endregion
12
- //#region src/index.d.ts
13
- export declare const SDK_VERSION = "0.5.0";
10
+ export declare const SDK_VERSION = "0.5.1";
14
11
  export type ToolStatus = 'success' | 'error' | 'cancelled';
15
12
  export interface ToolAnnotations {
16
13
  readOnlyHint?: boolean;
@@ -267,5 +264,4 @@ export declare const AgentStats: {
267
264
  getClient: typeof getClient;
268
265
  version: string;
269
266
  };
270
- //#endregion
271
267
  export { AgentStats as default, type EventProps };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/web.d.ts
2
1
  /**
3
2
  * Visitors: privacy-friendly web analytics for people. One small request per pageview or custom
4
3
  * event, no cookies, nothing stored in the browser. The server counts unique visitors from a
@@ -8,9 +7,7 @@
8
7
  * the lite script (`/sdk/lite.js`) for sites without WebMCP tools.
9
8
  */
10
9
  type EventProps = Record<string, string | number | boolean>;
11
- //#endregion
12
- //#region src/index.d.ts
13
- export declare const SDK_VERSION = "0.5.0";
10
+ export declare const SDK_VERSION = "0.5.1";
14
11
  export type ToolStatus = 'success' | 'error' | 'cancelled';
15
12
  export interface ToolAnnotations {
16
13
  readOnlyHint?: boolean;
@@ -267,5 +264,4 @@ export declare const AgentStats: {
267
264
  getClient: typeof getClient;
268
265
  version: string;
269
266
  };
270
- //#endregion
271
267
  export { AgentStats as default, type EventProps };
package/dist/index.js CHANGED
@@ -133,8 +133,7 @@ function watchSignals() {
133
133
  stop: () => ctl.abort()
134
134
  };
135
135
  }
136
- //#endregion
137
- //#region src/web.ts
136
+ // src/web.ts
138
137
  /**
139
138
  * Visitors: privacy-friendly web analytics for people. One small request per pageview or custom
140
139
  * event, no cookies, nothing stored in the browser. The server counts unique visitors from a
@@ -339,8 +338,7 @@ function webAnalytics(o) {
339
338
  }
340
339
  };
341
340
  }
342
- //#endregion
343
- //#region src/index.ts
341
+ // src/index.ts
344
342
  /**
345
343
  * AgentStats SDK — analytics for WebMCP tool calls, and for the people visiting the site.
346
344
  *
@@ -352,7 +350,7 @@ function webAnalytics(o) {
352
350
  * It also records pageviews (Visitors, see ./web.ts): no cookies, no personal data. Turn that
353
351
  * off with `trackPageviews: false`.
354
352
  */
355
- const SDK_VERSION = "0.5.0";
353
+ const SDK_VERSION = "0.5.1";
356
354
  const MAX_ARG_BYTES = 8192;
357
355
  const MAX_RESULT_CHARS = 2048;
358
356
  function uuid() {
@@ -951,5 +949,4 @@ const AgentStats = {
951
949
  getClient,
952
950
  version: SDK_VERSION
953
951
  };
954
- //#endregion
955
952
  export { AgentStats, AgentStats as default, AgentStatsClient, SDK_VERSION, flush, getClient, init, pageview, snapshot, track, wrap };
package/dist/lite.iife.js CHANGED
@@ -1 +1 @@
1
- (function(){let e=[10,40,100,250],t=[1,2,6,21],n=(e,t)=>{let n=0;for(;n<t.length&&e>=t[n];)n++;return n},r=e=>!!e&&(e.isContentEditable||e.tagName===`TEXTAREA`||e.tagName===`INPUT`&&/^(text|search|email|url|tel|password|number|)$/.test(e.type)),i=e=>!!e&&(e.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(e.tagName)),a=e=>{try{return e.matches(`:autofill`)}catch{return!1}};function o(){let o={take:()=>null,stop(){}};if(typeof document>`u`||typeof performance>`u`)return o;let s=()=>performance.now(),c=()=>document.visibilityState===`hidden`||!document.hasFocus(),l=[],u=0,d=0,f=-1e9,p=-1e9,m=-1e9,h=-1e9,g=new Map,_=()=>{l=Array.from({length:29},()=>0),l[0]=1,u=s(),d=0};_();let v=e=>{l[2]||(l[2]=Math.max(1,Math.round(e-u)))},y=new AbortController,b=(e,t)=>document.addEventListener(e,t,{capture:!0,passive:!0,signal:y.signal});b(`pointermove`,e=>{e.isTrusted&&(l[3]++,d++)}),b(`pointerdown`,e=>{e.isTrusted&&(m=s(),v(m))}),b(`click`,e=>{if(!e.isTrusted)return void l[26]++;v(s()),c()&&l[27]++,e.detail===0?l[10]++:e.pointerType===`touch`||e.pointerType===`pen`?l[9]++:e.detail===1&&l[4+n(d,t)]++,d=0}),b(`keydown`,t=>{if(!t.isTrusted)return void l[26]++;let r=s();v(r),m=p=r,c()&&l[27]++,!(t.repeat||t.target?.type===`password`)&&(r-f<2e3&&l[16+n(r-f,e)]++,f=r,g.set(t.code||t.key,r))}),b(`keyup`,t=>{let r=g.get(t.code||t.key);t.isTrusted&&r!==void 0&&(g.delete(t.code||t.key),l[11+n(s()-r,e)]++)});for(let e of[`paste`,`drop`,`compositionend`])b(e,()=>{p=s()});for(let e of[`wheel`,`touchstart`])b(e,()=>{m=s()});return b(`change`,e=>{!e.isTrusted&&i(e.target)&&l[28]++}),b(`input`,e=>{if(!e.isTrusted)return void(i(e.target)&&l[28]++);if(!r(e.target)||a(e.target))return;let t=s();v(t),c()&&l[27]++;let n=t-p;l[n<100?21:n<1e3?22:23]++}),b(`scroll`,()=>{let e=s();e-h>150&&(l[24]++,e-m>500&&l[25]++),h=e}),{take(){let e=l.slice(3).some(Boolean)?l:null;return e&&(e[1]=Math.min(2**31,Math.round(s()-u))),_(),e},stop:()=>y.abort()}}let s=`agentstats:locationchange`,c=Symbol.for(`agentstats.patched`),l=`pdf.xlsx.docx.txt.rtf.csv.exe.key.pps.ppt.pptx.7z.pkg.rar.gz.zip.avi.mov.mp4.mpeg.wmv.midi.mp3.wav.wma.dmg.iso.msi`.split(`.`);function u(e){try{return document.cookie.match(RegExp(`(?:^|; )${e}=([\\w-]{8,64})`))?.[1]}catch{return}}function d(){if(typeof document>`u`||typeof navigator>`u`)return null;if(document.querySelector?.(`#claude-agent-stop-container`))return{name:`claude-in-chrome`,via:`dom`};let e=String(navigator.userAgent??``);return/\bClaude\/\d/.test(e)?{name:`claude-browser`,via:`user-agent`}:u(`_al_v`)?{name:`verified-visit`,via:`visit`}:navigator.webdriver===!0||/HeadlessChrome/.test(e)?{name:`automation`,via:`webdriver`}:null}function f(){if(!(typeof history>`u`))for(let e of[`pushState`,`replaceState`]){let t=history[e];if(typeof t!=`function`||t[c])continue;let n=function(...e){let n=t.apply(this,e);return window.dispatchEvent(new Event(s)),n};Object.defineProperty(n,c,{value:!0}),history[e]=n}}function p(e){let t={pageview(){},track(){},stop(){}};if(typeof window>`u`||typeof document>`u`)return t;let n=(...t)=>e.debug&&console.debug(`[agentstats]`,...t),r=/^localhost$|^127(\.\d+){3}$|^\[::1?\]$|\.local$|^$/.test(location.hostname)||location.protocol===`file:`,i=!1;try{i=localStorage.getItem(`agentstats_ignore`)===`true`}catch{}let a=(t,a)=>{if(i)return n(`ignored: agentstats_ignore is set`);if(r&&!e.allowLocalhost)return n(`ignored on localhost:`,t);let o=JSON.stringify({k:e.key,...a,a:d()?.name});n(`send`,t);try{if(navigator.sendBeacon?.(e.endpoint,o))return}catch{}fetch(e.endpoint,{method:`POST`,body:o,keepalive:!0,headers:{"Content-Type":`text/plain`}}).catch(()=>{})},c=(t,n)=>a(t,{n:t,u:location.href,r:document.referrer||null,w:window.innerWidth,p:n,h:e.hashRouting?1:void 0}),u=e.agentSignals===!1?null:o(),p=location.href,m=()=>{let e=u?.take();e&&a(`signals`,{t:`s`,u:p,s:e})},h=new AbortController,g={signal:h.signal},_=``,v=()=>{if(h.signal.aborted)return;let t=location.pathname+(e.hashRouting?location.hash:``);t!==_&&(_&&m(),_=t,p=location.href,c(`pageview`))};(()=>{if(document.visibilityState!==`prerender`)return v();document.addEventListener(`visibilitychange`,function e(){document.visibilityState!==`prerender`&&(document.removeEventListener(`visibilitychange`,e),v())},g)})(),f();let y=()=>setTimeout(v,0);if(window.addEventListener(s,y,g),window.addEventListener(`popstate`,y,g),e.hashRouting&&window.addEventListener(`hashchange`,y,g),e.outboundLinks||e.fileDownloads){let t=Array.isArray(e.fileDownloads)?e.fileDownloads:e.fileDownloads?l:[],n=n=>{if(n.type===`auxclick`&&n.button!==1)return;let r=n.target?.closest?.(`a[href]`);if(!r)return;let i;try{i=new URL(r.href,location.href)}catch{return}let a=i.pathname.split(`.`).pop()?.toLowerCase()??``;t.includes(a)?c(`File Download`,{url:i.href.split(`?`)[0]}):e.outboundLinks&&/^https?:$/.test(i.protocol)&&i.host!==location.host&&c(`Outbound Link: Click`,{url:i.href.split(`?`)[0]})};document.addEventListener(`click`,n,{capture:!0,signal:h.signal}),document.addEventListener(`auxclick`,n,{capture:!0,signal:h.signal})}return u&&(window.addEventListener(`pagehide`,m,g),document.addEventListener(`visibilitychange`,()=>document.visibilityState===`hidden`&&m(),g)),{pageview:v,track:(e,t)=>c(String(e),t),stop:()=>{h.signal.aborted||(m(),u?.stop(),h.abort())}}}let m=document.currentScript,h=m?.dataset??{},g=e=>e!==void 0&&e!==`false`,_={pageview(){},track(){},stop(){}};if(h.key){let e=h.fileDownloads;_=p({key:h.key,endpoint:h.endpoint?`${h.endpoint.replace(/\/+$/,``)}/web`:new URL(`/api/ingest/web`,m.src).toString(),hashRouting:g(h.hashRouting),outboundLinks:g(h.outboundLinks),fileDownloads:e&&![``,`true`,`false`].includes(e)?e.split(`,`).map(e=>e.trim()):g(e),allowLocalhost:g(h.allowLocalhost),agentSignals:h.agentSignals!==`false`,debug:g(h.debug)})}let v=window;v.AgentStats??={track:(e,t)=>_.track(e,t),pageview:()=>_.pageview()}})();
1
+ (function(){let e=[10,40,100,250],t=[1,2,6,21],n=(e,t)=>{let n=0;for(;n<t.length&&e>=t[n];)n++;return n},r=e=>!!e&&(e.isContentEditable||e.tagName===`TEXTAREA`||e.tagName===`INPUT`&&/^(text|search|email|url|tel|password|number|)$/.test(e.type)),i=e=>!!e&&(e.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(e.tagName)),a=e=>{try{return e.matches(`:autofill`)}catch{return!1}};function o(){let o={take:()=>null,stop(){}};if(typeof document>`u`||typeof performance>`u`)return o;let s=()=>performance.now(),c=()=>document.visibilityState===`hidden`||!document.hasFocus(),l=[],u=0,d=0,f=-1e9,p=-1e9,m=-1e9,h=-1e9,g=/* @__PURE__ */ new Map,_=()=>{l=Array.from({length:29},()=>0),l[0]=1,u=s(),d=0};_();let v=e=>{l[2]||(l[2]=Math.max(1,Math.round(e-u)))},y=new AbortController,b=(e,t)=>document.addEventListener(e,t,{capture:!0,passive:!0,signal:y.signal});b(`pointermove`,e=>{e.isTrusted&&(l[3]++,d++)}),b(`pointerdown`,e=>{e.isTrusted&&(m=s(),v(m))}),b(`click`,e=>{if(!e.isTrusted)return void l[26]++;v(s()),c()&&l[27]++,e.detail===0?l[10]++:e.pointerType===`touch`||e.pointerType===`pen`?l[9]++:e.detail===1&&l[4+n(d,t)]++,d=0}),b(`keydown`,t=>{if(!t.isTrusted)return void l[26]++;let r=s();v(r),m=p=r,c()&&l[27]++,t.repeat||t.target?.type===`password`||(r-f<2e3&&l[16+n(r-f,e)]++,f=r,g.set(t.code||t.key,r))}),b(`keyup`,t=>{let r=g.get(t.code||t.key);t.isTrusted&&r!==void 0&&(g.delete(t.code||t.key),l[11+n(s()-r,e)]++)});for(let e of[`paste`,`drop`,`compositionend`])b(e,()=>{p=s()});for(let e of[`wheel`,`touchstart`])b(e,()=>{m=s()});return b(`change`,e=>{!e.isTrusted&&i(e.target)&&l[28]++}),b(`input`,e=>{if(!e.isTrusted)return void(i(e.target)&&l[28]++);if(!r(e.target)||a(e.target))return;let t=s();v(t),c()&&l[27]++;let n=t-p;l[n<100?21:n<1e3?22:23]++}),b(`scroll`,()=>{let e=s();e-h>150&&(l[24]++,e-m>500&&l[25]++),h=e}),{take(){let e=l.slice(3).some(Boolean)?l:null;return e&&(e[1]=Math.min(2**31,Math.round(s()-u))),_(),e},stop:()=>y.abort()}}let s=`agentstats:locationchange`,c=Symbol.for(`agentstats.patched`),l=/* @__PURE__ */ `pdf.xlsx.docx.txt.rtf.csv.exe.key.pps.ppt.pptx.7z.pkg.rar.gz.zip.avi.mov.mp4.mpeg.wmv.midi.mp3.wav.wma.dmg.iso.msi`.split(`.`);function u(e){try{return document.cookie.match(RegExp(`(?:^|; )${e}=([\\w-]{8,64})`))?.[1]}catch{return}}function d(){if(typeof document>`u`||typeof navigator>`u`)return null;if(document.querySelector?.(`#claude-agent-stop-container`))return{name:`claude-in-chrome`,via:`dom`};let e=String(navigator.userAgent??``);return/\bClaude\/\d/.test(e)?{name:`claude-browser`,via:`user-agent`}:u(`_al_v`)?{name:`verified-visit`,via:`visit`}:navigator.webdriver===!0||/HeadlessChrome/.test(e)?{name:`automation`,via:`webdriver`}:null}function f(){if(typeof history<`u`)for(let e of[`pushState`,`replaceState`]){let t=history[e];if(typeof t!=`function`||t[c])continue;let n=function(...e){let n=t.apply(this,e);return window.dispatchEvent(new Event(s)),n};Object.defineProperty(n,c,{value:!0}),history[e]=n}}function p(e){let t={pageview(){},track(){},stop(){}};if(typeof window>`u`||typeof document>`u`)return t;let n=(...t)=>e.debug&&console.debug(`[agentstats]`,...t),r=/^localhost$|^127(\.\d+){3}$|^\[::1?\]$|\.local$|^$/.test(location.hostname)||location.protocol===`file:`,i=!1;try{i=localStorage.getItem(`agentstats_ignore`)===`true`}catch{}let a=(t,a)=>{if(i)return n(`ignored: agentstats_ignore is set`);if(r&&!e.allowLocalhost)return n(`ignored on localhost:`,t);let o=JSON.stringify({k:e.key,...a,a:d()?.name});n(`send`,t);try{if(navigator.sendBeacon?.(e.endpoint,o))return}catch{}fetch(e.endpoint,{method:`POST`,body:o,keepalive:!0,headers:{"Content-Type":`text/plain`}}).catch(()=>{})},c=(t,n)=>a(t,{n:t,u:location.href,r:document.referrer||null,w:window.innerWidth,p:n,h:e.hashRouting?1:void 0}),u=e.agentSignals===!1?null:o(),p=location.href,m=()=>{let e=u?.take();e&&a(`signals`,{t:`s`,u:p,s:e})},h=new AbortController,g={signal:h.signal},_=``,v=()=>{if(h.signal.aborted)return;let t=location.pathname+(e.hashRouting?location.hash:``);t!==_&&(_&&m(),_=t,p=location.href,c(`pageview`))};(()=>{if(document.visibilityState!==`prerender`)return v();document.addEventListener(`visibilitychange`,function e(){document.visibilityState!==`prerender`&&(document.removeEventListener(`visibilitychange`,e),v())},g)})(),f();let y=()=>setTimeout(v,0);if(window.addEventListener(s,y,g),window.addEventListener(`popstate`,y,g),e.hashRouting&&window.addEventListener(`hashchange`,y,g),e.outboundLinks||e.fileDownloads){let t=Array.isArray(e.fileDownloads)?e.fileDownloads:e.fileDownloads?l:[],n=n=>{if(n.type===`auxclick`&&n.button!==1)return;let r=n.target?.closest?.(`a[href]`);if(!r)return;let i;try{i=new URL(r.href,location.href)}catch{return}let a=i.pathname.split(`.`).pop()?.toLowerCase()??``;t.includes(a)?c(`File Download`,{url:i.href.split(`?`)[0]}):e.outboundLinks&&/^https?:$/.test(i.protocol)&&i.host!==location.host&&c(`Outbound Link: Click`,{url:i.href.split(`?`)[0]})};document.addEventListener(`click`,n,{capture:!0,signal:h.signal}),document.addEventListener(`auxclick`,n,{capture:!0,signal:h.signal})}return u&&(window.addEventListener(`pagehide`,m,g),document.addEventListener(`visibilitychange`,()=>document.visibilityState===`hidden`&&m(),g)),{pageview:v,track:(e,t)=>c(String(e),t),stop:()=>{h.signal.aborted||(m(),u?.stop(),h.abort())}}}let m=document.currentScript,h=m?.dataset??{},g=e=>e!==void 0&&e!==`false`,_={pageview(){},track(){},stop(){}};if(h.key){let e=h.fileDownloads;_=p({key:h.key,endpoint:h.endpoint?`${h.endpoint.replace(/\/+$/,``)}/web`:new URL(`/api/ingest/web`,m.src).toString(),hashRouting:g(h.hashRouting),outboundLinks:g(h.outboundLinks),fileDownloads:e&&![``,`true`,`false`].includes(e)?e.split(`,`).map(e=>e.trim()):g(e),allowLocalhost:g(h.allowLocalhost),agentSignals:h.agentSignals!==`false`,debug:g(h.debug)})}let v=window;v.AgentStats??={track:(e,t)=>_.track(e,t),pageview:()=>_.pageview()}})();