1import{j as y}from"./jsx-runtime-u17CrQMm.js";import{A as M,u as J,a as S,W as A}from"./session.constants-DFrvAGqM.js";import{r as d,u as K,a as Z,c as B}from"./chunk-BV7QT456-BoE4PqLr.js";import{i as G,c as V,f as v}from"./client-logger-N-YHYd0z.js";const X=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Y=["/error","/healthz","/contact-us/entry","/winner/verification","/wheel-watchers/unsubscribe","/wheel-watchers/edit-profile/user-get-profile","/wheel-watchers/edit-profile/user-update-profile","/sitemap.xml"],Q=["/wheel-watchers/auth"],ee=[/^\/sitemap-[^/]+\.xml$/i,/^\/win\/[^/]+\/entry(?:-multiple)?\/?$/i],q=e=>e==="/ca"||e.startsWith("/ca/")?"en-ca":"en",U=e=>e==="/ca"||e.startsWith("/ca/"),te=e=>e==="en-ca"?"/ca":"",re=e=>e==="/"?"/":(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,""),ne=e=>{const r=re(e);return Y.some(a=>r===a)||Q.some(a=>r===a||r.startsWith(`${a}/`))||ee.some(a=>a.test(r))};function me(e,r){if(!e)return null;if(X.test(e)||e.startsWith("#")||e.startsWith("?"))return e;const a=e.match(/^([^?#]*)(\?[^#]*)?(#.*)?$/),n=a?.[1]||"/",o=a?.[2]||"",s=a?.[3]||"";return n.startsWith("/")?ne(n)?`${n}${o}${s}`:r==="en-ca"?U(n)?`${n}${o}${s}`:n==="/"?`/ca/${o}${s}`:`/ca${n}${o}${s}`:U(n)?`${n.replace(/^\/ca(?=\/|$)/,"")||"/"}${o}${s}`:`${n}${o}${s}`:e}const t=V("auth");function oe(e){if(!e||typeof e!="string")return null;const r=e.split(".");if(r.length<2)return{type:"opaque",fingerprint:v(e)};try{const a=JSON.parse(atob(r[0].replace(/-/g,"+").replace(/_/g,"/"))),n=JSON.parse(atob(r[1].replace(/-/g,"+").replace(/_/g,"/"))),o=typeof n.exp=="number"?new Date(n.exp*1e3).toISOString():void 0,s=typeof n.iat=="number"?new Date(n.iat*1e3).toISOString():void 0,l=typeof n.scope=="string"?n.scope:void 0;return{type:"JWT",fingerprint:v(e),header:{alg:a?.alg,typ:a?.typ},claims:{sub:n?.sub,aud:n?.aud,scope:l,iat:s,exp:o}}}catch{return{type:"unknown",fingerprint:v(e)}}}function ae(e){return typeof e=="string"?v(e):e}function D(e,r){t.group(`token: ${e}`),t.debug("summary:",oe(r)),t.groupEnd()}function se(){t.group("localStorage hints");try{const e=localStorage.getItem(A),r=localStorage.getItem(S),a=localStorage.getItem("auth0_redirect_url");t.debug({[A]:e?"(present)":"(missing)",[S]:r==="1"?"1":r??"(missing)",auth0_redirect_url:a??"(missing)"})}catch(e){t.warn("Unable to read localStorage hints:",e)}t.groupEnd()}function ce(e){t.info(`${e}: HttpOnly session cookie is NOT readable in JS (by design). Assuming set on SSR success.`)}const H=d.createContext({saveCurrentUrlToStorage:()=>{},getCallbackUrl:()=>""});function we(){return d.useContext(H)}const ie=["/wheel-watchers/login","/wheel-watchers/logout","/wheel-watchers/register","/wheel-watchers/welcome","/ca/wheel-watchers/login","/ca/wheel-watchers/logout","/ca/wheel-watchers/register","/ca/wheel-watchers/welcome"];function x(){return typeof window>"u"?"en":q(window.location.pathname)}function C(e){return(e??x())==="en-ca"?"/ca/":"/"}function O(e,r){const a=r??x(),n=te(a);return`${e}${n}/wheel-watchers/welcome`}function I(e){return ie.includes(e)}function Se(e){if(!e||typeof e!="string"||!e.startsWith("/")||e.startsWith("//"))return null;const r=e.split("?")[0].split("#")[0];return I(r)?null:e}function le(){const e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function z(){if(!(typeof window>"u")&&!localStorage.getItem("auth0_redirect_url")){const e=window.location.pathname+window.location.search+window.location.hash;localStorage.setItem("auth0_redirect_url",e),t.debug("Stashed return-to (if missing):",e)}}function ue(e,r){const a=C(r);if(!e)return a;try{const n=new URL(e,window.location.origin);return n.pathname.endsWith("/welcome")||I(n.pathname)?a:n.pathname+(n.search||"")+(n.hash||"")||a}catch{const n=e.split("?")[0].split("#")[0];return I(n)?a:e||a}}function j(e){const r=["openid","profile","email"],a=(e??"").split(/\s+/).filter(Boolean);return Array.from(new Set([...r,...a])).join(" ")}async function F(e,r,a,n){try{t.group(`ð§© ${n}: cache-first`),t.debug('Trying getAccessTokenSilently({ cacheMode: "cache-only" })â¦');const o=await e({authorizationParams:{audience:r,scope:a},cacheMode:"cache-only",detailedResponse:!1});if(!o)throw{error:"no_token"};return D("accessToken (cache)",o),t.groupEnd(),o}catch(o){const s=o?.error||o?.code||o?.message||"";t.debug("Cache-only miss; falling back to normal silent call:",s)}try{t.group(`ð§© ${n}: fallback â normal silent`);const o=await e({authorizationParams:{audience:r,scope:a},detailedResponse:!1});if(!o)throw{error:"no_token"};return D("accessToken (silent)",o),t.groupEnd(),o}catch(o){throw t.groupEnd(),o}}function de({auth0Config:e,children:r}){const a=K(),n=Z(),o=B(),{isLoading:s,isAuthenticated:l,getAccessTokenSilently:m,loginWithRedirect:p,logout:E}=J(),u=d.useRef(!1),W=d.useRef(!1),b=new URLSearchParams(n.search),k=b.has("code"),T=b.has("state"),R=b.has("error"),P=b.has("error_description"),$=k&&T||R&&P;d.useEffect(()=>{t.group("ð Route state"),t.debug("location.pathname:",n.pathname),t.debug("query:",Object.fromEntries(b.entries())),t.debug("isRealCallback:",$,"| hasCode:",k,"| hasState:",T,"| hasError:",R,"| hasErrorDescription:",P),t.debug("Auth0 SDK:",{isLoading:s,isAuthenticated:l}),se(),t.groupEnd()},[n.pathname,n.search,s,l]);const L=()=>{const i=le(),c=x(),h=`${O(e.feDomain,c)}?state=error&code=${i}`;t.warn("Logout â error page",{errorUrl:h,correlation:i,langcode:c});try{localStorage.removeItem(A),localStorage.removeItem(S),t.debug("Cleared client hints (CSRF + exchanged flag).")}catch{}E({logoutParams:{returnTo:h}})},w=j(e.scope)??"openid profile email offline_access";return d.useEffect(()=>{$&&(R||P||s||l&&localStorage.getItem(S)!=="1"&&(u.current||o.state!=="idle"||(u.current=!0,t.group("ð¦ Exchange start (callback flow)"),t.debug("Attempting access token acquisition (cache-first)â¦"),(async()=>
1{try{const i=await F(m,e.audience,w,"callback flow");t.debug("POST /wheel-watchers/auth/user-session (via fetcher.submit)â¦"),o.submit({token:i},{method:"POST",action:"/wheel-watchers/auth/user-session"}),t.groupEnd()}catch(i){const c=i?.error||i?.code||i?.message||"";if(c==="consent_required"||c==="login_required"||c==="missing_scope"||c==="interaction_required"||c==="no_token"){t.warn("Token acquisition requires interaction:",c),z(),await p({authorizationParams:{audience:e.audience,scope:w,prompt:"consent"}});return}t.error("Token acquisition failed (unrecoverable):",c,i),L()}})())))},[$,R,P,s,l,o.state,m,p,w]),d.useEffect(()=>{if(o.state!=="idle"||!o.data)return;const i=Array.isArray(o.data)?o.data[0]:o.data||{},c=!!i.ok,h=i.csrf;if(t.group("ð¬ Exchange response handled"),t.debug("fetcher.data (shape normalized):",{ok:c,csrf:h?"(present)":"(missing)"}),c&&h){try{localStorage.setItem(A,h),localStorage.setItem(S,"1"),t.debug('Stored CSRF + marked "exchanged" hint.')}catch(N){t.warn("Could not write localStorage hints:",N)}const g=localStorage.getItem("auth0_redirect_url");g&&(t.debug("Using stored return URL (then removing it):",g),localStorage.removeItem("auth0_redirect_url"));const f=q(n.pathname),_=ue(g,f);ce("SSR session established"),t.debug("Navigating to target:",_),a(_,{replace:!0}),setTimeout(()=>{(window.location.pathname.endsWith("/welcome")||window.location.search.includes("code=")||window.location.search.includes("state=error"))&&(t.warn("Soft navigate didnât stick; performing hard redirect to:",_),window.location.replace(_))},80),t.groupEnd();return}t.error("Exchange failed; logging out to error page."),t.groupEnd(),L()},[o.state,o.data,a]),d.useEffect(()=>{if(typeof window>"u"||s||!l||W.current)return;const i=window.location.pathname.endsWith("/wheel-watchers/welcome"),c=!k&&!T,h=localStorage.getItem(S)!=="1";i&&c&&h&&o.state==="idle"&&(W.current=!0,t.group("ð Second-try guard (stuck on /welcome)"),t.debug("Attempting one-time cache-first silent re-exchangeâ¦"),(async()=>{try{const g=await F(m,e.audience,w,"second-try guard");t.debug("Re-POST /wheel-watchers/auth/user-sessionâ¦"),o.submit({token:g},{method:"POST",action:"/wheel-watchers/auth/user-session"}),t.groupEnd()}catch(g){const f=g?.error||g?.code||g?.message||"";if(f==="consent_required"||f==="login_required"||f==="missing_scope"||f==="interaction_required"||f==="no_token"){t.warn("Second-try requires interaction:",f),z(),await p({authorizationParams:{audience:e.audience,scope:w,prompt:"consent"}});return}t.error("Second-try unrecoverable; navigating home to avoid trap.",f),a(C(),{replace:!0})}})())},[s,l,o.state,m,p,a,k,T,w]),y.jsx(y.Fragment,{children:r})}function be({children:e,auth0Config:r}){const[a,n]=d.useState(!1);d.useEffect(()=>{n(!0),t.info("Auth0ClientProviderWrapper mounted (client).")},[]);const o=()=>{if(typeof window<"u"){let u=window.location.pathname+window.location.search+window.location.hash;I(window.location.pathname)&&(u=C()),localStorage.setItem("auth0_redirect_url",u),t.debug("saveCurrentUrlToStorage() set auth0_redirect_url:",u)}},s=u=>O(r.feDomain,u),l=u=>{t.debug("onRedirectCallback invoked (no-op by design).")},m={saveCurrentUrlToStorage:a?o:()=>{},getCallbackUrl:a?s:u=>O(r.feDomain,u)},p=j(r.scope)??"openid profile email offline_access",E=O(r.feDomain);return G("auth")&&(t.group("âï¸ Auth0Provider config"),t.debug({domain:r.domain,clientId:ae(r.clientId),feDomain:r.feDomain,audience:r.audience,scope:p,redirect_uri:E,tokenCaching:"localstorage (per cacheLocation) with refresh tokens enabled",refreshTokens:{useRefreshTokens:!0,useRefreshTokensFallback:!0}}),t.groupEnd()),y.jsx(H.Provider,{value:m,children:a?y.jsx(M,{domain:r.domain,clientId:r.clientId,authorizationParams:{redirect_uri:E,audience:r.audience,scope:p},onRedirectCallback:l,cacheLocation:"localstorage",useRefreshTokens:!0,useRefreshTokensFallback:!0,children:y.jsx(de,{auth0Config:r,children:e})}):e})}export{be as A,C as a,q as g,me as l,we as u,Se as v};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.