@chemmangat/msal-next 1.2.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,425 +1,2 @@
1
- "use client";
2
- "use strict";
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
-
21
- // src/index.ts
22
- var index_exports = {};
23
- __export(index_exports, {
24
- MicrosoftSignInButton: () => MicrosoftSignInButton,
25
- MsalAuthProvider: () => MsalAuthProvider,
26
- getMsalInstance: () => getMsalInstance,
27
- useAccount: () => import_msal_react3.useAccount,
28
- useIsAuthenticated: () => import_msal_react3.useIsAuthenticated,
29
- useMsal: () => import_msal_react3.useMsal,
30
- useMsalAuth: () => useMsalAuth
31
- });
32
- module.exports = __toCommonJS(index_exports);
33
-
34
- // src/components/MsalAuthProvider.tsx
35
- var import_msal_react = require("@azure/msal-react");
36
- var import_msal_browser2 = require("@azure/msal-browser");
37
- var import_react = require("react");
38
-
39
- // src/utils/createMsalConfig.ts
40
- var import_msal_browser = require("@azure/msal-browser");
41
- function createMsalConfig(config) {
42
- if (config.msalConfig) {
43
- return config.msalConfig;
44
- }
45
- const {
46
- clientId,
47
- tenantId,
48
- authorityType = "common",
49
- redirectUri,
50
- postLogoutRedirectUri,
51
- cacheLocation = "sessionStorage",
52
- storeAuthStateInCookie = false,
53
- navigateToLoginRequestUrl = true,
54
- enableLogging = false,
55
- loggerCallback
56
- } = config;
57
- if (!clientId) {
58
- throw new Error("@chemmangat/msal-next: clientId is required");
59
- }
60
- const getAuthority = () => {
61
- if (authorityType === "tenant") {
62
- if (!tenantId) {
63
- throw new Error('@chemmangat/msal-next: tenantId is required when authorityType is "tenant"');
64
- }
65
- return `https://login.microsoftonline.com/${tenantId}`;
66
- }
67
- return `https://login.microsoftonline.com/${authorityType}`;
68
- };
69
- const defaultRedirectUri = typeof window !== "undefined" ? window.location.origin : "http://localhost:3000";
70
- const finalRedirectUri = redirectUri || defaultRedirectUri;
71
- const msalConfig = {
72
- auth: {
73
- clientId,
74
- authority: getAuthority(),
75
- redirectUri: finalRedirectUri,
76
- postLogoutRedirectUri: postLogoutRedirectUri || finalRedirectUri,
77
- navigateToLoginRequestUrl
78
- },
79
- cache: {
80
- cacheLocation,
81
- storeAuthStateInCookie
82
- },
83
- system: {
84
- loggerOptions: {
85
- loggerCallback: loggerCallback || ((level, message, containsPii) => {
86
- if (containsPii || !enableLogging) return;
87
- switch (level) {
88
- case import_msal_browser.LogLevel.Error:
89
- console.error("[MSAL]", message);
90
- break;
91
- case import_msal_browser.LogLevel.Warning:
92
- console.warn("[MSAL]", message);
93
- break;
94
- case import_msal_browser.LogLevel.Info:
95
- console.info("[MSAL]", message);
96
- break;
97
- case import_msal_browser.LogLevel.Verbose:
98
- console.debug("[MSAL]", message);
99
- break;
100
- }
101
- }),
102
- logLevel: enableLogging ? import_msal_browser.LogLevel.Verbose : import_msal_browser.LogLevel.Error
103
- }
104
- }
105
- };
106
- return msalConfig;
107
- }
108
-
109
- // src/components/MsalAuthProvider.tsx
110
- var import_jsx_runtime = require("react/jsx-runtime");
111
- var globalMsalInstance = null;
112
- function getMsalInstance() {
113
- return globalMsalInstance;
114
- }
115
- function MsalAuthProvider({ children, loadingComponent, onInitialized, ...config }) {
116
- const [msalInstance, setMsalInstance] = (0, import_react.useState)(null);
117
- const instanceRef = (0, import_react.useRef)(null);
118
- (0, import_react.useEffect)(() => {
119
- if (typeof window === "undefined") {
120
- return;
121
- }
122
- if (instanceRef.current) {
123
- return;
124
- }
125
- const initializeMsal = async () => {
126
- try {
127
- const msalConfig = createMsalConfig(config);
128
- const instance = new import_msal_browser2.PublicClientApplication(msalConfig);
129
- await instance.initialize();
130
- const response = await instance.handleRedirectPromise();
131
- if (response && config.enableLogging) {
132
- console.log("[MSAL] Redirect authentication successful");
133
- }
134
- const enableLogging = config.enableLogging || false;
135
- instance.addEventCallback((event) => {
136
- if (event.eventType === import_msal_browser2.EventType.LOGIN_SUCCESS) {
137
- if (enableLogging) {
138
- const payload = event.payload;
139
- console.log("[MSAL] Login successful:", payload.account?.username);
140
- }
141
- }
142
- if (event.eventType === import_msal_browser2.EventType.LOGIN_FAILURE) {
143
- console.error("[MSAL] Login failed:", event.error);
144
- }
145
- if (event.eventType === import_msal_browser2.EventType.LOGOUT_SUCCESS) {
146
- if (enableLogging) {
147
- console.log("[MSAL] Logout successful");
148
- }
149
- }
150
- });
151
- instanceRef.current = instance;
152
- globalMsalInstance = instance;
153
- setMsalInstance(instance);
154
- if (onInitialized) {
155
- onInitialized(instance);
156
- }
157
- } catch (error) {
158
- console.error("[MSAL] Initialization failed:", error);
159
- throw error;
160
- }
161
- };
162
- initializeMsal();
163
- }, []);
164
- if (typeof window === "undefined") {
165
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: loadingComponent || /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: "Loading authentication..." }) });
166
- }
167
- if (!msalInstance) {
168
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: loadingComponent || /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: "Loading authentication..." }) });
169
- }
170
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_msal_react.MsalProvider, { instance: msalInstance, children });
171
- }
172
-
173
- // src/hooks/useMsalAuth.ts
174
- var import_msal_react2 = require("@azure/msal-react");
175
- var import_msal_browser3 = require("@azure/msal-browser");
176
- var import_react2 = require("react");
177
- function useMsalAuth(defaultScopes = ["User.Read"]) {
178
- const { instance, accounts, inProgress } = (0, import_msal_react2.useMsal)();
179
- const account = (0, import_msal_react2.useAccount)(accounts[0] || null);
180
- const isAuthenticated = (0, import_react2.useMemo)(() => accounts.length > 0, [accounts]);
181
- const loginPopup = (0, import_react2.useCallback)(
182
- async (scopes = defaultScopes) => {
183
- try {
184
- const request = {
185
- scopes,
186
- prompt: "select_account"
187
- };
188
- await instance.loginPopup(request);
189
- } catch (error) {
190
- console.error("[MSAL] Login popup failed:", error);
191
- throw error;
192
- }
193
- },
194
- [instance, defaultScopes]
195
- );
196
- const loginRedirect = (0, import_react2.useCallback)(
197
- async (scopes = defaultScopes) => {
198
- try {
199
- const request = {
200
- scopes,
201
- prompt: "select_account"
202
- };
203
- await instance.loginRedirect(request);
204
- } catch (error) {
205
- console.error("[MSAL] Login redirect failed:", error);
206
- throw error;
207
- }
208
- },
209
- [instance, defaultScopes]
210
- );
211
- const logoutPopup = (0, import_react2.useCallback)(async () => {
212
- try {
213
- await instance.logoutPopup({
214
- account: account || void 0
215
- });
216
- } catch (error) {
217
- console.error("[MSAL] Logout popup failed:", error);
218
- throw error;
219
- }
220
- }, [instance, account]);
221
- const logoutRedirect = (0, import_react2.useCallback)(async () => {
222
- try {
223
- await instance.logoutRedirect({
224
- account: account || void 0
225
- });
226
- } catch (error) {
227
- console.error("[MSAL] Logout redirect failed:", error);
228
- throw error;
229
- }
230
- }, [instance, account]);
231
- const acquireTokenSilent = (0, import_react2.useCallback)(
232
- async (scopes = defaultScopes) => {
233
- if (!account) {
234
- throw new Error("[MSAL] No active account. Please login first.");
235
- }
236
- try {
237
- const request = {
238
- scopes,
239
- account
240
- };
241
- const response = await instance.acquireTokenSilent(request);
242
- return response.accessToken;
243
- } catch (error) {
244
- console.error("[MSAL] Silent token acquisition failed:", error);
245
- throw error;
246
- }
247
- },
248
- [instance, account, defaultScopes]
249
- );
250
- const acquireTokenPopup = (0, import_react2.useCallback)(
251
- async (scopes = defaultScopes) => {
252
- if (!account) {
253
- throw new Error("[MSAL] No active account. Please login first.");
254
- }
255
- try {
256
- const request = {
257
- scopes,
258
- account
259
- };
260
- const response = await instance.acquireTokenPopup(request);
261
- return response.accessToken;
262
- } catch (error) {
263
- console.error("[MSAL] Token popup acquisition failed:", error);
264
- throw error;
265
- }
266
- },
267
- [instance, account, defaultScopes]
268
- );
269
- const acquireTokenRedirect = (0, import_react2.useCallback)(
270
- async (scopes = defaultScopes) => {
271
- if (!account) {
272
- throw new Error("[MSAL] No active account. Please login first.");
273
- }
274
- try {
275
- const request = {
276
- scopes,
277
- account
278
- };
279
- await instance.acquireTokenRedirect(request);
280
- } catch (error) {
281
- console.error("[MSAL] Token redirect acquisition failed:", error);
282
- throw error;
283
- }
284
- },
285
- [instance, account, defaultScopes]
286
- );
287
- const acquireToken = (0, import_react2.useCallback)(
288
- async (scopes = defaultScopes) => {
289
- try {
290
- return await acquireTokenSilent(scopes);
291
- } catch (error) {
292
- console.warn("[MSAL] Silent token acquisition failed, falling back to popup");
293
- return await acquireTokenPopup(scopes);
294
- }
295
- },
296
- [acquireTokenSilent, acquireTokenPopup, defaultScopes]
297
- );
298
- const clearSession = (0, import_react2.useCallback)(async () => {
299
- instance.setActiveAccount(null);
300
- await instance.clearCache();
301
- }, [instance]);
302
- return {
303
- account,
304
- accounts,
305
- isAuthenticated,
306
- inProgress: inProgress !== import_msal_browser3.InteractionStatus.None,
307
- loginPopup,
308
- loginRedirect,
309
- logoutPopup,
310
- logoutRedirect,
311
- acquireToken,
312
- acquireTokenSilent,
313
- acquireTokenPopup,
314
- acquireTokenRedirect,
315
- clearSession
316
- };
317
- }
318
-
319
- // src/components/MicrosoftSignInButton.tsx
320
- var import_jsx_runtime2 = require("react/jsx-runtime");
321
- function MicrosoftSignInButton({
322
- text = "Sign in with Microsoft",
323
- variant = "dark",
324
- size = "medium",
325
- useRedirect = false,
326
- scopes,
327
- className = "",
328
- style,
329
- onSuccess,
330
- onError
331
- }) {
332
- const { loginPopup, loginRedirect, inProgress } = useMsalAuth();
333
- const handleClick = async () => {
334
- try {
335
- if (useRedirect) {
336
- await loginRedirect(scopes);
337
- } else {
338
- await loginPopup(scopes);
339
- }
340
- onSuccess?.();
341
- } catch (error) {
342
- onError?.(error);
343
- }
344
- };
345
- const sizeStyles = {
346
- small: {
347
- padding: "8px 16px",
348
- fontSize: "14px",
349
- height: "36px"
350
- },
351
- medium: {
352
- padding: "10px 20px",
353
- fontSize: "15px",
354
- height: "41px"
355
- },
356
- large: {
357
- padding: "12px 24px",
358
- fontSize: "16px",
359
- height: "48px"
360
- }
361
- };
362
- const variantStyles = {
363
- dark: {
364
- backgroundColor: "#2F2F2F",
365
- color: "#FFFFFF",
366
- border: "1px solid #8C8C8C"
367
- },
368
- light: {
369
- backgroundColor: "#FFFFFF",
370
- color: "#5E5E5E",
371
- border: "1px solid #8C8C8C"
372
- }
373
- };
374
- const baseStyles = {
375
- display: "inline-flex",
376
- alignItems: "center",
377
- justifyContent: "center",
378
- gap: "12px",
379
- fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',
380
- fontWeight: 600,
381
- borderRadius: "2px",
382
- cursor: inProgress ? "not-allowed" : "pointer",
383
- transition: "all 0.2s ease",
384
- opacity: inProgress ? 0.6 : 1,
385
- ...variantStyles[variant],
386
- ...sizeStyles[size],
387
- ...style
388
- };
389
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
390
- "button",
391
- {
392
- onClick: handleClick,
393
- disabled: inProgress,
394
- className,
395
- style: baseStyles,
396
- "aria-label": text,
397
- children: [
398
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(MicrosoftLogo, {}),
399
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: text })
400
- ]
401
- }
402
- );
403
- }
404
- function MicrosoftLogo() {
405
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("svg", { width: "21", height: "21", viewBox: "0 0 21 21", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [
406
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("rect", { width: "10", height: "10", fill: "#F25022" }),
407
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("rect", { x: "11", width: "10", height: "10", fill: "#7FBA00" }),
408
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("rect", { y: "11", width: "10", height: "10", fill: "#00A4EF" }),
409
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("rect", { x: "11", y: "11", width: "10", height: "10", fill: "#FFB900" })
410
- ] });
411
- }
412
-
413
- // src/index.ts
414
- var import_msal_react3 = require("@azure/msal-react");
415
- // Annotate the CommonJS export names for ESM import in node:
416
- 0 && (module.exports = {
417
- MicrosoftSignInButton,
418
- MsalAuthProvider,
419
- getMsalInstance,
420
- useAccount,
421
- useIsAuthenticated,
422
- useMsal,
423
- useMsalAuth
424
- });
425
- //# sourceMappingURL=index.js.map
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 G(r){if(r.msalConfig)return r.msalConfig;let{clientId:e,tenantId:o,authorityType:s="common",redirectUri:n,postLogoutRedirectUri:u,cacheLocation:p="sessionStorage",storeAuthStateInCookie:l=false,navigateToLoginRequestUrl:c=true,enableLogging:i=false,loggerCallback:f}=r;if(!e)throw new Error("@chemmangat/msal-next: clientId is required");let g=()=>{if(s==="tenant"){if(!o)throw new Error('@chemmangat/msal-next: tenantId is required when authorityType is "tenant"');return `https://login.microsoftonline.com/${o}`}return `https://login.microsoftonline.com/${s}`},h=typeof window<"u"?window.location.origin:"http://localhost:3000",d=n||h;return {auth:{clientId:e,authority:g(),redirectUri:d,postLogoutRedirectUri:u||d,navigateToLoginRequestUrl:c},cache:{cacheLocation:p,storeAuthStateInCookie:l},system:{loggerOptions:{loggerCallback:f||((a,t,y)=>{if(!(y||!i))switch(a){case msalBrowser.LogLevel.Error:console.error("[MSAL]",t);break;case msalBrowser.LogLevel.Warning:console.warn("[MSAL]",t);break;case msalBrowser.LogLevel.Info:console.info("[MSAL]",t);break;case msalBrowser.LogLevel.Verbose:console.debug("[MSAL]",t);break}}),logLevel:i?msalBrowser.LogLevel.Verbose:msalBrowser.LogLevel.Error}}}}var Q=null;function pe(){return Q}function de({children:r,loadingComponent:e,onInitialized:o,...s}){let[n,u]=react.useState(null),p=react.useRef(null);return react.useEffect(()=>{if(typeof window>"u"||p.current)return;(async()=>{try{let c=G(s),i=new msalBrowser.PublicClientApplication(c);await i.initialize(),await i.handleRedirectPromise()&&s.enableLogging&&console.log("[MSAL] Redirect authentication successful");let g=s.enableLogging||!1;i.addEventCallback(h=>{if(h.eventType===msalBrowser.EventType.LOGIN_SUCCESS&&g){let d=h.payload;console.log("[MSAL] Login successful:",d.account?.username);}h.eventType===msalBrowser.EventType.LOGIN_FAILURE&&console.error("[MSAL] Login failed:",h.error),h.eventType===msalBrowser.EventType.LOGOUT_SUCCESS&&g&&console.log("[MSAL] Logout successful");}),p.current=i,Q=i,u(i),o&&o(i);}catch(c){throw console.error("[MSAL] Initialization failed:",c),c}})();},[]),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..."})})}function A(r=["User.Read"]){let{instance:e,accounts:o,inProgress:s}=msalReact.useMsal(),n=msalReact.useAccount(o[0]||null),u=react.useMemo(()=>o.length>0,[o]),p=react.useCallback(async(a=r)=>{try{let t={scopes:a,prompt:"select_account"};await e.loginPopup(t);}catch(t){throw console.error("[MSAL] Login popup failed:",t),t}},[e,r]),l=react.useCallback(async(a=r)=>{try{let t={scopes:a,prompt:"select_account"};await e.loginRedirect(t);}catch(t){throw console.error("[MSAL] Login redirect failed:",t),t}},[e,r]),c=react.useCallback(async()=>{try{await e.logoutPopup({account:n||void 0});}catch(a){throw console.error("[MSAL] Logout popup failed:",a),a}},[e,n]),i=react.useCallback(async()=>{try{await e.logoutRedirect({account:n||void 0});}catch(a){throw console.error("[MSAL] Logout redirect failed:",a),a}},[e,n]),f=react.useCallback(async(a=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let t={scopes:a,account:n,forceRefresh:!1};return (await e.acquireTokenSilent(t)).accessToken}catch(t){throw console.error("[MSAL] Silent token acquisition failed:",t),t}},[e,n,r]),g=react.useCallback(async(a=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let t={scopes:a,account:n};return (await e.acquireTokenPopup(t)).accessToken}catch(t){throw console.error("[MSAL] Token popup acquisition failed:",t),t}},[e,n,r]),h=react.useCallback(async(a=r)=>{if(!n)throw new Error("[MSAL] No active account. Please login first.");try{let t={scopes:a,account:n};await e.acquireTokenRedirect(t);}catch(t){throw console.error("[MSAL] Token redirect acquisition failed:",t),t}},[e,n,r]),d=react.useCallback(async(a=r)=>{try{return await f(a)}catch{return console.warn("[MSAL] Silent token acquisition failed, falling back to popup"),await g(a)}},[f,g,r]),m=react.useCallback(async()=>{e.setActiveAccount(null),await e.clearCache();},[e]);return {account:n,accounts:o,isAuthenticated:u,inProgress:s!==msalBrowser.InteractionStatus.None,loginPopup:p,loginRedirect:l,logoutPopup:c,logoutRedirect:i,acquireToken:d,acquireTokenSilent:f,acquireTokenPopup:g,acquireTokenRedirect:h,clearSession:m}}function ye({text:r="Sign in with Microsoft",variant:e="dark",size:o="medium",useRedirect:s=false,scopes:n,className:u="",style:p,onSuccess:l,onError:c}){let{loginPopup:i,loginRedirect:f,inProgress:g}=A(),h=async()=>{try{s?await f(n):await i(n),l?.();}catch(t){c?.(t);}},d={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},a={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:g?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:g?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...d[o],...p};return jsxRuntime.jsxs("button",{onClick:h,disabled:g,className:u,style:a,"aria-label":r,children:[jsxRuntime.jsx(Ae,{}),jsxRuntime.jsx("span",{children:r})]})}function Ae(){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 be({text:r="Sign out",variant:e="dark",size:o="medium",useRedirect:s=false,className:n="",style:u,onSuccess:p,onError:l}){let{logoutPopup:c,logoutRedirect:i,inProgress:f}=A(),g=async()=>{try{s?await i():await c(),p?.();}catch(a){l?.(a);}},h={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},m={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:f?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:f?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...h[o],...u};return jsxRuntime.jsxs("button",{onClick:g,disabled:f,className:n,style:m,"aria-label":r,children:[jsxRuntime.jsx(xe,{}),jsxRuntime.jsx("span",{children:r})]})}function xe(){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 T(){let{acquireToken:r}=A(),e=react.useCallback(async(l,c={})=>{let{scopes:i=["User.Read"],version:f="v1.0",debug:g=false,...h}=c;try{let d=await r(i),m=`https://graph.microsoft.com/${f}`,a=l.startsWith("http")?l:`${m}${l.startsWith("/")?l:`/${l}`}`;g&&console.log("[GraphAPI] Request:",{url:a,method:h.method||"GET"});let t=await fetch(a,{...h,headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json",...h.headers}});if(!t.ok){let U=await t.text();throw new Error(`Graph API error (${t.status}): ${U}`)}if(t.status===204||t.headers.get("content-length")==="0")return null;let y=await t.json();return g&&console.log("[GraphAPI] Response:",y),y}catch(d){throw console.error("[GraphAPI] Request failed:",d),d}},[r]),o=react.useCallback((l,c={})=>e(l,{...c,method:"GET"}),[e]),s=react.useCallback((l,c,i={})=>e(l,{...i,method:"POST",body:c?JSON.stringify(c):void 0}),[e]),n=react.useCallback((l,c,i={})=>e(l,{...i,method:"PUT",body:c?JSON.stringify(c):void 0}),[e]),u=react.useCallback((l,c,i={})=>e(l,{...i,method:"PATCH",body:c?JSON.stringify(c):void 0}),[e]),p=react.useCallback((l,c={})=>e(l,{...c,method:"DELETE"}),[e]);return {get:o,post:s,put:n,patch:u,delete:p,request:e}}var q=new Map,ve=300*1e3;function B(){let{isAuthenticated:r,account:e}=A(),o=T(),[s,n]=react.useState(null),[u,p]=react.useState(false),[l,c]=react.useState(null),i=react.useCallback(async()=>{if(!r||!e){n(null);return}let g=e.homeAccountId,h=q.get(g);if(h&&Date.now()-h.timestamp<ve){n(h.data);return}p(true),c(null);try{let d=await o.get("/me",{scopes:["User.Read"]}),m;try{let t=await o.get("/me/photo/$value",{scopes:["User.Read"],headers:{"Content-Type":"image/jpeg"}});t&&(m=URL.createObjectURL(t));}catch{console.debug("[UserProfile] Photo not available");}let a={id:d.id,displayName:d.displayName,givenName:d.givenName,surname:d.surname,userPrincipalName:d.userPrincipalName,mail:d.mail,jobTitle:d.jobTitle,officeLocation:d.officeLocation,mobilePhone:d.mobilePhone,businessPhones:d.businessPhones,photo:m};q.set(g,{data:a,timestamp:Date.now()}),n(a);}catch(d){let m=d;c(m),console.error("[UserProfile] Failed to fetch profile:",m);}finally{p(false);}},[r,e,o]),f=react.useCallback(()=>{e&&q.delete(e.homeAccountId),n(null);},[e]);return react.useEffect(()=>{i();},[i]),{profile:s,loading:u,error:l,refetch:i,clearCache:f}}function Re({size:r=40,className:e="",style:o,showTooltip:s=true,fallbackImage:n}){let{profile:u,loading:p}=B(),[l,c]=react.useState(null),[i,f]=react.useState(false);react.useEffect(()=>{u?.photo&&c(u.photo);},[u?.photo]);let g=()=>{if(!u)return "?";let{givenName:m,surname:a,displayName:t}=u;if(m&&a)return `${m[0]}${a[0]}`.toUpperCase();if(t){let y=t.split(" ");return y.length>=2?`${y[0][0]}${y[y.length-1][0]}`.toUpperCase():t.substring(0,2).toUpperCase()}return "?"},h={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",...o},d=u?.displayName||"User";return p?jsxRuntime.jsx("div",{className:e,style:{...h,backgroundColor:"#E1E1E1"},"aria-label":"Loading user avatar",children:jsxRuntime.jsx("span",{style:{fontSize:`${r*.3}px`},children:"..."})}):l&&!i?jsxRuntime.jsx("div",{className:e,style:h,title:s?d:void 0,"aria-label":`${d} avatar`,children:jsxRuntime.jsx("img",{src:l,alt:d,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>{f(true),n&&c(n);}})}):jsxRuntime.jsx("div",{className:e,style:h,title:s?d:void 0,"aria-label":`${d} avatar`,children:g()})}function Ce({className:r="",style:e,showDetails:o=false,renderLoading:s,renderAuthenticated:n,renderUnauthenticated:u}){let{isAuthenticated:p,inProgress:l,account:c}=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(l)return s?jsxRuntime.jsx(jsxRuntime.Fragment,{children:s()}):jsxRuntime.jsxs("div",{className:r,style:{...i,backgroundColor:"#FFF4CE",color:"#8A6D3B"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx($,{color:"#FFA500"}),jsxRuntime.jsx("span",{children:"Loading..."})]});if(p){let f=c?.username||c?.name||"User";return n?jsxRuntime.jsx(jsxRuntime.Fragment,{children:n(f)}):jsxRuntime.jsxs("div",{className:r,style:{...i,backgroundColor:"#D4EDDA",color:"#155724"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx($,{color:"#28A745"}),jsxRuntime.jsx("span",{children:o?`Authenticated as ${f}`:"Authenticated"})]})}return u?jsxRuntime.jsx(jsxRuntime.Fragment,{children:u()}):jsxRuntime.jsxs("div",{className:r,style:{...i,backgroundColor:"#F8D7DA",color:"#721C24"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx($,{color:"#DC3545"}),jsxRuntime.jsx("span",{children:"Not authenticated"})]})}function $({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 _({children:r,loadingComponent:e,fallbackComponent:o,useRedirect:s=true,scopes:n,onAuthRequired:u}){let{isAuthenticated:p,inProgress:l,loginRedirect:c,loginPopup:i}=A();return react.useEffect(()=>{!p&&!l&&(u?.(),(async()=>{try{s?await c(n):await i(n);}catch(g){console.error("[AuthGuard] Authentication failed:",g);}})());},[p,l,s,n,c,i,u]),l?jsxRuntime.jsx(jsxRuntime.Fragment,{children:e||jsxRuntime.jsx("div",{children:"Authenticating..."})}):p?jsxRuntime.jsx(jsxRuntime.Fragment,{children:r}):jsxRuntime.jsx(jsxRuntime.Fragment,{children:o||jsxRuntime.jsx("div",{children:"Redirecting to login..."})})}var j=class extends react.Component{constructor(o){super(o);this.reset=()=>{this.setState({hasError:false,error:null});};this.state={hasError:false,error:null};}static getDerivedStateFromError(o){return {hasError:true,error:o}}componentDidCatch(o,s){let{onError:n,debug:u}=this.props;u&&(console.error("[ErrorBoundary] Caught error:",o),console.error("[ErrorBoundary] Error info:",s)),n?.(o,s);}render(){let{hasError:o,error:s}=this.state,{children:n,fallback:u}=this.props;return o&&s?u?u(s,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:s.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 re=new Map,ke=300*1e3;function Le(){let{isAuthenticated:r,account:e}=A(),o=T(),[s,n]=react.useState([]),[u,p]=react.useState([]),[l,c]=react.useState(false),[i,f]=react.useState(null),g=react.useCallback(async()=>{if(!r||!e){n([]),p([]);return}let t=e.homeAccountId,y=re.get(t);if(y&&Date.now()-y.timestamp<ke){n(y.roles),p(y.groups);return}c(true),f(null);try{let C=e.idTokenClaims?.roles||[],F=(await o.get("/me/memberOf",{scopes:["User.Read","Directory.Read.All"]})).value.map(ie=>ie.id);re.set(t,{roles:C,groups:F,timestamp:Date.now()}),n(C),p(F);}catch(U){let C=U;f(C),console.error("[Roles] Failed to fetch roles/groups:",C);let F=e.idTokenClaims?.roles||[];n(F);}finally{c(false);}},[r,e,o]),h=react.useCallback(t=>s.includes(t),[s]),d=react.useCallback(t=>u.includes(t),[u]),m=react.useCallback(t=>t.some(y=>s.includes(y)),[s]),a=react.useCallback(t=>t.every(y=>s.includes(y)),[s]);return react.useEffect(()=>{g();},[g]),{roles:s,groups:u,loading:l,error:i,hasRole:h,hasGroup:d,hasAnyRole:m,hasAllRoles:a,refetch:g}}function Ue(r,e={}){let{displayName:o,...s}=e,n=u=>jsxRuntime.jsx(_,{...s,children:jsxRuntime.jsx(r,{...u})});return n.displayName=o||`withAuth(${r.displayName||r.name||"Component"})`,n}async function oe(r,e={}){let{maxRetries:o=3,initialDelay:s=1e3,maxDelay:n=1e4,backoffMultiplier:u=2,debug:p=false}=e,l,c=s;for(let i=0;i<=o;i++)try{return p&&i>0&&console.log(`[TokenRetry] Attempt ${i+1}/${o+1}`),await r()}catch(f){if(l=f,i===o){p&&console.error("[TokenRetry] All retry attempts failed");break}if(!Fe(f))throw p&&console.log("[TokenRetry] Non-retryable error, aborting"),f;p&&console.warn(`[TokenRetry] Attempt ${i+1} failed, retrying in ${c}ms...`),await Ne(c),c=Math.min(c*u,n);}throw l}function Fe(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 Ne(r){return new Promise(e=>setTimeout(e,r))}function Ie(r,e={}){return (...o)=>oe(()=>r(...o),e)}var I=class{constructor(e={}){this.config={enabled:e.enabled??false,prefix:e.prefix??"[MSAL-Next]",showTimestamp:e.showTimestamp??true,level:e.level??"info"};}shouldLog(e){if(!this.config.enabled)return false;let o=["error","warn","info","debug"],s=o.indexOf(this.config.level);return o.indexOf(e)<=s}formatMessage(e,o,s){let n=this.config.showTimestamp?`[${new Date().toISOString()}]`:"",u=this.config.prefix,p=`[${e.toUpperCase()}]`,l=`${n} ${u} ${p} ${o}`;return s!==void 0&&(l+=`
2
+ `+JSON.stringify(s,null,2)),l}error(e,o){this.shouldLog("error")&&console.error(this.formatMessage("error",e,o));}warn(e,o){this.shouldLog("warn")&&console.warn(this.formatMessage("warn",e,o));}info(e,o){this.shouldLog("info")&&console.info(this.formatMessage("info",e,o));}debug(e,o){this.shouldLog("debug")&&console.debug(this.formatMessage("debug",e,o));}group(e){this.config.enabled&&console.group(`${this.config.prefix} ${e}`);}groupEnd(){this.config.enabled&&console.groupEnd();}setEnabled(e){this.config.enabled=e;}setLevel(e){e&&(this.config.level=e);}},L=null;function Ge(r){return L?r&&(r.enabled!==void 0&&L.setEnabled(r.enabled),r.level&&L.setLevel(r.level)):L=new I(r),L}function Oe(r,e){return new I({...e,prefix:`[MSAL-Next:${r}]`})}function De(r={}){let{protectedRoutes:e=[],publicOnlyRoutes:o=[],loginPath:s="/login",redirectAfterLogin:n="/",sessionCookie:u="msal.account",isAuthenticated:p,debug:l=false}=r;return async function(i){let{pathname:f}=i.nextUrl;l&&console.log("[AuthMiddleware] Processing:",f);let g=false;p?g=await p(i):g=!!i.cookies.get(u)?.value,l&&console.log("[AuthMiddleware] Authenticated:",g);let h=e.some(a=>f.startsWith(a)),d=o.some(a=>f.startsWith(a));if(h&&!g){l&&console.log("[AuthMiddleware] Redirecting to login");let a=i.nextUrl.clone();return a.pathname=s,a.searchParams.set("returnUrl",f),server.NextResponse.redirect(a)}if(d&&g){l&&console.log("[AuthMiddleware] Redirecting to home");let a=i.nextUrl.searchParams.get("returnUrl"),t=i.nextUrl.clone();return t.pathname=a||n,t.searchParams.delete("returnUrl"),server.NextResponse.redirect(t)}let m=server.NextResponse.next();if(g){m.headers.set("x-msal-authenticated","true");try{let a=i.cookies.get(u);if(a?.value){let t=JSON.parse(a.value);t.username&&m.headers.set("x-msal-username",t.username);}}catch{}}return m}}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=_;exports.AuthStatus=Ce;exports.ErrorBoundary=j;exports.MicrosoftSignInButton=ye;exports.MsalAuthProvider=de;exports.SignOutButton=be;exports.UserAvatar=Re;exports.createAuthMiddleware=De;exports.createMsalConfig=G;exports.createRetryWrapper=Ie;exports.createScopedLogger=Oe;exports.getDebugLogger=Ge;exports.getMsalInstance=pe;exports.retryWithBackoff=oe;exports.useGraphApi=T;exports.useMsalAuth=A;exports.useRoles=Le;exports.useUserProfile=B;exports.withAuth=Ue;