@chemmangat/msal-next 3.0.0 → 3.0.2

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.mts CHANGED
@@ -350,6 +350,34 @@ declare class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryS
350
350
  render(): ReactNode;
351
351
  }
352
352
 
353
+ /**
354
+ * Pre-configured Providers component for Next.js App Router layouts.
355
+ * This component is already marked as 'use client', so you can use it directly
356
+ * in your server-side layout.tsx without needing to create a separate client component.
357
+ *
358
+ * @example
359
+ * ```tsx
360
+ * // app/layout.tsx
361
+ * import { Providers } from '@chemmangat/msal-next'
362
+ *
363
+ * export default function RootLayout({ children }) {
364
+ * return (
365
+ * <html lang="en">
366
+ * <body>
367
+ * <Providers
368
+ * clientId={process.env.NEXT_PUBLIC_AZURE_AD_CLIENT_ID!}
369
+ * tenantId={process.env.NEXT_PUBLIC_AZURE_AD_TENANT_ID!}
370
+ * >
371
+ * {children}
372
+ * </Providers>
373
+ * </body>
374
+ * </html>
375
+ * )
376
+ * }
377
+ * ```
378
+ */
379
+ declare function Providers({ children, ...props }: MsalAuthProviderProps): react_jsx_runtime.JSX.Element;
380
+
353
381
  interface UseMsalAuthReturn {
354
382
  /**
355
383
  * Current authenticated account
@@ -903,4 +931,4 @@ interface ServerSession {
903
931
  accessToken?: string;
904
932
  }
905
933
 
906
- export { AuthGuard, type AuthGuardProps, type AuthMiddlewareConfig, AuthStatus, type AuthStatusProps, type CustomTokenClaims, type DebugLoggerConfig, ErrorBoundary, type ErrorBoundaryProps, type GraphApiOptions, MicrosoftSignInButton, type MicrosoftSignInButtonProps, type MsalAuthConfig, MsalAuthProvider, type MsalAuthProviderProps, type RetryConfig, type ServerSession, SignOutButton, type SignOutButtonProps, type UseGraphApiReturn, type UseMsalAuthReturn, type UseRolesReturn, type UseUserProfileReturn, UserAvatar, type UserAvatarProps, type UserProfile, type ValidatedAccountData, type WithAuthOptions, createAuthMiddleware, createMsalConfig, createRetryWrapper, createScopedLogger, getDebugLogger, getMsalInstance, isValidAccountData, isValidRedirectUri, isValidScope, retryWithBackoff, safeJsonParse, sanitizeError, useGraphApi, useMsalAuth, useRoles, useUserProfile, validateScopes, withAuth };
934
+ export { AuthGuard, type AuthGuardProps, type AuthMiddlewareConfig, AuthStatus, type AuthStatusProps, type CustomTokenClaims, type DebugLoggerConfig, ErrorBoundary, type ErrorBoundaryProps, type GraphApiOptions, MicrosoftSignInButton, type MicrosoftSignInButtonProps, type MsalAuthConfig, MsalAuthProvider, type MsalAuthProviderProps, Providers, type RetryConfig, type ServerSession, SignOutButton, type SignOutButtonProps, type UseGraphApiReturn, type UseMsalAuthReturn, type UseRolesReturn, type UseUserProfileReturn, UserAvatar, type UserAvatarProps, type UserProfile, type ValidatedAccountData, type WithAuthOptions, createAuthMiddleware, createMsalConfig, createRetryWrapper, createScopedLogger, getDebugLogger, getMsalInstance, isValidAccountData, isValidRedirectUri, isValidScope, retryWithBackoff, safeJsonParse, sanitizeError, useGraphApi, useMsalAuth, useRoles, useUserProfile, validateScopes, withAuth };
package/dist/index.d.ts CHANGED
@@ -350,6 +350,34 @@ declare class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryS
350
350
  render(): ReactNode;
351
351
  }
352
352
 
353
+ /**
354
+ * Pre-configured Providers component for Next.js App Router layouts.
355
+ * This component is already marked as 'use client', so you can use it directly
356
+ * in your server-side layout.tsx without needing to create a separate client component.
357
+ *
358
+ * @example
359
+ * ```tsx
360
+ * // app/layout.tsx
361
+ * import { Providers } from '@chemmangat/msal-next'
362
+ *
363
+ * export default function RootLayout({ children }) {
364
+ * return (
365
+ * <html lang="en">
366
+ * <body>
367
+ * <Providers
368
+ * clientId={process.env.NEXT_PUBLIC_AZURE_AD_CLIENT_ID!}
369
+ * tenantId={process.env.NEXT_PUBLIC_AZURE_AD_TENANT_ID!}
370
+ * >
371
+ * {children}
372
+ * </Providers>
373
+ * </body>
374
+ * </html>
375
+ * )
376
+ * }
377
+ * ```
378
+ */
379
+ declare function Providers({ children, ...props }: MsalAuthProviderProps): react_jsx_runtime.JSX.Element;
380
+
353
381
  interface UseMsalAuthReturn {
354
382
  /**
355
383
  * Current authenticated account
@@ -903,4 +931,4 @@ interface ServerSession {
903
931
  accessToken?: string;
904
932
  }
905
933
 
906
- export { AuthGuard, type AuthGuardProps, type AuthMiddlewareConfig, AuthStatus, type AuthStatusProps, type CustomTokenClaims, type DebugLoggerConfig, ErrorBoundary, type ErrorBoundaryProps, type GraphApiOptions, MicrosoftSignInButton, type MicrosoftSignInButtonProps, type MsalAuthConfig, MsalAuthProvider, type MsalAuthProviderProps, type RetryConfig, type ServerSession, SignOutButton, type SignOutButtonProps, type UseGraphApiReturn, type UseMsalAuthReturn, type UseRolesReturn, type UseUserProfileReturn, UserAvatar, type UserAvatarProps, type UserProfile, type ValidatedAccountData, type WithAuthOptions, createAuthMiddleware, createMsalConfig, createRetryWrapper, createScopedLogger, getDebugLogger, getMsalInstance, isValidAccountData, isValidRedirectUri, isValidScope, retryWithBackoff, safeJsonParse, sanitizeError, useGraphApi, useMsalAuth, useRoles, useUserProfile, validateScopes, withAuth };
934
+ export { AuthGuard, type AuthGuardProps, type AuthMiddlewareConfig, AuthStatus, type AuthStatusProps, type CustomTokenClaims, type DebugLoggerConfig, ErrorBoundary, type ErrorBoundaryProps, type GraphApiOptions, MicrosoftSignInButton, type MicrosoftSignInButtonProps, type MsalAuthConfig, MsalAuthProvider, type MsalAuthProviderProps, Providers, type RetryConfig, type ServerSession, SignOutButton, type SignOutButtonProps, type UseGraphApiReturn, type UseMsalAuthReturn, type UseRolesReturn, type UseUserProfileReturn, UserAvatar, type UserAvatarProps, type UserProfile, type ValidatedAccountData, type WithAuthOptions, createAuthMiddleware, createMsalConfig, createRetryWrapper, createScopedLogger, getDebugLogger, getMsalInstance, isValidAccountData, isValidRedirectUri, isValidScope, retryWithBackoff, safeJsonParse, sanitizeError, useGraphApi, useMsalAuth, useRoles, useUserProfile, validateScopes, withAuth };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var msalReact=require('@azure/msal-react'),msalBrowser=require('@azure/msal-browser'),react=require('react'),jsxRuntime=require('react/jsx-runtime'),server=require('next/server');function z(r,e){try{let t=JSON.parse(r);return e(t)?t:(console.warn("[Validation] JSON validation failed"),null)}catch(t){return console.error("[Validation] JSON parse error:",t),null}}function B(r){return typeof r=="object"&&r!==null&&typeof r.homeAccountId=="string"&&r.homeAccountId.length>0&&typeof r.username=="string"&&r.username.length>0&&(r.name===void 0||typeof r.name=="string")}function S(r){return r instanceof Error?r.message.replace(/[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g,"[TOKEN_REDACTED]").replace(/[a-f0-9]{32,}/gi,"[SECRET_REDACTED]").replace(/Bearer\s+[^\s]+/gi,"Bearer [REDACTED]"):"An unexpected error occurred"}function G(r,e){try{let t=new URL(r);return e.some(o=>{let n=new URL(o);return t.origin===n.origin})}catch{return false}}function oe(r){return /^[a-zA-Z0-9._-]+$/.test(r)}function me(r){return Array.isArray(r)&&r.every(oe)}function H(r){if(r.msalConfig)return r.msalConfig;let{clientId:e,tenantId:t,authorityType:o="common",redirectUri:n,postLogoutRedirectUri:a,cacheLocation:d="sessionStorage",storeAuthStateInCookie:c=false,navigateToLoginRequestUrl:u=true,enableLogging:s=false,loggerCallback:h,allowedRedirectUris:p}=r;if(!e)throw new Error("@chemmangat/msal-next: clientId is required");let m=()=>{if(o==="tenant"){if(!t)throw new Error('@chemmangat/msal-next: tenantId is required when authorityType is "tenant"');return `https://login.microsoftonline.com/${t}`}return `https://login.microsoftonline.com/${o}`},g=typeof window<"u"?window.location.origin:"http://localhost:3000",y=n||g;if(p&&p.length>0){if(!G(y,p))throw new Error(`@chemmangat/msal-next: redirectUri "${y}" is not in the allowed list`);let i=a||y;if(!G(i,p))throw new Error(`@chemmangat/msal-next: postLogoutRedirectUri "${i}" is not in the allowed list`)}return {auth:{clientId:e,authority:m(),redirectUri:y,postLogoutRedirectUri:a||y,navigateToLoginRequestUrl:u},cache:{cacheLocation:d,storeAuthStateInCookie:c},system:{loggerOptions:{loggerCallback:h||((i,l,A)=>{if(!(A||!s))switch(i){case msalBrowser.LogLevel.Error:console.error("[MSAL]",l);break;case msalBrowser.LogLevel.Warning:console.warn("[MSAL]",l);break;case msalBrowser.LogLevel.Info:console.info("[MSAL]",l);break;case msalBrowser.LogLevel.Verbose:console.debug("[MSAL]",l);break}}),logLevel:s?msalBrowser.LogLevel.Verbose:msalBrowser.LogLevel.Error}}}}var ie=null;function Pe(){return ie}function ve({children:r,loadingComponent:e,onInitialized:t,...o}){let[n,a]=react.useState(null),d=react.useRef(null);return react.useEffect(()=>{if(typeof window>"u"||d.current)return;(async()=>{try{let u=H(o),s=new msalBrowser.PublicClientApplication(u);await s.initialize(),await s.handleRedirectPromise()&&o.enableLogging&&console.log("[MSAL] Redirect authentication successful");let p=o.enableLogging||!1;s.addEventCallback(m=>{if(m.eventType===msalBrowser.EventType.LOGIN_SUCCESS&&p){let g=m.payload;console.log("[MSAL] Login successful:",g.account?.username);}m.eventType===msalBrowser.EventType.LOGIN_FAILURE&&console.error("[MSAL] Login failed:",m.error),m.eventType===msalBrowser.EventType.LOGOUT_SUCCESS&&p&&console.log("[MSAL] Logout successful");}),d.current=s,ie=s,a(s),t&&t(s);}catch(u){throw console.error("[MSAL] Initialization failed:",u),u}})();},[]),typeof window>"u"?jsxRuntime.jsx(jsxRuntime.Fragment,{children:e||jsxRuntime.jsx("div",{children:"Loading authentication..."})}):n?jsxRuntime.jsx(msalReact.MsalProvider,{instance:n,children:r}):jsxRuntime.jsx(jsxRuntime.Fragment,{children:e||jsxRuntime.jsx("div",{children:"Loading authentication..."})})}var W=new Map;function b(r=["User.Read"]){let{instance:e,accounts:t,inProgress:o}=msalReact.useMsal(),n=msalReact.useAccount(t[0]||null),a=react.useRef(false),d=react.useMemo(()=>t.length>0,[t]),c=react.useCallback(async(i=r)=>{try{let l={scopes:i,prompt:"select_account"};await e.loginPopup(l);}catch(l){throw console.error("[MSAL] Login popup failed:",l),l}},[e,r]),u=react.useCallback(async(i=r)=>{try{let l={scopes:i,prompt:"select_account"};await e.loginRedirect(l);}catch(l){throw console.error("[MSAL] Login redirect failed:",l),l}},[e,r]),s=react.useCallback(async()=>{try{await e.logoutPopup({account:n||void 0});}catch(i){throw console.error("[MSAL] Logout popup failed:",i),i}},[e,n]),h=react.useCallback(async()=>{try{await e.logoutRedirect({account:n||void 0});}catch(i){throw console.error("[MSAL] Logout redirect failed:",i),i}},[e,n]),p=react.useCallback(async(i=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let l={scopes:i,account:n,forceRefresh:!1};return (await e.acquireTokenSilent(l)).accessToken}catch(l){throw console.error("[MSAL] Silent token acquisition failed:",l),l}},[e,n,r]),m=react.useCallback(async(i=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");if(a.current)throw new Error("[MSAL] Popup already in progress. Please wait.");try{a.current=!0;let l={scopes:i,account:n};return (await e.acquireTokenPopup(l)).accessToken}catch(l){throw console.error("[MSAL] Token popup acquisition failed:",l),l}finally{a.current=false;}},[e,n,r]),g=react.useCallback(async(i=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let l={scopes:i,account:n};await e.acquireTokenRedirect(l);}catch(l){throw console.error("[MSAL] Token redirect acquisition failed:",l),l}},[e,n,r]),y=react.useCallback(async(i=r)=>{let l=`${n?.homeAccountId||"anonymous"}-${i.sort().join(",")}`,A=W.get(l);if(A)return A;let v=(async()=>{try{return await p(i)}catch{return console.warn("[MSAL] Silent token acquisition failed, falling back to popup"),await m(i)}finally{W.delete(l);}})();return W.set(l,v),v},[p,m,r,n]),f=react.useCallback(async()=>{e.setActiveAccount(null),await e.clearCache();},[e]);return {account:n,accounts:t,isAuthenticated:d,inProgress:o!==msalBrowser.InteractionStatus.None,loginPopup:c,loginRedirect:u,logoutPopup:s,logoutRedirect:h,acquireToken:y,acquireTokenSilent:p,acquireTokenPopup:m,acquireTokenRedirect:g,clearSession:f}}function Le({text:r="Sign in with Microsoft",variant:e="dark",size:t="medium",useRedirect:o=false,scopes:n,className:a="",style:d,onSuccess:c,onError:u}){let{loginPopup:s,loginRedirect:h,inProgress:p}=b(),m=async()=>{try{o?await h(n):await s(n),c?.();}catch(i){u?.(i);}},g={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},f={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:p?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:p?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...g[t],...d};return jsxRuntime.jsxs("button",{onClick:m,disabled:p,className:a,style:f,"aria-label":r,children:[jsxRuntime.jsx(ke,{}),jsxRuntime.jsx("span",{children:r})]})}function ke(){return jsxRuntime.jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsxRuntime.jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsxRuntime.jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsxRuntime.jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function Ue({text:r="Sign out",variant:e="dark",size:t="medium",useRedirect:o=false,className:n="",style:a,onSuccess:d,onError:c}){let{logoutPopup:u,logoutRedirect:s,inProgress:h}=b(),p=async()=>{try{o?await s():await u(),d?.();}catch(f){c?.(f);}},m={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},y={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:h?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:h?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...m[t],...a};return jsxRuntime.jsxs("button",{onClick:p,disabled:h,className:n,style:y,"aria-label":r,children:[jsxRuntime.jsx(Me,{}),jsxRuntime.jsx("span",{children:r})]})}function Me(){return jsxRuntime.jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsxRuntime.jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsxRuntime.jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsxRuntime.jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function U(){let{acquireToken:r}=b(),e=react.useCallback(async(c,u={})=>{let{scopes:s=["User.Read"],version:h="v1.0",debug:p=false,...m}=u;try{let g=await r(s),y=`https://graph.microsoft.com/${h}`,f=c.startsWith("http")?c:`${y}${c.startsWith("/")?c:`/${c}`}`;p&&console.log("[GraphAPI] Request:",{url:f,method:m.method||"GET"});let i=await fetch(f,{...m,headers:{Authorization:`Bearer ${g}`,"Content-Type":"application/json",...m.headers}});if(!i.ok){let A=await i.text(),v=`Graph API error (${i.status}): ${A}`;throw new Error(v)}if(i.status===204||i.headers.get("content-length")==="0")return null;let l=await i.json();return p&&console.log("[GraphAPI] Response:",l),l}catch(g){let y=S(g);throw console.error("[GraphAPI] Request failed:",y),new Error(y)}},[r]),t=react.useCallback((c,u={})=>e(c,{...u,method:"GET"}),[e]),o=react.useCallback((c,u,s={})=>e(c,{...s,method:"POST",body:u?JSON.stringify(u):void 0}),[e]),n=react.useCallback((c,u,s={})=>e(c,{...s,method:"PUT",body:u?JSON.stringify(u):void 0}),[e]),a=react.useCallback((c,u,s={})=>e(c,{...s,method:"PATCH",body:u?JSON.stringify(u):void 0}),[e]),d=react.useCallback((c,u={})=>e(c,{...u,method:"DELETE"}),[e]);return {get:t,post:o,put:n,patch:a,delete:d,request:e}}var P=new Map,Fe=300*1e3,ue=100;function Ne(){if(P.size>ue){let r=Array.from(P.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,P.size-ue).forEach(([t])=>{let o=P.get(t);o?.data.photo&&URL.revokeObjectURL(o.data.photo),P.delete(t);});}}function j(){let{isAuthenticated:r,account:e}=b(),t=U(),[o,n]=react.useState(null),[a,d]=react.useState(false),[c,u]=react.useState(null),s=react.useCallback(async()=>{if(!r||!e){n(null);return}let p=e.homeAccountId,m=P.get(p);if(m&&Date.now()-m.timestamp<Fe){n(m.data);return}d(true),u(null);try{let g=await t.get("/me",{scopes:["User.Read"]}),y;try{let i=await t.get("/me/photo/$value",{scopes:["User.Read"],headers:{"Content-Type":"image/jpeg"}});i&&(y=URL.createObjectURL(i));}catch{console.debug("[UserProfile] Photo not available");}let f={id:g.id,displayName:g.displayName,givenName:g.givenName,surname:g.surname,userPrincipalName:g.userPrincipalName,mail:g.mail,jobTitle:g.jobTitle,officeLocation:g.officeLocation,mobilePhone:g.mobilePhone,businessPhones:g.businessPhones,photo:y};P.set(p,{data:f,timestamp:Date.now()}),Ne(),n(f);}catch(g){let f=S(g),i=new Error(f);u(i),console.error("[UserProfile] Failed to fetch profile:",f);}finally{d(false);}},[r,e,t]),h=react.useCallback(()=>{if(e){let p=P.get(e.homeAccountId);p?.data.photo&&URL.revokeObjectURL(p.data.photo),P.delete(e.homeAccountId);}o?.photo&&URL.revokeObjectURL(o.photo),n(null);},[e,o]);return react.useEffect(()=>(s(),()=>{o?.photo&&URL.revokeObjectURL(o.photo);}),[s]),react.useEffect(()=>()=>{o?.photo&&URL.revokeObjectURL(o.photo);},[o?.photo]),{profile:o,loading:a,error:c,refetch:s,clearCache:h}}function De({size:r=40,className:e="",style:t,showTooltip:o=true,fallbackImage:n}){let{profile:a,loading:d}=j(),[c,u]=react.useState(null),[s,h]=react.useState(false);react.useEffect(()=>{a?.photo&&u(a.photo);},[a?.photo]);let p=()=>{if(!a)return "?";let{givenName:y,surname:f,displayName:i}=a;if(y&&f)return `${y[0]}${f[0]}`.toUpperCase();if(i){let l=i.split(" ");return l.length>=2?`${l[0][0]}${l[l.length-1][0]}`.toUpperCase():i.substring(0,2).toUpperCase()}return "?"},m={width:`${r}px`,height:`${r}px`,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:`${r*.4}px`,fontWeight:600,fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',backgroundColor:"#0078D4",color:"#FFFFFF",overflow:"hidden",userSelect:"none",...t},g=a?.displayName||"User";return d?jsxRuntime.jsx("div",{className:e,style:{...m,backgroundColor:"#E1E1E1"},"aria-label":"Loading user avatar",children:jsxRuntime.jsx("span",{style:{fontSize:`${r*.3}px`},children:"..."})}):c&&!s?jsxRuntime.jsx("div",{className:e,style:m,title:o?g:void 0,"aria-label":`${g} avatar`,children:jsxRuntime.jsx("img",{src:c,alt:g,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>{h(true),n&&u(n);}})}):jsxRuntime.jsx("div",{className:e,style:m,title:o?g:void 0,"aria-label":`${g} avatar`,children:p()})}function Oe({className:r="",style:e,showDetails:t=false,renderLoading:o,renderAuthenticated:n,renderUnauthenticated:a}){let{isAuthenticated:d,inProgress:c,account:u}=b(),s={display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"4px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontSize:"14px",fontWeight:500,...e};if(c)return o?jsxRuntime.jsx(jsxRuntime.Fragment,{children:o()}):jsxRuntime.jsxs("div",{className:r,style:{...s,backgroundColor:"#FFF4CE",color:"#8A6D3B"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx(J,{color:"#FFA500"}),jsxRuntime.jsx("span",{children:"Loading..."})]});if(d){let h=u?.username||u?.name||"User";return n?jsxRuntime.jsx(jsxRuntime.Fragment,{children:n(h)}):jsxRuntime.jsxs("div",{className:r,style:{...s,backgroundColor:"#D4EDDA",color:"#155724"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx(J,{color:"#28A745"}),jsxRuntime.jsx("span",{children:t?`Authenticated as ${h}`:"Authenticated"})]})}return a?jsxRuntime.jsx(jsxRuntime.Fragment,{children:a()}):jsxRuntime.jsxs("div",{className:r,style:{...s,backgroundColor:"#F8D7DA",color:"#721C24"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx(J,{color:"#DC3545"}),jsxRuntime.jsx("span",{children:"Not authenticated"})]})}function J({color:r}){return jsxRuntime.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntime.jsx("circle",{cx:"4",cy:"4",r:"4",fill:r})})}function Q({children:r,loadingComponent:e,fallbackComponent:t,useRedirect:o=true,scopes:n,onAuthRequired:a}){let{isAuthenticated:d,inProgress:c,loginRedirect:u,loginPopup:s}=b();return react.useEffect(()=>{!d&&!c&&(a?.(),(async()=>{try{o?await u(n):await s(n);}catch(p){console.error("[AuthGuard] Authentication failed:",p);}})());},[d,c,o,n,u,s,a]),c?jsxRuntime.jsx(jsxRuntime.Fragment,{children:e||jsxRuntime.jsx("div",{children:"Authenticating..."})}):d?jsxRuntime.jsx(jsxRuntime.Fragment,{children:r}):jsxRuntime.jsx(jsxRuntime.Fragment,{children:t||jsxRuntime.jsx("div",{children:"Redirecting to login..."})})}var ee=class extends react.Component{constructor(t){super(t);this.reset=()=>{this.setState({hasError:false,error:null});};this.state={hasError:false,error:null};}static getDerivedStateFromError(t){return {hasError:true,error:t}}componentDidCatch(t,o){let{onError:n,debug:a}=this.props;a&&(console.error("[ErrorBoundary] Caught error:",t),console.error("[ErrorBoundary] Error info:",o)),n?.(t,o);}render(){let{hasError:t,error:o}=this.state,{children:n,fallback:a}=this.props;return t&&o?a?a(o,this.reset):jsxRuntime.jsxs("div",{style:{padding:"20px",margin:"20px",border:"1px solid #DC3545",borderRadius:"4px",backgroundColor:"#F8D7DA",color:"#721C24",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif'},children:[jsxRuntime.jsx("h2",{style:{margin:"0 0 10px 0",fontSize:"18px"},children:"Authentication Error"}),jsxRuntime.jsx("p",{style:{margin:"0 0 10px 0"},children:o.message}),jsxRuntime.jsx("button",{onClick:this.reset,style:{padding:"8px 16px",backgroundColor:"#DC3545",color:"#FFFFFF",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px",fontWeight:600},children:"Try Again"})]}):n}};var R=new Map,Be=300*1e3,de=100;function He(r){r?R.delete(r):R.clear();}function Ve(){if(R.size>de){let r=Array.from(R.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,R.size-de).forEach(([t])=>R.delete(t));}}function We(){let{isAuthenticated:r,account:e}=b(),t=U(),[o,n]=react.useState([]),[a,d]=react.useState([]),[c,u]=react.useState(false),[s,h]=react.useState(null),p=react.useCallback(async()=>{if(!r||!e){n([]),d([]);return}let i=e.homeAccountId,l=R.get(i);if(l&&Date.now()-l.timestamp<Be){n(l.roles),d(l.groups);return}u(true),h(null);try{let v=e.idTokenClaims?.roles||[],O=(await t.get("/me/memberOf",{scopes:["User.Read","Directory.Read.All"]})).value.map(te=>te.id);R.set(i,{roles:v,groups:O,timestamp:Date.now()}),Ve(),n(v),d(O);}catch(A){let D=S(A),O=new Error(D);h(O),console.error("[Roles] Failed to fetch roles/groups:",D);let he=e.idTokenClaims?.roles||[];n(he);}finally{u(false);}},[r,e,t]),m=react.useCallback(i=>o.includes(i),[o]),g=react.useCallback(i=>a.includes(i),[a]),y=react.useCallback(i=>i.some(l=>o.includes(l)),[o]),f=react.useCallback(i=>i.every(l=>o.includes(l)),[o]);return react.useEffect(()=>(p(),()=>{e&&He(e.homeAccountId);}),[p,e]),{roles:o,groups:a,loading:c,error:s,hasRole:m,hasGroup:g,hasAnyRole:y,hasAllRoles:f,refetch:p}}function _e(r,e={}){let{displayName:t,...o}=e,n=a=>jsxRuntime.jsx(Q,{...o,children:jsxRuntime.jsx(r,{...a})});return n.displayName=t||`withAuth(${r.displayName||r.name||"Component"})`,n}async function fe(r,e={}){let{maxRetries:t=3,initialDelay:o=1e3,maxDelay:n=1e4,backoffMultiplier:a=2,debug:d=false}=e,c,u=o;for(let s=0;s<=t;s++)try{return d&&s>0&&console.log(`[TokenRetry] Attempt ${s+1}/${t+1}`),await r()}catch(h){if(c=h,s===t){d&&console.error("[TokenRetry] All retry attempts failed");break}if(!je(h))throw d&&console.log("[TokenRetry] Non-retryable error, aborting"),h;d&&console.warn(`[TokenRetry] Attempt ${s+1} failed, retrying in ${u}ms...`),await Je(u),u=Math.min(u*a,n);}throw c}function je(r){let e=r.message.toLowerCase();return !!(e.includes("network")||e.includes("timeout")||e.includes("fetch")||e.includes("connection")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("429")||e.includes("rate limit")||e.includes("token")&&e.includes("expired"))}function Je(r){return new Promise(e=>setTimeout(e,r))}function Ze(r,e={}){return (...t)=>fe(()=>r(...t),e)}var q=class{constructor(e={}){this.logHistory=[];this.performanceTimings=new Map;this.config={enabled:e.enabled??false,prefix:e.prefix??"[MSAL-Next]",showTimestamp:e.showTimestamp??true,level:e.level??"info",enablePerformance:e.enablePerformance??false,enableNetworkLogs:e.enableNetworkLogs??false,maxHistorySize:e.maxHistorySize??100};}shouldLog(e){if(!this.config.enabled)return false;let t=["error","warn","info","debug"],o=t.indexOf(this.config.level);return t.indexOf(e)<=o}formatMessage(e,t,o){let n=this.config.showTimestamp?`[${new Date().toISOString()}]`:"",a=this.config.prefix,d=`[${e.toUpperCase()}]`,c=`${n} ${a} ${d} ${t}`;return o!==void 0&&(c+=`
2
- `+JSON.stringify(o,null,2)),c}addToHistory(e,t,o){this.logHistory.length>=this.config.maxHistorySize&&this.logHistory.shift(),this.logHistory.push({timestamp:Date.now(),level:e,message:t,data:o});}error(e,t){this.shouldLog("error")&&(console.error(this.formatMessage("error",e,t)),this.addToHistory("error",e,t));}warn(e,t){this.shouldLog("warn")&&(console.warn(this.formatMessage("warn",e,t)),this.addToHistory("warn",e,t));}info(e,t){this.shouldLog("info")&&(console.info(this.formatMessage("info",e,t)),this.addToHistory("info",e,t));}debug(e,t){this.shouldLog("debug")&&(console.debug(this.formatMessage("debug",e,t)),this.addToHistory("debug",e,t));}group(e){this.config.enabled&&console.group(`${this.config.prefix} ${e}`);}groupEnd(){this.config.enabled&&console.groupEnd();}startTiming(e){this.config.enablePerformance&&(this.performanceTimings.set(e,{operation:e,startTime:performance.now()}),this.debug(`\u23F1\uFE0F Started: ${e}`));}endTiming(e){if(this.config.enablePerformance){let t=this.performanceTimings.get(e);if(t)return t.endTime=performance.now(),t.duration=t.endTime-t.startTime,this.info(`\u23F1\uFE0F Completed: ${e} (${t.duration.toFixed(2)}ms)`),t.duration}}logRequest(e,t,o){this.config.enableNetworkLogs&&this.debug(`\u{1F310} ${e} ${t}`,o);}logResponse(e,t,o,n){if(this.config.enableNetworkLogs){let a=o>=200&&o<300?"\u2705":"\u274C";this.debug(`${a} ${e} ${t} - ${o}`,n);}}getHistory(){return [...this.logHistory]}getPerformanceTimings(){return Array.from(this.performanceTimings.values())}clearHistory(){this.logHistory=[];}clearTimings(){this.performanceTimings.clear();}exportLogs(){return JSON.stringify({config:this.config,history:this.logHistory,performanceTimings:Array.from(this.performanceTimings.values()),exportedAt:new Date().toISOString()},null,2)}downloadLogs(e="msal-next-debug-logs.json"){if(typeof window>"u")return;let t=this.exportLogs(),o=new Blob([t],{type:"application/json"}),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n,a.download=e,a.click(),URL.revokeObjectURL(n);}setEnabled(e){this.config.enabled=e;}setLevel(e){e&&(this.config.level=e);}},I=null;function Ke(r){return I?r&&(r.enabled!==void 0&&I.setEnabled(r.enabled),r.level&&I.setLevel(r.level)):I=new q(r),I}function Xe(r,e){return new q({...e,prefix:`[MSAL-Next:${r}]`})}function Qe(r={}){let{protectedRoutes:e=[],publicOnlyRoutes:t=[],loginPath:o="/login",redirectAfterLogin:n="/",sessionCookie:a="msal.account",isAuthenticated:d,debug:c=false}=r;return async function(s){let{pathname:h}=s.nextUrl;c&&console.log("[AuthMiddleware] Processing:",h);let p=false;d?p=await d(s):p=!!s.cookies.get(a)?.value,c&&console.log("[AuthMiddleware] Authenticated:",p);let m=e.some(f=>h.startsWith(f)),g=t.some(f=>h.startsWith(f));if(m&&!p){c&&console.log("[AuthMiddleware] Redirecting to login");let f=s.nextUrl.clone();return f.pathname=o,f.searchParams.set("returnUrl",h),server.NextResponse.redirect(f)}if(g&&p){c&&console.log("[AuthMiddleware] Redirecting to home");let f=s.nextUrl.searchParams.get("returnUrl"),i=s.nextUrl.clone();return i.pathname=f||n,i.searchParams.delete("returnUrl"),server.NextResponse.redirect(i)}let y=server.NextResponse.next();if(p){y.headers.set("x-msal-authenticated","true");try{let f=s.cookies.get(a);if(f?.value){let i=z(f.value,B);i?.username&&y.headers.set("x-msal-username",i.username);}}catch{c&&console.warn("[AuthMiddleware] Failed to parse session data");}}return y}}Object.defineProperty(exports,"useAccount",{enumerable:true,get:function(){return msalReact.useAccount}});Object.defineProperty(exports,"useIsAuthenticated",{enumerable:true,get:function(){return msalReact.useIsAuthenticated}});Object.defineProperty(exports,"useMsal",{enumerable:true,get:function(){return msalReact.useMsal}});exports.AuthGuard=Q;exports.AuthStatus=Oe;exports.ErrorBoundary=ee;exports.MicrosoftSignInButton=Le;exports.MsalAuthProvider=ve;exports.SignOutButton=Ue;exports.UserAvatar=De;exports.createAuthMiddleware=Qe;exports.createMsalConfig=H;exports.createRetryWrapper=Ze;exports.createScopedLogger=Xe;exports.getDebugLogger=Ke;exports.getMsalInstance=Pe;exports.isValidAccountData=B;exports.isValidRedirectUri=G;exports.isValidScope=oe;exports.retryWithBackoff=fe;exports.safeJsonParse=z;exports.sanitizeError=S;exports.useGraphApi=U;exports.useMsalAuth=b;exports.useRoles=We;exports.useUserProfile=j;exports.validateScopes=me;exports.withAuth=_e;
1
+ 'use strict';var msalReact=require('@azure/msal-react'),msalBrowser=require('@azure/msal-browser'),react=require('react'),jsxRuntime=require('react/jsx-runtime'),server=require('next/server');function B(r,e){try{let t=JSON.parse(r);return e(t)?t:(console.warn("[Validation] JSON validation failed"),null)}catch(t){return console.error("[Validation] JSON parse error:",t),null}}function _(r){return typeof r=="object"&&r!==null&&typeof r.homeAccountId=="string"&&r.homeAccountId.length>0&&typeof r.username=="string"&&r.username.length>0&&(r.name===void 0||typeof r.name=="string")}function S(r){return r instanceof Error?r.message.replace(/[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g,"[TOKEN_REDACTED]").replace(/[a-f0-9]{32,}/gi,"[SECRET_REDACTED]").replace(/Bearer\s+[^\s]+/gi,"Bearer [REDACTED]"):"An unexpected error occurred"}function $(r,e){try{let t=new URL(r);return e.some(o=>{let n=new URL(o);return t.origin===n.origin})}catch{return false}}function ie(r){return /^[a-zA-Z0-9._-]+$/.test(r)}function Ae(r){return Array.isArray(r)&&r.every(ie)}function H(r){if(r.msalConfig)return r.msalConfig;let{clientId:e,tenantId:t,authorityType:o="common",redirectUri:n,postLogoutRedirectUri:a,cacheLocation:f="sessionStorage",storeAuthStateInCookie:c=false,navigateToLoginRequestUrl:u=true,enableLogging:i=false,loggerCallback:m,allowedRedirectUris:d}=r;if(!e)throw new Error("@chemmangat/msal-next: clientId is required");let p=()=>{if(o==="tenant"){if(!t)throw new Error('@chemmangat/msal-next: tenantId is required when authorityType is "tenant"');return `https://login.microsoftonline.com/${t}`}return `https://login.microsoftonline.com/${o}`},g=typeof window<"u"?window.location.origin:"http://localhost:3000",y=n||g;if(d&&d.length>0){if(!$(y,d))throw new Error(`@chemmangat/msal-next: redirectUri "${y}" is not in the allowed list`);let s=a||y;if(!$(s,d))throw new Error(`@chemmangat/msal-next: postLogoutRedirectUri "${s}" is not in the allowed list`)}return {auth:{clientId:e,authority:p(),redirectUri:y,postLogoutRedirectUri:a||y,navigateToLoginRequestUrl:u},cache:{cacheLocation:f,storeAuthStateInCookie:c},system:{loggerOptions:{loggerCallback:m||((s,l,b)=>{if(!(b||!i))switch(s){case msalBrowser.LogLevel.Error:console.error("[MSAL]",l);break;case msalBrowser.LogLevel.Warning:console.warn("[MSAL]",l);break;case msalBrowser.LogLevel.Info:console.info("[MSAL]",l);break;case msalBrowser.LogLevel.Verbose:console.debug("[MSAL]",l);break}}),logLevel:i?msalBrowser.LogLevel.Verbose:msalBrowser.LogLevel.Error}}}}var ae=null;function Re(){return ae}function V({children:r,loadingComponent:e,onInitialized:t,...o}){let[n,a]=react.useState(null),f=react.useRef(null);return react.useEffect(()=>{if(typeof window>"u"||f.current)return;(async()=>{try{let u=H(o),i=new msalBrowser.PublicClientApplication(u);await i.initialize();try{let p=await i.handleRedirectPromise();p&&(o.enableLogging&&console.log("[MSAL] Redirect authentication successful"),p.account&&i.setActiveAccount(p.account));}catch(p){p?.errorCode==="no_token_request_cache_error"?o.enableLogging&&console.log("[MSAL] No pending redirect found (this is normal)"):p?.errorCode==="user_cancelled"?o.enableLogging&&console.log("[MSAL] User cancelled authentication"):console.error("[MSAL] Redirect handling error:",p);}let m=i.getAllAccounts();m.length>0&&!i.getActiveAccount()&&i.setActiveAccount(m[0]);let d=o.enableLogging||!1;i.addEventCallback(p=>{if(p.eventType===msalBrowser.EventType.LOGIN_SUCCESS){let g=p.payload;g?.account&&i.setActiveAccount(g.account),d&&console.log("[MSAL] Login successful:",g.account?.username);}if(p.eventType===msalBrowser.EventType.LOGIN_FAILURE&&console.error("[MSAL] Login failed:",p.error),p.eventType===msalBrowser.EventType.LOGOUT_SUCCESS&&(i.setActiveAccount(null),d&&console.log("[MSAL] Logout successful")),p.eventType===msalBrowser.EventType.ACQUIRE_TOKEN_SUCCESS){let g=p.payload;g?.account&&!i.getActiveAccount()&&i.setActiveAccount(g.account);}p.eventType===msalBrowser.EventType.ACQUIRE_TOKEN_FAILURE&&d&&console.error("[MSAL] Token acquisition failed:",p.error);}),f.current=i,ae=i,a(i),t&&t(i);}catch(u){throw console.error("[MSAL] Initialization failed:",u),u}})();},[]),typeof window>"u"?jsxRuntime.jsx(jsxRuntime.Fragment,{children:e||jsxRuntime.jsx("div",{children:"Loading authentication..."})}):n?jsxRuntime.jsx(msalReact.MsalProvider,{instance:n,children:r}):jsxRuntime.jsx(jsxRuntime.Fragment,{children:e||jsxRuntime.jsx("div",{children:"Loading authentication..."})})}var j=new Map;function A(r=["User.Read"]){let{instance:e,accounts:t,inProgress:o}=msalReact.useMsal(),n=msalReact.useAccount(t[0]||null),a=react.useRef(false),f=react.useMemo(()=>t.length>0,[t]),c=react.useCallback(async(s=r)=>{if(o!==msalBrowser.InteractionStatus.None){console.warn("[MSAL] Interaction already in progress");return}try{let l={scopes:s,prompt:"select_account"},b=await e.loginPopup(l);b?.account&&e.setActiveAccount(b.account);}catch(l){if(l?.errorCode==="user_cancelled"){console.log("[MSAL] User cancelled login");return}throw console.error("[MSAL] Login popup failed:",l),l}},[e,r,o]),u=react.useCallback(async(s=r)=>{if(o!==msalBrowser.InteractionStatus.None){console.warn("[MSAL] Interaction already in progress");return}try{let l={scopes:s,prompt:"select_account"};await e.loginRedirect(l);}catch(l){if(l?.errorCode==="user_cancelled"){console.log("[MSAL] User cancelled login");return}throw console.error("[MSAL] Login redirect failed:",l),l}},[e,r,o]),i=react.useCallback(async()=>{try{await e.logoutPopup({account:n||void 0});}catch(s){throw console.error("[MSAL] Logout popup failed:",s),s}},[e,n]),m=react.useCallback(async()=>{try{await e.logoutRedirect({account:n||void 0});}catch(s){throw console.error("[MSAL] Logout redirect failed:",s),s}},[e,n]),d=react.useCallback(async(s=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let l={scopes:s,account:n,forceRefresh:!1};return (await e.acquireTokenSilent(l)).accessToken}catch(l){throw console.error("[MSAL] Silent token acquisition failed:",l),l}},[e,n,r]),p=react.useCallback(async(s=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");if(a.current)throw new Error("[MSAL] Popup already in progress. Please wait.");try{a.current=!0;let l={scopes:s,account:n};return (await e.acquireTokenPopup(l)).accessToken}catch(l){throw console.error("[MSAL] Token popup acquisition failed:",l),l}finally{a.current=false;}},[e,n,r]),g=react.useCallback(async(s=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let l={scopes:s,account:n};await e.acquireTokenRedirect(l);}catch(l){throw console.error("[MSAL] Token redirect acquisition failed:",l),l}},[e,n,r]),y=react.useCallback(async(s=r)=>{let l=`${n?.homeAccountId||"anonymous"}-${s.sort().join(",")}`,b=j.get(l);if(b)return b;let w=(async()=>{try{return await d(s)}catch{return console.warn("[MSAL] Silent token acquisition failed, falling back to popup"),await p(s)}finally{j.delete(l);}})();return j.set(l,w),w},[d,p,r,n]),h=react.useCallback(async()=>{e.setActiveAccount(null),await e.clearCache();},[e]);return {account:n,accounts:t,isAuthenticated:f,inProgress:o!==msalBrowser.InteractionStatus.None,loginPopup:c,loginRedirect:u,logoutPopup:i,logoutRedirect:m,acquireToken:y,acquireTokenSilent:d,acquireTokenPopup:p,acquireTokenRedirect:g,clearSession:h}}function Le({text:r="Sign in with Microsoft",variant:e="dark",size:t="medium",useRedirect:o=false,scopes:n,className:a="",style:f,onSuccess:c,onError:u}){let{loginPopup:i,loginRedirect:m,inProgress:d}=A(),p=async()=>{try{o?await m(n):await i(n),c?.();}catch(s){u?.(s);}},g={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},h={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:d?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:d?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...g[t],...f};return jsxRuntime.jsxs("button",{onClick:p,disabled:d,className:a,style:h,"aria-label":r,children:[jsxRuntime.jsx(Me,{}),jsxRuntime.jsx("span",{children:r})]})}function Me(){return jsxRuntime.jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsxRuntime.jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsxRuntime.jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsxRuntime.jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function Ue({text:r="Sign out",variant:e="dark",size:t="medium",useRedirect:o=false,className:n="",style:a,onSuccess:f,onError:c}){let{logoutPopup:u,logoutRedirect:i,inProgress:m}=A(),d=async()=>{try{o?await i():await u(),f?.();}catch(h){c?.(h);}},p={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},y={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:m?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:m?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...p[t],...a};return jsxRuntime.jsxs("button",{onClick:d,disabled:m,className:n,style:y,"aria-label":r,children:[jsxRuntime.jsx(ke,{}),jsxRuntime.jsx("span",{children:r})]})}function ke(){return jsxRuntime.jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsxRuntime.jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsxRuntime.jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsxRuntime.jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function k(){let{acquireToken:r}=A(),e=react.useCallback(async(c,u={})=>{let{scopes:i=["User.Read"],version:m="v1.0",debug:d=false,...p}=u;try{let g=await r(i),y=`https://graph.microsoft.com/${m}`,h=c.startsWith("http")?c:`${y}${c.startsWith("/")?c:`/${c}`}`;d&&console.log("[GraphAPI] Request:",{url:h,method:p.method||"GET"});let s=await fetch(h,{...p,headers:{Authorization:`Bearer ${g}`,"Content-Type":"application/json",...p.headers}});if(!s.ok){let b=await s.text(),w=`Graph API error (${s.status}): ${b}`;throw new Error(w)}if(s.status===204||s.headers.get("content-length")==="0")return null;let l=await s.json();return d&&console.log("[GraphAPI] Response:",l),l}catch(g){let y=S(g);throw console.error("[GraphAPI] Request failed:",y),new Error(y)}},[r]),t=react.useCallback((c,u={})=>e(c,{...u,method:"GET"}),[e]),o=react.useCallback((c,u,i={})=>e(c,{...i,method:"POST",body:u?JSON.stringify(u):void 0}),[e]),n=react.useCallback((c,u,i={})=>e(c,{...i,method:"PUT",body:u?JSON.stringify(u):void 0}),[e]),a=react.useCallback((c,u,i={})=>e(c,{...i,method:"PATCH",body:u?JSON.stringify(u):void 0}),[e]),f=react.useCallback((c,u={})=>e(c,{...u,method:"DELETE"}),[e]);return {get:t,post:o,put:n,patch:a,delete:f,request:e}}var P=new Map,Fe=300*1e3,de=100;function Ne(){if(P.size>de){let r=Array.from(P.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,P.size-de).forEach(([t])=>{let o=P.get(t);o?.data.photo&&URL.revokeObjectURL(o.data.photo),P.delete(t);});}}function K(){let{isAuthenticated:r,account:e}=A(),t=k(),[o,n]=react.useState(null),[a,f]=react.useState(false),[c,u]=react.useState(null),i=react.useCallback(async()=>{if(!r||!e){n(null);return}let d=e.homeAccountId,p=P.get(d);if(p&&Date.now()-p.timestamp<Fe){n(p.data);return}f(true),u(null);try{let g=await t.get("/me",{scopes:["User.Read"]}),y;try{let s=await t.get("/me/photo/$value",{scopes:["User.Read"],headers:{"Content-Type":"image/jpeg"}});s&&(y=URL.createObjectURL(s));}catch{console.debug("[UserProfile] Photo not available");}let h={id:g.id,displayName:g.displayName,givenName:g.givenName,surname:g.surname,userPrincipalName:g.userPrincipalName,mail:g.mail,jobTitle:g.jobTitle,officeLocation:g.officeLocation,mobilePhone:g.mobilePhone,businessPhones:g.businessPhones,photo:y};P.set(d,{data:h,timestamp:Date.now()}),Ne(),n(h);}catch(g){let h=S(g),s=new Error(h);u(s),console.error("[UserProfile] Failed to fetch profile:",h);}finally{f(false);}},[r,e,t]),m=react.useCallback(()=>{if(e){let d=P.get(e.homeAccountId);d?.data.photo&&URL.revokeObjectURL(d.data.photo),P.delete(e.homeAccountId);}o?.photo&&URL.revokeObjectURL(o.photo),n(null);},[e,o]);return react.useEffect(()=>(i(),()=>{o?.photo&&URL.revokeObjectURL(o.photo);}),[i]),react.useEffect(()=>()=>{o?.photo&&URL.revokeObjectURL(o.photo);},[o?.photo]),{profile:o,loading:a,error:c,refetch:i,clearCache:m}}function Oe({size:r=40,className:e="",style:t,showTooltip:o=true,fallbackImage:n}){let{profile:a,loading:f}=K(),[c,u]=react.useState(null),[i,m]=react.useState(false);react.useEffect(()=>{a?.photo&&u(a.photo);},[a?.photo]);let d=()=>{if(!a)return "?";let{givenName:y,surname:h,displayName:s}=a;if(y&&h)return `${y[0]}${h[0]}`.toUpperCase();if(s){let l=s.split(" ");return l.length>=2?`${l[0][0]}${l[l.length-1][0]}`.toUpperCase():s.substring(0,2).toUpperCase()}return "?"},p={width:`${r}px`,height:`${r}px`,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:`${r*.4}px`,fontWeight:600,fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',backgroundColor:"#0078D4",color:"#FFFFFF",overflow:"hidden",userSelect:"none",...t},g=a?.displayName||"User";return f?jsxRuntime.jsx("div",{className:e,style:{...p,backgroundColor:"#E1E1E1"},"aria-label":"Loading user avatar",children:jsxRuntime.jsx("span",{style:{fontSize:`${r*.3}px`},children:"..."})}):c&&!i?jsxRuntime.jsx("div",{className:e,style:p,title:o?g:void 0,"aria-label":`${g} avatar`,children:jsxRuntime.jsx("img",{src:c,alt:g,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>{m(true),n&&u(n);}})}):jsxRuntime.jsx("div",{className:e,style:p,title:o?g:void 0,"aria-label":`${g} avatar`,children:d()})}function De({className:r="",style:e,showDetails:t=false,renderLoading:o,renderAuthenticated:n,renderUnauthenticated:a}){let{isAuthenticated:f,inProgress:c,account:u}=A(),i={display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"4px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontSize:"14px",fontWeight:500,...e};if(c)return o?jsxRuntime.jsx(jsxRuntime.Fragment,{children:o()}):jsxRuntime.jsxs("div",{className:r,style:{...i,backgroundColor:"#FFF4CE",color:"#8A6D3B"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx(Z,{color:"#FFA500"}),jsxRuntime.jsx("span",{children:"Loading..."})]});if(f){let m=u?.username||u?.name||"User";return n?jsxRuntime.jsx(jsxRuntime.Fragment,{children:n(m)}):jsxRuntime.jsxs("div",{className:r,style:{...i,backgroundColor:"#D4EDDA",color:"#155724"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx(Z,{color:"#28A745"}),jsxRuntime.jsx("span",{children:t?`Authenticated as ${m}`:"Authenticated"})]})}return a?jsxRuntime.jsx(jsxRuntime.Fragment,{children:a()}):jsxRuntime.jsxs("div",{className:r,style:{...i,backgroundColor:"#F8D7DA",color:"#721C24"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx(Z,{color:"#DC3545"}),jsxRuntime.jsx("span",{children:"Not authenticated"})]})}function Z({color:r}){return jsxRuntime.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntime.jsx("circle",{cx:"4",cy:"4",r:"4",fill:r})})}function ee({children:r,loadingComponent:e,fallbackComponent:t,useRedirect:o=true,scopes:n,onAuthRequired:a}){let{isAuthenticated:f,inProgress:c,loginRedirect:u,loginPopup:i}=A();return react.useEffect(()=>{!f&&!c&&(a?.(),(async()=>{try{o?await u(n):await i(n);}catch(d){console.error("[AuthGuard] Authentication failed:",d);}})());},[f,c,o,n,u,i,a]),c?jsxRuntime.jsx(jsxRuntime.Fragment,{children:e||jsxRuntime.jsx("div",{children:"Authenticating..."})}):f?jsxRuntime.jsx(jsxRuntime.Fragment,{children:r}):jsxRuntime.jsx(jsxRuntime.Fragment,{children:t||jsxRuntime.jsx("div",{children:"Redirecting to login..."})})}var te=class extends react.Component{constructor(t){super(t);this.reset=()=>{this.setState({hasError:false,error:null});};this.state={hasError:false,error:null};}static getDerivedStateFromError(t){return {hasError:true,error:t}}componentDidCatch(t,o){let{onError:n,debug:a}=this.props;a&&(console.error("[ErrorBoundary] Caught error:",t),console.error("[ErrorBoundary] Error info:",o)),n?.(t,o);}render(){let{hasError:t,error:o}=this.state,{children:n,fallback:a}=this.props;return t&&o?a?a(o,this.reset):jsxRuntime.jsxs("div",{style:{padding:"20px",margin:"20px",border:"1px solid #DC3545",borderRadius:"4px",backgroundColor:"#F8D7DA",color:"#721C24",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif'},children:[jsxRuntime.jsx("h2",{style:{margin:"0 0 10px 0",fontSize:"18px"},children:"Authentication Error"}),jsxRuntime.jsx("p",{style:{margin:"0 0 10px 0"},children:o.message}),jsxRuntime.jsx("button",{onClick:this.reset,style:{padding:"8px 16px",backgroundColor:"#DC3545",color:"#FFFFFF",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px",fontWeight:600},children:"Try Again"})]}):n}};function ze({children:r,...e}){return jsxRuntime.jsx(V,{...e,children:r})}var R=new Map,He=300*1e3,fe=100;function Ve(r){r?R.delete(r):R.clear();}function We(){if(R.size>fe){let r=Array.from(R.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,R.size-fe).forEach(([t])=>R.delete(t));}}function je(){let{isAuthenticated:r,account:e}=A(),t=k(),[o,n]=react.useState([]),[a,f]=react.useState([]),[c,u]=react.useState(false),[i,m]=react.useState(null),d=react.useCallback(async()=>{if(!r||!e){n([]),f([]);return}let s=e.homeAccountId,l=R.get(s);if(l&&Date.now()-l.timestamp<He){n(l.roles),f(l.groups);return}u(true),m(null);try{let w=e.idTokenClaims?.roles||[],G=(await t.get("/me/memberOf",{scopes:["User.Read","Directory.Read.All"]})).value.map(ne=>ne.id);R.set(s,{roles:w,groups:G,timestamp:Date.now()}),We(),n(w),f(G);}catch(b){let D=S(b),G=new Error(D);m(G),console.error("[Roles] Failed to fetch roles/groups:",D);let ye=e.idTokenClaims?.roles||[];n(ye);}finally{u(false);}},[r,e,t]),p=react.useCallback(s=>o.includes(s),[o]),g=react.useCallback(s=>a.includes(s),[a]),y=react.useCallback(s=>s.some(l=>o.includes(l)),[o]),h=react.useCallback(s=>s.every(l=>o.includes(l)),[o]);return react.useEffect(()=>(d(),()=>{e&&Ve(e.homeAccountId);}),[d,e]),{roles:o,groups:a,loading:c,error:i,hasRole:p,hasGroup:g,hasAnyRole:y,hasAllRoles:h,refetch:d}}function Je(r,e={}){let{displayName:t,...o}=e,n=a=>jsxRuntime.jsx(ee,{...o,children:jsxRuntime.jsx(r,{...a})});return n.displayName=t||`withAuth(${r.displayName||r.name||"Component"})`,n}async function me(r,e={}){let{maxRetries:t=3,initialDelay:o=1e3,maxDelay:n=1e4,backoffMultiplier:a=2,debug:f=false}=e,c,u=o;for(let i=0;i<=t;i++)try{return f&&i>0&&console.log(`[TokenRetry] Attempt ${i+1}/${t+1}`),await r()}catch(m){if(c=m,i===t){f&&console.error("[TokenRetry] All retry attempts failed");break}if(!Ke(m))throw f&&console.log("[TokenRetry] Non-retryable error, aborting"),m;f&&console.warn(`[TokenRetry] Attempt ${i+1} failed, retrying in ${u}ms...`),await Ze(u),u=Math.min(u*a,n);}throw c}function Ke(r){let e=r.message.toLowerCase();return !!(e.includes("network")||e.includes("timeout")||e.includes("fetch")||e.includes("connection")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("429")||e.includes("rate limit")||e.includes("token")&&e.includes("expired"))}function Ze(r){return new Promise(e=>setTimeout(e,r))}function Qe(r,e={}){return (...t)=>me(()=>r(...t),e)}var z=class{constructor(e={}){this.logHistory=[];this.performanceTimings=new Map;this.config={enabled:e.enabled??false,prefix:e.prefix??"[MSAL-Next]",showTimestamp:e.showTimestamp??true,level:e.level??"info",enablePerformance:e.enablePerformance??false,enableNetworkLogs:e.enableNetworkLogs??false,maxHistorySize:e.maxHistorySize??100};}shouldLog(e){if(!this.config.enabled)return false;let t=["error","warn","info","debug"],o=t.indexOf(this.config.level);return t.indexOf(e)<=o}formatMessage(e,t,o){let n=this.config.showTimestamp?`[${new Date().toISOString()}]`:"",a=this.config.prefix,f=`[${e.toUpperCase()}]`,c=`${n} ${a} ${f} ${t}`;return o!==void 0&&(c+=`
2
+ `+JSON.stringify(o,null,2)),c}addToHistory(e,t,o){this.logHistory.length>=this.config.maxHistorySize&&this.logHistory.shift(),this.logHistory.push({timestamp:Date.now(),level:e,message:t,data:o});}error(e,t){this.shouldLog("error")&&(console.error(this.formatMessage("error",e,t)),this.addToHistory("error",e,t));}warn(e,t){this.shouldLog("warn")&&(console.warn(this.formatMessage("warn",e,t)),this.addToHistory("warn",e,t));}info(e,t){this.shouldLog("info")&&(console.info(this.formatMessage("info",e,t)),this.addToHistory("info",e,t));}debug(e,t){this.shouldLog("debug")&&(console.debug(this.formatMessage("debug",e,t)),this.addToHistory("debug",e,t));}group(e){this.config.enabled&&console.group(`${this.config.prefix} ${e}`);}groupEnd(){this.config.enabled&&console.groupEnd();}startTiming(e){this.config.enablePerformance&&(this.performanceTimings.set(e,{operation:e,startTime:performance.now()}),this.debug(`\u23F1\uFE0F Started: ${e}`));}endTiming(e){if(this.config.enablePerformance){let t=this.performanceTimings.get(e);if(t)return t.endTime=performance.now(),t.duration=t.endTime-t.startTime,this.info(`\u23F1\uFE0F Completed: ${e} (${t.duration.toFixed(2)}ms)`),t.duration}}logRequest(e,t,o){this.config.enableNetworkLogs&&this.debug(`\u{1F310} ${e} ${t}`,o);}logResponse(e,t,o,n){if(this.config.enableNetworkLogs){let a=o>=200&&o<300?"\u2705":"\u274C";this.debug(`${a} ${e} ${t} - ${o}`,n);}}getHistory(){return [...this.logHistory]}getPerformanceTimings(){return Array.from(this.performanceTimings.values())}clearHistory(){this.logHistory=[];}clearTimings(){this.performanceTimings.clear();}exportLogs(){return JSON.stringify({config:this.config,history:this.logHistory,performanceTimings:Array.from(this.performanceTimings.values()),exportedAt:new Date().toISOString()},null,2)}downloadLogs(e="msal-next-debug-logs.json"){if(typeof window>"u")return;let t=this.exportLogs(),o=new Blob([t],{type:"application/json"}),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n,a.download=e,a.click(),URL.revokeObjectURL(n);}setEnabled(e){this.config.enabled=e;}setLevel(e){e&&(this.config.level=e);}},O=null;function Xe(r){return O?r&&(r.enabled!==void 0&&O.setEnabled(r.enabled),r.level&&O.setLevel(r.level)):O=new z(r),O}function Ye(r,e){return new z({...e,prefix:`[MSAL-Next:${r}]`})}function er(r={}){let{protectedRoutes:e=[],publicOnlyRoutes:t=[],loginPath:o="/login",redirectAfterLogin:n="/",sessionCookie:a="msal.account",isAuthenticated:f,debug:c=false}=r;return async function(i){let{pathname:m}=i.nextUrl;c&&console.log("[AuthMiddleware] Processing:",m);let d=false;f?d=await f(i):d=!!i.cookies.get(a)?.value,c&&console.log("[AuthMiddleware] Authenticated:",d);let p=e.some(h=>m.startsWith(h)),g=t.some(h=>m.startsWith(h));if(p&&!d){c&&console.log("[AuthMiddleware] Redirecting to login");let h=i.nextUrl.clone();return h.pathname=o,h.searchParams.set("returnUrl",m),server.NextResponse.redirect(h)}if(g&&d){c&&console.log("[AuthMiddleware] Redirecting to home");let h=i.nextUrl.searchParams.get("returnUrl"),s=i.nextUrl.clone();return s.pathname=h||n,s.searchParams.delete("returnUrl"),server.NextResponse.redirect(s)}let y=server.NextResponse.next();if(d){y.headers.set("x-msal-authenticated","true");try{let h=i.cookies.get(a);if(h?.value){let s=B(h.value,_);s?.username&&y.headers.set("x-msal-username",s.username);}}catch{c&&console.warn("[AuthMiddleware] Failed to parse session data");}}return y}}Object.defineProperty(exports,"useAccount",{enumerable:true,get:function(){return msalReact.useAccount}});Object.defineProperty(exports,"useIsAuthenticated",{enumerable:true,get:function(){return msalReact.useIsAuthenticated}});Object.defineProperty(exports,"useMsal",{enumerable:true,get:function(){return msalReact.useMsal}});exports.AuthGuard=ee;exports.AuthStatus=De;exports.ErrorBoundary=te;exports.MicrosoftSignInButton=Le;exports.MsalAuthProvider=V;exports.Providers=ze;exports.SignOutButton=Ue;exports.UserAvatar=Oe;exports.createAuthMiddleware=er;exports.createMsalConfig=H;exports.createRetryWrapper=Qe;exports.createScopedLogger=Ye;exports.getDebugLogger=Xe;exports.getMsalInstance=Re;exports.isValidAccountData=_;exports.isValidRedirectUri=$;exports.isValidScope=ie;exports.retryWithBackoff=me;exports.safeJsonParse=B;exports.sanitizeError=S;exports.useGraphApi=k;exports.useMsalAuth=A;exports.useRoles=je;exports.useUserProfile=K;exports.validateScopes=Ae;exports.withAuth=Je;
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import {MsalProvider,useMsal,useAccount}from'@azure/msal-react';export{useAccount,useIsAuthenticated,useMsal}from'@azure/msal-react';import {LogLevel,PublicClientApplication,EventType,InteractionStatus}from'@azure/msal-browser';import {useState,useRef,useEffect,useMemo,useCallback,Component}from'react';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import {NextResponse}from'next/server';function z(r,e){try{let t=JSON.parse(r);return e(t)?t:(console.warn("[Validation] JSON validation failed"),null)}catch(t){return console.error("[Validation] JSON parse error:",t),null}}function B(r){return typeof r=="object"&&r!==null&&typeof r.homeAccountId=="string"&&r.homeAccountId.length>0&&typeof r.username=="string"&&r.username.length>0&&(r.name===void 0||typeof r.name=="string")}function S(r){return r instanceof Error?r.message.replace(/[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g,"[TOKEN_REDACTED]").replace(/[a-f0-9]{32,}/gi,"[SECRET_REDACTED]").replace(/Bearer\s+[^\s]+/gi,"Bearer [REDACTED]"):"An unexpected error occurred"}function G(r,e){try{let t=new URL(r);return e.some(o=>{let n=new URL(o);return t.origin===n.origin})}catch{return false}}function oe(r){return /^[a-zA-Z0-9._-]+$/.test(r)}function me(r){return Array.isArray(r)&&r.every(oe)}function H(r){if(r.msalConfig)return r.msalConfig;let{clientId:e,tenantId:t,authorityType:o="common",redirectUri:n,postLogoutRedirectUri:a,cacheLocation:d="sessionStorage",storeAuthStateInCookie:c=false,navigateToLoginRequestUrl:u=true,enableLogging:s=false,loggerCallback:h,allowedRedirectUris:p}=r;if(!e)throw new Error("@chemmangat/msal-next: clientId is required");let m=()=>{if(o==="tenant"){if(!t)throw new Error('@chemmangat/msal-next: tenantId is required when authorityType is "tenant"');return `https://login.microsoftonline.com/${t}`}return `https://login.microsoftonline.com/${o}`},g=typeof window<"u"?window.location.origin:"http://localhost:3000",y=n||g;if(p&&p.length>0){if(!G(y,p))throw new Error(`@chemmangat/msal-next: redirectUri "${y}" is not in the allowed list`);let i=a||y;if(!G(i,p))throw new Error(`@chemmangat/msal-next: postLogoutRedirectUri "${i}" is not in the allowed list`)}return {auth:{clientId:e,authority:m(),redirectUri:y,postLogoutRedirectUri:a||y,navigateToLoginRequestUrl:u},cache:{cacheLocation:d,storeAuthStateInCookie:c},system:{loggerOptions:{loggerCallback:h||((i,l,A)=>{if(!(A||!s))switch(i){case LogLevel.Error:console.error("[MSAL]",l);break;case LogLevel.Warning:console.warn("[MSAL]",l);break;case LogLevel.Info:console.info("[MSAL]",l);break;case LogLevel.Verbose:console.debug("[MSAL]",l);break}}),logLevel:s?LogLevel.Verbose:LogLevel.Error}}}}var ie=null;function Pe(){return ie}function ve({children:r,loadingComponent:e,onInitialized:t,...o}){let[n,a]=useState(null),d=useRef(null);return useEffect(()=>{if(typeof window>"u"||d.current)return;(async()=>{try{let u=H(o),s=new PublicClientApplication(u);await s.initialize(),await s.handleRedirectPromise()&&o.enableLogging&&console.log("[MSAL] Redirect authentication successful");let p=o.enableLogging||!1;s.addEventCallback(m=>{if(m.eventType===EventType.LOGIN_SUCCESS&&p){let g=m.payload;console.log("[MSAL] Login successful:",g.account?.username);}m.eventType===EventType.LOGIN_FAILURE&&console.error("[MSAL] Login failed:",m.error),m.eventType===EventType.LOGOUT_SUCCESS&&p&&console.log("[MSAL] Logout successful");}),d.current=s,ie=s,a(s),t&&t(s);}catch(u){throw console.error("[MSAL] Initialization failed:",u),u}})();},[]),typeof window>"u"?jsx(Fragment,{children:e||jsx("div",{children:"Loading authentication..."})}):n?jsx(MsalProvider,{instance:n,children:r}):jsx(Fragment,{children:e||jsx("div",{children:"Loading authentication..."})})}var W=new Map;function b(r=["User.Read"]){let{instance:e,accounts:t,inProgress:o}=useMsal(),n=useAccount(t[0]||null),a=useRef(false),d=useMemo(()=>t.length>0,[t]),c=useCallback(async(i=r)=>{try{let l={scopes:i,prompt:"select_account"};await e.loginPopup(l);}catch(l){throw console.error("[MSAL] Login popup failed:",l),l}},[e,r]),u=useCallback(async(i=r)=>{try{let l={scopes:i,prompt:"select_account"};await e.loginRedirect(l);}catch(l){throw console.error("[MSAL] Login redirect failed:",l),l}},[e,r]),s=useCallback(async()=>{try{await e.logoutPopup({account:n||void 0});}catch(i){throw console.error("[MSAL] Logout popup failed:",i),i}},[e,n]),h=useCallback(async()=>{try{await e.logoutRedirect({account:n||void 0});}catch(i){throw console.error("[MSAL] Logout redirect failed:",i),i}},[e,n]),p=useCallback(async(i=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let l={scopes:i,account:n,forceRefresh:!1};return (await e.acquireTokenSilent(l)).accessToken}catch(l){throw console.error("[MSAL] Silent token acquisition failed:",l),l}},[e,n,r]),m=useCallback(async(i=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");if(a.current)throw new Error("[MSAL] Popup already in progress. Please wait.");try{a.current=!0;let l={scopes:i,account:n};return (await e.acquireTokenPopup(l)).accessToken}catch(l){throw console.error("[MSAL] Token popup acquisition failed:",l),l}finally{a.current=false;}},[e,n,r]),g=useCallback(async(i=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let l={scopes:i,account:n};await e.acquireTokenRedirect(l);}catch(l){throw console.error("[MSAL] Token redirect acquisition failed:",l),l}},[e,n,r]),y=useCallback(async(i=r)=>{let l=`${n?.homeAccountId||"anonymous"}-${i.sort().join(",")}`,A=W.get(l);if(A)return A;let v=(async()=>{try{return await p(i)}catch{return console.warn("[MSAL] Silent token acquisition failed, falling back to popup"),await m(i)}finally{W.delete(l);}})();return W.set(l,v),v},[p,m,r,n]),f=useCallback(async()=>{e.setActiveAccount(null),await e.clearCache();},[e]);return {account:n,accounts:t,isAuthenticated:d,inProgress:o!==InteractionStatus.None,loginPopup:c,loginRedirect:u,logoutPopup:s,logoutRedirect:h,acquireToken:y,acquireTokenSilent:p,acquireTokenPopup:m,acquireTokenRedirect:g,clearSession:f}}function Le({text:r="Sign in with Microsoft",variant:e="dark",size:t="medium",useRedirect:o=false,scopes:n,className:a="",style:d,onSuccess:c,onError:u}){let{loginPopup:s,loginRedirect:h,inProgress:p}=b(),m=async()=>{try{o?await h(n):await s(n),c?.();}catch(i){u?.(i);}},g={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},f={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:p?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:p?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...g[t],...d};return jsxs("button",{onClick:m,disabled:p,className:a,style:f,"aria-label":r,children:[jsx(ke,{}),jsx("span",{children:r})]})}function ke(){return jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function Ue({text:r="Sign out",variant:e="dark",size:t="medium",useRedirect:o=false,className:n="",style:a,onSuccess:d,onError:c}){let{logoutPopup:u,logoutRedirect:s,inProgress:h}=b(),p=async()=>{try{o?await s():await u(),d?.();}catch(f){c?.(f);}},m={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},y={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:h?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:h?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...m[t],...a};return jsxs("button",{onClick:p,disabled:h,className:n,style:y,"aria-label":r,children:[jsx(Me,{}),jsx("span",{children:r})]})}function Me(){return jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function U(){let{acquireToken:r}=b(),e=useCallback(async(c,u={})=>{let{scopes:s=["User.Read"],version:h="v1.0",debug:p=false,...m}=u;try{let g=await r(s),y=`https://graph.microsoft.com/${h}`,f=c.startsWith("http")?c:`${y}${c.startsWith("/")?c:`/${c}`}`;p&&console.log("[GraphAPI] Request:",{url:f,method:m.method||"GET"});let i=await fetch(f,{...m,headers:{Authorization:`Bearer ${g}`,"Content-Type":"application/json",...m.headers}});if(!i.ok){let A=await i.text(),v=`Graph API error (${i.status}): ${A}`;throw new Error(v)}if(i.status===204||i.headers.get("content-length")==="0")return null;let l=await i.json();return p&&console.log("[GraphAPI] Response:",l),l}catch(g){let y=S(g);throw console.error("[GraphAPI] Request failed:",y),new Error(y)}},[r]),t=useCallback((c,u={})=>e(c,{...u,method:"GET"}),[e]),o=useCallback((c,u,s={})=>e(c,{...s,method:"POST",body:u?JSON.stringify(u):void 0}),[e]),n=useCallback((c,u,s={})=>e(c,{...s,method:"PUT",body:u?JSON.stringify(u):void 0}),[e]),a=useCallback((c,u,s={})=>e(c,{...s,method:"PATCH",body:u?JSON.stringify(u):void 0}),[e]),d=useCallback((c,u={})=>e(c,{...u,method:"DELETE"}),[e]);return {get:t,post:o,put:n,patch:a,delete:d,request:e}}var P=new Map,Fe=300*1e3,ue=100;function Ne(){if(P.size>ue){let r=Array.from(P.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,P.size-ue).forEach(([t])=>{let o=P.get(t);o?.data.photo&&URL.revokeObjectURL(o.data.photo),P.delete(t);});}}function j(){let{isAuthenticated:r,account:e}=b(),t=U(),[o,n]=useState(null),[a,d]=useState(false),[c,u]=useState(null),s=useCallback(async()=>{if(!r||!e){n(null);return}let p=e.homeAccountId,m=P.get(p);if(m&&Date.now()-m.timestamp<Fe){n(m.data);return}d(true),u(null);try{let g=await t.get("/me",{scopes:["User.Read"]}),y;try{let i=await t.get("/me/photo/$value",{scopes:["User.Read"],headers:{"Content-Type":"image/jpeg"}});i&&(y=URL.createObjectURL(i));}catch{console.debug("[UserProfile] Photo not available");}let f={id:g.id,displayName:g.displayName,givenName:g.givenName,surname:g.surname,userPrincipalName:g.userPrincipalName,mail:g.mail,jobTitle:g.jobTitle,officeLocation:g.officeLocation,mobilePhone:g.mobilePhone,businessPhones:g.businessPhones,photo:y};P.set(p,{data:f,timestamp:Date.now()}),Ne(),n(f);}catch(g){let f=S(g),i=new Error(f);u(i),console.error("[UserProfile] Failed to fetch profile:",f);}finally{d(false);}},[r,e,t]),h=useCallback(()=>{if(e){let p=P.get(e.homeAccountId);p?.data.photo&&URL.revokeObjectURL(p.data.photo),P.delete(e.homeAccountId);}o?.photo&&URL.revokeObjectURL(o.photo),n(null);},[e,o]);return useEffect(()=>(s(),()=>{o?.photo&&URL.revokeObjectURL(o.photo);}),[s]),useEffect(()=>()=>{o?.photo&&URL.revokeObjectURL(o.photo);},[o?.photo]),{profile:o,loading:a,error:c,refetch:s,clearCache:h}}function De({size:r=40,className:e="",style:t,showTooltip:o=true,fallbackImage:n}){let{profile:a,loading:d}=j(),[c,u]=useState(null),[s,h]=useState(false);useEffect(()=>{a?.photo&&u(a.photo);},[a?.photo]);let p=()=>{if(!a)return "?";let{givenName:y,surname:f,displayName:i}=a;if(y&&f)return `${y[0]}${f[0]}`.toUpperCase();if(i){let l=i.split(" ");return l.length>=2?`${l[0][0]}${l[l.length-1][0]}`.toUpperCase():i.substring(0,2).toUpperCase()}return "?"},m={width:`${r}px`,height:`${r}px`,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:`${r*.4}px`,fontWeight:600,fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',backgroundColor:"#0078D4",color:"#FFFFFF",overflow:"hidden",userSelect:"none",...t},g=a?.displayName||"User";return d?jsx("div",{className:e,style:{...m,backgroundColor:"#E1E1E1"},"aria-label":"Loading user avatar",children:jsx("span",{style:{fontSize:`${r*.3}px`},children:"..."})}):c&&!s?jsx("div",{className:e,style:m,title:o?g:void 0,"aria-label":`${g} avatar`,children:jsx("img",{src:c,alt:g,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>{h(true),n&&u(n);}})}):jsx("div",{className:e,style:m,title:o?g:void 0,"aria-label":`${g} avatar`,children:p()})}function Oe({className:r="",style:e,showDetails:t=false,renderLoading:o,renderAuthenticated:n,renderUnauthenticated:a}){let{isAuthenticated:d,inProgress:c,account:u}=b(),s={display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"4px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontSize:"14px",fontWeight:500,...e};if(c)return o?jsx(Fragment,{children:o()}):jsxs("div",{className:r,style:{...s,backgroundColor:"#FFF4CE",color:"#8A6D3B"},role:"status","aria-live":"polite",children:[jsx(J,{color:"#FFA500"}),jsx("span",{children:"Loading..."})]});if(d){let h=u?.username||u?.name||"User";return n?jsx(Fragment,{children:n(h)}):jsxs("div",{className:r,style:{...s,backgroundColor:"#D4EDDA",color:"#155724"},role:"status","aria-live":"polite",children:[jsx(J,{color:"#28A745"}),jsx("span",{children:t?`Authenticated as ${h}`:"Authenticated"})]})}return a?jsx(Fragment,{children:a()}):jsxs("div",{className:r,style:{...s,backgroundColor:"#F8D7DA",color:"#721C24"},role:"status","aria-live":"polite",children:[jsx(J,{color:"#DC3545"}),jsx("span",{children:"Not authenticated"})]})}function J({color:r}){return jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsx("circle",{cx:"4",cy:"4",r:"4",fill:r})})}function Q({children:r,loadingComponent:e,fallbackComponent:t,useRedirect:o=true,scopes:n,onAuthRequired:a}){let{isAuthenticated:d,inProgress:c,loginRedirect:u,loginPopup:s}=b();return useEffect(()=>{!d&&!c&&(a?.(),(async()=>{try{o?await u(n):await s(n);}catch(p){console.error("[AuthGuard] Authentication failed:",p);}})());},[d,c,o,n,u,s,a]),c?jsx(Fragment,{children:e||jsx("div",{children:"Authenticating..."})}):d?jsx(Fragment,{children:r}):jsx(Fragment,{children:t||jsx("div",{children:"Redirecting to login..."})})}var ee=class extends Component{constructor(t){super(t);this.reset=()=>{this.setState({hasError:false,error:null});};this.state={hasError:false,error:null};}static getDerivedStateFromError(t){return {hasError:true,error:t}}componentDidCatch(t,o){let{onError:n,debug:a}=this.props;a&&(console.error("[ErrorBoundary] Caught error:",t),console.error("[ErrorBoundary] Error info:",o)),n?.(t,o);}render(){let{hasError:t,error:o}=this.state,{children:n,fallback:a}=this.props;return t&&o?a?a(o,this.reset):jsxs("div",{style:{padding:"20px",margin:"20px",border:"1px solid #DC3545",borderRadius:"4px",backgroundColor:"#F8D7DA",color:"#721C24",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif'},children:[jsx("h2",{style:{margin:"0 0 10px 0",fontSize:"18px"},children:"Authentication Error"}),jsx("p",{style:{margin:"0 0 10px 0"},children:o.message}),jsx("button",{onClick:this.reset,style:{padding:"8px 16px",backgroundColor:"#DC3545",color:"#FFFFFF",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px",fontWeight:600},children:"Try Again"})]}):n}};var R=new Map,Be=300*1e3,de=100;function He(r){r?R.delete(r):R.clear();}function Ve(){if(R.size>de){let r=Array.from(R.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,R.size-de).forEach(([t])=>R.delete(t));}}function We(){let{isAuthenticated:r,account:e}=b(),t=U(),[o,n]=useState([]),[a,d]=useState([]),[c,u]=useState(false),[s,h]=useState(null),p=useCallback(async()=>{if(!r||!e){n([]),d([]);return}let i=e.homeAccountId,l=R.get(i);if(l&&Date.now()-l.timestamp<Be){n(l.roles),d(l.groups);return}u(true),h(null);try{let v=e.idTokenClaims?.roles||[],O=(await t.get("/me/memberOf",{scopes:["User.Read","Directory.Read.All"]})).value.map(te=>te.id);R.set(i,{roles:v,groups:O,timestamp:Date.now()}),Ve(),n(v),d(O);}catch(A){let D=S(A),O=new Error(D);h(O),console.error("[Roles] Failed to fetch roles/groups:",D);let he=e.idTokenClaims?.roles||[];n(he);}finally{u(false);}},[r,e,t]),m=useCallback(i=>o.includes(i),[o]),g=useCallback(i=>a.includes(i),[a]),y=useCallback(i=>i.some(l=>o.includes(l)),[o]),f=useCallback(i=>i.every(l=>o.includes(l)),[o]);return useEffect(()=>(p(),()=>{e&&He(e.homeAccountId);}),[p,e]),{roles:o,groups:a,loading:c,error:s,hasRole:m,hasGroup:g,hasAnyRole:y,hasAllRoles:f,refetch:p}}function _e(r,e={}){let{displayName:t,...o}=e,n=a=>jsx(Q,{...o,children:jsx(r,{...a})});return n.displayName=t||`withAuth(${r.displayName||r.name||"Component"})`,n}async function fe(r,e={}){let{maxRetries:t=3,initialDelay:o=1e3,maxDelay:n=1e4,backoffMultiplier:a=2,debug:d=false}=e,c,u=o;for(let s=0;s<=t;s++)try{return d&&s>0&&console.log(`[TokenRetry] Attempt ${s+1}/${t+1}`),await r()}catch(h){if(c=h,s===t){d&&console.error("[TokenRetry] All retry attempts failed");break}if(!je(h))throw d&&console.log("[TokenRetry] Non-retryable error, aborting"),h;d&&console.warn(`[TokenRetry] Attempt ${s+1} failed, retrying in ${u}ms...`),await Je(u),u=Math.min(u*a,n);}throw c}function je(r){let e=r.message.toLowerCase();return !!(e.includes("network")||e.includes("timeout")||e.includes("fetch")||e.includes("connection")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("429")||e.includes("rate limit")||e.includes("token")&&e.includes("expired"))}function Je(r){return new Promise(e=>setTimeout(e,r))}function Ze(r,e={}){return (...t)=>fe(()=>r(...t),e)}var q=class{constructor(e={}){this.logHistory=[];this.performanceTimings=new Map;this.config={enabled:e.enabled??false,prefix:e.prefix??"[MSAL-Next]",showTimestamp:e.showTimestamp??true,level:e.level??"info",enablePerformance:e.enablePerformance??false,enableNetworkLogs:e.enableNetworkLogs??false,maxHistorySize:e.maxHistorySize??100};}shouldLog(e){if(!this.config.enabled)return false;let t=["error","warn","info","debug"],o=t.indexOf(this.config.level);return t.indexOf(e)<=o}formatMessage(e,t,o){let n=this.config.showTimestamp?`[${new Date().toISOString()}]`:"",a=this.config.prefix,d=`[${e.toUpperCase()}]`,c=`${n} ${a} ${d} ${t}`;return o!==void 0&&(c+=`
2
- `+JSON.stringify(o,null,2)),c}addToHistory(e,t,o){this.logHistory.length>=this.config.maxHistorySize&&this.logHistory.shift(),this.logHistory.push({timestamp:Date.now(),level:e,message:t,data:o});}error(e,t){this.shouldLog("error")&&(console.error(this.formatMessage("error",e,t)),this.addToHistory("error",e,t));}warn(e,t){this.shouldLog("warn")&&(console.warn(this.formatMessage("warn",e,t)),this.addToHistory("warn",e,t));}info(e,t){this.shouldLog("info")&&(console.info(this.formatMessage("info",e,t)),this.addToHistory("info",e,t));}debug(e,t){this.shouldLog("debug")&&(console.debug(this.formatMessage("debug",e,t)),this.addToHistory("debug",e,t));}group(e){this.config.enabled&&console.group(`${this.config.prefix} ${e}`);}groupEnd(){this.config.enabled&&console.groupEnd();}startTiming(e){this.config.enablePerformance&&(this.performanceTimings.set(e,{operation:e,startTime:performance.now()}),this.debug(`\u23F1\uFE0F Started: ${e}`));}endTiming(e){if(this.config.enablePerformance){let t=this.performanceTimings.get(e);if(t)return t.endTime=performance.now(),t.duration=t.endTime-t.startTime,this.info(`\u23F1\uFE0F Completed: ${e} (${t.duration.toFixed(2)}ms)`),t.duration}}logRequest(e,t,o){this.config.enableNetworkLogs&&this.debug(`\u{1F310} ${e} ${t}`,o);}logResponse(e,t,o,n){if(this.config.enableNetworkLogs){let a=o>=200&&o<300?"\u2705":"\u274C";this.debug(`${a} ${e} ${t} - ${o}`,n);}}getHistory(){return [...this.logHistory]}getPerformanceTimings(){return Array.from(this.performanceTimings.values())}clearHistory(){this.logHistory=[];}clearTimings(){this.performanceTimings.clear();}exportLogs(){return JSON.stringify({config:this.config,history:this.logHistory,performanceTimings:Array.from(this.performanceTimings.values()),exportedAt:new Date().toISOString()},null,2)}downloadLogs(e="msal-next-debug-logs.json"){if(typeof window>"u")return;let t=this.exportLogs(),o=new Blob([t],{type:"application/json"}),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n,a.download=e,a.click(),URL.revokeObjectURL(n);}setEnabled(e){this.config.enabled=e;}setLevel(e){e&&(this.config.level=e);}},I=null;function Ke(r){return I?r&&(r.enabled!==void 0&&I.setEnabled(r.enabled),r.level&&I.setLevel(r.level)):I=new q(r),I}function Xe(r,e){return new q({...e,prefix:`[MSAL-Next:${r}]`})}function Qe(r={}){let{protectedRoutes:e=[],publicOnlyRoutes:t=[],loginPath:o="/login",redirectAfterLogin:n="/",sessionCookie:a="msal.account",isAuthenticated:d,debug:c=false}=r;return async function(s){let{pathname:h}=s.nextUrl;c&&console.log("[AuthMiddleware] Processing:",h);let p=false;d?p=await d(s):p=!!s.cookies.get(a)?.value,c&&console.log("[AuthMiddleware] Authenticated:",p);let m=e.some(f=>h.startsWith(f)),g=t.some(f=>h.startsWith(f));if(m&&!p){c&&console.log("[AuthMiddleware] Redirecting to login");let f=s.nextUrl.clone();return f.pathname=o,f.searchParams.set("returnUrl",h),NextResponse.redirect(f)}if(g&&p){c&&console.log("[AuthMiddleware] Redirecting to home");let f=s.nextUrl.searchParams.get("returnUrl"),i=s.nextUrl.clone();return i.pathname=f||n,i.searchParams.delete("returnUrl"),NextResponse.redirect(i)}let y=NextResponse.next();if(p){y.headers.set("x-msal-authenticated","true");try{let f=s.cookies.get(a);if(f?.value){let i=z(f.value,B);i?.username&&y.headers.set("x-msal-username",i.username);}}catch{c&&console.warn("[AuthMiddleware] Failed to parse session data");}}return y}}export{Q as AuthGuard,Oe as AuthStatus,ee as ErrorBoundary,Le as MicrosoftSignInButton,ve as MsalAuthProvider,Ue as SignOutButton,De as UserAvatar,Qe as createAuthMiddleware,H as createMsalConfig,Ze as createRetryWrapper,Xe as createScopedLogger,Ke as getDebugLogger,Pe as getMsalInstance,B as isValidAccountData,G as isValidRedirectUri,oe as isValidScope,fe as retryWithBackoff,z as safeJsonParse,S as sanitizeError,U as useGraphApi,b as useMsalAuth,We as useRoles,j as useUserProfile,me as validateScopes,_e as withAuth};
1
+ import {MsalProvider,useMsal,useAccount}from'@azure/msal-react';export{useAccount,useIsAuthenticated,useMsal}from'@azure/msal-react';import {LogLevel,PublicClientApplication,EventType,InteractionStatus}from'@azure/msal-browser';import {useState,useRef,useEffect,useMemo,useCallback,Component}from'react';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import {NextResponse}from'next/server';function B(r,e){try{let t=JSON.parse(r);return e(t)?t:(console.warn("[Validation] JSON validation failed"),null)}catch(t){return console.error("[Validation] JSON parse error:",t),null}}function _(r){return typeof r=="object"&&r!==null&&typeof r.homeAccountId=="string"&&r.homeAccountId.length>0&&typeof r.username=="string"&&r.username.length>0&&(r.name===void 0||typeof r.name=="string")}function S(r){return r instanceof Error?r.message.replace(/[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g,"[TOKEN_REDACTED]").replace(/[a-f0-9]{32,}/gi,"[SECRET_REDACTED]").replace(/Bearer\s+[^\s]+/gi,"Bearer [REDACTED]"):"An unexpected error occurred"}function $(r,e){try{let t=new URL(r);return e.some(o=>{let n=new URL(o);return t.origin===n.origin})}catch{return false}}function ie(r){return /^[a-zA-Z0-9._-]+$/.test(r)}function Ae(r){return Array.isArray(r)&&r.every(ie)}function H(r){if(r.msalConfig)return r.msalConfig;let{clientId:e,tenantId:t,authorityType:o="common",redirectUri:n,postLogoutRedirectUri:a,cacheLocation:f="sessionStorage",storeAuthStateInCookie:c=false,navigateToLoginRequestUrl:u=true,enableLogging:i=false,loggerCallback:m,allowedRedirectUris:d}=r;if(!e)throw new Error("@chemmangat/msal-next: clientId is required");let p=()=>{if(o==="tenant"){if(!t)throw new Error('@chemmangat/msal-next: tenantId is required when authorityType is "tenant"');return `https://login.microsoftonline.com/${t}`}return `https://login.microsoftonline.com/${o}`},g=typeof window<"u"?window.location.origin:"http://localhost:3000",y=n||g;if(d&&d.length>0){if(!$(y,d))throw new Error(`@chemmangat/msal-next: redirectUri "${y}" is not in the allowed list`);let s=a||y;if(!$(s,d))throw new Error(`@chemmangat/msal-next: postLogoutRedirectUri "${s}" is not in the allowed list`)}return {auth:{clientId:e,authority:p(),redirectUri:y,postLogoutRedirectUri:a||y,navigateToLoginRequestUrl:u},cache:{cacheLocation:f,storeAuthStateInCookie:c},system:{loggerOptions:{loggerCallback:m||((s,l,b)=>{if(!(b||!i))switch(s){case LogLevel.Error:console.error("[MSAL]",l);break;case LogLevel.Warning:console.warn("[MSAL]",l);break;case LogLevel.Info:console.info("[MSAL]",l);break;case LogLevel.Verbose:console.debug("[MSAL]",l);break}}),logLevel:i?LogLevel.Verbose:LogLevel.Error}}}}var ae=null;function Re(){return ae}function V({children:r,loadingComponent:e,onInitialized:t,...o}){let[n,a]=useState(null),f=useRef(null);return useEffect(()=>{if(typeof window>"u"||f.current)return;(async()=>{try{let u=H(o),i=new PublicClientApplication(u);await i.initialize();try{let p=await i.handleRedirectPromise();p&&(o.enableLogging&&console.log("[MSAL] Redirect authentication successful"),p.account&&i.setActiveAccount(p.account));}catch(p){p?.errorCode==="no_token_request_cache_error"?o.enableLogging&&console.log("[MSAL] No pending redirect found (this is normal)"):p?.errorCode==="user_cancelled"?o.enableLogging&&console.log("[MSAL] User cancelled authentication"):console.error("[MSAL] Redirect handling error:",p);}let m=i.getAllAccounts();m.length>0&&!i.getActiveAccount()&&i.setActiveAccount(m[0]);let d=o.enableLogging||!1;i.addEventCallback(p=>{if(p.eventType===EventType.LOGIN_SUCCESS){let g=p.payload;g?.account&&i.setActiveAccount(g.account),d&&console.log("[MSAL] Login successful:",g.account?.username);}if(p.eventType===EventType.LOGIN_FAILURE&&console.error("[MSAL] Login failed:",p.error),p.eventType===EventType.LOGOUT_SUCCESS&&(i.setActiveAccount(null),d&&console.log("[MSAL] Logout successful")),p.eventType===EventType.ACQUIRE_TOKEN_SUCCESS){let g=p.payload;g?.account&&!i.getActiveAccount()&&i.setActiveAccount(g.account);}p.eventType===EventType.ACQUIRE_TOKEN_FAILURE&&d&&console.error("[MSAL] Token acquisition failed:",p.error);}),f.current=i,ae=i,a(i),t&&t(i);}catch(u){throw console.error("[MSAL] Initialization failed:",u),u}})();},[]),typeof window>"u"?jsx(Fragment,{children:e||jsx("div",{children:"Loading authentication..."})}):n?jsx(MsalProvider,{instance:n,children:r}):jsx(Fragment,{children:e||jsx("div",{children:"Loading authentication..."})})}var j=new Map;function A(r=["User.Read"]){let{instance:e,accounts:t,inProgress:o}=useMsal(),n=useAccount(t[0]||null),a=useRef(false),f=useMemo(()=>t.length>0,[t]),c=useCallback(async(s=r)=>{if(o!==InteractionStatus.None){console.warn("[MSAL] Interaction already in progress");return}try{let l={scopes:s,prompt:"select_account"},b=await e.loginPopup(l);b?.account&&e.setActiveAccount(b.account);}catch(l){if(l?.errorCode==="user_cancelled"){console.log("[MSAL] User cancelled login");return}throw console.error("[MSAL] Login popup failed:",l),l}},[e,r,o]),u=useCallback(async(s=r)=>{if(o!==InteractionStatus.None){console.warn("[MSAL] Interaction already in progress");return}try{let l={scopes:s,prompt:"select_account"};await e.loginRedirect(l);}catch(l){if(l?.errorCode==="user_cancelled"){console.log("[MSAL] User cancelled login");return}throw console.error("[MSAL] Login redirect failed:",l),l}},[e,r,o]),i=useCallback(async()=>{try{await e.logoutPopup({account:n||void 0});}catch(s){throw console.error("[MSAL] Logout popup failed:",s),s}},[e,n]),m=useCallback(async()=>{try{await e.logoutRedirect({account:n||void 0});}catch(s){throw console.error("[MSAL] Logout redirect failed:",s),s}},[e,n]),d=useCallback(async(s=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let l={scopes:s,account:n,forceRefresh:!1};return (await e.acquireTokenSilent(l)).accessToken}catch(l){throw console.error("[MSAL] Silent token acquisition failed:",l),l}},[e,n,r]),p=useCallback(async(s=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");if(a.current)throw new Error("[MSAL] Popup already in progress. Please wait.");try{a.current=!0;let l={scopes:s,account:n};return (await e.acquireTokenPopup(l)).accessToken}catch(l){throw console.error("[MSAL] Token popup acquisition failed:",l),l}finally{a.current=false;}},[e,n,r]),g=useCallback(async(s=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let l={scopes:s,account:n};await e.acquireTokenRedirect(l);}catch(l){throw console.error("[MSAL] Token redirect acquisition failed:",l),l}},[e,n,r]),y=useCallback(async(s=r)=>{let l=`${n?.homeAccountId||"anonymous"}-${s.sort().join(",")}`,b=j.get(l);if(b)return b;let w=(async()=>{try{return await d(s)}catch{return console.warn("[MSAL] Silent token acquisition failed, falling back to popup"),await p(s)}finally{j.delete(l);}})();return j.set(l,w),w},[d,p,r,n]),h=useCallback(async()=>{e.setActiveAccount(null),await e.clearCache();},[e]);return {account:n,accounts:t,isAuthenticated:f,inProgress:o!==InteractionStatus.None,loginPopup:c,loginRedirect:u,logoutPopup:i,logoutRedirect:m,acquireToken:y,acquireTokenSilent:d,acquireTokenPopup:p,acquireTokenRedirect:g,clearSession:h}}function Le({text:r="Sign in with Microsoft",variant:e="dark",size:t="medium",useRedirect:o=false,scopes:n,className:a="",style:f,onSuccess:c,onError:u}){let{loginPopup:i,loginRedirect:m,inProgress:d}=A(),p=async()=>{try{o?await m(n):await i(n),c?.();}catch(s){u?.(s);}},g={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},h={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:d?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:d?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...g[t],...f};return jsxs("button",{onClick:p,disabled:d,className:a,style:h,"aria-label":r,children:[jsx(Me,{}),jsx("span",{children:r})]})}function Me(){return jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function Ue({text:r="Sign out",variant:e="dark",size:t="medium",useRedirect:o=false,className:n="",style:a,onSuccess:f,onError:c}){let{logoutPopup:u,logoutRedirect:i,inProgress:m}=A(),d=async()=>{try{o?await i():await u(),f?.();}catch(h){c?.(h);}},p={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},y={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:m?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:m?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...p[t],...a};return jsxs("button",{onClick:d,disabled:m,className:n,style:y,"aria-label":r,children:[jsx(ke,{}),jsx("span",{children:r})]})}function ke(){return jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function k(){let{acquireToken:r}=A(),e=useCallback(async(c,u={})=>{let{scopes:i=["User.Read"],version:m="v1.0",debug:d=false,...p}=u;try{let g=await r(i),y=`https://graph.microsoft.com/${m}`,h=c.startsWith("http")?c:`${y}${c.startsWith("/")?c:`/${c}`}`;d&&console.log("[GraphAPI] Request:",{url:h,method:p.method||"GET"});let s=await fetch(h,{...p,headers:{Authorization:`Bearer ${g}`,"Content-Type":"application/json",...p.headers}});if(!s.ok){let b=await s.text(),w=`Graph API error (${s.status}): ${b}`;throw new Error(w)}if(s.status===204||s.headers.get("content-length")==="0")return null;let l=await s.json();return d&&console.log("[GraphAPI] Response:",l),l}catch(g){let y=S(g);throw console.error("[GraphAPI] Request failed:",y),new Error(y)}},[r]),t=useCallback((c,u={})=>e(c,{...u,method:"GET"}),[e]),o=useCallback((c,u,i={})=>e(c,{...i,method:"POST",body:u?JSON.stringify(u):void 0}),[e]),n=useCallback((c,u,i={})=>e(c,{...i,method:"PUT",body:u?JSON.stringify(u):void 0}),[e]),a=useCallback((c,u,i={})=>e(c,{...i,method:"PATCH",body:u?JSON.stringify(u):void 0}),[e]),f=useCallback((c,u={})=>e(c,{...u,method:"DELETE"}),[e]);return {get:t,post:o,put:n,patch:a,delete:f,request:e}}var P=new Map,Fe=300*1e3,de=100;function Ne(){if(P.size>de){let r=Array.from(P.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,P.size-de).forEach(([t])=>{let o=P.get(t);o?.data.photo&&URL.revokeObjectURL(o.data.photo),P.delete(t);});}}function K(){let{isAuthenticated:r,account:e}=A(),t=k(),[o,n]=useState(null),[a,f]=useState(false),[c,u]=useState(null),i=useCallback(async()=>{if(!r||!e){n(null);return}let d=e.homeAccountId,p=P.get(d);if(p&&Date.now()-p.timestamp<Fe){n(p.data);return}f(true),u(null);try{let g=await t.get("/me",{scopes:["User.Read"]}),y;try{let s=await t.get("/me/photo/$value",{scopes:["User.Read"],headers:{"Content-Type":"image/jpeg"}});s&&(y=URL.createObjectURL(s));}catch{console.debug("[UserProfile] Photo not available");}let h={id:g.id,displayName:g.displayName,givenName:g.givenName,surname:g.surname,userPrincipalName:g.userPrincipalName,mail:g.mail,jobTitle:g.jobTitle,officeLocation:g.officeLocation,mobilePhone:g.mobilePhone,businessPhones:g.businessPhones,photo:y};P.set(d,{data:h,timestamp:Date.now()}),Ne(),n(h);}catch(g){let h=S(g),s=new Error(h);u(s),console.error("[UserProfile] Failed to fetch profile:",h);}finally{f(false);}},[r,e,t]),m=useCallback(()=>{if(e){let d=P.get(e.homeAccountId);d?.data.photo&&URL.revokeObjectURL(d.data.photo),P.delete(e.homeAccountId);}o?.photo&&URL.revokeObjectURL(o.photo),n(null);},[e,o]);return useEffect(()=>(i(),()=>{o?.photo&&URL.revokeObjectURL(o.photo);}),[i]),useEffect(()=>()=>{o?.photo&&URL.revokeObjectURL(o.photo);},[o?.photo]),{profile:o,loading:a,error:c,refetch:i,clearCache:m}}function Oe({size:r=40,className:e="",style:t,showTooltip:o=true,fallbackImage:n}){let{profile:a,loading:f}=K(),[c,u]=useState(null),[i,m]=useState(false);useEffect(()=>{a?.photo&&u(a.photo);},[a?.photo]);let d=()=>{if(!a)return "?";let{givenName:y,surname:h,displayName:s}=a;if(y&&h)return `${y[0]}${h[0]}`.toUpperCase();if(s){let l=s.split(" ");return l.length>=2?`${l[0][0]}${l[l.length-1][0]}`.toUpperCase():s.substring(0,2).toUpperCase()}return "?"},p={width:`${r}px`,height:`${r}px`,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:`${r*.4}px`,fontWeight:600,fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',backgroundColor:"#0078D4",color:"#FFFFFF",overflow:"hidden",userSelect:"none",...t},g=a?.displayName||"User";return f?jsx("div",{className:e,style:{...p,backgroundColor:"#E1E1E1"},"aria-label":"Loading user avatar",children:jsx("span",{style:{fontSize:`${r*.3}px`},children:"..."})}):c&&!i?jsx("div",{className:e,style:p,title:o?g:void 0,"aria-label":`${g} avatar`,children:jsx("img",{src:c,alt:g,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>{m(true),n&&u(n);}})}):jsx("div",{className:e,style:p,title:o?g:void 0,"aria-label":`${g} avatar`,children:d()})}function De({className:r="",style:e,showDetails:t=false,renderLoading:o,renderAuthenticated:n,renderUnauthenticated:a}){let{isAuthenticated:f,inProgress:c,account:u}=A(),i={display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"4px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontSize:"14px",fontWeight:500,...e};if(c)return o?jsx(Fragment,{children:o()}):jsxs("div",{className:r,style:{...i,backgroundColor:"#FFF4CE",color:"#8A6D3B"},role:"status","aria-live":"polite",children:[jsx(Z,{color:"#FFA500"}),jsx("span",{children:"Loading..."})]});if(f){let m=u?.username||u?.name||"User";return n?jsx(Fragment,{children:n(m)}):jsxs("div",{className:r,style:{...i,backgroundColor:"#D4EDDA",color:"#155724"},role:"status","aria-live":"polite",children:[jsx(Z,{color:"#28A745"}),jsx("span",{children:t?`Authenticated as ${m}`:"Authenticated"})]})}return a?jsx(Fragment,{children:a()}):jsxs("div",{className:r,style:{...i,backgroundColor:"#F8D7DA",color:"#721C24"},role:"status","aria-live":"polite",children:[jsx(Z,{color:"#DC3545"}),jsx("span",{children:"Not authenticated"})]})}function Z({color:r}){return jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsx("circle",{cx:"4",cy:"4",r:"4",fill:r})})}function ee({children:r,loadingComponent:e,fallbackComponent:t,useRedirect:o=true,scopes:n,onAuthRequired:a}){let{isAuthenticated:f,inProgress:c,loginRedirect:u,loginPopup:i}=A();return useEffect(()=>{!f&&!c&&(a?.(),(async()=>{try{o?await u(n):await i(n);}catch(d){console.error("[AuthGuard] Authentication failed:",d);}})());},[f,c,o,n,u,i,a]),c?jsx(Fragment,{children:e||jsx("div",{children:"Authenticating..."})}):f?jsx(Fragment,{children:r}):jsx(Fragment,{children:t||jsx("div",{children:"Redirecting to login..."})})}var te=class extends Component{constructor(t){super(t);this.reset=()=>{this.setState({hasError:false,error:null});};this.state={hasError:false,error:null};}static getDerivedStateFromError(t){return {hasError:true,error:t}}componentDidCatch(t,o){let{onError:n,debug:a}=this.props;a&&(console.error("[ErrorBoundary] Caught error:",t),console.error("[ErrorBoundary] Error info:",o)),n?.(t,o);}render(){let{hasError:t,error:o}=this.state,{children:n,fallback:a}=this.props;return t&&o?a?a(o,this.reset):jsxs("div",{style:{padding:"20px",margin:"20px",border:"1px solid #DC3545",borderRadius:"4px",backgroundColor:"#F8D7DA",color:"#721C24",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif'},children:[jsx("h2",{style:{margin:"0 0 10px 0",fontSize:"18px"},children:"Authentication Error"}),jsx("p",{style:{margin:"0 0 10px 0"},children:o.message}),jsx("button",{onClick:this.reset,style:{padding:"8px 16px",backgroundColor:"#DC3545",color:"#FFFFFF",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px",fontWeight:600},children:"Try Again"})]}):n}};function ze({children:r,...e}){return jsx(V,{...e,children:r})}var R=new Map,He=300*1e3,fe=100;function Ve(r){r?R.delete(r):R.clear();}function We(){if(R.size>fe){let r=Array.from(R.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,R.size-fe).forEach(([t])=>R.delete(t));}}function je(){let{isAuthenticated:r,account:e}=A(),t=k(),[o,n]=useState([]),[a,f]=useState([]),[c,u]=useState(false),[i,m]=useState(null),d=useCallback(async()=>{if(!r||!e){n([]),f([]);return}let s=e.homeAccountId,l=R.get(s);if(l&&Date.now()-l.timestamp<He){n(l.roles),f(l.groups);return}u(true),m(null);try{let w=e.idTokenClaims?.roles||[],G=(await t.get("/me/memberOf",{scopes:["User.Read","Directory.Read.All"]})).value.map(ne=>ne.id);R.set(s,{roles:w,groups:G,timestamp:Date.now()}),We(),n(w),f(G);}catch(b){let D=S(b),G=new Error(D);m(G),console.error("[Roles] Failed to fetch roles/groups:",D);let ye=e.idTokenClaims?.roles||[];n(ye);}finally{u(false);}},[r,e,t]),p=useCallback(s=>o.includes(s),[o]),g=useCallback(s=>a.includes(s),[a]),y=useCallback(s=>s.some(l=>o.includes(l)),[o]),h=useCallback(s=>s.every(l=>o.includes(l)),[o]);return useEffect(()=>(d(),()=>{e&&Ve(e.homeAccountId);}),[d,e]),{roles:o,groups:a,loading:c,error:i,hasRole:p,hasGroup:g,hasAnyRole:y,hasAllRoles:h,refetch:d}}function Je(r,e={}){let{displayName:t,...o}=e,n=a=>jsx(ee,{...o,children:jsx(r,{...a})});return n.displayName=t||`withAuth(${r.displayName||r.name||"Component"})`,n}async function me(r,e={}){let{maxRetries:t=3,initialDelay:o=1e3,maxDelay:n=1e4,backoffMultiplier:a=2,debug:f=false}=e,c,u=o;for(let i=0;i<=t;i++)try{return f&&i>0&&console.log(`[TokenRetry] Attempt ${i+1}/${t+1}`),await r()}catch(m){if(c=m,i===t){f&&console.error("[TokenRetry] All retry attempts failed");break}if(!Ke(m))throw f&&console.log("[TokenRetry] Non-retryable error, aborting"),m;f&&console.warn(`[TokenRetry] Attempt ${i+1} failed, retrying in ${u}ms...`),await Ze(u),u=Math.min(u*a,n);}throw c}function Ke(r){let e=r.message.toLowerCase();return !!(e.includes("network")||e.includes("timeout")||e.includes("fetch")||e.includes("connection")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("429")||e.includes("rate limit")||e.includes("token")&&e.includes("expired"))}function Ze(r){return new Promise(e=>setTimeout(e,r))}function Qe(r,e={}){return (...t)=>me(()=>r(...t),e)}var z=class{constructor(e={}){this.logHistory=[];this.performanceTimings=new Map;this.config={enabled:e.enabled??false,prefix:e.prefix??"[MSAL-Next]",showTimestamp:e.showTimestamp??true,level:e.level??"info",enablePerformance:e.enablePerformance??false,enableNetworkLogs:e.enableNetworkLogs??false,maxHistorySize:e.maxHistorySize??100};}shouldLog(e){if(!this.config.enabled)return false;let t=["error","warn","info","debug"],o=t.indexOf(this.config.level);return t.indexOf(e)<=o}formatMessage(e,t,o){let n=this.config.showTimestamp?`[${new Date().toISOString()}]`:"",a=this.config.prefix,f=`[${e.toUpperCase()}]`,c=`${n} ${a} ${f} ${t}`;return o!==void 0&&(c+=`
2
+ `+JSON.stringify(o,null,2)),c}addToHistory(e,t,o){this.logHistory.length>=this.config.maxHistorySize&&this.logHistory.shift(),this.logHistory.push({timestamp:Date.now(),level:e,message:t,data:o});}error(e,t){this.shouldLog("error")&&(console.error(this.formatMessage("error",e,t)),this.addToHistory("error",e,t));}warn(e,t){this.shouldLog("warn")&&(console.warn(this.formatMessage("warn",e,t)),this.addToHistory("warn",e,t));}info(e,t){this.shouldLog("info")&&(console.info(this.formatMessage("info",e,t)),this.addToHistory("info",e,t));}debug(e,t){this.shouldLog("debug")&&(console.debug(this.formatMessage("debug",e,t)),this.addToHistory("debug",e,t));}group(e){this.config.enabled&&console.group(`${this.config.prefix} ${e}`);}groupEnd(){this.config.enabled&&console.groupEnd();}startTiming(e){this.config.enablePerformance&&(this.performanceTimings.set(e,{operation:e,startTime:performance.now()}),this.debug(`\u23F1\uFE0F Started: ${e}`));}endTiming(e){if(this.config.enablePerformance){let t=this.performanceTimings.get(e);if(t)return t.endTime=performance.now(),t.duration=t.endTime-t.startTime,this.info(`\u23F1\uFE0F Completed: ${e} (${t.duration.toFixed(2)}ms)`),t.duration}}logRequest(e,t,o){this.config.enableNetworkLogs&&this.debug(`\u{1F310} ${e} ${t}`,o);}logResponse(e,t,o,n){if(this.config.enableNetworkLogs){let a=o>=200&&o<300?"\u2705":"\u274C";this.debug(`${a} ${e} ${t} - ${o}`,n);}}getHistory(){return [...this.logHistory]}getPerformanceTimings(){return Array.from(this.performanceTimings.values())}clearHistory(){this.logHistory=[];}clearTimings(){this.performanceTimings.clear();}exportLogs(){return JSON.stringify({config:this.config,history:this.logHistory,performanceTimings:Array.from(this.performanceTimings.values()),exportedAt:new Date().toISOString()},null,2)}downloadLogs(e="msal-next-debug-logs.json"){if(typeof window>"u")return;let t=this.exportLogs(),o=new Blob([t],{type:"application/json"}),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n,a.download=e,a.click(),URL.revokeObjectURL(n);}setEnabled(e){this.config.enabled=e;}setLevel(e){e&&(this.config.level=e);}},O=null;function Xe(r){return O?r&&(r.enabled!==void 0&&O.setEnabled(r.enabled),r.level&&O.setLevel(r.level)):O=new z(r),O}function Ye(r,e){return new z({...e,prefix:`[MSAL-Next:${r}]`})}function er(r={}){let{protectedRoutes:e=[],publicOnlyRoutes:t=[],loginPath:o="/login",redirectAfterLogin:n="/",sessionCookie:a="msal.account",isAuthenticated:f,debug:c=false}=r;return async function(i){let{pathname:m}=i.nextUrl;c&&console.log("[AuthMiddleware] Processing:",m);let d=false;f?d=await f(i):d=!!i.cookies.get(a)?.value,c&&console.log("[AuthMiddleware] Authenticated:",d);let p=e.some(h=>m.startsWith(h)),g=t.some(h=>m.startsWith(h));if(p&&!d){c&&console.log("[AuthMiddleware] Redirecting to login");let h=i.nextUrl.clone();return h.pathname=o,h.searchParams.set("returnUrl",m),NextResponse.redirect(h)}if(g&&d){c&&console.log("[AuthMiddleware] Redirecting to home");let h=i.nextUrl.searchParams.get("returnUrl"),s=i.nextUrl.clone();return s.pathname=h||n,s.searchParams.delete("returnUrl"),NextResponse.redirect(s)}let y=NextResponse.next();if(d){y.headers.set("x-msal-authenticated","true");try{let h=i.cookies.get(a);if(h?.value){let s=B(h.value,_);s?.username&&y.headers.set("x-msal-username",s.username);}}catch{c&&console.warn("[AuthMiddleware] Failed to parse session data");}}return y}}export{ee as AuthGuard,De as AuthStatus,te as ErrorBoundary,Le as MicrosoftSignInButton,V as MsalAuthProvider,ze as Providers,Ue as SignOutButton,Oe as UserAvatar,er as createAuthMiddleware,H as createMsalConfig,Qe as createRetryWrapper,Ye as createScopedLogger,Xe as getDebugLogger,Re as getMsalInstance,_ as isValidAccountData,$ as isValidRedirectUri,ie as isValidScope,me as retryWithBackoff,B as safeJsonParse,S as sanitizeError,k as useGraphApi,A as useMsalAuth,je as useRoles,K as useUserProfile,Ae as validateScopes,Je as withAuth};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
- {
1
+ {
2
2
  "name": "@chemmangat/msal-next",
3
- "version": "3.0.0",
3
+ "version": "3.0.2",
4
4
  "description": "Production-grade MSAL authentication package for Next.js App Router with minimal boilerplate",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -74,4 +74,4 @@
74
74
  "typescript": "^5.3.0",
75
75
  "vitest": "^1.0.0"
76
76
  }
77
- }
77
+ }