@numbunch/browser 0.1.0 → 0.1.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,2 +1,2 @@
|
|
|
1
|
-
var C=new TextEncoder;function O(o,e=0){let t=C.encode(o),i=t.length,s=i&-4,n=e>>>0,c;for(let a=0;a<s;a+=4)c=t[a]|t[a+1]<<8|t[a+2]<<16|t[a+3]<<24,n^=S(c),n=n<<13|n>>>19,n=Math.imul(n,5)+3864292196|0;let r=i&3;if(r){c=0;for(let a=r-1;a>=0;a--)c=c<<8|t[s+a];n^=S(c)}return n^=i,n^=n>>>16,n=Math.imul(n,2246822507),n^=n>>>13,n=Math.imul(n,3266489909),n^=n>>>16,n>>>0}function S(o){return o=Math.imul(o,3432918353),o=o<<15|o>>>17,Math.imul(o,461845907)}function p(o,e,t=""){return O(`${o}.${e}${t}`)/4294967296}function T(o,e){if(o.bucketing!=="murmur3_v1")return;if(!o.active)return!1;let{key:t,holdout:i,filters:s}=o,n=s.multivariate?.variants??[],c=[...s.groups??[]].sort((r,a)=>+!r.variant-+!a.variant);for(let r of c){if(r.properties?.length)return;if(p(t,e)<(r.rollout_percentage??100)/100){if(i&&p(`holdout-${i.id}`,e)<i.percentage/100)return`holdout-${i.id}`;if(r.variant&&n.some(l=>l.key===r.variant))return r.variant;if(!n.length)return!0;let a=p(t,e,"variant"),d=0;for(let l of n)if(d+=l.rollout_percentage/100,a<d)return l.key;return!0}}return!1}var g=class{constructor(e,t){this.h=e;this.bootstrap=t;this.cacheKey=`nb_${e.token}_flags`,this.payloads={...t?.payloads}}h;bootstrap;definitions;remoteValues;payloads={};requestVersion=0;remoteRequested=!1;started=!1;loading=!1;waiting=new Set;listeners=new Set;fetch=globalThis.fetch.bind(globalThis);cacheKey;start(e){this.started||(this.started=!0,this.h.storage=e,this.h.localEvaluation&&this.loadDefinitions(),this.h.remote==="eager"&&this.loadRemote(),this.notify())}value(e){let t=this.bootstrap?.flags?.[e];if(t!==void 0)return t;let i=this.definitions?.get(e),s=i&&T(i,this.h.distinctId());if(s!==void 0)return s;let n=this.remoteValues?.[e];return n===void 0&&this.started&&this.h.remote&&!this.remoteRequested&&(this.loading?this.waiting.add(e):this.loadRemote()),n}isLocal(e){return this.bootstrap?.flags?.[e]===void 0&&this.definitions?.has(e)===!0}version(e){return this.definitions?.get(e)?.version}payload(e){let t=this.value(e),s=this.definitions?.get(e)?.filters.payloads?.[String(t)];return t===void 0||t===!1?void 0:s??this.payloads[e]}all(){let e=new Set([...Object.keys(this.remoteValues??{}),...this.definitions?.keys()??[],...Object.keys(this.bootstrap?.flags??{})]),t={};for(let i of e){let s=this.value(i);s!==void 0&&(t[i]=s)}return t}onFlags(e){return this.listeners.add(e),(this.bootstrap?.flags||this.definitions||this.remoteValues)&&e(this.all()),()=>this.listeners.delete(e)}identityChanged(){this.requestVersion++,this.payloads={},this.bootstrap=void 0,this.remoteValues=void 0,this.remoteRequested=!1,this.h.remote==="eager"&&this.loadRemote(),this.notify()}async reload(){await Promise.all([this.h.localEvaluation&&this.loadDefinitions(!0),this.h.remote&&this.loadRemote()])}notify(){let e=this.all();for(let t of this.listeners)t(e)}async loadDefinitions(e=!1){let t;try{t=JSON.parse(this.h.storage?.getItem(this.cacheKey)??"null")??void 0}catch{t=void 0}if(t&&this.useDefinitions(t.f),!(t&&!e&&Date.now()-t.t<this.h.ttlMs)){this.loading=!this.definitions;try{let i=await this.fetch(`${this.h.host}/v1/flags/definitions?token=${encodeURIComponent(this.h.token)}`,{headers:t?.e?{"If-None-Match":t.e}:{}});if(i.status===304&&t)t.t=Date.now();else if(i.ok){let s=await i.json();t={t:Date.now(),e:i.headers.get("ETag")??void 0,f:s.flags},this.useDefinitions(t.f)}else return;this.h.storage?.setItem(this.cacheKey,JSON.stringify(t))}catch{}finally{this.loading=!1;let i=[...this.waiting].some(s=>!this.definitions?.has(s));this.waiting.clear(),i&&this.h.remote&&!this.remoteRequested&&this.loadRemote()}}}useDefinitions(e){this.definitions=new Map(e.map(t=>[t.key,t])),this.notify()}async loadRemote(){let e=++this.requestVersion;this.remoteRequested=!0;try{let t=await this.fetch(`${this.h.host}/flags/?v=2`,{method:"POST",headers:{"Content-Type":"text/plain"},body:JSON.stringify({token:this.h.token,distinct_id:this.h.distinctId(),groups:this.h.groups(),person_properties:this.h.personProperties??{}})});if(!t.ok)throw new Error("flag request failed");let i=await t.json();if(e!==this.requestVersion)return;this.payloads={};let s={};for(let[n,c]of Object.entries(i.flags??{})){s[n]=c.variant??c.enabled;let r=c.metadata?.payload;if(r!=null)try{this.payloads[n]=JSON.parse(r)}catch{this.payloads[n]=r}}this.remoteValues=s,this.notify()}catch{e===this.requestVersion&&(this.remoteRequested=!1)}}};function h(o){let e=crypto.getRandomValues(new Uint8Array(o)),t="";for(let i of e)t+=(i<16?"0":"")+i.toString(16);return t}function u(o=Date.now()){let e=o.toString(16).padStart(12,"0").slice(-12)+h(10),t=(parseInt(e[16],16)&3|8).toString(16);return`${e.slice(0,8)}-${e.slice(8,12)}-7${e.slice(13,16)}-${t}${e.slice(17,20)}-${e.slice(20,32)}`}function m(o){try{return o?JSON.parse(o):void 0}catch{return}}function v(){try{let o=window.localStorage;return o.setItem("__nb","1"),o.removeItem("__nb"),o}catch{return}}function I(o){try{for(let e of document.cookie.split(";")){let t=e.indexOf("=");if(e.slice(0,t).trim()===o)return decodeURIComponent(e.slice(t+1).trim())}}catch{}}var f=class{constructor(e,t,i){this.name=e;this.mode=t;this.domain=i;this.store=t==="memory"?void 0:v();let s=m(this.store?.getItem(e));this.cookie=(t==="cookie"?m(I(e)):s)??{},this.local=s??{}}name;mode;domain;cookie;local;store;save(){let{d:e,i:t,p:i,g:s}=this.local;if(this.mode==="cookie"){let c=location.protocol==="https:"?"; Secure":"",r=this.domain?`; domain=${this.domain}`:"";document.cookie=`${this.name}=${encodeURIComponent(JSON.stringify(this.cookie))}; path=/; max-age=31536000; SameSite=Lax${r}${c}`}let n=this.mode==="cookie"?{d:e,i:t,p:i,g:s}:{...this.cookie,d:e,i:t,p:i,g:s};try{this.store?.setItem(this.name,JSON.stringify(n))}catch{}}};function x(o){let e=typeof o=="string"?`ph_${o}_posthog`:document.cookie.match(/(?:^|;\s*)(ph_[^=]+_posthog)=/)?.[1];if(!e)return;let t=m(I(e)),i=m(v()?.getItem(e)),s=t??i;if(!s?.distinct_id)return;let n=i?.distinct_id===s.distinct_id?{...i,...s}:s,c=n.$user_state?n.$user_state==="identified":n.$epp===!0,r=c?n.$device_id??s.distinct_id:s.distinct_id,a=n.$sesid;return{cookie:{a:r,s:a?.[1]?[a[1],a[0],a[2]]:void 0},local:c?{d:s.distinct_id,i:1}:{}}}var b=class{traceId;parentId;constructor(){let t=(typeof document<"u"?document.querySelector('meta[name="traceparent"]'):null)?.getAttribute("content")?.match(/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/);this.traceId=t?.[1]??h(16),this.parentId=t?.[2]}rotate(){this.traceId=h(16),this.parentId=void 0}header(){return`00-${this.traceId}-${h(8)}-01`}};function D(o,e){return e?e==="same-origin"?o.origin===location.origin:e.some(t=>{if(typeof t!="string")return t.test(o.href);try{let i=new URL(t);return o.origin===i.origin&&o.href.startsWith(i.href)}catch{return!1}}):!1}function P(o,e,t){let i=e.propagateTo??"same-origin";if(!i||typeof window>"u"||!window.fetch)return()=>{};let s=window.fetch,n=!0,c=function(r,a){if(!n)return s.call(this,r,a);try{let d=new URL(r instanceof Request?r.url:String(r),location.href);if(D(d,i)){let l=new Headers(a?.headers??(r instanceof Request?r.headers:void 0));if(l.has("traceparent")||l.set("traceparent",o.header()),e.baggage!==!1){let w=Object.entries(t()).map(([R,E])=>`${R}=${encodeURIComponent(E)}`),k=l.get("baggage");w.length&&l.set("baggage",k?`${k},${w.join(",")}`:w.join(","))}a={...a,headers:l}}}catch{}return s.call(this,r,a)};return window.fetch=c,()=>{n=!1,window.fetch===c&&(window.fetch=s)}}async function F(o){if(!(typeof CompressionStream>"u"))try{return await new Response(new Response(o).body.pipeThrough(new CompressionStream("gzip"))).blob()}catch{return}}var y=class{constructor(e){this.o=e;this.tokens=e.burst}o;queue=[];timer;tokens;refilled=Date.now();fetch=globalThis.fetch.bind(globalThis);push(e,t=!1){let i=Date.now();return this.tokens=Math.min(this.o.burst,this.tokens+(i-this.refilled)/1e3*this.o.perSecond),this.refilled=i,this.tokens<1?!1:(this.tokens-=1,this.queue.push(e),t?this.flush(!0):this.queue.length>=this.o.maxBatchSize?this.flush():this.timer??=setTimeout(()=>{this.flush()},this.o.flushIntervalMs),!0)}flush(e=!1){clearTimeout(this.timer),this.timer=void 0;let t=this.queue.splice(0);if(!t.length)return Promise.resolve();let i=JSON.stringify({api_key:this.o.token,batch:t,sent_at:new Date().toISOString()});return e&&navigator.sendBeacon?.(`${this.o.url}?beacon=1`,new Blob([i],{type:"text/plain"}))?Promise.resolve():this.send(i,t,0)}async send(e,t,i){let s=!1,n=!0;try{let r=e.length>1024?await F(e):void 0,a=r?`${this.o.url}?compression=gzip-js`:this.o.url,d=await this.fetch(a,{method:"POST",headers:{"Content-Type":"text/plain"},body:r??e,keepalive:(r?.size??e.length)<6e4});s=d.ok,n=d.status>=500||d.status===429}catch{}if(s||!n||i>=10)return;let c=Math.min(3e4,1e3*2**i)*(.5+Math.random());return await new Promise(r=>setTimeout(r,c)),this.send(e,t,i+1)}};var M="0.1.0",V="numbunch-web",L="https://in.numbunch.com",H="$posthog_cookieless",$=6e4,q=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid"],_=class{token;options;apiHost;flags;trace;persistence=new f("","memory");lifetime;initialized=!1;transport;hooks;exposures=new Set;pageviews=0;constructor(e,t={},i=!1){let s=t;this.token=e,this.options=s,this.apiHost=(s.apiHost??L).replace(/\/$/,""),this.hooks=s.beforeSend?[].concat(s.beforeSend):[];let n=s.flags??{};this.transport=new y({url:`${this.apiHost}/batch/`,token:e,flushIntervalMs:s.flushIntervalMs??3e3,maxBatchSize:s.maxBatchSize??50,perSecond:s.rateLimit?.perSecond??10,burst:s.rateLimit?.burst??100}),this.flags=new g({token:e,host:(s.flagsHost??this.apiHost).replace(/\/$/,""),ttlMs:n.cacheTtlMs??5*$,remote:n.remote??"lazy",localEvaluation:n.localEvaluation!==!1,personProperties:n.personProperties,distinctId:()=>s.cookieless?this.persistence.cookie.a:this.getDistinctId(),groups:()=>this.persistence.local.g??{}},s.bootstrap),this.trace=new b,this.persistence.cookie.a=s.bootstrap?.distinctId??u(),i||this.start()}start(){if(this.lifetime)return;let e=new AbortController;this.lifetime=e;let t=this.options,i=!this.initialized;i&&(this.initialized=!0,this.loadIdentity(),this.flags.start(t.cookieless||t.persistence==="memory"?void 0:v()));let s=P(this.trace,t.tracing??{},()=>{let n={"session.id":this.getSessionId()};return t.cookieless||(n["user.id"]=this.getDistinctId()),n});if(e.signal.addEventListener("abort",s,{once:!0}),typeof window<"u"){let n=()=>{t.capturePageleave&&this.capture("$pageleave",{},{transport:"sendBeacon"}),this.transport.flush(!0)};window.addEventListener("pagehide",n,{signal:e.signal}),document.addEventListener("visibilitychange",()=>document.visibilityState==="hidden"&&void this.transport.flush(!0),{signal:e.signal})}i&&t.capturePageview&&this.pageview(),t.remoteConfig&&this.loadRemoteConfig(e.signal),i&&t.loaded?.(this)}stop(){this.lifetime?.abort(),this.lifetime=void 0,this.transport.flush()}loadIdentity(){let e=this.options,t=this.persistence=new f(`nb_${this.token}`,e.cookieless?"memory":e.persistence??"cookie",e.cookieDomain);if(!t.cookie.a){let s=e.adoptPostHogCookie?x(e.adoptPostHogCookie):void 0;s?(t.cookie={...s.cookie,c:t.cookie.c},t.local={...t.local,...s.local}):t.cookie.a=u()}let i=e.bootstrap;i?.distinctId&&i.distinctId!==this.getDistinctId()&&(i.isIdentified?t.local={...t.local,d:i.distinctId,i:1}:t.local.i||(t.cookie.a=i.distinctId)),t.save()}getDistinctId(){return this.options.cookieless?H:this.persistence.local.d??this.persistence.cookie.a}getAnonymousId(){return this.persistence.cookie.a}adoptAnonymousId(e){!e||this.isIdentified()||e===this.persistence.cookie.a||(this.persistence.cookie.a=e,this.persistence.save(),this.flags.identityChanged())}isIdentified(){return this.persistence.local.i===1}getSessionId(){return this.session(!1)}session(e){let t=this.persistence,i=Date.now(),s=t.cookie.s??["",0,0],n=s[1],[c,,r]=s,a=i-n>(this.options.sessionIdleMs??30*$)||i-r>(this.options.sessionMaxMs??1440*$);return(!c||a)&&(c=u(i),r=i,e=!0),e&&(t.cookie.s=[c,i,r],t.save()),c}capture(e,t={},i={}){if(!this.lifetime||this.hasOptedOut())return;let s=this.options,n=this.persistence,c=this.isIdentified(),r={...this.context(),...n.local.p,...t,distinct_id:this.getDistinctId(),$lib:V,$lib_version:M,$trace_id:this.trace.traceId,$process_person_profile:c||s.personProfiles==="always",$is_identified:c};s.cookieless||(r.$session_id=this.session(!0),r.$device_id=n.cookie.a),n.local.g&&Object.keys(n.local.g).length&&(r.$groups=n.local.g),i.$set&&(r.$set=i.$set),i.$set_once&&(r.$set_once=i.$set_once);let a={event:e,properties:r,timestamp:(i.timestamp??new Date).toISOString(),uuid:i.uuid??u()};for(let d of this.hooks)a=a&&d(a);if(a)return this.transport.push(a,i.transport==="sendBeacon")?a:void 0}context(){if(typeof location>"u")return{};let e=document.referrer,t="$direct";try{e&&(t=new URL(e).host)}catch{}let i={$current_url:location.href,$host:location.host,$pathname:location.pathname,$referrer:e||"$direct",$referring_domain:t,$screen_height:screen.height,$screen_width:screen.width,$viewport_height:innerHeight,$viewport_width:innerWidth,$browser_language:navigator.language},s=new URLSearchParams(location.search);for(let n of q){let c=s.get(n);c&&(i[n]=c)}return i}pageview(e={}){return this.pageviews++&&this.trace.rotate(),this.capture("$pageview",{title:typeof document<"u"?document.title:void 0,...e})}pageleave(e={}){return this.capture("$pageleave",e,{transport:"sendBeacon"})}identify(e,t,i){if(!e||this.options.cookieless)return;let s=this.getDistinctId();if(e===s&&this.isIdentified()){(t||i)&&this.setPersonProperties(t,i);return}this.persistence.local={...this.persistence.local,d:e,i:1},this.persistence.save(),this.capture("$identify",{$anon_distinct_id:s},{$set:t,$set_once:i}),this.exposures.clear(),this.flags.identityChanged()}reset(){let e=this.persistence;e.cookie={a:u(),c:e.cookie.c},e.local={},e.save(),this.trace.rotate(),this.exposures.clear(),this.flags.identityChanged()}register(e){this.persistence.local.p={...this.persistence.local.p,...e},this.persistence.save()}registerOnce(e){this.register({...e,...this.persistence.local.p})}unregister(e){delete this.persistence.local.p?.[e],this.persistence.save()}setPersonProperties(e,t){this.capture("$set",{},{$set:e??{},$set_once:t})}group(e,t,i){let s=this.persistence.local.g?.[e]!==t;this.persistence.local.g={...this.persistence.local.g,[e]:t},this.persistence.save(),s&&(this.exposures.clear(),this.flags.identityChanged()),i&&this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:i})}optIn(e={}){this.persistence.cookie.c=1,this.persistence.save(),e.captureEvent!==!1&&this.capture("$opt_in")}optOut(){this.persistence.cookie.c=0,this.persistence.save()}hasOptedIn(){return this.persistence.cookie.c===1}hasOptedOut(){let e=this.persistence.cookie.c;return e===0||e===void 0&&this.options.optOutByDefault===!0}getVariant(e,t={}){let i=this.flags.value(e);if(i!==void 0&&t.sendEvent!==!1&&this.options.flags?.sendExposure!==!1){let s=`${e}\0${i}`;this.exposures.has(s)||(this.exposures.add(s),this.capture("$feature_flag_called",{$feature_flag:e,$feature_flag_response:i,[`$feature/${e}`]:i,$feature_flag_version:this.flags.version(e),locally_evaluated:this.flags.isLocal(e)}))}return i}isEnabled(e,t){let i=this.getVariant(e,t);return i===void 0?void 0:i!==!1}getFlagPayload(e){return this.flags.payload(e)}getFlags(){return this.flags.all()}onFlags(e){return this.flags.onFlags(e)}reloadFlags(){return this.flags.reload()}traceparent(){return this.trace.header()}flush(){return this.transport.flush()}async loadRemoteConfig(e){try{let i=await(await fetch(`${this.apiHost}/array/${encodeURIComponent(this.token)}/config`,{signal:e})).json();if(i.autocaptureExceptions){let{exceptionAutocapture:n}=await import("../exceptions.js");if(e.aborted)return;e.addEventListener("abort",n(this),{once:!0})}let s=i.capturePerformance;if(s&&s.web_vitals){let{webVitals:n}=await import("../web-vitals.js");e.aborted||n(this,{metrics:s.web_vitals_allowed_metrics,signal:e})}}catch{}}};function Z(o,e){return new _(o,e)}export{O as a,p as b,T as c,u as d,M as e,_ as f,Z as g};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var C=new TextEncoder;function O(o,e=0){let t=C.encode(o),i=t.length,s=i&-4,n=e>>>0,c;for(let a=0;a<s;a+=4)c=t[a]|t[a+1]<<8|t[a+2]<<16|t[a+3]<<24,n^=S(c),n=n<<13|n>>>19,n=Math.imul(n,5)+3864292196|0;let r=i&3;if(r){c=0;for(let a=r-1;a>=0;a--)c=c<<8|t[s+a];n^=S(c)}return n^=i,n^=n>>>16,n=Math.imul(n,2246822507),n^=n>>>13,n=Math.imul(n,3266489909),n^=n>>>16,n>>>0}function S(o){return o=Math.imul(o,3432918353),o=o<<15|o>>>17,Math.imul(o,461845907)}function p(o,e,t=""){return O(`${o}.${e}${t}`)/4294967296}function T(o,e){if(o.bucketing!=="murmur3_v1")return;if(!o.active)return!1;let{key:t,holdout:i,filters:s}=o,n=s.multivariate?.variants??[],c=[...s.groups??[]].sort((r,a)=>+!r.variant-+!a.variant);for(let r of c){if(r.properties?.length)return;if(p(t,e)<(r.rollout_percentage??100)/100){if(i&&p(`holdout-${i.id}`,e)<i.percentage/100)return`holdout-${i.id}`;if(r.variant&&n.some(l=>l.key===r.variant))return r.variant;if(!n.length)return!0;let a=p(t,e,"variant"),d=0;for(let l of n)if(d+=l.rollout_percentage/100,a<d)return l.key;return!0}}return!1}var g=class{constructor(e,t){this.h=e;this.bootstrap=t;this.cacheKey=`nb_${e.token}_flags`,this.payloads={...t?.payloads}}h;bootstrap;definitions;remoteValues;payloads={};requestVersion=0;remoteRequested=!1;started=!1;loading=!1;waiting=new Set;listeners=new Set;fetch=globalThis.fetch.bind(globalThis);cacheKey;start(e){this.started||(this.started=!0,this.h.storage=e,this.h.localEvaluation&&this.loadDefinitions(),this.h.remote==="eager"&&this.loadRemote(),this.notify())}value(e){let t=this.bootstrap?.flags?.[e];if(t!==void 0)return t;let i=this.definitions?.get(e),s=i&&T(i,this.h.distinctId());if(s!==void 0)return s;let n=this.remoteValues?.[e];return n===void 0&&this.started&&this.h.remote&&!this.remoteRequested&&(this.loading?this.waiting.add(e):this.loadRemote()),n}isLocal(e){return this.bootstrap?.flags?.[e]===void 0&&this.definitions?.has(e)===!0}version(e){return this.definitions?.get(e)?.version}payload(e){let t=this.value(e),s=this.definitions?.get(e)?.filters.payloads?.[String(t)];return t===void 0||t===!1?void 0:s??this.payloads[e]}all(){let e=new Set([...Object.keys(this.remoteValues??{}),...this.definitions?.keys()??[],...Object.keys(this.bootstrap?.flags??{})]),t={};for(let i of e){let s=this.value(i);s!==void 0&&(t[i]=s)}return t}onFlags(e){return this.listeners.add(e),(this.bootstrap?.flags||this.definitions||this.remoteValues)&&e(this.all()),()=>this.listeners.delete(e)}identityChanged(){this.requestVersion++,this.payloads={},this.bootstrap=void 0,this.remoteValues=void 0,this.remoteRequested=!1,this.h.remote==="eager"&&this.loadRemote(),this.notify()}async reload(){await Promise.all([this.h.localEvaluation&&this.loadDefinitions(!0),this.h.remote&&this.loadRemote()])}notify(){let e=this.all();for(let t of this.listeners)t(e)}async loadDefinitions(e=!1){let t;try{t=JSON.parse(this.h.storage?.getItem(this.cacheKey)??"null")??void 0}catch{t=void 0}if(t&&this.useDefinitions(t.f),!(t&&!e&&Date.now()-t.t<this.h.ttlMs)){this.loading=!this.definitions;try{let i=await this.fetch(`${this.h.host}/v1/flags/definitions?token=${encodeURIComponent(this.h.token)}`,{headers:t?.e?{"If-None-Match":t.e}:{}});if(i.status===304&&t)t.t=Date.now();else if(i.ok){let s=await i.json();t={t:Date.now(),e:i.headers.get("ETag")??void 0,f:s.flags},this.useDefinitions(t.f)}else return;this.h.storage?.setItem(this.cacheKey,JSON.stringify(t))}catch{}finally{this.loading=!1;let i=[...this.waiting].some(s=>!this.definitions?.has(s));this.waiting.clear(),i&&this.h.remote&&!this.remoteRequested&&this.loadRemote()}}}useDefinitions(e){this.definitions=new Map(e.map(t=>[t.key,t])),this.notify()}async loadRemote(){let e=++this.requestVersion;this.remoteRequested=!0;try{let t=await this.fetch(`${this.h.host}/flags/?v=2`,{method:"POST",headers:{"Content-Type":"text/plain"},body:JSON.stringify({token:this.h.token,distinct_id:this.h.distinctId(),groups:this.h.groups(),person_properties:this.h.personProperties??{}})});if(!t.ok)throw new Error("flag request failed");let i=await t.json();if(e!==this.requestVersion)return;this.payloads={};let s={};for(let[n,c]of Object.entries(i.flags??{})){s[n]=c.variant??c.enabled;let r=c.metadata?.payload;if(r!=null)try{this.payloads[n]=JSON.parse(r)}catch{this.payloads[n]=r}}this.remoteValues=s,this.notify()}catch{e===this.requestVersion&&(this.remoteRequested=!1)}}};function h(o){let e=crypto.getRandomValues(new Uint8Array(o)),t="";for(let i of e)t+=(i<16?"0":"")+i.toString(16);return t}function u(o=Date.now()){let e=o.toString(16).padStart(12,"0").slice(-12)+h(10),t=(parseInt(e[16],16)&3|8).toString(16);return`${e.slice(0,8)}-${e.slice(8,12)}-7${e.slice(13,16)}-${t}${e.slice(17,20)}-${e.slice(20,32)}`}function m(o){try{return o?JSON.parse(o):void 0}catch{return}}function v(){try{let o=window.localStorage;return o.setItem("__nb","1"),o.removeItem("__nb"),o}catch{return}}function I(o){try{for(let e of document.cookie.split(";")){let t=e.indexOf("=");if(e.slice(0,t).trim()===o)return decodeURIComponent(e.slice(t+1).trim())}}catch{}}var f=class{constructor(e,t,i){this.name=e;this.mode=t;this.domain=i;this.store=t==="memory"?void 0:v();let s=m(this.store?.getItem(e));this.cookie=(t==="cookie"?m(I(e)):s)??{},this.local=s??{}}name;mode;domain;cookie;local;store;save(){let{d:e,i:t,p:i,g:s}=this.local;if(this.mode==="cookie"){let c=location.protocol==="https:"?"; Secure":"",r=this.domain?`; domain=${this.domain}`:"";document.cookie=`${this.name}=${encodeURIComponent(JSON.stringify(this.cookie))}; path=/; max-age=31536000; SameSite=Lax${r}${c}`}let n=this.mode==="cookie"?{d:e,i:t,p:i,g:s}:{...this.cookie,d:e,i:t,p:i,g:s};try{this.store?.setItem(this.name,JSON.stringify(n))}catch{}}};function x(o){let e=typeof o=="string"?`ph_${o}_posthog`:document.cookie.match(/(?:^|;\s*)(ph_[^=]+_posthog)=/)?.[1];if(!e)return;let t=m(I(e)),i=m(v()?.getItem(e)),s=t??i;if(!s?.distinct_id)return;let n=i?.distinct_id===s.distinct_id?{...i,...s}:s,c=n.$user_state?n.$user_state==="identified":n.$epp===!0,r=c?n.$device_id??s.distinct_id:s.distinct_id,a=n.$sesid;return{cookie:{a:r,s:a?.[1]?[a[1],a[0],a[2]]:void 0},local:c?{d:s.distinct_id,i:1}:{}}}var b=class{traceId;parentId;constructor(){let t=(typeof document<"u"?document.querySelector('meta[name="traceparent"]'):null)?.getAttribute("content")?.match(/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/);this.traceId=t?.[1]??h(16),this.parentId=t?.[2]}rotate(){this.traceId=h(16),this.parentId=void 0}header(){return`00-${this.traceId}-${h(8)}-01`}};function D(o,e){return e?e==="same-origin"?o.origin===location.origin:e.some(t=>{if(typeof t!="string")return t.test(o.href);try{let i=new URL(t);return o.origin===i.origin&&o.href.startsWith(i.href)}catch{return!1}}):!1}function P(o,e,t){let i=e.propagateTo??"same-origin";if(!i||typeof window>"u"||!window.fetch)return()=>{};let s=window.fetch,n=!0,c=function(r,a){if(!n)return s.call(this,r,a);try{let d=new URL(r instanceof Request?r.url:String(r),location.href);if(D(d,i)){let l=new Headers(a?.headers??(r instanceof Request?r.headers:void 0));if(l.has("traceparent")||l.set("traceparent",o.header()),e.baggage!==!1){let w=Object.entries(t()).map(([R,E])=>`${R}=${encodeURIComponent(E)}`),k=l.get("baggage");w.length&&l.set("baggage",k?`${k},${w.join(",")}`:w.join(","))}a={...a,headers:l}}}catch{}return s.call(this,r,a)};return window.fetch=c,()=>{n=!1,window.fetch===c&&(window.fetch=s)}}async function F(o){if(!(typeof CompressionStream>"u"))try{return await new Response(new Response(o).body.pipeThrough(new CompressionStream("gzip"))).blob()}catch{return}}var y=class{constructor(e){this.o=e;this.tokens=e.burst}o;queue=[];timer;tokens;refilled=Date.now();fetch=globalThis.fetch.bind(globalThis);push(e,t=!1){let i=Date.now();return this.tokens=Math.min(this.o.burst,this.tokens+(i-this.refilled)/1e3*this.o.perSecond),this.refilled=i,this.tokens<1?!1:(this.tokens-=1,this.queue.push(e),t?this.flush(!0):this.queue.length>=this.o.maxBatchSize?this.flush():this.timer??=setTimeout(()=>{this.flush()},this.o.flushIntervalMs),!0)}flush(e=!1){clearTimeout(this.timer),this.timer=void 0;let t=this.queue.splice(0);if(!t.length)return Promise.resolve();let i=JSON.stringify({api_key:this.o.token,batch:t,sent_at:new Date().toISOString()});return e&&navigator.sendBeacon?.(`${this.o.url}?beacon=1`,new Blob([i],{type:"text/plain"}))?Promise.resolve():this.send(i,t,0)}async send(e,t,i){let s=!1,n=!0;try{let r=e.length>1024?await F(e):void 0,a=r?`${this.o.url}?compression=gzip-js`:this.o.url,d=await this.fetch(a,{method:"POST",headers:{"Content-Type":"text/plain"},body:r??e,keepalive:(r?.size??e.length)<6e4});s=d.ok,n=d.status>=500||d.status===429}catch{}if(s||!n||i>=10)return;let c=Math.min(3e4,1e3*2**i)*(.5+Math.random());return await new Promise(r=>setTimeout(r,c)),this.send(e,t,i+1)}};var M="0.1.1",V="numbunch-web",L="https://in.numbunch.com",H="$posthog_cookieless",$=6e4,q=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid"],_=class{token;options;apiHost;flags;trace;persistence=new f("","memory");lifetime;initialized=!1;transport;hooks;exposures=new Set;pageviews=0;constructor(e,t={},i=!1){let s=t;this.token=e,this.options=s,this.apiHost=(s.apiHost??L).replace(/\/$/,""),this.hooks=s.beforeSend?[].concat(s.beforeSend):[];let n=s.flags??{};this.transport=new y({url:`${this.apiHost}/batch/`,token:e,flushIntervalMs:s.flushIntervalMs??3e3,maxBatchSize:s.maxBatchSize??50,perSecond:s.rateLimit?.perSecond??10,burst:s.rateLimit?.burst??100}),this.flags=new g({token:e,host:(s.flagsHost??this.apiHost).replace(/\/$/,""),ttlMs:n.cacheTtlMs??5*$,remote:n.remote??"lazy",localEvaluation:n.localEvaluation!==!1,personProperties:n.personProperties,distinctId:()=>s.cookieless?this.persistence.cookie.a:this.getDistinctId(),groups:()=>this.persistence.local.g??{}},s.bootstrap),this.trace=new b,this.persistence.cookie.a=s.bootstrap?.distinctId??u(),i||this.start()}start(){if(this.lifetime)return;let e=new AbortController;this.lifetime=e;let t=this.options,i=!this.initialized;i&&(this.initialized=!0,this.loadIdentity(),this.flags.start(t.cookieless||t.persistence==="memory"?void 0:v()));let s=P(this.trace,t.tracing??{},()=>{let n={"session.id":this.getSessionId()};return t.cookieless||(n["user.id"]=this.getDistinctId()),n});if(e.signal.addEventListener("abort",s,{once:!0}),typeof window<"u"){let n=()=>{t.capturePageleave&&this.capture("$pageleave",{},{transport:"sendBeacon"}),this.transport.flush(!0)};window.addEventListener("pagehide",n,{signal:e.signal}),document.addEventListener("visibilitychange",()=>document.visibilityState==="hidden"&&void this.transport.flush(!0),{signal:e.signal})}i&&t.capturePageview&&this.pageview(),t.remoteConfig&&this.loadRemoteConfig(e.signal),i&&t.loaded?.(this)}stop(){this.lifetime?.abort(),this.lifetime=void 0,this.transport.flush()}loadIdentity(){let e=this.options,t=this.persistence=new f(`nb_${this.token}`,e.cookieless?"memory":e.persistence??"cookie",e.cookieDomain);if(!t.cookie.a){let s=e.adoptPostHogCookie?x(e.adoptPostHogCookie):void 0;s?(t.cookie={...s.cookie,c:t.cookie.c},t.local={...t.local,...s.local}):t.cookie.a=u()}let i=e.bootstrap;i?.distinctId&&i.distinctId!==this.getDistinctId()&&(i.isIdentified?t.local={...t.local,d:i.distinctId,i:1}:t.local.i||(t.cookie.a=i.distinctId)),t.save()}getDistinctId(){return this.options.cookieless?H:this.persistence.local.d??this.persistence.cookie.a}getAnonymousId(){return this.persistence.cookie.a}adoptAnonymousId(e){!e||this.isIdentified()||e===this.persistence.cookie.a||(this.persistence.cookie.a=e,this.persistence.save(),this.flags.identityChanged())}isIdentified(){return this.persistence.local.i===1}getSessionId(){return this.session(!1)}session(e){let t=this.persistence,i=Date.now(),s=t.cookie.s??["",0,0],n=s[1],[c,,r]=s,a=i-n>(this.options.sessionIdleMs??30*$)||i-r>(this.options.sessionMaxMs??1440*$);return(!c||a)&&(c=u(i),r=i,e=!0),e&&(t.cookie.s=[c,i,r],t.save()),c}capture(e,t={},i={}){if(!this.lifetime||this.hasOptedOut())return;let s=this.options,n=this.persistence,c=this.isIdentified(),r={...this.context(),...n.local.p,...t,distinct_id:this.getDistinctId(),$lib:V,$lib_version:M,$trace_id:this.trace.traceId,$process_person_profile:c||s.personProfiles==="always",$is_identified:c};s.cookieless||(r.$session_id=this.session(!0),r.$device_id=n.cookie.a),n.local.g&&Object.keys(n.local.g).length&&(r.$groups=n.local.g),i.$set&&(r.$set=i.$set),i.$set_once&&(r.$set_once=i.$set_once);let a={event:e,properties:r,timestamp:(i.timestamp??new Date).toISOString(),uuid:i.uuid??u()};for(let d of this.hooks)a=a&&d(a);if(a)return this.transport.push(a,i.transport==="sendBeacon")?a:void 0}context(){if(typeof location>"u")return{};let e=document.referrer,t="$direct";try{e&&(t=new URL(e).host)}catch{}let i={$current_url:location.href,$host:location.host,$pathname:location.pathname,$referrer:e||"$direct",$referring_domain:t,$screen_height:screen.height,$screen_width:screen.width,$viewport_height:innerHeight,$viewport_width:innerWidth,$browser_language:navigator.language},s=new URLSearchParams(location.search);for(let n of q){let c=s.get(n);c&&(i[n]=c)}return i}pageview(e={}){return this.pageviews++&&this.trace.rotate(),this.capture("$pageview",{title:typeof document<"u"?document.title:void 0,...e})}pageleave(e={}){return this.capture("$pageleave",e,{transport:"sendBeacon"})}identify(e,t,i){if(!e||this.options.cookieless)return;let s=this.getDistinctId();if(e===s&&this.isIdentified()){(t||i)&&this.setPersonProperties(t,i);return}this.persistence.local={...this.persistence.local,d:e,i:1},this.persistence.save(),this.capture("$identify",{$anon_distinct_id:s},{$set:t,$set_once:i}),this.exposures.clear(),this.flags.identityChanged()}reset(){let e=this.persistence;e.cookie={a:u(),c:e.cookie.c},e.local={},e.save(),this.trace.rotate(),this.exposures.clear(),this.flags.identityChanged()}register(e){this.persistence.local.p={...this.persistence.local.p,...e},this.persistence.save()}registerOnce(e){this.register({...e,...this.persistence.local.p})}unregister(e){delete this.persistence.local.p?.[e],this.persistence.save()}setPersonProperties(e,t){this.capture("$set",{},{$set:e??{},$set_once:t})}group(e,t,i){let s=this.persistence.local.g?.[e]!==t;this.persistence.local.g={...this.persistence.local.g,[e]:t},this.persistence.save(),s&&(this.exposures.clear(),this.flags.identityChanged()),i&&this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:i})}optIn(e={}){this.persistence.cookie.c=1,this.persistence.save(),e.captureEvent!==!1&&this.capture("$opt_in")}optOut(){this.persistence.cookie.c=0,this.persistence.save()}hasOptedIn(){return this.persistence.cookie.c===1}hasOptedOut(){let e=this.persistence.cookie.c;return e===0||e===void 0&&this.options.optOutByDefault===!0}getVariant(e,t={}){let i=this.flags.value(e);if(i!==void 0&&t.sendEvent!==!1&&this.options.flags?.sendExposure!==!1){let s=`${e}\0${i}`;this.exposures.has(s)||(this.exposures.add(s),this.capture("$feature_flag_called",{$feature_flag:e,$feature_flag_response:i,[`$feature/${e}`]:i,$feature_flag_version:this.flags.version(e),locally_evaluated:this.flags.isLocal(e)}))}return i}isEnabled(e,t){let i=this.getVariant(e,t);return i===void 0?void 0:i!==!1}getFlagPayload(e){return this.flags.payload(e)}getFlags(){return this.flags.all()}onFlags(e){return this.flags.onFlags(e)}reloadFlags(){return this.flags.reload()}traceparent(){return this.trace.header()}flush(){return this.transport.flush()}async loadRemoteConfig(e){try{let i=await(await fetch(`${this.apiHost}/array/${encodeURIComponent(this.token)}/config`,{signal:e})).json();if(i.autocaptureExceptions){let{exceptionAutocapture:n}=await import("../exceptions.js");if(e.aborted)return;e.addEventListener("abort",n(this),{once:!0})}let s=i.capturePerformance;if(s&&s.web_vitals){let{webVitals:n}=await import("../web-vitals.js");e.aborted||n(this,{metrics:s.web_vitals_allowed_metrics,signal:e})}}catch{}}};function Z(o,e){return new _(o,e)}export{O as a,p as b,T as c,u as d,M as e,_ as f,Z as g};
|
|
2
|
+
//# sourceMappingURL=chunk-GEQWAF5D.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/murmur3.ts", "../../src/flags.ts", "../../src/uuid.ts", "../../src/storage.ts", "../../src/trace.ts", "../../src/transport.ts", "../../src/client.ts"],
|
|
4
|
-
"sourcesContent": ["// MurmurHash3 x86 32-bit (Austin Appleby, public domain) and the `murmur3_v1` bucketing value (ADR 0007).\n\nconst encoder = /* @__PURE__ */ new TextEncoder()\n\n/** `murmur3_x86_32` of the UTF-8 bytes of `input`. */\nexport function murmur3(input: string, seed = 0): number {\n const data = encoder.encode(input)\n const length = data.length\n const blocks = length & ~3\n let h = seed >>> 0\n let k: number\n for (let i = 0; i < blocks; i += 4) {\n k = data[i]! | (data[i + 1]! << 8) | (data[i + 2]! << 16) | (data[i + 3]! << 24)\n h ^= mix(k)\n h = (h << 13) | (h >>> 19)\n h = (Math.imul(h, 5) + 0xe6546b64) | 0\n }\n const tail = length & 3\n if (tail) {\n k = 0\n for (let i = tail - 1; i >= 0; i--) k = (k << 8) | data[blocks + i]!\n h ^= mix(k)\n }\n h ^= length\n h ^= h >>> 16\n h = Math.imul(h, 0x85ebca6b)\n h ^= h >>> 13\n h = Math.imul(h, 0xc2b2ae35)\n h ^= h >>> 16\n return h >>> 0\n}\n\nfunction mix(k: number): number {\n k = Math.imul(k, 0xcc9e2d51)\n k = (k << 15) | (k >>> 17)\n return Math.imul(k, 0x1b873593)\n}\n\n/** `murmur3(\"{key}.{id}{salt}\") / 2^32`, in [0, 1). The holdout value is `bucket(\"holdout-{holdout_id}\", id)`. */\nexport function bucket(key: string, id: string, salt = ''): number {\n return murmur3(`${key}.${id}${salt}`) / 4294967296\n}\n", "import { bucket } from './murmur3'\nimport type { Bootstrap, FlagValue, Properties } from './types'\n\n/** One flag from `GET /v1/flags/definitions?token=` (only client-evaluable flags are served there). */\nexport interface FlagDefinition {\n key: string\n version?: number\n active: boolean\n bucketing: string\n filters: {\n groups?: { properties?: unknown[]; rollout_percentage?: number | null; variant?: string | null }[]\n multivariate?: { variants: { key: string; rollout_percentage: number }[] } | null\n payloads?: Record<string, unknown>\n }\n holdout?: { id: number; percentage: number } | null\n}\n\n/**\n * Evaluates a client-evaluable flag for `id` with `murmur3_v1`: the condition sets (those pinning a variant first)\n * and the rollout, then for a targeted user the holdout and the variant walk. `undefined` if the definition needs the server.\n */\nexport function evaluate(flag: FlagDefinition, id: string): FlagValue | undefined {\n if (flag.bucketing !== 'murmur3_v1') return undefined\n if (!flag.active) return false\n const { key, holdout, filters } = flag\n const variants = filters.multivariate?.variants ?? []\n const groups = [...(filters.groups ?? [])].sort((a, b) => Number(!a.variant) - Number(!b.variant))\n for (const group of groups) {\n if (group.properties?.length) return undefined\n if (bucket(key, id) < (group.rollout_percentage ?? 100) / 100) {\n if (holdout && bucket(`holdout-${holdout.id}`, id) < holdout.percentage / 100) return `holdout-${holdout.id}`\n if (group.variant && variants.some((v) => v.key === group.variant)) return group.variant\n if (!variants.length) return true\n const value = bucket(key, id, 'variant')\n let cumulative = 0\n for (const variant of variants) {\n cumulative += variant.rollout_percentage / 100\n if (value < cumulative) return variant.key\n }\n return true\n }\n }\n return false\n}\n\ninterface Cached {\n /** Fetched at (ms). */\n t: number\n /** ETag. */\n e?: string\n f: FlagDefinition[]\n}\n\nexport interface FlagsHost {\n token: string\n host: string\n ttlMs: number\n remote: 'lazy' | 'eager' | false\n localEvaluation: boolean\n personProperties?: Properties\n storage?: Storage\n distinctId(): string\n groups(): Record<string, string>\n}\n\n/**\n * Flag values from, in order: the server-rendered bootstrap, local evaluation of cached definitions, and the last\n * remote evaluation. Values are synchronous; `onFlags` listeners hear about every change.\n */\nexport class Flags {\n private definitions: Map<string, FlagDefinition> | undefined\n private remoteValues: Record<string, FlagValue> | undefined\n private payloads: Record<string, unknown> = {}\n private requestVersion = 0\n private remoteRequested = false\n /** Definitions are being fetched and none are cached. */\n private started = false\n private loading = false\n /** Keys read while `loading`: asked of the server afterwards if the definitions do not have them. */\n private readonly waiting = new Set<string>()\n private readonly listeners = new Set<(flags: Record<string, FlagValue>) => void>()\n private readonly fetch = globalThis.fetch.bind(globalThis)\n private readonly cacheKey: string\n\n constructor(\n private readonly h: FlagsHost,\n private bootstrap: Bootstrap | undefined,\n ) {\n this.cacheKey = `nb_${h.token}_flags`\n this.payloads = { ...bootstrap?.payloads }\n }\n\n start(storage?: Storage): void {\n if (this.started) return\n this.started = true\n this.h.storage = storage\n if (this.h.localEvaluation) void this.loadDefinitions()\n if (this.h.remote === 'eager') void this.loadRemote()\n this.notify()\n }\n\n /** The flag's value, or `undefined` while unknown (a lazy remote evaluation is then started). */\n value(key: string): FlagValue | undefined {\n const boot = this.bootstrap?.flags?.[key]\n if (boot !== undefined) return boot\n const definition = this.definitions?.get(key)\n const local = definition && evaluate(definition, this.h.distinctId())\n if (local !== undefined) return local\n const remote = this.remoteValues?.[key]\n if (remote === undefined && this.started && this.h.remote && !this.remoteRequested) {\n if (this.loading) this.waiting.add(key)\n else void this.loadRemote()\n }\n return remote\n }\n\n /** Whether the value came from local evaluation (for `locally_evaluated` on exposures). */\n isLocal(key: string): boolean {\n return this.bootstrap?.flags?.[key] === undefined && this.definitions?.has(key) === true\n }\n\n version(key: string): number | undefined {\n return this.definitions?.get(key)?.version\n }\n\n payload(key: string): unknown {\n const value = this.value(key)\n const definition = this.definitions?.get(key)\n const local = definition?.filters.payloads?.[String(value)]\n return value === undefined || value === false ? undefined : (local ?? this.payloads[key])\n }\n\n /** Every known flag's value. */\n all(): Record<string, FlagValue> {\n const keys = new Set([\n ...Object.keys(this.remoteValues ?? {}),\n ...(this.definitions?.keys() ?? []),\n ...Object.keys(this.bootstrap?.flags ?? {}),\n ])\n const out: Record<string, FlagValue> = {}\n for (const key of keys) {\n const value = this.value(key)\n if (value !== undefined) out[key] = value\n }\n return out\n }\n\n /** Calls `listener` now (if anything is known) and on every change. Returns an unsubscribe function. */\n onFlags(listener: (flags: Record<string, FlagValue>) => void): () => void {\n this.listeners.add(listener)\n if (this.bootstrap?.flags || this.definitions || this.remoteValues) listener(this.all())\n return () => this.listeners.delete(listener)\n }\n\n /** The identity changed: bootstrap values belong to the old ID, remote values too. */\n identityChanged(): void {\n this.requestVersion++\n this.payloads = {}\n this.bootstrap = undefined\n this.remoteValues = undefined\n this.remoteRequested = false\n if (this.h.remote === 'eager') void this.loadRemote()\n this.notify()\n }\n\n /** Refetches definitions (ignoring the cache) and, if remote evaluation is on, remote values. */\n async reload(): Promise<void> {\n await Promise.all([this.h.localEvaluation && this.loadDefinitions(true), this.h.remote && this.loadRemote()])\n }\n\n private notify(): void {\n const all = this.all()\n for (const listener of this.listeners) listener(all)\n }\n\n private async loadDefinitions(force = false): Promise<void> {\n let cached: Cached | undefined\n try {\n cached = JSON.parse(this.h.storage?.getItem(this.cacheKey) ?? 'null') ?? undefined\n } catch {\n cached = undefined\n }\n if (cached) this.useDefinitions(cached.f)\n if (cached && !force && Date.now() - cached.t < this.h.ttlMs) return\n this.loading = !this.definitions\n try {\n const response = await this.fetch(`${this.h.host}/v1/flags/definitions?token=${encodeURIComponent(this.h.token)}`, {\n headers: cached?.e ? { 'If-None-Match': cached.e } : {},\n })\n if (response.status === 304 && cached) {\n cached.t = Date.now()\n } else if (response.ok) {\n const body = (await response.json()) as { flags: FlagDefinition[] }\n cached = { t: Date.now(), e: response.headers.get('ETag') ?? undefined, f: body.flags }\n this.useDefinitions(cached.f)\n } else {\n return\n }\n this.h.storage?.setItem(this.cacheKey, JSON.stringify(cached))\n } catch {\n // offline: keep what is cached\n } finally {\n this.loading = false\n const missing = [...this.waiting].some((key) => !this.definitions?.has(key))\n this.waiting.clear()\n if (missing && this.h.remote && !this.remoteRequested) void this.loadRemote()\n }\n }\n\n private useDefinitions(flags: FlagDefinition[]): void {\n this.definitions = new Map(flags.map((f) => [f.key, f]))\n this.notify()\n }\n\n private async loadRemote(): Promise<void> {\n const version = ++this.requestVersion\n this.remoteRequested = true\n try {\n const response = await this.fetch(`${this.h.host}/flags/?v=2`, {\n method: 'POST',\n headers: { 'Content-Type': 'text/plain' },\n body: JSON.stringify({\n token: this.h.token,\n distinct_id: this.h.distinctId(),\n groups: this.h.groups(),\n person_properties: this.h.personProperties ?? {},\n }),\n })\n if (!response.ok) throw new Error('flag request failed')\n const body = (await response.json()) as {\n flags?: Record<string, { enabled: boolean; variant?: string | null; metadata?: { payload?: string | null } }>\n }\n if (version !== this.requestVersion) return\n this.payloads = {}\n const values: Record<string, FlagValue> = {}\n for (const [key, detail] of Object.entries(body.flags ?? {})) {\n values[key] = detail.variant ?? detail.enabled\n const payload = detail.metadata?.payload\n if (payload != null) {\n try {\n this.payloads[key] = JSON.parse(payload)\n } catch {\n this.payloads[key] = payload\n }\n }\n }\n this.remoteValues = values\n this.notify()\n } catch {\n if (version === this.requestVersion) this.remoteRequested = false\n }\n }\n}\n", "/** Random hex of `bytes` bytes. */\nexport function randomHex(bytes: number): string {\n const out = crypto.getRandomValues(new Uint8Array(bytes))\n let hex = ''\n for (const b of out) hex += (b < 16 ? '0' : '') + b.toString(16)\n return hex\n}\n\n/** A UUIDv7 (RFC 9562): 48-bit Unix milliseconds, version 7, variant 10, random bits. */\nexport function uuidv7(now = Date.now()): string {\n const hex = now.toString(16).padStart(12, '0').slice(-12) + randomHex(10)\n const variant = ((parseInt(hex[16]!, 16) & 0x3) | 0x8).toString(16)\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-7${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`\n}\n\n/** The millisecond timestamp of a UUIDv7, or `undefined`. */\nexport function uuidv7Time(id: string): number | undefined {\n return /^[0-9a-f]{8}-[0-9a-f]{4}-7/i.test(id) ? parseInt(id.slice(0, 8) + id.slice(9, 13), 16) : undefined\n}\n", "import type { Properties } from './types'\n\n/** Stored in the first-party cookie: the anonymous ID, the session and consent only. */\nexport interface CookieState {\n /** Anonymous ID. */\n a?: string\n /** Session: [ID, last activity ms, start ms]. */\n s?: [string, number, number]\n /** Consent: 1 opted in, 0 opted out. */\n c?: 0 | 1\n}\n\n/** Stored in localStorage. */\nexport interface LocalState {\n /** Distinct ID once identified. */\n d?: string\n /** Identified. */\n i?: 1\n /** Super properties. */\n p?: Properties\n /** Groups. */\n g?: Record<string, string>\n}\n\nexport type Mode = 'cookie' | 'localStorage' | 'memory'\n\nfunction readJson<T>(text: string | null | undefined): T | undefined {\n try {\n return text ? (JSON.parse(text) as T) : undefined\n } catch {\n return undefined\n }\n}\n\nexport function local(): Storage | undefined {\n try {\n const s = window.localStorage\n s.setItem('__nb', '1')\n s.removeItem('__nb')\n return s\n } catch {\n return undefined\n }\n}\n\nexport function readCookie(name: string): string | undefined {\n try {\n for (const part of document.cookie.split(';')) {\n const i = part.indexOf('=')\n if (part.slice(0, i).trim() === name) return decodeURIComponent(part.slice(i + 1).trim())\n }\n } catch {\n // no document\n }\n return undefined\n}\n\nexport class Persistence {\n cookie: CookieState\n local: LocalState\n private readonly store: Storage | undefined\n\n constructor(\n private readonly name: string,\n private readonly mode: Mode,\n private readonly domain?: string,\n ) {\n this.store = mode === 'memory' ? undefined : local()\n const fromStore = readJson<CookieState & LocalState>(this.store?.getItem(name))\n this.cookie = (mode === 'cookie' ? readJson<CookieState>(readCookie(name)) : fromStore) ?? {}\n this.local = fromStore ?? {}\n }\n\n save(): void {\n const { d, i, p, g } = this.local\n if (this.mode === 'cookie') {\n const secure = location.protocol === 'https:' ? '; Secure' : ''\n const domain = this.domain ? `; domain=${this.domain}` : ''\n document.cookie = `${this.name}=${encodeURIComponent(JSON.stringify(this.cookie))}; path=/; max-age=31536000; SameSite=Lax${domain}${secure}`\n }\n const value = this.mode === 'cookie' ? { d, i, p, g } : { ...this.cookie, d, i, p, g }\n try {\n this.store?.setItem(this.name, JSON.stringify(value))\n } catch {\n // quota or privacy mode\n }\n }\n}\n\ninterface PostHogState {\n distinct_id?: string\n $device_id?: string\n $user_state?: string\n /** Person processing enabled (set by identify under `person_profiles: 'identified_only'`). */\n $epp?: boolean\n $sesid?: [number, string, number]\n}\n\n/**\n * Identity and session from posthog-js's persistence entry `ph_{token}_posthog`. With posthog-js 1.234's default\n * `localStorage+cookie`, the cookie holds only `distinct_id`, `$sesid` and `$epp`; `$device_id` and `$user_state`\n * are in localStorage under the same name, which counts only if it belongs to the same `distinct_id` (the cookie\n * may come from another subdomain). Without it, `$epp` tells whether the user was identified.\n */\nexport function postHogIdentity(token: boolean | string): { cookie: CookieState; local: LocalState } | undefined {\n const name =\n typeof token === 'string' ? `ph_${token}_posthog` : document.cookie.match(/(?:^|;\\s*)(ph_[^=]+_posthog)=/)?.[1]\n if (!name) return undefined\n const cookie = readJson<PostHogState>(readCookie(name))\n const stored = readJson<PostHogState>(local()?.getItem(name))\n const ph = cookie ?? stored\n if (!ph?.distinct_id) return undefined\n const full = stored?.distinct_id === ph.distinct_id ? { ...stored, ...ph } : ph\n const identified = full.$user_state ? full.$user_state === 'identified' : full.$epp === true\n // An anonymous user's events went out under `distinct_id`; once identified, `$device_id` is the anonymous ID.\n const anon = identified ? (full.$device_id ?? ph.distinct_id) : ph.distinct_id\n const s = full.$sesid\n return {\n cookie: { a: anon, s: s?.[1] ? [s[1], s[0], s[2]] : undefined },\n local: identified ? { d: ph.distinct_id, i: 1 } : {},\n }\n}\n", "import type { TracingOptions } from './types'\nimport { randomHex } from './uuid'\n\n/** The page's W3C trace: adopted from `<meta name=\"traceparent\">` (server rendering), else generated. */\nexport class Trace {\n traceId: string\n parentId: string | undefined\n\n constructor() {\n const meta = typeof document !== 'undefined' ? document.querySelector('meta[name=\"traceparent\"]') : null\n const match = meta?.getAttribute('content')?.match(/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/)\n this.traceId = match?.[1] ?? randomHex(16)\n this.parentId = match?.[2]\n }\n\n /** A new trace, for example on a client-side navigation. */\n rotate(): void {\n this.traceId = randomHex(16)\n this.parentId = undefined\n }\n\n /** A `traceparent` header for an outgoing request: this trace, a new span ID, sampled. */\n header(): string {\n return `00-${this.traceId}-${randomHex(8)}-01`\n }\n}\n\nfunction matches(url: URL, targets: TracingOptions['propagateTo']): boolean {\n if (!targets) return false\n if (targets === 'same-origin') return url.origin === location.origin\n return targets.some((target) => {\n if (typeof target !== 'string') return target.test(url.href)\n try {\n const allowed = new URL(target)\n return url.origin === allowed.origin && url.href.startsWith(allowed.href)\n } catch {\n return false\n }\n })\n}\n\n/**\n * Wraps `window.fetch` so requests to the configured targets carry `traceparent` and `baggage` (`session.id`,\n * `user.id`), letting backend spans join the page's trace and know the user. Returns a function that restores\n * `fetch`.\n */\nexport function propagate(trace: Trace, options: TracingOptions, baggage: () => Record<string, string>): () => void {\n const targets = options.propagateTo ?? 'same-origin'\n if (!targets || typeof window === 'undefined' || !window.fetch) return () => {}\n const original = window.fetch\n let active = true\n const wrapped: typeof window.fetch = function (this: Window, input, init) {\n if (!active) return original.call(this, input, init)\n try {\n const url = new URL(input instanceof Request ? input.url : String(input), location.href)\n if (matches(url, targets)) {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))\n if (!headers.has('traceparent')) headers.set('traceparent', trace.header())\n if (options.baggage !== false) {\n const entries = Object.entries(baggage()).map(([k, v]) => `${k}=${encodeURIComponent(v)}`)\n const existing = headers.get('baggage')\n if (entries.length) headers.set('baggage', existing ? `${existing},${entries.join(',')}` : entries.join(','))\n }\n init = { ...init, headers }\n }\n } catch {\n // leave the request as it is\n }\n return original.call(this, input, init)\n }\n window.fetch = wrapped\n return () => {\n active = false\n if (window.fetch === wrapped) window.fetch = original\n }\n}\n", "import type { CaptureEvent } from './types'\n\nexport interface TransportOptions {\n url: string\n token: string\n flushIntervalMs: number\n maxBatchSize: number\n perSecond: number\n burst: number\n}\n\nconst MAX_RETRIES = 10\n/** `fetch` with `keepalive` allows at most 64 KiB in flight. */\nconst KEEPALIVE_LIMIT = 60_000\n\n/** Gzip with `CompressionStream`, or `undefined` where it is not available. */\nexport async function gzip(text: string): Promise<Blob | undefined> {\n if (typeof CompressionStream === 'undefined') return undefined\n try {\n return await new Response(new Response(text).body!.pipeThrough(new CompressionStream('gzip'))).blob()\n } catch {\n return undefined\n }\n}\n\n/**\n * The capture queue: batches every `flushIntervalMs` or `maxBatchSize` events, gzips with `CompressionStream`,\n * retries with exponential backoff and jitter, rate-limits with a token bucket, and sends what is left with\n * `sendBeacon` when the page is hidden.\n */\nexport class Transport {\n private queue: CaptureEvent[] = []\n private timer: ReturnType<typeof setTimeout> | undefined\n private tokens: number\n private refilled = Date.now()\n private readonly fetch = globalThis.fetch.bind(globalThis)\n\n constructor(private readonly o: TransportOptions) {\n this.tokens = o.burst\n }\n\n /** Queues an event. Returns false if the rate limit dropped it. */\n push(event: CaptureEvent, beacon = false): boolean {\n const now = Date.now()\n this.tokens = Math.min(this.o.burst, this.tokens + ((now - this.refilled) / 1000) * this.o.perSecond)\n this.refilled = now\n if (this.tokens < 1) return false\n this.tokens -= 1\n this.queue.push(event)\n if (beacon) this.flush(true)\n else if (this.queue.length >= this.o.maxBatchSize) void this.flush()\n else this.timer ??= setTimeout(() => void this.flush(), this.o.flushIntervalMs)\n return true\n }\n\n /** Sends everything queued; with `beacon`, synchronously through `sendBeacon` (page hide). */\n flush(beacon = false): Promise<void> {\n clearTimeout(this.timer)\n this.timer = undefined\n const batch = this.queue.splice(0)\n if (!batch.length) return Promise.resolve()\n const body = JSON.stringify({ api_key: this.o.token, batch, sent_at: new Date().toISOString() })\n if (beacon && navigator.sendBeacon?.(`${this.o.url}?beacon=1`, new Blob([body], { type: 'text/plain' }))) {\n return Promise.resolve()\n }\n return this.send(body, batch, 0)\n }\n\n private async send(body: string, batch: CaptureEvent[], attempt: number): Promise<void> {\n let ok = false\n let retry = true\n try {\n const compressed = body.length > 1024 ? await gzip(body) : undefined\n const url = compressed ? `${this.o.url}?compression=gzip-js` : this.o.url\n const response = await this.fetch(url, {\n method: 'POST',\n // text/plain keeps cross-origin requests free of a CORS preflight.\n headers: { 'Content-Type': 'text/plain' },\n body: compressed ?? body,\n keepalive: (compressed?.size ?? body.length) < KEEPALIVE_LIMIT,\n })\n ok = response.ok\n retry = response.status >= 500 || response.status === 429\n } catch {\n // network error: retry\n }\n if (ok || !retry || attempt >= MAX_RETRIES) return\n const delay = Math.min(30_000, 1000 * 2 ** attempt) * (0.5 + Math.random())\n await new Promise((resolve) => setTimeout(resolve, delay))\n return this.send(body, batch, attempt + 1)\n }\n}\n", "import { Flags } from './flags'\nimport { Persistence, local, postHogIdentity } from './storage'\nimport { Trace, propagate } from './trace'\nimport { Transport } from './transport'\nimport type { BeforeSend, CaptureEvent, FlagValue, NumbunchOptions, Properties } from './types'\nimport { uuidv7 } from './uuid'\n\nexport const VERSION = '0.1.0'\nexport const LIB = 'numbunch-web'\nconst DEFAULT_HOST = 'https://in.numbunch.com'\n/** The distinct ID the server replaces with a daily visitor hash in cookieless mode (milestone 2). */\nconst COOKIELESS_ID = '$posthog_cookieless'\nconst MINUTE = 60_000\n\n/** Campaign parameters and ad click IDs copied from the page URL onto events (milestone 2's list). */\nconst CAMPAIGN_PARAMS = [\n 'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'gad_source', 'mc_cid',\n 'gclid', 'gclsrc', 'dclid', 'gbraid', 'wbraid', 'fbclid', 'msclkid', 'twclid', 'li_fat_id', 'igshid', 'ttclid',\n 'rdt_cid', 'epik', 'qclid', 'sccid', 'irclid',\n]\n\nexport interface CaptureOptions {\n /** `sendBeacon` sends at once, surviving navigation. */\n transport?: 'sendBeacon'\n timestamp?: Date\n uuid?: string\n $set?: Properties\n $set_once?: Properties\n}\n\nexport interface FlagReadOptions {\n /** Record an exposure (`$feature_flag_called`). Default true. */\n sendEvent?: boolean\n}\n\n/** The Numbunch browser client. Create one per page with {@link init} or `new Numbunch(token, options)`. */\nexport class Numbunch {\n readonly token: string\n readonly options: NumbunchOptions\n readonly apiHost: string\n readonly flags: Flags\n readonly trace: Trace\n private persistence = new Persistence('', 'memory')\n private lifetime?: AbortController\n private initialized = false\n private readonly transport: Transport\n private readonly hooks: BeforeSend[]\n private readonly exposures = new Set<string>()\n private pageviews = 0\n\n constructor(token: string, options: NumbunchOptions = {}, deferred = false) {\n const o = options\n this.token = token\n this.options = o\n this.apiHost = (o.apiHost ?? DEFAULT_HOST).replace(/\\/$/, '')\n this.hooks = o.beforeSend ? ([] as BeforeSend[]).concat(o.beforeSend) : []\n const f = o.flags ?? {}\n this.transport = new Transport({\n url: `${this.apiHost}/batch/`,\n token,\n flushIntervalMs: o.flushIntervalMs ?? 3000,\n maxBatchSize: o.maxBatchSize ?? 50,\n perSecond: o.rateLimit?.perSecond ?? 10,\n burst: o.rateLimit?.burst ?? 100,\n })\n this.flags = new Flags(\n {\n token,\n host: (o.flagsHost ?? this.apiHost).replace(/\\/$/, ''),\n ttlMs: f.cacheTtlMs ?? 5 * MINUTE,\n remote: f.remote ?? 'lazy',\n localEvaluation: f.localEvaluation !== false,\n personProperties: f.personProperties,\n distinctId: () => (o.cookieless ? this.persistence.cookie.a! : this.getDistinctId()),\n groups: () => this.persistence.local.g ?? {},\n },\n o.bootstrap,\n )\n this.trace = new Trace()\n this.persistence.cookie.a = o.bootstrap?.distinctId ?? uuidv7()\n if (!deferred) this.start()\n }\n\n /** Attach browser integrations after mount. A deferred client can read its bootstrap during SSR. */\n start(): void {\n if (this.lifetime) return\n const lifetime = new AbortController()\n this.lifetime = lifetime\n const o = this.options\n const first = !this.initialized\n if (first) {\n this.initialized = true\n this.loadIdentity()\n this.flags.start(o.cookieless || o.persistence === 'memory' ? undefined : local())\n }\n const restore = propagate(this.trace, o.tracing ?? {}, () => {\n const out: Record<string, string> = { 'session.id': this.getSessionId() }\n if (!o.cookieless) out['user.id'] = this.getDistinctId()\n return out\n })\n lifetime.signal.addEventListener('abort', restore, { once: true })\n if (typeof window !== 'undefined') {\n const hidden = () => {\n if (o.capturePageleave) this.capture('$pageleave', {}, { transport: 'sendBeacon' })\n void this.transport.flush(true)\n }\n window.addEventListener('pagehide', hidden, { signal: lifetime.signal })\n document.addEventListener('visibilitychange', () => document.visibilityState === 'hidden' && void this.transport.flush(true), { signal: lifetime.signal })\n }\n if (first && o.capturePageview) this.pageview()\n if (o.remoteConfig) void this.loadRemoteConfig(lifetime.signal)\n if (first) o.loaded?.(this)\n }\n\n /** Release integrations owned by this client and send remaining events. */\n stop(): void {\n this.lifetime?.abort()\n this.lifetime = undefined\n void this.transport.flush()\n }\n\n private loadIdentity(): void {\n const o = this.options\n const p = (this.persistence = new Persistence(`nb_${this.token}`, o.cookieless ? 'memory' : (o.persistence ?? 'cookie'), o.cookieDomain))\n if (!p.cookie.a) {\n const adopted = o.adoptPostHogCookie ? postHogIdentity(o.adoptPostHogCookie) : undefined\n if (adopted) {\n p.cookie = { ...adopted.cookie, c: p.cookie.c }\n p.local = { ...p.local, ...adopted.local }\n } else {\n p.cookie.a = uuidv7()\n }\n }\n const boot = o.bootstrap\n if (boot?.distinctId && boot.distinctId !== this.getDistinctId()) {\n if (boot.isIdentified) p.local = { ...p.local, d: boot.distinctId, i: 1 }\n else if (!p.local.i) p.cookie.a = boot.distinctId\n }\n p.save()\n }\n\n /** The ID events are sent under: the identified ID, else the anonymous one. */\n getDistinctId(): string {\n if (this.options.cookieless) return COOKIELESS_ID\n return this.persistence.local.d ?? this.persistence.cookie.a!\n }\n\n /** The anonymous (device) ID, kept across `identify` until `reset`. */\n getAnonymousId(): string {\n return this.persistence.cookie.a!\n }\n\n /**\n * Uses `id` as the anonymous ID (for example one a server assigned in a cookie). Ignored once identified, so\n * an identified user keeps their identity.\n */\n adoptAnonymousId(id: string): void {\n if (!id || this.isIdentified() || id === this.persistence.cookie.a) return\n this.persistence.cookie.a = id\n this.persistence.save()\n this.flags.identityChanged()\n }\n\n isIdentified(): boolean {\n return this.persistence.local.i === 1\n }\n\n /** The current session ID (UUIDv7). Sessions end after 30 minutes without events or after 24 hours. */\n getSessionId(): string {\n return this.session(false)\n }\n\n private session(activity: boolean): string {\n const p = this.persistence\n const now = Date.now()\n const stored = p.cookie.s ?? ['', 0, 0]\n const last = stored[1]\n let [id, , start] = stored\n const expired = now - last > (this.options.sessionIdleMs ?? 30 * MINUTE) || now - start > (this.options.sessionMaxMs ?? 24 * 60 * MINUTE)\n if (!id || expired) {\n id = uuidv7(now)\n start = now\n activity = true\n }\n if (activity) {\n p.cookie.s = [id, now, start]\n p.save()\n }\n return id\n }\n\n /** Captures an event. Returns it, or `undefined` if consent, a `beforeSend` hook or the rate limit dropped it. */\n capture(event: string, properties: Properties = {}, options: CaptureOptions = {}): CaptureEvent | undefined {\n if (!this.lifetime || this.hasOptedOut()) return undefined\n const o = this.options\n const p = this.persistence\n const identified = this.isIdentified()\n const props: Properties = {\n ...this.context(),\n ...p.local.p,\n ...properties,\n distinct_id: this.getDistinctId(),\n $lib: LIB,\n $lib_version: VERSION,\n $trace_id: this.trace.traceId,\n $process_person_profile: identified || o.personProfiles === 'always',\n $is_identified: identified,\n }\n if (!o.cookieless) {\n props.$session_id = this.session(true)\n props.$device_id = p.cookie.a\n }\n if (p.local.g && Object.keys(p.local.g).length) props.$groups = p.local.g\n if (options.$set) props.$set = options.$set\n if (options.$set_once) props.$set_once = options.$set_once\n let out: CaptureEvent | null = {\n event,\n properties: props,\n timestamp: (options.timestamp ?? new Date()).toISOString(),\n uuid: options.uuid ?? uuidv7(),\n }\n for (const hook of this.hooks) {\n out = out && hook(out)\n }\n if (!out) return undefined\n return this.transport.push(out, options.transport === 'sendBeacon') ? out : undefined\n }\n\n /** Page and campaign properties added to every event. */\n private context(): Properties {\n if (typeof location === 'undefined') return {}\n const referrer = document.referrer\n let referringDomain = '$direct'\n try {\n if (referrer) referringDomain = new URL(referrer).host\n } catch {\n // not a URL\n }\n const out: Properties = {\n $current_url: location.href,\n $host: location.host,\n $pathname: location.pathname,\n $referrer: referrer || '$direct',\n $referring_domain: referringDomain,\n $screen_height: screen.height,\n $screen_width: screen.width,\n $viewport_height: innerHeight,\n $viewport_width: innerWidth,\n $browser_language: navigator.language,\n }\n const params = new URLSearchParams(location.search)\n for (const key of CAMPAIGN_PARAMS) {\n const value = params.get(key)\n if (value) out[key] = value\n }\n return out\n }\n\n /** Captures `$pageview`. Every pageview after the first starts a new trace (a client-side navigation). */\n pageview(properties: Properties = {}): CaptureEvent | undefined {\n if (this.pageviews++) this.trace.rotate()\n return this.capture('$pageview', { title: typeof document !== 'undefined' ? document.title : undefined, ...properties })\n }\n\n pageleave(properties: Properties = {}): CaptureEvent | undefined {\n return this.capture('$pageleave', properties, { transport: 'sendBeacon' })\n }\n\n /**\n * Links the anonymous ID to `distinctId` (`$identify` with `$anon_distinct_id`) and starts sending person\n * profiles. `set` and `setOnce` become person properties.\n */\n identify(distinctId: string, set?: Properties, setOnce?: Properties): void {\n if (!distinctId || this.options.cookieless) return\n const previous = this.getDistinctId()\n if (distinctId === previous && this.isIdentified()) {\n if (set || setOnce) this.setPersonProperties(set, setOnce)\n return\n }\n this.persistence.local = { ...this.persistence.local, d: distinctId, i: 1 }\n this.persistence.save()\n this.capture('$identify', { $anon_distinct_id: previous }, { $set: set, $set_once: setOnce })\n this.exposures.clear()\n this.flags.identityChanged()\n }\n\n /** Forgets the user: new anonymous ID and session, no super properties or groups. Consent is kept. */\n reset(): void {\n const p = this.persistence\n p.cookie = { a: uuidv7(), c: p.cookie.c }\n p.local = {}\n p.save()\n this.trace.rotate()\n this.exposures.clear()\n this.flags.identityChanged()\n }\n\n /** Super properties, sent with every event. */\n register(properties: Properties): void {\n this.persistence.local.p = { ...this.persistence.local.p, ...properties }\n this.persistence.save()\n }\n\n registerOnce(properties: Properties): void {\n this.register({ ...properties, ...this.persistence.local.p })\n }\n\n unregister(key: string): void {\n delete this.persistence.local.p?.[key]\n this.persistence.save()\n }\n\n /** Sets person properties (`$set`, `$set_once`). */\n setPersonProperties(set?: Properties, setOnce?: Properties): void {\n this.capture('$set', {}, { $set: set ?? {}, $set_once: setOnce })\n }\n\n /** Associates later events with a group; `properties` are stored on the group (`$groupidentify`). */\n group(type: string, key: string, properties?: Properties): void {\n const changed = this.persistence.local.g?.[type] !== key\n this.persistence.local.g = { ...this.persistence.local.g, [type]: key }\n this.persistence.save()\n if (changed) {\n this.exposures.clear()\n this.flags.identityChanged()\n }\n if (properties) this.capture('$groupidentify', { $group_type: type, $group_key: key, $group_set: properties })\n }\n\n optIn(options: { captureEvent?: boolean } = {}): void {\n this.persistence.cookie.c = 1\n this.persistence.save()\n if (options.captureEvent !== false) this.capture('$opt_in')\n }\n\n optOut(): void {\n this.persistence.cookie.c = 0\n this.persistence.save()\n }\n\n hasOptedIn(): boolean {\n return this.persistence.cookie.c === 1\n }\n\n hasOptedOut(): boolean {\n const consent = this.persistence.cookie.c\n return consent === 0 || (consent === undefined && this.options.optOutByDefault === true)\n }\n\n /** The flag's value, synchronously; `undefined` while unknown. Records an exposure once per flag and value. */\n getVariant(key: string, options: FlagReadOptions = {}): FlagValue | undefined {\n const value = this.flags.value(key)\n if (value !== undefined && options.sendEvent !== false && this.options.flags?.sendExposure !== false) {\n const seen = `${key}\\u0000${value}`\n if (!this.exposures.has(seen)) {\n this.exposures.add(seen)\n this.capture('$feature_flag_called', {\n $feature_flag: key,\n $feature_flag_response: value,\n [`$feature/${key}`]: value,\n $feature_flag_version: this.flags.version(key),\n locally_evaluated: this.flags.isLocal(key),\n })\n }\n }\n return value\n }\n\n /** Whether the flag is on (any variant counts); `undefined` while unknown. */\n isEnabled(key: string, options?: FlagReadOptions): boolean | undefined {\n const value = this.getVariant(key, options)\n return value === undefined ? undefined : value !== false\n }\n\n getFlagPayload(key: string): unknown {\n return this.flags.payload(key)\n }\n\n /** Every known flag value, without recording exposures. */\n getFlags(): Record<string, FlagValue> {\n return this.flags.all()\n }\n\n /** Calls `listener` with all values now (if known) and whenever they change. Returns an unsubscribe function. */\n onFlags(listener: (flags: Record<string, FlagValue>) => void): () => void {\n return this.flags.onFlags(listener)\n }\n\n reloadFlags(): Promise<void> {\n return this.flags.reload()\n }\n\n /** A `traceparent` for a request made outside `fetch` (for example `XMLHttpRequest`). */\n traceparent(): string {\n return this.trace.header()\n }\n\n /** Sends queued events now. */\n flush(): Promise<void> {\n return this.transport.flush()\n }\n\n private async loadRemoteConfig(signal: AbortSignal): Promise<void> {\n try {\n const response = await fetch(`${this.apiHost}/array/${encodeURIComponent(this.token)}/config`, { signal })\n const config = (await response.json()) as {\n autocaptureExceptions?: boolean\n capturePerformance?: { web_vitals?: boolean; web_vitals_allowed_metrics?: string[] } | false\n }\n if (config.autocaptureExceptions) {\n const { exceptionAutocapture } = await import('./exceptions')\n if (signal.aborted) return\n signal.addEventListener('abort', exceptionAutocapture(this), { once: true })\n }\n const performance = config.capturePerformance\n if (performance && performance.web_vitals) {\n const { webVitals } = await import('./web-vitals')\n if (!signal.aborted) webVitals(this, { metrics: performance.web_vitals_allowed_metrics, signal })\n }\n } catch {\n // remote config is optional\n }\n }\n}\n\n/** Creates the client. */\nexport function init(token: string, options?: NumbunchOptions): Numbunch {\n return new Numbunch(token, options)\n}\n"],
|
|
4
|
+
"sourcesContent": ["// MurmurHash3 x86 32-bit (Austin Appleby, public domain) and the `murmur3_v1` bucketing value (ADR 0007).\n\nconst encoder = /* @__PURE__ */ new TextEncoder()\n\n/** `murmur3_x86_32` of the UTF-8 bytes of `input`. */\nexport function murmur3(input: string, seed = 0): number {\n const data = encoder.encode(input)\n const length = data.length\n const blocks = length & ~3\n let h = seed >>> 0\n let k: number\n for (let i = 0; i < blocks; i += 4) {\n k = data[i]! | (data[i + 1]! << 8) | (data[i + 2]! << 16) | (data[i + 3]! << 24)\n h ^= mix(k)\n h = (h << 13) | (h >>> 19)\n h = (Math.imul(h, 5) + 0xe6546b64) | 0\n }\n const tail = length & 3\n if (tail) {\n k = 0\n for (let i = tail - 1; i >= 0; i--) k = (k << 8) | data[blocks + i]!\n h ^= mix(k)\n }\n h ^= length\n h ^= h >>> 16\n h = Math.imul(h, 0x85ebca6b)\n h ^= h >>> 13\n h = Math.imul(h, 0xc2b2ae35)\n h ^= h >>> 16\n return h >>> 0\n}\n\nfunction mix(k: number): number {\n k = Math.imul(k, 0xcc9e2d51)\n k = (k << 15) | (k >>> 17)\n return Math.imul(k, 0x1b873593)\n}\n\n/** `murmur3(\"{key}.{id}{salt}\") / 2^32`, in [0, 1). The holdout value is `bucket(\"holdout-{holdout_id}\", id)`. */\nexport function bucket(key: string, id: string, salt = ''): number {\n return murmur3(`${key}.${id}${salt}`) / 4294967296\n}\n", "import { bucket } from './murmur3'\nimport type { Bootstrap, FlagValue, Properties } from './types'\n\n/** One flag from `GET /v1/flags/definitions?token=` (only client-evaluable flags are served there). */\nexport interface FlagDefinition {\n key: string\n version?: number\n active: boolean\n bucketing: string\n filters: {\n groups?: { properties?: unknown[]; rollout_percentage?: number | null; variant?: string | null }[]\n multivariate?: { variants: { key: string; rollout_percentage: number }[] } | null\n payloads?: Record<string, unknown>\n }\n holdout?: { id: number; percentage: number } | null\n}\n\n/**\n * Evaluates a client-evaluable flag for `id` with `murmur3_v1`: the condition sets (those pinning a variant first)\n * and the rollout, then for a targeted user the holdout and the variant walk. `undefined` if the definition needs the server.\n */\nexport function evaluate(flag: FlagDefinition, id: string): FlagValue | undefined {\n if (flag.bucketing !== 'murmur3_v1') return undefined\n if (!flag.active) return false\n const { key, holdout, filters } = flag\n const variants = filters.multivariate?.variants ?? []\n const groups = [...(filters.groups ?? [])].sort((a, b) => Number(!a.variant) - Number(!b.variant))\n for (const group of groups) {\n if (group.properties?.length) return undefined\n if (bucket(key, id) < (group.rollout_percentage ?? 100) / 100) {\n if (holdout && bucket(`holdout-${holdout.id}`, id) < holdout.percentage / 100) return `holdout-${holdout.id}`\n if (group.variant && variants.some((v) => v.key === group.variant)) return group.variant\n if (!variants.length) return true\n const value = bucket(key, id, 'variant')\n let cumulative = 0\n for (const variant of variants) {\n cumulative += variant.rollout_percentage / 100\n if (value < cumulative) return variant.key\n }\n return true\n }\n }\n return false\n}\n\ninterface Cached {\n /** Fetched at (ms). */\n t: number\n /** ETag. */\n e?: string\n f: FlagDefinition[]\n}\n\nexport interface FlagsHost {\n token: string\n host: string\n ttlMs: number\n remote: 'lazy' | 'eager' | false\n localEvaluation: boolean\n personProperties?: Properties\n storage?: Storage\n distinctId(): string\n groups(): Record<string, string>\n}\n\n/**\n * Flag values from, in order: the server-rendered bootstrap, local evaluation of cached definitions, and the last\n * remote evaluation. Values are synchronous; `onFlags` listeners hear about every change.\n */\nexport class Flags {\n private definitions: Map<string, FlagDefinition> | undefined\n private remoteValues: Record<string, FlagValue> | undefined\n private payloads: Record<string, unknown> = {}\n private requestVersion = 0\n private remoteRequested = false\n /** Definitions are being fetched and none are cached. */\n private started = false\n private loading = false\n /** Keys read while `loading`: asked of the server afterwards if the definitions do not have them. */\n private readonly waiting = new Set<string>()\n private readonly listeners = new Set<(flags: Record<string, FlagValue>) => void>()\n private readonly fetch = globalThis.fetch.bind(globalThis)\n private readonly cacheKey: string\n\n constructor(\n private readonly h: FlagsHost,\n private bootstrap: Bootstrap | undefined,\n ) {\n this.cacheKey = `nb_${h.token}_flags`\n this.payloads = { ...bootstrap?.payloads }\n }\n\n start(storage?: Storage): void {\n if (this.started) return\n this.started = true\n this.h.storage = storage\n if (this.h.localEvaluation) void this.loadDefinitions()\n if (this.h.remote === 'eager') void this.loadRemote()\n this.notify()\n }\n\n /** The flag's value, or `undefined` while unknown (a lazy remote evaluation is then started). */\n value(key: string): FlagValue | undefined {\n const boot = this.bootstrap?.flags?.[key]\n if (boot !== undefined) return boot\n const definition = this.definitions?.get(key)\n const local = definition && evaluate(definition, this.h.distinctId())\n if (local !== undefined) return local\n const remote = this.remoteValues?.[key]\n if (remote === undefined && this.started && this.h.remote && !this.remoteRequested) {\n if (this.loading) this.waiting.add(key)\n else void this.loadRemote()\n }\n return remote\n }\n\n /** Whether the value came from local evaluation (for `locally_evaluated` on exposures). */\n isLocal(key: string): boolean {\n return this.bootstrap?.flags?.[key] === undefined && this.definitions?.has(key) === true\n }\n\n version(key: string): number | undefined {\n return this.definitions?.get(key)?.version\n }\n\n payload(key: string): unknown {\n const value = this.value(key)\n const definition = this.definitions?.get(key)\n const local = definition?.filters.payloads?.[String(value)]\n return value === undefined || value === false ? undefined : (local ?? this.payloads[key])\n }\n\n /** Every known flag's value. */\n all(): Record<string, FlagValue> {\n const keys = new Set([\n ...Object.keys(this.remoteValues ?? {}),\n ...(this.definitions?.keys() ?? []),\n ...Object.keys(this.bootstrap?.flags ?? {}),\n ])\n const out: Record<string, FlagValue> = {}\n for (const key of keys) {\n const value = this.value(key)\n if (value !== undefined) out[key] = value\n }\n return out\n }\n\n /** Calls `listener` now (if anything is known) and on every change. Returns an unsubscribe function. */\n onFlags(listener: (flags: Record<string, FlagValue>) => void): () => void {\n this.listeners.add(listener)\n if (this.bootstrap?.flags || this.definitions || this.remoteValues) listener(this.all())\n return () => this.listeners.delete(listener)\n }\n\n /** The identity changed: bootstrap values belong to the old ID, remote values too. */\n identityChanged(): void {\n this.requestVersion++\n this.payloads = {}\n this.bootstrap = undefined\n this.remoteValues = undefined\n this.remoteRequested = false\n if (this.h.remote === 'eager') void this.loadRemote()\n this.notify()\n }\n\n /** Refetches definitions (ignoring the cache) and, if remote evaluation is on, remote values. */\n async reload(): Promise<void> {\n await Promise.all([this.h.localEvaluation && this.loadDefinitions(true), this.h.remote && this.loadRemote()])\n }\n\n private notify(): void {\n const all = this.all()\n for (const listener of this.listeners) listener(all)\n }\n\n private async loadDefinitions(force = false): Promise<void> {\n let cached: Cached | undefined\n try {\n cached = JSON.parse(this.h.storage?.getItem(this.cacheKey) ?? 'null') ?? undefined\n } catch {\n cached = undefined\n }\n if (cached) this.useDefinitions(cached.f)\n if (cached && !force && Date.now() - cached.t < this.h.ttlMs) return\n this.loading = !this.definitions\n try {\n const response = await this.fetch(`${this.h.host}/v1/flags/definitions?token=${encodeURIComponent(this.h.token)}`, {\n headers: cached?.e ? { 'If-None-Match': cached.e } : {},\n })\n if (response.status === 304 && cached) {\n cached.t = Date.now()\n } else if (response.ok) {\n const body = (await response.json()) as { flags: FlagDefinition[] }\n cached = { t: Date.now(), e: response.headers.get('ETag') ?? undefined, f: body.flags }\n this.useDefinitions(cached.f)\n } else {\n return\n }\n this.h.storage?.setItem(this.cacheKey, JSON.stringify(cached))\n } catch {\n // offline: keep what is cached\n } finally {\n this.loading = false\n const missing = [...this.waiting].some((key) => !this.definitions?.has(key))\n this.waiting.clear()\n if (missing && this.h.remote && !this.remoteRequested) void this.loadRemote()\n }\n }\n\n private useDefinitions(flags: FlagDefinition[]): void {\n this.definitions = new Map(flags.map((f) => [f.key, f]))\n this.notify()\n }\n\n private async loadRemote(): Promise<void> {\n const version = ++this.requestVersion\n this.remoteRequested = true\n try {\n const response = await this.fetch(`${this.h.host}/flags/?v=2`, {\n method: 'POST',\n headers: { 'Content-Type': 'text/plain' },\n body: JSON.stringify({\n token: this.h.token,\n distinct_id: this.h.distinctId(),\n groups: this.h.groups(),\n person_properties: this.h.personProperties ?? {},\n }),\n })\n if (!response.ok) throw new Error('flag request failed')\n const body = (await response.json()) as {\n flags?: Record<string, { enabled: boolean; variant?: string | null; metadata?: { payload?: string | null } }>\n }\n if (version !== this.requestVersion) return\n this.payloads = {}\n const values: Record<string, FlagValue> = {}\n for (const [key, detail] of Object.entries(body.flags ?? {})) {\n values[key] = detail.variant ?? detail.enabled\n const payload = detail.metadata?.payload\n if (payload != null) {\n try {\n this.payloads[key] = JSON.parse(payload)\n } catch {\n this.payloads[key] = payload\n }\n }\n }\n this.remoteValues = values\n this.notify()\n } catch {\n if (version === this.requestVersion) this.remoteRequested = false\n }\n }\n}\n", "/** Random hex of `bytes` bytes. */\nexport function randomHex(bytes: number): string {\n const out = crypto.getRandomValues(new Uint8Array(bytes))\n let hex = ''\n for (const b of out) hex += (b < 16 ? '0' : '') + b.toString(16)\n return hex\n}\n\n/** A UUIDv7 (RFC 9562): 48-bit Unix milliseconds, version 7, variant 10, random bits. */\nexport function uuidv7(now = Date.now()): string {\n const hex = now.toString(16).padStart(12, '0').slice(-12) + randomHex(10)\n const variant = ((parseInt(hex[16]!, 16) & 0x3) | 0x8).toString(16)\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-7${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`\n}\n\n/** The millisecond timestamp of a UUIDv7, or `undefined`. */\nexport function uuidv7Time(id: string): number | undefined {\n return /^[0-9a-f]{8}-[0-9a-f]{4}-7/i.test(id) ? parseInt(id.slice(0, 8) + id.slice(9, 13), 16) : undefined\n}\n", "import type { Properties } from './types'\n\n/** Stored in the first-party cookie: the anonymous ID, the session and consent only. */\nexport interface CookieState {\n /** Anonymous ID. */\n a?: string\n /** Session: [ID, last activity ms, start ms]. */\n s?: [string, number, number]\n /** Consent: 1 opted in, 0 opted out. */\n c?: 0 | 1\n}\n\n/** Stored in localStorage. */\nexport interface LocalState {\n /** Distinct ID once identified. */\n d?: string\n /** Identified. */\n i?: 1\n /** Super properties. */\n p?: Properties\n /** Groups. */\n g?: Record<string, string>\n}\n\nexport type Mode = 'cookie' | 'localStorage' | 'memory'\n\nfunction readJson<T>(text: string | null | undefined): T | undefined {\n try {\n return text ? (JSON.parse(text) as T) : undefined\n } catch {\n return undefined\n }\n}\n\nexport function local(): Storage | undefined {\n try {\n const s = window.localStorage\n s.setItem('__nb', '1')\n s.removeItem('__nb')\n return s\n } catch {\n return undefined\n }\n}\n\nexport function readCookie(name: string): string | undefined {\n try {\n for (const part of document.cookie.split(';')) {\n const i = part.indexOf('=')\n if (part.slice(0, i).trim() === name) return decodeURIComponent(part.slice(i + 1).trim())\n }\n } catch {\n // no document\n }\n return undefined\n}\n\nexport class Persistence {\n cookie: CookieState\n local: LocalState\n private readonly store: Storage | undefined\n\n constructor(\n private readonly name: string,\n private readonly mode: Mode,\n private readonly domain?: string,\n ) {\n this.store = mode === 'memory' ? undefined : local()\n const fromStore = readJson<CookieState & LocalState>(this.store?.getItem(name))\n this.cookie = (mode === 'cookie' ? readJson<CookieState>(readCookie(name)) : fromStore) ?? {}\n this.local = fromStore ?? {}\n }\n\n save(): void {\n const { d, i, p, g } = this.local\n if (this.mode === 'cookie') {\n const secure = location.protocol === 'https:' ? '; Secure' : ''\n const domain = this.domain ? `; domain=${this.domain}` : ''\n document.cookie = `${this.name}=${encodeURIComponent(JSON.stringify(this.cookie))}; path=/; max-age=31536000; SameSite=Lax${domain}${secure}`\n }\n const value = this.mode === 'cookie' ? { d, i, p, g } : { ...this.cookie, d, i, p, g }\n try {\n this.store?.setItem(this.name, JSON.stringify(value))\n } catch {\n // quota or privacy mode\n }\n }\n}\n\ninterface PostHogState {\n distinct_id?: string\n $device_id?: string\n $user_state?: string\n /** Person processing enabled (set by identify under `person_profiles: 'identified_only'`). */\n $epp?: boolean\n $sesid?: [number, string, number]\n}\n\n/**\n * Identity and session from posthog-js's persistence entry `ph_{token}_posthog`. With posthog-js 1.234's default\n * `localStorage+cookie`, the cookie holds only `distinct_id`, `$sesid` and `$epp`; `$device_id` and `$user_state`\n * are in localStorage under the same name, which counts only if it belongs to the same `distinct_id` (the cookie\n * may come from another subdomain). Without it, `$epp` tells whether the user was identified.\n */\nexport function postHogIdentity(token: boolean | string): { cookie: CookieState; local: LocalState } | undefined {\n const name =\n typeof token === 'string' ? `ph_${token}_posthog` : document.cookie.match(/(?:^|;\\s*)(ph_[^=]+_posthog)=/)?.[1]\n if (!name) return undefined\n const cookie = readJson<PostHogState>(readCookie(name))\n const stored = readJson<PostHogState>(local()?.getItem(name))\n const ph = cookie ?? stored\n if (!ph?.distinct_id) return undefined\n const full = stored?.distinct_id === ph.distinct_id ? { ...stored, ...ph } : ph\n const identified = full.$user_state ? full.$user_state === 'identified' : full.$epp === true\n // An anonymous user's events went out under `distinct_id`; once identified, `$device_id` is the anonymous ID.\n const anon = identified ? (full.$device_id ?? ph.distinct_id) : ph.distinct_id\n const s = full.$sesid\n return {\n cookie: { a: anon, s: s?.[1] ? [s[1], s[0], s[2]] : undefined },\n local: identified ? { d: ph.distinct_id, i: 1 } : {},\n }\n}\n", "import type { TracingOptions } from './types'\nimport { randomHex } from './uuid'\n\n/** The page's W3C trace: adopted from `<meta name=\"traceparent\">` (server rendering), else generated. */\nexport class Trace {\n traceId: string\n parentId: string | undefined\n\n constructor() {\n const meta = typeof document !== 'undefined' ? document.querySelector('meta[name=\"traceparent\"]') : null\n const match = meta?.getAttribute('content')?.match(/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/)\n this.traceId = match?.[1] ?? randomHex(16)\n this.parentId = match?.[2]\n }\n\n /** A new trace, for example on a client-side navigation. */\n rotate(): void {\n this.traceId = randomHex(16)\n this.parentId = undefined\n }\n\n /** A `traceparent` header for an outgoing request: this trace, a new span ID, sampled. */\n header(): string {\n return `00-${this.traceId}-${randomHex(8)}-01`\n }\n}\n\nfunction matches(url: URL, targets: TracingOptions['propagateTo']): boolean {\n if (!targets) return false\n if (targets === 'same-origin') return url.origin === location.origin\n return targets.some((target) => {\n if (typeof target !== 'string') return target.test(url.href)\n try {\n const allowed = new URL(target)\n return url.origin === allowed.origin && url.href.startsWith(allowed.href)\n } catch {\n return false\n }\n })\n}\n\n/**\n * Wraps `window.fetch` so requests to the configured targets carry `traceparent` and `baggage` (`session.id`,\n * `user.id`), letting backend spans join the page's trace and know the user. Returns a function that restores\n * `fetch`.\n */\nexport function propagate(trace: Trace, options: TracingOptions, baggage: () => Record<string, string>): () => void {\n const targets = options.propagateTo ?? 'same-origin'\n if (!targets || typeof window === 'undefined' || !window.fetch) return () => {}\n const original = window.fetch\n let active = true\n const wrapped: typeof window.fetch = function (this: Window, input, init) {\n if (!active) return original.call(this, input, init)\n try {\n const url = new URL(input instanceof Request ? input.url : String(input), location.href)\n if (matches(url, targets)) {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))\n if (!headers.has('traceparent')) headers.set('traceparent', trace.header())\n if (options.baggage !== false) {\n const entries = Object.entries(baggage()).map(([k, v]) => `${k}=${encodeURIComponent(v)}`)\n const existing = headers.get('baggage')\n if (entries.length) headers.set('baggage', existing ? `${existing},${entries.join(',')}` : entries.join(','))\n }\n init = { ...init, headers }\n }\n } catch {\n // leave the request as it is\n }\n return original.call(this, input, init)\n }\n window.fetch = wrapped\n return () => {\n active = false\n if (window.fetch === wrapped) window.fetch = original\n }\n}\n", "import type { CaptureEvent } from './types'\n\nexport interface TransportOptions {\n url: string\n token: string\n flushIntervalMs: number\n maxBatchSize: number\n perSecond: number\n burst: number\n}\n\nconst MAX_RETRIES = 10\n/** `fetch` with `keepalive` allows at most 64 KiB in flight. */\nconst KEEPALIVE_LIMIT = 60_000\n\n/** Gzip with `CompressionStream`, or `undefined` where it is not available. */\nexport async function gzip(text: string): Promise<Blob | undefined> {\n if (typeof CompressionStream === 'undefined') return undefined\n try {\n return await new Response(new Response(text).body!.pipeThrough(new CompressionStream('gzip'))).blob()\n } catch {\n return undefined\n }\n}\n\n/**\n * The capture queue: batches every `flushIntervalMs` or `maxBatchSize` events, gzips with `CompressionStream`,\n * retries with exponential backoff and jitter, rate-limits with a token bucket, and sends what is left with\n * `sendBeacon` when the page is hidden.\n */\nexport class Transport {\n private queue: CaptureEvent[] = []\n private timer: ReturnType<typeof setTimeout> | undefined\n private tokens: number\n private refilled = Date.now()\n private readonly fetch = globalThis.fetch.bind(globalThis)\n\n constructor(private readonly o: TransportOptions) {\n this.tokens = o.burst\n }\n\n /** Queues an event. Returns false if the rate limit dropped it. */\n push(event: CaptureEvent, beacon = false): boolean {\n const now = Date.now()\n this.tokens = Math.min(this.o.burst, this.tokens + ((now - this.refilled) / 1000) * this.o.perSecond)\n this.refilled = now\n if (this.tokens < 1) return false\n this.tokens -= 1\n this.queue.push(event)\n if (beacon) this.flush(true)\n else if (this.queue.length >= this.o.maxBatchSize) void this.flush()\n else this.timer ??= setTimeout(() => void this.flush(), this.o.flushIntervalMs)\n return true\n }\n\n /** Sends everything queued; with `beacon`, synchronously through `sendBeacon` (page hide). */\n flush(beacon = false): Promise<void> {\n clearTimeout(this.timer)\n this.timer = undefined\n const batch = this.queue.splice(0)\n if (!batch.length) return Promise.resolve()\n const body = JSON.stringify({ api_key: this.o.token, batch, sent_at: new Date().toISOString() })\n if (beacon && navigator.sendBeacon?.(`${this.o.url}?beacon=1`, new Blob([body], { type: 'text/plain' }))) {\n return Promise.resolve()\n }\n return this.send(body, batch, 0)\n }\n\n private async send(body: string, batch: CaptureEvent[], attempt: number): Promise<void> {\n let ok = false\n let retry = true\n try {\n const compressed = body.length > 1024 ? await gzip(body) : undefined\n const url = compressed ? `${this.o.url}?compression=gzip-js` : this.o.url\n const response = await this.fetch(url, {\n method: 'POST',\n // text/plain keeps cross-origin requests free of a CORS preflight.\n headers: { 'Content-Type': 'text/plain' },\n body: compressed ?? body,\n keepalive: (compressed?.size ?? body.length) < KEEPALIVE_LIMIT,\n })\n ok = response.ok\n retry = response.status >= 500 || response.status === 429\n } catch {\n // network error: retry\n }\n if (ok || !retry || attempt >= MAX_RETRIES) return\n const delay = Math.min(30_000, 1000 * 2 ** attempt) * (0.5 + Math.random())\n await new Promise((resolve) => setTimeout(resolve, delay))\n return this.send(body, batch, attempt + 1)\n }\n}\n", "import { Flags } from './flags'\nimport { Persistence, local, postHogIdentity } from './storage'\nimport { Trace, propagate } from './trace'\nimport { Transport } from './transport'\nimport type { BeforeSend, CaptureEvent, FlagValue, NumbunchOptions, Properties } from './types'\nimport { uuidv7 } from './uuid'\n\nexport const VERSION = '0.1.1'\nexport const LIB = 'numbunch-web'\nconst DEFAULT_HOST = 'https://in.numbunch.com'\n/** The distinct ID the server replaces with a daily visitor hash in cookieless mode (milestone 2). */\nconst COOKIELESS_ID = '$posthog_cookieless'\nconst MINUTE = 60_000\n\n/** Campaign parameters and ad click IDs copied from the page URL onto events (milestone 2's list). */\nconst CAMPAIGN_PARAMS = [\n 'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'gad_source', 'mc_cid',\n 'gclid', 'gclsrc', 'dclid', 'gbraid', 'wbraid', 'fbclid', 'msclkid', 'twclid', 'li_fat_id', 'igshid', 'ttclid',\n 'rdt_cid', 'epik', 'qclid', 'sccid', 'irclid',\n]\n\nexport interface CaptureOptions {\n /** `sendBeacon` sends at once, surviving navigation. */\n transport?: 'sendBeacon'\n timestamp?: Date\n uuid?: string\n $set?: Properties\n $set_once?: Properties\n}\n\nexport interface FlagReadOptions {\n /** Record an exposure (`$feature_flag_called`). Default true. */\n sendEvent?: boolean\n}\n\n/** The Numbunch browser client. Create one per page with {@link init} or `new Numbunch(token, options)`. */\nexport class Numbunch {\n readonly token: string\n readonly options: NumbunchOptions\n readonly apiHost: string\n readonly flags: Flags\n readonly trace: Trace\n private persistence = new Persistence('', 'memory')\n private lifetime?: AbortController\n private initialized = false\n private readonly transport: Transport\n private readonly hooks: BeforeSend[]\n private readonly exposures = new Set<string>()\n private pageviews = 0\n\n constructor(token: string, options: NumbunchOptions = {}, deferred = false) {\n const o = options\n this.token = token\n this.options = o\n this.apiHost = (o.apiHost ?? DEFAULT_HOST).replace(/\\/$/, '')\n this.hooks = o.beforeSend ? ([] as BeforeSend[]).concat(o.beforeSend) : []\n const f = o.flags ?? {}\n this.transport = new Transport({\n url: `${this.apiHost}/batch/`,\n token,\n flushIntervalMs: o.flushIntervalMs ?? 3000,\n maxBatchSize: o.maxBatchSize ?? 50,\n perSecond: o.rateLimit?.perSecond ?? 10,\n burst: o.rateLimit?.burst ?? 100,\n })\n this.flags = new Flags(\n {\n token,\n host: (o.flagsHost ?? this.apiHost).replace(/\\/$/, ''),\n ttlMs: f.cacheTtlMs ?? 5 * MINUTE,\n remote: f.remote ?? 'lazy',\n localEvaluation: f.localEvaluation !== false,\n personProperties: f.personProperties,\n distinctId: () => (o.cookieless ? this.persistence.cookie.a! : this.getDistinctId()),\n groups: () => this.persistence.local.g ?? {},\n },\n o.bootstrap,\n )\n this.trace = new Trace()\n this.persistence.cookie.a = o.bootstrap?.distinctId ?? uuidv7()\n if (!deferred) this.start()\n }\n\n /** Attach browser integrations after mount. A deferred client can read its bootstrap during SSR. */\n start(): void {\n if (this.lifetime) return\n const lifetime = new AbortController()\n this.lifetime = lifetime\n const o = this.options\n const first = !this.initialized\n if (first) {\n this.initialized = true\n this.loadIdentity()\n this.flags.start(o.cookieless || o.persistence === 'memory' ? undefined : local())\n }\n const restore = propagate(this.trace, o.tracing ?? {}, () => {\n const out: Record<string, string> = { 'session.id': this.getSessionId() }\n if (!o.cookieless) out['user.id'] = this.getDistinctId()\n return out\n })\n lifetime.signal.addEventListener('abort', restore, { once: true })\n if (typeof window !== 'undefined') {\n const hidden = () => {\n if (o.capturePageleave) this.capture('$pageleave', {}, { transport: 'sendBeacon' })\n void this.transport.flush(true)\n }\n window.addEventListener('pagehide', hidden, { signal: lifetime.signal })\n document.addEventListener('visibilitychange', () => document.visibilityState === 'hidden' && void this.transport.flush(true), { signal: lifetime.signal })\n }\n if (first && o.capturePageview) this.pageview()\n if (o.remoteConfig) void this.loadRemoteConfig(lifetime.signal)\n if (first) o.loaded?.(this)\n }\n\n /** Release integrations owned by this client and send remaining events. */\n stop(): void {\n this.lifetime?.abort()\n this.lifetime = undefined\n void this.transport.flush()\n }\n\n private loadIdentity(): void {\n const o = this.options\n const p = (this.persistence = new Persistence(`nb_${this.token}`, o.cookieless ? 'memory' : (o.persistence ?? 'cookie'), o.cookieDomain))\n if (!p.cookie.a) {\n const adopted = o.adoptPostHogCookie ? postHogIdentity(o.adoptPostHogCookie) : undefined\n if (adopted) {\n p.cookie = { ...adopted.cookie, c: p.cookie.c }\n p.local = { ...p.local, ...adopted.local }\n } else {\n p.cookie.a = uuidv7()\n }\n }\n const boot = o.bootstrap\n if (boot?.distinctId && boot.distinctId !== this.getDistinctId()) {\n if (boot.isIdentified) p.local = { ...p.local, d: boot.distinctId, i: 1 }\n else if (!p.local.i) p.cookie.a = boot.distinctId\n }\n p.save()\n }\n\n /** The ID events are sent under: the identified ID, else the anonymous one. */\n getDistinctId(): string {\n if (this.options.cookieless) return COOKIELESS_ID\n return this.persistence.local.d ?? this.persistence.cookie.a!\n }\n\n /** The anonymous (device) ID, kept across `identify` until `reset`. */\n getAnonymousId(): string {\n return this.persistence.cookie.a!\n }\n\n /**\n * Uses `id` as the anonymous ID (for example one a server assigned in a cookie). Ignored once identified, so\n * an identified user keeps their identity.\n */\n adoptAnonymousId(id: string): void {\n if (!id || this.isIdentified() || id === this.persistence.cookie.a) return\n this.persistence.cookie.a = id\n this.persistence.save()\n this.flags.identityChanged()\n }\n\n isIdentified(): boolean {\n return this.persistence.local.i === 1\n }\n\n /** The current session ID (UUIDv7). Sessions end after 30 minutes without events or after 24 hours. */\n getSessionId(): string {\n return this.session(false)\n }\n\n private session(activity: boolean): string {\n const p = this.persistence\n const now = Date.now()\n const stored = p.cookie.s ?? ['', 0, 0]\n const last = stored[1]\n let [id, , start] = stored\n const expired = now - last > (this.options.sessionIdleMs ?? 30 * MINUTE) || now - start > (this.options.sessionMaxMs ?? 24 * 60 * MINUTE)\n if (!id || expired) {\n id = uuidv7(now)\n start = now\n activity = true\n }\n if (activity) {\n p.cookie.s = [id, now, start]\n p.save()\n }\n return id\n }\n\n /** Captures an event. Returns it, or `undefined` if consent, a `beforeSend` hook or the rate limit dropped it. */\n capture(event: string, properties: Properties = {}, options: CaptureOptions = {}): CaptureEvent | undefined {\n if (!this.lifetime || this.hasOptedOut()) return undefined\n const o = this.options\n const p = this.persistence\n const identified = this.isIdentified()\n const props: Properties = {\n ...this.context(),\n ...p.local.p,\n ...properties,\n distinct_id: this.getDistinctId(),\n $lib: LIB,\n $lib_version: VERSION,\n $trace_id: this.trace.traceId,\n $process_person_profile: identified || o.personProfiles === 'always',\n $is_identified: identified,\n }\n if (!o.cookieless) {\n props.$session_id = this.session(true)\n props.$device_id = p.cookie.a\n }\n if (p.local.g && Object.keys(p.local.g).length) props.$groups = p.local.g\n if (options.$set) props.$set = options.$set\n if (options.$set_once) props.$set_once = options.$set_once\n let out: CaptureEvent | null = {\n event,\n properties: props,\n timestamp: (options.timestamp ?? new Date()).toISOString(),\n uuid: options.uuid ?? uuidv7(),\n }\n for (const hook of this.hooks) {\n out = out && hook(out)\n }\n if (!out) return undefined\n return this.transport.push(out, options.transport === 'sendBeacon') ? out : undefined\n }\n\n /** Page and campaign properties added to every event. */\n private context(): Properties {\n if (typeof location === 'undefined') return {}\n const referrer = document.referrer\n let referringDomain = '$direct'\n try {\n if (referrer) referringDomain = new URL(referrer).host\n } catch {\n // not a URL\n }\n const out: Properties = {\n $current_url: location.href,\n $host: location.host,\n $pathname: location.pathname,\n $referrer: referrer || '$direct',\n $referring_domain: referringDomain,\n $screen_height: screen.height,\n $screen_width: screen.width,\n $viewport_height: innerHeight,\n $viewport_width: innerWidth,\n $browser_language: navigator.language,\n }\n const params = new URLSearchParams(location.search)\n for (const key of CAMPAIGN_PARAMS) {\n const value = params.get(key)\n if (value) out[key] = value\n }\n return out\n }\n\n /** Captures `$pageview`. Every pageview after the first starts a new trace (a client-side navigation). */\n pageview(properties: Properties = {}): CaptureEvent | undefined {\n if (this.pageviews++) this.trace.rotate()\n return this.capture('$pageview', { title: typeof document !== 'undefined' ? document.title : undefined, ...properties })\n }\n\n pageleave(properties: Properties = {}): CaptureEvent | undefined {\n return this.capture('$pageleave', properties, { transport: 'sendBeacon' })\n }\n\n /**\n * Links the anonymous ID to `distinctId` (`$identify` with `$anon_distinct_id`) and starts sending person\n * profiles. `set` and `setOnce` become person properties.\n */\n identify(distinctId: string, set?: Properties, setOnce?: Properties): void {\n if (!distinctId || this.options.cookieless) return\n const previous = this.getDistinctId()\n if (distinctId === previous && this.isIdentified()) {\n if (set || setOnce) this.setPersonProperties(set, setOnce)\n return\n }\n this.persistence.local = { ...this.persistence.local, d: distinctId, i: 1 }\n this.persistence.save()\n this.capture('$identify', { $anon_distinct_id: previous }, { $set: set, $set_once: setOnce })\n this.exposures.clear()\n this.flags.identityChanged()\n }\n\n /** Forgets the user: new anonymous ID and session, no super properties or groups. Consent is kept. */\n reset(): void {\n const p = this.persistence\n p.cookie = { a: uuidv7(), c: p.cookie.c }\n p.local = {}\n p.save()\n this.trace.rotate()\n this.exposures.clear()\n this.flags.identityChanged()\n }\n\n /** Super properties, sent with every event. */\n register(properties: Properties): void {\n this.persistence.local.p = { ...this.persistence.local.p, ...properties }\n this.persistence.save()\n }\n\n registerOnce(properties: Properties): void {\n this.register({ ...properties, ...this.persistence.local.p })\n }\n\n unregister(key: string): void {\n delete this.persistence.local.p?.[key]\n this.persistence.save()\n }\n\n /** Sets person properties (`$set`, `$set_once`). */\n setPersonProperties(set?: Properties, setOnce?: Properties): void {\n this.capture('$set', {}, { $set: set ?? {}, $set_once: setOnce })\n }\n\n /** Associates later events with a group; `properties` are stored on the group (`$groupidentify`). */\n group(type: string, key: string, properties?: Properties): void {\n const changed = this.persistence.local.g?.[type] !== key\n this.persistence.local.g = { ...this.persistence.local.g, [type]: key }\n this.persistence.save()\n if (changed) {\n this.exposures.clear()\n this.flags.identityChanged()\n }\n if (properties) this.capture('$groupidentify', { $group_type: type, $group_key: key, $group_set: properties })\n }\n\n optIn(options: { captureEvent?: boolean } = {}): void {\n this.persistence.cookie.c = 1\n this.persistence.save()\n if (options.captureEvent !== false) this.capture('$opt_in')\n }\n\n optOut(): void {\n this.persistence.cookie.c = 0\n this.persistence.save()\n }\n\n hasOptedIn(): boolean {\n return this.persistence.cookie.c === 1\n }\n\n hasOptedOut(): boolean {\n const consent = this.persistence.cookie.c\n return consent === 0 || (consent === undefined && this.options.optOutByDefault === true)\n }\n\n /** The flag's value, synchronously; `undefined` while unknown. Records an exposure once per flag and value. */\n getVariant(key: string, options: FlagReadOptions = {}): FlagValue | undefined {\n const value = this.flags.value(key)\n if (value !== undefined && options.sendEvent !== false && this.options.flags?.sendExposure !== false) {\n const seen = `${key}\\u0000${value}`\n if (!this.exposures.has(seen)) {\n this.exposures.add(seen)\n this.capture('$feature_flag_called', {\n $feature_flag: key,\n $feature_flag_response: value,\n [`$feature/${key}`]: value,\n $feature_flag_version: this.flags.version(key),\n locally_evaluated: this.flags.isLocal(key),\n })\n }\n }\n return value\n }\n\n /** Whether the flag is on (any variant counts); `undefined` while unknown. */\n isEnabled(key: string, options?: FlagReadOptions): boolean | undefined {\n const value = this.getVariant(key, options)\n return value === undefined ? undefined : value !== false\n }\n\n getFlagPayload(key: string): unknown {\n return this.flags.payload(key)\n }\n\n /** Every known flag value, without recording exposures. */\n getFlags(): Record<string, FlagValue> {\n return this.flags.all()\n }\n\n /** Calls `listener` with all values now (if known) and whenever they change. Returns an unsubscribe function. */\n onFlags(listener: (flags: Record<string, FlagValue>) => void): () => void {\n return this.flags.onFlags(listener)\n }\n\n reloadFlags(): Promise<void> {\n return this.flags.reload()\n }\n\n /** A `traceparent` for a request made outside `fetch` (for example `XMLHttpRequest`). */\n traceparent(): string {\n return this.trace.header()\n }\n\n /** Sends queued events now. */\n flush(): Promise<void> {\n return this.transport.flush()\n }\n\n private async loadRemoteConfig(signal: AbortSignal): Promise<void> {\n try {\n const response = await fetch(`${this.apiHost}/array/${encodeURIComponent(this.token)}/config`, { signal })\n const config = (await response.json()) as {\n autocaptureExceptions?: boolean\n capturePerformance?: { web_vitals?: boolean; web_vitals_allowed_metrics?: string[] } | false\n }\n if (config.autocaptureExceptions) {\n const { exceptionAutocapture } = await import('./exceptions')\n if (signal.aborted) return\n signal.addEventListener('abort', exceptionAutocapture(this), { once: true })\n }\n const performance = config.capturePerformance\n if (performance && performance.web_vitals) {\n const { webVitals } = await import('./web-vitals')\n if (!signal.aborted) webVitals(this, { metrics: performance.web_vitals_allowed_metrics, signal })\n }\n } catch {\n // remote config is optional\n }\n }\n}\n\n/** Creates the client. */\nexport function init(token: string, options?: NumbunchOptions): Numbunch {\n return new Numbunch(token, options)\n}\n"],
|
|
5
5
|
"mappings": "AAEA,IAAMA,EAA0B,IAAI,YAG7B,SAASC,EAAQC,EAAeC,EAAO,EAAW,CACvD,IAAMC,EAAOJ,EAAQ,OAAOE,CAAK,EAC3BG,EAASD,EAAK,OACdE,EAASD,EAAS,GACpBE,EAAIJ,IAAS,EACbK,EACJ,QAASC,EAAI,EAAGA,EAAIH,EAAQG,GAAK,EAC/BD,EAAIJ,EAAKK,CAAC,EAAML,EAAKK,EAAI,CAAC,GAAM,EAAML,EAAKK,EAAI,CAAC,GAAM,GAAOL,EAAKK,EAAI,CAAC,GAAM,GAC7EF,GAAKG,EAAIF,CAAC,EACVD,EAAKA,GAAK,GAAOA,IAAM,GACvBA,EAAK,KAAK,KAAKA,EAAG,CAAC,EAAI,WAAc,EAEvC,IAAMI,EAAON,EAAS,EACtB,GAAIM,EAAM,CACRH,EAAI,EACJ,QAASC,EAAIE,EAAO,EAAGF,GAAK,EAAGA,IAAKD,EAAKA,GAAK,EAAKJ,EAAKE,EAASG,CAAC,EAClEF,GAAKG,EAAIF,CAAC,CACZ,CACA,OAAAD,GAAKF,EACLE,GAAKA,IAAM,GACXA,EAAI,KAAK,KAAKA,EAAG,UAAU,EAC3BA,GAAKA,IAAM,GACXA,EAAI,KAAK,KAAKA,EAAG,UAAU,EAC3BA,GAAKA,IAAM,GACJA,IAAM,CACf,CAEA,SAASG,EAAIF,EAAmB,CAC9B,OAAAA,EAAI,KAAK,KAAKA,EAAG,UAAU,E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A,aAAsB,CACpB,OAAO,KAAK,MAAM,OAAO,CAC3B,CAGA,OAAuB,CACrB,OAAO,KAAK,UAAU,MAAM,CAC9B,CAEA,MAAc,iBAAiBC,EAAoC,CACjE,GAAI,CAEF,IAAMC,EAAU,MADC,MAAM,MAAM,GAAG,KAAK,OAAO,UAAU,mBAAmB,KAAK,KAAK,CAAC,UAAW,CAAE,OAAAD,CAAO,CAAC,GAC1E,KAAK,EAIpC,GAAIC,EAAO,sBAAuB,CAChC,GAAM,CAAE,qBAAAC,CAAqB,EAAI,KAAM,QAAO,kBAAc,EAC5D,GAAIF,EAAO,QAAS,OACpBA,EAAO,iBAAiB,QAASE,EAAqB,IAAI,EAAG,CAAE,KAAM,EAAK,CAAC,CAC7E,CACA,IAAMC,EAAcF,EAAO,mBAC3B,GAAIE,GAAeA,EAAY,WAAY,CACzC,GAAM,CAAE,UAAAC,CAAU,EAAI,KAAM,QAAO,kBAAc,EAC5CJ,EAAO,SAASI,EAAU,KAAM,CAAE,QAASD,EAAY,2BAA4B,OAAAH,CAAO,CAAC,CAClG,CACF,MAAQ,CAER,CACF,CACF,EAGO,SAASK,EAAKnD,EAAeC,EAAqC,CACvE,OAAO,IAAIH,EAASE,EAAOC,CAAO,CACpC",
|
|
6
6
|
"names": ["encoder", "murmur3", "input", "seed", "data", "length", "blocks", "h", "k", "i", "mix", "tail", "bucket", "key", "id", "salt", "evaluate", "flag", "id", "key", "holdout", "filters", "variants", "groups", "a", "b", "group", "bucket", "v", "value", "cumulative", "variant", "Flags", "h", "bootstrap", "storage", "boot", "definition", "local", "remote", "keys", "out", "listener", "all", "force", "cached", "response", "body", "missing", "flags", "f", "version", "values", "detail", "payload", "randomHex", "bytes", "out", "hex", "b", "uuidv7", "now", "variant", "readJson", "text", "local", "s", "readCookie", "name", "part", "i", "Persistence", "mode", "domain", "fromStore", "d", "p", "g", "secure", "value", "postHogIdentity", "token", "cookie", "stored", "ph", "full", "identified", "anon", "Trace", "match", "randomHex", "matches", "url", "targets", "target", "allowed", "propagate", "trace", "options", "baggage", "original", "active", "wrapped", "input", "init", "headers", "entries", "k", "v", "existing", "gzip", "text", "Transport", "o", "event", "beacon", "now", "batch", "body", "attempt", "ok", "retry", "compressed", "url", "response", "delay", "resolve", "VERSION", "LIB", "DEFAULT_HOST", "COOKIELESS_ID", "MINUTE", "CAMPAIGN_PARAMS", "Numbunch", "Persistence", "token", "options", "deferred", "o", "f", "Transport", "Flags", "Trace", "uuidv7", "lifetime", "first", "local", "restore", "propagate", "out", "hidden", "p", "adopted", "postHogIdentity", "boot", "id", "activity", "now", "stored", "last", "start", "expired", "event", "properties", "identified", "props", "hook", "referrer", "referringDomain", "params", "key", "value", "distinctId", "set", "setOnce", "previous", "type", "changed", "consent", "seen", "listener", "signal", "config", "exceptionAutocapture", "performance", "webVitals", "init"]
|
|
7
7
|
}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Flags } from './flags';
|
|
2
2
|
import { Trace } from './trace';
|
|
3
3
|
import type { CaptureEvent, FlagValue, NumbunchOptions, Properties } from './types';
|
|
4
|
-
export declare const VERSION = "0.1.
|
|
4
|
+
export declare const VERSION = "0.1.1";
|
|
5
5
|
export declare const LIB = "numbunch-web";
|
|
6
6
|
export interface CaptureOptions {
|
|
7
7
|
/** `sendBeacon` sends at once, surviving navigation. */
|
package/dist/compat.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{f as o}from"./chunks/chunk-
|
|
1
|
+
import{f as o}from"./chunks/chunk-GEQWAF5D.js";var r=class{__loaded=!1;config={};nb;get numbunch(){if(!this.nb)throw new Error("posthog.init() has not been called");return this.nb}init(t,e={}){if(this.nb)return this;this.config=e;let n=e.capture_pageview!==!1,s=e.capture_pageleave,i=e.bootstrap;return this.nb=new o(t,{apiHost:e.api_host,persistence:e.persistence==="memory"?"memory":e.persistence==="localStorage"?"localStorage":"cookie",cookieDomain:e.cookie_domain,optOutByDefault:e.opt_out_capturing_by_default,cookieless:e.cookieless_mode==="always",personProfiles:e.person_profiles==="always"?"always":"identified_only",capturePageview:n,capturePageleave:s===!0||(s??"if_capture_pageview")==="if_capture_pageview"&&n,beforeSend:e.before_send,remoteConfig:!e.advanced_disable_decide,adoptPostHogCookie:!0,flags:{remote:"eager"},bootstrap:i&&{distinctId:i.distinctID,isIdentified:i.isIdentifiedID,flags:i.featureFlags,payloads:i.featureFlagPayloads},...e.numbunch}),this.__loaded=!0,e.loaded?.(this),this}capture(t,e,n={}){return this.nb?.capture(t,e??{},n)}identify(t,e,n){t&&this.nb?.identify(t,e,n)}reset(){this.nb?.reset(),this.config.opt_out_capturing_by_default&&this.nb?.optOut()}register(t){let{distinct_id:e,$device_id:n,...s}=t,i=e??n;typeof i=="string"&&this.nb?.adoptAnonymousId(i),Object.keys(s).length&&this.nb?.register(s)}register_once(t){this.nb?.registerOnce(t)}unregister(t){this.nb?.unregister(t)}people={set:(t,e)=>this.nb?.setPersonProperties(t,e),set_once:t=>this.nb?.setPersonProperties(void 0,t)};setPersonProperties(t,e){this.nb?.setPersonProperties(t,e)}group(t,e,n){this.nb?.group(t,e,n)}getFeatureFlag(t,e={}){return this.nb?.getVariant(t,{sendEvent:e.send_event!==!1})}isFeatureEnabled(t,e={}){return this.nb?.isEnabled(t,{sendEvent:e.send_event!==!1})}getFeatureFlagPayload(t){return this.nb?.getFlagPayload(t)}onFeatureFlags(t){return this.nb?.onFlags(e=>t(Object.keys(e).filter(n=>e[n]!==!1),e))??(()=>{})}reloadFeatureFlags(){this.nb?.reloadFlags()}opt_in_capturing(t={}){let e=t.captureEventName;this.nb?.optIn({captureEvent:!1}),e!==!1&&e!==null&&this.capture(e??"$opt_in")}opt_out_capturing(){this.nb?.optOut()}has_opted_in_capturing(){return this.nb?.hasOptedIn()??!1}has_opted_out_capturing(){return this.nb?.hasOptedOut()??!1}get_distinct_id(){return this.nb?.getDistinctId()??""}get_session_id(){return this.nb?.getSessionId()??""}get_property(t){let e=this.nb;if(e)switch(t){case"$user_state":return e.isIdentified()?"identified":"anonymous";case"distinct_id":return e.getDistinctId();case"$device_id":return e.getAnonymousId();case"$session_id":return e.getSessionId();default:return}}async captureException(t,e){if(this.nb)return(await import("./exceptions.js")).captureException(this.nb,t,e)}debug(){}},a=new r,p=a;export{r as PostHog,p as default,a as posthog};
|
|
2
2
|
//# sourceMappingURL=compat.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as o,b as r,c as n,d as p,e as u,f as m,g as i}from"./chunks/chunk-
|
|
1
|
+
import{a as o,b as r,c as n,d as p,e as u,f as m,g as i}from"./chunks/chunk-GEQWAF5D.js";function a(e="__numbunch_bootstrap"){try{let t=document.getElementById(e)?.textContent;return t?JSON.parse(t):void 0}catch{return}}export{m as Numbunch,u as VERSION,a as bootstrapFromDocument,r as bucket,n as evaluate,i as init,o as murmur3,p as uuidv7};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED