@numbunch/browser 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Numbunch contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +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-ARHCREVU.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 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"],
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,CA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A,CAAQ,CACpC,CAEA,aAA6B,CAC3B,OAAO,KAAK,MAAM,OAAO,CAC3B,CAGA,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
+ "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
+ }
@@ -0,0 +1,97 @@
1
+ import { Flags } from './flags';
2
+ import { Trace } from './trace';
3
+ import type { CaptureEvent, FlagValue, NumbunchOptions, Properties } from './types';
4
+ export declare const VERSION = "0.1.0";
5
+ export declare const LIB = "numbunch-web";
6
+ export interface CaptureOptions {
7
+ /** `sendBeacon` sends at once, surviving navigation. */
8
+ transport?: 'sendBeacon';
9
+ timestamp?: Date;
10
+ uuid?: string;
11
+ $set?: Properties;
12
+ $set_once?: Properties;
13
+ }
14
+ export interface FlagReadOptions {
15
+ /** Record an exposure (`$feature_flag_called`). Default true. */
16
+ sendEvent?: boolean;
17
+ }
18
+ /** The Numbunch browser client. Create one per page with {@link init} or `new Numbunch(token, options)`. */
19
+ export declare class Numbunch {
20
+ readonly token: string;
21
+ readonly options: NumbunchOptions;
22
+ readonly apiHost: string;
23
+ readonly flags: Flags;
24
+ readonly trace: Trace;
25
+ private persistence;
26
+ private lifetime?;
27
+ private initialized;
28
+ private readonly transport;
29
+ private readonly hooks;
30
+ private readonly exposures;
31
+ private pageviews;
32
+ constructor(token: string, options?: NumbunchOptions, deferred?: boolean);
33
+ /** Attach browser integrations after mount. A deferred client can read its bootstrap during SSR. */
34
+ start(): void;
35
+ /** Release integrations owned by this client and send remaining events. */
36
+ stop(): void;
37
+ private loadIdentity;
38
+ /** The ID events are sent under: the identified ID, else the anonymous one. */
39
+ getDistinctId(): string;
40
+ /** The anonymous (device) ID, kept across `identify` until `reset`. */
41
+ getAnonymousId(): string;
42
+ /**
43
+ * Uses `id` as the anonymous ID (for example one a server assigned in a cookie). Ignored once identified, so
44
+ * an identified user keeps their identity.
45
+ */
46
+ adoptAnonymousId(id: string): void;
47
+ isIdentified(): boolean;
48
+ /** The current session ID (UUIDv7). Sessions end after 30 minutes without events or after 24 hours. */
49
+ getSessionId(): string;
50
+ private session;
51
+ /** Captures an event. Returns it, or `undefined` if consent, a `beforeSend` hook or the rate limit dropped it. */
52
+ capture(event: string, properties?: Properties, options?: CaptureOptions): CaptureEvent | undefined;
53
+ /** Page and campaign properties added to every event. */
54
+ private context;
55
+ /** Captures `$pageview`. Every pageview after the first starts a new trace (a client-side navigation). */
56
+ pageview(properties?: Properties): CaptureEvent | undefined;
57
+ pageleave(properties?: Properties): CaptureEvent | undefined;
58
+ /**
59
+ * Links the anonymous ID to `distinctId` (`$identify` with `$anon_distinct_id`) and starts sending person
60
+ * profiles. `set` and `setOnce` become person properties.
61
+ */
62
+ identify(distinctId: string, set?: Properties, setOnce?: Properties): void;
63
+ /** Forgets the user: new anonymous ID and session, no super properties or groups. Consent is kept. */
64
+ reset(): void;
65
+ /** Super properties, sent with every event. */
66
+ register(properties: Properties): void;
67
+ registerOnce(properties: Properties): void;
68
+ unregister(key: string): void;
69
+ /** Sets person properties (`$set`, `$set_once`). */
70
+ setPersonProperties(set?: Properties, setOnce?: Properties): void;
71
+ /** Associates later events with a group; `properties` are stored on the group (`$groupidentify`). */
72
+ group(type: string, key: string, properties?: Properties): void;
73
+ optIn(options?: {
74
+ captureEvent?: boolean;
75
+ }): void;
76
+ optOut(): void;
77
+ hasOptedIn(): boolean;
78
+ hasOptedOut(): boolean;
79
+ /** The flag's value, synchronously; `undefined` while unknown. Records an exposure once per flag and value. */
80
+ getVariant(key: string, options?: FlagReadOptions): FlagValue | undefined;
81
+ /** Whether the flag is on (any variant counts); `undefined` while unknown. */
82
+ isEnabled(key: string, options?: FlagReadOptions): boolean | undefined;
83
+ getFlagPayload(key: string): unknown;
84
+ /** Every known flag value, without recording exposures. */
85
+ getFlags(): Record<string, FlagValue>;
86
+ /** Calls `listener` with all values now (if known) and whenever they change. Returns an unsubscribe function. */
87
+ onFlags(listener: (flags: Record<string, FlagValue>) => void): () => void;
88
+ reloadFlags(): Promise<void>;
89
+ /** A `traceparent` for a request made outside `fetch` (for example `XMLHttpRequest`). */
90
+ traceparent(): string;
91
+ /** Sends queued events now. */
92
+ flush(): Promise<void>;
93
+ private loadRemoteConfig;
94
+ }
95
+ /** Creates the client. */
96
+ export declare function init(token: string, options?: NumbunchOptions): Numbunch;
97
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE/B,OAAO,EAAE,KAAK,EAAa,MAAM,SAAS,CAAA;AAE1C,OAAO,KAAK,EAAc,YAAY,EAAE,SAAS,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAG/F,eAAO,MAAM,OAAO,UAAU,CAAA;AAC9B,eAAO,MAAM,GAAG,iBAAiB,CAAA;AAajC,MAAM,WAAW,cAAc;IAC7B,wDAAwD;IACxD,SAAS,CAAC,EAAE,YAAY,CAAA;IACxB,SAAS,CAAC,EAAE,IAAI,CAAA;IAChB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,UAAU,CAAA;IACjB,SAAS,CAAC,EAAE,UAAU,CAAA;CACvB;AAED,MAAM,WAAW,eAAe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I;IAIzE,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,yFAAyF;IACzF,WAAW,IAAI,MAAM;IAIrB,+BAA+B;IAC/B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;YAIR,gBAAgB;CAqB/B;AAED,0BAA0B;AAC1B,wBAAgB,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,QAAQ,CAEvE"}
@@ -0,0 +1,78 @@
1
+ import { Numbunch, type CaptureOptions } from './client';
2
+ import type { BeforeSend, CaptureEvent, FlagValue, NumbunchOptions, Properties } from './types';
3
+ export interface PostHogConfig {
4
+ api_host?: string;
5
+ ui_host?: string;
6
+ persistence?: 'localStorage+cookie' | 'cookie' | 'localStorage' | 'memory' | 'sessionStorage';
7
+ cookie_domain?: string;
8
+ opt_out_capturing_by_default?: boolean;
9
+ person_profiles?: 'identified_only' | 'always' | 'never';
10
+ capture_pageview?: boolean;
11
+ capture_pageleave?: boolean | 'if_capture_pageview';
12
+ cookieless_mode?: 'always' | 'never' | 'on_reject';
13
+ bootstrap?: {
14
+ distinctID?: string;
15
+ isIdentifiedID?: boolean;
16
+ featureFlags?: Record<string, FlagValue>;
17
+ featureFlagPayloads?: Record<string, unknown>;
18
+ };
19
+ before_send?: BeforeSend | BeforeSend[];
20
+ /** Skip the remote config request (exception autocapture and web vitals switched on in the app). */
21
+ advanced_disable_decide?: boolean;
22
+ loaded?: (posthog: PostHog) => void;
23
+ /** Numbunch options passed through unchanged. */
24
+ numbunch?: NumbunchOptions;
25
+ [unsupported: string]: unknown;
26
+ }
27
+ type FlagsCallback = (flags: string[], variants: Record<string, FlagValue>) => void;
28
+ export declare class PostHog {
29
+ /** True after `init`. */
30
+ __loaded: boolean;
31
+ config: PostHogConfig;
32
+ private nb;
33
+ /** The underlying Numbunch client (after `init`). */
34
+ get numbunch(): Numbunch;
35
+ init(token: string, config?: PostHogConfig): PostHog;
36
+ capture(event: string, properties?: Properties | null, options?: CaptureOptions): CaptureEvent | undefined;
37
+ identify(distinctId?: string, set?: Properties, setOnce?: Properties): void;
38
+ /** As posthog-js 1.234: a new anonymous user, and consent back to the default (opted out under `opt_out_capturing_by_default`). */
39
+ reset(): void;
40
+ /** Super properties. As in posthog-js, `distinct_id` (and `$device_id`) replace the anonymous ID. */
41
+ register(properties: Properties): void;
42
+ register_once(properties: Properties): void;
43
+ unregister(key: string): void;
44
+ readonly people: {
45
+ set: (set: Properties, setOnce?: Properties) => void | undefined;
46
+ set_once: (setOnce: Properties) => void | undefined;
47
+ };
48
+ setPersonProperties(set?: Properties, setOnce?: Properties): void;
49
+ group(type: string, key: string, properties?: Properties): void;
50
+ getFeatureFlag(key: string, options?: {
51
+ send_event?: boolean;
52
+ }): FlagValue | undefined;
53
+ isFeatureEnabled(key: string, options?: {
54
+ send_event?: boolean;
55
+ }): boolean | undefined;
56
+ getFeatureFlagPayload(key: string): unknown;
57
+ /** Calls back with the enabled flag keys and all values; returns an unsubscribe function. */
58
+ onFeatureFlags(callback: FlagsCallback): () => void;
59
+ reloadFeatureFlags(): void;
60
+ opt_in_capturing(options?: {
61
+ captureEventName?: string | false | null;
62
+ }): void;
63
+ opt_out_capturing(): void;
64
+ has_opted_in_capturing(): boolean;
65
+ has_opted_out_capturing(): boolean;
66
+ get_distinct_id(): string;
67
+ get_session_id(): string;
68
+ /** `$user_state`, `distinct_id`, `$device_id`, `$session_id`, or a super property. */
69
+ get_property(name: string): unknown;
70
+ captureException(error: unknown, properties?: Properties): Promise<CaptureEvent | undefined>;
71
+ /** posthog-js debugging switch; logs nothing here. */
72
+ debug(): void;
73
+ }
74
+ /** The default instance, like `import posthog from 'posthog-js'`. */
75
+ export declare const posthog: PostHog;
76
+ export default posthog;
77
+ export type { CaptureEvent as CaptureResult, Properties };
78
+ //# sourceMappingURL=compat.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compat.d.ts","sourceRoot":"","sources":["../src/compat.ts"],"names":[],"mappings":"AAOA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AAA;KAAO,GAAG,OAAO,GAAG,SAAS;IAI1F,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAI3C,6FAA6F;IAC7F,cAAc,CAAC,QAAQ,EAAE,aAAa,GAAG,MAAM,IAAI;IAMnD,kBAAkB,IAAI,IAAI;IAI1B,gBAAgB,CAAC,OAAO,GAAE;QAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAA;KAAO,GAAG,IAAI;IAMlF,iBAAiB,IAAI,IAAI;IAIzB,sBAAsB,IAAI,OAAO;IAIjC,uBAAuB,IAAI,OAAO;IAIlC,eAAe,IAAI,MAAM;IAIzB,cAAc,IAAI,MAAM;IAIxB,sFAAsF;IACtF,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAiB7B,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,UAAU,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC;IAKlG,sDAAsD;IACtD,KAAK,IAAI,IAAI;CACd;AAED,qEAAqE;AACrE,eAAO,MAAM,OAAO,SAAgB,CAAA;AACpC,eAAe,OAAO,CAAA;AACtB,YAAY,EAAE,YAAY,IAAI,aAAa,EAAE,UAAU,EAAE,CAAA"}
package/dist/compat.js ADDED
@@ -0,0 +1,2 @@
1
+ import{f as o}from"./chunks/chunk-ARHCREVU.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
+ //# sourceMappingURL=compat.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/compat.ts"],
4
+ "sourcesContent": ["// A posthog-js compatible surface over the Numbunch client, so a site can switch by changing an import:\n//\n// import posthog from '@numbunch/browser/compat' // was: import posthog from 'posthog-js'\n//\n// It covers the commonly used posthog-js API (see site/ docs, \"Migrating from posthog-js\"). Option and method\n// names follow posthog-js 1.234 (Apache 2.0); this file contains no posthog-js code.\n\nimport { Numbunch, type CaptureOptions } from './client'\nimport type { BeforeSend, CaptureEvent, FlagValue, NumbunchOptions, Properties } from './types'\n\nexport interface PostHogConfig {\n api_host?: string\n ui_host?: string\n persistence?: 'localStorage+cookie' | 'cookie' | 'localStorage' | 'memory' | 'sessionStorage'\n cookie_domain?: string\n opt_out_capturing_by_default?: boolean\n person_profiles?: 'identified_only' | 'always' | 'never'\n capture_pageview?: boolean\n capture_pageleave?: boolean | 'if_capture_pageview'\n cookieless_mode?: 'always' | 'never' | 'on_reject'\n bootstrap?: {\n distinctID?: string\n isIdentifiedID?: boolean\n featureFlags?: Record<string, FlagValue>\n featureFlagPayloads?: Record<string, unknown>\n }\n before_send?: BeforeSend | BeforeSend[]\n /** Skip the remote config request (exception autocapture and web vitals switched on in the app). */\n advanced_disable_decide?: boolean\n loaded?: (posthog: PostHog) => void\n /** Numbunch options passed through unchanged. */\n numbunch?: NumbunchOptions\n [unsupported: string]: unknown\n}\n\ntype FlagsCallback = (flags: string[], variants: Record<string, FlagValue>) => void\n\nexport class PostHog {\n /** True after `init`. */\n __loaded = false\n config: PostHogConfig = {}\n private nb: Numbunch | undefined\n\n /** The underlying Numbunch client (after `init`). */\n get numbunch(): Numbunch {\n if (!this.nb) throw new Error('posthog.init() has not been called')\n return this.nb\n }\n\n init(token: string, config: PostHogConfig = {}): PostHog {\n if (this.nb) return this\n this.config = config\n const pageview = config.capture_pageview !== false\n const leave = config.capture_pageleave\n const boot = config.bootstrap\n this.nb = new Numbunch(token, {\n apiHost: config.api_host,\n persistence: config.persistence === 'memory' ? 'memory' : config.persistence === 'localStorage' ? 'localStorage' : 'cookie',\n cookieDomain: config.cookie_domain,\n optOutByDefault: config.opt_out_capturing_by_default,\n cookieless: config.cookieless_mode === 'always',\n personProfiles: config.person_profiles === 'always' ? 'always' : 'identified_only',\n capturePageview: pageview,\n capturePageleave: leave === true || ((leave ?? 'if_capture_pageview') === 'if_capture_pageview' && pageview),\n beforeSend: config.before_send,\n remoteConfig: !config.advanced_disable_decide,\n // Keep the identity of visitors who were tracked by posthog-js before the switch.\n adoptPostHogCookie: true,\n flags: { remote: 'eager' },\n bootstrap: boot && {\n distinctId: boot.distinctID,\n isIdentified: boot.isIdentifiedID,\n flags: boot.featureFlags,\n payloads: boot.featureFlagPayloads,\n },\n ...config.numbunch,\n })\n this.__loaded = true\n config.loaded?.(this)\n return this\n }\n\n capture(event: string, properties?: Properties | null, options: CaptureOptions = {}): CaptureEvent | undefined {\n return this.nb?.capture(event, properties ?? {}, options)\n }\n\n identify(distinctId?: string, set?: Properties, setOnce?: Properties): void {\n if (distinctId) this.nb?.identify(distinctId, set, setOnce)\n }\n\n /** As posthog-js 1.234: a new anonymous user, and consent back to the default (opted out under `opt_out_capturing_by_default`). */\n reset(): void {\n this.nb?.reset()\n if (this.config.opt_out_capturing_by_default) this.nb?.optOut()\n }\n\n /** Super properties. As in posthog-js, `distinct_id` (and `$device_id`) replace the anonymous ID. */\n register(properties: Properties): void {\n const { distinct_id, $device_id, ...rest } = properties\n const id = distinct_id ?? $device_id\n if (typeof id === 'string') this.nb?.adoptAnonymousId(id)\n if (Object.keys(rest).length) this.nb?.register(rest)\n }\n\n register_once(properties: Properties): void {\n this.nb?.registerOnce(properties)\n }\n\n unregister(key: string): void {\n this.nb?.unregister(key)\n }\n\n readonly people = {\n set: (set: Properties, setOnce?: Properties) => this.nb?.setPersonProperties(set, setOnce),\n set_once: (setOnce: Properties) => this.nb?.setPersonProperties(undefined, setOnce),\n }\n\n setPersonProperties(set?: Properties, setOnce?: Properties): void {\n this.nb?.setPersonProperties(set, setOnce)\n }\n\n group(type: string, key: string, properties?: Properties): void {\n this.nb?.group(type, key, properties)\n }\n\n getFeatureFlag(key: string, options: { send_event?: boolean } = {}): FlagValue | undefined {\n return this.nb?.getVariant(key, { sendEvent: options.send_event !== false })\n }\n\n isFeatureEnabled(key: string, options: { send_event?: boolean } = {}): boolean | undefined {\n return this.nb?.isEnabled(key, { sendEvent: options.send_event !== false })\n }\n\n getFeatureFlagPayload(key: string): unknown {\n return this.nb?.getFlagPayload(key)\n }\n\n /** Calls back with the enabled flag keys and all values; returns an unsubscribe function. */\n onFeatureFlags(callback: FlagsCallback): () => void {\n return (\n this.nb?.onFlags((flags) => callback(Object.keys(flags).filter((k) => flags[k] !== false), flags)) ?? (() => {})\n )\n }\n\n reloadFeatureFlags(): void {\n void this.nb?.reloadFlags()\n }\n\n opt_in_capturing(options: { captureEventName?: string | false | null } = {}): void {\n const name = options.captureEventName\n this.nb?.optIn({ captureEvent: false })\n if (name !== false && name !== null) this.capture(name ?? '$opt_in')\n }\n\n opt_out_capturing(): void {\n this.nb?.optOut()\n }\n\n has_opted_in_capturing(): boolean {\n return this.nb?.hasOptedIn() ?? false\n }\n\n has_opted_out_capturing(): boolean {\n return this.nb?.hasOptedOut() ?? false\n }\n\n get_distinct_id(): string {\n return this.nb?.getDistinctId() ?? ''\n }\n\n get_session_id(): string {\n return this.nb?.getSessionId() ?? ''\n }\n\n /** `$user_state`, `distinct_id`, `$device_id`, `$session_id`, or a super property. */\n get_property(name: string): unknown {\n const nb = this.nb\n if (!nb) return undefined\n switch (name) {\n case '$user_state':\n return nb.isIdentified() ? 'identified' : 'anonymous'\n case 'distinct_id':\n return nb.getDistinctId()\n case '$device_id':\n return nb.getAnonymousId()\n case '$session_id':\n return nb.getSessionId()\n default:\n return undefined\n }\n }\n\n async captureException(error: unknown, properties?: Properties): Promise<CaptureEvent | undefined> {\n if (!this.nb) return undefined\n return (await import('./exceptions')).captureException(this.nb, error, properties)\n }\n\n /** posthog-js debugging switch; logs nothing here. */\n debug(): void {}\n}\n\n/** The default instance, like `import posthog from 'posthog-js'`. */\nexport const posthog = new PostHog()\nexport default posthog\nexport type { CaptureEvent as CaptureResult, Properties }\n"],
5
+ "mappings": "+CAqCO,IAAMA,EAAN,KAAc,CAEnB,SAAW,GACX,OAAwB,CAAC,EACjB,GAGR,IAAI,UAAqB,CACvB,GAAI,CAAC,KAAK,GAAI,MAAM,IAAI,MAAM,oCAAoC,EAClE,OAAO,KAAK,EACd,CAEA,KAAKC,EAAeC,EAAwB,CAAC,EAAY,CACvD,GAAI,KAAK,GAAI,OAAO,KACpB,KAAK,OAASA,EACd,IAAMC,EAAWD,EAAO,mBAAqB,GACvCE,EAAQF,EAAO,kBACfG,EAAOH,EAAO,UACpB,YAAK,GAAK,IAAII,EAASL,EAAO,CAC5B,QAASC,EAAO,SAChB,YAAaA,EAAO,cAAgB,SAAW,SAAWA,EAAO,cAAgB,eAAiB,eAAiB,SACnH,aAAcA,EAAO,cACrB,gBAAiBA,EAAO,6BACxB,WAAYA,EAAO,kBAAoB,SACvC,eAAgBA,EAAO,kBAAoB,SAAW,SAAW,kBACjE,gBAAiBC,EACjB,iBAAkBC,IAAU,KAAUA,GAAS,yBAA2B,uBAAyBD,EACnG,WAAYD,EAAO,YACnB,aAAc,CAACA,EAAO,wBAEtB,mBAAoB,GACpB,MAAO,CAAE,OAAQ,OAAQ,EACzB,UAAWG,GAAQ,CACjB,WAAYA,EAAK,WACjB,aAAcA,EAAK,eACnB,MAAOA,EAAK,aACZ,SAAUA,EAAK,mBACjB,EACA,GAAGH,EAAO,QACZ,CAAC,EACD,KAAK,SAAW,GAChBA,EAAO,SAAS,IAAI,EACb,IACT,CAEA,QAAQK,EAAeC,EAAgCC,EAA0B,CAAC,E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pC,CAGA,eAAeE,EAAqC,CAClD,OACE,KAAK,IAAI,QAASC,GAAUD,EAAS,OAAO,KAAKC,CAAK,EAAE,OAAQC,GAAMD,EAAMC,CAAC,IAAM,EAAK,EAAGD,CAAK,CAAC,IAAM,IAAM,CAAC,EAElH,CAEA,oBAA2B,CACpB,KAAK,IAAI,YAAY,CAC5B,CAEA,iBAAiBX,EAAwD,CAAC,EAAS,CACjF,IAAMa,EAAOb,EAAQ,iBACrB,KAAK,IAAI,MAAM,CAAE,aAAc,EAAM,CAAC,EAClCa,IAAS,IAASA,IAAS,MAAM,KAAK,QAAQA,GAAQ,SAAS,CACrE,CAEA,mBAA0B,CACxB,KAAK,IAAI,OAAO,CAClB,CAEA,wBAAkC,CAChC,OAAO,KAAK,IAAI,WAAW,GAAK,EAClC,CAEA,yBAAmC,CACjC,OAAO,KAAK,IAAI,YAAY,GAAK,EACnC,CAEA,iBAA0B,CACxB,OAAO,KAAK,IAAI,cAAc,GAAK,EACrC,CAEA,gBAAyB,CACvB,OAAO,KAAK,IAAI,aAAa,GAAK,EACpC,CAGA,aAAaA,EAAuB,CAClC,IAAMC,EAAK,KAAK,GAChB,GAAKA,EACL,OAAQD,EAAM,CACZ,IAAK,cACH,OAAOC,EAAG,aAAa,EAAI,aAAe,YAC5C,IAAK,cACH,OAAOA,EAAG,cAAc,EAC1B,IAAK,aACH,OAAOA,EAAG,eAAe,EAC3B,IAAK,cACH,OAAOA,EAAG,aAAa,EACzB,QACE,MACJ,CACF,CAEA,MAAM,iBAAiBC,EAAgBhB,EAA4D,CACjG,GAAK,KAAK,GACV,OAAQ,KAAM,QAAO,iBAAc,GAAG,iBAAiB,KAAK,GAAIgB,EAAOhB,CAAU,CACnF,CAGA,OAAc,CAAC,CACjB,EAGaiB,EAAU,IAAIzB,EACpB0B,EAAQD",
6
+ "names": ["PostHog", "token", "config", "pageview", "leave", "boot", "Numbunch", "event", "properties", "options", "distinctId", "set", "setOnce", "distinct_id", "$device_id", "rest", "id", "key", "type", "callback", "flags", "k", "name", "nb", "error", "posthog", "compat_default"]
7
+ }
@@ -0,0 +1,36 @@
1
+ import type { CaptureEvent, Properties } from './types';
2
+ interface Client {
3
+ capture(event: string, properties?: Properties): CaptureEvent | undefined;
4
+ }
5
+ export interface ExceptionFrame {
6
+ platform: 'web:javascript';
7
+ filename: string;
8
+ function: string;
9
+ lineno?: number;
10
+ colno?: number;
11
+ in_app: boolean;
12
+ chunk_id?: string;
13
+ }
14
+ export interface ExceptionEntry {
15
+ type: string;
16
+ value: string;
17
+ mechanism: {
18
+ type: string;
19
+ handled: boolean;
20
+ synthetic?: boolean;
21
+ };
22
+ stacktrace?: {
23
+ type: 'raw';
24
+ frames: ExceptionFrame[];
25
+ };
26
+ }
27
+ /** Stack frames of `stack`, crash site last. */
28
+ export declare function parseStack(stack: string | undefined): ExceptionFrame[];
29
+ /** The exception list for `error` and its `cause` chain, outermost first. */
30
+ export declare function exceptionList(error: unknown, mechanism?: string, handled?: boolean): ExceptionEntry[];
31
+ /** Captures `error` as `$exception`. */
32
+ export declare function captureException(client: Client, error: unknown, properties?: Properties, mechanism?: string, handled?: boolean): CaptureEvent | undefined;
33
+ /** Captures uncaught errors and unhandled promise rejections. Returns a function that stops. */
34
+ export declare function exceptionAutocapture(client: Client): () => void;
35
+ export {};
36
+ //# sourceMappingURL=exceptions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exceptions.d.ts","sourceRoot":"","sources":["../src/exceptions.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEvD,UAAU,MAAM;IACd,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,UAAU,GAAG,YAAY,GAAG,SAAS,CAAA;CAC1E;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,gBAAgB,CAAA;IAC1B,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,OAAO,CAAA;IACf,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,SAAS,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,OAAO,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,CAAA;IAClE,UAAU,CAAC,EAAE;QAAE,IAAI,EAAE,KAAK,CAAC;QAAC,MAAM,EAAE,cAAc,EAAE,CAAA;KAAE,CAAA;CACvD;AA2BD,gDAAgD;AAChD,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,cAAc,EAAE,CAUtE;AAED,6EAA6E;AAC7E,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,SAAY,EAAE,OAAO,UAAO,GAAG,cAAc,EAAE,CAgBrG;AAED,wCAAwC;AACxC,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,GAAE,UAAe,EAAE,SAAS,SAAY,EAAE,OAAO,UAAO,GAAG,YAAY,GAAG,SAAS,CAE7J;AAED,gGAAgG;AAChG,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,IAAI,CAa/D"}
@@ -0,0 +1,4 @@
1
+ var d=/^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/,f=/^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;function p(t){let n=t.match(d)??t.match(f);if(n)return{filename:n[2],function:n[1]||"?",lineno:Number(n[3]),colno:Number(n[4])}}function l(){let t={},n=globalThis._posthogChunkIds;for(let[o,r]of Object.entries(n??{}))for(let e of o.split(`
2
+ `)){let i=p(e);if(i){t[i.filename]=r;break}}return t}function m(t){let n=l(),o=[];for(let r of(t??"").split(`
3
+ `)){let e=p(r);if(!e)continue;let i=n[e.filename];o.push({platform:"web:javascript",...e,in_app:!/\/node_modules\//.test(e.filename),...i?{chunk_id:i}:{}})}return o.reverse()}function E(t,n="generic",o=!0){let r=[],e=t;for(let i=0;e!=null&&i<5;i++){let s=e instanceof Error?e:void 0,c={type:s&&s.name||"Error",value:s?s.message:typeof e=="string"?e:JSON.stringify(e)??String(e),mechanism:{type:i?"chained":n,handled:o,...s?{}:{synthetic:!0}}},a=s?m(s.stack):[];a.length&&(c.stacktrace={type:"raw",frames:a}),r.push(c),e=s?s.cause:void 0}return r}function u(t,n,o={},r="generic",e=!0){return t.capture("$exception",{$exception_list:E(n,r,e),$exception_level:"error",...o})}function g(t){let n=r=>{u(t,r.error??r.message,{},"onerror",!1)},o=r=>{u(t,r.reason,{},"onunhandledrejection",!1)};return window.addEventListener("error",n),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",n),window.removeEventListener("unhandledrejection",o)}}export{u as captureException,g as exceptionAutocapture,E as exceptionList,m as parseStack};
4
+ //# sourceMappingURL=exceptions.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/exceptions.ts"],
4
+ "sourcesContent": ["// Exception capture (lazy extension). Builds `$exception_list` in PostHog's format so milestone 5's pipeline\n// symbolicates and fingerprints it: frames crash-site last, `chunk_id` from `numbunch sourcemaps inject`.\n\nimport type { CaptureEvent, Properties } from './types'\n\ninterface Client {\n capture(event: string, properties?: Properties): CaptureEvent | undefined\n}\n\nexport interface ExceptionFrame {\n platform: 'web:javascript'\n filename: string\n function: string\n lineno?: number\n colno?: number\n in_app: boolean\n chunk_id?: string\n}\n\nexport interface ExceptionEntry {\n type: string\n value: string\n mechanism: { type: string; handled: boolean; synthetic?: boolean }\n stacktrace?: { type: 'raw'; frames: ExceptionFrame[] }\n}\n\nconst CHROME = /^\\s*at (?:(.+?) \\()?(.+?):(\\d+):(\\d+)\\)?\\s*$/\nconst GECKO = /^\\s*(.*?)@(.+?):(\\d+):(\\d+)\\s*$/\n\nfunction parseLine(line: string): Omit<ExceptionFrame, 'in_app' | 'platform'> | undefined {\n const m = line.match(CHROME) ?? line.match(GECKO)\n if (!m) return undefined\n return { filename: m[2]!, function: m[1] || '?', lineno: Number(m[3]), colno: Number(m[4]) }\n}\n\n/** File name \u2192 chunk ID, from the stacks `numbunch sourcemaps inject` records in `globalThis._posthogChunkIds`. */\nfunction chunkIds(): Record<string, string> {\n const out: Record<string, string> = {}\n const ids = (globalThis as { _posthogChunkIds?: Record<string, string> })._posthogChunkIds\n for (const [stack, id] of Object.entries(ids ?? {})) {\n for (const line of stack.split('\\n')) {\n const frame = parseLine(line)\n if (frame) {\n out[frame.filename] = id\n break\n }\n }\n }\n return out\n}\n\n/** Stack frames of `stack`, crash site last. */\nexport function parseStack(stack: string | undefined): ExceptionFrame[] {\n const chunks = chunkIds()\n const frames: ExceptionFrame[] = []\n for (const line of (stack ?? '').split('\\n')) {\n const frame = parseLine(line)\n if (!frame) continue\n const chunk = chunks[frame.filename]\n frames.push({ platform: 'web:javascript', ...frame, in_app: !/\\/node_modules\\//.test(frame.filename), ...(chunk ? { chunk_id: chunk } : {}) })\n }\n return frames.reverse()\n}\n\n/** The exception list for `error` and its `cause` chain, outermost first. */\nexport function exceptionList(error: unknown, mechanism = 'generic', handled = true): ExceptionEntry[] {\n const out: ExceptionEntry[] = []\n let current: unknown = error\n for (let depth = 0; current !== undefined && current !== null && depth < 5; depth++) {\n const err = current instanceof Error ? current : undefined\n const entry: ExceptionEntry = {\n type: err ? err.name || 'Error' : 'Error',\n value: err ? err.message : typeof current === 'string' ? current : (JSON.stringify(current) ?? String(current)),\n mechanism: { type: depth ? 'chained' : mechanism, handled, ...(err ? {} : { synthetic: true }) },\n }\n const frames = err ? parseStack(err.stack) : []\n if (frames.length) entry.stacktrace = { type: 'raw', frames }\n out.push(entry)\n current = err ? (err as Error & { cause?: unknown }).cause : undefined\n }\n return out\n}\n\n/** Captures `error` as `$exception`. */\nexport function captureException(client: Client, error: unknown, properties: Properties = {}, mechanism = 'generic', handled = true): CaptureEvent | undefined {\n return client.capture('$exception', { $exception_list: exceptionList(error, mechanism, handled), $exception_level: 'error', ...properties })\n}\n\n/** Captures uncaught errors and unhandled promise rejections. Returns a function that stops. */\nexport function exceptionAutocapture(client: Client): () => void {\n const onError = (event: ErrorEvent) => {\n captureException(client, event.error ?? event.message, {}, 'onerror', false)\n }\n const onRejection = (event: PromiseRejectionEvent) => {\n captureException(client, event.reason, {}, 'onunhandledrejection', false)\n }\n window.addEventListener('error', onError)\n window.addEventListener('unhandledrejection', onRejection)\n return () => {\n window.removeEventListener('error', onError)\n window.removeEventListener('unhandledrejection', onRejection)\n }\n}\n"],
5
+ "mappings": "AA0BA,IAAMA,EAAS,+CACTC,EAAQ,kCAEd,SAASC,EAAUC,EAAuE,CACxF,IAAMC,EAAID,EAAK,MAAMH,CAAM,GAAKG,EAAK,MAAMF,CAAK,EAChD,GAAKG,EACL,MAAO,CAAE,SAAUA,EAAE,CAAC,EAAI,SAAUA,EAAE,CAAC,GAAK,IAAK,OAAQ,OAAOA,EAAE,CAAC,CAAC,EAAG,MAAO,OAAOA,EAAE,CAAC,CAAC,CAAE,CAC7F,CAGA,SAASC,GAAmC,CAC1C,IAAMC,EAA8B,CAAC,EAC/BC,EAAO,WAA6D,iBAC1E,OAAW,CAACC,EAAOC,CAAE,IAAK,OAAO,QAAQF,GAAO,CAAC,CAAC,EAChD,QAAWJ,KAAQK,EAAM,MAAM;AAAA,CAAI,EAAG,CACpC,IAAME,EAAQR,EAAUC,CAAI,EAC5B,GAAIO,EAAO,CACTJ,EAAII,EAAM,QAAQ,EAAID,EACtB,KACF,CACF,CAEF,OAAOH,CACT,CAGO,SAASK,EAAWH,EAA6C,CACtE,IAAMI,EAASP,EAAS,EAClBQ,EAA2B,CAAC,EAClC,QAAWV,KAASK,GAAS,IAA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C/D,IAAMG,EAAWC,GAAsB,CACrCL,EAAiBC,EAAQI,EAAM,OAASA,EAAM,QAAS,CAAC,EAAG,UAAW,EAAK,CAC7E,EACMC,EAAeD,GAAiC,CACpDL,EAAiBC,EAAQI,EAAM,OAAQ,CAAC,EAAG,uBAAwB,EAAK,CAC1E,EACA,cAAO,iBAAiB,QAASD,CAAO,EACxC,OAAO,iBAAiB,qBAAsBE,CAAW,EAClD,IAAM,CACX,OAAO,oBAAoB,QAASF,CAAO,EAC3C,OAAO,oBAAoB,qBAAsBE,CAAW,CAC9D,CACF",
6
+ "names": ["CHROME", "GECKO", "parseLine", "line", "m", "chunkIds", "out", "ids", "stack", "id", "frame", "parseStack", "chunks", "frames", "chunk", "exceptionList", "error", "mechanism", "handled", "current", "depth", "err", "entry", "captureException", "client", "properties", "exceptionAutocapture", "onError", "event", "onRejection"]
7
+ }
@@ -0,0 +1,84 @@
1
+ import type { Bootstrap, FlagValue, Properties } from './types';
2
+ /** One flag from `GET /v1/flags/definitions?token=` (only client-evaluable flags are served there). */
3
+ export interface FlagDefinition {
4
+ key: string;
5
+ version?: number;
6
+ active: boolean;
7
+ bucketing: string;
8
+ filters: {
9
+ groups?: {
10
+ properties?: unknown[];
11
+ rollout_percentage?: number | null;
12
+ variant?: string | null;
13
+ }[];
14
+ multivariate?: {
15
+ variants: {
16
+ key: string;
17
+ rollout_percentage: number;
18
+ }[];
19
+ } | null;
20
+ payloads?: Record<string, unknown>;
21
+ };
22
+ holdout?: {
23
+ id: number;
24
+ percentage: number;
25
+ } | null;
26
+ }
27
+ /**
28
+ * Evaluates a client-evaluable flag for `id` with `murmur3_v1`: the condition sets (those pinning a variant first)
29
+ * and the rollout, then for a targeted user the holdout and the variant walk. `undefined` if the definition needs the server.
30
+ */
31
+ export declare function evaluate(flag: FlagDefinition, id: string): FlagValue | undefined;
32
+ export interface FlagsHost {
33
+ token: string;
34
+ host: string;
35
+ ttlMs: number;
36
+ remote: 'lazy' | 'eager' | false;
37
+ localEvaluation: boolean;
38
+ personProperties?: Properties;
39
+ storage?: Storage;
40
+ distinctId(): string;
41
+ groups(): Record<string, string>;
42
+ }
43
+ /**
44
+ * Flag values from, in order: the server-rendered bootstrap, local evaluation of cached definitions, and the last
45
+ * remote evaluation. Values are synchronous; `onFlags` listeners hear about every change.
46
+ */
47
+ export declare class Flags {
48
+ private readonly h;
49
+ private bootstrap;
50
+ private definitions;
51
+ private remoteValues;
52
+ private payloads;
53
+ private requestVersion;
54
+ private remoteRequested;
55
+ /** Definitions are being fetched and none are cached. */
56
+ private started;
57
+ private loading;
58
+ /** Keys read while `loading`: asked of the server afterwards if the definitions do not have them. */
59
+ private readonly waiting;
60
+ private readonly listeners;
61
+ private readonly fetch;
62
+ private readonly cacheKey;
63
+ constructor(h: FlagsHost, bootstrap: Bootstrap | undefined);
64
+ start(storage?: Storage): void;
65
+ /** The flag's value, or `undefined` while unknown (a lazy remote evaluation is then started). */
66
+ value(key: string): FlagValue | undefined;
67
+ /** Whether the value came from local evaluation (for `locally_evaluated` on exposures). */
68
+ isLocal(key: string): boolean;
69
+ version(key: string): number | undefined;
70
+ payload(key: string): unknown;
71
+ /** Every known flag's value. */
72
+ all(): Record<string, FlagValue>;
73
+ /** Calls `listener` now (if anything is known) and on every change. Returns an unsubscribe function. */
74
+ onFlags(listener: (flags: Record<string, FlagValue>) => void): () => void;
75
+ /** The identity changed: bootstrap values belong to the old ID, remote values too. */
76
+ identityChanged(): void;
77
+ /** Refetches definitions (ignoring the cache) and, if remote evaluation is on, remote values. */
78
+ reload(): Promise<void>;
79
+ private notify;
80
+ private loadDefinitions;
81
+ private useDefinitions;
82
+ private loadRemote;
83
+ }
84
+ //# sourceMappingURL=flags.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flags.d.ts","sourceRoot":"","sources":["../src/flags.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAE/D,uG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@@ -0,0 +1,8 @@
1
+ export { Numbunch, init, VERSION, type CaptureOptions, type FlagReadOptions } from './client';
2
+ export { evaluate, type FlagDefinition } from './flags';
3
+ export { bucket, murmur3 } from './murmur3';
4
+ export type * from './types';
5
+ export { uuidv7 } from './uuid';
6
+ /** Reads a bootstrap object a server rendered into `<script type="application/json" id="__numbunch_bootstrap">`. */
7
+ export declare function bootstrapFromDocument(id?: string): import('./types').Bootstrap | undefined;
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,MAAM,UAAU,CAAA;AAC7F,OAAO,EAAE,QAAQ,EAAE,KAAK,cAAc,EAAE,MAAM,SAAS,CAAA;AACvD,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAC3C,mBAAmB,SAAS,CAAA;AAC5B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAE/B,oHAAoH;AACpH,wBAAgB,qBAAqB,CAAC,EAAE,SAAyB,GAAG,OAAO,SAAS,EAAE,SAAS,GAAG,SAAS,CAO1G"}
package/dist/index.js ADDED
@@ -0,0 +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-ARHCREVU.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
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": ["// @numbunch/browser (MIT). The core: capture, identity, sessions, consent, flags and trace context. Exceptions and\n// web vitals are separate entry points (`@numbunch/browser/exceptions`, `@numbunch/browser/web-vitals`).\n\nexport { Numbunch, init, VERSION, type CaptureOptions, type FlagReadOptions } from './client'\nexport { evaluate, type FlagDefinition } from './flags'\nexport { bucket, murmur3 } from './murmur3'\nexport type * from './types'\nexport { uuidv7 } from './uuid'\n\n/** Reads a bootstrap object a server rendered into `<script type=\"application/json\" id=\"__numbunch_bootstrap\">`. */\nexport function bootstrapFromDocument(id = '__numbunch_bootstrap'): import('./types').Bootstrap | undefined {\n try {\n const text = document.getElementById(id)?.textContent\n return text ? JSON.parse(text) : undefined\n } catch {\n return undefined\n }\n}\n"],
5
+ "mappings": "yFAUO,SAASA,EAAsBC,EAAK,uBAAiE,CAC1G,GAAI,CACF,IAAMC,EAAO,SAAS,eAAeD,CAAE,GAAG,YAC1C,OAAOC,EAAO,KAAK,MAAMA,CAAI,EAAI,MACnC,MAAQ,CACN,MACF,CACF",
6
+ "names": ["bootstrapFromDocument", "id", "text"]
7
+ }
@@ -0,0 +1,5 @@
1
+ /** `murmur3_x86_32` of the UTF-8 bytes of `input`. */
2
+ export declare function murmur3(input: string, seed?: number): number;
3
+ /** `murmur3("{key}.{id}{salt}") / 2^32`, in [0, 1). The holdout value is `bucket("holdout-{holdout_id}", id)`. */
4
+ export declare function bucket(key: string, id: string, salt?: string): number;
5
+ //# sourceMappingURL=murmur3.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"murmur3.d.ts","sourceRoot":"","sources":["../src/murmur3.ts"],"names":[],"mappings":"AAIA,sDAAsD;AACtD,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,SAAI,GAAG,MAAM,CAyBvD;AAQD,kHAAkH;AAClH,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,SAAK,GAAG,MAAM,CAEjE"}
@@ -0,0 +1,45 @@
1
+ import type { Properties } from './types';
2
+ /** Stored in the first-party cookie: the anonymous ID, the session and consent only. */
3
+ export interface CookieState {
4
+ /** Anonymous ID. */
5
+ a?: string;
6
+ /** Session: [ID, last activity ms, start ms]. */
7
+ s?: [string, number, number];
8
+ /** Consent: 1 opted in, 0 opted out. */
9
+ c?: 0 | 1;
10
+ }
11
+ /** Stored in localStorage. */
12
+ export interface LocalState {
13
+ /** Distinct ID once identified. */
14
+ d?: string;
15
+ /** Identified. */
16
+ i?: 1;
17
+ /** Super properties. */
18
+ p?: Properties;
19
+ /** Groups. */
20
+ g?: Record<string, string>;
21
+ }
22
+ export type Mode = 'cookie' | 'localStorage' | 'memory';
23
+ export declare function local(): Storage | undefined;
24
+ export declare function readCookie(name: string): string | undefined;
25
+ export declare class Persistence {
26
+ private readonly name;
27
+ private readonly mode;
28
+ private readonly domain?;
29
+ cookie: CookieState;
30
+ local: LocalState;
31
+ private readonly store;
32
+ constructor(name: string, mode: Mode, domain?: string | undefined);
33
+ save(): void;
34
+ }
35
+ /**
36
+ * Identity and session from posthog-js's persistence entry `ph_{token}_posthog`. With posthog-js 1.234's default
37
+ * `localStorage+cookie`, the cookie holds only `distinct_id`, `$sesid` and `$epp`; `$device_id` and `$user_state`
38
+ * are in localStorage under the same name, which counts only if it belongs to the same `distinct_id` (the cookie
39
+ * may come from another subdomain). Without it, `$epp` tells whether the user was identified.
40
+ */
41
+ export declare function postHogIdentity(token: boolean | string): {
42
+ cookie: CookieState;
43
+ local: LocalState;
44
+ } | undefined;
45
+ //# sourceMappingURL=storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEzC,wFAAwF;AACxF,MAAM,WAAW,WAAW;IAC1B,oBAAoB;IACpB,CAAC,CAAC,EAAE,MAAM,CAAA;IACV,iDAAiD;IACjD,CAAC,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;IAC5B,wCAAwC;IACxC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAA;CACV;AAED,8BAA8B;AAC9B,MAAM,WAAW,UAAU;IACzB,mCAAmC;IACnC,CAAC,CAAC,EAAE,MAAM,CAAA;IACV,kBAAkB;IAClB,CAAC,CAAC,EAAE,CAAC,CAAA;IACL,wBAAwB;IACxB,CAAC,CAAC,EAAE,UAAU,CAAA;IACd,cAAc;IACd,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC3B;AAED,MAAM,MAAM,IAAI,GAAG,QAAQ,GAAG,cAAc,GAAG,QAAQ,CAAA;AAUvD,wBAAgB,KAAK,IAAI,OAAO,GAAG,SAAS,CAS3C;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAU3D;AAED,qBAAa,WAAW;IAMpB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;IAP1B,MAAM,EAAE,WAAW,CAAA;IACnB,KAAK,EAAE,UAAU,CAAA;IACjB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAqB;gBAGxB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,IAAI,EACV,MAAM,CAAC,EAAE,MAAM,YAAA;IAQlC,IAAI,IAAI,IAAI;CAcb;AAWD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,KAAK,EAAE,UAAU,CAAA;CAAE,GAAG,SAAS,CAiB/G"}
@@ -0,0 +1,18 @@
1
+ import type { TracingOptions } from './types';
2
+ /** The page's W3C trace: adopted from `<meta name="traceparent">` (server rendering), else generated. */
3
+ export declare class Trace {
4
+ traceId: string;
5
+ parentId: string | undefined;
6
+ constructor();
7
+ /** A new trace, for example on a client-side navigation. */
8
+ rotate(): void;
9
+ /** A `traceparent` header for an outgoing request: this trace, a new span ID, sampled. */
10
+ header(): string;
11
+ }
12
+ /**
13
+ * Wraps `window.fetch` so requests to the configured targets carry `traceparent` and `baggage` (`session.id`,
14
+ * `user.id`), letting backend spans join the page's trace and know the user. Returns a function that restores
15
+ * `fetch`.
16
+ */
17
+ export declare function propagate(trace: Trace, options: TracingOptions, baggage: () => Record<string, string>): () => void;
18
+ //# sourceMappingURL=trace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trace.d.ts","sourceRoot":"","sources":["../src/trace.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAG7C,yGAAyG;AACzG,qBAAa,KAAK;IAChB,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAA;;IAS5B,4DAA4D;IAC5D,MAAM,IAAI,IAAI;IAKd,0FAA0F;IAC1F,MAAM,IAAI,MAAM;CAGjB;AAgBD;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,IAAI,CA6BlH"}
@@ -0,0 +1,31 @@
1
+ import type { CaptureEvent } from './types';
2
+ export interface TransportOptions {
3
+ url: string;
4
+ token: string;
5
+ flushIntervalMs: number;
6
+ maxBatchSize: number;
7
+ perSecond: number;
8
+ burst: number;
9
+ }
10
+ /** Gzip with `CompressionStream`, or `undefined` where it is not available. */
11
+ export declare function gzip(text: string): Promise<Blob | undefined>;
12
+ /**
13
+ * The capture queue: batches every `flushIntervalMs` or `maxBatchSize` events, gzips with `CompressionStream`,
14
+ * retries with exponential backoff and jitter, rate-limits with a token bucket, and sends what is left with
15
+ * `sendBeacon` when the page is hidden.
16
+ */
17
+ export declare class Transport {
18
+ private readonly o;
19
+ private queue;
20
+ private timer;
21
+ private tokens;
22
+ private refilled;
23
+ private readonly fetch;
24
+ constructor(o: TransportOptions);
25
+ /** Queues an event. Returns false if the rate limit dropped it. */
26
+ push(event: CaptureEvent, beacon?: boolean): boolean;
27
+ /** Sends everything queued; with `beacon`, synchronously through `sendBeacon` (page hide). */
28
+ flush(beacon?: boolean): Promise<void>;
29
+ private send;
30
+ }
31
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAE3C,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,EAAE,MAAM,CAAA;IACb,eAAe,EAAE,MAAM,CAAA;IACvB,YAAY,EAAE,MAAM,CAAA;IACpB,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,MAAM,CAAA;CACd;AAMD,+EAA+E;AAC/E,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,CAOlE;AAED;;;;GAIG;AACH,qBAAa,SAAS;IAOR,OAAO,CAAC,QAAQ,CAAC,CAAC;IAN9B,OAAO,CAAC,KAAK,CAAqB;IAClC,OAAO,CAAC,KAAK,CAA2C;IACxD,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,QAAQ,CAAa;IAC7B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAoC;gBAE7B,CAAC,EAAE,gBAAgB;IAIhD,mEAAmE;IACnE,IAAI,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,UAAQ,GAAG,OAAO;IAalD,8FAA8F;IAC9F,KAAK,CAAC,MAAM,UAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;YAYtB,IAAI;CAuBnB"}
@@ -0,0 +1,85 @@
1
+ export type Properties = Record<string, unknown>;
2
+ /** A flag's value: the variant key, or whether a boolean flag is on. */
3
+ export type FlagValue = string | boolean;
4
+ /** Values computed on the server (for example by `@numbunch/node` `getBootstrap`) and embedded in the page. */
5
+ export interface Bootstrap {
6
+ distinctId?: string;
7
+ isIdentified?: boolean;
8
+ flags?: Record<string, FlagValue>;
9
+ payloads?: Record<string, unknown>;
10
+ }
11
+ /** An event as sent to the capture endpoint (PostHog's shape). */
12
+ export interface CaptureEvent {
13
+ event: string;
14
+ properties: Properties;
15
+ timestamp: string;
16
+ uuid: string;
17
+ }
18
+ /** Returns the event to send (possibly changed) or `null` to drop it. */
19
+ export type BeforeSend = (event: CaptureEvent) => CaptureEvent | null;
20
+ export interface FlagOptions {
21
+ /** Evaluate client-evaluable (`murmur3_v1`) flags from cached definitions. Default true. */
22
+ localEvaluation?: boolean;
23
+ /**
24
+ * Ask `/flags` for flags that cannot be evaluated locally: `lazy` (default) on the first read of such a flag,
25
+ * `eager` at start-up, `false` never.
26
+ */
27
+ remote?: 'lazy' | 'eager' | false;
28
+ /** How long cached definitions are used without a request. Default 5 minutes. */
29
+ cacheTtlMs?: number;
30
+ /** Send `$feature_flag_called` on reads (once per flag and value). Default true. */
31
+ sendExposure?: boolean;
32
+ /** Person properties sent with remote evaluation. */
33
+ personProperties?: Properties;
34
+ }
35
+ export interface TracingOptions {
36
+ /**
37
+ * Where `fetch` gets `traceparent` (and `baggage`): `same-origin` (default), a list of origins, URL prefixes or
38
+ * regular expressions, or `false` to leave `fetch` alone.
39
+ */
40
+ propagateTo?: 'same-origin' | (string | RegExp)[] | false;
41
+ /** Also send `baggage: session.id=…,user.id=…`. Default true. */
42
+ baggage?: boolean;
43
+ }
44
+ export interface NumbunchOptions {
45
+ /** Capture host, often a reverse proxy on your own domain such as `/ingest`. Default `https://in.numbunch.com`. */
46
+ apiHost?: string;
47
+ /** Host for flag definitions and remote evaluation. Default `apiHost`. */
48
+ flagsHost?: string;
49
+ /**
50
+ * `cookie` (default): one first-party cookie with the anonymous ID, session and consent, the rest in
51
+ * localStorage. `localStorage`: everything in localStorage. `memory`: nothing persisted.
52
+ */
53
+ persistence?: 'cookie' | 'localStorage' | 'memory';
54
+ cookieDomain?: string;
55
+ /** Capture nothing until `optIn()`. */
56
+ optOutByDefault?: boolean;
57
+ /** Send the cookieless sentinel ID; the server derives a daily visitor ID and the session. Persists nothing. */
58
+ cookieless?: boolean;
59
+ /** `identified_only` (default): events are personless until `identify`. */
60
+ personProfiles?: 'identified_only' | 'always';
61
+ bootstrap?: Bootstrap;
62
+ /** Take over the identity and session of a posthog-js cookie (`ph_{token}_posthog`) on first load. */
63
+ adoptPostHogCookie?: boolean | string;
64
+ beforeSend?: BeforeSend | BeforeSend[];
65
+ /** Capture `$pageview` on start-up. Default false. */
66
+ capturePageview?: boolean;
67
+ /** Capture `$pageleave` when the page is hidden for good. Default false. */
68
+ capturePageleave?: boolean;
69
+ /** Fetch the environment's remote config and load the exception and web-vitals extensions it enables. */
70
+ remoteConfig?: boolean;
71
+ flushIntervalMs?: number;
72
+ maxBatchSize?: number;
73
+ /** Client-side rate limit (events per second, burst). Default 10 and 100. */
74
+ rateLimit?: {
75
+ perSecond: number;
76
+ burst: number;
77
+ };
78
+ sessionIdleMs?: number;
79
+ sessionMaxMs?: number;
80
+ flags?: FlagOptions;
81
+ tracing?: TracingOptions;
82
+ /** Called once the client is ready (synchronously after construction). */
83
+ loaded?: (client: unknown) => void;
84
+ }
85
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAEhD,wEAAwE;AACxE,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,OAAO,CAAA;AAExC,+GAA+G;AAC/G,MAAM,WAAW,SAAS;IACxB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,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E,OAAO,CAAA;IACpB,2EAA2E;IAC3E,cAAc,CAAC,EAAE,iBAAiB,GAAG,QAAQ,CAAA;IAC7C,SAAS,CAAC,EAAE,SAAS,CAAA;IACrB,sGAAsG;IACtG,kBAAkB,CAAC,EAAE,OAAO,GAAG,MAAM,CAAA;IACrC,UAAU,CAAC,EAAE,UAAU,GAAG,UAAU,EAAE,CAAA;IACtC,sDAAsD;IACtD,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,4EAA4E;IAC5E,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,yGAAyG;IACzG,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,6EAA6E;IAC7E,SAAS,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAA;IAChD,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,KAAK,CAAC,EAAE,WAAW,CAAA;IACnB,OAAO,CAAC,EAAE,cAAc,CAAA;IACxB,0EAA0E;IAC1E,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAA;CACnC"}
package/dist/uuid.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /** Random hex of `bytes` bytes. */
2
+ export declare function randomHex(bytes: number): string;
3
+ /** A UUIDv7 (RFC 9562): 48-bit Unix milliseconds, version 7, variant 10, random bits. */
4
+ export declare function uuidv7(now?: number): string;
5
+ /** The millisecond timestamp of a UUIDv7, or `undefined`. */
6
+ export declare function uuidv7Time(id: string): number | undefined;
7
+ //# sourceMappingURL=uuid.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uuid.d.ts","sourceRoot":"","sources":["../src/uuid.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAK/C;AAED,yFAAyF;AACzF,wBAAgB,MAAM,CAAC,GAAG,SAAa,GAAG,MAAM,CAI/C;AAED,6DAA6D;AAC7D,wBAAgB,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEzD"}
@@ -0,0 +1,13 @@
1
+ import type { CaptureEvent, Properties } from './types';
2
+ interface Client {
3
+ capture(event: string, properties?: Properties, options?: {
4
+ transport?: 'sendBeacon';
5
+ }): CaptureEvent | undefined;
6
+ }
7
+ /** Reports LCP, INP, CLS and FCP (or `metrics`), batched into one event per page after 5 s or on page hide. */
8
+ export declare function webVitals(client: Client, options?: {
9
+ metrics?: string[];
10
+ signal?: AbortSignal;
11
+ }): void;
12
+ export {};
13
+ //# sourceMappingURL=web-vitals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-vitals.d.ts","sourceRoot":"","sources":["../src/web-vitals.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEvD,UAAU,MAAM;IACd,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,YAAY,CAAA;KAAE,GAAG,YAAY,GAAG,SAAS,CAAA;CAClH;AAID,+GAA+G;AAC/G,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE;IAAE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAAO,GAAG,IAAI,CAuB1G"}
@@ -0,0 +1,2 @@
1
+ import{onCLS as m,onFCP as v,onINP as b,onLCP as C}from"web-vitals";var P=["LCP","INP","CLS","FCP"];function y(l,o={}){let u=o.metrics??P,e={},r,s=n=>{clearTimeout(r),r=void 0,Object.keys(e).length&&(l.capture("$web_vitals",e,n?{transport:"sendBeacon"}:{}),e={})},t=n=>{if(o.signal?.aborted||!u.includes(n.name))return;let{name:i,value:a,delta:p,id:c,rating:d,navigationType:f}=n;e[`$web_vitals_${i}_value`]=a,e[`$web_vitals_${i}_event`]={name:i,value:a,delta:p,id:c,rating:d,navigationType:f,$current_url:location.href},document.visibilityState==="hidden"?s(!0):r??=setTimeout(()=>s(!1),5e3)};C(t),b(t),m(t),v(t)}export{y as webVitals};
2
+ //# sourceMappingURL=web-vitals.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/web-vitals.ts"],
4
+ "sourcesContent": ["// Web vitals (lazy extension), using the `web-vitals` library. Captures `$web_vitals` with posthog-js's property\n// names (`$web_vitals_LCP_value`, \u2026), which the web analytics p75 read (milestone 4).\n\nimport { onCLS, onFCP, onINP, onLCP, type Metric } from 'web-vitals'\n\nimport type { CaptureEvent, Properties } from './types'\n\ninterface Client {\n capture(event: string, properties?: Properties, options?: { transport?: 'sendBeacon' }): CaptureEvent | undefined\n}\n\nconst ALL = ['LCP', 'INP', 'CLS', 'FCP']\n\n/** Reports LCP, INP, CLS and FCP (or `metrics`), batched into one event per page after 5 s or on page hide. */\nexport function webVitals(client: Client, options: { metrics?: string[]; signal?: AbortSignal } = {}): void {\n const allowed = options.metrics ?? ALL\n let buffer: Properties = {}\n let timer: ReturnType<typeof setTimeout> | undefined\n const flush = (beacon: boolean) => {\n clearTimeout(timer)\n timer = undefined\n if (!Object.keys(buffer).length) return\n client.capture('$web_vitals', buffer, beacon ? { transport: 'sendBeacon' } : {})\n buffer = {}\n }\n const report = (metric: Metric) => {\n if (options.signal?.aborted || !allowed.includes(metric.name)) return\n const { name, value, delta, id, rating, navigationType } = metric\n buffer[`$web_vitals_${name}_value`] = value\n buffer[`$web_vitals_${name}_event`] = { name, value, delta, id, rating, navigationType, $current_url: location.href }\n if (document.visibilityState === 'hidden') flush(true)\n else timer ??= setTimeout(() => flush(false), 5000)\n }\n onLCP(report)\n onINP(report)\n onCLS(report)\n onFCP(report)\n}\n"],
5
+ "mappings": "AAGA,OAAS,SAAAA,EAAO,SAAAC,EAAO,SAAAC,EAAO,SAAAC,MAA0B,aAQxD,IAAMC,EAAM,CAAC,MAAO,MAAO,MAAO,KAAK,EAGhC,SAASC,EAAUC,EAAgBC,EAAwD,CAAC,EAAS,CAC1G,IAAMC,EAAUD,EAAQ,SAAWH,EAC/BK,EAAqB,CAAC,EACtBC,EACEC,EAASC,GAAoB,CACjC,aAAaF,CAAK,EAClBA,EAAQ,OACH,OAAO,KAAKD,CAAM,EAAE,SACzBH,EAAO,QAAQ,cAAeG,EAAQG,EAAS,CAAE,UAAW,YAAa,EAAI,CAAC,CAAC,EAC/EH,EAAS,CAAC,EACZ,EACMI,EAAUC,GAAmB,CACjC,GAAIP,EAAQ,QAAQ,SAAW,CAACC,EAAQ,SAASM,EAAO,IAAI,EAAG,OAC/D,GAAM,CAAE,KAAAC,EAAM,MAAAC,EAAO,MAAAC,EAAO,GAAAC,EAAI,OAAAC,EAAQ,eAAAC,CAAe,EAAIN,EAC3DL,EAAO,eAAeM,CAAI,QAAQ,EAAIC,EACtCP,EAAO,eAAeM,CAAI,QAAQ,EAAI,CAAE,KAAAA,EAAM,MAAAC,EAAO,MAAAC,EAAO,GAAAC,EAAI,OAAAC,EAAQ,eAAAC,EAAgB,aAAc,SAAS,IAAK,EAChH,SAAS,kBAAoB,SAAUT,EAAM,EAAI,EAChDD,IAAU,WAAW,IAAMC,EAAM,EAAK,EAAG,GAAI,CACpD,EACAR,EAAMU,CAAM,EACZX,EAAMW,CAAM,EACZb,EAAMa,CAAM,EACZZ,EAAMY,CAAM,CACd",
6
+ "names": ["onCLS", "onFCP", "onINP", "onLCP", "ALL", "webVitals", "client", "options", "allowed", "buffer", "timer", "flush", "beacon", "report", "metric", "name", "value", "delta", "id", "rating", "navigationType"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "@numbunch/browser",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Numbunch browser SDK: capture, sessions, consent, flags evaluated locally with murmur3_v1, trace context",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/MidgardAI/numbunch.git",
9
+ "directory": "sdk/browser"
10
+ },
11
+ "type": "module",
12
+ "sideEffects": false,
13
+ "files": [
14
+ "dist",
15
+ "LICENSE"
16
+ ],
17
+ "main": "./dist/index.js",
18
+ "module": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ },
25
+ "./exceptions": {
26
+ "types": "./dist/exceptions.d.ts",
27
+ "default": "./dist/exceptions.js"
28
+ },
29
+ "./web-vitals": {
30
+ "types": "./dist/web-vitals.d.ts",
31
+ "default": "./dist/web-vitals.js"
32
+ },
33
+ "./compat": {
34
+ "types": "./dist/compat.d.ts",
35
+ "default": "./dist/compat.js"
36
+ },
37
+ "./package.json": "./package.json"
38
+ },
39
+ "peerDependencies": {
40
+ "web-vitals": ">=4"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "web-vitals": {
44
+ "optional": true
45
+ }
46
+ },
47
+ "devDependencies": {
48
+ "@eslint/js": "10.0.1",
49
+ "eslint": "10.15.0",
50
+ "globals": "17.14.0",
51
+ "typescript": "6.0.3",
52
+ "typescript-eslint": "8.72.2",
53
+ "vitest": "5.1.0",
54
+ "esbuild": "0.28.2",
55
+ "jsdom": "31.0.1",
56
+ "web-vitals": "6.2.3",
57
+ "@types/node": "22.20.5"
58
+ },
59
+ "publishConfig": {
60
+ "access": "public"
61
+ },
62
+ "scripts": {
63
+ "build": "node scripts/build.mjs",
64
+ "size": "node scripts/size.mjs",
65
+ "typecheck": "tsc --noEmit -p tsconfig.json",
66
+ "lint": "eslint .",
67
+ "test": "vitest run",
68
+ "test:e2e": "pnpm --filter numbunch-sdk-e2e test:browser"
69
+ }
6
70
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.