/home/egir5919/public_html/wp-content/plugins/surerank/build/vendor-536eaa00/index.js
"use strict";(globalThis.webpackChunksurerank=globalThis.webpackChunksurerank||[]).push([[359],{51893(e,t,i){i.d(t,{A:()=>m});var r=function(){function e(e){var t=this;this._insertTag=function(e){t.container.insertBefore(e,0===t.tags.length?t.insertionPoint?t.insertionPoint.nextSibling:t.prepend?t.container.firstChild:t.before:t.tags[t.tags.length-1].nextSibling),t.tags.push(e)},this.isSpeedy=void 0===e.speedy||e.speedy,this.tags=[],this.ctr=0,this.nonce=e.nonce,this.key=e.key,this.container=e.container,this.prepend=e.prepend,this.insertionPoint=e.insertionPoint,this.before=null}var t=e.prototype;return t.hydrate=function(e){e.forEach(this._insertTag)},t.insert=function(e){this.ctr%(this.isSpeedy?65e3:1)===0&&this._insertTag(function(e){var t=document.createElement("style");return t.setAttribute("data-emotion",e.key),void 0!==e.nonce&&t.setAttribute("nonce",e.nonce),t.appendChild(document.createTextNode("")),t.setAttribute("data-s",""),t}(this));var t=this.tags[this.tags.length-1];if(this.isSpeedy){var i=function(e){if(e.sheet)return e.sheet;for(var t=0;t<document.styleSheets.length;t++)if(document.styleSheets[t].ownerNode===e)return document.styleSheets[t]}(t);try{i.insertRule(e,i.cssRules.length)}catch(r){}}else t.appendChild(document.createTextNode(e));this.ctr++},t.flush=function(){this.tags.forEach(function(e){var t;return null==(t=e.parentNode)?void 0:t.removeChild(e)}),this.tags=[],this.ctr=0},e}(),n=i(40390),s=i(19735),o=i(24534),a=i(50483),c=i(49503),l=i(73716),d=function(e,t,i){for(var r=0,s=0;r=s,s=(0,n.se)(),38===r&&12===s&&(t[i]=1),!(0,n.Sh)(s);)(0,n.K2)();return(0,n.di)(e,n.G1)},u=new WeakMap,g=function(e){if("rule"===e.type&&e.parent&&!(e.length<1)){for(var t=e.value,i=e.parent,r=e.column===i.column&&e.line===i.line;"rule"!==i.type;)if(!(i=i.parent))return;if((1!==e.props.length||58===t.charCodeAt(0)||u.get(i))&&!r){u.set(e,!0);for(var o=[],a=function(e,t){return(0,n.VF)(function(e,t){var i=-1,r=44;do{switch((0,n.Sh)(r)){case 0:38===r&&12===(0,n.se)()&&(t[i]=1),e[i]+=d(n.G1-1,t,i);break;case 2:e[i]+=(0,n.Tb)(r);break;case 4:if(44===r){e[++i]=58===(0,n.se)()?"&\f":"",t[i]=e[i].length;break}default:e[i]+=(0,s.HT)(r)}}while(r=(0,n.K2)());return e}((0,n.c4)(e),t))}(t,o),c=i.props,l=0,g=0;l<a.length;l++)for(var h=0;h<c.length;h++,g++)e.props[g]=o[l]?a[l].replace(/&\f/g,c[h]):c[h]+" "+a[l]}}},h=function(e){if("decl"===e.type){var t=e.value;108===t.charCodeAt(0)&&98===t.charCodeAt(2)&&(e.return="",e.value="")}};function p(e,t){switch((0,s.tW)(e,t)){case 5103:return o.j+"print-"+e+e;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return o.j+e+e;case 5349:case 4246:case 4810:case 6968:case 2756:return o.j+e+o.vd+e+o.MS+e+e;case 6828:case 4268:return o.j+e+o.MS+e+e;case 6165:return o.j+e+o.MS+"flex-"+e+e;case 5187:return o.j+e+(0,s.HC)(e,/(\w+).+(:[^]+)/,o.j+"box-$1$2"+o.MS+"flex-$1$2")+e;case 5443:return o.j+e+o.MS+"flex-item-"+(0,s.HC)(e,/flex-|-self/,"")+e;case 4675:return o.j+e+o.MS+"flex-line-pack"+(0,s.HC)(e,/align-content|flex-|-self/,"")+e;case 5548:return o.j+e+o.MS+(0,s.HC)(e,"shrink","negative")+e;case 5292:return o.j+e+o.MS+(0,s.HC)(e,"basis","preferred-size")+e;case 6060:return o.j+"box-"+(0,s.HC)(e,"-grow","")+o.j+e+o.MS+(0,s.HC)(e,"grow","positive")+e;case 4554:return o.j+(0,s.HC)(e,/([^-])(transform)/g,"$1"+o.j+"$2")+e;case 6187:return(0,s.HC)((0,s.HC)((0,s.HC)(e,/(zoom-|grab)/,o.j+"$1"),/(image-set)/,o.j+"$1"),e,"")+e;case 5495:case 3959:return(0,s.HC)(e,/(image-set\([^]*)/,o.j+"$1$`$1");case 4968:return(0,s.HC)((0,s.HC)(e,/(.+:)(flex-)?(.*)/,o.j+"box-pack:$3"+o.MS+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+o.j+e+e;case 4095:case 3583:case 4068:case 2532:return(0,s.HC)(e,/(.+)-inline(.+)/,o.j+"$1$2")+e;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if((0,s.b2)(e)-1-t>6)switch((0,s.wN)(e,t+1)){case 109:if(45!==(0,s.wN)(e,t+4))break;case 102:return(0,s.HC)(e,/(.+:)(.+)-([^]+)/,"$1"+o.j+"$2-$3$1"+o.vd+(108==(0,s.wN)(e,t+3)?"$3":"$2-$3"))+e;case 115:return~(0,s.K5)(e,"stretch")?p((0,s.HC)(e,"stretch","fill-available"),t)+e:e}break;case 4949:if(115!==(0,s.wN)(e,t+1))break;case 6444:switch((0,s.wN)(e,(0,s.b2)(e)-3-(~(0,s.K5)(e,"!important")&&10))){case 107:return(0,s.HC)(e,":",":"+o.j)+e;case 101:return(0,s.HC)(e,/(.+:)([^;!]+)(;|!.+)?/,"$1"+o.j+(45===(0,s.wN)(e,14)?"inline-":"")+"box$3$1"+o.j+"$2$3$1"+o.MS+"$2box$3")+e}break;case 5936:switch((0,s.wN)(e,t+11)){case 114:return o.j+e+o.MS+(0,s.HC)(e,/[svh]\w+-[tblr]{2}/,"tb")+e;case 108:return o.j+e+o.MS+(0,s.HC)(e,/[svh]\w+-[tblr]{2}/,"tb-rl")+e;case 45:return o.j+e+o.MS+(0,s.HC)(e,/[svh]\w+-[tblr]{2}/,"lr")+e}return o.j+e+o.MS+e+e}return e}var _=[function(e,t,i,r){if(e.length>-1&&!e.return)switch(e.type){case o.LU:e.return=p(e.value,e.length);break;case o.Sv:return(0,a.l)([(0,n.C)(e,{value:(0,s.HC)(e.value,"@","@"+o.j)})],r);case o.XZ:if(e.length)return(0,s.kg)(e.props,function(t){switch((0,s.YW)(t,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return(0,a.l)([(0,n.C)(e,{props:[(0,s.HC)(t,/:(read-\w+)/,":"+o.vd+"$1")]})],r);case"::placeholder":return(0,a.l)([(0,n.C)(e,{props:[(0,s.HC)(t,/:(plac\w+)/,":"+o.j+"input-$1")]}),(0,n.C)(e,{props:[(0,s.HC)(t,/:(plac\w+)/,":"+o.vd+"$1")]}),(0,n.C)(e,{props:[(0,s.HC)(t,/:(plac\w+)/,o.MS+"input-$1")]})],r)}return""})}}],m=function(e){var t=e.key;if("css"===t){var i=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(i,function(e){-1!==e.getAttribute("data-emotion").indexOf(" ")&&(document.head.appendChild(e),e.setAttribute("data-s",""))})}var n,s,o=e.stylisPlugins||_,d={},u=[];n=e.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+t+' "]'),function(e){for(var t=e.getAttribute("data-emotion").split(" "),i=1;i<t.length;i++)d[t[i]]=!0;u.push(e)});var p,m=[g,h],f=[a.A,(0,c.MY)(function(e){p.insert(e)})],w=(0,c.r1)(m.concat(o,f));s=function(e,t,i,r){p=i,(0,a.l)((0,l.wE)(e?e+"{"+t.styles+"}":t.styles),w),r&&(y.inserted[t.name]=!0)};var y={key:t,sheet:new r({key:t,container:n,nonce:e.nonce,speedy:e.speedy,prepend:e.prepend,insertionPoint:e.insertionPoint}),nonce:e.nonce,inserted:d,registered:{},insert:s};return y.sheet.hydrate(u),y}},11456(e,t,i){i.d(t,{AH:()=>A,Y:()=>I,i7:()=>R});var r=i(51609),n=i(51893),s=function(e,t,i){var r=e.key+"-"+t.name;!1===i&&void 0===e.registered[r]&&(e.registered[r]=t.styles)},o={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,scale:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1};function a(e){var t=Object.create(null);return function(i){return void 0===t[i]&&(t[i]=e(i)),t[i]}}var c=/[A-Z]|^ms/g,l=/_EMO_([^_]+?)_([^]*?)_EMO_/g,d=function(e){return 45===e.charCodeAt(1)},u=function(e){return null!=e&&"boolean"!==typeof e},g=a(function(e){return d(e)?e:e.replace(c,"-$&").toLowerCase()}),h=function(e,t){switch(e){case"animation":case"animationName":if("string"===typeof t)return t.replace(l,function(e,t,i){return _={name:t,styles:i,next:_},t})}return 1===o[e]||d(e)||"number"!==typeof t||0===t?t:t+"px"};function p(e,t,i){if(null==i)return"";if(void 0!==i.__emotion_styles)return i;switch(typeof i){case"boolean":return"";case"object":if(1===i.anim)return _={name:i.name,styles:i.styles,next:_},i.name;var r=i;if(void 0!==r.styles){var n=r.next;if(void 0!==n)for(;void 0!==n;)_={name:n.name,styles:n.styles,next:_},n=n.next;return r.styles+";"}return function(e,t,i){var r="";if(Array.isArray(i))for(var n=0;n<i.length;n++)r+=p(e,t,i[n])+";";else for(var s in i){var o=i[s];if("object"!==typeof o){var a=o;null!=t&&void 0!==t[a]?r+=s+"{"+t[a]+"}":u(a)&&(r+=g(s)+":"+h(s,a)+";")}else if(!Array.isArray(o)||"string"!==typeof o[0]||null!=t&&void 0!==t[o[0]]){var c=p(e,t,o);switch(s){case"animation":case"animationName":r+=g(s)+":"+c+";";break;default:r+=s+"{"+c+"}"}}else for(var l=0;l<o.length;l++)u(o[l])&&(r+=g(s)+":"+h(s,o[l])+";")}return r}(e,t,i);case"function":if(void 0!==e){var s=_,o=i(e);return _=s,p(e,t,o)}}if(null==t)return i;var a=t[i];return void 0!==a?a:i}var _,m=/label:\s*([^\s;{]+)\s*(;|$)/g;function f(e,t,i){if(1===e.length&&"object"===typeof e[0]&&null!==e[0]&&void 0!==e[0].styles)return e[0];var r=!0,n="";_=void 0;var s=e[0];null==s||void 0===s.raw?(r=!1,n+=p(i,t,s)):n+=s[0];for(var o=1;o<e.length;o++)n+=p(i,t,e[o]),r&&(n+=s[o]);m.lastIndex=0;for(var a,c="";null!==(a=m.exec(n));)c+="-"+a[1];var l=function(e){for(var t,i=0,r=0,n=e.length;n>=4;++r,n-=4)t=1540483477*(65535&(t=255&e.charCodeAt(r)|(255&e.charCodeAt(++r))<<8|(255&e.charCodeAt(++r))<<16|(255&e.charCodeAt(++r))<<24))+(59797*(t>>>16)<<16),i=1540483477*(65535&(t^=t>>>24))+(59797*(t>>>16)<<16)^1540483477*(65535&i)+(59797*(i>>>16)<<16);switch(n){case 3:i^=(255&e.charCodeAt(r+2))<<16;case 2:i^=(255&e.charCodeAt(r+1))<<8;case 1:i=1540483477*(65535&(i^=255&e.charCodeAt(r)))+(59797*(i>>>16)<<16)}return(((i=1540483477*(65535&(i^=i>>>13))+(59797*(i>>>16)<<16))^i>>>15)>>>0).toString(36)}(n)+c;return{name:l,styles:n,next:_}}var w=!!r.useInsertionEffect&&r.useInsertionEffect||function(e){return e()},y=r.createContext("undefined"!==typeof HTMLElement?(0,n.A)({key:"css"}):null),S=function(e){return(0,r.forwardRef)(function(t,i){var n=(0,r.useContext)(y);return e(t,n,i)})},v=r.createContext({}),b={}.hasOwnProperty,E="__EMOTION_TYPE_PLEASE_DO_NOT_USE__",k=function(e){var t=e.cache,i=e.serialized,r=e.isStringTag;return s(t,i,r),w(function(){return function(e,t,i){s(e,t,i);var r=e.key+"-"+t.name;if(void 0===e.inserted[t.name]){var n=t;do{e.insert(t===n?"."+r:"",n,e.sheet,!0),n=n.next}while(void 0!==n)}}(t,i,r)}),null},T=S(function(e,t,i){var n=e.css;"string"===typeof n&&void 0!==t.registered[n]&&(n=t.registered[n]);var s=e[E],o=[n],a="";"string"===typeof e.className?a=function(e,t,i){var r="";return i.split(" ").forEach(function(i){void 0!==e[i]?t.push(e[i]+";"):i&&(r+=i+" ")}),r}(t.registered,o,e.className):null!=e.className&&(a=e.className+" ");var c=f(o,void 0,r.useContext(v));a+=t.key+"-"+c.name;var l={};for(var d in e)b.call(e,d)&&"css"!==d&&d!==E&&(l[d]=e[d]);return l.className=a,i&&(l.ref=i),r.createElement(r.Fragment,null,r.createElement(k,{cache:t,serialized:c,isStringTag:"string"===typeof s}),r.createElement(s,l))}),I=(i(4146),function(e,t){var i=arguments;if(null==t||!b.call(t,"css"))return r.createElement.apply(void 0,i);var n=i.length,s=new Array(n);s[0]=T,s[1]=function(e,t){var i={};for(var r in t)b.call(t,r)&&(i[r]=t[r]);return i[E]=e,i}(e,t);for(var o=2;o<n;o++)s[o]=i[o];return r.createElement.apply(null,s)});function A(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return f(t)}function R(){var e=A.apply(void 0,arguments),t="animation-"+e.name;return{name:t,styles:"@keyframes "+t+"{"+e.styles+"}",anim:1,toString:function(){return"_EMO_"+this.name+"_"+this.styles+"_EMO_"}}}!function(e){var t;t||(t=e.JSX||(e.JSX={}))}(I||(I={}))},12542(e,t,i){i.d(t,{BK:()=>bt});var r=i(37917);const n={none:0,error:1,warn:2,info:3,debug:4},s={error:"error",warn:"warn",info:"info",log:"info",debug:"debug"},o=(e,t)=>n[e]<=n[t],a=e=>"string"==typeof e?e:JSON.stringify(e),c=(e,t)=>{let i=`[${a(e)}]`;return typeof window<"u"?{text:`%c${i}`,style:`color: ${t.color||"#00bcd4"}; font-weight: bold;`}:{text:i}},l=(e,t,i,r)=>(...n)=>{o(s[e],r())&&t&&c(t,i)},d=(e,t)=>{let i=t.logLevel??"debug",r=()=>i;return{log:l("log",e,t,r),info:l("info",e,t,r),warn:l("warn",e,t,r),error:l("error",e,t,r),debug:l("debug",e,t,r),setLogLevel:e=>{i=e},extend:r=>d(e?((e,t)=>`${a(e)} > ${a(t)}`)(e,r):r,{...t,logLevel:i})}},u=(e,t)=>d(e,{color:"#00bcd4",logLevel:"debug",...t}),g=u("angie-sdk",{color:"#00BCD4",logLevel:"error"}),h=e=>g.extend(e);var p,_,m,f,w,y,S,v;(p||(p={})).POST_MESSAGE="postMessage",(_||(_={})).POST_MESSAGE="postMessage",(v=m||(m={})).STREAMABLE_HTTP="streamableHttp",v.SSE="sse",function(e){e.LOCAL="local",e.REMOTE="remote"}(f||(f={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_ANGIE_REFRESH_PING="sdk-angie-refresh-ping",e.SDK_ANGIE_ALL_SERVERS_REGISTERED="sdk-angie-all-servers-registered",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response",e.ANGIE_SIDEBAR_RESIZED="angie-sidebar-resized",e.ANGIE_SIDEBAR_TOGGLED="angie-sidebar-toggled",e.ANGIE_CHAT_TOGGLE="angie-chat-toggle",e.ANGIE_STUDIO_TOGGLE="angie-studio-toggle",e.ANGIE_NAVIGATE_TO_URL="angie/navigate-to-url",e.ANGIE_PAGE_RELOAD="angie/page-reload",e.ANGIE_DISABLE_NAVIGATION_PREVENTION="angie/disable-navigation-prevention",e.ANGIE_NAVIGATE_AFTER_RESPONSE="angie/navigate-after-response"}(w||(w={})),function(e){e.SET="ANGIE_SET_LOCALSTORAGE",e.GET="ANGIE_GET_LOCALSTORAGE"}(y||(y={})),function(e){e.RESET_HASH="reset-hash",e.HOST_READY="host/ready",e.ANGIE_LOADED="angie/loaded",e.ANGIE_READY="angie/ready"}(S||(S={}));const b=h("angie-detector");class E{isAngieReady=!1;readyPromise;readyResolve;constructor(){if(this.readyPromise=new Promise(e=>{this.readyResolve=e}),"undefined"==typeof window)return;let e=0;const t=()=>{if(this.isAngieReady||e>=500)return void(!this.isAngieReady&&e>=500&&this.handleDetectionTimeout());const i=new MessageChannel;i.port1.onmessage=e=>{this.handleAngieReady(e.data),i.port1.close(),i.port2.close()};const r={type:w.SDK_ANGIE_READY_PING,timestamp:Date.now()};window.postMessage(r,window.location.origin,[i.port2]),e++,setTimeout(t,500)};t()}handleAngieReady(e){this.isAngieReady=!0,this.readyResolve&&this.readyResolve({isReady:!0,version:e.version,capabilities:e.capabilities})}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),b.warn("Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}}class k{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(e){if(!e)throw new Error("MessagePort is required");this._port=e,this._port.onmessage=e=>{try{const t=r.OR.parse(e.data);this.onmessage?.(t)}catch(v){const t=new Error(`Failed to parse message: ${v}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise((t,i)=>{try{this._port.postMessage(e),t()}catch(e){const r=e instanceof Error?e:new Error(String(e));this.onerror?.(r),i(r)}})}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}}class T{async requestClientCreation(e){const{config:t}=e,i={serverId:e.id,serverName:t.name,serverTitle:t.title,serverVersion:t.version,description:t.description,transport:t.transport||_.POST_MESSAGE,capabilities:t.capabilities,instanceId:e.instanceId};return"type"in t&&"remote"===t.type&&(i.remote={url:t.url}),new Promise((e,t)=>{const r=new MessageChannel,n=setTimeout(()=>{t(new Error("Client creation request timed out after 15000ms"))},15e3);r.port1.onmessage=t=>{clearTimeout(n),e(t.data)};const s={type:w.SDK_REQUEST_CLIENT_CREATION,payload:i,timestamp:Date.now()};window.postMessage(s,window.location.origin,[r.port2])})}}const I={open:!1,iframe:null,iframeUrlObject:null};class A extends Error{}A.prototype.name="InvalidTokenError";var R,C,x,O={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},P=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(P||{});(x=P||(P={})).reset=function(){R=3,C=O},x.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");R=e},x.setLogger=function(e){C=e};var N=class e{constructor(e){this._name=e}debug(...t){R>=4&&C.debug(e._format(this._name,this._method),...t)}info(...t){R>=3&&C.info(e._format(this._name,this._method),...t)}warn(...t){R>=2&&C.warn(e._format(this._name,this._method),...t)}error(...t){R>=1&&C.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,i){const r=new e(`${t}.${i}`);return r.debug("begin"),r}static _format(e,t){const i=`[${e}]`;return t?`${i} ${t}:`:i}static debug(t,...i){R>=4&&C.debug(e._format(t),...i)}static info(t,...i){R>=3&&C.info(e._format(t),...i)}static warn(t,...i){R>=2&&C.warn(e._format(t),...i)}static error(t,...i){R>=1&&C.error(e._format(t),...i)}};P.reset();var U=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new A("Invalid token specified: must be a string");t||(t={});const i=!0===t.header?0:1,r=e.split(".")[i];if("string"!=typeof r)throw new A(`Invalid token specified: missing part #${i+1}`);let n;try{n=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i}))}(t)}catch(e){return atob(t)}}(r)}catch(e){throw new A(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(n)}catch(e){throw new A(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e)}catch(e){throw N.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,i){const r=`${M.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${M.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,n=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},i,(new TextEncoder).encode(r));return`${r}.${M.encodeBase64Url(new Uint8Array(n))}`}static async generateSignedJwtWithHmac(e,t,i){const r=`${M.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${M.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,n=await window.crypto.subtle.sign("HMAC",i,(new TextEncoder).encode(r));return`${r}.${M.encodeBase64Url(new Uint8Array(n))}`}},D=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),L=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),i=await crypto.subtle.digest("SHA-256",t);return D(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw N.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const i=(new TextEncoder).encode([e,t].join(":"));return D(i)}static async hash(e,t){const i=(new TextEncoder).encode(t),r=await crypto.subtle.digest(e,i);return new Uint8Array(r)}static async customCalculateJwkThumbprint(t){let i;switch(t.kty){case"RSA":i={e:t.e,kty:t.kty,n:t.n};break;case"EC":i={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":i={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":i={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const r=await e.hash("SHA-256",JSON.stringify(i));return e.encodeBase64Url(r)}static async generateDPoPProof({url:t,accessToken:i,httpMethod:r,keyPair:n,nonce:s}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=r?r:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};i&&(o=await e.hash("SHA-256",i),a=e.encodeBase64Url(o),c.ath=a),s&&(c.nonce=s);try{const e=await crypto.subtle.exportKey("jwk",n.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await U.generateSignedJwt(t,c,n.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const i=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(i)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(t,i,r,n="HS256"){const s=Math.floor(Date.now()/1e3),o={alg:n,typ:"JWT"},a={iss:t,sub:t,aud:r,jti:e.generateUUIDv4(),exp:s+300,iat:s},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[n];if(!c)throw new Error(`Unsupported algorithm: ${n}. Supported algorithms are: HS256, HS384, HS512`);const l=new TextEncoder,d=await crypto.subtle.importKey("raw",l.encode(i),{name:"HMAC",hash:c},!1,["sign"]);return await U.generateSignedJwtWithHmac(o,a,d)}};L.encodeBase64Url=e=>D(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var M=L,H=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new N(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},q=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find(e=>e<=window.outerWidth/1.618))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,e])=>null!=e).map(([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`).join(",")}},$=class e extends H{constructor(){super(...arguments),this._logger=new N(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const i=this._logger.create("init");t=Math.max(Math.floor(t),1);const r=e.getEpochTime()+t;if(this.expiration===r&&this._timerHandle)return void i.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),i.debug("using duration",t),this._expiration=r;const n=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*n)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},j=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const i=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(i.slice(1))}},z=";",F=class extends Error{constructor(e,t){var i,r,n;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw N.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(i=e.error_description)?i:null,this.error_uri=null!=(r=e.error_uri)?r:null,this.state=e.userState,this.session_state=null!=(n=e.session_state)?n:null,this.url_state=e.url_state}},G=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},W=class{constructor(e){this._logger=new N("AccessTokenEvents"),this._expiringTimer=new $("Access token expiring"),this._expiredTimer=new $("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const i=e.expires_in;if(t.debug("access token present, remaining duration:",i),i>0){let e=i-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const r=i+1;t.debug("registering expired timer, raising in",r,"seconds"),this._expiredTimer.init(r)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},K=class{constructor(e,t,i,r,n){this._callback=e,this._client_id=t,this._intervalInSeconds=r,this._stopOnError=n,this._logger=new N("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const s=new URL(i);this._frame_origin=s.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=s.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},B=class{constructor(){this._logger=new N("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},J=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},V=class{constructor(e=[],t=null,i={}){this._jwtHandler=t,this._extraHeaders=i,this._logger=new N("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:i,...r}=t;if(!i)return await fetch(e,r);const n=new AbortController,s=setTimeout(()=>n.abort(),1e3*i);try{return await fetch(e,{...t,signal:n.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new G("Network timed out");throw e}finally{clearTimeout(s)}}async getJson(e,{token:t,credentials:i,timeoutInSeconds:r}={}){const n=this._logger.create("getJson"),s={Accept:this._contentTypes.join(", ")};let o;t&&(n.debug("token passed, setting Authorization header"),s.Authorization="Bearer "+t),this._appendExtraHeaders(s);try{n.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:s,timeoutInSeconds:r,credentials:i})}catch(e){throw n.error("Network Error"),e}n.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(e=>a.startsWith(e))&&n.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){if(n.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(n.error("Error from server:",c),c.error)throw new F(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:i,timeoutInSeconds:r,initCredentials:n,extraHeaders:s}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...s};let c;void 0!==i&&(a.Authorization="Basic "+i),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:r,credentials:n})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const l=c.headers.get("Content-Type");if(l&&!this._contentTypes.find(e=>l.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=l?l:"undefined"}, from URL: ${e}`);const d=await c.text();let u={};if(d)try{u=JSON.parse(d)}catch(e){if(o.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",u),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new J(e,`${JSON.stringify(u)}`)}if(u.error)throw new F(u,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(u)}`)}return u}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),i=Object.keys(this._extraHeaders),r=["accept","content-type"],n=["authorization"];0!==i.length&&i.forEach(i=>{if(r.includes(i.toLocaleLowerCase()))return void t.warn("Protected header could not be set",i,r);if(n.includes(i.toLocaleLowerCase())&&Object.keys(e).includes(i))return void t.warn("Header could not be overridden",i,n);const s="function"==typeof this._extraHeaders[i]?this._extraHeaders[i]():this._extraHeaders[i];s&&""!==s&&(e[i]=s)})}},Q=class{constructor(e){this._settings=e,this._logger=new N("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new V(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const i=this._logger.create(`_getMetadataProperty('${e}')`),r=await this.getMetadata();if(i.debug("resolved"),void 0===r[e]){if(!0===t)return void i.warn("Metadata does not contain optional property");i.throw(new Error("Metadata does not contain property "+e))}return r[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const i=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",i),!Array.isArray(i.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=i.keys,this._signingKeys}},Y=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new N("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let i=0;i<e;i++){const e=await this._store.key(i);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},X=class{constructor({authority:e,metadataUrl:t,metadata:i,signingKeys:r,metadataSeed:n,client_id:s,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:l,post_logout_redirect_uri:d,client_authentication:u="client_secret_post",token_endpoint_auth_signing_alg:g="HS256",prompt:h,display:p,max_age:_,ui_locales:m,acr_values:f,resource:w,response_mode:y,filterProtocolClaims:S=!0,loadUserInfo:v=!1,requestTimeoutInSeconds:b,staleStateAgeInSeconds:E=900,mergeClaimsStrategy:k={array:"replace"},disablePKCE:T=!1,stateStore:I,revokeTokenAdditionalContentTypes:A,fetchRequestCredentials:R,refreshTokenAllowedScope:C,extraQueryParams:x={},extraTokenParams:O={},extraHeaders:P={},dpop:N,omitScopeWhenRequesting:U=!1}){var D;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=i,this.metadataSeed=n,this.signingKeys=r,this.client_id=s,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=d,this.client_authentication=u,this.token_endpoint_auth_signing_alg=g,this.prompt=h,this.display=p,this.max_age=_,this.ui_locales=m,this.acr_values=f,this.resource=w,this.response_mode=y,this.filterProtocolClaims=null==S||S,this.loadUserInfo=!!v,this.staleStateAgeInSeconds=E,this.mergeClaimsStrategy=k,this.omitScopeWhenRequesting=U,this.disablePKCE=!!T,this.revokeTokenAdditionalContentTypes=A,this.fetchRequestCredentials=R||"same-origin",this.requestTimeoutInSeconds=b,I)this.stateStore=I;else{const e="undefined"!=typeof window?window.localStorage:new B;this.stateStore=new Y({store:e})}if(this.refreshTokenAllowedScope=C,this.extraQueryParams=x,this.extraTokenParams=O,this.extraHeaders=P,this.dpop=N,this.dpop&&!(null==(D=this.dpop)?void 0:D.store))throw new Error("A DPoPStore is required when dpop is enabled")}},Z=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new N("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const i=U.decode(e);return t.debug("JWT decoding successful"),i}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new V(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const i=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",i);const r=await this._jsonService.getJson(i,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",r),r}},ee=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new N("TokenClient"),this._jsonService=new V(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:i=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:n,...s}){const o=this._logger.create("exchangeCode");i||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),s.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[u,g]of Object.entries(s))null!=g&&a.set(u,g);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw o.throw(new Error("A client_secret is required")),null;let c;const l=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=M.generateBasicAuth(i,r);break;case"client_secret_post":a.append("client_id",i),r&&a.append("client_secret",r);break;case"client_secret_jwt":{const e=await M.generateClientAssertionJwt(i,r,l,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",i),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:n});return o.debug("got response"),d}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,scope:r=this._settings.scope,...n}){const s=this._logger.create("exchangeCredentials");t||s.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",r);for(const[d,u]of Object.entries(n))null!=u&&o.set(d,u);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw s.throw(new Error("A client_secret is required")),null;let a;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=M.generateBasicAuth(t,i);break;case"client_secret_post":o.append("client_id",t),i&&o.append("client_secret",i);break;case"client_secret_jwt":{const e=await M.generateClientAssertionJwt(t,i,c,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",t),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}s.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return s.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:n,...s}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),s.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[u,g]of Object.entries(s))Array.isArray(g)?g.forEach(e=>a.append(u,e)):null!=g&&a.set(u,g);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw o.throw(new Error("A client_secret is required")),null;let c;const l=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=M.generateBasicAuth(t,i);break;case"client_secret_post":a.append("client_id",t),i&&a.append("client_secret",i);break;case"client_secret_jwt":{const e=await M.generateClientAssertionJwt(t,i,l,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:n});return o.debug("got response"),d}async revoke(e){var t;const i=this._logger.create("revoke");e.token||i.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);i.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const n=new URLSearchParams;for(const[s,o]of Object.entries(e))null!=o&&n.set(s,o);n.set("client_id",this._settings.client_id),this._settings.client_secret&&n.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:n,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),i.debug("got response")}},te=class{constructor(e,t,i){this._settings=e,this._metadataService=t,this._claimsService=i,this._logger=new N("ResponseValidator"),this._userInfoService=new Z(this._settings,this._metadataService),this._tokenClient=new ee(this._settings,this._metadataService)}async validateSigninResponse(e,t,i){const r=this._logger.create("validateSigninResponse");this._processSigninState(e,t),r.debug("state processed"),await this._processCode(e,t,i),r.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(e,t){const i=this._logger.create("validateCredentialsResponse"),r=e.isOpenId&&!!e.id_token;r&&this._validateIdTokenAttributes(e),i.debug("tokens validated"),await this._processClaims(e,t,r),i.debug("claims processed")}async validateRefreshResponse(e,t){const i=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),i.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const r=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,r),i.debug("claims processed")}validateSignoutResponse(e,t){const i=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&i.throw(new Error("State does not match")),i.debug("state validated"),e.userState=t.data,e.error)throw i.warn("Response was error",e.error),new F(e)}_processSigninState(e,t){const i=this._logger.create("_processSigninState");if(t.id!==e.state&&i.throw(new Error("State does not match")),t.client_id||i.throw(new Error("No client_id on state")),t.authority||i.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&i.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&i.throw(new Error("client_id mismatch on settings vs. signin state")),i.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw i.warn("Response was error",e.error),new F(e);t.code_verifier&&!e.code&&i.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,i=!0){const r=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void r.debug("not loading user info");r.debug("loading user info");const n=await this._userInfoService.getClaims(e.access_token);r.debug("user info claims received from user info endpoint"),i&&n.sub!==e.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(n)),r.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,i){const r=this._logger.create("_processCode");if(e.code){r.debug("Validating code");const n=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:i,...t.extraTokenParams});Object.assign(e,n)}else r.debug("No code to process")}_validateIdTokenAttributes(e,t){var i;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const n=U.decode(null!=(i=e.id_token)?i:"");if(n.sub||r.throw(new Error("ID Token is missing a subject claim")),t){const e=U.decode(t);n.sub!==e.sub&&r.throw(new Error("sub in id_token does not match current sub")),n.auth_time&&n.auth_time!==e.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),n.azp&&n.azp!==e.azp&&r.throw(new Error("azp in id_token does not match original azp")),!n.azp&&e.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=n}},ie=class e{constructor(e){this.id=e.id||M.generateUUIDv4(),this.data=e.data,this.created=e.created&&e.created>0?e.created:$.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new N("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return N.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,i){const r=N.createStatic("State","clearStaleState"),n=$.getEpochTime()-i,s=await t.getAllKeys();r.debug("got keys",s);for(let o=0;o<s.length;o++){const i=s[o],a=await t.get(i);let c=!1;if(a)try{const t=await e.fromStorageString(a);r.debug("got item from key:",i,t.created),t.created<=n&&(c=!0)}catch(e){r.error("Error parsing state for key:",i,e),c=!0}else r.debug("no item in storage for key:",i),c=!0;c&&(r.debug("removed item for key:",i),t.remove(i))}}},re=class e extends ie{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const i=!0===t.code_verifier?M.generateCodeVerifier():t.code_verifier||void 0,r=i?await M.generateCodeChallenge(i):void 0;return new e({...t,code_verifier:i,code_challenge:r})}toStorageString(){return new N("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){N.createStatic("SigninState","fromStorageString");const i=JSON.parse(t);return e.create(i)}},ne=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:i,client_id:r,redirect_uri:n,response_type:s,scope:o,state_data:a,response_mode:c,request_type:l,client_secret:d,nonce:u,url_state:g,resource:h,skipUserInfo:p,extraQueryParams:_,extraTokenParams:m,disablePKCE:f,dpopJkt:w,omitScopeWhenRequesting:y,...S}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!n)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!s)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!i)throw this._logger.error("create: No authority passed"),new Error("authority");const v=await re.create({data:a,request_type:l,url_state:g,code_verifier:!f,client_id:r,authority:i,redirect_uri:n,response_mode:c,client_secret:d,scope:o,extraTokenParams:m,skipUserInfo:p}),b=new URL(t);b.searchParams.append("client_id",r),b.searchParams.append("redirect_uri",n),b.searchParams.append("response_type",s),y||b.searchParams.append("scope",o),u&&b.searchParams.append("nonce",u),w&&b.searchParams.append("dpop_jkt",w);let E=v.id;g&&(E=`${E}${z}${g}`),b.searchParams.append("state",E),v.code_challenge&&(b.searchParams.append("code_challenge",v.code_challenge),b.searchParams.append("code_challenge_method","S256")),h&&(Array.isArray(h)?h:[h]).forEach(e=>b.searchParams.append("resource",e));for(const[e,k]of Object.entries({response_mode:c,...S,..._}))null!=k&&b.searchParams.append(e,k.toString());return new e({url:b.href,state:v})}};ne._logger=new N("SigninRequest");var se=ne,oe=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(z);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(z))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-$.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+$.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},ae=class{constructor({url:e,state_data:t,id_token_hint:i,post_logout_redirect_uri:r,extraQueryParams:n,request_type:s,client_id:o,url_state:a}){if(this._logger=new N("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(i&&c.searchParams.append("id_token_hint",i),o&&c.searchParams.append("client_id",o),r&&(c.searchParams.append("post_logout_redirect_uri",r),t||a)){this.state=new ie({data:t,request_type:s,url_state:a});let e=this.state.id;a&&(e=`${e}${z}${a}`),c.searchParams.append("state",e)}for(const[l,d]of Object.entries({...n}))null!=d&&c.searchParams.append(l,d.toString());this.url=c.href}},ce=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(z);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(z))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},le=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],de=["sub","iss","aud","exp","iat"],ue=class{constructor(e){this._settings=e,this._logger=new N("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:le;for(const i of e)de.includes(i)||delete t[i]}return t}mergeClaims(e,t){const i={...e};for(const[r,n]of Object.entries(t))if(i[r]!==n)if(Array.isArray(i[r])||Array.isArray(n))if("replace"==this._settings.mergeClaimsStrategy.array)i[r]=n;else{const e=Array.isArray(i[r])?i[r]:[i[r]];for(const t of Array.isArray(n)?n:[n])e.includes(t)||e.push(t);i[r]=e}else i[r]="object"==typeof i[r]&&"object"==typeof n?this.mergeClaims(i[r],n):n;return i}},ge=class{constructor(e,t){this.keys=e,this.nonce=t}},he=class{constructor(e,t){this._logger=new N("OidcClient"),this.settings=e instanceof X?e:new X(e),this.metadataService=null!=t?t:new Q(this.settings),this._claimsService=new ue(this.settings),this._validator=new te(this.settings,this.metadataService,this._claimsService),this._tokenClient=new ee(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:i,request_type:r,id_token_hint:n,login_hint:s,skipUserInfo:o,nonce:a,url_state:c,response_type:l=this.settings.response_type,scope:d=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:g=this.settings.prompt,display:h=this.settings.display,max_age:p=this.settings.max_age,ui_locales:_=this.settings.ui_locales,acr_values:m=this.settings.acr_values,resource:f=this.settings.resource,response_mode:w=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:S=this.settings.extraTokenParams,dpopJkt:v,omitScopeWhenRequesting:b=this.settings.omitScopeWhenRequesting}){const E=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const k=await this.metadataService.getAuthorizationEndpoint();E.debug("Received authorization endpoint",k);const T=await se.create({url:k,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:l,scope:d,state_data:e,url_state:c,prompt:g,display:h,max_age:p,ui_locales:_,id_token_hint:n,login_hint:s,acr_values:m,dpopJkt:v,resource:f,request:t,request_uri:i,extraQueryParams:y,extraTokenParams:S,request_type:r,response_mode:w,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:b});await this.clearStaleState();const I=T.state;return await this.settings.stateStore.set(I.id,I.toStorageString()),T}async readSigninResponseState(e,t=!1){const i=this._logger.create("readSigninResponseState"),r=new oe(j.readParams(e,this.settings.response_mode));if(!r.state)throw i.throw(new Error("No state in response")),null;const n=await this.settings.stateStore[t?"remove":"get"](r.state);if(!n)throw i.throw(new Error("No matching state found in storage")),null;return{state:await re.fromStorageString(n),response:r}}async processSigninResponse(e,t,i=!0){const r=this._logger.create("processSigninResponse"),{state:n,response:s}=await this.readSigninResponseState(e,i);if(r.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(s,n,t)}catch(e){if(!(e instanceof J&&this.settings.dpop))throw e;{const i=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=i,await this._validator.validateSigninResponse(s,n,t)}}return s}async getDpopProof(e,t){let i,r;return(await e.getAllKeys()).includes(this.settings.client_id)?(r=await e.get(this.settings.client_id),r.nonce!==t&&t&&(r.nonce=t,await e.set(this.settings.client_id,r))):(i=await M.generateDPoPKeys(),r=new ge(i,t),await e.set(this.settings.client_id,r)),await M.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i=!1,extraTokenParams:r={}}){const n=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),s=new oe(new URLSearchParams);return Object.assign(s,n),await this._validator.validateCredentialsResponse(s,i),s}async useRefreshToken({state:e,redirect_uri:t,resource:i,timeoutInSeconds:r,extraHeaders:n,extraTokenParams:s}){var o;const a=this._logger.create("useRefreshToken");let c,l;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);n={...n,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:r,extraHeaders:n,...s})}catch(o){if(!(o instanceof J&&this.settings.dpop))throw o;n.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:r,extraHeaders:n,...s})}const d=new oe(new URLSearchParams);return Object.assign(d,l),a.debug("validating response",d),await this._validator.validateRefreshResponse(d,{...e,scope:c}),d}async createSignoutRequest({state:e,id_token_hint:t,client_id:i,request_type:r,url_state:n,post_logout_redirect_uri:s=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),i||!s||t||(i=this.settings.client_id);const l=new ae({url:c,id_token_hint:t,client_id:i,post_logout_redirect_uri:s,state_data:e,extraQueryParams:o,request_type:r,url_state:n});await this.clearStaleState();const d=l.state;return d&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(d.id,d.toStorageString())),l}async readSignoutResponseState(e,t=!1){const i=this._logger.create("readSignoutResponseState"),r=new ce(j.readParams(e,this.settings.response_mode));if(!r.state){if(i.debug("No state in response"),r.error)throw i.warn("Response was error:",r.error),new F(r);return{state:void 0,response:r}}const n=await this.settings.stateStore[t?"remove":"get"](r.state);if(!n)throw i.throw(new Error("No matching state found in storage")),null;return{state:await ie.fromStorageString(n),response:r}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:i,response:r}=await this.readSignoutResponseState(e,!0);return i?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,i)):t.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),ie.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},pe=class{constructor(e){this._userManager=e,this._logger=new N("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const i=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,i.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,i.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){i.debug("initializing check session iframe");const r=new K(this._callback,this._userManager.settings.client_id,e,this._userManager.settings.checkSessionIntervalInSeconds,this._userManager.settings.stopCheckSessionOnError);await r.load(),this._checkSessionIFrame=r,r.start(t)}else i.warn("no check session iframe found in the metadata")}catch(e){i.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval(async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();e&&this._start({session_state:e.session_state,profile:e.sub?{sub:e.sub}:null})}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}},1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let i=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(i=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),i?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(n){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",n),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(e=>{this._logger.error(e)})}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();e&&this._start({session_state:e.session_state,profile:e.sub?{sub:e.sub}:null})}}},_e=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-$.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+$.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new N("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return N.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},me="oidc-client",fe=class{constructor(){this._abort=new H("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:i,keepOpen:r}=await new Promise((i,r)=>{const n=n=>{var s;const o=n.data,a=null!=(s=e.scriptOrigin)?s:window.location.origin;if(n.origin===a&&(null==o?void 0:o.source)===me){try{const i=j.readParams(o.url,e.response_mode).get("state");if(i||t.warn("no state found in response url"),n.source!==this._window&&i!==e.state)return}catch{this._dispose(),r(new Error("Invalid response from window"))}i(o)}};window.addEventListener("message",n,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",n,!1));const s=new BroadcastChannel(`oidc-client-popup-${e.state}`);s.addEventListener("message",n,!1),this._disposeHandlers.add(()=>s.close()),this._disposeHandlers.add(this._abort.addHandler(e=>{this._dispose(),r(e)}))});return t.debug("got response from window"),this._dispose(),r||this.close(),{url:i}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,i=!1,r=window.location.origin){const n={source:me,url:t,keepOpen:i},s=new N("_notifyParent");if(e)s.debug("With parent. Using parent.postMessage."),e.postMessage(n,r);else{s.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const i=new BroadcastChannel(`oidc-client-popup-${e}`);i.postMessage(n),i.close()}}},we={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},ye="_blank",Se=60,ve=2,be=class extends X{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:i=e.post_logout_redirect_uri,popupWindowFeatures:r=we,popupWindowTarget:n=ye,redirectMethod:s="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:d=e.redirect_uri,silentRequestTimeoutInSeconds:u,automaticSilentRenew:g=!0,validateSubOnSilentRenew:h=!0,includeIdTokenInSilentRenew:p=!1,monitorSession:_=!1,monitorAnonymousSession:m=!1,checkSessionIntervalInSeconds:f=ve,query_status_response_type:w="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:S=["access_token","refresh_token"],revokeTokensOnSignout:v=!1,includeIdTokenInSilentSignout:b=!1,accessTokenExpiringNotificationTimeInSeconds:E=Se,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=i,this.popupWindowFeatures=r,this.popupWindowTarget=n,this.redirectMethod=s,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=d,this.silentRequestTimeoutInSeconds=u||l||10,this.automaticSilentRenew=g,this.validateSubOnSilentRenew=h,this.includeIdTokenInSilentRenew=p,this.monitorSession=_,this.monitorAnonymousSession=m,this.checkSessionIntervalInSeconds=f,this.stopCheckSessionOnError=y,this.query_status_response_type=w,this.revokeTokenTypes=S,this.revokeTokensOnSignout=v,this.includeIdTokenInSilentSignout=b,this.accessTokenExpiringNotificationTimeInSeconds=E,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new B;this.userStore=new Y({store:e})}}},Ee=class e extends fe{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new N("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout(()=>{this._abort.raise(new G("IFrame timed out without a response"))},1e3*this._timeoutInSeconds);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",e=>{var t;const i=e.target;null==(t=i.parentNode)||t.removeChild(i),this._abort.raise(new Error("IFrame removed from DOM"))},!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},ke=class{constructor(e){this._settings=e,this._logger=new N("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new Ee({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),Ee.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},Te=class extends fe{constructor({popupWindowTarget:e=ye,popupWindowFeatures:t={},popupSignal:i,popupAbortOnClose:r}){super(),this._logger=new N("PopupWindow");const n=q.center({...we,...t});this._window=window.open(void 0,e,q.serialize(n)),this.abortOnClose=Boolean(r),i&&i.addEventListener("abort",()=>{var e;this._abort.raise(new Error(null!=(e=i.reason)?e:"Popup aborted"))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))},1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const i=setInterval(()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),r(),this._disposeHandlers.delete(r),this.abortOnClose&&this._abort.raise(new Error("Popup closed by user")))},500),r=()=>clearInterval(i);return this._disposeHandlers.add(r),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},Ie=class{constructor(e){this._settings=e,this._logger=new N("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:i,popupAbortOnClose:r}){return new Te({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:i,popupAbortOnClose:r})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),Te.notifyOpener(e,t)}},Ae=class{constructor(e){this._settings=e,this._logger=new N("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var i;this._logger.create("prepare");let r=window.self;"top"===t&&(r=null!=(i=window.top)?i:window.self);const n=r.location[e].bind(r.location);let s;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise((t,i)=>{s=i,window.addEventListener("pageshow",()=>t(window.location.href)),n(e.url)});return await t},close:()=>{this._logger.create("close"),null==s||s(new Error("Redirect aborted")),r.stop()}}}async callback(){}},Re=class extends W{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new N("UserManagerEvents"),this._userLoaded=new H("User loaded"),this._userUnloaded=new H("User unloaded"),this._silentRenewError=new H("Silent renew error"),this._userSignedIn=new H("User signed in"),this._userSignedOut=new H("User signed out"),this._userSessionChanged=new H("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Ce=class{constructor(e){this._userManager=e,this._logger=new N("SilentRenewService"),this._isStarted=!1,this._retryTimer=new $("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(n){if(n instanceof G)return e.warn("ErrorTimeout from signinSilent:",n,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",n),await this._userManager.events._raiseSilentRenewError(n)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(n){e.error("getUser error",n)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},xe=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},Oe=class{constructor(e,t,i,r){this._logger=new N("UserManager"),this.settings=new be(e),this._client=new he(e),this._redirectNavigator=null!=t?t:new Ae(this.settings),this._popupNavigator=null!=i?i:new Ie(this.settings),this._iframeNavigator=null!=r?r:new ke(this.settings),this._events=new Re(this.settings),this._silentRenewService=new Ce(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new pe(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),i=await this._loadUser();return i?(t.info("user loaded"),await this._events.load(i,e),i):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:i,...r}=e;let n;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(n=await this.generateDPoPJkt(this.settings.dpop));const s=await this._redirectNavigator.prepare({redirectMethod:i});await this._signinStart({request_type:"si:r",dpopJkt:n,...r},s)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),i=await this._signinEnd(e);return i.profile&&i.profile.sub?t.info("success, signed in subject",i.profile.sub):t.info("no subject"),i}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:i=!1}){const r=this._logger.create("signinResourceOwnerCredential"),n=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i,extraTokenParams:this.settings.extraTokenParams});r.debug("got signin response");const s=await this._buildUser(n);return s.profile&&s.profile.sub?r.info("success, signed in subject",s.profile.sub):r.info("no subject"),s}async signinPopup(e={}){var t;const i=this._logger.create("signinPopup");let r;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(r=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:n,popupWindowTarget:s,popupSignal:o,popupAbortOnClose:a,...c}=e,l=this.settings.popup_redirect_uri;l||i.throw(new Error("No popup_redirect_uri configured"));const d=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:s,popupSignal:o,popupAbortOnClose:a}),u=await this._signin({request_type:"si:p",redirect_uri:l,display:"popup",dpopJkt:r,...c},d);return u&&(u.profile&&u.profile.sub?i.info("success, signed in subject",u.profile.sub):i.info("no subject")),u}async signinPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async signinSilent(e={}){var t,i;const r=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:n,...s}=e;let o,a=await this._loadUser();if(!e.forceIframeAuth&&(null==a?void 0:a.refresh_token)){r.debug("using refresh token");const e=new xe(a);return await this._useRefreshToken({state:e,redirect_uri:s.redirect_uri,resource:s.resource,extraTokenParams:s.extraTokenParams,timeoutInSeconds:n})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let l;c||r.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(r.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const d=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...s},d,l),a&&((null==(i=a.profile)?void 0:i.sub)?r.info("success, signed in subject",a.profile.sub):r.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),i=new _e({...e.state,...t});return await this.storeUser(i),await this._events.load(i),i}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:i}=await this._client.readSignoutResponseState(e);if(i)switch(i.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:i,...r}=e,n=this.settings.silent_redirect_uri;n||t.throw(new Error("No silent_redirect_uri configured"));const s=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i}),a=await this._signinStart({request_type:"si:s",redirect_uri:n,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==s?void 0:s.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...r},o);try{const e={},i=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),i.session_state&&i.profile.sub?(t.info("success for subject",i.profile.sub),{session_state:i.session_state,sub:i.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof F)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,i){const r=await this._signinStart(e,t);return await this._signinEnd(r.url,i)}async _signinStart(e,t){const i=this._logger.create("_signinStart");try{const r=await this._client.createSigninRequest(e);return i.debug("got signin request"),await t.navigate({url:r.url,state:r.state.id,response_mode:r.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const i=this._logger.create("_signinEnd"),r=await this._client.processSigninResponse(e,{});return i.debug("got signin response"),await this._buildUser(r,t)}async _buildUser(e,t){const i=this._logger.create("_buildUser"),r=new _e(e);if(t){if(t!==r.profile.sub)throw i.debug("current user does not match user returned from signin. sub from signin:",r.profile.sub),new F({...e,error:"login_required"});i.debug("current user matches user returned from signin")}return await this.storeUser(r),i.debug("user stored"),await this._events.load(r),r}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:i,...r}=e,n=await this._redirectNavigator.prepare({redirectMethod:i});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...r},n),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),i=await this._signoutEnd(e);return t.info("success"),i}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:i,popupWindowTarget:r,popupSignal:n,...s}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:r,popupSignal:n});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...s},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async _signout(e,t){const i=await this._signoutStart(e,t);return await this._signoutEnd(i.url)}async _signoutStart(e={},t){var i;const r=this._logger.create("_signoutStart");try{const n=await this._loadUser();r.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(n);const s=e.id_token_hint||n&&n.id_token;s&&(r.debug("setting id_token_hint in signout request"),e.id_token_hint=s),await this.removeUser(),r.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return r.debug("got signout request"),await t.navigate({url:o.url,state:null==(i=o.state)?void 0:i.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),i=await this._client.processSignoutResponse(e);return t.debug("got signout response"),i}async signoutSilent(e={}){var t;const i=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:r,...n}=e,s=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:s,...n},a),i.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const i=this._logger.create("_revokeInternal");if(!e)return;const r=t.filter(t=>"string"==typeof e[t]);if(r.length){for(const t of r)await this._client.revokeToken(e[t],t),i.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),i.debug("user stored"),await this._events.load(e)}else i.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),_e.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const i=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,i)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,i,r){var n,s;const o=await(null==(s=null==(n=this.settings.dpop)?void 0:n.store)?void 0:s.get(this.settings.client_id));if(o)return await M.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:i,keyPair:o.keys,nonce:r})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const i=await M.generateDPoPKeys();t=new ge(i),await e.store.set(this.settings.client_id,t)}return await M.generateDPoPJkt(t.keys)}};const Pe="OAUTH2_LOGIN_FLOW_COMPLETE_EVENT",Ne="OAUTH_GET_TOP_URL",Ue="OAUTH_REDIRECT_TOP_WINDOW",De="OAUTH_UPDATE_URL",Le="OAUTH2_CHECK_PENDING",Me="oauth2_top_origin",He="oauth2_login_success",qe="oauth2_state",$e=60,je=Math.max($e-15,20),ze=u("oidc-auth",{color:"green"}),Fe=e=>ze.extend(e);u("oidc-auth-utils");const Ge=()=>"undefined"==typeof window?"":new URLSearchParams(window.location.search).get("origin")||"";class We{static instance=null;settings=null;constructor(){}static getInstance(){return We.instance||(We.instance=new We),We.instance}configure(e){this.settings=e}isConfigured(){return null!==this.settings}getSettings(){if(!this.settings)throw new Error("OidcAuthConfig not configured. Call configure() or pass settings to OidcAuthClient.initialize().");return this.settings}getAuthOrigin(){const{authOrigin:e,authEndpoint:t}=this.getSettings();return e||new URL(t).origin}isAccessTokenProactiveRefreshEnabled(){return this.settings?.accessTokenProactiveRefreshEnabled??!0}getOidcSettings(){const e="undefined"==typeof window?"":window.location.origin,{clientId:t,authEndpoint:i}=this.getSettings(),r=this.getAuthOrigin(),n="undefined"!=typeof window?new Y({store:window.localStorage}):void 0,{accessTokenExpiringNotificationTimeInSeconds:s=$e}=this.getSettings();return{client_id:t,authority:r,redirect_uri:`${e}/login/oauth-callback`,post_logout_redirect_uri:e,response_type:"code",scope:"openid offline_access",automaticSilentRenew:!1,accessTokenExpiringNotificationTimeInSeconds:s,stateStore:n,userStore:n,metadata:{issuer:r,authorization_endpoint:i,token_endpoint:`${r}/connect/api/v1/oauth2/token`,end_session_endpoint:`${r}/logout/`}}}getAccessTokenExpiringNotificationTimeInSeconds(){return this.getSettings().accessTokenExpiringNotificationTimeInSeconds??$e}getAccessTokenFreshnessThresholdInSeconds(){return this.getSettings().accessTokenFreshnessThresholdInSeconds??je}getAllowedParentOrigins(){return this.settings?.allowedParentOrigins}}const Ke=We.getInstance(),Be=Fe("oidc-auth:host-api"),Je=async e=>new Promise((t,i)=>{const r=new MessageChannel;let n=!1;const s=()=>{n=!0,r.port1.close()},o=setTimeout(()=>{n||(s(),i(new Error(`Host message timeout: ${e.type}`)))},1e4);r.port1.onmessage=e=>{clearTimeout(o),s(),"success"!==e.data.status?i(e.data.payload):t(e.data.payload)};const a=new URLSearchParams(window.location.search).get("origin")||"";if(!function(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return!1;const t=Ke.getAllowedParentOrigins();return!t||0===t.length||t.includes(e)}(a))return clearTimeout(o),s(),void i(new Error("Origin not allowed"));Be.log("posting message to host",e),window.top.postMessage({type:e.type,payload:e.payload,...e.data||{}},a,[r.port2])}),Ve=Fe("oidc-auth:OidcAuthTimer");class Qe{timerHandle=null;expiration=null;initialized=!1;callback=()=>{};constructor(){this.timerHandle=null}init(e,t,i){const r=e-this.getEpochTime(),n=Math.max(r-t,10);this.cancel(),this.expiration=n,this.callback=i,Ve.debug("OIDC: timer - using expiration",n,r,t,e,r-t),this.timerHandle=setTimeout(this.callback,1e3*n),this.initialized=!0}cancel(){this.timerHandle&&(clearTimeout(this.timerHandle),this.timerHandle=null),this.expiration=null}getEpochTime(){return Math.floor(Date.now()/1e3)}isInitialized(){return this.initialized}}const Ye=Fe("oidc-auth:OidcAuthClient");class Xe{static instance=null;userManager=null;initialized=!1;accessTokenExpiringTimer=null;retryTimers=new Set;constructor(){}static getInstance(){return Xe.instance||(Xe.instance=new Xe),Xe.instance}isInitialized(){return this.initialized}ensureInitialized(){if(!this.userManager)throw new Error("OidcAuthClient not initialized. Call initialize() first.");return this.userManager}initialize(e){if(e&&(this.initialized=!1,Ke.configure(e)),this.initialized)Ye.info("OIDC: initialize() - already initialized, skipping");else if("undefined"!=typeof window)if(Ke.isConfigured())try{Ye.info("OIDC: initialize() - starting initialization");const e=Ke.getOidcSettings();this.userManager=new Oe(e),P.setLogger(Ye),P.setLevel(P.ERROR),this.initAccessTokenExpiringTimer(),this.initialized=!0}catch(e){throw Ye.error("OIDC: initialize() - FAILED:",e),e}else Ye.warn("OIDC: initialize() - skipped, config not set");else Ye.warn("OidcAuthClient cannot initialize on server side")}async initAccessTokenExpiringTimer(){Ke.isAccessTokenProactiveRefreshEnabled()?this.getUser().then(e=>{const t=e?.expires_at;t&&(this.accessTokenExpiringTimer||(this.accessTokenExpiringTimer=new Qe),this.accessTokenExpiringTimer.init(t,Ke.getAccessTokenExpiringNotificationTimeInSeconds(),async()=>{Ye.info("OIDC: timer proactive refresh access token expiring timer fired",t),this.proactiveRefreshWithRetry()}))}).catch(e=>{Ye.error("OIDC: initAccessTokenExpiringTimer - FAILED:",e)}):Ye.warn("OIDC: timer - not starting, access token proactive refresh is disabled")}async getUser(){if(!this.userManager)return null;try{return await this.userManager.getUser()}catch(v){return Ye.error("OIDC: getUser - FAILED:",v),null}}async storeUser(e){const t=this.ensureInitialized();await t.storeUser(e)}async getAccessToken(){const e=await this.getUser();if(!e)return Ye.info("OIDC: getAccessToken - no user found"),null;if(e.expired)try{const e=await this.signinSilent();return e?.access_token||null}catch(e){return Ye.error("OIDC: getAccessToken - silent renew failed:",e),null}return this.isTokenFresh(e)||this.signinSilent().catch(e=>{Ye.error("OIDC: getAccessToken - background refresh failed:",e)}),e.access_token}getUserData(){if("undefined"==typeof window)return null;try{const e=Ke.getOidcSettings(),t=`oidc.user:${e.authority}:${e.client_id}`,i=localStorage.getItem(t);if(!i)return null;const r=JSON.parse(i),n=r?.profile;return n?.sub?(Ye.info("OIDC: USER:",{profile:n}),{id:n.sub,email:n.email||"",first_name:n.given_name,last_name:n.family_name}):null}catch(v){return Ye.error("OIDC: getUserData - FAILED:",v),null}}async isAuthenticated(){const e=await this.getUser();return null!==e&&!e.expired}async signinRedirect(e){const t=this.ensureInitialized();await t.signinRedirect({state:e?{data:e}:void 0,prompt:"login"})}async signinCallback(){const e=this.ensureInitialized(),t=await e.signinCallback();if(!t)throw Ye.error("OIDC: signinCallback - FAILED: no user returned"),new Error("Signin callback failed: no user returned");return t}async signinSilent(e){return this.ensureInitialized(),"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request("oidc-token-refresh",async()=>{const t=await this.getUser();return t&&this.isTokenFresh(t,e)?t:this.doSigninSilent()}):(Ye.warn("OIDC: signinSilent - navigator.locks not available, proceeding without lock"),this.doSigninSilent())}isTokenFresh(e,t){if(!e.expires_at)return!1;const i=t??Ke.getAccessTokenFreshnessThresholdInSeconds(),r=Math.floor(Date.now()/1e3);return e.expires_at-r>i}async doSigninSilent(){const e=this.ensureInitialized();try{return await e.signinSilent()}catch(e){throw Ye.error("OIDC: doSigninSilent - FAILED:",e),e}}proactiveRefreshWithRetry(e=1){if("undefined"!=typeof document&&"hidden"===document.visibilityState){Ye.info("OIDC: tab is hidden, deferring proactive refresh until visible");const t=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",t),this.proactiveRefreshWithRetry(e))};return void document.addEventListener("visibilitychange",t)}this.signinSilent(Ke.getAccessTokenExpiringNotificationTimeInSeconds()).then(()=>{this.initAccessTokenExpiringTimer()}).catch(t=>{if(Ye.error(`OIDC: proactive refresh failed (attempt ${e}/2):`,t),e<2){const t=setTimeout(()=>{this.retryTimers.delete(t),this.proactiveRefreshWithRetry(e+1)},3e3);this.retryTimers.add(t)}else Ye.error("OIDC: proactive refresh exhausted all retries")})}async removeUser(){const e=this.ensureInitialized();this.accessTokenExpiringTimer?.cancel(),this.retryTimers.forEach(clearTimeout),this.retryTimers.clear(),await e.removeUser()}onUserLoaded(e){this.ensureInitialized().events.addUserLoaded(e)}offUserLoaded(e){this.ensureInitialized().events.removeUserLoaded(e)}onUserUnloaded(e){this.ensureInitialized().events.addUserUnloaded(e)}offUserUnloaded(e){this.ensureInitialized().events.removeUserUnloaded(e)}onSilentRenewError(e){this.ensureInitialized().events.addSilentRenewError(e)}offSilentRenewError(e){this.ensureInitialized().events.removeSilentRenewError(e)}onAccessTokenExpiring(e){this.ensureInitialized().events.addAccessTokenExpiring(e)}offAccessTokenExpiring(e){this.ensureInitialized().events.removeAccessTokenExpiring(e)}onAccessTokenExpired(e){this.ensureInitialized().events.addAccessTokenExpired(e)}offAccessTokenExpired(e){this.ensureInitialized().events.removeAccessTokenExpired(e)}getLogoutUrl(e,t){const i=new URL(function(e){return`${Ke.getAuthOrigin()}${e.logoutPath}`}(e));return t&&i.searchParams.set("redirect_to",t),i.toString()}getWindowOriginParam(){const e=new URL(window.location.href).searchParams.get("origin");if(!e)throw new Error("iframe origin param is required");return e}async getTopUrl(){return(await Je({type:Ne})).topUrl}async isOAuthFlowPending(){try{return(await Je({type:Le})).isPending}catch(v){return Ye.warn("OIDC: isOAuthFlowPending() - failed to check, assuming not pending:",v),!1}}async triggerLoginFlowViaParent({loginPath:e,windowPath:t}){Ye.info("OIDC: triggerLoginFlowViaParent() - starting");const i=await this.getTopUrl(),r=new URL(i).origin,n=`${r}${t}`,s=new URL(`${window.location.origin}${e}`);s.searchParams.set(Me,r),s.searchParams.set("oauth2_top_wp_url",n),Ye.info("OIDC: triggerLoginFlowViaParent() - redirecting parent to:",s.toString()),await Je({type:Ue,payload:{url:s.toString()}})}async handleLoginFlowComplete(e,t){if(!t)throw new Error("oauthUserState is required");const i=this.getWindowOriginParam(),r=t.state,n=r?.data?.[Me];if(i!==n)throw Ye.error("OIDC: handleLoginFlowComplete - origin mismatch:",i,"!==",n),new Error("Invalid origin in OAuth state");try{const e=new _e(t);await this.storeUser(e),this.initAccessTokenExpiringTimer(),window.dispatchEvent(new CustomEvent("oidc-auth-completed"))}catch(t){Ye.error("OIDC: handleLoginFlowComplete - FAILED to store user:",t),await this.triggerLoginFlowViaParent(e)}}async triggerLogoutViaParent(e,t=!0){const i=await this.getTopUrl(),r=new URL(i).origin,n=t?`${r}${e.windowPath}`:r;await this.removeUser();const s=this.getLogoutUrl(e,n);await Je({type:Ue,payload:{url:s}})}async cleanOAuthParamsFromUrl(){try{const e=await this.getTopUrl(),t=new URL(e);t.searchParams.delete("oauth_code"),t.searchParams.delete("oauth_state"),t.searchParams.delete("start-oauth"),t.searchParams.delete(He),t.searchParams.delete(qe),await Je({type:De,payload:{url:t.toString()}})}catch(v){Ye.warn("Failed to clean OAuth params from URL:",v)}}setupLoginFlowMessageListener(e){let t=!1;const i=i=>{if(i.data?.type!==Pe)return;if(i.origin!==Ge())return void Ye.error("OIDC: origin mismatch - expected:",Ge(),"received:",i.origin);if(t)return void Ye.debug("OIDC: LOGIN_FLOW_COMPLETE already processed, ignoring duplicate");const r=i.data.payload;r?.oauthState?(t=!0,this.handleLoginFlowComplete(e,r.oauthState).catch(e=>{Ye.error("OIDC: Failed to handle login flow complete:",e),t=!1})):Ye.warn("OIDC: LOGIN_FLOW_COMPLETE but no oauthState in payload")};return window.addEventListener("message",i),()=>{window.removeEventListener("message",i)}}async getTokenExpirationInfo(){const e=await this.getUser();if(!e||!e.expires_at)return{expiresAt:null,expiresInSeconds:null,isExpired:!0};const t=new Date(1e3*e.expires_at),i=Date.now(),r=Math.floor((1e3*e.expires_at-i)/1e3);return{expiresAt:t,expiresInSeconds:r,isExpired:r<=0}}async forceTokenRefresh(){return Ye.info("OIDC: forceTokenRefresh() - manually triggering token refresh"),this.signinSilent()}}const Ze=Xe.getInstance();"undefined"!=typeof window&&(window.oidcAuthClient=Ze);const et=Fe("oidc-auth:oidc-auth-redirect");function tt(e,t){e.postMessage({status:"success",payload:t})}function it(e,t){e.postMessage({status:"error",payload:t})}function rt({targets:e,onSuccess:t,attempt:i=1}){const r=new URLSearchParams(window.location.search);if(!r.get(He))return void et.warn("OIDC: No login_success param found, skipping");const n=r.get(qe);if(n){if(!e.window?.contentWindow||!e.windowURL)return et.warn("Cannot forward OIDC state: iframe not available"),void(i<5?setTimeout(()=>{rt({targets:e,onSuccess:t,attempt:i+1})},500):et.error("OIDC: Failed to forward login flow after",5,"attempts - iframe never became available"));try{const i=JSON.parse(n),r=i.state?.data?.[Me];if(r&&r!==window.location.origin)return void et.error("Origin mismatch in OIDC state:",r,"vs",window.location.origin);!function(e,t){const i=t.window?.contentWindow,r=t.windowURL?.origin;i&&r?i.postMessage({type:Pe,payload:e},r):et.warn("Cannot send OIDC state: window or origin not available")}({oauthState:i},e);const s=new URL(window.location.href);s.searchParams.delete(He),s.searchParams.delete(qe),history.replaceState({},"",s.toString()),t?.()}catch(e){et.error("Failed to parse or forward OIDC state:",e)}}else et.warn("OIDC login complete but no state found in URL")}const nt="angie_return_url",st=h("referrer-redirect"),ot=h("oauth");function at(){const e=function(){try{const e=localStorage.getItem(nt);if(!e)return null;let t;try{t=JSON.parse(e)}catch{return st.warn("Stored redirect data is not valid JSON, returning null"),null}return t.url&&"string"==typeof t.url?function(e){try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}(t.url)?t:(st.warn("Stored redirect URL is invalid, returning null:",t.url),null):(st.warn("Stored redirect data missing url field, returning null"),null)}catch(e){return st.warn("localStorage not available"),null}}();if(e)return function(){try{localStorage.removeItem(nt)}catch(e){st.warn("localStorage not available")}}(),void(window.location.href=(t=e.url,i=e.prompt,i?`${t}#angie-prompt=${encodeURIComponent(i)}`:t));var t,i;try{localStorage.setItem("angie_sidebar_state","open")}catch(e){ot.warn("localStorage not available")}setTimeout(()=>{window.toggleAngieSidebar(!0)},500)}const ct=(e,t)=>{const i=document.getElementById("angie-sidebar-container");i&&i.setAttribute("aria-hidden",t?"false":"true"),t?e.removeAttribute("tabindex"):e.setAttribute("tabindex","-1")},lt=(e,t)=>{e.postMessage({status:"success",payload:t})},dt=h("sdk");var ut;(ut||(ut={})).POST_MESSAGE="postMessage";const gt=h("iframe-utils");let ht=null;const pt=()=>(ht&&document.contains(ht)||(ht=document.querySelector('iframe[src*="angie/"]')),ht),_t=(e,t)=>{gt.log("postMessageToAngieIframe",e,t);const i=pt();if(!i?.contentWindow)return!1;const r=t||(()=>{const e=pt();if(!e)return null;try{return new URL(e.src).origin}catch(e){return gt.error("Error parsing iframe URL:",e),null}})();return r?(i.contentWindow.postMessage(e,r),!0):(gt.error("Could not determine target origin for Angie iframe"),!1)},mt=h("sidebar");let ft=!1;const wt=h("iframe"),yt=async()=>{if(I.iframe?.contentWindow&&I.iframeUrlObject)try{wt.log("Disabling navigation prevention in Angie iframe"),I.iframe.contentWindow.postMessage({type:w.ANGIE_DISABLE_NAVIGATION_PREVENTION},I.iframeUrlObject.origin),await new Promise(e=>setTimeout(e,100))}catch(v){throw wt.error("Failed to disable navigation prevention:",v),v}else wt.warn("Cannot disable navigation prevention: iframe or origin not available")},St=h("registration-queue");class vt{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),St.log(`Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter(e=>"pending"===e.status)}updateStatus(e,t,i){const r=this.queue.find(t=>t.id===e);r&&(r.status=t,i?r.error=i:"pending"!==t&&"registered"!==t||delete r.error,St.log(`Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void St.log("Already processing queue");this.isProcessing=!0;const t=this.getPending();St.log(`Processing ${t.length} pending registrations`);try{for(const i of t)try{await e(i),this.updateStatus(i.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(i.id,"failed",t),St.error(`Failed to process registration ${i.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],St.log("Cleared all registrations")}resetAllToPending(){if(this.isProcessing)return St.log("Cannot reset to pending - processing in progress"),!1;const e=this.queue.filter(e=>"registered"===e.status).length,t=this.queue.filter(e=>"failed"===e.status).length;return this.queue.forEach(e=>{"pending"!==e.status&&(e.status="pending",delete e.error)}),St.log(`Reset ${e+t} registrations to pending`),!0}remove(e){const t=this.queue.findIndex(t=>t.id===e);return-1!==t&&(this.queue.splice(t,1),St.log(`Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}class bt{angieDetector;clientManager;logger;registrationQueue;isInitialized=!1;instanceId;constructor(){this.instanceId=Math.random().toString(36).substring(2,8),this.logger=h({instanceId:this.instanceId}),this.logger.log("Constructor called - initializing SDK"),this.angieDetector=new E,this.registrationQueue=new vt,this.clientManager=new T,this.logger.log("Setting up event handlers"),this.setupAngieReadyHandler(),this.setupServerInitHandler(),this.setupReRegistrationHandler(),this.logger.log("SDK initialization complete")}async loadSidebar(e){!function(){if("undefined"==typeof document||ft)return;const e="angie-sidebar-styles";if(document.getElementById(e))return void(ft=!0);const t=document.createElement("style");t.id=e,t.textContent="/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* Layout (default) - Push content */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n";const i=document.head||document.getElementsByTagName("head")[0];i.insertBefore(t,i.firstChild),ft=!0}(),"undefined"!=typeof window&&(window.toggleAngieSidebar=function(e){return function(t,i){const r=document.body,n=document.getElementById("angie-sidebar-container");if(!n)return void mt.warn("Required elements not found!");const s=r.classList.contains("angie-sidebar-active"),o=void 0!==t?t:!s;i||(r.classList.add("angie-sidebar-transitioning"),setTimeout(function(){r.classList.remove("angie-sidebar-transitioning")},300)),o?r.classList.add("angie-sidebar-active"):r.classList.remove("angie-sidebar-active"),o&&setTimeout(function(){_t({type:"focusInput"})},i?0:300),e&&e(o,n,i),function(e){try{localStorage.setItem("angie_sidebar_state",e)}catch(e){mt.warn("localStorage not available")}}(o?"open":"closed");const a=new CustomEvent("angieSidebarToggle",{detail:{isOpen:o,sidebar:n,skipTransition:i}});document.dispatchEvent(a),_t({type:w.ANGIE_SIDEBAR_TOGGLED,payload:{state:o?"opened":"closed"}})}}(void 0),window.addEventListener("message",function(e){if(e.data&&"toggleAngieSidebar"===e.data.type){const{force:t,skipTransition:i}=e.data.payload||{};window.toggleAngieSidebar&&window.toggleAngieSidebar(t,i)}})),await(async e=>{if(window.screen.availWidth<=768)return void wt.log("Mobile detected, skipping iframe injection");let t=document.getElementById("angie-sidebar-container");if(!t){const e=performance.now();if(wt.log("\u23f1\ufe0f Waiting for sidebar container..."),await new Promise(e=>{let i=0;const r=setInterval(()=>{t=document.getElementById("angie-sidebar-container"),i++,(t||i>20)&&(clearInterval(r),t&&e())},100);setTimeout(()=>{if(clearInterval(r),t)return void e();const i=new MutationObserver(()=>{t=document.getElementById("angie-sidebar-container"),t&&(i.disconnect(),e())});i.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{i.disconnect(),e()},8e3)},2e3)}),wt.log(`\u23f1\ufe0f Sidebar container detection took: ${(performance.now()-e).toFixed(2)}ms`),!t)return void wt.error("Sidebar container not found")}const{iframe:i,iframeUrlObject:r}=await(async e=>{const t=e.origin,i=new URL(e.path,t),r=i.pathname.slice(1).replace(/\//,"--")+"-"+Math.random().toString(36).substring(7);return new Promise(n=>{const s=new URL(t);s.pathname=i.pathname;const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(s.searchParams.append("colorScheme",e.uiTheme||o||"light"),s.searchParams.append("sdkVersion",e.sdkVersion),s.searchParams.append("instanceId",r),s.searchParams.append("origin",window.location.origin),e.isRTL&&s.searchParams.append("isRTL",e.isRTL?"true":"false"),"localhost"===window.location.hostname&&window.location.search.includes("debug_error")){const e=new URLSearchParams(window.location.search).get("debug_error");e&&s.searchParams.append("debug_error",e)}i.searchParams.forEach((e,t)=>{s.searchParams.set(t,e)}),s.searchParams.set("ver",(new Date).getTime().toString());const a=e.parent||document,c=a.createElement("iframe"),l={"background-color":"transparent","color-scheme":"normal",...e.css};window.addEventListener("message",async e=>{if(e.origin===s.origin)switch(e.data.type){case S.ANGIE_READY:n({iframe:c,iframeUrlObject:s});break;case S.ANGIE_LOADED:c.contentWindow?.postMessage({type:S.HOST_READY,instanceId:r},s.origin)}}),c.setAttribute("src",s.href),c.id="angie-iframe",c.setAttribute("frameborder","0"),c.setAttribute("scrolling","no"),c.setAttribute("style",Object.entries(l).map(([e,t])=>`${e}: ${t}`).join("; ")),c.setAttribute("allow","clipboard-write; clipboard-read"),e.insertCallback?e.insertCallback(c):a.body.appendChild(c)})})({origin:e.origin||"https://angie.elementor.com",path:"angie/wp-admin",insertCallback:e=>{wt.log("Injecting Angie iframe into sidebar container"),e.setAttribute("title","Angie AI Assistant"),e.setAttribute("role","application"),e.setAttribute("aria-label","Angie AI Assistant Interface");const i=document.getElementById("angie-sidebar-loading");i&&(i.textContent=""),t?.appendChild(e),ct(e,!0),e.addEventListener("load",()=>{e.focus()})},css:{width:"100%",height:"100%",border:"none",outline:"none"},uiTheme:e.uiTheme,isRTL:e.isRTL,sdkVersion:"1.4.0"});I.iframe=i,I.iframeUrlObject=r,window.addEventListener("message",e=>{if(e.origin===I.iframeUrlObject?.origin)switch(e.data.type){case y.SET:window.localStorage.setItem(e.data.key,e.data.value);break;case y.GET:{const t=e.ports[0],i=window.localStorage.getItem(e.data.key);t.postMessage({value:i});break}}}),(e=>{window.addEventListener("message",async t=>{if(t.origin===window.location.origin||t.origin===e.iframeUrlObject?.origin)switch(t?.data?.type){case w.SDK_ANGIE_ALL_SERVERS_REGISTERED:break;case w.SDK_ANGIE_READY_PING:{const e=t.ports[0];dt.log("Angie is ready",t),lt(e,{message:"Angie is ready"});break}case w.SDK_REQUEST_CLIENT_CREATION:{const i=t.data.payload;try{const r=t.ports[0],n=new MessageChannel;n.port1.onmessage=e=>{r.postMessage({success:!0,data:e.data})};const s={type:w.SDK_REQUEST_CLIENT_CREATION,payload:{success:!0,...i,clientId:`dynamic-client-${i.serverName}-${i.serverVersion}-${Date.now()}`,requestId:t.data.payload.requestId},timestamp:Date.now()};if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage(s,e.iframeUrlObject?.origin||"",[n.port2])}catch(e){dt.error(`Failed to create client for SDK server "${i.serverName}":`,e)}break}case w.SDK_TRIGGER_ANGIE:dt.log("SDK Trigger Angie received",t.data);try{const{requestId:i,prompt:r,context:n}=t.data.payload;if(!e.iframe)throw new Error("Iframe not found");e.iframe.contentWindow?.postMessage({type:w.SDK_TRIGGER_ANGIE,payload:{requestId:i,prompt:r,context:n}},e.iframeUrlObject?.origin||""),window.postMessage({type:w.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!0,requestId:i,response:"Angie triggered successfully"}},window.location.origin)}catch(e){dt.error("Failed to trigger Angie:",e),window.postMessage({type:w.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!1,requestId:t.data.payload?.requestId,error:e instanceof Error?e.message:"Unknown error"}},window.location.origin)}}})})(I),function({trustedOrigin:e,onOAuthParamsCleared:t}){window.addEventListener("message",i=>{if(i.origin!==e)return;const r=i.ports?.[0];switch(i.data.type){case Ne:if(!r)return;tt(r,{topUrl:window.location.href});break;case Ue:window.location.href=i.data.payload.url;break;case De:{if(!r)return;const n=i.data.payload.url;if(!history?.replaceState)return void it(r,{message:"URL update not supported in this browser"});try{const e=window.location.href;history.replaceState({},"",n),function(e,t){const i=new URL(e).searchParams,r=new URL(t).searchParams,n=[He,qe,Me];return n.some(e=>i.has(e))&&!n.some(e=>r.has(e))}(e,n)&&t?.(),tt(r,{message:"URL updated successfully"})}catch(e){it(r,{message:"URL update failed: "+(e instanceof Error?e.message:"Unknown error")})}break}case Le:if(!r)return;tt(r,{isPending:"true"===new URLSearchParams(window.location.search).get(He)})}})}({trustedOrigin:I.iframeUrlObject?.origin??"",onOAuthParamsCleared:at}),(()=>{const e={window:I.iframe,windowURL:I.iframeUrlObject};window.addEventListener("load",()=>{ot.log("OIDC: Window load event fired, forwarding OIDC state if present"),rt({targets:e,onSuccess:at})}),rt({targets:e,onSuccess:at})})(),window.addEventListener("message",async t=>{if([window.location.origin,e.origin||"https://angie.elementor.com"].includes(t.origin))if(t?.data?.type===w.ANGIE_CHAT_TOGGLE)I.open=t.data.open,I.iframe&&ct(I.iframe,I.open);else if(t?.data?.type===w.ANGIE_STUDIO_TOGGLE){if(!I.iframe)return;if(t.data.isStudioOpen)document.documentElement.classList.add("angie-studio-active");else{const e=function(){if("undefined"==typeof window)return 370;try{const e=window.localStorage.getItem("angie_sidebar_width");if(e){const t=parseInt(e,10);if(t>=350&&t<=590)return t}}catch(e){mt.warn("localStorage not available")}return 370}();document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`),document.documentElement.classList.remove("angie-studio-active")}}else if(t?.data?.type===w.ANGIE_NAVIGATE_TO_URL){const{url:e="",confirmed:i=!1}=t.data.payload||{};if(!i)return void wt.log("Navigation requires user confirmation");if(!((e,t=[])=>{const i=0===t.length&&"undefined"!=typeof window?[window.location.origin]:t;if(!e.startsWith("http"))return!1;try{const t=new URL(e);return i.includes(t.origin)}catch{return!1}})(e))return void wt.error("Navigation blocked: Invalid or unsafe URL",{url:e});await yt(),window.location.assign(e)}else if(t?.data?.type===w.ANGIE_PAGE_RELOAD){const{confirmed:e=!1}=t.data.payload||{};if(!e)return void wt.log("Page reload requires user confirmation");wt.log("Page reload confirmed - disabling navigation prevention and reloading"),await yt(),setTimeout(()=>{window.location.reload()},50)}else t?.data?.type===S.RESET_HASH&&(window.location.hash="",lt(t.ports[0],{message:"Hash reset successfully"}))})})({origin:e?.origin||"https://angie.elementor.com",uiTheme:e?.uiTheme||"light",isRTL:e?.isRTL||!1,...e}),this.setupPromptHashDetection()}setupReRegistrationHandler(){window.addEventListener("message",e=>{if(e.data?.type===w.SDK_ANGIE_REFRESH_PING)if(this.logger.log("Angie refresh ping received"),this.registrationQueue.resetAllToPending()){const e=this.registrationQueue.getPending().length;this.logger.log(`Successfully reset ${e} registrations, processing queue`),this.handleAngieReady()}else this.logger.log("Skipping queue reset - processing already in progress")})}setupAngieReadyHandler(){this.angieDetector.waitForReady().then(e=>{e.isReady?this.handleAngieReady():this.logger.warn("Angie not detected - servers will remain queued")}).catch(e=>{this.logger.error("Error waiting for Angie:",e)})}async handleAngieReady(){this.logger.log("Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue(async e=>{this.logger.log(`processQueue callback called for "${e.config.name}"`),await this.processRegistration(e)}),this.isInitialized=!0,this.logger.log("Initialization complete")}catch(v){this.logger.error("Error processing registration queue:",v)}}async processRegistration(e){this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);try{this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);const t={...e,instanceId:this.instanceId};await this.clientManager.requestClientCreation(t),this.logger.log(`Successfully registered server "${e.config.name}"`)}catch(n){throw this.logger.error(`Failed to register server "${e.config.name}":`,n),n}}registerLocalServer(e){return e.type=f.LOCAL,e.transport=_.POST_MESSAGE,this.registerServer(e)}registerRemoteServer(e){return e.type=f.REMOTE,this.registerServer(e)}isLocalServerConfig(e){return e.type===f.LOCAL||!e.type&&"server"in e}isRemoteServerConfig(e){return e.type===f.REMOTE&&"url"in e}async registerServer(e){if(!e.type)return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"),void this.registerLocalServer(e);if(this.logger.log(`registerServer called for "${e.name}"`),!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");if(this.isLocalServerConfig(e)&&!e.server)throw new Error("Server instance is required for local servers");this.logger.log(`Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.logger.log(`Added registration to queue: ${t.id}`),this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),this.logger.log(`Server "${e.name}" registered successfully`)}catch(e){const i=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",i),e}else this.logger.log(`Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}async triggerAngie(e){if(!this.isAngieReady())throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");const t=this.generateRequestId(),i=e.options?.timeout||3e4;return new Promise((r,n)=>{const s=setTimeout(()=>{n(new Error("Angie trigger request timed out"))},i),o=e=>{e.data?.type===w.SDK_TRIGGER_ANGIE_RESPONSE&&e.data?.payload?.requestId===t&&(clearTimeout(s),window.removeEventListener("message",o),r(e.data.payload))};window.addEventListener("message",o);const a={type:w.SDK_TRIGGER_ANGIE,payload:{requestId:t,prompt:e.prompt,options:e.options,context:{pageUrl:window.location.href,pageTitle:document.title,...e.context}},timestamp:Date.now()};this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`),window.postMessage(a,window.location.origin)})}destroy(){this.registrationQueue.clear(),this.logger.log("SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",e=>{e.data?.type===w.SDK_REQUEST_INIT_SERVER&&(this.logger.log("Server init request received"),this.handleServerInitRequest(e))})}handleServerInitRequest(e){const{clientId:t,serverId:i,instanceId:r}=e.data.payload||{};if(t&&i)if(this.logger.log(`Server init request received - Request instanceId: ${r}, This instanceId: ${this.instanceId}`),r&&r!==this.instanceId)this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${r}, this instanceId: ${this.instanceId}`);else{this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${i}`);try{const t=this.registrationQueue.getAll().find(e=>e.id===i);if(!t)return void this.logger.error(`No registration found for serverId: ${i}`);if("type"in t.config&&"remote"===t.config.type)return void this.logger.log("Remote server registration detected; skipping local connect");const r=e.ports[0];if(!r)return void this.logger.error("No port provided in server init request");const n=t.config.server;this.migrateInstructionsCompat(n);const s=new k(r);n.connect(s),this.logger.log(`Server "${t.config.name}" initialized successfully`)}catch(e){this.logger.error(`Error initializing server for clientId ${t}:`,e)}}else this.logger.error("Invalid server init request - missing clientId or serverId")}migrateInstructionsCompat(e){try{const t="server"in e&&e.server?e.server:e,i=t._serverInfo,r=t._instructions;i?.instructions&&!r&&(t._instructions=i.instructions,this.logger.log("Migrated instructions from serverInfo to serverOptions (backward compat)"))}catch{}}generateRequestId(){return`${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}async handlePromptHash(){const e=window.location.hash;if(e.startsWith("#angie-prompt="))try{const t=e.replace("#angie-prompt=",""),i=decodeURIComponent(t);if(!i)return void this.logger.warn("Empty prompt detected in hash");this.logger.log("Detected prompt in hash:",i),await this.waitForReady();const r=await this.triggerAngie({prompt:i,context:{source:"hash-parameter",pageUrl:window.location.href,timestamp:(new Date).toISOString()}});this.logger.log("Triggered successfully from hash:",r),window.location.hash=""}catch(e){this.logger.error("Failed to trigger from hash:",e)}}setupPromptHashDetection(){this.handlePromptHash(),window.addEventListener("hashchange",()=>this.handlePromptHash())}}h("navigation")},99418(e,t,i){i.d(t,{A:()=>ie});const{entries:r,setPrototypeOf:n,isFrozen:s,getPrototypeOf:o,getOwnPropertyDescriptor:a}=Object;let{freeze:c,seal:l,create:d}=Object,{apply:u,construct:g}="undefined"!==typeof Reflect&&Reflect;c||(c=function(e){return e}),l||(l=function(e){return e}),u||(u=function(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return e.apply(t,r)}),g||(g=function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return new e(...i)});const h=R(Array.prototype.forEach),p=R(Array.prototype.lastIndexOf),_=R(Array.prototype.pop),m=R(Array.prototype.push),f=R(Array.prototype.splice),w=R(String.prototype.toLowerCase),y=R(String.prototype.toString),S=R(String.prototype.match),v=R(String.prototype.replace),b=R(String.prototype.indexOf),E=R(String.prototype.trim),k=R(Object.prototype.hasOwnProperty),T=R(RegExp.prototype.test),I=(A=TypeError,function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return g(A,t)});var A;function R(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];return u(e,t,r)}}function C(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:w;n&&n(e,null);let r=t.length;for(;r--;){let n=t[r];if("string"===typeof n){const e=i(n);e!==n&&(s(t)||(t[r]=e),n=e)}e[n]=!0}return e}function x(e){for(let t=0;t<e.length;t++)k(e,t)||(e[t]=null);return e}function O(e){const t=d(null);for(const[i,n]of r(e))k(e,i)&&(t[i]=Array.isArray(n)?x(n):n&&"object"===typeof n&&n.constructor===Object?O(n):n);return t}function P(e,t){for(;null!==e;){const i=a(e,t);if(i){if(i.get)return R(i.get);if("function"===typeof i.value)return R(i.value)}e=o(e)}return function(){return null}}const N=c(["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"]),U=c(["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"]),D=c(["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"]),L=c(["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"]),M=c(["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"]),H=c(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),q=c(["#text"]),$=c(["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"]),j=c(["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"]),z=c(["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"]),F=c(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),G=l(/\{\{[\w\W]*|[\w\W]*\}\}/gm),W=l(/<%[\w\W]*|[\w\W]*%>/gm),K=l(/\$\{[\w\W]*/gm),B=l(/^data-[\-\w.\u00B7-\uFFFF]+$/),J=l(/^aria-[\-\w]+$/),V=l(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Q=l(/^(?:\w+script|data):/i),Y=l(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),X=l(/^html$/i),Z=l(/^[a-z][.\w]*(-[.\w]+)+$/i);var ee=Object.freeze({__proto__:null,ARIA_ATTR:J,ATTR_WHITESPACE:Y,CUSTOM_ELEMENT:Z,DATA_ATTR:B,DOCTYPE_NAME:X,ERB_EXPR:W,IS_ALLOWED_URI:V,IS_SCRIPT_OR_DATA:Q,MUSTACHE_EXPR:G,TMPLIT_EXPR:K});const te=function(){return"undefined"===typeof window?null:window};var ie=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:te();const i=t=>e(t);if(i.version="3.3.1",i.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return i.isSupported=!1,i;let{document:n}=t;const s=n,o=s.currentScript,{DocumentFragment:a,HTMLTemplateElement:l,Node:u,Element:g,NodeFilter:A,NamedNodeMap:R=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:x,DOMParser:G,trustedTypes:W}=t,K=g.prototype,B=P(K,"cloneNode"),J=P(K,"remove"),Q=P(K,"nextSibling"),Y=P(K,"childNodes"),Z=P(K,"parentNode");if("function"===typeof l){const e=n.createElement("template");e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let ie,re="";const{implementation:ne,createNodeIterator:se,createDocumentFragment:oe,getElementsByTagName:ae}=n,{importNode:ce}=s;let le={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};i.isSupported="function"===typeof r&&"function"===typeof Z&&ne&&void 0!==ne.createHTMLDocument;const{MUSTACHE_EXPR:de,ERB_EXPR:ue,TMPLIT_EXPR:ge,DATA_ATTR:he,ARIA_ATTR:pe,IS_SCRIPT_OR_DATA:_e,ATTR_WHITESPACE:me,CUSTOM_ELEMENT:fe}=ee;let{IS_ALLOWED_URI:we}=ee,ye=null;const Se=C({},[...N,...U,...D,...M,...q]);let ve=null;const be=C({},[...$,...j,...z,...F]);let Ee=Object.seal(d(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ke=null,Te=null;const Ie=Object.seal(d(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Ae=!0,Re=!0,Ce=!1,xe=!0,Oe=!1,Pe=!0,Ne=!1,Ue=!1,De=!1,Le=!1,Me=!1,He=!1,qe=!0,$e=!1,je=!0,ze=!1,Fe={},Ge=null;const We=C({},["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"]);let Ke=null;const Be=C({},["audio","video","img","source","image","track"]);let Je=null;const Ve=C({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Qe="http://www.w3.org/1998/Math/MathML",Ye="http://www.w3.org/2000/svg",Xe="http://www.w3.org/1999/xhtml";let Ze=Xe,et=!1,tt=null;const it=C({},[Qe,Ye,Xe],y);let rt=C({},["mi","mo","mn","ms","mtext"]),nt=C({},["annotation-xml"]);const st=C({},["title","style","font","a","script"]);let ot=null;const at=["application/xhtml+xml","text/html"];let ct=null,lt=null;const dt=n.createElement("form"),ut=function(e){return e instanceof RegExp||e instanceof Function},gt=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!lt||lt!==e){if(e&&"object"===typeof e||(e={}),e=O(e),ot=-1===at.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,ct="application/xhtml+xml"===ot?y:w,ye=k(e,"ALLOWED_TAGS")?C({},e.ALLOWED_TAGS,ct):Se,ve=k(e,"ALLOWED_ATTR")?C({},e.ALLOWED_ATTR,ct):be,tt=k(e,"ALLOWED_NAMESPACES")?C({},e.ALLOWED_NAMESPACES,y):it,Je=k(e,"ADD_URI_SAFE_ATTR")?C(O(Ve),e.ADD_URI_SAFE_ATTR,ct):Ve,Ke=k(e,"ADD_DATA_URI_TAGS")?C(O(Be),e.ADD_DATA_URI_TAGS,ct):Be,Ge=k(e,"FORBID_CONTENTS")?C({},e.FORBID_CONTENTS,ct):We,ke=k(e,"FORBID_TAGS")?C({},e.FORBID_TAGS,ct):O({}),Te=k(e,"FORBID_ATTR")?C({},e.FORBID_ATTR,ct):O({}),Fe=!!k(e,"USE_PROFILES")&&e.USE_PROFILES,Ae=!1!==e.ALLOW_ARIA_ATTR,Re=!1!==e.ALLOW_DATA_ATTR,Ce=e.ALLOW_UNKNOWN_PROTOCOLS||!1,xe=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Oe=e.SAFE_FOR_TEMPLATES||!1,Pe=!1!==e.SAFE_FOR_XML,Ne=e.WHOLE_DOCUMENT||!1,Le=e.RETURN_DOM||!1,Me=e.RETURN_DOM_FRAGMENT||!1,He=e.RETURN_TRUSTED_TYPE||!1,De=e.FORCE_BODY||!1,qe=!1!==e.SANITIZE_DOM,$e=e.SANITIZE_NAMED_PROPS||!1,je=!1!==e.KEEP_CONTENT,ze=e.IN_PLACE||!1,we=e.ALLOWED_URI_REGEXP||V,Ze=e.NAMESPACE||Xe,rt=e.MATHML_TEXT_INTEGRATION_POINTS||rt,nt=e.HTML_INTEGRATION_POINTS||nt,Ee=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ut(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ee.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ut(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ee.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"===typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Ee.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Oe&&(Re=!1),Me&&(Le=!0),Fe&&(ye=C({},q),ve=[],!0===Fe.html&&(C(ye,N),C(ve,$)),!0===Fe.svg&&(C(ye,U),C(ve,j),C(ve,F)),!0===Fe.svgFilters&&(C(ye,D),C(ve,j),C(ve,F)),!0===Fe.mathMl&&(C(ye,M),C(ve,z),C(ve,F))),e.ADD_TAGS&&("function"===typeof e.ADD_TAGS?Ie.tagCheck=e.ADD_TAGS:(ye===Se&&(ye=O(ye)),C(ye,e.ADD_TAGS,ct))),e.ADD_ATTR&&("function"===typeof e.ADD_ATTR?Ie.attributeCheck=e.ADD_ATTR:(ve===be&&(ve=O(ve)),C(ve,e.ADD_ATTR,ct))),e.ADD_URI_SAFE_ATTR&&C(Je,e.ADD_URI_SAFE_ATTR,ct),e.FORBID_CONTENTS&&(Ge===We&&(Ge=O(Ge)),C(Ge,e.FORBID_CONTENTS,ct)),e.ADD_FORBID_CONTENTS&&(Ge===We&&(Ge=O(Ge)),C(Ge,e.ADD_FORBID_CONTENTS,ct)),je&&(ye["#text"]=!0),Ne&&C(ye,["html","head","body"]),ye.table&&(C(ye,["tbody"]),delete ke.tbody),e.TRUSTED_TYPES_POLICY){if("function"!==typeof e.TRUSTED_TYPES_POLICY.createHTML)throw I('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!==typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw I('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ie=e.TRUSTED_TYPES_POLICY,re=ie.createHTML("")}else void 0===ie&&(ie=function(e,t){if("object"!==typeof e||"function"!==typeof e.createPolicy)return null;let i=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(i=t.getAttribute(r));const n="dompurify"+(i?"#"+i:"");try{return e.createPolicy(n,{createHTML:e=>e,createScriptURL:e=>e})}catch(s){return null}}(W,o)),null!==ie&&"string"===typeof re&&(re=ie.createHTML(""));c&&c(e),lt=e}},ht=C({},[...U,...D,...L]),pt=C({},[...M,...H]),_t=function(e){m(i.removed,{element:e});try{Z(e).removeChild(e)}catch(t){J(e)}},mt=function(e,t){try{m(i.removed,{attribute:t.getAttributeNode(e),from:t})}catch(r){m(i.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(Le||Me)try{_t(t)}catch(r){}else try{t.setAttribute(e,"")}catch(r){}},ft=function(e){let t=null,i=null;if(De)e="<remove></remove>"+e;else{const t=S(e,/^[\r\n\t ]+/);i=t&&t[0]}"application/xhtml+xml"===ot&&Ze===Xe&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const r=ie?ie.createHTML(e):e;if(Ze===Xe)try{t=(new G).parseFromString(r,ot)}catch(o){}if(!t||!t.documentElement){t=ne.createDocument(Ze,"template",null);try{t.documentElement.innerHTML=et?re:r}catch(o){}}const s=t.body||t.documentElement;return e&&i&&s.insertBefore(n.createTextNode(i),s.childNodes[0]||null),Ze===Xe?ae.call(t,Ne?"html":"body")[0]:Ne?t.documentElement:s},wt=function(e){return se.call(e.ownerDocument||e,e,A.SHOW_ELEMENT|A.SHOW_COMMENT|A.SHOW_TEXT|A.SHOW_PROCESSING_INSTRUCTION|A.SHOW_CDATA_SECTION,null)},yt=function(e){return e instanceof x&&("string"!==typeof e.nodeName||"string"!==typeof e.textContent||"function"!==typeof e.removeChild||!(e.attributes instanceof R)||"function"!==typeof e.removeAttribute||"function"!==typeof e.setAttribute||"string"!==typeof e.namespaceURI||"function"!==typeof e.insertBefore||"function"!==typeof e.hasChildNodes)},St=function(e){return"function"===typeof u&&e instanceof u};function vt(e,t,r){h(e,e=>{e.call(i,t,r,lt)})}const bt=function(e){let t=null;if(vt(le.beforeSanitizeElements,e,null),yt(e))return _t(e),!0;const r=ct(e.nodeName);if(vt(le.uponSanitizeElement,e,{tagName:r,allowedTags:ye}),Pe&&e.hasChildNodes()&&!St(e.firstElementChild)&&T(/<[/\w!]/g,e.innerHTML)&&T(/<[/\w!]/g,e.textContent))return _t(e),!0;if(7===e.nodeType)return _t(e),!0;if(Pe&&8===e.nodeType&&T(/<[/\w]/g,e.data))return _t(e),!0;if(!(Ie.tagCheck instanceof Function&&Ie.tagCheck(r))&&(!ye[r]||ke[r])){if(!ke[r]&&kt(r)){if(Ee.tagNameCheck instanceof RegExp&&T(Ee.tagNameCheck,r))return!1;if(Ee.tagNameCheck instanceof Function&&Ee.tagNameCheck(r))return!1}if(je&&!Ge[r]){const t=Z(e)||e.parentNode,i=Y(e)||e.childNodes;if(i&&t)for(let r=i.length-1;r>=0;--r){const n=B(i[r],!0);n.__removalCount=(e.__removalCount||0)+1,t.insertBefore(n,Q(e))}}return _t(e),!0}return e instanceof g&&!function(e){let t=Z(e);t&&t.tagName||(t={namespaceURI:Ze,tagName:"template"});const i=w(e.tagName),r=w(t.tagName);return!!tt[e.namespaceURI]&&(e.namespaceURI===Ye?t.namespaceURI===Xe?"svg"===i:t.namespaceURI===Qe?"svg"===i&&("annotation-xml"===r||rt[r]):Boolean(ht[i]):e.namespaceURI===Qe?t.namespaceURI===Xe?"math"===i:t.namespaceURI===Ye?"math"===i&&nt[r]:Boolean(pt[i]):e.namespaceURI===Xe?!(t.namespaceURI===Ye&&!nt[r])&&!(t.namespaceURI===Qe&&!rt[r])&&!pt[i]&&(st[i]||!ht[i]):!("application/xhtml+xml"!==ot||!tt[e.namespaceURI]))}(e)?(_t(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!T(/<\/no(script|embed|frames)/i,e.innerHTML)?(Oe&&3===e.nodeType&&(t=e.textContent,h([de,ue,ge],e=>{t=v(t,e," ")}),e.textContent!==t&&(m(i.removed,{element:e.cloneNode()}),e.textContent=t)),vt(le.afterSanitizeElements,e,null),!1):(_t(e),!0)},Et=function(e,t,i){if(qe&&("id"===t||"name"===t)&&(i in n||i in dt))return!1;if(Re&&!Te[t]&&T(he,t));else if(Ae&&T(pe,t));else if(Ie.attributeCheck instanceof Function&&Ie.attributeCheck(t,e));else if(!ve[t]||Te[t]){if(!(kt(e)&&(Ee.tagNameCheck instanceof RegExp&&T(Ee.tagNameCheck,e)||Ee.tagNameCheck instanceof Function&&Ee.tagNameCheck(e))&&(Ee.attributeNameCheck instanceof RegExp&&T(Ee.attributeNameCheck,t)||Ee.attributeNameCheck instanceof Function&&Ee.attributeNameCheck(t,e))||"is"===t&&Ee.allowCustomizedBuiltInElements&&(Ee.tagNameCheck instanceof RegExp&&T(Ee.tagNameCheck,i)||Ee.tagNameCheck instanceof Function&&Ee.tagNameCheck(i))))return!1}else if(Je[t]);else if(T(we,v(i,me,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==b(i,"data:")||!Ke[e])if(Ce&&!T(_e,v(i,me,"")));else if(i)return!1;return!0},kt=function(e){return"annotation-xml"!==e&&S(e,fe)},Tt=function(e){vt(le.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||yt(e))return;const r={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ve,forceKeepAttr:void 0};let n=t.length;for(;n--;){const o=t[n],{name:a,namespaceURI:c,value:l}=o,d=ct(a),u=l;let g="value"===a?u:E(u);if(r.attrName=d,r.attrValue=g,r.keepAttr=!0,r.forceKeepAttr=void 0,vt(le.uponSanitizeAttribute,e,r),g=r.attrValue,!$e||"id"!==d&&"name"!==d||(mt(a,e),g="user-content-"+g),Pe&&T(/((--!?|])>)|<\/(style|title|textarea)/i,g)){mt(a,e);continue}if("attributename"===d&&S(g,"href")){mt(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){mt(a,e);continue}if(!xe&&T(/\/>/i,g)){mt(a,e);continue}Oe&&h([de,ue,ge],e=>{g=v(g,e," ")});const p=ct(e.nodeName);if(Et(p,d,g)){if(ie&&"object"===typeof W&&"function"===typeof W.getAttributeType)if(c);else switch(W.getAttributeType(p,d)){case"TrustedHTML":g=ie.createHTML(g);break;case"TrustedScriptURL":g=ie.createScriptURL(g)}if(g!==u)try{c?e.setAttributeNS(c,a,g):e.setAttribute(a,g),yt(e)?_t(e):_(i.removed)}catch(s){mt(a,e)}}else mt(a,e)}vt(le.afterSanitizeAttributes,e,null)},It=function e(t){let i=null;const r=wt(t);for(vt(le.beforeSanitizeShadowDOM,t,null);i=r.nextNode();)vt(le.uponSanitizeShadowNode,i,null),bt(i),Tt(i),i.content instanceof a&&e(i.content);vt(le.afterSanitizeShadowDOM,t,null)};return i.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,n=null,o=null,c=null;if(et=!e,et&&(e="\x3c!--\x3e"),"string"!==typeof e&&!St(e)){if("function"!==typeof e.toString)throw I("toString is not a function");if("string"!==typeof(e=e.toString()))throw I("dirty is not a string, aborting")}if(!i.isSupported)return e;if(Ue||gt(t),i.removed=[],"string"===typeof e&&(ze=!1),ze){if(e.nodeName){const t=ct(e.nodeName);if(!ye[t]||ke[t])throw I("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof u)r=ft("\x3c!----\x3e"),n=r.ownerDocument.importNode(e,!0),1===n.nodeType&&"BODY"===n.nodeName||"HTML"===n.nodeName?r=n:r.appendChild(n);else{if(!Le&&!Oe&&!Ne&&-1===e.indexOf("<"))return ie&&He?ie.createHTML(e):e;if(r=ft(e),!r)return Le?null:He?re:""}r&&De&&_t(r.firstChild);const l=wt(ze?e:r);for(;o=l.nextNode();)bt(o),Tt(o),o.content instanceof a&&It(o.content);if(ze)return e;if(Le){if(Me)for(c=oe.call(r.ownerDocument);r.firstChild;)c.appendChild(r.firstChild);else c=r;return(ve.shadowroot||ve.shadowrootmode)&&(c=ce.call(s,c,!0)),c}let d=Ne?r.outerHTML:r.innerHTML;return Ne&&ye["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&T(X,r.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+r.ownerDocument.doctype.name+">\n"+d),Oe&&h([de,ue,ge],e=>{d=v(d,e," ")}),ie&&He?ie.createHTML(d):d},i.setConfig=function(){gt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Ue=!0},i.clearConfig=function(){lt=null,Ue=!1},i.isValidAttribute=function(e,t,i){lt||gt({});const r=ct(e),n=ct(t);return Et(r,n,i)},i.addHook=function(e,t){"function"===typeof t&&m(le[e],t)},i.removeHook=function(e,t){if(void 0!==t){const i=p(le[e],t);return-1===i?void 0:f(le[e],i,1)[0]}return _(le[e])},i.removeHooks=function(e){le[e]=[]},i.removeAllHooks=function(){le={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},i}()}}]);