analytica-frontend-lib 1.0.73 → 1.0.75

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.
Files changed (73) hide show
  1. package/dist/Auth/AuthProvider/index.d.mts +3 -0
  2. package/dist/Auth/AuthProvider/index.d.ts +3 -0
  3. package/dist/Auth/AuthProvider/index.js +213 -0
  4. package/dist/Auth/AuthProvider/index.js.map +1 -0
  5. package/dist/Auth/AuthProvider/index.mjs +188 -0
  6. package/dist/Auth/AuthProvider/index.mjs.map +1 -0
  7. package/dist/Auth/ProtectedRoute/index.d.mts +3 -0
  8. package/dist/Auth/ProtectedRoute/index.d.ts +3 -0
  9. package/dist/Auth/ProtectedRoute/index.js +213 -0
  10. package/dist/Auth/ProtectedRoute/index.js.map +1 -0
  11. package/dist/Auth/ProtectedRoute/index.mjs +188 -0
  12. package/dist/Auth/ProtectedRoute/index.mjs.map +1 -0
  13. package/dist/Auth/PublicRoute/index.d.mts +3 -0
  14. package/dist/Auth/PublicRoute/index.d.ts +3 -0
  15. package/dist/Auth/PublicRoute/index.js +213 -0
  16. package/dist/Auth/PublicRoute/index.js.map +1 -0
  17. package/dist/Auth/PublicRoute/index.mjs +188 -0
  18. package/dist/Auth/PublicRoute/index.mjs.map +1 -0
  19. package/dist/Auth/getRootDomain/index.d.mts +3 -0
  20. package/dist/Auth/getRootDomain/index.d.ts +3 -0
  21. package/dist/Auth/getRootDomain/index.js +213 -0
  22. package/dist/Auth/getRootDomain/index.js.map +1 -0
  23. package/dist/Auth/getRootDomain/index.mjs +188 -0
  24. package/dist/Auth/getRootDomain/index.mjs.map +1 -0
  25. package/dist/Auth/index.d.mts +114 -20
  26. package/dist/Auth/index.d.ts +114 -20
  27. package/dist/Auth/index.js +23 -0
  28. package/dist/Auth/index.js.map +1 -1
  29. package/dist/Auth/index.mjs +22 -0
  30. package/dist/Auth/index.mjs.map +1 -1
  31. package/dist/Auth/useAuth/index.d.mts +3 -0
  32. package/dist/Auth/useAuth/index.d.ts +3 -0
  33. package/dist/Auth/useAuth/index.js +213 -0
  34. package/dist/Auth/useAuth/index.js.map +1 -0
  35. package/dist/Auth/useAuth/index.mjs +188 -0
  36. package/dist/Auth/useAuth/index.mjs.map +1 -0
  37. package/dist/Auth/useAuthGuard/index.d.mts +3 -0
  38. package/dist/Auth/useAuthGuard/index.d.ts +3 -0
  39. package/dist/Auth/useAuthGuard/index.js +213 -0
  40. package/dist/Auth/useAuthGuard/index.js.map +1 -0
  41. package/dist/Auth/useAuthGuard/index.mjs +188 -0
  42. package/dist/Auth/useAuthGuard/index.mjs.map +1 -0
  43. package/dist/Auth/useRouteAuth/index.d.mts +3 -0
  44. package/dist/Auth/useRouteAuth/index.d.ts +3 -0
  45. package/dist/Auth/useRouteAuth/index.js +213 -0
  46. package/dist/Auth/useRouteAuth/index.js.map +1 -0
  47. package/dist/Auth/useRouteAuth/index.mjs +188 -0
  48. package/dist/Auth/useRouteAuth/index.mjs.map +1 -0
  49. package/dist/Auth/useUrlAuthentication/index.d.mts +58 -0
  50. package/dist/Auth/useUrlAuthentication/index.d.ts +58 -0
  51. package/dist/Auth/useUrlAuthentication/index.js +94 -0
  52. package/dist/Auth/useUrlAuthentication/index.js.map +1 -0
  53. package/dist/Auth/useUrlAuthentication/index.mjs +69 -0
  54. package/dist/Auth/useUrlAuthentication/index.mjs.map +1 -0
  55. package/dist/Auth/withAuth/index.d.mts +3 -0
  56. package/dist/Auth/withAuth/index.d.ts +3 -0
  57. package/dist/Auth/withAuth/index.js +213 -0
  58. package/dist/Auth/withAuth/index.js.map +1 -0
  59. package/dist/Auth/withAuth/index.mjs +188 -0
  60. package/dist/Auth/withAuth/index.mjs.map +1 -0
  61. package/dist/Auth/zustandAuthAdapter/index.d.mts +75 -0
  62. package/dist/Auth/zustandAuthAdapter/index.d.ts +75 -0
  63. package/dist/Auth/zustandAuthAdapter/index.js +70 -0
  64. package/dist/Auth/zustandAuthAdapter/index.js.map +1 -0
  65. package/dist/Auth/zustandAuthAdapter/index.mjs +45 -0
  66. package/dist/Auth/zustandAuthAdapter/index.mjs.map +1 -0
  67. package/dist/index.d.mts +3 -1
  68. package/dist/index.d.ts +3 -1
  69. package/dist/index.js +135 -0
  70. package/dist/index.js.map +1 -1
  71. package/dist/index.mjs +132 -0
  72. package/dist/index.mjs.map +1 -1
  73. package/package.json +1 -1
@@ -2,7 +2,12 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode, ComponentType } from 'react';
3
3
 
4
4
  /**
5
- * Interface básica para tokens de autenticação
5
+ * Interface for basic authentication tokens
6
+ *
7
+ * @interface AuthTokens
8
+ * @property {string} token - Main authentication token
9
+ * @property {string} refreshToken - Token used to refresh the main token
10
+ * @property {unknown} [key] - Additional properties that can be included
6
11
  */
