@depsmith/depsmith-sdk 0.9.4 → 0.9.5

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.
@@ -0,0 +1,56 @@
1
+ /** REPLAY_SPEC §2.1 `ReplayState` / `ReplayReason`, as their wire strings. */
2
+ type ReplayState = 'off' | 'admitting' | 'recording' | 'paused' | 'finalizing';
3
+ type ReplayReason = 'not_initialized' | 'consent_not_granted' | 'child_safe_mode' | 'shutdown' | 'stopped' | 'opted_out' | 'not_sampled' | 'admission_denied' | 'admission_unavailable' | 'quota_exhausted' | 'policy_revoked' | 'policy_stale' | 'recording_closed' | 'chunk_conflict' | 'limit' | 'background' | 'resource_limit' | 'unsupported_platform' | 'remote_disabled' | 'awaiting_start_event';
4
+ interface ReplayStatus {
5
+ state: ReplayState;
6
+ reason?: ReplayReason;
7
+ recordingId?: string;
8
+ }
9
+ interface ReplayStartOptions {
10
+ allowedScreens?: string[];
11
+ excludedScreens?: string[];
12
+ }
13
+
14
+ /**
15
+ * Replay markers on the web (REPLAY_SPEC §6.4, Web): data attributes, named like the mobile
16
+ * `nativeID`s and the autocapture markers the page may already use.
17
+ *
18
+ * | Attribute | Pixels | Pointers (§6.7) |
19
+ * |------------------------------|------------------------------------------|-----------------------|
20
+ * | `data-depsmith-sdk-mask` | the whole subtree is one block, images too | recorded |
21
+ * | `data-depsmith-sdk-allow` | text inside is drawn; password/OTP stay masked | recorded |
22
+ * | `data-depsmith-sdk-exclude` | as the default (§6.2) | recorded without coordinates |
23
+ * | `data-depsmith-sdk-no-capture` (existing) | as the default | recorded without coordinates |
24
+ *
25
+ * Mask and Exclude win over Allow on the same element; an Allow inside a Mask has no effect.
26
+ */
27
+ declare const MASK_ATTR = "data-depsmith-sdk-mask";
28
+ declare const ALLOW_ATTR = "data-depsmith-sdk-allow";
29
+ declare const EXCLUDE_ATTR = "data-depsmith-sdk-exclude";
30
+ declare const NO_CAPTURE_ATTR = "data-depsmith-sdk-no-capture";
31
+
32
+ interface ReplayStopOptions {
33
+ /** Purge what is not uploaded yet and revoke the recording, instead of finishing it. */
34
+ discardPending?: boolean;
35
+ }
36
+ /** Whether this page can record at all: a window, a 2D canvas, IndexedDB, DEFLATE and SubtleCrypto. */
37
+ declare function replaySupported(): boolean;
38
+ declare const sessionReplay: {
39
+ /**
40
+ * Plugs Session Replay into the core. Idempotent. Before `init()` it lets this page load
41
+ * recover what an earlier one left (§10.2); `start()` installs on first use as well.
42
+ */
43
+ install(): void;
44
+ /**
45
+ * Arms replay for this page load and requests admission (§2.1). Optional since the project's
46
+ * remote config starts it by itself (§4.5), or from its start event (§4.6); while waiting for
47
+ * that event it acts as one. Resolves `off` / `remote_disabled` when the project's rule turns
48
+ * replay off. Never rejects; resolves within 10 s.
49
+ */
50
+ start(options?: ReplayStartOptions): Promise<ReplayStatus>;
51
+ /** Capture is off before this resolves (§2.1). Never rejects. */
52
+ stop(options?: ReplayStopOptions): Promise<void>;
53
+ getStatus(): ReplayStatus;
54
+ };
55
+
56
+ export { ALLOW_ATTR, EXCLUDE_ATTR, MASK_ATTR, NO_CAPTURE_ATTR, type ReplayReason, type ReplayStartOptions, type ReplayState, type ReplayStatus, type ReplayStopOptions, sessionReplay as default, replaySupported, sessionReplay };
@@ -0,0 +1,56 @@
1
+ /** REPLAY_SPEC §2.1 `ReplayState` / `ReplayReason`, as their wire strings. */
2
+ type ReplayState = 'off' | 'admitting' | 'recording' | 'paused' | 'finalizing';
3
+ type ReplayReason = 'not_initialized' | 'consent_not_granted' | 'child_safe_mode' | 'shutdown' | 'stopped' | 'opted_out' | 'not_sampled' | 'admission_denied' | 'admission_unavailable' | 'quota_exhausted' | 'policy_revoked' | 'policy_stale' | 'recording_closed' | 'chunk_conflict' | 'limit' | 'background' | 'resource_limit' | 'unsupported_platform' | 'remote_disabled' | 'awaiting_start_event';
4
+ interface ReplayStatus {
5
+ state: ReplayState;
6
+ reason?: ReplayReason;
7
+ recordingId?: string;
8
+ }
9
+ interface ReplayStartOptions {
10
+ allowedScreens?: string[];
11
+ excludedScreens?: string[];
12
+ }
13
+
14
+ /**
15
+ * Replay markers on the web (REPLAY_SPEC §6.4, Web): data attributes, named like the mobile
16
+ * `nativeID`s and the autocapture markers the page may already use.
17
+ *
18
+ * | Attribute | Pixels | Pointers (§6.7) |
19
+ * |------------------------------|------------------------------------------|-----------------------|
20
+ * | `data-depsmith-sdk-mask` | the whole subtree is one block, images too | recorded |
21
+ * | `data-depsmith-sdk-allow` | text inside is drawn; password/OTP stay masked | recorded |
22
+ * | `data-depsmith-sdk-exclude` | as the default (§6.2) | recorded without coordinates |
23
+ * | `data-depsmith-sdk-no-capture` (existing) | as the default | recorded without coordinates |
24
+ *
25
+ * Mask and Exclude win over Allow on the same element; an Allow inside a Mask has no effect.
26
+ */
27
+ declare const MASK_ATTR = "data-depsmith-sdk-mask";
28
+ declare const ALLOW_ATTR = "data-depsmith-sdk-allow";
29
+ declare const EXCLUDE_ATTR = "data-depsmith-sdk-exclude";
30
+ declare const NO_CAPTURE_ATTR = "data-depsmith-sdk-no-capture";
31
+
32
+ interface ReplayStopOptions {
33
+ /** Purge what is not uploaded yet and revoke the recording, instead of finishing it. */
34
+ discardPending?: boolean;
35
+ }
36
+ /** Whether this page can record at all: a window, a 2D canvas, IndexedDB, DEFLATE and SubtleCrypto. */
37
+ declare function replaySupported(): boolean;
38
+ declare const sessionReplay: {
39
+ /**
40
+ * Plugs Session Replay into the core. Idempotent. Before `init()` it lets this page load
41
+ * recover what an earlier one left (§10.2); `start()` installs on first use as well.
42
+ */
43
+ install(): void;
44
+ /**
45
+ * Arms replay for this page load and requests admission (§2.1). Optional since the project's
46
+ * remote config starts it by itself (§4.5), or from its start event (§4.6); while waiting for
47
+ * that event it acts as one. Resolves `off` / `remote_disabled` when the project's rule turns
48
+ * replay off. Never rejects; resolves within 10 s.
49
+ */
50
+ start(options?: ReplayStartOptions): Promise<ReplayStatus>;
51
+ /** Capture is off before this resolves (§2.1). Never rejects. */
52
+ stop(options?: ReplayStopOptions): Promise<void>;
53
+ getStatus(): ReplayStatus;
54
+ };
55
+
56
+ export { ALLOW_ATTR, EXCLUDE_ATTR, MASK_ATTR, NO_CAPTURE_ATTR, type ReplayReason, type ReplayStartOptions, type ReplayState, type ReplayStatus, type ReplayStopOptions, sessionReplay as default, replaySupported, sessionReplay };
package/dist/replay.js ADDED
@@ -0,0 +1,3 @@
1
+ function be(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)>>>0;return e.toString(36)}var we="@depsmith/depsmith-sdk",Se="0.9.5";var Q=Symbol.for("depsmith.sdk.replay.registry"),ke=()=>globalThis[Q]??(globalThis[Q]={});function _e(r){let e=ke();if(e.integration!==r&&(e.integration=r,e.current))try{r.clientCreated(e.current)}catch{}}function R(r,e){let t=r?.hooks;if(t)try{e(t)}catch{}}var Re=new WeakMap;function Z(r){let e=Re.get(r);if(e)return e;let t=r,n=null,s={get config(){let p=t.config;return{debug:p.debug,childSafeMode:p.childSafeMode,apiKey:p.apiKey,endpoint:p.endpoint,sessionTimeoutMs:p.sessionTimeoutMs,libraryName:we}},sdkVersion:Se,hooks:null,consentState:()=>t.consent.canUpload()?"granted":t.consent.current==="denied"?"denied":"pending",liveSessionId:()=>{let p=t.stopped?null:t.session.load();return p&&t.session.clock.now()-p.lastActivityAt<=t.session.timeoutMs?p.id:null},startSession:()=>t.stopped||!t.consent.canCapture()?null:t.touchSession().sessionId,userId:()=>t.identity.userId,anonymousId:()=>t.identity.anonymousId,currentScreen:()=>n,apiKeyFingerprint:p=>be(p)};Re.set(r,s);let i=t.consent,o=()=>i.current==="granted",{optIn:a,optOut:d,reload:c}=i;i.optIn=function(){a.call(i),R(s,p=>p.onConsentChanged(o()))},i.optOut=function(){d.call(i),R(s,p=>p.onConsentChanged(!1))},i.reload=function(){let p=c.call(i);return p&&R(s,f=>f.onConsentChanged(o())),p};let l=t.session,{rotate:u,adopt:h,touch:g}=l;l.rotate=function(){let p=u.call(l);return R(s,f=>f.onSessionRotated(p,"reset")),p},l.adopt=function(p,f){let w=h.call(l,p,f);return w&&R(s,k=>k.onSessionRotated(p,"set_session_id")),w},l.touch=function(){let p=g.call(l),f=p.startedSession;return f&&R(s,w=>w.onSessionRotated(f.id,"timeout")),p};let m=t.queue,y=m.enqueue;m.enqueue=function(p){if(y.call(m,p),p?.event_type==="page_view"){let f=p.properties?.$page_name;typeof f=="string"&&f&&(n=f,R(s,w=>w.onScreen(f)))}R(s,f=>f.onEventAccepted(p.event_id,p.session_id,p.event))};let v=t.shutdown;return t.shutdown=function(){v.call(r),ee(s,!1)},s}function ee(r,e){r?.hooks&&(R(r,t=>t.onShutdown(e)),r.hooks=null)}var te="data-depsmith-sdk-mask",ne="data-depsmith-sdk-allow",xe="data-depsmith-sdk-exclude",Ae="data-depsmith-sdk-no-capture",nt=`[${xe}],[${Ae}]`;function ie(r){if(r.tagName!=="INPUT")return!1;let e=r;if((e.getAttribute("type")??"").toLowerCase()==="password")return!0;let n=(e.getAttribute("autocomplete")??"").toLowerCase();if(n.includes("one-time-code")||n.includes("current-password")||n.includes("new-password"))return!0;let s=e.style?.webkitTextSecurity;return!!s&&s!=="none"}function it(r){if(!r)return!1;let e=r.tagName;if(e==="TEXTAREA"||e==="SELECT")return!0;if(e==="INPUT"){let t=(r.type||"text").toLowerCase();return!["button","submit","reset","checkbox","radio","image","range","color","file"].includes(t)}return r.isContentEditable===!0}function Ce(r){if(!r)return!1;if(it(r))return!0;try{return r.closest(nt)!==null}catch{return!0}}function Me(r){let e=r.activeElement;for(let t=0;t<8&&e?.shadowRoot?.activeElement;t++)e=e.shadowRoot.activeElement;return!!e&&ie(e)}var st="#e5e7eb",rt="#cbd5e1",ot=new Set(["SCRIPT","STYLE","LINK","META","HEAD","TITLE","NOSCRIPT","TEMPLATE","BASE","SOURCE","TRACK","PARAM","AREA","MAP"]),Ie=new Set(["IFRAME","EMBED","OBJECT","FRAME"]),H=class{constructor(e,t,n=256){this.onLoad=e;this.origin=t;this.max=n;this.entries=new Map}url(e){if(!e||e.startsWith("javascript:"))return null;let t=this.entries.get(e);return t==="loading"||t==="failed"?null:t||(this.load(e,e),null)}svg(e){let t=`svg:${e.length}:${at(e)}`,n=this.entries.get(t);if(n==="loading"||n==="failed")return null;if(n)return n;let s=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`;return this.load(t,s),null}load(e,t){if(typeof Image>"u")return;if(this.entries.size>=this.max){let i=this.entries.keys().next().value;i!==void 0&&this.entries.delete(i)}this.entries.set(e,"loading");let n=new Image,s=!1;try{let i=new URL(t,this.origin);s=i.protocol.startsWith("http")&&i.origin!==this.origin}catch{}s&&(n.crossOrigin="anonymous"),n.decoding="async",n.onload=()=>{this.entries.set(e,n),this.onLoad()},n.onerror=()=>this.entries.set(e,"failed"),n.src=t}};function at(r){let e=2166136261;for(let t=0;t<r.length;t++)e=Math.imul(e^r.charCodeAt(t),16777619);return(e>>>0).toString(36)}var Ee=(r,e)=>{let t="left"in r?r.left:r.x,n="top"in r?r.top:r.y,s="width"in r?r.width:r.w,i="height"in r?r.height:r.h;return t<e.x+e.w&&t+s>e.x&&n<e.y+e.h&&n+i>e.y&&s>0&&i>0},b=r=>{let e=parseFloat(r);return Number.isFinite(e)?e:0};function A(r){return!r||r==="transparent"||r==="rgba(0, 0, 0, 0)"||/^rgba\(.+,\s*0\)$/.test(r)?null:r}function Te(r,e,t,n,s){let i={ctx:e,vw:t,vh:n,opts:s,now:s.now??(()=>performance.now()),visited:0,aborted:!1,canvases:[],origin:r.location?.origin??""};try{e.setTransform(1,0,0,1,0,0),e.globalAlpha=1,e.fillStyle=dt(r),e.fillRect(0,0,e.canvas.width,e.canvas.height),e.setTransform(s.scale,0,0,s.scale,0,0);let o=r.documentElement,a={x:0,y:0,w:t,h:n};o&&re(i,o,a,1,!1),r.body&&re(i,r.body,a,1,!1,!0)}catch{}finally{e.setTransform(1,0,0,1,0,0),e.globalAlpha=1}return i.aborted?{ok:!1,reason:"budget"}:{ok:!0,canvases:i.canvases}}function dt(r){let e=r.defaultView;if(!e)return"#ffffff";for(let t of[r.documentElement,r.body]){if(!t)continue;let n=A(e.getComputedStyle(t).backgroundColor);if(n)return n}return"#ffffff"}function lt(r){if(r.shadowRoot)return Array.from(r.shadowRoot.childNodes);if(r.tagName==="SLOT"){let e=r.assignedNodes?.({flatten:!0})??[];if(e.length)return e}return Array.from(r.childNodes)}function re(r,e,t,n,s,i=!1){let o=e.ownerDocument.defaultView,a=[],d=[],c=0;for(let l of lt(e)){if(r.aborted)return;if(l.nodeType===3){St(r,l,e,t,n,s);continue}if(l.nodeType!==1)continue;let u=l;if(ot.has(u.tagName)||!i&&e===e.ownerDocument.documentElement&&u.tagName==="BODY")continue;if(o.getComputedStyle(u).position!=="static"){let g=parseInt(o.getComputedStyle(u).zIndex,10),m={el:u,z:Number.isFinite(g)?g:0,order:c++};m.z<0?a.push(m):d.push(m);continue}se(r,u,t,n,s)}for(let l of a.sort((u,h)=>u.z-h.z||u.order-h.order))se(r,l.el,t,n,s);for(let l of d.sort((u,h)=>u.z-h.z||u.order-h.order))se(r,l.el,t,n,s)}function ut(r){return++r.visited%64===0&&r.now()>r.opts.deadline&&(r.aborted=!0),r.aborted}function se(r,e,t,n,s){if(ut(r))return;let i=e.ownerDocument.defaultView,o=e.getBoundingClientRect(),a=i.getComputedStyle(e);if(a.display==="none")return;let d=n*(parseFloat(a.opacity)||(a.opacity==="0"?0:1));if(d<=.01)return;let l=a.position==="fixed"?{x:0,y:0,w:r.vw,h:r.vh}:t,u=a.visibility!=="hidden"&&a.visibility!=="collapse",h=Ee(o,l),g=r.ctx;if(e.hasAttribute(te)){h&&oe(g,l,()=>De(g,o,d,Oe(a)));return}let m=s||e.hasAttribute(ne);u&&h&&oe(g,l,()=>{g.globalAlpha=d,pt(r,e,o,a),gt(r,e,o,a,m)});let y=e.tagName;if(Ie.has(y)||y==="VIDEO"||y==="CANVAS"||y==="IMG"||y==="svg"||y==="SVG"||y==="INPUT"||y==="TEXTAREA"||y==="SELECT"||e.namespaceURI==="http://www.w3.org/2000/svg")return;let v=l;if(a.overflowX!=="visible"||a.overflowY!=="visible"||a.contain.includes("paint")){let p={x:o.left+b(a.borderLeftWidth),y:o.top+b(a.borderTopWidth),w:o.width-b(a.borderLeftWidth)-b(a.borderRightWidth),h:o.height-b(a.borderTopWidth)-b(a.borderBottomWidth)};if(v=ct(l,p),v.w<=0||v.h<=0)return}!h&&e.childElementCount===0&&!e.shadowRoot||re(r,e,v,d,m)}function ct(r,e){let t=Math.max(r.x,e.x),n=Math.max(r.y,e.y);return{x:t,y:n,w:Math.min(r.x+r.w,e.x+e.w)-t,h:Math.min(r.y+r.h,e.y+e.h)-n}}function oe(r,e,t){r.save(),r.beginPath(),r.rect(e.x,e.y,e.w,e.h),r.clip();try{t()}finally{r.restore()}}function K(r,e,t){r.beginPath();let n=Math.max(0,Math.min(t,e.w/2,e.h/2));n>0&&typeof r.roundRect=="function"?r.roundRect(e.x,e.y,e.w,e.h,n):r.rect(e.x,e.y,e.w,e.h)}function Pe(r){return{x:r.left,y:r.top,w:r.width,h:r.height}}function De(r,e,t,n){r.globalAlpha=t,r.fillStyle=n;let s="left"in e?Pe(e):e;r.fillRect(s.x,s.y,s.w,s.h)}var ae="#d1d5db",ht="#e5e7eb";function Oe(r){return ae}function pt(r,e,t,n){let s=r.ctx,i=Pe(t),o=b(n.borderTopLeftRadius),a=A(n.backgroundColor);a&&(s.fillStyle=a,K(s,i,o),s.fill());let d=n.backgroundImage;if(d&&d!=="none"){let u=/url\(["']?([^"')]+)["']?\)/.exec(d)?.[1];if(u){let h=r.opts.images.url(new URL(u,e.ownerDocument.baseURI).href);h&&ft(s,h,i,n,o)}else{let h=/(rgba?\([^)]+\)|#[0-9a-f]{3,8})/i.exec(d)?.[1];h&&(s.fillStyle=h,K(s,i,o),s.fill())}}let c=[[n.borderTopWidth,n.borderTopStyle,n.borderTopColor,[i.x,i.y,i.w,0]],[n.borderBottomWidth,n.borderBottomStyle,n.borderBottomColor,[i.x,i.y+i.h,i.w,0]],[n.borderLeftWidth,n.borderLeftStyle,n.borderLeftColor,[i.x,i.y,0,i.h]],[n.borderRightWidth,n.borderRightStyle,n.borderRightColor,[i.x+i.w,i.y,0,i.h]]];if(c.every(u=>u[0]===c[0][0]&&u[1]===c[0][1]&&u[2]===c[0][2])&&o>0){let u=b(c[0][0]),h=A(c[0][2]);u>0&&h&&c[0][1]!=="none"&&c[0][1]!=="hidden"&&(s.strokeStyle=h,s.lineWidth=u,K(s,{x:i.x+u/2,y:i.y+u/2,w:i.w-u,h:i.h-u},o-u/2),s.stroke());return}for(let[u,h,g,[m,y,v,p]]of c){let f=b(u),w=A(g);f<=0||!w||h==="none"||h==="hidden"||(s.fillStyle=w,v===0?s.fillRect(m===i.x?m:m-f,y,f,p):s.fillRect(m,y===i.y?y:y-f,v,f))}}function ft(r,e,t,n,s){let i=e.naturalWidth||e.width||0,o=e.naturalHeight||e.height||0;if(!i||!o)return;r.save(),K(r,t,s),r.clip();let a=n.backgroundSize;if(a==="cover"||a==="contain"){let d=a==="cover"?Math.max(t.w/i,t.h/o):Math.min(t.w/i,t.h/o),c=i*d,l=o*d;r.drawImage(e,t.x+(t.w-c)/2,t.y+(t.h-l)/2,c,l)}else if(n.backgroundRepeat.startsWith("no-repeat")||a.includes("100%"))r.drawImage(e,t.x,t.y,a.includes("100%")?t.w:i,a.includes("100%")?t.h:o);else{let d=r.createPattern(e,"repeat");d&&(r.fillStyle=d,r.translate(t.x,t.y),r.fillRect(0,0,t.w,t.h))}r.restore()}function gt(r,e,t,n,s){let i=r.ctx,o=e.tagName,a=mt(t,n);if(o==="IMG"||o==="INPUT"&&e.type==="image"){let d=e,c=yt(r,d);c?vt(i,c,a,n.objectFit,d.naturalWidth,d.naturalHeight):(d.complete===!1||d.naturalWidth>0)&&U(i,a);return}if(o==="CANVAS"){let d=e;if(r.opts.tainted.has(d)||d.width===0||d.height===0)U(i,a);else try{i.drawImage(d,a.x,a.y,a.w,a.h),r.canvases.push(d)}catch{U(i,a)}return}if(o==="VIDEO"){i.fillStyle="#111827",i.fillRect(a.x,a.y,a.w,a.h);return}if(Ie.has(o)){U(i,a);return}if(e.namespaceURI==="http://www.w3.org/2000/svg"&&e.tagName.toLowerCase()==="svg"){bt(r,e,t);return}(o==="INPUT"||o==="TEXTAREA"||o==="SELECT")&&wt(r,e,a,n,s)}function mt(r,e){let t=b(e.borderLeftWidth)+b(e.paddingLeft),n=b(e.borderTopWidth)+b(e.paddingTop),s=b(e.borderRightWidth)+b(e.paddingRight),i=b(e.borderBottomWidth)+b(e.paddingBottom);return{x:r.left+t,y:r.top+n,w:Math.max(0,r.width-t-s),h:Math.max(0,r.height-n-i)}}function U(r,e){e.w<=0||e.h<=0||(r.fillStyle=st,r.fillRect(e.x,e.y,e.w,e.h),r.strokeStyle=rt,r.lineWidth=1,r.strokeRect(e.x+.5,e.y+.5,Math.max(0,e.w-1),Math.max(0,e.h-1)))}function yt(r,e){if(!e.complete||e.naturalWidth===0)return null;let t=e.currentSrc||e.src;if(!t)return null;let n=!1;try{let s=new URL(t,e.ownerDocument.baseURI);n=s.protocol==="data:"||s.protocol==="blob:"||s.origin===r.origin}catch{return null}return n||e.crossOrigin==="anonymous"||e.crossOrigin==="use-credentials"?e:r.opts.images.url(t)}function vt(r,e,t,n,s,i){if(t.w<=0||t.h<=0)return;let o=s||e.naturalWidth||t.w,a=i||e.naturalHeight||t.h;if(n==="cover"||n==="contain"||n==="scale-down"){let d=n==="cover"?Math.max(t.w/o,t.h/a):Math.min(t.w/o,t.h/a);n==="scale-down"&&(d=Math.min(1,d));let c=o*d,l=a*d;r.save(),r.beginPath(),r.rect(t.x,t.y,t.w,t.h),r.clip(),r.drawImage(e,t.x+(t.w-c)/2,t.y+(t.h-l)/2,c,l),r.restore();return}r.drawImage(e,t.x,t.y,t.w,t.h)}function bt(r,e,t){let n=r.ctx,s=Array.from(e.querySelectorAll("text, foreignObject")),i=null;try{let a=e.cloneNode(!0);for(let c of Array.from(a.querySelectorAll('text, foreignObject, script, image, use[href^="http"]')))c.remove();a.setAttribute("width",String(t.width)),a.setAttribute("height",String(t.height)),a.getAttribute("xmlns")||a.setAttribute("xmlns","http://www.w3.org/2000/svg");let d=e.ownerDocument.defaultView.getComputedStyle(e).color;a.setAttribute("color",d),i=new XMLSerializer().serializeToString(a)}catch{i=null}let o=i&&i.length<2e5?r.opts.images.svg(i):null;o&&n.drawImage(o,t.left,t.top,t.width,t.height);for(let a of s){let d=a.getBoundingClientRect();d.width>0&&d.height>0&&De(n,d,n.globalAlpha,Oe(a.ownerDocument.defaultView.getComputedStyle(a)))}}function wt(r,e,t,n,s){let i=r.ctx,o=e.tagName,a=o==="INPUT"?(e.type||"text").toLowerCase():o.toLowerCase();if(a==="checkbox"||a==="radio"){let h=Math.min(t.w,t.h);if(h<=0)return;i.strokeStyle="#6b7280",i.lineWidth=1.5,i.beginPath(),a==="radio"?i.arc(t.x+t.w/2,t.y+t.h/2,h/2-1,0,Math.PI*2):i.rect(t.x+1,t.y+1,h-2,h-2),i.stroke(),e.checked&&(i.fillStyle=A(n.accentColor)??"#2563eb",i.beginPath(),a==="radio"?i.arc(t.x+t.w/2,t.y+t.h/2,h/4,0,Math.PI*2):i.rect(t.x+3,t.y+3,h-6,h-6),i.fill());return}if(["range","color","file","hidden"].includes(a))return;let d=ie(e),c=b(n.fontSize)||14,l=Math.min(t.h,c*1.25);if(s&&!d){let h=o==="SELECT"?e.selectedOptions?.[0]?.text??"":e.value||e.placeholder||"";if(!h)return;i.save(),i.beginPath(),i.rect(t.x,t.y,t.w,t.h),i.clip(),i.fillStyle=(e.value||o==="SELECT"?A(n.color):null)??"#9ca3af",i.font=n.font||`${c}px sans-serif`,i.textBaseline="middle",i.fillText(h,t.x,o==="TEXTAREA"?t.y+l/2:t.y+t.h/2),i.restore();return}(o==="SELECT"||d||e.value!==""||e.placeholder)&&(i.fillStyle=o==="SELECT"||d||e.value!==""?ae:ht,i.fillRect(t.x,o==="TEXTAREA"?t.y:t.y+(t.h-l)/2,t.w,o==="TEXTAREA"?t.h:l))}function St(r,e,t,n,s,i){let o=e.data;if(!o||!/\S/.test(o))return;let d=t.ownerDocument.defaultView.getComputedStyle(t);if(d.visibility==="hidden"||d.display==="none")return;let c=t.ownerDocument.createRange();c.selectNodeContents(e);let l=Array.from(c.getClientRects()).filter(h=>h.width>0&&h.height>0&&Ee(h,n));if(l.length===0)return;let u=r.ctx;oe(u,n,()=>{if(i&&!kt(t)){u.globalAlpha=s,u.fillStyle=A(d.color)??"#111827",u.font=d.font,u.textBaseline="alphabetic",Rt(u,e,c);return}u.globalAlpha=s,u.fillStyle=ae;for(let h of l){let g=Math.max(0,(h.height-(b(d.fontSize)||h.height))/2);u.fillRect(h.left,h.top+g,h.width,h.height-g*2)}})}function kt(r){return r.closest('input[type="password"]')!==null}function Rt(r,e,t){let n=e.data,s=/\S+/g,i,o=0;for(;(i=s.exec(n))&&o++<2e3;){t.setStart(e,i.index),t.setEnd(e,i.index+i[0].length);let a=t.getClientRects()[0];!a||a.width===0||r.fillText(i[0],a.left,a.bottom-a.height*.22,a.width+1)}}var W=class{constructor(e,t,n){this.maxFps=e;this.burstFps=t;this.keyframeIntervalMs=n;this.dirty=!0;this.lastAcquiredAt=-Number.MAX_SAFE_INTEGER/2;this.burstUntil=-Number.MAX_SAFE_INTEGER/2}update(e,t,n){this.maxFps=e,this.burstFps=t,this.keyframeIntervalMs=n}get isDirty(){return this.dirty}onDirty(){this.dirty=!0}onBurst(e){this.dirty=!0,this.burstUntil=e+_t}delayUntilDue(e){let t=e<this.burstUntil?Math.max(this.burstFps,this.maxFps):this.maxFps,n=t>0?Math.floor(1e3/t):Number.MAX_SAFE_INTEGER/4,s=e-this.lastAcquiredAt,i=this.dirty?n-s:this.keyframeIntervalMs-s;return Math.max(0,i)}onAcquired(e){this.lastAcquiredAt=e,this.dirty=!1}onDiscarded(){this.dirty=!0}},_t=3e3;var q=class{constructor(e){this.tileSize=e;this.width=-1;this.height=-1;this.hashes=new Uint32Array(0)}reset(){this.width=-1,this.height=-1,this.hashes=new Uint32Array(0)}diff(e,t,n){if(e.length<t*n)throw new Error("pixels too short");let s=this.tileSize,i=Math.ceil(t/s),o=Math.ceil(n/s),a=new Uint32Array(i*o),d=[],c=t===this.width&&n===this.height&&this.hashes.length===a.length;for(let l=0;l<o;l++)for(let u=0;u<i;u++){let h=u*s,g=l*s,m=Math.min(s,t-h),y=Math.min(s,n-g),v=xt(e,t,h,g,m,y),p=l*i+u;a[p]=v,c&&this.hashes[p]!==v&&d.push([h,g,m,y])}return this.hashes=a,this.width=t,this.height=n,c?d:null}tileCount(e,t){return Math.ceil(e/this.tileSize)*Math.ceil(t/this.tileSize)}};function xt(r,e,t,n,s,i){let o=2166136261;for(let a=n;a<n+i;a++){let d=a*e+t,c=d+s;for(;d<c;)o=Math.imul(o^r[d],16777619),d++}return o>>>0}var qe=4096,At=100,z=class{constructor(e,t=window){this.engine=e;this.win=t;this.policy=null;this.scheduler=new W(2,4,3e4);this.diff=new q(64);this.canvas=null;this.ctx=null;this.timer=null;this.timerDue=0;this.raf=null;this.busy=!1;this.codec=null;this.tainted=new WeakSet;this.observer=null;this.detachers=[];this.pointerDetachers=[];this.redactedPointers=new Map;this.lastMove=new Map;this.generation=0;this.images=new H(()=>this.dirty(),t.location.origin),e.onCaptureChanged=n=>this.setPolicy(n),e.onFrameDropped=()=>this.dirty(),this.attachPointers()}now(){return this.win.performance.now()}setPolicy(e){let t=this.policy;if(this.policy=e,!e){this.detach();return}this.scheduler.update(e.maxFps,e.burstFps,e.keyframeIntervalSeconds*1e3),(!t||t.tileSize!==e.tileSize||t.captureScale!==e.captureScale)&&(this.diff=new q(e.tileSize)),t||this.attach(),this.scheduler.onDirty(),this.schedule()}dispose(){this.detach();for(let e of this.pointerDetachers.splice(0))e();this.engine.onCaptureChanged=null,this.engine.onFrameDropped=null}attach(){let e=this.win.document,t=this.win.MutationObserver;t&&(this.observer=new t(()=>this.dirty()),this.observer.observe(e,{subtree:!0,childList:!0,attributes:!0,characterData:!0}));let n=(s,i,o)=>{s.addEventListener(i,o,{capture:!0,passive:!0}),this.detachers.push(()=>s.removeEventListener(i,o,{capture:!0}))};for(let s of["scroll","input","change","load","transitionend","animationend","focusin","focusout"])n(e,s,()=>this.dirty());n(this.win,"resize",()=>this.dirty()),this.canvas=e.createElement("canvas"),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0,alpha:!1})}detach(){this.generation++,this.observer?.disconnect(),this.observer=null;for(let e of this.detachers.splice(0))e();this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.raf!==null&&this.win.cancelAnimationFrame?.(this.raf),this.raf=null,this.canvas=null,this.ctx=null,this.diff.reset()}dirty(){this.policy&&(this.scheduler.onDirty(),this.schedule())}burst(){this.policy&&(this.scheduler.onBurst(this.now()),this.schedule())}schedule(){if(!this.policy||this.raf!==null||this.busy)return;let e=this.now(),t=this.scheduler.delayUntilDue(e);if(this.timer!==null){if(e+t>=this.timerDue)return;clearTimeout(this.timer)}this.timerDue=e+t,this.timer=setTimeout(()=>{this.timer=null;let n=()=>{this.raf=null,this.acquire()};typeof this.win.requestAnimationFrame=="function"&&this.win.document.visibilityState!=="hidden"?this.raf=this.win.requestAnimationFrame(n):n()},Math.min(t,2147e6))}viewport(){let e=this.win.visualViewport,t=Math.max(1,Math.round(this.win.innerWidth||e?.width||1)),n=Math.max(1,Math.round(this.win.innerHeight||e?.height||1));return{w:t,h:n}}async acquire(){let e=this.policy,t=this.ctx;if(!e||!t||!this.canvas||this.busy)return;this.busy=!0;let n=this.generation,s=this.now();this.scheduler.onAcquired(s);try{let{w:i,h:o}=this.viewport(),a=Math.min(e.captureScale,qe/i,qe/o),d=Math.max(1,Math.round(i*a)),c=Math.max(1,Math.round(o*a));(this.canvas.width!==d||this.canvas.height!==c)&&(this.canvas.width=d,this.canvas.height=c,this.diff.reset());let l=Te(this.win.document,t,i,o,{scale:a,deadline:s+e.uiBudgetMs,images:this.images,tainted:this.tainted});if(!l.ok){this.discard();return}let u;try{u=new Uint32Array(t.getImageData(0,0,d,c).data.buffer)}catch{for(let p of l.canvases)this.tainted.add(p);this.discard();return}if(this.now()-s>e.uiBudgetMs){this.discard();return}let h=this.diff.diff(u,d,c),g=e.imageQuality/100,m=this.engine.wantsKeyframe||h===null;if(!m&&h.length===0)return;if(m||h.length>this.diff.tileCount(d,c)/2){let p=await this.encode(this.canvas,g,d,c);if(n!==this.generation)return;if(!p){this.diff.reset(),this.discard();return}this.engine.submitFrame({keyframe:p});return}let v=[];for(let[p,f,w,k]of h){let N=this.win.document.createElement("canvas");N.width=w,N.height=k;let ye=N.getContext("2d",{alpha:!1});if(!ye){this.diff.reset(),this.discard();return}ye.drawImage(this.canvas,p,f,w,k,0,0,w,k);let ve=await this.encode(N,g,w,k);if(!ve){this.diff.reset(),this.discard();return}v.push([[p,f,w,k],ve])}if(n!==this.generation)return;this.engine.submitFrame({tiles:v})}catch{this.diff.reset(),this.discard()}finally{this.busy=!1,n===this.generation&&this.win.document.getAnimations?.().some(i=>i.playState==="running")&&this.scheduler.onDirty(),n===this.generation&&this.schedule()}}discard(){this.scheduler.onDiscarded(),this.engine.frameDiscarded()}async encode(e,t,n,s){if(this.codec===null)try{this.codec=e.toDataURL("image/webp",.1).startsWith("data:image/webp")?"webp":"jpeg"}catch{return null}let i=this.codec,o=await new Promise(d=>{try{e.toBlob(d,i==="webp"?"image/webp":"image/jpeg",t)}catch{d(null)}});if(!o)return null;let a=new Uint8Array(await o.arrayBuffer());return Ct(i,a)?{codec:i,w:n,h:s,bytes:a}:null}attachPointers(){let e=this.win,t=s=>i=>this.pointer(s,i),n=[["pointerdown",t("down")],["pointerup",t("up")],["pointermove",t("move")],["pointercancel",t("cancel")]];for(let[s,i]of n)e.addEventListener(s,i,{capture:!0,passive:!0}),this.pointerDetachers.push(()=>e.removeEventListener(s,i,{capture:!0}))}pointer(e,t){if(!this.engine.touchesWanted)return;let n=t.pointerId??1;if(e==="move"&&!this.redactedPointers.has(n))return;if(e==="move"){let c=this.now();if(c-(this.lastMove.get(n)??-1/0)<At)return;this.lastMove.set(n,c)}e==="down"&&this.burst();let s=t.composedPath?.()[0]instanceof Element?t.composedPath()[0]:t.target,i=Ce(s)||Me(this.win.document),o;e==="down"?(o=i,this.redactedPointers.set(n,i)):o=i||(this.redactedPointers.get(n)??!1),(e==="up"||e==="cancel")&&(this.redactedPointers.delete(n),this.lastMove.delete(n));let{w:a,h:d}=this.viewport();this.engine.submitTouch(e,t.clientX/a,t.clientY/d,Math.max(1,this.redactedPointers.size||1),o?"exclude":"plain")}};function Ct(r,e){return r==="jpeg"?e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255:e.length>=12&&String.fromCharCode(e[0],e[1],e[2],e[3])==="RIFF"&&String.fromCharCode(e[8],e[9],e[10],e[11])==="WEBP"}var C="safe-default-v1";var de={policy_version:1,profile:C,max_stale_seconds:60,max_recording_seconds:1800,max_recording_bytes:20971520,max_chunk_bytes:1048576,chunk_max_seconds:10,max_fps:2,burst_fps:4,keyframe_interval_seconds:30,tile_size:64,ui_budget_ms:40,image_quality:60,capture_scale:.5,excluded_screens:[]},Mt=r=>typeof r=="number"&&Number.isInteger(r),It=r=>typeof r=="number"&&Number.isFinite(r);function M(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r;if(e.profile!==C)return null;let t=["policy_version","max_stale_seconds","max_recording_seconds","max_recording_bytes","max_chunk_bytes","chunk_max_seconds","keyframe_interval_seconds","tile_size","ui_budget_ms","image_quality"];for(let i of t)if(!Mt(e[i]))return null;for(let i of["max_fps","burst_fps","capture_scale"])if(!It(e[i]))return null;let n=e.excluded_screens;if(!Array.isArray(n)||n.some(i=>typeof i!="string"))return null;let s={version:e.policy_version,maxStaleSeconds:e.max_stale_seconds,maxRecordingSeconds:e.max_recording_seconds,maxRecordingBytes:e.max_recording_bytes,maxChunkBytes:Math.min(e.max_chunk_bytes,1048576),chunkMaxSeconds:e.chunk_max_seconds,maxFps:e.max_fps,burstFps:e.burst_fps,keyframeIntervalSeconds:e.keyframe_interval_seconds,tileSize:e.tile_size,uiBudgetMs:e.ui_budget_ms,imageQuality:e.image_quality,captureScale:e.capture_scale,excludedScreens:new Set(n)};return s.version<1||s.maxFps<=0||s.maxStaleSeconds<=0||s.chunkMaxSeconds<=0||s.tileSize<8||s.captureScale<=0||s.captureScale>1?null:s}var _=r=>r.type==="keyframe"||r.type==="patch",j=r=>(r.images??[]).reduce((e,t)=>e+t.bytes.length,0)+200,Et=[68,83,82,67],Tt=1,Pt=32,Le=new TextEncoder;function L(r,e,t,n,s,i){if(s.length===0)throw new Error("a chunk has at least one record");let o=[],a=[],d=[],c=[],l=n;for(let p of s){let f={seq:l,t:p.t,type:p.type};p.type==="keyframe"?(Object.assign(f,p.fields),o.push(p.images[0]),f.image=o.length,d.push(p.fields.frame_id)):p.type==="patch"?(f.base_frame_id=p.fields.base_frame_id,c.push(p.fields.base_frame_id),f.tiles=p.fields.tiles.map((w,k)=>(o.push(p.images[k]),{...w,image:o.length}))):Object.assign(f,p.fields),a.push(JSON.stringify(f)),l++}let u=Le.encode(a.join(`
2
+ `)),g=s.find(p=>p.type==="patch")?.fields.base_frame_id,m=g&&!d.includes(g)?g:null,y=Fe({recording_id:r,stream_id:e,chunk_seq:t,first_seq:n,last_seq:l-1,first_t:s[0].t,last_t:s[s.length-1].t,keyframe_ids:d,base_frame_id:m,profile:C,policy_version:i},u.length,u.length,o),v=o.reduce((p,f)=>p+f.bytes.length,0);return{recordingId:r,streamId:e,chunkSeq:t,firstSeq:n,lastSeq:l-1,ndjson:u,header:y,images:o,bound:10+y.length+Pt+u.length+v,keyframes:d,bases:c}}function Fe(r,e,t,n){let s=[{kind:"records",codec:"deflate-ndjson",offset:0,length:e,uncompressed_length:t}],i=e;for(let o of n)s.push({kind:"image",codec:o.codec,offset:i,length:o.bytes.length,w:o.w,h:o.h}),i+=o.bytes.length;return Le.encode(JSON.stringify({...r,sections:s}))}async function Dt(r){let e=new Blob([r]).stream().pipeThrough(new CompressionStream("deflate-raw"));return new Uint8Array(await new Response(e).arrayBuffer())}async function Ot(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",r)),t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function Be(r){let e=await Dt(r.ndjson),t=JSON.parse(new TextDecoder().decode(r.header));delete t.sections;let n=Fe(t,e.length,r.ndjson.length,r.images),s=10+n.length+e.length+r.images.reduce((d,c)=>d+c.bytes.length,0),i=new Uint8Array(s);i.set(Et,0);let o=new DataView(i.buffer);o.setUint16(4,Tt),o.setUint32(6,n.length),i.set(n,10);let a=10+n.length;i.set(e,a),a+=e.length;for(let d of r.images)i.set(d.bytes,a),a+=d.bytes.length;return{bytes:i,sha256:await Ot(i)}}function Ne(){try{return typeof CompressionStream>"u"||typeof Blob>"u"?!1:(new CompressionStream("deflate-raw"),typeof crypto<"u"&&typeof crypto.subtle?.digest=="function")}catch{return!1}}var he=class{constructor(){this.values=new Map}get(e){let t=this.values.get(e);return t===void 0?null:JSON.parse(t)}set(e,t){this.values.set(e,JSON.stringify(t))}},T="web-main",Ue="Web",G=5e5,Ke=1e4,qt=1e4,He=3e6,We=10*1024*1024,le=4*1024*1024,Lt=24*3600*1e3,F=-Number.MAX_SAFE_INTEGER/2,ze=6e4,Ft=5*6e4,pe=200,ue=1024*1024,S=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:null,x=r=>typeof r=="string"?r:null,P=r=>typeof r=="number"&&Number.isInteger(r)?r:null,V=(r,e,t)=>Math.min(t,Math.max(e,r));function je(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let r=new Uint8Array(16);crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}var $=class{constructor(e,t){this.host=e;this.status={state:"off"};this.capturePolicy=null;this.wantsKeyframe=!0;this.onCaptureChanged=null;this.onFrameDropped=null;this.touchesWanted=!1;this.armed=!1;this.autoArmed=!1;this.hostStopped=!1;this.remoteChecking=!1;this.cfg=null;this.waiting=!1;this.triggered=!1;this.provisionals=new Set;this.options={allowedScreens:null,excludedScreens:new Set};this.admitting=!1;this.admissionAttempt=0;this.rotateAfterAdmission=!1;this.selfStarted=null;this.startingSession=!1;this.startWaiters=[];this.active=null;this.uploads=new Map;this.revokes=[];this.grants=new Map;this.checksumRetried=new Set;this.foreground=!0;this.backgroundSince=null;this.currentScreen=null;this.lastSuccessAt=0;this.backoffUntil=0;this.backoffMs=0;this.quotaUntil=0;this.lastRefreshAt=F;this.shutDown=!1;this.burstUntilMono=F;this.inflight=new Set;this.ticker=null;this.pumping=!1;this.pumpAgain=!1;this.writing=new Map;this.deps={startTimeoutMs:qt,state:new he,...t}}log(e,t,n){try{this.deps.log?this.deps.log(e,t,n):(this.host.config.debug||e==="error")&&(e==="debug"?console.debug:e==="warn"?console.warn:console.error)(`[depsmith-sdk] ${t}`,n??"")}catch{}}bind(){this.host.hooks=this,this.post(async()=>{let e=this.host.currentScreen();e&&(this.currentScreen=e),this.deps.autoStart&&this.mayAuto()&&(this.cfg=this.cachedConfig(),this.eventRule()&&await this.applyConfig()),await this.recover(),await this.autoCheck()})}async idle(){for(let e=0;e<1e4&&this.inflight.size>0;e++)await Promise.allSettled([...this.inflight])}post(e){if(this.shutDown)return;let t=(async()=>{try{await e(),this.publishCapture()}catch(n){this.log("error","replay error",n)}})();this.track(t)}track(e){return this.inflight.add(e),e.finally(()=>this.inflight.delete(e)).catch(()=>{}),e}storeOp(e){return this.track(e())}mayAuto(){return!this.shutDown&&!this.hostStopped&&this.host.consentState()==="granted"&&!this.host.config.childSafeMode}async autoCheck(){if(!(!this.deps.autoStart||!this.mayAuto()||this.remoteChecking)&&!(this.armed&&!this.autoArmed&&!this.triggered||this.admitting||this.active&&!this.triggered)){this.remoteChecking=!0;try{await this.fetchConfig()}finally{this.remoteChecking=!1}this.mayAuto()&&await this.applyConfig()}}async refreshConfig(){if(!this.deps.autoStart||!this.mayAuto()||this.remoteChecking||this.deps.now()-(this.cfg?.at??F)<Ft)return;let e=!!this.cfg?.rule;this.remoteChecking=!0;try{await this.fetchConfig()}finally{this.remoteChecking=!1}(e||this.cfg?.rule)&&this.mayAuto()&&await this.applyConfig()}eventRule(){let e=this.cfg?.rule;return e&&e.enabled&&e.startEvent?e:null}async applyConfig(){let e=this.cfg?.rule??null;if(e&&!e.enabled){this.waiting=!1,this.closeWindow();let n=this.active;n?.prov&&this.dropProvisional(n,this.admitting?void 0:"remote_disabled"),!this.active&&!this.admitting&&(this.armed=!1,this.autoArmed=!1,this.setStatus("off","remote_disabled"));return}let t=this.eventRule();if(t){if(this.waiting=!0,this.active||this.admitting||this.armed&&!this.autoArmed)return;this.armed=!1,this.autoArmed=!1;let n=this.window(),s=this.host.liveSessionId();s&&n?.open&&n.session_id===s&&n.start_event===t.startEvent&&n.event_id?this.beginProvisional(s,{start_event:t.startEvent,event_id:n.event_id},!0):(n?.open&&this.closeWindow(),this.setStatus("off",this.deniedReason()??"awaiting_start_event"));return}this.waiting=!1,!(this.armed&&!this.autoArmed||this.admitting||this.active)&&(e||this.cfg?.on?(this.armed=!0,this.autoArmed=!0,this.options={allowedScreens:null,excludedScreens:new Set},await this.admit()):(this.armed=!1,this.autoArmed=!1,this.setStatus("off","remote_disabled")))}fingerprint(){return this.host.apiKeyFingerprint(this.host.config.apiKey)}stateGet(e){try{return S(this.deps.state.get(e))}catch{return null}}stateSet(e,t){try{this.deps.state.set(e,t)}catch{}}cachedConfig(){let e;try{e=this.deps.state.get("remote")}catch{return null}if(e===1||e===0)return{fp:"",at:0,on:e===1,rule:null};let t=S(e);return!t||t.fp!==this.fingerprint()||typeof t.on!="boolean"?null:{fp:t.fp,at:P(t.at)??0,on:t.on,rule:$e(t.rule)}}async fetchConfig(){let e=this.host.config,t=`${e.endpoint.replace(/\/+$/,"")}/config?api_key=${encodeURIComponent(e.apiKey)}`,n=await this.deps.transport.get(t);if(n.status!==200)return;let s=I(n),i=S(s?.autocapture)?.session_replay;if(typeof i!="boolean")return;let o=s.session_replay??null,a={fp:this.fingerprint(),at:this.deps.now(),on:i,rule:$e(o)};this.cfg=a,this.stateSet("remote",{...a,rule:o})}window(){let e=this.stateGet("window");return e&&typeof e.session_id=="string"?e:null}closeWindow(){let e=this.window();e?.open&&this.stateSet("window",{...e,open:!1})}deniedReason(){let e=this.window(),t=e?.denied,n=this.host.liveSessionId();return t&&n&&e.session_id===n&&t.user_id===this.host.userId()?t.reason:null}hasTimedWork(){return!!this.active||this.armed||this.admitting||this.revokes.length>0||this.uploads.size>0||this.provisionals.size>0}updateTicker(){if(!(this.deps.manualTicks||this.shutDown)){if(!this.hasTimedWork()){this.ticker!==null&&clearInterval(this.ticker),this.ticker=null;return}this.ticker===null&&(this.ticker=setInterval(()=>this.post(()=>this.tickNow()),1e3),this.ticker.unref?.())}}start(e,t){let n={allowedScreens:e.allowedScreens?new Set(e.allowedScreens):null,excludedScreens:new Set(e.excludedScreens??[])};if(this.shutDown){t({...this.status});return}this.post(async()=>{let s=this.status.state;if(this.host.consentState()!=="granted")this.armed=!1,t(this.setStatus("off","consent_not_granted"));else if(this.host.config.childSafeMode)this.armed=!1,t(this.setStatus("off","child_safe_mode"));else if(this.deps.autoStart&&this.cfg?.rule&&!this.cfg.rule.enabled)t(this.setStatus("off","remote_disabled"));else if(this.admitting)this.autoArmed&&this.adoptHostOptions(n),this.startWaiters.push(t);else if((s==="recording"||s==="paused")&&this.triggered)this.adoptHostOptions(n),t({...this.status});else if(this.eventRule()&&!this.active){this.hostStopped=!1,this.waiting=!0,this.options=n;let i=this.sessionForAdmission(),o=i?this.beginProvisional(i,null,!1):null;o?(o.prov.waiters.push(t),(this.deps.setTimer??((d,c)=>setTimeout(d,c)))(()=>this.post(()=>this.resolveWaiters(o)),this.deps.startTimeoutMs)):t(this.setStatus("off","admission_unavailable"))}else(s==="recording"||s==="paused")&&this.autoArmed?(this.adoptHostOptions(n),t(this.status)):s==="recording"||s==="paused"?(Bt(n,this.options)||this.log("debug","replay: start() options change applies from the next admission"),t(this.status)):(this.armed=!0,this.autoArmed=!1,this.hostStopped=!1,this.options=n,this.startWaiters.push(t),await this.admit())})}stop(e,t){if(this.shutDown){t();return}this.post(async()=>{if(this.hostStopped=!0,this.autoArmed=!1,this.triggered=!1,this.status.state==="off"&&!this.active&&!this.admitting){this.armed=!1,t();return}this.armed=!1;let n=this.active;if(!n)this.admitting&&(this.admitting=!1,this.admissionAttempt++,this.rotateAfterAdmission=!1),this.setStatus("off","stopped"),this.notifyStart();else if(e)this.purge(n.meta,"host_discard"),this.setStatus("off","stopped");else if(n.prov)this.finalize(n,"host_stop"),this.setStatus("off","stopped");else{this.finalize(n,"host_stop"),this.setStatus("finalizing","stopped",n.meta.recordingId),t(),await this.pump();return}t()})}frameDropped(e){e.needKeyframe=!0;try{this.onFrameDropped?.()}catch{}}submitFrame(e){this.post(()=>{let t=this.active;if(!t)return;if(!this.canCapture(t)){t.needKeyframe=!0;return}let n=this.deps.monoMicros(),s=n<this.burstUntilMono?Math.max(t.policy.burstFps,t.policy.maxFps):t.policy.maxFps,i=Math.floor(1e6/s);if(n-t.lastFrameMono<i){this.frameDropped(t);return}let o=n-t.lastKeyframeMono>=t.policy.keyframeIntervalSeconds*1e6,a=t.needKeyframe||o||t.lastKeyframeId===null||!e.tiles,d=e.keyframe;if(a&&!d){this.frameDropped(t),this.publishCapture();return}if(!a&&(!e.tiles||e.tiles.length===0))return;t.lastFrameMono=n,this.closeGap(t,"mask_uncertain");let c=a?d.bytes.length:e.tiles.reduce((l,[,u])=>l+u.bytes.length,0);if(t.buffer.length>0&&ce(t)+c>=t.policy.maxChunkBytes*8/10&&this.closeChunk(t,!1),a){let l=`f${t.frames++}`;t.buffer.push({type:"keyframe",t:this.t(t),fields:{frame_id:l,w:d.w,h:d.h,windows:e.windows??1},images:[d]}),t.lastKeyframeId=l,t.lastKeyframeMono=n,t.needKeyframe=!1}else{let l=e.tiles;t.buffer.push({type:"patch",t:this.t(t),fields:{base_frame_id:t.lastKeyframeId,tiles:l.map(([[u,h,g,m]])=>({x:u,y:h,w:g,h:m}))},images:l.map(([,u])=>u)})}this.publishCapture(),this.maybeCloseForSize(t)})}frameDiscarded(){this.post(()=>{let e=this.active;!e||!this.canCapture(e)||e.openGaps.has("mask_uncertain")||e.openGaps.set("mask_uncertain",this.t(e))})}submitTouch(e,t,n,s=1,i="plain",o=!1){this.post(()=>{let a=this.active;if(!a||!this.canCapture(a,!1))return;this.burstUntilMono=this.deps.monoMicros()+He;let c=i!=="plain"||o||a.excluded?{kind:"redacted"}:{kind:e,nx:V(t,0,1),ny:V(n,0,1)};c.pointers=V(Math.round(s),1,10),a.buffer.push({type:"touch",t:this.t(a),fields:c})})}onConsentChanged(e){if(e){this.post(()=>this.autoCheck());return}this.post(()=>{this.armed=!1,this.triggered=!1,this.closeWindow(),this.active&&this.purge(this.active.meta,"opted_out");for(let t of[...this.uploads.values()])this.purge(t,"opted_out");for(let t of[...this.provisionals])this.dropProvisional(t);this.storeOp(()=>this.deps.store.purgeAll()),this.setStatus("off","opted_out"),this.track(this.pump())})}onSessionRotated(e,t){this.startingSession||e===this.selfStarted||this.post(async()=>{if(this.admitting){this.rotateAfterAdmission=!0;return}let n=this.active;if(n&&n.meta.sessionId!==e)this.finalize(n,"session_rotated"),this.setStatus("off");else if(n)return;this.window()?.session_id!==e&&this.closeWindow(),this.triggered&&(this.triggered=!1,this.armed=!1),this.autoArmed&&(this.armed=!1,this.autoArmed=!1),this.armed&&!this.active?await this.admit():await this.autoCheck()})}onEventAccepted(e,t,n){this.post(()=>{let s=this.eventRule();s&&n===s.startEvent&&this.waiting&&!this.active&&!this.admitting&&this.mayAuto()&&t===this.host.liveSessionId()&&!this.deniedReason()&&this.beginProvisional(t,{start_event:n,event_id:e},!1);let i=this.active;!i||t!==i.meta.sessionId||this.host.consentState()!=="granted"||(i.buffer.push({type:"event_ref",t:this.t(i),fields:{event_id:e}}),this.triggered&&s?.stopEvent&&n===s.stopEvent&&(i.meta.stopEvent=n,this.finalize(i,"stop_event"),this.triggered=!1,this.armed=!1,this.waiting=!0,this.closeWindow(),this.setStatus("off","awaiting_start_event"),this.track(this.pump())))})}onScreen(e){this.post(()=>{this.currentScreen=e,this.burstUntilMono=this.deps.monoMicros()+He;let t=this.active;if(!t)return;let n=this.isExcluded(t,e);t.excluded&&!n&&this.leaveExclusion(t),t.buffer.push({type:"screen",t:this.t(t),fields:{name:e.slice(0,128)}}),!t.excluded&&n&&this.enterExclusion(t)})}onForeground(){this.post(()=>{this.foreground=!0,this.backgroundSince=null,this.track(this.refreshConfig());let e=this.active;e&&(e.backgrounded&&(e.backgrounded=!1,e.buffer.push({type:"lifecycle",t:this.t(e),fields:{kind:"foreground"}}),e.needKeyframe=!0),e.paused==="background"&&(e.paused=null,this.setStatus("recording",void 0,this.sid(e))))})}onBackground(){this.post(async()=>{this.foreground=!1,this.backgroundSince=this.deps.now();let e=this.active;e&&(e.backgrounded||(this.dropYoungVisuals(e,"dropped_frames"),e.buffer.push({type:"lifecycle",t:this.t(e),fields:{kind:"background"}}),this.closeChunk(e,!0),e.backgrounded=!0,e.paused===null&&(e.paused="background",this.setStatus("paused","background",this.sid(e))),await this.pump()))})}onShutdown(e){this.post(async()=>{if(this.armed=!1,e){this.active&&this.purge(this.active.meta,"api_key_changed");for(let n of[...this.uploads.values()])this.purge(n,"api_key_changed");for(let n of[...this.provisionals])this.dropProvisional(n);this.setStatus("off","stopped")}else this.active&&this.finalize(this.active,"shutdown"),this.setStatus("off","shutdown");this.admitting&&(this.admitting=!1,this.admissionAttempt++),this.notifyStart();for(let n of this.provisionals)this.resolveWaiters(n);this.provisionals.clear(),this.ticker!==null&&clearInterval(this.ticker),this.ticker=null;let t=e?this.pumpRevokes():Promise.resolve();this.shutDown=!0;for(let n of this.uploads.keys())this.deps.claims.release(n);await t})}async admit(){let e=this.sessionForAdmission();if(!e){this.setStatus("off","admission_unavailable"),this.armed=!1,this.notifyStart();return}this.admitting=!0;let t=++this.admissionAttempt;this.rotateAfterAdmission=!1,this.setStatus("admitting");let n=this.deps.setTimer??((c,l)=>setTimeout(c,l)),s=this.deps.clearTimer??(c=>clearTimeout(c)),i=n(()=>{this.post(()=>{this.admitting&&this.admissionAttempt===t&&this.timeOutAdmission()})},this.deps.startTimeoutMs),o;try{o=await this.call("/replay/recordings",null,this.admissionBody(e,null))}finally{s(i)}let a=I(o),d=()=>this.revokeLate(o,a);if(t!==this.admissionAttempt){d(),await this.pump();return}if(this.admitting=!1,!this.armed||this.host.consentState()!=="granted"){d(),this.notifyStart(),await this.pump();return}if(o.status===201&&a){let c=M(a.policy),l=x(a.recording_id),u=x(a.admission_token),h=P(a.upload_deadline_seconds);!c||!l||!u||h===null?(this.setStatus("off","admission_unavailable"),this.armed=!1):(this.stateSet("policy",{fp:this.fingerprint(),policy:a.policy}),this.begin(l,u,e,c,this.deps.now()+h*1e3))}else o.status===200&&a?.state==="not_sampled"?this.setStatus("off","not_sampled"):o.status===400||o.status===401||o.status===403?(this.setStatus("off","admission_denied"),this.armed=!1):o.status===429?(this.setStatus("off","quota_exhausted"),this.armed=!1):(this.setStatus("off","admission_unavailable"),this.armed=!1);if(this.notifyStart(),this.rotateAfterAdmission){this.rotateAfterAdmission=!1;let c=this.host.liveSessionId();c&&this.onSessionRotated(c,"reset")}}sessionForAdmission(){let e=this.host.liveSessionId();if(e)return e;this.startingSession=!0;try{this.selfStarted=this.host.startSession()}finally{this.startingSession=!1}return this.selfStarted}admissionBody(e,t){let n=this.deps.viewport(),s={session_id:e,platform:Ue,sdk_version:this.host.sdkVersion,library:this.host.config.libraryName.slice(0,64),viewport:{w:n.w,h:n.h,density:n.density},profile:C,client_nonce:(this.deps.uuid??je)(),stream_id:T};this.options.allowedScreens&&(s.allowed_screens=[...this.options.allowedScreens]),this.options.excludedScreens.size>0&&(s.excluded_screens=[...this.options.excludedScreens]),t&&(s.trigger=t);let i=this.host.userId(),o=this.host.anonymousId();return i&&i.length<=pe&&(s.user_id=i),o&&o.length<=pe&&(s.anonymous_id=o),JSON.stringify(s)}revokeLate(e,t){if(e.status!==201)return;let n=x(t?.recording_id),s=x(t?.admission_token),i=this.host.consentState()==="granted"?"host_discard":"opted_out";n&&s&&this.revokes.push([n,s,i])}begin(e,t,n,s,i){let o=this.newMeta(e,t,n,i);this.uploads.set(e,o),this.lastSuccessAt=this.deps.now(),this.open(o,s,null)}newMeta(e,t,n,s){return{recordingId:e,token:t,sessionId:n,apiKeyFingerprint:this.fingerprint(),uploadDeadlineMs:s,streamId:T,lastChunkSeq:-1,finishReason:null,chunks:[]}}shell(e,t,n){return{meta:e,policy:t,beginMono:this.deps.monoMicros(),startedAt:this.deps.now(),buffer:[],nextSeq:0,nextChunkSeq:0,lastFrameMono:F,lastKeyframeMono:F,lastKeyframeId:null,frames:0,needKeyframe:!0,chains:new Map,writtenBytes:0,excluded:!1,paused:null,backgrounded:!1,openGaps:new Map,lastT:0,drafted:0,draftN:0,draftDirty:!1,prov:n,startScreen:this.currentScreen}}open(e,t,n){this.deps.claims.claim(e.recordingId),this.storeOp(()=>this.deps.store.save(e));let s=this.host.currentScreen();s&&(this.currentScreen=s);let i=this.shell(e,t,n);this.active=i;let o=this.deps.viewport();return i.buffer.push({type:"recording_begin",t:0,fields:{session_id:e.sessionId,recording_id:e.recordingId,stream_id:T,wall_epoch_ms:i.startedAt,viewport:{w:o.w,h:o.h,density:o.density},orientation:o.w>o.h?"landscape":"portrait",platform:Ue,sdk_version:this.host.sdkVersion,library:this.host.config.libraryName.slice(0,64),profile:C,policy_version:t.version}}),this.setStatus("recording",void 0,this.sid(i)),this.isExcluded(i,this.currentScreen)&&this.enterExclusion(i),this.foreground||(i.backgrounded=!0,i.buffer.push({type:"lifecycle",t:this.t(i),fields:{kind:"background"}}),i.paused="background",this.setStatus("paused","background",this.sid(i))),i}sid(e){return e.prov?void 0:e.meta.recordingId}beginProvisional(e,t,n){let s=this.deps.now(),i=this.stateGet("policy"),o=i?.fp===this.fingerprint()&&M(i.policy)||M(de),a=this.newMeta((this.deps.uuid??je)(),"",e,s+ze);a.provisional={openedAt:s,trigger:t},this.armed=!0,this.autoArmed=!1,this.triggered=!0,this.waiting=!1;let d=this.open(a,o,Ge(s,t));return this.provisionals.add(d),t&&!n&&this.stateSet("window",{session_id:e,open:!0,opened_at:s,...t}),this.track(this.attemptAdmission(d)),d}async attemptAdmission(e){let t=e.prov;if(!t||t.inFlight||!this.provisionals.has(e))return;t.inFlight=!0;let n=await this.call("/replay/recordings",null,this.admissionBody(e.meta.sessionId,t.trigger));t.inFlight=!1;let s=I(n);this.provisionals.has(e)?n.status===201&&s&&this.accept(e,s)||(n.status===200&&s?.state==="not_sampled"?this.refuse(e,"not_sampled"):n.status===400||n.status===401||n.status===403?this.refuse(e,S(s?.error)?.code==="REPLAY_DISABLED"?"remote_disabled":"admission_denied"):(t.last=n.status,t.backoffMs=Math.min(t.backoffMs?t.backoffMs*2:1e3,6e4),t.nextAt=this.deps.now()+Math.max(t.backoffMs,n.status===429?Xe(n):0))):this.revokeLate(n,s),this.resolveWaiters(e),await this.pump()}resolveWaiters(e){for(let t of e.prov?.waiters.splice(0)??[])try{t({...this.status})}catch{}}accept(e,t){let n=M(t.policy),s=x(t.recording_id),i=x(t.admission_token),o=P(t.upload_deadline_seconds);if(!n||!s||!i||o===null)return!1;this.stateSet("policy",{fp:this.fingerprint(),policy:t.policy}),this.provisionals.delete(e);let a=e.meta,d=a.recordingId;this.storeOp(()=>this.deps.store.deleteRecording(d)),this.deps.claims.release(d),a.recordingId=s,a.token=i,a.uploadDeadlineMs=this.deps.now()+o*1e3,delete a.provisional,e.prov=null;for(let l of e.buffer)l.type==="recording_begin"&&(l.fields={...l.fields,recording_id:s,policy_version:n.version});let c=e.policy.excludedScreens;return e.policy=n,this.retro(e,c),this.deps.claims.claim(s),this.storeOp(()=>this.deps.store.save(a)),this.uploads.set(s,a),e.draftDirty=!0,e===this.active?this.setStatus(e.paused?"paused":"recording",e.paused??void 0,s):this.closeChunk(e,!0),!0}retro(e,t){let n=l=>l!==null&&t.has(l)||this.isExcluded(e,l),s=(l,u)=>({type:"gap",t:u,fields:{reason:"excluded_screen",from_t:l,to_t:u}}),i=[],o=n(e.startScreen)?0:null,a=!1,d=!0;for(let l of e.buffer)if(!(l.type==="gap"&&l.fields.reason==="excluded_screen")){if(l.type==="screen"){let u=n(l.fields.name);if(o!==null&&!u&&(i.push(s(o,l.t)),o=null),i.push(l),o===null&&u){o=l.t;for(let h=i.length-1;h>=0&&i[h].t>l.t-G;h--)_(i[h])&&(o=Math.min(o,i.splice(h,1)[0].t),d=!1,a=!0)}continue}if(_(l)&&(o!==null||!d&&l.type==="patch")){d=!1,a=!0;continue}l.type==="keyframe"&&(d=!0),o!==null&&l.type==="touch"&&l.fields.nx!==void 0&&(l={...l,fields:{kind:"redacted",pointers:l.fields.pointers}}),o!==null&&l.type==="recording_end"&&(i.push(s(o,l.t)),o=null),i.push(l)}e.buffer=i,e.openGaps.delete("excluded_screen"),(a||!d)&&(e.needKeyframe=!0,e.lastKeyframeId=null);let c=i.findIndex(l=>l.type==="recording_end");if(c>=0){i[c]={...i[c],fields:{...i[c].fields,last_seq:e.nextSeq+c}};return}e.excluded=this.isExcluded(e,this.currentScreen),o!==null&&e.excluded&&e===this.active?e.openGaps.set("excluded_screen",o):o!==null?(i.push(s(o,e===this.active?this.t(e):i[i.length-1].t)),e.needKeyframe=!0):e.excluded&&e.openGaps.set("excluded_screen",this.t(e))}refuse(e,t){this.dropProvisional(e,t);let n=e.meta.sessionId,s=this.window();this.stateSet("window",{...s?.session_id===n?s:{session_id:n,opened_at:this.deps.now()},open:!1,denied:{user_id:this.host.userId(),reason:t}})}dropProvisional(e,t){this.provisionals.delete(e),this.storeOp(()=>this.deps.store.deleteRecording(e.meta.recordingId)),this.deps.claims.release(e.meta.recordingId),this.active===e&&(this.active=null,this.armed=!1,this.triggered=!1,this.waiting=!!this.eventRule()&&!this.hostStopped,t&&this.setStatus("off",t)),this.resolveWaiters(e)}tickProvisional(){let e=this.deps.now();for(let t of[...this.provisionals]){let n=t.prov;e-n.openedAt>ze||ce(t)>le?this.dropProvisional(t,n.last===429?"quota_exhausted":"admission_unavailable"):!n.inFlight&&e>=n.nextAt&&this.deps.isOnline()&&this.track(this.attemptAdmission(t))}}timeOutAdmission(){this.admitting=!1,this.admissionAttempt++,this.rotateAfterAdmission=!1,this.armed&&(this.armed=!1,this.setStatus("off","admission_unavailable")),this.notifyStart()}notifyStart(){let e=this.startWaiters.splice(0);for(let t of e)try{t(this.status)}catch{}}t(e){let t=Math.max(e.lastT,Math.round(this.deps.monoMicros()-e.beginMono));return e.lastT=t,t}canCapture(e,t=!0){return this.armed&&this.status.state==="recording"&&e.paused===null&&this.foreground&&this.host.consentState()==="granted"&&!this.host.config.childSafeMode&&(!!e.prov||this.deps.now()-this.lastSuccessAt<e.policy.maxStaleSeconds*1e3)&&(!t||!e.excluded)}adoptHostOptions(e){this.autoArmed=!1,this.hostStopped=!1,this.options=e;let t=this.active;if(!t)return;let n=this.isExcluded(t,this.currentScreen);!t.excluded&&n?this.enterExclusion(t):t.excluded&&!n&&this.leaveExclusion(t)}isExcluded(e,t){if(t!==null&&(e.policy.excludedScreens.has(t)||this.options.excludedScreens.has(t)))return!0;let n=this.options.allowedScreens;return n?t===null||!n.has(t):!1}enterExclusion(e){let t=this.dropYoungVisuals(e,null);e.excluded=!0,e.openGaps.has("excluded_screen")||e.openGaps.set("excluded_screen",t??this.t(e))}leaveExclusion(e){this.closeGap(e,"excluded_screen"),e.excluded=!1,e.needKeyframe=!0}dropYoungVisuals(e,t){let n=this.t(e),s=n-G,i=e.buffer.filter(a=>_(a)&&a.t>s);if(i.length===0)return null;e.buffer=e.buffer.filter(a=>!i.includes(a)),e.needKeyframe=!0;let o=Math.min(...i.map(a=>a.t));return t&&e.buffer.push({type:"gap",t:n,fields:{reason:t,from_t:o,to_t:n}}),o}closeGap(e,t){let n=e.openGaps.get(t);if(n===void 0)return;e.openGaps.delete(t);let s=this.t(e);e.buffer.push({type:"gap",t:s,fields:{reason:t,from_t:n,to_t:s}})}pause(e,t){e.paused===null&&(e.paused=t,e.openGaps.has(t)||e.openGaps.set(t,this.t(e)),this.setStatus("paused",t,this.sid(e)))}resume(e,t){e.paused===t&&(this.closeGap(e,t),e.paused=null,e.needKeyframe=!0,this.setStatus("recording",void 0,this.sid(e)))}maybeCloseForSize(e){ce(e)>=e.policy.maxChunkBytes*8/10&&this.closeChunk(e,!1)}closeChunk(e,t){if(e.prov){this.writeDraft(e);return}let n=e.buffer.length;if(!t){let i=this.t(e)-G,o=e.buffer.findIndex(a=>_(a)&&a.t>i);o>=0&&(n=o)}let s=e.policy.maxChunkBytes*8/10;for(;n>0;){let i=0;for(let o=0;i<n&&(i===0||o+j(e.buffer[i])<s);i++)o+=j(e.buffer[i]);this.sealPiece(e,e.buffer.splice(0,i)),n=Math.min(n-i,e.buffer.length)}}sealPiece(e,t){let n=e.meta.recordingId,s=L(n,T,e.nextChunkSeq,e.nextSeq,t,e.policy.version);if(s.bound>e.policy.maxChunkBytes){this.log("warn",`replay: chunk of ~${s.bound} bytes over max_chunk_bytes; frames dropped`),e.needKeyframe=!0,e.lastKeyframeId=null;let d=new Set(t.filter(u=>u.type==="keyframe").map(u=>u.fields.frame_id));this.dropOrphanedPatches(e,d);let l=[{type:"gap",t:t[0].t,fields:{reason:"chunk_dropped",from_t:t[0].t,to_t:t[t.length-1].t}},...t.filter(u=>!_(u))].map((u,h)=>u.type==="recording_end"?{...u,fields:{...u.fields,last_seq:e.nextSeq+h}}:u);if(s=L(n,T,e.nextChunkSeq,e.nextSeq,l,e.policy.version),s.bound>e.policy.maxChunkBytes)return}e.chains.set(s.chunkSeq,{keyframes:new Set(s.keyframes),bases:new Set(s.bases)}),e.meta.lastChunkSeq=s.chunkSeq,e.nextSeq=s.lastSeq+1,e.meta.nextSeq=e.nextSeq,e.nextChunkSeq++,e.drafted=0,e.draftN=0,e.draftDirty=!1,e.writtenBytes+=s.bound;let i=e.meta,o={streamId:T,chunkSeq:s.chunkSeq,length:s.bound,sha256:"",createdWallMs:this.deps.now(),encoded:!1};this.writing.set(n,(this.writing.get(n)??0)+1);let a=()=>{let d=(this.writing.get(n)??1)-1;d>0?this.writing.set(n,d):this.writing.delete(n)};this.storeOp(()=>this.deps.store.writeChunk(i,o,s)).then(()=>{a(),this.uploads.get(n)===i&&(this.enforceStoreBounds(),this.track(this.pump()))},d=>{a(),this.log("warn","replay: chunk write failed",d),this.chunkDroppedGap(i)})}writeDraft(e){let t=this.t(e)-G,n=e.buffer.findIndex(c=>_(c)&&c.t>t),s=n<0?e.buffer.length:n,i=e.draftDirty?0:e.drafted;if(s<=i&&!e.draftDirty)return;let o=e.draftDirty?0:e.draftN,a={chunkSeq:e.nextChunkSeq,policyVersion:e.policy.version,records:e.buffer.slice(i,s)};e.drafted=s,e.draftN=o+1,e.draftDirty=!1;let d=e.meta.recordingId;this.storeOp(()=>this.deps.store.appendDraft(d,o,a))}finalize(e,t){this.dropYoungVisuals(e,t==="session_rotated"?null:"dropped_frames");for(let o of[...e.openGaps.keys()])this.closeGap(e,o);let n=e.nextSeq+e.buffer.length,s=t==="stop_event"?"host_stop":t;e.buffer.push({type:"recording_end",t:this.t(e),fields:{reason:s,last_seq:n}}),this.closeChunk(e,!0),e.meta.finishReason=t;let i=e.meta;this.storeOp(async()=>{(this.uploads.get(i.recordingId)===i||this.provisionals.has(e))&&await this.deps.store.save(i)}),this.active=null}purge(e,t){for(let n of this.provisionals)if(n.meta===e)return this.dropProvisional(n);this.revokes.push([e.recordingId,e.token,t]),this.uploads.delete(e.recordingId),this.storeOp(()=>this.deps.store.deleteRecording(e.recordingId));for(let n of[...this.grants.keys()])n.startsWith(`${e.recordingId}:`)&&this.grants.delete(n);this.active?.meta.recordingId===e.recordingId&&(this.active=null),this.deps.claims.release(e.recordingId)}storeBytes(){let e=0;for(let t of this.uploads.values())for(let n of t.chunks)e+=n.length;return e}enforceStoreBounds(){let e=this.deps.now();for(let s of[...this.uploads.values()])for(let i of s.chunks.filter(o=>e-o.createdWallMs>Lt))this.deleteChunk(s,i);let t=this.active;if(!t)return;let n=()=>t.meta.chunks.reduce((s,i)=>s+i.length,0);for(;n()>le||this.storeBytes()>We;){let s=[...t.meta.chunks].sort((i,o)=>i.chunkSeq-o.chunkSeq)[0];if(!s)break;this.dropWithDependents(t,s),t.buffer.unshift({type:"gap",t:this.t(t),fields:{reason:"chunk_dropped",from_t:0,to_t:this.t(t)}}),t.draftDirty=!0,this.pause(t,"resource_limit")}}dropWithDependents(e,t){let n=new Set,s=[];for(let i of[...e.meta.chunks].sort((o,a)=>o.chunkSeq-a.chunkSeq)){let o=e.chains.get(i.chunkSeq);(i===t||o&&[...o.bases].some(a=>n.has(a)))&&(s.push(i),o?.keyframes.forEach(a=>n.add(a)))}for(let i of s)this.deleteChunk(e.meta,i),e.chains.delete(i.chunkSeq);this.dropOrphanedPatches(e,n)}dropOrphanedPatches(e,t){t.size!==0&&(e.buffer=e.buffer.filter(n=>!(n.type==="patch"&&t.has(n.fields.base_frame_id))),e.draftDirty=!0,e.lastKeyframeId!==null&&t.has(e.lastKeyframeId)&&(e.needKeyframe=!0,e.lastKeyframeId=null))}deleteChunk(e,t){e.chunks=e.chunks.filter(n=>n!==t),this.storeOp(()=>this.deps.store.deleteChunk({...e,chunks:[...e.chunks,t]},t))}tick(){this.post(()=>this.tickNow())}async tickNow(){this.tickProvisional();let e=this.active,t=this.deps.now();if(e){let n=e.buffer[0];n&&this.t(e)-n.t>=e.policy.chunkMaxSeconds*1e6?this.closeChunk(e,!1):this.writeDraft(e),!e.prov&&e.paused===null&&t-this.lastSuccessAt>=e.policy.maxStaleSeconds*1e3&&this.pause(e,"policy_stale"),(t-e.startedAt>=e.policy.maxRecordingSeconds*1e3||e.writtenBytes>=e.policy.maxRecordingBytes)&&(this.armed=!1,this.finalize(e,"limit"),this.setStatus("finalizing","limit",this.sid(e)));let s=this.backgroundSince;this.active&&!this.foreground&&s!==null&&t-s>this.host.config.sessionTimeoutMs&&(this.finalize(this.active,"background_timeout"),this.setStatus("off"))}await this.pump()}async hasDueWork(){if(await this.idle(),!this.deps.isOnline())return!1;let e=this.deps.now();if(this.revokes.length>0||this.provisionals.size>0)return!0;if(e<this.quotaUntil)return!1;for(let n of this.uploads.values())if(n.chunks.length>0||n.finishReason!==null)return!0;let t=this.active?.paused;return(t==="policy_stale"||t==="quota_exhausted")&&e-this.lastRefreshAt>=Ke}async pump(){if(!this.shutDown){if(this.pumping){this.pumpAgain=!0;return}this.pumping=!0;try{do this.pumpAgain=!1,await this.pumpOnce();while(this.pumpAgain&&!this.shutDown)}finally{this.pumping=!1}}}alive(e){return this.uploads.get(e.recordingId)===e}async pumpRevokes(){for(;this.revokes.length>0&&this.deps.isOnline();){let[e,t,n]=this.revokes.shift();await this.call(`/replay/recordings/${e}/revoke`,t,JSON.stringify({reason:n}),!1)}}async pumpOnce(){if(!this.deps.isOnline())return;await this.pumpRevokes();for(let n=0;n<64;n++){let s=this.deps.now();if(s<this.backoffUntil||s<this.quotaUntil)break;let i=this.active?.meta.recordingId,o=[...this.uploads.values()].find(c=>c.chunks.length>0||c.finishReason!==null&&c.recordingId!==i&&!this.writing.has(c.recordingId));if(!o)break;let a=[...o.chunks].sort((c,l)=>c.chunkSeq-l.chunkSeq)[0];if(!(a?await this.uploadOne(o,a):await this.finish(o)))break}let e=this.active;if(!e)return;e.paused==="resource_limit"&&e.meta.chunks.reduce((n,s)=>n+s.length,0)<=le/2&&this.storeBytes()<=We/2&&this.resume(e,"resource_limit");let t=this.deps.now();if((e.paused==="policy_stale"||e.paused==="quota_exhausted"&&t>=this.quotaUntil)&&t-this.lastRefreshAt>=Ke&&t>=this.backoffUntil){this.lastRefreshAt=t;let n=await this.call("/replay/grants",e.meta.token,this.grantsBody(e.meta,[]));n.status===200?this.applyPolicy(I(n)):this.handleError(e.meta,null,n)}}grantsBody(e,t){return JSON.stringify({recording_id:e.recordingId,policy_version:this.policyVersionFor(e),chunks:t.map(n=>({stream_id:n.streamId,chunk_seq:n.chunkSeq,length:n.length,sha256:n.sha256}))})}policyVersionFor(e){return this.active?.meta.recordingId===e.recordingId?this.active.policy.version:1}async uploadOne(e,t){let n=`${e.recordingId}:${t.streamId}:${t.chunkSeq}`,s=await this.storeOp(()=>this.deps.store.readChunk(e.recordingId,t));if(!this.alive(e))return!0;if(!s)return this.deleteChunk(e,t),!0;let i;if(s instanceof Uint8Array)i=s;else{let l=await Be(s);if(!this.alive(e))return!0;let u={...t,length:l.bytes.length,sha256:l.sha256,encoded:!0};try{await this.storeOp(()=>this.deps.store.replaceChunk(e,t,u,l.bytes))}catch{return this.backoff()}if(!this.alive(e))return!0;if(l.bytes.length>ue)return this.deleteChunk(e,u),this.chunkDroppedGap(e),!0;t=u,i=l.bytes}let o=this.grants.get(n);if(o&&this.deps.now()>=o.expiresAt&&(o=void 0),!o){let l=await this.call("/replay/grants",e.token,this.grantsBody(e,[t]));if(!this.alive(e))return!0;if(l.status!==200)return this.handleError(e,t,l);let u=I(l);if(!u)return this.backoff();if(this.applyPolicy(u),Array.isArray(u.committed)&&u.committed.some(f=>S(f)?.chunk_seq===t.chunkSeq))return this.deleteChunk(e,t),!0;let g=Array.isArray(u.grants)?S(u.grants[0]):null,m=S(g?.required_headers),y=x(g?.grant_id),v=x(g?.put_url),p=P(g?.expires_in_seconds);if(!g||!m||!y||!v||p===null||Object.values(m).some(f=>typeof f!="string"))return this.backoff();o={id:y,url:v,headers:m,expiresAt:this.deps.now()+(p-5)*1e3,uploaded:!1},this.grants.set(n,o)}if(!o.uploaded){let l=await this.deps.transport.put(o.url,o.headers,i);if(!this.alive(e))return!0;if(l<200||l>299)return this.backoff();o.uploaded=!0}let a=await this.call("/replay/commits",e.token,JSON.stringify({recording_id:e.recordingId,policy_version:this.policyVersionFor(e),grants:[{grant_id:o.id,stream_id:t.streamId,chunk_seq:t.chunkSeq}]}));if(!this.alive(e))return!0;if(a.status!==200)return this.handleError(e,t,a);let d=I(a);if(!d)return this.backoff();this.applyPolicy(d);let c=Array.isArray(d.results)?S(d.results[0]):null;if(!c)return this.backoff();switch(c.status){case"committed":case"duplicate":this.grants.delete(n),this.deleteChunk(e,t);break;case"pending":return this.backoff();case"expired":this.grants.delete(n);break;case"rejected":{this.grants.delete(n);let l=c.reason;if((l==="checksum_mismatch"||l==="size_mismatch")&&!this.checksumRetried.has(n))return this.checksumRetried.add(n),!0;this.deleteChunk(e,t),this.chunkDroppedGap(e);break}default:return this.backoff()}return!0}async finish(e){let t=await this.call(`/replay/recordings/${e.recordingId}/finish`,e.token,JSON.stringify({reason:e.finishReason,last_chunk_seq:{[e.streamId]:e.lastChunkSeq},...e.stopEvent?{stop_event:e.stopEvent}:{}}));return this.alive(e)?t.status===200||t.status===401||t.status===404||t.status===410?(this.done(e),!0):this.handleError(e,null,t):!0}done(e){this.uploads.delete(e.recordingId),this.storeOp(()=>this.deps.store.deleteRecording(e.recordingId)),this.deps.claims.release(e.recordingId),this.status.state==="finalizing"&&this.status.recordingId===e.recordingId&&!this.active&&this.setStatus("off",this.status.reason)}handleError(e,t,n){let s=this.active?.meta.recordingId===e.recordingId;switch(n.status){case 401:case 404:case 410:return this.purgeLocalOnly(e),s&&this.setStatus("off","recording_closed"),!0;case 403:return this.purgeLocalOnly(e),s&&(this.armed=!1,this.setStatus("off","policy_revoked")),!0;case 409:if(t&&this.deleteChunk(e,t),s){let i=this.active;this.armed=!1,this.active=null,i.meta.finishReason=i.meta.finishReason??"host_stop",this.setStatus("off","chunk_conflict")}return!0;case 400:case 413:return t&&(this.deleteChunk(e,t),this.chunkDroppedGap(e)),!0;case 429:return this.quotaUntil=this.deps.now()+Xe(n),s&&this.pause(this.active,"quota_exhausted"),!1;default:return this.backoff()}}purgeLocalOnly(e){this.uploads.delete(e.recordingId),this.storeOp(()=>this.deps.store.deleteRecording(e.recordingId)),this.deps.claims.release(e.recordingId),this.active?.meta.recordingId===e.recordingId&&(this.active=null)}chunkDroppedGap(e){let t=this.active;!t||t.meta.recordingId!==e.recordingId||t.buffer.push({type:"gap",t:this.t(t),fields:{reason:"chunk_dropped",from_t:0,to_t:this.t(t)}})}backoff(){this.backoffMs=this.backoffMs===0?1e3:Math.min(this.backoffMs*2,6e4);let e=this.deps.jitter===!1?this.backoffMs:Math.floor(this.backoffMs*(.5+Math.random()*.5));return this.backoffUntil=this.deps.now()+e,!1}applyPolicy(e){let t=this.active;if(!t)return;let n=P(e?.policy_version);if(n===null||n<=t.policy.version)return;let s=M(e?.policy);if(!s){this.pause(t,"policy_stale");return}t.policy=s;let i=this.isExcluded(t,this.currentScreen);!t.excluded&&i&&this.enterExclusion(t),t.excluded&&!i&&this.leaveExclusion(t)}markSuccess(){let e=this.deps.now();this.lastSuccessAt=e,this.backoffMs=0,this.backoffUntil=0;let t=this.active;t&&(t.paused==="policy_stale"&&this.resume(t,"policy_stale"),t.paused==="quota_exhausted"&&e>=this.quotaUntil&&this.resume(t,"quota_exhausted"))}async call(e,t,n,s=!0){let i=this.host.config,o=await this.deps.transport.post(i.endpoint.replace(/\/+$/,"")+e,i.apiKey,t,n);return s&&o.status>=200&&o.status<=299&&this.markSuccess(),o}async recover(){let e=this.host.consentState()==="granted",t=this.host.apiKeyFingerprint(this.host.config.apiKey),n=this.deps.now(),s=await this.storeOp(()=>this.deps.store.recordings());for(let i of s){let o=i.recordingId;if(!(this.uploads.has(o)||this.active?.meta.recordingId===o||[...this.provisionals].some(a=>a.meta.recordingId===o))&&await this.deps.claims.claim(o)){if(!e||this.host.config.childSafeMode||i.apiKeyFingerprint!==t||n>i.uploadDeadlineMs){await this.storeOp(()=>this.deps.store.deleteRecording(o)),this.deps.claims.release(o);continue}if(i.provisional){await this.recoverProvisional(i,i.provisional);continue}i.finishReason===null&&(i.finishReason="shutdown",await this.sealDrafts(i)),await this.storeOp(()=>this.deps.store.save(i)),this.uploads.set(i.recordingId,i)}}await this.pump()}async recoverProvisional(e,t){let{records:n}=await this.storeOp(()=>this.deps.store.readDrafts(e.recordingId,0));if(n[0]?.type!=="recording_begin"){await this.storeOp(()=>this.deps.store.deleteRecording(e.recordingId)),this.deps.claims.release(e.recordingId);return}e.finishReason??(e.finishReason="shutdown"),this.storeOp(()=>this.deps.store.save(e));let s=this.shell(e,M(de),Ge(t.openedAt,t.trigger));s.buffer=n,s.startScreen=null,this.provisionals.add(s),this.track(this.attemptAdmission(s))}async sealDrafts(e){let t=e.lastChunkSeq+1,{records:n,policyVersion:s}=await this.storeOp(()=>this.deps.store.readDrafts(e.recordingId,t));if(n.length===0||t===0!=(n[0]?.type==="recording_begin"))return;let i=L(e.recordingId,e.streamId,t,e.nextSeq??0,n,s);if(i.bound>ue&&(i=L(e.recordingId,e.streamId,t,e.nextSeq??0,n.filter(a=>!_(a)),s),i.bound>ue))return;let o={streamId:e.streamId,chunkSeq:t,length:i.bound,sha256:"",createdWallMs:this.deps.now(),encoded:!1};e.lastChunkSeq=t,e.nextSeq=i.lastSeq+1;try{await this.storeOp(()=>this.deps.store.writeChunk(e,o,i))}catch{e.lastChunkSeq=t-1}}setStatus(e,t,n){let s={state:e};return t&&(s.reason=t),n&&(s.recordingId=n),this.status=s,this.publishCapture(),s}publishCapture(){let e=this.active,t=!!e&&this.canCapture(e,!1),n=e&&t&&!e.excluded?e.policy:null;if(this.touchesWanted=t,this.wantsKeyframe=!e||e.needKeyframe||e.lastKeyframeId===null||this.deps.monoMicros()-e.lastKeyframeMono>=e.policy.keyframeIntervalSeconds*1e6,n!==this.capturePolicy){this.capturePolicy=n;try{this.onCaptureChanged?.(n)}catch{}}this.updateTicker()}get recordingId(){return this.active?.meta.recordingId??null}};function ce(r){return r.buffer.reduce((e,t)=>e+j(t),0)}function Bt(r,e){let t=(n,s)=>n===s||!!n&&!!s&&n.size===s.size&&[...n].every(i=>s.has(i));return t(r.allowedScreens,e.allowedScreens)&&t(r.excludedScreens,e.excludedScreens)}var Ge=(r,e)=>({openedAt:r,trigger:e,inFlight:!1,nextAt:0,backoffMs:0,last:0,waiters:[]}),Ve=r=>typeof r=="string"&&r.length>=1&&r.length<=pe?r:null;function $e(r){if(r==null)return null;let e=S(r),t=e?.start_event===null?null:Ve(e?.start_event),n=e?.stop_event===null?null:Ve(e?.stop_event);return!e||typeof e.replay_enabled!="boolean"||t===null&&e.start_event!==null||n===null&&e.stop_event!==null?{enabled:!1,startEvent:null,stopEvent:null}:{enabled:e.replay_enabled,startEvent:t,stopEvent:t!==null&&n!==t?n:null}}function Xe(r){let e=P(S(I(r)?.error)?.retry_after_seconds),t=r.retryAfter&&/^\d+$/.test(r.retryAfter.trim())?Number(r.retryAfter.trim()):null;return V(e??t??60,1,3600)*1e3}function I(r){try{return S(JSON.parse(r.body))}catch{return null}}var B=(r,e)=>`${r}-${e.streamId}-${e.chunkSeq}`,X=r=>({...r,chunks:r.chunks.map(e=>({...e}))}),Nt=(r,e)=>r.streamId===e.streamId&&r.chunkSeq===e.chunkSeq;var Ut="depsmith-replay",Kt=1,fe=r=>`${r}~draft~`,J=r=>IDBKeyRange.bound(fe(r),`${fe(r)}\uFFFF`);function D(r){return new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}function E(r){return new Promise((e,t)=>{r.oncomplete=()=>e(),r.onerror=()=>t(r.error),r.onabort=()=>t(r.error)})}var Y=class{constructor(e=indexedDB){this.db=new Promise((t,n)=>{let s=e.open(Ut,Kt);s.onupgradeneeded=()=>{let i=s.result;i.objectStoreNames.contains("meta")||i.createObjectStore("meta",{keyPath:"recordingId"}),i.objectStoreNames.contains("chunks")||i.createObjectStore("chunks")},s.onsuccess=()=>t(s.result),s.onerror=()=>n(s.error),s.onblocked=()=>n(new Error("replay store blocked"))}),this.db.catch(()=>{})}async tx(e){return(await this.db).transaction(["meta","chunks"],e)}async recordings(){try{let e=await this.tx("readonly"),t=await D(e.objectStore("meta").getAll()),n=new Set(await D(e.objectStore("chunks").getAllKeys()));for(let s of t)s.chunks=s.chunks.filter(i=>n.has(B(s.recordingId,i)));return t.sort((s,i)=>s.recordingId<i.recordingId?-1:1)}catch{return[]}}async save(e){try{let t=await this.tx("readwrite");t.objectStore("meta").put(X(e)),await E(t)}catch{}}async writeChunk(e,t,n){e.chunks.push(t);try{let s=await this.tx("readwrite");s.objectStore("chunks").put(n,B(e.recordingId,t)),s.objectStore("chunks").delete(J(e.recordingId)),s.objectStore("meta").put(X(e)),await E(s)}catch(s){throw e.chunks=e.chunks.filter(i=>i!==t),s}}async readChunk(e,t){try{let n=await this.tx("readonly"),s=await D(n.objectStore("chunks").get(B(e,t)));return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):s&&typeof s=="object"&&s.ndjson instanceof Uint8Array?s:null}catch{return null}}async replaceChunk(e,t,n,s){e.chunks=e.chunks.map(a=>Nt(a,t)?n:a);let i=await this.tx("readwrite");await D(i.objectStore("meta").get(e.recordingId))&&(i.objectStore("chunks").put(s,B(e.recordingId,n)),i.objectStore("meta").put(X(e)),await E(i))}async appendDraft(e,t,n){try{let s=await this.tx("readwrite");t===0&&s.objectStore("chunks").delete(J(e)),s.objectStore("chunks").put(n,`${fe(e)}${String(t).padStart(6,"0")}`),await E(s)}catch{}}async readDrafts(e,t){try{let n=await this.tx("readonly"),s=(await D(n.objectStore("chunks").getAll(J(e)))).filter(i=>i&&i.chunkSeq===t&&Array.isArray(i.records));return{records:s.flatMap(i=>i.records),policyVersion:s[0]?.policyVersion??1}}catch{return{records:[],policyVersion:1}}}async deleteChunk(e,t){e.chunks=e.chunks.filter(n=>!(n.streamId===t.streamId&&n.chunkSeq===t.chunkSeq));try{let n=await this.tx("readwrite");n.objectStore("chunks").delete(B(e.recordingId,t)),await D(n.objectStore("meta").get(e.recordingId))&&n.objectStore("meta").put(X(e)),await E(n)}catch{}}async deleteRecording(e){try{let t=await this.tx("readwrite");t.objectStore("meta").delete(e),t.objectStore("chunks").delete(IDBKeyRange.bound(`${e}-`,`${e}-\uFFFF`)),t.objectStore("chunks").delete(J(e)),await E(t)}catch{}}async purgeAll(){try{let e=await this.tx("readwrite");e.objectStore("meta").clear(),e.objectStore("chunks").clear(),await E(e)}catch{}}};function Ht(r){if(typeof AbortController>"u")return{cancel:()=>{}};let e=new AbortController,t=setTimeout(()=>e.abort(),r);return{signal:e.signal,cancel:()=>clearTimeout(t)}}function Je(r=(...e)=>fetch(...e)){let e=async(t,n)=>{let s=Ht(3e4);try{let i=await r(t,{...n,redirect:"manual",credentials:"omit",signal:s.signal});return i.type==="opaqueredirect"||i.status>=300&&i.status<400?{status:0,body:""}:{status:i.status,body:await i.text(),retryAfter:i.headers.get("Retry-After")}}catch{return{status:0,body:""}}finally{s.cancel()}};return{post:(t,n,s,i)=>{let o={"Content-Type":"application/json",Authorization:`Bearer ${n}`};return s&&(o["X-Replay-Token"]=s),e(t,{method:"POST",headers:o,body:i})},get:t=>e(t,{method:"GET"}),put:async(t,n,s)=>(await e(t,{method:"PUT",headers:{...n},body:s})).status}}var Wt={get(r){try{return JSON.parse(localStorage.getItem(`depsmith_replay_${r}`)??"null")}catch{return null}},set(r,e){try{localStorage.setItem(`depsmith_replay_${r}`,JSON.stringify(e))}catch{}}},ge=class{constructor(){this.held=new Map}async claim(e){if(this.held.has(e))return!0;let t=typeof navigator<"u"?navigator.locks:void 0;return t?.request?new Promise(n=>{t.request(`depsmith-replay:${e}`,{ifAvailable:!0},s=>{if(!s){n(!1);return}return new Promise(i=>{this.held.set(e,i),n(!0)})}).catch(()=>n(!0))}):!0}release(e){this.held.get(e)?.(),this.held.delete(e)}};function me(){try{if(typeof window>"u"||typeof document>"u"||typeof indexedDB>"u"||!Ne())return!1;let r=document.createElement("canvas");return typeof r.getContext=="function"&&!!r.getContext("2d")&&typeof r.toBlob=="function"}catch{return!1}}var O=null,Ye=null,Qe=!1,zt=new ge;function jt(){let r=Math.max(1,Math.min(16384,Math.round(window.innerWidth||1))),e=Math.max(1,Math.min(16384,Math.round(window.innerHeight||1))),t=window.devicePixelRatio,n=Number.isFinite(t)&&t>0?Math.min(8,Math.round(t*1e3)/1e3):1;return{w:r,h:e,density:n}}function Gt(r){if(et(),!me())return;Ye??(Ye=new Y);let e=new $(r,{now:()=>Date.now(),monoMicros:()=>Math.round(performance.now()*1e3),transport:Je(),store:Ye,isOnline:()=>navigator.onLine!==!1,viewport:jt,claims:zt,autoStart:!0,state:Wt});document.visibilityState==="hidden"&&e.onBackground();let t=()=>{document.visibilityState==="hidden"?e.onBackground():e.onForeground()},n=()=>e.onBackground(),s=o=>{o.persisted&&e.onForeground()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",n),window.addEventListener("pageshow",s);let i=new z(e,window);e.bind(),O={host:r,engine:e,capture:i,detach:()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",n),window.removeEventListener("pageshow",s),i.dispose()}}}function et(){let r=O;O=null,r?.detach()}var Vt={clientCreated:r=>Gt(Z(r)),clientGone:(r,e)=>{e&&ee(Z(r),!0),et()}},Ze=!1,tt={install(){if(!Qe){Qe=!0;try{_e(Vt)}catch{}}},start(r={}){if(tt.install(),!me())return Ze||(Ze=!0,console.warn("[depsmith-sdk] Session Replay is not supported on this page (needs a secure context, IndexedDB and canvas)")),Promise.resolve({state:"off",reason:"unsupported_platform"});let e=O;if(!e)return Promise.resolve({state:"off",reason:"not_initialized"});let t={allowedScreens:Array.isArray(r.allowedScreens)?r.allowedScreens.filter(n=>typeof n=="string"):void 0,excludedScreens:Array.isArray(r.excludedScreens)?r.excludedScreens.filter(n=>typeof n=="string"):void 0};return new Promise(n=>{try{e.engine.start(t,n)}catch{n({state:"off",reason:"admission_unavailable"})}})},stop(r={}){let e=O;return e?new Promise(t=>{try{e.engine.stop(r.discardPending===!0,t)}catch{t()}}):Promise.resolve()},getStatus(){let r=O;return r?{...r.engine.status}:{state:"off",reason:me()?"not_initialized":"unsupported_platform"}}},An=tt;export{ne as ALLOW_ATTR,xe as EXCLUDE_ATTR,te as MASK_ATTR,Ae as NO_CAPTURE_ATTR,An as default,me as replaySupported,tt as sessionReplay};
3
+ //# sourceMappingURL=replay.js.map