@nocios/crudify-ui 4.0.94 → 4.0.98
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-DxFMT2hN.d.ts → LoginComponent-saSn0o5x.d.mts} +0 -1
- package/dist/{index-CY6Qkw3q.d.mts → LoginComponent-saSn0o5x.d.ts} +0 -1
- package/dist/{chunk-3SLGRD36.js → chunk-5AQJTODW.js} +1 -1
- package/dist/chunk-5JKS55SE.mjs +1 -0
- package/dist/{chunk-5PZJJNHP.mjs → chunk-6WYDSIJ6.mjs} +1 -1
- package/dist/chunk-AT74WV5W.js +1 -0
- package/dist/{chunk-Q7FTH5JW.js → chunk-IJOEEO3Z.js} +1 -1
- package/dist/chunk-IO4RPCSZ.mjs +1 -0
- package/dist/{chunk-5INZZQD6.mjs → chunk-O52COIJA.mjs} +1 -1
- package/dist/chunk-VQUXX5W3.js +1 -0
- package/dist/components.d.mts +22 -2
- package/dist/components.d.ts +22 -2
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/errorTranslation-CBbQYNWR.d.ts +124 -0
- package/dist/errorTranslation-DqdgLEUy.d.mts +124 -0
- package/dist/hooks.d.mts +1 -1
- package/dist/hooks.d.ts +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/{index-BoWx_rFw.d.mts → index-BwF68SOh.d.mts} +19 -3
- package/dist/{index-CQttyYlB.d.ts → index-Fkm9ErmY.d.ts} +19 -3
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/utils.d.mts +121 -116
- package/dist/utils.d.ts +121 -116
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +13 -3
- package/vitest.config.ts +27 -0
- package/dist/chunk-2OSNNNID.js +0 -1
- package/dist/chunk-6EBMA4HZ.js +0 -1
- package/dist/chunk-VVXZWBHL.mjs +0 -1
- package/dist/chunk-YS3C7YG5.mjs +0 -1
package/dist/utils.d.mts
CHANGED
|
@@ -1,124 +1,129 @@
|
|
|
1
|
-
|
|
1
|
+
export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, k as ErrorCode, l as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, o as createErrorTranslator, d as decodeJwtSafely, a as getCookie, g as getCurrentUserEmail, f as getErrorMessage, h as handleCrudifyError, i as isTokenExpired, p as parseApiError, e as parseJavaScriptError, c as parseTransactionError, b as secureLocalStorage, s as secureSessionStorage, n as translateError, t as translateErrorCode, m as translateErrorCodes } from './errorTranslation-DqdgLEUy.mjs';
|
|
2
|
+
import './api-Djqihi4n.mjs';
|
|
2
3
|
|
|
3
|
-
interface JWTPayload extends JwtPayload {
|
|
4
|
-
"cognito:username"?: string;
|
|
5
|
-
}
|
|
6
|
-
declare const decodeJwtSafely: (token: string) => JWTPayload | null;
|
|
7
|
-
declare const getCurrentUserEmail: () => string | null;
|
|
8
|
-
declare const isTokenExpired: (token: string) => boolean;
|
|
9
|
-
|
|
10
|
-
declare const getCookie: (name: string) => string | null;
|
|
11
|
-
|
|
12
|
-
declare class SecureStorage {
|
|
13
|
-
private readonly encryptionKey;
|
|
14
|
-
private readonly storage;
|
|
15
|
-
constructor(storageType?: "localStorage" | "sessionStorage");
|
|
16
|
-
private generateEncryptionKey;
|
|
17
|
-
setItem(key: string, value: string, expiryMinutes?: number): void;
|
|
18
|
-
getItem(key: string): string | null;
|
|
19
|
-
removeItem(key: string): void;
|
|
20
|
-
setToken(token: string): void;
|
|
21
|
-
getToken(): string | null;
|
|
22
|
-
}
|
|
23
|
-
declare const secureSessionStorage: SecureStorage;
|
|
24
|
-
declare const secureLocalStorage: SecureStorage;
|
|
25
|
-
|
|
26
|
-
declare const ERROR_CODES: {
|
|
27
|
-
readonly INVALID_CREDENTIALS: "INVALID_CREDENTIALS";
|
|
28
|
-
readonly UNAUTHORIZED: "UNAUTHORIZED";
|
|
29
|
-
readonly INVALID_API_KEY: "INVALID_API_KEY";
|
|
30
|
-
readonly USER_NOT_FOUND: "USER_NOT_FOUND";
|
|
31
|
-
readonly USER_NOT_ACTIVE: "USER_NOT_ACTIVE";
|
|
32
|
-
readonly NO_PERMISSION: "NO_PERMISSION";
|
|
33
|
-
readonly ITEM_NOT_FOUND: "ITEM_NOT_FOUND";
|
|
34
|
-
readonly NOT_FOUND: "NOT_FOUND";
|
|
35
|
-
readonly IN_USE: "IN_USE";
|
|
36
|
-
readonly FIELD_ERROR: "FIELD_ERROR";
|
|
37
|
-
readonly BAD_REQUEST: "BAD_REQUEST";
|
|
38
|
-
readonly INVALID_EMAIL: "INVALID_EMAIL";
|
|
39
|
-
readonly INVALID_CODE: "INVALID_CODE";
|
|
40
|
-
readonly INTERNAL_SERVER_ERROR: "INTERNAL_SERVER_ERROR";
|
|
41
|
-
readonly DATABASE_CONNECTION_ERROR: "DATABASE_CONNECTION_ERROR";
|
|
42
|
-
readonly INVALID_CONFIGURATION: "INVALID_CONFIGURATION";
|
|
43
|
-
readonly UNKNOWN_OPERATION: "UNKNOWN_OPERATION";
|
|
44
|
-
readonly TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS";
|
|
45
|
-
readonly NETWORK_ERROR: "NETWORK_ERROR";
|
|
46
|
-
readonly TIMEOUT_ERROR: "TIMEOUT_ERROR";
|
|
47
|
-
};
|
|
48
|
-
type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
|
|
49
|
-
type ErrorSeverity = "info" | "warning" | "error" | "critical";
|
|
50
|
-
declare const ERROR_SEVERITY_MAP: Record<ErrorCode, ErrorSeverity>;
|
|
51
|
-
interface ParsedError {
|
|
52
|
-
code: ErrorCode;
|
|
53
|
-
message: string;
|
|
54
|
-
severity: ErrorSeverity;
|
|
55
|
-
field?: string;
|
|
56
|
-
details?: Record<string, unknown>;
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Parse a Crudify API response and extract standardized error information
|
|
60
|
-
*/
|
|
61
|
-
declare function parseApiError(response: unknown): ParsedError[];
|
|
62
|
-
/**
|
|
63
|
-
* Parse transaction response errors
|
|
64
|
-
*/
|
|
65
|
-
declare function parseTransactionError(response: unknown): ParsedError[];
|
|
66
|
-
/**
|
|
67
|
-
* Get a human-readable error message for an error code
|
|
68
|
-
*/
|
|
69
|
-
declare function getErrorMessage(code: ErrorCode): string;
|
|
70
|
-
/**
|
|
71
|
-
* Handle JavaScript/Network errors and convert to ParsedError
|
|
72
|
-
*/
|
|
73
|
-
declare function parseJavaScriptError(error: unknown): ParsedError;
|
|
74
4
|
/**
|
|
75
|
-
*
|
|
5
|
+
* Event Bus para coordinar acciones de autenticación
|
|
6
|
+
* Previene race conditions y asegura respuesta única a errores
|
|
7
|
+
*
|
|
8
|
+
* Uso:
|
|
9
|
+
* - Emitir eventos cuando hay errores de autenticación
|
|
10
|
+
* - Suscribirse para recibir notificaciones de eventos
|
|
11
|
+
* - Debounce automático para evitar múltiples disparos
|
|
76
12
|
*/
|
|
77
|
-
|
|
13
|
+
type AuthEventType = "SESSION_EXPIRED" | "TOKEN_REFRESH_FAILED" | "UNAUTHORIZED" | "TOKEN_EXPIRED";
|
|
14
|
+
type AuthEventDetails = {
|
|
15
|
+
message?: string;
|
|
16
|
+
error?: any;
|
|
17
|
+
source?: string;
|
|
18
|
+
};
|
|
19
|
+
type AuthEvent = {
|
|
20
|
+
type: AuthEventType;
|
|
21
|
+
details?: AuthEventDetails;
|
|
22
|
+
timestamp: number;
|
|
23
|
+
};
|
|
24
|
+
type AuthEventListener = (event: AuthEvent) => void;
|
|
25
|
+
declare class AuthEventBus {
|
|
26
|
+
private static instance;
|
|
27
|
+
private listeners;
|
|
28
|
+
private isHandlingAuthError;
|
|
29
|
+
private lastErrorTime;
|
|
30
|
+
private lastEventType;
|
|
31
|
+
private readonly DEBOUNCE_TIME;
|
|
32
|
+
private constructor();
|
|
33
|
+
static getInstance(): AuthEventBus;
|
|
34
|
+
/**
|
|
35
|
+
* Emitir evento de error de autenticación
|
|
36
|
+
* Con debounce para evitar múltiples disparos
|
|
37
|
+
*/
|
|
38
|
+
emit(type: AuthEventType, details?: AuthEventDetails): void;
|
|
39
|
+
/**
|
|
40
|
+
* Suscribirse a eventos de autenticación
|
|
41
|
+
* @returns Función de cleanup para desuscribirse
|
|
42
|
+
*/
|
|
43
|
+
subscribe(listener: AuthEventListener): () => void;
|
|
44
|
+
/**
|
|
45
|
+
* Limpiar todos los listeners
|
|
46
|
+
*/
|
|
47
|
+
clear(): void;
|
|
48
|
+
/**
|
|
49
|
+
* Verificar si hay un evento siendo manejado
|
|
50
|
+
*/
|
|
51
|
+
isHandling(): boolean;
|
|
52
|
+
}
|
|
53
|
+
declare const authEventBus: AuthEventBus;
|
|
78
54
|
|
|
79
55
|
/**
|
|
80
|
-
*
|
|
81
|
-
*
|
|
56
|
+
* Sistema global de tracking de navegación para evitar monkey-patching anidado
|
|
57
|
+
* Usa patrón singleton con reference counting
|
|
58
|
+
*
|
|
59
|
+
* Problema que resuelve:
|
|
60
|
+
* - Si múltiples componentes usan useSession, cada uno crearía su propio monkey-patch
|
|
61
|
+
* - Esto causa anidamiento infinito de patches
|
|
62
|
+
* - NavigationTracker centraliza el patching con reference counting
|
|
63
|
+
*
|
|
64
|
+
* Uso:
|
|
65
|
+
* ```typescript
|
|
66
|
+
* const tracker = NavigationTracker.getInstance();
|
|
67
|
+
* const unsubscribe = tracker.subscribe(() => {
|
|
68
|
+
* console.log("Navigation detected!");
|
|
69
|
+
* });
|
|
70
|
+
*
|
|
71
|
+
* // Cleanup
|
|
72
|
+
* unsubscribe();
|
|
73
|
+
* ```
|
|
82
74
|
*/
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
75
|
+
type NavigationCallback = () => void;
|
|
76
|
+
declare class NavigationTracker {
|
|
77
|
+
private static instance;
|
|
78
|
+
private isPatched;
|
|
79
|
+
private refCount;
|
|
80
|
+
private listeners;
|
|
81
|
+
private originalPushState;
|
|
82
|
+
private originalReplaceState;
|
|
83
|
+
private constructor();
|
|
84
|
+
/**
|
|
85
|
+
* Obtener instancia singleton
|
|
86
|
+
*/
|
|
87
|
+
static getInstance(): NavigationTracker;
|
|
88
|
+
/**
|
|
89
|
+
* Suscribirse a eventos de navegación
|
|
90
|
+
* @param callback - Función a llamar cuando hay navegación
|
|
91
|
+
* @returns Función de cleanup para desuscribirse
|
|
92
|
+
*/
|
|
93
|
+
subscribe(callback: NavigationCallback): () => void;
|
|
94
|
+
/**
|
|
95
|
+
* Desuscribirse de eventos de navegación
|
|
96
|
+
* @private
|
|
97
|
+
*/
|
|
98
|
+
private unsubscribe;
|
|
99
|
+
/**
|
|
100
|
+
* Aplicar monkey-patches a history API
|
|
101
|
+
* @private
|
|
102
|
+
*/
|
|
103
|
+
private applyPatches;
|
|
104
|
+
/**
|
|
105
|
+
* Remover monkey-patches y restaurar métodos originales
|
|
106
|
+
* @private
|
|
107
|
+
*/
|
|
108
|
+
private removePatches;
|
|
109
|
+
/**
|
|
110
|
+
* Notificar a todos los listeners
|
|
111
|
+
* @private
|
|
112
|
+
*/
|
|
113
|
+
private notifyListeners;
|
|
114
|
+
/**
|
|
115
|
+
* Para testing: limpiar completamente el tracker
|
|
116
|
+
* ⚠️ SOLO USAR EN TESTS
|
|
117
|
+
*/
|
|
118
|
+
static reset(): void;
|
|
119
|
+
/**
|
|
120
|
+
* Obtener número de suscriptores activos (útil para debugging)
|
|
121
|
+
*/
|
|
122
|
+
getSubscriberCount(): number;
|
|
123
|
+
/**
|
|
124
|
+
* Verificar si los patches están activos
|
|
125
|
+
*/
|
|
126
|
+
isActive(): boolean;
|
|
90
127
|
}
|
|
91
|
-
/**
|
|
92
|
-
* Traduce un código de error usando jerarquía de fallbacks
|
|
93
|
-
*/
|
|
94
|
-
declare function translateErrorCode(errorCode: string, config: ErrorTranslationConfig): string;
|
|
95
|
-
/**
|
|
96
|
-
* Traduce múltiples códigos de error
|
|
97
|
-
*/
|
|
98
|
-
declare function translateErrorCodes(errorCodes: string[], config: ErrorTranslationConfig): string[];
|
|
99
|
-
/**
|
|
100
|
-
* Traduce un error completo (código + mensaje personalizado)
|
|
101
|
-
*/
|
|
102
|
-
declare function translateError(error: {
|
|
103
|
-
code: string;
|
|
104
|
-
message?: string;
|
|
105
|
-
field?: string;
|
|
106
|
-
}, config: ErrorTranslationConfig): string;
|
|
107
|
-
/**
|
|
108
|
-
* Hook para usar en componentes React con i18next
|
|
109
|
-
*/
|
|
110
|
-
declare function createErrorTranslator(translateFn: (key: string) => string, options?: {
|
|
111
|
-
currentLanguage?: string;
|
|
112
|
-
enableDebug?: boolean;
|
|
113
|
-
}): {
|
|
114
|
-
translateErrorCode: (code: string) => string;
|
|
115
|
-
translateErrorCodes: (codes: string[]) => string[];
|
|
116
|
-
translateError: (error: {
|
|
117
|
-
code: string;
|
|
118
|
-
message?: string;
|
|
119
|
-
field?: string;
|
|
120
|
-
}) => string;
|
|
121
|
-
translateApiError: (apiResponse: any) => string;
|
|
122
|
-
};
|
|
123
128
|
|
|
124
|
-
export {
|
|
129
|
+
export { type AuthEvent, type AuthEventDetails, type AuthEventType, NavigationTracker, authEventBus };
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,124 +1,129 @@
|
|
|
1
|
-
|
|
1
|
+
export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, k as ErrorCode, l as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, o as createErrorTranslator, d as decodeJwtSafely, a as getCookie, g as getCurrentUserEmail, f as getErrorMessage, h as handleCrudifyError, i as isTokenExpired, p as parseApiError, e as parseJavaScriptError, c as parseTransactionError, b as secureLocalStorage, s as secureSessionStorage, n as translateError, t as translateErrorCode, m as translateErrorCodes } from './errorTranslation-CBbQYNWR.js';
|
|
2
|
+
import './api-Djqihi4n.js';
|
|
2
3
|
|
|
3
|
-
interface JWTPayload extends JwtPayload {
|
|
4
|
-
"cognito:username"?: string;
|
|
5
|
-
}
|
|
6
|
-
declare const decodeJwtSafely: (token: string) => JWTPayload | null;
|
|
7
|
-
declare const getCurrentUserEmail: () => string | null;
|
|
8
|
-
declare const isTokenExpired: (token: string) => boolean;
|
|
9
|
-
|
|
10
|
-
declare const getCookie: (name: string) => string | null;
|
|
11
|
-
|
|
12
|
-
declare class SecureStorage {
|
|
13
|
-
private readonly encryptionKey;
|
|
14
|
-
private readonly storage;
|
|
15
|
-
constructor(storageType?: "localStorage" | "sessionStorage");
|
|
16
|
-
private generateEncryptionKey;
|
|
17
|
-
setItem(key: string, value: string, expiryMinutes?: number): void;
|
|
18
|
-
getItem(key: string): string | null;
|
|
19
|
-
removeItem(key: string): void;
|
|
20
|
-
setToken(token: string): void;
|
|
21
|
-
getToken(): string | null;
|
|
22
|
-
}
|
|
23
|
-
declare const secureSessionStorage: SecureStorage;
|
|
24
|
-
declare const secureLocalStorage: SecureStorage;
|
|
25
|
-
|
|
26
|
-
declare const ERROR_CODES: {
|
|
27
|
-
readonly INVALID_CREDENTIALS: "INVALID_CREDENTIALS";
|
|
28
|
-
readonly UNAUTHORIZED: "UNAUTHORIZED";
|
|
29
|
-
readonly INVALID_API_KEY: "INVALID_API_KEY";
|
|
30
|
-
readonly USER_NOT_FOUND: "USER_NOT_FOUND";
|
|
31
|
-
readonly USER_NOT_ACTIVE: "USER_NOT_ACTIVE";
|
|
32
|
-
readonly NO_PERMISSION: "NO_PERMISSION";
|
|
33
|
-
readonly ITEM_NOT_FOUND: "ITEM_NOT_FOUND";
|
|
34
|
-
readonly NOT_FOUND: "NOT_FOUND";
|
|
35
|
-
readonly IN_USE: "IN_USE";
|
|
36
|
-
readonly FIELD_ERROR: "FIELD_ERROR";
|
|
37
|
-
readonly BAD_REQUEST: "BAD_REQUEST";
|
|
38
|
-
readonly INVALID_EMAIL: "INVALID_EMAIL";
|
|
39
|
-
readonly INVALID_CODE: "INVALID_CODE";
|
|
40
|
-
readonly INTERNAL_SERVER_ERROR: "INTERNAL_SERVER_ERROR";
|
|
41
|
-
readonly DATABASE_CONNECTION_ERROR: "DATABASE_CONNECTION_ERROR";
|
|
42
|
-
readonly INVALID_CONFIGURATION: "INVALID_CONFIGURATION";
|
|
43
|
-
readonly UNKNOWN_OPERATION: "UNKNOWN_OPERATION";
|
|
44
|
-
readonly TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS";
|
|
45
|
-
readonly NETWORK_ERROR: "NETWORK_ERROR";
|
|
46
|
-
readonly TIMEOUT_ERROR: "TIMEOUT_ERROR";
|
|
47
|
-
};
|
|
48
|
-
type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
|
|
49
|
-
type ErrorSeverity = "info" | "warning" | "error" | "critical";
|
|
50
|
-
declare const ERROR_SEVERITY_MAP: Record<ErrorCode, ErrorSeverity>;
|
|
51
|
-
interface ParsedError {
|
|
52
|
-
code: ErrorCode;
|
|
53
|
-
message: string;
|
|
54
|
-
severity: ErrorSeverity;
|
|
55
|
-
field?: string;
|
|
56
|
-
details?: Record<string, unknown>;
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Parse a Crudify API response and extract standardized error information
|
|
60
|
-
*/
|
|
61
|
-
declare function parseApiError(response: unknown): ParsedError[];
|
|
62
|
-
/**
|
|
63
|
-
* Parse transaction response errors
|
|
64
|
-
*/
|
|
65
|
-
declare function parseTransactionError(response: unknown): ParsedError[];
|
|
66
|
-
/**
|
|
67
|
-
* Get a human-readable error message for an error code
|
|
68
|
-
*/
|
|
69
|
-
declare function getErrorMessage(code: ErrorCode): string;
|
|
70
|
-
/**
|
|
71
|
-
* Handle JavaScript/Network errors and convert to ParsedError
|
|
72
|
-
*/
|
|
73
|
-
declare function parseJavaScriptError(error: unknown): ParsedError;
|
|
74
4
|
/**
|
|
75
|
-
*
|
|
5
|
+
* Event Bus para coordinar acciones de autenticación
|
|
6
|
+
* Previene race conditions y asegura respuesta única a errores
|
|
7
|
+
*
|
|
8
|
+
* Uso:
|
|
9
|
+
* - Emitir eventos cuando hay errores de autenticación
|
|
10
|
+
* - Suscribirse para recibir notificaciones de eventos
|
|
11
|
+
* - Debounce automático para evitar múltiples disparos
|
|
76
12
|
*/
|
|
77
|
-
|
|
13
|
+
type AuthEventType = "SESSION_EXPIRED" | "TOKEN_REFRESH_FAILED" | "UNAUTHORIZED" | "TOKEN_EXPIRED";
|
|
14
|
+
type AuthEventDetails = {
|
|
15
|
+
message?: string;
|
|
16
|
+
error?: any;
|
|
17
|
+
source?: string;
|
|
18
|
+
};
|
|
19
|
+
type AuthEvent = {
|
|
20
|
+
type: AuthEventType;
|
|
21
|
+
details?: AuthEventDetails;
|
|
22
|
+
timestamp: number;
|
|
23
|
+
};
|
|
24
|
+
type AuthEventListener = (event: AuthEvent) => void;
|
|
25
|
+
declare class AuthEventBus {
|
|
26
|
+
private static instance;
|
|
27
|
+
private listeners;
|
|
28
|
+
private isHandlingAuthError;
|
|
29
|
+
private lastErrorTime;
|
|
30
|
+
private lastEventType;
|
|
31
|
+
private readonly DEBOUNCE_TIME;
|
|
32
|
+
private constructor();
|
|
33
|
+
static getInstance(): AuthEventBus;
|
|
34
|
+
/**
|
|
35
|
+
* Emitir evento de error de autenticación
|
|
36
|
+
* Con debounce para evitar múltiples disparos
|
|
37
|
+
*/
|
|
38
|
+
emit(type: AuthEventType, details?: AuthEventDetails): void;
|
|
39
|
+
/**
|
|
40
|
+
* Suscribirse a eventos de autenticación
|
|
41
|
+
* @returns Función de cleanup para desuscribirse
|
|
42
|
+
*/
|
|
43
|
+
subscribe(listener: AuthEventListener): () => void;
|
|
44
|
+
/**
|
|
45
|
+
* Limpiar todos los listeners
|
|
46
|
+
*/
|
|
47
|
+
clear(): void;
|
|
48
|
+
/**
|
|
49
|
+
* Verificar si hay un evento siendo manejado
|
|
50
|
+
*/
|
|
51
|
+
isHandling(): boolean;
|
|
52
|
+
}
|
|
53
|
+
declare const authEventBus: AuthEventBus;
|
|
78
54
|
|
|
79
55
|
/**
|
|
80
|
-
*
|
|
81
|
-
*
|
|
56
|
+
* Sistema global de tracking de navegación para evitar monkey-patching anidado
|
|
57
|
+
* Usa patrón singleton con reference counting
|
|
58
|
+
*
|
|
59
|
+
* Problema que resuelve:
|
|
60
|
+
* - Si múltiples componentes usan useSession, cada uno crearía su propio monkey-patch
|
|
61
|
+
* - Esto causa anidamiento infinito de patches
|
|
62
|
+
* - NavigationTracker centraliza el patching con reference counting
|
|
63
|
+
*
|
|
64
|
+
* Uso:
|
|
65
|
+
* ```typescript
|
|
66
|
+
* const tracker = NavigationTracker.getInstance();
|
|
67
|
+
* const unsubscribe = tracker.subscribe(() => {
|
|
68
|
+
* console.log("Navigation detected!");
|
|
69
|
+
* });
|
|
70
|
+
*
|
|
71
|
+
* // Cleanup
|
|
72
|
+
* unsubscribe();
|
|
73
|
+
* ```
|
|
82
74
|
*/
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
75
|
+
type NavigationCallback = () => void;
|
|
76
|
+
declare class NavigationTracker {
|
|
77
|
+
private static instance;
|
|
78
|
+
private isPatched;
|
|
79
|
+
private refCount;
|
|
80
|
+
private listeners;
|
|
81
|
+
private originalPushState;
|
|
82
|
+
private originalReplaceState;
|
|
83
|
+
private constructor();
|
|
84
|
+
/**
|
|
85
|
+
* Obtener instancia singleton
|
|
86
|
+
*/
|
|
87
|
+
static getInstance(): NavigationTracker;
|
|
88
|
+
/**
|
|
89
|
+
* Suscribirse a eventos de navegación
|
|
90
|
+
* @param callback - Función a llamar cuando hay navegación
|
|
91
|
+
* @returns Función de cleanup para desuscribirse
|
|
92
|
+
*/
|
|
93
|
+
subscribe(callback: NavigationCallback): () => void;
|
|
94
|
+
/**
|
|
95
|
+
* Desuscribirse de eventos de navegación
|
|
96
|
+
* @private
|
|
97
|
+
*/
|
|
98
|
+
private unsubscribe;
|
|
99
|
+
/**
|
|
100
|
+
* Aplicar monkey-patches a history API
|
|
101
|
+
* @private
|
|
102
|
+
*/
|
|
103
|
+
private applyPatches;
|
|
104
|
+
/**
|
|
105
|
+
* Remover monkey-patches y restaurar métodos originales
|
|
106
|
+
* @private
|
|
107
|
+
*/
|
|
108
|
+
private removePatches;
|
|
109
|
+
/**
|
|
110
|
+
* Notificar a todos los listeners
|
|
111
|
+
* @private
|
|
112
|
+
*/
|
|
113
|
+
private notifyListeners;
|
|
114
|
+
/**
|
|
115
|
+
* Para testing: limpiar completamente el tracker
|
|
116
|
+
* ⚠️ SOLO USAR EN TESTS
|
|
117
|
+
*/
|
|
118
|
+
static reset(): void;
|
|
119
|
+
/**
|
|
120
|
+
* Obtener número de suscriptores activos (útil para debugging)
|
|
121
|
+
*/
|
|
122
|
+
getSubscriberCount(): number;
|
|
123
|
+
/**
|
|
124
|
+
* Verificar si los patches están activos
|
|
125
|
+
*/
|
|
126
|
+
isActive(): boolean;
|
|
90
127
|
}
|
|
91
|
-
/**
|
|
92
|
-
* Traduce un código de error usando jerarquía de fallbacks
|
|
93
|
-
*/
|
|
94
|
-
declare function translateErrorCode(errorCode: string, config: ErrorTranslationConfig): string;
|
|
95
|
-
/**
|
|
96
|
-
* Traduce múltiples códigos de error
|
|
97
|
-
*/
|
|
98
|
-
declare function translateErrorCodes(errorCodes: string[], config: ErrorTranslationConfig): string[];
|
|
99
|
-
/**
|
|
100
|
-
* Traduce un error completo (código + mensaje personalizado)
|
|
101
|
-
*/
|
|
102
|
-
declare function translateError(error: {
|
|
103
|
-
code: string;
|
|
104
|
-
message?: string;
|
|
105
|
-
field?: string;
|
|
106
|
-
}, config: ErrorTranslationConfig): string;
|
|
107
|
-
/**
|
|
108
|
-
* Hook para usar en componentes React con i18next
|
|
109
|
-
*/
|
|
110
|
-
declare function createErrorTranslator(translateFn: (key: string) => string, options?: {
|
|
111
|
-
currentLanguage?: string;
|
|
112
|
-
enableDebug?: boolean;
|
|
113
|
-
}): {
|
|
114
|
-
translateErrorCode: (code: string) => string;
|
|
115
|
-
translateErrorCodes: (codes: string[]) => string[];
|
|
116
|
-
translateError: (error: {
|
|
117
|
-
code: string;
|
|
118
|
-
message?: string;
|
|
119
|
-
field?: string;
|
|
120
|
-
}) => string;
|
|
121
|
-
translateApiError: (apiResponse: any) => string;
|
|
122
|
-
};
|
|
123
128
|
|
|
124
|
-
export {
|
|
129
|
+
export { type AuthEvent, type AuthEventDetails, type AuthEventType, NavigationTracker, authEventBus };
|
package/dist/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkNNY4A73Vjs = require('./chunk-NNY4A73V.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkNNY4A73Vjs = require('./chunk-NNY4A73V.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunkAT74WV5Wjs = require('./chunk-AT74WV5W.js');exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.NavigationTracker = _chunkAT74WV5Wjs.g; exports.authEventBus = _chunkAT74WV5Wjs.f; exports.createErrorTranslator = _chunkAT74WV5Wjs.e; exports.decodeJwtSafely = _chunkAT74WV5Wjs.h; exports.getCookie = _chunkAT74WV5Wjs.a; exports.getCurrentUserEmail = _chunkAT74WV5Wjs.i; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunkAT74WV5Wjs.j; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunkNNY4A73Vjs.b; exports.secureSessionStorage = _chunkNNY4A73Vjs.a; exports.translateError = _chunkAT74WV5Wjs.d; exports.translateErrorCode = _chunkAT74WV5Wjs.b; exports.translateErrorCodes = _chunkAT74WV5Wjs.c;
|
package/dist/utils.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as g,b as v}from"./chunk-T2CPA46I.mjs";import{a as f,b as l,c as m,d as u,e as x,f as d,g as c}from"./chunk-BJ6PIVZR.mjs";import{a as r,b as e,c as o,d as t,e as a,f as E,g as s,h as n,i as p,j as i}from"./chunk-5JKS55SE.mjs";export{f as ERROR_CODES,l as ERROR_SEVERITY_MAP,s as NavigationTracker,E as authEventBus,a as createErrorTranslator,n as decodeJwtSafely,r as getCookie,p as getCurrentUserEmail,x as getErrorMessage,c as handleCrudifyError,i as isTokenExpired,m as parseApiError,d as parseJavaScriptError,u as parseTransactionError,v as secureLocalStorage,g as secureSessionStorage,t as translateError,e as translateErrorCode,o as translateErrorCodes};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nocios/crudify-ui",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.98",
|
|
4
4
|
"description": "Biblioteca de componentes UI para Crudify",
|
|
5
5
|
"author": "Nocios",
|
|
6
6
|
"license": "MIT",
|
|
@@ -33,10 +33,13 @@
|
|
|
33
33
|
"build": "tsup",
|
|
34
34
|
"build:analyze": "tsup --metafile",
|
|
35
35
|
"start": "vite example",
|
|
36
|
+
"test": "vitest",
|
|
37
|
+
"test:ui": "vitest --ui",
|
|
38
|
+
"test:coverage": "vitest --coverage",
|
|
36
39
|
"prepublishOnly": "npm run build"
|
|
37
40
|
},
|
|
38
41
|
"dependencies": {
|
|
39
|
-
"@nocios/crudify-browser": "^4.0.
|
|
42
|
+
"@nocios/crudify-browser": "^4.0.8",
|
|
40
43
|
"crypto-js": "^4.2.0",
|
|
41
44
|
"dompurify": "^3.2.7",
|
|
42
45
|
"uuid": "^13.0.0"
|
|
@@ -54,11 +57,18 @@
|
|
|
54
57
|
"react-i18next": "^15.5.2"
|
|
55
58
|
},
|
|
56
59
|
"devDependencies": {
|
|
60
|
+
"@testing-library/jest-dom": "^6.1.5",
|
|
61
|
+
"@testing-library/react": "^16.3.0",
|
|
62
|
+
"@testing-library/user-event": "^14.5.1",
|
|
57
63
|
"@types/crypto-js": "^4.2.2",
|
|
58
64
|
"@types/react": "^19.0.3",
|
|
59
65
|
"@types/react-dom": "^19.0.1",
|
|
66
|
+
"@vitest/coverage-v8": "^1.1.0",
|
|
67
|
+
"@vitest/ui": "^1.1.0",
|
|
68
|
+
"jsdom": "^23.0.1",
|
|
60
69
|
"tsup": "^8.4.0",
|
|
61
|
-
"typescript": "^5.1.3"
|
|
70
|
+
"typescript": "^5.1.3",
|
|
71
|
+
"vitest": "^1.1.0"
|
|
62
72
|
},
|
|
63
73
|
"publishConfig": {
|
|
64
74
|
"access": "public"
|
package/vitest.config.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { defineConfig } from "vitest/config";
|
|
2
|
+
import path from "path";
|
|
3
|
+
|
|
4
|
+
export default defineConfig({
|
|
5
|
+
test: {
|
|
6
|
+
globals: true,
|
|
7
|
+
environment: "jsdom",
|
|
8
|
+
setupFiles: ["./src/__tests__/setup.ts"],
|
|
9
|
+
coverage: {
|
|
10
|
+
provider: "v8",
|
|
11
|
+
reporter: ["text", "json", "html"],
|
|
12
|
+
exclude: [
|
|
13
|
+
"node_modules/",
|
|
14
|
+
"src/__tests__/",
|
|
15
|
+
"dist/",
|
|
16
|
+
"**/*.d.ts",
|
|
17
|
+
"**/*.config.*",
|
|
18
|
+
"**/mockData.ts",
|
|
19
|
+
],
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
resolve: {
|
|
23
|
+
alias: {
|
|
24
|
+
"@": path.resolve(__dirname, "./src"),
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
});
|
package/dist/chunk-2OSNNNID.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk6EBMA4HZjs = require('./chunk-6EBMA4HZ.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var a=class a{static setStorageType(e){a.storageType=e}static generateEncryptionKey(){let e=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(e).toString()}static getEncryptionKey(){if(a.encryptionKey)return a.encryptionKey;let e=window.localStorage;if(!e)return a.encryptionKey=a.generateEncryptionKey(),a.encryptionKey;try{let t=e.getItem(a.ENCRYPTION_KEY_STORAGE);return(!t||t.length<32)&&(t=a.generateEncryptionKey(),e.setItem(a.ENCRYPTION_KEY_STORAGE,t)),a.encryptionKey=t,t}catch (e2){return console.warn("Crudify: Cannot persist encryption key, using temporary key"),a.encryptionKey=a.generateEncryptionKey(),a.encryptionKey}}static isStorageAvailable(e){try{let t=window[e],r="__storage_test__";return t.setItem(r,"test"),t.removeItem(r),!0}catch (e3){return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(console.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static encrypt(e){try{let t=a.getEncryptionKey();return _cryptojs2.default.AES.encrypt(e,t).toString()}catch(t){return console.error("Crudify: Encryption failed",t),e}}static decrypt(e){try{let t=a.getEncryptionKey();return _cryptojs2.default.AES.decrypt(e,t).toString(_cryptojs2.default.enc.Utf8)||e}catch(t){return console.error("Crudify: Decryption failed",t),e}}static saveTokens(e){let t=a.getStorage();if(t)try{let r={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},i=a.encrypt(JSON.stringify(r));t.setItem(a.TOKEN_KEY,i),console.debug("Crudify: Tokens saved successfully")}catch(r){console.error("Crudify: Failed to save tokens",r)}}static getTokens(){let e=a.getStorage();if(!e)return null;try{let t=e.getItem(a.TOKEN_KEY);if(!t)return null;let r=a.decrypt(t),i=JSON.parse(r);return!i.accessToken||!i.refreshToken||!i.expiresAt||!i.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),a.clearTokens(),null):Date.now()>=i.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),a.clearTokens(),null):{accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}}catch(t){return console.error("Crudify: Failed to retrieve tokens",t),a.clearTokens(),null}}static clearTokens(){let e=a.getStorage();if(e)try{e.removeItem(a.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(t){console.error("Crudify: Failed to clear tokens",t)}}static rotateEncryptionKey(){try{a.clearTokens(),a.encryptionKey=null;let e=window.localStorage;e&&e.removeItem(a.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(e){console.error("Crudify: Failed to rotate encryption key",e)}}static hasValidTokens(){return a.getTokens()!==null}static getExpirationInfo(){let e=a.getTokens();if(!e)return null;let t=Date.now();return{accessExpired:t>=e.expiresAt,refreshExpired:t>=e.refreshExpiresAt,accessExpiresIn:Math.max(0,e.expiresAt-t),refreshExpiresIn:Math.max(0,e.refreshExpiresAt-t)}}static updateAccessToken(e,t){let r=a.getTokens();if(!r){console.warn("Crudify: Cannot update access token, no existing tokens found");return}a.saveTokens({...r,accessToken:e,expiresAt:t})}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.encryptionKey=null,a.storageType="localStorage";var g=a;var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var P=class o{constructor(){this.config={};this.initialized=!1;this.lastActivityTime=0}static getInstance(){return o.instance||(o.instance=new o),o.instance}async initialize(e={}){if(this.initialized){console.warn("SessionManager: Already initialized");return}this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,...e},g.setStorageType(this.config.storageType||"localStorage"),this.config.enableLogging,this.config.autoRestore&&await this.restoreSession(),this.initialized=!0,this.log("SessionManager initialized successfully")}async login(e,t){try{this.log("Attempting login...");let r=await _crudifybrowser2.default.login(e,t);if(!r.success)return this.log("Login failed:",r.errors),{success:!1,error:this.formatError(r.errors),rawResponse:r};let i={accessToken:r.data.token,refreshToken:r.data.refreshToken,expiresAt:r.data.expiresAt,refreshExpiresAt:r.data.refreshExpiresAt};return g.saveTokens(i),this.lastActivityTime=Date.now(),this.log("Login successful, tokens saved"),_optionalChain([this, 'access', _2 => _2.config, 'access', _3 => _3.onLoginSuccess, 'optionalCall', _4 => _4(i)]),{success:!0,tokens:i,data:r.data}}catch(r){return this.log("Login error:",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),g.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _5 => _5.config, 'access', _6 => _6.onLogout, 'optionalCall', _7 => _7()])}catch(e){this.log("Logout error:",e),g.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let e=g.getTokens();if(!e)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=e.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),g.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),_crudifybrowser2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<e.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let i=g.getTokens();return i&&_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onSessionRestored, 'optionalCall', _10 => _10(i)]),!0}return g.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onSessionRestored, 'optionalCall', _13 => _13(e)]),!0}catch(e){return this.log("Session restore error:",e),g.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||g.hasValidTokens()}getTokenInfo(){let e=_crudifybrowser2.default.getTokenData(),t=g.getExpirationInfo();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:g.hasValidTokens()}}async refreshTokens(){try{this.log("Manually refreshing tokens...");let e=await _crudifybrowser2.default.refreshAccessToken();if(!e.success)return this.log("Token refresh failed:",e.errors),g.clearTokens(),_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.showNotification, 'optionalCall', _16 => _16(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionExpired, 'optionalCall', _19 => _19()]),!1;let t={accessToken:e.data.token,refreshToken:e.data.refreshToken,expiresAt:e.data.expiresAt,refreshExpiresAt:e.data.refreshExpiresAt};return g.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(e){return this.log("Token refresh error:",e),g.clearTokens(),_optionalChain([this, 'access', _20 => _20.config, 'access', _21 => _21.showNotification, 'optionalCall', _22 => _22(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _23 => _23.config, 'access', _24 => _24.onSessionExpired, 'optionalCall', _25 => _25()]),!1}}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async e=>{this.updateLastActivity();let t=this.detectAuthorizationError(e);if(t.isAuthError){if(console.warn("\u{1F6A8} SessionManager - Authorization error detected:",{errorType:t.errorType,errorDetails:t.errorDetails,fullResponse:e}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid or refresh already failed, clearing session"),g.clearTokens(),_optionalChain([this, 'access', _26 => _26.config, 'access', _27 => _27.showNotification, 'optionalCall', _28 => _28(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _29 => _29.config, 'access', _30 => _30.onSessionExpired, 'optionalCall', _31 => _31()]),e;g.hasValidTokens()&&!t.isIrrecoverable?(this.log("Auth error detected, attempting token refresh..."),await this.refreshTokens()||(this.log("Token refresh failed, triggering session expired"),_optionalChain([this, 'access', _32 => _32.config, 'access', _33 => _33.onSessionExpired, 'optionalCall', _34 => _34()]))):(this.log("Auth error with no valid tokens or irrecoverable error, triggering session expired"),g.clearTokens(),_optionalChain([this, 'access', _35 => _35.config, 'access', _36 => _36.showNotification, 'optionalCall', _37 => _37(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _38 => _38.config, 'access', _39 => _39.onSessionExpired, 'optionalCall', _40 => _40()]))}return e}),this.log("Response interceptor configured")}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isIrrecoverable:!1,errorType:"",errorDetails:null};if(e.errors){if(Array.isArray(e.errors))e.errors.some(i=>i.errorType==="Unauthorized"||_optionalChain([i, 'access', _41 => _41.message, 'optionalAccess', _42 => _42.includes, 'call', _43 => _43("Unauthorized")])||_optionalChain([i, 'access', _44 => _44.message, 'optionalAccess', _45 => _45.includes, 'call', _46 => _46("Not Authorized")])||_optionalChain([i, 'access', _47 => _47.message, 'optionalAccess', _48 => _48.includes, 'call', _49 => _49("Token")])||_optionalChain([i, 'access', _50 => _50.extensions, 'optionalAccess', _51 => _51.code])==="UNAUTHENTICATED"||_optionalChain([i, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("NOT_AUTHORIZED")]))&&(t.isAuthError=!0,t.errorType="GraphQL Array Format",t.errorDetails=e.errors);else if(typeof e.errors=="object"){let r=Object.values(e.errors).flat();r.some(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("Token")))&&(t.isAuthError=!0,t.errorType="GraphQL Object Format",t.errorDetails=e.errors,t.isTokenRefreshFailed=r.some(u=>typeof u=="string"&&u.includes("TOKEN_REFRESH_FAILED")))}}if(!t.isAuthError&&_optionalChain([e, 'access', _55 => _55.data, 'optionalAccess', _56 => _56.response, 'optionalAccess', _57 => _57.status])==="UNAUTHORIZED"&&(t.isAuthError=!0,t.errorType="Status UNAUTHORIZED",t.errorDetails=e.data.response,t.isIrrecoverable=!0),!t.isAuthError&&_optionalChain([e, 'access', _58 => _58.data, 'optionalAccess', _59 => _59.response, 'optionalAccess', _60 => _60.data]))try{let r=JSON.parse(e.data.response.data);(r.error==="REFRESH_TOKEN_INVALID"||r.error==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Parsed Data Format",t.errorDetails=r,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0)}catch (e4){}if(!t.isAuthError&&e.errorCode){let r=e.errorCode;(r==="UNAUTHORIZED"||r==="UNAUTHENTICATED"||r==="TOKEN_EXPIRED")&&(t.isAuthError=!0,t.errorType="Error Code Format",t.errorDetails={errorCode:r})}return t}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let e=this.getTimeSinceLastActivity(),t=_crudifybrowser2.default.getTokenData();if(this.lastActivityTime===0)return"none";let r=900*1e3,i=300*1e3,u=300*1e3;return e>r?(this.log(`Inactivity timeout: ${Math.floor(e/6e4)} minutes since last activity`),"logout"):e<i&&t.expiresIn<u&&t.expiresIn>0?(this.log(`User active recently (${Math.floor(e/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){g.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunk6EBMA4HZjs.b.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(e,...t){this.config.enableLogging&&console.log(`[SessionManager] ${e}`,...t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);function j(o={}){let[e,t]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),r=P.getInstance(),i=_react.useCallback.call(void 0, async()=>{try{t(s=>({...s,isLoading:!0,error:null}));let l={autoRestore:_nullishCoalesce(o.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(o.enableLogging, () => (!1)),showNotification:o.showNotification,translateFn:o.translateFn,onSessionExpired:()=>{t(s=>({...s,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([o, 'access', _61 => _61.onSessionExpired, 'optionalCall', _62 => _62()])},onSessionRestored:s=>{t(d=>({...d,isAuthenticated:!0,tokens:s,error:null})),_optionalChain([o, 'access', _63 => _63.onSessionRestored, 'optionalCall', _64 => _64(s)])},onLoginSuccess:s=>{t(d=>({...d,isAuthenticated:!0,tokens:s,error:null}))},onLogout:()=>{t(s=>({...s,isAuthenticated:!1,tokens:null,error:null}))}};await r.initialize(l),r.setupResponseInterceptor();let n=r.isAuthenticated(),c=r.getTokenInfo();t(s=>({...s,isAuthenticated:n,isInitialized:!0,isLoading:!1,tokens:c.crudifyTokens.accessToken?{accessToken:c.crudifyTokens.accessToken,refreshToken:c.crudifyTokens.refreshToken,expiresAt:c.crudifyTokens.expiresAt,refreshExpiresAt:c.crudifyTokens.refreshExpiresAt}:null}))}catch(l){let n=l instanceof Error?l.message:"Initialization failed";t(c=>({...c,isLoading:!1,isInitialized:!0,error:n}))}},[o.autoRestore,o.enableLogging,o.onSessionExpired,o.onSessionRestored]),u=_react.useCallback.call(void 0, async(l,n)=>{t(c=>({...c,isLoading:!0,error:null}));try{let c=await r.login(l,n);return c.success&&c.tokens?t(s=>({...s,isAuthenticated:!0,tokens:c.tokens,isLoading:!1,error:null})):t(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),c}catch(c){let s=c instanceof Error?c.message:"Login failed",d=s.includes("INVALID_CREDENTIALS")||s.includes("Invalid email")||s.includes("Invalid password")||s.includes("credentials");return t(T=>({...T,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:s})),{success:!1,error:s}}},[r]),v=_react.useCallback.call(void 0, async()=>{t(l=>({...l,isLoading:!0}));try{await r.logout(),t(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(l){t(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:l instanceof Error?l.message:"Logout error"}))}},[r]),p=_react.useCallback.call(void 0, async()=>{try{let l=await r.refreshTokens();if(l){let n=r.getTokenInfo();t(c=>({...c,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(n=>({...n,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return l}catch(l){return t(n=>({...n,isAuthenticated:!1,tokens:null,error:l instanceof Error?l.message:"Token refresh failed"})),!1}},[r]),x=_react.useCallback.call(void 0, ()=>{t(l=>({...l,error:null}))},[]),k=_react.useCallback.call(void 0, ()=>r.getTokenInfo(),[r]);_react.useEffect.call(void 0, ()=>{i()},[i]),_react.useEffect.call(void 0, ()=>{if(!e.isAuthenticated||!e.tokens)return;let l=()=>{r.updateLastActivity(),o.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")};window.addEventListener("popstate",l);let n=window.history.pushState,c=window.history.replaceState;window.history.pushState=function(...d){let T=n.apply(this,d);return l(),T},window.history.replaceState=function(...d){let T=c.apply(this,d);return l(),T};let s=setInterval(async()=>{let d=r.checkInactivity();if(d==="logout")o.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await v();else if(d==="refresh"&&(o.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),await r.refreshTokens())){let h=r.getTokenInfo();t(b=>({...b,tokens:h.crudifyTokens.accessToken?{accessToken:h.crudifyTokens.accessToken,refreshToken:h.crudifyTokens.refreshToken,expiresAt:h.crudifyTokens.expiresAt,refreshExpiresAt:h.crudifyTokens.refreshExpiresAt}:null}))}},120*1e3);return()=>{clearInterval(s),window.removeEventListener("popstate",l),window.history.pushState=n,window.history.replaceState=c}},[e.isAuthenticated,e.tokens,r,o.enableLogging,v]);let S=_react.useCallback.call(void 0, ()=>{r.updateLastActivity()},[r]);return{...e,login:u,logout:v,refreshTokens:p,clearError:x,getTokenInfo:k,updateActivity:S,isExpiringSoon:e.tokens?e.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:e.tokens?Math.max(0,e.tokens.expiresAt-Date.now()):0,refreshExpiresIn:e.tokens?Math.max(0,e.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var B=_react.createContext.call(void 0, null),ue=o=>_dompurify2.default.sanitize(o,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),J= exports.d =({children:o,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:r={vertical:"top",horizontal:"right"},enabled:i=!1,allowHtml:u=!1})=>{let[v,p]=_react.useState.call(void 0, []),x=_react.useCallback.call(void 0, (n,c="info",s)=>{if(!i)return"";if(!n||typeof n!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";n.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),n=n.substring(0,1e3)+"...");let d=_uuid.v4.call(void 0, ),T={id:d,message:n,severity:c,autoHideDuration:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _65 => _65.autoHideDuration]), () => (t)),persistent:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _66 => _66.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _67 => _67.allowHtml]), () => (u))};return p(h=>[...h.length>=e?h.slice(-(e-1)):h,T]),d},[e,t,i,u]),k=_react.useCallback.call(void 0, n=>{p(c=>c.filter(s=>s.id!==n))},[]),S=_react.useCallback.call(void 0, ()=>{p([])},[]),l={showNotification:x,hideNotification:k,clearAllNotifications:S};return _jsxruntime.jsxs.call(void 0, B.Provider,{value:l,children:[o,i&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[r.vertical]:(r.vertical==="top",24),[r.horizontal]:r.horizontal==="right"||r.horizontal==="left"?24:"50%",...r.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:r.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:v.map(n=>_jsxruntime.jsx.call(void 0, fe,{notification:n,onClose:()=>k(n.id)},n.id))})})]})},fe=({notification:o,onClose:e})=>{let[t,r]=_react.useState.call(void 0, !0),i=_react.useCallback.call(void 0, (u,v)=>{v!=="clickaway"&&(r(!1),setTimeout(e,300))},[e]);return _react.useEffect.call(void 0, ()=>{if(!o.persistent&&o.autoHideDuration){let u=setTimeout(()=>{i()},o.autoHideDuration);return()=>clearTimeout(u)}},[o.autoHideDuration,o.persistent,i]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:t,onClose:i,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:o.severity,onClose:i,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:o.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ue(o.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:o.message})})})},_= exports.e =()=>{let o=_react.useContext.call(void 0, B);if(!o)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return o};var X=_react.createContext.call(void 0, void 0);function ye({children:o,options:e={},config:t,showNotifications:r=!1,notificationOptions:i={}}){let u;try{let{showNotification:n}=_();u=n}catch (e5){}let v=_react2.default.useMemo(()=>({...e,showNotification:u,onSessionExpired:()=>{_optionalChain([e, 'access', _68 => _68.onSessionExpired, 'optionalCall', _69 => _69()])}}),[e,u]),p=j(v),x=_react.useMemo.call(void 0, ()=>{let n,c,s,d,T,h="unknown";if(_optionalChain([t, 'optionalAccess', _70 => _70.publicApiKey])&&(n=t.publicApiKey,h="props"),_optionalChain([t, 'optionalAccess', _71 => _71.env])&&(c=t.env),_optionalChain([t, 'optionalAccess', _72 => _72.appName])&&(s=t.appName),_optionalChain([t, 'optionalAccess', _73 => _73.loginActions])&&(d=t.loginActions),_optionalChain([t, 'optionalAccess', _74 => _74.logo])&&(T=t.logo),!n){let b=_chunk6EBMA4HZjs.a.call(void 0, "publicApiKey"),N=_chunk6EBMA4HZjs.a.call(void 0, "environment"),R=_chunk6EBMA4HZjs.a.call(void 0, "appName"),E=_chunk6EBMA4HZjs.a.call(void 0, "loginActions"),f=_chunk6EBMA4HZjs.a.call(void 0, "logo");b&&(n=b,h="cookies"),N&&["dev","stg","prod"].includes(N)&&(c=N),R&&(s=decodeURIComponent(R)),E&&(d=decodeURIComponent(E).split(",").map(L=>L.trim()).filter(Boolean)),f&&(T=decodeURIComponent(f))}return{publicApiKey:n,env:c,appName:s,loginActions:d,logo:T}},[t]),k=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([p, 'access', _75 => _75.tokens, 'optionalAccess', _76 => _76.accessToken])||!p.isAuthenticated)return null;try{let n=_chunk6EBMA4HZjs.f.call(void 0, p.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let c={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(s=>{["sub","email","subscriber"].includes(s)||(c[s]=n[s])}),c}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[_optionalChain([p, 'access', _77 => _77.tokens, 'optionalAccess', _78 => _78.accessToken]),p.isAuthenticated]),S={...p,sessionData:k,config:x},l={enabled:r,maxNotifications:i.maxNotifications||5,defaultAutoHideDuration:i.defaultAutoHideDuration||6e3,position:i.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, X.Provider,{value:S,children:o})}function Be(o){let e={enabled:o.showNotifications,maxNotifications:_optionalChain([o, 'access', _79 => _79.notificationOptions, 'optionalAccess', _80 => _80.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([o, 'access', _81 => _81.notificationOptions, 'optionalAccess', _82 => _82.defaultAutoHideDuration])||6e3,position:_optionalChain([o, 'access', _83 => _83.notificationOptions, 'optionalAccess', _84 => _84.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([o, 'access', _85 => _85.notificationOptions, 'optionalAccess', _86 => _86.allowHtml])||!1};return _jsxruntime.jsx.call(void 0, J,{...e,children:_jsxruntime.jsx.call(void 0, ye,{...o})})}function Z(){let o=_react.useContext.call(void 0, X);if(o===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return o}function Je({children:o,fallback:e=_jsxruntime.jsx.call(void 0, "div",{children:"Please log in to access this content"}),redirectTo:t}){let{isAuthenticated:r,isLoading:i,isInitialized:u}=Z();return!u||i?_jsxruntime.jsx.call(void 0, "div",{children:"Loading..."}):r?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):t?(t(),null):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function _e(){let o=Z();return o.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",o.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",o.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",o.error||"None"]}),o.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",o.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",o.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(o.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(o.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",o.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var et=(o={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:r=3}=o,[i,u]=_react.useState.call(void 0, null),[v,p]=_react.useState.call(void 0, !1),[x,k]=_react.useState.call(void 0, null),[S,l]=_react.useState.call(void 0, {}),n=_react.useRef.call(void 0, null),c=_react.useRef.call(void 0, !0),s=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),T=_react.useCallback.call(void 0, ()=>{u(null),k(null),p(!1),l({})},[]),h=_react.useCallback.call(void 0, async()=>{let b=_chunk6EBMA4HZjs.g.call(void 0, );if(!b){c.current&&(k("No user email available"),p(!1));return}n.current&&n.current.abort();let N=new AbortController;n.current=N;let R=++s.current;try{c.current&&(p(!0),k(null));let E=await _crudifybrowser2.default.readItems("users",{filter:{email:b},pagination:{limit:1}});if(R===s.current&&c.current&&!N.signal.aborted)if(E.success&&E.data&&E.data.length>0){let f=E.data[0];u(f);let H={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(L=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(L)).reduce((L,z)=>({...L,[z]:f[z]}),{})}};l(H),k(null),d.current=0}else k("User profile not found"),u(null),l({})}catch(E){if(R===s.current&&c.current){let f=E;if(f.name==="AbortError")return;t&&d.current<r&&(_optionalChain([f, 'access', _87 => _87.message, 'optionalAccess', _88 => _88.includes, 'call', _89 => _89("Network Error")])||_optionalChain([f, 'access', _90 => _90.message, 'optionalAccess', _91 => _91.includes, 'call', _92 => _92("Failed to fetch")]))?(d.current++,setTimeout(()=>{c.current&&h()},1e3*d.current)):(k("Failed to load user profile"),u(null),l({}))}}finally{R===s.current&&c.current&&p(!1),n.current===N&&(n.current=null)}},[t,r]);return _react.useEffect.call(void 0, ()=>{e&&h()},[e,h]),_react.useEffect.call(void 0, ()=>(c.current=!0,()=>{c.current=!1,n.current&&(n.current.abort(),n.current=null)}),[]),{userProfile:i,loading:v,error:x,extendedData:S,refreshProfile:h,clearProfile:T}};exports.a = g; exports.b = P; exports.c = j; exports.d = J; exports.e = _; exports.f = Be; exports.g = Z; exports.h = Je; exports.i = _e; exports.j = et;
|