7
12
  interface AuthTokens {
8
13
  token: string;
@@ -10,7 +15,13 @@ interface AuthTokens {
10
15
  [key: string]: unknown;
11
16
  }
12
17
  /**
13
- * Interface básica para usuário
18
+ * Interface for basic user information
19
+ *
20
+ * @interface AuthUser
21
+ * @property {string} id - Unique user identifier
22
+ * @property {string} [name] - Optional user name
23
+ * @property {string} [email] - Optional user email
24
+ * @property {unknown} [key] - Additional user properties
14
25
  */
15
26
  interface AuthUser {
16
27
  id: string;
@@ -19,7 +30,15 @@ interface AuthUser {
19
30
  [key: string]: unknown;
20
31
  }
21
32
  /**
22
- * Interface básica para informações de sessão
33
+ * Interface for basic session information
34
+ *
35
+ * @interface SessionInfo
36
+ * @property {string} [institutionId] - Optional institution identifier
37
+ * @property {string} [profileId] - Optional profile identifier
38
+ * @property {string} [schoolId] - Optional school identifier
39
+ * @property {string} [schoolYearId] - Optional school year identifier
40
+ * @property {string} [classId] - Optional class identifier
41
+ * @property {unknown} [key] - Additional session properties
23
42
  */
24
43
  interface SessionInfo {
25
44
  institutionId?: string;
@@ -30,7 +49,14 @@ interface SessionInfo {
30
49
  [key: string]: unknown;
31
50
  }
32
51
  /**
33
- * Interface para o estado de autenticação
52
+ * Interface for authentication state
53
+ *
54
+ * @interface AuthState
55
+ * @property {boolean} isAuthenticated - Whether the user is authenticated
56
+ * @property {boolean} isLoading - Whether authentication is being checked
57
+ * @property {AuthUser | null} [user] - Current user information
58
+ * @property {SessionInfo | null} [sessionInfo] - Current session information
59
+ * @property {AuthTokens | null} [tokens] - Current authentication tokens
34
60
  */
35
61
  interface AuthState {
36
62
  isAuthenticated: boolean;
@@ -40,14 +66,28 @@ interface AuthState {
40
66
  tokens?: AuthTokens | null;
41
67
  }
42
68
  /**
43
- * Interface para as funções de autenticação
69
+ * Interface for authentication context functions and state
70
+ *
71
+ * @interface AuthContextType
72
+ * @extends {AuthState}
73
+ * @property {() => Promise<boolean>} checkAuth - Function to check authentication status
74
+ * @property {() => void} signOut - Function to sign out the user
44
75
  */
45
76
  interface AuthContextType extends AuthState {
46
77
  checkAuth: () => Promise<boolean>;
47
78
  signOut: () => void;
48
79
  }
49
80
  /**
50
- * Props do AuthProvider
81
+ * Props for the AuthProvider component
82
+ *
83
+ * @interface AuthProviderProps
84
+ * @property {ReactNode} children - Child components
85
+ * @property {() => Promise<boolean> | boolean} [checkAuthFn] - Function to check if user is authenticated
86
+ * @property {() => void} [signOutFn] - Function to handle logout
87
+ * @property {Partial<AuthState>} [initialAuthState] - Initial authentication state
88
+ * @property {() => AuthUser | null | undefined} [getUserFn] - Function to get user data
89
+ * @property {() => SessionInfo | null | undefined} [getSessionFn] - Function to get session info
90
+ * @property {() => AuthTokens | null | undefined} [getTokensFn] - Function to get tokens
51
91
  */
52
92
  interface AuthProviderProps {
53
93
  children: ReactNode;
@@ -78,16 +118,44 @@ interface AuthProviderProps {
78
118
  getTokensFn?: () => AuthTokens | null | undefined;
79
119
  }
80
120
  /**
81
- * Provider de autenticação que gerencia o estado global de auth
82
- * Compatível com qualquer store (Zustand, Redux, Context, etc.)
121
+ * Authentication provider that manages global auth state
122
+ * Compatible with any store (Zustand, Redux, Context, etc.)
123
+ *
124
+ * @param {AuthProviderProps} props - The provider props
125
+ * @returns {JSX.Element} The provider component
126
+ *
127
+ * @example
128
+ * ```tsx
129
+ * <AuthProvider
130
+ * checkAuthFn={checkAuthFunction}
131
+ * signOutFn={signOutFunction}
132
+ * getUserFn={getUserFunction}
133
+ * >
134
+ * <App />
135
+ * </AuthProvider>
136
+ * ```
83
137
  */
84
138
  declare const AuthProvider: ({ children, checkAuthFn, signOutFn, initialAuthState, getUserFn, getSessionFn, getTokensFn, }: AuthProviderProps) => react_jsx_runtime.JSX.Element;
85
139
  /**
86
- * Hook para usar o contexto de autenticação
140
+ * Hook to use the authentication context
141
+ *
142
+ * @throws {Error} When used outside of AuthProvider
143
+ * @returns {AuthContextType} The authentication context
144
+ *
145
+ * @example
146
+ * ```tsx
147
+ * const { isAuthenticated, user, signOut } = useAuth();
148
+ * ```
87
149
  */
88
150
  declare const useAuth: () => AuthContextType;
89
151
  /**
90
- * Props do ProtectedRoute
152
+ * Props for the ProtectedRoute component
153
+ *
154
+ * @interface ProtectedRouteProps
155
+ * @property {ReactNode} children - Components to render when authenticated
156
+ * @property {string} [redirectTo] - Path to redirect when not authenticated (default: '/')
157
+ * @property {ReactNode} [loadingComponent] - Custom loading component
158
+ * @property {(authState: AuthState) => boolean} [additionalCheck] - Additional authentication check
91
159
  */
92
160
  interface ProtectedRouteProps {
93
161
  children: ReactNode;
@@ -114,9 +182,15 @@ interface ProtectedRouteProps {
114
182
  * </ProtectedRoute>
115
183
  * ```
116
184
  */
117
- declare const ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => react_jsx_runtime.JSX.Element;
185
+ declare const ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => react_jsx_runtime.JSX.Element | null;
118
186
  /**
119
- * Props do PublicRoute
187
+ * Props for the PublicRoute component
188
+ *
189
+ * @interface PublicRouteProps
190
+ * @property {ReactNode} children - Components to render
191
+ * @property {string} [redirectTo] - Path to redirect to (default: '/painel')
192
+ * @property {boolean} [redirectIfAuthenticated] - Whether to redirect if authenticated
193
+ * @property {boolean} [checkAuthBeforeRender] - Whether to check auth before rendering
120
194
  */
121
195
  interface PublicRouteProps {
122
196
  children: ReactNode;
@@ -146,25 +220,35 @@ interface PublicRouteProps {
146
220
  */
147
221
  declare const PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => react_jsx_runtime.JSX.Element;
148
222
  /**
149
- * HOC para proteger componentes com autenticação
223
+ * Higher-Order Component to protect components with authentication
224
+ *
225
+ * @template P - Component props type
226
+ * @param {ComponentType<P>} Component - Component to wrap with authentication
227
+ * @param {Omit<ProtectedRouteProps, 'children'>} [options] - Protection options
228
+ * @returns {(props: P) => JSX.Element} Wrapped component
150
229
  *
151
230
  * @example
152
231
  * ```tsx
153
232
  * const ProtectedComponent = withAuth(MyComponent, {
154
- * fallback: "/login",
233
+ * redirectTo: "/login",
155
234
  * loadingComponent: <CustomSpinner />
156
235
  * });
157
236
  * ```
158
237
  */
159
238
  declare const withAuth: <P extends object>(Component: ComponentType<P>, options?: Omit<ProtectedRouteProps, "children">) => (props: P) => react_jsx_runtime.JSX.Element;
160
239
  /**
161
- * Hook para guard de autenticação com verificações customizadas
240
+ * Hook for authentication guard with custom checks
241
+ *
242
+ * @param {object} [options] - Guard options
243
+ * @param {boolean} [options.requireAuth=true] - Whether authentication is required
244
+ * @param {(authState: AuthState) => boolean} [options.customCheck] - Custom check function
245
+ * @returns {object} Guard result with canAccess, isLoading, and authState
162
246
  *
163
247
  * @example
164
248
  * ```tsx
165
249
  * const { canAccess, isLoading } = useAuthGuard({
166
250
  * requireAuth: true,
167
- * customCheck: (user) => user?.role === 'admin'
251
+ * customCheck: (authState) => authState.user?.role === 'admin'
168
252
  * });
169
253
  * ```
170
254
  */
@@ -177,8 +261,11 @@ declare const useAuthGuard: (options?: {
177
261
  authState: AuthContextType;
178
262
  };
179
263
  /**
180
- * Hook para verificar autenticação em rotas específicas
181
- * Útil para verificações condicionais dentro de componentes
264
+ * Hook to check authentication on specific routes
265
+ * Useful for conditional checks within components
266
+ *
267
+ * @param {string} [fallbackPath='/'] - Path to redirect when not authenticated
268
+ * @returns {object} Object with isAuthenticated, isLoading, and redirectToLogin function
182
269
  *
183
270
  * @example
184
271
  * ```tsx
@@ -194,9 +281,16 @@ declare const useRouteAuth: (fallbackPath?: string) => {
194
281
  isLoading: boolean;
195
282
  redirectToLogin: () => react_jsx_runtime.JSX.Element;
196
283
  };
284
+ /**
285
+ * Get the root domain from the current window location
286
+ * Handles localhost and subdomain cases
287
+ *
288
+ * @returns {string} The root domain URL
289
+ */
290
+ declare const getRootDomain: () => string;
197
291
  declare const _default: {
198
292
  AuthProvider: ({ children, checkAuthFn, signOutFn, initialAuthState, getUserFn, getSessionFn, getTokensFn, }: AuthProviderProps) => react_jsx_runtime.JSX.Element;
199
- ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => react_jsx_runtime.JSX.Element;
293
+ ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => react_jsx_runtime.JSX.Element | null;
200
294
  PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => react_jsx_runtime.JSX.Element;
201
295
  withAuth: <P extends object>(Component: ComponentType<P>, options?: Omit<ProtectedRouteProps, "children">) => (props: P) => react_jsx_runtime.JSX.Element;
202
296
  useAuth: () => AuthContextType;
@@ -215,4 +309,4 @@ declare const _default: {
215
309
  };
216
310
  };
217
311
 
218
- export { type AuthContextType, AuthProvider, type AuthProviderProps, type AuthState, type AuthTokens, type AuthUser, ProtectedRoute, type ProtectedRouteProps, PublicRoute, type PublicRouteProps, type SessionInfo, _default as default, useAuth, useAuthGuard, useRouteAuth, withAuth };
312
+ export { type AuthContextType, AuthProvider, type AuthProviderProps, type AuthState, type AuthTokens, type AuthUser, ProtectedRoute, type ProtectedRouteProps, PublicRoute, type PublicRouteProps, type SessionInfo, _default as default, getRootDomain, useAuth, useAuthGuard, useRouteAuth, withAuth };
@@ -2,7 +2,12 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode, ComponentType } from 'react';
3
3
 
4
4
  /**
5
- * Interface básica para tokens de autenticação
5
+ * Interface for basic authentication tokens
6
+ *
7
+ * @interface AuthTokens
8
+ * @property {string} token - Main authentication token
9
+ * @property {string} refreshToken - Token used to refresh the main token
10
+ * @property {unknown} [key] - Additional properties that can be included
6
11
  */
7
12
  interface AuthTokens {
8
13
  token: string;
@@ -10,7 +15,13 @@ interface AuthTokens {
10
15
  [key: string]: unknown;
11
16
  }
12
17
  /**
13
- * Interface básica para usuário
18
+ * Interface for basic user information
19
+ *
20
+ * @interface AuthUser
21
+ * @property {string} id - Unique user identifier
22
+ * @property {string} [name] - Optional user name
23
+ * @property {string} [email] - Optional user email
24
+ * @property {unknown} [key] - Additional user properties
14
25
  */
15
26
  interface AuthUser {
16
27
  id: string;
@@ -19,7 +30,15 @@ interface AuthUser {
19
30
  [key: string]: unknown;
20
31
  }
21
32
  /**
22
- * Interface básica para informações de sessão
33
+ * Interface for basic session information
34
+ *
35
+ * @interface SessionInfo
36
+ * @property {string} [institutionId] - Optional institution identifier
37
+ * @property {string} [profileId] - Optional profile identifier
38
+ * @property {string} [schoolId] - Optional school identifier
39
+ * @property {string} [schoolYearId] - Optional school year identifier
40
+ * @property {string} [classId] - Optional class identifier
41
+ * @property {unknown} [key] - Additional session properties
23
42
  */
24
43
  interface SessionInfo {
25
44
  institutionId?: string;
@@ -30,7 +49,14 @@ interface SessionInfo {
30
49
  [key: string]: unknown;
31
50
  }
32
51
  /**
33
- * Interface para o estado de autenticação
52
+ * Interface for authentication state
53
+ *
54
+ * @interface AuthState
55
+ * @property {boolean} isAuthenticated - Whether the user is authenticated
56
+ * @property {boolean} isLoading - Whether authentication is being checked
57
+ * @property {AuthUser | null} [user] - Current user information
58
+ * @property {SessionInfo | null} [sessionInfo] - Current session information
59
+ * @property {AuthTokens | null} [tokens] - Current authentication tokens
34
60
  */
35
61
  interface AuthState {
36
62
  isAuthenticated: boolean;
@@ -40,14 +66,28 @@ interface AuthState {
40
66
  tokens?: AuthTokens | null;
41
67
  }
42
68
  /**
43
- * Interface para as funções de autenticação
69
+ * Interface for authentication context functions and state
70
+ *
71
+ * @interface AuthContextType
72
+ * @extends {AuthState}
73
+ * @property {() => Promise<boolean>} checkAuth - Function to check authentication status
74
+ * @property {() => void} signOut - Function to sign out the user
44
75
  */
45
76
  interface AuthContextType extends AuthState {
46
77
  checkAuth: () => Promise<boolean>;
47
78
  signOut: () => void;
48
79
  }
49
80
  /**
50
- * Props do AuthProvider
81
+ * Props for the AuthProvider component
82
+ *
83
+ * @interface AuthProviderProps
84
+ * @property {ReactNode} children - Child components
85
+ * @property {() => Promise<boolean> | boolean} [checkAuthFn] - Function to check if user is authenticated
86
+ * @property {() => void} [signOutFn] - Function to handle logout
87
+ * @property {Partial<AuthState>} [initialAuthState] - Initial authentication state
88
+ * @property {() => AuthUser | null | undefined} [getUserFn] - Function to get user data
89
+ * @property {() => SessionInfo | null | undefined} [getSessionFn] - Function to get session info
90
+ * @property {() => AuthTokens | null | undefined} [getTokensFn] - Function to get tokens
51
91
  */
52
92
  interface AuthProviderProps {
53
93
  children: ReactNode;
@@ -78,16 +118,44 @@ interface AuthProviderProps {
78
118
  getTokensFn?: () => AuthTokens | null | undefined;
79
119
  }
80
120
  /**
81
- * Provider de autenticação que gerencia o estado global de auth
82
- * Compatível com qualquer store (Zustand, Redux, Context, etc.)
121
+ * Authentication provider that manages global auth state
122
+ * Compatible with any store (Zustand, Redux, Context, etc.)
123
+ *
124
+ * @param {AuthProviderProps} props - The provider props
125
+ * @returns {JSX.Element} The provider component
126
+ *
127
+ * @example
128
+ * ```tsx
129
+ * <AuthProvider
130
+ * checkAuthFn={checkAuthFunction}
131
+ * signOutFn={signOutFunction}
132
+ * getUserFn={getUserFunction}
133
+ * >
134
+ * <App />
135
+ * </AuthProvider>
136
+ * ```
83
137
  */
84
138
  declare const AuthProvider: ({ children, checkAuthFn, signOutFn, initialAuthState, getUserFn, getSessionFn, getTokensFn, }: AuthProviderProps) => react_jsx_runtime.JSX.Element;
85
139
  /**
86
- * Hook para usar o contexto de autenticação
140
+ * Hook to use the authentication context
141
+ *
142
+ * @throws {Error} When used outside of AuthProvider
143
+ * @returns {AuthContextType} The authentication context
144
+ *
145
+ * @example
146
+ * ```tsx
147
+ * const { isAuthenticated, user, signOut } = useAuth();
148
+ * ```
87
149
  */
88
150
  declare const useAuth: () => AuthContextType;
89
151
  /**
90
- * Props do ProtectedRoute
152
+ * Props for the ProtectedRoute component
153
+ *
154
+ * @interface ProtectedRouteProps
155
+ * @property {ReactNode} children - Components to render when authenticated
156
+ * @property {string} [redirectTo] - Path to redirect when not authenticated (default: '/')
157
+ * @property {ReactNode} [loadingComponent] - Custom loading component
158
+ * @property {(authState: AuthState) => boolean} [additionalCheck] - Additional authentication check
91
159
  */
92
160
  interface ProtectedRouteProps {
93
161
  children: ReactNode;
@@ -114,9 +182,15 @@ interface ProtectedRouteProps {
114
182
  * </ProtectedRoute>
115
183
  * ```
116
184
  */
117
- declare const ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => react_jsx_runtime.JSX.Element;
185
+ declare const ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => react_jsx_runtime.JSX.Element | null;
118
186
  /**
119
- * Props do PublicRoute
187
+ * Props for the PublicRoute component
188
+ *
189
+ * @interface PublicRouteProps
190
+ * @property {ReactNode} children - Components to render
191
+ * @property {string} [redirectTo] - Path to redirect to (default: '/painel')
192
+ * @property {boolean} [redirectIfAuthenticated] - Whether to redirect if authenticated
193
+ * @property {boolean} [checkAuthBeforeRender] - Whether to check auth before rendering
120
194
  */
121
195
  interface PublicRouteProps {
122
196
  children: ReactNode;
@@ -146,25 +220,35 @@ interface PublicRouteProps {
146
220
  */
147
221
  declare const PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => react_jsx_runtime.JSX.Element;
148
222
  /**
149
- * HOC para proteger componentes com autenticação
223
+ * Higher-Order Component to protect components with authentication
224
+ *
225
+ * @template P - Component props type
226
+ * @param {ComponentType<P>} Component - Component to wrap with authentication
227
+ * @param {Omit<ProtectedRouteProps, 'children'>} [options] - Protection options
228
+ * @returns {(props: P) => JSX.Element} Wrapped component
150
229
  *
151
230
  * @example
152
231
  * ```tsx
153
232
  * const ProtectedComponent = withAuth(MyComponent, {
154
- * fallback: "/login",
233
+ * redirectTo: "/login",
155
234
  * loadingComponent: <CustomSpinner />
156
235
  * });
157
236
  * ```
158
237
  */
159
238
  declare const withAuth: <P extends object>(Component: ComponentType<P>, options?: Omit<ProtectedRouteProps, "children">) => (props: P) => react_jsx_runtime.JSX.Element;
160
239
  /**
161
- * Hook para guard de autenticação com verificações customizadas
240
+ * Hook for authentication guard with custom checks
241
+ *
242
+ * @param {object} [options] - Guard options
243
+ * @param {boolean} [options.requireAuth=true] - Whether authentication is required
244
+ * @param {(authState: AuthState) => boolean} [options.customCheck] - Custom check function
245
+ * @returns {object} Guard result with canAccess, isLoading, and authState
162
246
  *
163
247
  * @example
164
248
  * ```tsx
165
249
  * const { canAccess, isLoading } = useAuthGuard({
166
250
  * requireAuth: true,
167
- * customCheck: (user) => user?.role === 'admin'
251
+ * customCheck: (authState) => authState.user?.role === 'admin'
168
252
  * });
169
253
  * ```
170
254
  */
@@ -177,8 +261,11 @@ declare const useAuthGuard: (options?: {
177
261
  authState: AuthContextType;
178
262
  };
179
263
  /**
180
- * Hook para verificar autenticação em rotas específicas
181
- * Útil para verificações condicionais dentro de componentes
264
+ * Hook to check authentication on specific routes
265
+ * Useful for conditional checks within components
266
+ *
267
+ * @param {string} [fallbackPath='/'] - Path to redirect when not authenticated
268
+ * @returns {object} Object with isAuthenticated, isLoading, and redirectToLogin function
182
269
  *
183
270
  * @example
184
271
  * ```tsx
@@ -194,9 +281,16 @@ declare const useRouteAuth: (fallbackPath?: string) => {
194
281
  isLoading: boolean;
195
282
  redirectToLogin: () => react_jsx_runtime.JSX.Element;
196
283
  };
284
+ /**
285
+ * Get the root domain from the current window location
286
+ * Handles localhost and subdomain cases
287
+ *
288
+ * @returns {string} The root domain URL
289
+ */
290
+ declare const getRootDomain: () => string;
197
291
  declare const _default: {
198
292
  AuthProvider: ({ children, checkAuthFn, signOutFn, initialAuthState, getUserFn, getSessionFn, getTokensFn, }: AuthProviderProps) => react_jsx_runtime.JSX.Element;
199
- ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => react_jsx_runtime.JSX.Element;
293
+ ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => react_jsx_runtime.JSX.Element | null;
200
294
  PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => react_jsx_runtime.JSX.Element;
201
295
  withAuth: <P extends object>(Component: ComponentType<P>, options?: Omit<ProtectedRouteProps, "children">) => (props: P) => react_jsx_runtime.JSX.Element;
202
296
  useAuth: () => AuthContextType;
@@ -215,4 +309,4 @@ declare const _default: {
215
309
  };
216
310
  };
217
311
 
218
- export { type AuthContextType, AuthProvider, type AuthProviderProps, type AuthState, type AuthTokens, type AuthUser, ProtectedRoute, type ProtectedRouteProps, PublicRoute, type PublicRouteProps, type SessionInfo, _default as default, useAuth, useAuthGuard, useRouteAuth, withAuth };
312
+ export { type AuthContextType, AuthProvider, type AuthProviderProps, type AuthState, type AuthTokens, type AuthUser, ProtectedRoute, type ProtectedRouteProps, PublicRoute, type PublicRouteProps, type SessionInfo, _default as default, getRootDomain, useAuth, useAuthGuard, useRouteAuth, withAuth };
@@ -24,6 +24,7 @@ __export(Auth_exports, {
24
24
  ProtectedRoute: () => ProtectedRoute,
25
25
  PublicRoute: () => PublicRoute,
26
26
  default: () => Auth_default,
27
+ getRootDomain: () => getRootDomain,
27
28
  useAuth: () => useAuth,
28
29
  useAuthGuard: () => useAuthGuard,
29
30
  useRouteAuth: () => useRouteAuth,
@@ -123,6 +124,14 @@ var ProtectedRoute = ({
123
124
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: loadingComponent || defaultLoadingComponent });
124
125
  }
125
126
  if (!isAuthenticated) {
127
+ if (typeof window !== "undefined") {
128
+ const rootDomain = getRootDomain();
129
+ const currentLocation = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ":" + window.location.port : ""}`;
130
+ if (rootDomain !== currentLocation) {
131
+ window.location.href = rootDomain;
132
+ return null;
133
+ }
134
+ }
126
135
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom.Navigate, { to: redirectTo, replace: true });
127
136
  }
128
137
  if (additionalCheck && !additionalCheck({ isAuthenticated, isLoading, ...authState })) {
@@ -168,6 +177,19 @@ var useRouteAuth = (fallbackPath = "/") => {
168
177
  redirectToLogin
169
178
  };
170
179
  };
180
+ var getRootDomain = () => {
181
+ const { hostname, protocol, port } = window.location;
182
+ const portStr = port ? ":" + port : "";
183
+ if (hostname === "localhost") {
184
+ return `${protocol}//${hostname}${portStr}`;
185
+ }
186
+ const parts = hostname.split(".");
187
+ if (parts.length > 2) {
188
+ const base = parts.slice(-2).join(".");
189
+ return `${protocol}//${base}${portStr}`;
190
+ }
191
+ return `${protocol}//${hostname}${portStr}`;
192
+ };
171
193
  var Auth_default = {
172
194
  AuthProvider,
173
195
  ProtectedRoute,
@@ -182,6 +204,7 @@ var Auth_default = {
182
204
  AuthProvider,
183
205
  ProtectedRoute,
184
206
  PublicRoute,
207
+ getRootDomain,
185
208
  useAuth,
186
209
  useAuthGuard,
187
210
  useRouteAuth,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/components/Auth/Auth.tsx"],"sourcesContent":["import {\n createContext,\n useContext,\n useEffect,\n useState,\n ReactNode,\n ComponentType,\n useCallback,\n useMemo,\n} from 'react';\nimport { useLocation, Navigate } from 'react-router-dom';\n\n/**\n * Interface básica para tokens de autenticação\n */\nexport interface AuthTokens {\n token: string;\n refreshToken: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface básica para usuário\n */\nexport interface AuthUser {\n id: string;\n name?: string;\n email?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface básica para informações de sessão\n */\nexport interface SessionInfo {\n institutionId?: string;\n profileId?: string;\n schoolId?: string;\n schoolYearId?: string;\n classId?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface para o estado de autenticação\n */\nexport interface AuthState {\n isAuthenticated: boolean;\n isLoading: boolean;\n user?: AuthUser | null;\n sessionInfo?: SessionInfo | null;\n tokens?: AuthTokens | null;\n}\n\n/**\n * Interface para as funções de autenticação\n */\nexport interface AuthContextType extends AuthState {\n checkAuth: () => Promise<boolean>;\n signOut: () => void;\n}\n\n/**\n * Context de autenticação\n */\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\n/**\n * Props do AuthProvider\n */\nexport interface AuthProviderProps {\n children: ReactNode;\n /**\n * Função para verificar se o usuário está autenticado\n * Deve retornar uma Promise<boolean>\n */\n checkAuthFn?: () => Promise<boolean> | boolean;\n /**\n * Função para fazer logout\n */\n signOutFn?: () => void;\n /**\n * Estado de autenticação inicial\n */\n initialAuthState?: Partial<AuthState>;\n /**\n * Função para obter dados do usuário (opcional)\n */\n getUserFn?: () => AuthUser | null | undefined;\n /**\n * Função para obter informações da sessão (opcional)\n */\n getSessionFn?: () => SessionInfo | null | undefined;\n /**\n * Função para obter tokens (opcional)\n */\n getTokensFn?: () => AuthTokens | null | undefined;\n}\n\n/**\n * Provider de autenticação que gerencia o estado global de auth\n * Compatível com qualquer store (Zustand, Redux, Context, etc.)\n */\nexport const AuthProvider = ({\n children,\n checkAuthFn,\n signOutFn,\n initialAuthState = {},\n getUserFn,\n getSessionFn,\n getTokensFn,\n}: AuthProviderProps) => {\n const [authState, setAuthState] = useState<AuthState>({\n isAuthenticated: false,\n isLoading: true,\n ...initialAuthState,\n });\n\n const checkAuth = useCallback(async (): Promise<boolean> => {\n try {\n setAuthState((prev) => ({ ...prev, isLoading: true }));\n\n // Se não há função de verificação, assume como não autenticado\n if (!checkAuthFn) {\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n\n const isAuth = await checkAuthFn();\n\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: isAuth,\n isLoading: false,\n user: getUserFn ? getUserFn() : prev.user,\n sessionInfo: getSessionFn ? getSessionFn() : prev.sessionInfo,\n tokens: getTokensFn ? getTokensFn() : prev.tokens,\n }));\n\n return isAuth;\n } catch (error) {\n console.error('Erro ao verificar autenticação:', error);\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n }, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]);\n\n const signOut = useCallback(() => {\n if (signOutFn) {\n signOutFn();\n }\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n user: undefined,\n sessionInfo: undefined,\n tokens: undefined,\n }));\n }, [signOutFn]);\n\n useEffect(() => {\n checkAuth();\n }, [checkAuth]);\n\n const contextValue = useMemo(\n (): AuthContextType => ({\n ...authState,\n checkAuth,\n signOut,\n }),\n [authState, checkAuth, signOut]\n );\n\n return (\n <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>\n );\n};\n\n/**\n * Hook para usar o contexto de autenticação\n */\nexport const useAuth = (): AuthContextType => {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error('useAuth deve ser usado dentro de um AuthProvider');\n }\n return context;\n};\n\n/**\n * Props do ProtectedRoute\n */\nexport interface ProtectedRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento quando não autenticado\n */\n redirectTo?: string;\n /**\n * Componente de loading personalizado\n */\n loadingComponent?: ReactNode;\n /**\n * Função adicional de verificação (ex: verificar permissões específicas)\n */\n additionalCheck?: (authState: AuthState) => boolean;\n}\n\n/**\n * Componente para proteger rotas que requerem autenticação\n *\n * @example\n * ```tsx\n * <ProtectedRoute redirectTo=\"/login\">\n * <PainelPage />\n * </ProtectedRoute>\n * ```\n */\nexport const ProtectedRoute = ({\n children,\n redirectTo = '/',\n loadingComponent,\n additionalCheck,\n}: ProtectedRouteProps) => {\n const { isAuthenticated, isLoading, ...authState } = useAuth();\n\n // Componente de loading padrão\n const defaultLoadingComponent = (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n\n // Mostrar loading enquanto verifica autenticação\n if (isLoading) {\n return <>{loadingComponent || defaultLoadingComponent}</>;\n }\n\n // Verificar autenticação básica\n if (!isAuthenticated) {\n return <Navigate to={redirectTo} replace />;\n }\n\n // Verificação adicional (ex: permissões)\n if (\n additionalCheck &&\n !additionalCheck({ isAuthenticated, isLoading, ...authState })\n ) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Props do PublicRoute\n */\nexport interface PublicRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento\n */\n redirectTo?: string;\n /**\n * Se deve redirecionar quando usuário estiver autenticado\n */\n redirectIfAuthenticated?: boolean;\n /**\n * Se deve verificar autenticação antes de renderizar\n */\n checkAuthBeforeRender?: boolean;\n}\n\n/**\n * Componente para rotas públicas (login, recuperação de senha, etc.)\n * Opcionalmente redireciona se o usuário já estiver autenticado\n *\n * @example\n * ```tsx\n * <PublicRoute redirectTo=\"/painel\" redirectIfAuthenticated={true}>\n * <LoginPage />\n * </PublicRoute>\n * ```\n */\nexport const PublicRoute = ({\n children,\n redirectTo = '/painel',\n redirectIfAuthenticated = false,\n checkAuthBeforeRender = false,\n}: PublicRouteProps) => {\n const { isAuthenticated, isLoading } = useAuth();\n\n // Se deve aguardar verificação de auth antes de renderizar\n if (checkAuthBeforeRender && isLoading) {\n return (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n }\n\n // Redirecionar se já autenticado e configurado para isso\n if (isAuthenticated && redirectIfAuthenticated) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * HOC para proteger componentes com autenticação\n *\n * @example\n * ```tsx\n * const ProtectedComponent = withAuth(MyComponent, {\n * fallback: \"/login\",\n * loadingComponent: <CustomSpinner />\n * });\n * ```\n */\nexport const withAuth = <P extends object>(\n Component: ComponentType<P>,\n options: Omit<ProtectedRouteProps, 'children'> = {}\n) => {\n return (props: P) => (\n <ProtectedRoute {...options}>\n <Component {...props} />\n </ProtectedRoute>\n );\n};\n\n/**\n * Hook para guard de autenticação com verificações customizadas\n *\n * @example\n * ```tsx\n * const { canAccess, isLoading } = useAuthGuard({\n * requireAuth: true,\n * customCheck: (user) => user?.role === 'admin'\n * });\n * ```\n */\nexport const useAuthGuard = (\n options: {\n requireAuth?: boolean;\n customCheck?: (authState: AuthState) => boolean;\n } = {}\n) => {\n const authState = useAuth();\n const { requireAuth = true, customCheck } = options;\n\n const canAccess =\n !authState.isLoading &&\n (requireAuth\n ? authState.isAuthenticated && (!customCheck || customCheck(authState))\n : !authState.isAuthenticated || !customCheck || customCheck(authState));\n\n return {\n canAccess,\n isLoading: authState.isLoading,\n authState,\n };\n};\n\n/**\n * Hook para verificar autenticação em rotas específicas\n * Útil para verificações condicionais dentro de componentes\n *\n * @example\n * ```tsx\n * const { isAuthenticated, redirectToLogin } = useRouteAuth();\n *\n * if (!isAuthenticated) {\n * return redirectToLogin();\n * }\n * ```\n */\nexport const useRouteAuth = (fallbackPath = '/') => {\n const { isAuthenticated, isLoading } = useAuth();\n const location = useLocation();\n\n const redirectToLogin = () => (\n <Navigate to={fallbackPath} state={{ from: location }} replace />\n );\n\n return {\n isAuthenticated,\n isLoading,\n redirectToLogin,\n };\n};\n\nexport default {\n AuthProvider,\n ProtectedRoute,\n PublicRoute,\n withAuth,\n useAuth,\n useAuthGuard,\n useRouteAuth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AAA,EAC1B,wBAAwB;AAC1B,MAAwB;AACtB,QAAM,EAAE,iBAAiB,UAAU,IAAI,QAAQ;AAG/C,MAAI,yBAAyB,WAAW;AACtC,WACE,4CAAC,SAAI,WAAU,iDACb,sDAAC,SAAI,WAAU,yBAAwB,2BAAa,GACtD;AAAA,EAEJ;AAGA,MAAI,mBAAmB,yBAAyB;AAC9C,WAAO,4CAAC,oCAAS,IAAI,YAAY,SAAO,MAAC;AAAA,EAC3C;AAEA,SAAO,2EAAG,UAAS;AACrB;AAaO,IAAM,WAAW,CACtB,WACA,UAAiD,CAAC,MAC/C;AACH,SAAO,CAAC,UACN,4CAAC,kBAAgB,GAAG,SAClB,sDAAC,aAAW,GAAG,OAAO,GACxB;AAEJ;AAaO,IAAM,eAAe,CAC1B,UAGI,CAAC,MACF;AACH,QAAM,YAAY,QAAQ;AAC1B,QAAM,EAAE,cAAc,MAAM,YAAY,IAAI;AAE5C,QAAM,YACJ,CAAC,UAAU,cACV,cACG,UAAU,oBAAoB,CAAC,eAAe,YAAY,SAAS,KACnE,CAAC,UAAU,mBAAmB,CAAC,eAAe,YAAY,SAAS;AAEzE,SAAO;AAAA,IACL;AAAA,IACA,WAAW,UAAU;AAAA,IACrB;AAAA,EACF;AACF;AAeO,IAAM,eAAe,CAAC,eAAe,QAAQ;AAClD,QAAM,EAAE,iBAAiB,UAAU,IAAI,QAAQ;AAC/C,QAAM,eAAW,qCAAY;AAE7B,QAAM,kBAAkB,MACtB,4CAAC,oCAAS,IAAI,cAAc,OAAO,EAAE,MAAM,SAAS,GAAG,SAAO,MAAC;AAGjE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEA,IAAO,eAAQ;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/components/Auth/Auth.tsx"],"sourcesContent":["import {\n createContext,\n useContext,\n useEffect,\n useState,\n ReactNode,\n ComponentType,\n useCallback,\n useMemo,\n} from 'react';\nimport { useLocation, Navigate } from 'react-router-dom';\n\n/**\n * Interface for basic authentication tokens\n *\n * @interface AuthTokens\n * @property {string} token - Main authentication token\n * @property {string} refreshToken - Token used to refresh the main token\n * @property {unknown} [key] - Additional properties that can be included\n */\nexport interface AuthTokens {\n token: string;\n refreshToken: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for basic user information\n *\n * @interface AuthUser\n * @property {string} id - Unique user identifier\n * @property {string} [name] - Optional user name\n * @property {string} [email] - Optional user email\n * @property {unknown} [key] - Additional user properties\n */\nexport interface AuthUser {\n id: string;\n name?: string;\n email?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for basic session information\n *\n * @interface SessionInfo\n * @property {string} [institutionId] - Optional institution identifier\n * @property {string} [profileId] - Optional profile identifier\n * @property {string} [schoolId] - Optional school identifier\n * @property {string} [schoolYearId] - Optional school year identifier\n * @property {string} [classId] - Optional class identifier\n * @property {unknown} [key] - Additional session properties\n */\nexport interface SessionInfo {\n institutionId?: string;\n profileId?: string;\n schoolId?: string;\n schoolYearId?: string;\n classId?: string;\n [key: string]: unknown;\n}\n\n/**\n * Interface for authentication state\n *\n * @interface AuthState\n * @property {boolean} isAuthenticated - Whether the user is authenticated\n * @property {boolean} isLoading - Whether authentication is being checked\n * @property {AuthUser | null} [user] - Current user information\n * @property {SessionInfo | null} [sessionInfo] - Current session information\n * @property {AuthTokens | null} [tokens] - Current authentication tokens\n */\nexport interface AuthState {\n isAuthenticated: boolean;\n isLoading: boolean;\n user?: AuthUser | null;\n sessionInfo?: SessionInfo | null;\n tokens?: AuthTokens | null;\n}\n\n/**\n * Interface for authentication context functions and state\n *\n * @interface AuthContextType\n * @extends {AuthState}\n * @property {() => Promise<boolean>} checkAuth - Function to check authentication status\n * @property {() => void} signOut - Function to sign out the user\n */\nexport interface AuthContextType extends AuthState {\n checkAuth: () => Promise<boolean>;\n signOut: () => void;\n}\n\n/**\n * Authentication context for React components\n *\n * @private\n */\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\n/**\n * Props for the AuthProvider component\n *\n * @interface AuthProviderProps\n * @property {ReactNode} children - Child components\n * @property {() => Promise<boolean> | boolean} [checkAuthFn] - Function to check if user is authenticated\n * @property {() => void} [signOutFn] - Function to handle logout\n * @property {Partial<AuthState>} [initialAuthState] - Initial authentication state\n * @property {() => AuthUser | null | undefined} [getUserFn] - Function to get user data\n * @property {() => SessionInfo | null | undefined} [getSessionFn] - Function to get session info\n * @property {() => AuthTokens | null | undefined} [getTokensFn] - Function to get tokens\n */\nexport interface AuthProviderProps {\n children: ReactNode;\n /**\n * Função para verificar se o usuário está autenticado\n * Deve retornar uma Promise<boolean>\n */\n checkAuthFn?: () => Promise<boolean> | boolean;\n /**\n * Função para fazer logout\n */\n signOutFn?: () => void;\n /**\n * Estado de autenticação inicial\n */\n initialAuthState?: Partial<AuthState>;\n /**\n * Função para obter dados do usuário (opcional)\n */\n getUserFn?: () => AuthUser | null | undefined;\n /**\n * Função para obter informações da sessão (opcional)\n */\n getSessionFn?: () => SessionInfo | null | undefined;\n /**\n * Função para obter tokens (opcional)\n */\n getTokensFn?: () => AuthTokens | null | undefined;\n}\n\n/**\n * Authentication provider that manages global auth state\n * Compatible with any store (Zustand, Redux, Context, etc.)\n *\n * @param {AuthProviderProps} props - The provider props\n * @returns {JSX.Element} The provider component\n *\n * @example\n * ```tsx\n * <AuthProvider\n * checkAuthFn={checkAuthFunction}\n * signOutFn={signOutFunction}\n * getUserFn={getUserFunction}\n * >\n * <App />\n * </AuthProvider>\n * ```\n */\nexport const AuthProvider = ({\n children,\n checkAuthFn,\n signOutFn,\n initialAuthState = {},\n getUserFn,\n getSessionFn,\n getTokensFn,\n}: AuthProviderProps) => {\n const [authState, setAuthState] = useState<AuthState>({\n isAuthenticated: false,\n isLoading: true,\n ...initialAuthState,\n });\n\n /**\n * Check authentication status and update state accordingly\n *\n * @returns {Promise<boolean>} Promise that resolves to authentication status\n */\n const checkAuth = useCallback(async (): Promise<boolean> => {\n try {\n setAuthState((prev) => ({ ...prev, isLoading: true }));\n\n // Se não há função de verificação, assume como não autenticado\n if (!checkAuthFn) {\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n\n const isAuth = await checkAuthFn();\n\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: isAuth,\n isLoading: false,\n user: getUserFn ? getUserFn() : prev.user,\n sessionInfo: getSessionFn ? getSessionFn() : prev.sessionInfo,\n tokens: getTokensFn ? getTokensFn() : prev.tokens,\n }));\n\n return isAuth;\n } catch (error) {\n console.error('Erro ao verificar autenticação:', error);\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n isLoading: false,\n }));\n return false;\n }\n }, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]);\n\n /**\n * Sign out the current user and clear auth state\n *\n * @returns {void}\n */\n const signOut = useCallback(() => {\n if (signOutFn) {\n signOutFn();\n }\n setAuthState((prev) => ({\n ...prev,\n isAuthenticated: false,\n user: undefined,\n sessionInfo: undefined,\n tokens: undefined,\n }));\n }, [signOutFn]);\n\n useEffect(() => {\n checkAuth();\n }, [checkAuth]);\n\n const contextValue = useMemo(\n (): AuthContextType => ({\n ...authState,\n checkAuth,\n signOut,\n }),\n [authState, checkAuth, signOut]\n );\n\n return (\n <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>\n );\n};\n\n/**\n * Hook to use the authentication context\n *\n * @throws {Error} When used outside of AuthProvider\n * @returns {AuthContextType} The authentication context\n *\n * @example\n * ```tsx\n * const { isAuthenticated, user, signOut } = useAuth();\n * ```\n */\nexport const useAuth = (): AuthContextType => {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error('useAuth deve ser usado dentro de um AuthProvider');\n }\n return context;\n};\n\n/**\n * Props for the ProtectedRoute component\n *\n * @interface ProtectedRouteProps\n * @property {ReactNode} children - Components to render when authenticated\n * @property {string} [redirectTo] - Path to redirect when not authenticated (default: '/')\n * @property {ReactNode} [loadingComponent] - Custom loading component\n * @property {(authState: AuthState) => boolean} [additionalCheck] - Additional authentication check\n */\nexport interface ProtectedRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento quando não autenticado\n */\n redirectTo?: string;\n /**\n * Componente de loading personalizado\n */\n loadingComponent?: ReactNode;\n /**\n * Função adicional de verificação (ex: verificar permissões específicas)\n */\n additionalCheck?: (authState: AuthState) => boolean;\n}\n\n/**\n * Componente para proteger rotas que requerem autenticação\n *\n * @example\n * ```tsx\n * <ProtectedRoute redirectTo=\"/login\">\n * <PainelPage />\n * </ProtectedRoute>\n * ```\n */\nexport const ProtectedRoute = ({\n children,\n redirectTo = '/',\n loadingComponent,\n additionalCheck,\n}: ProtectedRouteProps) => {\n const { isAuthenticated, isLoading, ...authState } = useAuth();\n\n // Componente de loading padrão\n const defaultLoadingComponent = (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n\n // Mostrar loading enquanto verifica autenticação\n if (isLoading) {\n return <>{loadingComponent || defaultLoadingComponent}</>;\n }\n\n // Verificar autenticação básica\n if (!isAuthenticated) {\n if (typeof window !== 'undefined') {\n const rootDomain = getRootDomain();\n // Only redirect if the root domain is different from current location\n const currentLocation = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}`;\n if (rootDomain !== currentLocation) {\n window.location.href = rootDomain;\n return null;\n }\n }\n return <Navigate to={redirectTo} replace />;\n }\n\n // Verificação adicional (ex: permissões)\n if (\n additionalCheck &&\n !additionalCheck({ isAuthenticated, isLoading, ...authState })\n ) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Props for the PublicRoute component\n *\n * @interface PublicRouteProps\n * @property {ReactNode} children - Components to render\n * @property {string} [redirectTo] - Path to redirect to (default: '/painel')\n * @property {boolean} [redirectIfAuthenticated] - Whether to redirect if authenticated\n * @property {boolean} [checkAuthBeforeRender] - Whether to check auth before rendering\n */\nexport interface PublicRouteProps {\n children: ReactNode;\n /**\n * Path para redirecionamento\n */\n redirectTo?: string;\n /**\n * Se deve redirecionar quando usuário estiver autenticado\n */\n redirectIfAuthenticated?: boolean;\n /**\n * Se deve verificar autenticação antes de renderizar\n */\n checkAuthBeforeRender?: boolean;\n}\n\n/**\n * Componente para rotas públicas (login, recuperação de senha, etc.)\n * Opcionalmente redireciona se o usuário já estiver autenticado\n *\n * @example\n * ```tsx\n * <PublicRoute redirectTo=\"/painel\" redirectIfAuthenticated={true}>\n * <LoginPage />\n * </PublicRoute>\n * ```\n */\nexport const PublicRoute = ({\n children,\n redirectTo = '/painel',\n redirectIfAuthenticated = false,\n checkAuthBeforeRender = false,\n}: PublicRouteProps) => {\n const { isAuthenticated, isLoading } = useAuth();\n\n // Se deve aguardar verificação de auth antes de renderizar\n if (checkAuthBeforeRender && isLoading) {\n return (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-text-950 text-lg\">Carregando...</div>\n </div>\n );\n }\n\n // Redirecionar se já autenticado e configurado para isso\n if (isAuthenticated && redirectIfAuthenticated) {\n return <Navigate to={redirectTo} replace />;\n }\n\n return <>{children}</>;\n};\n\n/**\n * Higher-Order Component to protect components with authentication\n *\n * @template P - Component props type\n * @param {ComponentType<P>} Component - Component to wrap with authentication\n * @param {Omit<ProtectedRouteProps, 'children'>} [options] - Protection options\n * @returns {(props: P) => JSX.Element} Wrapped component\n *\n * @example\n * ```tsx\n * const ProtectedComponent = withAuth(MyComponent, {\n * redirectTo: \"/login\",\n * loadingComponent: <CustomSpinner />\n * });\n * ```\n */\nexport const withAuth = <P extends object>(\n Component: ComponentType<P>,\n options: Omit<ProtectedRouteProps, 'children'> = {}\n) => {\n return (props: P) => (\n <ProtectedRoute {...options}>\n <Component {...props} />\n </ProtectedRoute>\n );\n};\n\n/**\n * Hook for authentication guard with custom checks\n *\n * @param {object} [options] - Guard options\n * @param {boolean} [options.requireAuth=true] - Whether authentication is required\n * @param {(authState: AuthState) => boolean} [options.customCheck] - Custom check function\n * @returns {object} Guard result with canAccess, isLoading, and authState\n *\n * @example\n * ```tsx\n * const { canAccess, isLoading } = useAuthGuard({\n * requireAuth: true,\n * customCheck: (authState) => authState.user?.role === 'admin'\n * });\n * ```\n */\nexport const useAuthGuard = (\n options: {\n requireAuth?: boolean;\n customCheck?: (authState: AuthState) => boolean;\n } = {}\n) => {\n const authState = useAuth();\n const { requireAuth = true, customCheck } = options;\n\n const canAccess =\n !authState.isLoading &&\n (requireAuth\n ? authState.isAuthenticated && (!customCheck || customCheck(authState))\n : !authState.isAuthenticated || !customCheck || customCheck(authState));\n\n return {\n canAccess,\n isLoading: authState.isLoading,\n authState,\n };\n};\n\n/**\n * Hook to check authentication on specific routes\n * Useful for conditional checks within components\n *\n * @param {string} [fallbackPath='/'] - Path to redirect when not authenticated\n * @returns {object} Object with isAuthenticated, isLoading, and redirectToLogin function\n *\n * @example\n * ```tsx\n * const { isAuthenticated, redirectToLogin } = useRouteAuth();\n *\n * if (!isAuthenticated) {\n * return redirectToLogin();\n * }\n * ```\n */\nexport const useRouteAuth = (fallbackPath = '/') => {\n const { isAuthenticated, isLoading } = useAuth();\n const location = useLocation();\n\n const redirectToLogin = () => (\n <Navigate to={fallbackPath} state={{ from: location }} replace />\n );\n\n return {\n isAuthenticated,\n isLoading,\n redirectToLogin,\n };\n};\n\n/**\n * Get the root domain from the current window location\n * Handles localhost and subdomain cases\n *\n * @returns {string} The root domain URL\n */\nexport const getRootDomain = () => {\n const { hostname, protocol, port } = window.location;\n const portStr = port ? ':' + port : '';\n if (hostname === 'localhost') {\n return `${protocol}//${hostname}${portStr}`;\n }\n const parts = hostname.split('.');\n // Only treat as subdomain if there are 3+ parts (e.g., subdomain.example.com)\n if (parts.length > 2) {\n // Return the last 2 parts as the root domain (example.com)\n const base = parts.slice(-2).join('.');\n return `${protocol}//${base}${portStr}`;\n }\n // For 2-part domains (example.com) or single domains, return as-is\n return `${protocol}//${hostname}${portStr}`;\n};\n\nexport default {\n AuthProvider,\n ProtectedRoute,\n PublicRoute,\n withAuth,\n useAuth,\n useAuthGuard,\n useRouteAuth,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBASO;AACP,8BAAsC;AA8OlC;AAtJJ,IAAM,kBAAc,4BAA2C,MAAS;AA6DjE,IAAM,eAAe,CAAC;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAmB,CAAC;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AACF,MAAyB;AACvB,QAAM,CAAC,WAAW,YAAY,QAAI,uBAAoB;AAAA,IACpD,iBAAiB;AAAA,IACjB,WAAW;AAAA,IACX,GAAG;AAAA,EACL,CAAC;AAOD,QAAM,gBAAY,0BAAY,YAA8B;AAC1D,QAAI;AACF,mBAAa,CAAC,UAAU,EAAE,GAAG,MAAM,WAAW,KAAK,EAAE;AAGrD,UAAI,CAAC,aAAa;AAChB,qBAAa,CAAC,UAAU;AAAA,UACtB,GAAG;AAAA,UACH,iBAAiB;AAAA,UACjB,WAAW;AAAA,QACb,EAAE;AACF,eAAO;AAAA,MACT;AAEA,YAAM,SAAS,MAAM,YAAY;AAEjC,mBAAa,CAAC,UAAU;AAAA,QACtB,GAAG;AAAA,QACH,iBAAiB;AAAA,QACjB,WAAW;AAAA,QACX,MAAM,YAAY,UAAU,IAAI,KAAK;AAAA,QACrC,aAAa,eAAe,aAAa,IAAI,KAAK;AAAA,QAClD,QAAQ,cAAc,YAAY,IAAI,KAAK;AAAA,MAC7C,EAAE;AAEF,aAAO;AAAA,IACT,SAAS,OAAO;AACd,cAAQ,MAAM,yCAAmC,KAAK;AACtD,mBAAa,CAAC,UAAU;AAAA,QACtB,GAAG;AAAA,QACH,iBAAiB;AAAA,QACjB,WAAW;AAAA,MACb,EAAE;AACF,aAA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,IAAI,QAAQ;AAC/C,QAAM,eAAW,qCAAY;AAE7B,QAAM,kBAAkB,MACtB,4CAAC,oCAAS,IAAI,cAAc,OAAO,EAAE,MAAM,SAAS,GAAG,SAAO,MAAC;AAGjE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAQO,IAAM,gBAAgB,MAAM;AACjC,QAAM,EAAE,UAAU,UAAU,KAAK,IAAI,OAAO;AAC5C,QAAM,UAAU,OAAO,MAAM,OAAO;AACpC,MAAI,aAAa,aAAa;AAC5B,WAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC3C;AACA,QAAM,QAAQ,SAAS,MAAM,GAAG;AAEhC,MAAI,MAAM,SAAS,GAAG;AAEpB,UAAM,OAAO,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACrC,WAAO,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACvC;AAEA,SAAO,GAAG,QAAQ,KAAK,QAAQ,GAAG,OAAO;AAC3C;AAEA,IAAO,eAAQ;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
@@ -99,6 +99,14 @@ var ProtectedRoute = ({
99
99
  return /* @__PURE__ */ jsx(Fragment, { children: loadingComponent || defaultLoadingComponent });
100
100
  }
101
101
  if (!isAuthenticated) {
102
+ if (typeof window !== "undefined") {
103
+ const rootDomain = getRootDomain();
104
+ const currentLocation = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ":" + window.location.port : ""}`;
105
+ if (rootDomain !== currentLocation) {
106
+ window.location.href = rootDomain;
107
+ return null;
108
+ }
109
+ }
102
110
  return /* @__PURE__ */ jsx(Navigate, { to: redirectTo, replace: true });
103
111
  }
104
112
  if (additionalCheck && !additionalCheck({ isAuthenticated, isLoading, ...authState })) {
@@ -144,6 +152,19 @@ var useRouteAuth = (fallbackPath = "/") => {
144
152
  redirectToLogin
145
153
  };
146
154
  };
155
+ var getRootDomain = () => {
156
+ const { hostname, protocol, port } = window.location;
157
+ const portStr = port ? ":" + port : "";
158
+ if (hostname === "localhost") {
159
+ return `${protocol}//${hostname}${portStr}`;
160
+ }
161
+ const parts = hostname.split(".");
162
+ if (parts.length > 2) {
163
+ const base = parts.slice(-2).join(".");
164
+ return `${protocol}//${base}${portStr}`;
165
+ }
166
+ return `${protocol}//${hostname}${portStr}`;
167
+ };
147
168
  var Auth_default = {
148
169
  AuthProvider,
149
170
  ProtectedRoute,
@@ -158,6 +179,7 @@ export {
158
179
  ProtectedRoute,
159
180
  PublicRoute,
160
181
  Auth_default as default,
182
+ getRootDomain,
161
183
  useAuth,
162
184
  useAuthGuard,
163
185
  useRouteAuth,