@pydantic/logfire-session-replay 0.3.2 → 0.3.4

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/README.md CHANGED
@@ -142,14 +142,17 @@ seconds by default). After 30 seconds without recorded pointer, input, touch,
142
142
  scroll, media, resize, drag, or selection activity, background events use the
143
143
  greater of `flushIntervalMs` and 60 seconds. New user activity restores the
144
144
  configured cadence. After five minutes without activity, background events use
145
- the greater of `flushIntervalMs` and five minutes. Reaching `maxBufferBytes`
146
- still flushes immediately.
147
-
148
- Replays must reach `minSessionDurationMs` (5 seconds by default) before they are
149
- uploaded. An earlier flush keeps the events buffered for the remaining time,
150
- while stopping the recorder before the minimum discards them. Set the option to
151
- `0` when an application must upload a shorter replay. The `maxBufferBytes`
152
- memory bound still takes precedence over the duration floor.
145
+ the greater of `flushIntervalMs` and five minutes. After the replay reaches its
146
+ minimum duration, reaching `maxBufferBytes` still flushes immediately.
147
+
148
+ Replays must contain at least `minSessionDurationMs` of recorded events (5
149
+ seconds by default) before they are uploaded. While waiting, events stay
150
+ buffered. The initial `Meta` and `FullSnapshot` anchor is retained even when it
151
+ exceeds `maxBufferBytes`; later events are kept only while the estimated buffer
152
+ remains within the limit. After an overflow, a fresh full snapshot re-anchors
153
+ the recording when the minimum is reached. Stopping the recorder before the
154
+ minimum discards the recording. Set the option to `0` when an application must
155
+ upload a shorter replay.
153
156
 
154
157
  Sessions created only by background timeout monitoring remain held until the
