@pydantic/logfire-session-replay 0.1.0-alpha.1 → 0.2.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 CHANGED
@@ -34,11 +34,16 @@ const replay = startSessionReplay({
34
34
  sessionSampleRate: 0.1,
35
35
  onErrorSampleRate: 1,
36
36
 
37
+ // These are the privacy-safe defaults; they are shown for emphasis.
38
+ maskAllText: true,
37
39
  maskAllInputs: true,
38
40
  blockSelector: '[data-logfire-block]',
39
- maskTextSelector: '[data-logfire-mask]',
40
41
 
41
42
  distinctId: currentUser?.id,
43
+ getSessionAttributes: () => ({
44
+ account_tier: currentAccount.tier,
45
+ beta_user: currentUser.isBeta,
46
+ }),
42
47
  getTraceContext: () => getCurrentTraceContext(),
43
48
  })
44
49
 
@@ -46,6 +51,39 @@ await replay.flush()
46
51
  await replay.stop()
47
52
  ```
48
53
 
54
+ ### OpenTelemetry fetch and XHR instrumentation
55
+
56
+ When standalone replay runs alongside OpenTelemetry browser HTTP
57
+ instrumentation, configure ignores in both directions. Replay's
58
+ `ignoreUrlPatterns` must include the trace, metric, and replay upload endpoints
59
+ so those requests are not recorded as replay events. OpenTelemetry fetch and
60
+ XHR `ignoreUrls` must include the replay upload URL so replay uploads do not
61
+ create HTTP spans.
62
+
63
+ ```ts
64
+ const telemetryUrls = [/\/client-traces(?:[?#]|$)/, /\/client-metrics(?:[?#]|$)/]
65
+ const replayUploads = [/\/client-replay\/[^/?#]+(?:\?|$)/]
66
+
67
+ getWebAutoInstrumentations({
68
+ '@opentelemetry/instrumentation-fetch': {
69
+ ignoreUrls: replayUploads,
70
+ },
71
+ '@opentelemetry/instrumentation-xml-http-request': {
72
+ ignoreUrls: replayUploads,
73
+ },
74
+ })
75
+
76
+ startSessionReplay({
77
+ replayUrl: '/client-replay',
78
+ ignoreUrlPatterns: [...telemetryUrls, ...replayUploads],
79
+ })
80
+ ```
81
+
82
+ The replay fetch wrapper preserves OpenTelemetry's `fetch.__original` exporter
83
+ escape hatch when OpenTelemetry is installed first. That protects direct
84
+ exporter bypass, but it cannot infer your independently configured endpoints;
85
+ the bidirectional ignore lists are still required in either startup order.
86
+
49
87
  Your proxy should forward the compressed request body and these headers to
50
88
  Logfire replay ingest:
51
89
 
@@ -69,11 +107,20 @@ The decompressed body shape is:
69
107
  urls,
70
108
  traceIds,
71
109
  distinctId,
110
+ sessionAttributes,
72
111
  },
73
112
  events,
74
113
  }
75
114
  ```
76
115
 
116
+ `getSessionAttributes` is snapshotted once for every replay session. Keys must
117
+ match `^[a-z][a-z0-9_]{0,63}$`; at most 20 entries are retained. Values must be
118
+ booleans, finite numbers, or strings no longer than 200 Unicode code points.
119
+ Invalid entries are omitted, and callback failures are reported through
120
+ `onError` without stopping replay. The optional `meta.sessionAttributes` field
121
+ is omitted when the snapshot is empty. Keep these dimensions low-cardinality
122
+ and free of personal or sensitive data.
123
+
77
124
  ## Direct Token Escape Hatch
78
125
 
79
126
  For trusted runtimes or explicitly accepted advanced browser usage, you can
@@ -89,26 +136,78 @@ startSessionReplay({
89
136
  Normal browser applications should not expose project write tokens in bundles.
90
137
  Use `replayUrl + headers` with a backend proxy when possible.
91
138
 
92
- ## Privacy
139
+ ## Lifecycle Delivery
93
140
 
94
- The recorder masks input values by default, disables canvas recording, disables
95
- font collection, throttles media sampling, and never captures request or response
96
- bodies. Replay can still capture DOM text, full URLs, console output, fetch/XHR
97
- metadata, and navigation events depending on configuration.
141
+ Full-mode replay requests best-effort keepalive uploads when the page becomes
142
+ hidden or receives `pagehide`. Lifecycle chunks start independently of an
143
+ ordinary upload that is still in flight. The transport admits the earliest
144
+ contiguous prefix whose compressed bodies fit its 48,000-byte aggregate budget
145
+ across its own unfinished keepalive requests. Remaining lifecycle chunks are
146
+ attempted once as normal requests.
147
+
148
+ That budget is deliberately below the browser limit, but the browser quota is
149
+ shared with other unfinished keepalive requests on the page. It cannot guarantee
150
+ delivery after page freeze or termination. One individually oversized replay
151
+ event also cannot be split safely.
152
+
153
+ `headers` and functional `token` values are resolved during each upload. An
154
+ asynchronous credential callback can therefore delay the final request beyond
155
+ the browser's page-freeze boundary. Prefer synchronously available proxy
156
+ credentials, and call `flush()` before a controlled navigation when delivery is
157
+ critical.
158
+
159
+ Ordinary uploads use asynchronous gzip when available. If a restrictive Content
160
+ Security Policy blocks fflate's worker compressor, replay retries the same batch
161
+ with synchronous gzip and remembers the fallback for that replay controller.
162
+ This preserves the batch, but compression may briefly use the main thread.
163
+
164
+ ## Privacy
98
165
 
99
- Use `blockSelector` to omit entire DOM subtrees, `maskTextSelector` to mask text
100
- content before events are recorded, `redactUrlPatterns` to strip query strings
101
- and fragments from matching network URLs, and `captureConsole`,
102
- `captureNetwork`, or `captureNavigation` to disable capture classes that are not
103
- appropriate for your application.
166
+ The recorder masks all rendered text and input values by default
167
+ (`maskAllText: true`, `maskAllInputs: true`). It also disables canvas recording
168
+ and font collection, throttles media sampling, never captures request or
169
+ response bodies, and leaves console capture off (`captureConsole: false`).
170
+ Network and navigation capture remain on, but query strings and fragments are
171
+ removed from rrweb page metadata and captured network/navigation URLs by the
172
+ default `redactUrlPatterns` value. Replay envelope `meta.urls` contains those
173
+ same sanitized captured URLs.
174
+
175
+ Use `blockSelector` to omit entire DOM subtrees. Set `maskAllText: false` only
176
+ when visible text recording is acceptable; `maskTextSelector` can then retain
177
+ selective text masking. Set `captureConsole: true` only after auditing console
178
+ arguments. An explicit `redactUrlPatterns: []` restores raw captured page,
179
+ network, and navigation URLs. `captureNetwork` and `captureNavigation` can
180
+ disable those capture classes completely.
181
+
182
+ Text masking does not scrub DOM attributes, CSS content, resource URLs, or
183
+ arbitrary custom-event payloads. Avoid placing secrets there, block affected
184
+ subtrees, and sanitize custom events before recording them.
104
185
 
105
186
  ## Sampling
106
187
 
107
188
  The recorder uses a Sentry-style two-rate model:
108
189
 
109
- - `sessionSampleRate`: records the full session continuously
190
+ - `sessionSampleRate`: records the current browser session continuously
110
191
  - `onErrorSampleRate`: for sessions not selected by `sessionSampleRate`, keeps
111
- an in-memory replay buffer and uploads it only if an error occurs
192
+ an in-memory replay buffer and promotes it only for an uncaught `window.error`
193
+ or `unhandledrejection`
194
+
195
+ Buffer mode is bounded by `maxBufferBytes`, measured as the UTF-8 byte sum of
196
+ event JSON before envelope metadata and compression. It keeps the latest full
197
+ snapshot and the earliest contiguous incremental events that fit; later
198
+ incrementals are dropped until rrweb emits another full snapshot. Incrementals
199
+ before an anchor or larger than the cap are dropped. If one full snapshot is
200
+ larger than the cap, that snapshot is retained alone so promoted replay remains
201
+ playable.
202
+
203
+ Sampling is resolved and persisted independently for each session id. When the
204
+ session id rotates, the returned handle updates its `mode` and `recording`
205
+ properties. A sampled-off session keeps only a lightweight session-id monitor;
206
+ it does not start rrweb or patch console, network, or navigation globals, and a
207
+ later sampled session can begin recording without reloading the page.
208
+
209
+ Caught exceptions, `console.error`, and errors reported through another API do
210
+ not automatically promote the replay buffer.
112
211
 
113
212
  `stop()` is awaitable and flushes the final chunk before resolving.
114
213
 
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("rrweb"),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},i={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},a={Error:`logfire.error`,Trace:`logfire.trace`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},o={sessionSampleRate:1,onErrorSampleRate:1,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:144e5,distinctId:``,captureConsole:!0,captureNetwork:!0,captureNavigation:!0},s=[`log`,`info`,`warn`,`error`,`debug`],c=1024,l=()=>void 0;function u(e,t={}){let n=new Map,r=!1;for(let r of s){let i=console[r];if(typeof i!=`function`)continue;let o=i;n.set(r,o),console[r]=(...n)=>{_(e,a.Console,{level:r,args:n.slice(0,10).map(v)},t.onError),o.apply(console,n)}}return()=>{if(!r){r=!0;for(let[e,t]of n)console[e]=t}}}function d(e,t){let n=h(t),r=p(e,n),i=m(e,n),a=!1;return()=>{a||(a=!0,r(),i())}}function f(e,t={}){let n=history.pushState,r=history.replaceState,i=!1,o=n=>{_(e,a.Navigation,{url:window.location.href,kind:n},t.onError)};history.pushState=function(...e){n.apply(this,e),o(`push`)},history.replaceState=function(...e){r.apply(this,e),o(`replace`)};let s=()=>{o(`pop`)};return window.addEventListener(`popstate`,s),()=>{i||(i=!0,history.pushState=n,history.replaceState=r,window.removeEventListener(`popstate`,s))}}function p(e,t){let n=window.fetch;if(typeof n!=`function`)return l;let r=!1;return window.fetch=async(r,i)=>{let o=t.now(),s=b(r,i),c=x(r);if(D(c,t.ignoreUrlPatterns))return n(r,i);let l=E(c,t.redactUrlPatterns),u=T(i?.body);try{let c=await n(r,i);return _(e,a.Network,w({method:s,url:l,status:c.status,durationMs:Math.max(0,t.now()-o),reqBytes:u,resBytes:S(c.headers)}),t.onError),c}catch(n){throw _(e,a.Network,w({method:s,url:l,status:0,durationMs:Math.max(0,t.now()-o),failed:!0,reqBytes:u}),t.onError),n}},()=>{r||(r=!0,window.fetch=n)}}function m(e,t){let n=window.XMLHttpRequest.prototype,r=n.open,i=n.send,o=new WeakMap,s=!1;return n.open=function(e,n,i,a,s){let c=n.toString();if(D(c,t.ignoreUrlPatterns)){o.delete(this),r.call(this,e,n,i??!0,a??null,s??null);return}o.set(this,{method:e.toUpperCase(),url:E(c,t.redactUrlPatterns),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),r.call(this,e,n,i??!0,a??null,s??null)},n.send=function(n){let r=o.get(this);if(r===void 0){i.call(this,n);return}r.startedAt=t.now(),r.reqBytes=T(n);let s=()=>{r.failed=!0},c=()=>{r.emitted||(r.emitted=!0,this.removeEventListener(`error`,s),this.removeEventListener(`abort`,s),this.removeEventListener(`timeout`,s),_(e,a.Network,w({method:r.method,url:r.url,status:this.status,durationMs:Math.max(0,t.now()-r.startedAt),failed:r.failed||this.status===0,reqBytes:r.reqBytes,resBytes:C(this)}),t.onError))};this.addEventListener(`error`,s),this.addEventListener(`abort`,s),this.addEventListener(`timeout`,s),this.addEventListener(`loadend`,c,{once:!0});try{i.call(this,n)}catch(n){throw this.removeEventListener(`error`,s),this.removeEventListener(`abort`,s),this.removeEventListener(`timeout`,s),this.removeEventListener(`loadend`,c),_(e,a.Network,w({method:r.method,url:r.url,status:0,durationMs:Math.max(0,t.now()-r.startedAt),failed:!0,reqBytes:r.reqBytes}),t.onError),n}},()=>{s||(s=!0,n.open=r,n.send=i)}}function h(e){return{...e,ignoreUrlPatterns:g(e.ignoreUrlPatterns),redactUrlPatterns:g(e.redactUrlPatterns)}}function g(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function _(e,t,n,r){try{e(t,n)}catch(e){try{r?.(e)}catch{}}}function v(e){if(e==null)return String(e);if(typeof e==`string`)return y(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return y(e.stack??`${e.name}: ${e.message}`);try{return y(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function y(e){return e.length<=c?e:`${e.slice(0,c)}...(+${String(e.length-c)} chars)`}function b(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function x(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function S(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 C(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 w(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 T(e){if(e==null)return 0;if(typeof e==`string`)return e.length;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Blob)return e.size}function E(e,t){if(t.length===0||!t.some(t=>t.test(e)))return e;try{let t=new URL(e,window.location.href);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}function D(e,t){return t.some(t=>t.test(e))}const O=e.record;function ee(e){let t={emit:t=>{e.emit(t)},maskAllInputs:e.maskAllInputs,recordCanvas:!1,collectFonts:!1,sampling:{mousemove:!0,mouseInteraction:!0,scroll:150,media:800,input:`last`}};e.maskTextSelector!==void 0&&e.maskTextSelector.length>0&&(t.maskTextSelector=e.maskTextSelector),e.blockSelector!==void 0&&e.blockSelector.length>0&&(t.blockSelector=e.blockSelector),e.checkoutEveryNms!==void 0&&e.checkoutEveryNms>0&&(t.checkoutEveryNms=e.checkoutEveryNms);let n=O(t);return{stop:()=>{n?.()},addCustomEvent:(e,t)=>{O.addCustomEvent?.(e,t)},takeFullSnapshot:()=>{O.takeFullSnapshot?.(!0)}}}function k(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function A(e){let t=e.random??Math.random;return t()<k(e.sessionSampleRate)?`full`:t()<k(e.onErrorSampleRate)?`buffer`:`off`}function j(e=Date.now){let t=e(),n=new Uint8Array(new ArrayBuffer(16));te(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/2**8)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function te(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 M=`lf_session_replay`;var N=class{idleTimeoutMs;maxDurationMs;now;storage;memorySession;constructor(e){this.idleTimeoutMs=e.idleTimeoutMs,this.maxDurationMs=e.maxDurationMs,this.now=e.now??Date.now,this.storage=e.storage===void 0?P():e.storage}getSession(){let e=this.now(),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.write(t),t}reset(){return this.createSession(this.now())}isExpired(e,t){return t-e.lastActivityAt>this.idleTimeoutMs||t-e.startedAt>this.maxDurationMs}createSession(e){let t={id:j(this.now),startedAt:e,lastActivityAt:e};return this.write(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(M);if(e!==null){let t=JSON.parse(e);if(F(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(M,JSON.stringify(e))}catch{}}};function P(){try{return globalThis.sessionStorage??null}catch{return null}}function F(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}function I(e){return typeof e==`object`&&e?e:void 0}function L(e){return typeof e==`string`&&e.length>0?e:void 0}function ne(e,t,o){let s=1/0,c=0,l=0,u=0,d=0,f=!1,p=new Set,m=new Set;for(let e of t){e.timestamp<s&&(s=e.timestamp),e.timestamp>c&&(c=e.timestamp);let t=I(e.data);if(e.type===n.FullSnapshot)f=!0;else if(e.type===n.Meta){let e=L(t?.href);e!==void 0&&p.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)&&l++}else e===r.Input&&u++}else if(e.type===n.Custom&&t!==void 0){let e=L(t.tag),n=I(t.payload);if(e===a.Error)d++;else if(e===a.Trace){let e=L(n?.traceId);e!==void 0&&m.add(e)}else if(e===a.Console)n?.level===`error`&&d++;else if(e===a.Navigation){let e=L(n?.url);e!==void 0&&p.add(e)}}}return{seq:e,firstTimestamp:s===1/0?0:s,lastTimestamp:c,eventCount:t.length,clickCount:l,keypressCount:u,errorCount:d,hasFullSnapshot:f,urls:[...p],traceIds:[...m],...o!==void 0&&o.length>0?{distinctId:o}:{}}}const R=`lf_session_replay_seq`;var re=class{buffer=[];pendingBytes=0;seq=0;timer;mode;flushing;config;storage;sessionId;constructor(e,t,n,r=P()){this.config=e,this.sessionId=t,this.mode=n,this.storage=r,this.seq=this.loadSeq(t)}start(){this.timer!==void 0||this.mode!==`full`||(this.timer=setInterval(()=>{this.flushAndReport()},this.config.flushIntervalMs))}add(e){this.mode===`buffer`&&e.type===n.FullSnapshot&&(this.buffer=[],this.pendingBytes=0),this.buffer.push(e),this.pendingBytes+=H(e),this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&this.flushAndReport()}async triggerFlush(){return this.mode===`buffer`&&(this.mode=`full`,this.start()),this.flush()}async flush(e={}){if(this.mode===`buffer`||this.buffer.length===0)return;let t=this.buffer;this.buffer=[],this.pendingBytes=0;let n=e.keepalive===!0?U(t):[t],r=this.seq;this.seq+=n.length;let i=this.sessionId;this.saveSeq(i,this.seq);let a=(this.flushing??Promise.resolve()).then(async()=>{for(let t=0;t<n.length;t++){let a=n[t];a!==void 0&&await this.deliver(a,r+t,i,e.keepalive??!1)}});this.flushing=a.catch(()=>void 0),await a}rotate(e){return e===this.sessionId?!1:(this.mode===`buffer`?(this.buffer=[],this.pendingBytes=0):this.flushAndReport(),this.sessionId=e,this.seq=this.loadSeq(e),!0)}async shutdown(e={}){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),await this.flush(e),await this.flushing}getMode(){return this.mode}flushAndReport(){this.flush().catch(e=>{this.config.onError?.(e)})}async deliver(e,n,r,i){let a={version:1,meta:ne(n,e,this.config.getDistinctId?.()??this.config.distinctId),events:e};try{let e=JSON.stringify(a),o=i?(0,t.gzipSync)((0,t.strToU8)(e)):await W(e),s=i&&o.byteLength<=6e4;await this.sendWithRetry(r,n,o,s)}catch(e){this.config.onError?.(e)}}async sendWithRetry(e,t,n,r){let i=r?1:3;for(let a=1;a<=i;a++)try{await this.send(e,t,n,r);return}catch(e){if(e instanceof z&&e.status<500||a>=i)throw e;await V(500*a)}}async send(e,t,n,r){let i=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e)}?seq=${String(t)}`,a=await this.getUploadHeaders(),o=await this.config.fetchImpl(i,{method:`POST`,headers:a,body:n.slice(),keepalive:r});if(!o.ok)throw new z(o.status)}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await B(this.config.token);return{...e,...t===void 0||t.length===0?{}:{Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}loadSeq(e){if(this.storage===null)return 0;try{let t=this.storage.getItem(R);if(t===null)return 0;let n=JSON.parse(t);if(typeof n!=`object`||!n)return 0;let r=n;return r.id===e&&typeof r.seq==`number`&&Number.isFinite(r.seq)?r.seq:0}catch{return 0}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(R,JSON.stringify({id:e,seq:t}))}catch{}}},z=class extends Error{status;constructor(e){super(`replay ingest failed: ${String(e)}`),this.status=e,this.name=`ReplayIngestError`}};async function B(e){return typeof e==`function`?e():e}async function V(e){return new Promise(t=>{setTimeout(t,e)})}function H(e){try{return JSON.stringify(e).length}catch{return 0}}function U(e){let t=[],n=[],r=0;for(let i of e){let e=H(i);n.length>0&&r+e>48e3&&(t.push(n),n=[],r=0),n.push(i),r+=e}return n.length>0&&t.push(n),t}async function W(e){return new Promise((n,r)=>{(0,t.gzip)((0,t.strToU8)(e),{level:6},(e,t)=>{if(e!==null){r(e);return}n(t)})})}const G={mode:`off`,recording:!1,getSessionId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},K=`lf_session_replay_mode`;function q(e){if(typeof window>`u`||typeof document>`u`)return G;let t=J(e),n=new N({idleTimeoutMs:t.sessionIdleTimeoutMs,maxDurationMs:t.maxSessionDurationMs,now:t.now}),r=e=>{let r=t.getSessionId?.();return r!==void 0&&r.length>0?r:e?n.touch().id:n.getSession().id},i=r(!1),o=P(),s=Y(t,i,o);if(s===`off`)return G;let c=new re(t,i,s),l={},p=ee({emit:e=>{let t=r(!0);c.rotate(t)&&l.current?.takeFullSnapshot(),c.add(e)},maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:s===`buffer`?12e4:0});l.current=p;let m,h=t.getTraceContext===void 0?void 0:setInterval(()=>{let e=t.getTraceContext?.(),n=e?.traceId;n!==void 0&&n.length>0&&n!==m&&(m=n,p.addCustomEvent(a.Trace,{traceId:n,spanId:e?.spanId}))},1e3),g=e=>{p.addCustomEvent(a.Error,e),c.getMode()===`buffer`&&(X(o,r(!1),`full`),Q(c.triggerFlush(),t.onError))},_=e=>{g($(e.message,e.filename,oe(e.error)))},v=e=>{let t=e.reason;g($(t?.message??String(e.reason??`unhandledrejection`),void 0,t?.stack))},y=()=>{document.visibilityState===`hidden`&&Q(c.flush({keepalive:!0}),t.onError)};window.addEventListener(`error`,_,!0),window.addEventListener(`unhandledrejection`,v,!0),document.addEventListener(`visibilitychange`,y),window.addEventListener(`pagehide`,y);let b=(e,t)=>{p.addCustomEvent(e,t)},x=t.captureConsole?u(b,{onError:t.onError}):Z,S=t.captureNetwork?d(b,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns}):Z,C=t.captureNavigation?f(b,{onError:t.onError}):Z;c.start();let w;return{get mode(){return c.getMode()},recording:!0,getSessionId:()=>r(!1),flush:async()=>c.flush(),stop:async()=>(w??=(async()=>{h!==void 0&&clearInterval(h),window.removeEventListener(`error`,_,!0),window.removeEventListener(`unhandledrejection`,v,!0),document.removeEventListener(`visibilitychange`,y),window.removeEventListener(`pagehide`,y),x(),S(),C(),p.stop(),await c.shutdown({keepalive:!1})})(),w)}}function J(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(t===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,sessionSampleRate:e.sessionSampleRate??o.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??o.onErrorSampleRate,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,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??o.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??o.maxSessionDurationMs,distinctId:e.distinctId??o.distinctId,getDistinctId:e.getDistinctId,getTraceContext:e.getTraceContext,captureConsole:e.captureConsole??o.captureConsole,captureNetwork:e.captureNetwork??o.captureNetwork,captureNavigation:e.captureNavigation??o.captureNavigation,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[],onError:e.onError,fetchImpl:t,now:e.now??Date.now,random:e.random??Math.random}}function Y(e,t,n){let r=ie(n,t);if(r!==void 0)return r;let i=A({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return X(n,t,i),i}function ie(e,t){if(e!==null)try{let n=e.getItem(K);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!ae(i.mode)?void 0:i.mode}catch{return}}function X(e,t,n){if(e!==null)try{e.setItem(K,JSON.stringify({id:t,mode:n}))}catch{}}function ae(e){return e===`full`||e===`buffer`||e===`off`}function oe(e){let t=typeof e==`object`&&e&&`stack`in e?e.stack:void 0;return typeof t==`string`?t:void 0}function Z(){}function Q(e,t){e.catch(e=>{t?.(e)})}function $(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}exports.CHUNK_ENVELOPE_VERSION=1,exports.CustomTag=a,exports.EventType=n,exports.IncrementalSource=r,exports.MouseInteractions=i,exports.startSessionReplay=q;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("rrweb"),t=require("fflate");function n(e,t){return t.some(t=>new RegExp(t.source,t.flags).test(e))}function r(e,t,r){if(!n(e,t))return e;try{let t=new URL(e,r);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}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},o={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},s={Error:`logfire.error`,Trace:`logfire.trace`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},c={sessionSampleRate:1,onErrorSampleRate:1,maskAllText:!0,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:144e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,redactUrlPatterns:[/.+/u]},l=[`log`,`info`,`warn`,`error`,`debug`],u=1024,d=()=>void 0;function f(e,t={}){let n=[],r=b(t.onError);try{for(let t of l)typeof console[t]==`function`&&n.push(S(console,t,(n,i)=>function(...a){return i()&&y(e,s.Console,{level:t,args:a.slice(0,10).map(ee)},r),n.apply(this,a)}));return C(n)}catch(e){throw w(n),e}}function p(e,t){let n=_(t),r={...n,onError:b(n.onError)},i=h(e,r);try{return C([i,g(e,r)])}catch(e){throw i(),e}}function m(e,t={redactUrlPatterns:[]}){let n=b(t.onError),i=i=>{let a=r(window.location.href,t.redactUrlPatterns??[],window.location.href);y(e,s.Navigation,{url:a,kind:i},n)},a=[];try{a.push(S(history,`pushState`,(e,t)=>function(...n){let r=e.apply(this,n);return t()&&i(`push`),r})),a.push(S(history,`replaceState`,(e,t)=>function(...n){let r=e.apply(this,n);return t()&&i(`replace`),r}));let e=!0,t=()=>{e&&i(`pop`)};return window.addEventListener(`popstate`,t),a.push(()=>{e=!1,window.removeEventListener(`popstate`,t)}),C(a)}catch(e){throw w(a),e}}function h(e,t){return typeof window.fetch==`function`?S(window,`fetch`,(n,i)=>{let a=async function(a,o){let c=n;if(!i())return c.call(this,a,o);let l=t.now(),u=te(a,o),d=ne(a);if(O(d,t.ignoreUrlPatterns))return c.call(this,a,o);let f=r(d,t.redactUrlPatterns,window.location.href),p=D(o?.body);try{let n=await c.call(this,a,o);return i()&&y(e,s.Network,E({method:u,url:f,status:n.status,durationMs:Math.max(0,t.now()-l),reqBytes:p,resBytes:re(n.headers)}),t.onError),n}catch(n){throw i()&&y(e,s.Network,E({method:u,url:f,status:0,durationMs:Math.max(0,t.now()-l),failed:!0,reqBytes:p}),t.onError),n}},o=Reflect.get(n,`__original`);return Object.defineProperty(a,"__original",{configurable:!0,value:typeof o==`function`?o:n,writable:!0}),a}):d}function g(e,t){let n=window.XMLHttpRequest.prototype,i=new WeakMap,a=[];try{return a.push(S(n,`open`,(e,n)=>function(...a){let[o,s]=a;if(!n())return e.apply(this,a);let c=s.toString();return O(c,t.ignoreUrlPatterns)?(i.delete(this),e.apply(this,a)):(i.set(this,{method:o.toUpperCase(),url:r(c,t.redactUrlPatterns,window.location.href),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,a))})),a.push(S(n,`send`,(n,r)=>function(...a){let[o]=a,c=r()?i.get(this):void 0;if(c===void 0)return n.apply(this,a);c.startedAt=t.now(),c.reqBytes=D(o);let l=()=>{c.failed=!0},u=()=>{c.emitted||(c.emitted=!0,this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),r()&&y(e,s.Network,E({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:ie(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),r()&&y(e,s.Network,E({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),C(a)}catch(e){throw w(a),e}}function _(e){return{...e,ignoreUrlPatterns:v(e.ignoreUrlPatterns),redactUrlPatterns:v(e.redactUrlPatterns)}}function v(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function y(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function b(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);x(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function x(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function S(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return d;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function C(e){let t=!1;return()=>{t||(t=!0,w(e))}}function w(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function ee(e){if(e==null)return String(e);if(typeof e==`string`)return T(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return T(e.stack??`${e.name}: ${e.message}`);try{return T(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function T(e){return e.length<=u?e:`${e.slice(0,u)}...(+${String(e.length-u)} chars)`}function te(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function ne(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function re(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 ie(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 E(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 D(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 O(e,t){return n(e,t)}const k=e.record,ae=new Set([`action`,`formaction`,`href`,`src`]);function A(e){let t={emit:t=>{e.emit(oe(t,e.redactUrlPatterns))},maskAllInputs:e.maskAllInputs,recordCanvas:!1,collectFonts:!1,sampling:{mousemove:!0,mouseInteraction:!0,scroll:150,media:800,input:`last`}};e.maskAllText?t.maskTextSelector=`*`:e.maskTextSelector!==void 0&&e.maskTextSelector.length>0&&(t.maskTextSelector=e.maskTextSelector),e.blockSelector!==void 0&&e.blockSelector.length>0&&(t.blockSelector=e.blockSelector),e.checkoutEveryNms!==void 0&&e.checkoutEveryNms>0&&(t.checkoutEveryNms=e.checkoutEveryNms);let n=k(t);if(n===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{n()},addCustomEvent:(e,t)=>{k.addCustomEvent?.(e,t)}}}function oe(e,t){if(typeof e.data!=`object`||e.data===null)return e;let n=e.data;if(e.type===i.Meta){if(typeof n.href!=`string`)return e;let i=r(n.href,t,window.location.href);return i===n.href?e:{...e,data:{...n,href:i}}}if(e.type!==i.FullSnapshot&&(e.type!==i.IncrementalSnapshot||n.source!==a.Mutation))return e;let o=j(n,t);return o===n?e:{...e,data:o}}function j(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=j(i,t);e!==i&&(n=!0),r.push(e)}return n?r:e}if(typeof e!=`object`||!e)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n=e===`attributes`&&!Array.isArray(a)?se(a,t):j(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function se(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,i=!1,a={};for(let[e,o]of Object.entries(n)){if(!ae.has(e.toLowerCase())||typeof o!=`string`){a[e]=o;continue}let n=r(o,t,window.location.href);n!==o&&(i=!0),a[e]=n}return i?a:e}function M(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function ce(e){let t=e.random??Math.random;return t()<M(e.sessionSampleRate)?`full`:t()<M(e.onErrorSampleRate)?`buffer`:`off`}const le=/^[a-z][a-z0-9_]{0,63}$/u;function ue(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function de(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(!le.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`&&ue(r,200))&&(a[e]=r,o+=1,o===20))break}return Object.freeze(a)}function fe(e=Date.now){let t=e(),n=new Uint8Array(new ArrayBuffer(16));pe(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/2**8)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function pe(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 N=`lf_session_replay`;var me=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?P():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:fe(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(N);if(e!==null){let t=JSON.parse(e);if(he(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(N,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 P(){try{return globalThis.sessionStorage??null}catch{return null}}function he(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}function F(e){return typeof e==`object`&&e?e:void 0}function I(e){return typeof e==`string`&&e.length>0?e:void 0}function L(e,t,n,r={}){let c=1/0,l=0,u=0,d=0,f=0,p=!1,m=new Set,h=new Set;for(let e of t){e.timestamp<c&&(c=e.timestamp),e.timestamp>l&&(l=e.timestamp);let t=F(e.data);if(e.type===i.FullSnapshot)p=!0;else if(e.type===i.Meta){let e=I(t?.href);e!==void 0&&m.add(e)}else if(e.type===i.IncrementalSnapshot&&t!==void 0){let e=t.source;if(e===a.MouseInteraction){let e=t.type;(e===o.Click||e===o.DblClick)&&u++}else e===a.Input&&d++}else if(e.type===i.Custom&&t!==void 0){let e=I(t.tag),n=F(t.payload);if(e===s.Error)f++;else if(e===s.Trace){let e=I(n?.traceId);e!==void 0&&h.add(e)}else if(e===s.Console)n?.level===`error`&&f++;else if(e===s.Navigation){let e=I(n?.url);e!==void 0&&m.add(e)}}}return{seq:e,firstTimestamp:c===1/0?0:c,lastTimestamp:l,eventCount:t.length,clickCount:u,keypressCount:d,errorCount:f,hasFullSnapshot:p,urls:[...m],traceIds:[...h],...n!==void 0&&n.length>0?{distinctId:n}:{},...Object.keys(r).length===0?{}:{sessionAttributes:{...r}}}}const R=`lf_session_replay_seq`,ge={gzip:t.gzip,gzipSync:t.gzipSync};var _e=class{buffer=[];pendingBytes=0;seq=0;timer;mode;flushing;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;constructor(e,t,n,r=P(),i=ge,a={}){this.config=e,this.sessionId=t,this.sessionAttributes=Object.freeze({...a}),this.mode=n,this.storage=r,this.compression=i,this.seq=this.loadSeq(t)}start(){this.timer!==void 0||this.mode!==`full`||(this.timer=setInterval(()=>{this.flushAndReport()},this.config.flushIntervalMs))}add(e){let t=V(e);if(this.mode===`buffer`){if(e.type===i.FullSnapshot){this.buffer=[e],this.pendingBytes=t;return}if(this.buffer.length===0||t>this.config.maxBufferBytes||this.pendingBytes+t>this.config.maxBufferBytes)return}this.buffer.push(e),this.pendingBytes+=t,this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&this.flushAndReport()}async triggerFlush(){return this.mode===`buffer`&&(this.mode=`full`,this.start()),this.flush()}async flush(e={}){if(this.mode===`buffer`||this.buffer.length===0)return;let t=this.buffer;this.buffer=[],this.pendingBytes=0;let n=e.keepalive===!0?xe(t):[t],r=this.seq;this.seq+=n.length;let i=this.sessionId;this.saveSeq(i,this.seq);let a=e.keepalive===!0?Promise.resolve():this.flushing??Promise.resolve(),o=e.keepalive===!0?this.deliverLifecycle(n,r,i):a.then(async()=>{for(let e=0;e<n.length;e++){let t=n[e];t!==void 0&&await this.deliverOrdinary(t,r+e,i)}}),s=this.flushing;this.flushing=e.keepalive===!0&&s!==void 0?Promise.all([s,o]).then(()=>void 0,()=>void 0):o.catch(()=>void 0),await o}async shutdown(e={}){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),await this.flush(e),await this.flushing}discard(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),this.buffer=[],this.pendingBytes=0}getMode(){return this.mode}flushAndReport(){this.flush().catch(e=>{z(this.config.onError,e)})}createEnvelope(e,t){let n=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{n=this.config.getDistinctId()??this.config.distinctId}catch(e){z(this.config.onError,e)}return{version:1,meta:L(t,e,n,this.sessionAttributes),events:e}}async deliverOrdinary(e,n,r){let i=this.createEnvelope(e,n);try{let e=(0,t.strToU8)(JSON.stringify(i)),a=await this.compressOrdinary(e);await this.sendWithRetry({body:a,lifecycle:!1,requestKeepalive:!1,reservedBytes:0,seq:n,sessionId:r})}catch(e){z(this.config.onError,e)}}async deliverLifecycle(e,n,r){let i=[];for(let a=0;a<e.length;a++){let o=e[a];if(o===void 0){i.push(void 0);continue}let s=this.createEnvelope(o,n+a);try{i.push({body:this.compression.gzipSync((0,t.strToU8)(JSON.stringify(s))),lifecycle:!0,requestKeepalive:!1,reservedBytes:0,seq:n+a,sessionId:r})}catch(e){z(this.config.onError,e),i.push(void 0)}}let a=!0,o=Math.max(0,48e3-this.reservedKeepaliveBytes);for(let e of i){if(e===void 0){a=!1;continue}a&&e.body.byteLength<=o?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,o-=e.reservedBytes):a=!1}await Promise.all(i.map(async e=>{if(e!==void 0)try{await this.sendWithRetry(e)}catch(e){z(this.config.onError,e)}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await Se(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async sendWithRetry(e){let t=e.lifecycle?1:3;for(let n=1;n<=t;n++)try{await this.send(e);return}catch(e){let r=we(e,n);if(r===void 0||n>=t)throw e;await be(r)}}async send(e){let t,n,r,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`replay upload timed out after 10000ms`))},1e4);try{let a=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,o=await this.getUploadHeaders(),s=this.config.fetchImpl(a,{method:`POST`,headers:o,body:e.body.slice(),keepalive:e.requestKeepalive,signal:i.signal});t=!0;let c=await s;if(n=!0,r=await Ce(c),!c.ok){let e=c.status===429?Te(c.headers.get(`retry-after`),Date.now()):void 0;throw new B(c.status,e)}}finally{clearTimeout(a),e.reservedBytes>0&&(t!==!0||n!==!0||r===!0)&&(this.reservedKeepaliveBytes=Math.max(0,this.reservedKeepaliveBytes-e.reservedBytes))}}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await ye(this.config.token);return{...e,...t===void 0||t.length===0?{}:{Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}loadSeq(e){if(this.storage===null)return 0;try{let t=this.storage.getItem(R);if(t===null)return 0;let n=JSON.parse(t);if(typeof n!=`object`||!n)return 0;let r=n;return r.id===e&&typeof r.seq==`number`&&Number.isFinite(r.seq)?r.seq:0}catch{return 0}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(R,JSON.stringify({id:e,seq:t}))}catch{}}};function z(e,t){try{let n=e?.(t);ve(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function ve(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var B=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 ye(e){return typeof e==`function`?e():e}async function be(e){return new Promise(t=>{setTimeout(t,e)})}function V(e){try{return(0,t.strToU8)(JSON.stringify(e)).byteLength}catch{return 0}}function xe(e){let t=[],n=[],r=0;for(let i of e){let e=V(i);n.length>0&&r+e>48e3&&(t.push(n),n=[],r=0),n.push(i),r+=e}return n.length>0&&t.push(n),t}async function Se(e,t){return new Promise((n,r)=>{let i=[];typeof window<`u`&&i.push(window),typeof document<`u`&&i.push(document);let a=()=>{for(let e of i)e.removeEventListener(`securitypolicyviolation`,s)},o=(e,t)=>{if(a(),e!==null){r(e);return}n(t)},s=e=>{let t=e;(t.effectiveDirective.includes(`worker-src`)||t.violatedDirective.includes(`worker-src`))&&o(Error(`replay compression worker blocked by Content Security Policy`))};for(let e of i)e.addEventListener(`securitypolicyviolation`,s);try{e.gzip(t,{level:6},(e,t)=>{o(e,t)})}catch(e){a(),r(e instanceof Error?e:Error(String(e)))}})}async function Ce(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function we(e,t){return e instanceof B?e.status===429?e.retryAfter?.kind===`too-long`?void 0:e.retryAfter?.kind===`delay`?e.retryAfter.milliseconds:500*t:e.status<500?void 0:500*t:500*t}function Te(e,t){if(e===null)return{kind:`fallback`};let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?H(e*1e3):{kind:`fallback`}}let r=ke(n,t);return r===void 0?{kind:`fallback`}:H(Math.max(0,r-t))}function H(e){return e>1e4?{kind:`too-long`}:{kind:`delay`,milliseconds:e}}const Ee=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],De=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Oe=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function ke(e,t){let n=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(n!==null)return U(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),U(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 U(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function U(e,t,n,r,i,a,o){let s=Number(t),c=Ee.indexOf(n),l=Number(r),u=Number(i),d=Number(a),f=Number(o);if(c<0||s<1||s>31||u>23||d>59||f>59)return;let p=new Date(0);if(p.setUTCFullYear(l,c,s),p.setUTCHours(u,d,f,0),p.getUTCFullYear()!==l||p.getUTCMonth()!==c||p.getUTCDate()!==s||p.getUTCHours()!==u||p.getUTCMinutes()!==d||p.getUTCSeconds()!==f)return;let m=De.indexOf(e),h=Oe.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const Ae={mode:`off`,recording:!1,getSessionId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},W=`lf_session_replay_mode`,G=Symbol.for(`@pydantic/logfire-session-replay/controller`),K=1e3;function je(e){if(typeof window>`u`||typeof document>`u`)return Ae;let t=Re();try{let n=Ne(e),r=new me({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Z(n.onError,e),i}if(t!==void 0&&t.length>0)return i=t,t;let a=e?r.touch().id:r.getSession().id;return i=a,a},o=P(),s=a(!1),c,l=!1,u=Promise.resolve(),d,f=(e,t)=>{let r=Pe(n,e,o);if(!(r===`off`||l||e!==s))try{c=Me({config:n,getSessionId:a,mode:r,onSessionChanged:p,samplingModeStorage:o,sessionId:e})}catch(e){if(c=void 0,t)throw e;Z(n.onError,e)}},p=e=>{if(l||e===s)return;s=e;let t=c;c=void 0;let r=t?.deactivate()??Promise.resolve();u=u.then(async()=>{await X(r,n.onError),!l&&s===e&&f(e,!1)})},m;try{f(s,!0),m=setInterval(()=>{p(a(!1))},K)}catch(e){throw c?.discard(),c=void 0,e}return{get mode(){try{return c?.transport.getMode()??`off`}catch(e){return Z(n.onError,e),`off`}},get recording(){try{return c!==void 0}catch(e){return Z(n.onError,e),!1}},getSessionId:()=>a(!1),flush:async()=>{try{await u,await c?.transport.flush()}catch(e){Z(n.onError,e)}},stop:async()=>(d??=(async()=>{l=!0,clearInterval(m);let e=c;c=void 0,await X(e?.deactivate()??Promise.resolve(),n.onError),await u,r.flushPendingStorage(),t()})(),d)}}catch(e){throw t(),e}}function Me(e){let{config:t,getSessionId:n,mode:r,onSessionChanged:i,samplingModeStorage:a,sessionId:o}=e,c=new _e(t,o,r,void 0,void 0,de(t.getSessionAttributes,e=>{Z(t.onError,e)})),l=[],u=!0,d=()=>u,h;try{let e=A({emit:e=>{if(u)try{let t=n(!0);if(t!==o){i(t);return}c.add(e)}catch(e){Z(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:r===`buffer`?12e4:0,redactUrlPatterns:t.redactUrlPatterns});l.push(()=>{e.stop()});let g=(n,r)=>{if(u)try{e.addCustomEvent(n,r)}catch(e){Z(t.onError,e)}},_;if(t.getTraceContext!==void 0){let e=setInterval(()=>{if(u)try{let e=t.getTraceContext?.(),n=e?.traceId;n!==void 0&&n.length>0&&n!==_&&(_=n,g(s.Trace,{traceId:n,spanId:e?.spanId}))}catch(e){Z(t.onError,e)}},K);l.push(()=>{clearInterval(e)})}let v=e=>{d()&&(g(s.Error,e),d()&&c.getMode()===`buffer`&&(q(a,o,`full`),Y(c.triggerFlush(),t.onError)))},y=e=>{e instanceof ErrorEvent&&v($(e.message,e.filename,Ie(e.error)))},b=e=>{let t=e.reason;v($(ze(t?.message??e.reason),void 0,typeof t?.stack==`string`?t.stack:void 0))},x=()=>{document.visibilityState===`hidden`&&Y(c.flush({keepalive:!0}),t.onError)},S=()=>{Y(c.flush({keepalive:!0}),t.onError)};return window.addEventListener(`error`,y,!0),l.push(()=>{window.removeEventListener(`error`,y,!0)}),window.addEventListener(`unhandledrejection`,b,!0),l.push(()=>{window.removeEventListener(`unhandledrejection`,b,!0)}),document.addEventListener(`visibilitychange`,x),l.push(()=>{document.removeEventListener(`visibilitychange`,x)}),window.addEventListener(`pagehide`,S),l.push(()=>{window.removeEventListener(`pagehide`,S)}),t.captureConsole&&l.push(f(g,{onError:t.onError})),t.captureNetwork&&l.push(p(g,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&l.push(m(g,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),c.start(),{sessionId:o,transport:c,deactivate:async()=>(h??=(async()=>{u=!1,Q(l),await c.shutdown({keepalive:!1})})(),h),discard:()=>{u=!1,Q(l),c.discard()}}}catch(e){throw u=!1,Q(l),c.discard(),e}}function Ne(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=new URL(e.replayUrl,`https://logfire.invalid/`);if(t.search!==``||t.hash!==``)throw Error("logfire session replay: `replayUrl` must not contain a query or fragment");let n=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(n===void 0)throw Error("logfire session replay: no `fetch` available; pass `fetchImpl`");return{replayUrl:e.replayUrl,headers:e.headers,token:e.token,getSessionId:e.getSessionId,getSessionAttributes:e.getSessionAttributes,sessionSampleRate:e.sessionSampleRate??c.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??c.onErrorSampleRate,maskAllText:e.maskAllText??c.maskAllText,maskAllInputs:e.maskAllInputs??c.maskAllInputs,maskTextSelector:e.maskTextSelector??c.maskTextSelector,blockSelector:e.blockSelector??c.blockSelector,flushIntervalMs:e.flushIntervalMs??c.flushIntervalMs,maxBufferBytes:e.maxBufferBytes??c.maxBufferBytes,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??c.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??c.maxSessionDurationMs,distinctId:e.distinctId??c.distinctId,getDistinctId:e.getDistinctId,getTraceContext:e.getTraceContext,captureConsole:e.captureConsole??c.captureConsole,captureNetwork:e.captureNetwork??c.captureNetwork,captureNavigation:e.captureNavigation??c.captureNavigation,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...c.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function Pe(e,t,n){let r=Fe(n,t);if(r!==void 0)return r;let i=ce({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return q(n,t,i),i}function Fe(e,t){if(e!==null)try{let n=e.getItem(W);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!J(i.mode)?void 0:i.mode}catch{return}}function q(e,t,n){if(e!==null)try{e.setItem(W,JSON.stringify({id:t,mode:n}))}catch{}}function J(e){return e===`full`||e===`buffer`||e===`off`}function Ie(e){let t=typeof e==`object`&&e&&`stack`in e?e.stack:void 0;return typeof t==`string`?t:void 0}function Y(e,t){e.catch(e=>{Z(t,e)})}async function X(e,t){try{await e}catch(e){Z(t,e)}}function Z(e,t){try{let n=e?.(t);Le(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Le(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function Re(){let e=globalThis;if(e[G]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,G,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[G]===t&&Reflect.deleteProperty(e,G))}}function Q(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function $(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function ze(e){if(e==null)return`unhandledrejection`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);try{let t=JSON.stringify(e);return typeof t==`string`?t:Object.prototype.toString.call(e)}catch{return Object.prototype.toString.call(e)}}exports.CHUNK_ENVELOPE_VERSION=1,exports.CustomTag=s,exports.EventType=i,exports.IncrementalSource=a,exports.MouseInteractions=o,exports.startSessionReplay=je;
package/dist/index.d.cts CHANGED
@@ -39,6 +39,9 @@ declare const CHUNK_ENVELOPE_VERSION: 1;
39
39
  type MaybePromise<T> = T | Promise<T>;
40
40
  type ConsoleLevel = "log" | "info" | "warn" | "error" | "debug";
41
41
  type SamplingMode = "full" | "buffer" | "off";
42
+ type SessionAttributeValue = string | number | boolean;
43
+ type SessionAttributesInput = Record<string, SessionAttributeValue | undefined>;
44
+ type SessionAttributes = Record<string, SessionAttributeValue>;
42
45
  interface ConsolePayload {
43
46
  level: ConsoleLevel;
44
47
  args: string[];
@@ -55,7 +58,7 @@ interface NetworkPayload {
55
58
  }
56
59
  interface NavigationPayload {
57
60
  url: string;
58
- kind: "load" | "push" | "replace" | "pop";
61
+ kind: "push" | "replace" | "pop";
59
62
  }
60
63
  interface ChunkMeta {
61
64
  seq: number;
@@ -69,6 +72,7 @@ interface ChunkMeta {
69
72
  urls: string[];
70
73
  traceIds: string[];
71
74
  distinctId?: string;
75
+ sessionAttributes?: SessionAttributes;
72
76
  }
73
77
  interface ChunkEnvelope {
74
78
  version: typeof CHUNK_ENVELOPE_VERSION;
@@ -104,8 +108,17 @@ interface SessionReplayConfig {
104
108
  * pass its RUM session id here.
105
109
  */
106
110
  getSessionId?: () => string | undefined;
111
+ /**
112
+ * Returns low-cardinality, non-PII dimensions to snapshot once per replay
113
+ * session. Invalid or oversized entries are omitted.
114
+ */
115
+ getSessionAttributes?: () => SessionAttributesInput;
116
+ /** Probability of recording each new browser session in full. */
107
117
  sessionSampleRate?: number;
118
+ /** Probability of buffering each otherwise-unsampled session for uncaught error promotion. */
108
119
  onErrorSampleRate?: number;
120
+ /** Mask all rendered DOM text. Defaults to true. */
121
+ maskAllText?: boolean;
109
122
  maskAllInputs?: boolean;
110
123
  maskTextSelector?: string;
111
124
  blockSelector?: string;
@@ -140,4 +153,4 @@ interface SessionReplay {
140
153
  }
141
154
  declare function startSessionReplay(config: SessionReplayConfig): SessionReplay;
142
155
  //#endregion
143
- export { CHUNK_ENVELOPE_VERSION, type ChunkEnvelope, type ChunkMeta, type ConsolePayload, CustomTag, EventType, IncrementalSource, MouseInteractions, type NavigationPayload, type NetworkPayload, type RrwebEvent, type SamplingMode, SessionReplay, type SessionReplayConfig, startSessionReplay };
156
+ export { CHUNK_ENVELOPE_VERSION, type ChunkEnvelope, type ChunkMeta, type ConsolePayload, CustomTag, EventType, IncrementalSource, MouseInteractions, type NavigationPayload, type NetworkPayload, type RrwebEvent, type SamplingMode, type SessionAttributeValue, type SessionAttributes, type SessionAttributesInput, SessionReplay, type SessionReplayConfig, startSessionReplay };
package/dist/index.d.ts CHANGED
@@ -39,6 +39,9 @@ declare const CHUNK_ENVELOPE_VERSION: 1;
39
39
  type MaybePromise<T> = T | Promise<T>;
40
40
  type ConsoleLevel = "log" | "info" | "warn" | "error" | "debug";
41
41
  type SamplingMode = "full" | "buffer" | "off";
42
+ type SessionAttributeValue = string | number | boolean;
43
+ type SessionAttributesInput = Record<string, SessionAttributeValue | undefined>;
44
+ type SessionAttributes = Record<string, SessionAttributeValue>;
42
45
  interface ConsolePayload {
43
46
  level: ConsoleLevel;
44
47
  args: string[];
@@ -55,7 +58,7 @@ interface NetworkPayload {
55
58
  }
56
59
  interface NavigationPayload {
57
60
  url: string;
58
- kind: "load" | "push" | "replace" | "pop";
61
+ kind: "push" | "replace" | "pop";
59
62
  }
60
63
  interface ChunkMeta {
61
64
  seq: number;
@@ -69,6 +72,7 @@ interface ChunkMeta {
69
72
  urls: string[];
70
73
  traceIds: string[];
71
74
  distinctId?: string;
75
+ sessionAttributes?: SessionAttributes;
72
76
  }
73
77
  interface ChunkEnvelope {
74
78
  version: typeof CHUNK_ENVELOPE_VERSION;
@@ -104,8 +108,17 @@ interface SessionReplayConfig {
104
108
  * pass its RUM session id here.
105
109
  */
106
110
  getSessionId?: () => string | undefined;
111
+ /**
112
+ * Returns low-cardinality, non-PII dimensions to snapshot once per replay
113
+ * session. Invalid or oversized entries are omitted.
114
+ */
115
+ getSessionAttributes?: () => SessionAttributesInput;
116
+ /** Probability of recording each new browser session in full. */
107
117
  sessionSampleRate?: number;
118
+ /** Probability of buffering each otherwise-unsampled session for uncaught error promotion. */
108
119
  onErrorSampleRate?: number;
120
+ /** Mask all rendered DOM text. Defaults to true. */
121
+ maskAllText?: boolean;
109
122
  maskAllInputs?: boolean;
110
123
  maskTextSelector?: string;
111
124
  blockSelector?: string;
@@ -140,4 +153,4 @@ interface SessionReplay {
140
153
  }
141
154
  declare function startSessionReplay(config: SessionReplayConfig): SessionReplay;
142
155
  //#endregion
143
- export { CHUNK_ENVELOPE_VERSION, type ChunkEnvelope, type ChunkMeta, type ConsolePayload, CustomTag, EventType, IncrementalSource, MouseInteractions, type NavigationPayload, type NetworkPayload, type RrwebEvent, type SamplingMode, SessionReplay, type SessionReplayConfig, startSessionReplay };
156
+ export { CHUNK_ENVELOPE_VERSION, type ChunkEnvelope, type ChunkMeta, type ConsolePayload, CustomTag, EventType, IncrementalSource, MouseInteractions, type NavigationPayload, type NetworkPayload, type RrwebEvent, type SamplingMode, type SessionAttributeValue, type SessionAttributes, type SessionAttributesInput, SessionReplay, type SessionReplayConfig, startSessionReplay };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{record as e}from"rrweb";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},o={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},s={Error:`logfire.error`,Trace:`logfire.trace`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},c=1,l={sessionSampleRate:1,onErrorSampleRate:1,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:144e5,distinctId:``,captureConsole:!0,captureNetwork:!0,captureNavigation:!0},u=[`log`,`info`,`warn`,`error`,`debug`],d=1024,f=()=>void 0;function p(e,t={}){let n=new Map,r=!1;for(let r of u){let i=console[r];if(typeof i!=`function`)continue;let a=i;n.set(r,a),console[r]=(...n)=>{b(e,s.Console,{level:r,args:n.slice(0,10).map(x)},t.onError),a.apply(console,n)}}return()=>{if(!r){r=!0;for(let[e,t]of n)console[e]=t}}}function m(e,t){let n=v(t),r=g(e,n),i=_(e,n),a=!1;return()=>{a||(a=!0,r(),i())}}function h(e,t={}){let n=history.pushState,r=history.replaceState,i=!1,a=n=>{b(e,s.Navigation,{url:window.location.href,kind:n},t.onError)};history.pushState=function(...e){n.apply(this,e),a(`push`)},history.replaceState=function(...e){r.apply(this,e),a(`replace`)};let o=()=>{a(`pop`)};return window.addEventListener(`popstate`,o),()=>{i||(i=!0,history.pushState=n,history.replaceState=r,window.removeEventListener(`popstate`,o))}}function g(e,t){let n=window.fetch;if(typeof n!=`function`)return f;let r=!1;return window.fetch=async(r,i)=>{let a=t.now(),o=C(r,i),c=w(r);if(O(c,t.ignoreUrlPatterns))return n(r,i);let l=D(c,t.redactUrlPatterns),u=E(i?.body);try{let c=await n(r,i);return b(e,s.Network,T({method:o,url:l,status:c.status,durationMs:Math.max(0,t.now()-a),reqBytes:u,resBytes:ee(c.headers)}),t.onError),c}catch(n){throw b(e,s.Network,T({method:o,url:l,status:0,durationMs:Math.max(0,t.now()-a),failed:!0,reqBytes:u}),t.onError),n}},()=>{r||(r=!0,window.fetch=n)}}function _(e,t){let n=window.XMLHttpRequest.prototype,r=n.open,i=n.send,a=new WeakMap,o=!1;return n.open=function(e,n,i,o,s){let c=n.toString();if(O(c,t.ignoreUrlPatterns)){a.delete(this),r.call(this,e,n,i??!0,o??null,s??null);return}a.set(this,{method:e.toUpperCase(),url:D(c,t.redactUrlPatterns),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),r.call(this,e,n,i??!0,o??null,s??null)},n.send=function(n){let r=a.get(this);if(r===void 0){i.call(this,n);return}r.startedAt=t.now(),r.reqBytes=E(n);let o=()=>{r.failed=!0},c=()=>{r.emitted||(r.emitted=!0,this.removeEventListener(`error`,o),this.removeEventListener(`abort`,o),this.removeEventListener(`timeout`,o),b(e,s.Network,T({method:r.method,url:r.url,status:this.status,durationMs:Math.max(0,t.now()-r.startedAt),failed:r.failed||this.status===0,reqBytes:r.reqBytes,resBytes:te(this)}),t.onError))};this.addEventListener(`error`,o),this.addEventListener(`abort`,o),this.addEventListener(`timeout`,o),this.addEventListener(`loadend`,c,{once:!0});try{i.call(this,n)}catch(n){throw this.removeEventListener(`error`,o),this.removeEventListener(`abort`,o),this.removeEventListener(`timeout`,o),this.removeEventListener(`loadend`,c),b(e,s.Network,T({method:r.method,url:r.url,status:0,durationMs:Math.max(0,t.now()-r.startedAt),failed:!0,reqBytes:r.reqBytes}),t.onError),n}},()=>{o||(o=!0,n.open=r,n.send=i)}}function v(e){return{...e,ignoreUrlPatterns:y(e.ignoreUrlPatterns),redactUrlPatterns:y(e.redactUrlPatterns)}}function y(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function b(e,t,n,r){try{e(t,n)}catch(e){try{r?.(e)}catch{}}}function x(e){if(e==null)return String(e);if(typeof e==`string`)return S(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return S(e.stack??`${e.name}: ${e.message}`);try{return S(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function S(e){return e.length<=d?e:`${e.slice(0,d)}...(+${String(e.length-d)} chars)`}function C(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function w(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function ee(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 te(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 T(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 E(e){if(e==null)return 0;if(typeof e==`string`)return e.length;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Blob)return e.size}function D(e,t){if(t.length===0||!t.some(t=>t.test(e)))return e;try{let t=new URL(e,window.location.href);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}function O(e,t){return t.some(t=>t.test(e))}const k=e;function ne(e){let t={emit:t=>{e.emit(t)},maskAllInputs:e.maskAllInputs,recordCanvas:!1,collectFonts:!1,sampling:{mousemove:!0,mouseInteraction:!0,scroll:150,media:800,input:`last`}};e.maskTextSelector!==void 0&&e.maskTextSelector.length>0&&(t.maskTextSelector=e.maskTextSelector),e.blockSelector!==void 0&&e.blockSelector.length>0&&(t.blockSelector=e.blockSelector),e.checkoutEveryNms!==void 0&&e.checkoutEveryNms>0&&(t.checkoutEveryNms=e.checkoutEveryNms);let n=k(t);return{stop:()=>{n?.()},addCustomEvent:(e,t)=>{k.addCustomEvent?.(e,t)},takeFullSnapshot:()=>{k.takeFullSnapshot?.(!0)}}}function A(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function j(e){let t=e.random??Math.random;return t()<A(e.sessionSampleRate)?`full`:t()<A(e.onErrorSampleRate)?`buffer`:`off`}function M(e=Date.now){let t=e(),n=new Uint8Array(new ArrayBuffer(16));N(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/2**8)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function N(e){let t=globalThis.crypto;if(typeof t?.getRandomValues==`function`){t.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const P=`lf_session_replay`;var F=class{idleTimeoutMs;maxDurationMs;now;storage;memorySession;constructor(e){this.idleTimeoutMs=e.idleTimeoutMs,this.maxDurationMs=e.maxDurationMs,this.now=e.now??Date.now,this.storage=e.storage===void 0?I():e.storage}getSession(){let e=this.now(),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.write(t),t}reset(){return this.createSession(this.now())}isExpired(e,t){return t-e.lastActivityAt>this.idleTimeoutMs||t-e.startedAt>this.maxDurationMs}createSession(e){let t={id:M(this.now),startedAt:e,lastActivityAt:e};return this.write(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(P);if(e!==null){let t=JSON.parse(e);if(re(t))return this.memorySession=t,t}}catch{return this.memorySession}return this.memorySession}write(e){if(this.memorySession=e,this.storage!==null)try{this.storage.setItem(P,JSON.stringify(e))}catch{}}};function I(){try{return globalThis.sessionStorage??null}catch{return null}}function re(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}function L(e){return typeof e==`object`&&e?e:void 0}function R(e){return typeof e==`string`&&e.length>0?e:void 0}function ie(e,t,n){let r=1/0,c=0,l=0,u=0,d=0,f=!1,p=new Set,m=new Set;for(let e of t){e.timestamp<r&&(r=e.timestamp),e.timestamp>c&&(c=e.timestamp);let t=L(e.data);if(e.type===i.FullSnapshot)f=!0;else if(e.type===i.Meta){let e=R(t?.href);e!==void 0&&p.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)&&l++}else e===a.Input&&u++}else if(e.type===i.Custom&&t!==void 0){let e=R(t.tag),n=L(t.payload);if(e===s.Error)d++;else if(e===s.Trace){let e=R(n?.traceId);e!==void 0&&m.add(e)}else if(e===s.Console)n?.level===`error`&&d++;else if(e===s.Navigation){let e=R(n?.url);e!==void 0&&p.add(e)}}}return{seq:e,firstTimestamp:r===1/0?0:r,lastTimestamp:c,eventCount:t.length,clickCount:l,keypressCount:u,errorCount:d,hasFullSnapshot:f,urls:[...p],traceIds:[...m],...n!==void 0&&n.length>0?{distinctId:n}:{}}}const z=`lf_session_replay_seq`;var B=class{buffer=[];pendingBytes=0;seq=0;timer;mode;flushing;config;storage;sessionId;constructor(e,t,n,r=I()){this.config=e,this.sessionId=t,this.mode=n,this.storage=r,this.seq=this.loadSeq(t)}start(){this.timer!==void 0||this.mode!==`full`||(this.timer=setInterval(()=>{this.flushAndReport()},this.config.flushIntervalMs))}add(e){this.mode===`buffer`&&e.type===i.FullSnapshot&&(this.buffer=[],this.pendingBytes=0),this.buffer.push(e),this.pendingBytes+=W(e),this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&this.flushAndReport()}async triggerFlush(){return this.mode===`buffer`&&(this.mode=`full`,this.start()),this.flush()}async flush(e={}){if(this.mode===`buffer`||this.buffer.length===0)return;let t=this.buffer;this.buffer=[],this.pendingBytes=0;let n=e.keepalive===!0?G(t):[t],r=this.seq;this.seq+=n.length;let i=this.sessionId;this.saveSeq(i,this.seq);let a=(this.flushing??Promise.resolve()).then(async()=>{for(let t=0;t<n.length;t++){let a=n[t];a!==void 0&&await this.deliver(a,r+t,i,e.keepalive??!1)}});this.flushing=a.catch(()=>void 0),await a}rotate(e){return e===this.sessionId?!1:(this.mode===`buffer`?(this.buffer=[],this.pendingBytes=0):this.flushAndReport(),this.sessionId=e,this.seq=this.loadSeq(e),!0)}async shutdown(e={}){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),await this.flush(e),await this.flushing}getMode(){return this.mode}flushAndReport(){this.flush().catch(e=>{this.config.onError?.(e)})}async deliver(e,t,i,a){let o={version:1,meta:ie(t,e,this.config.getDistinctId?.()??this.config.distinctId),events:e};try{let e=JSON.stringify(o),s=a?n(r(e)):await K(e),c=a&&s.byteLength<=6e4;await this.sendWithRetry(i,t,s,c)}catch(e){this.config.onError?.(e)}}async sendWithRetry(e,t,n,r){let i=r?1:3;for(let a=1;a<=i;a++)try{await this.send(e,t,n,r);return}catch(e){if(e instanceof V&&e.status<500||a>=i)throw e;await U(500*a)}}async send(e,t,n,r){let i=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e)}?seq=${String(t)}`,a=await this.getUploadHeaders(),o=await this.config.fetchImpl(i,{method:`POST`,headers:a,body:n.slice(),keepalive:r});if(!o.ok)throw new V(o.status)}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await H(this.config.token);return{...e,...t===void 0||t.length===0?{}:{Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}loadSeq(e){if(this.storage===null)return 0;try{let t=this.storage.getItem(z);if(t===null)return 0;let n=JSON.parse(t);if(typeof n!=`object`||!n)return 0;let r=n;return r.id===e&&typeof r.seq==`number`&&Number.isFinite(r.seq)?r.seq:0}catch{return 0}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(z,JSON.stringify({id:e,seq:t}))}catch{}}},V=class extends Error{status;constructor(e){super(`replay ingest failed: ${String(e)}`),this.status=e,this.name=`ReplayIngestError`}};async function H(e){return typeof e==`function`?e():e}async function U(e){return new Promise(t=>{setTimeout(t,e)})}function W(e){try{return JSON.stringify(e).length}catch{return 0}}function G(e){let t=[],n=[],r=0;for(let i of e){let e=W(i);n.length>0&&r+e>48e3&&(t.push(n),n=[],r=0),n.push(i),r+=e}return n.length>0&&t.push(n),t}async function K(e){return new Promise((n,i)=>{t(r(e),{level:6},(e,t)=>{if(e!==null){i(e);return}n(t)})})}const q={mode:`off`,recording:!1,getSessionId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},J=`lf_session_replay_mode`;function ae(e){if(typeof window>`u`||typeof document>`u`)return q;let t=oe(e),n=new F({idleTimeoutMs:t.sessionIdleTimeoutMs,maxDurationMs:t.maxSessionDurationMs,now:t.now}),r=e=>{let r=t.getSessionId?.();return r!==void 0&&r.length>0?r:e?n.touch().id:n.getSession().id},i=r(!1),a=I(),o=se(t,i,a);if(o===`off`)return q;let c=new B(t,i,o),l={},u=ne({emit:e=>{let t=r(!0);c.rotate(t)&&l.current?.takeFullSnapshot(),c.add(e)},maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:o===`buffer`?12e4:0});l.current=u;let d,f=t.getTraceContext===void 0?void 0:setInterval(()=>{let e=t.getTraceContext?.(),n=e?.traceId;n!==void 0&&n.length>0&&n!==d&&(d=n,u.addCustomEvent(s.Trace,{traceId:n,spanId:e?.spanId}))},1e3),g=e=>{u.addCustomEvent(s.Error,e),c.getMode()===`buffer`&&(Y(a,r(!1),`full`),Q(c.triggerFlush(),t.onError))},_=e=>{g($(e.message,e.filename,X(e.error)))},v=e=>{let t=e.reason;g($(t?.message??String(e.reason??`unhandledrejection`),void 0,t?.stack))},y=()=>{document.visibilityState===`hidden`&&Q(c.flush({keepalive:!0}),t.onError)};window.addEventListener(`error`,_,!0),window.addEventListener(`unhandledrejection`,v,!0),document.addEventListener(`visibilitychange`,y),window.addEventListener(`pagehide`,y);let b=(e,t)=>{u.addCustomEvent(e,t)},x=t.captureConsole?p(b,{onError:t.onError}):Z,S=t.captureNetwork?m(b,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns}):Z,C=t.captureNavigation?h(b,{onError:t.onError}):Z;c.start();let w;return{get mode(){return c.getMode()},recording:!0,getSessionId:()=>r(!1),flush:async()=>c.flush(),stop:async()=>(w??=(async()=>{f!==void 0&&clearInterval(f),window.removeEventListener(`error`,_,!0),window.removeEventListener(`unhandledrejection`,v,!0),document.removeEventListener(`visibilitychange`,y),window.removeEventListener(`pagehide`,y),x(),S(),C(),u.stop(),await c.shutdown({keepalive:!1})})(),w)}}function oe(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(t===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,sessionSampleRate:e.sessionSampleRate??l.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??l.onErrorSampleRate,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,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??l.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??l.maxSessionDurationMs,distinctId:e.distinctId??l.distinctId,getDistinctId:e.getDistinctId,getTraceContext:e.getTraceContext,captureConsole:e.captureConsole??l.captureConsole,captureNetwork:e.captureNetwork??l.captureNetwork,captureNavigation:e.captureNavigation??l.captureNavigation,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[],onError:e.onError,fetchImpl:t,now:e.now??Date.now,random:e.random??Math.random}}function se(e,t,n){let r=ce(n,t);if(r!==void 0)return r;let i=j({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return Y(n,t,i),i}function ce(e,t){if(e!==null)try{let n=e.getItem(J);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!le(i.mode)?void 0:i.mode}catch{return}}function Y(e,t,n){if(e!==null)try{e.setItem(J,JSON.stringify({id:t,mode:n}))}catch{}}function le(e){return e===`full`||e===`buffer`||e===`off`}function X(e){let t=typeof e==`object`&&e&&`stack`in e?e.stack:void 0;return typeof t==`string`?t:void 0}function Z(){}function Q(e,t){e.catch(e=>{t?.(e)})}function $(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}export{c as CHUNK_ENVELOPE_VERSION,s as CustomTag,i as EventType,a as IncrementalSource,o as MouseInteractions,ae as startSessionReplay};
1
+ import{record as e}from"rrweb";import{gzip as t,gzipSync as n,strToU8 as r}from"fflate";function i(e,t){return t.some(t=>new RegExp(t.source,t.flags).test(e))}function a(e,t,n){if(!i(e,t))return e;try{let t=new URL(e,n);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const o={DomContentLoaded:0,Load:1,FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Custom:5,Plugin:6},s={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5},c={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},l={Error:`logfire.error`,Trace:`logfire.trace`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},u=1,d={sessionSampleRate:1,onErrorSampleRate:1,maskAllText:!0,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:144e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,redactUrlPatterns:[/.+/u]},f=[`log`,`info`,`warn`,`error`,`debug`],p=1024,m=()=>void 0;function h(e,t={}){let n=[],r=x(t.onError);try{for(let t of f)typeof console[t]==`function`&&n.push(S(console,t,(n,i)=>function(...a){return i()&&b(e,l.Console,{level:t,args:a.slice(0,10).map(re)},r),n.apply(this,a)}));return C(n)}catch(e){throw w(n),e}}function ee(e,t){let n=v(t),r={...n,onError:x(n.onError)},i=g(e,r);try{return C([i,_(e,r)])}catch(e){throw i(),e}}function te(e,t={redactUrlPatterns:[]}){let n=x(t.onError),r=r=>{let i=a(window.location.href,t.redactUrlPatterns??[],window.location.href);b(e,l.Navigation,{url:i,kind:r},n)},i=[];try{i.push(S(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(S(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)}),C(i)}catch(e){throw w(i),e}}function g(e,t){return typeof window.fetch==`function`?S(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(),u=ie(i,o),d=E(i);if(k(d,t.ignoreUrlPatterns))return s.call(this,i,o);let f=a(d,t.redactUrlPatterns,window.location.href),p=O(o?.body);try{let n=await s.call(this,i,o);return r()&&b(e,l.Network,D({method:u,url:f,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:p,resBytes:ae(n.headers)}),t.onError),n}catch(n){throw r()&&b(e,l.Network,D({method:u,url:f,status:0,durationMs:Math.max(0,t.now()-c),failed:!0,reqBytes:p}),t.onError),n}},o=Reflect.get(n,`__original`);return Object.defineProperty(i,"__original",{configurable:!0,value:typeof o==`function`?o:n,writable:!0}),i}):m}function _(e,t){let n=window.XMLHttpRequest.prototype,r=new WeakMap,i=[];try{return i.push(S(n,`open`,(e,n)=>function(...i){let[o,s]=i;if(!n())return e.apply(this,i);let c=s.toString();return k(c,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:o.toUpperCase(),url:a(c,t.redactUrlPatterns,window.location.href),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(S(n,`send`,(n,i)=>function(...a){let[o]=a,s=i()?r.get(this):void 0;if(s===void 0)return n.apply(this,a);s.startedAt=t.now(),s.reqBytes=O(o);let c=()=>{s.failed=!0},u=()=>{s.emitted||(s.emitted=!0,this.removeEventListener(`error`,c),this.removeEventListener(`abort`,c),this.removeEventListener(`timeout`,c),i()&&b(e,l.Network,D({method:s.method,url:s.url,status:this.status,durationMs:Math.max(0,t.now()-s.startedAt),failed:s.failed||this.status===0,reqBytes:s.reqBytes,resBytes:oe(this)}),t.onError))};this.addEventListener(`error`,c),this.addEventListener(`abort`,c),this.addEventListener(`timeout`,c),this.addEventListener(`loadend`,u,{once:!0});try{return n.apply(this,a)}catch(n){throw this.removeEventListener(`error`,c),this.removeEventListener(`abort`,c),this.removeEventListener(`timeout`,c),this.removeEventListener(`loadend`,u),i()&&b(e,l.Network,D({method:s.method,url:s.url,status:0,durationMs:Math.max(0,t.now()-s.startedAt),failed:!0,reqBytes:s.reqBytes}),t.onError),n}})),C(i)}catch(e){throw w(i),e}}function v(e){return{...e,ignoreUrlPatterns:y(e.ignoreUrlPatterns),redactUrlPatterns:y(e.redactUrlPatterns)}}function y(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function b(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function x(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 S(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return m;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function C(e){let t=!1;return()=>{t||(t=!0,w(e))}}function w(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 T(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return T(e.stack??`${e.name}: ${e.message}`);try{return T(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function T(e){return e.length<=p?e:`${e.slice(0,p)}...(+${String(e.length-p)} chars)`}function ie(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function E(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function ae(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 oe(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 D(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 O(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 k(e,t){return i(e,t)}const A=e,se=new Set([`action`,`formaction`,`href`,`src`]);function ce(e){let t={emit:t=>{e.emit(le(t,e.redactUrlPatterns))},maskAllInputs:e.maskAllInputs,recordCanvas:!1,collectFonts:!1,sampling:{mousemove:!0,mouseInteraction:!0,scroll:150,media:800,input:`last`}};e.maskAllText?t.maskTextSelector=`*`:e.maskTextSelector!==void 0&&e.maskTextSelector.length>0&&(t.maskTextSelector=e.maskTextSelector),e.blockSelector!==void 0&&e.blockSelector.length>0&&(t.blockSelector=e.blockSelector),e.checkoutEveryNms!==void 0&&e.checkoutEveryNms>0&&(t.checkoutEveryNms=e.checkoutEveryNms);let n=A(t);if(n===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{n()},addCustomEvent:(e,t)=>{A.addCustomEvent?.(e,t)}}}function le(e,t){if(typeof e.data!=`object`||e.data===null)return e;let n=e.data;if(e.type===o.Meta){if(typeof n.href!=`string`)return e;let r=a(n.href,t,window.location.href);return r===n.href?e:{...e,data:{...n,href:r}}}if(e.type!==o.FullSnapshot&&(e.type!==o.IncrementalSnapshot||n.source!==s.Mutation))return e;let r=j(n,t);return r===n?e:{...e,data:r}}function j(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=j(i,t);e!==i&&(n=!0),r.push(e)}return n?r:e}if(typeof e!=`object`||!e)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n=e===`attributes`&&!Array.isArray(a)?ue(a,t):j(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function ue(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=!1,i={};for(let[e,o]of Object.entries(n)){if(!se.has(e.toLowerCase())||typeof o!=`string`){i[e]=o;continue}let n=a(o,t,window.location.href);n!==o&&(r=!0),i[e]=n}return r?i:e}function M(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function de(e){let t=e.random??Math.random;return t()<M(e.sessionSampleRate)?`full`:t()<M(e.onErrorSampleRate)?`buffer`:`off`}const fe=/^[a-z][a-z0-9_]{0,63}$/u;function pe(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function me(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(!fe.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`&&pe(r,200))&&(a[e]=r,o+=1,o===20))break}return Object.freeze(a)}function he(e=Date.now){let t=e(),n=new Uint8Array(new ArrayBuffer(16));ge(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/2**8)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function ge(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 N=`lf_session_replay`;var _e=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?P():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:he(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(N);if(e!==null){let t=JSON.parse(e);if(F(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(N,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 P(){try{return globalThis.sessionStorage??null}catch{return null}}function F(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}function I(e){return typeof e==`object`&&e?e:void 0}function L(e){return typeof e==`string`&&e.length>0?e:void 0}function ve(e,t,n,r={}){let i=1/0,a=0,u=0,d=0,f=0,p=!1,m=new Set,h=new Set;for(let e of t){e.timestamp<i&&(i=e.timestamp),e.timestamp>a&&(a=e.timestamp);let t=I(e.data);if(e.type===o.FullSnapshot)p=!0;else if(e.type===o.Meta){let e=L(t?.href);e!==void 0&&m.add(e)}else if(e.type===o.IncrementalSnapshot&&t!==void 0){let e=t.source;if(e===s.MouseInteraction){let e=t.type;(e===c.Click||e===c.DblClick)&&u++}else e===s.Input&&d++}else if(e.type===o.Custom&&t!==void 0){let e=L(t.tag),n=I(t.payload);if(e===l.Error)f++;else if(e===l.Trace){let e=L(n?.traceId);e!==void 0&&h.add(e)}else if(e===l.Console)n?.level===`error`&&f++;else if(e===l.Navigation){let e=L(n?.url);e!==void 0&&m.add(e)}}}return{seq:e,firstTimestamp:i===1/0?0:i,lastTimestamp:a,eventCount:t.length,clickCount:u,keypressCount:d,errorCount:f,hasFullSnapshot:p,urls:[...m],traceIds:[...h],...n!==void 0&&n.length>0?{distinctId:n}:{},...Object.keys(r).length===0?{}:{sessionAttributes:{...r}}}}const R=`lf_session_replay_seq`,ye={gzip:t,gzipSync:n};var be=class{buffer=[];pendingBytes=0;seq=0;timer;mode;flushing;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;constructor(e,t,n,r=P(),i=ye,a={}){this.config=e,this.sessionId=t,this.sessionAttributes=Object.freeze({...a}),this.mode=n,this.storage=r,this.compression=i,this.seq=this.loadSeq(t)}start(){this.timer!==void 0||this.mode!==`full`||(this.timer=setInterval(()=>{this.flushAndReport()},this.config.flushIntervalMs))}add(e){let t=H(e);if(this.mode===`buffer`){if(e.type===o.FullSnapshot){this.buffer=[e],this.pendingBytes=t;return}if(this.buffer.length===0||t>this.config.maxBufferBytes||this.pendingBytes+t>this.config.maxBufferBytes)return}this.buffer.push(e),this.pendingBytes+=t,this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&this.flushAndReport()}async triggerFlush(){return this.mode===`buffer`&&(this.mode=`full`,this.start()),this.flush()}async flush(e={}){if(this.mode===`buffer`||this.buffer.length===0)return;let t=this.buffer;this.buffer=[],this.pendingBytes=0;let n=e.keepalive===!0?Ce(t):[t],r=this.seq;this.seq+=n.length;let i=this.sessionId;this.saveSeq(i,this.seq);let a=e.keepalive===!0?Promise.resolve():this.flushing??Promise.resolve(),o=e.keepalive===!0?this.deliverLifecycle(n,r,i):a.then(async()=>{for(let e=0;e<n.length;e++){let t=n[e];t!==void 0&&await this.deliverOrdinary(t,r+e,i)}}),s=this.flushing;this.flushing=e.keepalive===!0&&s!==void 0?Promise.all([s,o]).then(()=>void 0,()=>void 0):o.catch(()=>void 0),await o}async shutdown(e={}){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),await this.flush(e),await this.flushing}discard(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),this.buffer=[],this.pendingBytes=0}getMode(){return this.mode}flushAndReport(){this.flush().catch(e=>{z(this.config.onError,e)})}createEnvelope(e,t){let n=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{n=this.config.getDistinctId()??this.config.distinctId}catch(e){z(this.config.onError,e)}return{version:1,meta:ve(t,e,n,this.sessionAttributes),events:e}}async deliverOrdinary(e,t,n){let i=this.createEnvelope(e,t);try{let e=r(JSON.stringify(i)),a=await this.compressOrdinary(e);await this.sendWithRetry({body:a,lifecycle:!1,requestKeepalive:!1,reservedBytes:0,seq:t,sessionId:n})}catch(e){z(this.config.onError,e)}}async deliverLifecycle(e,t,n){let i=[];for(let a=0;a<e.length;a++){let o=e[a];if(o===void 0){i.push(void 0);continue}let s=this.createEnvelope(o,t+a);try{i.push({body:this.compression.gzipSync(r(JSON.stringify(s))),lifecycle:!0,requestKeepalive:!1,reservedBytes:0,seq:t+a,sessionId:n})}catch(e){z(this.config.onError,e),i.push(void 0)}}let a=!0,o=Math.max(0,48e3-this.reservedKeepaliveBytes);for(let e of i){if(e===void 0){a=!1;continue}a&&e.body.byteLength<=o?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,o-=e.reservedBytes):a=!1}await Promise.all(i.map(async e=>{if(e!==void 0)try{await this.sendWithRetry(e)}catch(e){z(this.config.onError,e)}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await we(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async sendWithRetry(e){let t=e.lifecycle?1:3;for(let n=1;n<=t;n++)try{await this.send(e);return}catch(e){let r=Ee(e,n);if(r===void 0||n>=t)throw e;await Se(r)}}async send(e){let t,n,r,i=new AbortController,a=setTimeout(()=>{i.abort(Error(`replay upload timed out after 10000ms`))},1e4);try{let a=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,o=await this.getUploadHeaders(),s=this.config.fetchImpl(a,{method:`POST`,headers:o,body:e.body.slice(),keepalive:e.requestKeepalive,signal:i.signal});t=!0;let c=await s;if(n=!0,r=await Te(c),!c.ok){let e=c.status===429?De(c.headers.get(`retry-after`),Date.now()):void 0;throw new B(c.status,e)}}finally{clearTimeout(a),e.reservedBytes>0&&(t!==!0||n!==!0||r===!0)&&(this.reservedKeepaliveBytes=Math.max(0,this.reservedKeepaliveBytes-e.reservedBytes))}}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await V(this.config.token);return{...e,...t===void 0||t.length===0?{}:{Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}loadSeq(e){if(this.storage===null)return 0;try{let t=this.storage.getItem(R);if(t===null)return 0;let n=JSON.parse(t);if(typeof n!=`object`||!n)return 0;let r=n;return r.id===e&&typeof r.seq==`number`&&Number.isFinite(r.seq)?r.seq:0}catch{return 0}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(R,JSON.stringify({id:e,seq:t}))}catch{}}};function z(e,t){try{let n=e?.(t);xe(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function xe(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var B=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 V(e){return typeof e==`function`?e():e}async function Se(e){return new Promise(t=>{setTimeout(t,e)})}function H(e){try{return r(JSON.stringify(e)).byteLength}catch{return 0}}function Ce(e){let t=[],n=[],r=0;for(let i of e){let e=H(i);n.length>0&&r+e>48e3&&(t.push(n),n=[],r=0),n.push(i),r+=e}return n.length>0&&t.push(n),t}async function we(e,t){return new Promise((n,r)=>{let i=[];typeof window<`u`&&i.push(window),typeof document<`u`&&i.push(document);let a=()=>{for(let e of i)e.removeEventListener(`securitypolicyviolation`,s)},o=(e,t)=>{if(a(),e!==null){r(e);return}n(t)},s=e=>{let t=e;(t.effectiveDirective.includes(`worker-src`)||t.violatedDirective.includes(`worker-src`))&&o(Error(`replay compression worker blocked by Content Security Policy`))};for(let e of i)e.addEventListener(`securitypolicyviolation`,s);try{e.gzip(t,{level:6},(e,t)=>{o(e,t)})}catch(e){a(),r(e instanceof Error?e:Error(String(e)))}})}async function Te(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function Ee(e,t){return e instanceof B?e.status===429?e.retryAfter?.kind===`too-long`?void 0:e.retryAfter?.kind===`delay`?e.retryAfter.milliseconds:500*t:e.status<500?void 0:500*t:500*t}function De(e,t){if(e===null)return{kind:`fallback`};let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?U(e*1e3):{kind:`fallback`}}let r=je(n,t);return r===void 0?{kind:`fallback`}:U(Math.max(0,r-t))}function U(e){return e>1e4?{kind:`too-long`}:{kind:`delay`,milliseconds:e}}const Oe=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],ke=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Ae=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function je(e,t){let n=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(n!==null)return W(n[1],n[2],n[3],n[4],n[5],n[6],n[7]);let r=/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(r!==null){let e=new Date(t).getUTCFullYear(),n=Number(r[4]),i=Math.floor(e/100)*100+n;return i>e+50&&(i-=100),W(r[1],r[2],r[3],String(i),r[5],r[6],r[7])}let i=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/u.exec(e);if(i!==null)return W(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function W(e,t,n,r,i,a,o){let s=Number(t),c=Oe.indexOf(n),l=Number(r),u=Number(i),d=Number(a),f=Number(o);if(c<0||s<1||s>31||u>23||d>59||f>59)return;let p=new Date(0);if(p.setUTCFullYear(l,c,s),p.setUTCHours(u,d,f,0),p.getUTCFullYear()!==l||p.getUTCMonth()!==c||p.getUTCDate()!==s||p.getUTCHours()!==u||p.getUTCMinutes()!==d||p.getUTCSeconds()!==f)return;let m=ke.indexOf(e),h=Ae.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const Me={mode:`off`,recording:!1,getSessionId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},G=`lf_session_replay_mode`,K=Symbol.for(`@pydantic/logfire-session-replay/controller`),q=1e3;function Ne(e){if(typeof window>`u`||typeof document>`u`)return Me;let t=Ve();try{let n=Fe(e),r=new _e({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Z(n.onError,e),i}if(t!==void 0&&t.length>0)return i=t,t;let a=e?r.touch().id:r.getSession().id;return i=a,a},o=P(),s=a(!1),c,l=!1,u=Promise.resolve(),d,f=(e,t)=>{let r=Ie(n,e,o);if(!(r===`off`||l||e!==s))try{c=Pe({config:n,getSessionId:a,mode:r,onSessionChanged:p,samplingModeStorage:o,sessionId:e})}catch(e){if(c=void 0,t)throw e;Z(n.onError,e)}},p=e=>{if(l||e===s)return;s=e;let t=c;c=void 0;let r=t?.deactivate()??Promise.resolve();u=u.then(async()=>{await X(r,n.onError),!l&&s===e&&f(e,!1)})},m;try{f(s,!0),m=setInterval(()=>{p(a(!1))},q)}catch(e){throw c?.discard(),c=void 0,e}return{get mode(){try{return c?.transport.getMode()??`off`}catch(e){return Z(n.onError,e),`off`}},get recording(){try{return c!==void 0}catch(e){return Z(n.onError,e),!1}},getSessionId:()=>a(!1),flush:async()=>{try{await u,await c?.transport.flush()}catch(e){Z(n.onError,e)}},stop:async()=>(d??=(async()=>{l=!0,clearInterval(m);let e=c;c=void 0,await X(e?.deactivate()??Promise.resolve(),n.onError),await u,r.flushPendingStorage(),t()})(),d)}}catch(e){throw t(),e}}function Pe(e){let{config:t,getSessionId:n,mode:r,onSessionChanged:i,samplingModeStorage:a,sessionId:o}=e,s=new be(t,o,r,void 0,void 0,me(t.getSessionAttributes,e=>{Z(t.onError,e)})),c=[],u=!0,d=()=>u,f;try{let e=ce({emit:e=>{if(u)try{let t=n(!0);if(t!==o){i(t);return}s.add(e)}catch(e){Z(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:r===`buffer`?12e4:0,redactUrlPatterns:t.redactUrlPatterns});c.push(()=>{e.stop()});let p=(n,r)=>{if(u)try{e.addCustomEvent(n,r)}catch(e){Z(t.onError,e)}},m;if(t.getTraceContext!==void 0){let e=setInterval(()=>{if(u)try{let e=t.getTraceContext?.(),n=e?.traceId;n!==void 0&&n.length>0&&n!==m&&(m=n,p(l.Trace,{traceId:n,spanId:e?.spanId}))}catch(e){Z(t.onError,e)}},q);c.push(()=>{clearInterval(e)})}let g=e=>{d()&&(p(l.Error,e),d()&&s.getMode()===`buffer`&&(J(a,o,`full`),Y(s.triggerFlush(),t.onError)))},_=e=>{e instanceof ErrorEvent&&g($(e.message,e.filename,ze(e.error)))},v=e=>{let t=e.reason;g($(He(t?.message??e.reason),void 0,typeof t?.stack==`string`?t.stack:void 0))},y=()=>{document.visibilityState===`hidden`&&Y(s.flush({keepalive:!0}),t.onError)},b=()=>{Y(s.flush({keepalive:!0}),t.onError)};return window.addEventListener(`error`,_,!0),c.push(()=>{window.removeEventListener(`error`,_,!0)}),window.addEventListener(`unhandledrejection`,v,!0),c.push(()=>{window.removeEventListener(`unhandledrejection`,v,!0)}),document.addEventListener(`visibilitychange`,y),c.push(()=>{document.removeEventListener(`visibilitychange`,y)}),window.addEventListener(`pagehide`,b),c.push(()=>{window.removeEventListener(`pagehide`,b)}),t.captureConsole&&c.push(h(p,{onError:t.onError})),t.captureNetwork&&c.push(ee(p,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&c.push(te(p,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),s.start(),{sessionId:o,transport:s,deactivate:async()=>(f??=(async()=>{u=!1,Q(c),await s.shutdown({keepalive:!1})})(),f),discard:()=>{u=!1,Q(c),s.discard()}}}catch(e){throw u=!1,Q(c),s.discard(),e}}function Fe(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??d.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??d.onErrorSampleRate,maskAllText:e.maskAllText??d.maskAllText,maskAllInputs:e.maskAllInputs??d.maskAllInputs,maskTextSelector:e.maskTextSelector??d.maskTextSelector,blockSelector:e.blockSelector??d.blockSelector,flushIntervalMs:e.flushIntervalMs??d.flushIntervalMs,maxBufferBytes:e.maxBufferBytes??d.maxBufferBytes,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??d.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??d.maxSessionDurationMs,distinctId:e.distinctId??d.distinctId,getDistinctId:e.getDistinctId,getTraceContext:e.getTraceContext,captureConsole:e.captureConsole??d.captureConsole,captureNetwork:e.captureNetwork??d.captureNetwork,captureNavigation:e.captureNavigation??d.captureNavigation,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...d.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function Ie(e,t,n){let r=Le(n,t);if(r!==void 0)return r;let i=de({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return J(n,t,i),i}function Le(e,t){if(e!==null)try{let n=e.getItem(G);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!Re(i.mode)?void 0:i.mode}catch{return}}function J(e,t,n){if(e!==null)try{e.setItem(G,JSON.stringify({id:t,mode:n}))}catch{}}function Re(e){return e===`full`||e===`buffer`||e===`off`}function ze(e){let t=typeof e==`object`&&e&&`stack`in e?e.stack:void 0;return typeof t==`string`?t:void 0}function Y(e,t){e.catch(e=>{Z(t,e)})}async function X(e,t){try{await e}catch(e){Z(t,e)}}function Z(e,t){try{let n=e?.(t);Be(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Be(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function Ve(){let e=globalThis;if(e[K]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,K,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[K]===t&&Reflect.deleteProperty(e,K))}}function Q(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function $(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function He(e){if(e==null)return`unhandledrejection`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);try{let t=JSON.stringify(e);return typeof t==`string`?t:Object.prototype.toString.call(e)}catch{return Object.prototype.toString.call(e)}}export{u as CHUNK_ENVELOPE_VERSION,l as CustomTag,o as EventType,s as IncrementalSource,c as MouseInteractions,Ne as startSessionReplay};
package/package.json CHANGED
@@ -24,7 +24,7 @@
24
24
  "rum",
25
25
  "rrweb"
26
26
  ],
27
- "version": "0.1.0-alpha.1",
27
+ "version": "0.2.0",
28
28
  "type": "module",
29
29
  "main": "./dist/index.cjs",
30
30
  "module": "./dist/index.js",