From 919ca1d01e7e80135b2e16303e75eabe27fe5762 Mon Sep 17 00:00:00 2001 From: Apteryx Date: Fri, 14 Feb 2025 20:12:19 +1300 Subject: [PATCH 1/6] Remove posthog analytics --- apps/discord-bot/package.json | 1 - apps/discord-bot/src/handlers/evaluate.ts | 12 - apps/discord-bot/src/index.ts | 19 - apps/discord-bot/src/services/analytics.ts | 16 - apps/website/package.json | 1 - .../components/editor/execute-bar/index.tsx | 6 - apps/website/src/components/providers.tsx | 7 +- apps/website/src/services/analytics.ts | 93 - package.json | 3 +- patches/posthog-js@1.161.3.patch | 10267 ---------------- pnpm-lock.yaml | 125 - 11 files changed, 2 insertions(+), 10548 deletions(-) delete mode 100644 apps/discord-bot/src/services/analytics.ts delete mode 100644 apps/website/src/services/analytics.ts delete mode 100644 patches/posthog-js@1.161.3.patch diff --git a/apps/discord-bot/package.json b/apps/discord-bot/package.json index 1a62b3e4..fcac5cad 100644 --- a/apps/discord-bot/package.json +++ b/apps/discord-bot/package.json @@ -24,7 +24,6 @@ "@evaluate/shapes": "workspace:^", "@t3-oss/env-core": "^0.11.1", "@vercel/functions": "^1.5.1", - "posthog-node": "^4.3.1", "zod": "3.22.4" } } diff --git a/apps/discord-bot/src/handlers/evaluate.ts b/apps/discord-bot/src/handlers/evaluate.ts index 307696f2..e1d25b78 100644 --- a/apps/discord-bot/src/handlers/evaluate.ts +++ b/apps/discord-bot/src/handlers/evaluate.ts @@ -15,7 +15,6 @@ import type { ExecuteResult, PartialRuntime } from '@evaluate/shapes'; import { EditEvaluationButton } from '~/components/edit-evaluation-button'; import { OpenEvaluationButton } from '~/components/open-evaluation-button'; import env from '~/env'; -import analytics from '~/services/analytics'; import { codeBlock } from '~/utilities/discord-formatting'; function isNew( @@ -99,17 +98,6 @@ export async function handleEvaluating( throw error; }); - analytics?.capture({ - distinctId: interaction.userId!, - event: 'code executed', - properties: { - platform: 'discord bot', - 'runtime id': runtime.id, - 'was successful': - result.run.code === 0 && (!result.compile || result.compile.code === 0), - }, - }); - const resultKey = result?.compile?.code ? 'compile' : 'run'; const hasTimedOut = result[resultKey]?.signal === 'SIGKILL'; const doesHaveDisplayableOutput = result[resultKey]?.output?.trim() !== ''; diff --git a/apps/discord-bot/src/index.ts b/apps/discord-bot/src/index.ts index aec6651a..72be19c7 100644 --- a/apps/discord-bot/src/index.ts +++ b/apps/discord-bot/src/index.ts @@ -1,6 +1,5 @@ import { InteractionType } from '@buape/carbon'; import env from './env'; -import analytics from './services/analytics'; import client from './services/client'; export default async function handler(request: Request) { @@ -27,23 +26,6 @@ export default async function handler(request: Request) { if (interaction.type === 1) return Response.json({ type: 1 }); - const user = interaction.member?.user ?? interaction.user; - if (analytics && user) - analytics.capture({ - distinctId: user.id, - event: 'interaction received', - properties: { - platform: 'discord bot', - 'interaction type': InteractionType[interaction.type], - 'guild id': interaction.guild?.id || null, - - $set_once: { - platform: 'discord bot', - username: user.username, - }, - }, - }); - if (interaction.type === InteractionType.ApplicationCommand) await client.commandHandler.handleCommandInteraction(interaction); if (interaction.type === InteractionType.MessageComponent) @@ -51,7 +33,6 @@ export default async function handler(request: Request) { if (interaction.type === InteractionType.ModalSubmit) await client.modalHandler.handleInteraction(interaction); - if (analytics) await analytics.shutdown(); return new Response(':)', { status: 200 }); } diff --git a/apps/discord-bot/src/services/analytics.ts b/apps/discord-bot/src/services/analytics.ts deleted file mode 100644 index 08501bb6..00000000 --- a/apps/discord-bot/src/services/analytics.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { PostHog } from 'posthog-node'; -import env from '~/env'; - -const enabled = Boolean(env.POSTHOG_KEY); -if (!enabled) - console.warn( - 'Missing Posthog environment variable, analytics will be disabled.', - ); - -export default enabled - ? new PostHog(env.POSTHOG_KEY!, { - host: 'https://app.posthog.com/', - flushAt: 1, - flushInterval: 0, - }) - : null; diff --git a/apps/website/package.json b/apps/website/package.json index 243b5cba..51376137 100644 --- a/apps/website/package.json +++ b/apps/website/package.json @@ -37,7 +37,6 @@ "material-icon-theme": "^5.14.1", "next": "^14.2.18", "next-themes": "npm:@wits/next-themes@^0.2.16", - "posthog-js": "^1.194.1", "react": "^18.3.1", "react-dnd": "^16.0.1", "react-dnd-html5-backend": "^16.0.1", diff --git a/apps/website/src/components/editor/execute-bar/index.tsx b/apps/website/src/components/editor/execute-bar/index.tsx index 2d250cea..1854272e 100644 --- a/apps/website/src/components/editor/execute-bar/index.tsx +++ b/apps/website/src/components/editor/execute-bar/index.tsx @@ -23,7 +23,6 @@ import { useForm } from 'react-hook-form'; import type { File } from 'virtual-file-explorer-backend'; import { useExplorer, useWatch } from '~/components/explorer/use'; import { useTerminal } from '~/components/terminal/use'; -import analytics from '~/services/analytics'; export function ExecuteBar({ runtime }: { runtime: PartialRuntime }) { const explorer = useExplorer(); @@ -103,11 +102,6 @@ export function ExecuteBar({ runtime }: { runtime: PartialRuntime }) { onSuccess(data) { setResult(data); dispatchEvent(new CustomEvent('mobile-terminal-open-change')); - analytics?.capture('code executed', { - 'runtime id': runtime.id, - 'was successful': - data.run.code === 0 && (!data.compile || data.compile.code === 0), - }); }, onError(error) { toast.error(error.message); diff --git a/apps/website/src/components/providers.tsx b/apps/website/src/components/providers.tsx index ca37da4a..31db3ded 100644 --- a/apps/website/src/components/providers.tsx +++ b/apps/website/src/components/providers.tsx @@ -24,8 +24,7 @@ import { TooltipProvider } from '@evaluate/components/tooltip'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; import { SpeedInsights } from '@vercel/speed-insights/next'; -import { useEffect, useState } from 'react'; -import { injectPageTracking } from '~/services/analytics'; +import { useState } from 'react'; import { BreakpointIndicator } from './breakpoint-indicator'; export function BodyProviders(p: React.PropsWithChildren) { @@ -46,10 +45,6 @@ export function BodyProviders(p: React.PropsWithChildren) { }), ); - useEffect(() => { - injectPageTracking(); - }, []); - return ( diff --git a/apps/website/src/services/analytics.ts b/apps/website/src/services/analytics.ts deleted file mode 100644 index ce66ef2f..00000000 --- a/apps/website/src/services/analytics.ts +++ /dev/null @@ -1,93 +0,0 @@ -import posthog from 'posthog-js'; -import env from '~/env'; - -const enabled = Boolean( - typeof window !== 'undefined' && - !window.location.origin.endsWith('.vercel.app') && - env.NEXT_PUBLIC_POSTHOG_KEY, -); -export default enabled ? posthog : null; - -if (enabled) { - posthog.init(env.NEXT_PUBLIC_POSTHOG_KEY!, { - api_host: `${window.location.origin}/api/ingest`, - ui_host: 'https://us.posthog.com/', - persistence: 'localStorage', - disable_compression: process.env.NODE_ENV === 'development', - enable_heatmaps: process.env.NODE_ENV === 'production', - }); - - posthog.register({ - platform: 'website', - $set_once: { platform: 'website' }, - }); -} - -export function injectPageTracking() { - if (!enabled) return false; - if (Reflect.get(history, '__injectPageTracking__')) return true; - - let isNavigating = false; - let lastLocation = { ...window.location }; - - function withoutHash(url: string | URL) { - return typeof url === 'string' ? url.split('#')[0] : url.href.split('#')[0]; - } - - window.addEventListener('popstate', () => { - if ( - !isNavigating && - withoutHash(lastLocation.href) !== withoutHash(location.href) - ) { - posthog.capture('$pageleave', { - $current_url: withoutHash(lastLocation.href), - $host: lastLocation.host, - $pathname: lastLocation.pathname, - }); - posthog.capture('$pageview', { - $current_url: withoutHash(location.href), - $host: location.host, - $pathname: location.pathname, - }); - } - - lastLocation = { ...window.location }; - }); - - function wrapStateFunction< - F extends typeof history.pushState | typeof history.replaceState, - >(fn: F) { - type T = ThisParameterType; - type P = Parameters; - - return function (this: T, state: P[0], _: P[1], url: P[2]) { - const isTracked = - !isNavigating && url && withoutHash(url) !== withoutHash(location.href); - if (isTracked) { - isNavigating = true; - posthog.capture('$pageleave', { - $current_url: withoutHash(location.href), - $host: location.host, - $pathname: location.pathname, - }); - } - fn.apply(this, [state, _, url]); - if (isTracked) - setTimeout(() => { - posthog.capture('$pageview', { - $current_url: withoutHash(location.href), - $host: location.host, - $pathname: location.pathname, - }); - lastLocation = { ...window.location }; - isNavigating = false; - }, 50); - }; - } - - history.pushState = wrapStateFunction(history.pushState); - history.replaceState = wrapStateFunction(history.replaceState); - Reflect.set(history, '__injectPageTracking__', true); - - return true; -} diff --git a/package.json b/package.json index bad726fe..a49ea583 100644 --- a/package.json +++ b/package.json @@ -26,8 +26,7 @@ }, "pnpm": { "patchedDependencies": { - "zod@3.22.4": "patches/zod@3.22.4.patch", - "posthog-js@1.161.3": "patches/posthog-js@1.161.3.patch" + "zod@3.22.4": "patches/zod@3.22.4.patch" }, "allowNonAppliedPatches": true } diff --git a/patches/posthog-js@1.161.3.patch b/patches/posthog-js@1.161.3.patch deleted file mode 100644 index fc394d1f..00000000 --- a/patches/posthog-js@1.161.3.patch +++ /dev/null @@ -1,10267 +0,0 @@ -diff --git a/dist/all-external-dependencies.js b/dist/all-external-dependencies.js -new file mode 100644 -index 0000000000000000000000000000000000000000..18c6217c358e84985ef28fded4ed3ace4703ab65 ---- /dev/null -+++ b/dist/all-external-dependencies.js -@@ -0,0 +1,17 @@ -+!function(){"use strict";function e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function t(t){for(var n=1;n=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var s=r.call(i,"catchLoc"),c=r.call(i,"finallyLoc");if(s&&c){if(this.prev=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),S(n),d}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var o=r.arg;S(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:k(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),d}},e}function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function o(e,t,n,r,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,o)}function i(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var a=e.apply(t,n);function s(e){o(a,r,i,s,c,"next",e)}function c(e){o(a,r,i,s,c,"throw",e)}s(void 0)}))}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){s=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}var g,v="2.0.0-alpha.13";function m(e){var t=null==e?void 0:e.host;return Boolean((null==t?void 0:t.shadowRoot)===e)}function y(e){return"[object ShadowRoot]"===Object.prototype.toString.call(e)}function b(e){try{var t=e.rules||e.cssRules;return t?((n=Array.from(t).map(C).join("")).includes(" background-clip: text;")&&!n.includes(" -webkit-background-clip: text;")&&(n=n.replace(" background-clip: text;"," -webkit-background-clip: text; background-clip: text;")),n):null}catch(e){return null}var n}function C(e){var t,n,r;if(function(e){return"styleSheet"in e}(e))try{t=b(e.styleSheet)||function(e){var t=e.cssText;if(t.split('"').length<3)return t;var n=["@import","url(".concat(JSON.stringify(e.href),")")];return""===e.layerName?n.push("layer"):e.layerName&&n.push("layer(".concat(e.layerName,")")),e.supportsText&&n.push("supports(".concat(e.supportsText,")")),e.media.length&&n.push(e.media.mediaText),n.join(" ")+";"}(e)}catch(e){}else if(function(e){return"selectorText"in e}(e)&&e.selectorText.includes(":"))return n=e.cssText,r=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm,n.replace(r,"$1\\$2");return t||e.cssText}!function(e){e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment"}(g||(g={}));var _=function(){function e(){a(this,e),this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}return c(e,[{key:"getId",value:function(e){var t;if(!e)return-1;var n=null===(t=this.getMeta(e))||void 0===t?void 0:t.id;return null!=n?n:-1}},{key:"getNode",value:function(e){return this.idNodeMap.get(e)||null}},{key:"getIds",value:function(){return Array.from(this.idNodeMap.keys())}},{key:"getMeta",value:function(e){return this.nodeMetaMap.get(e)||null}},{key:"removeNodeFromMap",value:function(e){var t=this,n=this.getId(e);this.idNodeMap.delete(n),e.childNodes&&e.childNodes.forEach((function(e){return t.removeNodeFromMap(e)}))}},{key:"has",value:function(e){return this.idNodeMap.has(e)}},{key:"hasNode",value:function(e){return this.nodeMetaMap.has(e)}},{key:"add",value:function(e,t){var n=t.id;this.idNodeMap.set(n,e),this.nodeMetaMap.set(e,t)}},{key:"replace",value:function(e,t){var n=this.getNode(e);if(n){var r=this.nodeMetaMap.get(n);r&&this.nodeMetaMap.set(t,r)}this.idNodeMap.set(e,t)}},{key:"reset",value:function(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}}]),e}();function I(e){var t=e.element,n=e.maskInputOptions,r=e.tagName,o=e.type,i=e.value,a=e.maskInputFn,s=i||"",c=o&&S(o);return(n[r.toLowerCase()]||c&&n[c])&&(s=a?a(s,t):"*".repeat(s.length)),s}function S(e){return e.toLowerCase()}var w="__rrweb_original__";function k(e){var t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?S(t):null}function x(e,t){var n,r;try{r=new URL(e,null!=t?t:window.location.href)}catch(e){return null}var o=r.pathname.match(/\.([0-9a-z]+)(?:$)/i);return null!==(n=null==o?void 0:o[1])&&void 0!==n?n:null}var A,T,M=1,E=new RegExp("[^a-z0-9-_:]"),N=-2;function O(){return M++}var L=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,R=/^(?:[a-z+]+:)?\/\//i,F=/^www\..*/i,D=/^(data:)([^,]*),(.*)/i;function q(e,t){return(e||"").replace(L,(function(e,n,r,o,i,a){var s,c=r||i||a,u=n||o||"";if(!c)return e;if(R.test(c)||F.test(c))return"url(".concat(u).concat(c).concat(u,")");if(D.test(c))return"url(".concat(u).concat(c).concat(u,")");if("/"===c[0])return"url(".concat(u).concat((s=t,(s.indexOf("//")>-1?s.split("/").slice(0,3).join("/"):s.split("/")[0]).split("?")[0]+c)).concat(u,")");var l=t.split("/"),d=c.split("/");l.pop();var p,f=h(d);try{for(f.s();!(p=f.n()).done;){var g=p.value;"."!==g&&(".."===g?l.pop():l.push(g))}}catch(e){f.e(e)}finally{f.f()}return"url(".concat(u).concat(l.join("/")).concat(u,")")}))}var P=/^[^ \t\n\r\u000c]+/,H=/^[, \t\n\r\u000c]+/;function B(e,t){if(!t||""===t.trim())return t;var n=e.createElement("a");return n.href=t,n.href}function W(e){return Boolean("svg"===e.tagName||e.ownerSVGElement)}function Z(){var e=document.createElement("a");return e.href="",e.href}function V(e,t,n,r){return r?"src"===n||"href"===n&&("use"!==t||"#"!==r[0])||"xlink:href"===n&&"#"!==r[0]?B(e,r):"background"!==n||"table"!==t&&"td"!==t&&"th"!==t?"srcset"===n?function(e,t){if(""===t.trim())return t;var n=0;function r(e){var r,o=e.exec(t.substring(n));return o?(r=o[0],n+=r.length,r):""}for(var o=[];r(H),!(n>=t.length);){var i=r(P);if(","===i.slice(-1))i=B(e,i.substring(0,i.length-1)),o.push(i);else{var a="";i=B(e,i);for(var s=!1;;){var c=t.charAt(n);if(""===c){o.push((i+a).trim());break}if(s)")"===c&&(s=!1);else{if(","===c){n+=1,o.push((i+a).trim());break}"("===c&&(s=!0)}a+=c,n+=1}}}return o.join(", ")}(e,r):"style"===n?q(r,Z()):"object"===t&&"data"===n?B(e,r):r:B(e,r):r}function U(e,t,n){return("video"===e||"audio"===e)&&"autoplay"===t||"video"===e&&"src"===t&&n&&n.startsWith("blob:http")}function j(e,t,n){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return!!n&&j(e.parentNode,t,n);for(var r=e.classList.length;r--;){var o=e.classList[r];if(t.test(o))return!0}return!!n&&j(e.parentNode,t,n)}function G(e,t,n,r){try{var o=e.nodeType===e.ELEMENT_NODE?e:e.parentElement;if(null===o)return!1;if("string"==typeof t){if(r){if(o.closest(".".concat(t)))return!0}else if(o.classList.contains(t))return!0}else if(j(o,t,r))return!0;if(n)if(r){if(o.closest(n))return!0}else if(o.matches(n))return!0}catch(e){}return!1}function K(e,t){var n=t.doc,r=t.mirror,o=t.blockClass,i=t.blockSelector,a=t.needsMask,s=t.inlineStylesheet,c=t.maskInputOptions,u=void 0===c?{}:c,l=t.maskTextFn,d=t.maskInputFn,p=t.dataURLOptions,f=void 0===p?{}:p,h=t.inlineImages,v=t.recordCanvas,m=t.keepIframeSrcFn,y=t.newlyAddedElement,C=void 0!==y&&y,_=function(e,t){if(!t.hasNode(e))return;var n=t.getId(e);return 1===n?void 0:n}(n,r);switch(e.nodeType){case e.DOCUMENT_NODE:return"CSS1Compat"!==e.compatMode?{type:g.Document,childNodes:[],compatMode:e.compatMode}:{type:g.Document,childNodes:[]};case e.DOCUMENT_TYPE_NODE:return{type:g.DocumentType,name:e.name,publicId:e.publicId,systemId:e.systemId,rootId:_};case e.ELEMENT_NODE:return function(e,t){for(var n,r=t.doc,o=t.blockClass,i=t.blockSelector,a=t.inlineStylesheet,s=t.maskInputOptions,c=void 0===s?{}:s,u=t.maskInputFn,l=t.dataURLOptions,d=void 0===l?{}:l,p=t.inlineImages,f=t.recordCanvas,h=t.keepIframeSrcFn,v=t.newlyAddedElement,m=void 0!==v&&v,y=t.rootId,C=function(e,t,n){try{if("string"==typeof t){if(e.classList.contains(t))return!0}else for(var r=e.classList.length;r--;){var o=e.classList[r];if(t.test(o))return!0}if(n)return e.matches(n)}catch(e){}return!1}(e,o,i),_=function(e){if(e instanceof HTMLFormElement)return"form";var t=S(e.tagName);return E.test(t)?"div":t}(e),x={},M=e.attributes.length,N=0;N2&&void 0!==arguments[2]?arguments[2]:document,r={capture:!0,passive:!0};return n.addEventListener(e,t,r),function(){return n.removeEventListener(e,t,r)}}var J="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.",X={map:{},getId:function(){return console.error(J),-1},getNode:function(){return console.error(J),null},removeNodeFromMap:function(){console.error(J)},has:function(){return console.error(J),!1},reset:function(){console.error(J)}};function $(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=null,o=0;return function(){for(var i=arguments.length,a=new Array(i),s=0;st?(r&&(clearTimeout(r),r=null),o=c,e.apply(l,a)):r||!1===n.trailing||(r=setTimeout((function(){o=!1===n.leading?0:Date.now(),r=null,e.apply(l,a)}),u))}}function ee(e,t,n,r){var o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:window,i=o.Object.getOwnPropertyDescriptor(e,t);return o.Object.defineProperty(e,t,r?n:{set:function(e){var t=this;setTimeout((function(){n.set.call(t,e)}),0),i&&i.set&&i.set.call(this,e)}}),function(){return ee(e,t,i||{},!0)}}function te(e,t,n){try{if(!(t in e))return function(){};var r=e[t],o=n(r);return"function"==typeof o&&(o.prototype=o.prototype||{},Object.defineProperties(o,{__rrweb_original__:{enumerable:!1,value:r}})),e[t]=o,function(){e[t]=r}}catch(e){return function(){}}}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(X=new Proxy(X,{get:function(e,t,n){return"map"===t&&console.error(J),Reflect.get(e,t,n)}}));var ne=Date.now;function re(e){var t,n,r,o,i,a,s=e.document;return{left:s.scrollingElement?s.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:(null==s?void 0:s.documentElement.scrollLeft)||(null===(n=null===(t=null==s?void 0:s.body)||void 0===t?void 0:t.parentElement)||void 0===n?void 0:n.scrollLeft)||(null===(r=null==s?void 0:s.body)||void 0===r?void 0:r.scrollLeft)||0,top:s.scrollingElement?s.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==s?void 0:s.documentElement.scrollTop)||(null===(i=null===(o=null==s?void 0:s.body)||void 0===o?void 0:o.parentElement)||void 0===i?void 0:i.scrollTop)||(null===(a=null==s?void 0:s.body)||void 0===a?void 0:a.scrollTop)||0}}function oe(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function ie(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function ae(e){return e?e.nodeType===e.ELEMENT_NODE?e:e.parentElement:null}function se(e,t,n,r){if(!e)return!1;var o=ae(e);if(!o)return!1;try{if("string"==typeof t){if(o.classList.contains(t))return!0;if(r&&null!==o.closest("."+t))return!0}else if(j(o,t,r))return!0}catch(e){}if(n){if(o.matches(n))return!0;if(r&&null!==o.closest(n))return!0}return!1}function ce(e,t){return t.getId(e)===N}function ue(e,t){if(m(e))return!1;var n=t.getId(e);return!t.has(n)||(!e.parentNode||e.parentNode.nodeType!==e.DOCUMENT_NODE)&&(!e.parentNode||ue(e.parentNode,t))}function le(e){return Boolean(e.changedTouches)}function de(e,t){return Boolean("IFRAME"===e.nodeName&&t.getMeta(e))}function pe(e,t){return Boolean("LINK"===e.nodeName&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&"stylesheet"===e.getAttribute("rel")&&t.getMeta(e))}function fe(e){return Boolean(null==e?void 0:e.shadowRoot)}/[1-9][0-9]{12}/.test(Date.now().toString())||(ne=function(){return(new Date).getTime()});var he=function(){function e(){a(this,e),this.id=1,this.styleIDMap=new WeakMap,this.idStyleMap=new Map}return c(e,[{key:"getId",value:function(e){var t;return null!==(t=this.styleIDMap.get(e))&&void 0!==t?t:-1}},{key:"has",value:function(e){return this.styleIDMap.has(e)}},{key:"add",value:function(e,t){return this.has(e)?this.getId(e):(n=void 0===t?this.id++:t,this.styleIDMap.set(e,n),this.idStyleMap.set(n,e),n);var n}},{key:"getStyle",value:function(e){return this.idStyleMap.get(e)||null}},{key:"reset",value:function(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}},{key:"generateId",value:function(){return this.id++}}]),e}();function ge(e){var t,n,r=null;return(null===(n=null===(t=e.getRootNode)||void 0===t?void 0:t.call(e))||void 0===n?void 0:n.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&e.getRootNode().host&&(r=e.getRootNode().host),r}function ve(e){var t=e.ownerDocument;if(!t)return!1;var n=function(e){for(var t,n=e;t=ge(n);)n=t;return n}(e);return t.contains(n)}function me(e){var t=e.ownerDocument;return!!t&&(t.contains(e)||ve(e))}var ye=function(e){return e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e}(ye||{}),be=function(e){return e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e}(be||{}),Ce=function(e){return e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e}(Ce||{}),_e=function(e){return e[e.Mouse=0]="Mouse",e[e.Pen=1]="Pen",e[e.Touch=2]="Touch",e}(_e||{}),Ie=function(e){return e[e["2D"]=0]="2D",e[e.WebGL=1]="WebGL",e[e.WebGL2=2]="WebGL2",e}(Ie||{});function Se(e){return"__ln"in e}var we,ke=function(){function e(){a(this,e),this.length=0,this.head=null,this.tail=null}return c(e,[{key:"get",value:function(e){if(e>=this.length)throw new Error("Position outside of list range");for(var t=this.head,n=0;n1&&void 0!==arguments[1]?arguments[1]:{},r=e.doc.defaultView;if(!r)return function(){};!function(e,t){var n=e.mutationCb,r=e.mousemoveCb,o=e.mouseInteractionCb,i=e.scrollCb,a=e.viewportResizeCb,s=e.inputCb,c=e.mediaInteractionCb,u=e.styleSheetRuleCb,l=e.styleDeclarationCb,d=e.canvasMutationCb,p=e.fontCb,f=e.selectionCb,h=e.customElementCb;e.mutationCb=function(){t.mutation&&t.mutation.apply(t,arguments),n.apply(void 0,arguments)},e.mousemoveCb=function(){t.mousemove&&t.mousemove.apply(t,arguments),r.apply(void 0,arguments)},e.mouseInteractionCb=function(){t.mouseInteraction&&t.mouseInteraction.apply(t,arguments),o.apply(void 0,arguments)},e.scrollCb=function(){t.scroll&&t.scroll.apply(t,arguments),i.apply(void 0,arguments)},e.viewportResizeCb=function(){t.viewportResize&&t.viewportResize.apply(t,arguments),a.apply(void 0,arguments)},e.inputCb=function(){t.input&&t.input.apply(t,arguments),s.apply(void 0,arguments)},e.mediaInteractionCb=function(){t.mediaInteaction&&t.mediaInteaction.apply(t,arguments),c.apply(void 0,arguments)},e.styleSheetRuleCb=function(){t.styleSheetRule&&t.styleSheetRule.apply(t,arguments),u.apply(void 0,arguments)},e.styleDeclarationCb=function(){t.styleDeclaration&&t.styleDeclaration.apply(t,arguments),l.apply(void 0,arguments)},e.canvasMutationCb=function(){t.canvasMutation&&t.canvasMutation.apply(t,arguments),d.apply(void 0,arguments)},e.fontCb=function(){t.font&&t.font.apply(t,arguments),p.apply(void 0,arguments)},e.selectionCb=function(){t.selection&&t.selection.apply(t,arguments),f.apply(void 0,arguments)},e.customElementCb=function(){t.customElement&&t.customElement.apply(t,arguments),h.apply(void 0,arguments)}}(e,n),e.recordDOM&&(t=Pe(e,e.doc));var o=function(e){var t=e.mousemoveCb,n=e.sampling,r=e.doc,o=e.mirror;if(!1===n.mousemove)return function(){};var i,a="number"==typeof n.mousemove?n.mousemove:50,s="number"==typeof n.mousemoveCallback?n.mousemoveCallback:500,c=[],u=$(Fe((function(e){var n=Date.now()-i;t(c.map((function(e){return e.timeOffset-=n,e})),e),c=[],i=null})),s),l=Fe($(Fe((function(e){var t=qe(e),n=le(e)?e.changedTouches[0]:e,r=n.clientX,a=n.clientY;i||(i=ne()),c.push({x:r,y:a,id:o.getId(t),timeOffset:ne()-i}),u("undefined"!=typeof DragEvent&&e instanceof DragEvent?be.Drag:e instanceof MouseEvent?be.MouseMove:be.TouchMove)})),a,{trailing:!1})),d=[Y("mousemove",l,r),Y("touchmove",l,r),Y("drag",l,r)];return Fe((function(){d.forEach((function(e){return e()}))}))}(e),i=He(e),a=Be(e),s=function(e,t){var n=e.viewportResizeCb,r=t.win,o=-1,i=-1;return Y("resize",Fe($(Fe((function(){var e=oe(),t=ie();o===e&&i===t||(n({width:Number(t),height:Number(e)}),o=e,i=t)})),200)),r)}(e,{win:r}),c=function(e){var t=e.inputCb,n=e.doc,r=e.mirror,o=e.blockClass,i=e.blockSelector,a=e.ignoreClass,s=e.ignoreSelector,c=e.maskInputOptions,u=e.maskInputFn,l=e.sampling,p=e.userTriggeredOnInput;function f(e){var t=qe(e),r=e.isTrusted,l=t&&t.tagName;if(t&&"OPTION"===l&&(t=t.parentElement),t&&l&&!(We.indexOf(l)<0)&&!se(t,o,i,!0)&&!(t.classList.contains(a)||s&&t.matches(s))){var d=t.value,f=!1,g=k(t)||"";"radio"===g||"checkbox"===g?f=t.checked:(c[l.toLowerCase()]||c[g])&&(d=I({element:t,maskInputOptions:c,tagName:l,type:g,value:d,maskInputFn:u})),h(t,p?{text:d,isChecked:f,userTriggered:r}:{text:d,isChecked:f});var v=t.name;"radio"===g&&v&&f&&n.querySelectorAll('input[type="radio"][name="'.concat(v,'"]')).forEach((function(e){if(e!==t){var n=e.value;h(e,p?{text:n,isChecked:!f,userTriggered:!1}:{text:n,isChecked:!f})}}))}}function h(e,n){var o=Ze.get(e);if(!o||o.text!==n.text||o.isChecked!==n.isChecked){Ze.set(e,n);var i=r.getId(e);Fe(t)(Object.assign(Object.assign({},n),{id:i}))}}var g=("last"===l.input?["change"]:["input","change"]).map((function(e){return Y(e,Fe(f),n)})),v=n.defaultView;if(!v)return function(){g.forEach((function(e){return e()}))};var m=v.Object.getOwnPropertyDescriptor(v.HTMLInputElement.prototype,"value"),y=[[v.HTMLInputElement.prototype,"value"],[v.HTMLInputElement.prototype,"checked"],[v.HTMLSelectElement.prototype,"value"],[v.HTMLTextAreaElement.prototype,"value"],[v.HTMLSelectElement.prototype,"selectedIndex"],[v.HTMLOptionElement.prototype,"selected"]];return m&&m.set&&g.push.apply(g,d(y.map((function(e){return ee(e[0],e[1],{set:function(){Fe(f)({target:this,isTrusted:!1})}},!1,v)})))),Fe((function(){g.forEach((function(e){return e()}))}))}(e),u=function(e){var t=e.mediaInteractionCb,n=e.blockClass,r=e.blockSelector,o=e.mirror,i=e.sampling,a=e.doc,s=Fe((function(e){return $(Fe((function(i){var a=qe(i);if(a&&!se(a,n,r,!0)){var s=a.currentTime,c=a.volume,u=a.muted,l=a.playbackRate,d=a.loop;t({type:e,id:o.getId(a),currentTime:s,volume:c,muted:u,playbackRate:l,loop:d})}})),i.media||500)})),c=[Y("play",s(0),a),Y("pause",s(1),a),Y("seeked",s(2),a),Y("volumechange",s(3),a),Y("ratechange",s(4),a)];return Fe((function(){c.forEach((function(e){return e()}))}))}(e),p=function(){},f=function(){},g=function(){},v=function(){};e.recordDOM&&(p=function(e,t){var n=e.styleSheetRuleCb,r=e.mirror,o=e.stylesheetManager,i=t.win;if(!i.CSSStyleSheet||!i.CSSStyleSheet.prototype)return function(){};var a=i.CSSStyleSheet.prototype.insertRule;i.CSSStyleSheet.prototype.insertRule=new Proxy(a,{apply:Fe((function(e,t,i){var a=l(i,2),s=a[0],c=a[1],u=Ue(t,r,o.styleMirror),d=u.id,p=u.styleId;return(d&&-1!==d||p&&-1!==p)&&n({id:d,styleId:p,adds:[{rule:s,index:c}]}),e.apply(t,i)}))});var s,c,u=i.CSSStyleSheet.prototype.deleteRule;i.CSSStyleSheet.prototype.deleteRule=new Proxy(u,{apply:Fe((function(e,t,i){var a=l(i,1)[0],s=Ue(t,r,o.styleMirror),c=s.id,u=s.styleId;return(c&&-1!==c||u&&-1!==u)&&n({id:c,styleId:u,removes:[{index:a}]}),e.apply(t,i)}))}),i.CSSStyleSheet.prototype.replace&&(s=i.CSSStyleSheet.prototype.replace,i.CSSStyleSheet.prototype.replace=new Proxy(s,{apply:Fe((function(e,t,i){var a=l(i,1)[0],s=Ue(t,r,o.styleMirror),c=s.id,u=s.styleId;return(c&&-1!==c||u&&-1!==u)&&n({id:c,styleId:u,replace:a}),e.apply(t,i)}))})),i.CSSStyleSheet.prototype.replaceSync&&(c=i.CSSStyleSheet.prototype.replaceSync,i.CSSStyleSheet.prototype.replaceSync=new Proxy(c,{apply:Fe((function(e,t,i){var a=l(i,1)[0],s=Ue(t,r,o.styleMirror),c=s.id,u=s.styleId;return(c&&-1!==c||u&&-1!==u)&&n({id:c,styleId:u,replaceSync:a}),e.apply(t,i)}))}));var p={};Qe("CSSGroupingRule")?p.CSSGroupingRule=i.CSSGroupingRule:(Qe("CSSMediaRule")&&(p.CSSMediaRule=i.CSSMediaRule),Qe("CSSConditionRule")&&(p.CSSConditionRule=i.CSSConditionRule),Qe("CSSSupportsRule")&&(p.CSSSupportsRule=i.CSSSupportsRule));var f={};return Object.entries(p).forEach((function(e){var t=l(e,2),i=t[0],a=t[1];f[i]={insertRule:a.prototype.insertRule,deleteRule:a.prototype.deleteRule},a.prototype.insertRule=new Proxy(f[i].insertRule,{apply:Fe((function(e,t,i){var a=l(i,2),s=a[0],c=a[1],u=Ue(t.parentStyleSheet,r,o.styleMirror),p=u.id,f=u.styleId;return(p&&-1!==p||f&&-1!==f)&&n({id:p,styleId:f,adds:[{rule:s,index:[].concat(d(Ve(t)),[c||0])}]}),e.apply(t,i)}))}),a.prototype.deleteRule=new Proxy(f[i].deleteRule,{apply:Fe((function(e,t,i){var a=l(i,1)[0],s=Ue(t.parentStyleSheet,r,o.styleMirror),c=s.id,u=s.styleId;return(c&&-1!==c||u&&-1!==u)&&n({id:c,styleId:u,removes:[{index:[].concat(d(Ve(t)),[a])}]}),e.apply(t,i)}))})})),Fe((function(){i.CSSStyleSheet.prototype.insertRule=a,i.CSSStyleSheet.prototype.deleteRule=u,s&&(i.CSSStyleSheet.prototype.replace=s),c&&(i.CSSStyleSheet.prototype.replaceSync=c),Object.entries(p).forEach((function(e){var t=l(e,2),n=t[0],r=t[1];r.prototype.insertRule=f[n].insertRule,r.prototype.deleteRule=f[n].deleteRule}))}))}(e,{win:r}),f=je(e,e.doc),g=function(e,t){var n=e.styleDeclarationCb,r=e.mirror,o=e.ignoreCSSAttributes,i=e.stylesheetManager,a=t.win,s=a.CSSStyleDeclaration.prototype.setProperty;a.CSSStyleDeclaration.prototype.setProperty=new Proxy(s,{apply:Fe((function(e,t,a){var c,u=l(a,3),d=u[0],p=u[1],f=u[2];if(o.has(d))return s.apply(t,[d,p,f]);var h=Ue(null===(c=t.parentRule)||void 0===c?void 0:c.parentStyleSheet,r,i.styleMirror),g=h.id,v=h.styleId;return(g&&-1!==g||v&&-1!==v)&&n({id:g,styleId:v,set:{property:d,value:p,priority:f},index:Ve(t.parentRule)}),e.apply(t,a)}))});var c=a.CSSStyleDeclaration.prototype.removeProperty;return a.CSSStyleDeclaration.prototype.removeProperty=new Proxy(c,{apply:Fe((function(e,t,a){var s,u=l(a,1)[0];if(o.has(u))return c.apply(t,[u]);var d=Ue(null===(s=t.parentRule)||void 0===s?void 0:s.parentStyleSheet,r,i.styleMirror),p=d.id,f=d.styleId;return(p&&-1!==p||f&&-1!==f)&&n({id:p,styleId:f,remove:{property:u},index:Ve(t.parentRule)}),e.apply(t,a)}))}),Fe((function(){a.CSSStyleDeclaration.prototype.setProperty=s,a.CSSStyleDeclaration.prototype.removeProperty=c}))}(e,{win:r}),e.collectFonts&&(v=function(e){var t=e.fontCb,n=e.doc,r=n.defaultView;if(!r)return function(){};var o=[],i=new WeakMap,a=r.FontFace;r.FontFace=function(e,t,n){var r=new a(e,t,n);return i.set(r,{family:e,buffer:"string"!=typeof t,descriptors:n,fontSource:"string"==typeof t?t:JSON.stringify(Array.from(new Uint8Array(t)))}),r};var s=te(n.fonts,"add",(function(e){return function(n){return setTimeout(Fe((function(){var e=i.get(n);e&&(t(e),i.delete(n))})),0),e.apply(this,[n])}}));return o.push((function(){r.FontFace=a})),o.push(s),Fe((function(){o.forEach((function(e){return e()}))}))}(e)));var m,y=function(e){var t=e.doc,n=e.mirror,r=e.blockClass,o=e.blockSelector,i=e.selectionCb,a=!0,s=Fe((function(){var e=t.getSelection();if(!(!e||a&&(null==e?void 0:e.isCollapsed))){a=e.isCollapsed||!1;for(var s=[],c=e.rangeCount||0,u=0;u0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}},{key:"handleMessage",value:function(e){var t=e;if("rrweb"===t.data.type&&t.origin===t.data.origin&&e.source){var n=this.crossOriginIframeMap.get(e.source);if(n){var r=this.transformCrossOriginEvent(n,t.data.event);r&&this.wrappedEmit(r,t.data.isCheckout)}}}},{key:"transformCrossOriginEvent",value:function(e,t){var n,r=this;switch(t.type){case ye.FullSnapshot:this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);var o=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,o),this.patchRootIdOnNode(t.data.node,o),{timestamp:t.timestamp,type:ye.IncrementalSnapshot,data:{source:be.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}};case ye.Meta:case ye.Load:case ye.DomContentLoaded:return!1;case ye.Plugin:return t;case ye.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case ye.IncrementalSnapshot:switch(t.data.source){case be.Mutation:return t.data.adds.forEach((function(t){r.replaceIds(t,e,["parentId","nextId","previousId"]),r.replaceIdOnNode(t.node,e);var n=r.crossOriginIframeRootIdMap.get(e);n&&r.patchRootIdOnNode(t.node,n)})),t.data.removes.forEach((function(t){r.replaceIds(t,e,["parentId","id"])})),t.data.attributes.forEach((function(t){r.replaceIds(t,e,["id"])})),t.data.texts.forEach((function(t){r.replaceIds(t,e,["id"])})),t;case be.Drag:case be.TouchMove:case be.MouseMove:return t.data.positions.forEach((function(t){r.replaceIds(t,e,["id"])})),t;case be.ViewportResize:return!1;case be.MediaInteraction:case be.MouseInteraction:case be.Scroll:case be.CanvasMutation:case be.Input:return this.replaceIds(t.data,e,["id"]),t;case be.StyleSheetRule:case be.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case be.Font:return t;case be.Selection:return t.data.ranges.forEach((function(t){r.replaceIds(t,e,["start","end"])})),t;case be.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),null===(n=t.data.styles)||void 0===n||n.forEach((function(t){r.replaceStyleIds(t,e,["styleId"])})),t}}return!1}},{key:"replace",value:function(e,t,n,r){var o,i=h(r);try{for(i.s();!(o=i.n()).done;){var a=o.value;(Array.isArray(t[a])||"number"==typeof t[a])&&(Array.isArray(t[a])?t[a]=e.getIds(n,t[a]):t[a]=e.getId(n,t[a]))}}catch(e){i.e(e)}finally{i.f()}return t}},{key:"replaceIds",value:function(e,t,n){return this.replace(this.crossOriginIframeMirror,e,t,n)}},{key:"replaceStyleIds",value:function(e,t,n){return this.replace(this.crossOriginIframeStyleMirror,e,t,n)}},{key:"replaceIdOnNode",value:function(e,t){var n=this;this.replaceIds(e,t,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach((function(e){n.replaceIdOnNode(e,t)}))}},{key:"patchRootIdOnNode",value:function(e,t){var n=this;e.type===g.Document||e.rootId||(e.rootId=t),"childNodes"in e&&e.childNodes.forEach((function(e){n.patchRootIdOnNode(e,t)}))}}]),e}(),Je=function(){function e(t){a(this,e),this.shadowDoms=new WeakSet,this.restoreHandlers=[],this.mutationCb=t.mutationCb,this.scrollCb=t.scrollCb,this.bypassOptions=t.bypassOptions,this.mirror=t.mirror,this.init()}return c(e,[{key:"init",value:function(){this.reset(),this.patchAttachShadow(Element,document)}},{key:"addShadowRoot",value:function(e,t){var n=this;if(y(e)&&!this.shadowDoms.has(e)){this.shadowDoms.add(e);var r=Pe(Object.assign(Object.assign({},this.bypassOptions),{doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),e);this.restoreHandlers.push((function(){return r.disconnect()})),this.restoreHandlers.push(Be(Object.assign(Object.assign({},this.bypassOptions),{scrollCb:this.scrollCb,doc:e,mirror:this.mirror}))),setTimeout((function(){e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&n.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,n.mirror.getId(e.host)),n.restoreHandlers.push(je({mirror:n.mirror,stylesheetManager:n.bypassOptions.stylesheetManager},e))}),0)}}},{key:"observeAttachShadow",value:function(e){e.contentWindow&&e.contentDocument&&this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)}},{key:"patchAttachShadow",value:function(e,t){var n=this;this.restoreHandlers.push(te(e.prototype,"attachShadow",(function(e){return function(r){var o=e.call(this,r);return this.shadowRoot&&me(this)&&n.addShadowRoot(this.shadowRoot,t),o}})))}},{key:"reset",value:function(){this.restoreHandlers.forEach((function(e){try{e()}catch(e){}})),this.restoreHandlers=[],this.shadowDoms=new WeakSet}}]),e}();function Xe(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function s(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((r=r.apply(e,t||[])).next())}))}for(var $e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",et="undefined"==typeof Uint8Array?[]:new Uint8Array(256),tt=0;tt<64;tt++)et[$e.charCodeAt(tt)]=tt;var nt=new Map;var rt=function(e,t,n){if(e&&(at(e,t)||"object"===r(e))){var o=function(e,t){var n=nt.get(e);return n||(n=new Map,nt.set(e,n)),n.has(t)||n.set(t,[]),n.get(t)}(n,e.constructor.name),i=o.indexOf(e);return-1===i&&(i=o.length,o.push(e)),i}};function ot(e,t,n){if(e instanceof Array)return e.map((function(e){return ot(e,t,n)}));if(null===e)return e;if(e instanceof Float32Array||e instanceof Float64Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Int8Array||e instanceof Uint8ClampedArray)return{rr_type:e.constructor.name,args:[Object.values(e)]};if(e instanceof ArrayBuffer){var o=e.constructor.name,i=function(e){var t,n=new Uint8Array(e),r=n.length,o="";for(t=0;t>2],o+=$e[(3&n[t])<<4|n[t+1]>>4],o+=$e[(15&n[t+1])<<2|n[t+2]>>6],o+=$e[63&n[t+2]];return r%3==2?o=o.substring(0,o.length-1)+"=":r%3==1&&(o=o.substring(0,o.length-2)+"=="),o}(e);return{rr_type:o,base64:i}}if(e instanceof DataView)return{rr_type:e.constructor.name,args:[ot(e.buffer,t,n),e.byteOffset,e.byteLength]};if(e instanceof HTMLImageElement)return{rr_type:e.constructor.name,src:e.src};if(e instanceof HTMLCanvasElement){return{rr_type:"HTMLImageElement",src:e.toDataURL()}}return e instanceof ImageData?{rr_type:e.constructor.name,args:[ot(e.data,t,n),e.width,e.height]}:at(e,t)||"object"===r(e)?{rr_type:e.constructor.name,index:rt(e,t,n)}:e}var it=function(e,t,n){return e.map((function(e){return ot(e,t,n)}))},at=function(e,t){var n=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter((function(e){return"function"==typeof t[e]}));return Boolean(n.find((function(n){return e instanceof t[n]})))};function st(e,t,n,o){var i=[];try{var a=te(e.HTMLCanvasElement.prototype,"getContext",(function(e){return function(i){for(var a=arguments.length,s=new Array(a>1?a-1:0),c=1;c0&&(r.styles=o),this.adoptedStyleSheetCb(r)}}},{key:"reset",value:function(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}},{key:"trackStylesheetInLinkElement",value:function(e){}}]),e}(),Ct=function(){function e(){a(this,e),this.nodeMap=new WeakMap,this.loop=!0,this.periodicallyClear()}return c(e,[{key:"periodicallyClear",value:function(){var e=this;requestAnimationFrame((function(){e.clear(),e.loop&&e.periodicallyClear()}))}},{key:"inOtherBuffer",value:function(e,t){var n=this.nodeMap.get(e);return n&&Array.from(n).some((function(e){return e!==t}))}},{key:"add",value:function(e,t){this.nodeMap.set(e,(this.nodeMap.get(e)||new Set).add(t))}},{key:"clear",value:function(){this.nodeMap=new WeakMap}},{key:"destroy",value:function(){this.loop=!1}}]),e}();function _t(e){return Object.assign(Object.assign({},e),{timestamp:ne()})}var It=!1,St=new _;function wt(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.emit,n=e.checkoutEveryNms,r=e.checkoutEveryNth,o=e.blockClass,i=void 0===o?"rr-block":o,a=e.blockSelector,s=void 0===a?null:a,c=e.ignoreClass,u=void 0===c?"rr-ignore":c,l=e.ignoreSelector,d=void 0===l?null:l,p=e.maskTextClass,f=void 0===p?"rr-mask":p,g=e.maskTextSelector,v=void 0===g?null:g,m=e.inlineStylesheet,y=void 0===m||m,b=e.maskAllInputs,C=e.maskInputOptions,I=e.slimDOMOptions,S=e.maskInputFn,w=e.maskTextFn,k=e.hooks,x=e.packFn,A=e.sampling,T=void 0===A?{}:A,M=e.dataURLOptions,E=void 0===M?{}:M,N=e.mousemoveWait,O=e.recordDOM,L=void 0===O||O,R=e.recordCanvas,F=void 0!==R&&R,D=e.recordCrossOriginIframes,q=void 0!==D&&D,P=e.recordAfter,H=void 0===P?"DOMContentLoaded"===e.recordAfter?e.recordAfter:"load":P,B=e.userTriggeredOnInput,W=void 0!==B&&B,Z=e.collectFonts,V=void 0!==Z&&Z,U=e.inlineImages,j=void 0!==U&&U,G=e.plugins,K=e.keepIframeSrcFn,Q=void 0===K?function(){return!1}:K,J=e.ignoreCSSAttributes,X=void 0===J?new Set([]):J;Le(e.errorHandler);var $=!q||window.parent===window,ee=!1;if(!$)try{window.parent.document&&(ee=!1)}catch(e){ee=!0}if($&&!t)throw new Error("emit function is required");void 0!==N&&void 0===T.mousemove&&(T.mousemove=N),St.reset();var te,ne=!0===b?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==C?C:{password:!0},ae=!0===I||"all"===I?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===I,headMetaDescKeywords:"all"===I}:I||{};!function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:window;"NodeList"in t&&!t.NodeList.prototype.forEach&&(t.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in t&&!t.DOMTokenList.prototype.forEach&&(t.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=function(){for(var t=arguments.length,n=new Array(t),r=0;r=r,c=n&&e.timestamp-te.timestamp>n;(s||c)&>(!0)}};var ue,le=function(e){ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.Mutation},e)}))},he=function(e){return ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.Scroll},e)}))},ge=function(e){return ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.CanvasMutation},e)}))},ve=new bt({mutationCb:le,adoptedStyleSheetCb:function(e){return ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.AdoptedStyleSheet},e)}))}}),me=new Ye({mirror:St,mutationCb:le,stylesheetManager:ve,recordCrossOriginIframes:q,wrappedEmit:ht}),Ce=h(G||[]);try{for(Ce.s();!(ue=Ce.n()).done;){var _e=ue.value;_e.getMirror&&_e.getMirror({nodeMirror:St,crossOriginIframeMirror:me.crossOriginIframeMirror,crossOriginIframeStyleMirror:me.crossOriginIframeStyleMirror})}}catch(e){Ce.e(e)}finally{Ce.f()}var Ie=new Ct;vt=new yt({recordCanvas:F,mutationCb:ge,win:window,blockClass:i,blockSelector:s,mirror:St,sampling:T.canvas,dataURLOptions:E});var Se=new Je({mutationCb:le,scrollCb:he,bypassOptions:{blockClass:i,blockSelector:s,maskTextClass:f,maskTextSelector:v,inlineStylesheet:y,maskInputOptions:ne,dataURLOptions:E,maskTextFn:w,maskInputFn:S,recordCanvas:F,inlineImages:j,sampling:T,slimDOMOptions:ae,iframeManager:me,stylesheetManager:ve,canvasManager:vt,keepIframeSrcFn:Q,processedNodeManager:Ie},mirror:St});gt=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(L){ht(_t({type:ye.Meta,data:{href:window.location.href,width:ie(),height:oe()}}),e),ve.reset(),Se.init(),De.forEach((function(e){return e.lock()}));var t=function(e,t){var n=t||{},r=n.mirror,o=void 0===r?new _:r,i=n.blockClass,a=void 0===i?"rr-block":i,s=n.blockSelector,c=void 0===s?null:s,u=n.maskTextClass,l=void 0===u?"rr-mask":u,d=n.maskTextSelector,p=void 0===d?null:d,f=n.inlineStylesheet,h=void 0===f||f,g=n.inlineImages,v=void 0!==g&&g,m=n.recordCanvas,y=void 0!==m&&m,b=n.maskAllInputs,C=void 0!==b&&b,I=n.maskTextFn,S=n.maskInputFn,w=n.slimDOM,k=void 0!==w&&w,x=n.dataURLOptions,A=n.preserveWhiteSpace,T=n.onSerialize,M=n.onIframeLoad,E=n.iframeLoadTimeout,N=n.onStylesheetLoad,O=n.stylesheetLoadTimeout,L=n.keepIframeSrcFn;return z(e,{doc:e,mirror:o,blockClass:a,blockSelector:c,maskTextClass:l,maskTextSelector:p,skipChild:!1,inlineStylesheet:h,maskInputOptions:!0===C?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===C?{password:!0}:C,maskTextFn:I,maskInputFn:S,slimDOMOptions:!0===k||"all"===k?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===k,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===k?{}:k,dataURLOptions:x,inlineImages:v,recordCanvas:y,preserveWhiteSpace:A,onSerialize:T,onIframeLoad:M,iframeLoadTimeout:E,onStylesheetLoad:N,stylesheetLoadTimeout:O,keepIframeSrcFn:void 0===L?function(){return!1}:L,newlyAddedElement:!1})}(document,{mirror:St,blockClass:i,blockSelector:s,maskTextClass:f,maskTextSelector:v,inlineStylesheet:y,maskAllInputs:ne,maskTextFn:w,slimDOM:ae,dataURLOptions:E,recordCanvas:F,inlineImages:j,onSerialize:function(e){de(e,St)&&me.addIframe(e),pe(e,St)&&ve.trackLinkElement(e),fe(e)&&Se.addShadowRoot(e.shadowRoot,document)},onIframeLoad:function(e,t){me.attachIframe(e,t),Se.observeAttachShadow(e)},onStylesheetLoad:function(e,t){ve.attachLinkElement(e,t)},keepIframeSrcFn:Q});if(!t)return console.warn("Failed to snapshot the document");ht(_t({type:ye.FullSnapshot,data:{node:t,initialOffset:re(window)}}),e),De.forEach((function(e){return e.unlock()})),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ve.adoptStyleSheets(document.adoptedStyleSheets,St.getId(document))}};try{var we=[],ke=function(e){var t;return Fe(Ge)({mutationCb:le,mousemoveCb:function(e,t){return ht(_t({type:ye.IncrementalSnapshot,data:{source:t,positions:e}}))},mouseInteractionCb:function(e){return ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.MouseInteraction},e)}))},scrollCb:he,viewportResizeCb:function(e){return ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.ViewportResize},e)}))},inputCb:function(e){return ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.Input},e)}))},mediaInteractionCb:function(e){return ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.MediaInteraction},e)}))},styleSheetRuleCb:function(e){return ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.StyleSheetRule},e)}))},styleDeclarationCb:function(e){return ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.StyleDeclaration},e)}))},canvasMutationCb:ge,fontCb:function(e){return ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.Font},e)}))},selectionCb:function(e){ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.Selection},e)}))},customElementCb:function(e){ht(_t({type:ye.IncrementalSnapshot,data:Object.assign({source:be.CustomElement},e)}))},blockClass:i,ignoreClass:u,ignoreSelector:d,maskTextClass:f,maskTextSelector:v,maskInputOptions:ne,inlineStylesheet:y,sampling:T,recordDOM:L,recordCanvas:F,inlineImages:j,userTriggeredOnInput:W,collectFonts:V,doc:e,maskInputFn:S,maskTextFn:w,keepIframeSrcFn:Q,blockSelector:s,slimDOMOptions:ae,dataURLOptions:E,mirror:St,iframeManager:me,stylesheetManager:ve,shadowDomManager:Se,processedNodeManager:Ie,canvasManager:vt,ignoreCSSAttributes:X,plugins:(null===(t=null==G?void 0:G.filter((function(e){return e.observer})))||void 0===t?void 0:t.map((function(e){return{observer:e.observer,options:e.options,callback:function(t){return ht(_t({type:ye.Plugin,data:{plugin:e.name,payload:t}}))}}})))||[]},k)};me.addLoadListener((function(e){try{we.push(ke(e.contentDocument))}catch(e){console.warn(e)}}));var xe=function(){gt(),we.push(ke(document)),It=!0};return"interactive"===document.readyState||"complete"===document.readyState?xe():(we.push(Y("DOMContentLoaded",(function(){ht(_t({type:ye.DomContentLoaded,data:{}})),"DOMContentLoaded"===H&&xe()}))),we.push(Y("load",(function(){ht(_t({type:ye.Load,data:{}})),"load"===H&&xe()}),window))),function(){we.forEach((function(e){return e()})),Ie.destroy(),It=!1,Re()}}catch(e){console.warn(e)}}wt.addCustomEvent=function(e,t){if(!It)throw new Error("please add custom event after start recording");ht(_t({type:ye.Custom,data:{tag:e,payload:t}}))},wt.freezePage=function(){De.forEach((function(e){return e.freeze()}))},wt.takeFullSnapshot=function(e){if(!It)throw new Error("please take full snapshot after start recording");gt(e)},wt.mirror=St;var kt=function(){function e(t){a(this,e),this.fileName=t.fileName||"",this.functionName=t.functionName||"",this.lineNumber=t.lineNumber,this.columnNumber=t.columnNumber}return c(e,[{key:"toString",value:function(){var e=this.lineNumber||"",t=this.columnNumber||"";return this.functionName?"".concat(this.functionName," (").concat(this.fileName,":").concat(e,":").concat(t,")"):"".concat(this.fileName,":").concat(e,":").concat(t)}}]),e}(),xt=/(^|@)\S+:\d+/,At=/^\s*at .*(\S+:\d+|\(native\))/m,Tt=/^(eval@)?(\[native code])?$/,Mt={parse:function(e){return e?void 0!==e.stacktrace||void 0!==e["opera#sourceloc"]?this.parseOpera(e):e.stack&&e.stack.match(At)?this.parseV8OrIE(e):e.stack?this.parseFFOrSafari(e):(console.warn("[console-record-plugin]: Failed to parse error object:",e),[]):[]},extractLocation:function(e){if(-1===e.indexOf(":"))return[e];var t=/(.+?)(?::(\d+))?(?::(\d+))?$/.exec(e.replace(/[()]/g,""));if(!t)throw new Error("Cannot parse given url: ".concat(e));return[t[1],t[2]||void 0,t[3]||void 0]},parseV8OrIE:function(e){return e.stack.split("\n").filter((function(e){return!!e.match(At)}),this).map((function(e){e.indexOf("(eval ")>-1&&(e=e.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(\),.*$)/g,""));var t=e.replace(/^\s+/,"").replace(/\(eval code/g,"("),n=t.match(/ (\((.+):(\d+):(\d+)\)$)/),r=(t=n?t.replace(n[0],""):t).split(/\s+/).slice(1),o=this.extractLocation(n?n[1]:r.pop()),i=r.join(" ")||void 0,a=["eval",""].indexOf(o[0])>-1?void 0:o[0];return new kt({functionName:i,fileName:a,lineNumber:o[1],columnNumber:o[2]})}),this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter((function(e){return!e.match(Tt)}),this).map((function(e){if(e.indexOf(" > eval")>-1&&(e=e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===e.indexOf("@")&&-1===e.indexOf(":"))return new kt({functionName:e});var t=/((.*".+"[^@]*)?[^@]*)(?:@)/,n=e.match(t),r=n&&n[1]?n[1]:void 0,o=this.extractLocation(e.replace(t,""));return new kt({functionName:r,fileName:o[0],lineNumber:o[1],columnNumber:o[2]})}),this)},parseOpera:function(e){return!e.stacktrace||e.message.indexOf("\n")>-1&&e.message.split("\n").length>e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)/i,n=e.message.split("\n"),r=[],o=2,i=n.length;o/,"$2").replace(/\([^)]*\)/g,"")||void 0;return new kt({functionName:r,fileName:n[0],lineNumber:n[1],columnNumber:n[2]})}),this)}};function Et(e){if(!e||!e.outerHTML)return"";for(var t="";e.parentElement;){var n=e.localName;if(!n)break;n=n.toLowerCase();var r=e.parentElement,o=[];if(r.children&&r.children.length>0)for(var i=0;i1&&(n+=":eq(".concat(o.indexOf(e),")")),t=n+(t?">"+t:""),e=r}return t}function Nt(e){return"[object Object]"===Object.prototype.toString.call(e)}function Ot(e,t){if(0===t)return!0;for(var n=0,r=Object.keys(e);n0){var i=r.indexOf(this);~i?r.splice(i+1):r.push(this),~i?o.splice(i,1/0,e):o.push(e),~r.indexOf(t)&&(t=r[0]===t?"[Circular ~]":"[Circular ~."+o.slice(0,r.indexOf(t)).join(".")+"]")}else r.push(t);if(null===t)return t;if(void 0===t)return"undefined";if(function(e){if(Nt(e)&&Object.keys(e).length>n.numOfKeysLimit)return!0;if("function"==typeof e)return!0;if(Nt(e)&&Ot(e,n.depthOfLimit))return!0;return!1}(t))return function(e){var t=e.toString();n.stringLengthLimit&&t.length>n.stringLengthLimit&&(t="".concat(t.slice(0,n.stringLengthLimit),"..."));return t}(t);if("bigint"==typeof t)return t.toString()+"n";if(t instanceof Event){var a={};for(var s in t){var c=t[s];Array.isArray(c)?a[s]=Et(c.length?c[0]:null):a[s]=c}return a}return t instanceof Node?t instanceof HTMLElement?t?t.outerHTML:"":t.nodeName:t instanceof Error?t.stack?t.stack+"\nEnd of stack for Error object":t.name+": "+t.message:t}))}var Rt={level:["assert","clear","count","countReset","debug","dir","dirxml","error","group","groupCollapsed","groupEnd","info","log","table","time","timeEnd","timeLog","trace","warn"],lengthThreshold:1e3,logger:"console"};function Ft(e,t,n){var r,o=n?Object.assign({},Rt,n):Rt,i=o.logger;if(!i)return function(){};r="string"==typeof i?t[i]:i;var a=0,s=!1,c=[];if(o.level.includes("error")){var u=function(t){var n=t.message,r=t.error,i=Mt.parse(r).map((function(e){return e.toString()})),a=[Lt(n,o.stringifyOptions)];e({level:"error",trace:i,payload:a})};t.addEventListener("error",u),c.push((function(){t.removeEventListener("error",u)}));var l=function(t){var n,r;t.reason instanceof Error?(n=t.reason,r=[Lt("Uncaught (in promise) ".concat(n.name,": ").concat(n.message),o.stringifyOptions)]):(n=new Error,r=[Lt("Uncaught (in promise)",o.stringifyOptions),Lt(t.reason,o.stringifyOptions)]);var i=Mt.parse(n).map((function(e){return e.toString()}));e({level:"error",trace:i,payload:r})};t.addEventListener("unhandledrejection",l),c.push((function(){t.removeEventListener("unhandledrejection",l)}))}var d,p=h(o.level);try{for(p.s();!(d=p.n()).done;){var f=d.value;c.push(g(r,f))}}catch(e){p.e(e)}finally{p.f()}return function(){c.forEach((function(e){return e()}))};function g(t,n){var r=this;return t[n]?te(t,n,(function(t){return function(){for(var i=arguments.length,c=new Array(i),u=0;u1?n-1:0),o=1;o1&&void 0!==arguments[1]?arguments[1]:"&",o=[];return un(e,(function(e,r){Ut(e)||Ut(r)||"undefined"===r||(t=encodeURIComponent(function(e){return e instanceof File}(e)?e.name:e.toString()),n=encodeURIComponent(r),o[o.length]=n+"="+t)})),o.join(r)},dn={initiatorTypes:["audio","beacon","body","css","early-hint","embed","fetch","frame","iframe","icon","image","img","input","link","navigation","object","ping","script","track","video","xmlhttprequest"],maskRequestFn:function(e){return e},recordHeaders:!1,recordBody:!1,recordInitialRequests:!1,recordPerformance:!1,performanceEntryTypeToObserve:["first-input","navigation","paint","resource"],payloadSizeLimitBytes:1e6,payloadHostDenyList:[".lr-ingest.io",".ingest.sentry.io"]};function pn(e,t,n){try{if(!(t in e))return function(){};var r=e[t],o=n(r);return Zt(o)&&(o.prototype=o.prototype||{},Object.defineProperties(o,{__posthog_wrapped__:{enumerable:!1,value:!0}})),e[t]=o,function(){e[t]=r}}catch(e){return function(){}}}function fn(e,t){var n,r=function(e){try{return"string"==typeof e?new URL(e).hostname:"url"in e?new URL(e.url).hostname:e.hostname}catch(e){return null}}(e),o={hostname:r,isHostDenied:!1};if(null===(n=t.payloadHostDenyList)||void 0===n||!n.length||null==r||!r.trim().length)return o;var i,a=h(t.payloadHostDenyList);try{for(a.s();!(i=a.n()).done;){var s=i.value;if(r.endsWith(s))return{hostname:r,isHostDenied:!0}}}catch(e){a.e(e)}finally{a.f()}return o}var hn=function(e){return"navigation"===e.entryType},gn=function(e){return"resource"===e.entryType};function vn(e,t){for(var n=e.length-1;n>=0;n-=1)if(t(e[n]))return e[n]}function mn(e,t,n){if(n.recordInitialRequests){var r=t.performance.getEntries().filter((function(e){return hn(e)||gn(e)&&n.initiatorTypes.includes(e.initiatorType)}));e({requests:r.flatMap((function(e){return wn({entry:e,method:void 0,status:void 0,networkRequest:{},isInitial:!0})})),isInitial:!0})}var o=new t.PerformanceObserver((function(t){var r=t.getEntries().filter((function(e){return hn(e)||gn(e)&&n.initiatorTypes.includes(e.initiatorType)&&function(e){return!n.recordBody&&!n.recordHeaders||"xmlhttprequest"!==e.initiatorType&&"fetch"!==e.initiatorType}(e)}));e({requests:r.flatMap((function(e){return wn({entry:e,method:void 0,status:void 0,networkRequest:{}})}))})})),i=PerformanceObserver.supportedEntryTypes.filter((function(e){return n.performanceEntryTypeToObserve.includes(e)}));return o.observe({entryTypes:i}),function(){o.disconnect()}}function yn(e,t){return!!t&&(Yt(t)||t[e])}function bn(e){var t=e.type,n=e.recordBody,r=e.headers;function o(e){var t=Object.keys(r).find((function(e){return"content-type"===e.toLowerCase()})),n=t&&r[t];return e.some((function(e){return null==n?void 0:n.includes(e)}))}if(!n)return!1;if(Yt(n))return!0;if(Wt(n))return o(n);var i=n[t];return Yt(i)?i:o(i)}function Cn(e,t,n,r,o){return _n.apply(this,arguments)}function _n(){return _n=i(n().mark((function e(t,r,o,i,a){var s,c,u,l=arguments;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!((s=l.length>5&&void 0!==l[5]?l[5]:0)>10)){e.next=4;break}return sn.warn("Failed to get performance entry for request",{url:o,initiatorType:r}),e.abrupt("return",null);case 4:if(c=t.performance.getEntriesByName(o),u=vn(c,(function(e){return gn(e)&&e.initiatorType===r&&(Ut(i)||e.startTime>=i)&&(Ut(a)||e.startTime<=a)}))){e.next=10;break}return e.next=9,new Promise((function(e){return setTimeout(e,50*s)}));case 9:return e.abrupt("return",Cn(t,r,o,i,a,s+1));case 10:return e.abrupt("return",u);case 11:case"end":return e.stop()}}),e)}))),_n.apply(this,arguments)}function In(e){var t=e.body,n=e.options,r=e.url;if(Qt(t))return null;var o=fn(r,n),i=o.hostname;if(o.isHostDenied)return i+" is in deny list";if(jt(t))return t;if(Jt(t))return t.textContent;if(Xt(t))return ln(t);if(Vt(t))try{return JSON.stringify(t)}catch(e){return"[SessionReplay] Failed to stringify response object"}return"[SessionReplay] Cannot read body of type "+toString.call(t)}var Sn=function(e){return!Kt(e)&&("navigation"===e.entryType||"resource"===e.entryType)};function wn(e){var n=e.entry,r=e.method,o=e.status,i=e.networkRequest,a=e.isInitial,s=e.start,c=e.end,u=e.url,l=e.initiatorType;s=n?n.startTime:s,c=n?n.responseEnd:c;var d=Math.floor(Date.now()-performance.now()),p=Math.floor(d+(s||0)),f=[t(t({},n?n.toJSON():{name:u}),{},{startTime:Ut(s)?void 0:Math.round(s),endTime:Ut(c)?void 0:Math.round(c),timeOrigin:d,timestamp:p,method:r,initiatorType:n?n.initiatorType:l,status:o,requestHeaders:i.requestHeaders,requestBody:i.requestBody,responseHeaders:i.responseHeaders,responseBody:i.responseBody,isInitial:a})];if(Sn(n)){var g,v=h(n.serverTiming||[]);try{for(v.s();!(g=v.n()).done;){var m=g.value;f.push({timeOrigin:d,timestamp:p,startTime:Math.round(n.startTime),name:m.name,duration:m.duration,entryType:"serverTiming"})}}catch(e){v.e(e)}finally{v.f()}}return f}var kn=["video/","audio/"];function xn(e){var t,n=e.r,r=e.options,o=e.url;if("chunked"===n.headers.get("Transfer-Encoding"))return"Chunked Transfer-Encoding is not supported";var i=null===(t=n.headers.get("Content-Type"))||void 0===t?void 0:t.toLowerCase(),a=kn.some((function(e){return null==i?void 0:i.startsWith(e)}));if(i&&a)return"Content-Type ".concat(i," is not supported");var s=fn(o,r),c=s.hostname;return s.isHostDenied?c+" is in deny list":null}function An(e){return new Promise((function(t,n){var r=setTimeout((function(){return t("[SessionReplay] Timeout while trying to read body")}),500);try{e.clone().text().then((function(e){return t(e)}),(function(e){return n(e)})).finally((function(){return clearTimeout(r)}))}catch(e){clearTimeout(r),t("[SessionReplay] Failed to read body")}}))}function Tn(e){return Mn.apply(this,arguments)}function Mn(){return Mn=i(n().mark((function e(t){var r,o,i,a,s;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t.r,o=t.options,i=t.url,a=fn(i,o),s=a.hostname,!a.isHostDenied){e.next=4;break}return e.abrupt("return",Promise.resolve(s+" is in deny list"));case 4:return e.abrupt("return",An(r));case 5:case"end":return e.stop()}}),e)}))),Mn.apply(this,arguments)}function En(e){return Nn.apply(this,arguments)}function Nn(){return Nn=i(n().mark((function e(t){var r,o,i,a;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t.r,o=t.options,i=t.url,a=xn({r:r,options:o,url:i}),Kt(a)){e.next=4;break}return e.abrupt("return",Promise.resolve(a));case 4:return e.abrupt("return",An(r));case 5:case"end":return e.stop()}}),e)}))),Nn.apply(this,arguments)}var On=null;function Ln(e,r,o){if(!("performance"in r))return function(){};if(On)return sn.warn("Network observer already initialised, doing nothing"),function(){};var a=o?Object.assign({},dn,o):dn,s=function(n){var r=[];n.requests.forEach((function(e){var t=a.maskRequestFn(e);t&&r.push(t)})),r.length>0&&e(t(t({},n),{},{requests:r}))},c=mn(s,r,a),u=function(){},l=function(){};return(a.recordHeaders||a.recordBody)&&(u=function(e,t,n){if(!n.initiatorTypes.includes("xmlhttprequest"))return function(){};var r=yn("request",n.recordHeaders),o=yn("response",n.recordHeaders),i=pn(t.XMLHttpRequest.prototype,"open",(function(i){return function(a,s){var c,u,l=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],d=arguments.length>3?arguments[3]:void 0,p=arguments.length>4?arguments[4]:void 0,f=this,h=new Request(s),g={},v={},m=f.setRequestHeader.bind(f);f.setRequestHeader=function(e,t){return v[e]=t,m(e,t)},r&&(g.requestHeaders=v);var y=f.send.bind(f);f.send=function(e){return bn({type:"request",headers:v,url:s,recordBody:n.recordBody})&&(g.requestBody=In({body:e,options:n,url:s})),c=t.performance.now(),y(e)},f.addEventListener("readystatechange",(function(){if(f.readyState===f.DONE){u=t.performance.now();var r={};f.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach((function(e){var t=e.split(": "),n=t.shift(),o=t.join(": ");n&&(r[n]=o)})),o&&(g.responseHeaders=r),bn({type:"response",headers:r,url:s,recordBody:n.recordBody})&&(g.responseBody=In({body:f.response,options:n,url:s})),Cn(t,"xmlhttprequest",h.url,c,u).then((function(t){var n=wn({entry:t,method:h.method,status:null==f?void 0:f.status,networkRequest:g,start:c,end:u,url:s.toString(),initiatorType:"xmlhttprequest"});e({requests:n})})).catch((function(){}))}})),i.call(f,a,s,l,d,p)}}));return function(){i()}}(s,r,a),l=function(e,t,r){if(!r.initiatorTypes.includes("fetch"))return function(){};var o=yn("request",r.recordHeaders),a=yn("response",r.recordHeaders),s=pn(t,"fetch",(function(s){return function(){var c=i(n().mark((function i(c,u){var l,d,p,f,h,g,v;return n().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(l=new Request(c,u),p={},n.prev=2,g={},l.headers.forEach((function(e,t){g[t]=e})),o&&(p.requestHeaders=g),!bn({type:"request",headers:g,url:c,recordBody:r.recordBody})){n.next=10;break}return n.next=9,Tn({r:l,options:r,url:c});case 9:p.requestBody=n.sent;case 10:return f=t.performance.now(),n.next=13,s(l);case 13:if(d=n.sent,h=t.performance.now(),v={},d.headers.forEach((function(e,t){v[t]=e})),a&&(p.responseHeaders=v),!bn({type:"response",headers:v,url:c,recordBody:r.recordBody})){n.next=22;break}return n.next=21,En({r:d,options:r,url:c});case 21:p.responseBody=n.sent;case 22:return n.abrupt("return",d);case 23:return n.prev=23,Cn(t,"fetch",l.url,f,h).then((function(t){var n,r=wn({entry:t,method:l.method,status:null===(n=d)||void 0===n?void 0:n.status,networkRequest:p,start:f,end:h,url:l.url,initiatorType:"fetch"});e({requests:r})})).catch((function(){})),n.finish(23);case 26:case"end":return n.stop()}}),i,null,[[2,,23,26]])})));return function(e,t){return c.apply(this,arguments)}}()}));return function(){s()}}(s,r,a)),On=function(){c(),u(),l()}}var Rn,Fn,Dn,qn=function(e){return{name:"rrweb/network@1",observer:Ln,options:e}};on.__PosthogExtensions__=on.__PosthogExtensions__||{},on.__PosthogExtensions__.rrwebPlugins={getRecordConsolePlugin:Dt,getRecordNetworkPlugin:qn},on.__PosthogExtensions__.rrweb={record:wt,version:"v2",rrwebVersion:v},on.rrweb={record:wt,version:"v2",rrwebVersion:v},on.rrwebConsoleRecord={getRecordConsolePlugin:Dt},on.getRecordNetworkPlugin=qn,function(e){e.Popover="popover",e.API="api",e.Widget="widget"}(Rn||(Rn={})),function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"}(Fn||(Fn={})),function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"}(Dn||(Dn={}));var Pn,Hn,Bn,Wn,Zn,Vn,Un,jn,Gn={},Kn=[],Qn=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,zn=Array.isArray;function Yn(e,t){for(var n in t)e[n]=t[n];return e}function Jn(e){var t=e.parentNode;t&&t.removeChild(e)}function Xn(e,t,n){var r,o,i,a={};for(i in t)"key"==i?r=t[i]:"ref"==i?o=t[i]:a[i]=t[i];if(arguments.length>2&&(a.children=arguments.length>3?Pn.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===a[i]&&(a[i]=e.defaultProps[i]);return $n(e,a,r,o,null)}function $n(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:null==o?++Bn:o,__i:-1,__u:0};return null==o&&null!=Hn.vnode&&Hn.vnode(i),i}function er(e){return e.children}function tr(e,t){this.props=e,this.context=t}function nr(e,t){if(null==t)return e.__?nr(e.__,e.__i+1):null;for(var n;tt&&Wn.sort(Un));ir.__r=0}function ar(e,t,n,r,o,i,a,s,c,u,l){var d,p,f,h,g,v=r&&r.__k||Kn,m=t.length;for(n.__d=c,function(e,t,n){var r,o,i,a,s,c=t.length,u=n.length,l=u,d=0;for(e.__k=[],r=0;r0?$n(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o)?(o.__=e,o.__b=e.__b+1,s=cr(o,n,a=r+d,l),o.__i=s,i=null,-1!==s&&(l--,(i=n[s])&&(i.__u|=131072)),null==i||null===i.__v?(-1==s&&d--,"function"!=typeof o.type&&(o.__u|=65536)):s!==a&&(s===a+1?d++:s>a?l>c-a?d+=s-a:d--:d=s(null!=c&&0==(131072&c.__u)?1:0))for(;a>=0||s=0){if((c=t[a])&&0==(131072&c.__u)&&o==c.key&&i===c.type)return a;a--}if(s2&&(s.children=arguments.length>3?Pn.call(arguments,2):n),$n(e.type,s,r||e.key,o||e.ref,null)}Pn=Kn.slice,Hn={__e:function(e,t,n,r){for(var o,i,a;t=t.__;)if((o=t.__c)&&!o.__)try{if((i=o.constructor)&&null!=i.getDerivedStateFromError&&(o.setState(i.getDerivedStateFromError(e)),a=o.__d),null!=o.componentDidCatch&&(o.componentDidCatch(e,r||{}),a=o.__d),a)return o.__E=o}catch(t){e=t}throw e}},Bn=0,tr.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=Yn({},this.state),"function"==typeof e&&(e=e(Yn({},n),this.props)),e&&Yn(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),or(this))},tr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),or(this))},tr.prototype.render=er,Wn=[],Vn="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Un=function(e,t){return e.__v.__b-t.__v.__b},ir.__r=0,jn=0;var Cr=$t,_r=rn,Ir=function(e){return'\n .survey-form, .thank-you-message {\n position: fixed;\n margin: 0px;\n bottom: 0px;\n color: black;\n font-weight: normal;\n font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Roboto", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";\n text-align: left;\n max-width: '.concat(parseInt((null==e?void 0:e.maxWidth)||"300"),"px;\n width: 100%;\n z-index: ").concat(parseInt((null==e?void 0:e.zIndex)||"99999"),";\n border: 1.5px solid ").concat((null==e?void 0:e.borderColor)||"#c9c6c6",";\n border-bottom: 0px;\n ").concat({left:"left: 30px;",right:"right: 30px;",center:"\n left: 50%;\n transform: translateX(-50%);\n "}[(null==e?void 0:e.position)||"right"]||"right: 30px;","\n flex-direction: column;\n background: ").concat((null==e?void 0:e.backgroundColor)||"#eeeded",';\n border-top-left-radius: 10px;\n border-top-right-radius: 10px;\n box-shadow: -6px 0 16px -8px rgb(0 0 0 / 8%), -9px 0 28px 0 rgb(0 0 0 / 5%), -12px 0 48px 16px rgb(0 0 0 / 3%);\n }\n \n .survey-box, .thank-you-message-container {\n padding: 20px 25px 10px;\n display: flex;\n flex-direction: column;\n border-radius: 10px;\n }\n\n .thank-you-message {\n text-align: center;\n }\n\n .form-submit[disabled] {\n opacity: 0.6;\n filter: grayscale(50%);\n cursor: not-allowed;\n }\n .survey-form textarea {\n color: #2d2d2d;\n font-size: 14px;\n font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Roboto", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";\n background: white;\n color: black;\n outline: none;\n padding-left: 10px;\n padding-right: 10px;\n padding-top: 10px;\n border-radius: 6px;\n border-color: ').concat((null==e?void 0:e.borderColor)||"#c9c6c6",";\n margin-top: 14px;\n width: 100%;\n box-sizing: border-box;\n }\n .survey-box:has(.survey-question:empty):not(:has(.survey-question-description)) textarea {\n margin-top: 0;\n }\n .form-submit {\n box-sizing: border-box;\n margin: 0;\n font-family: inherit;\n overflow: visible;\n text-transform: none;\n position: relative;\n display: inline-block;\n font-weight: 700;\n white-space: nowrap;\n text-align: center;\n border: 1.5px solid transparent;\n cursor: pointer;\n user-select: none;\n touch-action: manipulation;\n padding: 12px;\n font-size: 14px;\n border-radius: 6px;\n outline: 0;\n background: ").concat((null==e?void 0:e.submitButtonColor)||"black"," !important;\n text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.12);\n box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);\n width: 100%;\n }\n .form-cancel {\n display: flex;\n float: right;\n border: none;\n background: none;\n cursor: pointer;\n }\n .cancel-btn-wrapper {\n position: absolute;\n width: 35px;\n height: 35px;\n border-radius: 100%;\n top: 0;\n right: 0;\n transform: translate(50%, -50%);\n background: white;\n border: 1.5px solid ").concat((null==e?void 0:e.borderColor)||"#c9c6c6",";\n display: flex;\n justify-content: center;\n align-items: center;\n }\n .bolded { font-weight: 600; }\n .buttons {\n display: flex;\n justify-content: center;\n }\n .footer-branding {\n font-size: 11px;\n margin-top: 10px;\n text-align: center;\n display: flex;\n justify-content: center;\n gap: 4px;\n align-items: center;\n font-weight: 500;\n background: ").concat((null==e?void 0:e.backgroundColor)||"#eeeded",";\n text-decoration: none;\n backgroundColor: ").concat((null==e?void 0:e.backgroundColor)||"#eeeded",";\n color: ").concat(wr((null==e?void 0:e.backgroundColor)||"#eeeded"),";\n }\n .survey-question {\n font-weight: 500;\n font-size: 14px;\n background: ").concat((null==e?void 0:e.backgroundColor)||"#eeeded",";\n }\n .question-textarea-wrapper {\n display: flex;\n flex-direction: column;\n }\n .survey-question-description {\n font-size: 13px;\n padding-top: 5px;\n background: ").concat((null==e?void 0:e.backgroundColor)||"#eeeded",";\n }\n .ratings-number {\n font-size: 16px;\n font-weight: 600;\n padding: 8px 0px;\n border: none;\n }\n .ratings-number:hover {\n cursor: pointer;\n }\n .rating-options {\n margin-top: 14px;\n }\n .rating-options-number {\n display: grid;\n border-radius: 6px;\n overflow: hidden;\n border: 1.5px solid ").concat((null==e?void 0:e.borderColor)||"#c9c6c6",";\n }\n .rating-options-number > .ratings-number {\n border-right: 1px solid ").concat((null==e?void 0:e.borderColor)||"#c9c6c6",";\n }\n .rating-options-number > .ratings-number:last-of-type {\n border-right: 0px;\n }\n .rating-options-number .rating-active {\n background: ").concat((null==e?void 0:e.ratingButtonActiveColor)||"black",";\n }\n .rating-options-emoji {\n display: flex;\n justify-content: space-between;\n }\n .ratings-emoji {\n font-size: 16px;\n background-color: transparent;\n border: none;\n padding: 0px;\n }\n .ratings-emoji:hover {\n cursor: pointer;\n }\n .ratings-emoji.rating-active svg {\n fill: ").concat((null==e?void 0:e.ratingButtonActiveColor)||"black",";\n }\n .emoji-svg {\n fill: '#939393';\n }\n .rating-text {\n display: flex;\n flex-direction: row;\n font-size: 11px;\n justify-content: space-between;\n margin-top: 6px;\n background: ").concat((null==e?void 0:e.backgroundColor)||"#eeeded",";\n opacity: .60;\n }\n .multiple-choice-options {\n margin-top: 13px;\n font-size: 14px;\n }\n .survey-box:has(.survey-question:empty):not(:has(.survey-question-description)) .multiple-choice-options {\n margin-top: 0;\n }\n .multiple-choice-options .choice-option {\n display: flex;\n align-items: center;\n gap: 4px;\n font-size: 13px;\n cursor: pointer;\n margin-bottom: 5px;\n position: relative;\n }\n .multiple-choice-options > .choice-option:last-of-type {\n margin-bottom: 0px;\n }\n .multiple-choice-options input {\n cursor: pointer;\n position: absolute;\n opacity: 0;\n }\n .choice-check {\n position: absolute;\n right: 10px;\n background: white;\n }\n .choice-check svg {\n display: none;\n }\n .multiple-choice-options .choice-option:hover .choice-check svg {\n display: inline-block;\n opacity: .25;\n }\n .multiple-choice-options input:checked + label + .choice-check svg {\n display: inline-block;\n opacity: 100% !important;\n }\n .multiple-choice-options input:checked + label {\n font-weight: bold;\n border: 1.5px solid rgba(0,0,0);\n }\n .multiple-choice-options input:checked + label input {\n font-weight: bold;\n }\n .multiple-choice-options label {\n width: 100%;\n cursor: pointer;\n padding: 10px;\n border: 1.5px solid rgba(0,0,0,.25);\n border-radius: 4px;\n background: white;\n }\n .multiple-choice-options .choice-option-open label {\n padding-right: 30px;\n display: flex;\n flex-wrap: wrap;\n gap: 8px;\n max-width: 100%;\n }\n .multiple-choice-options .choice-option-open label span {\n width: 100%;\n }\n .multiple-choice-options .choice-option-open input:disabled + label {\n opacity: 0.6;\n }\n .multiple-choice-options .choice-option-open label input {\n position: relative;\n opacity: 1;\n flex-grow: 1;\n border: 0;\n outline: 0;\n }\n .thank-you-message-body {\n margin-top: 6px;\n font-size: 14px;\n background: ").concat((null==e?void 0:e.backgroundColor)||"#eeeded",";\n }\n .thank-you-message-header {\n margin: 10px 0px 0px;\n background: ").concat((null==e?void 0:e.backgroundColor)||"#eeeded",";\n }\n .thank-you-message-container .form-submit {\n margin-top: 20px;\n margin-bottom: 10px;\n }\n .thank-you-message-countdown {\n margin-left: 6px;\n }\n .bottom-section {\n margin-top: 14px;\n }\n ")};function Sr(e){if("#"===e[0]){var t=e.replace(/^#/,"");return"rgb("+parseInt(t.slice(0,2),16)+","+parseInt(t.slice(2,4),16)+","+parseInt(t.slice(4,6),16)+")"}return"rgb(255, 255, 255)"}function wr(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:xr;"#"===t[0]&&(e=Sr(t)),t.startsWith("rgb")&&(e=t);var n={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4","indianred ":"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"}[t.toLowerCase()];if(n&&(e=Sr(n)),!e)return"black";var r=e.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);if(r){var o=parseInt(r[1]),i=parseInt(r[2]),a=parseInt(r[3]);return Math.sqrt(o*o*.299+i*i*.587+a*a*.114)>127.5?"black":"white"}return"black"}var kr={backgroundColor:"#eeeded",submitButtonColor:"black",submitButtonTextColor:"white",ratingButtonColor:"white",ratingButtonActiveColor:"black",borderColor:"#c9c6c6",placeholder:"Start typing...",whiteLabel:!1,displayThankYouMessage:!0,thankYouMessageHeader:"Thank you for your feedback!",position:"right"},xr="#eeeded",Ar=function(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0,o=arguments.length>2?arguments[2]:void 0;o&&(localStorage.setItem(Lr(r),"true"),o.capture("survey sent",t(t({$survey_name:r.name,$survey_id:r.id,$survey_iteration:r.current_iteration,$survey_iteration_start_date:r.current_iteration_start_date,$survey_questions:r.questions.map((function(e){return e.question})),sessionRecordingUrl:null===(e=o.get_session_replay_url)||void 0===e?void 0:e.call(o)},n),{},{$set:u({},Rr(r,"responded"),!0)})),Cr.dispatchEvent(new Event("PHSurveySent")))},Tr=function(e,t,n){var r;!n&&t&&(t.capture("survey dismissed",{$survey_name:e.name,$survey_id:e.id,$survey_iteration:e.current_iteration,$survey_iteration_start_date:e.current_iteration_start_date,sessionRecordingUrl:null===(r=t.get_session_replay_url)||void 0===r?void 0:r.call(t),$set:u({},Rr(e,"dismissed"),!0)}),localStorage.setItem(Lr(e),"true"),Cr.dispatchEvent(new Event("PHSurveyClosed")))},Mr=function(e){return e.map((function(e){return{sort:Math.floor(10*Math.random()),value:e}})).sort((function(e,t){return e.sort-t.sort})).map((function(e){return e.value}))},Er=function(e,t){return e.length===t.length&&e.every((function(e,n){return e===t[n]}))?t.reverse():t},Nr=function(e){return e.questions.forEach((function(e,t){e.originalQuestionIndex=t})),e.appearance&&e.appearance.shuffleQuestions?Er(e.questions,Mr(e.questions)):e.questions},Or=function(e){var t,n;return!(null===(t=e.conditions)||void 0===t||null===(n=t.events)||void 0===n||!n.repeatedActivation||!function(e){var t,n,r,o,i,a;return null!=(null===(t=e.conditions)||void 0===t||null===(n=t.events)||void 0===n||null===(r=n.values)||void 0===r?void 0:r.length)&&(null===(o=e.conditions)||void 0===o||null===(i=o.events)||void 0===i||null===(a=i.values)||void 0===a?void 0:a.length)>0}(e))},Lr=function(e){var t="seenSurvey_".concat(e.id);return e.current_iteration&&e.current_iteration>0&&(t="seenSurvey_".concat(e.id,"_").concat(e.current_iteration)),t},Rr=function(e,t){var n="$survey_".concat(t,"/").concat(e.id);return e.current_iteration&&e.current_iteration>0&&(n="$survey_".concat(t,"/").concat(e.id,"/").concat(e.current_iteration)),n},Fr=function(e,t){var n={__c:t="__cC"+jn++,__:e,Consumer:function(e,t){return e.children(t)},Provider:function(e){var n,r;return this.getChildContext||(n=[],(r={})[t]=this,this.getChildContext=function(){return r},this.shouldComponentUpdate=function(e){this.props.value!==e.value&&n.some((function(e){e.__e=!0,or(e)}))},this.sub=function(e){n.push(e);var t=e.componentWillUnmount;e.componentWillUnmount=function(){n.splice(n.indexOf(e),1),t&&t.call(e)}}),e.children}};return n.Provider.__=n.Consumer.contextType=n}({isPreviewMode:!1,previewPageIndex:0,handleCloseSurveyPopup:function(){},isPopup:!0}),Dr=function(e){var t=e.component,n=e.children,r=e.renderAsHtml,o=e.style;return br(t,r?{dangerouslySetInnerHTML:{__html:n},style:o}:{children:n,style:o})},qr=rn;var Pr,Hr,Br,Wr,Zr=0,Vr=[],Ur=[],jr=Hn.__b,Gr=Hn.__r,Kr=Hn.diffed,Qr=Hn.__c,zr=Hn.unmount;function Yr(e,t){Hn.__h&&Hn.__h(Hr,e,Zr||t),Zr=0;var n=Hr.__H||(Hr.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:Ur}),n.__[e]}function Jr(e){return Zr=1,function(e,t,n){var r=Yr(Pr++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):co(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=Hr,!Hr.u)){var o=function(e,t,n){if(!r.__c.__H)return!0;var o=r.__c.__H.__.filter((function(e){return e.__c}));if(o.every((function(e){return!e.__N})))return!i||i.call(this,e,t,n);var a=!1;return o.forEach((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(a=!0)}})),!(!a&&r.__c.props===e)&&(!i||i.call(this,e,t,n))};Hr.u=!0;var i=Hr.shouldComponentUpdate,a=Hr.componentWillUpdate;Hr.componentWillUpdate=function(e,t,n){if(this.__e){var r=i;i=void 0,o(e,t,n),i=r}a&&a.call(this,e,t,n)},Hr.shouldComponentUpdate=o}return r.__N||r.__}(co,e)}function Xr(e,t){var n=Yr(Pr++,3);!Hn.__s&&so(n.__H,t)&&(n.__=e,n.i=t,Hr.__H.__h.push(n))}function $r(e){return Zr=5,eo((function(){return{current:e}}),[])}function eo(e,t){var n=Yr(Pr++,7);return so(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}function to(e){var t=Hr.context[e.__c],n=Yr(Pr++,9);return n.c=e,t?(null==n.__&&(n.__=!0,t.sub(Hr)),t.props.value):e.__}function no(){for(var e;e=Vr.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(io),e.__H.__h.forEach(ao),e.__H.__h=[]}catch(t){e.__H.__h=[],Hn.__e(t,e.__v)}}Hn.__b=function(e){Hr=null,jr&&jr(e)},Hn.__r=function(e){Gr&&Gr(e),Pr=0;var t=(Hr=e.__c).__H;t&&(Br===Hr?(t.__h=[],Hr.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=Ur,e.__N=e.i=void 0}))):(t.__h.forEach(io),t.__h.forEach(ao),t.__h=[],Pr=0)),Br=Hr},Hn.diffed=function(e){Kr&&Kr(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==Vr.push(t)&&Wr===Hn.requestAnimationFrame||((Wr=Hn.requestAnimationFrame)||oo)(no)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==Ur&&(e.__=e.__V),e.i=void 0,e.__V=Ur}))),Br=Hr=null},Hn.__c=function(e,t){t.some((function(e){try{e.__h.forEach(io),e.__h=e.__h.filter((function(e){return!e.__||ao(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Hn.__e(n,e.__v)}})),Qr&&Qr(e,t)},Hn.unmount=function(e){zr&&zr(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{io(e)}catch(e){t=e}})),n.__H=void 0,t&&Hn.__e(t,n.__v))};var ro="function"==typeof requestAnimationFrame;function oo(e){var t,n=function(){clearTimeout(r),ro&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);ro&&(t=requestAnimationFrame(n))}function io(e){var t=Hr,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Hr=t}function ao(e){var t=Hr;e.__c=e.__(),Hr=t}function so(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function co(e,t){return"function"==typeof t?t(e):t}var uo=0;function lo(e,t,n,r,o,i){var a,s,c={};for(s in t)"ref"==s?a=t[s]:c[s]=t[s];var u={type:e,props:c,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:--uo,__i:-1,__u:0,__source:o,__self:i};if("function"==typeof e&&(a=e.defaultProps))for(s in a)void 0===c[s]&&(c[s]=a[s]);return Hn.vnode&&Hn.vnode(u),u}var po=lo("svg",{className:"emoji-svg",xmlns:"http://www.w3.org/2000/svg",height:"48",viewBox:"0 -960 960 960",width:"48",children:lo("path",{d:"M626-533q22.5 0 38.25-15.75T680-587q0-22.5-15.75-38.25T626-641q-22.5 0-38.25 15.75T572-587q0 22.5 15.75 38.25T626-533Zm-292 0q22.5 0 38.25-15.75T388-587q0-22.5-15.75-38.25T334-641q-22.5 0-38.25 15.75T280-587q0 22.5 15.75 38.25T334-533Zm146 272q66 0 121.5-35.5T682-393h-52q-23 40-63 61.5T480.5-310q-46.5 0-87-21T331-393h-53q26 61 81 96.5T480-261Zm0 181q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z"})}),fo=lo("svg",{className:"emoji-svg",xmlns:"http://www.w3.org/2000/svg",height:"48",viewBox:"0 -960 960 960",width:"48",children:lo("path",{d:"M626-533q22.5 0 38.25-15.75T680-587q0-22.5-15.75-38.25T626-641q-22.5 0-38.25 15.75T572-587q0 22.5 15.75 38.25T626-533Zm-292 0q22.5 0 38.25-15.75T388-587q0-22.5-15.75-38.25T334-641q-22.5 0-38.25 15.75T280-587q0 22.5 15.75 38.25T334-533Zm20 194h253v-49H354v49ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z"})}),ho=lo("svg",{className:"emoji-svg",xmlns:"http://www.w3.org/2000/svg",height:"48",viewBox:"0 -960 960 960",width:"48",children:lo("path",{d:"M626-533q22.5 0 38.25-15.75T680-587q0-22.5-15.75-38.25T626-641q-22.5 0-38.25 15.75T572-587q0 22.5 15.75 38.25T626-533Zm-292 0q22.5 0 38.25-15.75T388-587q0-22.5-15.75-38.25T334-641q-22.5 0-38.25 15.75T280-587q0 22.5 15.75 38.25T334-533Zm146.174 116Q413-417 358.5-379.5T278-280h53q22-42 62.173-65t87.5-23Q528-368 567.5-344.5T630-280h52q-25-63-79.826-100-54.826-37-122-37ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z"})}),go=lo("svg",{className:"emoji-svg",xmlns:"http://www.w3.org/2000/svg",height:"48",viewBox:"0 -960 960 960",width:"48",children:lo("path",{d:"M480-417q-67 0-121.5 37.5T278-280h404q-25-63-80-100t-122-37Zm-183-72 50-45 45 45 31-36-45-45 45-45-31-36-45 45-50-45-31 36 45 45-45 45 31 36Zm272 0 44-45 51 45 31-36-45-45 45-45-31-36-51 45-44-45-31 36 44 45-44 45 31 36ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142 0 241-99t99-241q0-142-99-241t-241-99q-142 0-241 99t-99 241q0 142 99 241t241 99Z"})}),vo=lo("svg",{className:"emoji-svg",xmlns:"http://www.w3.org/2000/svg",height:"48",viewBox:"0 -960 960 960",width:"48",children:lo("path",{d:"M479.504-261Q537-261 585.5-287q48.5-26 78.5-72.4 6-11.6-.75-22.6-6.75-11-20.25-11H316.918Q303-393 296.5-382t-.5 22.6q30 46.4 78.5 72.4 48.5 26 105.004 26ZM347-578l27 27q7.636 8 17.818 8Q402-543 410-551q8-8 8-18t-8-18l-42-42q-8.8-9-20.9-9-12.1 0-21.1 9l-42 42q-8 7.636-8 17.818Q276-559 284-551q8 8 18 8t18-8l27-27Zm267 0 27 27q7.714 8 18 8t18-8q8-7.636 8-17.818Q685-579 677-587l-42-42q-8.8-9-20.9-9-12.1 0-21.1 9l-42 42q-8 7.714-8 18t8 18q7.636 8 17.818 8Q579-543 587-551l27-27ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z"})}),mo=lo("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:lo("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M0.164752 0.164752C0.384422 -0.0549175 0.740578 -0.0549175 0.960248 0.164752L6 5.20451L11.0398 0.164752C11.2594 -0.0549175 11.6156 -0.0549175 11.8352 0.164752C12.0549 0.384422 12.0549 0.740578 11.8352 0.960248L6.79549 6L11.8352 11.0398C12.0549 11.2594 12.0549 11.6156 11.8352 11.8352C11.6156 12.0549 11.2594 12.0549 11.0398 11.8352L6 6.79549L0.960248 11.8352C0.740578 12.0549 0.384422 12.0549 0.164752 11.8352C-0.0549175 11.6156 -0.0549175 11.2594 0.164752 11.0398L5.20451 6L0.164752 0.960248C-0.0549175 0.740578 -0.0549175 0.384422 0.164752 0.164752Z",fill:"black"})}),yo=lo("svg",{width:"77",height:"14",viewBox:"0 0 77 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[lo("g",{"clip-path":"url(#clip0_2415_6911)",children:[lo("mask",{id:"mask0_2415_6911",style:{maskType:"luminance"},maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"77",height:"14",children:lo("path",{d:"M0.5 0H76.5V14H0.5V0Z",fill:"white"})}),lo("g",{mask:"url(#mask0_2415_6911)",children:[lo("path",{d:"M5.77226 8.02931C5.59388 8.37329 5.08474 8.37329 4.90634 8.02931L4.4797 7.20672C4.41155 7.07535 4.41155 6.9207 4.4797 6.78933L4.90634 5.96669C5.08474 5.62276 5.59388 5.62276 5.77226 5.96669L6.19893 6.78933C6.26709 6.9207 6.26709 7.07535 6.19893 7.20672L5.77226 8.02931ZM5.77226 12.6946C5.59388 13.0386 5.08474 13.0386 4.90634 12.6946L4.4797 11.872C4.41155 11.7406 4.41155 11.586 4.4797 11.4546L4.90634 10.632C5.08474 10.288 5.59388 10.288 5.77226 10.632L6.19893 11.4546C6.26709 11.586 6.26709 11.7406 6.19893 11.872L5.77226 12.6946Z",fill:"#1D4AFF"}),lo("path",{d:"M0.5 10.9238C0.5 10.508 1.02142 10.2998 1.32637 10.5938L3.54508 12.7327C3.85003 13.0267 3.63405 13.5294 3.20279 13.5294H0.984076C0.716728 13.5294 0.5 13.3205 0.5 13.0627V10.9238ZM0.5 8.67083C0.5 8.79459 0.551001 8.91331 0.641783 9.00081L5.19753 13.3927C5.28831 13.4802 5.41144 13.5294 5.53982 13.5294H8.0421C8.47337 13.5294 8.68936 13.0267 8.3844 12.7327L1.32637 5.92856C1.02142 5.63456 0.5 5.84278 0.5 6.25854V8.67083ZM0.5 4.00556C0.5 4.12932 0.551001 4.24802 0.641783 4.33554L10.0368 13.3927C10.1276 13.4802 10.2508 13.5294 10.3791 13.5294H12.8814C13.3127 13.5294 13.5287 13.0267 13.2237 12.7327L1.32637 1.26329C1.02142 0.969312 0.5 1.17752 0.5 1.59327V4.00556ZM5.33931 4.00556C5.33931 4.12932 5.39033 4.24802 5.4811 4.33554L14.1916 12.7327C14.4965 13.0267 15.0179 12.8185 15.0179 12.4028V9.99047C15.0179 9.86671 14.9669 9.74799 14.8762 9.66049L6.16568 1.26329C5.86071 0.969307 5.33931 1.17752 5.33931 1.59327V4.00556ZM11.005 1.26329C10.7 0.969307 10.1786 1.17752 10.1786 1.59327V4.00556C10.1786 4.12932 10.2296 4.24802 10.3204 4.33554L14.1916 8.06748C14.4965 8.36148 15.0179 8.15325 15.0179 7.7375V5.3252C15.0179 5.20144 14.9669 5.08272 14.8762 4.99522L11.005 1.26329Z",fill:"#F9BD2B"}),lo("path",{d:"M21.0852 10.981L16.5288 6.58843C16.2238 6.29443 15.7024 6.50266 15.7024 6.91841V13.0627C15.7024 13.3205 15.9191 13.5294 16.1865 13.5294H23.2446C23.5119 13.5294 23.7287 13.3205 23.7287 13.0627V12.5032C23.7287 12.2455 23.511 12.0396 23.2459 12.0063C22.4323 11.9042 21.6713 11.546 21.0852 10.981ZM18.0252 12.0365C17.5978 12.0365 17.251 11.7021 17.251 11.2901C17.251 10.878 17.5978 10.5436 18.0252 10.5436C18.4527 10.5436 18.7996 10.878 18.7996 11.2901C18.7996 11.7021 18.4527 12.0365 18.0252 12.0365Z",fill:"currentColor"}),lo("path",{d:"M0.5 13.0627C0.5 13.3205 0.716728 13.5294 0.984076 13.5294H3.20279C3.63405 13.5294 3.85003 13.0267 3.54508 12.7327L1.32637 10.5938C1.02142 10.2998 0.5 10.508 0.5 10.9238V13.0627ZM5.33931 5.13191L1.32637 1.26329C1.02142 0.969306 0.5 1.17752 0.5 1.59327V4.00556C0.5 4.12932 0.551001 4.24802 0.641783 4.33554L5.33931 8.86412V5.13191ZM1.32637 5.92855C1.02142 5.63455 0.5 5.84278 0.5 6.25853V8.67083C0.5 8.79459 0.551001 8.91331 0.641783 9.00081L5.33931 13.5294V9.79717L1.32637 5.92855Z",fill:"#1D4AFF"}),lo("path",{d:"M10.1787 5.3252C10.1787 5.20144 10.1277 5.08272 10.0369 4.99522L6.16572 1.26329C5.8608 0.969306 5.33936 1.17752 5.33936 1.59327V4.00556C5.33936 4.12932 5.39037 4.24802 5.48114 4.33554L10.1787 8.86412V5.3252ZM5.33936 13.5294H8.04214C8.47341 13.5294 8.6894 13.0267 8.38443 12.7327L5.33936 9.79717V13.5294ZM5.33936 5.13191V8.67083C5.33936 8.79459 5.39037 8.91331 5.48114 9.00081L10.1787 13.5294V9.99047C10.1787 9.86671 10.1277 9.74803 10.0369 9.66049L5.33936 5.13191Z",fill:"#F54E00"}),lo("path",{d:"M29.375 11.6667H31.3636V8.48772H33.0249C34.8499 8.48772 36.0204 7.4443 36.0204 5.83052C36.0204 4.21681 34.8499 3.17334 33.0249 3.17334H29.375V11.6667ZM31.3636 6.84972V4.81136H32.8236C33.5787 4.81136 34.0318 5.19958 34.0318 5.83052C34.0318 6.4615 33.5787 6.84972 32.8236 6.84972H31.3636ZM39.618 11.7637C41.5563 11.7637 42.9659 10.429 42.9659 8.60905C42.9659 6.78905 41.5563 5.45438 39.618 5.45438C37.6546 5.45438 36.2701 6.78905 36.2701 8.60905C36.2701 10.429 37.6546 11.7637 39.618 11.7637ZM38.1077 8.60905C38.1077 7.63838 38.7118 6.97105 39.618 6.97105C40.5116 6.97105 41.1157 7.63838 41.1157 8.60905C41.1157 9.57972 40.5116 10.2471 39.618 10.2471C38.7118 10.2471 38.1077 9.57972 38.1077 8.60905ZM46.1482 11.7637C47.6333 11.7637 48.6402 10.8658 48.6402 9.81025C48.6402 7.33505 45.2294 8.13585 45.2294 7.16518C45.2294 6.8983 45.5189 6.72843 45.9342 6.72843C46.3622 6.72843 46.8782 6.98318 47.0418 7.54132L48.527 6.94678C48.2375 6.06105 47.1677 5.45438 45.8713 5.45438C44.4743 5.45438 43.6058 6.25518 43.6058 7.21372C43.6058 9.53118 46.9663 8.88812 46.9663 9.84665C46.9663 10.1864 46.6391 10.417 46.1482 10.417C45.4434 10.417 44.9525 9.94376 44.8015 9.3735L43.3164 9.93158C43.6436 10.8537 44.6001 11.7637 46.1482 11.7637ZM53.4241 11.606L53.2982 10.0651C53.0843 10.1743 52.8074 10.2106 52.5808 10.2106C52.1278 10.2106 51.8257 9.89523 51.8257 9.34918V7.03172H53.3612V5.55145H51.8257V3.78001H49.9755V5.55145H48.9687V7.03172H49.9755V9.57972C49.9755 11.06 51.0202 11.7637 52.3921 11.7637C52.7696 11.7637 53.122 11.7031 53.4241 11.606ZM59.8749 3.17334V6.47358H56.376V3.17334H54.3874V11.6667H56.376V8.11158H59.8749V11.6667H61.8761V3.17334H59.8749ZM66.2899 11.7637C68.2281 11.7637 69.6378 10.429 69.6378 8.60905C69.6378 6.78905 68.2281 5.45438 66.2899 5.45438C64.3265 5.45438 62.942 6.78905 62.942 8.60905C62.942 10.429 64.3265 11.7637 66.2899 11.7637ZM64.7796 8.60905C64.7796 7.63838 65.3837 6.97105 66.2899 6.97105C67.1835 6.97105 67.7876 7.63838 67.7876 8.60905C67.7876 9.57972 67.1835 10.2471 66.2899 10.2471C65.3837 10.2471 64.7796 9.57972 64.7796 8.60905ZM73.2088 11.4725C73.901 11.4725 74.5177 11.242 74.845 10.8416V11.424C74.845 12.1034 74.2786 12.5767 73.4102 12.5767C72.7935 12.5767 72.2523 12.2854 72.1642 11.788L70.4776 12.0428C70.7042 13.1955 71.925 13.972 73.4102 13.972C75.361 13.972 76.6574 12.8679 76.6574 11.2298V5.55145H74.8324V6.07318C74.4926 5.69705 73.9136 5.45438 73.171 5.45438C71.409 5.45438 70.3014 6.61918 70.3014 8.46345C70.3014 10.3077 71.409 11.4725 73.2088 11.4725ZM72.1012 8.46345C72.1012 7.55345 72.655 6.97105 73.5109 6.97105C74.3793 6.97105 74.9331 7.55345 74.9331 8.46345C74.9331 9.37345 74.3793 9.95585 73.5109 9.95585C72.655 9.95585 72.1012 9.37345 72.1012 8.46345Z",fill:"currentColor"})]})]}),lo("defs",{children:lo("clipPath",{id:"clip0_2415_6911",children:lo("rect",{width:"76",height:"14",fill:"white",transform:"translate(0.5)"})})})]}),bo=lo("svg",{width:"16",height:"12",viewBox:"0 0 16 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:lo("path",{d:"M5.30769 10.6923L4.77736 11.2226C4.91801 11.3633 5.10878 11.4423 5.30769 11.4423C5.5066 11.4423 5.69737 11.3633 5.83802 11.2226L5.30769 10.6923ZM15.5303 1.53033C15.8232 1.23744 15.8232 0.762563 15.5303 0.46967C15.2374 0.176777 14.7626 0.176777 14.4697 0.46967L15.5303 1.53033ZM1.53033 5.85429C1.23744 5.56139 0.762563 5.56139 0.46967 5.85429C0.176777 6.14718 0.176777 6.62205 0.46967 6.91495L1.53033 5.85429ZM5.83802 11.2226L15.5303 1.53033L14.4697 0.46967L4.77736 10.162L5.83802 11.2226ZM0.46967 6.91495L4.77736 11.2226L5.83802 10.162L1.53033 5.85429L0.46967 6.91495Z",fill:"currentColor"})});function Co(){return lo("a",{href:"https://posthog.com",target:"_blank",rel:"noopener",className:"footer-branding",children:["Survey by ",yo]})}function _o(e){var t=e.text,n=e.submitDisabled,r=e.appearance,o=e.onSubmit,i=e.link,a=to(Fr),s=a.isPreviewMode,c=a.isPopup,u=r.submitButtonTextColor||wr(r.submitButtonColor||kr.submitButtonColor);return lo("div",{className:"bottom-section",children:[lo("div",{className:"buttons",children:lo("button",{className:"form-submit",disabled:n&&!s,type:"button",style:c?{color:u}:{},onClick:function(){s||(i&&(null==$t||$t.open(i)),o())},children:t})}),!r.whiteLabel&&lo(Co,{})]})}function Io(e){var t=e.question,n=e.description,r=e.descriptionContentType,o=e.backgroundColor,i=e.forceDisableHtml;return lo("div",{style:to(Fr).isPopup?{backgroundColor:o||kr.backgroundColor}:{},children:[lo("div",{className:"survey-question",children:t}),n&&Dr({component:Xn("div",{className:"survey-question-description"}),children:n,renderAsHtml:!i&&"text"!==r})]})}function So(e){return lo("div",{className:"cancel-btn-wrapper",children:lo("button",{className:"form-cancel",onClick:e.onClick,disabled:to(Fr).isPreviewMode,children:mo})})}function wo(e){var n=e.header,r=e.description,o=e.contentType,i=e.forceDisableHtml,a=e.appearance,s=e.onClose,c=e.styleOverrides,u=wr(a.backgroundColor||kr.backgroundColor),l=to(Fr).isPopup;return lo(er,{children:lo("div",{className:"thank-you-message",style:t({},c),children:lo("div",{className:"thank-you-message-container",children:[l&&lo(So,{onClick:function(){return s()}}),lo("h3",{className:"thank-you-message-header",style:{color:u},children:n}),r&&Dr({component:Xn("div",{className:"thank-you-message-body"}),children:r,renderAsHtml:!i&&"text"!==o,style:{color:u}}),l&&lo(_o,{text:a.thankYouMessageCloseButtonText||"Close",submitDisabled:!1,appearance:a,onSubmit:function(){return s()}})]})})})}function ko(e){var t,n=$r(null),r=l(Jr(null!==(t=e.defaultTextColor)&&void 0!==t?t:"black"),2),o=r[0],i=r[1];return Xr((function(){if(n.current){var e=function(e){var t=Cr.getComputedStyle(e).backgroundColor;if("rgba(0, 0, 0, 0)"===t)return"black";var n=t.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);if(!n)return"black";var r=parseInt(n[1]),o=parseInt(n[2]),i=parseInt(n[3]);return Math.sqrt(r*r*.299+o*o*.587+i*i*.114)>127.5?"black":"white"}(n.current);i(e)}}),[e.appearance,e.forceUpdate]),{ref:n,textColor:o}}function xo(e){var t=e.question,n=e.forceDisableHtml,r=e.appearance,o=e.onSubmit,i=$r(null),a=l(Jr(""),2),s=a[0],c=a[1];return lo("div",{ref:i,children:[lo(Io,{question:t.question,description:t.description,descriptionContentType:t.descriptionContentType,backgroundColor:r.backgroundColor,forceDisableHtml:n}),lo("textarea",{rows:4,placeholder:null==r?void 0:r.placeholder,onInput:function(e){return c(e.currentTarget.value)}}),lo(_o,{text:t.buttonText||"Submit",submitDisabled:!s&&!t.optional,appearance:r,onSubmit:function(){return o(s)}})]})}function Ao(e){var t=e.question,n=e.forceDisableHtml,r=e.appearance,o=e.onSubmit;return lo(er,{children:[lo(Io,{question:t.question,description:t.description,descriptionContentType:t.descriptionContentType,forceDisableHtml:n}),lo(_o,{text:t.buttonText||"Submit",submitDisabled:!1,link:t.link,appearance:r,onSubmit:function(){return o("link clicked")}})]})}function To(e){var t=e.question,n=e.forceDisableHtml,r=e.displayQuestionIndex,o=e.appearance,i=e.onSubmit,a=t.scale,s=10===t.scale?0:1,c=l(Jr(null),2),u=c[0],d=c[1];return lo(er,{children:[lo(Io,{question:t.question,description:t.description,descriptionContentType:t.descriptionContentType,forceDisableHtml:n,backgroundColor:o.backgroundColor}),lo("div",{className:"rating-section",children:[lo("div",{className:"rating-options",children:["emoji"===t.display&&lo("div",{className:"rating-options-emoji",children:(3===t.scale?No:Oo).map((function(e,t){var n=t+1===u;return lo("button",{className:"ratings-emoji question-".concat(r,"-rating-").concat(t," ").concat(n?"rating-active":null),value:t+1,type:"button",onClick:function(){d(t+1)},style:{fill:n?o.ratingButtonActiveColor:o.ratingButtonColor,borderColor:o.borderColor},children:e},t)}))}),"number"===t.display&&lo("div",{className:"rating-options-number",style:{gridTemplateColumns:"repeat(".concat(a-s+1,", minmax(0, 1fr))")},children:Do(t.scale).map((function(e,t){return lo(Mo,{displayQuestionIndex:r,active:u===e,appearance:o,num:e,setActiveNumber:function(e){d(e)}},t)}))})]}),lo("div",{className:"rating-text",children:[lo("div",{children:t.lowerBoundLabel}),lo("div",{children:t.upperBoundLabel})]})]}),lo(_o,{text:t.buttonText||(null==o?void 0:o.submitButtonText)||"Submit",submitDisabled:Kt(u)&&!t.optional,appearance:o,onSubmit:function(){return i(u)}})]})}function Mo(e){var t=e.num,n=e.active,r=e.displayQuestionIndex,o=e.appearance,i=e.setActiveNumber,a=ko({appearance:o,defaultTextColor:"black",forceUpdate:n}),s=a.textColor;return lo("button",{ref:a.ref,className:"ratings-number question-".concat(r,"-rating-").concat(t," ").concat(n?"rating-active":null),type:"button",onClick:function(){i(t)},style:{color:s,backgroundColor:n?o.ratingButtonActiveColor:o.ratingButtonColor,borderColor:o.borderColor},children:t})}function Eo(e){var t=e.question,n=e.forceDisableHtml,r=e.displayQuestionIndex,o=e.appearance,i=e.onSubmit,a=$r(null),s=eo((function(){return function(e){if(!e.shuffleOptions)return e.choices;var t=e.choices,n="";e.hasOpenChoice&&(n=t.pop());var r=Er(t,Mr(t));return e.hasOpenChoice&&(e.choices.push(n),r.push(n)),r}(t)}),[t]),c=l(Jr(t.type===Fn.MultipleChoice?[]:null),2),u=c[0],p=c[1],f=l(Jr(!1),2),h=f[0],g=f[1],v=l(Jr(""),2),m=v[0],y=v[1],b=t.type===Fn.SingleChoice?"radio":"checkbox";return lo("div",{ref:a,children:[lo(Io,{question:t.question,description:t.description,descriptionContentType:t.descriptionContentType,forceDisableHtml:n,backgroundColor:o.backgroundColor}),lo("div",{className:"multiple-choice-options",children:s.map((function(e,n){var o="choice-option",i=e,a=e;return t.hasOpenChoice&&n===t.choices.length-1&&(o+=" choice-option-open"),lo("div",{className:o,children:[lo("input",{type:b,id:"surveyQuestion".concat(r,"Choice").concat(n),name:"question".concat(r),value:i,disabled:!i,onInput:function(){return t.hasOpenChoice&&n===t.choices.length-1?g(!h):t.type===Fn.SingleChoice?p(i):t.type===Fn.MultipleChoice&&Wt(u)?u.includes(i)?p(u.filter((function(e){return e!==i}))):p([].concat(d(u),[i])):void 0}}),lo("label",{htmlFor:"surveyQuestion".concat(r,"Choice").concat(n),style:{color:"black"},children:t.hasOpenChoice&&n===t.choices.length-1?lo(er,{children:[lo("span",{children:[a,":"]}),lo("input",{type:"text",id:"surveyQuestion".concat(r,"Choice").concat(n,"Open"),name:"question".concat(r),onInput:function(e){var n=e.currentTarget.value;return t.type===Fn.SingleChoice?p(n):t.type===Fn.MultipleChoice&&Wt(u)?y(n):void 0}})]}):a}),lo("span",{className:"choice-check",style:{color:"black"},children:bo})]})}))}),lo(_o,{text:t.buttonText||"Submit",submitDisabled:(Kt(u)||Wt(u)&&!h&&0===u.length||Wt(u)&&h&&!m&&0===u.length&&!t.optional)&&!t.optional,appearance:o,onSubmit:function(){h&&t.type===Fn.MultipleChoice?Wt(u)&&i([].concat(d(u),[m])):i(u)}})]})}var No=[ho,fo,po],Oo=[go,ho,fo,po,vo],Lo=[1,2,3,4,5],Ro=[1,2,3,4,5,6,7],Fo=[0,1,2,3,4,5,6,7,8,9,10];function Do(e){switch(e){case 5:default:return Lo;case 7:return Ro;case 10:return Fo}}var qo=$t,Po=rn,Ho=function(){function e(t){var n=this;a(this,e),u(this,"canShowNextEventBasedSurvey",(function(){var e,t=Po.querySelectorAll("div[class^=PostHogSurvey]");return!(t.length>0)||1===(null===(e=t[t.length-1].shadowRoot)||void 0===e?void 0:e.childElementCount)})),u(this,"handlePopoverSurvey",(function(e){var t,r=null===(t=e.conditions)||void 0===t?void 0:t.seenSurveyWaitPeriodInDays,o=localStorage.getItem("lastSeenSurveyDate");if(r&&o){var i=new Date,a=Math.abs(i.getTime()-new Date(o).getTime());if(Math.ceil(a/864e5)0&&void 0!==arguments[0]&&arguments[0];null===(e=n.posthog)||void 0===e||e.getActiveMatchingSurveys((function(e){var t=e.filter((function(e){return"api"!==e.type}));n.sortSurveysByAppearanceDelay(t).forEach((function(e){if(Kt(n.surveyInFocus)){var t,r,o;if(e.type===Rn.Widget)"tab"===(null===(t=e.appearance)||void 0===t?void 0:t.widgetType)&&0===Po.querySelectorAll(".PostHogWidget".concat(e.id)).length&&n.handleWidget(e),"selector"===(null===(r=e.appearance)||void 0===r?void 0:r.widgetType)&&null!==(o=e.appearance)&&void 0!==o&&o.widgetSelector&&n.handleWidgetSelector(e);e.type===Rn.Popover&&n.canShowNextEventBasedSurvey()&&n.handlePopoverSurvey(e)}}))}),t)})),u(this,"addSurveyToFocus",(function(e){Kt(n.surveyInFocus)||sn.error("Survey ".concat(d(n.surveyInFocus)," already in focus. Cannot add survey ").concat(e,".")),n.surveyInFocus=e})),u(this,"removeSurveyFromFocus",(function(e){n.surveyInFocus!==e&&sn.error("Survey ".concat(e," is not in focus. Cannot remove survey ").concat(e,".")),n.surveyInFocus=null})),this.posthog=t,this.surveyInFocus=null}return c(e,[{key:"sortSurveysByAppearanceDelay",value:function(e){return e.sort((function(e,t){var n,r;return((null===(n=e.appearance)||void 0===n?void 0:n.surveyPopupDelaySeconds)||0)-((null===(r=t.appearance)||void 0===r?void 0:r.surveyPopupDelaySeconds)||0)}))}},{key:"getTestAPI",value:function(){return{addSurveyToFocus:this.addSurveyToFocus,removeSurveyFromFocus:this.removeSurveyFromFocus,surveyInFocus:this.surveyInFocus,canShowNextEventBasedSurvey:this.canShowNextEventBasedSurvey,handleWidget:this.handleWidget,handlePopoverSurvey:this.handlePopoverSurvey,handleWidgetSelector:this.handleWidgetSelector,sortSurveysByAppearanceDelay:this.sortSurveysByAppearanceDelay}}}]),e}();function Bo(e){if(Po&&qo){var t=new Ho(e);return t.callSurveysAndEvaluateDisplayLogic(!0),setInterval((function(){t.callSurveysAndEvaluateDisplayLogic(!1)}),1e3),t}}function Wo(e){var n,r,o,i,a,s,c=e.survey,u=e.forceDisableHtml,d=e.posthog,p=e.style,f=e.previewPageIndex,h=e.removeSurveyFromFocus,g=e.isPopup,v=Number.isInteger(f),m=null!==(n=c.appearance)&&void 0!==n&&n.surveyPopupDelaySeconds?1e3*c.appearance.surveyPopupDelaySeconds:0,y=function(e,t,n,r,o){var i=l(Jr(r||0===n),2),a=i[0],s=i[1],c=l(Jr(!1),2),u=c[0],d=c[1];return Xr((function(){if(!r&&t){var i,a=function(){o(e.id),s(!1)},c=function(){var t,n;null!==(t=e.appearance)&&void 0!==t&&t.displayThankYouMessage?(d(!0),o(e.id),null!==(n=e.appearance)&&void 0!==n&&n.autoDisappear&&setTimeout((function(){s(!1)}),5e3)):(o(e.id),s(!1))},u=function(){var n;s(!0),qo.dispatchEvent(new Event("PHSurveyShown")),t.capture("survey shown",{$survey_name:e.name,$survey_id:e.id,$survey_iteration:e.current_iteration,$survey_iteration_start_date:e.current_iteration_start_date,sessionRecordingUrl:null===(n=t.get_session_replay_url)||void 0===n?void 0:n.call(t)}),localStorage.setItem("lastSeenSurveyDate",(new Date).toISOString())};return qo.addEventListener("PHSurveyClosed",a),qo.addEventListener("PHSurveySent",c),n>0?(i=setTimeout((function(){u()}),n),function(){clearTimeout(i),qo.removeEventListener("PHSurveyClosed",a),qo.removeEventListener("PHSurveySent",c)}):(u(),function(){qo.removeEventListener("PHSurveyClosed",a),qo.removeEventListener("PHSurveySent",c)})}}),[]),{isPopupVisible:a,isSurveySent:u,setIsPopupVisible:s}}(c,d,m,v,h),b=y.isPopupVisible,C=y.isSurveySent,_=y.setIsPopupVisible,I=C||f===c.questions.length,S=null!==(r=p)&&void 0!==r&&r.left&&zt(null===(o=p)||void 0===o?void 0:o.left)?{left:p.left-40}:{};return v&&((p=p||{}).left="unset",p.right="unset",p.transform="unset"),b?lo(Fr.Provider,{value:{isPreviewMode:v,previewPageIndex:f,handleCloseSurveyPopup:function(){return Tr(c,d,v)},isPopup:g||!1},children:I?lo(wo,{header:(null===(i=c.appearance)||void 0===i?void 0:i.thankYouMessageHeader)||"Thank you!",description:(null===(a=c.appearance)||void 0===a?void 0:a.thankYouMessageDescription)||"",forceDisableHtml:!!u,contentType:null===(s=c.appearance)||void 0===s?void 0:s.thankYouMessageDescriptionContentType,appearance:c.appearance||kr,styleOverrides:t(t({},p),S),onClose:function(){return _(!1)}}):lo(Zo,{survey:c,forceDisableHtml:!!u,posthog:d,styleOverrides:p})}):lo(er,{})}function Zo(e){var n,r,o=e.survey,i=e.forceDisableHtml,a=e.posthog,s=e.styleOverrides,c=wr((null===(n=o.appearance)||void 0===n?void 0:n.backgroundColor)||kr.backgroundColor),d=l(Jr({}),2),p=d[0],f=d[1],h=to(Fr),g=h.isPreviewMode,v=h.previewPageIndex,m=h.handleCloseSurveyPopup,y=h.isPopup,b=l(Jr(v||0),2),C=b[0],_=b[1],I=eo((function(){return Nr(o)}),[o]);Xr((function(){_(null!=v?v:0)}),[v]);return lo("form",{className:"survey-form",style:y?t({color:c,borderColor:null===(r=o.appearance)||void 0===r?void 0:r.borderColor},s):{},children:I.map((function(e,n){var r,s=e.originalQuestionIndex;return(g?C===s:C===n)&&lo("div",{className:"survey-box",style:y?{backgroundColor:(null===(r=o.appearance)||void 0===r?void 0:r.backgroundColor)||kr.backgroundColor}:{},children:[y&&lo(So,{onClick:function(){return m()}}),Uo({question:e,forceDisableHtml:i,displayQuestionIndex:n,appearance:o.appearance||kr,onSubmit:function(e){return function(e){var n=e.res,r=e.originalQuestionIndex,i=e.displayQuestionIndex;if(a){var s=0===r?"$survey_response":"$survey_response_".concat(r);if(f(t(t({},p),{},u({},s,n))),a.getNextSurveyStep){var c=a.getNextSurveyStep(o,i,n);c===Dn.End?Ar(t(t({},p),{},u({},s,n)),o,a):_(c)}else i===o.questions.length-1?Ar(t(t({},p),{},u({},s,n)),o,a):_(i+1)}}({res:e,originalQuestionIndex:s,displayQuestionIndex:n})}})]})}))})}function Vo(e){var t,n,r=e.survey,o=e.forceDisableHtml,i=e.posthog,a=e.readOnly,s=e.removeSurveyFromFocus,c=l(Jr(!1),2),u=c[0],d=c[1],p=l(Jr({}),2),f=p[0],h=p[1],g=$r(null);return Xr((function(){var e,t;if(!a&&i){if("tab"===(null===(e=r.appearance)||void 0===e?void 0:e.widgetType)&&g.current){var n,o=g.current.getBoundingClientRect(),s={top:"50%",left:parseInt("".concat(o.right-360)),bottom:"auto",borderRadius:10,borderBottom:"1.5px solid ".concat((null===(n=r.appearance)||void 0===n?void 0:n.borderColor)||"#c9c6c6")};h(s)}if("selector"===(null===(t=r.appearance)||void 0===t?void 0:t.widgetType)){var c=Po.querySelector(r.appearance.widgetSelector||"");null==c||c.addEventListener("click",(function(){d(!u)})),null==c||c.setAttribute("PHWidgetSurveyClickListener","true")}}}),[]),lo(er,{children:["tab"===(null===(t=r.appearance)||void 0===t?void 0:t.widgetType)&&lo("div",{className:"ph-survey-widget-tab",ref:g,onClick:function(){return!a&&d(!u)},style:{color:wr(r.appearance.widgetColor)},children:[lo("div",{className:"ph-survey-widget-tab-icon"}),(null===(n=r.appearance)||void 0===n?void 0:n.widgetLabel)||""]}),u&&lo(Wo,{posthog:i,survey:r,forceDisableHtml:o,style:f,removeSurveyFromFocus:s,isPopup:!0},"feedback-widget-survey")]})}var Uo=function(e){var n,r,o=e.question,i=e.forceDisableHtml,a=e.displayQuestionIndex,s=e.appearance,c=e.onSubmit,l=(u(n={},Fn.Open,xo),u(n,Fn.Link,Ao),u(n,Fn.Rating,To),u(n,Fn.SingleChoice,Eo),u(n,Fn.MultipleChoice,Eo),n),d={question:o,forceDisableHtml:i,appearance:s,onSubmit:c},p=(u(r={},Fn.Open,{}),u(r,Fn.Link,{}),u(r,Fn.Rating,{displayQuestionIndex:a}),u(r,Fn.SingleChoice,{displayQuestionIndex:a}),u(r,Fn.MultipleChoice,{displayQuestionIndex:a}),r),f=l[o.type],h=t(t({},d),p[o.type]);return lo(f,t({},h))};function jo(e){return!Ut(Event)&&Go(e,Event)}function Go(e,t){try{return e instanceof t}catch(e){return!1}}function Ko(e,t){return Object.prototype.toString.call(e)==="[object ".concat(t,"]")}function Qo(e){return Ko(e,"DOMError")}on.__PosthogExtensions__=on.__PosthogExtensions__||{},on.__PosthogExtensions__.canActivateRepeatedly=Or,on.__PosthogExtensions__.generateSurveys=Bo,on.extendPostHogWithSurveys=Bo;var zo=/\(error: (.*)\)/,Yo=50,Jo="?";function Xo(e,t,n,r){var o={filename:e,function:t,in_app:!0};return Ut(n)||(o.lineno=n),Ut(r)||(o.colno=r),o}var $o=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ei=/\((\S*)(?::(\d+))(?::(\d+))\)/,ti=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ni=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ri=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i;var oi,ii=function(){for(var e=arguments.length,n=new Array(e),r=0;r1&&void 0!==arguments[1]?arguments[1]:0,r=[],i=e.split("\n"),a=n;a1024)){var c=zo.test(s)?s.replace(zo,"$1"):s;if(!c.match(/\S*Error: /)){var u,l=h(o);try{for(l.s();!(u=l.n()).done;){var d=(0,u.value)(c);if(d){r.push(d);break}}}catch(e){l.e(e)}finally{l.f()}if(r.length>=Yo)break}}}return function(e){if(!e.length)return[];var n=e.slice(0,Yo);return n.reverse(),n.map((function(e){return t(t({},e),{},{filename:e.filename||n[n.length-1].filename,function:e.function||"?"})}))}(r)}}.apply(void 0,[[30,function(e){var t=$o.exec(e);if(t){if(t[2]&&0===t[2].indexOf("eval")){var n=ei.exec(t[2]);n&&(t[2]=n[1],t[3]=n[2],t[4]=n[3])}var r=l(ai(t[1]||Jo,t[2]),2),o=r[0];return Xo(r[1],o,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}}],[50,function(e){var t=ti.exec(e);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){var n=ni.exec(t[3]);n&&(t[1]=t[1]||"eval",t[3]=n[1],t[4]=n[2],t[5]="")}var r=t[3],o=t[1]||Jo,i=l(ai(o,r),2);return o=i[0],Xo(r=i[1],o,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}}],[40,function(e){var t=ri.exec(e);return t?Xo(t[2],t[1]||Jo,+t[3],t[4]?+t[4]:void 0):void 0}]]),ai=function(e,t){var n=-1!==e.indexOf("safari-extension"),r=-1!==e.indexOf("safari-web-extension");return n||r?[-1!==e.indexOf("@")?e.split("@")[0]:Jo,n?"safari-extension:".concat(t):"safari-web-extension:".concat(t)]:[e,t]};!function(e){e.GZipJS="gzip-js",e.Base64="base64"}(oi||(oi={}));var si=["fatal","error","warning","log","info","debug"],ci=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,ui=/Minified React error #\d+;/i;function li(e){var t=e.stacktrace||e.stack||"",n=function(e){if(e){if(zt(e.framesToPop))return e.framesToPop;if(ui.test(e.message))return 1}return 0}(e);try{return ii(t,n)}catch(e){}return[]}function di(e){var t=li(e);return{$exception_type:e.name,$exception_message:e.message,$exception_stack_trace_raw:JSON.stringify(t),$exception_level:"error"}}function pi(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:40,n=Object.keys(e);if(n.sort(),!n.length)return"[object has no keys]";for(var r=n.length;r>0;r--){var o=n.slice(0,r).join(", ");if(!(o.length>t))return r===n.length||o.length<=t?o:"".concat(o.slice(0,t),"...")}return""}function fi(e){return jt(e)&&!Gt(e)&&si.indexOf(e)>=0}function hi(e){var n=l(e,5),r=n[0],o=n[1],i=n[2],a=n[3],s=n[4],c={};if(Ut(s)&&jt(r)){var u="Error",d=r,p=r.match(ci);p&&(u=p[1],d=p[2]),c={$exception_type:u,$exception_message:d}}var f=s||r;if(Qo(f)||function(e){return Ko(e,"DOMException")}(f)){var h=f;if(function(e){return"stack"in e}(f))c=di(f);else{var g=h.name||(Qo(h)?"DOMError":"DOMException"),v=h.message?"".concat(g,": ").concat(h.message):g;c=function(e){return{$exception_type:"Error",$exception_message:e,$exception_level:"error"}}(v),c.$exception_type=Qo(h)?"DOMError":"DOMException",c.$exception_message=c.$exception_message||v}"code"in h&&(c.$exception_DOMException_code="".concat(h.code))}else if(function(e){return Ko(e,"ErrorEvent")}(f)&&f.error)c=di(f.error);else if(function(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return Go(e,Error)}}(f))c=di(f);else if(function(e){return Ko(e,"Object")}(f)||jo(f)){c=function(e){return{$exception_type:jo(e)?e.constructor.name:"Error",$exception_message:"Non-Error ".concat("exception"," captured with keys: ",pi(e)),$exception_level:fi(e.level)?e.level:"error"}}(f),c.$exception_is_synthetic=!0}else c.$exception_type=c.$exception_type||"Error",c.$exception_message=c.$exception_message||f,c.$exception_is_synthetic=!0;return t(t(t(t({},c),{},{$exception_type:c.$exception_type||"UnknownErrorType",$exception_message:c.$exception_message||"",$exception_level:fi(c.$exception_level)?c.$exception_level:"error"},o?{$exception_source:o}:{}),i?{$exception_lineno:i}:{}),a?{$exception_colno:a}:{})}function gi(e){var n=l(e,1)[0],r=n;try{"reason"in n?r=n.reason:"detail"in n&&"reason"in n.detail&&(r=n.detail.reason)}catch(e){}var o,i={};return(i=Kt(o=r)||!Vt(o)&&!Zt(o)?{$exception_message:"Non-Error promise rejection captured with value: ".concat(String(r))}:hi([r])).$exception_handled=!1,t(t({},i),{},{$exception_type:i.$exception_type="UnhandledRejection",$exception_message:i.$exception_message=i.$exception_message||n.reason||String(r),$exception_level:fi(i.$exception_level)?i.$exception_level:"error"})}var vi={wrapOnError:function(e){var t=$t;t||sn.info("window not available, cannot wrap onerror");var n=t.onerror;return t.onerror=function(){for(var t,r=arguments.length,o=new Array(r),i=0;i2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0,s=new Request(r);return mi(e,s),t.call(this,n,s.url,o,i,a)}}))}};on.__PosthogExtensions__.tracingHeadersPatchFns=yi,on.postHogTracingHeadersPatchFns=yi;var bi,Ci,_i,Ii=-1,Si=function(e){addEventListener("pageshow",(function(t){t.persisted&&(Ii=t.timeStamp,e(t))}),!0)},wi=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart=0?r="back-forward-cache":n&&(document.prerendering||ki()>0?r="prerender":document.wasDiscarded?r="restore":n.type&&(r=n.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},Ai=function(e,t,n){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var r=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return r.observe(Object.assign({type:e,buffered:!0},n||{})),r}}catch(e){}},Ti=function(e,t,n,r){var o,i;return function(a){t.value>=0&&(a||r)&&((i=t.value-(o||0))||void 0===o)&&(o=t.value,t.delta=i,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,n),e(t))}},Mi=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},Ei=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()}))},Ni=function(e){var t=!1;return function(){t||(e(),t=!0)}},Oi=-1,Li=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},Ri=function(e){"hidden"===document.visibilityState&&Oi>-1&&(Oi="visibilitychange"===e.type?e.timeStamp:0,Di())},Fi=function(){addEventListener("visibilitychange",Ri,!0),addEventListener("prerenderingchange",Ri,!0)},Di=function(){removeEventListener("visibilitychange",Ri,!0),removeEventListener("prerenderingchange",Ri,!0)},qi=function(){return Oi<0&&(Oi=Li(),Fi(),Si((function(){setTimeout((function(){Oi=Li(),Fi()}),0)}))),{get firstHiddenTime(){return Oi}}},Pi=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()},Hi=[1800,3e3],Bi=function(e,t){t=t||{},Pi((function(){var n,r=qi(),o=xi("FCP"),i=Ai("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(i.disconnect(),e.startTime0&&e.responseStart(t||100)-1)return n||o;if(n=n?o+">"+n:o,r.id)break;e=r.parentNode}}catch(e){}return n},Qi=-1,zi=function(e,t){var n=Ui(),r="navigate";return Qi>=0?r="back-forward-cache":n&&(document.prerendering||function(){var e=Ui();return e&&e.activationStart||0}()>0?r="prerender":document.wasDiscarded?r="restore":n.type&&(r=n.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},Yi=function(e,t,n){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var r=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return r.observe(Object.assign({type:e,buffered:!0},n||{})),r}}catch(e){}},Ji=function(e,t,n,r){var o,i;return function(a){t.value>=0&&(a||r)&&((i=t.value-(o||0))||void 0===o)&&(o=t.value,t.delta=i,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,n),e(t))}},Xi=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()}))},$i=0,ea=1/0,ta=0,na=function(e){e.forEach((function(e){e.interactionId&&(ea=Math.min(ea,e.interactionId),ta=Math.max(ta,e.interactionId),$i=ta?(ta-ea)/7+1:0)}))},ra=function(){"interactionCount"in performance||bi||(bi=Yi("event",na,{type:"event",buffered:!0,durationThreshold:0}))},oa=[],ia=new Map,aa=0,sa=function(){return(bi?$i:performance.interactionCount||0)-aa},ca=[],ua=function(e){if(ca.forEach((function(t){return t(e)})),e.interactionId||"first-input"===e.entryType){var t=oa[oa.length-1],n=ia.get(e.interactionId);if(n||oa.length<10||e.duration>t.latency){if(n)e.duration>n.latency?(n.entries=[e],n.latency=e.duration):e.duration===n.latency&&e.startTime===n.entries[0].startTime&&n.entries.push(e);else{var r={id:e.interactionId,latency:e.duration,entries:[e]};ia.set(r.id,r),oa.push(r)}oa.sort((function(e,t){return t.latency-e.latency})),oa.length>10&&oa.splice(10).forEach((function(e){return ia.delete(e.id)}))}}},la=function(e){var t=self.requestIdleCallback||self.setTimeout,n=-1;return e=function(e){var t=!1;return function(){t||(e(),t=!0)}}(e),"hidden"===document.visibilityState?e():(n=t(e),Xi(e)),n},da=[200,500],pa=function(e,t){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(t=t||{},function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()}((function(){var n;ra();var r,o=zi("INP"),i=function(e){la((function(){e.forEach(ua);var t,n=(t=Math.min(oa.length-1,Math.floor(sa()/50)),oa[t]);n&&n.latency!==o.value&&(o.value=n.latency,o.entries=n.entries,r())}))},a=Yi("event",i,{durationThreshold:null!==(n=t.durationThreshold)&&void 0!==n?n:40});r=Ji(e,o,da,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),Xi((function(){i(a.takeRecords()),r(!0)})),function(e){addEventListener("pageshow",(function(t){t.persisted&&(Qi=t.timeStamp,e(t))}),!0)}((function(){aa=0,oa.length=0,ia.clear(),o=zi("INP"),r=Ji(e,o,da,t.reportAllChanges)})))})))},fa=[],ha=[],ga=new WeakMap,va=new Map,ma=-1,ya=function(e){fa=fa.concat(e),ba()},ba=function(){ma<0&&(ma=la(Ca))},Ca=function(){va.size>10&&va.forEach((function(e,t){ia.has(t)||va.delete(t)}));var e=oa.map((function(e){return ga.get(e.entries[0])})),t=ha.length-50;ha=ha.filter((function(n,r){return r>=t||e.includes(n)}));for(var n=new Set,r=0;r=0;r--){var o=ha[r];if(Math.abs(n-o.renderTime)<=8){(t=o).startTime=Math.min(e.startTime,t.startTime),t.processingStart=Math.min(e.processingStart,t.processingStart),t.processingEnd=Math.max(e.processingEnd,t.processingEnd),t.entries.push(e);break}}t||(t={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:n,entries:[e]},ha.push(t)),(e.interactionId||"first-input"===e.entryType)&&ga.set(e,t),ba()}));var _a=function(e,t){for(var n,r=[],o=0;n=fa[o];o++)if(!(n.startTime+n.durationt)break;r.push(n)}return r},Ia={onLCP:function(e,t){t=t||{},Pi((function(){var n,r=qi(),o=xi("LCP"),i=function(e){t.reportAllChanges||(e=e.slice(-1)),e.forEach((function(e){e.startTimer.value&&(r.value=o,r.entries=i,n())},s=Ai("layout-shift",a);s&&(n=Ti(e,r,Wi,t.reportAllChanges),Ei((function(){a(s.takeRecords()),n(!0)})),Si((function(){o=0,r=xi("CLS",0),n=Ti(e,r,Wi,t.reportAllChanges),Mi((function(){return n()}))})),setTimeout(n,0))})))},onFCP:Bi,onINP:function(e,t){Ci||(Ci=Yi("long-animation-frame",ya)),pa((function(t){var n=function(e){var t=e.entries[0],n=ga.get(t),r=t.processingStart,o=n.processingEnd,i=n.entries.sort((function(e,t){return e.processingStart-t.processingStart})),a=_a(t.startTime,o),s=e.entries.find((function(e){return e.target})),c=s&&s.target||va.get(t.interactionId),u=[t.startTime+t.duration,o].concat(a.map((function(e){return e.startTime+e.duration}))),l=Math.max.apply(Math,u),d={interactionTarget:Ki(c),interactionTargetElement:c,interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:l,processedEventEntries:i,longAnimationFrameEntries:a,inputDelay:r-t.startTime,processingDuration:o-r,presentationDelay:Math.max(l-o,0),loadState:ji(t.startTime)};return Object.assign(e,{attribution:d})}(t);e(n)}),t)}};on.__PosthogExtensions__=on.__PosthogExtensions__||{},on.__PosthogExtensions__.postHogWebVitalsCallbacks=Ia,on.postHogWebVitalsCallbacks=Ia}(); -+//# sourceMappingURL=all-external-dependencies.js.map -diff --git a/dist/all-external-dependencies.js.map b/dist/all-external-dependencies.js.map -new file mode 100644 -index 0000000000000000000000000000000000000000..4f87e0d4c853ba8cc9834c9e17e977fd634fa02f ---- /dev/null -+++ b/dist/all-external-dependencies.js.map -@@ -0,0 +1 @@ -+{"version":3,"file":"all-external-dependencies.js","sources":["../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/utils.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/types/dist/types.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/mutation.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/error-handler.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observer.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/cross-origin-iframe-mirror.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/iframe-manager.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/shadow-dom-manager.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/ext/tslib/tslib.es6.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/ext/base64-arraybuffer/dist/base64-arraybuffer.es5.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/serialize-args.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/webgl.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/_virtual/_rollup-plugin-web-worker-loader__helper__browser__createBase64WorkerFactory.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/_virtual/image-bitmap-data-url-worker.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/index.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/2d.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/stylesheet-manager.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/record/processed-node-manager.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/plugins/console/record/error-stack-parser.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/plugins/console/record/stringify.js","../node_modules/.pnpm/rrweb@2.0.0-alpha.13_patch_hash=es276qklpcauxli22h726xp7fe/node_modules/rrweb/es/rrweb/packages/rrweb/src/plugins/console/record/index.js","../src/utils/type-utils.ts","../src/utils/globals.ts","../src/utils/logger.ts","../src/utils/index.ts","../src/utils/request-utils.ts","../src/extensions/replay/config.ts","../src/extensions/replay/rrweb-plugins/patch.ts","../src/extensions/replay/external/denylist.ts","../src/entrypoints/recorder.ts","../src/posthog-surveys-types.ts","../node_modules/.pnpm/preact@10.19.3/node_modules/preact/dist/preact.module.js","../src/extensions/surveys/surveys-utils.tsx","../src/extensions/surveys-widget.ts","../node_modules/.pnpm/preact@10.19.3/node_modules/preact/hooks/dist/hooks.module.js","../src/extensions/surveys/icons.tsx","../src/extensions/surveys/components/PostHogLogo.tsx","../src/extensions/surveys/components/BottomSection.tsx","../src/extensions/surveys/components/QuestionHeader.tsx","../src/extensions/surveys/components/ConfirmationMessage.tsx","../src/extensions/surveys/hooks/useContrastingTextColor.ts","../src/extensions/surveys/components/QuestionTypes.tsx","../src/extensions/surveys.tsx","../src/extensions/exception-autocapture/type-checking.ts","../src/entrypoints/surveys.ts","../src/extensions/exception-autocapture/stack-trace.ts","../src/types.ts","../src/extensions/exception-autocapture/error-conversion.ts","../src/entrypoints/exception-autocapture.ts","../src/entrypoints/tracing-headers.ts","../node_modules/.pnpm/web-vitals@4.2.0/node_modules/web-vitals/dist/web-vitals.js","../node_modules/.pnpm/web-vitals@4.2.0/node_modules/web-vitals/dist/web-vitals.attribution.js","../src/entrypoints/web-vitals.ts"],"sourcesContent":["var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n === null || n === void 0 ? void 0 : n.host;\r\n return Boolean((host === null || host === void 0 ? void 0 : host.shadowRoot) === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules).map(stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n var _a;\r\n if (!n)\r\n return -1;\r\n const id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;\r\n return id !== null && id !== void 0 ? id : -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction maskInputValue({ element, maskInputOptions, tagName, type, value, maskInputFn, }) {\r\n let text = value || '';\r\n const actualType = type && toLowerCase(type);\r\n if (maskInputOptions[tagName.toLowerCase()] ||\r\n (actualType && maskInputOptions[actualType])) {\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n else {\r\n text = '*'.repeat(text.length);\r\n }\r\n }\r\n return text;\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isNodeMetaEqual(a, b) {\r\n if (!a || !b || a.type !== b.type)\r\n return false;\r\n if (a.type === NodeType.Document)\r\n return a.compatMode === b.compatMode;\r\n else if (a.type === NodeType.DocumentType)\r\n return (a.name === b.name &&\r\n a.publicId === b.publicId &&\r\n a.systemId === b.systemId);\r\n else if (a.type === NodeType.Comment ||\r\n a.type === NodeType.Text ||\r\n a.type === NodeType.CDATA)\r\n return a.textContent === b.textContent;\r\n else if (a.type === NodeType.Element)\r\n return (a.tagName === b.tagName &&\r\n JSON.stringify(a.attributes) ===\r\n JSON.stringify(b.attributes) &&\r\n a.isSVG === b.isSVG &&\r\n a.needBlock === b.needBlock);\r\n return false;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction extractFileExtension(path, baseURL) {\r\n var _a;\r\n let url;\r\n try {\r\n url = new URL(path, baseURL !== null && baseURL !== void 0 ? baseURL : window.location.href);\r\n }\r\n catch (err) {\r\n return null;\r\n }\r\n const regex = /\\.([0-9a-z]+)(?:$)/i;\r\n const match = url.pathname.match(regex);\r\n return (_a = match === null || match === void 0 ? void 0 : match[1]) !== null && _a !== void 0 ? _a : null;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, value) {\r\n return (((tagName === 'video' || tagName === 'audio') && name === 'autoplay') ||\r\n (tagName === 'video' && name === 'src' && value && value.startsWith('blob:http')));\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector) {\r\n try {\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction classMatchesRegex(node, regex, checkAncestors) {\r\n if (!node)\r\n return false;\r\n if (node.nodeType !== node.ELEMENT_NODE) {\r\n if (!checkAncestors)\r\n return false;\r\n return classMatchesRegex(node.parentNode, regex, checkAncestors);\r\n }\r\n for (let eIndex = node.classList.length; eIndex--;) {\r\n const className = node.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n if (!checkAncestors)\r\n return false;\r\n return classMatchesRegex(node.parentNode, regex, checkAncestors);\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, checkAncestors) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (typeof maskTextClass === 'string') {\r\n if (checkAncestors) {\r\n if (el.closest(`.${maskTextClass}`))\r\n return true;\r\n }\r\n else {\r\n if (el.classList.contains(maskTextClass))\r\n return true;\r\n }\r\n }\r\n else {\r\n if (classMatchesRegex(el, maskTextClass, checkAncestors))\r\n return true;\r\n }\r\n if (maskTextSelector) {\r\n if (checkAncestors) {\r\n if (el.closest(maskTextSelector))\r\n return true;\r\n }\r\n else {\r\n if (el.matches(maskTextSelector))\r\n return true;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, needsMask, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n needsMask,\r\n maskTextFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n var _a;\r\n const { needsMask, maskTextFn, rootId } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n if (!isStyle && !isScript && textContent && needsMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, inlineStylesheet, maskInputOptions = {}, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (!ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const href = n.href\r\n let stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === href;\r\n });\r\n if (!stylesheet && href.includes('.css')) {\r\n const rootDomain = window.location.origin\r\n const stylesheetPath = href.replace(window.location.href, '')\r\n const potentialStylesheetHref = rootDomain + '/' + stylesheetPath\r\n stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === potentialStylesheetHref;\r\n });\r\n }\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') {\r\n const value = n.value;\r\n const checked = n.checked;\r\n if (attributes.type !== 'radio' &&\r\n attributes.type !== 'checkbox' &&\r\n attributes.type !== 'submit' &&\r\n attributes.type !== 'button' &&\r\n value) {\r\n attributes.value = maskInputValue({\r\n element: n,\r\n type: getInputType(n),\r\n tagName,\r\n value,\r\n maskInputOptions,\r\n maskInputFn,\r\n });\r\n }\r\n else if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n const mediaAttributes = attributes;\r\n mediaAttributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n mediaAttributes.rr_mediaCurrentTime = n.currentTime;\r\n mediaAttributes.rr_mediaPlaybackRate = n.playbackRate;\r\n mediaAttributes.rr_mediaMuted = n.muted;\r\n mediaAttributes.rr_mediaLoop = n.loop;\r\n mediaAttributes.rr_mediaVolume = n.volume;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n extractFileExtension(sn.attributes.href) === 'js'))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, maskTextClass, maskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { needsMask } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n if (!needsMask &&\r\n n.childNodes) {\r\n const checkAncestors = needsMask === undefined;\r\n needsMask = needMaskingText(n, maskTextClass, maskTextSelector, checkAncestors);\r\n }\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n needsMask,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n needsMask,\r\n maskTextClass,\r\n maskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'textarea' &&\r\n serializedNode.attributes.value !== undefined) ;\r\n else {\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n needsMask,\r\n maskTextClass,\r\n maskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n typeof serializedNode.attributes.rel === 'string' &&\r\n (serializedNode.attributes.rel === 'stylesheet' ||\r\n (serializedNode.attributes.rel === 'preload' &&\r\n typeof serializedNode.attributes.href === 'string' &&\r\n extractFileExtension(serializedNode.attributes.href) === 'css'))) {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n needsMask,\r\n maskTextClass,\r\n maskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n password: true,\r\n }\r\n : maskAllInputs === false\r\n ? {\r\n password: true,\r\n }\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskTextClass,\r\n maskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\r\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\r\nfunction parse(css, options = {}) {\r\n let lineno = 1;\r\n let column = 1;\r\n function updatePosition(str) {\r\n const lines = str.match(/\\n/g);\r\n if (lines) {\r\n lineno += lines.length;\r\n }\r\n const i = str.lastIndexOf('\\n');\r\n column = i === -1 ? column + str.length : str.length - i;\r\n }\r\n function position() {\r\n const start = { line: lineno, column };\r\n return (node) => {\r\n node.position = new Position(start);\r\n whitespace();\r\n return node;\r\n };\r\n }\r\n class Position {\r\n constructor(start) {\r\n this.start = start;\r\n this.end = { line: lineno, column };\r\n this.source = options.source;\r\n }\r\n }\r\n Position.prototype.content = css;\r\n const errorsList = [];\r\n function error(msg) {\r\n const err = new Error(`${options.source || ''}:${lineno}:${column}: ${msg}`);\r\n err.reason = msg;\r\n err.filename = options.source;\r\n err.line = lineno;\r\n err.column = column;\r\n err.source = css;\r\n if (options.silent) {\r\n errorsList.push(err);\r\n }\r\n else {\r\n throw err;\r\n }\r\n }\r\n function stylesheet() {\r\n const rulesList = rules();\r\n return {\r\n type: 'stylesheet',\r\n stylesheet: {\r\n source: options.source,\r\n rules: rulesList,\r\n parsingErrors: errorsList,\r\n },\r\n };\r\n }\r\n function open() {\r\n return match(/^{\\s*/);\r\n }\r\n function close() {\r\n return match(/^}/);\r\n }\r\n function rules() {\r\n let node;\r\n const rules = [];\r\n whitespace();\r\n comments(rules);\r\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\r\n if (node) {\r\n rules.push(node);\r\n comments(rules);\r\n }\r\n }\r\n return rules;\r\n }\r\n function match(re) {\r\n const m = re.exec(css);\r\n if (!m) {\r\n return;\r\n }\r\n const str = m[0];\r\n updatePosition(str);\r\n css = css.slice(str.length);\r\n return m;\r\n }\r\n function whitespace() {\r\n match(/^\\s*/);\r\n }\r\n function comments(rules = []) {\r\n let c;\r\n while ((c = comment())) {\r\n if (c) {\r\n rules.push(c);\r\n }\r\n c = comment();\r\n }\r\n return rules;\r\n }\r\n function comment() {\r\n const pos = position();\r\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\r\n return;\r\n }\r\n let i = 2;\r\n while ('' !== css.charAt(i) &&\r\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\r\n ++i;\r\n }\r\n i += 2;\r\n if ('' === css.charAt(i - 1)) {\r\n return error('End of comment missing');\r\n }\r\n const str = css.slice(2, i - 2);\r\n column += 2;\r\n updatePosition(str);\r\n css = css.slice(i);\r\n column += 2;\r\n return pos({\r\n type: 'comment',\r\n comment: str,\r\n });\r\n }\r\n function selector() {\r\n whitespace();\r\n while (css[0] == '}') {\r\n error('extra closing bracket');\r\n css = css.slice(1);\r\n whitespace();\r\n }\r\n const m = match(/^((\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'|[^{])+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const cleanedInput = m[0]\r\n .trim()\r\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\r\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\r\n return m.replace(/,/g, '\\u200C');\r\n });\r\n return customSplit(cleanedInput).map((s) => s.replace(/\\u200C/g, ',').trim());\r\n }\r\n function customSplit(input) {\r\n const result = [];\r\n let currentSegment = '';\r\n let depthParentheses = 0;\r\n let depthBrackets = 0;\r\n for (const char of input) {\r\n if (char === '(') {\r\n depthParentheses++;\r\n }\r\n else if (char === ')') {\r\n depthParentheses--;\r\n }\r\n else if (char === '[') {\r\n depthBrackets++;\r\n }\r\n else if (char === ']') {\r\n depthBrackets--;\r\n }\r\n if (char === ',' && depthParentheses === 0 && depthBrackets === 0) {\r\n result.push(currentSegment);\r\n currentSegment = '';\r\n }\r\n else {\r\n currentSegment += char;\r\n }\r\n }\r\n if (currentSegment) {\r\n result.push(currentSegment);\r\n }\r\n return result;\r\n }\r\n function declaration() {\r\n const pos = position();\r\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\r\n if (!propMatch) {\r\n return;\r\n }\r\n const prop = trim(propMatch[0]);\r\n if (!match(/^:\\s*/)) {\r\n return error(`property missing ':'`);\r\n }\r\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\r\n const ret = pos({\r\n type: 'declaration',\r\n property: prop.replace(commentre, ''),\r\n value: val ? trim(val[0]).replace(commentre, '') : '',\r\n });\r\n match(/^[;\\s]*/);\r\n return ret;\r\n }\r\n function declarations() {\r\n const decls = [];\r\n if (!open()) {\r\n return error(`missing '{'`);\r\n }\r\n comments(decls);\r\n let decl;\r\n while ((decl = declaration())) {\r\n if (decl !== false) {\r\n decls.push(decl);\r\n comments(decls);\r\n }\r\n decl = declaration();\r\n }\r\n if (!close()) {\r\n return error(`missing '}'`);\r\n }\r\n return decls;\r\n }\r\n function keyframe() {\r\n let m;\r\n const vals = [];\r\n const pos = position();\r\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\r\n vals.push(m[1]);\r\n match(/^,\\s*/);\r\n }\r\n if (!vals.length) {\r\n return;\r\n }\r\n return pos({\r\n type: 'keyframe',\r\n values: vals,\r\n declarations: declarations(),\r\n });\r\n }\r\n function atkeyframes() {\r\n const pos = position();\r\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = m[1];\r\n m = match(/^([-\\w]+)\\s*/);\r\n if (!m) {\r\n return error('@keyframes missing name');\r\n }\r\n const name = m[1];\r\n if (!open()) {\r\n return error(`@keyframes missing '{'`);\r\n }\r\n let frame;\r\n let frames = comments();\r\n while ((frame = keyframe())) {\r\n frames.push(frame);\r\n frames = frames.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@keyframes missing '}'`);\r\n }\r\n return pos({\r\n type: 'keyframes',\r\n name,\r\n vendor,\r\n keyframes: frames,\r\n });\r\n }\r\n function atsupports() {\r\n const pos = position();\r\n const m = match(/^@supports *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const supports = trim(m[1]);\r\n if (!open()) {\r\n return error(`@supports missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@supports missing '}'`);\r\n }\r\n return pos({\r\n type: 'supports',\r\n supports,\r\n rules: style,\r\n });\r\n }\r\n function athost() {\r\n const pos = position();\r\n const m = match(/^@host\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@host missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@host missing '}'`);\r\n }\r\n return pos({\r\n type: 'host',\r\n rules: style,\r\n });\r\n }\r\n function atmedia() {\r\n const pos = position();\r\n const m = match(/^@media *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const media = trim(m[1]);\r\n if (!open()) {\r\n return error(`@media missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@media missing '}'`);\r\n }\r\n return pos({\r\n type: 'media',\r\n media,\r\n rules: style,\r\n });\r\n }\r\n function atcustommedia() {\r\n const pos = position();\r\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\r\n if (!m) {\r\n return;\r\n }\r\n return pos({\r\n type: 'custom-media',\r\n name: trim(m[1]),\r\n media: trim(m[2]),\r\n });\r\n }\r\n function atpage() {\r\n const pos = position();\r\n const m = match(/^@page */);\r\n if (!m) {\r\n return;\r\n }\r\n const sel = selector() || [];\r\n if (!open()) {\r\n return error(`@page missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@page missing '}'`);\r\n }\r\n return pos({\r\n type: 'page',\r\n selectors: sel,\r\n declarations: decls,\r\n });\r\n }\r\n function atdocument() {\r\n const pos = position();\r\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = trim(m[1]);\r\n const doc = trim(m[2]);\r\n if (!open()) {\r\n return error(`@document missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@document missing '}'`);\r\n }\r\n return pos({\r\n type: 'document',\r\n document: doc,\r\n vendor,\r\n rules: style,\r\n });\r\n }\r\n function atfontface() {\r\n const pos = position();\r\n const m = match(/^@font-face\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@font-face missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@font-face missing '}'`);\r\n }\r\n return pos({\r\n type: 'font-face',\r\n declarations: decls,\r\n });\r\n }\r\n const atimport = _compileAtrule('import');\r\n const atcharset = _compileAtrule('charset');\r\n const atnamespace = _compileAtrule('namespace');\r\n function _compileAtrule(name) {\r\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\r\n return () => {\r\n const pos = position();\r\n const m = match(re);\r\n if (!m) {\r\n return;\r\n }\r\n const ret = { type: name };\r\n ret[name] = m[1].trim();\r\n return pos(ret);\r\n };\r\n }\r\n function atrule() {\r\n if (css[0] !== '@') {\r\n return;\r\n }\r\n return (atkeyframes() ||\r\n atmedia() ||\r\n atcustommedia() ||\r\n atsupports() ||\r\n atimport() ||\r\n atcharset() ||\r\n atnamespace() ||\r\n atdocument() ||\r\n atpage() ||\r\n athost() ||\r\n atfontface());\r\n }\r\n function rule() {\r\n const pos = position();\r\n const sel = selector();\r\n if (!sel) {\r\n return error('selector missing');\r\n }\r\n comments();\r\n return pos({\r\n type: 'rule',\r\n selectors: sel,\r\n declarations: declarations(),\r\n });\r\n }\r\n return addParent(stylesheet());\r\n}\r\nfunction trim(str) {\r\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\r\n}\r\nfunction addParent(obj, parent) {\r\n const isNode = obj && typeof obj.type === 'string';\r\n const childParent = isNode ? obj : parent;\r\n for (const k of Object.keys(obj)) {\r\n const value = obj[k];\r\n if (Array.isArray(value)) {\r\n value.forEach((v) => {\r\n addParent(v, childParent);\r\n });\r\n }\r\n else if (value && typeof value === 'object') {\r\n addParent(value, childParent);\r\n }\r\n }\r\n if (isNode) {\r\n Object.defineProperty(obj, 'parent', {\r\n configurable: true,\r\n writable: true,\r\n enumerable: false,\r\n value: parent || null,\r\n });\r\n }\r\n return obj;\r\n}\n\nconst tagMap = {\r\n script: 'noscript',\r\n altglyph: 'altGlyph',\r\n altglyphdef: 'altGlyphDef',\r\n altglyphitem: 'altGlyphItem',\r\n animatecolor: 'animateColor',\r\n animatemotion: 'animateMotion',\r\n animatetransform: 'animateTransform',\r\n clippath: 'clipPath',\r\n feblend: 'feBlend',\r\n fecolormatrix: 'feColorMatrix',\r\n fecomponenttransfer: 'feComponentTransfer',\r\n fecomposite: 'feComposite',\r\n feconvolvematrix: 'feConvolveMatrix',\r\n fediffuselighting: 'feDiffuseLighting',\r\n fedisplacementmap: 'feDisplacementMap',\r\n fedistantlight: 'feDistantLight',\r\n fedropshadow: 'feDropShadow',\r\n feflood: 'feFlood',\r\n fefunca: 'feFuncA',\r\n fefuncb: 'feFuncB',\r\n fefuncg: 'feFuncG',\r\n fefuncr: 'feFuncR',\r\n fegaussianblur: 'feGaussianBlur',\r\n feimage: 'feImage',\r\n femerge: 'feMerge',\r\n femergenode: 'feMergeNode',\r\n femorphology: 'feMorphology',\r\n feoffset: 'feOffset',\r\n fepointlight: 'fePointLight',\r\n fespecularlighting: 'feSpecularLighting',\r\n fespotlight: 'feSpotLight',\r\n fetile: 'feTile',\r\n feturbulence: 'feTurbulence',\r\n foreignobject: 'foreignObject',\r\n glyphref: 'glyphRef',\r\n lineargradient: 'linearGradient',\r\n radialgradient: 'radialGradient',\r\n};\r\nfunction getTagName(n) {\r\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\r\n if (tagName === 'link' && n.attributes._cssText) {\r\n tagName = 'style';\r\n }\r\n return tagName;\r\n}\r\nfunction escapeRegExp(str) {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\nconst MEDIA_SELECTOR = /(max|min)-device-(width|height)/;\r\nconst MEDIA_SELECTOR_GLOBAL = new RegExp(MEDIA_SELECTOR.source, 'g');\r\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\r\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\r\nfunction adaptCssForReplay(cssText, cache) {\r\n const cachedStyle = cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.get(cssText);\r\n if (cachedStyle)\r\n return cachedStyle;\r\n const ast = parse(cssText, {\r\n silent: true,\r\n });\r\n if (!ast.stylesheet) {\r\n return cssText;\r\n }\r\n const selectors = [];\r\n const medias = [];\r\n function getSelectors(rule) {\r\n if ('selectors' in rule && rule.selectors) {\r\n rule.selectors.forEach((selector) => {\r\n if (HOVER_SELECTOR.test(selector)) {\r\n selectors.push(selector);\r\n }\r\n });\r\n }\r\n if ('media' in rule && rule.media && MEDIA_SELECTOR.test(rule.media)) {\r\n medias.push(rule.media);\r\n }\r\n if ('rules' in rule && rule.rules) {\r\n rule.rules.forEach(getSelectors);\r\n }\r\n }\r\n getSelectors(ast.stylesheet);\r\n let result = cssText;\r\n if (selectors.length > 0) {\r\n const selectorMatcher = new RegExp(selectors\r\n .filter((selector, index) => selectors.indexOf(selector) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((selector) => {\r\n return escapeRegExp(selector);\r\n })\r\n .join('|'), 'g');\r\n result = result.replace(selectorMatcher, (selector) => {\r\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\r\n return `${selector}, ${newSelector}`;\r\n });\r\n }\r\n if (medias.length > 0) {\r\n const mediaMatcher = new RegExp(medias\r\n .filter((media, index) => medias.indexOf(media) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((media) => {\r\n return escapeRegExp(media);\r\n })\r\n .join('|'), 'g');\r\n result = result.replace(mediaMatcher, (media) => {\r\n return media.replace(MEDIA_SELECTOR_GLOBAL, '$1-$2');\r\n });\r\n }\r\n cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.set(cssText, result);\r\n return result;\r\n}\r\nfunction createCache() {\r\n const stylesWithHoverClass = new Map();\r\n return {\r\n stylesWithHoverClass,\r\n };\r\n}\r\nfunction buildNode(n, options) {\r\n var _a;\r\n const { doc, hackCss, cache } = options;\r\n switch (n.type) {\r\n case NodeType.Document:\r\n return doc.implementation.createDocument(null, '', null);\r\n case NodeType.DocumentType:\r\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\r\n case NodeType.Element: {\r\n const tagName = getTagName(n);\r\n let node;\r\n if (n.isSVG) {\r\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\r\n }\r\n else {\r\n if (n.isCustom &&\r\n ((_a = doc.defaultView) === null || _a === void 0 ? void 0 : _a.customElements) &&\r\n !doc.defaultView.customElements.get(n.tagName))\r\n doc.defaultView.customElements.define(n.tagName, class extends doc.defaultView.HTMLElement {\r\n });\r\n node = doc.createElement(tagName);\r\n }\r\n const specialAttributes = {};\r\n for (const name in n.attributes) {\r\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\r\n continue;\r\n }\r\n let value = n.attributes[name];\r\n if (tagName === 'option' &&\r\n name === 'selected' &&\r\n value === false) {\r\n continue;\r\n }\r\n if (value === null) {\r\n continue;\r\n }\r\n if (value === true)\r\n value = '';\r\n if (name.startsWith('rr_')) {\r\n specialAttributes[name] = value;\r\n continue;\r\n }\r\n const isTextarea = tagName === 'textarea' && name === 'value';\r\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\r\n if (isRemoteOrDynamicCss && hackCss && typeof value === 'string') {\r\n value = adaptCssForReplay(value, cache);\r\n }\r\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === 'string') {\r\n node.appendChild(doc.createTextNode(value));\r\n n.childNodes = [];\r\n continue;\r\n }\r\n try {\r\n if (n.isSVG && name === 'xlink:href') {\r\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value.toString());\r\n }\r\n else if (name === 'onload' ||\r\n name === 'onclick' ||\r\n name.substring(0, 7) === 'onmouse') {\r\n node.setAttribute('_' + name, value.toString());\r\n }\r\n else if (tagName === 'meta' &&\r\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\r\n name === 'content') {\r\n node.setAttribute('csp-content', value.toString());\r\n continue;\r\n }\r\n else if (tagName === 'link' &&\r\n (n.attributes.rel === 'preload' ||\r\n n.attributes.rel === 'modulepreload') &&\r\n n.attributes.as === 'script') {\r\n }\r\n else if (tagName === 'link' &&\r\n n.attributes.rel === 'prefetch' &&\r\n typeof n.attributes.href === 'string' &&\r\n n.attributes.href.endsWith('.js')) {\r\n }\r\n else if (tagName === 'img' &&\r\n n.attributes.srcset &&\r\n n.attributes.rr_dataURL) {\r\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\r\n }\r\n else {\r\n node.setAttribute(name, value.toString());\r\n }\r\n }\r\n catch (error) {\r\n }\r\n }\r\n for (const name in specialAttributes) {\r\n const value = specialAttributes[name];\r\n if (tagName === 'canvas' && name === 'rr_dataURL') {\r\n const image = document.createElement('img');\r\n image.onload = () => {\r\n const ctx = node.getContext('2d');\r\n if (ctx) {\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n }\r\n };\r\n image.src = value.toString();\r\n if (node.RRNodeType)\r\n node.rr_dataURL = value.toString();\r\n }\r\n else if (tagName === 'img' && name === 'rr_dataURL') {\r\n const image = node;\r\n if (!image.currentSrc.startsWith('data:')) {\r\n image.setAttribute('rrweb-original-src', n.attributes.src);\r\n image.src = value.toString();\r\n }\r\n }\r\n if (name === 'rr_width') {\r\n node.style.width = value.toString();\r\n }\r\n else if (name === 'rr_height') {\r\n node.style.height = value.toString();\r\n }\r\n else if (name === 'rr_mediaCurrentTime' &&\r\n typeof value === 'number') {\r\n node.currentTime = value;\r\n }\r\n else if (name === 'rr_mediaState') {\r\n switch (value) {\r\n case 'played':\r\n node\r\n .play()\r\n .catch((e) => console.warn('media playback error', e));\r\n break;\r\n case 'paused':\r\n node.pause();\r\n break;\r\n }\r\n }\r\n else if (name === 'rr_mediaPlaybackRate' &&\r\n typeof value === 'number') {\r\n node.playbackRate = value;\r\n }\r\n else if (name === 'rr_mediaMuted' && typeof value === 'boolean') {\r\n node.muted = value;\r\n }\r\n else if (name === 'rr_mediaLoop' && typeof value === 'boolean') {\r\n node.loop = value;\r\n }\r\n else if (name === 'rr_mediaVolume' && typeof value === 'number') {\r\n node.volume = value;\r\n }\r\n }\r\n if (n.isShadowHost) {\r\n if (!node.shadowRoot) {\r\n node.attachShadow({ mode: 'open' });\r\n }\r\n else {\r\n while (node.shadowRoot.firstChild) {\r\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n case NodeType.Text:\r\n return doc.createTextNode(n.isStyle && hackCss\r\n ? adaptCssForReplay(n.textContent, cache)\r\n : n.textContent);\r\n case NodeType.CDATA:\r\n return doc.createCDATASection(n.textContent);\r\n case NodeType.Comment:\r\n return doc.createComment(n.textContent);\r\n default:\r\n return null;\r\n }\r\n}\r\nfunction buildNodeWithSN(n, options) {\r\n const { doc, mirror, skipChild = false, hackCss = true, afterAppend, cache, } = options;\r\n if (mirror.has(n.id)) {\r\n const nodeInMirror = mirror.getNode(n.id);\r\n const meta = mirror.getMeta(nodeInMirror);\r\n if (isNodeMetaEqual(meta, n))\r\n return mirror.getNode(n.id);\r\n }\r\n let node = buildNode(n, { doc, hackCss, cache });\r\n if (!node) {\r\n return null;\r\n }\r\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\r\n mirror.replace(n.rootId, doc);\r\n }\r\n if (n.type === NodeType.Document) {\r\n doc.close();\r\n doc.open();\r\n if (n.compatMode === 'BackCompat' &&\r\n n.childNodes &&\r\n n.childNodes[0].type !== NodeType.DocumentType) {\r\n if (n.childNodes[0].type === NodeType.Element &&\r\n 'xmlns' in n.childNodes[0].attributes &&\r\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\r\n doc.write('');\r\n }\r\n else {\r\n doc.write('');\r\n }\r\n }\r\n node = doc;\r\n }\r\n mirror.add(node, n);\r\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\r\n !skipChild) {\r\n for (const childN of n.childNodes) {\r\n const childNode = buildNodeWithSN(childN, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n if (!childNode) {\r\n console.warn('Failed to rebuild', childN);\r\n continue;\r\n }\r\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\r\n node.shadowRoot.appendChild(childNode);\r\n }\r\n else if (n.type === NodeType.Document &&\r\n childN.type == NodeType.Element) {\r\n const htmlElement = childNode;\r\n let body = null;\r\n htmlElement.childNodes.forEach((child) => {\r\n if (child.nodeName === 'BODY')\r\n body = child;\r\n });\r\n if (body) {\r\n htmlElement.removeChild(body);\r\n node.appendChild(childNode);\r\n htmlElement.appendChild(body);\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n if (afterAppend) {\r\n afterAppend(childNode, childN.id);\r\n }\r\n }\r\n }\r\n return node;\r\n}\r\nfunction visit(mirror, onVisit) {\r\n function walk(node) {\r\n onVisit(node);\r\n }\r\n for (const id of mirror.getIds()) {\r\n if (mirror.has(id)) {\r\n walk(mirror.getNode(id));\r\n }\r\n }\r\n}\r\nfunction handleScroll(node, mirror) {\r\n const n = mirror.getMeta(node);\r\n if ((n === null || n === void 0 ? void 0 : n.type) !== NodeType.Element) {\r\n return;\r\n }\r\n const el = node;\r\n for (const name in n.attributes) {\r\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) &&\r\n name.startsWith('rr_'))) {\r\n continue;\r\n }\r\n const value = n.attributes[name];\r\n if (name === 'rr_scrollLeft') {\r\n el.scrollLeft = value;\r\n }\r\n if (name === 'rr_scrollTop') {\r\n el.scrollTop = value;\r\n }\r\n }\r\n}\r\nfunction rebuild(n, options) {\r\n const { doc, onVisit, hackCss = true, afterAppend, cache, mirror = new Mirror(), } = options;\r\n const node = buildNodeWithSN(n, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n visit(mirror, (visitedNode) => {\r\n if (onVisit) {\r\n onVisit(visitedNode);\r\n }\r\n handleScroll(visitedNode, mirror);\r\n });\r\n return node;\r\n}\n\nexport { IGNORED_NODE, Mirror, NodeType, adaptCssForReplay, buildNodeWithSN, classMatchesRegex, createCache, createMirror, escapeImportStatement, extractFileExtension, fixSafariColons, genId, getInputType, ignoreAttribute, is2DCanvasBlank, isCSSImportRule, isCSSStyleRule, isElement, isNativeShadowDom, isNodeMetaEqual, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, snapshot, stringifyRule, stringifyStylesheet, toLowerCase, transformAttribute };\n","import { classMatchesRegex, IGNORED_NODE, isShadowRoot } from '../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nfunction on(type, fn, target = document) {\r\n const options = { capture: true, passive: true };\r\n target.addEventListener(type, fn, options);\r\n return () => target.removeEventListener(type, fn, options);\r\n}\r\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\r\n '\\r\\n' +\r\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\r\n '\\r\\n' +\r\n 'or you can use record.mirror to access the mirror instance during recording.';\r\nlet _mirror = {\r\n map: {},\r\n getId() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return -1;\r\n },\r\n getNode() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return null;\r\n },\r\n removeNodeFromMap() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n has() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return false;\r\n },\r\n reset() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n};\r\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\r\n _mirror = new Proxy(_mirror, {\r\n get(target, prop, receiver) {\r\n if (prop === 'map') {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n }\r\n return Reflect.get(target, prop, receiver);\r\n },\r\n });\r\n}\r\nfunction throttle(func, wait, options = {}) {\r\n let timeout = null;\r\n let previous = 0;\r\n return function (...args) {\r\n const now = Date.now();\r\n if (!previous && options.leading === false) {\r\n previous = now;\r\n }\r\n const remaining = wait - (now - previous);\r\n const context = this;\r\n if (remaining <= 0 || remaining > wait) {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n }\r\n previous = now;\r\n func.apply(context, args);\r\n }\r\n else if (!timeout && options.trailing !== false) {\r\n timeout = setTimeout(() => {\r\n previous = options.leading === false ? 0 : Date.now();\r\n timeout = null;\r\n func.apply(context, args);\r\n }, remaining);\r\n }\r\n };\r\n}\r\nfunction hookSetter(target, key, d, isRevoked, win = window) {\r\n const original = win.Object.getOwnPropertyDescriptor(target, key);\r\n win.Object.defineProperty(target, key, isRevoked\r\n ? d\r\n : {\r\n set(value) {\r\n setTimeout(() => {\r\n d.set.call(this, value);\r\n }, 0);\r\n if (original && original.set) {\r\n original.set.call(this, value);\r\n }\r\n },\r\n });\r\n return () => hookSetter(target, key, original || {}, true);\r\n}\r\nfunction patch(source, name, replacement) {\r\n try {\r\n if (!(name in source)) {\r\n return () => {\r\n };\r\n }\r\n const original = source[name];\r\n const wrapped = replacement(original);\r\n if (typeof wrapped === 'function') {\r\n wrapped.prototype = wrapped.prototype || {};\r\n Object.defineProperties(wrapped, {\r\n __rrweb_original__: {\r\n enumerable: false,\r\n value: original,\r\n },\r\n });\r\n }\r\n source[name] = wrapped;\r\n return () => {\r\n source[name] = original;\r\n };\r\n }\r\n catch (_a) {\r\n return () => {\r\n };\r\n }\r\n}\r\nlet nowTimestamp = Date.now;\r\nif (!(/[1-9][0-9]{12}/.test(Date.now().toString()))) {\r\n nowTimestamp = () => new Date().getTime();\r\n}\r\nfunction getWindowScroll(win) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const doc = win.document;\r\n return {\r\n left: doc.scrollingElement\r\n ? doc.scrollingElement.scrollLeft\r\n : win.pageXOffset !== undefined\r\n ? win.pageXOffset\r\n : (doc === null || doc === void 0 ? void 0 : doc.documentElement.scrollLeft) ||\r\n ((_b = (_a = doc === null || doc === void 0 ? void 0 : doc.body) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.scrollLeft) ||\r\n ((_c = doc === null || doc === void 0 ? void 0 : doc.body) === null || _c === void 0 ? void 0 : _c.scrollLeft) ||\r\n 0,\r\n top: doc.scrollingElement\r\n ? doc.scrollingElement.scrollTop\r\n : win.pageYOffset !== undefined\r\n ? win.pageYOffset\r\n : (doc === null || doc === void 0 ? void 0 : doc.documentElement.scrollTop) ||\r\n ((_e = (_d = doc === null || doc === void 0 ? void 0 : doc.body) === null || _d === void 0 ? void 0 : _d.parentElement) === null || _e === void 0 ? void 0 : _e.scrollTop) ||\r\n ((_f = doc === null || doc === void 0 ? void 0 : doc.body) === null || _f === void 0 ? void 0 : _f.scrollTop) ||\r\n 0,\r\n };\r\n}\r\nfunction getWindowHeight() {\r\n return (window.innerHeight ||\r\n (document.documentElement && document.documentElement.clientHeight) ||\r\n (document.body && document.body.clientHeight));\r\n}\r\nfunction getWindowWidth() {\r\n return (window.innerWidth ||\r\n (document.documentElement && document.documentElement.clientWidth) ||\r\n (document.body && document.body.clientWidth));\r\n}\r\nfunction closestElementOfNode(node) {\r\n if (!node) {\r\n return null;\r\n }\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n return el;\r\n}\r\nfunction isBlocked(node, blockClass, blockSelector, checkAncestors) {\r\n if (!node) {\r\n return false;\r\n }\r\n const el = closestElementOfNode(node);\r\n if (!el) {\r\n return false;\r\n }\r\n try {\r\n if (typeof blockClass === 'string') {\r\n if (el.classList.contains(blockClass))\r\n return true;\r\n if (checkAncestors && el.closest('.' + blockClass) !== null)\r\n return true;\r\n }\r\n else {\r\n if (classMatchesRegex(el, blockClass, checkAncestors))\r\n return true;\r\n }\r\n }\r\n catch (e) {\r\n }\r\n if (blockSelector) {\r\n if (el.matches(blockSelector))\r\n return true;\r\n if (checkAncestors && el.closest(blockSelector) !== null)\r\n return true;\r\n }\r\n return false;\r\n}\r\nfunction isSerialized(n, mirror) {\r\n return mirror.getId(n) !== -1;\r\n}\r\nfunction isIgnored(n, mirror) {\r\n return mirror.getId(n) === IGNORED_NODE;\r\n}\r\nfunction isAncestorRemoved(target, mirror) {\r\n if (isShadowRoot(target)) {\r\n return false;\r\n }\r\n const id = mirror.getId(target);\r\n if (!mirror.has(id)) {\r\n return true;\r\n }\r\n if (target.parentNode &&\r\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\r\n return false;\r\n }\r\n if (!target.parentNode) {\r\n return true;\r\n }\r\n return isAncestorRemoved(target.parentNode, mirror);\r\n}\r\nfunction legacy_isTouchEvent(event) {\r\n return Boolean(event.changedTouches);\r\n}\r\nfunction polyfill(win = window) {\r\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\r\n win.NodeList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\r\n win.DOMTokenList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if (!Node.prototype.contains) {\r\n Node.prototype.contains = (...args) => {\r\n let node = args[0];\r\n if (!(0 in args)) {\r\n throw new TypeError('1 argument is required');\r\n }\r\n do {\r\n if (this === node) {\r\n return true;\r\n }\r\n } while ((node = node && node.parentNode));\r\n return false;\r\n };\r\n }\r\n}\r\nfunction queueToResolveTrees(queue) {\r\n const queueNodeMap = {};\r\n const putIntoMap = (m, parent) => {\r\n const nodeInTree = {\r\n value: m,\r\n parent,\r\n children: [],\r\n };\r\n queueNodeMap[m.node.id] = nodeInTree;\r\n return nodeInTree;\r\n };\r\n const queueNodeTrees = [];\r\n for (const mutation of queue) {\r\n const { nextId, parentId } = mutation;\r\n if (nextId && nextId in queueNodeMap) {\r\n const nextInTree = queueNodeMap[nextId];\r\n if (nextInTree.parent) {\r\n const idx = nextInTree.parent.children.indexOf(nextInTree);\r\n nextInTree.parent.children.splice(idx, 0, putIntoMap(mutation, nextInTree.parent));\r\n }\r\n else {\r\n const idx = queueNodeTrees.indexOf(nextInTree);\r\n queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\r\n }\r\n continue;\r\n }\r\n if (parentId in queueNodeMap) {\r\n const parentInTree = queueNodeMap[parentId];\r\n parentInTree.children.push(putIntoMap(mutation, parentInTree));\r\n continue;\r\n }\r\n queueNodeTrees.push(putIntoMap(mutation, null));\r\n }\r\n return queueNodeTrees;\r\n}\r\nfunction iterateResolveTree(tree, cb) {\r\n cb(tree.value);\r\n for (let i = tree.children.length - 1; i >= 0; i--) {\r\n iterateResolveTree(tree.children[i], cb);\r\n }\r\n}\r\nfunction isSerializedIframe(n, mirror) {\r\n return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\r\n}\r\nfunction isSerializedStylesheet(n, mirror) {\r\n return Boolean(n.nodeName === 'LINK' &&\r\n n.nodeType === n.ELEMENT_NODE &&\r\n n.getAttribute &&\r\n n.getAttribute('rel') === 'stylesheet' &&\r\n mirror.getMeta(n));\r\n}\r\nfunction getBaseDimension(node, rootIframe) {\r\n var _a, _b;\r\n const frameElement = (_b = (_a = node.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView) === null || _b === void 0 ? void 0 : _b.frameElement;\r\n if (!frameElement || frameElement === rootIframe) {\r\n return {\r\n x: 0,\r\n y: 0,\r\n relativeScale: 1,\r\n absoluteScale: 1,\r\n };\r\n }\r\n const frameDimension = frameElement.getBoundingClientRect();\r\n const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\r\n const relativeScale = frameDimension.height / frameElement.clientHeight;\r\n return {\r\n x: frameDimension.x * frameBaseDimension.relativeScale +\r\n frameBaseDimension.x,\r\n y: frameDimension.y * frameBaseDimension.relativeScale +\r\n frameBaseDimension.y,\r\n relativeScale,\r\n absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\r\n };\r\n}\r\nfunction hasShadowRoot(n) {\r\n return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);\r\n}\r\nfunction getNestedRule(rules, position) {\r\n const rule = rules[position[0]];\r\n if (position.length === 1) {\r\n return rule;\r\n }\r\n else {\r\n return getNestedRule(rule.cssRules[position[1]].cssRules, position.slice(2));\r\n }\r\n}\r\nfunction getPositionsAndIndex(nestedIndex) {\r\n const positions = [...nestedIndex];\r\n const index = positions.pop();\r\n return { positions, index };\r\n}\r\nfunction uniqueTextMutations(mutations) {\r\n const idSet = new Set();\r\n const uniqueMutations = [];\r\n for (let i = mutations.length; i--;) {\r\n const mutation = mutations[i];\r\n if (!idSet.has(mutation.id)) {\r\n uniqueMutations.push(mutation);\r\n idSet.add(mutation.id);\r\n }\r\n }\r\n return uniqueMutations;\r\n}\r\nclass StyleSheetMirror {\r\n constructor() {\r\n this.id = 1;\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n }\r\n getId(stylesheet) {\r\n var _a;\r\n return (_a = this.styleIDMap.get(stylesheet)) !== null && _a !== void 0 ? _a : -1;\r\n }\r\n has(stylesheet) {\r\n return this.styleIDMap.has(stylesheet);\r\n }\r\n add(stylesheet, id) {\r\n if (this.has(stylesheet))\r\n return this.getId(stylesheet);\r\n let newId;\r\n if (id === undefined) {\r\n newId = this.id++;\r\n }\r\n else\r\n newId = id;\r\n this.styleIDMap.set(stylesheet, newId);\r\n this.idStyleMap.set(newId, stylesheet);\r\n return newId;\r\n }\r\n getStyle(id) {\r\n return this.idStyleMap.get(id) || null;\r\n }\r\n reset() {\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n this.id = 1;\r\n }\r\n generateId() {\r\n return this.id++;\r\n }\r\n}\r\nfunction getShadowHost(n) {\r\n var _a, _b;\r\n let shadowHost = null;\r\n if (((_b = (_a = n.getRootNode) === null || _a === void 0 ? void 0 : _a.call(n)) === null || _b === void 0 ? void 0 : _b.nodeType) === Node.DOCUMENT_FRAGMENT_NODE &&\r\n n.getRootNode().host)\r\n shadowHost = n.getRootNode().host;\r\n return shadowHost;\r\n}\r\nfunction getRootShadowHost(n) {\r\n let rootShadowHost = n;\r\n let shadowHost;\r\n while ((shadowHost = getShadowHost(rootShadowHost)))\r\n rootShadowHost = shadowHost;\r\n return rootShadowHost;\r\n}\r\nfunction shadowHostInDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n const shadowHost = getRootShadowHost(n);\r\n return doc.contains(shadowHost);\r\n}\r\nfunction inDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n return doc.contains(n) || shadowHostInDom(n);\r\n}\n\nexport { StyleSheetMirror, _mirror, closestElementOfNode, getBaseDimension, getNestedRule, getPositionsAndIndex, getRootShadowHost, getShadowHost, getWindowHeight, getWindowScroll, getWindowWidth, hasShadowRoot, hookSetter, inDom, isAncestorRemoved, isBlocked, isIgnored, isSerialized, isSerializedIframe, isSerializedStylesheet, iterateResolveTree, legacy_isTouchEvent, nowTimestamp, on, patch, polyfill, queueToResolveTrees, shadowHostInDom, throttle, uniqueTextMutations };\n","var EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n return CanvasContext2;\n})(CanvasContext || {});\nvar ReplayerEvents = /* @__PURE__ */ ((ReplayerEvents2) => {\n ReplayerEvents2[\"Start\"] = \"start\";\n ReplayerEvents2[\"Pause\"] = \"pause\";\n ReplayerEvents2[\"Resume\"] = \"resume\";\n ReplayerEvents2[\"Resize\"] = \"resize\";\n ReplayerEvents2[\"Finish\"] = \"finish\";\n ReplayerEvents2[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n ReplayerEvents2[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n ReplayerEvents2[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n ReplayerEvents2[\"SkipStart\"] = \"skip-start\";\n ReplayerEvents2[\"SkipEnd\"] = \"skip-end\";\n ReplayerEvents2[\"MouseInteraction\"] = \"mouse-interaction\";\n ReplayerEvents2[\"EventCast\"] = \"event-cast\";\n ReplayerEvents2[\"CustomEvent\"] = \"custom-event\";\n ReplayerEvents2[\"Flush\"] = \"flush\";\n ReplayerEvents2[\"StateChange\"] = \"state-change\";\n ReplayerEvents2[\"PlayBack\"] = \"play-back\";\n ReplayerEvents2[\"Destroy\"] = \"destroy\";\n return ReplayerEvents2;\n})(ReplayerEvents || {});\n\nexport { CanvasContext, EventType, IncrementalSource, MouseInteractions, PointerTypes, ReplayerEvents };\n","import { isShadowRoot, isNativeShadowDom, getInputType, maskInputValue, ignoreAttribute, transformAttribute, toLowerCase, needMaskingText, IGNORED_NODE, serializeNodeWithId } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { isIgnored, isBlocked, isSerialized, isAncestorRemoved, closestElementOfNode, hasShadowRoot, inDom, getShadowHost, isSerializedIframe, isSerializedStylesheet } from '../utils.js';\n\nfunction isNodeInLinkedList(n) {\r\n return '__ln' in n;\r\n}\r\nclass DoubleLinkedList {\r\n constructor() {\r\n this.length = 0;\r\n this.head = null;\r\n this.tail = null;\r\n }\r\n get(position) {\r\n if (position >= this.length) {\r\n throw new Error('Position outside of list range');\r\n }\r\n let current = this.head;\r\n for (let index = 0; index < position; index++) {\r\n current = (current === null || current === void 0 ? void 0 : current.next) || null;\r\n }\r\n return current;\r\n }\r\n addNode(n) {\r\n const node = {\r\n value: n,\r\n previous: null,\r\n next: null,\r\n };\r\n n.__ln = node;\r\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\r\n const current = n.previousSibling.__ln.next;\r\n node.next = current;\r\n node.previous = n.previousSibling.__ln;\r\n n.previousSibling.__ln.next = node;\r\n if (current) {\r\n current.previous = node;\r\n }\r\n }\r\n else if (n.nextSibling &&\r\n isNodeInLinkedList(n.nextSibling) &&\r\n n.nextSibling.__ln.previous) {\r\n const current = n.nextSibling.__ln.previous;\r\n node.previous = current;\r\n node.next = n.nextSibling.__ln;\r\n n.nextSibling.__ln.previous = node;\r\n if (current) {\r\n current.next = node;\r\n }\r\n }\r\n else {\r\n if (this.head) {\r\n this.head.previous = node;\r\n }\r\n node.next = this.head;\r\n this.head = node;\r\n }\r\n if (node.next === null) {\r\n this.tail = node;\r\n }\r\n this.length++;\r\n }\r\n removeNode(n) {\r\n const current = n.__ln;\r\n if (!this.head) {\r\n return;\r\n }\r\n if (!current.previous) {\r\n this.head = current.next;\r\n if (this.head) {\r\n this.head.previous = null;\r\n }\r\n else {\r\n this.tail = null;\r\n }\r\n }\r\n else {\r\n current.previous.next = current.next;\r\n if (current.next) {\r\n current.next.previous = current.previous;\r\n }\r\n else {\r\n this.tail = current.previous;\r\n }\r\n }\r\n if (n.__ln) {\r\n delete n.__ln;\r\n }\r\n this.length--;\r\n }\r\n}\r\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\r\nclass MutationBuffer {\r\n constructor() {\r\n this.frozen = false;\r\n this.locked = false;\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.mapRemoves = [];\r\n this.movedMap = {};\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.processMutations = (mutations) => {\r\n mutations.forEach(this.processMutation);\r\n this.emit();\r\n };\r\n this.emit = () => {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const adds = [];\r\n const addedIds = new Set();\r\n const addList = new DoubleLinkedList();\r\n const getNextId = (n) => {\r\n let ns = n;\r\n let nextId = IGNORED_NODE;\r\n while (nextId === IGNORED_NODE) {\r\n ns = ns && ns.nextSibling;\r\n nextId = ns && this.mirror.getId(ns);\r\n }\r\n return nextId;\r\n };\r\n const pushAdd = (n) => {\r\n if (!n.parentNode ||\r\n !inDom(n) ||\r\n n.parentNode.tagName === 'TEXTAREA') {\r\n return;\r\n }\r\n const parentId = isShadowRoot(n.parentNode)\r\n ? this.mirror.getId(getShadowHost(n))\r\n : this.mirror.getId(n.parentNode);\r\n const nextId = getNextId(n);\r\n if (parentId === -1 || nextId === -1) {\r\n return addList.addNode(n);\r\n }\r\n const sn = serializeNodeWithId(n, {\r\n doc: this.doc,\r\n mirror: this.mirror,\r\n blockClass: this.blockClass,\r\n blockSelector: this.blockSelector,\r\n maskTextClass: this.maskTextClass,\r\n maskTextSelector: this.maskTextSelector,\r\n skipChild: true,\r\n newlyAddedElement: true,\r\n inlineStylesheet: this.inlineStylesheet,\r\n maskInputOptions: this.maskInputOptions,\r\n maskTextFn: this.maskTextFn,\r\n maskInputFn: this.maskInputFn,\r\n slimDOMOptions: this.slimDOMOptions,\r\n dataURLOptions: this.dataURLOptions,\r\n recordCanvas: this.recordCanvas,\r\n inlineImages: this.inlineImages,\r\n onSerialize: (currentN) => {\r\n if (isSerializedIframe(currentN, this.mirror)) {\r\n this.iframeManager.addIframe(currentN);\r\n }\r\n if (isSerializedStylesheet(currentN, this.mirror)) {\r\n this.stylesheetManager.trackLinkElement(currentN);\r\n }\r\n if (hasShadowRoot(n)) {\r\n this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n this.iframeManager.attachIframe(iframe, childSn);\r\n this.shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (link, childSn) => {\r\n this.stylesheetManager.attachLinkElement(link, childSn);\r\n },\r\n });\r\n if (sn) {\r\n adds.push({\r\n parentId,\r\n nextId,\r\n node: sn,\r\n });\r\n addedIds.add(sn.id);\r\n }\r\n };\r\n while (this.mapRemoves.length) {\r\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\r\n }\r\n for (const n of this.movedSet) {\r\n if (isParentRemoved(this.removes, n, this.mirror) &&\r\n !this.movedSet.has(n.parentNode)) {\r\n continue;\r\n }\r\n pushAdd(n);\r\n }\r\n for (const n of this.addedSet) {\r\n if (!isAncestorInSet(this.droppedSet, n) &&\r\n !isParentRemoved(this.removes, n, this.mirror)) {\r\n pushAdd(n);\r\n }\r\n else if (isAncestorInSet(this.movedSet, n)) {\r\n pushAdd(n);\r\n }\r\n else {\r\n this.droppedSet.add(n);\r\n }\r\n }\r\n let candidate = null;\r\n while (addList.length) {\r\n let node = null;\r\n if (candidate) {\r\n const parentId = this.mirror.getId(candidate.value.parentNode);\r\n const nextId = getNextId(candidate.value);\r\n if (parentId !== -1 && nextId !== -1) {\r\n node = candidate;\r\n }\r\n }\r\n if (!node) {\r\n let tailNode = addList.tail;\r\n while (tailNode) {\r\n const _node = tailNode;\r\n tailNode = tailNode.previous;\r\n if (_node) {\r\n const parentId = this.mirror.getId(_node.value.parentNode);\r\n const nextId = getNextId(_node.value);\r\n if (nextId === -1)\r\n continue;\r\n else if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n else {\r\n const unhandledNode = _node.value;\r\n if (unhandledNode.parentNode &&\r\n unhandledNode.parentNode.nodeType ===\r\n Node.DOCUMENT_FRAGMENT_NODE) {\r\n const shadowHost = unhandledNode.parentNode\r\n .host;\r\n const parentId = this.mirror.getId(shadowHost);\r\n if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (!node) {\r\n while (addList.head) {\r\n addList.removeNode(addList.head.value);\r\n }\r\n break;\r\n }\r\n candidate = node.previous;\r\n addList.removeNode(node.value);\r\n pushAdd(node.value);\r\n }\r\n const payload = {\r\n texts: this.texts\r\n .map((text) => {\r\n const n = text.node;\r\n if (n.parentNode &&\r\n n.parentNode.tagName === 'TEXTAREA') {\r\n this.genTextAreaValueMutation(n.parentNode);\r\n }\r\n return {\r\n id: this.mirror.getId(n),\r\n value: text.value,\r\n };\r\n })\r\n .filter((text) => !addedIds.has(text.id))\r\n .filter((text) => this.mirror.has(text.id)),\r\n attributes: this.attributes\r\n .map((attribute) => {\r\n const { attributes } = attribute;\r\n if (typeof attributes.style === 'string') {\r\n const diffAsStr = JSON.stringify(attribute.styleDiff);\r\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\r\n if (diffAsStr.length < attributes.style.length) {\r\n if ((diffAsStr + unchangedAsStr).split('var(').length ===\r\n attributes.style.split('var(').length) {\r\n attributes.style = attribute.styleDiff;\r\n }\r\n }\r\n }\r\n return {\r\n id: this.mirror.getId(attribute.node),\r\n attributes: attributes,\r\n };\r\n })\r\n .filter((attribute) => !addedIds.has(attribute.id))\r\n .filter((attribute) => this.mirror.has(attribute.id)),\r\n removes: this.removes,\r\n adds,\r\n };\r\n if (!payload.texts.length &&\r\n !payload.attributes.length &&\r\n !payload.removes.length &&\r\n !payload.adds.length) {\r\n return;\r\n }\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.movedMap = {};\r\n this.mutationCb(payload);\r\n };\r\n this.genTextAreaValueMutation = (textarea) => {\r\n let item = this.attributeMap.get(textarea);\r\n if (!item) {\r\n item = {\r\n node: textarea,\r\n attributes: {},\r\n styleDiff: {},\r\n _unchangedStyles: {},\r\n };\r\n this.attributes.push(item);\r\n this.attributeMap.set(textarea, item);\r\n }\r\n item.attributes.value = Array.from(textarea.childNodes, (cn) => cn.textContent || '').join('');\r\n };\r\n this.processMutation = (m) => {\r\n if (isIgnored(m.target, this.mirror)) {\r\n return;\r\n }\r\n switch (m.type) {\r\n case 'characterData': {\r\n const value = m.target.textContent;\r\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) &&\r\n value !== m.oldValue) {\r\n this.texts.push({\r\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, true) && value\r\n ? this.maskTextFn\r\n ? this.maskTextFn(value, closestElementOfNode(m.target))\r\n : value.replace(/[\\S]/g, '*')\r\n : value,\r\n node: m.target,\r\n });\r\n }\r\n break;\r\n }\r\n case 'attributes': {\r\n const target = m.target;\r\n let attributeName = m.attributeName;\r\n let value = m.target.getAttribute(attributeName);\r\n if (attributeName === 'value') {\r\n const type = getInputType(target);\r\n value = maskInputValue({\r\n element: target,\r\n maskInputOptions: this.maskInputOptions,\r\n tagName: target.tagName,\r\n type,\r\n value,\r\n maskInputFn: this.maskInputFn,\r\n });\r\n }\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||\r\n value === m.oldValue) {\r\n return;\r\n }\r\n let item = this.attributeMap.get(m.target);\r\n if (target.tagName === 'IFRAME' &&\r\n attributeName === 'src' &&\r\n !this.keepIframeSrcFn(value)) {\r\n if (!target.contentDocument) {\r\n attributeName = 'rr_src';\r\n }\r\n else {\r\n return;\r\n }\r\n }\r\n if (!item) {\r\n item = {\r\n node: m.target,\r\n attributes: {},\r\n styleDiff: {},\r\n _unchangedStyles: {},\r\n };\r\n this.attributes.push(item);\r\n this.attributeMap.set(m.target, item);\r\n }\r\n if (attributeName === 'type' &&\r\n target.tagName === 'INPUT' &&\r\n (m.oldValue || '').toLowerCase() === 'password') {\r\n target.setAttribute('data-rr-is-password', 'true');\r\n }\r\n if (!ignoreAttribute(target.tagName, attributeName, value)) {\r\n item.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value);\r\n if (attributeName === 'style') {\r\n if (!this.unattachedDoc) {\r\n try {\r\n this.unattachedDoc =\r\n document.implementation.createHTMLDocument();\r\n }\r\n catch (e) {\r\n this.unattachedDoc = this.doc;\r\n }\r\n }\r\n const old = this.unattachedDoc.createElement('span');\r\n if (m.oldValue) {\r\n old.setAttribute('style', m.oldValue);\r\n }\r\n for (const pname of Array.from(target.style)) {\r\n const newValue = target.style.getPropertyValue(pname);\r\n const newPriority = target.style.getPropertyPriority(pname);\r\n if (newValue !== old.style.getPropertyValue(pname) ||\r\n newPriority !== old.style.getPropertyPriority(pname)) {\r\n if (newPriority === '') {\r\n item.styleDiff[pname] = newValue;\r\n }\r\n else {\r\n item.styleDiff[pname] = [newValue, newPriority];\r\n }\r\n }\r\n else {\r\n item._unchangedStyles[pname] = [newValue, newPriority];\r\n }\r\n }\r\n for (const pname of Array.from(old.style)) {\r\n if (target.style.getPropertyValue(pname) === '') {\r\n item.styleDiff[pname] = false;\r\n }\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 'childList': {\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, true))\r\n return;\r\n if (m.target.tagName === 'TEXTAREA') {\r\n this.genTextAreaValueMutation(m.target);\r\n return;\r\n }\r\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\r\n m.removedNodes.forEach((n) => {\r\n const nodeId = this.mirror.getId(n);\r\n const parentId = isShadowRoot(m.target)\r\n ? this.mirror.getId(m.target.host)\r\n : this.mirror.getId(m.target);\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||\r\n isIgnored(n, this.mirror) ||\r\n !isSerialized(n, this.mirror)) {\r\n return;\r\n }\r\n if (this.addedSet.has(n)) {\r\n deepDelete(this.addedSet, n);\r\n this.droppedSet.add(n);\r\n }\r\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\r\n else if (isAncestorRemoved(m.target, this.mirror)) ;\r\n else if (this.movedSet.has(n) &&\r\n this.movedMap[moveKey(nodeId, parentId)]) {\r\n deepDelete(this.movedSet, n);\r\n }\r\n else {\r\n this.removes.push({\r\n parentId,\r\n id: nodeId,\r\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)\r\n ? true\r\n : undefined,\r\n });\r\n }\r\n this.mapRemoves.push(n);\r\n });\r\n break;\r\n }\r\n }\r\n };\r\n this.genAdds = (n, target) => {\r\n if (this.processedNodeManager.inOtherBuffer(n, this))\r\n return;\r\n if (this.addedSet.has(n) || this.movedSet.has(n))\r\n return;\r\n if (this.mirror.hasNode(n)) {\r\n if (isIgnored(n, this.mirror)) {\r\n return;\r\n }\r\n this.movedSet.add(n);\r\n let targetId = null;\r\n if (target && this.mirror.hasNode(target)) {\r\n targetId = this.mirror.getId(target);\r\n }\r\n if (targetId && targetId !== -1) {\r\n this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\r\n }\r\n }\r\n else {\r\n this.addedSet.add(n);\r\n this.droppedSet.delete(n);\r\n }\r\n if (!isBlocked(n, this.blockClass, this.blockSelector, false)) {\r\n n.childNodes.forEach((childN) => this.genAdds(childN));\r\n if (hasShadowRoot(n)) {\r\n n.shadowRoot.childNodes.forEach((childN) => {\r\n this.processedNodeManager.add(childN, this);\r\n this.genAdds(childN, n);\r\n });\r\n }\r\n }\r\n };\r\n }\r\n init(options) {\r\n [\r\n 'mutationCb',\r\n 'blockClass',\r\n 'blockSelector',\r\n 'maskTextClass',\r\n 'maskTextSelector',\r\n 'inlineStylesheet',\r\n 'maskInputOptions',\r\n 'maskTextFn',\r\n 'maskInputFn',\r\n 'keepIframeSrcFn',\r\n 'recordCanvas',\r\n 'inlineImages',\r\n 'slimDOMOptions',\r\n 'dataURLOptions',\r\n 'doc',\r\n 'mirror',\r\n 'iframeManager',\r\n 'stylesheetManager',\r\n 'shadowDomManager',\r\n 'canvasManager',\r\n 'processedNodeManager',\r\n ].forEach((key) => {\r\n this[key] = options[key];\r\n });\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n this.canvasManager.freeze();\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n this.canvasManager.unfreeze();\r\n this.emit();\r\n }\r\n isFrozen() {\r\n return this.frozen;\r\n }\r\n lock() {\r\n this.locked = true;\r\n this.canvasManager.lock();\r\n }\r\n unlock() {\r\n this.locked = false;\r\n this.canvasManager.unlock();\r\n this.emit();\r\n }\r\n reset() {\r\n this.shadowDomManager.reset();\r\n this.canvasManager.reset();\r\n }\r\n}\r\nfunction deepDelete(addsSet, n) {\r\n addsSet.delete(n);\r\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\r\n}\r\nfunction isParentRemoved(removes, n, mirror) {\r\n if (removes.length === 0)\r\n return false;\r\n return _isParentRemoved(removes, n, mirror);\r\n}\r\nfunction _isParentRemoved(removes, n, mirror) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n const parentId = mirror.getId(parentNode);\r\n if (removes.some((r) => r.id === parentId)) {\r\n return true;\r\n }\r\n return _isParentRemoved(removes, parentNode, mirror);\r\n}\r\nfunction isAncestorInSet(set, n) {\r\n if (set.size === 0)\r\n return false;\r\n return _isAncestorInSet(set, n);\r\n}\r\nfunction _isAncestorInSet(set, n) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n if (set.has(parentNode)) {\r\n return true;\r\n }\r\n return _isAncestorInSet(set, parentNode);\r\n}\n\nexport { MutationBuffer as default };\n","let errorHandler;\r\nfunction registerErrorHandler(handler) {\r\n errorHandler = handler;\r\n}\r\nfunction unregisterErrorHandler() {\r\n errorHandler = undefined;\r\n}\r\nconst callbackWrapper = (cb) => {\r\n if (!errorHandler) {\r\n return cb;\r\n }\r\n const rrwebWrapped = ((...rest) => {\r\n try {\r\n return cb(...rest);\r\n }\r\n catch (error) {\r\n if (errorHandler && errorHandler(error) === true) {\r\n return;\r\n }\r\n throw error;\r\n }\r\n });\r\n return rrwebWrapped;\r\n};\n\nexport { callbackWrapper, registerErrorHandler, unregisterErrorHandler };\n","import { toLowerCase, getInputType, maskInputValue } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { on, throttle, isBlocked, getWindowScroll, getWindowHeight, getWindowWidth, hookSetter, patch, legacy_isTouchEvent, nowTimestamp } from '../utils.js';\nimport { MouseInteractions, IncrementalSource, PointerTypes } from '../../../types/dist/types.js';\nimport MutationBuffer from './mutation.js';\nimport { callbackWrapper } from './error-handler.js';\n\nconst mutationBuffers = [];\r\nfunction getEventTarget(event) {\r\n try {\r\n if ('composedPath' in event) {\r\n const path = event.composedPath();\r\n if (path.length) {\r\n return path[0];\r\n }\r\n }\r\n else if ('path' in event && event.path.length) {\r\n return event.path[0];\r\n }\r\n }\r\n catch (_a) {\r\n }\r\n return event && event.target;\r\n}\r\nfunction initMutationObserver(options, rootEl) {\r\n var _a, _b;\r\n const mutationBuffer = new MutationBuffer();\r\n mutationBuffers.push(mutationBuffer);\r\n mutationBuffer.init(options);\r\n let mutationObserverCtor = window.MutationObserver ||\r\n window.__rrMutationObserver;\r\n const angularZoneSymbol = (_b = (_a = window === null || window === void 0 ? void 0 : window.Zone) === null || _a === void 0 ? void 0 : _a.__symbol__) === null || _b === void 0 ? void 0 : _b.call(_a, 'MutationObserver');\r\n if (angularZoneSymbol &&\r\n window[angularZoneSymbol]) {\r\n mutationObserverCtor = window[angularZoneSymbol];\r\n }\r\n const observer = new mutationObserverCtor(callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer)));\r\n observer.observe(rootEl, {\r\n attributes: true,\r\n attributeOldValue: true,\r\n characterData: true,\r\n characterDataOldValue: true,\r\n childList: true,\r\n subtree: true,\r\n });\r\n return observer;\r\n}\r\nfunction initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {\r\n if (sampling.mousemove === false) {\r\n return () => {\r\n };\r\n }\r\n const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\r\n const callbackThreshold = typeof sampling.mousemoveCallback === 'number'\r\n ? sampling.mousemoveCallback\r\n : 500;\r\n let positions = [];\r\n let timeBaseline;\r\n const wrappedCb = throttle(callbackWrapper((source) => {\r\n const totalOffset = Date.now() - timeBaseline;\r\n mousemoveCb(positions.map((p) => {\r\n p.timeOffset -= totalOffset;\r\n return p;\r\n }), source);\r\n positions = [];\r\n timeBaseline = null;\r\n }), callbackThreshold);\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n const { clientX, clientY } = legacy_isTouchEvent(evt)\r\n ? evt.changedTouches[0]\r\n : evt;\r\n if (!timeBaseline) {\r\n timeBaseline = nowTimestamp();\r\n }\r\n positions.push({\r\n x: clientX,\r\n y: clientY,\r\n id: mirror.getId(target),\r\n timeOffset: nowTimestamp() - timeBaseline,\r\n });\r\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\r\n ? IncrementalSource.Drag\r\n : evt instanceof MouseEvent\r\n ? IncrementalSource.MouseMove\r\n : IncrementalSource.TouchMove);\r\n }), threshold, {\r\n trailing: false,\r\n }));\r\n const handlers = [\r\n on('mousemove', updatePosition, doc),\r\n on('touchmove', updatePosition, doc),\r\n on('drag', updatePosition, doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, sampling, }) {\r\n if (sampling.mouseInteraction === false) {\r\n return () => {\r\n };\r\n }\r\n const disableMap = sampling.mouseInteraction === true ||\r\n sampling.mouseInteraction === undefined\r\n ? {}\r\n : sampling.mouseInteraction;\r\n const handlers = [];\r\n let currentPointerType = null;\r\n const getHandler = (eventKey) => {\r\n return (event) => {\r\n const target = getEventTarget(event);\r\n if (isBlocked(target, blockClass, blockSelector, true)) {\r\n return;\r\n }\r\n let pointerType = null;\r\n let thisEventKey = eventKey;\r\n if ('pointerType' in event) {\r\n switch (event.pointerType) {\r\n case 'mouse':\r\n pointerType = PointerTypes.Mouse;\r\n break;\r\n case 'touch':\r\n pointerType = PointerTypes.Touch;\r\n break;\r\n case 'pen':\r\n pointerType = PointerTypes.Pen;\r\n break;\r\n }\r\n if (pointerType === PointerTypes.Touch) {\r\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\r\n thisEventKey = 'TouchStart';\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\r\n thisEventKey = 'TouchEnd';\r\n }\r\n }\r\n else if (pointerType === PointerTypes.Pen) ;\r\n }\r\n else if (legacy_isTouchEvent(event)) {\r\n pointerType = PointerTypes.Touch;\r\n }\r\n if (pointerType !== null) {\r\n currentPointerType = pointerType;\r\n if ((thisEventKey.startsWith('Touch') &&\r\n pointerType === PointerTypes.Touch) ||\r\n (thisEventKey.startsWith('Mouse') &&\r\n pointerType === PointerTypes.Mouse)) {\r\n pointerType = null;\r\n }\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\r\n pointerType = currentPointerType;\r\n currentPointerType = null;\r\n }\r\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\r\n if (!e) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n const { clientX, clientY } = e;\r\n callbackWrapper(mouseInteractionCb)(Object.assign({ type: MouseInteractions[thisEventKey], id, x: clientX, y: clientY }, (pointerType !== null && { pointerType })));\r\n };\r\n };\r\n Object.keys(MouseInteractions)\r\n .filter((key) => Number.isNaN(Number(key)) &&\r\n !key.endsWith('_Departed') &&\r\n disableMap[key] !== false)\r\n .forEach((eventKey) => {\r\n let eventName = toLowerCase(eventKey);\r\n const handler = getHandler(eventKey);\r\n if (window.PointerEvent) {\r\n switch (MouseInteractions[eventKey]) {\r\n case MouseInteractions.MouseDown:\r\n case MouseInteractions.MouseUp:\r\n eventName = eventName.replace('mouse', 'pointer');\r\n break;\r\n case MouseInteractions.TouchStart:\r\n case MouseInteractions.TouchEnd:\r\n return;\r\n }\r\n }\r\n handlers.push(on(eventName, handler, doc));\r\n });\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, sampling, }) {\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, true)) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n if (target === doc && doc.defaultView) {\r\n const scrollLeftTop = getWindowScroll(doc.defaultView);\r\n scrollCb({\r\n id,\r\n x: scrollLeftTop.left,\r\n y: scrollLeftTop.top,\r\n });\r\n }\r\n else {\r\n scrollCb({\r\n id,\r\n x: target.scrollLeft,\r\n y: target.scrollTop,\r\n });\r\n }\r\n }), sampling.scroll || 100));\r\n return on('scroll', updatePosition, doc);\r\n}\r\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\r\n let lastH = -1;\r\n let lastW = -1;\r\n const updateDimension = callbackWrapper(throttle(callbackWrapper(() => {\r\n const height = getWindowHeight();\r\n const width = getWindowWidth();\r\n if (lastH !== height || lastW !== width) {\r\n viewportResizeCb({\r\n width: Number(width),\r\n height: Number(height),\r\n });\r\n lastH = height;\r\n lastW = width;\r\n }\r\n }), 200));\r\n return on('resize', updateDimension, win);\r\n}\r\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\r\nconst lastInputValueMap = new WeakMap();\r\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, }) {\r\n function eventHandler(event) {\r\n let target = getEventTarget(event);\r\n const userTriggered = event.isTrusted;\r\n const tagName = target && target.tagName;\r\n if (target && tagName === 'OPTION') {\r\n target = target.parentElement;\r\n }\r\n if (!target ||\r\n !tagName ||\r\n INPUT_TAGS.indexOf(tagName) < 0 ||\r\n isBlocked(target, blockClass, blockSelector, true)) {\r\n return;\r\n }\r\n if (target.classList.contains(ignoreClass) ||\r\n (ignoreSelector && target.matches(ignoreSelector))) {\r\n return;\r\n }\r\n let text = target.value;\r\n let isChecked = false;\r\n const type = getInputType(target) || '';\r\n if (type === 'radio' || type === 'checkbox') {\r\n isChecked = target.checked;\r\n }\r\n else if (maskInputOptions[tagName.toLowerCase()] ||\r\n maskInputOptions[type]) {\r\n text = maskInputValue({\r\n element: target,\r\n maskInputOptions,\r\n tagName,\r\n type,\r\n value: text,\r\n maskInputFn,\r\n });\r\n }\r\n cbWithDedup(target, userTriggeredOnInput\r\n ? { text, isChecked, userTriggered }\r\n : { text, isChecked });\r\n const name = target.name;\r\n if (type === 'radio' && name && isChecked) {\r\n doc\r\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\r\n .forEach((el) => {\r\n if (el !== target) {\r\n const text = el.value;\r\n cbWithDedup(el, userTriggeredOnInput\r\n ? { text, isChecked: !isChecked, userTriggered: false }\r\n : { text, isChecked: !isChecked });\r\n }\r\n });\r\n }\r\n }\r\n function cbWithDedup(target, v) {\r\n const lastInputValue = lastInputValueMap.get(target);\r\n if (!lastInputValue ||\r\n lastInputValue.text !== v.text ||\r\n lastInputValue.isChecked !== v.isChecked) {\r\n lastInputValueMap.set(target, v);\r\n const id = mirror.getId(target);\r\n callbackWrapper(inputCb)(Object.assign(Object.assign({}, v), { id }));\r\n }\r\n }\r\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\r\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\r\n const currentWindow = doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n }\r\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');\r\n const hookProperties = [\r\n [currentWindow.HTMLInputElement.prototype, 'value'],\r\n [currentWindow.HTMLInputElement.prototype, 'checked'],\r\n [currentWindow.HTMLSelectElement.prototype, 'value'],\r\n [currentWindow.HTMLTextAreaElement.prototype, 'value'],\r\n [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],\r\n [currentWindow.HTMLOptionElement.prototype, 'selected'],\r\n ];\r\n if (propertyDescriptor && propertyDescriptor.set) {\r\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\r\n set() {\r\n callbackWrapper(eventHandler)({\r\n target: this,\r\n isTrusted: false,\r\n });\r\n },\r\n }, false, currentWindow)));\r\n }\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction getNestedCSSRulePositions(rule) {\r\n const positions = [];\r\n function recurse(childRule, pos) {\r\n if ((hasNestedCSSRule('CSSGroupingRule') &&\r\n childRule.parentRule instanceof CSSGroupingRule) ||\r\n (hasNestedCSSRule('CSSMediaRule') &&\r\n childRule.parentRule instanceof CSSMediaRule) ||\r\n (hasNestedCSSRule('CSSSupportsRule') &&\r\n childRule.parentRule instanceof CSSSupportsRule) ||\r\n (hasNestedCSSRule('CSSConditionRule') &&\r\n childRule.parentRule instanceof CSSConditionRule)) {\r\n const rules = Array.from(childRule.parentRule.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n else if (childRule.parentStyleSheet) {\r\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n return pos;\r\n }\r\n return recurse(rule, positions);\r\n}\r\nfunction getIdAndStyleId(sheet, mirror, styleMirror) {\r\n let id, styleId;\r\n if (!sheet)\r\n return {};\r\n if (sheet.ownerNode)\r\n id = mirror.getId(sheet.ownerNode);\r\n else\r\n styleId = styleMirror.getId(sheet);\r\n return {\r\n styleId,\r\n id,\r\n };\r\n}\r\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {\r\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\r\n return () => {\r\n };\r\n }\r\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\r\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [{ rule, index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\r\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [{ index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n let replace;\r\n if (win.CSSStyleSheet.prototype.replace) {\r\n replace = win.CSSStyleSheet.prototype.replace;\r\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replace: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n let replaceSync;\r\n if (win.CSSStyleSheet.prototype.replaceSync) {\r\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\r\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replaceSync: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n const supportedNestedCSSRuleTypes = {};\r\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\r\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\r\n }\r\n else {\r\n if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\r\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\r\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\r\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\r\n }\r\n }\r\n const unmodifiedFunctions = {};\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n unmodifiedFunctions[typeKey] = {\r\n insertRule: type.prototype.insertRule,\r\n deleteRule: type.prototype.deleteRule,\r\n };\r\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [\r\n {\r\n rule,\r\n index: [\r\n ...getNestedCSSRulePositions(thisArg),\r\n index || 0,\r\n ],\r\n },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [\r\n { index: [...getNestedCSSRulePositions(thisArg), index] },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleSheet.prototype.insertRule = insertRule;\r\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\r\n replace && (win.CSSStyleSheet.prototype.replace = replace);\r\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\r\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\r\n });\r\n });\r\n}\r\nfunction initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {\r\n var _a, _b, _c;\r\n let hostId = null;\r\n if (host.nodeName === '#document')\r\n hostId = mirror.getId(host);\r\n else\r\n hostId = mirror.getId(host.host);\r\n const patchTarget = host.nodeName === '#document'\r\n ? (_a = host.defaultView) === null || _a === void 0 ? void 0 : _a.Document\r\n : (_c = (_b = host.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView) === null || _c === void 0 ? void 0 : _c.ShadowRoot;\r\n const originalPropertyDescriptor = (patchTarget === null || patchTarget === void 0 ? void 0 : patchTarget.prototype)\r\n ? Object.getOwnPropertyDescriptor(patchTarget === null || patchTarget === void 0 ? void 0 : patchTarget.prototype, 'adoptedStyleSheets')\r\n : undefined;\r\n if (hostId === null ||\r\n hostId === -1 ||\r\n !patchTarget ||\r\n !originalPropertyDescriptor)\r\n return () => {\r\n };\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get() {\r\n var _a;\r\n return (_a = originalPropertyDescriptor.get) === null || _a === void 0 ? void 0 : _a.call(this);\r\n },\r\n set(sheets) {\r\n var _a;\r\n const result = (_a = originalPropertyDescriptor.set) === null || _a === void 0 ? void 0 : _a.call(this, sheets);\r\n if (hostId !== null && hostId !== -1) {\r\n try {\r\n stylesheetManager.adoptStyleSheets(sheets, hostId);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return result;\r\n },\r\n });\r\n return callbackWrapper(() => {\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get: originalPropertyDescriptor.get,\r\n set: originalPropertyDescriptor.set,\r\n });\r\n });\r\n}\r\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {\r\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\r\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n var _a;\r\n const [property, value, priority] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return setProperty.apply(thisArg, [property, value, priority]);\r\n }\r\n const { id, styleId } = getIdAndStyleId((_a = thisArg.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n set: {\r\n property,\r\n value,\r\n priority,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n var _a;\r\n const [property] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return removeProperty.apply(thisArg, [property]);\r\n }\r\n const { id, styleId } = getIdAndStyleId((_a = thisArg.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n remove: {\r\n property,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\r\n });\r\n}\r\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, mirror, sampling, doc, }) {\r\n const handler = callbackWrapper((type) => throttle(callbackWrapper((event) => {\r\n const target = getEventTarget(event);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, true)) {\r\n return;\r\n }\r\n const { currentTime, volume, muted, playbackRate, loop } = target;\r\n mediaInteractionCb({\r\n type,\r\n id: mirror.getId(target),\r\n currentTime,\r\n volume,\r\n muted,\r\n playbackRate,\r\n loop,\r\n });\r\n }), sampling.media || 500));\r\n const handlers = [\r\n on('play', handler(0), doc),\r\n on('pause', handler(1), doc),\r\n on('seeked', handler(2), doc),\r\n on('volumechange', handler(3), doc),\r\n on('ratechange', handler(4), doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initFontObserver({ fontCb, doc }) {\r\n const win = doc.defaultView;\r\n if (!win) {\r\n return () => {\r\n };\r\n }\r\n const handlers = [];\r\n const fontMap = new WeakMap();\r\n const originalFontFace = win.FontFace;\r\n win.FontFace = function FontFace(family, source, descriptors) {\r\n const fontFace = new originalFontFace(family, source, descriptors);\r\n fontMap.set(fontFace, {\r\n family,\r\n buffer: typeof source !== 'string',\r\n descriptors,\r\n fontSource: typeof source === 'string'\r\n ? source\r\n : JSON.stringify(Array.from(new Uint8Array(source))),\r\n });\r\n return fontFace;\r\n };\r\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\r\n return function (fontFace) {\r\n setTimeout(callbackWrapper(() => {\r\n const p = fontMap.get(fontFace);\r\n if (p) {\r\n fontCb(p);\r\n fontMap.delete(fontFace);\r\n }\r\n }), 0);\r\n return original.apply(this, [fontFace]);\r\n };\r\n });\r\n handlers.push(() => {\r\n win.FontFace = originalFontFace;\r\n });\r\n handlers.push(restoreHandler);\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initSelectionObserver(param) {\r\n const { doc, mirror, blockClass, blockSelector, selectionCb } = param;\r\n let collapsed = true;\r\n const updateSelection = callbackWrapper(() => {\r\n const selection = doc.getSelection();\r\n if (!selection || (collapsed && (selection === null || selection === void 0 ? void 0 : selection.isCollapsed)))\r\n return;\r\n collapsed = selection.isCollapsed || false;\r\n const ranges = [];\r\n const count = selection.rangeCount || 0;\r\n for (let i = 0; i < count; i++) {\r\n const range = selection.getRangeAt(i);\r\n const { startContainer, startOffset, endContainer, endOffset } = range;\r\n const blocked = isBlocked(startContainer, blockClass, blockSelector, true) ||\r\n isBlocked(endContainer, blockClass, blockSelector, true);\r\n if (blocked)\r\n continue;\r\n ranges.push({\r\n start: mirror.getId(startContainer),\r\n startOffset,\r\n end: mirror.getId(endContainer),\r\n endOffset,\r\n });\r\n }\r\n selectionCb({ ranges });\r\n });\r\n updateSelection();\r\n return on('selectionchange', updateSelection);\r\n}\r\nfunction initCustomElementObserver({ doc, customElementCb, }) {\r\n const win = doc.defaultView;\r\n if (!win || !win.customElements)\r\n return () => { };\r\n const restoreHandler = patch(win.customElements, 'define', function (original) {\r\n return function (name, constructor, options) {\r\n try {\r\n customElementCb({\r\n define: {\r\n name,\r\n },\r\n });\r\n }\r\n catch (e) {\r\n console.warn(`Custom element callback failed for ${name}`);\r\n }\r\n return original.apply(this, [name, constructor, options]);\r\n };\r\n });\r\n return restoreHandler;\r\n}\r\nfunction mergeHooks(o, hooks) {\r\n const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, selectionCb, customElementCb, } = o;\r\n o.mutationCb = (...p) => {\r\n if (hooks.mutation) {\r\n hooks.mutation(...p);\r\n }\r\n mutationCb(...p);\r\n };\r\n o.mousemoveCb = (...p) => {\r\n if (hooks.mousemove) {\r\n hooks.mousemove(...p);\r\n }\r\n mousemoveCb(...p);\r\n };\r\n o.mouseInteractionCb = (...p) => {\r\n if (hooks.mouseInteraction) {\r\n hooks.mouseInteraction(...p);\r\n }\r\n mouseInteractionCb(...p);\r\n };\r\n o.scrollCb = (...p) => {\r\n if (hooks.scroll) {\r\n hooks.scroll(...p);\r\n }\r\n scrollCb(...p);\r\n };\r\n o.viewportResizeCb = (...p) => {\r\n if (hooks.viewportResize) {\r\n hooks.viewportResize(...p);\r\n }\r\n viewportResizeCb(...p);\r\n };\r\n o.inputCb = (...p) => {\r\n if (hooks.input) {\r\n hooks.input(...p);\r\n }\r\n inputCb(...p);\r\n };\r\n o.mediaInteractionCb = (...p) => {\r\n if (hooks.mediaInteaction) {\r\n hooks.mediaInteaction(...p);\r\n }\r\n mediaInteractionCb(...p);\r\n };\r\n o.styleSheetRuleCb = (...p) => {\r\n if (hooks.styleSheetRule) {\r\n hooks.styleSheetRule(...p);\r\n }\r\n styleSheetRuleCb(...p);\r\n };\r\n o.styleDeclarationCb = (...p) => {\r\n if (hooks.styleDeclaration) {\r\n hooks.styleDeclaration(...p);\r\n }\r\n styleDeclarationCb(...p);\r\n };\r\n o.canvasMutationCb = (...p) => {\r\n if (hooks.canvasMutation) {\r\n hooks.canvasMutation(...p);\r\n }\r\n canvasMutationCb(...p);\r\n };\r\n o.fontCb = (...p) => {\r\n if (hooks.font) {\r\n hooks.font(...p);\r\n }\r\n fontCb(...p);\r\n };\r\n o.selectionCb = (...p) => {\r\n if (hooks.selection) {\r\n hooks.selection(...p);\r\n }\r\n selectionCb(...p);\r\n };\r\n o.customElementCb = (...c) => {\r\n if (hooks.customElement) {\r\n hooks.customElement(...c);\r\n }\r\n customElementCb(...c);\r\n };\r\n}\r\nfunction initObservers(o, hooks = {}) {\r\n const currentWindow = o.doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n };\r\n }\r\n mergeHooks(o, hooks);\r\n let mutationObserver;\r\n if (o.recordDOM) {\r\n mutationObserver = initMutationObserver(o, o.doc);\r\n }\r\n const mousemoveHandler = initMoveObserver(o);\r\n const mouseInteractionHandler = initMouseInteractionObserver(o);\r\n const scrollHandler = initScrollObserver(o);\r\n const viewportResizeHandler = initViewportResizeObserver(o, {\r\n win: currentWindow,\r\n });\r\n const inputHandler = initInputObserver(o);\r\n const mediaInteractionHandler = initMediaInteractionObserver(o);\r\n let styleSheetObserver = () => { };\r\n let adoptedStyleSheetObserver = () => { };\r\n let styleDeclarationObserver = () => { };\r\n let fontObserver = () => { };\r\n if (o.recordDOM) {\r\n styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\r\n adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\r\n styleDeclarationObserver = initStyleDeclarationObserver(o, {\r\n win: currentWindow,\r\n });\r\n if (o.collectFonts) {\r\n fontObserver = initFontObserver(o);\r\n }\r\n }\r\n const selectionObserver = initSelectionObserver(o);\r\n const customElementObserver = initCustomElementObserver(o);\r\n const pluginHandlers = [];\r\n for (const plugin of o.plugins) {\r\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\r\n }\r\n return callbackWrapper(() => {\r\n mutationBuffers.forEach((b) => b.reset());\r\n mutationObserver === null || mutationObserver === void 0 ? void 0 : mutationObserver.disconnect();\r\n mousemoveHandler();\r\n mouseInteractionHandler();\r\n scrollHandler();\r\n viewportResizeHandler();\r\n inputHandler();\r\n mediaInteractionHandler();\r\n styleSheetObserver();\r\n adoptedStyleSheetObserver();\r\n styleDeclarationObserver();\r\n fontObserver();\r\n selectionObserver();\r\n customElementObserver();\r\n pluginHandlers.forEach((h) => h());\r\n });\r\n}\r\nfunction hasNestedCSSRule(prop) {\r\n return typeof window[prop] !== 'undefined';\r\n}\r\nfunction canMonkeyPatchNestedCSSRule(prop) {\r\n return Boolean(typeof window[prop] !== 'undefined' &&\r\n window[prop].prototype &&\r\n 'insertRule' in window[prop].prototype &&\r\n 'deleteRule' in window[prop].prototype);\r\n}\n\nexport { INPUT_TAGS, initAdoptedStyleSheetObserver, initMutationObserver, initObservers, initScrollObserver, mutationBuffers };\n","class CrossOriginIframeMirror {\r\n constructor(generateIdFn) {\r\n this.generateIdFn = generateIdFn;\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n }\r\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\r\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\r\n let id = idToRemoteIdMap.get(remoteId);\r\n if (!id) {\r\n id = this.generateIdFn();\r\n idToRemoteIdMap.set(remoteId, id);\r\n remoteIdToIdMap.set(id, remoteId);\r\n }\r\n return id;\r\n }\r\n getIds(iframe, remoteId) {\r\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));\r\n }\r\n getRemoteId(iframe, id, map) {\r\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\r\n if (typeof id !== 'number')\r\n return id;\r\n const remoteId = remoteIdToIdMap.get(id);\r\n if (!remoteId)\r\n return -1;\r\n return remoteId;\r\n }\r\n getRemoteIds(iframe, ids) {\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\r\n }\r\n reset(iframe) {\r\n if (!iframe) {\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n return;\r\n }\r\n this.iframeIdToRemoteIdMap.delete(iframe);\r\n this.iframeRemoteIdToIdMap.delete(iframe);\r\n }\r\n getIdToRemoteIdMap(iframe) {\r\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\r\n if (!idToRemoteIdMap) {\r\n idToRemoteIdMap = new Map();\r\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\r\n }\r\n return idToRemoteIdMap;\r\n }\r\n getRemoteIdToIdMap(iframe) {\r\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\r\n if (!remoteIdToIdMap) {\r\n remoteIdToIdMap = new Map();\r\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\r\n }\r\n return remoteIdToIdMap;\r\n }\r\n}\n\nexport { CrossOriginIframeMirror as default };\n","import { genId, NodeType } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport CrossOriginIframeMirror from './cross-origin-iframe-mirror.js';\nimport { EventType, IncrementalSource } from '../../../types/dist/types.js';\n\nclass IframeManager {\r\n constructor(options) {\r\n this.iframes = new WeakMap();\r\n this.crossOriginIframeMap = new WeakMap();\r\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\r\n this.crossOriginIframeRootIdMap = new WeakMap();\r\n this.mutationCb = options.mutationCb;\r\n this.wrappedEmit = options.wrappedEmit;\r\n this.stylesheetManager = options.stylesheetManager;\r\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\r\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));\r\n this.mirror = options.mirror;\r\n if (this.recordCrossOriginIframes) {\r\n window.addEventListener('message', this.handleMessage.bind(this));\r\n }\r\n }\r\n addIframe(iframeEl) {\r\n this.iframes.set(iframeEl, true);\r\n if (iframeEl.contentWindow)\r\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\r\n }\r\n addLoadListener(cb) {\r\n this.loadListener = cb;\r\n }\r\n attachIframe(iframeEl, childSn) {\r\n var _a;\r\n this.mutationCb({\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: childSn,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n });\r\n (_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);\r\n if (iframeEl.contentDocument &&\r\n iframeEl.contentDocument.adoptedStyleSheets &&\r\n iframeEl.contentDocument.adoptedStyleSheets.length > 0)\r\n this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));\r\n }\r\n handleMessage(message) {\r\n const crossOriginMessageEvent = message;\r\n if (crossOriginMessageEvent.data.type !== 'rrweb' ||\r\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\r\n return;\r\n const iframeSourceWindow = message.source;\r\n if (!iframeSourceWindow)\r\n return;\r\n const iframeEl = this.crossOriginIframeMap.get(message.source);\r\n if (!iframeEl)\r\n return;\r\n const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);\r\n if (transformedEvent)\r\n this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);\r\n }\r\n transformCrossOriginEvent(iframeEl, e) {\r\n var _a;\r\n switch (e.type) {\r\n case EventType.FullSnapshot: {\r\n this.crossOriginIframeMirror.reset(iframeEl);\r\n this.crossOriginIframeStyleMirror.reset(iframeEl);\r\n this.replaceIdOnNode(e.data.node, iframeEl);\r\n const rootId = e.data.node.id;\r\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\r\n this.patchRootIdOnNode(e.data.node, rootId);\r\n return {\r\n timestamp: e.timestamp,\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Mutation,\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: e.data.node,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n },\r\n };\r\n }\r\n case EventType.Meta:\r\n case EventType.Load:\r\n case EventType.DomContentLoaded: {\r\n return false;\r\n }\r\n case EventType.Plugin: {\r\n return e;\r\n }\r\n case EventType.Custom: {\r\n this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);\r\n return e;\r\n }\r\n case EventType.IncrementalSnapshot: {\r\n switch (e.data.source) {\r\n case IncrementalSource.Mutation: {\r\n e.data.adds.forEach((n) => {\r\n this.replaceIds(n, iframeEl, [\r\n 'parentId',\r\n 'nextId',\r\n 'previousId',\r\n ]);\r\n this.replaceIdOnNode(n.node, iframeEl);\r\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\r\n rootId && this.patchRootIdOnNode(n.node, rootId);\r\n });\r\n e.data.removes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['parentId', 'id']);\r\n });\r\n e.data.attributes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n e.data.texts.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.Drag:\r\n case IncrementalSource.TouchMove:\r\n case IncrementalSource.MouseMove: {\r\n e.data.positions.forEach((p) => {\r\n this.replaceIds(p, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.ViewportResize: {\r\n return false;\r\n }\r\n case IncrementalSource.MediaInteraction:\r\n case IncrementalSource.MouseInteraction:\r\n case IncrementalSource.Scroll:\r\n case IncrementalSource.CanvasMutation:\r\n case IncrementalSource.Input: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n return e;\r\n }\r\n case IncrementalSource.StyleSheetRule:\r\n case IncrementalSource.StyleDeclaration: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleId']);\r\n return e;\r\n }\r\n case IncrementalSource.Font: {\r\n return e;\r\n }\r\n case IncrementalSource.Selection: {\r\n e.data.ranges.forEach((range) => {\r\n this.replaceIds(range, iframeEl, ['start', 'end']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.AdoptedStyleSheet: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleIds']);\r\n (_a = e.data.styles) === null || _a === void 0 ? void 0 : _a.forEach((style) => {\r\n this.replaceStyleIds(style, iframeEl, ['styleId']);\r\n });\r\n return e;\r\n }\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n replace(iframeMirror, obj, iframeEl, keys) {\r\n for (const key of keys) {\r\n if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')\r\n continue;\r\n if (Array.isArray(obj[key])) {\r\n obj[key] = iframeMirror.getIds(iframeEl, obj[key]);\r\n }\r\n else {\r\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\r\n }\r\n }\r\n return obj;\r\n }\r\n replaceIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\r\n }\r\n replaceStyleIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\r\n }\r\n replaceIdOnNode(node, iframeEl) {\r\n this.replaceIds(node, iframeEl, ['id', 'rootId']);\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.replaceIdOnNode(child, iframeEl);\r\n });\r\n }\r\n }\r\n patchRootIdOnNode(node, rootId) {\r\n if (node.type !== NodeType.Document && !node.rootId)\r\n node.rootId = rootId;\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.patchRootIdOnNode(child, rootId);\r\n });\r\n }\r\n }\r\n}\n\nexport { IframeManager };\n","import { initMutationObserver, initScrollObserver, initAdoptedStyleSheetObserver } from './observer.js';\nimport { patch, inDom } from '../utils.js';\nimport { isNativeShadowDom } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nclass ShadowDomManager {\r\n constructor(options) {\r\n this.shadowDoms = new WeakSet();\r\n this.restoreHandlers = [];\r\n this.mutationCb = options.mutationCb;\r\n this.scrollCb = options.scrollCb;\r\n this.bypassOptions = options.bypassOptions;\r\n this.mirror = options.mirror;\r\n this.init();\r\n }\r\n init() {\r\n this.reset();\r\n this.patchAttachShadow(Element, document);\r\n }\r\n addShadowRoot(shadowRoot, doc) {\r\n if (!isNativeShadowDom(shadowRoot))\r\n return;\r\n if (this.shadowDoms.has(shadowRoot))\r\n return;\r\n this.shadowDoms.add(shadowRoot);\r\n const observer = initMutationObserver(Object.assign(Object.assign({}, this.bypassOptions), { doc, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }), shadowRoot);\r\n this.restoreHandlers.push(() => observer.disconnect());\r\n this.restoreHandlers.push(initScrollObserver(Object.assign(Object.assign({}, this.bypassOptions), { scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror })));\r\n setTimeout(() => {\r\n if (shadowRoot.adoptedStyleSheets &&\r\n shadowRoot.adoptedStyleSheets.length > 0)\r\n this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));\r\n this.restoreHandlers.push(initAdoptedStyleSheetObserver({\r\n mirror: this.mirror,\r\n stylesheetManager: this.bypassOptions.stylesheetManager,\r\n }, shadowRoot));\r\n }, 0);\r\n }\r\n observeAttachShadow(iframeElement) {\r\n if (!iframeElement.contentWindow || !iframeElement.contentDocument)\r\n return;\r\n this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);\r\n }\r\n patchAttachShadow(element, doc) {\r\n const manager = this;\r\n this.restoreHandlers.push(patch(element.prototype, 'attachShadow', function (original) {\r\n return function (option) {\r\n const shadowRoot = original.call(this, option);\r\n if (this.shadowRoot && inDom(this))\r\n manager.addShadowRoot(this.shadowRoot, doc);\r\n return shadowRoot;\r\n };\r\n }));\r\n }\r\n reset() {\r\n this.restoreHandlers.forEach((handler) => {\r\n try {\r\n handler();\r\n }\r\n catch (e) {\r\n }\r\n });\r\n this.restoreHandlers = [];\r\n this.shadowDoms = new WeakSet();\r\n }\r\n}\n\nexport { ShadowDomManager };\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\n\nexport { __awaiter, __rest };\n","/*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2021 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n","import { encode } from './../../../../../../ext/base64-arraybuffer/dist/base64-arraybuffer.es5.js';\n\nconst canvasVarMap = new Map();\r\nfunction variableListFor(ctx, ctor) {\r\n let contextMap = canvasVarMap.get(ctx);\r\n if (!contextMap) {\r\n contextMap = new Map();\r\n canvasVarMap.set(ctx, contextMap);\r\n }\r\n if (!contextMap.has(ctor)) {\r\n contextMap.set(ctor, []);\r\n }\r\n return contextMap.get(ctor);\r\n}\r\nconst saveWebGLVar = (value, win, ctx) => {\r\n if (!value ||\r\n !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))\r\n return;\r\n const name = value.constructor.name;\r\n const list = variableListFor(ctx, name);\r\n let index = list.indexOf(value);\r\n if (index === -1) {\r\n index = list.length;\r\n list.push(value);\r\n }\r\n return index;\r\n};\r\nfunction serializeArg(value, win, ctx) {\r\n if (value instanceof Array) {\r\n return value.map((arg) => serializeArg(arg, win, ctx));\r\n }\r\n else if (value === null) {\r\n return value;\r\n }\r\n else if (value instanceof Float32Array ||\r\n value instanceof Float64Array ||\r\n value instanceof Int32Array ||\r\n value instanceof Uint32Array ||\r\n value instanceof Uint8Array ||\r\n value instanceof Uint16Array ||\r\n value instanceof Int16Array ||\r\n value instanceof Int8Array ||\r\n value instanceof Uint8ClampedArray) {\r\n const name = value.constructor.name;\r\n return {\r\n rr_type: name,\r\n args: [Object.values(value)],\r\n };\r\n }\r\n else if (value instanceof ArrayBuffer) {\r\n const name = value.constructor.name;\r\n const base64 = encode(value);\r\n return {\r\n rr_type: name,\r\n base64,\r\n };\r\n }\r\n else if (value instanceof DataView) {\r\n const name = value.constructor.name;\r\n return {\r\n rr_type: name,\r\n args: [\r\n serializeArg(value.buffer, win, ctx),\r\n value.byteOffset,\r\n value.byteLength,\r\n ],\r\n };\r\n }\r\n else if (value instanceof HTMLImageElement) {\r\n const name = value.constructor.name;\r\n const { src } = value;\r\n return {\r\n rr_type: name,\r\n src,\r\n };\r\n }\r\n else if (value instanceof HTMLCanvasElement) {\r\n const name = 'HTMLImageElement';\r\n const src = value.toDataURL();\r\n return {\r\n rr_type: name,\r\n src,\r\n };\r\n }\r\n else if (value instanceof ImageData) {\r\n const name = value.constructor.name;\r\n return {\r\n rr_type: name,\r\n args: [serializeArg(value.data, win, ctx), value.width, value.height],\r\n };\r\n }\r\n else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {\r\n const name = value.constructor.name;\r\n const index = saveWebGLVar(value, win, ctx);\r\n return {\r\n rr_type: name,\r\n index: index,\r\n };\r\n }\r\n return value;\r\n}\r\nconst serializeArgs = (args, win, ctx) => {\r\n return args.map((arg) => serializeArg(arg, win, ctx));\r\n};\r\nconst isInstanceOfWebGLObject = (value, win) => {\r\n const webGLConstructorNames = [\r\n 'WebGLActiveInfo',\r\n 'WebGLBuffer',\r\n 'WebGLFramebuffer',\r\n 'WebGLProgram',\r\n 'WebGLRenderbuffer',\r\n 'WebGLShader',\r\n 'WebGLShaderPrecisionFormat',\r\n 'WebGLTexture',\r\n 'WebGLUniformLocation',\r\n 'WebGLVertexArrayObject',\r\n 'WebGLVertexArrayObjectOES',\r\n ];\r\n const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === 'function');\r\n return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));\r\n};\n\nexport { isInstanceOfWebGLObject, saveWebGLVar, serializeArg, serializeArgs, variableListFor };\n","import { patch, isBlocked } from '../../../utils.js';\n\nfunction getNormalizedContextName(contextType) {\r\n return contextType === 'experimental-webgl' ? 'webgl' : contextType;\r\n}\r\nfunction initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {\r\n const handlers = [];\r\n try {\r\n const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {\r\n return function (contextType, ...args) {\r\n if (!isBlocked(this, blockClass, blockSelector, true)) {\r\n const ctxName = getNormalizedContextName(contextType);\r\n if (!('__context' in this))\r\n this.__context = ctxName;\r\n if (setPreserveDrawingBufferToTrue &&\r\n ['webgl', 'webgl2'].includes(ctxName)) {\r\n if (args[0] && typeof args[0] === 'object') {\r\n const contextAttributes = args[0];\r\n if (!contextAttributes.preserveDrawingBuffer) {\r\n contextAttributes.preserveDrawingBuffer = true;\r\n }\r\n }\r\n else {\r\n args.splice(0, 1, {\r\n preserveDrawingBuffer: true,\r\n });\r\n }\r\n }\r\n }\r\n return original.apply(this, [contextType, ...args]);\r\n };\r\n });\r\n handlers.push(restoreHandler);\r\n }\r\n catch (_a) {\r\n console.error('failed to patch HTMLCanvasElement.prototype.getContext');\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n}\n\nexport { initCanvasContextObserver as default };\n","import { CanvasContext } from '../../../../../types/dist/types.js';\nimport { patch, isBlocked, hookSetter } from '../../../utils.js';\nimport { saveWebGLVar, serializeArgs } from './serialize-args.js';\n\nfunction patchGLPrototype(prototype, type, cb, blockClass, blockSelector, mirror, win) {\r\n const handlers = [];\r\n const props = Object.getOwnPropertyNames(prototype);\r\n for (const prop of props) {\r\n if ([\r\n 'isContextLost',\r\n 'canvas',\r\n 'drawingBufferWidth',\r\n 'drawingBufferHeight',\r\n ].includes(prop)) {\r\n continue;\r\n }\r\n try {\r\n if (typeof prototype[prop] !== 'function') {\r\n continue;\r\n }\r\n const restoreHandler = patch(prototype, prop, function (original) {\r\n return function (...args) {\r\n const result = original.apply(this, args);\r\n saveWebGLVar(result, win, this);\r\n if ('tagName' in this.canvas &&\r\n !isBlocked(this.canvas, blockClass, blockSelector, true)) {\r\n const recordArgs = serializeArgs(args, win, this);\r\n const mutation = {\r\n type,\r\n property: prop,\r\n args: recordArgs,\r\n };\r\n cb(this.canvas, mutation);\r\n }\r\n return result;\r\n };\r\n });\r\n handlers.push(restoreHandler);\r\n }\r\n catch (_a) {\r\n const hookHandler = hookSetter(prototype, prop, {\r\n set(v) {\r\n cb(this.canvas, {\r\n type,\r\n property: prop,\r\n args: [v],\r\n setter: true,\r\n });\r\n },\r\n });\r\n handlers.push(hookHandler);\r\n }\r\n }\r\n return handlers;\r\n}\r\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, mirror) {\r\n const handlers = [];\r\n handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, mirror, win));\r\n if (typeof win.WebGL2RenderingContext !== 'undefined') {\r\n handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, mirror, win));\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n}\n\nexport { initCanvasWebGLMutationObserver as default };\n","function decodeBase64(base64, enableUnicode) {\n var binaryString = atob(base64);\n if (enableUnicode) {\n var binaryView = new Uint8Array(binaryString.length);\n for (var i = 0, n = binaryString.length; i < n; ++i) {\n binaryView[i] = binaryString.charCodeAt(i);\n }\n return String.fromCharCode.apply(null, new Uint16Array(binaryView.buffer));\n }\n return binaryString;\n}\n\nfunction createURL(base64, sourcemapArg, enableUnicodeArg) {\n var sourcemap = sourcemapArg === undefined ? null : sourcemapArg;\n var enableUnicode = enableUnicodeArg === undefined ? false : enableUnicodeArg;\n var source = decodeBase64(base64, enableUnicode);\n var start = source.indexOf('\\n', 10) + 1;\n var body = source.substring(start) + (sourcemap ? '\\/\\/# sourceMappingURL=' + sourcemap : '');\n var blob = new Blob([body], { type: 'application/javascript' });\n return URL.createObjectURL(blob);\n}\n\nfunction createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) {\n var url;\n return function WorkerFactory(options) {\n url = url || createURL(base64, sourcemapArg, enableUnicodeArg);\n return new Worker(url, options);\n };\n}\n\nexport { createBase64WorkerFactory };","import { createBase64WorkerFactory } from './_rollup-plugin-web-worker-loader__helper__browser__createBase64WorkerFactory.js';\n\nvar WorkerFactory = createBase64WorkerFactory('Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=', null, false);\n/* eslint-enable */\n\nexport { WorkerFactory as default };\n","import { createMirror, snapshot } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { initObservers, mutationBuffers } from './observer.js';\nimport { polyfill, nowTimestamp, on, getWindowWidth, getWindowHeight, getWindowScroll, isSerializedIframe, isSerializedStylesheet, hasShadowRoot } from '../utils.js';\nimport { EventType, IncrementalSource } from '../../../types/dist/types.js';\nimport { IframeManager } from './iframe-manager.js';\nimport { ShadowDomManager } from './shadow-dom-manager.js';\nimport { CanvasManager } from './observers/canvas/canvas-manager.js';\nimport { StylesheetManager } from './stylesheet-manager.js';\nimport ProcessedNodeManager from './processed-node-manager.js';\nimport { callbackWrapper, unregisterErrorHandler, registerErrorHandler } from './error-handler.js';\n\nfunction wrapEvent(e) {\r\n return Object.assign(Object.assign({}, e), { timestamp: nowTimestamp() });\r\n}\r\nlet wrappedEmit;\r\nlet takeFullSnapshot;\r\nlet canvasManager;\r\nlet recording = false;\r\nconst mirror = createMirror();\r\nfunction record(options = {}) {\r\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskInputFn, maskTextFn, hooks, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordDOM = true, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options.recordAfter === 'DOMContentLoaded'\r\n ? options.recordAfter\r\n : 'load', userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), errorHandler, } = options;\r\n registerErrorHandler(errorHandler);\r\n const inEmittingFrame = recordCrossOriginIframes\r\n ? window.parent === window\r\n : true;\r\n let passEmitsToParent = false;\r\n if (!inEmittingFrame) {\r\n try {\r\n if (window.parent.document) {\r\n passEmitsToParent = false;\r\n }\r\n }\r\n catch (e) {\r\n passEmitsToParent = true;\r\n }\r\n }\r\n if (inEmittingFrame && !emit) {\r\n throw new Error('emit function is required');\r\n }\r\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\r\n sampling.mousemove = mousemoveWait;\r\n }\r\n mirror.reset();\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n password: true,\r\n }\r\n : _maskInputOptions !== undefined\r\n ? _maskInputOptions\r\n : { password: true };\r\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\r\n ? {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaVerification: true,\r\n headMetaAuthorship: _slimDOMOptions === 'all',\r\n headMetaDescKeywords: _slimDOMOptions === 'all',\r\n }\r\n : _slimDOMOptions\r\n ? _slimDOMOptions\r\n : {};\r\n polyfill();\r\n let lastFullSnapshotEvent;\r\n let incrementalSnapshotCount = 0;\r\n const eventProcessor = (e) => {\r\n for (const plugin of plugins || []) {\r\n if (plugin.eventProcessor) {\r\n e = plugin.eventProcessor(e);\r\n }\r\n }\r\n if (packFn &&\r\n !passEmitsToParent) {\r\n e = packFn(e);\r\n }\r\n return e;\r\n };\r\n wrappedEmit = (e, isCheckout) => {\r\n var _a;\r\n if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) &&\r\n e.type !== EventType.FullSnapshot &&\r\n !(e.type === EventType.IncrementalSnapshot &&\r\n e.data.source === IncrementalSource.Mutation)) {\r\n mutationBuffers.forEach((buf) => buf.unfreeze());\r\n }\r\n if (inEmittingFrame) {\r\n emit === null || emit === void 0 ? void 0 : emit(eventProcessor(e), isCheckout);\r\n }\r\n else if (passEmitsToParent) {\r\n const message = {\r\n type: 'rrweb',\r\n event: eventProcessor(e),\r\n origin: window.location.origin,\r\n isCheckout,\r\n };\r\n window.parent.postMessage(message, '*');\r\n }\r\n if (e.type === EventType.FullSnapshot) {\r\n lastFullSnapshotEvent = e;\r\n incrementalSnapshotCount = 0;\r\n }\r\n else if (e.type === EventType.IncrementalSnapshot) {\r\n if (e.data.source === IncrementalSource.Mutation &&\r\n e.data.isAttachIframe) {\r\n return;\r\n }\r\n incrementalSnapshotCount++;\r\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\r\n const exceedTime = checkoutEveryNms &&\r\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\r\n if (exceedCount || exceedTime) {\r\n takeFullSnapshot(true);\r\n }\r\n }\r\n };\r\n const wrappedMutationEmit = (m) => {\r\n wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.Mutation }, m),\r\n }));\r\n };\r\n const wrappedScrollEmit = (p) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.Scroll }, p),\r\n }));\r\n const wrappedCanvasMutationEmit = (p) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.CanvasMutation }, p),\r\n }));\r\n const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.AdoptedStyleSheet }, a),\r\n }));\r\n const stylesheetManager = new StylesheetManager({\r\n mutationCb: wrappedMutationEmit,\r\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,\r\n });\r\n const iframeManager = new IframeManager({\r\n mirror,\r\n mutationCb: wrappedMutationEmit,\r\n stylesheetManager: stylesheetManager,\r\n recordCrossOriginIframes,\r\n wrappedEmit,\r\n });\r\n for (const plugin of plugins || []) {\r\n if (plugin.getMirror)\r\n plugin.getMirror({\r\n nodeMirror: mirror,\r\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\r\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,\r\n });\r\n }\r\n const processedNodeManager = new ProcessedNodeManager();\r\n canvasManager = new CanvasManager({\r\n recordCanvas,\r\n mutationCb: wrappedCanvasMutationEmit,\r\n win: window,\r\n blockClass,\r\n blockSelector,\r\n mirror,\r\n sampling: sampling.canvas,\r\n dataURLOptions,\r\n });\r\n const shadowDomManager = new ShadowDomManager({\r\n mutationCb: wrappedMutationEmit,\r\n scrollCb: wrappedScrollEmit,\r\n bypassOptions: {\r\n blockClass,\r\n blockSelector,\r\n maskTextClass,\r\n maskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n dataURLOptions,\r\n maskTextFn,\r\n maskInputFn,\r\n recordCanvas,\r\n inlineImages,\r\n sampling,\r\n slimDOMOptions,\r\n iframeManager,\r\n stylesheetManager,\r\n canvasManager,\r\n keepIframeSrcFn,\r\n processedNodeManager,\r\n },\r\n mirror,\r\n });\r\n takeFullSnapshot = (isCheckout = false) => {\r\n if (!recordDOM) {\r\n return;\r\n }\r\n wrappedEmit(wrapEvent({\r\n type: EventType.Meta,\r\n data: {\r\n href: window.location.href,\r\n width: getWindowWidth(),\r\n height: getWindowHeight(),\r\n },\r\n }), isCheckout);\r\n stylesheetManager.reset();\r\n shadowDomManager.init();\r\n mutationBuffers.forEach((buf) => buf.lock());\r\n const node = snapshot(document, {\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskTextClass,\r\n maskTextSelector,\r\n inlineStylesheet,\r\n maskAllInputs: maskInputOptions,\r\n maskTextFn,\r\n slimDOM: slimDOMOptions,\r\n dataURLOptions,\r\n recordCanvas,\r\n inlineImages,\r\n onSerialize: (n) => {\r\n if (isSerializedIframe(n, mirror)) {\r\n iframeManager.addIframe(n);\r\n }\r\n if (isSerializedStylesheet(n, mirror)) {\r\n stylesheetManager.trackLinkElement(n);\r\n }\r\n if (hasShadowRoot(n)) {\r\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n iframeManager.attachIframe(iframe, childSn);\r\n shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (linkEl, childSn) => {\r\n stylesheetManager.attachLinkElement(linkEl, childSn);\r\n },\r\n keepIframeSrcFn,\r\n });\r\n if (!node) {\r\n return console.warn('Failed to snapshot the document');\r\n }\r\n wrappedEmit(wrapEvent({\r\n type: EventType.FullSnapshot,\r\n data: {\r\n node,\r\n initialOffset: getWindowScroll(window),\r\n },\r\n }), isCheckout);\r\n mutationBuffers.forEach((buf) => buf.unlock());\r\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\r\n stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));\r\n };\r\n try {\r\n const handlers = [];\r\n const observe = (doc) => {\r\n var _a;\r\n return callbackWrapper(initObservers)({\r\n mutationCb: wrappedMutationEmit,\r\n mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source,\r\n positions,\r\n },\r\n })),\r\n mouseInteractionCb: (d) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.MouseInteraction }, d),\r\n })),\r\n scrollCb: wrappedScrollEmit,\r\n viewportResizeCb: (d) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.ViewportResize }, d),\r\n })),\r\n inputCb: (v) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.Input }, v),\r\n })),\r\n mediaInteractionCb: (p) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.MediaInteraction }, p),\r\n })),\r\n styleSheetRuleCb: (r) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.StyleSheetRule }, r),\r\n })),\r\n styleDeclarationCb: (r) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.StyleDeclaration }, r),\r\n })),\r\n canvasMutationCb: wrappedCanvasMutationEmit,\r\n fontCb: (p) => wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.Font }, p),\r\n })),\r\n selectionCb: (p) => {\r\n wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.Selection }, p),\r\n }));\r\n },\r\n customElementCb: (c) => {\r\n wrappedEmit(wrapEvent({\r\n type: EventType.IncrementalSnapshot,\r\n data: Object.assign({ source: IncrementalSource.CustomElement }, c),\r\n }));\r\n },\r\n blockClass,\r\n ignoreClass,\r\n ignoreSelector,\r\n maskTextClass,\r\n maskTextSelector,\r\n maskInputOptions,\r\n inlineStylesheet,\r\n sampling,\r\n recordDOM,\r\n recordCanvas,\r\n inlineImages,\r\n userTriggeredOnInput,\r\n collectFonts,\r\n doc,\r\n maskInputFn,\r\n maskTextFn,\r\n keepIframeSrcFn,\r\n blockSelector,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n mirror,\r\n iframeManager,\r\n stylesheetManager,\r\n shadowDomManager,\r\n processedNodeManager,\r\n canvasManager,\r\n ignoreCSSAttributes,\r\n plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter((p) => p.observer)) === null || _a === void 0 ? void 0 : _a.map((p) => ({\r\n observer: p.observer,\r\n options: p.options,\r\n callback: (payload) => wrappedEmit(wrapEvent({\r\n type: EventType.Plugin,\r\n data: {\r\n plugin: p.name,\r\n payload,\r\n },\r\n })),\r\n }))) || [],\r\n }, hooks);\r\n };\r\n iframeManager.addLoadListener((iframeEl) => {\r\n try {\r\n handlers.push(observe(iframeEl.contentDocument));\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n });\r\n const init = () => {\r\n takeFullSnapshot();\r\n handlers.push(observe(document));\r\n recording = true;\r\n };\r\n if (document.readyState === 'interactive' ||\r\n document.readyState === 'complete') {\r\n init();\r\n }\r\n else {\r\n handlers.push(on('DOMContentLoaded', () => {\r\n wrappedEmit(wrapEvent({\r\n type: EventType.DomContentLoaded,\r\n data: {},\r\n }));\r\n if (recordAfter === 'DOMContentLoaded')\r\n init();\r\n }));\r\n handlers.push(on('load', () => {\r\n wrappedEmit(wrapEvent({\r\n type: EventType.Load,\r\n data: {},\r\n }));\r\n if (recordAfter === 'load')\r\n init();\r\n }, window));\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n processedNodeManager.destroy();\r\n recording = false;\r\n unregisterErrorHandler();\r\n };\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n}\r\nrecord.addCustomEvent = (tag, payload) => {\r\n if (!recording) {\r\n throw new Error('please add custom event after start recording');\r\n }\r\n wrappedEmit(wrapEvent({\r\n type: EventType.Custom,\r\n data: {\r\n tag,\r\n payload,\r\n },\r\n }));\r\n};\r\nrecord.freezePage = () => {\r\n mutationBuffers.forEach((buf) => buf.freeze());\r\n};\r\nrecord.takeFullSnapshot = (isCheckout) => {\r\n if (!recording) {\r\n throw new Error('please take full snapshot after start recording');\r\n }\r\n takeFullSnapshot(isCheckout);\r\n};\r\nrecord.mirror = mirror;\n\nexport { record as default };\n","import { __rest, __awaiter } from './../../../../../../ext/tslib/tslib.es6.js';\nimport { isBlocked } from '../../../utils.js';\nimport { CanvasContext } from '../../../../../types/dist/types.js';\nimport initCanvas2DMutationObserver from './2d.js';\nimport initCanvasContextObserver from './canvas.js';\nimport initCanvasWebGLMutationObserver from './webgl.js';\nimport WorkerFactory from '../../../../../../_virtual/image-bitmap-data-url-worker.js';\n\nclass CanvasManager {\r\n reset() {\r\n this.pendingCanvasMutations.clear();\r\n this.resetObservers && this.resetObservers();\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n }\r\n lock() {\r\n this.locked = true;\r\n }\r\n unlock() {\r\n this.locked = false;\r\n }\r\n constructor(options) {\r\n this.pendingCanvasMutations = new Map();\r\n this.rafStamps = { latestId: 0, invokeId: null };\r\n this.frozen = false;\r\n this.locked = false;\r\n this.processMutation = (target, mutation) => {\r\n const newFrame = this.rafStamps.invokeId &&\r\n this.rafStamps.latestId !== this.rafStamps.invokeId;\r\n if (newFrame || !this.rafStamps.invokeId)\r\n this.rafStamps.invokeId = this.rafStamps.latestId;\r\n if (!this.pendingCanvasMutations.has(target)) {\r\n this.pendingCanvasMutations.set(target, []);\r\n }\r\n this.pendingCanvasMutations.get(target).push(mutation);\r\n };\r\n const { sampling = 'all', win, blockClass, blockSelector, recordCanvas, dataURLOptions, } = options;\r\n this.mutationCb = options.mutationCb;\r\n this.mirror = options.mirror;\r\n if (recordCanvas && sampling === 'all')\r\n this.initCanvasMutationObserver(win, blockClass, blockSelector);\r\n if (recordCanvas && typeof sampling === 'number')\r\n this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {\r\n dataURLOptions,\r\n });\r\n }\r\n initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, true);\r\n const snapshotInProgressMap = new Map();\r\n const worker = new WorkerFactory();\r\n worker.onmessage = (e) => {\r\n const { id } = e.data;\r\n snapshotInProgressMap.set(id, false);\r\n if (!('base64' in e.data))\r\n return;\r\n const { base64, type, width, height } = e.data;\r\n this.mutationCb({\r\n id,\r\n type: CanvasContext['2D'],\r\n commands: [\r\n {\r\n property: 'clearRect',\r\n args: [0, 0, width, height],\r\n },\r\n {\r\n property: 'drawImage',\r\n args: [\r\n {\r\n rr_type: 'ImageBitmap',\r\n args: [\r\n {\r\n rr_type: 'Blob',\r\n data: [{ rr_type: 'ArrayBuffer', base64 }],\r\n type,\r\n },\r\n ],\r\n },\r\n 0,\r\n 0,\r\n ],\r\n },\r\n ],\r\n });\r\n };\r\n const timeBetweenSnapshots = 1000 / fps;\r\n let lastSnapshotTime = 0;\r\n let rafId;\r\n const getCanvas = () => {\r\n const matchedCanvas = [];\r\n\r\n const searchCanvas = (root) => {\r\n root.querySelectorAll('canvas').forEach((canvas) => {\r\n if (!isBlocked(canvas, blockClass, blockSelector, true)) {\r\n matchedCanvas.push(canvas);\r\n }\r\n });\r\n root.querySelectorAll('*').forEach((elem) => {\r\n if (elem.shadowRoot) {\r\n searchCanvas(elem.shadowRoot);\r\n }\r\n });\r\n };\r\n \r\n searchCanvas(win.document);\r\n return matchedCanvas;\r\n };\r\n const takeCanvasSnapshots = (timestamp) => {\r\n if (lastSnapshotTime &&\r\n timestamp - lastSnapshotTime < timeBetweenSnapshots) {\r\n rafId = requestAnimationFrame(takeCanvasSnapshots);\r\n return;\r\n }\r\n lastSnapshotTime = timestamp;\r\n getCanvas()\r\n .forEach((canvas) => __awaiter(this, void 0, void 0, function* () {\r\n var _a;\r\n const id = this.mirror.getId(canvas);\r\n if (snapshotInProgressMap.get(id))\r\n return;\r\n if (canvas.width === 0 || canvas.height === 0)\r\n return;\r\n snapshotInProgressMap.set(id, true);\r\n if (['webgl', 'webgl2'].includes(canvas.__context)) {\r\n const context = canvas.getContext(canvas.__context);\r\n if (((_a = context === null || context === void 0 ? void 0 : context.getContextAttributes()) === null || _a === void 0 ? void 0 : _a.preserveDrawingBuffer) === false) {\r\n context.clear(context.COLOR_BUFFER_BIT);\r\n }\r\n }\r\n\r\n // createImageBitmap throws if resizing to 0\r\n // Fallback to intrinsic size if canvas has not yet rendered\r\n const width = canvas.clientWidth || canvas.width;\r\n const height = canvas.clientHeight || canvas.height;\r\n\r\n const bitmap = yield createImageBitmap(canvas, {\r\n resizeWidth: width,\r\n resizeHeight: height\r\n })\r\n\r\n worker.postMessage({\r\n id,\r\n bitmap,\r\n width: width,\r\n height: height,\r\n dataURLOptions: options.dataURLOptions,\r\n }, [bitmap]);\r\n }));\r\n rafId = requestAnimationFrame(takeCanvasSnapshots);\r\n };\r\n rafId = requestAnimationFrame(takeCanvasSnapshots);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n initCanvasMutationObserver(win, blockClass, blockSelector) {\r\n this.startRAFTimestamping();\r\n this.startPendingCanvasMutationFlusher();\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, false);\r\n const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);\r\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, this.mirror);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n canvas2DReset();\r\n canvasWebGL1and2Reset();\r\n };\r\n }\r\n startPendingCanvasMutationFlusher() {\r\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n startRAFTimestamping() {\r\n const setLatestRAFTimestamp = (timestamp) => {\r\n this.rafStamps.latestId = timestamp;\r\n requestAnimationFrame(setLatestRAFTimestamp);\r\n };\r\n requestAnimationFrame(setLatestRAFTimestamp);\r\n }\r\n flushPendingCanvasMutations() {\r\n this.pendingCanvasMutations.forEach((values, canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n this.flushPendingCanvasMutationFor(canvas, id);\r\n });\r\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n flushPendingCanvasMutationFor(canvas, id) {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\r\n if (!valuesWithType || id === -1)\r\n return;\r\n const values = valuesWithType.map((value) => {\r\n const rest = __rest(value, [\"type\"]);\r\n return rest;\r\n });\r\n const { type } = valuesWithType[0];\r\n this.mutationCb({ id, type, commands: values });\r\n this.pendingCanvasMutations.delete(canvas);\r\n }\r\n}\n\nexport { CanvasManager };\n","import { CanvasContext } from '../../../../../types/dist/types.js';\nimport { patch, isBlocked, hookSetter } from '../../../utils.js';\nimport { serializeArgs } from './serialize-args.js';\n\nfunction initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {\r\n const handlers = [];\r\n const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);\r\n for (const prop of props2D) {\r\n try {\r\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {\r\n continue;\r\n }\r\n const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {\r\n return function (...args) {\r\n if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {\r\n setTimeout(() => {\r\n const recordArgs = serializeArgs(args, win, this);\r\n cb(this.canvas, {\r\n type: CanvasContext['2D'],\r\n property: prop,\r\n args: recordArgs,\r\n });\r\n }, 0);\r\n }\r\n return original.apply(this, args);\r\n };\r\n });\r\n handlers.push(restoreHandler);\r\n }\r\n catch (_a) {\r\n const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {\r\n set(v) {\r\n cb(this.canvas, {\r\n type: CanvasContext['2D'],\r\n property: prop,\r\n args: [v],\r\n setter: true,\r\n });\r\n },\r\n });\r\n handlers.push(hookHandler);\r\n }\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n}\n\nexport { initCanvas2DMutationObserver as default };\n","import { stringifyRule } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { StyleSheetMirror } from '../utils.js';\n\nclass StylesheetManager {\r\n constructor(options) {\r\n this.trackedLinkElements = new WeakSet();\r\n this.styleMirror = new StyleSheetMirror();\r\n this.mutationCb = options.mutationCb;\r\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\r\n }\r\n attachLinkElement(linkEl, childSn) {\r\n if ('_cssText' in childSn.attributes)\r\n this.mutationCb({\r\n adds: [],\r\n removes: [],\r\n texts: [],\r\n attributes: [\r\n {\r\n id: childSn.id,\r\n attributes: childSn\r\n .attributes,\r\n },\r\n ],\r\n });\r\n this.trackLinkElement(linkEl);\r\n }\r\n trackLinkElement(linkEl) {\r\n if (this.trackedLinkElements.has(linkEl))\r\n return;\r\n this.trackedLinkElements.add(linkEl);\r\n this.trackStylesheetInLinkElement(linkEl);\r\n }\r\n adoptStyleSheets(sheets, hostId) {\r\n if (sheets.length === 0)\r\n return;\r\n const adoptedStyleSheetData = {\r\n id: hostId,\r\n styleIds: [],\r\n };\r\n const styles = [];\r\n for (const sheet of sheets) {\r\n let styleId;\r\n if (!this.styleMirror.has(sheet)) {\r\n styleId = this.styleMirror.add(sheet);\r\n styles.push({\r\n styleId,\r\n rules: Array.from(sheet.rules || CSSRule, (r, index) => ({\r\n rule: stringifyRule(r),\r\n index,\r\n })),\r\n });\r\n }\r\n else\r\n styleId = this.styleMirror.getId(sheet);\r\n adoptedStyleSheetData.styleIds.push(styleId);\r\n }\r\n if (styles.length > 0)\r\n adoptedStyleSheetData.styles = styles;\r\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\r\n }\r\n reset() {\r\n this.styleMirror.reset();\r\n this.trackedLinkElements = new WeakSet();\r\n }\r\n trackStylesheetInLinkElement(linkEl) {\r\n }\r\n}\n\nexport { StylesheetManager };\n","class ProcessedNodeManager {\r\n constructor() {\r\n this.nodeMap = new WeakMap();\r\n this.loop = true;\r\n this.periodicallyClear();\r\n }\r\n periodicallyClear() {\r\n requestAnimationFrame(() => {\r\n this.clear();\r\n if (this.loop)\r\n this.periodicallyClear();\r\n });\r\n }\r\n inOtherBuffer(node, thisBuffer) {\r\n const buffers = this.nodeMap.get(node);\r\n return (buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer));\r\n }\r\n add(node, buffer) {\r\n this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));\r\n }\r\n clear() {\r\n this.nodeMap = new WeakMap();\r\n }\r\n destroy() {\r\n this.loop = false;\r\n }\r\n}\n\nexport { ProcessedNodeManager as default };\n","class StackFrame {\r\n constructor(obj) {\r\n this.fileName = obj.fileName || '';\r\n this.functionName = obj.functionName || '';\r\n this.lineNumber = obj.lineNumber;\r\n this.columnNumber = obj.columnNumber;\r\n }\r\n toString() {\r\n const lineNumber = this.lineNumber || '';\r\n const columnNumber = this.columnNumber || '';\r\n if (this.functionName)\r\n return `${this.functionName} (${this.fileName}:${lineNumber}:${columnNumber})`;\r\n return `${this.fileName}:${lineNumber}:${columnNumber}`;\r\n }\r\n}\r\nconst FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\\S+:\\d+/;\r\nconst CHROME_IE_STACK_REGEXP = /^\\s*at .*(\\S+:\\d+|\\(native\\))/m;\r\nconst SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\\[native code])?$/;\r\nconst ErrorStackParser = {\r\n parse: function (error) {\r\n if (!error) {\r\n return [];\r\n }\r\n if (typeof error.stacktrace !== 'undefined' ||\r\n typeof error['opera#sourceloc'] !== 'undefined') {\r\n return this.parseOpera(error);\r\n }\r\n else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {\r\n return this.parseV8OrIE(error);\r\n }\r\n else if (error.stack) {\r\n return this.parseFFOrSafari(error);\r\n }\r\n else {\r\n console.warn('[console-record-plugin]: Failed to parse error object:', error);\r\n return [];\r\n }\r\n },\r\n extractLocation: function (urlLike) {\r\n if (urlLike.indexOf(':') === -1) {\r\n return [urlLike];\r\n }\r\n const regExp = /(.+?)(?::(\\d+))?(?::(\\d+))?$/;\r\n const parts = regExp.exec(urlLike.replace(/[()]/g, ''));\r\n if (!parts)\r\n throw new Error(`Cannot parse given url: ${urlLike}`);\r\n return [parts[1], parts[2] || undefined, parts[3] || undefined];\r\n },\r\n parseV8OrIE: function (error) {\r\n const filtered = error.stack.split('\\n').filter(function (line) {\r\n return !!line.match(CHROME_IE_STACK_REGEXP);\r\n }, this);\r\n return filtered.map(function (line) {\r\n if (line.indexOf('(eval ') > -1) {\r\n line = line\r\n .replace(/eval code/g, 'eval')\r\n .replace(/(\\(eval at [^()]*)|(\\),.*$)/g, '');\r\n }\r\n let sanitizedLine = line.replace(/^\\s+/, '').replace(/\\(eval code/g, '(');\r\n const location = sanitizedLine.match(/ (\\((.+):(\\d+):(\\d+)\\)$)/);\r\n sanitizedLine = location\r\n ? sanitizedLine.replace(location[0], '')\r\n : sanitizedLine;\r\n const tokens = sanitizedLine.split(/\\s+/).slice(1);\r\n const locationParts = this.extractLocation(location ? location[1] : tokens.pop());\r\n const functionName = tokens.join(' ') || undefined;\r\n const fileName = ['eval', ''].indexOf(locationParts[0]) > -1\r\n ? undefined\r\n : locationParts[0];\r\n return new StackFrame({\r\n functionName,\r\n fileName,\r\n lineNumber: locationParts[1],\r\n columnNumber: locationParts[2],\r\n });\r\n }, this);\r\n },\r\n parseFFOrSafari: function (error) {\r\n const filtered = error.stack.split('\\n').filter(function (line) {\r\n return !line.match(SAFARI_NATIVE_CODE_REGEXP);\r\n }, this);\r\n return filtered.map(function (line) {\r\n if (line.indexOf(' > eval') > -1) {\r\n line = line.replace(/ line (\\d+)(?: > eval line \\d+)* > eval:\\d+:\\d+/g, ':$1');\r\n }\r\n if (line.indexOf('@') === -1 && line.indexOf(':') === -1) {\r\n return new StackFrame({\r\n functionName: line,\r\n });\r\n }\r\n else {\r\n const functionNameRegex = /((.*\".+\"[^@]*)?[^@]*)(?:@)/;\r\n const matches = line.match(functionNameRegex);\r\n const functionName = matches && matches[1] ? matches[1] : undefined;\r\n const locationParts = this.extractLocation(line.replace(functionNameRegex, ''));\r\n return new StackFrame({\r\n functionName,\r\n fileName: locationParts[0],\r\n lineNumber: locationParts[1],\r\n columnNumber: locationParts[2],\r\n });\r\n }\r\n }, this);\r\n },\r\n parseOpera: function (e) {\r\n if (!e.stacktrace ||\r\n (e.message.indexOf('\\n') > -1 &&\r\n e.message.split('\\n').length > e.stacktrace.split('\\n').length)) {\r\n return this.parseOpera9(e);\r\n }\r\n else if (!e.stack) {\r\n return this.parseOpera10(e);\r\n }\r\n else {\r\n return this.parseOpera11(e);\r\n }\r\n },\r\n parseOpera9: function (e) {\r\n const lineRE = /Line (\\d+).*script (?:in )?(\\S+)/i;\r\n const lines = e.message.split('\\n');\r\n const result = [];\r\n for (let i = 2, len = lines.length; i < len; i += 2) {\r\n const match = lineRE.exec(lines[i]);\r\n if (match) {\r\n result.push(new StackFrame({\r\n fileName: match[2],\r\n lineNumber: parseFloat(match[1]),\r\n }));\r\n }\r\n }\r\n return result;\r\n },\r\n parseOpera10: function (e) {\r\n const lineRE = /Line (\\d+).*script (?:in )?(\\S+)(?:: In function (\\S+))?$/i;\r\n const lines = e.stacktrace.split('\\n');\r\n const result = [];\r\n for (let i = 0, len = lines.length; i < len; i += 2) {\r\n const match = lineRE.exec(lines[i]);\r\n if (match) {\r\n result.push(new StackFrame({\r\n functionName: match[3] || undefined,\r\n fileName: match[2],\r\n lineNumber: parseFloat(match[1]),\r\n }));\r\n }\r\n }\r\n return result;\r\n },\r\n parseOpera11: function (error) {\r\n const filtered = error.stack.split('\\n').filter(function (line) {\r\n return (!!line.match(FIREFOX_SAFARI_STACK_REGEXP) &&\r\n !line.match(/^Error created at/));\r\n }, this);\r\n return filtered.map(function (line) {\r\n const tokens = line.split('@');\r\n const locationParts = this.extractLocation(tokens.pop());\r\n const functionCall = tokens.shift() || '';\r\n const functionName = functionCall\r\n .replace(//, '$2')\r\n .replace(/\\([^)]*\\)/g, '') || undefined;\r\n return new StackFrame({\r\n functionName,\r\n fileName: locationParts[0],\r\n lineNumber: locationParts[1],\r\n columnNumber: locationParts[2],\r\n });\r\n }, this);\r\n },\r\n};\n\nexport { ErrorStackParser, StackFrame };\n","function pathToSelector(node) {\r\n if (!node || !node.outerHTML) {\r\n return '';\r\n }\r\n let path = '';\r\n while (node.parentElement) {\r\n let name = node.localName;\r\n if (!name) {\r\n break;\r\n }\r\n name = name.toLowerCase();\r\n const parent = node.parentElement;\r\n const domSiblings = [];\r\n if (parent.children && parent.children.length > 0) {\r\n for (let i = 0; i < parent.children.length; i++) {\r\n const sibling = parent.children[i];\r\n if (sibling.localName && sibling.localName.toLowerCase) {\r\n if (sibling.localName.toLowerCase() === name) {\r\n domSiblings.push(sibling);\r\n }\r\n }\r\n }\r\n }\r\n if (domSiblings.length > 1) {\r\n name += `:eq(${domSiblings.indexOf(node)})`;\r\n }\r\n path = name + (path ? '>' + path : '');\r\n node = parent;\r\n }\r\n return path;\r\n}\r\nfunction isObject(obj) {\r\n return Object.prototype.toString.call(obj) === '[object Object]';\r\n}\r\nfunction isObjTooDeep(obj, limit) {\r\n if (limit === 0) {\r\n return true;\r\n }\r\n const keys = Object.keys(obj);\r\n for (const key of keys) {\r\n if (isObject(obj[key]) &&\r\n isObjTooDeep(obj[key], limit - 1)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction stringify(obj, stringifyOptions) {\r\n const options = {\r\n numOfKeysLimit: 50,\r\n depthOfLimit: 4,\r\n };\r\n Object.assign(options, stringifyOptions);\r\n const stack = [];\r\n const keys = [];\r\n return JSON.stringify(obj, function (key, value) {\r\n if (stack.length > 0) {\r\n const thisPos = stack.indexOf(this);\r\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\r\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\r\n if (~stack.indexOf(value)) {\r\n if (stack[0] === value) {\r\n value = '[Circular ~]';\r\n }\r\n else {\r\n value =\r\n '[Circular ~.' +\r\n keys.slice(0, stack.indexOf(value)).join('.') +\r\n ']';\r\n }\r\n }\r\n }\r\n else {\r\n stack.push(value);\r\n }\r\n if (value === null)\r\n return value;\r\n if (value === undefined)\r\n return 'undefined';\r\n if (shouldIgnore(value)) {\r\n return toString(value);\r\n }\r\n if (typeof value === 'bigint') {\r\n return value.toString() + 'n';\r\n }\r\n if (value instanceof Event) {\r\n const eventResult = {};\r\n for (const eventKey in value) {\r\n const eventValue = value[eventKey];\r\n if (Array.isArray(eventValue)) {\r\n eventResult[eventKey] = pathToSelector((eventValue.length ? eventValue[0] : null));\r\n }\r\n else {\r\n eventResult[eventKey] = eventValue;\r\n }\r\n }\r\n return eventResult;\r\n }\r\n else if (value instanceof Node) {\r\n if (value instanceof HTMLElement) {\r\n return value ? value.outerHTML : '';\r\n }\r\n return value.nodeName;\r\n }\r\n else if (value instanceof Error) {\r\n return value.stack\r\n ? value.stack + '\\nEnd of stack for Error object'\r\n : value.name + ': ' + value.message;\r\n }\r\n return value;\r\n });\r\n function shouldIgnore(_obj) {\r\n if (isObject(_obj) && Object.keys(_obj).length > options.numOfKeysLimit) {\r\n return true;\r\n }\r\n if (typeof _obj === 'function') {\r\n return true;\r\n }\r\n if (isObject(_obj) &&\r\n isObjTooDeep(_obj, options.depthOfLimit)) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n function toString(_obj) {\r\n let str = _obj.toString();\r\n if (options.stringLengthLimit && str.length > options.stringLengthLimit) {\r\n str = `${str.slice(0, options.stringLengthLimit)}...`;\r\n }\r\n return str;\r\n }\r\n}\n\nexport { stringify };\n","import { patch } from '../../../utils.js';\nimport { ErrorStackParser } from './error-stack-parser.js';\nimport { stringify } from './stringify.js';\n\nconst defaultLogOptions = {\r\n level: [\r\n 'assert',\r\n 'clear',\r\n 'count',\r\n 'countReset',\r\n 'debug',\r\n 'dir',\r\n 'dirxml',\r\n 'error',\r\n 'group',\r\n 'groupCollapsed',\r\n 'groupEnd',\r\n 'info',\r\n 'log',\r\n 'table',\r\n 'time',\r\n 'timeEnd',\r\n 'timeLog',\r\n 'trace',\r\n 'warn',\r\n ],\r\n lengthThreshold: 1000,\r\n logger: 'console',\r\n};\r\nfunction initLogObserver(cb, win, options) {\r\n const logOptions = (options ? Object.assign({}, defaultLogOptions, options) : defaultLogOptions);\r\n const loggerType = logOptions.logger;\r\n if (!loggerType) {\r\n return () => {\r\n };\r\n }\r\n let logger;\r\n if (typeof loggerType === 'string') {\r\n logger = win[loggerType];\r\n }\r\n else {\r\n logger = loggerType;\r\n }\r\n let logCount = 0;\r\n let inStack = false;\r\n const cancelHandlers = [];\r\n if (logOptions.level.includes('error')) {\r\n const errorHandler = (event) => {\r\n const message = event.message, error = event.error;\r\n const trace = ErrorStackParser.parse(error).map((stackFrame) => stackFrame.toString());\r\n const payload = [stringify(message, logOptions.stringifyOptions)];\r\n cb({\r\n level: 'error',\r\n trace,\r\n payload,\r\n });\r\n };\r\n win.addEventListener('error', errorHandler);\r\n cancelHandlers.push(() => {\r\n win.removeEventListener('error', errorHandler);\r\n });\r\n const unhandledrejectionHandler = (event) => {\r\n let error;\r\n let payload;\r\n if (event.reason instanceof Error) {\r\n error = event.reason;\r\n payload = [\r\n stringify(`Uncaught (in promise) ${error.name}: ${error.message}`, logOptions.stringifyOptions),\r\n ];\r\n }\r\n else {\r\n error = new Error();\r\n payload = [\r\n stringify('Uncaught (in promise)', logOptions.stringifyOptions),\r\n stringify(event.reason, logOptions.stringifyOptions),\r\n ];\r\n }\r\n const trace = ErrorStackParser.parse(error).map((stackFrame) => stackFrame.toString());\r\n cb({\r\n level: 'error',\r\n trace,\r\n payload,\r\n });\r\n };\r\n win.addEventListener('unhandledrejection', unhandledrejectionHandler);\r\n cancelHandlers.push(() => {\r\n win.removeEventListener('unhandledrejection', unhandledrejectionHandler);\r\n });\r\n }\r\n for (const levelType of logOptions.level) {\r\n cancelHandlers.push(replace(logger, levelType));\r\n }\r\n return () => {\r\n cancelHandlers.forEach((h) => h());\r\n };\r\n function replace(_logger, level) {\r\n if (!_logger[level]) {\r\n return () => {\r\n };\r\n }\r\n return patch(_logger, level, (original) => {\r\n return (...args) => {\r\n original.apply(this, args);\r\n if (inStack) {\r\n return;\r\n }\r\n inStack = true;\r\n try {\r\n const trace = ErrorStackParser.parse(new Error())\r\n .map((stackFrame) => stackFrame.toString())\r\n .splice(1);\r\n const payload = args.map((s) => stringify(s, logOptions.stringifyOptions));\r\n logCount++;\r\n if (logCount < logOptions.lengthThreshold) {\r\n cb({\r\n level,\r\n trace,\r\n payload,\r\n });\r\n }\r\n else if (logCount === logOptions.lengthThreshold) {\r\n cb({\r\n level: 'warn',\r\n trace: [],\r\n payload: [\r\n stringify('The number of log records reached the threshold.'),\r\n ],\r\n });\r\n }\r\n }\r\n catch (error) {\r\n original('rrweb logger error:', error, ...args);\r\n }\r\n finally {\r\n inStack = false;\r\n }\r\n };\r\n });\r\n }\r\n}\r\nconst PLUGIN_NAME = 'rrweb/console@1';\r\nconst getRecordConsolePlugin = (options) => ({\r\n name: PLUGIN_NAME,\r\n observer: initLogObserver,\r\n options: options,\r\n});\n\nexport { PLUGIN_NAME, getRecordConsolePlugin };\n","// eslint-disable-next-line posthog-js/no-direct-array-check\nconst nativeIsArray = Array.isArray\nconst ObjProto = Object.prototype\nexport const hasOwnProperty = ObjProto.hasOwnProperty\nconst toString = ObjProto.toString\n\nexport const isArray =\n nativeIsArray ||\n function (obj: any): obj is any[] {\n return toString.call(obj) === '[object Array]'\n }\nexport const isUint8Array = function (x: unknown): x is Uint8Array {\n return toString.call(x) === '[object Uint8Array]'\n}\n// from a comment on http://dbj.org/dbj/?p=286\n// fails on only one very rare and deliberate custom object:\n// let bomb = { toString : undefined, valueOf: function(o) { return \"function BOMBA!\"; }};\nexport const isFunction = function (f: any): f is (...args: any[]) => any {\n // eslint-disable-next-line posthog-js/no-direct-function-check\n return typeof f === 'function'\n}\n// Underscore Addons\nexport const isObject = function (x: unknown): x is Record {\n // eslint-disable-next-line posthog-js/no-direct-object-check\n return x === Object(x) && !isArray(x)\n}\nexport const isEmptyObject = function (x: unknown): x is Record {\n if (isObject(x)) {\n for (const key in x) {\n if (hasOwnProperty.call(x, key)) {\n return false\n }\n }\n return true\n }\n return false\n}\nexport const isUndefined = function (x: unknown): x is undefined {\n return x === void 0\n}\n\nexport const isString = function (x: unknown): x is string {\n // eslint-disable-next-line posthog-js/no-direct-string-check\n return toString.call(x) == '[object String]'\n}\n\nexport const isEmptyString = function (x: unknown): boolean {\n return isString(x) && x.trim().length === 0\n}\n\nexport const isNull = function (x: unknown): x is null {\n // eslint-disable-next-line posthog-js/no-direct-null-check\n return x === null\n}\n\n/*\n sometimes you want to check if something is null or undefined\n that's what this is for\n */\nexport const isNullish = function (x: unknown): x is null | undefined {\n return isUndefined(x) || isNull(x)\n}\n\nexport const isDate = function (x: unknown): x is Date {\n // eslint-disable-next-line posthog-js/no-direct-date-check\n return toString.call(x) == '[object Date]'\n}\nexport const isNumber = function (x: unknown): x is number {\n // eslint-disable-next-line posthog-js/no-direct-number-check\n return toString.call(x) == '[object Number]'\n}\nexport const isBoolean = function (x: unknown): x is boolean {\n // eslint-disable-next-line posthog-js/no-direct-boolean-check\n return toString.call(x) === '[object Boolean]'\n}\n\nexport const isDocument = (x: unknown): x is Document => {\n // eslint-disable-next-line posthog-js/no-direct-document-check\n return x instanceof Document\n}\n\nexport const isFormData = (x: unknown): x is FormData => {\n // eslint-disable-next-line posthog-js/no-direct-form-data-check\n return x instanceof FormData\n}\n\nexport const isFile = (x: unknown): x is File => {\n // eslint-disable-next-line posthog-js/no-direct-file-check\n return x instanceof File\n}\n","import type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport { ErrorEventArgs, ErrorProperties, Properties } from '../types'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type PostHogExtensionKind =\n | 'toolbar'\n | 'exception-autocapture'\n | 'web-vitals'\n | 'recorder'\n | 'tracing-headers'\n | 'surveys'\n\ninterface PostHogExtensions {\n loadExternalDependency?: (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n ) => void\n\n loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n parseErrorAsProperties?: ([event, source, lineno, colno, error]: ErrorEventArgs) => ErrorProperties\n errorWrappingFunctions?: {\n wrapOnError: (captureFn: (props: Properties) => void) => () => void\n wrapUnhandledRejection: (captureFn: (props: Properties) => void) => () => void\n }\n rrweb?: { record: any; version: string; rrwebVersion: string }\n rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n canActivateRepeatedly?: (survey: any) => boolean\n generateSurveys?: (posthog: PostHog) => any | undefined\n postHogWebVitalsCallbacks?: {\n onLCP: (metric: any) => void\n onCLS: (metric: any) => void\n onFCP: (metric: any) => void\n onINP: (metric: any) => void\n }\n tracingHeadersPatchFns?: {\n _patchFetch: (sessionManager: SessionIdManager) => () => void\n _patchXHR: (sessionManager: any) => () => void\n }\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\nexport const ArrayProto = Array.prototype\nexport const nativeForEach = ArrayProto.forEach\nexport const nativeIndexOf = ArrayProto.indexOf\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: Window &\n typeof globalThis &\n Record & {\n __PosthogExtensions__?: PostHogExtensions\n } = win ?? ({} as any)\n\nexport { win as window }\n","import Config from '../config'\nimport { isUndefined } from './type-utils'\nimport { assignableWindow, window } from './globals'\n\nconst LOGGER_PREFIX = '[PostHog.js]'\nexport const logger = {\n _log: (level: 'log' | 'warn' | 'error', ...args: any[]) => {\n if (\n window &&\n (Config.DEBUG || assignableWindow.POSTHOG_DEBUG) &&\n !isUndefined(window.console) &&\n window.console\n ) {\n const consoleLog =\n '__rrweb_original__' in window.console[level]\n ? (window.console[level] as any)['__rrweb_original__']\n : window.console[level]\n\n // eslint-disable-next-line no-console\n consoleLog(LOGGER_PREFIX, ...args)\n }\n },\n\n info: (...args: any[]) => {\n logger._log('log', ...args)\n },\n\n warn: (...args: any[]) => {\n logger._log('warn', ...args)\n },\n\n error: (...args: any[]) => {\n logger._log('error', ...args)\n },\n\n critical: (...args: any[]) => {\n // Critical errors are always logged to the console\n // eslint-disable-next-line no-console\n console.error(LOGGER_PREFIX, ...args)\n },\n\n uninitializedWarning: (methodName: string) => {\n logger.error(`You must initialize PostHog before calling ${methodName}`)\n },\n}\n","import { Breaker, EventHandler, Properties } from '../types'\nimport { isArray, isFormData, isFunction, isNull, isNullish, isString, hasOwnProperty } from './type-utils'\nimport { logger } from './logger'\nimport { window, nativeForEach, nativeIndexOf } from './globals'\n\nconst breaker: Breaker = {}\n\n// UNDERSCORE\n// Embed part of the Underscore Library\nexport const trim = function (str: string): string {\n return str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '')\n}\n\nexport function eachArray(\n obj: E[] | null | undefined,\n iterator: (value: E, key: number) => void | Breaker,\n thisArg?: any\n): void {\n if (isArray(obj)) {\n if (nativeForEach && obj.forEach === nativeForEach) {\n obj.forEach(iterator, thisArg)\n } else if ('length' in obj && obj.length === +obj.length) {\n for (let i = 0, l = obj.length; i < l; i++) {\n if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {\n return\n }\n }\n }\n }\n}\n\n/**\n * @param {*=} obj\n * @param {function(...*)=} iterator\n * @param {Object=} thisArg\n */\nexport function each(obj: any, iterator: (value: any, key: any) => void | Breaker, thisArg?: any): void {\n if (isNullish(obj)) {\n return\n }\n if (isArray(obj)) {\n return eachArray(obj, iterator, thisArg)\n }\n if (isFormData(obj)) {\n for (const pair of obj.entries()) {\n if (iterator.call(thisArg, pair[1], pair[0]) === breaker) {\n return\n }\n }\n return\n }\n for (const key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n if (iterator.call(thisArg, obj[key], key) === breaker) {\n return\n }\n }\n }\n}\n\nexport const extend = function (obj: Record, ...args: Record[]): Record {\n eachArray(args, function (source) {\n for (const prop in source) {\n if (source[prop] !== void 0) {\n obj[prop] = source[prop]\n }\n }\n })\n return obj\n}\n\nexport const include = function (\n obj: null | string | Array | Record,\n target: any\n): boolean | Breaker {\n let found = false\n if (isNull(obj)) {\n return found\n }\n if (nativeIndexOf && obj.indexOf === nativeIndexOf) {\n return obj.indexOf(target) != -1\n }\n each(obj, function (value) {\n if (found || (found = value === target)) {\n return breaker\n }\n return\n })\n return found\n}\n\nexport function includes(str: T[] | string, needle: T): boolean {\n return (str as any).indexOf(needle) !== -1\n}\n\n/**\n * Object.entries() polyfill\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\n */\nexport function entries(obj: Record): [string, T][] {\n const ownProps = Object.keys(obj)\n let i = ownProps.length\n const resArray = new Array(i) // preallocate the Array\n\n while (i--) {\n resArray[i] = [ownProps[i], obj[ownProps[i]]]\n }\n return resArray\n}\n\nexport const isValidRegex = function (str: string): boolean {\n try {\n new RegExp(str)\n } catch {\n return false\n }\n return true\n}\n\nexport const trySafe = function (fn: () => T): T | undefined {\n try {\n return fn()\n } catch {\n return undefined\n }\n}\n\nexport const safewrap = function any = (...args: any[]) => any>(f: F): F {\n return function (...args) {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return f.apply(this, args)\n } catch (e) {\n logger.critical(\n 'Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A.'\n )\n logger.critical(e)\n }\n } as F\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport const safewrapClass = function (klass: Function, functions: string[]): void {\n for (let i = 0; i < functions.length; i++) {\n klass.prototype[functions[i]] = safewrap(klass.prototype[functions[i]])\n }\n}\n\nexport const stripEmptyProperties = function (p: Properties): Properties {\n const ret: Properties = {}\n each(p, function (v, k) {\n if (isString(v) && v.length > 0) {\n ret[k] = v\n }\n })\n return ret\n}\n\nexport const stripLeadingDollar = function (s: string): string {\n return s.replace(/^\\$/, '')\n}\n\n/**\n * Deep copies an object.\n * It handles cycles by replacing all references to them with `undefined`\n * Also supports customizing native values\n *\n * @param value\n * @param customizer\n * @returns {{}|undefined|*}\n */\nfunction deepCircularCopy = Record>(\n value: T,\n customizer?: (value: T[K], key?: K) => T[K]\n): T | undefined {\n const COPY_IN_PROGRESS_SET = new Set()\n\n function internalDeepCircularCopy(value: T, key?: string): T | undefined {\n if (value !== Object(value)) return customizer ? customizer(value as any, key) : value // primitive value\n\n if (COPY_IN_PROGRESS_SET.has(value)) return undefined\n COPY_IN_PROGRESS_SET.add(value)\n let result: T\n\n if (isArray(value)) {\n result = [] as any as T\n eachArray(value, (it) => {\n result.push(internalDeepCircularCopy(it))\n })\n } else {\n result = {} as T\n each(value, (val, key) => {\n if (!COPY_IN_PROGRESS_SET.has(val)) {\n ;(result as any)[key] = internalDeepCircularCopy(val, key)\n }\n })\n }\n return result\n }\n return internalDeepCircularCopy(value)\n}\n\nexport function _copyAndTruncateStrings = Record>(\n object: T,\n maxStringLength: number | null\n): T {\n return deepCircularCopy(object, (value: any) => {\n if (isString(value) && !isNull(maxStringLength)) {\n return (value as string).slice(0, maxStringLength)\n }\n return value\n }) as T\n}\n\nexport function _base64Encode(data: null): null\nexport function _base64Encode(data: undefined): undefined\nexport function _base64Encode(data: string): string\nexport function _base64Encode(data: string | null | undefined): string | null | undefined {\n const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let o1,\n o2,\n o3,\n h1,\n h2,\n h3,\n h4,\n bits,\n i = 0,\n ac = 0,\n enc = ''\n const tmp_arr: string[] = []\n\n if (!data) {\n return data\n }\n\n data = utf8Encode(data)\n\n do {\n // pack three octets into four hexets\n o1 = data.charCodeAt(i++)\n o2 = data.charCodeAt(i++)\n o3 = data.charCodeAt(i++)\n\n bits = (o1 << 16) | (o2 << 8) | o3\n\n h1 = (bits >> 18) & 0x3f\n h2 = (bits >> 12) & 0x3f\n h3 = (bits >> 6) & 0x3f\n h4 = bits & 0x3f\n\n // use hexets to index into b64, and append result to encoded string\n tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4)\n } while (i < data.length)\n\n enc = tmp_arr.join('')\n\n switch (data.length % 3) {\n case 1:\n enc = enc.slice(0, -2) + '=='\n break\n case 2:\n enc = enc.slice(0, -1) + '='\n break\n }\n\n return enc\n}\n\nexport const utf8Encode = function (string: string): string {\n string = (string + '').replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\n\n let utftext = '',\n start,\n end\n let stringl = 0,\n n\n\n start = end = 0\n stringl = string.length\n\n for (n = 0; n < stringl; n++) {\n const c1 = string.charCodeAt(n)\n let enc = null\n\n if (c1 < 128) {\n end++\n } else if (c1 > 127 && c1 < 2048) {\n enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128)\n } else {\n enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128)\n }\n if (!isNull(enc)) {\n if (end > start) {\n utftext += string.substring(start, end)\n }\n utftext += enc\n start = end = n + 1\n }\n }\n\n if (end > start) {\n utftext += string.substring(start, string.length)\n }\n\n return utftext\n}\n\nexport const registerEvent = (function () {\n // written by Dean Edwards, 2005\n // with input from Tino Zijdel - crisp@xs4all.nl\n // with input from Carl Sverre - mail@carlsverre.com\n // with input from PostHog\n // http://dean.edwards.name/weblog/2005/10/add-event/\n // https://gist.github.com/1930440\n\n /**\n * @param {Object} element\n * @param {string} type\n * @param {function(...*)} handler\n * @param {boolean=} oldSchool\n * @param {boolean=} useCapture\n */\n const register_event = function (\n element: Element | Window | Document | Node,\n type: string,\n handler: EventHandler,\n oldSchool?: boolean,\n useCapture?: boolean\n ) {\n if (!element) {\n logger.error('No valid element provided to register_event')\n return\n }\n\n if (element.addEventListener && !oldSchool) {\n element.addEventListener(type, handler, !!useCapture)\n } else {\n const ontype = 'on' + type\n const old_handler = (element as any)[ontype] // can be undefined\n ;(element as any)[ontype] = makeHandler(element, handler, old_handler)\n }\n }\n\n function makeHandler(\n element: Element | Window | Document | Node,\n new_handler: EventHandler,\n old_handlers: EventHandler\n ) {\n return function (event: Event): boolean | void {\n event = event || fixEvent(window?.event)\n\n // this basically happens in firefox whenever another script\n // overwrites the onload callback and doesn't pass the event\n // object to previously defined callbacks. All the browsers\n // that don't define window.event implement addEventListener\n // so the dom_loaded handler will still be fired as usual.\n if (!event) {\n return undefined\n }\n\n let ret = true\n let old_result: any\n\n if (isFunction(old_handlers)) {\n old_result = old_handlers(event)\n }\n const new_result = new_handler.call(element, event)\n\n if (false === old_result || false === new_result) {\n ret = false\n }\n\n return ret\n }\n }\n\n function fixEvent(event: Event | undefined): Event | undefined {\n if (event) {\n event.preventDefault = fixEvent.preventDefault\n event.stopPropagation = fixEvent.stopPropagation\n }\n return event\n }\n fixEvent.preventDefault = function () {\n ;(this as any as Event).returnValue = false\n }\n fixEvent.stopPropagation = function () {\n ;(this as any as Event).cancelBubble = true\n }\n\n return register_event\n})()\n\nexport function isCrossDomainCookie(documentLocation: Location | undefined) {\n const hostname = documentLocation?.hostname\n\n if (!isString(hostname)) {\n return false\n }\n // split and slice isn't a great way to match arbitrary domains,\n // but it's good enough for ensuring we only match herokuapp.com when it is the TLD\n // for the hostname\n return hostname.split('.').slice(-2).join('.') !== 'herokuapp.com'\n}\n\nexport function isDistinctIdStringLike(value: string): boolean {\n return ['distinct_id', 'distinctid'].includes(value.toLowerCase())\n}\n\nexport function find(value: T[], predicate: (value: T) => boolean): T | undefined {\n for (let i = 0; i < value.length; i++) {\n if (predicate(value[i])) {\n return value[i]\n }\n }\n return undefined\n}\n","import { each, isValidRegex } from './'\n\nimport { isArray, isFile, isUndefined } from './type-utils'\nimport { logger } from './logger'\nimport { document } from './globals'\n\nconst localDomains = ['localhost', '127.0.0.1']\n\n/**\n * IE11 doesn't support `new URL`\n * so we can create an anchor element and use that to parse the URL\n * there's a lot of overlap between HTMLHyperlinkElementUtils and URL\n * meaning useful properties like `pathname` are available on both\n */\nexport const convertToURL = (url: string): HTMLAnchorElement | null => {\n const location = document?.createElement('a')\n if (isUndefined(location)) {\n return null\n }\n\n location.href = url\n return location\n}\n\nexport const isUrlMatchingRegex = function (url: string, pattern: string): boolean {\n if (!isValidRegex(pattern)) return false\n return new RegExp(pattern).test(url)\n}\n\nexport const formDataToQuery = function (formdata: Record | FormData, arg_separator = '&'): string {\n let use_val: string\n let use_key: string\n const tph_arr: string[] = []\n\n each(formdata, function (val: File | string | undefined, key: string | undefined) {\n // the key might be literally the string undefined for e.g. if {undefined: 'something'}\n if (isUndefined(val) || isUndefined(key) || key === 'undefined') {\n return\n }\n\n use_val = encodeURIComponent(isFile(val) ? val.name : val.toString())\n use_key = encodeURIComponent(key)\n tph_arr[tph_arr.length] = use_key + '=' + use_val\n })\n\n return tph_arr.join(arg_separator)\n}\n\nexport const getQueryParam = function (url: string, param: string): string {\n const withoutHash: string = url.split('#')[0] || ''\n const queryParams: string = withoutHash.split('?')[1] || ''\n\n const queryParts = queryParams.split('&')\n let keyValuePair\n\n for (let i = 0; i < queryParts.length; i++) {\n const parts = queryParts[i].split('=')\n if (parts[0] === param) {\n keyValuePair = parts\n break\n }\n }\n\n if (!isArray(keyValuePair) || keyValuePair.length < 2) {\n return ''\n } else {\n let result = keyValuePair[1]\n try {\n result = decodeURIComponent(result)\n } catch {\n logger.error('Skipping decoding for malformed query param: ' + result)\n }\n return result.replace(/\\+/g, ' ')\n }\n}\n\nexport const _getHashParam = function (hash: string, param: string): string | null {\n const matches = hash.match(new RegExp(param + '=([^&]*)'))\n return matches ? matches[1] : null\n}\n\nexport const isLocalhost = (): boolean => {\n return localDomains.includes(location.hostname)\n}\n","import { CapturedNetworkRequest, NetworkRecordOptions, PostHogConfig } from '../../types'\nimport { isFunction, isNullish, isString, isUndefined } from '../../utils/type-utils'\nimport { convertToURL } from '../../utils/request-utils'\nimport { logger } from '../../utils/logger'\nimport { shouldCaptureValue } from '../../autocapture-utils'\nimport { each } from '../../utils'\n\nconst LOGGER_PREFIX = '[SessionRecording]'\nconst REDACTED = 'redacted'\n\nexport const defaultNetworkOptions: Required = {\n initiatorTypes: [\n 'audio',\n 'beacon',\n 'body',\n 'css',\n 'early-hint',\n 'embed',\n 'fetch',\n 'frame',\n 'iframe',\n 'icon',\n 'image',\n 'img',\n 'input',\n 'link',\n 'navigation',\n 'object',\n 'ping',\n 'script',\n 'track',\n 'video',\n 'xmlhttprequest',\n ],\n maskRequestFn: (data: CapturedNetworkRequest) => data,\n recordHeaders: false,\n recordBody: false,\n recordInitialRequests: false,\n recordPerformance: false,\n performanceEntryTypeToObserve: [\n // 'event', // This is too noisy as it covers all browser events\n 'first-input',\n // 'mark', // Mark is used too liberally. We would need to filter for specific marks\n // 'measure', // Measure is used too liberally. We would need to filter for specific measures\n 'navigation',\n 'paint',\n 'resource',\n ],\n payloadSizeLimitBytes: 1000000,\n payloadHostDenyList: ['.lr-ingest.io', '.ingest.sentry.io'],\n}\n\nconst HEADER_DENY_LIST = [\n 'authorization',\n 'x-forwarded-for',\n 'authorization',\n 'cookie',\n 'set-cookie',\n 'x-api-key',\n 'x-real-ip',\n 'remote-addr',\n 'forwarded',\n 'proxy-authorization',\n 'x-csrf-token',\n 'x-csrftoken',\n 'x-xsrf-token',\n]\n\nconst PAYLOAD_CONTENT_DENY_LIST = [\n 'password',\n 'secret',\n 'passwd',\n 'api_key',\n 'apikey',\n 'auth',\n 'credentials',\n 'mysql_pwd',\n 'privatekey',\n 'private_key',\n 'token',\n]\n\n// we always remove headers on the deny list because we never want to capture this sensitive data\nconst removeAuthorizationHeader = (data: CapturedNetworkRequest): CapturedNetworkRequest => {\n const headers = data.requestHeaders\n if (!isNullish(headers)) {\n each(Object.keys(headers ?? {}), (header) => {\n if (HEADER_DENY_LIST.includes(header.toLowerCase())) {\n headers[header] = REDACTED\n }\n })\n }\n return data\n}\n\nconst POSTHOG_PATHS_TO_IGNORE = ['/s/', '/e/', '/i/']\n// want to ignore posthog paths when capturing requests, or we can get trapped in a loop\n// because calls to PostHog would be reported using a call to PostHog which would be reported....\nconst ignorePostHogPaths = (data: CapturedNetworkRequest): CapturedNetworkRequest | undefined => {\n const url = convertToURL(data.name)\n if (url && url.pathname && POSTHOG_PATHS_TO_IGNORE.some((path) => url.pathname.indexOf(path) === 0)) {\n return undefined\n }\n return data\n}\n\nfunction estimateBytes(payload: string): number {\n return new Blob([payload]).size\n}\n\nfunction enforcePayloadSizeLimit(\n payload: string | null | undefined,\n headers: Record | undefined,\n limit: number,\n description: string\n): string | null | undefined {\n if (isNullish(payload)) {\n return payload\n }\n\n let requestContentLength: string | number = headers?.['content-length'] || estimateBytes(payload)\n if (isString(requestContentLength)) {\n requestContentLength = parseInt(requestContentLength)\n }\n\n if (requestContentLength > limit) {\n return LOGGER_PREFIX + ` ${description} body too large to record (${requestContentLength} bytes)`\n }\n\n return payload\n}\n\n// people can have arbitrarily large payloads on their site, but we don't want to ingest them\nconst limitPayloadSize = (\n options: NetworkRecordOptions\n): ((data: CapturedNetworkRequest | undefined) => CapturedNetworkRequest | undefined) => {\n // the smallest of 1MB or the specified limit if there is one\n const limit = Math.min(1000000, options.payloadSizeLimitBytes ?? 1000000)\n\n return (data) => {\n if (data?.requestBody) {\n data.requestBody = enforcePayloadSizeLimit(data.requestBody, data.requestHeaders, limit, 'Request')\n }\n\n if (data?.responseBody) {\n data.responseBody = enforcePayloadSizeLimit(data.responseBody, data.responseHeaders, limit, 'Response')\n }\n\n return data\n }\n}\n\nfunction scrubPayload(payload: string | null | undefined, label: 'Request' | 'Response'): string | null | undefined {\n if (isNullish(payload)) {\n return payload\n }\n let scrubbed = payload\n\n if (!shouldCaptureValue(scrubbed, false)) {\n scrubbed = LOGGER_PREFIX + ' ' + label + ' body ' + REDACTED\n }\n each(PAYLOAD_CONTENT_DENY_LIST, (text) => {\n if (scrubbed?.length && scrubbed?.indexOf(text) !== -1) {\n scrubbed = LOGGER_PREFIX + ' ' + label + ' body ' + REDACTED + ' as might contain: ' + text\n }\n })\n\n return scrubbed\n}\n\nfunction scrubPayloads(capturedRequest: CapturedNetworkRequest | undefined): CapturedNetworkRequest | undefined {\n if (isUndefined(capturedRequest)) {\n return undefined\n }\n\n capturedRequest.requestBody = scrubPayload(capturedRequest.requestBody, 'Request')\n capturedRequest.responseBody = scrubPayload(capturedRequest.responseBody, 'Response')\n\n return capturedRequest\n}\n\n/**\n * whether a maskRequestFn is provided or not,\n * we ensure that we remove the denied header from requests\n * we _never_ want to record that header by accident\n * if someone complains then we'll add an opt-in to let them override it\n */\nexport const buildNetworkRequestOptions = (\n instanceConfig: PostHogConfig,\n remoteNetworkOptions: Pick<\n NetworkRecordOptions,\n 'recordHeaders' | 'recordBody' | 'recordPerformance' | 'payloadHostDenyList'\n >\n): NetworkRecordOptions => {\n const config: NetworkRecordOptions = {\n payloadSizeLimitBytes: defaultNetworkOptions.payloadSizeLimitBytes,\n performanceEntryTypeToObserve: [...defaultNetworkOptions.performanceEntryTypeToObserve],\n payloadHostDenyList: [\n ...(remoteNetworkOptions.payloadHostDenyList || []),\n ...defaultNetworkOptions.payloadHostDenyList,\n ],\n }\n // client can always disable despite remote options\n const canRecordHeaders =\n instanceConfig.session_recording.recordHeaders === false ? false : remoteNetworkOptions.recordHeaders\n const canRecordBody =\n instanceConfig.session_recording.recordBody === false ? false : remoteNetworkOptions.recordBody\n const canRecordPerformance =\n instanceConfig.capture_performance === false ? false : remoteNetworkOptions.recordPerformance\n\n const payloadLimiter = limitPayloadSize(config)\n\n const enforcedCleaningFn: NetworkRecordOptions['maskRequestFn'] = (d: CapturedNetworkRequest) =>\n payloadLimiter(ignorePostHogPaths(removeAuthorizationHeader(d)))\n\n const hasDeprecatedMaskFunction = isFunction(instanceConfig.session_recording.maskNetworkRequestFn)\n\n if (hasDeprecatedMaskFunction && isFunction(instanceConfig.session_recording.maskCapturedNetworkRequestFn)) {\n logger.warn(\n 'Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored.'\n )\n }\n\n if (hasDeprecatedMaskFunction) {\n instanceConfig.session_recording.maskCapturedNetworkRequestFn = (data: CapturedNetworkRequest) => {\n const cleanedURL = instanceConfig.session_recording.maskNetworkRequestFn!({ url: data.name })\n return {\n ...data,\n name: cleanedURL?.url,\n } as CapturedNetworkRequest\n }\n }\n\n config.maskRequestFn = isFunction(instanceConfig.session_recording.maskCapturedNetworkRequestFn)\n ? (data) => {\n const cleanedRequest = enforcedCleaningFn(data)\n return cleanedRequest\n ? instanceConfig.session_recording.maskCapturedNetworkRequestFn?.(cleanedRequest) ?? undefined\n : undefined\n }\n : (data) => scrubPayloads(enforcedCleaningFn(data))\n\n return {\n ...defaultNetworkOptions,\n ...config,\n recordHeaders: canRecordHeaders,\n recordBody: canRecordBody,\n recordPerformance: canRecordPerformance,\n recordInitialRequests: canRecordPerformance,\n }\n}\n","// import { patch } from 'rrweb/typings/utils'\n// copied from https://github.com/rrweb-io/rrweb/blob/8aea5b00a4dfe5a6f59bd2ae72bb624f45e51e81/packages/rrweb/src/utils.ts#L129\n// which was copied from https://github.com/getsentry/sentry-javascript/blob/b2109071975af8bf0316d3b5b38f519bdaf5dc15/packages/utils/src/object.ts\nimport { isFunction } from '../../../utils/type-utils'\n\nexport function patch(\n source: { [key: string]: any },\n name: string,\n replacement: (...args: unknown[]) => unknown\n): () => void {\n try {\n if (!(name in source)) {\n return () => {\n //\n }\n }\n\n const original = source[name] as () => unknown\n const wrapped = replacement(original)\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (isFunction(wrapped)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n wrapped.prototype = wrapped.prototype || {}\n Object.defineProperties(wrapped, {\n __posthog_wrapped__: {\n enumerable: false,\n value: true,\n },\n })\n }\n\n source[name] = wrapped\n\n return () => {\n source[name] = original\n }\n } catch {\n return () => {\n //\n }\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n}\n","import { NetworkRecordOptions } from '../../../types'\n\nfunction hostnameFromURL(url: string | URL | RequestInfo): string | null {\n try {\n if (typeof url === 'string') {\n return new URL(url).hostname\n }\n if ('url' in url) {\n return new URL(url.url).hostname\n }\n return url.hostname\n } catch {\n return null\n }\n}\n\nexport function isHostOnDenyList(url: string | URL | Request, options: NetworkRecordOptions) {\n const hostname = hostnameFromURL(url)\n const defaultNotDenied = { hostname, isHostDenied: false }\n\n if (!options.payloadHostDenyList?.length || !hostname?.trim().length) {\n return defaultNotDenied\n }\n\n for (const deny of options.payloadHostDenyList) {\n if (hostname.endsWith(deny)) {\n return { hostname, isHostDenied: true }\n }\n }\n\n return defaultNotDenied\n}\n","import { version } from 'rrweb/package.json'\n\n// Same as loader-globals.ts except includes rrweb2 scripts.\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport rrwebRecord from 'rrweb/es/rrweb/packages/rrweb/src/record'\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport { getRecordConsolePlugin } from 'rrweb/es/rrweb/packages/rrweb/src/plugins/console/record'\n\n// rrweb/network@1 code starts\n// most of what is below here will be removed when rrweb release their code for this\n// see https://github.com/rrweb-io/rrweb/pull/1105\n/// \n// NB adopted from https://github.com/rrweb-io/rrweb/pull/1105 which looks like it will be accepted into rrweb\n// however, in the PR, it throws when the performance observer data is not available\n// and assumes it is running in a browser with the Request API (i.e. not IE11)\n// copying here so that we can use it before rrweb adopt it\nimport type { IWindow, listenerHandler, RecordPlugin } from '@rrweb/types'\nimport { CapturedNetworkRequest, Headers, InitiatorType, NetworkRecordOptions } from '../types'\nimport {\n isArray,\n isBoolean,\n isDocument,\n isFormData,\n isNull,\n isNullish,\n isObject,\n isString,\n isUndefined,\n} from '../utils/type-utils'\nimport { logger } from '../utils/logger'\nimport { assignableWindow } from '../utils/globals'\nimport { defaultNetworkOptions } from '../extensions/replay/config'\nimport { formDataToQuery } from '../utils/request-utils'\nimport { patch } from '../extensions/replay/rrweb-plugins/patch'\nimport { isHostOnDenyList } from '../extensions/replay/external/denylist'\n\nexport type NetworkData = {\n requests: CapturedNetworkRequest[]\n isInitial?: boolean\n}\n\ntype networkCallback = (data: NetworkData) => void\n\nconst isNavigationTiming = (entry: PerformanceEntry): entry is PerformanceNavigationTiming =>\n entry.entryType === 'navigation'\nconst isResourceTiming = (entry: PerformanceEntry): entry is PerformanceResourceTiming => entry.entryType === 'resource'\n\ntype ObservedPerformanceEntry = (PerformanceNavigationTiming | PerformanceResourceTiming) & {\n responseStatus?: number\n}\n\nexport function findLast(array: Array, predicate: (value: T) => boolean): T | undefined {\n const length = array.length\n for (let i = length - 1; i >= 0; i -= 1) {\n if (predicate(array[i])) {\n return array[i]\n }\n }\n return undefined\n}\n\nfunction initPerformanceObserver(cb: networkCallback, win: IWindow, options: Required) {\n // if we are only observing timings then we could have a single observer for all types, with buffer true,\n // but we are going to filter by initiatorType _if we are wrapping fetch and xhr as the wrapped functions\n // will deal with those.\n // so we have a block which captures requests from before fetch/xhr is wrapped\n // these are marked `isInitial` so playback can display them differently if needed\n // they will never have method/status/headers/body because they are pre-wrapping that provides that\n if (options.recordInitialRequests) {\n const initialPerformanceEntries = win.performance\n .getEntries()\n .filter(\n (entry): entry is ObservedPerformanceEntry =>\n isNavigationTiming(entry) ||\n (isResourceTiming(entry) && options.initiatorTypes.includes(entry.initiatorType as InitiatorType))\n )\n cb({\n requests: initialPerformanceEntries.flatMap((entry) =>\n prepareRequest({ entry, method: undefined, status: undefined, networkRequest: {}, isInitial: true })\n ),\n isInitial: true,\n })\n }\n const observer = new win.PerformanceObserver((entries) => {\n // if recordBody or recordHeaders is true then we don't want to record fetch or xhr here\n // as the wrapped functions will do that. Otherwise, this filter becomes a noop\n // because we do want to record them here\n const wrappedInitiatorFilter = (entry: ObservedPerformanceEntry) =>\n options.recordBody || options.recordHeaders\n ? entry.initiatorType !== 'xmlhttprequest' && entry.initiatorType !== 'fetch'\n : true\n\n const performanceEntries = entries.getEntries().filter(\n (entry): entry is ObservedPerformanceEntry =>\n isNavigationTiming(entry) ||\n (isResourceTiming(entry) &&\n options.initiatorTypes.includes(entry.initiatorType as InitiatorType) &&\n // TODO if we are _only_ capturing timing we don't want to filter initiator here\n wrappedInitiatorFilter(entry))\n )\n\n cb({\n requests: performanceEntries.flatMap((entry) =>\n prepareRequest({ entry, method: undefined, status: undefined, networkRequest: {} })\n ),\n })\n })\n // compat checked earlier\n // eslint-disable-next-line compat/compat\n const entryTypes = PerformanceObserver.supportedEntryTypes.filter((x) =>\n options.performanceEntryTypeToObserve.includes(x)\n )\n // initial records are gathered above, so we don't need to observe and buffer each type separately\n observer.observe({ entryTypes })\n return () => {\n observer.disconnect()\n }\n}\n\nfunction shouldRecordHeaders(type: 'request' | 'response', recordHeaders: NetworkRecordOptions['recordHeaders']) {\n return !!recordHeaders && (isBoolean(recordHeaders) || recordHeaders[type])\n}\n\nfunction shouldRecordBody({\n type,\n recordBody,\n headers,\n}: {\n type: 'request' | 'response'\n recordBody: NetworkRecordOptions['recordBody']\n headers: Headers\n url: string | URL | RequestInfo\n}) {\n function matchesContentType(contentTypes: string[]) {\n const contentTypeHeader = Object.keys(headers).find((key) => key.toLowerCase() === 'content-type')\n const contentType = contentTypeHeader && headers[contentTypeHeader]\n return contentTypes.some((ct) => contentType?.includes(ct))\n }\n\n if (!recordBody) return false\n if (isBoolean(recordBody)) return true\n if (isArray(recordBody)) return matchesContentType(recordBody)\n const recordBodyType = recordBody[type]\n if (isBoolean(recordBodyType)) return recordBodyType\n return matchesContentType(recordBodyType)\n}\n\nasync function getRequestPerformanceEntry(\n win: IWindow,\n initiatorType: string,\n url: string,\n start?: number,\n end?: number,\n attempt = 0\n): Promise {\n if (attempt > 10) {\n logger.warn('Failed to get performance entry for request', { url, initiatorType })\n return null\n }\n const urlPerformanceEntries = win.performance.getEntriesByName(url) as PerformanceResourceTiming[]\n const performanceEntry = findLast(\n urlPerformanceEntries,\n (entry) =>\n isResourceTiming(entry) &&\n entry.initiatorType === initiatorType &&\n (isUndefined(start) || entry.startTime >= start) &&\n (isUndefined(end) || entry.startTime <= end)\n )\n if (!performanceEntry) {\n await new Promise((resolve) => setTimeout(resolve, 50 * attempt))\n return getRequestPerformanceEntry(win, initiatorType, url, start, end, attempt + 1)\n }\n return performanceEntry\n}\n\n/**\n * According to MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response\n * xhr response is typed as any but can be an ArrayBuffer, a Blob, a Document, a JavaScript object,\n * or a string, depending on the value of XMLHttpRequest.responseType, that contains the response entity body.\n *\n * XHR request body is Document | XMLHttpRequestBodyInit | null | undefined\n */\nfunction _tryReadXHRBody({\n body,\n options,\n url,\n}: {\n body: Document | XMLHttpRequestBodyInit | any | null | undefined\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): string | null {\n if (isNullish(body)) {\n return null\n }\n\n const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n if (isHostDenied) {\n return hostname + ' is in deny list'\n }\n\n if (isString(body)) {\n return body\n }\n\n if (isDocument(body)) {\n return body.textContent\n }\n\n if (isFormData(body)) {\n return formDataToQuery(body)\n }\n\n if (isObject(body)) {\n try {\n return JSON.stringify(body)\n } catch {\n return '[SessionReplay] Failed to stringify response object'\n }\n }\n\n return '[SessionReplay] Cannot read body of type ' + toString.call(body)\n}\n\nfunction initXhrObserver(cb: networkCallback, win: IWindow, options: Required): listenerHandler {\n if (!options.initiatorTypes.includes('xmlhttprequest')) {\n return () => {\n //\n }\n }\n const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders)\n const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders)\n\n const restorePatch = patch(\n win.XMLHttpRequest.prototype,\n 'open',\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n (originalOpen: typeof XMLHttpRequest.prototype.open) => {\n return function (\n method: string,\n url: string | URL,\n async = true,\n username?: string | null,\n password?: string | null\n ) {\n // because this function is returned in its actual context `this` _is_ an XMLHttpRequest\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const xhr = this as XMLHttpRequest\n\n // check IE earlier than this, we only initialize if Request is present\n // eslint-disable-next-line compat/compat\n const req = new Request(url)\n const networkRequest: Partial = {}\n let start: number | undefined\n let end: number | undefined\n\n const requestHeaders: Headers = {}\n const originalSetRequestHeader = xhr.setRequestHeader.bind(xhr)\n xhr.setRequestHeader = (header: string, value: string) => {\n requestHeaders[header] = value\n return originalSetRequestHeader(header, value)\n }\n if (recordRequestHeaders) {\n networkRequest.requestHeaders = requestHeaders\n }\n\n const originalSend = xhr.send.bind(xhr)\n xhr.send = (body) => {\n if (\n shouldRecordBody({\n type: 'request',\n headers: requestHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.requestBody = _tryReadXHRBody({ body, options, url })\n }\n start = win.performance.now()\n return originalSend(body)\n }\n\n xhr.addEventListener('readystatechange', () => {\n if (xhr.readyState !== xhr.DONE) {\n return\n }\n end = win.performance.now()\n const responseHeaders: Headers = {}\n const rawHeaders = xhr.getAllResponseHeaders()\n const headers = rawHeaders.trim().split(/[\\r\\n]+/)\n headers.forEach((line) => {\n const parts = line.split(': ')\n const header = parts.shift()\n const value = parts.join(': ')\n if (header) {\n responseHeaders[header] = value\n }\n })\n if (recordResponseHeaders) {\n networkRequest.responseHeaders = responseHeaders\n }\n if (\n shouldRecordBody({\n type: 'response',\n headers: responseHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.responseBody = _tryReadXHRBody({ body: xhr.response, options, url })\n }\n getRequestPerformanceEntry(win, 'xmlhttprequest', req.url, start, end)\n .then((entry) => {\n const requests = prepareRequest({\n entry,\n method: req.method,\n status: xhr?.status,\n networkRequest,\n start,\n end,\n url: url.toString(),\n initiatorType: 'xmlhttprequest',\n })\n cb({ requests })\n })\n .catch(() => {\n //\n })\n })\n originalOpen.call(xhr, method, url, async, username, password)\n }\n }\n )\n return () => {\n restorePatch()\n }\n}\n\n/**\n * Check if this PerformanceEntry is either a PerformanceResourceTiming or a PerformanceNavigationTiming\n * NB PerformanceNavigationTiming extends PerformanceResourceTiming\n * Here we don't care which interface it implements as both expose `serverTimings`\n */\nconst exposesServerTiming = (event: PerformanceEntry | null): event is PerformanceResourceTiming =>\n !isNull(event) && (event.entryType === 'navigation' || event.entryType === 'resource')\n\nfunction prepareRequest({\n entry,\n method,\n status,\n networkRequest,\n isInitial,\n start,\n end,\n url,\n initiatorType,\n}: {\n entry: PerformanceResourceTiming | null\n method: string | undefined\n status: number | undefined\n networkRequest: Partial\n isInitial?: boolean\n start?: number\n end?: number\n // if there is no performance observer entry, we still need to know the url\n url?: string\n // if there is no performance observer entry, we can provide the initiatorType\n initiatorType?: string\n}): CapturedNetworkRequest[] {\n start = entry ? entry.startTime : start\n end = entry ? entry.responseEnd : end\n\n // kudos to sentry javascript sdk for excellent background on why to use Date.now() here\n // https://github.com/getsentry/sentry-javascript/blob/e856e40b6e71a73252e788cd42b5260f81c9c88e/packages/utils/src/time.ts#L70\n // can't start observer if performance.now() is not available\n // eslint-disable-next-line compat/compat\n const timeOrigin = Math.floor(Date.now() - performance.now())\n // clickhouse can't ingest timestamps that are floats\n // (in this case representing fractions of a millisecond we don't care about anyway)\n // use timeOrigin if we really can't gather a start time\n const timestamp = Math.floor(timeOrigin + (start || 0))\n\n const entryJSON = entry ? entry.toJSON() : { name: url }\n\n const requests: CapturedNetworkRequest[] = [\n {\n ...entryJSON,\n startTime: isUndefined(start) ? undefined : Math.round(start),\n endTime: isUndefined(end) ? undefined : Math.round(end),\n timeOrigin,\n timestamp,\n method: method,\n initiatorType: entry ? (entry.initiatorType as InitiatorType) : initiatorType,\n status,\n requestHeaders: networkRequest.requestHeaders,\n requestBody: networkRequest.requestBody,\n responseHeaders: networkRequest.responseHeaders,\n responseBody: networkRequest.responseBody,\n isInitial,\n },\n ]\n\n if (exposesServerTiming(entry)) {\n for (const timing of entry.serverTiming || []) {\n requests.push({\n timeOrigin,\n timestamp,\n startTime: Math.round(entry.startTime),\n name: timing.name,\n duration: timing.duration,\n // the spec has a closed list of possible types\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType\n // but, we need to know this was a server timing so that we know to\n // match it to the appropriate navigation or resource timing\n // that matching will have to be on timestamp and $current_url\n entryType: 'serverTiming',\n })\n }\n }\n\n return requests\n}\n\nconst contentTypePrefixDenyList = ['video/', 'audio/']\n\nfunction _checkForCannotReadResponseBody({\n r,\n options,\n url,\n}: {\n r: Response\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): string | null {\n if (r.headers.get('Transfer-Encoding') === 'chunked') {\n return 'Chunked Transfer-Encoding is not supported'\n }\n\n // `get` and `has` are case-insensitive\n // but return the header value with the casing that was supplied\n const contentType = r.headers.get('Content-Type')?.toLowerCase()\n const contentTypeIsDenied = contentTypePrefixDenyList.some((prefix) => contentType?.startsWith(prefix))\n if (contentType && contentTypeIsDenied) {\n return `Content-Type ${contentType} is not supported`\n }\n\n const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n if (isHostDenied) {\n return hostname + ' is in deny list'\n }\n\n return null\n}\n\nfunction _tryReadBody(r: Request | Response): Promise {\n // there are now already multiple places where we're using Promise...\n // eslint-disable-next-line compat/compat\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => resolve('[SessionReplay] Timeout while trying to read body'), 500)\n try {\n r.clone()\n .text()\n .then(\n (txt) => resolve(txt),\n (reason) => reject(reason)\n )\n .finally(() => clearTimeout(timeout))\n } catch {\n clearTimeout(timeout)\n resolve('[SessionReplay] Failed to read body')\n }\n })\n}\n\nasync function _tryReadRequestBody({\n r,\n options,\n url,\n}: {\n r: Request\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): Promise {\n const { hostname, isHostDenied } = isHostOnDenyList(url, options)\n if (isHostDenied) {\n return Promise.resolve(hostname + ' is in deny list')\n }\n\n return _tryReadBody(r)\n}\n\nasync function _tryReadResponseBody({\n r,\n options,\n url,\n}: {\n r: Response\n options: NetworkRecordOptions\n url: string | URL | RequestInfo\n}): Promise {\n const cannotReadBodyReason: string | null = _checkForCannotReadResponseBody({ r, options, url })\n if (!isNull(cannotReadBodyReason)) {\n return Promise.resolve(cannotReadBodyReason)\n }\n\n return _tryReadBody(r)\n}\n\nfunction initFetchObserver(\n cb: networkCallback,\n win: IWindow,\n options: Required\n): listenerHandler {\n if (!options.initiatorTypes.includes('fetch')) {\n return () => {\n //\n }\n }\n const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders)\n const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders)\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const restorePatch = patch(win, 'fetch', (originalFetch: typeof fetch) => {\n return async function (url: URL | RequestInfo, init?: RequestInit | undefined) {\n // check IE earlier than this, we only initialize if Request is present\n // eslint-disable-next-line compat/compat\n const req = new Request(url, init)\n let res: Response | undefined\n const networkRequest: Partial = {}\n let start: number | undefined\n let end: number | undefined\n\n try {\n const requestHeaders: Headers = {}\n req.headers.forEach((value, header) => {\n requestHeaders[header] = value\n })\n if (recordRequestHeaders) {\n networkRequest.requestHeaders = requestHeaders\n }\n if (\n shouldRecordBody({\n type: 'request',\n headers: requestHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.requestBody = await _tryReadRequestBody({ r: req, options, url })\n }\n\n start = win.performance.now()\n res = await originalFetch(req)\n end = win.performance.now()\n\n const responseHeaders: Headers = {}\n res.headers.forEach((value, header) => {\n responseHeaders[header] = value\n })\n if (recordResponseHeaders) {\n networkRequest.responseHeaders = responseHeaders\n }\n if (\n shouldRecordBody({\n type: 'response',\n headers: responseHeaders,\n url,\n recordBody: options.recordBody,\n })\n ) {\n networkRequest.responseBody = await _tryReadResponseBody({ r: res, options, url })\n }\n\n return res\n } finally {\n getRequestPerformanceEntry(win, 'fetch', req.url, start, end)\n .then((entry) => {\n const requests = prepareRequest({\n entry,\n method: req.method,\n status: res?.status,\n networkRequest,\n start,\n end,\n url: req.url,\n initiatorType: 'fetch',\n })\n cb({ requests })\n })\n .catch(() => {\n //\n })\n }\n }\n })\n return () => {\n restorePatch()\n }\n}\n\nlet initialisedHandler: listenerHandler | null = null\n\nfunction initNetworkObserver(\n callback: networkCallback,\n win: IWindow, // top window or in an iframe\n options: NetworkRecordOptions\n): listenerHandler {\n if (!('performance' in win)) {\n return () => {\n //\n }\n }\n\n if (initialisedHandler) {\n logger.warn('Network observer already initialised, doing nothing')\n return () => {\n // the first caller should already have this handler and will be responsible for teardown\n }\n }\n\n const networkOptions = (\n options ? Object.assign({}, defaultNetworkOptions, options) : defaultNetworkOptions\n ) as Required\n\n const cb: networkCallback = (data) => {\n const requests: CapturedNetworkRequest[] = []\n data.requests.forEach((request) => {\n const maskedRequest = networkOptions.maskRequestFn(request)\n if (maskedRequest) {\n requests.push(maskedRequest)\n }\n })\n\n if (requests.length > 0) {\n callback({ ...data, requests })\n }\n }\n const performanceObserver = initPerformanceObserver(cb, win, networkOptions)\n\n // only wrap fetch and xhr if headers or body are being recorded\n let xhrObserver: listenerHandler = () => {}\n let fetchObserver: listenerHandler = () => {}\n if (networkOptions.recordHeaders || networkOptions.recordBody) {\n xhrObserver = initXhrObserver(cb, win, networkOptions)\n fetchObserver = initFetchObserver(cb, win, networkOptions)\n }\n\n initialisedHandler = () => {\n performanceObserver()\n xhrObserver()\n fetchObserver()\n }\n return initialisedHandler\n}\n\n// use the plugin name so that when this functionality is adopted into rrweb\n// we can remove this plugin and use the core functionality with the same data\nexport const NETWORK_PLUGIN_NAME = 'rrweb/network@1'\n\n// TODO how should this be typed?\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nexport const getRecordNetworkPlugin: (options?: NetworkRecordOptions) => RecordPlugin = (options) => {\n return {\n name: NETWORK_PLUGIN_NAME,\n observer: initNetworkObserver,\n options: options,\n }\n}\n\n// rrweb/networ@1 ends\n\nassignableWindow.__PosthogExtensions__ = assignableWindow.__PosthogExtensions__ || {}\nassignableWindow.__PosthogExtensions__.rrwebPlugins = { getRecordConsolePlugin, getRecordNetworkPlugin }\nassignableWindow.__PosthogExtensions__.rrweb = { record: rrwebRecord, version: 'v2', rrwebVersion: version }\n\n// we used to put all of these items directly on window, and now we put it on __PosthogExtensions__\n// but that means that old clients which lazily load this extension are looking in the wrong place\n// yuck,\n// so we also put them directly on the window\n// when 1.161.1 is the oldest version seen in production we can remove this\nassignableWindow.rrweb = { record: rrwebRecord, version: 'v2', rrwebVersion: version }\nassignableWindow.rrwebConsoleRecord = { getRecordConsolePlugin }\nassignableWindow.getRecordNetworkPlugin = getRecordNetworkPlugin\n\nexport default rrwebRecord\n","/**\n * Having Survey types in types.ts was confusing tsc\n * and generating an invalid module.d.ts\n * See https://github.com/PostHog/posthog-js/issues/698\n */\n\nexport interface SurveyAppearance {\n // keep in sync with frontend/src/types.ts -> SurveyAppearance\n backgroundColor?: string\n submitButtonColor?: string\n // text color is deprecated, use auto contrast text color instead\n textColor?: string\n // deprecate submit button text eventually\n submitButtonText?: string\n submitButtonTextColor?: string\n descriptionTextColor?: string\n ratingButtonColor?: string\n ratingButtonActiveColor?: string\n ratingButtonHoverColor?: string\n whiteLabel?: boolean\n autoDisappear?: boolean\n displayThankYouMessage?: boolean\n thankYouMessageHeader?: string\n thankYouMessageDescription?: string\n thankYouMessageDescriptionContentType?: SurveyQuestionDescriptionContentType\n thankYouMessageCloseButtonText?: string\n borderColor?: string\n position?: 'left' | 'right' | 'center'\n placeholder?: string\n shuffleQuestions?: boolean\n surveyPopupDelaySeconds?: number\n // widget options\n widgetType?: 'button' | 'tab' | 'selector'\n widgetSelector?: string\n widgetLabel?: string\n widgetColor?: string\n // questionable: Not in frontend/src/types.ts -> SurveyAppearance, but used in site app\n maxWidth?: string\n zIndex?: string\n}\n\nexport enum SurveyType {\n Popover = 'popover',\n API = 'api',\n Widget = 'widget',\n}\n\nexport type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion\n\nexport type SurveyQuestionDescriptionContentType = 'html' | 'text'\n\ninterface SurveyQuestionBase {\n question: string\n description?: string | null\n descriptionContentType?: SurveyQuestionDescriptionContentType\n optional?: boolean\n buttonText?: string\n originalQuestionIndex: number\n branching?: NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching\n}\n\nexport interface BasicSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.Open\n}\n\nexport interface LinkSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.Link\n link?: string | null\n}\n\nexport interface RatingSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.Rating\n display: 'number' | 'emoji'\n scale: 3 | 5 | 7 | 10\n lowerBoundLabel: string\n upperBoundLabel: string\n}\n\nexport interface MultipleSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice\n choices: string[]\n hasOpenChoice?: boolean\n shuffleOptions?: boolean\n}\n\nexport enum SurveyQuestionType {\n Open = 'open',\n MultipleChoice = 'multiple_choice',\n SingleChoice = 'single_choice',\n Rating = 'rating',\n Link = 'link',\n}\n\nexport enum SurveyQuestionBranchingType {\n NextQuestion = 'next_question',\n End = 'end',\n ResponseBased = 'response_based',\n SpecificQuestion = 'specific_question',\n}\n\ninterface NextQuestionBranching {\n type: SurveyQuestionBranchingType.NextQuestion\n}\n\ninterface EndBranching {\n type: SurveyQuestionBranchingType.End\n}\n\ninterface ResponseBasedBranching {\n type: SurveyQuestionBranchingType.ResponseBased\n responseValues: Record\n}\n\ninterface SpecificQuestionBranching {\n type: SurveyQuestionBranchingType.SpecificQuestion\n index: number\n}\n\nexport interface SurveyResponse {\n surveys: Survey[]\n}\n\nexport type SurveyCallback = (surveys: Survey[]) => void\n\nexport type SurveyUrlMatchType = 'regex' | 'not_regex' | 'exact' | 'is_not' | 'icontains' | 'not_icontains'\n\nexport interface SurveyElement {\n text?: string\n $el_text?: string\n tag_name?: string\n href?: string\n attr_id?: string\n attr_class?: string[]\n nth_child?: number\n nth_of_type?: number\n attributes?: Record\n event_id?: number\n order?: number\n group_id?: number\n}\nexport interface SurveyRenderReason {\n visible: boolean\n disabledReason?: string\n}\n\nexport interface Survey {\n // Sync this with the backend's SurveyAPISerializer!\n id: string\n name: string\n description: string\n type: SurveyType\n linked_flag_key: string | null\n targeting_flag_key: string | null\n internal_targeting_flag_key: string | null\n questions: SurveyQuestion[]\n appearance: SurveyAppearance | null\n conditions: {\n url?: string\n selector?: string\n seenSurveyWaitPeriodInDays?: number\n urlMatchType?: SurveyUrlMatchType\n events: {\n repeatedActivation?: boolean\n values: {\n name: string\n }[]\n } | null\n actions: {\n values: ActionType[]\n } | null\n } | null\n start_date: string | null\n end_date: string | null\n current_iteration: number | null\n current_iteration_start_date: string | null\n}\n\nexport interface ActionType {\n count?: number\n created_at: string\n deleted?: boolean\n id: number\n name: string | null\n steps?: ActionStepType[]\n tags?: string[]\n is_action?: true\n action_id?: number // alias of id to make it compatible with event definitions uuid\n}\n\n/** Sync with plugin-server/src/types.ts */\nexport type ActionStepStringMatching = 'contains' | 'exact' | 'regex'\n\nexport interface ActionStepType {\n event?: string | null\n selector?: string | null\n /** @deprecated Only `selector` should be used now. */\n tag_name?: string\n text?: string | null\n /** @default StringMatching.Exact */\n text_matching?: ActionStepStringMatching | null\n href?: string | null\n /** @default ActionStepStringMatching.Exact */\n href_matching?: ActionStepStringMatching | null\n url?: string | null\n /** @default StringMatching.Contains */\n url_matching?: ActionStepStringMatching | null\n}\n","var n,l,u,t,i,o,r,f,e,c={},s=[],a=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,h=Array.isArray;function v(n,l){for(var u in l)n[u]=l[u];return n}function p(n){var l=n.parentNode;l&&l.removeChild(n)}function y(l,u,t){var i,o,r,f={};for(r in u)\"key\"==r?i=u[r]:\"ref\"==r?o=u[r]:f[r]=u[r];if(arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):t),\"function\"==typeof l&&null!=l.defaultProps)for(r in l.defaultProps)void 0===f[r]&&(f[r]=l.defaultProps[r]);return d(l,f,i,o,null)}function d(n,t,i,o,r){var f={type:n,props:t,key:i,ref:o,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:null==r?++u:r,__i:-1,__u:0};return null==r&&null!=l.vnode&&l.vnode(f),f}function _(){return{current:null}}function g(n){return n.children}function b(n,l){this.props=n,this.context=l}function m(n,l){if(null==l)return n.__?m(n.__,n.__i+1):null;for(var u;lu&&i.sort(f));x.__r=0}function C(n,l,u,t,i,o,r,f,e,a,h){var v,p,y,d,_,g=t&&t.__k||s,b=l.length;for(u.__d=e,P(u,l,g),e=u.__d,v=0;v0?d(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):i)?(i.__=n,i.__b=n.__b+1,f=H(i,u,r=t+a,s),i.__i=f,o=null,-1!==f&&(s--,(o=u[f])&&(o.__u|=131072)),null==o||null===o.__v?(-1==f&&a--,\"function\"!=typeof i.type&&(i.__u|=65536)):f!==r&&(f===r+1?a++:f>r?s>e-r?a+=f-r:a--:a=f(null!=e&&0==(131072&e.__u)?1:0))for(;r>=0||f=0){if((e=l[r])&&0==(131072&e.__u)&&i==e.key&&o===e.type)return r;r--}if(f2&&(e.children=arguments.length>3?n.call(arguments,2):t),d(l.type,e,i||l.key,o||l.ref,null)}function F(n,l){var u={__c:l=\"__cC\"+e++,__:n,Consumer:function(n,l){return n.children(l)},Provider:function(n){var u,t;return this.getChildContext||(u=[],(t={})[l]=this,this.getChildContext=function(){return t},this.shouldComponentUpdate=function(n){this.props.value!==n.value&&u.some(function(n){n.__e=!0,w(n)})},this.sub=function(n){u.push(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u.splice(u.indexOf(n),1),l&&l.call(n)}}),n.children}};return u.Provider.__=u.Consumer.contextType=u}n=s.slice,l={__e:function(n,l,u,t){for(var i,o,r;l=l.__;)if((i=l.__c)&&!i.__)try{if((o=i.constructor)&&null!=o.getDerivedStateFromError&&(i.setState(o.getDerivedStateFromError(n)),r=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(n,t||{}),r=i.__d),r)return i.__E=i}catch(l){n=l}throw n}},u=0,t=function(n){return null!=n&&null==n.constructor},b.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=v({},this.state),\"function\"==typeof n&&(n=n(v({},u),this.props)),n&&v(u,n),null!=n&&this.__v&&(l&&this._sb.push(l),w(this))},b.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),w(this))},b.prototype.render=g,i=[],r=\"function\"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,f=function(n,l){return n.__v.__b-l.__v.__b},x.__r=0,e=0;export{b as Component,g as Fragment,E as cloneElement,F as createContext,y as createElement,_ as createRef,y as h,B as hydrate,t as isValidElement,l as options,q as render,$ as toChildArray};\n//# sourceMappingURL=preact.module.js.map\n","import { PostHog } from '../../posthog-core'\nimport { Survey, SurveyAppearance, MultipleSurveyQuestion, SurveyQuestion } from '../../posthog-surveys-types'\nimport { window as _window, document as _document } from '../../utils/globals'\nimport { VNode, cloneElement, createContext } from 'preact'\n// We cast the types here which is dangerous but protected by the top level generateSurveys call\nconst window = _window as Window & typeof globalThis\nconst document = _document as Document\n\nexport const style = (appearance: SurveyAppearance | null) => {\n const positions = {\n left: 'left: 30px;',\n right: 'right: 30px;',\n center: `\n left: 50%;\n transform: translateX(-50%);\n `,\n }\n return `\n .survey-form, .thank-you-message {\n position: fixed;\n margin: 0px;\n bottom: 0px;\n color: black;\n font-weight: normal;\n font-family: -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", \"Roboto\", Helvetica, Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\";\n text-align: left;\n max-width: ${parseInt(appearance?.maxWidth || '300')}px;\n width: 100%;\n z-index: ${parseInt(appearance?.zIndex || '99999')};\n border: 1.5px solid ${appearance?.borderColor || '#c9c6c6'};\n border-bottom: 0px;\n ${positions[appearance?.position || 'right'] || 'right: 30px;'}\n flex-direction: column;\n background: ${appearance?.backgroundColor || '#eeeded'};\n border-top-left-radius: 10px;\n border-top-right-radius: 10px;\n box-shadow: -6px 0 16px -8px rgb(0 0 0 / 8%), -9px 0 28px 0 rgb(0 0 0 / 5%), -12px 0 48px 16px rgb(0 0 0 / 3%);\n }\n \n .survey-box, .thank-you-message-container {\n padding: 20px 25px 10px;\n display: flex;\n flex-direction: column;\n border-radius: 10px;\n }\n\n .thank-you-message {\n text-align: center;\n }\n\n .form-submit[disabled] {\n opacity: 0.6;\n filter: grayscale(50%);\n cursor: not-allowed;\n }\n .survey-form textarea {\n color: #2d2d2d;\n font-size: 14px;\n font-family: -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", \"Roboto\", Helvetica, Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\";\n background: white;\n color: black;\n outline: none;\n padding-left: 10px;\n padding-right: 10px;\n padding-top: 10px;\n border-radius: 6px;\n border-color: ${appearance?.borderColor || '#c9c6c6'};\n margin-top: 14px;\n width: 100%;\n box-sizing: border-box;\n }\n .survey-box:has(.survey-question:empty):not(:has(.survey-question-description)) textarea {\n margin-top: 0;\n }\n .form-submit {\n box-sizing: border-box;\n margin: 0;\n font-family: inherit;\n overflow: visible;\n text-transform: none;\n position: relative;\n display: inline-block;\n font-weight: 700;\n white-space: nowrap;\n text-align: center;\n border: 1.5px solid transparent;\n cursor: pointer;\n user-select: none;\n touch-action: manipulation;\n padding: 12px;\n font-size: 14px;\n border-radius: 6px;\n outline: 0;\n background: ${appearance?.submitButtonColor || 'black'} !important;\n text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.12);\n box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);\n width: 100%;\n }\n .form-cancel {\n display: flex;\n float: right;\n border: none;\n background: none;\n cursor: pointer;\n }\n .cancel-btn-wrapper {\n position: absolute;\n width: 35px;\n height: 35px;\n border-radius: 100%;\n top: 0;\n right: 0;\n transform: translate(50%, -50%);\n background: white;\n border: 1.5px solid ${appearance?.borderColor || '#c9c6c6'};\n display: flex;\n justify-content: center;\n align-items: center;\n }\n .bolded { font-weight: 600; }\n .buttons {\n display: flex;\n justify-content: center;\n }\n .footer-branding {\n font-size: 11px;\n margin-top: 10px;\n text-align: center;\n display: flex;\n justify-content: center;\n gap: 4px;\n align-items: center;\n font-weight: 500;\n background: ${appearance?.backgroundColor || '#eeeded'};\n text-decoration: none;\n backgroundColor: ${appearance?.backgroundColor || '#eeeded'};\n color: ${getContrastingTextColor(appearance?.backgroundColor || '#eeeded')};\n }\n .survey-question {\n font-weight: 500;\n font-size: 14px;\n background: ${appearance?.backgroundColor || '#eeeded'};\n }\n .question-textarea-wrapper {\n display: flex;\n flex-direction: column;\n }\n .survey-question-description {\n font-size: 13px;\n padding-top: 5px;\n background: ${appearance?.backgroundColor || '#eeeded'};\n }\n .ratings-number {\n font-size: 16px;\n font-weight: 600;\n padding: 8px 0px;\n border: none;\n }\n .ratings-number:hover {\n cursor: pointer;\n }\n .rating-options {\n margin-top: 14px;\n }\n .rating-options-number {\n display: grid;\n border-radius: 6px;\n overflow: hidden;\n border: 1.5px solid ${appearance?.borderColor || '#c9c6c6'};\n }\n .rating-options-number > .ratings-number {\n border-right: 1px solid ${appearance?.borderColor || '#c9c6c6'};\n }\n .rating-options-number > .ratings-number:last-of-type {\n border-right: 0px;\n }\n .rating-options-number .rating-active {\n background: ${appearance?.ratingButtonActiveColor || 'black'};\n }\n .rating-options-emoji {\n display: flex;\n justify-content: space-between;\n }\n .ratings-emoji {\n font-size: 16px;\n background-color: transparent;\n border: none;\n padding: 0px;\n }\n .ratings-emoji:hover {\n cursor: pointer;\n }\n .ratings-emoji.rating-active svg {\n fill: ${appearance?.ratingButtonActiveColor || 'black'};\n }\n .emoji-svg {\n fill: '#939393';\n }\n .rating-text {\n display: flex;\n flex-direction: row;\n font-size: 11px;\n justify-content: space-between;\n margin-top: 6px;\n background: ${appearance?.backgroundColor || '#eeeded'};\n opacity: .60;\n }\n .multiple-choice-options {\n margin-top: 13px;\n font-size: 14px;\n }\n .survey-box:has(.survey-question:empty):not(:has(.survey-question-description)) .multiple-choice-options {\n margin-top: 0;\n }\n .multiple-choice-options .choice-option {\n display: flex;\n align-items: center;\n gap: 4px;\n font-size: 13px;\n cursor: pointer;\n margin-bottom: 5px;\n position: relative;\n }\n .multiple-choice-options > .choice-option:last-of-type {\n margin-bottom: 0px;\n }\n .multiple-choice-options input {\n cursor: pointer;\n position: absolute;\n opacity: 0;\n }\n .choice-check {\n position: absolute;\n right: 10px;\n background: white;\n }\n .choice-check svg {\n display: none;\n }\n .multiple-choice-options .choice-option:hover .choice-check svg {\n display: inline-block;\n opacity: .25;\n }\n .multiple-choice-options input:checked + label + .choice-check svg {\n display: inline-block;\n opacity: 100% !important;\n }\n .multiple-choice-options input:checked + label {\n font-weight: bold;\n border: 1.5px solid rgba(0,0,0);\n }\n .multiple-choice-options input:checked + label input {\n font-weight: bold;\n }\n .multiple-choice-options label {\n width: 100%;\n cursor: pointer;\n padding: 10px;\n border: 1.5px solid rgba(0,0,0,.25);\n border-radius: 4px;\n background: white;\n }\n .multiple-choice-options .choice-option-open label {\n padding-right: 30px;\n display: flex;\n flex-wrap: wrap;\n gap: 8px;\n max-width: 100%;\n }\n .multiple-choice-options .choice-option-open label span {\n width: 100%;\n }\n .multiple-choice-options .choice-option-open input:disabled + label {\n opacity: 0.6;\n }\n .multiple-choice-options .choice-option-open label input {\n position: relative;\n opacity: 1;\n flex-grow: 1;\n border: 0;\n outline: 0;\n }\n .thank-you-message-body {\n margin-top: 6px;\n font-size: 14px;\n background: ${appearance?.backgroundColor || '#eeeded'};\n }\n .thank-you-message-header {\n margin: 10px 0px 0px;\n background: ${appearance?.backgroundColor || '#eeeded'};\n }\n .thank-you-message-container .form-submit {\n margin-top: 20px;\n margin-bottom: 10px;\n }\n .thank-you-message-countdown {\n margin-left: 6px;\n }\n .bottom-section {\n margin-top: 14px;\n }\n `\n}\n\nfunction nameToHex(name: string) {\n return {\n aliceblue: '#f0f8ff',\n antiquewhite: '#faebd7',\n aqua: '#00ffff',\n aquamarine: '#7fffd4',\n azure: '#f0ffff',\n beige: '#f5f5dc',\n bisque: '#ffe4c4',\n black: '#000000',\n blanchedalmond: '#ffebcd',\n blue: '#0000ff',\n blueviolet: '#8a2be2',\n brown: '#a52a2a',\n burlywood: '#deb887',\n cadetblue: '#5f9ea0',\n chartreuse: '#7fff00',\n chocolate: '#d2691e',\n coral: '#ff7f50',\n cornflowerblue: '#6495ed',\n cornsilk: '#fff8dc',\n crimson: '#dc143c',\n cyan: '#00ffff',\n darkblue: '#00008b',\n darkcyan: '#008b8b',\n darkgoldenrod: '#b8860b',\n darkgray: '#a9a9a9',\n darkgreen: '#006400',\n darkkhaki: '#bdb76b',\n darkmagenta: '#8b008b',\n darkolivegreen: '#556b2f',\n darkorange: '#ff8c00',\n darkorchid: '#9932cc',\n darkred: '#8b0000',\n darksalmon: '#e9967a',\n darkseagreen: '#8fbc8f',\n darkslateblue: '#483d8b',\n darkslategray: '#2f4f4f',\n darkturquoise: '#00ced1',\n darkviolet: '#9400d3',\n deeppink: '#ff1493',\n deepskyblue: '#00bfff',\n dimgray: '#696969',\n dodgerblue: '#1e90ff',\n firebrick: '#b22222',\n floralwhite: '#fffaf0',\n forestgreen: '#228b22',\n fuchsia: '#ff00ff',\n gainsboro: '#dcdcdc',\n ghostwhite: '#f8f8ff',\n gold: '#ffd700',\n goldenrod: '#daa520',\n gray: '#808080',\n green: '#008000',\n greenyellow: '#adff2f',\n honeydew: '#f0fff0',\n hotpink: '#ff69b4',\n 'indianred ': '#cd5c5c',\n indigo: '#4b0082',\n ivory: '#fffff0',\n khaki: '#f0e68c',\n lavender: '#e6e6fa',\n lavenderblush: '#fff0f5',\n lawngreen: '#7cfc00',\n lemonchiffon: '#fffacd',\n lightblue: '#add8e6',\n lightcoral: '#f08080',\n lightcyan: '#e0ffff',\n lightgoldenrodyellow: '#fafad2',\n lightgrey: '#d3d3d3',\n lightgreen: '#90ee90',\n lightpink: '#ffb6c1',\n lightsalmon: '#ffa07a',\n lightseagreen: '#20b2aa',\n lightskyblue: '#87cefa',\n lightslategray: '#778899',\n lightsteelblue: '#b0c4de',\n lightyellow: '#ffffe0',\n lime: '#00ff00',\n limegreen: '#32cd32',\n linen: '#faf0e6',\n magenta: '#ff00ff',\n maroon: '#800000',\n mediumaquamarine: '#66cdaa',\n mediumblue: '#0000cd',\n mediumorchid: '#ba55d3',\n mediumpurple: '#9370d8',\n mediumseagreen: '#3cb371',\n mediumslateblue: '#7b68ee',\n mediumspringgreen: '#00fa9a',\n mediumturquoise: '#48d1cc',\n mediumvioletred: '#c71585',\n midnightblue: '#191970',\n mintcream: '#f5fffa',\n mistyrose: '#ffe4e1',\n moccasin: '#ffe4b5',\n navajowhite: '#ffdead',\n navy: '#000080',\n oldlace: '#fdf5e6',\n olive: '#808000',\n olivedrab: '#6b8e23',\n orange: '#ffa500',\n orangered: '#ff4500',\n orchid: '#da70d6',\n palegoldenrod: '#eee8aa',\n palegreen: '#98fb98',\n paleturquoise: '#afeeee',\n palevioletred: '#d87093',\n papayawhip: '#ffefd5',\n peachpuff: '#ffdab9',\n peru: '#cd853f',\n pink: '#ffc0cb',\n plum: '#dda0dd',\n powderblue: '#b0e0e6',\n purple: '#800080',\n red: '#ff0000',\n rosybrown: '#bc8f8f',\n royalblue: '#4169e1',\n saddlebrown: '#8b4513',\n salmon: '#fa8072',\n sandybrown: '#f4a460',\n seagreen: '#2e8b57',\n seashell: '#fff5ee',\n sienna: '#a0522d',\n silver: '#c0c0c0',\n skyblue: '#87ceeb',\n slateblue: '#6a5acd',\n slategray: '#708090',\n snow: '#fffafa',\n springgreen: '#00ff7f',\n steelblue: '#4682b4',\n tan: '#d2b48c',\n teal: '#008080',\n thistle: '#d8bfd8',\n tomato: '#ff6347',\n turquoise: '#40e0d0',\n violet: '#ee82ee',\n wheat: '#f5deb3',\n white: '#ffffff',\n whitesmoke: '#f5f5f5',\n yellow: '#ffff00',\n yellowgreen: '#9acd32',\n }[name.toLowerCase()]\n}\n\nfunction hex2rgb(c: string) {\n if (c[0] === '#') {\n const hexColor = c.replace(/^#/, '')\n const r = parseInt(hexColor.slice(0, 2), 16)\n const g = parseInt(hexColor.slice(2, 4), 16)\n const b = parseInt(hexColor.slice(4, 6), 16)\n return 'rgb(' + r + ',' + g + ',' + b + ')'\n }\n return 'rgb(255, 255, 255)'\n}\n\nexport function getContrastingTextColor(color: string = defaultBackgroundColor) {\n let rgb\n if (color[0] === '#') {\n rgb = hex2rgb(color)\n }\n if (color.startsWith('rgb')) {\n rgb = color\n }\n // otherwise it's a color name\n const nameColorToHex = nameToHex(color)\n if (nameColorToHex) {\n rgb = hex2rgb(nameColorToHex)\n }\n if (!rgb) {\n return 'black'\n }\n const colorMatch = rgb.match(/^rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*(\\d+(?:\\.\\d+)?))?\\)$/)\n if (colorMatch) {\n const r = parseInt(colorMatch[1])\n const g = parseInt(colorMatch[2])\n const b = parseInt(colorMatch[3])\n const hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b))\n return hsp > 127.5 ? 'black' : 'white'\n }\n return 'black'\n}\nexport function getTextColor(el: HTMLElement) {\n const backgroundColor = window.getComputedStyle(el).backgroundColor\n if (backgroundColor === 'rgba(0, 0, 0, 0)') {\n return 'black'\n }\n const colorMatch = backgroundColor.match(/^rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*(\\d+(?:\\.\\d+)?))?\\)$/)\n if (!colorMatch) return 'black'\n\n const r = parseInt(colorMatch[1])\n const g = parseInt(colorMatch[2])\n const b = parseInt(colorMatch[3])\n const hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b))\n return hsp > 127.5 ? 'black' : 'white'\n}\n\nexport const defaultSurveyAppearance: SurveyAppearance = {\n backgroundColor: '#eeeded',\n submitButtonColor: 'black',\n submitButtonTextColor: 'white',\n ratingButtonColor: 'white',\n ratingButtonActiveColor: 'black',\n borderColor: '#c9c6c6',\n placeholder: 'Start typing...',\n whiteLabel: false,\n displayThankYouMessage: true,\n thankYouMessageHeader: 'Thank you for your feedback!',\n position: 'right',\n}\n\nexport const defaultBackgroundColor = '#eeeded'\n\nexport const createShadow = (styleSheet: string, surveyId: string, element?: Element) => {\n const div = document.createElement('div')\n div.className = `PostHogSurvey${surveyId}`\n const shadow = div.attachShadow({ mode: 'open' })\n if (styleSheet) {\n const styleElement = Object.assign(document.createElement('style'), {\n innerText: styleSheet,\n })\n shadow.appendChild(styleElement)\n }\n ;(element ? element : document.body).appendChild(div)\n return shadow\n}\n\nexport const sendSurveyEvent = (\n responses: Record = {},\n survey: Survey,\n posthog?: PostHog\n) => {\n if (!posthog) return\n localStorage.setItem(getSurveySeenKey(survey), 'true')\n\n posthog.capture('survey sent', {\n $survey_name: survey.name,\n $survey_id: survey.id,\n $survey_iteration: survey.current_iteration,\n $survey_iteration_start_date: survey.current_iteration_start_date,\n $survey_questions: survey.questions.map((question) => question.question),\n sessionRecordingUrl: posthog.get_session_replay_url?.(),\n ...responses,\n $set: {\n [getSurveyInteractionProperty(survey, 'responded')]: true,\n },\n })\n window.dispatchEvent(new Event('PHSurveySent'))\n}\n\nexport const dismissedSurveyEvent = (survey: Survey, posthog?: PostHog, readOnly?: boolean) => {\n // TODO: state management and unit tests for this would be nice\n if (readOnly || !posthog) {\n return\n }\n posthog.capture('survey dismissed', {\n $survey_name: survey.name,\n $survey_id: survey.id,\n $survey_iteration: survey.current_iteration,\n $survey_iteration_start_date: survey.current_iteration_start_date,\n sessionRecordingUrl: posthog.get_session_replay_url?.(),\n $set: {\n [getSurveyInteractionProperty(survey, 'dismissed')]: true,\n },\n })\n localStorage.setItem(getSurveySeenKey(survey), 'true')\n window.dispatchEvent(new Event('PHSurveyClosed'))\n}\n\n// Use the Fisher-yates algorithm to shuffle this array\n// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\nexport const shuffle = (array: any[]) => {\n return array\n .map((a) => ({ sort: Math.floor(Math.random() * 10), value: a }))\n .sort((a, b) => a.sort - b.sort)\n .map((a) => a.value)\n}\n\nconst reverseIfUnshuffled = (unshuffled: any[], shuffled: any[]): any[] => {\n if (unshuffled.length === shuffled.length && unshuffled.every((val, index) => val === shuffled[index])) {\n return shuffled.reverse()\n }\n\n return shuffled\n}\n\nexport const getDisplayOrderChoices = (question: MultipleSurveyQuestion): string[] => {\n if (!question.shuffleOptions) {\n return question.choices\n }\n\n const displayOrderChoices = question.choices\n let openEndedChoice = ''\n if (question.hasOpenChoice) {\n // if the question has an open-ended choice, its always the last element in the choices array.\n openEndedChoice = displayOrderChoices.pop()!\n }\n\n const shuffledOptions = reverseIfUnshuffled(displayOrderChoices, shuffle(displayOrderChoices))\n\n if (question.hasOpenChoice) {\n question.choices.push(openEndedChoice)\n shuffledOptions.push(openEndedChoice)\n }\n\n return shuffledOptions\n}\n\nexport const getDisplayOrderQuestions = (survey: Survey): SurveyQuestion[] => {\n // retain the original questionIndex so we can correlate values in the webapp\n survey.questions.forEach((question, idx) => {\n question.originalQuestionIndex = idx\n })\n\n if (!survey.appearance || !survey.appearance.shuffleQuestions) {\n return survey.questions\n }\n\n return reverseIfUnshuffled(survey.questions, shuffle(survey.questions))\n}\n\nexport const hasEvents = (survey: Survey): boolean => {\n return survey.conditions?.events?.values?.length != undefined && survey.conditions?.events?.values?.length > 0\n}\n\nexport const canActivateRepeatedly = (survey: Survey): boolean => {\n return !!(survey.conditions?.events?.repeatedActivation && hasEvents(survey))\n}\n\n/**\n * getSurveySeen checks local storage for the surveySeen Key a\n * and overrides this value if the survey can be repeatedly activated by its events.\n * @param survey\n */\nexport const getSurveySeen = (survey: Survey): boolean => {\n const surveySeen = localStorage.getItem(getSurveySeenKey(survey))\n if (surveySeen) {\n // if a survey has already been seen,\n // we will override it with the event repeated activation value.\n return !canActivateRepeatedly(survey)\n }\n\n return false\n}\n\nexport const getSurveySeenKey = (survey: Survey): string => {\n let surveySeenKey = `seenSurvey_${survey.id}`\n if (survey.current_iteration && survey.current_iteration > 0) {\n surveySeenKey = `seenSurvey_${survey.id}_${survey.current_iteration}`\n }\n\n return surveySeenKey\n}\n\nconst getSurveyInteractionProperty = (survey: Survey, action: string): string => {\n let surveyProperty = `$survey_${action}/${survey.id}`\n if (survey.current_iteration && survey.current_iteration > 0) {\n surveyProperty = `$survey_${action}/${survey.id}/${survey.current_iteration}`\n }\n\n return surveyProperty\n}\n\nexport const SurveyContext = createContext<{\n isPreviewMode: boolean\n previewPageIndex: number | undefined\n handleCloseSurveyPopup: () => void\n isPopup: boolean\n}>({\n isPreviewMode: false,\n previewPageIndex: 0,\n handleCloseSurveyPopup: () => {},\n isPopup: true,\n})\n\ninterface RenderProps {\n component: VNode<{ className: string }>\n children: string\n renderAsHtml?: boolean\n style?: React.CSSProperties\n}\n\nexport const renderChildrenAsTextOrHtml = ({ component, children, renderAsHtml, style }: RenderProps) => {\n return renderAsHtml\n ? cloneElement(component, {\n dangerouslySetInnerHTML: { __html: children },\n style,\n })\n : cloneElement(component, {\n children,\n style,\n })\n}\n","import { Survey } from '../posthog-surveys-types'\nimport { document as _document } from '../utils/globals'\n\n// We cast the types here which is dangerous but protected by the top level generateSurveys call\nconst document = _document as Document\n\nexport function createWidgetShadow(survey: Survey) {\n const div = document.createElement('div')\n div.className = `PostHogWidget${survey.id}`\n const shadow = div.attachShadow({ mode: 'open' })\n const widgetStyleSheet = createWidgetStyle(survey.appearance?.widgetColor)\n shadow.append(Object.assign(document.createElement('style'), { innerText: widgetStyleSheet }))\n document.body.appendChild(div)\n return shadow\n}\n\nexport function createWidgetStyle(widgetColor?: string) {\n return `\n .ph-survey-widget-tab {\n position: fixed;\n top: 50%;\n right: 0;\n background: ${widgetColor || '#e0a045'};\n color: white;\n transform: rotate(-90deg) translate(0, -100%);\n transform-origin: right top;\n min-width: 40px;\n padding: 8px 12px;\n font-weight: 500;\n border-radius: 3px 3px 0 0;\n text-align: center;\n cursor: pointer;\n z-index: 9999999;\n }\n .ph-survey-widget-tab:hover {\n padding-bottom: 13px;\n }\n .ph-survey-widget-button {\n position: fixed;\n }\n `\n}\n","import{options as n}from\"preact\";var t,r,u,i,o=0,f=[],c=[],e=n.__b,a=n.__r,v=n.diffed,l=n.__c,m=n.unmount;function d(t,u){n.__h&&n.__h(r,t,o||u),o=0;var i=r.__H||(r.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({__V:c}),i.__[t]}function h(n){return o=1,s(B,n)}function s(n,u,i){var o=d(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):B(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}))}],o.__c=r,!r.u)){var f=function(n,t,r){if(!o.__c.__H)return!0;var u=o.__c.__H.__.filter(function(n){return n.__c});if(u.every(function(n){return!n.__N}))return!c||c.call(this,n,t,r);var i=!1;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0)}}),!(!i&&o.__c.props===n)&&(!c||c.call(this,n,t,r))};r.u=!0;var c=r.shouldComponentUpdate,e=r.componentWillUpdate;r.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u}e&&e.call(this,n,t,r)},r.shouldComponentUpdate=f}return o.__N||o.__}function p(u,i){var o=d(t++,3);!n.__s&&z(o.__H,i)&&(o.__=u,o.i=i,r.__H.__h.push(o))}function y(u,i){var o=d(t++,4);!n.__s&&z(o.__H,i)&&(o.__=u,o.i=i,r.__h.push(o))}function _(n){return o=5,F(function(){return{current:n}},[])}function A(n,t,r){o=6,y(function(){return\"function\"==typeof n?(n(t()),function(){return n(null)}):n?(n.current=t(),function(){return n.current=null}):void 0},null==r?r:r.concat(n))}function F(n,r){var u=d(t++,7);return z(u.__H,r)?(u.__V=n(),u.i=r,u.__h=n,u.__V):u.__}function T(n,t){return o=8,F(function(){return n},t)}function q(n){var u=r.context[n.__c],i=d(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function x(t,r){n.useDebugValue&&n.useDebugValue(r?r(t):t)}function P(n){var u=d(t++,10),i=h();return u.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,t){u.__&&u.__(n,t),i[1](n)}),[i[0],function(){i[1](void 0)}]}function V(){var n=d(t++,11);if(!n.__){for(var u=r.__v;null!==u&&!u.__m&&null!==u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__=\"P\"+i[0]+\"-\"+i[1]++}return n.__}function b(){for(var t;t=f.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(k),t.__H.__h.forEach(w),t.__H.__h=[]}catch(r){t.__H.__h=[],n.__e(r,t.__v)}}n.__b=function(n){r=null,e&&e(n)},n.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.forEach(function(n){n.__N&&(n.__=n.__N),n.__V=c,n.__N=n.i=void 0})):(i.__h.forEach(k),i.__h.forEach(w),i.__h=[],t=0)),u=r},n.diffed=function(t){v&&v(t);var o=t.__c;o&&o.__H&&(o.__H.__h.length&&(1!==f.push(o)&&i===n.requestAnimationFrame||((i=n.requestAnimationFrame)||j)(b)),o.__H.__.forEach(function(n){n.i&&(n.__H=n.i),n.__V!==c&&(n.__=n.__V),n.i=void 0,n.__V=c})),u=r=null},n.__c=function(t,r){r.some(function(t){try{t.__h.forEach(k),t.__h=t.__h.filter(function(n){return!n.__||w(n)})}catch(u){r.some(function(n){n.__h&&(n.__h=[])}),r=[],n.__e(u,t.__v)}}),l&&l(t,r)},n.unmount=function(t){m&&m(t);var r,u=t.__c;u&&u.__H&&(u.__H.__.forEach(function(n){try{k(n)}catch(n){r=n}}),u.__H=void 0,r&&n.__e(r,u.__v))};var g=\"function\"==typeof requestAnimationFrame;function j(n){var t,r=function(){clearTimeout(u),g&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,100);g&&(t=requestAnimationFrame(r))}function k(n){var t=r,u=n.__c;\"function\"==typeof u&&(n.__c=void 0,u()),r=t}function w(n){var t=r;n.__c=n.__(),r=t}function z(n,t){return!n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function B(n,t){return\"function\"==typeof t?t(n):t}export{T as useCallback,q as useContext,x as useDebugValue,p as useEffect,P as useErrorBoundary,V as useId,A as useImperativeHandle,y as useLayoutEffect,F as useMemo,s as useReducer,_ as useRef,h as useState};\n//# sourceMappingURL=hooks.module.js.map\n","export const satisfiedEmoji = (\n \n \n \n)\nexport const neutralEmoji = (\n \n \n \n)\nexport const dissatisfiedEmoji = (\n \n \n \n)\nexport const veryDissatisfiedEmoji = (\n \n \n \n)\nexport const verySatisfiedEmoji = (\n \n \n \n)\nexport const cancelSVG = (\n \n \n \n)\nexport const IconPosthogLogo = (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n)\nexport const checkSVG = (\n \n \n \n)\n","import { IconPosthogLogo } from '../icons'\n// import { getContrastingTextColor } from '../surveys-utils'\n\nexport function PostHogLogo() {\n // const textColor = getContrastingTextColor(backgroundColor)\n\n return (\n \n Survey by {IconPosthogLogo}\n \n )\n}\n","import { window } from '../../../utils/globals'\n\nimport { SurveyAppearance } from '../../../posthog-surveys-types'\n\nimport { PostHogLogo } from './PostHogLogo'\nimport { useContext } from 'preact/hooks'\nimport { SurveyContext, defaultSurveyAppearance, getContrastingTextColor } from '../surveys-utils'\n\nexport function BottomSection({\n text,\n submitDisabled,\n appearance,\n onSubmit,\n link,\n}: {\n text: string\n submitDisabled: boolean\n appearance: SurveyAppearance\n onSubmit: () => void\n link?: string | null\n}) {\n const { isPreviewMode, isPopup } = useContext(SurveyContext)\n const textColor =\n appearance.submitButtonTextColor ||\n getContrastingTextColor(appearance.submitButtonColor || defaultSurveyAppearance.submitButtonColor)\n return (\n
\n
\n {\n if (isPreviewMode) return\n if (link) {\n window?.open(link)\n }\n onSubmit()\n }}\n >\n {text}\n \n
\n {!appearance.whiteLabel && }\n
\n )\n}\n","import { SurveyContext, defaultSurveyAppearance, renderChildrenAsTextOrHtml } from '../surveys-utils'\nimport { cancelSVG } from '../icons'\nimport { useContext } from 'preact/hooks'\nimport { SurveyQuestionDescriptionContentType } from '../../../posthog-surveys-types'\nimport { h } from 'preact'\n\nexport function QuestionHeader({\n question,\n description,\n descriptionContentType,\n backgroundColor,\n forceDisableHtml,\n}: {\n question: string\n description?: string | null\n descriptionContentType?: SurveyQuestionDescriptionContentType\n forceDisableHtml: boolean\n backgroundColor?: string\n}) {\n const { isPopup } = useContext(SurveyContext)\n return (\n
\n
{question}
\n {description &&\n renderChildrenAsTextOrHtml({\n component: h('div', { className: 'survey-question-description' }),\n children: description,\n renderAsHtml: !forceDisableHtml && descriptionContentType !== 'text',\n })}\n
\n )\n}\n\nexport function Cancel({ onClick }: { onClick: () => void }) {\n const { isPreviewMode } = useContext(SurveyContext)\n\n return (\n
\n \n
\n )\n}\n","import { BottomSection } from './BottomSection'\nimport { Cancel } from './QuestionHeader'\nimport { SurveyAppearance, SurveyQuestionDescriptionContentType } from '../../../posthog-surveys-types'\nimport { defaultSurveyAppearance, getContrastingTextColor, renderChildrenAsTextOrHtml } from '../surveys-utils'\nimport { h } from 'preact'\n\nimport { useContext } from 'preact/hooks'\nimport { SurveyContext } from '../../surveys/surveys-utils'\n\nexport function ConfirmationMessage({\n header,\n description,\n contentType,\n forceDisableHtml,\n appearance,\n onClose,\n styleOverrides,\n}: {\n header: string\n description: string\n forceDisableHtml: boolean\n contentType?: SurveyQuestionDescriptionContentType\n appearance: SurveyAppearance\n onClose: () => void\n styleOverrides?: React.CSSProperties\n}) {\n const textColor = getContrastingTextColor(appearance.backgroundColor || defaultSurveyAppearance.backgroundColor)\n\n const { isPopup } = useContext(SurveyContext)\n\n return (\n <>\n
\n
\n {isPopup && onClose()} />}\n

\n {header}\n

\n {description &&\n renderChildrenAsTextOrHtml({\n component: h('div', { className: 'thank-you-message-body' }),\n children: description,\n renderAsHtml: !forceDisableHtml && contentType !== 'text',\n style: { color: textColor },\n })}\n {isPopup && (\n onClose()}\n />\n )}\n
\n
\n \n )\n}\n","import { useEffect, useRef, useState } from 'preact/hooks'\nimport { SurveyAppearance } from '../../../posthog-surveys-types'\nimport * as Preact from 'preact'\nimport { getTextColor } from '../surveys-utils'\n\nexport function useContrastingTextColor(options: {\n appearance: SurveyAppearance\n defaultTextColor?: string\n forceUpdate?: boolean\n}): {\n ref: Preact.RefObject\n textColor: string\n} {\n const ref = useRef(null)\n const [textColor, setTextColor] = useState(options.defaultTextColor ?? 'black')\n\n // TODO: useContext to get the background colors instead of querying the DOM\n useEffect(() => {\n if (ref.current) {\n const color = getTextColor(ref.current)\n setTextColor(color)\n }\n }, [options.appearance, options.forceUpdate])\n\n return {\n ref,\n textColor,\n }\n}\n","import {\n BasicSurveyQuestion,\n SurveyAppearance,\n LinkSurveyQuestion,\n RatingSurveyQuestion,\n MultipleSurveyQuestion,\n SurveyQuestionType,\n} from '../../../posthog-surveys-types'\nimport { RefObject } from 'preact'\nimport { useRef, useState, useMemo } from 'preact/hooks'\nimport { isNull, isArray } from '../../../utils/type-utils'\nimport { useContrastingTextColor } from '../hooks/useContrastingTextColor'\nimport {\n checkSVG,\n dissatisfiedEmoji,\n neutralEmoji,\n satisfiedEmoji,\n veryDissatisfiedEmoji,\n verySatisfiedEmoji,\n} from '../icons'\nimport { getDisplayOrderChoices } from '../surveys-utils'\nimport { BottomSection } from './BottomSection'\nimport { QuestionHeader } from './QuestionHeader'\n\nexport function OpenTextQuestion({\n question,\n forceDisableHtml,\n appearance,\n onSubmit,\n}: {\n question: BasicSurveyQuestion\n forceDisableHtml: boolean\n appearance: SurveyAppearance\n onSubmit: (text: string) => void\n}) {\n const textRef = useRef(null)\n const [text, setText] = useState('')\n\n return (\n
\n \n