posthog-js 1.412.0 → 1.412.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"product-tours-preview.js","sources":["../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/preact/10.29.3/140084fb8a57e97c29fa8a8c859027ef9e32ecc372b13de68ff8b4819864c7f8/node_modules/preact/dist/preact.module.js","../../browser-common/dist/utils/globals.mjs","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/dompurify/3.3.2/c1707aa7a756e00521933c88574fff9a86650fdb9769975ac6a467bc300c16d1/node_modules/dompurify/dist/purify.es.mjs","../../core/dist/utils/logger.mjs","../src/posthog-product-tours-types.ts","../src/constants.ts","../../core/dist/utils/type-utils.mjs","../src/extensions/product-tours/element-inference.ts","../../browser-common/dist/utils/logger.mjs","../../browser-common/dist/utils/stylesheet-loader.mjs","../src/utils/survey-utils.ts","../../browser-common/dist/utils/uuidv7.mjs","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/preact/10.29.3/140084fb8a57e97c29fa8a8c859027ef9e32ecc372b13de68ff8b4819864c7f8/node_modules/preact/hooks/dist/hooks.module.js","../src/extensions/surveys/surveys-extension-utils.tsx","../src/extensions/product-tours/product-tours-utils.ts","../src/extensions/surveys/icons.tsx","../src/extensions/product-tours/components/ProductTourBanner.tsx","../src/extensions/product-tours/components/ProductTourSurveyStepInner.tsx","../src/extensions/product-tours/components/ProductTourTooltipInner.tsx","../src/extensions/product-tours/preview.tsx"],"sourcesContent":["var n,l,u,t,i,r,o,e,f,c,a,s,h,p,v,y,d={},w=[],_=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,g=Array.isArray;function m(n,l){for(var u in l)n[u]=l[u];return n}function b(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function k(l,u,t){var i,r,o,e={};for(o in u)\"key\"==o?i=u[o]:\"ref\"==o?r=u[o]:e[o]=u[o];if(arguments.length>2&&(e.children=arguments.length>3?n.call(arguments,2):t),\"function\"==typeof l&&null!=l.defaultProps)for(o in l.defaultProps)void 0===e[o]&&(e[o]=l.defaultProps[o]);return x(l,e,i,r,null)}function x(n,t,i,r,o){var e={type:n,props:t,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==o?++u:o,__i:-1,__u:0};return null==o&&null!=l.vnode&&l.vnode(e),e}function M(){return{current:null}}function S(n){return n.children}function C(n,l){this.props=n,this.context=l}function $(n,l){if(null==l)return n.__?$(n.__,n.__i+1):null;for(var u;l<n.__k.length;l++)if(null!=(u=n.__k[l])&&null!=u.__e)return u.__e;return\"function\"==typeof n.type?$(n):null}function I(n){if(n.__P&&n.__d){var u=n.__v,t=u.__e,i=[],r=[],o=m({},u);o.__v=u.__v+1,l.vnode&&l.vnode(o),q(n.__P,o,u,n.__n,n.__P.namespaceURI,32&u.__u?[t]:null,i,null==t?$(u):t,!!(32&u.__u),r),o.__v=u.__v,o.__.__k[o.__i]=o,D(i,o,r),u.__e=u.__=null,o.__e!=t&&P(o)}}function P(n){if(null!=(n=n.__)&&null!=n.__c)return n.__e=n.__c.base=null,n.__k.some(function(l){if(null!=l&&null!=l.__e)return n.__e=n.__c.base=l.__e}),P(n)}function A(n){(!n.__d&&(n.__d=!0)&&i.push(n)&&!H.__r++||r!=l.debounceRendering)&&((r=l.debounceRendering)||o)(H)}function H(){try{for(var n,l=1;i.length;)i.length>l&&i.sort(e),n=i.shift(),l=i.length,I(n)}finally{i.length=H.__r=0}}function L(n,l,u,t,i,r,o,e,f,c,a){var s,h,p,v,y,_,g,m=t&&t.__k||w,b=l.length;for(f=T(u,l,m,f,b),s=0;s<b;s++)null!=(p=u.__k[s])&&(h=-1!=p.__i&&m[p.__i]||d,p.__i=s,_=q(n,p,h,i,r,o,e,f,c,a),v=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&J(h.ref,null,p),a.push(p.ref,p.__c||v,p)),null==y&&null!=v&&(y=v),(g=!!(4&p.__u))||h.__k===p.__k?(f=j(p,f,n,g),g&&h.__e&&(h.__e=null)):\"function\"==typeof p.type&&void 0!==_?f=_:v&&(f=v.nextSibling),p.__u&=-7);return u.__e=y,f}function T(n,l,u,t,i){var r,o,e,f,c,a=u.length,s=a,h=0;for(n.__k=new Array(i),r=0;r<i;r++)null!=(o=l[r])&&\"boolean\"!=typeof o&&\"function\"!=typeof o?(\"string\"==typeof o||\"number\"==typeof o||\"bigint\"==typeof o||o.constructor==String?o=n.__k[r]=x(null,o,null,null,null):g(o)?o=n.__k[r]=x(S,{children:o},null,null,null):void 0===o.constructor&&o.__b>0?o=n.__k[r]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):n.__k[r]=o,f=r+h,o.__=n,o.__b=n.__b+1,e=null,-1!=(c=o.__i=O(o,u,f,s))&&(s--,(e=u[c])&&(e.__u|=2)),null==e||null==e.__v?(-1==c&&(i>a?h--:i<a&&h++),\"function\"!=typeof o.type&&(o.__u|=4)):c!=f&&(c==f-1?h--:c==f+1?h++:(c>f?h--:h++,o.__u|=4))):n.__k[r]=null;if(s)for(r=0;r<a;r++)null!=(e=u[r])&&0==(2&e.__u)&&(e.__e==t&&(t=$(e)),K(e,e));return t}function j(n,l,u,t){var i,r;if(\"function\"==typeof n.type){for(i=n.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=n,l=j(i[r],l,u,t));return l}n.__e!=l&&(t&&(l&&n.type&&!l.parentNode&&(l=$(n)),u.insertBefore(n.__e,l||null)),l=n.__e);do{l=l&&l.nextSibling}while(null!=l&&8==l.nodeType);return l}function F(n,l){return l=l||[],null==n||\"boolean\"==typeof n||(g(n)?n.some(function(n){F(n,l)}):l.push(n)),l}function O(n,l,u,t){var i,r,o,e=n.key,f=n.type,c=l[u],a=null!=c&&0==(2&c.__u);if(null===c&&null==e||a&&e==c.key&&f==c.type)return u;if(t>(a?1:0))for(i=u-1,r=u+1;i>=0||r<l.length;)if(null!=(c=l[o=i>=0?i--:r++])&&0==(2&c.__u)&&e==c.key&&f==c.type)return o;return-1}function z(n,l,u){\"-\"==l[0]?n.setProperty(l,null==u?\"\":u):n[l]=null==u?\"\":\"number\"!=typeof u||_.test(l)?u:u+\"px\"}function N(n,l,u,t,i){var r,o;n:if(\"style\"==l)if(\"string\"==typeof u)n.style.cssText=u;else{if(\"string\"==typeof t&&(n.style.cssText=t=\"\"),t)for(l in t)u&&l in u||z(n.style,l,\"\");if(u)for(l in u)t&&u[l]==t[l]||z(n.style,l,u[l])}else if(\"o\"==l[0]&&\"n\"==l[1])r=l!=(l=l.replace(s,\"$1\")),o=l.toLowerCase(),l=o in n||\"onFocusOut\"==l||\"onFocusIn\"==l?o.slice(2):l.slice(2),n.l||(n.l={}),n.l[l+r]=u,u?t?u[a]=t[a]:(u[a]=h,n.addEventListener(l,r?v:p,r)):n.removeEventListener(l,r?v:p,r);else{if(\"http://www.w3.org/2000/svg\"==i)l=l.replace(/xlink(H|:h)/,\"h\").replace(/sName$/,\"s\");else if(\"width\"!=l&&\"height\"!=l&&\"href\"!=l&&\"list\"!=l&&\"form\"!=l&&\"tabIndex\"!=l&&\"download\"!=l&&\"rowSpan\"!=l&&\"colSpan\"!=l&&\"role\"!=l&&\"popover\"!=l&&l in n)try{n[l]=null==u?\"\":u;break n}catch(n){}\"function\"==typeof u||(null==u||!1===u&&\"-\"!=l[4]?n.removeAttribute(l):n.setAttribute(l,\"popover\"==l&&1==u?\"\":u))}}function V(n){return function(u){if(this.l){var t=this.l[u.type+n];if(null==u[c])u[c]=h++;else if(u[c]<t[a])return;return t(l.event?l.event(u):u)}}}function q(n,u,t,i,r,o,e,f,c,a){var s,h,p,v,y,d,_,k,x,M,$,I,P,A,H,T,j=u.type;if(void 0!==u.constructor)return null;128&t.__u&&(c=!!(32&t.__u),o=[f=u.__e=t.__e]),(s=l.__b)&&s(u);n:if(\"function\"==typeof j){h=e.length;try{if(x=u.props,M=j.prototype&&j.prototype.render,$=(s=j.contextType)&&i[s.__c],I=s?$?$.props.value:s.__:i,t.__c?k=(p=u.__c=t.__c).__=p.__E:(M?u.__c=p=new j(x,I):(u.__c=p=new C(x,I),p.constructor=j,p.render=Q),$&&$.sub(p),p.state||(p.state={}),p.__n=i,v=p.__d=!0,p.__h=[],p._sb=[]),M&&null==p.__s&&(p.__s=p.state),M&&null!=j.getDerivedStateFromProps&&(p.__s==p.state&&(p.__s=m({},p.__s)),m(p.__s,j.getDerivedStateFromProps(x,p.__s))),y=p.props,d=p.state,p.__v=u,v)M&&null==j.getDerivedStateFromProps&&null!=p.componentWillMount&&p.componentWillMount(),M&&null!=p.componentDidMount&&p.__h.push(p.componentDidMount);else{if(M&&null==j.getDerivedStateFromProps&&x!==y&&null!=p.componentWillReceiveProps&&p.componentWillReceiveProps(x,I),u.__v==t.__v||!p.__e&&null!=p.shouldComponentUpdate&&!1===p.shouldComponentUpdate(x,p.__s,I)){u.__v!=t.__v&&(p.props=x,p.state=p.__s,p.__d=!1),u.__e=t.__e,u.__k=t.__k,u.__k.some(function(n){n&&(n.__=u)}),w.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&e.push(p);break n}null!=p.componentWillUpdate&&p.componentWillUpdate(x,p.__s,I),M&&null!=p.componentDidUpdate&&p.__h.push(function(){p.componentDidUpdate(y,d,_)})}if(p.context=I,p.props=x,p.__P=n,p.__e=!1,P=l.__r,A=0,M)p.state=p.__s,p.__d=!1,P&&P(u),s=p.render(p.props,p.state,p.context),w.push.apply(p.__h,p._sb),p._sb=[];else do{p.__d=!1,P&&P(u),s=p.render(p.props,p.state,p.context),p.state=p.__s}while(p.__d&&++A<25);p.state=p.__s,null!=p.getChildContext&&(i=m(m({},i),p.getChildContext())),M&&!v&&null!=p.getSnapshotBeforeUpdate&&(_=p.getSnapshotBeforeUpdate(y,d)),H=null!=s&&s.type===S&&null==s.key?E(s.props.children):s,f=L(n,g(H)?H:[H],u,t,i,r,o,e,f,c,a),p.base=u.__e,u.__u&=-161,p.__h.length&&e.push(p),k&&(p.__E=p.__=null)}catch(n){if(e.length=h,u.__v=null,c||null!=o)if(n.then){for(u.__u|=c?160:128;f&&8==f.nodeType&&f.nextSibling;)f=f.nextSibling;null!=o&&(o[o.indexOf(f)]=null),u.__e=f}else{if(null!=o)for(T=o.length;T--;)b(o[T]);B(u)}else u.__e=t.__e,!u.__k&&t.__k&&(u.__k=t.__k),n.then||B(u);l.__e(n,u,t)}}else null==o&&u.__v==t.__v?(u.__k=t.__k,u.__e=t.__e):f=u.__e=G(t.__e,u,t,i,r,o,e,c,a);return(s=l.diffed)&&s(u),128&u.__u?void 0:f}function B(n){n&&(n.__c&&(n.__c.__e=!0),n.__k&&n.__k.some(B))}function D(n,u,t){for(var i=0;i<t.length;i++)J(t[i],t[++i],t[++i]);l.__c&&l.__c(u,n),n.some(function(u){try{n=u.__h,u.__h=[],n.some(function(n){n.call(u)})}catch(n){l.__e(n,u.__v)}})}function E(n){return\"object\"!=typeof n||null==n||n.__b>0?n:g(n)?n.map(E):void 0!==n.constructor?null:m({},n)}function G(u,t,i,r,o,e,f,c,a){var s,h,p,v,y,w,_,m=i.props||d,k=t.props,x=t.type;if(\"svg\"==x?o=\"http://www.w3.org/2000/svg\":\"math\"==x?o=\"http://www.w3.org/1998/Math/MathML\":o||(o=\"http://www.w3.org/1999/xhtml\"),null!=e)for(s=0;s<e.length;s++)if((y=e[s])&&\"setAttribute\"in y==!!x&&(x?y.localName==x:3==y.nodeType)){u=y,e[s]=null;break}if(null==u){if(null==x)return document.createTextNode(k);u=document.createElementNS(o,x,k.is&&k),c&&(l.__m&&l.__m(t,e),c=!1),e=null}if(null==x)m===k||c&&u.data==k||(u.data=k);else{if(e=\"textarea\"==x&&null!=k.defaultValue?null:e&&n.call(u.childNodes),!c&&null!=e)for(m={},s=0;s<u.attributes.length;s++)m[(y=u.attributes[s]).name]=y.value;for(s in m)y=m[s],\"dangerouslySetInnerHTML\"==s?p=y:\"children\"==s||s in k||\"value\"==s&&\"defaultValue\"in k||\"checked\"==s&&\"defaultChecked\"in k||N(u,s,null,y,o);for(s in k)y=k[s],\"children\"==s?v=y:\"dangerouslySetInnerHTML\"==s?h=y:\"value\"==s?w=y:\"checked\"==s?_=y:c&&\"function\"!=typeof y||m[s]===y||N(u,s,y,m[s],o);if(h)c||p&&(h.__html==p.__html||h.__html==u.innerHTML)||(u.innerHTML=h.__html),t.__k=[];else if(p&&(u.innerHTML=\"\"),L(\"template\"==t.type?u.content:u,g(v)?v:[v],t,i,r,\"foreignObject\"==x?\"http://www.w3.org/1999/xhtml\":o,e,f,e?e[0]:i.__k&&$(i,0),c,a),null!=e)for(s=e.length;s--;)b(e[s]);c&&\"textarea\"!=x||(s=\"value\",\"progress\"==x&&null==w?u.removeAttribute(\"value\"):null!=w&&(w!==u[s]||\"progress\"==x&&!w||\"option\"==x&&w!=m[s])&&N(u,s,w,m[s],o),s=\"checked\",null!=_&&_!=u[s]&&N(u,s,_,m[s],o))}return u}function J(n,u,t){try{if(\"function\"==typeof n){var i=\"function\"==typeof n.__u;i&&n.__u(),i&&null==u||(n.__u=n(u))}else n.current=u}catch(n){l.__e(n,t)}}function K(n,u,t){var i,r;if(l.unmount&&l.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||J(i,null,u)),null!=(i=n.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(n){l.__e(n,u)}i.base=i.__P=i.__n=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&K(i[r],u,t||\"function\"!=typeof n.type);t||b(n.__e),n.__c=n.__=n.__e=void 0}function Q(n,l,u){return this.constructor(n,u)}function R(u,t,i){var r,o,e,f;t==document&&(t=document.documentElement),l.__&&l.__(u,t),o=(r=\"function\"==typeof i)?null:i&&i.__k||t.__k,e=[],f=[],q(t,u=(!r&&i||t).__k=k(S,null,[u]),o||d,d,t.namespaceURI,!r&&i?[i]:o?null:t.firstChild?n.call(t.childNodes):null,e,!r&&i?i:o?o.__e:t.firstChild,r,f),D(e,u,f),u.props.children=null}function U(n,l){R(n,l,U)}function W(l,u,t){var i,r,o,e,f=m({},l.props);for(o in l.type&&l.type.defaultProps&&(e=l.type.defaultProps),u)\"key\"==o?i=u[o]:\"ref\"==o?r=u[o]:f[o]=void 0===u[o]&&null!=e?e[o]:u[o];return arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):t),x(l.type,f,i||l.key,r||l.ref,null)}function X(n){function l(n){var u,t;return this.getChildContext||(u=new Set,(t={})[l.__c]=this,this.getChildContext=function(){return t},this.componentWillUnmount=function(){u=null},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&u.forEach(function(n){n.__e=!0,A(n)})},this.sub=function(n){u.add(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u&&u.delete(n),l&&l.call(n)}}),n.children}return l.__c=\"__cC\"+y++,l.__=n,l.Provider=l.__l=(l.Consumer=function(n,l){return n.children(l)}).contextType=l,l}n=w.slice,l={__e:function(n,l,u,t){for(var i,r,o;l=l.__;)if((i=l.__c)&&!i.__)try{if((r=i.constructor)&&null!=r.getDerivedStateFromError&&(i.setState(r.getDerivedStateFromError(n)),o=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(n,t||{}),o=i.__d),o)return i.__E=i}catch(l){n=l}throw n}},u=0,t=function(n){return null!=n&&void 0===n.constructor},C.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=m({},this.state),\"function\"==typeof n&&(n=n(m({},u),this.props)),n&&m(u,n),null!=n&&this.__v&&(l&&this._sb.push(l),A(this))},C.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),A(this))},C.prototype.render=S,i=[],o=\"function\"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,e=function(n,l){return n.__v.__b-l.__v.__b},H.__r=0,f=Math.random().toString(8),c=\"__d\"+f,a=\"__a\"+f,s=/(PointerCapture)$|Capture$/i,h=0,p=V(!1),v=V(!0),y=0;export{C as Component,S as Fragment,W as cloneElement,X as createContext,k as createElement,M as createRef,k as h,U as hydrate,t as isValidElement,l as options,R as render,F as toChildArray};\n//# sourceMappingURL=preact.module.js.map\n","const win = 'undefined' != typeof window ? window : void 0;\nconst global = 'undefined' != typeof globalThis ? globalThis : win;\nconst globals_navigator = global?.navigator;\nconst globals_document = global?.document;\nconst globals_location = global?.location;\nconst fetch = global?.fetch;\nconst XMLHttpRequest = global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : void 0;\nconst AbortController = global?.AbortController;\nconst CompressionStream = global?.CompressionStream;\nconst userAgent = globals_navigator?.userAgent;\nfunction isBrowserOnline() {\n return !!(win && false !== win.navigator.onLine);\n}\nexport { AbortController, CompressionStream, XMLHttpRequest, globals_document as document, fetch, isBrowserOnline, globals_location as location, globals_navigator as navigator, userAgent, win as window };\n","/*! @license DOMPurify 3.3.2 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.2/LICENSE */\n\nconst {\n entries,\n setPrototypeOf,\n isFrozen,\n getPrototypeOf,\n getOwnPropertyDescriptor\n} = Object;\nlet {\n freeze,\n seal,\n create\n} = Object; // eslint-disable-line import/no-mutable-exports\nlet {\n apply,\n construct\n} = typeof Reflect !== 'undefined' && Reflect;\nif (!freeze) {\n freeze = function freeze(x) {\n return x;\n };\n}\nif (!seal) {\n seal = function seal(x) {\n return x;\n };\n}\nif (!apply) {\n apply = function apply(func, thisArg) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n return func.apply(thisArg, args);\n };\n}\nif (!construct) {\n construct = function construct(Func) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n return new Func(...args);\n };\n}\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySplice = unapply(Array.prototype.splice);\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst regExpTest = unapply(RegExp.prototype.test);\nconst typeErrorCreate = unconstruct(TypeError);\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply(func) {\n return function (thisArg) {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n args[_key3 - 1] = arguments[_key3];\n }\n return apply(func, thisArg, args);\n };\n}\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct(Func) {\n return function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n return construct(Func, args);\n };\n}\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(set, array) {\n let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n array[l] = lcElement;\n }\n element = lcElement;\n }\n }\n set[element] = true;\n }\n return set;\n}\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray(array) {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n return array;\n}\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone(object) {\n const newObject = create(null);\n for (const [property, value] of entries(object)) {\n const isPropertyExist = objectHasOwnProperty(object, property);\n if (isPropertyExist) {\n if (Array.isArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (value && typeof value === 'object' && value.constructor === Object) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n return newObject;\n}\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter(object, prop) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n object = getPrototypeOf(object);\n }\n function fallbackValue() {\n return null;\n }\n return fallbackValue;\n}\n\nconst html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);\nconst svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);\nconst svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nconst svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);\nconst mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nconst mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);\nconst text = freeze(['#text']);\n\nconst html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);\nconst svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);\nconst mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);\nconst xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);\n\n// eslint-disable-next-line unicorn/better-regex\nconst MUSTACHE_EXPR = seal(/\\{\\{[\\w\\W]*|[\\w\\W]*\\}\\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode\nconst ERB_EXPR = seal(/<%[\\w\\W]*|[\\w\\W]*%>/gm);\nconst TMPLIT_EXPR = seal(/\\$\\{[\\w\\W]*/gm); // eslint-disable-line unicorn/better-regex\nconst DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nconst ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nconst IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nconst IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nconst ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nconst DOCTYPE_NAME = seal(/^html$/i);\nconst CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n\nvar EXPRESSIONS = /*#__PURE__*/Object.freeze({\n __proto__: null,\n ARIA_ATTR: ARIA_ATTR,\n ATTR_WHITESPACE: ATTR_WHITESPACE,\n CUSTOM_ELEMENT: CUSTOM_ELEMENT,\n DATA_ATTR: DATA_ATTR,\n DOCTYPE_NAME: DOCTYPE_NAME,\n ERB_EXPR: ERB_EXPR,\n IS_ALLOWED_URI: IS_ALLOWED_URI,\n IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,\n MUSTACHE_EXPR: MUSTACHE_EXPR,\n TMPLIT_EXPR: TMPLIT_EXPR\n});\n\n/* eslint-disable @typescript-eslint/indent */\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5,\n // Deprecated\n entityNode: 6,\n // Deprecated\n progressingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12 // Deprecated\n};\nconst getGlobal = function getGlobal() {\n return typeof window === 'undefined' ? null : window;\n};\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {\n if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {\n return null;\n }\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n }\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn('TrustedTypes policy ' + policyName + ' could not be created.');\n return null;\n }\n};\nconst _createHooksMap = function _createHooksMap() {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: []\n };\n};\nfunction createDOMPurify() {\n let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();\n const DOMPurify = root => createDOMPurify(root);\n DOMPurify.version = '3.3.2';\n DOMPurify.removed = [];\n if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n return DOMPurify;\n }\n let {\n document\n } = window;\n const originalDocument = document;\n const currentScript = originalDocument.currentScript;\n const {\n DocumentFragment,\n HTMLTemplateElement,\n Node,\n Element,\n NodeFilter,\n NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,\n HTMLFormElement,\n DOMParser,\n trustedTypes\n } = window;\n const ElementPrototype = Element.prototype;\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n let trustedTypesPolicy;\n let emptyHTML = '';\n const {\n implementation,\n createNodeIterator,\n createDocumentFragment,\n getElementsByTagName\n } = document;\n const {\n importNode\n } = originalDocument;\n let hooks = _createHooksMap();\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;\n const {\n MUSTACHE_EXPR,\n ERB_EXPR,\n TMPLIT_EXPR,\n DATA_ATTR,\n ARIA_ATTR,\n IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE,\n CUSTOM_ELEMENT\n } = EXPRESSIONS;\n let {\n IS_ALLOWED_URI: IS_ALLOWED_URI$1\n } = EXPRESSIONS;\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false\n }\n }));\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {\n tagCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n }\n }));\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n /* Decide if document with <html>... should be returned */\n let WHOLE_DOCUMENT = false;\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES = {};\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);\n let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc = null;\n /* Keep a reference to config to pass to hooks */\n let CONFIG = null;\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n const formElement = document.createElement('form');\n const isRegexOrFunction = function isRegexOrFunction(testValue) {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function _parseConfig() {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;\n /* Set configuration parameters */\n ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;\n ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;\n ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;\n URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;\n DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;\n FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;\n FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});\n FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;\n NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;\n MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;\n HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;\n CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};\n if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;\n }\n if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;\n }\n if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;\n }\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, text);\n ALLOWED_ATTR = create(null);\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, html$1);\n addToSet(ALLOWED_ATTR, html);\n }\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, svg$1);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, svgFilters);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, mathMl$1);\n addToSet(ALLOWED_ATTR, mathMl);\n addToSet(ALLOWED_ATTR, xml);\n }\n }\n /* Prevent function-based ADD_ATTR / ADD_TAGS from leaking across calls */\n if (!objectHasOwnProperty(cfg, 'ADD_TAGS')) {\n EXTRA_ELEMENT_HANDLING.tagCheck = null;\n }\n if (!objectHasOwnProperty(cfg, 'ADD_ATTR')) {\n EXTRA_ELEMENT_HANDLING.attributeCheck = null;\n }\n /* Merge configuration parameters */\n if (cfg.ADD_TAGS) {\n if (typeof cfg.ADD_TAGS === 'function') {\n EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n } else {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n }\n if (cfg.ADD_ATTR) {\n if (typeof cfg.ADD_ATTR === 'function') {\n EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n } else {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n }\n if (cfg.ADD_URI_SAFE_ATTR) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n if (cfg.FORBID_CONTENTS) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n if (cfg.ADD_FORBID_CONTENTS) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);\n }\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.');\n }\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.');\n }\n // Overwrite existing TrustedTypes policy.\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n // Sign local variables required by `sanitize`.\n emptyHTML = trustedTypesPolicy.createHTML('');\n } else {\n // Uninitialized policy, attempt to initialize the internal dompurify policy.\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);\n }\n // If creating the internal policy succeeded sign internal variables.\n if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {\n emptyHTML = trustedTypesPolicy.createHTML('');\n }\n }\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n CONFIG = cfg;\n };\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);\n const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function _checkValidNamespace(element) {\n let parent = getParentNode(element);\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template'\n };\n }\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n if (element.namespaceURI === SVG_NAMESPACE) {\n // The only way to switch from HTML namespace to SVG\n // is via <svg>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n // The only way to switch from MathML to SVG is via`\n // svg if parent is either <annotation-xml> or MathML\n // text integration points.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);\n }\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n }\n if (element.namespaceURI === MATHML_NAMESPACE) {\n // The only way to switch from HTML namespace to MathML\n // is via <math>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n // The only way to switch from SVG to MathML is via\n // <math> and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n }\n if (element.namespaceURI === HTML_NAMESPACE) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);\n }\n // For XHTML and XML documents that support custom namespaces\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {\n return true;\n }\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function _forceRemove(node) {\n arrayPush(DOMPurify.removed, {\n element: node\n });\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n remove(node);\n }\n };\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function _removeAttribute(name, element) {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element\n });\n }\n element.removeAttribute(name);\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function _initDocument(dirty) {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n if (FORCE_BODY) {\n dirty = '<remove></remove>' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty = '<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>' + dirty + '</body></html>';\n }\n const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n const body = doc.body || doc.documentElement;\n if (dirty && leadingWhitespace) {\n body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);\n }\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];\n }\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function _createNodeIterator(root) {\n return createNodeIterator.call(root.ownerDocument || root, root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);\n };\n /**\n * _isClobbered\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function _isClobbered(element) {\n return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');\n };\n /**\n * Checks whether the given object is a DOM node.\n *\n * @param value object to check whether it's a DOM node\n * @return true is object is a DOM node\n */\n const _isNode = function _isNode(value) {\n return typeof Node === 'function' && value instanceof Node;\n };\n function _executeHooks(hooks, currentNode, data) {\n arrayForEach(hooks, hook => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n const _sanitizeElements = function _sanitizeElements(currentNode) {\n let content = null;\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(currentNode.nodeName);\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS\n });\n /* Detect mXSS attempts abusing namespace confusion */\n if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\\w!]/g, currentNode.textContent)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove any kind of possibly harmful comments */\n if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\\w]/g, currentNode.data)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove element if anything forbids its presence */\n if (!(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {\n return false;\n }\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {\n return false;\n }\n }\n /* Keep content except for bad-listed elements */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode) || currentNode.parentNode;\n const childNodes = getChildNodes(currentNode) || currentNode.childNodes;\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n for (let i = childCount - 1; i >= 0; --i) {\n const childClone = cloneNode(childNodes[i], true);\n childClone.__removalCount = (currentNode.__removalCount || 0) + 1;\n parentNode.insertBefore(childClone, getNextSibling(currentNode));\n }\n }\n }\n _forceRemove(currentNode);\n return true;\n }\n /* Check whether element has a valid namespace */\n if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\\/no(script|embed|frames)/i, currentNode.innerHTML)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n content = currentNode.textContent;\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {\n content = stringReplace(content, expr, ' ');\n });\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, {\n element: currentNode.cloneNode()\n });\n currentNode.textContent = content;\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n return false;\n };\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {\n /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */\n if (FORBID_ATTR[lcName]) {\n return false;\n }\n /* Make sure attribute cannot clobber */\n if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {\n return false;\n }\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {\n return false;\n } else ;\n return true;\n };\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function _isBasicCustomElement(tagName) {\n return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);\n };\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n const {\n attributes\n } = currentNode;\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined\n };\n let l = attributes.length;\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const {\n name,\n namespaceURI,\n value: attrValue\n } = attr;\n const lcName = transformCaseFunc(name);\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n /* Work around a security issue with comments inside attributes */\n if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Make sure we cannot easily use animated hrefs, even if animations are allowed */\n if (lcName === 'attributename' && stringMatch(value, 'href')) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Did the hooks approve of the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\\/>/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {\n value = stringReplace(value, expr, ' ');\n });\n }\n /* Is `value` valid for this attribute? */\n const lcTag = transformCaseFunc(currentNode.nodeName);\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Handle attributes that require Trusted Types */\n if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {\n if (namespaceURI) ; else {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML':\n {\n value = trustedTypesPolicy.createHTML(value);\n break;\n }\n case 'TrustedScriptURL':\n {\n value = trustedTypesPolicy.createScriptURL(value);\n break;\n }\n }\n }\n }\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {\n _removeAttribute(name, currentNode);\n }\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n while (shadowNode = shadowIterator.nextNode()) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode);\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n /* Deep shadow DOM detected */\n if (shadowNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(shadowNode.content);\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty) {\n let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '<!-->';\n }\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n if (typeof dirty.toString === 'function') {\n dirty = dirty.toString();\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n } else {\n throw typeErrorCreate('toString is not a function');\n }\n }\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n /* Assign config vars */\n if (!SET_CONFIG) {\n _parseConfig(cfg);\n }\n /* Clean up removed elements */\n DOMPurify.removed = [];\n /* Check if dirty is correctly typed for IN_PLACE */\n if (typeof dirty === 'string') {\n IN_PLACE = false;\n }\n if (IN_PLACE) {\n /* Do some early pre-sanitization to avoid unsafe root nodes */\n if (dirty.nodeName) {\n const tagName = transformCaseFunc(dirty.nodeName);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');\n }\n }\n } else if (dirty instanceof Node) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('<!---->');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n } else {\n /* Exit directly if we have nothing to do */\n if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;\n }\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n /* Get node iterator */\n const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);\n /* Now start iterating over the created document */\n while (currentNode = nodeIterator.nextNode()) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode);\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n /* Shadow DOM detected, sanitize it */\n if (currentNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(currentNode.content);\n }\n }\n /* If we sanitized `dirty` in-place, return it. */\n if (IN_PLACE) {\n return dirty;\n }\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n return returnNode;\n }\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n /* Serialize doctype if allowed */\n if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {\n serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\\n' + serializedHTML;\n }\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {\n serializedHTML = stringReplace(serializedHTML, expr, ' ');\n });\n }\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;\n };\n DOMPurify.setConfig = function () {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n _parseConfig(cfg);\n SET_CONFIG = true;\n };\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n };\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n DOMPurify.addHook = function (entryPoint, hookFunction) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n arrayPush(hooks[entryPoint], hookFunction);\n };\n DOMPurify.removeHook = function (entryPoint, hookFunction) {\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n return arrayPop(hooks[entryPoint]);\n };\n DOMPurify.removeHooks = function (entryPoint) {\n hooks[entryPoint] = [];\n };\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n return DOMPurify;\n}\nvar purify = createDOMPurify();\n\nexport { purify as default };\n//# sourceMappingURL=purify.es.mjs.map\n","function createConsole(consoleLike = console) {\n const lockedMethods = {\n log: consoleLike.log.bind(consoleLike),\n warn: consoleLike.warn.bind(consoleLike),\n error: consoleLike.error.bind(consoleLike),\n debug: consoleLike.debug.bind(consoleLike)\n };\n return lockedMethods;\n}\nconst _createLogger = (prefix, maybeCall, consoleLike)=>{\n function _log(level, ...args) {\n maybeCall(()=>{\n const consoleMethod = consoleLike[level];\n consoleMethod(prefix, ...args);\n });\n }\n const logger = {\n debug: (...args)=>{\n _log('debug', ...args);\n },\n info: (...args)=>{\n _log('log', ...args);\n },\n warn: (...args)=>{\n _log('warn', ...args);\n },\n error: (...args)=>{\n _log('error', ...args);\n },\n critical: (...args)=>{\n consoleLike['error'](prefix, ...args);\n },\n createLogger: (additionalPrefix)=>_createLogger(`${prefix} ${additionalPrefix}`, maybeCall, consoleLike)\n };\n return logger;\n};\nconst passThrough = (fn)=>fn();\nfunction createLogger(prefix, maybeCall = passThrough) {\n return _createLogger(prefix, maybeCall, createConsole());\n}\nexport { _createLogger, createLogger };\n","import { PropertyMatchType } from './types'\nimport { SurveyActionType, SurveyEventWithFilters } from './posthog-surveys-types'\nimport type { InferredSelector } from './extensions/product-tours/element-inference'\nimport { SurveyPosition } from '@posthog/core'\nimport { Z_INDEX_TOURS } from './constants'\n\nexport interface JSONContent {\n type?: string\n attrs?: Record<string, any>\n content?: JSONContent[]\n marks?: { type: string; attrs?: Record<string, any> }[]\n text?: string\n}\n\nexport type ProductTourStepType = 'element' | 'modal' | 'survey' | 'banner'\n\nexport interface ProductTourBannerConfig {\n behavior: 'sticky' | 'static' | 'custom'\n selector?: string\n action?: {\n type: 'none' | 'link' | 'trigger_tour'\n link?: string\n tourId?: string\n }\n animation?: {\n duration?: number\n }\n}\n\n/** Button actions available on modal steps */\nexport type ProductTourButtonAction = 'dismiss' | 'link' | 'next_step' | 'previous_step' | 'trigger_tour'\n\nexport interface ProductTourStepButton {\n text: string\n action: ProductTourButtonAction\n /** URL to open when action is 'link' */\n link?: string\n /** Tour ID to trigger when action is 'trigger_tour' */\n tourId?: string\n}\n\nexport interface ProductTourStepButtons {\n primary?: ProductTourStepButton\n secondary?: ProductTourStepButton\n}\n\nexport type ProductTourSurveyQuestionType = 'open' | 'rating'\n\nexport interface ProductTourSurveyQuestion {\n type: ProductTourSurveyQuestionType\n questionText: string\n /** Rating display type - emoji or number */\n display?: 'emoji' | 'number'\n /** Rating scale - 3 or 5 for emoji, 5 or 10 for number */\n scale?: 3 | 5 | 10\n /** Label for low end of rating scale (e.g., \"Not likely\") */\n lowerBoundLabel?: string\n /** Label for high end of rating scale (e.g., \"Very likely\") */\n upperBoundLabel?: string\n submitButtonText?: string\n backButtonText?: string\n}\n\nexport interface ProductTourStep {\n id: string\n type: ProductTourStepType\n selector?: string\n progressionTrigger: 'button' | 'click'\n content: JSONContent | null\n /** Pre-rendered HTML content from the editor. If present, SDK should use this instead of rendering from JSONContent. */\n contentHtml?: string\n /** Inline survey question config - if present, this is a survey step */\n survey?: ProductTourSurveyQuestion\n /** ID of the auto-created survey for this step (set by backend) */\n linkedSurveyId?: string\n /** ID of the survey question (set by backend, used for event tracking) */\n linkedSurveyQuestionId?: string\n /** Enhanced element data for more reliable lookup at runtime */\n inferenceData?: InferredSelector\n /** Use CSS selector instead of inference. Defaults to false (use inference). */\n useManualSelector?: boolean\n /** Maximum tooltip width in pixels (defaults to 320px) */\n maxWidth?: number\n /** Position for modal/survey steps (defaults to middle_center) */\n modalPosition?: SurveyPosition\n /** Button configuration for modal steps */\n buttons?: ProductTourStepButtons\n /** Banner configuration (only for banner steps) */\n bannerConfig?: ProductTourBannerConfig\n /** translation data for this tour step */\n translations?: Record<string, ProductTourStepTranslation>\n}\n\n/** all translatable content for a given tour step */\nexport interface ProductTourStepTranslation {\n content?: ProductTourStep['content']\n contentHtml?: ProductTourStep['contentHtml']\n buttons?: {\n primary?: Pick<ProductTourStepButton, 'text'>\n secondary?: Pick<ProductTourStepButton, 'text'>\n }\n survey?: Pick<\n ProductTourSurveyQuestion,\n 'questionText' | 'lowerBoundLabel' | 'upperBoundLabel' | 'submitButtonText' | 'backButtonText'\n >\n}\n\n/** maps to main repo EffectiveProductTourType */\nexport type ProductTourType = 'tour' | 'announcement' | 'banner'\n\nexport interface ProductTourWaitPeriod {\n days: number\n types: ProductTourType[]\n}\n\nexport interface ProductTourConditions {\n url?: string\n urlMatchType?: PropertyMatchType\n selector?: string\n autoShowDelaySeconds?: number\n events?: {\n values: SurveyEventWithFilters[]\n } | null\n cancelEvents?: {\n values: SurveyEventWithFilters[]\n } | null\n actions?: {\n values: SurveyActionType[]\n } | null\n linkedFlagVariant?: string\n deviceTypes?: string[]\n seenTourWaitPeriod?: ProductTourWaitPeriod\n}\n\nexport interface ProductTourAppearance {\n backgroundColor?: string\n textColor?: string\n buttonColor?: string\n borderRadius?: number\n buttonBorderRadius?: number\n borderColor?: string\n fontFamily?: string\n boxShadow?: string\n showOverlay?: boolean\n whiteLabel?: boolean\n /** defaults to true, auto-set to false for announcements/banners */\n dismissOnClickOutside?: boolean\n zIndex?: number\n}\n\nexport type ProductTourDisplayFrequency = 'show_once' | 'until_interacted' | 'always'\n\nexport interface ProductTour {\n id: string\n name: string\n description?: string\n tour_type: ProductTourType // inferred in API based on tour content\n auto_launch?: boolean\n start_date: string | null\n end_date: string | null\n current_iteration?: number\n conditions?: ProductTourConditions\n appearance?: ProductTourAppearance\n steps: ProductTourStep[]\n internal_targeting_flag_key?: string\n linked_flag_key?: string\n display_frequency?: ProductTourDisplayFrequency\n disable_image_preload?: boolean\n}\n\nexport type ProductTourCallback = (tours: ProductTour[], context?: { isLoaded: boolean; error?: string }) => void\n\nexport type ProductTourSelectorError = 'not_found' | 'multiple_matches' | 'not_visible'\n\nexport type ProductTourDismissReason =\n | 'user_clicked_skip'\n | 'user_clicked_outside'\n | 'escape_key'\n | 'element_unavailable'\n | 'container_unavailable'\n\nexport type ProductTourRenderReason = 'auto' | 'api' | 'trigger' | 'event'\n\nexport const DEFAULT_PRODUCT_TOUR_APPEARANCE: Required<ProductTourAppearance> = {\n backgroundColor: '#ffffff',\n textColor: '#1d1f27',\n buttonColor: '#1d1f27',\n borderRadius: 8,\n buttonBorderRadius: 6,\n borderColor: '#e5e7eb',\n fontFamily: 'system-ui',\n boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',\n showOverlay: true,\n whiteLabel: false,\n dismissOnClickOutside: true,\n zIndex: Z_INDEX_TOURS,\n}\n\nexport interface ShowTourOptions {\n reason?: ProductTourRenderReason\n enableStrictValidation?: boolean\n}\n\nexport const ProductTourEventName = {\n SHOWN: 'product tour shown',\n DISMISSED: 'product tour dismissed',\n COMPLETED: 'product tour completed',\n STEP_SHOWN: 'product tour step shown',\n STEP_COMPLETED: 'product tour step completed',\n BUTTON_CLICKED: 'product tour button clicked',\n STEP_SELECTOR_FAILED: 'product tour step selector failed',\n BANNER_CONTAINER_SELECTOR_FAILED: 'product tour banner container selector failed',\n BANNER_ACTION_CLICKED: 'product tour banner action clicked',\n} as const\nexport type ProductTourEventName = (typeof ProductTourEventName)[keyof typeof ProductTourEventName]\n\nexport const ProductTourEventProperties = {\n TOUR_ID: '$product_tour_id',\n TOUR_NAME: '$product_tour_name',\n TOUR_ITERATION: '$product_tour_iteration',\n TOUR_RENDER_REASON: '$product_tour_render_reason',\n TOUR_STEP_ID: '$product_tour_step_id',\n TOUR_STEP_ORDER: '$product_tour_step_order',\n TOUR_STEP_TYPE: '$product_tour_step_type',\n TOUR_DISMISS_REASON: '$product_tour_dismiss_reason',\n TOUR_BUTTON_TEXT: '$product_tour_button_text',\n TOUR_BUTTON_ACTION: '$product_tour_button_action',\n TOUR_BUTTON_LINK: '$product_tour_button_link',\n TOUR_BUTTON_TOUR_ID: '$product_tour_button_tour_id',\n TOUR_STEPS_COUNT: '$product_tour_steps_count',\n TOUR_STEP_SELECTOR: '$product_tour_step_selector',\n TOUR_STEP_SELECTOR_FOUND: '$product_tour_step_selector_found',\n TOUR_STEP_ELEMENT_TAG: '$product_tour_step_element_tag',\n TOUR_STEP_ELEMENT_ID: '$product_tour_step_element_id',\n TOUR_STEP_ELEMENT_CLASSES: '$product_tour_step_element_classes',\n TOUR_STEP_ELEMENT_TEXT: '$product_tour_step_element_text',\n TOUR_ERROR: '$product_tour_error',\n TOUR_MATCHES_COUNT: '$product_tour_matches_count',\n TOUR_FAILURE_PHASE: '$product_tour_failure_phase',\n TOUR_WAITED_FOR_ELEMENT: '$product_tour_waited_for_element',\n TOUR_WAIT_DURATION_MS: '$product_tour_wait_duration_ms',\n TOUR_BANNER_SELECTOR: '$product_tour_banner_selector',\n TOUR_LINKED_SURVEY_ID: '$product_tour_linked_survey_id',\n USE_MANUAL_SELECTOR: '$use_manual_selector',\n INFERENCE_DATA_PRESENT: '$inference_data_present',\n TOUR_LAST_SEEN_DATE: '$product_tour_last_seen_date',\n TOUR_TYPE: '$product_tour_type',\n} as const\nexport type ProductTourEventProperties = (typeof ProductTourEventProperties)[keyof typeof ProductTourEventProperties]\n","/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const DEVICE_ID = '$device_id'\nexport const DEVICE_MODEL = '$device_model'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side'\nexport const EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = '$exception_capture_enabled_server_side'\nexport const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules'\nexport const ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS = '$error_tracking_capture_extension_exceptions'\nexport const WEB_VITALS_ENABLED_SERVER_SIDE = '$web_vitals_enabled_server_side'\nexport const DEAD_CLICKS_ENABLED_SERVER_SIDE = '$dead_clicks_enabled_server_side'\nexport const PRODUCT_TOURS_ENABLED_SERVER_SIDE = '$product_tours_enabled_server_side'\nexport const WEB_VITALS_ALLOWED_METRICS = '$web_vitals_allowed_metrics'\nexport const SESSION_RECORDING_REMOTE_CONFIG = '$session_recording_remote_config'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MASKING = '$session_recording_masking'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_CANVAS_RECORDING = '$session_recording_canvas_recording'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SAMPLE_RATE = '$replay_sample_rate'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MINIMUM_DURATION = '$replay_minimum_duration'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SCRIPT_CONFIG = '$replay_script_config'\nexport const SESSION_RECORDING_OVERRIDE_SAMPLING = '$replay_override_sampling'\nexport const SESSION_RECORDING_OVERRIDE_LINKED_FLAG = '$replay_override_linked_flag'\nexport const SESSION_RECORDING_OVERRIDE_URL_TRIGGER = '$replay_override_url_trigger'\nexport const SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER = '$replay_override_event_trigger'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const SESSION_RECORDING_PAST_MINIMUM_DURATION = '$session_past_minimum_duration'\nexport const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session'\nexport const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session'\n// V2 Trigger Groups: Per-group persistence key prefixes (suffix with group ID)\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX = '$posthog_sr_group_event_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX = '$posthog_sr_group_url_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX = '$posthog_sr_group_sampling_'\nexport const SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP = '$debug_first_full_snapshot_timestamp'\nexport const SESSION_RECORDING_FLUSHED_SIZE = '$sess_rec_flush_size'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_ACTIVE_FEATURE_FLAGS = '$active_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details'\nexport const PERSISTENCE_FEATURE_FLAG_PAYLOADS = '$feature_flag_payloads'\nexport const PERSISTENCE_FEATURE_FLAG_REQUEST_ID = '$feature_flag_request_id'\nexport const PERSISTENCE_MINIMAL_FLAG_CALLED_EVENTS = '$minimal_flag_called_events'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAGS = '$override_feature_flags'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS = '$override_feature_flag_payloads'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const SURVEYS_LOADED_AT = '$surveys_loaded_at'\nexport const SURVEYS_ACTIVATED = '$surveys_activated'\nexport const SURVEYS_ACTIVATED_SESSION = '$surveys_activated_session'\nexport const SURVEYS_ACTIVATED_TIMESTAMPS = '$surveys_activated_timestamps'\nexport const PRODUCT_TOURS = 'ph_product_tours'\nexport const PRODUCT_TOURS_ACTIVATED = '$product_tours_activated'\nexport const PRODUCT_TOURS_ACTIVATED_SESSION = '$product_tours_activated_session'\nexport const CONVERSATIONS = '$conversations'\nexport const CONVERSATIONS_LEGACY_WIDGET_SESSION_ID = '$conversations_widget_session_id'\nexport const CONVERSATIONS_LEGACY_TICKET_ID = '$conversations_ticket_id'\nexport const CONVERSATIONS_LEGACY_WIDGET_STATE = '$conversations_widget_state'\nexport const CONVERSATIONS_LEGACY_USER_TRAITS = '$conversations_user_traits'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const FLAG_CALL_REPORTED_SESSION_ID = '$flag_call_reported_session_id'\nexport const PERSISTENCE_FEATURE_FLAG_ERRORS = '$feature_flag_errors'\nexport const PERSISTENCE_FEATURE_FLAG_EVALUATED_AT = '$feature_flag_evaluated_at'\nexport const USER_STATE = '$user_state'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\nexport const CAPTURE_RATE_LIMIT = '$capture_rate_limit'\n\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params'\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_REFERRER_INFO = '$initial_referrer_info'\nexport const INITIAL_PERSON_INFO = '$initial_person_info'\nexport const ENABLE_PERSON_PROCESSING = '$epp'\n\n/**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * Sentinel value for distinct id, device id, session id. Signals that the server should generate the value\n * */\nexport const COOKIELESS_SENTINEL_VALUE = '$posthog_cookieless'\nexport const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode'\n\nexport const WEB_EXPERIMENTS = '$web_experiments'\n\nexport const SDK_DEBUG_EXTENSIONS_INIT_METHOD = '$sdk_debug_extensions_init_method'\nexport const SDK_DEBUG_EXTENSIONS_INIT_TIME_MS = '$sdk_debug_extensions_init_time_ms'\nexport const SDK_DEBUG_RECORDING_SCRIPT_NOT_LOADED = '$sdk_debug_recording_script_not_loaded'\nexport const SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS = '$sdk_debug_replay_event_trigger_status'\nexport const SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS = '$sdk_debug_replay_linked_flag_trigger_status'\nexport const SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS = '$sdk_debug_replay_matched_recording_trigger_groups'\nexport const SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG = '$sdk_debug_replay_remote_trigger_matching_config'\nexport const SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT = '$sdk_debug_replay_trigger_groups_count'\nexport const SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS = '$sdk_debug_replay_url_trigger_status'\nexport const SDK_DEBUG_REPLAY_RRWEB_ATTACHED = '$sdk_debug_rrweb_attached'\nexport const SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED = '$sdk_debug_rrweb_start_attempted'\nexport const SESSION_RECORDING_START_REASON = '$session_recording_start_reason'\n\nexport const SURVEYS_REQUEST_TIMEOUT_MS = 10000\n// How long the cached `$surveys` definitions are considered fresh. After this, the next\n// `getSurveys` call serves the cache immediately but kicks off a background refresh so\n// server-side changes (e.g. a survey switched from popover to API) propagate to a\n// long-lived tab without needing a page reload.\nexport const SURVEYS_CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes\n// After a failed background refresh we back off for the same window as the cache TTL before\n// trying again. Aliased to make the shared duration intentional rather than coincidental.\nexport const SURVEYS_REFRESH_BACKOFF_MS = SURVEYS_CACHE_TTL_MS\nexport const LOAD_EXT_NOT_FOUND = 'PostHog loadExternalDependency extension not found.'\n\n/* EVENT NAMES - interned to reduce bundle size */\n/* COOKIELESS MODE VALUES */\nexport const COOKIELESS_ON_REJECT = 'on_reject' as const\nexport const COOKIELESS_ALWAYS = 'always' as const\n\n/* USER STATE VALUES */\nexport const USER_STATE_ANONYMOUS = 'anonymous'\nexport const USER_STATE_IDENTIFIED = 'identified'\n\n/* PERSON PROFILE MODES */\nexport const PERSON_PROFILES_IDENTIFIED_ONLY = 'identified_only' as const\n\n/* DOM EVENT NAMES - interned to reduce bundle size */\nexport const DOM_EVENT_VISIBILITYCHANGE = 'visibilitychange'\nexport const DOM_EVENT_BEFOREUNLOAD = 'beforeunload'\n\nexport const EVENT_PAGEVIEW = '$pageview'\nexport const EVENT_PAGELEAVE = '$pageleave'\nexport const EVENT_IDENTIFY = '$identify'\nexport const EVENT_GROUPIDENTIFY = '$groupidentify'\n\n/* Z-INDEX HIERARCHY: tours > surveys > support */\nexport const Z_INDEX_TOURS = 2147483646\nexport const Z_INDEX_SURVEYS = 2147483645\nexport const Z_INDEX_CONVERSATIONS = 2147483644\n","import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","import { querySelectorAllDeep } from 'query-selector-shadow-dom'\nimport { window as _window } from '@posthog/browser-common/utils/globals'\nimport { createLogger, isArray, isUndefined } from '@posthog/core'\n\nconst window = _window as Window & typeof globalThis\nconst logger = createLogger('[Element Inference]')\n\n// this is copied directly from the main repo: /frontend/src/toolbar/utils.ts\n// TODO: once this is deployed, we can have the main repo reference this instead\nexport function elementIsVisible(element: HTMLElement, cache: WeakMap<HTMLElement, boolean>): boolean {\n try {\n const alreadyCached = cache.get(element)\n if (!isUndefined(alreadyCached)) {\n return alreadyCached\n }\n\n if (element.checkVisibility) {\n const nativeIsVisible = element.checkVisibility({\n checkOpacity: true,\n checkVisibilityCSS: true,\n })\n cache.set(element, nativeIsVisible)\n return nativeIsVisible\n }\n\n const style = window.getComputedStyle(element)\n const isInvisible = style.display === 'none' || style.visibility === 'hidden' || parseFloat(style.opacity) === 0\n if (isInvisible) {\n cache.set(element, false)\n return false\n }\n\n // Check parent chain for display/visibility\n let parent = element.parentElement\n while (parent) {\n // Check cache first\n const cached = cache.get(parent)\n if (!isUndefined(cached)) {\n if (!cached) {\n return false\n }\n // If cached as visible, skip to next parent\n parent = parent.parentElement\n continue\n }\n\n const parentStyle = window.getComputedStyle(parent)\n const parentVisible = parentStyle.display !== 'none' && parentStyle.visibility !== 'hidden'\n\n cache.set(parent, parentVisible)\n\n if (!parentVisible) {\n return false\n }\n parent = parent.parentElement\n }\n\n // Check if element has actual rendered dimensions\n const rect = element.getBoundingClientRect()\n const elementHasActualRenderedDimensions =\n rect.width > 0 ||\n rect.height > 0 ||\n // Some elements might be 0x0 but still visible (e.g., inline elements with content)\n element.getClientRects().length > 0\n cache.set(element, elementHasActualRenderedDimensions)\n return elementHasActualRenderedDimensions\n } catch {\n // if we can't get the computed style, we'll assume the element is visible\n return true\n }\n}\n\nexport interface SelectorGroup {\n cardinality: number\n cssSelectors: Array<{\n css: string\n offset: number\n }>\n}\n\nexport interface AutoData {\n notextGroups: SelectorGroup[]\n textGroups: SelectorGroup[]\n}\n\nexport interface InferredSelector {\n autoData: string\n text: string | null\n excludeText?: boolean\n precision?: number\n}\n\nfunction getElementText(element: HTMLElement): string | null {\n const text = element.innerText?.trim()\n // anything higher than 250 chars -> prob not a good selector / button / target\n if (!text || text.length > 250) {\n return null\n }\n return text\n}\n\nfunction elementMatchesText(element: HTMLElement, text: string): boolean {\n const elementText = getElementText(element)\n return elementText?.toLowerCase() === text.toLowerCase()\n}\n\n// generator to query elements, filtering by text and visibility\nfunction* queryElements(\n selector: string,\n text: string | null,\n visibilityCache: WeakMap<HTMLElement, boolean>\n): Generator<HTMLElement, void, undefined> {\n let elements: HTMLElement[]\n\n try {\n elements = querySelectorAllDeep(selector) as unknown as HTMLElement[]\n } catch {\n return\n }\n\n for (const el of elements) {\n const element = el as HTMLElement\n if (text && !elementMatchesText(element, text)) {\n continue\n }\n if (!elementIsVisible(element, visibilityCache)) {\n continue\n }\n yield element\n }\n}\n\n// could be inlined, but wanna keep lazy eval from queryElements\nfunction nth<T>(iterable: Iterable<T>, n: number): T | null {\n let idx = 0\n for (const item of iterable) {\n if (idx === n) {\n return item\n }\n idx++\n }\n return null\n}\n\n/**\n * if inferSelector is the sauce, this is the nugget\n *\n * find an element in the dom using the element inference data\n *\n * 1. try each group of selectors, starting with most specific (lowest cardinality)\n * 2. try each selector in the group - run the css query, go to offset\n * 3. \"vote\" for the element if it was found\n * 4. return early if any element gets majority votes\n * 5. return element w/ most votes\n */\nexport function findElement(selector: InferredSelector): HTMLElement | null {\n try {\n const autoData = JSON.parse(selector.autoData) as AutoData\n if (!isArray(autoData?.textGroups) || !isArray(autoData?.notextGroups)) {\n logger.error('Invalid autoData structure:', autoData)\n return null\n }\n const { text, excludeText, precision = 1 } = selector\n\n // excludeText -> user setting, usually if the target element\n // has dynamic/localized text\n const useText = text != null && !excludeText\n\n // choose appropriate group + sort\n const groups = (useText ? autoData.textGroups : autoData.notextGroups).sort(\n (a, b) => a.cardinality - b.cardinality\n )\n\n if (groups.length === 0) {\n return null\n }\n\n // precision controls how many groups to search\n // 1 = strict (only most specific group), 0 = loose (all groups)\n const maxGroups = Math.max(1, Math.ceil((1 - precision) * groups.length))\n\n const visibilityCache = new WeakMap<HTMLElement, boolean>()\n\n // try each selector group, starting w/ most specific (lowest cardinality)\n for (let i = 0; i < maxGroups; i++) {\n const group = groups[i]\n const votes = new Map<HTMLElement, number>()\n let winner: HTMLElement | null = null\n let maxVotes = 0\n\n // test each selector in the group\n for (const { css, offset } of group.cssSelectors) {\n // get matches, jump to offset to find our target\n const element = nth(queryElements(css, useText ? text : null, visibilityCache), offset)\n\n if (!element) {\n continue\n }\n\n // if we found something, this element gets a vote\n const voteCount = (votes.get(element) ?? 0) + 1\n votes.set(element, voteCount)\n\n if (voteCount > maxVotes) {\n maxVotes = voteCount\n winner = element\n\n // break early if we have a majority\n if (voteCount >= Math.ceil(group.cssSelectors.length / 2)) {\n return winner\n }\n }\n }\n\n if (winner) {\n return winner\n }\n }\n\n return null\n } catch (error) {\n logger.error('Error finding element:', error)\n return null\n }\n}\n\nexport function getElementPath(el: HTMLElement | null, depth = 4): string | null {\n if (!el) {\n return null\n }\n const parts: string[] = []\n let current: HTMLElement | null = el\n\n while (current && parts.length < depth && current.tagName !== 'BODY') {\n let part = current.tagName.toLowerCase()\n if (current.id) {\n part += `#${current.id}`\n } else if (current.classList.length) {\n part += `.${current.classList[0]}`\n }\n parts.unshift(part)\n current = current.parentElement\n }\n\n return parts.join(' > ')\n}\n","import config from \"../config.mjs\";\nimport { isUndefined } from \"@posthog/core\";\nimport { window as external_globals_mjs_window } from \"./globals.mjs\";\nconst _createLogger = (prefix, { debugEnabled } = {})=>{\n const logger = {\n _log: (level, ...args)=>{\n if (external_globals_mjs_window && (config.DEBUG || external_globals_mjs_window.POSTHOG_DEBUG || debugEnabled) && !isUndefined(external_globals_mjs_window.console) && external_globals_mjs_window.console) {\n const consoleLog = '__rrweb_original__' in external_globals_mjs_window.console[level] ? external_globals_mjs_window.console[level]['__rrweb_original__'] : external_globals_mjs_window.console[level];\n consoleLog(prefix, ...args);\n }\n },\n debug: (...args)=>{\n logger._log('debug', ...args);\n },\n info: (...args)=>{\n logger._log('log', ...args);\n },\n warn: (...args)=>{\n logger._log('warn', ...args);\n },\n error: (...args)=>{\n logger._log('error', ...args);\n },\n critical: (...args)=>{\n console.error(prefix, ...args);\n },\n uninitializedWarning: (methodName)=>{\n logger.error(`You must initialize PostHog before calling ${methodName}`);\n },\n createLogger: (additionalPrefix, options)=>_createLogger(`${prefix} ${additionalPrefix}`, options)\n };\n return logger;\n};\nconst logger_logger = _createLogger('[PostHog.js]');\nconst createLogger = logger_logger.createLogger;\nexport { createLogger, logger_logger as logger };\n","import { isFunction } from \"@posthog/core\";\nimport { createLogger } from \"./logger.mjs\";\nconst logger = createLogger('[Stylesheet Loader]');\nconst getStylesheetPreparer = (context)=>{\n if (isFunction(context)) return context;\n return context?.config?.prepare_external_dependency_stylesheet;\n};\nconst prepareStylesheet = (document, innerText, context)=>{\n let stylesheet = document.createElement('style');\n stylesheet.innerText = innerText;\n const prepareExternalDependencyStylesheet = getStylesheetPreparer(context);\n if (prepareExternalDependencyStylesheet) stylesheet = prepareExternalDependencyStylesheet(stylesheet);\n if (!stylesheet) {\n logger.error('prepare_external_dependency_stylesheet returned null');\n return null;\n }\n return stylesheet;\n};\nexport { prepareStylesheet };\n","import { getSurveyIterationKey } from '@posthog/core/surveys'\n\nimport { DisplaySurveyOptions, Survey, SurveyType, DisplaySurveyType } from '../posthog-surveys-types'\nimport { createLogger } from '@posthog/browser-common/utils/logger'\n\nexport { doesSurveyActivateByEvent, getSurveyInteractionProperty, isSurveyIterationBased } from '@posthog/core/surveys'\n\nexport const SURVEY_LOGGER = createLogger('[Surveys]')\n\nexport function isSurveyRunning(survey: Survey): boolean {\n return !!(survey.start_date && !survey.end_date)\n}\n\nexport function doesSurveyActivateByAction(survey: Pick<Survey, 'conditions'>): boolean {\n return !!survey.conditions?.actions?.values?.length\n}\n\nexport const SURVEY_SEEN_PREFIX = 'seenSurvey_'\nexport const SURVEY_IN_PROGRESS_PREFIX = 'inProgressSurvey_'\nexport const SURVEY_ABANDONED_PREFIX = 'abandonedSurvey_'\n\n// Prefix namespacing is a localStorage concern, so it stays in the browser package;\n// the iteration-qualified key itself is shared with the other SDKs via @posthog/core.\nexport const getSurveyStorageKey = (prefix: string, survey: Pick<Survey, 'id' | 'current_iteration'>): string => {\n return `${prefix}${getSurveyIterationKey(survey)}`\n}\n\nexport const getSurveySeenKey = (survey: Pick<Survey, 'id' | 'current_iteration'>): string => {\n return getSurveyStorageKey(SURVEY_SEEN_PREFIX, survey)\n}\n\nexport const getSurveyAbandonedKey = (survey: Pick<Survey, 'id' | 'current_iteration'>): string => {\n return getSurveyStorageKey(SURVEY_ABANDONED_PREFIX, survey)\n}\n\nexport const setSurveySeenOnLocalStorage = (survey: Pick<Survey, 'id' | 'current_iteration'>) => {\n try {\n const surveySeenKey = getSurveySeenKey(survey)\n const isSurveySeen = localStorage.getItem(surveySeenKey)\n // if survey is already seen, no need to set it again\n if (isSurveySeen) {\n return\n }\n\n localStorage.setItem(surveySeenKey, 'true')\n } catch (error) {\n SURVEY_LOGGER.error('Failed to persist survey seen state', error)\n }\n}\n\n// These surveys are relevant for the getActiveMatchingSurveys method. They are used to\n// display surveys in our customer's application. Any new in-app survey type should be added here.\nexport const IN_APP_SURVEY_TYPES: SurveyType[] = [SurveyType.Popover, SurveyType.Widget, SurveyType.API]\n\nexport const DEFAULT_DISPLAY_SURVEY_OPTIONS: DisplaySurveyOptions = {\n ignoreConditions: false,\n ignoreDelay: false,\n displayType: DisplaySurveyType.Popover,\n}\n","/*! For license information please see uuidv7.mjs.LICENSE.txt */\nimport { window as external_globals_mjs_window } from \"./globals.mjs\";\nimport { isNumber, isUndefined } from \"@posthog/core\";\n/**\n * uuidv7: An experimental implementation of the proposed UUID Version 7\n *\n * @license Apache-2.0\n * @copyright 2021-2023 LiosK\n * @packageDocumentation\n *\n * from https://github.com/LiosK/uuidv7/blob/e501462ea3d23241de13192ceae726956f9b3b7d/src/index.ts\n */ if (!Math.trunc) Math.trunc = function(v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\nif (!Number.isInteger) Number.isInteger = function(value) {\n return isNumber(value) && isFinite(value) && Math.floor(value) === value;\n};\nclass UUID {\n constructor(bytes){\n this.bytes = bytes;\n if (16 !== bytes.length) throw new TypeError('not 128-bit length');\n }\n static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {\n if (!Number.isInteger(unixTsMs) || !Number.isInteger(randA) || !Number.isInteger(randBHi) || !Number.isInteger(randBLo) || unixTsMs < 0 || randA < 0 || randBHi < 0 || randBLo < 0 || unixTsMs > 0xffffffffffff || randA > 0xfff || randBHi > 0x3fffffff || randBLo > 0xffffffff) throw new RangeError('invalid field value');\n const bytes = new Uint8Array(16);\n bytes[0] = unixTsMs / 2 ** 40;\n bytes[1] = unixTsMs / 2 ** 32;\n bytes[2] = unixTsMs / 2 ** 24;\n bytes[3] = unixTsMs / 2 ** 16;\n bytes[4] = unixTsMs / 256;\n bytes[5] = unixTsMs;\n bytes[6] = 0x70 | randA >>> 8;\n bytes[7] = randA;\n bytes[8] = 0x80 | randBHi >>> 24;\n bytes[9] = randBHi >>> 16;\n bytes[10] = randBHi >>> 8;\n bytes[11] = randBHi;\n bytes[12] = randBLo >>> 24;\n bytes[13] = randBLo >>> 16;\n bytes[14] = randBLo >>> 8;\n bytes[15] = randBLo;\n return new UUID(bytes);\n }\n toString() {\n let text = '';\n for(let i = 0; i < this.bytes.length; i++){\n text = text + (this.bytes[i] >>> 4).toString(16) + (0xf & this.bytes[i]).toString(16);\n if (3 === i || 5 === i || 7 === i || 9 === i) text += '-';\n }\n if (36 !== text.length) throw new Error('Invalid UUIDv7 was generated');\n return text;\n }\n clone() {\n return new UUID(this.bytes.slice(0));\n }\n equals(other) {\n return 0 === this.compareTo(other);\n }\n compareTo(other) {\n for(let i = 0; i < 16; i++){\n const diff = this.bytes[i] - other.bytes[i];\n if (0 !== diff) return Math.sign(diff);\n }\n return 0;\n }\n}\nclass V7Generator {\n generate() {\n const value = this.generateOrAbort();\n if (!isUndefined(value)) return value;\n {\n this._timestamp = 0;\n const valueAfterReset = this.generateOrAbort();\n if (isUndefined(valueAfterReset)) throw new Error('Could not generate UUID after timestamp reset');\n return valueAfterReset;\n }\n }\n generateOrAbort() {\n const MAX_COUNTER = 0x3ffffffffff;\n const ROLLBACK_ALLOWANCE = 10000;\n const ts = Date.now();\n if (ts > this._timestamp) {\n this._timestamp = ts;\n this._resetCounter();\n } else {\n if (!(ts + ROLLBACK_ALLOWANCE > this._timestamp)) return;\n this._counter++;\n if (this._counter > MAX_COUNTER) {\n this._timestamp++;\n this._resetCounter();\n }\n }\n return UUID.fromFieldsV7(this._timestamp, Math.trunc(this._counter / 2 ** 30), this._counter & 2 ** 30 - 1, this._random.nextUint32());\n }\n _resetCounter() {\n this._counter = 0x400 * this._random.nextUint32() + (0x3ff & this._random.nextUint32());\n }\n constructor(){\n this._timestamp = 0;\n this._counter = 0;\n this._random = new DefaultRandom();\n }\n}\nlet getRandomValues = (buffer)=>{\n if ('undefined' != typeof UUIDV7_DENY_WEAK_RNG && UUIDV7_DENY_WEAK_RNG) throw new Error('no cryptographically strong RNG available');\n for(let i = 0; i < buffer.length; i++)buffer[i] = 0x10000 * Math.trunc(0x10000 * Math.random()) + Math.trunc(0x10000 * Math.random());\n return buffer;\n};\nif (external_globals_mjs_window && !isUndefined(external_globals_mjs_window.crypto) && crypto.getRandomValues) getRandomValues = (buffer)=>crypto.getRandomValues(buffer);\nclass DefaultRandom {\n nextUint32() {\n if (this._cursor >= this._buffer.length) {\n getRandomValues(this._buffer);\n this._cursor = 0;\n }\n return this._buffer[this._cursor++];\n }\n constructor(){\n this._buffer = new Uint32Array(8);\n this._cursor = 1 / 0;\n }\n}\nlet defaultGenerator;\nconst uuidv7 = ()=>uuidv7obj().toString();\nconst uuidv7obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generate();\nconst uuid7ToTimestampMs = (uuid)=>{\n const hex = uuid.replace(/-/g, '');\n if (32 !== hex.length) throw new Error('Not a valid UUID');\n if ('7' !== hex[12]) throw new Error('Not a UUIDv7');\n return parseInt(hex.substring(0, 12), 16);\n};\nexport { UUID, uuid7ToTimestampMs, uuidv7 };\n","import{options as n}from\"preact\";var t,r,u,i,o=0,f=[],c=n,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,p=c.__;function s(n,t){c.__h&&c.__h(r,n,o||t),o=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return o=1,y(D,n)}function y(n,u,i){var o=s(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):D(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.__f)){var f=function(n,t,r){if(!o.__c.__H)return!0;var u=!1,i=o.__c.props!==n;if(o.__c.__H.__.some(function(n){if(n.__N){u=!0;var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0)}}),c){var f=c.call(this,n,t,r);return u?f||i:f}return!u||i};r.__f=!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 h(n,u){var i=s(t++,3);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__H.__h.push(i))}function _(n,u){var i=s(t++,4);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__h.push(i))}function A(n){return o=5,T(function(){return{current:n}},[])}function F(n,t,r){o=6,_(function(){if(\"function\"==typeof n){var r=n(t());return function(){n(null),r&&\"function\"==typeof r&&r()}}if(n)return n.current=t(),function(){return n.current=null}},null==r?r:r.concat(n))}function T(n,r){var u=s(t++,7);return C(u.__H,r)&&(u.__=n(),u.__H=r,u.__h=n),u.__}function q(n,t){return o=8,T(function(){return n},t)}function x(n){var u=r.context[n.__c],i=s(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function P(n,t){c.useDebugValue&&c.useDebugValue(t?t(n):n)}function b(n){var u=s(t++,10),i=d();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 g(){var n=s(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 j(){for(var n;n=f.shift();){var t=n.__H;if(n.__P&&t)try{t.__h.some(z),t.__h.some(B),t.__h=[]}catch(r){t.__h=[],c.__e(r,n.__v)}}}c.__b=function(n){r=null,e&&e(n)},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),p&&p(n,t)},c.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(i.__h.length&&j(),t=0)),u=r},c.diffed=function(n){v&&v(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==f.push(t)&&i===c.requestAnimationFrame||((i=c.requestAnimationFrame)||w)(j)),t.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),u=r=null},c.__c=function(n,t){t.some(function(n){try{n.__h.some(z),n.__h=n.__h.filter(function(n){return!n.__||B(n)})}catch(r){t.some(function(n){n.__h&&(n.__h=[])}),t=[],c.__e(r,n.__v)}}),l&&l(n,t)},c.unmount=function(n){m&&m(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.some(function(n){try{z(n)}catch(n){t=n}}),r.__H=void 0,t&&c.__e(t,r.__v))};var k=\"function\"==typeof requestAnimationFrame;function w(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r))}function z(n){var t=r,u=n.__c;\"function\"==typeof u&&(n.__c=void 0,u()),r=t}function B(n){var t=r;n.__c=n.__(),r=t}function C(n,t){return!n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function D(n,t){return\"function\"==typeof t?t(n):t}export{q as useCallback,x as useContext,P as useDebugValue,h as useEffect,b as useErrorBoundary,g as useId,F as useImperativeHandle,_ as useLayoutEffect,T as useMemo,y as useReducer,A as useRef,d as useState};\n//# sourceMappingURL=hooks.module.js.map\n","import { VNode, cloneElement, createContext, type JSX } from 'preact'\nimport { PostHog } from '../../posthog-core'\nimport {\n MultipleSurveyQuestion,\n Survey,\n SurveyAppearance,\n SurveyEventName,\n SurveyEventProperties,\n SurveyPosition,\n SurveyQuestion,\n SurveyType,\n SurveyWidgetType,\n} from '../../posthog-surveys-types'\nimport { document as _document, window as _window } from '@posthog/browser-common/utils/globals'\nimport {\n getSurveyInteractionProperty,\n getSurveySeenKey,\n getSurveyAbandonedKey,\n getSurveyStorageKey,\n SURVEY_LOGGER as logger,\n setSurveySeenOnLocalStorage,\n SURVEY_IN_PROGRESS_PREFIX,\n} from '../../utils/survey-utils'\nimport { isNullish, type SurveyResponses } from '@posthog/core'\nimport {\n buildSurveyResponseProperties,\n canSurveyActivateRepeatedly,\n getSurveyResponseKey,\n surveyHasResponses,\n} from '@posthog/core/surveys'\n\nimport { propertyComparisons } from '@posthog/browser-common/utils/property-utils'\nimport { getTargetingUrl } from '@posthog/browser-common/utils/url-targeting-utils'\nimport { localStore } from '../../storage'\nimport { Properties, PropertyMatchType } from '../../types'\nimport { Z_INDEX_SURVEYS } from '../../constants'\nimport { prepareStylesheet } from '@posthog/browser-common/utils/stylesheet-loader'\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\nimport surveyStyles from './survey.css'\nimport { useContext } from 'preact/hooks'\nimport { doesDeviceTypeMatch, hasPeriodPassed } from '@posthog/browser-common/utils/matcher-utils'\n\nexport function getFontFamily(fontFamily?: string): string {\n if (fontFamily === 'inherit') {\n return 'inherit'\n }\n\n const defaultFontStack =\n 'BlinkMacSystemFont, \"Inter\", \"Segoe UI\", \"Roboto\", Helvetica, Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\"'\n return fontFamily ? `${fontFamily}, ${defaultFontStack}` : `-apple-system, ${defaultFontStack}`\n}\n\nexport { getSurveyResponseKey }\n\nconst BLACK_TEXT_COLOR = '#020617' // Maps out to text-slate-950 from tailwind colors. Intended for text use outside interactive elements like buttons\n\n// Keep in sync with defaultSurveyAppearance on the main app\nexport const defaultSurveyAppearance = {\n fontFamily: 'inherit',\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: SurveyPosition.Right,\n widgetType: SurveyWidgetType.Tab,\n widgetLabel: 'Feedback',\n widgetColor: 'black',\n zIndex: String(Z_INDEX_SURVEYS),\n disabledButtonOpacity: '0.6',\n maxWidth: '300px',\n textSubtleColor: '#939393',\n boxPadding: '20px 24px',\n boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',\n borderRadius: '10px',\n shuffleQuestions: false,\n surveyPopupDelaySeconds: undefined,\n // Not customizable atm\n outlineColor: 'rgba(59, 130, 246, 0.8)',\n inputBackground: 'white',\n inputTextColor: BLACK_TEXT_COLOR,\n scrollbarThumbColor: 'var(--ph-survey-border-color)',\n scrollbarTrackColor: 'var(--ph-survey-background-color)',\n} as const\n\nconst BOTTOM_BORDER_SURVEY_POSITIONS: SurveyPosition[] = [\n SurveyPosition.Center,\n SurveyPosition.Left,\n SurveyPosition.Right,\n]\n\nexport const addSurveyCSSVariablesToElement = (\n element: HTMLElement,\n type: SurveyType,\n appearance?: SurveyAppearance | null\n) => {\n const effectiveAppearance = { ...defaultSurveyAppearance, ...appearance }\n const hostStyle = element.style\n\n const surveyHasBottomBorder =\n !BOTTOM_BORDER_SURVEY_POSITIONS.includes(effectiveAppearance.position) ||\n (type === SurveyType.Widget && appearance?.widgetType === SurveyWidgetType.Tab)\n\n hostStyle.setProperty('--ph-survey-font-family', getFontFamily(effectiveAppearance.fontFamily))\n hostStyle.setProperty('--ph-survey-box-padding', effectiveAppearance.boxPadding)\n hostStyle.setProperty('--ph-survey-max-width', effectiveAppearance.maxWidth)\n hostStyle.setProperty('--ph-survey-z-index', effectiveAppearance.zIndex)\n hostStyle.setProperty('--ph-survey-border-color', effectiveAppearance.borderColor)\n // Non-bottom surveys or tab surveys have the border bottom\n if (surveyHasBottomBorder) {\n hostStyle.setProperty('--ph-survey-border-radius', effectiveAppearance.borderRadius)\n hostStyle.setProperty('--ph-survey-border-bottom', '1.5px solid var(--ph-survey-border-color)')\n } else {\n hostStyle.setProperty('--ph-survey-border-bottom', 'none')\n hostStyle.setProperty(\n '--ph-survey-border-radius',\n `${effectiveAppearance.borderRadius} ${effectiveAppearance.borderRadius} 0 0`\n )\n }\n hostStyle.setProperty('--ph-survey-background-color', effectiveAppearance.backgroundColor)\n hostStyle.setProperty('--ph-survey-box-shadow', effectiveAppearance.boxShadow)\n hostStyle.setProperty('--ph-survey-disabled-button-opacity', effectiveAppearance.disabledButtonOpacity)\n hostStyle.setProperty('--ph-survey-submit-button-color', effectiveAppearance.submitButtonColor)\n hostStyle.setProperty(\n '--ph-survey-submit-button-text-color',\n appearance?.submitButtonTextColor || getContrastingTextColor(effectiveAppearance.submitButtonColor)\n )\n hostStyle.setProperty('--ph-survey-rating-bg-color', effectiveAppearance.ratingButtonColor)\n hostStyle.setProperty('--ph-survey-rating-active-bg-color', effectiveAppearance.ratingButtonActiveColor)\n // Active rating text is always auto-calculated for contrast with active background\n hostStyle.setProperty(\n '--ph-survey-rating-active-text-color',\n getContrastingTextColor(effectiveAppearance.ratingButtonActiveColor)\n )\n // Primary text color: use override if provided, otherwise auto-calculate from background\n hostStyle.setProperty(\n '--ph-survey-text-primary-color',\n appearance?.textColor || getContrastingTextColor(effectiveAppearance.backgroundColor)\n )\n hostStyle.setProperty('--ph-survey-text-subtle-color', effectiveAppearance.textSubtleColor)\n hostStyle.setProperty('--ph-widget-color', effectiveAppearance.widgetColor)\n hostStyle.setProperty('--ph-widget-text-color', getContrastingTextColor(effectiveAppearance.widgetColor))\n hostStyle.setProperty('--ph-widget-z-index', effectiveAppearance.zIndex)\n\n // Use user-provided inputBackground (or deprecated inputBackgroundColor for backwards compat)\n // Fallback to internal default, with slight adjustment for white backgrounds\n const userInputBg = appearance?.inputBackground || appearance?.inputBackgroundColor\n let inputBgColor = userInputBg || effectiveAppearance.inputBackground\n if (!userInputBg && effectiveAppearance.backgroundColor === 'white') {\n inputBgColor = '#f8f8f8'\n }\n hostStyle.setProperty('--ph-survey-input-background', inputBgColor)\n // Input text color applies to both text inputs and inactive rating buttons\n const inputTextColor = appearance?.inputTextColor || getContrastingTextColor(inputBgColor)\n hostStyle.setProperty('--ph-survey-input-text-color', inputTextColor)\n hostStyle.setProperty('--ph-survey-rating-text-color', inputTextColor)\n hostStyle.setProperty('--ph-survey-scrollbar-thumb-color', effectiveAppearance.scrollbarThumbColor)\n hostStyle.setProperty('--ph-survey-scrollbar-track-color', effectiveAppearance.scrollbarTrackColor)\n hostStyle.setProperty('--ph-survey-outline-color', effectiveAppearance.outlineColor)\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\nexport function hex2rgb(c: string): string {\n if (c.startsWith('#')) {\n let hexColor = c.replace(/^#/, '')\n // Handle 3-character shorthand (e.g., #111 -> #111111, #abc -> #aabbcc)\n if (/^[0-9A-Fa-f]{3}$/.test(hexColor)) {\n hexColor = hexColor[0] + hexColor[0] + hexColor[1] + hexColor[1] + hexColor[2] + hexColor[2]\n }\n if (!/^[0-9A-Fa-f]{6}$/.test(hexColor)) {\n return 'rgb(255, 255, 255)'\n }\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 hexToRgba(hex: string, opacity: number): string {\n const rgb = hex2rgb(hex)\n const match = rgb.match(/^rgb\\((\\d+),(\\d+),(\\d+)\\)$/)\n if (!match) {\n return hex\n }\n return `rgba(${match[1]}, ${match[2]}, ${match[3]}, ${opacity})`\n}\n\nexport function getContrastingTextColor(color: string = defaultSurveyAppearance.backgroundColor) {\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_TEXT_COLOR\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_TEXT_COLOR : 'white'\n }\n return BLACK_TEXT_COLOR\n}\n\nexport function getSurveyStylesheet(posthog?: PostHog) {\n const stylesheet = prepareStylesheet(document, typeof surveyStyles === 'string' ? surveyStyles : '', posthog)\n stylesheet?.setAttribute('data-ph-survey-style', 'true')\n return stylesheet\n}\n\nexport const retrieveSurveyShadow = (\n survey: Pick<Survey, 'id' | 'appearance' | 'type'>,\n posthog?: PostHog,\n element?: Element\n) => {\n const widgetClassName = getSurveyContainerClass(survey)\n const existingDiv = document.querySelector(`.${widgetClassName}`)\n\n if (existingDiv && existingDiv.shadowRoot) {\n return {\n shadow: existingDiv.shadowRoot,\n isNewlyCreated: false,\n }\n }\n\n // If it doesn't exist, create it\n const div = document.createElement('div')\n addSurveyCSSVariablesToElement(div, survey.type, survey.appearance)\n div.className = widgetClassName\n const shadow = div.attachShadow({ mode: 'open' })\n const stylesheet = getSurveyStylesheet(posthog)\n if (stylesheet) {\n const existingStylesheet = shadow.querySelector('style')\n if (existingStylesheet) {\n shadow.removeChild(existingStylesheet)\n }\n shadow.appendChild(stylesheet)\n }\n ;(element ? element : document.body).appendChild(div)\n return {\n shadow,\n isNewlyCreated: true,\n }\n}\n\ninterface SendSurveyEventArgs {\n responses: SurveyResponses\n survey: Survey\n surveySubmissionId: string\n isSurveyCompleted: boolean\n posthog?: PostHog\n /** Additional properties to include in the survey event */\n properties?: Properties\n /** The language that was applied to the survey. */\n surveyLanguage?: string | null\n}\n\nexport const sendSurveyEvent = ({\n responses,\n survey,\n surveySubmissionId,\n posthog,\n isSurveyCompleted,\n properties,\n surveyLanguage,\n}: SendSurveyEventArgs) => {\n if (!posthog) {\n logger.error('[survey sent] event not captured, PostHog instance not found.')\n return\n }\n setSurveySeenOnLocalStorage(survey)\n posthog.capture(SurveyEventName.SENT, {\n [SurveyEventProperties.SURVEY_NAME]: survey.name,\n [SurveyEventProperties.SURVEY_ID]: survey.id,\n [SurveyEventProperties.SURVEY_ITERATION]: survey.current_iteration,\n [SurveyEventProperties.SURVEY_ITERATION_START_DATE]: survey.current_iteration_start_date,\n [SurveyEventProperties.SURVEY_SUBMISSION_ID]: surveySubmissionId,\n [SurveyEventProperties.SURVEY_COMPLETED]: isSurveyCompleted,\n ...(surveyLanguage && { [SurveyEventProperties.SURVEY_LANGUAGE]: surveyLanguage }),\n sessionRecordingUrl: posthog.get_session_replay_url?.(),\n ...buildSurveyResponseProperties(responses, survey),\n ...properties,\n $set: {\n [getSurveyInteractionProperty(survey, 'responded')]: true,\n },\n })\n if (isSurveyCompleted) {\n // Only dispatch PHSurveySent if the survey is completed, as that removes the survey from focus\n window.dispatchEvent(new CustomEvent('PHSurveySent', { detail: { surveyId: survey.id } }))\n clearInProgressSurveyState(survey)\n // Recompute the internal targeting flag promptly. The response we just recorded makes this\n // person ineligible server-side, but the cached flag still says \"eligible\", so reloading now\n // stops a quick revisit from re-showing the survey and recording a duplicate response.\n posthog.reloadFeatureFlags()\n }\n}\n\nconst _buildSurveyEventProperties = (\n survey: Survey,\n inProgressSurvey: InProgressSurveyState | null,\n posthog: PostHog\n) => ({\n [SurveyEventProperties.SURVEY_NAME]: survey.name,\n [SurveyEventProperties.SURVEY_ID]: survey.id,\n [SurveyEventProperties.SURVEY_ITERATION]: survey.current_iteration,\n [SurveyEventProperties.SURVEY_ITERATION_START_DATE]: survey.current_iteration_start_date,\n [SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED]: surveyHasResponses(inProgressSurvey?.responses),\n ...(inProgressSurvey?.surveyLanguage && {\n [SurveyEventProperties.SURVEY_LANGUAGE]: inProgressSurvey.surveyLanguage,\n }),\n sessionRecordingUrl: posthog.get_session_replay_url?.(),\n [SurveyEventProperties.SURVEY_SUBMISSION_ID]: inProgressSurvey?.surveySubmissionId,\n ...buildSurveyResponseProperties(inProgressSurvey?.responses, survey),\n})\n\nexport const dismissedSurveyEvent = (\n survey: Survey,\n posthog?: PostHog,\n readOnly?: boolean,\n surveyLanguage?: string | null\n) => {\n if (!posthog) {\n logger.error('[survey dismissed] event not captured, PostHog instance not found.')\n return\n }\n if (readOnly) {\n return\n }\n\n const inProgressSurvey = getInProgressSurveyState(survey)\n posthog.capture(SurveyEventName.DISMISSED, {\n ..._buildSurveyEventProperties(survey, inProgressSurvey, posthog),\n ...(surveyLanguage && { [SurveyEventProperties.SURVEY_LANGUAGE]: surveyLanguage }),\n $set: {\n [getSurveyInteractionProperty(survey, 'dismissed')]: true,\n },\n })\n clearInProgressSurveyState(survey)\n setSurveySeenOnLocalStorage(survey)\n window.dispatchEvent(new CustomEvent('PHSurveyClosed', { detail: { surveyId: survey.id } }))\n}\n\nexport const sendSurveyAbandonedEvent = (survey: Survey, posthog?: PostHog) => {\n if (!posthog) {\n logger.error('[survey abandoned] event not captured, PostHog instance not found.')\n return\n }\n\n const abandonedKey = getSurveyAbandonedKey(survey)\n try {\n if (localStorage.getItem(abandonedKey) === 'true') {\n return\n }\n } catch {\n // localStorage not available\n return\n }\n\n const inProgressSurvey = getInProgressSurveyState(survey)\n if (!inProgressSurvey) {\n return\n }\n\n try {\n localStorage.setItem(abandonedKey, 'true')\n } catch {\n // localStorage not available\n }\n\n posthog.capture(SurveyEventName.ABANDONED, _buildSurveyEventProperties(survey, inProgressSurvey, posthog), {\n transport: 'sendBeacon',\n })\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 if (!survey.appearance || !survey.appearance.shuffleQuestions || survey.enable_partial_responses) {\n return survey.questions\n }\n\n return reverseIfUnshuffled(survey.questions, shuffle(survey.questions))\n}\n\nexport const canActivateRepeatedly = (\n survey: Pick<Survey, 'schedule' | 'conditions' | 'id' | 'current_iteration'>\n): boolean => {\n return canSurveyActivateRepeatedly(survey) || isSurveyInProgress(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 = localStore._get(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\nconst LAST_SEEN_SURVEY_DATE_KEY = 'lastSeenSurveyDate'\n\nexport const hasWaitPeriodPassed = (waitPeriodInDays: number | undefined): boolean => {\n const lastSeenSurveyDate = localStore._get(LAST_SEEN_SURVEY_DATE_KEY)\n return hasPeriodPassed(waitPeriodInDays, lastSeenSurveyDate)\n}\n\ninterface SurveyContextProps {\n isPreviewMode: boolean\n previewPageIndex: number | undefined\n onPopupSurveyDismissed: () => void\n isPopup: boolean\n onPreviewSubmit: (res: string | string[] | number | null) => void\n onPreviewBack: () => void\n surveySubmissionId: string\n /** Additional properties to include in all survey events */\n properties?: Properties\n /** The language that was applied to the survey. */\n surveyLanguage?: string | null\n}\n\nexport const SurveyContext = createContext<SurveyContextProps>({\n isPreviewMode: false,\n previewPageIndex: 0,\n onPopupSurveyDismissed: () => {},\n isPopup: true,\n onPreviewSubmit: () => {},\n onPreviewBack: () => {},\n surveySubmissionId: '',\n properties: undefined,\n surveyLanguage: null,\n})\n\nexport const useSurveyContext = () => {\n return useContext(SurveyContext)\n}\n\ninterface RenderProps {\n component: VNode<{ className: string }>\n children: string\n renderAsHtml?: boolean\n style?: JSX.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\nfunction defaultMatchType(matchType?: PropertyMatchType): PropertyMatchType {\n return matchType ?? 'icontains'\n}\n\n// use urlMatchType to validate url condition, fallback to contains for backwards compatibility\nexport function doesSurveyUrlMatch(survey: Pick<Survey, 'conditions'>, posthog?: PostHog): boolean {\n if (!survey.conditions?.url) {\n return true\n }\n // honors the `get_current_url` config hook so apps that rewrite their URL can target surveys correctly\n const href = getTargetingUrl(posthog)\n if (!href) {\n // if we dont know the url, assume it is not a match\n return false\n }\n const targets = [survey.conditions.url]\n const matchType = defaultMatchType(survey.conditions?.urlMatchType)\n return propertyComparisons[matchType](targets, [href])\n}\n\nexport function doesSurveyDeviceTypesMatch(survey: Survey): boolean {\n return doesDeviceTypeMatch(survey.conditions?.deviceTypes, survey.conditions?.deviceTypesMatchType)\n}\n\nexport function doesSurveyMatchSelector(survey: Survey): boolean {\n if (!survey.conditions?.selector) {\n return true\n }\n return !!document?.querySelector(survey.conditions.selector)\n}\n\ninterface InProgressSurveyState {\n surveySubmissionId: string\n lastQuestionIndex: number\n // Indices the respondent has visited, in order, excluding the current one. Pushed on next, popped on back.\n // Optional for backwards compat with state persisted before the back-navigation feature.\n visitedIndices?: number[]\n responses: SurveyResponses\n surveyLanguage?: string | null\n}\n\nconst getInProgressSurveyStateKey = (survey: Pick<Survey, 'id' | 'current_iteration'>): string => {\n return getSurveyStorageKey(SURVEY_IN_PROGRESS_PREFIX, survey)\n}\n\nexport const setInProgressSurveyState = (\n survey: Pick<Survey, 'id' | 'current_iteration'>,\n state: InProgressSurveyState\n): void => {\n try {\n localStorage.setItem(getInProgressSurveyStateKey(survey), JSON.stringify(state))\n } catch (e) {\n logger.error('Error setting in-progress survey state in localStorage', e)\n }\n}\n\nexport const getInProgressSurveyState = (\n survey: Pick<Survey, 'id' | 'current_iteration'>\n): InProgressSurveyState | null => {\n try {\n const stateString = localStorage.getItem(getInProgressSurveyStateKey(survey))\n if (stateString) {\n return JSON.parse(stateString) as InProgressSurveyState\n }\n } catch (e) {\n logger.error('Error getting in-progress survey state from localStorage', e)\n }\n return null\n}\n\nexport const isSurveyInProgress = (survey: Pick<Survey, 'id' | 'current_iteration'>): boolean => {\n const state = getInProgressSurveyState(survey)\n return !isNullish(state?.surveySubmissionId)\n}\n\nexport const clearInProgressSurveyState = (survey: Pick<Survey, 'id' | 'current_iteration'>): void => {\n try {\n localStorage.removeItem(getInProgressSurveyStateKey(survey))\n } catch (e) {\n logger.error('Error clearing in-progress survey state from localStorage', e)\n }\n}\n\nexport function getSurveyContainerClass(survey: Pick<Survey, 'id'>, asSelector = false): string {\n const className = `PostHogSurvey-${survey.id}`\n return asSelector ? `.${className}` : className\n}\n\n/**\n * Get CSS position styles for a popover/modal based on SurveyPosition\n * Used by both surveys and product tours for consistent positioning\n */\nexport function getPopoverPosition(\n type?: SurveyType,\n position: SurveyPosition = SurveyPosition.Right,\n surveyWidgetType?: SurveyWidgetType\n): Record<string, string> {\n if (type === SurveyType.ExternalSurvey) {\n return {}\n }\n\n switch (position) {\n case SurveyPosition.TopLeft:\n return { top: '0', left: '0', transform: 'translate(30px, 30px)' }\n case SurveyPosition.TopRight:\n return { top: '0', right: '0', transform: 'translate(-30px, 30px)' }\n case SurveyPosition.TopCenter:\n return { top: '0', left: '50%', transform: 'translate(-50%, 30px)' }\n case SurveyPosition.MiddleLeft:\n return { top: '50%', left: '0', transform: 'translate(30px, -50%)' }\n case SurveyPosition.MiddleRight:\n return { top: '50%', right: '0', transform: 'translate(-30px, -50%)' }\n case SurveyPosition.MiddleCenter:\n return { top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }\n case SurveyPosition.Left:\n return { left: '30px' }\n case SurveyPosition.Center:\n return { left: '50%', transform: 'translateX(-50%)' }\n default:\n case SurveyPosition.Right:\n return { right: type === SurveyType.Widget && surveyWidgetType === SurveyWidgetType.Tab ? '60px' : '30px' }\n }\n}\n","import DOMPurify from 'dompurify'\n\nimport { PostHog } from '../../posthog-core'\nimport {\n JSONContent,\n ProductTourAppearance,\n ProductTourSelectorError,\n ProductTourStep,\n DEFAULT_PRODUCT_TOUR_APPEARANCE,\n ProductTourWaitPeriod,\n} from '../../posthog-product-tours-types'\nimport { findElement } from './element-inference'\nimport { prepareStylesheet } from '@posthog/browser-common/utils/stylesheet-loader'\nimport { document as _document, window as _window } from '@posthog/browser-common/utils/globals'\nimport { getFontFamily, getContrastingTextColor, hexToRgba } from '../surveys/surveys-extension-utils'\nimport { createLogger } from '@posthog/browser-common/utils/logger'\nimport { localStore } from '../../storage'\nimport { LAST_SEEN_TOUR_DATE_KEY_PREFIX } from './constants'\n\nimport productTourStyles from './product-tour.css'\nimport { isUndefined } from '@posthog/core'\nimport { hasPeriodPassed } from '@posthog/browser-common/utils/matcher-utils'\n\nconst logger = createLogger('[Product Tours]')\n\nconst document = _document as Document\nconst window = _window as Window & typeof globalThis\n\nexport function getProductTourStylesheet(posthog?: PostHog): HTMLStyleElement | null {\n const stylesheet = prepareStylesheet(\n document,\n typeof productTourStyles === 'string' ? productTourStyles : '',\n posthog\n )\n stylesheet?.setAttribute('data-ph-product-tour-style', 'true')\n return stylesheet\n}\n\nexport interface ElementFindResult {\n element: HTMLElement | null\n error: ProductTourSelectorError | null\n matchCount: number\n}\n\nexport function hasElementTarget(step: ProductTourStep): boolean {\n if (step.useManualSelector) {\n return !!step.selector\n }\n return !!step.inferenceData\n}\n\nexport function findElementBySelector(selector: string): ElementFindResult {\n try {\n const elements = document.querySelectorAll(selector)\n\n if (elements.length === 0) {\n return { element: null, error: 'not_found', matchCount: 0 }\n }\n\n const element = elements[0] as HTMLElement\n\n if (!isElementVisible(element)) {\n return { element: null, error: 'not_visible', matchCount: elements.length }\n }\n\n if (elements.length > 1) {\n return { element, error: 'multiple_matches', matchCount: elements.length }\n }\n\n return { element, error: null, matchCount: 1 }\n } catch {\n return { element: null, error: 'not_found', matchCount: 0 }\n }\n}\n\n/**\n * Find element for a step based on its lookup mode.\n * Default: use inference. If useManualSelector is true: use CSS selector.\n */\nexport function findStepElement(step: ProductTourStep): ElementFindResult {\n const useManualSelector = step.useManualSelector ?? false\n\n if (useManualSelector) {\n if (!step.selector) {\n return { element: null, error: 'not_found', matchCount: 0 }\n }\n return findElementBySelector(step.selector)\n }\n\n if (!step.inferenceData) {\n return { element: null, error: 'not_found', matchCount: 0 }\n }\n\n const element = findElement(step.inferenceData)\n return element ? { element, error: null, matchCount: 1 } : { element: null, error: 'not_found', matchCount: 0 }\n}\n\nexport function isElementVisible(element: HTMLElement): boolean {\n const style = window.getComputedStyle(element)\n\n if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {\n return false\n }\n\n const rect = element.getBoundingClientRect()\n if (rect.width === 0 || rect.height === 0) {\n return false\n }\n\n return true\n}\n\nexport function getElementMetadata(element: HTMLElement): {\n tag: string\n id: string | undefined\n classes: string | undefined\n text: string | undefined\n} {\n return {\n tag: element.tagName,\n id: element.id || undefined,\n classes: element.className || undefined,\n text: element.innerText?.slice(0, 100) || undefined,\n }\n}\n\nexport type TooltipPosition = 'top' | 'bottom' | 'left' | 'right'\n\nexport interface PositionResult {\n position: TooltipPosition\n top?: number\n bottom?: number\n left?: number\n right?: number\n arrowOffset: number // pixels from center (positive = right/down)\n}\n\nconst TOOLTIP_MARGIN = 12\nconst VIEWPORT_PADDING = 8\n\nfunction clampToViewport(\n value: number,\n dimension: number,\n viewportDimension: number\n): { clamped: number; offset: number } {\n const min = VIEWPORT_PADDING + dimension / 2\n const max = viewportDimension - VIEWPORT_PADDING - dimension / 2\n const clamped = Math.max(min, Math.min(max, value))\n return { clamped, offset: value - clamped }\n}\n\nexport interface TooltipDimensions {\n width: number\n height: number\n}\n\nexport function calculateTooltipPosition(targetRect: DOMRect, tooltipDimensions: TooltipDimensions): PositionResult {\n const viewportWidth = window.innerWidth\n const viewportHeight = window.innerHeight\n\n const { width, height } = tooltipDimensions\n const spaceAbove = targetRect.top\n const spaceBelow = viewportHeight - targetRect.bottom\n const spaceLeft = targetRect.left\n const spaceRight = viewportWidth - targetRect.right\n\n const targetCenterY = targetRect.top + targetRect.height / 2\n const targetCenterX = targetRect.left + targetRect.width / 2\n\n if (spaceRight >= width + TOOLTIP_MARGIN) {\n // right of element\n const left = targetRect.right + TOOLTIP_MARGIN\n const { clamped: top, offset: arrowOffset } = clampToViewport(targetCenterY, height, viewportHeight)\n return { position: 'right', top, left, arrowOffset }\n }\n if (spaceLeft >= width + TOOLTIP_MARGIN) {\n // left of element\n const right = viewportWidth - targetRect.left + TOOLTIP_MARGIN\n const { clamped: top, offset: arrowOffset } = clampToViewport(targetCenterY, height, viewportHeight)\n return { position: 'left', top, right, arrowOffset }\n }\n if (spaceAbove >= height + TOOLTIP_MARGIN && spaceBelow < height + TOOLTIP_MARGIN) {\n // above element\n const bottom = viewportHeight - targetRect.top + TOOLTIP_MARGIN\n const { clamped: left, offset: arrowOffset } = clampToViewport(targetCenterX, width, viewportWidth)\n return { position: 'top', bottom, left, arrowOffset }\n }\n\n // default: below element\n const top = targetRect.bottom + TOOLTIP_MARGIN\n const { clamped: left, offset: arrowOffset } = clampToViewport(targetCenterX, width, viewportWidth)\n return { position: 'bottom', top, left, arrowOffset }\n}\n\nexport function getSpotlightStyle(targetRect: DOMRect, padding: number = 8): Record<string, string> {\n return {\n top: `${targetRect.top - padding}px`,\n left: `${targetRect.left - padding}px`,\n width: `${targetRect.width + padding * 2}px`,\n height: `${targetRect.height + padding * 2}px`,\n }\n}\n\nexport function addProductTourCSSVariablesToElement(element: HTMLElement, appearance?: ProductTourAppearance): void {\n const merged = { ...DEFAULT_PRODUCT_TOUR_APPEARANCE, ...appearance }\n const style = element.style\n\n // User-customizable variables\n style.setProperty('--ph-tour-background-color', merged.backgroundColor)\n style.setProperty('--ph-tour-text-color', merged.textColor)\n style.setProperty('--ph-tour-button-color', merged.buttonColor)\n style.setProperty('--ph-tour-border-radius', `${merged.borderRadius}px`)\n style.setProperty('--ph-tour-button-border-radius', `${merged.buttonBorderRadius}px`)\n style.setProperty('--ph-tour-border-color', merged.borderColor)\n style.setProperty('--ph-tour-font-family', getFontFamily(merged.fontFamily))\n\n // Derived colors\n style.setProperty('--ph-tour-text-secondary-color', hexToRgba(merged.textColor, 0.6))\n style.setProperty('--ph-tour-branding-text-color', getContrastingTextColor(merged.backgroundColor))\n style.setProperty('--ph-tour-button-text-color', getContrastingTextColor(merged.buttonColor))\n style.setProperty('--ph-tour-box-shadow', merged.boxShadow)\n style.setProperty('--ph-tour-overlay-color', merged.showOverlay ? 'rgba(0, 0, 0, 0.5)' : 'transparent')\n style.setProperty('--ph-tour-z-index', String(merged.zIndex))\n\n // Internal styling variables (not customizable)\n style.setProperty('--ph-tour-button-secondary-color', 'transparent')\n style.setProperty('--ph-tour-button-secondary-text-color', merged.textColor)\n style.setProperty('--ph-tour-max-width', '320px')\n style.setProperty('--ph-tour-padding', '16px')\n}\n\nexport function renderTipTapContent(content: any): string {\n if (!content) {\n return ''\n }\n\n if (typeof content === 'string') {\n return escapeHtml(content)\n }\n\n if (content.type === 'text') {\n let text = escapeHtml(content.text || '')\n\n if (content.marks) {\n for (const mark of content.marks) {\n switch (mark.type) {\n case 'bold':\n text = `<strong>${text}</strong>`\n break\n case 'italic':\n text = `<em>${text}</em>`\n break\n case 'underline':\n text = `<u>${text}</u>`\n break\n case 'strike':\n text = `<s>${text}</s>`\n break\n }\n }\n }\n\n return text\n }\n\n const children = content.content?.map(renderTipTapContent).join('') || ''\n\n switch (content.type) {\n case 'doc':\n return children\n case 'paragraph':\n return `<p>${children}</p>`\n case 'heading': {\n const level = content.attrs?.level || 1\n return `<h${level}>${children}</h${level}>`\n }\n case 'bulletList':\n return `<ul>${children}</ul>`\n case 'orderedList':\n return `<ol>${children}</ol>`\n case 'listItem':\n return `<li>${children}</li>`\n case 'hardBreak':\n return '<br>'\n default:\n return children\n }\n}\n\nexport function normalizeUrl(url: string): string {\n return url.endsWith('/') ? url.slice(0, -1) : url\n}\n\nfunction escapeHtml(text: string): string {\n const div = document.createElement('div')\n div.textContent = text\n return div.innerHTML\n}\n\nexport function resolveStepTranslation(step: ProductTourStep, lang: string | null): ProductTourStep {\n if (!lang || !step.translations) {\n return step\n }\n\n const translations = step.translations\n\n // exact match (en-US === en-US), then base match (en-US falls back to en)\n const t = translations[lang] ?? translations[lang.split('-')[0]]\n\n if (!t) {\n logger.info(`No matching translation for \"${lang}\" in step ${step.id}, using default`)\n return step\n }\n\n const resolved = { ...step }\n\n if (!isUndefined(t.content)) {\n resolved.content = t.content\n }\n\n if (!isUndefined(t.contentHtml)) {\n resolved.contentHtml = t.contentHtml\n }\n\n if (t.buttons && resolved.buttons) {\n resolved.buttons = {\n primary: resolved.buttons.primary && { ...resolved.buttons.primary, ...t.buttons.primary },\n secondary: resolved.buttons.secondary && { ...resolved.buttons.secondary, ...t.buttons.secondary },\n }\n }\n\n if (t.survey && resolved.survey) {\n resolved.survey = { ...resolved.survey, ...t.survey }\n }\n\n return resolved\n}\n\nexport function getStepImageUrls(step: ProductTourStep): string[] {\n const urls: string[] = []\n function walk(node: JSONContent) {\n if (node.type === 'image' && node.attrs?.src) {\n urls.push(node.attrs.src)\n }\n node.content?.forEach(walk)\n }\n if (step.content) {\n walk(step.content)\n }\n return urls\n}\n\nexport function getStepHtml(step: ProductTourStep): string {\n if (step.contentHtml) {\n return DOMPurify.sanitize(step.contentHtml, {\n ADD_TAGS: ['iframe'],\n ADD_ATTR: ['allowfullscreen', 'frameborder', 'referrerpolicy'],\n })\n }\n\n // backwards compat, will be deprecated\n return renderTipTapContent(step.content)\n}\n\nexport function hasTourWaitPeriodPassed(seenTourWaitPeriod?: ProductTourWaitPeriod): boolean {\n if (!seenTourWaitPeriod) {\n return true\n }\n\n const { days, types } = seenTourWaitPeriod\n if (!days || !types || types.length === 0) {\n return true\n }\n\n let mostRecentDate: Date | null = null\n\n for (const type of types) {\n const raw = localStore._get(`${LAST_SEEN_TOUR_DATE_KEY_PREFIX}${type}`)\n if (raw) {\n try {\n const stored = JSON.parse(raw)\n const date = new Date(stored)\n if (!isNaN(date.getTime()) && (!mostRecentDate || date > mostRecentDate)) {\n mostRecentDate = date\n }\n } catch {\n // ignore malformed entries\n }\n }\n }\n\n if (!mostRecentDate) {\n return true\n }\n\n return hasPeriodPassed(days, mostRecentDate)\n}\n","export const satisfiedEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 -960 960 960\" width=\"48\">\n <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\" />\n </svg>\n)\nexport const neutralEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 -960 960 960\" width=\"48\">\n <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\" />\n </svg>\n)\nexport const dissatisfiedEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 -960 960 960\" width=\"48\">\n <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\" />\n </svg>\n)\nexport const veryDissatisfiedEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 -960 960 960\" width=\"48\">\n <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\" />\n </svg>\n)\nexport const verySatisfiedEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 -960 960 960\" width=\"48\">\n <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\" />\n </svg>\n)\nexport const thumbsUpEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 0 24 24\" width=\"48\">\n <path d=\"M2 20h2c.55 0 1-.45 1-1v-9c0-.55-.45-1-1-1H2v11zm19.83-7.12c.11-.25.17-.52.17-.8V11c0-1.1-.9-2-2-2h-5.5l.92-4.65c.05-.22.02-.46-.08-.66-.23-.45-.52-.86-.88-1.22L14 2 7.59 8.41C7.21 8.79 7 9.3 7 9.83v7.84C7 18.95 8.05 20 9.34 20h8.11c.7 0 1.36-.37 1.72-.97l2.66-6.15z\" />\n </svg>\n)\nexport const thumbsDownEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 0 24 24\" width=\"48\">\n <path d=\"M22 4h-2c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h2V4zM2.17 11.12c-.11.25-.17.52-.17.8V13c0 1.1.9 2 2 2h5.5l-.92 4.65c-.05.22-.02.46.08.66.23.45.52.86.88 1.22L10 22l6.41-6.41c.38-.38.59-.89.59-1.42V6.34C17 5.05 15.95 4 14.66 4H6.55c-.7 0-1.36.37-1.72.97l-2.66 6.15z\" />\n </svg>\n)\nexport const cancelSVG = ({ fill = 'currentColor' }: { fill?: string } = {}) => (\n <svg\n width=\"12\"\n height=\"12\"\n viewBox=\"0 0 12 12\"\n fill={fill}\n xmlns=\"http://www.w3.org/2000/svg\"\n aria-labelledby=\"close-survey-title-adam\"\n >\n <title id=\"close-survey-title\" className=\"adam-testing\">\n Close survey\n </title>\n <path\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n 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\"\n fill={fill}\n />\n </svg>\n)\nexport const IconPosthogLogo = (\n <svg width=\"77\" height=\"14\" viewBox=\"0 0 77 14\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <g clip-path=\"url(#clip0_2415_6911)\">\n <mask\n id=\"mask0_2415_6911\"\n style={{ maskType: 'luminance' }}\n maskUnits=\"userSpaceOnUse\"\n x=\"0\"\n y=\"0\"\n width=\"77\"\n height=\"14\"\n >\n <path d=\"M0.5 0H76.5V14H0.5V0Z\" fill=\"white\" />\n </mask>\n <g mask=\"url(#mask0_2415_6911)\">\n <path\n 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\"\n fill=\"#1D4AFF\"\n />\n <path\n 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\"\n fill=\"#F9BD2B\"\n />\n <path\n 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\"\n fill=\"currentColor\"\n />\n <path\n 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\"\n fill=\"#1D4AFF\"\n />\n <path\n 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\"\n fill=\"#F54E00\"\n />\n <path\n 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\"\n fill=\"currentColor\"\n />\n </g>\n </g>\n <defs>\n <clipPath id=\"clip0_2415_6911\">\n <rect width=\"76\" height=\"14\" fill=\"white\" transform=\"translate(0.5)\" />\n </clipPath>\n </defs>\n </svg>\n)\nexport const checkSVG = (\n <svg width=\"16\" height=\"12\" viewBox=\"0 0 16 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path\n 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\"\n fill=\"currentColor\"\n />\n </svg>\n)\n","import { h, ComponentChildren } from 'preact'\nimport { ProductTourDisplayFrequency, ProductTourStep } from '../../../posthog-product-tours-types'\nimport { getStepHtml } from '../product-tours-utils'\nimport { cancelSVG } from '../../surveys/icons'\n\nexport interface ProductTourBannerProps {\n step: ProductTourStep\n onDismiss: () => void\n onActionClick?: () => void\n displayFrequency?: ProductTourDisplayFrequency\n}\n\ninterface BannerWrapperProps {\n class: string\n children: ComponentChildren\n}\n\ninterface LinkWrapperProps extends BannerWrapperProps {\n href: string\n onClick?: () => void\n}\n\ninterface ButtonWrapperProps extends BannerWrapperProps {\n onClick: () => void\n}\n\nfunction LinkWrapper({ class: className, href, onClick, children }: LinkWrapperProps): h.JSX.Element {\n return (\n <a class={className} href={href} target=\"_blank\" rel=\"noopener noreferrer\" onClick={onClick}>\n {children}\n </a>\n )\n}\n\nfunction ButtonWrapper({ class: className, onClick, children }: ButtonWrapperProps): h.JSX.Element {\n return (\n <div\n class={className}\n role=\"button\"\n tabIndex={0}\n onClick={onClick}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault()\n onClick()\n }\n }}\n style={{ cursor: 'pointer' }}\n >\n {children}\n </div>\n )\n}\n\nfunction StaticWrapper({ class: className, children }: BannerWrapperProps): h.JSX.Element {\n return <div class={className}>{children}</div>\n}\n\nexport function ProductTourBanner(props: ProductTourBannerProps) {\n return (\n <div class=\"ph-tour-banner-wrapper\">\n <div class=\"ph-tour-banner-slide\">\n <ProductTourBannerInner {...props} />\n </div>\n </div>\n )\n}\n\nfunction ProductTourBannerInner({\n step,\n onDismiss,\n onActionClick,\n displayFrequency,\n}: ProductTourBannerProps): h.JSX.Element {\n const config = step.bannerConfig ?? { behavior: 'sticky' }\n const action = config.action\n\n // \"always\" display frequency means no dismiss button\n const showDismissButton = displayFrequency !== 'always'\n\n const classNames = [\n 'ph-tour-banner',\n config.behavior === 'sticky' && 'ph-tour-banner--sticky',\n config.behavior === 'custom' && 'ph-tour-banner--custom',\n ]\n .filter(Boolean)\n .join(' ')\n\n const content = (\n <>\n <div class=\"ph-tour-banner-content\" dangerouslySetInnerHTML={{ __html: getStepHtml(step) }} />\n\n {showDismissButton && (\n <button\n class=\"ph-tour-banner-dismiss\"\n onClick={(e) => {\n e.stopPropagation()\n e.preventDefault()\n onDismiss()\n }}\n aria-label=\"Close banner\"\n >\n {cancelSVG()}\n </button>\n )}\n </>\n )\n\n if (action?.type === 'link' && action.link) {\n return (\n <LinkWrapper class={classNames} href={action.link} onClick={onActionClick}>\n {content}\n </LinkWrapper>\n )\n }\n\n if (action?.type === 'trigger_tour' && onActionClick) {\n return (\n <ButtonWrapper class={classNames} onClick={onActionClick}>\n {content}\n </ButtonWrapper>\n )\n }\n\n return <StaticWrapper class={classNames}>{content}</StaticWrapper>\n}\n","import { h } from 'preact'\nimport { useState, useRef, useEffect } from 'preact/hooks'\nimport { ProductTourStep, ProductTourAppearance, ProductTourSurveyQuestion } from '../../../posthog-product-tours-types'\nimport { cancelSVG, IconPosthogLogo } from '../../surveys/icons'\nimport {\n dissatisfiedEmoji,\n neutralEmoji,\n satisfiedEmoji,\n veryDissatisfiedEmoji,\n verySatisfiedEmoji,\n} from '../../surveys/icons'\n\nexport interface ProductTourSurveyStepInnerProps {\n step: ProductTourStep\n appearance?: ProductTourAppearance\n stepIndex: number\n totalSteps: number\n onPrevious?: () => void\n onSubmit?: (response: string | number | null) => void\n onDismiss?: () => void\n}\n\nconst threeScaleEmojis = [dissatisfiedEmoji, neutralEmoji, satisfiedEmoji]\nconst fiveScaleEmojis = [veryDissatisfiedEmoji, dissatisfiedEmoji, neutralEmoji, satisfiedEmoji, verySatisfiedEmoji]\n\nfunction getScaleNumbers(scale: number): number[] {\n switch (scale) {\n case 5:\n return [1, 2, 3, 4, 5]\n case 10:\n return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n default:\n return [1, 2, 3, 4, 5]\n }\n}\n\nfunction OpenTextInput({\n value,\n onChange,\n onSubmit,\n isInteractive,\n}: {\n value: string\n onChange: (text: string) => void\n onSubmit?: () => void\n isInteractive: boolean\n}): h.JSX.Element {\n const inputRef = useRef<HTMLTextAreaElement>(null)\n\n useEffect(() => {\n if (isInteractive) {\n setTimeout(() => inputRef.current?.focus(), 100)\n }\n }, [isInteractive])\n\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Enter' && e.metaKey && isInteractive) {\n e.preventDefault()\n onSubmit?.()\n }\n }\n\n return (\n <textarea\n ref={inputRef}\n class=\"ph-tour-survey-textarea\"\n rows={3}\n placeholder=\"Your feedback (optional)...\"\n value={value}\n onInput={(e) => onChange((e.target as HTMLTextAreaElement).value)}\n onKeyDown={handleKeyDown}\n disabled={!isInteractive}\n style={isInteractive ? undefined : { cursor: 'default' }}\n />\n )\n}\n\nfunction RatingInput({\n survey,\n onSubmit,\n isInteractive,\n}: {\n survey: ProductTourSurveyQuestion\n onSubmit?: (rating: number) => void\n isInteractive: boolean\n}): h.JSX.Element {\n const [selectedRating, setSelectedRating] = useState<number | null>(null)\n const display = survey.display || 'emoji'\n const scale = survey.scale || 5\n\n const handleSelect = (rating: number) => {\n if (!isInteractive) {\n return\n }\n setSelectedRating(rating)\n // Auto-submit on selection for ratings\n onSubmit?.(rating)\n }\n\n if (display === 'emoji') {\n const emojis = scale === 3 ? threeScaleEmojis : fiveScaleEmojis\n return (\n <div class=\"ph-tour-survey-rating-container\">\n <div class=\"ph-tour-survey-rating-emoji\">\n {emojis.map((emoji, idx) => {\n const rating = idx + 1\n const isActive = selectedRating === rating\n return (\n <button\n key={idx}\n type=\"button\"\n class={`ph-tour-survey-emoji-button ${isActive ? 'ph-tour-survey-emoji-button--active' : ''}`}\n onClick={() => handleSelect(rating)}\n style={isInteractive ? undefined : { cursor: 'default' }}\n aria-label={`Rate ${rating}`}\n >\n {emoji}\n </button>\n )\n })}\n </div>\n {(survey.lowerBoundLabel || survey.upperBoundLabel) && (\n <div class=\"ph-tour-survey-rating-labels\">\n <span>{survey.lowerBoundLabel}</span>\n <span>{survey.upperBoundLabel}</span>\n </div>\n )}\n </div>\n )\n }\n\n // Number display\n const numbers = getScaleNumbers(scale)\n return (\n <div class=\"ph-tour-survey-rating-container\">\n <div\n class=\"ph-tour-survey-rating-numbers\"\n style={{ gridTemplateColumns: `repeat(${numbers.length}, minmax(0, 1fr))` }}\n >\n {numbers.map((num) => {\n const isActive = selectedRating === num\n return (\n <button\n key={num}\n type=\"button\"\n class={`ph-tour-survey-number-button ${isActive ? 'ph-tour-survey-number-button--active' : ''}`}\n onClick={() => handleSelect(num)}\n style={isInteractive ? undefined : { cursor: 'default' }}\n aria-label={`Rate ${num}`}\n >\n {num}\n </button>\n )\n })}\n </div>\n {(survey.lowerBoundLabel || survey.upperBoundLabel) && (\n <div class=\"ph-tour-survey-rating-labels\">\n <span>{survey.lowerBoundLabel}</span>\n <span>{survey.upperBoundLabel}</span>\n </div>\n )}\n </div>\n )\n}\n\nexport function ProductTourSurveyStepInner({\n step,\n appearance,\n stepIndex,\n totalSteps,\n onPrevious,\n onSubmit,\n onDismiss,\n}: ProductTourSurveyStepInnerProps): h.JSX.Element {\n const [textValue, setTextValue] = useState('')\n const survey = step.survey\n const whiteLabel = appearance?.whiteLabel ?? false\n const isFirstStep = stepIndex === 0\n const isOpenText = survey?.type === 'open'\n\n const isInteractive = !!(onPrevious || onSubmit || onDismiss)\n const cursorStyle = isInteractive ? undefined : { cursor: 'default' }\n\n const handleTextSubmit = () => {\n onSubmit?.(textValue.trim() || null)\n }\n\n if (!survey) {\n return <div />\n }\n\n return (\n <>\n <button class=\"ph-tour-dismiss\" onClick={onDismiss} aria-label=\"Close survey\" style={cursorStyle}>\n {cancelSVG()}\n </button>\n\n <div class=\"ph-tour-survey-question\">{survey.questionText}</div>\n\n {isOpenText ? (\n <OpenTextInput\n value={textValue}\n onChange={setTextValue}\n onSubmit={handleTextSubmit}\n isInteractive={isInteractive}\n />\n ) : (\n <RatingInput survey={survey} onSubmit={onSubmit} isInteractive={isInteractive} />\n )}\n\n <div class=\"ph-tour-footer\">\n <span class=\"ph-tour-progress\">\n {stepIndex + 1} of {totalSteps}\n </span>\n\n <div class=\"ph-tour-buttons\">\n {!isFirstStep && (\n <button\n class=\"ph-tour-button ph-tour-button--secondary\"\n onClick={onPrevious}\n style={cursorStyle}\n >\n {survey.backButtonText || 'Back'}\n </button>\n )}\n {isOpenText && (\n <button\n class=\"ph-tour-button ph-tour-button--primary\"\n onClick={handleTextSubmit}\n style={cursorStyle}\n >\n {survey.submitButtonText || 'Submit'}\n </button>\n )}\n </div>\n </div>\n\n {!whiteLabel && (\n <a\n href={isInteractive ? 'https://posthog.com/product-tours' : undefined}\n target={isInteractive ? '_blank' : undefined}\n rel={isInteractive ? 'noopener noreferrer' : undefined}\n class=\"ph-tour-branding\"\n style={isInteractive ? undefined : { cursor: 'default', pointerEvents: 'none' }}\n >\n Survey by {IconPosthogLogo}\n </a>\n )}\n </>\n )\n}\n","import { h } from 'preact'\nimport { ProductTourStep, ProductTourAppearance, ProductTourStepButton } from '../../../posthog-product-tours-types'\nimport { getStepHtml, hasElementTarget } from '../product-tours-utils'\nimport { IconPosthogLogo, cancelSVG } from '../../surveys/icons'\n\ninterface TourButtonProps {\n button: ProductTourStepButton\n variant: 'primary' | 'secondary'\n onClick: (button: ProductTourStepButton) => void\n cursorStyle?: h.JSX.CSSProperties\n}\n\nfunction TourButton({ button, variant, onClick, cursorStyle }: TourButtonProps): h.JSX.Element {\n const className = `ph-tour-button ph-tour-button--${variant}`\n\n if (button.action === 'link' && button.link) {\n return (\n <a\n href={button.link}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n class={className}\n onClick={() => onClick(button)} // track interaction & dismiss tour\n >\n {button.text}\n </a>\n )\n }\n\n return (\n <button class={className} onClick={() => onClick(button)} style={cursorStyle}>\n {button.text}\n </button>\n )\n}\n\nexport interface ProductTourTooltipInnerProps {\n step: ProductTourStep\n appearance?: ProductTourAppearance\n stepIndex: number\n totalSteps: number\n onNext?: () => void\n onPrevious?: () => void\n onDismiss?: () => void\n onButtonClick?: (button: ProductTourStepButton) => void\n}\n\nexport function ProductTourTooltipInner({\n step,\n appearance,\n stepIndex,\n totalSteps,\n onNext,\n onPrevious,\n onDismiss,\n onButtonClick,\n}: ProductTourTooltipInnerProps): h.JSX.Element {\n const whiteLabel = appearance?.whiteLabel ?? false\n const isLastStep = stepIndex >= totalSteps - 1\n const isFirstStep = stepIndex === 0\n const showDefaultButtons = !step.buttons && (step.progressionTrigger === 'button' || !hasElementTarget(step))\n const hasCustomButtons = !!step.buttons\n\n const isInteractive = !!(onNext || onPrevious || onDismiss || onButtonClick)\n const cursorStyle = isInteractive ? undefined : { cursor: 'default' }\n\n const showPostHogBranding = !whiteLabel && isFirstStep\n\n const handleButtonClick = (button: ProductTourStepButton) => {\n if (onButtonClick) {\n onButtonClick(button)\n }\n }\n\n return (\n <>\n <button class=\"ph-tour-dismiss\" onClick={onDismiss} aria-label=\"Close tour\" style={cursorStyle}>\n {cancelSVG()}\n </button>\n\n <div class=\"ph-tour-content\" dangerouslySetInnerHTML={{ __html: getStepHtml(step) }} />\n\n <div class=\"ph-tour-footer\">\n {totalSteps > 1 && (\n <span class=\"ph-tour-progress\">\n {stepIndex + 1} of {totalSteps}\n </span>\n )}\n\n <div class=\"ph-tour-buttons\">\n {/* Default buttons for tours without custom buttons */}\n {showDefaultButtons && (\n <>\n {!isFirstStep && (\n <button\n class=\"ph-tour-button ph-tour-button--secondary\"\n onClick={onPrevious}\n style={cursorStyle}\n >\n Back\n </button>\n )}\n <button class=\"ph-tour-button ph-tour-button--primary\" onClick={onNext} style={cursorStyle}>\n {isLastStep ? 'Done' : 'Next'}\n </button>\n </>\n )}\n\n {/* Custom buttons */}\n {hasCustomButtons && (\n <>\n {step.buttons?.secondary && (\n <TourButton\n button={step.buttons.secondary}\n variant=\"secondary\"\n onClick={handleButtonClick}\n cursorStyle={cursorStyle}\n />\n )}\n {step.buttons?.primary && (\n <TourButton\n button={step.buttons.primary}\n variant=\"primary\"\n onClick={handleButtonClick}\n cursorStyle={cursorStyle}\n />\n )}\n </>\n )}\n </div>\n </div>\n\n {showPostHogBranding && (\n <a\n href={isInteractive ? 'https://posthog.com/docs/product-tours' : undefined}\n target={isInteractive ? '_blank' : undefined}\n rel={isInteractive ? 'noopener noreferrer' : undefined}\n class=\"ph-tour-branding\"\n style={isInteractive ? undefined : { cursor: 'default', pointerEvents: 'none' }}\n >\n Tour by {IconPosthogLogo}\n </a>\n )}\n </>\n )\n}\n","import { render, JSX } from 'preact'\n\nimport { PostHog } from '../../posthog-core'\nimport { ProductTourStep, ProductTourAppearance } from '../../posthog-product-tours-types'\nimport { document as _document } from '@posthog/browser-common/utils/globals'\nimport { ProductTourBanner } from './components/ProductTourBanner'\nimport { ProductTourSurveyStepInner } from './components/ProductTourSurveyStepInner'\nimport { ProductTourTooltipInner } from './components/ProductTourTooltipInner'\nimport { getProductTourStylesheet, addProductTourCSSVariablesToElement, hasElementTarget } from './product-tours-utils'\n\nconst document = _document as Document\n\nexport interface RenderProductTourPreviewOptions {\n step: ProductTourStep\n appearance?: ProductTourAppearance\n parentElement: HTMLElement\n stepIndex?: number\n totalSteps?: number\n style?: JSX.CSSProperties\n posthog?: PostHog\n}\n\nexport function renderProductTourPreview({\n step,\n appearance,\n parentElement,\n stepIndex = 0,\n totalSteps = 1,\n style,\n posthog,\n}: RenderProductTourPreviewOptions): void {\n parentElement.innerHTML = ''\n\n const shadowHost = document.createElement('div')\n addProductTourCSSVariablesToElement(shadowHost, appearance)\n parentElement.appendChild(shadowHost)\n const shadow = shadowHost.attachShadow({ mode: 'open' })\n\n const stylesheet = getProductTourStylesheet(posthog)\n if (stylesheet) {\n shadow.appendChild(stylesheet)\n }\n\n const renderTarget = document.createElement('div')\n shadow.appendChild(renderTarget)\n\n const isSurveyStep = step.type === 'survey'\n const isBannerStep = step.type === 'banner'\n const isModal = !hasElementTarget(step)\n const tooltipClass = `ph-tour-tooltip${isModal ? ' ph-tour-tooltip--modal' : ''}${isSurveyStep ? ' ph-tour-survey-step' : ''}`\n\n if (isBannerStep) {\n render(\n <div class=\"ph-tour-container\">\n <ProductTourBanner step={step} onDismiss={() => {}} />\n </div>,\n renderTarget\n )\n return\n }\n\n render(\n <div class=\"ph-tour-container\">\n <div\n class={tooltipClass}\n style={{\n position: 'relative',\n animation: 'none',\n ...(step.maxWidth && { width: `${step.maxWidth}px`, maxWidth: `${step.maxWidth}px` }),\n ...style,\n }}\n >\n {isSurveyStep ? (\n <ProductTourSurveyStepInner\n step={step}\n appearance={appearance}\n stepIndex={stepIndex}\n totalSteps={totalSteps}\n />\n ) : (\n <ProductTourTooltipInner\n step={step}\n appearance={appearance}\n stepIndex={stepIndex}\n totalSteps={totalSteps}\n />\n )}\n </div>\n </div>,\n renderTarget\n )\n}\n"],"names":["d","w","_","win","window","global","globalThis","globals_document","document","XMLHttpRequest","entries","Object","setPrototypeOf","isFrozen","getPrototypeOf","getOwnPropertyDescriptor","freeze","seal","create","_ref","Reflect","apply","construct","x","func","thisArg","_len","arguments","length","args","Array","_key","Func","_len2","_key2","arrayForEach","unapply","forEach","arrayLastIndexOf","lastIndexOf","arrayPop","pop","arrayPush","push","arraySplice","splice","stringToLowerCase","String","toLowerCase","stringToString","toString","stringMatch","match","stringReplace","replace","stringIndexOf","indexOf","stringTrim","trim","objectHasOwnProperty","prototype","hasOwnProperty","regExpTest","RegExp","test","typeErrorCreate","TypeError","_len4","_key4","lastIndex","_len3","_key3","addToSet","set","array","transformCaseFunc","undefined","l","element","lcElement","cleanArray","index","clone","object","newObject","_ref3","property","value","isArray","constructor","lookupGetter","prop","desc","get","maybeCall","consoleLike","DEFAULT_PRODUCT_TOUR_APPEARANCE","backgroundColor","textColor","buttonColor","borderRadius","buttonBorderRadius","borderColor","fontFamily","boxShadow","showOverlay","whiteLabel","dismissOnClickOutside","zIndex","type_utils_toString","isUndefined","_createLogger","prefix","_log","level","consoleMethod","debug","info","warn","error","_len5","_key5","critical","_len6","_key6","createLogger","additionalPrefix","fn","console","log","bind","_temp","debugEnabled","logger","external_globals_mjs_window","POSTHOG_DEBUG","consoleLog","uninitializedWarning","methodName","options","Math","trunc","v","ceil","floor","Number","isInteger","call","isNumber","isFinite","crypto","t","r","u","i","o","f","c","n","e","__b","a","__r","diffed","__c","m","unmount","p","__","s","__h","__H","D","__N","setState","__f","props","some","this","shouldComponentUpdate","componentWillUpdate","__e","y","j","shift","__P","z","B","__v","__k","__m","requestAnimationFrame","filter","k","clearTimeout","cancelAnimationFrame","setTimeout","C","BLACK_TEXT_COLOR","defaultSurveyAppearance","hex2rgb","startsWith","hexColor","parseInt","slice","getContrastingTextColor","color","rgb","nameColorToHex","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","honeydew","hotpink","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgrey","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","colorMatch","g","b","sqrt","createContext","isPreviewMode","previewPageIndex","onPopupSurveyDismissed","isPopup","onPreviewSubmit","onPreviewBack","surveySubmissionId","properties","surveyLanguage","_document","hasElementTarget","step","useManualSelector","selector","inferenceData","renderTipTapContent","content","_content$content","escapeHtml","type","text","marks","mark","children","map","join","_content$attrs","attrs","div","createElement","textContent","innerHTML","getStepHtml","contentHtml","DOMPurify","sanitize","ADD_TAGS","ADD_ATTR","satisfiedEmoji","_jsx","className","xmlns","height","viewBox","width","neutralEmoji","dissatisfiedEmoji","veryDissatisfiedEmoji","verySatisfiedEmoji","cancelSVG","_ref$fill","fill","_jsxs","id","IconPosthogLogo","style","maskType","maskUnits","mask","transform","LinkWrapper","class","href","target","rel","onClick","ButtonWrapper","_ref2","role","tabIndex","onKeyDown","key","preventDefault","cursor","StaticWrapper","ProductTourBanner","ProductTourBannerInner","_extends","_ref4","_step$bannerConfig","onDismiss","onActionClick","config","bannerConfig","behavior","action","showDismissButton","displayFrequency","classNames","Boolean","_Fragment","dangerouslySetInnerHTML","__html","stopPropagation","link","threeScaleEmojis","fiveScaleEmojis","OpenTextInput","onChange","onSubmit","isInteractive","inputRef","T","current","useRef","__s","_inputRef$current","focus","useEffect","ref","rows","placeholder","onInput","handleKeyDown","metaKey","disabled","RatingInput","survey","_useState","useState","selectedRating","setSelectedRating","scale","handleSelect","rating","display","emoji","idx","lowerBoundLabel","upperBoundLabel","numbers","getScaleNumbers","gridTemplateColumns","num","ProductTourSurveyStepInner","_appearance$whiteLabe","appearance","stepIndex","totalSteps","onPrevious","_useState2","textValue","setTextValue","isFirstStep","isOpenText","cursorStyle","handleTextSubmit","questionText","backButtonText","submitButtonText","pointerEvents","TourButton","button","variant","ProductTourTooltipInner","_step$buttons","_step$buttons2","onNext","onButtonClick","isLastStep","showDefaultButtons","buttons","progressionTrigger","hasCustomButtons","showPostHogBranding","handleButtonClick","secondary","primary","renderProductTourPreview","parentElement","_ref$stepIndex","_ref$totalSteps","posthog","shadowHost","hex","merged","setProperty","defaultFontStack","getFontFamily","addProductTourCSSVariablesToElement","appendChild","shadow","attachShadow","mode","stylesheet","prepareStylesheet","innerText","context","prepareExternalDependencyStylesheet","_context$config","isFunction","prepare_external_dependency_stylesheet","getStylesheetPreparer","setAttribute","getProductTourStylesheet","renderTarget","isSurveyStep","isBannerStep","tooltipClass","render","position","animation","maxWidth"],"mapp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AAY,CAAE9J,MAAUjC,EAAK+L,SAAQ,KAAMA,SAAa/L,EAAK+L,SAAQ,MAC3EnJ,GACLhC,SAGEgB,GADH6J,EACI9D,GAOAoB,GAP0B,CACvB/I,KAAMA,EACN6H,WAAYA,EACZC,UAAWA,EACXC,WAAYA,QArBxByD,EAmCZ","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]}
1
+ {"version":3,"file":"product-tours-preview.js","sources":["../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/preact/10.29.3/140084fb8a57e97c29fa8a8c859027ef9e32ecc372b13de68ff8b4819864c7f8/node_modules/preact/dist/preact.module.js","../../browser-common/dist/utils/globals.mjs","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/dompurify/3.4.12/c46b270a205ddd3592d1d50ff54a7626594163d9ec5d767c12b7378ae1d63dc0/node_modules/dompurify/dist/purify.es.mjs","../../core/dist/utils/logger.mjs","../src/posthog-product-tours-types.ts","../src/constants.ts","../../core/dist/utils/type-utils.mjs","../src/extensions/product-tours/element-inference.ts","../../browser-common/dist/utils/logger.mjs","../../browser-common/dist/utils/stylesheet-loader.mjs","../src/utils/survey-utils.ts","../../browser-common/dist/utils/uuidv7.mjs","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/preact/10.29.3/140084fb8a57e97c29fa8a8c859027ef9e32ecc372b13de68ff8b4819864c7f8/node_modules/preact/hooks/dist/hooks.module.js","../src/extensions/surveys/surveys-extension-utils.tsx","../src/extensions/product-tours/product-tours-utils.ts","../src/extensions/surveys/icons.tsx","../src/extensions/product-tours/components/ProductTourBanner.tsx","../src/extensions/product-tours/components/ProductTourSurveyStepInner.tsx","../src/extensions/product-tours/components/ProductTourTooltipInner.tsx","../src/extensions/product-tours/preview.tsx"],"sourcesContent":["var n,l,u,t,i,r,o,e,f,c,a,s,h,p,v,y,d={},w=[],_=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,g=Array.isArray;function m(n,l){for(var u in l)n[u]=l[u];return n}function b(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function k(l,u,t){var i,r,o,e={};for(o in u)\"key\"==o?i=u[o]:\"ref\"==o?r=u[o]:e[o]=u[o];if(arguments.length>2&&(e.children=arguments.length>3?n.call(arguments,2):t),\"function\"==typeof l&&null!=l.defaultProps)for(o in l.defaultProps)void 0===e[o]&&(e[o]=l.defaultProps[o]);return x(l,e,i,r,null)}function x(n,t,i,r,o){var e={type:n,props:t,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==o?++u:o,__i:-1,__u:0};return null==o&&null!=l.vnode&&l.vnode(e),e}function M(){return{current:null}}function S(n){return n.children}function C(n,l){this.props=n,this.context=l}function $(n,l){if(null==l)return n.__?$(n.__,n.__i+1):null;for(var u;l<n.__k.length;l++)if(null!=(u=n.__k[l])&&null!=u.__e)return u.__e;return\"function\"==typeof n.type?$(n):null}function I(n){if(n.__P&&n.__d){var u=n.__v,t=u.__e,i=[],r=[],o=m({},u);o.__v=u.__v+1,l.vnode&&l.vnode(o),q(n.__P,o,u,n.__n,n.__P.namespaceURI,32&u.__u?[t]:null,i,null==t?$(u):t,!!(32&u.__u),r),o.__v=u.__v,o.__.__k[o.__i]=o,D(i,o,r),u.__e=u.__=null,o.__e!=t&&P(o)}}function P(n){if(null!=(n=n.__)&&null!=n.__c)return n.__e=n.__c.base=null,n.__k.some(function(l){if(null!=l&&null!=l.__e)return n.__e=n.__c.base=l.__e}),P(n)}function A(n){(!n.__d&&(n.__d=!0)&&i.push(n)&&!H.__r++||r!=l.debounceRendering)&&((r=l.debounceRendering)||o)(H)}function H(){try{for(var n,l=1;i.length;)i.length>l&&i.sort(e),n=i.shift(),l=i.length,I(n)}finally{i.length=H.__r=0}}function L(n,l,u,t,i,r,o,e,f,c,a){var s,h,p,v,y,_,g,m=t&&t.__k||w,b=l.length;for(f=T(u,l,m,f,b),s=0;s<b;s++)null!=(p=u.__k[s])&&(h=-1!=p.__i&&m[p.__i]||d,p.__i=s,_=q(n,p,h,i,r,o,e,f,c,a),v=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&J(h.ref,null,p),a.push(p.ref,p.__c||v,p)),null==y&&null!=v&&(y=v),(g=!!(4&p.__u))||h.__k===p.__k?(f=j(p,f,n,g),g&&h.__e&&(h.__e=null)):\"function\"==typeof p.type&&void 0!==_?f=_:v&&(f=v.nextSibling),p.__u&=-7);return u.__e=y,f}function T(n,l,u,t,i){var r,o,e,f,c,a=u.length,s=a,h=0;for(n.__k=new Array(i),r=0;r<i;r++)null!=(o=l[r])&&\"boolean\"!=typeof o&&\"function\"!=typeof o?(\"string\"==typeof o||\"number\"==typeof o||\"bigint\"==typeof o||o.constructor==String?o=n.__k[r]=x(null,o,null,null,null):g(o)?o=n.__k[r]=x(S,{children:o},null,null,null):void 0===o.constructor&&o.__b>0?o=n.__k[r]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):n.__k[r]=o,f=r+h,o.__=n,o.__b=n.__b+1,e=null,-1!=(c=o.__i=O(o,u,f,s))&&(s--,(e=u[c])&&(e.__u|=2)),null==e||null==e.__v?(-1==c&&(i>a?h--:i<a&&h++),\"function\"!=typeof o.type&&(o.__u|=4)):c!=f&&(c==f-1?h--:c==f+1?h++:(c>f?h--:h++,o.__u|=4))):n.__k[r]=null;if(s)for(r=0;r<a;r++)null!=(e=u[r])&&0==(2&e.__u)&&(e.__e==t&&(t=$(e)),K(e,e));return t}function j(n,l,u,t){var i,r;if(\"function\"==typeof n.type){for(i=n.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=n,l=j(i[r],l,u,t));return l}n.__e!=l&&(t&&(l&&n.type&&!l.parentNode&&(l=$(n)),u.insertBefore(n.__e,l||null)),l=n.__e);do{l=l&&l.nextSibling}while(null!=l&&8==l.nodeType);return l}function F(n,l){return l=l||[],null==n||\"boolean\"==typeof n||(g(n)?n.some(function(n){F(n,l)}):l.push(n)),l}function O(n,l,u,t){var i,r,o,e=n.key,f=n.type,c=l[u],a=null!=c&&0==(2&c.__u);if(null===c&&null==e||a&&e==c.key&&f==c.type)return u;if(t>(a?1:0))for(i=u-1,r=u+1;i>=0||r<l.length;)if(null!=(c=l[o=i>=0?i--:r++])&&0==(2&c.__u)&&e==c.key&&f==c.type)return o;return-1}function z(n,l,u){\"-\"==l[0]?n.setProperty(l,null==u?\"\":u):n[l]=null==u?\"\":\"number\"!=typeof u||_.test(l)?u:u+\"px\"}function N(n,l,u,t,i){var r,o;n:if(\"style\"==l)if(\"string\"==typeof u)n.style.cssText=u;else{if(\"string\"==typeof t&&(n.style.cssText=t=\"\"),t)for(l in t)u&&l in u||z(n.style,l,\"\");if(u)for(l in u)t&&u[l]==t[l]||z(n.style,l,u[l])}else if(\"o\"==l[0]&&\"n\"==l[1])r=l!=(l=l.replace(s,\"$1\")),o=l.toLowerCase(),l=o in n||\"onFocusOut\"==l||\"onFocusIn\"==l?o.slice(2):l.slice(2),n.l||(n.l={}),n.l[l+r]=u,u?t?u[a]=t[a]:(u[a]=h,n.addEventListener(l,r?v:p,r)):n.removeEventListener(l,r?v:p,r);else{if(\"http://www.w3.org/2000/svg\"==i)l=l.replace(/xlink(H|:h)/,\"h\").replace(/sName$/,\"s\");else if(\"width\"!=l&&\"height\"!=l&&\"href\"!=l&&\"list\"!=l&&\"form\"!=l&&\"tabIndex\"!=l&&\"download\"!=l&&\"rowSpan\"!=l&&\"colSpan\"!=l&&\"role\"!=l&&\"popover\"!=l&&l in n)try{n[l]=null==u?\"\":u;break n}catch(n){}\"function\"==typeof u||(null==u||!1===u&&\"-\"!=l[4]?n.removeAttribute(l):n.setAttribute(l,\"popover\"==l&&1==u?\"\":u))}}function V(n){return function(u){if(this.l){var t=this.l[u.type+n];if(null==u[c])u[c]=h++;else if(u[c]<t[a])return;return t(l.event?l.event(u):u)}}}function q(n,u,t,i,r,o,e,f,c,a){var s,h,p,v,y,d,_,k,x,M,$,I,P,A,H,T,j=u.type;if(void 0!==u.constructor)return null;128&t.__u&&(c=!!(32&t.__u),o=[f=u.__e=t.__e]),(s=l.__b)&&s(u);n:if(\"function\"==typeof j){h=e.length;try{if(x=u.props,M=j.prototype&&j.prototype.render,$=(s=j.contextType)&&i[s.__c],I=s?$?$.props.value:s.__:i,t.__c?k=(p=u.__c=t.__c).__=p.__E:(M?u.__c=p=new j(x,I):(u.__c=p=new C(x,I),p.constructor=j,p.render=Q),$&&$.sub(p),p.state||(p.state={}),p.__n=i,v=p.__d=!0,p.__h=[],p._sb=[]),M&&null==p.__s&&(p.__s=p.state),M&&null!=j.getDerivedStateFromProps&&(p.__s==p.state&&(p.__s=m({},p.__s)),m(p.__s,j.getDerivedStateFromProps(x,p.__s))),y=p.props,d=p.state,p.__v=u,v)M&&null==j.getDerivedStateFromProps&&null!=p.componentWillMount&&p.componentWillMount(),M&&null!=p.componentDidMount&&p.__h.push(p.componentDidMount);else{if(M&&null==j.getDerivedStateFromProps&&x!==y&&null!=p.componentWillReceiveProps&&p.componentWillReceiveProps(x,I),u.__v==t.__v||!p.__e&&null!=p.shouldComponentUpdate&&!1===p.shouldComponentUpdate(x,p.__s,I)){u.__v!=t.__v&&(p.props=x,p.state=p.__s,p.__d=!1),u.__e=t.__e,u.__k=t.__k,u.__k.some(function(n){n&&(n.__=u)}),w.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&e.push(p);break n}null!=p.componentWillUpdate&&p.componentWillUpdate(x,p.__s,I),M&&null!=p.componentDidUpdate&&p.__h.push(function(){p.componentDidUpdate(y,d,_)})}if(p.context=I,p.props=x,p.__P=n,p.__e=!1,P=l.__r,A=0,M)p.state=p.__s,p.__d=!1,P&&P(u),s=p.render(p.props,p.state,p.context),w.push.apply(p.__h,p._sb),p._sb=[];else do{p.__d=!1,P&&P(u),s=p.render(p.props,p.state,p.context),p.state=p.__s}while(p.__d&&++A<25);p.state=p.__s,null!=p.getChildContext&&(i=m(m({},i),p.getChildContext())),M&&!v&&null!=p.getSnapshotBeforeUpdate&&(_=p.getSnapshotBeforeUpdate(y,d)),H=null!=s&&s.type===S&&null==s.key?E(s.props.children):s,f=L(n,g(H)?H:[H],u,t,i,r,o,e,f,c,a),p.base=u.__e,u.__u&=-161,p.__h.length&&e.push(p),k&&(p.__E=p.__=null)}catch(n){if(e.length=h,u.__v=null,c||null!=o)if(n.then){for(u.__u|=c?160:128;f&&8==f.nodeType&&f.nextSibling;)f=f.nextSibling;null!=o&&(o[o.indexOf(f)]=null),u.__e=f}else{if(null!=o)for(T=o.length;T--;)b(o[T]);B(u)}else u.__e=t.__e,!u.__k&&t.__k&&(u.__k=t.__k),n.then||B(u);l.__e(n,u,t)}}else null==o&&u.__v==t.__v?(u.__k=t.__k,u.__e=t.__e):f=u.__e=G(t.__e,u,t,i,r,o,e,c,a);return(s=l.diffed)&&s(u),128&u.__u?void 0:f}function B(n){n&&(n.__c&&(n.__c.__e=!0),n.__k&&n.__k.some(B))}function D(n,u,t){for(var i=0;i<t.length;i++)J(t[i],t[++i],t[++i]);l.__c&&l.__c(u,n),n.some(function(u){try{n=u.__h,u.__h=[],n.some(function(n){n.call(u)})}catch(n){l.__e(n,u.__v)}})}function E(n){return\"object\"!=typeof n||null==n||n.__b>0?n:g(n)?n.map(E):void 0!==n.constructor?null:m({},n)}function G(u,t,i,r,o,e,f,c,a){var s,h,p,v,y,w,_,m=i.props||d,k=t.props,x=t.type;if(\"svg\"==x?o=\"http://www.w3.org/2000/svg\":\"math\"==x?o=\"http://www.w3.org/1998/Math/MathML\":o||(o=\"http://www.w3.org/1999/xhtml\"),null!=e)for(s=0;s<e.length;s++)if((y=e[s])&&\"setAttribute\"in y==!!x&&(x?y.localName==x:3==y.nodeType)){u=y,e[s]=null;break}if(null==u){if(null==x)return document.createTextNode(k);u=document.createElementNS(o,x,k.is&&k),c&&(l.__m&&l.__m(t,e),c=!1),e=null}if(null==x)m===k||c&&u.data==k||(u.data=k);else{if(e=\"textarea\"==x&&null!=k.defaultValue?null:e&&n.call(u.childNodes),!c&&null!=e)for(m={},s=0;s<u.attributes.length;s++)m[(y=u.attributes[s]).name]=y.value;for(s in m)y=m[s],\"dangerouslySetInnerHTML\"==s?p=y:\"children\"==s||s in k||\"value\"==s&&\"defaultValue\"in k||\"checked\"==s&&\"defaultChecked\"in k||N(u,s,null,y,o);for(s in k)y=k[s],\"children\"==s?v=y:\"dangerouslySetInnerHTML\"==s?h=y:\"value\"==s?w=y:\"checked\"==s?_=y:c&&\"function\"!=typeof y||m[s]===y||N(u,s,y,m[s],o);if(h)c||p&&(h.__html==p.__html||h.__html==u.innerHTML)||(u.innerHTML=h.__html),t.__k=[];else if(p&&(u.innerHTML=\"\"),L(\"template\"==t.type?u.content:u,g(v)?v:[v],t,i,r,\"foreignObject\"==x?\"http://www.w3.org/1999/xhtml\":o,e,f,e?e[0]:i.__k&&$(i,0),c,a),null!=e)for(s=e.length;s--;)b(e[s]);c&&\"textarea\"!=x||(s=\"value\",\"progress\"==x&&null==w?u.removeAttribute(\"value\"):null!=w&&(w!==u[s]||\"progress\"==x&&!w||\"option\"==x&&w!=m[s])&&N(u,s,w,m[s],o),s=\"checked\",null!=_&&_!=u[s]&&N(u,s,_,m[s],o))}return u}function J(n,u,t){try{if(\"function\"==typeof n){var i=\"function\"==typeof n.__u;i&&n.__u(),i&&null==u||(n.__u=n(u))}else n.current=u}catch(n){l.__e(n,t)}}function K(n,u,t){var i,r;if(l.unmount&&l.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||J(i,null,u)),null!=(i=n.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(n){l.__e(n,u)}i.base=i.__P=i.__n=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&K(i[r],u,t||\"function\"!=typeof n.type);t||b(n.__e),n.__c=n.__=n.__e=void 0}function Q(n,l,u){return this.constructor(n,u)}function R(u,t,i){var r,o,e,f;t==document&&(t=document.documentElement),l.__&&l.__(u,t),o=(r=\"function\"==typeof i)?null:i&&i.__k||t.__k,e=[],f=[],q(t,u=(!r&&i||t).__k=k(S,null,[u]),o||d,d,t.namespaceURI,!r&&i?[i]:o?null:t.firstChild?n.call(t.childNodes):null,e,!r&&i?i:o?o.__e:t.firstChild,r,f),D(e,u,f),u.props.children=null}function U(n,l){R(n,l,U)}function W(l,u,t){var i,r,o,e,f=m({},l.props);for(o in l.type&&l.type.defaultProps&&(e=l.type.defaultProps),u)\"key\"==o?i=u[o]:\"ref\"==o?r=u[o]:f[o]=void 0===u[o]&&null!=e?e[o]:u[o];return arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):t),x(l.type,f,i||l.key,r||l.ref,null)}function X(n){function l(n){var u,t;return this.getChildContext||(u=new Set,(t={})[l.__c]=this,this.getChildContext=function(){return t},this.componentWillUnmount=function(){u=null},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&u.forEach(function(n){n.__e=!0,A(n)})},this.sub=function(n){u.add(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u&&u.delete(n),l&&l.call(n)}}),n.children}return l.__c=\"__cC\"+y++,l.__=n,l.Provider=l.__l=(l.Consumer=function(n,l){return n.children(l)}).contextType=l,l}n=w.slice,l={__e:function(n,l,u,t){for(var i,r,o;l=l.__;)if((i=l.__c)&&!i.__)try{if((r=i.constructor)&&null!=r.getDerivedStateFromError&&(i.setState(r.getDerivedStateFromError(n)),o=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(n,t||{}),o=i.__d),o)return i.__E=i}catch(l){n=l}throw n}},u=0,t=function(n){return null!=n&&void 0===n.constructor},C.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=m({},this.state),\"function\"==typeof n&&(n=n(m({},u),this.props)),n&&m(u,n),null!=n&&this.__v&&(l&&this._sb.push(l),A(this))},C.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),A(this))},C.prototype.render=S,i=[],o=\"function\"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,e=function(n,l){return n.__v.__b-l.__v.__b},H.__r=0,f=Math.random().toString(8),c=\"__d\"+f,a=\"__a\"+f,s=/(PointerCapture)$|Capture$/i,h=0,p=V(!1),v=V(!0),y=0;export{C as Component,S as Fragment,W as cloneElement,X as createContext,k as createElement,M as createRef,k as h,U as hydrate,t as isValidElement,l as options,R as render,F as toChildArray};\n//# sourceMappingURL=preact.module.js.map\n","const win = 'undefined' != typeof window ? window : void 0;\nconst global = 'undefined' != typeof globalThis ? globalThis : win;\nconst globals_navigator = global?.navigator;\nconst globals_document = global?.document;\nconst globals_location = global?.location;\nconst fetch = global?.fetch;\nconst XMLHttpRequest = global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : void 0;\nconst AbortController = global?.AbortController;\nconst CompressionStream = global?.CompressionStream;\nconst userAgent = globals_navigator?.userAgent;\nfunction isBrowserOnline() {\n return !!(win && false !== win.navigator.onLine);\n}\nexport { AbortController, CompressionStream, XMLHttpRequest, globals_document as document, fetch, isBrowserOnline, globals_location as location, globals_navigator as navigator, userAgent, win as window };\n","/*! @license DOMPurify 3.4.12 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.12/LICENSE */\n\nfunction _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nfunction _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nfunction _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = true,\n o = false;\n try {\n if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = true, n = r;\n } finally {\n try {\n if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _slicedToArray(r, e) {\n return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();\n}\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n }\n}\n\nconst entries = Object.entries,\n setPrototypeOf = Object.setPrototypeOf,\n isFrozen = Object.isFrozen,\n getPrototypeOf = Object.getPrototypeOf,\n getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nlet freeze = Object.freeze,\n seal = Object.seal,\n create = Object.create; // eslint-disable-line import/no-mutable-exports\nlet _ref = typeof Reflect !== 'undefined' && Reflect,\n apply = _ref.apply,\n construct = _ref.construct;\nif (!freeze) {\n freeze = function freeze(x) {\n return x;\n };\n}\nif (!seal) {\n seal = function seal(x) {\n return x;\n };\n}\nif (!apply) {\n apply = function apply(func, thisArg) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n return func.apply(thisArg, args);\n };\n}\nif (!construct) {\n construct = function construct(Func) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n return new Func(...args);\n };\n}\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySplice = unapply(Array.prototype.splice);\nconst arrayIsArray = Array.isArray;\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\nconst numberToString = unapply(Number.prototype.toString);\nconst booleanToString = unapply(Boolean.prototype.toString);\nconst bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);\nconst symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst objectToString = unapply(Object.prototype.toString);\nconst regExpTest = unapply(RegExp.prototype.test);\nconst typeErrorCreate = unconstruct(TypeError);\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply(func) {\n return function (thisArg) {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n args[_key3 - 1] = arguments[_key3];\n }\n return apply(func, thisArg, args);\n };\n}\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct(Func) {\n return function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n return construct(Func, args);\n };\n}\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(set, array) {\n let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n if (!arrayIsArray(array)) {\n return set;\n }\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n array[l] = lcElement;\n }\n element = lcElement;\n }\n }\n set[element] = true;\n }\n return set;\n}\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray(array) {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n return array;\n}\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone(object) {\n const newObject = create(null);\n for (const _ref2 of entries(object)) {\n var _ref3 = _slicedToArray(_ref2, 2);\n const property = _ref3[0];\n const value = _ref3[1];\n const isPropertyExist = objectHasOwnProperty(object, property);\n if (isPropertyExist) {\n if (arrayIsArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (value && typeof value === 'object' && value.constructor === Object) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n return newObject;\n}\n/**\n * Convert non-node values into strings without depending on direct property access.\n *\n * @param value - The value to stringify.\n * @returns A string representation of the provided value.\n */\nfunction stringifyValue(value) {\n switch (typeof value) {\n case 'string':\n {\n return value;\n }\n case 'number':\n {\n return numberToString(value);\n }\n case 'boolean':\n {\n return booleanToString(value);\n }\n case 'bigint':\n {\n return bigintToString ? bigintToString(value) : '0';\n }\n case 'symbol':\n {\n return symbolToString ? symbolToString(value) : 'Symbol()';\n }\n case 'undefined':\n {\n return objectToString(value);\n }\n case 'function':\n case 'object':\n {\n if (value === null) {\n return objectToString(value);\n }\n const valueAsRecord = value;\n const valueToString = lookupGetter(valueAsRecord, 'toString');\n if (typeof valueToString === 'function') {\n const stringified = valueToString(valueAsRecord);\n return typeof stringified === 'string' ? stringified : objectToString(stringified);\n }\n return objectToString(value);\n }\n default:\n {\n return objectToString(value);\n }\n }\n}\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter(object, prop) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n object = getPrototypeOf(object);\n }\n function fallbackValue() {\n return null;\n }\n return fallbackValue;\n}\nfunction isRegex(value) {\n try {\n regExpTest(value, '');\n return true;\n } catch (_unused) {\n return false;\n }\n}\n\nconst html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);\nconst svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);\nconst svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nconst svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);\nconst mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nconst mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);\nconst text = freeze(['#text']);\n\nconst html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);\nconst svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dominant-baseline', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-orientation', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);\nconst mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);\nconst xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);\n\nconst MUSTACHE_EXPR = seal(/{{[\\w\\W]*|^[\\w\\W]*}}/g);\nconst ERB_EXPR = seal(/<%[\\w\\W]*|^[\\w\\W]*%>/g);\nconst TMPLIT_EXPR = seal(/\\${[\\w\\W]*/g);\nconst DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nconst ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nconst IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nconst IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nconst ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nconst DOCTYPE_NAME = seal(/^html$/i);\nconst CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n// Markup-significant character probes used by _sanitizeElements.\n// Shared module-level instances are safe despite the sticky /g flags:\n// unapply() resets lastIndex for RegExp receivers before every call.\nconst ELEMENT_MARKUP_PROBE = seal(/<[/\\w!]/g);\nconst COMMENT_MARKUP_PROBE = seal(/<[/\\w]/g);\nconst FALLBACK_TAG_CLOSE = seal(/<\\/no(script|embed|frames)/i);\nconst SELF_CLOSING_TAG = seal(/\\/>/i);\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5,\n // Deprecated\n entityNode: 6,\n // Deprecated\n processingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12 // Deprecated\n};\nconst getGlobal = function getGlobal() {\n return typeof window === 'undefined' ? null : window;\n};\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {\n if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {\n return null;\n }\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n }\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn('TrustedTypes policy ' + policyName + ' could not be created.');\n return null;\n }\n};\nconst _createHooksMap = function _createHooksMap() {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: []\n };\n};\n/**\n * Resolve a set-valued configuration option: a fresh set built from\n * cfg[key] when it is an own array property (seeded with a clone of\n * options.base when given, case-normalized via options.transform),\n * the fallback set otherwise.\n *\n * @param cfg the cloned, prototype-free configuration object\n * @param key the configuration property to read\n * @param fallback the set to use when the option is absent or not an array\n * @param options transform and optional base set to merge into\n * @returns the resolved set\n */\nconst _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {\n return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;\n};\nfunction createDOMPurify() {\n let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();\n const DOMPurify = root => createDOMPurify(root);\n DOMPurify.version = '3.4.12';\n DOMPurify.removed = [];\n if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n return DOMPurify;\n }\n let document = window.document;\n const originalDocument = document;\n const currentScript = originalDocument.currentScript;\n window.DocumentFragment;\n const HTMLTemplateElement = window.HTMLTemplateElement,\n Node = window.Node,\n Element = window.Element,\n NodeFilter = window.NodeFilter,\n _window$NamedNodeMap = window.NamedNodeMap;\n _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;\n window.HTMLFormElement;\n const DOMParser = window.DOMParser,\n trustedTypes = window.trustedTypes;\n const ElementPrototype = Element.prototype;\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');\n const getAttributes = lookupGetter(ElementPrototype, 'attributes');\n const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;\n const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n let trustedTypesPolicy;\n let emptyHTML = '';\n // The instance's own internal Trusted Types policy. Unlike a caller-supplied\n // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws\n // on duplicate policy names — and is the only policy allowed to persist\n // across configurations and survive `clearConfig()`.\n let defaultTrustedTypesPolicy;\n let defaultTrustedTypesPolicyResolved = false;\n // Tracks whether we are already inside a call to the configured Trusted Types\n // policy (`createHTML` or `createScriptURL`). If a supplied policy callback\n // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would\n // re-enter the policy and recurse until the stack overflows. We detect that\n // re-entry and throw a clear, actionable error instead. The guard is shared\n // across both callbacks, because either one re-entering `sanitize` triggers\n // the same unbounded recursion.\n let IN_TRUSTED_TYPES_POLICY = 0;\n const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {\n if (IN_TRUSTED_TYPES_POLICY > 0) {\n throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or ' + 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' + 'infinite recursion. Do not pass a policy whose callbacks wrap ' + 'DOMPurify as TRUSTED_TYPES_POLICY; see the \"DOMPurify and Trusted ' + 'Types\" section of the README.');\n }\n };\n const _createTrustedHTML = function _createTrustedHTML(html) {\n _assertNotInTrustedTypesPolicy();\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createHTML(html);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {\n _assertNotInTrustedTypesPolicy();\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createScriptURL(scriptUrl);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n // Lazily resolve (and cache) the instance's internal default policy.\n // Resolution is attempted at most once: a successful `createPolicy` cannot be\n // repeated (Trusted Types throws on duplicate names), and a failed or\n // unsupported attempt must not be retried on every parse.\n const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {\n if (!defaultTrustedTypesPolicyResolved) {\n defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);\n defaultTrustedTypesPolicyResolved = true;\n }\n return defaultTrustedTypesPolicy;\n };\n const _document = document,\n implementation = _document.implementation,\n createNodeIterator = _document.createNodeIterator,\n createDocumentFragment = _document.createDocumentFragment,\n getElementsByTagName = _document.getElementsByTagName;\n const importNode = originalDocument.importNode;\n let hooks = _createHooksMap();\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;\n const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,\n ERB_EXPR$1 = ERB_EXPR,\n TMPLIT_EXPR$1 = TMPLIT_EXPR,\n DATA_ATTR$1 = DATA_ATTR,\n ARIA_ATTR$1 = ARIA_ATTR,\n IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE$1 = ATTR_WHITESPACE,\n CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;\n let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false\n }\n }));\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {\n tagCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n }\n }));\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n /* Decide if document with <html>... should be returned */\n let WHOLE_DOCUMENT = false;\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n /* Pristine allowlist bindings captured at setConfig() time. On the\n * persistent-config path sanitize() restores the sets from these before\n * the per-walk hook clone-guard, so a hook's in-call widening cannot\n * carry across calls. Null until setConfig() is called; reset by\n * clearConfig(). */\n let SET_CONFIG_ALLOWED_TAGS = null;\n let SET_CONFIG_ALLOWED_ATTR = null;\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES = {};\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',\n // <selectedcontent> mirrors the selected <option>'s subtree, cloned by\n // the UA (customizable <select>) — including any on* handlers — and the\n // engine re-mirrors synchronously whenever a removal changes which\n // option/selectedcontent is current, even inside DOMPurify's inert\n // DOMParser document. Hoisting its children on removal re-inserts a fresh\n // mirror target ahead of the walk, which the engine refills, looping\n // forever (DoS) and amplifying output. Dropping its content on removal\n // (rather than hoisting) breaks that cascade; the content is a duplicate\n // of the option, which is sanitized on its own. See campaign-3 F1/F6.\n 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);\n const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);\n const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);\n let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc = null;\n /* Keep a reference to config to pass to hooks */\n let CONFIG = null;\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n const formElement = document.createElement('form');\n const isRegexOrFunction = function isRegexOrFunction(testValue) {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function _parseConfig() {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;\n /* Set configuration parameters */\n ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {\n transform: transformCaseFunc\n });\n ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {\n transform: transformCaseFunc\n });\n ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {\n transform: stringToString\n });\n URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {\n transform: transformCaseFunc,\n base: DEFAULT_URI_SAFE_ATTRIBUTES\n });\n DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {\n transform: transformCaseFunc,\n base: DEFAULT_DATA_URI_TAGS\n });\n FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {\n transform: transformCaseFunc\n });\n FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {\n transform: transformCaseFunc\n });\n FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {\n transform: transformCaseFunc\n });\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp\n NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace\n MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map\n HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map\n const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);\n CUSTOM_ELEMENT_HANDLING = create(null);\n if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined\n }\n if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined\n }\n if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined\n }\n seal(CUSTOM_ELEMENT_HANDLING);\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, text);\n ALLOWED_ATTR = create(null);\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, html$1);\n addToSet(ALLOWED_ATTR, html);\n }\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, svg$1);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, svgFilters);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, mathMl$1);\n addToSet(ALLOWED_ATTR, mathMl);\n addToSet(ALLOWED_ATTR, xml);\n }\n }\n /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent\n * leaking across calls when switching from function to array config */\n EXTRA_ELEMENT_HANDLING.tagCheck = null;\n EXTRA_ELEMENT_HANDLING.attributeCheck = null;\n /* Merge configuration parameters */\n if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {\n if (typeof cfg.ADD_TAGS === 'function') {\n EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n } else if (arrayIsArray(cfg.ADD_TAGS)) {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n }\n if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {\n if (typeof cfg.ADD_ATTR === 'function') {\n EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n } else if (arrayIsArray(cfg.ADD_ATTR)) {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n }\n if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);\n }\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n // Re-derive the active Trusted Types policy from this configuration on\n // every parse. The active policy must never be sticky closure state that\n // outlives the config that set it: a caller-supplied policy left in place\n // after `clearConfig()` — or after a later call that supplied none, or\n // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent \"default\"\n // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.\n // See GHSA-vxr8-fq34-vvx9.\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.');\n }\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.');\n }\n // A caller-supplied policy applies to this configuration only.\n const previousTrustedTypesPolicy = trustedTypesPolicy;\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n // Sign local variables required by `sanitize`. If the supplied policy's\n // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this\n // throws via the re-entrancy guard. Restore the previous policy first so\n // the instance is not left in a poisoned state. See #1422.\n try {\n emptyHTML = _createTrustedHTML('');\n } catch (error) {\n trustedTypesPolicy = previousTrustedTypesPolicy;\n throw error;\n }\n } else if (cfg.TRUSTED_TYPES_POLICY === null) {\n // Explicit opt-out for this call: perform no Trusted Types signing and\n // create nothing (so a strict `trusted-types` CSP that disallows a\n // `dompurify` policy can still call `sanitize` from inside its own\n // policy — see #1422). Resetting to `undefined` rather than a sticky\n // `null` also drops any previously retained caller policy, so it cannot\n // resurface on a later call, while still allowing the next config-less\n // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = undefined;\n emptyHTML = '';\n } else {\n // No policy supplied: keep the currently active policy if one is set — a\n // previously supplied policy is intentionally sticky across config-less\n // calls — otherwise fall back to the instance's own internal policy,\n // created at most once. (A policy supplied for a *single* call still\n // lingers by design; what must not linger is a policy whose configuration\n // has been torn down via `clearConfig()`, which restores the default.)\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _getDefaultTrustedTypesPolicy();\n }\n // Sign internal variables only when a policy is active. A falsy policy\n // (Trusted Types unsupported, creation failed, or an explicit opt-out)\n // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on\n // a non-policy and throw. See #1422.\n if (trustedTypesPolicy && typeof emptyHTML === 'string') {\n emptyHTML = _createTrustedHTML('');\n }\n }\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n CONFIG = cfg;\n };\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);\n const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);\n /**\n * Namespace rules for an element in the SVG namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {\n // The only way to switch from HTML namespace to SVG\n // is via <svg>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n // The only way to switch from MathML to SVG is via <svg>\n // if the parent is either <annotation-xml> or a MathML\n // text integration point.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);\n }\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n };\n /**\n * Namespace rules for an element in the MathML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {\n // The only way to switch from HTML namespace to MathML\n // is via <math>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n // The only way to switch from SVG to MathML is via\n // <math> and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n };\n /**\n * Namespace rules for an element in the HTML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);\n };\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function _checkValidNamespace(element) {\n let parent = getParentNode(element);\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template'\n };\n }\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n if (element.namespaceURI === SVG_NAMESPACE) {\n return _checkSvgNamespace(tagName, parent, parentTagName);\n }\n if (element.namespaceURI === MATHML_NAMESPACE) {\n return _checkMathMlNamespace(tagName, parent, parentTagName);\n }\n if (element.namespaceURI === HTML_NAMESPACE) {\n return _checkHtmlNamespace(tagName, parent, parentTagName);\n }\n // For XHTML and XML documents that support custom namespaces\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {\n return true;\n }\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function _forceRemove(node) {\n arrayPush(DOMPurify.removed, {\n element: node\n });\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n /* The normal detach failed — this is reached for a parentless node\n (getParentNode() is null, so .removeChild throws). Element.prototype\n .remove() is itself a spec no-op on a parentless node, so a recorded\n \"removal\" would otherwise hand the caller back an intact,\n payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or\n the style-with-element-child rule decided to kill). Fail closed by\n throwing — exactly as a clobbered root does at the IN_PLACE entry —\n rather than trying to \"neutralize\" the node via its own methods.\n Neutralizing would mean calling getAttributeNames()/removeAttribute()\n on the node, both of which a <form> root can clobber via a named child\n (and _isClobbered does not even probe getAttributeNames), so the\n neutralize step could itself be silently defeated, leaving the payload\n intact. A throw touches only the cached, clobber-safe remove() and\n getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)\n to every root-kill reason. REPORT-3.\n This lives inside the catch, so it never fires for a normally-removed\n in-tree node: those have a parent, removeChild() succeeds, and the\n catch is not entered. Only a kept (parentless) root reaches here. */\n remove(node);\n if (!getParentNode(node)) {\n throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');\n }\n }\n };\n /**\n * _neutralizeRoot\n *\n * Fail-closed teardown of an in-place root after the sanitize walk aborts\n * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered\n * custom element's reaction detaches a node so `_forceRemove`'s deliberate\n * parentless guard throws, or any other re-entrant engine mutation — would\n * otherwise leave the caller's *live* tree half-sanitized, with everything\n * after the abort point still carrying its handlers. There is no safe way\n * to resume the walk (the tree mutated under us), so we strip the root bare:\n * remove every child and every attribute, then let the caller's catch see\n * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`\n * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).\n *\n * @param root the in-place root to empty\n */\n const _neutralizeRoot = function _neutralizeRoot(root) {\n /* Strip every disallowed attribute (on* handlers included) off the whole\n subtree BEFORE detaching anything. Detaching first would hand back\n handler-bearing originals (e.g. an already-loading `<img onerror>`)\n whose queued resource event still fires in page scope after we throw.\n Clobber-safe reads; a doomed clobbered node's own attributes are\n irrelevant while its non-clobbered descendants are reached and scrubbed. */\n _neutralizeSubtree(root);\n const childNodes = getChildNodes(root);\n if (childNodes) {\n const snapshot = [];\n arrayForEach(childNodes, child => {\n arrayPush(snapshot, child);\n });\n arrayForEach(snapshot, child => {\n try {\n remove(child);\n } catch (_) {\n /* Best-effort teardown; a still-attached child is handled below */\n }\n });\n }\n const attributes = getAttributes(root);\n if (attributes) {\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name === 'string') {\n try {\n root.removeAttribute(name);\n } catch (_) {\n /* Clobbered removeAttribute — ignore (fail-closed best effort) */\n }\n }\n }\n }\n };\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function _removeAttribute(name, element) {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element\n });\n }\n element.removeAttribute(name);\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n /**\n * _stripDisallowedAttributes\n *\n * Removes every attribute the active configuration does not allow from a\n * single element, using the same allowlist as the main attribute pass (so\n * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to\n * neutralise nodes that are being discarded from an in-place tree.\n *\n * @param element the element to strip\n */\n const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {\n const attributes = getAttributes(element);\n if (!attributes) {\n return;\n }\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {\n continue;\n }\n try {\n element.removeAttribute(name);\n } catch (_) {\n /* Clobbered removeAttribute on a doomed node — ignore */\n }\n }\n };\n /**\n * _neutralizeSubtree\n *\n * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT\n * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,\n * namespace, comment, processing-instruction and KEEP_CONTENT:false removals\n * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path\n * those dropped nodes are detached from the caller's LIVE tree but a\n * handler-bearing original among them (an `<img onerror>`/`<video>` that was\n * loading) keeps its queued resource event, which fires in page scope after\n * sanitize returns. This walks a removed subtree and strips every attribute\n * the active configuration does not allow — so `on*` handlers are cancelled\n * through the SAME allowlist that governs kept nodes, not a separate `/^on/`\n * blocklist. Run synchronously before sanitize returns, i.e. before any\n * queued event can fire. Hook-free by design: these nodes leave the output,\n * so firing attribute hooks for them would be surprising. Clobber-safe reads;\n * a doomed clobbered node may shadow `removeAttribute` (its own attributes are\n * irrelevant — it is discarded — while its non-clobbered descendants, e.g.\n * the `<img>`, are reached and scrubbed).\n *\n * @param root the root of a removed subtree to neutralise\n */\n const _neutralizeSubtree = function _neutralizeSubtree(root) {\n const stack = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n if (nodeType === NODE_TYPE.element) {\n _stripDisallowedAttributes(node);\n }\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push(childNodes[i]);\n }\n }\n }\n };\n /**\n * _neutralizePatchLinkage\n *\n * IN_PLACE entry pre-pass (declarative-partial-updates / streaming\n * hardening, https://github.com/WICG/declarative-partial-updates).\n *\n * The main walk strips patch linkage (`for`/`patchsrc`) and removes range\n * markers (PIs / markup comments) node-by-node, in document order, AS it\n * reaches each node. On a live in-place root that leaves a window: from the\n * moment the root is connected until the walk arrives at a given node, that\n * node's linkage is live. A patch applied on connection/stream can fire as\n * a microtask during the walk and inject or teleport an unsanitized DOM\n * range into a region the iterator has already passed and will not revisit,\n * so the post-return \"tree is sanitized\" contract is violated. Sweep the\n * whole tree once up front and sever every linkage before the walk begins,\n * closing that window.\n *\n * This CANNOT undo a patch that already fired before sanitize ran — that is\n * the irreducible \"do not IN_PLACE a live-connected attacker tree\" caveat —\n * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML\n * to group with the rest of the declarative-partial-updates handling and\n * stay overridable, consistent with the codebase.\n *\n * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a\n * clobbered root cannot defeat the sweep of its non-clobbered descendants.\n *\n * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe\n * .html Q1): this mirrors the existing policy of keeping `for` on\n * <label>/<output>. If the shipping feature can drive a patch through a\n * surviving `for`-on-label/output + `id` pair, this pre-pass and the\n * attribute check at _isBasicCustomElement's caller must additionally drop\n * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.\n *\n * @param root the in-place root to sweep\n */\n const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {\n if (!SAFE_FOR_XML) {\n return;\n }\n const stack = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n /* Remove range markers (the target side of a patch linkage): every\n processing instruction, and any markup-bearing comment. */\n if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {\n try {\n remove(node);\n } catch (_) {\n /* Best-effort */\n }\n continue;\n }\n /* Strip patch-source attributes (the source side) off elements. */\n if (nodeType === NODE_TYPE.element) {\n const element = node;\n const lcTag = transformCaseFunc(getNodeName ? getNodeName(node) : node.nodeName);\n try {\n if (element.hasAttribute && element.hasAttribute('patchsrc')) {\n element.removeAttribute('patchsrc');\n }\n if (element.hasAttribute && element.hasAttribute('for') && lcTag !== 'label' && lcTag !== 'output') {\n element.removeAttribute('for');\n }\n } catch (_) {\n /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */\n }\n }\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push(childNodes[i]);\n }\n }\n }\n };\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function _initDocument(dirty) {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n if (FORCE_BODY) {\n dirty = '<remove></remove>' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty = '<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>' + dirty + '</body></html>';\n }\n const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n const body = doc.body || doc.documentElement;\n if (dirty && leadingWhitespace) {\n body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);\n }\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];\n }\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function _createNodeIterator(root) {\n return createNodeIterator.call(root.ownerDocument || root, root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);\n };\n /**\n * Replace template expression syntax (mustache, ERB, template\n * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub\n * sites. Order matters: mustache, then ERB, then template literal.\n *\n * @param value the string to scrub\n * @returns the scrubbed string\n */\n const _stripTemplateExpressions = function _stripTemplateExpressions(value) {\n value = stringReplace(value, MUSTACHE_EXPR$1, ' ');\n value = stringReplace(value, ERB_EXPR$1, ' ');\n value = stringReplace(value, TMPLIT_EXPR$1, ' ');\n return value;\n };\n /**\n * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the\n * character data of an element subtree. Used as the final safety net for\n * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions\n * which only form after text-node normalization (e.g. fragments split across\n * stripped elements) cannot survive into a template-evaluating framework.\n *\n * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`\n * in place rather than round-tripping through innerHTML. This preserves\n * descendant node references (important for IN_PLACE callers), avoids a\n * serialize/reparse cycle, and reads literal character data — which means\n * `<%...%>` in text content matches the ERB regex against its real bytes\n * instead of the HTML-entity-escaped form innerHTML would produce.\n *\n * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for\n * attributes is performed during the per-node `_sanitizeAttributes` pass.\n *\n * @param node The root element whose character data should be scrubbed.\n */\n const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {\n var _node$querySelectorAl;\n node.normalize();\n const walker = createNodeIterator.call(node.ownerDocument || node, node,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);\n let currentNode = walker.nextNode();\n while (currentNode) {\n currentNode.data = _stripTemplateExpressions(currentNode.data);\n currentNode = walker.nextNode();\n }\n // NodeIterator does not descend into <template>.content per the DOM spec,\n // so we must explicitly recurse into each template's content fragment,\n // mirroring the approach used by _sanitizeShadowDOM.\n const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');\n if (templates) {\n arrayForEach(templates, tmpl => {\n if (_isDocumentFragment(tmpl.content)) {\n _scrubTemplateExpressions2(tmpl.content);\n }\n });\n }\n };\n /**\n * _isClobbered\n *\n * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML\n * interface with [LegacyOverrideBuiltIns]; a descendant element with a\n * `name` attribute matching a prototype property shadows that property\n * on direct reads. We use this check at the IN_PLACE entry-point and\n * during attribute sanitization to refuse clobbered forms.\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function _isClobbered(element) {\n // Realm-independent tag-name probe. If we can't determine the tag\n // name at all, we can't reason about clobbering — return false\n // (the caller's other defences still apply).\n const realTagName = getNodeName ? getNodeName(element) : null;\n if (typeof realTagName !== 'string') {\n return false;\n }\n if (transformCaseFunc(realTagName) !== 'form') {\n return false;\n }\n return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||\n // Realm-safe NamedNodeMap detection: equality against the cached\n // prototype getter. Clobbered .attributes (e.g. <input name=\"attributes\">)\n // makes the direct read diverge from the cached read; a clean form\n // (same-realm OR foreign-realm) has both reads pointing at the same\n // canonical NamedNodeMap.\n element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||\n // NodeType clobbering probe. Cached Node.prototype.nodeType getter\n // returns the integer 1 for any Element regardless of realm; direct\n // read on a clobbered form (e.g. <input name=\"nodeType\">) returns\n // the named child element. Cheap addition — nodeType is read from\n // an internal slot, no serialization cost — and removes a residual\n // clobbering surface used by several mXSS / PI / comment branches\n // in _sanitizeElements that compare currentNode.nodeType directly.\n element.nodeType !== getNodeType(element) ||\n // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named\n // \"childNodes\" shadows the prototype getter. Direct reads of\n // form.childNodes from a clobbered form return the named child\n // instead of the real NodeList, so any walk that reads it directly\n // skips the form's real children. Compare the direct read to the\n // cached Node.prototype getter — when the form's named-property\n // getter intercepts the read, the two values differ and we flag\n // the form. This catches every clobbering child type (input,\n // select, etc.) regardless of whether the named child happens to\n // carry a numeric .length, which a typeof-based probe would miss\n // (e.g. HTMLSelectElement.length is a defined unsigned-long).\n element.childNodes !== getChildNodes(element);\n };\n /**\n * Checks whether the given value is a DocumentFragment from any realm.\n *\n * The realm-independent replacement reads `nodeType` through the cached\n * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE\n * constant (11). nodeType is a numeric value resolved from the node's\n * internal slot, identical across realms for the same kind of node.\n *\n * @param value object to check\n * @return true if value is a DocumentFragment-shaped node from any realm\n */\n const _isDocumentFragment = function _isDocumentFragment(value) {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return getNodeType(value) === NODE_TYPE.documentFragment;\n } catch (_) {\n return false;\n }\n };\n /**\n * Checks whether the given object is a DOM node, including nodes that\n * originate from a different window/realm (e.g. an iframe's\n * contentDocument). The previous `value instanceof Node` check was\n * realm-bound: nodes from a different window failed it, causing\n * sanitize() to silently stringify them and reset IN_PLACE to false,\n * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.\n *\n * @param value object to check whether it's a DOM node\n * @return true if value is a DOM node from any realm\n */\n const _isNode = function _isNode(value) {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof getNodeType(value) === 'number';\n } catch (_) {\n return false;\n }\n };\n function _executeHooks(hooks, currentNode, data) {\n if (hooks.length === 0) {\n return;\n }\n arrayForEach(hooks, hook => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n /**\n * Structural-threat checks that condemn a node regardless of the\n * allowlists: mXSS via namespace confusion, risky CSS construction,\n * processing instructions, markup-bearing comments. Pure predicate;\n * the caller removes. Check order is load-bearing.\n *\n * @param currentNode the node to inspect\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node must be removed\n */\n const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {\n /* Detect mXSS attempts abusing namespace confusion */\n if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {\n return true;\n }\n /* Remove risky CSS construction leading to mXSS */\n if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {\n return true;\n }\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.processingInstruction) {\n return true;\n }\n /* Remove any kind of possibly harmful comments */\n if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {\n return true;\n }\n return false;\n };\n /**\n * Handle a node whose tag is forbidden or not allowlisted: keep\n * allowed custom elements (false return exits _sanitizeElements\n * early - the namespace and fallback-tag removal checks are\n * intentionally skipped for kept custom elements), else hoist\n * content per KEEP_CONTENT and remove.\n *\n * A kept custom element is the ONLY case in which this function\n * returns false, so the caller uses that return value to run the\n * afterSanitizeElements hook on the kept element and keep the\n * element-hook lifecycle consistent with normal allowlisted\n * elements (GHSA-c2j3-45gr-mqc4).\n *\n * @param currentNode the disallowed node\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node was removed, false if kept\n */\n const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {\n return false;\n }\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {\n return false;\n }\n }\n /* Keep content except for bad-listed elements.\n Use the cached prototype getters exclusively — the previous code\n had `|| currentNode.parentNode` / `|| currentNode.childNodes`\n fallbacks, but the cached getters always return the canonical\n value (or null for a real parent-less node), so the fallback\n path was dead in safe cases and a clobbering surface in unsafe\n ones. Falsy cached results stay falsy; the `if (childNodes &&\n parentNode)` check already gates correctly. */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode);\n const childNodes = getChildNodes(currentNode);\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n /* In-place: hoist the *original* children so the iterator visits\n and sanitises them through the same allowlist pass as every other\n node. The caller built the tree in the live document, so the\n originals carry already-queued resource events (`<img onerror>`,\n `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave\n those originals detached but still armed, firing in page scope\n while the returned tree looked clean. Moving is safe in-place: the\n root is pre-validated as an allowed tag and so is never the node\n being removed, which keeps `parentNode` inside the iterator root\n and the relocated child inside the serialised tree.\n Otherwise (string / DOM-copy paths): clone. The iterator is rooted\n at — and the result serialised from — `body`, so a restrictive\n ALLOWED_TAGS that removes `body` itself must leave its content in\n place, which only cloning does; and those paths parse into an\n inert document, so their discarded originals never had a queued\n event to neutralise.\n `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`\n valid whether we move (drops the trailing entry) or clone (leaves\n the list intact). */\n for (let i = childCount - 1; i >= 0; --i) {\n const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);\n parentNode.insertBefore(hoisted, getNextSibling(currentNode));\n }\n }\n }\n _forceRemove(currentNode);\n return true;\n };\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n // eslint-disable-next-line complexity\n const _sanitizeElements = function _sanitizeElements(currentNode, root) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n /* A hook may have detached the node — treat it as removed (see the\n detached-node comment after the uponSanitizeElement hook below). */\n if (currentNode !== root && getParentNode(currentNode) === null) {\n return true;\n }\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS\n });\n /* A hook may have detached the node from the tree — a long-standing\n user pattern (issue #469; draw.io-style foreignObject filtering).\n Per the cached, unclobberable parentNode getter the node is\n genuinely out of the tree, so it can reach neither the serialized\n output nor an IN_PLACE live tree; treat it as removed and stop\n processing it. Without this guard, the unsafe-node / namespace\n checks below would call _forceRemove on a parentless node and hit\n the REPORT-3 fail-closed throw — which exists for nodes DOMPurify\n wants gone but *cannot* detach (clobbered / parentless roots), the\n opposite of a node that is already safely gone. The walk root is\n exempt: a detached IN_PLACE root is legitimate input and must still\n be fully sanitized, and a kill-decision on it must keep hitting the\n REPORT-3 throw. Nodes detached by hooks are the hook's\n responsibility: they are not recorded in DOMPurify.removed and are\n not neutralized by the post-walk IN_PLACE pass. */\n if (currentNode !== root && getParentNode(currentNode) === null) {\n return true;\n }\n /* Remove mXSS vectors, processing instructions and risky comments */\n if (_isUnsafeNode(currentNode, tagName)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove element if anything forbids its presence */\n if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {\n const removed = _sanitizeDisallowedNode(currentNode, tagName);\n /* A false return means the node is a custom element kept via\n CUSTOM_ELEMENT_HANDLING - the only keep path through\n _sanitizeDisallowedNode. Run afterSanitizeElements on it so the\n element-hook lifecycle matches normal allowlisted elements: a\n security policy applied in this hook (e.g. stripping an attribute\n from every surviving element) must not silently skip kept custom\n elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element\n tail below - the hook runs, then the walker's subsequent\n _sanitizeAttributes pass sanitizes the element's attributes. The\n deliberately skipped namespace and fallback-tag removal checks stay\n skipped; they are removal decisions, not the hook contract. */\n if (removed === false) {\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n }\n return removed;\n }\n /* Check whether element has a valid namespace.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype\n nodeType getter rather than `instanceof Element`, which is realm-\n bound and short-circuits to false for any node minted in a different\n realm — letting a foreign-realm element with a forbidden namespace\n slip past the namespace check entirely. */\n const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;\n if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n const content = _stripTemplateExpressions(currentNode.textContent);\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, {\n element: currentNode.cloneNode()\n });\n currentNode.textContent = content;\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n return false;\n };\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {\n /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */\n if (FORBID_ATTR[lcName]) {\n return false;\n }\n /* Reject declarative-partial-updates patch-linkage attributes\n (https://github.com/WICG/declarative-partial-updates).\n Empirical note (Chrome 150, verified — see\n test/declarative-patch-probe-v3.html): expansion is NOT applied after\n sanitization. For the string path it fires during sanitize()'s own\n parse, so the walk sees and sanitizes the fully materialized expanded\n tree — teleports into MathML/SVG integration points included; a\n weaponized `<template for>`->`<img onerror>` comes back with the handler\n stripped. For the IN_PLACE path it fires on connection, before the walk.\n Either way DOMPurify is NOT blind to the patch.\n This removal is therefore defense-in-depth rather than the sole barrier:\n it prevents live linkage from surviving into the OUTPUT and re-expanding\n in the caller's context, and keeps behaviour deterministic if a future\n engine defers expansion. `for` is legitimate only on <label>/<output>;\n anywhere else (notably <template for>) it links the element to a patch\n target and teleports or removes an arbitrary DOM range by id/marker name.\n `patchsrc` fetches remote markup and is treated as a script-loading\n mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the\n other structural-threat checks and stays overridable, consistent with\n the rest of the codebase. PI range markers are already removed by\n _isUnsafeNode. */\n if (SAFE_FOR_XML && lcName === 'patchsrc') {\n return false;\n }\n if (SAFE_FOR_XML && lcName === 'for' && lcTag !== 'label' && lcTag !== 'output') {\n return false;\n }\n /* Make sure attribute cannot clobber */\n if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {\n return false;\n }\n const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {\n return false;\n } else ;\n return true;\n };\n /* Names the HTML spec reserves from valid-custom-element-name; these must\n * never be treated as basic custom elements even when a permissive\n * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */\n const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']);\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function _isBasicCustomElement(tagName) {\n return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);\n };\n /**\n * Wrap an attribute value in the matching Trusted Types object when\n * the active policy requires it. Namespaced attributes pass through\n * unchanged (no TT support yet, see\n * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).\n *\n * @param lcTag lowercase tag name of the containing element\n * @param lcName lowercase attribute name\n * @param namespaceURI the attribute's namespace, if any\n * @param value the attribute value to wrap\n * @return the value, wrapped when Trusted Types demand it\n */\n const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {\n if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML':\n {\n return _createTrustedHTML(value);\n }\n case 'TrustedScriptURL':\n {\n return _createTrustedScriptURL(value);\n }\n }\n }\n return value;\n };\n /**\n * Write a modified attribute value back onto the element. On\n * success, re-probe for clobbering introduced by the new value and\n * remove the element when found; otherwise pop the removal entry\n * recorded by the earlier _removeAttribute (long-standing pairing\n * with the SANITIZE_NAMED_PROPS path - do not \"fix\" casually). On\n * failure, remove the attribute instead.\n *\n * @param currentNode the element carrying the attribute\n * @param name the attribute name as present on the element\n * @param namespaceURI the attribute's namespace, if any\n * @param value the new attribute value\n */\n const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {\n _removeAttribute(name, currentNode);\n }\n };\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n const attributes = currentNode.attributes;\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined\n };\n let l = attributes.length;\n const lcTag = transformCaseFunc(currentNode.nodeName);\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const name = attr.name,\n namespaceURI = attr.namespaceURI,\n attrValue = attr.value;\n const lcName = transformCaseFunc(name);\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n // Else: already prefixed, leave the attribute alone — the prefix is\n // itself the clobbering protection, and re-applying it is incorrect.\n /* Work around a security issue with comments inside attributes */\n if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Make sure we cannot easily use animated hrefs, even if animations are allowed */\n if (lcName === 'attributename' && stringMatch(value, 'href')) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Did the hooks force-keep the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n value = _stripTemplateExpressions(value);\n }\n /* Is `value` valid for this attribute? */\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Handle attributes that require Trusted Types */\n value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n _setAttributeValue(currentNode, name, namespaceURI, value);\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n while (shadowNode = shadowIterator.nextNode()) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode, fragment);\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n /* Deep shadow DOM detected.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the\n DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we\n recurse into <template>.content from foreign realms too. */\n if (_isDocumentFragment(shadowNode.content)) {\n _sanitizeShadowDOM2(shadowNode.content);\n }\n /* An element iterated here may itself host an attached\n shadow root. The default NodeIterator does not enter shadow\n trees, so a shadow root nested inside template.content was\n previously reached by no walk at all (the pre-pass at\n _sanitizeAttachedShadowRoots descends via childNodes, which\n doesn't enter template.content; the template-content recursion\n above iterates the content but never inspected shadowRoot).\n Walk it explicitly. The nodeType guard avoids reading\n shadowRoot off text / comment / CDATA / PI nodes that the\n iterator also surfaces. */\n const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;\n if (shadowNodeType === NODE_TYPE.element) {\n const innerSr = getShadowRoot(shadowNode);\n if (_isDocumentFragment(innerSr)) {\n _sanitizeAttachedShadowRoots(innerSr);\n _sanitizeShadowDOM2(innerSr);\n }\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n /**\n * _sanitizeAttachedShadowRoots\n *\n * Walks `root` and feeds every attached shadow root we encounter into\n * the existing _sanitizeShadowDOM pipeline. The default node iterator\n * does not descend into shadow trees, so nodes inside an attached\n * shadow root would otherwise be skipped entirely.\n *\n * Two real input paths put attached shadow roots in front of us:\n * 1. IN_PLACE on a DOM node that already has shadow roots attached.\n * 2. DOM-node input where importNode(dirty, true) deep-clones the\n * shadow root because it was created with `clonable: true`.\n *\n * This pass runs once, up front, so the main iteration loop (and the\n * existing _sanitizeShadowDOM template-content recursion) stay\n * untouched — string-input paths are not affected.\n *\n * @param root the subtree root to walk for attached shadow roots\n */\n const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {\n /* Iterative (explicit stack) rather than per-child recursion. DOM APIs\n impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data\n built straight into the DOM — the IN_PLACE surface) deeper than the JS\n call-stack budget would otherwise overflow native recursion here and\n throw at the IN_PLACE entry pre-pass, before a single node is\n sanitized, leaving the caller's live tree untouched (fail-open). See\n campaign-3 F4. A heap stack keeps depth off the call stack.\n Each work item is either a node to descend into, or a deferred\n `_sanitizeShadowDOM` for an already-walked shadow root. The deferred\n form preserves the original post-order discipline: a shadow root's\n nested shadow roots are discovered before the outer shadow is\n sanitized (which may remove hosts). Pushes are in reverse of the\n desired processing order (LIFO): template content, then children, then\n the shadow-sanitize, then the shadow walk — so the order matches the\n previous recursion exactly. */\n const stack = [{\n node: root,\n shadow: null\n }];\n while (stack.length > 0) {\n const item = stack.pop();\n /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */\n if (item.shadow) {\n _sanitizeShadowDOM2(item.shadow);\n continue;\n }\n const node = item.node;\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n const isElement = nodeType === NODE_TYPE.element;\n /* (pushed last → processed first) Children, snapshotted in reverse so\n the first child is processed first. Snapshotting matters because a\n hook may detach siblings mid-walk. */\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push({\n node: childNodes[i],\n shadow: null\n });\n }\n }\n /* (pushed before children → processed after them, matching the old\n \"template content last\" order) When the node is a <template>,\n descend into its content. */\n if (isElement) {\n const rootName = getNodeName ? getNodeName(node) : null;\n if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {\n const content = node.content;\n if (_isDocumentFragment(content)) {\n stack.push({\n node: content,\n shadow: null\n });\n }\n }\n }\n /* Shadow root (processed first): walk its subtree, then sanitise it.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection\n rather than `instanceof DocumentFragment`, which is realm-bound and\n silently skipped foreign-realm shadow roots (e.g.\n iframe.contentDocument attachShadow). */\n if (isElement) {\n const sr = getShadowRoot(node);\n if (_isDocumentFragment(sr)) {\n /* Push the deferred sanitise first so it pops after the shadow\n walk we push next, i.e. nested shadow roots are discovered\n before this one is sanitised. */\n stack.push({\n node: null,\n shadow: sr\n }, {\n node: sr,\n shadow: null\n });\n }\n }\n }\n };\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty) {\n let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '<!-->';\n }\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n dirty = stringifyValue(dirty);\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n }\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n /* Assign config vars */\n if (SET_CONFIG) {\n /* Persistent setConfig() path: _parseConfig is skipped, so the sets are\n * not re-derived per call. Restore them from the pristine bindings\n * captured at setConfig() time so a previous call's hook clone (mutated\n * below) does not carry over. */\n ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;\n ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;\n } else {\n _parseConfig(cfg);\n }\n /* Clone the hook-mutable allowlists before the walk whenever an\n * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS\n * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so\n * a hook that widens them would otherwise mutate the shared set\n * permanently: across later calls and across every element. Cloning per\n * walk keeps documented in-call widening working while scoping it to the\n * call. A single guard for both config paths - the per-call path rebinds\n * the sets in _parseConfig each call, the persistent path restores them\n * from the captured bindings just above - so the two cannot diverge. */\n if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n if (hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n /* Clean up removed elements */\n DOMPurify.removed = [];\n /* Resolve IN_PLACE for this call without mutating persistent config.\n Writing the IN_PLACE closure variable here leaks under setConfig(),\n where _parseConfig is skipped on later calls: a single string call would\n disable in-place mode for every subsequent node call, returning a\n sanitized copy while leaving the caller's node — which in-place callers\n keep using and whose return value they ignore — unsanitized. REPORT-2. */\n const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);\n if (inPlace) {\n /* Declarative-partial-updates / streaming pre-pass: sever every patch\n linkage across the live tree BEFORE the walk, so no patch can fire\n mid-walk and inject into an already-processed region. Runs first, so\n it also covers the forbidden/clobbered roots that throw below. */\n _neutralizePatchLinkage(dirty);\n /* Do some early pre-sanitization to avoid unsafe root nodes.\n Read nodeName through the cached prototype getter — a clobbering\n child named \"nodeName\" on the form root would otherwise shadow\n the property and let this check skip the root-allowlist\n validation entirely. */\n const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;\n if (typeof nn === 'string') {\n const tagName = transformCaseFunc(nn);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n /* Fail closed on a live root: neutralize handlers/children before\n throwing, exactly as the mid-walk abort path does. */\n _neutralizeRoot(dirty);\n throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');\n }\n }\n /* Pre-flight the root through _isClobbered. The iterator-driven\n removal path can not detach a parent-less root: _forceRemove\n falls through to Element.prototype.remove(), which per spec\n is a no-op on a node with no parent. A clobbered root would\n then survive the main loop with its attributes uninspected,\n because _sanitizeAttributes early-returns on _isClobbered. The\n result would be an attacker-controlled form, complete with any\n event-handler attributes the caller passed in, handed back to\n the application unsanitized. Refuse to sanitize such a root\n the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */\n if (_isClobbered(dirty)) {\n /* Fail closed on a live clobbered root before throwing.\n _neutralizeRoot's reads are clobber-safe (cached getters); the\n form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */\n _neutralizeRoot(dirty);\n throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');\n }\n /* Sanitize attached shadow roots before the main iterator runs.\n The iterator does not descend into shadow trees. Same fail-closed\n barrier as the main walk (campaign-3 F2): a custom-element reaction\n inside a shadow root could abort this pre-pass before the walk runs,\n which would otherwise leave the entire live tree unsanitized. */\n try {\n _sanitizeAttachedShadowRoots(dirty);\n } catch (error) {\n _neutralizeRoot(dirty);\n throw error;\n }\n } else if (_isNode(dirty)) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('<!---->');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n /* Clonable shadow roots are deep-cloned by importNode(); sanitize\n them before the main iterator runs, since the iterator does not\n descend into shadow trees. The walk routes every read through a\n cached prototype getter so clobbering descendants on a form root\n cannot hide a shadow host from this pass. */\n _sanitizeAttachedShadowRoots(importedNode);\n } else {\n /* Exit directly if we have nothing to do */\n if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;\n }\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n /* Get node iterator */\n const walkRoot = inPlace ? dirty : body;\n const nodeIterator = _createNodeIterator(walkRoot);\n /* Now start iterating over the created document.\n The walk runs inside an exception barrier (campaign-3 F2): a re-entrant\n engine/custom-element mutation can detach a node mid-walk so\n `_forceRemove`'s parentless guard throws, aborting the loop. Without the\n barrier the caller's in-place tree would be left half-sanitized with the\n unvisited tail still armed. On any throw we fail closed — strip the\n in-place root bare — then rethrow so the existing throw contract is\n preserved. (String/DOM-copy paths never return the partial body, so the\n propagating throw is already fail-closed there.) */\n try {\n while (currentNode = nodeIterator.nextNode()) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode, walkRoot);\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n /* Shadow DOM detected, sanitize it.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection\n instead of instanceof, so foreign-realm <template>.content is\n walked correctly. */\n if (_isDocumentFragment(currentNode.content)) {\n _sanitizeShadowDOM2(currentNode.content);\n }\n }\n } catch (error) {\n if (inPlace) {\n _neutralizeRoot(dirty);\n /* Nodes _forceRemove'd earlier in the aborted walk are already\n detached from the root, so _neutralizeRoot's subtree pass does not\n reach them. Defuse them too, mirroring the success-path loop below. */\n arrayForEach(DOMPurify.removed, entry => {\n if (entry.element) {\n _neutralizeSubtree(entry.element);\n }\n });\n }\n throw error;\n }\n /* If we sanitized `dirty` in-place, return it. */\n if (inPlace) {\n /* Fail-closed completion of the audit-5 F1 fix: every node removed from\n the caller's live tree is detached but may still hold a queued\n resource-event handler that fires in page scope after we return. The\n move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the\n non-allow-listed attributes off every other removed subtree (clobber,\n mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are\n cancelled before any event can fire. Runs synchronously, pre-return. */\n arrayForEach(DOMPurify.removed, entry => {\n if (entry.element) {\n _neutralizeSubtree(entry.element);\n }\n });\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions2(dirty);\n }\n return dirty;\n }\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions2(body);\n }\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n return returnNode;\n }\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n /* Serialize doctype if allowed */\n if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {\n serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\\n' + serializedHTML;\n }\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n serializedHTML = _stripTemplateExpressions(serializedHTML);\n }\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;\n };\n DOMPurify.setConfig = function () {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n _parseConfig(cfg);\n SET_CONFIG = true;\n SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;\n SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;\n };\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n SET_CONFIG_ALLOWED_TAGS = null;\n SET_CONFIG_ALLOWED_ATTR = null;\n // Drop any caller-supplied Trusted Types policy so it cannot poison later\n // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and\n // never recreated — Trusted Types throws on duplicate names) is restored by\n // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = defaultTrustedTypesPolicy;\n emptyHTML = '';\n };\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n DOMPurify.addHook = function (entryPoint, hookFunction) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n /* Reject unknown entry points. Without this, a non-hook key (e.g.\n * '__proto__') indexes off the prototype chain rather than a real\n * hook array, and arrayPush then writes to Object.prototype. Guard\n * with an own-property check against the known hook names. */\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n arrayPush(hooks[entryPoint], hookFunction);\n };\n DOMPurify.removeHook = function (entryPoint, hookFunction) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return undefined;\n }\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n return arrayPop(hooks[entryPoint]);\n };\n DOMPurify.removeHooks = function (entryPoint) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n hooks[entryPoint] = [];\n };\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n return DOMPurify;\n}\nvar purify = createDOMPurify();\n\nexport { purify as default };\n//# sourceMappingURL=purify.es.mjs.map\n","function createConsole(consoleLike = console) {\n const lockedMethods = {\n log: consoleLike.log.bind(consoleLike),\n warn: consoleLike.warn.bind(consoleLike),\n error: consoleLike.error.bind(consoleLike),\n debug: consoleLike.debug.bind(consoleLike)\n };\n return lockedMethods;\n}\nconst _createLogger = (prefix, maybeCall, consoleLike)=>{\n function _log(level, ...args) {\n maybeCall(()=>{\n const consoleMethod = consoleLike[level];\n consoleMethod(prefix, ...args);\n });\n }\n const logger = {\n debug: (...args)=>{\n _log('debug', ...args);\n },\n info: (...args)=>{\n _log('log', ...args);\n },\n warn: (...args)=>{\n _log('warn', ...args);\n },\n error: (...args)=>{\n _log('error', ...args);\n },\n critical: (...args)=>{\n consoleLike['error'](prefix, ...args);\n },\n createLogger: (additionalPrefix)=>_createLogger(`${prefix} ${additionalPrefix}`, maybeCall, consoleLike)\n };\n return logger;\n};\nconst passThrough = (fn)=>fn();\nfunction createLogger(prefix, maybeCall = passThrough) {\n return _createLogger(prefix, maybeCall, createConsole());\n}\nexport { _createLogger, createLogger };\n","import { PropertyMatchType } from './types'\nimport { SurveyActionType, SurveyEventWithFilters } from './posthog-surveys-types'\nimport type { InferredSelector } from './extensions/product-tours/element-inference'\nimport { SurveyPosition } from '@posthog/core'\nimport { Z_INDEX_TOURS } from './constants'\n\nexport interface JSONContent {\n type?: string\n attrs?: Record<string, any>\n content?: JSONContent[]\n marks?: { type: string; attrs?: Record<string, any> }[]\n text?: string\n}\n\nexport type ProductTourStepType = 'element' | 'modal' | 'survey' | 'banner'\n\nexport interface ProductTourBannerConfig {\n behavior: 'sticky' | 'static' | 'custom'\n selector?: string\n action?: {\n type: 'none' | 'link' | 'trigger_tour'\n link?: string\n tourId?: string\n }\n animation?: {\n duration?: number\n }\n}\n\n/** Button actions available on modal steps */\nexport type ProductTourButtonAction = 'dismiss' | 'link' | 'next_step' | 'previous_step' | 'trigger_tour'\n\nexport interface ProductTourStepButton {\n text: string\n action: ProductTourButtonAction\n /** URL to open when action is 'link' */\n link?: string\n /** Tour ID to trigger when action is 'trigger_tour' */\n tourId?: string\n}\n\nexport interface ProductTourStepButtons {\n primary?: ProductTourStepButton\n secondary?: ProductTourStepButton\n}\n\nexport type ProductTourSurveyQuestionType = 'open' | 'rating'\n\nexport interface ProductTourSurveyQuestion {\n type: ProductTourSurveyQuestionType\n questionText: string\n /** Rating display type - emoji or number */\n display?: 'emoji' | 'number'\n /** Rating scale - 3 or 5 for emoji, 5 or 10 for number */\n scale?: 3 | 5 | 10\n /** Label for low end of rating scale (e.g., \"Not likely\") */\n lowerBoundLabel?: string\n /** Label for high end of rating scale (e.g., \"Very likely\") */\n upperBoundLabel?: string\n submitButtonText?: string\n backButtonText?: string\n}\n\nexport interface ProductTourStep {\n id: string\n type: ProductTourStepType\n selector?: string\n progressionTrigger: 'button' | 'click'\n content: JSONContent | null\n /** Pre-rendered HTML content from the editor. If present, SDK should use this instead of rendering from JSONContent. */\n contentHtml?: string\n /** Inline survey question config - if present, this is a survey step */\n survey?: ProductTourSurveyQuestion\n /** ID of the auto-created survey for this step (set by backend) */\n linkedSurveyId?: string\n /** ID of the survey question (set by backend, used for event tracking) */\n linkedSurveyQuestionId?: string\n /** Enhanced element data for more reliable lookup at runtime */\n inferenceData?: InferredSelector\n /** Use CSS selector instead of inference. Defaults to false (use inference). */\n useManualSelector?: boolean\n /** Maximum tooltip width in pixels (defaults to 320px) */\n maxWidth?: number\n /** Position for modal/survey steps (defaults to middle_center) */\n modalPosition?: SurveyPosition\n /** Button configuration for modal steps */\n buttons?: ProductTourStepButtons\n /** Banner configuration (only for banner steps) */\n bannerConfig?: ProductTourBannerConfig\n /** translation data for this tour step */\n translations?: Record<string, ProductTourStepTranslation>\n}\n\n/** all translatable content for a given tour step */\nexport interface ProductTourStepTranslation {\n content?: ProductTourStep['content']\n contentHtml?: ProductTourStep['contentHtml']\n buttons?: {\n primary?: Pick<ProductTourStepButton, 'text'>\n secondary?: Pick<ProductTourStepButton, 'text'>\n }\n survey?: Pick<\n ProductTourSurveyQuestion,\n 'questionText' | 'lowerBoundLabel' | 'upperBoundLabel' | 'submitButtonText' | 'backButtonText'\n >\n}\n\n/** maps to main repo EffectiveProductTourType */\nexport type ProductTourType = 'tour' | 'announcement' | 'banner'\n\nexport interface ProductTourWaitPeriod {\n days: number\n types: ProductTourType[]\n}\n\nexport interface ProductTourConditions {\n url?: string\n urlMatchType?: PropertyMatchType\n selector?: string\n autoShowDelaySeconds?: number\n events?: {\n values: SurveyEventWithFilters[]\n } | null\n cancelEvents?: {\n values: SurveyEventWithFilters[]\n } | null\n actions?: {\n values: SurveyActionType[]\n } | null\n linkedFlagVariant?: string\n deviceTypes?: string[]\n seenTourWaitPeriod?: ProductTourWaitPeriod\n}\n\nexport interface ProductTourAppearance {\n backgroundColor?: string\n textColor?: string\n buttonColor?: string\n borderRadius?: number\n buttonBorderRadius?: number\n borderColor?: string\n fontFamily?: string\n boxShadow?: string\n showOverlay?: boolean\n whiteLabel?: boolean\n /** defaults to true, auto-set to false for announcements/banners */\n dismissOnClickOutside?: boolean\n zIndex?: number\n}\n\nexport type ProductTourDisplayFrequency = 'show_once' | 'until_interacted' | 'always'\n\nexport interface ProductTour {\n id: string\n name: string\n description?: string\n tour_type: ProductTourType // inferred in API based on tour content\n auto_launch?: boolean\n start_date: string | null\n end_date: string | null\n current_iteration?: number\n conditions?: ProductTourConditions\n appearance?: ProductTourAppearance\n steps: ProductTourStep[]\n internal_targeting_flag_key?: string\n linked_flag_key?: string\n display_frequency?: ProductTourDisplayFrequency\n disable_image_preload?: boolean\n}\n\nexport type ProductTourCallback = (tours: ProductTour[], context?: { isLoaded: boolean; error?: string }) => void\n\nexport type ProductTourSelectorError = 'not_found' | 'multiple_matches' | 'not_visible'\n\nexport type ProductTourDismissReason =\n | 'user_clicked_skip'\n | 'user_clicked_outside'\n | 'escape_key'\n | 'element_unavailable'\n | 'container_unavailable'\n\nexport type ProductTourRenderReason = 'auto' | 'api' | 'trigger' | 'event'\n\nexport const DEFAULT_PRODUCT_TOUR_APPEARANCE: Required<ProductTourAppearance> = {\n backgroundColor: '#ffffff',\n textColor: '#1d1f27',\n buttonColor: '#1d1f27',\n borderRadius: 8,\n buttonBorderRadius: 6,\n borderColor: '#e5e7eb',\n fontFamily: 'system-ui',\n boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',\n showOverlay: true,\n whiteLabel: false,\n dismissOnClickOutside: true,\n zIndex: Z_INDEX_TOURS,\n}\n\nexport interface ShowTourOptions {\n reason?: ProductTourRenderReason\n enableStrictValidation?: boolean\n}\n\nexport const ProductTourEventName = {\n SHOWN: 'product tour shown',\n DISMISSED: 'product tour dismissed',\n COMPLETED: 'product tour completed',\n STEP_SHOWN: 'product tour step shown',\n STEP_COMPLETED: 'product tour step completed',\n BUTTON_CLICKED: 'product tour button clicked',\n STEP_SELECTOR_FAILED: 'product tour step selector failed',\n BANNER_CONTAINER_SELECTOR_FAILED: 'product tour banner container selector failed',\n BANNER_ACTION_CLICKED: 'product tour banner action clicked',\n} as const\nexport type ProductTourEventName = (typeof ProductTourEventName)[keyof typeof ProductTourEventName]\n\nexport const ProductTourEventProperties = {\n TOUR_ID: '$product_tour_id',\n TOUR_NAME: '$product_tour_name',\n TOUR_ITERATION: '$product_tour_iteration',\n TOUR_RENDER_REASON: '$product_tour_render_reason',\n TOUR_STEP_ID: '$product_tour_step_id',\n TOUR_STEP_ORDER: '$product_tour_step_order',\n TOUR_STEP_TYPE: '$product_tour_step_type',\n TOUR_DISMISS_REASON: '$product_tour_dismiss_reason',\n TOUR_BUTTON_TEXT: '$product_tour_button_text',\n TOUR_BUTTON_ACTION: '$product_tour_button_action',\n TOUR_BUTTON_LINK: '$product_tour_button_link',\n TOUR_BUTTON_TOUR_ID: '$product_tour_button_tour_id',\n TOUR_STEPS_COUNT: '$product_tour_steps_count',\n TOUR_STEP_SELECTOR: '$product_tour_step_selector',\n TOUR_STEP_SELECTOR_FOUND: '$product_tour_step_selector_found',\n TOUR_STEP_ELEMENT_TAG: '$product_tour_step_element_tag',\n TOUR_STEP_ELEMENT_ID: '$product_tour_step_element_id',\n TOUR_STEP_ELEMENT_CLASSES: '$product_tour_step_element_classes',\n TOUR_STEP_ELEMENT_TEXT: '$product_tour_step_element_text',\n TOUR_ERROR: '$product_tour_error',\n TOUR_MATCHES_COUNT: '$product_tour_matches_count',\n TOUR_FAILURE_PHASE: '$product_tour_failure_phase',\n TOUR_WAITED_FOR_ELEMENT: '$product_tour_waited_for_element',\n TOUR_WAIT_DURATION_MS: '$product_tour_wait_duration_ms',\n TOUR_BANNER_SELECTOR: '$product_tour_banner_selector',\n TOUR_LINKED_SURVEY_ID: '$product_tour_linked_survey_id',\n USE_MANUAL_SELECTOR: '$use_manual_selector',\n INFERENCE_DATA_PRESENT: '$inference_data_present',\n TOUR_LAST_SEEN_DATE: '$product_tour_last_seen_date',\n TOUR_TYPE: '$product_tour_type',\n} as const\nexport type ProductTourEventProperties = (typeof ProductTourEventProperties)[keyof typeof ProductTourEventProperties]\n","/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const DEVICE_ID = '$device_id'\nexport const DEVICE_MODEL = '$device_model'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side'\nexport const EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = '$exception_capture_enabled_server_side'\nexport const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules'\nexport const ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS = '$error_tracking_capture_extension_exceptions'\nexport const WEB_VITALS_ENABLED_SERVER_SIDE = '$web_vitals_enabled_server_side'\nexport const DEAD_CLICKS_ENABLED_SERVER_SIDE = '$dead_clicks_enabled_server_side'\nexport const PRODUCT_TOURS_ENABLED_SERVER_SIDE = '$product_tours_enabled_server_side'\nexport const WEB_VITALS_ALLOWED_METRICS = '$web_vitals_allowed_metrics'\nexport const SESSION_RECORDING_REMOTE_CONFIG = '$session_recording_remote_config'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MASKING = '$session_recording_masking'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_CANVAS_RECORDING = '$session_recording_canvas_recording'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SAMPLE_RATE = '$replay_sample_rate'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MINIMUM_DURATION = '$replay_minimum_duration'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SCRIPT_CONFIG = '$replay_script_config'\nexport const SESSION_RECORDING_OVERRIDE_SAMPLING = '$replay_override_sampling'\nexport const SESSION_RECORDING_OVERRIDE_LINKED_FLAG = '$replay_override_linked_flag'\nexport const SESSION_RECORDING_OVERRIDE_URL_TRIGGER = '$replay_override_url_trigger'\nexport const SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER = '$replay_override_event_trigger'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const SESSION_RECORDING_PAST_MINIMUM_DURATION = '$session_past_minimum_duration'\nexport const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session'\nexport const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session'\n// V2 Trigger Groups: Per-group persistence key prefixes (suffix with group ID)\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX = '$posthog_sr_group_event_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX = '$posthog_sr_group_url_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX = '$posthog_sr_group_sampling_'\nexport const SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP = '$debug_first_full_snapshot_timestamp'\nexport const SESSION_RECORDING_FLUSHED_SIZE = '$sess_rec_flush_size'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_ACTIVE_FEATURE_FLAGS = '$active_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details'\nexport const PERSISTENCE_FEATURE_FLAG_PAYLOADS = '$feature_flag_payloads'\nexport const PERSISTENCE_FEATURE_FLAG_REQUEST_ID = '$feature_flag_request_id'\nexport const PERSISTENCE_MINIMAL_FLAG_CALLED_EVENTS = '$minimal_flag_called_events'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAGS = '$override_feature_flags'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS = '$override_feature_flag_payloads'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const SURVEYS_LOADED_AT = '$surveys_loaded_at'\nexport const SURVEYS_ACTIVATED = '$surveys_activated'\nexport const SURVEYS_ACTIVATED_SESSION = '$surveys_activated_session'\nexport const SURVEYS_ACTIVATED_TIMESTAMPS = '$surveys_activated_timestamps'\nexport const PRODUCT_TOURS = 'ph_product_tours'\nexport const PRODUCT_TOURS_ACTIVATED = '$product_tours_activated'\nexport const PRODUCT_TOURS_ACTIVATED_SESSION = '$product_tours_activated_session'\nexport const CONVERSATIONS = '$conversations'\nexport const CONVERSATIONS_LEGACY_WIDGET_SESSION_ID = '$conversations_widget_session_id'\nexport const CONVERSATIONS_LEGACY_TICKET_ID = '$conversations_ticket_id'\nexport const CONVERSATIONS_LEGACY_WIDGET_STATE = '$conversations_widget_state'\nexport const CONVERSATIONS_LEGACY_USER_TRAITS = '$conversations_user_traits'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const FLAG_CALL_REPORTED_SESSION_ID = '$flag_call_reported_session_id'\nexport const PERSISTENCE_FEATURE_FLAG_ERRORS = '$feature_flag_errors'\nexport const PERSISTENCE_FEATURE_FLAG_EVALUATED_AT = '$feature_flag_evaluated_at'\nexport const USER_STATE = '$user_state'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\nexport const CAPTURE_RATE_LIMIT = '$capture_rate_limit'\n\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params'\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_REFERRER_INFO = '$initial_referrer_info'\nexport const INITIAL_PERSON_INFO = '$initial_person_info'\nexport const ENABLE_PERSON_PROCESSING = '$epp'\n\n/**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * Sentinel value for distinct id, device id, session id. Signals that the server should generate the value\n * */\nexport const COOKIELESS_SENTINEL_VALUE = '$posthog_cookieless'\nexport const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode'\n\nexport const WEB_EXPERIMENTS = '$web_experiments'\n\nexport const SDK_DEBUG_EXTENSIONS_INIT_METHOD = '$sdk_debug_extensions_init_method'\nexport const SDK_DEBUG_EXTENSIONS_INIT_TIME_MS = '$sdk_debug_extensions_init_time_ms'\nexport const SDK_DEBUG_RECORDING_SCRIPT_NOT_LOADED = '$sdk_debug_recording_script_not_loaded'\nexport const SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS = '$sdk_debug_replay_event_trigger_status'\nexport const SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS = '$sdk_debug_replay_linked_flag_trigger_status'\nexport const SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS = '$sdk_debug_replay_matched_recording_trigger_groups'\nexport const SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG = '$sdk_debug_replay_remote_trigger_matching_config'\nexport const SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT = '$sdk_debug_replay_trigger_groups_count'\nexport const SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS = '$sdk_debug_replay_url_trigger_status'\nexport const SDK_DEBUG_REPLAY_RRWEB_ATTACHED = '$sdk_debug_rrweb_attached'\nexport const SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED = '$sdk_debug_rrweb_start_attempted'\nexport const SESSION_RECORDING_START_REASON = '$session_recording_start_reason'\n\nexport const SURVEYS_REQUEST_TIMEOUT_MS = 10000\n// How long the cached `$surveys` definitions are considered fresh. After this, the next\n// `getSurveys` call serves the cache immediately but kicks off a background refresh so\n// server-side changes (e.g. a survey switched from popover to API) propagate to a\n// long-lived tab without needing a page reload.\nexport const SURVEYS_CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes\n// After a failed background refresh we back off for the same window as the cache TTL before\n// trying again. Aliased to make the shared duration intentional rather than coincidental.\nexport const SURVEYS_REFRESH_BACKOFF_MS = SURVEYS_CACHE_TTL_MS\nexport const LOAD_EXT_NOT_FOUND = 'PostHog loadExternalDependency extension not found.'\n\n/* EVENT NAMES - interned to reduce bundle size */\n/* COOKIELESS MODE VALUES */\nexport const COOKIELESS_ON_REJECT = 'on_reject' as const\nexport const COOKIELESS_ALWAYS = 'always' as const\n\n/* USER STATE VALUES */\nexport const USER_STATE_ANONYMOUS = 'anonymous'\nexport const USER_STATE_IDENTIFIED = 'identified'\n\n/* PERSON PROFILE MODES */\nexport const PERSON_PROFILES_IDENTIFIED_ONLY = 'identified_only' as const\n\n/* DOM EVENT NAMES - interned to reduce bundle size */\nexport const DOM_EVENT_VISIBILITYCHANGE = 'visibilitychange'\nexport const DOM_EVENT_BEFOREUNLOAD = 'beforeunload'\n\nexport const EVENT_PAGEVIEW = '$pageview'\nexport const EVENT_PAGELEAVE = '$pageleave'\nexport const EVENT_IDENTIFY = '$identify'\nexport const EVENT_GROUPIDENTIFY = '$groupidentify'\n\n/* Z-INDEX HIERARCHY: tours > surveys > support */\nexport const Z_INDEX_TOURS = 2147483646\nexport const Z_INDEX_SURVEYS = 2147483645\nexport const Z_INDEX_CONVERSATIONS = 2147483644\n","import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","import { querySelectorAllDeep } from 'query-selector-shadow-dom'\nimport { window as _window } from '@posthog/browser-common/utils/globals'\nimport { createLogger, isArray, isUndefined } from '@posthog/core'\n\nconst window = _window as Window & typeof globalThis\nconst logger = createLogger('[Element Inference]')\n\n// this is copied directly from the main repo: /frontend/src/toolbar/utils.ts\n// TODO: once this is deployed, we can have the main repo reference this instead\nexport function elementIsVisible(element: HTMLElement, cache: WeakMap<HTMLElement, boolean>): boolean {\n try {\n const alreadyCached = cache.get(element)\n if (!isUndefined(alreadyCached)) {\n return alreadyCached\n }\n\n if (element.checkVisibility) {\n const nativeIsVisible = element.checkVisibility({\n checkOpacity: true,\n checkVisibilityCSS: true,\n })\n cache.set(element, nativeIsVisible)\n return nativeIsVisible\n }\n\n const style = window.getComputedStyle(element)\n const isInvisible = style.display === 'none' || style.visibility === 'hidden' || parseFloat(style.opacity) === 0\n if (isInvisible) {\n cache.set(element, false)\n return false\n }\n\n // Check parent chain for display/visibility\n let parent = element.parentElement\n while (parent) {\n // Check cache first\n const cached = cache.get(parent)\n if (!isUndefined(cached)) {\n if (!cached) {\n return false\n }\n // If cached as visible, skip to next parent\n parent = parent.parentElement\n continue\n }\n\n const parentStyle = window.getComputedStyle(parent)\n const parentVisible = parentStyle.display !== 'none' && parentStyle.visibility !== 'hidden'\n\n cache.set(parent, parentVisible)\n\n if (!parentVisible) {\n return false\n }\n parent = parent.parentElement\n }\n\n // Check if element has actual rendered dimensions\n const rect = element.getBoundingClientRect()\n const elementHasActualRenderedDimensions =\n rect.width > 0 ||\n rect.height > 0 ||\n // Some elements might be 0x0 but still visible (e.g., inline elements with content)\n element.getClientRects().length > 0\n cache.set(element, elementHasActualRenderedDimensions)\n return elementHasActualRenderedDimensions\n } catch {\n // if we can't get the computed style, we'll assume the element is visible\n return true\n }\n}\n\nexport interface SelectorGroup {\n cardinality: number\n cssSelectors: Array<{\n css: string\n offset: number\n }>\n}\n\nexport interface AutoData {\n notextGroups: SelectorGroup[]\n textGroups: SelectorGroup[]\n}\n\nexport interface InferredSelector {\n autoData: string\n text: string | null\n excludeText?: boolean\n precision?: number\n}\n\nfunction getElementText(element: HTMLElement): string | null {\n const text = element.innerText?.trim()\n // anything higher than 250 chars -> prob not a good selector / button / target\n if (!text || text.length > 250) {\n return null\n }\n return text\n}\n\nfunction elementMatchesText(element: HTMLElement, text: string): boolean {\n const elementText = getElementText(element)\n return elementText?.toLowerCase() === text.toLowerCase()\n}\n\n// generator to query elements, filtering by text and visibility\nfunction* queryElements(\n selector: string,\n text: string | null,\n visibilityCache: WeakMap<HTMLElement, boolean>\n): Generator<HTMLElement, void, undefined> {\n let elements: HTMLElement[]\n\n try {\n elements = querySelectorAllDeep(selector) as unknown as HTMLElement[]\n } catch {\n return\n }\n\n for (const el of elements) {\n const element = el as HTMLElement\n if (text && !elementMatchesText(element, text)) {\n continue\n }\n if (!elementIsVisible(element, visibilityCache)) {\n continue\n }\n yield element\n }\n}\n\n// could be inlined, but wanna keep lazy eval from queryElements\nfunction nth<T>(iterable: Iterable<T>, n: number): T | null {\n let idx = 0\n for (const item of iterable) {\n if (idx === n) {\n return item\n }\n idx++\n }\n return null\n}\n\n/**\n * if inferSelector is the sauce, this is the nugget\n *\n * find an element in the dom using the element inference data\n *\n * 1. try each group of selectors, starting with most specific (lowest cardinality)\n * 2. try each selector in the group - run the css query, go to offset\n * 3. \"vote\" for the element if it was found\n * 4. return early if any element gets majority votes\n * 5. return element w/ most votes\n */\nexport function findElement(selector: InferredSelector): HTMLElement | null {\n try {\n const autoData = JSON.parse(selector.autoData) as AutoData\n if (!isArray(autoData?.textGroups) || !isArray(autoData?.notextGroups)) {\n logger.error('Invalid autoData structure:', autoData)\n return null\n }\n const { text, excludeText, precision = 1 } = selector\n\n // excludeText -> user setting, usually if the target element\n // has dynamic/localized text\n const useText = text != null && !excludeText\n\n // choose appropriate group + sort\n const groups = (useText ? autoData.textGroups : autoData.notextGroups).sort(\n (a, b) => a.cardinality - b.cardinality\n )\n\n if (groups.length === 0) {\n return null\n }\n\n // precision controls how many groups to search\n // 1 = strict (only most specific group), 0 = loose (all groups)\n const maxGroups = Math.max(1, Math.ceil((1 - precision) * groups.length))\n\n const visibilityCache = new WeakMap<HTMLElement, boolean>()\n\n // try each selector group, starting w/ most specific (lowest cardinality)\n for (let i = 0; i < maxGroups; i++) {\n const group = groups[i]\n const votes = new Map<HTMLElement, number>()\n let winner: HTMLElement | null = null\n let maxVotes = 0\n\n // test each selector in the group\n for (const { css, offset } of group.cssSelectors) {\n // get matches, jump to offset to find our target\n const element = nth(queryElements(css, useText ? text : null, visibilityCache), offset)\n\n if (!element) {\n continue\n }\n\n // if we found something, this element gets a vote\n const voteCount = (votes.get(element) ?? 0) + 1\n votes.set(element, voteCount)\n\n if (voteCount > maxVotes) {\n maxVotes = voteCount\n winner = element\n\n // break early if we have a majority\n if (voteCount >= Math.ceil(group.cssSelectors.length / 2)) {\n return winner\n }\n }\n }\n\n if (winner) {\n return winner\n }\n }\n\n return null\n } catch (error) {\n logger.error('Error finding element:', error)\n return null\n }\n}\n\nexport function getElementPath(el: HTMLElement | null, depth = 4): string | null {\n if (!el) {\n return null\n }\n const parts: string[] = []\n let current: HTMLElement | null = el\n\n while (current && parts.length < depth && current.tagName !== 'BODY') {\n let part = current.tagName.toLowerCase()\n if (current.id) {\n part += `#${current.id}`\n } else if (current.classList.length) {\n part += `.${current.classList[0]}`\n }\n parts.unshift(part)\n current = current.parentElement\n }\n\n return parts.join(' > ')\n}\n","import config from \"../config.mjs\";\nimport { isUndefined } from \"@posthog/core\";\nimport { window as external_globals_mjs_window } from \"./globals.mjs\";\nconst _createLogger = (prefix, { debugEnabled } = {})=>{\n const logger = {\n _log: (level, ...args)=>{\n if (external_globals_mjs_window && (config.DEBUG || external_globals_mjs_window.POSTHOG_DEBUG || debugEnabled) && !isUndefined(external_globals_mjs_window.console) && external_globals_mjs_window.console) {\n const consoleLog = '__rrweb_original__' in external_globals_mjs_window.console[level] ? external_globals_mjs_window.console[level]['__rrweb_original__'] : external_globals_mjs_window.console[level];\n consoleLog(prefix, ...args);\n }\n },\n debug: (...args)=>{\n logger._log('debug', ...args);\n },\n info: (...args)=>{\n logger._log('log', ...args);\n },\n warn: (...args)=>{\n logger._log('warn', ...args);\n },\n error: (...args)=>{\n logger._log('error', ...args);\n },\n critical: (...args)=>{\n console.error(prefix, ...args);\n },\n uninitializedWarning: (methodName)=>{\n logger.error(`You must initialize PostHog before calling ${methodName}`);\n },\n createLogger: (additionalPrefix, options)=>_createLogger(`${prefix} ${additionalPrefix}`, options)\n };\n return logger;\n};\nconst logger_logger = _createLogger('[PostHog.js]');\nconst createLogger = logger_logger.createLogger;\nexport { createLogger, logger_logger as logger };\n","import { isFunction } from \"@posthog/core\";\nimport { createLogger } from \"./logger.mjs\";\nconst logger = createLogger('[Stylesheet Loader]');\nconst getStylesheetPreparer = (context)=>{\n if (isFunction(context)) return context;\n return context?.config?.prepare_external_dependency_stylesheet;\n};\nconst prepareStylesheet = (document, innerText, context)=>{\n let stylesheet = document.createElement('style');\n stylesheet.innerText = innerText;\n const prepareExternalDependencyStylesheet = getStylesheetPreparer(context);\n if (prepareExternalDependencyStylesheet) stylesheet = prepareExternalDependencyStylesheet(stylesheet);\n if (!stylesheet) {\n logger.error('prepare_external_dependency_stylesheet returned null');\n return null;\n }\n return stylesheet;\n};\nexport { prepareStylesheet };\n","import { getSurveyIterationKey } from '@posthog/core/surveys'\n\nimport { DisplaySurveyOptions, Survey, SurveyType, DisplaySurveyType } from '../posthog-surveys-types'\nimport { createLogger } from '@posthog/browser-common/utils/logger'\n\nexport { doesSurveyActivateByEvent, getSurveyInteractionProperty, isSurveyIterationBased } from '@posthog/core/surveys'\n\nexport const SURVEY_LOGGER = createLogger('[Surveys]')\n\nexport function isSurveyRunning(survey: Survey): boolean {\n return !!(survey.start_date && !survey.end_date)\n}\n\nexport function doesSurveyActivateByAction(survey: Pick<Survey, 'conditions'>): boolean {\n return !!survey.conditions?.actions?.values?.length\n}\n\nexport const SURVEY_SEEN_PREFIX = 'seenSurvey_'\nexport const SURVEY_IN_PROGRESS_PREFIX = 'inProgressSurvey_'\nexport const SURVEY_ABANDONED_PREFIX = 'abandonedSurvey_'\n\n// Prefix namespacing is a localStorage concern, so it stays in the browser package;\n// the iteration-qualified key itself is shared with the other SDKs via @posthog/core.\nexport const getSurveyStorageKey = (prefix: string, survey: Pick<Survey, 'id' | 'current_iteration'>): string => {\n return `${prefix}${getSurveyIterationKey(survey)}`\n}\n\nexport const getSurveySeenKey = (survey: Pick<Survey, 'id' | 'current_iteration'>): string => {\n return getSurveyStorageKey(SURVEY_SEEN_PREFIX, survey)\n}\n\nexport const getSurveyAbandonedKey = (survey: Pick<Survey, 'id' | 'current_iteration'>): string => {\n return getSurveyStorageKey(SURVEY_ABANDONED_PREFIX, survey)\n}\n\nexport const setSurveySeenOnLocalStorage = (survey: Pick<Survey, 'id' | 'current_iteration'>) => {\n try {\n const surveySeenKey = getSurveySeenKey(survey)\n const isSurveySeen = localStorage.getItem(surveySeenKey)\n // if survey is already seen, no need to set it again\n if (isSurveySeen) {\n return\n }\n\n localStorage.setItem(surveySeenKey, 'true')\n } catch (error) {\n SURVEY_LOGGER.error('Failed to persist survey seen state', error)\n }\n}\n\n// These surveys are relevant for the getActiveMatchingSurveys method. They are used to\n// display surveys in our customer's application. Any new in-app survey type should be added here.\nexport const IN_APP_SURVEY_TYPES: SurveyType[] = [SurveyType.Popover, SurveyType.Widget, SurveyType.API]\n\nexport const DEFAULT_DISPLAY_SURVEY_OPTIONS: DisplaySurveyOptions = {\n ignoreConditions: false,\n ignoreDelay: false,\n displayType: DisplaySurveyType.Popover,\n}\n","/*! For license information please see uuidv7.mjs.LICENSE.txt */\nimport { window as external_globals_mjs_window } from \"./globals.mjs\";\nimport { isNumber, isUndefined } from \"@posthog/core\";\n/**\n * uuidv7: An experimental implementation of the proposed UUID Version 7\n *\n * @license Apache-2.0\n * @copyright 2021-2023 LiosK\n * @packageDocumentation\n *\n * from https://github.com/LiosK/uuidv7/blob/e501462ea3d23241de13192ceae726956f9b3b7d/src/index.ts\n */ if (!Math.trunc) Math.trunc = function(v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\nif (!Number.isInteger) Number.isInteger = function(value) {\n return isNumber(value) && isFinite(value) && Math.floor(value) === value;\n};\nclass UUID {\n constructor(bytes){\n this.bytes = bytes;\n if (16 !== bytes.length) throw new TypeError('not 128-bit length');\n }\n static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {\n if (!Number.isInteger(unixTsMs) || !Number.isInteger(randA) || !Number.isInteger(randBHi) || !Number.isInteger(randBLo) || unixTsMs < 0 || randA < 0 || randBHi < 0 || randBLo < 0 || unixTsMs > 0xffffffffffff || randA > 0xfff || randBHi > 0x3fffffff || randBLo > 0xffffffff) throw new RangeError('invalid field value');\n const bytes = new Uint8Array(16);\n bytes[0] = unixTsMs / 2 ** 40;\n bytes[1] = unixTsMs / 2 ** 32;\n bytes[2] = unixTsMs / 2 ** 24;\n bytes[3] = unixTsMs / 2 ** 16;\n bytes[4] = unixTsMs / 256;\n bytes[5] = unixTsMs;\n bytes[6] = 0x70 | randA >>> 8;\n bytes[7] = randA;\n bytes[8] = 0x80 | randBHi >>> 24;\n bytes[9] = randBHi >>> 16;\n bytes[10] = randBHi >>> 8;\n bytes[11] = randBHi;\n bytes[12] = randBLo >>> 24;\n bytes[13] = randBLo >>> 16;\n bytes[14] = randBLo >>> 8;\n bytes[15] = randBLo;\n return new UUID(bytes);\n }\n toString() {\n let text = '';\n for(let i = 0; i < this.bytes.length; i++){\n text = text + (this.bytes[i] >>> 4).toString(16) + (0xf & this.bytes[i]).toString(16);\n if (3 === i || 5 === i || 7 === i || 9 === i) text += '-';\n }\n if (36 !== text.length) throw new Error('Invalid UUIDv7 was generated');\n return text;\n }\n clone() {\n return new UUID(this.bytes.slice(0));\n }\n equals(other) {\n return 0 === this.compareTo(other);\n }\n compareTo(other) {\n for(let i = 0; i < 16; i++){\n const diff = this.bytes[i] - other.bytes[i];\n if (0 !== diff) return Math.sign(diff);\n }\n return 0;\n }\n}\nclass V7Generator {\n generate() {\n const value = this.generateOrAbort();\n if (!isUndefined(value)) return value;\n {\n this._timestamp = 0;\n const valueAfterReset = this.generateOrAbort();\n if (isUndefined(valueAfterReset)) throw new Error('Could not generate UUID after timestamp reset');\n return valueAfterReset;\n }\n }\n generateOrAbort() {\n const MAX_COUNTER = 0x3ffffffffff;\n const ROLLBACK_ALLOWANCE = 10000;\n const ts = Date.now();\n if (ts > this._timestamp) {\n this._timestamp = ts;\n this._resetCounter();\n } else {\n if (!(ts + ROLLBACK_ALLOWANCE > this._timestamp)) return;\n this._counter++;\n if (this._counter > MAX_COUNTER) {\n this._timestamp++;\n this._resetCounter();\n }\n }\n return UUID.fromFieldsV7(this._timestamp, Math.trunc(this._counter / 2 ** 30), this._counter & 2 ** 30 - 1, this._random.nextUint32());\n }\n _resetCounter() {\n this._counter = 0x400 * this._random.nextUint32() + (0x3ff & this._random.nextUint32());\n }\n constructor(){\n this._timestamp = 0;\n this._counter = 0;\n this._random = new DefaultRandom();\n }\n}\nlet getRandomValues = (buffer)=>{\n if ('undefined' != typeof UUIDV7_DENY_WEAK_RNG && UUIDV7_DENY_WEAK_RNG) throw new Error('no cryptographically strong RNG available');\n for(let i = 0; i < buffer.length; i++)buffer[i] = 0x10000 * Math.trunc(0x10000 * Math.random()) + Math.trunc(0x10000 * Math.random());\n return buffer;\n};\nif (external_globals_mjs_window && !isUndefined(external_globals_mjs_window.crypto) && crypto.getRandomValues) getRandomValues = (buffer)=>crypto.getRandomValues(buffer);\nclass DefaultRandom {\n nextUint32() {\n if (this._cursor >= this._buffer.length) {\n getRandomValues(this._buffer);\n this._cursor = 0;\n }\n return this._buffer[this._cursor++];\n }\n constructor(){\n this._buffer = new Uint32Array(8);\n this._cursor = 1 / 0;\n }\n}\nlet defaultGenerator;\nconst uuidv7 = ()=>uuidv7obj().toString();\nconst uuidv7obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generate();\nconst uuid7ToTimestampMs = (uuid)=>{\n const hex = uuid.replace(/-/g, '');\n if (32 !== hex.length) throw new Error('Not a valid UUID');\n if ('7' !== hex[12]) throw new Error('Not a UUIDv7');\n return parseInt(hex.substring(0, 12), 16);\n};\nexport { UUID, uuid7ToTimestampMs, uuidv7 };\n","import{options as n}from\"preact\";var t,r,u,i,o=0,f=[],c=n,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,p=c.__;function s(n,t){c.__h&&c.__h(r,n,o||t),o=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return o=1,y(D,n)}function y(n,u,i){var o=s(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):D(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.__f)){var f=function(n,t,r){if(!o.__c.__H)return!0;var u=!1,i=o.__c.props!==n;if(o.__c.__H.__.some(function(n){if(n.__N){u=!0;var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0)}}),c){var f=c.call(this,n,t,r);return u?f||i:f}return!u||i};r.__f=!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 h(n,u){var i=s(t++,3);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__H.__h.push(i))}function _(n,u){var i=s(t++,4);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__h.push(i))}function A(n){return o=5,T(function(){return{current:n}},[])}function F(n,t,r){o=6,_(function(){if(\"function\"==typeof n){var r=n(t());return function(){n(null),r&&\"function\"==typeof r&&r()}}if(n)return n.current=t(),function(){return n.current=null}},null==r?r:r.concat(n))}function T(n,r){var u=s(t++,7);return C(u.__H,r)&&(u.__=n(),u.__H=r,u.__h=n),u.__}function q(n,t){return o=8,T(function(){return n},t)}function x(n){var u=r.context[n.__c],i=s(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function P(n,t){c.useDebugValue&&c.useDebugValue(t?t(n):n)}function b(n){var u=s(t++,10),i=d();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 g(){var n=s(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 j(){for(var n;n=f.shift();){var t=n.__H;if(n.__P&&t)try{t.__h.some(z),t.__h.some(B),t.__h=[]}catch(r){t.__h=[],c.__e(r,n.__v)}}}c.__b=function(n){r=null,e&&e(n)},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),p&&p(n,t)},c.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(i.__h.length&&j(),t=0)),u=r},c.diffed=function(n){v&&v(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==f.push(t)&&i===c.requestAnimationFrame||((i=c.requestAnimationFrame)||w)(j)),t.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),u=r=null},c.__c=function(n,t){t.some(function(n){try{n.__h.some(z),n.__h=n.__h.filter(function(n){return!n.__||B(n)})}catch(r){t.some(function(n){n.__h&&(n.__h=[])}),t=[],c.__e(r,n.__v)}}),l&&l(n,t)},c.unmount=function(n){m&&m(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.some(function(n){try{z(n)}catch(n){t=n}}),r.__H=void 0,t&&c.__e(t,r.__v))};var k=\"function\"==typeof requestAnimationFrame;function w(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r))}function z(n){var t=r,u=n.__c;\"function\"==typeof u&&(n.__c=void 0,u()),r=t}function B(n){var t=r;n.__c=n.__(),r=t}function C(n,t){return!n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function D(n,t){return\"function\"==typeof t?t(n):t}export{q as useCallback,x as useContext,P as useDebugValue,h as useEffect,b as useErrorBoundary,g as useId,F as useImperativeHandle,_ as useLayoutEffect,T as useMemo,y as useReducer,A as useRef,d as useState};\n//# sourceMappingURL=hooks.module.js.map\n","import { VNode, cloneElement, createContext, type JSX } from 'preact'\nimport { PostHog } from '../../posthog-core'\nimport {\n MultipleSurveyQuestion,\n Survey,\n SurveyAppearance,\n SurveyEventName,\n SurveyEventProperties,\n SurveyPosition,\n SurveyQuestion,\n SurveyType,\n SurveyWidgetType,\n} from '../../posthog-surveys-types'\nimport { document as _document, window as _window } from '@posthog/browser-common/utils/globals'\nimport {\n getSurveyInteractionProperty,\n getSurveySeenKey,\n getSurveyAbandonedKey,\n getSurveyStorageKey,\n SURVEY_LOGGER as logger,\n setSurveySeenOnLocalStorage,\n SURVEY_IN_PROGRESS_PREFIX,\n} from '../../utils/survey-utils'\nimport { isNullish, type SurveyResponses } from '@posthog/core'\nimport {\n buildSurveyResponseProperties,\n canSurveyActivateRepeatedly,\n getSurveyResponseKey,\n surveyHasResponses,\n} from '@posthog/core/surveys'\n\nimport { propertyComparisons } from '@posthog/browser-common/utils/property-utils'\nimport { getTargetingUrl } from '@posthog/browser-common/utils/url-targeting-utils'\nimport { localStore } from '../../storage'\nimport { Properties, PropertyMatchType } from '../../types'\nimport { Z_INDEX_SURVEYS } from '../../constants'\nimport { prepareStylesheet } from '@posthog/browser-common/utils/stylesheet-loader'\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\nimport surveyStyles from './survey.css'\nimport { useContext } from 'preact/hooks'\nimport { doesDeviceTypeMatch, hasPeriodPassed } from '@posthog/browser-common/utils/matcher-utils'\n\nexport function getFontFamily(fontFamily?: string): string {\n if (fontFamily === 'inherit') {\n return 'inherit'\n }\n\n const defaultFontStack =\n 'BlinkMacSystemFont, \"Inter\", \"Segoe UI\", \"Roboto\", Helvetica, Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\"'\n return fontFamily ? `${fontFamily}, ${defaultFontStack}` : `-apple-system, ${defaultFontStack}`\n}\n\nexport { getSurveyResponseKey }\n\nconst BLACK_TEXT_COLOR = '#020617' // Maps out to text-slate-950 from tailwind colors. Intended for text use outside interactive elements like buttons\n\n// Keep in sync with defaultSurveyAppearance on the main app\nexport const defaultSurveyAppearance = {\n fontFamily: 'inherit',\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: SurveyPosition.Right,\n widgetType: SurveyWidgetType.Tab,\n widgetLabel: 'Feedback',\n widgetColor: 'black',\n zIndex: String(Z_INDEX_SURVEYS),\n disabledButtonOpacity: '0.6',\n maxWidth: '300px',\n textSubtleColor: '#939393',\n boxPadding: '20px 24px',\n boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',\n borderRadius: '10px',\n shuffleQuestions: false,\n surveyPopupDelaySeconds: undefined,\n // Not customizable atm\n outlineColor: 'rgba(59, 130, 246, 0.8)',\n inputBackground: 'white',\n inputTextColor: BLACK_TEXT_COLOR,\n scrollbarThumbColor: 'var(--ph-survey-border-color)',\n scrollbarTrackColor: 'var(--ph-survey-background-color)',\n} as const\n\nconst BOTTOM_BORDER_SURVEY_POSITIONS: SurveyPosition[] = [\n SurveyPosition.Center,\n SurveyPosition.Left,\n SurveyPosition.Right,\n]\n\nexport const addSurveyCSSVariablesToElement = (\n element: HTMLElement,\n type: SurveyType,\n appearance?: SurveyAppearance | null\n) => {\n const effectiveAppearance = { ...defaultSurveyAppearance, ...appearance }\n const hostStyle = element.style\n\n const surveyHasBottomBorder =\n !BOTTOM_BORDER_SURVEY_POSITIONS.includes(effectiveAppearance.position) ||\n (type === SurveyType.Widget && appearance?.widgetType === SurveyWidgetType.Tab)\n\n hostStyle.setProperty('--ph-survey-font-family', getFontFamily(effectiveAppearance.fontFamily))\n hostStyle.setProperty('--ph-survey-box-padding', effectiveAppearance.boxPadding)\n hostStyle.setProperty('--ph-survey-max-width', effectiveAppearance.maxWidth)\n hostStyle.setProperty('--ph-survey-z-index', effectiveAppearance.zIndex)\n hostStyle.setProperty('--ph-survey-border-color', effectiveAppearance.borderColor)\n // Non-bottom surveys or tab surveys have the border bottom\n if (surveyHasBottomBorder) {\n hostStyle.setProperty('--ph-survey-border-radius', effectiveAppearance.borderRadius)\n hostStyle.setProperty('--ph-survey-border-bottom', '1.5px solid var(--ph-survey-border-color)')\n } else {\n hostStyle.setProperty('--ph-survey-border-bottom', 'none')\n hostStyle.setProperty(\n '--ph-survey-border-radius',\n `${effectiveAppearance.borderRadius} ${effectiveAppearance.borderRadius} 0 0`\n )\n }\n hostStyle.setProperty('--ph-survey-background-color', effectiveAppearance.backgroundColor)\n hostStyle.setProperty('--ph-survey-box-shadow', effectiveAppearance.boxShadow)\n hostStyle.setProperty('--ph-survey-disabled-button-opacity', effectiveAppearance.disabledButtonOpacity)\n hostStyle.setProperty('--ph-survey-submit-button-color', effectiveAppearance.submitButtonColor)\n hostStyle.setProperty(\n '--ph-survey-submit-button-text-color',\n appearance?.submitButtonTextColor || getContrastingTextColor(effectiveAppearance.submitButtonColor)\n )\n hostStyle.setProperty('--ph-survey-rating-bg-color', effectiveAppearance.ratingButtonColor)\n hostStyle.setProperty('--ph-survey-rating-active-bg-color', effectiveAppearance.ratingButtonActiveColor)\n // Active rating text is always auto-calculated for contrast with active background\n hostStyle.setProperty(\n '--ph-survey-rating-active-text-color',\n getContrastingTextColor(effectiveAppearance.ratingButtonActiveColor)\n )\n // Primary text color: use override if provided, otherwise auto-calculate from background\n hostStyle.setProperty(\n '--ph-survey-text-primary-color',\n appearance?.textColor || getContrastingTextColor(effectiveAppearance.backgroundColor)\n )\n hostStyle.setProperty('--ph-survey-text-subtle-color', effectiveAppearance.textSubtleColor)\n hostStyle.setProperty('--ph-widget-color', effectiveAppearance.widgetColor)\n hostStyle.setProperty('--ph-widget-text-color', getContrastingTextColor(effectiveAppearance.widgetColor))\n hostStyle.setProperty('--ph-widget-z-index', effectiveAppearance.zIndex)\n\n // Use user-provided inputBackground (or deprecated inputBackgroundColor for backwards compat)\n // Fallback to internal default, with slight adjustment for white backgrounds\n const userInputBg = appearance?.inputBackground || appearance?.inputBackgroundColor\n let inputBgColor = userInputBg || effectiveAppearance.inputBackground\n if (!userInputBg && effectiveAppearance.backgroundColor === 'white') {\n inputBgColor = '#f8f8f8'\n }\n hostStyle.setProperty('--ph-survey-input-background', inputBgColor)\n // Input text color applies to both text inputs and inactive rating buttons\n const inputTextColor = appearance?.inputTextColor || getContrastingTextColor(inputBgColor)\n hostStyle.setProperty('--ph-survey-input-text-color', inputTextColor)\n hostStyle.setProperty('--ph-survey-rating-text-color', inputTextColor)\n hostStyle.setProperty('--ph-survey-scrollbar-thumb-color', effectiveAppearance.scrollbarThumbColor)\n hostStyle.setProperty('--ph-survey-scrollbar-track-color', effectiveAppearance.scrollbarTrackColor)\n hostStyle.setProperty('--ph-survey-outline-color', effectiveAppearance.outlineColor)\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\nexport function hex2rgb(c: string): string {\n if (c.startsWith('#')) {\n let hexColor = c.replace(/^#/, '')\n // Handle 3-character shorthand (e.g., #111 -> #111111, #abc -> #aabbcc)\n if (/^[0-9A-Fa-f]{3}$/.test(hexColor)) {\n hexColor = hexColor[0] + hexColor[0] + hexColor[1] + hexColor[1] + hexColor[2] + hexColor[2]\n }\n if (!/^[0-9A-Fa-f]{6}$/.test(hexColor)) {\n return 'rgb(255, 255, 255)'\n }\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 hexToRgba(hex: string, opacity: number): string {\n const rgb = hex2rgb(hex)\n const match = rgb.match(/^rgb\\((\\d+),(\\d+),(\\d+)\\)$/)\n if (!match) {\n return hex\n }\n return `rgba(${match[1]}, ${match[2]}, ${match[3]}, ${opacity})`\n}\n\nexport function getContrastingTextColor(color: string = defaultSurveyAppearance.backgroundColor) {\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_TEXT_COLOR\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_TEXT_COLOR : 'white'\n }\n return BLACK_TEXT_COLOR\n}\n\nexport function getSurveyStylesheet(posthog?: PostHog) {\n const stylesheet = prepareStylesheet(document, typeof surveyStyles === 'string' ? surveyStyles : '', posthog)\n stylesheet?.setAttribute('data-ph-survey-style', 'true')\n return stylesheet\n}\n\nexport const retrieveSurveyShadow = (\n survey: Pick<Survey, 'id' | 'appearance' | 'type'>,\n posthog?: PostHog,\n element?: Element\n) => {\n const widgetClassName = getSurveyContainerClass(survey)\n const existingDiv = document.querySelector(`.${widgetClassName}`)\n\n if (existingDiv && existingDiv.shadowRoot) {\n return {\n shadow: existingDiv.shadowRoot,\n isNewlyCreated: false,\n }\n }\n\n // If it doesn't exist, create it\n const div = document.createElement('div')\n addSurveyCSSVariablesToElement(div, survey.type, survey.appearance)\n div.className = widgetClassName\n const shadow = div.attachShadow({ mode: 'open' })\n const stylesheet = getSurveyStylesheet(posthog)\n if (stylesheet) {\n const existingStylesheet = shadow.querySelector('style')\n if (existingStylesheet) {\n shadow.removeChild(existingStylesheet)\n }\n shadow.appendChild(stylesheet)\n }\n ;(element ? element : document.body).appendChild(div)\n return {\n shadow,\n isNewlyCreated: true,\n }\n}\n\ninterface SendSurveyEventArgs {\n responses: SurveyResponses\n survey: Survey\n surveySubmissionId: string\n isSurveyCompleted: boolean\n posthog?: PostHog\n /** Additional properties to include in the survey event */\n properties?: Properties\n /** The language that was applied to the survey. */\n surveyLanguage?: string | null\n}\n\nexport const sendSurveyEvent = ({\n responses,\n survey,\n surveySubmissionId,\n posthog,\n isSurveyCompleted,\n properties,\n surveyLanguage,\n}: SendSurveyEventArgs) => {\n if (!posthog) {\n logger.error('[survey sent] event not captured, PostHog instance not found.')\n return\n }\n setSurveySeenOnLocalStorage(survey)\n posthog.capture(SurveyEventName.SENT, {\n [SurveyEventProperties.SURVEY_NAME]: survey.name,\n [SurveyEventProperties.SURVEY_ID]: survey.id,\n [SurveyEventProperties.SURVEY_ITERATION]: survey.current_iteration,\n [SurveyEventProperties.SURVEY_ITERATION_START_DATE]: survey.current_iteration_start_date,\n [SurveyEventProperties.SURVEY_SUBMISSION_ID]: surveySubmissionId,\n [SurveyEventProperties.SURVEY_COMPLETED]: isSurveyCompleted,\n ...(surveyLanguage && { [SurveyEventProperties.SURVEY_LANGUAGE]: surveyLanguage }),\n sessionRecordingUrl: posthog.get_session_replay_url?.(),\n ...buildSurveyResponseProperties(responses, survey),\n ...properties,\n $set: {\n [getSurveyInteractionProperty(survey, 'responded')]: true,\n },\n })\n if (isSurveyCompleted) {\n // Only dispatch PHSurveySent if the survey is completed, as that removes the survey from focus\n window.dispatchEvent(new CustomEvent('PHSurveySent', { detail: { surveyId: survey.id } }))\n clearInProgressSurveyState(survey)\n // Recompute the internal targeting flag promptly. The response we just recorded makes this\n // person ineligible server-side, but the cached flag still says \"eligible\", so reloading now\n // stops a quick revisit from re-showing the survey and recording a duplicate response.\n posthog.reloadFeatureFlags()\n }\n}\n\nconst _buildSurveyEventProperties = (\n survey: Survey,\n inProgressSurvey: InProgressSurveyState | null,\n posthog: PostHog\n) => ({\n [SurveyEventProperties.SURVEY_NAME]: survey.name,\n [SurveyEventProperties.SURVEY_ID]: survey.id,\n [SurveyEventProperties.SURVEY_ITERATION]: survey.current_iteration,\n [SurveyEventProperties.SURVEY_ITERATION_START_DATE]: survey.current_iteration_start_date,\n [SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED]: surveyHasResponses(inProgressSurvey?.responses),\n ...(inProgressSurvey?.surveyLanguage && {\n [SurveyEventProperties.SURVEY_LANGUAGE]: inProgressSurvey.surveyLanguage,\n }),\n sessionRecordingUrl: posthog.get_session_replay_url?.(),\n [SurveyEventProperties.SURVEY_SUBMISSION_ID]: inProgressSurvey?.surveySubmissionId,\n ...buildSurveyResponseProperties(inProgressSurvey?.responses, survey),\n})\n\nexport const dismissedSurveyEvent = (\n survey: Survey,\n posthog?: PostHog,\n readOnly?: boolean,\n surveyLanguage?: string | null\n) => {\n if (!posthog) {\n logger.error('[survey dismissed] event not captured, PostHog instance not found.')\n return\n }\n if (readOnly) {\n return\n }\n\n const inProgressSurvey = getInProgressSurveyState(survey)\n posthog.capture(SurveyEventName.DISMISSED, {\n ..._buildSurveyEventProperties(survey, inProgressSurvey, posthog),\n ...(surveyLanguage && { [SurveyEventProperties.SURVEY_LANGUAGE]: surveyLanguage }),\n $set: {\n [getSurveyInteractionProperty(survey, 'dismissed')]: true,\n },\n })\n clearInProgressSurveyState(survey)\n setSurveySeenOnLocalStorage(survey)\n window.dispatchEvent(new CustomEvent('PHSurveyClosed', { detail: { surveyId: survey.id } }))\n}\n\nexport const sendSurveyAbandonedEvent = (survey: Survey, posthog?: PostHog) => {\n if (!posthog) {\n logger.error('[survey abandoned] event not captured, PostHog instance not found.')\n return\n }\n\n const abandonedKey = getSurveyAbandonedKey(survey)\n try {\n if (localStorage.getItem(abandonedKey) === 'true') {\n return\n }\n } catch {\n // localStorage not available\n return\n }\n\n const inProgressSurvey = getInProgressSurveyState(survey)\n if (!inProgressSurvey) {\n return\n }\n\n try {\n localStorage.setItem(abandonedKey, 'true')\n } catch {\n // localStorage not available\n }\n\n posthog.capture(SurveyEventName.ABANDONED, _buildSurveyEventProperties(survey, inProgressSurvey, posthog), {\n transport: 'sendBeacon',\n })\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 if (!survey.appearance || !survey.appearance.shuffleQuestions || survey.enable_partial_responses) {\n return survey.questions\n }\n\n return reverseIfUnshuffled(survey.questions, shuffle(survey.questions))\n}\n\nexport const canActivateRepeatedly = (\n survey: Pick<Survey, 'schedule' | 'conditions' | 'id' | 'current_iteration'>\n): boolean => {\n return canSurveyActivateRepeatedly(survey) || isSurveyInProgress(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 = localStore._get(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\nconst LAST_SEEN_SURVEY_DATE_KEY = 'lastSeenSurveyDate'\n\nexport const hasWaitPeriodPassed = (waitPeriodInDays: number | undefined): boolean => {\n const lastSeenSurveyDate = localStore._get(LAST_SEEN_SURVEY_DATE_KEY)\n return hasPeriodPassed(waitPeriodInDays, lastSeenSurveyDate)\n}\n\ninterface SurveyContextProps {\n isPreviewMode: boolean\n previewPageIndex: number | undefined\n onPopupSurveyDismissed: () => void\n isPopup: boolean\n onPreviewSubmit: (res: string | string[] | number | null) => void\n onPreviewBack: () => void\n surveySubmissionId: string\n /** Additional properties to include in all survey events */\n properties?: Properties\n /** The language that was applied to the survey. */\n surveyLanguage?: string | null\n}\n\nexport const SurveyContext = createContext<SurveyContextProps>({\n isPreviewMode: false,\n previewPageIndex: 0,\n onPopupSurveyDismissed: () => {},\n isPopup: true,\n onPreviewSubmit: () => {},\n onPreviewBack: () => {},\n surveySubmissionId: '',\n properties: undefined,\n surveyLanguage: null,\n})\n\nexport const useSurveyContext = () => {\n return useContext(SurveyContext)\n}\n\ninterface RenderProps {\n component: VNode<{ className: string }>\n children: string\n renderAsHtml?: boolean\n style?: JSX.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\nfunction defaultMatchType(matchType?: PropertyMatchType): PropertyMatchType {\n return matchType ?? 'icontains'\n}\n\n// use urlMatchType to validate url condition, fallback to contains for backwards compatibility\nexport function doesSurveyUrlMatch(survey: Pick<Survey, 'conditions'>, posthog?: PostHog): boolean {\n if (!survey.conditions?.url) {\n return true\n }\n // honors the `get_current_url` config hook so apps that rewrite their URL can target surveys correctly\n const href = getTargetingUrl(posthog)\n if (!href) {\n // if we dont know the url, assume it is not a match\n return false\n }\n const targets = [survey.conditions.url]\n const matchType = defaultMatchType(survey.conditions?.urlMatchType)\n return propertyComparisons[matchType](targets, [href])\n}\n\nexport function doesSurveyDeviceTypesMatch(survey: Survey): boolean {\n return doesDeviceTypeMatch(survey.conditions?.deviceTypes, survey.conditions?.deviceTypesMatchType)\n}\n\nexport function doesSurveyMatchSelector(survey: Survey): boolean {\n if (!survey.conditions?.selector) {\n return true\n }\n return !!document?.querySelector(survey.conditions.selector)\n}\n\ninterface InProgressSurveyState {\n surveySubmissionId: string\n lastQuestionIndex: number\n // Indices the respondent has visited, in order, excluding the current one. Pushed on next, popped on back.\n // Optional for backwards compat with state persisted before the back-navigation feature.\n visitedIndices?: number[]\n responses: SurveyResponses\n surveyLanguage?: string | null\n}\n\nconst getInProgressSurveyStateKey = (survey: Pick<Survey, 'id' | 'current_iteration'>): string => {\n return getSurveyStorageKey(SURVEY_IN_PROGRESS_PREFIX, survey)\n}\n\nexport const setInProgressSurveyState = (\n survey: Pick<Survey, 'id' | 'current_iteration'>,\n state: InProgressSurveyState\n): void => {\n try {\n localStorage.setItem(getInProgressSurveyStateKey(survey), JSON.stringify(state))\n } catch (e) {\n logger.error('Error setting in-progress survey state in localStorage', e)\n }\n}\n\nexport const getInProgressSurveyState = (\n survey: Pick<Survey, 'id' | 'current_iteration'>\n): InProgressSurveyState | null => {\n try {\n const stateString = localStorage.getItem(getInProgressSurveyStateKey(survey))\n if (stateString) {\n return JSON.parse(stateString) as InProgressSurveyState\n }\n } catch (e) {\n logger.error('Error getting in-progress survey state from localStorage', e)\n }\n return null\n}\n\nexport const isSurveyInProgress = (survey: Pick<Survey, 'id' | 'current_iteration'>): boolean => {\n const state = getInProgressSurveyState(survey)\n return !isNullish(state?.surveySubmissionId)\n}\n\nexport const clearInProgressSurveyState = (survey: Pick<Survey, 'id' | 'current_iteration'>): void => {\n try {\n localStorage.removeItem(getInProgressSurveyStateKey(survey))\n } catch (e) {\n logger.error('Error clearing in-progress survey state from localStorage', e)\n }\n}\n\nexport function getSurveyContainerClass(survey: Pick<Survey, 'id'>, asSelector = false): string {\n const className = `PostHogSurvey-${survey.id}`\n return asSelector ? `.${className}` : className\n}\n\n/**\n * Get CSS position styles for a popover/modal based on SurveyPosition\n * Used by both surveys and product tours for consistent positioning\n */\nexport function getPopoverPosition(\n type?: SurveyType,\n position: SurveyPosition = SurveyPosition.Right,\n surveyWidgetType?: SurveyWidgetType\n): Record<string, string> {\n if (type === SurveyType.ExternalSurvey) {\n return {}\n }\n\n switch (position) {\n case SurveyPosition.TopLeft:\n return { top: '0', left: '0', transform: 'translate(30px, 30px)' }\n case SurveyPosition.TopRight:\n return { top: '0', right: '0', transform: 'translate(-30px, 30px)' }\n case SurveyPosition.TopCenter:\n return { top: '0', left: '50%', transform: 'translate(-50%, 30px)' }\n case SurveyPosition.MiddleLeft:\n return { top: '50%', left: '0', transform: 'translate(30px, -50%)' }\n case SurveyPosition.MiddleRight:\n return { top: '50%', right: '0', transform: 'translate(-30px, -50%)' }\n case SurveyPosition.MiddleCenter:\n return { top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }\n case SurveyPosition.Left:\n return { left: '30px' }\n case SurveyPosition.Center:\n return { left: '50%', transform: 'translateX(-50%)' }\n default:\n case SurveyPosition.Right:\n return { right: type === SurveyType.Widget && surveyWidgetType === SurveyWidgetType.Tab ? '60px' : '30px' }\n }\n}\n","import DOMPurify from 'dompurify'\n\nimport { PostHog } from '../../posthog-core'\nimport {\n JSONContent,\n ProductTourAppearance,\n ProductTourSelectorError,\n ProductTourStep,\n DEFAULT_PRODUCT_TOUR_APPEARANCE,\n ProductTourWaitPeriod,\n} from '../../posthog-product-tours-types'\nimport { findElement } from './element-inference'\nimport { prepareStylesheet } from '@posthog/browser-common/utils/stylesheet-loader'\nimport { document as _document, window as _window } from '@posthog/browser-common/utils/globals'\nimport { getFontFamily, getContrastingTextColor, hexToRgba } from '../surveys/surveys-extension-utils'\nimport { createLogger } from '@posthog/browser-common/utils/logger'\nimport { localStore } from '../../storage'\nimport { LAST_SEEN_TOUR_DATE_KEY_PREFIX } from './constants'\n\nimport productTourStyles from './product-tour.css'\nimport { isUndefined } from '@posthog/core'\nimport { hasPeriodPassed } from '@posthog/browser-common/utils/matcher-utils'\n\nconst logger = createLogger('[Product Tours]')\n\nconst document = _document as Document\nconst window = _window as Window & typeof globalThis\n\nexport function getProductTourStylesheet(posthog?: PostHog): HTMLStyleElement | null {\n const stylesheet = prepareStylesheet(\n document,\n typeof productTourStyles === 'string' ? productTourStyles : '',\n posthog\n )\n stylesheet?.setAttribute('data-ph-product-tour-style', 'true')\n return stylesheet\n}\n\nexport interface ElementFindResult {\n element: HTMLElement | null\n error: ProductTourSelectorError | null\n matchCount: number\n}\n\nexport function hasElementTarget(step: ProductTourStep): boolean {\n if (step.useManualSelector) {\n return !!step.selector\n }\n return !!step.inferenceData\n}\n\nexport function findElementBySelector(selector: string): ElementFindResult {\n try {\n const elements = document.querySelectorAll(selector)\n\n if (elements.length === 0) {\n return { element: null, error: 'not_found', matchCount: 0 }\n }\n\n const element = elements[0] as HTMLElement\n\n if (!isElementVisible(element)) {\n return { element: null, error: 'not_visible', matchCount: elements.length }\n }\n\n if (elements.length > 1) {\n return { element, error: 'multiple_matches', matchCount: elements.length }\n }\n\n return { element, error: null, matchCount: 1 }\n } catch {\n return { element: null, error: 'not_found', matchCount: 0 }\n }\n}\n\n/**\n * Find element for a step based on its lookup mode.\n * Default: use inference. If useManualSelector is true: use CSS selector.\n */\nexport function findStepElement(step: ProductTourStep): ElementFindResult {\n const useManualSelector = step.useManualSelector ?? false\n\n if (useManualSelector) {\n if (!step.selector) {\n return { element: null, error: 'not_found', matchCount: 0 }\n }\n return findElementBySelector(step.selector)\n }\n\n if (!step.inferenceData) {\n return { element: null, error: 'not_found', matchCount: 0 }\n }\n\n const element = findElement(step.inferenceData)\n return element ? { element, error: null, matchCount: 1 } : { element: null, error: 'not_found', matchCount: 0 }\n}\n\nexport function isElementVisible(element: HTMLElement): boolean {\n const style = window.getComputedStyle(element)\n\n if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {\n return false\n }\n\n const rect = element.getBoundingClientRect()\n if (rect.width === 0 || rect.height === 0) {\n return false\n }\n\n return true\n}\n\nexport function getElementMetadata(element: HTMLElement): {\n tag: string\n id: string | undefined\n classes: string | undefined\n text: string | undefined\n} {\n return {\n tag: element.tagName,\n id: element.id || undefined,\n classes: element.className || undefined,\n text: element.innerText?.slice(0, 100) || undefined,\n }\n}\n\nexport type TooltipPosition = 'top' | 'bottom' | 'left' | 'right'\n\nexport interface PositionResult {\n position: TooltipPosition\n top?: number\n bottom?: number\n left?: number\n right?: number\n arrowOffset: number // pixels from center (positive = right/down)\n}\n\nconst TOOLTIP_MARGIN = 12\nconst VIEWPORT_PADDING = 8\n\nfunction clampToViewport(\n value: number,\n dimension: number,\n viewportDimension: number\n): { clamped: number; offset: number } {\n const min = VIEWPORT_PADDING + dimension / 2\n const max = viewportDimension - VIEWPORT_PADDING - dimension / 2\n const clamped = Math.max(min, Math.min(max, value))\n return { clamped, offset: value - clamped }\n}\n\nexport interface TooltipDimensions {\n width: number\n height: number\n}\n\nexport function calculateTooltipPosition(targetRect: DOMRect, tooltipDimensions: TooltipDimensions): PositionResult {\n const viewportWidth = window.innerWidth\n const viewportHeight = window.innerHeight\n\n const { width, height } = tooltipDimensions\n const spaceAbove = targetRect.top\n const spaceBelow = viewportHeight - targetRect.bottom\n const spaceLeft = targetRect.left\n const spaceRight = viewportWidth - targetRect.right\n\n const targetCenterY = targetRect.top + targetRect.height / 2\n const targetCenterX = targetRect.left + targetRect.width / 2\n\n if (spaceRight >= width + TOOLTIP_MARGIN) {\n // right of element\n const left = targetRect.right + TOOLTIP_MARGIN\n const { clamped: top, offset: arrowOffset } = clampToViewport(targetCenterY, height, viewportHeight)\n return { position: 'right', top, left, arrowOffset }\n }\n if (spaceLeft >= width + TOOLTIP_MARGIN) {\n // left of element\n const right = viewportWidth - targetRect.left + TOOLTIP_MARGIN\n const { clamped: top, offset: arrowOffset } = clampToViewport(targetCenterY, height, viewportHeight)\n return { position: 'left', top, right, arrowOffset }\n }\n if (spaceAbove >= height + TOOLTIP_MARGIN && spaceBelow < height + TOOLTIP_MARGIN) {\n // above element\n const bottom = viewportHeight - targetRect.top + TOOLTIP_MARGIN\n const { clamped: left, offset: arrowOffset } = clampToViewport(targetCenterX, width, viewportWidth)\n return { position: 'top', bottom, left, arrowOffset }\n }\n\n // default: below element\n const top = targetRect.bottom + TOOLTIP_MARGIN\n const { clamped: left, offset: arrowOffset } = clampToViewport(targetCenterX, width, viewportWidth)\n return { position: 'bottom', top, left, arrowOffset }\n}\n\nexport function getSpotlightStyle(targetRect: DOMRect, padding: number = 8): Record<string, string> {\n return {\n top: `${targetRect.top - padding}px`,\n left: `${targetRect.left - padding}px`,\n width: `${targetRect.width + padding * 2}px`,\n height: `${targetRect.height + padding * 2}px`,\n }\n}\n\nexport function addProductTourCSSVariablesToElement(element: HTMLElement, appearance?: ProductTourAppearance): void {\n const merged = { ...DEFAULT_PRODUCT_TOUR_APPEARANCE, ...appearance }\n const style = element.style\n\n // User-customizable variables\n style.setProperty('--ph-tour-background-color', merged.backgroundColor)\n style.setProperty('--ph-tour-text-color', merged.textColor)\n style.setProperty('--ph-tour-button-color', merged.buttonColor)\n style.setProperty('--ph-tour-border-radius', `${merged.borderRadius}px`)\n style.setProperty('--ph-tour-button-border-radius', `${merged.buttonBorderRadius}px`)\n style.setProperty('--ph-tour-border-color', merged.borderColor)\n style.setProperty('--ph-tour-font-family', getFontFamily(merged.fontFamily))\n\n // Derived colors\n style.setProperty('--ph-tour-text-secondary-color', hexToRgba(merged.textColor, 0.6))\n style.setProperty('--ph-tour-branding-text-color', getContrastingTextColor(merged.backgroundColor))\n style.setProperty('--ph-tour-button-text-color', getContrastingTextColor(merged.buttonColor))\n style.setProperty('--ph-tour-box-shadow', merged.boxShadow)\n style.setProperty('--ph-tour-overlay-color', merged.showOverlay ? 'rgba(0, 0, 0, 0.5)' : 'transparent')\n style.setProperty('--ph-tour-z-index', String(merged.zIndex))\n\n // Internal styling variables (not customizable)\n style.setProperty('--ph-tour-button-secondary-color', 'transparent')\n style.setProperty('--ph-tour-button-secondary-text-color', merged.textColor)\n style.setProperty('--ph-tour-max-width', '320px')\n style.setProperty('--ph-tour-padding', '16px')\n}\n\nexport function renderTipTapContent(content: any): string {\n if (!content) {\n return ''\n }\n\n if (typeof content === 'string') {\n return escapeHtml(content)\n }\n\n if (content.type === 'text') {\n let text = escapeHtml(content.text || '')\n\n if (content.marks) {\n for (const mark of content.marks) {\n switch (mark.type) {\n case 'bold':\n text = `<strong>${text}</strong>`\n break\n case 'italic':\n text = `<em>${text}</em>`\n break\n case 'underline':\n text = `<u>${text}</u>`\n break\n case 'strike':\n text = `<s>${text}</s>`\n break\n }\n }\n }\n\n return text\n }\n\n const children = content.content?.map(renderTipTapContent).join('') || ''\n\n switch (content.type) {\n case 'doc':\n return children\n case 'paragraph':\n return `<p>${children}</p>`\n case 'heading': {\n const level = content.attrs?.level || 1\n return `<h${level}>${children}</h${level}>`\n }\n case 'bulletList':\n return `<ul>${children}</ul>`\n case 'orderedList':\n return `<ol>${children}</ol>`\n case 'listItem':\n return `<li>${children}</li>`\n case 'hardBreak':\n return '<br>'\n default:\n return children\n }\n}\n\nexport function normalizeUrl(url: string): string {\n return url.endsWith('/') ? url.slice(0, -1) : url\n}\n\nfunction escapeHtml(text: string): string {\n const div = document.createElement('div')\n div.textContent = text\n return div.innerHTML\n}\n\nexport function resolveStepTranslation(step: ProductTourStep, lang: string | null): ProductTourStep {\n if (!lang || !step.translations) {\n return step\n }\n\n const translations = step.translations\n\n // exact match (en-US === en-US), then base match (en-US falls back to en)\n const t = translations[lang] ?? translations[lang.split('-')[0]]\n\n if (!t) {\n logger.info(`No matching translation for \"${lang}\" in step ${step.id}, using default`)\n return step\n }\n\n const resolved = { ...step }\n\n if (!isUndefined(t.content)) {\n resolved.content = t.content\n }\n\n if (!isUndefined(t.contentHtml)) {\n resolved.contentHtml = t.contentHtml\n }\n\n if (t.buttons && resolved.buttons) {\n resolved.buttons = {\n primary: resolved.buttons.primary && { ...resolved.buttons.primary, ...t.buttons.primary },\n secondary: resolved.buttons.secondary && { ...resolved.buttons.secondary, ...t.buttons.secondary },\n }\n }\n\n if (t.survey && resolved.survey) {\n resolved.survey = { ...resolved.survey, ...t.survey }\n }\n\n return resolved\n}\n\nexport function getStepImageUrls(step: ProductTourStep): string[] {\n const urls: string[] = []\n function walk(node: JSONContent) {\n if (node.type === 'image' && node.attrs?.src) {\n urls.push(node.attrs.src)\n }\n node.content?.forEach(walk)\n }\n if (step.content) {\n walk(step.content)\n }\n return urls\n}\n\nexport function getStepHtml(step: ProductTourStep): string {\n if (step.contentHtml) {\n return DOMPurify.sanitize(step.contentHtml, {\n ADD_TAGS: ['iframe'],\n ADD_ATTR: ['allowfullscreen', 'frameborder', 'referrerpolicy'],\n })\n }\n\n // backwards compat, will be deprecated\n return renderTipTapContent(step.content)\n}\n\nexport function hasTourWaitPeriodPassed(seenTourWaitPeriod?: ProductTourWaitPeriod): boolean {\n if (!seenTourWaitPeriod) {\n return true\n }\n\n const { days, types } = seenTourWaitPeriod\n if (!days || !types || types.length === 0) {\n return true\n }\n\n let mostRecentDate: Date | null = null\n\n for (const type of types) {\n const raw = localStore._get(`${LAST_SEEN_TOUR_DATE_KEY_PREFIX}${type}`)\n if (raw) {\n try {\n const stored = JSON.parse(raw)\n const date = new Date(stored)\n if (!isNaN(date.getTime()) && (!mostRecentDate || date > mostRecentDate)) {\n mostRecentDate = date\n }\n } catch {\n // ignore malformed entries\n }\n }\n }\n\n if (!mostRecentDate) {\n return true\n }\n\n return hasPeriodPassed(days, mostRecentDate)\n}\n","export const satisfiedEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 -960 960 960\" width=\"48\">\n <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\" />\n </svg>\n)\nexport const neutralEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 -960 960 960\" width=\"48\">\n <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\" />\n </svg>\n)\nexport const dissatisfiedEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 -960 960 960\" width=\"48\">\n <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\" />\n </svg>\n)\nexport const veryDissatisfiedEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 -960 960 960\" width=\"48\">\n <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\" />\n </svg>\n)\nexport const verySatisfiedEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 -960 960 960\" width=\"48\">\n <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\" />\n </svg>\n)\nexport const thumbsUpEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 0 24 24\" width=\"48\">\n <path d=\"M2 20h2c.55 0 1-.45 1-1v-9c0-.55-.45-1-1-1H2v11zm19.83-7.12c.11-.25.17-.52.17-.8V11c0-1.1-.9-2-2-2h-5.5l.92-4.65c.05-.22.02-.46-.08-.66-.23-.45-.52-.86-.88-1.22L14 2 7.59 8.41C7.21 8.79 7 9.3 7 9.83v7.84C7 18.95 8.05 20 9.34 20h8.11c.7 0 1.36-.37 1.72-.97l2.66-6.15z\" />\n </svg>\n)\nexport const thumbsDownEmoji = (\n <svg className=\"emoji-svg\" xmlns=\"http://www.w3.org/2000/svg\" height=\"48\" viewBox=\"0 0 24 24\" width=\"48\">\n <path d=\"M22 4h-2c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h2V4zM2.17 11.12c-.11.25-.17.52-.17.8V13c0 1.1.9 2 2 2h5.5l-.92 4.65c-.05.22-.02.46.08.66.23.45.52.86.88 1.22L10 22l6.41-6.41c.38-.38.59-.89.59-1.42V6.34C17 5.05 15.95 4 14.66 4H6.55c-.7 0-1.36.37-1.72.97l-2.66 6.15z\" />\n </svg>\n)\nexport const cancelSVG = ({ fill = 'currentColor' }: { fill?: string } = {}) => (\n <svg\n width=\"12\"\n height=\"12\"\n viewBox=\"0 0 12 12\"\n fill={fill}\n xmlns=\"http://www.w3.org/2000/svg\"\n aria-labelledby=\"close-survey-title-adam\"\n >\n <title id=\"close-survey-title\" className=\"adam-testing\">\n Close survey\n </title>\n <path\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n 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\"\n fill={fill}\n />\n </svg>\n)\nexport const IconPosthogLogo = (\n <svg width=\"77\" height=\"14\" viewBox=\"0 0 77 14\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <g clip-path=\"url(#clip0_2415_6911)\">\n <mask\n id=\"mask0_2415_6911\"\n style={{ maskType: 'luminance' }}\n maskUnits=\"userSpaceOnUse\"\n x=\"0\"\n y=\"0\"\n width=\"77\"\n height=\"14\"\n >\n <path d=\"M0.5 0H76.5V14H0.5V0Z\" fill=\"white\" />\n </mask>\n <g mask=\"url(#mask0_2415_6911)\">\n <path\n 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\"\n fill=\"#1D4AFF\"\n />\n <path\n 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\"\n fill=\"#F9BD2B\"\n />\n <path\n 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\"\n fill=\"currentColor\"\n />\n <path\n 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\"\n fill=\"#1D4AFF\"\n />\n <path\n 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\"\n fill=\"#F54E00\"\n />\n <path\n 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\"\n fill=\"currentColor\"\n />\n </g>\n </g>\n <defs>\n <clipPath id=\"clip0_2415_6911\">\n <rect width=\"76\" height=\"14\" fill=\"white\" transform=\"translate(0.5)\" />\n </clipPath>\n </defs>\n </svg>\n)\nexport const checkSVG = (\n <svg width=\"16\" height=\"12\" viewBox=\"0 0 16 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path\n 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\"\n fill=\"currentColor\"\n />\n </svg>\n)\n","import { h, ComponentChildren } from 'preact'\nimport { ProductTourDisplayFrequency, ProductTourStep } from '../../../posthog-product-tours-types'\nimport { getStepHtml } from '../product-tours-utils'\nimport { cancelSVG } from '../../surveys/icons'\n\nexport interface ProductTourBannerProps {\n step: ProductTourStep\n onDismiss: () => void\n onActionClick?: () => void\n displayFrequency?: ProductTourDisplayFrequency\n}\n\ninterface BannerWrapperProps {\n class: string\n children: ComponentChildren\n}\n\ninterface LinkWrapperProps extends BannerWrapperProps {\n href: string\n onClick?: () => void\n}\n\ninterface ButtonWrapperProps extends BannerWrapperProps {\n onClick: () => void\n}\n\nfunction LinkWrapper({ class: className, href, onClick, children }: LinkWrapperProps): h.JSX.Element {\n return (\n <a class={className} href={href} target=\"_blank\" rel=\"noopener noreferrer\" onClick={onClick}>\n {children}\n </a>\n )\n}\n\nfunction ButtonWrapper({ class: className, onClick, children }: ButtonWrapperProps): h.JSX.Element {\n return (\n <div\n class={className}\n role=\"button\"\n tabIndex={0}\n onClick={onClick}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault()\n onClick()\n }\n }}\n style={{ cursor: 'pointer' }}\n >\n {children}\n </div>\n )\n}\n\nfunction StaticWrapper({ class: className, children }: BannerWrapperProps): h.JSX.Element {\n return <div class={className}>{children}</div>\n}\n\nexport function ProductTourBanner(props: ProductTourBannerProps) {\n return (\n <div class=\"ph-tour-banner-wrapper\">\n <div class=\"ph-tour-banner-slide\">\n <ProductTourBannerInner {...props} />\n </div>\n </div>\n )\n}\n\nfunction ProductTourBannerInner({\n step,\n onDismiss,\n onActionClick,\n displayFrequency,\n}: ProductTourBannerProps): h.JSX.Element {\n const config = step.bannerConfig ?? { behavior: 'sticky' }\n const action = config.action\n\n // \"always\" display frequency means no dismiss button\n const showDismissButton = displayFrequency !== 'always'\n\n const classNames = [\n 'ph-tour-banner',\n config.behavior === 'sticky' && 'ph-tour-banner--sticky',\n config.behavior === 'custom' && 'ph-tour-banner--custom',\n ]\n .filter(Boolean)\n .join(' ')\n\n const content = (\n <>\n <div class=\"ph-tour-banner-content\" dangerouslySetInnerHTML={{ __html: getStepHtml(step) }} />\n\n {showDismissButton && (\n <button\n class=\"ph-tour-banner-dismiss\"\n onClick={(e) => {\n e.stopPropagation()\n e.preventDefault()\n onDismiss()\n }}\n aria-label=\"Close banner\"\n >\n {cancelSVG()}\n </button>\n )}\n </>\n )\n\n if (action?.type === 'link' && action.link) {\n return (\n <LinkWrapper class={classNames} href={action.link} onClick={onActionClick}>\n {content}\n </LinkWrapper>\n )\n }\n\n if (action?.type === 'trigger_tour' && onActionClick) {\n return (\n <ButtonWrapper class={classNames} onClick={onActionClick}>\n {content}\n </ButtonWrapper>\n )\n }\n\n return <StaticWrapper class={classNames}>{content}</StaticWrapper>\n}\n","import { h } from 'preact'\nimport { useState, useRef, useEffect } from 'preact/hooks'\nimport { ProductTourStep, ProductTourAppearance, ProductTourSurveyQuestion } from '../../../posthog-product-tours-types'\nimport { cancelSVG, IconPosthogLogo } from '../../surveys/icons'\nimport {\n dissatisfiedEmoji,\n neutralEmoji,\n satisfiedEmoji,\n veryDissatisfiedEmoji,\n verySatisfiedEmoji,\n} from '../../surveys/icons'\n\nexport interface ProductTourSurveyStepInnerProps {\n step: ProductTourStep\n appearance?: ProductTourAppearance\n stepIndex: number\n totalSteps: number\n onPrevious?: () => void\n onSubmit?: (response: string | number | null) => void\n onDismiss?: () => void\n}\n\nconst threeScaleEmojis = [dissatisfiedEmoji, neutralEmoji, satisfiedEmoji]\nconst fiveScaleEmojis = [veryDissatisfiedEmoji, dissatisfiedEmoji, neutralEmoji, satisfiedEmoji, verySatisfiedEmoji]\n\nfunction getScaleNumbers(scale: number): number[] {\n switch (scale) {\n case 5:\n return [1, 2, 3, 4, 5]\n case 10:\n return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n default:\n return [1, 2, 3, 4, 5]\n }\n}\n\nfunction OpenTextInput({\n value,\n onChange,\n onSubmit,\n isInteractive,\n}: {\n value: string\n onChange: (text: string) => void\n onSubmit?: () => void\n isInteractive: boolean\n}): h.JSX.Element {\n const inputRef = useRef<HTMLTextAreaElement>(null)\n\n useEffect(() => {\n if (isInteractive) {\n setTimeout(() => inputRef.current?.focus(), 100)\n }\n }, [isInteractive])\n\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Enter' && e.metaKey && isInteractive) {\n e.preventDefault()\n onSubmit?.()\n }\n }\n\n return (\n <textarea\n ref={inputRef}\n class=\"ph-tour-survey-textarea\"\n rows={3}\n placeholder=\"Your feedback (optional)...\"\n value={value}\n onInput={(e) => onChange((e.target as HTMLTextAreaElement).value)}\n onKeyDown={handleKeyDown}\n disabled={!isInteractive}\n style={isInteractive ? undefined : { cursor: 'default' }}\n />\n )\n}\n\nfunction RatingInput({\n survey,\n onSubmit,\n isInteractive,\n}: {\n survey: ProductTourSurveyQuestion\n onSubmit?: (rating: number) => void\n isInteractive: boolean\n}): h.JSX.Element {\n const [selectedRating, setSelectedRating] = useState<number | null>(null)\n const display = survey.display || 'emoji'\n const scale = survey.scale || 5\n\n const handleSelect = (rating: number) => {\n if (!isInteractive) {\n return\n }\n setSelectedRating(rating)\n // Auto-submit on selection for ratings\n onSubmit?.(rating)\n }\n\n if (display === 'emoji') {\n const emojis = scale === 3 ? threeScaleEmojis : fiveScaleEmojis\n return (\n <div class=\"ph-tour-survey-rating-container\">\n <div class=\"ph-tour-survey-rating-emoji\">\n {emojis.map((emoji, idx) => {\n const rating = idx + 1\n const isActive = selectedRating === rating\n return (\n <button\n key={idx}\n type=\"button\"\n class={`ph-tour-survey-emoji-button ${isActive ? 'ph-tour-survey-emoji-button--active' : ''}`}\n onClick={() => handleSelect(rating)}\n style={isInteractive ? undefined : { cursor: 'default' }}\n aria-label={`Rate ${rating}`}\n >\n {emoji}\n </button>\n )\n })}\n </div>\n {(survey.lowerBoundLabel || survey.upperBoundLabel) && (\n <div class=\"ph-tour-survey-rating-labels\">\n <span>{survey.lowerBoundLabel}</span>\n <span>{survey.upperBoundLabel}</span>\n </div>\n )}\n </div>\n )\n }\n\n // Number display\n const numbers = getScaleNumbers(scale)\n return (\n <div class=\"ph-tour-survey-rating-container\">\n <div\n class=\"ph-tour-survey-rating-numbers\"\n style={{ gridTemplateColumns: `repeat(${numbers.length}, minmax(0, 1fr))` }}\n >\n {numbers.map((num) => {\n const isActive = selectedRating === num\n return (\n <button\n key={num}\n type=\"button\"\n class={`ph-tour-survey-number-button ${isActive ? 'ph-tour-survey-number-button--active' : ''}`}\n onClick={() => handleSelect(num)}\n style={isInteractive ? undefined : { cursor: 'default' }}\n aria-label={`Rate ${num}`}\n >\n {num}\n </button>\n )\n })}\n </div>\n {(survey.lowerBoundLabel || survey.upperBoundLabel) && (\n <div class=\"ph-tour-survey-rating-labels\">\n <span>{survey.lowerBoundLabel}</span>\n <span>{survey.upperBoundLabel}</span>\n </div>\n )}\n </div>\n )\n}\n\nexport function ProductTourSurveyStepInner({\n step,\n appearance,\n stepIndex,\n totalSteps,\n onPrevious,\n onSubmit,\n onDismiss,\n}: ProductTourSurveyStepInnerProps): h.JSX.Element {\n const [textValue, setTextValue] = useState('')\n const survey = step.survey\n const whiteLabel = appearance?.whiteLabel ?? false\n const isFirstStep = stepIndex === 0\n const isOpenText = survey?.type === 'open'\n\n const isInteractive = !!(onPrevious || onSubmit || onDismiss)\n const cursorStyle = isInteractive ? undefined : { cursor: 'default' }\n\n const handleTextSubmit = () => {\n onSubmit?.(textValue.trim() || null)\n }\n\n if (!survey) {\n return <div />\n }\n\n return (\n <>\n <button class=\"ph-tour-dismiss\" onClick={onDismiss} aria-label=\"Close survey\" style={cursorStyle}>\n {cancelSVG()}\n </button>\n\n <div class=\"ph-tour-survey-question\">{survey.questionText}</div>\n\n {isOpenText ? (\n <OpenTextInput\n value={textValue}\n onChange={setTextValue}\n onSubmit={handleTextSubmit}\n isInteractive={isInteractive}\n />\n ) : (\n <RatingInput survey={survey} onSubmit={onSubmit} isInteractive={isInteractive} />\n )}\n\n <div class=\"ph-tour-footer\">\n <span class=\"ph-tour-progress\">\n {stepIndex + 1} of {totalSteps}\n </span>\n\n <div class=\"ph-tour-buttons\">\n {!isFirstStep && (\n <button\n class=\"ph-tour-button ph-tour-button--secondary\"\n onClick={onPrevious}\n style={cursorStyle}\n >\n {survey.backButtonText || 'Back'}\n </button>\n )}\n {isOpenText && (\n <button\n class=\"ph-tour-button ph-tour-button--primary\"\n onClick={handleTextSubmit}\n style={cursorStyle}\n >\n {survey.submitButtonText || 'Submit'}\n </button>\n )}\n </div>\n </div>\n\n {!whiteLabel && (\n <a\n href={isInteractive ? 'https://posthog.com/product-tours' : undefined}\n target={isInteractive ? '_blank' : undefined}\n rel={isInteractive ? 'noopener noreferrer' : undefined}\n class=\"ph-tour-branding\"\n style={isInteractive ? undefined : { cursor: 'default', pointerEvents: 'none' }}\n >\n Survey by {IconPosthogLogo}\n </a>\n )}\n </>\n )\n}\n","import { h } from 'preact'\nimport { ProductTourStep, ProductTourAppearance, ProductTourStepButton } from '../../../posthog-product-tours-types'\nimport { getStepHtml, hasElementTarget } from '../product-tours-utils'\nimport { IconPosthogLogo, cancelSVG } from '../../surveys/icons'\n\ninterface TourButtonProps {\n button: ProductTourStepButton\n variant: 'primary' | 'secondary'\n onClick: (button: ProductTourStepButton) => void\n cursorStyle?: h.JSX.CSSProperties\n}\n\nfunction TourButton({ button, variant, onClick, cursorStyle }: TourButtonProps): h.JSX.Element {\n const className = `ph-tour-button ph-tour-button--${variant}`\n\n if (button.action === 'link' && button.link) {\n return (\n <a\n href={button.link}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n class={className}\n onClick={() => onClick(button)} // track interaction & dismiss tour\n >\n {button.text}\n </a>\n )\n }\n\n return (\n <button class={className} onClick={() => onClick(button)} style={cursorStyle}>\n {button.text}\n </button>\n )\n}\n\nexport interface ProductTourTooltipInnerProps {\n step: ProductTourStep\n appearance?: ProductTourAppearance\n stepIndex: number\n totalSteps: number\n onNext?: () => void\n onPrevious?: () => void\n onDismiss?: () => void\n onButtonClick?: (button: ProductTourStepButton) => void\n}\n\nexport function ProductTourTooltipInner({\n step,\n appearance,\n stepIndex,\n totalSteps,\n onNext,\n onPrevious,\n onDismiss,\n onButtonClick,\n}: ProductTourTooltipInnerProps): h.JSX.Element {\n const whiteLabel = appearance?.whiteLabel ?? false\n const isLastStep = stepIndex >= totalSteps - 1\n const isFirstStep = stepIndex === 0\n const showDefaultButtons = !step.buttons && (step.progressionTrigger === 'button' || !hasElementTarget(step))\n const hasCustomButtons = !!step.buttons\n\n const isInteractive = !!(onNext || onPrevious || onDismiss || onButtonClick)\n const cursorStyle = isInteractive ? undefined : { cursor: 'default' }\n\n const showPostHogBranding = !whiteLabel && isFirstStep\n\n const handleButtonClick = (button: ProductTourStepButton) => {\n if (onButtonClick) {\n onButtonClick(button)\n }\n }\n\n return (\n <>\n <button class=\"ph-tour-dismiss\" onClick={onDismiss} aria-label=\"Close tour\" style={cursorStyle}>\n {cancelSVG()}\n </button>\n\n <div class=\"ph-tour-content\" dangerouslySetInnerHTML={{ __html: getStepHtml(step) }} />\n\n <div class=\"ph-tour-footer\">\n {totalSteps > 1 && (\n <span class=\"ph-tour-progress\">\n {stepIndex + 1} of {totalSteps}\n </span>\n )}\n\n <div class=\"ph-tour-buttons\">\n {/* Default buttons for tours without custom buttons */}\n {showDefaultButtons && (\n <>\n {!isFirstStep && (\n <button\n class=\"ph-tour-button ph-tour-button--secondary\"\n onClick={onPrevious}\n style={cursorStyle}\n >\n Back\n </button>\n )}\n <button class=\"ph-tour-button ph-tour-button--primary\" onClick={onNext} style={cursorStyle}>\n {isLastStep ? 'Done' : 'Next'}\n </button>\n </>\n )}\n\n {/* Custom buttons */}\n {hasCustomButtons && (\n <>\n {step.buttons?.secondary && (\n <TourButton\n button={step.buttons.secondary}\n variant=\"secondary\"\n onClick={handleButtonClick}\n cursorStyle={cursorStyle}\n />\n )}\n {step.buttons?.primary && (\n <TourButton\n button={step.buttons.primary}\n variant=\"primary\"\n onClick={handleButtonClick}\n cursorStyle={cursorStyle}\n />\n )}\n </>\n )}\n </div>\n </div>\n\n {showPostHogBranding && (\n <a\n href={isInteractive ? 'https://posthog.com/docs/product-tours' : undefined}\n target={isInteractive ? '_blank' : undefined}\n rel={isInteractive ? 'noopener noreferrer' : undefined}\n class=\"ph-tour-branding\"\n style={isInteractive ? undefined : { cursor: 'default', pointerEvents: 'none' }}\n >\n Tour by {IconPosthogLogo}\n </a>\n )}\n </>\n )\n}\n","import { render, JSX } from 'preact'\n\nimport { PostHog } from '../../posthog-core'\nimport { ProductTourStep, ProductTourAppearance } from '../../posthog-product-tours-types'\nimport { document as _document } from '@posthog/browser-common/utils/globals'\nimport { ProductTourBanner } from './components/ProductTourBanner'\nimport { ProductTourSurveyStepInner } from './components/ProductTourSurveyStepInner'\nimport { ProductTourTooltipInner } from './components/ProductTourTooltipInner'\nimport { getProductTourStylesheet, addProductTourCSSVariablesToElement, hasElementTarget } from './product-tours-utils'\n\nconst document = _document as Document\n\nexport interface RenderProductTourPreviewOptions {\n step: ProductTourStep\n appearance?: ProductTourAppearance\n parentElement: HTMLElement\n stepIndex?: number\n totalSteps?: number\n style?: JSX.CSSProperties\n posthog?: PostHog\n}\n\nexport function renderProductTourPreview({\n step,\n appearance,\n parentElement,\n stepIndex = 0,\n totalSteps = 1,\n style,\n posthog,\n}: RenderProductTourPreviewOptions): void {\n parentElement.innerHTML = ''\n\n const shadowHost = document.createElement('div')\n addProductTourCSSVariablesToElement(shadowHost, appearance)\n parentElement.appendChild(shadowHost)\n const shadow = shadowHost.attachShadow({ mode: 'open' })\n\n const stylesheet = getProductTourStylesheet(posthog)\n if (stylesheet) {\n shadow.appendChild(stylesheet)\n }\n\n const renderTarget = document.createElement('div')\n shadow.appendChild(renderTarget)\n\n const isSurveyStep = step.type === 'survey'\n const isBannerStep = step.type === 'banner'\n const isModal = !hasElementTarget(step)\n const tooltipClass = `ph-tour-tooltip${isModal ? ' ph-tour-tooltip--modal' : ''}${isSurveyStep ? ' ph-tour-survey-step' : ''}`\n\n if (isBannerStep) {\n render(\n <div class=\"ph-tour-container\">\n <ProductTourBanner step={step} onDismiss={() => {}} />\n </div>,\n renderTarget\n )\n return\n }\n\n render(\n <div class=\"ph-tour-container\">\n <div\n class={tooltipClass}\n style={{\n position: 'relative',\n animation: 'none',\n ...(step.maxWidth && { width: `${step.maxWidth}px`, maxWidth: `${step.maxWidth}px` }),\n ...style,\n }}\n >\n {isSurveyStep ? (\n <ProductTourSurveyStepInner\n step={step}\n appearance={appearance}\n stepIndex={stepIndex}\n totalSteps={totalSteps}\n />\n ) : (\n <ProductTourTooltipInner\n step={step}\n appearance={appearance}\n stepIndex={stepIndex}\n totalSteps={totalSteps}\n />\n )}\n </div>\n </div>,\n renderTarget\n )\n}\n"],"names":["d","w","_","win","window","global","globalThis","globals_document","document","XMLHttpRequest","entries","Object","setPrototypeOf","isFrozen","getPrototypeOf","getOwnPropertyDescriptor","freeze","seal","create","_ref","Reflect","apply","construct","x","func","thisArg","_len","arguments","length","args","Array","_key","Func","_len2","_key2","arrayForEach","unapply","forEach","arrayLastIndexOf","lastIndexOf","arrayPop","pop","arrayPush","push","arraySplice","splice","arrayIsArray","isArray","stringToLowerCase","String","toLowerCase","stringToString","toString","stringMatch","match","stringReplace","replace","stringIndexOf","indexOf","stringTrim","trim","numberToString","Number","booleanToString","Boolean","prototype","bigintToString","BigInt","symbolToString","Symbol","objectHasOwnProperty","hasOwnProperty","objectToString","regExpTest","RegExp","test","typeErrorCreate","TypeError","_len4","_key4","lastIndex","_len3","_key3","addToSet","set","array","transformCaseFunc","undefined","l","element","lcElement","cleanArray","index","clone","object","newObject","_ref2","_ref3","_slicedToArray","property","value","constructor","lookupGetter","prop","desc","get","maybeCall","consoleLike","_unused","valueAsRecord","valueToString","stringified","DEFAULT_PRODUCT_TOUR_APPEARANCE","backgroundColor","textColor","buttonColor","borderRadius","buttonBorderRadius","borderColor","fontFamily","boxShadow","showOverlay","whiteLabel","dismissOnClickOutside","zIndex","type_utils_toString","isUndefined","_createLogger","prefix","_log","level","consoleMethod","debug","info","warn","error","_len5","_key5","critical","_len6","_key6","createLogger","additionalPrefix","fn","console","log","bind","_temp","debugEnabled","logger","external_globals_mjs_window","POSTHOG_DEBUG","consoleLog","uninitializedWarning","methodName","options","Math","trunc","v","ceil","floor","isInteger","call","isNumber","isFinite","crypto","t","r","u","i","o","f","c","n","e","__b","a","__r","diffed","__c","m","unmount","p","__","s","__h","__H","D","__N","setState","__f","props","some","this","shouldComponentUpdate","componentWillUpdate","__e","y","j","shift","__P","z","B","__v","__k","__m","requestAnimationFrame","filter","k","clearTimeout","cancelAnimationFrame","setTimeout","C","BLACK_TEXT_COLOR","defaultSurveyAppearance","hex2rgb","startsWith","hexColor","parseInt","slice","getContrastingTextColor","color","rgb","nameColorToHex","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","honeydew","hotpink","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgrey","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","colorMatch","g","b","sqrt","createContext","isPreviewMode","previewPageIndex","onPopupSurveyDismissed","isPopup","onPreviewSubmit","onPreviewBack","surveySubmissionId","properties","surveyLanguage","_document","hasElementTarget","step","useManualSelector","selector","inferenceData","renderTipTapContent","content","_content$content","escapeHtml","type","text","marks","mark","children","map","join","_content$attrs","attrs","div","createElement","textContent","innerHTML","getStepHtml","contentHtml","DOMPurify","sanitize","ADD_TAGS","ADD_ATTR","satisfiedEmoji","_jsx","className","xmlns","height","viewBox","width","neutralEmoji","dissatisfiedEmoji","veryDissatisfiedEmoji","verySatisfiedEmoji","cancelSVG","_ref$fill","fill","_jsxs","id","IconPosthogLogo","style","maskType","maskUnits","mask","transform","LinkWrapper","class","href","target","rel","onClick","ButtonWrapper","role","tabIndex","onKeyDown","key","preventDefault","cursor","StaticWrapper","ProductTourBanner","ProductTourBannerInner","_extends","_ref4","_step$bannerConfig","onDismiss","onActionClick","config","bannerConfig","behavior","action","showDismissButton","displayFrequency","classNames","_Fragment","dangerouslySetInnerHTML","__html","stopPropagation","link","threeScaleEmojis","fiveScaleEmojis","OpenTextInput","onChange","onSubmit","isInteractive","inputRef","T","current","useRef","__s","_inputRef$current","focus","useEffect","ref","rows","placeholder","onInput","handleKeyDown","metaKey","disabled","RatingInput","survey","_useState","useState","selectedRating","setSelectedRating","scale","handleSelect","rating","display","emoji","idx","lowerBoundLabel","upperBoundLabel","numbers","getScaleNumbers","gridTemplateColumns","num","ProductTourSurveyStepInner","_appearance$whiteLabe","appearance","stepIndex","totalSteps","onPrevious","_useState2","textValue","setTextValue","isFirstStep","isOpenText","cursorStyle","handleTextSubmit","questionText","backButtonText","submitButtonText","pointerEvents","TourButton","button","variant","ProductTourTooltipInner","_step$buttons","_step$buttons2","onNext","onButtonClick","isLastStep","showDefaultButtons","buttons","progressionTrigger","hasCustomButtons","showPostHogBranding","handleButtonClick","secondary","primary","renderProductTourPreview","parentElement","_ref$stepIndex","_ref$totalSteps","posthog","shadowHost","hex","merged","setProperty","defaultFontStack","getFontFamily","addProductTourCSSVariablesToElement","appendChild","shadow","attachShadow","mode","stylesheet","prepareStylesheet","innerText","context","prepareExternalDependencyStylesheet","_context$config","isFunction","prepare_external_dependency_stylesheet","getStylesheetPreparer","setAttribute","getProductTourStylesheet","renderTarget","isSurveyStep","isBannerStep","tooltipClass","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