@pydantic/logfire-session-replay 0.7.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -7
- package/dist/{index-BxzwrVOz.d.cts → index-WIWZDir6.d.cts} +12 -1
- package/dist/{index-BxzwrVOz.d.ts → index-WIWZDir6.d.ts} +12 -1
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/integration.d.cts +1 -1
- package/dist/integration.d.ts +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -248,15 +248,46 @@ not retry them.
|
|
|
248
248
|
## Privacy
|
|
249
249
|
|
|
250
250
|
The recorder masks all rendered text and input values by default
|
|
251
|
-
(`maskAllText: true`, `maskAllInputs: true`).
|
|
251
|
+
(`maskAllText: true`, `maskAllInputs: true`). `maskAllInputs` also masks
|
|
252
|
+
hidden input values. `maskAllText` also masks the text-bearing attributes
|
|
253
|
+
`title`, `alt`, `aria-label`, `aria-description`, `aria-placeholder`,
|
|
254
|
+
`aria-roledescription`, `aria-valuetext`, `label`, `placeholder`, the value of
|
|
255
|
+
`button`, `submit`, and `reset` inputs, and `data-*` attributes. So that styled
|
|
256
|
+
states and themes replay correctly, `data-*` values that are empty, `true`, or
|
|
257
|
+
`false` are kept, as are the attributes `data-state`, `data-orientation`,
|
|
258
|
+
`data-side`, `data-align`, `data-placement`, `data-popper-placement`,
|
|
259
|
+
`data-disabled`, `data-highlighted`, `data-selected`, `data-checked`,
|
|
260
|
+
`data-active`, `data-headlessui-state`, `data-slot`, `data-variant`,
|
|
261
|
+
`data-size`, `data-theme`, and `data-bs-theme`. The recorder also disables canvas recording
|
|
252
262
|
and font collection, skips inlined images and cross-origin iframe recording,
|
|
253
263
|
omits nonvisual DOM metadata, throttles pointer, scroll, and media sampling,
|
|
254
264
|
never captures request or response bodies, and leaves console capture off
|
|
255
265
|
(`captureConsole: false`).
|
|
256
266
|
Network and navigation capture remain on, but query strings and fragments are
|
|
257
|
-
removed from rrweb page metadata
|
|
258
|
-
|
|
259
|
-
|
|
267
|
+
removed from rrweb page metadata, captured network/navigation URLs, and URL
|
|
268
|
+
attributes (`href`, `src`, `srcset`, `poster`, `data`, `xlink:href`, and
|
|
269
|
+
similar) by the default `redactUrlPatterns` value. URLs with an opaque scheme,
|
|
270
|
+
such as `mailto:`, `tel:`, `data:`, and `blob:`, keep only the scheme. An inline
|
|
271
|
+
`style` value that could reference a URL, because it contains `url`,
|
|
272
|
+
`image-set`, `src(`, or a backslash escape, is removed whole, so such elements
|
|
273
|
+
can lose background images or other styling in replays. This also applies when
|
|
274
|
+
only `transformUrl` is set, and not with `redactUrlPatterns: []` alone. Replay envelope `meta.urls` contains those same sanitized captured
|
|
275
|
+
URLs. Error messages and stacks in replay error events are limited to 1,024 and
|
|
276
|
+
8,192 characters.
|
|
277
|
+
|
|
278
|
+
Paths can also carry private values, such as reset tokens or email addresses.
|
|
279
|
+
Use `transformUrl` to rewrite them. It runs after `redactUrlPatterns` on page
|
|
280
|
+
metadata, navigation and network URLs, and DOM URL attributes, so it also
|
|
281
|
+
applies to `meta.urls`. URLs inside error messages, stacks, and console
|
|
282
|
+
arguments keep the built-in redaction only. When `transformUrl` throws, the
|
|
283
|
+
URL keeps the built-in redaction and `onError` receives the error.
|
|
284
|
+
|
|
285
|
+
```ts
|
|
286
|
+
startSessionReplay({
|
|
287
|
+
replayUrl: '/replay',
|
|
288
|
+
transformUrl: (url) => url.replace(/\/reset-password\/[^/]+/u, '/reset-password/:token'),
|
|
289
|
+
})
|
|
290
|
+
```
|
|
260
291
|
|
|
261
292
|
Use `blockSelector` to omit entire DOM subtrees. Set `maskAllText: false` only
|
|
262
293
|
when visible text recording is acceptable; `maskTextSelector` can then retain
|
|
@@ -265,9 +296,11 @@ arguments. An explicit `redactUrlPatterns: []` restores raw captured page,
|
|
|
265
296
|
network, and navigation URLs. `captureNetwork` and `captureNavigation` can
|
|
266
297
|
disable those capture classes completely.
|
|
267
298
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
299
|
+
Attribute masking applies only with `maskAllText: true`; a selective
|
|
300
|
+
`maskTextSelector` masks text nodes only. Masking does not scrub other DOM
|
|
301
|
+
attributes, stylesheet content, or arbitrary custom-event payloads. Avoid
|
|
302
|
+
placing secrets there, block affected subtrees, and sanitize custom events
|
|
303
|
+
before recording them.
|
|
271
304
|
|
|
272
305
|
## Sampling
|
|
273
306
|
|
|
@@ -127,8 +127,12 @@ interface SessionReplayConfig {
|
|
|
127
127
|
sessionSampleRate?: number;
|
|
128
128
|
/** Probability of buffering each otherwise-unsampled session for uncaught error promotion. */
|
|
129
129
|
onErrorSampleRate?: number;
|
|
130
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* Mask all rendered DOM text and text-bearing attributes such as `title`, `alt`, `aria-label`,
|
|
132
|
+
* `placeholder`, and `data-*`. Defaults to true.
|
|
133
|
+
*/
|
|
131
134
|
maskAllText?: boolean;
|
|
135
|
+
/** Mask the values of all inputs, including hidden inputs. Defaults to true. */
|
|
132
136
|
maskAllInputs?: boolean;
|
|
133
137
|
maskTextSelector?: string;
|
|
134
138
|
blockSelector?: string;
|
|
@@ -160,6 +164,13 @@ interface SessionReplayConfig {
|
|
|
160
164
|
captureGlobalErrors?: boolean;
|
|
161
165
|
ignoreUrlPatterns?: RegExp[];
|
|
162
166
|
redactUrlPatterns?: RegExp[];
|
|
167
|
+
/**
|
|
168
|
+
* Rewrites each page, navigation, network, and DOM attribute URL after `redactUrlPatterns` has
|
|
169
|
+
* removed its query and fragment, for example to replace a token or email in the path. URLs inside
|
|
170
|
+
* error messages, stacks, and console arguments keep the built-in redaction only. When it throws,
|
|
171
|
+
* the URL keeps the built-in redaction and `onError` receives the error.
|
|
172
|
+
*/
|
|
173
|
+
transformUrl?: (url: string) => string;
|
|
163
174
|
onError?: (error: unknown) => void;
|
|
164
175
|
fetchImpl?: typeof fetch;
|
|
165
176
|
now?: () => number;
|
|
@@ -127,8 +127,12 @@ interface SessionReplayConfig {
|
|
|
127
127
|
sessionSampleRate?: number;
|
|
128
128
|
/** Probability of buffering each otherwise-unsampled session for uncaught error promotion. */
|
|
129
129
|
onErrorSampleRate?: number;
|
|
130
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* Mask all rendered DOM text and text-bearing attributes such as `title`, `alt`, `aria-label`,
|
|
132
|
+
* `placeholder`, and `data-*`. Defaults to true.
|
|
133
|
+
*/
|
|
131
134
|
maskAllText?: boolean;
|
|
135
|
+
/** Mask the values of all inputs, including hidden inputs. Defaults to true. */
|
|
132
136
|
maskAllInputs?: boolean;
|
|
133
137
|
maskTextSelector?: string;
|
|
134
138
|
blockSelector?: string;
|
|
@@ -160,6 +164,13 @@ interface SessionReplayConfig {
|
|
|
160
164
|
captureGlobalErrors?: boolean;
|
|
161
165
|
ignoreUrlPatterns?: RegExp[];
|
|
162
166
|
redactUrlPatterns?: RegExp[];
|
|
167
|
+
/**
|
|
168
|
+
* Rewrites each page, navigation, network, and DOM attribute URL after `redactUrlPatterns` has
|
|
169
|
+
* removed its query and fragment, for example to replace a token or email in the path. URLs inside
|
|
170
|
+
* error messages, stacks, and console arguments keep the built-in redaction only. When it throws,
|
|
171
|
+
* the URL keeps the built-in redaction and `onError` receives the error.
|
|
172
|
+
*/
|
|
173
|
+
transformUrl?: (url: string) => string;
|
|
163
174
|
onError?: (error: unknown) => void;
|
|
164
175
|
fetchImpl?: typeof fetch;
|
|
165
176
|
now?: () => number;
|
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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:1e4,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:72e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,captureGlobalErrors:!0,redactUrlPatterns:[/.+/u]},s=/* @__PURE__ */ 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){
|
|
2
|
-
`).map(e=>{let i=r&&
|
|
3
|
-
`)}const x=[`log`,`info`,`warn`,`error`,`debug`],S=1024,C=()=>void 0;function ee(e,t={}){let n=[],r=A(t.onError);try{for(let t of x)typeof console[t]==`function`&&n.push(j(console,t,(n,i)=>function(...o){return i()&&k(e,a.Console,{level:t,args:o.slice(0,10).map(re)},r),n.apply(this,o)}));return M(n)}catch(e){throw N(n),e}}function te(e,t){let n=D(t),r={...n,onError:A(n.onError)},i=T(e,r);try{return M([i,E(e,r)])}catch(e){throw i(),e}}function w(e,t={redactUrlPatterns:[]}){let n=A(t.onError),r=r=>{let i=d(window.location.href,t.redactUrlPatterns??[],window.location.href);k(e,a.Navigation,{url:i,kind:r},n)},i=[];try{i.push(j(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(j(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)}),M(i)}catch(e){throw N(i),e}}function T(e,t){return typeof window.fetch==`function`?j(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=ie(i,o),u=ae(i);if(le(u,t.ignoreUrlPatterns))return s.call(this,i,o);let f=d(u,t.redactUrlPatterns,window.location.href),p=ce(o?.body);try{let n=await s.call(this,i,o);return r()&&k(e,a.Network,F({method:l,url:f,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:p,resBytes:oe(n.headers)}),t.onError),n}catch(n){throw r()&&k(e,a.Network,F({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}):C}function E(e,t){let n=window.XMLHttpRequest.prototype,r=/* @__PURE__ */ new WeakMap,i=[];try{return i.push(j(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return le(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(j(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=ce(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()&&k(e,a.Network,F({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,o)}catch(n){throw this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),this.removeEventListener(`loadend`,u),i()&&k(e,a.Network,F({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),M(i)}catch(e){throw N(i),e}}function D(e){return{...e,ignoreUrlPatterns:O(e.ignoreUrlPatterns),redactUrlPatterns:O(e.redactUrlPatterns)}}function O(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function k(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function A(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);ne(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function ne(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function j(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return C;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function M(e){let t=!1;return()=>{t||(t=!0,N(e))}}function N(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function re(e){if(e==null)return String(e);if(typeof e==`string`)return P(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return P(e.stack??`${e.name}: ${e.message}`);try{return P(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function P(e){if(e.length<=S)return e;let t=e.charCodeAt(1023),n=t>=55296&&t<=56319?1023:S;return`${e.slice(0,n)}...(+${String(e.length-n)} chars)`}function ie(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 F(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 ce(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 le(e,t){return u(e,t)}const ue=/* @__PURE__ */ new Set([`action`,`formaction`,`href`,`src`]);function de(t){let n=()=>{t.beforeUserActivity?.()},r={emit:e=>{t.emit(fe(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 fe(e,t){if(typeof e.data!=`object`||e.data===null)return e;let i=e.data;if(e.type===n.Custom)return pe(e,i,t);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=I(i,t);return a===i?e:{...e,data:a}}function pe(e,t,n){let r=t.payload;if(typeof r!=`object`||!r)return e;let i=r,o=window.location.href,s;if(t.tag===a.Error)s={...i},typeof i.message==`string`&&(s.message=b(i.message,n,o)),typeof i.source==`string`&&(s.source=d(i.source,n,o)),typeof i.stack==`string`&&(s.stack=b(i.stack,n,o,{stackTrace:!0}));else if(t.tag===a.Console&&Array.isArray(i.args))s={...i,args:i.args.map(e=>typeof e==`string`?b(e,n,o):e)};else return e;return{...e,data:{...t,payload:s}}}function I(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=I(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)?me(a,t):I(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function me(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(!ue.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 L(e){return typeof e==`object`&&e?e:void 0}function R(e){return typeof e==`string`&&e.length>0?e:void 0}function he(e){let t=L(e),n=R(t?.id);if(t===void 0||n===void 0)return;let r=R(t.name),i=R(t.email);return{id:n,...r===void 0?{}:{name:r},...i===void 0?{}:{email:i}}}function ge(e,t,o,s={},c){let l=1/0,u=0,d=0,f=0,p=0,m=!1,h=/* @__PURE__ */ new Set;for(let e of t){e.timestamp<l&&(l=e.timestamp),e.timestamp>u&&(u=e.timestamp);let t=L(e.data);if(e.type===n.FullSnapshot)m=!0;else if(e.type===n.Meta){let e=R(t?.href);e!==void 0&&h.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)&&d++}else e===r.Input&&f++}else if(e.type===n.Custom&&t!==void 0){let e=R(t.tag),n=L(t.payload);if(e===a.Error)p++;else if(e===a.Console)n?.level===`error`&&p++;else if(e===a.Navigation){let e=R(n?.url);e!==void 0&&h.add(e)}}}return{seq:e,firstTimestamp:l===1/0?0:l,lastTimestamp:u,eventCount:t.length,clickCount:d,keypressCount:f,errorCount:p,hasFullSnapshot:m,urls:[...h],...o!==void 0&&o.length>0?{distinctId:o}:{},...c===void 0?{}:{user:{...c}},...Object.keys(s).length===0?{}:{sessionAttributes:{...s}}}}function z(e=Date.now){let t=e(),n=new Uint8Array(/* @__PURE__ */ 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/256)&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 ve=`lf_session_replay`;var ye=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?B():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:z(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(ve);if(e!==null){let t=JSON.parse(e);if(be(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(ve,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 B(){try{return globalThis.sessionStorage??null}catch{return null}}function be(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)}var V=class extends Error{droppedSeqs;reason;seq;sessionId;status;constructor(e){super(xe(e),{cause:e.cause}),this.name=`ReplayUploadError`,this.droppedSeqs=Object.freeze([...e.droppedSeqs??[]]),this.reason=e.reason,this.seq=e.seq,this.sessionId=e.sessionId,this.status=e.status}};function xe(e){let t=e.seq===void 0?`replay chunk`:`replay chunk seq=${String(e.seq)}`,n=e.cause instanceof Error?`: ${e.cause.message}`:``;return`${t} ${e.reason}${n}`}const H=`lf_session_replay_seq`,U=1e4,Se=3e4,W=48e3,Ce=1e6,we=.9,Te={gzip:t.gzip,gzipSync:t.gzipSync};var Ee=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;queue=[];retainedBytes=0;activeUpload;drainPromise;draining=!1;pagehideUploads=/* @__PURE__ */ new Set;lifecycleFlights=/* @__PURE__ */ new Set;closed=!1;shuttingDown=!1;wakeRetry;retryAbort=new AbortController;deadlineAbort=new AbortController;resyncPending=!1;resyncTimer;lastResyncAt;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;takeFullSnapshot;sequenceRecord;sequenceRecordFailed=!1;awaitingBinding;bindingBufferIncomplete=!1;constructor(e,t,n,r=B(),i=Te,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.sequenceRecord=o.sequenceRecord,this.awaitingBinding=o.awaitBinding===!0,this.minimumDurationSatisfied=e.minSessionDurationMs===0,this.seq=o.sequenceRecord?.initialSeq??this.readPersistedSequence()??0,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=q(e);if(this.resyncPending){this.addDuringResync(e,t);return}if(this.refreshingMinimumSnapshot){this.buffer.push(e),this.pendingBytes+=t;return}let r=!this.minimumDurationSatisfied;if(this.mode===`buffer`||this.held||r||this.awaitingBinding){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:q(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.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=r,r&&this.finishMinimumBufferingEvent();return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=r,r&&this.finishMinimumBufferingEvent();return}}if(e.type===n.Meta&&this.mode===`full`&&this.buffer.length>0&&this.flushAndReport(),this.buffer.push(e),this.pendingBytes+=t,r&&this.minimumDurationReached()){this.flushAndReport();return}this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&e.type!==n.Meta?this.flushAndReport():this.scheduleFlush()}addDuringResync(e,t){if(e.type===n.Meta){this.buffer=[e],this.pendingBytes=t;return}if(e.type!==n.FullSnapshot)return;let r=this.buffer.length===1&&this.buffer[0]?.type===n.Meta?this.buffer[0]:void 0;this.buffer=r===void 0?[e]:[r,e],this.pendingBytes=t+(r===void 0?0:q(r)),this.resyncPending=!1,this.clearResyncTimer(),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={}){if(this.closed)return;if(e.keepalive!==!0)return this.flushInternal(e);this.activeUpload!==void 0&&(this.activeUpload.background=!0,this.activeUpload.pagehide=!0);let t=this.queue.filter(e=>(e!==this.activeUpload||!e.attempting)&&!this.pagehideUploads.has(e));for(let e of t)this.pagehideUploads.add(e),e.background=!0;this.wakeRetry?.();let n=this.trackLifecycle(Promise.all(t.map(async e=>this.finalAttempt(e))).then(()=>void 0));await Promise.all([this.flushInternal(e),n])}async flushInternal(e={}){if(this.closed||this.mode===`buffer`||this.held||this.awaitingBinding||this.buffer.length===0||!this.minimumDurationReached()||(this.clearScheduledFlush(),this.minimumBufferIncomplete&&!this.refreshMinimumBuffer()))return;this.minimumDurationSatisfied=!0;let t=this.buffer,n=this.pendingBytes;this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0;let r=this.sessionId,i=this.snapshotIdentity();if(e.keepalive===!0){let e=this.splitKeepaliveEventChunks(t,i,Math.max(0,W-this.reservedKeepaliveBytes)),n=this.allocateSeq(e.length);if(n===void 0)return;await this.trackLifecycle(this.deliverLifecycle(e,n,r,i));return}if(e.background===!0){let e=[];for(let n of this.splitKeepaliveEventChunks(t,i)){let t=this.enqueue(n.events,n.eventBytes,r,i,!0,n);if(t===void 0)break;e.push(t)}await Promise.all(e.map(async e=>e.done));return}await this.enqueue(t,n,r,i)?.done}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held||this.awaitingBinding||!this.minimumDurationReached()){this.discard(),await this.settleWithinDeadline([]);return}if(e.keepalive===!0){await this.flush(e),this.closed=!0,this.clearResyncTimer(),await this.settleWithinDeadline([]);return}let t=this.flushInternal();this.closed=!0,this.shuttingDown=!0,this.clearResyncTimer(),this.retryAbort.abort();let n=this.queue.filter(e=>e!==this.activeUpload&&!this.pagehideUploads.has(e)).map(async e=>this.finalAttempt(e));await this.settleWithinDeadline([t,...n])}discard(){this.started=!1,this.closed=!0,this.clearScheduledFlush(),this.clearResyncTimer(),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=>{G(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){G(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)}snapshotIdentity(){let e=this.snapshotUser(),t=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{t=this.config.getDistinctId()??this.config.distinctId}catch(e){G(this.config.onError,e)}else e!==void 0&&(t=e.id);return{distinctId:t,user:e}}createEnvelope(e,t,n){return{version:1,meta:ge(t,e,n.distinctId,this.sessionAttributes,n.user),events:e}}snapshotUser(){if(this.config.getUser!==void 0)try{return he(this.config.getUser())}catch(e){G(this.config.onError,e);return}}allocateSeq(e){let t=this.seq,n=this.sequenceRecord;if(n!==void 0){if(this.sequenceRecordFailed)return;if(!n.write(t+e)){this.sequenceRecordFailed=!0,this.discard();try{n.onFailure()}catch(e){G(this.config.onError,e)}return}}return this.seq+=e,this.saveSeq(this.sessionId,this.seq),t}enqueue(e,t,r,i,a=!1,o){let s=Math.max(2e6,2*this.config.maxBufferBytes);if(this.queue.length>0&&this.retainedBytes+t>s){G(this.config.onError,new V({cause:/* @__PURE__ */ Error(`replay upload queue is full`),reason:`not-sent`,seq:void 0,sessionId:r})),this.beginResync();return}let c=this.allocateSeq(1);if(c===void 0)return;let l=()=>void 0,u={body:void 0,done:new Promise(e=>{l=e}),events:e,hasFullSnapshot:e.some(e=>e.type===n.FullSnapshot),identity:i,reachedFetch:!1,attempting:!1,background:a,pagehide:!1,prepared:o,resolve:l,retainedBytes:t,seq:c,sessionId:r,settled:!1};return this.queue.push(u),this.retainedBytes+=t,this.draining||(this.draining=!0,this.drainPromise=this.drain()),u}async drain(){try{for(;!this.shuttingDown;){let e=this.queue.find(e=>!this.pagehideUploads.has(e));if(e===void 0)break;this.activeUpload=e;let t=await this.deliverQueued(e);this.activeUpload=void 0,this.settle(e,t)}}finally{this.activeUpload=void 0,this.draining=!1}}async deliverQueued(e){let t=await this.compressQueued(e);if(t!==void 0||e.settled)return t;let n=Date.now(),r;for(let t=1;;t++){if(this.pagehideUploads.has(e))return e.done.then(()=>void 0);let i=Se-(Date.now()-n);if(t>1&&i<=0)return Y(r,e.reachedFetch);let a=await this.attemptQueued(e,Math.min(U,i));if(a===void 0)return;r=a;let o=Ie(a,t,this.config.random);if(o===void 0||this.shuttingDown||e.pagehide||Date.now()-n+o>=Se)return Y(a,e.reachedFetch);await this.backoff(o)}}retainCompressedBody(e,t){this.retainedBytes+=t.byteLength-e.retainedBytes,e.retainedBytes=t.byteLength,e.body=t,e.events=void 0}compressQueuedSync(e){let n=e.prepared;if(e.prepared=void 0,!(e.body!==void 0||e.events===void 0||e.settled)){if(n?.body!==void 0&&n.events===e.events){this.retainCompressedBody(e,n.body);return}try{let n=(0,t.strToU8)(JSON.stringify(this.createEnvelope(e.events,e.seq,e.identity)));this.retainCompressedBody(e,this.compression.gzipSync(n));return}catch(e){return{cause:e,reason:`not-sent`}}}}async compressQueued(e){if(this.shuttingDown||e.background)return this.compressQueuedSync(e);if(e.body!==void 0||e.events===void 0)return;let n=e.events;try{let r=(0,t.strToU8)(JSON.stringify(this.createEnvelope(n,e.seq,e.identity))),i=await this.compressOrdinary(r);if(e.events!==n)return await this.compressQueued(e);e.settled||this.retainCompressedBody(e,i);return}catch(e){return{cause:e,reason:`not-sent`}}}async attemptQueued(e,t=U){let n=e.body;if(n!==void 0){e.attempting=!0;try{await this.send(this.prepareUpload(n,e.seq,e.sessionId,e.background),()=>{e.reachedFetch=!0},t);return}catch(e){return e}finally{e.attempting=!1}}}async finalAttempt(e){let t=e.background?this.compressQueuedSync(e):await this.compressQueued(e);if(t!==void 0){this.settle(e,t);return}let n=await this.attemptQueued(e);this.settle(e,n===void 0?void 0:Y(n,e.reachedFetch))}async trackLifecycle(e){this.lifecycleFlights.add(e);let t=()=>{this.lifecycleFlights.delete(e)};return e.then(t,t),e}async settleWithinDeadline(e){let t=Promise.all([...e,this.drainPromise,...this.lifecycleFlights]).then(()=>void 0,()=>void 0),n,r=new Promise(e=>{n=setTimeout(e,U)});if(await Promise.race([t,r]),clearTimeout(n),this.shuttingDown){this.deadlineAbort.abort(/* @__PURE__ */ Error(`replay upload did not finish before shutdown`));for(let e of[...this.queue])this.settle(e,{cause:/* @__PURE__ */ Error(`replay upload did not finish before shutdown`),reason:e.reachedFetch?`unconfirmed`:`not-sent`})}}settle(e,t){if(e.settled)return;e.settled=!0,this.pagehideUploads.delete(e),this.retainedBytes-=e.retainedBytes;let n=this.queue.indexOf(e);n>=0&&this.queue.splice(n,1),e.body=void 0,e.events=void 0,e.resolve(),t!==void 0&&this.handleSequencedLoss(e.seq,e.sessionId,t)}handleSequencedLoss(e,t,n){let r=[];if(!this.shuttingDown){let t=!1;for(let n of[...this.queue])if(!(n.seq<e)){if(n.events===void 0){if(n.hasFullSnapshot){t=!0;break}continue}if(n.hasFullSnapshot){let e=Ae(n.events),r=je(e);this.retainedBytes+=r-n.retainedBytes,n.retainedBytes=r,n.events=e,t=!0;break}r.push(n.seq),this.settle(n,void 0)}!t&&!this.trimBufferToAnchor()&&this.beginResync()}G(this.config.onError,new V({cause:n.cause,droppedSeqs:r,reason:n.reason,seq:e,sessionId:t,status:n.status}))}trimBufferToAnchor(){return this.buffer.some(e=>e.type===n.FullSnapshot)?(this.buffer=Ae(this.buffer),this.pendingBytes=je(this.buffer),!0):!1}beginResync(){this.closed||(this.resyncPending=!0,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.clearScheduledFlush(),this.scheduleResyncSnapshot())}scheduleResyncSnapshot(){if(this.resyncTimer!==void 0||this.closed)return;let e=this.lastResyncAt===void 0?0:Math.max(0,this.lastResyncAt+6e4-this.config.now());this.resyncTimer=setTimeout(()=>{this.resyncTimer=void 0,this.takeResyncSnapshot()},e)}takeResyncSnapshot(){if(this.resyncPending&&!this.closed&&this.takeFullSnapshot!==void 0){this.lastResyncAt=this.config.now();try{this.takeFullSnapshot()}catch(e){G(this.config.onError,e),this.scheduleResyncSnapshot();return}this.isResyncPending()&&(G(this.config.onError,/* @__PURE__ */ Error(`replay resync snapshot produced no full snapshot`)),this.scheduleResyncSnapshot())}}isResyncPending(){return this.resyncPending}clearResyncTimer(){this.resyncTimer!==void 0&&(clearTimeout(this.resyncTimer),this.resyncTimer=void 0)}async backoff(e){let t=this.retryAbort.signal;t.aborted||await new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),this.wakeRetry===r&&(this.wakeRetry=void 0),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r),this.wakeRetry=r})}prepareUpload(e,t,n,r){let i=r&&this.reservedKeepaliveBytes+e.byteLength<=W?e.byteLength:0;return this.reservedKeepaliveBytes+=i,{body:e,seq:t,sessionId:n,reservedBytes:i,requestKeepalive:i>0}}splitKeepaliveEventChunks(e,n,r=1/0){let i=e.map(q),a=[],o=r,s,c=0;for(;c<e.length;){let l=Math.min(W,o);if(l<4800){a.push({events:e.slice(c),eventBytes:J(i,c,e.length)});break}let u=this.seq+a.length,d=s===void 0?Ce:Math.min(Ce,l*s*we),f=Me(i,c,d);for(;;){let d=e.slice(c,f),p=J(i,c,f),m;try{m=this.compression.gzipSync((0,t.strToU8)(JSON.stringify(this.createEnvelope(d,u,n))))}catch{a.push({events:d,eventBytes:p}),o=Number.isFinite(r)?0:o;break}if(s=p/Math.max(1,m.byteLength),m.byteLength<=l){a.push({events:d,eventBytes:p,body:m}),o-=m.byteLength;break}if(f-c===1){Number.isFinite(r)?(a.push({events:e.slice(c),eventBytes:J(i,c,e.length)}),f=e.length):a.push({events:d,eventBytes:p,body:m});break}f=Math.max(c+1,Math.min(f-1,Me(i,c,l*s*we)))}c=f}return a}async deliverLifecycle(e,n,r,i){let a=[];for(let o=0;o<e.length;o++){let s=e[o];if(s===void 0){a.push(void 0);continue}try{a.push({body:s.body??this.compression.gzipSync((0,t.strToU8)(JSON.stringify(this.createEnvelope(s.events,n+o,i)))),requestKeepalive:!1,reservedBytes:0,seq:n+o,sessionId:r})}catch(e){this.handleSequencedLoss(n+o,r,{cause:e,reason:`not-sent`}),a.push(void 0)}}let o=!0,s=Math.max(0,W-this.reservedKeepaliveBytes);for(let e of a){if(e===void 0){o=!1;continue}o&&e.body.byteLength<=s?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,s-=e.reservedBytes):o=!1}await Promise.all(a.map(async e=>{if(e===void 0)return;let t=!1;try{await this.send(e,()=>{t=!0})}catch(n){this.handleSequencedLoss(e.seq,e.sessionId,Y(n,t))}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await Ne(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async send(e,t,n=U){let r,i,a,o=new AbortController,s=setTimeout(()=>{o.abort(/* @__PURE__ */ Error(`replay upload timed out after ${String(n)}ms`))},n),c=this.deadlineAbort.signal,l=()=>{o.abort(c.reason)};c.addEventListener(`abort`,l);try{let n=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,s=await ke(this.getUploadHeaders(),o.signal);t();let c=this.config.fetchImpl(n,{method:`POST`,headers:s,body:e.body.slice(),keepalive:e.requestKeepalive,signal:o.signal});r=!0;let l=await c;if(i=!0,a=await Pe(l),!l.ok){let e=l.status===429||l.status===503?Le(l.headers.get(`retry-after`),Date.now()):void 0;throw new K(l.status,e)}}finally{clearTimeout(s),c.removeEventListener(`abort`,l),e.reservedBytes>0&&(r!==!0||i!==!0||a===!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 Oe(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`}}canResumeSequence(){return this.awaitingBinding?!0:this.readPersistedSequence()===this.seq}isAwaitingBinding(){return this.awaitingBinding}bind(e){this.awaitingBinding&&!this.closed&&(this.sequenceRecord=e,this.seq=e.initialSeq,this.awaitingBinding=!1,this.bindingBufferIncomplete&&(this.bindingBufferIncomplete=!1,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.takeFullSnapshot?.()),!(this.mode!==`full`||this.held||this.buffer.length===0)&&(this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()))}readPersistedSequence(){if(this.storage!==null)try{let e=this.storage.getItem(H);if(e===null)return;let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return n.id===this.sessionId&&typeof n.seq==`number`&&Number.isSafeInteger(n.seq)&&n.seq>=0?n.seq:void 0}catch{return}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(H,JSON.stringify({id:e,seq:t}))}catch{}}};function G(e,t){try{let n=e?.(t);De(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function De(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var K=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 Oe(e){return typeof e==`function`?e():e}async function ke(e,t){if(t.aborted)throw t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e instanceof Error?e:Error(String(e)))})})}function q(e){try{return(0,t.strToU8)(JSON.stringify(e)).byteLength}catch{return 0}}function Ae(e){let t=e.findIndex(e=>e.type===n.FullSnapshot);if(t<0)return e;let r=t>0&&e[t-1]?.type===n.Meta?t-1:t;return e.slice(r)}function je(e){return e.reduce((e,t)=>e+q(t),0)}function J(e,t,n){let r=0;for(let i=t;i<n;i++)r+=e[i]??0;return r}function Me(e,t,n){let r=t+1,i=e[t]??0;for(;r<e.length&&i+(e[r]??0)<=n;)i+=e[r]??0,r++;return r}async function Ne(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(/* @__PURE__ */ 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 Pe(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function Fe(e){return e===408||e===425||e===429||e>=500}function Ie(e,t,n){if(e instanceof K&&!Fe(e.status))return;let r=Math.min(8e3,500*2**(t-1)),i=Math.round(r*(1-.5*n())),a=e instanceof K?e.retryAfter:void 0;return a===void 0?i:Math.max(a,i)}function Y(e,t){let n=e instanceof K?e.status:void 0;return n!==void 0&&!Fe(n)?{cause:e,reason:`rejected`,status:n}:{cause:e,reason:t?`unconfirmed`:`not-sent`,status:n}}function Le(e,t){if(e===null)return;let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?e*1e3:void 0}let r=Ve(n,t);return r===void 0?void 0:Math.max(0,r-t)}const Re=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],ze=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Be=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function Ve(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 X(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),X(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 X(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function X(e,t,n,r,i,a,o){let s=Number(t),c=Re.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=/* @__PURE__ */ 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=ze.indexOf(e),h=Be.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const He=`lf_session_replay_recording`,Ue=`lf_session_replay_recording_owner`,We=72e5;var Ge=class{state;resumed=!1;storage;owner;now;maxDurationMs;readOpenerState;constructor(e,t,n,r=()=>null){this.storage=e,this.now=t,this.owner=z(t),this.maxDurationMs=Math.min(n,We),this.readOpenerState=r;try{e?.getItem(`lf_session_replay_recording_owner`)===null&&(this.state=this.readResumableState()),e?.setItem(Ue,this.owner),e?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.storage=null,this.state=void 0)}catch{this.storage=null,this.state=void 0}this.resumed=this.state!==void 0}get(e){return this.state!==void 0&&this.isCurrent(this.state.id,e)?this.state.id:this.replace(e)}candidate(e){return{id:this.get(e),resumed:this.resumed}}replace(e){this.state={id:z(this.now),rumSessionId:e,startedAt:this.now()},this.resumed=!1;try{this.storage?.setItem(He,JSON.stringify(this.state))}catch{}return this.state.id}isCurrent(e,t){let n=this.state;if(n===void 0)return!1;let r=this.now();return n.id===e&&n.rumSessionId===t&&r>=n.startedAt&&r-n.startedAt<this.maxDurationMs}release(){try{this.storage?.getItem(`lf_session_replay_recording_owner`)===this.owner&&this.storage.removeItem(Ue)}catch{}}resume(){try{this.state=this.storage?.getItem(`lf_session_replay_recording_owner`)===null?this.readResumableState():void 0,this.storage?.setItem(Ue,this.owner),this.storage?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.state=void 0,this.storage=null)}catch{this.state=void 0,this.storage=null}this.resumed=this.state!==void 0}readResumableState(){let e=this.storage?.getItem(He),t=this.storage?.getItem(H);if(e==null||t==null)return;let n=null;try{n=this.readOpenerState()}catch{}if(n!==e)return Ke(e,t)}};function Ke(e,t){let n=JSON.parse(e),r=JSON.parse(t);if(typeof n!=`object`||!n||typeof r!=`object`||!r)return;let i=n,a=r;if(!(typeof i.id!=`string`||i.id.length===0||typeof i.rumSessionId!=`string`||typeof i.startedAt!=`number`||!Number.isFinite(i.startedAt)||a.id!==i.id||typeof a.seq!=`number`||!Number.isSafeInteger(a.seq)||a.seq<0))return{id:i.id,rumSessionId:i.rumSessionId,startedAt:i.startedAt}}function qe(){try{if(typeof window>`u`||!window.isSecureContext)return;let e=globalThis.navigator?.locks;return typeof e?.request==`function`?e:void 0}catch{return}}async function Je(e,t,n,r=1e3){return n.aborted?{kind:`aborted`}:new Promise(i=>{let a=!1,o=e=>{a||(a=!0,clearTimeout(c),n.removeEventListener(`abort`,l),i(e))},s=new AbortController,c=setTimeout(()=>{s.abort(),o({kind:`timeout`})},r),l=()=>{s.abort(),o({kind:`aborted`})};n.addEventListener(`abort`,l);let u=!1;try{e.request(`logfire-session-replay:${t}`,{mode:`exclusive`,signal:s.signal},async()=>{if(u=!0,a||n.aborted){o({kind:`aborted`});return}await new Promise(e=>{o({kind:`held`,lock:{release:e}})})}).catch(()=>{u||o({kind:`aborted`})})}catch{o({kind:`aborted`})}})}function Ye(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Xe(e){let t=e.random??Math.random;return t()<Ye(e.sessionSampleRate)?`full`:t()<Ye(e.onErrorSampleRate)?`buffer`:`off`}const Ze=`lf_session_replay_seq:`,Qe=`lf_session_replay_probe`;var $e=class{storage;now;constructor(e,t){this.storage=e,this.now=t}read(e){try{return nt(this.storage.getItem(tt(e)))?.seq}catch{return}}write(e,t){try{return this.storage.setItem(tt(e),JSON.stringify({seq:t,at:this.now()})),this.read(e)===t}catch{return!1}}prune(e){try{let t=this.now()-e,n=[];for(let e=0;e<this.storage.length;e+=1){let r=this.storage.key(e);if(r===null||!r.startsWith(Ze))continue;let i=nt(this.storage.getItem(r));(i===void 0||i.at<t)&&n.push(r)}for(let e of n)this.storage.removeItem(e)}catch{}}};function et(){try{let e=globalThis.localStorage;if(e===void 0)return null;e.setItem(Qe,`1`);let t=e.getItem(Qe)===`1`;return e.removeItem(Qe),t?e:null}catch{return null}}function tt(e){return`${Ze}${e}`}function nt(e){if(e!==null)try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return typeof n.seq!=`number`||!Number.isSafeInteger(n.seq)||n.seq<0||typeof n.at!=`number`||!Number.isFinite(n.at)?void 0:{seq:n.seq,at:n.at}}catch{return}}const rt=/^[a-z][a-z0-9_]{0,63}$/u;function it(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function at(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(!rt.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`&&it(r,200))&&(Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:r,writable:!0}),o+=1,o===20))break}return Object.freeze(a)}const ot={mode:`off`,recording:!1,getSessionId:()=>``,captureError:()=>void 0,getRecordingId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},st=`lf_session_replay_mode`,Z=Symbol.for(`@pydantic/logfire-session-replay/controller`);function ct(e){if(typeof window>`u`||typeof document>`u`)return ot;let t=St();try{let n=ut(e),r=new ye({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Q(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=B(),s=new Ge(o,n.now,n.maxSessionDurationMs,()=>window.opener?.sessionStorage.getItem(`lf_session_replay_recording`)??null),c=dt(n.now),l=a(!1),u=s.get(l),d,f=!1,p=!1,m=0,h=!0,g=Promise.resolve(),_=Promise.resolve(),v,y,b,x=!1,S=e=>{y!==void 0&&(e===void 0||y.recordingId===e)&&(y.lock.release(),y=void 0)},C=(e,t,r=!t,i=!1)=>{let c=ft(n,e,o);if(!(c===`off`||f||p||d!==void 0||e!==l))try{x=i&&s.candidate(e).resumed;let t=u;d=lt({config:n,getSessionId:a,mode:c,onSessionChanged:E,samplingModeStorage:o,sessionId:e,recordingId:t,isCurrentRecording:()=>s.isCurrent(t,a(!1)),holdUntilActivity:r,awaitBinding:i})}catch(e){if(d=void 0,t)throw e;Q(n.onError,e)}},ee=(e,t,n)=>({initialSeq:n,write:n=>e.records.write(t,n),onFailure:()=>{queueMicrotask(()=>{!f&&u===t&&(s.replace(l),E(l,!1))})}}),te=async(e,t,r)=>{b?.abort();let i=new AbortController;b=i;let a=()=>i.signal.aborted||f||p||m!==r||l!==t,o=s.candidate(t);u=o.id;let c=()=>{o={id:s.replace(t),resumed:!1},u=o.id};for(let t=0;t<2;t+=1){let t=await Je(e.locks,o.id,i.signal);if(t.kind===`aborted`)return;if(t.kind===`timeout`){c();continue}if(a()||u!==o.id){t.lock.release();return}let n;if(o.resumed?n=e.records.read(o.id):e.records.write(o.id,0)&&(n=0),n===void 0){t.lock.release(),c();continue}return y={recordingId:o.id,lock:t.lock},{recordingId:o.id,sequenceRecord:ee(e,o.id,n)}}Q(n.onError,/* @__PURE__ */ Error(`logfire session replay: could not claim a replay recording`))},w=async(e,t,r,i)=>{try{let n=await te(e,t,r),a=!f&&!p&&m===r&&l===t;if(n===void 0){a&&d?.transport.isAwaitingBinding()===!0&&(d.discard(),d=void 0);return}if(!a){S(n.recordingId);return}if(d!==void 0&&d.recordingId!==n.recordingId&&(d.discard(),d=void 0,C(t,!1,i,!0)),d===void 0||d.recordingId!==n.recordingId){S(n.recordingId);return}x=!1,d.transport.bind(n.sequenceRecord)}catch(e){Q(n.onError,e)}},T=async(e,t,n)=>{C(e,!1,n,c!==void 0),c!==void 0&&d!==void 0&&await w(c,e,t,n)},E=(e,t=!0)=>{if(f||p)return;let r=s.get(e);if(e===l&&r===u)return;let i=u;l=e,u=r,b?.abort();let a=d;d=void 0;let o=a?.deactivate()??Promise.resolve(),c=m;g=g.then(async()=>{await bt(o,n.onError),S(i),!f&&m===c&&l===e&&u===r&&await T(e,c,t)})},D;try{if(c===void 0)C(l,!0);else if(c.records.prune(We),C(l,!0,!1,!0),d!==void 0){let e=l,t=m;g=g.then(async()=>w(c,e,t,!1))}D=setInterval(()=>{E(a(!1))},1e3)}catch(e){throw d?.discard(),d=void 0,b?.abort(),S(),s.release(),e}let O=()=>{p=!0,m+=1,b?.abort();let e=d;d=void 0;let t=e?.deactivate(!0)??Promise.resolve();S(),_=Promise.all([_,g,bt(t,n.onError)]).then(()=>void 0),g=Promise.resolve(),h=e?.transport.canResumeSequence()??h,h&&s.release()},k=e=>{if(!e.persisted||f)return;d?.discard(),d=void 0;let t=m;g=g.then(async()=>{let e=()=>f||m!==t;if(e())return;let n=new AbortController;b=n;let r,i=!1;if(c!==void 0){let e=await Je(c.locks,u,n.signal);if(e.kind===`aborted`)return;e.kind===`held`&&(r=e.lock),i=e.kind===`timeout`}else await new Promise(e=>{setTimeout(e,0)});try{if(e())return;p=!1,s.resume(),l=a(!1),u=i?s.replace(l):s.get(l),h=!0}finally{r?.release()}await T(l,t,!1)})};return window.addEventListener(`pagehide`,O),window.addEventListener(`pageshow`,k),{get mode(){try{return d?.transport.getMode()??`off`}catch(e){return Q(n.onError,e),`off`}},get recording(){try{return d!==void 0}catch(e){return Q(n.onError,e),!1}},getSessionId:()=>a(!1),captureError:(e,t)=>{try{d?.captureError(e,t)}catch(e){Q(n.onError,e)}},getRecordingId:()=>d===void 0||x&&d.transport.isAwaitingBinding()?``:s.isCurrent(d.recordingId,a(!1))?d.recordingId:``,flush:async()=>{try{await g,await d?.transport.flush()}catch(e){Q(n.onError,e)}},stop:async()=>(v??=(async()=>{f=!0,m+=1,b?.abort(),clearInterval(D),window.removeEventListener(`pagehide`,O),window.removeEventListener(`pageshow`,k);let e=d;d=void 0,await bt(e?.deactivate()??Promise.resolve(),n.onError),await g,await _,r.flushPendingStorage(),h=e?.transport.canResumeSequence()??h,h&&s.release(),S(),t()})(),v)}}catch(e){throw t(),e}}function lt(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:o,samplingModeStorage:s,sessionId:l,recordingId:u,isCurrentRecording:d,awaitBinding:f}=e,p=at(t.getSessionAttributes,e=>{Q(t.onError,e)}),m,h=new Ee(t,u,i,void 0,void 0,p,{holdUntilActivity:r,takeFullSnapshot:()=>{m.takeFullSnapshot()},awaitBinding:f}),g=[],_=!0,v=()=>_,y;try{m=de({beforeUserActivity:()=>{if(_&&h.isHeld())try{let e=n(!0);if(e!==l||!d()){o(e,!1);return}h.releaseHeld(()=>{m.takeFullSnapshot()})}catch(e){Q(t.onError,e)}},emit:e=>{if(_)try{let t=n(c(e));if(t!==l||!d()){o(t,!1);return}h.add(e)}catch(e){Q(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:Math.max(3e5,t.minSessionDurationMs),redactUrlPatterns:t.redactUrlPatterns}),g.push(()=>{m.stop()});let e=(e,n)=>{if(_)try{m.addCustomEvent(e,n)}catch(e){Q(t.onError,e)}},r=n=>{v()&&(h.releaseHeld(()=>{m.takeFullSnapshot()}),e(a.Error,n),v()&&h.getMode()===`buffer`&&(mt(s,l,`full`),yt(h.triggerFlush(),t.onError)))},f=/* @__PURE__ */ new WeakSet,p=e=>typeof e!=`object`||!e||!f.has(e)&&(f.add(e),!0),b=(e,t)=>{if(p(e)){let n=Ct(gt(e),void 0,_t(e));r(typeof t?.timestamp==`number`?{...n,timestamp:t.timestamp}:n)}},x=e=>{e instanceof ErrorEvent&&p(e.error)&&r(Ct(e.message,e.filename,_t(e.error)))},S=e=>{b(e.reason)},C=()=>{document.visibilityState===`hidden`&&yt(h.flush({background:!0}),t.onError)},T=()=>{yt(h.flush({keepalive:!0}),t.onError)};return t.captureGlobalErrors&&(window.addEventListener(`error`,x,!0),g.push(()=>{window.removeEventListener(`error`,x,!0)}),window.addEventListener(`unhandledrejection`,S,!0),g.push(()=>{window.removeEventListener(`unhandledrejection`,S,!0)})),document.addEventListener(`visibilitychange`,C),g.push(()=>{document.removeEventListener(`visibilitychange`,C)}),window.addEventListener(`pagehide`,T),g.push(()=>{window.removeEventListener(`pagehide`,T)}),t.captureConsole&&g.push(ee(e,{onError:t.onError})),t.captureNetwork&&g.push(te(e,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&g.push(w(e,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),h.start(),{sessionId:l,recordingId:u,transport:h,captureError:b,deactivate:async(e=!1)=>(y??=(async()=>{let t=h.shutdown({keepalive:e});_=!1,$(g),await t})(),y),discard:()=>{_=!1,$(g),h.discard()}}}catch(e){throw _=!1,$(g),h.discard(),e}}function ut(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,getUser:e.getUser,captureConsole:e.captureConsole??o.captureConsole,captureNetwork:e.captureNetwork??o.captureNetwork,captureNavigation:e.captureNavigation??o.captureNavigation,captureGlobalErrors:e.captureGlobalErrors??o.captureGlobalErrors,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...o.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function dt(e){let t=qe();if(t===void 0)return;let n=et();return n===null?void 0:{locks:t,records:new $e(n,e)}}function ft(e,t,n){let r=pt(n,t);if(r!==void 0)return r;let i=Xe({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return mt(n,t,i),i}function pt(e,t){if(e!==null)try{let n=e.getItem(st);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!ht(i.mode)?void 0:i.mode}catch{return}}function mt(e,t,n){if(e!==null)try{e.setItem(st,JSON.stringify({id:t,mode:n}))}catch{}}function ht(e){return e===`full`||e===`buffer`||e===`off`}function gt(e){return wt(vt(e,`message`)??e)}function _t(e){let t=vt(e,`stack`);return typeof t==`string`?t:void 0}function vt(e,t){try{return typeof e==`object`&&e&&t in e?e[t]:void 0}catch{return}}function yt(e,t){e.catch(e=>{Q(t,e)})}async function bt(e,t){try{await e}catch(e){Q(t,e)}}function Q(e,t){try{let n=e?.(t);xt(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function xt(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function St(){let e=globalThis;if(e[Z]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,Z,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[Z]===t&&Reflect.deleteProperty(e,Z))}}function $(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function Ct(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function wt(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{return Object.prototype.toString.call(e)}catch{return`[object Object]`}}exports.CHUNK_ENVELOPE_VERSION=1,exports.CustomTag=a,exports.EventType=n,exports.IncrementalSource=r,exports.MouseInteractions=i,exports.ReplayUploadError=V,exports.startSessionReplay=ct;
|
|
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:1e4,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:72e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,captureGlobalErrors:!0,redactUrlPatterns:[/.+/u]},s=/* @__PURE__ */ 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,r){let i=u(e,t)?p(e,n):e;return r===void 0?i:f(i,r)}function f(e,t){try{let n=t(e);return typeof n==`string`?n:e}catch{return e}}function p(e,t){try{let n=new URL(e,t);return n.origin===`null`||n.protocol===`blob:`?n.protocol:`${n.origin}${n.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const m=/https?:\/\/[^\s"<>`]+/giu,h=/:\d+:\d+\)?$/u,g=/(?=https?:\/\/)/iu,_=/^\s*at\s/u;function v(e,t){return(t?h.exec(e)?.[0]:void 0)??y(e)}function y(e){let t=e.length;for(;t>0&&(e[t-1]===`)`||e[t-1]===`'`);)t--;return e.slice(t)}function b(e,t,n){return u(e,t)||e.split(g).some(e=>u(e,t))?p(e,n):e}function x(e,t,n,{stackTrace:r=!1}={}){return t.length===0?e:e.split(`
|
|
2
|
+
`).map(e=>{let i=r&&_.test(e);return e.replace(m,(a,o)=>{let s=v(a,i||r&&e[o-1]===`@`);return`${b(a.slice(0,a.length-s.length),t,n)}${s}`})}).join(`
|
|
3
|
+
`)}function S(e,t){let n=``,r=0;for(;r<e.length;){let i=r;for(;r<e.length&&/[\s,]/u.test(e[r]??``);)r++;if(n+=e.slice(i,r),r>=e.length)break;let a=r;for(;r<e.length&&!/\s/u.test(e[r]??``);)r++;let o=r;for(;o>a&&e[o-1]===`,`;)o--;if(n+=t(e.slice(a,o))+e.slice(o,r),o<r)continue;let s=r;for(;r<e.length&&e[r]!==`,`;)r++;n+=e.slice(s,r)}return n}const C=/\\|url|image-set|src\(/iu;function w(e){return C.test(e)}function T(e,t){if(e.length<=t)return[e,0];let n=e.charCodeAt(t-1),r=n>=55296&&n<=56319?t-1:t;return[e.slice(0,r),e.length-r]}function E(e){return e===0?``:`...(+${String(e)} chars)`}function D(e,t){let[n,r]=T(e,t);return`${n}${E(r)}`}const O=[`log`,`info`,`warn`,`error`,`debug`],k=()=>void 0;function A(e,t={}){let n=[],r=ae(t.onError);try{for(let t of O)typeof console[t]==`function`&&n.push(N(console,t,(n,i)=>function(...o){return i()&&M(e,a.Console,{level:t,args:o.slice(0,10).map(se)},r),n.apply(this,o)}));return P(n)}catch(e){throw F(n),e}}function j(e,t){let n=re(t),r={...n,onError:ae(n.onError)},i=te(e,r);try{return P([i,ne(e,r)])}catch(e){throw i(),e}}function ee(e,t={redactUrlPatterns:[]}){let n=ae(t.onError),r=r=>{let i=d(window.location.href,t.redactUrlPatterns??[],window.location.href,t.transformUrl);M(e,a.Navigation,{url:i,kind:r},n)},i=[];try{i.push(N(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(N(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)}),P(i)}catch(e){throw F(i),e}}function te(e,t){return typeof window.fetch==`function`?N(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=ce(i,o),u=le(i);if(pe(u,t.ignoreUrlPatterns))return s.call(this,i,o);let f=d(u,t.redactUrlPatterns,window.location.href,t.transformUrl),p=fe(o?.body);try{let n=await s.call(this,i,o);return r()&&M(e,a.Network,L({method:l,url:f,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:p,resBytes:ue(n.headers)}),t.onError),n}catch(n){throw r()&&M(e,a.Network,L({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}):k}function ne(e,t){let n=window.XMLHttpRequest.prototype,r=/* @__PURE__ */ new WeakMap,i=[];try{return i.push(N(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return pe(s,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:a.toUpperCase(),url:d(s,t.redactUrlPatterns,window.location.href,t.transformUrl),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(N(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=fe(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()&&M(e,a.Network,L({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:de(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()&&M(e,a.Network,L({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),P(i)}catch(e){throw F(i),e}}function re(e){return{...e,ignoreUrlPatterns:ie(e.ignoreUrlPatterns),redactUrlPatterns:ie(e.redactUrlPatterns)}}function ie(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function M(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function ae(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);oe(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function oe(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function N(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return k;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function P(e){let t=!1;return()=>{t||(t=!0,F(e))}}function F(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function se(e){if(e==null)return String(e);if(typeof e==`string`)return I(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return I(e.stack??`${e.name}: ${e.message}`);try{return I(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function I(e){return D(e,1024)}function ce(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function le(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function ue(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 de(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 L(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 fe(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 pe(e,t){return u(e,t)}const me=/* @__PURE__ */ new Set([`action`,`background`,`cite`,`data`,`formaction`,`href`,`poster`,`rr_src`,`src`,`xlink:href`]),he=/* @__PURE__ */ new Set([`imagesrcset`,`srcset`]),ge=/* @__PURE__ */ new Set([`alt`,`aria-description`,`aria-label`,`aria-placeholder`,`aria-roledescription`,`aria-valuetext`,`label`,`placeholder`,`title`]),_e=/* @__PURE__ */ new Set([`data-active`,`data-align`,`data-bs-theme`,`data-checked`,`data-disabled`,`data-headlessui-state`,`data-highlighted`,`data-orientation`,`data-placement`,`data-popper-placement`,`data-selected`,`data-side`,`data-size`,`data-slot`,`data-state`,`data-theme`,`data-variant`]),ve=/* @__PURE__ */ new Set([``,`false`,`true`]),ye=/* @__PURE__ */ new Set([`button`,`reset`,`submit`]),be={color:!0,date:!0,"datetime-local":!0,email:!0,hidden:!0,month:!0,number:!0,password:!0,range:!0,search:!0,select:!0,tel:!0,text:!0,textarea:!0,time:!0,url:!0,week:!0};function xe(t){let n=()=>{t.beforeUserActivity?.()},r={maskTextAttributes:t.maskAllText,patterns:t.redactUrlPatterns,transformUrl:t.transformUrl},i={emit:e=>{t.emit(Se(e,r))},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.maskAllInputs?i.maskInputOptions=be:i.maskAllInputs=!1,t.maskAllText?i.maskTextSelector=`*`:t.maskTextSelector!==void 0&&t.maskTextSelector.length>0&&(i.maskTextSelector=t.maskTextSelector),t.blockSelector!==void 0&&t.blockSelector.length>0&&(i.blockSelector=t.blockSelector),t.checkoutEveryNms!==void 0&&t.checkoutEveryNms>0&&(i.checkoutEveryNms=t.checkoutEveryNms);let a=(0,e.record)(i);if(a===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{a()},addCustomEvent:(t,n)=>{e.record.addCustomEvent(t,n)},takeFullSnapshot:()=>{e.record.takeFullSnapshot(!0)}}}function Se(e,t){if(typeof e.data!=`object`||e.data===null)return e;let i=e.data;if(e.type===n.Custom)return Ce(e,i,t.patterns);if(e.type===n.Meta){if(typeof i.href!=`string`)return e;let n=d(i.href,t.patterns,window.location.href,t.transformUrl);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=R(i,t);return a===i?e:{...e,data:a}}function Ce(e,t,n){let r=t.payload;if(typeof r!=`object`||!r)return e;let i=r,o=window.location.href,s;if(t.tag===a.Error)s={...i},typeof i.message==`string`&&(s.message=we(i.message,1024,e=>x(e,n,o))),typeof i.source==`string`&&(s.source=d(i.source,n,o)),typeof i.stack==`string`&&(s.stack=we(i.stack,8192,e=>x(e,n,o,{stackTrace:!0})));else if(t.tag===a.Console&&Array.isArray(i.args))s={...i,args:i.args.map(e=>typeof e==`string`?x(e,n,o):e)};else return e;return{...e,data:{...t,payload:s}}}function we(e,t,n){let[r,i]=T(e,t);return`${n(r)}${E(i)}`}function R(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=R(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)?Te(a,t):R(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function Te(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=t.maskTextAttributes&&typeof n.type==`string`&&ye.has(n.type.toLowerCase()),i=!1,a={};for(let[e,o]of Object.entries(n)){let n=e.toLowerCase(),s=r&&n===`value`?ke(o):Ee(n,o,t);s!==o&&(i=!0),a[e]=s}return i?a:e}function Ee(e,t,n){let r=e=>d(e,n.patterns,window.location.href,n.transformUrl);return e===`style`?n.patterns.length>0||n.transformUrl!==void 0?Oe(t):t:typeof t==`string`?me.has(e)?r(t):he.has(e)?S(t,r):n.maskTextAttributes&&De(e,t)?ke(t):t:t}function De(e,t){return ge.has(e)?!0:e.startsWith(`data-`)&&!e.startsWith(`data-rr-`)&&!_e.has(e)&&!ve.has(t)}function Oe(e){if(typeof e==`string`)return w(e)?``:e;if(typeof e!=`object`||!e||Array.isArray(e))return e;let t=!1,n={};for(let[r,i]of Object.entries(e)){let e=Array.isArray(i)?i[0]:i,a=typeof e==`string`&&w(e)?``:i;a!==i&&(t=!0),n[r]=a}return t?n:e}function ke(e){return typeof e==`string`?e.replace(/\S/gu,`*`):e}function z(e){return typeof e==`object`&&e?e:void 0}function B(e){return typeof e==`string`&&e.length>0?e:void 0}function Ae(e){let t=z(e),n=B(t?.id);if(t===void 0||n===void 0)return;let r=B(t.name),i=B(t.email);return{id:n,...r===void 0?{}:{name:r},...i===void 0?{}:{email:i}}}function je(e,t,o,s={},c){let l=1/0,u=0,d=0,f=0,p=0,m=!1,h=/* @__PURE__ */ new Set;for(let e of t){e.timestamp<l&&(l=e.timestamp),e.timestamp>u&&(u=e.timestamp);let t=z(e.data);if(e.type===n.FullSnapshot)m=!0;else if(e.type===n.Meta){let e=B(t?.href);e!==void 0&&h.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)&&d++}else e===r.Input&&f++}else if(e.type===n.Custom&&t!==void 0){let e=B(t.tag),n=z(t.payload);if(e===a.Error)p++;else if(e===a.Console)n?.level===`error`&&p++;else if(e===a.Navigation){let e=B(n?.url);e!==void 0&&h.add(e)}}}return{seq:e,firstTimestamp:l===1/0?0:l,lastTimestamp:u,eventCount:t.length,clickCount:d,keypressCount:f,errorCount:p,hasFullSnapshot:m,urls:[...h],...o!==void 0&&o.length>0?{distinctId:o}:{},...c===void 0?{}:{user:{...c}},...Object.keys(s).length===0?{}:{sessionAttributes:{...s}}}}function Me(e=Date.now){let t=e(),n=new Uint8Array(/* @__PURE__ */ new ArrayBuffer(16));Ne(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/256)&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 Ne(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 Pe=`lf_session_replay`;var Fe=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?Ie():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:Me(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(Pe);if(e!==null){let t=JSON.parse(e);if(Le(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(Pe,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 Ie(){try{return globalThis.sessionStorage??null}catch{return null}}function Le(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)}var Re=class extends Error{droppedSeqs;reason;seq;sessionId;status;constructor(e){super(ze(e),{cause:e.cause}),this.name=`ReplayUploadError`,this.droppedSeqs=Object.freeze([...e.droppedSeqs??[]]),this.reason=e.reason,this.seq=e.seq,this.sessionId=e.sessionId,this.status=e.status}};function ze(e){let t=e.seq===void 0?`replay chunk`:`replay chunk seq=${String(e.seq)}`,n=e.cause instanceof Error?`: ${e.cause.message}`:``;return`${t} ${e.reason}${n}`}const V=`lf_session_replay_seq`,H=1e4,Be=3e4,U=48e3,Ve=1e6,He=.9,Ue={gzip:t.gzip,gzipSync:t.gzipSync};var We=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;queue=[];retainedBytes=0;activeUpload;drainPromise;draining=!1;pagehideUploads=/* @__PURE__ */ new Set;lifecycleFlights=/* @__PURE__ */ new Set;closed=!1;shuttingDown=!1;wakeRetry;retryAbort=new AbortController;deadlineAbort=new AbortController;resyncPending=!1;resyncTimer;lastResyncAt;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;takeFullSnapshot;sequenceRecord;sequenceRecordFailed=!1;awaitingBinding;bindingBufferIncomplete=!1;constructor(e,t,n,r=Ie(),i=Ue,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.sequenceRecord=o.sequenceRecord,this.awaitingBinding=o.awaitBinding===!0,this.minimumDurationSatisfied=e.minSessionDurationMs===0,this.seq=o.sequenceRecord?.initialSeq??this.readPersistedSequence()??0,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=K(e);if(this.resyncPending){this.addDuringResync(e,t);return}if(this.refreshingMinimumSnapshot){this.buffer.push(e),this.pendingBytes+=t;return}let r=!this.minimumDurationSatisfied;if(this.mode===`buffer`||this.held||r||this.awaitingBinding){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:K(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.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=r,r&&this.finishMinimumBufferingEvent();return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=r,r&&this.finishMinimumBufferingEvent();return}}if(e.type===n.Meta&&this.mode===`full`&&this.buffer.length>0&&this.flushAndReport(),this.buffer.push(e),this.pendingBytes+=t,r&&this.minimumDurationReached()){this.flushAndReport();return}this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&e.type!==n.Meta?this.flushAndReport():this.scheduleFlush()}addDuringResync(e,t){if(e.type===n.Meta){this.buffer=[e],this.pendingBytes=t;return}if(e.type!==n.FullSnapshot)return;let r=this.buffer.length===1&&this.buffer[0]?.type===n.Meta?this.buffer[0]:void 0;this.buffer=r===void 0?[e]:[r,e],this.pendingBytes=t+(r===void 0?0:K(r)),this.resyncPending=!1,this.clearResyncTimer(),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={}){if(this.closed)return;if(e.keepalive!==!0)return this.flushInternal(e);this.activeUpload!==void 0&&(this.activeUpload.background=!0,this.activeUpload.pagehide=!0);let t=this.queue.filter(e=>(e!==this.activeUpload||!e.attempting)&&!this.pagehideUploads.has(e));for(let e of t)this.pagehideUploads.add(e),e.background=!0;this.wakeRetry?.();let n=this.trackLifecycle(Promise.all(t.map(async e=>this.finalAttempt(e))).then(()=>void 0));await Promise.all([this.flushInternal(e),n])}async flushInternal(e={}){if(this.closed||this.mode===`buffer`||this.held||this.awaitingBinding||this.buffer.length===0||!this.minimumDurationReached()||(this.clearScheduledFlush(),this.minimumBufferIncomplete&&!this.refreshMinimumBuffer()))return;this.minimumDurationSatisfied=!0;let t=this.buffer,n=this.pendingBytes;this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0;let r=this.sessionId,i=this.snapshotIdentity();if(e.keepalive===!0){let e=this.splitKeepaliveEventChunks(t,i,Math.max(0,U-this.reservedKeepaliveBytes)),n=this.allocateSeq(e.length);if(n===void 0)return;await this.trackLifecycle(this.deliverLifecycle(e,n,r,i));return}if(e.background===!0){let e=[];for(let n of this.splitKeepaliveEventChunks(t,i)){let t=this.enqueue(n.events,n.eventBytes,r,i,!0,n);if(t===void 0)break;e.push(t)}await Promise.all(e.map(async e=>e.done));return}await this.enqueue(t,n,r,i)?.done}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held||this.awaitingBinding||!this.minimumDurationReached()){this.discard(),await this.settleWithinDeadline([]);return}if(e.keepalive===!0){await this.flush(e),this.closed=!0,this.clearResyncTimer(),await this.settleWithinDeadline([]);return}let t=this.flushInternal();this.closed=!0,this.shuttingDown=!0,this.clearResyncTimer(),this.retryAbort.abort();let n=this.queue.filter(e=>e!==this.activeUpload&&!this.pagehideUploads.has(e)).map(async e=>this.finalAttempt(e));await this.settleWithinDeadline([t,...n])}discard(){this.started=!1,this.closed=!0,this.clearScheduledFlush(),this.clearResyncTimer(),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=>{W(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){W(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)}snapshotIdentity(){let e=this.snapshotUser(),t=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{t=this.config.getDistinctId()??this.config.distinctId}catch(e){W(this.config.onError,e)}else e!==void 0&&(t=e.id);return{distinctId:t,user:e}}createEnvelope(e,t,n){return{version:1,meta:je(t,e,n.distinctId,this.sessionAttributes,n.user),events:e}}snapshotUser(){if(this.config.getUser!==void 0)try{return Ae(this.config.getUser())}catch(e){W(this.config.onError,e);return}}allocateSeq(e){let t=this.seq,n=this.sequenceRecord;if(n!==void 0){if(this.sequenceRecordFailed)return;if(!n.write(t+e)){this.sequenceRecordFailed=!0,this.discard();try{n.onFailure()}catch(e){W(this.config.onError,e)}return}}return this.seq+=e,this.saveSeq(this.sessionId,this.seq),t}enqueue(e,t,r,i,a=!1,o){let s=Math.max(2e6,2*this.config.maxBufferBytes);if(this.queue.length>0&&this.retainedBytes+t>s){W(this.config.onError,new Re({cause:/* @__PURE__ */ Error(`replay upload queue is full`),reason:`not-sent`,seq:void 0,sessionId:r})),this.beginResync();return}let c=this.allocateSeq(1);if(c===void 0)return;let l=()=>void 0,u={body:void 0,done:new Promise(e=>{l=e}),events:e,hasFullSnapshot:e.some(e=>e.type===n.FullSnapshot),identity:i,reachedFetch:!1,attempting:!1,background:a,pagehide:!1,prepared:o,resolve:l,retainedBytes:t,seq:c,sessionId:r,settled:!1};return this.queue.push(u),this.retainedBytes+=t,this.draining||(this.draining=!0,this.drainPromise=this.drain()),u}async drain(){try{for(;!this.shuttingDown;){let e=this.queue.find(e=>!this.pagehideUploads.has(e));if(e===void 0)break;this.activeUpload=e;let t=await this.deliverQueued(e);this.activeUpload=void 0,this.settle(e,t)}}finally{this.activeUpload=void 0,this.draining=!1}}async deliverQueued(e){let t=await this.compressQueued(e);if(t!==void 0||e.settled)return t;let n=Date.now(),r;for(let t=1;;t++){if(this.pagehideUploads.has(e))return e.done.then(()=>void 0);let i=Be-(Date.now()-n);if(t>1&&i<=0)return J(r,e.reachedFetch);let a=await this.attemptQueued(e,Math.min(H,i));if(a===void 0)return;r=a;let o=et(a,t,this.config.random);if(o===void 0||this.shuttingDown||e.pagehide||Date.now()-n+o>=Be)return J(a,e.reachedFetch);await this.backoff(o)}}retainCompressedBody(e,t){this.retainedBytes+=t.byteLength-e.retainedBytes,e.retainedBytes=t.byteLength,e.body=t,e.events=void 0}compressQueuedSync(e){let n=e.prepared;if(e.prepared=void 0,!(e.body!==void 0||e.events===void 0||e.settled)){if(n?.body!==void 0&&n.events===e.events){this.retainCompressedBody(e,n.body);return}try{let n=(0,t.strToU8)(JSON.stringify(this.createEnvelope(e.events,e.seq,e.identity)));this.retainCompressedBody(e,this.compression.gzipSync(n));return}catch(e){return{cause:e,reason:`not-sent`}}}}async compressQueued(e){if(this.shuttingDown||e.background)return this.compressQueuedSync(e);if(e.body!==void 0||e.events===void 0)return;let n=e.events;try{let r=(0,t.strToU8)(JSON.stringify(this.createEnvelope(n,e.seq,e.identity))),i=await this.compressOrdinary(r);if(e.events!==n)return await this.compressQueued(e);e.settled||this.retainCompressedBody(e,i);return}catch(e){return{cause:e,reason:`not-sent`}}}async attemptQueued(e,t=H){let n=e.body;if(n!==void 0){e.attempting=!0;try{await this.send(this.prepareUpload(n,e.seq,e.sessionId,e.background),()=>{e.reachedFetch=!0},t);return}catch(e){return e}finally{e.attempting=!1}}}async finalAttempt(e){let t=e.background?this.compressQueuedSync(e):await this.compressQueued(e);if(t!==void 0){this.settle(e,t);return}let n=await this.attemptQueued(e);this.settle(e,n===void 0?void 0:J(n,e.reachedFetch))}async trackLifecycle(e){this.lifecycleFlights.add(e);let t=()=>{this.lifecycleFlights.delete(e)};return e.then(t,t),e}async settleWithinDeadline(e){let t=Promise.all([...e,this.drainPromise,...this.lifecycleFlights]).then(()=>void 0,()=>void 0),n,r=new Promise(e=>{n=setTimeout(e,H)});if(await Promise.race([t,r]),clearTimeout(n),this.shuttingDown){this.deadlineAbort.abort(/* @__PURE__ */ Error(`replay upload did not finish before shutdown`));for(let e of[...this.queue])this.settle(e,{cause:/* @__PURE__ */ Error(`replay upload did not finish before shutdown`),reason:e.reachedFetch?`unconfirmed`:`not-sent`})}}settle(e,t){if(e.settled)return;e.settled=!0,this.pagehideUploads.delete(e),this.retainedBytes-=e.retainedBytes;let n=this.queue.indexOf(e);n>=0&&this.queue.splice(n,1),e.body=void 0,e.events=void 0,e.resolve(),t!==void 0&&this.handleSequencedLoss(e.seq,e.sessionId,t)}handleSequencedLoss(e,t,n){let r=[];if(!this.shuttingDown){let t=!1;for(let n of[...this.queue])if(!(n.seq<e)){if(n.events===void 0){if(n.hasFullSnapshot){t=!0;break}continue}if(n.hasFullSnapshot){let e=Je(n.events),r=Ye(e);this.retainedBytes+=r-n.retainedBytes,n.retainedBytes=r,n.events=e,t=!0;break}r.push(n.seq),this.settle(n,void 0)}!t&&!this.trimBufferToAnchor()&&this.beginResync()}W(this.config.onError,new Re({cause:n.cause,droppedSeqs:r,reason:n.reason,seq:e,sessionId:t,status:n.status}))}trimBufferToAnchor(){return this.buffer.some(e=>e.type===n.FullSnapshot)?(this.buffer=Je(this.buffer),this.pendingBytes=Ye(this.buffer),!0):!1}beginResync(){this.closed||(this.resyncPending=!0,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.clearScheduledFlush(),this.scheduleResyncSnapshot())}scheduleResyncSnapshot(){if(this.resyncTimer!==void 0||this.closed)return;let e=this.lastResyncAt===void 0?0:Math.max(0,this.lastResyncAt+6e4-this.config.now());this.resyncTimer=setTimeout(()=>{this.resyncTimer=void 0,this.takeResyncSnapshot()},e)}takeResyncSnapshot(){if(this.resyncPending&&!this.closed&&this.takeFullSnapshot!==void 0){this.lastResyncAt=this.config.now();try{this.takeFullSnapshot()}catch(e){W(this.config.onError,e),this.scheduleResyncSnapshot();return}this.isResyncPending()&&(W(this.config.onError,/* @__PURE__ */ Error(`replay resync snapshot produced no full snapshot`)),this.scheduleResyncSnapshot())}}isResyncPending(){return this.resyncPending}clearResyncTimer(){this.resyncTimer!==void 0&&(clearTimeout(this.resyncTimer),this.resyncTimer=void 0)}async backoff(e){let t=this.retryAbort.signal;t.aborted||await new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),this.wakeRetry===r&&(this.wakeRetry=void 0),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r),this.wakeRetry=r})}prepareUpload(e,t,n,r){let i=r&&this.reservedKeepaliveBytes+e.byteLength<=U?e.byteLength:0;return this.reservedKeepaliveBytes+=i,{body:e,seq:t,sessionId:n,reservedBytes:i,requestKeepalive:i>0}}splitKeepaliveEventChunks(e,n,r=1/0){let i=e.map(K),a=[],o=r,s,c=0;for(;c<e.length;){let l=Math.min(U,o);if(l<4800){a.push({events:e.slice(c),eventBytes:q(i,c,e.length)});break}let u=this.seq+a.length,d=s===void 0?Ve:Math.min(Ve,l*s*He),f=Xe(i,c,d);for(;;){let d=e.slice(c,f),p=q(i,c,f),m;try{m=this.compression.gzipSync((0,t.strToU8)(JSON.stringify(this.createEnvelope(d,u,n))))}catch{a.push({events:d,eventBytes:p}),o=Number.isFinite(r)?0:o;break}if(s=p/Math.max(1,m.byteLength),m.byteLength<=l){a.push({events:d,eventBytes:p,body:m}),o-=m.byteLength;break}if(f-c===1){Number.isFinite(r)?(a.push({events:e.slice(c),eventBytes:q(i,c,e.length)}),f=e.length):a.push({events:d,eventBytes:p,body:m});break}f=Math.max(c+1,Math.min(f-1,Xe(i,c,l*s*He)))}c=f}return a}async deliverLifecycle(e,n,r,i){let a=[];for(let o=0;o<e.length;o++){let s=e[o];if(s===void 0){a.push(void 0);continue}try{a.push({body:s.body??this.compression.gzipSync((0,t.strToU8)(JSON.stringify(this.createEnvelope(s.events,n+o,i)))),requestKeepalive:!1,reservedBytes:0,seq:n+o,sessionId:r})}catch(e){this.handleSequencedLoss(n+o,r,{cause:e,reason:`not-sent`}),a.push(void 0)}}let o=!0,s=Math.max(0,U-this.reservedKeepaliveBytes);for(let e of a){if(e===void 0){o=!1;continue}o&&e.body.byteLength<=s?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,s-=e.reservedBytes):o=!1}await Promise.all(a.map(async e=>{if(e===void 0)return;let t=!1;try{await this.send(e,()=>{t=!0})}catch(n){this.handleSequencedLoss(e.seq,e.sessionId,J(n,t))}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await Ze(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async send(e,t,n=H){let r,i,a,o=new AbortController,s=setTimeout(()=>{o.abort(/* @__PURE__ */ Error(`replay upload timed out after ${String(n)}ms`))},n),c=this.deadlineAbort.signal,l=()=>{o.abort(c.reason)};c.addEventListener(`abort`,l);try{let n=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,s=await qe(this.getUploadHeaders(),o.signal);t();let c=this.config.fetchImpl(n,{method:`POST`,headers:s,body:e.body.slice(),keepalive:e.requestKeepalive,signal:o.signal});r=!0;let l=await c;if(i=!0,a=await Qe(l),!l.ok){let e=l.status===429||l.status===503?tt(l.headers.get(`retry-after`),Date.now()):void 0;throw new G(l.status,e)}}finally{clearTimeout(s),c.removeEventListener(`abort`,l),e.reservedBytes>0&&(r!==!0||i!==!0||a===!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 Ke(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`}}canResumeSequence(){return this.awaitingBinding?!0:this.readPersistedSequence()===this.seq}isAwaitingBinding(){return this.awaitingBinding}bind(e){this.awaitingBinding&&!this.closed&&(this.sequenceRecord=e,this.seq=e.initialSeq,this.awaitingBinding=!1,this.bindingBufferIncomplete&&(this.bindingBufferIncomplete=!1,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.takeFullSnapshot?.()),!(this.mode!==`full`||this.held||this.buffer.length===0)&&(this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()))}readPersistedSequence(){if(this.storage!==null)try{let e=this.storage.getItem(V);if(e===null)return;let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return n.id===this.sessionId&&typeof n.seq==`number`&&Number.isSafeInteger(n.seq)&&n.seq>=0?n.seq:void 0}catch{return}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(V,JSON.stringify({id:e,seq:t}))}catch{}}};function W(e,t){try{let n=e?.(t);Ge(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Ge(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var G=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 Ke(e){return typeof e==`function`?e():e}async function qe(e,t){if(t.aborted)throw t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e instanceof Error?e:Error(String(e)))})})}function K(e){try{return(0,t.strToU8)(JSON.stringify(e)).byteLength}catch{return 0}}function Je(e){let t=e.findIndex(e=>e.type===n.FullSnapshot);if(t<0)return e;let r=t>0&&e[t-1]?.type===n.Meta?t-1:t;return e.slice(r)}function Ye(e){return e.reduce((e,t)=>e+K(t),0)}function q(e,t,n){let r=0;for(let i=t;i<n;i++)r+=e[i]??0;return r}function Xe(e,t,n){let r=t+1,i=e[t]??0;for(;r<e.length&&i+(e[r]??0)<=n;)i+=e[r]??0,r++;return r}async function Ze(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(/* @__PURE__ */ 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 Qe(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function $e(e){return e===408||e===425||e===429||e>=500}function et(e,t,n){if(e instanceof G&&!$e(e.status))return;let r=Math.min(8e3,500*2**(t-1)),i=Math.round(r*(1-.5*n())),a=e instanceof G?e.retryAfter:void 0;return a===void 0?i:Math.max(a,i)}function J(e,t){let n=e instanceof G?e.status:void 0;return n!==void 0&&!$e(n)?{cause:e,reason:`rejected`,status:n}:{cause:e,reason:t?`unconfirmed`:`not-sent`,status:n}}function tt(e,t){if(e===null)return;let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?e*1e3:void 0}let r=at(n,t);return r===void 0?void 0:Math.max(0,r-t)}const nt=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],rt=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],it=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function at(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 Y(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),Y(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 Y(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function Y(e,t,n,r,i,a,o){let s=Number(t),c=nt.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=/* @__PURE__ */ 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=rt.indexOf(e),h=it.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const ot=`lf_session_replay_recording`,X=`lf_session_replay_recording_owner`,st=72e5;var ct=class{state;resumed=!1;storage;owner;now;maxDurationMs;readOpenerState;constructor(e,t,n,r=()=>null){this.storage=e,this.now=t,this.owner=Me(t),this.maxDurationMs=Math.min(n,st),this.readOpenerState=r;try{e?.getItem(`lf_session_replay_recording_owner`)===null&&(this.state=this.readResumableState()),e?.setItem(X,this.owner),e?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.storage=null,this.state=void 0)}catch{this.storage=null,this.state=void 0}this.resumed=this.state!==void 0}get(e){return this.state!==void 0&&this.isCurrent(this.state.id,e)?this.state.id:this.replace(e)}candidate(e){return{id:this.get(e),resumed:this.resumed}}replace(e){this.state={id:Me(this.now),rumSessionId:e,startedAt:this.now()},this.resumed=!1;try{this.storage?.setItem(ot,JSON.stringify(this.state))}catch{}return this.state.id}isCurrent(e,t){let n=this.state;if(n===void 0)return!1;let r=this.now();return n.id===e&&n.rumSessionId===t&&r>=n.startedAt&&r-n.startedAt<this.maxDurationMs}release(){try{this.storage?.getItem(`lf_session_replay_recording_owner`)===this.owner&&this.storage.removeItem(X)}catch{}}resume(){try{this.state=this.storage?.getItem(`lf_session_replay_recording_owner`)===null?this.readResumableState():void 0,this.storage?.setItem(X,this.owner),this.storage?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.state=void 0,this.storage=null)}catch{this.state=void 0,this.storage=null}this.resumed=this.state!==void 0}readResumableState(){let e=this.storage?.getItem(ot),t=this.storage?.getItem(V);if(e==null||t==null)return;let n=null;try{n=this.readOpenerState()}catch{}if(n!==e)return lt(e,t)}};function lt(e,t){let n=JSON.parse(e),r=JSON.parse(t);if(typeof n!=`object`||!n||typeof r!=`object`||!r)return;let i=n,a=r;if(!(typeof i.id!=`string`||i.id.length===0||typeof i.rumSessionId!=`string`||typeof i.startedAt!=`number`||!Number.isFinite(i.startedAt)||a.id!==i.id||typeof a.seq!=`number`||!Number.isSafeInteger(a.seq)||a.seq<0))return{id:i.id,rumSessionId:i.rumSessionId,startedAt:i.startedAt}}function ut(){try{if(typeof window>`u`||!window.isSecureContext)return;let e=globalThis.navigator?.locks;return typeof e?.request==`function`?e:void 0}catch{return}}async function dt(e,t,n,r=1e3){return n.aborted?{kind:`aborted`}:new Promise(i=>{let a=!1,o=e=>{a||(a=!0,clearTimeout(c),n.removeEventListener(`abort`,l),i(e))},s=new AbortController,c=setTimeout(()=>{s.abort(),o({kind:`timeout`})},r),l=()=>{s.abort(),o({kind:`aborted`})};n.addEventListener(`abort`,l);let u=!1;try{e.request(`logfire-session-replay:${t}`,{mode:`exclusive`,signal:s.signal},async()=>{if(u=!0,a||n.aborted){o({kind:`aborted`});return}await new Promise(e=>{o({kind:`held`,lock:{release:e}})})}).catch(()=>{u||o({kind:`aborted`})})}catch{o({kind:`aborted`})}})}function ft(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function pt(e){let t=e.random??Math.random;return t()<ft(e.sessionSampleRate)?`full`:t()<ft(e.onErrorSampleRate)?`buffer`:`off`}const mt=`lf_session_replay_seq:`,Z=`lf_session_replay_probe`;var ht=class{storage;now;constructor(e,t){this.storage=e,this.now=t}read(e){try{return vt(this.storage.getItem(_t(e)))?.seq}catch{return}}write(e,t){try{return this.storage.setItem(_t(e),JSON.stringify({seq:t,at:this.now()})),this.read(e)===t}catch{return!1}}prune(e){try{let t=this.now()-e,n=[];for(let e=0;e<this.storage.length;e+=1){let r=this.storage.key(e);if(r===null||!r.startsWith(mt))continue;let i=vt(this.storage.getItem(r));(i===void 0||i.at<t)&&n.push(r)}for(let e of n)this.storage.removeItem(e)}catch{}}};function gt(){try{let e=globalThis.localStorage;if(e===void 0)return null;e.setItem(Z,`1`);let t=e.getItem(Z)===`1`;return e.removeItem(Z),t?e:null}catch{return null}}function _t(e){return`${mt}${e}`}function vt(e){if(e!==null)try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return typeof n.seq!=`number`||!Number.isSafeInteger(n.seq)||n.seq<0||typeof n.at!=`number`||!Number.isFinite(n.at)?void 0:{seq:n.seq,at:n.at}}catch{return}}const yt=/^[a-z][a-z0-9_]{0,63}$/u;function bt(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function xt(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(!yt.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`&&bt(r,200))&&(Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:r,writable:!0}),o+=1,o===20))break}return Object.freeze(a)}const St={mode:`off`,recording:!1,getSessionId:()=>``,captureError:()=>void 0,getRecordingId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},Ct=`lf_session_replay_mode`,Q=Symbol.for(`@pydantic/logfire-session-replay/controller`);function wt(e){if(typeof window>`u`||typeof document>`u`)return St;let t=zt();try{let n=Et(e),r=new Fe({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return $(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=Ie(),s=new ct(o,n.now,n.maxSessionDurationMs,()=>window.opener?.sessionStorage.getItem(`lf_session_replay_recording`)??null),c=Dt(n.now),l=a(!1),u=s.get(l),d,f=!1,p=!1,m=0,h=!0,g=Promise.resolve(),_=Promise.resolve(),v,y,b,x=!1,S=e=>{y!==void 0&&(e===void 0||y.recordingId===e)&&(y.lock.release(),y=void 0)},C=(e,t,r=!t,i=!1)=>{let c=Ot(n,e,o);if(!(c===`off`||f||p||d!==void 0||e!==l))try{x=i&&s.candidate(e).resumed;let t=u;d=Tt({config:n,getSessionId:a,mode:c,onSessionChanged:O,samplingModeStorage:o,sessionId:e,recordingId:t,isCurrentRecording:()=>s.isCurrent(t,a(!1)),holdUntilActivity:r,awaitBinding:i})}catch(e){if(d=void 0,t)throw e;$(n.onError,e)}},w=(e,t,n)=>({initialSeq:n,write:n=>e.records.write(t,n),onFailure:()=>{queueMicrotask(()=>{!f&&u===t&&(s.replace(l),O(l,!1))})}}),T=async(e,t,r)=>{b?.abort();let i=new AbortController;b=i;let a=()=>i.signal.aborted||f||p||m!==r||l!==t,o=s.candidate(t);u=o.id;let c=()=>{o={id:s.replace(t),resumed:!1},u=o.id};for(let t=0;t<2;t+=1){let t=await dt(e.locks,o.id,i.signal);if(t.kind===`aborted`)return;if(t.kind===`timeout`){c();continue}if(a()||u!==o.id){t.lock.release();return}let n;if(o.resumed?n=e.records.read(o.id):e.records.write(o.id,0)&&(n=0),n===void 0){t.lock.release(),c();continue}return y={recordingId:o.id,lock:t.lock},{recordingId:o.id,sequenceRecord:w(e,o.id,n)}}$(n.onError,/* @__PURE__ */ Error(`logfire session replay: could not claim a replay recording`))},E=async(e,t,r,i)=>{try{let n=await T(e,t,r),a=!f&&!p&&m===r&&l===t;if(n===void 0){a&&d?.transport.isAwaitingBinding()===!0&&(d.discard(),d=void 0);return}if(!a){S(n.recordingId);return}if(d!==void 0&&d.recordingId!==n.recordingId&&(d.discard(),d=void 0,C(t,!1,i,!0)),d===void 0||d.recordingId!==n.recordingId){S(n.recordingId);return}x=!1,d.transport.bind(n.sequenceRecord)}catch(e){$(n.onError,e)}},D=async(e,t,n)=>{C(e,!1,n,c!==void 0),c!==void 0&&d!==void 0&&await E(c,e,t,n)},O=(e,t=!0)=>{if(f||p)return;let r=s.get(e);if(e===l&&r===u)return;let i=u;l=e,u=r,b?.abort();let a=d;d=void 0;let o=a?.deactivate()??Promise.resolve(),c=m;g=g.then(async()=>{await It(o,n.onError),S(i),!f&&m===c&&l===e&&u===r&&await D(e,c,t)})},k;try{if(c===void 0)C(l,!0);else if(c.records.prune(st),C(l,!0,!1,!0),d!==void 0){let e=l,t=m;g=g.then(async()=>E(c,e,t,!1))}k=setInterval(()=>{O(a(!1))},1e3)}catch(e){throw d?.discard(),d=void 0,b?.abort(),S(),s.release(),e}let A=()=>{p=!0,m+=1,b?.abort();let e=d;d=void 0;let t=e?.deactivate(!0)??Promise.resolve();S(),_=Promise.all([_,g,It(t,n.onError)]).then(()=>void 0),g=Promise.resolve(),h=e?.transport.canResumeSequence()??h,h&&s.release()},j=e=>{if(!e.persisted||f)return;d?.discard(),d=void 0;let t=m;g=g.then(async()=>{let e=()=>f||m!==t;if(e())return;let n=new AbortController;b=n;let r,i=!1;if(c!==void 0){let e=await dt(c.locks,u,n.signal);if(e.kind===`aborted`)return;e.kind===`held`&&(r=e.lock),i=e.kind===`timeout`}else await new Promise(e=>{setTimeout(e,0)});try{if(e())return;p=!1,s.resume(),l=a(!1),u=i?s.replace(l):s.get(l),h=!0}finally{r?.release()}await D(l,t,!1)})};return window.addEventListener(`pagehide`,A),window.addEventListener(`pageshow`,j),{get mode(){try{return d?.transport.getMode()??`off`}catch(e){return $(n.onError,e),`off`}},get recording(){try{return d!==void 0}catch(e){return $(n.onError,e),!1}},getSessionId:()=>a(!1),captureError:(e,t)=>{try{d?.captureError(e,t)}catch(e){$(n.onError,e)}},getRecordingId:()=>d===void 0||x&&d.transport.isAwaitingBinding()?``:s.isCurrent(d.recordingId,a(!1))?d.recordingId:``,flush:async()=>{try{await g,await d?.transport.flush()}catch(e){$(n.onError,e)}},stop:async()=>(v??=(async()=>{f=!0,m+=1,b?.abort(),clearInterval(k),window.removeEventListener(`pagehide`,A),window.removeEventListener(`pageshow`,j);let e=d;d=void 0,await It(e?.deactivate()??Promise.resolve(),n.onError),await g,await _,r.flushPendingStorage(),h=e?.transport.canResumeSequence()??h,h&&s.release(),S(),t()})(),v)}}catch(e){throw t(),e}}function Tt(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:o,samplingModeStorage:s,sessionId:l,recordingId:u,isCurrentRecording:d,awaitBinding:f}=e,p=xt(t.getSessionAttributes,e=>{$(t.onError,e)}),m,h=new We(t,u,i,void 0,void 0,p,{holdUntilActivity:r,takeFullSnapshot:()=>{m.takeFullSnapshot()},awaitBinding:f}),g=[],_=!0,v=()=>_,y;try{m=xe({beforeUserActivity:()=>{if(_&&h.isHeld())try{let e=n(!0);if(e!==l||!d()){o(e,!1);return}h.releaseHeld(()=>{m.takeFullSnapshot()})}catch(e){$(t.onError,e)}},emit:e=>{if(_)try{let t=n(c(e));if(t!==l||!d()){o(t,!1);return}h.add(e)}catch(e){$(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:Math.max(3e5,t.minSessionDurationMs),redactUrlPatterns:t.redactUrlPatterns,transformUrl:t.transformUrl}),g.push(()=>{m.stop()});let e=(e,n)=>{if(_)try{m.addCustomEvent(e,n)}catch(e){$(t.onError,e)}},r=n=>{v()&&(h.releaseHeld(()=>{m.takeFullSnapshot()}),e(a.Error,n),v()&&h.getMode()===`buffer`&&(At(s,l,`full`),Ft(h.triggerFlush(),t.onError)))},f=/* @__PURE__ */ new WeakSet,p=e=>typeof e!=`object`||!e||!f.has(e)&&(f.add(e),!0),b=(e,t)=>{if(p(e)){let n=Vt(Mt(e),void 0,Nt(e));r(typeof t?.timestamp==`number`?{...n,timestamp:t.timestamp}:n)}},x=e=>{e instanceof ErrorEvent&&p(e.error)&&r(Vt(e.message,e.filename,Nt(e.error)))},S=e=>{b(e.reason)},C=()=>{document.visibilityState===`hidden`&&Ft(h.flush({background:!0}),t.onError)},w=()=>{Ft(h.flush({keepalive:!0}),t.onError)};return t.captureGlobalErrors&&(window.addEventListener(`error`,x,!0),g.push(()=>{window.removeEventListener(`error`,x,!0)}),window.addEventListener(`unhandledrejection`,S,!0),g.push(()=>{window.removeEventListener(`unhandledrejection`,S,!0)})),document.addEventListener(`visibilitychange`,C),g.push(()=>{document.removeEventListener(`visibilitychange`,C)}),window.addEventListener(`pagehide`,w),g.push(()=>{window.removeEventListener(`pagehide`,w)}),t.captureConsole&&g.push(A(e,{onError:t.onError})),t.captureNetwork&&g.push(j(e,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns,transformUrl:t.transformUrl})),t.captureNavigation&&g.push(ee(e,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns,transformUrl:t.transformUrl})),h.start(),{sessionId:l,recordingId:u,transport:h,captureError:b,deactivate:async(e=!1)=>(y??=(async()=>{let t=h.shutdown({keepalive:e});_=!1,Bt(g),await t})(),y),discard:()=>{_=!1,Bt(g),h.discard()}}}catch(e){throw _=!1,Bt(g),h.discard(),e}}function Et(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,getUser:e.getUser,captureConsole:e.captureConsole??o.captureConsole,captureNetwork:e.captureNetwork??o.captureNetwork,captureNavigation:e.captureNavigation??o.captureNavigation,captureGlobalErrors:e.captureGlobalErrors??o.captureGlobalErrors,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...o.redactUrlPatterns],transformUrl:Lt(e.transformUrl,e.onError),onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function Dt(e){let t=ut();if(t===void 0)return;let n=gt();return n===null?void 0:{locks:t,records:new ht(n,e)}}function Ot(e,t,n){let r=kt(n,t);if(r!==void 0)return r;let i=pt({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return At(n,t,i),i}function kt(e,t){if(e!==null)try{let n=e.getItem(Ct);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!jt(i.mode)?void 0:i.mode}catch{return}}function At(e,t,n){if(e!==null)try{e.setItem(Ct,JSON.stringify({id:t,mode:n}))}catch{}}function jt(e){return e===`full`||e===`buffer`||e===`off`}function Mt(e){return Ht(Pt(e,`message`)??e)}function Nt(e){let t=Pt(e,`stack`);return typeof t==`string`?t:void 0}function Pt(e,t){try{return typeof e==`object`&&e&&t in e?e[t]:void 0}catch{return}}function Ft(e,t){e.catch(e=>{$(t,e)})}async function It(e,t){try{await e}catch(e){$(t,e)}}function Lt(e,t){if(e===void 0)return;let n=!1;return r=>{try{return e(r)}catch(e){throw n||(n=!0,$(t,e)),e}}}function $(e,t){try{let n=e?.(t);Rt(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Rt(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function zt(){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 Bt(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function Vt(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function Ht(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{return Object.prototype.toString.call(e)}catch{return`[object Object]`}}exports.CHUNK_ENVELOPE_VERSION=1,exports.CustomTag=a,exports.EventType=n,exports.IncrementalSource=r,exports.MouseInteractions=i,exports.ReplayUploadError=Re,exports.startSessionReplay=wt;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as SessionReplayConfig, S as SessionAttributesInput, _ as ReplayUser, a as ReplayUploadErrorInit, b as SessionAttributeValue, c as ChunkEnvelope, d as CustomTag, f as EventType, g as NetworkPayload, h as NavigationPayload, i as ReplayUploadError, l as ChunkMeta, m as MouseInteractions, n as SessionReplay, o as ReplayUploadFailureReason, p as IncrementalSource, r as startSessionReplay, s as CHUNK_ENVELOPE_VERSION, t as CaptureErrorOptions, u as ConsolePayload, v as RrwebEvent, x as SessionAttributes, y as SamplingMode } from "./index-
|
|
1
|
+
import { C as SessionReplayConfig, S as SessionAttributesInput, _ as ReplayUser, a as ReplayUploadErrorInit, b as SessionAttributeValue, c as ChunkEnvelope, d as CustomTag, f as EventType, g as NetworkPayload, h as NavigationPayload, i as ReplayUploadError, l as ChunkMeta, m as MouseInteractions, n as SessionReplay, o as ReplayUploadFailureReason, p as IncrementalSource, r as startSessionReplay, s as CHUNK_ENVELOPE_VERSION, t as CaptureErrorOptions, u as ConsolePayload, v as RrwebEvent, x as SessionAttributes, y as SamplingMode } from "./index-WIWZDir6.js";
|
|
2
2
|
export { CHUNK_ENVELOPE_VERSION, CaptureErrorOptions, type ChunkEnvelope, type ChunkMeta, type ConsolePayload, CustomTag, EventType, IncrementalSource, MouseInteractions, type NavigationPayload, type NetworkPayload, ReplayUploadError, type ReplayUploadErrorInit, type ReplayUploadFailureReason, type ReplayUser, type RrwebEvent, type SamplingMode, type SessionAttributeValue, type SessionAttributes, type SessionAttributesInput, SessionReplay, type SessionReplayConfig, startSessionReplay };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as SessionReplayConfig, S as SessionAttributesInput, _ as ReplayUser, a as ReplayUploadErrorInit, b as SessionAttributeValue, c as ChunkEnvelope, d as CustomTag, f as EventType, g as NetworkPayload, h as NavigationPayload, i as ReplayUploadError, l as ChunkMeta, m as MouseInteractions, n as SessionReplay, o as ReplayUploadFailureReason, p as IncrementalSource, r as startSessionReplay, s as CHUNK_ENVELOPE_VERSION, t as CaptureErrorOptions, u as ConsolePayload, v as RrwebEvent, x as SessionAttributes, y as SamplingMode } from "./index-
|
|
1
|
+
import { C as SessionReplayConfig, S as SessionAttributesInput, _ as ReplayUser, a as ReplayUploadErrorInit, b as SessionAttributeValue, c as ChunkEnvelope, d as CustomTag, f as EventType, g as NetworkPayload, h as NavigationPayload, i as ReplayUploadError, l as ChunkMeta, m as MouseInteractions, n as SessionReplay, o as ReplayUploadFailureReason, p as IncrementalSource, r as startSessionReplay, s as CHUNK_ENVELOPE_VERSION, t as CaptureErrorOptions, u as ConsolePayload, v as RrwebEvent, x as SessionAttributes, y as SamplingMode } from "./index-WIWZDir6.js";
|
|
2
2
|
export { CHUNK_ENVELOPE_VERSION, CaptureErrorOptions, type ChunkEnvelope, type ChunkMeta, type ConsolePayload, CustomTag, EventType, IncrementalSource, MouseInteractions, type NavigationPayload, type NetworkPayload, ReplayUploadError, type ReplayUploadErrorInit, type ReplayUploadFailureReason, type ReplayUser, type RrwebEvent, type SamplingMode, type SessionAttributeValue, type SessionAttributes, type SessionAttributesInput, SessionReplay, type SessionReplayConfig, startSessionReplay };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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:1e4,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:72e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,captureGlobalErrors:!0,redactUrlPatterns:[/.+/u]},u=/* @__PURE__ */ 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){
|
|
2
|
-
`).map(e=>{let i=r&&
|
|
3
|
-
`)}const w=[`log`,`info`,`warn`,`error`,`debug`],T=1024,E=()=>void 0;function D(e,t={}){let n=[],r=M(t.onError);try{for(let t of w)typeof console[t]==`function`&&n.push(N(console,t,(n,i)=>function(...a){return i()&&j(e,s.Console,{level:t,args:a.slice(0,10).map(ie)},r),n.apply(this,a)}));return P(n)}catch(e){throw F(n),e}}function O(e,t){let n=te(t),r={...n,onError:M(n.onError)},i=k(e,r);try{return P([i,A(e,r)])}catch(e){throw i(),e}}function ee(e,t={redactUrlPatterns:[]}){let n=M(t.onError),r=r=>{let i=m(window.location.href,t.redactUrlPatterns??[],window.location.href);j(e,s.Navigation,{url:i,kind:r},n)},i=[];try{i.push(N(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(N(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)}),P(i)}catch(e){throw F(i),e}}function k(e,t){return typeof window.fetch==`function`?N(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=ae(i,a),u=oe(i);if(ue(u,t.ignoreUrlPatterns))return o.call(this,i,a);let d=m(u,t.redactUrlPatterns,window.location.href),f=le(a?.body);try{let n=await o.call(this,i,a);return r()&&j(e,s.Network,L({method:l,url:d,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:f,resBytes:se(n.headers)}),t.onError),n}catch(n){throw r()&&j(e,s.Network,L({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}):E}function A(e,t){let n=window.XMLHttpRequest.prototype,r=/* @__PURE__ */ new WeakMap,i=[];try{return i.push(N(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return ue(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(N(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=le(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()&&j(e,s.Network,L({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:ce(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()&&j(e,s.Network,L({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),P(i)}catch(e){throw F(i),e}}function te(e){return{...e,ignoreUrlPatterns:ne(e.ignoreUrlPatterns),redactUrlPatterns:ne(e.redactUrlPatterns)}}function ne(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function j(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function M(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 N(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return E;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function P(e){let t=!1;return()=>{t||(t=!0,F(e))}}function F(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 I(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return I(e.stack??`${e.name}: ${e.message}`);try{return I(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function I(e){if(e.length<=T)return e;let t=e.charCodeAt(1023),n=t>=55296&&t<=56319?1023:T;return`${e.slice(0,n)}...(+${String(e.length-n)} chars)`}function ae(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function oe(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function se(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 ce(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 L(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 le(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 ue(e,t){return p(e,t)}const de=/* @__PURE__ */ new Set([`action`,`formaction`,`href`,`src`]);function fe(t){let n=()=>{t.beforeUserActivity?.()},r={emit:e=>{t.emit(pe(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 pe(e,t){if(typeof e.data!=`object`||e.data===null)return e;let n=e.data;if(e.type===i.Custom)return me(e,n,t);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=R(n,t);return r===n?e:{...e,data:r}}function me(e,t,n){let r=t.payload;if(typeof r!=`object`||!r)return e;let i=r,a=window.location.href,o;if(t.tag===s.Error)o={...i},typeof i.message==`string`&&(o.message=C(i.message,n,a)),typeof i.source==`string`&&(o.source=m(i.source,n,a)),typeof i.stack==`string`&&(o.stack=C(i.stack,n,a,{stackTrace:!0}));else if(t.tag===s.Console&&Array.isArray(i.args))o={...i,args:i.args.map(e=>typeof e==`string`?C(e,n,a):e)};else return e;return{...e,data:{...t,payload:o}}}function R(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=R(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)?he(a,t):R(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function he(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(!de.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 z(e){return typeof e==`object`&&e?e:void 0}function B(e){return typeof e==`string`&&e.length>0?e:void 0}function ge(e){let t=z(e),n=B(t?.id);if(t===void 0||n===void 0)return;let r=B(t.name),i=B(t.email);return{id:n,...r===void 0?{}:{name:r},...i===void 0?{}:{email:i}}}function _e(e,t,n,r={},c){let l=1/0,u=0,d=0,f=0,p=0,m=!1,h=/* @__PURE__ */ new Set;for(let e of t){e.timestamp<l&&(l=e.timestamp),e.timestamp>u&&(u=e.timestamp);let t=z(e.data);if(e.type===i.FullSnapshot)m=!0;else if(e.type===i.Meta){let e=B(t?.href);e!==void 0&&h.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)&&d++}else e===a.Input&&f++}else if(e.type===i.Custom&&t!==void 0){let e=B(t.tag),n=z(t.payload);if(e===s.Error)p++;else if(e===s.Console)n?.level===`error`&&p++;else if(e===s.Navigation){let e=B(n?.url);e!==void 0&&h.add(e)}}}return{seq:e,firstTimestamp:l===1/0?0:l,lastTimestamp:u,eventCount:t.length,clickCount:d,keypressCount:f,errorCount:p,hasFullSnapshot:m,urls:[...h],...n!==void 0&&n.length>0?{distinctId:n}:{},...c===void 0?{}:{user:{...c}},...Object.keys(r).length===0?{}:{sessionAttributes:{...r}}}}function V(e=Date.now){let t=e(),n=new Uint8Array(/* @__PURE__ */ new ArrayBuffer(16));ve(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/256)&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 ve(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 ye=`lf_session_replay`;var be=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?H():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:V(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(ye);if(e!==null){let t=JSON.parse(e);if(xe(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(ye,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 H(){try{return globalThis.sessionStorage??null}catch{return null}}function xe(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)}var U=class extends Error{droppedSeqs;reason;seq;sessionId;status;constructor(e){super(Se(e),{cause:e.cause}),this.name=`ReplayUploadError`,this.droppedSeqs=Object.freeze([...e.droppedSeqs??[]]),this.reason=e.reason,this.seq=e.seq,this.sessionId=e.sessionId,this.status=e.status}};function Se(e){let t=e.seq===void 0?`replay chunk`:`replay chunk seq=${String(e.seq)}`,n=e.cause instanceof Error?`: ${e.cause.message}`:``;return`${t} ${e.reason}${n}`}const W=`lf_session_replay_seq`,G=1e4,Ce=3e4,K=48e3,we=1e6,Te=.9,Ee={gzip:t,gzipSync:n};var De=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;queue=[];retainedBytes=0;activeUpload;drainPromise;draining=!1;pagehideUploads=/* @__PURE__ */ new Set;lifecycleFlights=/* @__PURE__ */ new Set;closed=!1;shuttingDown=!1;wakeRetry;retryAbort=new AbortController;deadlineAbort=new AbortController;resyncPending=!1;resyncTimer;lastResyncAt;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;takeFullSnapshot;sequenceRecord;sequenceRecordFailed=!1;awaitingBinding;bindingBufferIncomplete=!1;constructor(e,t,n,r=H(),i=Ee,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.sequenceRecord=o.sequenceRecord,this.awaitingBinding=o.awaitBinding===!0,this.minimumDurationSatisfied=e.minSessionDurationMs===0,this.seq=o.sequenceRecord?.initialSeq??this.readPersistedSequence()??0,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=Y(e);if(this.resyncPending){this.addDuringResync(e,t);return}if(this.refreshingMinimumSnapshot){this.buffer.push(e),this.pendingBytes+=t;return}let n=!this.minimumDurationSatisfied;if(this.mode===`buffer`||this.held||n||this.awaitingBinding){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:Y(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.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=n,n&&this.finishMinimumBufferingEvent();return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=n,n&&this.finishMinimumBufferingEvent();return}}if(e.type===i.Meta&&this.mode===`full`&&this.buffer.length>0&&this.flushAndReport(),this.buffer.push(e),this.pendingBytes+=t,n&&this.minimumDurationReached()){this.flushAndReport();return}this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&e.type!==i.Meta?this.flushAndReport():this.scheduleFlush()}addDuringResync(e,t){if(e.type===i.Meta){this.buffer=[e],this.pendingBytes=t;return}if(e.type!==i.FullSnapshot)return;let n=this.buffer.length===1&&this.buffer[0]?.type===i.Meta?this.buffer[0]:void 0;this.buffer=n===void 0?[e]:[n,e],this.pendingBytes=t+(n===void 0?0:Y(n)),this.resyncPending=!1,this.clearResyncTimer(),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={}){if(this.closed)return;if(e.keepalive!==!0)return this.flushInternal(e);this.activeUpload!==void 0&&(this.activeUpload.background=!0,this.activeUpload.pagehide=!0);let t=this.queue.filter(e=>(e!==this.activeUpload||!e.attempting)&&!this.pagehideUploads.has(e));for(let e of t)this.pagehideUploads.add(e),e.background=!0;this.wakeRetry?.();let n=this.trackLifecycle(Promise.all(t.map(async e=>this.finalAttempt(e))).then(()=>void 0));await Promise.all([this.flushInternal(e),n])}async flushInternal(e={}){if(this.closed||this.mode===`buffer`||this.held||this.awaitingBinding||this.buffer.length===0||!this.minimumDurationReached()||(this.clearScheduledFlush(),this.minimumBufferIncomplete&&!this.refreshMinimumBuffer()))return;this.minimumDurationSatisfied=!0;let t=this.buffer,n=this.pendingBytes;this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0;let r=this.sessionId,i=this.snapshotIdentity();if(e.keepalive===!0){let e=this.splitKeepaliveEventChunks(t,i,Math.max(0,K-this.reservedKeepaliveBytes)),n=this.allocateSeq(e.length);if(n===void 0)return;await this.trackLifecycle(this.deliverLifecycle(e,n,r,i));return}if(e.background===!0){let e=[];for(let n of this.splitKeepaliveEventChunks(t,i)){let t=this.enqueue(n.events,n.eventBytes,r,i,!0,n);if(t===void 0)break;e.push(t)}await Promise.all(e.map(async e=>e.done));return}await this.enqueue(t,n,r,i)?.done}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held||this.awaitingBinding||!this.minimumDurationReached()){this.discard(),await this.settleWithinDeadline([]);return}if(e.keepalive===!0){await this.flush(e),this.closed=!0,this.clearResyncTimer(),await this.settleWithinDeadline([]);return}let t=this.flushInternal();this.closed=!0,this.shuttingDown=!0,this.clearResyncTimer(),this.retryAbort.abort();let n=this.queue.filter(e=>e!==this.activeUpload&&!this.pagehideUploads.has(e)).map(async e=>this.finalAttempt(e));await this.settleWithinDeadline([t,...n])}discard(){this.started=!1,this.closed=!0,this.clearScheduledFlush(),this.clearResyncTimer(),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=>{q(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){q(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)}snapshotIdentity(){let e=this.snapshotUser(),t=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{t=this.config.getDistinctId()??this.config.distinctId}catch(e){q(this.config.onError,e)}else e!==void 0&&(t=e.id);return{distinctId:t,user:e}}createEnvelope(e,t,n){return{version:1,meta:_e(t,e,n.distinctId,this.sessionAttributes,n.user),events:e}}snapshotUser(){if(this.config.getUser!==void 0)try{return ge(this.config.getUser())}catch(e){q(this.config.onError,e);return}}allocateSeq(e){let t=this.seq,n=this.sequenceRecord;if(n!==void 0){if(this.sequenceRecordFailed)return;if(!n.write(t+e)){this.sequenceRecordFailed=!0,this.discard();try{n.onFailure()}catch(e){q(this.config.onError,e)}return}}return this.seq+=e,this.saveSeq(this.sessionId,this.seq),t}enqueue(e,t,n,r,a=!1,o){let s=Math.max(2e6,2*this.config.maxBufferBytes);if(this.queue.length>0&&this.retainedBytes+t>s){q(this.config.onError,new U({cause:/* @__PURE__ */ Error(`replay upload queue is full`),reason:`not-sent`,seq:void 0,sessionId:n})),this.beginResync();return}let c=this.allocateSeq(1);if(c===void 0)return;let l=()=>void 0,u={body:void 0,done:new Promise(e=>{l=e}),events:e,hasFullSnapshot:e.some(e=>e.type===i.FullSnapshot),identity:r,reachedFetch:!1,attempting:!1,background:a,pagehide:!1,prepared:o,resolve:l,retainedBytes:t,seq:c,sessionId:n,settled:!1};return this.queue.push(u),this.retainedBytes+=t,this.draining||(this.draining=!0,this.drainPromise=this.drain()),u}async drain(){try{for(;!this.shuttingDown;){let e=this.queue.find(e=>!this.pagehideUploads.has(e));if(e===void 0)break;this.activeUpload=e;let t=await this.deliverQueued(e);this.activeUpload=void 0,this.settle(e,t)}}finally{this.activeUpload=void 0,this.draining=!1}}async deliverQueued(e){let t=await this.compressQueued(e);if(t!==void 0||e.settled)return t;let n=Date.now(),r;for(let t=1;;t++){if(this.pagehideUploads.has(e))return e.done.then(()=>void 0);let i=Ce-(Date.now()-n);if(t>1&&i<=0)return Z(r,e.reachedFetch);let a=await this.attemptQueued(e,Math.min(G,i));if(a===void 0)return;r=a;let o=Le(a,t,this.config.random);if(o===void 0||this.shuttingDown||e.pagehide||Date.now()-n+o>=Ce)return Z(a,e.reachedFetch);await this.backoff(o)}}retainCompressedBody(e,t){this.retainedBytes+=t.byteLength-e.retainedBytes,e.retainedBytes=t.byteLength,e.body=t,e.events=void 0}compressQueuedSync(e){let t=e.prepared;if(e.prepared=void 0,!(e.body!==void 0||e.events===void 0||e.settled)){if(t?.body!==void 0&&t.events===e.events){this.retainCompressedBody(e,t.body);return}try{let t=r(JSON.stringify(this.createEnvelope(e.events,e.seq,e.identity)));this.retainCompressedBody(e,this.compression.gzipSync(t));return}catch(e){return{cause:e,reason:`not-sent`}}}}async compressQueued(e){if(this.shuttingDown||e.background)return this.compressQueuedSync(e);if(e.body!==void 0||e.events===void 0)return;let t=e.events;try{let n=r(JSON.stringify(this.createEnvelope(t,e.seq,e.identity))),i=await this.compressOrdinary(n);if(e.events!==t)return await this.compressQueued(e);e.settled||this.retainCompressedBody(e,i);return}catch(e){return{cause:e,reason:`not-sent`}}}async attemptQueued(e,t=G){let n=e.body;if(n!==void 0){e.attempting=!0;try{await this.send(this.prepareUpload(n,e.seq,e.sessionId,e.background),()=>{e.reachedFetch=!0},t);return}catch(e){return e}finally{e.attempting=!1}}}async finalAttempt(e){let t=e.background?this.compressQueuedSync(e):await this.compressQueued(e);if(t!==void 0){this.settle(e,t);return}let n=await this.attemptQueued(e);this.settle(e,n===void 0?void 0:Z(n,e.reachedFetch))}async trackLifecycle(e){this.lifecycleFlights.add(e);let t=()=>{this.lifecycleFlights.delete(e)};return e.then(t,t),e}async settleWithinDeadline(e){let t=Promise.all([...e,this.drainPromise,...this.lifecycleFlights]).then(()=>void 0,()=>void 0),n,r=new Promise(e=>{n=setTimeout(e,G)});if(await Promise.race([t,r]),clearTimeout(n),this.shuttingDown){this.deadlineAbort.abort(/* @__PURE__ */ Error(`replay upload did not finish before shutdown`));for(let e of[...this.queue])this.settle(e,{cause:/* @__PURE__ */ Error(`replay upload did not finish before shutdown`),reason:e.reachedFetch?`unconfirmed`:`not-sent`})}}settle(e,t){if(e.settled)return;e.settled=!0,this.pagehideUploads.delete(e),this.retainedBytes-=e.retainedBytes;let n=this.queue.indexOf(e);n>=0&&this.queue.splice(n,1),e.body=void 0,e.events=void 0,e.resolve(),t!==void 0&&this.handleSequencedLoss(e.seq,e.sessionId,t)}handleSequencedLoss(e,t,n){let r=[];if(!this.shuttingDown){let t=!1;for(let n of[...this.queue])if(!(n.seq<e)){if(n.events===void 0){if(n.hasFullSnapshot){t=!0;break}continue}if(n.hasFullSnapshot){let e=je(n.events),r=Me(e);this.retainedBytes+=r-n.retainedBytes,n.retainedBytes=r,n.events=e,t=!0;break}r.push(n.seq),this.settle(n,void 0)}!t&&!this.trimBufferToAnchor()&&this.beginResync()}q(this.config.onError,new U({cause:n.cause,droppedSeqs:r,reason:n.reason,seq:e,sessionId:t,status:n.status}))}trimBufferToAnchor(){return this.buffer.some(e=>e.type===i.FullSnapshot)?(this.buffer=je(this.buffer),this.pendingBytes=Me(this.buffer),!0):!1}beginResync(){this.closed||(this.resyncPending=!0,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.clearScheduledFlush(),this.scheduleResyncSnapshot())}scheduleResyncSnapshot(){if(this.resyncTimer!==void 0||this.closed)return;let e=this.lastResyncAt===void 0?0:Math.max(0,this.lastResyncAt+6e4-this.config.now());this.resyncTimer=setTimeout(()=>{this.resyncTimer=void 0,this.takeResyncSnapshot()},e)}takeResyncSnapshot(){if(this.resyncPending&&!this.closed&&this.takeFullSnapshot!==void 0){this.lastResyncAt=this.config.now();try{this.takeFullSnapshot()}catch(e){q(this.config.onError,e),this.scheduleResyncSnapshot();return}this.isResyncPending()&&(q(this.config.onError,/* @__PURE__ */ Error(`replay resync snapshot produced no full snapshot`)),this.scheduleResyncSnapshot())}}isResyncPending(){return this.resyncPending}clearResyncTimer(){this.resyncTimer!==void 0&&(clearTimeout(this.resyncTimer),this.resyncTimer=void 0)}async backoff(e){let t=this.retryAbort.signal;t.aborted||await new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),this.wakeRetry===r&&(this.wakeRetry=void 0),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r),this.wakeRetry=r})}prepareUpload(e,t,n,r){let i=r&&this.reservedKeepaliveBytes+e.byteLength<=K?e.byteLength:0;return this.reservedKeepaliveBytes+=i,{body:e,seq:t,sessionId:n,reservedBytes:i,requestKeepalive:i>0}}splitKeepaliveEventChunks(e,t,n=1/0){let i=e.map(Y),a=[],o=n,s,c=0;for(;c<e.length;){let l=Math.min(K,o);if(l<4800){a.push({events:e.slice(c),eventBytes:X(i,c,e.length)});break}let u=this.seq+a.length,d=s===void 0?we:Math.min(we,l*s*Te),f=Ne(i,c,d);for(;;){let d=e.slice(c,f),p=X(i,c,f),m;try{m=this.compression.gzipSync(r(JSON.stringify(this.createEnvelope(d,u,t))))}catch{a.push({events:d,eventBytes:p}),o=Number.isFinite(n)?0:o;break}if(s=p/Math.max(1,m.byteLength),m.byteLength<=l){a.push({events:d,eventBytes:p,body:m}),o-=m.byteLength;break}if(f-c===1){Number.isFinite(n)?(a.push({events:e.slice(c),eventBytes:X(i,c,e.length)}),f=e.length):a.push({events:d,eventBytes:p,body:m});break}f=Math.max(c+1,Math.min(f-1,Ne(i,c,l*s*Te)))}c=f}return a}async deliverLifecycle(e,t,n,i){let a=[];for(let o=0;o<e.length;o++){let s=e[o];if(s===void 0){a.push(void 0);continue}try{a.push({body:s.body??this.compression.gzipSync(r(JSON.stringify(this.createEnvelope(s.events,t+o,i)))),requestKeepalive:!1,reservedBytes:0,seq:t+o,sessionId:n})}catch(e){this.handleSequencedLoss(t+o,n,{cause:e,reason:`not-sent`}),a.push(void 0)}}let o=!0,s=Math.max(0,K-this.reservedKeepaliveBytes);for(let e of a){if(e===void 0){o=!1;continue}o&&e.body.byteLength<=s?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,s-=e.reservedBytes):o=!1}await Promise.all(a.map(async e=>{if(e===void 0)return;let t=!1;try{await this.send(e,()=>{t=!0})}catch(n){this.handleSequencedLoss(e.seq,e.sessionId,Z(n,t))}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await Pe(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async send(e,t,n=G){let r,i,a,o=new AbortController,s=setTimeout(()=>{o.abort(/* @__PURE__ */ Error(`replay upload timed out after ${String(n)}ms`))},n),c=this.deadlineAbort.signal,l=()=>{o.abort(c.reason)};c.addEventListener(`abort`,l);try{let n=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,s=await Ae(this.getUploadHeaders(),o.signal);t();let c=this.config.fetchImpl(n,{method:`POST`,headers:s,body:e.body.slice(),keepalive:e.requestKeepalive,signal:o.signal});r=!0;let l=await c;if(i=!0,a=await Fe(l),!l.ok){let e=l.status===429||l.status===503?Re(l.headers.get(`retry-after`),Date.now()):void 0;throw new J(l.status,e)}}finally{clearTimeout(s),c.removeEventListener(`abort`,l),e.reservedBytes>0&&(r!==!0||i!==!0||a===!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 ke(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`}}canResumeSequence(){return this.awaitingBinding?!0:this.readPersistedSequence()===this.seq}isAwaitingBinding(){return this.awaitingBinding}bind(e){this.awaitingBinding&&!this.closed&&(this.sequenceRecord=e,this.seq=e.initialSeq,this.awaitingBinding=!1,this.bindingBufferIncomplete&&(this.bindingBufferIncomplete=!1,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.takeFullSnapshot?.()),!(this.mode!==`full`||this.held||this.buffer.length===0)&&(this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()))}readPersistedSequence(){if(this.storage!==null)try{let e=this.storage.getItem(W);if(e===null)return;let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return n.id===this.sessionId&&typeof n.seq==`number`&&Number.isSafeInteger(n.seq)&&n.seq>=0?n.seq:void 0}catch{return}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(W,JSON.stringify({id:e,seq:t}))}catch{}}};function q(e,t){try{let n=e?.(t);Oe(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Oe(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var J=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 ke(e){return typeof e==`function`?e():e}async function Ae(e,t){if(t.aborted)throw t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e instanceof Error?e:Error(String(e)))})})}function Y(e){try{return r(JSON.stringify(e)).byteLength}catch{return 0}}function je(e){let t=e.findIndex(e=>e.type===i.FullSnapshot);if(t<0)return e;let n=t>0&&e[t-1]?.type===i.Meta?t-1:t;return e.slice(n)}function Me(e){return e.reduce((e,t)=>e+Y(t),0)}function X(e,t,n){let r=0;for(let i=t;i<n;i++)r+=e[i]??0;return r}function Ne(e,t,n){let r=t+1,i=e[t]??0;for(;r<e.length&&i+(e[r]??0)<=n;)i+=e[r]??0,r++;return r}async function Pe(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(/* @__PURE__ */ 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 Fe(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function Ie(e){return e===408||e===425||e===429||e>=500}function Le(e,t,n){if(e instanceof J&&!Ie(e.status))return;let r=Math.min(8e3,500*2**(t-1)),i=Math.round(r*(1-.5*n())),a=e instanceof J?e.retryAfter:void 0;return a===void 0?i:Math.max(a,i)}function Z(e,t){let n=e instanceof J?e.status:void 0;return n!==void 0&&!Ie(n)?{cause:e,reason:`rejected`,status:n}:{cause:e,reason:t?`unconfirmed`:`not-sent`,status:n}}function Re(e,t){if(e===null)return;let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?e*1e3:void 0}let r=He(n,t);return r===void 0?void 0:Math.max(0,r-t)}const ze=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Be=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Ve=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function He(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 Ue(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),Ue(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 Ue(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function Ue(e,t,n,r,i,a,o){let s=Number(t),c=ze.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=/* @__PURE__ */ 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=Be.indexOf(e),h=Ve.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const We=`lf_session_replay_recording`,Ge=`lf_session_replay_recording_owner`,Ke=72e5;var qe=class{state;resumed=!1;storage;owner;now;maxDurationMs;readOpenerState;constructor(e,t,n,r=()=>null){this.storage=e,this.now=t,this.owner=V(t),this.maxDurationMs=Math.min(n,Ke),this.readOpenerState=r;try{e?.getItem(`lf_session_replay_recording_owner`)===null&&(this.state=this.readResumableState()),e?.setItem(Ge,this.owner),e?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.storage=null,this.state=void 0)}catch{this.storage=null,this.state=void 0}this.resumed=this.state!==void 0}get(e){return this.state!==void 0&&this.isCurrent(this.state.id,e)?this.state.id:this.replace(e)}candidate(e){return{id:this.get(e),resumed:this.resumed}}replace(e){this.state={id:V(this.now),rumSessionId:e,startedAt:this.now()},this.resumed=!1;try{this.storage?.setItem(We,JSON.stringify(this.state))}catch{}return this.state.id}isCurrent(e,t){let n=this.state;if(n===void 0)return!1;let r=this.now();return n.id===e&&n.rumSessionId===t&&r>=n.startedAt&&r-n.startedAt<this.maxDurationMs}release(){try{this.storage?.getItem(`lf_session_replay_recording_owner`)===this.owner&&this.storage.removeItem(Ge)}catch{}}resume(){try{this.state=this.storage?.getItem(`lf_session_replay_recording_owner`)===null?this.readResumableState():void 0,this.storage?.setItem(Ge,this.owner),this.storage?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.state=void 0,this.storage=null)}catch{this.state=void 0,this.storage=null}this.resumed=this.state!==void 0}readResumableState(){let e=this.storage?.getItem(We),t=this.storage?.getItem(W);if(e==null||t==null)return;let n=null;try{n=this.readOpenerState()}catch{}if(n!==e)return Je(e,t)}};function Je(e,t){let n=JSON.parse(e),r=JSON.parse(t);if(typeof n!=`object`||!n||typeof r!=`object`||!r)return;let i=n,a=r;if(!(typeof i.id!=`string`||i.id.length===0||typeof i.rumSessionId!=`string`||typeof i.startedAt!=`number`||!Number.isFinite(i.startedAt)||a.id!==i.id||typeof a.seq!=`number`||!Number.isSafeInteger(a.seq)||a.seq<0))return{id:i.id,rumSessionId:i.rumSessionId,startedAt:i.startedAt}}function Ye(){try{if(typeof window>`u`||!window.isSecureContext)return;let e=globalThis.navigator?.locks;return typeof e?.request==`function`?e:void 0}catch{return}}async function Xe(e,t,n,r=1e3){return n.aborted?{kind:`aborted`}:new Promise(i=>{let a=!1,o=e=>{a||(a=!0,clearTimeout(c),n.removeEventListener(`abort`,l),i(e))},s=new AbortController,c=setTimeout(()=>{s.abort(),o({kind:`timeout`})},r),l=()=>{s.abort(),o({kind:`aborted`})};n.addEventListener(`abort`,l);let u=!1;try{e.request(`logfire-session-replay:${t}`,{mode:`exclusive`,signal:s.signal},async()=>{if(u=!0,a||n.aborted){o({kind:`aborted`});return}await new Promise(e=>{o({kind:`held`,lock:{release:e}})})}).catch(()=>{u||o({kind:`aborted`})})}catch{o({kind:`aborted`})}})}function Ze(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Qe(e){let t=e.random??Math.random;return t()<Ze(e.sessionSampleRate)?`full`:t()<Ze(e.onErrorSampleRate)?`buffer`:`off`}const $e=`lf_session_replay_seq:`,et=`lf_session_replay_probe`;var tt=class{storage;now;constructor(e,t){this.storage=e,this.now=t}read(e){try{return it(this.storage.getItem(rt(e)))?.seq}catch{return}}write(e,t){try{return this.storage.setItem(rt(e),JSON.stringify({seq:t,at:this.now()})),this.read(e)===t}catch{return!1}}prune(e){try{let t=this.now()-e,n=[];for(let e=0;e<this.storage.length;e+=1){let r=this.storage.key(e);if(r===null||!r.startsWith($e))continue;let i=it(this.storage.getItem(r));(i===void 0||i.at<t)&&n.push(r)}for(let e of n)this.storage.removeItem(e)}catch{}}};function nt(){try{let e=globalThis.localStorage;if(e===void 0)return null;e.setItem(et,`1`);let t=e.getItem(et)===`1`;return e.removeItem(et),t?e:null}catch{return null}}function rt(e){return`${$e}${e}`}function it(e){if(e!==null)try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return typeof n.seq!=`number`||!Number.isSafeInteger(n.seq)||n.seq<0||typeof n.at!=`number`||!Number.isFinite(n.at)?void 0:{seq:n.seq,at:n.at}}catch{return}}const at=/^[a-z][a-z0-9_]{0,63}$/u;function ot(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function st(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(!at.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`&&ot(r,200))&&(Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:r,writable:!0}),o+=1,o===20))break}return Object.freeze(a)}const ct={mode:`off`,recording:!1,getSessionId:()=>``,captureError:()=>void 0,getRecordingId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},lt=`lf_session_replay_mode`,Q=Symbol.for(`@pydantic/logfire-session-replay/controller`);function ut(e){if(typeof window>`u`||typeof document>`u`)return ct;let t=wt();try{let n=ft(e),r=new be({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return $(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=H(),s=new qe(o,n.now,n.maxSessionDurationMs,()=>window.opener?.sessionStorage.getItem(`lf_session_replay_recording`)??null),c=pt(n.now),l=a(!1),u=s.get(l),d,f=!1,p=!1,m=0,h=!0,g=Promise.resolve(),_=Promise.resolve(),v,y,b,x=!1,S=e=>{y!==void 0&&(e===void 0||y.recordingId===e)&&(y.lock.release(),y=void 0)},C=(e,t,r=!t,i=!1)=>{let c=mt(n,e,o);if(!(c===`off`||f||p||d!==void 0||e!==l))try{x=i&&s.candidate(e).resumed;let t=u;d=dt({config:n,getSessionId:a,mode:c,onSessionChanged:O,samplingModeStorage:o,sessionId:e,recordingId:t,isCurrentRecording:()=>s.isCurrent(t,a(!1)),holdUntilActivity:r,awaitBinding:i})}catch(e){if(d=void 0,t)throw e;$(n.onError,e)}},w=(e,t,n)=>({initialSeq:n,write:n=>e.records.write(t,n),onFailure:()=>{queueMicrotask(()=>{!f&&u===t&&(s.replace(l),O(l,!1))})}}),T=async(e,t,r)=>{b?.abort();let i=new AbortController;b=i;let a=()=>i.signal.aborted||f||p||m!==r||l!==t,o=s.candidate(t);u=o.id;let c=()=>{o={id:s.replace(t),resumed:!1},u=o.id};for(let t=0;t<2;t+=1){let t=await Xe(e.locks,o.id,i.signal);if(t.kind===`aborted`)return;if(t.kind===`timeout`){c();continue}if(a()||u!==o.id){t.lock.release();return}let n;if(o.resumed?n=e.records.read(o.id):e.records.write(o.id,0)&&(n=0),n===void 0){t.lock.release(),c();continue}return y={recordingId:o.id,lock:t.lock},{recordingId:o.id,sequenceRecord:w(e,o.id,n)}}$(n.onError,/* @__PURE__ */ Error(`logfire session replay: could not claim a replay recording`))},E=async(e,t,r,i)=>{try{let n=await T(e,t,r),a=!f&&!p&&m===r&&l===t;if(n===void 0){a&&d?.transport.isAwaitingBinding()===!0&&(d.discard(),d=void 0);return}if(!a){S(n.recordingId);return}if(d!==void 0&&d.recordingId!==n.recordingId&&(d.discard(),d=void 0,C(t,!1,i,!0)),d===void 0||d.recordingId!==n.recordingId){S(n.recordingId);return}x=!1,d.transport.bind(n.sequenceRecord)}catch(e){$(n.onError,e)}},D=async(e,t,n)=>{C(e,!1,n,c!==void 0),c!==void 0&&d!==void 0&&await E(c,e,t,n)},O=(e,t=!0)=>{if(f||p)return;let r=s.get(e);if(e===l&&r===u)return;let i=u;l=e,u=r,b?.abort();let a=d;d=void 0;let o=a?.deactivate()??Promise.resolve(),c=m;g=g.then(async()=>{await St(o,n.onError),S(i),!f&&m===c&&l===e&&u===r&&await D(e,c,t)})},ee;try{if(c===void 0)C(l,!0);else if(c.records.prune(Ke),C(l,!0,!1,!0),d!==void 0){let e=l,t=m;g=g.then(async()=>E(c,e,t,!1))}ee=setInterval(()=>{O(a(!1))},1e3)}catch(e){throw d?.discard(),d=void 0,b?.abort(),S(),s.release(),e}let k=()=>{p=!0,m+=1,b?.abort();let e=d;d=void 0;let t=e?.deactivate(!0)??Promise.resolve();S(),_=Promise.all([_,g,St(t,n.onError)]).then(()=>void 0),g=Promise.resolve(),h=e?.transport.canResumeSequence()??h,h&&s.release()},A=e=>{if(!e.persisted||f)return;d?.discard(),d=void 0;let t=m;g=g.then(async()=>{let e=()=>f||m!==t;if(e())return;let n=new AbortController;b=n;let r,i=!1;if(c!==void 0){let e=await Xe(c.locks,u,n.signal);if(e.kind===`aborted`)return;e.kind===`held`&&(r=e.lock),i=e.kind===`timeout`}else await new Promise(e=>{setTimeout(e,0)});try{if(e())return;p=!1,s.resume(),l=a(!1),u=i?s.replace(l):s.get(l),h=!0}finally{r?.release()}await D(l,t,!1)})};return window.addEventListener(`pagehide`,k),window.addEventListener(`pageshow`,A),{get mode(){try{return d?.transport.getMode()??`off`}catch(e){return $(n.onError,e),`off`}},get recording(){try{return d!==void 0}catch(e){return $(n.onError,e),!1}},getSessionId:()=>a(!1),captureError:(e,t)=>{try{d?.captureError(e,t)}catch(e){$(n.onError,e)}},getRecordingId:()=>d===void 0||x&&d.transport.isAwaitingBinding()?``:s.isCurrent(d.recordingId,a(!1))?d.recordingId:``,flush:async()=>{try{await g,await d?.transport.flush()}catch(e){$(n.onError,e)}},stop:async()=>(v??=(async()=>{f=!0,m+=1,b?.abort(),clearInterval(ee),window.removeEventListener(`pagehide`,k),window.removeEventListener(`pageshow`,A);let e=d;d=void 0,await St(e?.deactivate()??Promise.resolve(),n.onError),await g,await _,r.flushPendingStorage(),h=e?.transport.canResumeSequence()??h,h&&s.release(),S(),t()})(),v)}}catch(e){throw t(),e}}function dt(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:a,samplingModeStorage:o,sessionId:c,recordingId:l,isCurrentRecording:u,awaitBinding:f}=e,p=st(t.getSessionAttributes,e=>{$(t.onError,e)}),m,h=new De(t,l,i,void 0,void 0,p,{holdUntilActivity:r,takeFullSnapshot:()=>{m.takeFullSnapshot()},awaitBinding:f}),g=[],_=!0,v=()=>_,y;try{m=fe({beforeUserActivity:()=>{if(_&&h.isHeld())try{let e=n(!0);if(e!==c||!u()){a(e,!1);return}h.releaseHeld(()=>{m.takeFullSnapshot()})}catch(e){$(t.onError,e)}},emit:e=>{if(_)try{let t=n(d(e));if(t!==c||!u()){a(t,!1);return}h.add(e)}catch(e){$(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:Math.max(3e5,t.minSessionDurationMs),redactUrlPatterns:t.redactUrlPatterns}),g.push(()=>{m.stop()});let e=(e,n)=>{if(_)try{m.addCustomEvent(e,n)}catch(e){$(t.onError,e)}},r=n=>{v()&&(h.releaseHeld(()=>{m.takeFullSnapshot()}),e(s.Error,n),v()&&h.getMode()===`buffer`&&(gt(o,c,`full`),xt(h.triggerFlush(),t.onError)))},f=/* @__PURE__ */ new WeakSet,p=e=>typeof e!=`object`||!e||!f.has(e)&&(f.add(e),!0),b=(e,t)=>{if(p(e)){let n=Et(vt(e),void 0,yt(e));r(typeof t?.timestamp==`number`?{...n,timestamp:t.timestamp}:n)}},x=e=>{e instanceof ErrorEvent&&p(e.error)&&r(Et(e.message,e.filename,yt(e.error)))},S=e=>{b(e.reason)},C=()=>{document.visibilityState===`hidden`&&xt(h.flush({background:!0}),t.onError)},w=()=>{xt(h.flush({keepalive:!0}),t.onError)};return t.captureGlobalErrors&&(window.addEventListener(`error`,x,!0),g.push(()=>{window.removeEventListener(`error`,x,!0)}),window.addEventListener(`unhandledrejection`,S,!0),g.push(()=>{window.removeEventListener(`unhandledrejection`,S,!0)})),document.addEventListener(`visibilitychange`,C),g.push(()=>{document.removeEventListener(`visibilitychange`,C)}),window.addEventListener(`pagehide`,w),g.push(()=>{window.removeEventListener(`pagehide`,w)}),t.captureConsole&&g.push(D(e,{onError:t.onError})),t.captureNetwork&&g.push(O(e,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&g.push(ee(e,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),h.start(),{sessionId:c,recordingId:l,transport:h,captureError:b,deactivate:async(e=!1)=>(y??=(async()=>{let t=h.shutdown({keepalive:e});_=!1,Tt(g),await t})(),y),discard:()=>{_=!1,Tt(g),h.discard()}}}catch(e){throw _=!1,Tt(g),h.discard(),e}}function ft(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,getUser:e.getUser,captureConsole:e.captureConsole??l.captureConsole,captureNetwork:e.captureNetwork??l.captureNetwork,captureNavigation:e.captureNavigation??l.captureNavigation,captureGlobalErrors:e.captureGlobalErrors??l.captureGlobalErrors,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...l.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function pt(e){let t=Ye();if(t===void 0)return;let n=nt();return n===null?void 0:{locks:t,records:new tt(n,e)}}function mt(e,t,n){let r=ht(n,t);if(r!==void 0)return r;let i=Qe({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return gt(n,t,i),i}function ht(e,t){if(e!==null)try{let n=e.getItem(lt);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!_t(i.mode)?void 0:i.mode}catch{return}}function gt(e,t,n){if(e!==null)try{e.setItem(lt,JSON.stringify({id:t,mode:n}))}catch{}}function _t(e){return e===`full`||e===`buffer`||e===`off`}function vt(e){return Dt(bt(e,`message`)??e)}function yt(e){let t=bt(e,`stack`);return typeof t==`string`?t:void 0}function bt(e,t){try{return typeof e==`object`&&e&&t in e?e[t]:void 0}catch{return}}function xt(e,t){e.catch(e=>{$(t,e)})}async function St(e,t){try{await e}catch(e){$(t,e)}}function $(e,t){try{let n=e?.(t);Ct(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Ct(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function wt(){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 Tt(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function Et(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function Dt(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{return Object.prototype.toString.call(e)}catch{return`[object Object]`}}export{c as CHUNK_ENVELOPE_VERSION,s as CustomTag,i as EventType,a as IncrementalSource,o as MouseInteractions,U as ReplayUploadError,ut 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:1e4,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:72e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,captureGlobalErrors:!0,redactUrlPatterns:[/.+/u]},u=/* @__PURE__ */ 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,r){let i=p(e,t)?g(e,n):e;return r===void 0?i:h(i,r)}function h(e,t){try{let n=t(e);return typeof n==`string`?n:e}catch{return e}}function g(e,t){try{let n=new URL(e,t);return n.origin===`null`||n.protocol===`blob:`?n.protocol:`${n.origin}${n.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const _=/https?:\/\/[^\s"<>`]+/giu,v=/:\d+:\d+\)?$/u,y=/(?=https?:\/\/)/iu,b=/^\s*at\s/u;function x(e,t){return(t?v.exec(e)?.[0]:void 0)??S(e)}function S(e){let t=e.length;for(;t>0&&(e[t-1]===`)`||e[t-1]===`'`);)t--;return e.slice(t)}function C(e,t,n){return p(e,t)||e.split(y).some(e=>p(e,t))?g(e,n):e}function w(e,t,n,{stackTrace:r=!1}={}){return t.length===0?e:e.split(`
|
|
2
|
+
`).map(e=>{let i=r&&b.test(e);return e.replace(_,(a,o)=>{let s=x(a,i||r&&e[o-1]===`@`);return`${C(a.slice(0,a.length-s.length),t,n)}${s}`})}).join(`
|
|
3
|
+
`)}function ee(e,t){let n=``,r=0;for(;r<e.length;){let i=r;for(;r<e.length&&/[\s,]/u.test(e[r]??``);)r++;if(n+=e.slice(i,r),r>=e.length)break;let a=r;for(;r<e.length&&!/\s/u.test(e[r]??``);)r++;let o=r;for(;o>a&&e[o-1]===`,`;)o--;if(n+=t(e.slice(a,o))+e.slice(o,r),o<r)continue;let s=r;for(;r<e.length&&e[r]!==`,`;)r++;n+=e.slice(s,r)}return n}const T=/\\|url|image-set|src\(/iu;function E(e){return T.test(e)}function D(e,t){if(e.length<=t)return[e,0];let n=e.charCodeAt(t-1),r=n>=55296&&n<=56319?t-1:t;return[e.slice(0,r),e.length-r]}function O(e){return e===0?``:`...(+${String(e)} chars)`}function k(e,t){let[n,r]=D(e,t);return`${n}${O(r)}`}const A=[`log`,`info`,`warn`,`error`,`debug`],te=()=>void 0;function ne(e,t={}){let n=[],r=le(t.onError);try{for(let t of A)typeof console[t]==`function`&&n.push(M(console,t,(n,i)=>function(...a){return i()&&j(e,s.Console,{level:t,args:a.slice(0,10).map(de)},r),n.apply(this,a)}));return N(n)}catch(e){throw P(n),e}}function re(e,t){let n=se(t),r={...n,onError:le(n.onError)},i=ae(e,r);try{return N([i,oe(e,r)])}catch(e){throw i(),e}}function ie(e,t={redactUrlPatterns:[]}){let n=le(t.onError),r=r=>{let i=m(window.location.href,t.redactUrlPatterns??[],window.location.href,t.transformUrl);j(e,s.Navigation,{url:i,kind:r},n)},i=[];try{i.push(M(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(M(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)}),N(i)}catch(e){throw P(i),e}}function ae(e,t){return typeof window.fetch==`function`?M(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=fe(i,a),u=pe(i);if(_e(u,t.ignoreUrlPatterns))return o.call(this,i,a);let d=m(u,t.redactUrlPatterns,window.location.href,t.transformUrl),f=ge(a?.body);try{let n=await o.call(this,i,a);return r()&&j(e,s.Network,I({method:l,url:d,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:f,resBytes:me(n.headers)}),t.onError),n}catch(n){throw r()&&j(e,s.Network,I({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}):te}function oe(e,t){let n=window.XMLHttpRequest.prototype,r=/* @__PURE__ */ new WeakMap,i=[];try{return i.push(M(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return _e(s,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:a.toUpperCase(),url:m(s,t.redactUrlPatterns,window.location.href,t.transformUrl),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(M(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=ge(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()&&j(e,s.Network,I({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:he(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()&&j(e,s.Network,I({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),N(i)}catch(e){throw P(i),e}}function se(e){return{...e,ignoreUrlPatterns:ce(e.ignoreUrlPatterns),redactUrlPatterns:ce(e.redactUrlPatterns)}}function ce(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function j(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function le(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);ue(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function ue(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function M(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return te;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function N(e){let t=!1;return()=>{t||(t=!0,P(e))}}function P(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function de(e){if(e==null)return String(e);if(typeof e==`string`)return F(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return F(e.stack??`${e.name}: ${e.message}`);try{return F(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function F(e){return k(e,1024)}function fe(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function pe(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function me(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 he(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 I(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 ge(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 _e(e,t){return p(e,t)}const ve=/* @__PURE__ */ new Set([`action`,`background`,`cite`,`data`,`formaction`,`href`,`poster`,`rr_src`,`src`,`xlink:href`]),ye=/* @__PURE__ */ new Set([`imagesrcset`,`srcset`]),be=/* @__PURE__ */ new Set([`alt`,`aria-description`,`aria-label`,`aria-placeholder`,`aria-roledescription`,`aria-valuetext`,`label`,`placeholder`,`title`]),xe=/* @__PURE__ */ new Set([`data-active`,`data-align`,`data-bs-theme`,`data-checked`,`data-disabled`,`data-headlessui-state`,`data-highlighted`,`data-orientation`,`data-placement`,`data-popper-placement`,`data-selected`,`data-side`,`data-size`,`data-slot`,`data-state`,`data-theme`,`data-variant`]),Se=/* @__PURE__ */ new Set([``,`false`,`true`]),Ce=/* @__PURE__ */ new Set([`button`,`reset`,`submit`]),we={color:!0,date:!0,"datetime-local":!0,email:!0,hidden:!0,month:!0,number:!0,password:!0,range:!0,search:!0,select:!0,tel:!0,text:!0,textarea:!0,time:!0,url:!0,week:!0};function Te(t){let n=()=>{t.beforeUserActivity?.()},r={maskTextAttributes:t.maskAllText,patterns:t.redactUrlPatterns,transformUrl:t.transformUrl},i={emit:e=>{t.emit(Ee(e,r))},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.maskAllInputs?i.maskInputOptions=we:i.maskAllInputs=!1,t.maskAllText?i.maskTextSelector=`*`:t.maskTextSelector!==void 0&&t.maskTextSelector.length>0&&(i.maskTextSelector=t.maskTextSelector),t.blockSelector!==void 0&&t.blockSelector.length>0&&(i.blockSelector=t.blockSelector),t.checkoutEveryNms!==void 0&&t.checkoutEveryNms>0&&(i.checkoutEveryNms=t.checkoutEveryNms);let a=e(i);if(a===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{a()},addCustomEvent:(t,n)=>{e.addCustomEvent(t,n)},takeFullSnapshot:()=>{e.takeFullSnapshot(!0)}}}function Ee(e,t){if(typeof e.data!=`object`||e.data===null)return e;let n=e.data;if(e.type===i.Custom)return De(e,n,t.patterns);if(e.type===i.Meta){if(typeof n.href!=`string`)return e;let r=m(n.href,t.patterns,window.location.href,t.transformUrl);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=L(n,t);return r===n?e:{...e,data:r}}function De(e,t,n){let r=t.payload;if(typeof r!=`object`||!r)return e;let i=r,a=window.location.href,o;if(t.tag===s.Error)o={...i},typeof i.message==`string`&&(o.message=Oe(i.message,1024,e=>w(e,n,a))),typeof i.source==`string`&&(o.source=m(i.source,n,a)),typeof i.stack==`string`&&(o.stack=Oe(i.stack,8192,e=>w(e,n,a,{stackTrace:!0})));else if(t.tag===s.Console&&Array.isArray(i.args))o={...i,args:i.args.map(e=>typeof e==`string`?w(e,n,a):e)};else return e;return{...e,data:{...t,payload:o}}}function Oe(e,t,n){let[r,i]=D(e,t);return`${n(r)}${O(i)}`}function L(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=L(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)?ke(a,t):L(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function ke(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=t.maskTextAttributes&&typeof n.type==`string`&&Ce.has(n.type.toLowerCase()),i=!1,a={};for(let[e,o]of Object.entries(n)){let n=e.toLowerCase(),s=r&&n===`value`?Ne(o):Ae(n,o,t);s!==o&&(i=!0),a[e]=s}return i?a:e}function Ae(e,t,n){let r=e=>m(e,n.patterns,window.location.href,n.transformUrl);return e===`style`?n.patterns.length>0||n.transformUrl!==void 0?Me(t):t:typeof t==`string`?ve.has(e)?r(t):ye.has(e)?ee(t,r):n.maskTextAttributes&&je(e,t)?Ne(t):t:t}function je(e,t){return be.has(e)?!0:e.startsWith(`data-`)&&!e.startsWith(`data-rr-`)&&!xe.has(e)&&!Se.has(t)}function Me(e){if(typeof e==`string`)return E(e)?``:e;if(typeof e!=`object`||!e||Array.isArray(e))return e;let t=!1,n={};for(let[r,i]of Object.entries(e)){let e=Array.isArray(i)?i[0]:i,a=typeof e==`string`&&E(e)?``:i;a!==i&&(t=!0),n[r]=a}return t?n:e}function Ne(e){return typeof e==`string`?e.replace(/\S/gu,`*`):e}function R(e){return typeof e==`object`&&e?e:void 0}function z(e){return typeof e==`string`&&e.length>0?e:void 0}function Pe(e){let t=R(e),n=z(t?.id);if(t===void 0||n===void 0)return;let r=z(t.name),i=z(t.email);return{id:n,...r===void 0?{}:{name:r},...i===void 0?{}:{email:i}}}function Fe(e,t,n,r={},c){let l=1/0,u=0,d=0,f=0,p=0,m=!1,h=/* @__PURE__ */ new Set;for(let e of t){e.timestamp<l&&(l=e.timestamp),e.timestamp>u&&(u=e.timestamp);let t=R(e.data);if(e.type===i.FullSnapshot)m=!0;else if(e.type===i.Meta){let e=z(t?.href);e!==void 0&&h.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)&&d++}else e===a.Input&&f++}else if(e.type===i.Custom&&t!==void 0){let e=z(t.tag),n=R(t.payload);if(e===s.Error)p++;else if(e===s.Console)n?.level===`error`&&p++;else if(e===s.Navigation){let e=z(n?.url);e!==void 0&&h.add(e)}}}return{seq:e,firstTimestamp:l===1/0?0:l,lastTimestamp:u,eventCount:t.length,clickCount:d,keypressCount:f,errorCount:p,hasFullSnapshot:m,urls:[...h],...n!==void 0&&n.length>0?{distinctId:n}:{},...c===void 0?{}:{user:{...c}},...Object.keys(r).length===0?{}:{sessionAttributes:{...r}}}}function B(e=Date.now){let t=e(),n=new Uint8Array(/* @__PURE__ */ new ArrayBuffer(16));Ie(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/256)&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 Ie(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 Le=`lf_session_replay`;var Re=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?V():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:B(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(Le);if(e!==null){let t=JSON.parse(e);if(ze(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(Le,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 V(){try{return globalThis.sessionStorage??null}catch{return null}}function ze(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)}var H=class extends Error{droppedSeqs;reason;seq;sessionId;status;constructor(e){super(Be(e),{cause:e.cause}),this.name=`ReplayUploadError`,this.droppedSeqs=Object.freeze([...e.droppedSeqs??[]]),this.reason=e.reason,this.seq=e.seq,this.sessionId=e.sessionId,this.status=e.status}};function Be(e){let t=e.seq===void 0?`replay chunk`:`replay chunk seq=${String(e.seq)}`,n=e.cause instanceof Error?`: ${e.cause.message}`:``;return`${t} ${e.reason}${n}`}const U=`lf_session_replay_seq`,W=1e4,Ve=3e4,G=48e3,He=1e6,Ue=.9,We={gzip:t,gzipSync:n};var Ge=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;queue=[];retainedBytes=0;activeUpload;drainPromise;draining=!1;pagehideUploads=/* @__PURE__ */ new Set;lifecycleFlights=/* @__PURE__ */ new Set;closed=!1;shuttingDown=!1;wakeRetry;retryAbort=new AbortController;deadlineAbort=new AbortController;resyncPending=!1;resyncTimer;lastResyncAt;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;takeFullSnapshot;sequenceRecord;sequenceRecordFailed=!1;awaitingBinding;bindingBufferIncomplete=!1;constructor(e,t,n,r=V(),i=We,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.sequenceRecord=o.sequenceRecord,this.awaitingBinding=o.awaitBinding===!0,this.minimumDurationSatisfied=e.minSessionDurationMs===0,this.seq=o.sequenceRecord?.initialSeq??this.readPersistedSequence()??0,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=J(e);if(this.resyncPending){this.addDuringResync(e,t);return}if(this.refreshingMinimumSnapshot){this.buffer.push(e),this.pendingBytes+=t;return}let n=!this.minimumDurationSatisfied;if(this.mode===`buffer`||this.held||n||this.awaitingBinding){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:J(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.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=n,n&&this.finishMinimumBufferingEvent();return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=n,n&&this.finishMinimumBufferingEvent();return}}if(e.type===i.Meta&&this.mode===`full`&&this.buffer.length>0&&this.flushAndReport(),this.buffer.push(e),this.pendingBytes+=t,n&&this.minimumDurationReached()){this.flushAndReport();return}this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&e.type!==i.Meta?this.flushAndReport():this.scheduleFlush()}addDuringResync(e,t){if(e.type===i.Meta){this.buffer=[e],this.pendingBytes=t;return}if(e.type!==i.FullSnapshot)return;let n=this.buffer.length===1&&this.buffer[0]?.type===i.Meta?this.buffer[0]:void 0;this.buffer=n===void 0?[e]:[n,e],this.pendingBytes=t+(n===void 0?0:J(n)),this.resyncPending=!1,this.clearResyncTimer(),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={}){if(this.closed)return;if(e.keepalive!==!0)return this.flushInternal(e);this.activeUpload!==void 0&&(this.activeUpload.background=!0,this.activeUpload.pagehide=!0);let t=this.queue.filter(e=>(e!==this.activeUpload||!e.attempting)&&!this.pagehideUploads.has(e));for(let e of t)this.pagehideUploads.add(e),e.background=!0;this.wakeRetry?.();let n=this.trackLifecycle(Promise.all(t.map(async e=>this.finalAttempt(e))).then(()=>void 0));await Promise.all([this.flushInternal(e),n])}async flushInternal(e={}){if(this.closed||this.mode===`buffer`||this.held||this.awaitingBinding||this.buffer.length===0||!this.minimumDurationReached()||(this.clearScheduledFlush(),this.minimumBufferIncomplete&&!this.refreshMinimumBuffer()))return;this.minimumDurationSatisfied=!0;let t=this.buffer,n=this.pendingBytes;this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0;let r=this.sessionId,i=this.snapshotIdentity();if(e.keepalive===!0){let e=this.splitKeepaliveEventChunks(t,i,Math.max(0,G-this.reservedKeepaliveBytes)),n=this.allocateSeq(e.length);if(n===void 0)return;await this.trackLifecycle(this.deliverLifecycle(e,n,r,i));return}if(e.background===!0){let e=[];for(let n of this.splitKeepaliveEventChunks(t,i)){let t=this.enqueue(n.events,n.eventBytes,r,i,!0,n);if(t===void 0)break;e.push(t)}await Promise.all(e.map(async e=>e.done));return}await this.enqueue(t,n,r,i)?.done}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held||this.awaitingBinding||!this.minimumDurationReached()){this.discard(),await this.settleWithinDeadline([]);return}if(e.keepalive===!0){await this.flush(e),this.closed=!0,this.clearResyncTimer(),await this.settleWithinDeadline([]);return}let t=this.flushInternal();this.closed=!0,this.shuttingDown=!0,this.clearResyncTimer(),this.retryAbort.abort();let n=this.queue.filter(e=>e!==this.activeUpload&&!this.pagehideUploads.has(e)).map(async e=>this.finalAttempt(e));await this.settleWithinDeadline([t,...n])}discard(){this.started=!1,this.closed=!0,this.clearScheduledFlush(),this.clearResyncTimer(),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=>{K(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){K(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)}snapshotIdentity(){let e=this.snapshotUser(),t=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{t=this.config.getDistinctId()??this.config.distinctId}catch(e){K(this.config.onError,e)}else e!==void 0&&(t=e.id);return{distinctId:t,user:e}}createEnvelope(e,t,n){return{version:1,meta:Fe(t,e,n.distinctId,this.sessionAttributes,n.user),events:e}}snapshotUser(){if(this.config.getUser!==void 0)try{return Pe(this.config.getUser())}catch(e){K(this.config.onError,e);return}}allocateSeq(e){let t=this.seq,n=this.sequenceRecord;if(n!==void 0){if(this.sequenceRecordFailed)return;if(!n.write(t+e)){this.sequenceRecordFailed=!0,this.discard();try{n.onFailure()}catch(e){K(this.config.onError,e)}return}}return this.seq+=e,this.saveSeq(this.sessionId,this.seq),t}enqueue(e,t,n,r,a=!1,o){let s=Math.max(2e6,2*this.config.maxBufferBytes);if(this.queue.length>0&&this.retainedBytes+t>s){K(this.config.onError,new H({cause:/* @__PURE__ */ Error(`replay upload queue is full`),reason:`not-sent`,seq:void 0,sessionId:n})),this.beginResync();return}let c=this.allocateSeq(1);if(c===void 0)return;let l=()=>void 0,u={body:void 0,done:new Promise(e=>{l=e}),events:e,hasFullSnapshot:e.some(e=>e.type===i.FullSnapshot),identity:r,reachedFetch:!1,attempting:!1,background:a,pagehide:!1,prepared:o,resolve:l,retainedBytes:t,seq:c,sessionId:n,settled:!1};return this.queue.push(u),this.retainedBytes+=t,this.draining||(this.draining=!0,this.drainPromise=this.drain()),u}async drain(){try{for(;!this.shuttingDown;){let e=this.queue.find(e=>!this.pagehideUploads.has(e));if(e===void 0)break;this.activeUpload=e;let t=await this.deliverQueued(e);this.activeUpload=void 0,this.settle(e,t)}}finally{this.activeUpload=void 0,this.draining=!1}}async deliverQueued(e){let t=await this.compressQueued(e);if(t!==void 0||e.settled)return t;let n=Date.now(),r;for(let t=1;;t++){if(this.pagehideUploads.has(e))return e.done.then(()=>void 0);let i=Ve-(Date.now()-n);if(t>1&&i<=0)return Y(r,e.reachedFetch);let a=await this.attemptQueued(e,Math.min(W,i));if(a===void 0)return;r=a;let o=nt(a,t,this.config.random);if(o===void 0||this.shuttingDown||e.pagehide||Date.now()-n+o>=Ve)return Y(a,e.reachedFetch);await this.backoff(o)}}retainCompressedBody(e,t){this.retainedBytes+=t.byteLength-e.retainedBytes,e.retainedBytes=t.byteLength,e.body=t,e.events=void 0}compressQueuedSync(e){let t=e.prepared;if(e.prepared=void 0,!(e.body!==void 0||e.events===void 0||e.settled)){if(t?.body!==void 0&&t.events===e.events){this.retainCompressedBody(e,t.body);return}try{let t=r(JSON.stringify(this.createEnvelope(e.events,e.seq,e.identity)));this.retainCompressedBody(e,this.compression.gzipSync(t));return}catch(e){return{cause:e,reason:`not-sent`}}}}async compressQueued(e){if(this.shuttingDown||e.background)return this.compressQueuedSync(e);if(e.body!==void 0||e.events===void 0)return;let t=e.events;try{let n=r(JSON.stringify(this.createEnvelope(t,e.seq,e.identity))),i=await this.compressOrdinary(n);if(e.events!==t)return await this.compressQueued(e);e.settled||this.retainCompressedBody(e,i);return}catch(e){return{cause:e,reason:`not-sent`}}}async attemptQueued(e,t=W){let n=e.body;if(n!==void 0){e.attempting=!0;try{await this.send(this.prepareUpload(n,e.seq,e.sessionId,e.background),()=>{e.reachedFetch=!0},t);return}catch(e){return e}finally{e.attempting=!1}}}async finalAttempt(e){let t=e.background?this.compressQueuedSync(e):await this.compressQueued(e);if(t!==void 0){this.settle(e,t);return}let n=await this.attemptQueued(e);this.settle(e,n===void 0?void 0:Y(n,e.reachedFetch))}async trackLifecycle(e){this.lifecycleFlights.add(e);let t=()=>{this.lifecycleFlights.delete(e)};return e.then(t,t),e}async settleWithinDeadline(e){let t=Promise.all([...e,this.drainPromise,...this.lifecycleFlights]).then(()=>void 0,()=>void 0),n,r=new Promise(e=>{n=setTimeout(e,W)});if(await Promise.race([t,r]),clearTimeout(n),this.shuttingDown){this.deadlineAbort.abort(/* @__PURE__ */ Error(`replay upload did not finish before shutdown`));for(let e of[...this.queue])this.settle(e,{cause:/* @__PURE__ */ Error(`replay upload did not finish before shutdown`),reason:e.reachedFetch?`unconfirmed`:`not-sent`})}}settle(e,t){if(e.settled)return;e.settled=!0,this.pagehideUploads.delete(e),this.retainedBytes-=e.retainedBytes;let n=this.queue.indexOf(e);n>=0&&this.queue.splice(n,1),e.body=void 0,e.events=void 0,e.resolve(),t!==void 0&&this.handleSequencedLoss(e.seq,e.sessionId,t)}handleSequencedLoss(e,t,n){let r=[];if(!this.shuttingDown){let t=!1;for(let n of[...this.queue])if(!(n.seq<e)){if(n.events===void 0){if(n.hasFullSnapshot){t=!0;break}continue}if(n.hasFullSnapshot){let e=Ye(n.events),r=Xe(e);this.retainedBytes+=r-n.retainedBytes,n.retainedBytes=r,n.events=e,t=!0;break}r.push(n.seq),this.settle(n,void 0)}!t&&!this.trimBufferToAnchor()&&this.beginResync()}K(this.config.onError,new H({cause:n.cause,droppedSeqs:r,reason:n.reason,seq:e,sessionId:t,status:n.status}))}trimBufferToAnchor(){return this.buffer.some(e=>e.type===i.FullSnapshot)?(this.buffer=Ye(this.buffer),this.pendingBytes=Xe(this.buffer),!0):!1}beginResync(){this.closed||(this.resyncPending=!0,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.clearScheduledFlush(),this.scheduleResyncSnapshot())}scheduleResyncSnapshot(){if(this.resyncTimer!==void 0||this.closed)return;let e=this.lastResyncAt===void 0?0:Math.max(0,this.lastResyncAt+6e4-this.config.now());this.resyncTimer=setTimeout(()=>{this.resyncTimer=void 0,this.takeResyncSnapshot()},e)}takeResyncSnapshot(){if(this.resyncPending&&!this.closed&&this.takeFullSnapshot!==void 0){this.lastResyncAt=this.config.now();try{this.takeFullSnapshot()}catch(e){K(this.config.onError,e),this.scheduleResyncSnapshot();return}this.isResyncPending()&&(K(this.config.onError,/* @__PURE__ */ Error(`replay resync snapshot produced no full snapshot`)),this.scheduleResyncSnapshot())}}isResyncPending(){return this.resyncPending}clearResyncTimer(){this.resyncTimer!==void 0&&(clearTimeout(this.resyncTimer),this.resyncTimer=void 0)}async backoff(e){let t=this.retryAbort.signal;t.aborted||await new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),this.wakeRetry===r&&(this.wakeRetry=void 0),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r),this.wakeRetry=r})}prepareUpload(e,t,n,r){let i=r&&this.reservedKeepaliveBytes+e.byteLength<=G?e.byteLength:0;return this.reservedKeepaliveBytes+=i,{body:e,seq:t,sessionId:n,reservedBytes:i,requestKeepalive:i>0}}splitKeepaliveEventChunks(e,t,n=1/0){let i=e.map(J),a=[],o=n,s,c=0;for(;c<e.length;){let l=Math.min(G,o);if(l<4800){a.push({events:e.slice(c),eventBytes:Ze(i,c,e.length)});break}let u=this.seq+a.length,d=s===void 0?He:Math.min(He,l*s*Ue),f=Qe(i,c,d);for(;;){let d=e.slice(c,f),p=Ze(i,c,f),m;try{m=this.compression.gzipSync(r(JSON.stringify(this.createEnvelope(d,u,t))))}catch{a.push({events:d,eventBytes:p}),o=Number.isFinite(n)?0:o;break}if(s=p/Math.max(1,m.byteLength),m.byteLength<=l){a.push({events:d,eventBytes:p,body:m}),o-=m.byteLength;break}if(f-c===1){Number.isFinite(n)?(a.push({events:e.slice(c),eventBytes:Ze(i,c,e.length)}),f=e.length):a.push({events:d,eventBytes:p,body:m});break}f=Math.max(c+1,Math.min(f-1,Qe(i,c,l*s*Ue)))}c=f}return a}async deliverLifecycle(e,t,n,i){let a=[];for(let o=0;o<e.length;o++){let s=e[o];if(s===void 0){a.push(void 0);continue}try{a.push({body:s.body??this.compression.gzipSync(r(JSON.stringify(this.createEnvelope(s.events,t+o,i)))),requestKeepalive:!1,reservedBytes:0,seq:t+o,sessionId:n})}catch(e){this.handleSequencedLoss(t+o,n,{cause:e,reason:`not-sent`}),a.push(void 0)}}let o=!0,s=Math.max(0,G-this.reservedKeepaliveBytes);for(let e of a){if(e===void 0){o=!1;continue}o&&e.body.byteLength<=s?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,s-=e.reservedBytes):o=!1}await Promise.all(a.map(async e=>{if(e===void 0)return;let t=!1;try{await this.send(e,()=>{t=!0})}catch(n){this.handleSequencedLoss(e.seq,e.sessionId,Y(n,t))}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await $e(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async send(e,t,n=W){let r,i,a,o=new AbortController,s=setTimeout(()=>{o.abort(/* @__PURE__ */ Error(`replay upload timed out after ${String(n)}ms`))},n),c=this.deadlineAbort.signal,l=()=>{o.abort(c.reason)};c.addEventListener(`abort`,l);try{let n=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,s=await Je(this.getUploadHeaders(),o.signal);t();let c=this.config.fetchImpl(n,{method:`POST`,headers:s,body:e.body.slice(),keepalive:e.requestKeepalive,signal:o.signal});r=!0;let l=await c;if(i=!0,a=await et(l),!l.ok){let e=l.status===429||l.status===503?rt(l.headers.get(`retry-after`),Date.now()):void 0;throw new q(l.status,e)}}finally{clearTimeout(s),c.removeEventListener(`abort`,l),e.reservedBytes>0&&(r!==!0||i!==!0||a===!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 qe(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`}}canResumeSequence(){return this.awaitingBinding?!0:this.readPersistedSequence()===this.seq}isAwaitingBinding(){return this.awaitingBinding}bind(e){this.awaitingBinding&&!this.closed&&(this.sequenceRecord=e,this.seq=e.initialSeq,this.awaitingBinding=!1,this.bindingBufferIncomplete&&(this.bindingBufferIncomplete=!1,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.takeFullSnapshot?.()),!(this.mode!==`full`||this.held||this.buffer.length===0)&&(this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()))}readPersistedSequence(){if(this.storage!==null)try{let e=this.storage.getItem(U);if(e===null)return;let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return n.id===this.sessionId&&typeof n.seq==`number`&&Number.isSafeInteger(n.seq)&&n.seq>=0?n.seq:void 0}catch{return}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(U,JSON.stringify({id:e,seq:t}))}catch{}}};function K(e,t){try{let n=e?.(t);Ke(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Ke(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var q=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 qe(e){return typeof e==`function`?e():e}async function Je(e,t){if(t.aborted)throw t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e instanceof Error?e:Error(String(e)))})})}function J(e){try{return r(JSON.stringify(e)).byteLength}catch{return 0}}function Ye(e){let t=e.findIndex(e=>e.type===i.FullSnapshot);if(t<0)return e;let n=t>0&&e[t-1]?.type===i.Meta?t-1:t;return e.slice(n)}function Xe(e){return e.reduce((e,t)=>e+J(t),0)}function Ze(e,t,n){let r=0;for(let i=t;i<n;i++)r+=e[i]??0;return r}function Qe(e,t,n){let r=t+1,i=e[t]??0;for(;r<e.length&&i+(e[r]??0)<=n;)i+=e[r]??0,r++;return r}async function $e(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(/* @__PURE__ */ 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 et(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function tt(e){return e===408||e===425||e===429||e>=500}function nt(e,t,n){if(e instanceof q&&!tt(e.status))return;let r=Math.min(8e3,500*2**(t-1)),i=Math.round(r*(1-.5*n())),a=e instanceof q?e.retryAfter:void 0;return a===void 0?i:Math.max(a,i)}function Y(e,t){let n=e instanceof q?e.status:void 0;return n!==void 0&&!tt(n)?{cause:e,reason:`rejected`,status:n}:{cause:e,reason:t?`unconfirmed`:`not-sent`,status:n}}function rt(e,t){if(e===null)return;let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?e*1e3:void 0}let r=st(n,t);return r===void 0?void 0:Math.max(0,r-t)}const it=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],at=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],ot=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function st(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 X(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),X(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 X(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function X(e,t,n,r,i,a,o){let s=Number(t),c=it.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=/* @__PURE__ */ 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=at.indexOf(e),h=ot.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const ct=`lf_session_replay_recording`,Z=`lf_session_replay_recording_owner`,lt=72e5;var ut=class{state;resumed=!1;storage;owner;now;maxDurationMs;readOpenerState;constructor(e,t,n,r=()=>null){this.storage=e,this.now=t,this.owner=B(t),this.maxDurationMs=Math.min(n,lt),this.readOpenerState=r;try{e?.getItem(`lf_session_replay_recording_owner`)===null&&(this.state=this.readResumableState()),e?.setItem(Z,this.owner),e?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.storage=null,this.state=void 0)}catch{this.storage=null,this.state=void 0}this.resumed=this.state!==void 0}get(e){return this.state!==void 0&&this.isCurrent(this.state.id,e)?this.state.id:this.replace(e)}candidate(e){return{id:this.get(e),resumed:this.resumed}}replace(e){this.state={id:B(this.now),rumSessionId:e,startedAt:this.now()},this.resumed=!1;try{this.storage?.setItem(ct,JSON.stringify(this.state))}catch{}return this.state.id}isCurrent(e,t){let n=this.state;if(n===void 0)return!1;let r=this.now();return n.id===e&&n.rumSessionId===t&&r>=n.startedAt&&r-n.startedAt<this.maxDurationMs}release(){try{this.storage?.getItem(`lf_session_replay_recording_owner`)===this.owner&&this.storage.removeItem(Z)}catch{}}resume(){try{this.state=this.storage?.getItem(`lf_session_replay_recording_owner`)===null?this.readResumableState():void 0,this.storage?.setItem(Z,this.owner),this.storage?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.state=void 0,this.storage=null)}catch{this.state=void 0,this.storage=null}this.resumed=this.state!==void 0}readResumableState(){let e=this.storage?.getItem(ct),t=this.storage?.getItem(U);if(e==null||t==null)return;let n=null;try{n=this.readOpenerState()}catch{}if(n!==e)return dt(e,t)}};function dt(e,t){let n=JSON.parse(e),r=JSON.parse(t);if(typeof n!=`object`||!n||typeof r!=`object`||!r)return;let i=n,a=r;if(!(typeof i.id!=`string`||i.id.length===0||typeof i.rumSessionId!=`string`||typeof i.startedAt!=`number`||!Number.isFinite(i.startedAt)||a.id!==i.id||typeof a.seq!=`number`||!Number.isSafeInteger(a.seq)||a.seq<0))return{id:i.id,rumSessionId:i.rumSessionId,startedAt:i.startedAt}}function ft(){try{if(typeof window>`u`||!window.isSecureContext)return;let e=globalThis.navigator?.locks;return typeof e?.request==`function`?e:void 0}catch{return}}async function pt(e,t,n,r=1e3){return n.aborted?{kind:`aborted`}:new Promise(i=>{let a=!1,o=e=>{a||(a=!0,clearTimeout(c),n.removeEventListener(`abort`,l),i(e))},s=new AbortController,c=setTimeout(()=>{s.abort(),o({kind:`timeout`})},r),l=()=>{s.abort(),o({kind:`aborted`})};n.addEventListener(`abort`,l);let u=!1;try{e.request(`logfire-session-replay:${t}`,{mode:`exclusive`,signal:s.signal},async()=>{if(u=!0,a||n.aborted){o({kind:`aborted`});return}await new Promise(e=>{o({kind:`held`,lock:{release:e}})})}).catch(()=>{u||o({kind:`aborted`})})}catch{o({kind:`aborted`})}})}function mt(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function ht(e){let t=e.random??Math.random;return t()<mt(e.sessionSampleRate)?`full`:t()<mt(e.onErrorSampleRate)?`buffer`:`off`}const gt=`lf_session_replay_seq:`,_t=`lf_session_replay_probe`;var vt=class{storage;now;constructor(e,t){this.storage=e,this.now=t}read(e){try{return xt(this.storage.getItem(bt(e)))?.seq}catch{return}}write(e,t){try{return this.storage.setItem(bt(e),JSON.stringify({seq:t,at:this.now()})),this.read(e)===t}catch{return!1}}prune(e){try{let t=this.now()-e,n=[];for(let e=0;e<this.storage.length;e+=1){let r=this.storage.key(e);if(r===null||!r.startsWith(gt))continue;let i=xt(this.storage.getItem(r));(i===void 0||i.at<t)&&n.push(r)}for(let e of n)this.storage.removeItem(e)}catch{}}};function yt(){try{let e=globalThis.localStorage;if(e===void 0)return null;e.setItem(_t,`1`);let t=e.getItem(_t)===`1`;return e.removeItem(_t),t?e:null}catch{return null}}function bt(e){return`${gt}${e}`}function xt(e){if(e!==null)try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return typeof n.seq!=`number`||!Number.isSafeInteger(n.seq)||n.seq<0||typeof n.at!=`number`||!Number.isFinite(n.at)?void 0:{seq:n.seq,at:n.at}}catch{return}}const St=/^[a-z][a-z0-9_]{0,63}$/u;function Ct(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function wt(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(!St.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`&&Ct(r,200))&&(Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:r,writable:!0}),o+=1,o===20))break}return Object.freeze(a)}const Tt={mode:`off`,recording:!1,getSessionId:()=>``,captureError:()=>void 0,getRecordingId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},Et=`lf_session_replay_mode`,Q=Symbol.for(`@pydantic/logfire-session-replay/controller`);function Dt(e){if(typeof window>`u`||typeof document>`u`)return Tt;let t=Ht();try{let n=kt(e),r=new Re({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return $(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=V(),s=new ut(o,n.now,n.maxSessionDurationMs,()=>window.opener?.sessionStorage.getItem(`lf_session_replay_recording`)??null),c=At(n.now),l=a(!1),u=s.get(l),d,f=!1,p=!1,m=0,h=!0,g=Promise.resolve(),_=Promise.resolve(),v,y,b,x=!1,S=e=>{y!==void 0&&(e===void 0||y.recordingId===e)&&(y.lock.release(),y=void 0)},C=(e,t,r=!t,i=!1)=>{let c=jt(n,e,o);if(!(c===`off`||f||p||d!==void 0||e!==l))try{x=i&&s.candidate(e).resumed;let t=u;d=Ot({config:n,getSessionId:a,mode:c,onSessionChanged:D,samplingModeStorage:o,sessionId:e,recordingId:t,isCurrentRecording:()=>s.isCurrent(t,a(!1)),holdUntilActivity:r,awaitBinding:i})}catch(e){if(d=void 0,t)throw e;$(n.onError,e)}},w=(e,t,n)=>({initialSeq:n,write:n=>e.records.write(t,n),onFailure:()=>{queueMicrotask(()=>{!f&&u===t&&(s.replace(l),D(l,!1))})}}),ee=async(e,t,r)=>{b?.abort();let i=new AbortController;b=i;let a=()=>i.signal.aborted||f||p||m!==r||l!==t,o=s.candidate(t);u=o.id;let c=()=>{o={id:s.replace(t),resumed:!1},u=o.id};for(let t=0;t<2;t+=1){let t=await pt(e.locks,o.id,i.signal);if(t.kind===`aborted`)return;if(t.kind===`timeout`){c();continue}if(a()||u!==o.id){t.lock.release();return}let n;if(o.resumed?n=e.records.read(o.id):e.records.write(o.id,0)&&(n=0),n===void 0){t.lock.release(),c();continue}return y={recordingId:o.id,lock:t.lock},{recordingId:o.id,sequenceRecord:w(e,o.id,n)}}$(n.onError,/* @__PURE__ */ Error(`logfire session replay: could not claim a replay recording`))},T=async(e,t,r,i)=>{try{let n=await ee(e,t,r),a=!f&&!p&&m===r&&l===t;if(n===void 0){a&&d?.transport.isAwaitingBinding()===!0&&(d.discard(),d=void 0);return}if(!a){S(n.recordingId);return}if(d!==void 0&&d.recordingId!==n.recordingId&&(d.discard(),d=void 0,C(t,!1,i,!0)),d===void 0||d.recordingId!==n.recordingId){S(n.recordingId);return}x=!1,d.transport.bind(n.sequenceRecord)}catch(e){$(n.onError,e)}},E=async(e,t,n)=>{C(e,!1,n,c!==void 0),c!==void 0&&d!==void 0&&await T(c,e,t,n)},D=(e,t=!0)=>{if(f||p)return;let r=s.get(e);if(e===l&&r===u)return;let i=u;l=e,u=r,b?.abort();let a=d;d=void 0;let o=a?.deactivate()??Promise.resolve(),c=m;g=g.then(async()=>{await zt(o,n.onError),S(i),!f&&m===c&&l===e&&u===r&&await E(e,c,t)})},O;try{if(c===void 0)C(l,!0);else if(c.records.prune(lt),C(l,!0,!1,!0),d!==void 0){let e=l,t=m;g=g.then(async()=>T(c,e,t,!1))}O=setInterval(()=>{D(a(!1))},1e3)}catch(e){throw d?.discard(),d=void 0,b?.abort(),S(),s.release(),e}let k=()=>{p=!0,m+=1,b?.abort();let e=d;d=void 0;let t=e?.deactivate(!0)??Promise.resolve();S(),_=Promise.all([_,g,zt(t,n.onError)]).then(()=>void 0),g=Promise.resolve(),h=e?.transport.canResumeSequence()??h,h&&s.release()},A=e=>{if(!e.persisted||f)return;d?.discard(),d=void 0;let t=m;g=g.then(async()=>{let e=()=>f||m!==t;if(e())return;let n=new AbortController;b=n;let r,i=!1;if(c!==void 0){let e=await pt(c.locks,u,n.signal);if(e.kind===`aborted`)return;e.kind===`held`&&(r=e.lock),i=e.kind===`timeout`}else await new Promise(e=>{setTimeout(e,0)});try{if(e())return;p=!1,s.resume(),l=a(!1),u=i?s.replace(l):s.get(l),h=!0}finally{r?.release()}await E(l,t,!1)})};return window.addEventListener(`pagehide`,k),window.addEventListener(`pageshow`,A),{get mode(){try{return d?.transport.getMode()??`off`}catch(e){return $(n.onError,e),`off`}},get recording(){try{return d!==void 0}catch(e){return $(n.onError,e),!1}},getSessionId:()=>a(!1),captureError:(e,t)=>{try{d?.captureError(e,t)}catch(e){$(n.onError,e)}},getRecordingId:()=>d===void 0||x&&d.transport.isAwaitingBinding()?``:s.isCurrent(d.recordingId,a(!1))?d.recordingId:``,flush:async()=>{try{await g,await d?.transport.flush()}catch(e){$(n.onError,e)}},stop:async()=>(v??=(async()=>{f=!0,m+=1,b?.abort(),clearInterval(O),window.removeEventListener(`pagehide`,k),window.removeEventListener(`pageshow`,A);let e=d;d=void 0,await zt(e?.deactivate()??Promise.resolve(),n.onError),await g,await _,r.flushPendingStorage(),h=e?.transport.canResumeSequence()??h,h&&s.release(),S(),t()})(),v)}}catch(e){throw t(),e}}function Ot(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:a,samplingModeStorage:o,sessionId:c,recordingId:l,isCurrentRecording:u,awaitBinding:f}=e,p=wt(t.getSessionAttributes,e=>{$(t.onError,e)}),m,h=new Ge(t,l,i,void 0,void 0,p,{holdUntilActivity:r,takeFullSnapshot:()=>{m.takeFullSnapshot()},awaitBinding:f}),g=[],_=!0,v=()=>_,y;try{m=Te({beforeUserActivity:()=>{if(_&&h.isHeld())try{let e=n(!0);if(e!==c||!u()){a(e,!1);return}h.releaseHeld(()=>{m.takeFullSnapshot()})}catch(e){$(t.onError,e)}},emit:e=>{if(_)try{let t=n(d(e));if(t!==c||!u()){a(t,!1);return}h.add(e)}catch(e){$(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:Math.max(3e5,t.minSessionDurationMs),redactUrlPatterns:t.redactUrlPatterns,transformUrl:t.transformUrl}),g.push(()=>{m.stop()});let e=(e,n)=>{if(_)try{m.addCustomEvent(e,n)}catch(e){$(t.onError,e)}},r=n=>{v()&&(h.releaseHeld(()=>{m.takeFullSnapshot()}),e(s.Error,n),v()&&h.getMode()===`buffer`&&(Nt(o,c,`full`),Rt(h.triggerFlush(),t.onError)))},f=/* @__PURE__ */ new WeakSet,p=e=>typeof e!=`object`||!e||!f.has(e)&&(f.add(e),!0),b=(e,t)=>{if(p(e)){let n=Wt(Ft(e),void 0,It(e));r(typeof t?.timestamp==`number`?{...n,timestamp:t.timestamp}:n)}},x=e=>{e instanceof ErrorEvent&&p(e.error)&&r(Wt(e.message,e.filename,It(e.error)))},S=e=>{b(e.reason)},C=()=>{document.visibilityState===`hidden`&&Rt(h.flush({background:!0}),t.onError)},w=()=>{Rt(h.flush({keepalive:!0}),t.onError)};return t.captureGlobalErrors&&(window.addEventListener(`error`,x,!0),g.push(()=>{window.removeEventListener(`error`,x,!0)}),window.addEventListener(`unhandledrejection`,S,!0),g.push(()=>{window.removeEventListener(`unhandledrejection`,S,!0)})),document.addEventListener(`visibilitychange`,C),g.push(()=>{document.removeEventListener(`visibilitychange`,C)}),window.addEventListener(`pagehide`,w),g.push(()=>{window.removeEventListener(`pagehide`,w)}),t.captureConsole&&g.push(ne(e,{onError:t.onError})),t.captureNetwork&&g.push(re(e,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns,transformUrl:t.transformUrl})),t.captureNavigation&&g.push(ie(e,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns,transformUrl:t.transformUrl})),h.start(),{sessionId:c,recordingId:l,transport:h,captureError:b,deactivate:async(e=!1)=>(y??=(async()=>{let t=h.shutdown({keepalive:e});_=!1,Ut(g),await t})(),y),discard:()=>{_=!1,Ut(g),h.discard()}}}catch(e){throw _=!1,Ut(g),h.discard(),e}}function kt(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,getUser:e.getUser,captureConsole:e.captureConsole??l.captureConsole,captureNetwork:e.captureNetwork??l.captureNetwork,captureNavigation:e.captureNavigation??l.captureNavigation,captureGlobalErrors:e.captureGlobalErrors??l.captureGlobalErrors,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...l.redactUrlPatterns],transformUrl:Bt(e.transformUrl,e.onError),onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function At(e){let t=ft();if(t===void 0)return;let n=yt();return n===null?void 0:{locks:t,records:new vt(n,e)}}function jt(e,t,n){let r=Mt(n,t);if(r!==void 0)return r;let i=ht({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return Nt(n,t,i),i}function Mt(e,t){if(e!==null)try{let n=e.getItem(Et);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!Pt(i.mode)?void 0:i.mode}catch{return}}function Nt(e,t,n){if(e!==null)try{e.setItem(Et,JSON.stringify({id:t,mode:n}))}catch{}}function Pt(e){return e===`full`||e===`buffer`||e===`off`}function Ft(e){return Gt(Lt(e,`message`)??e)}function It(e){let t=Lt(e,`stack`);return typeof t==`string`?t:void 0}function Lt(e,t){try{return typeof e==`object`&&e&&t in e?e[t]:void 0}catch{return}}function Rt(e,t){e.catch(e=>{$(t,e)})}async function zt(e,t){try{await e}catch(e){$(t,e)}}function Bt(e,t){if(e===void 0)return;let n=!1;return r=>{try{return e(r)}catch(e){throw n||(n=!0,$(t,e)),e}}}function $(e,t){try{let n=e?.(t);Vt(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Vt(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function Ht(){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 Ut(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function Wt(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function Gt(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{return Object.prototype.toString.call(e)}catch{return`[object Object]`}}export{c as CHUNK_ENVELOPE_VERSION,s as CustomTag,i as EventType,a as IncrementalSource,o as MouseInteractions,H as ReplayUploadError,Dt as startSessionReplay};
|
package/dist/integration.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as SessionReplayConfig, r as startSessionReplay } from "./index-
|
|
1
|
+
import { C as SessionReplayConfig, r as startSessionReplay } from "./index-WIWZDir6.js";
|
|
2
2
|
//#region src/integration.d.ts
|
|
3
3
|
export type SessionReplayIntegrationOptions = Omit<SessionReplayConfig, "getSessionAttributes" | "getSessionId" | "getUser" | "headers" | "maxSessionDurationMs" | "now" | "random" | "replayUrl" | "sessionIdleTimeoutMs" | "token">;
|
|
4
4
|
export interface SessionReplayIntegration extends SessionReplayIntegrationOptions {
|
package/dist/integration.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as SessionReplayConfig, r as startSessionReplay } from "./index-
|
|
1
|
+
import { C as SessionReplayConfig, r as startSessionReplay } from "./index-WIWZDir6.js";
|
|
2
2
|
//#region src/integration.d.ts
|
|
3
3
|
export type SessionReplayIntegrationOptions = Omit<SessionReplayConfig, "getSessionAttributes" | "getSessionId" | "getUser" | "headers" | "maxSessionDurationMs" | "now" | "random" | "replayUrl" | "sessionIdleTimeoutMs" | "token">;
|
|
4
4
|
export interface SessionReplayIntegration extends SessionReplayIntegrationOptions {
|