155
158
  next user activity. Calling `flush()`, hiding the page, or stopping the recorder
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@rrweb/record"),t=require("fflate");const n={DomContentLoaded:0,Load:1,FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Custom:5,Plugin:6},r={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5,TouchMove:6,MediaInteraction:7,Drag:12,Selection:14},i={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},a={Error:`logfire.error`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},o={sessionSampleRate:1,onErrorSampleRate:1,maskAllText:!0,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,minSessionDurationMs:5e3,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:144e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,redactUrlPatterns:[/.+/u]},s=new Set([r.MouseMove,r.MouseInteraction,r.Scroll,r.ViewportResize,r.Input,r.TouchMove,r.MediaInteraction,r.Drag,r.Selection]);function c(e){return e.type!==n.IncrementalSnapshot||typeof e.data!=`object`||e.data===null||!(`source`in e.data)?!1:typeof e.data.source==`number`&&s.has(e.data.source)}function l(e,t){return t<3e4?e:t<3e5?Math.max(e,6e4):Math.max(e,3e5)}function u(e,t){return t.some(t=>new RegExp(t.source,t.flags).test(e))}function d(e,t,n){if(!u(e,t))return e;try{let t=new URL(e,n);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const f=[`log`,`info`,`warn`,`error`,`debug`],p=1024,m=()=>void 0;function h(e,t={}){let n=[],r=S(t.onError);try{for(let t of f)typeof console[t]==`function`&&n.push(C(console,t,(n,i)=>function(...o){return i()&&x(e,a.Console,{level:t,args:o.slice(0,10).map(E)},r),n.apply(this,o)}));return w(n)}catch(e){throw T(n),e}}function ee(e,t){let n=y(t),r={...n,onError:S(n.onError)},i=_(e,r);try{return w([i,v(e,r)])}catch(e){throw i(),e}}function g(e,t={redactUrlPatterns:[]}){let n=S(t.onError),r=r=>{let i=d(window.location.href,t.redactUrlPatterns??[],window.location.href);x(e,a.Navigation,{url:i,kind:r},n)},i=[];try{i.push(C(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(C(history,`replaceState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`replace`),i}));let e=!0,t=()=>{e&&r(`pop`)};return window.addEventListener(`popstate`,t),i.push(()=>{e=!1,window.removeEventListener(`popstate`,t)}),w(i)}catch(e){throw T(i),e}}function _(e,t){return typeof window.fetch==`function`?C(window,`fetch`,(n,r)=>{let i=async function(i,o){let s=n;if(!r())return s.call(this,i,o);let c=t.now(),l=ne(i,o),u=re(i);if(A(u,t.ignoreUrlPatterns))return s.call(this,i,o);let f=d(u,t.redactUrlPatterns,window.location.href),p=k(o?.body);try{let n=await s.call(this,i,o);return r()&&x(e,a.Network,O({method:l,url:f,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:p,resBytes:ie(n.headers)}),t.onError),n}catch(n){throw r()&&x(e,a.Network,O({method:l,url:f,status:0,durationMs:Math.max(0,t.now()-c),failed:!0,reqBytes:p}),t.onError),n}},o=Reflect.get(n,`__original`);return Object.defineProperty(i,"__original",{configurable:!0,value:typeof o==`function`?o:n,writable:!0}),i}):m}function v(e,t){let n=window.XMLHttpRequest.prototype,r=new WeakMap,i=[];try{return i.push(C(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return A(s,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:a.toUpperCase(),url:d(s,t.redactUrlPatterns,window.location.href),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(C(n,`send`,(n,i)=>function(...o){let[s]=o,c=i()?r.get(this):void 0;if(c===void 0)return n.apply(this,o);c.startedAt=t.now(),c.reqBytes=k(s);let l=()=>{c.failed=!0},u=()=>{c.emitted||(c.emitted=!0,this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),i()&&x(e,a.Network,O({method:c.method,url:c.url,status:this.status,durationMs:Math.max(0,t.now()-c.startedAt),failed:c.failed||this.status===0,reqBytes:c.reqBytes,resBytes:ae(this)}),t.onError))};this.addEventListener(`error`,l),this.addEventListener(`abort`,l),this.addEventListener(`timeout`,l),this.addEventListener(`loadend`,u,{once:!0});try{return n.apply(this,o)}catch(n){throw this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),this.removeEventListener(`loadend`,u),i()&&x(e,a.Network,O({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),w(i)}catch(e){throw T(i),e}}function y(e){return{...e,ignoreUrlPatterns:b(e.ignoreUrlPatterns),redactUrlPatterns:b(e.redactUrlPatterns)}}function b(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function x(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function S(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);te(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function te(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function C(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return m;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function w(e){let t=!1;return()=>{t||(t=!0,T(e))}}function T(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function E(e){if(e==null)return String(e);if(typeof e==`string`)return D(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return D(e.stack??`${e.name}: ${e.message}`);try{return D(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function D(e){if(e.length<=p)return e;let t=e.charCodeAt(p-1),n=t>=55296&&t<=56319?p-1:p;return`${e.slice(0,n)}...(+${String(e.length-n)} chars)`}function ne(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function re(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function ie(e){let t=e.get(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}function ae(e){try{let t=e.getResponseHeader(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}catch{return}}function O(e){return{method:e.method,url:e.url,status:e.status,durationMs:e.durationMs,...e.failed===void 0?{}:{failed:e.failed},...e.reqBytes===void 0?{}:{reqBytes:e.reqBytes},...e.resBytes===void 0?{}:{resBytes:e.resBytes}}}function k(e){if(e==null)return 0;if(typeof e==`string`)return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Blob)return e.size}function A(e,t){return u(e,t)}const oe=new Set([`action`,`formaction`,`href`,`src`]);function se(t){let n=()=>{t.beforeUserActivity?.()},r={emit:e=>{t.emit(ce(e,t.redactUrlPatterns))},maskAllInputs:t.maskAllInputs,recordCanvas:!1,collectFonts:!1,inlineImages:!1,recordCrossOriginIframes:!1,slimDOMOptions:`all`,hooks:{input:n,mediaInteaction:n,mouseInteraction:n,mousemove:n,scroll:n,selection:n,viewportResize:n},sampling:{mousemove:100,mouseInteraction:!0,scroll:250,media:800,input:`last`}};t.maskAllText?r.maskTextSelector=`*`:t.maskTextSelector!==void 0&&t.maskTextSelector.length>0&&(r.maskTextSelector=t.maskTextSelector),t.blockSelector!==void 0&&t.blockSelector.length>0&&(r.blockSelector=t.blockSelector),t.checkoutEveryNms!==void 0&&t.checkoutEveryNms>0&&(r.checkoutEveryNms=t.checkoutEveryNms);let i=(0,e.record)(r);if(i===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{i()},addCustomEvent:(t,n)=>{e.record.addCustomEvent(t,n)},takeFullSnapshot:()=>{e.record.takeFullSnapshot(!0)}}}function ce(e,t){if(typeof e.data!=`object`||e.data===null)return e;let i=e.data;if(e.type===n.Meta){if(typeof i.href!=`string`)return e;let n=d(i.href,t,window.location.href);return n===i.href?e:{...e,data:{...i,href:n}}}if(e.type!==n.FullSnapshot&&(e.type!==n.IncrementalSnapshot||i.source!==r.Mutation))return e;let a=j(i,t);return a===i?e:{...e,data:a}}function j(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=j(i,t);e!==i&&(n=!0),r.push(e)}return n?r:e}if(typeof e!=`object`||!e)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n=e===`attributes`&&!Array.isArray(a)?M(a,t):j(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function M(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){if(!oe.has(e.toLowerCase())||typeof a!=`string`){i[e]=a;continue}let n=d(a,t,window.location.href);n!==a&&(r=!0),i[e]=n}return r?i:e}function N(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function le(e){let t=e.random??Math.random;return t()<N(e.sessionSampleRate)?`full`:t()<N(e.onErrorSampleRate)?`buffer`:`off`}const ue=/^[a-z][a-z0-9_]{0,63}$/u;function de(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function fe(e,t){if(e===void 0)return Object.freeze({});let n;try{n=e()}catch(e){return t(e),Object.freeze({})}if(typeof n!=`object`||!n||Array.isArray(n))return Object.freeze({});let r;try{r=Object.getPrototypeOf(n)}catch(e){return t(e),Object.freeze({})}if(r!==Object.prototype&&r!==null)return Object.freeze({});let i;try{i=Object.keys(n)}catch(e){return t(e),Object.freeze({})}let a={},o=0;for(let e of i){if(!ue.test(e))continue;let r;try{r=Reflect.get(n,e)}catch(e){t(e);continue}if((typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r)||typeof r==`string`&&de(r,200))&&(a[e]=r,o+=1,o===20))break}return Object.freeze(a)}function pe(e=Date.now){let t=e(),n=new Uint8Array(new ArrayBuffer(16));me(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/2**8)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function me(e){let t=globalThis.crypto;if(typeof t?.getRandomValues==`function`){t.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const P=`lf_session_replay`;var he=class{idleTimeoutMs;maxDurationMs;now;storage;memorySession;pendingSession;persistenceTimer;constructor(e){this.idleTimeoutMs=e.idleTimeoutMs,this.maxDurationMs=e.maxDurationMs,this.now=e.now??Date.now,this.storage=e.storage===void 0?F():e.storage}getSession(){let e=this.now();if(this.memorySession!==void 0&&!this.isExpired(this.memorySession,e))return this.memorySession;let t=this.read();return t!==void 0&&!this.isExpired(t,e)?t:this.createSession(e)}touch(){let e=this.now(),t={...this.getSession(),lastActivityAt:e};return this.memorySession=t,this.scheduleWrite(t),t}reset(){return this.createSession(this.now())}flushPendingStorage(){this.persistenceTimer!==void 0&&(clearTimeout(this.persistenceTimer),this.persistenceTimer=void 0);let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)}isExpired(e,t){return t-e.lastActivityAt>this.idleTimeoutMs||t-e.startedAt>this.maxDurationMs}createSession(e){let t={id:pe(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(P);if(e!==null){let t=JSON.parse(e);if(I(t))return this.memorySession=t,t}}catch{return this.memorySession}return this.memorySession}write(e){if(this.memorySession=e,this.storage!==null)try{this.storage.setItem(P,JSON.stringify(e))}catch{}}scheduleWrite(e){this.pendingSession=e,this.persistenceTimer===void 0&&(this.persistenceTimer=setTimeout(()=>{this.persistenceTimer=void 0;let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)},1e3))}writeNow(e){this.memorySession=e,this.write(e)}};function F(){try{return globalThis.sessionStorage??null}catch{return null}}function I(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}function L(e){return typeof e==`object`&&e?e:void 0}function R(e){return typeof e==`string`&&e.length>0?e:void 0}function ge(e,t,o,s={}){let c=1/0,l=0,u=0,d=0,f=0,p=!1,m=new Set;for(let e of t){e.timestamp<c&&(c=e.timestamp),e.timestamp>l&&(l=e.timestamp);let t=L(e.data);if(e.type===n.FullSnapshot)p=!0;else if(e.type===n.Meta){let e=R(t?.href);e!==void 0&&m.add(e)}else if(e.type===n.IncrementalSnapshot&&t!==void 0){let e=t.source;if(e===r.MouseInteraction){let e=t.type;(e===i.Click||e===i.DblClick)&&u++}else e===r.Input&&d++}else if(e.type===n.Custom&&t!==void 0){let e=R(t.tag),n=L(t.payload);if(e===a.Error)f++;else if(e===a.Console)n?.level===`error`&&f++;else if(e===a.Navigation){let e=R(n?.url);e!==void 0&&m.add(e)}}}return{seq:e,firstTimestamp:c===1/0?0:c,lastTimestamp:l,eventCount:t.length,clickCount:u,keypressCount:d,errorCount:f,hasFullSnapshot:p,urls:[...m],...o!==void 0&&o.length>0?{distinctId:o}:{},...Object.keys(s).length===0?{}:{sessionAttributes:{...s}}}}const z=`lf_session_replay_seq`,_e={gzip:t.gzip,gzipSync:t.gzipSync};var ve=class{buffer=[];bufferHasFullSnapshot=!1;pendingBytes=0;seq=0;timer;nextFlushAt;lastUserActivityAt;startedAt;started=!1;held;heldBufferIncomplete=!1;mode;flushing;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;constructor(e,t,n,r=F(),i=_e,a={},o={}){this.config=e,this.sessionId=t,this.sessionAttributes=Object.freeze({...a}),this.mode=n,this.storage=r,this.compression=i,this.held=o.holdUntilActivity===!0&&n===`full`,this.seq=this.loadSeq(t),this.startedAt=this.config.now(),this.lastUserActivityAt=this.startedAt}start(){this.started||this.mode!==`full`||(this.started=!0,this.scheduleFlush())}add(e){c(e)&&(this.lastUserActivityAt=this.config.now());let t=H(e);if(this.mode===`buffer`||this.held){if(e.type===n.Meta){this.buffer=[e],this.bufferHasFullSnapshot=!1,this.pendingBytes=t;return}if(e.type===n.FullSnapshot){let r=!this.bufferHasFullSnapshot&&this.buffer.length===1&&this.buffer[0]?.type===n.Meta?this.buffer[0]:void 0;this.buffer=r===void 0?[e]:[r,e],this.bufferHasFullSnapshot=!0,this.pendingBytes=t+(r===void 0?0:H(r)),this.heldBufferIncomplete=!1;return}if(!this.bufferHasFullSnapshot||t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held;return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held;return}}this.buffer.push(e),this.pendingBytes+=t,this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport({ignoreMinimumDuration:!0}):this.scheduleFlush()}async triggerFlush(){return this.mode===`buffer`&&(this.bufferHasFullSnapshot||(this.buffer=[],this.pendingBytes=0),this.mode=`full`,this.start()),this.flush()}async flush(e={}){return this.flushInternal(e)}async flushInternal(e){if(this.mode===`buffer`||this.held||this.buffer.length===0)return;if(e.ignoreMinimumDuration!==!0&&!this.minimumDurationReached()){this.scheduleMinimumDurationFlush();return}this.clearScheduledFlush();let t=this.buffer;this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0;let n=e.keepalive===!0?U(t):[t],r=this.seq;this.seq+=n.length;let i=this.sessionId;this.saveSeq(i,this.seq);let a=e.keepalive===!0?Promise.resolve():this.flushing??Promise.resolve(),o=e.keepalive===!0?this.deliverLifecycle(n,r,i):a.then(async()=>{for(let e=0;e<n.length;e++){let t=n[e];t!==void 0&&await this.deliverOrdinary(t,r+e,i)}}),s=this.flushing;this.flushing=e.keepalive===!0&&s!==void 0?Promise.all([s,o]).then(()=>void 0,()=>void 0):o.catch(()=>void 0),await o}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held){this.discard(),await this.flushing;return}if(!this.minimumDurationReached()){this.discard(),await this.flushing;return}await this.flush(e),await this.flushing}discard(){this.started=!1,this.clearScheduledFlush(),this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0}getMode(){return this.mode}isHeld(){return this.held}releaseHeld(e){this.held&&((this.heldBufferIncomplete||!this.bufferHasFullSnapshot)&&(this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,e()),this.held=!1,this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport({ignoreMinimumDuration:!0}):this.scheduleFlush())}flushAndReport(e={}){this.flushInternal(e).catch(e=>{B(this.config.onError,e)})}scheduleFlush(){let e=this.config.now(),t=Math.max(0,this.config.minSessionDurationMs-(e-this.startedAt)),n=Math.max(l(this.config.flushIntervalMs,e-this.lastUserActivityAt),t);this.scheduleFlushIn(e,n)}scheduleMinimumDurationFlush(){let e=this.config.now(),t=Math.max(0,this.config.minSessionDurationMs-(e-this.startedAt));this.scheduleFlushIn(e,t)}scheduleFlushIn(e,t){if(!this.started||this.mode!==`full`||this.held||this.buffer.length===0)return;let n=e+t;this.timer!==void 0&&this.nextFlushAt!==void 0&&this.nextFlushAt<=n||(this.clearScheduledFlush(),this.nextFlushAt=n,this.timer=setTimeout(()=>{this.timer=void 0,this.nextFlushAt=void 0,this.flushAndReport()},t))}clearScheduledFlush(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0),this.nextFlushAt=void 0}minimumDurationReached(){return this.config.now()-this.startedAt>=this.config.minSessionDurationMs}createEnvelope(e,t){let n=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{n=this.config.getDistinctId()??this.config.distinctId}catch(e){B(this.config.onError,e)}return{version:1,meta:ge(t,e,n,this.sessionAttributes),events:e}}async deliverOrdinary(e,n,r){let i=this.createEnvelope(e,n);try{let e=(0,t.strToU8)(JSON.stringify(i)),a=await this.compressOrdinary(e);await this.sendWithRetry({body:a,lifecycle:!1,requestKeepalive:!1,reservedBytes:0,seq:n,sessionId:r})}catch(e){B(this.config.onError,e)}}async deliverLifecycle(e,n,r){let i=[];for(let a=0;a<e.length;a++){let o=e[a];if(o===void 0){i.push(void 0);continue}let s=this.createEnvelope(o,n+a);try{i.push({body:this.compression.gzipSync((0,t.strToU8)(JSON.stringify(s))),lifecycle:!0,requestKeepalive:!1,reservedBytes:0,seq:n+a,sessionId:r})}catch(e){B(this.config.onError,e),i.push(void 0)}}let a=!0,o=Math.max(0,48e3-this.reservedKeepaliveBytes);for(let e of i){if(e===void 0){a=!1;continue}a&&e.body.byteLength<=o?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,o-=e.reservedBytes):a=!1}await Promise.all(i.map(async e=>{if(e!==void 0)try{await this.sendWithRetry(e)}catch(e){B(this.config.onError,e)}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await Se(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async sendWithRetry(e){let t=e.lifecycle?1:3;for(let n=1;n<=t;n++)try{await this.send(e);return}catch(e){let r=we(e,n);if(r===void 0||n>=t)throw e;await xe(r)}}async send(e){let t,n,r,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`replay upload timed out after 10000ms`))},1e4);try{let a=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,o=await this.getUploadHeaders(),s=this.config.fetchImpl(a,{method:`POST`,headers:o,body:e.body.slice(),keepalive:e.requestKeepalive,signal:i.signal});t=!0;let c=await s;if(n=!0,r=await Ce(c),!c.ok){let e=c.status===429?Te(c.headers.get(`retry-after`),Date.now()):void 0;throw new V(c.status,e)}}finally{clearTimeout(a),e.reservedBytes>0&&(t!==!0||n!==!0||r===!0)&&(this.reservedKeepaliveBytes=Math.max(0,this.reservedKeepaliveBytes-e.reservedBytes))}}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await be(this.config.token);return{...e,...t===void 0||t.length===0?{}:{Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}loadSeq(e){if(this.storage===null)return 0;try{let t=this.storage.getItem(z);if(t===null)return 0;let n=JSON.parse(t);if(typeof n!=`object`||!n)return 0;let r=n;return r.id===e&&typeof r.seq==`number`&&Number.isFinite(r.seq)?r.seq:0}catch{return 0}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(z,JSON.stringify({id:e,seq:t}))}catch{}}};function B(e,t){try{let n=e?.(t);ye(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function ye(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var V=class extends Error{retryAfter;status;constructor(e,t){super(`replay ingest failed: ${String(e)}`),this.status=e,this.retryAfter=t,this.name=`ReplayIngestError`}};async function be(e){return typeof e==`function`?e():e}async function xe(e){return new Promise(t=>{setTimeout(t,e)})}function H(e){try{return(0,t.strToU8)(JSON.stringify(e)).byteLength}catch{return 0}}function U(e){let t=[],n=[],r=0;for(let i of e){let e=H(i);n.length>0&&r+e>48e3&&(t.push(n),n=[],r=0),n.push(i),r+=e}return n.length>0&&t.push(n),t}async function Se(e,t){return new Promise((n,r)=>{let i=[];typeof window<`u`&&i.push(window),typeof document<`u`&&i.push(document);let a=()=>{for(let e of i)e.removeEventListener(`securitypolicyviolation`,s)},o=(e,t)=>{if(a(),e!==null){r(e);return}n(t)},s=e=>{let t=e;(t.effectiveDirective.includes(`worker-src`)||t.violatedDirective.includes(`worker-src`))&&o(Error(`replay compression worker blocked by Content Security Policy`))};for(let e of i)e.addEventListener(`securitypolicyviolation`,s);try{e.gzip(t,{level:6},(e,t)=>{o(e,t)})}catch(e){a(),r(e instanceof Error?e:Error(String(e)))}})}async function Ce(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function we(e,t){return e instanceof V?e.status===429?e.retryAfter?.kind===`too-long`?void 0:e.retryAfter?.kind===`delay`?e.retryAfter.milliseconds:500*t:e.status<500?void 0:500*t:500*t}function Te(e,t){if(e===null)return{kind:`fallback`};let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?W(e*1e3):{kind:`fallback`}}let r=ke(n,t);return r===void 0?{kind:`fallback`}:W(Math.max(0,r-t))}function W(e){return e>1e4?{kind:`too-long`}:{kind:`delay`,milliseconds:e}}const Ee=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],De=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Oe=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function ke(e,t){let n=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(n!==null)return G(n[1],n[2],n[3],n[4],n[5],n[6],n[7]);let r=/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(r!==null){let e=new Date(t).getUTCFullYear(),n=Number(r[4]),i=Math.floor(e/100)*100+n;return i>e+50&&(i-=100),G(r[1],r[2],r[3],String(i),r[5],r[6],r[7])}let i=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/u.exec(e);if(i!==null)return G(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function G(e,t,n,r,i,a,o){let s=Number(t),c=Ee.indexOf(n),l=Number(r),u=Number(i),d=Number(a),f=Number(o);if(c<0||s<1||s>31||u>23||d>59||f>59)return;let p=new Date(0);if(p.setUTCFullYear(l,c,s),p.setUTCHours(u,d,f,0),p.getUTCFullYear()!==l||p.getUTCMonth()!==c||p.getUTCDate()!==s||p.getUTCHours()!==u||p.getUTCMinutes()!==d||p.getUTCSeconds()!==f)return;let m=De.indexOf(e),h=Oe.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const Ae={mode:`off`,recording:!1,getSessionId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},K=`lf_session_replay_mode`,q=Symbol.for(`@pydantic/logfire-session-replay/controller`);function je(e){if(typeof window>`u`||typeof document>`u`)return Ae;let t=ze();try{let n=Ne(e),r=new he({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Z(n.onError,e),i}if(t!==void 0&&t.length>0)return i=t,t;let a=e?r.touch().id:r.getSession().id;return i=a,a},o=F(),s=a(!1),c,l=!1,u=Promise.resolve(),d,f=(e,t,r=!t)=>{let i=Pe(n,e,o);if(!(i===`off`||l||e!==s))try{c=Me({config:n,getSessionId:a,mode:i,onSessionChanged:p,samplingModeStorage:o,sessionId:e,holdUntilActivity:r})}catch(e){if(c=void 0,t)throw e;Z(n.onError,e)}},p=(e,t=!0)=>{if(l||e===s)return;s=e;let r=c;c=void 0;let i=r?.deactivate()??Promise.resolve();u=u.then(async()=>{await X(i,n.onError),!l&&s===e&&f(e,!1,t)})},m;try{f(s,!0),m=setInterval(()=>{p(a(!1))},1e3)}catch(e){throw c?.discard(),c=void 0,e}return{get mode(){try{return c?.transport.getMode()??`off`}catch(e){return Z(n.onError,e),`off`}},get recording(){try{return c!==void 0}catch(e){return Z(n.onError,e),!1}},getSessionId:()=>a(!1),flush:async()=>{try{await u,await c?.transport.flush()}catch(e){Z(n.onError,e)}},stop:async()=>(d??=(async()=>{l=!0,clearInterval(m);let e=c;c=void 0,await X(e?.deactivate()??Promise.resolve(),n.onError),await u,r.flushPendingStorage(),t()})(),d)}}catch(e){throw t(),e}}function Me(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:o,samplingModeStorage:s,sessionId:l}=e,u=new ve(t,l,i,void 0,void 0,fe(t.getSessionAttributes,e=>{Z(t.onError,e)}),{holdUntilActivity:r}),d=[],f=!0,p=()=>f,m;try{let e=se({beforeUserActivity:()=>{if(!(!f||!u.isHeld()))try{let t=n(!0);if(t!==l){o(t,!1);return}u.releaseHeld(()=>{e.takeFullSnapshot()})}catch(e){Z(t.onError,e)}},emit:e=>{if(f)try{let t=n(c(e));if(t!==l){o(t,!1);return}u.add(e)}catch(e){Z(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:0,redactUrlPatterns:t.redactUrlPatterns});d.push(()=>{e.stop()});let r=(n,r)=>{if(f)try{e.addCustomEvent(n,r)}catch(e){Z(t.onError,e)}},_=n=>{p()&&(u.releaseHeld(()=>{e.takeFullSnapshot()}),r(a.Error,n),p()&&u.getMode()===`buffer`&&(J(s,l,`full`),Y(u.triggerFlush(),t.onError)))},v=e=>{e instanceof ErrorEvent&&_($(e.message,e.filename,Le(e.error)))},y=e=>{let t=e.reason;_($(Be(t?.message??e.reason),void 0,typeof t?.stack==`string`?t.stack:void 0))},b=()=>{document.visibilityState===`hidden`&&Y(u.flush({keepalive:!0}),t.onError)},x=()=>{Y(u.flush({keepalive:!0}),t.onError)};return window.addEventListener(`error`,v,!0),d.push(()=>{window.removeEventListener(`error`,v,!0)}),window.addEventListener(`unhandledrejection`,y,!0),d.push(()=>{window.removeEventListener(`unhandledrejection`,y,!0)}),document.addEventListener(`visibilitychange`,b),d.push(()=>{document.removeEventListener(`visibilitychange`,b)}),window.addEventListener(`pagehide`,x),d.push(()=>{window.removeEventListener(`pagehide`,x)}),t.captureConsole&&d.push(h(r,{onError:t.onError})),t.captureNetwork&&d.push(ee(r,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&d.push(g(r,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),u.start(),{sessionId:l,transport:u,deactivate:async()=>(m??=(async()=>{f=!1,Q(d),await u.shutdown({keepalive:!1})})(),m),discard:()=>{f=!1,Q(d),u.discard()}}}catch(e){throw f=!1,Q(d),u.discard(),e}}function Ne(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=new URL(e.replayUrl,`https://logfire.invalid/`);if(t.search!==``||t.hash!==``)throw Error("logfire session replay: `replayUrl` must not contain a query or fragment");let n=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(n===void 0)throw Error("logfire session replay: no `fetch` available; pass `fetchImpl`");return{replayUrl:e.replayUrl,headers:e.headers,token:e.token,getSessionId:e.getSessionId,getSessionAttributes:e.getSessionAttributes,sessionSampleRate:e.sessionSampleRate??o.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??o.onErrorSampleRate,maskAllText:e.maskAllText??o.maskAllText,maskAllInputs:e.maskAllInputs??o.maskAllInputs,maskTextSelector:e.maskTextSelector??o.maskTextSelector,blockSelector:e.blockSelector??o.blockSelector,flushIntervalMs:e.flushIntervalMs??o.flushIntervalMs,maxBufferBytes:e.maxBufferBytes??o.maxBufferBytes,minSessionDurationMs:e.minSessionDurationMs??o.minSessionDurationMs,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??o.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??o.maxSessionDurationMs,distinctId:e.distinctId??o.distinctId,getDistinctId:e.getDistinctId,captureConsole:e.captureConsole??o.captureConsole,captureNetwork:e.captureNetwork??o.captureNetwork,captureNavigation:e.captureNavigation??o.captureNavigation,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...o.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function Pe(e,t,n){let r=Fe(n,t);if(r!==void 0)return r;let i=le({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return J(n,t,i),i}function Fe(e,t){if(e!==null)try{let n=e.getItem(K);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!Ie(i.mode)?void 0:i.mode}catch{return}}function J(e,t,n){if(e!==null)try{e.setItem(K,JSON.stringify({id:t,mode:n}))}catch{}}function Ie(e){return e===`full`||e===`buffer`||e===`off`}function Le(e){let t=typeof e==`object`&&e&&`stack`in e?e.stack:void 0;return typeof t==`string`?t:void 0}function Y(e,t){e.catch(e=>{Z(t,e)})}async function X(e,t){try{await e}catch(e){Z(t,e)}}function Z(e,t){try{let n=e?.(t);Re(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Re(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function ze(){let e=globalThis;if(e[q]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,q,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[q]===t&&Reflect.deleteProperty(e,q))}}function Q(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function $(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function Be(e){if(e==null)return`unhandledrejection`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);try{let t=JSON.stringify(e);return typeof t==`string`?t:Object.prototype.toString.call(e)}catch{return Object.prototype.toString.call(e)}}exports.CHUNK_ENVELOPE_VERSION=1,exports.CustomTag=a,exports.EventType=n,exports.IncrementalSource=r,exports.MouseInteractions=i,exports.startSessionReplay=je;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@rrweb/record"),t=require("fflate");const n={DomContentLoaded:0,Load:1,FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Custom:5,Plugin:6},r={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5,TouchMove:6,MediaInteraction:7,Drag:12,Selection:14},i={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},a={Error:`logfire.error`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},o={sessionSampleRate:1,onErrorSampleRate:1,maskAllText:!0,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,minSessionDurationMs:5e3,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:144e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,redactUrlPatterns:[/.+/u]},s=new Set([r.MouseMove,r.MouseInteraction,r.Scroll,r.ViewportResize,r.Input,r.TouchMove,r.MediaInteraction,r.Drag,r.Selection]);function c(e){return e.type!==n.IncrementalSnapshot||typeof e.data!=`object`||e.data===null||!(`source`in e.data)?!1:typeof e.data.source==`number`&&s.has(e.data.source)}function l(e,t){return t<3e4?e:t<3e5?Math.max(e,6e4):Math.max(e,3e5)}function u(e,t){return t.some(t=>new RegExp(t.source,t.flags).test(e))}function d(e,t,n){if(!u(e,t))return e;try{let t=new URL(e,n);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const f=[`log`,`info`,`warn`,`error`,`debug`],p=1024,m=()=>void 0;function h(e,t={}){let n=[],r=S(t.onError);try{for(let t of f)typeof console[t]==`function`&&n.push(C(console,t,(n,i)=>function(...o){return i()&&x(e,a.Console,{level:t,args:o.slice(0,10).map(E)},r),n.apply(this,o)}));return w(n)}catch(e){throw T(n),e}}function ee(e,t){let n=y(t),r={...n,onError:S(n.onError)},i=_(e,r);try{return w([i,v(e,r)])}catch(e){throw i(),e}}function g(e,t={redactUrlPatterns:[]}){let n=S(t.onError),r=r=>{let i=d(window.location.href,t.redactUrlPatterns??[],window.location.href);x(e,a.Navigation,{url:i,kind:r},n)},i=[];try{i.push(C(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(C(history,`replaceState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`replace`),i}));let e=!0,t=()=>{e&&r(`pop`)};return window.addEventListener(`popstate`,t),i.push(()=>{e=!1,window.removeEventListener(`popstate`,t)}),w(i)}catch(e){throw T(i),e}}function _(e,t){return typeof window.fetch==`function`?C(window,`fetch`,(n,r)=>{let i=async function(i,o){let s=n;if(!r())return s.call(this,i,o);let c=t.now(),l=ne(i,o),u=re(i);if(A(u,t.ignoreUrlPatterns))return s.call(this,i,o);let f=d(u,t.redactUrlPatterns,window.location.href),p=k(o?.body);try{let n=await s.call(this,i,o);return r()&&x(e,a.Network,O({method:l,url:f,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:p,resBytes:ie(n.headers)}),t.onError),n}catch(n){throw r()&&x(e,a.Network,O({method:l,url:f,status:0,durationMs:Math.max(0,t.now()-c),failed:!0,reqBytes:p}),t.onError),n}},o=Reflect.get(n,`__original`);return Object.defineProperty(i,"__original",{configurable:!0,value:typeof o==`function`?o:n,writable:!0}),i}):m}function v(e,t){let n=window.XMLHttpRequest.prototype,r=new WeakMap,i=[];try{return i.push(C(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return A(s,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:a.toUpperCase(),url:d(s,t.redactUrlPatterns,window.location.href),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(C(n,`send`,(n,i)=>function(...o){let[s]=o,c=i()?r.get(this):void 0;if(c===void 0)return n.apply(this,o);c.startedAt=t.now(),c.reqBytes=k(s);let l=()=>{c.failed=!0},u=()=>{c.emitted||(c.emitted=!0,this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),i()&&x(e,a.Network,O({method:c.method,url:c.url,status:this.status,durationMs:Math.max(0,t.now()-c.startedAt),failed:c.failed||this.status===0,reqBytes:c.reqBytes,resBytes:ae(this)}),t.onError))};this.addEventListener(`error`,l),this.addEventListener(`abort`,l),this.addEventListener(`timeout`,l),this.addEventListener(`loadend`,u,{once:!0});try{return n.apply(this,o)}catch(n){throw this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),this.removeEventListener(`loadend`,u),i()&&x(e,a.Network,O({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),w(i)}catch(e){throw T(i),e}}function y(e){return{...e,ignoreUrlPatterns:b(e.ignoreUrlPatterns),redactUrlPatterns:b(e.redactUrlPatterns)}}function b(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function x(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function S(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);te(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function te(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function C(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return m;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function w(e){let t=!1;return()=>{t||(t=!0,T(e))}}function T(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function E(e){if(e==null)return String(e);if(typeof e==`string`)return D(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return D(e.stack??`${e.name}: ${e.message}`);try{return D(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function D(e){if(e.length<=p)return e;let t=e.charCodeAt(p-1),n=t>=55296&&t<=56319?p-1:p;return`${e.slice(0,n)}...(+${String(e.length-n)} chars)`}function ne(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function re(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function ie(e){let t=e.get(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}function ae(e){try{let t=e.getResponseHeader(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}catch{return}}function O(e){return{method:e.method,url:e.url,status:e.status,durationMs:e.durationMs,...e.failed===void 0?{}:{failed:e.failed},...e.reqBytes===void 0?{}:{reqBytes:e.reqBytes},...e.resBytes===void 0?{}:{resBytes:e.resBytes}}}function k(e){if(e==null)return 0;if(typeof e==`string`)return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Blob)return e.size}function A(e,t){return u(e,t)}const oe=new Set([`action`,`formaction`,`href`,`src`]);function se(t){let n=()=>{t.beforeUserActivity?.()},r={emit:e=>{t.emit(ce(e,t.redactUrlPatterns))},maskAllInputs:t.maskAllInputs,recordCanvas:!1,collectFonts:!1,inlineImages:!1,recordCrossOriginIframes:!1,slimDOMOptions:`all`,hooks:{input:n,mediaInteaction:n,mouseInteraction:n,mousemove:n,scroll:n,selection:n,viewportResize:n},sampling:{mousemove:100,mouseInteraction:!0,scroll:250,media:800,input:`last`}};t.maskAllText?r.maskTextSelector=`*`:t.maskTextSelector!==void 0&&t.maskTextSelector.length>0&&(r.maskTextSelector=t.maskTextSelector),t.blockSelector!==void 0&&t.blockSelector.length>0&&(r.blockSelector=t.blockSelector),t.checkoutEveryNms!==void 0&&t.checkoutEveryNms>0&&(r.checkoutEveryNms=t.checkoutEveryNms);let i=(0,e.record)(r);if(i===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{i()},addCustomEvent:(t,n)=>{e.record.addCustomEvent(t,n)},takeFullSnapshot:()=>{e.record.takeFullSnapshot(!0)}}}function ce(e,t){if(typeof e.data!=`object`||e.data===null)return e;let i=e.data;if(e.type===n.Meta){if(typeof i.href!=`string`)return e;let n=d(i.href,t,window.location.href);return n===i.href?e:{...e,data:{...i,href:n}}}if(e.type!==n.FullSnapshot&&(e.type!==n.IncrementalSnapshot||i.source!==r.Mutation))return e;let a=j(i,t);return a===i?e:{...e,data:a}}function j(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=j(i,t);e!==i&&(n=!0),r.push(e)}return n?r:e}if(typeof e!=`object`||!e)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n=e===`attributes`&&!Array.isArray(a)?M(a,t):j(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function M(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){if(!oe.has(e.toLowerCase())||typeof a!=`string`){i[e]=a;continue}let n=d(a,t,window.location.href);n!==a&&(r=!0),i[e]=n}return r?i:e}function N(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function le(e){let t=e.random??Math.random;return t()<N(e.sessionSampleRate)?`full`:t()<N(e.onErrorSampleRate)?`buffer`:`off`}const ue=/^[a-z][a-z0-9_]{0,63}$/u;function de(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function fe(e,t){if(e===void 0)return Object.freeze({});let n;try{n=e()}catch(e){return t(e),Object.freeze({})}if(typeof n!=`object`||!n||Array.isArray(n))return Object.freeze({});let r;try{r=Object.getPrototypeOf(n)}catch(e){return t(e),Object.freeze({})}if(r!==Object.prototype&&r!==null)return Object.freeze({});let i;try{i=Object.keys(n)}catch(e){return t(e),Object.freeze({})}let a={},o=0;for(let e of i){if(!ue.test(e))continue;let r;try{r=Reflect.get(n,e)}catch(e){t(e);continue}if((typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r)||typeof r==`string`&&de(r,200))&&(Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:r,writable:!0}),o+=1,o===20))break}return Object.freeze(a)}function pe(e=Date.now){let t=e(),n=new Uint8Array(new ArrayBuffer(16));me(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/2**8)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function me(e){let t=globalThis.crypto;if(typeof t?.getRandomValues==`function`){t.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const P=`lf_session_replay`;var he=class{idleTimeoutMs;maxDurationMs;now;storage;memorySession;pendingSession;persistenceTimer;constructor(e){this.idleTimeoutMs=e.idleTimeoutMs,this.maxDurationMs=e.maxDurationMs,this.now=e.now??Date.now,this.storage=e.storage===void 0?F():e.storage}getSession(){let e=this.now();if(this.memorySession!==void 0&&!this.isExpired(this.memorySession,e))return this.memorySession;let t=this.read();return t!==void 0&&!this.isExpired(t,e)?t:this.createSession(e)}touch(){let e=this.now(),t={...this.getSession(),lastActivityAt:e};return this.memorySession=t,this.scheduleWrite(t),t}reset(){return this.createSession(this.now())}flushPendingStorage(){this.persistenceTimer!==void 0&&(clearTimeout(this.persistenceTimer),this.persistenceTimer=void 0);let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)}isExpired(e,t){return t-e.lastActivityAt>this.idleTimeoutMs||t-e.startedAt>this.maxDurationMs}createSession(e){let t={id:pe(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(P);if(e!==null){let t=JSON.parse(e);if(I(t))return this.memorySession=t,t}}catch{return this.memorySession}return this.memorySession}write(e){if(this.memorySession=e,this.storage!==null)try{this.storage.setItem(P,JSON.stringify(e))}catch{}}scheduleWrite(e){this.pendingSession=e,this.persistenceTimer===void 0&&(this.persistenceTimer=setTimeout(()=>{this.persistenceTimer=void 0;let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)},1e3))}writeNow(e){this.memorySession=e,this.write(e)}};function F(){try{return globalThis.sessionStorage??null}catch{return null}}function I(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}function L(e){return typeof e==`object`&&e?e:void 0}function R(e){return typeof e==`string`&&e.length>0?e:void 0}function ge(e,t,o,s={}){let c=1/0,l=0,u=0,d=0,f=0,p=!1,m=new Set;for(let e of t){e.timestamp<c&&(c=e.timestamp),e.timestamp>l&&(l=e.timestamp);let t=L(e.data);if(e.type===n.FullSnapshot)p=!0;else if(e.type===n.Meta){let e=R(t?.href);e!==void 0&&m.add(e)}else if(e.type===n.IncrementalSnapshot&&t!==void 0){let e=t.source;if(e===r.MouseInteraction){let e=t.type;(e===i.Click||e===i.DblClick)&&u++}else e===r.Input&&d++}else if(e.type===n.Custom&&t!==void 0){let e=R(t.tag),n=L(t.payload);if(e===a.Error)f++;else if(e===a.Console)n?.level===`error`&&f++;else if(e===a.Navigation){let e=R(n?.url);e!==void 0&&m.add(e)}}}return{seq:e,firstTimestamp:c===1/0?0:c,lastTimestamp:l,eventCount:t.length,clickCount:u,keypressCount:d,errorCount:f,hasFullSnapshot:p,urls:[...m],...o!==void 0&&o.length>0?{distinctId:o}:{},...Object.keys(s).length===0?{}:{sessionAttributes:{...s}}}}const z=`lf_session_replay_seq`,_e={gzip:t.gzip,gzipSync:t.gzipSync};var ve=class{buffer=[];bufferHasFullSnapshot=!1;pendingBytes=0;seq=0;timer;nextFlushAt;lastUserActivityAt;startedAt;started=!1;held;heldBufferIncomplete=!1;minimumBufferIncomplete=!1;minimumDurationSatisfied=!1;firstObservedTimestamp;lastObservedTimestamp;refreshingMinimumSnapshot=!1;mode;flushing;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;takeFullSnapshot;constructor(e,t,n,r=F(),i=_e,a={},o={}){this.config=e,this.sessionId=t,this.sessionAttributes=Object.freeze({...a}),this.mode=n,this.storage=r,this.compression=i,this.held=o.holdUntilActivity===!0&&n===`full`,this.takeFullSnapshot=o.takeFullSnapshot,this.minimumDurationSatisfied=e.minSessionDurationMs===0,this.seq=this.loadSeq(t),this.startedAt=this.config.now(),this.lastUserActivityAt=this.startedAt}start(){this.started||this.mode!==`full`||(this.started=!0,this.scheduleFlush())}add(e){this.minimumDurationSatisfied||(this.firstObservedTimestamp??=e.timestamp,this.lastObservedTimestamp=Math.max(this.lastObservedTimestamp??e.timestamp,e.timestamp)),c(e)&&(this.lastUserActivityAt=this.config.now());let t=H(e);if(this.refreshingMinimumSnapshot){this.buffer.push(e),this.pendingBytes+=t;return}let r=!this.minimumDurationSatisfied;if(this.mode===`buffer`||this.held||r){if(e.type===n.Meta){this.buffer=[e],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=t,r&&(this.mode===`full`&&(this.firstObservedTimestamp=e.timestamp),this.finishMinimumBufferingEvent());return}if(e.type===n.FullSnapshot){let i=!this.bufferHasFullSnapshot&&this.buffer.length===1&&this.buffer[0]?.type===n.Meta?this.buffer[0]:void 0;this.buffer=i===void 0?[e]:[i,e],this.bufferHasFullSnapshot=!0,this.pendingBytes=t+(i===void 0?0:H(i)),this.heldBufferIncomplete=!1,this.minimumBufferIncomplete=!1,r&&(this.mode===`full`&&(this.firstObservedTimestamp=i?.timestamp??e.timestamp),this.finishMinimumBufferingEvent());return}if(!this.bufferHasFullSnapshot||t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.minimumBufferIncomplete||=r,r&&this.finishMinimumBufferingEvent();return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.minimumBufferIncomplete||=r,r&&this.finishMinimumBufferingEvent();return}}if(this.buffer.push(e),this.pendingBytes+=t,r&&this.minimumDurationReached()){this.flushAndReport();return}this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()}async triggerFlush(){return this.mode===`buffer`&&(this.bufferHasFullSnapshot||(this.buffer=[],this.pendingBytes=0),this.mode=`full`,this.start()),this.flush()}async flush(e={}){return this.flushInternal(e)}async flushInternal(e={}){if(this.mode===`buffer`||this.held||this.buffer.length===0||!this.minimumDurationReached()||(this.clearScheduledFlush(),this.minimumBufferIncomplete&&!this.refreshMinimumBuffer()))return;this.minimumDurationSatisfied=!0;let t=this.buffer;this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0;let n=e.keepalive===!0?U(t):[t],r=this.seq;this.seq+=n.length;let i=this.sessionId;this.saveSeq(i,this.seq);let a=e.keepalive===!0?Promise.resolve():this.flushing??Promise.resolve(),o=e.keepalive===!0?this.deliverLifecycle(n,r,i):a.then(async()=>{for(let e=0;e<n.length;e++){let t=n[e];t!==void 0&&await this.deliverOrdinary(t,r+e,i)}}),s=this.flushing;this.flushing=e.keepalive===!0&&s!==void 0?Promise.all([s,o]).then(()=>void 0,()=>void 0):o.catch(()=>void 0),await o}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held){this.discard(),await this.flushing;return}if(!this.minimumDurationReached()){this.discard(),await this.flushing;return}await this.flush(e),await this.flushing}discard(){this.started=!1,this.clearScheduledFlush(),this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0}getMode(){return this.mode}isHeld(){return this.held}releaseHeld(e){this.held&&((this.heldBufferIncomplete||!this.bufferHasFullSnapshot)&&(this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,e()),this.held=!1,this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush())}flushAndReport(){this.flushInternal().catch(e=>{B(this.config.onError,e)})}scheduleFlush(){let e=this.config.now(),t=Math.max(0,this.config.minSessionDurationMs-(e-this.startedAt)),n=Math.max(l(this.config.flushIntervalMs,e-this.lastUserActivityAt),t);this.scheduleFlushIn(e,n)}scheduleFlushIn(e,t){if(!this.started||this.mode!==`full`||this.held||this.buffer.length===0)return;let n=e+t;this.timer!==void 0&&this.nextFlushAt!==void 0&&this.nextFlushAt<=n||(this.clearScheduledFlush(),this.nextFlushAt=n,this.timer=setTimeout(()=>{this.timer=void 0,this.nextFlushAt=void 0,this.flushAndReport()},t))}clearScheduledFlush(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0),this.nextFlushAt=void 0}minimumDurationReached(){return this.minimumDurationSatisfied||this.config.minSessionDurationMs===0?!0:this.firstObservedTimestamp===void 0||this.lastObservedTimestamp===void 0?!1:this.lastObservedTimestamp-this.firstObservedTimestamp>=this.config.minSessionDurationMs}finishMinimumBufferingEvent(){this.minimumDurationReached()?this.flushAndReport():this.scheduleFlush()}refreshMinimumBuffer(){let e=this.buffer.length,t=this.pendingBytes;if(this.takeFullSnapshot!==void 0){this.refreshingMinimumSnapshot=!0;try{this.takeFullSnapshot()}catch(e){B(this.config.onError,e)}finally{this.refreshingMinimumSnapshot=!1}}return this.buffer.slice(e).some(e=>e.type===n.FullSnapshot)?(this.minimumBufferIncomplete=!1,!0):(this.buffer.length=e,this.pendingBytes=t,!1)}createEnvelope(e,t){let n=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{n=this.config.getDistinctId()??this.config.distinctId}catch(e){B(this.config.onError,e)}return{version:1,meta:ge(t,e,n,this.sessionAttributes),events:e}}async deliverOrdinary(e,n,r){let i=this.createEnvelope(e,n);try{let e=(0,t.strToU8)(JSON.stringify(i)),a=await this.compressOrdinary(e);await this.sendWithRetry({body:a,lifecycle:!1,requestKeepalive:!1,reservedBytes:0,seq:n,sessionId:r})}catch(e){B(this.config.onError,e)}}async deliverLifecycle(e,n,r){let i=[];for(let a=0;a<e.length;a++){let o=e[a];if(o===void 0){i.push(void 0);continue}let s=this.createEnvelope(o,n+a);try{i.push({body:this.compression.gzipSync((0,t.strToU8)(JSON.stringify(s))),lifecycle:!0,requestKeepalive:!1,reservedBytes:0,seq:n+a,sessionId:r})}catch(e){B(this.config.onError,e),i.push(void 0)}}let a=!0,o=Math.max(0,48e3-this.reservedKeepaliveBytes);for(let e of i){if(e===void 0){a=!1;continue}a&&e.body.byteLength<=o?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,o-=e.reservedBytes):a=!1}await Promise.all(i.map(async e=>{if(e!==void 0)try{await this.sendWithRetry(e)}catch(e){B(this.config.onError,e)}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await Se(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async sendWithRetry(e){let t=e.lifecycle?1:3;for(let n=1;n<=t;n++)try{await this.send(e);return}catch(e){let r=we(e,n);if(r===void 0||n>=t)throw e;await xe(r)}}async send(e){let t,n,r,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`replay upload timed out after 10000ms`))},1e4);try{let a=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,o=await this.getUploadHeaders(),s=this.config.fetchImpl(a,{method:`POST`,headers:o,body:e.body.slice(),keepalive:e.requestKeepalive,signal:i.signal});t=!0;let c=await s;if(n=!0,r=await Ce(c),!c.ok){let e=c.status===429?Te(c.headers.get(`retry-after`),Date.now()):void 0;throw new V(c.status,e)}}finally{clearTimeout(a),e.reservedBytes>0&&(t!==!0||n!==!0||r===!0)&&(this.reservedKeepaliveBytes=Math.max(0,this.reservedKeepaliveBytes-e.reservedBytes))}}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await be(this.config.token);return{...t===void 0||t.length===0?e:{...Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`authorization`)),Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}loadSeq(e){if(this.storage===null)return 0;try{let t=this.storage.getItem(z);if(t===null)return 0;let n=JSON.parse(t);if(typeof n!=`object`||!n)return 0;let r=n;return r.id===e&&typeof r.seq==`number`&&Number.isFinite(r.seq)?r.seq:0}catch{return 0}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(z,JSON.stringify({id:e,seq:t}))}catch{}}};function B(e,t){try{let n=e?.(t);ye(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function ye(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var V=class extends Error{retryAfter;status;constructor(e,t){super(`replay ingest failed: ${String(e)}`),this.status=e,this.retryAfter=t,this.name=`ReplayIngestError`}};async function be(e){return typeof e==`function`?e():e}async function xe(e){return new Promise(t=>{setTimeout(t,e)})}function H(e){try{return(0,t.strToU8)(JSON.stringify(e)).byteLength}catch{return 0}}function U(e){let t=[],n=[],r=0;for(let i of e){let e=H(i);n.length>0&&r+e>48e3&&(t.push(n),n=[],r=0),n.push(i),r+=e}return n.length>0&&t.push(n),t}async function Se(e,t){return new Promise((n,r)=>{let i=[];typeof window<`u`&&i.push(window),typeof document<`u`&&i.push(document);let a=()=>{for(let e of i)e.removeEventListener(`securitypolicyviolation`,s)},o=(e,t)=>{if(a(),e!==null){r(e);return}n(t)},s=e=>{let t=e;(t.effectiveDirective.includes(`worker-src`)||t.violatedDirective.includes(`worker-src`))&&o(Error(`replay compression worker blocked by Content Security Policy`))};for(let e of i)e.addEventListener(`securitypolicyviolation`,s);try{e.gzip(t,{level:6},(e,t)=>{o(e,t)})}catch(e){a(),r(e instanceof Error?e:Error(String(e)))}})}async function Ce(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function we(e,t){return e instanceof V?e.status===429?e.retryAfter?.kind===`too-long`?void 0:e.retryAfter?.kind===`delay`?e.retryAfter.milliseconds:500*t:e.status<500?void 0:500*t:500*t}function Te(e,t){if(e===null)return{kind:`fallback`};let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?W(e*1e3):{kind:`fallback`}}let r=ke(n,t);return r===void 0?{kind:`fallback`}:W(Math.max(0,r-t))}function W(e){return e>1e4?{kind:`too-long`}:{kind:`delay`,milliseconds:e}}const Ee=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],De=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Oe=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function ke(e,t){let n=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(n!==null)return G(n[1],n[2],n[3],n[4],n[5],n[6],n[7]);let r=/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(r!==null){let e=new Date(t).getUTCFullYear(),n=Number(r[4]),i=Math.floor(e/100)*100+n;return i>e+50&&(i-=100),G(r[1],r[2],r[3],String(i),r[5],r[6],r[7])}let i=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/u.exec(e);if(i!==null)return G(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function G(e,t,n,r,i,a,o){let s=Number(t),c=Ee.indexOf(n),l=Number(r),u=Number(i),d=Number(a),f=Number(o);if(c<0||s<1||s>31||u>23||d>59||f>59)return;let p=new Date(0);if(p.setUTCFullYear(l,c,s),p.setUTCHours(u,d,f,0),p.getUTCFullYear()!==l||p.getUTCMonth()!==c||p.getUTCDate()!==s||p.getUTCHours()!==u||p.getUTCMinutes()!==d||p.getUTCSeconds()!==f)return;let m=De.indexOf(e),h=Oe.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const Ae={mode:`off`,recording:!1,getSessionId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},K=`lf_session_replay_mode`,q=Symbol.for(`@pydantic/logfire-session-replay/controller`);function je(e){if(typeof window>`u`||typeof document>`u`)return Ae;let t=ze();try{let n=Ne(e),r=new he({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Z(n.onError,e),i}if(t!==void 0&&t.length>0)return i=t,t;let a=e?r.touch().id:r.getSession().id;return i=a,a},o=F(),s=a(!1),c,l=!1,u=Promise.resolve(),d,f=(e,t,r=!t)=>{let i=Pe(n,e,o);if(!(i===`off`||l||e!==s))try{c=Me({config:n,getSessionId:a,mode:i,onSessionChanged:p,samplingModeStorage:o,sessionId:e,holdUntilActivity:r})}catch(e){if(c=void 0,t)throw e;Z(n.onError,e)}},p=(e,t=!0)=>{if(l||e===s)return;s=e;let r=c;c=void 0;let i=r?.deactivate()??Promise.resolve();u=u.then(async()=>{await X(i,n.onError),!l&&s===e&&f(e,!1,t)})},m;try{f(s,!0),m=setInterval(()=>{p(a(!1))},1e3)}catch(e){throw c?.discard(),c=void 0,e}return{get mode(){try{return c?.transport.getMode()??`off`}catch(e){return Z(n.onError,e),`off`}},get recording(){try{return c!==void 0}catch(e){return Z(n.onError,e),!1}},getSessionId:()=>a(!1),flush:async()=>{try{await u,await c?.transport.flush()}catch(e){Z(n.onError,e)}},stop:async()=>(d??=(async()=>{l=!0,clearInterval(m);let e=c;c=void 0,await X(e?.deactivate()??Promise.resolve(),n.onError),await u,r.flushPendingStorage(),t()})(),d)}}catch(e){throw t(),e}}function Me(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:o,samplingModeStorage:s,sessionId:l}=e,u=fe(t.getSessionAttributes,e=>{Z(t.onError,e)}),d,f=new ve(t,l,i,void 0,void 0,u,{holdUntilActivity:r,takeFullSnapshot:()=>{d.takeFullSnapshot()}}),p=[],m=!0,_=()=>m,v;try{d=se({beforeUserActivity:()=>{if(!(!m||!f.isHeld()))try{let e=n(!0);if(e!==l){o(e,!1);return}f.releaseHeld(()=>{d.takeFullSnapshot()})}catch(e){Z(t.onError,e)}},emit:e=>{if(m)try{let t=n(c(e));if(t!==l){o(t,!1);return}f.add(e)}catch(e){Z(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:0,redactUrlPatterns:t.redactUrlPatterns}),p.push(()=>{d.stop()});let e=(e,n)=>{if(m)try{d.addCustomEvent(e,n)}catch(e){Z(t.onError,e)}},r=n=>{_()&&(f.releaseHeld(()=>{d.takeFullSnapshot()}),e(a.Error,n),_()&&f.getMode()===`buffer`&&(J(s,l,`full`),Y(f.triggerFlush(),t.onError)))},u=e=>{e instanceof ErrorEvent&&r($(e.message,e.filename,Le(e.error)))},y=e=>{let t=e.reason;r($(Be(t?.message??e.reason),void 0,typeof t?.stack==`string`?t.stack:void 0))},b=()=>{document.visibilityState===`hidden`&&Y(f.flush({keepalive:!0}),t.onError)},x=()=>{Y(f.flush({keepalive:!0}),t.onError)};return window.addEventListener(`error`,u,!0),p.push(()=>{window.removeEventListener(`error`,u,!0)}),window.addEventListener(`unhandledrejection`,y,!0),p.push(()=>{window.removeEventListener(`unhandledrejection`,y,!0)}),document.addEventListener(`visibilitychange`,b),p.push(()=>{document.removeEventListener(`visibilitychange`,b)}),window.addEventListener(`pagehide`,x),p.push(()=>{window.removeEventListener(`pagehide`,x)}),t.captureConsole&&p.push(h(e,{onError:t.onError})),t.captureNetwork&&p.push(ee(e,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&p.push(g(e,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),f.start(),{sessionId:l,transport:f,deactivate:async()=>(v??=(async()=>{let e=f.flush({keepalive:!1});m=!1,Q(p),await e,await f.shutdown({keepalive:!1})})(),v),discard:()=>{m=!1,Q(p),f.discard()}}}catch(e){throw m=!1,Q(p),f.discard(),e}}function Ne(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=new URL(e.replayUrl,`https://logfire.invalid/`);if(t.search!==``||t.hash!==``)throw Error("logfire session replay: `replayUrl` must not contain a query or fragment");let n=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(n===void 0)throw Error("logfire session replay: no `fetch` available; pass `fetchImpl`");return{replayUrl:e.replayUrl,headers:e.headers,token:e.token,getSessionId:e.getSessionId,getSessionAttributes:e.getSessionAttributes,sessionSampleRate:e.sessionSampleRate??o.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??o.onErrorSampleRate,maskAllText:e.maskAllText??o.maskAllText,maskAllInputs:e.maskAllInputs??o.maskAllInputs,maskTextSelector:e.maskTextSelector??o.maskTextSelector,blockSelector:e.blockSelector??o.blockSelector,flushIntervalMs:e.flushIntervalMs??o.flushIntervalMs,maxBufferBytes:e.maxBufferBytes??o.maxBufferBytes,minSessionDurationMs:e.minSessionDurationMs??o.minSessionDurationMs,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??o.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??o.maxSessionDurationMs,distinctId:e.distinctId??o.distinctId,getDistinctId:e.getDistinctId,captureConsole:e.captureConsole??o.captureConsole,captureNetwork:e.captureNetwork??o.captureNetwork,captureNavigation:e.captureNavigation??o.captureNavigation,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...o.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function Pe(e,t,n){let r=Fe(n,t);if(r!==void 0)return r;let i=le({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return J(n,t,i),i}function Fe(e,t){if(e!==null)try{let n=e.getItem(K);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!Ie(i.mode)?void 0:i.mode}catch{return}}function J(e,t,n){if(e!==null)try{e.setItem(K,JSON.stringify({id:t,mode:n}))}catch{}}function Ie(e){return e===`full`||e===`buffer`||e===`off`}function Le(e){let t=typeof e==`object`&&e&&`stack`in e?e.stack:void 0;return typeof t==`string`?t:void 0}function Y(e,t){e.catch(e=>{Z(t,e)})}async function X(e,t){try{await e}catch(e){Z(t,e)}}function Z(e,t){try{let n=e?.(t);Re(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Re(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function ze(){let e=globalThis;if(e[q]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,q,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[q]===t&&Reflect.deleteProperty(e,q))}}function Q(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function $(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function Be(e){if(e==null)return`unhandledrejection`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);try{let t=JSON.stringify(e);return typeof t==`string`?t:Object.prototype.toString.call(e)}catch{return Object.prototype.toString.call(e)}}exports.CHUNK_ENVELOPE_VERSION=1,exports.CustomTag=a,exports.EventType=n,exports.IncrementalSource=r,exports.MouseInteractions=i,exports.startSessionReplay=je;
package/dist/index.d.cts CHANGED
@@ -89,20 +89,21 @@ interface ChunkEnvelope {
89
89
  */
90
90
  interface SessionReplayConfig {
91
91
  /**
92
- * Replay upload endpoint. For normal browser applications this should be a
93
- * backend proxy endpoint. With the direct-token escape hatch, this may point
94
- * at Logfire ingest. The SDK posts to `${replayUrl}/${sessionId}?seq=${seq}`.
92
+ * Browser-safe replay upload endpoint, either direct Logfire ingest with a
93
+ * restricted frontend application token or an application-owned proxy. The
94
+ * SDK posts to `${replayUrl}/${sessionId}?seq=${seq}`.
95
95
  */
96
96
  replayUrl: string;
97
97
  /**
98
- * Headers added to each replay upload. Use this for CSRF/session auth to the
99
- * caller's backend proxy.
98
+ * Headers added to each replay upload. Direct Logfire ingest uses the same
99
+ * restricted frontend application headers as traces and metrics.
100
100
  */
101
101
  headers?: () => MaybePromise<Record<string, string>>;
102
102
  /**
103
- * Advanced escape hatch for direct Logfire ingest. Prefer `headers` with a
104
- * backend proxy for normal browser applications. When provided, the SDK adds
105
- * `Authorization: Bearer ${token}` to replay uploads.
103
+ * Convenience token source. A non-empty value removes any case-insensitive
104
+ * Authorization entry returned by `headers`, then sets
105
+ * `Authorization: Bearer ${token}`. Only restricted frontend application
106
+ * tokens are safe in browsers.
106
107
  */
107
108
  token?: string | (() => MaybePromise<string>);
108
109
  /**
package/dist/index.d.ts CHANGED
@@ -89,20 +89,21 @@ interface ChunkEnvelope {
89
89
  */
90
90
  interface SessionReplayConfig {
91
91
  /**
92
- * Replay upload endpoint. For normal browser applications this should be a
93
- * backend proxy endpoint. With the direct-token escape hatch, this may point
94
- * at Logfire ingest. The SDK posts to `${replayUrl}/${sessionId}?seq=${seq}`.
92
+ * Browser-safe replay upload endpoint, either direct Logfire ingest with a
93
+ * restricted frontend application token or an application-owned proxy. The
94
+ * SDK posts to `${replayUrl}/${sessionId}?seq=${seq}`.
95
95
  */
96
96
  replayUrl: string;
97
97
  /**
98
- * Headers added to each replay upload. Use this for CSRF/session auth to the
99
- * caller's backend proxy.
98
+ * Headers added to each replay upload. Direct Logfire ingest uses the same
99
+ * restricted frontend application headers as traces and metrics.
100
100
  */
101
101
  headers?: () => MaybePromise<Record<string, string>>;
102
102
  /**
103
- * Advanced escape hatch for direct Logfire ingest. Prefer `headers` with a
104
- * backend proxy for normal browser applications. When provided, the SDK adds
105
- * `Authorization: Bearer ${token}` to replay uploads.
103
+ * Convenience token source. A non-empty value removes any case-insensitive
104
+ * Authorization entry returned by `headers`, then sets
105
+ * `Authorization: Bearer ${token}`. Only restricted frontend application
106
+ * tokens are safe in browsers.
106
107
  */
107
108
  token?: string | (() => MaybePromise<string>);
108
109
  /**
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{record as e}from"@rrweb/record";import{gzip as t,gzipSync as n,strToU8 as r}from"fflate";const i={DomContentLoaded:0,Load:1,FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Custom:5,Plugin:6},a={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5,TouchMove:6,MediaInteraction:7,Drag:12,Selection:14},o={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},s={Error:`logfire.error`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},c=1,l={sessionSampleRate:1,onErrorSampleRate:1,maskAllText:!0,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,minSessionDurationMs:5e3,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:144e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,redactUrlPatterns:[/.+/u]},u=new Set([a.MouseMove,a.MouseInteraction,a.Scroll,a.ViewportResize,a.Input,a.TouchMove,a.MediaInteraction,a.Drag,a.Selection]);function d(e){return e.type!==i.IncrementalSnapshot||typeof e.data!=`object`||e.data===null||!(`source`in e.data)?!1:typeof e.data.source==`number`&&u.has(e.data.source)}function f(e,t){return t<3e4?e:t<3e5?Math.max(e,6e4):Math.max(e,3e5)}function p(e,t){return t.some(t=>new RegExp(t.source,t.flags).test(e))}function m(e,t,n){if(!p(e,t))return e;try{let t=new URL(e,n);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const h=[`log`,`info`,`warn`,`error`,`debug`],g=1024,_=()=>void 0;function ee(e,t={}){let n=[],r=C(t.onError);try{for(let t of h)typeof console[t]==`function`&&n.push(w(console,t,(n,i)=>function(...a){return i()&&S(e,s.Console,{level:t,args:a.slice(0,10).map(ie)},r),n.apply(this,a)}));return T(n)}catch(e){throw E(n),e}}function v(e,t){let n=ne(t),r={...n,onError:C(n.onError)},i=y(e,r);try{return T([i,b(e,r)])}catch(e){throw i(),e}}function te(e,t={redactUrlPatterns:[]}){let n=C(t.onError),r=r=>{let i=m(window.location.href,t.redactUrlPatterns??[],window.location.href);S(e,s.Navigation,{url:i,kind:r},n)},i=[];try{i.push(w(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(w(history,`replaceState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`replace`),i}));let e=!0,t=()=>{e&&r(`pop`)};return window.addEventListener(`popstate`,t),i.push(()=>{e=!1,window.removeEventListener(`popstate`,t)}),T(i)}catch(e){throw E(i),e}}function y(e,t){return typeof window.fetch==`function`?w(window,`fetch`,(n,r)=>{let i=async function(i,a){let o=n;if(!r())return o.call(this,i,a);let c=t.now(),l=O(i,a),u=ae(i);if(j(u,t.ignoreUrlPatterns))return o.call(this,i,a);let d=m(u,t.redactUrlPatterns,window.location.href),f=A(a?.body);try{let n=await o.call(this,i,a);return r()&&S(e,s.Network,k({method:l,url:d,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:f,resBytes:oe(n.headers)}),t.onError),n}catch(n){throw r()&&S(e,s.Network,k({method:l,url:d,status:0,durationMs:Math.max(0,t.now()-c),failed:!0,reqBytes:f}),t.onError),n}},a=Reflect.get(n,`__original`);return Object.defineProperty(i,"__original",{configurable:!0,value:typeof a==`function`?a:n,writable:!0}),i}):_}function b(e,t){let n=window.XMLHttpRequest.prototype,r=new WeakMap,i=[];try{return i.push(w(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return j(s,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:a.toUpperCase(),url:m(s,t.redactUrlPatterns,window.location.href),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(w(n,`send`,(n,i)=>function(...a){let[o]=a,c=i()?r.get(this):void 0;if(c===void 0)return n.apply(this,a);c.startedAt=t.now(),c.reqBytes=A(o);let l=()=>{c.failed=!0},u=()=>{c.emitted||(c.emitted=!0,this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),i()&&S(e,s.Network,k({method:c.method,url:c.url,status:this.status,durationMs:Math.max(0,t.now()-c.startedAt),failed:c.failed||this.status===0,reqBytes:c.reqBytes,resBytes:se(this)}),t.onError))};this.addEventListener(`error`,l),this.addEventListener(`abort`,l),this.addEventListener(`timeout`,l),this.addEventListener(`loadend`,u,{once:!0});try{return n.apply(this,a)}catch(n){throw this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),this.removeEventListener(`loadend`,u),i()&&S(e,s.Network,k({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),T(i)}catch(e){throw E(i),e}}function ne(e){return{...e,ignoreUrlPatterns:x(e.ignoreUrlPatterns),redactUrlPatterns:x(e.redactUrlPatterns)}}function x(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function S(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function C(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);re(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function re(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function w(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return _;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function T(e){let t=!1;return()=>{t||(t=!0,E(e))}}function E(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function ie(e){if(e==null)return String(e);if(typeof e==`string`)return D(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return D(e.stack??`${e.name}: ${e.message}`);try{return D(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function D(e){if(e.length<=g)return e;let t=e.charCodeAt(g-1),n=t>=55296&&t<=56319?g-1:g;return`${e.slice(0,n)}...(+${String(e.length-n)} chars)`}function O(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function ae(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function oe(e){let t=e.get(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}function se(e){try{let t=e.getResponseHeader(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}catch{return}}function k(e){return{method:e.method,url:e.url,status:e.status,durationMs:e.durationMs,...e.failed===void 0?{}:{failed:e.failed},...e.reqBytes===void 0?{}:{reqBytes:e.reqBytes},...e.resBytes===void 0?{}:{resBytes:e.resBytes}}}function A(e){if(e==null)return 0;if(typeof e==`string`)return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Blob)return e.size}function j(e,t){return p(e,t)}const ce=new Set([`action`,`formaction`,`href`,`src`]);function le(t){let n=()=>{t.beforeUserActivity?.()},r={emit:e=>{t.emit(ue(e,t.redactUrlPatterns))},maskAllInputs:t.maskAllInputs,recordCanvas:!1,collectFonts:!1,inlineImages:!1,recordCrossOriginIframes:!1,slimDOMOptions:`all`,hooks:{input:n,mediaInteaction:n,mouseInteraction:n,mousemove:n,scroll:n,selection:n,viewportResize:n},sampling:{mousemove:100,mouseInteraction:!0,scroll:250,media:800,input:`last`}};t.maskAllText?r.maskTextSelector=`*`:t.maskTextSelector!==void 0&&t.maskTextSelector.length>0&&(r.maskTextSelector=t.maskTextSelector),t.blockSelector!==void 0&&t.blockSelector.length>0&&(r.blockSelector=t.blockSelector),t.checkoutEveryNms!==void 0&&t.checkoutEveryNms>0&&(r.checkoutEveryNms=t.checkoutEveryNms);let i=e(r);if(i===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{i()},addCustomEvent:(t,n)=>{e.addCustomEvent(t,n)},takeFullSnapshot:()=>{e.takeFullSnapshot(!0)}}}function ue(e,t){if(typeof e.data!=`object`||e.data===null)return e;let n=e.data;if(e.type===i.Meta){if(typeof n.href!=`string`)return e;let r=m(n.href,t,window.location.href);return r===n.href?e:{...e,data:{...n,href:r}}}if(e.type!==i.FullSnapshot&&(e.type!==i.IncrementalSnapshot||n.source!==a.Mutation))return e;let r=M(n,t);return r===n?e:{...e,data:r}}function M(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=M(i,t);e!==i&&(n=!0),r.push(e)}return n?r:e}if(typeof e!=`object`||!e)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n=e===`attributes`&&!Array.isArray(a)?de(a,t):M(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function de(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){if(!ce.has(e.toLowerCase())||typeof a!=`string`){i[e]=a;continue}let n=m(a,t,window.location.href);n!==a&&(r=!0),i[e]=n}return r?i:e}function N(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function fe(e){let t=e.random??Math.random;return t()<N(e.sessionSampleRate)?`full`:t()<N(e.onErrorSampleRate)?`buffer`:`off`}const pe=/^[a-z][a-z0-9_]{0,63}$/u;function me(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function he(e,t){if(e===void 0)return Object.freeze({});let n;try{n=e()}catch(e){return t(e),Object.freeze({})}if(typeof n!=`object`||!n||Array.isArray(n))return Object.freeze({});let r;try{r=Object.getPrototypeOf(n)}catch(e){return t(e),Object.freeze({})}if(r!==Object.prototype&&r!==null)return Object.freeze({});let i;try{i=Object.keys(n)}catch(e){return t(e),Object.freeze({})}let a={},o=0;for(let e of i){if(!pe.test(e))continue;let r;try{r=Reflect.get(n,e)}catch(e){t(e);continue}if((typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r)||typeof r==`string`&&me(r,200))&&(a[e]=r,o+=1,o===20))break}return Object.freeze(a)}function ge(e=Date.now){let t=e(),n=new Uint8Array(new ArrayBuffer(16));_e(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/2**8)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function _e(e){let t=globalThis.crypto;if(typeof t?.getRandomValues==`function`){t.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const P=`lf_session_replay`;var F=class{idleTimeoutMs;maxDurationMs;now;storage;memorySession;pendingSession;persistenceTimer;constructor(e){this.idleTimeoutMs=e.idleTimeoutMs,this.maxDurationMs=e.maxDurationMs,this.now=e.now??Date.now,this.storage=e.storage===void 0?I():e.storage}getSession(){let e=this.now();if(this.memorySession!==void 0&&!this.isExpired(this.memorySession,e))return this.memorySession;let t=this.read();return t!==void 0&&!this.isExpired(t,e)?t:this.createSession(e)}touch(){let e=this.now(),t={...this.getSession(),lastActivityAt:e};return this.memorySession=t,this.scheduleWrite(t),t}reset(){return this.createSession(this.now())}flushPendingStorage(){this.persistenceTimer!==void 0&&(clearTimeout(this.persistenceTimer),this.persistenceTimer=void 0);let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)}isExpired(e,t){return t-e.lastActivityAt>this.idleTimeoutMs||t-e.startedAt>this.maxDurationMs}createSession(e){let t={id:ge(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(P);if(e!==null){let t=JSON.parse(e);if(ve(t))return this.memorySession=t,t}}catch{return this.memorySession}return this.memorySession}write(e){if(this.memorySession=e,this.storage!==null)try{this.storage.setItem(P,JSON.stringify(e))}catch{}}scheduleWrite(e){this.pendingSession=e,this.persistenceTimer===void 0&&(this.persistenceTimer=setTimeout(()=>{this.persistenceTimer=void 0;let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)},1e3))}writeNow(e){this.memorySession=e,this.write(e)}};function I(){try{return globalThis.sessionStorage??null}catch{return null}}function ve(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}function L(e){return typeof e==`object`&&e?e:void 0}function R(e){return typeof e==`string`&&e.length>0?e:void 0}function ye(e,t,n,r={}){let c=1/0,l=0,u=0,d=0,f=0,p=!1,m=new Set;for(let e of t){e.timestamp<c&&(c=e.timestamp),e.timestamp>l&&(l=e.timestamp);let t=L(e.data);if(e.type===i.FullSnapshot)p=!0;else if(e.type===i.Meta){let e=R(t?.href);e!==void 0&&m.add(e)}else if(e.type===i.IncrementalSnapshot&&t!==void 0){let e=t.source;if(e===a.MouseInteraction){let e=t.type;(e===o.Click||e===o.DblClick)&&u++}else e===a.Input&&d++}else if(e.type===i.Custom&&t!==void 0){let e=R(t.tag),n=L(t.payload);if(e===s.Error)f++;else if(e===s.Console)n?.level===`error`&&f++;else if(e===s.Navigation){let e=R(n?.url);e!==void 0&&m.add(e)}}}return{seq:e,firstTimestamp:c===1/0?0:c,lastTimestamp:l,eventCount:t.length,clickCount:u,keypressCount:d,errorCount:f,hasFullSnapshot:p,urls:[...m],...n!==void 0&&n.length>0?{distinctId:n}:{},...Object.keys(r).length===0?{}:{sessionAttributes:{...r}}}}const z=`lf_session_replay_seq`,be={gzip:t,gzipSync:n};var xe=class{buffer=[];bufferHasFullSnapshot=!1;pendingBytes=0;seq=0;timer;nextFlushAt;lastUserActivityAt;startedAt;started=!1;held;heldBufferIncomplete=!1;mode;flushing;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;constructor(e,t,n,r=I(),i=be,a={},o={}){this.config=e,this.sessionId=t,this.sessionAttributes=Object.freeze({...a}),this.mode=n,this.storage=r,this.compression=i,this.held=o.holdUntilActivity===!0&&n===`full`,this.seq=this.loadSeq(t),this.startedAt=this.config.now(),this.lastUserActivityAt=this.startedAt}start(){this.started||this.mode!==`full`||(this.started=!0,this.scheduleFlush())}add(e){d(e)&&(this.lastUserActivityAt=this.config.now());let t=H(e);if(this.mode===`buffer`||this.held){if(e.type===i.Meta){this.buffer=[e],this.bufferHasFullSnapshot=!1,this.pendingBytes=t;return}if(e.type===i.FullSnapshot){let n=!this.bufferHasFullSnapshot&&this.buffer.length===1&&this.buffer[0]?.type===i.Meta?this.buffer[0]:void 0;this.buffer=n===void 0?[e]:[n,e],this.bufferHasFullSnapshot=!0,this.pendingBytes=t+(n===void 0?0:H(n)),this.heldBufferIncomplete=!1;return}if(!this.bufferHasFullSnapshot||t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held;return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held;return}}this.buffer.push(e),this.pendingBytes+=t,this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport({ignoreMinimumDuration:!0}):this.scheduleFlush()}async triggerFlush(){return this.mode===`buffer`&&(this.bufferHasFullSnapshot||(this.buffer=[],this.pendingBytes=0),this.mode=`full`,this.start()),this.flush()}async flush(e={}){return this.flushInternal(e)}async flushInternal(e){if(this.mode===`buffer`||this.held||this.buffer.length===0)return;if(e.ignoreMinimumDuration!==!0&&!this.minimumDurationReached()){this.scheduleMinimumDurationFlush();return}this.clearScheduledFlush();let t=this.buffer;this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0;let n=e.keepalive===!0?Te(t):[t],r=this.seq;this.seq+=n.length;let i=this.sessionId;this.saveSeq(i,this.seq);let a=e.keepalive===!0?Promise.resolve():this.flushing??Promise.resolve(),o=e.keepalive===!0?this.deliverLifecycle(n,r,i):a.then(async()=>{for(let e=0;e<n.length;e++){let t=n[e];t!==void 0&&await this.deliverOrdinary(t,r+e,i)}}),s=this.flushing;this.flushing=e.keepalive===!0&&s!==void 0?Promise.all([s,o]).then(()=>void 0,()=>void 0):o.catch(()=>void 0),await o}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held){this.discard(),await this.flushing;return}if(!this.minimumDurationReached()){this.discard(),await this.flushing;return}await this.flush(e),await this.flushing}discard(){this.started=!1,this.clearScheduledFlush(),this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0}getMode(){return this.mode}isHeld(){return this.held}releaseHeld(e){this.held&&((this.heldBufferIncomplete||!this.bufferHasFullSnapshot)&&(this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,e()),this.held=!1,this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport({ignoreMinimumDuration:!0}):this.scheduleFlush())}flushAndReport(e={}){this.flushInternal(e).catch(e=>{B(this.config.onError,e)})}scheduleFlush(){let e=this.config.now(),t=Math.max(0,this.config.minSessionDurationMs-(e-this.startedAt)),n=Math.max(f(this.config.flushIntervalMs,e-this.lastUserActivityAt),t);this.scheduleFlushIn(e,n)}scheduleMinimumDurationFlush(){let e=this.config.now(),t=Math.max(0,this.config.minSessionDurationMs-(e-this.startedAt));this.scheduleFlushIn(e,t)}scheduleFlushIn(e,t){if(!this.started||this.mode!==`full`||this.held||this.buffer.length===0)return;let n=e+t;this.timer!==void 0&&this.nextFlushAt!==void 0&&this.nextFlushAt<=n||(this.clearScheduledFlush(),this.nextFlushAt=n,this.timer=setTimeout(()=>{this.timer=void 0,this.nextFlushAt=void 0,this.flushAndReport()},t))}clearScheduledFlush(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0),this.nextFlushAt=void 0}minimumDurationReached(){return this.config.now()-this.startedAt>=this.config.minSessionDurationMs}createEnvelope(e,t){let n=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{n=this.config.getDistinctId()??this.config.distinctId}catch(e){B(this.config.onError,e)}return{version:1,meta:ye(t,e,n,this.sessionAttributes),events:e}}async deliverOrdinary(e,t,n){let i=this.createEnvelope(e,t);try{let e=r(JSON.stringify(i)),a=await this.compressOrdinary(e);await this.sendWithRetry({body:a,lifecycle:!1,requestKeepalive:!1,reservedBytes:0,seq:t,sessionId:n})}catch(e){B(this.config.onError,e)}}async deliverLifecycle(e,t,n){let i=[];for(let a=0;a<e.length;a++){let o=e[a];if(o===void 0){i.push(void 0);continue}let s=this.createEnvelope(o,t+a);try{i.push({body:this.compression.gzipSync(r(JSON.stringify(s))),lifecycle:!0,requestKeepalive:!1,reservedBytes:0,seq:t+a,sessionId:n})}catch(e){B(this.config.onError,e),i.push(void 0)}}let a=!0,o=Math.max(0,48e3-this.reservedKeepaliveBytes);for(let e of i){if(e===void 0){a=!1;continue}a&&e.body.byteLength<=o?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,o-=e.reservedBytes):a=!1}await Promise.all(i.map(async e=>{if(e!==void 0)try{await this.sendWithRetry(e)}catch(e){B(this.config.onError,e)}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await Ee(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async sendWithRetry(e){let t=e.lifecycle?1:3;for(let n=1;n<=t;n++)try{await this.send(e);return}catch(e){let r=Oe(e,n);if(r===void 0||n>=t)throw e;await we(r)}}async send(e){let t,n,r,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`replay upload timed out after 10000ms`))},1e4);try{let a=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,o=await this.getUploadHeaders(),s=this.config.fetchImpl(a,{method:`POST`,headers:o,body:e.body.slice(),keepalive:e.requestKeepalive,signal:i.signal});t=!0;let c=await s;if(n=!0,r=await De(c),!c.ok){let e=c.status===429?ke(c.headers.get(`retry-after`),Date.now()):void 0;throw new V(c.status,e)}}finally{clearTimeout(a),e.reservedBytes>0&&(t!==!0||n!==!0||r===!0)&&(this.reservedKeepaliveBytes=Math.max(0,this.reservedKeepaliveBytes-e.reservedBytes))}}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await Ce(this.config.token);return{...e,...t===void 0||t.length===0?{}:{Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}loadSeq(e){if(this.storage===null)return 0;try{let t=this.storage.getItem(z);if(t===null)return 0;let n=JSON.parse(t);if(typeof n!=`object`||!n)return 0;let r=n;return r.id===e&&typeof r.seq==`number`&&Number.isFinite(r.seq)?r.seq:0}catch{return 0}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(z,JSON.stringify({id:e,seq:t}))}catch{}}};function B(e,t){try{let n=e?.(t);Se(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Se(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var V=class extends Error{retryAfter;status;constructor(e,t){super(`replay ingest failed: ${String(e)}`),this.status=e,this.retryAfter=t,this.name=`ReplayIngestError`}};async function Ce(e){return typeof e==`function`?e():e}async function we(e){return new Promise(t=>{setTimeout(t,e)})}function H(e){try{return r(JSON.stringify(e)).byteLength}catch{return 0}}function Te(e){let t=[],n=[],r=0;for(let i of e){let e=H(i);n.length>0&&r+e>48e3&&(t.push(n),n=[],r=0),n.push(i),r+=e}return n.length>0&&t.push(n),t}async function Ee(e,t){return new Promise((n,r)=>{let i=[];typeof window<`u`&&i.push(window),typeof document<`u`&&i.push(document);let a=()=>{for(let e of i)e.removeEventListener(`securitypolicyviolation`,s)},o=(e,t)=>{if(a(),e!==null){r(e);return}n(t)},s=e=>{let t=e;(t.effectiveDirective.includes(`worker-src`)||t.violatedDirective.includes(`worker-src`))&&o(Error(`replay compression worker blocked by Content Security Policy`))};for(let e of i)e.addEventListener(`securitypolicyviolation`,s);try{e.gzip(t,{level:6},(e,t)=>{o(e,t)})}catch(e){a(),r(e instanceof Error?e:Error(String(e)))}})}async function De(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function Oe(e,t){return e instanceof V?e.status===429?e.retryAfter?.kind===`too-long`?void 0:e.retryAfter?.kind===`delay`?e.retryAfter.milliseconds:500*t:e.status<500?void 0:500*t:500*t}function ke(e,t){if(e===null)return{kind:`fallback`};let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?U(e*1e3):{kind:`fallback`}}let r=Ne(n,t);return r===void 0?{kind:`fallback`}:U(Math.max(0,r-t))}function U(e){return e>1e4?{kind:`too-long`}:{kind:`delay`,milliseconds:e}}const Ae=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],je=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Me=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function Ne(e,t){let n=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(n!==null)return W(n[1],n[2],n[3],n[4],n[5],n[6],n[7]);let r=/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(r!==null){let e=new Date(t).getUTCFullYear(),n=Number(r[4]),i=Math.floor(e/100)*100+n;return i>e+50&&(i-=100),W(r[1],r[2],r[3],String(i),r[5],r[6],r[7])}let i=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/u.exec(e);if(i!==null)return W(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function W(e,t,n,r,i,a,o){let s=Number(t),c=Ae.indexOf(n),l=Number(r),u=Number(i),d=Number(a),f=Number(o);if(c<0||s<1||s>31||u>23||d>59||f>59)return;let p=new Date(0);if(p.setUTCFullYear(l,c,s),p.setUTCHours(u,d,f,0),p.getUTCFullYear()!==l||p.getUTCMonth()!==c||p.getUTCDate()!==s||p.getUTCHours()!==u||p.getUTCMinutes()!==d||p.getUTCSeconds()!==f)return;let m=je.indexOf(e),h=Me.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const Pe={mode:`off`,recording:!1,getSessionId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},G=`lf_session_replay_mode`,K=Symbol.for(`@pydantic/logfire-session-replay/controller`);function Fe(e){if(typeof window>`u`||typeof document>`u`)return Pe;let t=He();try{let n=Le(e),r=new F({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Z(n.onError,e),i}if(t!==void 0&&t.length>0)return i=t,t;let a=e?r.touch().id:r.getSession().id;return i=a,a},o=I(),s=a(!1),c,l=!1,u=Promise.resolve(),d,f=(e,t,r=!t)=>{let i=Re(n,e,o);if(!(i===`off`||l||e!==s))try{c=Ie({config:n,getSessionId:a,mode:i,onSessionChanged:p,samplingModeStorage:o,sessionId:e,holdUntilActivity:r})}catch(e){if(c=void 0,t)throw e;Z(n.onError,e)}},p=(e,t=!0)=>{if(l||e===s)return;s=e;let r=c;c=void 0;let i=r?.deactivate()??Promise.resolve();u=u.then(async()=>{await X(i,n.onError),!l&&s===e&&f(e,!1,t)})},m;try{f(s,!0),m=setInterval(()=>{p(a(!1))},1e3)}catch(e){throw c?.discard(),c=void 0,e}return{get mode(){try{return c?.transport.getMode()??`off`}catch(e){return Z(n.onError,e),`off`}},get recording(){try{return c!==void 0}catch(e){return Z(n.onError,e),!1}},getSessionId:()=>a(!1),flush:async()=>{try{await u,await c?.transport.flush()}catch(e){Z(n.onError,e)}},stop:async()=>(d??=(async()=>{l=!0,clearInterval(m);let e=c;c=void 0,await X(e?.deactivate()??Promise.resolve(),n.onError),await u,r.flushPendingStorage(),t()})(),d)}}catch(e){throw t(),e}}function Ie(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:a,samplingModeStorage:o,sessionId:c}=e,l=new xe(t,c,i,void 0,void 0,he(t.getSessionAttributes,e=>{Z(t.onError,e)}),{holdUntilActivity:r}),u=[],f=!0,p=()=>f,m;try{let e=le({beforeUserActivity:()=>{if(!(!f||!l.isHeld()))try{let t=n(!0);if(t!==c){a(t,!1);return}l.releaseHeld(()=>{e.takeFullSnapshot()})}catch(e){Z(t.onError,e)}},emit:e=>{if(f)try{let t=n(d(e));if(t!==c){a(t,!1);return}l.add(e)}catch(e){Z(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:0,redactUrlPatterns:t.redactUrlPatterns});u.push(()=>{e.stop()});let r=(n,r)=>{if(f)try{e.addCustomEvent(n,r)}catch(e){Z(t.onError,e)}},h=n=>{p()&&(l.releaseHeld(()=>{e.takeFullSnapshot()}),r(s.Error,n),p()&&l.getMode()===`buffer`&&(q(o,c,`full`),Y(l.triggerFlush(),t.onError)))},g=e=>{e instanceof ErrorEvent&&h($(e.message,e.filename,Be(e.error)))},_=e=>{let t=e.reason;h($(Ue(t?.message??e.reason),void 0,typeof t?.stack==`string`?t.stack:void 0))},y=()=>{document.visibilityState===`hidden`&&Y(l.flush({keepalive:!0}),t.onError)},b=()=>{Y(l.flush({keepalive:!0}),t.onError)};return window.addEventListener(`error`,g,!0),u.push(()=>{window.removeEventListener(`error`,g,!0)}),window.addEventListener(`unhandledrejection`,_,!0),u.push(()=>{window.removeEventListener(`unhandledrejection`,_,!0)}),document.addEventListener(`visibilitychange`,y),u.push(()=>{document.removeEventListener(`visibilitychange`,y)}),window.addEventListener(`pagehide`,b),u.push(()=>{window.removeEventListener(`pagehide`,b)}),t.captureConsole&&u.push(ee(r,{onError:t.onError})),t.captureNetwork&&u.push(v(r,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&u.push(te(r,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),l.start(),{sessionId:c,transport:l,deactivate:async()=>(m??=(async()=>{f=!1,Q(u),await l.shutdown({keepalive:!1})})(),m),discard:()=>{f=!1,Q(u),l.discard()}}}catch(e){throw f=!1,Q(u),l.discard(),e}}function Le(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=new URL(e.replayUrl,`https://logfire.invalid/`);if(t.search!==``||t.hash!==``)throw Error("logfire session replay: `replayUrl` must not contain a query or fragment");let n=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(n===void 0)throw Error("logfire session replay: no `fetch` available; pass `fetchImpl`");return{replayUrl:e.replayUrl,headers:e.headers,token:e.token,getSessionId:e.getSessionId,getSessionAttributes:e.getSessionAttributes,sessionSampleRate:e.sessionSampleRate??l.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??l.onErrorSampleRate,maskAllText:e.maskAllText??l.maskAllText,maskAllInputs:e.maskAllInputs??l.maskAllInputs,maskTextSelector:e.maskTextSelector??l.maskTextSelector,blockSelector:e.blockSelector??l.blockSelector,flushIntervalMs:e.flushIntervalMs??l.flushIntervalMs,maxBufferBytes:e.maxBufferBytes??l.maxBufferBytes,minSessionDurationMs:e.minSessionDurationMs??l.minSessionDurationMs,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??l.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??l.maxSessionDurationMs,distinctId:e.distinctId??l.distinctId,getDistinctId:e.getDistinctId,captureConsole:e.captureConsole??l.captureConsole,captureNetwork:e.captureNetwork??l.captureNetwork,captureNavigation:e.captureNavigation??l.captureNavigation,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...l.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function Re(e,t,n){let r=ze(n,t);if(r!==void 0)return r;let i=fe({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return q(n,t,i),i}function ze(e,t){if(e!==null)try{let n=e.getItem(G);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!J(i.mode)?void 0:i.mode}catch{return}}function q(e,t,n){if(e!==null)try{e.setItem(G,JSON.stringify({id:t,mode:n}))}catch{}}function J(e){return e===`full`||e===`buffer`||e===`off`}function Be(e){let t=typeof e==`object`&&e&&`stack`in e?e.stack:void 0;return typeof t==`string`?t:void 0}function Y(e,t){e.catch(e=>{Z(t,e)})}async function X(e,t){try{await e}catch(e){Z(t,e)}}function Z(e,t){try{let n=e?.(t);Ve(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Ve(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function He(){let e=globalThis;if(e[K]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,K,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[K]===t&&Reflect.deleteProperty(e,K))}}function Q(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function $(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function Ue(e){if(e==null)return`unhandledrejection`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);try{let t=JSON.stringify(e);return typeof t==`string`?t:Object.prototype.toString.call(e)}catch{return Object.prototype.toString.call(e)}}export{c as CHUNK_ENVELOPE_VERSION,s as CustomTag,i as EventType,a as IncrementalSource,o as MouseInteractions,Fe as startSessionReplay};
1
+ import{record as e}from"@rrweb/record";import{gzip as t,gzipSync as n,strToU8 as r}from"fflate";const i={DomContentLoaded:0,Load:1,FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Custom:5,Plugin:6},a={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5,TouchMove:6,MediaInteraction:7,Drag:12,Selection:14},o={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},s={Error:`logfire.error`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},c=1,l={sessionSampleRate:1,onErrorSampleRate:1,maskAllText:!0,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,minSessionDurationMs:5e3,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:144e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,redactUrlPatterns:[/.+/u]},u=new Set([a.MouseMove,a.MouseInteraction,a.Scroll,a.ViewportResize,a.Input,a.TouchMove,a.MediaInteraction,a.Drag,a.Selection]);function d(e){return e.type!==i.IncrementalSnapshot||typeof e.data!=`object`||e.data===null||!(`source`in e.data)?!1:typeof e.data.source==`number`&&u.has(e.data.source)}function f(e,t){return t<3e4?e:t<3e5?Math.max(e,6e4):Math.max(e,3e5)}function p(e,t){return t.some(t=>new RegExp(t.source,t.flags).test(e))}function m(e,t,n){if(!p(e,t))return e;try{let t=new URL(e,n);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const h=[`log`,`info`,`warn`,`error`,`debug`],g=1024,_=()=>void 0;function ee(e,t={}){let n=[],r=C(t.onError);try{for(let t of h)typeof console[t]==`function`&&n.push(w(console,t,(n,i)=>function(...a){return i()&&S(e,s.Console,{level:t,args:a.slice(0,10).map(ie)},r),n.apply(this,a)}));return T(n)}catch(e){throw E(n),e}}function v(e,t){let n=ne(t),r={...n,onError:C(n.onError)},i=y(e,r);try{return T([i,b(e,r)])}catch(e){throw i(),e}}function te(e,t={redactUrlPatterns:[]}){let n=C(t.onError),r=r=>{let i=m(window.location.href,t.redactUrlPatterns??[],window.location.href);S(e,s.Navigation,{url:i,kind:r},n)},i=[];try{i.push(w(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(w(history,`replaceState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`replace`),i}));let e=!0,t=()=>{e&&r(`pop`)};return window.addEventListener(`popstate`,t),i.push(()=>{e=!1,window.removeEventListener(`popstate`,t)}),T(i)}catch(e){throw E(i),e}}function y(e,t){return typeof window.fetch==`function`?w(window,`fetch`,(n,r)=>{let i=async function(i,a){let o=n;if(!r())return o.call(this,i,a);let c=t.now(),l=O(i,a),u=ae(i);if(j(u,t.ignoreUrlPatterns))return o.call(this,i,a);let d=m(u,t.redactUrlPatterns,window.location.href),f=A(a?.body);try{let n=await o.call(this,i,a);return r()&&S(e,s.Network,k({method:l,url:d,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:f,resBytes:oe(n.headers)}),t.onError),n}catch(n){throw r()&&S(e,s.Network,k({method:l,url:d,status:0,durationMs:Math.max(0,t.now()-c),failed:!0,reqBytes:f}),t.onError),n}},a=Reflect.get(n,`__original`);return Object.defineProperty(i,"__original",{configurable:!0,value:typeof a==`function`?a:n,writable:!0}),i}):_}function b(e,t){let n=window.XMLHttpRequest.prototype,r=new WeakMap,i=[];try{return i.push(w(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return j(s,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:a.toUpperCase(),url:m(s,t.redactUrlPatterns,window.location.href),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(w(n,`send`,(n,i)=>function(...a){let[o]=a,c=i()?r.get(this):void 0;if(c===void 0)return n.apply(this,a);c.startedAt=t.now(),c.reqBytes=A(o);let l=()=>{c.failed=!0},u=()=>{c.emitted||(c.emitted=!0,this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),i()&&S(e,s.Network,k({method:c.method,url:c.url,status:this.status,durationMs:Math.max(0,t.now()-c.startedAt),failed:c.failed||this.status===0,reqBytes:c.reqBytes,resBytes:se(this)}),t.onError))};this.addEventListener(`error`,l),this.addEventListener(`abort`,l),this.addEventListener(`timeout`,l),this.addEventListener(`loadend`,u,{once:!0});try{return n.apply(this,a)}catch(n){throw this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),this.removeEventListener(`loadend`,u),i()&&S(e,s.Network,k({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),T(i)}catch(e){throw E(i),e}}function ne(e){return{...e,ignoreUrlPatterns:x(e.ignoreUrlPatterns),redactUrlPatterns:x(e.redactUrlPatterns)}}function x(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function S(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function C(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);re(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function re(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function w(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return _;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function T(e){let t=!1;return()=>{t||(t=!0,E(e))}}function E(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function ie(e){if(e==null)return String(e);if(typeof e==`string`)return D(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return D(e.stack??`${e.name}: ${e.message}`);try{return D(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function D(e){if(e.length<=g)return e;let t=e.charCodeAt(g-1),n=t>=55296&&t<=56319?g-1:g;return`${e.slice(0,n)}...(+${String(e.length-n)} chars)`}function O(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function ae(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function oe(e){let t=e.get(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}function se(e){try{let t=e.getResponseHeader(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}catch{return}}function k(e){return{method:e.method,url:e.url,status:e.status,durationMs:e.durationMs,...e.failed===void 0?{}:{failed:e.failed},...e.reqBytes===void 0?{}:{reqBytes:e.reqBytes},...e.resBytes===void 0?{}:{resBytes:e.resBytes}}}function A(e){if(e==null)return 0;if(typeof e==`string`)return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Blob)return e.size}function j(e,t){return p(e,t)}const ce=new Set([`action`,`formaction`,`href`,`src`]);function le(t){let n=()=>{t.beforeUserActivity?.()},r={emit:e=>{t.emit(ue(e,t.redactUrlPatterns))},maskAllInputs:t.maskAllInputs,recordCanvas:!1,collectFonts:!1,inlineImages:!1,recordCrossOriginIframes:!1,slimDOMOptions:`all`,hooks:{input:n,mediaInteaction:n,mouseInteraction:n,mousemove:n,scroll:n,selection:n,viewportResize:n},sampling:{mousemove:100,mouseInteraction:!0,scroll:250,media:800,input:`last`}};t.maskAllText?r.maskTextSelector=`*`:t.maskTextSelector!==void 0&&t.maskTextSelector.length>0&&(r.maskTextSelector=t.maskTextSelector),t.blockSelector!==void 0&&t.blockSelector.length>0&&(r.blockSelector=t.blockSelector),t.checkoutEveryNms!==void 0&&t.checkoutEveryNms>0&&(r.checkoutEveryNms=t.checkoutEveryNms);let i=e(r);if(i===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{i()},addCustomEvent:(t,n)=>{e.addCustomEvent(t,n)},takeFullSnapshot:()=>{e.takeFullSnapshot(!0)}}}function ue(e,t){if(typeof e.data!=`object`||e.data===null)return e;let n=e.data;if(e.type===i.Meta){if(typeof n.href!=`string`)return e;let r=m(n.href,t,window.location.href);return r===n.href?e:{...e,data:{...n,href:r}}}if(e.type!==i.FullSnapshot&&(e.type!==i.IncrementalSnapshot||n.source!==a.Mutation))return e;let r=M(n,t);return r===n?e:{...e,data:r}}function M(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=M(i,t);e!==i&&(n=!0),r.push(e)}return n?r:e}if(typeof e!=`object`||!e)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n=e===`attributes`&&!Array.isArray(a)?de(a,t):M(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function de(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){if(!ce.has(e.toLowerCase())||typeof a!=`string`){i[e]=a;continue}let n=m(a,t,window.location.href);n!==a&&(r=!0),i[e]=n}return r?i:e}function N(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function fe(e){let t=e.random??Math.random;return t()<N(e.sessionSampleRate)?`full`:t()<N(e.onErrorSampleRate)?`buffer`:`off`}const pe=/^[a-z][a-z0-9_]{0,63}$/u;function me(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function he(e,t){if(e===void 0)return Object.freeze({});let n;try{n=e()}catch(e){return t(e),Object.freeze({})}if(typeof n!=`object`||!n||Array.isArray(n))return Object.freeze({});let r;try{r=Object.getPrototypeOf(n)}catch(e){return t(e),Object.freeze({})}if(r!==Object.prototype&&r!==null)return Object.freeze({});let i;try{i=Object.keys(n)}catch(e){return t(e),Object.freeze({})}let a={},o=0;for(let e of i){if(!pe.test(e))continue;let r;try{r=Reflect.get(n,e)}catch(e){t(e);continue}if((typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r)||typeof r==`string`&&me(r,200))&&(Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:r,writable:!0}),o+=1,o===20))break}return Object.freeze(a)}function ge(e=Date.now){let t=e(),n=new Uint8Array(new ArrayBuffer(16));_e(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/2**8)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function _e(e){let t=globalThis.crypto;if(typeof t?.getRandomValues==`function`){t.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const P=`lf_session_replay`;var F=class{idleTimeoutMs;maxDurationMs;now;storage;memorySession;pendingSession;persistenceTimer;constructor(e){this.idleTimeoutMs=e.idleTimeoutMs,this.maxDurationMs=e.maxDurationMs,this.now=e.now??Date.now,this.storage=e.storage===void 0?I():e.storage}getSession(){let e=this.now();if(this.memorySession!==void 0&&!this.isExpired(this.memorySession,e))return this.memorySession;let t=this.read();return t!==void 0&&!this.isExpired(t,e)?t:this.createSession(e)}touch(){let e=this.now(),t={...this.getSession(),lastActivityAt:e};return this.memorySession=t,this.scheduleWrite(t),t}reset(){return this.createSession(this.now())}flushPendingStorage(){this.persistenceTimer!==void 0&&(clearTimeout(this.persistenceTimer),this.persistenceTimer=void 0);let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)}isExpired(e,t){return t-e.lastActivityAt>this.idleTimeoutMs||t-e.startedAt>this.maxDurationMs}createSession(e){let t={id:ge(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(P);if(e!==null){let t=JSON.parse(e);if(ve(t))return this.memorySession=t,t}}catch{return this.memorySession}return this.memorySession}write(e){if(this.memorySession=e,this.storage!==null)try{this.storage.setItem(P,JSON.stringify(e))}catch{}}scheduleWrite(e){this.pendingSession=e,this.persistenceTimer===void 0&&(this.persistenceTimer=setTimeout(()=>{this.persistenceTimer=void 0;let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)},1e3))}writeNow(e){this.memorySession=e,this.write(e)}};function I(){try{return globalThis.sessionStorage??null}catch{return null}}function ve(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}function L(e){return typeof e==`object`&&e?e:void 0}function R(e){return typeof e==`string`&&e.length>0?e:void 0}function ye(e,t,n,r={}){let c=1/0,l=0,u=0,d=0,f=0,p=!1,m=new Set;for(let e of t){e.timestamp<c&&(c=e.timestamp),e.timestamp>l&&(l=e.timestamp);let t=L(e.data);if(e.type===i.FullSnapshot)p=!0;else if(e.type===i.Meta){let e=R(t?.href);e!==void 0&&m.add(e)}else if(e.type===i.IncrementalSnapshot&&t!==void 0){let e=t.source;if(e===a.MouseInteraction){let e=t.type;(e===o.Click||e===o.DblClick)&&u++}else e===a.Input&&d++}else if(e.type===i.Custom&&t!==void 0){let e=R(t.tag),n=L(t.payload);if(e===s.Error)f++;else if(e===s.Console)n?.level===`error`&&f++;else if(e===s.Navigation){let e=R(n?.url);e!==void 0&&m.add(e)}}}return{seq:e,firstTimestamp:c===1/0?0:c,lastTimestamp:l,eventCount:t.length,clickCount:u,keypressCount:d,errorCount:f,hasFullSnapshot:p,urls:[...m],...n!==void 0&&n.length>0?{distinctId:n}:{},...Object.keys(r).length===0?{}:{sessionAttributes:{...r}}}}const z=`lf_session_replay_seq`,be={gzip:t,gzipSync:n};var xe=class{buffer=[];bufferHasFullSnapshot=!1;pendingBytes=0;seq=0;timer;nextFlushAt;lastUserActivityAt;startedAt;started=!1;held;heldBufferIncomplete=!1;minimumBufferIncomplete=!1;minimumDurationSatisfied=!1;firstObservedTimestamp;lastObservedTimestamp;refreshingMinimumSnapshot=!1;mode;flushing;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;takeFullSnapshot;constructor(e,t,n,r=I(),i=be,a={},o={}){this.config=e,this.sessionId=t,this.sessionAttributes=Object.freeze({...a}),this.mode=n,this.storage=r,this.compression=i,this.held=o.holdUntilActivity===!0&&n===`full`,this.takeFullSnapshot=o.takeFullSnapshot,this.minimumDurationSatisfied=e.minSessionDurationMs===0,this.seq=this.loadSeq(t),this.startedAt=this.config.now(),this.lastUserActivityAt=this.startedAt}start(){this.started||this.mode!==`full`||(this.started=!0,this.scheduleFlush())}add(e){this.minimumDurationSatisfied||(this.firstObservedTimestamp??=e.timestamp,this.lastObservedTimestamp=Math.max(this.lastObservedTimestamp??e.timestamp,e.timestamp)),d(e)&&(this.lastUserActivityAt=this.config.now());let t=H(e);if(this.refreshingMinimumSnapshot){this.buffer.push(e),this.pendingBytes+=t;return}let n=!this.minimumDurationSatisfied;if(this.mode===`buffer`||this.held||n){if(e.type===i.Meta){this.buffer=[e],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=t,n&&(this.mode===`full`&&(this.firstObservedTimestamp=e.timestamp),this.finishMinimumBufferingEvent());return}if(e.type===i.FullSnapshot){let r=!this.bufferHasFullSnapshot&&this.buffer.length===1&&this.buffer[0]?.type===i.Meta?this.buffer[0]:void 0;this.buffer=r===void 0?[e]:[r,e],this.bufferHasFullSnapshot=!0,this.pendingBytes=t+(r===void 0?0:H(r)),this.heldBufferIncomplete=!1,this.minimumBufferIncomplete=!1,n&&(this.mode===`full`&&(this.firstObservedTimestamp=r?.timestamp??e.timestamp),this.finishMinimumBufferingEvent());return}if(!this.bufferHasFullSnapshot||t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.minimumBufferIncomplete||=n,n&&this.finishMinimumBufferingEvent();return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.minimumBufferIncomplete||=n,n&&this.finishMinimumBufferingEvent();return}}if(this.buffer.push(e),this.pendingBytes+=t,n&&this.minimumDurationReached()){this.flushAndReport();return}this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()}async triggerFlush(){return this.mode===`buffer`&&(this.bufferHasFullSnapshot||(this.buffer=[],this.pendingBytes=0),this.mode=`full`,this.start()),this.flush()}async flush(e={}){return this.flushInternal(e)}async flushInternal(e={}){if(this.mode===`buffer`||this.held||this.buffer.length===0||!this.minimumDurationReached()||(this.clearScheduledFlush(),this.minimumBufferIncomplete&&!this.refreshMinimumBuffer()))return;this.minimumDurationSatisfied=!0;let t=this.buffer;this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0;let n=e.keepalive===!0?Te(t):[t],r=this.seq;this.seq+=n.length;let i=this.sessionId;this.saveSeq(i,this.seq);let a=e.keepalive===!0?Promise.resolve():this.flushing??Promise.resolve(),o=e.keepalive===!0?this.deliverLifecycle(n,r,i):a.then(async()=>{for(let e=0;e<n.length;e++){let t=n[e];t!==void 0&&await this.deliverOrdinary(t,r+e,i)}}),s=this.flushing;this.flushing=e.keepalive===!0&&s!==void 0?Promise.all([s,o]).then(()=>void 0,()=>void 0):o.catch(()=>void 0),await o}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held){this.discard(),await this.flushing;return}if(!this.minimumDurationReached()){this.discard(),await this.flushing;return}await this.flush(e),await this.flushing}discard(){this.started=!1,this.clearScheduledFlush(),this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0}getMode(){return this.mode}isHeld(){return this.held}releaseHeld(e){this.held&&((this.heldBufferIncomplete||!this.bufferHasFullSnapshot)&&(this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,e()),this.held=!1,this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush())}flushAndReport(){this.flushInternal().catch(e=>{B(this.config.onError,e)})}scheduleFlush(){let e=this.config.now(),t=Math.max(0,this.config.minSessionDurationMs-(e-this.startedAt)),n=Math.max(f(this.config.flushIntervalMs,e-this.lastUserActivityAt),t);this.scheduleFlushIn(e,n)}scheduleFlushIn(e,t){if(!this.started||this.mode!==`full`||this.held||this.buffer.length===0)return;let n=e+t;this.timer!==void 0&&this.nextFlushAt!==void 0&&this.nextFlushAt<=n||(this.clearScheduledFlush(),this.nextFlushAt=n,this.timer=setTimeout(()=>{this.timer=void 0,this.nextFlushAt=void 0,this.flushAndReport()},t))}clearScheduledFlush(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0),this.nextFlushAt=void 0}minimumDurationReached(){return this.minimumDurationSatisfied||this.config.minSessionDurationMs===0?!0:this.firstObservedTimestamp===void 0||this.lastObservedTimestamp===void 0?!1:this.lastObservedTimestamp-this.firstObservedTimestamp>=this.config.minSessionDurationMs}finishMinimumBufferingEvent(){this.minimumDurationReached()?this.flushAndReport():this.scheduleFlush()}refreshMinimumBuffer(){let e=this.buffer.length,t=this.pendingBytes;if(this.takeFullSnapshot!==void 0){this.refreshingMinimumSnapshot=!0;try{this.takeFullSnapshot()}catch(e){B(this.config.onError,e)}finally{this.refreshingMinimumSnapshot=!1}}return this.buffer.slice(e).some(e=>e.type===i.FullSnapshot)?(this.minimumBufferIncomplete=!1,!0):(this.buffer.length=e,this.pendingBytes=t,!1)}createEnvelope(e,t){let n=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{n=this.config.getDistinctId()??this.config.distinctId}catch(e){B(this.config.onError,e)}return{version:1,meta:ye(t,e,n,this.sessionAttributes),events:e}}async deliverOrdinary(e,t,n){let i=this.createEnvelope(e,t);try{let e=r(JSON.stringify(i)),a=await this.compressOrdinary(e);await this.sendWithRetry({body:a,lifecycle:!1,requestKeepalive:!1,reservedBytes:0,seq:t,sessionId:n})}catch(e){B(this.config.onError,e)}}async deliverLifecycle(e,t,n){let i=[];for(let a=0;a<e.length;a++){let o=e[a];if(o===void 0){i.push(void 0);continue}let s=this.createEnvelope(o,t+a);try{i.push({body:this.compression.gzipSync(r(JSON.stringify(s))),lifecycle:!0,requestKeepalive:!1,reservedBytes:0,seq:t+a,sessionId:n})}catch(e){B(this.config.onError,e),i.push(void 0)}}let a=!0,o=Math.max(0,48e3-this.reservedKeepaliveBytes);for(let e of i){if(e===void 0){a=!1;continue}a&&e.body.byteLength<=o?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,o-=e.reservedBytes):a=!1}await Promise.all(i.map(async e=>{if(e!==void 0)try{await this.sendWithRetry(e)}catch(e){B(this.config.onError,e)}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await Ee(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async sendWithRetry(e){let t=e.lifecycle?1:3;for(let n=1;n<=t;n++)try{await this.send(e);return}catch(e){let r=Oe(e,n);if(r===void 0||n>=t)throw e;await we(r)}}async send(e){let t,n,r,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`replay upload timed out after 10000ms`))},1e4);try{let a=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,o=await this.getUploadHeaders(),s=this.config.fetchImpl(a,{method:`POST`,headers:o,body:e.body.slice(),keepalive:e.requestKeepalive,signal:i.signal});t=!0;let c=await s;if(n=!0,r=await De(c),!c.ok){let e=c.status===429?ke(c.headers.get(`retry-after`),Date.now()):void 0;throw new V(c.status,e)}}finally{clearTimeout(a),e.reservedBytes>0&&(t!==!0||n!==!0||r===!0)&&(this.reservedKeepaliveBytes=Math.max(0,this.reservedKeepaliveBytes-e.reservedBytes))}}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await Ce(this.config.token);return{...t===void 0||t.length===0?e:{...Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`authorization`)),Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}loadSeq(e){if(this.storage===null)return 0;try{let t=this.storage.getItem(z);if(t===null)return 0;let n=JSON.parse(t);if(typeof n!=`object`||!n)return 0;let r=n;return r.id===e&&typeof r.seq==`number`&&Number.isFinite(r.seq)?r.seq:0}catch{return 0}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(z,JSON.stringify({id:e,seq:t}))}catch{}}};function B(e,t){try{let n=e?.(t);Se(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Se(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var V=class extends Error{retryAfter;status;constructor(e,t){super(`replay ingest failed: ${String(e)}`),this.status=e,this.retryAfter=t,this.name=`ReplayIngestError`}};async function Ce(e){return typeof e==`function`?e():e}async function we(e){return new Promise(t=>{setTimeout(t,e)})}function H(e){try{return r(JSON.stringify(e)).byteLength}catch{return 0}}function Te(e){let t=[],n=[],r=0;for(let i of e){let e=H(i);n.length>0&&r+e>48e3&&(t.push(n),n=[],r=0),n.push(i),r+=e}return n.length>0&&t.push(n),t}async function Ee(e,t){return new Promise((n,r)=>{let i=[];typeof window<`u`&&i.push(window),typeof document<`u`&&i.push(document);let a=()=>{for(let e of i)e.removeEventListener(`securitypolicyviolation`,s)},o=(e,t)=>{if(a(),e!==null){r(e);return}n(t)},s=e=>{let t=e;(t.effectiveDirective.includes(`worker-src`)||t.violatedDirective.includes(`worker-src`))&&o(Error(`replay compression worker blocked by Content Security Policy`))};for(let e of i)e.addEventListener(`securitypolicyviolation`,s);try{e.gzip(t,{level:6},(e,t)=>{o(e,t)})}catch(e){a(),r(e instanceof Error?e:Error(String(e)))}})}async function De(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function Oe(e,t){return e instanceof V?e.status===429?e.retryAfter?.kind===`too-long`?void 0:e.retryAfter?.kind===`delay`?e.retryAfter.milliseconds:500*t:e.status<500?void 0:500*t:500*t}function ke(e,t){if(e===null)return{kind:`fallback`};let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?U(e*1e3):{kind:`fallback`}}let r=Ne(n,t);return r===void 0?{kind:`fallback`}:U(Math.max(0,r-t))}function U(e){return e>1e4?{kind:`too-long`}:{kind:`delay`,milliseconds:e}}const Ae=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],je=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Me=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function Ne(e,t){let n=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(n!==null)return W(n[1],n[2],n[3],n[4],n[5],n[6],n[7]);let r=/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(r!==null){let e=new Date(t).getUTCFullYear(),n=Number(r[4]),i=Math.floor(e/100)*100+n;return i>e+50&&(i-=100),W(r[1],r[2],r[3],String(i),r[5],r[6],r[7])}let i=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/u.exec(e);if(i!==null)return W(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function W(e,t,n,r,i,a,o){let s=Number(t),c=Ae.indexOf(n),l=Number(r),u=Number(i),d=Number(a),f=Number(o);if(c<0||s<1||s>31||u>23||d>59||f>59)return;let p=new Date(0);if(p.setUTCFullYear(l,c,s),p.setUTCHours(u,d,f,0),p.getUTCFullYear()!==l||p.getUTCMonth()!==c||p.getUTCDate()!==s||p.getUTCHours()!==u||p.getUTCMinutes()!==d||p.getUTCSeconds()!==f)return;let m=je.indexOf(e),h=Me.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const Pe={mode:`off`,recording:!1,getSessionId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},G=`lf_session_replay_mode`,K=Symbol.for(`@pydantic/logfire-session-replay/controller`);function Fe(e){if(typeof window>`u`||typeof document>`u`)return Pe;let t=He();try{let n=Le(e),r=new F({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Z(n.onError,e),i}if(t!==void 0&&t.length>0)return i=t,t;let a=e?r.touch().id:r.getSession().id;return i=a,a},o=I(),s=a(!1),c,l=!1,u=Promise.resolve(),d,f=(e,t,r=!t)=>{let i=Re(n,e,o);if(!(i===`off`||l||e!==s))try{c=Ie({config:n,getSessionId:a,mode:i,onSessionChanged:p,samplingModeStorage:o,sessionId:e,holdUntilActivity:r})}catch(e){if(c=void 0,t)throw e;Z(n.onError,e)}},p=(e,t=!0)=>{if(l||e===s)return;s=e;let r=c;c=void 0;let i=r?.deactivate()??Promise.resolve();u=u.then(async()=>{await X(i,n.onError),!l&&s===e&&f(e,!1,t)})},m;try{f(s,!0),m=setInterval(()=>{p(a(!1))},1e3)}catch(e){throw c?.discard(),c=void 0,e}return{get mode(){try{return c?.transport.getMode()??`off`}catch(e){return Z(n.onError,e),`off`}},get recording(){try{return c!==void 0}catch(e){return Z(n.onError,e),!1}},getSessionId:()=>a(!1),flush:async()=>{try{await u,await c?.transport.flush()}catch(e){Z(n.onError,e)}},stop:async()=>(d??=(async()=>{l=!0,clearInterval(m);let e=c;c=void 0,await X(e?.deactivate()??Promise.resolve(),n.onError),await u,r.flushPendingStorage(),t()})(),d)}}catch(e){throw t(),e}}function Ie(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:a,samplingModeStorage:o,sessionId:c}=e,l=he(t.getSessionAttributes,e=>{Z(t.onError,e)}),u,f=new xe(t,c,i,void 0,void 0,l,{holdUntilActivity:r,takeFullSnapshot:()=>{u.takeFullSnapshot()}}),p=[],m=!0,h=()=>m,g;try{u=le({beforeUserActivity:()=>{if(!(!m||!f.isHeld()))try{let e=n(!0);if(e!==c){a(e,!1);return}f.releaseHeld(()=>{u.takeFullSnapshot()})}catch(e){Z(t.onError,e)}},emit:e=>{if(m)try{let t=n(d(e));if(t!==c){a(t,!1);return}f.add(e)}catch(e){Z(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:0,redactUrlPatterns:t.redactUrlPatterns}),p.push(()=>{u.stop()});let e=(e,n)=>{if(m)try{u.addCustomEvent(e,n)}catch(e){Z(t.onError,e)}},r=n=>{h()&&(f.releaseHeld(()=>{u.takeFullSnapshot()}),e(s.Error,n),h()&&f.getMode()===`buffer`&&(q(o,c,`full`),Y(f.triggerFlush(),t.onError)))},l=e=>{e instanceof ErrorEvent&&r($(e.message,e.filename,Be(e.error)))},_=e=>{let t=e.reason;r($(Ue(t?.message??e.reason),void 0,typeof t?.stack==`string`?t.stack:void 0))},y=()=>{document.visibilityState===`hidden`&&Y(f.flush({keepalive:!0}),t.onError)},b=()=>{Y(f.flush({keepalive:!0}),t.onError)};return window.addEventListener(`error`,l,!0),p.push(()=>{window.removeEventListener(`error`,l,!0)}),window.addEventListener(`unhandledrejection`,_,!0),p.push(()=>{window.removeEventListener(`unhandledrejection`,_,!0)}),document.addEventListener(`visibilitychange`,y),p.push(()=>{document.removeEventListener(`visibilitychange`,y)}),window.addEventListener(`pagehide`,b),p.push(()=>{window.removeEventListener(`pagehide`,b)}),t.captureConsole&&p.push(ee(e,{onError:t.onError})),t.captureNetwork&&p.push(v(e,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&p.push(te(e,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),f.start(),{sessionId:c,transport:f,deactivate:async()=>(g??=(async()=>{let e=f.flush({keepalive:!1});m=!1,Q(p),await e,await f.shutdown({keepalive:!1})})(),g),discard:()=>{m=!1,Q(p),f.discard()}}}catch(e){throw m=!1,Q(p),f.discard(),e}}function Le(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=new URL(e.replayUrl,`https://logfire.invalid/`);if(t.search!==``||t.hash!==``)throw Error("logfire session replay: `replayUrl` must not contain a query or fragment");let n=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(n===void 0)throw Error("logfire session replay: no `fetch` available; pass `fetchImpl`");return{replayUrl:e.replayUrl,headers:e.headers,token:e.token,getSessionId:e.getSessionId,getSessionAttributes:e.getSessionAttributes,sessionSampleRate:e.sessionSampleRate??l.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??l.onErrorSampleRate,maskAllText:e.maskAllText??l.maskAllText,maskAllInputs:e.maskAllInputs??l.maskAllInputs,maskTextSelector:e.maskTextSelector??l.maskTextSelector,blockSelector:e.blockSelector??l.blockSelector,flushIntervalMs:e.flushIntervalMs??l.flushIntervalMs,maxBufferBytes:e.maxBufferBytes??l.maxBufferBytes,minSessionDurationMs:e.minSessionDurationMs??l.minSessionDurationMs,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??l.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??l.maxSessionDurationMs,distinctId:e.distinctId??l.distinctId,getDistinctId:e.getDistinctId,captureConsole:e.captureConsole??l.captureConsole,captureNetwork:e.captureNetwork??l.captureNetwork,captureNavigation:e.captureNavigation??l.captureNavigation,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...l.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function Re(e,t,n){let r=ze(n,t);if(r!==void 0)return r;let i=fe({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return q(n,t,i),i}function ze(e,t){if(e!==null)try{let n=e.getItem(G);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!J(i.mode)?void 0:i.mode}catch{return}}function q(e,t,n){if(e!==null)try{e.setItem(G,JSON.stringify({id:t,mode:n}))}catch{}}function J(e){return e===`full`||e===`buffer`||e===`off`}function Be(e){let t=typeof e==`object`&&e&&`stack`in e?e.stack:void 0;return typeof t==`string`?t:void 0}function Y(e,t){e.catch(e=>{Z(t,e)})}async function X(e,t){try{await e}catch(e){Z(t,e)}}function Z(e,t){try{let n=e?.(t);Ve(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Ve(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function He(){let e=globalThis;if(e[K]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,K,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[K]===t&&Reflect.deleteProperty(e,K))}}function Q(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function $(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function Ue(e){if(e==null)return`unhandledrejection`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);try{let t=JSON.stringify(e);return typeof t==`string`?t:Object.prototype.toString.call(e)}catch{return Object.prototype.toString.call(e)}}export{c as CHUNK_ENVELOPE_VERSION,s as CustomTag,i as EventType,a as IncrementalSource,o as MouseInteractions,Fe as startSessionReplay};
package/package.json CHANGED
@@ -24,7 +24,7 @@
24
24
  "rum",
25
25
  "rrweb"
26
26
  ],
27
- "version": "0.3.2",
27
+ "version": "0.3.4",
28
28
  "type": "module",
29
29
  "main": "./dist/index.cjs",
30
30
  "module": "./dist/index.js",