@well-played.gg/react-sdk 2.0.6 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts
CHANGED
|
@@ -111,7 +111,7 @@ export declare const useConnectedPlayer: () => {
|
|
|
111
111
|
username: string;
|
|
112
112
|
customFields: {
|
|
113
113
|
property: string;
|
|
114
|
-
value: string;
|
|
114
|
+
value: string | null;
|
|
115
115
|
}[];
|
|
116
116
|
}[];
|
|
117
117
|
identities: {
|
|
@@ -135,7 +135,7 @@ export declare const useConnectedPlayer: () => {
|
|
|
135
135
|
username: string;
|
|
136
136
|
customFields: {
|
|
137
137
|
property: string;
|
|
138
|
-
value: string;
|
|
138
|
+
value: string | null;
|
|
139
139
|
}[];
|
|
140
140
|
}[];
|
|
141
141
|
identities: {
|
|
@@ -192,7 +192,7 @@ export declare const usePlayers: ({ playerIds, skip, }: {
|
|
|
192
192
|
ownerId: string | null;
|
|
193
193
|
customFields: {
|
|
194
194
|
property: string;
|
|
195
|
-
value: string;
|
|
195
|
+
value: string | null;
|
|
196
196
|
}[];
|
|
197
197
|
identities: {
|
|
198
198
|
providerId: string;
|
|
@@ -238,6 +238,7 @@ export declare const useWellPlayed: () => {
|
|
|
238
238
|
organizationId: string;
|
|
239
239
|
apiClient: ApolloClient<NormalizedCacheObject>;
|
|
240
240
|
typedClient: ReturnType<typeof createTypedClient>;
|
|
241
|
+
accessToken?: string;
|
|
241
242
|
};
|
|
242
243
|
|
|
243
244
|
export declare const WellPlayedProvider: ({ children, oidcConfig, wpAppConfig, ...configs }: PropsWithChildren<WPConfigProps>) => JSX.Element;
|
package/dist/wp-react-sdk.cjs.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
React keys must be passed directly to JSX without using spread:
|
|
22
22
|
let props = %s;
|
|
23
23
|
<%s key={someKey} {...props} />`,Ve,Me,Mt,Me),hs[Me+Ve]=!0)}if(Me=null,xe!==void 0&&(t(xe),Me=""+xe),a(te)&&(t(te.key),Me=""+te.key),"key"in te){xe={};for(var gi in te)gi!=="key"&&(xe[gi]=te[gi])}else xe=te;return Me&&c(xe,typeof F=="function"?F.displayName||F.name||"Unknown":F),d(F,Me,Je,tn,i(),xe,Nn,mi)}function p(F){typeof F=="object"&&F!==null&&F.$$typeof===y&&F._store&&(F._store.validated=1)}var g=q,y=Symbol.for("react.transitional.element"),_=Symbol.for("react.portal"),w=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),P=Symbol.for("react.consumer"),L=Symbol.for("react.context"),B=Symbol.for("react.forward_ref"),z=Symbol.for("react.suspense"),$=Symbol.for("react.suspense_list"),J=Symbol.for("react.memo"),K=Symbol.for("react.lazy"),V=Symbol.for("react.activity"),ne=Symbol.for("react.client.reference"),ve=g.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,De=Object.prototype.hasOwnProperty,pt=Array.isArray,We=console.createTask?console.createTask:function(){return null};g={"react-stack-bottom-frame":function(F){return F()}};var Ce,ot={},jt=g["react-stack-bottom-frame"].bind(g,s)(),dn=We(r(s)),hs={};$i.Fragment=w,$i.jsx=function(F,te,xe,Ve,tn){var Je=1e4>ve.recentlyCreatedOwnerStacks++;return h(F,te,xe,!1,Ve,tn,Je?Error("react-stack-top-frame"):jt,Je?We(r(F)):dn)},$i.jsxs=function(F,te,xe,Ve,tn){var Je=1e4>ve.recentlyCreatedOwnerStacks++;return h(F,te,xe,!0,Ve,tn,Je?Error("react-stack-top-frame"):jt,Je?We(r(F)):dn)}}()),$i}process.env.NODE_ENV==="production"?cc.exports=J1():cc.exports=G1();var Y=cc.exports;let oi=class{open(e){window.location.href=e}reload(){window.location.reload()}getCurrentHref(){return window.location.href}getPath(){const e=window.location;return e.pathname+(e.search||"")+(e.hash||"")}getOrigin(){return window.origin}};const dh=2e3,Gr=console;let Y1=class{constructor(e,t,r,i=dh,s=!0){this._callback=e,this._client_id=t,this._url=r,this._interval=i||dh,this._stopOnError=s;const a=r.indexOf("/",r.indexOf("//")+2);this._frame_origin=r.substring(0,a),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.width=0,this._frame.height=0,this._frame.src=r}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1)})}_message(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data==="error"?(Gr.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):e.data==="changed"?(Gr.debug(e),Gr.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):Gr.debug("CheckSessionIFrame: "+e.data+" message from check session op iframe"))}start(e){Gr.debug("CheckSessionIFrame.start :"+e),this.stop();const t=()=>{this._frame.contentWindow.postMessage(this._client_id+" "+e,this._frame_origin)};t(),this._timer=window.setInterval(t,this._interval)}stop(){this._timer&&(Gr.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)}};const ce={service_worker_not_supported_by_browser:"service_worker_not_supported_by_browser",token_acquired:"token_acquired",logout_from_another_tab:"logout_from_another_tab",logout_from_same_tab:"logout_from_same_tab",token_renewed:"token_renewed",token_timer:"token_timer",loginAsync_begin:"loginAsync_begin",loginAsync_error:"loginAsync_error",loginCallbackAsync_begin:"loginCallbackAsync_begin",loginCallbackAsync_end:"loginCallbackAsync_end",loginCallbackAsync_error:"loginCallbackAsync_error",refreshTokensAsync_begin:"refreshTokensAsync_begin",refreshTokensAsync:"refreshTokensAsync",refreshTokensAsync_end:"refreshTokensAsync_end",refreshTokensAsync_error:"refreshTokensAsync_error",refreshTokensAsync_silent_error:"refreshTokensAsync_silent_error",tryKeepExistingSessionAsync_begin:"tryKeepExistingSessionAsync_begin",tryKeepExistingSessionAsync_end:"tryKeepExistingSessionAsync_end",tryKeepExistingSessionAsync_error:"tryKeepExistingSessionAsync_error",silentLoginAsync_begin:"silentLoginAsync_begin",silentLoginAsync:"silentLoginAsync",silentLoginAsync_end:"silentLoginAsync_end",silentLoginAsync_error:"silentLoginAsync_error",syncTokensAsync_begin:"syncTokensAsync_begin",syncTokensAsync_lock_not_available:"syncTokensAsync_lock_not_available",syncTokensAsync_end:"syncTokensAsync_end",syncTokensAsync_error:"syncTokensAsync_error",tokensInvalidAndWaitingActionsToRefresh:"tokensInvalidAndWaitingActionsToRefresh"},Vt=(n,e=sessionStorage)=>{const t=w=>(e[`oidc.${n}`]=JSON.stringify({tokens:null,status:w}),Promise.resolve()),r=async()=>{if(!e[`oidc.${n}`])return e[`oidc.${n}`]=JSON.stringify({tokens:null,status:null}),{tokens:null,status:null};const w=JSON.parse(e[`oidc.${n}`]);return Promise.resolve({tokens:w.tokens,status:w.status})},i=w=>{e[`oidc.${n}`]=JSON.stringify({tokens:w})},s=async w=>{e[`oidc.session_state.${n}`]=w},a=async()=>e[`oidc.session_state.${n}`],c=w=>{e[`oidc.nonce.${n}`]=w.nonce},u=w=>{e[`oidc.jwk.${n}`]=JSON.stringify(w)},d=()=>JSON.parse(e[`oidc.jwk.${n}`]),h=async()=>({nonce:e[`oidc.nonce.${n}`]}),p=async w=>{e[`oidc.dpop_nonce.${n}`]=w},g=()=>e[`oidc.dpop_nonce.${n}`],y=()=>e[`oidc.${n}`]?JSON.stringify({tokens:JSON.parse(e[`oidc.${n}`]).tokens}):null,_={};return{clearAsync:t,initAsync:r,setTokens:i,getTokens:y,setSessionStateAsync:s,getSessionStateAsync:a,setNonceAsync:c,getNonceAsync:h,setLoginParams:w=>{_[n]=w,e[`oidc.login.${n}`]=JSON.stringify(w)},getLoginParams:()=>{const w=e[`oidc.login.${n}`];return w?(_[n]||(_[n]=JSON.parse(w)),_[n]):(console.warn(`storage[oidc.login.${n}] is empty, you should have an bad OIDC or code configuration somewhere.`),null)},getStateAsync:async()=>e[`oidc.state.${n}`],setStateAsync:async w=>{e[`oidc.state.${n}`]=w},getCodeVerifierAsync:async()=>e[`oidc.code_verifier.${n}`],setCodeVerifierAsync:async w=>{e[`oidc.code_verifier.${n}`]=w},setDemonstratingProofOfPossessionNonce:p,getDemonstratingProofOfPossessionNonce:g,setDemonstratingProofOfPossessionJwkAsync:u,getDemonstratingProofOfPossessionJwkAsync:d}};var Qi=(n=>(n.AutomaticBeforeTokenExpiration="AutomaticBeforeTokensExpiration",n.AutomaticOnlyWhenFetchExecuted="AutomaticOnlyWhenFetchExecuted",n))(Qi||{});const Q1=n=>decodeURIComponent(Array.prototype.map.call(atob(n),e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join("")),X1=n=>JSON.parse(Q1(n.replaceAll(/-/g,"+").replaceAll(/_/g,"/"))),hh=n=>{try{return n&&Z1(n,".")===2?X1(n.split(".")[1]):null}catch(e){console.warn(e)}return null},Z1=(n,e)=>n.split(e).length-1,uc={access_token_or_id_token_invalid:"access_token_or_id_token_invalid",access_token_invalid:"access_token_invalid",id_token_invalid:"id_token_invalid"};function ex(n,e,t){if(n.issuedAt){if(typeof n.issuedAt=="string")return parseInt(n.issuedAt,10)}else return e&&e.iat?e.iat:t&&t.iat?t.iat:new Date().getTime()/1e3;return n.issuedAt}const Vc=(n,e=null,t)=>{if(!n)return null;let r;const i=typeof n.expiresIn=="string"?parseInt(n.expiresIn,10):n.expiresIn;n.accessTokenPayload!==void 0?r=n.accessTokenPayload:r=hh(n.accessToken);let s;e!=null&&"idToken"in e&&!("idToken"in n)?s=e.idToken:s=n.idToken;const a=n.idTokenPayload?n.idTokenPayload:hh(s),c=a&&a.exp?a.exp:Number.MAX_VALUE,u=r&&r.exp?r.exp:n.issuedAt+i;n.issuedAt=ex(n,r,a);let d;n.expiresAt?d=n.expiresAt:t===uc.access_token_invalid?d=u:t===uc.id_token_invalid?d=c:d=c<u?c:u;const h={...n,idTokenPayload:a,accessTokenPayload:r,expiresAt:d,idToken:s};if(e!=null&&"refreshToken"in e&&!("refreshToken"in n)){const p=e.refreshToken;return{...h,refreshToken:p}}return h},Hc=(n,e,t)=>{if(!n)return null;if(!n.issued_at){const i=new Date().getTime()/1e3;n.issued_at=i}const r={accessToken:n.access_token,expiresIn:n.expires_in,idToken:n.id_token,scope:n.scope,tokenType:n.token_type,issuedAt:n.issued_at};return"refresh_token"in n&&(r.refreshToken=n.refresh_token),n.accessTokenPayload!==void 0&&(r.accessTokenPayload=n.accessTokenPayload),n.idTokenPayload!==void 0&&(r.idTokenPayload=n.idTokenPayload),Vc(r,e,t)},qi=(n,e)=>{const t=new Date().getTime()/1e3,r=e-t;return Math.round(r-n)},ph=(n,e=0)=>n?qi(e,n.expiresAt)>0:!1,am=async(n,e=200,t=50)=>{let r=t;if(!n.getTokens())return null;for(;!ph(n.getTokens(),n.configuration.refresh_time_before_tokens_expiration_in_second)&&r>0;){if(n.configuration.token_automatic_renew_mode==Qi.AutomaticOnlyWhenFetchExecuted){await n.renewTokensAsync({});break}else await Wo({milliseconds:e});r=r-1}return{isTokensValid:ph(n.getTokens()),tokens:n.getTokens(),numberWaited:r-t}},lm=(n,e,t)=>{if(n.idTokenPayload){const r=n.idTokenPayload;if(t.issuer!==r.iss)return{isValid:!1,reason:`Issuer does not match (oidcServerConfiguration issuer) ${t.issuer} !== (idTokenPayload issuer) ${r.iss}`};const i=new Date().getTime()/1e3;if(r.exp&&r.exp<i)return{isValid:!1,reason:`Token expired (idTokenPayload exp) ${r.exp} < (currentTimeUnixSecond) ${i}`};const s=60*60*24*7;if(r.iat&&r.iat+s<i)return{isValid:!1,reason:`Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${r.iat+s} < (currentTimeUnixSecond) ${i}`};if(r.nonce&&r.nonce!==e)return{isValid:!1,reason:`Nonce does not match (idTokenPayload nonce) ${r.nonce} !== (nonce) ${e}`}}return{isValid:!0,reason:""}},ai=function(){const n=typeof window>"u"?global:window;return{setTimeout:setTimeout.bind(n),clearTimeout:clearTimeout.bind(n),setInterval:setInterval.bind(n),clearInterval:clearInterval.bind(n)}}(),mh="7.25.7";let gh=null,ko;const Wo=({milliseconds:n})=>new Promise(e=>ai.setTimeout(e,n)),cm=(n="/")=>{try{ko=new AbortController,fetch(`${n}OidcKeepAliveServiceWorker.json?minSleepSeconds=150`,{signal:ko.signal}).catch(e=>{console.log(e)}),Wo({milliseconds:150*1e3}).then(cm)}catch(e){console.log(e)}},yh=()=>{ko&&ko.abort()},tx=(n="/")=>fetch(`${n}OidcKeepAliveServiceWorker.json`,{headers:{"oidc-vanilla":"true"}}).then(e=>e.statusText==="oidc-service-worker").catch(e=>{console.log(e)}),nx=n=>async(e,t)=>{t(),await e.update();const r=await e.unregister();console.log(`Service worker unregistration ${r?"successful":"failed"}`),await Wo({milliseconds:2e3}),n.reload()},um=n=>{const e=sessionStorage.getItem(`oidc.tabId.${n}`);if(e)return e;const t=globalThis.crypto.randomUUID();return sessionStorage.setItem(`oidc.tabId.${n}`,t),t},ut=n=>e=>new Promise(function(t,r){const i=new MessageChannel;i.port1.onmessage=function(s){s!=null&&s.data.error?r(s.data.error):t(s.data),i.port1.close(),i.port2.close()},n.active.postMessage({...e,tabId:um(e.configurationName)},[i.port2])}),Ht=async(n,e)=>{var t;const r=n.service_worker_relative_url;if(typeof window>"u"||typeof navigator>"u"||!navigator.serviceWorker||!r||n.service_worker_activate()===!1)return null;let i=null;n.service_worker_register?i=await n.service_worker_register(r):(i=await navigator.serviceWorker.register(r),i.active&&i.waiting&&(console.log("Detected new service worker waiting, unregistering and reloading"),await((t=n.service_worker_update_require_callback)==null?void 0:t.call(n,i,yh))));try{await navigator.serviceWorker.ready,navigator.serviceWorker.controller||await ut(i)({type:"claim"})}catch(y){return console.warn(`Failed init ServiceWorker ${y.toString()}`),null}const s=async y=>ut(i)({type:"clear",data:{status:y},configurationName:e}),a=async(y,_,w)=>{var k;const A=await ut(i)({type:"init",data:{oidcServerConfiguration:y,where:_,oidcConfiguration:{token_renew_mode:w.token_renew_mode,service_worker_convert_all_requests_to_cors:w.service_worker_convert_all_requests_to_cors}},configurationName:e}),P=A.version;return P!==mh&&(console.warn(`Service worker ${P} version mismatch with js client version ${mh}, unregistering and reloading`),await((k=w.service_worker_update_require_callback)==null?void 0:k.call(w,i,yh))),{tokens:Hc(A.tokens,null,w.token_renew_mode),status:A.status}},c=(y="/")=>{gh==null&&(gh="not_null",cm(y))},u=y=>ut(i)({type:"setSessionState",data:{sessionState:y},configurationName:e}),d=async()=>(await ut(i)({type:"getSessionState",data:null,configurationName:e})).sessionState,h=y=>(sessionStorage[`oidc.nonce.${e}`]=y.nonce,ut(i)({type:"setNonce",data:{nonce:y},configurationName:e})),p=async()=>{let y=(await ut(i)({type:"getNonce",data:null,configurationName:e})).nonce;return y||(y=sessionStorage[`oidc.nonce.${e}`],console.warn("nonce not found in service worker, using sessionStorage")),{nonce:y}},g={};return{clearAsync:s,initAsync:a,startKeepAliveServiceWorker:()=>c(n.service_worker_keep_alive_path),isServiceWorkerProxyActiveAsync:()=>tx(n.service_worker_keep_alive_path),setSessionStateAsync:u,getSessionStateAsync:d,setNonceAsync:h,getNonceAsync:p,setLoginParams:y=>{g[e]=y,localStorage[`oidc.login.${e}`]=JSON.stringify(y)},getLoginParams:()=>{const y=localStorage[`oidc.login.${e}`];return g[e]||(g[e]=JSON.parse(y)),g[e]},getStateAsync:async()=>{let y=(await ut(i)({type:"getState",data:null,configurationName:e})).state;return y||(y=sessionStorage[`oidc.state.${e}`],console.warn("state not found in service worker, using sessionStorage")),y},setStateAsync:async y=>(sessionStorage[`oidc.state.${e}`]=y,ut(i)({type:"setState",data:{state:y},configurationName:e})),getCodeVerifierAsync:async()=>{let y=(await ut(i)({type:"getCodeVerifier",data:null,configurationName:e})).codeVerifier;return y||(y=sessionStorage[`oidc.code_verifier.${e}`],console.warn("codeVerifier not found in service worker, using sessionStorage")),y},setCodeVerifierAsync:async y=>(sessionStorage[`oidc.code_verifier.${e}`]=y,ut(i)({type:"setCodeVerifier",data:{codeVerifier:y},configurationName:e})),setDemonstratingProofOfPossessionNonce:async y=>{await ut(i)({type:"setDemonstratingProofOfPossessionNonce",data:{demonstratingProofOfPossessionNonce:y},configurationName:e})},getDemonstratingProofOfPossessionNonce:async()=>(await ut(i)({type:"getDemonstratingProofOfPossessionNonce",data:null,configurationName:e})).demonstratingProofOfPossessionNonce,setDemonstratingProofOfPossessionJwkAsync:async y=>{const _=JSON.stringify(y);await ut(i)({type:"setDemonstratingProofOfPossessionJwk",data:{demonstratingProofOfPossessionJwkJson:_},configurationName:e})},getDemonstratingProofOfPossessionJwkAsync:async()=>{const y=await ut(i)({type:"getDemonstratingProofOfPossessionJwk",data:null,configurationName:e});return y.demonstratingProofOfPossessionJwkJson?JSON.parse(y.demonstratingProofOfPossessionJwkJson):null}}},Xr={},rx=(n,e=window.sessionStorage,t)=>{if(!Xr[n]&&e){const i=e.getItem(n);i&&(Xr[n]=JSON.parse(i))}const r=1e3*t;return Xr[n]&&Xr[n].timestamp+r>Date.now()?Xr[n].result:null},ix=(n,e,t=window.sessionStorage)=>{const r=Date.now();Xr[n]={result:e,timestamp:r},t&&t.setItem(n,JSON.stringify({result:e,timestamp:r}))};function fm(n){return new TextEncoder().encode(n)}function dm(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function sx(n){return encodeURIComponent(n).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode(parseInt(t,16))})}const Uc=n=>{let e="";return n.forEach(function(t){e+=String.fromCharCode(t)}),dm(e)};function _h(n){return dm(sx(n))}const ox={importKeyAlgorithm:{name:"ECDSA",namedCurve:"P-256",hash:{name:"ES256"}},signAlgorithm:{name:"ECDSA",hash:{name:"SHA-256"}},generateKeyAlgorithm:{name:"ECDSA",namedCurve:"P-256"},digestAlgorithm:{name:"SHA-256"},jwtHeaderAlgorithm:"ES256"},ax=n=>async(e,t,r,i,s="dpop+jwt")=>{switch(e=Object.assign({},e),t.typ=s,t.alg=i.jwtHeaderAlgorithm,t.alg){case"ES256":t.jwk={kty:e.kty,crv:e.crv,x:e.x,y:e.y};break;case"RS256":t.jwk={kty:e.kty,n:e.n,e:e.e,kid:t.kid};break;default:throw new Error("Unknown or not implemented JWS algorithm")}const a={protected:_h(JSON.stringify(t)),payload:_h(JSON.stringify(r))},c=i.importKeyAlgorithm,u=!0,d=["sign"],h=await n.crypto.subtle.importKey("jwk",e,c,u,d),p=fm(`${a.protected}.${a.payload}`),g=i.signAlgorithm,y=await n.crypto.subtle.sign(g,h,p);return a.signature=Uc(new Uint8Array(y)),`${a.protected}.${a.payload}.${a.signature}`},lx={sign:ax},cx=n=>async e=>{const t=e,r=!0,i=["sign","verify"],s=await n.crypto.subtle.generateKey(t,r,i);return await n.crypto.subtle.exportKey("jwk",s.privateKey)},ux=n=>{const e=Object.assign({},n);return delete e.d,e.key_ops=["verify"],e},fx={generate:cx,neuter:ux},dx=n=>async(e,t)=>{let r;switch(e.kty){case"EC":r='{"crv":"CRV","kty":"EC","x":"X","y":"Y"}'.replace("CRV",e.crv).replace("X",e.x).replace("Y",e.y);break;case"RSA":r='{"e":"E","kty":"RSA","n":"N"}'.replace("E",e.e).replace("N",e.n);break;default:throw new Error("Unknown or not implemented JWK type")}const i=await n.crypto.subtle.digest(t,fm(r));return Uc(new Uint8Array(i))},hx={thumbprint:dx},px=n=>async e=>await fx.generate(n)(e),hm=n=>e=>async(t,r="POST",i,s={})=>{const a={jti:btoa(mx()),htm:r,htu:i,iat:Math.round(Date.now()/1e3),...s},c=await hx.thumbprint(n)(t,e.digestAlgorithm);return await lx.sign(n)(t,{kid:c},a,e)},mx=()=>{const n="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",e="0123456789abcdef";let t=0,r="";for(let i=0;i<36;i++)n[i]!=="-"&&n[i]!=="4"&&(t=Math.random()*16|0),n[i]==="x"?r+=e[t]:n[i]==="y"?(t&=3,t|=8,r+=e[t]):r+=n[i];return r},pm=()=>{const n=typeof window<"u"&&!!window.crypto,e=n&&!!window.crypto.subtle;return{hasCrypto:n,hasSubtleCrypto:e}},fc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",gx=n=>{const e=[];for(let t=0;t<n.byteLength;t+=1){const r=n[t]%fc.length;e.push(fc[r])}return e.join("")},dc=n=>{const e=new Uint8Array(n),{hasCrypto:t}=pm();if(t)window.crypto.getRandomValues(e);else for(let r=0;r<n;r+=1)e[r]=Math.random()*fc.length|0;return gx(e)};function yx(n){const e=new ArrayBuffer(n.length),t=new Uint8Array(e);for(let r=0;r<n.length;r++)t[r]=n.charCodeAt(r);return t}function mm(n){return new Promise((e,t)=>{crypto.subtle.digest("SHA-256",yx(n)).then(r=>e(Uc(new Uint8Array(r))),r=>t(r))})}const _x=n=>{if(n.length<43||n.length>128)return Promise.reject(new Error("Invalid code length."));const{hasSubtleCrypto:e}=pm();return e?mm(n):Promise.reject(new Error("window.crypto.subtle is unavailable."))},bx=60*60,vx=n=>async(e,t=bx,r=window.sessionStorage,i=1e4)=>{const s=`${e}/.well-known/openid-configuration`,a=`oidc.server:${e}`,c=rx(a,r,t);if(c)return new pc(c);const u=await cs(n)(s,{},i);if(u.status!==200)return null;const d=await u.json();return ix(a,d,r),new pc(d)},cs=n=>async(e,t={},r=1e4,i=0)=>{let s;try{const a=new AbortController;setTimeout(()=>a.abort(),r),s=await n(e,{...t,signal:a.signal})}catch(a){if(a.name==="AbortError"||a.message==="Network request failed"){if(i<=1)return await cs(n)(e,t,r,i+1);throw a}else throw console.error(a.message),a}return s},hc={refresh_token:"refresh_token",access_token:"access_token"},bh=n=>async(e,t,r=hc.refresh_token,i,s={},a=1e4)=>{const c={token:t,token_type_hint:r,client_id:i};for(const[h,p]of Object.entries(s))c[h]===void 0&&(c[h]=p);const u=[];for(const h in c){const p=encodeURIComponent(h),g=encodeURIComponent(c[h]);u.push(`${p}=${g}`)}const d=u.join("&");return(await cs(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:d},a)).status!==200?{success:!1}:{success:!0}},Sx=n=>async(e,t,r,i,s={},a,c=1e4)=>{for(const[y,_]of Object.entries(r))t[y]===void 0&&(t[y]=_);const u=[];for(const y in t){const _=encodeURIComponent(y),w=encodeURIComponent(t[y]);u.push(`${_}=${w}`)}const d=u.join("&"),h=await cs(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",...s},body:d},c);if(h.status!==200)return{success:!1,status:h.status,demonstratingProofOfPossessionNonce:null};const p=await h.json();let g=null;return h.headers.has(xo)&&(g=h.headers.get(xo)),{success:!0,status:h.status,data:Hc(p,i,a),demonstratingProofOfPossessionNonce:g}},wx=(n,e)=>async(t,r)=>{r=r?{...r}:{};const i=dc(128),s=await _x(i);await n.setCodeVerifierAsync(i),await n.setStateAsync(r.state),r.code_challenge=s,r.code_challenge_method="S256";let a="";if(r)for(const[c,u]of Object.entries(r))a===""?a+="?":a+="&",a+=`${c}=${encodeURIComponent(u)}`;e.open(`${t}${a}`)},xo="DPoP-Nonce",kx=n=>async(e,t,r,i,s=1e4)=>{t=t?{...t}:{},t.code_verifier=await n.getCodeVerifierAsync();const a=[];for(const p in t){const g=encodeURIComponent(p),y=encodeURIComponent(t[p]);a.push(`${g}=${y}`)}const c=a.join("&"),u=await cs(fetch)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",...r},body:c},s);if(await Promise.all([n.setCodeVerifierAsync(null),n.setStateAsync(null)]),u.status!==200)return{success:!1,status:u.status};let d=null;u.headers.has(xo)&&(d=u.headers.get(xo));const h=await u.json();return{success:!0,data:{state:t.state,tokens:Hc(h,null,i),demonstratingProofOfPossessionNonce:d}}};async function vh(n,e,t,r=null){const i=c=>{n.tokens=c},{tokens:s,status:a}=await mo(n)(i,0,e,t,r);return await Ht(n.configuration,n.configurationName)||await Vt(n.configurationName,n.configuration.storage).setTokens(n.tokens),n.tokens?s:(await n.destroyAsync(a),null)}async function gm(n,e=!1,t=null,r=null){const i=n.configuration,s=`${i.client_id}_${n.configurationName}_${i.authority}`;let a;const c=await Ht(n.configuration,n.configurationName);if((i==null?void 0:i.storage)===(window==null?void 0:window.sessionStorage)&&!c||!navigator.locks)a=await vh(n,e,t,r);else{let u="retry";for(;u==="retry";)u=await navigator.locks.request(s,{ifAvailable:!0},async d=>d?await vh(n,e,t,r):(n.publishEvent(An.eventNames.syncTokensAsync_lock_not_available,{lock:"lock not available"}),"retry"));a=u}return a?(n.timeoutId&&(n.timeoutId=Xi(n,n.tokens.expiresAt,t,r)),n.tokens):null}const Xi=(n,e,t=null,r=null)=>{const i=n.configuration.refresh_time_before_tokens_expiration_in_second;return n.timeoutId&&ai.clearTimeout(n.timeoutId),ai.setTimeout(async()=>{const s={timeLeft:qi(i,e)};n.publishEvent(An.eventNames.token_timer,s),await gm(n,!1,t,r)},1e3)},Wn={FORCE_REFRESH:"FORCE_REFRESH",SESSION_LOST:"SESSION_LOST",NOT_CONNECTED:"NOT_CONNECTED",TOKENS_VALID:"TOKENS_VALID",TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID",LOGOUT_FROM_ANOTHER_TAB:"LOGOUT_FROM_ANOTHER_TAB",REQUIRE_SYNC_TOKENS:"REQUIRE_SYNC_TOKENS"},xx=n=>async(e,t,r,i=!1)=>{const s={nonce:null};if(!r)return{tokens:null,status:"NOT_CONNECTED",nonce:s};let a=s;const c=await n.initAsync(e.authority,e.authority_configuration),u=await Ht(e,t);if(u){const{status:h,tokens:p}=await u.initAsync(c,"syncTokensAsync",e);if(h==="LOGGED_OUT")return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:s};if(h==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:s};if(!h||!p)return{tokens:null,status:"REQUIRE_SYNC_TOKENS",nonce:s};if(p.issuedAt!==r.issuedAt){const g=qi(e.refresh_time_before_tokens_expiration_in_second,p.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",y=await u.getNonceAsync();return{tokens:p,status:g,nonce:y}}a=await u.getNonceAsync()}else{const h=Vt(t,e.storage??sessionStorage),p=await h.initAsync();let{tokens:g}=p;const{status:y}=p;if(g&&(g=Vc(g,n.tokens,e.token_renew_mode)),g){if(y==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:s};if(g.issuedAt!==r.issuedAt){const _=qi(e.refresh_time_before_tokens_expiration_in_second,g.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",w=await h.getNonceAsync();return{tokens:g,status:_,nonce:w}}}else return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:s};a=await h.getNonceAsync()}const d=qi(e.refresh_time_before_tokens_expiration_in_second,r.expiresAt)>0?"TOKENS_VALID":"TOKENS_INVALID";return i?{tokens:r,status:"FORCE_REFRESH",nonce:a}:{tokens:r,status:d,nonce:a}},mo=n=>async(e,t=0,r=!1,i=null,s=null)=>{if(!navigator.onLine&&document.hidden)return{tokens:n.tokens,status:"GIVE_UP"};let a=6;for(;!navigator.onLine&&a>0;)await Wo({milliseconds:1e3}),a--,n.publishEvent(ce.refreshTokensAsync,{message:`wait because navigator is offline try ${a}`});const c=document.hidden,u=c?t:t+1;if(t>4)return c?{tokens:n.tokens,status:"GIVE_UP"}:(e(null),n.publishEvent(ce.refreshTokensAsync_error,{message:"refresh token"}),{tokens:null,status:"SESSION_LOST"});i||(i={});const d=n.configuration,h=(g,y=null,_=null)=>Kc(n.configurationName,n.configuration,n.publishEvent.bind(n))(g,y,_),p=async()=>{try{let g;const y=await Ht(d,n.configurationName);y?g=y.getLoginParams():g=Vt(n.configurationName,d.storage).getLoginParams();const _=await h({...g.extras,...i,prompt:"none",scope:s});return _?_.error?(e(null),n.publishEvent(ce.refreshTokensAsync_error,{message:"refresh token silent"}),{tokens:null,status:"SESSION_LOST"}):(e(_.tokens),n.publishEvent(An.eventNames.token_renewed,{}),{tokens:_.tokens,status:"LOGGED"}):(e(null),n.publishEvent(ce.refreshTokensAsync_error,{message:"refresh token silent not active"}),{tokens:null,status:"SESSION_LOST"})}catch(g){return console.error(g),n.publishEvent(ce.refreshTokensAsync_silent_error,{message:"exceptionSilent",exception:g.message}),await mo(n)(e,u,r,i,s)}};try{const{status:g,tokens:y,nonce:_}=await xx(n)(d,n.configurationName,n.tokens,r);switch(g){case Wn.SESSION_LOST:return e(null),n.publishEvent(ce.refreshTokensAsync_error,{message:"refresh token session lost"}),{tokens:null,status:"SESSION_LOST"};case Wn.NOT_CONNECTED:return e(null),{tokens:null,status:null};case Wn.TOKENS_VALID:return e(y),{tokens:y,status:"LOGGED_IN"};case Wn.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:return e(y),n.publishEvent(An.eventNames.token_renewed,{reason:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"}),{tokens:y,status:"LOGGED_IN"};case Wn.LOGOUT_FROM_ANOTHER_TAB:return e(null),n.publishEvent(ce.logout_from_another_tab,{status:"session syncTokensAsync"}),{tokens:null,status:"LOGGED_OUT"};case Wn.REQUIRE_SYNC_TOKENS:return d.token_automatic_renew_mode==Qi.AutomaticOnlyWhenFetchExecuted&&Wn.FORCE_REFRESH!==g?(n.publishEvent(ce.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:n.tokens,status:"GIVE_UP"}):(n.publishEvent(ce.refreshTokensAsync_begin,{tryNumber:t}),await p());default:{if(d.token_automatic_renew_mode==Qi.AutomaticOnlyWhenFetchExecuted&&Wn.FORCE_REFRESH!==g)return n.publishEvent(ce.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:n.tokens,status:"GIVE_UP"};if(n.publishEvent(ce.refreshTokensAsync_begin,{refreshToken:y.refreshToken,status:g,tryNumber:t}),!y.refreshToken)return await p();const w=d.client_id,k=d.redirect_uri,A=d.authority,P={...d.token_request_extras?d.token_request_extras:{}};for(const[L,B]of Object.entries(i))L.endsWith(":token_request")&&(P[L.replace(":token_request","")]=B);return await(async()=>{const L={client_id:w,redirect_uri:k,grant_type:"refresh_token",refresh_token:y.refreshToken},B=await n.initAsync(A,d.authority_configuration),z=document.hidden?1e4:3e4*10,$=B.tokenEndpoint,J={};d.demonstrating_proof_of_possession&&(J.DPoP=await n.generateDemonstrationOfProofOfPossessionAsync(y.accessToken,$,"POST"));const K=await Sx(n.getFetch())($,L,P,y,J,d.token_renew_mode,z);if(K.success){const{isValid:V,reason:ne}=lm(K.data,_.nonce,B);if(!V)return e(null),n.publishEvent(ce.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${ne}`}),{tokens:null,status:"SESSION_LOST"};if(e(K.data),K.demonstratingProofOfPossessionNonce){const ve=await Ht(d,n.configurationName);ve?await ve.setDemonstratingProofOfPossessionNonce(K.demonstratingProofOfPossessionNonce):await Vt(n.configurationName,d.storage).setDemonstratingProofOfPossessionNonce(K.demonstratingProofOfPossessionNonce)}return n.publishEvent(ce.refreshTokensAsync_end,{success:K.success}),n.publishEvent(An.eventNames.token_renewed,{reason:"REFRESH_TOKEN"}),{tokens:K.data,status:"LOGGED_IN"}}else return n.publishEvent(ce.refreshTokensAsync_silent_error,{message:"bad request",tokenResponse:K}),K.status>=400&&K.status<500?(e(null),n.publishEvent(ce.refreshTokensAsync_error,{message:`session lost: ${K.status}`}),{tokens:null,status:"SESSION_LOST"}):await mo(n)(e,u,r,i,s)})()}}}catch(g){return console.error(g),n.publishEvent(ce.refreshTokensAsync_silent_error,{message:"exception",exception:g.message}),new Promise((y,_)=>{setTimeout(()=>{mo(n)(e,u,r,i,s).then(y).catch(_)},1e3)})}},Kc=(n,e,t)=>(r=null,i=null,s=null)=>{if(!e.silent_redirect_uri||!e.silent_login_uri)return Promise.resolve(null);try{t(ce.silentLoginAsync_begin,{});let a="";if(i&&(r==null&&(r={}),r.state=i),s!=null&&(r==null&&(r={}),r.scope=s),r!=null)for(const[p,g]of Object.entries(r))a===""?a=`?${encodeURIComponent(p)}=${encodeURIComponent(g)}`:a+=`&${encodeURIComponent(p)}=${encodeURIComponent(g)}`;const c=e.silent_login_uri+a,u=c.indexOf("/",c.indexOf("//")+2),d=c.substring(0,u),h=document.createElement("iframe");return h.width="0px",h.height="0px",h.id=`${n}_oidc_iframe`,h.setAttribute("src",c),document.body.appendChild(h),new Promise((p,g)=>{let y=!1;const _=()=>{window.removeEventListener("message",w),h.remove(),y=!0},w=k=>{if(k.origin===d&&k.source===h.contentWindow){const A=`${n}_oidc_tokens:`,P=`${n}_oidc_error:`,L=`${n}_oidc_exception:`,B=k.data;if(B&&typeof B=="string"&&!y){if(B.startsWith(A)){const z=JSON.parse(k.data.replace(A,""));t(ce.silentLoginAsync_end,{}),p(z),_()}else if(B.startsWith(P)){const z=JSON.parse(k.data.replace(P,""));t(ce.silentLoginAsync_error,z),p({error:"oidc_"+z.error,tokens:null,sessionState:null}),_()}else if(B.startsWith(L)){const z=JSON.parse(k.data.replace(L,""));t(ce.silentLoginAsync_error,z),g(new Error(z.error)),_()}}}};try{window.addEventListener("message",w);const k=e.silent_login_timeout;setTimeout(()=>{y||(_(),t(ce.silentLoginAsync_error,{reason:"timeout"}),g(new Error("timeout")))},k)}catch(k){_(),t(ce.silentLoginAsync_error,k),g(k)}})}catch(a){throw t(ce.silentLoginAsync_error,a),a}},Ex=(n,e,t,r,i)=>(s=null,a=void 0)=>{s={...s};const c=(u,d,h)=>Kc(e,t,r.bind(i))(u,d,h);return(async()=>{i.timeoutId&&ai.clearTimeout(i.timeoutId);let u;s&&"state"in s&&(u=s.state,delete s.state);try{const d=t.extras?{...t.extras,...s}:s,h=await c({...d,prompt:"none"},u,a);if(h)return i.tokens=h.tokens,r(ce.token_acquired,{}),i.timeoutId=Xi(i,i.tokens.expiresAt,s,a),{}}catch(d){return d}})()},Ox=(n,e,t)=>(r,i,s,a=!1)=>{const c=(u,d=void 0,h=void 0)=>Kc(n.configurationName,t,n.publishEvent.bind(n))(u,d,h);return new Promise((u,d)=>{if(t.silent_login_uri&&t.silent_redirect_uri&&t.monitor_session&&r&&s&&!a){const h=()=>{n.checkSessionIFrame.stop();const p=n.tokens;if(p===null)return;const g=p.idToken,y=p.idTokenPayload;return c({prompt:"none",id_token_hint:g,scope:t.scope||"openid"}).then(_=>{if(_.error)throw new Error(_.error);const w=_.tokens.idTokenPayload;if(y.sub===w.sub){const k=_.sessionState;n.checkSessionIFrame.start(_.sessionState),y.sid===w.sid?console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",k):console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",k)}else console.debug("SessionMonitor._callback: Different subject signed into OP:",w.sub)}).catch(async _=>{console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:",_);for(const[,w]of Object.entries(e))await w.logoutOtherTabAsync(t.client_id,y.sub)})};n.checkSessionIFrame=new Y1(h,i,r),n.checkSessionIFrame.load().then(()=>{n.checkSessionIFrame.start(s),u(n.checkSessionIFrame)}).catch(p=>{d(p)})}else u(null)})},Tx=n=>!!(n.os==="iOS"&&n.osVersion.startsWith("12")||n.os==="Mac OS X"&&n.osVersion.startsWith("10_15_6")),Ax=n=>{const e=n.appVersion,t=n.userAgent,r="-";let i=r;const s=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Chrome OS",r:/CrOS/},{s:"Linux",r:/(Linux|X11(?!.*CrOS))/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(const c in s){const u=s[c];if(u.r.test(t)){i=u.s;break}}let a=r;switch(/Windows/.test(i)&&(a=/Windows (.*)/.exec(i)[1],i="Windows"),i){case"Mac OS":case"Mac OS X":case"Android":a=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(t)[1];break;case"iOS":{const c=/OS (\d+)_(\d+)_?(\d+)?/.exec(e);c!=null&&c.length>2&&(a=c[1]+"."+c[2]+"."+(parseInt(c[3])|0));break}}return{os:i,osVersion:a}};function Cx(){const n=navigator.userAgent;let e,t=n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(t[1]))return e=/\brv[ :]+(\d+)/g.exec(n)||[],{name:"ie",version:e[1]||""};if(t[1]==="Chrome"&&(e=n.match(/\bOPR|Edge\/(\d+)/),e!=null)){let r=e[1];if(!r){const i=n.split(e[0]+"/");i.length>1&&(r=i[1])}return{name:"opera",version:r}}return t=t[2]?[t[1],t[2]]:[navigator.appName,navigator.appVersion,"-?"],(e=n.match(/version\/(\d+)/i))!=null&&t.splice(1,1,e[1]),{name:t[0].toLowerCase(),version:t[1]}}const Mx=()=>{const{name:n,version:e}=Cx();if(n==="chrome"&&parseInt(e)<=70||n==="opera"&&(!e||parseInt(e.split(".")[0])<80)||n==="ie")return!1;const t=Ax(navigator);return!Tx(t)},Nx=async n=>{let e;if(n.tokens!=null)return!1;n.publishEvent(ce.tryKeepExistingSessionAsync_begin,{});try{const t=n.configuration,r=await n.initAsync(t.authority,t.authority_configuration);if(e=await Ht(t,n.configurationName),e){const{tokens:i}=await e.initAsync(r,"tryKeepExistingSessionAsync",t);if(i){e.startKeepAliveServiceWorker(),n.tokens=i;const s=e.getLoginParams(n.configurationName);n.timeoutId=Xi(n,n.tokens.expiresAt,s.extras,s.scope);const a=await e.getSessionStateAsync();return await n.startCheckSessionAsync(r.checkSessionIframe,t.client_id,a),t.preload_user_info&&await n.userInfoAsync(),n.publishEvent(ce.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside ServiceWorker are valid"}),!0}n.publishEvent(ce.tryKeepExistingSessionAsync_end,{success:!1,message:"no exiting session found"})}else{t.service_worker_relative_url&&n.publishEvent(ce.service_worker_not_supported_by_browser,{message:"service worker is not supported by this browser"});const i=Vt(n.configurationName,t.storage??sessionStorage),{tokens:s}=await i.initAsync();if(s){n.tokens=Vc(s,null,t.token_renew_mode);const a=i.getLoginParams();n.timeoutId=Xi(n,n.tokens.expiresAt,a.extras,a.scope);const c=await i.getSessionStateAsync();return await n.startCheckSessionAsync(r.checkSessionIframe,t.client_id,c),t.preload_user_info&&await n.userInfoAsync(),n.publishEvent(ce.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside storage are valid"}),!0}}return n.publishEvent(ce.tryKeepExistingSessionAsync_end,{success:!1,message:e?"service worker sessions not retrieved":"session storage sessions not retrieved"}),!1}catch(t){return console.error(t),e&&await e.clearAsync(),n.publishEvent(ce.tryKeepExistingSessionAsync_error,"tokens inside ServiceWorker are invalid"),!1}},ym=n=>{const e=n.match(/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!e)throw new Error("Invalid URL");let t=e[6],r=e[7];if(r){const i=r.split("?");i.length===2&&(r=i[0],t=i[1])}return t.startsWith("?")&&(t=t.slice(1)),e&&{href:n,protocol:e[1],host:e[2],hostname:e[3],port:e[4],path:e[5],search:t,hash:r}},zi=n=>{const e=ym(n);let{path:t}=e;t.endsWith("/")&&(t=t.slice(0,-1));let{hash:r}=e;return r==="#_=_"&&(r=""),r&&(t+=r),t},Eo=n=>{const e=ym(n),{search:t}=e;return Ix(t)},Ix=n=>{const e={};let t,r,i;const s=n.split("&");for(r=0,i=s.length;r<i;r++)t=s[r].split("="),e[decodeURIComponent(t[0])]=decodeURIComponent(t[1]);return e},Px=(n,e,t,r,i)=>(s=void 0,a=null,c=!1,u=void 0)=>{const d=a;return a={...a},(async()=>{const h=s||i.getPath();if("state"in a||(a.state=dc(16)),t(ce.loginAsync_begin,{}),a)for(const p of Object.keys(a))p.endsWith(":token_request")&&delete a[p];try{const p=c?e.silent_redirect_uri:e.redirect_uri;u||(u=e.scope);const g=e.extras?{...e.extras,...a}:a;g.nonce||(g.nonce=dc(12));const y={nonce:g.nonce},_=await Ht(e,n),w=await r(e.authority,e.authority_configuration);let k;if(_)_.setLoginParams({callbackPath:h,extras:d,scope:u}),await _.initAsync(w,"loginAsync",e),await _.setNonceAsync(y),_.startKeepAliveServiceWorker(),k=_;else{const P=Vt(n,e.storage??sessionStorage);P.setLoginParams({callbackPath:h,extras:d,scope:u}),await P.setNonceAsync(y),k=P}const A={client_id:e.client_id,redirect_uri:p,scope:u,response_type:"code",...g};await wx(k,i)(w.authorizationEndpoint,A)}catch(p){throw t(ce.loginAsync_error,p),p}})()},Rx=n=>async(e=!1)=>{try{n.publishEvent(ce.loginCallbackAsync_begin,{});const t=n.configuration,r=t.client_id,i=e?t.silent_redirect_uri:t.redirect_uri,s=t.authority,a=t.token_request_timeout,c=await n.initAsync(s,t.authority_configuration),u=n.location.getCurrentHref(),d=Eo(u),h=d.session_state,p=await Ht(t,n.configurationName);let g,y,_,w;if(p)await p.initAsync(c,"loginCallbackAsync",t),await p.setSessionStateAsync(h),y=await p.getNonceAsync(),_=p.getLoginParams(),w=await p.getStateAsync(),p.startKeepAliveServiceWorker(),g=p;else{const ne=Vt(n.configurationName,t.storage??sessionStorage);await ne.setSessionStateAsync(h),y=await ne.getNonceAsync(),_=ne.getLoginParams(),w=await ne.getStateAsync(),g=ne}if(d.error||d.error_description)throw new Error(`Error from OIDC server: ${d.error} - ${d.error_description}`);if(d.iss&&d.iss!==c.issuer)throw console.error(),new Error(`Issuer not valid (expected: ${c.issuer}, received: ${d.iss})`);if(d.state&&d.state!==w)throw new Error(`State not valid (expected: ${w}, received: ${d.state})`);const k={code:d.code,grant_type:"authorization_code",client_id:t.client_id,redirect_uri:i},A={};if(t.token_request_extras)for(const[ne,ve]of Object.entries(t.token_request_extras))A[ne]=ve;if(_!=null&&_.extras)for(const[ne,ve]of Object.entries(_.extras))ne.endsWith(":token_request")&&(A[ne.replace(":token_request","")]=ve);const P=c.tokenEndpoint,L={};if(t.demonstrating_proof_of_possession)if(p)L.DPoP=`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${n.configurationName}`;else{const ne=await px(window)(t.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm);await Vt(n.configurationName,t.storage).setDemonstratingProofOfPossessionJwkAsync(ne),L.DPoP=await hm(window)(t.demonstrating_proof_of_possession_configuration)(ne,"POST",P)}const B=await kx(g)(P,{...k,...A},L,n.configuration.token_renew_mode,a);if(!B.success)throw new Error("Token request failed");let z;const $=B.data.tokens,J=B.data.demonstratingProofOfPossessionNonce;if(B.data.state!==A.state)throw new Error("state is not valid");const{isValid:K,reason:V}=lm($,y.nonce,c);if(!K)throw new Error(`Tokens are not OpenID valid, reason: ${V}`);if(p){if($.refreshToken&&!$.refreshToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))throw new Error("Refresh token should be hidden by service worker");if(J&&$!=null&&$.accessToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))throw new Error("Demonstration of proof of possession require Access token not hidden by service worker")}if(p)await p.initAsync(c,"syncTokensAsync",t),z=p.getLoginParams(),J&&await p.setDemonstratingProofOfPossessionNonce(J);else{const ne=Vt(n.configurationName,t.storage);z=ne.getLoginParams(),J&&await ne.setDemonstratingProofOfPossessionNonce(J)}return await n.startCheckSessionAsync(c.checkSessionIframe,r,h,e),n.publishEvent(ce.loginCallbackAsync_end,{}),{tokens:$,state:"request.state",callbackPath:z.callbackPath,scope:d.scope,extras:z.extras}}catch(t){throw console.error(t),n.publishEvent(ce.loginCallbackAsync_error,t),t}},Sh={access_token:"access_token",refresh_token:"refresh_token"},Ol=(n,e)=>{const t={};if(n){for(const[r,i]of Object.entries(n))if(r.endsWith(e)){const s=r.replace(e,"");t[s]=i}return t}return t},Dx=n=>{const e={};if(n){for(const[t,r]of Object.entries(n))t.includes(":")||(e[t]=r);return e}return e},Lx=n=>async e=>{ai.clearTimeout(n.timeoutId),n.timeoutId=null,n.checkSessionIFrame&&n.checkSessionIFrame.stop();const t=await Ht(n.configuration,n.configurationName);t?await t.clearAsync(e):await Vt(n.configurationName,n.configuration.storage).clearAsync(e),n.tokens=null,n.userInfo=null},Bx=(n,e,t,r,i)=>async(s=void 0,a=null)=>{var c,u;const d=n.configuration,h=await n.initAsync(d.authority,d.authority_configuration);s&&typeof s!="string"&&(s=void 0,r.warn("callbackPathOrUrl path is not a string"));const p=s??i.getPath();let g=!1;s&&(g=s.includes("https://")||s.includes("http://"));const y=g?s:i.getOrigin()+p,_=n.tokens?n.tokens.idToken:"";try{const P=h.revocationEndpoint;if(P){const L=[],B=n.tokens?n.tokens.accessToken:null;if(B&&d.logout_tokens_to_invalidate.includes(Sh.access_token)){const $=Ol(a,":revoke_access_token"),J=bh(t)(P,B,hc.access_token,d.client_id,$);L.push(J)}const z=n.tokens?n.tokens.refreshToken:null;if(z&&d.logout_tokens_to_invalidate.includes(Sh.refresh_token)){const $=Ol(a,":revoke_refresh_token"),J=bh(t)(P,z,hc.refresh_token,d.client_id,$);L.push(J)}L.length>0&&await Promise.all(L)}}catch(P){r.warn("logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error"),r.warn(P)}const w=((u=(c=n.tokens)==null?void 0:c.idTokenPayload)==null?void 0:u.sub)??null;await n.destroyAsync("LOGGED_OUT");for(const[,P]of Object.entries(e))P!==n?await n.logoutSameTabAsync(n.configuration.client_id,w):n.publishEvent(ce.logout_from_same_tab,{});const k=Ol(a,":oidc");if(k&&k.no_reload==="true")return;const A=Dx(a);if(h.endSessionEndpoint){"id_token_hint"in A||(A.id_token_hint=_),!("post_logout_redirect_uri"in A)&&s!==null&&(A.post_logout_redirect_uri=y);let P="";for(const[L,B]of Object.entries(A))B!=null&&(P===""?P+="?":P+="&",P+=`${L}=${encodeURIComponent(B)}`);i.open(`${h.endSessionEndpoint}${P}`)}else i.reload()},_m=(n,e,t=!1)=>async(...r)=>{var i;const[s,a,...c]=r,u=a?{...a}:{method:"GET"};let d=new Headers;u.headers&&(d=u.headers instanceof Headers?u.headers:new Headers(u.headers));const h={getTokens:()=>e.tokens,configuration:{token_automatic_renew_mode:e.configuration.token_automatic_renew_mode,refresh_time_before_tokens_expiration_in_second:e.configuration.refresh_time_before_tokens_expiration_in_second},renewTokensAsync:e.renewTokensAsync.bind(e)},p=await am(h),g=(i=p==null?void 0:p.tokens)==null?void 0:i.accessToken;if(d.has("Accept")||d.set("Accept","application/json"),g){if(e.configuration.demonstrating_proof_of_possession&&t){const _=await e.generateDemonstrationOfProofOfPossessionAsync(g,s.toString(),u.method);d.set("Authorization",`DPoP ${g}`),d.set("DPoP",_)}else d.set("Authorization",`Bearer ${g}`);u.credentials||(u.credentials="same-origin")}const y={...u,headers:d};return await n(s,y,...c)},Fx=n=>async(e=!1,t=!1)=>{if(n.userInfo!=null&&!e)return n.userInfo;const r=n.configuration,i=(await n.initAsync(r.authority,r.authority_configuration)).userInfoEndpoint,s=await(async()=>{const a=await _m(fetch,n,t)(i);return a.status!==200?null:a.json()})();return n.userInfo=s,s},bm=()=>fetch;let pc=class{constructor(e){this.authorizationEndpoint=e.authorization_endpoint,this.tokenEndpoint=e.token_endpoint,this.revocationEndpoint=e.revocation_endpoint,this.userInfoEndpoint=e.userinfo_endpoint,this.checkSessionIframe=e.check_session_iframe,this.issuer=e.issuer,this.endSessionEndpoint=e.end_session_endpoint}};const gr={},$x=(n,e=new oi)=>(t,r="default")=>(gr[r]||(gr[r]=new An(t,r,n,e)),gr[r]),zx=async n=>{const{parsedTokens:e,callbackPath:t,extras:r,scope:i}=await n.loginCallbackAsync();return n.timeoutId=Xi(n,e.expiresAt,r,i),{callbackPath:t}},Wx=n=>Math.floor(Math.random()*n),mc=class vm{constructor(e,t="default",r,i=new oi){this.initPromise=null,this.tryKeepExistingSessionPromise=null,this.loginPromise=null,this.loginCallbackPromise=null,this.loginCallbackWithAutoTokensRenewPromise=null,this.userInfoPromise=null,this.renewTokensPromise=null,this.logoutPromise=null;let s=e.silent_login_uri;e.silent_redirect_uri&&!e.silent_login_uri&&(s=`${e.silent_redirect_uri.replace("-callback","").replace("callback","")}-login`);let a=e.refresh_time_before_tokens_expiration_in_second??120;a>60&&(a=a-Math.floor(Math.random()*40)),this.location=i??new oi;const c=e.service_worker_update_require_callback??nx(this.location);this.configuration={...e,silent_login_uri:s,token_automatic_renew_mode:e.token_automatic_renew_mode??Qi.AutomaticBeforeTokenExpiration,monitor_session:e.monitor_session??!1,refresh_time_before_tokens_expiration_in_second:a,silent_login_timeout:e.silent_login_timeout??12e3,token_renew_mode:e.token_renew_mode??uc.access_token_or_id_token_invalid,demonstrating_proof_of_possession:e.demonstrating_proof_of_possession??!1,authority_timeout_wellknowurl_in_millisecond:e.authority_timeout_wellknowurl_in_millisecond??1e4,logout_tokens_to_invalidate:e.logout_tokens_to_invalidate??["access_token","refresh_token"],service_worker_update_require_callback:c,service_worker_activate:e.service_worker_activate??Mx,demonstrating_proof_of_possession_configuration:e.demonstrating_proof_of_possession_configuration??ox,preload_user_info:e.preload_user_info??!1},this.getFetch=r??bm,this.configurationName=t,this.tokens=null,this.userInfo=null,this.events=[],this.timeoutId=null,this.loginCallbackWithAutoTokensRenewAsync.bind(this),this.initAsync.bind(this),this.loginCallbackAsync.bind(this),this.subscribeEvents.bind(this),this.removeEventSubscription.bind(this),this.publishEvent.bind(this),this.destroyAsync.bind(this),this.logoutAsync.bind(this),this.renewTokensAsync.bind(this),this.initAsync(this.configuration.authority,this.configuration.authority_configuration)}subscribeEvents(e){const t=Wx(9999999999999).toString();return this.events.push({id:t,func:e}),t}removeEventSubscription(e){const t=this.events.filter(r=>r.id!==e);this.events=t}publishEvent(e,t){this.events.forEach(r=>{r.func(e,t)})}static get(e="default"){const t=typeof process>"u";if(!Object.prototype.hasOwnProperty.call(gr,e)&&t)throw Error(`OIDC library does seem initialized.
|
|
24
|
-
Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${e}"></OidcProvider> component.`);return gr[e]}_silentLoginCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=this.location,t=Eo(e.getCurrentHref());window.parent.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:this.tokens,sessionState:t.session_state})}`,e.getOrigin())}}_silentLoginErrorCallbackFromIFrame(e=null){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const t=this.location,r=Eo(t.getCurrentHref());r.error?window.parent.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:r.error})}`,t.getOrigin()):window.parent.postMessage(`${this.configurationName}_oidc_exception:${JSON.stringify({error:e==null?"":e.toString()})}`,t.getOrigin())}}async silentLoginCallbackAsync(){try{await this.loginCallbackAsync(!0),this._silentLoginCallbackFromIFrame()}catch(e){console.error(e),this._silentLoginErrorCallbackFromIFrame(e)}}async initAsync(e,t){if(this.initPromise!==null)return this.initPromise;const r=async()=>{if(t!=null)return new pc({authorization_endpoint:t.authorization_endpoint,end_session_endpoint:t.end_session_endpoint,revocation_endpoint:t.revocation_endpoint,token_endpoint:t.token_endpoint,userinfo_endpoint:t.userinfo_endpoint,check_session_iframe:t.check_session_iframe,issuer:t.issuer});const i=await Ht(this.configuration,this.configurationName)?window.sessionStorage:null;return await vx(this.getFetch())(e,this.configuration.authority_time_cache_wellknowurl_in_second??60*60,i,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=r(),this.initPromise.finally(()=>{this.initPromise=null})}async tryKeepExistingSessionAsync(){return this.tryKeepExistingSessionPromise!==null?this.tryKeepExistingSessionPromise:(this.tryKeepExistingSessionPromise=Nx(this),this.tryKeepExistingSessionPromise.finally(()=>{this.tryKeepExistingSessionPromise=null}))}async startCheckSessionAsync(e,t,r,i=!1){await Ox(this,gr,this.configuration)(e,t,r,i)}async loginAsync(e=void 0,t=null,r=!1,i=void 0,s=!1){return this.logoutPromise&&await this.logoutPromise,this.loginPromise!==null?this.loginPromise:(s?this.loginPromise=Ex(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,i):this.loginPromise=Px(this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this),this.location)(e,t,r,i),this.loginPromise.finally(()=>{this.loginPromise=null}))}async loginCallbackAsync(e=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;const t=async()=>{const r=await Rx(this)(e),i=r.tokens;return this.tokens=i,await Ht(this.configuration,this.configurationName)||Vt(this.configurationName,this.configuration.storage).setTokens(i),this.publishEvent(vm.eventNames.token_acquired,i),this.configuration.preload_user_info&&await this.userInfoAsync(),{parsedTokens:i,state:r.state,callbackPath:r.callbackPath,scope:r.scope,extras:r.extras}};return this.loginCallbackPromise=t(),this.loginCallbackPromise.finally(()=>{this.loginCallbackPromise=null})}async generateDemonstrationOfProofOfPossessionAsync(e,t,r,i={}){const s=this.configuration,a={ath:await mm(e),...i};if(await Ht(s,this.configurationName))return`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${this.configurationName}#tabId=${um(this.configurationName)}`;const c=Vt(this.configurationName,s.storage),u=await c.getDemonstratingProofOfPossessionJwkAsync(),d=c.getDemonstratingProofOfPossessionNonce();return d&&(a.nonce=d),await hm(window)(s.demonstrating_proof_of_possession_configuration)(u,r,t,a)}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise!==null?this.loginCallbackWithAutoTokensRenewPromise:(this.loginCallbackWithAutoTokensRenewPromise=zx(this),this.loginCallbackWithAutoTokensRenewPromise.finally(()=>{this.loginCallbackWithAutoTokensRenewPromise=null}))}userInfoAsync(e=!1,t=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=Fx(this)(e,t),this.userInfoPromise.finally(()=>{this.userInfoPromise=null}))}async renewTokensAsync(e=null,t=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(this.timeoutId)return ai.clearTimeout(this.timeoutId),this.renewTokensPromise=gm(this,!0,e,t),this.renewTokensPromise.finally(()=>{this.renewTokensPromise=null})}async destroyAsync(e){return await Lx(this)(e)}async logoutSameTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(ce.logout_from_same_tab,{mmessage:"SessionMonitor",sub:t}))}async logoutOtherTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(ce.logout_from_another_tab,{message:"SessionMonitor",sub:t}))}async logoutAsync(e=void 0,t=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=Bx(this,gr,this.getFetch(),console,this.location)(e,t),this.logoutPromise.finally(()=>{this.logoutPromise=null}))}};mc.getOrCreate=(n,e)=>(t,r="default")=>$x(n,e)(t,r),mc.eventNames=ce;let An=mc;const go=class Sm{constructor(e){this._oidc=e}subscribeEvents(e){return this._oidc.subscribeEvents(e)}removeEventSubscription(e){this._oidc.removeEventSubscription(e)}publishEvent(e,t){this._oidc.publishEvent(e,t)}static get(e="default"){return new Sm(An.get(e))}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(e=void 0,t=null,r=!1,i=void 0,s=!1){return this._oidc.loginAsync(e,t,r,i,s)}logoutAsync(e=void 0,t=null){return this._oidc.logoutAsync(e,t)}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(e=null,t=null){return this._oidc.renewTokensAsync(e,t)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async generateDemonstrationOfProofOfPossessionAsync(e,t,r,i={}){return this._oidc.generateDemonstrationOfProofOfPossessionAsync(e,t,r,i)}async getValidTokenAsync(e=200,t=50){const r=this._oidc,i={getTokens:()=>r.tokens,configuration:{token_automatic_renew_mode:r.configuration.token_automatic_renew_mode,refresh_time_before_tokens_expiration_in_second:r.configuration.refresh_time_before_tokens_expiration_in_second},renewTokensAsync:r.renewTokensAsync.bind(r)};return am(i,e,t)}fetchWithTokens(e,t=!1){return _m(e,this._oidc,t)}async userInfoAsync(e=!1,t=!1){return this._oidc.userInfoAsync(e,t)}userInfo(){return this._oidc.userInfo}};go.getOrCreate=(n,e=new oi)=>(t,r="default")=>new go(An.getOrCreate(n,e)(t,r)),go.eventNames=An.eventNames;let me=go;const wm=()=>Y.jsx("div",{className:"oidc-authenticating",children:Y.jsxs("div",{className:"oidc-authenticating__container",children:[Y.jsx("h1",{className:"oidc-authenticating__title",children:"Error authentication"}),Y.jsx("p",{className:"oidc-authenticating__content",children:"An error occurred during authentication."})]})}),Vx=()=>Y.jsx("div",{className:"oidc-authenticating",children:Y.jsxs("div",{className:"oidc-authenticating__container",children:[Y.jsx("h1",{className:"oidc-authenticating__title",children:"Authentication in progress"}),Y.jsx("p",{className:"oidc-authenticating__content",children:"You will be redirected to the login page."})]})}),Hx=()=>Math.random().toString(36).slice(2,8),Ux=(n,e)=>(t,r)=>{if(typeof n.CustomEvent=="function")return new n.CustomEvent(t,r);const i=r||{bubbles:!1,cancelable:!1,detail:void 0},s=e.createEvent("CustomEvent");return s.initCustomEvent(t,i.bubbles,i.cancelable,i.detail),s.prototype=n.Event.prototype,s},Kx=(n,e,t)=>({replaceState:(r,i)=>{const s=t(),a=i||n.history.state;n.history.replaceState({key:s,state:a},null,r),n.dispatchEvent(e("popstate"))}}),jx=()=>Kx(window,Ux(window,document),Hx),km=()=>Y.jsx("div",{className:"oidc-callback",children:Y.jsxs("div",{className:"oidc-callback__container",children:[Y.jsx("h1",{className:"oidc-callback__title",children:"Authentication complete"}),Y.jsx("p",{className:"oidc-callback__content",children:"You will be redirected to your application."})]})}),qx=({callBackError:n,callBackSuccess:e,configurationName:t,withCustomHistory:r})=>{const[i,s]=q.useState(!1);q.useEffect(()=>{let u=!0;return(async()=>{const d=me.get;try{const{callbackPath:h}=await d(t).loginCallbackAsync();(r?r():jx()).replaceState(h||"/")}catch(h){u&&(console.warn(h),s(!0))}})(),()=>{u=!1}},[]);const a=n||wm,c=e||km;return i?Y.jsx(a,{configurationName:t}):Y.jsx(c,{configurationName:t})},Jx=()=>Y.jsx("span",{className:"oidc-loading",children:"Loading"}),Gx=()=>Y.jsx("div",{className:"oidc-serviceworker",children:Y.jsxs("div",{className:"oidc-serviceworker__container",children:[Y.jsx("h1",{className:"oidc-serviceworker__title",children:"Unable to authenticate on this browser"}),Y.jsx("p",{className:"oidc-serviceworker__content",children:"Your browser is not secure enough to make authentication work. Try updating your browser or use a newer browser."})]})}),Yx=()=>Y.jsx("div",{className:"oidc-session-lost",children:Y.jsxs("div",{className:"oidc-session-lost__container",children:[Y.jsx("h1",{className:"oidc-session-lost__title",children:"Session timed out"}),Y.jsx("p",{className:"oidc-session-lost__content",children:"Your session has expired. Please re-authenticate."})]})}),Qx=({configurationName:n})=>(q.useEffect(()=>{(async()=>{me.get(n).silentLoginCallbackAsync()})().catch(e=>{console.error("Error during silent login callback:",e)})},[n]),null),Xx=({configurationName:n})=>{const e=Eo(window.location.href),t=me.get,r=t(n);let i=null;for(const[s,a]of Object.entries(e))s==="state"||s==="scope"||(i===null&&(i={}),i[s]=a);return q.useEffect(()=>{r.tokens||r.loginAsync(null,i,!0,e.scope)},[]),Y.jsx(Y.Fragment,{})},Zx=({callbackErrorComponent:n,callbackSuccessComponent:e,redirect_uri:t,silent_redirect_uri:r,silent_login_uri:i,children:s,configurationName:a,withCustomHistory:c=null})=>{const u=window?zi(window.location.href):"",[d,h]=q.useState(u);q.useEffect(()=>{const g=()=>h(zi(window.location.href));return g(),window.addEventListener("popstate",g,!1),()=>window.removeEventListener("popstate",g,!1)},[]);const p=zi(t);if(r&&d===zi(r))return Y.jsx(Qx,{configurationName:a});if(i&&d===zi(i))return Y.jsx(Xx,{configurationName:a});switch(d){case p:return Y.jsx(qx,{callBackError:n,callBackSuccess:e,configurationName:a,withCustomHistory:c});default:return Y.jsx(Y.Fragment,{children:s})}},eE=q.memo(Zx),wh={name:"",data:null},tE=({loadingComponent:n,children:e,configurationName:t})=>{const[r,i]=q.useState(!0),s=me.get,a=s(t);return q.useEffect(()=>{let c=!0;return a&&a.tryKeepExistingSessionAsync().then(()=>{c&&i(!1)}),()=>{c=!1}},[t]),Y.jsx(Y.Fragment,{children:r?Y.jsx(n,{configurationName:t}):Y.jsx(Y.Fragment,{children:e})})},Wi=({isLoading:n,loadingComponent:e,children:t,configurationName:r})=>{const i=e;return n?Y.jsx(i,{configurationName:r,children:t}):Y.jsx(Y.Fragment,{children:t})},nE=({children:n,configuration:e,configurationName:t="default",callbackSuccessComponent:r=km,authenticatingComponent:i=Vx,loadingComponent:s=Jx,serviceWorkerNotSupportedComponent:a=Gx,authenticatingErrorComponent:c=wm,sessionLostComponent:u=Yx,onSessionLost:d=null,onLogoutFromAnotherTab:h=null,onLogoutFromSameTab:p=null,withCustomHistory:g=null,onEvent:y=null,getFetch:_=null,location:w=null})=>{const k=(We="default")=>me.getOrCreate(_??bm,w??new oi)(e,We),[A,P]=q.useState(!0),[L,B]=q.useState(wh),[z,$]=q.useState("default");q.useEffect(()=>{const We=k(t).subscribeEvents((Ce,ot)=>{y&&y(t,Ce,ot)});return()=>{k(t).removeEventSubscription(We)}},[t,y]),q.useEffect(()=>{const We=k(t).subscribeEvents((Ce,ot)=>{if(Ce===me.eventNames.refreshTokensAsync_error||Ce===me.eventNames.syncTokensAsync_error){if(d!=null){d();return}B({name:Ce,data:ot})}else if(Ce===me.eventNames.logout_from_another_tab){if(h!=null){h();return}B({name:Ce,data:ot})}else Ce===me.eventNames.logout_from_same_tab?p!=null&&p():Ce===me.eventNames.loginAsync_begin||Ce===me.eventNames.loginCallbackAsync_end||Ce===me.eventNames.loginAsync_error||Ce===me.eventNames.loginCallbackAsync_error?B({name:Ce,data:ot}):Ce===me.eventNames.service_worker_not_supported_by_browser&&e.service_worker_only===!0&&B({name:Ce,data:ot})});return $(t),P(!1),()=>{k(t).removeEventSubscription(We),B(wh)}},[e,t]);const J=u,K=i,V=s,ne=a,ve=c,De=A||z!==t,pt=k(t);switch(L.name){case me.eventNames.service_worker_not_supported_by_browser:return Y.jsx(Wi,{loadingComponent:V,isLoading:De,configurationName:t,children:Y.jsx(ne,{configurationName:t})});case me.eventNames.loginAsync_begin:return Y.jsx(Wi,{loadingComponent:V,isLoading:De,configurationName:t,children:Y.jsx(K,{configurationName:t})});case me.eventNames.loginAsync_error:case me.eventNames.loginCallbackAsync_error:return Y.jsx(Wi,{loadingComponent:V,isLoading:De,configurationName:t,children:Y.jsx(ve,{configurationName:t})});case me.eventNames.refreshTokensAsync_error:case me.eventNames.syncTokensAsync_error:case me.eventNames.logout_from_another_tab:return Y.jsx(Wi,{loadingComponent:V,isLoading:De,configurationName:t,children:Y.jsx(J,{configurationName:t})});default:return Y.jsx(Wi,{loadingComponent:V,isLoading:De,configurationName:t,children:Y.jsx(eE,{redirect_uri:pt.configuration.redirect_uri,silent_redirect_uri:pt.configuration.silent_redirect_uri,silent_login_uri:pt.configuration.silent_login_uri,callbackSuccessComponent:r,callbackErrorComponent:c,authenticatingComponent:i,configurationName:t,withCustomHistory:g,location:w??new oi,children:Y.jsx(tE,{loadingComponent:V,configurationName:t,children:n})})})}},xm="default",Tl=(n,e)=>{let t=!1;return n(e)&&(t=n(e).tokens!=null),t},rE=(n=xm)=>{const e=me.get,[t,r]=q.useState(Tl(e,n));return q.useEffect(()=>{let i=!0;const s=e(n);r(Tl(e,n));const a=s.subscribeEvents((c,u)=>{(c===me.eventNames.logout_from_another_tab||c===me.eventNames.logout_from_same_tab||c===me.eventNames.token_acquired)&&i&&r(Tl(e,n))});return()=>{i=!1,s.removeEventSubscription(a)}},[n]),{login:(i=void 0,s=void 0,a=!1,c=void 0)=>e(n).loginAsync(i,s,!1,c,a),logout:(i=void 0,s=void 0)=>e(n).logoutAsync(i,s),renewTokens:async(i=void 0)=>{const s=await e(n).renewTokensAsync(i);return{accessToken:s.accessToken,accessTokenPayload:s.accessTokenPayload,idToken:s.idToken,idTokenPayload:s.idTokenPayload}},isAuthenticated:t}},Em={accessToken:null,accessTokenPayload:null},iE=n=>{const e=me.get,t=e(n);if(t.tokens){const r=t.tokens;return{accessToken:r.accessToken,accessTokenPayload:r.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:t.configuration.demonstrating_proof_of_possession?(i,s)=>t.generateDemonstrationOfProofOfPossessionAsync(r.accessToken,i,s):null}}return Em};function sE(n,e){return n.configuration.demonstrating_proof_of_possession?(t,r,i={})=>n.generateDemonstrationOfProofOfPossessionAsync(e.accessToken,t,r,i):null}const oE=(n=xm)=>{const e=me.get,[t,r]=q.useState(iE(n));return q.useEffect(()=>{let i=!0;const s=e(n);if(s.tokens){const c=s.tokens;r({accessToken:c.accessToken,accessTokenPayload:c.accessTokenPayload})}const a=s.subscribeEvents((c,u)=>{if((c===me.eventNames.token_renewed||c===me.eventNames.token_acquired||c===me.eventNames.logout_from_another_tab||c===me.eventNames.logout_from_same_tab||c===me.eventNames.refreshTokensAsync_error||c===me.eventNames.syncTokensAsync_error)&&i){const d=s.tokens;r(d!=null?{accessToken:d.accessToken,accessTokenPayload:d.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:sE(s,d)}:Em)}});return()=>{i=!1,s.removeEventSubscription(a)}},[n]),t},Om=q.createContext({}),hi=()=>{const n=q.useContext(Om);if(!n)throw new Error("useWellPlayed must be used within a WellPlayedProvider");return n},aE=({children:n,clientConfig:e,organizationId:t,apiBaseUrl:r,typedClientConfig:i})=>{const s=oE(),a=q.useMemo(()=>Er.createWellPlayedClient({token:(s==null?void 0:s.accessToken)??void 0,organizationId:t,...e,apiBaseUrl:r}),[s==null?void 0:s.accessToken,t,e,r]);return Y.jsx(A1,{client:a,children:Y.jsx(Om.Provider,{value:{organizationId:t,apiClient:a,typedClient:Er.createTypedClient({apiBaseUrl:r,organizationId:t,token:(s==null?void 0:s.accessToken)??void 0,...i})},children:n})})},lE=({children:n,oidcConfig:e,wpAppConfig:t,...r})=>Y.jsx(nE,{...e,configuration:{...t,...e==null?void 0:e.configuration,authority:`https://oauth.warrior.${r.apiBaseUrl??"well-played.gg"}`},children:Y.jsx(aE,{...r,children:n})}),cE=(n,e)=>{const{apiClient:t}=hi(),{data:r,loading:i,refetch:s,fetchMore:a}=zc(n,{...e,notifyOnNetworkStatusChange:!0,variables:{...e==null?void 0:e.variables,page:{first:(e==null?void 0:e.pageSize)??100}},client:t}),c=n.definitions[0].selectionSet.selections[0].name.value;return{data:r,loading:i,loadNextPage:u=>{const d=r==null?void 0:r[c];if(d!=null&&d.pageInfo.hasNextPage)return s({...e==null?void 0:e.variables,...u,page:{first:(e==null?void 0:e.pageSize)??100,after:d.pageInfo.endCursor}})},loadNextPageWithoutAppendingOldData:u=>{const d=r==null?void 0:r[c];return a({variables:{...e==null?void 0:e.variables,...u,page:{first:(e==null?void 0:e.pageSize)??100,after:d==null?void 0:d.pageInfo.endCursor}}})}}},jc=(n,e)=>{const[t,r]=q.useState(!(e!=null&&e.skip)),[i,s]=q.useState([]),{apiClient:a}=hi(),[c]=om(n,{...e,client:a}),u=async d=>{var _;const h=n.definitions[0].selectionSet.selections[0].name.value;r(!0);let p=!0,g=null;const y=[];for(;p;){const{data:w,error:k}=await c({variables:{...e==null?void 0:e.variables,...d,page:{first:100,after:g}}});if(k)throw k;const A=w==null?void 0:w[h];A&&(y.push(...A.nodes??[]),p=A.pageInfo.hasNextPage,g=A.pageInfo.endCursor)}return s(y),(_=e==null?void 0:e.onResults)==null||_.call(e,y),r(!1),y};return q.useEffect(()=>{e!=null&&e.skip||u()},[e==null?void 0:e.skip]),{loading:t,results:i,refetch:u}},uE=Er.graphql(`
|
|
24
|
+
Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${e}"></OidcProvider> component.`);return gr[e]}_silentLoginCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=this.location,t=Eo(e.getCurrentHref());window.parent.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:this.tokens,sessionState:t.session_state})}`,e.getOrigin())}}_silentLoginErrorCallbackFromIFrame(e=null){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const t=this.location,r=Eo(t.getCurrentHref());r.error?window.parent.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:r.error})}`,t.getOrigin()):window.parent.postMessage(`${this.configurationName}_oidc_exception:${JSON.stringify({error:e==null?"":e.toString()})}`,t.getOrigin())}}async silentLoginCallbackAsync(){try{await this.loginCallbackAsync(!0),this._silentLoginCallbackFromIFrame()}catch(e){console.error(e),this._silentLoginErrorCallbackFromIFrame(e)}}async initAsync(e,t){if(this.initPromise!==null)return this.initPromise;const r=async()=>{if(t!=null)return new pc({authorization_endpoint:t.authorization_endpoint,end_session_endpoint:t.end_session_endpoint,revocation_endpoint:t.revocation_endpoint,token_endpoint:t.token_endpoint,userinfo_endpoint:t.userinfo_endpoint,check_session_iframe:t.check_session_iframe,issuer:t.issuer});const i=await Ht(this.configuration,this.configurationName)?window.sessionStorage:null;return await vx(this.getFetch())(e,this.configuration.authority_time_cache_wellknowurl_in_second??60*60,i,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=r(),this.initPromise.finally(()=>{this.initPromise=null})}async tryKeepExistingSessionAsync(){return this.tryKeepExistingSessionPromise!==null?this.tryKeepExistingSessionPromise:(this.tryKeepExistingSessionPromise=Nx(this),this.tryKeepExistingSessionPromise.finally(()=>{this.tryKeepExistingSessionPromise=null}))}async startCheckSessionAsync(e,t,r,i=!1){await Ox(this,gr,this.configuration)(e,t,r,i)}async loginAsync(e=void 0,t=null,r=!1,i=void 0,s=!1){return this.logoutPromise&&await this.logoutPromise,this.loginPromise!==null?this.loginPromise:(s?this.loginPromise=Ex(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,i):this.loginPromise=Px(this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this),this.location)(e,t,r,i),this.loginPromise.finally(()=>{this.loginPromise=null}))}async loginCallbackAsync(e=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;const t=async()=>{const r=await Rx(this)(e),i=r.tokens;return this.tokens=i,await Ht(this.configuration,this.configurationName)||Vt(this.configurationName,this.configuration.storage).setTokens(i),this.publishEvent(vm.eventNames.token_acquired,i),this.configuration.preload_user_info&&await this.userInfoAsync(),{parsedTokens:i,state:r.state,callbackPath:r.callbackPath,scope:r.scope,extras:r.extras}};return this.loginCallbackPromise=t(),this.loginCallbackPromise.finally(()=>{this.loginCallbackPromise=null})}async generateDemonstrationOfProofOfPossessionAsync(e,t,r,i={}){const s=this.configuration,a={ath:await mm(e),...i};if(await Ht(s,this.configurationName))return`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${this.configurationName}#tabId=${um(this.configurationName)}`;const c=Vt(this.configurationName,s.storage),u=await c.getDemonstratingProofOfPossessionJwkAsync(),d=c.getDemonstratingProofOfPossessionNonce();return d&&(a.nonce=d),await hm(window)(s.demonstrating_proof_of_possession_configuration)(u,r,t,a)}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise!==null?this.loginCallbackWithAutoTokensRenewPromise:(this.loginCallbackWithAutoTokensRenewPromise=zx(this),this.loginCallbackWithAutoTokensRenewPromise.finally(()=>{this.loginCallbackWithAutoTokensRenewPromise=null}))}userInfoAsync(e=!1,t=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=Fx(this)(e,t),this.userInfoPromise.finally(()=>{this.userInfoPromise=null}))}async renewTokensAsync(e=null,t=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(this.timeoutId)return ai.clearTimeout(this.timeoutId),this.renewTokensPromise=gm(this,!0,e,t),this.renewTokensPromise.finally(()=>{this.renewTokensPromise=null})}async destroyAsync(e){return await Lx(this)(e)}async logoutSameTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(ce.logout_from_same_tab,{mmessage:"SessionMonitor",sub:t}))}async logoutOtherTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(ce.logout_from_another_tab,{message:"SessionMonitor",sub:t}))}async logoutAsync(e=void 0,t=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=Bx(this,gr,this.getFetch(),console,this.location)(e,t),this.logoutPromise.finally(()=>{this.logoutPromise=null}))}};mc.getOrCreate=(n,e)=>(t,r="default")=>$x(n,e)(t,r),mc.eventNames=ce;let An=mc;const go=class Sm{constructor(e){this._oidc=e}subscribeEvents(e){return this._oidc.subscribeEvents(e)}removeEventSubscription(e){this._oidc.removeEventSubscription(e)}publishEvent(e,t){this._oidc.publishEvent(e,t)}static get(e="default"){return new Sm(An.get(e))}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(e=void 0,t=null,r=!1,i=void 0,s=!1){return this._oidc.loginAsync(e,t,r,i,s)}logoutAsync(e=void 0,t=null){return this._oidc.logoutAsync(e,t)}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(e=null,t=null){return this._oidc.renewTokensAsync(e,t)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async generateDemonstrationOfProofOfPossessionAsync(e,t,r,i={}){return this._oidc.generateDemonstrationOfProofOfPossessionAsync(e,t,r,i)}async getValidTokenAsync(e=200,t=50){const r=this._oidc,i={getTokens:()=>r.tokens,configuration:{token_automatic_renew_mode:r.configuration.token_automatic_renew_mode,refresh_time_before_tokens_expiration_in_second:r.configuration.refresh_time_before_tokens_expiration_in_second},renewTokensAsync:r.renewTokensAsync.bind(r)};return am(i,e,t)}fetchWithTokens(e,t=!1){return _m(e,this._oidc,t)}async userInfoAsync(e=!1,t=!1){return this._oidc.userInfoAsync(e,t)}userInfo(){return this._oidc.userInfo}};go.getOrCreate=(n,e=new oi)=>(t,r="default")=>new go(An.getOrCreate(n,e)(t,r)),go.eventNames=An.eventNames;let me=go;const wm=()=>Y.jsx("div",{className:"oidc-authenticating",children:Y.jsxs("div",{className:"oidc-authenticating__container",children:[Y.jsx("h1",{className:"oidc-authenticating__title",children:"Error authentication"}),Y.jsx("p",{className:"oidc-authenticating__content",children:"An error occurred during authentication."})]})}),Vx=()=>Y.jsx("div",{className:"oidc-authenticating",children:Y.jsxs("div",{className:"oidc-authenticating__container",children:[Y.jsx("h1",{className:"oidc-authenticating__title",children:"Authentication in progress"}),Y.jsx("p",{className:"oidc-authenticating__content",children:"You will be redirected to the login page."})]})}),Hx=()=>Math.random().toString(36).slice(2,8),Ux=(n,e)=>(t,r)=>{if(typeof n.CustomEvent=="function")return new n.CustomEvent(t,r);const i=r||{bubbles:!1,cancelable:!1,detail:void 0},s=e.createEvent("CustomEvent");return s.initCustomEvent(t,i.bubbles,i.cancelable,i.detail),s.prototype=n.Event.prototype,s},Kx=(n,e,t)=>({replaceState:(r,i)=>{const s=t(),a=i||n.history.state;n.history.replaceState({key:s,state:a},null,r),n.dispatchEvent(e("popstate"))}}),jx=()=>Kx(window,Ux(window,document),Hx),km=()=>Y.jsx("div",{className:"oidc-callback",children:Y.jsxs("div",{className:"oidc-callback__container",children:[Y.jsx("h1",{className:"oidc-callback__title",children:"Authentication complete"}),Y.jsx("p",{className:"oidc-callback__content",children:"You will be redirected to your application."})]})}),qx=({callBackError:n,callBackSuccess:e,configurationName:t,withCustomHistory:r})=>{const[i,s]=q.useState(!1);q.useEffect(()=>{let u=!0;return(async()=>{const d=me.get;try{const{callbackPath:h}=await d(t).loginCallbackAsync();(r?r():jx()).replaceState(h||"/")}catch(h){u&&(console.warn(h),s(!0))}})(),()=>{u=!1}},[]);const a=n||wm,c=e||km;return i?Y.jsx(a,{configurationName:t}):Y.jsx(c,{configurationName:t})},Jx=()=>Y.jsx("span",{className:"oidc-loading",children:"Loading"}),Gx=()=>Y.jsx("div",{className:"oidc-serviceworker",children:Y.jsxs("div",{className:"oidc-serviceworker__container",children:[Y.jsx("h1",{className:"oidc-serviceworker__title",children:"Unable to authenticate on this browser"}),Y.jsx("p",{className:"oidc-serviceworker__content",children:"Your browser is not secure enough to make authentication work. Try updating your browser or use a newer browser."})]})}),Yx=()=>Y.jsx("div",{className:"oidc-session-lost",children:Y.jsxs("div",{className:"oidc-session-lost__container",children:[Y.jsx("h1",{className:"oidc-session-lost__title",children:"Session timed out"}),Y.jsx("p",{className:"oidc-session-lost__content",children:"Your session has expired. Please re-authenticate."})]})}),Qx=({configurationName:n})=>(q.useEffect(()=>{(async()=>{me.get(n).silentLoginCallbackAsync()})().catch(e=>{console.error("Error during silent login callback:",e)})},[n]),null),Xx=({configurationName:n})=>{const e=Eo(window.location.href),t=me.get,r=t(n);let i=null;for(const[s,a]of Object.entries(e))s==="state"||s==="scope"||(i===null&&(i={}),i[s]=a);return q.useEffect(()=>{r.tokens||r.loginAsync(null,i,!0,e.scope)},[]),Y.jsx(Y.Fragment,{})},Zx=({callbackErrorComponent:n,callbackSuccessComponent:e,redirect_uri:t,silent_redirect_uri:r,silent_login_uri:i,children:s,configurationName:a,withCustomHistory:c=null})=>{const u=window?zi(window.location.href):"",[d,h]=q.useState(u);q.useEffect(()=>{const g=()=>h(zi(window.location.href));return g(),window.addEventListener("popstate",g,!1),()=>window.removeEventListener("popstate",g,!1)},[]);const p=zi(t);if(r&&d===zi(r))return Y.jsx(Qx,{configurationName:a});if(i&&d===zi(i))return Y.jsx(Xx,{configurationName:a});switch(d){case p:return Y.jsx(qx,{callBackError:n,callBackSuccess:e,configurationName:a,withCustomHistory:c});default:return Y.jsx(Y.Fragment,{children:s})}},eE=q.memo(Zx),wh={name:"",data:null},tE=({loadingComponent:n,children:e,configurationName:t})=>{const[r,i]=q.useState(!0),s=me.get,a=s(t);return q.useEffect(()=>{let c=!0;return a&&a.tryKeepExistingSessionAsync().then(()=>{c&&i(!1)}),()=>{c=!1}},[t]),Y.jsx(Y.Fragment,{children:r?Y.jsx(n,{configurationName:t}):Y.jsx(Y.Fragment,{children:e})})},Wi=({isLoading:n,loadingComponent:e,children:t,configurationName:r})=>{const i=e;return n?Y.jsx(i,{configurationName:r,children:t}):Y.jsx(Y.Fragment,{children:t})},nE=({children:n,configuration:e,configurationName:t="default",callbackSuccessComponent:r=km,authenticatingComponent:i=Vx,loadingComponent:s=Jx,serviceWorkerNotSupportedComponent:a=Gx,authenticatingErrorComponent:c=wm,sessionLostComponent:u=Yx,onSessionLost:d=null,onLogoutFromAnotherTab:h=null,onLogoutFromSameTab:p=null,withCustomHistory:g=null,onEvent:y=null,getFetch:_=null,location:w=null})=>{const k=(We="default")=>me.getOrCreate(_??bm,w??new oi)(e,We),[A,P]=q.useState(!0),[L,B]=q.useState(wh),[z,$]=q.useState("default");q.useEffect(()=>{const We=k(t).subscribeEvents((Ce,ot)=>{y&&y(t,Ce,ot)});return()=>{k(t).removeEventSubscription(We)}},[t,y]),q.useEffect(()=>{const We=k(t).subscribeEvents((Ce,ot)=>{if(Ce===me.eventNames.refreshTokensAsync_error||Ce===me.eventNames.syncTokensAsync_error){if(d!=null){d();return}B({name:Ce,data:ot})}else if(Ce===me.eventNames.logout_from_another_tab){if(h!=null){h();return}B({name:Ce,data:ot})}else Ce===me.eventNames.logout_from_same_tab?p!=null&&p():Ce===me.eventNames.loginAsync_begin||Ce===me.eventNames.loginCallbackAsync_end||Ce===me.eventNames.loginAsync_error||Ce===me.eventNames.loginCallbackAsync_error?B({name:Ce,data:ot}):Ce===me.eventNames.service_worker_not_supported_by_browser&&e.service_worker_only===!0&&B({name:Ce,data:ot})});return $(t),P(!1),()=>{k(t).removeEventSubscription(We),B(wh)}},[e,t]);const J=u,K=i,V=s,ne=a,ve=c,De=A||z!==t,pt=k(t);switch(L.name){case me.eventNames.service_worker_not_supported_by_browser:return Y.jsx(Wi,{loadingComponent:V,isLoading:De,configurationName:t,children:Y.jsx(ne,{configurationName:t})});case me.eventNames.loginAsync_begin:return Y.jsx(Wi,{loadingComponent:V,isLoading:De,configurationName:t,children:Y.jsx(K,{configurationName:t})});case me.eventNames.loginAsync_error:case me.eventNames.loginCallbackAsync_error:return Y.jsx(Wi,{loadingComponent:V,isLoading:De,configurationName:t,children:Y.jsx(ve,{configurationName:t})});case me.eventNames.refreshTokensAsync_error:case me.eventNames.syncTokensAsync_error:case me.eventNames.logout_from_another_tab:return Y.jsx(Wi,{loadingComponent:V,isLoading:De,configurationName:t,children:Y.jsx(J,{configurationName:t})});default:return Y.jsx(Wi,{loadingComponent:V,isLoading:De,configurationName:t,children:Y.jsx(eE,{redirect_uri:pt.configuration.redirect_uri,silent_redirect_uri:pt.configuration.silent_redirect_uri,silent_login_uri:pt.configuration.silent_login_uri,callbackSuccessComponent:r,callbackErrorComponent:c,authenticatingComponent:i,configurationName:t,withCustomHistory:g,location:w??new oi,children:Y.jsx(tE,{loadingComponent:V,configurationName:t,children:n})})})}},xm="default",Tl=(n,e)=>{let t=!1;return n(e)&&(t=n(e).tokens!=null),t},rE=(n=xm)=>{const e=me.get,[t,r]=q.useState(Tl(e,n));return q.useEffect(()=>{let i=!0;const s=e(n);r(Tl(e,n));const a=s.subscribeEvents((c,u)=>{(c===me.eventNames.logout_from_another_tab||c===me.eventNames.logout_from_same_tab||c===me.eventNames.token_acquired)&&i&&r(Tl(e,n))});return()=>{i=!1,s.removeEventSubscription(a)}},[n]),{login:(i=void 0,s=void 0,a=!1,c=void 0)=>e(n).loginAsync(i,s,!1,c,a),logout:(i=void 0,s=void 0)=>e(n).logoutAsync(i,s),renewTokens:async(i=void 0)=>{const s=await e(n).renewTokensAsync(i);return{accessToken:s.accessToken,accessTokenPayload:s.accessTokenPayload,idToken:s.idToken,idTokenPayload:s.idTokenPayload}},isAuthenticated:t}},Em={accessToken:null,accessTokenPayload:null},iE=n=>{const e=me.get,t=e(n);if(t.tokens){const r=t.tokens;return{accessToken:r.accessToken,accessTokenPayload:r.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:t.configuration.demonstrating_proof_of_possession?(i,s)=>t.generateDemonstrationOfProofOfPossessionAsync(r.accessToken,i,s):null}}return Em};function sE(n,e){return n.configuration.demonstrating_proof_of_possession?(t,r,i={})=>n.generateDemonstrationOfProofOfPossessionAsync(e.accessToken,t,r,i):null}const oE=(n=xm)=>{const e=me.get,[t,r]=q.useState(iE(n));return q.useEffect(()=>{let i=!0;const s=e(n);if(s.tokens){const c=s.tokens;r({accessToken:c.accessToken,accessTokenPayload:c.accessTokenPayload})}const a=s.subscribeEvents((c,u)=>{if((c===me.eventNames.token_renewed||c===me.eventNames.token_acquired||c===me.eventNames.logout_from_another_tab||c===me.eventNames.logout_from_same_tab||c===me.eventNames.refreshTokensAsync_error||c===me.eventNames.syncTokensAsync_error)&&i){const d=s.tokens;r(d!=null?{accessToken:d.accessToken,accessTokenPayload:d.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:sE(s,d)}:Em)}});return()=>{i=!1,s.removeEventSubscription(a)}},[n]),t},Om=q.createContext({}),hi=()=>{const n=q.useContext(Om);if(!n)throw new Error("useWellPlayed must be used within a WellPlayedProvider");return n},aE=({children:n,clientConfig:e,organizationId:t,apiBaseUrl:r,typedClientConfig:i})=>{const s=oE(),a=q.useMemo(()=>Er.createWellPlayedClient({token:(s==null?void 0:s.accessToken)??void 0,organizationId:t,...e,apiBaseUrl:r}),[s==null?void 0:s.accessToken,t,e,r]);return Y.jsx(A1,{client:a,children:Y.jsx(Om.Provider,{value:{organizationId:t,apiClient:a,typedClient:Er.createTypedClient({apiBaseUrl:r,organizationId:t,token:(s==null?void 0:s.accessToken)??void 0,...i}),accessToken:(s==null?void 0:s.accessToken)??void 0},children:n})})},lE=({children:n,oidcConfig:e,wpAppConfig:t,...r})=>Y.jsx(nE,{...e,configuration:{...t,...e==null?void 0:e.configuration,authority:`https://oauth.warrior.${r.apiBaseUrl??"well-played.gg"}`},children:Y.jsx(aE,{...r,children:n})}),cE=(n,e)=>{const{apiClient:t}=hi(),{data:r,loading:i,refetch:s,fetchMore:a}=zc(n,{...e,notifyOnNetworkStatusChange:!0,variables:{...e==null?void 0:e.variables,page:{first:(e==null?void 0:e.pageSize)??100}},client:t}),c=n.definitions[0].selectionSet.selections[0].name.value;return{data:r,loading:i,loadNextPage:u=>{const d=r==null?void 0:r[c];if(d!=null&&d.pageInfo.hasNextPage)return s({...e==null?void 0:e.variables,...u,page:{first:(e==null?void 0:e.pageSize)??100,after:d.pageInfo.endCursor}})},loadNextPageWithoutAppendingOldData:u=>{const d=r==null?void 0:r[c];return a({variables:{...e==null?void 0:e.variables,...u,page:{first:(e==null?void 0:e.pageSize)??100,after:d==null?void 0:d.pageInfo.endCursor}}})}}},jc=(n,e)=>{const[t,r]=q.useState(!(e!=null&&e.skip)),[i,s]=q.useState([]),{apiClient:a}=hi(),[c]=om(n,{...e,client:a}),u=async d=>{var _;const h=n.definitions[0].selectionSet.selections[0].name.value;r(!0);let p=!0,g=null;const y=[];for(;p;){const{data:w,error:k}=await c({variables:{...e==null?void 0:e.variables,...d,page:{first:100,after:g}}});if(k)throw k;const A=w==null?void 0:w[h];A&&(y.push(...A.nodes??[]),p=A.pageInfo.hasNextPage,g=A.pageInfo.endCursor)}return s(y),(_=e==null?void 0:e.onResults)==null||_.call(e,y),r(!1),y};return q.useEffect(()=>{e!=null&&e.skip||u()},[e==null?void 0:e.skip]),{loading:t,results:i,refetch:u}},uE=Er.graphql(`
|
|
25
25
|
query players(
|
|
26
26
|
$ids: [ID!]!
|
|
27
27
|
$page: PageInfo!
|
package/dist/wp-react-sdk.es.js
CHANGED
package/dist/wp-react-sdk.umd.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
React keys must be passed directly to JSX without using spread:
|
|
22
22
|
let props = %s;
|
|
23
23
|
<%s key={someKey} {...props} />`,je,Ne,Ft,Ne),fo[Ne+je]=!0)}if(Ne=null,Ee!==void 0&&(t(Ee),Ne=""+Ee),l(te)&&(t(te.key),Ne=""+te.key),"key"in te){Ee={};for(var ji in te)ji!=="key"&&(Ee[ji]=te[ji])}else Ee=te;return Ne&&c(Ee,typeof F=="function"?F.displayName||F.name||"Unknown":F),d(F,Ne,Xe,cn,i(),Ee,Gn,Ki)}function p(F){typeof F=="object"&&F!==null&&F.$$typeof===y&&F._store&&(F._store.validated=1)}var g=K,y=Symbol.for("react.transitional.element"),_=Symbol.for("react.portal"),S=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),P=Symbol.for("react.consumer"),L=Symbol.for("react.context"),B=Symbol.for("react.forward_ref"),W=Symbol.for("react.suspense"),z=Symbol.for("react.suspense_list"),J=Symbol.for("react.memo"),j=Symbol.for("react.lazy"),V=Symbol.for("react.activity"),ne=Symbol.for("react.client.reference"),ve=g.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Le=Object.prototype.hasOwnProperty,_t=Array.isArray,Ke=console.createTask?console.createTask:function(){return null};g={"react-stack-bottom-frame":function(F){return F()}};var Me,ft={},Gt=g["react-stack-bottom-frame"].bind(g,s)(),wn=Ke(r(s)),fo={};bi.Fragment=S,bi.jsx=function(F,te,Ee,je,cn){var Xe=1e4>ve.recentlyCreatedOwnerStacks++;return h(F,te,Ee,!1,je,cn,Xe?Error("react-stack-top-frame"):Gt,Xe?Ke(r(F)):wn)},bi.jsxs=function(F,te,Ee,je,cn){var Xe=1e4>ve.recentlyCreatedOwnerStacks++;return h(F,te,Ee,!0,je,cn,Xe?Error("react-stack-top-frame"):Gt,Xe?Ke(r(F)):wn)}}()),bi}process.env.NODE_ENV==="production"?vl.exports=f0():vl.exports=d0();var Y=vl.exports;let Dr=class{open(e){window.location.href=e}reload(){window.location.reload()}getCurrentHref(){return window.location.href}getPath(){const e=window.location;return e.pathname+(e.search||"")+(e.hash||"")}getOrigin(){return window.origin}};const tf=2e3,Lr=console;let h0=class{constructor(e,t,r,i=tf,s=!0){this._callback=e,this._client_id=t,this._url=r,this._interval=i||tf,this._stopOnError=s;const l=r.indexOf("/",r.indexOf("//")+2);this._frame_origin=r.substring(0,l),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.width=0,this._frame.height=0,this._frame.src=r}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1)})}_message(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data==="error"?(Lr.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):e.data==="changed"?(Lr.debug(e),Lr.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):Lr.debug("CheckSessionIFrame: "+e.data+" message from check session op iframe"))}start(e){Lr.debug("CheckSessionIFrame.start :"+e),this.stop();const t=()=>{this._frame.contentWindow.postMessage(this._client_id+" "+e,this._frame_origin)};t(),this._timer=window.setInterval(t,this._interval)}stop(){this._timer&&(Lr.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)}};const ae={service_worker_not_supported_by_browser:"service_worker_not_supported_by_browser",token_acquired:"token_acquired",logout_from_another_tab:"logout_from_another_tab",logout_from_same_tab:"logout_from_same_tab",token_renewed:"token_renewed",token_timer:"token_timer",loginAsync_begin:"loginAsync_begin",loginAsync_error:"loginAsync_error",loginCallbackAsync_begin:"loginCallbackAsync_begin",loginCallbackAsync_end:"loginCallbackAsync_end",loginCallbackAsync_error:"loginCallbackAsync_error",refreshTokensAsync_begin:"refreshTokensAsync_begin",refreshTokensAsync:"refreshTokensAsync",refreshTokensAsync_end:"refreshTokensAsync_end",refreshTokensAsync_error:"refreshTokensAsync_error",refreshTokensAsync_silent_error:"refreshTokensAsync_silent_error",tryKeepExistingSessionAsync_begin:"tryKeepExistingSessionAsync_begin",tryKeepExistingSessionAsync_end:"tryKeepExistingSessionAsync_end",tryKeepExistingSessionAsync_error:"tryKeepExistingSessionAsync_error",silentLoginAsync_begin:"silentLoginAsync_begin",silentLoginAsync:"silentLoginAsync",silentLoginAsync_end:"silentLoginAsync_end",silentLoginAsync_error:"silentLoginAsync_error",syncTokensAsync_begin:"syncTokensAsync_begin",syncTokensAsync_lock_not_available:"syncTokensAsync_lock_not_available",syncTokensAsync_end:"syncTokensAsync_end",syncTokensAsync_error:"syncTokensAsync_error",tokensInvalidAndWaitingActionsToRefresh:"tokensInvalidAndWaitingActionsToRefresh"},Nt=(n,e=sessionStorage)=>{const t=S=>(e[`oidc.${n}`]=JSON.stringify({tokens:null,status:S}),Promise.resolve()),r=async()=>{if(!e[`oidc.${n}`])return e[`oidc.${n}`]=JSON.stringify({tokens:null,status:null}),{tokens:null,status:null};const S=JSON.parse(e[`oidc.${n}`]);return Promise.resolve({tokens:S.tokens,status:S.status})},i=S=>{e[`oidc.${n}`]=JSON.stringify({tokens:S})},s=async S=>{e[`oidc.session_state.${n}`]=S},l=async()=>e[`oidc.session_state.${n}`],c=S=>{e[`oidc.nonce.${n}`]=S.nonce},u=S=>{e[`oidc.jwk.${n}`]=JSON.stringify(S)},d=()=>JSON.parse(e[`oidc.jwk.${n}`]),h=async()=>({nonce:e[`oidc.nonce.${n}`]}),p=async S=>{e[`oidc.dpop_nonce.${n}`]=S},g=()=>e[`oidc.dpop_nonce.${n}`],y=()=>e[`oidc.${n}`]?JSON.stringify({tokens:JSON.parse(e[`oidc.${n}`]).tokens}):null,_={};return{clearAsync:t,initAsync:r,setTokens:i,getTokens:y,setSessionStateAsync:s,getSessionStateAsync:l,setNonceAsync:c,getNonceAsync:h,setLoginParams:S=>{_[n]=S,e[`oidc.login.${n}`]=JSON.stringify(S)},getLoginParams:()=>{const S=e[`oidc.login.${n}`];return S?(_[n]||(_[n]=JSON.parse(S)),_[n]):(console.warn(`storage[oidc.login.${n}] is empty, you should have an bad OIDC or code configuration somewhere.`),null)},getStateAsync:async()=>e[`oidc.state.${n}`],setStateAsync:async S=>{e[`oidc.state.${n}`]=S},getCodeVerifierAsync:async()=>e[`oidc.code_verifier.${n}`],setCodeVerifierAsync:async S=>{e[`oidc.code_verifier.${n}`]=S},setDemonstratingProofOfPossessionNonce:p,getDemonstratingProofOfPossessionNonce:g,setDemonstratingProofOfPossessionJwkAsync:u,getDemonstratingProofOfPossessionJwkAsync:d}};var vi=(n=>(n.AutomaticBeforeTokenExpiration="AutomaticBeforeTokensExpiration",n.AutomaticOnlyWhenFetchExecuted="AutomaticOnlyWhenFetchExecuted",n))(vi||{});const p0=n=>decodeURIComponent(Array.prototype.map.call(atob(n),e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join("")),m0=n=>JSON.parse(p0(n.replaceAll(/-/g,"+").replaceAll(/_/g,"/"))),nf=n=>{try{return n&&g0(n,".")===2?m0(n.split(".")[1]):null}catch(e){console.warn(e)}return null},g0=(n,e)=>n.split(e).length-1,wl={access_token_or_id_token_invalid:"access_token_or_id_token_invalid",access_token_invalid:"access_token_invalid",id_token_invalid:"id_token_invalid"};function y0(n,e,t){if(n.issuedAt){if(typeof n.issuedAt=="string")return parseInt(n.issuedAt,10)}else return e&&e.iat?e.iat:t&&t.iat?t.iat:new Date().getTime()/1e3;return n.issuedAt}const Sl=(n,e=null,t)=>{if(!n)return null;let r;const i=typeof n.expiresIn=="string"?parseInt(n.expiresIn,10):n.expiresIn;n.accessTokenPayload!==void 0?r=n.accessTokenPayload:r=nf(n.accessToken);let s;e!=null&&"idToken"in e&&!("idToken"in n)?s=e.idToken:s=n.idToken;const l=n.idTokenPayload?n.idTokenPayload:nf(s),c=l&&l.exp?l.exp:Number.MAX_VALUE,u=r&&r.exp?r.exp:n.issuedAt+i;n.issuedAt=y0(n,r,l);let d;n.expiresAt?d=n.expiresAt:t===wl.access_token_invalid?d=u:t===wl.id_token_invalid?d=c:d=c<u?c:u;const h={...n,idTokenPayload:l,accessTokenPayload:r,expiresAt:d,idToken:s};if(e!=null&&"refreshToken"in e&&!("refreshToken"in n)){const p=e.refreshToken;return{...h,refreshToken:p}}return h},kl=(n,e,t)=>{if(!n)return null;if(!n.issued_at){const i=new Date().getTime()/1e3;n.issued_at=i}const r={accessToken:n.access_token,expiresIn:n.expires_in,idToken:n.id_token,scope:n.scope,tokenType:n.token_type,issuedAt:n.issued_at};return"refresh_token"in n&&(r.refreshToken=n.refresh_token),n.accessTokenPayload!==void 0&&(r.accessTokenPayload=n.accessTokenPayload),n.idTokenPayload!==void 0&&(r.idTokenPayload=n.idTokenPayload),Sl(r,e,t)},wi=(n,e)=>{const t=new Date().getTime()/1e3,r=e-t;return Math.round(r-n)},rf=(n,e=0)=>n?wi(e,n.expiresAt)>0:!1,sf=async(n,e=200,t=50)=>{let r=t;if(!n.getTokens())return null;for(;!rf(n.getTokens(),n.configuration.refresh_time_before_tokens_expiration_in_second)&&r>0;){if(n.configuration.token_automatic_renew_mode==vi.AutomaticOnlyWhenFetchExecuted){await n.renewTokensAsync({});break}else await bs({milliseconds:e});r=r-1}return{isTokensValid:rf(n.getTokens()),tokens:n.getTokens(),numberWaited:r-t}},of=(n,e,t)=>{if(n.idTokenPayload){const r=n.idTokenPayload;if(t.issuer!==r.iss)return{isValid:!1,reason:`Issuer does not match (oidcServerConfiguration issuer) ${t.issuer} !== (idTokenPayload issuer) ${r.iss}`};const i=new Date().getTime()/1e3;if(r.exp&&r.exp<i)return{isValid:!1,reason:`Token expired (idTokenPayload exp) ${r.exp} < (currentTimeUnixSecond) ${i}`};const s=60*60*24*7;if(r.iat&&r.iat+s<i)return{isValid:!1,reason:`Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${r.iat+s} < (currentTimeUnixSecond) ${i}`};if(r.nonce&&r.nonce!==e)return{isValid:!1,reason:`Nonce does not match (idTokenPayload nonce) ${r.nonce} !== (nonce) ${e}`}}return{isValid:!0,reason:""}},Br=function(){const n=typeof window>"u"?global:window;return{setTimeout:setTimeout.bind(n),clearTimeout:clearTimeout.bind(n),setInterval:setInterval.bind(n),clearInterval:clearInterval.bind(n)}}(),lf="7.25.7";let af=null,_s;const bs=({milliseconds:n})=>new Promise(e=>Br.setTimeout(e,n)),cf=(n="/")=>{try{_s=new AbortController,fetch(`${n}OidcKeepAliveServiceWorker.json?minSleepSeconds=150`,{signal:_s.signal}).catch(e=>{console.log(e)}),bs({milliseconds:150*1e3}).then(cf)}catch(e){console.log(e)}},uf=()=>{_s&&_s.abort()},_0=(n="/")=>fetch(`${n}OidcKeepAliveServiceWorker.json`,{headers:{"oidc-vanilla":"true"}}).then(e=>e.statusText==="oidc-service-worker").catch(e=>{console.log(e)}),b0=n=>async(e,t)=>{t(),await e.update();const r=await e.unregister();console.log(`Service worker unregistration ${r?"successful":"failed"}`),await bs({milliseconds:2e3}),n.reload()},ff=n=>{const e=sessionStorage.getItem(`oidc.tabId.${n}`);if(e)return e;const t=globalThis.crypto.randomUUID();return sessionStorage.setItem(`oidc.tabId.${n}`,t),t},lt=n=>e=>new Promise(function(t,r){const i=new MessageChannel;i.port1.onmessage=function(s){s!=null&&s.data.error?r(s.data.error):t(s.data),i.port1.close(),i.port2.close()},n.active.postMessage({...e,tabId:ff(e.configurationName)},[i.port2])}),It=async(n,e)=>{var t;const r=n.service_worker_relative_url;if(typeof window>"u"||typeof navigator>"u"||!navigator.serviceWorker||!r||n.service_worker_activate()===!1)return null;let i=null;n.service_worker_register?i=await n.service_worker_register(r):(i=await navigator.serviceWorker.register(r),i.active&&i.waiting&&(console.log("Detected new service worker waiting, unregistering and reloading"),await((t=n.service_worker_update_require_callback)==null?void 0:t.call(n,i,uf))));try{await navigator.serviceWorker.ready,navigator.serviceWorker.controller||await lt(i)({type:"claim"})}catch(y){return console.warn(`Failed init ServiceWorker ${y.toString()}`),null}const s=async y=>lt(i)({type:"clear",data:{status:y},configurationName:e}),l=async(y,_,S)=>{var k;const A=await lt(i)({type:"init",data:{oidcServerConfiguration:y,where:_,oidcConfiguration:{token_renew_mode:S.token_renew_mode,service_worker_convert_all_requests_to_cors:S.service_worker_convert_all_requests_to_cors}},configurationName:e}),P=A.version;return P!==lf&&(console.warn(`Service worker ${P} version mismatch with js client version ${lf}, unregistering and reloading`),await((k=S.service_worker_update_require_callback)==null?void 0:k.call(S,i,uf))),{tokens:kl(A.tokens,null,S.token_renew_mode),status:A.status}},c=(y="/")=>{af==null&&(af="not_null",cf(y))},u=y=>lt(i)({type:"setSessionState",data:{sessionState:y},configurationName:e}),d=async()=>(await lt(i)({type:"getSessionState",data:null,configurationName:e})).sessionState,h=y=>(sessionStorage[`oidc.nonce.${e}`]=y.nonce,lt(i)({type:"setNonce",data:{nonce:y},configurationName:e})),p=async()=>{let y=(await lt(i)({type:"getNonce",data:null,configurationName:e})).nonce;return y||(y=sessionStorage[`oidc.nonce.${e}`],console.warn("nonce not found in service worker, using sessionStorage")),{nonce:y}},g={};return{clearAsync:s,initAsync:l,startKeepAliveServiceWorker:()=>c(n.service_worker_keep_alive_path),isServiceWorkerProxyActiveAsync:()=>_0(n.service_worker_keep_alive_path),setSessionStateAsync:u,getSessionStateAsync:d,setNonceAsync:h,getNonceAsync:p,setLoginParams:y=>{g[e]=y,localStorage[`oidc.login.${e}`]=JSON.stringify(y)},getLoginParams:()=>{const y=localStorage[`oidc.login.${e}`];return g[e]||(g[e]=JSON.parse(y)),g[e]},getStateAsync:async()=>{let y=(await lt(i)({type:"getState",data:null,configurationName:e})).state;return y||(y=sessionStorage[`oidc.state.${e}`],console.warn("state not found in service worker, using sessionStorage")),y},setStateAsync:async y=>(sessionStorage[`oidc.state.${e}`]=y,lt(i)({type:"setState",data:{state:y},configurationName:e})),getCodeVerifierAsync:async()=>{let y=(await lt(i)({type:"getCodeVerifier",data:null,configurationName:e})).codeVerifier;return y||(y=sessionStorage[`oidc.code_verifier.${e}`],console.warn("codeVerifier not found in service worker, using sessionStorage")),y},setCodeVerifierAsync:async y=>(sessionStorage[`oidc.code_verifier.${e}`]=y,lt(i)({type:"setCodeVerifier",data:{codeVerifier:y},configurationName:e})),setDemonstratingProofOfPossessionNonce:async y=>{await lt(i)({type:"setDemonstratingProofOfPossessionNonce",data:{demonstratingProofOfPossessionNonce:y},configurationName:e})},getDemonstratingProofOfPossessionNonce:async()=>(await lt(i)({type:"getDemonstratingProofOfPossessionNonce",data:null,configurationName:e})).demonstratingProofOfPossessionNonce,setDemonstratingProofOfPossessionJwkAsync:async y=>{const _=JSON.stringify(y);await lt(i)({type:"setDemonstratingProofOfPossessionJwk",data:{demonstratingProofOfPossessionJwkJson:_},configurationName:e})},getDemonstratingProofOfPossessionJwkAsync:async()=>{const y=await lt(i)({type:"getDemonstratingProofOfPossessionJwk",data:null,configurationName:e});return y.demonstratingProofOfPossessionJwkJson?JSON.parse(y.demonstratingProofOfPossessionJwkJson):null}}},Fr={},v0=(n,e=window.sessionStorage,t)=>{if(!Fr[n]&&e){const i=e.getItem(n);i&&(Fr[n]=JSON.parse(i))}const r=1e3*t;return Fr[n]&&Fr[n].timestamp+r>Date.now()?Fr[n].result:null},w0=(n,e,t=window.sessionStorage)=>{const r=Date.now();Fr[n]={result:e,timestamp:r},t&&t.setItem(n,JSON.stringify({result:e,timestamp:r}))};function df(n){return new TextEncoder().encode(n)}function hf(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function S0(n){return encodeURIComponent(n).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode(parseInt(t,16))})}const xl=n=>{let e="";return n.forEach(function(t){e+=String.fromCharCode(t)}),hf(e)};function pf(n){return hf(S0(n))}const k0={importKeyAlgorithm:{name:"ECDSA",namedCurve:"P-256",hash:{name:"ES256"}},signAlgorithm:{name:"ECDSA",hash:{name:"SHA-256"}},generateKeyAlgorithm:{name:"ECDSA",namedCurve:"P-256"},digestAlgorithm:{name:"SHA-256"},jwtHeaderAlgorithm:"ES256"},x0=n=>async(e,t,r,i,s="dpop+jwt")=>{switch(e=Object.assign({},e),t.typ=s,t.alg=i.jwtHeaderAlgorithm,t.alg){case"ES256":t.jwk={kty:e.kty,crv:e.crv,x:e.x,y:e.y};break;case"RS256":t.jwk={kty:e.kty,n:e.n,e:e.e,kid:t.kid};break;default:throw new Error("Unknown or not implemented JWS algorithm")}const l={protected:pf(JSON.stringify(t)),payload:pf(JSON.stringify(r))},c=i.importKeyAlgorithm,u=!0,d=["sign"],h=await n.crypto.subtle.importKey("jwk",e,c,u,d),p=df(`${l.protected}.${l.payload}`),g=i.signAlgorithm,y=await n.crypto.subtle.sign(g,h,p);return l.signature=xl(new Uint8Array(y)),`${l.protected}.${l.payload}.${l.signature}`},E0={sign:x0},T0=n=>async e=>{const t=e,r=!0,i=["sign","verify"],s=await n.crypto.subtle.generateKey(t,r,i);return await n.crypto.subtle.exportKey("jwk",s.privateKey)},O0=n=>{const e=Object.assign({},n);return delete e.d,e.key_ops=["verify"],e},A0={generate:T0,neuter:O0},C0=n=>async(e,t)=>{let r;switch(e.kty){case"EC":r='{"crv":"CRV","kty":"EC","x":"X","y":"Y"}'.replace("CRV",e.crv).replace("X",e.x).replace("Y",e.y);break;case"RSA":r='{"e":"E","kty":"RSA","n":"N"}'.replace("E",e.e).replace("N",e.n);break;default:throw new Error("Unknown or not implemented JWK type")}const i=await n.crypto.subtle.digest(t,df(r));return xl(new Uint8Array(i))},M0={thumbprint:C0},N0=n=>async e=>await A0.generate(n)(e),mf=n=>e=>async(t,r="POST",i,s={})=>{const l={jti:btoa(I0()),htm:r,htu:i,iat:Math.round(Date.now()/1e3),...s},c=await M0.thumbprint(n)(t,e.digestAlgorithm);return await E0.sign(n)(t,{kid:c},l,e)},I0=()=>{const n="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",e="0123456789abcdef";let t=0,r="";for(let i=0;i<36;i++)n[i]!=="-"&&n[i]!=="4"&&(t=Math.random()*16|0),n[i]==="x"?r+=e[t]:n[i]==="y"?(t&=3,t|=8,r+=e[t]):r+=n[i];return r},gf=()=>{const n=typeof window<"u"&&!!window.crypto,e=n&&!!window.crypto.subtle;return{hasCrypto:n,hasSubtleCrypto:e}},El="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",P0=n=>{const e=[];for(let t=0;t<n.byteLength;t+=1){const r=n[t]%El.length;e.push(El[r])}return e.join("")},Tl=n=>{const e=new Uint8Array(n),{hasCrypto:t}=gf();if(t)window.crypto.getRandomValues(e);else for(let r=0;r<n;r+=1)e[r]=Math.random()*El.length|0;return P0(e)};function R0(n){const e=new ArrayBuffer(n.length),t=new Uint8Array(e);for(let r=0;r<n.length;r++)t[r]=n.charCodeAt(r);return t}function yf(n){return new Promise((e,t)=>{crypto.subtle.digest("SHA-256",R0(n)).then(r=>e(xl(new Uint8Array(r))),r=>t(r))})}const D0=n=>{if(n.length<43||n.length>128)return Promise.reject(new Error("Invalid code length."));const{hasSubtleCrypto:e}=gf();return e?yf(n):Promise.reject(new Error("window.crypto.subtle is unavailable."))},L0=60*60,B0=n=>async(e,t=L0,r=window.sessionStorage,i=1e4)=>{const s=`${e}/.well-known/openid-configuration`,l=`oidc.server:${e}`,c=v0(l,r,t);if(c)return new Ml(c);const u=await Si(n)(s,{},i);if(u.status!==200)return null;const d=await u.json();return w0(l,d,r),new Ml(d)},Si=n=>async(e,t={},r=1e4,i=0)=>{let s;try{const l=new AbortController;setTimeout(()=>l.abort(),r),s=await n(e,{...t,signal:l.signal})}catch(l){if(l.name==="AbortError"||l.message==="Network request failed"){if(i<=1)return await Si(n)(e,t,r,i+1);throw l}else throw console.error(l.message),l}return s},Ol={refresh_token:"refresh_token",access_token:"access_token"},_f=n=>async(e,t,r=Ol.refresh_token,i,s={},l=1e4)=>{const c={token:t,token_type_hint:r,client_id:i};for(const[h,p]of Object.entries(s))c[h]===void 0&&(c[h]=p);const u=[];for(const h in c){const p=encodeURIComponent(h),g=encodeURIComponent(c[h]);u.push(`${p}=${g}`)}const d=u.join("&");return(await Si(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:d},l)).status!==200?{success:!1}:{success:!0}},F0=n=>async(e,t,r,i,s={},l,c=1e4)=>{for(const[y,_]of Object.entries(r))t[y]===void 0&&(t[y]=_);const u=[];for(const y in t){const _=encodeURIComponent(y),S=encodeURIComponent(t[y]);u.push(`${_}=${S}`)}const d=u.join("&"),h=await Si(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",...s},body:d},c);if(h.status!==200)return{success:!1,status:h.status,demonstratingProofOfPossessionNonce:null};const p=await h.json();let g=null;return h.headers.has(vs)&&(g=h.headers.get(vs)),{success:!0,status:h.status,data:kl(p,i,l),demonstratingProofOfPossessionNonce:g}},z0=(n,e)=>async(t,r)=>{r=r?{...r}:{};const i=Tl(128),s=await D0(i);await n.setCodeVerifierAsync(i),await n.setStateAsync(r.state),r.code_challenge=s,r.code_challenge_method="S256";let l="";if(r)for(const[c,u]of Object.entries(r))l===""?l+="?":l+="&",l+=`${c}=${encodeURIComponent(u)}`;e.open(`${t}${l}`)},vs="DPoP-Nonce",W0=n=>async(e,t,r,i,s=1e4)=>{t=t?{...t}:{},t.code_verifier=await n.getCodeVerifierAsync();const l=[];for(const p in t){const g=encodeURIComponent(p),y=encodeURIComponent(t[p]);l.push(`${g}=${y}`)}const c=l.join("&"),u=await Si(fetch)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",...r},body:c},s);if(await Promise.all([n.setCodeVerifierAsync(null),n.setStateAsync(null)]),u.status!==200)return{success:!1,status:u.status};let d=null;u.headers.has(vs)&&(d=u.headers.get(vs));const h=await u.json();return{success:!0,data:{state:t.state,tokens:kl(h,null,i),demonstratingProofOfPossessionNonce:d}}};async function bf(n,e,t,r=null){const i=c=>{n.tokens=c},{tokens:s,status:l}=await ws(n)(i,0,e,t,r);return await It(n.configuration,n.configurationName)||await Nt(n.configurationName,n.configuration.storage).setTokens(n.tokens),n.tokens?s:(await n.destroyAsync(l),null)}async function vf(n,e=!1,t=null,r=null){const i=n.configuration,s=`${i.client_id}_${n.configurationName}_${i.authority}`;let l;const c=await It(n.configuration,n.configurationName);if((i==null?void 0:i.storage)===(window==null?void 0:window.sessionStorage)&&!c||!navigator.locks)l=await bf(n,e,t,r);else{let u="retry";for(;u==="retry";)u=await navigator.locks.request(s,{ifAvailable:!0},async d=>d?await bf(n,e,t,r):(n.publishEvent(mn.eventNames.syncTokensAsync_lock_not_available,{lock:"lock not available"}),"retry"));l=u}return l?(n.timeoutId&&(n.timeoutId=ki(n,n.tokens.expiresAt,t,r)),n.tokens):null}const ki=(n,e,t=null,r=null)=>{const i=n.configuration.refresh_time_before_tokens_expiration_in_second;return n.timeoutId&&Br.clearTimeout(n.timeoutId),Br.setTimeout(async()=>{const s={timeLeft:wi(i,e)};n.publishEvent(mn.eventNames.token_timer,s),await vf(n,!1,t,r)},1e3)},In={FORCE_REFRESH:"FORCE_REFRESH",SESSION_LOST:"SESSION_LOST",NOT_CONNECTED:"NOT_CONNECTED",TOKENS_VALID:"TOKENS_VALID",TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID",LOGOUT_FROM_ANOTHER_TAB:"LOGOUT_FROM_ANOTHER_TAB",REQUIRE_SYNC_TOKENS:"REQUIRE_SYNC_TOKENS"},$0=n=>async(e,t,r,i=!1)=>{const s={nonce:null};if(!r)return{tokens:null,status:"NOT_CONNECTED",nonce:s};let l=s;const c=await n.initAsync(e.authority,e.authority_configuration),u=await It(e,t);if(u){const{status:h,tokens:p}=await u.initAsync(c,"syncTokensAsync",e);if(h==="LOGGED_OUT")return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:s};if(h==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:s};if(!h||!p)return{tokens:null,status:"REQUIRE_SYNC_TOKENS",nonce:s};if(p.issuedAt!==r.issuedAt){const g=wi(e.refresh_time_before_tokens_expiration_in_second,p.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",y=await u.getNonceAsync();return{tokens:p,status:g,nonce:y}}l=await u.getNonceAsync()}else{const h=Nt(t,e.storage??sessionStorage),p=await h.initAsync();let{tokens:g}=p;const{status:y}=p;if(g&&(g=Sl(g,n.tokens,e.token_renew_mode)),g){if(y==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:s};if(g.issuedAt!==r.issuedAt){const _=wi(e.refresh_time_before_tokens_expiration_in_second,g.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",S=await h.getNonceAsync();return{tokens:g,status:_,nonce:S}}}else return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:s};l=await h.getNonceAsync()}const d=wi(e.refresh_time_before_tokens_expiration_in_second,r.expiresAt)>0?"TOKENS_VALID":"TOKENS_INVALID";return i?{tokens:r,status:"FORCE_REFRESH",nonce:l}:{tokens:r,status:d,nonce:l}},ws=n=>async(e,t=0,r=!1,i=null,s=null)=>{if(!navigator.onLine&&document.hidden)return{tokens:n.tokens,status:"GIVE_UP"};let l=6;for(;!navigator.onLine&&l>0;)await bs({milliseconds:1e3}),l--,n.publishEvent(ae.refreshTokensAsync,{message:`wait because navigator is offline try ${l}`});const c=document.hidden,u=c?t:t+1;if(t>4)return c?{tokens:n.tokens,status:"GIVE_UP"}:(e(null),n.publishEvent(ae.refreshTokensAsync_error,{message:"refresh token"}),{tokens:null,status:"SESSION_LOST"});i||(i={});const d=n.configuration,h=(g,y=null,_=null)=>Al(n.configurationName,n.configuration,n.publishEvent.bind(n))(g,y,_),p=async()=>{try{let g;const y=await It(d,n.configurationName);y?g=y.getLoginParams():g=Nt(n.configurationName,d.storage).getLoginParams();const _=await h({...g.extras,...i,prompt:"none",scope:s});return _?_.error?(e(null),n.publishEvent(ae.refreshTokensAsync_error,{message:"refresh token silent"}),{tokens:null,status:"SESSION_LOST"}):(e(_.tokens),n.publishEvent(mn.eventNames.token_renewed,{}),{tokens:_.tokens,status:"LOGGED"}):(e(null),n.publishEvent(ae.refreshTokensAsync_error,{message:"refresh token silent not active"}),{tokens:null,status:"SESSION_LOST"})}catch(g){return console.error(g),n.publishEvent(ae.refreshTokensAsync_silent_error,{message:"exceptionSilent",exception:g.message}),await ws(n)(e,u,r,i,s)}};try{const{status:g,tokens:y,nonce:_}=await $0(n)(d,n.configurationName,n.tokens,r);switch(g){case In.SESSION_LOST:return e(null),n.publishEvent(ae.refreshTokensAsync_error,{message:"refresh token session lost"}),{tokens:null,status:"SESSION_LOST"};case In.NOT_CONNECTED:return e(null),{tokens:null,status:null};case In.TOKENS_VALID:return e(y),{tokens:y,status:"LOGGED_IN"};case In.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:return e(y),n.publishEvent(mn.eventNames.token_renewed,{reason:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"}),{tokens:y,status:"LOGGED_IN"};case In.LOGOUT_FROM_ANOTHER_TAB:return e(null),n.publishEvent(ae.logout_from_another_tab,{status:"session syncTokensAsync"}),{tokens:null,status:"LOGGED_OUT"};case In.REQUIRE_SYNC_TOKENS:return d.token_automatic_renew_mode==vi.AutomaticOnlyWhenFetchExecuted&&In.FORCE_REFRESH!==g?(n.publishEvent(ae.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:n.tokens,status:"GIVE_UP"}):(n.publishEvent(ae.refreshTokensAsync_begin,{tryNumber:t}),await p());default:{if(d.token_automatic_renew_mode==vi.AutomaticOnlyWhenFetchExecuted&&In.FORCE_REFRESH!==g)return n.publishEvent(ae.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:n.tokens,status:"GIVE_UP"};if(n.publishEvent(ae.refreshTokensAsync_begin,{refreshToken:y.refreshToken,status:g,tryNumber:t}),!y.refreshToken)return await p();const S=d.client_id,k=d.redirect_uri,A=d.authority,P={...d.token_request_extras?d.token_request_extras:{}};for(const[L,B]of Object.entries(i))L.endsWith(":token_request")&&(P[L.replace(":token_request","")]=B);return await(async()=>{const L={client_id:S,redirect_uri:k,grant_type:"refresh_token",refresh_token:y.refreshToken},B=await n.initAsync(A,d.authority_configuration),W=document.hidden?1e4:3e4*10,z=B.tokenEndpoint,J={};d.demonstrating_proof_of_possession&&(J.DPoP=await n.generateDemonstrationOfProofOfPossessionAsync(y.accessToken,z,"POST"));const j=await F0(n.getFetch())(z,L,P,y,J,d.token_renew_mode,W);if(j.success){const{isValid:V,reason:ne}=of(j.data,_.nonce,B);if(!V)return e(null),n.publishEvent(ae.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${ne}`}),{tokens:null,status:"SESSION_LOST"};if(e(j.data),j.demonstratingProofOfPossessionNonce){const ve=await It(d,n.configurationName);ve?await ve.setDemonstratingProofOfPossessionNonce(j.demonstratingProofOfPossessionNonce):await Nt(n.configurationName,d.storage).setDemonstratingProofOfPossessionNonce(j.demonstratingProofOfPossessionNonce)}return n.publishEvent(ae.refreshTokensAsync_end,{success:j.success}),n.publishEvent(mn.eventNames.token_renewed,{reason:"REFRESH_TOKEN"}),{tokens:j.data,status:"LOGGED_IN"}}else return n.publishEvent(ae.refreshTokensAsync_silent_error,{message:"bad request",tokenResponse:j}),j.status>=400&&j.status<500?(e(null),n.publishEvent(ae.refreshTokensAsync_error,{message:`session lost: ${j.status}`}),{tokens:null,status:"SESSION_LOST"}):await ws(n)(e,u,r,i,s)})()}}}catch(g){return console.error(g),n.publishEvent(ae.refreshTokensAsync_silent_error,{message:"exception",exception:g.message}),new Promise((y,_)=>{setTimeout(()=>{ws(n)(e,u,r,i,s).then(y).catch(_)},1e3)})}},Al=(n,e,t)=>(r=null,i=null,s=null)=>{if(!e.silent_redirect_uri||!e.silent_login_uri)return Promise.resolve(null);try{t(ae.silentLoginAsync_begin,{});let l="";if(i&&(r==null&&(r={}),r.state=i),s!=null&&(r==null&&(r={}),r.scope=s),r!=null)for(const[p,g]of Object.entries(r))l===""?l=`?${encodeURIComponent(p)}=${encodeURIComponent(g)}`:l+=`&${encodeURIComponent(p)}=${encodeURIComponent(g)}`;const c=e.silent_login_uri+l,u=c.indexOf("/",c.indexOf("//")+2),d=c.substring(0,u),h=document.createElement("iframe");return h.width="0px",h.height="0px",h.id=`${n}_oidc_iframe`,h.setAttribute("src",c),document.body.appendChild(h),new Promise((p,g)=>{let y=!1;const _=()=>{window.removeEventListener("message",S),h.remove(),y=!0},S=k=>{if(k.origin===d&&k.source===h.contentWindow){const A=`${n}_oidc_tokens:`,P=`${n}_oidc_error:`,L=`${n}_oidc_exception:`,B=k.data;if(B&&typeof B=="string"&&!y){if(B.startsWith(A)){const W=JSON.parse(k.data.replace(A,""));t(ae.silentLoginAsync_end,{}),p(W),_()}else if(B.startsWith(P)){const W=JSON.parse(k.data.replace(P,""));t(ae.silentLoginAsync_error,W),p({error:"oidc_"+W.error,tokens:null,sessionState:null}),_()}else if(B.startsWith(L)){const W=JSON.parse(k.data.replace(L,""));t(ae.silentLoginAsync_error,W),g(new Error(W.error)),_()}}}};try{window.addEventListener("message",S);const k=e.silent_login_timeout;setTimeout(()=>{y||(_(),t(ae.silentLoginAsync_error,{reason:"timeout"}),g(new Error("timeout")))},k)}catch(k){_(),t(ae.silentLoginAsync_error,k),g(k)}})}catch(l){throw t(ae.silentLoginAsync_error,l),l}},V0=(n,e,t,r,i)=>(s=null,l=void 0)=>{s={...s};const c=(u,d,h)=>Al(e,t,r.bind(i))(u,d,h);return(async()=>{i.timeoutId&&Br.clearTimeout(i.timeoutId);let u;s&&"state"in s&&(u=s.state,delete s.state);try{const d=t.extras?{...t.extras,...s}:s,h=await c({...d,prompt:"none"},u,l);if(h)return i.tokens=h.tokens,r(ae.token_acquired,{}),i.timeoutId=ki(i,i.tokens.expiresAt,s,l),{}}catch(d){return d}})()},H0=(n,e,t)=>(r,i,s,l=!1)=>{const c=(u,d=void 0,h=void 0)=>Al(n.configurationName,t,n.publishEvent.bind(n))(u,d,h);return new Promise((u,d)=>{if(t.silent_login_uri&&t.silent_redirect_uri&&t.monitor_session&&r&&s&&!l){const h=()=>{n.checkSessionIFrame.stop();const p=n.tokens;if(p===null)return;const g=p.idToken,y=p.idTokenPayload;return c({prompt:"none",id_token_hint:g,scope:t.scope||"openid"}).then(_=>{if(_.error)throw new Error(_.error);const S=_.tokens.idTokenPayload;if(y.sub===S.sub){const k=_.sessionState;n.checkSessionIFrame.start(_.sessionState),y.sid===S.sid?console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",k):console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",k)}else console.debug("SessionMonitor._callback: Different subject signed into OP:",S.sub)}).catch(async _=>{console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:",_);for(const[,S]of Object.entries(e))await S.logoutOtherTabAsync(t.client_id,y.sub)})};n.checkSessionIFrame=new h0(h,i,r),n.checkSessionIFrame.load().then(()=>{n.checkSessionIFrame.start(s),u(n.checkSessionIFrame)}).catch(p=>{d(p)})}else u(null)})},U0=n=>!!(n.os==="iOS"&&n.osVersion.startsWith("12")||n.os==="Mac OS X"&&n.osVersion.startsWith("10_15_6")),K0=n=>{const e=n.appVersion,t=n.userAgent,r="-";let i=r;const s=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Chrome OS",r:/CrOS/},{s:"Linux",r:/(Linux|X11(?!.*CrOS))/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(const c in s){const u=s[c];if(u.r.test(t)){i=u.s;break}}let l=r;switch(/Windows/.test(i)&&(l=/Windows (.*)/.exec(i)[1],i="Windows"),i){case"Mac OS":case"Mac OS X":case"Android":l=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(t)[1];break;case"iOS":{const c=/OS (\d+)_(\d+)_?(\d+)?/.exec(e);c!=null&&c.length>2&&(l=c[1]+"."+c[2]+"."+(parseInt(c[3])|0));break}}return{os:i,osVersion:l}};function j0(){const n=navigator.userAgent;let e,t=n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(t[1]))return e=/\brv[ :]+(\d+)/g.exec(n)||[],{name:"ie",version:e[1]||""};if(t[1]==="Chrome"&&(e=n.match(/\bOPR|Edge\/(\d+)/),e!=null)){let r=e[1];if(!r){const i=n.split(e[0]+"/");i.length>1&&(r=i[1])}return{name:"opera",version:r}}return t=t[2]?[t[1],t[2]]:[navigator.appName,navigator.appVersion,"-?"],(e=n.match(/version\/(\d+)/i))!=null&&t.splice(1,1,e[1]),{name:t[0].toLowerCase(),version:t[1]}}const q0=()=>{const{name:n,version:e}=j0();if(n==="chrome"&&parseInt(e)<=70||n==="opera"&&(!e||parseInt(e.split(".")[0])<80)||n==="ie")return!1;const t=K0(navigator);return!U0(t)},J0=async n=>{let e;if(n.tokens!=null)return!1;n.publishEvent(ae.tryKeepExistingSessionAsync_begin,{});try{const t=n.configuration,r=await n.initAsync(t.authority,t.authority_configuration);if(e=await It(t,n.configurationName),e){const{tokens:i}=await e.initAsync(r,"tryKeepExistingSessionAsync",t);if(i){e.startKeepAliveServiceWorker(),n.tokens=i;const s=e.getLoginParams(n.configurationName);n.timeoutId=ki(n,n.tokens.expiresAt,s.extras,s.scope);const l=await e.getSessionStateAsync();return await n.startCheckSessionAsync(r.checkSessionIframe,t.client_id,l),t.preload_user_info&&await n.userInfoAsync(),n.publishEvent(ae.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside ServiceWorker are valid"}),!0}n.publishEvent(ae.tryKeepExistingSessionAsync_end,{success:!1,message:"no exiting session found"})}else{t.service_worker_relative_url&&n.publishEvent(ae.service_worker_not_supported_by_browser,{message:"service worker is not supported by this browser"});const i=Nt(n.configurationName,t.storage??sessionStorage),{tokens:s}=await i.initAsync();if(s){n.tokens=Sl(s,null,t.token_renew_mode);const l=i.getLoginParams();n.timeoutId=ki(n,n.tokens.expiresAt,l.extras,l.scope);const c=await i.getSessionStateAsync();return await n.startCheckSessionAsync(r.checkSessionIframe,t.client_id,c),t.preload_user_info&&await n.userInfoAsync(),n.publishEvent(ae.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside storage are valid"}),!0}}return n.publishEvent(ae.tryKeepExistingSessionAsync_end,{success:!1,message:e?"service worker sessions not retrieved":"session storage sessions not retrieved"}),!1}catch(t){return console.error(t),e&&await e.clearAsync(),n.publishEvent(ae.tryKeepExistingSessionAsync_error,"tokens inside ServiceWorker are invalid"),!1}},wf=n=>{const e=n.match(/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!e)throw new Error("Invalid URL");let t=e[6],r=e[7];if(r){const i=r.split("?");i.length===2&&(r=i[0],t=i[1])}return t.startsWith("?")&&(t=t.slice(1)),e&&{href:n,protocol:e[1],host:e[2],hostname:e[3],port:e[4],path:e[5],search:t,hash:r}},xi=n=>{const e=wf(n);let{path:t}=e;t.endsWith("/")&&(t=t.slice(0,-1));let{hash:r}=e;return r==="#_=_"&&(r=""),r&&(t+=r),t},Ss=n=>{const e=wf(n),{search:t}=e;return G0(t)},G0=n=>{const e={};let t,r,i;const s=n.split("&");for(r=0,i=s.length;r<i;r++)t=s[r].split("="),e[decodeURIComponent(t[0])]=decodeURIComponent(t[1]);return e},Y0=(n,e,t,r,i)=>(s=void 0,l=null,c=!1,u=void 0)=>{const d=l;return l={...l},(async()=>{const h=s||i.getPath();if("state"in l||(l.state=Tl(16)),t(ae.loginAsync_begin,{}),l)for(const p of Object.keys(l))p.endsWith(":token_request")&&delete l[p];try{const p=c?e.silent_redirect_uri:e.redirect_uri;u||(u=e.scope);const g=e.extras?{...e.extras,...l}:l;g.nonce||(g.nonce=Tl(12));const y={nonce:g.nonce},_=await It(e,n),S=await r(e.authority,e.authority_configuration);let k;if(_)_.setLoginParams({callbackPath:h,extras:d,scope:u}),await _.initAsync(S,"loginAsync",e),await _.setNonceAsync(y),_.startKeepAliveServiceWorker(),k=_;else{const P=Nt(n,e.storage??sessionStorage);P.setLoginParams({callbackPath:h,extras:d,scope:u}),await P.setNonceAsync(y),k=P}const A={client_id:e.client_id,redirect_uri:p,scope:u,response_type:"code",...g};await z0(k,i)(S.authorizationEndpoint,A)}catch(p){throw t(ae.loginAsync_error,p),p}})()},Q0=n=>async(e=!1)=>{try{n.publishEvent(ae.loginCallbackAsync_begin,{});const t=n.configuration,r=t.client_id,i=e?t.silent_redirect_uri:t.redirect_uri,s=t.authority,l=t.token_request_timeout,c=await n.initAsync(s,t.authority_configuration),u=n.location.getCurrentHref(),d=Ss(u),h=d.session_state,p=await It(t,n.configurationName);let g,y,_,S;if(p)await p.initAsync(c,"loginCallbackAsync",t),await p.setSessionStateAsync(h),y=await p.getNonceAsync(),_=p.getLoginParams(),S=await p.getStateAsync(),p.startKeepAliveServiceWorker(),g=p;else{const ne=Nt(n.configurationName,t.storage??sessionStorage);await ne.setSessionStateAsync(h),y=await ne.getNonceAsync(),_=ne.getLoginParams(),S=await ne.getStateAsync(),g=ne}if(d.error||d.error_description)throw new Error(`Error from OIDC server: ${d.error} - ${d.error_description}`);if(d.iss&&d.iss!==c.issuer)throw console.error(),new Error(`Issuer not valid (expected: ${c.issuer}, received: ${d.iss})`);if(d.state&&d.state!==S)throw new Error(`State not valid (expected: ${S}, received: ${d.state})`);const k={code:d.code,grant_type:"authorization_code",client_id:t.client_id,redirect_uri:i},A={};if(t.token_request_extras)for(const[ne,ve]of Object.entries(t.token_request_extras))A[ne]=ve;if(_!=null&&_.extras)for(const[ne,ve]of Object.entries(_.extras))ne.endsWith(":token_request")&&(A[ne.replace(":token_request","")]=ve);const P=c.tokenEndpoint,L={};if(t.demonstrating_proof_of_possession)if(p)L.DPoP=`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${n.configurationName}`;else{const ne=await N0(window)(t.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm);await Nt(n.configurationName,t.storage).setDemonstratingProofOfPossessionJwkAsync(ne),L.DPoP=await mf(window)(t.demonstrating_proof_of_possession_configuration)(ne,"POST",P)}const B=await W0(g)(P,{...k,...A},L,n.configuration.token_renew_mode,l);if(!B.success)throw new Error("Token request failed");let W;const z=B.data.tokens,J=B.data.demonstratingProofOfPossessionNonce;if(B.data.state!==A.state)throw new Error("state is not valid");const{isValid:j,reason:V}=of(z,y.nonce,c);if(!j)throw new Error(`Tokens are not OpenID valid, reason: ${V}`);if(p){if(z.refreshToken&&!z.refreshToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))throw new Error("Refresh token should be hidden by service worker");if(J&&z!=null&&z.accessToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))throw new Error("Demonstration of proof of possession require Access token not hidden by service worker")}if(p)await p.initAsync(c,"syncTokensAsync",t),W=p.getLoginParams(),J&&await p.setDemonstratingProofOfPossessionNonce(J);else{const ne=Nt(n.configurationName,t.storage);W=ne.getLoginParams(),J&&await ne.setDemonstratingProofOfPossessionNonce(J)}return await n.startCheckSessionAsync(c.checkSessionIframe,r,h,e),n.publishEvent(ae.loginCallbackAsync_end,{}),{tokens:z,state:"request.state",callbackPath:W.callbackPath,scope:d.scope,extras:W.extras}}catch(t){throw console.error(t),n.publishEvent(ae.loginCallbackAsync_error,t),t}},Sf={access_token:"access_token",refresh_token:"refresh_token"},Cl=(n,e)=>{const t={};if(n){for(const[r,i]of Object.entries(n))if(r.endsWith(e)){const s=r.replace(e,"");t[s]=i}return t}return t},X0=n=>{const e={};if(n){for(const[t,r]of Object.entries(n))t.includes(":")||(e[t]=r);return e}return e},Z0=n=>async e=>{Br.clearTimeout(n.timeoutId),n.timeoutId=null,n.checkSessionIFrame&&n.checkSessionIFrame.stop();const t=await It(n.configuration,n.configurationName);t?await t.clearAsync(e):await Nt(n.configurationName,n.configuration.storage).clearAsync(e),n.tokens=null,n.userInfo=null},e_=(n,e,t,r,i)=>async(s=void 0,l=null)=>{var c,u;const d=n.configuration,h=await n.initAsync(d.authority,d.authority_configuration);s&&typeof s!="string"&&(s=void 0,r.warn("callbackPathOrUrl path is not a string"));const p=s??i.getPath();let g=!1;s&&(g=s.includes("https://")||s.includes("http://"));const y=g?s:i.getOrigin()+p,_=n.tokens?n.tokens.idToken:"";try{const P=h.revocationEndpoint;if(P){const L=[],B=n.tokens?n.tokens.accessToken:null;if(B&&d.logout_tokens_to_invalidate.includes(Sf.access_token)){const z=Cl(l,":revoke_access_token"),J=_f(t)(P,B,Ol.access_token,d.client_id,z);L.push(J)}const W=n.tokens?n.tokens.refreshToken:null;if(W&&d.logout_tokens_to_invalidate.includes(Sf.refresh_token)){const z=Cl(l,":revoke_refresh_token"),J=_f(t)(P,W,Ol.refresh_token,d.client_id,z);L.push(J)}L.length>0&&await Promise.all(L)}}catch(P){r.warn("logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error"),r.warn(P)}const S=((u=(c=n.tokens)==null?void 0:c.idTokenPayload)==null?void 0:u.sub)??null;await n.destroyAsync("LOGGED_OUT");for(const[,P]of Object.entries(e))P!==n?await n.logoutSameTabAsync(n.configuration.client_id,S):n.publishEvent(ae.logout_from_same_tab,{});const k=Cl(l,":oidc");if(k&&k.no_reload==="true")return;const A=X0(l);if(h.endSessionEndpoint){"id_token_hint"in A||(A.id_token_hint=_),!("post_logout_redirect_uri"in A)&&s!==null&&(A.post_logout_redirect_uri=y);let P="";for(const[L,B]of Object.entries(A))B!=null&&(P===""?P+="?":P+="&",P+=`${L}=${encodeURIComponent(B)}`);i.open(`${h.endSessionEndpoint}${P}`)}else i.reload()},kf=(n,e,t=!1)=>async(...r)=>{var i;const[s,l,...c]=r,u=l?{...l}:{method:"GET"};let d=new Headers;u.headers&&(d=u.headers instanceof Headers?u.headers:new Headers(u.headers));const h={getTokens:()=>e.tokens,configuration:{token_automatic_renew_mode:e.configuration.token_automatic_renew_mode,refresh_time_before_tokens_expiration_in_second:e.configuration.refresh_time_before_tokens_expiration_in_second},renewTokensAsync:e.renewTokensAsync.bind(e)},p=await sf(h),g=(i=p==null?void 0:p.tokens)==null?void 0:i.accessToken;if(d.has("Accept")||d.set("Accept","application/json"),g){if(e.configuration.demonstrating_proof_of_possession&&t){const _=await e.generateDemonstrationOfProofOfPossessionAsync(g,s.toString(),u.method);d.set("Authorization",`DPoP ${g}`),d.set("DPoP",_)}else d.set("Authorization",`Bearer ${g}`);u.credentials||(u.credentials="same-origin")}const y={...u,headers:d};return await n(s,y,...c)},t_=n=>async(e=!1,t=!1)=>{if(n.userInfo!=null&&!e)return n.userInfo;const r=n.configuration,i=(await n.initAsync(r.authority,r.authority_configuration)).userInfoEndpoint,s=await(async()=>{const l=await kf(fetch,n,t)(i);return l.status!==200?null:l.json()})();return n.userInfo=s,s},xf=()=>fetch;let Ml=class{constructor(e){this.authorizationEndpoint=e.authorization_endpoint,this.tokenEndpoint=e.token_endpoint,this.revocationEndpoint=e.revocation_endpoint,this.userInfoEndpoint=e.userinfo_endpoint,this.checkSessionIframe=e.check_session_iframe,this.issuer=e.issuer,this.endSessionEndpoint=e.end_session_endpoint}};const ar={},n_=(n,e=new Dr)=>(t,r="default")=>(ar[r]||(ar[r]=new mn(t,r,n,e)),ar[r]),r_=async n=>{const{parsedTokens:e,callbackPath:t,extras:r,scope:i}=await n.loginCallbackAsync();return n.timeoutId=ki(n,e.expiresAt,r,i),{callbackPath:t}},i_=n=>Math.floor(Math.random()*n),Nl=class py{constructor(e,t="default",r,i=new Dr){this.initPromise=null,this.tryKeepExistingSessionPromise=null,this.loginPromise=null,this.loginCallbackPromise=null,this.loginCallbackWithAutoTokensRenewPromise=null,this.userInfoPromise=null,this.renewTokensPromise=null,this.logoutPromise=null;let s=e.silent_login_uri;e.silent_redirect_uri&&!e.silent_login_uri&&(s=`${e.silent_redirect_uri.replace("-callback","").replace("callback","")}-login`);let l=e.refresh_time_before_tokens_expiration_in_second??120;l>60&&(l=l-Math.floor(Math.random()*40)),this.location=i??new Dr;const c=e.service_worker_update_require_callback??b0(this.location);this.configuration={...e,silent_login_uri:s,token_automatic_renew_mode:e.token_automatic_renew_mode??vi.AutomaticBeforeTokenExpiration,monitor_session:e.monitor_session??!1,refresh_time_before_tokens_expiration_in_second:l,silent_login_timeout:e.silent_login_timeout??12e3,token_renew_mode:e.token_renew_mode??wl.access_token_or_id_token_invalid,demonstrating_proof_of_possession:e.demonstrating_proof_of_possession??!1,authority_timeout_wellknowurl_in_millisecond:e.authority_timeout_wellknowurl_in_millisecond??1e4,logout_tokens_to_invalidate:e.logout_tokens_to_invalidate??["access_token","refresh_token"],service_worker_update_require_callback:c,service_worker_activate:e.service_worker_activate??q0,demonstrating_proof_of_possession_configuration:e.demonstrating_proof_of_possession_configuration??k0,preload_user_info:e.preload_user_info??!1},this.getFetch=r??xf,this.configurationName=t,this.tokens=null,this.userInfo=null,this.events=[],this.timeoutId=null,this.loginCallbackWithAutoTokensRenewAsync.bind(this),this.initAsync.bind(this),this.loginCallbackAsync.bind(this),this.subscribeEvents.bind(this),this.removeEventSubscription.bind(this),this.publishEvent.bind(this),this.destroyAsync.bind(this),this.logoutAsync.bind(this),this.renewTokensAsync.bind(this),this.initAsync(this.configuration.authority,this.configuration.authority_configuration)}subscribeEvents(e){const t=i_(9999999999999).toString();return this.events.push({id:t,func:e}),t}removeEventSubscription(e){const t=this.events.filter(r=>r.id!==e);this.events=t}publishEvent(e,t){this.events.forEach(r=>{r.func(e,t)})}static get(e="default"){const t=typeof process>"u";if(!Object.prototype.hasOwnProperty.call(ar,e)&&t)throw Error(`OIDC library does seem initialized.
|
|
24
|
-
Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${e}"></OidcProvider> component.`);return ar[e]}_silentLoginCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=this.location,t=Ss(e.getCurrentHref());window.parent.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:this.tokens,sessionState:t.session_state})}`,e.getOrigin())}}_silentLoginErrorCallbackFromIFrame(e=null){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const t=this.location,r=Ss(t.getCurrentHref());r.error?window.parent.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:r.error})}`,t.getOrigin()):window.parent.postMessage(`${this.configurationName}_oidc_exception:${JSON.stringify({error:e==null?"":e.toString()})}`,t.getOrigin())}}async silentLoginCallbackAsync(){try{await this.loginCallbackAsync(!0),this._silentLoginCallbackFromIFrame()}catch(e){console.error(e),this._silentLoginErrorCallbackFromIFrame(e)}}async initAsync(e,t){if(this.initPromise!==null)return this.initPromise;const r=async()=>{if(t!=null)return new Ml({authorization_endpoint:t.authorization_endpoint,end_session_endpoint:t.end_session_endpoint,revocation_endpoint:t.revocation_endpoint,token_endpoint:t.token_endpoint,userinfo_endpoint:t.userinfo_endpoint,check_session_iframe:t.check_session_iframe,issuer:t.issuer});const i=await It(this.configuration,this.configurationName)?window.sessionStorage:null;return await B0(this.getFetch())(e,this.configuration.authority_time_cache_wellknowurl_in_second??60*60,i,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=r(),this.initPromise.finally(()=>{this.initPromise=null})}async tryKeepExistingSessionAsync(){return this.tryKeepExistingSessionPromise!==null?this.tryKeepExistingSessionPromise:(this.tryKeepExistingSessionPromise=J0(this),this.tryKeepExistingSessionPromise.finally(()=>{this.tryKeepExistingSessionPromise=null}))}async startCheckSessionAsync(e,t,r,i=!1){await H0(this,ar,this.configuration)(e,t,r,i)}async loginAsync(e=void 0,t=null,r=!1,i=void 0,s=!1){return this.logoutPromise&&await this.logoutPromise,this.loginPromise!==null?this.loginPromise:(s?this.loginPromise=V0(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,i):this.loginPromise=Y0(this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this),this.location)(e,t,r,i),this.loginPromise.finally(()=>{this.loginPromise=null}))}async loginCallbackAsync(e=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;const t=async()=>{const r=await Q0(this)(e),i=r.tokens;return this.tokens=i,await It(this.configuration,this.configurationName)||Nt(this.configurationName,this.configuration.storage).setTokens(i),this.publishEvent(py.eventNames.token_acquired,i),this.configuration.preload_user_info&&await this.userInfoAsync(),{parsedTokens:i,state:r.state,callbackPath:r.callbackPath,scope:r.scope,extras:r.extras}};return this.loginCallbackPromise=t(),this.loginCallbackPromise.finally(()=>{this.loginCallbackPromise=null})}async generateDemonstrationOfProofOfPossessionAsync(e,t,r,i={}){const s=this.configuration,l={ath:await yf(e),...i};if(await It(s,this.configurationName))return`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${this.configurationName}#tabId=${ff(this.configurationName)}`;const c=Nt(this.configurationName,s.storage),u=await c.getDemonstratingProofOfPossessionJwkAsync(),d=c.getDemonstratingProofOfPossessionNonce();return d&&(l.nonce=d),await mf(window)(s.demonstrating_proof_of_possession_configuration)(u,r,t,l)}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise!==null?this.loginCallbackWithAutoTokensRenewPromise:(this.loginCallbackWithAutoTokensRenewPromise=r_(this),this.loginCallbackWithAutoTokensRenewPromise.finally(()=>{this.loginCallbackWithAutoTokensRenewPromise=null}))}userInfoAsync(e=!1,t=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=t_(this)(e,t),this.userInfoPromise.finally(()=>{this.userInfoPromise=null}))}async renewTokensAsync(e=null,t=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(this.timeoutId)return Br.clearTimeout(this.timeoutId),this.renewTokensPromise=vf(this,!0,e,t),this.renewTokensPromise.finally(()=>{this.renewTokensPromise=null})}async destroyAsync(e){return await Z0(this)(e)}async logoutSameTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(ae.logout_from_same_tab,{mmessage:"SessionMonitor",sub:t}))}async logoutOtherTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(ae.logout_from_another_tab,{message:"SessionMonitor",sub:t}))}async logoutAsync(e=void 0,t=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=e_(this,ar,this.getFetch(),console,this.location)(e,t),this.logoutPromise.finally(()=>{this.logoutPromise=null}))}};Nl.getOrCreate=(n,e)=>(t,r="default")=>n_(n,e)(t,r),Nl.eventNames=ae;let mn=Nl;const ks=class my{constructor(e){this._oidc=e}subscribeEvents(e){return this._oidc.subscribeEvents(e)}removeEventSubscription(e){this._oidc.removeEventSubscription(e)}publishEvent(e,t){this._oidc.publishEvent(e,t)}static get(e="default"){return new my(mn.get(e))}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(e=void 0,t=null,r=!1,i=void 0,s=!1){return this._oidc.loginAsync(e,t,r,i,s)}logoutAsync(e=void 0,t=null){return this._oidc.logoutAsync(e,t)}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(e=null,t=null){return this._oidc.renewTokensAsync(e,t)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async generateDemonstrationOfProofOfPossessionAsync(e,t,r,i={}){return this._oidc.generateDemonstrationOfProofOfPossessionAsync(e,t,r,i)}async getValidTokenAsync(e=200,t=50){const r=this._oidc,i={getTokens:()=>r.tokens,configuration:{token_automatic_renew_mode:r.configuration.token_automatic_renew_mode,refresh_time_before_tokens_expiration_in_second:r.configuration.refresh_time_before_tokens_expiration_in_second},renewTokensAsync:r.renewTokensAsync.bind(r)};return sf(i,e,t)}fetchWithTokens(e,t=!1){return kf(e,this._oidc,t)}async userInfoAsync(e=!1,t=!1){return this._oidc.userInfoAsync(e,t)}userInfo(){return this._oidc.userInfo}};ks.getOrCreate=(n,e=new Dr)=>(t,r="default")=>new ks(mn.getOrCreate(n,e)(t,r)),ks.eventNames=mn.eventNames;let me=ks;const Ef=()=>Y.jsx("div",{className:"oidc-authenticating",children:Y.jsxs("div",{className:"oidc-authenticating__container",children:[Y.jsx("h1",{className:"oidc-authenticating__title",children:"Error authentication"}),Y.jsx("p",{className:"oidc-authenticating__content",children:"An error occurred during authentication."})]})}),s_=()=>Y.jsx("div",{className:"oidc-authenticating",children:Y.jsxs("div",{className:"oidc-authenticating__container",children:[Y.jsx("h1",{className:"oidc-authenticating__title",children:"Authentication in progress"}),Y.jsx("p",{className:"oidc-authenticating__content",children:"You will be redirected to the login page."})]})}),o_=()=>Math.random().toString(36).slice(2,8),l_=(n,e)=>(t,r)=>{if(typeof n.CustomEvent=="function")return new n.CustomEvent(t,r);const i=r||{bubbles:!1,cancelable:!1,detail:void 0},s=e.createEvent("CustomEvent");return s.initCustomEvent(t,i.bubbles,i.cancelable,i.detail),s.prototype=n.Event.prototype,s},a_=(n,e,t)=>({replaceState:(r,i)=>{const s=t(),l=i||n.history.state;n.history.replaceState({key:s,state:l},null,r),n.dispatchEvent(e("popstate"))}}),c_=()=>a_(window,l_(window,document),o_),Tf=()=>Y.jsx("div",{className:"oidc-callback",children:Y.jsxs("div",{className:"oidc-callback__container",children:[Y.jsx("h1",{className:"oidc-callback__title",children:"Authentication complete"}),Y.jsx("p",{className:"oidc-callback__content",children:"You will be redirected to your application."})]})}),u_=({callBackError:n,callBackSuccess:e,configurationName:t,withCustomHistory:r})=>{const[i,s]=K.useState(!1);K.useEffect(()=>{let u=!0;return(async()=>{const d=me.get;try{const{callbackPath:h}=await d(t).loginCallbackAsync();(r?r():c_()).replaceState(h||"/")}catch(h){u&&(console.warn(h),s(!0))}})(),()=>{u=!1}},[]);const l=n||Ef,c=e||Tf;return i?Y.jsx(l,{configurationName:t}):Y.jsx(c,{configurationName:t})},f_=()=>Y.jsx("span",{className:"oidc-loading",children:"Loading"}),d_=()=>Y.jsx("div",{className:"oidc-serviceworker",children:Y.jsxs("div",{className:"oidc-serviceworker__container",children:[Y.jsx("h1",{className:"oidc-serviceworker__title",children:"Unable to authenticate on this browser"}),Y.jsx("p",{className:"oidc-serviceworker__content",children:"Your browser is not secure enough to make authentication work. Try updating your browser or use a newer browser."})]})}),h_=()=>Y.jsx("div",{className:"oidc-session-lost",children:Y.jsxs("div",{className:"oidc-session-lost__container",children:[Y.jsx("h1",{className:"oidc-session-lost__title",children:"Session timed out"}),Y.jsx("p",{className:"oidc-session-lost__content",children:"Your session has expired. Please re-authenticate."})]})}),p_=({configurationName:n})=>(K.useEffect(()=>{(async()=>{me.get(n).silentLoginCallbackAsync()})().catch(e=>{console.error("Error during silent login callback:",e)})},[n]),null),m_=({configurationName:n})=>{const e=Ss(window.location.href),t=me.get,r=t(n);let i=null;for(const[s,l]of Object.entries(e))s==="state"||s==="scope"||(i===null&&(i={}),i[s]=l);return K.useEffect(()=>{r.tokens||r.loginAsync(null,i,!0,e.scope)},[]),Y.jsx(Y.Fragment,{})},g_=({callbackErrorComponent:n,callbackSuccessComponent:e,redirect_uri:t,silent_redirect_uri:r,silent_login_uri:i,children:s,configurationName:l,withCustomHistory:c=null})=>{const u=window?xi(window.location.href):"",[d,h]=K.useState(u);K.useEffect(()=>{const g=()=>h(xi(window.location.href));return g(),window.addEventListener("popstate",g,!1),()=>window.removeEventListener("popstate",g,!1)},[]);const p=xi(t);if(r&&d===xi(r))return Y.jsx(p_,{configurationName:l});if(i&&d===xi(i))return Y.jsx(m_,{configurationName:l});switch(d){case p:return Y.jsx(u_,{callBackError:n,callBackSuccess:e,configurationName:l,withCustomHistory:c});default:return Y.jsx(Y.Fragment,{children:s})}},y_=K.memo(g_),Of={name:"",data:null},__=({loadingComponent:n,children:e,configurationName:t})=>{const[r,i]=K.useState(!0),s=me.get,l=s(t);return K.useEffect(()=>{let c=!0;return l&&l.tryKeepExistingSessionAsync().then(()=>{c&&i(!1)}),()=>{c=!1}},[t]),Y.jsx(Y.Fragment,{children:r?Y.jsx(n,{configurationName:t}):Y.jsx(Y.Fragment,{children:e})})},Ei=({isLoading:n,loadingComponent:e,children:t,configurationName:r})=>{const i=e;return n?Y.jsx(i,{configurationName:r,children:t}):Y.jsx(Y.Fragment,{children:t})},b_=({children:n,configuration:e,configurationName:t="default",callbackSuccessComponent:r=Tf,authenticatingComponent:i=s_,loadingComponent:s=f_,serviceWorkerNotSupportedComponent:l=d_,authenticatingErrorComponent:c=Ef,sessionLostComponent:u=h_,onSessionLost:d=null,onLogoutFromAnotherTab:h=null,onLogoutFromSameTab:p=null,withCustomHistory:g=null,onEvent:y=null,getFetch:_=null,location:S=null})=>{const k=(Ke="default")=>me.getOrCreate(_??xf,S??new Dr)(e,Ke),[A,P]=K.useState(!0),[L,B]=K.useState(Of),[W,z]=K.useState("default");K.useEffect(()=>{const Ke=k(t).subscribeEvents((Me,ft)=>{y&&y(t,Me,ft)});return()=>{k(t).removeEventSubscription(Ke)}},[t,y]),K.useEffect(()=>{const Ke=k(t).subscribeEvents((Me,ft)=>{if(Me===me.eventNames.refreshTokensAsync_error||Me===me.eventNames.syncTokensAsync_error){if(d!=null){d();return}B({name:Me,data:ft})}else if(Me===me.eventNames.logout_from_another_tab){if(h!=null){h();return}B({name:Me,data:ft})}else Me===me.eventNames.logout_from_same_tab?p!=null&&p():Me===me.eventNames.loginAsync_begin||Me===me.eventNames.loginCallbackAsync_end||Me===me.eventNames.loginAsync_error||Me===me.eventNames.loginCallbackAsync_error?B({name:Me,data:ft}):Me===me.eventNames.service_worker_not_supported_by_browser&&e.service_worker_only===!0&&B({name:Me,data:ft})});return z(t),P(!1),()=>{k(t).removeEventSubscription(Ke),B(Of)}},[e,t]);const J=u,j=i,V=s,ne=l,ve=c,Le=A||W!==t,_t=k(t);switch(L.name){case me.eventNames.service_worker_not_supported_by_browser:return Y.jsx(Ei,{loadingComponent:V,isLoading:Le,configurationName:t,children:Y.jsx(ne,{configurationName:t})});case me.eventNames.loginAsync_begin:return Y.jsx(Ei,{loadingComponent:V,isLoading:Le,configurationName:t,children:Y.jsx(j,{configurationName:t})});case me.eventNames.loginAsync_error:case me.eventNames.loginCallbackAsync_error:return Y.jsx(Ei,{loadingComponent:V,isLoading:Le,configurationName:t,children:Y.jsx(ve,{configurationName:t})});case me.eventNames.refreshTokensAsync_error:case me.eventNames.syncTokensAsync_error:case me.eventNames.logout_from_another_tab:return Y.jsx(Ei,{loadingComponent:V,isLoading:Le,configurationName:t,children:Y.jsx(J,{configurationName:t})});default:return Y.jsx(Ei,{loadingComponent:V,isLoading:Le,configurationName:t,children:Y.jsx(y_,{redirect_uri:_t.configuration.redirect_uri,silent_redirect_uri:_t.configuration.silent_redirect_uri,silent_login_uri:_t.configuration.silent_login_uri,callbackSuccessComponent:r,callbackErrorComponent:c,authenticatingComponent:i,configurationName:t,withCustomHistory:g,location:S??new Dr,children:Y.jsx(__,{loadingComponent:V,configurationName:t,children:n})})})}},Af="default",Il=(n,e)=>{let t=!1;return n(e)&&(t=n(e).tokens!=null),t},v_=(n=Af)=>{const e=me.get,[t,r]=K.useState(Il(e,n));return K.useEffect(()=>{let i=!0;const s=e(n);r(Il(e,n));const l=s.subscribeEvents((c,u)=>{(c===me.eventNames.logout_from_another_tab||c===me.eventNames.logout_from_same_tab||c===me.eventNames.token_acquired)&&i&&r(Il(e,n))});return()=>{i=!1,s.removeEventSubscription(l)}},[n]),{login:(i=void 0,s=void 0,l=!1,c=void 0)=>e(n).loginAsync(i,s,!1,c,l),logout:(i=void 0,s=void 0)=>e(n).logoutAsync(i,s),renewTokens:async(i=void 0)=>{const s=await e(n).renewTokensAsync(i);return{accessToken:s.accessToken,accessTokenPayload:s.accessTokenPayload,idToken:s.idToken,idTokenPayload:s.idTokenPayload}},isAuthenticated:t}},Cf={accessToken:null,accessTokenPayload:null},w_=n=>{const e=me.get,t=e(n);if(t.tokens){const r=t.tokens;return{accessToken:r.accessToken,accessTokenPayload:r.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:t.configuration.demonstrating_proof_of_possession?(i,s)=>t.generateDemonstrationOfProofOfPossessionAsync(r.accessToken,i,s):null}}return Cf};function S_(n,e){return n.configuration.demonstrating_proof_of_possession?(t,r,i={})=>n.generateDemonstrationOfProofOfPossessionAsync(e.accessToken,t,r,i):null}const k_=(n=Af)=>{const e=me.get,[t,r]=K.useState(w_(n));return K.useEffect(()=>{let i=!0;const s=e(n);if(s.tokens){const c=s.tokens;r({accessToken:c.accessToken,accessTokenPayload:c.accessTokenPayload})}const l=s.subscribeEvents((c,u)=>{if((c===me.eventNames.token_renewed||c===me.eventNames.token_acquired||c===me.eventNames.logout_from_another_tab||c===me.eventNames.logout_from_same_tab||c===me.eventNames.refreshTokensAsync_error||c===me.eventNames.syncTokensAsync_error)&&i){const d=s.tokens;r(d!=null?{accessToken:d.accessToken,accessTokenPayload:d.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:S_(s,d)}:Cf)}});return()=>{i=!1,s.removeEventSubscription(l)}},[n]),t},Mf=K.createContext({}),zr=()=>{const n=K.useContext(Mf);if(!n)throw new Error("useWellPlayed must be used within a WellPlayedProvider");return n},x_=({children:n,clientConfig:e,organizationId:t,apiBaseUrl:r,typedClientConfig:i})=>{const s=k_(),l=K.useMemo(()=>sr.createWellPlayedClient({token:(s==null?void 0:s.accessToken)??void 0,organizationId:t,...e,apiBaseUrl:r}),[s==null?void 0:s.accessToken,t,e,r]);return Y.jsx(Ky,{client:l,children:Y.jsx(Mf.Provider,{value:{organizationId:t,apiClient:l,typedClient:sr.createTypedClient({apiBaseUrl:r,organizationId:t,token:(s==null?void 0:s.accessToken)??void 0,...i})},children:n})})},E_=({children:n,oidcConfig:e,wpAppConfig:t,...r})=>Y.jsx(b_,{...e,configuration:{...t,...e==null?void 0:e.configuration,authority:`https://oauth.warrior.${r.apiBaseUrl??"well-played.gg"}`},children:Y.jsx(x_,{...r,children:n})}),T_=(n,e)=>{const{apiClient:t}=zr(),{data:r,loading:i,refetch:s,fetchMore:l}=gl(n,{...e,notifyOnNetworkStatusChange:!0,variables:{...e==null?void 0:e.variables,page:{first:(e==null?void 0:e.pageSize)??100}},client:t}),c=n.definitions[0].selectionSet.selections[0].name.value;return{data:r,loading:i,loadNextPage:u=>{const d=r==null?void 0:r[c];if(d!=null&&d.pageInfo.hasNextPage)return s({...e==null?void 0:e.variables,...u,page:{first:(e==null?void 0:e.pageSize)??100,after:d.pageInfo.endCursor}})},loadNextPageWithoutAppendingOldData:u=>{const d=r==null?void 0:r[c];return l({variables:{...e==null?void 0:e.variables,...u,page:{first:(e==null?void 0:e.pageSize)??100,after:d==null?void 0:d.pageInfo.endCursor}}})}}},Pl=(n,e)=>{const[t,r]=K.useState(!(e!=null&&e.skip)),[i,s]=K.useState([]),{apiClient:l}=zr(),[c]=Xu(n,{...e,client:l}),u=async d=>{var _;const h=n.definitions[0].selectionSet.selections[0].name.value;r(!0);let p=!0,g=null;const y=[];for(;p;){const{data:S,error:k}=await c({variables:{...e==null?void 0:e.variables,...d,page:{first:100,after:g}}});if(k)throw k;const A=S==null?void 0:S[h];A&&(y.push(...A.nodes??[]),p=A.pageInfo.hasNextPage,g=A.pageInfo.endCursor)}return s(y),(_=e==null?void 0:e.onResults)==null||_.call(e,y),r(!1),y};return K.useEffect(()=>{e!=null&&e.skip||u()},[e==null?void 0:e.skip]),{loading:t,results:i,refetch:u}},O_=sr.graphql(`
|
|
24
|
+
Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${e}"></OidcProvider> component.`);return ar[e]}_silentLoginCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=this.location,t=Ss(e.getCurrentHref());window.parent.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:this.tokens,sessionState:t.session_state})}`,e.getOrigin())}}_silentLoginErrorCallbackFromIFrame(e=null){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const t=this.location,r=Ss(t.getCurrentHref());r.error?window.parent.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:r.error})}`,t.getOrigin()):window.parent.postMessage(`${this.configurationName}_oidc_exception:${JSON.stringify({error:e==null?"":e.toString()})}`,t.getOrigin())}}async silentLoginCallbackAsync(){try{await this.loginCallbackAsync(!0),this._silentLoginCallbackFromIFrame()}catch(e){console.error(e),this._silentLoginErrorCallbackFromIFrame(e)}}async initAsync(e,t){if(this.initPromise!==null)return this.initPromise;const r=async()=>{if(t!=null)return new Ml({authorization_endpoint:t.authorization_endpoint,end_session_endpoint:t.end_session_endpoint,revocation_endpoint:t.revocation_endpoint,token_endpoint:t.token_endpoint,userinfo_endpoint:t.userinfo_endpoint,check_session_iframe:t.check_session_iframe,issuer:t.issuer});const i=await It(this.configuration,this.configurationName)?window.sessionStorage:null;return await B0(this.getFetch())(e,this.configuration.authority_time_cache_wellknowurl_in_second??60*60,i,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=r(),this.initPromise.finally(()=>{this.initPromise=null})}async tryKeepExistingSessionAsync(){return this.tryKeepExistingSessionPromise!==null?this.tryKeepExistingSessionPromise:(this.tryKeepExistingSessionPromise=J0(this),this.tryKeepExistingSessionPromise.finally(()=>{this.tryKeepExistingSessionPromise=null}))}async startCheckSessionAsync(e,t,r,i=!1){await H0(this,ar,this.configuration)(e,t,r,i)}async loginAsync(e=void 0,t=null,r=!1,i=void 0,s=!1){return this.logoutPromise&&await this.logoutPromise,this.loginPromise!==null?this.loginPromise:(s?this.loginPromise=V0(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,i):this.loginPromise=Y0(this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this),this.location)(e,t,r,i),this.loginPromise.finally(()=>{this.loginPromise=null}))}async loginCallbackAsync(e=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;const t=async()=>{const r=await Q0(this)(e),i=r.tokens;return this.tokens=i,await It(this.configuration,this.configurationName)||Nt(this.configurationName,this.configuration.storage).setTokens(i),this.publishEvent(py.eventNames.token_acquired,i),this.configuration.preload_user_info&&await this.userInfoAsync(),{parsedTokens:i,state:r.state,callbackPath:r.callbackPath,scope:r.scope,extras:r.extras}};return this.loginCallbackPromise=t(),this.loginCallbackPromise.finally(()=>{this.loginCallbackPromise=null})}async generateDemonstrationOfProofOfPossessionAsync(e,t,r,i={}){const s=this.configuration,l={ath:await yf(e),...i};if(await It(s,this.configurationName))return`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${this.configurationName}#tabId=${ff(this.configurationName)}`;const c=Nt(this.configurationName,s.storage),u=await c.getDemonstratingProofOfPossessionJwkAsync(),d=c.getDemonstratingProofOfPossessionNonce();return d&&(l.nonce=d),await mf(window)(s.demonstrating_proof_of_possession_configuration)(u,r,t,l)}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise!==null?this.loginCallbackWithAutoTokensRenewPromise:(this.loginCallbackWithAutoTokensRenewPromise=r_(this),this.loginCallbackWithAutoTokensRenewPromise.finally(()=>{this.loginCallbackWithAutoTokensRenewPromise=null}))}userInfoAsync(e=!1,t=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=t_(this)(e,t),this.userInfoPromise.finally(()=>{this.userInfoPromise=null}))}async renewTokensAsync(e=null,t=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(this.timeoutId)return Br.clearTimeout(this.timeoutId),this.renewTokensPromise=vf(this,!0,e,t),this.renewTokensPromise.finally(()=>{this.renewTokensPromise=null})}async destroyAsync(e){return await Z0(this)(e)}async logoutSameTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(ae.logout_from_same_tab,{mmessage:"SessionMonitor",sub:t}))}async logoutOtherTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(ae.logout_from_another_tab,{message:"SessionMonitor",sub:t}))}async logoutAsync(e=void 0,t=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=e_(this,ar,this.getFetch(),console,this.location)(e,t),this.logoutPromise.finally(()=>{this.logoutPromise=null}))}};Nl.getOrCreate=(n,e)=>(t,r="default")=>n_(n,e)(t,r),Nl.eventNames=ae;let mn=Nl;const ks=class my{constructor(e){this._oidc=e}subscribeEvents(e){return this._oidc.subscribeEvents(e)}removeEventSubscription(e){this._oidc.removeEventSubscription(e)}publishEvent(e,t){this._oidc.publishEvent(e,t)}static get(e="default"){return new my(mn.get(e))}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(e=void 0,t=null,r=!1,i=void 0,s=!1){return this._oidc.loginAsync(e,t,r,i,s)}logoutAsync(e=void 0,t=null){return this._oidc.logoutAsync(e,t)}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(e=null,t=null){return this._oidc.renewTokensAsync(e,t)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async generateDemonstrationOfProofOfPossessionAsync(e,t,r,i={}){return this._oidc.generateDemonstrationOfProofOfPossessionAsync(e,t,r,i)}async getValidTokenAsync(e=200,t=50){const r=this._oidc,i={getTokens:()=>r.tokens,configuration:{token_automatic_renew_mode:r.configuration.token_automatic_renew_mode,refresh_time_before_tokens_expiration_in_second:r.configuration.refresh_time_before_tokens_expiration_in_second},renewTokensAsync:r.renewTokensAsync.bind(r)};return sf(i,e,t)}fetchWithTokens(e,t=!1){return kf(e,this._oidc,t)}async userInfoAsync(e=!1,t=!1){return this._oidc.userInfoAsync(e,t)}userInfo(){return this._oidc.userInfo}};ks.getOrCreate=(n,e=new Dr)=>(t,r="default")=>new ks(mn.getOrCreate(n,e)(t,r)),ks.eventNames=mn.eventNames;let me=ks;const Ef=()=>Y.jsx("div",{className:"oidc-authenticating",children:Y.jsxs("div",{className:"oidc-authenticating__container",children:[Y.jsx("h1",{className:"oidc-authenticating__title",children:"Error authentication"}),Y.jsx("p",{className:"oidc-authenticating__content",children:"An error occurred during authentication."})]})}),s_=()=>Y.jsx("div",{className:"oidc-authenticating",children:Y.jsxs("div",{className:"oidc-authenticating__container",children:[Y.jsx("h1",{className:"oidc-authenticating__title",children:"Authentication in progress"}),Y.jsx("p",{className:"oidc-authenticating__content",children:"You will be redirected to the login page."})]})}),o_=()=>Math.random().toString(36).slice(2,8),l_=(n,e)=>(t,r)=>{if(typeof n.CustomEvent=="function")return new n.CustomEvent(t,r);const i=r||{bubbles:!1,cancelable:!1,detail:void 0},s=e.createEvent("CustomEvent");return s.initCustomEvent(t,i.bubbles,i.cancelable,i.detail),s.prototype=n.Event.prototype,s},a_=(n,e,t)=>({replaceState:(r,i)=>{const s=t(),l=i||n.history.state;n.history.replaceState({key:s,state:l},null,r),n.dispatchEvent(e("popstate"))}}),c_=()=>a_(window,l_(window,document),o_),Tf=()=>Y.jsx("div",{className:"oidc-callback",children:Y.jsxs("div",{className:"oidc-callback__container",children:[Y.jsx("h1",{className:"oidc-callback__title",children:"Authentication complete"}),Y.jsx("p",{className:"oidc-callback__content",children:"You will be redirected to your application."})]})}),u_=({callBackError:n,callBackSuccess:e,configurationName:t,withCustomHistory:r})=>{const[i,s]=K.useState(!1);K.useEffect(()=>{let u=!0;return(async()=>{const d=me.get;try{const{callbackPath:h}=await d(t).loginCallbackAsync();(r?r():c_()).replaceState(h||"/")}catch(h){u&&(console.warn(h),s(!0))}})(),()=>{u=!1}},[]);const l=n||Ef,c=e||Tf;return i?Y.jsx(l,{configurationName:t}):Y.jsx(c,{configurationName:t})},f_=()=>Y.jsx("span",{className:"oidc-loading",children:"Loading"}),d_=()=>Y.jsx("div",{className:"oidc-serviceworker",children:Y.jsxs("div",{className:"oidc-serviceworker__container",children:[Y.jsx("h1",{className:"oidc-serviceworker__title",children:"Unable to authenticate on this browser"}),Y.jsx("p",{className:"oidc-serviceworker__content",children:"Your browser is not secure enough to make authentication work. Try updating your browser or use a newer browser."})]})}),h_=()=>Y.jsx("div",{className:"oidc-session-lost",children:Y.jsxs("div",{className:"oidc-session-lost__container",children:[Y.jsx("h1",{className:"oidc-session-lost__title",children:"Session timed out"}),Y.jsx("p",{className:"oidc-session-lost__content",children:"Your session has expired. Please re-authenticate."})]})}),p_=({configurationName:n})=>(K.useEffect(()=>{(async()=>{me.get(n).silentLoginCallbackAsync()})().catch(e=>{console.error("Error during silent login callback:",e)})},[n]),null),m_=({configurationName:n})=>{const e=Ss(window.location.href),t=me.get,r=t(n);let i=null;for(const[s,l]of Object.entries(e))s==="state"||s==="scope"||(i===null&&(i={}),i[s]=l);return K.useEffect(()=>{r.tokens||r.loginAsync(null,i,!0,e.scope)},[]),Y.jsx(Y.Fragment,{})},g_=({callbackErrorComponent:n,callbackSuccessComponent:e,redirect_uri:t,silent_redirect_uri:r,silent_login_uri:i,children:s,configurationName:l,withCustomHistory:c=null})=>{const u=window?xi(window.location.href):"",[d,h]=K.useState(u);K.useEffect(()=>{const g=()=>h(xi(window.location.href));return g(),window.addEventListener("popstate",g,!1),()=>window.removeEventListener("popstate",g,!1)},[]);const p=xi(t);if(r&&d===xi(r))return Y.jsx(p_,{configurationName:l});if(i&&d===xi(i))return Y.jsx(m_,{configurationName:l});switch(d){case p:return Y.jsx(u_,{callBackError:n,callBackSuccess:e,configurationName:l,withCustomHistory:c});default:return Y.jsx(Y.Fragment,{children:s})}},y_=K.memo(g_),Of={name:"",data:null},__=({loadingComponent:n,children:e,configurationName:t})=>{const[r,i]=K.useState(!0),s=me.get,l=s(t);return K.useEffect(()=>{let c=!0;return l&&l.tryKeepExistingSessionAsync().then(()=>{c&&i(!1)}),()=>{c=!1}},[t]),Y.jsx(Y.Fragment,{children:r?Y.jsx(n,{configurationName:t}):Y.jsx(Y.Fragment,{children:e})})},Ei=({isLoading:n,loadingComponent:e,children:t,configurationName:r})=>{const i=e;return n?Y.jsx(i,{configurationName:r,children:t}):Y.jsx(Y.Fragment,{children:t})},b_=({children:n,configuration:e,configurationName:t="default",callbackSuccessComponent:r=Tf,authenticatingComponent:i=s_,loadingComponent:s=f_,serviceWorkerNotSupportedComponent:l=d_,authenticatingErrorComponent:c=Ef,sessionLostComponent:u=h_,onSessionLost:d=null,onLogoutFromAnotherTab:h=null,onLogoutFromSameTab:p=null,withCustomHistory:g=null,onEvent:y=null,getFetch:_=null,location:S=null})=>{const k=(Ke="default")=>me.getOrCreate(_??xf,S??new Dr)(e,Ke),[A,P]=K.useState(!0),[L,B]=K.useState(Of),[W,z]=K.useState("default");K.useEffect(()=>{const Ke=k(t).subscribeEvents((Me,ft)=>{y&&y(t,Me,ft)});return()=>{k(t).removeEventSubscription(Ke)}},[t,y]),K.useEffect(()=>{const Ke=k(t).subscribeEvents((Me,ft)=>{if(Me===me.eventNames.refreshTokensAsync_error||Me===me.eventNames.syncTokensAsync_error){if(d!=null){d();return}B({name:Me,data:ft})}else if(Me===me.eventNames.logout_from_another_tab){if(h!=null){h();return}B({name:Me,data:ft})}else Me===me.eventNames.logout_from_same_tab?p!=null&&p():Me===me.eventNames.loginAsync_begin||Me===me.eventNames.loginCallbackAsync_end||Me===me.eventNames.loginAsync_error||Me===me.eventNames.loginCallbackAsync_error?B({name:Me,data:ft}):Me===me.eventNames.service_worker_not_supported_by_browser&&e.service_worker_only===!0&&B({name:Me,data:ft})});return z(t),P(!1),()=>{k(t).removeEventSubscription(Ke),B(Of)}},[e,t]);const J=u,j=i,V=s,ne=l,ve=c,Le=A||W!==t,_t=k(t);switch(L.name){case me.eventNames.service_worker_not_supported_by_browser:return Y.jsx(Ei,{loadingComponent:V,isLoading:Le,configurationName:t,children:Y.jsx(ne,{configurationName:t})});case me.eventNames.loginAsync_begin:return Y.jsx(Ei,{loadingComponent:V,isLoading:Le,configurationName:t,children:Y.jsx(j,{configurationName:t})});case me.eventNames.loginAsync_error:case me.eventNames.loginCallbackAsync_error:return Y.jsx(Ei,{loadingComponent:V,isLoading:Le,configurationName:t,children:Y.jsx(ve,{configurationName:t})});case me.eventNames.refreshTokensAsync_error:case me.eventNames.syncTokensAsync_error:case me.eventNames.logout_from_another_tab:return Y.jsx(Ei,{loadingComponent:V,isLoading:Le,configurationName:t,children:Y.jsx(J,{configurationName:t})});default:return Y.jsx(Ei,{loadingComponent:V,isLoading:Le,configurationName:t,children:Y.jsx(y_,{redirect_uri:_t.configuration.redirect_uri,silent_redirect_uri:_t.configuration.silent_redirect_uri,silent_login_uri:_t.configuration.silent_login_uri,callbackSuccessComponent:r,callbackErrorComponent:c,authenticatingComponent:i,configurationName:t,withCustomHistory:g,location:S??new Dr,children:Y.jsx(__,{loadingComponent:V,configurationName:t,children:n})})})}},Af="default",Il=(n,e)=>{let t=!1;return n(e)&&(t=n(e).tokens!=null),t},v_=(n=Af)=>{const e=me.get,[t,r]=K.useState(Il(e,n));return K.useEffect(()=>{let i=!0;const s=e(n);r(Il(e,n));const l=s.subscribeEvents((c,u)=>{(c===me.eventNames.logout_from_another_tab||c===me.eventNames.logout_from_same_tab||c===me.eventNames.token_acquired)&&i&&r(Il(e,n))});return()=>{i=!1,s.removeEventSubscription(l)}},[n]),{login:(i=void 0,s=void 0,l=!1,c=void 0)=>e(n).loginAsync(i,s,!1,c,l),logout:(i=void 0,s=void 0)=>e(n).logoutAsync(i,s),renewTokens:async(i=void 0)=>{const s=await e(n).renewTokensAsync(i);return{accessToken:s.accessToken,accessTokenPayload:s.accessTokenPayload,idToken:s.idToken,idTokenPayload:s.idTokenPayload}},isAuthenticated:t}},Cf={accessToken:null,accessTokenPayload:null},w_=n=>{const e=me.get,t=e(n);if(t.tokens){const r=t.tokens;return{accessToken:r.accessToken,accessTokenPayload:r.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:t.configuration.demonstrating_proof_of_possession?(i,s)=>t.generateDemonstrationOfProofOfPossessionAsync(r.accessToken,i,s):null}}return Cf};function S_(n,e){return n.configuration.demonstrating_proof_of_possession?(t,r,i={})=>n.generateDemonstrationOfProofOfPossessionAsync(e.accessToken,t,r,i):null}const k_=(n=Af)=>{const e=me.get,[t,r]=K.useState(w_(n));return K.useEffect(()=>{let i=!0;const s=e(n);if(s.tokens){const c=s.tokens;r({accessToken:c.accessToken,accessTokenPayload:c.accessTokenPayload})}const l=s.subscribeEvents((c,u)=>{if((c===me.eventNames.token_renewed||c===me.eventNames.token_acquired||c===me.eventNames.logout_from_another_tab||c===me.eventNames.logout_from_same_tab||c===me.eventNames.refreshTokensAsync_error||c===me.eventNames.syncTokensAsync_error)&&i){const d=s.tokens;r(d!=null?{accessToken:d.accessToken,accessTokenPayload:d.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:S_(s,d)}:Cf)}});return()=>{i=!1,s.removeEventSubscription(l)}},[n]),t},Mf=K.createContext({}),zr=()=>{const n=K.useContext(Mf);if(!n)throw new Error("useWellPlayed must be used within a WellPlayedProvider");return n},x_=({children:n,clientConfig:e,organizationId:t,apiBaseUrl:r,typedClientConfig:i})=>{const s=k_(),l=K.useMemo(()=>sr.createWellPlayedClient({token:(s==null?void 0:s.accessToken)??void 0,organizationId:t,...e,apiBaseUrl:r}),[s==null?void 0:s.accessToken,t,e,r]);return Y.jsx(Ky,{client:l,children:Y.jsx(Mf.Provider,{value:{organizationId:t,apiClient:l,typedClient:sr.createTypedClient({apiBaseUrl:r,organizationId:t,token:(s==null?void 0:s.accessToken)??void 0,...i}),accessToken:(s==null?void 0:s.accessToken)??void 0},children:n})})},E_=({children:n,oidcConfig:e,wpAppConfig:t,...r})=>Y.jsx(b_,{...e,configuration:{...t,...e==null?void 0:e.configuration,authority:`https://oauth.warrior.${r.apiBaseUrl??"well-played.gg"}`},children:Y.jsx(x_,{...r,children:n})}),T_=(n,e)=>{const{apiClient:t}=zr(),{data:r,loading:i,refetch:s,fetchMore:l}=gl(n,{...e,notifyOnNetworkStatusChange:!0,variables:{...e==null?void 0:e.variables,page:{first:(e==null?void 0:e.pageSize)??100}},client:t}),c=n.definitions[0].selectionSet.selections[0].name.value;return{data:r,loading:i,loadNextPage:u=>{const d=r==null?void 0:r[c];if(d!=null&&d.pageInfo.hasNextPage)return s({...e==null?void 0:e.variables,...u,page:{first:(e==null?void 0:e.pageSize)??100,after:d.pageInfo.endCursor}})},loadNextPageWithoutAppendingOldData:u=>{const d=r==null?void 0:r[c];return l({variables:{...e==null?void 0:e.variables,...u,page:{first:(e==null?void 0:e.pageSize)??100,after:d==null?void 0:d.pageInfo.endCursor}}})}}},Pl=(n,e)=>{const[t,r]=K.useState(!(e!=null&&e.skip)),[i,s]=K.useState([]),{apiClient:l}=zr(),[c]=Xu(n,{...e,client:l}),u=async d=>{var _;const h=n.definitions[0].selectionSet.selections[0].name.value;r(!0);let p=!0,g=null;const y=[];for(;p;){const{data:S,error:k}=await c({variables:{...e==null?void 0:e.variables,...d,page:{first:100,after:g}}});if(k)throw k;const A=S==null?void 0:S[h];A&&(y.push(...A.nodes??[]),p=A.pageInfo.hasNextPage,g=A.pageInfo.endCursor)}return s(y),(_=e==null?void 0:e.onResults)==null||_.call(e,y),r(!1),y};return K.useEffect(()=>{e!=null&&e.skip||u()},[e==null?void 0:e.skip]),{loading:t,results:i,refetch:u}},O_=sr.graphql(`
|
|
25
25
|
query players(
|
|
26
26
|
$ids: [ID!]!
|
|
27
27
|
$page: PageInfo!
|